File size: 37,700 Bytes
3322b77
a51c831
ddc5859
0edd404
fc19570
a51c831
 
3322b77
b84230c
a51c831
 
 
fc19570
 
 
 
 
 
 
 
 
 
ddc5859
 
3322b77
a51c831
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8dc7996
 
a51c831
8dc7996
a51c831
 
 
8dc7996
 
a51c831
8dc7996
 
a51c831
 
fc19570
 
 
 
 
3322b77
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fc19570
 
 
3322b77
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bb469a5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3322b77
 
 
 
 
 
 
 
 
 
 
 
 
 
bb469a5
 
3322b77
bb469a5
 
 
 
 
3322b77
fc19570
 
 
 
 
 
 
 
 
 
ddc5859
3322b77
fc19570
ddc5859
fc19570
 
3322b77
 
 
fc19570
3322b77
 
 
 
 
 
 
ddc5859
3322b77
ddc5859
3322b77
 
ddc5859
3322b77
 
 
 
 
 
 
 
 
 
bb469a5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3322b77
 
 
 
 
 
 
bb469a5
ddc5859
 
fc19570
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a51c831
 
 
 
0edd404
 
a51c831
8dc7996
2a35e5e
fc19570
 
bb469a5
 
fc19570
3322b77
2a35e5e
a51c831
 
0edd404
 
a51c831
8dc7996
2a35e5e
fc19570
 
bb469a5
 
fc19570
3322b77
2a35e5e
a51c831
 
 
 
 
 
 
 
 
 
 
 
fc19570
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bb469a5
 
 
 
fc19570
bb469a5
 
 
 
 
 
 
 
 
 
 
 
 
3322b77
fc19570
bb469a5
 
 
fc19570
 
a51c831
fc19570
a51c831
fc19570
 
a51c831
fc19570
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8dc7996
a51c831
fc19570
 
 
 
 
 
 
 
bb469a5
 
 
 
 
 
 
 
 
3322b77
 
bb469a5
fc19570
 
 
 
 
 
bb469a5
 
fc19570
3322b77
bb469a5
fc19570
a51c831
 
8dc7996
fc19570
0edd404
8dc7996
fc19570
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bb469a5
 
 
 
 
 
 
 
 
 
 
3322b77
 
 
bb469a5
 
 
 
 
 
 
 
 
fc19570
 
 
 
 
 
 
 
 
 
 
 
bb469a5
 
 
fc19570
 
 
 
 
bb469a5
 
 
 
 
fc19570
bb469a5
 
 
 
 
 
 
 
 
 
 
 
 
3322b77
fc19570
bb469a5
 
 
 
 
fc19570
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bb469a5
 
 
 
 
 
 
 
3322b77
 
8dc7996
0edd404
8dc7996
0edd404
fc19570
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bb469a5
 
 
 
 
 
 
3322b77
 
 
 
bb469a5
 
3322b77
 
 
fc19570
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bb469a5
 
 
 
 
 
 
 
 
 
 
3322b77
 
 
bb469a5
 
 
 
 
 
 
 
fc19570
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bb469a5
 
 
 
 
fc19570
bb469a5
 
 
 
 
 
 
 
 
 
 
 
 
3322b77
fc19570
bb469a5
 
 
 
 
fc19570
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bb469a5
 
 
 
 
 
 
 
3322b77
 
fc19570
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bb469a5
 
 
 
 
 
 
3322b77
 
 
bb469a5
 
3322b77
 
 
fc19570
 
 
 
 
 
 
 
bb469a5
fc19570
 
 
 
 
 
 
 
 
bb469a5
 
 
 
 
 
 
 
 
 
 
3322b77
 
 
bb469a5
 
 
 
 
 
 
fc19570
 
 
 
 
 
 
bb469a5
 
 
 
 
 
 
 
 
 
 
 
3322b77
 
 
 
 
 
bb469a5
fc19570
bb469a5
3322b77
fc19570
bb469a5
 
 
 
 
fc19570
 
 
 
 
 
 
 
 
bb469a5
 
 
 
 
 
 
 
3322b77
 
fc19570
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bb469a5
 
 
 
 
 
 
3322b77
 
bb469a5
 
3322b77
 
 
fc19570
 
bb469a5
fc19570
 
 
 
 
 
bb469a5
fc19570
bb469a5
 
 
 
 
 
 
 
 
 
 
 
 
 
3322b77
bb469a5
3322b77
bb469a5
fc19570
bb469a5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fc19570
 
 
bb469a5
fc19570
 
 
 
bb469a5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a51c831
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fc19570
 
 
bb469a5
 
fc19570
3322b77
a51c831
 
 
 
fc19570
 
 
 
 
bb469a5
 
fc19570
3322b77
fc19570
 
