GT5557 commited on
Commit
ed8f742
Β·
verified Β·
1 Parent(s): ca8b11b

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +67 -17
app.py CHANGED
@@ -8,6 +8,7 @@ import time
8
  import threading
9
  import requests
10
  import pandas as pd
 
11
  import gradio as gr
12
 
13
  from langchain_core.messages import HumanMessage
@@ -30,7 +31,7 @@ DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
30
  # Single values β€” no per-difficulty branching
31
  TIMEOUT_SECONDS = 60
32
  RECURSION_LIMIT = 12
33
- PAUSE_SECONDS = 1.5
34
 
35
  # ==========================================================
36
  # LOGGING
@@ -104,28 +105,31 @@ def submit_answers(url: str, payload: dict) -> dict:
104
  return r.json()
105
 
106
 
107
- def fetch_task_file(task_id: str) -> str | None:
108
  """
109
- Try to download the file attached to a task from GET /files/{task_id}.
110
- Saves it to /tmp/<task_id>.<ext> and returns the local path.
111
- Returns None if the task has no attachment or the download fails.
 
 
112
  """
113
  url = f"{DEFAULT_API_URL}/files/{task_id}"
114
  try:
115
  r = requests.get(url, timeout=20)
116
  if r.status_code == 404:
117
- return None
 
118
  r.raise_for_status()
119
 
120
- # Determine extension from Content-Disposition or Content-Type
121
  ext = ""
122
  cd = r.headers.get("Content-Disposition", "")
123
  ct = r.headers.get("Content-Type", "")
124
 
125
  if "filename=" in cd:
126
- fname = cd.split("filename=")[-1].strip().strip('"')
127
- ext = os.path.splitext(fname)[-1]
128
- elif "spreadsheet" in ct or "excel" in ct:
129
  ext = ".xlsx"
130
  elif "csv" in ct:
131
  ext = ".csv"
@@ -135,8 +139,10 @@ def fetch_task_file(task_id: str) -> str | None:
135
  ext = ".png"
136
  elif "jpeg" in ct or "jpg" in ct:
137
  ext = ".jpg"
138
- elif "python" in ct or "text/plain" in ct:
139
  ext = ".py"
 
 
140
  else:
141
  ext = ""
142
 
@@ -144,12 +150,45 @@ def fetch_task_file(task_id: str) -> str | None:
144
  with open(local_path, "wb") as f:
145
  f.write(r.content)
146
 
147
- log(f"File : downloaded β†’ {local_path} ({len(r.content)} bytes)")
148
- return local_path
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
149
 
150
  except Exception as e:
151
  log(f"File : download failed β€” {e}")
152
- return None
153
 
154
  # ==========================================================
155
  # MAIN RUNNER
@@ -204,9 +243,20 @@ def run_and_submit_all(profile: gr.OAuthProfile | None):
204
  log(f"Question : {question[:200]}")
205
  log("-" * 80)
206
 
207
- # Download any attached file and append its path to the question
208
- file_path = fetch_task_file(task_id)
209
- if file_path:
 
 
 
 
 
 
 
 
 
 
 
210
  question = question + f"\n[ATTACHED FILE: {file_path}]"
211
 
212
  start = time.time()
 
8
  import threading
9
  import requests
10
  import pandas as pd
11
+ import pandas as pd
12
  import gradio as gr
13
 
14
  from langchain_core.messages import HumanMessage
 
31
  # Single values β€” no per-difficulty branching
32
  TIMEOUT_SECONDS = 60
33
  RECURSION_LIMIT = 12
34
+ PAUSE_SECONDS = 1.0
35
 
36
  # ==========================================================
37
  # LOGGING
 
105
  return r.json()
106
 
107
 
108
+ def fetch_task_file(task_id: str) -> tuple[str | None, str | None]:
109
  """
110
+ Download the file attached to a task from GET /files/{task_id}.
111
+ Returns (local_path, injected_text):
112
+ - local_path: saved file path (for binary files like .py the model runs directly)
113
+ - injected_text: pre-read text content to inject into the question (for Excel/CSV)
114
+ Returns (None, None) if no attachment exists.
115
  """
