File size: 5,124 Bytes
5b8a14c
 
 
b9f48c0
5348754
b9f48c0
5cfddce
62d25a6
240c790
 
 
5b8a14c
 
 
240c790
 
 
 
 
b9f48c0
62d25a6
 
 
 
 
 
 
 
b9f48c0
240c790
b9f48c0
 
 
 
 
 
 
 
 
 
 
62d25a6
b9f48c0
 
 
 
 
 
 
 
 
 
 
 
5233d34
b9f48c0
 
 
be1618e
b9f48c0
 
 
62d25a6
 
 
b9f48c0
 
62d25a6
be1618e
 
 
 
 
 
 
 
 
 
 
5b8a14c
 
 
 
 
 
 
 
62d25a6
5b8a14c
 
62d25a6
5b8a14c
 
 
5348754
5b8a14c
 
 
fb59e81
5b8a14c
 
be1618e
 
 
 
 
 
5b8a14c
be1618e
 
5b8a14c
 
be1618e
5cfddce
be1618e
 
 
 
 
 
 
 
5cfddce
 
be1618e
5cfddce
5348754
be1618e
 
5b8a14c
 
5233d34
62d25a6
5b8a14c
 
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
import gradio as gr
from huggingface_hub import InferenceClient
import os
import requests
from typing import List, Dict, Union
import concurrent.futures
import traceback

# ํ™˜๊ฒฝ ๋ณ€์ˆ˜์—์„œ ํ† ํฐ ๊ฐ€์ ธ์˜ค๊ธฐ
HF_TOKEN = os.getenv("HF_TOKEN")

# ์ถ”๋ก  API ํด๋ผ์ด์–ธํŠธ ์„ค์ •
hf_client = InferenceClient("CohereForAI/c4ai-command-r-plus-08-2024", 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 = 100) -> 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()
        data = response.json()
        
        if isinstance(data, list):
            return data
        else:
            return f"Unexpected API response format: {type(data)}"
    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}]
    
    with concurrent.futures.ThreadPoolExecutor(max_workers=10) as executor:
        return list(executor.map(format_space, spaces))

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 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}
    ]
    
    response = hf_client.chat_completion(messages, max_tokens=150, temperature=0.7)
    return response.choices[0].message.content

def create_ui():
    spaces_list = get_most_liked_spaces()
    formatted_spaces = format_spaces(spaces_list)
    print(f"Total spaces loaded: {len(formatted_spaces)}")  # ๋””๋ฒ„๊น… ์ถœ๋ ฅ

    with gr.Blocks() as demo:
        gr.Markdown("# Hugging Face Most Liked Spaces")
        
        with gr.Row():
            with gr.Column(scale=1):
                space_buttons = []
                for space in formatted_spaces:
                    with gr.Row():
                        gr.Markdown(f"{space['name']} by {space['author']} (Likes: {space['likes']})")
                        button = gr.Button("ํด๋ฆญ", elem_id=f"btn-{space['id']}")
                        space_buttons.append(button)
            
            with gr.Column(scale=1):
                info_output = gr.Textbox(label="Space ์ •๋ณด ๋ฐ ์š”์•ฝ", lines=10)
                app_py_content = gr.Code(language="python", label="app.py ๋‚ด์šฉ")

        def on_select(space):
            try:
                summary = summarize_space(space)
                app_content = get_app_py_content(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}"
                return info, app_content
            except Exception as e:
                print(f"Error in on_select: {str(e)}")
                print(traceback.format_exc())
                return f"์˜ค๋ฅ˜๊ฐ€ ๋ฐœ์ƒํ–ˆ์Šต๋‹ˆ๋‹ค: {str(e)}", ""

        for button, space in zip(space_buttons, formatted_spaces):
            button.click(on_select, inputs=[gr.State(space)], outputs=[info_output, app_py_content])

    return demo

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