a51c831
 
 
8dc7996
a51c831
fc19570
 
 
 
bb469a5
 
fc19570
3322b77
fc19570
 
 
 
 
 
3322b77
 
 
bb469a5
 
3322b77
 
 
fc19570
 
 
 
 
 
 
 
 
 
3322b77
 
bb469a5
 
3322b77
 
 
fc19570
 
 
bb469a5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fc19570
 
 
 
 
 
 
bb469a5
fc19570
bb469a5
a51c831
 
 
 
 
fc19570
 
 
 
 
bb469a5
 
fc19570
3322b77
fc19570
 
a51c831
 
 
 
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
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
import json
from functools import lru_cache
import re
import traceback
from typing import Optional

import gradio as gr
from huggingface_hub import HfApi, hf_hub_download, hf_hub_url
from huggingface_hub.utils import HfHubHTTPError


DEFAULT_REPO_ID = "mlfoundations-cua-dev/human_eval"
IMAGE_EXTENSIONS = (
    ".jpg",
    ".jpeg",
    ".png",
    ".bmp",
    ".gif",
    ".webp",
    ".tif",
    ".tiff",
)
INIT_SCREENSHOT_NAMES = {"intial_screenshot", "initial_screenshot"}
STEP_FILENAME_PATTERN = re.compile(r"^step_(\d+)(?:\.[^.]+)?$", re.IGNORECASE)
TRAJECTORY_FILENAME = "traj.jsonl"


api = HfApi()


@lru_cache(maxsize=16)
def _list_repo_files(repo_id: str) -> list[str]:
    """Return all file paths contained in a Hugging Face dataset repository."""
    return api.list_repo_files(repo_id=repo_id, repo_type="dataset")


def _extract_top_level(repo_id: str) -> tuple[list[str], list[str]]:
    """Split top-level folders and files for the given repository."""
    files = _list_repo_files(repo_id)
    top_level_dirs = sorted({path.split("/", 1)[0] for path in files if "/" in path})
    top_level_files = sorted(path for path in files if "/" not in path)
    return top_level_dirs, top_level_files


def _get_subdirectories(repo_id: str, directory: str) -> list[str]:
    """Return the direct subdirectories of the given directory."""
    if not directory:
        return []

    files = [path for path in _list_repo_files(repo_id) if path.startswith(f"{directory}/")]
    relative_paths = [path[len(directory) + 1 :] for path in files]
    
    # Get immediate subdirectories (first level only)
    child_dirs = sorted({rel.split("/", 1)[0] for rel in relative_paths if "/" in rel})
    
    return child_dirs


def _build_path(*parts) -> str:
    """Join path parts while skipping empty values."""
    return "/".join(part for part in parts if part)


def _image_sort_key(path: str):
    filename = path.rsplit("/", 1)[-1]
    lower_name = filename.lower()

    if any(lower_name.startswith(name) for name in INIT_SCREENSHOT_NAMES):
        return (0, 0)

    match = STEP_FILENAME_PATTERN.match(lower_name)
    if match:
        return (1, int(match.group(1)))

    return (2, lower_name)


def _load_traj_entries(repo_id: str, directory: str) -> list:
    """Load trajectory annotations from traj.jsonl within the given directory."""
    if not directory:
        return []

    traj_path = _build_path(directory, TRAJECTORY_FILENAME)
    repo_files = _list_repo_files(repo_id)

    if traj_path not in repo_files:
        return []

    local_path = hf_hub_download(
        repo_id=repo_id,
        filename=traj_path,
        repo_type="dataset",
    )

    entries: list = []
    with open(local_path, "r", encoding="utf-8") as file:
        for raw_line in file:
            stripped = raw_line.strip()
            if not stripped:
                continue

            parsed = json.loads(stripped)
            if isinstance(parsed, list):
                entries.extend(parsed)
            else:
                entries.append(parsed)

    return entries


def _load_instruction_file(repo_id: str, filepath: str) -> Optional[str]:
    """Download a metadata JSON file and extract its instruction field."""
    local_path = hf_hub_download(
        repo_id=repo_id,
        filename=filepath,
        repo_type="dataset",
    )

    with open(local_path, "r", encoding="utf-8") as file:
        data = json.load(file)

    instruction: Optional[str] = None
    if isinstance(data, dict):
        instruction = data.get("instruction")
    elif isinstance(data, list):
        for entry in data:
            if isinstance(entry, dict) and "instruction" in entry:
                instruction = entry["instruction"]
                break

    if instruction is None:
        return None

    if isinstance(instruction, str):
        return instruction.strip()

    return str(instruction)


def _format_annotation(index: int, annotation) -> str:
    prefix = f"Step {index + 1}"
    if isinstance(annotation, str):
        content = annotation.strip()
    else:
        try:
            content = json.dumps(annotation, ensure_ascii=False)
        except TypeError:
            content = str(annotation)
    return f"{prefix}: {content}" if content else prefix


