cstr commited on
Commit
20199a1
·
verified ·
1 Parent(s): f28e02b

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +57 -2
app.py CHANGED
@@ -179,8 +179,63 @@ Recent Logs:
179
  return None, error_msg
180
 
181
  def translate_document_sync(*args, **kwargs):
182
- """Synchronous wrapper for Gradio"""
183
- return asyncio.run(translate_document_async(*args, **kwargs))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
184
 
185
  # ============================================================================
186
  # GRADIO INTERFACE
 
179
  return None, error_msg
180
 
181
  def translate_document_sync(*args, **kwargs):
182
+ """Synchronous wrapper with explicit event loop management"""
183
+ import asyncio
184
+ import concurrent.futures
185
+ from datetime import datetime
186
+
187
+ print(f"\n{'='*60}")
188
+ print(f"[{datetime.now().strftime('%H:%M:%S')}] 🔄 translate_document_sync called")
189
+
190
+ # Define a helper to run the async function in a new thread's loop
191
+ def run_in_new_loop(func, *args, **kwargs):
192
+ """Create a fresh event loop in the new thread"""
193
+ new_loop = asyncio.new_event_loop()
194
+ asyncio.set_event_loop(new_loop)
195
+ try:
196
+ return new_loop.run_until_complete(func(*args, **kwargs))
197
+ finally:
198
+ new_loop.close()
199
+
200
+ try:
201
+ try:
202
+ # Check if a loop is already running (Gradio/HF Spaces context)
203
+ asyncio.get_running_loop()
204
+ print(f"[DEBUG] ⚠️ Event loop running - Offloading to ThreadPool")
205
+
206
+ with concurrent.futures.ThreadPoolExecutor(max_workers=1) as executor:
207
+ # Pass the FUNCTION and ARGS separately
208
+ future = executor.submit(
209
+ run_in_new_loop,
210
+ translate_document_async,
211
+ *args,
212
+ **kwargs
213
+ )
214
+ result = future.result(timeout=600)
215
+ print(f"[DEBUG] ✓ Thread execution completed")
216
+ return result
217
+
218
+ except RuntimeError:
219
+ # No loop running (Standalone context)
220
+ print(f"[DEBUG] ℹ️ No running loop - Using standard asyncio.run")
221
+ result = asyncio.run(translate_document_async(*args, **kwargs))
222
+ print(f"[DEBUG] ✓ asyncio.run() completed")
223
+ return result
224
+
225
+ except concurrent.futures.TimeoutError:
226
+ error_msg = "❌ Translation timeout (>10 minutes)"
227
+ print(f"[ERROR] {error_msg}")
228
+ return None, error_msg
229
+
230
+ except Exception as e:
231
+ print(f"[ERROR] Critical failure: {e}")
232
+ import traceback
233
+ traceback.print_exc()
234
+ return None, f"❌ Error: {str(e)}"
235
+
236
+ finally:
237
+ print(f"[{datetime.now().strftime('%H:%M:%S')}] 🏁 Finished")
238
+ print(f"{'='*60}\n")
239
 
240
  # ============================================================================
241
  # GRADIO INTERFACE