Spaces:
Running
Running
Update app.py
Browse files
app.py
CHANGED
@@ -8,11 +8,11 @@ import requests
|
|
8 |
import re
|
9 |
import traceback
|
10 |
|
11 |
-
# HuggingFace
|
12 |
HF_TOKEN = os.getenv("HF_TOKEN")
|
13 |
hf_api = HfApi(token=HF_TOKEN)
|
14 |
|
15 |
-
# Gemini 2.0 Flash Thinking
|
16 |
GEMINI_API_KEY = os.getenv("GEMINI_API_KEY")
|
17 |
genai.configure(api_key=GEMINI_API_KEY)
|
18 |
model = genai.GenerativeModel("gemini-2.0-flash-thinking-exp-01-21")
|
@@ -41,7 +41,7 @@ def get_space_structure(space_id: str) -> Dict:
|
|
41 |
path_parts = file.split('/')
|
42 |
current = tree
|
43 |
for i, part in enumerate(path_parts):
|
44 |
-
if i == len(path_parts) - 1: #
|
45 |
current["children"].append({"type": "file", "path": file, "name": part})
|
46 |
else:
|
47 |
found = False
|
@@ -78,55 +78,52 @@ def analyze_space(url: str, progress=gr.Progress()):
|
|
78 |
if not re.match(r'^[\w.-]+/[\w.-]+$', space_id):
|
79 |
raise ValueError(f"Invalid Space ID format: {space_id}")
|
80 |
|
81 |
-
progress(0.1, desc="
|
82 |
tree_structure = get_space_structure(space_id)
|
83 |
if "error" in tree_structure:
|
84 |
raise ValueError(tree_structure["error"])
|
85 |
tree_view = format_tree_structure(tree_structure)
|
86 |
|
87 |
-
progress(0.3, desc="
|
88 |
app_content = get_file_content(space_id, "app.py")
|
89 |
|
90 |
-
progress(0.5, desc="
|
91 |
summary = summarize_code(app_content)
|
92 |
|
93 |
-
progress(0.7, desc="
|
94 |
analysis = analyze_code(app_content)
|
95 |
|
96 |
-
progress(0.9, desc="
|
97 |
usage = explain_usage(app_content)
|
98 |
|
99 |
lines_for_app_py = adjust_lines_for_code(app_content)
|
100 |
-
progress(1.0, desc="
|
101 |
|
102 |
return app_content, tree_view, tree_structure, space_id, summary, analysis, usage, lines_for_app_py
|
103 |
|
104 |
except Exception as e:
|
105 |
print(f"Error in analyze_space: {str(e)}")
|
106 |
print(traceback.format_exc())
|
107 |
-
return f"
|
108 |
-
|
109 |
|
110 |
# --------------------------------------------------
|
111 |
-
# Gemini 2.0 Flash Thinking
|
112 |
# --------------------------------------------------
|
113 |
from gradio import ChatMessage
|
114 |
|
115 |
def format_chat_history(messages: List[ChatMessage]) -> List[Dict]:
|
116 |
"""
|
117 |
-
|
118 |
-
(
|
119 |
"""
|
120 |
formatted = []
|
121 |
for m in messages:
|
122 |
-
if hasattr(m, "metadata") and m.metadata: # 'Thinking'
|
123 |
continue
|
124 |
role = "assistant" if m.role == "assistant" else "user"
|
125 |
formatted.append({"role": role, "parts": [m.content or ""]})
|
126 |
return formatted
|
127 |
|
128 |
-
import google.generativeai as genai
|
129 |
-
|
130 |
def gemini_chat_completion(system_message: str, user_message: str, max_tokens: int = 200, temperature: float = 0.7) -> str:
|
131 |
init_msgs = [
|
132 |
ChatMessage(role="system", content=system_message),
|
@@ -144,60 +141,52 @@ def gemini_chat_completion(system_message: str, user_message: str, max_tokens: i
|
|
144 |
final += parts[0].text
|
145 |
return final.strip()
|
146 |
except Exception as e:
|
147 |
-
return f"
|
148 |
-
|
149 |
|
150 |
def summarize_code(app_content: str):
|
151 |
-
system_msg = "
|
152 |
-
user_msg = f"
|
153 |
try:
|
154 |
return gemini_chat_completion(system_msg, user_msg, max_tokens=200, temperature=0.7)
|
155 |
except Exception as e:
|
156 |
-
return f"
|
157 |
|
158 |
def analyze_code(app_content: str):
|
159 |
system_msg = (
|
160 |
-
"You are
|
161 |
-
"
|
162 |
-
"
|
163 |
-
"
|
164 |
-
"
|
165 |
-
"
|
166 |
-
"
|
167 |
-
"D. μ μ© λμ λ° νκ²\n"
|
168 |
-
"E. κΈ°λν¨κ³Ό\n"
|
169 |
-
"κΈ°μ‘΄ λ° μ μ¬ νλ‘μ νΈμ λΉκ΅νμ¬ λΆμν΄μ£ΌμΈμ. Markdown νμμΌλ‘ μΆλ ₯νμΈμ."
|
170 |
)
|
171 |
-
user_msg = f"
|
172 |
try:
|
173 |
return gemini_chat_completion(system_msg, user_msg, max_tokens=1000, temperature=0.7)
|
174 |
except Exception as e:
|
175 |
-
return f"
|
176 |
|
177 |
def explain_usage(app_content: str):
|
178 |
system_msg = (
|
179 |
-
"You are
|
180 |
-
"and deliberate with yourself via systematic reasoning processes to help come to a correct solution prior to answering. "
|
181 |
-
"You should enclose your thoughts and internal monologue inside tags, and then provide your solution or response to the problem. "
|
182 |
-
"λΉμ μ Python μ½λλ₯Ό λΆμνμ¬ μ¬μ©λ²μ μ€λͺ
νλ AI μ‘°μμ
λλ€. μ£Όμ΄μ§ μ½λλ₯Ό λ°νμΌλ‘ λ§μΉ νλ©΄μ 보λ κ²μ²λΌ μ¬μ©λ²μ μμΈν μ€λͺ
ν΄μ£ΌμΈμ. Markdown νμμΌλ‘ μΆλ ₯νμΈμ."
|
183 |
)
|
184 |
-
user_msg = f"
|
185 |
try:
|
186 |
return gemini_chat_completion(system_msg, user_msg, max_tokens=800, temperature=0.7)
|
187 |
except Exception as e:
|
188 |
-
return f"
|
189 |
|
190 |
def stream_gemini_response(user_message: str, conversation_state: List[ChatMessage]) -> Iterator[List[ChatMessage]]:
|
191 |
"""
|
192 |
-
|
193 |
-
|
194 |
"""
|
195 |
if not user_message.strip():
|
196 |
-
# λΉ μ
λ ₯ μ²λ¦¬: μλ΄ λ©μμ§ νμ
|
197 |
conversation_state.append(
|
198 |
ChatMessage(
|
199 |
role="assistant",
|
200 |
-
content="
|
201 |
)
|
202 |
)
|
203 |
yield conversation_state
|
@@ -273,7 +262,7 @@ def stream_gemini_response(user_message: str, conversation_state: List[ChatMessa
|
|
273 |
|
274 |
def convert_for_messages_format(messages: List[ChatMessage]) -> List[Dict[str, str]]:
|
275 |
"""
|
276 |
-
|
277 |
"""
|
278 |
output = []
|
279 |
for msg in messages:
|
@@ -285,14 +274,14 @@ def user_submit_message(msg: str, conversation_state: List[ChatMessage]):
|
|
285 |
return "", conversation_state
|
286 |
|
287 |
def respond_wrapper(message: str, conversation_state: List[ChatMessage], max_tokens, temperature, top_p):
|
288 |
-
#
|
289 |
last_user_message = ""
|
290 |
for msg in reversed(conversation_state):
|
291 |
if msg.role == "user":
|
292 |
last_user_message = msg.content
|
293 |
break
|
294 |
|
295 |
-
#
|
296 |
for updated_messages in stream_gemini_response(last_user_message, conversation_state):
|
297 |
yield "", convert_for_messages_format(updated_messages)
|
298 |
|
@@ -320,16 +309,16 @@ def create_ui():
|
|
320 |
gr.Markdown("# π MOUSE: Space Research Thinking")
|
321 |
|
322 |
with gr.Tabs():
|
323 |
-
with gr.TabItem("π
|
324 |
with gr.Row():
|
325 |
with gr.Column():
|
326 |
-
url_input = gr.Textbox(label="π HuggingFace Space URL", placeholder="
|
327 |
-
analyze_button = gr.Button("
|
328 |
|
329 |
-
summary_output = gr.Markdown(label="π
|
330 |
-
analysis_output = gr.Markdown(label="π
|
331 |
-
usage_output = gr.Markdown(label="π
|
332 |
-
tree_view_output = gr.Textbox(label="π
|
333 |
|
334 |
with gr.Column():
|
335 |
code_tabs = gr.Tabs()
|
@@ -346,16 +335,16 @@ def create_ui():
|
|
346 |
lines=50
|
347 |
)
|
348 |
|
349 |
-
with gr.TabItem("π€ AI
|
350 |
-
gr.Markdown("## π¬
|
351 |
chatbot = gr.Chatbot(
|
352 |
-
label="
|
353 |
height=400,
|
354 |
type="messages"
|
355 |
)
|
356 |
msg = gr.Textbox(
|
357 |
-
label="
|
358 |
-
placeholder="
|
359 |
)
|
360 |
max_tokens = gr.Slider(
|
361 |
minimum=1, maximum=8000,
|
@@ -374,12 +363,12 @@ def create_ui():
|
|
374 |
)
|
375 |
|
376 |
examples = [
|
377 |
-
["
|
378 |
-
["
|
379 |
-
["
|
380 |
-
["
|
381 |
-
["
|
382 |
-
["
|
383 |
]
|
384 |
gr.Examples(examples, inputs=msg)
|
385 |
|
@@ -401,7 +390,7 @@ def create_ui():
|
|
401 |
"Discover recommended HuggingFace Spaces [here](https://huggingface.co/spaces/openfree/Korean-Leaderboard)."
|
402 |
)
|
403 |
|
404 |
-
#
|
405 |
space_id_state = gr.State()
|
406 |
tree_structure_state = gr.State()
|
407 |
app_py_content_lines = gr.State()
|
|
|
8 |
import re
|
9 |
import traceback
|
10 |
|
11 |
+
# HuggingFace API key for space analysis
|
12 |
HF_TOKEN = os.getenv("HF_TOKEN")
|
13 |
hf_api = HfApi(token=HF_TOKEN)
|
14 |
|
15 |
+
# Gemini 2.0 Flash Thinking model API key and client (for LLM)
|
16 |
GEMINI_API_KEY = os.getenv("GEMINI_API_KEY")
|
17 |
genai.configure(api_key=GEMINI_API_KEY)
|
18 |
model = genai.GenerativeModel("gemini-2.0-flash-thinking-exp-01-21")
|
|
|
41 |
path_parts = file.split('/')
|
42 |
current = tree
|
43 |
for i, part in enumerate(path_parts):
|
44 |
+
if i == len(path_parts) - 1: # file
|
45 |
current["children"].append({"type": "file", "path": file, "name": part})
|
46 |
else:
|
47 |
found = False
|
|
|
78 |
if not re.match(r'^[\w.-]+/[\w.-]+$', space_id):
|
79 |
raise ValueError(f"Invalid Space ID format: {space_id}")
|
80 |
|
81 |
+
progress(0.1, desc="Analyzing file structure...")
|
82 |
tree_structure = get_space_structure(space_id)
|
83 |
if "error" in tree_structure:
|
84 |
raise ValueError(tree_structure["error"])
|
85 |
tree_view = format_tree_structure(tree_structure)
|
86 |
|
87 |
+
progress(0.3, desc="Fetching app.py content...")
|
88 |
app_content = get_file_content(space_id, "app.py")
|
89 |
|
90 |
+
progress(0.5, desc="Summarizing code...")
|
91 |
summary = summarize_code(app_content)
|
92 |
|
93 |
+
progress(0.7, desc="Analyzing code...")
|
94 |
analysis = analyze_code(app_content)
|
95 |
|
96 |
+
progress(0.9, desc="Generating usage instructions...")
|
97 |
usage = explain_usage(app_content)
|
98 |
|
99 |
lines_for_app_py = adjust_lines_for_code(app_content)
|
100 |
+
progress(1.0, desc="Complete")
|
101 |
|
102 |
return app_content, tree_view, tree_structure, space_id, summary, analysis, usage, lines_for_app_py
|
103 |
|
104 |
except Exception as e:
|
105 |
print(f"Error in analyze_space: {str(e)}")
|
106 |
print(traceback.format_exc())
|
107 |
+
return f"An error occurred: {str(e)}", "", None, "", "", "", "", 10
|
|
|
108 |
|
109 |
# --------------------------------------------------
|
110 |
+
# Gemini 2.0 Flash Thinking model (LLM) functions
|
111 |
# --------------------------------------------------
|
112 |
from gradio import ChatMessage
|
113 |
|
114 |
def format_chat_history(messages: List[ChatMessage]) -> List[Dict]:
|
115 |
"""
|
116 |
+
Convert a list of ChatMessages to a format that the Gemini model can understand.
|
117 |
+
(Skip messages with 'Thinking' metadata)
|
118 |
"""
|
119 |
formatted = []
|
120 |
for m in messages:
|
121 |
+
if hasattr(m, "metadata") and m.metadata: # Skip 'Thinking' messages
|
122 |
continue
|
123 |
role = "assistant" if m.role == "assistant" else "user"
|
124 |
formatted.append({"role": role, "parts": [m.content or ""]})
|
125 |
return formatted
|
126 |
|
|
|
|
|
127 |
def gemini_chat_completion(system_message: str, user_message: str, max_tokens: int = 200, temperature: float = 0.7) -> str:
|
128 |
init_msgs = [
|
129 |
ChatMessage(role="system", content=system_message),
|
|
|
141 |
final += parts[0].text
|
142 |
return final.strip()
|
143 |
except Exception as e:
|
144 |
+
return f"Error calling LLM: {str(e)}"
|
|
|
145 |
|
146 |
def summarize_code(app_content: str):
|
147 |
+
system_msg = "You are an AI assistant that analyzes and summarizes Python code. Please summarize the provided code in no more than 3 lines."
|
148 |
+
user_msg = f"Please summarize the following Python code in no more than 3 lines:\n\n{app_content}"
|
149 |
try:
|
150 |
return gemini_chat_completion(system_msg, user_msg, max_tokens=200, temperature=0.7)
|
151 |
except Exception as e:
|
152 |
+
return f"Error generating summary: {str(e)}"
|
153 |
|
154 |
def analyze_code(app_content: str):
|
155 |
system_msg = (
|
156 |
+
"You are an AI assistant that analyzes Python code. Please analyze the provided code in terms of its service utility and application with respect to the following aspects:\n"
|
157 |
+
"A. Background and Necessity\n"
|
158 |
+
"B. Functional Utility and Value\n"
|
159 |
+
"C. Key Features\n"
|
160 |
+
"D. Target Audience\n"
|
161 |
+
"E. Expected Impact\n"
|
162 |
+
"Please also compare with existing and similar projects. Output in Markdown format."
|
|
|
|
|
|
|
163 |
)
|
164 |
+
user_msg = f"Please analyze the following Python code:\n\n{app_content}"
|
165 |
try:
|
166 |
return gemini_chat_completion(system_msg, user_msg, max_tokens=1000, temperature=0.7)
|
167 |
except Exception as e:
|
168 |
+
return f"Error generating analysis: {str(e)}"
|
169 |
|
170 |
def explain_usage(app_content: str):
|
171 |
system_msg = (
|
172 |
+
"You are an AI assistant that analyzes Python code to explain its usage. Based on the provided code, please describe how to use it as if you were viewing the interface. Output in Markdown format."
|
|
|
|
|
|
|
173 |
)
|
174 |
+
user_msg = f"Please explain how to use the following Python code:\n\n{app_content}"
|
175 |
try:
|
176 |
return gemini_chat_completion(system_msg, user_msg, max_tokens=800, temperature=0.7)
|
177 |
except Exception as e:
|
178 |
+
return f"Error generating usage instructions: {str(e)}"
|
179 |
|
180 |
def stream_gemini_response(user_message: str, conversation_state: List[ChatMessage]) -> Iterator[List[ChatMessage]]:
|
181 |
"""
|
182 |
+
Send a streaming request to Gemini.
|
183 |
+
If the user_message is empty, append a minimal guidance message from the assistant and yield.
|
184 |
"""
|
185 |
if not user_message.strip():
|
|
|
186 |
conversation_state.append(
|
187 |
ChatMessage(
|
188 |
role="assistant",
|
189 |
+
content="No input provided. Please enter a question!"
|
190 |
)
|
191 |
)
|
192 |
yield conversation_state
|
|
|
262 |
|
263 |
def convert_for_messages_format(messages: List[ChatMessage]) -> List[Dict[str, str]]:
|
264 |
"""
|
265 |
+
Convert a list of ChatMessages to the format [{"role": "assistant"/"user", "content": "..."}].
|
266 |
"""
|
267 |
output = []
|
268 |
for msg in messages:
|
|
|
274 |
return "", conversation_state
|
275 |
|
276 |
def respond_wrapper(message: str, conversation_state: List[ChatMessage], max_tokens, temperature, top_p):
|
277 |
+
# Get the last user message
|
278 |
last_user_message = ""
|
279 |
for msg in reversed(conversation_state):
|
280 |
if msg.role == "user":
|
281 |
last_user_message = msg.content
|
282 |
break
|
283 |
|
284 |
+
# Generate response based on the last user message
|
285 |
for updated_messages in stream_gemini_response(last_user_message, conversation_state):
|
286 |
yield "", convert_for_messages_format(updated_messages)
|
287 |
|
|
|
309 |
gr.Markdown("# π MOUSE: Space Research Thinking")
|
310 |
|
311 |
with gr.Tabs():
|
312 |
+
with gr.TabItem("π Analysis"):
|
313 |
with gr.Row():
|
314 |
with gr.Column():
|
315 |
+
url_input = gr.Textbox(label="π HuggingFace Space URL", placeholder="e.g.: https://huggingface.co/spaces/username/space-name")
|
316 |
+
analyze_button = gr.Button("Start Analysis π", variant="primary")
|
317 |
|
318 |
+
summary_output = gr.Markdown(label="π Code Summary")
|
319 |
+
analysis_output = gr.Markdown(label="π Code Analysis")
|
320 |
+
usage_output = gr.Markdown(label="π Usage Instructions")
|
321 |
+
tree_view_output = gr.Textbox(label="π File Structure", lines=20)
|
322 |
|
323 |
with gr.Column():
|
324 |
code_tabs = gr.Tabs()
|
|
|
335 |
lines=50
|
336 |
)
|
337 |
|
338 |
+
with gr.TabItem("π€ AI Code Chat"):
|
339 |
+
gr.Markdown("## π¬ Enter an example or paste your source code and ask your question!")
|
340 |
chatbot = gr.Chatbot(
|
341 |
+
label="Chat Window",
|
342 |
height=400,
|
343 |
type="messages"
|
344 |
)
|
345 |
msg = gr.Textbox(
|
346 |
+
label="Enter your message",
|
347 |
+
placeholder="Type your message here..."
|
348 |
)
|
349 |
max_tokens = gr.Slider(
|
350 |
minimum=1, maximum=8000,
|
|
|
363 |
)
|
364 |
|
365 |
examples = [
|
366 |
+
["Explain detailed usage instructions in over 4000 tokens"],
|
367 |
+
["Generate 20 FAQs in over 4000 tokens"],
|
368 |
+
["Describe technical differentiators and strengths in over 4000 tokens"],
|
369 |
+
["Generate innovative ideas for patent applications in over 4000 tokens"],
|
370 |
+
["Write an academic paper in over 4000 tokens"],
|
371 |
+
["Continue your answer"]
|
372 |
]
|
373 |
gr.Examples(examples, inputs=msg)
|
374 |
|
|
|
390 |
"Discover recommended HuggingFace Spaces [here](https://huggingface.co/spaces/openfree/Korean-Leaderboard)."
|
391 |
)
|
392 |
|
393 |
+
# Analysis tab logic
|
394 |
space_id_state = gr.State()
|
395 |
tree_structure_state = gr.State()
|
396 |
app_py_content_lines = gr.State()
|