Spaces:
Sleeping
Sleeping
Update app.py
Browse files112335678910456789101617181920211112131423151617181920282930313233343536372122233924254126272829463031323334513536375438394041from transformers import pipelinefrom code_name_suggester import get_suggesterimport gradio as grimport re
# 加载模型pipe = pipeline( "text-generation", model="KyrieChao/code-method-namer", device=-1 # CPU)# 单例加载(首次访问时加载,约需 10~30 秒)suggester = get_suggester(model_name_or_path="KyrieChao/code-method-namer", device="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: # 自动替换用户友好的占位符 processed = code_input.replace("todo", "<extra_id_0>").replace("???", "<extra_id_0>").replace("___", "<extra_id_0>") if "<extra_id_0>" not in processed: return { "warning": "未检测到命名位置。请用 'todo'、'???' 或 '___' 标记待命名处", "warning": "未检测到命名位置", "tip": "请用 '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} names = suggester.suggest(processed, num_candidates=3) return {"建议名称": names} if names else {"result": "未生成有效名称"} except Exception as e: return {"error": f"生成失败: {str(e)}"} return {"error": 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)", placeholder="例如:def todo(x): return x + 1", lines=4 ), outputs=gr.JSON(label="💡 AI 建议"), title="🤖 Code Method Namer", description="输入代码片段,用 <code>todo</code>、<code>???</code> 或 <code>___</code> 标记需要命名的位置,AI 自动生成语义化名称。", description="基于 CodeT5 的智能代码命名助手。输入代码片段,AI 自动生成语义化函数名。", examples=[ ["def todo(x): return x * 2"], ["for ??? in range(10): print(i)"], ["for ??? in items: print(item)"], ["result = safe_add(todo, b)"] ], allow_flagging="never"app.py+14-30