fparodi commited on
Commit
91a8ec6
·
verified ·
1 Parent(s): 9946ae7

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +86 -66
app.py CHANGED
@@ -1,19 +1,16 @@
1
  import gradio as gr
2
  from gradio_client import Client
3
  import os
 
 
4
 
5
  BACKEND_URL = os.environ.get("BACKEND_URL", "").strip()
6
 
7
- # Create persistent client and check available endpoints
8
  try:
9
  client = Client(BACKEND_URL, headers={"ngrok-skip-browser-warning": "true"})
10
  backend_available = True
11
-
12
- # Debug: Check what endpoints are available
13
- print("Available endpoints:")
14
- for endpoint in client.endpoints:
15
- print(f" - {endpoint}")
16
-
17
  except Exception as e:
18
  client = None
19
  backend_available = False
@@ -22,56 +19,45 @@ except Exception as e:
22
  def process_media(file_obj, webcam_img, model_type, conf_thresh, max_dets, task_type):
23
  """Main processing function"""
24
  if not client:
25
- return [None] * 5
26
 
27
  try:
28
- # The main endpoint is likely at index 0 or 1
29
- # Try to find the process_media endpoint
 
 
 
 
 
 
30
  result = client.predict(
31
  file_obj,
32
- webcam_img,
33
  model_type,
34
  conf_thresh,
35
  max_dets,
36
  task_type,
37
- fn_index=1 # Usually the main function is at index 1
38
  )
 
 
 
 
 
39
  return result
 
40
  except Exception as e:
41
  print(f"Error in process_media: {e}")
42
- # Return empty updates for all outputs
43
- return [
44
- gr.update(visible=False), # display_raw_image_file
45
- gr.update(visible=False), # display_raw_video_file
46
- gr.update(visible=False), # display_raw_image_webcam
47
- gr.update(visible=False), # display_processed_image
48
- gr.update(visible=False) # display_processed_video
49
- ]
50
-
51
- def handle_file_preview(file_obj):
52
- """Handle file upload and show preview"""
53
- if file_obj is None:
54
- return gr.update(visible=False), gr.update(visible=False), gr.update(visible=True)
55
-
56
- # Check if it's an image or video
57
- if file_obj.name.lower().endswith(('.png', '.jpg', '.jpeg', '.bmp', '.webp')):
58
- return gr.update(value=file_obj.name, visible=True), gr.update(visible=False), gr.update(visible=False)
59
- elif file_obj.name.lower().endswith(('.mp4', '.avi', '.mov', '.mkv', '.webm')):
60
- return gr.update(visible=False), gr.update(value=file_obj.name, visible=True), gr.update(visible=False)
61
- else:
62
- return gr.update(visible=False), gr.update(visible=False), gr.update(visible=True)
63
 
64
  def clear_all():
65
  """Clear all inputs and outputs"""
66
- return [
67
- gr.update(value=None), # input_file
68
- gr.update(value=None), # input_webcam
69
- gr.update(visible=False), # display_raw_image_file
70
- gr.update(visible=False), # display_raw_video_file
71
- gr.update(visible=False), # display_raw_image_webcam
72
- gr.update(visible=False), # display_processed_image
73
- gr.update(visible=False) # display_processed_video
74
- ]
75
 
76
  # Build the interface
77
  with gr.Blocks(theme=gr.themes.Soft()) as demo:
@@ -87,12 +73,13 @@ with gr.Blocks(theme=gr.themes.Soft()) as demo:
87
  with gr.Tabs():
88
  with gr.TabItem("Upload File"):
89
  input_file = gr.File(label="Upload Image or Video Here", file_types=["image", "video"])
90
- display_raw_image_file = gr.Image(label="Raw Image Preview", type="filepath", visible=False)
91
  display_raw_video_file = gr.Video(label="Raw Video Preview", visible=False)
92
 
93
  with gr.TabItem("Webcam"):
94
- input_webcam = gr.Image(sources=["webcam"], type="pil", label="Click to capture")
95
- display_raw_image_webcam = gr.Image(label="Captured", type="pil", visible=False)
 
96
 
97
  clear_all_button = gr.Button("Clear All Inputs & Outputs")
98
 
