jonathanagustin commited on
Commit
97ed94f
1 Parent(s): ec35216

document code

Browse files
Files changed (1) hide show
  1. app.py +214 -11
app.py CHANGED
@@ -1,7 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import logging
2
  import sys
3
  from enum import Enum
4
- from typing import Any, Dict, Optional
5
 
6
  import cv2
7
  import gradio as gr
@@ -17,27 +43,87 @@ model = YOLO("yolov8x.pt")
17
 
18
 
19
  class SearchFilter(Enum):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
20
  LIVE = ("EgJAAQ%3D%3D", "Live")
21
  VIDEO = ("EgIQAQ%3D%3D", "Video")
22
 
23
  def __init__(self, code, human_readable):
 
 
 
 
 
 
 
24
  self.code = code
25
  self.human_readable = human_readable
26
 
27
  def __str__(self):
 
 
 
 
 
28
  return self.human_readable
29
 
30
 
31
  class SearchService:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
32
  @staticmethod
33
  def search(query: Optional[str], filter: SearchFilter = SearchFilter.VIDEO):
 
 
 
 
 
 
 
 
 
34
  client = innertube.InnerTube("WEB", "2.20230920.00.00")
35
  response = SearchService._search(query, filter)
36
  results = SearchService.parse(response)
37
  return results
38
 
39
  @staticmethod
40
- def parse(data: Dict[str, Any]):
 
 
 
 
 
 
 
41
  results = []
42
  contents = data["contents"]["twoColumnSearchResultsRenderer"]["primaryContents"]["sectionListRenderer"]["contents"]
43
  items = contents[0]["itemSectionRenderer"]["contents"] if contents else []
@@ -54,17 +140,40 @@ class SearchService:
54
  return results
55
 
56
  @staticmethod
57
- def _search(query: Optional[str] = None, filter: SearchFilter = SearchFilter.VIDEO):
 
 
 
 
 
 
 
 
 
58
  client = innertube.InnerTube("WEB", "2.20230920.00.00")
59
  response = client.search(query=query, params=filter.code if filter else None)
60
  return response
61
 
62
  @staticmethod
63
  def get_youtube_url(video_id: str) -> str:
 
 
 
 
 
 
 
64
  return f"https://www.youtube.com/watch?v={video_id}"
65
 
66
  @staticmethod
67
- def get_stream(youtube_url):
 
 
 
 
 
 
 
68
  try:
69
  session = streamlink.Streamlink()
70
  streams = session.streams(youtube_url)
@@ -81,13 +190,40 @@ class SearchService:
81
 
82
 
83
  INITIAL_STREAMS = SearchService.search("world live cams", SearchFilter.LIVE)
 
 
 
 
 
 
84
 
 
 
85
 
86
- class LiveYouTubeObjectDetector:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
87
  def __init__(self):
 
88
  logging.getLogger().setLevel(logging.DEBUG)
89
  self.model = YOLO("yolov8x.pt")
90
- self.current_page_token = None
91
  self.streams = INITIAL_STREAMS
92
 
93
  # Gradio UI
@@ -100,7 +236,15 @@ class LiveYouTubeObjectDetector:
100
  self.submit_button = gr.Button("Detect Objects", variant="primary", size="lg")
101
  self.page_title = gr.HTML("<center><h1><b>Object Detection in Live YouTube Streams</b></h1></center>")
102
 
103
- def detect_objects(self, url):
 
 
 
 
 
 
 
 
104
  stream_url = SearchService.get_stream(url)
105
  if not stream_url:
106
  gr.Error(f"Unable to find a stream for: {stream_url}")
@@ -111,7 +255,15 @@ class LiveYouTubeObjectDetector:
111
  return self.create_black_image(), []
112
  return self.annotate(frame)
113
 
114
- def get_frame(self, stream_url):
 
 
 
 
 
 
 
 
115
  if not stream_url:
116
  return None
117
  try:
@@ -127,13 +279,33 @@ class LiveYouTubeObjectDetector:
127
  logging.warning(f"An error occurred while capturing the frame: {e}")
128
  return None
129
 
130
- def annotate(self, frame):
 
 
 
 
 
 
 
 
131
  frame_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
132
  results = self.model(frame_rgb)
133
  annotations = self.get_annotations(results)
134
  return Image.fromarray(frame_rgb), annotations
135
 
136
- def get_annotations(self, results):
 
 
 
 
 
 
 
 
 
 
 
 
137
  annotations = []
138
  for result in results:
139
  for box in result.boxes:
@@ -145,7 +317,17 @@ class LiveYouTubeObjectDetector:
145
  annotations.append((bbox_coords, class_name))
146
  return annotations
147
 
 
148
  def create_black_image():
 
 
 
 
 
 
 
 
 
149
  black_image = np.zeros((1080, 1920, 3), dtype=np.uint8)
150
  pil_black_image = Image.fromarray(black_image)
151
  cv2_black_image = cv2.cvtColor(np.array(pil_black_image), cv2.COLOR_RGB2BGR)
@@ -153,9 +335,30 @@ class LiveYouTubeObjectDetector:
153
 
154
  @staticmethod
155
  def get_live_streams(query=""):
 
 
 
 
 
 
 
 
 
 
 
156
  return SearchService.search(query if query else "world live cams", SearchFilter.LIVE)
157
 
158
  def render(self):
 
 
 
 
 
 
 
 
 
 
159
  with gr.Blocks(title="Object Detection in Live YouTube Streams", css="footer {visibility: hidden}") as app:
160
  self.page_title.render()
161
  with gr.Column():
@@ -190,7 +393,7 @@ class LiveYouTubeObjectDetector:
190
  def detect_objects_from_url(url):
191
  return self.detect_objects(url)
192
 
193
- return app.queue().launch(show_api=False, debug=True, quiet=False, share=True)
194
 
195
 
196
  if __name__ == "__main__":
 
1
+ """
2
+ This module integrates real-time object detection into live YouTube streams using the YOLO (You Only Look Once) model, and provides an interactive user interface through Gradio. It is designed to allow users to search for live YouTube streams and apply object detection to these streams in real time.
3
+
4
+ Main Features:
5
+ - Search for live YouTube streams using specific queries.
6
+ - Retrieve live stream URLs using the Streamlink library.
7
+ - Perform real-time object detection on live streams using the YOLO model.
8
+ - Display the live stream and object detection results through a Gradio interface.
9
+
10
+ The module comprises several key components:
11
+ - `SearchFilter`: An enumeration for YouTube search filters.
12
+ - `SearchService`: A service class to search for YouTube videos and retrieve live stream URLs.
13
+ - `LiveYouTubeObjectDetector`: The main class integrating the YOLO model and Gradio UI, handling the entire workflow of searching, streaming, and object detection.
14
+
15
+ Dependencies:
16
+ - cv2 (OpenCV): Used for image processing tasks.
17
+ - Gradio: Provides the interactive web-based user interface.
18
+ - innertube, streamlink: Used for interacting with YouTube and retrieving live stream data.
19
+ - numpy: Utilized for numerical operations on image data.
20
+ - PIL (Pillow): A Python Imaging Library for opening, manipulating, and saving images.
21
+ - ultralytics YOLO: The YOLO model implementation for object detection.
22
+
23
+ Usage:
24
+ 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.
25
+
26
+ """
27
  import logging
28
  import sys
29
  from enum import Enum
30
+ from typing import Any, Dict, List, Optional, Tuple
31
 
32
  import cv2
33
  import gradio as gr
 
43
 
44
 
45
  class SearchFilter(Enum):
46
+ """
47
+ An enumeration for specifying different types of YouTube search filters.
48
+
49
+ This Enum class is used to define filters for categorizing YouTube search
50
+ results into either live or regular video content. It is utilized in
51
+ conjunction with the `SearchService` class to refine YouTube searches
52
+ based on the type of content being sought.
53
+
54
+ Attributes:
55
+ LIVE (str): Represents the filter code for live video content on YouTube.
56
+ VIDEO (str): Represents the filter code for regular, non-live video content on YouTube.
57
+
58
+ Each attribute consists of a tuple where the first element is the filter code
59
+ used in YouTube search queries, and the second element is a human-readable
60
+ string describing the filter.
61
+ """
62
  LIVE = ("EgJAAQ%3D%3D", "Live")
