File size: 27,891 Bytes
10e9b7d
b2ae1ba
0c19db9
b2ae1ba
 
 
 
10e9b7d
e86c92c
3c4371f
b2ae1ba
 
 
0c19db9
b2ae1ba
 
 
 
 
0c19db9
b2ae1ba
10e9b7d
3db6293
0c19db9
 
e80aab9
b2ae1ba
0c19db9
 
 
b2ae1ba
0c19db9
b2ae1ba
0c19db9
 
 
 
 
 
b2ae1ba
 
 
 
0c19db9
b2ae1ba
 
0c19db9
 
 
 
 
b2ae1ba
 
 
 
 
 
 
0c19db9
b2ae1ba
 
 
 
 
0c19db9
 
b2ae1ba
0c19db9
 
b2ae1ba
0c19db9
b2ae1ba
 
0c19db9
 
 
b2ae1ba
 
0c19db9
b2ae1ba
 
 
 
 
 
0c19db9
b2ae1ba
 
 
 
0c19db9
 
 
 
b2ae1ba
 
 
 
 
 
 
 
 
0c19db9
b2ae1ba
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0c19db9
b2ae1ba
 
 
 
 
0c19db9
b2ae1ba
0c19db9
b2ae1ba
 
0c19db9
 
 
 
 
 
 
 
b2ae1ba
 
0c19db9
b2ae1ba
0c19db9
b2ae1ba
 
 
 
 
0c19db9
b2ae1ba
 
 
 
 
 
 
 
 
0c19db9
 
 
b2ae1ba
0c19db9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b2ae1ba
0c19db9
b2ae1ba
 
0c19db9
 
 
 
 
 
 
 
 
 
 
 
b2ae1ba
 
 
0c19db9
c1edb78
0c19db9
 
b2ae1ba
e907462
c1edb78
 
e907462
0c19db9
 
 
 
 
 
e907462
 
 
 
 
0c19db9
c1edb78
 
b2ae1ba
0c19db9
e907462
c1edb78
 
 
0c19db9
c1edb78
0c19db9
e907462
 
c1edb78
0c19db9
 
 
 
b2ae1ba
 
e907462
c1edb78
 
e907462
c1edb78
 
b2ae1ba
0c19db9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b2ae1ba
 
 
0c19db9
b2ae1ba
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0c19db9
b2ae1ba
 
 
 
0c19db9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b2ae1ba
0c19db9
 
 
 
 
 
b2ae1ba
 
 
 
 
 
 
 
 
0c19db9
 
 
b2ae1ba
 
0c19db9
 
 
 
 
 
b2ae1ba
0c19db9
b2ae1ba
0c19db9
b2ae1ba
 
0c19db9
 
b2ae1ba
 
 
0c19db9
b2ae1ba
0c19db9
b2ae1ba
 
 
 
0c19db9
 
b2ae1ba
 
0c19db9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b2ae1ba
 
 
3c4371f
 
0c19db9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b2ae1ba
0c19db9
 
 
 
 
 
b2ae1ba
0c19db9
 
 
 
 
 
 
b2ae1ba
e80aab9
0c19db9
 
 
20cdea2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0c19db9
31243f4
0c19db9
b2ae1ba
0c19db9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b2ae1ba
eccf8e4
0c19db9
 
 
 
b2ae1ba
0c19db9
 
 
 
 
 
 
 
 
b2ae1ba
 
0c19db9
 
 
 
 
 
b2ae1ba
0c19db9
 
31243f4
0c19db9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b2ae1ba
 
c66e877
c91d08b
 
 
 
 
 
 
 
 
 
 
 
 
c66e877
c91d08b
 
 
 
 
 
 
 
 
b2ae1ba
0c19db9
 
 
 
 
b2ae1ba
0c19db9
 
b2ae1ba
0c19db9
 
 
 
b2ae1ba
 
0c19db9
 
 
 
 
 
b2ae1ba
 
0c19db9
 
 
 
 
b2ae1ba
0c19db9
 
 
 
 
c66e877
b2ae1ba
 
 
 
e80aab9
b2ae1ba
0c19db9
 
 
b2ae1ba
e80aab9
b2ae1ba
 
 
 
 
 
c66e877
 
b2ae1ba
 
c66e877
0c19db9
b2ae1ba
 
c91d08b
0c19db9
 
 
b2ae1ba
0c19db9
b2ae1ba
 
