Update app.py
Browse files
app.py
CHANGED
|
@@ -3,76 +3,91 @@ import gradio as gr
|
|
| 3 |
import requests
|
| 4 |
import pandas as pd
|
| 5 |
import json
|
| 6 |
-
|
|
|
|
| 7 |
|
| 8 |
# --- Constants ---
|
| 9 |
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
| 10 |
|
| 11 |
-
# --- Smart Agent
|
| 12 |
-
class
|
| 13 |
def __init__(self):
|
| 14 |
-
print("
|
| 15 |
-
self.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 16 |
|
| 17 |
def __call__(self, question: str) -> str:
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 25 |
def run_and_submit_all(profile: gr.OAuthProfile | None):
|
| 26 |
space_id = os.getenv("SPACE_ID")
|
| 27 |
|
| 28 |
if profile:
|
| 29 |
username = f"{profile.username}"
|
| 30 |
-
print(f"User logged in: {username}")
|
| 31 |
else:
|
| 32 |
-
print("User not logged in.")
|
| 33 |
return "Please Login to Hugging Face with the button.", None
|
| 34 |
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
submit_url = f"{api_url}/submit"
|
| 38 |
|
| 39 |
try:
|
| 40 |
-
agent =
|
| 41 |
except Exception as e:
|
| 42 |
-
|
| 43 |
-
return f"Error initializing agent: {e}", None
|
| 44 |
|
| 45 |
agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
|
| 46 |
-
print(f"Agent
|
| 47 |
|
| 48 |
try:
|
| 49 |
response = requests.get(questions_url, timeout=15)
|
| 50 |
response.raise_for_status()
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
return "Fetched questions list is empty or invalid format.", None
|
| 54 |
-
print(f"Fetched {len(questions_data)} questions.")
|
| 55 |
except Exception as e:
|
| 56 |
-
return f"
|
| 57 |
|
| 58 |
-
results_log = []
|
| 59 |
answers_payload = []
|
| 60 |
-
|
|
|
|
|
|
|
| 61 |
task_id = item.get("task_id")
|
| 62 |
question_text = item.get("question")
|
| 63 |
-
|
|
|
|
| 64 |
continue
|
|
|
|
| 65 |
try:
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
|
| 70 |
-
results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
|
| 71 |
except Exception as e:
|
| 72 |
-
results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"
|
| 73 |
|
| 74 |
if not answers_payload:
|
| 75 |
-
return "
|
| 76 |
|
| 77 |
submission_data = {
|
| 78 |
"username": username.strip(),
|
|
@@ -80,47 +95,43 @@ def run_and_submit_all(profile: gr.OAuthProfile | None):
|
|
| 80 |
"answers": answers_payload
|
| 81 |
}
|
| 82 |
|
| 83 |
-
|
| 84 |
-
print(
|
| 85 |
-
print(json.dumps(submission_data, indent=2)[:1000]) # Safe preview log
|
| 86 |
|
| 87 |
try:
|
| 88 |
response = requests.post(submit_url, json=submission_data, timeout=60)
|
| 89 |
response.raise_for_status()
|
| 90 |
-
|
| 91 |
-
|
| 92 |
f"β
Submission Successful!\n"
|
| 93 |
-
f"π€ User: {
|
| 94 |
-
f"π Score: {
|
| 95 |
-
f"({
|
| 96 |
-
f"π Message: {
|
| 97 |
)
|
| 98 |
-
return
|
| 99 |
-
except requests.exceptions.RequestException as e:
|
| 100 |
-
return f"β Submission Failed: {str(e)}", pd.DataFrame(results_log)
|
| 101 |
except Exception as e:
|
| 102 |
-
return f"β
|
| 103 |
|
| 104 |
# --- Gradio UI ---
|
| 105 |
with gr.Blocks() as demo:
|
| 106 |
-
gr.Markdown("#
|
| 107 |
gr.Markdown(
|
| 108 |
"""
|
| 109 |
β
**Instructions:**
|
| 110 |
1. Login to your Hugging Face account.
|
| 111 |
-
2. Click
|
| 112 |
-
3. Wait
|
| 113 |
-
π You need at least **30% correct** on Level 1 to unlock the certificate.
|
| 114 |
"""
|
| 115 |
)
|
| 116 |
|
| 117 |
gr.LoginButton()
|
| 118 |
run_button = gr.Button("π Run Evaluation & Submit All Answers")
|
| 119 |
-
status_output = gr.Textbox(label="π
|
| 120 |
-
results_table = gr.DataFrame(label="π
|
| 121 |
|
| 122 |
run_button.click(fn=run_and_submit_all, outputs=[status_output, results_table])
|
| 123 |
|
| 124 |
if __name__ == "__main__":
|
| 125 |
-
print("Launching Smart Agent
|
| 126 |
demo.launch(debug=True, share=False)
|
|
|
|
| 3 |
import requests
|
| 4 |
import pandas as pd
|
| 5 |
import json
|
| 6 |
+
import torch
|
| 7 |
+
from transformers import AutoTokenizer, AutoModelForCausalLM
|
| 8 |
|
| 9 |
# --- Constants ---
|
| 10 |
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
| 11 |
|
| 12 |
+
# --- Smart Agent using Mistral-7B ---
|
| 13 |
+
class SmartLLMAgent:
|
| 14 |
def __init__(self):
|
| 15 |
+
print("π Loading SmartLLMAgent with Mistral-7B...")
|
| 16 |
+
self.tokenizer = AutoTokenizer.from_pretrained("mistralai/Mistral-7B-Instruct-v0.2")
|
| 17 |
+
self.model = AutoModelForCausalLM.from_pretrained(
|
| 18 |
+
"mistralai/Mistral-7B-Instruct-v0.2",
|
| 19 |
+
torch_dtype=torch.float16 if torch.cuda.is_available() else torch.float32,
|
| 20 |
+
device_map="auto"
|
| 21 |
+
)
|
| 22 |
|
| 23 |
def __call__(self, question: str) -> str:
|
| 24 |
+
prompt = f"Answer the following question clearly and precisely:\n\nQuestion: {question}\n\nAnswer:"
|
| 25 |
+
inputs = self.tokenizer(prompt, return_tensors="pt", truncation=True, max_length=2048)
|
| 26 |
+
inputs = {k: v.to(self.model.device) for k, v in inputs.items()}
|
| 27 |
+
|
| 28 |
+
with torch.no_grad():
|
| 29 |
+
outputs = self.model.generate(
|
| 30 |
+
**inputs,
|
| 31 |
+
max_new_tokens=150,
|
| 32 |
+
do_sample=True,
|
| 33 |
+
top_p=0.9,
|
| 34 |
+
temperature=0.7,
|
| 35 |
+
pad_token_id=self.tokenizer.eos_token_id
|
| 36 |
+
)
|
| 37 |
+
|
| 38 |
+
decoded = self.tokenizer.decode(outputs[0], skip_special_tokens=True)
|
| 39 |
+
final_answer = decoded.split("Answer:")[-1].strip()
|
| 40 |
+
print(f"β
Generated answer: {final_answer}")
|
| 41 |
+
return final_answer or "Not Enough Information"
|
| 42 |
+
|
| 43 |
+
# --- Run Agent & Submit ---
|
| 44 |
def run_and_submit_all(profile: gr.OAuthProfile | None):
|
| 45 |
space_id = os.getenv("SPACE_ID")
|
| 46 |
|
| 47 |
if profile:
|
| 48 |
username = f"{profile.username}"
|
| 49 |
+
print(f"π€ User logged in: {username}")
|
| 50 |
else:
|
|
|
|
| 51 |
return "Please Login to Hugging Face with the button.", None
|
| 52 |
|
| 53 |
+
questions_url = f"{DEFAULT_API_URL}/questions"
|
| 54 |
+
submit_url = f"{DEFAULT_API_URL}/submit"
|
|
|
|
| 55 |
|
| 56 |
try:
|
| 57 |
+
agent = SmartLLMAgent()
|
| 58 |
except Exception as e:
|
| 59 |
+
return f"β Error loading agent: {e}", None
|
|
|
|
| 60 |
|
| 61 |
agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
|
| 62 |
+
print(f"π Agent Code: {agent_code}")
|
| 63 |
|
| 64 |
try:
|
| 65 |
response = requests.get(questions_url, timeout=15)
|
| 66 |
response.raise_for_status()
|
| 67 |
+
questions = response.json()
|
| 68 |
+
print(f"π₯ Fetched {len(questions)} questions.")
|
|
|
|
|
|
|
| 69 |
except Exception as e:
|
| 70 |
+
return f"β Failed to fetch questions: {e}", None
|
| 71 |
|
|
|
|
| 72 |
answers_payload = []
|
| 73 |
+
results_log = []
|
| 74 |
+
|
| 75 |
+
for item in questions:
|
| 76 |
task_id = item.get("task_id")
|
| 77 |
question_text = item.get("question")
|
| 78 |
+
|
| 79 |
+
if not task_id or not question_text:
|
| 80 |
continue
|
| 81 |
+
|
| 82 |
try:
|
| 83 |
+
answer = agent(question_text)
|
| 84 |
+
answers_payload.append({"task_id": task_id, "submitted_answer": answer})
|
| 85 |
+
results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": answer})
|
|
|
|
|
|
|
| 86 |
except Exception as e:
|
| 87 |
+
results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"ERROR: {e}"})
|
| 88 |
|
| 89 |
if not answers_payload:
|
| 90 |
+
return "β No answers produced.", pd.DataFrame(results_log)
|
| 91 |
|
| 92 |
submission_data = {
|
| 93 |
"username": username.strip(),
|
|
|
|
| 95 |
"answers": answers_payload
|
| 96 |
}
|
| 97 |
|
| 98 |
+
print("π€ Submission Payload:")
|
| 99 |
+
print(json.dumps(submission_data, indent=2)[:1000])
|
|
|
|
| 100 |
|
| 101 |
try:
|
| 102 |
response = requests.post(submit_url, json=submission_data, timeout=60)
|
| 103 |
response.raise_for_status()
|
| 104 |
+
result = response.json()
|
| 105 |
+
status = (
|
| 106 |
f"β
Submission Successful!\n"
|
| 107 |
+
f"π€ User: {result.get('username')}\n"
|
| 108 |
+
f"π Score: {result.get('score', 'N/A')}% "
|
| 109 |
+
f"({result.get('correct_count', '?')}/{result.get('total_attempted', '?')} correct)\n"
|
| 110 |
+
f"π Message: {result.get('message', 'No message received.')}"
|
| 111 |
)
|
| 112 |
+
return status, pd.DataFrame(results_log)
|
|
|
|
|
|
|
| 113 |
except Exception as e:
|
| 114 |
+
return f"β Submission Failed: {e}", pd.DataFrame(results_log)
|
| 115 |
|
| 116 |
# --- Gradio UI ---
|
| 117 |
with gr.Blocks() as demo:
|
| 118 |
+
gr.Markdown("# π§ Smart Agent Evaluation Runner (Mistral-7B)")
|
| 119 |
gr.Markdown(
|
| 120 |
"""
|
| 121 |
β
**Instructions:**
|
| 122 |
1. Login to your Hugging Face account.
|
| 123 |
+
2. Click **"Run Evaluation & Submit All Answers"**.
|
| 124 |
+
3. Wait 1β2 mins. You need at least **30% correct** to pass Level 1 and get the certificate.
|
|
|
|
| 125 |
"""
|
| 126 |
)
|
| 127 |
|
| 128 |
gr.LoginButton()
|
| 129 |
run_button = gr.Button("π Run Evaluation & Submit All Answers")
|
| 130 |
+
status_output = gr.Textbox(label="π Submission Result", lines=6, interactive=False)
|
| 131 |
+
results_table = gr.DataFrame(label="π Agent Answers", wrap=True)
|
| 132 |
|
| 133 |
run_button.click(fn=run_and_submit_all, outputs=[status_output, results_table])
|
| 134 |
|
| 135 |
if __name__ == "__main__":
|
| 136 |
+
print("π Launching Smart Agent with Mistral-7B...")
|
| 137 |
demo.launch(debug=True, share=False)
|