def _prepare_gallery_items(
    repo_id: str, directory: Optional[str]
) -> tuple[list[tuple[str, str]], list[str], str]:
    """Prepare gallery items, status messages, and instruction text for a directory."""
    if not directory:
        return (
            [],
            ["Select a fifth-level folder to view screenshots."],
            "ℹ️ Instruction will appear once a fifth-level folder is selected.",
        )

    prefix = f"{directory}/"
    files = [path for path in _list_repo_files(repo_id) if path.startswith(prefix)]

    image_files = [
        path
        for path in files
        if "/" not in path[len(prefix) :]
        and path.lower().endswith(IMAGE_EXTENSIONS)
    ]

    sorted_files = sorted(image_files, key=_image_sort_key)
    image_urls = [
        hf_hub_url(repo_id=repo_id, filename=path, repo_type="dataset")
        for path in sorted_files
    ]

    status_lines: list[str] = [
        f"🖼️ Images: {len(image_urls)}",
    ]

    annotations: list = []
    try:
        annotations = _load_traj_entries(repo_id, directory)
    except json.JSONDecodeError as error:
        status_lines.append(f"⚠️ Failed to parse `{TRAJECTORY_FILENAME}`: {error}")
    except Exception as error:  # pragma: no cover - unexpected IO errors
        status_lines.append(f"⚠️ Error loading `{TRAJECTORY_FILENAME}`: {error}")

    status_lines.append(f"📝 Annotations: {len(annotations)}")

    if not image_urls:
        status_lines.append("⚠️ No images found in this folder.")

    if image_urls and not annotations:
        status_lines.append(
            f"⚠️ `{TRAJECTORY_FILENAME}` missing or empty; no annotations to display."
        )

    if annotations and len(annotations) != len(image_urls):
        status_lines.append(
            "⚠️ Mismatch between images and annotations; displaying available pairs."
        )

    folder_name = directory.rsplit("/", 1)[-1]
    metadata_files = [
        path
        for path in files
        if "/" not in path[len(prefix) :]
        and path.lower().endswith(".json")
        and not path.lower().endswith(".jsonl")
    ]

    instruction_markdown = ""
    if metadata_files:
        metadata_files.sort(
            key=lambda path: (
                0
                if path.rsplit("/", 1)[-1].rsplit(".", 1)[0] == folder_name
                else 1,
                path.rsplit("/", 1)[-1].lower(),
            )
        )
        metadata_path = metadata_files[0]
        metadata_filename = metadata_path.rsplit("/", 1)[-1]
        try:
            instruction_value = _load_instruction_file(repo_id, metadata_path)
            if instruction_value:
                instruction_markdown = f"**Instruction:** {instruction_value}"
                status_lines.append("📋 Instruction: loaded")
            else:
                instruction_markdown = (
                    f"⚠️ Instruction missing in `{metadata_filename}`."
                )
                status_lines.append("⚠️ Instruction: missing in metadata.")
        except json.JSONDecodeError as error:
            status_lines.append(
                f"⚠️ Failed to parse `{metadata_filename}`: {error}"
            )
            instruction_markdown = (
                f"⚠️ Unable to parse instruction from `{metadata_filename}`."
            )
        except Exception as error:  # pragma: no cover - unexpected IO errors
            status_lines.append(
                f"⚠️ Error loading `{metadata_filename}`: {error}"
            )
            instruction_markdown = (
                f"⚠️ Unable to load instruction from `{metadata_filename}`."
            )
    else:
        instruction_markdown = "⚠️ Instruction file not found in this folder."
        status_lines.append("⚠️ Instruction: file not found.")

    gallery_items: list[tuple[str, str]] = []
    for idx, url in enumerate(image_urls):
        caption = "No annotation available"
        if idx < len(annotations):
            caption = _format_annotation(idx, annotations[idx])
        gallery_items.append((url, caption))

    return gallery_items, status_lines, instruction_markdown


def _dropdown_update(
    *,
    choices: list[str],
    value: Optional[str],
    label: str,
    filled_info: str,
    empty_info: str,
):
    has_choices = bool(choices)
    return gr.update(
        choices=choices,
        value=value if has_choices else None,
        interactive=has_choices,
        label=label,
        info=filled_info if has_choices else empty_info,
    )