e514fd7
0c19db9
 
 
 
 
 
b2ae1ba
e80aab9
 
7e4a06b
e80aab9
0c19db9
 
 
e80aab9
0c19db9
 
 
b2ae1ba
 
0c19db9
 
 
 
 
 
 
 
 
2556693
20cdea2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b2ae1ba
0c19db9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b2ae1ba
 
e80aab9
0c19db9
 
 
e80aab9
 
b2ae1ba
e80aab9
0c19db9
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
import os
import re
import json
import tempfile
from pathlib import Path
from urllib.parse import unquote, urlparse, parse_qs

import gradio as gr
print("GRADIO VERSION:", gr.__version__)
import pandas as pd
import requests
from pypdf import PdfReader
from youtube_transcript_api import YouTubeTranscriptApi
from huggingface_hub import InferenceClient, hf_hub_download
from smolagents import (
    CodeAgent,
    DuckDuckGoSearchTool,
    InferenceClientModel,
    VisitWebpageTool,
    PythonInterpreterTool,
)

DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
MODEL_ID = os.getenv("MODEL_ID", "Qwen/Qwen2.5-Coder-32B-Instruct")
GAIA_DATASET = "gaia-benchmark/GAIA"


# ----------------------------
# Answer normalization
# ----------------------------
def clean_answer(value: str) -> str:
    value = str(value or "").strip()

    for prefix in (
        "final answer:",
        "final answer",
        "answer:",
        "answer",
    ):
        if value.lower().startswith(prefix):
            value = value[len(prefix):].lstrip(": \n\t").strip()
            break

    if len(value) >= 2 and value[0] == value[-1] and value[0] in {'"', "'"}:
        value = value[1:-1].strip()

    # Remove common wrapper without damaging decimals.
    value = re.sub(r"^\s*FINAL ANSWER\s*:\s*", "", value, flags=re.I)
    if value.endswith(".") and not re.search(r"\d\.\d$", value):
        value = value[:-1].rstrip()

    bad_markers = (
        "Thought:",
        "Calling tools:",
        "<code>",
        "</code>",
        "python_interpreter",
    )
    if any(marker.lower() in value.lower() for marker in bad_markers):
        return ""

    return value


def normalize_requested_format(question: str, answer: str) -> str:
    value = clean_answer(answer)

    if "without abbreviations" in question.lower():
        value = re.sub(r"\bSt\.\s+", "Saint ", value, flags=re.I)

    return value


# ----------------------------
# Deterministic solvers
# ----------------------------
def looks_reversed(question: str) -> bool:
    reversed_text = question[::-1].lower()
    markers = (" answer", " write ", " sentence", " word ", " understand ")
    return (
        sum(m in reversed_text for m in markers)
        >= sum(m in question.lower() for m in markers) + 2
    )


def solve_reversed_text(question: str):
    if not looks_reversed(question):
        return None
    decoded = question[::-1].lower()
    pairs = {
        "left": "right", "right": "left",
        "up": "down", "down": "up",
        "yes": "no", "no": "yes",
        "true": "false", "false": "true",
    }
    if "opposite" not in decoded:
        return None
    for source, target in pairs.items():
        if re.search(rf"\b{re.escape(source)}\b", decoded):
            return target
    return None


def solve_commutativity_table(question: str):
    if "not commutative" not in question.lower() or "|*|" not in question:
        return None

    lines = [line.strip() for line in question.splitlines() if line.strip()]
    table_lines = [line for line in lines if line.startswith("|")]
    if len(table_lines) < 3:
        return None

    header = [x.strip() for x in table_lines[0].strip("|").split("|")][1:]
    row_lines = table_lines[2:]

    matrix = {}
    for row in row_lines:
        cells = [x.strip() for x in row.strip("|").split("|")]
        if len(cells) != len(header) + 1:
            continue
        for col_name, value in zip(header, cells[1:]):
            matrix[(cells[0], col_name)] = value

    involved = set()
    for a in header:
        for b in header:
            if matrix.get((a, b)) != matrix.get((b, a)):
                involved.update((a, b))

    return ", ".join(sorted(involved)) if involved else None


BOTANICAL_VEGETABLES = {
    "artichoke", "asparagus", "beet", "beets", "bok choy", "broccoli",
    "brussels sprouts", "cabbage", "carrot", "carrots", "cauliflower",
    "celery", "chard", "collard greens", "fresh basil", "garlic", "ginger",
    "kale", "leek", "leeks", "lettuce", "onion", "onions", "parsnip",
    "parsnips", "potato", "potatoes", "radish", "radishes", "spinach",
    "sweet potato", "sweet potatoes", "turnip", "turnips",
}


