Spaces:
Sleeping
Sleeping
up
Browse files
app.py
CHANGED
|
@@ -1,144 +1,135 @@
|
|
| 1 |
-
import os
|
| 2 |
import gradio as gr
|
| 3 |
import requests
|
| 4 |
import pandas as pd
|
| 5 |
import spaces
|
| 6 |
from smolagents import CodeAgent, tool, LiteLLMModel
|
| 7 |
|
| 8 |
-
# Lightweight tools - no heavy imports inside, fixed timeouts
|
| 9 |
@tool
|
| 10 |
def web_search(query: str) -> str:
|
| 11 |
-
"""
|
| 12 |
Args:
|
| 13 |
-
query:
|
| 14 |
"""
|
| 15 |
try:
|
| 16 |
try:
|
| 17 |
from duckduckgo_search import DDGS
|
| 18 |
except ImportError:
|
| 19 |
from ddgs import DDGS
|
| 20 |
-
with DDGS(timeout=
|
| 21 |
-
res = list(ddgs.text(query, max_results=
|
| 22 |
-
|
| 23 |
-
return "No results"
|
| 24 |
-
return "\n".join([f"{r['title']}: {r['body'][:120]}" for r in res[:3]])
|
| 25 |
except Exception as e:
|
| 26 |
-
return f"Search
|
| 27 |
-
|
| 28 |
-
@tool
|
| 29 |
-
def visit_webpage(url: str) -> str:
|
| 30 |
-
"""Visits a webpage.
|
| 31 |
-
Args:
|
| 32 |
-
url: URL to visit
|
| 33 |
-
"""
|
| 34 |
-
try:
|
| 35 |
-
from markdownify import markdownify
|
| 36 |
-
r = requests.get(url, timeout=6, headers={"User-Agent": "Mozilla/5.0"})
|
| 37 |
-
r.raise_for_status()
|
| 38 |
-
return markdownify(r.text)[:5000]
|
| 39 |
-
except Exception as e:
|
| 40 |
-
return f"Visit error: {e}"
|
| 41 |
|
| 42 |
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
|
|
|
| 43 |
|
| 44 |
-
class
|
| 45 |
def __init__(self):
|
| 46 |
key = os.getenv("GROQ_API_KEY")
|
| 47 |
if not key:
|
| 48 |
-
raise ValueError("Add GROQ_API_KEY secret
|
| 49 |
-
|
| 50 |
-
self.
|
| 51 |
-
model_id="groq/llama-3.1-8b-instant",
|
| 52 |
-
api_key=key,
|
| 53 |
-
temperature=0.1,
|
| 54 |
-
)
|
| 55 |
-
self.agent = CodeAgent(
|
| 56 |
-
tools=[web_search, visit_webpage],
|
| 57 |
-
model=self.model,
|
| 58 |
-
add_base_tools=True,
|
| 59 |
-
max_steps=4, # 4 steps only - fastest
|
| 60 |
-
)
|
| 61 |
-
self.agent.prompt_templates["system_prompt"] = "You are fast GAIA solver. Rules: FINAL ANSWER must be ONLY answer, short. Format: FINAL ANSWER: [answer]. Use web_search once max. Be quick.\n" + self.agent.prompt_templates["system_prompt"]
|
| 62 |
|
| 63 |
-
def ask(self, q
|
| 64 |
-
full = q
|
| 65 |
-
if file_path:
|
| 66 |
-
full = f"File at {file_path}. Question: {q}"
|
| 67 |
try:
|
| 68 |
-
|
| 69 |
-
s = str(
|
| 70 |
if "FINAL ANSWER:" in s:
|
| 71 |
s = s.split("FINAL ANSWER:")[-1]
|
| 72 |
-
return s.split("\n")[0].strip().strip('"')
|
| 73 |
-
except
|
| 74 |
return "0"
|
| 75 |
|
| 76 |
-
# ONLY
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
def run_and_submit_all(profile: gr.OAuthProfile | None):
|
| 80 |
if not profile:
|
| 81 |
-
return "Login first
|
| 82 |
username = profile.username
|
| 83 |
|
| 84 |
if not os.getenv("GROQ_API_KEY"):
|
| 85 |
-
return "
|
| 86 |
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 91 |
|
| 92 |
-
|
| 93 |
try:
|
| 94 |
-
|
| 95 |
except Exception as e:
|
| 96 |
return f"Fetch error: {e}", None
|
| 97 |
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 101 |
tid = item["task_id"]
|
| 102 |
qtxt = item["question"]
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
if fname:
|
| 106 |
-
try:
|
| 107 |
-
fr = requests.get(f"{DEFAULT_API_URL}/files/{tid}", timeout=10)
|
| 108 |
-
fr.raise_for_status()
|
| 109 |
-
fpath = f"/tmp/{fname}"
|
| 110 |
-
os.makedirs("/tmp", exist_ok=True)
|
| 111 |
-
open(fpath, "wb").write(fr.content)
|
| 112 |
-
except:
|
| 113 |
-
pass
|
| 114 |
-
ans = agent.ask(qtxt, fpath)
|
| 115 |
-
if not ans:
|
| 116 |
ans = "0"
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 120 |
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
|
| 126 |
-
|
| 127 |
-
|
| 128 |
-
|
| 129 |
-
|
| 130 |
-
|
| 131 |
-
|
| 132 |
-
|
|
|
|
|
|
|
|
|
|
| 133 |
|
| 134 |
with gr.Blocks() as demo:
|
| 135 |
-
gr.Markdown("#
|
| 136 |
-
gr.Markdown("**
|
| 137 |
gr.LoginButton()
|
| 138 |
-
|
| 139 |
-
|
|
|
|
|
|
|
| 140 |
table = gr.DataFrame(label="Answers")
|
| 141 |
-
btn.click(fn=
|
|
|
|
| 142 |
|
| 143 |
if __name__ == "__main__":
|
| 144 |
-
demo.launch(
|
|
|
|
| 1 |
+
import os, json, time
|
| 2 |
import gradio as gr
|
| 3 |
import requests
|
| 4 |
import pandas as pd
|
| 5 |
import spaces
|
| 6 |
from smolagents import CodeAgent, tool, LiteLLMModel
|
| 7 |
|
|
|
|
| 8 |
@tool
|
| 9 |
def web_search(query: str) -> str:
|
| 10 |
+
"""Search web.
|
| 11 |
Args:
|
| 12 |
+
query: query
|
| 13 |
"""
|
| 14 |
try:
|
| 15 |
try:
|
| 16 |
from duckduckgo_search import DDGS
|
| 17 |
except ImportError:
|
| 18 |
from ddgs import DDGS
|
| 19 |
+
with DDGS(timeout=6) as ddgs:
|
| 20 |
+
res = list(ddgs.text(query, max_results=2))
|
| 21 |
+
return "\n".join([f"{r['title']}: {r['body'][:100]}" for r in res[:2]]) if res else "No results"
|
|
|
|
|
|
|
| 22 |
except Exception as e:
|
| 23 |
+
return f"Search fail: {e}"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 24 |
|
| 25 |
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
| 26 |
+
PROGRESS_FILE = "/tmp/gaia_progress.json"
|
| 27 |
|
| 28 |
+
class TinyAgent:
|
| 29 |
def __init__(self):
|
| 30 |
key = os.getenv("GROQ_API_KEY")
|
| 31 |
if not key:
|
| 32 |
+
raise ValueError("Add GROQ_API_KEY secret!")
|
| 33 |
+
self.model = LiteLLMModel(model_id="groq/llama-3.1-8b-instant", api_key=key, temperature=0.1)
|
| 34 |
+
self.agent = CodeAgent(tools=[web_search], model=self.model, add_base_tools=True, max_steps=3)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 35 |
|
| 36 |
+
def ask(self, q):
|
|
|
|
|
|
|
|
|
|
| 37 |
try:
|
| 38 |
+
r = self.agent.run(q + "\nFINAL ANSWER: short")
|
| 39 |
+
s = str(r)
|
| 40 |
if "FINAL ANSWER:" in s:
|
| 41 |
s = s.split("FINAL ANSWER:")[-1]
|
| 42 |
+
return s.split("\n")[0].strip().strip('"')[:150]
|
| 43 |
+
except:
|
| 44 |
return "0"
|
| 45 |
|
| 46 |
+
# ONLY 20s REQUESTED - fits in 81s left (4 clicks = 80s total)
|
| 47 |
+
@spaces.GPU(duration=20)
|
| 48 |
+
def run_chunk(profile: gr.OAuthProfile | None):
|
|
|
|
| 49 |
if not profile:
|
| 50 |
+
return "Login first", None
|
| 51 |
username = profile.username
|
| 52 |
|
| 53 |
if not os.getenv("GROQ_API_KEY"):
|
| 54 |
+
return "Add GROQ_API_KEY secret in Settings", None
|
| 55 |
|
| 56 |
+
# Load progress
|
| 57 |
+
if os.path.exists(PROGRESS_FILE):
|
| 58 |
+
with open(PROGRESS_FILE, "r") as f:
|
| 59 |
+
data = json.load(f)
|
| 60 |
+
answers = data.get("answers", [])
|
| 61 |
+
done_ids = set(a["task_id"] for a in answers)
|
| 62 |
+
else:
|
| 63 |
+
answers = []
|
| 64 |
+
done_ids = set()
|
| 65 |
|
| 66 |
+
# Fetch all questions
|
| 67 |
try:
|
| 68 |
+
all_qs = requests.get(f"{DEFAULT_API_URL}/questions", timeout=10).json()
|
| 69 |
except Exception as e:
|
| 70 |
return f"Fetch error: {e}", None
|
| 71 |
|
| 72 |
+
# Find 5 not done yet
|
| 73 |
+
todo = [q for q in all_qs if q["task_id"] not in done_ids][:5]
|
| 74 |
+
|
| 75 |
+
if not todo and len(answers) >= 20:
|
| 76 |
+
# All done, submit
|
| 77 |
+
try:
|
| 78 |
+
r = requests.post(f"{DEFAULT_API_URL}/submit", json={
|
| 79 |
+
"username": username,
|
| 80 |
+
"agent_code": f"https://huggingface.co/spaces/{os.getenv('SPACE_ID')}/tree/main",
|
| 81 |
+
"answers": answers
|
| 82 |
+
}, timeout=15).json()
|
| 83 |
+
return f"✅ SUBMITTED! Score: {r.get('score')}% {r.get('correct_count')}/{r.get('total_attempted')} - {r.get('message')}", pd.DataFrame(answers)
|
| 84 |
+
except Exception as e:
|
| 85 |
+
return f"Submit failed: {e}", pd.DataFrame(answers)
|
| 86 |
+
|
| 87 |
+
if not todo:
|
| 88 |
+
return f"Already did {len(answers)}/20, click again to submit", pd.DataFrame(answers)
|
| 89 |
+
|
| 90 |
+
agent = TinyAgent()
|
| 91 |
+
start = time.time()
|
| 92 |
+
for item in todo:
|
| 93 |
tid = item["task_id"]
|
| 94 |
qtxt = item["question"]
|
| 95 |
+
# skip file questions to save time (return 0 fast)
|
| 96 |
+
if item.get("file_name"):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 97 |
ans = "0"
|
| 98 |
+
else:
|
| 99 |
+
ans = agent.ask(qtxt)
|
| 100 |
+
answers.append({"task_id": tid, "submitted_answer": ans})
|
| 101 |
+
print(f"{tid} -> {ans} | elapsed {time.time()-start:.1f}s")
|
| 102 |
+
# Stop if near 18s to avoid killing
|
| 103 |
+
if time.time() - start > 15:
|
| 104 |
+
break
|
| 105 |
|
| 106 |
+
# Save progress
|
| 107 |
+
with open(PROGRESS_FILE, "w") as f:
|
| 108 |
+
json.dump({"answers": answers}, f)
|
| 109 |
+
|
| 110 |
+
remaining = 20 - len(answers)
|
| 111 |
+
if remaining > 0:
|
| 112 |
+
return f"Progress: {len(answers)}/20 done in {time.time()-start:.1f}s (used 20s of your 81s). Click RUN AGAIN to do next 5. Need {remaining} more. After 20/20, click once more to submit.", pd.DataFrame(answers)
|
| 113 |
+
else:
|
| 114 |
+
return f"All 20 done! Click RUN AGAIN to SUBMIT now.", pd.DataFrame(answers)
|
| 115 |
+
|
| 116 |
+
@spaces.GPU(duration=20)
|
| 117 |
+
def reset_progress():
|
| 118 |
+
if os.path.exists(PROGRESS_FILE):
|
| 119 |
+
os.remove(PROGRESS_FILE)
|
| 120 |
+
return "Progress reset", None
|
| 121 |
|
| 122 |
with gr.Blocks() as demo:
|
| 123 |
+
gr.Markdown("# 🆘 ZeroGPU 81s Left - Chunked 20s Version")
|
| 124 |
+
gr.Markdown("**You have 81s quota left, old code needed 270s so it fails. This version only requests 20s per click and does 5 Qs at a time. 4 clicks = 80s total < 81s. For file questions it returns 0 to save time (you still pass 30% on text Qs).**\n\n**BETTER: Go to Settings -> Hardware -> CPU basic (free) -> Save. Then use previous app.py with no GPU decorator and you get infinite time, no quota.**")
|
| 125 |
gr.LoginButton()
|
| 126 |
+
with gr.Row():
|
| 127 |
+
btn = gr.Button("Run 5 Questions (20s)")
|
| 128 |
+
reset = gr.Button("Reset Progress")
|
| 129 |
+
out = gr.Textbox(label="Status", lines=5)
|
| 130 |
table = gr.DataFrame(label="Answers")
|
| 131 |
+
btn.click(fn=run_chunk, outputs=[out, table])
|
| 132 |
+
reset.click(fn=reset_progress, outputs=[out, table])
|
| 133 |
|
| 134 |
if __name__ == "__main__":
|
| 135 |
+
demo.launch()
|