parkerjj commited on
Commit
a65e7e5
1 Parent(s): 2ae9fb3

Change to Gradio

Browse files
Files changed (1) hide show
  1. app.py +15 -23
app.py CHANGED
@@ -1,38 +1,30 @@
1
- import os
2
  from fastapi import FastAPI
3
  from pydantic import BaseModel
4
- import gradio as gr
5
 
6
- app = FastAPI()
7
 
8
- # 定义请求数据模型
9
  class TextRequest(BaseModel):
10
  text: str
11
 
12
- # 定义 Gradio 处理函数
13
- def process_aaa(text):
14
- return text + 'aaa'
15
-
16
- def process_bbb(text):
17
- return text + 'bbb'
18
-
19
- # 使用 Gradio 的接口函数,但不启动 Web 界面
20
- iface_aaa = gr.Interface(fn=process_aaa, inputs="text", outputs="text")
21
- iface_bbb = gr.Interface(fn=process_bbb, inputs="text", outputs="text")
22
-
23
- # FastAPI 路由,用于接收和处理请求
24
  @app.post("/api/aaa")
25
  async def api_aaa(request: TextRequest):
26
- result = iface_aaa(request.text)
27
  return {"result": result}
28
 
29
  @app.post("/api/bbb")
30
  async def api_bbb(request: TextRequest):
31
- result = iface_bbb(request.text)
32
  return {"result": result}
33
 
34
- # 启动应用,使用环境变量指定的端口
35
- if __name__ == "__main__":
36
- import uvicorn
37
- port = int(os.getenv("PORT", 7860)) # 获取 PORT 环境变量
38
- uvicorn.run(app, host="0.0.0.0", port=port)
 
 
 
 
1
+ import gradio as gr
2
  from fastapi import FastAPI
3
  from pydantic import BaseModel
4
+ from fastapi.middleware.wsgi import WSGIMiddleware
5
 
6
+ app = FastAPI() # 创建 FastAPI 应用
7
 
8
+ # 定义请求模型
9
  class TextRequest(BaseModel):
10
  text: str
11
 
12
+ # 定义两个 API 路由处理函数
 
 
 
 
 
 
 
 
 
 
 
13
  @app.post("/api/aaa")
14
  async def api_aaa(request: TextRequest):
15
+ result = request.text + 'aaa'
16
  return {"result": result}
17
 
18
  @app.post("/api/bbb")
19
  async def api_bbb(request: TextRequest):
20
+ result = request.text + 'bbb'
21
  return {"result": result}
22
 
23
+ # Gradio 假界面,保持 app.py 有一个 Gradio 接口
24
+ def fake_interface():
25
+ return "Gradio Interface Placeholder"
26
+
27
+ # 将 FastAPI app 作为 Gradio 的后端
28
+ app = gr.mount_gradio_app(app, gr.Interface(fn=fake_interface, inputs=None, outputs="text"))
29
+
30
+ # 注意:Hugging Face Spaces 会自动运行此 app 文件,因此不需要 __main__ 入口。