File size: 1,149 Bytes
43384f2
 
b6ff8ba
 
 
43384f2
 
 
 
b6ff8ba
 
 
 
 
 
 
c8d788b
43384f2
 
 
b6ff8ba
43384f2
 
 
 
 
 
 
 
 
b6ff8ba
 
 
 
43384f2
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
from fastapi import FastAPI
from fastapi.responses import StreamingResponse
from fastapi.staticfiles import StaticFiles
from fastapi.templating import Jinja2Templates
from starlette.requests import Request
import cv2

app = FastAPI()

# Serve static files (for HTML & JS)
app.mount("/static", StaticFiles(directory="static"), name="static")

# Jinja2 template rendering
templates = Jinja2Templates(directory="templates")

# Open webcam (or use a file)
video_source = 1  # Change to "video.mp4" for a file
cap = cv2.VideoCapture(video_source)

def generate_frames():
    """Stream video frames as MJPEG."""
    while True:
        success, frame = cap.read()
        if not success:
            break
        _, buffer = cv2.imencode(".jpg", frame)
        yield (b"--frame\r\n"
               b"Content-Type: image/jpeg\r\n\r\n" +
               buffer.tobytes() + b"\r\n")

@app.get("/")
async def homepage(request: Request):
    return templates.TemplateResponse("index.html", {"request": request})

@app.get("/video")
async def video_feed():
    return StreamingResponse(generate_frames(), media_type="multipart/x-mixed-replace; boundary=frame")