foleymon commited on
Commit
129dbb0
·
verified ·
1 Parent(s): c50894d

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +404 -94
app.py CHANGED
@@ -1,34 +1,223 @@
1
  import os
 
2
  import gradio as gr
3
  import requests
4
  import inspect
5
  import pandas as pd
 
 
 
6
 
7
  # (Keep Constants as is)
8
  # --- Constants ---
9
  DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
10
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
11
  # --- Basic Agent Definition ---
12
  # ----- THIS IS WERE YOU CAN BUILD WHAT YOU WANT ------
13
  class BasicAgent:
14
  def __init__(self):
 
 
 
 
 
 
 
 
 
15
  print("BasicAgent initialized.")
 
16
  def __call__(self, question: str) -> str:
17
  print(f"Agent received question (first 50 chars): {question[:50]}...")
18
- fixed_answer = "This is a default answer."
19
- print(f"Agent returning fixed answer: {fixed_answer}")
20
- return fixed_answer
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
21
 
22
- def run_and_submit_all( profile: gr.OAuthProfile | None):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
23
  """
24
  Fetches all questions, runs the BasicAgent on them, submits all answers,
25
  and displays the results.
26
- """
27
  # --- Determine HF Space Runtime URL and Repo URL ---
28
- space_id = os.getenv("SPACE_ID") # Get the SPACE_ID for sending link to the code
29
 
30
  if profile:
31
- username= f"{profile.username}"
32
  print(f"User logged in: {username}")
33
  else:
34
  print("User not logged in.")
@@ -41,10 +230,11 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
41
  # 1. Instantiate Agent ( modify this part to create your agent)
42
  try:
43
  agent = BasicAgent()
44
- except Exception as e:
45
  print(f"Error instantiating agent: {e}")
46
  return f"Error initializing agent: {e}", None
47
- # In the case of an app running as a hugging Face space, this link points toward your codebase ( usefull for others so please keep it public)
 
48
  agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
49
  print(agent_code)
50
 
@@ -55,19 +245,54 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
55
  response.raise_for_status()
56
  questions_data = response.json()
57
  if not questions_data:
58
- print("Fetched questions list is empty.")
59
- return "Fetched questions list is empty or invalid format.", None
60
  print(f"Fetched {len(questions_data)} questions.")
61
- except requests.exceptions.RequestException as e:
62
  print(f"Error fetching questions: {e}")
63
  return f"Error fetching questions: {e}", None
64
- except requests.exceptions.JSONDecodeError as e:
65
- print(f"Error decoding JSON response from questions endpoint: {e}")
66
- print(f"Response text: {response.text[:500]}")
67
- return f"Error decoding server response for questions: {e}", None
68
- except Exception as e:
69
- print(f"An unexpected error occurred fetching questions: {e}")
70
- return f"An unexpected error occurred fetching questions: {e}", None
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
71
 
72
  # 3. Run your Agent
73
  results_log = []
@@ -80,117 +305,202 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
80
  print(f"Skipping item with missing task_id or question: {item}")
81
  continue
82
  try:
83
- submitted_answer = agent(question_text)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
84
  answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
85
  results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
86
  except Exception as e:
87
- print(f"Error running agent on task {task_id}: {e}")
88
- results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"})
89
 
90
  if not answers_payload:
91
  print("Agent did not produce any answers to submit.")
92
  return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
93
 
94
- # 4. Prepare Submission
95
- submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
96
- status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..."
97
- print(status_update)
98
-
99
- # 5. Submit
100
  print(f"Submitting {len(answers_payload)} answers to: {submit_url}")
101
  try:
102
- response = requests.post(submit_url, json=submission_data, timeout=60)
 
103
  response.raise_for_status()
104
  result_data = response.json()
105
- final_status = (
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
106
  f"Submission Successful!\n"
107
  f"User: {result_data.get('username')}\n"
108
- f"Overall Score: {result_data.get('score', 'N/A')}% "
109
- f"({result_data.get('correct_count', '?')}/{result_data.get('total_attempted', '?')} correct)\n"
110
- f"Message: {result_data.get('message', 'No message received.')}"
111
  )
112
- print("Submission successful.")
113
- results_df = pd.DataFrame(results_log)
114
- return final_status, results_df
115
- except requests.exceptions.HTTPError as e:
116
- error_detail = f"Server responded with status {e.response.status_code}."
117
- try:
118
- error_json = e.response.json()
119
- error_detail += f" Detail: {error_json.get('detail', e.response.text)}"
120
- except requests.exceptions.JSONDecodeError:
121
- error_detail += f" Response: {e.response.text[:500]}"
122
- status_message = f"Submission Failed: {error_detail}"
123
- print(status_message)
124
- results_df = pd.DataFrame(results_log)
125
- return status_message, results_df
126
- except requests.exceptions.Timeout:
127
- status_message = "Submission Failed: The request timed out."
128
- print(status_message)
129
- results_df = pd.DataFrame(results_log)
130
- return status_message, results_df
131
- except requests.exceptions.RequestException as e:
132
- status_message = f"Submission Failed: Network error - {e}"
133
  print(status_message)
