File size: 8,198 Bytes
3b2e7c4
8c9d551
3b2e7c4
 
f79dac7
3a0fa58
 
 
 
f79dac7
 
3b2e7c4
8849302
14aed2b
9ffe47e
3b2e7c4
9ffe47e
 
 
3a6600d
9ffe47e
 
 
 
 
 
 
 
f79dac7
 
 
 
9c9698b
f79dac7
 
 
 
8849302
 
 
f79dac7
9ffe47e
 
 
 
 
 
3a0fa58
3a6600d
9c9698b
f79dac7
9c9698b
f79dac7
 
9ffe47e
 
c5437a5
14aed2b
 
c5437a5
14aed2b
3a6600d
 
9ffe47e
 
3e40f7e
514cd38
9ffe47e
3a6600d
 
 
 
 
9ffe47e
 
 
 
 
3a6600d
9ffe47e
3a6600d
 
9ffe47e
3a6600d
 
 
9ffe47e
 
 
14aed2b
9ffe47e
 
 
 
 
 
 
3a6600d
514cd38
 
 
9ffe47e
 
 
 
6d77ca6
14aed2b
8849302
14aed2b
9ffe47e
 
 
 
 
14aed2b
 
 
9ffe47e
 
14aed2b
 
9ffe47e
09f2264
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9ffe47e
14aed2b
 
 
 
 
9ffe47e
bf508de
14aed2b
 
189b3c1
14aed2b
9ffe47e
 
09f2264
 
14aed2b
 
 
 
 
 
 
 
9ffe47e
14aed2b
 
 
 
 
9ffe47e
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
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
from pathlib import Path

# μŠ€ν¬λ¦°μƒ· μΊμ‹œ 디렉토리 μ„€μ •
CACHE_DIR = Path("screenshot_cache")
CACHE_DIR.mkdir(exist_ok=True)

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()
            
    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)
        WebDriverWait(driver, 10).until(
            EC.presence_of_element_located((By.TAG_NAME, "body"))
        )
        screenshot = driver.get_screenshot_as_png()
        
        # μΊμ‹œ 파일 μ €μž₯
        with open(cache_file, "wb") as f:
            f.write(screenshot)
            
        return base64.b64encode(screenshot).decode()
    except Exception as e:
        print(f"Screenshot error for {url}: {str(e)}")
        return None
    finally:
        if 'driver' in locals():
            driver.quit()

def get_space_card(space: dict, index: int) -> str:
    """슀페이슀 μΉ΄λ“œ HTML 생성"""
    space_id = space.get('id', '')
    author, title = space_id.split('/', 1)
    likes = format(space.get('likes', 0), ',')
    sdk = space.get('sdk', 'N/A')
    created = space.get('createdAt', '').split('T')[0]
    url = f"https://huggingface.co/spaces/{space_id}"
    
    screenshot = get_cached_screenshot(url)
    bg_color = f"rgba({random.randint(230,255)}, {random.randint(230,255)}, {random.randint(230,255)}, 0.8)"
    
    return f"""
    <div class="space-card" style='
        border: none; 
        padding: 20px; 
        margin: 10px; 
        border-radius: 15px; 
        box-shadow: 0 4px 8px rgba(0,0,0,0.1);
        background-image: linear-gradient({bg_color}, {bg_color}), 
            url(data:image/png;base64,{screenshot if screenshot else ''});
        background-size: cover;
        background-position: center;
        background-blend-mode: overlay;
        transition: transform 0.3s ease;
        min-height: 200px;'>
        
        <div style='
            background: rgba(255, 255, 255, 0.95);
            padding: 15px;
            border-radius: 10px;
            backdrop-filter: blur(5px);'>
            <div style='font-size: 1.2em; font-weight: bold; color: #333;'>#{index + 1} {title}</div>
            <p style='margin: 5px 0; color: #666;'>πŸ‘€ {author}</p>
            <p style='margin: 5px 0; color: #666;'>πŸ› οΈ {sdk}</p>
            <p style='margin: 5px 0; color: #666;'>❀️ {likes}</p>
            <p style='margin: 5px 0; color: #666;'>πŸ“… {created}</p>
            <a href='{url}' target='_blank' 
               style='display: inline-block; margin-top: 10px; padding: 5px 10px; 
                      background: #007bff; color: white; text-decoration: none; 
                      border-radius: 5px;'>
                πŸ”— View Space
            </a>
        </div>
    </div>
    """

