File size: 57,308 Bytes
a4c66c6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7e67548
 
 
 
 
a4c66c6
 
7e67548
 
 
 
 
 
 
 
 
 
 
 
a4c66c6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
14a1280
 
 
a4c66c6
14a1280
 
 
 
 
 
 
 
 
 
 
 
 
 
a4c66c6
 
14a1280
 
a4c66c6
 
 
 
a13c44b
a4c66c6
a13c44b
 
 
a4c66c6
a13c44b
a4c66c6
 
 
 
 
a13c44b
a4c66c6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a13c44b
a4c66c6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a13c44b
 
 
 
28da886
a4c66c6
 
28da886
 
 
 
 
 
 
 
 
 
 
a13c44b
28da886
 
a4c66c6
 
a13c44b
a4c66c6
a13c44b
a4c66c6
 
a13c44b
 
 
a4c66c6
 
 
 
 
 
 
 
 
 
a13c44b
 
 
 
 
a4c66c6
 
 
a13c44b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a4c66c6
 
 
a13c44b
 
a4c66c6
a13c44b
a4c66c6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
333cd03
 
a4c66c6
 
 
 
 
 
 
 
 
 
 
 
333cd03
a4c66c6
 
 
333cd03
a4c66c6
333cd03
a4c66c6
 
 
 
333cd03
a4c66c6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a13c44b
 
 
 
 
 
 
 
 
333cd03
a4c66c6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a13c44b
a4c66c6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
333cd03
 
 
 
a4c66c6
333cd03
a4c66c6
 
 
 
333cd03
a4c66c6
333cd03
a4c66c6
 
 
 
 
 
 
 
 
 
 
 
 
333cd03
a4c66c6
333cd03
a4c66c6
 
 
 
 
 
 
 
 
 
333cd03
 
 
 
 
 
 
 
 
 
 
 
a4c66c6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a13c44b
 
 
 
 
 
a4c66c6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
14a1280
a13c44b
a4c66c6
a13c44b
a4c66c6
 
 
 
 
a13c44b
 
 
 
a4c66c6
a13c44b
a4c66c6
 
 
 
a13c44b
 
 
a4c66c6
 
 
 
 
 
a13c44b
a4c66c6
a13c44b
 
 
 
a4c66c6
 
a13c44b
a4c66c6
 
 
a13c44b
a4c66c6
 
 
 
a13c44b
 
a4c66c6
 
a13c44b
a4c66c6
 
a13c44b
a4c66c6
a13c44b
 
 
 
 
 
 
a4c66c6
 
a13c44b
 
 
 
a4c66c6
a13c44b
 
 
 
 
 
 
 
 
 
a4c66c6
 
a13c44b
 
 
a4c66c6
 
 
 
 
 
 
 
28da886
 
 
 
a4c66c6
 
a13c44b
 
a4c66c6
 
 
 
 
 
 
 
 
 
 
 
 
a13c44b
 
 
 
 
a4c66c6
 
 
 
 
 
a13c44b
28da886
a13c44b
a4c66c6
 
