Spaces:
Sleeping
Sleeping
GeraldoRiberia commited on
Commit ·
679b5d0
1
Parent(s): 9f43980
123452 unmodified lines89101112135 unmodified lines19202122232418 unmodified lines434445464748495011 unmodified lines62636465666728 unmodified lines96979899100101102103104105106from fastapi import FastAPI, WebSocket, WebSocketDisconnectfrom fastapi.middleware.cors import CORSMiddlewareimport uvicornimport cv2import numpy as np2 unmodified linesimport loggingimport asynciofrom concurrent.futures import ThreadPoolExecutorfrom services.single_tracker import SingleTrackerfrom services.multi_tracker import MultiTracker5 unmodified lines# Executor for CPU-bound tasksexecutor = ThreadPoolExecutor(max_workers=1)app = FastAPI(title="AFS Tracking Backend")app.add_middleware(18 unmodified lineslogger.error(f"Failed to decode image: {e}")return None@app.websocket("/ws")async def websocket_endpoint(websocket: WebSocket):await websocket.accept()logger.info("New WebSocket connection established.")11 unmodified lineslogger.info(f"Switching mode from {current_mode} to {payload['mode']}")current_mode = payload["mode"]await websocket.send_json({"type": "mode_ack", "mode": current_mode})except json.JSONDecodeError:logger.error("Invalid JSON received.")continue28 unmodified lines# Send results back to clientresponse_data["mode"] = current_modeawait websocket.send_json(response_data)except WebSocketDisconnect:logger.info("WebSocket client disconnected.")except Exception as e:logger.error(f"WebSocket error: {e}")if __name__ == "__main__":uvicorn.run("server:app", host="0.0.0.0", port=8000, reload=True)1234562 unmodified lines910111213141516175 unmodified lines23242526272829303132333435363738394041424344454618 unmodified lines656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318411 unmodified lines19619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423528 unmodified lines264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318from fastapi import FastAPI, WebSocket, WebSocketDisconnectfrom fastapi.middleware.cors import CORSMiddlewarefrom fastapi.responses import StreamingResponseimport uvicornimport cv2import numpy as np2 unmodified linesimport loggingimport asynciofrom concurrent.futures import ThreadPoolExecutorfrom datetime import datetimeimport threadingimport pyvirtualcamfrom services.single_tracker import SingleTrackerfrom services.multi_tracker import MultiTracker5 unmodified lines# Executor for CPU-bound tasksexecutor = ThreadPoolExecutor(max_workers=1)# --- OBS and Recording State ---latest_obs_frame = None # Store the latest JPEG encoded cropped frame for the OBS feed (deprecated by vcam)obs_frame_lock = threading.Lock()is_obs_active = Falsevcam = None # Virtual Camera referenceis_recording = Falsevideo_writer = Nonerecording_filename = ""# --- Center Stage State (EMA Smoothing) ---current_cx = 0.5current_cy = 0.5current_scale = 1.0# Configurable parameters for smooth panningSMOOTHING_FACTOR = 0.1 # Lower is smoother but slower (similar to Dart's TweenAnimation)TARGET_ASPECT_RATIO = 16.0 / 9.0 # Assuming output is meant to be 16:9app = FastAPI(title="AFS Tracking Backend")app.add_middleware(18 unmodified lineslogger.error(f"Failed to decode image: {e}")return Nonedef apply_center_stage_crop(frame, tracking_data):"""Applies an exponential moving average (EMA) to smoothly pan and zoomthe frame based on the tracking target bounding box.Returns the cropped frame."""global current_cx, current_cy, current_scaleh, w = frame.shape[:2]# Defaultstarget_cx = 0.5target_cy = 0.5target_scale = 1.0# Calculate target state based on tracking databoxes = tracking_data.get("boxes", [])if tracking_data.get("mode") == "multi":if "aggregate_box" in tracking_data:ab = tracking_data["aggregate_box"]box_cx = (ab["x1"] + ab["x2"]) / 2.0box_cy = (ab["y1"] + ab["y2"]) / 2.0box_w = ab["x2"] - ab["x1"]box_h = ab["y2"] - ab["y1"]target_cx = box_cx / wtarget_cy = box_cy / h# Target scale logic (from Dart): max dimension proportion * 1.5 marginmax_dim = max(box_w / w, box_h / h)target_scale = 1.0 / (max_dim * 1.5)# Clamp scaletarget_scale = max(1.0, min(target_scale, 3.0))else: # singletarget_box = Nonefor b in boxes:if b.get("is_target"):target_box = bbreakif target_box:box_cx = (target_box["x1"] + target_box["x2"]) / 2.0box_cy = (target_box["y1"] + target_box["y2"]) / 2.0box_w = target_box["x2"] - target_box["x1"]box_h = target_box["y2"] - target_box["y1"]target_cx = box_cx / wtarget_cy = box_cy / hmax_dim = max(box_w / w, box_h / h)target_scale = 1.0 / (max_dim * 2.0) # slightly tighter for single persontarget_scale = max(1.0, min(target_scale, 3.0))# Apply EMA smoothingcurrent_cx += (target_cx - current_cx) * SMOOTHING_FACTORcurrent_cy += (target_cy - current_cy) * SMOOTHING_FACTORcurrent_scale += (target_scale - current_scale) * SMOOTHING_FACTOR# Calculate crop dimensions# When scale is S, the crop width is w / Scrop_w = int(w / current_scale)crop_h = int(h / current_scale)# Enforce aspect ratio# If crop_w / crop_h is not 16:9, adjust one to matchcurrent_ar = crop_w / max(1, crop_h)if current_ar > TARGET_ASPECT_RATIO:# Too wide, shrink widthcrop_w = int(crop_h * TARGET_ASPECT_RATIO)else:# Too tall, shrink heightcrop_h = int(crop_w / TARGET_ASPECT_RATIO)# Calculate top-left point of crop, clamping to frame boundariescenter_px_x = int(current_cx * w)center_px_y = int(current_cy * h)start_x = max(0, center_px_x - crop_w // 2)start_y = max(0, center_px_y - crop_h // 2)# Adjust if crop box goes out of boundsif start_x + crop_w > w:start_x = w - crop_wif start_y + crop_h > h:start_y = h - crop_h# Cropcropped = frame[start_y:start_y+crop_h, start_x:start_x+crop_w]return croppedasync def generate_obs_stream():"""Generator for the MJPEG stream used by OBS."""global latest_obs_framewhile True:with obs_frame_lock:if latest_obs_frame is not None:yield (b'--frame\r\n'b'Content-Type: image/jpeg\r\n\r\n' + latest_obs_frame + b'\r\n')else:# If no frame yet, yield a blank frame or sleepawait asyncio.sleep(0.1)continue# Use asyncio sleep to prevent blocking the event loopawait asyncio.sleep(0.033) # roughly 30 fps@app.get("/obs_feed")async def obs_feed():"""Endpoint for OBS Media Source to connect to."""return StreamingResponse(generate_obs_stream(), media_type="multipart/x-mixed-replace; boundary=frame")@app.websocket("/ws")async def websocket_endpoint(websocket: WebSocket):global is_recording, video_writer, recording_filename, latest_obs_frame, is_obs_active, vcamawait websocket.accept()logger.info("New WebSocket connection established.")11 unmodified lineslogger.info(f"Switching mode from {current_mode} to {payload['mode']}")current_mode = payload["mode"]await websocket.send_json({"type": "mode_ack", "mode": current_mode})elif "command" in payload:# Handle recording commandscommand = payload["command"]if command == "start_recording":if not is_recording:is_recording = Truerecording_filename = f"capture_{datetime.now().strftime('%Y%m%d_%H%M%S')}.mp4"logger.info(f"Started recording to {recording_filename}")await websocket.send_json({"type": "recording_ack", "status": "started"})elif command == "stop_recording":if is_recording:is_recording = Falseif video_writer is not None:video_writer.release()video_writer = Nonelogger.info(f"Stopped recording. File saved as {recording_filename}")elif command == "start_obs":if not is_obs_active:is_obs_active = Truelogger.info("Started OBS Virtual Camera stream")try:if vcam is None:vcam = pyvirtualcam.Camera(width=1280, height=720, fps=30)except Exception as e:logger.error(f"Failed to start vcam: {e}")await websocket.send_json({"type": "obs_ack", "status": "started"})elif command == "stop_obs":if is_obs_active:is_obs_active = Falselogger.info("Stopped OBS Virtual Camera stream")if vcam is not None:vcam.close()vcam = Noneawait websocket.send_json({"type": "obs_ack", "status": "stopped"})except json.JSONDecodeError:logger.error("Invalid JSON received.")continue28 unmodified lines# Send results back to clientresponse_data["mode"] = current_modeawait websocket.send_json(response_data)# Apply Crop and Handle OBS / Recordingtry:cropped_frame = apply_center_stage_crop(frame, response_data)# 1. Update OBS Virtual Cameraif is_obs_active and vcam is not None:try:# Virtual cameras generally strict size requirementscam_frame = cv2.resize(cropped_frame, (vcam.width, vcam.height))cam_frame = cv2.cvtColor(cam_frame, cv2.COLOR_BGR2RGB)vcam.send(cam_frame)except Exception as e:logger.error(f"Failed to push vcam frame: {e}")# 2. Update Recording Outputif is_recording:h, w = cropped_frame.shape[:2]if video_writer is None:# Initialize writer with the exact dimensions of the FIRST cropped framefourcc = cv2.VideoWriter_fourcc(*'avc1')video_writer = cv2.VideoWriter(recording_filename, fourcc, 5.0, (w, h))# Ensure we try to resize cleanly if aspect ratio forces slight off-by-one errors over timeif video_writer is not None:target_w = int(video_writer.get(cv2.CAP_PROP_FRAME_WIDTH))target_h = int(video_writer.get(cv2.CAP_PROP_FRAME_HEIGHT))if (w, h) != (target_w, target_h):cropped_frame = cv2.resize(cropped_frame, (target_w, target_h))video_writer.write(cropped_frame)except Exception as e:logger.error(f"Error handling post-process crops: {e}")except WebSocketDisconnect:logger.info("WebSocket client disconnected.")except Exception as e:logger.error(f"WebSocket error: {e}")finally:# Cleanup Virtual Cameraif vcam is not None:vcam.close()vcam = Noneis_obs_active = False# Cleanup Recordingif video_writer is not None:video_writer.release()video_writer = Noneis_recording = Falseif __name__ == "__main__":uvicorn.run("server:app", host="0.0.0.0", port=8000, reload=True)
.DS_StoreAdded
server.py+212