Spaces:
Sleeping
Sleeping
Update app.py
Browse files3 unmodified lines456789101112131415161718192021227 unmodified lines30313233343536373839404142434445463 unmodified linesfrom code_name_suggester import get_suggesterimport os# 加载模型(单例)suggester = get_suggester("KyrieChao/code-method-namer", device="cpu")# 创建 FastAPI 实例app = FastAPI()@app.post("/predict")async def predict(payload: dict):code = payload.get("code", "")if not code.strip():return {"error": "code is required"}# 自动替换占位符processed = code.replace("todo", "<extra_id_0>").replace("???", "<extra_id_0>")if "<extra_id_0>" not in processed:return {7 unmodified linesexcept Exception as e:return {"error": str(e)}# 如果你还想保留 Gradio UI(可选)if os.getenv("GRADIO_UI", "1") == "1":import gradio as grdef gr_predict(code):result = predict({"code": code})return resultgr_interface = gr.Interface(fn=gr_predict,inputs=gr.Textbox(placeholder="def todo(x): return x + 1", lines=4),outputs="json",title="Code Method Namer (API + UI)")app = mount_gradio_app(app, gr_interface, path="/")3 unmodified lines456789101112131415161718192021227 unmodified lines303132333435363738394041424344454647483 unmodified linesfrom code_name_suggester import get_suggesterimport os# 1. 加载模型(单例)suggester = get_suggester("KyrieChao/code-method-namer", device="cpu")# 2. 创建 FastAPI 实例app = FastAPI(title="Code Method Namer API")# 3. 添加预测 API 路由@app.post("/predict")async def predict(payload: dict):code = payload.get("code", "")if not code.strip():return {"error": "code is required"}processed = code.replace("todo", "<extra_id_0>").replace("???", "<extra_id_0>")if "<extra_id_0>" not in processed:return {7 unmodified linesexcept Exception as e:return {"error": str(e)}# 4. 【可选】挂载 Gradio UI 到根路径 /if os.getenv("ENABLE_UI", "1") == "1":import gradio as grdef gr_predict(code):return predict({"code": code})gr_interface = gr.Interface(fn=gr_predict,inputs=gr.Textbox(placeholder="def todo(x): return x + 1", lines=4),outputs="json",title="🤖 Code Method Namer",description="输入代码,AI 生成函数名")# 关键:mount 到 app,不 launch!app = mount_gradio_app(app, gr_interface, path="/")
app.py+11-9