def solve_botanical_vegetables(question: str):
    lowered = question.lower()
    if not all(x in lowered for x in ("botanical fruits", "vegetables", "alphabet", "comma")):
        return None

    match = re.search(
        r"(?:list i have so far|list.*?so far)\s*:\s*(.+?)(?:\n\s*\n|i need to)",
        question,
        flags=re.I | re.S,
    )
    if not match:
        return None

    items = [
        item.strip()
        for item in match.group(1).replace("\n", " ").split(",")
        if item.strip()
    ]
    selected = [x for x in items if x.lower() in BOTANICAL_VEGETABLES]
    return ", ".join(sorted(selected, key=str.lower)) if selected else None


def deterministic_solve(question: str):
    for name, solver in (
        ("Reversed text", solve_reversed_text),
        ("Commutativity table", solve_commutativity_table),
        ("Botanical vegetables", solve_botanical_vegetables),
    ):
        answer = solver(question)
        if answer is not None:
            return name, normalize_requested_format(question, answer)
    return "LLM required", None


# ----------------------------
# Attachment handling
# ----------------------------
def filename_from_response(response, task_id):
    header = response.headers.get("content-disposition", "")
    match = re.search(r"filename\*=UTF-8''([^;]+)", header, flags=re.I)
    if match:
        return Path(unquote(match.group(1))).name
    match = re.search(r'filename="?([^";]+)"?', header)
    if match:
        return Path(match.group(1).strip()).name

    content_type = response.headers.get("content-type", "").split(";")[0].lower()
    ext_map = {
        "application/pdf": ".pdf",
        "text/csv": ".csv",
        "application/json": ".json",
        "text/plain": ".txt",
        "audio/mpeg": ".mp3",
        "audio/wav": ".wav",
        "image/png": ".png",
        "image/jpeg": ".jpg",
        "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet": ".xlsx",
        "application/vnd.ms-excel": ".xls",
    }
    return f"{task_id}{ext_map.get(content_type, '.bin')}"


def download_scoring_file(task_id: str):
    url = f"{DEFAULT_API_URL}/files/{task_id}"
    try:
        response = requests.get(url, timeout=30)
        if response.status_code != 200 or not response.content:
            return None
        filename = filename_from_response(response, task_id)
        temp_dir = Path(tempfile.mkdtemp(prefix=f"gaia_{task_id[:8]}_"))
        path = temp_dir / filename
        path.write_bytes(response.content)
        return str(path)
    except Exception:
        return None


def dataset_fallback_file(task_id: str, hf_token: str):
    """Use the GAIA validation dataset to locate an attachment if one exists."""
    try:
        from datasets import load_dataset

        if not hf_token:
            print("HF_TOKEN is empty; skipping GAIA dataset fallback.")
            return None

        ds = load_dataset(
            GAIA_DATASET,
            "2023_level1",
            split="validation",
            token=hf_token,
        )

        matches = ds.filter(
            lambda row: row["task_id"] == task_id
        )

        if len(matches) == 0:
            print(f"Task {task_id} not found in GAIA validation dataset.")
            return None

        file_path = matches[0].get("file_path")

        # IMPORTANT:
        # Many GAIA questions have no attachment.
        # That is normal and must not be treated as an error.
        if not file_path:
            return None

        print(f"GAIA attachment file_path: {file_path}")

        return hf_hub_download(
            repo_id=GAIA_DATASET,
            repo_type="dataset",
            filename=file_path,
            token=hf_token,
        )

    except Exception as exc:
        print(
            f"GAIA dataset fallback failed for {task_id}: "
            f"{type(exc).__name__}: {exc}"
        )
        return None

def download_task_file(task_id: str, hf_token: str):
    return download_scoring_file(task_id) or dataset_fallback_file(task_id, hf_token)


