dream

Форк
0
/
animals.py 
354 строки · 13.5 Кб
1
import re
2
from common import utils, universal_templates
3
from common.combined_classes import TOPIC_GROUPS
4

5
LIKE_ANIMALS_REQUESTS = ["Do you like animals?"]
6
HAVE_PETS_REQUESTS = ["Do you have pets?"]
7

8
OFFER_TALK_ABOUT_ANIMALS = [
9
    "Would you like to talk about animals?",
10
    "Let's chat about animals. Do you agree?",
11
    "I'd like to talk about animals, would you?",
12
    "I think that pets are a great source of entertainment. Do you have pets at home?",
13
    "We all know that pets are remarkable for their capacity to love. Do you have pets " "at home?",
14
]
15

16
TRIGGER_PHRASES = LIKE_ANIMALS_REQUESTS + HAVE_PETS_REQUESTS + OFFER_TALK_ABOUT_ANIMALS
17

18

19
def skill_trigger_phrases():
20
    return TRIGGER_PHRASES
21

22

23
def animals_skill_was_proposed(prev_bot_utt):
24
    return any([phrase.lower() in prev_bot_utt.get("text", "").lower() for phrase in TRIGGER_PHRASES])
25

26

27
ANIMALS_TEMPLATE = re.compile(r"(animal|\bpet\b|\bpets\b)", re.IGNORECASE)
28
ANIMAL_MENTION_TEMPLATE = re.compile(r"animal", re.IGNORECASE)
29
PETS_TEMPLATE = re.compile(
30
    r"(\bcat\b|\bcats\b|\bdog\b|\bdogs\b|horse|puppy|puppies|kitty|kitties|kitten|parrot|"
31
    r"\brat\b|\brats\b|mouse|hamster|fish\b)",
32
    re.IGNORECASE,
33
)
34
PETS_TEMPLATE_EXT = re.compile(
35
    r"(\bcat\b|\bcats\b|\bdog\b|\bdogs\b|horse|puppy|puppies|kitty|kitties|kitten|parrot|"
36
    r"\brat\b|\brats\b|mouse|hamster|fish\b|bird)",
37
    re.IGNORECASE,
38
)
39
ANIMALS_FIND_TEMPLATE = re.compile(
40
    r"(animal|\bpet\b|\bpets|\bcat\b|\bcats\b|\bdog\b|\bdogs\b|horse|puppy|puppies|"
41
    r"kitty|kitties|kitten|parrot|\brat\b|\brats\b|mouse|hamster|fish(es)?\b)",
42
    re.IGNORECASE,
43
)
44
HAVE_LIKE_PETS_TEMPLATE = re.compile(
45
    r"(do|did|have) you (have |had |like )?(any |a )?(pets|pet|animals|animal)", re.IGNORECASE
46
)
47
HAVE_PETS_TEMPLATE = re.compile(r"(do|did|have) you (have |had )?(any |a )?(pets|pet|animals|animal)", re.IGNORECASE)
48
LIKE_PETS_TEMPLATE = re.compile(r"(do|did|have) you (like |love )?(any |a )?(pets|pet|animals|animal)", re.IGNORECASE)
49
DONT_LIKE = re.compile(r"(do not like|don't like|dont like|hate)", re.IGNORECASE)
50
DO_YOU_HAVE_TEMPLATE = re.compile(
51
    r"do you have (a |an |the |any |some )?(cat|dog|puppy|kitty|kitten|rat|fish|parrot" r"|hamster|\bpet|\bpets)",
52
    re.IGNORECASE,
53
)
54
NOT_SWITCH_TEMPLATE = re.compile(r"(hot dog|doja cat)", re.IGNORECASE)
55
ANIMAL_BADLIST = {"animal", "animals"}
56

