Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,130 +1,93 @@
|
|
| 1 |
import os
|
| 2 |
-
import gradio as gr
|
| 3 |
-
import requests
|
| 4 |
import time
|
|
|
|
|
|
|
| 5 |
import pandas as pd
|
| 6 |
|
| 7 |
-
|
|
|
|
|
|
|
| 8 |
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
| 9 |
|
| 10 |
-
# --- Gemini Agent ---
|
| 11 |
class GeminiAgent:
|
| 12 |
def __init__(self):
|
| 13 |
-
|
| 14 |
-
|
| 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 |
-
|
| 22 |
-
}
|
| 23 |
payload = {
|
| 24 |
-
"contents": [{
|
| 25 |
-
"role": "user",
|
| 26 |
-
"parts": [{"text": question}]
|
| 27 |
-
}]
|
| 28 |
}
|
| 29 |
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
-
|
| 49 |
-
else:
|
| 50 |
-
return "Please login with Hugging Face to continue.", None
|
| 51 |
|
| 52 |
-
|
| 53 |
-
submit_url = f"{DEFAULT_API_URL}/submit"
|
| 54 |
agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
|
|
|
|
| 55 |
|
| 56 |
try:
|
| 57 |
-
|
| 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"
|
| 68 |
|
| 69 |
-
|
| 70 |
-
answers_payload = []
|
| 71 |
results_log = []
|
|
|
|
| 72 |
|
| 73 |
for item in questions_data:
|
| 74 |
task_id = item.get("task_id")
|
| 75 |
-
|
| 76 |
-
if not task_id or
|
| 77 |
continue
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 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 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
)
|
| 109 |
-
return final_status, pd.DataFrame(results_log)
|
| 110 |
except Exception as e:
|
| 111 |
-
return f"
|
| 112 |
|
| 113 |
-
#
|
| 114 |
with gr.Blocks() as demo:
|
| 115 |
-
gr.Markdown("## Gemini Agent
|
| 116 |
-
gr.Markdown(""
|
| 117 |
-
1. Убедитесь, что вы установили `GEMINI_API_KEY` как переменную окружения.
|
| 118 |
-
2. Нажмите кнопку авторизации.
|
| 119 |
-
3. Нажмите **Run Evaluation** для запуска и отправки.
|
| 120 |
-
""")
|
| 121 |
gr.LoginButton()
|
| 122 |
-
run_btn = gr.Button("
|
| 123 |
-
status = gr.Textbox(label="
|
| 124 |
-
table = gr.DataFrame(label="
|
| 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()
|
|
|
|
| 1 |
import os
|
|
|
|
|
|
|
| 2 |
import time
|
| 3 |
+
import requests
|
| 4 |
+
import gradio as gr
|
| 5 |
import pandas as pd
|
| 6 |
|
| 7 |
+
GEMINI_API_KEY = os.getenv("GEMINI_API_KEY")
|
| 8 |
+
GEMINI_MODEL = "gemini-1.5-flash"
|
| 9 |
+
GEMINI_API_URL = f"https://generativelanguage.googleapis.com/v1/models/{GEMINI_MODEL}:generateContent"
|
| 10 |
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
| 11 |
|
|
|
|
| 12 |
class GeminiAgent:
|
| 13 |
def __init__(self):
|
| 14 |
+
if not GEMINI_API_KEY:
|
| 15 |
+
raise ValueError("❌ Переменная окружения GEMINI_API_KEY не установлена.")
|
|
|
|
|
|
|
|
|
|
| 16 |
|
| 17 |
def __call__(self, question: str) -> str:
|
| 18 |
+
headers = {"Content-Type": "application/json"}
|
| 19 |
+
params = {"key": GEMINI_API_KEY}
|
|
|
|
| 20 |
payload = {
|
| 21 |
+
"contents": [{"parts": [{"text": question}]}]
|
|
|
|
|
|
|
|
|
|
| 22 |
}
|
| 23 |
|
| 24 |
+
for attempt in range(3):
|
| 25 |
+
try:
|
| 26 |
+
response = requests.post(GEMINI_API_URL, headers=headers, params=params, json=payload)
|
| 27 |
+
if response.status_code == 429:
|
| 28 |
+
print(f"⚠️ Попытка {attempt+1}: Превышен лимит. Ждём 5 сек.")
|
| 29 |
+
time.sleep(5)
|
| 30 |
+
continue
|
| 31 |
+
response.raise_for_status()
|
| 32 |
+
return response.json()["candidates"][0]["content"]["parts"][0]["text"].strip()
|
| 33 |
+
except Exception as e:
|
| 34 |
+
print(f"❌ Ошибка: {e}")
|
| 35 |
+
time.sleep(5)
|
| 36 |
+
return "Ошибка при получении ответа от Gemini API"
|
| 37 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 38 |
def run_and_submit_all(profile: gr.OAuthProfile | None):
|
| 39 |
space_id = os.getenv("SPACE_ID")
|
| 40 |
+
if not profile:
|
| 41 |
+
return "Пожалуйста, войдите в Hugging Face", None
|
|
|
|
|
|
|
| 42 |
|
| 43 |
+
username = profile.username
|
|
|
|
| 44 |
agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
|
| 45 |
+
print(f"Пользователь: {username}")
|
| 46 |
|
| 47 |
try:
|
| 48 |
+
response = requests.get(f"{DEFAULT_API_URL}/questions", timeout=15)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 49 |
response.raise_for_status()
|
| 50 |
questions_data = response.json()
|
| 51 |
except Exception as e:
|
| 52 |
+
return f"❌ Ошибка при загрузке вопросов: {e}", None
|
| 53 |
|
| 54 |
+
agent = GeminiAgent()
|
|
|
|
| 55 |
results_log = []
|
| 56 |
+
answers_payload = []
|
| 57 |
|
| 58 |
for item in questions_data:
|
| 59 |
task_id = item.get("task_id")
|
| 60 |
+
question_text = item.get("question")
|
| 61 |
+
if not task_id or not question_text:
|
| 62 |
continue
|
| 63 |
+
answer = agent(question_text)
|
| 64 |
+
results_log.append({"Task ID": task_id, "Question": question_text, "Answer": answer})
|
| 65 |
+
answers_payload.append({"task_id": task_id, "submitted_answer": answer})
|
| 66 |
+
time.sleep(3) # ⏳ Задержка между запросами
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 67 |
|
| 68 |
try:
|
| 69 |
+
submission_data = {
|
| 70 |
+
"username": username,
|
| 71 |
+
"agent_code": agent_code,
|
| 72 |
+
"answers": answers_payload
|
| 73 |
+
}
|
| 74 |
+
submit_response = requests.post(f"{DEFAULT_API_URL}/submit", json=submission_data)
|
| 75 |
+
submit_response.raise_for_status()
|
| 76 |
+
result = submit_response.json()
|
| 77 |
+
score = result.get("score", "N/A")
|
| 78 |
+
return f"✅ Отправка завершена! Ваш результат: {score}%", pd.DataFrame(results_log)
|
|
|
|
| 79 |
except Exception as e:
|
| 80 |
+
return f"❌ Ошибка при отправке ответов: {e}", pd.DataFrame(results_log)
|
| 81 |
|
| 82 |
+
# Gradio UI
|
| 83 |
with gr.Blocks() as demo:
|
| 84 |
+
gr.Markdown("## Gemini 2.5 Agent 🤖")
|
| 85 |
+
gr.Markdown("Войдите в Hugging Face и нажмите кнопку для запуска агента.")
|
|
|
|
|
|
|
|
|
|
|
|
|
| 86 |
gr.LoginButton()
|
| 87 |
+
run_btn = gr.Button("▶️ Запустить агента")
|
| 88 |
+
status = gr.Textbox(label="Статус")
|
| 89 |
+
table = gr.DataFrame(label="Результаты")
|
|
|
|
| 90 |
run_btn.click(fn=run_and_submit_all, outputs=[status, table])
|
| 91 |
|
| 92 |
if __name__ == "__main__":
|
|
|
|
| 93 |
demo.launch()
|