def refresh_repo(repo_id: str):
    try:
        top_dirs, top_files = _extract_top_level(repo_id)
    except HfHubHTTPError as error:
        print(f"[refresh_repo] Hub HTTP error for {repo_id}: {error}", flush=True)
        print(traceback.format_exc(), flush=True)
        return (
            gr.update(choices=[], value=None, interactive=False),
            gr.update(choices=[], value=None, interactive=False),
            gr.update(choices=[], value=None, interactive=False),
            gr.update(choices=[], value=None, interactive=False),
            gr.update(choices=[], value=None, interactive=False),
            gr.update(value=""),
            gr.update(value=[]),
            gr.update(value=""),
            gr.update(value=f"❌ Unable to load repo `{repo_id}`: {error}"),
        )
    except Exception as error:  # pragma: no cover - network and auth edge cases
        print(f"[refresh_repo] Unexpected error for {repo_id}: {error}", flush=True)
        print(traceback.format_exc(), flush=True)
        return (
            gr.update(choices=[], value=None, interactive=False),
            gr.update(choices=[], value=None, interactive=False),
            gr.update(choices=[], value=None, interactive=False),
            gr.update(choices=[], value=None, interactive=False),
            gr.update(choices=[], value=None, interactive=False),
            gr.update(value=""),
            gr.update(value=[]),
            gr.update(value=""),
            gr.update(value=f"❌ Unexpected error loading `{repo_id}`: {error}"),
        )

    status_lines = [
        f"✅ Loaded `{repo_id}`",
        f"• Top-level folders: {len(top_dirs)}",
    ]

    if top_files:
        status_lines.append(f"• Loose files at root: {len(top_files)}")
    if not top_dirs:
        status_lines.append("• No sub-folders found at root.")

    top_value = top_dirs[0] if top_dirs else None

    second_dirs = _get_subdirectories(repo_id, top_value) if top_value else []
    second_value = second_dirs[0] if second_dirs else None

    third_dirs = (
        _get_subdirectories(repo_id, _build_path(top_value, second_value))
        if second_value
        else []
    )
    third_value = third_dirs[0] if third_dirs else None

    fourth_dirs = (
        _get_subdirectories(repo_id, _build_path(top_value, second_value, third_value))
        if third_value
        else []
    )
    fourth_value = fourth_dirs[0] if fourth_dirs else None

    fifth_dirs = (
        _get_subdirectories(
            repo_id, _build_path(top_value, second_value, third_value, fourth_value)
        )
        if fourth_value
        else []
    )
    fifth_value = fifth_dirs[0] if fifth_dirs else None

    target_directory = (
        _build_path(
            top_value,
            second_value,
            third_value,
            fourth_value,
            fifth_value,
        )
        if fifth_value
        else None
    )
    gallery_items, gallery_status, instruction_markdown = _prepare_gallery_items(
        repo_id, target_directory
    )

    first_dropdown_update = _dropdown_update(
        choices=top_dirs,
        value=top_value,
        label="Top-level folders",
        filled_info="Choose a folder to explore",
        empty_info="No folders found at the repository root",
    )

    second_dropdown_update = _dropdown_update(
        choices=second_dirs,
        value=second_value,
        label="Second-level folders",
        filled_info="Choose a second-level folder",
        empty_info="No subdirectories under the selected folder",
    )

    third_dropdown_update = _dropdown_update(
        choices=third_dirs,
        value=third_value,
        label="Third-level folders",
        filled_info="Choose a third-level folder",
        empty_info="No third-level folders under the selection",
    )

    fourth_dropdown_update = _dropdown_update(
        choices=fourth_dirs,
        value=fourth_value,
        label="Fourth-level folders",
        filled_info="Choose a fourth-level folder",
        empty_info="No fourth-level folders under the selection",
    )

    fifth_dropdown_update = _dropdown_update(
        choices=fifth_dirs,
        value=fifth_value,
        label="Fifth-level folders",
        filled_info="Choose a fifth-level folder",
        empty_info="No fifth-level folders under the selection",
    )

    instruction_update = gr.update(value=instruction_markdown)
    gallery_update = gr.update(value=gallery_items)
    annotation_update = gr.update(value="\n".join(gallery_status))
    status_update = gr.update(value="\n".join(status_lines))

    return (
        first_dropdown_update,
        second_dropdown_update,
        third_dropdown_update,
        fourth_dropdown_update,
        fifth_dropdown_update,
        instruction_update,
        gallery_update,
        annotation_update,
        status_update,
    )