63
  VIDEO = ("EgIQAQ%3D%3D", "Video")
64
 
65
  def __init__(self, code, human_readable):
66
+ """Initializes the SearchFilter with a code and a human-readable string.
67
+
68
+ :param code: The filter code used in YouTube search queries.
69
+ :type code: str
70
+ :param human_readable: A human-readable representation of the filter.
71
+ :type human_readable: str
72
+ """
73
  self.code = code
74
  self.human_readable = human_readable
75
 
76
  def __str__(self):
77
+ """Returns the human-readable representation of the filter.
78
+
79
+ :return: The human-readable representation of the filter.
80
+ :rtype: str
81
+ """
82
  return self.human_readable
83
 
84
 
85
  class SearchService:
86
+ """
87
+ SearchService provides functionality to search for YouTube videos using the
88
+ InnerTube API and retrieve live stream URLs using the Streamlink library.
89
+
90
+ This service allows filtering search results to either live or regular video
91
+ content and parsing the search response to extract relevant video information.
92
+ It also constructs YouTube URLs for given video IDs and retrieves the best
93
+ available stream URL for live YouTube videos.
94
+
95
+ Methods:
96
+ search: Searches YouTube for videos matching a query and filter.
97
+ parse: Parses raw search response data into a list of video details.
98
+ _search: Performs a YouTube search with the given query and filter.
99
+ get_youtube_url: Constructs a YouTube URL for a given video ID.
100
+ get_stream: Retrieves the stream URL for a given YouTube video URL.
101
+ """
102
  @staticmethod
103
  def search(query: Optional[str], filter: SearchFilter = SearchFilter.VIDEO):
104
+ """Searches YouTube for videos matching the given query and filter.
105
+
106
+ :param query: The search query.
107
+ :type query: Optional[str]
108
+ :param filter: The search filter to apply.
109
+ :type filter: SearchFilter
110
+ :return: A list of search results, each a dictionary with video details.
111
+ :rtype: List[Dict[str, Any]]
112
+ """
113
  client = innertube.InnerTube("WEB", "2.20230920.00.00")
114
  response = SearchService._search(query, filter)
115
  results = SearchService.parse(response)
116
  return results
117
 
118
  @staticmethod
119
+ def parse(data: Dict[str, Any]) -> List[Dict[str, str]]:
120
+ """Parses the raw search response data into a list of video details.
121
+
122
+ :param data: The raw search response data from YouTube.
123
+ :type data: Dict[str, Any]
124
+ :return: A list of parsed video details.
125
+ :rtype: List[Dict[str, str]]
126
+ """
127
  results = []
128
  contents = data["contents"]["twoColumnSearchResultsRenderer"]["primaryContents"]["sectionListRenderer"]["contents"]
129
  items = contents[0]["itemSectionRenderer"]["contents"] if contents else []
 
140
  return results
141
 
142
  @staticmethod
143
+ def _search(query: Optional[str] = None, filter: SearchFilter = SearchFilter.VIDEO) -> Dict[str, Any]:
144
+ """Performs a YouTube search with the given query and filter.
145
+
146
+ :param query: The search query.
147
+ :type query: Optional[str]
148
+ :param filter: The search filter to apply.
149
+ :type filter: SearchFilter
150
+ :return: The raw search response data from YouTube.
151
+ :rtype: Dict[str, Any]
152
+ """
153
  client = innertube.InnerTube("WEB", "2.20230920.00.00")
154
  response = client.search(query=query, params=filter.code if filter else None)
155
  return response
156
 
157
  @staticmethod
158
  def get_youtube_url(video_id: str) -> str:
159
+ """Constructs a YouTube URL for the given video ID.
160
+
161
+ :param video_id: The ID of the YouTube video.
162
+ :type video_id: str
163
+ :return: The YouTube URL for the video.
164
+ :rtype: str
165
+ """
166
  return f"https://www.youtube.com/watch?v={video_id}"
