ginipick commited on
Commit
7cb753c
·
verified ·
1 Parent(s): cdde9f2

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +195 -0
app.py ADDED
@@ -0,0 +1,195 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ from huggingface_hub import InferenceClient
3
+ import os
4
+ import requests
5
+ from typing import List, Dict, Union
6
+ import concurrent.futures
7
+ import base64
8
+ import traceback
9
+
10
+ # 환경 변수에서 토큰 가져오기
11
+ HF_TOKEN = os.getenv("HF_TOKEN")
12
+
13
+ # 추론 API 클라이언트 설정
14
+ hf_client = InferenceClient("CohereForAI/c4ai-command-r-plus-08-2024", token=HF_TOKEN)
15
+
16
+ def get_headers():
17
+ if not HF_TOKEN:
18
+ raise ValueError("Hugging Face token not found in environment variables")
19
+ return {"Authorization": f"Bearer {HF_TOKEN}"}
20
+
21
+ def get_most_liked_spaces(limit: int = 100) -> Union[List[Dict], str]:
22
+ url = "https://huggingface.co/api/spaces"
23
+ params = {
24
+ "sort": "likes",
25
+ "direction": -1,
26
+ "limit": limit,
27
+ "full": "true"
28
+ }
29
+
30
+ try:
31
+ response = requests.get(url, params=params, headers=get_headers())
32
+ response.raise_for_status()
33
+ data = response.json()
34
+
35
+ if isinstance(data, list):
36
+ return data
37
+ else:
38
+ return f"Unexpected API response format: {type(data)}"
39
+ except requests.RequestException as e:
40
+ return f"API request error: {str(e)}"
41
+ except ValueError as e:
42
+ return f"JSON decoding error: {str(e)}"
43
+
44
+ def capture_thumbnail(space_id: str) -> str:
45
+ screenshot_url = f"https://huggingface.co/spaces/{space_id}/screenshot.jpg"
46
+ try:
47
+ response = requests.get(screenshot_url, headers=get_headers())
48
+ if response.status_code == 200:
49
+ return base64.b64encode(response.content).decode('utf-8')
50
+ except requests.RequestException:
51
+ pass
52
+ return ""
53
+
54
+ def get_app_py_content(space_id: str) -> str:
55
+ app_py_url = f"https://huggingface.co/spaces/{space_id}/raw/main/app.py"
56
+ try:
57
+ response = requests.get(app_py_url, headers=get_headers())
58
+ if response.status_code == 200:
59
+ return response.text
60
+ else:
61
+ return f"app.py file not found or inaccessible for space: {space_id}"
62
+ except requests.RequestException:
63
+ return f"Error fetching app.py content for space: {space_id}"
64
+
65
+ def format_space(space: Dict) -> Dict:
66
+ space_id = space.get('id', 'Unknown')
67
+ space_name = space_id.split('/')[-1] if '/' in space_id else space_id
68
+
69
+ space_author = space.get('author', 'Unknown')
70
+ if isinstance(space_author, dict):
71
+ space_author = space_author.get('user', space_author.get('name', 'Unknown'))
72
+
73
+ space_likes = space.get('likes', 'N/A')
74
+ space_url = f"https://huggingface.co/spaces/{space_id}"
75
+
76
+ thumbnail = capture_thumbnail(space_id)
77
+
78
+ return {
79
+ "id": space_id,
80
+ "name": space_name,
81
+ "author": space_author,
82
+ "likes": space_likes,
83
+ "url": space_url,
84
+ "thumbnail": thumbnail
85
+ }
86
+
87
+ def format_spaces(spaces: Union[List[Dict], str]) -> List[Dict]:
88
+ if isinstance(spaces, str):
89
+ return [{"error": spaces}]
90
+
91
+ with concurrent.futures.ThreadPoolExecutor(max_workers=10) as executor:
92
+ return list(executor.map(format_space, spaces))
93
+
94
+ def summarize_space(space: Dict) -> str:
95
+ system_message = "당신은 Hugging Face Space의 내용을 요약하는 AI 조수입니다. 주어진 정보를 바탕으로 간결하고 명확한 요약을 제공해주세요."
96
+ user_message = f"다음 Hugging Face Space를 요약해주세요: {space['name']} by {space['author']}. 좋아요 수: {space['likes']}. URL: {space['url']}"
97
+
98
+ messages = [
99
+ {"role": "system", "content": system_message},
100
+ {"role": "user", "content": user_message}
101
+ ]
102
+
103
+ response = hf_client.chat_completion(messages, max_tokens=150, temperature=0.7)
104
+ return response.choices[0].message.content
105
+
106
+ def create_ui():
107
+ spaces_list = get_most_liked_spaces()
108
+ formatted_spaces = format_spaces(spaces_list)
109
+ print(f"Total spaces loaded: {len(formatted_spaces)}") # 디버깅 출력
110
+
111
+ space_choices = {f"{space['name']} by {space['author']} (Likes: {space['likes']})": space['id'] for space in formatted_spaces}
112
+
113
+ with gr.Blocks(css="#space-list { height: 400px; overflow-y: auto; }") as demo:
114
+ gr.Markdown("# Hugging Face Most Liked Spaces")
115
+
116
+ with gr.Row():
117
+ with gr.Column(scale=1):
118
+ with gr.Box(elem_id="space-list"):
119
+ for space in formatted_spaces:
120
+ with gr.Row():
121
+ gr.Radio(
122
+ choices=[f"{space['name']} by {space['author']} (Likes: {space['likes']})"],
123
+ label="",
124
+ value=None,
125
+ name=space['id']
126
+ )
127
+ gr.Button("🔗", elem_id=f"link-{space['id']}")
128
+ summarize_btn = gr.Button("요약")
129
+
130
+ with gr.Column(scale=2):
131
+ output = gr.Textbox(label="Space 정보", lines=10)
132
+ app_py_content = gr.Code(language="python", label="app.py 내용")
133
+
134
+ def on_select(choice):
135
+ try:
136
+ print(f"Selected: {choice}") # 디버깅 출력
137
+ selected_id = space_choices[choice]
138
+ selected_space = next((space for space in formatted_spaces if space['id'] == selected_id), None)
139
+ if selected_space:
140
+ app_content = get_app_py_content(selected_id)
141
+ print(f"Selected space: {selected_space['name']} (ID: {selected_id})") # 디버깅 출력
142
+ return f"선택된 Space: {selected_space['name']} (ID: {selected_id})\nURL: {selected_space['url']}", app_content
143
+ else:
144
+ print(f"Space not found for ID: {selected_id}") # 디버깅 출력
145
+ return "선택된 space를 찾을 수 없습니다.", ""
146
+ except Exception as e:
147
+ print(f"Error in on_select: {str(e)}")
148
+ print(traceback.format_exc()) # 상세한 오류 정보 출력
149
+ return f"오류가 발생했습니다: {str(e)}", ""
150
+
151
+ def on_summarize(choice):
152
+ try:
153
+ if choice:
154
+ selected_id = space_choices[choice]
155
+ selected_space = next((space for space in formatted_spaces if space['id'] == selected_id), None)
156
+ if selected_space:
157
+ summary = summarize_space(selected_space)
158
+ print(f"Summarizing space: {selected_space['name']}") # 디버깅 출력
159
+ return summary
160
+ print("No space selected for summarization") # 디버깅 출력
161
+ return "선택된 space가 없습니다. 먼저 리스트에서 space를 선택해주세요."
162
+ except Exception as e:
163
+ print(f"Error in on_summarize: {str(e)}")
164
+ print(traceback.format_exc()) # 상세한 오류 정보 출력
165
+ return f"요약 중 오류가 발생했습니다: {str(e)}"
166
+
167
+ for space in formatted_spaces:
168
+ radio = demo.components[0].children[0].children[0].children[0].children[formatted_spaces.index(space)].children[0]
169
+ radio.change(on_select, radio, [output, app_py_content])
170
+
171
+ summarize_btn.click(on_summarize, inputs=[gr.State(lambda: next(radio for radio in demo.components[0].children[0].children[0].children[0].children if radio.children[0].value))], outputs=[output])
172
+
173
+ # JavaScript to open links in new tabs
174
+ link_script = """
175
+ function setupLinkButtons() {
176
+ document.querySelectorAll('button[id^="link-"]').forEach(button => {
177
+ button.addEventListener('click', function() {
178
+ var spaceId = this.id.split('-')[1];
179
+ window.open('https://huggingface.co/spaces/' + spaceId, '_blank');
180
+ });
181
+ });
182
+ }
183
+ if (document.readyState === 'complete') {
184
+ setupLinkButtons();
185
+ } else {
186
+ document.addEventListener('DOMContentLoaded', setupLinkButtons);
187
+ }
188
+ """
189
+ demo.load(None, None, None, _js=link_script)
190
+
191
+ return demo
192
+
193
+ if __name__ == "__main__":
194
+ demo = create_ui()
195
+ demo.launch()