dream

Форк
0
1747 строк · 69.9 Кб
1
# %%
2
import os
3
import logging
4
import random
5
from enum import Enum, auto
6
import re
7

8
import sentry_sdk
9

10
from dff import dialogflow_extension
11
import common.dialogflow_framework.utils.state as state_utils
12
import common.dialogflow_framework.utils.condition as condition_utils
13
import common.utils as common_utils
14
import common.constants as common_constants
15
import common.news as general_this_news
16
from common.gossip import talk_about_gossip, skill_trigger_phrases
17
from common.fact_random import get_fact
18

19
import dialogflows.scenarios.gossip as this_gossip
20
import common.gossip as common_gossip
21
import dialogflows.scenarios.news as this_news
22

23
import dialogflows.scopes as scopes
24

25
from dialogflows.flows import utils
26

27
sentry_sdk.init(dsn=os.getenv("SENTRY_DSN"))
28
NEWS_API_ANNOTATOR_URL = os.environ.get("NEWS_API_ANNOTATOR_URL")
29
assert NEWS_API_ANNOTATOR_URL
30

31
logger = logging.getLogger(__name__)
32

33

34
class State(Enum):
35
    USR_START = auto()
36

37
    SYS_TOPIC_TO_EVENT = auto()
38
    USR_TOPIC_TO_EVENT = auto()
39

40
    SYS_NO_OR_YES = auto()
41
    USR_NO_OR_YES = auto()
42

43
    SYS_EVENT_TO_PERSON = auto()
44
    USR_EVENT_TO_PERSON = auto()
45

46
    # BEGIN: USR_NOT_INTERESTED_IN_PERSON
47
    SYS_NOT_INTERESTED_IN_PERSON = auto()
48
    USR_NOT_INTERESTED_IN_PERSON = auto()
49

50
    SYS_CHANGE_TO_PERSON = auto()
51
    USR_CHANGE_TO_PERSON = auto()
52
    # transitions back to:
53
    # NOT_INTERESTED_IN_PERSON
54
    # AGREES_ABT_PERSON
55
    # DISAGREES_ABT_PERSON
56
    # SAYS_OPINION_ABT_PERSON
57
    # END
58

59
    # BEGIN: USR_AGREES_ABT_PERSON
60
    SYS_AGREES_ABT_PERSON = auto()
61
    USR_AGREES_ABT_PERSON = auto()
62

63
    SYS_PERSON_AGREE = auto()
64
    USR_PERSON_AGREE = auto()
65

66
    SYS_SAYS_SOMETHING_AFTER_AGREE = auto()
67
    USR_SAYS_SOMETHING_AFTER_AGREE = auto()
68
    # transitions back to:
69
    # NOT_INTERESTED_IN_PERSON
70
    # AGREES_ABT_PERSON
71
    # DISAGREES_ABT_PERSON
72
    # SAYS_OPINION_ABT_PERSON
73
    # END
74

75
    # BEGIN
76
    SYS_DISAGREES_ABT_PERSON = auto()
77
    USR_DISAGREES_ABT_PERSON = auto()
78

79
    SYS_PERSON_DISAGREE = auto()
80
    USR_PERSON_DISAGREE = auto()
81

82
    SYS_SAYS_SOMETHING_AFTER_DISAGREE = auto()
83
    USR_SAYS_SOMETHING_AFTER_DISAGREE = auto()
84
    # transitions back to:
85
    # NOT_INTERESTED_IN_PERSON
86
    # AGREES_ABT_PERSON
87
    # DISAGREES_ABT_PERSON
88
    # SAYS_OPINION_ABT_PERSON
89
    # END
90

91
    # BEGIN: USR_SAYS_OPINION_ABT_PERSON
92
    SYS_SAYS_OPINION_ABT_PERSON = auto()
93
    USR_SAYS_OPINION_ABT_PERSON = auto()
94

95
    SYS_PERSON_OPINION = auto()
96
    USR_PERSON_OPINION = auto()
97

98
    SYS_SAYS_SOMETHING_AFTER_OPINION = auto()
99
    USR_SAYS_SOMETHING_AFTER_OPINION = auto()
100
    # transitions back to:
101
    # NOT_INTERESTED_IN_PERSON
102
    # AGREES_ABT_PERSON
103
    # DISAGREES_ABT_PERSON
104
    # SAYS_OPINION_ABT_PERSON
105
    # END
106

107
    SYS_MENTIONS_ANOTHER_PERSON = auto()
108
    USR_MENTIONS_ANOTHER_PERSON = auto()
109

110
    # Helpers: Error
111
    SYS_ERR = auto()
112
    USR_ERR = auto()
113

114
    # Helpers: End?
115
    SYS_END = auto()
116
    USR_END = auto()
117

118

119
# endregion
120

121

122
# region CONFIDENCES
123
DIALOG_BEGINNING_START_CONFIDENCE = 0.98
124
DIALOG_BEGINNING_CONTINUE_CONFIDENCE = 0.9
125
DIALOG_BEGINNING_SHORT_ANSWER_CONFIDENCE = 0.98
126
MIDDLE_DIALOG_START_CONFIDENCE = 0.7
127
SUPER_CONFIDENCE = 1.0
128
HIGH_CONFIDENCE = 0.98
129

130
MUST_CONTINUE_CONFIDENCE = 0.98
131
CANNOT_CONTINUE_CONFIDENCE = 0.0
132
# endregion
133

134
# endregion
135

136
################################################################################
137
# %%
138

139

140
##################################################################################################################
141
# Init DialogFlow
142
##################################################################################################################
143

144

145
simplified_dialogflow = dialogflow_extension.DFEasyFilling(State.USR_START)
146

147

148
##################################################################################################################
149
##################################################################################################################
150
# Design DialogFlow.
151
##################################################################################################################
152
##################################################################################################################
153
##################################################################################################################
154
# utils
155

156

157
def get_people_for_topic(cobot_topic):
158
    # human-curated list (top 10-20 for 2010s)
159
    peoples = [
160
        list(x.get("People", [])) for x in common_gossip.TOPICS_TO_PEOPLE_MAPPINGS if x.get("Topic", "") == cobot_topic
161
    ]
162
    peoples = list(set(sum(peoples, [])))
163
    # wikidata-based list
164
    top_people_from_wiki = utils.get_top_people_from_wiki_for_cobot_topic(cobot_topic, peoples)
165
    return top_people_from_wiki + peoples
166

167

168
def get_phrase_about_person_in_content(person, content):
169
    # TODO: "." for what?
170
    sentences_list = content.split(".")
171

172
    for sentence in sentences_list:
173
        if sentence.lower().count(person.lower()) > 0:
174
            return sentence
175

176

177
def save_mentioned_person(vars, person, judgement, share_memory_key):
178
    if person:
179
        shared_memory = state_utils.get_shared_memory(vars)
180
        # "people_mentioned_by_bot"
181
        # obtaining a list of previously mentioned people
182
        all_mentioned_people = shared_memory.get(share_memory_key, [])
183
        are_judgements = [x.get("Judgement", "") == judgement for x in all_mentioned_people]
184
        if sum(are_judgements) == 0:
185
            all_mentioned_people.append({"Judgement": judgement, "People": []})
186
            are_judgements.append(True)
187
        judgement_index = are_judgements.index(True)
188
        people_list = all_mentioned_people[judgement_index]["People"]
189
        is_this_person = people_list and people_list[-1] == person
190
        if not is_this_person:
191
            all_mentioned_people[judgement_index]["People"].append(person)
192
        state_utils.save_to_shared_memory(vars, **{share_memory_key: all_mentioned_people})
193

194

195
def get_mentioned_people(vars, share_memory_key="", judgements=["Liked", "Disliked", "Not Interested", "Other"]):
196
    shared_memory = state_utils.get_shared_memory(vars)
197
    # obtaining a list of previously mentioned people
198
    all_mentioned_people = shared_memory.get(share_memory_key, [])
199
    if all_mentioned_people:
200
        peoples = [list(x.get("People", [])) for x in all_mentioned_people if x.get("Judgement", "") in judgements]
201
        peoples = list(set(sum(peoples, [])))
202
        return peoples
203
    else:
204
        return []
205

206

207
# inefficient if number of people is finite
208
def get_fresh_person_for_topic(vars, cobot_topic):
209
    all_mentioned_people = set(get_mentioned_people(vars, share_memory_key="people_mentioned_by_bot"))
210
    topic_people = [
211
        list(i.get("People", [])) for i in common_gossip.TOPICS_TO_PEOPLE_MAPPINGS if i.get("Topic", "") == cobot_topic
212
    ]
213
    topic_people = sum(topic_people, [])
214
    topic_people = set(topic_people)
215
    topic_people = topic_people - all_mentioned_people
216
    if topic_people:
217
        return random.choice(list(topic_people))
218

219

220
def mark_news_as_mentioned_by_bot(vars, news_title):
221
    shared_memory = state_utils.get_shared_memory(vars)
222

223
    # obtaining a list of previously mentioned news
224
    all_mentioned_news = shared_memory.get("news_mentioned_by_bot", [])
225

226
    all_mentioned_news.append(news_title)
227
    # saving
228
    state_utils.save_to_shared_memory(vars, all_mentioned_news=all_mentioned_news)
229

230

231
def get_people_related_to_bot_mentioned_ones(vars, user_mentioned_person):
232
    # for the time being, we support only one user
233
    related_people = []
234

235
    if not user_mentioned_person:
236
        return related_people
237

238
    # user_mentioned_person = user_mentioned_people[0]
239

240
    people_mentioned_and_liked_by_bot = get_mentioned_people(vars, "people_mentioned_by_bot", ["Liked", "Disliked"])
241

242
    for person in people_mentioned_and_liked_by_bot:
243
        relationship = utils.get_relationship_between_two_people(user_mentioned_person, person)
244
        if relationship:
245
            related_people.append([person, relationship])
246

247
    return related_people
248

249

250
def get_people_related_to_user_mentioned_ones(vars, user_mentioned_person):
251
    # for the time being, we support only one user
