MariaKaiser commited on
Commit
39d8f28
·
verified ·
1 Parent(s): 6847181

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +68 -66
app.py CHANGED
@@ -152,88 +152,90 @@ async def download_scene_files(scene: SceneDto):
152
  downloaded_files = await asyncio.gather(*tasks)
153
  return downloaded_files
154
 
155
- # async def download_file_from_url(url: str, retries: int = 3, delay: float = 2.0) -> str | None:
156
- # """
157
- # Downloads a file from a URL and returns the path to a temporary file.
158
- # If download fails after `retries` attempts, returns None instead of raising an error.
159
- # Caches successful downloads to avoid repeated requests.
160
- # """
161
- # if url in download_cache:
162
- # #print(f"{url} is got from cache")
163
- # return download_cache[url]
164
-
165
- # for attempt in range(1, retries + 1):
166
- # try:
167
- # async with httpx.AsyncClient(timeout=60.0) as client:
168
- # response = await client.get(url)
169
- # response.raise_for_status()
170
-
171
- # temp_file = tempfile.NamedTemporaryFile(delete=False, suffix=".wav")
172
- # temp_file.write(response.content)
173
- # temp_file.close()
174
-
175
- # #print(f"{url} is downloaded and saved in cache")
176
-
177
- # download_cache[url] = temp_file.name
178
- # return temp_file.name
179
-
180
- # except Exception as e:
181
- # #print(f"Attempt {attempt} failed for {url}: {e}")
182
- # if attempt < retries:
183
- # await asyncio.sleep(delay)
184
-
185
- # #print(f"All {retries} attempts failed for {url}, skipping...")
186
- # return None
187
-
188
- import os
189
- import httpx
190
- import asyncio
191
-
192
- CACHE_DIR = "audio_cache"
193
- os.makedirs(CACHE_DIR, exist_ok=True) # create if not exists folder stores permanently on disk
194
-
195
  download_cache = {} # in-memory map: url -> local file
196
 
197
  async def download_file_from_url(url: str, retries: int = 3, delay: float = 2.0) -> str | None:
198
  """
199
- Downloads a file from a URL and stores it in a permanent cache folder.
200
- Returns the local file path. Reuses already downloaded files.
 
201
  """
202
  if url in download_cache:
203
- #print(f"{url} is in download cache")
204
  return download_cache[url]
205
-
206
- # determine local file path in cache folder
207
- filename = url.split("/")[-1] # simple filename from URL
208
- local_path = os.path.join(CACHE_DIR, filename)
209
-
210
- # check if file already exists on disk
211
- if os.path.exists(local_path):
212
- #print(f"{url} is in disk and put to download cache now")
213
- download_cache[url] = local_path
214
- return local_path
215
-
216
- # download if not cached
217
  for attempt in range(1, retries + 1):
218
  try:
219
  async with httpx.AsyncClient(timeout=60.0) as client:
220
  response = await client.get(url)
221
  response.raise_for_status()
222
 
223
- # save to permanent cache folder
224
- with open(local_path, "wb") as f:
225
- f.write(response.content)
226
-
227
- download_cache[url] = local_path
228
- #print(f"{url} is downloaded from supabase and stored in disk and download cache now")
229
- return local_path
 
230
 
231
  except Exception as e:
 
232
  if attempt < retries:
233
  await asyncio.sleep(delay)
234
 
 
235
  return None
236
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
237
  #-----------------------------------------------------------
238
 
239
  #takes the text to be said and path to the prosody audio and path to save the generated audio and returns path to the generated audio
@@ -690,10 +692,10 @@ async def get_results(task_id: str):
690
  if result and all(k in result for k in ("fileName", "duration", "audioPath")):
691
  #clearing cache
692
  print(f"all fields are available {result}")
693
- # for file_path in download_cache.values():
694
- # if os.path.exists(file_path):
695
- # os.remove(file_path)
696
- # download_cache.clear()
697
 
