Mustafa-albakkar commited on
Commit
63f1c30
·
verified ·
1 Parent(s): 6cfad42

Upload main.py

Browse files
Files changed (1) hide show
  1. main.py +555 -0
main.py ADDED
@@ -0,0 +1,555 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import pandas as pd
3
+ from fastapi import FastAPI, HTTPException, Body
4
+ from fastapi.responses import FileResponse
5
+ from pydantic import BaseModel, Field
6
+ from typing import List, Dict, Any, Optional, Union
7
+ from datasets import load_dataset, Dataset, DatasetDict
8
+ from huggingface_hub import HfApi, hf_hub_download
9
+ from datetime import datetime, timezone
10
+ import logging
11
+ import uvicorn
12
+ import random
13
+ import mimetypes
14
+ # --- Constants and Config ---
15
+ HF_DATASET_ID = "agents-course/unit4-students-scores"
16
+
17
+
18
+ logging.basicConfig(level=logging.INFO)
19
+ logger = logging.getLogger(__name__)
20
+
21
+ task_file_paths: Dict[str, str] = {}
22
+ tool_threshold = 3
23
+ step_threshold = 6
24
+ questions_for_api: List[Dict[str, Any]] = []
25
+ ground_truth_answers: Dict[str, str] = {}
26
+ filtered_dataset = None
27
+
28
+ ALLOWED_CACHE_BASE = os.path.abspath("/app/.cache")
29
+
30
+ class ErrorResponse(BaseModel):
31
+ detail: str
32
+
33
+
34
+ def load_questions():
35
+ """
36
+ Loads the GAIA dataset, filters questions based on tool/step counts,
37
+ populates 'questions_for_api' with data for the API (excluding sensitive/internal fields),
38
+ stores ground truth answers, and maps task IDs to their local file paths on the server.
39
+ """
40
+ global filtered_dataset
41
+ global questions_for_api
42
+ global ground_truth_answers
43
+ global task_file_paths
44
+
45
+ tempo_filtered = []
46
+ questions_for_api.clear()
47
+ ground_truth_answers.clear()
48
+ task_file_paths.clear()
49
+
50
+ logger.info("Starting to load and filter GAIA dataset (validation split)...")
51
+ try:
52
+ dataset = load_dataset("gaia-benchmark/GAIA", "2023_level1", split="validation", trust_remote_code=True)
53
+ logger.info(f"GAIA dataset validation split loaded. Features: {dataset.features}")
54
+ except Exception as e:
55
+ logger.error(f"Failed to load GAIA dataset: {e}", exc_info=True)
56
+ raise RuntimeError("Could not load the primary GAIA dataset.") from e
57
+
58
+ # --- Filtering Logic based on Annotator Metadata ---
59
+ for item in dataset:
60
+ metadata = item.get('Annotator Metadata')
61
+
62
+ if metadata:
63
+ num_tools_str = metadata.get('Number of tools')
64
+ num_steps_str = metadata.get('Number of steps')
65
+
66
+ if num_tools_str is not None and num_steps_str is not None:
67
+ try:
68
+ num_tools = int(num_tools_str)
69
+ num_steps = int(num_steps_str)
70
+ if num_tools < tool_threshold and num_steps < step_threshold:
71
+ tempo_filtered.append(item)
72
+ except ValueError:
73
+ logger.warning(f"Skipping Task ID: {item.get('task_id', 'N/A')} - Could not convert tool/step count in metadata: tools='{num_tools_str}', steps='{num_steps_str}'.")
74
+ else:
75
+ logger.warning(f"Skipping Task ID: {item.get('task_id', 'N/A')} - 'Number of tools' or 'Number of steps' missing in Metadata.")
76
+ else:
77
+ logger.warning(f"Skipping Task ID: {item.get('task_id', 'N/A')} - Missing 'Annotator Metadata'.")
78
+
79
+ filtered_dataset = tempo_filtered
80
+ logger.info(f"Found {len(filtered_dataset)} questions matching the criteria (tools < {tool_threshold}, steps < {step_threshold}).")
81
+
82
+ processed_count = 0
83
+ for item in filtered_dataset:
84
+ # Extract data from the dataset item
85
+ task_id = item.get('task_id')
86
+ original_question_text = item.get('Question')
87
+ final_answer = item.get('Final answer')
88
+ local_file_path = item.get('file_path')
89
+ file_name = item.get('file_name')
90
+
91
+ if task_id and original_question_text and final_answer is not None:
92
+
93
+ # 1. Create the dictionary to be exposed via the API
94
+ # (Includes 'file_name' for info, but excludes 'file_path')
95
+ processed_item = {
96
+ "task_id": str(task_id),
97
+ "question": str(original_question_text),
98
+ "Level": item.get("Level"),
99
+ "file_name": file_name,
100
+ }
101
+ processed_item = {k: v for k, v in processed_item.items() if v is not None}
102
+
103
+ questions_for_api.append(processed_item)
104
+
105
+ # 2. Store the ground truth answer separately
106
+ ground_truth_answers[str(task_id)] = str(final_answer)
107
+
108
+ # 3. Store the file path mapping if file details exist and are valid
109
+ if local_file_path and file_name:
110
+ # Log if the path from the dataset isn't absolute (might indicate issues)
111
+ if not os.path.isabs(local_file_path):
112
+ logger.warning(f"Task {task_id}: Path '{local_file_path}' from dataset is not absolute. This might cause issues finding the file on the server.")
113
+
114
+
115
+ if os.path.exists(local_file_path) and os.path.isfile(local_file_path):
116
+ task_file_paths[str(task_id)] = local_file_path
117
+ logger.debug(f"Stored file path mapping for task_id {task_id}: {local_file_path}")
118
+ else:
119
+ logger.warning(f"File path '{local_file_path}' for task_id {task_id} does NOT exist or is not a file on server. Mapping skipped.")
120
+ elif task_id:
121
+
122
+ if not local_file_path and not file_name:
123
+ logger.debug(f"Task {task_id}: No 'file_path' or 'file_name' found in dataset item. No file mapping stored.")
124
+ elif not local_file_path:
125
+ logger.debug(f"Task {task_id}: 'file_path' is missing in dataset item (file_name: '{file_name}'). No file mapping stored.")
126
+ else: # Not file_name
127
+ logger.debug(f"Task {task_id}: 'file_name' is missing in dataset item (file_path: '{local_file_path}'). No file mapping stored.")
128
+
129
+
130
+ processed_count += 1
131
+ else:
132
+ logger.warning(f"Skipping item processing due to missing essential fields: task_id={task_id}, has_question={original_question_text is not None}, has_answer={final_answer is not None}")
133
+
134
+ logger.info(f"Successfully processed {processed_count} questions for the API.")
135
+ logger.info(f"Stored file path mappings for {len(task_file_paths)} tasks.")
136
+
137
+ if not questions_for_api:
138
+ logger.error("CRITICAL: No valid questions were loaded after filtering and processing. API endpoints like /questions will fail.")
139
+
140
+
141
+
142
+
143
+ class Question(BaseModel):
144
+ task_id: str
145
+ question: str
146
+ Level: Optional[str] = None
147
+ file_name: Optional[str] = None
148
+
149
+
150
+ # --- The rest of your Pydantic models remain the same ---
151
+ class AnswerItem(BaseModel):
152
+ task_id: str
153
+ submitted_answer: str = Field(..., description="The agent's answer for the task_id")
154
+
155
+ class Submission(BaseModel):
156
+ username: str = Field(..., description="Hugging Face username", min_length=1)
157
+ agent_code: str = Field(..., description="The Python class code for the agent")
158
+ answers: List[AnswerItem] = Field(..., description="List of answers submitted by the agent")
159
+
160
+ class ScoreResponse(BaseModel):
161
+ username: str
162
+ score: float
163
+ correct_count: int
164
+ total_attempted: int
165
+ message: str
166
+ timestamp: str
167
+
168
+ class ErrorResponse(BaseModel):
169
+ detail: str
170
+
171
+ class AnswerItem(BaseModel):
172
+ task_id: str
173
+ submitted_answer: Union[str, int, float] = Field(..., description="The agent's answer for the task_id. Accepts str, int and float")
174
+
175
+ class Submission(BaseModel):
176
+ username: str = Field(..., description="Hugging Face username", min_length=1)
177
+ agent_code: str = Field(..., description="The Python class code for the agent", min_length=10)
178
+ answers: List[AnswerItem] = Field(..., description="List of answers submitted by the agent")
179
+
180
+ class ScoreResponse(BaseModel):
181
+ username: str
182
+ score: float
183
+ correct_count: int
184
+ total_attempted: int
185
+ message: str
186
+ timestamp: str
187
+
188
+ class ErrorResponse(BaseModel):
189
+ detail: str
190
+
191
+
192
+ # --- FastAPI Application ---
193
+ app = FastAPI(
194
+ title="Agent Evaluation API",
195
+ description="API to fetch questions and submit agent answers for scoring.",
196
+ )
197
+
198
+ # --- Startup Event ---
199
+ @app.on_event("startup")
200
+ async def startup_event():
201
+ logger.info("Application startup: Loading questions...")
202
+ try:
203
+ load_questions()
204
+ if not questions_for_api:
205
+ logger.error("CRITICAL: No questions were loaded during startup.")
206
+ else:
207
+ logger.info(f"Successfully loaded {len(questions_for_api)} questions.")
208
+ except Exception as e:
209
+ logger.error(f"CRITICAL ERROR DURING STARTUP while loading questions: {e}", exc_info=True)
210
+
211
+
212
+
213
+ @app.get("/files/{task_id}",
214
+ summary="Get Associated File by Task ID",
215
+ description="Downloads the file associated with the given task_id, if one exists and is mapped.",
216
+ responses={
217
+ 200: {
218
+ "description": "File content.",
219
+ "content": {"*/*": {}}
220
+ },
221
+ 403: {"model": ErrorResponse, "description": "Access denied (e.g., path traversal attempt)."},
222
+ 404: {"model": ErrorResponse, "description": "Task ID not found, no file associated, or file missing on server."},
223
+ 500: {"model": ErrorResponse, "description": "Server error reading file."}
224
+ })
225
+ async def get_task_file(task_id: str):
226
+ """
227
+ Serves the file associated with a specific task ID.
228
+ Includes security checks to prevent accessing arbitrary files.
229
+ """
230
+ logger.info(f"Request received for file associated with task_id: {task_id}")
231
+
232
+ if task_id not in task_file_paths:
233
+ logger.warning(f"File request failed: task_id '{task_id}' not found in file path mapping.")
234
+ raise HTTPException(status_code=404, detail=f"No file path associated with task_id {task_id}.")
235
+
236
+ # --- ASSIGNMENT HAPPENS HERE ---
237
+ local_file_path = task_file_paths[task_id]
238
+ logger.debug(f"Mapped task_id '{task_id}' to local path: {local_file_path}")
239
+
240
+ # --- CRUCIAL SECURITY CHECK ---
241
+ try:
242
+
243
+ abs_file_path = os.path.abspath(local_file_path)
244
+ abs_base_path = ALLOWED_CACHE_BASE # Already absolute
245
+
246
+ if not abs_file_path.startswith(abs_base_path):
247
+ logger.error(f"SECURITY ALERT: Path traversal attempt denied for task_id '{task_id}'. Path '{local_file_path}' resolves outside base '{abs_base_path}'.")
248
+ raise HTTPException(status_code=403, detail="File access denied.")
249
+
250
+ if not os.path.exists(abs_file_path) or not os.path.isfile(abs_file_path):
251
+ logger.error(f"File not found on server for task_id '{task_id}' at expected path: {abs_file_path}")
252
+ raise HTTPException(status_code=404, detail=f"File associated with task_id {task_id} not found on server disk.")
253
+
254
+ except HTTPException as http_exc:
255
+ raise http_exc
256
+ except Exception as path_err:
257
+ logger.error(f"Error resolving or checking path '{local_file_path}' for task_id '{task_id}': {path_err}", exc_info=True)
258
+ raise HTTPException(status_code=500, detail="Server error validating file path.")
259
+
260
+
261
+ mime_type, _ = mimetypes.guess_type(abs_file_path)
262
+ media_type = mime_type if mime_type else "application/octet-stream"
263
+
264
+ file_name_for_download = os.path.basename(abs_file_path)
265
+
266
+ logger.info(f"Serving file '{file_name_for_download}' (type: {media_type}) for task_id '{task_id}' from path: {abs_file_path}")
267
+
268
+ return FileResponse(path=abs_file_path, media_type=media_type, filename=file_name_for_download)
269
+
270
+ def update_huggingface_dataset(username: str, score: float, code_link: str):
271
+ """
272
+ Loads the dataset, updates the score and code link if the score is higher,
273
+ and pushes back to the Hugging Face Hub.
274
+
275
+ Args:
276
+ username: The username of the participant.
277
+ score: The new score achieved by the participant.
278
+ code_link: The link to the code submission associated with this score.
279
+
280
+ Returns:
281
+ True if the dataset was updated and pushed, False otherwise.
282
+
283
+ Raises:
284
+ HTTPException: If there's an error interacting with the dataset.
285
+ """
286
+ try:
287
+ # Define the expected schema including the 'code' column
288
+ expected_columns = {
289
+ 'username': 'str',
290
+ 'score': 'float',
291
+ 'timestamp': 'str',
292
+ 'code': 'str' # Added the code column
293
+ }
294
+
295
+ # 1. Attempt to load the dataset
296
+ logger.info(f"Attempting to load dataset '{HF_DATASET_ID}'...")
297
+ ds_dict = None
298
+ df = None
299
+ try:
300
+
301
+ ds_dict = load_dataset(HF_DATASET_ID, trust_remote_code=True) # Added trust_remote_code=True if needed
302
+ logger.info("Dataset loaded successfully.")
303
+ if "train" in ds_dict:
304
+ df = ds_dict['train'].to_pandas()
305
+ else:
306
+ logger.warning(f"Dataset '{HF_DATASET_ID}' loaded but no 'train' split found. Creating structure.")
307
+ #df = pd.DataFrame({col: pd.Series(dtype=dtype) for col, dtype in expected_columns.items()})
308
+
309
+ except Exception as load_error:
310
+ logger.error(f"CRITICAL: Could not load dataset '{HF_DATASET_ID}'. Error: {load_error}", exc_info=True)
311
+ raise HTTPException(
312
+ status_code=500,
313
+ detail=f"Failed to load required dataset '{HF_DATASET_ID}': {load_error}"
314
+ )
315
+
316
+ for col, dtype in expected_columns.items():
317
+ if col not in df.columns:
318
+ logger.warning(f"Column '{col}' not found in loaded data. Adding it.")
319
+
320
+ df[col] = pd.Series(dtype=dtype)
321
+
322
+
323
+ df['score'] = pd.to_numeric(df['score'], errors='coerce').fillna(0.0)
324
+
325
+ df['username'] = df['username'].astype(str).fillna('')
326
+ df['timestamp'] = df['timestamp'].astype(str).fillna('')
327
+ df['code'] = df['code'].astype(str).fillna('')
328
+
329
+ # 2. Find existing score for the user
330
+ existing_entries = df[df['username'] == username]
331
+ current_timestamp = datetime.now(timezone.utc).isoformat()
332
+ needs_update = False
333
+
334
+ if not existing_entries.empty:
335
+ # User exists, find their highest score
336
+ max_existing_score = existing_entries['score'].max() # Already numeric
337
+ if score > max_existing_score:
338
+ logger.info(f"New score {score} is higher than existing max {max_existing_score} for {username}. Updating entry.")
339
+ df = df[df['username'] != username].copy()
340
+ new_entry = pd.DataFrame([{
341
+ 'username': username,
342
+ 'score': score,
343
+ 'timestamp': current_timestamp,
344
+ 'code': code_link # Add the code link here
345
+ }])
346
+ df = pd.concat([df, new_entry], ignore_index=True)
347
+ needs_update = True
348
+ else:
349
+ logger.info(f"New score {score} is not higher than existing max {max_existing_score} for {username}. No update needed.")
350
+ else:
351
+ # User does not exist, add them
352
+ logger.info(f"User {username} not found. Adding new entry with score {score}.")
353
+ new_entry = pd.DataFrame([{
354
+ 'username': username,
355
+ 'score': score,
356
+ 'timestamp': current_timestamp,
357
+ 'code': code_link # Add the code link here
358
+ }])
359
+ df = pd.concat([df, new_entry], ignore_index=True)
360
+ needs_update = True
361
+
362
+ # 3. Push updated data back to Hugging Face Hub if changes were made
363
+ if needs_update:
364
+ logger.info(f"Preparing to push updated dataset to '{HF_DATASET_ID}'...")
365
+
366
+ df = df[list(expected_columns.keys())]
367
+ for col, dtype in expected_columns.items():
368
+ if dtype == 'str':
369
+ df[col] = df[col].astype(str).fillna('')
370
+ elif dtype == 'float':
371
+ df[col] = pd.to_numeric(df[col], errors='coerce').fillna(0.0) # Ensure float conversion
372
+
373
+ logger.info(f"Final DataFrame columns and types:\n{df.dtypes}")
374
+ logger.info(f"Sample data before push:\n{df.head().to_string()}")
375
+
376
+ updated_ds = Dataset.from_pandas(df)
377
+ final_ds_dict = DatasetDict({'train': updated_ds})
378
+
379
+ logger.info(f"Dataset structure to push: {final_ds_dict}")
380
+
381
+ final_ds_dict.push_to_hub(HF_DATASET_ID)
382
+ logger.warning("Dataset push to hub is currently commented out in the code.")
383
+ return True
384
+ else:
385
+ logger.info("No changes needed, dataset not pushed.")
386
+ return False # No update was pushed
387
+
388
+ except Exception as e:
389
+ logger.error(f"Error interacting with Hugging Face dataset '{HF_DATASET_ID}': {e}", exc_info=True)
390
+
391
+ raise HTTPException(status_code=500, detail=f"Failed to update Hugging Face dataset: {e}")
392
+
393
+
394
+ @app.get("/questions",
395
+ # Return a list of dictionaries with arbitrary keys/values
396
+ response_model=List[Dict[str, Any]],
397
+ summary="Get All Filtered Questions (Full Data)",
398
+ description="Returns the complete list of questions with all associated data (excluding answer/annotation) filtered based on criteria.")
399
+ async def get_questions():
400
+ """
401
+ Provides the list of questions (with extended data) that agents should answer.
402
+ """
403
+ if not questions_for_api:
404
+ logger.error("GET /questions requested but no questions are loaded.")
405
+ raise HTTPException(status_code=404, detail="No questions available.")
406
+ # questions_for_api now contains the richer dictionaries
407
+ return questions_for_api
408
+
409
+ @app.get("/random-question",
410
+ # Return a single dictionary with arbitrary keys/values
411
+ response_model=Dict[str, Any],
412
+ summary="Get One Random Question (Full Data)",
413
+ description="Returns a single random question with all associated data (excluding answer/annotation) from the available filtered set.",
414
+ responses={
415
+ 200: {"description": "A random question with its full data."},
416
+ 404: {"model": ErrorResponse, "description": "No questions available to choose from."}
417
+ })
418
+ async def get_random_question():
419
+ """
420
+ Provides a single, randomly selected question with its extended data.
421
+ """
422
+ if not questions_for_api:
423
+ logger.warning("GET /random-question requested but no questions are loaded.")
424
+ raise HTTPException(status_code=404, detail="No questions available to choose from.")
425
+
426
+ # Select and return a random question dictionary
427
+ random_question = random.choice(questions_for_api)
428
+ logger.info(f"Returning random question with task_id: {random_question.get('task_id', 'N/A')}")
429
+ # random_question is already the richer dictionary
430
+ return random_question
431
+
432
+ # --- Submit Endpoint (remains the same, uses ground_truth_answers) ---
433
+ @app.post("/submit",
434
+ response_model=ScoreResponse,
435
+ summary="Submit Agent Answers",
436
+ description="Submit answers from an agent, calculate score, and update leaderboard on Hugging Face.",
437
+ responses={
438
+ 200: {"description": "Submission successful, score calculated."},
439
+ 400: {"model": ErrorResponse, "description": "Invalid input data."},
440
+ 404: {"model": ErrorResponse, "description": "Task ID not found in submission or ground truth."},
441
+ 500: {"model": ErrorResponse, "description": "Server error (e.g., failed to update dataset)."}
442
+ })
443
+ async def submit_answers(submission: Submission = Body(...)):
444
+ """
445
+ Receives agent submissions:
446
+ - Validates input.
447
+ - Checks presence of agent code (basic anti-cheat).
448
+ - Calculates score based on submitted answers vs ground truth.
449
+ - Updates the score on the Hugging Face dataset if it's a new high score for the user.
450
+ """
451
+ logger.info(f"Received submission from username: {submission.username}")
452
+
453
+ # Basic check for agent code presence
454
+ if not submission.agent_code or len(submission.agent_code.strip()) < 10:
455
+ logger.warning(f"Submission rejected for {submission.username}: Agent code missing or too short.")
456
+ raise HTTPException(status_code=400, detail="Agent code is required and must be sufficiently long.")
457
+
458
+ if not submission.answers:
459
+ logger.warning(f"Submission rejected for {submission.username}: No answers provided.")
460
+ raise HTTPException(status_code=400, detail="No answers provided in the submission.")
461
+
462
+
463
+ correct_count = 0
464
+ total_attempted_in_payload = len(submission.answers)
465
+ valid_attempted_count = 0
466
+ processed_ids = set()
467
+
468
+ for answer_item in submission.answers:
469
+ task_id = str(answer_item.task_id)
470
+ submitted = str(answer_item.submitted_answer)
471
+
472
+
473
+ if task_id in processed_ids:
474
+ logger.warning(f"Duplicate task_id '{task_id}' in submission from {submission.username}. Skipping.")
475
+ continue
476
+ processed_ids.add(task_id)
477
+
478
+
479
+
480
+ if task_id not in ground_truth_answers:
481
+ logger.warning(f"Task ID '{task_id}' submitted by {submission.username} not found in ground truth list. Skipping this answer.")
482
+ continue
483
+
484
+
485
+ valid_attempted_count += 1
486
+ ground_truth = ground_truth_answers[task_id]
487
+ # Compare answers (case-insensitive, strip whitespace)
488
+ if submitted.strip().lower() == ground_truth.strip().lower():
489
+ correct_count += 1
490
+ logger.debug(f"Correct answer for {task_id} from {submission.username}")
491
+ else:
492
+ logger.debug(f"Incorrect answer for {task_id} from {submission.username}. Submitted: '{submitted}', Expected: '{ground_truth}'")
493
+
494
+ if valid_attempted_count == 0:
495
+ score = 0.0
496
+ message = f"Submission received, but no valid/matching task IDs were found in the {total_attempted_in_payload} answers provided."
497
+ logger.warning(f"No valid answers processed for {submission.username} out of {total_attempted_in_payload} submitted.")
498
+ elif not ground_truth_answers: # Prevent division by zero if no questions loaded
499
+ score = 0.0
500
+ message = "Score cannot be calculated because no ground truth answers are loaded."
501
+ logger.error(f"Cannot calculate score for {submission.username}: ground_truth_answers is empty.")
502
+ else:
503
+ # Score is based on correct answers divided by the TOTAL number of questions in the filtered set
504
+ score = round((correct_count / len(ground_truth_answers)) * 100, 2)
505
+ message = f"Score calculated successfully: {correct_count}/{len(ground_truth_answers)} total questions answered correctly ({valid_attempted_count} valid tasks attempted)."
506
+ if valid_attempted_count < total_attempted_in_payload:
507
+ message += f" ({total_attempted_in_payload - valid_attempted_count} submitted answers had invalid or duplicate task IDs)."
508
+ logger.info(f"Score for {submission.username}: {score}% ({correct_count}/{len(ground_truth_answers)} correct, based on {valid_attempted_count} valid attempts)")
509
+
510
+
511
+ # Update Hugging Face dataset
512
+ try:
513
+ updated = update_huggingface_dataset(submission.username, score, submission.agent_code)
514
+ if updated:
515
+ message += " High score updated on leaderboard."
516
+ logger.info(f"Leaderboard updated for {submission.username}.")
517
+ else:
518
+ message += " Score did not improve previous record, leaderboard not updated."
519
+ logger.info(f"Leaderboard not updated for {submission.username} as score was not higher.")
520
+
521
+ except HTTPException as http_exc:
522
+ # Propagate HTTPException from the helper function (e.g., 500 error)
523
+ raise http_exc
524
+ except Exception as e:
525
+ # Catch any other unexpected errors during HF update
526
+ logger.error(f"Unexpected error during dataset update for {submission.username}: {e}", exc_info=True)
527
+ raise HTTPException(status_code=500, detail="An unexpected error occurred while updating the leaderboard.")
528
+
529
+
530
+ return ScoreResponse(
531
+ username=submission.username,
532
+ score=score,
533
+ correct_count=correct_count,
534
+ # Return the count of *valid* attempts for clarity
535
+ total_attempted=valid_attempted_count,
536
+ message=message,
537
+ timestamp=datetime.now(timezone.utc).isoformat()
538
+ )
539
+
540
+ # --- Run the application ---
541
+ if __name__ == "__main__":
542
+ logger.info("Starting FastAPI server for local development...")
543
+ try:
544
+ load_questions() # Load questions before starting server
545
+ if not questions_for_api:
546
+ logger.error("EXITING: Cannot start server without loaded questions.")
547
+ # Optional: exit if questions are essential
548
+ # import sys
549
+ # sys.exit(1)
550
+ else:
551
+ local_port = int(os.getenv("PORT", "8000"))
552
+ logger.info(f"Running Uvicorn locally on http://127.0.0.1:{local_port}")
553
+ uvicorn.run(app, host="127.0.0.1", port=local_port, log_level="info")
554
+ except Exception as e:
555
+ logger.error(f"Failed to start server: {e}", exc_info=True)