134
- results_df = pd.DataFrame(results_log)
135
- return status_message, results_df
136
- except Exception as e:
137
- status_message = f"An unexpected error occurred during submission: {e}"
138
- print(status_message)
139
- results_df = pd.DataFrame(results_log)
140
- return status_message, results_df
 
 
 
 
 
 
141
 
142
 
143
- # --- Build Gradio Interface using Blocks ---
 
 
 
 
 
 
144
  with gr.Blocks() as demo:
145
  gr.Markdown("# Basic Agent Evaluation Runner")
146
  gr.Markdown(
147
  """
148
  **Instructions:**
149
 
150
- 1. Please clone this space, then modify the code to define your agent's logic, the tools, the necessary packages, etc ...
151
- 2. Log in to your Hugging Face account using the button below. This uses your HF username for submission.
152
- 3. Click 'Run Evaluation & Submit All Answers' to fetch questions, run your agent, submit answers, and see the score.
153
 
154
  ---
155
- **Disclaimers:**
156
- Once clicking on the "submit button, it can take quite some time ( this is the time for the agent to go through all the questions).
157
- This space provides a basic setup and is intentionally sub-optimal to encourage you to develop your own, more robust solution. For instance for the delay process of the submit button, a solution could be to cache the answers and submit in a seperate action or even to answer the questions in async.
158
- """
159
  )
160
 
 
161
  gr.LoginButton()
162
 
 
163
  run_button = gr.Button("Run Evaluation & Submit All Answers")
164
 
165
- status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)
166
- # Removed max_rows=10 from DataFrame constructor
167
- results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
 
 
 
 
 
 
 
168
 
169
- run_button.click(
170
- fn=run_and_submit_all,
171
- outputs=[status_output, results_table]
172
- )
173
 
 
 
 
174
  if __name__ == "__main__":
175
- print("\n" + "-"*30 + " App Starting " + "-"*30)
176
- # Check for SPACE_HOST and SPACE_ID at startup for information
177
- space_host_startup = os.getenv("SPACE_HOST")
178
- space_id_startup = os.getenv("SPACE_ID") # Get SPACE_ID at startup
179
-
180
- if space_host_startup:
181
- print(f"✅ SPACE_HOST found: {space_host_startup}")
182
- print(f" Runtime URL should be: https://{space_host_startup}.hf.space")
183
- else:
184
- print("ℹ️ SPACE_HOST environment variable not found (running locally?).")
185
 
186
- if space_id_startup: # Print repo URLs if SPACE_ID is found
187
- print(f"✅ SPACE_ID found: {space_id_startup}")
188
- print(f" Repo URL: https://huggingface.co/spaces/{space_id_startup}")
189
- print(f" Repo Tree URL: https://huggingface.co/spaces/{space_id_startup}/tree/main")
190
  else:
191
- print("ℹ️ SPACE_ID environment variable not found (running locally?). Repo URL cannot be determined.")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
192
 
193
- print("-"*(60 + len(" App Starting ")) + "\n")
194
 
195
- print("Launching Gradio Interface for Basic Agent Evaluation...")
196
- demo.launch(debug=True, share=False)
 
1
  import os
2
+ import re
3
  import gradio as gr
4
  import requests
5
  import inspect
6
  import pandas as pd
7
+ import spaces
8
+ from smolagents import CodeAgent, HfApiModel, DuckDuckGoSearchTool, VisitWebpageTool, tool
9
+
10
 
11
  # (Keep Constants as is)
12
  # --- Constants ---
13
  DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
14
 