698
  return {"status": "completed", **result}
699
  else:
 
152
  downloaded_files = await asyncio.gather(*tasks)
153
  return downloaded_files
154
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
155
  download_cache = {} # in-memory map: url -> local file
156
 
157
  async def download_file_from_url(url: str, retries: int = 3, delay: float = 2.0) -> str | None:
158
  """
159
+ Downloads a file from a URL and returns the path to a temporary file.
160
+ If download fails after `retries` attempts, returns None instead of raising an error.
161
+ Caches successful downloads to avoid repeated requests.
162
  """
163
  if url in download_cache:
164
+ #print(f"{url} is got from cache")
165
  return download_cache[url]
166
+
 
 
 
 
 
 
 
 
 
 
 
167
  for attempt in range(1, retries + 1):
168
  try:
169
  async with httpx.AsyncClient(timeout=60.0) as client:
170
  response = await client.get(url)
171
  response.raise_for_status()
172
 
173
+ temp_file = tempfile.NamedTemporaryFile(delete=False, suffix=".wav")
174
+ temp_file.write(response.content)
175
+ temp_file.close()
176
+
177
+ #print(f"{url} is downloaded and saved in cache")
178
+
179
+ download_cache[url] = temp_file.name
180
+ return temp_file.name
181
 
182
  except Exception as e:
183
+ #print(f"Attempt {attempt} failed for {url}: {e}")
184
  if attempt < retries:
185
  await asyncio.sleep(delay)
186
 
187
+ #print(f"All {retries} attempts failed for {url}, skipping...")
188
  return None
189
 
190
+ # import os
191
+ # import httpx
192
+ # import asyncio
193
+
194
+ # CACHE_DIR = "audio_cache"
195
+ # os.makedirs(CACHE_DIR, exist_ok=True) # create if not exists folder stores permanently on disk
196
+
197
+
198
+
199
+ # async def download_file_from_url(url: str, retries: int = 3, delay: float = 2.0) -> str | None:
200
+ # """
201
+ # Downloads a file from a URL and stores it in a permanent cache folder.
202
+ # Returns the local file path. Reuses already downloaded files.
203
+ # """
204
+ # if url in download_cache:
205
+ # #print(f"{url} is in download cache")
206
+ # return download_cache[url]
207
+
208
+ # # determine local file path in cache folder
209
+ # filename = url.split("/")[-1] # simple filename from URL
210
+ # local_path = os.path.join(CACHE_DIR, filename)
211
+
212
+ # # check if file already exists on disk
213
+ # if os.path.exists(local_path):
214
+ # #print(f"{url} is in disk and put to download cache now")
215
+ # download_cache[url] = local_path
216
+ # return local_path
217
+
218
+ # # download if not cached
219
+ # for attempt in range(1, retries + 1):
220
+ # try:
221
+ # async with httpx.AsyncClient(timeout=60.0) as client:
222
+ # response = await client.get(url)
223
+ # response.raise_for_status()
224
+
225
+ # # save to permanent cache folder
226
+ # with open(local_path, "wb") as f:
227
+ # f.write(response.content)
228
+
229
+ # download_cache[url] = local_path
230
+ # #print(f"{url} is downloaded from supabase and stored in disk and download cache now")
231
+ # return local_path
232
+
233
+ # except Exception as e:
234
+ # if attempt < retries:
235
+ # await asyncio.sleep(delay)
236
+
237
+ # return None
238
+
239
  #-----------------------------------------------------------
240
 
241
  #takes the text to be said and path to the prosody audio and path to save the generated audio and returns path to the generated audio
 
692
  if result and all(k in result for k in ("fileName", "duration", "audioPath")):
693
  #clearing cache
694
  print(f"all fields are available {result}")
695
+ for file_path in download_cache.values():
696
+ if os.path.exists(file_path):
697
+ os.remove(file_path)
698
+ download_cache.clear()
699
 
700
  return {"status": "completed", **result}
701
  else: