Spaces:
Running
Running
File size: 8,436 Bytes
7cb753c 730989a eaa9ab5 e7ad194 6f35c03 88fe1ec 7cb753c 587b6d5 7cb753c 4855252 7cb753c 29af47d 7cb753c ccbe8d0 7cb753c 4855252 29af47d 4855252 e1e1afb 4855252 e1e1afb 4855252 8477558 4855252 026790d d934b2b d470784 abbf372 d470784 d934b2b abbf372 e7ad194 4855252 8af6f36 4855252 990edf6 8af6f36 cbc2346 4855252 cbc2346 7e8c8ee 8af6f36 7e8c8ee f78ba74 8af6f36 f78ba74 8af6f36 f78ba74 e7ad194 730989a 8af6f36 e7ad194 8af6f36 8888ccb eaa9ab5 8af6f36 3b4bd32 7cb753c 1edcd51 7cb753c 423f90c da191b4 423f90c 11aeea5 d934b2b 423f90c d470784 423f90c abbf372 c485d87 082e1ed 8af6f36 082e1ed cbc2346 6f35c03 423f90c daffb13 abbf372 e7ad194 cbc2346 c485d87 daffb13 d470784 082e1ed 6f35c03 e461da6 6f35c03 e461da6 423f90c 1edcd51 f355446 |
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 |
import gradio as gr
from huggingface_hub import InferenceClient
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
HF_TOKEN = os.getenv("HF_TOKEN")
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 = 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:
content = response.text
if len(content) > 500: # ๋ด์ฉ์ 500์๋ก ์ ํํฉ๋๋ค
content = content[:497] + "..."
return content
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 on_select(space):
try:
print(f"Selected space: {space['name']}")
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}"
print(f"Returning URL: {space['url']}")
return info, app_content, space['url']
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):
print(f"Updating screenshot. Current URL: {url}, Last URL: {last_url}")
if url and url != last_url:
screenshot = take_screenshot(url)
print("Screenshot updated")
return screenshot, url
print("No update needed")
return gr.update(), last_url
def take_screenshot(url):
try:
print(f"Attempting to take 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', (540, 360), color='lightgray')
except Exception as e:
print(f"Screenshot error: {str(e)}")
return Image.new('RGB', (540, 360), color='lightgray')
def create_ui():
try:
spaces_list = get_most_liked_spaces()
print(f"Type of spaces_list: {type(spaces_list)}")
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;}
"""
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=1):
info_output = gr.Textbox(label="Space ์ ๋ณด ๋ฐ ์์ฝ", lines=20)
url_state = gr.State("")
last_url_state = gr.State("")
with gr.Row():
screenshot_output = gr.Image(type="pil", label="Live ํ๋ฉด", height=360, width=600)
refresh_button = gr.Button("๐ ์๋ก๊ณ ์นจ", scale=0.1)
app_py_content = gr.Code(language="python", label="๋ฉ์ธ ์์ค์ฝ๋")
update_trigger = gr.Button("Update Screenshot", visible=False)
for _, button, space in space_rows:
button.click(
lambda s=space: on_select(s),
inputs=[],
outputs=[info_output, app_py_content, url_state]
).then(
update_screenshot,
inputs=[url_state, last_url_state],
outputs=[screenshot_output, last_url_state]
)
refresh_button.click(
update_screenshot,
inputs=[url_state, last_url_state],
outputs=[screenshot_output, last_url_state]
)
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()) |