ginipick commited on
Commit
c2606ca
ยท
verified ยท
1 Parent(s): 620f97e

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +71 -200
app.py CHANGED
@@ -21,76 +21,6 @@ def get_headers():
21
  raise ValueError("Hugging Face token not found in environment variables")
22
  return {"Authorization": f"Bearer {HF_TOKEN}"}
23
 
24
- def get_most_liked_spaces(limit: int = 300) -> Union[List[Dict], str]:
25
- url = "https://huggingface.co/api/spaces"
26
- params = {
27
- "sort": "likes",
28
- "direction": -1,
29
- "limit": limit,
30
- "full": "true"
31
- }
32
-
33
- try:
34
- response = requests.get(url, params=params, headers=get_headers())
35
- response.raise_for_status()
36
- return response.json()
37
- except requests.RequestException as e:
38
- return f"API request error: {str(e)}"
39
- except ValueError as e:
40
- return f"JSON decoding error: {str(e)}"
41
-
42
- def format_space(space: Dict) -> Dict:
43
- space_id = space.get('id', 'Unknown')
44
- space_name = space_id.split('/')[-1] if '/' in space_id else space_id
45
-
46
- space_author = space.get('author', 'Unknown')
47
- if isinstance(space_author, dict):
48
- space_author = space_author.get('user', space_author.get('name', 'Unknown'))
49
-
50
- space_likes = space.get('likes', 'N/A')
51
- space_url = f"https://huggingface.co/spaces/{space_id}"
52
-
53
- return {
54
- "id": space_id,
55
- "name": space_name,
56
- "author": space_author,
57
- "likes": space_likes,
58
- "url": space_url,
59
- }
60
-
61
- def format_spaces(spaces: Union[List[Dict], str]) -> List[Dict]:
62
- if isinstance(spaces, str):
63
- return [{"error": spaces}]
64
-
65
- return [format_space(space) for space in spaces if isinstance(space, dict)]
66
-
67
- def summarize_space(space: Dict) -> str:
68
- system_message = "๋‹น์‹ ์€ Hugging Face Space์˜ ๋‚ด์šฉ์„ ์š”์•ฝํ•˜๋Š” AI ์กฐ์ˆ˜์ž…๋‹ˆ๋‹ค. ์ฃผ์–ด์ง„ ์ •๋ณด๋ฅผ ๋ฐ”ํƒ•์œผ๋กœ ๊ฐ„๊ฒฐํ•˜๊ณ  ๋ช…ํ™•ํ•œ ์š”์•ฝ์„ ์ œ๊ณตํ•ด์ฃผ์„ธ์š”."
69
- user_message = f"๋‹ค์Œ Hugging Face Space๋ฅผ ์š”์•ฝํ•ด์ฃผ์„ธ์š”: {space['name']} by {space['author']}. ์ข‹์•„์š” ์ˆ˜: {space['likes']}. URL: {space['url']}"
70
-
71
- messages = [
72
- {"role": "system", "content": system_message},
73
- {"role": "user", "content": user_message}
74
- ]
75
-
76
- try:
77
- response = hf_client.chat_completion(messages, max_tokens=400, temperature=0.7)
78
- return response.choices[0].message.content
79
- except Exception as e:
80
- return f"์š”์•ฝ ์ƒ์„ฑ ์ค‘ ์˜ค๋ฅ˜ ๋ฐœ์ƒ: {str(e)}"
81
-
82
- def get_app_py_content(space_id: str) -> str:
83
- app_py_url = f"https://huggingface.co/spaces/{space_id}/raw/main/app.py"
84
- try:
85
- response = requests.get(app_py_url, headers=get_headers())
86
- if response.status_code == 200:
87
- return response.text # ์ „์ฒด ๋‚ด์šฉ์„ ๋ฐ˜ํ™˜
88
- else:
89
- return f"app.py file not found or inaccessible for space: {space_id}"
90
- except requests.RequestException:
91
- return f"Error fetching app.py content for space: {space_id}"
92
-
93
-
94
  def get_space_structure(space_id: str) -> Dict:
95
  try:
96
  # space_id์—์„œ owner์™€ repo_name์„ ๋ถ„๋ฆฌ
@@ -144,42 +74,31 @@ def format_list_structure(tree_data: Dict) -> List[str]:
144
  formatted.extend(format_list_structure(item))
145
  return formatted
146
 
147
- def on_select(space):
 
148
  try:
149
- print(f"Selected space: {space['name']}")
150
- summary = summarize_space(space)
151
- app_content = get_app_py_content(space['id'])
152
- tree_structure = get_space_structure(space['id'])
153
-
154
- info = f"์„ ํƒ๋œ Space: {space['name']} (ID: {space['id']})\n"
155
- info += f"Author: {space['author']}\n"
156
- info += f"Likes: {space['likes']}\n"
157
- info += f"URL: {space['url']}\n\n"
158
- info += f"์š”์•ฝ:\n{summary}"
159
-
160
- tree_view = format_tree_structure(tree_structure)
161
- list_view = "\n".join(format_list_structure(tree_structure))
162
-
163
- print(f"Returning URL: {space['url']}")
164
- return info, app_content, space['url'], tree_view, list_view
165
- except Exception as e:
166
- print(f"Error in on_select: {str(e)}")
167
- print(traceback.format_exc())
168
- return f"์˜ค๋ฅ˜๊ฐ€ ๋ฐœ์ƒํ–ˆ์Šต๋‹ˆ๋‹ค: {str(e)}", "", "", "", ""
169
-
170
- def update_screenshot(url, last_url, force_update=False):
171
- print(f"Updating screenshot. Current URL: {url}, Last URL: {last_url}, Force update: {force_update}")
172
- if url and (url != last_url or force_update):
173
- screenshot = take_screenshot(url)
174
- print("Screenshot updated")
175
- return screenshot, url
176
- print("No update needed")
177
- return gr.update(), last_url
178
 
179
- def refresh_screenshot(url, last_url):
180
- print(f"Refresh button clicked. URL: {url}, Last URL: {last_url}")
181
- # ํ•ญ์ƒ ๊ฐ•์ œ๋กœ ์—…๋ฐ์ดํŠธ
182
- return update_screenshot(url, last_url, force_update=True)
 
 
 
 
 
 
 
 
 
 
183
 
184
  def take_screenshot(url):
185
  try:
@@ -196,27 +115,27 @@ def take_screenshot(url):
196
  print(f"Screenshot error: {str(e)}")
197
  return Image.new('RGB', (600, 360), color='lightgray')
198
 
199
- def generate_usage_guide(app_content):
200
- system_message = "๋‹น์‹ ์€ Python ์ฝ”๋“œ๋ฅผ ๋ถ„์„ํ•˜์—ฌ, ํ™”๋ฉด ๋ณด๋“ฏ์ด ์ด์šฉ ๋ฐฉ๋ฒ•์„ ์„ค๋ช…ํ•˜๋Š” AI ์กฐ์ˆ˜์ž…๋‹ˆ๋‹ค. app.py ์ฝ”๋“œ๋ฅผ ๋ฐ”ํƒ•์œผ๋กœ ์ฝ”๋“œ์— ๋Œ€ํ•œ ์–ธ๊ธ‰์€ ์ œ์™ธํ•˜๊ณ , ์ด์šฉ์ž ๊ด€์ ์—์„œ 1) ๊ธฐ์กด ์œ ์‚ฌ ๊ธฐ์ˆ  ๋ฐฉ์‹๊ดด ๋น„๊ตํ•ด ํŠน์ง•, ์žฅ์ ์— ๋Œ€ํ•ด ์นœ์ ˆํ•˜๊ณ  ์ž์„ธํ•˜๊ฒŒ ์ƒ์„ธํ•œ ์‚ฌ์šฉ ๋ฐฉ๋ฒ•์„ ์ œ๊ณตํ•ด์ฃผ์„ธ์š”."
201
- user_message = f"๋‹ค์Œ Python ์ฝ”๋“œ๋ฅผ ๊ธฐ๋ฐ˜์œผ๋กœ ํ™”๋ฉด UI/UX์  ์ธก๋ฉด์œผ๋กœ ํŠน์ง•๊ณผ ์‚ฌ์šฉ ๋ฐฉ๋ฒ•์„ ์„ค๋ช…ํ•ด์ฃผ์„ธ์š”:\n\n{app_content}"
202
-
203
- messages = [
204
- {"role": "system", "content": system_message},
205
- {"role": "user", "content": user_message}
206
- ]
207
-
208
  try:
209
- response = hf_client.chat_completion(messages, max_tokens=4000, temperature=0.7)
210
- return response.choices[0].message.content
 
 
 
 
 
 
 
 
 
 
211
  except Exception as e:
212
- return f"์‚ฌ์šฉ ๋ฐฉ๋ฒ• ์ƒ์„ฑ ์ค‘ ์˜ค๋ฅ˜ ๋ฐœ์ƒ: {str(e)}"
 
 
213
 
214
  def create_ui():
215
  try:
216
- spaces_list = get_most_liked_spaces()
217
- formatted_spaces = format_spaces(spaces_list)
218
- print(f"Total spaces loaded: {len(formatted_spaces)}")
219
-
220
  css = """
221
  footer {visibility: hidden;}
222
  .minimal-button {min-width: 30px !important; height: 25px !important; line-height: 1 !important; font-size: 12px !important; padding: 2px 5px !important;}
@@ -252,32 +171,21 @@ def create_ui():
252
  """
253
 
254
  with gr.Blocks(css=css, theme="Nymbo/Nymbo_Theme") as demo:
255
- gr.Markdown("# 300: HuggingFace Most Liked Spaces")
 
 
 
 
256
 
257
  with gr.Row():
258
- with gr.Column(scale=1):
259
- space_rows = []
260
- for space in formatted_spaces:
261
- with gr.Row(elem_classes="space-row") as space_row:
262
- with gr.Column():
263
- gr.Markdown(f"{space['name']} by {space['author']} (Likes: {space['likes']})", elem_classes="space-info")
264
- button = gr.Button("ํด๋ฆญ", elem_classes="minimal-button")
265
- space_rows.append((space_row, button, space))
266
-
267
  with gr.Column(scale=2):
268
  with gr.Tabs():
269
  with gr.TabItem("๊ธฐ๋ณธ ์ •๋ณด"):
270
  with gr.Group(elem_classes="output-group scroll-lock"):
271
  info_output = gr.Textbox(label="Space ์ •๋ณด ๋ฐ ์š”์•ฝ", elem_id="info-output", lines=20, max_lines=30)
272
- url_state = gr.State("")
273
- last_url_state = gr.State("")
274
 
275
  screenshot_output = gr.Image(type="pil", label="Live ํ™”๋ฉด", height=360, width=600)
276
  refresh_button = gr.Button("๐Ÿ”„ ์„œ๋น„์Šค ํ™”๋ฉด", elem_id="refresh-button")
277
- manual_button = gr.Button("์„ ํƒ ์„œ๋น„์Šค ํŠน์ง• ๋ฐ ์‚ฌ์šฉ๋ฒ•", elem_id="manual-button")
278
-
279
- with gr.Group(elem_classes="output-group scroll-lock"):
280
- usage_guide = gr.Textbox(label="์„ ๏ฟฝ๏ฟฝ ์„œ๋น„์Šค ํŠน์ง• ๋ฐ ์‚ฌ์šฉ๋ฒ•", elem_id="usage-guide", visible=False, lines=20, max_lines=30)
281
 
282
  with gr.Group(elem_classes="output-group full-height"):
283
  app_py_content = gr.Code(language="python", label="๋ฉ”์ธ ์†Œ์Šค์ฝ”๋“œ", elem_id="app-py-content", lines=None, max_lines=None)
@@ -288,69 +196,32 @@ def create_ui():
288
  with gr.Group(elem_classes="output-group scroll-lock"):
289
  tree_view = gr.Textbox(label="ํŠธ๋ฆฌ ๊ตฌ์กฐ", elem_id="tree-view", lines=30, max_lines=50)
290
  with gr.Group(elem_classes="output-group scroll-lock"):