252
    related_people = []
253

254
    if not user_mentioned_person:
255
        return related_people
256

257
    # user_mentioned_person = user_mentioned_people[0]
258

259
    people_mentioned_and_liked_by_user = get_mentioned_people(vars, "people_mentioned_by_user", ["Liked", "Disliked"])
260

261
    for person in people_mentioned_and_liked_by_user:
262
        relationship = utils.get_relationship_between_two_people(user_mentioned_person, person)
263
        if relationship:
264
            related_people.append([person, relationship])
265

266
    return related_people
267

268

269
def get_news_for_topic(vars, cobot_topic):
270
    people = get_people_for_topic(cobot_topic)
271
    mentioned_people = get_mentioned_people(vars, share_memory_key="people_mentioned_by_bot")
272
    people = [person for person in people if person not in mentioned_people]
273

274
    if people:
275
        person = random.choice(people)
276
        curr_news = general_this_news.get_news_about_topic(person, NEWS_API_ANNOTATOR_URL)
277
        logger.debug(f"news = {curr_news}")
278

279
        if curr_news and "content" in curr_news and "title" in curr_news:
280
            content = curr_news["content"].split("[")[0]
281
            title = curr_news["title"]
282

283
            if person.lower() in content.lower():
284
                logger.debug("random_person was mentioned in content")
285
                filtered_content = get_phrase_about_person_in_content(person.lower(), content.lower())
286
                return person, title, filtered_content
287
            elif person.lower() in title.lower():
288
                logger.debug("random_person was mentioned in title")
289
                return person, title, content
290

291
    topic_news = [
292
        list(i["News"]) for i in this_news.TEMPORARY_NEWS_FOR_COBOT_TOPICS if i.get("Topic", "") == cobot_topic
293
    ]
294
    topic_news = sum(topic_news, [])
295
    logger.debug(f"topic_news={topic_news}")
296
    if topic_news:
297
        random_news = random.choice(topic_news)
298
        person = random_news["Person"]
299
        title = random_news["Title"]
300
        content = random_news["Content"]
301
    else:
302
        person = ""
303
        title = ""
304
        content = ""
305

306
    return person, title, content
307

308

309
def get_random_judgement_for_emotion(emotion):
310
    judgements = [
311
        list(x.get("People", [])) for x in this_gossip.TARGET_JUDGEMENTS_FOR_EMOTION if x["Emotion"] in emotion
312
    ]
313
    judgements = list(set(sum(judgements, [])))
314
    return random.choice(judgements) if judgements else "Great"
315

316

317
supported_cobot_topics = [
318
    "Entertainment_Movies",
319
    "Entertainment_Music",
320
    "Entertainment_Books",
321
    "Sports",
322
    "Politics",
323
    "Entertainment_General",
324
    "Science_and_Technology",
325
]
326

327

328
def get_supported_cobot_topics(vars):
329
    topics = common_utils.get_topics(state_utils.get_last_human_utterance(vars), which="cobot_dialogact_topics")
330
    selected_topics = set(topics) & set(supported_cobot_topics)
331
    selected_topics = selected_topics if selected_topics else supported_cobot_topics
332
    return selected_topics
333

334

335
##################################################################################################################
336
# error
337
##################################################################################################################
338

339

340
def error_response(vars):
341
    logger.debug("exec error_response")
342
    state_utils.set_confidence(vars, CANNOT_CONTINUE_CONFIDENCE)
343
    state_utils.set_confidence(vars, 0)
344
    return ""
345

346

347
##################################################################################################################
348
# Handlers
349
##################################################################################################################
350

351

352
def talk_about_gossip_request(ngrams, vars):
353
    human_utterance = state_utils.get_last_human_utterance(vars)
354
    bot_utterance = state_utils.get_last_bot_utterance(vars)
355
    flag = talk_about_gossip(human_utterance, bot_utterance)
356
    logger.info(f"talk_about_gossip_request: {flag}")
357
    return flag
358

359

360
# region CELEBRITY
361
##################################################################################################################
362

363

364
def set_people_jobs(vars, celebrity_name, core_jobs, other_jobs, mentioned_jobs):
365
    shared_memory = state_utils.get_shared_memory(vars)
366
    people_jobs = shared_memory.get("people_jobs", {})
367
    mentioned_jobs = people_jobs.get(celebrity_name, {}).get("Mentioned_Jobs", []) + mentioned_jobs
368
    mentioned_jobs = list(set(mentioned_jobs))
369
    people_jobs[celebrity_name] = {"Jobs": core_jobs, "Other_Jobs": other_jobs, "Mentioned_Jobs": mentioned_jobs}
370
    state_utils.save_to_shared_memory(vars, people_jobs=people_jobs)
371

372

373
def get_people_jobs(vars, celebrity_name):
374
    shared_memory = state_utils.get_shared_memory(vars)
375
    people_jobs = shared_memory.get("people_jobs", {})
376
    celebrity_jobs = people_jobs.get(celebrity_name, {})
377
    argument_names = ["Jobs", "Other_Jobs", "Mentioned_Jobs"]
378
    return [celebrity_jobs.get(argument_name, []) for argument_name in argument_names]
379

380

381
def get_mentioned_jobs(vars, celebrity_name):
382
    jobs = get_people_jobs(vars, celebrity_name)[-1]
383
    return jobs if jobs else []
384

385

386
def get_celebrity_from_uttr(vars, exclude_types=False, use_only_last_utt=False):
387
    # Look only at one turn
388
    # shared_memory = state_utils.get_shared_memory(vars)
389
    human_utterance = state_utils.get_last_human_utterance(vars)
390
    logger.debug(f'Calling get_celebrity_from_uttr on {human_utterance["text"]} {exclude_types} {use_only_last_utt}')
391

392
    # we need to get all supported occupations
393
    celebrity_name, matching_types, mismatching_types = common_gossip.celebrity_from_uttr(human_utterance)
394
    logger.warning(f"Relations {celebrity_name} {matching_types} {mismatching_types}")
395
    if not celebrity_name or not matching_types:
396
        return None, None
397
    mentioned_jobs = get_mentioned_jobs(vars, celebrity_name)
398
    mismatching_types = [type_ for type_ in mismatching_types if type_ not in mentioned_jobs]
399
    if exclude_types and mismatching_types:
400
        mentioned_job = random.choice(mismatching_types)
401
    else:
402
        mentioned_job = random.choice(matching_types)
403
    set_people_jobs(vars, celebrity_name, matching_types, mismatching_types, mentioned_jobs + [mentioned_job])
404
    logger.debug(f"Answer for get_celebrity exclude_types {exclude_types} : {celebrity_name} {mentioned_job}")
405

406
    return celebrity_name, mentioned_job
407

408

409
def sys_celebrity_found_request(ngrams, vars, use_only_last_utt=True):
410
    shared_memory = state_utils.get_shared_memory(vars)
411
    asked_celebrities = shared_memory.get("asked_celebrities", [])
412
    person, occupation = get_celebrity_from_uttr(vars, use_only_last_utt=use_only_last_utt)
413
    flag = person and person not in asked_celebrities
414
    logger.info(f"celebrity_in_phrase_request : {flag}")
415
    return flag
416

417

418
# get occupations for current_person
419
# build phrase about
420
def get_celebrity_prompt(vars, person):
421
    logger.debug("Celebrity branch")
422
    shared_memory = state_utils.get_shared_memory(vars)
423
    # persons = get_mentioned_people(vars, share_memory_key="people_mentioned_by_user")
424
    just_was_celebrity_prompt = shared_memory.get("celebrity_prompt", False)
425
    used_celeb_prompts = shared_memory.get("used_celeb_prompts", [])
426
    last_bot_uttr = state_utils.get_last_bot_utterance(vars)["text"]
427
    prompt = None
428
    if person:
429
        # logger.info(f"get_celebrity_prompt for people: {persons}")
430
        # logger.debug(str(persons[-1]))
431
        # person = persons[-1]
432
        logger.info(f"get_celebrity_prompt for person: {person}")
433
        matching_jobs, mismatching_jobs, mentioned_jobs = get_people_jobs(vars, person)
434
        logger.info(f"{person} {matching_jobs} {mismatching_jobs}")
435
        logger.info(f"Mismatching_jobs len {len(mismatching_jobs)}")
436
        if matching_jobs:
437
            logger.info(f"get_celebrity_prompt: matching jobs! just was celebrity prompt? {just_was_celebrity_prompt}")
438
            is_actor = "actor" in " ".join(matching_jobs)
439
            prompt_candidate = (
440
                f"{person} is an amazing {matching_jobs[0]}! " "Would you like to learn more about this person?"
441
            )
442
            we_not_repeat_start_prompt = prompt_candidate not in used_celeb_prompts
443
            actor_asking = "What is your favourite film with this actor?"
444
            if not just_was_celebrity_prompt and matching_jobs and we_not_repeat_start_prompt:
445
                logger.debug("start prompt")
446
                prompt = prompt_candidate
447
            elif just_was_celebrity_prompt and matching_jobs and mismatching_jobs and actor_asking not in last_bot_uttr:
448
                logger.info("get_celebrity_prompt: just was celebrity prompt and actor:")
449
                rand_job = random.choice(mismatching_jobs)
450
                prompt = f"{person} is also a {rand_job}. "
451
                if "actor" in rand_job:
452
                    asking = actor_asking
453
                else:
454
                    questions = this_gossip.WANT_TO_HEAR_ANOTHER_FACT
455
                    asking = random.choice(questions)
456
                prompt = f"{prompt} {asking}"
457
                mismatching_jobs.remove(rand_job)
458
                mentioned_jobs.append(rand_job)
459
                save_mentioned_person(vars, person, "Other", "people_mentioned_by_user")
460
                set_people_jobs(vars, person, matching_jobs, mismatching_jobs, mentioned_jobs)
461
            elif just_was_celebrity_prompt and matching_jobs and actor_asking not in last_bot_uttr:
462
                logger.info("get_celebrity_prompt: just was celebrity prompt and actor:")
463
                prompt = get_cobot_fact(person, used_celeb_prompts)