def extract_attachment_content(file_path):
    if not file_path:
        return ""

    path = Path(file_path)
    suffix = path.suffix.lower()

    try:
        if suffix == ".csv":
            return f"CSV DATA:\n{pd.read_csv(path).to_csv(index=False)}"

        if suffix in {".xlsx", ".xls"}:
            xls = pd.ExcelFile(path)
            sections = []
            for sheet in xls.sheet_names:
                df = pd.read_excel(path, sheet_name=sheet, header=None)
                sections.append(f"SHEET {sheet}:\n{df.to_csv(index=False, header=False)}")
            return "\n\n".join(sections)

        if suffix in {".py", ".txt", ".md", ".json", ".jsonld"}:
            return path.read_text(encoding="utf-8", errors="replace")

        if suffix == ".pdf":
            reader = PdfReader(path)
            return "\n\n".join(page.extract_text() or "" for page in reader.pages)

        return ""
    except Exception as exc:
        return f"Attachment extraction failed: {type(exc).__name__}: {exc}"


# ----------------------------
# YouTube
# ----------------------------
def youtube_transcript(question: str):
    urls = re.findall(
        r"https?://(?:www\.)?(?:youtube\.com/[^\s]+|youtu\.be/[^\s]+)",
        question,
        flags=re.I,
    )
    if not urls:
        return ""

    api = YouTubeTranscriptApi()
    sections = []

    for raw_url in urls:
        url = raw_url.rstrip(".,);]}>\"'")
        parsed = urlparse(url)
        video_id = None

        if parsed.netloc in {"youtu.be", "www.youtu.be"}:
            video_id = parsed.path.strip("/").split("/")[0] or None
        elif "youtube.com" in parsed.netloc:
            if parsed.path == "/watch":
                video_id = parse_qs(parsed.query).get("v", [None])[0]
            else:
                parts = [p for p in parsed.path.split("/") if p]
                if len(parts) >= 2 and parts[0] in {"shorts", "embed", "live"}:
                    video_id = parts[1]

        if not video_id:
            continue

        try:
            transcript = api.fetch(video_id)
            text = " ".join(snippet.text for snippet in transcript.snippets)
            if text.strip():
                sections.append(text)
        except Exception as exc:
            print(f"Transcript unavailable: {exc}")

    return "\n\n".join(sections)


# ----------------------------
# Optional multimodal helpers
# ----------------------------
def multimodal_attachment_answer(file_path, question, hf_token):
    """Try HF Inference Providers for image/audio attachments."""
    if not file_path or not hf_token:
        return ""

    suffix = Path(file_path).suffix.lower()
    client = InferenceClient(token=hf_token)

    try:
        if suffix in {".png", ".jpg", ".jpeg", ".webp"}:
            # VLM via chat completion. The exact provider/model can be
            # overridden with VISION_MODEL.
            model = os.getenv("VISION_MODEL", "Qwen/Qwen2.5-VL-7B-Instruct")
            import base64
            mime = {
                ".png": "image/png",
                ".jpg": "image/jpeg",
                ".jpeg": "image/jpeg",
                ".webp": "image/webp",
            }[suffix]
            data = base64.b64encode(Path(file_path).read_bytes()).decode()
            response = client.chat.completions.create(
                model=model,
                messages=[{
                    "role": "user",
                    "content": [
                        {"type": "text", "text": (
                            "Answer the question using the attached image. "
                            "Return only the answer, with no explanation.\n\n"
                            f"Question: {question}"
                        )},
                        {"type": "image_url", "image_url": {
                            "url": f"data:{mime};base64,{data}"
                        }},
                    ],
                }],
                max_tokens=300,
            )
            return clean_answer(response.choices[0].message.content)

        if suffix in {".mp3", ".wav", ".m4a", ".flac", ".ogg"}:
            model = os.getenv("AUDIO_MODEL", "openai/whisper-large-v3")
            transcript = client.automatic_speech_recognition(
                file_path,
                model=model,
            )
            text = getattr(transcript, "text", str(transcript))
            return text.strip()

    except Exception as exc:
        print(f"Multimodal inference unavailable: {exc}")

    return ""


