GT5557 commited on
Commit
460477d
·
verified ·
1 Parent(s): 7da1e13

Upload app.py

Browse files
Files changed (1) hide show
  1. app.py +1 -113
app.py CHANGED
@@ -8,7 +8,6 @@ import 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
@@ -104,101 +103,6 @@ def submit_answers(url: str, payload: dict) -> dict:
104
  r.raise_for_status()
105
  return r.json()
106
 
107
-
108
- def fetch_task_file(task_id: str, question: str = "") -> tuple[str | None, str | None]:
109
- """
110
- Download the file attached to a task from GET /files/{task_id}.
111
- If that fails, search the question text for embedded file content or links.
112
- Returns (local_path, injected_text):
113
- - local_path: saved file path (for binary files like .py the model runs directly)
114
- - injected_text: pre-read text content to inject into the question (for Excel/CSV)
115
- Returns (None, None) if no attachment exists.
116
- """
117
- url = f"{DEFAULT_API_URL}/files/{task_id}"
118
- try:
119
- r = requests.get(url, timeout=20)
120
- if r.status_code == 404:
121
- log(f"File : endpoint /files/{task_id} returned 404 — trying alternate patterns")
122
- # Fallback: try query param format
123
- url2 = f"{DEFAULT_API_URL}/files?task_id={task_id}"
124
- try:
125
- r = requests.get(url2, timeout=20)
126
- if r.status_code != 200:
127
- log(f"File : no attachment found (both endpoints failed)")
128
- return None, None
129
- except Exception as e:
130
- log(f"File : fallback endpoint also failed — {e}")
131
- return None, None
132
-
133
- r.raise_for_status()
134
-
135
- # Determine extension
136
- ext = ""
137
- cd = r.headers.get("Content-Disposition", "")
138
- ct = r.headers.get("Content-Type", "")
139
-
140
- if "filename=" in cd:
141
- raw_name = cd.split("filename=")[-1].strip().strip('"').strip("'")
142
- ext = os.path.splitext(raw_name)[-1].lower()
143
- elif "spreadsheet" in ct or "excel" in ct or "openxmlformats" in ct:
144
- ext = ".xlsx"
145
- elif "csv" in ct:
146
- ext = ".csv"
147
- elif "pdf" in ct:
148
- ext = ".pdf"
149
- elif "png" in ct:
150
- ext = ".png"
151
- elif "jpeg" in ct or "jpg" in ct:
152
- ext = ".jpg"
153
- elif "python" in ct or "text/plain" in ct:
154
- ext = ".py"
155
- else:
156
- ext = ""
157
-
158
- local_path = f"/tmp/{task_id}{ext}"
159
- with open(local_path, "wb") as f:
160
- f.write(r.content)
161
-
162
- log(f"File : downloaded → {local_path} ({len(r.content)} bytes, type={ext})")
163
-
164
- # For Excel/CSV: read with pandas and inject as text — don't rely on
165
- # the model downloading it again inside run_python.
166
- injected_text = None
167
- if ext in (".xlsx", ".xls"):
168
- try:
169
- import pandas as pd
170
- dfs = pd.read_excel(local_path, sheet_name=None)
171
- parts = []
172
- for sheet, df in dfs.items():
173
- parts.append(f"=== Sheet: {sheet} ===\n{df.to_csv(index=False)}")
174
- injected_text = "\n\n".join(parts)[:6000]
175
- log(f"File : Excel read OK — {sum(len(d) for d in dfs.values())} rows total")
176
- except Exception as e:
177
- log(f"File : Excel read failed — {e}")
178
-
179
- elif ext == ".csv":
180
- try:
181
- import pandas as pd
182
- df = pd.read_csv(local_path)
183
- injected_text = df.to_csv(index=False)[:6000]
184
- log(f"File : CSV read OK — {len(df)} rows")
185
- except Exception as e:
186
- log(f"File : CSV read failed — {e}")
187
-
188
- elif ext in (".py", ".txt"):
189
- try:
190
- with open(local_path, "r", errors="replace") as f:
191
- injected_text = f.read()[:4000]
192
- log(f"File : text read OK")
193
- except Exception as e:
194
- log(f"File : text read failed — {e}")
195
-
196
- return local_path, injected_text
197
-
198
- except Exception as e:
199
- log(f"File : download failed — {e}")
200
- return None, None
201
-
202
  # ==========================================================
203
  # MAIN RUNNER
204
  # ==========================================================
@@ -252,22 +156,6 @@ def run_and_submit_all(profile: gr.OAuthProfile | None):
252
  log(f"Question : {question[:200]}")
253
  log("-" * 80)
254
 
255
- # Download any attached file and inject content into the question
256
- file_path, injected_text = fetch_task_file(task_id, question)
257
- if injected_text:
258
- # For Excel/CSV/text: embed the content directly so the model
259
- # doesn't need to re-download anything
260
- ext = os.path.splitext(file_path)[-1].lower() if file_path else ""
261
- if ext in (".xlsx", ".xls", ".csv"):
262
- question = question + f"\n\n[ATTACHED FILE DATA — use this for calculations, do NOT try to re-read the file]:\n{injected_text}"
263
- elif ext in (".py", ".txt"):
264
- question = question + f"\n\n[ATTACHED FILE CONTENT — this is the file to process]:\n{injected_text}"
265
- else:
266
- question = question + f"\n[ATTACHED FILE: {file_path}]"
267
- elif file_path:
268
- # Binary files (images, PDF) — just pass the path
269
- question = question + f"\n[ATTACHED FILE: {file_path}]"
270
-
271
  start = time.time()
272
  submitted_answer = "N/A"
273
  tools_used: list[str] = []
@@ -391,4 +279,4 @@ with gr.Blocks() as demo:
391
  # ==========================================================
392
 
393
  if __name__ == "__main__":
394
- demo.launch(debug=True, ssr_mode=False)
 
8
  import threading
9
  import requests
10
  import pandas as pd
 
11
  import gradio as gr
12
 
13
  from langchain_core.messages import HumanMessage
 
103
  r.raise_for_status()
104
  return r.json()
105
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
106
  # ==========================================================
107
  # MAIN RUNNER
108
  # ==========================================================
 
156
  log(f"Question : {question[:200]}")
157
  log("-" * 80)
158
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
159
  start = time.time()
160
  submitted_answer = "N/A"
161
  tools_used: list[str] = []
 
279
  # ==========================================================
280
 
281
  if __name__ == "__main__":
282
+ demo.launch(debug=True, ssr_mode=False)