464
                logger.debug(f"Cobot prompt {prompt}")
465
            elif just_was_celebrity_prompt and not mismatching_jobs and not is_actor:
466
                logger.info("get_celebrity_prompt: just was celebrity prompt and non-actor:")
467
                prompt = get_cobot_fact(person, used_celeb_prompts)
468
                logger.debug(f"Cobot prompt {prompt}")
469
            if prompt:
470
                state_utils.save_to_shared_memory(
471
                    vars, celebrity_prompt=True, used_celeb_prompts=used_celeb_prompts + [prompt]
472
                )
473
    return prompt
474

475

476
# region TOPIC_TO_EVENT
477
##################################################################################################################
478

479

480
def sys_topic_to_event_request(ngrams, vars):
481
    # we get here because user mentioned a topic, or we've got a topic
482
    # ok so let's for the time being believe that we are here by default - just because a topic was mentioned
483
    bot_utterance = state_utils.get_last_bot_utterance(vars)
484
    flag = (bool(get_supported_cobot_topics(vars)) and talk_about_gossip_request(ngrams, vars)) or (
485
        any([phrase in bot_utterance["text"] for phrase in skill_trigger_phrases()])
486
        and condition_utils.is_yes_vars(vars)
487
    )
488
    logger.info(f"sys_topic_to_event={flag}")
489
    return flag
490

491

492
def default_condition_request(ngrams, vars):
493
    flag = True
494
    flag = flag and not condition_utils.is_switch_topic(vars)
495
    flag = flag and not condition_utils.is_lets_chat_about_topic_human_initiative(vars)
496
    flag = flag and not condition_utils.is_question(vars)
497
    flag = flag or talk_about_gossip_request(ngrams, vars)
498
    return flag
499

500

501
def usr_topic_to_event_response(vars):
502
    # %ack%. So, speaking of %target_topic%, this happened recently: %event%. Have you heard about it?
503
    logger.debug("exec usr_topic_to_event_response")
504
    try:
505
        selected_topics = get_supported_cobot_topics(vars)
506
        if selected_topics:
507
            cobot_topic = random.choice(list(selected_topics))  # "Entertainment_Movies" # for the time being
508
        else:
509
            return error_response(vars)
510

511
        # obtaining person, news_title, news_content for a given cobot_topic
512
        person, news_title, news_content = get_news_for_topic(vars, cobot_topic)
513
        logger.debug(f"person = {person}, news_title = {news_title}, news_content = {news_content}, ")
514

515
        person = person.strip()
516
        if person and person.lower() in news_title.lower():
517
            logger.debug(f"News about {person} : {news_title}")
518
            event = news_title
519
        elif person and person.lower() in news_content.lower():
520
            logger.debug(f"News about {person} : It's said that {news_content}: {news_title}")
521
            event = news_content
522
        else:
523
            # for testing purposes only
524
            event = "Natasha Romanoff (Scarlett Johansson) is going back to where it all started"
525
            person = "Scarlett Johansson"
526
            news_title = "Disney will release Scarlett Johansson in Black Widow in theaters and streaming in July"
527

528
        # get ack, body
529
        ack = condition_utils.get_not_used_and_save_sentiment_acknowledgement(vars)
530

531
        # saving person to the list of people mentioned by bot, for now with "Other" judgement
532
        save_mentioned_person(vars, person, "Other", "people_mentioned_by_bot")
533
        # saving news as mentioned by bot
534
        mark_news_as_mentioned_by_bot(vars, news_title)
535

536
        state_utils.save_to_shared_memory(vars, current_person=person)
537

538
        # saving current cobot_topic
539
        state_utils.save_to_shared_memory(vars, current_cobot_topic=cobot_topic)
540

541
        # generating response
542

543
        topic = this_news.COBOT_TO_HUMAN_READABLE_TOPICS.get(cobot_topic)
544
        questions = this_gossip.TOPIC_TO_EVENT_QUESTIONS
545
        questions = questions if topic else [i for i in questions if "target_topic" not in i]
546
        questions = questions if event else [i for i in questions if "target_event" not in i]
547

548
        if not questions:
549
            return error_response(vars)
550

551
        body = random.choice(questions)
552

553
        body = body.replace("target_topic", topic) if topic else body
554
        body = body.replace("target_event", event)
555

556
        # set confidence
557
        state_utils.set_confidence(vars, SUPER_CONFIDENCE)
558
        # can continue = true
559
        state_utils.set_can_continue(vars, common_constants.MUST_CONTINUE)
560

561
        return " ".join([ack, body])
562
    except Exception as exc:
563
        logger.exception(exc)
564
        sentry_sdk.capture_exception(exc)
565
        return error_response(vars)
566

567

568
# endregion
569

570
# region NO_OR_YES
571
################################################################################
572

573

574
def sys_no_or_yes_request(ngrams, vars):
575
    logger.debug("sys_no_or_yes_request: BEGIN")
576
    flag = False
577

578
    human_utterance = state_utils.get_last_human_utterance(vars)
579

580
    sf_type, sf_confidence = utils.get_speech_function_for_human_utterance(human_utterance)
581

582
    # using speech function classifier for agree (yes)
583
    # (with the aid of MIDAS & Intents for now)
584
    flag = utils.is_speech_function_agree(vars)
585

586
    # using speech function classifier for disagree (no)
587
    if not flag:
588
        flag = utils.is_speech_function_disagree(vars)
589
    flag = flag and default_condition_request(ngrams, vars)
590
    logger.info(f"sys_no_or_yes_request={flag}")
591
    return flag
592

593

594
def usr_event_to_person_response(vars):
595
    # %ack%. %Person% particularly interested me.
596
    # I %usuality_modulation_level% %Person% is a %complement% %occupation%.
597
    # %Judgement%. But... What do you think?
598
    logger.debug("exec usr_event_to_person_response")
599
    try:
600
        shared_memory = state_utils.get_shared_memory(vars)
601

602
        # obtaining current person
603
        current_person = shared_memory.get("current_person", "")
604
        current_cobot_topic = shared_memory.get("current_cobot_topic", "")
605

606
        # TEMPORARY OVERRIDE
607
        # current_cobot_topic = "Entertainment_Movies"
608

609
        # Positive or Negative
610
        emotion_reaction_options = ["Liked", "Disliked"]
611
        # trusting holy RNG
612
        target_emotion_type = random.choice(emotion_reaction_options)
613
        target_judgement = get_random_judgement_for_emotion(target_emotion_type)
614

615
        # saving current bot's emotion towards the currently discussed person
616
        state_utils.save_to_shared_memory(vars, bot_emotion_towards_current_person=target_emotion_type)
617

618
        # get ack, body
619
        ack = condition_utils.get_not_used_and_save_sentiment_acknowledgement(vars)
620

621
        # generating response
622
        body = random.choice(this_gossip.EVENT_TO_PERSON_QUESTIONS)
623

624
        # putting actual person's name into an upcoming utterance
625
        body = body.replace("target_person", current_person)
626
        body = body.replace("target_judgement", target_judgement)
627

628
        # obtaining occupation (person/generic/wiki-based)
629
        occupation = utils.get_occupation_for_person(current_person, current_cobot_topic, body)
630

631
        logger.info(f"found occupation: {occupation}")
632

633
        # saving it
634
        state_utils.save_to_shared_memory(vars, current_person_occupation=occupation)
635

636
        # further updating body with the obtained occupation
637
        body = body.replace("target_occupation", occupation)
638

639
        # building prompt
640
        prompt = random.choice(this_gossip.AGREEMENT_PROMPTS)
641

642
        state_utils.set_confidence(vars, MUST_CONTINUE_CONFIDENCE)
643
        # can continue = true
644
        state_utils.set_can_continue(vars, common_constants.CAN_CONTINUE_SCENARIO)
645

646
        return " ".join([ack, body, prompt])
647
    except Exception as exc:
648
        logger.exception(exc)
649
        sentry_sdk.capture_exception(exc)
650
        return error_response(vars)
651

652

653
# endregion
654

655

656
# region LOOP #1: NOT_INTERESTED_IN_PERSON
657

658
# STEP 1
659
################################################################################
660

661

662
def get_cobot_fact(celebrity_name, given_facts):
663
    logger.debug(f"Calling cobot_fact for {celebrity_name} {given_facts}")
664
    answer = get_fact(celebrity_name, f"fact about {celebrity_name}")
665
    if answer is None:
666
        error_message = f"Answer from random fact or fact about {celebrity_name} not obtained"
667
        logger.error(error_message)
668
        return None
669
    for phrase_ in ["This might answer your question", "According to Wikipedia"]:
670
        if phrase_ in answer:
671
            answer = answer.split(phrase_)[1]
672
    logger.debug(f"Answer from cobot_fact obtained {answer}")
673
    if answer not in given_facts:
674
        return answer
675
    else:
676
        return ""
677

678

679
def sys_not_interested_in_person_request(ngrams, vars):
680
    flag = False
681
    human_utterance = state_utils.get_last_human_utterance(vars)
682

683
    sf_type, sf_confidence = utils.get_speech_function_for_human_utterance(human_utterance)
684
    logger.debug(f"sys_not_interested_in_person_request: Speech Function: {sf_type}")
685

686
    # using speech function classifier for not interested
687
    flag = utils.is_not_interested_speech_function(vars)
688
    flag = flag and default_condition_request(ngrams, vars)
689

690
    logger.info(f"sys_not_interested_in_person_request={flag}")
691
    return flag
692

693

694
def usr_not_interested_in_person_response(vars):
695
    logger.debug("exec usr_not_interested_in_person_response")
696
    try:
697
        shared_memory = state_utils.get_shared_memory(vars)
698
        # obtaining current context
699
        current_cobot_topic = shared_memory.get("current_cobot_topic", "")
700
        # getting human-readable version
701
        # TODO
702
        human_topic = this_news.COBOT_TO_HUMAN_READABLE_TOPICS.get(current_cobot_topic)
703

704
        # obtaining new random person + news for current cobot_topic
