Update app.py
Browse files
app.py
CHANGED
@@ -260,55 +260,254 @@ class RobustSafetyMonitor:
|
|
260 |
|
261 |
|
262 |
def create_monitor_interface():
|
263 |
-
|
264 |
-
monitor = RobustSafetyMonitor()
|
265 |
|
266 |
-
|
267 |
-
|
268 |
-
|
269 |
-
|
270 |
-
|
271 |
-
|
272 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
273 |
|
274 |
with gr.Row():
|
275 |
-
|
276 |
-
|
277 |
-
lines=8,
|
278 |
-
placeholder="Safety analysis will appear here..."
|
279 |
-
)
|
280 |
|
|
|
|
|
281 |
def analyze_image(image):
|
282 |
if image is None:
|
283 |
-
return None, "
|
284 |
try:
|
285 |
processed_frame, analysis = monitor.process_frame(image)
|
286 |
return processed_frame, analysis
|
287 |
except Exception as e:
|
288 |
-
print(f"
|
289 |
-
return None, f"Error
|
290 |
|
291 |
-
input_image.
|
292 |
fn=analyze_image,
|
293 |
inputs=input_image,
|
294 |
outputs=[output_image, analysis_text]
|
295 |
)
|
296 |
|
297 |
gr.Markdown("""
|
298 |
-
## Instructions
|
299 |
-
1. Upload a workplace image
|
300 |
-
2. View detected
|
301 |
-
3.
|
302 |
-
|
303 |
-
## Features
|
304 |
-
- Real-time object detection
|
305 |
-
- AI-powered safety risk analysis
|
306 |
-
- Visual risk highlighting
|
307 |
-
- Detailed safety recommendations
|
308 |
""")
|
309 |
|
310 |
return demo
|
311 |
|
312 |
if __name__ == "__main__":
|
313 |
demo = create_monitor_interface()
|
314 |
-
demo.launch(
|
|
|
260 |
|
261 |
|
262 |
def create_monitor_interface():
|
263 |
+
api_key = os.getenv("GROQ_API_KEY")
|
|
|
264 |
|
265 |
+
class SafetyMonitor:
|
266 |
+
def __init__(self):
|
267 |
+
"""Initialize Safety Monitor with configuration."""
|
268 |
+
self.client = Groq()
|
269 |
+
self.model_name = "llama-3.2-90b-vision-preview"
|
270 |
+
self.max_image_size = (800, 800)
|
271 |
+
self.colors = [(0, 0, 255), (255, 0, 0), (0, 255, 0), (255, 255, 0), (255, 0, 255)]
|
272 |
+
|
273 |
+
def resize_image(self, image):
|
274 |
+
"""Resize image while maintaining aspect ratio."""
|
275 |
+
height, width = image.shape[:2]
|
276 |
+
aspect = width / height
|
277 |
+
|
278 |
+
if width > height:
|
279 |
+
new_width = min(self.max_image_size[0], width)
|
280 |
+
new_height = int(new_width / aspect)
|
281 |
+
else:
|
282 |
+
new_height = min(self.max_image_size[1], height)
|
283 |
+
new_width = int(new_height * aspect)
|
284 |
+
|
285 |
+
return cv2.resize(image, (new_width, new_height), interpolation=cv2.INTER_AREA)
|
286 |
+
|
287 |
+
def analyze_frame(self, frame: np.ndarray) -> str:
|
288 |
+
"""Analyze frame for safety concerns."""
|
289 |
+
if frame is None:
|
290 |
+
return "No frame received"
|
291 |
+
|
292 |
+
# Convert and resize image
|
293 |
+
if len(frame.shape) == 2:
|
294 |
+
frame = cv2.cvtColor(frame, cv2.COLOR_GRAY2RGB)
|
295 |
+
elif len(frame.shape) == 3 and frame.shape[2] == 4:
|
296 |
+
frame = cv2.cvtColor(frame, cv2.COLOR_RGBA2RGB)
|
297 |
+
|
298 |
+
frame = self.resize_image(frame)
|
299 |
+
frame_pil = PILImage.fromarray(frame)
|
300 |
+
|
301 |
+
# Convert to base64
|
302 |
+
buffered = io.BytesIO()
|
303 |
+
frame_pil.save(buffered,
|
304 |
+
format="JPEG",
|
305 |
+
quality=95, # High quality for better analysis
|
306 |
+
optimize=True)
|
307 |
+
img_base64 = base64.b64encode(buffered.getvalue()).decode('utf-8')
|
308 |
+
image_url = f"data:image/jpeg;base64,{img_base64}"
|
309 |
+
|
310 |
+
try:
|
311 |
+
completion = self.client.chat.completions.create(
|
312 |
+
model=self.model_name,
|
313 |
+
messages=[
|
314 |
+
{
|
315 |
+
"role": "user",
|
316 |
+
"content": [
|
317 |
+
{
|
318 |
+
"type": "text",
|
319 |
+
"text": """Analyze this workplace image for safety hazards. For each hazard:
|
320 |
+
1. Specify the exact location (e.g., center, top-left, bottom-right)
|
321 |
+
2. Describe the safety concern in detail
|
322 |
+
|
323 |
+
Format each finding as:
|
324 |
+
- <location>position:detailed safety description</location>
|
325 |
+
|
326 |
+
Consider:
|
327 |
+
- PPE usage and compliance
|
328 |
+
- Ergonomic risks
|
329 |
+
- Equipment safety
|
330 |
+
- Environmental hazards
|
331 |
+
- Work procedures
|
332 |
+
- Material handling
|
333 |
+
"""
|
334 |
+
},
|
335 |
+
{
|
336 |
+
"type": "image_url",
|
337 |
+
"image_url": {
|
338 |
+
"url": image_url
|
339 |
+
}
|
340 |
+
}
|
341 |
+
]
|
342 |
+
}
|
343 |
+
],
|
344 |
+
temperature=0.5,
|
345 |
+
max_tokens=500,
|
346 |
+
stream=False
|
347 |
+
)
|
348 |
+
return completion.choices[0].message.content
|
349 |
+
except Exception as e:
|
350 |
+
print(f"Analysis error: {str(e)}")
|
351 |
+
return f"Analysis Error: {str(e)}"
|
352 |
+
|
353 |
+
def draw_observations(self, image, observations):
|
354 |
+
"""Draw safety observations with accurate locations."""
|
355 |
+
height, width = image.shape[:2]
|
356 |
+
font = cv2.FONT_HERSHEY_SIMPLEX
|
357 |
+
font_scale = 0.5
|
358 |
+
thickness = 2
|
359 |
+
|
360 |
+
def get_region_coordinates(location_text):
|
361 |
+
"""Get coordinates based on location description."""
|
362 |
+
location_text = location_text.lower()
|
363 |
+
regions = {
|
364 |
+
# Basic positions
|
365 |
+
'center': (width//3, height//3, 2*width//3, 2*height//3),
|
366 |
+
'top': (width//4, 0, 3*width//4, height//3),
|
367 |
+
'bottom': (width//4, 2*height//3, 3*width//4, height),
|
368 |
+
'left': (0, height//4, width//3, 3*height//4),
|
369 |
+
'right': (2*width//3, height//4, width, 3*height//4),
|
370 |
+
'top-left': (0, 0, width//3, height//3),
|
371 |
+
'top-right': (2*width//3, 0, width, height//3),
|
372 |
+
'bottom-left': (0, 2*height//3, width//3, height),
|
373 |
+
'bottom-right': (2*width//3, 2*height//3, width, height),
|
374 |
+
|
375 |
+
# Work areas
|
376 |
+
'workspace': (width//4, height//4, 3*width//4, 3*height//4),
|
377 |
+
'machine': (2*width//3, 0, width, height),
|
378 |
+
'equipment': (2*width//3, height//3, width, 2*height//3),
|
379 |
+
'material': (0, 2*height//3, width//3, height),
|
380 |
+
'ground': (0, 2*height//3, width, height),
|
381 |
+
'floor': (0, 3*height//4, width, height),
|
382 |
+
|
383 |
+
# Body regions
|
384 |
+
'body': (width//3, height//3, 2*width//3, 2*height//3),
|
385 |
+
'hands': (width//2, height//2, 3*width//4, 2*height//3),
|
386 |
+
'head': (width//3, 0, 2*width//3, height//4),
|
387 |
+
'feet': (width//3, 3*height//4, 2*width//3, height),
|
388 |
+
'back': (width//3, height//3, 2*width//3, 2*height//3),
|
389 |
+
'knees': (width//3, 2*height//3, 2*width//3, height),
|
390 |
+
|
391 |
+
# Special areas
|
392 |
+
'workspace': (width//4, height//4, 3*width//4, 3*height//4),
|
393 |
+
'working-area': (width//4, height//4, 3*width//4, 3*height//4),
|
394 |
+
'surrounding': (0, 0, width, height),
|
395 |
+
'background': (0, 0, width, height)
|
396 |
+
}
|
397 |
+
|
398 |
+
# Find best matching region
|
399 |
+
best_match = 'center' # default
|
400 |
+
max_match_length = 0
|
401 |
+
|
402 |
+
for region_name in regions.keys():
|
403 |
+
if region_name in location_text and len(region_name) > max_match_length:
|
404 |
+
best_match = region_name
|
405 |
+
max_match_length = len(region_name)
|
406 |
+
|
407 |
+
return regions[best_match]
|
408 |
+
|
409 |
+
for idx, obs in enumerate(observations):
|
410 |
+
color = self.colors[idx % len(self.colors)]
|
411 |
+
|
412 |
+
# Split location and description if available
|
413 |
+
parts = obs.split(':')
|
414 |
+
if len(parts) >= 2:
|
415 |
+
location = parts[0]
|
416 |
+
description = ':'.join(parts[1:])
|
417 |
+
else:
|
418 |
+
location = 'center'
|
419 |
+
description = obs
|
420 |
+
|
421 |
+
# Get region coordinates
|
422 |
+
x1, y1, x2, y2 = get_region_coordinates(location)
|
423 |
+
|
424 |
+
# Draw rectangle
|
425 |
+
cv2.rectangle(image, (x1, y1), (x2, y2), color, 2)
|
426 |
+
|
427 |
+
# Add label
|
428 |
+
label = description[:50] + "..." if len(description) > 50 else description
|
429 |
+
label_size = cv2.getTextSize(label, font, font_scale, thickness)[0]
|
430 |
+
|
431 |
+
# Position text above box
|
432 |
+
text_x = max(0, x1)
|
433 |
+
text_y = max(20, y1 - 5)
|
434 |
+
|
435 |
+
# Draw text background
|
436 |
+
cv2.rectangle(image,
|
437 |
+
(text_x, text_y - label_size[1] - 5),
|
438 |
+
(text_x + label_size[0], text_y),
|
439 |
+
color, -1)
|
440 |
+
|
441 |
+
# Draw text
|
442 |
+
cv2.putText(image, label, (text_x, text_y - 5),
|
443 |
+
font, font_scale, (255, 255, 255), thickness)
|
444 |
+
|
445 |
+
return image
|
446 |
+
|
447 |
+
def process_frame(self, frame: np.ndarray) -> tuple[np.ndarray, str]:
|
448 |
+
"""Process frame and generate safety analysis."""
|
449 |
+
if frame is None:
|
450 |
+
return None, "No image provided"
|
451 |
+
|
452 |
+
analysis = self.analyze_frame(frame)
|
453 |
+
display_frame = self.resize_image(frame.copy())
|
454 |
+
|
455 |
+
# Parse observations
|
456 |
+
observations = []
|
457 |
+
for line in analysis.split('\n'):
|
458 |
+
line = line.strip()
|
459 |
+
if line.startswith('-'):
|
460 |
+
if '<location>' in line and '</location>' in line:
|
461 |
+
start = line.find('<location>') + len('<location>')
|
462 |
+
end = line.find('</location>')
|
463 |
+
observation = line[start:end].strip()
|
464 |
+
if observation:
|
465 |
+
observations.append(observation)
|
466 |
+
|
467 |
+
# Draw observations
|
468 |
+
if observations:
|
469 |
+
annotated_frame = self.draw_observations(display_frame, observations)
|
470 |
+
return annotated_frame, analysis
|
471 |
+
|
472 |
+
return display_frame, analysis
|
473 |
+
|
474 |
+
# Create interface
|
475 |
+
monitor = SafetyMonitor()
|
476 |
+
|
477 |
+
with gr.Blocks() as demo:
|
478 |
+
gr.Markdown("# Safety Analysis System powered by Llama 3.2 90b vision")
|
479 |
|
480 |
with gr.Row():
|
481 |
+
input_image = gr.Image(label="Upload Image")
|
482 |
+
output_image = gr.Image(label="Safety Analysis")
|
|
|
|
|
|
|
483 |
|
484 |
+
analysis_text = gr.Textbox(label="Detailed Analysis", lines=5)
|
485 |
+
|
486 |
def analyze_image(image):
|
487 |
if image is None:
|
488 |
+
return None, "No image provided"
|
489 |
try:
|
490 |
processed_frame, analysis = monitor.process_frame(image)
|
491 |
return processed_frame, analysis
|
492 |
except Exception as e:
|
493 |
+
print(f"Processing error: {str(e)}")
|
494 |
+
return None, f"Error processing image: {str(e)}"
|
495 |
|
496 |
+
input_image.change(
|
497 |
fn=analyze_image,
|
498 |
inputs=input_image,
|
499 |
outputs=[output_image, analysis_text]
|
500 |
)
|
501 |
|
502 |
gr.Markdown("""
|
503 |
+
## Instructions:
|
504 |
+
1. Upload a workplace image
|
505 |
+
2. View detected safety concerns
|
506 |
+
3. Check detailed analysis
|
|
|
|
|
|
|
|
|
|
|
|
|
507 |
""")
|
508 |
|
509 |
return demo
|
510 |
|
511 |
if __name__ == "__main__":
|
512 |
demo = create_monitor_interface()
|
513 |
+
demo.launch()
|