@@ -101,19 +88,23 @@ with gr.Blocks(theme=gr.themes.Soft()) as demo:
101
  display_processed_image = gr.Image(label="Processed Image", type="pil", visible=False)
102
  display_processed_video = gr.Video(label="Processed Video", visible=False)
103
 
104
- # Examples
105
- gr.Examples(
106
- examples=[
107
- ["images/allocebus_000003.jpeg"],
108
- ["images/tarsius_000120.jpeg"],
109
- ["images/nasalis_proboscis-monkey.png"],
110
- ["images/macaca_000032.jpeg"],
111
- ["images/mandrillus_000011.jpeg"],
112
- ["images/pongo_000006.jpeg"]
113
- ],
114
- inputs=input_file,
115
- label="Example Images"
116
- )
 
 
 
 
117
 
118
  submit_button = gr.Button("Detect Faces", variant="primary", scale=2)
119
 
@@ -128,24 +119,54 @@ with gr.Blocks(theme=gr.themes.Soft()) as demo:
128
  conf_threshold = gr.Slider(0.05, 0.95, 0.25, step=0.05, label="Confidence Threshold")
129
  max_detections = gr.Slider(1, 10, 3, step=1, label="Max Detections")
130
 
131
- # Simple file preview
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
132
  input_file.change(
133
- handle_file_preview,
134
  inputs=[input_file],
135
  outputs=[display_raw_image_file, display_raw_video_file, input_file]
136
  )
137
 
138
- # Webcam capture
139
  input_webcam.change(
140
- lambda img: gr.update(value=img, visible=True) if img else gr.update(visible=False),
141
  inputs=[input_webcam],
142
- outputs=[display_raw_image_webcam]
143
  )
144
 
145
- # Process button
146
  submit_button.click(
147
  process_media,
148
- inputs=[input_file, display_raw_image_webcam, model_choice, conf_threshold, max_detections, task_type],
149
  outputs=[
150
  display_raw_image_file,
151
  display_raw_video_file,
@@ -155,7 +176,6 @@ with gr.Blocks(theme=gr.themes.Soft()) as demo:
155
  ]
156
  )
157
 