705
        person = get_fresh_person_for_topic(vars, current_cobot_topic)
706
        if not person:
707
            raise Exception(f"Have no fresh person for {current_cobot_topic}")
708

709
        # Positive or Negative
710
        emotion_reaction_options = ["Liked", "Disliked"]
711
        # trusting holy RNG
712
        target_emotion_type = random.choice(emotion_reaction_options)
713
        target_judgement = get_random_judgement_for_emotion(target_emotion_type)
714

715
        # saving current bot's emotion towards the currently discussed person
716
        state_utils.save_to_shared_memory(vars, bot_emotion_towards_current_person=target_emotion_type)
717

718
        # saving person to the list of people mentioned by bot, for now with "Other" judgement
719
        save_mentioned_person(vars, person, "Liked", "people_mentioned_by_bot")
720
        # setting current context (only person, we didn't change topic)
721
        state_utils.save_to_shared_memory(vars, current_person=person)
722

723
        # generating response
724
        ack = f"{random.choice(this_gossip.NOT_INTERESTED_IN_PERSON_ACKNOWLEDGEMENTS)}."
725
        prompt = random.choice(this_gossip.CHANGE_TO_OTHER_PERSON_QUESTIONS)
726

727
        # occupation
728
        occupation = utils.get_occupation_for_person(person, current_cobot_topic, prompt)
729

730
        fake_utterance = f"I like to learn more about {occupation} {person} {human_topic}"
731
        gender, age = utils.get_gender_age_person(person, fake_utterance)
732

733
        gender_is = utils.get_human_readable_gender_statement_current_is(gender)
734

735
        prompt = prompt.replace("target_person", person)
736
        prompt = prompt.replace("target_topic", human_topic)
737
        prompt = prompt.replace("target_judgement", target_judgement)
738
        prompt = prompt.replace("target_gender_is", gender_is)
739

740
        # saving it
741
        state_utils.save_to_shared_memory(vars, current_person_occupation=occupation)
742

743
        prompt = prompt.replace("target_occupation", occupation)
744

745
        state_utils.set_confidence(vars, MUST_CONTINUE_CONFIDENCE)
746
        state_utils.set_can_continue(vars, common_constants.CAN_CONTINUE_PROMPT)
747

748
        return " ".join([ack, prompt])
749
    except Exception as exc:
750
        logger.exception(exc)
751
        sentry_sdk.capture_exception(exc)
752
        return error_response(vars)
753

754

755
# endregion
756

757
# region LOOP #2: AGREES_ABT_PERSON
758

759
# STEP 1
760
################################################################################
761

762

763
def sys_agrees_abt_person_request(ngrams, vars):
764
    flag = False
765

766
    human_utterance = state_utils.get_last_human_utterance(vars)
767

768
    sf_type, sf_confidence = utils.get_speech_function_for_human_utterance(human_utterance)
769
    logger.debug(f"sys_agrees_abt_person_request: Speech Function: {sf_type}")
770

771
    # using speech function classifier for agree (yes)
772
    # (with the aid of MIDAS & Intents for now)
773
    flag = utils.is_speech_function_agree(vars)
774
    flag = flag and default_condition_request(ngrams, vars)
775

776
    logger.info(f"sys_agrees_abt_person_request={flag}")
777
    return flag
778

779

780
patterns_creative_topics = ["Entertainment_Movies", "Entertainment_Books", "Entertainment_Music"]
781
creative_topics_patterns_re = re.compile("(" + "|".join(patterns_creative_topics) + ")", re.IGNORECASE)
782

783

784
def replace_occupation(prompt, bot_judgement, current_person_occupation):
785
    if prompt:
786
        prompt = prompt.replace("target_judgement", bot_judgement)
787
        prompt = prompt.replace("target_occupation", current_person_occupation)
788
    return prompt
789

790

791
def replace_gender(prompt, gender):
792
    if prompt:
793
        is_gender = utils.get_human_readable_gender_statement_current_is(gender)
794
        eir_gender = utils.get_human_readable_gender_statement_current_eir(gender)
795
        im_gender = utils.get_human_readable_gender_statement_current_im(gender)
796
        prompt = prompt.replace("target_gender_is", is_gender)
797
        prompt = prompt.replace("target_gender_im", im_gender)
798
        prompt = prompt.replace("target_gender_eir", eir_gender)
799
    return prompt
800

801

802
def usr_agrees_abt_person_response(vars):
803
    logger.debug("exec usr_agrees_abt_person_response")
804
    try:
805
        shared_memory = state_utils.get_shared_memory(vars)
806

807
        # obtaining current person's context
808

809
        current_cobot_topic = shared_memory.get("current_cobot_topic", "")
810
        # TODO
811
        human_topic = this_news.COBOT_TO_HUMAN_READABLE_TOPICS.get(current_cobot_topic)
812

813
        current_person = shared_memory.get("current_person", "")
814
        current_person_occupation = shared_memory.get("current_person_occupation", "")
815
        if len(current_person_occupation) == 0:
816
            current_person_occupation = utils.get_basic_occupation_for_topic(current_cobot_topic)
817
            # current_person_occupation = utils.get_occupation_for_person(current_person,
818
            # current_cobot_topic, "I would love to learn more about " + current_person
819
            # + " in " + human_topic)
820

821
        # we need to remember that user agreed with us. Now, the question is, what our emotion was?
822
        bot_emotion_towards_current_person = shared_memory.get("bot_emotion_towards_current_person", "Liked")
823
        # obtaining judgement
824
        bot_judgement = get_random_judgement_for_emotion(bot_emotion_towards_current_person)
825

826
        # obtaining supporting info like gender & age
827
        fake_utterance = f"I like to learn more about {current_person_occupation} {current_person} {human_topic}"
828
        gender, age = utils.get_gender_age_person(current_person, fake_utterance)
829

830
        # obtaining forms
831
        hr_gender = utils.get_human_readable_gender_statement_current_is(gender)
832

833
        # generating generic response
834
        body = "So stick with it!"  # YOUR CODE HERE
835

836
        prompt = ""
837
        # TODO : oh my god
838
        notable_work = ""
839

840
        #
841
        logger.debug(f"current cobot topic: {current_cobot_topic}")
842

843
        # we need to generate some opinion based on one of the person's aspects
844
        # ASPECT #1: AGE
845
        age = age[0] if isinstance(age, list) and age else age
846
        try:
847
            age = int(age)
848
        except Exception as exc:
849
            logger.warn(f"Can not cast age: {exc}")
850
            age = 0
851
        if age != 0:
852
            if age < 25:
853
                # mentioning age
854
                body = f"Wow {hr_gender} so young! "
855
                prompt = random.choice(this_gossip.REACTION_TO_YOUNG_AGE[bot_emotion_towards_current_person])
856
                prompt = replace_occupation(prompt, bot_judgement, current_person_occupation)
857
                prompt = replace_gender(prompt, gender)
858

859
        # ASPECT #2: PERSONAL RELATIONSHIPS (SPOUSE/PARTNER)
860
        if not prompt:
861
            spouse, partner = utils.get_spouse_or_partner_person(current_person, fake_utterance)
862
            if spouse is not None and not spouse and partner:
863
                body = ""
864
                prompt = random.choice(this_gossip.ASK_ABOUT_DATING)
865
                prompt = replace_gender(prompt, gender)
866

867
                prompt = prompt.replace("target_partner", partner)
868

869
        # ASPECT #3: CREATIVE WORKS
870
        if not prompt:
871
            is_creative_person = bool(re.search(creative_topics_patterns_re, current_cobot_topic))
872
            # obtaining
873
            if is_creative_person:
874
                item_kind = "notable work"
875

876
                films, songs, albums, notable_works = utils.get_notable_works_for_creative_person(
877
                    current_person, fake_utterance
878
                )
879

880
                if "Entertainment_Movies" in current_cobot_topic:
881
                    logger.debug(f"movies: {films}")
882
                    if films and films[0]:
883
                        film = random.choice(films[0])[1]
884
                        logger.debug(f"target film: {film}")
885
                        notable_work = film if film and film[0] else notable_work
886
                    item_kind = "movie"
887
                elif "Entertainment_Music" in current_cobot_topic:
888
                    logger.debug(f"albums: {albums}")
889
                    if albums and albums[0]:
890
                        album = random.choice(albums[0])[1]
891
                        logger.debug(f"target album: {album}")
892
                        if len(album) > 0:
893
                            notable_work = album
894
                    item_kind = "album"
895
                elif "Entertainment_Books" in current_cobot_topic:
896
                    logger.debug(f"notable works: {notable_works}")
897
                    if notable_works and notable_works[0]:
898
                        book = random.choice(notable_works[0])[1]
899
                        logger.debug(f"target book: {book}")
900
                        if len(book) > 0:
901
                            notable_work = book
902

903
                    item_kind = "book"
904

905
                logger.debug(f"notable_work: {notable_work}")
906

907
                # TODO : oh my god
908
                if notable_work:
909
                    # body = "So... "
910
                    body = ""
911
                    prompt = random.choice(this_gossip.REACTION_TO_CREATIVE_WORK[bot_emotion_towards_current_person])
912
                    prompt = prompt.replace("target_creative_work", item_kind)
913
                    prompt = prompt.replace("target_work_name", notable_work)
914

915
                    prompt = replace_gender(prompt, gender)
916
                    prompt = replace_occupation(prompt, bot_judgement, current_person_occupation)
917
                # if user is creative but has no known works we skip `em`
918

919
                # if:
920
                #     # body = "So... "
921
                #     body = ""
922
                #     prompt = random.choice(
923
                # this_gossip.GENERIC_REACTION_TO_CREATIVE_WORK[bot_emotion_towards_current_person]
924
                # )
925
                #     prompt = prompt.replace("target_creative_work", item_kind)
926

927
        # ASPECT #4: SPORTSPEOPLE
928
        if not prompt:
929
            if "Sports" in current_cobot_topic:
930
                item_kind = "team"
931
                sports_kind = "sports"
932
                # TODO : oh my god
933
                team_name = "[[]]"
