Spaces:
Running
Running
Update app.py
Browse files
app.py
CHANGED
@@ -3,13 +3,9 @@ from huggingface_hub import InferenceClient
|
|
3 |
import os
|
4 |
import requests
|
5 |
from typing import List, Dict, Union
|
6 |
-
import concurrent.futures
|
7 |
import traceback
|
8 |
|
9 |
-
# 환경 변수에서 토큰 가져오기
|
10 |
HF_TOKEN = os.getenv("HF_TOKEN")
|
11 |
-
|
12 |
-
# 추론 API 클라이언트 설정
|
13 |
hf_client = InferenceClient("CohereForAI/c4ai-command-r-plus-08-2024", token=HF_TOKEN)
|
14 |
|
15 |
def get_headers():
|
@@ -29,52 +25,28 @@ def get_most_liked_spaces(limit: int = 100) -> Union[List[Dict], str]:
|
|
29 |
try:
|
30 |
response = requests.get(url, params=params, headers=get_headers())
|
31 |
response.raise_for_status()
|
32 |
-
|
33 |
-
|
34 |
-
if isinstance(data, list):
|
35 |
-
return data
|
36 |
-
else:
|
37 |
-
return f"Unexpected API response format: {type(data)}"
|
38 |
except requests.RequestException as e:
|
39 |
return f"API request error: {str(e)}"
|
40 |
except ValueError as e:
|
41 |
return f"JSON decoding error: {str(e)}"
|
42 |
|
43 |
-
def
|
44 |
-
|
45 |
-
|
46 |
-
|
47 |
-
if
|
48 |
-
return
|
49 |
-
except requests.RequestException:
|
50 |
-
pass
|
51 |
-
return None
|
52 |
-
|
53 |
-
|
54 |
-
def format_spaces(spaces: Union[List[Dict], str]) -> List[Dict]:
|
55 |
-
if isinstance(spaces, str):
|
56 |
-
return [{"error": spaces}]
|
57 |
-
|
58 |
-
valid_spaces = []
|
59 |
-
for space in spaces:
|
60 |
-
if isinstance(space, dict):
|
61 |
-
valid_spaces.append(space)
|
62 |
-
else:
|
63 |
-
print(f"Skipping invalid space: {space}")
|
64 |
|
65 |
-
|
66 |
-
|
67 |
-
|
68 |
-
|
69 |
-
|
70 |
-
print(f"Error formatting space: {space.get('id', 'Unknown')}. Error: {str(e)}")
|
71 |
|
72 |
-
return
|
73 |
|
74 |
def format_space(space: Dict) -> Dict:
|
75 |
-
if not isinstance(space, dict):
|
76 |
-
raise ValueError(f"Invalid space format: {space}")
|
77 |
-
|
78 |
space_id = space.get('id', 'Unknown')
|
79 |
space_name = space_id.split('/')[-1] if '/' in space_id else space_id
|
80 |
|
@@ -85,7 +57,7 @@ def format_space(space: Dict) -> Dict:
|
|
85 |
space_likes = space.get('likes', 'N/A')
|
86 |
space_url = f"https://huggingface.co/spaces/{space_id}"
|
87 |
|
88 |
-
|
89 |
hardware = get_hardware_requirements(space)
|
90 |
|
91 |
return {
|
@@ -94,32 +66,30 @@ def format_space(space: Dict) -> Dict:
|
|
94 |
"author": space_author,
|
95 |
"likes": space_likes,
|
96 |
"url": space_url,
|
97 |
-
"thumbnail":
|
98 |
"hardware": hardware
|
99 |
}
|
100 |
|
101 |
-
def
|
102 |
-
if
|
103 |
-
return "
|
104 |
|
105 |
-
|
106 |
-
|
107 |
-
|
|
|
|
|
108 |
|
109 |
-
|
110 |
-
|
111 |
-
|
|
|
112 |
|
113 |
-
|
114 |
-
|
115 |
-
return
|
116 |
-
|
117 |
-
|
118 |
-
if isinstance(host_requirements, dict):
|
119 |
-
hardware = host_requirements.get('hardware', {})
|
120 |
-
if isinstance(hardware, dict):
|
121 |
-
return 'CPU' if hardware.get('gpu') is False else 'GPU'
|
122 |
-
return 'Unknown'
|
123 |
|
124 |
def get_app_py_content(space_id: str) -> str:
|
125 |
app_py_url = f"https://huggingface.co/spaces/{space_id}/raw/main/app.py"
|
@@ -132,51 +102,34 @@ def get_app_py_content(space_id: str) -> str:
|
|
132 |
except requests.RequestException:
|
133 |
return f"Error fetching app.py content for space: {space_id}"
|
134 |
|
135 |
-
def
|
136 |
-
|
137 |
-
|
138 |
-
|
139 |
-
|
140 |
-
|
141 |
-
|
142 |
-
|
143 |
-
|
144 |
-
|
145 |
-
|
|
|
|
|
|
|
|
|
146 |
|
147 |
def create_ui():
|
148 |
spaces_list = get_most_liked_spaces()
|
149 |
print(f"Type of spaces_list: {type(spaces_list)}")
|
150 |
-
if isinstance(spaces_list, str):
|
151 |
-
print(f"Error in get_most_liked_spaces: {spaces_list}")
|
152 |
-
return gr.Blocks().launch()
|
153 |
-
|
154 |
formatted_spaces = format_spaces(spaces_list)
|
155 |
-
print(f"Total spaces loaded: {len(formatted_spaces)}")
|
156 |
|
157 |
css = """
|
158 |
-
footer {
|
159 |
-
|
160 |
-
}
|
161 |
-
.
|
162 |
-
|
163 |
-
height: 25px !important;
|
164 |
-
line-height: 1 !important;
|
165 |
-
font-size: 12px !important;
|
166 |
-
padding: 2px 5px !important;
|
167 |
-
}
|
168 |
-
.space-row {
|
169 |
-
margin-bottom: 5px !important;
|
170 |
-
}
|
171 |
-
.thumbnail {
|
172 |
-
width: 100px;
|
173 |
-
height: 100px;
|
174 |
-
object-fit: cover;
|
175 |
-
}
|
176 |
-
.hardware-info {
|
177 |
-
font-size: 12px;
|
178 |
-
color: #666;
|
179 |
-
}
|
180 |
"""
|
181 |
|
182 |
with gr.Blocks(css=css, theme="Nymbo/Nymbo_Theme") as demo:
|
@@ -187,10 +140,7 @@ def create_ui():
|
|
187 |
space_rows = []
|
188 |
for space in formatted_spaces:
|
189 |
with gr.Row(elem_classes="space-row") as space_row:
|
190 |
-
|
191 |
-
gr.Image(value=space['thumbnail'], width=100, height=100, show_label=False, elem_classes="thumbnail")
|
192 |
-
else:
|
193 |
-
gr.Image(value="https://huggingface.co/front/assets/huggingface_logo-noborder.svg", width=100, height=100, show_label=False, elem_classes="thumbnail")
|
194 |
with gr.Column():
|
195 |
gr.Markdown(f"{space['name']} by {space['author']} (Likes: {space['likes']})", elem_classes="space-info")
|
196 |
gr.Markdown(f"Hardware: {space['hardware']}", elem_classes="hardware-info")
|
|
|
3 |
import os
|
4 |
import requests
|
5 |
from typing import List, Dict, Union
|
|
|
6 |
import traceback
|
7 |
|
|
|
8 |
HF_TOKEN = os.getenv("HF_TOKEN")
|
|
|
|
|
9 |
hf_client = InferenceClient("CohereForAI/c4ai-command-r-plus-08-2024", token=HF_TOKEN)
|
10 |
|
11 |
def get_headers():
|
|
|
25 |
try:
|
26 |
response = requests.get(url, params=params, headers=get_headers())
|
27 |
response.raise_for_status()
|
28 |
+
return response.json()
|
|
|
|
|
|
|
|
|
|
|
29 |
except requests.RequestException as e:
|
30 |
return f"API request error: {str(e)}"
|
31 |
except ValueError as e:
|
32 |
return f"JSON decoding error: {str(e)}"
|
33 |
|
34 |
+
def get_hardware_requirements(space: Dict) -> str:
|
35 |
+
sdk = space.get('sdk', {})
|
36 |
+
if isinstance(sdk, dict):
|
37 |
+
hardware = sdk.get('hardware')
|
38 |
+
if hardware:
|
39 |
+
return hardware
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
40 |
|
41 |
+
host_requirements = space.get('host_requirements', {})
|
42 |
+
if isinstance(host_requirements, dict):
|
43 |
+
hardware = host_requirements.get('hardware', {})
|
44 |
+
if isinstance(hardware, dict):
|
45 |
+
return 'CPU' if hardware.get('gpu') is False else 'GPU'
|
|
|
46 |
|
47 |
+
return 'Unknown'
|
48 |
|
49 |
def format_space(space: Dict) -> Dict:
|
|
|
|
|
|
|
50 |
space_id = space.get('id', 'Unknown')
|
51 |
space_name = space_id.split('/')[-1] if '/' in space_id else space_id
|
52 |
|
|
|
57 |
space_likes = space.get('likes', 'N/A')
|
58 |
space_url = f"https://huggingface.co/spaces/{space_id}"
|
59 |
|
60 |
+
thumbnail_url = f"https://huggingface.co/spaces/{space_id}/resolve/main/thumbnail.png"
|
61 |
hardware = get_hardware_requirements(space)
|
62 |
|
63 |
return {
|
|
|
66 |
"author": space_author,
|
67 |
"likes": space_likes,
|
68 |
"url": space_url,
|
69 |
+
"thumbnail": thumbnail_url,
|
70 |
"hardware": hardware
|
71 |
}
|
72 |
|
73 |
+
def format_spaces(spaces: Union[List[Dict], str]) -> List[Dict]:
|
74 |
+
if isinstance(spaces, str):
|
75 |
+
return [{"error": spaces}]
|
76 |
|
77 |
+
return [format_space(space) for space in spaces if isinstance(space, dict)]
|
78 |
+
|
79 |
+
def summarize_space(space: Dict) -> str:
|
80 |
+
system_message = "당신은 Hugging Face Space의 내용을 요약하는 AI 조수입니다. 주어진 정보를 바탕으로 간결하고 명확한 요약을 제공해주세요."
|
81 |
+
user_message = f"다음 Hugging Face Space를 요약해주세요: {space['name']} by {space['author']}. 좋아요 수: {space['likes']}. URL: {space['url']}"
|
82 |
|
83 |
+
messages = [
|
84 |
+
{"role": "system", "content": system_message},
|
85 |
+
{"role": "user", "content": user_message}
|
86 |
+
]
|
87 |
|
88 |
+
try:
|
89 |
+
response = hf_client.chat_completion(messages, max_tokens=150, temperature=0.7)
|
90 |
+
return response.choices[0].message.content
|
91 |
+
except Exception as e:
|
92 |
+
return f"요약 생성 중 오류 발생: {str(e)}"
|
|
|
|
|
|
|
|
|
|
|
93 |
|
94 |
def get_app_py_content(space_id: str) -> str:
|
95 |
app_py_url = f"https://huggingface.co/spaces/{space_id}/raw/main/app.py"
|
|
|
102 |
except requests.RequestException:
|
103 |
return f"Error fetching app.py content for space: {space_id}"
|
104 |
|
105 |
+
def on_select(space):
|
106 |
+
try:
|
107 |
+
summary = summarize_space(space)
|
108 |
+
app_content = get_app_py_content(space['id'])
|
109 |
+
info = f"선택된 Space: {space['name']} (ID: {space['id']})\n"
|
110 |
+
info += f"Author: {space['author']}\n"
|
111 |
+
info += f"Likes: {space['likes']}\n"
|
112 |
+
info += f"Hardware: {space['hardware']}\n"
|
113 |
+
info += f"URL: {space['url']}\n\n"
|
114 |
+
info += f"요약:\n{summary}"
|
115 |
+
return info, app_content
|
116 |
+
except Exception as e:
|
117 |
+
print(f"Error in on_select: {str(e)}")
|
118 |
+
print(traceback.format_exc())
|
119 |
+
return f"오류가 발생했습니다: {str(e)}", ""
|
120 |
|
121 |
def create_ui():
|
122 |
spaces_list = get_most_liked_spaces()
|
123 |
print(f"Type of spaces_list: {type(spaces_list)}")
|
|
|
|
|
|
|
|
|
124 |
formatted_spaces = format_spaces(spaces_list)
|
125 |
+
print(f"Total spaces loaded: {len(formatted_spaces)}")
|
126 |
|
127 |
css = """
|
128 |
+
footer {visibility: hidden;}
|
129 |
+
.minimal-button {min-width: 30px !important; height: 25px !important; line-height: 1 !important; font-size: 12px !important; padding: 2px 5px !important;}
|
130 |
+
.space-row {margin-bottom: 5px !important;}
|
131 |
+
.thumbnail {width: 100px; height: 100px; object-fit: cover;}
|
132 |
+
.hardware-info {font-size: 12px; color: #666;}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
133 |
"""
|
134 |
|
135 |
with gr.Blocks(css=css, theme="Nymbo/Nymbo_Theme") as demo:
|
|
|
140 |
space_rows = []
|
141 |
for space in formatted_spaces:
|
142 |
with gr.Row(elem_classes="space-row") as space_row:
|
143 |
+
gr.Image(value=space['thumbnail'], width=100, height=100, show_label=False, elem_classes="thumbnail")
|
|
|
|
|
|
|
144 |
with gr.Column():
|
145 |
gr.Markdown(f"{space['name']} by {space['author']} (Likes: {space['likes']})", elem_classes="space-info")
|
146 |
gr.Markdown(f"Hardware: {space['hardware']}", elem_classes="hardware-info")
|