[PYTHON] Make a chatbot and practice to be popular.

Introduction

In recent years, most of communication is shifting to chat such as LINE. In today's society, where it is necessary to write attractive sentences in order to be popular, there are limited places to practice due to the surrounding environment, and many people will suddenly come to the actual performance. ~~ I am. ~~ To address the challenges of humankind living in the present age, we will prepare a chatbot that outputs the degree of interest in ourselves, practice throwing messages to it, and take an approach to improve our message skills.

The figure below is a part of the training that the author is conducting. 異性を映画に誘う修行の一部である

The degree of interest of the other party is output in three stages (positive, uninterested, unknown). The other party's message itself has no meaning. I prepared what I have been told.

You win if you make your opponent positive. It seems that the actual training will not come forever even if you practice here, but in this article, we will explain how to create a chatbot and aim to improve the message skills of humankind.

line_bot.png [Updated on February 23, 2020] I made a LINE bot.

create

Even if I try to create it, the opposite sex is not familiar in the first place. In other words, the degree of interest cannot be measured. Meanwhile, the author discovered married / unmarried ones in the user attribute estimation of the reference of COTOHA API, which is a natural language processing platform. For those who are not popular, married people have performed miracles that cannot normally be accomplished, that is, God. I thought. According to the estimation by machine learning, it is estimated that the sentence is married, that is, it is a message that attracts interest. Natural Language Processing / Speech Processing API Platform COTOHA API

Using the COTOHA API like this, create a bot that outputs (positive, uninterested, unknown) to your message.

Throw to COTOHA API

First, register with Developers from the COTOHA API link above. The free tier is 1,000 calls / day each. (As of February 13, 2020) With all this, you can probably practice without rest.

The minimum requirement is

  1. Obtaining an access token
  2. Throw the entered string to user attribute estimation

This time, as a room for customization, if the estimation result is "unmarried" or the result is not returned, a message that you have seen is returned at random. In addition, when "married" is encountered, the input character string is thrown to "sentence type estimation", and a relatively favorable message is returned according to the type of speech act. This will make the story seem connected and the painful discipline will be a little lighter.

Code to throw to COTOHA API

python


import random
import requests
import json

BASE_URL = "https://api.ce-cotoha.com/api/dev/nlp/"
CLIENT_ID = "******"
CLIENT_SECRET = "******"

def auth():
    token_url = "https://api.ce-cotoha.com/v1/oauth/accesstokens"
    headers = {
        "Content-Type": "application/json",
        "charset": "UTF-8"
    }

    data = {
        "grantType": "client_credentials",
        "clientId": CLIENT_ID,
        "clientSecret": CLIENT_SECRET
    }
    r = requests.post(token_url,
                      headers=headers,
                      data=json.dumps(data))
    res = r.json()

    return res["access_token"]  # ["expires_in"]:remaining time

def sequence_anlysis(sentence):
    headers = {
        "Content-Type": "application/json",
        "charset": "UTF-8",
        "Authorization": "Bearer {}".format(access_token)
    }
    data = {
        "sentence": sentence,
        "type": "default"
    }
    r = requests.post(BASE_URL + "v1/sentence_type",
                      headers=headers,
                      data=json.dumps(data))
    res_type = r.json()
    if not res_type["status"] == 0:
        print('type API Error status', res_type["status"])
        exit(1)

    data = {
        "document": sentence,
        "type": "kuzure",  #Collapse mode such as tweets
        "do_segment": False
    }
    r = requests.post(BASE_URL + "beta/user_attribute",
                        headers=headers,
                        data=json.dumps(data))

    res_attr = r.json()
    if not res_attr["status"] == 0:
        print('attr API Error status', res_attr["status"])
        exit(1)
    
    if not "civilstatus" in res_attr["result"].keys():
        civilstatus = "unknown"
    else:
        civilstatus = res_attr["result"]["civilstatus"]
    return res_type["result"]["modality"], res_type["result"]["dialog_act"], civilstatus

Prepare a chatbot

Use Python to prepare a chat space that runs on the console. ~~ It was troublesome to prepare LINE Bot etc., so this time I implemented it with standard input and output.

Code to throw to COTOHA API

python


print('End with quit')
while True:
    s = input('you: ')
    if s == "":
        continue
    elif s == 'quit':
        break
        exit(0)
    else:
        #Parse input
        modality, dialog_act, civilstatus = sequence_anlysis(s)
        #Create a reply
        output = make_sentence(dialog_act, civilstatus)
        if civilstatus == "married":
            print('bot (Positive):    ', output)
        elif civilstatus == "Unmarried":
            print('bot (Not interested):  ', output)
        else:
            print('bot (unknown):      ', output)

Summary

A chatbot using the COTOHA API was used to create a training ground for popularity. I sincerely hope that this will save some of the love refugees around the world.

Future tasks

Recommended Posts

Make a chatbot and practice to be popular.
[Introduction to Tensorflow] Understand Tensorflow properly and try to make a model
How to make a Japanese-English translation
How to make a slack bot
How to make a crawler --Advanced
How to make a recursive function
How to make a deadman's switch
[Blender] How to make a Blender plugin
5 Ways to Create a Python Chatbot
How to make a crawler --Basic
How to make a surveillance camera (Security Camera) with Opencv and Python
[C language] How to create, avoid, and make a zombie process
I tried to make a periodical process with Selenium and Python
How to split and save a DataFrame
[Python] How to make a class iterable
How to make a rock-paper-scissors bot that can be easily moved (commentary)
Fractal to make and play with Python
How to make a container name a subdomain and make it accessible in Docker
I tried to make a Web API
To make a dict type property read-only
How to make a Backtrader custom indicator
How to make a Pelican site map
I want to make a web application using React and Python flask
I tried to make a periodical process with CentOS7, Selenium, Python and Chrome
I want to make a music player and file music at the same time
WEB scraping with python and try to make a word cloud from reviews
Load a photo and make a handwritten sketch. With zoom function. Tried to make it.
I tried to make a simple image recognition API with Fast API and Tensorflow
I set up TensowFlow and was addicted to it, so make a note
How to make a dialogue system dedicated to beginners
A memorandum to make WebDAV only with nginx
Would you like to make a Twitter resume?
How to make a dictionary with a hierarchical structure.
I want to make a game with Python
Try to make a "cryptanalysis" cipher with Python
Pretend to be a server with two PCs
How to make a QGIS plugin (package generation)
I read "How to make a hacking lab"
Try to make a dihedral group with Python
I tried to make a ○ ✕ game using TensorFlow
Lark Basics (Python, Lark to make a shell-like guy)
I tried to make something like a chatbot with the Seq2Seq model of TensorFlow
What to do if pvcreate produces a lot of WARNING and cannot be created
It would be wise to write like boolean and "A" or "B" [Python] [But]
I tried to make a memo app that can be pomodoro, but a reflection record
I tried to make a "fucking big literary converter"
Try to make a Python module in C language
Specify the volume on linux and make a sound
Try to make a command standby tool with python
Created a module to monitor file and URL updates
Let's make a Makefile and build it (super beginner)
[Practice] Make a Watson app with Python! # 2 [Translation function]
[Practice] Make a Watson app with Python! # 1 [Language discrimination]
How to make a shooting game with toio (Part 1)
Let's make a simple game with Python 3 and iPhone
I want to find a popular package on PyPi
sympy and Decimal seem to be on bad terms
Make a function to describe Japanese fonts with OpenCV
How to make a Python package using VS Code
[Python] I want to make a nested list a tuple
Machine learning beginners try to make a decision tree