934
                sport, teams = utils.get_teams_for_sportsperson(current_person, fake_utterance)
935

936
                sports_kind = sport[0][1]
937

938
                logger.debug(f"teams: {teams}")
939
                if len(teams) > 0:
940
                    random_team = random.choice(teams)
941
                    logger.debug(f"target team: {random_team}")
942
                    if len(random_team) > 0:
943
                        team_name = random_team[1]
944

945
                logger.debug(f"team name: {team_name}")
946

947
                # TODO : oh my god
948
                if "[[]]" not in str(team_name):
949
                    # body = "So... "
950
                    body = ""
951
                    prompt = random.choice(this_gossip.REACTION_TO_SPORT[bot_emotion_towards_current_person])
952
                    prompt = prompt.replace("target_sport_name", sports_kind)
953
                    prompt = prompt.replace("target_sport_team", team_name)
954

955
                    prompt = replace_gender(prompt, gender)
956
                    prompt = replace_occupation(prompt, bot_judgement, current_person_occupation)
957

958
                # TODO : oh my god
959
                if "[[]]" in str(team_name):
960
                    # body = "So... "
961
                    body = ""
962
                    prompt = random.choice(this_gossip.GENERIC_REACTION_TO_SPORT[bot_emotion_towards_current_person])
963
                    prompt = prompt.replace("target_sport_name", sports_kind)
964

965
                    prompt = replace_gender(prompt, gender)
966
                    prompt = replace_occupation(prompt, bot_judgement, current_person_occupation)
967
        # ASPECT 5. CELEBRITY
968
        if not prompt:
969
            body = ""
970
            prompt = get_celebrity_prompt(vars, current_person)
971
            logger.info(f"usr_agrees_abt_person_response: CELEBRITY, suggested prompt: {prompt}")
972
            if not prompt:
973
                prompt = ""
974
            else:
975
                im_gender = utils.get_human_readable_gender_statement_current_im(gender)
976
                # eir_gender = utils.get_human_readable_gender_statement_current_eir(gender)
977
                prompt = prompt.replace("this person", im_gender)
978
                prompt = prompt.replace("target_gender_im", im_gender)
979

980
        elif prompt:  # put memory to zero
981
            # Not talking about celebrity - saving
982
            logger.debug("Not in celebrity branch")
983
            state_utils.save_to_shared_memory(vars, celebrity_prompt=False)
984

985
        if prompt:
986
            state_utils.set_confidence(vars, MUST_CONTINUE_CONFIDENCE)
987
            state_utils.set_can_continue(vars, common_constants.CAN_CONTINUE_PROMPT)
988
        else:
989
            state_utils.set_confidence(vars, CANNOT_CONTINUE_CONFIDENCE)
990
            state_utils.set_can_continue(vars, common_constants.CAN_NOT_CONTINUE)
991

992
        return " ".join([body, prompt])
993
    except Exception as exc:
994
        logger.exception(exc)
995
        sentry_sdk.capture_exception(exc)
996
        return error_response(vars)
997

998

999
# # STEP 2
1000
# ################################################################################
1001

1002

1003
# def sys_person_agree_request(ngrams, vars):
1004
#     flag = False
1005
#     raise NotImplementedError()  # YOUR CODE HERE
1006
#     info.info(f"weekend_request={flag}")
1007
#     return flag
1008

1009

1010
# def usr_person_agree_response(vars):
1011
#     logger.debug("exec usr_person_agree_response")
1012
#     try:
1013
#         state_utils.set_confidence(vars, MUST_CONTINUE_CONFIDENCE)
1014
#         state_utils.set_can_continue(vars)
1015
#         response_text = ""  # YOUR CODE HERE
1016
#         raise NotImplementedError()  # YOUR CODE HERE
1017
#         return response_text
1018
#     except Exception as exc:
1019
#         logger.exception(exc)
1020
#         sentry_sdk.capture_exception(exc)
1021
#         return error_response(vars)
1022

1023

1024
# # STEP 3
1025
# ################################################################################
1026

1027

1028
# def sys_says_something_after_agree_request(ngrams, vars):
1029
#     flag = False
1030
#     raise NotImplementedError()  # YOUR CODE HERE
1031
#     info.info(f"weekend_request={flag}")
1032
#     return flag
1033

1034

1035
# def usr_says_something_after_agree_response(vars):
1036
#     logger.debug("exec usr_says_something_after_agree_response")
1037
#     try:
1038
#         state_utils.set_confidence(vars, MUST_CONTINUE_CONFIDENCE)
1039
#         state_utils.set_can_continue(vars)
1040
#         response_text = ""  # YOUR CODE HERE
1041
#         raise NotImplementedError()  # YOUR CODE HERE
1042
#         return response_text
1043
#     except Exception as exc:
1044
#         logger.exception(exc)
1045
#         sentry_sdk.capture_exception(exc)
1046
#         return error_response(vars)
1047

1048

1049
# endregion
1050

1051
# region LOOP #3: DISAGREES_ABT_PERSON
1052

1053
# STEP 1
1054
################################################################################
1055

1056

1057
def sys_disagrees_abt_person_request(ngrams, vars):
1058
    flag = False
1059
    human_utterance = state_utils.get_last_human_utterance(vars)
1060

1061
    sf_type, sf_confidence = utils.get_speech_function_for_human_utterance(human_utterance)
1062
    logger.debug(f"sys_disagrees_abt_person: Speech Function: {sf_type}")
1063

1064
    # using speech function classifier for disagree (no)
1065
    # (with the aid of MIDAS & Intents for now)
1066
    flag = utils.is_speech_function_disagree(vars)
1067

1068
    logger.info(f"sys_disagrees_abt_person={flag}")
1069
    return flag
1070

1071

1072
def usr_disagrees_abt_person_response(vars):
1073
    logger.debug("exec usr_disagrees_abt_person_response")
1074
    try:
1075
        state_utils.set_confidence(vars, MUST_CONTINUE_CONFIDENCE)
1076
        state_utils.set_can_continue(vars, common_constants.CAN_NOT_CONTINUE)
1077
        # Wait but why... But a little bit smarter this time around
1078
        # response_text = utils.get_not_used_and_save_wait_but_why_question(vars)
1079
        response_text = "OK. I got it."
1080
        return response_text
1081
    except Exception as exc:
1082
        logger.exception(exc)
1083
        sentry_sdk.capture_exception(exc)
1084
        return error_response(vars)
1085

1086

1087
# # STEP 2
1088
# ################################################################################
1089

1090

1091
# def sys_person_disagree_request(ngrams, vars):
1092
#     flag = False
1093
#     raise NotImplementedError()  # YOUR CODE HERE
1094
#     info.info(f"weekend_request={flag}")
1095
#     return flag
1096

1097

1098
# def usr_person_disagree_response(vars):
1099
#     logger.debug("exec usr_person_disagree_response")
1100
#     try:
1101
#         state_utils.set_confidence(vars, MUST_CONTINUE_CONFIDENCE)
1102
#         state_utils.set_can_continue(vars)
1103
#         response_text = ""  # YOUR CODE HERE
1104
#         raise NotImplementedError()  # YOUR CODE HERE
1105
#         return response_text
1106
#     except Exception as exc:
1107
#         logger.exception(exc)
1108
#         sentry_sdk.capture_exception(exc)
1109
#         return error_response(vars)
1110

1111

1112
# # STEP 3
1113
# ################################################################################
1114

1115

1116
# def sys_says_something_after_disagree_request(ngrams, vars):
1117
#     flag = False
1118
#     raise NotImplementedError()  # YOUR CODE HERE
1119
#     info.info(f"weekend_request={flag}")
1120
#     return flag
1121

1122

1123
# def usr_says_something_after_disagree_response(vars):
1124
#     logger.debug("exec usr_says_something_after_disagree_response")
1125
#     try:
1126
#         state_utils.set_confidence(vars, MUST_CONTINUE_CONFIDENCE)
1127
#         state_utils.set_can_continue(vars)
1128
#         response_text = ""  # YOUR CODE HERE
1129
#         raise NotImplementedError()  # YOUR CODE HERE
1130
#         return response_text
1131
#     except Exception as exc:
1132
#         logger.exception(exc)
1133
#         sentry_sdk.capture_exception(exc)
1134
#         return error_response(vars)
1135

1136

1137
# endregion
1138

1139
# region LOOP #4: SAYS_OPINION_ABT_PERSON
1140

1141
# STEP 1
1142
################################################################################
1143

1144

1145
def sys_says_opinion_abt_person_request(ngrams, vars):
1146
    flag = False
1147
    human_utterance = state_utils.get_last_human_utterance(vars)
1148

1149
    sf_type, sf_confidence = utils.get_speech_function_for_human_utterance(human_utterance)
1150
    logger.debug(f"sys_says_opinion_abt_person_request: Speech Function: {sf_type}")
1151

1152
    # using speech function classifier for express_opinion
1153
    # (with the aid of MIDAS & Intents for now)
1154
    flag = utils.is_speech_function_express_opinion(vars)
1155
    logger.info(f"sys_says_opinion_abt_person_request={flag}")
1156
    return flag
1157

1158

1159
def usr_says_opinion_abt_person_response(vars):
1160
    logger.debug("exec usr_says_opinion_abt_person_response")
1161
    try:
1162
        shared_memory = state_utils.get_shared_memory(vars)
1163

1164
        # while we understand this is an opinion we don't know what it actually is
1165
        # so we use sentiment analysis as a shortcut
1166
        sentiment = state_utils.get_human_sentiment(vars, negative_threshold=0.75)
1167

1168
        current_person = shared_memory.get("current_person", "")
1169

1170
        # generating sentiment-based response
1171

1172
        sentiment = state_utils.get_human_sentiment(vars, negative_threshold=0.75)
1173
        judgement = "Other"
1174
        if "negative" in sentiment:
1175
            judgement = "Disliked"
1176
        elif "positive" in sentiment:
1177
            judgement = "Liked"
1178
        elif "neutral" in sentiment:
1179
            judgement = "Other"
1180

