FinnNick commited on
Commit
3c83ee3
·
verified ·
1 Parent(s): 1802d94

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +17 -25
app.py CHANGED
@@ -5,7 +5,7 @@ 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-pro"
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
 
@@ -25,26 +25,24 @@ class GeminiAgent:
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}: 429 Too Many Requests — ждём 5 сек...")
29
  time.sleep(5)
30
  continue
31
  response.raise_for_status()
32
- raw = response.json()
33
- answer = raw["candidates"][0]["content"]["parts"][0]["text"]
34
- return str(answer).strip()
35
  except Exception as e:
36
- print(f"❌ Ошибка Gemini API: {e}")
37
  time.sleep(5)
38
- return "Не удалось получить ответ. Попробуйте позже."
39
 
40
  def run_and_submit_all(profile: gr.OAuthProfile | None):
41
  space_id = os.getenv("SPACE_ID")
42
  if not profile:
43
- return "⚠️ Пожалуйста, войдите в Hugging Face", None
44
 
45
  username = profile.username
46
  agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
47
- print(f"👤 Пользователь: {username}")
48
 
49
  try:
50
  response = requests.get(f"{DEFAULT_API_URL}/questions", timeout=15)
@@ -57,17 +55,15 @@ def run_and_submit_all(profile: gr.OAuthProfile | None):
57
  results_log = []
58
  answers_payload = []
59
 
60
- for i, item in enumerate(questions_data):
61
  task_id = item.get("task_id")
62
  question_text = item.get("question")
63
  if not task_id or not question_text:
64
  continue
65
- answer = str(agent(question_text)).strip()
66
  results_log.append({"Task ID": task_id, "Question": question_text, "Answer": answer})
67
- if task_id and answer:
68
- answers_payload.append({"task_id": task_id, "submitted_answer": answer})
69
- print(f"✅ [{i+1}/{len(questions_data)}] ID: {task_id} | Ответ: {answer[:50]}")
70
- time.sleep(3)
71
 
72
  try:
73
  submission_data = {
@@ -75,25 +71,21 @@ def run_and_submit_all(profile: gr.OAuthProfile | None):
75
  "agent_code": agent_code,
76
  "answers": answers_payload
77
  }
78
-
79
- print("📤 Пример отправки:", submission_data["answers"][:2]) # Для отладки
80
  submit_response = requests.post(f"{DEFAULT_API_URL}/submit", json=submission_data)
81
  submit_response.raise_for_status()
82
  result = submit_response.json()
83
  score = result.get("score", "N/A")
84
- correct = result.get("correct_count", "?")
85
- total = result.get("total_attempted", "?")
86
- return f"✅ Отправка завершена!\nРезультат: {score}% ({correct}/{total})", pd.DataFrame(results_log)
87
  except Exception as e:
88
- return f"❌ Ошибка при отправке: {e}", pd.DataFrame(results_log)
89
 
90
  # Gradio UI
91
  with gr.Blocks() as demo:
92
- gr.Markdown("## 🤖 Gemini 2.5 Agent")
93
- gr.Markdown("Войдите в Hugging Face, затем нажмите кнопку запуска.")
94
  gr.LoginButton()
95
- run_btn = gr.Button("🚀 Запустить агента")
96
- status = gr.Textbox(label="Статус выполнения")
97
  table = gr.DataFrame(label="Результаты")
98
  run_btn.click(fn=run_and_submit_all, outputs=[status, table])
99
 
 
5
  import pandas as pd
6
 
7
  GEMINI_API_KEY = os.getenv("GEMINI_API_KEY")
8
+ GEMINI_MODEL = "gemini-2.5-pro"
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
 
 
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)
 
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 = {
 
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