DeekshithN05 commited on
Commit
ad2fd80
·
verified ·
1 Parent(s): 9618c03

Delete app.py

Browse files
Files changed (1) hide show
  1. app.py +0 -228
app.py DELETED
@@ -1,228 +0,0 @@
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
- from transformers import pipeline
14
-
15
- class BasicAgent:
16
- def __init__(self):
17
- print("Loading LaMini-T5-738M model...")
18
- self.pipeline = pipeline(
19
- "text2text-generation",
20
- model="MBZUAI/LaMini-T5-738M",
21
- max_new_tokens=128,
22
- temperature=0.3
23
- )
24
- print("Model loaded.")
25
-
26
- def __call__(self, question: str) -> str:
27
- print(f"Received question: {question[:60]}...")
28
-
29
- few_shot_example = (
30
- "Question: List just the vegetables from [milk, eggs, carrots, onions, cookies].\n"
31
- "Answer: carrots, onions\n\n"
32
- )
33
-
34
- prompt = (
35
- few_shot_example +
36
- "Please solve the following step by step and return only the final answer:\n"
37
- f"{question}"
38
- )
39
-
40
- try:
41
- response = self.pipeline(prompt)[0]["generated_text"]
42
- if "Answer:" in response:
43
- answer = response.strip().split("Answer:")[-1].strip().split("\n")[0]
44
- else:
45
- answer = response.strip().split("\n")[0]
46
- except Exception as e:
47
- print(f"Model error: {e}")
48
- answer = "[Error generating answer]"
49
-
50
- print(f"Final answer: {answer}")
51
- return answer
52
-
53
-
54
- def run_and_submit_all( profile: gr.OAuthProfile | None):
55
- """
56
- Fetches all questions, runs the BasicAgent on them, submits all answers,
57
- and displays the results.
58
- """
59
- # --- Determine HF Space Runtime URL and Repo URL ---
60
- space_id = os.getenv("SPACE_ID") # Get the SPACE_ID for sending link to the code
61
-
62
- if profile:
63
- username= f"{profile.username}"
64
- print(f"User logged in: {username}")
65
- else:
66
- print("User not logged in.")
67
- return "Please Login to Hugging Face with the button.", None
68
-
69
- api_url = DEFAULT_API_URL
70
- questions_url = f"{api_url}/questions"
71
- submit_url = f"{api_url}/submit"
72
-
73
- # 1. Instantiate Agent ( modify this part to create your agent)
74
- try:
75
- agent = BasicAgent()
76
- except Exception as e:
77
- print(f"Error instantiating agent: {e}")
78
- return f"Error initializing agent: {e}", None
79
- # 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)
80
- agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
81
- print(agent_code)
82
-
83
- # 2. Fetch Questions
84
- print(f"Fetching questions from: {questions_url}")
85
- try:
86
- response = requests.get(questions_url, timeout=15)
87
- response.raise_for_status()
88
- questions_data = response.json()
89
- if not questions_data:
90
- print("Fetched questions list is empty.")
91
- return "Fetched questions list is empty or invalid format.", None
92
- print(f"Fetched {len(questions_data)} questions.")
93
- except requests.exceptions.RequestException as e:
94
- print(f"Error fetching questions: {e}")
95
- return f"Error fetching questions: {e}", None
96
- except requests.exceptions.JSONDecodeError as e:
97
- print(f"Error decoding JSON response from questions endpoint: {e}")
98
- print(f"Response text: {response.text[:500]}")
99
- return f"Error decoding server response for questions: {e}", None
100
- except Exception as e:
101
- print(f"An unexpected error occurred fetching questions: {e}")
102
- return f"An unexpected error occurred fetching questions: {e}", None
103
-
104
- # 3. Run your Agent
105
- results_log = []
106
- answers_payload = []
107
- print(f"Running agent on {len(questions_data)} questions...")
108
- for item in questions_data:
109
- task_id = item.get("task_id")
110
- question_text = item.get("question")
111
- if not task_id or question_text is None:
112
- print(f"Skipping item with missing task_id or question: {item}")
113
- continue
114
- try:
115
- submitted_answer = agent(question_text)
116
- answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
117
- results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
118
- except Exception as e:
119
- print(f"Error running agent on task {task_id}: {e}")
120
- results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"})
121
-
122
- if not answers_payload:
123
- print("Agent did not produce any answers to submit.")
124
- return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
125
-
126
- # 4. Prepare Submission
127
- submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
128
- status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..."
129
- print(status_update)
130
-
131
- # 5. Submit
132
- print(f"Submitting {len(answers_payload)} answers to: {submit_url}")
133
- try:
134
- response = requests.post(submit_url, json=submission_data, timeout=60)
135
- response.raise_for_status()
136
- result_data = response.json()
137
- final_status = (
138
- f"Submission Successful!\n"
139
- f"User: {result_data.get('username')}\n"
140
- f"Overall Score: {result_data.get('score', 'N/A')}% "
141
- f"({result_data.get('correct_count', '?')}/{result_data.get('total_attempted', '?')} correct)\n"
142
- f"Message: {result_data.get('message', 'No message received.')}"
143
- )
144
- print("Submission successful.")
145
- results_df = pd.DataFrame(results_log)
146
- return final_status, results_df
147
- except requests.exceptions.HTTPError as e:
148
- error_detail = f"Server responded with status {e.response.status_code}."
149
- try:
150
- error_json = e.response.json()
151
- error_detail += f" Detail: {error_json.get('detail', e.response.text)}"
152
- except requests.exceptions.JSONDecodeError:
153
- error_detail += f" Response: {e.response.text[:500]}"
154
- status_message = f"Submission Failed: {error_detail}"
155
- print(status_message)
156
- results_df = pd.DataFrame(results_log)
157
- return status_message, results_df
158
- except requests.exceptions.Timeout:
159
- status_message = "Submission Failed: The request timed out."
160
- print(status_message)
161
- results_df = pd.DataFrame(results_log)
162
- return status_message, results_df
163
- except requests.exceptions.RequestException as e:
164
- status_message = f"Submission Failed: Network error - {e}"
165
- print(status_message)
166
- results_df = pd.DataFrame(results_log)
167
- return status_message, results_df
168
- except Exception as e:
169
- status_message = f"An unexpected error occurred during submission: {e}"
170
- print(status_message)
171
- results_df = pd.DataFrame(results_log)
172
- return status_message, results_df
173
-
174
-
175
- # --- Build Gradio Interface using Blocks ---
176
- with gr.Blocks() as demo:
177
- gr.Markdown("# Basic Agent Evaluation Runner")
178
- gr.Markdown(
179
- """
180
- **Instructions:**
181
-
182
- 1. Please clone this space, then modify the code to define your agent's logic, the tools, the necessary packages, etc ...
183
- 2. Log in to your Hugging Face account using the button below. This uses your HF username for submission.
184
- 3. Click 'Run Evaluation & Submit All Answers' to fetch questions, run your agent, submit answers, and see the score.
185
-
186
- ---
187
- **Disclaimers:**
188
- 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).
189
- 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.
190
- """
191
- )
192
-
193
- gr.LoginButton()
194
-
195
- run_button = gr.Button("Run Evaluation & Submit All Answers")
196
-
197
- status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)
198
- # Removed max_rows=10 from DataFrame constructor
199
- results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
200
-
201
- run_button.click(
202
- fn=run_and_submit_all,
203
- outputs=[status_output, results_table]
204
- )
205
-
206
- if __name__ == "__main__":
207
- print("\n" + "-"*30 + " App Starting " + "-"*30)
208
- # Check for SPACE_HOST and SPACE_ID at startup for information
209
- space_host_startup = os.getenv("SPACE_HOST")
210
- space_id_startup = os.getenv("SPACE_ID") # Get SPACE_ID at startup
211
-
212
- if space_host_startup:
213
- print(f"✅ SPACE_HOST found: {space_host_startup}")
214
- print(f" Runtime URL should be: https://{space_host_startup}.hf.space")
215
- else:
216
- print("ℹ️ SPACE_HOST environment variable not found (running locally?).")
217
-
218
- if space_id_startup: # Print repo URLs if SPACE_ID is found
219
- print(f"✅ SPACE_ID found: {space_id_startup}")
220
- print(f" Repo URL: https://huggingface.co/spaces/{space_id_startup}")
221
- print(f" Repo Tree URL: https://huggingface.co/spaces/{space_id_startup}/tree/main")
222
- else:
223
- print("ℹ️ SPACE_ID environment variable not found (running locally?). Repo URL cannot be determined.")
224
-
225
- print("-"*(60 + len(" App Starting ")) + "\n")
226
-
227
- print("Launching Gradio Interface for Basic Agent Evaluation...")
228
- demo.launch(debug=True, share=False)