File size: 15,485 Bytes
4acdad0
1748922
4acdad0
 
 
 
 
 
 
 
 
 
4af25eb
4acdad0
 
 
1748922
4acdad0
 
 
 
 
 
2d79140
b74fbff
 
2d79140
b74fbff
 
 
 
 
 
 
 
2d79140
b74fbff
2d79140
 
 
4acdad0
 
 
2d79140
4acdad0
 
 
 
 
 
2d79140
4acdad0
2d79140
4acdad0
 
 
 
 
 
 
 
 
2d79140
4acdad0
2d79140
4acdad0
 
 
2d79140
4acdad0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2d79140
4acdad0
 
 
 
4af25eb
2d79140
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4acdad0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2d79140
4acdad0
2d79140
4acdad0
 
 
 
 
6081210
4acdad0
 
 
4af25eb
95bb429
 
 
4acdad0
 
 
 
 
 
 
 
 
 
 
 
95bb429
 
 
 
f90e879
 
 
 
4acdad0
383b3b6
4acdad0
2d79140
4acdad0
 
 
 
 
 
 
2d79140
4acdad0
 
 
609b856
4af25eb
 
95bb429
4af25eb
 
 
 
 
 
 
 
95bb429
4af25eb
 
f90e879
 
4af25eb
 
 
 
95bb429
4af25eb
95bb429
4af25eb
609b856
4acdad0
 
2d79140
6081210
4af25eb
d4737ee
4af25eb
502964a
4acdad0
 
6081210
4acdad0
4af25eb
4acdad0
 
 
 
 
 
d4737ee
 
4af25eb
d4737ee
 
 
6081210
 
d4737ee
6081210
d4737ee
6081210
 
4acdad0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2d79140
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
import gradio as gr
from huggingface_hub import InferenceClient, HfApi
import os
import requests
from typing import List, Dict, Union
import traceback
from PIL import Image
from io import BytesIO
import asyncio
from gradio_client import Client
import time
import threading
import json

HF_TOKEN = os.getenv("HF_TOKEN")
hf_client = InferenceClient("CohereForAI/c4ai-command-r-plus-08-2024", token=HF_TOKEN)
hf_api = HfApi(token=HF_TOKEN)

def get_headers():
    if not HF_TOKEN:
        raise ValueError("Hugging Face token not found in environment variables")
    return {"Authorization": f"Bearer {HF_TOKEN}"}

def get_most_liked_spaces(limit: int = 300) -> Union[List[Dict], str]:
    url = "https://huggingface.co/api/spaces"
    params = {
        "sort": "likes",
        "direction": -1,
        "limit": limit,
        "full": "true"
    }
    
    try:
        response = requests.get(url, params=params, headers=get_headers())
        response.raise_for_status()
        return response.json()
    except requests.RequestException as e:
        return f"API request error: {str(e)}"
    except ValueError as e:
        return f"JSON decoding error: {str(e)}"

def format_space(space: Dict) -> Dict:
    space_id = space.get('id', 'Unknown')
    space_name = space_id.split('/')[-1] if '/' in space_id else space_id
    
    space_author = space.get('author', 'Unknown')
    if isinstance(space_author, dict):
        space_author = space_author.get('user', space_author.get('name', 'Unknown'))
    
    space_likes = space.get('likes', 'N/A')
    space_url = f"https://huggingface.co/spaces/{space_id}"
    
    return {
        "id": space_id,
        "name": space_name,
        "author": space_author,
        "likes": space_likes,
        "url": space_url,
    }

def format_spaces(spaces: Union[List[Dict], str]) -> List[Dict]:
    if isinstance(spaces, str):
        return [{"error": spaces}]
    
    return [format_space(space) for space in spaces if isinstance(space, dict)]

def summarize_space(space: Dict) -> str:
    system_message = "๋‹น์‹ ์€ Hugging Face Space์˜ ๋‚ด์šฉ์„ ์š”์•ฝํ•˜๋Š” AI ์กฐ์ˆ˜์ž…๋‹ˆ๋‹ค. ์ฃผ์–ด์ง„ ์ •๋ณด๋ฅผ ๋ฐ”ํƒ•์œผ๋กœ ๊ฐ„๊ฒฐํ•˜๊ณ  ๋ช…ํ™•ํ•œ ์š”์•ฝ์„ ์ œ๊ณตํ•ด์ฃผ์„ธ์š”."
    user_message = f"๋‹ค์Œ Hugging Face Space๋ฅผ ์š”์•ฝํ•ด์ฃผ์„ธ์š”: {space['name']} by {space['author']}. ์ข‹์•„์š” ์ˆ˜: {space['likes']}. URL: {space['url']}"
    
    messages = [
        {"role": "system", "content": system_message},
        {"role": "user", "content": user_message}
    ]
    
    try:
        response = hf_client.chat_completion(messages, max_tokens=400, temperature=0.7)
        return response.choices[0].message.content
    except Exception as e:
        return f"์š”์•ฝ ์ƒ์„ฑ ์ค‘ ์˜ค๋ฅ˜ ๋ฐœ์ƒ: {str(e)}"

