File size: 30,703 Bytes
980e7a1
 
9338bc8
980e7a1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
47b5d74
980e7a1
 
0c4189b
980e7a1
 
 
 
 
 
 
 
 
0c4189b
980e7a1
 
 
 
0c4189b
980e7a1
 
 
 
 
 
 
 
 
0c4189b
980e7a1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0c4189b
 
980e7a1
 
47b5d74
980e7a1
 
 
0c4189b
980e7a1
 
 
 
 
0c4189b
980e7a1
0c4189b
980e7a1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0c4189b
980e7a1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0c4189b
980e7a1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0c4189b
980e7a1
 
0c4189b
faeec80
 
 
 
 
 
3e40f7e
980e7a1
 
1114252
 
 
980e7a1
 
 
 
 
 
 
 
 
 
 
 
 
 
1114252
 
 
51585e0
 
 
 
 
 
 
 
c9933ea
 
 
 
fbf9146
f60c972
 
 
 
ba159ad
 
 
 
 
 
 
 
 
 
 
 
b714baa
 
ba159ad
 
 
 
 
 
 
 
 
 
b714baa
 
ba159ad
 
 
 
 
 
 
 
 
 
b714baa
 
2d4a3da
e7dbb16
 
 
3127fda
 
b714baa
3127fda
ba159ad
3127fda
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
faeec80
 
ba159ad
514cd38
faeec80
9c0a3cf
3a6600d
9c0a3cf
 
 
 
 
 
 
 
 
 
faeec80
 
9c0a3cf
3a6600d
faeec80
3a6600d
9c0a3cf
 
faeec80
9c0a3cf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
faeec80
9c0a3cf
 
 
 
faeec80
9c0a3cf
 
 
faeec80
 
9c0a3cf
faeec80
3127fda
9c0a3cf
 
 
c9933ea
 
fe2f52f
 
 
9c0a3cf
 
 
 
 
 
 
 
 
fe2f52f
 
9c0a3cf
 
980e7a1
9c0a3cf
 
 
 
fe2f52f
 
 
 
 
9c0a3cf
 
fe2f52f
9c0a3cf
 
fe2f52f
9c0a3cf
 
 
3127fda
e7dbb16
3a6600d
514cd38
 
2069306
7181c87
9ffe47e
 
 
6d77ca6
14aed2b
ed53868
 
980e7a1
58eb2f8
5a88e63
f60c972
14aed2b
9ffe47e
 
8e6fe54
7181c87
8e6fe54
 
 
 
 
 
 
 
 
 
 
 
7181c87
14aed2b
980e7a1
 
 
 
14aed2b
8a4b75f
faeec80
7181c87
14aed2b
980e7a1
14aed2b
 
7181c87
9ffe47e
bf508de
14aed2b
 
189b3c1
7181c87
550cf29
 
 
 
 
8a4b75f
 
8e6fe54
8a4b75f
 
550cf29
 
 
8e6fe54
7181c87
8e6fe54
 
 
 
 
 
 
 
 
 
 
 
7181c87
550cf29
980e7a1
 
 
 
550cf29
8a4b75f
faeec80
7181c87
550cf29
980e7a1
550cf29
 
7181c87
550cf29
 
 
 
 
7181c87
550cf29
 
 
 
 
8a4b75f
 
8e6fe54
8a4b75f
 
550cf29
 
 
8e6fe54
7181c87
8e6fe54
 
 
 
 
 
 
 
 
 
 
 
7181c87
550cf29
980e7a1
 
 
 
550cf29
8a4b75f
faeec80
7181c87
550cf29
980e7a1
550cf29
 
7181c87
550cf29
 
 
 
 
7181c87
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
14aed2b
1d8e135
 
dadc7b8
1d8e135
 
 
 
8e6fe54
1d8e135
 
 
 
dadc7b8
1d8e135
dadc7b8
d702c1e
1d8e135
 
 
 
dadc7b8
1d8e135
 
 
 
 
 
 
 
 
53b3b68
c6b4030
dadc7b8
 
 
53b3b68
c6b4030
 
1d8e135
 
 
c6b4030
dadc7b8
1d8e135
 
dadc7b8
1d8e135
 
 
a4d241a
1d8e135
 
14aed2b
550cf29
 
 
1995dde
c5147b3
 
 
 
 
 
 
 
8e6fe54
 
 
 
c5147b3
 
 
 
 
 
 
550cf29
c5147b3
550cf29
 
 
1995dde
c5147b3
 
 
 
 
 
 
 
dadc7b8
c5147b3
8e6fe54
 
c5147b3
 
 
 
 
 
 
550cf29
c5147b3
550cf29
 
 
1995dde
c5147b3
 
 
 
 
 
 
 
dadc7b8
c5147b3
8e6fe54
 
c5147b3
 
 
 
 
 
 
550cf29
c5147b3
7181c87
c5147b3
550cf29
9ffe47e
7181c87
 
550cf29
 
 
 
7181c87
 
14aed2b
 
550cf29
 
7181c87
 
550cf29
 
7181c87
 
9ffe47e
7181c87
550cf29
 
7181c87
 
550cf29
7181c87
550cf29
 
7181c87
 
550cf29
7181c87
550cf29
14aed2b
7181c87
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c5147b3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
14aed2b
189b3c1
57572ee
14aed2b
 
 
 
 
 
 
 
 
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

        
import os
import random
import base64
import requests
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from selenium.common.exceptions import WebDriverException, TimeoutException
from PIL import Image
from io import BytesIO
from datetime import datetime
import gradio as gr
from typing import Tuple
import time
from pathlib import Path  # ์ถ”๊ฐ€

# ์Šคํฌ๋ฆฐ์ƒท ์บ์‹œ ๋””๋ ‰ํ† ๋ฆฌ ์„ค์ •
CACHE_DIR = Path("screenshot_cache")
CACHE_DIR.mkdir(exist_ok=True)

# ์ „์—ญ ๋ณ€์ˆ˜๋กœ ์Šคํฌ๋ฆฐ์ƒท ์บ์‹œ ์„ ์–ธ
SCREENSHOT_CACHE = {}

def get_cached_screenshot(url: str) -> str:
    """์บ์‹œ๋œ ์Šคํฌ๋ฆฐ์ƒท ๊ฐ€์ ธ์˜ค๊ธฐ ๋˜๋Š” ์ƒˆ๋กœ ์ƒ์„ฑ"""
    cache_file = CACHE_DIR / f"{base64.b64encode(url.encode()).decode()}.png"
    
    if cache_file.exists():
        with open(cache_file, "rb") as f:
            return base64.b64encode(f.read()).decode()
            
    return take_screenshot(url)
    
def take_screenshot(url):
    """์›น์‚ฌ์ดํŠธ ์Šคํฌ๋ฆฐ์ƒท ์ดฌ์˜ ํ•จ์ˆ˜ (๋กœ๋”ฉ ๋Œ€๊ธฐ ์‹œ๊ฐ„ ์ถ”๊ฐ€)"""
    if url in SCREENSHOT_CACHE:
        return SCREENSHOT_CACHE[url]
        
    if not url.startswith('http'):
        url = f"https://{url}"
        
    options = webdriver.ChromeOptions()
    options.add_argument('--headless')
    options.add_argument('--no-sandbox')
    options.add_argument('--disable-dev-shm-usage')
    options.add_argument('--window-size=1080,720')
    
    try:
        driver = webdriver.Chrome(options=options)
        driver.get(url)
        
        # ๋ช…์‹œ์  ๋Œ€๊ธฐ: body ์š”์†Œ๊ฐ€ ๋กœ๋“œ๋  ๋•Œ๊นŒ์ง€ ๋Œ€๊ธฐ (์ตœ๋Œ€ 10์ดˆ)
        try:
            WebDriverWait(driver, 10).until(
                EC.presence_of_element_located((By.TAG_NAME, "body"))
            )
        except TimeoutException:
            print(f"ํŽ˜์ด์ง€ ๋กœ๋”ฉ ํƒ€์ž„์•„์›ƒ: {url}")
        
        # ์ถ”๊ฐ€ ๋Œ€๊ธฐ ์‹œ๊ฐ„์„ 2์ดˆ๋กœ ์ฆ๊ฐ€
        time.sleep(2)  # 1์ดˆ์—์„œ 2์ดˆ๋กœ ๋ณ€๊ฒฝ
        
        # JavaScript ์‹คํ–‰ ์™„๋ฃŒ ๋Œ€๊ธฐ
        driver.execute_script("return document.readyState") == "complete"
        
        # ์Šคํฌ๋ฆฐ์ƒท ์ดฌ์˜
        screenshot = driver.get_screenshot_as_png()
        img = Image.open(BytesIO(screenshot))
        buffered = BytesIO()
        img.save(buffered, format="PNG")
        base64_image = base64.b64encode(buffered.getvalue()).decode()
        
        # ์บ์‹œ์— ์ €์žฅ
        SCREENSHOT_CACHE[url] = base64_image
        return base64_image
        
    except WebDriverException as e:
        print(f"์Šคํฌ๋ฆฐ์ƒท ์ดฌ์˜ ์‹คํŒจ: {str(e)} for URL: {url}")
        return None
    except Exception as e:
        print(f"์˜ˆ์ƒ์น˜ ๋ชปํ•œ ์˜ค๋ฅ˜: {str(e)} for URL: {url}")
        return None
    finally:
        if 'driver' in locals():
            driver.quit()

from datetime import datetime, timedelta

