Poprawki do systemu, złożenie wszystkich modułów w całość

This commit is contained in:
s495727 2024-06-13 15:25:52 +02:00
parent 41f41cc692
commit 10fc617cad
9 changed files with 598 additions and 500 deletions

View File

@ -1,39 +1,40 @@
{ {
"size": ["M", "L", "XL"],
"dough": [ "dough": [
"thick" "thick"
], ],
"drink": { "drink": {
"woda": {
"price": 5
},
"pepsi": { "pepsi": {
"price": 10 "price": 7
}, },
"cola": { "cola": {
"price": 10 "price": 8
},
"water": {
"price": 5
} }
}, },
"food": [ "food": [
"pizza" "pizza"
], ],
"meat": [ "meat": [
"chicken", "kurczak",
"ham", "szynka",
"tuna" "tuna"
], ],
"sauce": [ "sauce": [
"garlic", "garlic",
"1000w" "1000w"
], ],
"ingredient": { "ingredients": {
"chicken": {}, "kurczak": {},
"tuna": {}, "tuna": {},
"pineapple": {}, "ananas": {},
"onion": {}, "cebula": {},
"cheese": {}, "ser": {},
"tomato": {}, "pomidor": {},
"ham": {}, "szynka": {},
"pepper": {} "papryka": {}
}, },
"menu": [ "menu": [
"capri", "capri",

View File

@ -1,50 +1,56 @@
from service.dialog_state_monitor import DialogStateMonitor from service.dialog_state_monitor import DialogStateMonitor
from service.dialog_policy import DialogPolicy from service.dialog_policy import DialogPolicy
from service.natural_languag_understanding import NaturalLanguageUnderstanding from service.natural_languag_understanding import NaturalLanguageUnderstanding
from service.natural_language_generation import NaturalLanguageGeneration, parse_frame from service.natural_language_generation import NaturalLanguageGeneration, parse_frame
from service.templates import templates from service.templates import templates
# initialize classes # initialize classes
nlu = NaturalLanguageUnderstanding(use_mocks=False) # NLU nlu = NaturalLanguageUnderstanding(use_mocks=False) # NLU
monitor = DialogStateMonitor() # DSM monitor = DialogStateMonitor() # DSM
dialog_policy = DialogPolicy() # DP dialog_policy = DialogPolicy() # DP
language_generation = NaturalLanguageGeneration(templates) # NLG language_generation = NaturalLanguageGeneration(templates) # NLG
def frame_to_dict(frame): def frame_to_dict(frame):
return { return {
"act": frame.act, "act": frame.act,
"slots": [{"name": slot.name, "value": slot.value} for slot in frame.slots] "slots": [{"name": slot.name, "value": slot.value} for slot in frame.slots],
} "act_understood": frame.act_understood,
}
# Main loop
dial_num = 0 # Main loop
print("CTRL+C aby zakończyć program.") dial_num = 0
while True: print("CTRL+C aby zakończyć program.")
monitor.reset() while True:
monitor.reset()
# print(f"\n==== Rozpoczynasz rozmowę nr {dial_num} ====\n")
user_input = input("Witamy w naszej pizzerii. W czym mogę pomóc?\n") print(f"\n==== Rozpoczynasz rozmowę nr {dial_num} ====\n")
user_input = input("Witamy w naszej pizza-przez-internet. W czym mogę pomóc?\n")
while True:
# NLU while True:
frame = nlu.predict(user_input) # NLU
print("Frame: ", frame) frame = nlu.predict(user_input)
print("Frame: ", frame)
# DSM
monitor.update(frame) # DSM
monitor.update(frame)
# DP
system_action = dialog_policy.predict(monitor) # DP
system_action = frame_to_dict(system_action) # Ensure system_action is a dictionary system_action = dialog_policy.predict(monitor)
print("System action: ", system_action) system_action_dict = frame_to_dict(system_action) # Ensure system_action is a dictionary
print("System action: ", system_action_dict)
# NLG
response = language_generation.generate(frame, system_action) # NLG
print(response) response = language_generation.generate(frame, system_action_dict)
print(response)
if frame.act == "bye":
break if system_action.act == "bye_and_thanks" or system_action.act == "bye":
print(monitor.print_order())
user_input = input(">\n") break
# dial_num += 1
if frame.act == "bye":
print(monitor.print_order())
break
user_input = input(">\n")
dial_num += 1

View File

@ -1,10 +1,11 @@
from .slot import Slot from .slot import Slot
class Frame: class Frame:
def __init__(self, source: str, act: str, slots: list[Slot] = []): def __init__(self, source: str, act: str, slots: list[Slot] = [], act_understood = None):
self.source = source self.source = source
self.slots = slots self.slots = slots
self.act = act self.act = act
self.act_understood = act_understood
def __str__(self): def __str__(self):
msg = f"Act: {self.act}, Slots: [" msg = f"Act: {self.act}, Slots: ["

View File

@ -3,26 +3,37 @@ from model.frame import Frame
from model.slot import Slot from model.slot import Slot
class DialogPolicy: class DialogPolicy:
def _predict(self, dsm):
def predict(self, dsm):
last_frame = dsm.state['history'][-1] last_frame = dsm.state['history'][-1]
act_processed = dsm.state['was_system_act_processed']
if(dsm.state['was_previous_order_invalid'] == False): if(dsm.state['was_previous_order_invalid'] == False):
if("inform" in last_frame.act): if last_frame.act == "inform/order-complete":
act = last_frame.act
elif ("inform" in last_frame.act):
act = last_frame.act.split('/')[0] act = last_frame.act.split('/')[0]
else: else:
act = last_frame.act act = last_frame.act
match(act): match(act):
case "bye":
return Frame(source="system", act = "bye")
case "inform/order-complete":
return Frame(source="system", act = "bye_and_thanks")
case "inform" | "affirm" | "negate": case "inform" | "affirm" | "negate":
current_active_status = dsm.get_current_active_stage() current_active_stage = dsm.get_current_active_stage()
match(current_active_status): if current_active_stage == None:
return Frame(source="system", act = "bye_and_thanks")
match(current_active_stage['name']):
case "collect_food": case "collect_food":
return Frame(source="system", act = "request/food") # current_active_stage['confirmed'] = True
return Frame(source="system", act = "request/food", slots = [Slot("menu", dsm.state['constants']['menu'])], act_understood=act_processed)
case "collect_drinks": case "collect_drinks":
return Frame(source="system", act = "request/drinks") return Frame(source="system", act = "request/drinks", slots = [Slot("drink", dsm.state['constants']['drink'])], act_understood=act_processed)
case "collect_address": case "collect_address":
return Frame(source="system", act = "request/address") return Frame(source="system", act = "request/address", act_understood=act_processed)
if(current_active_status == None): case "collect_payment_method":
return Frame(source="system", act = "end") return Frame(source="system", act = "request/payment-method", act_understood=act_processed)
case "collect_phone":
return Frame(source="system", act = "request/phone", act_understood=act_processed)
case "request/menu": case "request/menu":
return Frame(source="system", act = "inform", slots = [Slot("menu", dsm.state['constants']['menu'])]) return Frame(source="system", act = "inform", slots = [Slot("menu", dsm.state['constants']['menu'])])
case "request/price": case "request/price":
@ -41,7 +52,12 @@ class DialogPolicy:
return Frame(source="system", act = "inform", slots = [Slot("drink", dsm.state['constants']['drink'])]) return Frame(source="system", act = "inform", slots = [Slot("drink", dsm.state['constants']['drink'])])
case "welcomemsg": case "welcomemsg":
return Frame(source="system", act = "inform", slots = [Slot("menu", dsm.state['constants']['menu'])]) return Frame(source="system", act = "inform", slots = [Slot("menu", dsm.state['constants']['menu'])])
case "bye": case "repeat":
return Frame(source="system", act = "bye") return Frame(source="system", act = "repeat")
return Frame(source="system", act = "repeat") return Frame(source="system", act = "repeat")
def predict(self, dsm):
frame = self._predict(dsm)
dsm.state["system_history"].append(frame)
return frame

View File

@ -1,11 +1,19 @@
from src.model.frame import Frame from model.frame import Frame
import copy import copy
import json import json
def normalize(value): def normalize(value):
value = value.lower() value = value.lower()
# TODO: pomyslec nad odmianą slów if value[-1] in [",", "!", "?" ,"." ,")" ,"(",")"]:
value = value[:-1]
if value[-2:] == "ie":
value = value[:-2] + "a"
if value[-1] in ["ę", "ą", "y"]:
value = value[:-1] + "a"
if value in ["pizz", "pizzy", "pizze", "picce"]:
value = "pizza"
return ' '.join(value.split()) return ' '.join(value.split())
@ -13,37 +21,71 @@ class DialogStateMonitor:
def __init__(self, initial_state_file: str = 'attributes.json'): def __init__(self, initial_state_file: str = 'attributes.json'):
with open(initial_state_file) as file: with open(initial_state_file) as file:
constants = json.load(file) constants = json.load(file)
self.__initial_state = dict(belief_state={ self.__initial_state = dict(
'order': [], belief_state={
'address': {}, 'order': [],
'order-complete': False, 'address': {},
'phone': {}, 'order-complete': False,
'delivery': {}, 'phone': {},
'payment': {}, 'delivery': {},
'time': {}, 'payment': {},
'name': {}, 'time': {},
}, 'name': {},
},
total_cost=0, total_cost=0,
stages=[ stages=[
{'completed': False, 'name': 'collect_food'}, {'completed': False, 'name': 'collect_food', "confirmed": False},
{'completed': False, 'name': 'collect_drinks'}, {'completed': False, 'name': 'collect_drinks', "confirmed": False},
{'completed': False, 'name': 'collect_address'}, {'completed': False, 'name': 'collect_address', "confirmed": False},
{'completed': False, 'name': 'collect_phone', "confirmed": False},
], ],
was_previous_order_invalid=False, was_previous_order_invalid=False,
was_system_act_processed=False,
constants=constants, constants=constants,
history=[]) history=[],
system_history=[]
)
self.state = copy.deepcopy(self.__initial_state) self.state = copy.deepcopy(self.__initial_state)
def get_current_active_stage(self) -> str | None: def get_current_active_stage(self) -> str | None:
for stage in self.state['stages']: for stage in self.state['stages']:
if stage['completed'] is False: if stage['completed'] is False:
return stage['name'] print("Current stage: ", stage['name'])
return stage
self.state['belief_state']['order-complete'] = True
def mark_current_stage_completed(self) -> None: def mark_current_stage_completed(self) -> None:
for stage in self.state['stages']: for stage in self.state['stages']:
if stage['completed'] is False: if stage['completed'] is False: # and stage['confirmed']:
print("Stage completed: ", stage['name'])
stage['completed'] = True stage['completed'] = True
return return
def complete_stage_if_valid(self, stage_name):
for stage in self.state['stages']:
if stage['name'] != stage_name:
continue
if stage['name'] == "collect_food":
for order in self.state['belief_state']['order']:
if order.get("pizza"):
stage['completed'] = True
return
elif stage["name"] == "collect_drinks":
for order in self.state['belief_state']['order']:
if order.get("drink"):
stage['completed'] = True
return
elif stage["name"] == "collect_address":
if not len(self.state['belief_state']['address']):
return
stage['completed'] = True
return
elif stage["name"] == "collect_phone":
if self.state['belief_state']["phone"].get("phone"):
stage['completed'] = True
return
pass
def item_exists(self, type: str, name: str) -> bool: def item_exists(self, type: str, name: str) -> bool:
return normalize(name) in self.state['constants'][type] return normalize(name) in self.state['constants'][type]
@ -53,8 +95,30 @@ class DialogStateMonitor:
def get_total_cost(self) -> int: def get_total_cost(self) -> int:
return self.state['total_cost'] return self.state['total_cost']
def slot_augmentation(self, slot, value):
drink_normalize = ["woda", "pepsi", "cola", "coca cola", "cole", "coca"]
if slot.name in ["food", "pizza", "ingredient"]:
if value in drink_normalize:
slot.name = 'drink'
return slot
def slot_valid(self, slot, act):
if act == "inform/order":
if slot.name in ["address", "payment-method", 'delivery', 'phone', 'time', 'name']:
return False
return True
def value_valid(self, slot_name, value):
if slot_name == "food":
if value != "pizza":
return False
return True
def update(self, frame: Frame) -> None: def update(self, frame: Frame) -> None:
self.state['was_system_act_processed'] = False
belief_state_copy = copy.deepcopy(self.state["belief_state"])
self.state['history'].append(frame) self.state['history'].append(frame)
if frame.source != 'user': if frame.source != 'user':
return return
@ -62,27 +126,40 @@ class DialogStateMonitor:
new_order = dict() new_order = dict()
for slot in frame.slots: for slot in frame.slots:
value = normalize(slot.value) value = normalize(slot.value)
if (slot.name == 'pizza' and self.get_current_active_stage() == 'collect_food') or (slot.name == 'drink' and self.get_current_active_stage() == 'collect_drinks'): slot = self.slot_augmentation(slot, value)
if not self.slot_valid(slot, frame.act):
continue
if not self.value_valid(slot.name, value):
continue
stage_name = self.get_current_active_stage()['name']
is_collect_food = (slot.name == 'pizza' and stage_name == 'collect_food')
is_collect_drinks = (slot.name == 'drink' and stage_name == 'collect_drinks')
if is_collect_food or is_collect_drinks:
if self.item_exists(slot.name, value) is False: if self.item_exists(slot.name, value) is False:
self.state['was_previous_order_invalid'] = True self.state['was_previous_order_invalid'] = True
return return
self.state['was_previous_order_invalid'] = False self.state['was_previous_order_invalid'] = False
self.state['total_cost'] += self.state['constants'][slot.name][value]['price'] self.state['total_cost'] += self.state['constants'][slot.name][value]['price']
self.mark_current_stage_completed()
new_order[slot.name] = value new_order[slot.name] = value
self.state['belief_state']['order'].append(new_order) if len(new_order) > 0:
elif frame.act == 'inform/address' and self.get_current_active_stage() == 'collect_address': self.state['belief_state']['order'].append(new_order)
self.complete_stage_if_valid('collect_food')
self.complete_stage_if_valid('collect_drinks')
elif frame.act == 'inform/address':
for slot in frame.slots: for slot in frame.slots:
self.state['belief_state']['address'][slot.name] = normalize(slot.value) self.state['belief_state']['address'][slot.name] = normalize(slot.value)
self.mark_current_stage_completed() self.complete_stage_if_valid('collect_address')
elif frame.act == 'inform/phone': elif frame.act == 'inform/phone':
for slot in frame.slots: for slot in frame.slots:
self.state['belief_state']['phone'][slot.name] = normalize(slot.value) self.state['belief_state']['phone'][slot.name] = normalize(slot.value)
self.complete_stage_if_valid('collect_phone')
elif frame.act == 'inform/order-complete': elif frame.act == 'inform/order-complete':
self.state['belief_state']['order-complete'] = True self.state['belief_state']['order-complete'] = True
elif frame.act == 'inform/delivery': elif frame.act == 'inform/delivery':
for slot in frame.slots: for slot in frame.slots:
self.state['belief_state']['delivery'][slot.name] = normalize(slot.value) self.state['belief_state']['delivery'][slot.name] = normalize(slot.value)
self.complete_stage_if_valid('collect_address')
elif frame.act == 'inform/payment': elif frame.act == 'inform/payment':
for slot in frame.slots: for slot in frame.slots:
self.state['belief_state']['payment'][slot.name] = normalize(slot.value) self.state['belief_state']['payment'][slot.name] = normalize(slot.value)
@ -92,6 +169,16 @@ class DialogStateMonitor:
elif frame.act == 'inform/name': elif frame.act == 'inform/name':
for slot in frame.slots: for slot in frame.slots:
self.state['belief_state']['name'][slot.name] = normalize(slot.value) self.state['belief_state']['name'][slot.name] = normalize(slot.value)
elif frame.act == 'negate':
if "request" in self.state["system_history"][-1].act:
self.mark_current_stage_completed()
self.state['was_system_act_processed'] = True
if self.state["belief_state"] != belief_state_copy and frame.act not in ["repeat", 'affirm', 'negate']:
self.state['was_system_act_processed'] = True
def reset(self) -> None: def reset(self) -> None:
self.state = copy.deepcopy(self.__initial_state) self.state = copy.deepcopy(self.__initial_state)
def print_order(self) -> dict:
return json.dumps(self.state['belief_state'])

View File

@ -91,10 +91,13 @@ class NaturalLanguageUnderstanding():
def predict(self, text: str): def predict(self, text: str):
if not self.use_mocks: if not self.use_mocks:
act = self.__predict_intention(text) try:
slots = self.__predict_slot(text) act = self.__predict_intention(text)
frame = Frame(source = 'user', act = act, slots = slots) slots = self.__predict_slot(text)
return frame frame = Frame(source = 'user', act = act, slots = slots)
return frame
except:
return Frame(source="user", act = "repeat", slots=[])
else: else:
frames = [ frames = [
Frame(source="user", act = "inform/order", slots=[Slot(name="pizza", value="barcelona")]), Frame(source="user", act = "inform/order", slots=[Slot(name="pizza", value="barcelona")]),

View File

@ -27,6 +27,10 @@ class NaturalLanguageGeneration:
slot_dict[slot['name']] = slot['value'] slot_dict[slot['name']] = slot['value']
response = template.format(**slot_dict) response = template.format(**slot_dict)
if system_action['act_understood'] == True:
response = f"Zrozumiałem. {response}"
elif system_action['act_understood'] == False:
response = f"Nie zrozumiałem. {response}"
return response return response
def parse_frame(frame): def parse_frame(frame):
@ -37,14 +41,3 @@ def parse_frame(frame):
slots = [{"name": slot.name, "value": slot.value} for slot in frame.slots] slots = [{"name": slot.name, "value": slot.value} for slot in frame.slots]
return act, slots return act, slots
class Slot:
def __init__(self, name, value):
self.name = name
self.value = value
class Frame:
def __init__(self, act, slots):
self.act = act
self.slots = slots

View File

@ -1,203 +1,208 @@
import random import random
from service.templates import templates from service.templates import templates
def generate_pizza_info(slots): def generate_pizza_info(slots):
pizza_name = None pizza_name = None
query_type = None query_type = None
for slot in slots: for slot in slots:
if slot['name'] == 'pizza': if slot['name'] == 'pizza':
pizza_name = slot['value'].lower() pizza_name = slot['value'].lower()
elif slot['name'] == 'ingredient': elif slot['name'] == 'ingredient':
query_type = 'ingredient' query_type = 'ingredient'
elif slot['name'] == 'price': elif slot['name'] == 'price':
query_type = 'price' query_type = 'price'
if pizza_name not in pizza_data: if pizza_name not in pizza_data:
return f"Nie mamy w ofercie pizzy o nazwie {pizza_name}." return f"Nie mamy w ofercie pizzy o nazwie {pizza_name}."
if query_type == 'ingredient': if query_type == 'ingredient':
ingredients = pizza_data[pizza_name]['ingredient'] ingredients = pizza_data[pizza_name]['ingredient']
return f"Składniki pizzy {pizza_name} to: {', '.join(ingredients)}." return f"Składniki pizzy {pizza_name} to: {', '.join(ingredients)}."
elif query_type == 'price': elif query_type == 'price':
price = pizza_data[pizza_name]['price'] price = pizza_data[pizza_name]['price']
return f"Cena pizzy {pizza_name} to {price} zł." return f"Cena pizzy {pizza_name} to {price} zł."
return f"Informacje o pizzy {pizza_name}: składniki to {', '.join(pizza_data[pizza_name]['ingredient'])}, cena to {pizza_data[pizza_name]['price']} zł." return f"Informacje o pizzy {pizza_name}: składniki to {', '.join(pizza_data[pizza_name]['ingredient'])}, cena to {pizza_data[pizza_name]['price']} zł."
def generate_ingredients_response(slots): def generate_ingredients_response(slots):
ingredients = [slot['value'] for slot in slots if slot['name'] == 'ingredients'] ingredients = [slot['value'] for slot in slots if slot['name'] == 'ingredients']
if ingredients: if ingredients:
ingredient_list = [] ingredient_list = []
for ingredient in ingredients: for ingredient in ingredients:
ingredient_list.extend(ingredient.keys()) ingredient_list.extend(ingredient.keys())
response = f"Składniki to: {', '.join(ingredient_list)}." response = f"Dostępne składniki to: {', '.join(ingredient_list)}."
return response return response
return "Nie podano składników." return "Nie podano składników."
def generate_drinks_response(slots): def generate_drinks_response(slots):
drinks = [slot['value'] for slot in slots if slot['name'] == 'drink'] drinks = [slot['value'] for slot in slots if slot['name'] == 'drink']
if drinks: print(slots)
drink_details = [] print(drinks)
for drink in drinks: if drinks:
for name, details in drink.items(): drink_details = []
price = details.get('price', 'unknown') for drink in drinks:
drink_details.append(f"{name} w cenie {price}") for name, details in drink.items():
if len(drink_details) > 1: # price = details.get('price', 'unknown')
response = f"Dostępne napoje to: {', '.join(drink_details[:-1])} oraz {drink_details[-1]}." drink_details.append(f"{name}") # w cenie {price} zł")
else: if len(drink_details) > 1:
response = f"Dostępne napoje to: {drink_details[0]}." response = f"Czy chcesz coś do picia? Dostępne napoje to: {', '.join(drink_details[:-1])} oraz {drink_details[-1]}."
return response else:
return "Nie podano napojów." response = f"Czy chcesz coś do picia? Dostępne napoje to: {drink_details[0]}."
return response
def generate_size_response(slots): return "Nie podano napojów."
sizes = [slot['value'] for slot in slots if slot['name'] == 'size']
if sizes: def generate_size_response(slots):
size_details = [] sizes = [slot['value'] for slot in slots if slot['name'] == 'size'][0]
for size in sizes: if len(sizes) != 0:
for name, details in size.items(): return F"Dostępne rozmiary to: {', '.join(sizes)}"
rozmiar = details.get('rozmiar', 'unknown') return "Nie podano rozmiarów."
size_details.append(f"{name} o średnicy {rozmiar} cm")
if len(size_details) > 1: def generate_sauce_response(slots):
response = f"Dostępne rozmiary to: {', '.join(size_details[:-1])} oraz {size_details[-1]}." sauces = [slot['value'] for slot in slots if slot['name'] == 'sauce']
else: if sauces:
response = f"Dostępne rozmiary to: {size_details[0]}." sauce_list = []
return response for sauce in sauces:
return "Nie podano rozmiarów." if isinstance(sauce, list):
sauce_list.extend(sauce)
def generate_sauce_response(slots): else:
sauces = [slot['value'] for slot in slots if slot['name'] == 'sauce'] sauce_list.append(sauce)
if sauces: return f"Dostępne sosy to: {', '.join(sauce_list)}."
sauce_list = [] return "Nie podano sosów."
for sauce in sauces:
if isinstance(sauce, list):
sauce_list.extend(sauce) def select_template(act, slots):
else: slot_names = {slot['name'] for slot in slots}
sauce_list.append(sauce)
return f"Dostępne sosy to: {', '.join(sauce_list)}." if act == "welcomemsg":
return "Nie podano sosów." return random.choice(templates["welcomemsg"])
if "ingredients" in slot_names:
def select_template(act, slots): return generate_ingredients_response(slots)
slot_names = {slot['name'] for slot in slots} elif "drink" in slot_names:
return generate_drinks_response(slots)
if act == "welcomemsg": elif "sauce" in slot_names:
return random.choice(templates["welcomemsg"]) return generate_sauce_response(slots)
elif "size" in slot_names:
if "ingredients" in slot_names: return generate_size_response(slots)
return generate_ingredients_response(slots) elif "price" in slot_names:
elif "drink" in slot_names: return random.choice(templates["inform/price"])
return generate_drinks_response(slots) elif "food" in slot_names:
elif "sauce" in slot_names: return random.choice(templates["inform/menu"])
return generate_sauce_response(slots)
elif "size" in slot_names: if act == "inform":
return generate_size_response(slots) if "menu" in slot_names:
elif "price" in slot_names: return random.choice(templates["inform/menu"])
return random.choice(templates["inform/price"]) elif "address" in slot_names:
return random.choice(templates["inform/address"])
if act == "inform": elif "phone" in slot_names:
if "menu" in slot_names: return random.choice(templates["inform/phone"])
return random.choice(templates["inform/menu"]) elif "order-complete" in slot_names:
elif "address" in slot_names: return random.choice(templates["inform/order-complete"])
return random.choice(templates["inform/address"]) elif "delivery" in slot_names:
elif "phone" in slot_names: return random.choice(templates["inform/delivery"])
return random.choice(templates["inform/phone"]) elif "payment" in slot_names:
elif "order-complete" in slot_names: return random.choice(templates["inform/payment"])
return random.choice(templates["inform/order-complete"]) elif "time" in slot_names:
elif "delivery" in slot_names: return random.choice(templates["inform/time"])
return random.choice(templates["inform/delivery"]) elif "name" in slot_names:
elif "payment" in slot_names: return random.choice(templates["inform/name"])
return random.choice(templates["inform/payment"]) elif "price" in slot_names and "pizza" in slot_names:
elif "time" in slot_names: return generate_pizza_info(slots)
return random.choice(templates["inform/time"]) elif act == "inform/order":
elif "name" in slot_names: if "quantity" in slot_names and "pizza" in slot_names and "size" in slot_names:
return random.choice(templates["inform/name"]) return templates["inform/order"][1]
elif "price" in slot_names and "pizza" in slot_names: elif "quantity" in slot_names and "pizza" in slot_names:
return generate_pizza_info(slots) return templates["inform/order"][2]
elif act == "inform/order": elif "quantity" in slot_names and "food" in slot_names:
if "quantity" in slot_names and "pizza" in slot_names and "size" in slot_names: return templates["inform/order"][0]
return templates["inform/order"][1] elif "food" in slot_names and "pizza" in slot_names and "price" in slot_names:
elif "quantity" in slot_names and "pizza" in slot_names: return templates["inform/order"][5]
return templates["inform/order"][2] elif "quantity" in slot_names:
elif "quantity" in slot_names and "food" in slot_names: return templates["inform/order"][3]
return templates["inform/order"][0] else:
elif "food" in slot_names and "pizza" in slot_names and "price" in slot_names: return templates["inform/order"][4]
return templates["inform/order"][5] elif act == "request/menu":
elif "quantity" in slot_names: return random.choice(templates["request/menu"])
return templates["inform/order"][3] elif act == "inform/address":
else: return random.choice(templates["inform/address"])
return templates["inform/order"][4] elif act == "request/price":
elif act == "request/menu": return random.choice(templates["request/price"])
return random.choice(templates["request/menu"]) elif act == "inform/menu":
elif act == "inform/address": return random.choice(templates["inform/menu"])
return random.choice(templates["inform/address"]) elif act == "request/ingredients":
elif act == "request/price": return random.choice(templates["request/ingredients"])
return random.choice(templates["request/price"]) elif act == "request/sauce":
elif act == "inform/menu": return random.choice(templates["request/sauce"])
return random.choice(templates["inform/menu"]) elif act == "inform/phone":
elif act == "request/ingredients": return random.choice(templates["inform/phone"])
return random.choice(templates["request/ingredients"]) elif act == "inform/order-complete":
elif act == "request/sauce": return random.choice(templates["inform/order-complete"])
return random.choice(templates["request/sauce"]) elif act == "request/time":
elif act == "inform/phone": return random.choice(templates["request/time"])
return random.choice(templates["inform/phone"]) elif act == "request/size":
elif act == "inform/order-complete": return random.choice(templates["request/size"])
return random.choice(templates["inform/order-complete"]) elif act == "inform/delivery":
elif act == "request/time": return random.choice(templates["inform/delivery"])
return random.choice(templates["request/time"]) elif act == "inform/payment":
elif act == "request/size": return random.choice(templates["inform/payment"])
return random.choice(templates["request/size"]) elif act == "request/delivery-price":
elif act == "inform/delivery": return random.choice(templates["request/delivery-price"])
return random.choice(templates["inform/delivery"]) elif act == "inform/time":
elif act == "inform/payment": return random.choice(templates["inform/time"])
return random.choice(templates["inform/payment"]) elif act == "request/drinks":
elif act == "request/delivery-price": return random.choice(templates["request/drinks"])
return random.choice(templates["request/delivery-price"]) elif act == "request/food":
elif act == "inform/time": return random.choice(templates["inform/menu"])
return random.choice(templates["inform/time"]) elif act == "inform/name":
elif act == "request/drinks": return random.choice(templates["inform/name"])
return random.choice(templates["request/drinks"]) elif act == "bye":
elif act == "request/food": return random.choice(templates["bye"]) # TODO force end?
return random.choice(templates["request/food"]) elif act == "bye_and_thanks":
elif act == "inform/name": return random.choice(templates["bye_and_thanks"])
return random.choice(templates["inform/name"]) elif act == "repeat":
elif act == "bye": return random.choice(templates["repeat"])
return random.choice(templates["bye"]) elif act == "request/address":
return random.choice(templates["request/address"])
return None elif act == "request/payment-method":
return random.choice(templates["request/payment-method"])
elif act == "request/phone":
# def select_template(act, slots): return random.choice(templates["request/phone"])
# slot_names = {slot['name'] for slot in slots}
return None
# if act == "welcomemsg":
# return random.choice(templates["welcomemsg"])
# if act == "request/menu": # def select_template(act, slots):
# return random.choice(templates["request/menu"]) # slot_names = {slot['name'] for slot in slots}
# if act == "inform/address":
# return random.choice(templates["inform/address"]) # if act == "welcomemsg":
# if act == "inform/delivery": # return random.choice(templates["welcomemsg"])
# return random.choice(templates["inform/delivery"]) # if act == "request/menu":
# if act == "inform/payment": # return random.choice(templates["request/menu"])
# return random.choice(templates["inform/payment"]) # if act == "inform/address":
# if act == "affirm": # return random.choice(templates["inform/address"])
# return random.choice(templates["affirm"]) # if act == "inform/delivery":
# if act == "request/drinks": # return random.choice(templates["inform/delivery"])
# return random.choice(templates["request/drinks"]) # if act == "inform/payment":
# if act == "bye": # return random.choice(templates["inform/payment"])
# return random.choice(templates["bye"]) # if act == "affirm":
# if act == "inform/order": # return random.choice(templates["affirm"])
# if "quantity" in slot_names and "food" in slot_names and "pizza" in slot_names: # if act == "request/drinks":
# return templates["inform/order"][1] # return random.choice(templates["request/drinks"])
# elif "quantity" in slot_names and "pizza" in slot_names: # if act == "bye":
# return templates["inform/order"][4] # return random.choice(templates["bye"])
# elif "food" in slot_names and "pizza" in slot_names: # if act == "inform/order":
# return templates["inform/order"][2] # if "quantity" in slot_names and "food" in slot_names and "pizza" in slot_names:
# elif "quantity" in slot_names: # return templates["inform/order"][1]
# return templates["inform/order"][3] # elif "quantity" in slot_names and "pizza" in slot_names:
# else: # return templates["inform/order"][4]
# return templates["inform/order"][4] # elif "food" in slot_names and "pizza" in slot_names:
# return templates["inform/order"][2]
# return "default/template" # elif "quantity" in slot_names:
# return templates["inform/order"][3]
# else:
# return templates["inform/order"][4]
# return "default/template"

View File

@ -1,180 +1,166 @@
templates = { templates = {
"inform/order": [ "inform/order": [
"Zamówiłeś {quantity} x {food}.", "Zamówiłeś {quantity} x {food}.",
"Twoje zamówienie to {quantity} x {food} {pizza}.", "Twoje zamówienie to {quantity} x {food} {pizza}.",
"Mmmm... {food} {pizza} to rewelacyjny wybór. Czy chcesz coś do picia?", "Mmmm... {food} {pizza} to rewelacyjny wybór. Czy chcesz coś do picia?",
"Dziękujemy za zamówienie {quantity} x {food}.", "Dziękujemy za zamówienie {quantity} x {food}.",
"Na jaką pizzę masz ochotę?" "Na jaką pizzę masz ochotę?"
], ],
"inform/menu": [ "inform/menu": [
"Oferujemy następujące pizze: {menu}.", "Oferujemy następujące pizze: {menu}.",
"Nasze pizze to: {menu}.", ],
"W naszym menu znajdziesz pizze: {menu}.", "inform/name": [
"Dostępne pizze to: {menu}.", "Twoje imię to {name}.",
"Proszę, oto lista dostępnych pizz: {menu}." "Podane imię: {name}.",
], "Twoje imię: {name}.",
"inform/name": [ "Masz na imię {name}.",
"Twoje imię to {name}.", "Imię: {name}."
"Podane imię: {name}.", ],
"Twoje imię: {name}.", "inform/price": [
"Masz na imię {name}.", "Cena wybranej pizzy to {price} zł.",
"Imię: {name}." "Koszt pizzy to {price} zł.",
], "Wybrana pizza kosztuje {price} zł.",
"inform/price": [ "Cena pizzy wynosi {price} zł."
"Cena wybranej pizzy to {price} zł.", ],
"Koszt pizzy to {price} zł.", "inform/address": [
"Wybrana pizza kosztuje {price} zł.", "Twój adres to: {address}.",
"Cena pizzy wynosi {price} zł." "Adres, który podałeś, to: {address}.",
], "Dostawa na adres: {address}.",
"inform/address": [ "Dostarczymy na adres: {address}.",
"Twój adres to: {address}.", "Twój podany adres to: {address}."
"Adres, który podałeś, to: {address}.", ],
"Dostawa na adres: {address}.", "inform/sauce": [
"Dostarczymy na adres: {address}.", "Dostępne sosy to: {sauce}.",
"Twój podany adres to: {address}." "Możesz wybrać spośród następujących sosów: {sauce}.",
], "Oferujemy następujące sosy: {sauce}."
"inform/sauce": [ ],
"Dostępne sosy to: {sauce}.", "inform/phone": [
"Możesz wybrać spośród następujących sosów: {sauce}.", "Twój numer telefonu to: {phone}.",
"Oferujemy następujące sosy: {sauce}." "Podany numer telefonu: {phone}.",
], "Numer telefonu, który podałeś, to: {phone}.",
"inform/phone": [ "Twoje dane kontaktowe: {phone}.",
"Twój numer telefonu to: {phone}.", "Telefon kontaktowy: {phone}."
"Podany numer telefonu: {phone}.", ],
"Numer telefonu, który podałeś, to: {phone}.", "inform/order-complete": [
"Twoje dane kontaktowe: {phone}.", "Twoje zamówienie zostało zrealizowane. Dziękujemy!",
"Telefon kontaktowy: {phone}." "Zamówienie zakończone. Dziękujemy za zakupy!",
], "Zamówienie zrealizowane. Czekaj na dostawę!",
"inform/order-complete": [ "Twoje zamówienie jest gotowe. Dziękujemy!",
"Twoje zamówienie zostało zrealizowane. Dziękujemy!", "Realizacja zamówienia zakończona. Dziękujemy!"
"Zamówienie zakończone. Dziękujemy za zakupy!", ],
"Zamówienie zrealizowane. Czekaj na dostawę!", "inform/delivery": [
"Twoje zamówienie jest gotowe. Dziękujemy!", "Twoje zamówienie zostanie dostarczone na {address}.",
"Realizacja zamówienia zakończona. Dziękujemy!" "Dostarczymy zamówienie na adres: {address}.",
], "Dostawa na adres: {address}.",
"inform/delivery": [ "Twoje zamówienie jedzie na {address}.",
"Twoje zamówienie zostanie dostarczone na {address}.", "Adres dostawy: {address}."
"Dostarczymy zamówienie na adres: {address}.", ],
"Dostawa na adres: {address}.", "inform/address": [
"Twoje zamówienie jedzie na {address}.", "Twoje zamówienie zostanie dostarczone na adres: {address}.",
"Adres dostawy: {address}." "Dostawa będzie na adres: {address}.",
], "Adres dostawy: {address}."
"inform/address": [ ],
"Twoje zamówienie zostanie dostarczone na adres: {address}.", "inform/payment": [
"Dostawa będzie na adres: {address}.", "Metoda płatności to: {payment-method}.",
"Adres dostawy: {address}." "Płatność realizujesz przez: {payment-method}.",
], "Wybrałeś metodę płatności: {payment-method}.",
"inform/payment": [ "Płatność: {payment-method}.",
"Metoda płatności to: {payment-method}.", "Możesz zapłacić kartą, gotówką lub blikiem"
"Płatność realizujesz przez: {payment-method}.", ],
"Wybrałeś metodę płatności: {payment-method}.", "affirm": [
"Płatność: {payment-method}.", "Świetnie! Napisz co Ci chodzi po głowie.",
"Możesz zapłacić kartą, gotówką lub blikiem" "Dobrze! Co dalej?",
], "OK! Co chciałbyś zamówić?",
"affirm": [ "Super! Co dalej?",
"Świetnie! Napisz co Ci chodzi po głowie.", "Dobrze! Jakie dalsze zamówienia?"
"Dobrze! Co dalej?", ],
"OK! Co chciałbyś zamówić?", "request/delivery-price": [
"Super! Co dalej?", "Koszt dostawy wynosi {delivery-price} zł.",
"Dobrze! Jakie dalsze zamówienia?" "Cena dostawy to {delivery-price} zł.",
], "Za dostawę zapłacisz {delivery-price} zł.",
"request/delivery-price": [ "Dostawa kosztuje {delivery-price} zł.",
"Koszt dostawy wynosi {delivery-price} zł.", "Koszt dostawy: {delivery-price} zł."
"Cena dostawy to {delivery-price} zł.", ],
"Za dostawę zapłacisz {delivery-price} zł.", "request/menu": [
"Dostawa kosztuje {delivery-price} zł.", "W naszym menu znajdziesz: {menu}."
"Koszt dostawy: {delivery-price} zł." ],
], "inform/time": [
"request/menu": [ "Aktualny czas to {time}.",
"Oto nasze menu: {menu}.", "Jest teraz {time}.",
"Nasze menu obejmuje: {menu}.", "Czas: {time}.",
"Proszę, oto lista dostępnych dań: {menu}.", "Godzina: {time}.",
"Dostępne dania to: {menu}.", "Obecny czas: {time}."
"W naszym menu znajdziesz: {menu}." ],
], "welcomemsg": [
"inform/time": [ "Witaj w naszej wspaniałej pizzerii. W czym mogę pomóc?",
"Aktualny czas to {time}.", "Halo, halo, tu najlepsza pizza w mieście. Masz głoda?",
"Jest teraz {time}.", "Dzieńdoberek, gdyby wszyscy jedli nasze pizze, na świecie nie byłoby wojen. Jaką pizzę sobie dziś gruchniesz?",
"Czas: {time}.", ],
"Godzina: {time}.", "request/price": [
"Obecny czas: {time}." "Cena za {food} wynosi {price} zł.",
], "Koszt {food} to {price} zł.",
"request/drinks": [ "Cena {pizza} o rozmiarze {size} wynosi {price} zł.",
"Jakie napoje chciałbyś zamówić?", "Za {quantity} x {pizza} zapłacisz {price} zł.",
"Proszę wybrać napoje do zamówienia.", "Koszt {food} to {price} zł."
"Jakie napoje dołączamy do zamówienia?", ],
"Co chciałbyś pić?", "request/ingredients": [
"Proszę podać napoje do zamówienia." "Nasza {food} {pizza} składa się z ciasta, sosu pomidorowego, sera i innych dodatków.",
], "W {pizza} znajdziesz: {ingredients}.",
"welcomemsg": [ "{pizza} zawiera: {ingredients}.",
"Witaj w naszej wspaniałej pizzerii. W czym mogę pomóc?", "W skład {pizza} wchodzi: {ingredients}.",
"Halo, halo, tu najlepsza pizza w mieście. Masz głoda?", "Na {pizza} składają się: {ingredients}."
"Dzieńdoberek, gdyby wszyscy jedli nasze pizze, na świecie nie byłoby wojen. Jaką pizzę sobie dziś gruchniesz?", ],
], "request/sauce": [
"request/menu": [ "Jakie sosy chciałbyś do {food}?",
"W naszym menu znajdują się pizze, spaghetti, gnocci oraz aranchini. Polecam potrawkę śląską po grecku.", "Proszę wybrać sosy do {food}.",
"Smażymy, gotujemy, prażymy, ale najlepiej nam wychodzi pizza. Na co masz ochotę?", "Jakie sosy zamawiasz do {food}?",
], "Które sosy mają być do {food}?",
"request/drink": [ "Wybierz sosy do {food}."
"Oferujemy napoje zimne, ciepłe i letnie. Cola, fanta, woda mineralna, kawa, herbata lub frappe.", ],
"Może z alkoholem? Mamy świeżo warzone piwo", "request/food": [
], "Co chciałbyś zamówić?",
"request/price": [ "Proszę podać na jaką pizzę masz ochotę",
"Cena za {food} wynosi {price} zł.", "Którą pizzę wybrałeś?"
"Koszt {food} to {price} zł.", ],
"Cena {pizza} o rozmiarze {size} wynosi {price} zł.", "request/time": [
"Za {quantity} x {pizza} zapłacisz {price} zł.", "Oczekiwany czas dostawy to {time} minut.",
"Koszt {food} to {price} zł." "Dostawa zajmie około {time} minut.",
], "Czas dostawy to około {time} minut.",
"request/ingredients": [ "Przewidywany czas dostawy to {time} minut.",
"Nasza {food} {pizza} składa się z ciasta, sosu pomidorowego, sera i innych dodatków.", "Twoje zamówienie dotrze w {time} minut."
"W {pizza} znajdziesz: {ingredients}.", ],
"{pizza} zawiera: {ingredients}.", "request/size": [
"W skład {pizza} wchodzi: {ingredients}.", "Jaką wielkość {pizza} preferujesz? Mamy {sizes}.",
"Na {pizza} składają się: {ingredients}." "Dostępne rozmiary {pizza} to {sizes}.",
], "Jaką wielkość {pizza} chciałbyś zamówić? {sizes}.",
"request/sauce": [ "Proszę wybrać rozmiar {pizza}: {sizes}.",
"Jakie sosy chciałbyś do {food}?", "Mamy następujące rozmiary {pizza}: {sizes}."
"Proszę wybrać sosy do {food}.", ],
"Jakie sosy zamawiasz do {food}?", "bye": [
"Które sosy mają być do {food}?", "Dziękujemy i do zobaczenia wkrótce.",
"Wybierz sosy do {food}." "Polecamy się na przyszłość. Do zobaczenia!",
], "Do widzenia.",
"request/food": [ ],
"Co chciałbyś zamówić?", "negate": [
"Proszę podać na jaką pizzę masz ochotę", "Przepraszam, nie mamy {ingredient/neg} w ofercie.",
"Którą pizzę wybrałeś?" "Niestety, {ingredient/neg} jest niedostępne.",
], "Nie posiadamy {ingredient/neg} w menu.",
"request/time": [ "Brak {ingredient/neg} w naszej ofercie.",
"Oczekiwany czas dostawy to {time} minut.", "Niestety, nie mamy {ingredient/neg}."
"Dostawa zajmie około {time} minut.", ],
"Czas dostawy to około {time} minut.", "default/template": [
"Przewidywany czas dostawy to {time} minut.", "Nie zrozumiałem, spróbuj inaczej sformułować zdanie."
"Twoje zamówienie dotrze w {time} minut." ],
], "repeat": [
"request/size": [ "Nie zrozumiałem, spróbuj inaczej sformułować zdanie.",
"Jaką wielkość {pizza} preferujesz? Mamy {sizes}.", ],
"Dostępne rozmiary {pizza} to {sizes}.", "request/address": [
"Jaką wielkość {pizza} chciałbyś zamówić? {sizes}.", "Jaki adres dostawy?"
"Proszę wybrać rozmiar {pizza}: {sizes}.", ],
"Mamy następujące rozmiary {pizza}: {sizes}." "bye_and_thanks": [
], "Dziękujemy za zamówienie. Do zobaczenia!",
"bye": [ ],
"Dziękujemy i do zobaczenia wkrótce.", "request/phone": [
"Polecamy się na przyszłość. Do zobaczenia!", "Podaj proszę numer telefonu do kontaktu dla kuriera."
"Do widzenia.", ]
], }
"negate": [
"Przepraszam, nie mamy {ingredient/neg} w ofercie.",
"Niestety, {ingredient/neg} jest niedostępne.",
"Nie posiadamy {ingredient/neg} w menu.",
"Brak {ingredient/neg} w naszej ofercie.",
"Niestety, nie mamy {ingredient/neg}."
],
"default/template": [
"Przepraszamy, ale nie rozumiemy Twojego zapytania.",
"Proszę spróbować ponownie później.",
"Nie rozpoznajemy Twojej prośby, spróbuj ponownie.",
"Strasznie szybko to napisałeś, nie zrozumiałem...."
]
}