Joseph Pollack commited on
Commit
dae7e9c
Β·
unverified Β·
1 Parent(s): 1a36286

skip examples caching

Browse files
Files changed (1) hide show
  1. app.py +96 -75
app.py CHANGED
@@ -21,6 +21,7 @@ import os
21
  HF_TOKEN = os.getenv("HF_TOKEN")
22
  if not HF_TOKEN:
23
  logger.warning("HF_TOKEN not found in environment variables. Model access may be restricted.")
 
24
 
25
  class LOperatorDemo:
26
  def __init__(self):
@@ -29,15 +30,18 @@ class LOperatorDemo:
29
  self.is_loaded = False
30
 
31
  def load_model(self):
32
- """Load the L-Operator model and processor"""
33
  try:
 
 
34
  logger.info(f"Loading model {MODEL_ID} on device {DEVICE}")
35
-
36
  # Check if token is available
37
  if not HF_TOKEN:
38
  return "❌ HF_TOKEN not found. Please set HF_TOKEN in Spaces secrets."
39
-
40
- # Load model following the working example pattern
 
41
  self.model = AutoModelForImageTextToText.from_pretrained(
42
  MODEL_ID,
43
  device_map="auto",
@@ -46,17 +50,20 @@ class LOperatorDemo:
46
  )
47
 
48
  # Load processor
 
49
  self.processor = AutoProcessor.from_pretrained(
50
  MODEL_ID,
51
  trust_remote_code=True
52
- )
 
53
  if DEVICE == "cpu":
54
  self.model = self.model.to(DEVICE)
55
-
56
  self.is_loaded = True
57
- logger.info("Model loaded successfully with token authentication")
58
- return "βœ… Model loaded successfully with token authentication!"
59
-
 
60
  except Exception as e:
61
  logger.error(f"Error loading model: {str(e)}")
62
  return f"❌ Error loading model: {str(e)} - This may be a custom model requiring special handling"
@@ -163,74 +170,72 @@ class LOperatorDemo:
163
  # Initialize demo
164
  demo_instance = LOperatorDemo()
165
 
166
- # Auto-load the model on startup
167
- def auto_load_model():
168
- """Auto-load the model when the application starts"""
 
 
 
 
 
 
 
 
 
169
  try:
170
- logger.info("Auto-loading L-Operator model on startup...")
171
  result = demo_instance.load_model()
172
- logger.info(f"Auto-load result: {result}")
173
  return result
 
 
 
174
  except Exception as e:
175
- logger.error(f"Error auto-loading model: {str(e)}")
176
- return f"❌ Error auto-loading model: {str(e)}"
177
-
178
- # Load model automatically (this happens during import)
179
- print("πŸš€ Auto-loading L-Operator model on startup...")
180
- auto_load_model()
181
- print("βœ… Model loading completed!")
182
 
183
- # Load example episodes
184
  def load_example_episodes():
185
- """Load example episodes from the extracted data with error handling"""
186
  examples = []
187
 
188
  try:
189
- # Load episode 13
190
- with open("extracted_episodes_duckdb/episode_13/metadata.json", "r") as f:
191
- episode_13 = json.load(f)
192
-
193
- # Load episode 53
194
- with open("extracted_episodes_duckdb/episode_53/metadata.json", "r") as f:
195
- episode_53 = json.load(f)
196
 
197
- # Load episode 73
198
- with open("extracted_episodes_duckdb/episode_73/metadata.json", "r") as f:
199
- episode_73 = json.load(f)
200
-
201
- # Create examples with simple identifiers
202
- examples = [
203
- (
204
- "extracted_episodes_duckdb/episode_13/screenshots/screenshot_1.png",
205
- f"Episode 13: {episode_13.get('goal', 'Navigate app interface')[:50]}..."
206
- ),
207
- (
208
- "extracted_episodes_duckdb/episode_53/screenshots/screenshot_1.png",
209
- f"Episode 53: {episode_53.get('goal', 'App interaction example')[:50]}..."
210
- ),
211
- (
212
- "extracted_episodes_duckdb/episode_73/screenshots/screenshot_1.png",
213
- f"Episode 73: {episode_73.get('goal', 'Device control task')[:50]}..."
214
- )
215
- ]
216
-
217
- # Validate each example by checking if image file exists and is readable
218
- for image_path, description in examples:
219
  try:
220
- # Try to open the image to validate it
221
- from PIL import Image
222
- with Image.open(image_path) as img:
223
- # If we get here, the image is valid
224
- examples.append([image_path, description])
225
- except Exception as img_error:
226
- logger.warning(f"Skipping invalid image {image_path}: {str(img_error)}")
227
  continue
228
 
 
 
 
 
 
 
 
 
 
 
 
 
 
229
  except Exception as e:
230
  logger.error(f"Error loading examples: {str(e)}")
231
  examples = []
232
 
233
- logger.info(f"Loaded {len(examples)} valid examples")
234
  return examples
235
 
236
  # Create Gradio interface
@@ -322,7 +327,8 @@ def create_demo():
322
  title="L-Operator Chat",
323
  description="Chat with L-Operator using screenshots and text instructions",
324
  examples=load_example_episodes(),
325
- type="messages"
 
326
  )
327
 
328
  gr.Markdown("### 🎯 Action Output")
@@ -349,20 +355,26 @@ def create_demo():
349
  except:
350
  return {"raw_response": response}
351
 
352
- # Update model status on page load
353
  def update_model_status():
 
 
 
 
 
 
354
  if demo_instance.is_loaded:
355
  return "βœ… L-Operator model loaded and ready!"
356
  else:
357
  return "❌ Model failed to load. Please check logs."
358
-
359
  generate_btn.click(
360
  fn=on_generate_action,
361
  inputs=[image_input, goal_input, step_input],
362
  outputs=action_output
363
  )
364
-
365
- # Update model status on page load
366
  demo.load(
367
  fn=update_model_status,
368
  outputs=model_status
@@ -404,14 +416,23 @@ def create_demo():
404
 
405
  return demo
406
 
407
- # Create and launch the demo
408
  if __name__ == "__main__":
409
- demo = create_demo()
410
- demo.launch(
411
- server_name="0.0.0.0",
412
- server_port=7860,
413
- share=False,
414
- debug=True,
415
- show_error=True,
416
- ssr_mode=False
417
- )
 
 
 
 
 
 
 
 
 
 
21
  HF_TOKEN = os.getenv("HF_TOKEN")
22
  if not HF_TOKEN:
23
  logger.warning("HF_TOKEN not found in environment variables. Model access may be restricted.")
24
+ logger.warning("Please set HF_TOKEN in your environment variables or Spaces secrets.")
25
 
26
  class LOperatorDemo:
27
  def __init__(self):
 
30
  self.is_loaded = False
31
 
32
  def load_model(self):
33
+ """Load the L-Operator model and processor with timeout handling"""
34
  try:
35
+ import time
36
+ start_time = time.time()
37
  logger.info(f"Loading model {MODEL_ID} on device {DEVICE}")
38
+
39
  # Check if token is available
40
  if not HF_TOKEN:
41
  return "❌ HF_TOKEN not found. Please set HF_TOKEN in Spaces secrets."
42
+
43
+ # Load model with progress logging
44
+ logger.info("Downloading and loading model weights...")
45
  self.model = AutoModelForImageTextToText.from_pretrained(
46
  MODEL_ID,
47
  device_map="auto",
 
50
  )
51
 
52
  # Load processor
53
+ logger.info("Loading processor...")
54
  self.processor = AutoProcessor.from_pretrained(
55
  MODEL_ID,
56
  trust_remote_code=True
57
+ )
58
+
59
  if DEVICE == "cpu":
60
  self.model = self.model.to(DEVICE)
61
+
62
  self.is_loaded = True
63
+ load_time = time.time() - start_time
64
+ logger.info(".1f")
65
+ return ".1f"
66
+
67
  except Exception as e:
68
  logger.error(f"Error loading model: {str(e)}")
69
  return f"❌ Error loading model: {str(e)} - This may be a custom model requiring special handling"
 
170
  # Initialize demo
171
  demo_instance = LOperatorDemo()
172
 
173
+ def load_model_with_timeout(timeout_seconds=600): # 10 minutes timeout
174
+ """Load model with timeout protection"""
175
+ import signal
176
+ import time
177
+
178
+ def timeout_handler(signum, frame):
179
+ raise TimeoutError("Model loading timed out")
180
+
181
+ # Set up the signal handler for timeout
182
+ old_handler = signal.signal(signal.SIGALRM, timeout_handler)
183
+ signal.alarm(timeout_seconds)
184
+
185
  try:
186
+ logger.info("Loading L-Operator model with timeout protection...")
187
  result = demo_instance.load_model()
188
+ logger.info(f"Model loading result: {result}")
189
  return result
190
+ except TimeoutError:
191
+ logger.error("Model loading timed out - this may be due to network issues or large model size")
192
+ return "❌ Model loading timed out. Please try again or check your internet connection."
193
  except Exception as e:
194
+ logger.error(f"Error loading model: {str(e)}")
195
+ return f"❌ Error loading model: {str(e)}"
196
+ finally:
197
+ # Restore the original signal handler
198
+ signal.alarm(0)
199
+ signal.signal(signal.SIGALRM, old_handler)
 
200
 
201
+ # Load example episodes (lazy loading to avoid startup timeout)
202
  def load_example_episodes():
203
+ """Load example episodes from the extracted data - simplified for fast startup"""
204
  examples = []
205
 
206
  try:
207
+ # Load episode metadata quickly without PIL validation
208
+ episodes_data = []
209
+ episode_dirs = ["episode_13", "episode_53", "episode_73"]
 
 
 
 
210
 
211
+ for episode_dir in episode_dirs:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
212
  try:
213
+ metadata_path = f"extracted_episodes_duckdb/{episode_dir}/metadata.json"
214
+ with open(metadata_path, "r") as f:
215
+ metadata = json.load(f)
216
+ episodes_data.append(metadata)
217
+ except Exception as e:
218
+ logger.warning(f"Could not load metadata for {episode_dir}: {str(e)}")
 
219
  continue
220
 
221
+ # Create examples with simple path checks (no PIL validation)
222
+ for i, metadata in enumerate(episodes_data):
223
+ episode_num = ["13", "53", "73"][i]
224
+ image_path = f"extracted_episodes_duckdb/episode_{episode_num}/screenshots/screenshot_1.png"
225
+
226
+ # Simple file existence check instead of PIL validation
227
+ if os.path.exists(image_path):
228
+ goal_text = metadata.get('goal', f'Episode {episode_num} example')
229
+ examples.append([
230
+ image_path,
231
+ f"Episode {episode_num}: {goal_text[:50]}..."
232
+ ])
233
+
234
  except Exception as e:
235
  logger.error(f"Error loading examples: {str(e)}")
236
  examples = []
237
 
238
+ logger.info(f"Loaded {len(examples)} examples (without validation for faster startup)")
239
  return examples
240
 
241
  # Create Gradio interface
 
327
  title="L-Operator Chat",
328
  description="Chat with L-Operator using screenshots and text instructions",
329
  examples=load_example_episodes(),
330
+ type="messages",
331
+ cache_examples=False
332
  )
