yoshizen commited on
Commit
a3faa74
·
verified ·
1 Parent(s): 0d32a9e

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +125 -387
app.py CHANGED
@@ -17,12 +17,12 @@ import time
17
  import sys
18
 
19
  # Настройка логирования
20
- logging.basicConfig(level=logging.INFO)
21
  logger = logging.getLogger("GAIA-Mastermind")
22
 
23
  # Конфигурация
24
  DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
25
- MODEL_NAME = "google/flan-t5-large" # Упрощенная модель для CPU
26
  API_RETRIES = 3
27
  API_TIMEOUT = 45
28
 
@@ -33,12 +33,12 @@ class GAIAThoughtProcessor:
33
  logger.info(f"⚡ Инициализация GAIAThoughtProcessor на {self.device.upper()}")
34
 
35
  try:
36
- # Оптимизированная загрузка модели
37
  self.tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME)
38
  self.model = AutoModelForSeq2SeqLM.from_pretrained(
39
  MODEL_NAME,
40
  device_map="auto" if torch.cuda.is_available() else None,
41
- torch_dtype=torch.float16 if "cuda" in self.device else torch.float32,
42
  low_cpu_mem_usage=True
43
  ).eval()
44
 
@@ -47,8 +47,8 @@ class GAIAThoughtProcessor:
47
  "text2text-generation",
48
  model=self.model,
49
  tokenizer=self.tokenizer,
50
- device=self.device,
51
- max_new_tokens=256
52
  )
53
 
54
  logger.info("✅ GAIAThoughtProcessor готов")
@@ -56,158 +56,30 @@ class GAIAThoughtProcessor:
56
  logger.exception("Ошибка инициализации модели")
57
  raise RuntimeError(f"Ошибка инициализации: {str(e)}")
58
 
59
- def _math_solver(self, expression: str) -> str:
60
- """Безопасное вычисление математических выражений"""
61
- try:
62
- # Очистка выражения
63
- clean_expr = re.sub(r"[^0-9+\-*/().^√π]", "", expression)
64
- # Поддержка математических функций
65
- context = {
66
- "sqrt": np.sqrt,
67
- "log": np.log,
68
- "log10": np.log10,
69
- "pi": np.pi,
70
- "e": np.e,
71
- "sin": np.sin,
72
- "cos": np.cos,
73
- "tan": np.tan
74
- }
75
- return str(eval(clean_expr, {"__builtins__": None}, context))
76
- except Exception as e:
77
- logger.error(f"Math error: {e}")
78
- return f"Math Error: {str(e)}"
79
-
80
- def _table_analyzer(self, table_data: str, query: str) -> str:
81
- """Анализ табличных данных"""
82
- try:
83
- # Автоопределение формата таблицы
84
- if "\t" in table_data:
85
- df = pd.read_csv(io.StringIO(table_data), sep="\t")
86
- elif "," in table_data:
87
- df = pd.read_csv(io.StringIO(table_data))
88
- else:
89
- df = pd.read_fwf(io.StringIO(table_data))
90
-
91
- # Выполнение запросов
92
- query = query.lower()
93
- if "sum" in query:
94
- return str(df.sum(numeric_only=True).to_dict())
95
- elif "mean" in query:
96
- return str(df.mean(numeric_only=True).to_dict())
97
- elif "max" in query:
98
- return str(df.max(numeric_only=True).to_dict())
99
- elif "min" in query:
100
- return str(df.min(numeric_only=True).to_dict())
101
- elif "count" in query:
102
- return str(df.count().to_dict())
103
- else:
104
- return df.describe().to_string()
105
- except Exception as e:
106
- logger.error(f"Table error: {e}")
107
- return f"Table Error: {str(e)}"
108
-
109
- def _text_processor(self, text: str, operation: str) -> str:
110
- """Операции с текстом"""
111
- operation = operation.lower()
112
- if operation == "reverse":
113
- return text[::-1]
114
- elif operation == "count_words":
115
- return str(len(text.split()))
116
- elif operation == "extract_numbers":
117
- return ", ".join(re.findall(r"[-+]?\d*\.\d+|\d+", text))
118
- elif operation == "uppercase":
119
- return text.upper()
120
- elif operation == "lowercase":
121
- return text.lower()
122
- else:
123
- return f"Unsupported operation: {operation}"
124
-
125
- def _image_processor(self, image_input: str) -> str:
126
- """Обработка изображений"""
127
- try:
128
- # Обработка URL
129
- if image_input.startswith("http"):
130
- response = requests.get(image_input, timeout=30)
131
- response.raise_for_status()
132
- img_data = response.content
133
- img = Image.open(io.BytesIO(img_data))
134
- # Обработка base64
135
- elif image_input.startswith("data:image"):
136
- header, data = image_input.split(",", 1)
137
- img_data = base64.b64decode(data)
138
- img = Image.open(io.BytesIO(img_data))
139
- else:
140
- return "Invalid image format"
141
-
142
- # Базовый анализ изображения
143
- description = (
144
- f"Format: {img.format}, Size: {img.size}, "
145
- f"Mode: {img.mode}"
146
- )
147
- return description
148
- except (UnidentifiedImageError, requests.exceptions.RequestException) as e:
149
- logger.error(f"Image processing error: {e}")
150
- return f"Image Error: {str(e)}"
151
- except Exception as e:
152
- logger.exception("Unexpected image error")
153
- return f"Unexpected Error: {str(e)}"
154
-
155
- def _call_tool(self, tool_name: str, arguments: str) -> str:
156
- """Вызов инструмента по имени"""
157
  try:
