Spaces:
Sleeping
Sleeping
app.py
Browse files12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061from transformers import pipelineimport gradio as grimport re
# 加载模型pipe = pipeline( "text2text-generation", model="KyrieChao/code-method-namer", device=-1 # CPU)
def suggest(code_input): if not code_input.strip(): return {"error": "请输入代码片段"} # === 关键:将用户友好的占位符 → 模型需要的 <extra_id_0> === # 支持多种写法:todo, TODO, ???, ___, [name], etc. code_processed = re.sub(r'\b(todo|TODO|___|\?\?\?)\b', '<extra_id_0>', code_input) # 如果用户已经写了 <extra_id_0>,也保留 if '<extra_id_0>' not in code_processed: return { "warning": "未检测到命名位置。请用 'todo'、'???' 或 '___' 标记待命名处", "example": "def todo(x): return x * 2" } try: results = pipe( code_processed, max_length=20, num_return_sequences=3, clean_up_tokenization_spaces=True ) suggestions = [r['generated_text'].strip() for r in results if r['generated_text'].strip()] if not suggestions: return {"error": "模型未返回有效建议"} return {"建议名称": suggestions} except Exception as e: return {"error": f"生成失败: {str(e)}"}
# Gradio 界面demo = gr.Interface( fn=suggest, inputs=gr.Textbox( label="📝 输入代码(用 todo / ??? 标记待命名位置)", placeholder="例如:def todo(x): return x + 1\n或:for ??? in items: print(item)", lines=4 ), outputs=gr.JSON(label="💡 AI 建议"), title="🤖 Code Method Namer", description="输入代码片段,用 <code>todo</code>、<code>???</code> 或 <code>___</code> 标记需要命名的位置,AI 自动生成语义化名称。", examples=[ ["def todo(x): return x * 2"], ["for ??? in range(10): print(i)"], ["result = safe_add(todo, b)"] ], allow_flagging="never")
if __name__ == "__main__": demo.launch()app.pyAdded+61