Update app.py
Browse files
app.py
CHANGED
|
@@ -3,42 +3,30 @@ import gradio as gr
|
|
| 3 |
import requests
|
| 4 |
import pandas as pd
|
| 5 |
import json
|
| 6 |
-
import
|
| 7 |
-
from transformers import AutoTokenizer, AutoModelForCausalLM
|
| 8 |
|
| 9 |
# --- Constants ---
|
| 10 |
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
| 11 |
|
| 12 |
-
# ---
|
| 13 |
-
class
|
| 14 |
def __init__(self):
|
| 15 |
-
print("
|
| 16 |
-
self.
|
| 17 |
-
|
| 18 |
-
"
|
| 19 |
-
|
| 20 |
-
|
|
|
|
|
|
|
| 21 |
)
|
| 22 |
|
| 23 |
def __call__(self, question: str) -> str:
|
| 24 |
-
prompt = f"Answer the following question
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 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):
|
|
@@ -46,39 +34,35 @@ def run_and_submit_all(profile: gr.OAuthProfile | None):
|
|
| 46 |
|
| 47 |
if profile:
|
| 48 |
username = f"{profile.username}"
|
| 49 |
-
print(f"π€
|
| 50 |
else:
|
| 51 |
-
return "Please
|
| 52 |
|
|
|
|
| 53 |
questions_url = f"{DEFAULT_API_URL}/questions"
|
| 54 |
submit_url = f"{DEFAULT_API_URL}/submit"
|
| 55 |
|
| 56 |
try:
|
| 57 |
-
agent =
|
| 58 |
except Exception as e:
|
| 59 |
-
return f"β Error
|
| 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 |
-
|
| 68 |
-
print(f"π₯ Fetched {len(
|
| 69 |
except Exception as e:
|
| 70 |
-
return f"β
|
| 71 |
|
| 72 |
-
answers_payload = []
|
| 73 |
results_log = []
|
|
|
|
| 74 |
|
| 75 |
-
for item in
|
| 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})
|
|
@@ -87,7 +71,7 @@ def run_and_submit_all(profile: gr.OAuthProfile | None):
|
|
| 87 |
results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"ERROR: {e}"})
|
| 88 |
|
| 89 |
if not answers_payload:
|
| 90 |
-
return "β
|
| 91 |
|
| 92 |
submission_data = {
|
| 93 |
"username": username.strip(),
|
|
@@ -95,7 +79,7 @@ def run_and_submit_all(profile: gr.OAuthProfile | None):
|
|
| 95 |
"answers": answers_payload
|
| 96 |
}
|
| 97 |
|
| 98 |
-
print("π€ Submission
|
| 99 |
print(json.dumps(submission_data, indent=2)[:1000])
|
| 100 |
|
| 101 |
try:
|
|
@@ -115,13 +99,13 @@ def run_and_submit_all(profile: gr.OAuthProfile | None):
|
|
| 115 |
|
| 116 |
# --- Gradio UI ---
|
| 117 |
with gr.Blocks() as demo:
|
| 118 |
-
gr.Markdown("#
|
| 119 |
gr.Markdown(
|
| 120 |
"""
|
| 121 |
β
**Instructions:**
|
| 122 |
-
1.
|
| 123 |
-
2. Click
|
| 124 |
-
3. Wait 1β2 mins. You need at least **30% correct** to
|
| 125 |
"""
|
| 126 |
)
|
| 127 |
|
|
@@ -133,5 +117,5 @@ with gr.Blocks() as demo:
|
|
| 133 |
run_button.click(fn=run_and_submit_all, outputs=[status_output, results_table])
|
| 134 |
|
| 135 |
if __name__ == "__main__":
|
| 136 |
-
print("π Launching
|
| 137 |
demo.launch(debug=True, share=False)
|
|
|
|
| 3 |
import requests
|
| 4 |
import pandas as pd
|
| 5 |
import json
|
| 6 |
+
from transformers import pipeline
|
|
|
|
| 7 |
|
| 8 |
# --- Constants ---
|
| 9 |
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
| 10 |
|
| 11 |
+
# --- Hugging Face Agent using Transformers Pipeline ---
|
| 12 |
+
class HFTransformersAgent:
|
| 13 |
def __init__(self):
|
| 14 |
+
print("π€ Loading text-generation agent...")
|
| 15 |
+
self.generator = pipeline(
|
| 16 |
+
"text-generation",
|
| 17 |
+
model="tiiuae/falcon-7b-instruct",
|
| 18 |
+
max_new_tokens=100,
|
| 19 |
+
do_sample=True,
|
| 20 |
+
temperature=0.7,
|
| 21 |
+
top_p=0.9
|
| 22 |
)
|
| 23 |
|
| 24 |
def __call__(self, question: str) -> str:
|
| 25 |
+
prompt = f"Answer the following question:\n\n{question}\n\nAnswer:"
|
| 26 |
+
result = self.generator(prompt)[0]["generated_text"]
|
| 27 |
+
answer = result.split("Answer:")[-1].strip()
|
| 28 |
+
print(f"β
Generated answer: {answer}")
|
| 29 |
+
return answer if answer else "Not Enough Information"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 30 |
|
| 31 |
# --- Run Agent & Submit ---
|
| 32 |
def run_and_submit_all(profile: gr.OAuthProfile | None):
|
|
|
|
| 34 |
|
| 35 |
if profile:
|
| 36 |
username = f"{profile.username}"
|
| 37 |
+
print(f"π€ Logged in: {username}")
|
| 38 |
else:
|
| 39 |
+
return "Please log in to Hugging Face using the button.", None
|
| 40 |
|
| 41 |
+
agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
|
| 42 |
questions_url = f"{DEFAULT_API_URL}/questions"
|
| 43 |
submit_url = f"{DEFAULT_API_URL}/submit"
|
| 44 |
|
| 45 |
try:
|
| 46 |
+
agent = HFTransformersAgent()
|
| 47 |
except Exception as e:
|
| 48 |
+
return f"β Error initializing agent: {e}", None
|
|
|
|
|
|
|
|
|
|
| 49 |
|
| 50 |
try:
|
| 51 |
response = requests.get(questions_url, timeout=15)
|
| 52 |
response.raise_for_status()
|
| 53 |
+
questions_data = response.json()
|
| 54 |
+
print(f"π₯ Fetched {len(questions_data)} questions.")
|
| 55 |
except Exception as e:
|
| 56 |
+
return f"β Error fetching questions: {e}", None
|
| 57 |
|
|
|
|
| 58 |
results_log = []
|
| 59 |
+
answers_payload = []
|
| 60 |
|
| 61 |
+
for item in questions_data:
|
| 62 |
task_id = item.get("task_id")
|
| 63 |
question_text = item.get("question")
|
|
|
|
| 64 |
if not task_id or not question_text:
|
| 65 |
continue
|
|
|
|
| 66 |
try:
|
| 67 |
answer = agent(question_text)
|
| 68 |
answers_payload.append({"task_id": task_id, "submitted_answer": answer})
|
|
|
|
| 71 |
results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"ERROR: {e}"})
|
| 72 |
|
| 73 |
if not answers_payload:
|
| 74 |
+
return "β Agent did not produce any answers.", pd.DataFrame(results_log)
|
| 75 |
|
| 76 |
submission_data = {
|
| 77 |
"username": username.strip(),
|
|
|
|
| 79 |
"answers": answers_payload
|
| 80 |
}
|
| 81 |
|
| 82 |
+
print("π€ Submission preview:")
|
| 83 |
print(json.dumps(submission_data, indent=2)[:1000])
|
| 84 |
|
| 85 |
try:
|
|
|
|
| 99 |
|
| 100 |
# --- Gradio UI ---
|
| 101 |
with gr.Blocks() as demo:
|
| 102 |
+
gr.Markdown("# π€ Smart Agent Runner (HF Transformers)")
|
| 103 |
gr.Markdown(
|
| 104 |
"""
|
| 105 |
β
**Instructions:**
|
| 106 |
+
1. Log in to your Hugging Face account.
|
| 107 |
+
2. Click **βRun Evaluation & Submit All Answersβ**.
|
| 108 |
+
3. Wait ~1β2 mins. You need at least **30% correct** to unlock the certificate.
|
| 109 |
"""
|
| 110 |
)
|
| 111 |
|
|
|
|
| 117 |
run_button.click(fn=run_and_submit_all, outputs=[status_output, results_table])
|
| 118 |
|
| 119 |
if __name__ == "__main__":
|
| 120 |
+
print("π Launching agent...")
|
| 121 |
demo.launch(debug=True, share=False)
|