# ----------------------------
# Agent
# ----------------------------
class ResearchAgent:
    def __init__(self):
        hf_token = os.getenv("HF_TOKEN")
        if not hf_token:
            raise RuntimeError("HF_TOKEN secret is not configured.")

        model = InferenceClientModel(
            model_id=MODEL_ID,
            token=hf_token,
            timeout=180,
            temperature=0.1,
            max_tokens=1200,
        )

        tools = [
            DuckDuckGoSearchTool(max_results=8),
            VisitWebpageTool(),
            PythonInterpreterTool(),
        ]

        self.agent = CodeAgent(
            tools=tools,
            model=model,
            max_steps=10,
            verbosity_level=0,
            additional_authorized_imports=[
                "math", "statistics", "datetime", "re",
                "json", "pandas", "numpy",
            ],
        )

    def answer(self, question, attachment_content="", extra_context="", attachment_path=None):
        prompt = f"""
You are solving ONE GAIA Level-1 benchmark question.

QUESTION:
{question}

ATTACHMENT TEXT:
{attachment_content or "No text attachment content is available."}

EXTRA CONTEXT:
{extra_context or "No YouTube transcript is available."}

Rules:
1. Solve the question completely. Do not guess.
2. Use web search when current/factual/research information is needed.
3. Use Python for arithmetic, data processing, tables, dates, and calculations.
4. If attachment text is provided, use it as evidence.
5. If an attachment is an image/audio file, use the multimodal result supplied separately when available.
6. Cross-check important facts before answering.
7. Follow every formatting instruction in the question exactly.
8. The evaluator uses EXACT MATCH.
9. Return ONLY the final answer. No reasoning, no markdown, no labels, no "FINAL ANSWER".
10. For numeric answers, do not add units or commas unless the question explicitly requests them.
11. For lists, preserve the requested ordering and separator.

Work carefully, then output only the answer.
"""
        result = self.agent.run(prompt)
        return clean_answer(str(result))


# ----------------------------
# Question loading
# ----------------------------
def get_questions():
    response = requests.get(f"{DEFAULT_API_URL}/questions", timeout=30)
    response.raise_for_status()
    return response.json()


def solve_one(item, agent=None):
    task_id = item.get("task_id")
    question = item.get("question", "")

    solver, deterministic_answer = deterministic_solve(question)
    if deterministic_answer is not None:
        return {
            "task_id": task_id,
            "question": question,
            "solver": solver,
            "answer": deterministic_answer,
            "attachment": "not needed",
        }

    hf_token = os.getenv("HF_TOKEN", "")
    file_path = download_task_file(task_id, hf_token)

    attachment = extract_attachment_content(file_path)
    transcript = youtube_transcript(question)

    # Give images/audio a dedicated inference attempt before the text agent.
    multimodal = multimodal_attachment_answer(file_path, question, hf_token)
    if multimodal:
        # Audio output is a transcript, not necessarily the answer, so let the
        # main agent consume it as context rather than submitting it directly.
        if Path(file_path).suffix.lower() in {".mp3", ".wav", ".m4a", ".flac", ".ogg"}:
            attachment = f"AUDIO TRANSCRIPT:\n{multimodal}\n\n{attachment}"
        else:
            attachment = f"IMAGE MODEL RESULT:\n{multimodal}\n\n{attachment}"

    if agent is None:
        agent = ResearchAgent()

    answer = agent.answer(
        question=question,
        attachment_content=attachment,
        extra_context=transcript,
        attachment_path=file_path,
    )

    return {
        "task_id": task_id,
        "question": question,
        "solver": "ResearchAgent",
        "answer": normalize_requested_format(question, answer),
        "attachment": Path(file_path).name if file_path else "none",
    }


# ----------------------------
# UI actions
# ----------------------------
def diagnose_attachment(task_id):
    """Diagnose GAIA attachment retrieval without LLM calls or submission."""

    task_id = (task_id or "").strip()

    if not task_id:
        return "Please enter a Task ID.", pd.DataFrame()

    rows = []

    # Get question metadata
    try:
        questions = get_questions()
        item = next(
            (q for q in questions if q.get("task_id") == task_id),
            None,
        )

        if item is None:
            return f"Task ID not found: {task_id}", pd.DataFrame()

        rows.append({
            "Check": "Question metadata",
            "Status": "FOUND",
            "Details": f"Question: {item.get('question', '')[:500]}",
        })

    except Exception as exc:
        return (
            f"Could not fetch question metadata: "
            f"{type(exc).__name__}: {exc}",
            pd.DataFrame(),
        )

    hf_token = os.getenv("HF_TOKEN", "")

    # Try scoring API
    try:
        response = requests.get(
            f"{DEFAULT_API_URL}/files/{task_id}",
            timeout=30,
        )

        rows.append({
            "Check": "Scoring API",
            "Status": str(response.status_code),
            "Details": (
                f"bytes={len(response.content)}, "
                f"content-type={response.headers.get('content-type', '')}, "
                f"content-disposition="
                f"{response.headers.get('content-disposition', '')}"
            ),
        })

    except Exception as exc:
        rows.append({
            "Check": "Scoring API",
            "Status": "ERROR",
            "Details": f"{type(exc).__name__}: {exc}",
        })

    # Try the same download function used by the agent
    try:
        file_path = download_task_file(task_id, hf_token)

        if file_path:
            path = Path(file_path)

            rows.append({
                "Check": "Attachment download",
                "Status": "SUCCESS",
                "Details": (
                    f"filename={path.name}, "
                    f"size={path.stat().st_size} bytes"
                ),
            })

            # Extract content
            extracted = extract_attachment_content(file_path)

            rows.append({
                "Check": "Attachment extraction",
                "Status": "SUCCESS" if extracted else "EMPTY",
                "Details": (
                    extracted[:5000]
                    if extracted
                    else "No text was extracted."
                ),
            })

        else:
            rows.append({
                "Check": "Attachment download",
                "Status": "FAILED",
                "Details": "download_task_file() returned None.",
            })

    except Exception as exc:
        rows.append({
            "Check": "Attachment processing",
            "Status": "ERROR",
            "Details": f"{type(exc).__name__}: {exc}",
        })

    status = (
        f"Attachment diagnostic complete for {task_id}. "
        "No LLM call and no submission."
    )

    return status, pd.DataFrame(rows)
