[TOC]
创建、激活虚拟环境
python3 -m venv py_env
source py_env/bin/activate
导入包
使用了清华大学的镜像
// fastapi必要包
pip install -i https://pypi.tuna.tsinghua.edu.cn/simple fastapi
pip install -i https://pypi.tuna.tsinghua.edu.cn/simple uvicorn
// 参考了一些导入ChatterBot的方法,出现各种错误,在查找一些博客后,使用源码编译安装不报错
git clone https://gitee.com/Lamentations/ChatterBot.git
cd ChatterBot/
python setup.py build
python setup.py install
// 在使用ChatterBot报出缺乏一些包的错误,升级pip,导入以下包
pip install -i https://pypi.tuna.tsinghua.edu.cn/simple --upgrade pip
pip install -i https://pypi.tuna.tsinghua.edu.cn/simple six
pip install -i https://pypi.tuna.tsinghua.edu.cn/simple pyyaml
训练
以下内容参考ChatterBot官方文档https://chatterbot.readthedocs.io/en/stable/
自定义训练
- 训练脚本
from chatterbot import ChatBot
from chatterbot.trainers import ListTrainer
chatbot = ChatBot("Double mouth Teacher Lv")
conversation = [
"你好",
"你好",
"你好",
"我不好",
"你叫什么名字",
"名字只是一个代号,叫什么无所谓,但我不想告诉你",
"谢谢",
"不客气,很高兴没能帮到你",
]
trainer = ListTrainer(chatbot)
trainer.train(conversation)
- 写个导入接口导入对话列表来训练
from fastapi import Body, FastAPI, status
from fastapi.responses import JSONResponse
import uvicorn
from chatterbot import ChatBot
from chatterbot.trainers import ListTrainer
from pydantic import BaseModel
app = FastAPI()
chatbot = ChatBot("Double mouth Teacher Lv")
@app.post("/training")
async def training(uselessKey: str = None, dialogue: list=[]):
if uselessKey != 'nnnnnnnnnnnn':
return JSONResponse(status_code=403, content='403 Forbidden')
conversation = dialogue
trainer = ListTrainer(chatbot)
trainer.train(conversation)
return {"code": "200"}
- 使用官方语言包来训练
from chatterbot import ChatBot
from chatterbot.trainers import ChatterBotCorpusTrainer
chatterbot = ChatBot("Double mouth Teacher Lv")
chatterbot.set_trainer(ChatterBotCorpusTrainer)
chatterbot.train(
"chatterbot.corpus.chinese.greetings",
"chatterbot.corpus.chinese.conversations"
)
对话
- 写个接口获取对话返回值
from fastapi import Body, FastAPI, status
from fastapi.responses import JSONResponse
import uvicorn
from chatterbot import ChatBot
from chatterbot.trainers import ListTrainer
from pydantic import BaseModel
app = FastAPI()
chatbot = ChatBot("Double mouth Teacher Lv")
@app.get("/talking")
async def talking(uselessKey: str = None, ask: str = '你好'):
if uselessKey != 'wszzs110':
return JSONResponse(status_code=403, content='403 Forbidden')
response = chatbot.get_response(ask)
return response
启动fastapi
uvicorn main:app --reload
# 指定端口
uvicorn main:app --host '0.0.0.0' --port 8080 --reload
部署到服务器上
- 使用gunicorn启动
# 安装依赖
pip install -i https://pypi.tuna.tsinghua.edu.cn/simple gunicorn
pip install -i https://pypi.tuna.tsinghua.edu.cn/simple uvloop
pip install -i https://pypi.tuna.tsinghua.edu.cn/simple zipp
pip install -i https://pypi.tuna.tsinghua.edu.cn/simple httptools
# 启动 (-D 守护进程 -b 指定端口)
gunicorn -D main:app -b 0.0.0.0:9090 -w 4 -k uvicorn.workers.UvicornWorker
- 配置nginx转发
# 服务器部署
# nginx 转发
location / {
proxy_pass http://127.0.0.1:8000/;
}