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

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +60 -141
app.py CHANGED
@@ -21,59 +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_space_structure(space_id: str) -> Dict:
25
- try:
26
- # space_id์—์„œ owner์™€ repo_name์„ ๋ถ„๋ฆฌ
27
- owner, repo_name = space_id.split('/')
28
-
29
- # HfApi๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ ํŒŒ์ผ ๋ชฉ๋ก์„ ๊ฐ€์ ธ์˜ด
30
- files = hf_api.list_repo_files(repo_id=space_id, repo_type="space")
31
-
32
- # ํŒŒ์ผ ๋ชฉ๋ก์„ ํŠธ๋ฆฌ ๊ตฌ์กฐ๋กœ ๋ณ€ํ™˜
33
- tree = {"type": "directory", "path": "", "tree": []}
34
- for file in files:
35
- path_parts = file.split('/')
36
- current = tree
37
- for i, part in enumerate(path_parts):
38
- if i == len(path_parts) - 1: # ํŒŒ์ผ
39
- current["tree"].append({"type": "file", "path": part})
40
- else: # ๋””๋ ‰ํ† ๋ฆฌ
41
- found = False
42
- for item in current["tree"]:
43
- if item["type"] == "directory" and item["path"] == part:
44
- current = item
45
- found = True
46
- break
47
- if not found:
48
- new_dir = {"type": "directory", "path": part, "tree": []}
49
- current["tree"].append(new_dir)
50
- current = new_dir
51
-
52
- return tree
53
- except Exception as e:
54
- print(f"Error in get_space_structure: {str(e)}")
55
- return {"error": f"API request error: {str(e)}"}
56
-
57
- def format_tree_structure(tree_data: Dict, indent: str = "") -> str:
58
- formatted = ""
59
- for item in tree_data.get("tree", []):
60
- if item["type"] == "file":
61
- formatted += f"{indent}โ”œโ”€โ”€ {item['path']}\n"
62
- elif item["type"] == "directory":
63
- formatted += f"{indent}โ”œโ”€โ”€ {item['path']}/\n"
64
- formatted += format_tree_structure(item, indent + "โ”‚ ")
65
- return formatted
66
-
67
- def format_list_structure(tree_data: Dict) -> List[str]:
68
- formatted = []
69
- for item in tree_data.get("tree", []):
70
- if item["type"] == "file":
71
- formatted.append(item["path"])
72
- elif item["type"] == "directory":
73
- formatted.append(f"{item['path']}/")
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:
@@ -85,9 +32,9 @@ def get_app_py_content(space_id: str) -> str:
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},
@@ -95,65 +42,67 @@ def summarize_space(space_id: str) -> str:
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:
105
- print(f"Taking screenshot of URL: {url}")
106
- client = Client("ginipick/selenium-screenshot-gradio")
107
- result = client.predict(url=url, api_name="/predict")
108
- print(f"Screenshot result: {result}")
109
- if isinstance(result, str) and os.path.exists(result):
110
- return Image.open(result)
111
- else:
112
- print(f"Invalid result from API: {result}")
113
- return Image.new('RGB', (600, 360), color='lightgray')
 
 
 
 
 
 
 
 
114
  except Exception as e:
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;}
142
- .space-row {margin-bottom: 5px !important;}
143
- #refresh-button, #manual-button, #open-space-button {
144
- width: 100% !important;
145
- margin-top: 5px !important;
146
- }
147
- #info-output, #usage-guide, #tree-view, #list-view {
148
- height: 400px !important;
149
- overflow-y: auto !important;
150
- padding-right: 10px !important;
151
- }
152
- #app-py-content {
153
- height: auto !important;
154
- max-height: none !important;
155
- overflow-y: visible !important;
156
- }
157
  .output-group {
158
  border: 1px solid #ddd;
159
  border-radius: 5px;
@@ -164,63 +113,33 @@ def create_ui():
164
  overflow: auto !important;
165
  max-height: 400px !important;
166
  }
167
- .full-height {
168
- height: auto !important;
169
- max-height: none !important;
170
- }
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)
192
-
193
- open_space_button = gr.Button("์„ ํƒํ•œ Space ์—ด๊ธฐ", elem_id="open-space-button")
194
-
195
- with gr.TabItem("์ฝ”๋“œ ๊ตฌ์กฐ ๋ถ„์„"):
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
@@ -236,4 +155,4 @@ if __name__ == "__main__":
236
  demo.launch()
