Spaces:
Paused
Paused
Zhen Ye Claude Opus 4.6 commited on
Commit Β·
624478a
1
Parent(s): a2ca6f9
feat: Add LLM post-processing relevance gate for broad detection
Browse filesMove LLM's role from pre-processing (choosing detector classes) to
post-processing (filtering detected objects against mission intent).
Fast-path (comma-separated labels) is unchanged. LLM-path now detects
broadly (all COCO classes or domain-expanded queries), then asks GPT
once on frame 0 which labels are mission-relevant, caching the result
for deterministic filtering on all subsequent frames.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Files changed (5)
- app.py+6-5
- inference.py+81-28
- utils/mission_parser.py+46
- utils/relevance.py+88-3
- utils/schemas.py+7
56 unmodified lines57585960616263210 unmodified lines27427527627727827928089 unmodified lines37037137237337437537637737837938056 unmodified lines)from utils.gpt_reasoning import estimate_threat_gptfrom utils.threat_chat import chat_about_threatsfrom utils.mission_parser import parse_mission_text, MissionParseErrorlogging.basicConfig(level=logging.INFO)210 unmodified linesif queries.strip():try:mission_spec = parse_mission_text(queries.strip(), detector_name)query_list = mission_spec.object_classesexcept MissionParseError as e:raise HTTPException(status_code=422, detail=str(e))else:89 unmodified linesif queries.strip():try:mission_spec = parse_mission_text(queries.strip(), detector_name)query_list = mission_spec.object_classesmission_mode = "MISSION"logging.info("Mission parsed: mode=%s classes=%s domain=%s(%s)",mission_mode, query_list, mission_spec.domain, mission_spec.domain_source,)except MissionParseError as e:raise HTTPException(56 unmodified lines57585960616263210 unmodified lines27427527627727827928089 unmodified lines37037137237337437537637737837938038156 unmodified lines)from utils.gpt_reasoning import estimate_threat_gptfrom utils.threat_chat import chat_about_threatsfrom utils.mission_parser import parse_mission_text, build_broad_queries, MissionParseErrorlogging.basicConfig(level=logging.INFO)210 unmodified linesif queries.strip():try:mission_spec = parse_mission_text(queries.strip(), detector_name)query_list = build_broad_queries(detector_name, mission_spec)except MissionParseError as e:raise HTTPException(status_code=422, detail=str(e))else:89 unmodified linesif queries.strip():try:mission_spec = parse_mission_text(queries.strip(), detector_name)query_list = build_broad_queries(detector_name, mission_spec)mission_mode = "MISSION"logging.info("Mission parsed: mode=%s classes=%s broad_queries=%s domain=%s(%s)",mission_mode, mission_spec.object_classes, query_list,mission_spec.domain, mission_spec.domain_source,)except MissionParseError as e:raise HTTPException(
22 unmodified lines23242526272829702 unmodified lines732733734735736737738739740741742743744745746747748749750751752753754755756360 unmodified lines11171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311442 unmodified lines114711481149115011511152115322 unmodified linesfrom models.depth_estimators.base import DepthEstimatorfrom utils.video import extract_frames, write_video, VideoReader, VideoWriter, AsyncVideoReaderfrom utils.gpt_reasoning import estimate_threat_gptfrom utils.relevance import evaluate_relevancefrom jobs.storage import set_track_dataimport tempfileimport json as json_module702 unmodified lines# --- RELEVANCE GATE (between detection and GPT) ---if mission_spec:relevant_dets = []for det in detections:decision = evaluate_relevance(det, mission_spec.relevance_criteria)det["mission_relevant"] = decision.relevantdet["relevance_reason"] = decision.reasonif decision.relevant:relevant_dets.append(det)else:logging.info(json_module.dumps({"event": "relevance_decision","label": det.get("label"),"relevant": False,"reason": decision.reason,"required_classes": mission_spec.relevance_criteria.required_classes,"frame": 0,}))gpt_input_dets = relevant_detselse:# LEGACY mode: all detections pass, tagged as unresolvedfor det in detections:360 unmodified lines# Initialize Tracker & Speed Estimatortracker = ByteTracker(frame_rate=fps)speed_est = SpeedEstimator(fps=fps)try:with VideoWriter(output_video_path, fps, width, height) as writer:while next_idx < total_frames:# Fetch from queuetry:while next_idx not in buffer:# Backpressure: If buffer gets too big due to out-of-order frames,# we might want to warn or just hope for the best.# But here we are just consuming.# However, if 'buffer' grows too large (because we are missing next_idx),# we are effectively unbounded again if queue_out fills up with future frames.# So we should monitor buffer size.if len(buffer) > 200 and len(buffer) % 50 == 0:logging.warning("Writer buffer large (%d items), waiting for frame %d (GPT Latency?)...", len(buffer), next_idx)item = queue_out.get(timeout=1.0) # waitidx, p_frame, dets = itembuffer[idx] = (p_frame, dets)# Write next_idxp_frame, dets = buffer.pop(next_idx)2 unmodified linesdets = tracker.update(dets)speed_est.estimate(dets)# --- RELEVANCE GATE ---if mission_spec:for d in dets:decision = evaluate_relevance(d, mission_spec.relevance_criteria)22 unmodified lines23242526272829702 unmodified lines732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788360 unmodified lines114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611772 unmodified lines11801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120622 unmodified linesfrom models.depth_estimators.base import DepthEstimatorfrom utils.video import extract_frames, write_video, VideoReader, VideoWriter, AsyncVideoReaderfrom utils.gpt_reasoning import estimate_threat_gptfrom utils.relevance import evaluate_relevance, evaluate_relevance_llmfrom jobs.storage import set_track_dataimport tempfileimport json as json_module702 unmodified lines# --- RELEVANCE GATE (between detection and GPT) ---if mission_spec:if mission_spec.parse_mode == "FAST_PATH":# Deterministic gate (unchanged)relevant_dets = []for det in detections:decision = evaluate_relevance(det, mission_spec.relevance_criteria)det["mission_relevant"] = decision.relevantdet["relevance_reason"] = decision.reasonif decision.relevant:relevant_dets.append(det)else:logging.info(json_module.dumps({"event": "relevance_decision","label": det.get("label"),"relevant": False,"reason": decision.reason,"required_classes": mission_spec.relevance_criteria.required_classes,"frame": 0,}))gpt_input_dets = relevant_detselse:# LLM_EXTRACTED: post-filter with GPT on frame 0unique_labels = list({d.get("label", "").lower()for d in detections if d.get("label")})relevant_labels = evaluate_relevance_llm(unique_labels, mission_spec.operator_text)# Cache GPT-approved labels into relevance_criteria for subsequent framesmission_spec.relevance_criteria.required_classes = list(relevant_labels)for det in detections:label = (det.get("label") or "").lower()is_relevant = label in relevant_labelsdet["mission_relevant"] = is_relevantdet["relevance_reason"] = "ok" if is_relevant else "llm_excluded"if not is_relevant:logging.info(json_module.dumps({"event": "relevance_decision","label": det.get("label"),"relevant": False,"reason": "llm_excluded","relevant_labels": list(relevant_labels),"frame": 0,}))gpt_input_dets = [d for d in detections if d.get("mission_relevant")]else:# LEGACY mode: all detections pass, tagged as unresolvedfor det in detections:360 unmodified lines# Initialize Tracker & Speed Estimatortracker = ByteTracker(frame_rate=fps)speed_est = SpeedEstimator(fps=fps)llm_filtered = False # LLM post-filter runs once on frame 0try:with VideoWriter(output_video_path, fps, width, height) as writer:while next_idx < total_frames:# Fetch from queuetry:while next_idx not in buffer:# Backpressure: If buffer gets too big due to out-of-order frames,# we might want to warn or just hope for the best.# But here we are just consuming.# However, if 'buffer' grows too large (because we are missing next_idx),# we are effectively unbounded again if queue_out fills up with future frames.# So we should monitor buffer size.if len(buffer) > 200 and len(buffer) % 50 == 0:logging.warning("Writer buffer large (%d items), waiting for frame %d (GPT Latency?)...", len(buffer), next_idx)item = queue_out.get(timeout=1.0) # waitidx, p_frame, dets = itembuffer[idx] = (p_frame, dets)# Write next_idxp_frame, dets = buffer.pop(next_idx)2 unmodified linesdets = tracker.update(dets)speed_est.estimate(dets)# --- LLM POST-FILTER (frame 0 only, LLM_EXTRACTED mode) ---if (mission_specand mission_spec.parse_mode == "LLM_EXTRACTED"and not llm_filteredand next_idx == 0):unique_labels = list({d.get("label", "").lower()for d in dets if d.get("label")})relevant_labels = evaluate_relevance_llm(unique_labels, mission_spec.operator_text)# Cache into relevance_criteria for all subsequent framesmission_spec.relevance_criteria.required_classes = list(relevant_labels)llm_filtered = Truelogging.info("LLM post-filter applied on frame 0: relevant=%s",relevant_labels,)# --- RELEVANCE GATE (deterministic, uses updated criteria) ---if mission_spec:for d in dets:decision = evaluate_relevance(d, mission_spec.relevance_criteria)
113 unmodified lines114115116117118119208 unmodified lines328329330331332333334335336337338113 unmodified linescontext_phrases=[],stripped_modifiers=[],operator_text=raw_text,parse_confidence="HIGH",parse_warnings=warnings,)208 unmodified linescontext_phrases=context_phrases,stripped_modifiers=stripped_modifiers,operator_text=raw_text,parse_confidence=parse_confidence,parse_warnings=parse_warnings,)def parse_mission_text(raw_text: str,detector_key: str,113 unmodified lines114115116117118119120208 unmodified lines329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384113 unmodified linescontext_phrases=[],stripped_modifiers=[],operator_text=raw_text,parse_mode="FAST_PATH",parse_confidence="HIGH",parse_warnings=warnings,)208 unmodified linescontext_phrases=context_phrases,stripped_modifiers=stripped_modifiers,operator_text=raw_text,parse_mode="LLM_EXTRACTED",parse_confidence=parse_confidence,parse_warnings=parse_warnings,)_DOMAIN_BROAD_CATEGORIES: dict[str, List[str]] = {"NAVAL": ["vessel", "ship", "boat", "buoy", "person"],"AERIAL": ["aircraft", "helicopter", "drone", "airplane"],"GROUND": ["vehicle", "car", "truck", "person", "building"],"URBAN": ["person", "vehicle", "car", "bicycle"],"GENERIC": ["object"],}def build_broad_queries(detector_key: str, mission_spec: MissionSpecification) -> List[str]:"""Build broad detector queries for LLM post-filter mode.For FAST_PATH: return object_classes directly (unchanged behavior).For COCO detectors (LLM_EXTRACTED): return ALL 80 COCO classes.For open-vocab detectors (LLM_EXTRACTED): return LLM-extracted classesPLUS broad domain categories to maximize recall."""if mission_spec.parse_mode == "FAST_PATH":return mission_spec.object_classes# LLM_EXTRACTED path: detect broadlyif _is_coco_only(detector_key):# COCO detectors ignore queries anyway (DETR detects all 80;# YOLOv8 falls back to all if no matches). Send everything.return list(COCO_CLASSES)# Open-vocab detector (e.g. Grounding DINO):# Combine LLM-extracted classes with domain-specific broad categoriesbroad = list(mission_spec.object_classes)domain_extras = _DOMAIN_BROAD_CATEGORIES.get(mission_spec.domain, _DOMAIN_BROAD_CATEGORIES["GENERIC"])seen = {c.lower() for c in broad}for cat in domain_extras:if cat.lower() not in seen:broad.append(cat)seen.add(cat.lower())logger.info("Broad queries for %s: %s", detector_key, broad)return broaddef parse_mission_text(raw_text: str,detector_key: str,
12345678910111213141553 unmodified lines697071"""Object relevance evaluation β deterministic gate between detection and GPT assessment.Single public function: evaluate_relevance(detection, criteria) -> RelevanceDecisionINVARIANT INV-13 enforcement: This function accepts RelevanceCriteria, NOTMissionSpecification. It cannot see context_phrases, stripped_modifiers, or anyLLM-derived field. This is structural, not by convention."""import loggingfrom typing import Any, Dict, NamedTuplefrom coco_classes import canonicalize_coco_namefrom utils.schemas import RelevanceCriteria53 unmodified linesreturn RelevanceDecision(True, "ok")return RelevanceDecision(False, "label_not_in_required_classes")12345678910111213141516171819202153 unmodified lines75767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156"""Object relevance evaluation β deterministic gate between detection and GPT assessment.Public functions:evaluate_relevance(detection, criteria) -> RelevanceDecision (deterministic)evaluate_relevance_llm(detected_labels, mission_text) -> set[str] (LLM post-filter)INVARIANT INV-13 enforcement: evaluate_relevance() accepts RelevanceCriteria, NOTMissionSpecification. It cannot see context_phrases, stripped_modifiers, or anyLLM-derived field. This is structural, not by convention."""import jsonimport loggingimport osimport urllib.requestimport urllib.errorfrom typing import Any, Dict, List, NamedTuple, Setfrom coco_classes import canonicalize_coco_namefrom utils.schemas import RelevanceCriteria53 unmodified linesreturn RelevanceDecision(True, "ok")return RelevanceDecision(False, "label_not_in_required_classes")def evaluate_relevance_llm(detected_labels: List[str],mission_text: str,) -> Set[str]:"""Ask GPT which detected labels are relevant to the mission.Called ONCE on frame 0 with the unique labels found by the detector.Returns a set of relevant label strings (lowercased).On API failure, falls back to accepting all labels (fail-open, logged)."""if not detected_labels:return set()api_key = os.environ.get("OPENAI_API_KEY")if not api_key:logger.warning("OPENAI_API_KEY not set β LLM relevance filter falling back to accept-all")return set(detected_labels)prompt = (f"Given this mission: \"{mission_text}\"\n\n"f"Which of these detected object classes are relevant to the mission?\n"f"{json.dumps(detected_labels)}\n\n""Return JSON: {\"relevant_labels\": [...]}\n""Only include labels from the provided list that are relevant to ""accomplishing the mission. Be inclusive β if in doubt, include it.")payload = {"model": "gpt-4o","temperature": 0.0,"max_tokens": 200,"response_format": {"type": "json_object"},"messages": [{"role": "system", "content": "You are a mission relevance filter. Return only JSON."},{"role": "user", "content": prompt},],}headers = {"Content-Type": "application/json","Authorization": f"Bearer {api_key}",}try:req = urllib.request.Request("https://api.openai.com/v1/chat/completions",data=json.dumps(payload).encode("utf-8"),headers=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")if not content:logger.warning("GPT returned empty content for relevance filter β accept-all")return set(detected_labels)result = json.loads(content)relevant = result.get("relevant_labels", detected_labels)relevant_set = {label.lower() for label in relevant}logger.info("LLM relevance filter: mission=%r detected=%s relevant=%s",mission_text, detected_labels, relevant_set,)return relevant_setexcept (urllib.error.HTTPError, urllib.error.URLError) as e:logger.warning("LLM relevance API call failed: %s β accept-all fallback", e)return set(detected_labels)except (json.JSONDecodeError, KeyError, TypeError) as e:logger.warning("LLM relevance response parse failed: %s β accept-all fallback", e)return set(detected_labels)
123 unmodified lines124125126127128129123 unmodified linesdescription="Original unmodified mission text from the operator. Preserved for audit.")# --- LLM self-assessment ---parse_confidence: Literal["HIGH", "MEDIUM", "LOW"] = Field(...,123 unmodified lines124125126127128129130131132133134135136123 unmodified linesdescription="Original unmodified mission text from the operator. Preserved for audit.")# --- Parse mode ---parse_mode: Literal["FAST_PATH", "LLM_EXTRACTED"] = Field(default="FAST_PATH",description="How this spec was created. FAST_PATH = comma-separated labels, ""LLM_EXTRACTED = natural language parsed by GPT.")# --- LLM self-assessment ---parse_confidence: Literal["HIGH", "MEDIUM", "LOW"] = Field(...,
app.py+6-5
inference.py+81-28
utils/mission_parser.py+46
utils/relevance.py+88-3
utils/schemas.py+7