VincentG1234 commited on
Commit
099d700
·
verified ·
1 Parent(s): ec1a203

Delete mehta_app.py

Browse files
Files changed (1) hide show
  1. mehta_app.py +0 -277
mehta_app.py DELETED
@@ -1,277 +0,0 @@
1
- import os
2
- import gradio as gr
3
- import requests
4
- import inspect
5
- import pandas as pd
6
- import time
7
- from google import genai
8
- from smolagents import Tool , CodeAgent, ToolCallingAgent, DuckDuckGoSearchTool, LiteLLMModel, PythonInterpreterTool, tool, DuckDuckGoSearchTool
9
- from langchain_community.document_loaders import YoutubeLoader
10
- import re
11
- import requests
12
- from markdownify import markdownify
13
- from requests.exceptions import RequestException
14
-
15
-
16
- @tool
17
- def visit_webpage(url: str) -> str:
18
- """Visits a webpage at the given URL and returns its content as a markdown string.
19
-
20
- Args:
21
- url: The URL of the webpage to visit.
22
-
23
- Returns:
24
- The content of the webpage converted to Markdown, or an error message if the request fails.
25
- """
26
- try:
27
- # Send a GET request to the URL
28
- response = requests.get(url)
29
- response.raise_for_status() # Raise an exception for bad status codes
30
-
31
- # Convert the HTML content to Markdown
32
- markdown_content = markdownify(response.text).strip()
33
-
34
- # Remove multiple line breaks
35
- markdown_content = re.sub(r"\n{3,}", "\n\n", markdown_content)
36
-
37
- return markdown_content
38
-
39
- except RequestException as e:
40
- return f"Error fetching the webpage: {str(e)}"
41
- except Exception as e:
42
- return f"An unexpected error occurred: {str(e)}"
43
-
44
- #client = genai.Client(api_key=os.getenv("API_KEY"))
45
- model = LiteLLMModel(model_id="gemini/gemini-2.0-flash-lite",
46
- api_key=os.getenv("API_KEY"))
47
- # (Keep Constants as is)
48
- # --- Constants ---
49
- DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
50
-
51
- # --- Basic Agent Definition ---
52
- # ----- THIS IS WERE YOU CAN BUILD WHAT YOU WANT ------
53
-
54
- @tool
55
- def youtube_transcription_tool(url: str) -> str:
56
- """
57
- This tool returns transcript of the youtube video.
58
-
59
- Args:
60
- url: youtube video url
61
- """
62
- # Example list of catering services and their ratings
63
- loader = YoutubeLoader.from_youtube_url(
64
- url, add_video_info=False
65
- )
66
-
67
-
68
- return loader.load()[0].page_content
69
-
70
-
71
- class BasicAgent:
72
- def __init__(self):
73
- print("BasicAgent initialized.")
74
- def __call__(self, question: str) -> str:
75
- print(f"Agent received question (first 50 chars): {question[:50]}...")
76
-
77
-
78
- # response = client.models.generate_content(
79
- # model="gemini-2.5-flash-preview-04-17", contents=question
80
- # )
81
- # gemini_flash_answer = response.text
82
-
83
- # youtube_tool = Tool.from_space(
84
- # "black-forest-labs/FLUX.1-schnell",
85
- # name="image_generator",
86
- # description="Generate an image from a prompt"
87
- # )
88
-
89
- agent = CodeAgent(
90
- tools=[DuckDuckGoSearchTool(), youtube_transcription_tool, visit_webpage],
91
- model=model,
92
- #additional_authorized_imports=["helium"],
93
- #step_callbacks=[save_screenshot],
94
- max_steps=20,
95
- verbosity_level=2,
96
- )
97
- answer = agent.run(question)
98
- #fixed_answer = "This is a default answer."
99
- print(f"Agent returning fixed answer: {answer}")
100
- return answer
101
-
102
- def run_and_submit_all( profile: gr.OAuthProfile | None):
103
- """
104
- Fetches all questions, runs the BasicAgent on them, submits all answers,
105
- and displays the results.
106
- """
107
- # --- Determine HF Space Runtime URL and Repo URL ---
108
- space_id = os.getenv("SPACE_ID") # Get the SPACE_ID for sending link to the code
109
-
110
- if profile:
111
- username= f"{profile.username}"
112
- print(f"User logged in: {username}")
113
- else:
114
- print("User not logged in.")
115
- return "Please Login to Hugging Face with the button.", None
116
-
117
- api_url = DEFAULT_API_URL
118
- questions_url = f"{api_url}/questions"
119
- submit_url = f"{api_url}/submit"
120
-
121
- # 1. Instantiate Agent ( modify this part to create your agent)
122
- try:
123
- agent = BasicAgent()
124
- except Exception as e:
125
- print(f"Error instantiating agent: {e}")
126
- return f"Error initializing agent: {e}", None
127
- # 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)
128
- agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
129
- print(agent_code)
130
-
131
- # 2. Fetch Questions
132
- print(f"Fetching questions from: {questions_url}")
133
- try:
134
- response = requests.get(questions_url, timeout=30)
135
- response.raise_for_status()
136
- questions_data = response.json()
137
- if not questions_data:
138
- print("Fetched questions list is empty.")
139
- return "Fetched questions list is empty or invalid format.", None
140
- print(f"Fetched {len(questions_data)} questions.")
141
- except requests.exceptions.RequestException as e:
142
- print(f"Error fetching questions: {e}")
143
- return f"Error fetching questions: {e}", None
144
- except requests.exceptions.JSONDecodeError as e:
145
- print(f"Error decoding JSON response from questions endpoint: {e}")
146
- print(f"Response text: {response.text[:500]}")
147
- return f"Error decoding server response for questions: {e}", None
148
- except Exception as e:
149
- print(f"An unexpected error occurred fetching questions: {e}")
150
- return f"An unexpected error occurred fetching questions: {e}", None
151
-
152
- # 3. Run your Agent
153
- results_log = []
154
- answers_payload = []
155
- print(f"Running agent on {len(questions_data)} questions...")
156
- for item in questions_data:
157
- task_id = item.get("task_id")
158
- question_text = item.get("question")
159
- if not task_id or question_text is None:
160
- print(f"Skipping item with missing task_id or question: {item}")
161
- continue
162
- try:
163
- submitted_answer = agent(question_text)
164
- time.sleep(60)
165
- answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
166
- results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
167
- except Exception as e:
168
- print(f"Error running agent on task {task_id}: {e}")
169
- results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"})
170
-
171
- if not answers_payload:
172
- print("Agent did not produce any answers to submit.")
173
- return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
174
-
175
- # 4. Prepare Submission
176
- submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
177
- status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..."
178
- print(status_update)
179
-
180
- # 5. Submit
181
- print(f"Submitting {len(answers_payload)} answers to: {submit_url}")
182
- try:
183
- response = requests.post(submit_url, json=submission_data, timeout=60)
184
- response.raise_for_status()
185
- result_data = response.json()
186
- final_status = (
187
- f"Submission Successful!\n"
188
- f"User: {result_data.get('username')}\n"
189
- f"Overall Score: {result_data.get('score', 'N/A')}% "
190
- f"({result_data.get('correct_count', '?')}/{result_data.get('total_attempted', '?')} correct)\n"
191
- f"Message: {result_data.get('message', 'No message received.')}"
192
- )
193
- print("Submission successful.")
194
- results_df = pd.DataFrame(results_log)
195
- return final_status, results_df
196
- except requests.exceptions.HTTPError as e:
197
- error_detail = f"Server responded with status {e.response.status_code}."
198
- try:
199
- error_json = e.response.json()
200
- error_detail += f" Detail: {error_json.get('detail', e.response.text)}"
201
- except requests.exceptions.JSONDecodeError:
202
- error_detail += f" Response: {e.response.text[:500]}"
203
- status_message = f"Submission Failed: {error_detail}"
204
- print(status_message)
205
- results_df = pd.DataFrame(results_log)
206
- return status_message, results_df
207
- except requests.exceptions.Timeout:
208
- status_message = "Submission Failed: The request timed out."
209
- print(status_message)
210
- results_df = pd.DataFrame(results_log)
211
- return status_message, results_df
212
- except requests.exceptions.RequestException as e:
213
- status_message = f"Submission Failed: Network error - {e}"
214
- print(status_message)
215
- results_df = pd.DataFrame(results_log)
216
- return status_message, results_df
217
- except Exception as e:
218
- status_message = f"An unexpected error occurred during submission: {e}"
219
- print(status_message)
220
- results_df = pd.DataFrame(results_log)
221
- return status_message, results_df
222
-
223
-
224
- # --- Build Gradio Interface using Blocks ---
225
- with gr.Blocks() as demo:
226
- gr.Markdown("# Basic Agent Evaluation Runner")
227
- gr.Markdown(
228
- """
229
- **Instructions:**
230
-
231
- 1. Please clone this space, then modify the code to define your agent's logic, the tools, the necessary packages, etc ...
232
- 2. Log in to your Hugging Face account using the button below. This uses your HF username for submission.
233
- 3. Click 'Run Evaluation & Submit All Answers' to fetch questions, run your agent, submit answers, and see the score.
234
-
235
- ---
236
- **Disclaimers:**
237
- 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).
238
- 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.
239
- """
240
- )
241
-
242
- gr.LoginButton()
243
-
244
- run_button = gr.Button("Run Evaluation & Submit All Answers")
245
-
246
- status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)
247
- # Removed max_rows=10 from DataFrame constructor
248
- results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
249
-
250
- run_button.click(
251
- fn=run_and_submit_all,
252
- outputs=[status_output, results_table]
253
- )
254
-
255
- if __name__ == "__main__":
256
- print("\n" + "-"*30 + " App Starting " + "-"*30)
257
- # Check for SPACE_HOST and SPACE_ID at startup for information
258
- space_host_startup = os.getenv("SPACE_HOST")
259
- space_id_startup = os.getenv("SPACE_ID") # Get SPACE_ID at startup
260
-
261
- if space_host_startup:
262
- print(f"✅ SPACE_HOST found: {space_host_startup}")
263
- print(f" Runtime URL should be: https://{space_host_startup}.hf.space")
264
- else:
265
- print("ℹ️ SPACE_HOST environment variable not found (running locally?).")
266
-
267
- if space_id_startup: # Print repo URLs if SPACE_ID is found
268
- print(f"✅ SPACE_ID found: {space_id_startup}")
269
- print(f" Repo URL: https://huggingface.co/spaces/{space_id_startup}")
270
- print(f" Repo Tree URL: https://huggingface.co/spaces/{space_id_startup}/tree/main")
271
- else:
272
- print("ℹ️ SPACE_ID environment variable not found (running locally?). Repo URL cannot be determined.")
273
-
274
- print("-"*(60 + len(" App Starting ")) + "\n")
275
-
276
- print("Launching Gradio Interface for Basic Agent Evaluation...")
277
- demo.launch(debug=True, share=False)