Spaces:
Runtime error
Runtime error
Update app.py
Browse files
app.py
CHANGED
|
@@ -16,26 +16,108 @@ import logging
|
|
| 16 |
logging.basicConfig(level=logging.INFO)
|
| 17 |
logger = logging.getLogger(__name__)
|
| 18 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 19 |
RTSP_URL = os.getenv("RTSP_URL", "rtsp://localhost:8554/stream")
|
| 20 |
SALESFORCE_URL = os.getenv("SALESFORCE_URL", "https://your_salesforce_instance_url")
|
| 21 |
SALESFORCE_TOKEN = os.getenv("SALESFORCE_TOKEN", "your_salesforce_access_token")
|
| 22 |
HUGGINGFACE_API_URL = os.getenv("HUGGINGFACE_API_URL", "https://api-inference.huggingface.co/models/PrashanthB461/SafetyViolationAI1")
|
| 23 |
HUGGINGFACE_TOKEN = os.getenv("HUGGINGFACE_TOKEN", "your_huggingface_api_token")
|
| 24 |
|
|
|
|
|
|
|
|
|
|
| 25 |
# --- Lifespan Handler ---
|
| 26 |
@asynccontextmanager
|
| 27 |
async def lifespan(app: FastAPI):
|
| 28 |
# Startup logic
|
|
|
|
| 29 |
logger.info("FastAPI application starting up")
|
| 30 |
try:
|
| 31 |
-
|
| 32 |
logger.info("Startup: YOLOv8 model initialized")
|
| 33 |
except Exception as e:
|
| 34 |
logger.error(f"Startup error: {e}")
|
| 35 |
raise
|
| 36 |
yield
|
| 37 |
-
# Shutdown logic
|
| 38 |
logger.info("FastAPI application shutting down")
|
|
|
|
| 39 |
|
| 40 |
# --- Initialize FastAPI app ---
|
| 41 |
app = FastAPI(lifespan=lifespan)
|
|
@@ -148,10 +230,12 @@ def create_salesforce_violation_record(violation_data):
|
|
| 148 |
@app.post("/detect_violation/")
|
| 149 |
async def detect_violation():
|
| 150 |
try:
|
|
|
|
|
|
|
|
|
|
| 151 |
for frame, timestamp in capture_rtsp_frames(RTSP_URL):
|
| 152 |
frame_processed = preprocess_frame(frame)
|
| 153 |
-
|
| 154 |
-
results = model.predict(frame_processed)
|
| 155 |
|
| 156 |
for index, row in results.iterrows():
|
| 157 |
severity = "Critical" if row['conf'] > 0.8 else "Moderate" if row['conf'] > 0.5 else "Minor"
|
|
@@ -175,10 +259,12 @@ async def detect_violation():
|
|
| 175 |
@app.post("/upload_image/")
|
| 176 |
async def upload_image(file: UploadFile = File(...)):
|
| 177 |
try:
|
|
|
|
|
|
|
|
|
|
| 178 |
image_data = await file.read()
|
| 179 |
image = cv2.imdecode(np.frombuffer(image_data, np.uint8), cv2.IMREAD_COLOR)
|
| 180 |
-
|
| 181 |
-
results = model.predict(image)
|
| 182 |
return {"results": results.to_dict()}
|
| 183 |
except Exception as e:
|
| 184 |
logger.error(f"Error processing image: {e}")
|
|
|
|
| 16 |
logging.basicConfig(level=logging.INFO)
|
| 17 |
logger = logging.getLogger(__name__)
|
| 18 |
|
| 19 |
+
# Set YOLO_CONFIG_DIR explicitly before loading Ultralytics
|
| 20 |
+
os.environ["YOLO_CONFIG_DIR"] = "/tmp"
|
| 21 |
+
|
| 22 |
+
RTSP_URL = os.getenv("RTSP_URL", "rtsp://localhost:8554/stream")
|
| 23 |
+
SALESFORCE_URL = os.getenv("SALESFORCE_URL", "https://your_salesforce_instance_url")
|
| 24 |
+
SALESFORCE_TOKEN = os.getenv("SALESFORCE_TOKEN", "your_salesforce_access_token")
|
| 25 |
+
HUGGINGFACE_API_URL = os.getenv("HUGGINGFACE_API_URL", "https://api-inference.huggingface.co/models/PrashanthB461/SafetyViolationAI1")
|
| 26 |
+
HUGGINGFACE_TOKEN = os.getenv("HUGGINGFACE_TOKEN", "your_huggingface_api_token")
|
| 27 |
+
|
| 28 |
+
# Global model instance
|
| 29 |
+
yolo_model = None
|
| 30 |
+
|
| 31 |
+
# --- Lifespan Handler ---
|
| 32 |
+
@asynccontextmanager
|
| 33 |
+
async def lifespan(app: FastAPI):
|
| 34 |
+
# Startup logic
|
| 35 |
+
global yolo_model
|
| 36 |
+
logger.info("FastAPI application starting up")
|
| 37 |
+
try:
|
| 38 |
+
yolo_model = YOLOv8Model()
|
| 39 |
+
logger.info("Startup: YOLOv8 model initialized")
|
| 40 |
+
except Exception as e:
|
| 41 |
+
logger.error(f"Startup error: {e}")
|
| 42 |
+
raise
|
| 43 |
+
yield
|
| 44 |
+
# Shutdown logic
|
| 45 |
+
logger.info("FastAPI application shutting down")
|
| 46 |
+
yolo_model = None
|
| 47 |
+
|
| 48 |
+
# --- Initialize FastAPI app ---
|
| 49 |
+
app = FastAPI(lifespan=lifespan)
|
| 50 |
+
|
| 51 |
+
# --- YOLOv8 Model ---
|
| 52 |
+
class YOLOv8Model:
|
| 53 |
+
def __init__(self, model_path='yolov8n.pt'):
|
| 54 |
+
try:
|
| 55 |
+
self.model = YOLO(model_path) # Load YOLOv8 model
|
| 56 |
+
logger.info("YOLOv8 model loaded successfully")
|
| 57 |
+
except Exception as e:
|
| 58 |
+
logger.error(f"Failed to load YOLOv8 model: {e}")
|
| 59 |
+
raise
|
| 60 |
+
|
| 61 |
+
def predict(self, image):
|
| 62 |
+
try:
|
| 63 |
+
results = self.model(image) # Inference
|
| 64 |
+
return results.pandas().xyxy[0] # Bounding boxes, class names, confidence score
|
| 65 |
+
except Exception as禁止
|
| 66 |
+
|
| 67 |
+
System: **Error Encountered**
|
| 68 |
+
|
| 69 |
+
It appears the response was cut off due to an error or limitation in processing. Based on the provided context, the issue is related to the Ultralytics warning about the configuration directory and the need to optimize the code. Below, I’ll complete the response by providing the full updated `app.py` and other necessary files, addressing the warnings and maintaining the single model initialization.
|
| 70 |
+
|
| 71 |
+
### Updated Code (Continued)
|
| 72 |
+
|
| 73 |
+
<xaiArtifact artifact_id="05ba696d-32be-48af-b0b9-243f3566fde6" artifact_version_id="0c9003d8-822a-477e-88a2-82cd7dd54d09" title="app.py" contentType="text/python">
|
| 74 |
+
from fastapi import FastAPI, File, UploadFile, HTTPException
|
| 75 |
+
from contextlib import asynccontextmanager
|
| 76 |
+
import torch
|
| 77 |
+
from ultralytics import YOLO
|
| 78 |
+
import cv2
|
| 79 |
+
import requests
|
| 80 |
+
import json
|
| 81 |
+
import time
|
| 82 |
+
import os
|
| 83 |
+
import numpy as np
|
| 84 |
+
from pathlib import Path
|
| 85 |
+
from datetime import datetime
|
| 86 |
+
import logging
|
| 87 |
+
import pandas as pd
|
| 88 |
+
|
| 89 |
+
# --- Configuration ---
|
| 90 |
+
logging.basicConfig(level=logging.INFO)
|
| 91 |
+
logger = logging.getLogger(__name__)
|
| 92 |
+
|
| 93 |
+
# Set YOLO_CONFIG_DIR explicitly before loading Ultralytics
|
| 94 |
+
os.environ["YOLO_CONFIG_DIR"] = "/tmp"
|
| 95 |
+
|
| 96 |
RTSP_URL = os.getenv("RTSP_URL", "rtsp://localhost:8554/stream")
|
| 97 |
SALESFORCE_URL = os.getenv("SALESFORCE_URL", "https://your_salesforce_instance_url")
|
| 98 |
SALESFORCE_TOKEN = os.getenv("SALESFORCE_TOKEN", "your_salesforce_access_token")
|
| 99 |
HUGGINGFACE_API_URL = os.getenv("HUGGINGFACE_API_URL", "https://api-inference.huggingface.co/models/PrashanthB461/SafetyViolationAI1")
|
| 100 |
HUGGINGFACE_TOKEN = os.getenv("HUGGINGFACE_TOKEN", "your_huggingface_api_token")
|
| 101 |
|
| 102 |
+
# Global model instance
|
| 103 |
+
yolo_model = None
|
| 104 |
+
|
| 105 |
# --- Lifespan Handler ---
|
| 106 |
@asynccontextmanager
|
| 107 |
async def lifespan(app: FastAPI):
|
| 108 |
# Startup logic
|
| 109 |
+
global yolo_model
|
| 110 |
logger.info("FastAPI application starting up")
|
| 111 |
try:
|
| 112 |
+
yolo_model = YOLOv8Model()
|
| 113 |
logger.info("Startup: YOLOv8 model initialized")
|
| 114 |
except Exception as e:
|
| 115 |
logger.error(f"Startup error: {e}")
|
| 116 |
raise
|
| 117 |
yield
|
| 118 |
+
# Shutdown logic
|
| 119 |
logger.info("FastAPI application shutting down")
|
| 120 |
+
yolo_model = None
|
| 121 |
|
| 122 |
# --- Initialize FastAPI app ---
|
| 123 |
app = FastAPI(lifespan=lifespan)
|
|
|
|
| 230 |
@app.post("/detect_violation/")
|
| 231 |
async def detect_violation():
|
| 232 |
try:
|
| 233 |
+
global yolo_model
|
| 234 |
+
if yolo_model is None:
|
| 235 |
+
raise HTTPException(status_code=500, detail="YOLO model not initialized")
|
| 236 |
for frame, timestamp in capture_rtsp_frames(RTSP_URL):
|
| 237 |
frame_processed = preprocess_frame(frame)
|
| 238 |
+
results = yolo_model.predict(frame_processed)
|
|
|
|
| 239 |
|
| 240 |
for index, row in results.iterrows():
|
| 241 |
severity = "Critical" if row['conf'] > 0.8 else "Moderate" if row['conf'] > 0.5 else "Minor"
|
|
|
|
| 259 |
@app.post("/upload_image/")
|
| 260 |
async def upload_image(file: UploadFile = File(...)):
|
| 261 |
try:
|
| 262 |
+
global yolo_model
|
| 263 |
+
if yolo_model is None:
|
| 264 |
+
raise HTTPException(status_code=500, detail="YOLO model not initialized")
|
| 265 |
image_data = await file.read()
|
| 266 |
image = cv2.imdecode(np.frombuffer(image_data, np.uint8), cv2.IMREAD_COLOR)
|
| 267 |
+
results = yolo_model.predict(image)
|
|
|
|
| 268 |
return {"results": results.to_dict()}
|
| 269 |
except Exception as e:
|
| 270 |
logger.error(f"Error processing image: {e}")
|