ginipick commited on
Commit
4af25eb
Β·
verified Β·
1 Parent(s): d4737ee

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +71 -31
app.py CHANGED
@@ -10,6 +10,7 @@ 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)
@@ -90,28 +91,62 @@ def get_app_py_content(space_id: str) -> str:
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
@@ -123,7 +158,6 @@ def refresh_screenshot(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}")
@@ -138,7 +172,6 @@ def take_screenshot(url):
138
  except Exception as e:
139
  print(f"Screenshot error: {str(e)}")
140
  return Image.new('RGB', (600, 360), color='lightgray')
141
-
142
 
143
  def generate_usage_guide(app_content):
144
  system_message = "당신은 Python μ½”λ“œλ₯Ό λΆ„μ„ν•˜μ—¬, ν™”λ©΄ 보듯이 이용 방법을 μ„€λͺ…ν•˜λŠ” AI μ‘°μˆ˜μž…λ‹ˆλ‹€. app.py μ½”λ“œλ₯Ό λ°”νƒ•μœΌλ‘œ μ½”λ“œμ— λŒ€ν•œ 언급은 μ œμ™Έν•˜κ³ , 이용자 κ΄€μ μ—μ„œ 1) κΈ°μ‘΄ μœ μ‚¬ 기술 방식괴 비ꡐ해 νŠΉμ§•, μž₯점에 λŒ€ν•΄ μΉœμ ˆν•˜κ³  μžμ„Έν•˜κ²Œ μƒμ„Έν•œ μ‚¬μš© 방법을 μ œκ³΅ν•΄μ£Όμ„Έμš”."
@@ -169,7 +202,7 @@ def create_ui():
169
  width: 100% !important;
170
  margin-top: 5px !important;
171
  }
172
- #info-output, #usage-guide {
173
  height: 400px;
174
  overflow-y: auto;
175
  padding-right: 10px;
@@ -201,35 +234,43 @@ def create_ui():
201
  space_rows.append((space_row, button, space))
202
 
203
  with gr.Column(scale=2):
204
- with gr.Group(elem_classes="output-group"):
205
- info_output = gr.Textbox(label="Space 정보 및 μš”μ•½", elem_id="info-output", lines=20, max_lines=30)
206
- url_state = gr.State("")
207
- last_url_state = gr.State("")
208
-
209
- screenshot_output = gr.Image(type="pil", label="Live ν™”λ©΄", height=360, width=600)
210
- refresh_button = gr.Button("πŸ”„ μ„œλΉ„μŠ€ ν™”λ©΄", elem_id="refresh-button")
211
- manual_button = gr.Button("선택 μ„œλΉ„μŠ€ νŠΉμ§• 및 μ‚¬μš©λ²•", elem_id="manual-button")
212
-
213
- with gr.Group(elem_classes="output-group"):
214
- usage_guide = gr.Textbox(label="선택 μ„œλΉ„μŠ€ νŠΉμ§• 및 μ‚¬μš©λ²•", elem_id="usage-guide", visible=False, lines=20, max_lines=30)
215
-
216
- with gr.Group(elem_classes="output-group"):
217
- app_py_content = gr.Code(language="python", label="메인 μ†ŒμŠ€μ½”λ“œ", elem_id="app-py-content", lines=None, max_lines=None)
218
-
219
- open_space_button = gr.Button("μ„ νƒν•œ Space μ—΄κΈ°", elem_id="open-space-button")
 
 
 
 
 
 
 
 
220
 
221
  update_trigger = gr.Button("Update Screenshot", visible=False)
222
 
223
  def on_select_with_link(space):
224
- info, app_content, url = on_select(space)
225
  info += f"\n\nμ„ νƒν•œ Space URL: {url}"
226
- return info, app_content, url
227
 
228
  for _, button, space in space_rows:
229
  button.click(
230
  lambda s=space: on_select_with_link(s),
231
  inputs=[],
232
- outputs=[info_output, app_py_content, url_state]
233
  ).then(
234
  update_screenshot,
235
  inputs=[url_state, last_url_state],
@@ -238,6 +279,7 @@ def create_ui():
238
 
239
  def open_space_in_browser(url):
240
  if url:
 
241
  webbrowser.open(url)
242
  return f"'{url}' μ£Όμ†Œκ°€ μƒˆ νƒ­μ—μ„œ μ—΄λ ΈμŠ΅λ‹ˆλ‹€."
243
  return "μ„ νƒλœ Spaceκ°€ μ—†μŠ΅λ‹ˆλ‹€."
@@ -248,10 +290,6 @@ def create_ui():
248
  outputs=[gr.Textbox(label="μƒνƒœ λ©”μ‹œμ§€")]
249
  )
