GOATS/reguly.ipynb

12 KiB

from convlab.base_models.t5.nlu import T5NLU
import requests


def translate_text(text, target_language='en'):
    url = 'https://translate.googleapis.com/translate_a/single?client=gtx&sl=auto&tl={}&dt=t&q={}'.format(
        target_language, text)
    response = requests.get(url)
    if response.status_code == 200:
        translated_text = response.json()[0][0][0]
        return translated_text
    else:
        return None


class NaturalLanguageAnalyzer: 
    def predict(self, text, context=None):
        # Inicjalizacja modelu NLU
        model_name = "ConvLab/t5-small-nlu-multiwoz21"
        nlu_model = T5NLU(speaker='user', context_window_size=0, model_name_or_path=model_name)

        # Automatyczne tłumaczenie na język angielski
        translated_input = translate_text(text)

        # Wygenerowanie odpowiedzi z modelu NLU
        nlu_output = nlu_model.predict(translated_input)

        return nlu_output

    def init_session(self):
        # Inicjalizacja sesji (jeśli konieczne)
        pass
from convlab.util.multiwoz.state import default_state
default_state()
{'user_action': [],
 'system_action': [],
 'belief_state': {'attraction': {'type': '', 'name': '', 'area': ''},
  'hotel': {'name': '',
   'area': '',
   'parking': '',
   'price range': '',
   'stars': '4',
   'internet': 'yes',
   'type': 'hotel',
   'book stay': '',
   'book day': '',
   'book people': ''},
  'restaurant': {'food': '',
   'price range': '',
   'name': '',
   'area': '',
   'book time': '',
   'book day': '',
   'book people': ''},
  'taxi': {'leave at': '',
   'destination': '',
   'departure': '',
   'arrive by': ''},
  'train': {'leave at': '',
   'destination': '',
   'day': '',
   'arrive by': '',
   'departure': '',
   'book people': ''},
  'hospital': {'department': ''}},
 'booked': {},
 'request_state': {},
 'terminated': False,
 'history': []}
import json
import os
from convlab.dst.dst import DST
from convlab.dst.rule.multiwoz.dst_util import normalize_value

class SimpleRuleDST(DST):
    def __init__(self):
        DST.__init__(self)
        self.state = default_state()
        self.value_dict = json.load(open('value_dict.json'))

    def update(self, user_act=None):
        for intent, domain, slot, value in user_act:
            domain = domain.lower()
            intent = intent.lower()
            slot = slot.lower()
            
            if domain not in self.state['belief_state']:
                continue

            if intent == 'inform':
                if slot == 'none' or slot == '':
                    continue

                domain_dic = self.state['belief_state'][domain]

                if slot in domain_dic:
                    nvalue = normalize_value(self.value_dict, domain, slot, value)
                    self.state['belief_state'][domain][slot] = nvalue

            elif intent == 'request':
                if domain not in self.state['request_state']:
                    self.state['request_state'][domain] = {}
                if slot not in self.state['request_state'][domain]:
                    self.state['request_state'][domain][slot] = 0

        return self.state

    def init_session(self):
        self.state = default_state()
dst = SimpleRuleDST()
dst.state
dst.update([['Inform', 'Hotel', 'Price Range', 'cheap'], ['Inform', 'Hotel', 'Parking', 'yes']])
dst.state['belief_state']['hotel']
{'name': '',
 'area': '',
 'parking': 'yes',
 'price range': 'cheap',
 'stars': '4',
 'internet': 'yes',
 'type': 'hotel',
 'book stay': '',
 'book day': '',
 'book people': ''}
from collections import defaultdict
import copy
import json
from copy import deepcopy

from convlab.policy.policy import Policy
from convlab.util.multiwoz.dbquery import Database


class SimpleRulePolicy(Policy):
    def __init__(self):
        Policy.__init__(self)
        self.db = Database()

    def predict(self, state):
        self.results = []
        system_action = defaultdict(list)
        user_action = defaultdict(list)

        for intent, domain, slot, value in state['user_action']:
            user_action[(domain.lower(), intent.lower())].append((slot.lower(), value))

        for user_act in user_action:
            self.update_system_action(user_act, user_action, state, system_action)

        # Reguła 3
        if any(True for slots in user_action.values() for (slot, _) in slots if slot in ['book stay', 'book day', 'book people']):
            if self.results:
                system_action = {('Booking', 'Book'): [["Ref", self.results[0].get('Ref', 'N/A')]]}

        system_acts = [[intent, domain, slot, value] for (domain, intent), slots in system_action.items() for slot, value in slots]
        state['system_action'] = system_acts
        return system_acts

    def update_system_action(self, user_act, user_action, state, system_action):
        domain, intent = user_act
        constraints = [(slot, value) for slot, value in state['belief_state'][domain.lower()].items() if value != '']
        self.results = deepcopy(self.db.query(domain.lower(), constraints))

        # Reguła 1
        if intent == 'request':
            if len(self.results) == 0:
                system_action[(domain, 'NoOffer')] = []
            else:
                for slot in user_action[user_act]:                  
                    if slot[0] in self.results[0]:
                        system_action[(domain, 'Inform')].append([slot[0], self.results[0].get(slot[0], 'unknown')])

        # Reguła 2
        elif intent == 'inform':
            if len(self.results) == 0:
                system_action[(domain, 'NoOffer')] = []
            else:
                system_action[(domain, 'Inform')].append(['Choice', str(len(self.results))])
                choice = self.results[0]

                if domain in ["hotel", "attraction", "police", "restaurant"]:
                    system_action[(domain, 'Recommend')].append(['Name', choice['name']])
from convlab.dialog_agent import PipelineAgent
dst.init_session()
policy = SimpleRulePolicy()
agent = PipelineAgent(nlu=None, dst=dst, policy=policy, nlg=None, name='sys')
WARNING:root:nlu info_dict is not initialized
WARNING:root:dst info_dict is not initialized
WARNING:root:policy info_dict is not initialized
WARNING:root:nlg info_dict is not initialized
agent.response([['Inform', 'Hotel', 'Price Range', 'cheap'], ['Inform', 'Hotel', 'Parking', 'yes']])
[['Inform', 'hotel', 'Choice', '3'],
 ['Recommend', 'hotel', 'Name', 'huntingdon marriott hotel']]
from convlab.base_models.t5.nlu import T5NLU
from convlab.nlg.template.multiwoz import TemplateNLG

# nlu =  T5NLU(speaker='user', context_window_size=0, model_name_or_path='ConvLab/t5-small-nlu-multiwoz21')
nlu = NaturalLanguageAnalyzer()
nlg = TemplateNLG(is_user=False)
agent = PipelineAgent(nlu=nlu, dst=dst, policy=policy, nlg=nlg, name='sys')
WARNING:root:nlu info_dict is not initialized
WARNING:root:dst info_dict is not initialized
WARNING:root:policy info_dict is not initialized
WARNING:root:nlg info_dict is not initialized
NLG seed 0
agent.response("I need a cheap hotel with free parking .")
'We have 3 such places . Would huntingdon marriott hotel work for you ?'