capradeepgujaran commited on
Commit
9bf83e0
1 Parent(s): f2ae346

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +57 -24
app.py CHANGED
@@ -7,15 +7,17 @@ from PIL import Image as PILImage
7
  import io
8
  import os
9
  import base64
 
10
 
11
  def create_monitor_interface():
12
  api_key = os.getenv("GROQ_API_KEY")
13
 
14
  class SafetyMonitor:
15
  def __init__(self):
16
- self.client = Groq() # API key handled by environment variable
17
  self.model_name = "llama-3.2-90b-vision-preview"
18
- self.max_image_size = (128, 128)
 
19
 
20
  def resize_image(self, image):
21
  height, width = image.shape[:2]
@@ -47,7 +49,7 @@ def create_monitor_interface():
47
  buffered = io.BytesIO()
48
  frame_pil.save(buffered,
49
  format="JPEG",
50
- quality=20,
51
  optimize=True)
52
  img_base64 = base64.b64encode(buffered.getvalue()).decode('utf-8')
53
  image_url = f"data:image/jpeg;base64,{img_base64}"
@@ -61,7 +63,9 @@ def create_monitor_interface():
61
  "content": [
62
  {
63
  "type": "text",
64
- "text": "Analyze this workplace for safety concerns. List any safety issues, missing PPE, or hazards you observe."
 
 
65
  },
66
  {
67
  "type": "image_url",
@@ -77,7 +81,7 @@ def create_monitor_interface():
77
  }
78
  ],
79
  temperature=0.1,
80
- max_tokens=100,
81
  top_p=1,
82
  stream=False,
83
  stop=None
@@ -87,30 +91,59 @@ def create_monitor_interface():
87
  print(f"Detailed error: {str(e)}")
88
  return f"Analysis Error: {str(e)}"
89
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
90
  def process_frame(self, frame: np.ndarray) -> tuple[np.ndarray, str]:
91
  if frame is None:
92
  return None, "No image provided"
93
 
94
  analysis = self.analyze_frame(frame)
95
- display_frame = frame.copy()
96
 
97
- # Add text overlay
98
- overlay = display_frame.copy()
99
- height, width = display_frame.shape[:2]
100
- cv2.rectangle(overlay, (5, 5), (width-5, 100), (0, 0, 0), -1)
101
- cv2.addWeighted(overlay, 0.3, display_frame, 0.7, 0, display_frame)
 
 
 
 
 
 
 
 
 
102
 
103
- # Add analysis text
104
- y_position = 30
105
- lines = analysis.split('\n')
106
- for line in lines:
107
- cv2.putText(display_frame, line[:80], (10, y_position),
108
- cv2.FONT_HERSHEY_SIMPLEX, 0.6, (0, 255, 0), 2)
109
- y_position += 30
110
- if y_position >= 90:
111
- break
112
-
113
- return display_frame, analysis
114
 
115
  # Create the main interface
116
  monitor = SafetyMonitor()
@@ -120,9 +153,9 @@ def create_monitor_interface():
120
 
121
  with gr.Row():
122
  input_image = gr.Image(label="Upload Image")
123
- output_image = gr.Image(label="Results")
124
 
125
- analysis_text = gr.Textbox(label="Analysis", lines=5)
126
 
127
  def analyze_image(image):
128
  if image is None:
 
7
  import io
8
  import os
9
  import base64
10
+ import random
11
 
12
  def create_monitor_interface():
13
  api_key = os.getenv("GROQ_API_KEY")
14
 
15
  class SafetyMonitor:
16
  def __init__(self):
17
+ self.client = Groq()
18
  self.model_name = "llama-3.2-90b-vision-preview"
19
+ self.max_image_size = (640, 640) # Increased size for better visibility
20
+ self.colors = [(255, 0, 0), (0, 255, 0), (0, 0, 255), (255, 255, 0), (255, 0, 255)]
21
 
22
  def resize_image(self, image):
23
  height, width = image.shape[:2]
 
49
  buffered = io.BytesIO()
50
  frame_pil.save(buffered,
51
  format="JPEG",
52
+ quality=30,
53
  optimize=True)
54
  img_base64 = base64.b64encode(buffered.getvalue()).decode('utf-8')
55
  image_url = f"data:image/jpeg;base64,{img_base64}"
 
63
  "content": [
64
  {
65
  "type": "text",
66
+ "text": """Analyze this workplace image and describe each safety concern in this format:
67
+ - <location>Description</location>
68
+ Use one line per issue, starting with a dash and location in tags."""
69
  },
70
  {
71
  "type": "image_url",
 
81
  }
82
  ],
83
  temperature=0.1,
84
+ max_tokens=150,
85
  top_p=1,
86
  stream=False,
87
  stop=None
 
91
  print(f"Detailed error: {str(e)}")
92
  return f"Analysis Error: {str(e)}"
93
 
94
+ def draw_observations(self, image, observations):
95
+ height, width = image.shape[:2]
96
+ font = cv2.FONT_HERSHEY_SIMPLEX
97
+ font_scale = 0.5
98
+ thickness = 2
99
+
100
+ # Generate random positions for each observation
101
+ for idx, obs in enumerate(observations):
102
+ color = self.colors[idx % len(self.colors)]
103
+
104
+ # Generate random box position
105
+ box_width = width // 3
106
+ box_height = height // 3
107
+ x = random.randint(0, width - box_width)
108
+ y = random.randint(0, height - box_height)
109
+
110
+ # Draw rectangle
111
+ cv2.rectangle(image, (x, y), (x + box_width, y + box_height), color, 2)
112
+
113
+ # Add label with background
114
+ label = obs[:40] + "..." if len(obs) > 40 else obs
115
+ label_size = cv2.getTextSize(label, font, font_scale, thickness)[0]
116
+ cv2.rectangle(image, (x, y - 20), (x + label_size[0], y), color, -1)
117
+ cv2.putText(image, label, (x, y - 5), font, font_scale, (255, 255, 255), thickness)
118
+
119
+ return image
120
+
121
  def process_frame(self, frame: np.ndarray) -> tuple[np.ndarray, str]:
122
  if frame is None:
123
  return None, "No image provided"
124
 
125
  analysis = self.analyze_frame(frame)
126
+ display_frame = self.resize_image(frame.copy())
127
 
128
+ # Parse observations from the analysis
129
+ observations = []
130
+ for line in analysis.split('\n'):
131
+ line = line.strip()
132
+ if line.startswith('-'):
133
+ # Extract text between <location> tags if present
134
+ if '<location>' in line and '</location>' in line:
135
+ start = line.find('<location>') + len('<location>')
136
+ end = line.find('</location>')
137
+ observation = line[end + len('</location>'):].strip()
138
+ else:
139
+ observation = line[1:].strip() # Remove the dash
140
+ if observation:
141
+ observations.append(observation)
142
 
143
+ # Draw observations on the image
144
+ annotated_frame = self.draw_observations(display_frame, observations)
145
+
146
+ return annotated_frame, analysis
 
 
 
 
 
 
 
147
 
148
  # Create the main interface
149
  monitor = SafetyMonitor()
 
153
 
154
  with gr.Row():
155
  input_image = gr.Image(label="Upload Image")
156
+ output_image = gr.Image(label="Annotated Results")
157
 
158
+ analysis_text = gr.Textbox(label="Detailed Analysis", lines=5)
159
 
160
  def analyze_image(image):
161
  if image is None: