Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -3,108 +3,79 @@ import gradio as gr
|
|
| 3 |
import requests
|
| 4 |
import pandas as pd
|
| 5 |
from typing import Optional
|
|
|
|
| 6 |
|
| 7 |
# --- Constants ---
|
| 8 |
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
| 9 |
-
HF_API_URL = "https://api-inference.huggingface.co/models"
|
| 10 |
|
| 11 |
class BasicAgent:
|
| 12 |
def __init__(self):
|
| 13 |
-
"""
|
| 14 |
-
self.
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
if not self.hf_token:
|
| 18 |
-
print("β HF_TOKEN not found in Secrets")
|
| 19 |
-
self.agent = None
|
| 20 |
-
return
|
| 21 |
-
|
| 22 |
-
self.agent_url = f"{HF_API_URL}/{self.model_name}"
|
| 23 |
-
print("β Agent initialized (using HF Inference API)")
|
| 24 |
|
| 25 |
def __call__(self, question: str) -> str:
|
| 26 |
-
"""
|
| 27 |
-
if self.agent is None:
|
| 28 |
-
return "HF_TOKEN not configured. Add it to Secrets."
|
| 29 |
-
|
| 30 |
try:
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
payload = {
|
| 34 |
-
"inputs": question,
|
| 35 |
-
"parameters": {
|
| 36 |
-
"max_new_tokens": 256,
|
| 37 |
-
"temperature": 0.7,
|
| 38 |
-
"top_p": 0.9
|
| 39 |
-
}
|
| 40 |
-
}
|
| 41 |
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
headers=headers,
|
| 45 |
-
json=payload,
|
| 46 |
-
timeout=60
|
| 47 |
-
)
|
| 48 |
|
| 49 |
-
|
| 50 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 51 |
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
# θ§£ζεζ
|
| 55 |
-
if isinstance(result, list) and len(result) > 0:
|
| 56 |
-
answer = result[0].get("generated_text", "")
|
| 57 |
-
# ε»ι€ει‘ι¨ε
|
| 58 |
-
answer = answer.replace(question, "").strip()
|
| 59 |
-
return answer[:1000] if answer else "No answer"
|
| 60 |
-
|
| 61 |
-
return "Invalid API response"
|
| 62 |
-
|
| 63 |
-
except requests.exceptions.Timeout:
|
| 64 |
-
return "API request timeout"
|
| 65 |
except Exception as e:
|
| 66 |
-
print(f"
|
| 67 |
-
return f"
|
| 68 |
|
| 69 |
|
| 70 |
def run_and_submit_all(profile: Optional[gr.OAuthProfile] = None):
|
| 71 |
"""δΈ»θ¦θ©δΌ°εζδΊ€ε½ζΈ"""
|
| 72 |
|
|
|
|
| 73 |
if profile is None:
|
| 74 |
return "Please Login to Hugging Face with the button.", None
|
| 75 |
|
| 76 |
username = profile.username
|
| 77 |
-
space_id = os.getenv("SPACE_ID")
|
| 78 |
-
|
| 79 |
-
if not space_id:
|
| 80 |
-
return "Error: SPACE_ID not set.", None
|
| 81 |
|
| 82 |
api_url = DEFAULT_API_URL
|
| 83 |
questions_url = f"{api_url}/questions"
|
| 84 |
submit_url = f"{api_url}/submit"
|
| 85 |
|
|
|
|
| 86 |
try:
|
| 87 |
agent = BasicAgent()
|
| 88 |
except Exception as e:
|
| 89 |
-
return f"Error initializing agent: {str(e)
|
| 90 |
|
| 91 |
agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
|
| 92 |
|
|
|
|
| 93 |
try:
|
| 94 |
response = requests.get(questions_url, timeout=30)
|
| 95 |
response.raise_for_status()
|
| 96 |
questions_data = response.json()
|
| 97 |
except Exception as e:
|
| 98 |
-
return f"Error fetching questions: {str(e)
|
| 99 |
|
| 100 |
answers_payload = []
|
| 101 |
results_log = []
|
| 102 |
|
| 103 |
-
|
|
|
|
|
|
|
| 104 |
task_id = item.get("task_id")
|
| 105 |
question_text = item.get("question")
|
| 106 |
|
| 107 |
-
print(f"[{idx
|
| 108 |
|
| 109 |
try:
|
| 110 |
submitted_answer = agent(question_text)
|
|
@@ -115,10 +86,10 @@ def run_and_submit_all(profile: Optional[gr.OAuthProfile] = None):
|
|
| 115 |
results_log.append({
|
| 116 |
"Task ID": task_id,
|
| 117 |
"Question": question_text[:80],
|
| 118 |
-
"Answer": submitted_answer[:
|
| 119 |
})
|
| 120 |
except Exception as e:
|
| 121 |
-
error_answer = f"Error: {str(e)
|
| 122 |
answers_payload.append({
|
| 123 |
"task_id": task_id,
|
| 124 |
"submitted_answer": error_answer
|
|
@@ -129,6 +100,7 @@ def run_and_submit_all(profile: Optional[gr.OAuthProfile] = None):
|
|
| 129 |
"Answer": error_answer
|
| 130 |
})
|
| 131 |
|
|
|
|
| 132 |
submission_data = {
|
| 133 |
"username": username,
|
| 134 |
"agent_code": agent_code,
|
|
@@ -142,10 +114,10 @@ def run_and_submit_all(profile: Optional[gr.OAuthProfile] = None):
|
|
| 142 |
|
| 143 |
score = result_data.get('score', 'N/A')
|
| 144 |
correct = result_data.get('correct_count', 0)
|
| 145 |
-
|
| 146 |
-
status_msg = f"Score: {score}% ({correct}/{
|
| 147 |
except Exception as e:
|
| 148 |
-
status_msg = f"Submission Failed: {str(e)
|
| 149 |
|
| 150 |
return status_msg, pd.DataFrame(results_log)
|
| 151 |
|
|
@@ -153,7 +125,7 @@ def run_and_submit_all(profile: Optional[gr.OAuthProfile] = None):
|
|
| 153 |
# Gradio UI
|
| 154 |
with gr.Blocks(title="Unit 4 Final Assignment") as demo:
|
| 155 |
gr.Markdown("# Unit 4 Final Project: AI Agent")
|
| 156 |
-
gr.Markdown("
|
| 157 |
|
| 158 |
with gr.Row():
|
| 159 |
gr.LoginButton(scale=1)
|
|
|
|
| 3 |
import requests
|
| 4 |
import pandas as pd
|
| 5 |
from typing import Optional
|
| 6 |
+
from duckduckgo_search import DDGS
|
| 7 |
|
| 8 |
# --- Constants ---
|
| 9 |
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
|
|
|
| 10 |
|
| 11 |
class BasicAgent:
|
| 12 |
def __init__(self):
|
| 13 |
+
"""εε§εζε° Agent"""
|
| 14 |
+
self.agent = True
|
| 15 |
+
print("β Search agent initialized")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 16 |
|
| 17 |
def __call__(self, question: str) -> str:
|
| 18 |
+
"""η¨ DuckDuckGo ζε°εηει‘"""
|
|
|
|
|
|
|
|
|
|
| 19 |
try:
|
| 20 |
+
ddgs = DDGS()
|
| 21 |
+
results = ddgs.text(question, max_results=5)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 22 |
|
| 23 |
+
if not results:
|
| 24 |
+
return "No search results found for this question."
|
|
|
|
|
|
|
|
|
|
|
|
|
| 25 |
|
| 26 |
+
# η΅εζε°η΅ζ
|
| 27 |
+
answer = ""
|
| 28 |
+
for i, result in enumerate(results[:3], 1):
|
| 29 |
+
title = result.get('title', 'Unknown')
|
| 30 |
+
body = result.get('body', '')[:300]
|
| 31 |
+
answer += f"{title}: {body}\n"
|
| 32 |
|
| 33 |
+
return answer.strip() if answer else "Could not find relevant information"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 34 |
except Exception as e:
|
| 35 |
+
print(f"Search error: {e}")
|
| 36 |
+
return f"Unable to search: Please try again"
|
| 37 |
|
| 38 |
|
| 39 |
def run_and_submit_all(profile: Optional[gr.OAuthProfile] = None):
|
| 40 |
"""δΈ»θ¦θ©δΌ°εζδΊ€ε½ζΈ"""
|
| 41 |
|
| 42 |
+
# ζͺ’ζ₯η»ε
₯
|
| 43 |
if profile is None:
|
| 44 |
return "Please Login to Hugging Face with the button.", None
|
| 45 |
|
| 46 |
username = profile.username
|
| 47 |
+
space_id = os.getenv("SPACE_ID", "s1144662")
|
|
|
|
|
|
|
|
|
|
| 48 |
|
| 49 |
api_url = DEFAULT_API_URL
|
| 50 |
questions_url = f"{api_url}/questions"
|
| 51 |
submit_url = f"{api_url}/submit"
|
| 52 |
|
| 53 |
+
# εε§ε Agent
|
| 54 |
try:
|
| 55 |
agent = BasicAgent()
|
| 56 |
except Exception as e:
|
| 57 |
+
return f"Error initializing agent: {str(e)}", None
|
| 58 |
|
| 59 |
agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
|
| 60 |
|
| 61 |
+
# η²εει‘
|
| 62 |
try:
|
| 63 |
response = requests.get(questions_url, timeout=30)
|
| 64 |
response.raise_for_status()
|
| 65 |
questions_data = response.json()
|
| 66 |
except Exception as e:
|
| 67 |
+
return f"Error fetching questions: {str(e)}", None
|
| 68 |
|
| 69 |
answers_payload = []
|
| 70 |
results_log = []
|
| 71 |
|
| 72 |
+
# ιεεηει‘
|
| 73 |
+
total = len(questions_data)
|
| 74 |
+
for idx, item in enumerate(questions_data, 1):
|
| 75 |
task_id = item.get("task_id")
|
| 76 |
question_text = item.get("question")
|
| 77 |
|
| 78 |
+
print(f"[{idx}/{total}] Processing: {task_id}")
|
| 79 |
|
| 80 |
try:
|
| 81 |
submitted_answer = agent(question_text)
|
|
|
|
| 86 |
results_log.append({
|
| 87 |
"Task ID": task_id,
|
| 88 |
"Question": question_text[:80],
|
| 89 |
+
"Answer": submitted_answer[:200]
|
| 90 |
})
|
| 91 |
except Exception as e:
|
| 92 |
+
error_answer = f"Error: {str(e)}"
|
| 93 |
answers_payload.append({
|
| 94 |
"task_id": task_id,
|
| 95 |
"submitted_answer": error_answer
|
|
|
|
| 100 |
"Answer": error_answer
|
| 101 |
})
|
| 102 |
|
| 103 |
+
# ζδΊ€ηζ‘
|
| 104 |
submission_data = {
|
| 105 |
"username": username,
|
| 106 |
"agent_code": agent_code,
|
|
|
|
| 114 |
|
| 115 |
score = result_data.get('score', 'N/A')
|
| 116 |
correct = result_data.get('correct_count', 0)
|
| 117 |
+
total_q = result_data.get('total_attempted', 0)
|
| 118 |
+
status_msg = f"β Score: {score}% ({correct}/{total_q} correct)"
|
| 119 |
except Exception as e:
|
| 120 |
+
status_msg = f"β Submission Failed: {str(e)}"
|
| 121 |
|
| 122 |
return status_msg, pd.DataFrame(results_log)
|
| 123 |
|
|
|
|
| 125 |
# Gradio UI
|
| 126 |
with gr.Blocks(title="Unit 4 Final Assignment") as demo:
|
| 127 |
gr.Markdown("# Unit 4 Final Project: AI Agent")
|
| 128 |
+
gr.Markdown("_Using DuckDuckGo Search to answer questions_")
|
| 129 |
|
| 130 |
with gr.Row():
|
| 131 |
gr.LoginButton(scale=1)
|