def calculate_rising_rate(created_date: str, rank: int) -> int:
    """AI Rising Rate ๊ณ„์‚ฐ"""
    # ์ƒ์„ฑ์ผ ๊ธฐ์ค€ ์ ์ˆ˜ ๊ณ„์‚ฐ
    created = datetime.strptime(created_date.split('T')[0], '%Y-%m-%d')
    today = datetime.now()
    days_diff = (today - created).days
    date_score = max(0, 300 - days_diff)  # ์ตœ๋Œ€ 300์ 
    
    # ์ˆœ์œ„ ๊ธฐ์ค€ ์ ์ˆ˜ ๊ณ„์‚ฐ
    rank_score = max(0, 300 - rank)  # ์ตœ๋Œ€ 300์ 
    
    # ์ด์  ๊ณ„์‚ฐ
    total_score = date_score + rank_score
    
    # ๋ณ„ ๊ฐœ์ˆ˜ ๊ณ„์‚ฐ (0~5)
    if total_score <= 100:
        stars = 1
    elif total_score <= 200:
        stars = 2
    elif total_score <= 300:
        stars = 3
    elif total_score <= 400:
        stars = 4
    else:
        stars = 5
        
    return stars

def get_popularity_grade(likes: int, stars: int) -> tuple:
    """AI Popularity Score ๋“ฑ๊ธ‰ ๊ณ„์‚ฐ"""
    # ๊ธฐ๋ณธ ์ ์ˆ˜ (likes)
    base_score = min(likes, 10000)  # ์ตœ๋Œ€ 10000์ 
    
    # ๋ณ„์  ์ถ”๊ฐ€ ์ ์ˆ˜ (๋ณ„ ํ•˜๋‚˜๋‹น 500์ )
    star_score = stars * 500
    
    # ์ด์ 
    total_score = base_score + star_score
    
    # ๋“ฑ๊ธ‰ ํ…Œ์ด๋ธ” (18๋‹จ๊ณ„)
    grades = [
        (9000, "AAA+"), (8500, "AAA"), (8000, "AAA-"),
        (7500, "AA+"), (7000, "AA"), (6500, "AA-"),
        (6000, "A+"), (5500, "A"), (5000, "A-"),
        (4500, "BBB+"), (4000, "BBB"), (3500, "BBB-"),
        (3000, "BB+"), (2500, "BB"), (2000, "BB-"),
        (1500, "B+"), (1000, "B"), (500, "B-")
    ]
    
    for threshold, grade in grades:
        if total_score >= threshold:
            return grade, total_score
            
    return "B-", total_score

# get_card ํ•จ์ˆ˜ ๋‚ด์˜ hardware_info ๋ถ€๋ถ„์„ ๋‹ค์Œ์œผ๋กœ ๊ต์ฒด:
def get_rating_info(item: dict, index: int) -> str:
    """ํ‰๊ฐ€ ์ •๋ณด HTML ์ƒ์„ฑ"""
    created = item.get('createdAt', '').split('T')[0]
    likes = int(str(item.get('likes', '0')).replace(',', ''))
    
    # AI Rising Rate ๊ณ„์‚ฐ
    stars = calculate_rising_rate(created, index + 1)
    star_html = "โ˜…" * stars + "โ˜†" * (5 - stars)  # ์ฑ„์›Œ์ง„ ๋ณ„๊ณผ ๋นˆ ๋ณ„ ์กฐํ•ฉ
    
    # AI Popularity Score ๊ณ„์‚ฐ
    grade, score = get_popularity_grade(likes, stars)
    
    # ๋“ฑ๊ธ‰๋ณ„ ์ƒ‰์ƒ ์„ค์ •
    grade_colors = {
        'AAA': '#FFD700', 'AA': '#FFA500', 'A': '#FF4500',
        'BBB': '#4169E1', 'BB': '#1E90FF', 'B': '#00BFFF'
    }
    grade_base = grade.rstrip('+-')
    grade_color = grade_colors.get(grade_base, '#666666')
    
    return f"""
    <div style='
        margin-top: 15px;
        padding: 15px;
        background: rgba(255,255,255,0.4);
        border-radius: 10px;
        font-size: 0.9em;
        box-shadow: 0 2px 10px rgba(0,0,0,0.1);'>
        <div style='
            display: grid;
            grid-template-columns: repeat(2, 1fr);
            gap: 15px;'>
            <div style='
                color: #333;
                display: flex;
                flex-direction: column;
                gap: 5px;'>
                <span style='font-weight: bold;'>AI Rising Rate:</span>
                <span style='
                    color: #FF8C00;
                    font-size: 1.4em;
                    letter-spacing: 2px;
                    text-shadow: 1px 1px 2px rgba(0,0,0,0.1);'>{star_html}</span>
            </div>
            <div style='
                color: #333;
                display: flex;
                flex-direction: column;
                gap: 5px;'>
                <span style='font-weight: bold;'>AI Popularity Score:</span>
                <span style='
                    font-size: 1.2em;
                    font-weight: bold;
                    color: {grade_color};
                    text-shadow: 1px 1px 2px rgba(0,0,0,0.1);'>{grade} ({score:,})</span>
            </div>
        </div>
    </div>
    """

def get_hardware_info(item: dict) -> tuple:
    """ํ•˜๋“œ์›จ์–ด ์ •๋ณด ์ถ”์ถœ"""
    try:
        # runtime ์ •๋ณด ํ™•์ธ
        runtime = item.get('runtime', {})
        
        # CPU ์ •๋ณด ์ฒ˜๋ฆฌ
        cpu_info = runtime.get('cpu', 'Standard')
        
        # GPU ์ •๋ณด ์ฒ˜๋ฆฌ
        gpu_info = "None"
        if runtime.get('accelerator') == "gpu":
            gpu_type = runtime.get('gpu', {}).get('name', '')
            gpu_memory = runtime.get('gpu', {}).get('memory', '')
            if gpu_type:
                gpu_info = f"{gpu_type}"
                if gpu_memory:
                    gpu_info += f" ({gpu_memory}GB)"
        
        # spaces decorator ํ™•์ธ
        if '@spaces.GPU' in str(item.get('sdk_version', '')):
            if gpu_info == "None":
                gpu_info = "GPU Enabled"
        
        # SDK ์ •๋ณด ์ฒ˜๋ฆฌ
        sdk = item.get('sdk', 'N/A')
        
        print(f"Debug - Runtime Info: {runtime}")  # ๋””๋ฒ„๊ทธ ์ถœ๋ ฅ
        print(f"Debug - GPU Info: {gpu_info}")    # ๋””๋ฒ„๊ทธ ์ถœ๋ ฅ
        
        return cpu_info, gpu_info, sdk
        
    except Exception as e:
        print(f"Error parsing hardware info: {str(e)}")
        return 'Standard', 'None', 'N/A'