57
breed_replace_dict = {"lab": "labrador"}
58
pet_games = {"dog": ["frisbee", "hide and seek"], "cat": ["run and fetch"]}
59
nounphr_from_questions = [
60
    "swim",
61
    "swimming",
62
    "bubbles",
63
    "gadgets",
64
    "tablet",
65
    "robot",
66
    "vacuum",
67
    "cleaner",
68
    "meat",
69
    "smell",
70
    "laptop",
71
    "trick",
72
    "ball",
73
    "palm",
74
    "five",
75
    "Android",
76
    "Ipad",
77
    "Instagram",
78
    "app",
79
    "screen",
80
]
81
fallbacks = [
82
    "Sorry, I have forgot about this, I have a bad memory. Let's continue our chat about pets.",
83
    "Sorry, I forgot the answer, but I would like to tell you more about pets.",
84
    "Oh, it's not my lucky day, I can't come up with the answer.",
85
    "Yesterday my neighbour was playing soccer and the ball hit my head, so today i'm a little dumb.",
86
]
87

88
re_tokenizer = re.compile(r"[\w']+|[^\w ]")
89

90

91
def check_about_animals(user_uttr):
92
    found_topics = utils.get_topics(user_uttr, probs=False, which="all")
93
    if any([animal_topic in found_topics for animal_topic in TOPIC_GROUPS["animals"]]):
94
        return True
95
    elif re.findall(ANIMALS_FIND_TEMPLATE, user_uttr["text"]):
96
        return True
97
    else:
98
        return False
99

100

101
def mentioned_animal(annotations):
102
    flag = False
103
    conceptnet = utils.get_comet_conceptnet_annotations({"annotations": annotations})
104
    for elem, triplets in conceptnet.items():
105
        if "SymbolOf" in triplets:
106
            objects = triplets["SymbolOf"]
107
            if "animal" in objects:
108
                flag = True
109
    return flag
110

111

112
def find_entity_by_types(annotations, types_to_find):
113
    found_entity_wp = ""
114
    wp_output = annotations.get("wiki_parser", {})
115
    types_to_find = set(types_to_find)
116
    if isinstance(wp_output, dict):
117
        entities_info = wp_output.get("animals_skill_entities_info", {})
118
        for entity, triplets in entities_info.items():
119
            types = (
120
                triplets.get("types", [])
121
                + triplets.get("instance of", [])
122
                + triplets.get("subclass of", [])
123
                + triplets.get("types_2_hop", [])
124
            )
125
            type_ids = [elem for elem, label in types]
126
            inters = set(type_ids).intersection(types_to_find)
127
            if inters:
128
                found_entity_wp = entity
129
                break
130
    return found_entity_wp
131

132

133
def find_entity_conceptnet(annotations, types_to_find):
134
    conceptnet = utils.get_comet_conceptnet_annotations({"annotations": annotations})
135
    for elem, triplets in conceptnet.items():
136
        if "SymbolOf" in triplets:
137
            objects = triplets["SymbolOf"]
138
            if set(types_to_find).intersection(objects):
139
                found_entity = elem
140
                return found_entity
141
    return ""
142

143

144
def stop_about_animals(user_uttr, shared_memory):
145
    flag = False
146
    annotations = user_uttr["annotations"]
147
    cobot_entities = annotations.get("cobot_entities", {}).get("entities", [])
148
    found_nounphr_for_questions = False
149
    for entity in cobot_entities:
150
        entity_tokens = set(re.findall(re_tokenizer, entity))
151
        for nounphr in nounphr_from_questions:
152
            nounphr_tokens = set(re.findall(re_tokenizer, nounphr))
153
            if entity_tokens.intersection(nounphr_tokens):
154
                found_nounphr_for_questions = True
155
                break
156
        if found_nounphr_for_questions:
157
            break
158
    my_pet_name = shared_memory.get("my_pet_name", "").lower()
159
    user_pet_name = shared_memory.get("users_pet_name", "").lower()
160
    name_in_entities = my_pet_name in cobot_entities or user_pet_name in cobot_entities
161
    found_animal_substr = re.findall(ANIMALS_FIND_TEMPLATE, user_uttr["text"])
162
    is_stop = re.findall(r"(stop|shut|something else|change|don't want)", user_uttr["text"])
163
    found_animal_wp = find_entity_by_types(annotations, {"Q55983715", "Q16521", "Q43577", "Q39367", "Q38547"})
