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
from rasa_sdk.events import SlotSet
import re
from twilio.rest import Client
from datetime import datetime
import time, os
os.environ['TZ'] = 'US/Central'
time.tzset()
account_sid = "ACc460d692e5a467c60b352714b1416140"
auth_token = "bf2a890f36e3329b52d0516a14097623"
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})"
class ActionSendSms(Action):
def name(self) -> Text:
return "action_send_sms"
import re
async def run(
self,
dispatcher: CollectingDispatcher,
tracker: Tracker,
domain: Dict[Text, Any],
) -> List[Dict[Text, Any]]:
#extracting email from user entered text
def ExtractEmail(slot_to_fill):
email_addresse_list = re.findall('\S+@\S+', slot_to_fill)
return email_addresse_list
for each_event in tracker.events[::-1]:
if each_event['event'] == 'user':
#print(tracker.events[-1]['parse_data']['intent']['name'])
if each_event['parse_data']['intent']['name'] == "send_sms":
querytext = each_event['text']
intentname = "send_sms"
confidence = each_event['parse_data']['intent']['confidence']
print(querytext)
pattern = re.compile(regex_phone)
data = pattern.search(querytext)
if data is not None:
phone_no = data.group()
client.messages.create(
to = phone_no,
from_= "+19169995105",
body= "Hi. This is VERA from V-Soft consulting. We may have great job opportunities based on your profile. Are you interested ? "
)
dispatcher.utter_template('utter_sms', tracker)
return []
class Primary_information(FormAction):
print('in Primary_information')
#extracting mobile from user enterd text
def ExtractMobilenumber(slot_to_fill):
#phone number extraction
#regex = re.compile("\+?\d[\( -]?\d{3}[\) -]?\d{3}[ -]?\d{2}[ -]?\d{2}")
regex = re.compile("\d{3}[-\.\s]??\d{3}[-\.\s]??\d{4}|\(\d{3}\)\s*\d{3}[-\.\s]??\d{4}|\d{3}[-\.\s]??\d{4}")
mobile_numbers_list = re.findall(regex, slot_to_fill)
return mobile_numbers_list
def validate_available_date(date_text):
try:
timestamp = int(datetime.strptime(date_text, '%Y-%m-%d %H:%M:%S').strftime("%s"))
new_date_text = datetime.fromtimestamp(timestamp)
print("new_date_text",new_date_text)
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"]
dayNumber = int(new_date_text.strftime('%w')) #To check weekend or weekday
print("daynumber",dayNumber)
dateCheck = new_date_text.strftime('%Y-%m-%d') #To check for public holidays
print("dateCheck",dateCheck)
timeCheck = new_date_text.strftime('%-H') #To check for office hours
print("timeCheck",timeCheck)
date_format = "%Y-%m-%d %H:%M:%S"
# create datetime objects from the strings
givenDate = datetime.strptime(date_text, date_format)
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:
return "primary_information_form"
return "greet_primary_information_form"
@staticmethod
def required_slots(tracker: Tracker) -> List[Text]:
intent = tracker.latest_message.get("intent", {}).get("name")
conf = tracker.latest_message.get("intent", {}).get("confidence")
print('querytext',tracker.slots["querytext"])
print('intent',intent)
print('conf',conf)
#if intent == "affirm" :
if intent != "deny" :
print("IN from deny")
#tracker.slots["querytext"] = "no"
return["intentname","confidence","querytext","askques", "email", "mobilenumber", "company","experience", "skills","availabletime"]
print('tracker.slots',tracker.slots)
print("INTENT")
if intent == "stop" and conf>0.8:
print("INSTOP")
tracker.slots["querytext"] = "stop"
return["querytext"]
else:
print("IN from deny1")
tracker.slots["querytext"] = "no"
return["availabletime"]
return["intentname","confidence","querytext" ,"askques","refferals","skills", "email_mobile","email", "mobilenumber", "availabletime","response"]
def validate_querytext(self,value:Text,dispatcher: CollectingDispatcher,tracker: Tracker,domain: Dict[Text, Any],) -> Dict[Text, Any]:
print("------------------------")
#print(tracker.events)
#print(tracker.events)
for each_event in tracker.events[::-1]:
print('1111111')
print("each_event['event']", each_event['event'])
if each_event['event'] == 'user':
print('2222')
print('intent name', tracker.events[-1]['parse_data']['intent']['name'])
if each_event['parse_data']['intent']['name'] == "affirm":
print('33333')
#print(tracker.events[-1]['parse_data']['intent']['name'])
if each_event['parse_data']['intent']['name'] == "greet":
querytext = each_event['text']
intentname = "affirm"
intentname = "greet"
confidence = each_event['parse_data']['intent']['confidence']
print(querytext)
break
print('44444444')
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]]]:
# print("type of self from text",type(self.from_text()))
# print("self from text",self.from_text())
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(),
"mobilenumber": self.from_text(),
"company": self.from_text(),
"experience": 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(
......@@ -104,18 +221,18 @@ class Primary_information(FormAction):
dispatcher: CollectingDispatcher,
tracker: Tracker,
domain: Dict[Text, Any]) ->List[Dict]:
if tracker.get_slot("querytext") != "no":
if tracker.get_slot("querytext") != "stop":
return []
else:
dispatcher.utter_template('utter_slots_datetime', tracker)
dispatcher.utter_template('utter_stop', tracker)
return []
class ResetSlot(Action):
def name(self):
return "action_reset"
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)]
#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"),
def run(self, dispatcher, tracker, domain):
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")]
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