Spaces:
Sleeping
Sleeping
Update app.py
Browse files1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991 unmodified line101102103104105106107108109# app.pyfrom code_name_suggester import get_suggesterimport gradio as gr# 1. 加载模型suggester = get_suggester("KyrieChao/code-method-namer", device="cpu")# 2. 预测函数(保持不变)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' 或 '???' 标记命名位置","example": "def todo(x): return x + 1"}try:names = suggester.suggest(processed, num_candidates=3)return names # 直接返回列表,简化逻辑except Exception as e:return {"error": str(e)}# 3. 渲染建议为 HTML(带复制按钮)def render_suggestions(names):if isinstance(names, dict) and "error" in names:return f"<div style='color:#ef4444; font-size:14px;'>❌ {names['error']}</div>"if not isinstance(names, list):return "<div>⚠️ 未知输出格式</div>"lines = []for name in names:clean = name.strip()if not clean:continue# 转义引号防止 JS 注入escaped = clean.replace('"', '\\"').replace("'", "\\'")html = f"""<div style="display:flex; align-items:center; margin:8px 0; font-family:monospace; font-size:15px;"><span>{clean}</span><buttononclick='navigator.clipboard.writeText("{escaped}");this.textContent="✓";setTimeout(() => this.textContent="📋", 1000);'style="border:none; background:none; cursor:pointer;margin-left:12px; font-size:14px; color:#6b7280;padding:2px 6px; border-radius:4px;"title="复制">📋</button></div>"""lines.append(html)return "".join(lines) if lines else "<div>💡 无建议结果</div>"# 4. 自定义 CSS 和主题(移到 launch)custom_css = """.container { max-width: 900px; margin: auto; padding: 20px; background: #f9fafb; border-radius: 16px; box-shadow: 0 4px 12px rgba(0,0,0,0.05); }.title { text-align: center; color: #1f2937; font-size: 1.8em; margin-bottom: 10px; }.subtitle { text-align: center; color: #4b5563; font-size: 1em; margin-bottom: 20px; }.output-area { background: white; border-radius: 10px; padding: 16px; margin-top: 16px; }footer { display: none !important; }"""# 5. 构建界面(Blocks 不再接收 theme/css)with gr.Blocks() as demo:gr.HTML("<div class='container'>")gr.Markdown("<div class='title'>🤖 Code Method Namer</div>")gr.Markdown("<div class='subtitle'>基于 CodeT5 的智能代码命名助手。输入代码片段,AI 自动生成语义化函数名。</div>")with gr.Row():input_code = gr.Textbox(label="📝 输入代码(用 todo / ??? 标记待命名位置)",placeholder="例如:def todo(a,b): return a+b",lines=6,value="def todo(a,b): return a+b")output = gr.HTML(label="💡 AI 建议", elem_classes="output-area") # 使用 HTML 组件with gr.Row():clear_btn = gr.Button("🧹 Clear", variant="secondary")submit_btn = gr.Button("🚀 Submit", variant="primary")gr.Markdown("### 📌 Examples")examples = ["def todo(x): return x * 2","for ??? in items: print(item)","result = safe_add(todo, b)"]with gr.Row():for ex in examples:btn = gr.Button(ex, size="sm")btn.click(lambda x=ex: x, inputs=None, outputs=input_code)# 绑定事件submit_btn.click(suggest, inputs=input_code, outputs=output).then(1 unmodified line)clear_btn.click(lambda: "", inputs=None, outputs=input_code)# 6. 启动(theme 和 css 放这里!)if __name__ == "__main__":demo.launch(theme=gr.themes.Soft(primary_hue="indigo", secondary_hue="slate"),css=custom_css)1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132141 unmodified line216217218219220221222223224225226import htmlfrom code_name_suggester import get_suggesterimport gradio as gr# 1. 加载模型suggester = get_suggester("KyrieChao/code-method-namer", device="cpu")# 2. 预测函数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 namesexcept Exception as e:return {"error": str(e)}# 3. 渲染建议(带编号卡片 + 复制)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><buttononclick='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>"""# 4. 自定义 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;}.container {max-width: 1000px;margin: 2rem auto;padding: 2rem;background: white;border-radius: 32px;box-shadow: 0 20px 40px -15px rgba(0,0,0,0.08);}.title {font-size: 2.5rem !important;font-weight: 600 !important;letter-spacing: -0.02em;background: linear-gradient(135deg, #4f46e5, #7c3aed);-webkit-background-clip: text;-webkit-text-fill-color: transparent;margin-bottom: 0.25rem !important;text-align: center;}.subtitle {color: #64748b;font-size: 1.1rem;text-align: center;margin-bottom: 2rem !important;font-weight: 400;}.gr-code, pre, code {font-family: 'JetBrains Mono', 'Fira Code', monospace !important;font-size: 14px;border-radius: 16px !important;background: #f1f5f9 !important;border: 1px solid #e2e8f0 !important;}.gr-code:focus-within {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: 180px;}.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;}.gr-button[size="sm"] {background: white !important;border: 1px solid #e2e8f0 !important;color: #334155 !important;border-radius: 30px !important;padding: 0.25rem 1rem !important;font-size: 0.85rem !important;box-shadow: none !important;}.gr-button[size="sm"]:hover {background: #f1f5f9 !important;border-color: #94a3b8 !important;}footer { display: none !important; }@media (max-width: 640px) {.container { padding: 1.5rem; margin: 1rem; }.title { font-size: 2rem !important; }.gr-button[size="sm"] { font-size: 0.75rem !important; padding: 0.2rem 0.8rem !important; }}"""# 5. 构建界面 —— 修正点:不再用 with gr.HTML 包裹with gr.Blocks(title="Code Method Namer") as demo:# 字体已通过 @import 加载,此处可省略,但保留也无妨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">""")# 使用 Column 模拟 containerwith 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(equal_height=True):with gr.Column(scale=1):input_code = gr.Code(label="📝 输入代码片段",placeholder="例如:def todo(a,b): return a+b",lines=8,language="python",value="def todo(a,b): return a+b")with gr.Row():clear_btn = gr.Button("🧹 清空", variant="secondary", size="sm")submit_btn = gr.Button("✨ 生成建议", variant="primary", size="lg")with gr.Column(scale=1):output = gr.HTML(label="💡 命名建议", elem_classes="output-area")gr.Markdown("### 📌 试试这些例子")examples = ["def todo(x): return x * 2","for ??? in items: print(item)","result = safe_add(todo, b)"]with gr.Row():for ex in examples:btn = gr.Button(ex, size="sm")btn.click(lambda x=ex: x, inputs=None, outputs=input_code)# 绑定事件submit_btn.click(suggest, inputs=input_code, outputs=output).then(1 unmodified line)clear_btn.click(lambda: "", inputs=None, outputs=input_code)# 6. 启动 —— theme 和 css 放这里!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)
app.py+184-67