def update_second_dropdown(repo_id: str, top_level_dir: str):
    """Update downstream dropdowns when the top-level selection changes."""
    try:
        if not top_level_dir:
            empty_second = _dropdown_update(
                choices=[],
                value=None,
                label="Second-level folders",
                filled_info="Choose a second-level folder",
                empty_info="Select a top-level folder first",
            )
            empty_third = _dropdown_update(
                choices=[],
                value=None,
                label="Third-level folders",
                filled_info="Choose a third-level folder",
                empty_info="Select a higher-level folder first",
            )
            empty_fourth = _dropdown_update(
                choices=[],
                value=None,
                label="Fourth-level folders",
                filled_info="Choose a fourth-level folder",
                empty_info="Select a higher-level folder first",
            )
            empty_fifth = _dropdown_update(
                choices=[],
                value=None,
                label="Fifth-level folders",
                filled_info="Choose a fifth-level folder",
                empty_info="Select a higher-level folder first",
            )
            instruction_update = gr.update(
                value="ℹ️ Select a top-level folder to display its instruction."
            )
            gallery_update = gr.update(value=[])
            annotation_update = gr.update(
                value="Select a top-level folder to load screenshots and annotations."
            )
            return (
                empty_second,
                empty_third,
                empty_fourth,
                empty_fifth,
                instruction_update,
                gallery_update,
                annotation_update,
            )

        second_dirs = _get_subdirectories(repo_id, top_level_dir)
        second_value = second_dirs[0] if second_dirs else None

        third_dirs = (
            _get_subdirectories(repo_id, _build_path(top_level_dir, second_value))
            if second_value
            else []
        )
        third_value = third_dirs[0] if third_dirs else None

        fourth_dirs = (
            _get_subdirectories(
                repo_id, _build_path(top_level_dir, second_value, third_value)
            )
            if third_value
            else []
        )
        fourth_value = fourth_dirs[0] if fourth_dirs else None

        fifth_dirs = (
            _get_subdirectories(
                repo_id,
                _build_path(top_level_dir, second_value, third_value, fourth_value),
            )
            if fourth_value
            else []
        )
        fifth_value = fifth_dirs[0] if fifth_dirs else None

        target_directory = (
            _build_path(
                top_level_dir,
                second_value,
                third_value,
                fourth_value,
                fifth_value,
            )
            if fifth_value
            else None
        )
        (
            gallery_items,
            gallery_status,
            instruction_markdown,
        ) = _prepare_gallery_items(repo_id, target_directory)

        return (
            _dropdown_update(
                choices=second_dirs,
                value=second_value,
                label="Second-level folders",
                filled_info="Choose a second-level folder",
                empty_info="No subdirectories under the selected folder",
            ),
            _dropdown_update(
                choices=third_dirs,
                value=third_value,
                label="Third-level folders",
                filled_info="Choose a third-level folder",
                empty_info="No third-level folders under the selection",
            ),
            _dropdown_update(
                choices=fourth_dirs,
                value=fourth_value,
                label="Fourth-level folders",
                filled_info="Choose a fourth-level folder",
                empty_info="No fourth-level folders under the selection",
            ),
            _dropdown_update(
                choices=fifth_dirs,
                value=fifth_value,
                label="Fifth-level folders",
                filled_info="Choose a fifth-level folder",
                empty_info="No fifth-level folders under the selection",
            ),
            gr.update(value=instruction_markdown),
            gr.update(value=gallery_items),
            gr.update(value="\n".join(gallery_status)),
        )
    except Exception as error:
        print(f"[update_second_dropdown] Error for {repo_id}/{top_level_dir}: {error}", flush=True)
        print(traceback.format_exc(), flush=True)
        empty_second = _dropdown_update(
            choices=[],
            value=None,
            label="Second-level folders",
            filled_info="Choose a second-level folder",
            empty_info="Unable to load subdirectories",
        )
        empty_third = _dropdown_update(
            choices=[],
            value=None,
            label="Third-level folders",
            filled_info="Choose a third-level folder",
            empty_info="Unable to load subdirectories",
        )
        empty_fourth = _dropdown_update(
            choices=[],
            value=None,
            label="Fourth-level folders",
            filled_info="Choose a fourth-level folder",
            empty_info="Unable to load subdirectories",
        )
        empty_fifth = _dropdown_update(
            choices=[],
            value=None,
            label="Fifth-level folders",
            filled_info="Choose a fifth-level folder",
            empty_info="Unable to load subdirectories",
        )
        return (
            empty_second,
            empty_third,
            empty_fourth,
            empty_fifth,
            gr.update(value="Unable to load instruction."),
            gr.update(value=[]),
            gr.update(value="Unable to load screenshots or annotations."),
        )


