Spaces:
Paused
Paused
Update app/main.py
Browse files- app/main.py +21 -5
app/main.py
CHANGED
|
@@ -23,14 +23,30 @@ if not API_KEY:
|
|
| 23 |
global_client = None
|
| 24 |
|
| 25 |
def get_gradio_client():
|
|
|
|
| 26 |
global global_client
|
| 27 |
if global_client:
|
| 28 |
return global_client
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 34 |
except utils.TooManyRequestsError:
|
| 35 |
raise RuntimeError("Gradio API config rate-limited. Please try again later.")
|
| 36 |
except Exception as e:
|
|
|
|
| 23 |
global_client = None
|
| 24 |
|
| 25 |
def get_gradio_client():
|
| 26 |
+
"""Initialize or return cached Gradio client, retrying on rate limits or timeouts."""
|
| 27 |
global global_client
|
| 28 |
if global_client:
|
| 29 |
return global_client
|
| 30 |
+
# Try up to 3 times with exponential backoff
|
| 31 |
+
for attempt in range(3):
|
| 32 |
+
try:
|
| 33 |
+
client = Client(SPACE_ID)
|
| 34 |
+
# set HTTPX timeouts (connect quick, allow longer reads)
|
| 35 |
+
client.client.timeout = httpx.Timeout(connect=5.0, read=GRADIO_TIMEOUT)
|
| 36 |
+
global_client = client
|
| 37 |
+
return client
|
| 38 |
+
except utils.TooManyRequestsError:
|
| 39 |
+
if attempt < 2:
|
| 40 |
+
time.sleep(2 ** attempt)
|
| 41 |
+
continue
|
| 42 |
+
raise RuntimeError("Gradio API config rate-limited. Please try again later.")
|
| 43 |
+
except Exception as e:
|
| 44 |
+
msg = str(e)
|
| 45 |
+
if "ReadTimeout" in msg and attempt < 2:
|
| 46 |
+
# retry on read timeouts
|
| 47 |
+
time.sleep(2 ** attempt)
|
| 48 |
+
continue
|
| 49 |
+
raise RuntimeError(f"Failed to initialize Gradio client: {e}")
|
| 50 |
except utils.TooManyRequestsError:
|
| 51 |
raise RuntimeError("Gradio API config rate-limited. Please try again later.")
|
| 52 |
except Exception as e:
|