116
  url = f"{DEFAULT_API_URL}/files/{task_id}"
117
  try:
118
  r = requests.get(url, timeout=20)
119
  if r.status_code == 404:
120
+ log("File : no attachment (404)")
121
+ return None, None
122
  r.raise_for_status()
123
 
124
+ # Determine extension
125
  ext = ""
126
  cd = r.headers.get("Content-Disposition", "")
127
  ct = r.headers.get("Content-Type", "")
128
 
129
  if "filename=" in cd:
130
+ raw_name = cd.split("filename=")[-1].strip().strip('"').strip("'")
131
+ ext = os.path.splitext(raw_name)[-1].lower()
132
+ elif "spreadsheet" in ct or "excel" in ct or "openxmlformats" in ct:
133
  ext = ".xlsx"
134
  elif "csv" in ct:
135
  ext = ".csv"
 
139
  ext = ".png"
140
  elif "jpeg" in ct or "jpg" in ct:
141
  ext = ".jpg"
142
+ elif "python" in ct:
143
  ext = ".py"
144
+ elif "text/plain" in ct:
145
+ ext = ".txt"
146
  else:
147
  ext = ""
148
 
 
150
  with open(local_path, "wb") as f:
151
  f.write(r.content)
152
 
153
+ log(f"File : downloaded β†’ {local_path} ({len(r.content)} bytes, type={ext})")
154
+
155
+ # For Excel/CSV: read with pandas and inject as text β€” don't rely on
156
+ # the model downloading it again inside run_python.
157
+ injected_text = None
158
+ if ext in (".xlsx", ".xls"):
159
+ try:
160
+ import pandas as pd
161
+ dfs = pd.read_excel(local_path, sheet_name=None)
162
+ parts = []
163
+ for sheet, df in dfs.items():
164
+ parts.append(f"=== Sheet: {sheet} ===\n{df.to_csv(index=False)}")
165
+ injected_text = "\n\n".join(parts)[:6000]
166
+ log(f"File : Excel read OK β€” {sum(len(d) for d in dfs.values())} rows total")
167
+ except Exception as e:
168
+ log(f"File : Excel read failed β€” {e}")
169
+
170
+ elif ext == ".csv":
171
+ try:
172
+ import pandas as pd
173
+ df = pd.read_csv(local_path)
174
+ injected_text = df.to_csv(index=False)[:6000]
175
+ log(f"File : CSV read OK β€” {len(df)} rows")
176
+ except Exception as e:
177
+ log(f"File : CSV read failed β€” {e}")
178
+
179
+ elif ext in (".py", ".txt"):
180
+ try:
181
+ with open(local_path, "r", errors="replace") as f:
182
+ injected_text = f.read()[:4000]
183
+ log(f"File : text read OK")
184
+ except Exception as e:
185
+ log(f"File : text read failed β€” {e}")
186
+
187
+ return local_path, injected_text
188
 
189
  except Exception as e:
190
  log(f"File : download failed β€” {e}")
191
+ return None, None
192
 
193
  # ==========================================================
194
  # MAIN RUNNER
 
243
  log(f"Question : {question[:200]}")
244
  log("-" * 80)
245
 
246
+ # Download any attached file and inject content into the question
247
+ file_path, injected_text = fetch_task_file(task_id)
248
+ if injected_text:
249
+ # For Excel/CSV/text: embed the content directly so the model
250
+ # doesn't need to re-download anything
251
+ ext = os.path.splitext(file_path)[-1].lower() if file_path else ""
252
+ if ext in (".xlsx", ".xls", ".csv"):
253
+ question = question + f"\n\n[ATTACHED FILE DATA β€” use this for calculations, do NOT try to re-read the file]:\n{injected_text}"
254
+ elif ext in (".py", ".txt"):
255
+ question = question + f"\n\n[ATTACHED FILE CONTENT β€” this is the file to process]:\n{injected_text}"
256
+ else:
257
+ question = question + f"\n[ATTACHED FILE: {file_path}]"
258
+ elif file_path:
259
+ # Binary files (images, PDF) β€” just pass the path
260
  question = question + f"\n[ATTACHED FILE: {file_path}]"
261
 
262
  start = time.time()