Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -15,12 +15,14 @@ from ddgs import DDGS
|
|
| 15 |
DEFAULT_API_URL = "https://hf.space"
|
| 16 |
MODEL_ID = "Qwen/Qwen2.5-7B-Instruct"
|
| 17 |
|
|
|
|
| 18 |
tokenizer = AutoTokenizer.from_pretrained(MODEL_ID)
|
| 19 |
model = AutoModelForCausalLM.from_pretrained(
|
| 20 |
MODEL_ID,
|
| 21 |
torch_dtype=torch.bfloat16,
|
| 22 |
device_map="auto",
|
| 23 |
)
|
|
|
|
| 24 |
|
| 25 |
def download_file(task_id: str, file_name: str) -> str | None:
|
| 26 |
if not file_name:
|
|
@@ -41,20 +43,32 @@ def read_non_audio_file(file_path: str) -> str:
|
|
| 41 |
if not file_path or not os.path.exists(file_path):
|
| 42 |
return ""
|
| 43 |
ext = os.path.splitext(file_path)[1].lower()
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
|
|
|
|
|
|
|
|
|
| 55 |
return f"[Attached file: {os.path.basename(file_path)}]"
|
| 56 |
|
| 57 |
-
def
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 58 |
snippets = []
|
| 59 |
try:
|
| 60 |
ddg_results = DDGS().text(query, max_results=4, backend="lite")
|
|
@@ -65,20 +79,20 @@ def search_web_and_wiki(query: str) -> str:
|
|
| 65 |
try:
|
| 66 |
titles = wikipedia.search(query, results=2)
|
| 67 |
for title in titles:
|
| 68 |
-
summary = wikipedia.summary(title, sentences=
|
| 69 |
snippets.append(f"[Wikipedia: {title}] {summary}")
|
| 70 |
except Exception:
|
| 71 |
pass
|
| 72 |
return "\n".join(snippets)
|
| 73 |
|
| 74 |
SYSTEM_PROMPT = """You are an expert AI assistant solving GAIA benchmark questions.
|
| 75 |
-
Think step-by-step
|
| 76 |
|
| 77 |
STRICT FORMATTING RULES FOR FINAL_ANSWER:
|
| 78 |
-
- Output ONLY the raw answer after 'FINAL_ANSWER: ' with no
|
| 79 |
- If a number is requested, write only digits (e.g., FINAL_ANSWER: 42).
|
| 80 |
-
- If USD with two decimal places is requested, write e.g. FINAL_ANSWER: 123.45
|
| 81 |
-
- If a comma-separated list is requested, follow exact alphabetical
|
| 82 |
"""
|
| 83 |
|
| 84 |
def extract_final_answer(raw_text: str) -> str:
|
|
@@ -90,35 +104,17 @@ def extract_final_answer(raw_text: str) -> str:
|
|
| 90 |
|
| 91 |
@spaces.GPU(duration=180)
|
| 92 |
def process_all_on_gpu(items_with_files: list[dict]) -> list[str]:
|
| 93 |
-
|
| 94 |
-
|
| 95 |
for entry in items_with_files:
|
| 96 |
fp = entry.get("file_path")
|
| 97 |
if fp and fp.lower().endswith(".mp3"):
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
|
|
|
| 102 |
|
| 103 |
-
# 2. Generate short search queries for text questions that don't have attached files
|
| 104 |
-
for entry in items_with_files:
|
| 105 |
-
if not entry.get("file_path"):
|
| 106 |
-
q_messages = [
|
| 107 |
-
{"role": "system", "content": "Extract a concise 4-7 word web search query to answer the user's question. Reply with ONLY the search query."},
|
| 108 |
-
{"role": "user", "content": entry["question"]},
|
| 109 |
-
]
|
| 110 |
-
q_text = tokenizer.apply_chat_template(q_messages, tokenize=False, add_generation_prompt=True)
|
| 111 |
-
q_in = tokenizer([q_text], return_tensors="pt").to("cuda")
|
| 112 |
-
with torch.no_grad():
|
| 113 |
-
q_out = model.generate(**q_in, max_new_tokens=24, do_sample=False)
|
| 114 |
-
clean_query = tokenizer.decode(q_out[q_in.input_ids.shape:], skip_special_tokens=True).strip().strip('"')
|
| 115 |
-
web_ctx = search_web_and_wiki(clean_query)
|
| 116 |
-
if web_ctx:
|
| 117 |
-
entry["context"] += f"\n\nSearch Results for '{clean_query}':\n{web_ctx}"
|
| 118 |
-
|
| 119 |
-
# 3. Solve each question with chain-of-thought and extract FINAL_ANSWER
|
| 120 |
-
answers = []
|
| 121 |
-
for entry in items_with_files:
|
| 122 |
user_prompt = entry["question"]
|
| 123 |
if entry["context"]:
|
| 124 |
user_prompt += f"\n\n--- Supporting Context ---\n{entry['context']}"
|
|
@@ -131,9 +127,10 @@ def process_all_on_gpu(items_with_files: list[dict]) -> list[str]:
|
|
| 131 |
inputs = tokenizer([text], return_tensors="pt").to("cuda")
|
| 132 |
|
| 133 |
with torch.no_grad():
|
| 134 |
-
outputs = model.generate(**inputs, max_new_tokens=
|
| 135 |
|
| 136 |
-
|
|
|
|
| 137 |
answers.append(extract_final_answer(raw_response))
|
| 138 |
|
| 139 |
return answers
|
|
@@ -163,7 +160,7 @@ def run_and_submit_all(profile: gr.OAuthProfile | None):
|
|
| 163 |
if not questions_data:
|
| 164 |
return "Error: Could not load questions.", None
|
| 165 |
|
| 166 |
-
# Download
|
| 167 |
prepared_items = []
|
| 168 |
for item in questions_data:
|
| 169 |
task_id = item.get("task_id")
|
|
@@ -172,12 +169,12 @@ def run_and_submit_all(profile: gr.OAuthProfile | None):
|
|
| 172 |
if not task_id or question_text is None:
|
| 173 |
continue
|
| 174 |
fp = download_file(task_id, file_name)
|
| 175 |
-
|
| 176 |
prepared_items.append({
|
| 177 |
"task_id": task_id,
|
| 178 |
"question": question_text,
|
| 179 |
"file_path": fp,
|
| 180 |
-
"context":
|
| 181 |
})
|
| 182 |
|
| 183 |
try:
|
|
@@ -204,6 +201,8 @@ def run_and_submit_all(profile: gr.OAuthProfile | None):
|
|
| 204 |
f"Message: {result_data.get('message', 'No message received.')}"
|
| 205 |
)
|
| 206 |
return final_status, pd.DataFrame(results_log)
|
|
|
|
|
|
|
| 207 |
except Exception as e:
|
| 208 |
return f"Submission Failed: {e}", pd.DataFrame(results_log)
|
| 209 |
|
|
|
|
| 15 |
DEFAULT_API_URL = "https://hf.space"
|
| 16 |
MODEL_ID = "Qwen/Qwen2.5-7B-Instruct"
|
| 17 |
|
| 18 |
+
# Load models at startup so GPU time is used only for inference
|
| 19 |
tokenizer = AutoTokenizer.from_pretrained(MODEL_ID)
|
| 20 |
model = AutoModelForCausalLM.from_pretrained(
|
| 21 |
MODEL_ID,
|
| 22 |
torch_dtype=torch.bfloat16,
|
| 23 |
device_map="auto",
|
| 24 |
)
|
| 25 |
+
asr_pipe = pipeline("automatic-speech-recognition", model="openai/whisper-small")
|
| 26 |
|
| 27 |
def download_file(task_id: str, file_name: str) -> str | None:
|
| 28 |
if not file_name:
|
|
|
|
| 43 |
if not file_path or not os.path.exists(file_path):
|
| 44 |
return ""
|
| 45 |
ext = os.path.splitext(file_path)[1].lower()
|
| 46 |
+
try:
|
| 47 |
+
if ext == ".py":
|
| 48 |
+
res = subprocess.run(["python3", file_path], capture_output=True, text=True, timeout=15)
|
| 49 |
+
with open(file_path, "r", encoding="utf-8") as f:
|
| 50 |
+
code = f.read()
|
| 51 |
+
return f"Python Code:\n{code}\n\nExact Execution Output:\n{res.stdout.strip()}"
|
| 52 |
+
elif ext in [".xlsx", ".xls"]:
|
| 53 |
+
df = pd.read_excel(file_path)
|
| 54 |
+
return f"Excel Table Contents:\n{df.to_string(index=False)}"
|
| 55 |
+
elif ext in [".txt", ".csv", ".json"]:
|
| 56 |
+
with open(file_path, "r", encoding="utf-8", errors="ignore") as f:
|
| 57 |
+
return f.read()[:6000]
|
| 58 |
+
except Exception as e:
|
| 59 |
+
return f"File read error: {e}"
|
| 60 |
return f"[Attached file: {os.path.basename(file_path)}]"
|
| 61 |
|
| 62 |
+
def build_clean_query(question: str) -> str:
|
| 63 |
+
# Strip conversational filler so DuckDuckGo & Wikipedia return exact hits
|
| 64 |
+
q = re.sub(r"https?://\S+", "", question)
|
| 65 |
+
words = [w for w in re.findall(r"[A-Za-z0-9'-]+", q) if len(w) > 2]
|
| 66 |
+
return " ".join(words[:10])
|
| 67 |
+
|
| 68 |
+
def search_web_and_wiki(question: str) -> str:
|
| 69 |
+
query = build_clean_query(question)
|
| 70 |
+
if not query:
|
| 71 |
+
return ""
|
| 72 |
snippets = []
|
| 73 |
try:
|
| 74 |
ddg_results = DDGS().text(query, max_results=4, backend="lite")
|
|
|
|
| 79 |
try:
|
| 80 |
titles = wikipedia.search(query, results=2)
|
| 81 |
for title in titles:
|
| 82 |
+
summary = wikipedia.summary(title, sentences=4, auto_suggest=False)
|
| 83 |
snippets.append(f"[Wikipedia: {title}] {summary}")
|
| 84 |
except Exception:
|
| 85 |
pass
|
| 86 |
return "\n".join(snippets)
|
| 87 |
|
| 88 |
SYSTEM_PROMPT = """You are an expert AI assistant solving GAIA benchmark questions.
|
| 89 |
+
Think step-by-step concisely, then output the exact final answer on the very last line prefixed with 'FINAL_ANSWER: '.
|
| 90 |
|
| 91 |
STRICT FORMATTING RULES FOR FINAL_ANSWER:
|
| 92 |
+
- Output ONLY the raw answer after 'FINAL_ANSWER: ' with no trailing period, no extra words, and no units unless asked.
|
| 93 |
- If a number is requested, write only digits (e.g., FINAL_ANSWER: 42).
|
| 94 |
+
- If USD with two decimal places is requested, write e.g. FINAL_ANSWER: 123.45.
|
| 95 |
+
- If a comma-separated list is requested, follow exact alphabetical or ascending order and spacing (e.g., FINAL_ANSWER: apple, banana).
|
| 96 |
"""
|
| 97 |
|
| 98 |
def extract_final_answer(raw_text: str) -> str:
|
|
|
|
| 104 |
|
| 105 |
@spaces.GPU(duration=180)
|
| 106 |
def process_all_on_gpu(items_with_files: list[dict]) -> list[str]:
|
| 107 |
+
asr_pipe.model.to("cuda")
|
| 108 |
+
answers = []
|
| 109 |
for entry in items_with_files:
|
| 110 |
fp = entry.get("file_path")
|
| 111 |
if fp and fp.lower().endswith(".mp3"):
|
| 112 |
+
try:
|
| 113 |
+
transcript = asr_pipe(fp)["text"]
|
| 114 |
+
entry["context"] += f"\n\nAudio Transcript ({os.path.basename(fp)}):\n{transcript}"
|
| 115 |
+
except Exception as e:
|
| 116 |
+
entry["context"] += f"\n\nAudio error: {e}"
|
| 117 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 118 |
user_prompt = entry["question"]
|
| 119 |
if entry["context"]:
|
| 120 |
user_prompt += f"\n\n--- Supporting Context ---\n{entry['context']}"
|
|
|
|
| 127 |
inputs = tokenizer([text], return_tensors="pt").to("cuda")
|
| 128 |
|
| 129 |
with torch.no_grad():
|
| 130 |
+
outputs = model.generate(**inputs, max_new_tokens=200, do_sample=False)
|
| 131 |
|
| 132 |
+
generated_tokens = outputs[0][inputs.input_ids.shape[1]:]
|
| 133 |
+
raw_response = tokenizer.decode(generated_tokens, skip_special_tokens=True)
|
| 134 |
answers.append(extract_final_answer(raw_response))
|
| 135 |
|
| 136 |
return answers
|
|
|
|
| 160 |
if not questions_data:
|
| 161 |
return "Error: Could not load questions.", None
|
| 162 |
|
| 163 |
+
# Download files & gather web/wiki search context on CPU first
|
| 164 |
prepared_items = []
|
| 165 |
for item in questions_data:
|
| 166 |
task_id = item.get("task_id")
|
|
|
|
| 169 |
if not task_id or question_text is None:
|
| 170 |
continue
|
| 171 |
fp = download_file(task_id, file_name)
|
| 172 |
+
ctx = read_non_audio_file(fp) if fp else search_web_and_wiki(question_text)
|
| 173 |
prepared_items.append({
|
| 174 |
"task_id": task_id,
|
| 175 |
"question": question_text,
|
| 176 |
"file_path": fp,
|
| 177 |
+
"context": ctx,
|
| 178 |
})
|
| 179 |
|
| 180 |
try:
|
|
|
|
| 201 |
f"Message: {result_data.get('message', 'No message received.')}"
|
| 202 |
)
|
| 203 |
return final_status, pd.DataFrame(results_log)
|
| 204 |
+
except requests.exceptions.HTTPError as e:
|
| 205 |
+
return f"Submission Failed ({e.response.status_code}): {e.response.text[:500]}", pd.DataFrame(results_log)
|
| 206 |
except Exception as e:
|
| 207 |
return f"Submission Failed: {e}", pd.DataFrame(results_log)
|
| 208 |
|