Skip to content

Commit

Permalink
feat: 동영상을 통한 스트리밍 기능 추가
Browse files Browse the repository at this point in the history
  • Loading branch information
sukkyun2 committed Aug 28, 2024
1 parent 5ca1396 commit c178dba
Showing 1 changed file with 42 additions and 3 deletions.
45 changes: 42 additions & 3 deletions app/main.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
import asyncio
import io
import os
import tempfile
from io import BytesIO
from typing import Optional

Expand All @@ -8,15 +11,14 @@
from fastapi import FastAPI, WebSocket, WebSocketDisconnect
from fastapi import UploadFile, File
from fastapi.middleware.cors import CORSMiddleware
from fastapi.params import Query
from fastapi.params import Query, Form

from app.api_response import ApiResponse, ApiListResponse
from app.config import settings
from app.connection_manager import ConnectionManager
from app.history import async_save_history
from model.detect import detect, estimate_distance, DetectionResult, area_intrusion
from model.detect import detect
from model.operations import OperationType, define_operation
from model.video_recorder import VideoRecorder

app = FastAPI()

Expand Down Expand Up @@ -49,6 +51,43 @@ def exists_publisher() -> ApiListResponse[str]:
return ApiListResponse[str].ok_with_data(list(manager.publishers.keys()))


@app.post("/api/detect-video")
async def detect_video(file: UploadFile = File(...),
location_name: str = Form(...),
op: Optional[OperationType] = Form(...)):
file_content = await file.read()

with tempfile.NamedTemporaryFile(delete=False, suffix='.mp4') as temp_file:
temp_file.write(file_content)
temp_file_path = temp_file.name

cap = cv2.VideoCapture(temp_file_path)

if not cap.isOpened():
os.remove(temp_file_path)
return ApiResponse.bad_request("Error opening video file")

async def process_video():
while True:
ret, img = cap.read()
if not ret:
break

operation = define_operation(op)
pattern_detected, result = operation(img)
if pattern_detected:
await async_save_history(result, location_name)

await manager.broadcast(location_name, result.get_encoded_nparr().tobytes())

cap.release()
os.remove(temp_file_path)

asyncio.create_task(process_video())

return ApiResponse.ok()


@app.websocket("/ws/publishers/{location_name}")
async def websocket_publisher(websocket: WebSocket,
location_name: str,
Expand Down

0 comments on commit c178dba

Please sign in to comment.