158
- # Парсинг аргументов
159
- args = [a.strip() for a in arguments.split(",")]
160
 
161
- if tool_name == "math_solver":
162
- return self._math_solver(args[0])
163
- elif tool_name == "table_analyzer":
164
- return self._table_analyzer(args[0], args[1])
165
- elif tool_name == "text_processor":
166
- return self._text_processor(args[0], args[1])
167
- elif tool_name == "image_processor":
168
- return self._image_processor(args[0])
169
- else:
170
- return f"Unknown tool: {tool_name}"
171
- except Exception as e:
172
- return f"Tool Error: {str(e)}"
173
-
174
- def _generate_response(self, prompt: str) -> str:
175
- """Генерация ответа с помощью модели"""
176
- try:
177
  result = self.text_generator(
178
  prompt,
179
- max_new_tokens=256,
180
- num_beams=3,
181
  early_stopping=True,
182
- temperature=0.01
183
  )
184
- return result[0]['generated_text']
185
- except Exception as e:
186
- logger.error(f"Generation error: {e}")
187
- return f"Generation Error: {str(e)}"
188
- finally:
189
- # Очистка памяти GPU
190
- if "cuda" in self.device:
191
- torch.cuda.empty_cache()
192
-
193
- def process_question(self, question: str, task_id: str) -> str:
194
- """Обработка вопроса с декомпозицией на шаги"""
195
- try:
196
- # Упрощенный промпт для CPU
197
- prompt = f"Реши задачу шаг за шагом: {question}\n\nФинальный ответ:"
198
- response = self._generate_response(prompt)
199
 
200
- # Извлечение чистого ответа
201
- if "final_answer" in response:
202
- return json.dumps({"final_answer": response})
203
- else:
204
- return json.dumps({"final_answer": response.strip()})
205
  except Exception as e:
206
- logger.exception("Processing failed")
207
  return json.dumps({
208
  "task_id": task_id,
209
  "error": str(e),
210
- "final_answer": f"SYSTEM ERROR: {str(e)}"
211
  })
212
 
213
  # === СИСТЕМА ОЦЕНКИ ===
@@ -224,198 +96,87 @@ class GAIAEvaluationRunner:
224
  })
225
  logger.info(f"🌐 Инициализирован GAIAEvaluationRunner для {api_url}")
226
 