250
 
251
- def refresh_screenshot(url, last_url):
252
- print(f"Refresh button clicked. URL: {url}, Last URL: {last_url}")
253
- return update_screenshot(url, last_url)
254
-
255
  refresh_button.click(
256
  refresh_screenshot,
257
  inputs=[url_state, last_url_state],
@@ -295,4 +333,6 @@ if __name__ == "__main__":
295
  demo.launch()
296
  except Exception as e:
297
  print(f"Error in main: {str(e)}")
298
- print(traceback.format_exc())
 
 
 
10
  from gradio_client import Client
11
  import time
12
  import threading
13
+ import json
14
 
15
  HF_TOKEN = os.getenv("HF_TOKEN")
16
  hf_client = InferenceClient("CohereForAI/c4ai-command-r-plus-08-2024", token=HF_TOKEN)
 
91
  return f"app.py file not found or inaccessible for space: {space_id}"
92
  except requests.RequestException:
93
  return f"Error fetching app.py content for space: {space_id}"
94
+
95
+ def get_space_structure(space_id: str) -> Dict:
96
+ api_url = f"https://huggingface.co/api/spaces/{space_id}/tree"
97
+ try:
98
+ response = requests.get(api_url, headers=get_headers())
99
+ response.raise_for_status()
100
+ return response.json()
101
+ except requests.RequestException as e:
102
+ return {"error": f"API request error: {str(e)}"}
103
+
104
+ def format_tree_structure(tree_data: Dict, indent: str = "") -> str:
105
+ formatted = ""
106
+ for item in tree_data.get("tree", []):
107
+ if item["type"] == "file":
108
+ formatted += f"{indent}β”œβ”€β”€ {item['path']}\n"
109
+ elif item["type"] == "directory":
110
+ formatted += f"{indent}β”œβ”€β”€ {item['path']}/\n"
111
+ formatted += format_tree_structure(item, indent + "β”‚ ")
112
+ return formatted
113
+
114
+ def format_list_structure(tree_data: Dict) -> List[str]:
115
+ formatted = []
116
+ for item in tree_data.get("tree", []):
117
+ if item["type"] == "file":
118
+ formatted.append(item["path"])
119
+ elif item["type"] == "directory":
120
+ formatted.append(f"{item['path']}/")
121
+ formatted.extend(format_list_structure(item))
122
+ return formatted
123
+
124
  def on_select(space):
125
  try:
126
  print(f"Selected space: {space['name']}")
127
  summary = summarize_space(space)
128
  app_content = get_app_py_content(space['id'])
129
+ tree_structure = get_space_structure(space['id'])
130
+
131
  info = f"μ„ νƒλœ Space: {space['name']} (ID: {space['id']})\n"
132
  info += f"Author: {space['author']}\n"
133
  info += f"Likes: {space['likes']}\n"
134
  info += f"URL: {space['url']}\n\n"
135
  info += f"μš”μ•½:\n{summary}"
136
+
137
+ tree_view = format_tree_structure(tree_structure)
138
+ list_view = "\n".join(format_list_structure(tree_structure))
139
+
140
  print(f"Returning URL: {space['url']}")
141
+ return info, app_content, space['url'], tree_view, list_view
142
  except Exception as e:
143
  print(f"Error in on_select: {str(e)}")
144
  print(traceback.format_exc())
145
+ return f"였λ₯˜κ°€ λ°œμƒν–ˆμŠ΅λ‹ˆλ‹€: {str(e)}", "", "", "", ""
146
 
147
  def update_screenshot(url, last_url, force_update=False):
148
  print(f"Updating screenshot. Current URL: {url}, Last URL: {last_url}, Force update: {force_update}")
149
  if url and (url != last_url or force_update):
 
150
  screenshot = take_screenshot(url)
151
  print("Screenshot updated")
152
  return screenshot, url
 
158
  # 항상 κ°•μ œλ‘œ μ—…λ°μ΄νŠΈ
159
  return update_screenshot(url, last_url, force_update=True)
160
 
 
161
  def take_screenshot(url):
162
  try:
163
  print(f"Taking screenshot of URL: {url}")
 
172
  except Exception as e:
173
  print(f"Screenshot error: {str(e)}")
174
  return Image.new('RGB', (600, 360), color='lightgray')
 
175
 
176
  def generate_usage_guide(app_content):
177
  system_message = "당신은 Python μ½”λ“œλ₯Ό λΆ„μ„ν•˜μ—¬, ν™”λ©΄ 보듯이 이용 방법을 μ„€λͺ…ν•˜λŠ” AI μ‘°μˆ˜μž…λ‹ˆλ‹€. app.py μ½”λ“œλ₯Ό λ°”νƒ•μœΌλ‘œ μ½”λ“œμ— λŒ€ν•œ 언급은 μ œμ™Έν•˜κ³ , 이용자 κ΄€μ μ—μ„œ 1) κΈ°μ‘΄ μœ μ‚¬ 기술 방식괴 비ꡐ해 νŠΉμ§•, μž₯점에 λŒ€ν•΄ μΉœμ ˆν•˜κ³  μžμ„Έν•˜κ²Œ μƒμ„Έν•œ μ‚¬μš© 방법을 μ œκ³΅ν•΄μ£Όμ„Έμš”."
 
202
  width: 100% !important;
203
  margin-top: 5px !important;
204
  }