def test_deterministic():
    try:
        questions = get_questions()
    except Exception as exc:
        return f"Could not fetch questions: {exc}", pd.DataFrame()

    rows = []
    for item in questions:
        solver, answer = deterministic_solve(item.get("question", ""))
        rows.append({
            "Task ID": item.get("task_id"),
            "Solver": solver,
            "Answer": answer or "",
            "Question": item.get("question", ""),
        })

    solved = sum(bool(row["Answer"]) for row in rows)
    return (
        f"Deterministic validation complete: {solved}/{len(rows)} "
        "questions matched a local solver. No LLM calls and no submission.",
        pd.DataFrame(rows),
    )


def test_single(task_id):
    task_id = (task_id or "").strip()
    if not task_id:
        return "Enter a Task ID.", pd.DataFrame()

    try:
        questions = get_questions()
        item = next((q for q in questions if q.get("task_id") == task_id), None)
        if item is None:
            return "Task ID not found.", pd.DataFrame()

        result = solve_one(item)
        return (
            f"Test complete. Solver: {result['solver']}\n"
            f"Answer: {result['answer']}\n"
            f"Attachment: {result['attachment']}",
            pd.DataFrame([result]),
        )
    except Exception as exc:
        return f"Single-question test failed: {type(exc).__name__}: {exc}", pd.DataFrame()


def run_all_no_submit():
    try:
        questions = get_questions()
        agent = ResearchAgent()
    except Exception as exc:
        return f"Agent initialization failed: {type(exc).__name__}: {exc}", pd.DataFrame()

    rows = []
    for index, item in enumerate(questions, start=1):
        try:
            result = solve_one(item, agent=agent)
            rows.append(result)
        except Exception as exc:
            rows.append({
                "task_id": item.get("task_id"),
                "question": item.get("question", ""),
                "solver": "ERROR",
                "answer": "",
                "attachment": f"{type(exc).__name__}: {exc}",
            })

    valid = sum(bool(x["answer"]) for x in rows)
    return (
        f"Dry run complete: {valid}/{len(rows)} produced an answer. "
        "NOT submitted to the leaderboard.",
        pd.DataFrame(rows),
    )


