Commit 0629d579 by Surya Narayana

Replace actions.py

parent 999831a3
Showing with 183 additions and 66 deletions
...@@ -6,97 +6,214 @@ from rasa_sdk.forms import FormAction, Action ...@@ -6,97 +6,214 @@ from rasa_sdk.forms import FormAction, Action
from rasa_sdk.events import SlotSet from rasa_sdk.events import SlotSet
import re import re
from twilio.rest import Client from twilio.rest import Client
from datetime import datetime
import time, os
os.environ['TZ'] = 'US/Central'
time.tzset()
account_sid = "ACc460d692e5a467c60b352714b1416140" account_sid = "ACc460d692e5a467c60b352714b1416140"
auth_token = "bf2a890f36e3329b52d0516a14097623" auth_token = "bf2a890f36e3329b52d0516a14097623"
client = Client(account_sid, auth_token) client = Client(account_sid, auth_token)
regex_phone = r"(\d{3}[-\.\s]??\d{3}[-\.\s]??\d{4}\d?|\(\d{3}\)\s*[-]?\d{3}[-\.\s]??\d{4}|\d{3}[-\.\s]??\d{4}|[+]?\d[-][(]?\d{3}[)]?[-]\d{3}[-]\d{4})" regex_phone = r"(\d{3}[-\.\s]??\d{3}[-\.\s]??\d{4}\d?|\(\d{3}\)\s*[-]?\d{3}[-\.\s]??\d{4}|\d{3}[-\.\s]??\d{4}|[+]?\d[-][(]?\d{3}[)]?[-]\d{3}[-]\d{4})"
class ActionSendSms(Action):
def name(self) -> Text: import re
return "action_send_sms"
async def run( #extracting email from user entered text
self, def ExtractEmail(slot_to_fill):
dispatcher: CollectingDispatcher, email_addresse_list = re.findall('\S+@\S+', slot_to_fill)
tracker: Tracker, return email_addresse_list
domain: Dict[Text, Any],
) -> List[Dict[Text, Any]]:
for each_event in tracker.events[::-1]: #extracting mobile from user enterd text
if each_event['event'] == 'user': def ExtractMobilenumber(slot_to_fill):
#print(tracker.events[-1]['parse_data']['intent']['name']) #phone number extraction
if each_event['parse_data']['intent']['name'] == "send_sms": #regex = re.compile("\+?\d[\( -]?\d{3}[\) -]?\d{3}[ -]?\d{2}[ -]?\d{2}")
querytext = each_event['text'] regex = re.compile("\d{3}[-\.\s]??\d{3}[-\.\s]??\d{4}|\(\d{3}\)\s*\d{3}[-\.\s]??\d{4}|\d{3}[-\.\s]??\d{4}")
intentname = "send_sms" mobile_numbers_list = re.findall(regex, slot_to_fill)
confidence = each_event['parse_data']['intent']['confidence'] return mobile_numbers_list
print(querytext) def validate_available_date(date_text):
pattern = re.compile(regex_phone) try:
data = pattern.search(querytext) timestamp = int(datetime.strptime(date_text, '%Y-%m-%d %H:%M:%S').strftime("%s"))
new_date_text = datetime.fromtimestamp(timestamp)
if data is not None: print("new_date_text",new_date_text)
phone_no = data.group() HolidaysList = ["2021-01-01","2021-05-31","2021-07-05","2021-09-06","2021-11-25","2021-11-26","2021-12-24","2021-12-27"]
client.messages.create( dayNumber = int(new_date_text.strftime('%w')) #To check weekend or weekday
to = phone_no, print("daynumber",dayNumber)
from_= "+19169995105", dateCheck = new_date_text.strftime('%Y-%m-%d') #To check for public holidays
body= "Hi. This is VERA from V-Soft consulting. We may have great job opportunities based on your profile. Are you interested ? " print("dateCheck",dateCheck)
) timeCheck = new_date_text.strftime('%-H') #To check for office hours
print("timeCheck",timeCheck)
dispatcher.utter_template('utter_sms', tracker) date_format = "%Y-%m-%d %H:%M:%S"
return [] # create datetime objects from the strings
class Primary_information(FormAction): givenDate = datetime.strptime(date_text, date_format)
print('in Primary_information') presentDate = str(datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
presentDate = datetime.strptime(presentDate, date_format)
if givenDate >= presentDate:
print("passed past date check condition")
if dayNumber not in [0,6]:
print("passed weekday condition")
if dateCheck not in HolidaysList:
print("passed non holidays day condition")
if int(timeCheck) >=10 and int(timeCheck) < 18:
print("passed working hours condition")
return True
return False
except Exception as e:
print("FALSE in validate_available_date",e)
return False
def validate_date(date_text):
try:
datetime.strptime(date_text, '%Y-%m-%d %H:%M:%S')
return True
except ValueError:
return False
class greet_primary_information(FormAction):
print('in greet_primary_information_form')
def name(self) -> Text: def name(self) -> Text:
return "primary_information_form" return "greet_primary_information_form"
@staticmethod @staticmethod
def required_slots(tracker: Tracker) -> List[Text]: def required_slots(tracker: Tracker) -> List[Text]:
intent = tracker.latest_message.get("intent", {}).get("name") intent = tracker.latest_message.get("intent", {}).get("name")
conf = tracker.latest_message.get("intent", {}).get("confidence") conf = tracker.latest_message.get("intent", {}).get("confidence")
print('querytext',tracker.slots["querytext"]) print('tracker.slots',tracker.slots)
print('intent',intent) print("INTENT")
print('conf',conf) if intent == "stop" and conf>0.8:
#if intent == "affirm" : print("INSTOP")
if intent != "deny" : tracker.slots["querytext"] = "stop"
print("IN from deny") return["querytext"]
#tracker.slots["querytext"] = "no"
return["intentname","confidence","querytext","askques", "email", "mobilenumber", "company","experience", "skills","availabletime"]
else: else:
print("IN from deny1") return["intentname","confidence","querytext" ,"askques","refferals","skills", "email_mobile","email", "mobilenumber", "availabletime","response"]
tracker.slots["querytext"] = "no"
return["availabletime"]
def validate_querytext(self,value:Text,dispatcher: CollectingDispatcher,tracker: Tracker,domain: Dict[Text, Any],) -> Dict[Text, Any]: def validate_querytext(self,value:Text,dispatcher: CollectingDispatcher,tracker: Tracker,domain: Dict[Text, Any],) -> Dict[Text, Any]:
print("------------------------") print("------------------------")
#print(tracker.events) #print(tracker.events)
for each_event in tracker.events[::-1]: for each_event in tracker.events[::-1]:
print('1111111')
print("each_event['event']", each_event['event'])
if each_event['event'] == 'user': if each_event['event'] == 'user':
print('2222') #print(tracker.events[-1]['parse_data']['intent']['name'])
print('intent name', tracker.events[-1]['parse_data']['intent']['name']) if each_event['parse_data']['intent']['name'] == "greet":
if each_event['parse_data']['intent']['name'] == "affirm":
print('33333')
querytext = each_event['text'] querytext = each_event['text']
intentname = "affirm" intentname = "greet"
confidence = each_event['parse_data']['intent']['confidence'] confidence = each_event['parse_data']['intent']['confidence']
print(querytext)
break break
print('44444444')
return {"querytext":querytext,"intentname":intentname,"confidence":confidence} return {"querytext":querytext,"intentname":intentname,"confidence":confidence}
def validate_askques(self,value:Text,dispatcher: CollectingDispatcher,tracker: Tracker,domain: Dict[Text, Any],) -> Dict[Text, Any]:
print('in validate askques')
print(tracker.events)
#intentname=tracker.events[-1]['parse_data']['intent']['name']
intentname="greet"
#confidence=tracker.events[-1]['parse_data']['intent']['confidence']
confidence= 0.8
slot_to_fill = value.lower()
print("askques")
print(slot_to_fill)
print(value)
if slot_to_fill == "yes":
print('in yes askq')
return {"askques":"yes",'skills':None,"intentname":"affirm","confidence":0.8,"refferals":"empty","mobilenumber":"None","email":"None"}
elif slot_to_fill == "no":
print('askques-no')
return {"askques":"no","refferals":None,"intentname":"deny","confidence":0.8}
else:
print("------------None------------")
return {"askques":None}
#validating email and phone user can give both or single entity value
def validate_email_mobile(self,value:Text,dispatcher: CollectingDispatcher,tracker: Tracker,domain: Dict[Text, Any],) -> Dict[Text, Any]:
print('in validate email_mobile')
slot_to_fill = value.lower()
print("email_mobile")
print(slot_to_fill)
return {"email_mobile": slot_to_fill ,"availabletime":None , "refferals":"None", "email":"None", "mobilenumber":"None"}
#validating email using regex
def validate_email(self,value:Text,dispatcher: CollectingDispatcher,tracker: Tracker,domain: Dict[Text, Any],) -> Dict[Text, Any]:
print('in validate email')
slot_to_fill = value.lower()
print("email_mobile")
print(slot_to_fill)
email_addresse_list=ExtractEmail(slot_to_fill)
print('email_addresse_list',email_addresse_list)
if email_addresse_list == []:
return {"email":None}
else:
return { "refferals" : "None","email": email_addresse_list, "email_mobile":"None"}
def validate_refferals(self,value:Text,dispatcher: CollectingDispatcher,tracker: Tracker,domain: Dict[Text, Any],) -> Dict[Text, Any]:
print('in validate refferals')
slot_to_fill = value.lower()
print("refferals")
print(slot_to_fill)
print(value)
if value.lower() in ['yes','yeah','ha','y']:
print('validate_refferals yes')
return {"refferals":"None","response":"Great! Please enter the candidate’s name and phone number in our portal http://app.vsoftconsulting.com/aistaffingprod/referral.html ​with your reference number. Thank you for your time and Have a great day.","email_mobile":"None", "skills":"None","availabletime":"None","mobilenumber":"none","email":"none"}
elif value.lower() in ['no','No','N']:
print('askques-no')
return{"response":"Thank you for your time. Please reach out to recruiter@vsoftconsulting.com with your reference number if you have any questions. Have a great day.", "email_mobile":"","email":"", "mobilenumber":"", "skills":"","availabletime":""}
else:
print("------------None------------")
return {"refferals":None}
def validate_availabletime(self,value:Text,dispatcher: CollectingDispatcher,tracker: Tracker,domain: Dict[Text, Any],) -> Dict[Text, Any]:
print("VALUE")
print(value)
print("OUT")
try:
print("tracker.events ", type(tracker.events))
print("tracker.events ", tracker.events)
trackerEvents = tracker.events
print()
for eachDict in trackerEvents:
if 'name' in eachDict:
if eachDict['name'] == 'time':
timeentity=eachDict['value']
#timeentity=tracker.events[-1]['parse_data']['entities'][0]['value']
matchedDate = datetime.strptime(timeentity, "%Y-%m-%dT%H:%M:%S.000-06:00").strftime('%Y-%m-%d %H:%M:%S')
print("matchedDate",matchedDate)
# Since both the fields are populated, the form
# will no longer prompt the user separately for the end_date
print("Validate available time try")
if validate_date(matchedDate):
print("Validate available time if")
if validate_available_date(matchedDate):
finalDate = datetime.strptime(matchedDate, "%Y-%m-%d %H:%M:%S").strftime('%m/%d/%y %I:%M %p')
print("Validate available time if")
return {"availabletime":finalDate,"response":"Thank you. We’ll have a recruiter reach out to you at that time. Please feel free to update your resume at http://app.vsoftconsulting.com/aistaffingprod/uploadresume.html Or if you have any questions please mail to recruiter@vsoftconsulting.com with your reference number"}
else:
print("Validate office available time else")
dispatcher.utter_message(template="utter_wrong_office_hours")
return {'availabletime':None}
else:
print("Validate available time else")
dispatcher.utter_message(template="utter_wrong_availabletime")
return {'availabletime':None}
except Exception as timeException:
print("Validate available time except",timeException)
print(tracker.latest_message)
dispatcher.utter_message(template="utter_wrong_availabletime")
return {'availabletime':None}
def slot_mappings(self) -> Dict[Text, Union[Dict, List[Dict]]]: def slot_mappings(self) -> Dict[Text, Union[Dict, List[Dict]]]:
# print("type of self from text",type(self.from_text()))
# print("self from text",self.from_text())
return { return {
"askques": self.from_text(), "askques": [self.from_intent(intent=["affirm"],value="yes"),self.from_intent(intent=["deny"],value="no"),self.from_text()],
"email_mobile": self.from_text(),
"email": self.from_text(), "email": self.from_text(),
"mobilenumber": self.from_text(), "mobilenumber": self.from_text(),
"company": self.from_text(),
"experience": self.from_text(),
"skills": self.from_text(), "skills": self.from_text(),
"availabletime": self.from_text() "availabletime": self.from_text(),
"refferals":[self.from_intent(intent=["affirm"],value="yes"),self.from_intent(intent=["deny"],value="no"),self.from_text()],
} }
def submit( def submit(
...@@ -104,18 +221,18 @@ class Primary_information(FormAction): ...@@ -104,18 +221,18 @@ class Primary_information(FormAction):
dispatcher: CollectingDispatcher, dispatcher: CollectingDispatcher,
tracker: Tracker, tracker: Tracker,
domain: Dict[Text, Any]) ->List[Dict]: domain: Dict[Text, Any]) ->List[Dict]:
if tracker.get_slot("querytext") != "no": if tracker.get_slot("querytext") != "stop":
return [] return []
else: else:
dispatcher.utter_template('utter_slots_datetime', tracker) dispatcher.utter_template('utter_stop', tracker)
return [] return []
class ResetSlot(Action): class ResetSlot(Action):
def name(self): def name(self):
return "action_reset" return "action_reset"
def run(self, dispatcher, tracker, domain): def run(self, dispatcher, tracker, domain):
return [SlotSet("email", None), SlotSet("querytext","empty"),SlotSet("intentname","empty"),SlotSet("confidence",None),SlotSet("mobilenumber",None),SlotSet("experience",None), SlotSet("skills",None), SlotSet("askques",None),SlotSet("availabletime",None)] return [SlotSet("email_mobile", None),SlotSet("email", None),SlotSet("mobilenumber", None),SlotSet("refferals", None),SlotSet("intentname","empty"),SlotSet("confidence",None), SlotSet("skills",None), SlotSet("askques",None),SlotSet("availabletime",None),SlotSet("querytext","empty")]
#SlotSet("copeup","empty"),SlotSet("sources","empty"), SlotSet("concern","empty"),SlotSet("pressingconcerns","empty"),SlotSet("items","empty"),SlotSet("purchase","empty"),SlotSet("fmembers","empty"),SlotSet("socialmedia","empty"),SlotSet("assistance","empty"),SlotSet("mobilenumber","empty"),
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or sign in to comment