""" Netra AI - Gate Auditor AI-powered material classification for construction sites """ import gradio as gr import cv2 import json import base64 import tempfile import os from pathlib import Path from openai import OpenAI import numpy as np OPENAI_API_KEY = os.getenv("OPENAI_API_KEY", "") MOTION_THRESHOLD = 50000 COOLDOWN_SECONDS = 5 PROMPT = """ Analyze this construction site image: 1. **Find the truck/vehicle** carrying material 2. **Return bounding box** as percentage (0-100) 3. **Classify the material** in the truck bed Material classes: - **Reet (Sand)**: Fine to coarse granular material. Smooth texture, no large rocks. - **12mm VSI**: Uniform, small, cubical stones (~10-15mm). Consistent size, clean. - **Stone**: Large irregular BOULDERS with DEEP VOIDS between them. NO fine dust filling gaps. - **GSB**: Mixed-size rocks WITH FINE DUST/SAND FILLING THE GAPS. Dust matrix visible between rocks. **Key**: Stone has voids, GSB has dust filling gaps. Return ONLY JSON: {"bbox": {"x1": 10, "y1": 30, "x2": 90, "y2": 85}, "material": "class_name", "confidence": 0.95, "reason": "brief explanation"} """ def apply_clahe(frame): lab = cv2.cvtColor(frame, cv2.COLOR_BGR2LAB) clahe = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8, 8)) lab[:, :, 0] = clahe.apply(lab[:, :, 0]) return cv2.cvtColor(lab, cv2.COLOR_LAB2BGR) def analyze_frame(frame, client): _, buffer = cv2.imencode('.jpg', frame) image_data = base64.b64encode(buffer).decode('utf-8') response = client.chat.completions.create( model="gpt-4o", max_tokens=200, messages=[{ "role": "user", "content": [ {"type": "image_url", "image_url": {"url": f"data:image/jpeg;base64,{image_data}"}}, {"type": "text", "text": PROMPT} ], }] ) result_text = response.choices[0].message.content.strip() try: if '```' in result_text: for part in result_text.split('```'): if '{' in part: result_text = part.replace('json', '').strip() break return json.loads(result_text) except: material = "Unknown" for m in ["Reet", "Sand", "12mm VSI", "VSI", "Stone", "GSB"]: if m in result_text: material = "Reet" if m == "Sand" else ("12mm VSI" if m == "VSI" else m) break return {"bbox": {"x1": 10, "y1": 30, "x2": 90, "y2": 85}, "material": material, "confidence": 0.0, "reason": ""} def bbox_center(bbox): return ((bbox['x1'] + bbox['x2']) / 2, (bbox['y1'] + bbox['y2']) / 2) def is_same_truck(bbox1, bbox2, threshold=20): c1, c2 = bbox_center(bbox1), bbox_center(bbox2) return abs(c1[0] - c2[0]) < threshold and abs(c1[1] - c2[1]) < threshold def process_video(video_path, progress=gr.Progress()): if not OPENAI_API_KEY: return None, "Error: System not configured. Please contact support.", [] if video_path is None: return None, "Please upload a video", [] client = OpenAI(api_key=OPENAI_API_KEY) cap = cv2.VideoCapture(video_path) if not cap.isOpened(): return None, "Cannot open video", [] fps = cap.get(cv2.CAP_PROP_FPS) total_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT)) width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)) height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT)) duration = total_frames / fps output_path = tempfile.mktemp(suffix='.mp4') fourcc = cv2.VideoWriter_fourcc(*'mp4v') out = cv2.VideoWriter(output_path, fourcc, fps, (width, height)) backSub = cv2.createBackgroundSubtractorMOG2(history=30, varThreshold=25, detectShadows=True) results = [] trucks = {} truck_counter = 0 last_classified_time = -COOLDOWN_SECONDS frame_count = 0 last_detection = None progress(0, desc="Analyzing video...") while True: ret, frame = cap.read() if not ret: break frame_count += 1 current_time = frame_count / fps progress(frame_count / total_frames, desc=f"Processing {current_time:.1f}s / {duration:.1f}s") processed = apply_clahe(frame) vis_frame = frame.copy() if last_detection: bbox = last_detection['bbox_px'] cv2.rectangle(vis_frame, (bbox['x1'], bbox['y1']), (bbox['x2'], bbox['y2']), (0, 0, 255), 3) label = f"Truck #{last_detection['truck_id']}: {last_detection['material']}" cv2.putText(vis_frame, label, (bbox['x1'], bbox['y1'] - 10), cv2.FONT_HERSHEY_SIMPLEX, 1.0, (0, 0, 255), 3) cv2.putText(vis_frame, f"{current_time:.1f}s", (20, 40), cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 255, 255), 2) out.write(vis_frame) fg_mask = backSub.apply(processed) motion_pixels = cv2.countNonZero(fg_mask) if motion_pixels > MOTION_THRESHOLD and (current_time - last_classified_time) > COOLDOWN_SECONDS: try: analysis = analyze_frame(processed, client) bbox_pct = analysis['bbox'] bbox_px = { 'x1': int(bbox_pct['x1'] * width / 100), 'y1': int(bbox_pct['y1'] * height / 100), 'x2': int(bbox_pct['x2'] * width / 100), 'y2': int(bbox_pct['y2'] * height / 100), } truck_id = None for tid, truck in trucks.items(): if current_time - truck['last_seen'] < 10 and is_same_truck(bbox_pct, truck['bbox']): truck_id = tid trucks[tid]['last_seen'] = current_time break if truck_id is None: truck_counter += 1 truck_id = truck_counter trucks[truck_id] = {'bbox': bbox_pct, 'material': analysis['material'], 'last_seen': current_time} result = { "truck_id": truck_id, "timestamp": f"{int(current_time//60):02d}:{int(current_time%60):02d}", "seconds": round(current_time, 2), "material": analysis['material'], "confidence": analysis.get('confidence', 0.0), "reason": analysis.get('reason', ''), "bbox_px": bbox_px } results.append(result) last_detection = result last_classified_time = current_time except Exception as e: print(f"Error at {current_time:.1f}s: {e}") cap.release() out.release() h264_path = tempfile.mktemp(suffix='.mp4') os.system(f'ffmpeg -i {output_path} -c:v libx264 -preset fast -crf 23 {h264_path} -y -loglevel error') if os.path.exists(h264_path) and os.path.getsize(h264_path) > 0: os.remove(output_path) output_path = h264_path counts = {} for r in results: counts[r['material']] = counts.get(r['material'], 0) + 1 summary = f"**Video Duration:** {duration:.1f} seconds\n\n" summary += f"**Trucks Detected:** {truck_counter}\n\n" summary += f"**Total Classifications:** {len(results)}\n\n" if counts: summary += f"**Materials:** {', '.join(f'{m}: {c}' for m, c in counts.items())}" table_data = [[r['truck_id'], r['timestamp'], r['material'], f"{r['confidence']:.0%}"] for r in results] return output_path, summary, table_data custom_css = """ #header { text-align: center; background: linear-gradient(90deg, #667eea 0%, #764ba2 100%); padding: 20px; border-radius: 10px; color: white; margin-bottom: 20px; } """ with gr.Blocks(css=custom_css, title="Netra AI - Gate Auditor") as demo: gr.Markdown("""
AI-powered material classification for construction sites