hfjv commited on
Commit
3304e07
·
verified ·
1 Parent(s): 2b41723

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +115 -6
app.py CHANGED
@@ -36,7 +36,7 @@ def process_image_with_yolov8(model_name, image=None, url=None):
36
  model = load_yolov8_model(model_name)
37
  if model is None:
38
  return None
39
-
40
  if url:
41
  try:
42
  response = requests.get(url)
@@ -45,7 +45,7 @@ def process_image_with_yolov8(model_name, image=None, url=None):
45
  except Exception as e:
46
  print(f"Error loading image from URL: {e}")
47
  return None
48
-
49
  try:
50
  image = np.array(image)
51
  output_image = detect_objects(image, model)
@@ -54,6 +54,75 @@ def process_image_with_yolov8(model_name, image=None, url=None):
54
  print(f"Error processing image: {e}")
55
  return None
56
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
57
  def handle_input_selection(model_name, choice, image, url):
58
  if choice == "Upload":
59
  return process_image_with_yolov8(model_name, image=image), None
@@ -62,6 +131,26 @@ def handle_input_selection(model_name, choice, image, url):
62
  else:
63
  return None, "Please select a valid input method"
64
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
65
  def toggle_inputs(choice):
66
  if choice == "Upload":
67
  return gr.update(visible=True), gr.update(visible=False)
@@ -70,12 +159,20 @@ def toggle_inputs(choice):
70
  else:
71
  return gr.update(visible=False), gr.update(visible=False)
72
 
 
 
 
 
 
 
 
 
73
  # Create Gradio Interface
74
  with gr.Blocks() as demo:
75
  gr.Markdown("## YOLOv8 Object Detection on Images and Videos")
76
-
77
  model_choice = gr.Radio(["yolov8s.pt", "yolov8m.pt"], label="Select Model")
78
-
79
  with gr.Tabs() as tabs:
80
  with gr.TabItem("Image Detection"):
81
  input_choice = gr.Radio(["Upload", "URL"], label="Select Input Method")
@@ -88,7 +185,19 @@ with gr.Blocks() as demo:
88
  output_image = gr.Image(type="numpy", label="Processed Image")
89
  process_button_image = gr.Button("Process Image")
90
  process_button_image.click(handle_input_selection, [model_choice, input_choice, input_image, input_url], [output_image, gr.State()])
 
 
 
 
 
 
 
 
 
 
 
 
91
 
92
- gr.Markdown("Upload an image or provide an image URL to perform object detection using YOLOv8 model.")
93
-
94
  demo.launch()
 
36
  model = load_yolov8_model(model_name)
37
  if model is None:
38
  return None
39
+
40
  if url:
41
  try:
42
  response = requests.get(url)
 
45
  except Exception as e:
46
  print(f"Error loading image from URL: {e}")
47
  return None
48
+
49
  try:
50
  image = np.array(image)
51
  output_image = detect_objects(image, model)
 
54
  print(f"Error processing image: {e}")
55
  return None
56
 
57
+ def download_image(url, save_path):
58
+ try:
59
+ response = requests.get(url)
60
+ response.raise_for_status()
61
+ with Image.open(BytesIO(response.content)) as image:
62
+ image.save(save_path)
63
+ print(f"Image saved to {save_path}")
64
+ except requests.exceptions.RequestException as e:
65
+ print(f"Failed to retrieve image. Error: {e}")
66
+
67
+ def download_base64_image(base64_data, save_path):
68
+ try:
69
+ header, encoded = base64_data.split(',', 1)
70
+ data = base64.b64decode(encoded)
71
+ with Image.open(BytesIO(data)) as image:
72
+ image.save(save_path)
73
+ print(f"Image saved to {save_path}")
74
+ except Exception as e:
75
+ print(f"Failed to decode base64 image. Error: {e}")
76
+
77
+ def download_video(url, save_path):
78
+ try:
79
+ yt = YouTube(url)
80
+ stream = yt.streams.get_highest_resolution()
81
+ stream.download(output_path=save_path)
82
+ print(f"Video saved to {os.path.join(save_path, stream.default_filename)}")
83
+ except Exception as e:
84
+ print(f"Failed to retrieve video. Error: {e}")
85
+
86
+ def download_youtube_video(youtube_url):
87
+ try:
88
+ yt = YouTube(youtube_url)
89
+ stream = yt.streams.filter(file_extension='mp4', res="720p").first()
90
+ if not stream:
91
+ stream = yt.streams.filter(file_extension='mp4').first()
92
+ output_path = os.path.join(tempfile.gettempdir(), "downloaded_video.mp4")
93
+ stream.download(output_path=os.path.dirname(output_path), filename=os.path.basename(output_path))
94
+ return output_path
95
+ except Exception as e:
96
+ print(f"Failed to retrieve video from YouTube. Error: {e}")
97
+ return None
98
+
99
+ def process_video(input_video_path, output_video_path, model):
100
+ cap = cv2.VideoCapture(input_video_path)
101
+ if not cap.isOpened():
102
+ print(f"Error: Cannot open video file {input_video_path}")
103
+ return None
104
+
105
+ frame_width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
106
+ frame_height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
107
+ fps = cap.get(cv2.CAP_PROP_FPS)
108
+ fourcc = cv2.VideoWriter_fourcc(*'mp4v')
109
+
110
+ out = cv2.VideoWriter(output_video_path, fourcc, fps, (frame_width, frame_height))
111
+
112
+ while True:
113
+ ret, frame = cap.read()
114
+ if not ret:
115
+ break
116
+
117
+ processed_frame = detect_objects(frame, model)
118
+ if processed_frame is not None:
119
+ out.write(processed_frame)
120
+
121
+ cap.release()
122
+ out.release()
123
+
124
+ return output_video_path
125
+
126
  def handle_input_selection(model_name, choice, image, url):
127
  if choice == "Upload":
128
  return process_image_with_yolov8(model_name, image=image), None
 
131
  else:
132
  return None, "Please select a valid input method"
133
 
134
+ def process_input(model_name, video_choice, local_video=None, video_url=None):
135
+ model = load_yolov8_model(model_name)
136
+ if model is None:
137
+ return "Error loading model."
138
+
139
+ output_path = os.path.join(tempfile.gettempdir(), "processed_video.mp4")
140
+
141
+ if video_choice == "Upload":
142
+ input_path = local_video
143
+ elif video_choice == "YouTube":
144
+ input_path = download_youtube_video(video_url)
145
+ else:
146
+ return "Please provide a video file or YouTube URL."
147
+
148
+ if input_path is None:
149
+ return "Error downloading video."
150
+
151
+ result = process_video(input_path, output_path, model)
152
+ return result
153
+
154
  def toggle_inputs(choice):
155
  if choice == "Upload":
156
  return gr.update(visible=True), gr.update(visible=False)
 
159
  else:
160
  return gr.update(visible=False), gr.update(visible=False)
161
 
162
+ def toggle_video_inputs(choice):
163
+ if choice == "Upload":
164
+ return gr.update(visible=True), gr.update(visible=False)
165
+ elif choice == "YouTube":
166
+ return gr.update(visible=False), gr.update(visible=True)
167
+ else:
168
+ return gr.update(visible=False), gr.update(visible=False)
169
+
170
  # Create Gradio Interface
171
  with gr.Blocks() as demo:
172
  gr.Markdown("## YOLOv8 Object Detection on Images and Videos")
173
+
174
  model_choice = gr.Radio(["yolov8s.pt", "yolov8m.pt"], label="Select Model")
175
+
176
  with gr.Tabs() as tabs:
177
  with gr.TabItem("Image Detection"):
178
  input_choice = gr.Radio(["Upload", "URL"], label="Select Input Method")
 
185
  output_image = gr.Image(type="numpy", label="Processed Image")
186
  process_button_image = gr.Button("Process Image")
187
  process_button_image.click(handle_input_selection, [model_choice, input_choice, input_image, input_url], [output_image, gr.State()])
188
+
189
+ with gr.TabItem("Video Detection"):
190
+ video_choice = gr.Radio(["Upload", "YouTube"], label="Select Input Method")
191
+ with gr.Row():
192
+ with gr.Column(visible=False) as upload_section:
193
+ local_video = gr.Video(label="Upload Local Video")
194
+ with gr.Column(visible=False) as url_section:
195
+ video_url = gr.Textbox(label="YouTube Video URL")
196
+ video_choice.change(toggle_video_inputs, video_choice, [upload_section, url_section])
197
+ output_video = gr.Video(label="Processed Video")
198
+ process_button_video = gr.Button("Process Video")
199
+ process_button_video.click(process_input, [model_choice, video_choice, local_video, video_url], output_video)
200
 
201
+ gr.Markdown("Upload an image, provide an image URL, or provide a YouTube video URL to perform object detection using YOLOv8 model.")
202
+
203
  demo.launch()