PrashanthB461 commited on
Commit
b69e47e
·
verified ·
1 Parent(s): 5a78d5c

Create Integ.py

Browse files
Files changed (1) hide show
  1. Integ.py +63 -0
Integ.py ADDED
@@ -0,0 +1,63 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import torch
3
+ import cv2
4
+ from fastapi import FastAPI, File, UploadFile
5
+ from ultralytics import YOLO
6
+ import io
7
+ from pydantic import BaseModel
8
+ import json
9
+
10
+ # Initialize the Hugging Face app
11
+ app = FastAPI()
12
+
13
+ # Load YOLO model
14
+ model = YOLO('yolov8s.pt') # Replace with your custom model if needed
15
+
16
+ class Violation(BaseModel):
17
+ frame: int
18
+ violation: str
19
+ confidence: float
20
+ timestamp: str
21
+
22
+ # Inference endpoint to process video
23
+ @app.post("/process_video/")
24
+ async def process_video(file: UploadFile = File(...)):
25
+ # Read video file from user upload
26
+ video_data = await file.read()
27
+ video_path = f"temp_{file.filename}"
28
+ with open(video_path, "wb") as f:
29
+ f.write(video_data)
30
+
31
+ # Process the video using YOLO model
32
+ results = process_video_with_yolo(video_path)
33
+
34
+ # Clean up
35
+ os.remove(video_path)
36
+
37
+ return {"violations": results}
38
+
39
+ # Function to process video with YOLO model
40
+ def process_video_with_yolo(video_path):
41
+ video = cv2.VideoCapture(video_path)
42
+ violations = []
43
+ frame_count = 0
44
+
45
+ while True:
46
+ ret, frame = video.read()
47
+ if not ret:
48
+ break
49
+ # Run inference on the frame
50
+ results = model(frame)
51
+ for result in results:
52
+ for box in result.boxes:
53
+ violation = {
54
+ "frame": frame_count,
55
+ "violation": "no_helmet", # Example violation (this can be dynamic based on the class)
56
+ "confidence": float(box.conf),
57
+ "timestamp": str(frame_count / 30) # Timestamp (frame rate assumption)
58
+ }
59
+ violations.append(violation)
60
+ frame_count += 1
61
+
62
+ video.release()
63
+ return violations