Irfshaikh commited on
Commit
404278e
·
verified ·
1 Parent(s): a28d100

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +79 -0
app.py CHANGED
@@ -0,0 +1,79 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import requests
3
+ import pandas as pd
4
+ import gradio as gr
5
+ from langchain_core.messages import HumanMessage
6
+ from agent import build_graph
7
+
8
+ DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
9
+
10
+ class BasicAgent:
11
+ def __init__(self):
12
+ self.graph = build_graph()
13
+
14
+ def __call__(self, question: str) -> str:
15
+ result = self.graph.invoke({"messages": [HumanMessage(content=question)]})
16
+ return result['messages'][-1].content
17
+
18
+ def run_and_submit_all(profile: gr.OAuthProfile | None):
19
+ if not profile:
20
+ return "Please Login to Hugging Face with the button.", None
21
+
22
+ username = profile.username
23
+ agent_code = f"https://huggingface.co/spaces/{os.getenv('SPACE_ID')}/tree/main"
24
+ session = requests.Session()
25
+
26
+ try:
27
+ agent = BasicAgent()
28
+ except Exception as e:
29
+ return f"Error initializing agent: {e}", None
30
+
31
+ try:
32
+ response = session.get(f"{DEFAULT_API_URL}/questions", timeout=15)
33
+ response.raise_for_status()
34
+ questions = response.json()
35
+ if not questions:
36
+ return "No questions received from server.", None
37
+ except Exception as e:
38
+ return f"Error fetching questions: {e}", None
39
+
40
+ results_log = []
41
+ answers_payload = []
42
+
43
+ for item in questions:
44
+ task_id = item.get("task_id")
45
+ q = item.get("question")
46
+ if not (task_id and q):
47
+ continue
48
+ try:
49
+ answer = agent(q)
50
+ answers_payload.append({"task_id": task_id, "submitted_answer": answer})
51
+ except Exception as e:
52
+ answer = f"AGENT ERROR: {e}"
53
+ results_log.append({"Task ID": task_id, "Question": q, "Submitted Answer": answer})
54
+
55
+ if not answers_payload:
56
+ return "Agent did not produce valid answers.", pd.DataFrame(results_log)
57
+
58
+ try:
59
+ res = session.post(
60
+ f"{DEFAULT_API_URL}/submit",
61
+ json={
62
+ "username": username.strip(),
63
+ "agent_code": agent_code,
64
+ "answers": answers_payload
65
+ },
66
+ timeout=60
67
+ )
68
+ res.raise_for_status()
69
+ r = res.json()
70
+ status = (
71
+ f"Submission Successful!\nUser: {r.get('username')}\n"
72
+ f"Score: {r.get('score', 'N/A')}% "
73
+ f"({r.get('correct_count', '?')}/{r.get('total_attempted', '?')})\n"
74
+ f"Message: {r.get('message', 'No message received.')}"
75
+ )
76
+ return status, pd.DataFrame(results_log)
77
+
78
+ except requests.exceptions.RequestException as e:
79
+ return f"Submission Failed: {e}", pd.DataFrame(results_log)