def get_card(item: dict, index: int, card_type: str = "space") -> str:
    """ํ†ตํ•ฉ ์นด๋“œ HTML ์ƒ์„ฑ"""
    item_id = item.get('id', '')
    author, title = item_id.split('/', 1)
    likes = format(item.get('likes', 0), ',')
    created = item.get('createdAt', '').split('T')[0]
    
    # short_description ๊ฐ€์ ธ์˜ค๊ธฐ
    short_description = item.get('cardData', {}).get('short_description', '')
    
    # title๊ณผ short_description์„ ํฌํ•จํ•œ ํ—ค๋” HTML
    title_html = f"""
        <h3 style='
            margin: 0 0 15px 0;
            color: #333;
            font-size: 1.3em;
            line-height: 1.4;
            display: -webkit-box;
            -webkit-line-clamp: 2;
            -webkit-box-orient: vertical;
            overflow: hidden;
            text-overflow: ellipsis;
            text-shadow: 1px 1px 1px rgba(255,255,255,0.8);'>
            {title}
            {f'<span style="display: block; font-size: 0.7em; color: #666; margin-top: 5px; font-weight: normal; font-style: italic;">{short_description}</span>' if short_description else ''}
        </h3>
    """

    
    # URL ์ •์˜
    if card_type == "space":
        url = f"https://huggingface.co/spaces/{item_id}"
    elif card_type == "model":
        url = f"https://huggingface.co/{item_id}"
    else:  # dataset
        url = f"https://huggingface.co/datasets/{item_id}"
    
    # ๋ฉ”ํƒ€๋ฐ์ดํ„ฐ ์ฒ˜๋ฆฌ
    tags = item.get('tags', [])
    pipeline_tag = item.get('pipeline_tag', '')
    license = item.get('license', '')
    sdk = item.get('sdk', 'N/A')

    # AI Rating ์ •๋ณด ๊ฐ€์ ธ์˜ค๊ธฐ
    rating_info = get_rating_info(item, index)

    # ์นด๋“œ ํƒ€์ž…๋ณ„ ๊ทธ๋ผ๋ฐ์ด์…˜ ์„ค์ •
    if card_type == "space":
        gradient_colors = """
            rgba(255, 182, 193, 0.7),    /* ํŒŒ์Šคํ…” ํ•‘ํฌ */
            rgba(173, 216, 230, 0.7),    /* ํŒŒ์Šคํ…” ๋ธ”๋ฃจ */
            rgba(255, 218, 185, 0.7)     /* ํŒŒ์Šคํ…” ํ”ผ์น˜ */
        """
        bg_content = f"""
            background-image: url(data:image/png;base64,{get_cached_screenshot(url) if get_cached_screenshot(url) else ''});
            background-size: cover;
            background-position: center;
        """
        type_icon = "๐ŸŽฏ"
        type_label = "SPACE"
    elif card_type == "model":
        gradient_colors = """
            rgba(110, 142, 251, 0.7),    /* ๋ชจ๋ธ ๋ธ”๋ฃจ */
            rgba(130, 158, 251, 0.7),
            rgba(150, 174, 251, 0.7)
        """
        bg_content = f"""
            background: linear-gradient(135deg, #6e8efb, #4a6cf7);
            padding: 15px;
        """
        type_icon = "๐Ÿค–"
        type_label = "MODEL"
    else:  # dataset
        gradient_colors = """
            rgba(255, 107, 107, 0.7),    /* ๋ฐ์ดํ„ฐ์…‹ ๋ ˆ๋“œ */
            rgba(255, 127, 127, 0.7),
            rgba(255, 147, 147, 0.7)
        """
        bg_content = f"""
            background: linear-gradient(135deg, #ff6b6b, #ff8787);
            padding: 15px;
        """
        type_icon = "๐Ÿ“Š"
        type_label = "DATASET"

    content_bg = f"""
        background: linear-gradient(135deg, {gradient_colors});
        backdrop-filter: blur(10px);
    """


    # ํƒœ๊ทธ ํ‘œ์‹œ (models์™€ datasets์šฉ)
    tags_html = ""
    if card_type != "space":
        tags_html = f"""
        <div style='
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            display: flex;
            flex-wrap: wrap;
            gap: 5px;
            justify-content: center;
            width: 90%;'>
            {' '.join([f'''
                <span style='
                    background: rgba(255,255,255,0.2);
                    padding: 5px 10px;
                    border-radius: 15px;
                    color: white;
                    font-size: 0.8em;'>
                    #{tag}
                </span>
            ''' for tag in tags[:5]])}
        </div>
        """

    # ์นด๋“œ HTML ๋ฐ˜ํ™˜
    return f"""
    <div class="card" style='
        position: relative;
        border: none; 
        padding: 0;
        margin: 10px;
        border-radius: 20px;
        box-shadow: 0 10px 20px rgba(0,0,0,0.1);
        background: white;
        transition: all 0.3s ease;
        overflow: hidden;
        min-height: 400px;
        cursor: pointer;
        transform-origin: center;'
        onmouseover="this.style.transform='scale(0.98) translateY(5px)'; this.style.boxShadow='0 5px 15px rgba(0,0,0,0.2)';"
        onmouseout="this.style.transform='scale(1) translateY(0)'; this.style.boxShadow='0 10px 20px rgba(0,0,0,0.1)';"
        onclick="window.open('{url}', '_blank')">
        
        <!-- ์ƒ๋‹จ ์˜์—ญ -->
        <div style='
            width: 100%;
            height: 200px;
            {bg_content}
            position: relative;'>
            
            <!-- ์ˆœ์œ„ ๋ฑƒ์ง€ -->
            <div style='
                position: absolute;
                top: 10px;
                left: 10px;
                background: rgba(0,0,0,0.7);
                color: white;
                padding: 5px 15px;
                border-radius: 20px;
                font-weight: bold;
                font-size: 0.9em;
                backdrop-filter: blur(5px);'>
                #{index + 1}
            </div>
            
            <!-- ํƒ€์ž… ๋ฑƒ์ง€ -->
            <div style='
                position: absolute;
                top: 10px;
                right: 10px;
                background: rgba(255,255,255,0.9);
                padding: 5px 15px;
                border-radius: 20px;
                font-weight: bold;
                font-size: 0.8em;'>
                {type_icon} {type_label}
            </div>

            {tags_html}
        </div>
        
        <!-- ์ฝ˜ํ…์ธ  ์˜์—ญ -->
        <div style='
            padding: 20px;
            {content_bg}
            border-radius: 0 0 20px 20px;
            border-top: 1px solid rgba(255,255,255,0.5);'>
            <h3 style='
                margin: 0 0 15px 0;
                color: #333;
                font-size: 1.3em;
                line-height: 1.4;
                display: -webkit-box;
                -webkit-line-clamp: 2;
                -webkit-box-orient: vertical;
                overflow: hidden;
                text-overflow: ellipsis;
                text-shadow: 1px 1px 1px rgba(255,255,255,0.8);'>
                {title}
            </h3>
            
            <div style='
                display: grid;
                grid-template-columns: repeat(2, 1fr);
                gap: 10px;
                font-size: 0.9em;
                background: rgba(255,255,255,0.3);
                padding: 10px;
                border-radius: 10px;'>
                <div style='color: #444;'>
                    <span style='margin-right: 5px;'>๐Ÿ‘ค</span> {author}
                </div>
                <div style='color: #444;'>
                    <span style='margin-right: 5px;'>โค๏ธ</span> {likes}
                </div>
                <div style='color: #444; grid-column: span 2;'>
                    <span style='margin-right: 5px;'>๐Ÿ“…</span> {created}
                </div>
            </div>

            {rating_info}
        </div>
    </div>
    """

