Giter VIP home page Giter VIP logo

paddlehub-wechaty-demo's Introduction

paddlehub-wechaty-demo

本例子展示一个基于 PaddleHub + Wechaty 的微信闲聊机器人demo。通过Wechaty获取微信接收的消息,然后使用PaddleHub的plato-mini模型根据对话的上下文生成新的对话文本,最终以微信消息的形式发送,实现闲聊的交互。

风险提示

本项目采用的api为第三方——Wechaty提供,非微信官方api,用户需承担来自微信方的使用风险。
在运行项目的过程中,建议尽量选用新注册的小号进行测试,不要用自己的常用微信号。

Wechaty

关于Wechaty和python-wechaty,请查阅以下官方repo:

环境准备

  • 系统环境:Linux, MacOS, Windows
  • python3.7+

安装和使用

  1. Clone本项目代码

    git clone https://github.com/KPatr1ck/paddlehub-wechaty-demo.git
    cd paddlehub-wechaty-demo
  2. 安装依赖 —— paddlepaddle, paddlehub, wechaty

    pip install -r requirements.txt
  3. 安装项目所需的PaddleHub的module

    此demo以plato-mini为示例,其他module根据项目所需安装,更多的模型请查阅PaddleHub官网

    hub install plato-mini==1.0.0
  4. Set token for your bot

    在当前系统的环境变量中,配置以下与WECHATY_PUPPET相关的两个变量。 关于其作用详情和TOKEN的获取方式,请查看Wechaty Puppet Services

    export WECHATY_PUPPET=wechaty-puppet-service
    export WECHATY_PUPPET_SERVICE_TOKEN=your_token_at_here

    Paimon的短期TOKEN经测试可用,其他TOKEN请自行测试使用。

  5. Run the bot

    python examples/paddlehub-chatbot.py

    运行后,可以通过微信移动端扫码登陆,登陆成功后则可正常使用。

运行效果

examples/paddlehub-chatbot.py中,通过以下几行代码即可实例化一个plato-mini的模型,关于模型的更多用法,请查看PaddleHub: plato-mini

# Initialize a PaddleHub plato-mini model
import paddlehub as hub

model = hub.Module(name='plato-mini', version='1.0.0')
model._interactive_mode = True  # 开启交互模式
model.max_turn = 10             # 对话轮次配置
model.context = deque(maxlen=model.max_turn)  # 对话上下文的存储队列

on_message方法是接收到消息时的回调函数,可以通过自定义的条件(譬如消息类型、消息来源、消息文字是否包含关键字、是否群聊消息等等)来判断是否回复信息,消息的更多属性和条件可以参考Class Message

本示例中的on_message方法的代码如下,脚本中回复的条件是:

  1. 消息类型是文字
  2. 文字信息以[Test]开头
async def on_message(msg: Message):
    """
    Message Handler for the Bot
    """
    ### PaddleHub chatbot
    if isinstance(msg.text(), str) and len(msg.text()) > 0 \
        and msg._payload.type == MessageType.MESSAGE_TYPE_TEXT \
        and msg.text().startswith('[Test]'):  # Use a special token '[Test]' to select messages to respond.
        bot_response = model.predict(data=msg.text().replace('[Test]', ''))[0]
        await msg.say(bot_response)  # Return the text generated by PaddleHub chatbot
    ###

脚本成功运行后,所登陆的账号即可作为一个Chatbot,下图左侧的内容由Chatbot生成和回复。

gIZF5F.md.jpg gIZiUU.md.jpg

paddlehub-wechaty-demo's People

Contributors

kpatr1ck avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

paddlehub-wechaty-demo's Issues

导入模块报错:UnicodeDecodeError: 'utf-8' codec can't decode byte 0xc3 in position 109051644: invalid continuation byte

model = hub.Module(name='plato-mini')

[2021-08-17 11:30:13,858] [ INFO] - Already cached C:\Users\Administrator.paddlenlp\models\plato-mini\plato-mini.pdparams
Traceback (most recent call last):
File "", line 1, in
File "C:\ProgramData\Miniconda3\envs\paddle_mini\lib\site-packages\paddlehub\module\module.py", line 388, in new
module = cls.init_with_name(
File "C:\ProgramData\Miniconda3\envs\paddle_mini\lib\site-packages\paddlehub\module\module.py", line 511, in init_with_name
return user_module_cls(**kwargs)
File "C:\Users\Administrator.paddlehub\modules\plato_mini\module.py", line 41, in init
self.model = UnifiedTransformerLMHeadModel.from_pretrained('plato-mini')
File "C:\ProgramData\Miniconda3\envs\paddle_mini\lib\site-packages\paddlenlp\transformers\model_utils.py", line 297, in from_pretrained
state_dict = paddle.load(weight_path)
File "C:\ProgramData\Miniconda3\envs\paddle_mini\lib\site-packages\paddle\framework\io.py", line 364, in load
load_result = pickle.load(f) if six.PY2 else pickle.load(
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xc3 in position 109051644: invalid continuation byte

安装的版本:
paddle2onnx 0.7
paddlehub 2.1.0
paddlenlp 2.0.2
paddlepaddle 2.0.2

结果都不打印,直接就finished ,还没报错

from collections import deque
import paddlehub as hub
model = hub.Module(name='plato-mini', version='1.0.0')
model._interactive_mode = True
model.max_turn = 10
model.context = deque(maxlen=model.max_turn)

result = model.predict("hello")
print(result)

结果都不打印,直接就finished ,还没报错
[2021-06-23 18:28:37,384] [ INFO] - Already cached C:\Users\pc.paddlenlp\models\plato-mini\plato-mini.pdparams
[2021-06-23 18:28:48,339] [ INFO] - Found C:\Users\pc.paddlenlp\models\plato-mini\plato-mini-vocab.txt
[2021-06-23 18:28:48,340] [ INFO] - Found C:\Users\pc.paddlenlp\models\plato-mini\plato-mini-spm.model
Building prefix dict from the default dictionary ...
Loading model from cache C:\Users\pc\AppData\Local\Temp\jieba.cache
Loading model cost 0.696 seconds.
Prefix dict has been built successfully.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.