📜 ⬆️ ⬇️

Bot for telegram with status in DBMS and text classification

Since My classifier from the past post still works (however, the parameters out of the box are not always successful, so I rendered the opportunity to slightly adjust the Conv1d layers and the hidden layer) - I decided to fasten it to the bot. Yes, I was late for this HYIP) By the way, I’ll clarify in advance that I haven’t tried to fasten Russian yet, although this shouldn’t be a problem - the necessary features are supported in nltk, word2vec training is not conceptually different from English, and pre-trained models seem to be available .

Well, immediately there are questions:



Requirements


You will need:
')

To hell with details, give an example


Python code
import logging from robotframework_telegram import RobotFrameworkTelegram from config import config if __name__ == '__main__': bots = RobotFrameworkTelegram({ 'DATABASE_URI': 'URI', 'KEEP_WORD_VECTORS': 3, 'ROBOT_CONFIGURATIONS': 'robot_configurations', 'KEEP_ROBOTS': 5, 'OUTPUT_HANDLERS': {}, 'TOKENS': [ # Your tokens here ], 'NO_ANSWER_MESSAGE': 'Sorry, I can\'t answer now.', 'NO_INSTANCE_MESSAGE': 'Sorry, robot not instantiated yet. ' + \ 'You\'ll get answer after instantiation - it can take few minutes', 'TELEGRAM_WORKERS_PER_BOT': 1, 'WORKER_COUNT': 2, 'WORKER_SLEEP_TIME': 0.2, 'LOGGER': logging, }) bots.start_polling() 


For the data (structure and dump of the postgres database, word2vec, the configuration of the trained bot) - here .

Script Description


In my case, the bot script can be described as a tree (well, in fact - taking into account "goto" - rather a graph), whose node can contain conditions:


In addition to the tree in the script are:


for example
a bunch of yaml
 script: text: Hello. I'm weather robot. How can I help you? name: main children: - name: city_conditions text: "Conditions in {%print $city%} is next." conditions: class: conditions entity_variables: city: $city - name: city_temperature text: "Temperature in {%print $city%} is next." conditions: class: temperature entity_variables: city: $city - name: conditions text: Okay, type city name. conditions: class: conditions children: - name: conditions_city_selected text: "{%goto city_conditions%}" conditions: entity_variables: city: $city - name: temperature text: Okay, type city name. conditions: class: temperature children: - name: temperature_city_selected text: "{%goto city_temperature%}" conditions: entity_variables: city: $city entities: city: - Moscow - Tokyo - Ottava synonyms: Moscow: - default city - DC classes: temperature: - How hot is it today? - Is it hot outside? - Will it be uncomfortably hot? - Will it be sweltering? - How cold is it today? - Is it cold outside? - Will it be uncomfortably cold? - Will it be frigid? - What is the expected high for today? - What is the expected temperature? - Will high temperatures be dangerous? - Is it dangerously cold? - When will the heat subside? - Is it hot? - Is it cold? - How cold is it now? - Will we have a cold day today? - When will the cold subside? - What highs are we expecting? - What lows are we expecting? - Is it warm? - Is it chilly? - What's the current temp in Celsius? - What is the temperature in Fahrenheit? conditions: - Is it windy? - Will it rain today? - What are the chances for rain? - Will we get snow? - Are we expecting sunny conditions? - Is it overcast? - Will it be cloudy? - How much rain will fall today? - How much snow are we expecting? - Is it windy outside? - How much snow do we expect? - Is the forecast calling for snow today? - Will we see some sun? - When will the rain subside? - Is it cloudy? - Is it sunny now? - Will it rain? - Will we have much snow? - Are the winds dangerous? - What is the expected snowfall today? - Will it be dry? - Will it be breezy? - Will it be humid? - What is today's expected humidity? - Will the blizzard hit us? - Is it drizzling? classifier_params: filter_sizes: [1] hidden_size: 100 nb_filter: 150 min_class_confidence: 0.8 


Switching from one state to another (and at the same time - extracting entities) to another happens like this:


Under the hood, part 1


Awful bitbucket code . For starters - singled out such entities:


Now this is possible:

 script = Script.load(os.path.join(os.path.dirname(__file__), "script.yaml")) text_processor = TextProcessor("english", [["turn", "on"], ["turn", "off"]], Word2Vec.load_word2vec_format( os.path.join(os.path.dirname(__file__), "100d.txt") )) robot = Robot(script, text_processor) state, output = robot.output() self.assertEqual(output, "Hello. I'm weather robot. How can I help you?") self.assertIsNotNone(state) self.assertEqual(state.stage, "main") self.assertEqual(state.variables, {}) state, output = robot.answer(state, "How cold it'll be in Moscow today?") self.assertIsNotNone(state) self.assertEqual(state.stage, "city_temperature") self.assertEqual(state.variables, {"$city": ["Moscow"]}) self.assertEqual(output, "Temperature in Moscow is next.") 

You can already try to run something, but I went further.

Wrapper around robot and sqlalchemy. Yet without telegram


Even more awful bitbucket code . Again we divide entities:


Something like this:



Code example:

 from robotframework import * from sqlalchemy import select app = Application({ 'DATABASE_URI': '', 'KEEP_WORD_VECTORS': 4 }) robot = Robot.filter(lambda query: query.where(Robot.id == 1))[0] user = User.filter(lambda query: query.where(User.id == 1))[0] conversation = robot.converse(user) #print(robot.instance) items = lambda: print([str(item) for item in conversation.items]) items() conversation.output() conversation.answer('How hot it\'ll be in Moscow today?') conversation.answer('Okay, turn off') items() 

Well, as a result:

 [] ["Hello. I'm weather robot. How can I help you?", "How hot it'll be in Moscow today", "Temperature in Moscow is next", ""] 

The last entry is empty, because in the script there is no node on which to go in this case.

In the configuration - the following options:

 { 'DATABASE_URI' : '', # URI   sqlalchemy   'KEEP_WORD_VECTORS': 3, #       "" word2vec,    ,   ()     'KEEP_ROBOTS': 3, #     'ROBOT_CONFIGURATIONS': 'robot_configurations', # ,     , 'OUTPUT_HANDLERS': {} } 

Now we seem to have all the means for more or less adequate storage of robots, their states and auxiliary data. And - the ability to fasten them to different messengers (and not only), screwing the appropriate wrapper.

Telegram


Before viewing the code is recommended stock up on sedation . The wrapper adds a couple more fields to the models (telegram_chat_id in Conversation, telegram_bot_id in Robot). Well, multithreading in all fields.

Here is an example:

 import logging from robotframework_telegram import RobotFrameworkTelegram from config import config if __name__ == '__main__': bots = RobotFrameworkTelegram({ 'DATABASE_URI': 'URI', 'KEEP_WORD_VECTORS': 3, 'ROBOT_CONFIGURATIONS': 'robot_configurations', 'KEEP_ROBOTS': 5, 'OUTPUT_HANDLERS': {}, 'TOKENS': [ # Your tokens here ], 'NO_ANSWER_MESSAGE': 'Sorry, I can\'t answer now.', 'NO_INSTANCE_MESSAGE': 'Sorry, robot not instantiated yet. ' + \ 'You\'ll get answer after instantiation - it can take few minutes', 'TELEGRAM_WORKERS_PER_BOT': 1, 'WORKER_COUNT': 2, 'WORKER_SLEEP_TIME': 0.2, 'LOGGER': logging, }) bots.start_polling() 

And the dialogue obtained during the test

[7:14:55 AM]
/ start
[7:14:56 AM] robotframework_demo_weather:
Sorry, robot not instantiated yet. You'll get answer after instantiation - it can take a few minuutes
Hello. I'm weather robot. How can I help you?
[7:16:07 AM] #:
It's cold?
[7:16:08 AM] robotframework_demo_weather:
Okay, type city name.
[7:16:11 AM] #:
Moscow
[7:16:11 AM] robotframework_demo_weather:
Temperature in Moscow is next.

[7:40:25 AM] #:
/ start
[7:40:26 AM] robotframework_demo_weather:
Hello. I'm weather robot. How can I help you?
[7:40:48 AM] #:
What is your destination, robot? Seems like you must not answer
[7:40:48 AM] robotframework_demo_weather:
Sorry, I can't answer now.

Source: https://habr.com/ru/post/316838/


All Articles