def get_trending_spaces(progress=gr.Progress()) -> Tuple[str, str]:
    """νŠΈλ Œλ”© 슀페이슀 κ°€μ Έμ˜€κΈ°"""
    url = "https://huggingface.co/api/spaces"
    
    try:
        progress(0, desc="Fetching spaces data...")
        response = requests.get(url)
        response.raise_for_status()
        spaces = response.json()
        
        # μ’‹μ•„μš” 수둜 μ •λ ¬ν•˜κ³  μƒμœ„ 10개만 선택
        spaces.sort(key=lambda x: x.get('likes', 0), reverse=True)
        top_spaces = spaces[:10]
        
        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(top_spaces):
            author, title = space['id'].split('/', 1)
            space_url = f"https://huggingface.co/spaces/{space['id']}"
            likes = format(space.get('likes', 0), ',')
            created = space.get('createdAt', '').split('T')[0]
            
            screenshot = get_cached_screenshot(space_url)
            bg_color = f"rgba({random.randint(230,255)}, {random.randint(230,255)}, {random.randint(230,255)}, 0.8)"
            
            html_content += f"""
            <div class="space-card" style='
                position: relative;
                border: none; 
                padding: 20px; 
                margin: 10px; 
                border-radius: 15px; 
                box-shadow: 0 4px 8px rgba(0,0,0,0.1);
                background-image: linear-gradient({bg_color}, {bg_color}), 
                    url(data:image/png;base64,{screenshot if screenshot else ''});
                background-size: cover;
                background-position: center;
                background-blend-mode: overlay;
                transition: transform 0.3s ease;
                min-height: 250px;
                cursor: pointer;'
                onclick="window.open('{space_url}', '_blank')">
                
                <div style='
                    position: absolute;
                    bottom: 0;
                    left: 0;
                    right: 0;
                    background: rgba(255, 255, 255, 0.95);
                    padding: 10px;
                    border-radius: 0 0 15px 15px;
                    font-size: 0.8em;'>
                    <div style='font-size: 1.2em; font-weight: bold; color: #333; margin-bottom: 5px;'>
                        #{idx + 1} {title}
                    </div>
                    <div style='display: grid; grid-template-columns: repeat(2, 1fr); gap: 5px;'>
                        <div style='color: #666;'>πŸ‘€ {author}</div>
                        <div style='color: #666;'>πŸ› οΈ {space.get('sdk', 'N/A')}</div>
                        <div style='color: #666;'>❀️ {likes}</div>
                        <div style='color: #666;'>πŸ“… {created}</div>
                    </div>
                </div>
            </div>
            """
            
            progress((0.1 + 0.9 * idx/10), desc=f"Loading space {idx+1}/10...")
            
        html_content += "</div></div>"
        
        progress(1.0, desc="Complete!")
        return html_content, "Gallery refresh complete!"
        
    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 create_interface():
    """Gradio μΈν„°νŽ˜μ΄μŠ€ 생성"""
    with gr.Blocks(title="Hugging Face Trending Spaces") as interface:
        gr.Markdown("# πŸ€— Hugging Face Top 10 Trending Spaces")
        gr.Markdown("Shows top 10 most liked spaces on Hugging Face")
        
        with gr.Row():
            refresh_btn = gr.Button("Refresh Gallery", variant="primary")
        
        gallery_html = gr.HTML()
        status = gr.Markdown("Ready")
        
        refresh_btn.click(
            fn=get_trending_spaces,
            outputs=[gallery_html, status],
            show_progress=True
        )
        
        interface.load(
            fn=get_trending_spaces,
            outputs=[gallery_html, 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}")