def get_app_py_content(space_id: str) -> str:
    app_py_url = f"https://huggingface.co/spaces/{space_id}/raw/main/app.py"
    try:
        response = requests.get(app_py_url, headers=get_headers())
        if response.status_code == 200:
            return response.text  # ์ „์ฒด ๋‚ด์šฉ์„ ๋ฐ˜ํ™˜
        else:
            return f"app.py file not found or inaccessible for space: {space_id}"
    except requests.RequestException:
        return f"Error fetching app.py content for space: {space_id}"


def get_space_structure(space_id: str) -> Dict:
    try:
        # space_id์—์„œ owner์™€ repo_name์„ ๋ถ„๋ฆฌ
        owner, repo_name = space_id.split('/')
        
        # HfApi๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ ํŒŒ์ผ ๋ชฉ๋ก์„ ๊ฐ€์ ธ์˜ด
        files = hf_api.list_repo_files(repo_id=space_id, repo_type="space")
        
        # ํŒŒ์ผ ๋ชฉ๋ก์„ ํŠธ๋ฆฌ ๊ตฌ์กฐ๋กœ ๋ณ€ํ™˜
        tree = {"type": "directory", "path": "", "tree": []}
        for file in files:
            path_parts = file.split('/')
            current = tree
            for i, part in enumerate(path_parts):
                if i == len(path_parts) - 1:  # ํŒŒ์ผ
                    current["tree"].append({"type": "file", "path": part})
                else:  # ๋””๋ ‰ํ† ๋ฆฌ
                    found = False
                    for item in current["tree"]:
                        if item["type"] == "directory" and item["path"] == part:
                            current = item
                            found = True
                            break
                    if not found:
                        new_dir = {"type": "directory", "path": part, "tree": []}
                        current["tree"].append(new_dir)
                        current = new_dir
        
        return tree
    except Exception as e:
        print(f"Error in get_space_structure: {str(e)}")
        return {"error": f"API request error: {str(e)}"}

def format_tree_structure(tree_data: Dict, indent: str = "") -> str:
    formatted = ""
    for item in tree_data.get("tree", []):
        if item["type"] == "file":
            formatted += f"{indent}โ”œโ”€โ”€ {item['path']}\n"
        elif item["type"] == "directory":
            formatted += f"{indent}โ”œโ”€โ”€ {item['path']}/\n"
            formatted += format_tree_structure(item, indent + "โ”‚   ")
    return formatted

def format_list_structure(tree_data: Dict) -> List[str]:
    formatted = []
    for item in tree_data.get("tree", []):
        if item["type"] == "file":
            formatted.append(item["path"])
        elif item["type"] == "directory":
            formatted.append(f"{item['path']}/")
            formatted.extend(format_list_structure(item))
    return formatted

def on_select(space):
    try:
        print(f"Selected space: {space['name']}")
        summary = summarize_space(space)
        app_content = get_app_py_content(space['id'])
        tree_structure = get_space_structure(space['id'])
        
        info = f"์„ ํƒ๋œ Space: {space['name']} (ID: {space['id']})\n"
        info += f"Author: {space['author']}\n"
        info += f"Likes: {space['likes']}\n"
        info += f"URL: {space['url']}\n\n"
        info += f"์š”์•ฝ:\n{summary}"
        
        tree_view = format_tree_structure(tree_structure)
        list_view = "\n".join(format_list_structure(tree_structure))
        
        print(f"Returning URL: {space['url']}")
        return info, app_content, space['url'], tree_view, list_view
    except Exception as e:
        print(f"Error in on_select: {str(e)}")
        print(traceback.format_exc())
        return f"์˜ค๋ฅ˜๊ฐ€ ๋ฐœ์ƒํ–ˆ์Šต๋‹ˆ๋‹ค: {str(e)}", "", "", "", ""

def update_screenshot(url, last_url, force_update=False):
    print(f"Updating screenshot. Current URL: {url}, Last URL: {last_url}, Force update: {force_update}")
    if url and (url != last_url or force_update):
        screenshot = take_screenshot(url)
        print("Screenshot updated")
        return screenshot, url
    print("No update needed")
    return gr.update(), last_url

def refresh_screenshot(url, last_url):
    print(f"Refresh button clicked. URL: {url}, Last URL: {last_url}")
    # ํ•ญ์ƒ ๊ฐ•์ œ๋กœ ์—…๋ฐ์ดํŠธ
    return update_screenshot(url, last_url, force_update=True)

