fparodi commited on
Commit
342ff64
·
verified ·
1 Parent(s): 719b0c2

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +20 -173
app.py CHANGED
@@ -1,184 +1,31 @@
1
  import gradio as gr
2
- from gradio_client import Client
3
  import os
4
- import requests
5
- from datetime import datetime
6
- import time
7
 
8
- # Configuration
9
  BACKEND_URL = os.environ.get("BACKEND_URL", "").strip()
10
- CHECK_INTERVAL = 60 # Check backend status every 60 seconds
11
 
12
- class BackendConnection:
13
- def __init__(self):
14
- self.client = None
15
- self.last_check = 0
16
- self.is_connected = False
17
- self.error_message = ""
18
-
19
- def check_backend(self):
20
- """Check if backend is accessible"""
21
- current_time = time.time()
22
-
23
- # Only check every CHECK_INTERVAL seconds
24
- if current_time - self.last_check < CHECK_INTERVAL and self.client:
25
- return self.is_connected
26
-
27
- self.last_check = current_time
28
-
29
- if not BACKEND_URL:
30
- self.error_message = "Backend URL not configured. Please set the BACKEND_URL secret."
31
- self.is_connected = False
32
- return False
33
-
34
- try:
35
- # Try to connect to the backend
36
- response = requests.get(f"{BACKEND_URL}/health", timeout=5)
37
- if response.status_code == 200:
38
- # Try to create client
39
- self.client = Client(BACKEND_URL)
40
- self.is_connected = True
41
- self.error_message = ""
42
- return True
43
- except Exception as e:
44
- self.error_message = f"Cannot connect to GPU server: {str(e)}"
45
- self.is_connected = False
46
- self.client = None
47
-
48
- return False
49
-
50
- # Global connection manager
51
- backend = BackendConnection()
52
-
53
- def process_with_backend(file_obj, webcam_img, model_type, conf_thresh, max_dets, task_type):
54
- """Forward request to backend"""
55
- if not backend.check_backend():
56
- return (
57
- gr.update(visible=False), # raw_img_file
58
- gr.update(visible=False), # raw_vid_file
59
- gr.update(visible=False), # raw_img_webcam
60
- gr.update(value=None, visible=True), # processed_img
61
- gr.update(visible=False), # processed_vid
62
- f"❌ GPU Server Offline: {backend.error_message}"
63
- )
64
-
65
- try:
66
- # Forward to backend
67
- result = backend.client.predict(
68
- file_obj,
69
- webcam_img,
70
- model_type,
71
- conf_thresh,
72
- max_dets,
73
- task_type,
74
- api_name="/predict"
75
- )
76
- return result
77
- except Exception as e:
78
- return (
79
- gr.update(visible=False),
80
- gr.update(visible=False),
81
- gr.update(visible=False),
82
- gr.update(value=None, visible=True),
83
- gr.update(visible=False),
84
- f"❌ Processing Error: {str(e)}"
85
- )
86
-
87
- # Create the interface
88
  with gr.Blocks(theme=gr.themes.Soft(), title="PrimateFace Demo") as demo:
