Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,120 +1,99 @@
|
|
| 1 |
import os
|
| 2 |
import gradio as gr
|
| 3 |
import requests
|
| 4 |
-
import inspect
|
| 5 |
-
import pandas as pd
|
| 6 |
import time
|
|
|
|
| 7 |
|
| 8 |
-
# (Keep Constants as is)
|
| 9 |
# --- Constants ---
|
| 10 |
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
| 11 |
|
| 12 |
-
# ---
|
| 13 |
-
|
| 14 |
-
class BasicAgent:
|
| 15 |
def __init__(self):
|
| 16 |
-
self.api_key = os.getenv("GEMINI_API_KEY")
|
| 17 |
-
self.api_url = "https://generativelanguage.googleapis.com/v1/models/gemini-pro:generateContent?key=" + self.api_key
|
| 18 |
if not self.api_key:
|
| 19 |
-
raise ValueError("
|
| 20 |
-
|
|
|
|
| 21 |
|
| 22 |
def __call__(self, question: str) -> str:
|
| 23 |
headers = {
|
| 24 |
"Content-Type": "application/json"
|
| 25 |
}
|
| 26 |
-
|
| 27 |
payload = {
|
| 28 |
-
"contents": [
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
}
|
| 33 |
-
]
|
| 34 |
}
|
| 35 |
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
response.raise_for_status()
|
| 51 |
-
|
| 52 |
-
data = response.json()
|
| 53 |
-
return data["candidates"][0]["content"]["parts"][0]["text"]
|
| 54 |
-
|
| 55 |
-
except Exception as e:
|
| 56 |
-
print("❌ Ошибка Gemini API:", e)
|
| 57 |
-
return f"Ошибка Gemini API: {e}"
|
| 58 |
-
|
| 59 |
-
return "❌ Не удалось получить ответ от Gemini API после нескольких попыток."
|
| 60 |
-
|
| 61 |
|
|
|
|
| 62 |
def run_and_submit_all(profile: gr.OAuthProfile | None):
|
| 63 |
space_id = os.getenv("SPACE_ID")
|
| 64 |
-
|
| 65 |
if profile:
|
| 66 |
-
username =
|
| 67 |
-
print(f"User logged in: {username}")
|
| 68 |
else:
|
| 69 |
-
|
| 70 |
-
return "Please Login to Hugging Face with the button.", None
|
| 71 |
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
| 75 |
|
| 76 |
try:
|
| 77 |
-
agent =
|
| 78 |
except Exception as e:
|
| 79 |
return f"Error initializing agent: {e}", None
|
| 80 |
|
| 81 |
-
|
| 82 |
-
print(agent_code)
|
| 83 |
-
|
| 84 |
-
print(f"Fetching questions from: {questions_url}")
|
| 85 |
try:
|
| 86 |
response = requests.get(questions_url, timeout=15)
|
| 87 |
response.raise_for_status()
|
| 88 |
questions_data = response.json()
|
| 89 |
-
if not questions_data:
|
| 90 |
-
return "Fetched questions list is empty or invalid format.", None
|
| 91 |
-
print(f"Fetched {len(questions_data)} questions.")
|
| 92 |
except Exception as e:
|
| 93 |
return f"Error fetching questions: {e}", None
|
| 94 |
|
| 95 |
-
|
| 96 |
answers_payload = []
|
| 97 |
-
|
| 98 |
|
| 99 |
for item in questions_data:
|
| 100 |
task_id = item.get("task_id")
|
| 101 |
-
|
| 102 |
-
if not task_id or
|
| 103 |
continue
|
|
|
|
| 104 |
try:
|
| 105 |
-
|
| 106 |
-
answers_payload.append({"task_id": task_id, "submitted_answer":
|
| 107 |
-
results_log.append({"Task ID": task_id, "Question":
|
| 108 |
except Exception as e:
|
| 109 |
-
results_log.append({"Task ID": task_id, "Question":
|
| 110 |
|
| 111 |
-
time.sleep(
|
| 112 |
|
| 113 |
if not answers_payload:
|
| 114 |
return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
|
| 115 |
|
| 116 |
-
|
| 117 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 118 |
|
| 119 |
try:
|
| 120 |
response = requests.post(submit_url, json=submission_data, timeout=60)
|
|
@@ -123,26 +102,29 @@ def run_and_submit_all(profile: gr.OAuthProfile | None):
|
|
| 123 |
final_status = (
|
| 124 |
f"Submission Successful!\n"
|
| 125 |
f"User: {result_data.get('username')}\n"
|
| 126 |
-
f"
|
| 127 |
-
f"({result_data.get('correct_count'
|
| 128 |
-
f"Message: {result_data.get('message'
|
| 129 |
)
|
| 130 |
return final_status, pd.DataFrame(results_log)
|
| 131 |
except Exception as e:
|
| 132 |
return f"Submission Failed: {e}", pd.DataFrame(results_log)
|
| 133 |
|
| 134 |
-
|
| 135 |
# --- Gradio UI ---
|
| 136 |
with gr.Blocks() as demo:
|
| 137 |
-
gr.Markdown("
|
| 138 |
-
gr.Markdown("
|
| 139 |
-
|
|
|
|
|
|
|
|
|
|
| 140 |
gr.LoginButton()
|
| 141 |
-
|
| 142 |
-
|
| 143 |
-
|
| 144 |
|
| 145 |
-
|
| 146 |
|
| 147 |
if __name__ == "__main__":
|
| 148 |
-
|
|
|
|
|
|
| 1 |
import os
|
| 2 |
import gradio as gr
|
| 3 |
import requests
|
|
|
|
|
|
|
| 4 |
import time
|
| 5 |
+
import pandas as pd
|
| 6 |
|
|
|
|
| 7 |
# --- Constants ---
|
| 8 |
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
| 9 |
|
| 10 |
+
# --- Gemini Agent ---
|
| 11 |
+
class GeminiAgent:
|
|
|
|
| 12 |
def __init__(self):
|
| 13 |
+
self.api_key = os.getenv("GEMINI_API_KEY")
|
|
|
|
| 14 |
if not self.api_key:
|
| 15 |
+
raise ValueError("GEMINI_API_KEY environment variable not set.")
|
| 16 |
+
self.api_url = f"https://generativelanguage.googleapis.com/v1/models/gemini-1.5-pro:generateContent?key={self.api_key}"
|
| 17 |
+
print("GeminiAgent initialized.")
|
| 18 |
|
| 19 |
def __call__(self, question: str) -> str:
|
| 20 |
headers = {
|
| 21 |
"Content-Type": "application/json"
|
| 22 |
}
|
|
|
|
| 23 |
payload = {
|
| 24 |
+
"contents": [{
|
| 25 |
+
"role": "user",
|
| 26 |
+
"parts": [{"text": question}]
|
| 27 |
+
}]
|
|
|
|
|
|
|
| 28 |
}
|
| 29 |
|
| 30 |
+
try:
|
| 31 |
+
response = requests.post(self.api_url, headers=headers, json=payload)
|
| 32 |
+
if response.status_code == 429:
|
| 33 |
+
print("Rate limit hit. Waiting 3 seconds before retrying...")
|
| 34 |
+
time.sleep(3)
|
| 35 |
+
response = requests.post(self.api_url, headers=headers, json=payload)
|
| 36 |
+
|
| 37 |
+
response.raise_for_status()
|
| 38 |
+
data = response.json()
|
| 39 |
+
return data['candidates'][0]['content']['parts'][0]['text']
|
| 40 |
+
except Exception as e:
|
| 41 |
+
print(f"Ошибка при вызове Gemini API: {e}")
|
| 42 |
+
return f"ERROR: {e}"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 43 |
|
| 44 |
+
# --- Evaluation and Submission ---
|
| 45 |
def run_and_submit_all(profile: gr.OAuthProfile | None):
|
| 46 |
space_id = os.getenv("SPACE_ID")
|
|
|
|
| 47 |
if profile:
|
| 48 |
+
username = profile.username
|
|
|
|
| 49 |
else:
|
| 50 |
+
return "Please login with Hugging Face to continue.", None
|
|
|
|
| 51 |
|
| 52 |
+
questions_url = f"{DEFAULT_API_URL}/questions"
|
| 53 |
+
submit_url = f"{DEFAULT_API_URL}/submit"
|
| 54 |
+
agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
|
| 55 |
|
| 56 |
try:
|
| 57 |
+
agent = GeminiAgent()
|
| 58 |
except Exception as e:
|
| 59 |
return f"Error initializing agent: {e}", None
|
| 60 |
|
| 61 |
+
# Fetch questions
|
|
|
|
|
|
|
|
|
|
| 62 |
try:
|
| 63 |
response = requests.get(questions_url, timeout=15)
|
| 64 |
response.raise_for_status()
|
| 65 |
questions_data = response.json()
|
|
|
|
|
|
|
|
|
|
| 66 |
except Exception as e:
|
| 67 |
return f"Error fetching questions: {e}", None
|
| 68 |
|
| 69 |
+
# Answer questions
|
| 70 |
answers_payload = []
|
| 71 |
+
results_log = []
|
| 72 |
|
| 73 |
for item in questions_data:
|
| 74 |
task_id = item.get("task_id")
|
| 75 |
+
question = item.get("question")
|
| 76 |
+
if not task_id or question is None:
|
| 77 |
continue
|
| 78 |
+
|
| 79 |
try:
|
| 80 |
+
answer = agent(question)
|
| 81 |
+
answers_payload.append({"task_id": task_id, "submitted_answer": answer})
|
| 82 |
+
results_log.append({"Task ID": task_id, "Question": question, "Submitted Answer": answer})
|
| 83 |
except Exception as e:
|
| 84 |
+
results_log.append({"Task ID": task_id, "Question": question, "Submitted Answer": f"ERROR: {e}"})
|
| 85 |
|
| 86 |
+
time.sleep(2) # ⏳ delay to avoid rate limits
|
| 87 |
|
| 88 |
if not answers_payload:
|
| 89 |
return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
|
| 90 |
|
| 91 |
+
# Submit answers
|
| 92 |
+
submission_data = {
|
| 93 |
+
"username": username,
|
| 94 |
+
"agent_code": agent_code,
|
| 95 |
+
"answers": answers_payload
|
| 96 |
+
}
|
| 97 |
|
| 98 |
try:
|
| 99 |
response = requests.post(submit_url, json=submission_data, timeout=60)
|
|
|
|
| 102 |
final_status = (
|
| 103 |
f"Submission Successful!\n"
|
| 104 |
f"User: {result_data.get('username')}\n"
|
| 105 |
+
f"Score: {result_data.get('score', 'N/A')}% "
|
| 106 |
+
f"({result_data.get('correct_count')}/{result_data.get('total_attempted')})\n"
|
| 107 |
+
f"Message: {result_data.get('message')}"
|
| 108 |
)
|
| 109 |
return final_status, pd.DataFrame(results_log)
|
| 110 |
except Exception as e:
|
| 111 |
return f"Submission Failed: {e}", pd.DataFrame(results_log)
|
| 112 |
|
|
|
|
| 113 |
# --- Gradio UI ---
|
| 114 |
with gr.Blocks() as demo:
|
| 115 |
+
gr.Markdown("## Gemini Agent Evaluation (Unit 4)")
|
| 116 |
+
gr.Markdown("""
|
| 117 |
+
1. Убедитесь, что вы установили `GEMINI_API_KEY` как переменную окружения.
|
| 118 |
+
2. Нажмите кнопку авторизации.
|
| 119 |
+
3. Нажмите **Run Evaluation** для запуска и отправки.
|
| 120 |
+
""")
|
| 121 |
gr.LoginButton()
|
| 122 |
+
run_btn = gr.Button("Run Evaluation & Submit All Answers")
|
| 123 |
+
status = gr.Textbox(label="Status")
|
| 124 |
+
table = gr.DataFrame(label="Answers Log", wrap=True)
|
| 125 |
|
| 126 |
+
run_btn.click(fn=run_and_submit_all, outputs=[status, table])
|
| 127 |
|
| 128 |
if __name__ == "__main__":
|
| 129 |
+
print("Launching Gemini Agent Evaluation...")
|
| 130 |
+
demo.launch()
|