ginipick commited on
Commit
4e8ad25
Β·
verified Β·
1 Parent(s): 5c92b1e

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +18 -73
app.py CHANGED
@@ -11,6 +11,7 @@ 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)
@@ -61,77 +62,15 @@ def get_space_structure(space_id: str) -> Dict:
61
  return {"error": f"API request error: {str(e)}"}
62
 
63
  def format_tree_structure(tree_data: Dict, indent: str = "") -> str:
64
- formatted = f"{indent}{'πŸ“' if tree_data['type'] == 'directory' else 'πŸ“„'} {tree_data['name']}\n"
65
- if tree_data["type"] == "directory":
66
- for child in sorted(tree_data.get("children", []), key=lambda x: (x["type"] != "directory", x["name"])):
 
 
 
67
  formatted += format_tree_structure(child, indent + " ")
68
  return formatted
69
 
70
-
71
-
72
-
73
-
74
-
75
-
76
- def analyze_space(url: str, progress=gr.Progress()):
77
- try:
78
- space_id = url.split('spaces/')[-1]
79
-
80
- progress(0.1, desc="파일 ꡬ쑰 뢄석 쀑...")
81
- tree_structure = get_space_structure(space_id)
82
- tree_view = format_tree_structure(tree_structure)
83
-
84
- progress(0.3, desc="app.py λ‚΄μš© κ°€μ Έμ˜€λŠ” 쀑...")
85
- app_content = get_file_content(space_id, "app.py")
86
-
87
- progress(0.4, desc="μ½”λ“œ μš”μ•½ 쀑...")
88
- summary = summarize_code(app_content)
89
-
90
- progress(0.6, desc="μ½”λ“œ 뢄석 쀑...")
91
- analysis = analyze_code(app_content)
92
-
93
- progress(0.8, desc="μ‚¬μš©λ²• μ„€λͺ… 생성 쀑...")
94
- usage = explain_usage(app_content)
95
-
96
- progress(1.0, desc="μ™„λ£Œ")
97
- return summary, analysis, usage, app_content, tree_view, tree_structure, space_id
98
- except Exception as e:
99
- print(f"Error in analyze_space: {str(e)}")
100
- print(traceback.format_exc())
101
- return f"였λ₯˜κ°€ λ°œμƒν–ˆμŠ΅λ‹ˆλ‹€: {str(e)}", "", "", "", "", None, ""
102
-
103
- def respond(
104
- message: str,
105
- history: List[Tuple[str, str]],
106
- system_message: str = "",
107
- max_tokens: int = 4000,
108
- temperature: float = 0.7,
109
- top_p: float = 0.9,
110
- ):
111
- system_prefix = """λ°˜λ“œμ‹œ ν•œκΈ€λ‘œ 닡변할것. λ„ˆλŠ” μ£Όμ–΄μ§„ μ†ŒμŠ€μ½”λ“œλ₯Ό 기반으둜 "μ„œλΉ„μŠ€ μ‚¬μš© μ„€λͺ… 및 μ•ˆλ‚΄, qnaλ₯Ό ν•˜λŠ” 역할이닀". μ•„μ£Ό μΉœμ ˆν•˜κ³  μžμ„Έν•˜κ²Œ 4000토큰 이상 μž‘μ„±ν•˜λΌ. λ„ˆλŠ” μ½”λ“œλ₯Ό 기반으둜 μ‚¬μš© μ„€λͺ… 및 질의 응닡을 μ§„ν–‰ν•˜λ©°, μ΄μš©μžμ—κ²Œ 도움을 μ£Όμ–΄μ•Ό ν•œλ‹€. μ΄μš©μžκ°€ κΆκΈˆν•΄ ν•  만 ν•œ λ‚΄μš©μ— μΉœμ ˆν•˜κ²Œ μ•Œλ €μ£Όλ„λ‘ ν•˜λΌ. μ½”λ“œ 전체 λ‚΄μš©μ— λŒ€ν•΄μ„œλŠ” λ³΄μ•ˆμ„ μœ μ§€ν•˜κ³ , ν‚€ κ°’ 및 μ—”λ“œν¬μΈνŠΈμ™€ ꡬ체적인 λͺ¨λΈμ€ κ³΅κ°œν•˜μ§€ 마라."""
112
-
113
- messages = [{"role": "system", "content": f"{system_prefix} {system_message}"}]
114
- for user, assistant in history:
115
- messages.append({"role": "user", "content": user})
116
- messages.append({"role": "assistant", "content": assistant})
117
- messages.append({"role": "user", "content": message})
118
-
119
- response = ""
120
- for message in hf_client.chat_completion(
121
- messages,
122
- max_tokens=max_tokens,
123
- stream=True,
124
- temperature=temperature,
125
- top_p=top_p,
126
- ):
127
- token = message.choices[0].delta.get('content', None)
128
- if token:
129
- response += token.strip("")
130
- yield response
131
-
132
-
133
-
134
-
135
  def summarize_code(app_content: str):
136
  system_message = "당신은 Python μ½”λ“œλ₯Ό λΆ„μ„ν•˜κ³  μš”μ•½ν•˜λŠ” AI μ‘°μˆ˜μž…λ‹ˆλ‹€. μ£Όμ–΄μ§„ μ½”λ“œλ₯Ό 3쀄 μ΄λ‚΄λ‘œ κ°„κ²°ν•˜κ²Œ μš”μ•½ν•΄μ£Όμ„Έμš”."
137
  user_message = f"λ‹€μŒ Python μ½”λ“œλ₯Ό 3쀄 μ΄λ‚΄λ‘œ μš”μ•½ν•΄μ£Όμ„Έμš”:\n\n{app_content}"
@@ -187,8 +126,14 @@ def analyze_space(url: str, progress=gr.Progress()):
187
  try:
188
  space_id = url.split('spaces/')[-1]
189
 
 
 
 
 
190
  progress(0.1, desc="파일 ꡬ쑰 뢄석 쀑...")
191
  tree_structure = get_space_structure(space_id)
 
 
192
  tree_view = format_tree_structure(tree_structure)
193
 
194
  progress(0.3, desc="app.py λ‚΄μš© κ°€μ Έμ˜€λŠ” 쀑...")
@@ -201,8 +146,6 @@ def analyze_space(url: str, progress=gr.Progress()):
201
  print(traceback.format_exc())
202
  return f"였λ₯˜κ°€ λ°œμƒν–ˆμŠ΅λ‹ˆλ‹€: {str(e)}", "", None, ""
203
 
204
-
205
-
206
  def create_ui():
207
  try:
208
  css = """
@@ -244,7 +187,7 @@ def create_ui():
244
  """
245
 
246
  with gr.Blocks(css=css, theme="Nymbo/Nymbo_Theme") as demo:
247
- gr.Markdown("# mouse lightning: HuggingFace")
248
 
249
  with gr.Tabs(elem_classes="main-tabs") as tabs:
250
  with gr.TabItem("뢄석"):
@@ -289,7 +232,9 @@ def create_ui():
289
  top_p = gr.Slider(minimum=0, maximum=1, value=0.9, label="Top P")
290
 
291
  examples = [
292
-
 
 
293
  ["μƒμ„Έν•œ μ‚¬μš© 방법을 마치 화면을 λ³΄λ©΄μ„œ μ„€λͺ…ν•˜λ“―이 4000 토큰 이상 μžμ„Ένžˆ μ„€λͺ…ν•˜λΌ"],
294
  ["FAQ 20건을 μƒμ„Έν•˜κ²Œ μž‘μ„±ν•˜λΌ. 4000토큰 이상 μ‚¬μš©ν•˜λΌ."],
295
  ["μ‚¬μš© 방법과 차별점, νŠΉμ§•, 강점을 μ€‘μ‹¬μœΌλ‘œ 4000 토큰 이상 유튜브 μ˜μƒ 슀크립트 ν˜•νƒœλ‘œ μž‘μ„±ν•˜λΌ"],
@@ -407,4 +352,4 @@ if __name__ == "__main__":
407
  )
408
  except Exception as e:
409
  print(f"Error in main: {str(e)}")
410
- print(traceback.format_exc())
 
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)
 
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}"
 
126
  try:
127
  space_id = url.split('spaces/')[-1]
128
 
129
+ # Space ID μœ νš¨μ„± 검사
130
+ if not re.match(r'^[\w.-]{1,96}$', space_id) or space_id.startswith(('-', '.')) or space_id.endswith(('-', '.')):
131
+ raise ValueError(f"Invalid Space ID: {space_id}")
132
+
133
  progress(0.1, desc="파일 ꡬ쑰 뢄석 쀑...")
134
  tree_structure = get_space_structure(space_id)
135
+ if "error" in tree_structure:
136
+ raise ValueError(tree_structure["error"])
137
  tree_view = format_tree_structure(tree_structure)
138
 
139
  progress(0.3, desc="app.py λ‚΄μš© κ°€μ Έμ˜€λŠ” 쀑...")
 
146
  print(traceback.format_exc())
147
  return f"였λ₯˜κ°€ λ°œμƒν–ˆμŠ΅λ‹ˆλ‹€: {str(e)}", "", None, ""
148
 
 
 
149
  def create_ui():
150
  try:
151
  css = """
 
187
  """
188
 
189
  with gr.Blocks(css=css, theme="Nymbo/Nymbo_Theme") as demo:
190
+ gr.Markdown("# HuggingFace Space Analyzer")
191
 
192
  with gr.Tabs(elem_classes="main-tabs") as tabs:
193
  with gr.TabItem("뢄석"):
 
232
  top_p = gr.Slider(minimum=0, maximum=1, value=0.9, label="Top P")
233
 
234
  examples = [
235
+ ["νŒ¨μ…˜ μ½”λ“œ μ‹€ν–‰"],
236
+ ["UHD 이미지 μ½”λ“œ μ‹€ν–‰"],
237
+ ["MixGEN μ½”λ“œ μ‹€ν–‰"],
238
  ["μƒμ„Έν•œ μ‚¬μš© 방법을 마치 화면을 λ³΄λ©΄μ„œ μ„€λͺ…ν•˜λ“―이 4000 토큰 이상 μžμ„Ένžˆ μ„€λͺ…ν•˜λΌ"],
239
  ["FAQ 20건을 μƒμ„Έν•˜κ²Œ μž‘μ„±ν•˜λΌ. 4000토큰 이상 μ‚¬μš©ν•˜λΌ."],
240
  ["μ‚¬μš© 방법과 차별점, νŠΉμ§•, 강점을 μ€‘μ‹¬μœΌλ‘œ 4000 토큰 이상 유튜브 μ˜μƒ 슀크립트 ν˜•νƒœλ‘œ μž‘μ„±ν•˜λΌ"],
 
352
  )
353
  except Exception as e:
354
  print(f"Error in main: {str(e)}")
355
+ print(traceback.format_exc())