a13c44b
 
 
 
 
 
 
 
 
a4c66c6
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
Hackathon Roulette โ€” spin through the Build Small Hackathon and discover
projects you'd never find by scrolling. Categorizes every submission and
lets you roulette your way to hidden gems (with in-session memory of what
you've already seen).
"""

import random
import re
import time
import html as _html

import gradio as gr
from huggingface_hub import HfApi

# โ”€โ”€ Config (the only hackathon this tool follows) โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€

HACKATHON_ORG  = "build-small-hackathon"
HACKATHON_NAME = "Build Small Hackathon"

# Org spaces that aren't real submissions โ€” excluded from the roulette.
INFRA_SPACES = {"field-guide", "readme", "registration"}

# โ”€โ”€ Category taxonomy โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
# Ordered list of (name, emoji, keywords). Categorization is FIRST-MATCH-WINS,
# so order runs specific genres/domains first, modality next, and the broad
# "Assistants" bucket last as a catch-all. Keywords are matched with a LEFT
# word-boundary (\bkw) against a camelCase-split, lowercased blob of
# title+name+description+tags โ€” so "radio" never matches "gradio" and "voice"
# never matches "invoice", while stems like "transcrib" still catch
# "transcribe". Tuned against all live submissions: ~92% land in a real
# category; the remaining "Other" are spaces that ship no description and no
# topical tags on the Hub, so there is nothing to categorize them by.
# NOTE: avoid keywords that match non-topical badge/track tags (e.g. "brand"
# hits the "off-brand" achievement tag, "track" hits "track:wood").

TAXONOMY = [
 ("Games, RPGs & Interactive Fiction", "๐ŸŽฎ", ["game","rpg","roguelike","roguelite","deckbuild","dungeon","escape room","escape-room","text-adventure","text adventure","adventure","misadventure","interactive-fiction","interactive fiction","visual novel","visual-novel","ttrpg","tabletop","whodunit","detective","courtroom","tribunal","verdict","jury","puzzle","riddle","arcade","poker","chess","mafia","duel","arena","akinator","backrooms","parkour","phaser","playable","gameplay","roleplay","role-play","reverse-turing","reverse turing","trolley","board game","deathmatch","choose your","trivia","survival","maze","wordle","sudoku","betting","dating sim","platformer","sokoban","tower defense","idle game","mystery","heist","casino","card game","gamif","goblin","brawl","argue","debate","karate","kung fu","ninja","samurai","dota","doom","emulat","gameboy","game boy","nintendo","n64","royale","worldcup","world cup","objection","trial","arcane","fighter","battle","combat","boss fight","zombie","monster","tycoon","racing","racer","wrestl","boxing","party game","interrogat","dare","escape the","you are a god","play as","npc","pixel game","bullet hell","stealth game","sandbox game","grid royale","party","speak to your manager","chaos goblin","worst","you decide"]),
 ("Worlds, Sims & Multi-Agent Societies", "๐ŸŒ", ["multi-agent","multi agent","simulation","simulator","persistent world","world-build","world building","world-building","world model","colony","civilization","civilisation","city-builder","city builder","village","smol town","ecosystem","terraform","self-play","agent-simulation","trading firm","rumor economy","gossip economy","tiny civilization","living forest","sandbox","life sim","tamagotchi","god game","council","swarm","terrarium","parliament","senate","society","kingdom","empire","dynasty","planet","universe","galaxy","cosmos","forest","organism","flock","hive mind","tiny minds","mastermind","multi-model","multi model","agent society","emergent","cellular automata","game of life","conway","ant colony","aquarium","habitat","biome"]),
 ("Health, Medical & Wellness", "๐Ÿฉบ", ["medical","clinical","clinic","healthcare","health companion","medgemma","patient","symptom","diagnos","radiology","x-ray","dental","pharmacy","pharma","prescription","medicine","blood test","nutrition","nutri","pregnan","caregiver","elderly","parkinson","stroke","vaccine","neoantigen","first aid","physiotherap","cardiac","heartbeat","variant effect","prediction engine","mental-health","mental health","emotional support","anxiety","therapy","wellness","grief","adhd","neurodiverg","allergen","disease","doctor","nurse","hospital","telemedicine","surgery","surgeon","dentist","cancer","tumor","tumour","diabet","insulin","glucose","blood pressure","asthma","skin","derma","biosignal","biomarker","genom","dna","protein","molecul","metaboli","drug","medication","rehab","addiction","depression","autism","fitness","workout","exercise","meditat","sleep tracker","calorie","diet","vitamin","supplement","counsel","mri","ultrasound","spoilage"]),
 ("Tutors, Study & Language Learning", "๐ŸŽ“", ["tutor","study buddy","study partner","studybuddy","study copilot","homework","exam","flashcard","quiz","socratic","lesson","teaching","teach an","teach the","classroom","kids","children","preschool","toddler","language-learning","language learning","language practice","lingo","learn korean","learn japanese","learn languages","learn english","english expression","duolingo","reading buddy","read-along","read along","dyslexi","iep","whiteboard","cbse","ncert","samacheer","scholar","literature-review","interview coach","interview prep","speech coach","running coach","gym coach","curriculum","educational","flashcard generator","spaced repetition","vocabulary","grammar","mnemonic","coach","mentor","study","math","physics","chemistry","biology","school","student","academic","university","college","mandarin","spanish","french","german","japanese","sentence","essay","spelling","explainer","encyclopedia","admission","scholarship","upskill","tutorial","counsellor","counselor","exam prep","study abroad","memoriz","practice partner","skill builder","wikipedia"]),
 ("Finance, Documents & Business", "๐Ÿ’ผ", ["invoice","accounting","bookkeep","ledger","receipt","expense","budget","taxes","tax filing","tax season","finops","finance","financ","financial","stocks","stock market","trading","alpha signal","sec filing","insurance","crm","inventory","udhaar","shopkeeper","kirana","dukaan","sales","pricing","price comparison","real-estate","real estate","ads advisor","resume","job description","reconcil","lease","legal","legislation","contract","bureaucra","immigration","compliance","ocr","document-ai","text-to-sql","spreadsheet","rfq","payroll","procurement","gig work","freelance","order desk","orders","retail","shop","store","marketplace","ecommerce","e-commerce","wallet","payment","money","salary","wage","startup","business","entrepreneur","marketing","advertis","customer","revenue","profit","bank","loan","mortgage","crypto","portfolio","market","economy","logistics","supply chain","warehouse","dispatch","delivery","vendor","quote","estimate","proposal","pdf","paperwork","report generat","dashboard","analytics","excel","csv","data analysis","structured data","audit","job","hiring","recruit","applicant","rejection","pitch deck","pitch practice","operations","letter","decoder","finops","fin ops","viscosity","controller"]),
 ("Scan, Vision & Physical-World Utilities", "๐Ÿ“ธ", ["plant","garden","crop","weed","herbicide","farm","beekeep","honeybee","apiar","soil","satellite","eurosat","land-use","solar","weather","watering","fridge","recipe","meal plan","cook","ingredient","food waste","upcycl","mushroom","forager","edible","stray animal","wardrobe","outfit","fashion","stylist","car diagnostic","appliance fault","repair","defect","building-inspection","road-defect","object-detection","yolo","vlm","vision-language","computer-vision","image classif","segment","label lens","posture","barcode","football","soccer","referee","sports","photo","photograph","camera","scan","snap","detect","recognition","classif","classifier","identif","vision","map","maps","gps","navigation","travel","route","drone","aircraft","vehicle","automobile","traffic","parking","animal","bird","insect","wildlife","species","fish","pet ","dog","cat ","kitten","food","kitchen","waste","recycl","agriculture","3d print","3d-print","printer","factory","manufactur","mechanic","machine fault","maintenance","inspection","sensor","iot","gesture","augmented reality","junk drawer","aircraft rarity"]),
 ("Safety, Security & Privacy", "๐Ÿ›ก๏ธ", ["scam","phishing","fraud","online-safety","online safety","cybersec","security","soc analyst","osint","threat","vuln","pii","privacy","redact","guardrail","firewall","dark pattern","deepfake","captcha","jailbreak","safety-eval","prompt-injection","airlock","malware","ransomware","hacker","exploit","encrypt","decrypt","password","authentication","biometric","surveillance","moderation","toxic","abuse","harassment","nsfw","misinformation","fact check","fake news","watermark","ai detector","deepverify","scrub","sensitive leak","content filter","redac","anonymiz"]),
 ("Dev, Code, Robotics & Model Tooling", "โš™๏ธ", ["code review","code-review","code-generation","commit","repo","github","mermaid","flowchart","diagram","debug","rubber duck","rubber-duck","pull request","refactor","decompil","gpu kernel","gpu-kernel","fine-tune","fine-tuning","distill","quantiz","benchmark","structured json","data-engineering","excalidraw","skill router","skill-router","formal-verification","lean4","mcp-server","devops","reachy","robot","esp32","arduino","onnx","webgpu","transformers.js","transformers-js","rl-environment","openenv","grpo","interpretab","surprisal","next-token","abliterat","tokenizer","regex","evaluation pipeline","llm eval","sql query","coding","developer","software","api ","cli ","terminal","shell","bash","python","javascript","database","backend","frontend","kubernetes","deploy","unit test","compile","kernel","vram","cuda","inference","latency","throughput","embedding","neural","pytorch","wasm","plugin","firmware","observability","monitoring","logging","codebase","cognitive architecture","evaluat","benchmark suite","prompt engineer","activation","emulator","vla ","policy network","skill","recap and shell"]),
 ("Voice, Speech, Music & Translation", "๐ŸŽ™๏ธ", ["voice","music","radio","voice-clon","voice clon","tts","text-to-speech","asr","speech-to-text","speech-to-speech","speech-translation","whisper","voxcpm","kokoro","f5-tts","fastconformer","dubbing","narration","narrator","read aloud","read-aloud","audiobook","podcast","music-generation","music generator","lofi","lo-fi","lullab","singalong","karaoke","lyric","sheet music","transcrib","pronunciation","recitation","sign language","sign-language","sign2voice","dictation","translation","translate","translat","spoken word","song","melody","chorus","beat","rhythm","remix","compose","composer","composition","instrument","instrumental","piano","guitar","drum","violin","saxophone","synth","vocal","singer","singing","soundtrack","midi","harmony","chord","ambient","playlist","jingle","anthem","acoustic","audio","sound","speech","spoken","multilingual","subtitle","caption","accent","band","music video"]),
 ("Story, Image & Creative Generation", "๐ŸŽจ", ["story","stories","storybook","storytell","bedtime","fairytale","fairy tale","picture book","comic","manga","illustrat","poem","poetry","poetic","novel","fable","creative-writing","creative writing","narrative","text-to-image","image-generation","image generation","img2img","image-to-image","diffusion","flux","sd-turbo","sticker","pixel-art","pixel art","typograph","voxel","avatar","manim","animation","text-to-video","image-to-video","claymation","postcard","sketch","doodle","watercolour","minecraftify","generative-art","kinetic typography","icon generator","logo","wallpaper","emoji","meme","theater","theatre","puppet","myth","legend","fantasy","witch","wizard","dragon","coloring","collage","video","film","tale","tales","draw","drawing","paint","painting","artist","design","designer","creative","render","scene","webtoon","poster","greeting card","album cover","cover art","font","3d","canvas","author","quill","writing","write","clip","broadcast","movie","cinema","gif","caricature","portrait"]),
 ("Companions, Personas & Reflective Toys", "๐Ÿ’š", ["companion","waifu","persona","character chat","character with","in character","virtual character","desktop pet","floating desktop","virtual pet","tsundere","yandere","girlfriend","confidant","journaling","voice journal","mood journal","gratitude journal","daily journal","reflection","oneiro","oracle","divination","prophecy","fortune teller","magic 8","tarot","arcana","seance","sรฉance","occult","constellation","lives unlived","unlived","parallel life","museum of","elegy","afterlife","loneliness","mindful","stargazing","imaginary friend","pen pal","penpal","diary","gratitude","affirmation","horoscope","zodiac","astrolog","emotion","feeling","mood","empath","friend","buddy","familiar","creature","soul","spirit","ghost","fairy","imaginary","comfort","vent","confession","secret","wish","memory","nostalgia","heart","love","romance","crush","relationship","tombstone","raise a","baby ai","overthink","decompress","dream","temper","inner voice","alter ego"]),
 ("Assistants, Agents & Productivity", "๐Ÿ’ฌ", ["assistant","co-pilot","copilot","chatbot","chat assistant","chat with","agent","helper","concierge","butler","productivity","to-do","todo","task manager","note-taking","note taking","notetaking","meeting notes","summari","email","inbox","calendar","schedul","planner","reminder","advisor","recommend","knowledge base","knowledge hub","knowledgehub","second brain","retrieval-augmented","rag ","search engine","web search","personal ai","local ai","offline ai","home assistant","conversational","workflow","support","docu","research assistant","news","digest","faq","automation","ai","app","tool","chat","bot","gpt","llm","small model","tiny model","local model","on-device","mini","tiny","smol","helps you","help you","capture","recall","organize","tracker","logbook","search","ask","query","answer","wiki","scrape","crawl","pipeline","integration","slack","discord","telegram","whatsapp","decision","prompt","model","plan","vibe","gemma","llama","qwen","nemotron","minicpm","smol","context","studio","powered","pocket","forge","32b","14b","8b","mind"]),
]

OTHER_NAME, OTHER_EMOJI = "Other", "๐ŸŽ"

CAT_EMOJI = {name: emoji for name, emoji, _ in TAXONOMY}
CAT_EMOJI[OTHER_NAME] = OTHER_EMOJI
CAT_EMOJI["All"] = "๐ŸŽฒ"

# Filter choices: All, every real category, then Other (the grab-bag).
ALL_CATEGORIES = ["All"] + [name for name, _, _ in TAXONOMY] + [OTHER_NAME]

# Pre-compile keyword patterns once (left word-boundary).
_COMPILED = [(name, [re.compile(r"\b" + re.escape(k)) for k in kws])
             for name, _, kws in TAXONOMY]
_CAMEL = re.compile(r"(?<=[a-z0-9])(?=[A-Z])")

# Framework / sponsor / model tags that carry no topical signal.
_NOISE_TOK = {
    "gradio", "docker", "static", "build-small-hackathon", "backyard-ai",
    "backyard ai", "tiny-titan", "tiny titan", "off-the-grid", "offgrid",
    "nemotron", "minicpm", "llama-cpp", "openbmb", "zerogpu", "transformers",
    "nvidia", "modal", "openai", "region:us",
}

# Official hackathon tracks โ†’ friendly label (shown as a card badge).
_TRACK_MAP = {
    "track:backyard": "Backyard", "track:backyard-ai": "Backyard",
    "track:wood": "Thousand Token Wood",
    "track:thousand-token-wood": "Thousand Token Wood",
    "track:thousand_token_wood": "Thousand Token Wood",
}

# โ”€โ”€ Categorization โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€

def _categorize(title: str, raw: str, desc: str, tags: list) -> str:
    keep = [t for t in tags if t.lower() not in _NOISE_TOK]
    blob = f"{title} {raw.replace('-', ' ').replace('_', ' ')} {desc} {' '.join(keep)}"
    blob = _CAMEL.sub(" ", blob).lower()
    for name, pats in _COMPILED:
        if any(p.search(blob) for p in pats):
            return name
    return OTHER_NAME


def _track_of(tags: list) -> str:
    for t in tags:
        lbl = _TRACK_MAP.get(t.lower())
        if lbl:
            return lbl
    return ""

# โ”€โ”€ Data loading (cached once per process) โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€

_CACHE: list | None = None
_CACHE_TS: float = 0.0
CACHE_TTL = 600  # re-index at most every 10 min so live submissions join the pool

# Populated on every successful load so the UI can explain the pool size.
_STATS = {"listed": 0, "private": 0, "infra": 0, "pool": 0}


def _card_data(space) -> dict:
    """Robustly pull the card dict โ€” SpaceCardData is NOT a plain dict on
    modern huggingface_hub, so isinstance(dict) would silently drop everything."""
    cd = getattr(space, "cardData", None)
    if cd is None:
        return {}
    if hasattr(cd, "to_dict"):
        try:
            return cd.to_dict()
        except Exception:
            pass
    if isinstance(cd, dict):
        return dict(cd)
    return {}


def load_spaces(force: bool = False) -> list:
    """Index every PUBLIC submission in the hackathon org.

    Private/gated spaces are skipped on purpose: they aren't in the public
    listing, they'd be dead links for anyone the roulette sends there, and
    skipping them makes the pool identical whether or not an HF token is
    present in the environment โ€” so the draw is fair and reproducible.
    """
    global _CACHE, _CACHE_TS
    now = time.time()
    if not force and _CACHE is not None and (now - _CACHE_TS) < CACHE_TTL:
        return _CACHE

    api = HfApi()
    spaces: list = []
    listed = private = infra = 0
    try:
        for s in api.list_spaces(author=HACKATHON_ORG, full=True):
            listed += 1
            if getattr(s, "private", False):
                private += 1
                continue
            raw = s.id.split("/")[-1] if "/" in s.id else s.id
            if raw.lower() in INFRA_SPACES:
                infra += 1
                continue

            cd     = _card_data(s)
            title  = str(cd.get("title") or "").strip()
            desc   = str(cd.get("short_description") or cd.get("description") or "").strip()[:320]
            sdk    = str(cd.get("sdk") or "").strip()
            tags   = list(s.tags or [])
            author = s.author or (s.id.split("/")[0] if "/" in s.id else "?")

            spaces.append({
                "id":       s.id,
                "name":     title or raw.replace("-", " ").replace("_", " ").title(),
                "raw_name": raw,
                "author":   author,
                "tags":     tags,
                "likes":    int(getattr(s, "likes", 0) or 0),
                "url":      f"https://huggingface.co/spaces/{s.id}",
                "desc":     desc,
                "sdk":      sdk,
                "track":    _track_of(tags),
                "category": _categorize(title, raw, desc, tags),
            })
    except Exception as exc:  # never let a network hiccup crash the Space
        print(f"[hackathon-roulette] load error: {exc}")

    # Only replace a good cache when we actually got data โ€” a transient fetch
    # error shouldn't empty the pool mid-event.
    if spaces or _CACHE is None:
        _CACHE = spaces
        _CACHE_TS = now
        if spaces:
            _STATS.update(listed=listed, private=private, infra=infra, pool=len(spaces))
    return _CACHE


def _bucket(spaces: list, cat: str) -> list:
    return [s for s in spaces if cat == "All" or s["category"] == cat]


def _display_tags(sp: dict) -> list:
    out = []
    for t in sp["tags"]:
        tl = t.lower()
        if tl in _NOISE_TOK:
            continue
        if t.startswith(("region:", "license:", "arxiv:", "doi:", "track:",
                         "sponsor:", "achievement:", "base_model:", "dataset:",
                         "pipeline_tag:", "badge-", "badge:")):
            continue
        out.append(t)
    return out

# โ”€โ”€ HTML builders โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€

def _stats(seen: list, spaces: list, cat: str) -> str:
    seen_set = set(seen)
    bucket = _bucket(spaces, cat)
    total  = len(bucket)
    found  = sum(1 for s in bucket if s["id"] in seen_set)
    left   = total - found
    pct    = round(found / total * 100) if total else 0

    cats_html = ""
    if cat == "All":
        counts = {}
        for s in spaces:
            counts[s["category"]] = counts.get(s["category"], 0) + 1
        ordered = [(n, e, counts.get(n, 0)) for n, e, _ in TAXONOMY]
        ordered.append((OTHER_NAME, OTHER_EMOJI, counts.get(OTHER_NAME, 0)))
        cats_html = "".join(
            f'<span class="cat-count" title="{_html.escape(n)}">{e}&nbsp;{c}</span>'
            for n, e, c in ordered if c
        )

    return f"""
<div class="stats-bar">
  <div class="stat-row">
    <div class="stat-item"><span class="snum">{total}</span><span class="slbl">spaces</span></div>
    <span class="sdot">ยท</span>
    <div class="stat-item"><span class="snum" style="color:#4ade80">{found}</span><span class="slbl">seen</span></div>
    <span class="sdot">ยท</span>
    <div class="stat-item"><span class="snum" style="color:#60a5fa">{left}</span><span class="slbl">to go</span></div>
    <div class="pbar-wrap"><div class="pbar-fill" style="width:{pct}%"></div></div>
    <span class="pbar-lbl">{pct}%</span>
  </div>
  {_why_note() if cat == "All" else ""}
  {f'<div class="cat-counts">{cats_html}</div>' if cats_html else ""}
</div>"""


def _why_note() -> str:
    pool   = _STATS.get("pool", 0)
    infra  = _STATS.get("infra", 0)
    priv   = _STATS.get("private", 0)
    listed = _STATS.get("listed", 0) or (pool + infra + priv)
    if not listed:
        return ""
    pub  = listed - priv  # public Spaces โ€” the count the org page shows visitors
    info = (f"<strong>{infra}</strong> org info page" + ("s" if infra != 1 else "")
            + " (<em>field-guide</em> &amp; <em>README</em>)")
    if priv:
        # Authenticated: we can actually see and count the private/test spaces, so
        # reconcile every number โ€” total, private, the public page count, infra.
        head = f"โ“˜ why {pool}, not {listed}?"
        body = (f"The org has <strong>{listed}</strong> Spaces in total. "
                f"<strong>{priv}</strong> are private or test spaces (so the public page "
                f"shows <strong>{pub}</strong>), and {info} aren't competition entries โ€” "
                f"leaving <strong>{pool}</strong> real, public submissions to spin through.")
    else:
        # Anonymous: the Hub API won't reveal the private spaces, so don't claim a
        # total that would contradict the higher number on the org page.
        head = f"โ“˜ {pool} public submissions"
        body = (f"Every public project the Hub's API serves, minus {info}. Private and "
                f"test Spaces โ€” plus a handful the org page counts that the public API "
                f"doesn't return โ€” aren't included.")
    return f"""
<div class="why-line">
  <span class="why-chip" tabindex="0">{head}
    <span class="why-pop">{body}</span>
  </span>
</div>"""


def _placeholder(msg: str = "", spin_count: int | None = None) -> str:
    inner = msg or "Pull the lever โ€” hit <strong>SPIN</strong> to discover a random project!"
    # When a placeholder is the *result* of a spin/back (overlay is up), carry
    # data-spin so the client reveal poller resolves instead of timing out.
    ds = f' data-spin="{spin_count}"' if spin_count is not None else ""
    return f"""
<div class="ph-wrap"{ds}>
  <div class="ph-dice">๐ŸŽฐ</div>
  <p class="ph-txt">{inner}</p>
</div>"""


def _card(sp: dict, spin_count: int, footer: str = "") -> str:
    e   = _html.escape
    cat = sp["category"]
    em  = CAT_EMOJI.get(cat, "๐ŸŽ")

    chips = "".join(f'<span class="tag-chip">{e(t)}</span>' for t in _display_tags(sp)[:7])
    sdk_b   = f'<span class="sdk-pill">{e(sp["sdk"])}</span>' if sp.get("sdk") else ""
    track_b = f'<span class="track-pill">๐ŸŒฒ {e(sp["track"])}</span>' if sp.get("track") else ""

    desc = sp.get("desc", "").strip()
    desc_html = e(desc) if desc else "<em class='nodesc'>No description provided โ€” open it to find out!</em>"

    # data-spin carries the monotonic spin counter so the client can reliably
    # detect "a fresh result arrived" by polling for the value to change โ€” robust
    # whether Gradio mounts a new node or mutates the existing one. The card
    # animates via pure CSS (no inline <script>, which wouldn't run via innerHTML).
    return f"""
<div class="space-card" data-spin="{spin_count}">
  <div class="card-shine"></div>
  <div class="card-meta">
    <span class="cat-pill">{em} {e(cat)}</span>
    {track_b}{sdk_b}
    <span class="likes-pill">โค๏ธ {sp['likes']}</span>
  </div>
  <h2 class="card-h">{e(sp['name'])}</h2>
  <p class="card-by">by <strong>{e(sp['author'])}</strong></p>
  <p class="card-desc">{desc_html}</p>
  <div class="card-chips">{chips}</div>
  <div class="card-foot">
    <a href="{sp['url']}" target="_blank" rel="noopener" class="open-btn">๐Ÿš€ Open Space</a>
    <span class="draw-note">{footer}</span>
  </div>
</div>"""


def _browse_list(spaces: list, cat: str, seen: list) -> str:
    bucket = sorted(_bucket(spaces, cat), key=lambda s: -s["likes"])
    if not bucket:
        return '<p class="browse-empty">Nothing here yet.</p>'

    seen_set = set(seen)
    CAP = 60
    rows = []
    for s in bucket[:CAP]:
        e = _html.escape
        seen_mark = '<span class="seen-dot" title="already seen">โœ“</span>' if s["id"] in seen_set else ""
        em = CAT_EMOJI.get(s["category"], "๐ŸŽ")
        rows.append(f"""
<a class="browse-row" href="{s['url']}" target="_blank" rel="noopener">
  <span class="br-em">{em}</span>
  <span class="br-name">{e(s['name'])}{seen_mark}</span>
  <span class="br-author">{e(s['author'])}</span>
  <span class="br-likes">โค๏ธ {s['likes']}</span>
</a>""")
    more = ""
    if len(bucket) > CAP:
        more = f'<p class="browse-more">+ {len(bucket) - CAP} more โ€” spin or pick a tighter category to see them</p>'
    return f'<div class="browse-wrap">{"".join(rows)}{more}</div>'

# โ”€โ”€ Callbacks โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€

def _find(spaces: list, sid: str):
    return next((s for s in spaces if s["id"] == sid), None)


def on_load(seen: list):
    spaces = load_spaces()
    n = len(spaces)
    # `seen` arrives from the browser (BrowserState โ†’ localStorage), so returning
    # visitors keep their progress. Drop ids no longer in the pool and de-dupe.
    valid = {s["id"] for s in spaces}
    seen  = [sid for sid in dict.fromkeys(seen or []) if sid in valid]
    if not n:
        msg = "Couldn't reach the Hub right now โ€” try refreshing in a moment."
    elif seen:
        msg = (f"๐Ÿ‘‹ Welcome back โ€” you've already seen <strong>{len(seen)}</strong> of "
               f"<strong>{n}</strong> projects. Hit SPIN for one you haven't!")
    else:
        msg = f"Loaded <strong>{n}</strong> projects from the {HACKATHON_NAME} โ€” ready to roll! ๐ŸŽ‰"
    # state: seen, cat, spin_ctr, hist, pos  +  stats, card, back-button(disabled)
    return (seen, "All", 0, [], -1,
            _stats(seen, spaces, "All"), _placeholder(msg), gr.update(interactive=False))


def on_spin(seen: list, cat: str, spin_count: int, hist: list, pos: int):
    spaces = load_spaces()
    new_count = spin_count + 1
    bucket = _bucket(spaces, cat)
    if not bucket:
        # data-spin on the placeholder so the client reveal poller still resolves
        return (_placeholder("No projects in this category.", new_count), seen, new_count,
                _stats(seen, spaces, cat), hist, pos, gr.update(interactive=pos > 0))

    seen_set = set(seen)
    unseen = [s for s in bucket if s["id"] not in seen_set]
    banner = ""
    if not unseen:
        bucket_ids = {s["id"] for s in bucket}
        seen   = [sid for sid in seen if sid not in bucket_ids]   # reset just this bucket
        unseen = bucket
        banner = '<div class="reset-note">๐ŸŽ‰ You\'ve seen every project here โ€” reshuffling the deck!</div>'

    # Don't redraw the project already on screen (only reachable on the reshuffle
    # path, where the current card is back in the pool) unless it's the only one.
    cur_id = hist[pos] if 0 <= pos < len(hist) else None
    pool   = [s for s in unseen if s["id"] != cur_id] or unseen
    pick      = random.choice(pool)
    new_seen  = list(seen) + [pick["id"]]
    position  = sum(1 for s in bucket if s["id"] in set(new_seen))

    # Browser-style history: drop anything "forward" of the current position,
    # then append this draw. Back Spin walks this stack; it's global, so it
    # survives category switches.
    new_hist  = list(hist[:pos + 1]) + [pick["id"]]
    new_pos   = len(new_hist) - 1

    card = banner + _card(pick, new_count, f"draw #{position} of {len(bucket)}")
    return (card, new_seen, new_count, _stats(new_seen, spaces, cat),
            new_hist, new_pos, gr.update(interactive=new_pos > 0))


def on_back(hist: list, pos: int, spin_count: int):
    """Re-show the project viewed just before the current one."""
    spaces    = load_spaces()
    new_count = spin_count + 1                      # always bump so the client poller resolves
    # Step back when possible; if already at the start (button should be disabled,
    # but a click can slip through before the disabled state propagates) just
    # re-show the current card rather than hanging the reel.
    new_pos = pos - 1 if (pos > 0 and hist) else max(pos, 0)
    if not hist:
        return _placeholder("Spin first!", new_count), pos, new_count, gr.update(interactive=False)

    sp = _find(spaces, hist[new_pos]) if 0 <= new_pos < len(hist) else None
    if sp is None:
        card = _placeholder("That project is no longer available.", new_count)
    else:
        card = _card(sp, new_count, f"โ†ฉ back-spin ยท {new_pos + 1} of {len(hist)}")
    return card, new_pos, new_count, gr.update(interactive=new_pos > 0)


def on_category(cat: str, seen: list):
    # Keep the current card on screen (don't reset it) so Back Spin always has the
    # last project to return to, and so switching filters never wipes your view.
    spaces = load_spaces()
    return cat, _stats(seen, spaces, cat)


def on_browse(cat: str, seen: list):
    spaces = load_spaces()
    return _browse_list(spaces, cat, seen)

# โ”€โ”€ CSS โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€

CSS = r"""
/* โ”€โ”€ aurora backdrop โ”€โ”€ */
body, gradio-app { background:#070714 !important; }
.gradio-container { background: transparent !important; max-width: 760px !important; margin: 0 auto !important; position: relative; z-index: 1; }
body::before {
  content:''; position:fixed; inset:-30%; z-index:0; pointer-events:none; filter: blur(22px);
  background:
    radial-gradient(38% 38% at 20% 22%, #7c3aed30, transparent 60%),
    radial-gradient(36% 36% at 82% 18%, #2563eb2b, transparent 60%),
    radial-gradient(44% 44% at 72% 82%, #f472b624, transparent 60%),
    radial-gradient(40% 40% at 22% 86%, #22d3ee1f, transparent 60%);
  animation: aurora 24s ease-in-out infinite alternate;
}
@keyframes aurora {
  0%   { transform: translate3d(-3%,-2%,0) rotate(0deg)  scale(1.05); }
  50%  { transform: translate3d(3%, 2%,0)  rotate(7deg)  scale(1.16); }
  100% { transform: translate3d(-2%,3%,0)  rotate(-6deg) scale(1.08); }
}
footer { display: none !important; }

.app-header { text-align: center; padding: 2rem 1rem 0.4rem; position: relative; }
.hdr-icon { font-size: 3.1rem; display: block; margin-bottom: .25rem;
  animation: pop 1s cubic-bezier(.175,.885,.32,1.275) both;
  filter: drop-shadow(0 0 14px #7c3aed88); }
@keyframes pop { 0%{transform:scale(0) rotate(-200deg);opacity:0} 75%{transform:scale(1.18) rotate(10deg)} 100%{transform:scale(1) rotate(0);opacity:1} }
.hdr-title { font-size: 2rem; font-weight: 900; margin: .1rem 0 .35rem;
  background: linear-gradient(120deg,#a78bfa,#60a5fa 50%,#f472b6);
  background-size: 200% auto; -webkit-background-clip: text; -webkit-text-fill-color: transparent;
  background-clip: text; animation: shimmer 6s linear infinite; }
@keyframes shimmer { to { background-position: 200% center; } }
.hdr-sub { color: #9292c6; font-size: .87rem; margin: 0; }
.hdr-sub strong { color: #b8b8e0; }

/* โ”€โ”€ mute toggle โ”€โ”€ */
.rl-mute { position:absolute; top:.4rem; right:.2rem; background:#0f0f28; border:1px solid #242456;
  color:#c0c0e8; border-radius:10px; width:38px; height:38px; font-size:1.05rem; cursor:pointer;
  transition:transform .12s, border-color .15s, box-shadow .2s; z-index:3; }
.rl-mute:hover { transform:scale(1.08); border-color:#7c3aed; box-shadow:0 0 14px #7c3aed55; }
.rl-mute.muted { opacity:.55; }

.stats-bar { background:#0f0f28cc; backdrop-filter:blur(6px); border:1px solid #1e1e48; border-radius:12px; padding:.6rem 1rem; margin:.5rem 0; }
.stat-row { display:flex; align-items:center; gap:.65rem; flex-wrap:wrap; }
.stat-item { display:flex; flex-direction:column; align-items:center; }
.snum { font-size:1.25rem; font-weight:800; color:#a78bfa; line-height:1.05; transition:color .3s; }
.slbl { font-size:.58rem; color:#9090c4; text-transform:uppercase; letter-spacing:.07em; }
.sdot { color:#1e1e48; }
.pbar-wrap { flex:1; min-width:60px; height:5px; background:#1e1e48; border-radius:3px; overflow:hidden; }
.pbar-fill { height:100%; background:linear-gradient(90deg,#7c3aed,#60a5fa,#f472b6); background-size:200% auto; transition:width .5s ease; animation:shimmer 3s linear infinite; }
.pbar-lbl { color:#9292c6; font-size:.74rem; font-weight:600; min-width:2.4rem; text-align:right; }
.cat-counts { display:flex; gap:.32rem; flex-wrap:wrap; margin-top:.55rem; padding-top:.55rem; border-top:1px solid #16163a; }
.cat-count { background:#0a0a20; border:1px solid #1e1e48; border-radius:7px; padding:.1rem .42rem; font-size:.72rem; color:#9a9acc; transition:transform .1s, border-color .15s; }
.cat-count:hover { transform:translateY(-1px); border-color:#34346e; }

/* โ”€โ”€ why-884 tooltip โ”€โ”€ */
.why-line { margin-top:.5rem; padding-top:.5rem; border-top:1px solid #16163a; }
.why-chip { position:relative; display:inline-block; font-size:.74rem; color:#9a9acc;
  background:#0a0a20; border:1px solid #20204a; border-radius:8px; padding:.12rem .5rem; cursor:help; outline:none; }
.why-chip:hover, .why-chip:focus { border-color:#7c3aed; color:#a78bfa; }
.why-pop { position:absolute; left:0; bottom:130%; width:300px; max-width:80vw; z-index:20;
  background:#13132e; border:1px solid #34346e; border-radius:10px; padding:.6rem .75rem;
  color:#a0a0d0; font-size:.78rem; line-height:1.5; text-align:left; box-shadow:0 8px 30px #000a;
  opacity:0; transform:translateY(4px); pointer-events:none; transition:opacity .15s, transform .15s; }
.why-pop strong { color:#c8c8f0; } .why-pop em { color:#5fd58b; font-style:normal; }
.why-chip:hover .why-pop, .why-chip:focus .why-pop { opacity:1; transform:translateY(0); }

/* โ”€โ”€ SPIN button: glow + spin states โ”€โ”€ */
#spin-btn, #spin-btn button { background:linear-gradient(135deg,#7c3aed,#2563eb)!important; color:#fff!important; border:none!important;
  border-radius:14px!important; font-size:1.3rem!important; font-weight:900!important; letter-spacing:.1em!important;
  transition:transform .12s, box-shadow .2s!important; min-height:54px!important; animation: glow 2.6s ease-in-out infinite; }
@keyframes glow { 0%,100%{ box-shadow:0 4px 22px rgba(124,58,237,.45); } 50%{ box-shadow:0 4px 30px rgba(124,58,237,.7), 0 0 16px rgba(96,165,250,.45); } }
#spin-btn:hover, #spin-btn button:hover { transform:translateY(-2px)!important; box-shadow:0 7px 34px rgba(124,58,237,.75)!important; }
#spin-btn:active, #spin-btn button:active { transform:translateY(0) scale(.97)!important; }
#spin-btn.spinning, #spin-btn.spinning button { animation: glow-fast .45s ease-in-out infinite; }
@keyframes glow-fast { 0%,100%{ box-shadow:0 4px 26px rgba(124,58,237,.7); } 50%{ box-shadow:0 6px 44px rgba(244,114,182,.85), 0 0 28px rgba(96,165,250,.7); } }

/* โ”€โ”€ Back Spin button โ€” subtler sibling of SPIN, disabled until there's history โ”€โ”€ */
#back-btn, #back-btn button { background:#13132e!important; color:#a78bfa!important; border:1px solid #34346e!important;
  border-radius:14px!important; font-size:1rem!important; font-weight:800!important; letter-spacing:.04em!important;
  transition:transform .12s, box-shadow .2s, opacity .2s, border-color .2s!important; min-height:54px!important; }
#back-btn:not(:disabled):hover, #back-btn:not(:disabled) button:hover { transform:translateY(-2px)!important; border-color:#7c3aed!important; box-shadow:0 6px 22px rgba(124,58,237,.4)!important; }
#back-btn:not(:disabled):active, #back-btn:not(:disabled) button:active { transform:translateY(0) scale(.97)!important; }
#back-btn:disabled, #back-btn button:disabled, #back-btn[disabled] { opacity:.38!important; cursor:not-allowed!important; box-shadow:none!important; transform:none!important; }
#back-btn.spinning, #back-btn.spinning button { animation: glow-fast .4s ease-in-out infinite; border-color:#7c3aed!important; }

#cat-dd label span { color:#9292c6!important; font-size:.78rem!important; }
#cat-dd input, #cat-dd .wrap { background:#0f0f28!important; border-color:#1e1e48!important; color:#c0c0e8!important; }

/* โ”€โ”€ slot reel (shown while waiting for the draw) โ”€โ”€ */
#card-out { position: relative; }
.rl-reel-overlay { position:absolute; inset:0; min-height:172px; z-index:40; display:flex;
  align-items:center; justify-content:center; background:#0a0a1c; border-radius:16px;
  animation: ov-in .12s ease both; }
@keyframes ov-in { from { opacity:.35; } to { opacity:1; } }
.rl-reel-overlay .reel-wrap { padding:1rem; }
.reel-wrap { text-align:center; padding:2.2rem 1rem; }
.reel { width:100%; max-width:340px; height:78px; margin:0 auto; overflow:hidden; position:relative;
  border:1px solid #2a2a5c; border-radius:14px; background:#0c0c22;
  box-shadow:inset 0 0 30px #000, 0 0 26px #7c3aed66; }
.reel::before, .reel::after { content:''; position:absolute; top:0; bottom:0; width:46px; z-index:2; pointer-events:none; }
.reel::before { left:0;  background:linear-gradient(90deg,#0c0c22,transparent); }
.reel::after  { right:0; background:linear-gradient(270deg,#0c0c22,transparent); }
.reel-strip { display:inline-block; white-space:nowrap; font-size:2.7rem; line-height:78px;
  animation: reel-roll .42s linear infinite; filter: blur(.3px); will-change: transform; }
.reel.reel-back .reel-strip { animation-direction: reverse; }   /* rewind scrolls the other way */
@keyframes reel-roll { from { transform:translateX(0); } to { transform:translateX(-2em); } }
.reel-txt { color:#7c7cb8; margin-top:.85rem; font-size:.92rem; letter-spacing:.05em; animation: pulse-txt 1s ease-in-out infinite; }
@keyframes pulse-txt { 0%,100%{ opacity:.45; } 50%{ opacity:1; } }

/* โ”€โ”€ result card โ”€โ”€ */
.space-card { background:#0f0f28; border:1px solid #242456; border-radius:16px; padding:1.5rem; margin-top:.7rem;
  position:relative; overflow:hidden; transform-origin:center top;
  animation: card-drop .55s cubic-bezier(.175,.885,.32,1.275) both; }
.space-card::before { content:''; position:absolute; inset:0; z-index:0; border-radius:16px; background:linear-gradient(135deg,#7c3aed14,#2563eb14,#f472b614); pointer-events:none; }
@keyframes card-drop { 0%{opacity:0;transform:translateY(26px) scale(.94) rotateX(9deg);filter:blur(5px)} 60%{opacity:1;transform:translateY(-6px) scale(1.015)} 100%{opacity:1;transform:translateY(0) scale(1);filter:blur(0)} }
.card-shine { position:absolute; top:0; left:-60%; width:50%; height:100%; z-index:1; pointer-events:none;
  background:linear-gradient(105deg, transparent, #ffffff22 45%, #ffffff33 50%, transparent 60%);
  animation: shine 1.1s ease-out .25s both; }
@keyframes shine { from { left:-60%; } to { left:130%; } }
.space-card > *:not(.card-shine) { position:relative; z-index:2; }

.card-meta { display:flex; align-items:center; gap:.4rem; flex-wrap:wrap; margin-bottom:.85rem; position:relative; z-index:2; }
.cat-pill { background:#17173a; border:1px solid #34346e; border-radius:10px; padding:.2rem .6rem; font-size:.76rem; color:#a78bfa; }
.track-pill { background:#0c1f12; border:1px solid #1c4a2c; border-radius:10px; padding:.2rem .6rem; font-size:.72rem; color:#5fd58b; }
.sdk-pill { background:#0a1420; border:1px solid #1a3050; border-radius:10px; padding:.2rem .6rem; font-size:.7rem; color:#6aa8e0; text-transform:uppercase; letter-spacing:.04em; }
.likes-pill { margin-left:auto; color:#f472b6; font-weight:700; font-size:.86rem; }
.card-h { font-size:1.5rem; font-weight:900; color:#e6e6ff; margin:0 0 .15rem; line-height:1.18; position:relative; z-index:2; }
.card-by { color:#9090c4; font-size:.86rem; margin:0 0 .8rem; position:relative; z-index:2; }
.card-by strong { color:#b8b8e0; }
.card-desc { color:#9c9cd2; font-size:.95rem; line-height:1.6; margin:0 0 1rem; position:relative; z-index:2; }
.card-desc .nodesc { color:#8c8cc2; }
.card-chips { display:flex; flex-wrap:wrap; gap:.3rem; margin-bottom:1.1rem; position:relative; z-index:2; }
.tag-chip { background:#080818; border:1px solid #1c1c3c; border-radius:6px; padding:.13rem .48rem; font-size:.68rem; color:#9a9acc; }
.card-foot { display:flex; align-items:center; gap:.8rem; }
.open-btn { display:inline-block; background:linear-gradient(135deg,#7c3aed,#2563eb); color:#fff!important; text-decoration:none!important;
  border-radius:10px; padding:.55rem 1.3rem; font-weight:700; font-size:.92rem; box-shadow:0 2px 12px rgba(124,58,237,.35); transition:opacity .18s,transform .1s; }
.open-btn:hover { opacity:.9; transform:translateY(-1px); }
.draw-note { color:#8484b8; font-size:.74rem; }

.ph-wrap { text-align:center; padding:2.6rem 1rem; color:#9090c4; }
.ph-dice { font-size:3.1rem; margin-bottom:.6rem; animation:float 3s ease-in-out infinite; }
@keyframes float { 0%,100%{transform:translateY(0) rotate(-4deg)} 50%{transform:translateY(-10px) rotate(4deg)} }
.ph-txt { font-size:1rem; } .ph-txt strong { color:#a78bfa; }

.reset-note { background:#15153a; border:1px solid #7c3aed44; border-radius:10px; padding:.55rem 1rem; color:#a78bfa; font-weight:600; text-align:center; margin-bottom:.6rem; font-size:.9rem; }

#browse-acc { margin-top:.4rem; }
.browse-wrap { display:flex; flex-direction:column; gap:.25rem; max-height:420px; overflow-y:auto; padding:.2rem; }
.browse-row { display:flex; align-items:center; gap:.6rem; padding:.45rem .6rem; border-radius:9px; background:#0c0c22; border:1px solid #17173a; text-decoration:none!important; transition:background .12s,border-color .12s; }
.browse-row:hover { background:#13132e; border-color:#34346e; }
.br-em { font-size:1rem; }
.br-name { color:#c8c8f0; font-weight:600; font-size:.9rem; flex:1; min-width:0; overflow:hidden; text-overflow:ellipsis; white-space:nowrap; }
.seen-dot { color:#4ade80; font-size:.78rem; margin-left:.4rem; }
.br-author { color:#9090c4; font-size:.78rem; max-width:120px; overflow:hidden; text-overflow:ellipsis; white-space:nowrap; }
.br-likes { color:#f472b6; font-size:.78rem; font-weight:600; }
.browse-more, .browse-empty { color:#9090c4; font-size:.82rem; text-align:center; padding:.6rem; }
"""

# โ”€โ”€ Client-side JS (synthesized sound + confetti + slot reel) โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
# Wired through Gradio's supported client hooks: SETUP_JS runs once via
# demo.load(js=...), REVEAL_JS runs after each spin via .then(js=...). Audio is
# synthesized with the Web Audio API (no external files) and only starts after
# the user's first click, satisfying browser autoplay rules. A mute toggle and
# throttled/short envelopes keep it tasteful rather than grating.

HEAD_HTML = r"""<script>
// Force dark mode for ALL components regardless of the visitor's system theme.
// The custom CSS only darkens our own elements; Gradio's native chrome (dropdown,
// accordion, labels, option popups) otherwise keeps the light theme's dark text,
// which is unreadable on the dark background. Adding `dark` to <html> makes Gradio
// apply its dark palette everywhere; a MutationObserver re-asserts it if Gradio
// flips it back for a light-system viewer.
(function forceDark() {
  const el = document.documentElement;
  const ensure = () => { if (!el.classList.contains('dark')) el.classList.add('dark'); };
  ensure();
  try { new MutationObserver(ensure).observe(el, { attributes: true, attributeFilter: ['class'] }); } catch (e) {}
})();
(function () {
  if (window.RL) return;
  const RL = window.RL = { muted: false };
  let ctx = null;
  const ac = () => {
    try { if (!ctx) ctx = new (window.AudioContext || window.webkitAudioContext)(); } catch (e) { return null; }
    if (ctx && ctx.state === 'suspended') ctx.resume();
    return ctx;
  };
  const blip = (freq, t0, dur, peak, type) => {
    const c = ctx; if (!c) return;
    const o = c.createOscillator(), g = c.createGain();
    o.type = type || 'triangle'; o.frequency.setValueAtTime(freq, t0);
    g.gain.setValueAtTime(0.0001, t0);
    g.gain.exponentialRampToValueAtTime(peak, t0 + 0.01);
    g.gain.exponentialRampToValueAtTime(0.0001, t0 + dur);
    o.connect(g); g.connect(c.destination);
    o.start(t0); o.stop(t0 + dur + 0.02);
  };
  RL.tick = (v) => { if (RL.muted || !ac()) return; blip(360 + Math.random() * 240, ctx.currentTime, 0.05, v || 0.045, 'square'); };
  let hov = 0;
  RL.hover = () => { if (RL.muted) return; const n = performance.now(); if (n - hov < 90) return; hov = n; if (!ac()) return; blip(880, ctx.currentTime, 0.05, 0.02, 'sine'); };
  RL.chime = () => {
    if (RL.muted || !ac()) return;
    const base = 523.25, steps = [1, 1.25, 1.5, 2.0];
    steps.forEach((r, i) => blip(base * r, ctx.currentTime + i * 0.075, 0.5, 0.085, 'triangle'));
    const c = ctx, t = c.currentTime, o = c.createOscillator(), g = c.createGain();
    o.type = 'sine'; o.frequency.setValueAtTime(170, t); o.frequency.exponentialRampToValueAtTime(70, t + 0.25);
    g.gain.setValueAtTime(0.0001, t); g.gain.exponentialRampToValueAtTime(0.11, t + 0.012); g.gain.exponentialRampToValueAtTime(0.0001, t + 0.3);
    o.connect(g); g.connect(c.destination); o.start(t); o.stop(t + 0.33);
  };
  let spinTimer = null;
  RL.startSpinSound = () => {
    if (RL.muted) return;
    let delay = 38;
    const step = () => { RL.tick(0.045); delay = Math.min(150, delay * 1.07); spinTimer = setTimeout(step, delay); };
    step();
  };
  RL.stopSpinSound = () => { if (spinTimer) { clearTimeout(spinTimer); spinTimer = null; } };
  RL.startBackSound = () => {   // descending ticks โ€” a "rewind" counterpart to the spin
    if (RL.muted || !ac()) return;
    let f = 700, delay = 46;
    const step = () => { blip(f, ctx.currentTime, 0.05, 0.04, 'square'); f = Math.max(170, f * 0.85); delay = Math.min(150, delay * 1.06); spinTimer = setTimeout(step, delay); };
    step();
  };

  // confetti burst on a fixed overlay canvas
  let cv, cx, parts = [], raf = null;
  const COLORS = ['#a78bfa', '#60a5fa', '#f472b6', '#4ade80', '#fbbf24', '#22d3ee'];
  const mkCanvas = () => {
    if (cv) return;
    cv = document.createElement('canvas'); cv.id = 'rl-confetti';
    cv.style.cssText = 'position:fixed;inset:0;width:100vw;height:100vh;pointer-events:none;z-index:99999';
    document.body.appendChild(cv); cx = cv.getContext('2d');
    const rs = () => { cv.width = innerWidth * devicePixelRatio; cv.height = innerHeight * devicePixelRatio; cx.setTransform(devicePixelRatio, 0, 0, devicePixelRatio, 0, 0); };
    rs(); addEventListener('resize', rs);
  };
  const loop = () => {
    cx.clearRect(0, 0, innerWidth, innerHeight);
    for (const p of parts) { p.vy += p.g; p.x += p.vx; p.y += p.vy; p.vx *= 0.99; p.rot += p.vr; p.life -= 0.011; }
    parts = parts.filter(p => p.life > 0 && p.y < innerHeight + 50);
    for (const p of parts) { cx.save(); cx.globalAlpha = Math.max(0, p.life); cx.translate(p.x, p.y); cx.rotate(p.rot); cx.fillStyle = p.col; cx.fillRect(-p.s / 2, -p.s / 2, p.s, p.s * 0.55); cx.restore(); }
    raf = parts.length ? requestAnimationFrame(loop) : null;
  };
  RL.burst = (x, y) => {
    mkCanvas();
    for (let i = 0; i < 54; i++) { const a = Math.random() * Math.PI * 2, sp = 3 + Math.random() * 8; parts.push({ x, y, vx: Math.cos(a) * sp, vy: Math.sin(a) * sp - 4.5, g: 0.16 + Math.random() * 0.12, s: 5 + Math.random() * 7, rot: Math.random() * 6.28, vr: -0.3 + Math.random() * 0.6, col: COLORS[i % COLORS.length], life: 1 }); }
    if (!raf) loop();
  };

  const MIN_SPIN = 1100;  // keep the wheel visibly spinning even when the draw is instant
  const MIN_BACK = 600;   // back-spin rewinds quicker than a fresh spin
  const REEL = '<div class="reel-wrap"><div class="reel"><div class="reel-strip">๐ŸŽฎ ๐ŸŽจ ๐ŸŽ™๏ธ ๐Ÿฉบ ๐Ÿ’ผ ๐ŸŽ“ โš™๏ธ ๐ŸŒ ๐Ÿ’ฌ ๐Ÿ›ก๏ธ ๐Ÿ“ธ ๐Ÿ’š ๐ŸŽฎ ๐ŸŽจ ๐ŸŽ™๏ธ ๐Ÿฉบ<\/div><\/div><p class="reel-txt">spinning the wheelโ€ฆ<\/p><\/div>';
  const REEL_BACK = '<div class="reel-wrap"><div class="reel reel-back"><div class="reel-strip">๐Ÿฉบ ๐ŸŽ™๏ธ ๐ŸŽจ ๐ŸŽฎ ๐Ÿ’š ๐Ÿ“ธ ๐Ÿ›ก๏ธ ๐Ÿ’ฌ ๐ŸŒ โš™๏ธ ๐ŸŽ“ ๐Ÿ’ผ ๐Ÿฉบ ๐ŸŽ™๏ธ ๐ŸŽจ ๐ŸŽฎ<\/div><\/div><p class="reel-txt">โ†ฉ rewindingโ€ฆ<\/p><\/div>';
  // The reel is an OVERLAY on top of #card-out โ€” never the card's own DOM. Two
  // bugs this fixes: (1) mutating Gradio's Svelte-managed card node broke every
  // spin after the first; (2) when a cached draw returns instantly the reel/
  // sound used to flash by invisibly โ€” now the overlay (and ticks) stay up for
  // at least MIN_SPIN before the reveal.
  // Shared overlay+poll routine for both forward spins and back-spins. opts:
  // { reel, sound, min, btn } โ€” what to show, what to play, how long to hold, and
  // which button glows.
  RL._begin = (opts) => {
    ac();
    RL._busy = true;                               // serialize: ignore clicks until land()
    if (RL._poll) { clearInterval(RL._poll); RL._poll = null; }
    if (RL._revealTimer) { clearTimeout(RL._revealTimer); RL._revealTimer = null; }
    RL.stopSpinSound();
    RL._spinStart = performance.now();
    RL._min = opts.min;
    // Poll/compare against any data-spin holder (real card OR a result placeholder).
    const prev = document.querySelector('#card-out [data-spin]');
    RL._prevSpin = prev ? prev.getAttribute('data-spin') : '-1';
    const host = document.getElementById('card-out');
    if (host) {
      host.style.position = 'relative';
      let ov = host.querySelector('.rl-reel-overlay');
      if (!ov) { ov = document.createElement('div'); ov.className = 'rl-reel-overlay'; host.appendChild(ov); }
      ov.innerHTML = opts.reel; ov.style.display = 'flex';
    }
    const b = document.getElementById(opts.btn); if (b) b.classList.add('spinning');
    opts.sound();
    // Poll for the new result (data-spin changes on every draw AND back-spin);
    // reveal once it has arrived AND the wheel has spun for at least its minimum.
    const t0 = performance.now();
    RL._poll = setInterval(() => {
      const cur = document.querySelector('#card-out [data-spin]');
      const arrived = cur && cur.getAttribute('data-spin') !== RL._prevSpin;
      if (arrived || performance.now() - t0 > 6000) {
        clearInterval(RL._poll); RL._poll = null;
        const wait = Math.max(0, RL._min - (performance.now() - RL._spinStart));
        RL._revealTimer = setTimeout(() => { RL._revealTimer = null; RL.land(); }, wait);
      }
    }, 40);
  };
  RL.startSpin = () => RL._begin({ reel: REEL,      sound: RL.startSpinSound, min: MIN_SPIN, btn: 'spin-btn' });
  RL.startBack = () => RL._begin({ reel: REEL_BACK, sound: RL.startBackSound, min: MIN_BACK, btn: 'back-btn' });
  RL.land = () => {
    RL.stopSpinSound();
    ['spin-btn', 'back-btn'].forEach(id => { const b = document.getElementById(id); if (b) b.classList.remove('spinning'); });
    const host = document.getElementById('card-out');
    const ov = host && host.querySelector('.rl-reel-overlay');
    if (ov) ov.remove();                         // reveal the result underneath
    const card = document.querySelector('#card-out .space-card');
    if (card) {                                  // celebrate real cards only (not placeholders)
      card.style.animation = 'none'; void card.offsetWidth; card.style.animation = '';
      RL.chime();
      const r = card.getBoundingClientRect();
      RL.burst(r.left + r.width / 2, r.top + Math.min(120, r.height * 0.35));
    }
    RL._busy = false;                            // ready for the next click
  };

  // delegated listeners survive Gradio re-renders. Capture phase so we can
  // suppress Gradio's own click handler when a draw is mid-flight (prevents
  // overlapping spin/back draws from desyncing the history state) or when Back
  // is disabled (its click would otherwise no-op on the server).
  document.addEventListener('click', (e) => {
    const closest = (sel) => (e.target.closest && e.target.closest(sel)) || null;
    const spin = closest('#spin-btn');
    const back = closest('#back-btn');
    if (spin || back) {
      const backOff = back && (back.disabled || back.getAttribute('aria-disabled') === 'true');
      if (RL._busy || backOff) { e.preventDefault(); e.stopImmediatePropagation(); return; }
      if (spin) RL.startSpin(); else RL.startBack();
      return;
    }
    const m = closest('#rl-mute');
    if (m) { RL.muted = !RL.muted; m.textContent = RL.muted ? '๐Ÿ”‡' : '๐Ÿ”Š'; m.classList.toggle('muted', RL.muted); if (RL.muted) RL.stopSpinSound(); }
  }, true);
  document.addEventListener('pointerover', (e) => {
    if (e.target.closest && (e.target.closest('#spin-btn') || e.target.closest('#back-btn'))) RL.hover();
  }, true);
})();
</script>
"""

# โ”€โ”€ UI โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€

with gr.Blocks(css=CSS, title="๐ŸŽฐ Hackathon Roulette", theme=gr.themes.Base(),
               head=HEAD_HTML) as demo:
    # Persists viewed-project ids in the browser. A fixed secret keeps the
    # encryption key stable across Space restarts so progress survives redeploys
    # (the data is non-sensitive, so a public key is fine โ€” stability is the point).
    seen_st  = gr.BrowserState([], storage_key="hr_seen_v1", secret="hr-roulette-v1")
    cat_st   = gr.State("All")
    spin_ctr = gr.State(0)
    hist_st  = gr.State([])    # chronological ids of viewed projects (global, all categories)
    pos_st   = gr.State(-1)    # index into hist_st of the currently shown card

    gr.HTML(f"""
<div class="app-header">
  <button id="rl-mute" class="rl-mute" title="Sound on / off" aria-label="Toggle sound">๐Ÿ”Š</button>
  <span class="hdr-icon">๐ŸŽฐ</span>
  <h1 class="hdr-title">Hackathon Roulette</h1>
  <p class="hdr-sub">Spin to discover hidden gems from the <strong>{HACKATHON_NAME}</strong></p>
</div>""")

    stats_out = gr.HTML()

    with gr.Row():
        cat_dd = gr.Dropdown(choices=ALL_CATEGORIES, value="All", label="Browse by category",
                             elem_id="cat-dd", interactive=True, filterable=False)
    with gr.Row():
        back_btn = gr.Button("โ†ฉ  Back Spin", elem_id="back-btn", scale=2,
                             interactive=False, min_width=120)
        spin_btn = gr.Button("๐ŸŽฐ  SPIN", elem_id="spin-btn", scale=3, min_width=160)

    card_out = gr.HTML(elem_id="card-out")

    with gr.Accordion("๐Ÿ“‹ Browse all in this category", open=False, elem_id="browse-acc") as browse_acc:
        browse_out = gr.HTML()

    # events  (the reveal โ€” chime + confetti โ€” is driven by the data-spin poller in HEAD_HTML)
    demo.load(on_load, inputs=[seen_st],
              outputs=[seen_st, cat_st, spin_ctr, hist_st, pos_st, stats_out, card_out, back_btn])
    spin_btn.click(
        on_spin,
        inputs=[seen_st, cat_st, spin_ctr, hist_st, pos_st],
        outputs=[card_out, seen_st, spin_ctr, stats_out, hist_st, pos_st, back_btn],
    )
    back_btn.click(
        on_back,
        inputs=[hist_st, pos_st, spin_ctr],
        outputs=[card_out, pos_st, spin_ctr, back_btn],
    )
    cat_dd.change(on_category, inputs=[cat_dd, seen_st], outputs=[cat_st, stats_out])
    # keep the browse list in sync whenever the category changes or the panel opens
    cat_dd.change(on_browse, inputs=[cat_dd, seen_st], outputs=[browse_out])
    browse_acc.expand(on_browse, inputs=[cat_st, seen_st], outputs=[browse_out])


# Warm the cache at startup so the first visitor doesn't wait on the Hub.
try:
    load_spaces()
except Exception as _exc:  # pragma: no cover
    print(f"[hackathon-roulette] prewarm skipped: {_exc}")


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