15
+
16
+ # --- ZeroGPU: the Space needs at least one @spaces.GPU function to start ---
17
+ @spaces.GPU(duration=120)
18
+ def _zero_gpu_keepalive():
19
+ return "ok"
20
+
21
+
22
+ # --- Extra tools for the GAIA agent ---
23
+ @tool
24
+ def search_wikipedia(query: str) -> str:
25
+ """Search English Wikipedia for a topic and return a short summary of the best matching article.
26
+ Args:
27
+ query: The topic or question to look up on Wikipedia.
28
+ """""
29
+ try:
30
+ search_url = "https://en.wikipedia.org/w/api.php"
31
+ params = {"action": "query", "list": "search", "srsearch": query, "srlimit": 3, "format": "json"}
32
+ headers = {"User-Agent": "GAIA-agent-course/1.0"}
33
+ resp = requests.get(search_url, params=params, headers=headers, timeout=20)
34
+ resp.raise_for_status()
35
+ results = resp.json().get("query", {}).get("search", [])
36
+ if not results:
37
+ return "No Wikipedia article found."
38
+
39
+
40
+
41
+
42
+
43
+
44
+
45
+
46
+
47
+
48
+
49
+
50
+
51
+
52
+
53
+
54
+
55
+
56
+
57
+
58
+
59
+
60
+
61
+
62
+
63
+ title = results[0]["title"]
64
+ summary_url = "https://en.wikipedia.org/api/rest_v1/page/summary/" + requests.utils.quote(title)
65
+ summary_resp = requests.get(summary_url, headers=headers, timeout=20)
66
+ summary_resp.raise_for_status()
67
+ data = summary_resp.json()
68
+ text = data.get("extract", "")
69
+ if text:
70
+ return f"Wikipedia article '{title}': {text}"
71
+ return f"Wikipedia article found: {title} (no summary available)."
72
+ except Exception as e:
73
+ return f"Wikipedia search failed: {e}"
74
+
75
+
76
+ @tool
77
+ def read_file(path: str) -> str:
78
+ """Read a local file and return its contents as text. Supports .txt, .py, .md, .csv and .json files and .xlsx spreadsheets (returned as a table). Use this to inspect files attached to a task.
79
+ Args:
80
+ path: The local file path to read.
81
+ """""
82
+ try:
83
+ if path.lower().endswith(".xlsx"):
84
+ df = pd.read_excel(path)
85
+ return df.to_string(index=False)
86
+ if path.lower().endswith((".mp3", ".wav", ".png", ".jpg", ".jpeg")):
87
+ return f"The file {path} is an audio or image file and cannot be read as text with the available tools."
88
+ with open(path, "r", encoding="utf-8", errors="replace") as f:
89
+ content = f.read()
90
+ if len(content) > 8000:
91
+ return content[:8000]
92
+ return content
93
+ except Exception as e:
94
+ return f"Could not read file {path}: {e}"
95
+
96
+
97
+
98
+
99
+
100
+
101
+
102
+
103
+
104
+
105
+
106
+
107
+
108
+
109
+
110
+
111
+
112
+
113
+
114
+
115
+
116
+
117
+
118
+
119
+
120
+
121
+
122
+ @tool
123
+ def get_youtube_transcript(video_url: str) -> str:
124
+ """Fetch the transcript (subtitles) of a YouTube video, given its URL or video ID.
125
+ Args:
126
+ video_url: The full YouTube video URL or the video ID.
127
+ """""
128
+ try:
129
+ from youtube_transcript_api import YouTubeTranscriptApi
130
+ match = re.search(r"(?:v=|youtu\.be/|shorts/)([A-Za-z0-9_-]{11})", video_url)
131
+ video_id = match.group(1) if match else video_url.strip()
132
+ try:
133
+ transcript = YouTubeTranscriptApi().fetch(video_id)
134
+ lines = [entry.text for entry in transcript]
135
+ except Exception:
136
+ transcript = YouTubeTranscriptApi.get_transcript(video_id)
137
+ lines = [entry["text"] for entry in transcript]
138
+ text = " ".join(lines)
139
+ if len(text) > 8000:
140
+ return text[:8000]
141
+ return text
142
+ except Exception as e:
143
+ return f"Could not fetch YouTube transcript: {e}"
144
+
145
+
146
  # --- Basic Agent Definition ---
147
  # ----- THIS IS WERE YOU CAN BUILD WHAT YOU WANT ------
148
  class BasicAgent:
149
  def __init__(self):
150
+ model = HfApiModel(
151
+ model_id="Qwen/Qwen2.5-Coder-32B-Instruct",
152
+ token=os.getenv("HF_TOKEN"),
153
+ )
154
+ self.agent = CodeAgent(
155
+ tools=[DuckDuckGoSearchTool(), VisitWebpageTool(), search_wikipedia, read_file, get_youtube_transcript],
156
+ model=model,
157
+ max_steps=10,
158
+ )
159
  print("BasicAgent initialized.")
160
+
161
  def __call__(self, question: str) -> str:
162
  print(f"Agent received question (first 50 chars): {question[:50]}...")
