wxcyn commited on
Commit
72dd4d9
·
verified ·
1 Parent(s): 59e70c5

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +43 -84
app.py CHANGED
@@ -116,102 +116,62 @@
116
  # interface = create_interface()
117
  # interface.launch()
118
 
119
-
120
  import gradio as gr
121
- from pathlib import Path
122
  import os
 
 
123
  from dotenv import load_dotenv
124
- import time
125
- import requests
126
- import traceback
127
 
128
  # Load environment variables
129
  load_dotenv()
130
 
131
- # Get Hugging Face token from environment
132
- HF_TOKEN = os.getenv("HF_TOKEN")
 
 
 
 
 
 
 
 
133
 
134
  def process_video(video_file, question, password, progress=gr.Progress()):
 
135
  try:
136
  if video_file is None:
137
  return "Error: No video file uploaded.", None
138
-
139
- if not password:
140
- return "Error: Password is required.", None
141
-
142
- progress(0.2, desc="Preparing request...")
143
-
144
- # Configure the API endpoint
145
- SPACE_NAME = "wxcyn-video-analysis" # Replace with your space name
146
- api_url = f"https://{SPACE_NAME}.hf.space/run/predict"
147
-
148
- headers = {
149
- 'Authorization': f'Bearer {HF_TOKEN}'
150
- }
151
 
152
- # Prepare the multipart form data exactly as your private space expects it
153
- files = {
154
- 'video_file': ('video.mp4', open(video_file.name, 'rb'), 'video/mp4')
155
- }
156
 
157
- data = {
158
- 'question': question,
159
- 'password': password
160
- }
161
-
162
- progress(0.4, desc="Sending to analysis server...")
163
-
164
- response = requests.post(
165
- api_url,
166
- headers=headers,
167
- files=files,
168
- data=data
169
  )
170
 
171
- progress(0.8, desc="Processing response...")
172
-
173
- if response.status_code == 200:
174
- try:
175
- result = response.json()
176
- if isinstance(result, dict) and 'data' in result:
177
- # Handle the standard Gradio API response format
178
- analysis_text = result['data'][0]
179
- video_clip = result['data'][1] if len(result['data']) > 1 else None
180
- else:
181
- # Handle direct response format
182
- analysis_text = result[0] if isinstance(result, list) else str(result)
183
- video_clip = result[1] if isinstance(result, list) and len(result) > 1 else None
184
- return analysis_text, video_clip
185
- except Exception as e:
186
- print(f"Error parsing response: {str(e)}")
187
- print(f"Response content: {response.text}")
188
- return "Error: Invalid response format from server.", None
189
  else:
190
- error_message = f"Error: Failed to process video. Status code: {response.status_code}"
191
- try:
192
- error_detail = response.json()
193
- error_message += f"\nDetails: {error_detail}"
194
- except:
195
- error_message += f"\nResponse: {response.text}"
196
- print(error_message)
197
- return error_message, None
198
-
199
  except Exception as e:
200
- print(f"Error processing video: {traceback.format_exc()}")
201
- return f"An error occurred: {str(e)}", None
202
- finally:
203
- # Make sure to close any opened files
204
- try:
205
- files['video_file'][1].close()
206
- except:
207
- pass
208
 
209
  def create_interface():
210
- with gr.Blocks(title="Video Analysis Interface") as interface:
 
211
  gr.Markdown("# Video Content Analysis (1 file under 2.5 minutes)")
212
 
213
  with gr.Row():
214
  with gr.Column(scale=2):
 
215
  password = gr.Textbox(
216
  label="Password",
217
  type="password",
@@ -219,7 +179,7 @@ def create_interface():
219
  interactive=True
220
  )
221
  video_file = gr.File(
222
- label="Upload Video File (up to 30MB)",
223
  file_types=['video'],
224
  interactive=True
225
  )
@@ -231,6 +191,7 @@ def create_interface():
231
  submit_btn = gr.Button("Analyze Video", variant="primary")
232
 
233
  with gr.Column(scale=3):
 
234
  output_text = gr.Textbox(
235
  label="Analysis Result",
236
  lines=15,
@@ -241,6 +202,7 @@ def create_interface():
241
  interactive=False
242
  )
