Spaces:
Sleeping

KyrieChao's picture
Update app.py
1c35dd9 verified
Raw History Blame Contribute Delete
8.09 kB
import html
from code_name_suggester import get_suggester
import gradio as gr
# 加载模型
suggester = get_suggester("KyrieChao/code-method-namer", device="cpu")
def suggest(code: str):
if not code.strip():
return {"error": "请输入代码"}
processed = code.replace("todo", "<extra_id_0>").replace("???", "<extra_id_0>")
if "<extra_id_0>" not in processed:
return {"error": "请用 'todo' 或 '???' 标记命名位置"}
try:
names = suggester.suggest(processed, num_candidates=3)
return names
except Exception as e:
return {"error": str(e)}
def render_suggestions(names):
if isinstance(names, dict) and "error" in names:
return f"""
<div style="background:#fee2e2; border-left:4px solid #ef4444; padding:12px 16px; border-radius:8px; color:#b91c1c; font-size:14px; display:flex; align-items:center; gap:8px;">
<span style="font-size:18px;">❌</span> {html.escape(names['error'])}
</div>
"""
if not isinstance(names, list):
return "<div style='color:#6b7280; padding:16px; text-align:center;'>⚠️ 未知输出格式</div>"
valid_names = [n.strip() for n in names if n and n.strip()]
if not valid_names:
return "<div style='color:#6b7280; padding:16px; text-align:center;'>💡 没有生成建议,请尝试其他输入</div>"
items = []
for idx, name in enumerate(valid_names, 1):
escaped = html.escape(name.replace('"', '\\"').replace("'", "\\'"))
item = f"""
<div class="suggestion-item" style="display:flex; align-items:center; justify-content:space-between; background:white; border-radius:12px; padding:8px 16px; margin:8px 0; box-shadow:0 2px 8px rgba(0,0,0,0.02); border:1px solid #f0f0f0; transition:all 0.2s;">
<div style="display:flex; align-items:center; gap:12px;">
<span style="background:#e0e7ff; color:#4f46e5; width:24px; height:24px; display:flex; align-items:center; justify-content:center; border-radius:999px; font-size:13px; font-weight:600;">{idx}</span>
<span style="font-family:'JetBrains Mono', monospace; font-size:16px; font-weight:500; color:#1e293b;">{html.escape(name)}</span>
</div>
<button
onclick='navigator.clipboard.writeText("{escaped}");
this.innerHTML="✓";
this.style.background="#10b981";
this.style.color="white";
setTimeout(() => {{
this.innerHTML="📋";
this.style.background="";
this.style.color="";
}}, 1000);'
style="border:none; background:#f1f5f9; cursor:pointer; width:36px; height:36px; border-radius:999px; font-size:18px; display:flex; align-items:center; justify-content:center; color:#475569; transition:all 0.15s;"
title="复制到剪贴板"
>📋</button>
</div>
"""
items.append(item)
return f"""<div style="display:flex; flex-direction:column; gap:4px;">{"".join(items)}</div>"""
# 自定义 CSS:铺满 + 大标题 + 宽松代码区
custom_css = """
@import url('https://fonts.googleapis.com/css2?family=Inter:ital,opsz,wght@0,14..32,100..900;1,14..32,100..900&family=JetBrains+Mono:wght@400;500;600&display=swap');
body, .gradio-container {
font-family: 'Inter', -apple-system, BlinkMacSystemFont, sans-serif !important;
background: #f8fafc !important;
margin: 0 !important;
padding: 0 !important;
}
.container {
max-width: none !important;
width: 100% !important;
padding: 2rem;
background: white;
border-radius: 24px;
box-shadow: 0 20px 40px -15px rgba(0,0,0,0.08);
margin: 2rem auto;
min-height: 80vh;
}
.title {
font-size: 3rem !important;
font-weight: 700 !important;
letter-spacing: -0.02em;
background: linear-gradient(135deg, #4f46e5, #7c3aed);
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
margin-bottom: 0.5rem !important;
text-align: center;
}
.subtitle {
color: #64748b;
font-size: 1.1rem;
text-align: center;
margin-bottom: 2rem !important;
font-weight: 400;
}
.code-input {
min-height: 500px !important;
border-radius: 16px !important;
background: #f8fafc !important;
padding: 1rem !important;
}
.gr-code textarea,
.gr-code pre {
font-family: 'JetBrains Mono', 'Fira Code', monospace !important;
font-size: 16px !important;
line-height: 1.6 !important;
padding: 1.2rem !important;
border-radius: 16px !important;
background: #f8fafc !important;
border: 1px solid #e2e8f0 !important;
caret-color: #4f46e5 !important;
}
.gr-code:focus-within textarea,
.gr-code:focus-within pre {
border-color: #4f46e5 !important;
box-shadow: 0 0 0 3px rgba(79, 70, 229, 0.1) !important;
}
.output-area {
background: #f8fafc !important;
border-radius: 20px !important;
padding: 16px !important;
border: 1px solid #edf2f7 !important;
min-height: 500px;
}
.suggestion-item:hover {
border-color: #cbd5e1 !important;
box-shadow: 0 8px 16px -8px rgba(0,0,0,0.08) !important;
background: #ffffff !important;
}
button.gr-button {
border-radius: 40px !important;
font-weight: 500 !important;
padding: 0.5rem 1.5rem !important;
transition: all 0.15s !important;
border: none !important;
}
button.gr-button[data-variant="primary"] {
background: #4f46e5 !important;
color: white !important;
box-shadow: 0 4px 10px rgba(79, 70, 229, 0.3) !important;
}
button.gr-button[data-variant="primary"]:hover {
background: #6366f1 !important;
transform: translateY(-1px);
box-shadow: 0 8px 16px rgba(79, 70, 229, 0.3) !important;
}
button.gr-button[data-variant="secondary"] {
background: white !important;
color: #334155 !important;
border: 1px solid #e2e8f0 !important;
}
button.gr-button[data-variant="secondary"]:hover {
background: #f8fafc !important;
border-color: #cbd5e1 !important;
}
footer { display: none !important; }
@media (max-width: 640px) {
.container { padding: 1.5rem; }
.title { font-size: 2.2rem !important; }
}
"""
# 构建界面
with gr.Blocks(title="Code Method Namer") as demo:
gr.HTML("""
<link href="https://fonts.googleapis.com/css2?family=Inter:ital,opsz,wght@0,14..32,100..900;1,14..32,100..900&family=JetBrains+Mono:wght@400;500;600&display=swap" rel="stylesheet">
""")
with gr.Column(elem_classes="container"):
gr.Markdown("<div class='title'>🤖 Code Method Namer</div>")
gr.Markdown("<div class='subtitle'>基于 CodeT5 的智能命名助手 · 用 <code>todo</code> 或 <code>???</code> 标记待命名位置</div>")
with gr.Row():
with gr.Column(scale=1):
input_code = gr.Code(
label="📝 输入代码片段",
lines=30,
elem_classes="code-input",
value="""public static void todo(int times, Runnable task) {
for (int i = 0; i < times; i++) {
task.run();
}
}""",
)
with gr.Row():
clear_btn = gr.Button("🧹 清空", variant="secondary", size="lg") # ← 改为 size="lg"
submit_btn = gr.Button("✨ 生成建议", variant="primary", size="lg")
with gr.Column(scale=1):
output = gr.HTML(label="💡 命名建议", elem_classes="output-area", min_height=500)
# 绑定事件
submit_btn.click(suggest, inputs=input_code, outputs=output).then(
render_suggestions, inputs=output, outputs=output
)
clear_btn.click(lambda: "", inputs=None, outputs=input_code)
if __name__ == "__main__":
demo.launch(
server_name="0.0.0.0",
css=custom_css,
theme=gr.themes.Soft(primary_hue="indigo", secondary_hue="slate"),
quiet=True
)