lethaq commited on
Commit
a68a46b
·
verified ·
1 Parent(s): 96680fc

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +61 -12
app.py CHANGED
@@ -24,6 +24,43 @@ from typing import List, Dict, Any, Optional
24
  from litellm import completion
25
  from duckduckgo_search import DDGS
26
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
27
  # --- Constants ---
28
  DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
29
  DEFAULT_USERNAME = "lethaq" # 默认用户名,您可以修改为您的用户名
@@ -52,6 +89,11 @@ class DuckDuckGoSearchTool:
52
  except Exception as e:
53
  print(f"DuckDuckGo search error: {e}")
54
  return [{"title": f"Search error: {e}", "body": "", "href": ""}]
 
 
 
 
 
55
 
56
  def __call__(self, query: str, max_results: int = 8) -> Dict[str, Any]:
57
  """
@@ -443,18 +485,25 @@ def run_and_submit_all():
443
  for item in questions_data:
444
  task_id = item.get("task_id")
445
  question_text = item.get("question")
446
- if not task_id or question_text is None:
447
- print(f"Skipping item with missing task_id or question: {item}")
448
- continue
449
- try:
450
- print(f"Processing task {task_id}: {question_text[:50]}...")
451
- submitted_answer = agent(question_text)
452
- answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
453
- results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
454
- print(f"Answer for task {task_id}: {submitted_answer[:50]}...")
455
- except Exception as e:
456
- print(f"Error running agent on task {task_id}: {e}")
457
- results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"})
 
 
 
 
 
 
 
458
 
459
  if not answers_payload:
460
  print("Agent did not produce any answers to submit.")
 
24
  from litellm import completion
25
  from duckduckgo_search import DDGS
26
 
27
+ # 用於獲取並解析附件
28
+ def fetch_and_summarize_attachment(task_id, question, files_api_url="https://agents-course-unit4-scoring.hf.space/files/"):
29
+ import pandas as pd, requests
30
+ q_lower = question.lower()
31
+ keywords = ["attached", "file", "excel", "csv", "spreadsheet", "audio", "mp3", "image", "picture", "python code", "code"]
32
+ if not any(k in q_lower for k in keywords):
33
+ return ""
34
+ try:
35
+ file_url = f"{files_api_url}{task_id}"
36
+ response = requests.get(file_url, timeout=10)
37
+ local_path = f"/tmp/{task_id}"
38
+ with open(local_path, "wb") as f:
39
+ f.write(response.content)
40
+ if local_path.endswith(".csv") or b"," in response.content[:512]:
41
+ df = pd.read_csv(local_path)
42
+ summary = df.head(10).to_string()
43
+ return f"[Attachment Detected: CSV Table]\nFirst 10 rows:\n{summary}\n"
44
+ elif local_path.endswith(".xls") or local_path.endswith(".xlsx"):
45
+ df = pd.read_excel(local_path)
46
+ summary = df.head(10).to_string()
47
+ return f"[Attachment Detected: Excel Table]\nFirst 10 rows:\n{summary}\n"
48
+ elif local_path.endswith(".txt") or b"\n" in response.content[:512]:
49
+ with open(local_path, "r", encoding="utf-8", errors="ignore") as f:
50
+ text = f.read(1000)
51
+ return f"[Attachment Detected: Text File]\n{text}\n"
52
+ elif local_path.endswith(".py"):
53
+ with open(local_path, "r", encoding="utf-8", errors="ignore") as f:
54
+ code = f.read(1000)
55
+ return f"[Attachment Detected: Python Code]\n{code}\n"
56
+ else:
57
+ return "[Attachment Detected, but file type not supported for summary]\n"
58
+ except Exception as e:
59
+ return f"[Attachment Error: {e}]\n"
60
+
61
+
62
+
63
+
64
  # --- Constants ---
65
  DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
66
  DEFAULT_USERNAME = "lethaq" # 默认用户名,您可以修改为您的用户名
 
89
  except Exception as e:
90
  print(f"DuckDuckGo search error: {e}")
91
  return [{"title": f"Search error: {e}", "body": "", "href": ""}]
92
+
93
+
94
+
95
+
96
+
97
 
98
  def __call__(self, query: str, max_results: int = 8) -> Dict[str, Any]:
99
  """
 
485
  for item in questions_data:
486
  task_id = item.get("task_id")
487
  question_text = item.get("question")
488
+ if not task_id or question_text is None:
489
+ print(f"Skipping item with missing task_id or question: {item}")
490
+ continue
491
+ try:
492
+ # Attachment 摘要插入
493
+ attachment_context = fetch_and_summarize_attachment(task_id, question_text)
494
+ # prompt(根據你的 agent 用法):
495
+ # (方案A)如果 agent 支援 attachment_context 參數
496
+ # submitted_answer = agent(question_text, attachment_context=attachment_context)
497
+ # (方案B)最直接:把 attachment 拼到問題開頭
498
+ full_question = (attachment_context + "\n" + question_text).strip()
499
+ submitted_answer = agent(full_question)
500
+ answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
501
+ results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
502
+ print(f"Answer for task {task_id}: {submitted_answer[:50]}...")
503
+ except Exception as e:
504
+ print(f"Error running agent on task {task_id}: {e}")
505
+ results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"})
506
+
507
 
508
  if not answers_payload:
509
  print("Agent did not produce any answers to submit.")