def get_trending_spaces(search_query="", sort_by="rank", progress=gr.Progress()) -> Tuple[str, str]:
    """ํŠธ๋ Œ๋”ฉ ์ŠคํŽ˜์ด์Šค ๊ฐ€์ ธ์˜ค๊ธฐ"""
    url = "https://huggingface.co/api/spaces"
    
    try:
        progress(0, desc="Fetching spaces data...")
        params = {
            'full': 'true',
            'limit': 100
        }

        response = requests.get(url, params=params)
        response.raise_for_status()
        spaces = response.json()
        
        # ๊ฒ€์ƒ‰์–ด๋กœ ํ•„ํ„ฐ๋ง
        if search_query:
            spaces = [space for space in spaces if search_query.lower() in 
                     (space.get('id', '') + ' ' + space.get('title', '')).lower()]
        
        # ์ •๋ ฌ
        sort_by = sort_by.lower()
        if sort_by == "rising_rate":
            spaces.sort(key=lambda x: calculate_rising_rate(x.get('createdAt', ''), 0), reverse=True)
        elif sort_by == "popularity":
            spaces.sort(key=lambda x: get_popularity_grade(
                int(str(x.get('likes', '0')).replace(',', '')),
                calculate_rising_rate(x.get('createdAt', ''), 0))[1],
                reverse=True)
        
        progress(0.1, desc="Creating gallery...")
        html_content = """
        <div style='padding: 20px; background: #f5f5f5;'>
            <div style='display: grid; grid-template-columns: repeat(auto-fill, minmax(300px, 1fr)); gap: 20px;'>
        """
        
        for idx, space in enumerate(spaces):
            html_content += get_card(space, idx, "space")
            progress((0.1 + 0.9 * idx/len(spaces)), desc=f"Loading space {idx+1}/{len(spaces)}...")
            
        html_content += "</div></div>"
        
        progress(1.0, desc="Complete!")
        return html_content, f"Found {len(spaces)} spaces"
        
    except Exception as e:
        error_html = f'<div style="color: red; padding: 20px;">Error: {str(e)}</div>'
        return error_html, f"Error: {str(e)}"

def get_models(search_query="", sort_by="rank", progress=gr.Progress()) -> Tuple[str, str]:
    """์ธ๊ธฐ ๋ชจ๋ธ ๊ฐ€์ ธ์˜ค๊ธฐ"""
    url = "https://huggingface.co/api/models"
    
    try:
        progress(0, desc="Fetching models data...")
        params = {
            'full': 'true',
            'limit': 300
        }
        response = requests.get(url, params=params)
        response.raise_for_status()
        models = response.json()
        
        # ๊ฒ€์ƒ‰์–ด๋กœ ํ•„ํ„ฐ๋ง
        if search_query:
            models = [model for model in models if search_query.lower() in 
                     (model.get('id', '') + ' ' + model.get('title', '')).lower()]
        
        # ์ •๋ ฌ
        sort_by = sort_by.lower()
        if sort_by == "rising_rate":
            models.sort(key=lambda x: calculate_rising_rate(x.get('createdAt', ''), 0), reverse=True)
        elif sort_by == "popularity":
            models.sort(key=lambda x: get_popularity_grade(
                int(str(x.get('likes', '0')).replace(',', '')),
                calculate_rising_rate(x.get('createdAt', ''), 0))[1],
                reverse=True)
        
        progress(0.1, desc="Creating gallery...")
        html_content = """
        <div style='padding: 20px; background: #f5f5f5;'>
            <div style='display: grid; grid-template-columns: repeat(auto-fill, minmax(300px, 1fr)); gap: 20px;'>
        """
        
        for idx, model in enumerate(models):
            html_content += get_card(model, idx, "model")
            progress((0.1 + 0.9 * idx/len(models)), desc=f"Loading model {idx+1}/{len(models)}...")
            
        html_content += "</div></div>"
        
        progress(1.0, desc="Complete!")
        return html_content, f"Found {len(models)} models"
        
    except Exception as e:
        error_html = f'<div style="color: red; padding: 20px;">Error: {str(e)}</div>'
        return error_html, f"Error: {str(e)}"

def get_datasets(search_query="", sort_by="rank", progress=gr.Progress()) -> Tuple[str, str]:
    """์ธ๊ธฐ ๋ฐ์ดํ„ฐ์…‹ ๊ฐ€์ ธ์˜ค๊ธฐ"""
    url = "https://huggingface.co/api/datasets"
    
    try:
        progress(0, desc="Fetching datasets data...")
        params = {
            'full': 'true',
            'limit': 300
        }
        response = requests.get(url, params=params)
        response.raise_for_status()
        datasets = response.json()
        
        # ๊ฒ€์ƒ‰์–ด๋กœ ํ•„ํ„ฐ๋ง
        if search_query:
            datasets = [dataset for dataset in datasets if search_query.lower() in 
                       (dataset.get('id', '') + ' ' + dataset.get('title', '')).lower()]
        
        # ์ •๋ ฌ
        sort_by = sort_by.lower()
        if sort_by == "rising_rate":
            datasets.sort(key=lambda x: calculate_rising_rate(x.get('createdAt', ''), 0), reverse=True)
        elif sort_by == "popularity":
            datasets.sort(key=lambda x: get_popularity_grade(
                int(str(x.get('likes', '0')).replace(',', '')),
                calculate_rising_rate(x.get('createdAt', ''), 0))[1],
                reverse=True)
        
        progress(0.1, desc="Creating gallery...")
        html_content = """
        <div style='padding: 20px; background: #f5f5f5;'>
            <div style='display: grid; grid-template-columns: repeat(auto-fill, minmax(300px, 1fr)); gap: 20px;'>
        """
        
        for idx, dataset in enumerate(datasets):
            html_content += get_card(dataset, idx, "dataset")
            progress((0.1 + 0.9 * idx/len(datasets)), desc=f"Loading dataset {idx+1}/{len(datasets)}...")
            
        html_content += "</div></div>"
        
        progress(1.0, desc="Complete!")
        return html_content, f"Found {len(datasets)} datasets"
        
    except Exception as e:
        error_html = f'<div style="color: red; padding: 20px;">Error: {str(e)}</div>'
        return error_html, f"Error: {str(e)}"