1181
        save_mentioned_person(vars, current_person, judgement, "people_mentioned_by_user")
1182

1183
        prompt = random.choice(this_gossip.REACTION_TO_USER_OPINION_ABOUT_PERSON[judgement])
1184

1185
        state_utils.set_confidence(vars, MUST_CONTINUE_CONFIDENCE)
1186
        state_utils.set_can_continue(vars, common_constants.CAN_CONTINUE_SCENARIO)
1187

1188
        return prompt
1189
    except Exception as exc:
1190
        logger.exception(exc)
1191
        sentry_sdk.capture_exception(exc)
1192
        return error_response(vars)
1193

1194

1195
# # STEP 2
1196
# ################################################################################
1197

1198

1199
# def sys_person_opinion_request(ngrams, vars):
1200
#     flag = False
1201
#     raise NotImplementedError()  # YOUR CODE HERE
1202
#     info.info(f"weekend_request={flag}")
1203
#     return flag
1204

1205

1206
# def usr_person_opinion_response(vars):
1207
#     logger.debug("exec usr_person_opinion_response")
1208
#     try:
1209
#         state_utils.set_confidence(vars, MUST_CONTINUE_CONFIDENCE)
1210
#         state_utils.set_can_continue(vars)
1211
#         response_text = ""  # YOUR CODE HERE
1212
#         raise NotImplementedError()  # YOUR CODE HERE
1213
#         return response_text
1214
#     except Exception as exc:
1215
#         logger.exception(exc)
1216
#         sentry_sdk.capture_exception(exc)
1217
#         return error_response(vars)
1218

1219

1220
# # STEP 3
1221
# ################################################################################
1222

1223

1224
# def sys_says_something_after_opinion_request(ngrams, vars):
1225
#     flag = False
1226
#     raise NotImplementedError()  # YOUR CODE HERE
1227
#     info.info(f"weekend_request={flag}")
1228
#     return flag
1229

1230

1231
# def usr_says_something_after_opinion_response(vars):
1232
#     logger.debug("exec usr_says_something_after_opinion_response")
1233
#     try:
1234
#         state_utils.set_confidence(vars, MUST_CONTINUE_CONFIDENCE)
1235
#         state_utils.set_can_continue(vars)
1236
#         response_text = ""  # YOUR CODE HERE
1237
#         raise NotImplementedError()  # YOUR CODE HERE
1238
#         return response_text
1239
#     except Exception as exc:
1240
#         logger.exception(exc)
1241
#         sentry_sdk.capture_exception(exc)
1242
#         return error_response(vars)
1243

1244

1245
# endregion
1246

1247
# # region SYS_CHANGE_TO_PERSON
1248
# ################################################################################
1249

1250

1251
# def sys_change_to_person_request(ngrams, vars):
1252
#     flag = True
1253
#     # raise NotImplementedError()  # YOUR CODE HERE
1254
#     info.info(f"sys_change_to_person_request={flag}")
1255
#     return flag
1256

1257

1258
def usr_change_to_person_response(vars):
1259
    logger.debug("exec usr_not_interested_in_person_response")
1260
    try:
1261
        shared_memory = state_utils.get_shared_memory(vars)
1262
        # obtaining current context
1263
        current_cobot_topic = shared_memory.get("current_cobot_topic", "")
1264
        # getting human-readable version
1265
        human_topic = this_news.COBOT_TO_HUMAN_READABLE_TOPICS.get(current_cobot_topic)
1266

1267
        # obtaining new random person + news for current cobot_topic
1268
        person = get_fresh_person_for_topic(vars, current_cobot_topic)
1269

1270
        # Positive
1271
        target_emotion_type = "Liked"
1272
        target_judgement = get_random_judgement_for_emotion(target_emotion_type)
1273

1274
        # saving current bot's emotion towards the currently discussed person
1275
        state_utils.save_to_shared_memory(vars, bot_emotion_towards_current_person=target_emotion_type)
1276

1277
        # saving person to the list of people mentioned by bot, for now with "Other" judgement
1278
        save_mentioned_person(vars, person, "Liked", "people_mentioned_by_bot")
1279
        # setting current context (only person, we didn't change topic)
1280
        state_utils.save_to_shared_memory(vars, current_person=person)
1281

1282
        # generating response
1283
        ack = condition_utils.get_not_used_and_save_sentiment_acknowledgement(vars)
1284

1285
        prompt = random.choice(this_gossip.CHANGE_TO_OTHER_PERSON_QUESTIONS)
1286

1287
        prompt = prompt.replace("target_person", person) if person else prompt
1288
        prompt = prompt.replace("target_topic", human_topic) if human_topic else prompt
1289
        prompt = prompt.replace("target_judgement", target_judgement)
1290

1291
        # occupation
1292
        occupation = utils.get_occupation_for_person(person, current_cobot_topic, prompt)
1293

1294
        prompt = prompt.replace("target_occupation", occupation)
1295

1296
        state_utils.set_confidence(vars, MUST_CONTINUE_CONFIDENCE)
1297
        state_utils.set_can_continue(vars, common_constants.CAN_CONTINUE_PROMPT)
1298
        return " ".join([ack, prompt])
1299
    except Exception as exc:
1300
        logger.exception(exc)
1301
        sentry_sdk.capture_exception(exc)
1302
        return error_response(vars)
1303

1304

1305
# STEP 2 MENTIONS_ANOTHER_PERSON
1306
################################################################################
1307

1308

1309
def sys_mentions_another_person_request(ngrams, vars):
1310
    flag = False
1311

1312
    use_only_last_utt = True
1313
    mentioned_by_user_people = []
1314
    found_celebrity, _ = get_celebrity_from_uttr(vars, use_only_last_utt=use_only_last_utt)
1315

1316
    if found_celebrity:
1317
        mentioned_by_user_people.append(found_celebrity)
1318

1319
    logger.info(f"sys_mentions_another_person_request: {mentioned_by_user_people}")
1320

1321
    shared_memory = state_utils.get_shared_memory(vars)
1322
    current_person = shared_memory.get("current_person", "")
1323
    current_person = str(current_person)
1324

1325
    logger.debug(f"mentioned_people: {mentioned_by_user_people}")
1326
    other_mentioned_people = [
1327
        people for people in mentioned_by_user_people if str(people).lower() != current_person.lower()
1328
    ]
1329

1330
    # checking if user mentioned at least one person
1331
    if len(other_mentioned_people) > 0:
1332
        flag = True
1333

1334
    logger.info(f"sys_mentions_another_person_request={flag}")
1335
    return flag
1336

1337

1338
def usr_mentions_another_person_response(vars):
1339
    logger.debug("exec usr_mentions_another_person_response")
1340
    try:
1341
        shared_memory = state_utils.get_shared_memory(vars)
1342

1343
        # sf_type, sf_confidence = utils.get_speech_function_for_human_utterance(human_utterance)
1344
        # logger.debug(f"usr_mentions_another_person_response: Speech Function: {sf_type}")
1345

1346
        # using speech function classifier for express_opinion
1347
        # (with the aid of MIDAS & Intents for now)
1348

1349
        use_only_last_utt = True
1350
        found_celebrity, occupation = get_celebrity_from_uttr(vars, use_only_last_utt=use_only_last_utt)
1351

1352
        # obtaining occupation (person/generic/wiki-based)
1353
        # occupation = utils.get_occupation_for_person(current_person, current_cobot_topic, body)
1354

1355
        logger.info(f"found occupation: {occupation}")
1356

1357
        # saving it
1358
        state_utils.save_to_shared_memory(vars, current_person_occupation=occupation)
1359

1360
        if found_celebrity:
1361
            logger.info(f"user just mentioned these people: {found_celebrity}")
1362

1363
        # obtaining previously mentioned people
1364
        # user_mentioned_people = get_mentioned_people(vars, share_memory_key="people_mentioned_by_user")
1365

1366
        # checking current person
1367
        current_person = shared_memory.get("current_person", "")
1368

1369
        body = random.choice(this_gossip.CONFUSED_WHY_USER_MENTIONED_PEOPLE)
1370
        state_utils.set_confidence(vars, DIALOG_BEGINNING_CONTINUE_CONFIDENCE)
1371
        state_utils.set_can_continue(vars, common_constants.CAN_CONTINUE_PROMPT)
1372
        # checking if user mentioned at least one person
1373
        if found_celebrity:
1374
            state_utils.set_confidence(vars, MUST_CONTINUE_CONFIDENCE)
1375
            state_utils.set_can_continue(vars, common_constants.CAN_CONTINUE_PROMPT)
1376
            user_mentioned_person = found_celebrity
1377
            logger.info("# of mentioned people: 1")
1378
            # path #1: mentioned person is the current one (w/o coref)
1379
            if str(user_mentioned_person).lower() in str(current_person).lower():
1380
                logger.info(f"just mentioned person {user_mentioned_person} is the current_one: {current_person}")
1381
                if utils.is_speech_function_demand_opinion(vars):
1382
                    if current_person in get_mentioned_people(vars, "people_mentioned_by_bot", ["Liked"]):
1383
                        body = random.choice(this_gossip.SIMPLE_OPINION_ABOUT_LIKED_PERSON_PREVIOUSLY_MENTIONED_BY_BOT)
1384
                        fake_utterance = f"I like to learn more about {user_mentioned_person}"
1385
                        gender, age = utils.get_gender_age_person(user_mentioned_person, fake_utterance)
1386
                        gender_is = utils.get_human_readable_gender_statement_current_is(gender)
1387
                        body = body.replace("target_gender_is", gender_is)
1388
                    elif current_person in get_mentioned_people(vars, "people_mentioned_by_bot", ["Disliked"]):
1389
                        body = random.choice(
1390
                            this_gossip.SIMPLE_OPINION_ABOUT_DISLIKED_PERSON_PREVIOUSLY_MENTIONED_BY_BOT
1391
                        )
1392
                        fake_utterance = f"I like to learn more about {user_mentioned_person}"
1393
                        gender, age = utils.get_gender_age_person(user_mentioned_person, fake_utterance)