def update_third_dropdown(repo_id: str, top_level_dir: str, second_level_dir: str):
    """Update the third and fourth dropdowns when the second-level changes."""
    try:
        if not top_level_dir or not second_level_dir:
            empty_third = _dropdown_update(
                choices=[],
                value=None,
                label="Third-level folders",
                filled_info="Choose a third-level folder",
                empty_info="Select higher-level folders first",
            )
            empty_fourth = _dropdown_update(
                choices=[],
                value=None,
                label="Fourth-level folders",
                filled_info="Choose a fourth-level folder",
                empty_info="Select higher-level folders first",
            )
            empty_fifth = _dropdown_update(
                choices=[],
                value=None,
                label="Fifth-level folders",
                filled_info="Choose a fifth-level folder",
                empty_info="Select higher-level folders first",
            )
            instruction_update = gr.update(
                value="ℹ️ Select higher-level folders to display the instruction."
            )
            gallery_update = gr.update(value=[])
            annotation_update = gr.update(
                value="Select higher-level folders to load screenshots and annotations."
            )
            return (
                empty_third,
                empty_fourth,
                empty_fifth,
                instruction_update,
                gallery_update,
                annotation_update,
            )

        third_dirs = _get_subdirectories(
            repo_id, _build_path(top_level_dir, second_level_dir)
        )
        third_value = third_dirs[0] if third_dirs else None

        fourth_dirs = (
            _get_subdirectories(
                repo_id, _build_path(top_level_dir, second_level_dir, third_value)
            )
            if third_value
            else []
        )
        fourth_value = fourth_dirs[0] if fourth_dirs else None

        fifth_dirs = (
            _get_subdirectories(
                repo_id,
                _build_path(top_level_dir, second_level_dir, third_value, fourth_value),
            )
            if fourth_value
            else []
        )
        fifth_value = fifth_dirs[0] if fifth_dirs else None

        target_directory = (
            _build_path(
                top_level_dir,
                second_level_dir,
                third_value,
                fourth_value,
                fifth_value,
            )
            if fifth_value
            else None
        )
        (
            gallery_items,
            gallery_status,
            instruction_markdown,
        ) = _prepare_gallery_items(repo_id, target_directory)

        return (
            _dropdown_update(
                choices=third_dirs,
                value=third_value,
                label="Third-level folders",
                filled_info="Choose a third-level folder",
                empty_info="No third-level folders under the selection",
            ),
            _dropdown_update(
                choices=fourth_dirs,
                value=fourth_value,
                label="Fourth-level folders",
                filled_info="Choose a fourth-level folder",
                empty_info="No fourth-level folders under the selection",
            ),
            _dropdown_update(
                choices=fifth_dirs,
                value=fifth_value,
                label="Fifth-level folders",
                filled_info="Choose a fifth-level folder",
                empty_info="No fifth-level folders under the selection",
            ),
            gr.update(value=instruction_markdown),
            gr.update(value=gallery_items),
            gr.update(value="\n".join(gallery_status)),
        )
    except Exception as error:
        print(
            f"[update_third_dropdown] Error for {repo_id}/{top_level_dir}/{second_level_dir}: {error}",
            flush=True,
        )
        print(traceback.format_exc(), flush=True)
        empty_third = _dropdown_update(
            choices=[],
            value=None,
            label="Third-level folders",
            filled_info="Choose a third-level folder",
            empty_info="Unable to load subdirectories",
        )
        empty_fourth = _dropdown_update(
            choices=[],
            value=None,
            label="Fourth-level folders",
            filled_info="Choose a fourth-level folder",
            empty_info="Unable to load subdirectories",
        )
        empty_fifth = _dropdown_update(
            choices=[],
            value=None,
            label="Fifth-level folders",
            filled_info="Choose a fifth-level folder",
            empty_info="Unable to load subdirectories",
        )
        return (
            empty_third,
            empty_fourth,
            empty_fifth,
            gr.update(value="Unable to load instruction."),
            gr.update(value=[]),
            gr.update(value="Unable to load screenshots or annotations."),
        )


