Spaces:
Sleeping
Sleeping
Update app.py
Browse files1233547567108910131112161713141516171819205 unmodified lines26272831323334353637383940414243444546474829# app.pyfrom fastapi import FastAPIfrom gradio import mount_gradio_appfrom code_name_suggester import get_suggesterimport os
# 1. 加载模型(单例)# 只初始化一次模型(在模块顶层)suggester = get_suggester("KyrieChao/code-method-namer", device="cpu")
# 2. 创建 FastAPI 实例# 创建 FastAPI appapp = FastAPI(title="Code Method Namer API")
# 3. 添加预测 API 路由@app.post("/predict")async def predict(payload: dict): code = payload.get("code", "") if not code.strip(): code = payload.get("code", "").strip() if not code: return {"error": "code is required"} # 替换占位符 processed = code.replace("todo", "<extra_id_0>").replace("???", "<extra_id_0>") if "<extra_id_0>" not in processed: return {5 unmodified lines names = suggester.suggest(processed, num_candidates=3) return {"suggestions": names} except Exception as e: return {"error": str(e)}
# 4. 【可选】挂载 Gradio UI 到根路径 /if os.getenv("ENABLE_UI", "1") == "1": import gradio as gr def 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="/") return {"error": str(e)}app.py+6-25