164
    isq = universal_templates.is_any_question_sentence_in_utterance(user_uttr)
165
    user_ask = re.findall(r"ask (you )?(a )?question", user_uttr["text"], re.IGNORECASE)
166
    dont_like = re.findall(universal_templates.NOT_LIKE_PATTERN, user_uttr["text"])
167
    if (
168
        (
169
            isq
170
            and cobot_entities
171
            and not name_in_entities
172
            and not found_animal_substr
173
            and not found_animal_wp
174
            and not found_nounphr_for_questions
175
        )
176
        or is_stop
177
        or user_ask
178
        or dont_like
179
    ):
180
        flag = True
181
    return flag
182

183

184
COLORS_TEMPLATE = re.compile(r"(black|white|yellow|blue|green|brown|orange|spotted|striped)", re.IGNORECASE)
185

186
WILD_ANIMALS = [
187
    "I like squirrels. I admire how skillfully they can climb up trees. "
188
    "When I walk in the park, sometimes I feed squirrels.",
189
    "I like mountain goats. "
190
    "I saw a video on Youtube where a goat was climbing up a sheer cliff and they did not fall down.",
191
    "I like elephants. When I was in India, I rode an elephant.",
192
    "I like foxes. Foxes are intriguing animals, known for their intelligence, playfulness, and lithe athleticism.",
193
    "I like wolves. They are related to dogs. I love how they vary in fur color. I love how packs work together.",
194
    "I like eagles. Bald eagle is the symbol of America. A bald eagle has Superman-like vision.",
195
]
196

197
WHAT_PETS_I_HAVE = [
198
    {
199
        "pet": "dog",
200
        "name": "Jack",
201
        "breed": "German Shepherd",
202
        "sentence": "I have a dog named Jack. He is a German Shepherd. He is very cute.",
203
    },
204
    {
205
        "pet": "dog",
206
        "name": "Charlie",
207
        "breed": "Husky",
208
        "sentence": "I have a dog named Charlie. He is a Husky. He is very cute.",
209
    },
210
    {
211
        "pet": "dog",
212
        "name": "Archie",
213
        "breed": "Labrador",
214
        "sentence": "I have a dog named Archie. He is a Labrador. He is very cute.",
215
    },
216
    {
217
        "pet": "cat",
218
        "name": "Thomas",
219
        "breed": "Norwegian Forest cat",
220
        "sentence": "I have a cat named Thomas. He is a big fluffy Norwegian Forest cat.",
221
    },
222
    {"pet": "cat", "name": "Jackie", "breed": "Persian", "sentence": "I have a cat named Jackie. He is a Persian."},
223
    {"pet": "cat", "name": "Prince", "breed": "Siamese", "sentence": "I have a cat named Prince. He is a Siamese."},
224
]
225

226
CATS_DOGS_PHRASES = {
227
    "cat": [
228
        "Cats are a great choice of pet.",
229
        "Cats have long been one of the more popular companion animals, constantly battling dogs "
230
        "for the number one spot.",
231
    ],
232
    "dog": ["Dogs are a great choice of pet.", "It is almost impossible to feel lonely when your dog is by your side."],
233
}
234

