""" This module integrates real-time object detection into live YouTube streams using the YOLO model and provides an interactive user interface through Gradio. It allows users to search for live YouTube streams and apply object detection to these streams in real time. Main Features: - Search for live YouTube streams using specific queries. - Retrieve live stream URLs using the `pytube` library. - Perform real-time object detection on live streams using the YOLO model. - Display the live stream and object detection results through a Gradio interface. Dependencies: - cv2 (OpenCV): Used for image processing tasks. - Gradio: Provides the interactive web-based user interface. - `pytube`: Used for retrieving live stream URLs from YouTube. - innertube: Used for interacting with YouTube's internal API. - numpy: Utilized for numerical operations on image data. - PIL (Pillow): A Python Imaging Library for opening, manipulating, and saving images. - ultralytics YOLO: The YOLO model implementation for object detection. Usage: Run this file to launch the Gradio interface, which allows users to input search queries for YouTube live streams, select a stream, and perform object detection on the selected live stream. """ import logging import sys from enum import Enum from typing import Any, Dict, List, Optional, Tuple import cv2 import gradio as gr import innertube import numpy as np from PIL import Image from ultralytics import YOLO # Import pytube from pytube import YouTube # Set up logging logging.basicConfig(stream=sys.stderr, level=logging.DEBUG) class SearchFilter(Enum): LIVE = ("EgJAAQ%3D%3D", "Live") VIDEO = ("EgIQAQ%3D%3D", "Video") def __init__(self, code, human_readable): self.code = code self.human_readable = human_readable def __str__(self): return self.human_readable class SearchService: @staticmethod def search(query: Optional[str], filter: SearchFilter = SearchFilter.VIDEO): response = SearchService._search(query, filter) results = SearchService.parse(response) return results @staticmethod def parse(data: Dict[str, Any]) -> List[Dict[str, str]]: results = [] try: contents = data["contents"]["twoColumnSearchResultsRenderer"]["primaryContents"]["sectionListRenderer"]["contents"] for content in contents: items = content.get("itemSectionRenderer", {}).get("contents", []) for item in items: if "videoRenderer" in item: renderer = item["videoRenderer"] video_id = renderer.get("videoId", "") thumbnails = renderer.get("thumbnail", {}).get("thumbnails", []) thumbnail_url = thumbnails[-1]["url"] if thumbnails else "" title_runs = renderer.get("title", {}).get("runs", []) title = "".join(run.get("text", "") for run in title_runs) results.append( { "video_id": video_id, "thumbnail_url": thumbnail_url, "title": title, } ) except Exception as e: logging.error(f"Error parsing search results: {e}") return results @staticmethod def _search(query: Optional[str] = None, filter: SearchFilter = SearchFilter.VIDEO) -> Dict[str, Any]: client = innertube.InnerTube(client_name="WEB", client_version="2.20230920.00.00") response = client.search(query=query, params=filter.code if filter else None) return response @staticmethod def get_youtube_url(video_id: str) -> str: return f"https://www.youtube.com/watch?v={video_id}" @staticmethod def get_stream(youtube_url: str) -> Optional[str]: """Retrieves the live stream URL for a given YouTube video URL using pytube. :param youtube_url: The URL of the YouTube video. :type youtube_url: str :return: The HLS manifest URL if available, otherwise None. :rtype: Optional[str] """ try: yt = YouTube(youtube_url) if yt.is_live: streaming_data = yt.player_response.get('streamingData', {}) hls_manifest_url = streaming_data.get('hlsManifestUrl') if hls_manifest_url: logging.debug(f"Found HLS manifest URL for live stream: {hls_manifest_url}") return hls_manifest_url else: logging.warning(f"HLS manifest URL not found for live stream: {youtube_url}") return None else: logging.warning(f"Video is not a live stream: {youtube_url}") return None except Exception as e: logging.warning(f"An error occurred while getting stream: {e}") return None INITIAL_STREAMS = SearchService.search("world live cams", SearchFilter.LIVE) class LiveYouTubeObjectDetector: def __init__(self): logging.getLogger().setLevel(logging.DEBUG) self.model = YOLO("yolo11n.pt") self.streams = INITIAL_STREAMS # Gradio UI initial_gallery_items = [(stream["thumbnail_url"], stream["title"]) for stream in self.streams] self.gallery = gr.Gallery(label="Live YouTube Videos", value=initial_gallery_items, show_label=True, columns=[4], rows=[5], object_fit="contain", height="auto", allow_preview=False) self.search_input = gr.Textbox(label="Search Live YouTube Videos") self.stream_input = gr.Textbox(label="URL of Live YouTube Video") self.annotated_image = gr.AnnotatedImage(show_label=False) self.search_button = gr.Button("Search", size="lg") self.submit_button = gr.Button("Detect Objects", variant="primary", size="lg") self.page_title = gr.HTML("