Spaces:
Running
Running
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 capture_thumbnail(space_id: str) -> bytes: | |
screenshot_url = f"https://huggingface.co/spaces/{space_id}/thumbnail.png" | |
try: | |
response = requests.get(screenshot_url, headers=get_headers()) | |
if response.status_code == 200: | |
return response.content | |
except requests.RequestException: | |
pass | |
return None | |
def get_hardware_requirements(space: Dict) -> str: | |
sdk_version = space.get('sdk', {}).get('hf', {}).get('version') | |
if sdk_version and int(sdk_version.split('.')[0]) >= 3: | |
return space.get('sdk', {}).get('hardware', 'Unknown') | |
else: | |
return 'CPU' if space.get('host_requirements', {}).get('hardware', {}).get('gpu') is False else 'GPU' | |
def format_spaces(spaces: Union[List[Dict], str]) -> List[Dict]: | |
if isinstance(spaces, str): | |
return [{"error": spaces}] | |
valid_spaces = [space for space in spaces if isinstance(space, dict)] | |
with concurrent.futures.ThreadPoolExecutor(max_workers=10) as executor: | |
return list(executor.map(format_space, valid_spaces)) | |
def format_space(space: Union[Dict, str]) -> Dict: | |
if not isinstance(space, dict): | |
return {"error": "Invalid space data"} | |
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}" | |
thumbnail = capture_thumbnail(space_id) | |
hardware = get_hardware_requirements(space) | |
return { | |
"id": space_id, | |
"name": space_name, | |
"author": space_author, | |
"likes": space_likes, | |
"url": space_url, | |
"thumbnail": thumbnail, | |
"hardware": hardware | |
} | |
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)}") # ๋๋ฒ๊น ์ถ๋ ฅ | |
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; | |
} | |
.thumbnail { | |
width: 100px; | |
height: 100px; | |
object-fit: cover; | |
} | |
.hardware-info { | |
font-size: 12px; | |
color: #666; | |
} | |
""" | |
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"Hardware: {space['hardware']}\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)}", "" | |
with gr.Blocks(css=css, theme="Nymbo/Nymbo_Theme") as demo: | |
gr.Markdown("# Hugging Face 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: | |
if space['thumbnail']: | |
gr.Image(value=space['thumbnail'], shape=(100, 100), show_label=False, elem_classes="thumbnail") | |
else: | |
gr.Image(value="https://huggingface.co/front/assets/huggingface_logo-noborder.svg", shape=(100, 100), show_label=False, elem_classes="thumbnail") | |
with gr.Column(): | |
gr.Markdown(f"{space['name']} by {space['author']} (Likes: {space['likes']})", elem_classes="space-info") | |
gr.Markdown(f"Hardware: {space['hardware']}", elem_classes="hardware-info") | |
button = gr.Button("ํด๋ฆญ", elem_classes="minimal-button") | |
space_rows.append((space_row, button, space)) | |
with gr.Column(scale=1): | |
info_output = gr.Textbox(label="Space ์ ๋ณด ๋ฐ ์์ฝ", lines=10) | |
app_py_content = gr.Code(language="python", label="app.py ๋ด์ฉ") | |
for _, button, space in space_rows: | |
button.click( | |
lambda s=space: on_select(s), | |
inputs=[], | |
outputs=[info_output, app_py_content] | |
) | |
return demo | |
if __name__ == "__main__": | |
demo = create_ui() | |
demo.launch() |