abhi1294 commited on
Commit
7eda9ec
·
1 Parent(s): 81917a3

updated final assignment

Browse files
Files changed (6) hide show
  1. .env +1 -0
  2. agent.py +78 -0
  3. app.py +117 -97
  4. prompts.py +55 -0
  5. tools.py +182 -0
  6. utils.py +100 -0
.env ADDED
@@ -0,0 +1 @@
 
 
1
+ SPACE_ID = "abhi1294/Final_Assignment_Template"
agent.py ADDED
@@ -0,0 +1,78 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from dataclasses import dataclass
4
+ from typing import Optional
5
+
6
+ from prompts import build_solver_prompt
7
+ from tools import TaskFileTool
8
+ from utils import extract_final_answer, normalize_final_answer
9
+
10
+
11
+ @dataclass
12
+ class AgentConfig:
13
+ api_base_url: str = "https://agents-course-unit4-scoring.hf.space"
14
+ max_context_chars: int = 12000
15
+
16
+
17
+ class SubmissionAgent:
18
+ """
19
+ V1 agent for the Hugging Face Agents Course Unit 4 final project.
20
+
21
+ Goals:
22
+ - Accept a benchmark question and optional task_id
23
+ - Load attached task-file context when available
24
+ - Return ONLY the final answer string
25
+ - Stay framework-agnostic for now so we can plug in any LLM later
26
+ """
27
+
28
+ def __init__(self, llm_client=None, config: Optional[AgentConfig] = None):
29
+ self.llm_client = llm_client
30
+ self.config = config or AgentConfig()
31
+ self.task_file_tool = TaskFileTool(api_base_url=self.config.api_base_url)
32
+
33
+ def __call__(self, question: str, task_id: Optional[str] = None) -> str:
34
+ """
35
+ Main entry point used by app.py.
36
+ """
37
+ context = self._load_context(task_id=task_id)
38
+ raw_output = self._solve(question=question, context=context)
39
+ final_answer = extract_final_answer(raw_output)
40
+ return normalize_final_answer(final_answer)
41
+
42
+ def _load_context(self, task_id: Optional[str]) -> str:
43
+ """
44
+ Try to fetch and read any task-linked file.
45
+ Safe fallback: empty context.
46
+ """
47
+ if not task_id:
48
+ return ""
49
+
50
+ try:
51
+ file_text = self.task_file_tool.get_task_context(task_id=task_id)
52
+ if not file_text:
53
+ return ""
54
+
55
+ return file_text[: self.config.max_context_chars]
56
+ except Exception:
57
+ return ""
58
+
59
+ def _solve(self, question: str, context: str) -> str:
60
+ """
61
+ Solve the question with either:
62
+ 1) a plugged-in LLM client, or
63
+ 2) a safe fallback so the app does not crash during setup.
64
+
65
+ The LLM client is expected to expose a .generate(prompt: str) -> str method.
66
+ We will wire the real model later.
67
+ """
68
+ prompt = build_solver_prompt(question=question, context=context)
69
+
70
+ if self.llm_client is None:
71
+ # Safe placeholder so the app can run while we build the stack.
72
+ # We will replace this with a real model client later.
73
+ return "PLACEHOLDER"
74
+
75
+ try:
76
+ return self.llm_client.generate(prompt)
77
+ except Exception:
78
+ return "PLACEHOLDER"
app.py CHANGED
@@ -1,107 +1,128 @@
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.")
35
- return "Please Login to Hugging Face with the button.", None
36
 
37
  api_url = DEFAULT_API_URL
38
  questions_url = f"{api_url}/questions"
39
  submit_url = f"{api_url}/submit"
40
 
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
 
51
- # 2. Fetch Questions
 
 
 
 
 
 
 
 
52
  print(f"Fetching questions from: {questions_url}")
53
  try:
54
- response = requests.get(questions_url, timeout=15)
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 = []
74
  answers_payload = []
 
75
  print(f"Running agent on {len(questions_data)} questions...")
 
76
  for item in questions_data:
77
  task_id = item.get("task_id")
78
  question_text = item.get("question")
 
79
  if not task_id or question_text is 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"
@@ -109,88 +130,87 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
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 gradio as gr
3
  import requests
 
4
  import pandas as pd
5
 
6
+ from agent import SubmissionAgent
7
+
8
  DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
9
 
10
+
11
+ def run_and_submit_all(profile: gr.OAuthProfile | None):
 
 
 
 
 
 
 
 
 
 
12
  """
13
+ Fetch all questions, run the agent on them, submit answers,
14
+ and display the final score plus a results table.
15
  """
16
+ space_id = os.getenv("SPACE_ID")
 
17
 
18
  if profile:
19
+ username = profile.username
20
  print(f"User logged in: {username}")
21
  else:
22
  print("User not logged in.")
23
+ return "Please login to Hugging Face first.", None
24
 
25
  api_url = DEFAULT_API_URL
26
  questions_url = f"{api_url}/questions"
27
  submit_url = f"{api_url}/submit"
28
 
29
+ # Instantiate your real agent
30
  try:
31
+ agent = SubmissionAgent()
32
  except Exception as e:
33
+ print(f"Error initializing agent: {e}")
34
  return f"Error initializing agent: {e}", None
 
 
 
35
 
36
+ # Public code link required by the benchmark
37
+ if space_id:
38
+ agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
39
+ else:
40
+ agent_code = "SPACE_ID_NOT_AVAILABLE"
41
+
42
+ print(f"Agent code URL: {agent_code}")
43
+
44
+ # Fetch questions
45
  print(f"Fetching questions from: {questions_url}")
46
  try:
47
+ response = requests.get(questions_url, timeout=20)
48
  response.raise_for_status()
49
  questions_data = response.json()
50
+
51
  if not questions_data:
52
+ return "Fetched questions list is empty.", None
53
+
54
  print(f"Fetched {len(questions_data)} questions.")
55
+
56
  except requests.exceptions.RequestException as e:
57
  print(f"Error fetching questions: {e}")
58
  return f"Error fetching questions: {e}", None
59
+ except ValueError as e:
60
+ print(f"Error decoding questions JSON: {e}")
61
+ return f"Error decoding questions JSON: {e}", None
 
62
  except Exception as e:
63
+ print(f"Unexpected error fetching questions: {e}")
64
+ return f"Unexpected error fetching questions: {e}", None
65
 
66
+ # Run agent on all questions
67
  results_log = []
68
  answers_payload = []
69
+
70
  print(f"Running agent on {len(questions_data)} questions...")
71
+
72
  for item in questions_data:
73
  task_id = item.get("task_id")
74
  question_text = item.get("question")
75
+
76
  if not task_id or question_text is None:
77
+ print(f"Skipping malformed item: {item}")
78
  continue
79
+
80
  try:
81
+ submitted_answer = agent(question_text, task_id=task_id)
82
+
83
+ answers_payload.append(
84
+ {
85
+ "task_id": task_id,
86
+ "submitted_answer": submitted_answer,
87
+ }
88
+ )
89
+
90
+ results_log.append(
91
+ {
92
+ "Task ID": task_id,
93
+ "Question": question_text,
94
+ "Submitted Answer": submitted_answer,
95
+ }
96
+ )
97
+
98
  except Exception as e:
99
+ print(f"Error on task {task_id}: {e}")
100
+ results_log.append(
101
+ {
102
+ "Task ID": task_id,
103
+ "Question": question_text,
104
+ "Submitted Answer": f"AGENT ERROR: {e}",
105
+ }
106
+ )
107
 
108
  if not answers_payload:
109
+ print("No answers generated.")
110
+ return "Agent did not generate any answers.", pd.DataFrame(results_log)
111
 
112
+ # Prepare submission payload
113
+ submission_data = {
114
+ "username": username.strip(),
115
+ "agent_code": agent_code,
116
+ "answers": answers_payload,
117
+ }
118
 
 
119
  print(f"Submitting {len(answers_payload)} answers to: {submit_url}")
120
+
121
  try:
122
  response = requests.post(submit_url, json=submission_data, timeout=60)
123
  response.raise_for_status()
124
  result_data = response.json()
125
+
126
  final_status = (
127
  f"Submission Successful!\n"
128
  f"User: {result_data.get('username')}\n"
 
130
  f"({result_data.get('correct_count', '?')}/{result_data.get('total_attempted', '?')} correct)\n"
131
  f"Message: {result_data.get('message', 'No message received.')}"
132
  )
133
+
134
  print("Submission successful.")
135
+ return final_status, pd.DataFrame(results_log)
136
+
137
  except requests.exceptions.HTTPError as e:
138
  error_detail = f"Server responded with status {e.response.status_code}."
139
  try:
140
  error_json = e.response.json()
141
  error_detail += f" Detail: {error_json.get('detail', e.response.text)}"
142
+ except ValueError:
143
  error_detail += f" Response: {e.response.text[:500]}"
144
+
145
  status_message = f"Submission Failed: {error_detail}"
146
  print(status_message)
147
+ return status_message, pd.DataFrame(results_log)
148
+
149
  except requests.exceptions.Timeout:
150
+ status_message = "Submission Failed: Request timed out."
151
  print(status_message)
152
+ return status_message, pd.DataFrame(results_log)
153
+
154
  except requests.exceptions.RequestException as e:
155
  status_message = f"Submission Failed: Network error - {e}"
156
  print(status_message)
157
+ return status_message, pd.DataFrame(results_log)
158
+
159
  except Exception as e:
160
+ status_message = f"Unexpected submission error: {e}"
161
  print(status_message)
162
+ return status_message, pd.DataFrame(results_log)
 
163
 
164
 
 
165
  with gr.Blocks() as demo:
166
+ gr.Markdown("# Hugging Face Unit 4 Agent Evaluation Runner")
167
  gr.Markdown(
168
  """
169
+ Log in with your Hugging Face account, run your agent on all benchmark questions,
170
+ submit the answers, and view the score plus answer log.
 
 
 
 
 
 
 
 
171
  """
172
  )
173
 
174
+ login_button = gr.LoginButton()
 
175
  run_button = gr.Button("Run Evaluation & Submit All Answers")
176
 
177
+ status_output = gr.Textbox(
178
+ label="Run Status / Submission Result",
179
+ lines=6,
180
+ interactive=False,
181
+ )
182
+
183
+ results_table = gr.DataFrame(
184
+ label="Questions and Agent Answers",
185
+ wrap=True,
186
+ )
187
 
188
  run_button.click(
189
  fn=run_and_submit_all,
190
+ inputs=[login_button],
191
+ outputs=[status_output, results_table],
192
  )
193
 
194
+
195
  if __name__ == "__main__":
196
+ print("\n" + "-" * 30 + " App Starting " + "-" * 30)
197
+
198
  space_host_startup = os.getenv("SPACE_HOST")
199
+ space_id_startup = os.getenv("SPACE_ID")
200
 
201
  if space_host_startup:
202
+ print(f"SPACE_HOST: {space_host_startup}")
203
+ print(f"Runtime URL: https://{space_host_startup}.hf.space")
204
  else:
205
+ print("SPACE_HOST not found. Probably running locally.")
206
 
207
+ if space_id_startup:
208
+ print(f"SPACE_ID: {space_id_startup}")
209
+ print(f"Repo URL: https://huggingface.co/spaces/{space_id_startup}")
210
+ print(f"Repo Tree URL: https://huggingface.co/spaces/{space_id_startup}/tree/main")
211
  else:
212
+ print("SPACE_ID not found. Probably running locally.")
 
 
213
 
214
+ print("-" * 75 + "\n")
215
+ print("Launching Gradio app...")
216
+ demo.launch(debug=True)
prompts.py ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+
4
+ SYSTEM_PROMPT = """
5
+ You are a benchmark-solving AI agent.
6
+
7
+ Your task is to answer questions as accurately as possible.
8
+
9
+ Rules:
10
+ - Return ONLY the final answer.
11
+ - Do NOT include explanations.
12
+ - Do NOT include reasoning.
13
+ - Do NOT include the words "FINAL ANSWER".
14
+ - Do NOT include labels like "Answer:".
15
+ - Output must be exactly the answer text.
16
+
17
+ Formatting rules:
18
+ - If the answer is a number, output only the number.
19
+ - If the answer is a word or phrase, output only that word or phrase.
20
+ - If the answer is a date, return the exact date string.
21
+ - Do not add punctuation unless it is part of the answer.
22
+
23
+ Your response must contain only the final answer string.
24
+ """
25
+
26
+
27
+ def build_solver_prompt(question: str, context: str = "") -> str:
28
+ """
29
+ Builds the final prompt sent to the model.
30
+ Includes optional file context when a task provides additional data.
31
+ """
32
+
33
+ if context:
34
+ prompt = f"""
35
+ {SYSTEM_PROMPT}
36
+
37
+ Context information:
38
+ {context}
39
+
40
+ Question:
41
+ {question}
42
+
43
+ Return only the final answer.
44
+ """
45
+ else:
46
+ prompt = f"""
47
+ {SYSTEM_PROMPT}
48
+
49
+ Question:
50
+ {question}
51
+
52
+ Return only the final answer.
53
+ """
54
+
55
+ return prompt.strip()
tools.py ADDED
@@ -0,0 +1,182 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+ import io
3
+ import json
4
+ import os
5
+ from pathlib import Path
6
+ from typing import Optional
7
+ import pandas as pd
8
+ import requests
9
+
10
+ class TaskFileTool:
11
+ """
12
+ Downloads and reads task-linked files from the Hugging Face
13
+ Unit 4 scoring API.
14
+
15
+ Supported text extration:
16
+ - txt
17
+ - csv
18
+ - json
19
+ - md
20
+ - html
21
+ - xml
22
+
23
+ For unsupported or binary files, it safely returns an empty string for now.
24
+ We can extend this later for PDF/images if needed.
25
+ """
26
+
27
+ def __init__(self, api_base_url: str, cache_dir:str = "task_files", timeout: int =30):
28
+ self.api_base_url = api_base_url.strip("/")
29
+ self.cache_dir = Path(cache_dir)
30
+ self.cache_dir.mkdir(parents=True, exist_ok=True)
31
+ self.timeout = timeout
32
+
33
+ def get_task_context(self, task_id: str) -> str:
34
+ """
35
+ Main entry point used by the agent:
36
+ 1. download the task file if present
37
+ 2. read it into text context if supported
38
+ """
39
+ file_path = self.download_task_file(task_id)
40
+ if file_path is None:
41
+ return ""
42
+ return self.read_file_as_text(file_path)
43
+
44
+ def download_task_file(self, task_id: str) -> Optional[Path]:
45
+ """
46
+ Downloads the file linked to a task_id using:
47
+ GET /files/{task_id}
48
+
49
+ Returns:
50
+ Path to saved file if successful, else None
51
+ """
52
+ url = f"{self.api_base_url}/file/{task_id}"
53
+
54
+ try:
55
+ response = requests.get(url, timeout=self.timeout)
56
+ except requests.RequestException:
57
+ return None
58
+
59
+ if response.status_code !=200:
60
+ return None
61
+
62
+ filename = self._infer_filename(response=response, task_id=task_id)
63
+ file_path = self.cache_dir / filename
64
+
65
+ try:
66
+ with open(file_path, "wb") as f:
67
+ f.write(response.content)
68
+ return file_path
69
+ except OSError:
70
+ return None
71
+ return file_path
72
+
73
+ def read_file_as_text(self, file_path: Path) -> str:
74
+ """
75
+ Reads supported file types into plain text.
76
+ """
77
+ suffix = file_path.suffix.lower()
78
+
79
+ try:
80
+ if suffix in {".txt", ".md", ".html", ".xml", ".csv", ".json"}:
81
+ return self._read_supported_text_file(file_path, suffix)
82
+
83
+ # common fallback for files saved without extension but actually text
84
+ if suffix == "":
85
+ return self._read_extensionless_file(file_path)
86
+
87
+ return ""
88
+ except Exception:
89
+ return ""
90
+
91
+ def _read_supported_text_file(self, file_path: Path, suffix: str) -> str:
92
+ if suffix in {".txt", ".md", ".html", ".xml"}:
93
+ return file_path.read_text(encoding="utf-8", errors="ignore")
94
+
95
+ if suffix == ".json":
96
+ raw = file_path.read_text(encoding="utf-8", errors="ignore")
97
+ try:
98
+ parsed = json.loads(raw)
99
+ return json.dumps(parsed, indent=2, ensure_ascii=False)
100
+ except json.JSONDecodeError:
101
+ return raw
102
+
103
+ if suffix == ".csv":
104
+ try:
105
+ df = pd.read_csv(file_path)
106
+ return df.to_csv(index=False)
107
+ except Exception:
108
+ return file_path.read_text(encoding="utf-8", errors="ignore")
109
+
110
+ return ""
111
+
112
+ def _read_extensionless_file(self, file_path: Path) -> str:
113
+ """
114
+ Try to interpret extensionless files as utf-8 text first.
115
+ """
116
+ try:
117
+ raw = file_path.read_text(encoding="utf-8", errors="ignore")
118
+ if raw.strip():
119
+ return raw
120
+ except Exception:
121
+ pass
122
+ return ""
123
+
124
+ def _infer_filename(self, response: requests.Response, task_id: str) -> str:
125
+ """
126
+ Attempts to infer a useful filename from headers.
127
+ Falls back to task_id if no filename is available.
128
+ """
129
+ content_disposition = response.headers.get("content-disposition", "")
130
+ filename = self._extract_filename_from_content_disposition(content_disposition)
131
+
132
+ if filename:
133
+ return self._safe_filename(filename)
134
+
135
+ content_type = response.headers.get("content-type", "").lower()
136
+ extension = self._extension_from_content_type(content_type)
137
+
138
+ if extension:
139
+ return f"{task_id}{extension}"
140
+
141
+ return str(task_id)
142
+
143
+ @staticmethod
144
+ def _extract_filename_from_content_disposition(content_disposition: str) -> Optional[str]:
145
+ """
146
+ Example header:
147
+ content-disposition: attachment; filename="example.csv"
148
+ """
149
+ if "filename=" not in content_disposition:
150
+ return None
151
+
152
+ try:
153
+ filename = content_disposition.split("filename=")[-1].strip().strip('"')
154
+ return filename or None
155
+ except Exception:
156
+ return None
157
+
158
+ @staticmethod
159
+ def _extension_from_content_type(content_type: str) -> str:
160
+ mapping = {
161
+ "text/plain": ".txt",
162
+ "text/csv": ".csv",
163
+ "application/csv": ".csv",
164
+ "application/json": ".json",
165
+ "text/markdown": ".md",
166
+ "text/html": ".html",
167
+ "application/xml": ".xml",
168
+ "text/xml": ".xml",
169
+ }
170
+
171
+ for key, ext in mapping.items():
172
+ if key in content_type:
173
+ return ext
174
+
175
+ return ""
176
+
177
+ @staticmethod
178
+ def _safe_filename(filename: str) -> str:
179
+ """
180
+ Prevent path traversal and weird path issues.
181
+ """
182
+ return os.path.basename(filename)
utils.py ADDED
@@ -0,0 +1,100 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import re
4
+
5
+
6
+ def extract_final_answer(text: str) -> str:
7
+ """
8
+ Extract the most likely final answer from raw model output.
9
+
10
+ In V1 we keep this conservative:
11
+ - if the model returns a normal short answer, keep it
12
+ - if it adds common prefixes like 'Answer:' or 'Final answer:', remove them
13
+ - if it returns multiple lines, prefer the last non-empty line
14
+ """
15
+ if text is None:
16
+ return ""
17
+
18
+ text = str(text).strip()
19
+ if not text:
20
+ return ""
21
+
22
+ # Remove fenced code blocks if the model wraps the answer oddly
23
+ text = re.sub(r"^```[a-zA-Z0-9_-]*\s*", "", text)
24
+ text = re.sub(r"\s*```$", "", text)
25
+
26
+ # Common exact-answer markers
27
+ marker_patterns = [
28
+ r"(?i)\bfinal answer\s*:\s*",
29
+ r"(?i)\banswer\s*:\s*",
30
+ r"(?i)\bthe answer is\s*:\s*",
31
+ r"(?i)\bthe answer is\s+",
32
+ ]
33
+
34
+ cleaned = text
35
+ for pattern in marker_patterns:
36
+ cleaned = re.sub(pattern, "", cleaned).strip()
37
+
38
+ # If multi-line, prefer the last meaningful line
39
+ lines = [line.strip() for line in cleaned.splitlines() if line.strip()]
40
+ if not lines:
41
+ return ""
42
+
43
+ if len(lines) == 1:
44
+ return lines[0]
45
+
46
+ return lines[-1]
47
+
48
+
49
+ def normalize_final_answer(text: str) -> str:
50
+ """
51
+ Normalize answer text for safer exact-match submission without being too aggressive.
52
+
53
+ Rules:
54
+ - trim outer whitespace
55
+ - collapse internal repeated whitespace
56
+ - remove wrapping quotes if they wrap the full answer
57
+ - remove a single trailing period only for plain word/phrase answers
58
+ but keep decimal numbers and date punctuation intact
59
+ """
60
+ if text is None:
61
+ return ""
62
+
63
+ text = str(text).strip()
64
+ if not text:
65
+ return ""
66
+
67
+ # Collapse repeated whitespace
68
+ text = re.sub(r"\s+", " ", text).strip()
69
+
70
+ # Remove matching surrounding quotes
71
+ if len(text) >= 2:
72
+ if (text[0] == text[-1]) and text[0] in {'"', "'"}:
73
+ text = text[1:-1].strip()
74
+
75
+ # Remove common leading labels again, just in case
76
+ text = re.sub(r"(?i)^(final answer|answer)\s*:\s*", "", text).strip()
77
+
78
+ # Remove one trailing period for simple phrase answers only
79
+ # Keep decimals like 3.14 intact
80
+ if text.endswith("."):
81
+ if not re.fullmatch(r"\d+\.\d+", text):
82
+ text = text[:-1].strip()
83
+
84
+ return text
85
+
86
+
87
+ def is_placeholder_answer(text: str) -> bool:
88
+ """
89
+ Detect placeholder/fallback outputs so app.py can optionally flag them.
90
+ """
91
+ if text is None:
92
+ return True
93
+
94
+ normalized = normalize_final_answer(text).lower()
95
+ return normalized in {
96
+ "",
97
+ "placeholder",
98
+ "n/a",
99
+ "unknown",
100
+ }