Spaces:
Paused
Paused
Zhen Ye commited on
Commit ·
55e372a
1
Parent(s): 58bb3a4
GPT reasoning: add in-memory frame encoding, image_b64 support, use gpt-4o-mini for relevance
Browse filesFiles changed (2)
- utils/gpt_reasoning.py+31-10
- utils/relevance.py+1-1
14 unmodified lines15161718192089 unmodified lines11011111211311411511611711811912012112212312412512612712812913012 unmodified lines14314414514614714814915015115215330 unmodified lines18418518618718818919016 unmodified lines20720820921021121221314 unmodified linesreturn base64.b64encode(image_file.read()).decode('utf-8')_DOMAIN_ROLES = {"NAVAL": "Naval Intelligence Officer and Maritime Threat Analyst","GROUND": "Ground Surveillance Intelligence Officer",89 unmodified linesdef estimate_threat_gpt(image_path: str,detections: List[Dict[str, Any]],mission_spec=None, # Optional[MissionSpecification]) -> Dict[str, Any]:"""Perform Threat Assessment on detected objects using GPT-4o.Args:image_path: Path to the image file.detections: List of detection dicts (bbox, label, etc.).mission_spec: Optional MissionSpecification for domain-aware assessment.Returns:Dict mapping object ID (e.g., T01) to threat assessment dict."""api_key = os.environ.get("OPENAI_API_KEY")if not api_key:logger.warning("OPENAI_API_KEY not set. Skipping GPT threat assessment.")12 unmodified linesif not det_text:return {}# 2. Encode imagetry:base64_image = encode_image(image_path)except Exception as e:logger.error(f"Failed to encode image for GPT: {e}")return {}# 3. Domain-aware prompt selection (INV-7)30 unmodified lines{"type": "image_url","image_url": {"url": f"data:image/jpeg;base64,{base64_image}"}}]16 unmodified linesheaders=headers,method="POST")with urllib.request.urlopen(req) as response:resp_data = json.loads(response.read().decode('utf-8'))content = resp_data['choices'][0]['message'].get('content')14 unmodified lines15161718192021222324252627282989 unmodified lines11912012112212312412512612712812913013113213313413513613713813914014114214314412 unmodified lines15715815916016116216316416516616716816917017117217330 unmodified lines20420520620720820921021116 unmodified lines22822923023123223323414 unmodified linesreturn base64.b64encode(image_file.read()).decode('utf-8')def encode_frame_to_b64(frame) -> str:"""Encode an OpenCV BGR frame to a base64 JPEG string in memory (no disk I/O)."""import cv2success, buf = cv2.imencode('.jpg', frame)if not success:raise ValueError("Failed to encode frame to JPEG")return base64.b64encode(buf.tobytes()).decode('utf-8')_DOMAIN_ROLES = {"NAVAL": "Naval Intelligence Officer and Maritime Threat Analyst","GROUND": "Ground Surveillance Intelligence Officer",89 unmodified linesdef estimate_threat_gpt(image_path: Optional[str] = None,detections: Optional[List[Dict[str, Any]]] = None,mission_spec=None, # Optional[MissionSpecification]image_b64: Optional[str] = None,) -> Dict[str, Any]:"""Perform Threat Assessment on detected objects using GPT-4o.Args:image_path: Path to the image file (mutually exclusive with image_b64).detections: List of detection dicts (bbox, label, etc.).mission_spec: Optional MissionSpecification for domain-aware assessment.image_b64: Pre-encoded base64 JPEG string (avoids disk round-trip).Returns:Dict mapping object ID (e.g., T01) to threat assessment dict."""if detections is None:detections = []api_key = os.environ.get("OPENAI_API_KEY")if not api_key:logger.warning("OPENAI_API_KEY not set. Skipping GPT threat assessment.")12 unmodified linesif not det_text:return {}# 2. Encode image (prefer pre-encoded b64 to avoid disk I/O)if image_b64:base64_image = image_b64elif image_path:try:base64_image = encode_image(image_path)except Exception as e:logger.error(f"Failed to encode image for GPT: {e}")return {}else:logger.error("estimate_threat_gpt: no image_path or image_b64 provided")return {}# 3. Domain-aware prompt selection (INV-7)30 unmodified lines{"type": "image_url","image_url": {"url": f"data:image/jpeg;base64,{base64_image}","detail": "low"}}]16 unmodified linesheaders=headers,method="POST")with urllib.request.urlopen(req, timeout=30) as response:resp_data = json.loads(response.read().decode('utf-8'))content = resp_data['choices'][0]['message'].get('content')
107 unmodified lines108109110111112113114107 unmodified lines)payload = {"model": "gpt-4o","temperature": 0.0,"max_tokens": 200,"response_format": {"type": "json_object"},107 unmodified lines108109110111112113114107 unmodified lines)payload = {"model": "gpt-4o-mini","temperature": 0.0,"max_tokens": 200,"response_format": {"type": "json_object"},
utils/gpt_reasoning.py+31-10
utils/relevance.py+1-1