158
- # Clear button
159
  clear_all_button.click(
160
  clear_all,
161
  outputs=[
 
1
  import gradio as gr
2
  from gradio_client import Client
3
  import os
4
+ import tempfile
5
+ from PIL import Image
6
 
7
  BACKEND_URL = os.environ.get("BACKEND_URL", "").strip()
8
 
9
+ # Create persistent client
10
  try:
11
  client = Client(BACKEND_URL, headers={"ngrok-skip-browser-warning": "true"})
12
  backend_available = True
13
+ print(f"Connected to backend at {BACKEND_URL}")
 
 
 
 
 
14
  except Exception as e:
15
  client = None
16
  backend_available = False
 
19
  def process_media(file_obj, webcam_img, model_type, conf_thresh, max_dets, task_type):
20
  """Main processing function"""
21
  if not client:
22
+ return [gr.update()] * 5
23
 
24
  try:
25
+ # Handle webcam image - save PIL to temp file
26
+ webcam_file = None
27
+ if webcam_img is not None:
28
+ with tempfile.NamedTemporaryFile(suffix='.png', delete=False) as tmp:
29
+ webcam_img.save(tmp, 'PNG')
30
+ webcam_file = tmp.name
31
+
32
+ # Call backend - process_media is likely at index 3
33
  result = client.predict(
34
  file_obj,
35
+ webcam_file, # Pass file path instead of PIL object
36
  model_type,
37
  conf_thresh,
38
  max_dets,
39
  task_type,
40
+ fn_index=3 # process_media endpoint
41
  )
42
+
43
+ # Clean up temp file
44
+ if webcam_file and os.path.exists(webcam_file):
45
+ os.unlink(webcam_file)
46
+
47
  return result
48
+
49
  except Exception as e:
50
  print(f"Error in process_media: {e}")
51
+ return [gr.update()] * 5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
52
 
53
  def clear_all():
54
  """Clear all inputs and outputs"""
55
+ try:
56
+ # Call backend clear function at index 4
57
+ return client.predict(fn_index=4)
58
+ except:
59
+ # Fallback to local clear
60
+ return [gr.update(value=None)] * 7
 
 
 
61
 
62
  # Build the interface
63
  with gr.Blocks(theme=gr.themes.Soft()) as demo:
 
73
  with gr.Tabs():
74
  with gr.TabItem("Upload File"):
75
  input_file = gr.File(label="Upload Image or Video Here", file_types=["image", "video"])
76
+ display_raw_image_file = gr.Image(label="Raw Image Preview", type="pil", visible=False)
77
  display_raw_video_file = gr.Video(label="Raw Video Preview", visible=False)
78
 
79
  with gr.TabItem("Webcam"):
80
+ gr.Markdown("Click on feed or press Enter to capture")
81
+ input_webcam = gr.Image(sources=["webcam"], type="pil")
82
+ display_raw_image_webcam = gr.Image(label="Captured Snapshot", type="pil", visible=False)
83
 
84
  clear_all_button = gr.Button("Clear All Inputs & Outputs")
85
 
 
88
  display_processed_image = gr.Image(label="Processed Image", type="pil", visible=False)
89
  display_processed_video = gr.Video(label="Processed Video", visible=False)
90
 
91
+ # Examples with preview
92
+ example_images = [
93
+ "images/allocebus_000003.jpeg",
94
+ "images/tarsius_000120.jpeg",
95
+ "images/nasalis_proboscis-monkey.png",
96
+ "images/macaca_000032.jpeg",
97
+ "images/mandrillus_000011.jpeg",
98
+ "images/pongo_000006.jpeg"
99
+ ]
100
+
101
+ with gr.Row():
102
+ gr.Examples(
103
+ examples=[[img] for img in example_images],
104
+ inputs=input_file,
105
+ label="Example Images (Click to load)",
106
+ examples_per_page=6
107
+ )
108
 
109
  submit_button = gr.Button("Detect Faces", variant="primary", scale=2)
110
 
 
119
  conf_threshold = gr.Slider(0.05, 0.95, 0.25, step=0.05, label="Confidence Threshold")
120
  max_detections = gr.Slider(1, 10, 3, step=1, label="Max Detections")
121
 
122
+ # Event handlers
123
+ def handle_file_change(file_obj):
124
+ """Handle file upload preview locally"""
125
+ if file_obj is None:
126
+ return gr.update(visible=False), gr.update(visible=False), gr.update(visible=True)
127
+
128
+ try:
129
+ # Forward to backend for preview
130
+ result = client.predict(file_obj, fn_index=0)
131
+ return result[:3] # Return first 3 outputs for preview
132
+ except:
133
+ # Fallback local preview
134
+ if file_obj.name.lower().endswith(('.png', '.jpg', '.jpeg', '.bmp')):
135
+ return gr.update(value=file_obj.name, visible=True), gr.update(visible=False), gr.update(visible=False)
136
+ else:
137
+ return gr.update(visible=False), gr.update(visible=False), gr.update(visible=True)
138
+
139
+ def handle_webcam_change(img):
140
+ """Handle webcam capture"""
141
+ if img is None:
142
+ return gr.update(visible=False), gr.update(visible=True)
143
+ try:
144
+ # Save and forward to backend
145
+ with tempfile.NamedTemporaryFile(suffix='.png', delete=False) as tmp:
146
+ img.save(tmp, 'PNG')
147
+ result = client.predict(tmp.name, fn_index=1)
148
+ os.unlink(tmp.name)
149
+ return result[:2] # Return webcam-related outputs
150
+ except:
151
+ # Fallback
152
+ return gr.update(value=img, visible=True), gr.update(visible=False)
153
+
154
+ # Wire events
155
  input_file.change(
156
+ handle_file_change,
157
  inputs=[input_file],
158
  outputs=[display_raw_image_file, display_raw_video_file, input_file]
159
  )
160
 
 
161
  input_webcam.change(
162
+ handle_webcam_change,
163
  inputs=[input_webcam],
164
+ outputs=[display_raw_image_webcam, input_webcam]
165
  )
166
 
 
167
  submit_button.click(
168
  process_media,
169
+ inputs=[input_file, input_webcam, model_choice, conf_threshold, max_detections, task_type],
170
  outputs=[
171
  display_raw_image_file,
172
  display_raw_video_file,
 
176
  ]
177
  )
178
 
 
179
  clear_all_button.click(
180
  clear_all,
181
  outputs=[