291
- list_view = gr.Textbox(label="๋ฆฌ์ŠคํŠธ ๊ตฌ์กฐ", elem_id="list-view", lines=30, max_lines=50)
292
-
293
- update_trigger = gr.Button("Update Screenshot", visible=False)
294
-
295
-
296
- def on_select_with_link(space):
297
- info, app_content, url, tree, list_structure = on_select(space)
298
- info += f"\n\n์„ ํƒํ•œ Space URL: {url}"
299
- return info, app_content, url, tree, list_structure
300
-
301
- for _, button, space in space_rows:
302
- button.click(
303
- lambda s=space: on_select_with_link(s),
304
- inputs=[],
305
- outputs=[info_output, app_py_content, url_state, tree_view, list_view]
306
- ).then(
307
- update_screenshot,
308
- inputs=[url_state, last_url_state],
309
- outputs=[screenshot_output, last_url_state]
310
- )
311
-
312
- def open_space_in_browser(url):
313
- if url:
314
- import webbrowser
315
- webbrowser.open(url)
316
- return f"'{url}' ์ฃผ์†Œ๊ฐ€ ์ƒˆ ํƒญ์—์„œ ์—ด๋ ธ์Šต๋‹ˆ๋‹ค."
317
- return "์„ ํƒ๋œ Space๊ฐ€ ์—†์Šต๋‹ˆ๋‹ค."
318
-
319
- open_space_button.click(
320
- open_space_in_browser,
321
- inputs=[url_state],
322
- outputs=[gr.Textbox(label="์ƒํƒœ ๋ฉ”์‹œ์ง€")]
323
- )
324
-
325
- refresh_button.click(
326
- refresh_screenshot,
327
- inputs=[url_state, last_url_state],
328
- outputs=[screenshot_output, last_url_state]
329
- )
330
-
331
- def show_usage_guide(app_content):
332
- usage_text = generate_usage_guide(app_content)
333
- return gr.update(value=usage_text, visible=True)
334
-
335
- manual_button.click(
336
- show_usage_guide,
337
- inputs=[app_py_content],
338
- outputs=[usage_guide]
339
- )
340
-
341
- update_trigger.click(
342
- update_screenshot,
343
- inputs=[url_state, last_url_state],
344
- outputs=[screenshot_output, last_url_state]
345
- )
346
-
347
- # Start a background thread to trigger updates
348
- def trigger_updates():
349
- while True:
350
- time.sleep(5)
351
- update_trigger.click()
352
-
353
- threading.Thread(target=trigger_updates, daemon=True).start()
354
 
355
  return demo
356
 
@@ -365,4 +236,4 @@ if __name__ == "__main__":
365
  demo.launch()
366
  except Exception as e:
367
  print(f"Error in main: {str(e)}")
368
- print(traceback.format_exc())
 
21
  raise ValueError("Hugging Face token not found in environment variables")
22
  return {"Authorization": f"Bearer {HF_TOKEN}"}
23
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
24
  def get_space_structure(space_id: str) -> Dict:
25
  try:
26
  # space_id์—์„œ owner์™€ repo_name์„ ๋ถ„๋ฆฌ
 
74
  formatted.extend(format_list_structure(item))
75
  return formatted
76
 
77
+ def get_app_py_content(space_id: str) -> str:
78
+ app_py_url = f"https://huggingface.co/spaces/{space_id}/raw/main/app.py"
79
  try:
80
+ response = requests.get(app_py_url, headers=get_headers())
81
+ if response.status_code == 200:
82
+ return response.text
83
+ else:
84
+ return f"app.py file not found or inaccessible for space: {space_id}"
85
+ except requests.RequestException:
86
+ return f"Error fetching app.py content for space: {space_id}"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
87
 
88
+ def summarize_space(space_id: str) -> str:
89
+ system_message = "๋‹น์‹ ์€ Hugging Face Space์˜ ๋‚ด์šฉ์„ ์š”์•ฝํ•˜๋Š” AI ์กฐ์ˆ˜์ž…๋‹ˆ๋‹ค. ์ฃผ์–ด์ง„ ์ •๋ณด๋ฅผ ๋ฐ”ํƒ•์œผ๋กœ ๊ฐ„๊ฒฐํ•˜๊ณ  ๋ช…ํ™•ํ•œ ์š”์•ฝ์„ ์ œ๊ณตํ•ด์ฃผ์„ธ์š”."
90
+ user_message = f"๋‹ค์Œ Hugging Face Space๋ฅผ ์š”์•ฝํ•ด์ฃผ์„ธ์š”: {space_id}"
91
+
92
+ messages = [
93
+ {"role": "system", "content": system_message},
94
+ {"role": "user", "content": user_message}
95
+ ]
96
+
97
+ try:
98
+ response = hf_client.chat_completion(messages, max_tokens=400, temperature=0.7)
99
+ return response.choices[0].message.content
100
+ except Exception as e:
101
+ return f"์š”์•ฝ ์ƒ์„ฑ ์ค‘ ์˜ค๋ฅ˜ ๋ฐœ์ƒ: {str(e)}"
102
 
103
  def take_screenshot(url):
104
  try:
 
115
  print(f"Screenshot error: {str(e)}")
116
  return Image.new('RGB', (600, 360), color='lightgray')
117
 
118
+ def analyze_space(url: str):
 
 
 
 
 
 
 
 
119
  try:
120
+ # URL์—์„œ space_id ์ถ”์ถœ
121
+ space_id = url.split('spaces/')[-1]
122
+
123
+ summary = summarize_space(space_id)
124
+ app_content = get_app_py_content(space_id)
125
+ tree_structure = get_space_structure(space_id)
126
+
127
+ tree_view = format_tree_structure(tree_structure)
128
+ list_view = "\n".join(format_list_structure(tree_structure))
129
+ screenshot = take_screenshot(url)
130
+
131
+ return summary, app_content, tree_view, list_view, screenshot, url
132
  except Exception as e:
133
+ print(f"Error in analyze_space: {str(e)}")
134
+ print(traceback.format_exc())
135
+ return f"์˜ค๋ฅ˜๊ฐ€ ๋ฐœ์ƒํ–ˆ์Šต๋‹ˆ๋‹ค: {str(e)}", "", "", "", None, ""
136
 
137
  def create_ui():
138
  try:
 
 
 
 
139
  css = """
140
  footer {visibility: hidden;}
141
  .minimal-button {min-width: 30px !important; height: 25px !important; line-height: 1 !important; font-size: 12px !important; padding: 2px 5px !important;}
 
171
  """
172
 
173
  with gr.Blocks(css=css, theme="Nymbo/Nymbo_Theme") as demo:
174
+ gr.Markdown("# HuggingFace Space Analyzer")
175
+
176
+ with gr.Row():
177
+ url_input = gr.Textbox(label="HuggingFace Space URL")
178
+ analyze_button = gr.Button("๋ถ„์„")
179
 
180
  with gr.Row():
 
 
 
 
 
 
 
 
 
181
  with gr.Column(scale=2):
182
  with gr.Tabs():
183
  with gr.TabItem("๊ธฐ๋ณธ ์ •๋ณด"):
184
  with gr.Group(elem_classes="output-group scroll-lock"):
185
  info_output = gr.Textbox(label="Space ์ •๋ณด ๋ฐ ์š”์•ฝ", elem_id="info-output", lines=20, max_lines=30)
 
 
186
 
187
  screenshot_output = gr.Image(type="pil", label="Live ํ™”๋ฉด", height=360, width=600)
188
  refresh_button = gr.Button("๐Ÿ”„ ์„œ๋น„์Šค ํ™”๋ฉด", elem_id="refresh-button")
 
 
 
 
189
 
190
  with gr.Group(elem_classes="output-group full-height"):
191
  app_py_content = gr.Code(language="python", label="๋ฉ”์ธ ์†Œ์Šค์ฝ”๋“œ", elem_id="app-py-content", lines=None, max_lines=None)
 
196
  with gr.Group(elem_classes="output-group scroll-lock"):
197
  tree_view = gr.Textbox(label="ํŠธ๋ฆฌ ๊ตฌ์กฐ", elem_id="tree-view", lines=30, max_lines=50)
198
  with gr.Group(elem_classes="output-group scroll-lock"):
199
+ list_view = gr.Textbox(label="ํŒŒ์ผ ๋ฆฌ์ŠคํŠธ", elem_id="list-view", lines=30, max_lines=50)
200
+
201
+ def open_space_in_browser(url):
202
+ if url:
203
+ import webbrowser
204
+ webbrowser.open(url)
205
+ return f"'{url}' ์ฃผ์†Œ๊ฐ€ ์ƒˆ ํƒญ์—์„œ ์—ด๋ ธ์Šต๋‹ˆ๋‹ค."
206
+ return "์„ ํƒ๋œ Space๊ฐ€ ์—†์Šต๋‹ˆ๋‹ค."
207
+
208
+ analyze_button.click(
209
+ analyze_space,
210
+ inputs=[url_input],
211
+ outputs=[info_output, app_py_content, tree_view, list_view, screenshot_output, url_input]
212
+ )
213
+
214
+ open_space_button.click(
215
+ open_space_in_browser,
216
+ inputs=[url_input],
217
+ outputs=[gr.Textbox(label="์ƒํƒœ ๋ฉ”์‹œ์ง€")]
218
+ )
219
+
220
+ refresh_button.click(
221
+ take_screenshot,
222
+ inputs=[url_input],
223
+ outputs=[screenshot_output]
224
+ )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
225
 
226
  return demo
227
 
 
236
  demo.launch()
237
  except Exception as e:
238
  print(f"Error in main: {str(e)}")
239
+ print(traceback.format_exc())