1394
                        gender_is = utils.get_human_readable_gender_statement_current_is(gender)
1395
                        body = body.replace("target_gender_is", gender_is)
1396
                if utils.is_speech_function_express_opinion(vars):
1397
                    body = random.choice(this_gossip.SIMPLE_REACTION_TO_PERSON_PREVIOUSLY_MENTIONED_BY_BOT)
1398
            # path #2: mentioned person is the one mentioned by bot before
1399
            elif user_mentioned_person in get_mentioned_people(vars, share_memory_key="people_mentioned_by_bot"):
1400
                if utils.is_speech_function_demand_opinion(vars):
1401
                    if user_mentioned_person in get_mentioned_people(vars, "people_mentioned_by_bot", ["Liked"]):
1402
                        body = random.choice(this_gossip.SIMPLE_OPINION_ABOUT_LIKED_PERSON_PREVIOUSLY_MENTIONED_BY_BOT)
1403
                        fake_utterance = f"I like to learn more about {user_mentioned_person}"
1404
                        gender, age = utils.get_gender_age_person(user_mentioned_person, fake_utterance)
1405
                        gender_is = utils.get_human_readable_gender_statement_current_is(gender)
1406
                        body = body.replace("target_gender_is", gender_is)
1407
                    elif user_mentioned_person in get_mentioned_people(vars, "people_mentioned_by_bot", ["Disliked"]):
1408
                        body = random.choice(
1409
                            this_gossip.SIMPLE_OPINION_ABOUT_DISLIKED_PERSON_PREVIOUSLY_MENTIONED_BY_BOT
1410
                        )
1411
                        fake_utterance = f"I like to learn more about {user_mentioned_person}"
1412
                        gender, age = utils.get_gender_age_person(user_mentioned_person, fake_utterance)
1413
                        gender_is = utils.get_human_readable_gender_statement_current_is(gender)
1414
                        body = body.replace("target_gender_is", gender_is)
1415
                if utils.is_speech_function_express_opinion(vars):
1416
                    body = random.choice(this_gossip.SIMPLE_REACTION_TO_PERSON_PREVIOUSLY_MENTIONED_BY_BOT)
1417
            # path #3: mentioned person is the one mentioned by user before
1418
            elif user_mentioned_person in get_mentioned_people(vars, "people_mentioned_by_user"):
1419
                if utils.is_speech_function_demand_opinion(vars):
1420
                    body = random.choice(this_gossip.SIMPLE_OPINION_ABOUT_PERSON_PREVIOUSLY_MENTIONED_BY_USER)
1421
                if utils.is_speech_function_express_opinion(vars):
1422
                    body = random.choice(this_gossip.SIMPLE_REACTION_TO_PERSON_PREVIOUSLY_MENTIONED_BY_USER)
1423
            # path #4: mentioned person is the new one
1424
            else:
1425
                bot_mentioned_people_related_to_new_ones = get_people_related_to_bot_mentioned_ones(
1426
                    vars, user_mentioned_person
1427
                )
1428
                user_mentioned_people_related_to_new_ones = get_people_related_to_user_mentioned_ones(
1429
                    vars, user_mentioned_person
1430
                )
1431
                # bot mentioned at least one of the people who are related to one user just mentioned
1432
                if len(bot_mentioned_people_related_to_new_ones):
1433
                    if utils.is_speech_function_demand_opinion(vars):
1434
                        body = random.choice(
1435
                            this_gossip.OPINION_TO_USER_MENTIONING_SOMEONE_RELATED_TO_WHO_BOT_MENTIONED_BEFORE
1436
                        )
1437
                    if utils.is_speech_function_express_opinion(vars):
1438
                        body = random.choice(
1439
                            this_gossip.REACTION_TO_USER_MENTIONING_SOMEONE_RELATED_TO_WHO_BOT_MENTIONED_BEFORE
1440
                        )
1441
                # user mentioned at least one of the people who are related to one user just mentioned
1442
                elif len(user_mentioned_people_related_to_new_ones):
1443
                    if utils.is_speech_function_demand_opinion(vars):
1444
                        body = random.choice(
1445
                            this_gossip.OPINION_TO_USER_MENTIONING_SOMEONE_RELATION_TO_WHO_USER_MENTIONED_BEFORE
1446
                        )
1447
                    if utils.is_speech_function_express_opinion(vars):
1448
                        body = random.choice(
1449
                            this_gossip.REACTION_TO_USER_MENTIONING_SOMEONE_RELATED_TO_WHO_USER_MENTIONED_BEFORE
1450
                        )
1451
                # we should also think about the same occupation BTW!
1452
                # TO DO
1453

1454
                # generic case, just a new person
1455
                else:
1456
                    # being smarter about using templates
1457
                    body = utils.get_not_used_and_save_reaction_to_new_mentioned_person(vars)
1458
                    fake_utterance = f"I like to learn more about {user_mentioned_person}"
1459
                    gender, age = utils.get_gender_age_person(user_mentioned_person, fake_utterance)
1460
                    # gender_is = utils.get_human_readable_gender_statement_current_is(gender)
1461
                    body = body.replace("target_gender_is", user_mentioned_person + " is ")
1462

1463
                    # saving person to the list of people mentioned by bot, for now with "Like" judgement
1464
                    save_mentioned_person(vars, current_person, "Liked", "people_mentioned_by_bot")
1465

1466
                    # Positive
1467
                    target_emotion_type = "Liked"
1468
                    # target_judgement = get_random_judgement_for_emotion(target_emotion_type)
1469

1470
                    # saving current bot's emotion towards the currently discussed person
1471
                    state_utils.save_to_shared_memory(vars, bot_emotion_towards_current_person=target_emotion_type)
1472

1473
            # no matter what we want to save the fact that user mentioned this particular person
1474
            sentiment = state_utils.get_human_sentiment(vars, negative_threshold=0.75)
1475
            judgement = "Other"
1476
            if "negative" in sentiment:
1477
                judgement = "Disliked"
1478
            elif "positive" in sentiment:
1479
                judgement = "Liked"
1480
            elif "neutral" in sentiment:
1481
                judgement = "Liked"  # temporary override until we'll get templates for neutral
1482

1483
            save_mentioned_person(vars, user_mentioned_person, judgement, "people_mentioned_by_user")
1484

1485
            # saving current user's emotion towards the currently discussed person
1486
            state_utils.save_to_shared_memory(vars, bot_emotion_towards_current_person=judgement)
1487

1488
            current_person = user_mentioned_person
1489
            # obtaining topic using reverse lookup from occupations
1490
            current_topic = utils.get_cobot_topic_for_occupation(occupation)
1491

1492
            # changing current person and current topic
1493
            state_utils.save_to_shared_memory(vars, current_person=current_person)
1494
            logger.info(f"sys_mentioned_another_person: setting current_person to {current_person}")
1495
            state_utils.save_to_shared_memory(vars, current_cobot_topic=current_topic)
1496
            logger.info(f"sys_mentioned_another_person: setting current_topic to {current_topic}")
1497
            state_utils.save_to_shared_memory(vars, current_person_occupation=occupation)
1498
            logger.info(f"sys_mentioned_another_person: setting current_person_ocupation to {occupation}")
1499

1500
        else:
1501
            logger.info("# of mentioned people: few")
1502
            # finally we are lazy and if we hear more than one person we ask to talk about just one person
1503
            body = random.choice(this_gossip.CONFUSED_WHY_USER_MENTIONED_PEOPLE)
1504

1505
        if body:
1506
            return body
1507
        else:
1508
            return error_response(vars)
1509
    except Exception as exc:
1510
        logger.exception(exc)
1511
        sentry_sdk.capture_exception(exc)
1512
        return error_response(vars)
1513

1514

1515
# endregion
1516

1517
##################################################################################################################
1518
#  START
1519

1520
simplified_dialogflow.add_user_serial_transitions(
1521
    State.USR_START,
1522
    {
1523
        State.SYS_TOPIC_TO_EVENT: sys_topic_to_event_request,
1524
        State.SYS_AGREES_ABT_PERSON: sys_celebrity_found_request,
1525
        # State.SYS_MENTIONS_ANOTHER_PERSON: sys_celebrity_found_request,
1526
        State.SYS_MENTIONS_ANOTHER_PERSON: sys_mentions_another_person_request,
1527
    },
1528
)
1529
simplified_dialogflow.set_error_successor(State.USR_START, State.SYS_ERR)
1530

1531
# -------------------------------------------------------------------------------
1532
# SYS_TOPIC_TO_EVENT
1533

1534
simplified_dialogflow.add_system_transition(
1535
    State.SYS_TOPIC_TO_EVENT, State.USR_TOPIC_TO_EVENT, usr_topic_to_event_response
1536
)
1537

1538
simplified_dialogflow.add_user_serial_transitions(
1539
    State.USR_TOPIC_TO_EVENT,
1540
    {
1541
        State.SYS_NO_OR_YES: sys_no_or_yes_request,
1542
        State.SYS_SAYS_OPINION_ABT_PERSON: sys_says_opinion_abt_person_request,
1543
        State.SYS_NOT_INTERESTED_IN_PERSON: sys_not_interested_in_person_request,
1544
        State.SYS_MENTIONS_ANOTHER_PERSON: sys_mentions_another_person_request,
1545
    },
1546
)
1547

1548
simplified_dialogflow.set_error_successor(State.USR_TOPIC_TO_EVENT, State.SYS_ERR)
1549

1550
# -------------------------------------------------------------------------------
1551
# SYS_NO_OR_YES TO SYS_EVENT_TO_PERSON
1552

1553
simplified_dialogflow.add_system_transition(
1554
    State.SYS_NO_OR_YES, State.USR_EVENT_TO_PERSON, usr_event_to_person_response
1555
)
1556