167
 
168
  @staticmethod
169
+ def get_stream(youtube_url: str) -> Optional[str]:
170
+ """Retrieves the stream URL for a given YouTube video URL.
171
+
172
+ :param youtube_url: The URL of the YouTube video.
173
+ :type youtube_url: str
174
+ :return: The stream URL if available, otherwise None.
175
+ :rtype: Optional[str]
176
+ """
177
  try:
178
  session = streamlink.Streamlink()
179
  streams = session.streams(youtube_url)
 
190
 
191
 
192
  INITIAL_STREAMS = SearchService.search("world live cams", SearchFilter.LIVE)
193
+ class LiveYouTubeObjectDetector:
194
+ """
195
+ LiveYouTubeObjectDetector is a class that integrates object detection into live YouTube streams.
196
+ It uses the YOLO (You Only Look Once) model to detect objects in video frames captured from live streams.
197
+ The class also provides a Gradio interface for users to interact with the object detection system,
198
+ allowing them to search for live streams, view them, and detect objects in real-time.
199
 
200
+ The class handles the retrieval of live stream URLs, frame capture from the streams, object detection
201
+ on the frames, and updating the Gradio interface with the results.
202
 
203
+ Attributes:
204
+ model (YOLO): The YOLO model used for object detection.
205
+ streams (list): A list of dictionaries containing information about the current live streams.
206
+ gallery (gr.Gallery): A Gradio gallery widget to display live stream thumbnails.
207
+ search_input (gr.Textbox): A Gradio textbox for inputting search queries.
208
+ stream_input (gr.Textbox): A Gradio textbox for inputting a specific live stream URL.
209
+ annotated_image (gr.AnnotatedImage): A Gradio annotated image widget to display detection results.
210
+ search_button (gr.Button): A Gradio button to initiate a new search for live streams.
211
+ submit_button (gr.Button): A Gradio button to start object detection on a specified live stream.
212
+ page_title (gr.HTML): A Gradio HTML widget to display the page title.
213
+
214
+ Methods:
215
+ detect_objects: Detects objects in a live YouTube stream given its URL.
216
+ get_frame: Captures a frame from a live stream URL.
217
+ annotate: Annotates a frame with detected objects.
218
+ get_annotations: Converts YOLO detection results into annotations for Gradio.
219
+ create_black_image: Creates a black placeholder image.
220
+ get_live_streams: Searches for live streams based on a query.
221
+ render: Sets up and launches the Gradio interface.
222
+ """
223
  def __init__(self):
224
+ """Initializes the LiveYouTubeObjectDetector with YOLO model and UI components."""
225
  logging.getLogger().setLevel(logging.DEBUG)
226
  self.model = YOLO("yolov8x.pt")
 
227
  self.streams = INITIAL_STREAMS
228
 
229
  # Gradio UI
 
236
  self.submit_button = gr.Button("Detect Objects", variant="primary", size="lg")
237
  self.page_title = gr.HTML("<center><h1><b>Object Detection in Live YouTube Streams</b></h1></center>")
238
 
239
+ def detect_objects(self, url: str) -> Tuple[Image.Image, List[Tuple[Tuple[int, int, int, int], str]]]:
240
+ """
241
+ Detects objects in the given live YouTube stream URL.
242
+
243
+ :param url: The URL of the live YouTube video.
244
+ :type url: str
245
+ :return: A tuple containing the annotated image and a list of annotations.
246
+ :rtype: Tuple[Image.Image, List[Tuple[Tuple[int, int, int, int], str]]]
247
+ """
248
  stream_url = SearchService.get_stream(url)
249
  if not stream_url:
250
  gr.Error(f"Unable to find a stream for: {stream_url}")
 
255
  return self.create_black_image(), []
256
  return self.annotate(frame)
257
 