333
 
334
  gr.Markdown("### 🎯 Action Output")
 
355
  except:
356
  return {"raw_response": response}
357
 
358
+ # Update model status on page load (with timeout-protected model loading)
359
  def update_model_status():
360
+ if not demo_instance.is_loaded:
361
+ logger.info("Loading model on Gradio startup with timeout protection...")
362
+ result = load_model_with_timeout(timeout_seconds=900) # 15 minutes for Spaces
363
+ logger.info(f"Model loading result: {result}")
364
+ return result
365
+
366
  if demo_instance.is_loaded:
367
  return "βœ… L-Operator model loaded and ready!"
368
  else:
369
  return "❌ Model failed to load. Please check logs."
370
+
371
  generate_btn.click(
372
  fn=on_generate_action,
373
  inputs=[image_input, goal_input, step_input],
374
  outputs=action_output
375
  )
376
+
377
+ # Load model and update status on page load
378
  demo.load(
379
  fn=update_model_status,
380
  outputs=model_status
 
416
 
417
  return demo
418
 
419
+ # Create and launch the demo with optimized settings
420
  if __name__ == "__main__":
421
+ try:
422
+ logger.info("Creating Gradio demo interface...")
423
+ demo = create_demo()
424
+
425
+ logger.info("Launching Gradio server...")
426
+ demo.launch(
427
+ server_name="0.0.0.0",
428
+ server_port=7860,
429
+ share=False,
430
+ debug=False, # Disable debug to reduce startup time
431
+ show_error=True,
432
+ ssr_mode=False,
433
+ max_threads=2, # Limit threads to prevent resource exhaustion
434
+ quiet=True # Reduce startup logging noise
435
+ )
436
+ except Exception as e:
437
+ logger.error(f"Failed to launch Gradio app: {str(e)}")
438
+ raise