def update_fourth_dropdown(
    repo_id: str,
    top_level_dir: str,
    second_level_dir: str,
    third_level_dir: str,
):
    """Update the fourth and fifth dropdowns when the third-level changes."""
    try:
        if not top_level_dir or not second_level_dir or not third_level_dir:
            empty_fourth = _dropdown_update(
                choices=[],
                value=None,
                label="Fourth-level folders",
                filled_info="Choose a fourth-level folder",
                empty_info="Select higher-level folders first",
            )
            empty_fifth = _dropdown_update(
                choices=[],
                value=None,
                label="Fifth-level folders",
                filled_info="Choose a fifth-level folder",
                empty_info="Select higher-level folders first",
            )
            instruction_update = gr.update(
                value="ℹ️ Select higher-level folders to display the instruction."
            )
            gallery_update = gr.update(value=[])
            annotation_update = gr.update(
                value="Select higher-level folders to load screenshots and annotations."
            )
            return (
                empty_fourth,
                empty_fifth,
                instruction_update,
                gallery_update,
                annotation_update,
            )

        fourth_dirs = _get_subdirectories(
            repo_id,
            _build_path(top_level_dir, second_level_dir, third_level_dir),
        )
        fourth_value = fourth_dirs[0] if fourth_dirs else None

        fifth_dirs = (
            _get_subdirectories(
                repo_id,
                _build_path(
                    top_level_dir, second_level_dir, third_level_dir, fourth_value
                ),
            )
            if fourth_value
            else []
        )
        fifth_value = fifth_dirs[0] if fifth_dirs else None

        target_directory = (
            _build_path(
                top_level_dir,
                second_level_dir,
                third_level_dir,
                fourth_value,
                fifth_value,
            )
            if fifth_value
            else None
        )
        (
            gallery_items,
            gallery_status,
            instruction_markdown,
        ) = _prepare_gallery_items(repo_id, target_directory)

        return (
            _dropdown_update(
                choices=fourth_dirs,
                value=fourth_value,
                label="Fourth-level folders",
                filled_info="Choose a fourth-level folder",
                empty_info="No fourth-level folders under the selection",
            ),
            _dropdown_update(
                choices=fifth_dirs,
                value=fifth_value,
                label="Fifth-level folders",
                filled_info="Choose a fifth-level folder",
                empty_info="No fifth-level folders under the selection",
            ),
            gr.update(value=instruction_markdown),
            gr.update(value=gallery_items),
            gr.update(value="\n".join(gallery_status)),
        )
    except Exception as error:
        print(
            "[update_fourth_dropdown] Error for "
            f"{repo_id}/{top_level_dir}/{second_level_dir}/{third_level_dir}: {error}",
            flush=True,
        )
        print(traceback.format_exc(), flush=True)
        empty_fourth = _dropdown_update(
            choices=[],
            value=None,
            label="Fourth-level folders",
            filled_info="Choose a fourth-level folder",
            empty_info="Unable to load subdirectories",
        )
        empty_fifth = _dropdown_update(
            choices=[],
            value=None,
            label="Fifth-level folders",
            filled_info="Choose a fifth-level folder",
            empty_info="Unable to load subdirectories",
        )
        return (
            empty_fourth,
            empty_fifth,
            gr.update(value="Unable to load instruction."),
            gr.update(value=[]),
            gr.update(value="Unable to load screenshots or annotations."),
        )


def update_fifth_dropdown(
    repo_id: str,
    top_level_dir: str,
    second_level_dir: str,
    third_level_dir: str,
    fourth_level_dir: str,
):
    """Update the fifth dropdown and gallery when the fourth-level changes."""
    try:
        if not all(
            [top_level_dir, second_level_dir, third_level_dir, fourth_level_dir]
        ):
            empty_fifth = _dropdown_update(
                choices=[],
                value=None,
                label="Fifth-level folders",
                filled_info="Choose a fifth-level folder",
                empty_info="Select higher-level folders first",
            )
            instruction_update = gr.update(
                value="ℹ️ Select higher-level folders to display the instruction."
            )
            gallery_update = gr.update(value=[])
            annotation_update = gr.update(
                value="Select higher-level folders to load screenshots and annotations."
            )
            return empty_fifth, instruction_update, gallery_update, annotation_update

        fifth_dirs = _get_subdirectories(
            repo_id,
            _build_path(
                top_level_dir,
                second_level_dir,
                third_level_dir,
                fourth_level_dir,
            ),
        )
        fifth_value = fifth_dirs[0] if fifth_dirs else None

        target_directory = (
            _build_path(
                top_level_dir,
                second_level_dir,
                third_level_dir,
                fourth_level_dir,
                fifth_value,
            )
            if fifth_value
            else None
        )
        (
            gallery_items,
            gallery_status,
            instruction_markdown,
        ) = _prepare_gallery_items(repo_id, target_directory)

        return (
            _dropdown_update(
                choices=fifth_dirs,
                value=fifth_value,
                label="Fifth-level folders",
                filled_info="Choose a fifth-level folder",
                empty_info="No fifth-level folders under the selection",
            ),
            gr.update(value=instruction_markdown),
            gr.update(value=gallery_items),
            gr.update(value="\n".join(gallery_status)),
        )
    except Exception as error:
        print(
            "[update_fifth_dropdown] Error for "
            f"{repo_id}/{top_level_dir}/{second_level_dir}/{third_level_dir}/{fourth_level_dir}: {error}",
            flush=True,
        )
        print(traceback.format_exc(), flush=True)
        empty_fifth = _dropdown_update(
            choices=[],
            value=None,
            label="Fifth-level folders",
            filled_info="Choose a fifth-level folder",
            empty_info="Unable to load subdirectories",
        )
        return (
            empty_fifth,
            gr.update(value="Unable to load instruction."),
            gr.update(value=[]),
            gr.update(value="Unable to load screenshots or annotations."),
        )