227
- def run_evaluation(self, agent, username: str, agent_code: str, progress=tqdm):
228
- # Получение вопросов
229
- questions, status = self._fetch_questions()
230
- if status != "success":
231
- # Возвращаем ошибку в понятном формате
232
- error_df = pd.DataFrame([{
233
- "Task ID": "ERROR",
234
- "Question": status,
235
- "Answer": "Не удалось получить вопросы",
236
- "Status": "Failed"
237
- }])
238
- return status, 0, 0, error_df
239
-
240
- # Обработка вопросов
241
- results = []
242
- answers = []
243
- for i, q in enumerate(progress(questions, desc="🧠 Processing GAIA")):
244
- try:
245
- task_id = q.get("task_id", f"unknown_{i}")
246
- json_response = agent.process_question(q["question"], task_id)
247
-
248
- # Парсинг ответа
249
- try:
250
- response_obj = json.loads(json_response)
251
- final_answer = response_obj.get("final_answer", "")
252
- if not isinstance(final_answer, str):
253
- final_answer = str(final_answer)
254
- except json.JSONDecodeError:
255
- final_answer = json_response
256
-
257
- # Формирование ответа для GAIA API
258
- answers.append({
259
- "task_id": task_id,
260
- "answer": final_answer[:500] # Ограничение длины
261
- })
262
-
263
- # Запись результатов
264
- results.append({
265
- "Task ID": task_id,
266
- "Question": q["question"][:100] + "..." if len(q["question"]) > 100 else q["question"],
267
- "Answer": final_answer[:100] + "..." if len(final_answer) > 100 else final_answer,
268
- "Status": "Processed"
269
- })
270
- except Exception as e:
271
- logger.error(f"Task {task_id} failed: {e}")
272
- answers.append({
273
- "task_id": task_id,
274
- "answer": f"ERROR: {str(e)}"
275
- })
276
- results.append({
277
- "Task ID": task_id,
278
- "Question": "Error",
279
- "Answer": f"ERROR: {str(e)}",
280
- "Status": "Failed"
281
- })
282
-
283
- # Отправка ответов
284
- try:
285
- submission_result, score = self._submit_answers(username, agent_code, answers)
286
- return submission_result, score, len(questions), pd.DataFrame(results)
287
- except Exception as e:
288
- error_message = f"Ошибка отправки: {str(e)}"
289
- results.append({
290
- "Task ID": "SUBMIT_ERROR",
291
- "Question": error_message,
292
- "Answer": "",
293
- "Status": "Failed"
294
- })
295
- return error_message, 0, len(questions), pd.DataFrame(results)
296
-
297
  def _fetch_questions(self) -> Tuple[list, str]:
298
  """Получение вопросов с API"""
299
- for attempt in range(API_RETRIES):
300
- try:
301
- response = self.session.get(
302
- self.questions_url,
303
- timeout=API_TIMEOUT
304
- )
305
-
306
- if response.status_code == 200:
307
- questions = response.json()
308
- if not isinstance(questions, list):
309
- return [], f"Неверный формат ответа: ожидался список, получен {type(questions)}"
310
-
311
- # Добавление task_id если отсутствует
312
- for q in questions:
313
- q.setdefault("task_id", f"id_{hash(q['question']) % 100000}")
314
- return questions, "success"
315
-
316
- elif response.status_code == 429:
317
- wait_time = 2 ** attempt # Экспоненциальная задержка
318
- logger.warning(f"Rate limited, retrying in {wait_time}s...")
319
- time.sleep(wait_time)
320
- continue
321
-
322
- else:
323
- return [], f"Ошибка API: HTTP {response.status_code} - {response.text}"
324
 
325
- except requests.exceptions.RequestException as e:
326
- logger.error(f"Ошибка соединения: {e}")
327
- return [], f"Ошибка сети: {str(e)}"
328
- except Exception as e:
329
- logger.error(f"Неожиданная ошибка: {e}")
330
- return [], f"Неожиданная ошибка: {str(e)}"
331
-
332
- return [], "API недоступен после попыток"
333
 
334
  def _submit_answers(self, username: str, agent_code: str, answers: list) -> Tuple[str, int]:
335
  """Отправка ответов на сервер"""
336
- payload = {
337
- "username": username.strip(),
338
- "agent_code": agent_code.strip(),
339
- "answers": answers
340
- }
341
-
342
- for attempt in range(API_RETRIES):
343
- try:
344
- response = self.session.post(
345
- self.submit_url,
346
- json=payload,
347
- timeout=API_TIMEOUT * 2
348
- )
349
-
350
- if response.status_code == 200:
351
- result = response.json()
352
- score = result.get("score", 0)
353
- return result.get("message", "Ответы успешно отправлены"), score
354
-
355
- elif response.status_code == 400:
356
- error = response.json().get("error", "Неверный запрос")
357
- logger.error(f"Ошибка валидации: {error}")
358
- return f"Ошибка валидации: {error}", 0
359
-
360
- elif response.status_code == 429:
361
- wait_time = 5 * (attempt + 1)
362
- logger.warning(f"Rate limited, retrying in {wait_time}s...")
363
- time.sleep(wait_time)
364
- continue
365
-
366
- else:
367
- return f"HTTP Ошибка {response.status_code} - {response.text}", 0
368
 