def submit_all(request: gr.Request):
    hf_token = os.getenv("HF_TOKEN", "")

    if not hf_token:
        return "HF_TOKEN is missing from Space secrets.", None

    try:
        user_response = requests.get(
            "https://huggingface.co/api/whoami-v2",
            headers={"Authorization": f"Bearer {hf_token}"},
            timeout=30,
        )
        user_response.raise_for_status()
        profile = user_response.json().get("name")

        if not profile:
            return "Could not determine Hugging Face username from HF_TOKEN.", None

    except Exception as exc:
        return (
            f"Could not verify Hugging Face identity: "
            f"{type(exc).__name__}: {exc}",
            None,
        )

    try:
        questions = get_questions()
        agent = ResearchAgent()
    except Exception as exc:
        return f"Agent initialization failed: {type(exc).__name__}: {exc}", None

    answers = []
    rows = []

    for item in questions:
        try:
            result = solve_one(item, agent=agent)
            answer = result["answer"]
        except Exception as exc:
            answer = ""
            result = {
                "task_id": item.get("task_id"),
                "question": item.get("question", ""),
                "solver": "ERROR",
                "answer": "",
                "attachment": f"{type(exc).__name__}: {exc}",
            }

        answers.append({
            "task_id": item.get("task_id"),
            "submitted_answer": answer,
        })
        rows.append(result)

    space_id = os.getenv("SPACE_ID")
    if not space_id:
        return "SPACE_ID is missing from the Space environment.", pd.DataFrame(rows)

    payload = {
        "username": str(profile),
        "agent_code": f"https://huggingface.co/spaces/{space_id}/tree/main",
        "answers": answers,
    }

    try:
        response = requests.post(
            f"{DEFAULT_API_URL}/submit",
            json=payload,
            timeout=120,
        )
        response.raise_for_status()
        data = response.json()

        status = (
            "Submission Successful!\n"
            f"User: {data.get('username')}\n"
            f"Overall Score: {data.get('score', 'N/A')}% "
            f"({data.get('correct_count', '?')}/"
            f"{data.get('total_attempted', '?')} correct)\n"
            f"Message: {data.get('message', '')}"
        )

        return status, pd.DataFrame(rows)

    except Exception as exc:
        return ( f"Submission failed: {type(exc).__name__}: {exc}", pd.DataFrame(rows))
# ----------------------------
# Gradio
# ----------------------------
with gr.Blocks() as demo:
    gr.Markdown("# GAIA Agent — Test Before Submit")

    gr.Markdown(
        """
This runner separates **validation**, **dry runs**, and **leaderboard submission**.

1. Test deterministic solvers — free, no LLM calls.
2. Test one question by Task ID.
3. Run all 20 without submitting.
4. Only then submit to the GAIA scorer.
"""
    )

    gr.LoginButton()

    with gr.Row():
        deterministic_button = gr.Button("1. Test Deterministic Solvers")
        dry_run_button = gr.Button("3. Run All — No Submit")

    deterministic_status = gr.Textbox(
        label="Deterministic Validation",
        lines=3,
        interactive=False,
    )
    deterministic_table = gr.DataFrame(
        label="Deterministic Results",
        wrap=True,
    )

    deterministic_button.click(
        fn=test_deterministic,
        outputs=[deterministic_status, deterministic_table],
    )
    gr.Markdown("### 2. Diagnose Attachment")

    diagnostic_task_id = gr.Textbox(
        label="Task ID",
        placeholder="Paste a Task ID with an attachment",
    )

    diagnostic_button = gr.Button("Diagnose Attachment")

    diagnostic_status = gr.Textbox(
        label="Attachment Diagnostic",
        lines=8,
        interactive=False,
    )

    diagnostic_table = gr.DataFrame(
        label="Attachment Details",
        wrap=True,
    )

    diagnostic_button.click(
        fn=diagnose_attachment,
        inputs=[diagnostic_task_id],
        outputs=[diagnostic_status, diagnostic_table],
    )

    gr.Markdown("### 2. Test One Question")
    task_id_input = gr.Textbox(
        label="Task ID",
        placeholder="Paste one Task ID from the deterministic table",
    )
    single_button = gr.Button("Run One Question")
    single_status = gr.Textbox(
        label="Single Question Result",
        lines=5,
        interactive=False,
    )
    single_table = gr.DataFrame(
        label="Single Question Details",
        wrap=True,
    )

    single_button.click(
        fn=test_single,
        inputs=[task_id_input],
        outputs=[single_status, single_table],
    )

    dry_status = gr.Textbox(
        label="Dry Run Status",
        lines=3,
        interactive=False,
    )
    dry_table = gr.DataFrame(
        label="All Answers — NOT Submitted",
        wrap=True,
    )

    dry_run_button.click(
        fn=run_all_no_submit,
        outputs=[dry_status, dry_table],
    )

    gr.Markdown("### 4. Leaderboard Submission")
    submit_button = gr.Button(
        "4. Submit All Answers",
        variant="primary",
    )
    submit_status = gr.Textbox(
        label="Submission Result",
        lines=6,
        interactive=False,
    )
    submit_table = gr.DataFrame(
        label="Submitted Answers",
        wrap=True,
    )

    submit_button.click(
        fn=submit_all,
        outputs=[submit_status, submit_table],
    )


if __name__ == "__main__":
    demo.launch()