# ์ •๋ ฌ ํ•จ์ˆ˜ ์ถ”๊ฐ€
def sort_items(items, sort_by):
    if sort_by == "rank":
        return items  # ์ด๋ฏธ ์ˆœ์œ„๋Œ€๋กœ ์ •๋ ฌ๋˜์–ด ์žˆ์Œ
    elif sort_by == "rising_rate":
        return sorted(items, key=lambda x: calculate_rising_rate(x.get('createdAt', ''), 0), reverse=True)
    elif sort_by == "popularity":
        return sorted(items, key=lambda x: get_popularity_grade(int(str(x.get('likes', '0')).replace(',', '')), 
                     calculate_rising_rate(x.get('createdAt', ''), 0))[1], reverse=True)
    return items

# API ํ˜ธ์ถœ ํ•จ์ˆ˜ ์ˆ˜์ •
def fetch_items(item_type, search_query="", sort_by="rank", limit=1000):
    """์•„์ดํ…œ ๊ฐ€์ ธ์˜ค๊ธฐ (spaces/models/datasets)"""
    base_url = f"https://huggingface.co/api/{item_type}"
    params = {
        'full': 'true',
        'limit': limit,
        'search': search_query
    }
    
    try:
        response = requests.get(base_url, params=params)
        response.raise_for_status()
        items = response.json()
        
        # ๊ฒ€์ƒ‰์–ด๋กœ ํ•„ํ„ฐ๋ง
        if search_query:
            items = [item for item in items if search_query.lower() in 
                    (item.get('id', '') + item.get('title', '')).lower()]
        
        # ์ •๋ ฌ
        items = sort_items(items, sort_by)
        
        return items[:300]  # ์ƒ์œ„ 300๊ฐœ๋งŒ ๋ฐ˜ํ™˜
    except Exception as e:
        print(f"Error fetching items: {e}")
        return []

