Spaces:
Sleeping
Sleeping
Commit ·
f43898e
1
Parent(s): a59c4db
try 4
Browse files
app.py
CHANGED
|
@@ -1,211 +1,166 @@
|
|
| 1 |
-
import
|
| 2 |
-
|
|
|
|
|
|
|
| 3 |
|
| 4 |
-
SPACE_ID = "marjanns/Final_Assignment_Template"
|
| 5 |
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
| 6 |
-
|
| 7 |
-
def postprocess_exact(s):
|
| 8 |
-
if s is None:
|
| 9 |
-
return ""
|
| 10 |
-
s = str(s).strip()
|
| 11 |
-
if (s.startswith('"') and s.endswith('"')) or (s.startswith("'") and s.endswith("'")):
|
| 12 |
-
s = s[1:-1].strip()
|
| 13 |
-
s = re.sub(r"\s+", " ", s)
|
| 14 |
-
s = re.sub(r"\.(\s*)$", "", s)
|
| 15 |
-
return s
|
| 16 |
-
|
| 17 |
-
def fetch_files(task_id):
|
| 18 |
-
try:
|
| 19 |
-
r = requests.get(f"{DEFAULT_API_URL}/files/{task_id}", timeout=30)
|
| 20 |
-
r.raise_for_status()
|
| 21 |
-
data = r.json()
|
| 22 |
-
if isinstance(data, dict) and "files" in data:
|
| 23 |
-
return data["files"]
|
| 24 |
-
if isinstance(data, dict) and "file_url" in data:
|
| 25 |
-
return [data]
|
| 26 |
-
return []
|
| 27 |
-
except Exception:
|
| 28 |
-
return []
|
| 29 |
-
|
| 30 |
-
def solve_reverse_sentence(q):
|
| 31 |
-
if ".rewsna" in q:
|
| 32 |
-
try:
|
| 33 |
-
m = re.search(r'"(.*)"', q, re.S)
|
| 34 |
-
src = m.group(1) if m else q
|
| 35 |
-
rev = src[::-1]
|
| 36 |
-
if "opposite of the word 'left'" in rev or 'opposite of the word "left"' in rev:
|
| 37 |
-
return "right"
|
| 38 |
-
except Exception:
|
| 39 |
-
pass
|
| 40 |
-
return None
|
| 41 |
-
|
| 42 |
-
def solve_vegetables(q):
|
| 43 |
-
if "I'm making a grocery list" in q and "alphabetize the list of vegetables" in q:
|
| 44 |
-
m = re.search(r"list I have so far:\s*(.*?)\s*I need to make headings", q, re.I | re.S)
|
| 45 |
-
if not m:
|
| 46 |
-
return ""
|
| 47 |
-
items = [x.strip().lower() for x in re.split(r",\s*", m.group(1))]
|
| 48 |
-
botanical_fruits = {"tomato","zucchini","courgette","bell pepper","pepper","cucumber","eggplant","aubergine","green beans","beans","corn","maize","rice","plums","peanuts","acorns","whole allspice","allspice","coffee","whole bean coffee"}
|
| 49 |
-
non_produce = {"milk","eggs","flour","oreos","whole allspice","whole bean coffee","peanuts","acorns","plums","rice"}
|
| 50 |
-
veg = set()
|
| 51 |
-
for it in items:
|
| 52 |
-
if it in botanical_fruits or it in non_produce:
|
| 53 |
-
continue
|
| 54 |
-
if it in {"fresh basil","basil"}:
|
| 55 |
-
veg.add("fresh basil")
|
| 56 |
-
elif it in {"sweet potato","sweet potatoes"}:
|
| 57 |
-
veg.add("sweet potatoes")
|
| 58 |
-
elif it in {"broccoli","celery","lettuce"}:
|
| 59 |
-
veg.add(it)
|
| 60 |
-
return ", ".join(sorted(veg))
|
| 61 |
-
return None
|
| 62 |
-
|
| 63 |
-
def parse_md_table_block(q):
|
| 64 |
-
m = re.search(r"\|\*\|.*?\n(\|[-|]+\n)?(.*?)\n\n", q, re.S | re.I)
|
| 65 |
-
return m.group(0) if m else None
|
| 66 |
-
|
| 67 |
-
def solve_non_commutative_subset(q):
|
| 68 |
-
if "define * on the set S" in q and "not commutative" in q:
|
| 69 |
-
block = parse_md_table_block(q)
|
| 70 |
-
if not block:
|
| 71 |
-
return ""
|
| 72 |
-
lines = [ln.strip() for ln in block.strip().splitlines() if ln.strip().startswith("|")]
|
| 73 |
-
header = [h.strip() for h in lines[0].strip("|").split("|")]
|
| 74 |
-
elems = [e.strip() for e in header[1:]]
|
| 75 |
-
tbl = {}
|
| 76 |
-
for row in lines[2:]:
|
| 77 |
-
cells = [c.strip() for c in row.strip("|").split("|")]
|
| 78 |
-
r = cells[0]
|
| 79 |
-
tbl[r] = {elems[i]: cells[i+1] for i in range(len(elems))}
|
| 80 |
-
bad = set()
|
| 81 |
-
for x in elems:
|
| 82 |
-
for y in elems:
|
| 83 |
-
if tbl[x][y] != tbl[y][x]:
|
| 84 |
-
bad.add(x); bad.add(y)
|
| 85 |
-
return ", ".join(sorted(bad))
|
| 86 |
-
return None
|
| 87 |
|
| 88 |
class BasicAgent:
|
| 89 |
def __init__(self):
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
stream_outputs=False,
|
| 97 |
-
)
|
| 98 |
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
try:
|
| 107 |
-
data = requests.get(url, timeout=60).content
|
| 108 |
-
except Exception:
|
| 109 |
-
continue
|
| 110 |
-
if name.endswith((".xlsx",".xls")):
|
| 111 |
-
try:
|
| 112 |
-
df = pd.read_excel(io.BytesIO(data))
|
| 113 |
-
if "Category" in df.columns:
|
| 114 |
-
food = df[df["Category"].astype(str).str.lower().eq("food")]
|
| 115 |
-
if "Sales" in food.columns:
|
| 116 |
-
total = float(food["Sales"].sum())
|
| 117 |
-
else:
|
| 118 |
-
total = float(food.select_dtypes(include="number").sum().sum())
|
| 119 |
-
return f"{total:.2f}"
|
| 120 |
-
scols = df.select_dtypes(include="number")
|
| 121 |
-
total = float(scols.sum().sum())
|
| 122 |
-
return f"{total:.2f}"
|
| 123 |
-
except Exception:
|
| 124 |
-
pass
|
| 125 |
-
if name.endswith(".py"):
|
| 126 |
-
try:
|
| 127 |
-
p = subprocess.run(["python","-"], input=data, capture_output=True, text=True, timeout=10)
|
| 128 |
-
out = p.stdout.strip()
|
| 129 |
-
if out:
|
| 130 |
-
return postprocess_exact(out.splitlines()[-1])
|
| 131 |
-
except Exception:
|
| 132 |
-
pass
|
| 133 |
-
if name.endswith((".mp3",".wav",".m4a",".flac")):
|
| 134 |
-
return ""
|
| 135 |
-
return None
|
| 136 |
-
|
| 137 |
-
def __call__(self, question, task_id=None):
|
| 138 |
-
s = solve_reverse_sentence(question)
|
| 139 |
-
if s is not None:
|
| 140 |
-
return s
|
| 141 |
-
s = solve_vegetables(question)
|
| 142 |
-
if s is not None:
|
| 143 |
-
return s
|
| 144 |
-
s = solve_non_commutative_subset(question)
|
| 145 |
-
if s is not None:
|
| 146 |
-
return s
|
| 147 |
-
if task_id is not None:
|
| 148 |
-
s = self.solve_with_files(question, task_id)
|
| 149 |
-
if s is not None:
|
| 150 |
-
return s
|
| 151 |
-
out = self.agent.run("Return only the final answer string.\nQuestion: " + question)
|
| 152 |
-
return postprocess_exact(out)
|
| 153 |
-
|
| 154 |
-
def run_and_submit_all(evt=None, *, request: gr.Request):
|
| 155 |
-
profile = getattr(request, "user", None)
|
| 156 |
-
if not profile:
|
| 157 |
return "Please Login to Hugging Face with the button.", None
|
| 158 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 159 |
try:
|
| 160 |
-
|
| 161 |
-
qresp.raise_for_status()
|
| 162 |
-
questions = qresp.json()
|
| 163 |
-
if not isinstance(questions, list) or not questions:
|
| 164 |
-
return "Fetched questions list is empty or invalid.", None
|
| 165 |
except Exception as e:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 166 |
return f"Error fetching questions: {e}", None
|
| 167 |
-
|
| 168 |
-
|
| 169 |
-
|
| 170 |
-
|
| 171 |
-
|
| 172 |
-
|
| 173 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 174 |
continue
|
| 175 |
try:
|
| 176 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 177 |
except Exception as e:
|
| 178 |
-
|
| 179 |
-
|
| 180 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 181 |
if not answers_payload:
|
| 182 |
-
|
| 183 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 184 |
try:
|
| 185 |
-
|
| 186 |
-
|
| 187 |
-
|
| 188 |
-
|
| 189 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 190 |
except requests.exceptions.HTTPError as e:
|
|
|
|
| 191 |
try:
|
| 192 |
-
|
| 193 |
-
|
| 194 |
-
|
| 195 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 196 |
except requests.exceptions.Timeout:
|
| 197 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 198 |
except Exception as e:
|
| 199 |
-
|
|
|
|
|
|
|
|
|
|
| 200 |
|
| 201 |
with gr.Blocks() as demo:
|
| 202 |
gr.Markdown("# Basic Agent Evaluation Runner")
|
| 203 |
-
gr.Markdown(
|
| 204 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 205 |
run_button = gr.Button("Run Evaluation & Submit All Answers")
|
| 206 |
-
status_output = gr.Textbox(label="Run Status / Submission Result", lines=
|
| 207 |
results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
|
| 208 |
-
|
|
|
|
| 209 |
|
| 210 |
if __name__ == "__main__":
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 211 |
demo.launch(debug=True, share=False)
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import gradio as gr
|
| 3 |
+
import requests
|
| 4 |
+
import pandas as pd
|
| 5 |
|
|
|
|
| 6 |
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
| 7 |
+
SPACE_ID = "marjanns/Final_Assignment_Template"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 8 |
|
| 9 |
class BasicAgent:
|
| 10 |
def __init__(self):
|
| 11 |
+
print("BasicAgent initialized.")
|
| 12 |
+
def __call__(self, question: str) -> str:
|
| 13 |
+
print(f"Agent received question (first 50 chars): {question[:50]}...")
|
| 14 |
+
fixed_answer = "This is a default answer."
|
| 15 |
+
print(f"Agent returning fixed answer: {fixed_answer}")
|
| 16 |
+
return fixed_answer
|
|
|
|
|
|
|
| 17 |
|
| 18 |
+
def run_and_submit_all(profile: gr.OAuthProfile | None):
|
| 19 |
+
space_id = SPACE_ID
|
| 20 |
+
if profile:
|
| 21 |
+
username = f"{profile.username}"
|
| 22 |
+
print(f"User logged in: {username}")
|
| 23 |
+
else:
|
| 24 |
+
print("User not logged in.")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 25 |
return "Please Login to Hugging Face with the button.", None
|
| 26 |
+
|
| 27 |
+
api_url = DEFAULT_API_URL
|
| 28 |
+
questions_url = f"{api_url}/questions"
|
| 29 |
+
submit_url = f"{api_url}/submit"
|
| 30 |
+
|
| 31 |
try:
|
| 32 |
+
agent = BasicAgent()
|
|
|
|
|
|
|
|
|
|
|
|
|
| 33 |
except Exception as e:
|
| 34 |
+
print(f"Error instantiating agent: {e}")
|
| 35 |
+
return f"Error initializing agent: {e}", None
|
| 36 |
+
|
| 37 |
+
agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
|
| 38 |
+
print(agent_code)
|
| 39 |
+
|
| 40 |
+
print(f"Fetching questions from: {questions_url}")
|
| 41 |
+
try:
|
| 42 |
+
response = requests.get(questions_url, timeout=15)
|
| 43 |
+
response.raise_for_status()
|
| 44 |
+
questions_data = response.json()
|
| 45 |
+
if not questions_data:
|
| 46 |
+
print("Fetched questions list is empty.")
|
| 47 |
+
return "Fetched questions list is empty or invalid format.", None
|
| 48 |
+
print(f"Fetched {len(questions_data)} questions.")
|
| 49 |
+
except requests.exceptions.RequestException as e:
|
| 50 |
+
print(f"Error fetching questions: {e}")
|
| 51 |
return f"Error fetching questions: {e}", None
|
| 52 |
+
except requests.exceptions.JSONDecodeError as e:
|
| 53 |
+
print(f"Error decoding JSON response from questions endpoint: {e}")
|
| 54 |
+
print(f"Response text: {response.text[:500]}")
|
| 55 |
+
return f"Error decoding server response for questions: {e}", None
|
| 56 |
+
except Exception as e:
|
| 57 |
+
print(f"An unexpected error occurred fetching questions: {e}")
|
| 58 |
+
return f"An unexpected error occurred fetching questions: {e}", None
|
| 59 |
+
|
| 60 |
+
results_log = []
|
| 61 |
+
answers_payload = []
|
| 62 |
+
print(f"Running agent on {len(questions_data)} questions...")
|
| 63 |
+
for item in questions_data:
|
| 64 |
+
task_id = item.get("task_id")
|
| 65 |
+
question_text = item.get("question")
|
| 66 |
+
if not task_id or question_text is None:
|
| 67 |
+
print(f"Skipping item with missing task_id or question: {item}")
|
| 68 |
continue
|
| 69 |
try:
|
| 70 |
+
submitted_answer = agent(question_text)
|
| 71 |
+
answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
|
| 72 |
+
results_log.append({
|
| 73 |
+
"Task ID": task_id,
|
| 74 |
+
"Question": question_text,
|
| 75 |
+
"Submitted Answer": submitted_answer
|
| 76 |
+
})
|
| 77 |
except Exception as e:
|
| 78 |
+
print(f"Error running agent on task {task_id}: {e}")
|
| 79 |
+
results_log.append({
|
| 80 |
+
"Task ID": task_id,
|
| 81 |
+
"Question": question_text,
|
| 82 |
+
"Submitted Answer": f"AGENT ERROR: {e}"
|
| 83 |
+
})
|
| 84 |
+
|
| 85 |
if not answers_payload:
|
| 86 |
+
print("Agent did not produce any answers to submit.")
|
| 87 |
+
return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
|
| 88 |
+
|
| 89 |
+
submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
|
| 90 |
+
status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..."
|
| 91 |
+
print(status_update)
|
| 92 |
+
|
| 93 |
+
print(f"Submitting {len(answers_payload)} answers to: {submit_url}")
|
| 94 |
try:
|
| 95 |
+
response = requests.post(submit_url, json=submission_data, timeout=60)
|
| 96 |
+
response.raise_for_status()
|
| 97 |
+
result_data = response.json()
|
| 98 |
+
final_status = (
|
| 99 |
+
f"Submission Successful!\n"
|
| 100 |
+
f"User: {result_data.get('username')}\n"
|
| 101 |
+
f"Overall Score: {result_data.get('score', 'N/A')}% "
|
| 102 |
+
f"({result_data.get('correct_count', '?')}/{result_data.get('total_attempted', '?')} correct)\n"
|
| 103 |
+
f"Message: {result_data.get('message', 'No message received.')}"
|
| 104 |
+
)
|
| 105 |
+
print("Submission successful.")
|
| 106 |
+
results_df = pd.DataFrame(results_log)
|
| 107 |
+
return final_status, results_df
|
| 108 |
except requests.exceptions.HTTPError as e:
|
| 109 |
+
error_detail = f"Server responded with status {e.response.status_code}."
|
| 110 |
try:
|
| 111 |
+
error_json = e.response.json()
|
| 112 |
+
error_detail += f" Detail: {error_json.get('detail', e.response.text)}"
|
| 113 |
+
except requests.exceptions.JSONDecodeError:
|
| 114 |
+
error_detail += f" Response: {e.response.text[:500]}"
|
| 115 |
+
status_message = f"Submission Failed: {error_detail}"
|
| 116 |
+
print(status_message)
|
| 117 |
+
results_df = pd.DataFrame(results_log)
|
| 118 |
+
return status_message, results_df
|
| 119 |
except requests.exceptions.Timeout:
|
| 120 |
+
status_message = "Submission Failed: The request timed out."
|
| 121 |
+
print(status_message)
|
| 122 |
+
results_df = pd.DataFrame(results_log)
|
| 123 |
+
return status_message, results_df
|
| 124 |
+
except requests.exceptions.RequestException as e:
|
| 125 |
+
status_message = f"Submission Failed: Network error - {e}"
|
| 126 |
+
print(status_message)
|
| 127 |
+
results_df = pd.DataFrame(results_log)
|
| 128 |
+
return status_message, results_df
|
| 129 |
except Exception as e:
|
| 130 |
+
status_message = f"An unexpected error occurred during submission: {e}"
|
| 131 |
+
print(status_message)
|
| 132 |
+
results_df = pd.DataFrame(results_log)
|
| 133 |
+
return status_message, results_df
|
| 134 |
|
| 135 |
with gr.Blocks() as demo:
|
| 136 |
gr.Markdown("# Basic Agent Evaluation Runner")
|
| 137 |
+
gr.Markdown(
|
| 138 |
+
"""
|
| 139 |
+
**Instructions:**
|
| 140 |
+
1) Clone this space, then modify the code to define your agent's logic.
|
| 141 |
+
2) Log in to your Hugging Face account using the button below.
|
| 142 |
+
3) Click 'Run Evaluation & Submit All Answers' to fetch questions, run your agent, submit answers, and see the score.
|
| 143 |
+
"""
|
| 144 |
+
)
|
| 145 |
+
|
| 146 |
+
login = gr.LoginButton()
|
| 147 |
+
user_state = gr.State()
|
| 148 |
+
login.click(lambda p: p, inputs=login, outputs=user_state)
|
| 149 |
+
|
| 150 |
run_button = gr.Button("Run Evaluation & Submit All Answers")
|
| 151 |
+
status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)
|
| 152 |
results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
|
| 153 |
+
|
| 154 |
+
run_button.click(fn=run_and_submit_all, inputs=[user_state], outputs=[status_output, results_table])
|
| 155 |
|
| 156 |
if __name__ == "__main__":
|
| 157 |
+
print("\n" + "-"*30 + " App Starting " + "-"*30)
|
| 158 |
+
space_host_startup = os.getenv("SPACE_HOST")
|
| 159 |
+
print(f"Repo URL: https://huggingface.co/spaces/{SPACE_ID}")
|
| 160 |
+
print(f"Repo Tree URL: https://huggingface.co/spaces/{SPACE_ID}/tree/main")
|
| 161 |
+
if space_host_startup:
|
| 162 |
+
print(f"Runtime URL should be: https://{space_host_startup}.hf.space")
|
| 163 |
+
else:
|
| 164 |
+
print("SPACE_HOST not found (running locally?).")
|
| 165 |
+
print("-"*(60 + len(" App Starting ")) + "\n")
|
| 166 |
demo.launch(debug=True, share=False)
|