369
- except requests.exceptions.RequestException as e:
370
- logger.error(f"Ошибка отправки: {e}")
371
- return f"Ошибка сети: {str(e)}", 0
372
- except Exception as e:
373
- logger.error(f"Неожиданная ошибка отправки: {e}")
374
- return f"Неожиданная ошибка: {str(e)}", 0
375
-
376
- return "Сбой отправки после попыток", 0
377
 
378
- # === ИНТЕРФЕЙС GRADIO ===
379
- def run_evaluation(username: str, agent_code: str, progress=gr.Progress()):
380
- try:
381
- progress(0, desc="⚡ Инициализация GAIA Mastermind...")
382
- agent = GAIAThoughtProcessor()
383
-
384
- progress(0.1, desc="🌐 Подключение к GAIA API...")
385
- runner = GAIAEvaluationRunner()
386
-
387
  # Получение вопросов
388
- progress(0.2, desc="📡 Получение вопросов...")
389
- questions, status = runner._fetch_questions()
390
  if status != "success":
391
- error_message = f"Ошибка: {status}"
392
- error_df = pd.DataFrame([{
393
- "Task ID": "ERROR",
394
- "Question": error_message,
395
- "Answer": "Не удалось получить вопросы",
396
- "Status": "Failed"
397
- }])
398
- return error_message, 0, 0, error_df
399
 
400
- total = len(questions)
401
- if total == 0:
402
- error_message = "Получено 0 вопросов"
403
- error_df = pd.DataFrame([{
404
- "Task ID": "ERROR",
405
- "Question": error_message,
406
- "Answer": "Нет данных",
407
- "Status": "Failed"
408
- }])
409
- return error_message, 0, 0, error_df
410
 
411
- # Обработка вопросов с прогрессом
412
  results = []
413
  answers = []
414
 
415
  for i, q in enumerate(questions):
416
- progress(i / total, desc=f"🧠 Обработка задачи {i+1}/{total}")
417
  try:
418
- task_id = q.get("task_id", f"unknown_{i}")
 
 
419
  json_response = agent.process_question(q["question"], task_id)
420
 
421
  # Парсинг ответа
@@ -432,12 +193,12 @@ def run_evaluation(username: str, agent_code: str, progress=gr.Progress()):
432
 
433
  results.append({
434
  "Task ID": task_id,
435
- "Question": q["question"][:100] + "..." if len(q["question"]) > 100 else q["question"],
436
- "Answer": str(final_answer)[:100] + "..." if len(str(final_answer)) > 100 else str(final_answer),
437
  "Status": "Processed"
438
  })
439
  except Exception as e:
440
- logger.error(f"Task {task_id} failed: {e}")
441
  answers.append({
442
  "task_id": task_id,
443
  "answer": f"ERROR: {str(e)}"
@@ -450,84 +211,63 @@ def run_evaluation(username: str, agent_code: str, progress=gr.Progress()):
450
  })
451
 
452
  # Отправка ответов
453
- progress(0.9, desc="📤 Отправка результатов...")
454
- submission_result, score = runner._submit_answers(username, agent_code, answers)
455
- return submission_result, score, total, pd.DataFrame(results)
 
 
 
 
 
 
 
 
 
 
 
 
456
 
457
  except Exception as e:
458
- logger.exception("Critical error in run_evaluation")
459
- error_message = f"Критическая ошибка: {str(e)}"
460
  error_df = pd.DataFrame([{
461
- "Task ID": "CRITICAL",
462
- "Question": error_message,
463
  "Answer": "См. логи",
464
  "Status": "Failed"
465
  }])
466
- return error_message, 0, 0, error_df
467
 
468
  # Создание интерфейса