def update_gallery(
    repo_id: str,
    top_level_dir: str,
    second_level_dir: str,
    third_level_dir: str,
    fourth_level_dir: str,
    fifth_level_dir: str,
):
    """Update the image gallery when the fifth-level selection changes."""
    try:
        directory = (
            _build_path(
                top_level_dir,
                second_level_dir,
                third_level_dir,
                fourth_level_dir,
                fifth_level_dir,
            )
            if all(
                [
                    top_level_dir,
                    second_level_dir,
                    third_level_dir,
                    fourth_level_dir,
                    fifth_level_dir,
                ]
            )
            else None
        )
        (
            gallery_items,
            gallery_status,
            instruction_markdown,
        ) = _prepare_gallery_items(repo_id, directory)
        return (
            gr.update(value=instruction_markdown),
            gr.update(value=gallery_items),
            gr.update(value="\n".join(gallery_status)),
        )
    except Exception as error:
        print(
            "[update_gallery] Error for "
            f"{repo_id}/{top_level_dir}/{second_level_dir}/{third_level_dir}/{fourth_level_dir}/{fifth_level_dir}: {error}",
            flush=True,
        )
        print(traceback.format_exc(), flush=True)
        return (
            gr.update(value="Unable to load instruction."),
            gr.update(value=[]),
            gr.update(value="Unable to load screenshots or annotations."),
        )


with gr.Blocks(title="HF Dataset Explorer") as demo:
    gr.Markdown(
        """# Hugging Face Dataset Explorer

Provide a dataset repository ID (e.g. `org/dataset`) to list its top-level folders."""
    )

    with gr.Row():
        repo_id_input = gr.Textbox(
            value=DEFAULT_REPO_ID,
            label="Dataset repo ID",
            placeholder="owner/dataset",
            info="Any public dataset on the Hugging Face Hub"
        )
        reload_button = gr.Button("Load repo", variant="primary")

    status_display = gr.Markdown()
    folder_dropdown = gr.Dropdown(label="Top-level folders", interactive=False)
    second_level_dropdown = gr.Dropdown(label="Second-level folders", interactive=False)
    third_level_dropdown = gr.Dropdown(label="Third-level folders", interactive=False)
    fourth_level_dropdown = gr.Dropdown(label="Fourth-level folders", interactive=False)
    fifth_level_dropdown = gr.Dropdown(label="Fifth-level folders", interactive=False)
    instruction_display = gr.Markdown()
    image_gallery = gr.Gallery(label="Images", columns=4)
    annotation_status = gr.Markdown()

    reload_button.click(
        refresh_repo,
        inputs=repo_id_input,
        outputs=[
            folder_dropdown,
            second_level_dropdown,
            third_level_dropdown,
            fourth_level_dropdown,
            fifth_level_dropdown,
            instruction_display,
            image_gallery,
            annotation_status,
            status_display,
        ],
    )

    folder_dropdown.change(
        update_second_dropdown,
        inputs=[repo_id_input, folder_dropdown],
        outputs=[
            second_level_dropdown,
            third_level_dropdown,
            fourth_level_dropdown,
            fifth_level_dropdown,
            instruction_display,
            image_gallery,
            annotation_status,
        ],
    )

    second_level_dropdown.change(
        update_third_dropdown,
        inputs=[repo_id_input, folder_dropdown, second_level_dropdown],
        outputs=[
            third_level_dropdown,
            fourth_level_dropdown,
            fifth_level_dropdown,
            instruction_display,
            image_gallery,
            annotation_status,
        ],
    )

    third_level_dropdown.change(
        update_fourth_dropdown,
        inputs=[
            repo_id_input,
            folder_dropdown,
            second_level_dropdown,
            third_level_dropdown,
        ],
        outputs=[
            fourth_level_dropdown,
            fifth_level_dropdown,
            instruction_display,
            image_gallery,
            annotation_status,
        ],
    )

    fourth_level_dropdown.change(
        update_fifth_dropdown,
        inputs=[
            repo_id_input,
            folder_dropdown,
            second_level_dropdown,
            third_level_dropdown,
            fourth_level_dropdown,
        ],
        outputs=[
            fifth_level_dropdown,
            instruction_display,
            image_gallery,
            annotation_status,
        ],
    )

    fifth_level_dropdown.change(
        update_gallery,
        inputs=[
            repo_id_input,
            folder_dropdown,
            second_level_dropdown,
            third_level_dropdown,
            fourth_level_dropdown,
            fifth_level_dropdown,
        ],
        outputs=[instruction_display, image_gallery, annotation_status],
    )

    demo.load(
        refresh_repo,
        inputs=repo_id_input,
        outputs=[
            folder_dropdown,
            second_level_dropdown,
            third_level_dropdown,
            fourth_level_dropdown,
            fifth_level_dropdown,
            instruction_display,
            image_gallery,
            annotation_status,
            status_display,
        ],
    )

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