237
  except Exception as e:
238
  print(f"Error in main: {str(e)}")
239
- 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_app_py_content(space_id: str) -> str:
25
  app_py_url = f"https://huggingface.co/spaces/{space_id}/raw/main/app.py"
26
  try:
 
32
  except requests.RequestException:
33
  return f"Error fetching app.py content for space: {space_id}"
34
 
35
+ def summarize_code(app_content: str) -> str:
36
+ system_message = "๋‹น์‹ ์€ Python ์ฝ”๋“œ๋ฅผ ๋ถ„์„ํ•˜๊ณ  ์š”์•ฝํ•˜๋Š” AI ์กฐ์ˆ˜์ž…๋‹ˆ๋‹ค. ์ฃผ์–ด์ง„ ์ฝ”๋“œ๋ฅผ 3์ค„ ์ด๋‚ด๋กœ ๊ฐ„๊ฒฐํ•˜๊ฒŒ ์š”์•ฝํ•ด์ฃผ์„ธ์š”."
37
+ user_message = f"๋‹ค์Œ Python ์ฝ”๋“œ๋ฅผ 3์ค„ ์ด๋‚ด๋กœ ์š”์•ฝํ•ด์ฃผ์„ธ์š”:\n\n{app_content}"
38
 
39
  messages = [
40
  {"role": "system", "content": system_message},
 
42
  ]
43
 
44
  try:
45
+ response = hf_client.chat_completion(messages, max_tokens=200, temperature=0.7)
46
  return response.choices[0].message.content
47
  except Exception as e:
48
  return f"์š”์•ฝ ์ƒ์„ฑ ์ค‘ ์˜ค๋ฅ˜ ๋ฐœ์ƒ: {str(e)}"
49
 
50
+ def analyze_code(app_content: str) -> str:
51
+ system_message = """๋‹น์‹ ์€ Python ์ฝ”๋“œ๋ฅผ ๋ถ„์„ํ•˜๋Š” AI ์กฐ์ˆ˜์ž…๋‹ˆ๋‹ค. ์ฃผ์–ด์ง„ ์ฝ”๋“œ๋ฅผ ๋ถ„์„ํ•˜์—ฌ ๋‹ค์Œ ํ•ญ๋ชฉ์— ๋Œ€ํ•ด ์„ค๋ช…ํ•ด์ฃผ์„ธ์š”:
52
+ A. ๋ฐฐ๊ฒฝ ๋ฐ ํ•„์š”์„ฑ
53
+ B. ๊ธฐ๋Šฅ์  ํšจ์šฉ์„ฑ ๋ฐ ๊ฐ€์น˜
54
+ C. ํŠน์žฅ์ 
55
+ D. ์ ์šฉ ๋Œ€์ƒ ๋ฐ ํƒ€๊ฒŸ
56
+ E. ๊ธฐ๋Œ€ํšจ๊ณผ
57
+ ๊ธฐ์กด ๋ฐ ์œ ์‚ฌ ํ”„๋กœ์ ํŠธ์™€ ๋น„๊ตํ•˜์—ฌ ๋ถ„์„ํ•ด์ฃผ์„ธ์š”."""
58
+ user_message = f"๋‹ค์Œ Python ์ฝ”๋“œ๋ฅผ ๋ถ„์„ํ•ด์ฃผ์„ธ์š”:\n\n{app_content}"
59
+
60
+ messages = [
61
+ {"role": "system", "content": system_message},
62
+ {"role": "user", "content": user_message}
63
+ ]
64
+
65
  try:
66
+ response = hf_client.chat_completion(messages, max_tokens=1000, temperature=0.7)
67
+ return response.choices[0].message.content
68
+ except Exception as e:
69
+ return f"๋ถ„์„ ์ƒ์„ฑ ์ค‘ ์˜ค๋ฅ˜ ๋ฐœ์ƒ: {str(e)}"
70
+
71
+ def explain_usage(app_content: str) -> str:
72
+ system_message = "๋‹น์‹ ์€ Python ์ฝ”๋“œ๋ฅผ ๋ถ„์„ํ•˜์—ฌ ์‚ฌ์šฉ๋ฒ•์„ ์„ค๋ช…ํ•˜๋Š” AI ์กฐ์ˆ˜์ž…๋‹ˆ๋‹ค. ์ฃผ์–ด์ง„ ์ฝ”๋“œ๋ฅผ ๋ฐ”ํƒ•์œผ๋กœ ๋งˆ์น˜ ํ™”๋ฉด์„ ๋ณด๋Š” ๊ฒƒ์ฒ˜๋Ÿผ ์‚ฌ์šฉ๋ฒ•์„ ์ƒ์„ธํžˆ ์„ค๋ช…ํ•ด์ฃผ์„ธ์š”."
73
+ user_message = f"๋‹ค์Œ Python ์ฝ”๋“œ์˜ ์‚ฌ์šฉ๋ฒ•์„ ์„ค๋ช…ํ•ด์ฃผ์„ธ์š”:\n\n{app_content}"
74
+
75
+ messages = [
76
+ {"role": "system", "content": system_message},
77
+ {"role": "user", "content": user_message}
78
+ ]
79
+
80
+ try:
81
+ response = hf_client.chat_completion(messages, max_tokens=800, temperature=0.7)
82
+ return response.choices[0].message.content
83
  except Exception as e:
84
+ return f"์‚ฌ์šฉ๋ฒ• ์„ค๋ช… ์ƒ์„ฑ ์ค‘ ์˜ค๋ฅ˜ ๋ฐœ์ƒ: {str(e)}"
 
85
 
86
  def analyze_space(url: str):
87
  try:
88
  # URL์—์„œ space_id ์ถ”์ถœ
89
  space_id = url.split('spaces/')[-1]
90
 
 
91
  app_content = get_app_py_content(space_id)
92
+ summary = summarize_code(app_content)
93
+ analysis = analyze_code(app_content)
94
+ usage = explain_usage(app_content)
 
 
95
 
96
+ return summary, analysis, usage, app_content
97
  except Exception as e:
98
  print(f"Error in analyze_space: {str(e)}")
99
  print(traceback.format_exc())
100
+ return f"์˜ค๋ฅ˜๊ฐ€ ๋ฐœ์ƒํ–ˆ์Šต๋‹ˆ๋‹ค: {str(e)}", "", "", ""
101
 
102
  def create_ui():
103
  try:
104
  css = """
105
  footer {visibility: hidden;}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
106
  .output-group {
107
  border: 1px solid #ddd;
108
  border-radius: 5px;
 
113
  overflow: auto !important;
114
  max-height: 400px !important;
115
  }
 
 
 
 
116
  """
117
 
118
  with gr.Blocks(css=css, theme="Nymbo/Nymbo_Theme") as demo:
119
  gr.Markdown("# HuggingFace Space Analyzer")
120
 
121
  with gr.Row():
122
+ with gr.Column(scale=6): # ์™ผ์ชฝ 60%
123
+ url_input = gr.Textbox(label="HuggingFace Space URL")
124
+ analyze_button = gr.Button("๋ถ„์„")
125
+
126
+ with gr.Group(elem_classes="output-group scroll-lock"):
127
+ summary_output = gr.Textbox(label="์š”์•ฝ (3์ค„ ์ด๋‚ด)", lines=3)
128
+
129
+ with gr.Group(elem_classes="output-group scroll-lock"):
130
+ analysis_output = gr.Textbox(label="๋ถ„์„", lines=15)
131
+
132
+ with gr.Group(elem_classes="output-group scroll-lock"):
133
+ usage_output = gr.Textbox(label="์‚ฌ์šฉ๋ฒ•", lines=10)
134
+
135
+ with gr.Column(scale=4): # ์˜ค๋ฅธ์ชฝ 40%
136
+ with gr.Group(elem_classes="output-group scroll-lock"):
137
+ app_py_content = gr.Code(language="python", label="๋ฉ”์ธ ์†Œ์Šค์ฝ”๋“œ", lines=30)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
138
 
139
  analyze_button.click(
140
  analyze_space,
141
  inputs=[url_input],
142
+ outputs=[summary_output, analysis_output, usage_output, app_py_content]
 
 
 
 
 
 
 
 
 
 
 
 
143
  )
144
 
145
  return demo
 
155
  demo.launch()
156
  except Exception as e:
157
  print(f"Error in main: {str(e)}")
158
+ print(traceback.format_exc())