ginipick commited on
Commit
c7cd542
·
verified ·
1 Parent(s): 984ff0a

Delete app-backup10.py

Browse files
Files changed (1) hide show
  1. app-backup10.py +0 -399
app-backup10.py DELETED
@@ -1,399 +0,0 @@
1
- import gradio as gr
2
- from huggingface_hub import InferenceClient, HfApi
3
- import os
4
- import requests
5
- from typing import List, Dict, Union, Tuple
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
- import json
14
- import re
15
-
16
- HF_TOKEN = os.getenv("HF_TOKEN")
17
- hf_client = InferenceClient("CohereForAI/c4ai-command-r-plus-08-2024", token=HF_TOKEN)
18
- hf_api = HfApi(token=HF_TOKEN)
19
-
20
- def get_headers():
21
- if not HF_TOKEN:
22
- raise ValueError("Hugging Face token not found in environment variables")
23
- return {"Authorization": f"Bearer {HF_TOKEN}"}
24
-
25
- def get_file_content(space_id: str, file_path: str) -> str:
26
- file_url = f"https://huggingface.co/spaces/{space_id}/raw/main/{file_path}"
27
- try:
28
- response = requests.get(file_url, headers=get_headers())
29
- if response.status_code == 200:
30
- return response.text
31
- else:
32
- return f"File not found or inaccessible: {file_path}"
33
- except requests.RequestException:
34
- return f"Error fetching content for file: {file_path}"
35
-
36
- def get_space_structure(space_id: str) -> Dict:
37
- try:
38
- files = hf_api.list_repo_files(repo_id=space_id, repo_type="space")
39
-
40
- tree = {"type": "directory", "path": "", "name": space_id, "children": []}
41
- for file in files:
42
- path_parts = file.split('/')
43
- current = tree
44
- for i, part in enumerate(path_parts):
45
- if i == len(path_parts) - 1: # 파일
46
- current["children"].append({"type": "file", "path": file, "name": part})
47
- else: # 디렉토리
48
- found = False
49
- for child in current["children"]:
50
- if child["type"] == "directory" and child["name"] == part:
51
- current = child
52
- found = True
53
- break
54
- if not found:
55
- new_dir = {"type": "directory", "path": '/'.join(path_parts[:i+1]), "name": part, "children": []}
56
- current["children"].append(new_dir)
57
- current = new_dir
58
-
59
- return tree
60
- except Exception as e:
61
- print(f"Error in get_space_structure: {str(e)}")
62
- return {"error": f"API request error: {str(e)}"}
63
-
64
- def format_tree_structure(tree_data: Dict, indent: str = "") -> str:
65
- if "error" in tree_data:
66
- return tree_data["error"]
67
-
68
- formatted = f"{indent}{'📁' if tree_data.get('type') == 'directory' else '📄'} {tree_data.get('name', 'Unknown')}\n"
69
- if tree_data.get("type") == "directory":
70
- for child in sorted(tree_data.get("children", []), key=lambda x: (x.get("type", "") != "directory", x.get("name", ""))):
71
- formatted += format_tree_structure(child, indent + " ")
72
- return formatted
73
-
74
- def summarize_code(app_content: str):
75
- system_message = "당신은 Python 코드를 분석하고 요약하는 AI 조수입니다. 주어진 코드를 3줄 이내로 간결하게 요약해주세요."
76
- user_message = f"다음 Python 코드를 3줄 이내로 요약해주세요:\n\n{app_content}"
77
-
78
- messages = [
79
- {"role": "system", "content": system_message},
80
- {"role": "user", "content": user_message}
81
- ]
82
-
83
- try:
84
- response = hf_client.chat_completion(messages, max_tokens=200, temperature=0.7)
85
- return response.choices[0].message.content
86
- except Exception as e:
87
- return f"요약 생성 중 오류 발생: {str(e)}"
88
-
89
- def analyze_code(app_content: str):
90
- system_message = """당신은 Python 코드를 분석하는 AI 조수입니다. 주어진 코드를 분석하여 다음 항목에 대해 설명해주세요:
91
- A. 배경 및 필요성
92
- B. 기능적 효용성 및 가치
93
- C. 특장점
94
- D. 적용 대상 및 타겟
95
- E. 기대효과
96
- 기존 및 유사 프로젝트와 비교하여 분석해주세요. Markdown 형식으로 출력하세요."""
97
- user_message = f"다음 Python 코드를 분석해주세요:\n\n{app_content}"
98
-
99
- messages = [
100
- {"role": "system", "content": system_message},
101
- {"role": "user", "content": user_message}
102
- ]
103
-
104
- try:
105
- response = hf_client.chat_completion(messages, max_tokens=1000, temperature=0.7)
106
- return response.choices[0].message.content
107
- except Exception as e:
108
- return f"분석 생성 중 오류 발생: {str(e)}"
109
-
110
- def explain_usage(app_content: str):
111
- system_message = "당신은 Python 코드를 분석하여 사용법을 설명하는 AI 조수입니다. 주어진 코드를 바탕으로 마치 화면을 보는 것처럼 사용법을 상세히 설명해주세요. Markdown 형식으로 출력하세요."
112
- user_message = f"다음 Python 코드의 사용법을 설명해주세요:\n\n{app_content}"
113
-
114
- messages = [
115
- {"role": "system", "content": system_message},
116
- {"role": "user", "content": user_message}
117
- ]
118
-
119
- try:
120
- response = hf_client.chat_completion(messages, max_tokens=800, temperature=0.7)
121
- return response.choices[0].message.content
122
- except Exception as e:
123
- return f"사용법 설명 생성 중 오류 발생: {str(e)}"
124
-
125
- def adjust_lines_for_code(code_content: str, min_lines: int = 10, max_lines: int = 100) -> int:
126
- """
127
- 코드 내용에 따라 lines 수를 동적으로 조정합니다.
128
-
129
- Parameters:
130
- - code_content (str): 코드 텍스트 내용
131
- - min_lines (int): 최소 lines 수
132
- - max_lines (int): 최대 lines 수
133
-
134
- Returns:
135
- - int: 설정된 lines 수
136
- """
137
- # 코드의 줄 수 계산
138
- num_lines = len(code_content.split('\n'))
139
- # 줄 수가 min_lines보다 적다면 min_lines 사용, max_lines보다 크면 max_lines 사용
140
- return min(max(num_lines, min_lines), max_lines)
141
-
142
- def analyze_space(url: str, progress=gr.Progress()):
143
- try:
144
- space_id = url.split('spaces/')[-1]
145
-
146
- # Space ID 유효성 검사 수정
147
- if not re.match(r'^[\w.-]+/[\w.-]+$', space_id):
148
- raise ValueError(f"Invalid Space ID format: {space_id}")
149
-
150
- progress(0.1, desc="파일 구조 분석 중...")
151
- tree_structure = get_space_structure(space_id)
152
- if "error" in tree_structure:
153
- raise ValueError(tree_structure["error"])
154
- tree_view = format_tree_structure(tree_structure)
155
-
156
- progress(0.3, desc="app.py 내용 가져오는 중...")
157
- app_content = get_file_content(space_id, "app.py")
158
-
159
- progress(0.5, desc="코드 요약 중...")
160
- summary = summarize_code(app_content)
161
-
162
- progress(0.7, desc="코드 분석 중...")
163
- analysis = analyze_code(app_content)
164
-
165
- progress(0.9, desc="사용법 설명 생성 중...")
166
- usage = explain_usage(app_content)
167
-
168
- # 줄 수 계산하여 lines 설정
169
- app_py_lines = adjust_lines_for_code(app_content)
170
-
171
- progress(1.0, desc="완료")
172
- return app_content, tree_view, tree_structure, space_id, summary, analysis, usage, app_py_lines
173
- except Exception as e:
174
- print(f"Error in analyze_space: {str(e)}")
175
- print(traceback.format_exc())
176
- return f"오류가 발생했습니다: {str(e)}", "", None, "", "", "", "", 10
177
-
178
- def respond(
179
- message: str,
180
- history: List[Tuple[str, str]],
181
- system_message: str = "",
182
- max_tokens: int = 1024,
183
- temperature: float = 0.7,
184
- top_p: float = 0.9,
185
- ):
186
- system_prefix = """당신은 허깅페이스에 특화된 AI 코딩 전문가입니다. 사용자의 질문에 친절하고 상세하게 답변해주세요.
187
- Gradio 특성을 정확히 인식하고 Requirements.txt 누락없이 코딩과 오류를 해결해야 합니다.
188
- 항상 정확하고 유용한 정보를 제공하도록 노력하세요."""
189
-
190
- messages = [{"role": "system", "content": f"{system_prefix} {system_message}"}]
191
- for user_msg, assistant_msg in history:
192
- messages.append({"role": "user", "content": user_msg})
193
- if assistant_msg:
194
- messages.append({"role": "assistant", "content": assistant_msg})
195
- messages.append({"role": "user", "content": message})
196
-
197
- response = ""
198
- for message in hf_client.chat_completion(
199
- messages,
200
- max_tokens=max_tokens,
201
- stream=True,
202
- temperature=temperature,
203
- top_p=top_p,
204
- ):
205
- token = message.choices[0].delta.get('content', None)
206
- if token:
207
- response += token.strip("")
208
- yield response
209
-
210
-
211
- def create_ui():
212
- try:
213
- css = """
214
- footer {visibility: hidden;}
215
- .output-group {
216
- border: 1px solid #ddd;
217
- border-radius: 5px;
218
- padding: 10px;
219
- margin-bottom: 20px;
220
- }
221
- .scroll-lock {
222
- overflow-y: auto !important;
223
- max-height: calc((100vh - 200px) / 5) !important;
224
- }
225
- .tree-view-scroll {
226
- overflow-y: auto !important;
227
- max-height: calc((100vh - 200px) / 2) !important;
228
- }
229
- .full-height {
230
- height: calc(200em * 1.2) !important;
231
- overflow-y: auto !important;
232
- }
233
- .code-box {
234
- overflow-x: auto !important;
235
- overflow-y: auto !important;
236
- white-space: pre !important;
237
- word-wrap: normal !important;
238
- height: 100% !important;
239
- }
240
- .code-box > div {
241
- min-width: 100% !important;
242
- }
243
- .code-box > div > textarea {
244
- word-break: normal !important;
245
- overflow-wrap: normal !important;
246
- }
247
- .tab-nav {
248
- background-color: #2c3e50;
249
- border-radius: 5px 5px 0 0;
250
- overflow: hidden;
251
- }
252
- .tab-nav button {
253
- color: #ecf0f1 !important;
254
- background-color: #34495e;
255
- border: none;
256
- padding: 10px 20px;
257
- margin: 0;
258
- transition: background-color 0.3s;
259
- font-size: 16px;
260
- font-weight: bold;
261
- }
262
- .tab-nav button:hover {
263
- background-color: #2980b9;
264
- }
265
- .tab-nav button.selected {
266
- color: #2c3e50 !important;
267
- background-color: #ecf0f1;
268
- }
269
- input[type="text"], textarea {
270
- color: #2c3e50 !important;
271
- background-color: #ecf0f1 !important;
272
- }
273
- """
274
-
275
- with gr.Blocks(theme="Nymbo/Nymbo_Theme", css=css) as demo:
276
- gr.Markdown("# Mouse: HuggingFace")
277
-
278
- with gr.Tabs() as tabs:
279
- with gr.TabItem("분석"):
280
- with gr.Row():
281
- with gr.Column(scale=6): # 왼쪽 60%
282
- url_input = gr.Textbox(label="HuggingFace Space URL")
283
- analyze_button = gr.Button("분석")
284
-
285
- with gr.Group(elem_classes="output-group scroll-lock"):
286
- summary_output = gr.Markdown(label="요약 (3줄 이내)")
287
-
288
- with gr.Group(elem_classes="output-group scroll-lock"):
289
- analysis_output = gr.Markdown(label="분석")
290
-
291
- with gr.Group(elem_classes="output-group scroll-lock"):
292
- usage_output = gr.Markdown(label="사용법")
293
-
294
- with gr.Group(elem_classes="output-group tree-view-scroll"): # 트리 뷰 스크롤 추가
295
- tree_view_output = gr.Textbox(label="파일 구조 (Tree View)", lines=30)
296
-
297
- with gr.Column(scale=4): # 오른쪽 40%
298
- with gr.Group(elem_classes="output-group full-height"):
299
- code_tabs = gr.Tabs()
300
- with code_tabs:
301
- app_py_tab = gr.TabItem("app.py")
302
- with app_py_tab:
303
- app_py_content = gr.Code(
304
- language="python",
305
- label="app.py",
306
- lines=200,
307
- elem_classes="full-height code-box"
308
- )
309
- requirements_tab = gr.TabItem("requirements.txt")
310
- with requirements_tab:
311
- requirements_content = gr.Textbox(
312
- label="requirements.txt",
313
- lines=200,
314
- elem_classes="full-height code-box"
315
- )
316
-
317
- with gr.TabItem("AI 코딩"):
318
- chatbot = gr.Chatbot(label="대화")
319
-
320
- msg = gr.Textbox(label="메시지")
321
-
322
- # 숨겨진 상태로 파라미터 설정
323
- max_tokens = gr.Slider(minimum=1, maximum=8000, value=4000, label="Max Tokens", visible=False)
324
- temperature = gr.Slider(minimum=0, maximum=1, value=0.7, label="Temperature", visible=False)
325
- top_p = gr.Slider(minimum=0, maximum=1, value=0.9, label="Top P", visible=False)
326
-
327
- examples = [
328
- ["상세한 사용 방법을 마치 화면을 보면서 설명하듯이 4000 토큰 이상 자세히 설명하라"],
329
- ["FAQ 20건을 상세하게 작성하라. 4000토큰 이상 사용하라."],
330
- ["사용 방법과 차별점, 특징, 강점을 중심으로 4000 토큰 이상 유튜브 영상 스크립트 형태로 작성하라"],
331
- ["본 서비스를 SEO 최적화하여 블로그 포스트(배경 및 필요성, 기존 유사 서비스와 비교하여 특장점, 활용처, 가치, 기대효과, 결론을 포함)로 4000 토큰 이상 작성하라"],
332
- ["특허 출원에 활용할 기술 및 비즈니스모델 측면을 포함하여 특허 출원서 구성에 맞게 혁신적인 창의 발명 내용을 중심으로 4000토큰 이상 작성하라."],
333
- ["계속 이어서 답변하라"],
334
- ]
335
-
336
- gr.Examples(examples, inputs=msg)
337
-
338
- def respond_wrapper(message, chat_history, max_tokens, temperature, top_p):
339
- bot_message = ""
340
- for response in respond(message, chat_history, max_tokens=max_tokens, temperature=temperature, top_p=top_p):
341
- bot_message = response # 마지막 응답을 저장
342
- yield "", chat_history + [(message, bot_message)]
343
-
344
- chat_history.append((message, bot_message))
345
- return "", chat_history
346
-
347
-
348
-
349
- msg.submit(respond_wrapper, [msg, chatbot, max_tokens, temperature, top_p], [msg, chatbot])
350
-
351
- space_id_state = gr.State()
352
- tree_structure_state = gr.State()
353
- app_py_content_lines = gr.State()
354
-
355
- analyze_button.click(
356
- analyze_space,
357
- inputs=[url_input],
358
- outputs=[app_py_content, tree_view_output, tree_structure_state, space_id_state, summary_output, analysis_output, usage_output, app_py_content_lines]
359
- ).then(
360
- lambda space_id: get_file_content(space_id, "requirements.txt"),
361
- inputs=[space_id_state],
362
- outputs=[requirements_content]
363
- )
364
-
365
- # lines 수를 동적으로 설정
366
- app_py_content.change(lambda lines: gr.update(lines=lines), inputs=[app_py_content_lines], outputs=[app_py_content])
367
-
368
- return demo
369
-
370
- except Exception as e:
371
- print(f"Error in create_ui: {str(e)}")
372
- print(traceback.format_exc())
373
- raise
374
-
375
-
376
- if __name__ == "__main__":
377
- try:
378
- print("Starting HuggingFace Space Analyzer...")
379
- demo = create_ui()
380
- print("UI created successfully.")
381
-
382
- print("Configuring Gradio queue...")
383
- demo.queue()
384
- print("Gradio queue configured.")
385
-
386
- print("Launching Gradio app...")
387
- demo.launch(
388
- server_name="0.0.0.0",
389
- server_port=7860,
390
- share=False,
391
- debug=True,
392
- show_api=False
393
- )
394
- print("Gradio app launched successfully.")
395
- except Exception as e:
396
- print(f"Error in main: {str(e)}")
397
- print("Detailed error information:")
398
- print(traceback.format_exc())
399
- raise