radub23 commited on
Commit
f438e63
·
1 Parent(s): 1384d3c

Add retry logic and robust tensor handling for intermittent failures

Browse files
Files changed (1) hide show
  1. app.py +61 -24
app.py CHANGED
@@ -4,6 +4,7 @@ from fastai.learner import load_learner
4
  from pathlib import Path
5
  import pandas as pd
6
  import os
 
7
 
8
  """
9
  Warning Lamp Detector using FastAI
@@ -44,31 +45,67 @@ def detect_warning_lamp(image, history: list[tuple[str, str]], system_message):
44
  if image is None:
45
  history.append((None, "Please upload an image first."))
46
  return history
47
-
48
- try:
49
- # Convert PIL image to FastAI compatible format
50
- img = PILImage(image)
51
-
52
- # Get model prediction
53
- pred_class, pred_idx, probs = learn_inf.predict(img)
54
-
55
- # Format the prediction results
56
- confidence = float(probs[pred_idx]) # Convert to float for better formatting
57
- response = f"Detected Warning Lamp: {pred_class}\nConfidence: {confidence:.2%}"
58
-
59
- # Add probabilities for all classes
60
- response += "\n\nProbabilities for all classes:"
61
- for i, (cls, prob) in enumerate(zip(learn_inf.dls.vocab, probs)):
62
- response += f"\n- {cls}: {float(prob):.2%}"
63
 
64
- # Update chat history
65
- history.append((None, response))
66
- return history
67
- except Exception as e:
68
- error_msg = f"Error processing image: {str(e)}"
69
- print(f"Exception in detect_warning_lamp: {e}")
70
- history.append((None, error_msg))
71
- return history
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
72
 
73
  # Create a custom interface with image upload
74
  with gr.Blocks(title="Warning Lamp Detector", theme=gr.themes.Soft()) as demo:
 
4
  from pathlib import Path
5
  import pandas as pd
6
  import os
7
+ import time
8
 
9
  """
10
  Warning Lamp Detector using FastAI
 
45
  if image is None:
46
  history.append((None, "Please upload an image first."))
47
  return history
48
+
49
+ # Maximum number of retries
50
+ max_retries = 3
51
+ retry_count = 0
52
+
53
+ while retry_count < max_retries:
54
+ try:
55
+ # Convert PIL image to FastAI compatible format
56
+ img = PILImage(image)
 
 
 
 
 
 
 
57
 
58
+ # Get model prediction
59
+ pred_class, pred_idx, probs = learn_inf.predict(img)
60
+
61
+ # Try different approaches to handle tensor conversion
62
+ try:
63
+ # First approach - direct conversion
64
+ confidence = float(probs[pred_idx])
65
+ except Exception as e1:
66
+ print(f"First conversion approach failed: {e1}")
67
+ try:
68
+ # Second approach - convert index first
69
+ idx = int(pred_idx)
70
+ confidence = float(probs[idx])
71
+ except Exception as e2:
72
+ print(f"Second conversion approach failed: {e2}")
73
+ # Third approach - use item() method if available
74
+ if hasattr(probs[pred_idx], 'item'):
75
+ confidence = probs[pred_idx].item()
76
+ else:
77
+ # Last resort - use the max probability
78
+ confidence = float(max(probs))
79
+
80
+ # Format the prediction results
81
+ response = f"Detected Warning Lamp: {pred_class}\nConfidence: {confidence:.2%}"
82
+
83
+ # Add probabilities for all classes
84
+ response += "\n\nProbabilities for all classes:"
85
+ for i, (cls, prob) in enumerate(zip(learn_inf.dls.vocab, probs)):
86
+ try:
87
+ prob_value = float(prob)
88
+ response += f"\n- {cls}: {prob_value:.2%}"
89
+ except Exception as prob_error:
90
+ print(f"Error converting probability for {cls}: {prob_error}")
91
+ response += f"\n- {cls}: N/A"
92
+
93
+ # Update chat history
94
+ history.append((None, response))
95
+ return history
96
+
97
+ except Exception as e:
98
+ retry_count += 1
99
+ print(f"Attempt {retry_count} failed with error: {e}")
100
+
101
+ if retry_count < max_retries:
102
+ print(f"Retrying in 1 second...")
103
+ time.sleep(1) # Wait a bit before retrying
104
+ else:
105
+ error_msg = f"Error processing image after {max_retries} attempts: {str(e)}"
106
+ print(f"All retries failed: {error_msg}")
107
+ history.append((None, error_msg))
108
+ return history
109
 
110
  # Create a custom interface with image upload
111
  with gr.Blocks(title="Warning Lamp Detector", theme=gr.themes.Soft()) as demo: