ginipick's picture
Update app.py
f00b06e verified
raw
history blame
17.1 kB
import gradio as gr
from huggingface_hub import InferenceClient, HfApi
import os
import requests
from typing import List, Dict, Union, Tuple
import traceback
from PIL import Image
from io import BytesIO
import asyncio
from gradio_client import Client
import time
import threading
import json
HF_TOKEN = os.getenv("HF_TOKEN")
hf_client = InferenceClient("CohereForAI/c4ai-command-r-plus-08-2024", token=HF_TOKEN)
hf_api = HfApi(token=HF_TOKEN)
def get_headers():
if not HF_TOKEN:
raise ValueError("Hugging Face token not found in environment variables")
return {"Authorization": f"Bearer {HF_TOKEN}"}
def get_file_content(space_id: str, file_path: str) -> str:
file_url = f"https://huggingface.co/spaces/{space_id}/raw/main/{file_path}"
try:
response = requests.get(file_url, headers=get_headers())
if response.status_code == 200:
return response.text
else:
return f"File not found or inaccessible: {file_path}"
except requests.RequestException:
return f"Error fetching content for file: {file_path}"
def get_space_structure(space_id: str) -> Dict:
try:
files = hf_api.list_repo_files(repo_id=space_id, repo_type="space")
tree = {"type": "directory", "path": "", "name": space_id, "children": []}
for file in files:
path_parts = file.split('/')
current = tree
for i, part in enumerate(path_parts):
if i == len(path_parts) - 1: # 파일
current["children"].append({"type": "file", "path": file, "name": part})
else: # 디렉토리
found = False
for child in current["children"]:
if child["type"] == "directory" and child["name"] == part:
current = child
found = True
break
if not found:
new_dir = {"type": "directory", "path": '/'.join(path_parts[:i+1]), "name": part, "children": []}
current["children"].append(new_dir)
current = new_dir
return tree
except Exception as e:
print(f"Error in get_space_structure: {str(e)}")
return {"error": f"API request error: {str(e)}"}
def format_tree_structure(tree_data: Dict, indent: str = "") -> str:
formatted = f"{indent}{'πŸ“' if tree_data['type'] == 'directory' else 'πŸ“„'} {tree_data['name']}\n"
if tree_data["type"] == "directory":
for child in sorted(tree_data.get("children", []), key=lambda x: (x["type"] != "directory", x["name"])):
formatted += format_tree_structure(child, indent + " ")
return formatted
def analyze_space(url: str, progress=gr.Progress()):
try:
space_id = url.split('spaces/')[-1]
progress(0.1, desc="파일 ꡬ쑰 뢄석 쀑...")
tree_structure = get_space_structure(space_id)
tree_view = format_tree_structure(tree_structure)
progress(0.3, desc="app.py λ‚΄μš© κ°€μ Έμ˜€λŠ” 쀑...")
app_content = get_file_content(space_id, "app.py")
progress(0.4, desc="μ½”λ“œ μš”μ•½ 쀑...")
summary = summarize_code(app_content)
progress(0.6, desc="μ½”λ“œ 뢄석 쀑...")
analysis = analyze_code(app_content)
progress(0.8, desc="μ‚¬μš©λ²• μ„€λͺ… 생성 쀑...")
usage = explain_usage(app_content)
progress(1.0, desc="μ™„λ£Œ")
return summary, analysis, usage, app_content, tree_view, tree_structure, space_id
except Exception as e:
print(f"Error in analyze_space: {str(e)}")
print(traceback.format_exc())
return f"였λ₯˜κ°€ λ°œμƒν–ˆμŠ΅λ‹ˆλ‹€: {str(e)}", "", "", "", "", None, ""
def respond(
message: str,
history: List[Tuple[str, str]],
system_message: str = "",
max_tokens: int = 4000,
temperature: float = 0.7,
top_p: float = 0.9,
):
system_prefix = """λ°˜λ“œμ‹œ ν•œκΈ€λ‘œ 닡변할것. λ„ˆλŠ” μ£Όμ–΄μ§„ μ†ŒμŠ€μ½”λ“œλ₯Ό 기반으둜 "μ„œλΉ„μŠ€ μ‚¬μš© μ„€λͺ… 및 μ•ˆλ‚΄, qnaλ₯Ό ν•˜λŠ” 역할이닀". μ•„μ£Ό μΉœμ ˆν•˜κ³  μžμ„Έν•˜κ²Œ 4000토큰 이상 μž‘μ„±ν•˜λΌ. λ„ˆλŠ” μ½”λ“œλ₯Ό 기반으둜 μ‚¬μš© μ„€λͺ… 및 질의 응닡을 μ§„ν–‰ν•˜λ©°, μ΄μš©μžμ—κ²Œ 도움을 μ£Όμ–΄μ•Ό ν•œλ‹€. μ΄μš©μžκ°€ κΆκΈˆν•΄ ν•  만 ν•œ λ‚΄μš©μ— μΉœμ ˆν•˜κ²Œ μ•Œλ €μ£Όλ„λ‘ ν•˜λΌ. μ½”λ“œ 전체 λ‚΄μš©μ— λŒ€ν•΄μ„œλŠ” λ³΄μ•ˆμ„ μœ μ§€ν•˜κ³ , ν‚€ κ°’ 및 μ—”λ“œν¬μΈνŠΈμ™€ ꡬ체적인 λͺ¨λΈμ€ κ³΅κ°œν•˜μ§€ 마라."""
messages = [{"role": "system", "content": f"{system_prefix} {system_message}"}]
for user, assistant in history:
messages.append({"role": "user", "content": user})
messages.append({"role": "assistant", "content": assistant})
messages.append({"role": "user", "content": message})
response = ""
for message in hf_client.chat_completion(
messages,
max_tokens=max_tokens,
stream=True,
temperature=temperature,
top_p=top_p,
):
token = message.choices[0].delta.get('content', None)
if token:
response += token.strip("")
yield response
def summarize_code(app_content: str):
system_message = "당신은 Python μ½”λ“œλ₯Ό λΆ„μ„ν•˜κ³  μš”μ•½ν•˜λŠ” AI μ‘°μˆ˜μž…λ‹ˆλ‹€. μ£Όμ–΄μ§„ μ½”λ“œλ₯Ό 3쀄 μ΄λ‚΄λ‘œ κ°„κ²°ν•˜κ²Œ μš”μ•½ν•΄μ£Όμ„Έμš”."
user_message = f"λ‹€μŒ Python μ½”λ“œλ₯Ό 3쀄 μ΄λ‚΄λ‘œ μš”μ•½ν•΄μ£Όμ„Έμš”:\n\n{app_content}"
messages = [
{"role": "system", "content": system_message},
{"role": "user", "content": user_message}
]
try:
for response in hf_client.chat_completion_stream(messages, max_tokens=200, temperature=0.7):
yield response.choices[0].delta.content
except Exception as e:
yield f"μš”μ•½ 생성 쀑 였λ₯˜ λ°œμƒ: {str(e)}"
def analyze_code(app_content: str):
system_message = """당신은 Python μ½”λ“œλ₯Ό λΆ„μ„ν•˜λŠ” AI μ‘°μˆ˜μž…λ‹ˆλ‹€. μ£Όμ–΄μ§„ μ½”λ“œλ₯Ό λΆ„μ„ν•˜μ—¬ λ‹€μŒ ν•­λͺ©μ— λŒ€ν•΄ μ„€λͺ…ν•΄μ£Όμ„Έμš”:
A. λ°°κ²½ 및 ν•„μš”μ„±
B. κΈ°λŠ₯적 νš¨μš©μ„± 및 κ°€μΉ˜
C. 특μž₯점
D. 적용 λŒ€μƒ 및 νƒ€κ²Ÿ
E. κΈ°λŒ€νš¨κ³Ό
κΈ°μ‘΄ 및 μœ μ‚¬ ν”„λ‘œμ νŠΈμ™€ λΉ„κ΅ν•˜μ—¬ λΆ„μ„ν•΄μ£Όμ„Έμš”. Markdown ν˜•μ‹μœΌλ‘œ 좜λ ₯ν•˜μ„Έμš”."""
user_message = f"λ‹€μŒ Python μ½”λ“œλ₯Ό λΆ„μ„ν•΄μ£Όμ„Έμš”:\n\n{app_content}"
messages = [
{"role": "system", "content": system_message},
{"role": "user", "content": user_message}
]
try:
for response in hf_client.chat_completion_stream(messages, max_tokens=1000, temperature=0.7):
yield response.choices[0].delta.content
except Exception as e:
yield f"뢄석 생성 쀑 였λ₯˜ λ°œμƒ: {str(e)}"
def explain_usage(app_content: str):
system_message = "당신은 Python μ½”λ“œλ₯Ό λΆ„μ„ν•˜μ—¬ μ‚¬μš©λ²•μ„ μ„€λͺ…ν•˜λŠ” AI μ‘°μˆ˜μž…λ‹ˆλ‹€. μ£Όμ–΄μ§„ μ½”λ“œλ₯Ό λ°”νƒ•μœΌλ‘œ 마치 화면을 λ³΄λŠ” κ²ƒμ²˜λŸΌ μ‚¬μš©λ²•μ„ μƒμ„Ένžˆ μ„€λͺ…ν•΄μ£Όμ„Έμš”. Markdown ν˜•μ‹μœΌλ‘œ 좜λ ₯ν•˜μ„Έμš”."
user_message = f"λ‹€μŒ Python μ½”λ“œμ˜ μ‚¬μš©λ²•μ„ μ„€λͺ…ν•΄μ£Όμ„Έμš”:\n\n{app_content}"
messages = [
{"role": "system", "content": system_message},
{"role": "user", "content": user_message}
]
try:
for response in hf_client.chat_completion_stream(messages, max_tokens=800, temperature=0.7):
yield response.choices[0].delta.content
except Exception as e:
yield f"μ‚¬μš©λ²• μ„€λͺ… 생성 쀑 였λ₯˜ λ°œμƒ: {str(e)}"
def analyze_space(url: str, progress=gr.Progress()):
try:
space_id = url.split('spaces/')[-1]
progress(0.1, desc="파일 ꡬ쑰 뢄석 쀑...")
tree_structure = get_space_structure(space_id)
tree_view = format_tree_structure(tree_structure)
progress(0.3, desc="app.py λ‚΄μš© κ°€μ Έμ˜€λŠ” 쀑...")
app_content = get_file_content(space_id, "app.py")
progress(1.0, desc="μ™„λ£Œ")
return app_content, tree_view, tree_structure, space_id
except Exception as e:
print(f"Error in analyze_space: {str(e)}")
print(traceback.format_exc())
return f"였λ₯˜κ°€ λ°œμƒν–ˆμŠ΅λ‹ˆλ‹€: {str(e)}", "", None, ""
def create_ui():
try:
css = """
footer {visibility: hidden;}
.output-group {
border: 1px solid #ddd;
border-radius: 5px;
padding: 10px;
margin-bottom: 20px;
}
.scroll-lock {
overflow-y: auto !important;
max-height: calc((100vh - 200px) / 5) !important;
}
.full-height {
height: calc(100vh - 200px) !important;
overflow-y: auto !important;
}
.tabs-style {
background-color: #ffff00 !important;
font-weight: bold !important;
}
.main-tabs .tabitem[id^="tab_"] {
background-color: #ffff00 !important;
font-weight: bold !important;
}
.file-button {
background-color: #f0f0f0;
border: 1px solid #ddd;
padding: 5px 10px;
margin: 2px 0;
cursor: pointer;
text-align: left;
width: 100%;
}
.file-button:hover {
background-color: #e0e0e0;
}
"""
with gr.Blocks(css=css, theme="Nymbo/Nymbo_Theme") as demo:
gr.Markdown("# HuggingFace Space Analyzer")
with gr.Tabs(elem_classes="main-tabs") as tabs:
with gr.TabItem("뢄석"):
with gr.Row():
with gr.Column(scale=6): # μ™Όμͺ½ 60%
url_input = gr.Textbox(label="HuggingFace Space URL")
analyze_button = gr.Button("뢄석")
with gr.Group(elem_classes="output-group scroll-lock"):
summary_output = gr.Markdown(label="μš”μ•½ (3쀄 이내)")
with gr.Group(elem_classes="output-group scroll-lock"):
analysis_output = gr.Markdown(label="뢄석")
with gr.Group(elem_classes="output-group scroll-lock"):
usage_output = gr.Markdown(label="μ‚¬μš©λ²•")
with gr.Group(elem_classes="output-group scroll-lock"):
tree_view_output = gr.Textbox(label="파일 ꡬ쑰 (Tree View)", lines=20)
with gr.Group(elem_classes="output-group scroll-lock"):
file_buttons = gr.HTML(label="파일 리슀트")
with gr.Column(scale=4): # 였λ₯Έμͺ½ 40%
with gr.Group(elem_classes="output-group full-height"):
code_tabs = gr.Tabs(elem_classes="tabs-style")
with code_tabs:
app_py_tab = gr.TabItem("app.py")
with app_py_tab:
app_py_content = gr.Code(language="python", label="app.py", lines=30)
requirements_tab = gr.TabItem("requirements.txt")
with requirements_tab:
requirements_content = gr.Code(language="text", label="requirements.txt", lines=30)
with gr.TabItem("AI μ½”λ”©"):
chatbot = gr.Chatbot(label="λŒ€ν™”", type="messages")
msg = gr.Textbox(label="λ©”μ‹œμ§€")
with gr.Row():
system_message = gr.Textbox(label="System Message", value="")
max_tokens = gr.Slider(minimum=1, maximum=8000, value=4000, label="Max Tokens")
temperature = gr.Slider(minimum=0, maximum=1, value=0.7, label="Temperature")
top_p = gr.Slider(minimum=0, maximum=1, value=0.9, label="Top P")
examples = [
["μƒμ„Έν•œ μ‚¬μš© 방법을 마치 화면을 λ³΄λ©΄μ„œ μ„€λͺ…ν•˜λ“―이 4000 토큰 이상 μžμ„Ένžˆ μ„€λͺ…ν•˜λΌ"],
["FAQ 20건을 μƒμ„Έν•˜κ²Œ μž‘μ„±ν•˜λΌ. 4000토큰 이상 μ‚¬μš©ν•˜λΌ."],
["μ‚¬μš© 방법과 차별점, νŠΉμ§•, 강점을 μ€‘μ‹¬μœΌλ‘œ 4000 토큰 이상 유튜브 μ˜μƒ 슀크립트 ν˜•νƒœλ‘œ μž‘μ„±ν•˜λΌ"],
["λ³Έ μ„œλΉ„μŠ€λ₯Ό SEO μ΅œμ ν™”ν•˜μ—¬ λΈ”λ‘œκ·Έ 포슀트(λ°°κ²½ 및 ν•„μš”μ„±, κΈ°μ‘΄ μœ μ‚¬ μ„œλΉ„μŠ€μ™€ λΉ„κ΅ν•˜μ—¬ 특μž₯점, ν™œμš©μ²˜, κ°€μΉ˜, κΈ°λŒ€νš¨κ³Ό, 결둠을 포함)둜 4000 토큰 이상 μž‘μ„±ν•˜λΌ"],
["νŠΉν—ˆ μΆœμ›μ— ν™œμš©ν•  기술 및 λΉ„μ¦ˆλ‹ˆμŠ€λͺ¨λΈ 츑면을 ν¬ν•¨ν•˜μ—¬ νŠΉν—ˆ μΆœμ›μ„œ ꡬ성에 맞게 ν˜μ‹ μ μΈ 창의 발λͺ… λ‚΄μš©μ„ μ€‘μ‹¬μœΌλ‘œ 4000토큰 이상 μž‘μ„±ν•˜λΌ."],
["계속 μ΄μ–΄μ„œ λ‹΅λ³€ν•˜λΌ"],
]
gr.Examples(examples, inputs=msg)
def respond_wrapper(message, chat_history, system_message, max_tokens, temperature, top_p):
bot_message = respond(message, chat_history, system_message, max_tokens, temperature, top_p)
chat_history.append({"role": "user", "content": message})
chat_history.append({"role": "assistant", "content": bot_message})
return "", chat_history
msg.submit(respond_wrapper, [msg, chatbot, system_message, max_tokens, temperature, top_p], [msg, chatbot])
space_id_state = gr.State()
tree_structure_state = gr.State()
def update_file_buttons(tree_structure, space_id):
if tree_structure is None:
return ""
def get_files(node):
files = []
if node["type"] == "file":
files.append(node)
elif node["type"] == "directory":
for child in node.get("children", []):
files.extend(get_files(child))
return files
files = get_files(tree_structure)
buttons_html = "<div style='display: flex; flex-direction: column;'>"
for file in files:
buttons_html += f"<button class='file-button' onclick='openFile(\"{file['path']}\", \"{space_id}\")'>{file['path']}</button>"
buttons_html += "</div>"
return buttons_html
def open_file(file_path: str, space_id: str):
content = get_file_content(space_id, file_path)
file_name = file_path.split('/')[-1]
language = "python" if file_name.endswith('.py') else "text"
return gr.Tabs.update(selected=file_name), gr.Code.update(value=content, language=language, label=file_name)
analyze_button.click(
analyze_space,
inputs=[url_input],
outputs=[app_py_content, tree_view_output, tree_structure_state, space_id_state]
).then(
update_file_buttons,
inputs=[tree_structure_state, space_id_state],
outputs=[file_buttons]
).then(
summarize_code,
inputs=[app_py_content],
outputs=[summary_output]
).then(
analyze_code,
inputs=[app_py_content],
outputs=[analysis_output]
).then(
explain_usage,
inputs=[app_py_content],
outputs=[usage_output]
).then(
lambda space_id: get_file_content(space_id, "requirements.txt"),
inputs=[space_id_state],
outputs=[requirements_content]
)
file_path_input = gr.Textbox(visible=False)
space_id_input = gr.Textbox(visible=False)
file_path_input.change(
open_file,
inputs=[file_path_input, space_id_input],
outputs=[code_tabs, code_tabs]
)
return demo
except Exception as e:
print(f"Error in create_ui: {str(e)}")
print(traceback.format_exc())
raise
if __name__ == "__main__":
try:
demo = create_ui()
demo.queue()
demo.launch(
share=False,
debug=True,
show_api=False
)
except Exception as e:
print(f"Error in main: {str(e)}")
print(traceback.format_exc())