243
 
 
244
  submit_btn.click(
245
  fn=process_video,
246
  inputs=[video_file, question, password],
@@ -249,19 +211,16 @@ def create_interface():
249
 
250
  return interface
251
 
252
- # Entry point
253
  if __name__ == "__main__":
254
- if not HF_TOKEN:
255
- raise ValueError("HF_TOKEN environment variable is not set")
256
-
257
  Path('data').mkdir(exist_ok=True)
258
  Path('temp').mkdir(exist_ok=True)
259
 
 
260
  interface = create_interface()
261
- interface.launch(server_name="0.0.0.0", server_port=7860)
262
- else:
263
- # For Hugging Face Spaces deployment
264
- Path('data').mkdir(exist_ok=True)
265
- Path('temp').mkdir(exist_ok=True)
266
- interface = create_interface()
267
- interface.launch(server_name="0.0.0.0", server_port=7860)
 
116
  # interface = create_interface()
117
  # interface.launch()
118
 
 
119
  import gradio as gr
 
120
  import os
121
+ from pathlib import Path
122
+ from gradio_client import Client
123
  from dotenv import load_dotenv
 
 
 
124
 
125
  # Load environment variables
126
  load_dotenv()
127
 
128
+ def create_client():
129
+ """Create a client connection to the private space"""
130
+ hf_token = os.getenv("HF_TOKEN")
131
+ if not hf_token:
132
+ raise ValueError("HF_TOKEN environment variable not set")
133
+
134
+ return Client(
135
+ "wxcyn/video-analysis",
136
+ hf_token=hf_token
137
+ )
138
 
139
  def process_video(video_file, question, password, progress=gr.Progress()):
140
+ """Process video by calling the private space API"""
141
  try:
142
  if video_file is None:
143
  return "Error: No video file uploaded.", None
 
 
 
 
 
 
 
 
 
 
 
 
 
144
 
145
+ progress(0.2, desc="Connecting to video analysis service...")
146
+ client = create_client()
 
 
147
 
148
+ progress(0.4, desc="Uploading and processing video...")
149
+ result = client.predict(
150
+ video_file.name, # video_file path
151
+ question, # question
152
+ password, # password
153
+ api_name="/process_video"
 
 
 
 
 
 
154
  )
155
 
156
+ # Unpack results
157
+ if isinstance(result, tuple) and len(result) == 2:
158
+ analysis_text, video_clip = result
159
+ return analysis_text, video_clip
 
 
 
 
 
 
 
 
 
 
 
 
 
 
160
  else:
161
+ return str(result), None
162
+
 
 
 
 
 
 
 
163
  except Exception as e:
164
+ print(f"Error processing video: {e}")
165
+ return f"Error processing video: {str(e)}", None
 
 
 
 
 
 
166
 
167
  def create_interface():
168
+ """Create the Gradio interface"""
169
+ with gr.Blocks(title="Public Video Analysis Interface") as interface:
170
  gr.Markdown("# Video Content Analysis (1 file under 2.5 minutes)")
171
 
172
  with gr.Row():
173
  with gr.Column(scale=2):
174
+ # Input components
175
  password = gr.Textbox(
176
  label="Password",
177
  type="password",
 
179
  interactive=True
180
  )
181
  video_file = gr.File(
182
+ label="Upload Video File(up to 30MB)",
183
  file_types=['video'],
184
  interactive=True
185
  )
 
191
  submit_btn = gr.Button("Analyze Video", variant="primary")
192
 
193
  with gr.Column(scale=3):
194
+ # Output components
195
  output_text = gr.Textbox(
196
  label="Analysis Result",
197
  lines=15,
 
202
  interactive=False
203
  )
204
 
205
+ # Connect components
206
  submit_btn.click(
207
  fn=process_video,
208
  inputs=[video_file, question, password],
 
211
 
212
  return interface
213
 
 
214
  if __name__ == "__main__":
215
+ # Create required directories
 
 
216
  Path('data').mkdir(exist_ok=True)
217
  Path('temp').mkdir(exist_ok=True)
218
 
219
+ # Create and launch interface
220
  interface = create_interface()
221
+ interface.launch(
222
+ server_name="0.0.0.0",
223
+ server_port=7860,
224
+ share=True,
225
+ show_error=True # Enable verbose error reporting
226
+ )