Spaces:
Running
Running
Delete app-backup4.py
Browse files- app-backup4.py +0 -232
app-backup4.py
DELETED
@@ -1,232 +0,0 @@
|
|
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 traceback
|
7 |
-
from PIL import Image
|
8 |
-
from io import BytesIO
|
9 |
-
import asyncio
|
10 |
-
from gradio_client import Client
|
11 |
-
import time
|
12 |
-
import threading
|
13 |
-
|
14 |
-
HF_TOKEN = os.getenv("HF_TOKEN")
|
15 |
-
hf_client = InferenceClient("CohereForAI/c4ai-command-r-plus-08-2024", token=HF_TOKEN)
|
16 |
-
|
17 |
-
def get_headers():
|
18 |
-
if not HF_TOKEN:
|
19 |
-
raise ValueError("Hugging Face token not found in environment variables")
|
20 |
-
return {"Authorization": f"Bearer {HF_TOKEN}"}
|
21 |
-
|
22 |
-
def get_most_liked_spaces(limit: int = 300) -> Union[List[Dict], str]:
|
23 |
-
url = "https://huggingface.co/api/spaces"
|
24 |
-
params = {
|
25 |
-
"sort": "likes",
|
26 |
-
"direction": -1,
|
27 |
-
"limit": limit,
|
28 |
-
"full": "true"
|
29 |
-
}
|
30 |
-
|
31 |
-
try:
|
32 |
-
response = requests.get(url, params=params, headers=get_headers())
|
33 |
-
response.raise_for_status()
|
34 |
-
return response.json()
|
35 |
-
except requests.RequestException as e:
|
36 |
-
return f"API request error: {str(e)}"
|
37 |
-
except ValueError as e:
|
38 |
-
return f"JSON decoding error: {str(e)}"
|
39 |
-
|
40 |
-
def format_space(space: Dict) -> Dict:
|
41 |
-
space_id = space.get('id', 'Unknown')
|
42 |
-
space_name = space_id.split('/')[-1] if '/' in space_id else space_id
|
43 |
-
|
44 |
-
space_author = space.get('author', 'Unknown')
|
45 |
-
if isinstance(space_author, dict):
|
46 |
-
space_author = space_author.get('user', space_author.get('name', 'Unknown'))
|
47 |
-
|
48 |
-
space_likes = space.get('likes', 'N/A')
|
49 |
-
space_url = f"https://huggingface.co/spaces/{space_id}"
|
50 |
-
|
51 |
-
return {
|
52 |
-
"id": space_id,
|
53 |
-
"name": space_name,
|
54 |
-
"author": space_author,
|
55 |
-
"likes": space_likes,
|
56 |
-
"url": space_url,
|
57 |
-
}
|
58 |
-
|
59 |
-
def format_spaces(spaces: Union[List[Dict], str]) -> List[Dict]:
|
60 |
-
if isinstance(spaces, str):
|
61 |
-
return [{"error": spaces}]
|
62 |
-
|
63 |
-
return [format_space(space) for space in spaces if isinstance(space, dict)]
|
64 |
-
|
65 |
-
def summarize_space(space: Dict) -> str:
|
66 |
-
system_message = "๋น์ ์ Hugging Face Space์ ๋ด์ฉ์ ์์ฝํ๋ AI ์กฐ์์
๋๋ค. ์ฃผ์ด์ง ์ ๋ณด๋ฅผ ๋ฐํ์ผ๋ก ๊ฐ๊ฒฐํ๊ณ ๋ช
ํํ ์์ฝ์ ์ ๊ณตํด์ฃผ์ธ์."
|
67 |
-
user_message = f"๋ค์ Hugging Face Space๋ฅผ ์์ฝํด์ฃผ์ธ์: {space['name']} by {space['author']}. ์ข์์ ์: {space['likes']}. URL: {space['url']}"
|
68 |
-
|
69 |
-
messages = [
|
70 |
-
{"role": "system", "content": system_message},
|
71 |
-
{"role": "user", "content": user_message}
|
72 |
-
]
|
73 |
-
|
74 |
-
try:
|
75 |
-
response = hf_client.chat_completion(messages, max_tokens=400, temperature=0.7)
|
76 |
-
return response.choices[0].message.content
|
77 |
-
except Exception as e:
|
78 |
-
return f"์์ฝ ์์ฑ ์ค ์ค๋ฅ ๋ฐ์: {str(e)}"
|
79 |
-
|
80 |
-
def get_app_py_content(space_id: str) -> str:
|
81 |
-
app_py_url = f"https://huggingface.co/spaces/{space_id}/raw/main/app.py"
|
82 |
-
try:
|
83 |
-
response = requests.get(app_py_url, headers=get_headers())
|
84 |
-
if response.status_code == 200:
|
85 |
-
content = response.text
|
86 |
-
if len(content) > 500: # ๋ด์ฉ์ 500์๋ก ์ ํํฉ๋๋ค
|
87 |
-
content = content[:497] + "..."
|
88 |
-
return content
|
89 |
-
else:
|
90 |
-
return f"app.py file not found or inaccessible for space: {space_id}"
|
91 |
-
except requests.RequestException:
|
92 |
-
return f"Error fetching app.py content for space: {space_id}"
|
93 |
-
|
94 |
-
def on_select(space):
|
95 |
-
try:
|
96 |
-
print(f"Selected space: {space['name']}")
|
97 |
-
summary = summarize_space(space)
|
98 |
-
app_content = get_app_py_content(space['id'])
|
99 |
-
info = f"์ ํ๋ Space: {space['name']} (ID: {space['id']})\n"
|
100 |
-
info += f"Author: {space['author']}\n"
|
101 |
-
info += f"Likes: {space['likes']}\n"
|
102 |
-
info += f"URL: {space['url']}\n\n"
|
103 |
-
info += f"์์ฝ:\n{summary}"
|
104 |
-
print(f"Returning URL: {space['url']}")
|
105 |
-
return info, app_content, space['url']
|
106 |
-
except Exception as e:
|
107 |
-
print(f"Error in on_select: {str(e)}")
|
108 |
-
print(traceback.format_exc())
|
109 |
-
return f"์ค๋ฅ๊ฐ ๋ฐ์ํ์ต๋๋ค: {str(e)}", "", ""
|
110 |
-
|
111 |
-
def update_screenshot(url, last_url, force_update=False):
|
112 |
-
print(f"Updating screenshot. Current URL: {url}, Last URL: {last_url}, Force update: {force_update}")
|
113 |
-
if url and (url != last_url or force_update):
|
114 |
-
|
115 |
-
screenshot = take_screenshot(url)
|
116 |
-
print("Screenshot updated")
|
117 |
-
return screenshot, url
|
118 |
-
print("No update needed")
|
119 |
-
return gr.update(), last_url
|
120 |
-
|
121 |
-
def refresh_screenshot(url, last_url):
|
122 |
-
print(f"Refresh button clicked. URL: {url}, Last URL: {last_url}")
|
123 |
-
# ํญ์ ๊ฐ์ ๋ก ์
๋ฐ์ดํธ
|
124 |
-
return update_screenshot(url, last_url, force_update=True)
|
125 |
-
|
126 |
-
|
127 |
-
def take_screenshot(url):
|
128 |
-
try:
|
129 |
-
print(f"Taking screenshot of URL: {url}")
|
130 |
-
client = Client("ginipick/selenium-screenshot-gradio")
|
131 |
-
result = client.predict(url=url, api_name="/predict")
|
132 |
-
print(f"Screenshot result: {result}")
|
133 |
-
if isinstance(result, str) and os.path.exists(result):
|
134 |
-
return Image.open(result)
|
135 |
-
else:
|
136 |
-
print(f"Invalid result from API: {result}")
|
137 |
-
return Image.new('RGB', (600, 360), color='lightgray')
|
138 |
-
except Exception as e:
|
139 |
-
print(f"Screenshot error: {str(e)}")
|
140 |
-
return Image.new('RGB', (600, 360), color='lightgray')
|
141 |
-
|
142 |
-
def create_ui():
|
143 |
-
try:
|
144 |
-
spaces_list = get_most_liked_spaces()
|
145 |
-
print(f"Type of spaces_list: {type(spaces_list)}")
|
146 |
-
formatted_spaces = format_spaces(spaces_list)
|
147 |
-
print(f"Total spaces loaded: {len(formatted_spaces)}")
|
148 |
-
|
149 |
-
css = """
|
150 |
-
footer {visibility: hidden;}
|
151 |
-
.minimal-button {min-width: 30px !important; height: 25px !important; line-height: 1 !important; font-size: 12px !important; padding: 2px 5px !important;}
|
152 |
-
.space-row {margin-bottom: 5px !important;}
|
153 |
-
#refresh-button {
|
154 |
-
width: 100% !important;
|
155 |
-
margin-top: 5px !important;
|
156 |
-
}
|
157 |
-
"""
|
158 |
-
|
159 |
-
with gr.Blocks(css=css, theme="Nymbo/Nymbo_Theme") as demo:
|
160 |
-
gr.Markdown("# 300: HuggingFace Most Liked Spaces")
|
161 |
-
|
162 |
-
with gr.Row():
|
163 |
-
with gr.Column(scale=1):
|
164 |
-
space_rows = []
|
165 |
-
for space in formatted_spaces:
|
166 |
-
with gr.Row(elem_classes="space-row") as space_row:
|
167 |
-
with gr.Column():
|
168 |
-
gr.Markdown(f"{space['name']} by {space['author']} (Likes: {space['likes']})", elem_classes="space-info")
|
169 |
-
button = gr.Button("ํด๋ฆญ", elem_classes="minimal-button")
|
170 |
-
space_rows.append((space_row, button, space))
|
171 |
-
|
172 |
-
with gr.Column(scale=1):
|
173 |
-
info_output = gr.Textbox(label="Space ์ ๋ณด ๋ฐ ์์ฝ", lines=20)
|
174 |
-
url_state = gr.State("")
|
175 |
-
last_url_state = gr.State("")
|
176 |
-
|
177 |
-
screenshot_output = gr.Image(type="pil", label="Live ํ๋ฉด", height=360, width=600)
|
178 |
-
refresh_button = gr.Button("๐ ์๋ก๊ณ ์นจ", elem_id="refresh-button")
|
179 |
-
|
180 |
-
app_py_content = gr.Code(language="python", label="๋ฉ์ธ ์์ค์ฝ๋")
|
181 |
-
update_trigger = gr.Button("Update Screenshot", visible=False)
|
182 |
-
|
183 |
-
for _, button, space in space_rows:
|
184 |
-
button.click(
|
185 |
-
lambda s=space: on_select(s),
|
186 |
-
inputs=[],
|
187 |
-
outputs=[info_output, app_py_content, url_state]
|
188 |
-
).then(
|
189 |
-
update_screenshot,
|
190 |
-
inputs=[url_state, last_url_state],
|
191 |
-
outputs=[screenshot_output, last_url_state]
|
192 |
-
)
|
193 |
-
|
194 |
-
def refresh_screenshot(url, last_url):
|
195 |
-
print(f"Refresh button clicked. URL: {url}, Last URL: {last_url}")
|
196 |
-
return update_screenshot(url, last_url)
|
197 |
-
|
198 |
-
refresh_button.click(
|
199 |
-
refresh_screenshot,
|
200 |
-
inputs=[url_state, last_url_state],
|
201 |
-
outputs=[screenshot_output, last_url_state]
|
202 |
-
)
|
203 |
-
|
204 |
-
|
205 |
-
update_trigger.click(
|
206 |
-
update_screenshot,
|
207 |
-
inputs=[url_state, last_url_state],
|
208 |
-
outputs=[screenshot_output, last_url_state]
|
209 |
-
)
|
210 |
-
|
211 |
-
# Start a background thread to trigger updates
|
212 |
-
def trigger_updates():
|
213 |
-
while True:
|
214 |
-
time.sleep(5)
|
215 |
-
update_trigger.click()
|
216 |
-
|
217 |
-
threading.Thread(target=trigger_updates, daemon=True).start()
|
218 |
-
|
219 |
-
return demo
|
220 |
-
|
221 |
-
except Exception as e:
|
222 |
-
print(f"Error in create_ui: {str(e)}")
|
223 |
-
print(traceback.format_exc())
|
224 |
-
raise
|
225 |
-
|
226 |
-
if __name__ == "__main__":
|
227 |
-
try:
|
228 |
-
demo = create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