Spaces:
Paused
Paused
Zhen Ye commited on
Commit ·
4977275
1
Parent(s): 55e372a
Add StreamingVideoWriter (ffmpeg pipe), reuse first-frame GPT results in inference pipeline
Browse filesFiles changed (2)
- inference.py+69-61
- utils/video.py+78-3
20 unmodified lines2122232425262728689 unmodified lines71871972072172272372472572672772872973091 unmodified lines82282382482582682782882983083183283383483583614 unmodified lines8518528538548558568578 unmodified lines866867868869870871123 unmodified lines99599699799899910001001145 unmodified lines1147114811491150115111521153115411551156115711581159116011611162116311641165116613 unmodified lines1180118111821183118411851186118711881189119011911192119311941195119611971198119922 unmodified lines1222122312241225122612271228122912301231123212331234123512361237123812391240124112421243319 unmodified lines15631564156515661567156815691570157115721573157415751576157715781579318 unmodified lines1898189919001901190219031904190519061907190819091910191119123 unmodified lines191619171918191919201921192219231924192519267 unmodified lines193419351936193719381939194020 unmodified linesfrom models.segmenters.model_loader import load_segmenter, load_segmenter_on_devicefrom models.depth_estimators.model_loader import load_depth_estimator, load_depth_estimator_on_devicefrom 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 tempfile689 unmodified linesenable_depth_estimator: bool = False,enable_gpt: bool = True, # ENABLED BY DEFAULTmission_spec=None, # Optional[MissionSpecification]) -> Tuple[np.ndarray, List[Dict[str, Any]], Optional[np.ndarray]]:frame, _, _, _ = extract_first_frame(video_path)if mode == "segmentation":processed, _ = infer_segmentation_frame(frame, text_queries=queries, segmenter_name=segmenter_name)return processed, [], Noneprocessed, detections = infer_frame(frame, queries, detector_name=detector_name91 unmodified lines# 2. GPT-based Distance/Direction Estimation (Explicitly enabled)# Only assess mission-relevant detectionsif enable_gpt and gpt_input_dets:try:with tempfile.NamedTemporaryFile(suffix=".jpg", delete=False) as tmp_img:cv2.imwrite(tmp_img.name, frame)gpt_results = estimate_threat_gpt(tmp_img.name, gpt_input_dets, mission_spec=mission_spec)logging.info(f"GPT Output for First Frame:\n{gpt_results}")os.remove(tmp_img.name)# Merge GPT results into detections (polyfilled keys from gpt_reasoning)for i, det in enumerate(gpt_input_dets):14 unmodified linesif "assessment_status" not in det:det["assessment_status"] = "UNASSESSED"return processed, detections, depth_mapdef run_inference(8 unmodified linesenable_gpt: bool = True,stream_queue: Optional[Queue] = None,mission_spec=None, # Optional[MissionSpecification]) -> Tuple[str, List[List[Dict[str, Any]]]]:# 1. Setup Video Reader123 unmodified linesqueue_in = Queue(maxsize=16)# Tuning for A10: buffer at least 32 frames per GPU (batch size)# GPT Latency Buffer: GPT takes ~3s. At 30fps, that's 90 frames. We need to absorb this burst.queue_out_max = max(512, (len(detectors) if detectors else 1) * 64)queue_out = Queue(maxsize=queue_out_max)145 unmodified linesllm_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) # wait13 unmodified linesand 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:22 unmodified lines# --- GPT ESTIMATION (Frame 0 Only) ---if next_idx == 0 and enable_gpt and gpt_dets:try:logging.info("Running GPT estimation for video start (Frame 0)...")with tempfile.NamedTemporaryFile(suffix=".jpg", delete=False) as tmp:cv2.imwrite(tmp.name, p_frame)gpt_res = estimate_threat_gpt(tmp.name, gpt_dets, mission_spec=mission_spec)os.remove(tmp.name)# Merge using real track_id assigned by ByteTrackerfor d in gpt_dets:oid = d.get('track_id')if oid and oid in gpt_res:d.update(gpt_res[oid])d["gpt_raw"] = gpt_res[oid]d["assessment_frame_index"] = 0d["assessment_status"] = "ASSESSED"# Push GPT data back into tracker's internal STrack objectstracker.inject_metadata(gpt_dets)319 unmodified linesbuffer = {}try:with VideoWriter(output_video_path, fps, width, height) as writer:while next_idx < total_frames:try:while next_idx not in buffer:# Check buffer sizeif len(buffer) > 64:logging.warning("Writer buffer large (%d), waiting for %d", len(buffer), next_idx)idx, frm = queue_out.get(timeout=1.0)buffer[idx] = frmfrm = buffer.pop(next_idx)writer.write(frm)318 unmodified linesprocessed_frames_subset = [] # Keep first frame for saving if neededtry:with VideoWriter(output_video_path, fps, width, height) as writer:while next_idx < total_frames:try:while next_idx not in buffer:if len(buffer) > 64:logging.warning("Writer buffer large (%d), waiting for %d", len(buffer), next_idx)idx, frm = queue_out.get(timeout=1.0)buffer[idx] = frmfrm = buffer.pop(next_idx)writer.write(frm)3 unmodified linesexcept:passif first_frame_depth_path and not first_frame_saved and next_idx == 0:cv2.imwrite(first_frame_depth_path, frm)first_frame_saved = Truenext_idx += 1if next_idx % 30 == 0:logging.debug("Wrote depth frame %d/%d", next_idx, total_frames)7 unmodified linesw_thread = Thread(target=writer_loop, daemon=True)w_thread.start()# Feedertry:reader_iter = iter(reader)20 unmodified lines2122232425262728689 unmodified lines71871972072172272372472572672772872973091 unmodified lines82282382482582682782882983083183283383483583614 unmodified lines8518528538548558568578 unmodified lines866867868869870871872123 unmodified lines996997998999100010011002145 unmodified lines11481149115011511152115311541155115611571158115911601161116213 unmodified lines11761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120222 unmodified lines12251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250319 unmodified lines15701571157215731574157515761577157815791580158115821583158415851586318 unmodified lines19051906190719081909191019111912191319141915191619171918191919203 unmodified lines192419251926192719281929193019311932193319347 unmodified lines194219431944194519461947194820 unmodified linesfrom models.segmenters.model_loader import load_segmenter, load_segmenter_on_devicefrom models.depth_estimators.model_loader import load_depth_estimator, load_depth_estimator_on_devicefrom models.depth_estimators.base import DepthEstimatorfrom utils.video import extract_frames, write_video, VideoReader, VideoWriter, AsyncVideoReader, StreamingVideoWriterfrom utils.gpt_reasoning import estimate_threat_gpt, encode_frame_to_b64from utils.relevance import evaluate_relevance, evaluate_relevance_llmfrom jobs.storage import set_track_dataimport tempfile689 unmodified linesenable_depth_estimator: bool = False,enable_gpt: bool = True, # ENABLED BY DEFAULTmission_spec=None, # Optional[MissionSpecification]) -> Tuple[np.ndarray, List[Dict[str, Any]], Optional[np.ndarray], Optional[Dict[str, Any]]]:frame, _, _, _ = extract_first_frame(video_path)if mode == "segmentation":processed, _ = infer_segmentation_frame(frame, text_queries=queries, segmenter_name=segmenter_name)return processed, [], None, Noneprocessed, detections = infer_frame(frame, queries, detector_name=detector_name91 unmodified lines# 2. GPT-based Distance/Direction Estimation (Explicitly enabled)# Only assess mission-relevant detectionsgpt_results = Noneif enable_gpt and gpt_input_dets:try:frame_b64 = encode_frame_to_b64(frame)gpt_results = estimate_threat_gpt(detections=gpt_input_dets, mission_spec=mission_spec,image_b64=frame_b64,)logging.info(f"GPT Output for First Frame:\n{gpt_results}")# Merge GPT results into detections (polyfilled keys from gpt_reasoning)for i, det in enumerate(gpt_input_dets):14 unmodified linesif "assessment_status" not in det:det["assessment_status"] = "UNASSESSED"return processed, detections, depth_map, gpt_resultsdef run_inference(8 unmodified linesenable_gpt: bool = True,stream_queue: Optional[Queue] = None,mission_spec=None, # Optional[MissionSpecification]first_frame_gpt_results: Optional[Dict[str, Any]] = None,) -> Tuple[str, List[List[Dict[str, Any]]]]:# 1. Setup Video Reader123 unmodified linesqueue_in = Queue(maxsize=16)# Tuning for A10: buffer at least 32 frames per GPU (batch size)# GPT Latency Buffer: GPT takes ~3s. At 30fps, that's 90 frames. We need to absorb this burst.queue_out_max = max(128, (len(detectors) if detectors else 1) * 32)queue_out = Queue(maxsize=queue_out_max)145 unmodified linesllm_filtered = False # LLM post-filter runs once on frame 0try:with StreamingVideoWriter(output_video_path, fps, width, height) as writer:while next_idx < total_frames:# Fetch from queuetry:while next_idx not in buffer:# Backpressure: bound the reorder buffer to prevent memory blowupif len(buffer) > 128:logging.warning("Writer reorder buffer too large (%d items), applying backpressure (waiting for frame %d)...", len(buffer), next_idx)time.sleep(0.05)item = queue_out.get(timeout=1.0) # wait13 unmodified linesand mission_spec.parse_mode == "LLM_EXTRACTED"and not llm_filteredand next_idx == 0):# Skip if process_first_frame already populated required_classesif mission_spec.relevance_criteria.required_classes:logging.info("LLM post-filter already applied by process_first_frame: classes=%s",mission_spec.relevance_criteria.required_classes,)else: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)logging.info("LLM post-filter applied on frame 0: relevant=%s",relevant_labels,)llm_filtered = True# --- RELEVANCE GATE (deterministic, uses updated criteria) ---if mission_spec:22 unmodified lines# --- GPT ESTIMATION (Frame 0 Only) ---if next_idx == 0 and enable_gpt and gpt_dets:try:if first_frame_gpt_results:# Re-use GPT results from process_first_frame (avoid duplicate call)logging.info("Re-using GPT results from first-frame processing (skipping duplicate call)")gpt_res = first_frame_gpt_resultselse:logging.info("Running GPT estimation for video start (Frame 0)...")frame_b64 = encode_frame_to_b64(p_frame)gpt_res = estimate_threat_gpt(detections=gpt_dets, mission_spec=mission_spec,image_b64=frame_b64,)# Merge using real track_id assigned by ByteTrackerfor d in gpt_dets:oid = d.get('track_id')if oid and oid in gpt_res:d.update(gpt_res[oid])d["gpt_raw"] = gpt_res[oid]d["assessment_frame_index"] = 0d["assessment_status"] = "ASSESSED"# Push GPT data back into tracker's internal STrack objectstracker.inject_metadata(gpt_dets)319 unmodified linesbuffer = {}try:with StreamingVideoWriter(output_video_path, fps, width, height) as writer:while next_idx < total_frames:try:while next_idx not in buffer:if len(buffer) > 128:logging.warning("Writer reorder buffer too large (%d), applying backpressure (waiting for frame %d)...", len(buffer), next_idx)time.sleep(0.05)idx, frm = queue_out.get(timeout=1.0)buffer[idx] = frmfrm = buffer.pop(next_idx)writer.write(frm)318 unmodified linesprocessed_frames_subset = [] # Keep first frame for saving if neededtry:with StreamingVideoWriter(output_video_path, fps, width, height) as writer:while next_idx < total_frames:try:while next_idx not in buffer:if len(buffer) > 128:logging.warning("Writer reorder buffer too large (%d), applying backpressure (waiting for frame %d)...", len(buffer), next_idx)time.sleep(0.05)idx, frm = queue_out.get(timeout=1.0)buffer[idx] = frmfrm = buffer.pop(next_idx)writer.write(frm)3 unmodified linesexcept:passif first_frame_depth_path and not first_frame_saved and next_idx == 0:cv2.imwrite(first_frame_depth_path, frm)first_frame_saved = Truenext_idx += 1if next_idx % 30 == 0:logging.debug("Wrote depth frame %d/%d", next_idx, total_frames)7 unmodified linesw_thread = Thread(target=writer_loop, daemon=True)w_thread.start()# Feedertry:reader_iter = iter(reader)
211 unmodified lines2122132142152162172182192202216 unmodified lines22822923023123223323411 unmodified lines246247248211 unmodified linesself.fps = fpsself.width = widthself.height = heightself.temp_fd, self.temp_path = tempfile.mkstemp(prefix="raw_", suffix=".mp4")os.close(self.temp_fd)# Use mp4v for speed during writing, then transcodeself.writer = cv2.VideoWriter(self.temp_path, cv2.VideoWriter_fourcc(*"mp4v"), self.fps, (self.width, self.height))if not self.writer.isOpened():6 unmodified linesdef close(self):if self.writer.isOpened():self.writer.release()# Transcode phasetry:_transcode_with_ffmpeg(self.temp_path, self.output_path)11 unmodified linesdef __exit__(self, exc_type, exc_val, exc_tb):self.close()211 unmodified lines2122132142152162172182192202216 unmodified lines22822923023123223323411 unmodified lines246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323211 unmodified linesself.fps = fpsself.width = widthself.height = heightself.temp_fd, self.temp_path = tempfile.mkstemp(prefix="raw_", suffix=".mp4")os.close(self.temp_fd)# Use mp4v for speed during writing, then transcodeself.writer = cv2.VideoWriter(self.temp_path, cv2.VideoWriter_fourcc(*"mp4v"), self.fps, (self.width, self.height))if not self.writer.isOpened():6 unmodified linesdef close(self):if self.writer.isOpened():self.writer.release()# Transcode phasetry:_transcode_with_ffmpeg(self.temp_path, self.output_path)11 unmodified linesdef __exit__(self, exc_type, exc_val, exc_tb):self.close()def _ffmpeg_available() -> bool:"""Check if ffmpeg is available on the system PATH."""return shutil.which("ffmpeg") is not Noneclass StreamingVideoWriter:"""Pipes raw BGR frames directly to an ffmpeg subprocess for H.264 encoding.Eliminates the cv2.VideoWriter + post-transcode round-trip.Falls back to VideoWriter if ffmpeg is unavailable."""def __init__(self, output_path: str, fps: float, width: int, height: int):self.output_path = output_pathself._fallback = Noneif not _ffmpeg_available():logging.warning("ffmpeg not found; StreamingVideoWriter falling back to VideoWriter.")self._fallback = VideoWriter(output_path, fps, width, height)returncmd = ["ffmpeg", "-y","-f", "rawvideo","-pix_fmt", "bgr24","-s", f"{width}x{height}","-r", str(fps),"-i", "pipe:","-c:v", "libx264","-preset", "veryfast","-pix_fmt", "yuv420p","-movflags", "+faststart",output_path,]try:self.proc = subprocess.Popen(cmd,stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=subprocess.PIPE,)except OSError as e:logging.warning("Failed to start ffmpeg (%s); falling back to VideoWriter.", e)self._fallback = VideoWriter(output_path, fps, width, height)def write(self, frame: np.ndarray):if self._fallback is not None:self._fallback.write(frame)returntry:self.proc.stdin.write(frame.tobytes())except BrokenPipeError:logging.error("ffmpeg pipe broken; frames may be lost.")def close(self):if self._fallback is not None:self._fallback.close()returntry:self.proc.stdin.close()except OSError:passself.proc.wait()if self.proc.returncode != 0:stderr = self.proc.stderr.read().decode("utf-8", errors="ignore")logging.error("StreamingVideoWriter ffmpeg exited with code %d: %s",self.proc.returncode, stderr)def __enter__(self):return selfdef __exit__(self, exc_type, exc_val, exc_tb):self.close()
inference.py+69-61
utils/video.py+78-3