Spaces:
Paused
Paused
Zhen Ye commited on
Commit ·
517108e
1
Parent(s): d257dcc
feat: add job processing timing and latency measurements to backend and frontend
Browse filesFiles changed (5)
27 unmodified lines28293031323354 unmodified lines8889909192935 unmodified lines991001011021031041051 unmodified line1071081091101111121131141151161171181197 unmodified lines127128129130131132277 unmodified lines41041141241341441566 unmodified lines48248348448548648721 unmodified lines50951051151251351448 unmodified lines56356456556656756827 unmodified linesimport asyncioimport shutilimport tempfileimport uuidfrom contextlib import asynccontextmanagerfrom datetime import timedelta54 unmodified lines"""if not enable_gpt or not detections:returntry:# Non-LLM_EXTRACTED relevance filter runs BEFORE run_enrichment (FAST_PATH case)if mission_spec and mission_spec.parse_mode != "LLM_EXTRACTED":5 unmodified linesif not filtered:for det in detections:det["assessment_status"] = AssessmentStatus.ASSESSEDget_job_storage().update(job_id, first_frame_detections=detections)logging.info("All detections non-relevant for job %s; marked ASSESSED", job_id)return1 unmodified linerun_enrichment, 0, frame, detections, mission_spec,job_id=job_id,)logging.info("Background GPT enrichment complete for job %s", job_id)if not gpt_results:# All detections filtered as not relevantfor det in detections:det["assessment_status"] = AssessmentStatus.ASSESSEDget_job_storage().update(job_id, first_frame_detections=detections)logging.info("All detections non-relevant for job %s; marked ASSESSED", job_id)return7 unmodified linesjob_id,first_frame_detections=detections,first_frame_gpt_results=gpt_results,)logging.info("Updated first_frame_detections with GPT results for job %s", job_id)277 unmodified linesraise HTTPException(status_code=400, detail="Video file is required.")job_id = uuid.uuid4().hexjob_dir = get_job_directory(job_id)input_path = get_input_video_path(job_id)output_path = get_output_video_path(job_id)66 unmodified linessegmenter_name=segmenter,)cv2.imwrite(str(first_frame_path), processed_frame)# GPT and depth are now handled in the async pipeline (enrichment thread)depth_map = Nonefirst_frame_gpt_results = None21 unmodified linesmission_spec=mission_spec,mission_mode=mission_mode,first_frame_gpt_results=first_frame_gpt_results,)get_job_storage().create(job)asyncio.create_task(process_video_async(job_id))48 unmodified lines"completed_at": job.completed_at.isoformat() if job.completed_at else None,"error": job.error,"first_frame_detections": job.first_frame_detections,}27 unmodified lines2829303132333454 unmodified lines899091929394955 unmodified lines1011021031041051061071081091101111121131 unmodified line1151161171181191201211221231241251261271281291301311321337 unmodified lines141142143144145146147277 unmodified lines42542642742842943043166 unmodified lines49849950050150250350450521 unmodified lines52752852953053153253348 unmodified lines58258358458558658758858959059159259359427 unmodified linesimport asyncioimport shutilimport tempfileimport timeimport uuidfrom contextlib import asynccontextmanagerfrom datetime import timedelta54 unmodified lines"""if not enable_gpt or not detections:returnt_gpt_start = time.monotonic()try:# Non-LLM_EXTRACTED relevance filter runs BEFORE run_enrichment (FAST_PATH case)if mission_spec and mission_spec.parse_mode != "LLM_EXTRACTED":5 unmodified linesif not filtered:for det in detections:det["assessment_status"] = AssessmentStatus.ASSESSEDgpt_elapsed = time.monotonic() - t_gpt_startlogging.info("TIMING gpt_first_frame=%.3fs for job %s (all non-relevant)", gpt_elapsed, job_id)get_job_storage().update(job_id,first_frame_detections=detections,timing_gpt_first_frame_s=gpt_elapsed,)logging.info("All detections non-relevant for job %s; marked ASSESSED", job_id)return1 unmodified linerun_enrichment, 0, frame, detections, mission_spec,job_id=job_id,)gpt_elapsed = time.monotonic() - t_gpt_startlogging.info("TIMING gpt_first_frame=%.3fs for job %s", gpt_elapsed, job_id)logging.info("Background GPT enrichment complete for job %s", job_id)if not gpt_results:# All detections filtered as not relevantfor det in detections:det["assessment_status"] = AssessmentStatus.ASSESSEDget_job_storage().update(job_id,first_frame_detections=detections,timing_gpt_first_frame_s=gpt_elapsed,)logging.info("All detections non-relevant for job %s; marked ASSESSED", job_id)return7 unmodified linesjob_id,first_frame_detections=detections,first_frame_gpt_results=gpt_results,timing_gpt_first_frame_s=gpt_elapsed,)logging.info("Updated first_frame_detections with GPT results for job %s", job_id)277 unmodified linesraise HTTPException(status_code=400, detail="Video file is required.")job_id = uuid.uuid4().hext_job_start = time.monotonic()job_dir = get_job_directory(job_id)input_path = get_input_video_path(job_id)output_path = get_output_video_path(job_id)66 unmodified linessegmenter_name=segmenter,)cv2.imwrite(str(first_frame_path), processed_frame)first_frame_elapsed = time.monotonic() - t_job_startlogging.info("TIMING first_frame=%.3fs for job %s", first_frame_elapsed, job_id)# GPT and depth are now handled in the async pipeline (enrichment thread)depth_map = Nonefirst_frame_gpt_results = None21 unmodified linesmission_spec=mission_spec,mission_mode=mission_mode,first_frame_gpt_results=first_frame_gpt_results,timing_first_frame_s=first_frame_elapsed,)get_job_storage().create(job)asyncio.create_task(process_video_async(job_id))48 unmodified lines"completed_at": job.completed_at.isoformat() if job.completed_at else None,"error": job.error,"first_frame_detections": job.first_frame_detections,"timing": {"first_frame_s": job.timing_first_frame_s,"video_processing_s": job.timing_video_processing_s,"gpt_first_frame_s": job.timing_gpt_first_frame_s,"gpt_enrichment_s": job.timing_gpt_enrichment_s,"total_s": job.timing_total_s,},}
191 unmodified lines192193194195196197191 unmodified linessyncGpt(status.first_frame_detections, "final sync");}try {await fetchProcessedVideo();await fetchDepthVideo();191 unmodified lines192193194195196197198199200201202203204205206207208209191 unmodified linessyncGpt(status.first_frame_detections, "final sync");}// Display timing summaryif (status.timing) {const t = status.timing;const parts = [];if (t.first_frame_s != null) parts.push(`1st frame: ${t.first_frame_s.toFixed(2)}s`);if (t.video_processing_s != null) parts.push(`video: ${t.video_processing_s.toFixed(2)}s`);if (t.gpt_first_frame_s != null) parts.push(`GPT: ${t.gpt_first_frame_s.toFixed(2)}s`);if (t.gpt_enrichment_s != null) parts.push(`GPT enrich: ${t.gpt_enrichment_s.toFixed(2)}s`);if (t.total_s != null) parts.push(`total: ${t.total_s.toFixed(2)}s`);if (parts.length) log(`Timing: ${parts.join(" | ")}`, "t");}try {await fetchProcessedVideo();await fetchDepthVideo();
1984 unmodified lines19851986198719881989199019911992199319941995199635 unmodified lines2032203320342035203620371984 unmodified linesbreakframe_idx, frame_data, gpt_dets, ms = itemtry:gpt_res = run_enrichment(frame_idx, frame_data, gpt_dets, ms,first_frame_gpt_results=first_frame_gpt_results,job_id=job_id,relevance_refined_event=_relevance_refined,)# GSAM2-specific: store results in per-track dict and persist to job storageif gpt_res:35 unmodified linesjob_id,first_frame_detections=_st.first_frame_detections,first_frame_gpt_results=gpt_res,)logging.info("GSAM2 enrichment: updated first_frame_detections in job storage for %s",1984 unmodified lines19851986198719881989199019911992199319941995199619971998199935 unmodified lines20352036203720382039204020411984 unmodified linesbreakframe_idx, frame_data, gpt_dets, ms = itemtry:t_enrich_start = time.monotonic()gpt_res = run_enrichment(frame_idx, frame_data, gpt_dets, ms,first_frame_gpt_results=first_frame_gpt_results,job_id=job_id,relevance_refined_event=_relevance_refined,)gpt_enrichment_elapsed = time.monotonic() - t_enrich_startlogging.info("TIMING gpt_enrichment=%.3fs for job %s", gpt_enrichment_elapsed, job_id)# GSAM2-specific: store results in per-track dict and persist to job storageif gpt_res:35 unmodified linesjob_id,first_frame_detections=_st.first_frame_detections,first_frame_gpt_results=gpt_res,timing_gpt_enrichment_s=gpt_enrichment_elapsed,)logging.info("GSAM2 enrichment: updated first_frame_detections in job storage for %s",
1234518 unmodified lines24252627282933 unmodified lines63646566676869703 unmodified lines7475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121import asyncioimport loggingfrom datetime import datetimeimport torch18 unmodified lines# Create stream for live viewstream_queue = create_stream(job_id)try:# Run detection or segmentation firstif job.mode == "segmentation":33 unmodified linesdetection_path, detections_list = result_pkg# If depth was requested, checking if output path exists for depth# The unified pipeline creates 'output_video_path'.# If depth enabled, it might have written depth there?# Actually run_inference returns (video_path, detections).# If depth was ON, the video at video_path *has* depth overlays.# But the 'Depth Video' (heatmap only) is usually separate.3 unmodified lines# Let's keep it simple: If depth enabled, the main video IS the depth view (overlay).# Or if we want separate `depth_output_path`, we need `run_inference` to handle it.# Let's assume for now `run_inference` writes the main visualization path.if job.depth_estimator_name:# In unified mode, the main video contains the depth vizdepth_path = detection_pathlogging.info("Depth estimation included in main video for job %s", job_id)# Mark as completed (with or without depth)storage.update(job_id,status=JobStatus.COMPLETED,completed_at=datetime.utcnow(),output_video_path=detection_path,depth_output_path=depth_path,partial_success=partial_success,depth_error=depth_error,)except RuntimeError as exc:# Handle cancellation specificallyif "cancelled" in str(exc).lower():logging.info("Job %s was cancelled", job_id)storage.update(job_id,status=JobStatus.CANCELLED,completed_at=datetime.utcnow(),error="Cancelled by user",)else:logging.exception("Background processing failed for job %s", job_id)storage.update(job_id,status=JobStatus.FAILED,completed_at=datetime.utcnow(),error=str(exc),)except Exception as exc:logging.exception("Background processing failed for job %s", job_id)storage.update(job_id,status=JobStatus.FAILED,completed_at=datetime.utcnow(),error=str(exc),)finally:remove_stream(job_id)12345618 unmodified lines252627282930313233 unmodified lines66676869707172733 unmodified lines7778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144import asyncioimport loggingimport timefrom datetime import datetimeimport torch18 unmodified lines# Create stream for live viewstream_queue = create_stream(job_id)t_video_start = time.monotonic()try:# Run detection or segmentation firstif job.mode == "segmentation":33 unmodified linesdetection_path, detections_list = result_pkg# If depth was requested, checking if output path exists for depth# The unified pipeline creates 'output_video_path'.# If depth enabled, it might have written depth there?# Actually run_inference returns (video_path, detections).# If depth was ON, the video at video_path *has* depth overlays.# But the 'Depth Video' (heatmap only) is usually separate.3 unmodified lines# Let's keep it simple: If depth enabled, the main video IS the depth view (overlay).# Or if we want separate `depth_output_path`, we need `run_inference` to handle it.# Let's assume for now `run_inference` writes the main visualization path.if job.depth_estimator_name:# In unified mode, the main video contains the depth vizdepth_path = detection_pathlogging.info("Depth estimation included in main video for job %s", job_id)video_elapsed = time.monotonic() - t_video_startcompleted_at = datetime.utcnow()total_elapsed = (completed_at - job.created_at).total_seconds()logging.info("TIMING video_processing=%.3fs for job %s", video_elapsed, job_id)logging.info("TIMING total=%.3fs for job %s", total_elapsed, job_id)# Mark as completed (with or without depth)storage.update(job_id,status=JobStatus.COMPLETED,completed_at=completed_at,output_video_path=detection_path,depth_output_path=depth_path,partial_success=partial_success,depth_error=depth_error,timing_video_processing_s=video_elapsed,timing_total_s=total_elapsed,)except RuntimeError as exc:video_elapsed = time.monotonic() - t_video_startcompleted_at = datetime.utcnow()total_elapsed = (completed_at - job.created_at).total_seconds()# Handle cancellation specificallyif "cancelled" in str(exc).lower():logging.info("Job %s was cancelled", job_id)storage.update(job_id,status=JobStatus.CANCELLED,completed_at=completed_at,error="Cancelled by user",timing_video_processing_s=video_elapsed,timing_total_s=total_elapsed,)else:logging.exception("Background processing failed for job %s", job_id)storage.update(job_id,status=JobStatus.FAILED,completed_at=completed_at,error=str(exc),timing_video_processing_s=video_elapsed,timing_total_s=total_elapsed,)except Exception as exc:video_elapsed = time.monotonic() - t_video_startcompleted_at = datetime.utcnow()total_elapsed = (completed_at - job.created_at).total_seconds()logging.exception("Background processing failed for job %s", job_id)storage.update(job_id,status=JobStatus.FAILED,completed_at=completed_at,error=str(exc),timing_video_processing_s=video_elapsed,timing_total_s=total_elapsed,)finally:remove_stream(job_id)
37 unmodified lines38394037 unmodified linesmission_spec: Optional[Any] = None # utils.schemas.MissionSpecificationmission_mode: str = "LEGACY" # "MISSION" or "LEGACY"first_frame_gpt_results: Optional[Dict[str, Any]] = None # Cached GPT results from process_first_frame37 unmodified lines38394041424344454637 unmodified linesmission_spec: Optional[Any] = None # utils.schemas.MissionSpecificationmission_mode: str = "LEGACY" # "MISSION" or "LEGACY"first_frame_gpt_results: Optional[Dict[str, Any]] = None # Cached GPT results from process_first_frame# Latency measurements (seconds)timing_first_frame_s: Optional[float] = Nonetiming_video_processing_s: Optional[float] = Nonetiming_gpt_first_frame_s: Optional[float] = Nonetiming_gpt_enrichment_s: Optional[float] = Nonetiming_total_s: Optional[float] = None
app.py+28-2
frontend/js/api/client.js+12
inference.py+4
jobs/background.py+30-7
jobs/models.py+6