163
+ prompt = (
164
+ question
165
+ + "\n\nUse your tools to research the question and verify the facts before answering. "
166
+ "When you know the answer, finish with exactly one line in this format: FINAL ANSWER: <your answer> "
167
+ "Do not add anything after that line."
168
+ )
169
+ result = self.agent.run(prompt)
170
+ answer = str(result).strip()
171
+ if "FINAL ANSWER:" in answer:
172
+ answer = answer.split("FINAL ANSWER:")[-1].strip()
173
+ answer = answer.split("\n")[0].strip()
174
+ print(f"Agent returning answer: {answer}")
175
+ return answer
176
+
177
+
178
+
179
+
180
+
181
+
182
+
183
+
184
+
185
+
186
+
187
+
188
+
189
+
190
+
191
+
192
+
193
+
194
+
195
+
196
 
197
+
198
+
199
+
200
+
201
+
202
+
203
+
204
+
205
+
206
+
207
+
208
+
209
+
210
+
211
+ def run_and_submit_all(profile: gr.OAuthProfile | None):
212
  """
213
  Fetches all questions, runs the BasicAgent on them, submits all answers,
214
  and displays the results.
215
+ """""
216
  # --- Determine HF Space Runtime URL and Repo URL ---
217
+ space_id = os.getenv("SPACE_ID") # Get the SPACE_ID for sending link to the code
218
 
219
  if profile:
220
+ username = f"{profile.username}"
221
  print(f"User logged in: {username}")
222
  else:
223
  print("User not logged in.")
 
230
  # 1. Instantiate Agent ( modify this part to create your agent)
231
  try:
232
  agent = BasicAgent()
233
+ except Exception as e:
234
  print(f"Error instantiating agent: {e}")
235
  return f"Error initializing agent: {e}", None
236
+
237
+ # In the case of an app running as a hugging Face space, this link points toward your codebase ( use the SPACE_ID environment variable if you don't want to hardcode it)
238
  agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
239
  print(agent_code)
240
 
 
245
  response.raise_for_status()
246
  questions_data = response.json()
247
  if not questions_data:
248
+ print("Fetched questions list is empty.")
249
+ return "Fetched questions list is empty or invalid format.", None
250
  print(f"Fetched {len(questions_data)} questions.")
251
+ except requests.exceptions.RequestException as e:
252
  print(f"Error fetching questions: {e}")
253
  return f"Error fetching questions: {e}", None
254
+ except requests.exceptions.JSONDecodeError as e:
255
+ print(f"Error decoding JSON response of questions: {e}")
256
+ return f"Error decoding JSON response of questions: {e}", None
257
+ except Exception as e:
258
+ print(f"Unexpected error fetching questions: {e}")
259
+ return f"Unexpected error fetching questions: {e}", None
260
+
261
+
262
+
263
+
264
+
265
+
266
+
267
+
268
+
269
+
270
+
271
+
272
+
273
+
274
+
275
+
276
+
277
+
278
+
279
+
280
+
281
+
282
+
283
+
284
+
285
+
286
+
287
+
288
+
289
+
290
+
291
+
292
+
293
+
294
+
295
+
296
 
297
  # 3. Run your Agent
298
  results_log = []
 
305
  print(f"Skipping item with missing task_id or question: {item}")
306
  continue
307
  try:
308
+ # Download the file attached to this task, if any, so the agent can inspect it
309
+ file_name = item.get("file_name") or ""
310
+ question_for_agent = question_text
311
+ if file_name:
312
+ try:
313
+ file_url = f"{api_url}/files/{task_id}"
314
+ file_response = requests.get(file_url, timeout=60)
315
+ file_response.raise_for_status()
316
+ local_path = os.path.join("/tmp", file_name)
317
+ with open(local_path, "wb") as f:
318
+ f.write(file_response.content)
319
+ question_for_agent = (
320
+ question_text
321
+ + f"\n\nAn attached file for this task was downloaded to: {local_path}. Use the read_file tool to inspect it if it helps answer the question."
322
+ )
323
+ except Exception as fe:
324
+ print(f"Could not download file for task {task_id}: {fe}")
325
+
326
+
327
+
328
+
329
+
330
+
331
+
332
+
333
+
334
+
335
+
336
+
337
+
338
+
339
+
340
+
341
+
342
+
343
+
344
+
345
+
346
+
347
+
348
+
349
+
350
+ submitted_answer = agent(question_for_agent)
351
  answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
352
  results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
353
  except Exception as e:
354
+ print(f"Error running agent on task {task_id}: {e}")
355
+ results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"})
356
 
357
  if not answers_payload:
358
  print("Agent did not produce any answers to submit.")
359
  return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
360
 
361
+ # 4. Submit Answers
 
 
 
 
 
