Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,14 +1,24 @@
|
|
| 1 |
from fastapi import FastAPI
|
| 2 |
from fastapi.responses import StreamingResponse
|
|
|
|
|
|
|
|
|
|
| 3 |
import cv2
|
| 4 |
|
| 5 |
app = FastAPI()
|
| 6 |
|
| 7 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 8 |
video_source = 0 # Change to "video.mp4" for a file
|
| 9 |
cap = cv2.VideoCapture(video_source)
|
| 10 |
|
| 11 |
def generate_frames():
|
|
|
|
| 12 |
while True:
|
| 13 |
success, frame = cap.read()
|
| 14 |
if not success:
|
|
@@ -18,10 +28,10 @@ def generate_frames():
|
|
| 18 |
b"Content-Type: image/jpeg\r\n\r\n" +
|
| 19 |
buffer.tobytes() + b"\r\n")
|
| 20 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 21 |
@app.get("/video")
|
| 22 |
async def video_feed():
|
| 23 |
return StreamingResponse(generate_frames(), media_type="multipart/x-mixed-replace; boundary=frame")
|
| 24 |
-
|
| 25 |
-
@app.get("/")
|
| 26 |
-
def index():
|
| 27 |
-
return {"message": "Video Streaming with FastAPI"}
|
|
|
|
| 1 |
from fastapi import FastAPI
|
| 2 |
from fastapi.responses import StreamingResponse
|
| 3 |
+
from fastapi.staticfiles import StaticFiles
|
| 4 |
+
from fastapi.templating import Jinja2Templates
|
| 5 |
+
from starlette.requests import Request
|
| 6 |
import cv2
|
| 7 |
|
| 8 |
app = FastAPI()
|
| 9 |
|
| 10 |
+
# Serve static files (for HTML & JS)
|
| 11 |
+
app.mount("/static", StaticFiles(directory="static"), name="static")
|
| 12 |
+
|
| 13 |
+
# Jinja2 template rendering
|
| 14 |
+
templates = Jinja2Templates(directory="templates")
|
| 15 |
+
|
| 16 |
+
# Open webcam (or use a file)
|
| 17 |
video_source = 0 # Change to "video.mp4" for a file
|
| 18 |
cap = cv2.VideoCapture(video_source)
|
| 19 |
|
| 20 |
def generate_frames():
|
| 21 |
+
"""Stream video frames as MJPEG."""
|
| 22 |
while True:
|
| 23 |
success, frame = cap.read()
|
| 24 |
if not success:
|
|
|
|
| 28 |
b"Content-Type: image/jpeg\r\n\r\n" +
|
| 29 |
buffer.tobytes() + b"\r\n")
|
| 30 |
|
| 31 |
+
@app.get("/")
|
| 32 |
+
async def homepage(request: Request):
|
| 33 |
+
return templates.TemplateResponse("index.html", {"request": request})
|
| 34 |
+
|
| 35 |
@app.get("/video")
|
| 36 |
async def video_feed():
|
| 37 |
return StreamingResponse(generate_frames(), media_type="multipart/x-mixed-replace; boundary=frame")
|
|
|
|
|
|
|
|
|
|
|
|