469
- with gr.Blocks(
470
- title="🧠 GAIA Mastermind",
471
- theme=gr.themes.Soft(),
472
- css="""
473
- .gradio-container {background: linear-gradient(135deg, #1a2a6c, #2c5364)}
474
- .dark {color: #f0f0f0}
475
- """
476
- ) as demo:
477
- gr.Markdown("""
478
- <div style="text-align:center; background: linear-gradient(135deg, #0f2027, #203a43);
479
- padding: 20px; border-radius: 15px; color: white; box-shadow: 0 10px 20px rgba(0,0,0,0.3);">
480
- <h1>🧠 GAIA Mastermind</h1>
481
- <h3>Многошаговое решение задач с декомпозицией</h3>
482
- <p>Соответствует спецификации GAIA API</p>
483
- </div>
484
- """)
485
 
486
  with gr.Row():
487
- with gr.Column(scale=1):
488
- gr.Markdown("### 🔐 Авторизация")
489
- username = gr.Textbox(
490
- label="HF Username",
491
- value="yoshizen",
492
- info="Ваше имя пользователя Hugging Face"
493
- )
494
- agent_code = gr.Textbox(
495
- label="Agent Code",
496
- value="https://huggingface.co/spaces/yoshizen/FinalTest",
497
- info="URL вашего агента"
498
- )
499
- run_btn = gr.Button("🚀 Запустить оценку", variant="primary", scale=1)
500
 
501
- gr.Markdown("### ⚙️ Статус системы")
502
- sys_info = gr.Textbox(label="Системная информация", interactive=False, value="")
503
 
504
- with gr.Column(scale=2):
505
- gr.Markdown("### 📊 Результаты GAIA")
506
  with gr.Row():
507
- result_output = gr.Textbox(
508
- label="Статус отправки",
509
- interactive=False,
510
- max_lines=3
511
- )
512
- correct_output = gr.Number(
513
- label="✅ Правильные ответы",
514
- interactive=False
515
- )
516
- total_output = gr.Number(
517
- label="📚 Всего вопросов",
518
- interactive=False
519
- )
520
 
521
- # Упрощенный Dataframe
522
  results_table = gr.Dataframe(
523
- label="🔍 Детализация ответов",
524
  headers=["Task ID", "Question", "Answer", "Status"],
525
  interactive=False
526
  )
527
 
528
  # Системная информация
529
  def get_system_info():
530
- device = "GPU" if torch.cuda.is_available() else "CPU ⚠️"
531
  return f"Device: {device} | Model: {MODEL_NAME} | API: {DEFAULT_API_URL}"
532
 
533
  demo.load(get_system_info, inputs=None, outputs=sys_info)
@@ -536,15 +276,13 @@ with gr.Blocks(
536
  fn=run_evaluation,
537
  inputs=[username, agent_code],
538
  outputs=[result_output, correct_output, total_output, results_table],
539
- concurrency_limit=1,
540
- show_progress="minimal"
541
  )
542
 
543
  if __name__ == "__main__":
544
- demo.queue(max_size=5).launch(
545
  server_name="0.0.0.0",
546
  server_port=7860,
547
  share=False,
548
- show_error=True,
549
- debug=True # Включение детального лога
550
  )
 
17
  import sys
18
 
19
  # Настройка логирования
20
+ logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
21
  logger = logging.getLogger("GAIA-Mastermind")
22
 
23
  # Конфигурация
24
  DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
25
+ MODEL_NAME = "google/flan-t5-large" # Оптимизировано для CPU
26
  API_RETRIES = 3
27
  API_TIMEOUT = 45
28
 
 
33
  logger.info(f"⚡ Инициализация GAIAThoughtProcessor на {self.device.upper()}")
34
 
35
  try:
36
+ # Оптимизированная загрузка модели для CPU
37
  self.tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME)
38
  self.model = AutoModelForSeq2SeqLM.from_pretrained(
39
  MODEL_NAME,
40
  device_map="auto" if torch.cuda.is_available() else None,
41
+ torch_dtype=torch.float32,
42
  low_cpu_mem_usage=True
43
  ).eval()
44
 
 
47
  "text2text-generation",
48
  model=self.model,
49
  tokenizer=self.tokenizer,
50
+ device=-1 if self.device == "cpu" else 0,
51
+ max_new_tokens=128
52
  )
53
 
54
  logger.info("✅ GAIAThoughtProcessor готов")
 
56
  logger.exception("Ошибка инициализации модели")
57
  raise RuntimeError(f"Ошибка инициализации: {str(e)}")
58
 