def create_interface():
    with gr.Blocks(title="HuggingFace Trending Board", css="""
        .search-sort-container { 
            background: linear-gradient(135deg, rgba(255,255,255,0.95), rgba(240,240,255,0.95));
            border-radius: 15px;
            padding: 20px;
            margin: 10px 0;
            box-shadow: 0 4px 6px rgba(0,0,0,0.1);
            overflow: visible;
        }
        .search-box { 
            border: 2px solid #e1e1e1;
            border-radius: 10px;
            padding: 12px;
            transition: all 0.3s ease;
            background: linear-gradient(135deg, #ffffff, #f8f9ff);
            width: 100%;
        }
        .search-box:focus { 
            border-color: #7b61ff;
            box-shadow: 0 0 0 2px rgba(123,97,255,0.2);
            background: linear-gradient(135deg, #ffffff, #f0f3ff);
        }
        .refresh-btn {
            background: linear-gradient(135deg, #7b61ff, #6366f1);
            color: white;
            border: none;
            padding: 10px 20px;
            border-radius: 10px;
            cursor: pointer;
            transition: all 0.3s ease;
            width: 120px;
            height: 80px !important;
            display: flex;
            align-items: center;
            justify-content: center;
            margin-left: auto;
            font-size: 1.2em !important;
            box-shadow: 0 4px 6px rgba(0,0,0,0.1);
        }
        .refresh-btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 6px 12px rgba(0,0,0,0.2);
            background: linear-gradient(135deg, #8b71ff, #7376f1);
        }
    """) as interface:
        
        gr.Markdown("""
            # ๐Ÿค— HuggingFace Trending TOP 300 Board
            <div style='margin-bottom: 20px; padding: 10px; background: linear-gradient(135deg, rgba(123,97,255,0.1), rgba(99,102,241,0.1)); border-radius: 10px;'>
                Explore, search, and sort through the Shows Top 300 Trending spaces with AI Ratings
            </div>
        """)
        
        with gr.Tabs() as tabs:
            # Spaces ํƒญ
            with gr.Tab("๐ŸŽฏ Trending Spaces"):
                with gr.Row(elem_classes="search-sort-container"):
                    with gr.Column(scale=2):
                        spaces_search = gr.Textbox(
                            label="๐Ÿ” Search Spaces",
                            placeholder="Enter keywords to search...",
                            elem_classes="search-box"
                        )
                    with gr.Column(scale=2):
                        spaces_sort = gr.Radio(
                            choices=["rank", "rising_rate", "popularity"],
                            value="rank",
                            label="Sort by",
                            interactive=True
                        )
                    with gr.Column(scale=1):
                        spaces_refresh_btn = gr.Button(
                            "๐Ÿ”„ Refresh",
                            variant="primary",
                            elem_classes="refresh-btn"
                        )
                spaces_gallery = gr.HTML()
                spaces_status = gr.Markdown("Loading...")
            
            # Models ํƒญ
            with gr.Tab("๐Ÿค– Trending Models"):
                with gr.Row(elem_classes="search-sort-container"):
                    with gr.Column(scale=2):
                        models_search = gr.Textbox(
                            label="๐Ÿ” Search Models",
                            placeholder="Enter keywords to search...",
                            elem_classes="search-box"
                        )
                    with gr.Column(scale=2):
                        models_sort = gr.Radio(
                            choices=["rank", "rising_rate", "popularity"],
                            value="rank",
                            label="Sort by",
                            interactive=True
                        )
                    with gr.Column(scale=1):
                        models_refresh_btn = gr.Button(
                            "๐Ÿ”„ Refresh",
                            variant="primary",
                            elem_classes="refresh-btn"
                        )
                models_gallery = gr.HTML()
                models_status = gr.Markdown("Loading...")
            
            # Datasets ํƒญ
            with gr.Tab("๐Ÿ“Š Trending Datasets"):
                with gr.Row(elem_classes="search-sort-container"):
                    with gr.Column(scale=2):
                        datasets_search = gr.Textbox(
                            label="๐Ÿ” Search Datasets",
                            placeholder="Enter keywords to search...",
                            elem_classes="search-box"
                        )
                    with gr.Column(scale=2):
                        datasets_sort = gr.Radio(
                            choices=["rank", "rising_rate", "popularity"],
                            value="rank",
                            label="Sort by",
                            interactive=True
                        )
                    with gr.Column(scale=1):
                        datasets_refresh_btn = gr.Button(
                            "๐Ÿ”„ Refresh",
                            variant="primary",
                            elem_classes="refresh-btn"
                        )
                datasets_gallery = gr.HTML()
                datasets_status = gr.Markdown("Loading...")

        # Event handlers
        spaces_refresh_btn.click(
            fn=get_trending_spaces,
            inputs=[spaces_search, spaces_sort],
            outputs=[spaces_gallery, spaces_status]
        )
        
        models_refresh_btn.click(
            fn=get_models,
            inputs=[models_search, models_sort],
            outputs=[models_gallery, models_status]
        )
        
        datasets_refresh_btn.click(
            fn=get_datasets,
            inputs=[datasets_search, datasets_sort],
            outputs=[datasets_gallery, datasets_status]
        )
        
        # ๊ฒ€์ƒ‰์–ด ๋ณ€๊ฒฝ ์‹œ ์ž๋™ ์ƒˆ๋กœ๊ณ ์นจ
        spaces_search.change(
            fn=get_trending_spaces,
            inputs=[spaces_search, spaces_sort],
            outputs=[spaces_gallery, spaces_status]
        )
        
        models_search.change(
            fn=get_models,
            inputs=[models_search, models_sort],
            outputs=[models_gallery, models_status]
        )
        
        datasets_search.change(
            fn=get_datasets,
            inputs=[datasets_search, datasets_sort],
            outputs=[datasets_gallery, datasets_status]
        )
        
        # ์ •๋ ฌ ๋ฐฉ์‹ ๋ณ€๊ฒฝ ์‹œ ์ž๋™ ์ƒˆ๋กœ๊ณ ์นจ
        spaces_sort.change(
            fn=get_trending_spaces,
            inputs=[spaces_search, spaces_sort],
            outputs=[spaces_gallery, spaces_status]
        )
        
        models_sort.change(
            fn=get_models,
            inputs=[models_search, models_sort],
            outputs=[models_gallery, models_status]
        )
        
        datasets_sort.change(
            fn=get_datasets,
            inputs=[datasets_search, datasets_sort],
            outputs=[datasets_gallery, datasets_status]
        )

        # ์ดˆ๊ธฐ ๋ฐ์ดํ„ฐ ๋กœ๋“œ
        interface.load(
            fn=get_trending_spaces,
            inputs=[spaces_search, spaces_sort],
            outputs=[spaces_gallery, spaces_status]
        )
        interface.load(
            fn=get_models,
            inputs=[models_search, models_sort],
            outputs=[models_gallery, models_status]
        )
        interface.load(
            fn=get_datasets,
            inputs=[datasets_search, datasets_sort],
            outputs=[datasets_gallery, datasets_status]
        )

    return interface

if __name__ == "__main__":
    try:
        demo = create_interface()
        demo.launch(
            share=True,
            inbrowser=True,
            show_api=False
        )
    except Exception as e:
        print(f"Error launching app: {e}")