MariaKaiser commited on
Commit
83571c9
·
verified ·
1 Parent(s): 4ee781d

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +24 -18
app.py CHANGED
@@ -103,28 +103,34 @@ class StoryCreationDTO(BaseModel):
103
 
104
  import httpx
105
  import tempfile
 
106
 
107
- async def download_file_from_url(url: str) -> str | None:
108
  """
109
  Downloads a file from a URL and returns the path to a temporary file.
110
- Returns None if the download fails.
 
111
  """
112
- try:
113
- async with httpx.AsyncClient() as client:
114
- response = await client.get(url, timeout=60.0) # optional timeout
115
- response.raise_for_status() # raises for non-200 status codes
116
-
117
- # Save to a temporary file
118
- temp_file = tempfile.NamedTemporaryFile(delete=False, suffix=".wav")
119
- temp_file.write(response.content)
120
- temp_file.close()
121
- print(f"downloaded {url} successfully")
122
- return temp_file.name
123
-
124
- except Exception as e:
125
- # Catch any exception (network, timeout, invalid response)
126
- print(f"Failed to download {url}: {e}")
127
- return None
 
 
 
 
128
 
129
  #-----------------------------------------------------------
130
 
 
103
 
104
  import httpx
105
  import tempfile
106
+ import asyncio
107
 
108
+ async def download_file_from_url(url: str, retries: int = 3, delay: float = 2.0) -> str | None:
109
  """
110
  Downloads a file from a URL and returns the path to a temporary file.
111
+ Retries on failure up to `retries` times, waiting `delay` seconds between attempts.
112
+ Returns None if all attempts fail.
113
  """
114
+ for attempt in range(1, retries + 1):
115
+ try:
116
+ async with httpx.AsyncClient(timeout=60.0) as client: # increased timeout
117
+ response = await client.get(url)
118
+ response.raise_for_status() # raises for non-200 status codes
119
+
120
+ # Save to a temporary file
121
+ temp_file = tempfile.NamedTemporaryFile(delete=False, suffix=".wav")
122
+ temp_file.write(response.content)
123
+ temp_file.close()
124
+ print(f"Downloaded {url} successfully on attempt {attempt}")
125
+ return temp_file.name
126
+
127
+ except Exception as e:
128
+ print(f"Attempt {attempt} failed for {url}: {e}")
129
+ if attempt < retries:
130
+ await asyncio.sleep(delay) # wait before retrying
131
+
132
+ print(f"All {retries} attempts failed for {url}")
133
+ return None
134
 
135
  #-----------------------------------------------------------
136