59
+ def process_question(self, question: str, task_id: str) -> str:
60
+ """Упрощенная обработка вопроса"""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
61
  try:
62
+ prompt = f"Реши задачу шаг за шагом: {question}\n\nФинальный ответ:"
 
63
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
64
  result = self.text_generator(
65
  prompt,
66
+ max_new_tokens=128,
67
+ num_beams=2,
68
  early_stopping=True,
69
+ temperature=0.1
70
  )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
71
 
72
+ response = result[0]['generated_text'].strip()
73
+
74
+ # Создаем JSON ответ
75
+ return json.dumps({"final_answer": response})
76
+
77
  except Exception as e:
78
+ logger.error(f"Ошибка обработки вопроса: {str(e)}")
79
  return json.dumps({
80
  "task_id": task_id,
81
  "error": str(e),
82
+ "final_answer": f"ERROR: {str(e)}"
83
  })
84
 
85
  # === СИСТЕМА ОЦЕНКИ ===
 
96
  })
97
  logger.info(f"🌐 Инициализирован GAIAEvaluationRunner для {api_url}")
98
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
99
  def _fetch_questions(self) -> Tuple[list, str]:
100
  """Получение вопросов с API"""
101
+ logger.info(f"🔍 Запрос вопросов с {self.questions_url}")
102
+ try:
103
+ response = self.session.get(
104
+ self.questions_url,
105
+ timeout=API_TIMEOUT
106
+ )
107
+
108
+ logger.info(f"Статус ответа: {response.status_code}")
109
+
110
+ if response.status_code == 200:
111
+ questions = response.json()
112
+ logger.info(f"Получено {len(questions)} вопросов")
113
+ return questions, "success"
114
+ else:
115
+ error_msg = f"Ошибка API: HTTP {response.status_code}"
116
+ logger.error(error_msg)
117
+ return [], error_msg
 
 
 
 
 
 
 
 
118
 
119
+ except Exception as e:
120
+ error_msg = f"Ошибка соединения: {str(e)}"
121
+ logger.exception(error_msg)
122
+ return [], error_msg
 
 
 
 
123
 
124
  def _submit_answers(self, username: str, agent_code: str, answers: list) -> Tuple[str, int]:
125
  """Отправка ответов на сервер"""
126
+ logger.info(f"📤 Отправка ответов для пользователя {username}")
127
+ try:
128
+ payload = {
129
+ "username": username.strip(),
130
+ "agent_code": agent_code.strip(),
131
+ "answers": answers
132
+ }
133
+
134
+ response = self.session.post(
135
+ self.submit_url,
136
+ json=payload,
137
+ timeout=API_TIMEOUT * 2
138
+ )
139
+
140
+ logger.info(f"Статус отправки: {response.status_code}")
141
+
142
+ if response.status_code == 200:
143
+ result = response.json()
144
+ score = result.get("score", 0)
145
+ return result.get("message", "Ответы успешно отправлены"), score
146
+ else:
147
+ error = f"HTTP Ошибка {response.status_code}"
148
+ if response.text:
149
+ error += f": {response.text[:200]}"
150
+ logger.error(error)
151
+ return error, 0
 
 
 
 
 
 
152
 
153
+ except Exception as e:
154
+ error = f"Ошибка отправки: {str(e)}"
155
+ logger.exception(error)
156
+ return error, 0
 
 
 
 
157
 
158
+ def run_evaluation(self, agent, username: str, agent_code: str, progress=gr.Progress()):
159
+ """Основной процесс оценки"""
 
 
 
 
 
 
 
160
  # Получение вопросов
161
+ progress(0.1, desc="Получение вопросов")
162
+ questions, status = self._fetch_questions()
163
  if status != "success":
164
+ return status, 0, 0, pd.DataFrame()
 
 
 
 
 
 
 
165
 
166
+ total_questions = len(questions)
167
+ if total_questions == 0:
168
+ return "Получено 0 вопросов", 0, 0, pd.DataFrame()
 
 
 
 
 
 
 
169
 
170
+ # Обработка вопросов
171
  results = []
172
  answers = []
173
 
174
  for i, q in enumerate(questions):
175
+ progress(i / total_questions, desc=f"Обработка задачи {i+1}/{total_questions}")
176
  try:
177
+ task_id = q.get("task_id", f"task_{i}")
178
+ logger.info(f"🔧 Обработка задачи {task_id}")
179
+
180
  json_response = agent.process_question(q["question"], task_id)
181
 
182
  # Парсинг ответа
 
193
 
194
  results.append({
195
  "Task ID": task_id,
196
+ "Question": q["question"][:50] + "..." if len(q["question"]) > 50 else q["question"],
197
+ "Answer": str(final_answer)[:50] + "..." if len(str(final_answer)) > 50 else str(final_answer),
198
  "Status": "Processed"
199
  })
200
  except Exception as e:
201
+ logger.error(f"Ошибка обработки задачи: {str(e)}")
202
  answers.append({
203
  "task_id": task_id,
204
  "answer": f"ERROR: {str(e)}"
 
211
  })
212
 
213
  # Отправка ответов
214
+ progress(0.9, desc="Отправка результатов")
215
+ submission_result, score = self._submit_answers(username, agent_code, answers)
216
+ return submission_result, score, total_questions, pd.DataFrame(results)
217
+
218
+ # === ИНТЕРФЕЙС GRADIO ===
219
+ def run_evaluation(username: str, agent_code: str, progress=gr.Progress()):
220
+ try:
221
+ progress(0, desc="Инициализация агента")
222
+ agent = GAIAThoughtProcessor()
223
+
224
+ progress(0.1, desc="Подключение к API")
225
+ runner = GAIAEvaluationRunner()
226
+
227
+ # Запуск оценки
228
+ return runner.run_evaluation(agent, username, agent_code, progress)
229
 
230
  except Exception as e:
231
+ logger.exception("Критическая ошибка в run_evaluation")
 
232
  error_df = pd.DataFrame([{
233
+ "Task ID": "ERROR",
234
+ "Question": f"Критическая ошибка: {str(e)}",
235
  "Answer": "См. логи",
236
  "Status": "Failed"
237
  }])
238
+ return f"Ошибка: {str(e)}", 0, 0, error_df
239
 
240
  # Создание интерфейса
241
+ with gr.Blocks(title="GAIA Mastermind") as demo:
242
+ gr.Markdown("# GAIA Mastermind")
243
+ gr.Markdown("Многошаговое решение задач с декомпозицией")
 
 
 
 
 
 
 
 
 
 
 
 
 
244
 
245
  with gr.Row():
246
+ with gr.Column():
247
+ gr.Markdown("## 🔐 Авторизация")
248
+ username = gr.Textbox(label="HF Username", value="yoshizen")
249
+ agent_code = gr.Textbox(label="Agent Code", value="https://huggingface.co/spaces/yoshizen/FinalTest")
250
+ run_btn = gr.Button("Запустить оценку")
 
 
 
 
 
 
 
 
251
 
252
+ gr.Markdown("## ⚙️ Статус системы")
253
+ sys_info = gr.Textbox(label="Системная информация", interactive=False)
254
 
255
+ with gr.Column():
256
+ gr.Markdown("## 📊 Результаты GAIA")
257
  with gr.Row():
258
+ result_output = gr.Textbox(label="Статус отправки", interactive=False)
259
+ correct_output = gr.Number(label="Правильные ответы", interactive=False)
260
+ total_output = gr.Number(label="Всего вопросов", interactive=False)
 
 
 
 
 
 
 
 
 
 
261
 
 
262
  results_table = gr.Dataframe(
263
+ label="Детализация ответов",
264
  headers=["Task ID", "Question", "Answer", "Status"],
265
  interactive=False
266
  )
267
 
268
  # Системная информация
269
  def get_system_info():
270
+ device = "GPU" if torch.cuda.is_available() else "CPU"
271
  return f"Device: {device} | Model: {MODEL_NAME} | API: {DEFAULT_API_URL}"
272
 
273
  demo.load(get_system_info, inputs=None, outputs=sys_info)
 
276
  fn=run_evaluation,
277
  inputs=[username, agent_code],
278
  outputs=[result_output, correct_output, total_output, results_table],
279
+ concurrency_limit=1
 
280
  )
281
 
282
  if __name__ == "__main__":
283
+ demo.queue(max_size=1).launch(
284
  server_name="0.0.0.0",
285
  server_port=7860,
286
  share=False,
287
+ show_error=True
 
288
  )