1557
simplified_dialogflow.add_user_serial_transitions(
1558
    State.USR_EVENT_TO_PERSON,
1559
    {
1560
        State.SYS_DISAGREES_ABT_PERSON: sys_disagrees_abt_person_request,
1561
        State.SYS_SAYS_OPINION_ABT_PERSON: sys_says_opinion_abt_person_request,
1562
        State.SYS_NOT_INTERESTED_IN_PERSON: sys_not_interested_in_person_request,
1563
        State.SYS_AGREES_ABT_PERSON: sys_agrees_abt_person_request,
1564
        State.SYS_MENTIONS_ANOTHER_PERSON: sys_mentions_another_person_request,
1565
    },
1566
)
1567

1568
simplified_dialogflow.set_error_successor(State.USR_EVENT_TO_PERSON, State.SYS_ERR)
1569

1570
# region LOOP #1: NOT_INTERESTED_IN_PERSON
1571

1572
# -------------------------------------------------------------------------------
1573
# SYS_NOT_INTERESTED_IN_PERSON
1574

1575
simplified_dialogflow.add_system_transition(
1576
    State.SYS_NOT_INTERESTED_IN_PERSON, State.USR_NOT_INTERESTED_IN_PERSON, usr_not_interested_in_person_response
1577
)
1578

1579
simplified_dialogflow.set_error_successor(State.SYS_NOT_INTERESTED_IN_PERSON, State.SYS_ERR)
1580

1581
simplified_dialogflow.add_user_serial_transitions(
1582
    State.USR_NOT_INTERESTED_IN_PERSON,
1583
    {
1584
        State.SYS_DISAGREES_ABT_PERSON: sys_disagrees_abt_person_request,
1585
        State.SYS_SAYS_OPINION_ABT_PERSON: sys_says_opinion_abt_person_request,
1586
        State.SYS_NOT_INTERESTED_IN_PERSON: sys_not_interested_in_person_request,
1587
        State.SYS_AGREES_ABT_PERSON: sys_agrees_abt_person_request,
1588
        State.SYS_MENTIONS_ANOTHER_PERSON: sys_mentions_another_person_request,
1589
    },
1590
)
1591

1592
# simplified_dialogflow.add_user_transition(
1593
#     State.USR_NOT_INTERESTED_IN_PERSON,
1594
#     State.SYS_CHANGE_TO_PERSON,
1595
#     sys_change_to_person_request)
1596

1597
# workaround
1598
simplified_dialogflow.set_error_successor(State.USR_NOT_INTERESTED_IN_PERSON, State.SYS_CHANGE_TO_PERSON)
1599

1600
# endregion
1601

1602
# region LOOP #2: AGREES_ABT_PERSON
1603

1604
# -------------------------------------------------------------------------------
1605
# SYS_AGREES_ABT_PERSON
1606

1607
simplified_dialogflow.add_system_transition(
1608
    State.SYS_AGREES_ABT_PERSON, State.USR_AGREES_ABT_PERSON, usr_agrees_abt_person_response
1609
)
1610

1611
simplified_dialogflow.add_user_serial_transitions(
1612
    State.USR_AGREES_ABT_PERSON,
1613
    {
1614
        State.SYS_DISAGREES_ABT_PERSON: sys_disagrees_abt_person_request,
1615
        State.SYS_SAYS_OPINION_ABT_PERSON: sys_says_opinion_abt_person_request,
1616
        State.SYS_NOT_INTERESTED_IN_PERSON: sys_not_interested_in_person_request,
1617
        State.SYS_AGREES_ABT_PERSON: sys_agrees_abt_person_request,
1618
        State.SYS_MENTIONS_ANOTHER_PERSON: sys_mentions_another_person_request,
1619
    },
1620
)
1621

1622
# simplified_dialogflow.add_user_transition(
1623
#     State.USR_AGREES_ABT_PERSON,
1624
#     # State.SYS_PERSON_AGREE,
1625
#     # sys_person_agree_request)
1626
#     State.SYS_CHANGE_TO_PERSON,
1627
#     sys_change_to_person_request)
1628

1629
# workaround
1630
simplified_dialogflow.set_error_successor(State.USR_AGREES_ABT_PERSON, State.SYS_CHANGE_TO_PERSON)
1631

1632
# endregion
1633

1634
# region LOOP #3: DISAGREES_ABT_PERSON
1635

1636
# -------------------------------------------------------------------------------
1637
# SYS_DISAGREES_ABT_PERSON
1638

1639
simplified_dialogflow.add_system_transition(
1640
    State.SYS_DISAGREES_ABT_PERSON, State.USR_DISAGREES_ABT_PERSON, usr_disagrees_abt_person_response
1641
)
1642

1643
simplified_dialogflow.set_error_successor(State.SYS_DISAGREES_ABT_PERSON, State.SYS_ERR)
1644

1645
# simplified_dialogflow.add_user_serial_transitions(
1646
#    State.USR_DISAGREES_ABT_PERSON,
1647
#    {
1648
#        State.SYS_MENTIONS_ANOTHER_PERSON: sys_mentions_another_person_request,
1649
#        State.SYS_DISAGREES_ABT_PERSON: sys_disagrees_abt_person_request,
1650
#        State.SYS_SAYS_OPINION_ABT_PERSON: sys_says_opinion_abt_person_request,
1651
#        State.SYS_NOT_INTERESTED_IN_PERSON: sys_not_interested_in_person_request,
1652
#        State.SYS_AGREES_ABT_PERSON: sys_agrees_abt_person_request,
1653
#    },
1654
# )
1655

1656
# simplified_dialogflow.add_user_transition(
1657
#     State.USR_DISAGREES_ABT_PERSON,
1658
#     # State.SYS_PERSON_DISAGREE,
1659
#     # sys_person_disagree_request)
1660
#     State.SYS_CHANGE_TO_PERSON,
1661
#     sys_change_to_person_request)
1662

1663
# workaround
1664
simplified_dialogflow.set_error_successor(State.USR_DISAGREES_ABT_PERSON, State.SYS_CHANGE_TO_PERSON)
1665

1666
# endregion
1667

1668
# region LOOP #4: SAYS_OPINION_ABT_PERSON
1669

1670
# -------------------------------------------------------------------------------
1671
# SYS_SAYS_OPINION_ABT_USER
1672

1673
simplified_dialogflow.add_system_transition(
1674
    State.SYS_SAYS_OPINION_ABT_PERSON, State.USR_SAYS_OPINION_ABT_PERSON, usr_says_opinion_abt_person_response
1675
)
1676

1677
simplified_dialogflow.add_user_serial_transitions(
1678
    State.USR_SAYS_OPINION_ABT_PERSON,
1679
    {
1680
        State.SYS_DISAGREES_ABT_PERSON: sys_disagrees_abt_person_request,
1681
        # State.SYS_SAYS_OPINION_ABT_PERSON: sys_says_opinion_abt_person_request,
1682
        State.SYS_NOT_INTERESTED_IN_PERSON: sys_not_interested_in_person_request,
1683
        State.SYS_AGREES_ABT_PERSON: sys_agrees_abt_person_request,
1684
        State.SYS_MENTIONS_ANOTHER_PERSON: sys_mentions_another_person_request,
1685
    },
1686
)
1687

1688
# simplified_dialogflow.add_user_transition(
1689
#     State.USR_SAYS_OPINION_ABT_PERSON,
1690
#     # State.SYS_PERSON_OPINION,
1691
#     State.SYS_CHANGE_TO_PERSON,SYS_DISAGREES_ABT_PERSON
1692
#     sys_change_to_person_request)
1693

1694
# workaround
1695
simplified_dialogflow.set_error_successor(State.USR_SAYS_OPINION_ABT_PERSON, State.SYS_CHANGE_TO_PERSON)
1696

1697
# endregion
1698

1699

1700
# -------------------------------------------------------------------------------
1701
# SYS_CHANGE_TO_PERSON
1702

1703
simplified_dialogflow.add_system_transition(
1704
    State.SYS_CHANGE_TO_PERSON, State.USR_CHANGE_TO_PERSON, usr_change_to_person_response
1705
)
1706

1707
simplified_dialogflow.add_user_serial_transitions(
1708
    State.USR_CHANGE_TO_PERSON,
1709
    {
1710
        State.SYS_DISAGREES_ABT_PERSON: sys_disagrees_abt_person_request,
1711
        State.SYS_SAYS_OPINION_ABT_PERSON: sys_says_opinion_abt_person_request,
1712
        State.SYS_NOT_INTERESTED_IN_PERSON: sys_not_interested_in_person_request,
1713
        State.SYS_AGREES_ABT_PERSON: sys_agrees_abt_person_request,
1714
        State.SYS_MENTIONS_ANOTHER_PERSON: sys_mentions_another_person_request,
1715
    },
1716
)
1717

1718

1719
# -------------------------------------------------------------------------------
1720
# SYS_MENTIONS_ANOTHER_PERSON
1721

1722
simplified_dialogflow.add_system_transition(
1723
    State.SYS_MENTIONS_ANOTHER_PERSON, State.USR_MENTIONS_ANOTHER_PERSON, usr_mentions_another_person_response
1724
)
1725

1726
simplified_dialogflow.add_user_serial_transitions(
1727
    State.USR_MENTIONS_ANOTHER_PERSON,
1728
    {
1729
        State.SYS_DISAGREES_ABT_PERSON: sys_disagrees_abt_person_request,
1730
        State.SYS_SAYS_OPINION_ABT_PERSON: sys_says_opinion_abt_person_request,
1731
        State.SYS_NOT_INTERESTED_IN_PERSON: sys_not_interested_in_person_request,
1732
        State.SYS_AGREES_ABT_PERSON: sys_agrees_abt_person_request,
1733
        State.SYS_MENTIONS_ANOTHER_PERSON: sys_mentions_another_person_request,
1734
    },
1735
)
1736

1737
simplified_dialogflow.set_error_successor(State.USR_CHANGE_TO_PERSON, State.SYS_ERR)
1738

1739
################################################################################
1740
#  SYS_ERR
1741
simplified_dialogflow.add_system_transition(
1742
    State.SYS_ERR,
1743
    (scopes.MAIN, scopes.State.USR_ROOT),
1744
    error_response,
1745
)
1746

1747
dialogflow = simplified_dialogflow.get_dialogflow()
1748

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

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

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

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