Spaces:
Sleeping
Sleeping
File size: 13,192 Bytes
9b1cbb7 |
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 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 |
import os
import cv2
import tempfile
import requests
import base64
import numpy as np
import logging
from dataclasses import dataclass
from typing import Optional, Union, Tuple
from PIL import Image
from io import BytesIO
from ultralytics import YOLO
import streamlit as st
import yt_dlp as youtube_dl
from config import Config
# Configure logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
@dataclass
class DetectionResult:
"""Data class to store detection results"""
success: bool
image: Optional[np.ndarray] = None
error_message: Optional[str] = None
@st.cache_resource
def load_yolo_model(model_name: str) -> YOLO:
"""Load YOLO model with caching"""
try:
if model_name not in Config.AVAILABLE_MODELS:
raise ValueError(f"Invalid model name: {model_name}")
return YOLO(model_name)
except Exception as e:
logger.error(f"Error loading model: {e}")
raise RuntimeError(f"Failed to load model: {str(e)}")
class YOLOModel:
"""Class to handle YOLO model operations"""
def __init__(self, model_name: str = Config.DEFAULT_MODEL):
if not Config.validate_config():
raise RuntimeError("Invalid configuration")
self.model = load_yolo_model(model_name)
def detect_objects(self, image: np.ndarray) -> DetectionResult:
"""Perform object detection on the input image"""
if self.model is None:
return DetectionResult(False, error_message="Model not loaded")
try:
results = self.model(image)
annotated_image = image.copy()
for result in results[0].boxes:
x1, y1, x2, y2 = map(int, result.xyxy[0])
label = self.model.names[int(result.cls)]
confidence = result.conf.item()
if confidence < Config.CONFIDENCE_THRESHOLD:
continue
cv2.rectangle(
annotated_image,
(x1, y1),
(x2, y2),
Config.BBOX_COLOR,
2
)
label_text = f'{label} {confidence:.2f}'
cv2.putText(
annotated_image,
label_text,
(x1, y1 - 10),
cv2.FONT_HERSHEY_SIMPLEX,
Config.FONT_SCALE,
Config.BBOX_COLOR,
Config.FONT_THICKNESS
)
return DetectionResult(True, annotated_image)
except Exception as e:
logger.error(f"Error during object detection: {e}")
return DetectionResult(False, error_message=str(e))
class ImageProcessor:
"""Class to handle image processing operations"""
def __init__(self, model: YOLOModel):
self.model = model
def process_image(self, image: Union[Image.Image, str]) -> DetectionResult:
"""Process image from various sources (PIL Image or URL)"""
try:
if isinstance(image, str):
image = self._load_image_from_url(image)
if image is None:
return DetectionResult(False, error_message="Failed to load image")
# Convert image to RGB if it has an alpha channel
if image.mode == 'RGBA':
image = image.convert('RGB')
np_image = np.array(image)
return self.model.detect_objects(np_image)
except Exception as e:
logger.error(f"Error processing image: {e}")
return DetectionResult(False, error_message=str(e))
def _load_image_from_url(self, url: str) -> Optional[Image.Image]:
"""Load image from URL with support for base64"""
try:
if url.startswith('data:image'):
header, encoded = url.split(',', 1)
image_data = base64.b64decode(encoded)
return Image.open(BytesIO(image_data))
else:
response = requests.get(url)
response.raise_for_status()
return Image.open(BytesIO(response.content))
except Exception as e:
logger.error(f"Error loading image from URL: {e}")
return None
class VideoProcessor:
"""Class to handle video processing operations"""
def __init__(self, model: YOLOModel):
self.model = model
os.makedirs(Config.TEMP_DIR, exist_ok=True)
def process_video(self, input_path: str) -> Tuple[bool, Optional[str]]:
"""Process video file and return path to processed video"""
cap = None
writer = None
progress_bar = st.progress(0)
status_text = st.empty()
try:
cap = cv2.VideoCapture(input_path)
if not cap.isOpened():
return False, "Cannot open video file"
total_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
if total_frames <= 0:
return False, "Invalid video file"
output_path = os.path.join(Config.TEMP_DIR, "processed_video.mp4")
writer = self._setup_video_writer(cap, output_path)
frame_count = 0
while True:
ret, frame = cap.read()
if not ret:
break
frame_count += 1
progress = min(100, int(frame_count * 100 / total_frames))
progress_bar.progress(progress)
status_text.text(f"Processing frame {frame_count}/{total_frames}")
result = self.model.detect_objects(frame)
if result.success:
writer.write(result.image)
return True, output_path
except Exception as e:
logger.error(f"Error processing video: {e}")
return False, str(e)
finally:
if cap is not None:
cap.release()
if writer is not None:
writer.release()
progress_bar.empty()
status_text.empty()
def _setup_video_writer(self, cap: cv2.VideoCapture, output_path: str) -> cv2.VideoWriter:
"""Set up video writer with input video properties"""
width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
fps = cap.get(cv2.CAP_PROP_FPS)
fourcc = cv2.VideoWriter_fourcc(*Config.VIDEO_OUTPUT_FORMAT)
return cv2.VideoWriter(output_path, fourcc, fps, (width, height))
def download_youtube_video(youtube_url: str) -> Optional[str]:
"""Download YouTube video and return path to downloaded file"""
try:
temp_dir = tempfile.gettempdir()
output_path = os.path.join(temp_dir, 'downloaded_video.mp4')
ydl_opts = {
'format': 'best',
'outtmpl': output_path
}
with youtube_dl.YoutubeDL(ydl_opts) as ydl:
ydl.download([youtube_url])
return output_path
except Exception as e:
logger.error(f"Failed to retrieve video from YouTube: {e}")
return None
def cleanup_temp_files():
"""Clean up temporary files"""
try:
for file in os.listdir(Config.TEMP_DIR):
file_path = os.path.join(Config.TEMP_DIR, file)
try:
if os.path.isfile(file_path):
os.unlink(file_path)
except Exception as e:
logger.error(f"Error deleting {file_path}: {e}")
except Exception as e:
logger.error(f"Error cleaning up temp directory: {e}")
def validate_image(image: Image.Image) -> Tuple[bool, str]:
"""Validate image format and properties"""
try:
# Check image mode
if image.mode not in ['RGB', 'RGBA']:
return False, f"Unsupported image mode: {image.mode}"
# Check image size
max_dimension = 1920
width, height = image.size
if width > max_dimension or height > max_dimension:
return False, f"Image too large. Maximum dimension: {max_dimension}px"
# Check if image is valid
image.verify()
return True, "Image is valid"
except Exception as e:
return False, str(e)
def main():
"""Main application function"""
st.title("MULTIMEDIA OBJECT DETECTION USING YOLO")
# Model selection with description
st.subheader("Model Selection")
model_choice = st.selectbox(
"Select YOLO Model",
options=Config.AVAILABLE_MODELS,
index=Config.AVAILABLE_MODELS.index(Config.DEFAULT_MODEL),
format_func=lambda x: f"{x} - {Config.YOLO_MODELS[x]}"
)
# Initialize model using session state
if 'model' not in st.session_state or st.session_state.get('model_choice') != model_choice:
try:
st.session_state.model = YOLOModel(model_choice)
st.session_state.model_choice = model_choice
except Exception as e:
st.error(f"Error loading model: {str(e)}")
return
model = st.session_state.model
image_processor = ImageProcessor(model)
video_processor = VideoProcessor(model)
# Display model capabilities
model_type = "Detection"
if "pose" in model_choice:
model_type = "Pose Estimation"
st.info("This model will detect and estimate human poses in the image/video.")
elif "seg" in model_choice:
model_type = "Instance Segmentation"
st.info("This model will perform instance segmentation, creating precise masks for detected objects.")
else:
st.info("This model will detect and classify objects with bounding boxes.")
tabs = st.tabs(["Image Detection", "Video Detection"])
with tabs[0]:
st.header("Image Detection")
input_choice = st.radio("Select Input Method", ["Upload", "URL"])
if input_choice == "Upload":
uploaded_image = st.file_uploader(
"Upload Image",
type=Config.ALLOWED_IMAGE_TYPES
)
if uploaded_image is not None:
image = Image.open(uploaded_image)
result = image_processor.process_image(image)
if result.success:
st.image(result.image, caption="Processed Image", use_container_width=True)
else:
st.error(result.error_message)
elif input_choice == "URL":
image_url = st.text_input("Image URL")
if image_url:
result = image_processor.process_image(image_url)
if result.success:
st.image(result.image, caption="Processed Image", use_container_width=True)
else:
st.error(result.error_message)
with tabs[1]:
st.header("Video Detection")
video_choice = st.radio("Select Input Method", ["Upload", "YouTube"])
if video_choice == "Upload":
try:
uploaded_video = st.file_uploader(
"Upload Local Video",
type=Config.ALLOWED_VIDEO_TYPES
)
if uploaded_video is not None:
if uploaded_video.size > 200 * 1024 * 1024: # 200MB limit
st.error("Video file is too large. Please upload a file smaller than 200MB.")
return
input_video_path = os.path.join(Config.TEMP_DIR, uploaded_video.name)
with open(input_video_path, "wb") as f:
f.write(uploaded_video.read())
try:
success, result = video_processor.process_video(input_video_path)
if success:
st.video(result)
else:
st.error(f"Error processing video: {result}")
finally:
cleanup_temp_files()
except Exception as e:
st.error(f"An error occurred: {str(e)}")
elif video_choice == "YouTube":
video_url = st.text_input("YouTube Video URL")
if video_url:
with st.spinner("Downloading video..."):
input_video_path = download_youtube_video(video_url)
if input_video_path:
try:
success, result = video_processor.process_video(input_video_path)
if success:
st.video(result)
else:
st.error(result)
finally:
cleanup_temp_files()
else:
st.error("Failed to download YouTube video")
if __name__ == "__main__":
main() |