205
+ #info-output, #usage-guide, #tree-view, #list-view {
206
  height: 400px;
207
  overflow-y: auto;
208
  padding-right: 10px;
 
234
  space_rows.append((space_row, button, space))
235
 
236
  with gr.Column(scale=2):
237
+ with gr.Tabs():
238
+ with gr.TabItem("κΈ°λ³Έ 정보"):
239
+ with gr.Group(elem_classes="output-group"):
240
+ info_output = gr.Textbox(label="Space 정보 및 μš”μ•½", elem_id="info-output", lines=20, max_lines=30)
241
+ url_state = gr.State("")
242
+ last_url_state = gr.State("")
243
+
244
+ screenshot_output = gr.Image(type="pil", label="Live ν™”λ©΄", height=360, width=600)
245
+ refresh_button = gr.Button("πŸ”„ μ„œλΉ„μŠ€ ν™”λ©΄", elem_id="refresh-button")
246
+ manual_button = gr.Button("선택 μ„œλΉ„μŠ€ νŠΉμ§• 및 μ‚¬μš©λ²•", elem_id="manual-button")
247
+
248
+ with gr.Group(elem_classes="output-group"):
249
+ usage_guide = gr.Textbox(label="선택 μ„œλΉ„μŠ€ νŠΉμ§• 및 μ‚¬μš©λ²•", elem_id="usage-guide", visible=False, lines=20, max_lines=30)
250
+
251
+ with gr.Group(elem_classes="output-group"):
252
+ app_py_content = gr.Code(language="python", label="메인 μ†ŒμŠ€μ½”λ“œ", elem_id="app-py-content", lines=None, max_lines=None)
253
+
254
+ open_space_button = gr.Button("μ„ νƒν•œ Space μ—΄κΈ°", elem_id="open-space-button")
255
+
256
+ with gr.TabItem("μ½”λ“œ ꡬ쑰 뢄석"):
257
+ with gr.Group(elem_classes="output-group"):
258
+ tree_view = gr.Textbox(label="트리 ꡬ쑰", elem_id="tree-view", lines=30, max_lines=50)
259
+ with gr.Group(elem_classes="output-group"):
260
+ list_view = gr.Textbox(label="리슀트 ꡬ쑰", elem_id="list-view", lines=30, max_lines=50)
261
 
262
  update_trigger = gr.Button("Update Screenshot", visible=False)
263
 
264
  def on_select_with_link(space):
265
+ info, app_content, url, tree, list_structure = on_select(space)
266
  info += f"\n\nμ„ νƒν•œ Space URL: {url}"
267
+ return info, app_content, url, tree, list_structure
268
 
269
  for _, button, space in space_rows:
270
  button.click(
271
  lambda s=space: on_select_with_link(s),
272
  inputs=[],
273
+ outputs=[info_output, app_py_content, url_state, tree_view, list_view]
274
  ).then(
275
  update_screenshot,
276
  inputs=[url_state, last_url_state],
 
279
 
280
  def open_space_in_browser(url):
281
  if url:
282
+ import webbrowser
283
  webbrowser.open(url)
284
  return f"'{url}' μ£Όμ†Œκ°€ μƒˆ νƒ­μ—μ„œ μ—΄λ ΈμŠ΅λ‹ˆλ‹€."
285
  return "μ„ νƒλœ Spaceκ°€ μ—†μŠ΅λ‹ˆλ‹€."
 
290
  outputs=[gr.Textbox(label="μƒνƒœ λ©”μ‹œμ§€")]
291
  )
292
 
 
 
 
 
293
  refresh_button.click(
294
  refresh_screenshot,
295
  inputs=[url_state, last_url_state],
 
333
  demo.launch()
334
  except Exception as e:
335
  print(f"Error in main: {str(e)}")
336
+ print(traceback.format_exc())
337
+
338
+