-
Notifications
You must be signed in to change notification settings - Fork 0
/
call_session.py
1960 lines (1847 loc) · 93 KB
/
call_session.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
###
##
# Copyright (C) 2021 James A. Bowery
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, see: <http://www.gnu.org/licenses/>.
##
###
import logging
import datetime
from voters import Voter
import voters
from global_utils import select_indirect, PhoneNumber, not_None, phonemes_idx_sigma_match, just_numbers
#from application_factory.extensions import scheduler
#from application_factory.tasks import task2
import random
import voters_df
from voters_df import my_phonemize_cached, my_phonemes_distance_cached, my_phonemize, all_possibilities, my_phonemes_distance, nicknames_of_homonyms
from shelves import sessions_shelve as shelve
from shelves import nick2REGN_NUMs
import os
import telnyx
from threading import Thread
import pandas as pd
import re
from word2number import w2n
from dotenv import load_dotenv
load_dotenv(override=True)
STATE_OR_PROVINCE = os.getenv("STATE_OR_PROVINCE")
exec(open(f'static_data/country/usa/{STATE_OR_PROVINCE}/county_name_to_auditor_phone.py').read())
shelve['live_calls'] = dict()
logging.debug(f'initializing class {shelve}')
def pick_keywords(some_words, num = 3):
from static_data.stop_words import stop_words
logging.debug(some_words)
filtered_sentence = [w for w in some_words.lower().split(' ') if not w.lower() in stop_words]
filtered_sentence = [w for w in filtered_sentence if len(w)>3]
logging.debug(filtered_sentence)
picked_keywords = ' '.join(random.sample(set(filtered_sentence), num))
logging.debug(picked_keywords)
return picked_keywords
def get_current_bills():
###
## Get bills
#
from bs4 import BeautifulSoup
import requests
url = requests.get('https://docs.house.gov/BillsThisWeek-RSS.xml')
soup = BeautifulSoup(url.content, features='lxml')
entries = soup.find_all('entry')
billdict = dict()
# for i in [entries[-1]]:
# title = re.sub(r'[^0-9a-zA-Z]',' ',i.title.text)
# link = i.link['href']
# content = i.content.text
# logging.debug(f'Title: {title}\n\nSummary: {content}\n\nLink: {link}\n\n------------------------\n')
htmlentry = BeautifulSoup(BeautifulSoup(str(entries[-1]), features='lxml').content.text,'html.parser')
blank_bill_number_count = 0
bill_numbers = [re.sub(r'[^0-9]','',x.text) for x in htmlentry.select('.legisNum')],
bill_titles = [x.text.lower() for x in htmlentry.select('.floorText')]
for x in bill_numbers[0]:
print(x)
bill_title = bill_titles.pop(0)
if not(x): # Sometimes the House throws in an item with no number
x = 'abcdefghijklmnopqrstuvwxyz'[blank_bill_number_count]
blank_bill_number_count += 1
continue # TODO find a better identifier than an arbitrary letter of the alphabet
billdict[x] = re.sub(r'[^0-9a-zA-Z]',' ',bill_title)
logging.debug(f'Bill Number: {x}, Title: {billdict[x]}')
# billdict = dict(
# zip(
# [re.sub(r'[^0-9]','',x.text) for x in htmlentry.select('.legisNum')],
# [x.text.lower() for x in htmlentry.select('.floorText')]
# )
# )
#
## Got bills
###
return billdict
class Call_Session:
event_types = { # each must be accompanied by a method of that name with . changed to _
'call.transcription',
'call.answered',
'call.initiated',
'call.recording.saved',
'call.speak.ended',
'call.gather.ended'
}
###
## Action naming conventions for methods are as follows:
## f'{action}q' asks ('q'ueries) the user for information required to take f'{action},
##
## These naming conventions must be followed for the state machine to work.
##
## The state of the state machine is a stack of menus along with other properties persisting in the Call_Session.
## When a menu's item is selected, the item is pushed on top of the stack and the machine enters the new state.
## A menu's lifecycle is:
## 1) self.push_state() #save the context of the current action's menu (if any)
## 2) eval(f'self.{action}q()') #Enter the context for an action's menu
## 3) self.state = f'{action}' #set the state (top of stack)
## 4) self.say('prompt/query the user for voice input') #
## 4) Exit to send voice prompt.
## 5) Receive transcripted voice response.
## 6) eval(f'self.{self.state}()') #Resume execution to take the action on the voice response's transcript.
## 7) eval(f'self.{self.pop_state()}') # Pop the stack back to the prior f'{action}q' and execute immediately.
##
## In some cases, such as a 'yes' confirmation (yes/no) menu, it is necessary to pop two menus.
##
##
## KLUDGE ADAPTATION TO TELNYX LATENCY PROBLEM WITH START OF TRANSCRIPTION:
## f'{action]qq' is interjected in the state transitions to deal with the following issue:
##
## Telnyx voice transcription-driven IVR has a dilemma due to the latency between call.transcription_start() sending
## of a POST to https;//api.telnyx.com/v2/calls/.../actions/transcription_start and the actual start of transcription
## acknowledged by the response_code=200:
## If one waits for a call.speak.end event to start transcription, the user will frequently, if not usually,
## start speaking before the latency period ends and transcription is actually started. If the user response is a
## simple word (such as 'yes' or 'no') there will be no incoming transcription event and the user will be hung in limbo.
## This "limbo" state is actually not limbo. The system is actually waiting for the user to speak but the
## user thinks the system has gone dead.
## * If one simply turns on transcription for the entire call, this limbo is avoided, but my experience has been that
## users will frequently engage in side-talk while the speech synthesis prompt is completing and end up with a nonsense
## response from the IVR system as a result.
## My solution, in the absence of an appropriate function at the telnyx end, is complex and inadequate: for every voice
## prompt, divide it into two parts and add an additional state to the state machine for each part of each prompt.
## The second state initiates the second part of the voice prompt and does the call.transcription_start(), hoping the
## latency approximately matches the duration of the second speech prompt such that any side-talk is ignored until
## precisely the end of the second speech synthesis.
##
## The ...qq methods are the additional states
##
#
delegate_network_actions = ['money','politics','tell_me_about']#
voting_actions = ['delegate','audit','vote','register','tell_me_about']
#
##
###
# res = telnyx.OutboundVoiceProfile.retrieve(os.environ["TELNYX_OUTBOUND_VOICE_PROFILE_ID"])
def __init__(self,event):
Call_Session.sovereign_phones = eval(os.getenv('SOVEREIGN_PHONES') or '[]') # can change sovereigns on the fly
if type(event) == str: # if this is a session id
# initialize only ._id and return the object
# don't initialize .id as that updates the activity timer
# and will inhibit the call hangup on inactivity
self._id = event
return
self.event = event
self.data = event.data
TELNYX_CONNECTION_ID = os.getenv('TELNYX_APP_CONNECTION_ID')
call = telnyx.Call(connection_id=TELNYX_CONNECTION_ID)
# call_control_id for use in telnyx API URL endpoints
call.call_control_id = self.data.payload.call_control_id
self._call = call # later self.call will return telnyx query of call status
self.id = str(self.data.payload.call_control_id) #must be set before other properties
# logging.debug('call control id class is '+str(self.data.payload.call_control_id.__class__))
self.call_control_id = self.data.payload.call_control_id
self.event_type = self.data.event_type
self.speech_prompt = '' # Assuming successful initiation of some intervoting_action
self.kind_of_help_needed = None # intra-transcription processing failure diagnostic to prompt voter for another try
self.payload = self.data.payload
@classmethod
def delete_headntail_sp(cls,trs):
trs = re.sub(r'^\s+','',trs)
trs = re.sub(r'\s+$','',trs)
return trs
@classmethod
def extract_ten_digit_hyphenated_phone(cls,trs):
# trs should not contain any numerals not a part of a phone number
# otherwise it will confound the pattern recognition in PhoneNumber()
mgrp = re.search(r'(\d\d\d-\d\d\d-\d\d\d\d)',trs)
if mgrp:
return mgrp.group(1)
trs = re.sub(r' ?to ?','2',trs) # compensate for bad transcription of the numeral 2
logging.debug(trs)
trs = re.sub(r' ?(or|for) ?','4',trs) # compensate for bad transcription of the numeral 4
logging.debug(trs)
trs = re.sub(r'^7 ','',trs) # compensate for bad transcription of leading 'send' as 7
logging.debug(trs)
numbers = just_numbers(trs)
logging.debug(numbers)
numbers = re.sub(r'(2|4)(\d{10})',r'\2',numbers) #compensate for bad transcription of the word 'to' and 'for'
logging.debug(numbers)
phonetrs = str(PhoneNumber(numbers))
logging.debug(phonetrs)
mgrp = re.search(r'(\d\d\d-\d\d\d-\d\d\d\d)',phonetrs)
if mgrp:
return mgrp.group(1)
else:
return ""
# def add(self):
# """Add a task.
# :url: /add/
# :returns: job
# """
# job = scheduler.add_job(
# func=task2,
# trigger="interval",
# seconds=10,
# id="test job 2",
# name="test job 2",
# replace_existing=True,
# )
# return "%s added!" % job.name
def call_recording_saved(self):
self.payload = self.data.payload
# self.id = self.payload.call_control_id
recording_url = self.data.payload.recording_urls.mp3
recording_name = 'mp3s/'+self.payload.recording_id+".mp3"
import urllib
urllib.request.urlretrieve(recording_url, recording_name)
with open("dynamic_data/transcripts.txt", "a") as file_object:
print(f'{self.id}: {recording_name}',file=file_object)
self.log(recording_name)
def call_initiated(self):
# Must use _call because call is not yet
# available from telnyx.Call.retrieve
res =self._call.answer()
logging.debug('answering: '+str(res))
@classmethod
def call_transcription_thread(cls, self):
def evalnewstate(self):
self.speak_stop()
logging.debug('evalnewstate: '+str(self.state))
eval('self.'+self.state+'()')
# logging.debug('speak: '+str(self.speech_prompt))
self.speak()
logging.debug('TRANSCRIPTIONPID: '+str(os.getpid()))
self.call.transcription_stop()
self.payload = self.data.payload
# self.id = self.payload.call_control_id
try:
self.speak_stop() # the user wants to do something so stop yammering at him and get on with it.
except Exception as e:
logging.debug(e)
self.transcript = self.payload.transcription_data.transcript.lower()
self.transcript_confidence = self.payload.transcription_data.confidence
self.log(f'confidence {self.transcript_confidence}: {self.transcript}')
if self.transcript.find('help')>-1: # help should always be available once we're listening
logging.debug(f'needs help for {self.state}')
if self.state[-1] != 'q':
logging.debug('no q ending '+str(self.state))
self.state = self.state+'q'
else:
logging.debug('q ending '+str(self.state))
self.make_need_help(self.state, True)
logging.debug(f'{self.state} with self.need_help[{self.state}] == {self.need_help[self.state]}.')
self.say('Say')
self.say('menu')
self.say('to return to the main menu')
elif self.transcript.find('menu')>-1:
logging.debug('returning to main menu')
self.say('returning to main menu')
self.transcript=''
self.reset_state_to('delegate_network_actionq') # Discard any stacked states. This is the main menu.
else:
logging.debug(f'{self.transcript} contains neither help nor menu')
logging.debug(self.transcript)
logging.debug('Transcription Confidence: '+str(self.transcript_confidence))
with open("dynamic_data/transcripts.txt", "a") as file_object:
# print(f'{self.id} {self.transcript_confidence}: {self.transcript}',file=file_object)
print(f'{self.id} {self.transcript_confidence}: {self.payload.transcription_data.transcript}',file=file_object)
self.transcript = Call_Session.delete_headntail_sp(self.transcript)
evalnewstate(self)
def call_transcription(self):
try:
self.call.transcription_stop()
except Exception as e:
logging.error('unable to stop transcription because')
logging.error(e)
thread = Thread(target=Call_Session.call_transcription_thread,args=(self,)) # this evaluates to the next state's function (method) but doesn't call it except via Thread's targeting
thread.start()
logging.debug("Thread started on "+str('self.'+self.state))
return # immediately respond with success to preempt telnyx from bouncing the transcript again (telnyx API bug?)
def log(self,msg):
log = self.get('log')
log[datetime.datetime.now()] = msg
self.set('log',log)
def say(self,text_to_add_to_speech_prompt, end=None):
# the actual call to speak is just before exiting from an execution of a self.state
# only call this when the text is complete enough to justify a pause, as at the end of a paragraph
text_to_add_to_speech_prompt = re.sub('_',' ',text_to_add_to_speech_prompt)
text_to_add_to_speech_prompt = text_to_add_to_speech_prompt+("""
""" if end==None else '') # that was the pause
logging.debug('queuing up: '+str(text_to_add_to_speech_prompt))
self.speech_prompt += text_to_add_to_speech_prompt
def speak(self): ## called just before a successful exit from a *q self.state (one that queries the user for speech input)
if not(self.speech_prompt):
return
logging.debug("NOW SPEAKING"+str(self.speech_prompt))
self._call.speak(language='en-US', voice='male', payload = self.speech_prompt)
self.log(self.speech_prompt)
self.speech_prompt = ''
def get(self,prop):
return shelve[self.id][prop] if prop in shelve[self.id] else None
def set(self,prop,val):
pdict = shelve[self._id]
pdict[prop] = val
# logging.debug(prop,val+str(pdict[prop]))
shelve[self._id] = pdict
shelve.sync()
def vr_count(self):
return len([x for x in self.voters_with_phone if x.is_registered()])
@property
def on_confirmation(self):
on_confirmation = self.get('on_confirmation')
return on_confirmation
@on_confirmation.setter
def on_confirmation(self,onconfirmation):
logging.debug('setting on_confirmation')
logging.debug(onconfirmation)
self.set('on_confirmation',onconfirmation)
logging.debug('getting on_confirmation')
logging.debug(self.on_confirmation)
@property
def on_disambiguation(self):
on_disambiguation = self.get('on_disambiguation')
return on_disambiguation
@on_disambiguation.setter
def on_disambiguation(self,ondisambiguation):
logging.debug('setting on_disambiguation')
logging.debug(ondisambiguation)
self.set('on_disambiguation',ondisambiguation)
logging.debug('getting on_disambiguation')
logging.debug(self.on_disambiguation)
@property
def whoms(self):
whoms = self.get('whoms')
return whoms
@whoms.setter
def whoms(self,whoms):
self.set('whoms',whoms)
@property
def action(self):
action = self.get('action')
return action
@action.setter
def action(self,action):
self.set('action',action)
@property
def action_modifier(self):
action_modifier = self.get('action_modifier')
return action_modifier
@action_modifier.setter
def action_modifier(self,action_modifier):
self.set('action_modifier',action_modifier)
@property
def which_whom_query(self):
which_whom_query = self.get('which_whom_query')
return which_whom_query
@which_whom_query.setter
def which_whom_query(self,which_whom_query):
self.set('which_whom_query',dict(which_whom_query) if not_None(which_whom_query) else None) #normalize to dict rather than series
@property
def first_whom_query(self):
first_whom_query = self.get('first_whom_query')
return first_whom_query
@first_whom_query.setter
def first_whom_query(self,first_whom_query):
self.set('first_whom_query',dict(first_whom_query) if not_None(first_whom_query) else None) #normalize to dict rather than series
@property
def phone(self):
phone = PhoneNumber(self.get('phone'))
return phone
@phone.setter
def phone(self,numberofclassPhone):
self.set('phone',numberofclassPhone)
@property
def id(self):
return self._id # 'def get' above needs this so it can't call 'def get'
@id.setter
def id(self,idval):
self._id = idval
# if not found in the shelve database
# (the should initialize only the first time id is set)
if not(idval in shelve):
## initialize
shelve[idval]={} # this enables the above 'def set' method as well as 'def get'
shelve.sync()
self.set('log',dict()) # log of this session's dialogue
self.phone = self.data.payload.from_.ten_digit_hyphenated
logging.debug('initializing session for '+str(self.phone))
logging.debug(f"1self.voters_with_phone = Voter.select({'PHONENO:'+str(self.phone)})")
self.voters_with_phone = Voter.select({'PHONENO':str(self.phone)}) #returns a list of voters
logging.debug(self.voters_with_phone)
if(len(self.voters_with_phone)==0):
self.voter = Voter()
self.voter.PHONENO = str(self.phone)
logging.debug(f"2self.voters_with_phone = Voter.select({'PHONENO:'+str(self.phone)})")
self.voters_with_phone = Voter.select({'PHONENO':str(self.phone)})
else:
self.voter = self.voters_with_phone[0] # if multiple possible voters at this phone pick the first one
self.need_introduction = True
# TODO: states relating to "gifts" are for "christmas money"
self.need_help = {qstate:not(self.voter.is_active) for qstate in [ 'giftq', 'votingq', 'delegate_network_actionq', 'voting_actionq', 'whomq', 'delegateconfirmq', 'voteq', 'votebillq', 'recallconfirmq', 'registerwhomconfirmq', 'payq', 'payconfirmq']}
self.make_need_help('payq', True) # Always provide the caveat speech for paying.
self.state = 'initialized'
else:
logging.debug(f"3self.voters_with_phone = Voter.select({'PHONENO:'+str(self.phone)})")
self.voters_with_phone = Voter.select({'PHONENO':str(self.phone)})
live_calls = shelve['live_calls']
live_calls[idval] = datetime.datetime.now()
shelve['live_calls'] = live_calls
@property
def need_help(self):
need_help = self.get('need_help')# TODO: move this to Voter class so people aren't harrassed everytime they call
return need_help
@need_help.setter
def need_help(self,nh):
self.set('need_help',nh)
@property
def voter(self):
# vtr = self.get('voter')
# if vtr != None:
# logging.debug('get ',vtr.id,' voter.__class__'+str(vtr.__class__))
return self.get('voter')
@voter.setter
def voter(self,votervalue):
self.set('voter',votervalue)
@property
def bill(self):
return self.get('bill')
@bill.setter
def bill(self,billvalue):
self.set('bill',billvalue)
@property
def call(self):
TELNYX_CONNECTION_ID = os.getenv('TELNYX_APP_CONNECTION_ID')
call = telnyx.Call(connection_id=TELNYX_CONNECTION_ID)
call.call_control_id = self._id
logging.debug('attempting to retrieve call with id '+str(self._id))
return call.retrieve(self._id)
# return self.get('call')
@call.setter
def call(self,callvalue):
# this is invalid
# raise exception?
return
@property
def is_alive(self):
TELNYX_CONNECTION_ID = os.getenv('TELNYX_APP_CONNECTION_ID')
call = telnyx.Call(connection_id=TELNYX_CONNECTION_ID)
# call_control_id for use in telnyx API URL endpoints
call.call_control_id = self._id
return call.retrieve(self._id).is_alive
@property
def state(self):
logging.debug('get(state): '+str(self.get('state') )) # 'None' if None)
state = self.get('state') # 'None' if None
logging.debug(f'state: {state}')
return None if state == None else str(state[-1]) # 'None' if None
@state.setter
def state(self, new_state):
state = self.get('state')
self.set('state',[new_state] if state == None else self.get('state')[:-1]+[new_state]) #replace top of stack
def push_state(self): # This pushes the current state and leaves placeholder for the new state that must be filled
state = self.get('state')
state.append(None)
self.set('state', state)
def pop_state(self):
state_stack = self.get('state')
state_stack.pop() # toss the state we're returning from
self.set('state', state_stack)
state = self.state # return only the state to which we're returning
return state if state[-1]==')' else state+'()' # return in eval form only the state to which we're returning
def reset_state_to(self,new_state):
self.set('state',[new_state])
@property
def call_control_id(self):
logging.debug('get(call_control_id): '+str(self.get('call_control_id') )) # 'None' if None)
return str(self.get('call_control_id') ) # 'None' if None
@call_control_id.setter
def call_control_id(self, new_call_control_id):
self.set('call_control_id',new_call_control_id)
@property
def billdict(self):
billdict = self.get('billdict')
if not(billdict):
self.billdict = get_current_bills()
return self.get('billdict')
@billdict.setter
def billdict(self, new_billdict):
self.set('billdict',new_billdict)
@property
def whom(self):
whom_id = self.get('whom_id')
return Voter(self.get('whom_id')) if whom_id else None
@whom.setter
def whom(self, new_whom):
self.set('whom_id',new_whom.id if new_whom else None)
@property
def amount(self):
return self.get('amount')
@amount.setter
def amount(self, new_amount):
self.set('amount',new_amount)
def best_phoneme_match(self, astring, phoneme_options):
astring_phonemes = my_phonemize(astring)
phds = pd.Series({optstr:my_phonemes_distance_cached(optphn,astring_phonemes,optstr,astring) for optstr, optphn in phoneme_options.items()}).sort_values(ascending=False)
logging.debug(phds)
mv = phds.min()
mi = phds.idxmin()
logging.debug(mv+str( mi))
return mi
def match_transcript(self,options, sigma=1):
logging.debug('matching transcript: '+self.transcript)
for option in options:
logging.debug(f'option "{option}" == "{self.transcript}"')
if self.transcript.find(option)>-1:
return option
# exact match failed, so try phoneme distance
tph = my_phonemize(self.transcript)
phds = pd.Series({option:my_phonemes_distance(my_phonemize(option),tph) for option in options})
logging.debug(phds)
return phonemes_idx_sigma_match(phds,sigma=sigma)
# logging.debug(phds)
# mv = min(phds)
# logging.debug(mv)
# mi = phds.index(mv)
# logging.debug(mi)
# logging.debug(options[mi])
# return options[mi]
def hangup(self):
if self.is_alive:
self.call.hangup()
###
## Start critical section
#
try:
live_calls = shelve['live_calls']
del live_calls[self.id]
shelve['live_calls'] = live_calls
except Exception as e:
logging.debug('The hangup method failed to delete session id '+str(self.id))
logging.debug('The Exception was '+str(e))
#
## End critical section
###
@property
def captcha_digits(self):
return self.get('captcha_digits')
@captcha_digits.setter
def captcha_digits(self,digits):
self.set('captcha_digits',digits)
####
## State Machine
#
# initialized -> answered/welcomed -> voting_action?
def call_answered(self):
# if not(self.data.payload.from_.area in {'712', '515','641', '402','319','563'}): # TODO configuration
# logging.debug('hanging up on area code '+str(self.data.payload.from_.area))
# self.hangup()
# return
# self.payload = self.data.payload
# self.call.transcription_start(language='en')
## transcription_url = f'https://api.telnyx.com/v2/calls/{self.call_control_id}/actions/transcription_start'
## headers2 = {'Content-Type':'application/json','Accept': 'application/json;charset=utf-8','Authorization': f'Bearer {telnyx.api_key}',}
## data2 = '{"language":"en"}'
## import requests
## response2 = requests.post(transcription_url, headers=headers2, data=data2)
## if response2:
## logging.debug(response2)
# start_recording = self._call.record_start(format="mp3", channels="single")
# logging.debug(start_recording)
# self.say("Welcome to the demo test version of the delegate network for Iowa. The delegate network is publicly auditable at all times.") # TODO configuration
import random
self.captcha_digits = ['0123456789'[random.randint(0,9)] for x in range(2)]
self.call.gather_using_speak(language='en-US',voice="female", payload=f"Welcome to the demo test version of the delegate network for Iowa. To prove you're a person, please enter these 2 numbers on your keypad: {' '.join(self.captcha_digits)}", maximum_digits=2, minimum_digits=2)
def call_gather_ended(self):
if self.payload.digits != ''.join(self.captcha_digits):
self.say("That didn't match. Good-bye.")
self.speak()
self.call.hangup()
return
self.say("Thank you.")
# self.say("The delegate network is publicly auditable at all times.") # TODO configuration
# self.say("To see the audit log, visit http://delegate.network/audit")
# self.say("All actions taken in the demo test will be erased without notice.")
self.delegate_network_actionq()
def call_speak_ended(self):
logging.debug('call_speak_ended called')
self.payload = self.data.payload
if self.state[-2:] == 'qq':
self.call.transcription_start(language='en')
eval('self.'+self.state+'()')
elif self.state[-1]=='q':
pass
logging.debug('call_speak_end returning')
def make_need_help(self,qstate,boolval):
nh = self.need_help
nh[qstate] = boolval
self.need_help = nh
def delegate_network_actionq(self):
self.state="delegate_network_actionq"
logging.debug('EXECUTING delgate_network_actionq')
if not(self.voter.balance):
# Bypass the store if no delegate money
self.push_state() #but come back after voting action complete in the event the balance becomes nonzero
self.voting()
return
if self.need_help['delegate_network_actionq']:
self.say("You can interrupt me at any time.")
self.say("Say. money. if you would like to send someone delegate money.")
self.say("Say. politics. to participate in the delegate network.")
self.say("Say. tell me about. to hear about this service.")
self.make_need_help('delegate_network_actionq',False)
if self.sovereign:
self.say("since you are calling from a sovereign's phone, you are privileged to create delegate money when you say, 'money'!")
# delegate_network_action? (delegate, vote, recall, audit, register) -> delegate_network_action
else:
# self.say( "If you need help, just say so.")
self.say( "One moment...")
self.state="delegate_network_actionqq"
def delegate_network_actionqq(self):
self.say("Please choose: ")
self.sayor(Call_Session.delegate_network_actions)
self.state="delegate_network_action"
@property
def sovereign(self):
return self.phone in Call_Session.sovereign_phones
def delegate_network_action(self):
self.state = 'delegate_network_action'
take_delegate_network_action = self.match_transcript(Call_Session.delegate_network_actions,sigma=0)
if not(take_delegate_network_action):
self.say("I didn't quite get that.")
self.delegate_network_actionq()
return
logging.debug(take_delegate_network_action)
dispatch_dict = {"money":self.payq, "politics":self.voting,"tell_me_about":self.tell_me_about}
logging.debug(dispatch_dict[take_delegate_network_action])
self.state="delegate_network_actionq"#come back after store action complete
self.push_state()
(dispatch_dict[take_delegate_network_action])()
def delegate_network_actionhelp(self):
self.make_need_help('delegate_network_actionq', True)
self.delegate_network_actionq()
def tell_me_about(self):
self.say("the, delegate money and political networks are Services of the Berkana Ecclesium of The Fair Church") # TODO configuration
self.say("both are intended to revitalize the heritage of local autonomy that founded the United States")
self.say("please visit http://delegate.network")
self.returnq()
def loopq(self):
# TODO: On entry self.state == self.action? ie: no 'q' suffix.
eval(f'self.{self.state}q()')
def returnq(self):
# Nothing should be done after this method is called.
eval('self.'+self.pop_state()) # call the q method of the parent menu -- return all the way to terminate this thread
def voting(self):
# This is called only at the end of call_answered.
# If this is the first time for this voter, push voting_actionq to get his delegate from him and then pop back to voting_actionq, otherwise, just go to voting_actionq.
if not(self.voter.is_active):
# self.say("Here, Registered voters may, at will")
# self.say("vote directly on bills before the US House of Representatives.")
# self.say("delegate their power")
# self.say("audit how that power is being used, and")
# self.say("recall that delegation of power.")
# self.say("At any time, you may interrupt me")
# self.say("say, help, for additional instructions")
# self.say("or say, menu, to return to the main menu")
# self.say("or just hang up on me.")
self.say("Let's get started!")
self.say("first")
self.state='voting_actionq' #
self.push_state() #come back to voting_actionq after delegating
self.delegateq()
else:
self.voting_actionq()
if False:
speech_prompt = "According to our latest update from the Iowa Secretary of State," #TODO configuration
if self.vr_count():
if self.vr_count() == 1:
self.say(speech_prompt + " there is one person registered to vote at your caller ID phone number.")
self.say("I'll assume you are that person unless you tell me your name and it doesn't match.")
else:
self.say(speech_prompt + f" there are {self.vr_count()} registered voters at your caller ID phone number.")
self.say("For now I'll assume you are one of them.")
else:
self.say(speech_prompt + " there is no one registered to vote with your caller ID phone number. ")
self.say("Your delegations and votes will have effect once the delegate network verifies you are a registered voter.")
# self.speak()
def voting_actionq(self):
self.state='voting_actionq'
if self.need_help['voting_actionq']:
self.say("Say. delegate. if, in the absence of your vote on a bill, you would like to delegate your voting power to another registered voter.")
self.say("Say. vote. if you would like to vote on a bill.")
self.say("Say. audit. if you would like to audit votes.")
self.say("Say. register. ",end='')
if self.voter.is_registered():
self.say("to update your voter registration.")
else:
self.say(f"if you want your delegate network actions to count when calling from your current phone number: {self.voter.PHONENO}.")
self.say("Say. tell me about. to hear about this service.")
# self.say("say. pay. if you would like to to send someone in simulated property money.")
self.make_need_help('voting_actionq',False)
# voting_action? (delegate, vote, audit, register, tell_me_about) -> voting_action
else:
self.say( "one moment...")
self.state='voting_actionqq'
def voting_actionqq(self):
self.say("Would you like to ")
self.sayor(Call_Session.voting_actions)
self.state="voting_action"
def voting_action(self):
self.state = 'voting_action'
take_voting_action = self.match_transcript(Call_Session.voting_actions,sigma=1.6)
if not(take_voting_action):
self.say("I didn't quite get that.")
self.voting_actionq()
return
logging.debug(take_voting_action)
dispatch_dict = {"delegate":self.delegateq, "vote":self.voteq, "audit":self.auditq, "register":self.registerq, "tell_me_about":self.tell_me_about}
logging.debug(dispatch_dict[take_voting_action])
(dispatch_dict[take_voting_action])()
def voting_actionhelp(self):
self.make_need_help('voting_actionq', True)
self.voting_actionq()
def whomhelp(self,theiryour='their'):
if self.kind_of_help_needed:
self.say("unable to identify")
if self.kind_of_help_needed == 'location':
self.kind_of_help_needed = None
# self.say("I did not understand a location from what I heard, which was:")
# self.say(self.transcript)
self.say(f"Please say {theiryour} name again and include location information such as their city, county, stree name or zipcode")
else:
self.say("You might need to spell a name.")
self.say("For example, instead of saying:")
self.say("JOHN, Doe, OF, Warren, County,")
self.say("You might spell out the name, Doe," )
self.say("JOHN, D. O. E. , OF, Warren, County,")
else:
self.say(f"Just say {theiryour} 10 digit phone number or their name as it appears in {theiryour} voter registration.")
self.say(f"If you say {theiryour} name, please also provide any of {theiryour} town, county, zip and/or street name.")
self.say("Please speak slowly and distinctly.")
def delegateq(self):
self.state = 'delegateq'
if self.need_help['whomq']:
self.say("In your absence on a vote, tell me to whom you delegate your voting power. ")
self.whomhelp()
self.make_need_help('whomq',False)
if self.voter.default_delegate:
self.say("Curently, your delgate is "+self.voter.default_delegate.name_identification_string()+".")
self.state='delegateqq'
def delegateqq(self):
self.say("To whom do you wish to delegate your vote when absent?")
self.state = 'delegate'
def voter_delegate_whom(self): #on_confirmation callback
self.voter.delegate(self.whom)
self.say(f'You have delegated {self.voter.default_delegate.first_middle_last_of_city_string()} to vote on your behalf in your absence on a vote. ')
def voter_pay_whom_amount(self): #on_confirmation callback
self.voter.pay(self.whom,self.amount)
self.say(f'You have paid ${self.amount} in Delegate money to {self.whom.first_middle_last_of_city_string()}')
def delegate(self):
self.state = 'delegate'
self.action = 'delegate'
self.action_modifier=None
self.on_confirmation = Call_Session.voter_delegate_whom
self.act_whom_match_and_disambiguate()
def act_whom_match_and_disambiguate(self):
returnfrompmt = self.person_match_transcript() # saves matched person(s) in self.whoms and if just one, then in self.whom
logging.debug(returnfrompmt)
if returnfrompmt: # saves matched person(s) in self.whoms and if just one, then in self.whom
#### confirm?
if self.ambiguouswhom():
self.push_state() #come back to confirm after disambiguation
self.disambiguatewhomq()
else:
logging.debug('unambiguous')
self.push_state() #may come back to query for current action again upon disconfirmation
self.confirmq()
else:
self.need_help['whomq'] = True
if not(self.kind_of_help_needed):
self.kind_of_help_needed = 'unknown'
self.loopq() # restart 'q'uery for current action
def yn_transcript(self):
return self.match_transcript(['yes','no'])
def disambiguatewhomq(self):
self.state = 'disambiguatewhomq'
self.on_disambiguation = self.confirmq
self.say(f'There are {len(self.whoms)} registered at that number.')
first_names = [x.FIRST_NAME for x in self.whoms]
logging.debug(first_names)
self.sayor(first_names)
self.state='disambiguatewhomqq'
def disambiguatewhomqq(self):
self.say('Which did you intend?')
self.state = 'disambiguatewhom'
def disambiguatewhom(self):
self.state = 'disambiguatewhom'
first_names = [x.FIRST_NAME for x in self.whoms]
first_name = self.match_transcript(first_names)
if not(first_name):
self.say("I didn't quite get that.")
self.loopq()
return
self.whom = self.whoms[first_names.index(first_name)]
self.push_state() # may come back to query for another first name to disambiguation upon disconfirmation
self.confirmq()
def sayor(self,options):
try:
self.say(', '.join(options[:-1])+', or, '+options[-1])
except:
logging.debug(f'failed sayor with options: {options}')
def ambiguouswhom(self):
return self.whoms != None and len(self.whoms)>1
def payq(self):
self.state = 'payq'
self.say("")
# self.say("spelled, c. h. r. i. s. m. o. n.")
if self.voter.balance:
self.say(f'Your delegate bank balance is ${self.voter.balance}')
else:
self.say("You don't yet have any delegate money")
self.returnq()
return
if self.need_help['payq']:
# self.say("let's say you want to send $10.25 in delegate money to delegate john doe of montgomery county.")
# self.say("say, $10.25 to john doe of montgomery county.")
# self.say("or, if his voter registered phone number is 712-321-9876,")
# self.say("say, $10.25 to 712-321-9876")
self.make_need_help('payq',False)
self.state='payqq'
def payqq(self):
self.say("send how much delegate money to what delegate?")
# self.push_state()
self.state = 'pay'
def pay(self):
self.state = 'pay'
trs = self.transcript
trs = re.sub(r'^(send|pay|give|transfer)','',trs)
###
## Compensate for bad money transcription via w2n library.
#
dollars = '0'
cents = '00'
if trs.find('dollars')>-1:
ds = re.search(r'(.*)dollars',trs)
try:
dollars = w2n.word_to_num(ds.group(1))
logging.debug(f'word_to_num({ds.group(1)})=={dollars} dollars')
except:
dollars_match= re.search(r'([0-9,]+) dollars',ds.group(0))
if dollars_match:
dollars = dollars_match.group(1)
logging.debug(f'{ds.group(0)} -> {dollars}')
else:
self.say("I'm sorry, but I didn't understand.")
self.say("I thought I heard you say")
self.say(self.transcript)
self.make_need_help('payq',True) # provide help again
self.payq() # and re-prompt for the amount
return
logging.debug(f'nullify commas: {dollars}')
trs = re.sub(re.escape(ds.group(1)),'',trs)
trs = re.sub('dollars','',trs)
if trs.find('cents')>-1:
cs = re.search(r'(.*)cents',trs)
try:
cents = w2n.word_to_num(cs.group(1))
except:
cents = re.search(r'(\d+) cents',ds.group(0)).group(1)
trs = re.sub(re.escape(cs.group(1)),'',trs)
trs = re.sub('cents','',trs)
if int(dollars) or int(cents):
if len(cents)==1:
cents = '0'+cents
logging.info(f'compensating for bad transcription of dollar value ${dollars}.{cents}')
trs = f'${dollars}.{cents} '+trs
#
## Compensated for bad money transcription via w2n library.
###
trs = re.sub(',','',trs) # deal with thousands, eg $1,000
logging.debug(trs)
amt = re.search(r'\$((\d+)\.(\d\d)|\.(/d/d)|(\d+)|)',trs)
if not(amt):
self.say("I'm sorry, but I didn't hear an amount.")
self.say("I thought I heard you say")
self.say(self.transcript)
self.make_need_help('payq',True) # provide help again
self.payq() # and re-prompt for the amount
return
self.amount = amt.group(1)
logging.debug(str(amt))
trs = re.sub(re.escape('$'+amt.group(1)),'',trs, count=1) # get rid of non-phone number numerals before extracing problematic transcriptions of phone number
logging.debug(trs)
self.transcript = re.sub(r'^\s*to\S*','',trs)
self.action = 'pay'
self.action_modifier = f' ${self.amount} to '
self.on_confirmation = Call_Session.voter_pay_whom_amount
self.act_whom_match_and_disambiguate()
return
# the following code was written when "christmas money" was being considered.
# it permits sending to any phone number regardless of voter registration of that phone number
def say_confirm_action(self):
voter = self.whom
if self.which_whom_query and self.first_whom_query != self.which_whom_query:
if 'MIDDLE_NAME' in self.which_whom_query and not('FIRST_NAME' in self.which_whom_query):
# and self.first_whom_query['FIRST_NAME'] == self.which_whom_query['MIDDLE_NAME']:
self.say("Do you call that person by their middle name?")
self.say(f'Please confirm, that you want to {self.action}{self.action_modifier or ""} {voter.first_middle_last_of_city_string()}. ',end='')
if self.which_whom_query and 'COUNTY' in self.which_whom_query:
self.say(f'in {voter.COUNTY} county')
def confirmq(self):
self.state='confirmq'
self.say_confirm_action()
self.state='confirmqq'