def take_screenshot(url):
    try:
        print(f"Taking screenshot of URL: {url}")
        client = Client("ginipick/selenium-screenshot-gradio")
        result = client.predict(url=url, api_name="/predict")
        print(f"Screenshot result: {result}")
        if isinstance(result, str) and os.path.exists(result):
            return Image.open(result)
        else:
            print(f"Invalid result from API: {result}")
            return Image.new('RGB', (600, 360), color='lightgray')
    except Exception as e:
        print(f"Screenshot error: {str(e)}")
        return Image.new('RGB', (600, 360), color='lightgray')

def generate_usage_guide(app_content):
    system_message = "๋‹น์‹ ์€ Python ์ฝ”๋“œ๋ฅผ ๋ถ„์„ํ•˜์—ฌ, ํ™”๋ฉด ๋ณด๋“ฏ์ด ์ด์šฉ ๋ฐฉ๋ฒ•์„ ์„ค๋ช…ํ•˜๋Š” AI ์กฐ์ˆ˜์ž…๋‹ˆ๋‹ค. app.py ์ฝ”๋“œ๋ฅผ ๋ฐ”ํƒ•์œผ๋กœ ์ฝ”๋“œ์— ๋Œ€ํ•œ ์–ธ๊ธ‰์€ ์ œ์™ธํ•˜๊ณ , ์ด์šฉ์ž ๊ด€์ ์—์„œ 1) ๊ธฐ์กด ์œ ์‚ฌ ๊ธฐ์ˆ  ๋ฐฉ์‹๊ดด ๋น„๊ตํ•ด ํŠน์ง•, ์žฅ์ ์— ๋Œ€ํ•ด ์นœ์ ˆํ•˜๊ณ  ์ž์„ธํ•˜๊ฒŒ ์ƒ์„ธํ•œ ์‚ฌ์šฉ ๋ฐฉ๋ฒ•์„ ์ œ๊ณตํ•ด์ฃผ์„ธ์š”."
    user_message = f"๋‹ค์Œ Python ์ฝ”๋“œ๋ฅผ ๊ธฐ๋ฐ˜์œผ๋กœ ํ™”๋ฉด UI/UX์  ์ธก๋ฉด์œผ๋กœ ํŠน์ง•๊ณผ ์‚ฌ์šฉ ๋ฐฉ๋ฒ•์„ ์„ค๋ช…ํ•ด์ฃผ์„ธ์š”:\n\n{app_content}"
    
    messages = [
        {"role": "system", "content": system_message},
        {"role": "user", "content": user_message}
    ]
    
    try:
        response = hf_client.chat_completion(messages, max_tokens=4000, temperature=0.7)
        return response.choices[0].message.content
    except Exception as e:
        return f"์‚ฌ์šฉ ๋ฐฉ๋ฒ• ์ƒ์„ฑ ์ค‘ ์˜ค๋ฅ˜ ๋ฐœ์ƒ: {str(e)}"