362
  print(f"Submitting {len(answers_payload)} answers to: {submit_url}")
363
  try:
364
+ payload = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
365
+ response = requests.post(submit_url, json=payload, timeout=60)
366
  response.raise_for_status()
367
  result_data = response.json()
368
+ except requests.exceptions.HTTPError as e:
369
+ error_detail = f"HTTP Error: {e}"
370
+ try:
371
+ error_json = response.json()
372
+ error_detail += f" | Server response: {error_json}"
373
+ except Exception:
374
+ error_detail += f" | Server raw response: {response.text[:500]}"
375
+ print(error_detail)
376
+ return error_detail, pd.DataFrame(results_log)
377
+
378
+
379
+
380
+
381
+
382
+
383
+
384
+
385
+
386
+
387
+
388
+
389
+
390
+
391
+
392
+
393
+
394
+
395
+
396
+
397
+
398
+
399
+
400
+ except requests.exceptions.RequestException as e:
401
+ print(f"Error submitting answers: {e}")
402
+ return f"Error submitting answers: {e}", pd.DataFrame(results_log)
403
+ except requests.exceptions.JSONDecodeError as e:
404
+ print(f"Error decoding JSON response of submission: {e}")
405
+ return f"Error decoding JSON response of submission: {e}", pd.DataFrame(results_log)
406
+ except Exception as e:
407
+ print(f"Unexpected error submitting answers: {e}")
408
+ return f"Unexpected error submitting answers: {e}", pd.DataFrame(results_log)
409
+
410
+ # 5. Format Submission Results
411
+ try:
412
+ status_message = (
413
  f"Submission Successful!\n"
414
  f"User: {result_data.get('username')}\n"
415
+ f"Score: {result_data.get('score')} ({result_data.get('correct_count')}/{result_data.get('total_attempted')} correct)\n"
416
+ f"Message: {result_data.get('message')}"
 
417
  )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
418
  print(status_message)
419
+ return status_message, pd.DataFrame(results_log)
420
+ except Exception as e:
421
+ print(f"Error formatting submission results: {e}")
422
+ return f"Submission worked but formatting failed: {e}\nRaw data: {result_data}", pd.DataFrame(results_log)
423
+
424
+
425
+
426
+
427
+
428
+
429
+
430
+
431
+
432
 
433
 
434
+
435
+
436
+
437
+
438
+
439
+
440
+ # --- Build the Gradio UI ---
441
  with gr.Blocks() as demo:
442
  gr.Markdown("# Basic Agent Evaluation Runner")
443
  gr.Markdown(
444
  """
445
  **Instructions:**
446
 
447
+ 1. Log in to your Hugging Face account using the button below. This uses your HF username for submission.
448
+ 2. Click 'Run Evaluation & Submit All Answers' to fetch the 20 GAIA level-1 questions, run the agent on them, submit the answers, and see the score.
 
449
 
450
  ---
451
+ **Disclaimer:**
452
+
453
+ Running the evaluation can take quite some time (this is the time for the agent to answer all 20 questions). Please be patient.
454
+ """""
455
  )
456
 
457
+ # --- OAuth ---
458
  gr.LoginButton()
459
 
460
+ # --- Interactive Components ---
461
  run_button = gr.Button("Run Evaluation & Submit All Answers")
462
 
463
+ status_output = gr.Textbox(label="Status Message", lines=5, interactive=False)
464
+ results_dataframe = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
465
+
466
+ # --- UI Events ---
467
+ run_button.click(fn=run_and_submit_all, outputs=[status_output, results_dataframe])
468
+
469
+
470
+
471
+
472
+
473
 
 
 
 
 
474
 
475
+
476
+
477
+ # --- Launch the App ---
478
  if __name__ == "__main__":
479
+ space_host = os.getenv("SPACE_HOST")
480
+ space_id = os.getenv("SPACE_ID")
 
 
 
 
 
 
 
 
481
 
482
+ if space_host:
483
+ print(f"SPACE_HOST found: {space_host}")
484
+ print(f"SPACE_ID='{space_id}'")
 
485
  else:
486
+ print("SPACE_HOST environment variable not found (running locally?).")
487
+ print("SPACE_ID environment variable not found (running locally?). Repo URL cannot be determined.")
488
+
489
+ launch_kwargs = {"debug": True, "share": False}
490
+ if space_host:
491
+ launch_kwargs["server_name"] = "0.0.0.0"
492
+ launch_kwargs["server_port"] = 7860
493
+
494
+ demo.launch(**launch_kwargs)
495
+
496
+
497
+
498
+
499
+
500
+
501
+
502
+
503
+
504
+
505
 
 
506