89
- # Header with status
90
- with gr.Row():
91
- gr.Markdown("# 🐵 PrimateFace Detection, Pose Estimation, and Gaze Demo")
92
- status_indicator = gr.Markdown("🟡 Checking GPU server status...", elem_id="status")
93
-
94
- gr.Markdown("""
95
- This demo showcases state-of-the-art primate face analysis including detection,
96
- 68-point facial landmarks, and gaze estimation across multiple primate species.
97
- """)
98
-
99
- # Check initial status
100
- if backend.check_backend():
101
- status_indicator.value = "🟢 GPU Server: Online"
102
-
103
- # Load the actual interface from backend
104
- try:
105
- # Get the interface configuration from backend
106
- with gr.Row():
107
- with gr.Column(scale=1):
108
- # Input section
109
- with gr.Tabs():
110
- with gr.TabItem("Upload File"):
111
- input_file = gr.File(label="Upload Image or Video", file_types=["image", "video"])
112
- display_raw_image_file = gr.Image(label="Preview", visible=False)
113
- display_raw_video_file = gr.Video(label="Preview", visible=False)
114
-
115
- with gr.TabItem("Webcam"):
116
- gr.Markdown("Click on the feed or press Enter to capture")
117
- input_webcam = gr.Image(sources=["webcam"], type="pil")
118
- display_raw_image_webcam = gr.Image(label="Captured", visible=False)
119
-
120
- clear_button = gr.Button("Clear All")
121
-
122
- with gr.Column(scale=1):
123
- # Output section
124
- gr.Markdown("### Processed Output")
125
- display_processed_image = gr.Image(label="Result", visible=False)
126
- display_processed_video = gr.Video(label="Result", visible=False)
127
- error_message = gr.Markdown(visible=False)
128
-
129
- # Controls
130
- submit_button = gr.Button("🚀 Detect Faces", variant="primary", size="lg")
131
-
132
- with gr.Accordion("Advanced Settings", open=False):
133
- model_choice = gr.Radio(
134
- choices=["MMDetection"],
135
- value="MMDetection",
136
- label="Model",
137
- visible=False
138
- )
139
- task_type = gr.Dropdown(
140
- choices=["Face Detection", "Face Pose Estimation", "Gaze Estimation [experimental]"],
141
- value="Face Detection",
142
- label="Task"
143
- )
144
- conf_threshold = gr.Slider(0.05, 0.95, 0.25, step=0.05, label="Confidence Threshold")
145
- max_detections = gr.Slider(1, 10, 3, step=1, label="Max Detections")
146
-
147
- # Wire up the interface
148
- submit_button.click(
149
- process_with_backend,
150
- inputs=[input_file, input_webcam, model_choice, conf_threshold, max_detections, task_type],
151
- outputs=[display_raw_image_file, display_raw_video_file, display_raw_image_webcam,
152
- display_processed_image, display_processed_video, error_message]
153
- )
154
-
155
- except Exception as e:
156
- gr.Markdown(f"❌ Failed to load interface: {str(e)}")
157
-
158
  else:
159
- status_indicator.value = "🔴 GPU Server: Offline"
160
- gr.Markdown(f"""
161
- ### 🔴 GPU Server is Currently Offline
162
-
163
- {backend.error_message}
164
 
165
- The demo requires a GPU server for processing. Please check back later.
166
 
167
- **Note:** The server may be temporarily unavailable for maintenance.
 
168
  """)
169
-
170
- # Add info section regardless of status
171
- gr.Markdown("""
172
- ---
173
- ### Technical Details
174
- - **Detection**: MMDetection (Cascade R-CNN R101-FPN)
175
- - **Pose**: MMPose (HRNet-W18) with 68 facial landmarks
176
- - **Gaze**: Gazelle (DINOv2-based) experimental gaze estimation
177
- - **GPU**: NVIDIA GPU with CUDA support
178
-
179
- ### About
180
- Created by Felipe Parodi | [Project GitHub](https://github.com/KordingLab/PrimateFace) | [Personal](https://github.com/felipe-parodi)
181
- """)
182
 
183
- if __name__ == "__main__":
184
- demo.launch()
 
1
  import gradio as gr
 
2
  import os
 
 
 
3
 
 
4
  BACKEND_URL = os.environ.get("BACKEND_URL", "").strip()
 
5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6
  with gr.Blocks(theme=gr.themes.Soft(), title="PrimateFace Demo") as demo:
7
+ if BACKEND_URL:
8
+ gr.HTML(f'''
9
+ <div style="padding: 20px;">
10
+ <h1 style="text-align: center;">🐵 PrimateFace Detection, Pose & Gaze Demo</h1>
11
+ <p style="text-align: center; color: green;">✅ GPU Server Connected</p>
12
+ </div>
13
+ <iframe
14
+ src="{BACKEND_URL}"
15
+ width="100%"
16
+ height="1000px"
17
+ frameborder="0"
18
+ style="border: 1px solid #ccc; border-radius: 8px;">
19
+ </iframe>
20
+ ''')
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
21
  else:
22
+ gr.Markdown("""
23
+ # 🐵 PrimateFace Demo
 
 
 
24
 
25
+ ### 🔴 Configuration Error
26
 
27
+ The BACKEND_URL environment variable is not set.
28
+ Please configure it in the Space settings under "Repository secrets".
29
  """)
 
 
 
 
 
 
 
 
 
 
 
 
 
30
 
31
+ demo.launch()