def create_ui():
    try:
        spaces_list = get_most_liked_spaces()
        formatted_spaces = format_spaces(spaces_list)
        print(f"Total spaces loaded: {len(formatted_spaces)}")

        css = """
        footer {visibility: hidden;}
        .minimal-button {min-width: 30px !important; height: 25px !important; line-height: 1 !important; font-size: 12px !important; padding: 2px 5px !important;}
        .space-row {margin-bottom: 5px !important;}
        #refresh-button, #manual-button, #open-space-button {
            width: 100% !important;
            margin-top: 5px !important;
        }
        #info-output, #usage-guide, #tree-view, #list-view {
            height: 400px !important;
            overflow-y: auto !important;
            padding-right: 10px !important;
        }
        #app-py-content {
            height: auto !important;
            max-height: none !important;
            overflow-y: visible !important;
        }
        .output-group {
            border: 1px solid #ddd;
            border-radius: 5px;
            padding: 10px;
            margin-bottom: 20px;
        }
        .scroll-lock {
            overflow: auto !important;
            max-height: 400px !important;
        }
        .full-height {
            height: auto !important;
            max-height: none !important;
        }
        """

        with gr.Blocks(css=css, theme="Nymbo/Nymbo_Theme") as demo:
            gr.Markdown("# 300: HuggingFace Most Liked Spaces")
            
            with gr.Row():
                with gr.Column(scale=1):
                    space_rows = []
                    for space in formatted_spaces:
                        with gr.Row(elem_classes="space-row") as space_row:
                            with gr.Column():
                                gr.Markdown(f"{space['name']} by {space['author']} (Likes: {space['likes']})", elem_classes="space-info")
                                button = gr.Button("ํด๋ฆญ", elem_classes="minimal-button")
                        space_rows.append((space_row, button, space))

                with gr.Column(scale=2):
                    with gr.Tabs():
                        with gr.TabItem("๊ธฐ๋ณธ ์ •๋ณด"):
                            with gr.Group(elem_classes="output-group scroll-lock"):
                                info_output = gr.Textbox(label="Space ์ •๋ณด ๋ฐ ์š”์•ฝ", elem_id="info-output", lines=20, max_lines=30)
                            url_state = gr.State("")
                            last_url_state = gr.State("")
                            
                            screenshot_output = gr.Image(type="pil", label="Live ํ™”๋ฉด", height=360, width=600)
                            refresh_button = gr.Button("๐Ÿ”„ ์„œ๋น„์Šค ํ™”๋ฉด", elem_id="refresh-button")
                            manual_button = gr.Button("์„ ํƒ ์„œ๋น„์Šค ํŠน์ง• ๋ฐ ์‚ฌ์šฉ๋ฒ•", elem_id="manual-button")
                            
                            with gr.Group(elem_classes="output-group scroll-lock"):
                                usage_guide = gr.Textbox(label="์„ ํƒ ์„œ๋น„์Šค ํŠน์ง• ๋ฐ ์‚ฌ์šฉ๋ฒ•", elem_id="usage-guide", visible=False, lines=20, max_lines=30)
                            
                            with gr.Group(elem_classes="output-group full-height"):
                                app_py_content = gr.Code(language="python", label="๋ฉ”์ธ ์†Œ์Šค์ฝ”๋“œ", elem_id="app-py-content", lines=None, max_lines=None)
                            
                            open_space_button = gr.Button("์„ ํƒํ•œ Space ์—ด๊ธฐ", elem_id="open-space-button")
                        
                        with gr.TabItem("์ฝ”๋“œ ๊ตฌ์กฐ ๋ถ„์„"):
                            with gr.Group(elem_classes="output-group scroll-lock"):
                                tree_view = gr.Textbox(label="ํŠธ๋ฆฌ ๊ตฌ์กฐ", elem_id="tree-view", lines=30, max_lines=50)
                            with gr.Group(elem_classes="output-group scroll-lock"):
                                list_view = gr.Textbox(label="๋ฆฌ์ŠคํŠธ ๊ตฌ์กฐ", elem_id="list-view", lines=30, max_lines=50)
                    
                    update_trigger = gr.Button("Update Screenshot", visible=False)


                def on_select_with_link(space):
                    info, app_content, url, tree, list_structure = on_select(space)
                    info += f"\n\n์„ ํƒํ•œ Space URL: {url}"
                    return info, app_content, url, tree, list_structure

                for _, button, space in space_rows:
                    button.click(
                        lambda s=space: on_select_with_link(s),
                        inputs=[],
                        outputs=[info_output, app_py_content, url_state, tree_view, list_view]
                    ).then(
                        update_screenshot,
                        inputs=[url_state, last_url_state],
                        outputs=[screenshot_output, last_url_state]
                    )

                def open_space_in_browser(url):
                    if url:
                        import webbrowser
                        webbrowser.open(url)
                        return f"'{url}' ์ฃผ์†Œ๊ฐ€ ์ƒˆ ํƒญ์—์„œ ์—ด๋ ธ์Šต๋‹ˆ๋‹ค."
                    return "์„ ํƒ๋œ Space๊ฐ€ ์—†์Šต๋‹ˆ๋‹ค."

                open_space_button.click(
                    open_space_in_browser,
                    inputs=[url_state],
                    outputs=[gr.Textbox(label="์ƒํƒœ ๋ฉ”์‹œ์ง€")]
                )

                refresh_button.click(
                    refresh_screenshot,
                    inputs=[url_state, last_url_state],
                    outputs=[screenshot_output, last_url_state]
                )

                def show_usage_guide(app_content):
                    usage_text = generate_usage_guide(app_content)
                    return gr.update(value=usage_text, visible=True)

                manual_button.click(
                    show_usage_guide,
                    inputs=[app_py_content],
                    outputs=[usage_guide]
                )

                update_trigger.click(
                    update_screenshot,
                    inputs=[url_state, last_url_state],
                    outputs=[screenshot_output, last_url_state]
                )

        # Start a background thread to trigger updates
        def trigger_updates():
            while True:
                time.sleep(5)
                update_trigger.click()

        threading.Thread(target=trigger_updates, daemon=True).start()

        return demo

    except Exception as e:
        print(f"Error in create_ui: {str(e)}")
        print(traceback.format_exc())
        raise

if __name__ == "__main__":
    try:
        demo = create_ui()
        demo.launch()
    except Exception as e:
        print(f"Error in main: {str(e)}")
        print(traceback.format_exc())