258
+ def get_frame(self, stream_url: str) -> Optional[np.ndarray]:
259
+ """
260
+ Captures a frame from the given live stream URL.
261
+
262
+ :param stream_url: The URL of the live stream.
263
+ :type stream_url: str
264
+ :return: The captured frame as a numpy array, or None if capture fails.
265
+ :rtype: Optional[np.ndarray]
266
+ """
267
  if not stream_url:
268
  return None
269
  try:
 
279
  logging.warning(f"An error occurred while capturing the frame: {e}")
280
  return None
281
 
282
+ def annotate(self, frame: np.ndarray) -> Tuple[Image.Image, List[Tuple[Tuple[int, int, int, int], str]]]:
283
+ """
284
+ Annotates the given frame with detected objects.
285
+
286
+ :param frame: The frame to be annotated.
287
+ :type frame: np.ndarray
288
+ :return: A tuple of the annotated PIL image and list of annotations.
289
+ :rtype: Tuple[Image.Image, List[Tuple[Tuple[int, int, int, int], str]]]
290
+ """
291
  frame_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
292
  results = self.model(frame_rgb)
293
  annotations = self.get_annotations(results)
294
  return Image.fromarray(frame_rgb), annotations
295
 
296
+ def get_annotations(self, results) -> List[Tuple[Tuple[int, int, int, int], str]]:
297
+ """
298
+ Converts YOLO detection results into annotations suitable for Gradio visualization.
299
+
300
+ This method processes the results from the YOLO object detection model, extracting
301
+ the bounding box coordinates and class names for each detected object.
302
+
303
+ :param results: The detection results from the YOLO model.
304
+ :type results: List[DetectionResult]
305
+ :return: A list of tuples, each containing the bounding box (as a tuple of integers)
306
+ and the class name of the detected object.
307
+ :rtype: List[Tuple[Tuple[int, int, int, int], str]]
308
+ """
309
  annotations = []
310
  for result in results:
311
  for box in result.boxes:
 
317
  annotations.append((bbox_coords, class_name))
318
  return annotations
319
 
320
+ @staticmethod
321
  def create_black_image():
322
+ """
323
+ Creates a black image of fixed dimensions.
324
+
325
+ This method generates a black image that can be used as a placeholder or background.
326
+ It is particularly useful in cases where no valid frame is available for processing.
327
+
328
+ :return: A black image as a numpy array.
329
+ :rtype: np.ndarray
330
+ """
331
  black_image = np.zeros((1080, 1920, 3), dtype=np.uint8)
332
  pil_black_image = Image.fromarray(black_image)
333
  cv2_black_image = cv2.cvtColor(np.array(pil_black_image), cv2.COLOR_RGB2BGR)
 
335
 
336
  @staticmethod
337
  def get_live_streams(query=""):
338
+ """
339
+ Searches for live streams on YouTube based on the given query.
340
+
341
+ This method utilizes the SearchService to find live YouTube streams. If no query is
342
+ provided, it defaults to searching for 'world live cams'.
343
+
344
+ :param query: The search query for live streams, defaults to an empty string.
345
+ :type query: str, optional
346
+ :return: A list of dictionaries containing information about each live stream.
347
+ :rtype: List[Dict[str, str]]
348
+ """
349
  return SearchService.search(query if query else "world live cams", SearchFilter.LIVE)
350
 
351
  def render(self):
352
+ """
353
+ Sets up and launches the Gradio interface for the application.
354
+
355
+ This method creates the Gradio UI elements and defines the behavior of the application.
356
+ It includes the setup of interactive widgets like galleries, textboxes, and buttons,
357
+ and defines the actions triggered by user interactions with these widgets.
358
+
359
+ The Gradio interface allows users to search for live YouTube streams, select a stream,
360
+ and run object detection on the selected live stream.
361
+ """
362
  with gr.Blocks(title="Object Detection in Live YouTube Streams", css="footer {visibility: hidden}") as app:
363
  self.page_title.render()
364
  with gr.Column():
 
393
  def detect_objects_from_url(url):
394
  return self.detect_objects(url)
395
 
396
+ return app.queue().launch(show_api=False)
397
 
398
 
399
  if __name__ == "__main__":