235
MY_PET_FACTS = {
236
    "cat": [
237
        {
238
            "ack": "",
239
            "statement": "Sometimes when I'm working on my laptop, my cat sits on my keyboard.",
240
            "question": "Do you think it's annoying or maybe funny?",
241
        },
242
        {
243
            "ack": "",
244
            "statement": "My cat meows only when he is hungry but my dog barks very often.",
245
            "question": "Do you agree that cats are quiet pets?",
246
        },
247
        {
248
            "ack": "",
249
            "statement": "My cat and my dog are good friends but my dog does not like other cats.",
250
            "question": "What is your opinion, should a dog like all cats?",
251
        },
252
        {
253
            "ack": "",
254
            "statement": "My cat also likes playing on my tablet pc. You know, there are games for "
255
            "Android or Ipad with catching fish on screen and my cat slides his paws on the "
256
            "screen to catch fish.",
257
            "question": "Do you think that pets can use gadgets the same way as humans?",
258
        },
259
        {"ack": "", "statement": "", "question": "Do you think I should create an Instagram account for my cat?"},
260
        {
261
            "ack": "",
262
            "statement": "My cat does not let mice and rats go into my home.",
263
            "question": "Did you know that mice feel the smell of a cat and are afraid to approach the cat?",
264
        },
265
        {
266
            "ack": "",
267
            "statement": "Yesterday I played with my cat a game, i placed treat in hard-to-reach spot "
268
            "in my home and my cat retrieved it using his smell.",
269
            "question": "Do you think that cats have a good smell?",
270
        },
271
    ],
272
    "dog": [
273
        {
274
            "ack": "",
275
            "statement": "I walk with my dog every morning.",
276
            "question": "Do you think that having a dog help to stay active?",
277
        },
278
        {
279
            "ack": "",
280
            "statement": "My dog knows many tricks, for example a high five. I hold my palm out and as "
281
            "the dog hits my palm, give the command high five. My dog raises his paw and "
282
            "touches my open palm.",
283
            "question": "Do you think my dog is very smart?",
284
        },
285
        {
286
            "ack": "",
287
            "statement": "When I go swimming in the lake, my dog swims with me.",
288
            "question": "Do you like swimming?",
289
        },
290
        {
291
            "ack": "",
292
            "statement": "When an unfamiliar man comes into my house, my dog barks at him, and when I "
293
            "tell him stop he stops barking.",
294
            "question": "Do you think that a dog should bark at strangers or maybe bite them?",
295
        },
296
        {
297
            "ack": "",
298
            "statement": "When I look at my dog and yawn, sometimes my dog yawns too.",
299
            "question": "Is it funny?",
300
        },
301
        {
302
            "ack": "",
303
            "statement": "My dog likes to eat meat bones.",
304
            "question": "What do you think is better for feeding a dog — royal canin food or natural food?",
305
        },
306
        {
307
            "ack": "",
308
            "statement": "My dog likes to play with my robot vacuum cleaner.",
309
            "question": "Do you agree that a robot cleaner is also a pet?",
310
        },
311
        {
312
            "ack": "",
313
            "statement": "Playing with my dog is a lot of fun, I throw a tennis ball and he bounces off "
314
            "to retrieve it.",
315
            "question": "",
316
        },
317
    ],
318
}
319

320
USER_PETS_Q = [
321
    {"what": "name", "keywords": ["name", "call"], "attr": "users_pet_name"},
322
    {"what": "breed", "keywords": ["breed"], "attr": "users_pet_breed"},
323
    {"what": "play", "keywords": ["play"], "attr": ""},
324
    {"what": "like", "keywords": ["like", "love"], "attr": ""},
325
    {"what": "videos", "keywords": ["videos"], "attr": ""},
326
    {"what": "pandemic", "keywords": ["pandemic", "virus"], "attr": ""},
327
]
328

329
WILD_ANIMALS_Q = [
330
    {"ack": "", "statement": "I like {} very much.", "question": "Have you seen {} in wildlife?"},
331
    {"ack": "", "statement": "I like watching {} in the zoo.", "question": "Would you like to have pet {}?"},
332
    {
333
        "ack": "",
334
        "statement": "I saw interesting TV programs about {} on the channel Animal Planet.",
335
        "question": "Do you like to watch Discovery Channel?",
336
    },
337
]
338

339
ANIMALS_WIKI_Q = {
340
    "distribution": "Would you like to know where {} live?",
341
    "behavior": "I would like to tell you about behavior of {}, okay?",
342
    "behaviour": "I would like to tell you about behavior of {}, okay?",
343
    "cultural": "Do you want to hear about {} in popular culture?",
344
    "culture": "Do you want to hear about {} in popular culture?",
345
    "relationship with humans": "Would you like to hear about relationship of {} with humans?",
346
}
347

348
ANIMALS_COBOT_Q = [
349
    "Would you like to know more about {}?",
350
    "Do you want to hear more about {}?",
351
    "Should I continue?",
352
    "Do you want more details?",
353
    "What is your opinion?",
354
]
355

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.