Ejemplo n.º 1
0
    def _test_pipeline(
        self, nlp
    ):  # override the default test method to check that the output is a `Conversation` object
        self.assertIsNotNone(nlp)

        # We need to recreate conversation for successive tests to pass as
        # Conversation objects get *consumed* by the pipeline
        conversation = Conversation("Hi there!")
        mono_result = nlp(conversation)
        self.assertIsInstance(mono_result, Conversation)

        conversations = [
            Conversation("Hi there!"),
            Conversation("How are you?")
        ]
        multi_result = nlp(conversations)
        self.assertIsInstance(multi_result, list)
        self.assertIsInstance(multi_result[0], Conversation)
        # Conversation have been consumed and are not valid anymore
        # Inactive conversations passed to the pipeline raise a ValueError
        self.assertRaises(ValueError, nlp, conversation)
        self.assertRaises(ValueError, nlp, conversations)

        for bad_input in self.invalid_inputs:
            self.assertRaises(Exception, nlp, bad_input)
        self.assertRaises(Exception, nlp, self.invalid_inputs)
    def test_from_pipeline_conversation(self):
        model_id = "facebook/blenderbot_small-90M"

        # from model id
        conversation_agent_from_model_id = pipeline("conversational",
                                                    model=model_id,
                                                    tokenizer=model_id)

        # from model object
        model = BlenderbotSmallForConditionalGeneration.from_pretrained(
            model_id)
        tokenizer = BlenderbotSmallTokenizer.from_pretrained(model_id)
        conversation_agent_from_model = pipeline("conversational",
                                                 model=model,
                                                 tokenizer=tokenizer)

        conversation = Conversation("My name is Sarah and I live in London")
        conversation_copy = Conversation(
            "My name is Sarah and I live in London")

        result_model_id = conversation_agent_from_model_id([conversation])
        result_model = conversation_agent_from_model([conversation_copy])

        # check for equality
        self.assertEqual(
            result_model_id.generated_responses[0],
            "hi sarah, i live in london as well. do you have any plans for the weekend?",
        )
        self.assertEqual(
            result_model_id.generated_responses[0],
            result_model.generated_responses[0],
        )
Ejemplo n.º 3
0
 def test_integration_torch_conversation(self):
     # When
     nlp = pipeline(task="conversational", device=DEFAULT_DEVICE_NUM)
     conversation_1 = Conversation(
         "Going to the movies tonight - any suggestions?")
     conversation_2 = Conversation("What's the last book you have read?")
     # Then
     self.assertEqual(len(conversation_1.past_user_inputs), 0)
     self.assertEqual(len(conversation_2.past_user_inputs), 0)
     # When
     result = nlp([conversation_1, conversation_2],
                  do_sample=False,
                  max_length=1000)
     # Then
     self.assertEqual(result, [conversation_1, conversation_2])
     self.assertEqual(len(result[0].past_user_inputs), 1)
     self.assertEqual(len(result[1].past_user_inputs), 1)
     self.assertEqual(len(result[0].generated_responses), 1)
     self.assertEqual(len(result[1].generated_responses), 1)
     self.assertEqual(result[0].past_user_inputs[0],
                      "Going to the movies tonight - any suggestions?")
     self.assertEqual(result[0].generated_responses[0], "The Big Lebowski")
     self.assertEqual(result[1].past_user_inputs[0],
                      "What's the last book you have read?")
     self.assertEqual(result[1].generated_responses[0], "The Last Question")
     # When
     conversation_2.add_user_input("Why do you recommend it?")
     result = nlp(conversation_2, do_sample=False, max_length=1000)
     # Then
     self.assertEqual(result, conversation_2)
     self.assertEqual(len(result.past_user_inputs), 2)
     self.assertEqual(len(result.generated_responses), 2)
     self.assertEqual(result.past_user_inputs[1],
                      "Why do you recommend it?")
     self.assertEqual(result.generated_responses[1], "It's a good book.")
Ejemplo n.º 4
0
    def test_integration_torch_conversation_dialogpt_input_ids(self):
        tokenizer = AutoTokenizer.from_pretrained("microsoft/DialoGPT-small")
        model = AutoModelForCausalLM.from_pretrained(
            "microsoft/DialoGPT-small")
        nlp = ConversationalPipeline(model=model, tokenizer=tokenizer)

        conversation_1 = Conversation("hello")
        inputs = nlp._parse_and_tokenize([conversation_1])
        self.assertEqual(inputs["input_ids"].tolist(), [[31373, 50256]])

        conversation_2 = Conversation("how are you ?",
                                      past_user_inputs=["hello"],
                                      generated_responses=["Hi there!"])
        inputs = nlp._parse_and_tokenize([conversation_2])
        self.assertEqual(
            inputs["input_ids"].tolist(),
            [[31373, 50256, 17250, 612, 0, 50256, 4919, 389, 345, 5633, 50256]
             ])

        inputs = nlp._parse_and_tokenize([conversation_1, conversation_2])
        self.assertEqual(
            inputs["input_ids"].tolist(),
            [
                [
                    31373, 50256, 50256, 50256, 50256, 50256, 50256, 50256,
                    50256, 50256, 50256
                ],
                [
                    31373, 50256, 17250, 612, 0, 50256, 4919, 389, 345, 5633,
                    50256
                ],
            ],
        )
Ejemplo n.º 5
0
 def test_integration_torch_conversation_truncated_history(self):
     # When
     nlp = pipeline(task="conversational",
                    min_length_for_response=24,
                    device=DEFAULT_DEVICE_NUM)
     conversation_1 = Conversation(
         "Going to the movies tonight - any suggestions?")
     # Then
     self.assertEqual(len(conversation_1.past_user_inputs), 0)
     # When
     result = nlp(conversation_1, do_sample=False, max_length=36)
     # Then
     self.assertEqual(result, conversation_1)
     self.assertEqual(len(result.past_user_inputs), 1)
     self.assertEqual(len(result.generated_responses), 1)
     self.assertEqual(result.past_user_inputs[0],
                      "Going to the movies tonight - any suggestions?")
     self.assertEqual(result.generated_responses[0], "The Big Lebowski")
     # When
     conversation_1.add_user_input("Is it an action movie?")
     result = nlp(conversation_1, do_sample=False, max_length=36)
     # Then
     self.assertEqual(result, conversation_1)
     self.assertEqual(len(result.past_user_inputs), 2)
     self.assertEqual(len(result.generated_responses), 2)
     self.assertEqual(result.past_user_inputs[1], "Is it an action movie?")
     self.assertEqual(result.generated_responses[1], "It's a comedy.")
Ejemplo n.º 6
0
    def test_integration_torch_conversation_blenderbot_400M(self):
        tokenizer = AutoTokenizer.from_pretrained(
            "facebook/blenderbot-400M-distill")
        model = AutoModelForSeq2SeqLM.from_pretrained(
            "facebook/blenderbot-400M-distill")
        nlp = ConversationalPipeline(model=model, tokenizer=tokenizer)

        conversation_1 = Conversation("hello")
        result = nlp(conversation_1, )
        self.assertEqual(
            result.generated_responses[0],
            # ParlAI implementation output, we have a different one, but it's our
            # second best, you can check by using num_return_sequences=10
            # " Hello! How are you? I'm just getting ready to go to work, how about you?",
            " Hello! How are you doing today? I just got back from a walk with my dog.",
        )

        conversation_1 = Conversation("Lasagne   hello")
        result = nlp(conversation_1, encoder_no_repeat_ngram_size=3)
        self.assertEqual(
            result.generated_responses[0],
            " Do you like lasagne? It is a traditional Italian dish consisting of a shepherd's pie.",
        )

        conversation_1 = Conversation(
            "Lasagne   hello   Lasagne is my favorite Italian dish. Do you like lasagne?   I like lasagne."
        )
        result = nlp(
            conversation_1,
            encoder_no_repeat_ngram_size=3,
        )
        self.assertEqual(
            result.generated_responses[0],
            " Me too. I like how it can be topped with vegetables, meats, and condiments.",
        )
Ejemplo n.º 7
0
 def test_small_model_tf(self):
     tokenizer = AutoTokenizer.from_pretrained("microsoft/DialoGPT-small")
     model = TFAutoModelForCausalLM.from_pretrained("microsoft/DialoGPT-small")
     conversation_agent = ConversationalPipeline(model=model, tokenizer=tokenizer)
     conversation = Conversation("hello")
     output = conversation_agent(conversation)
     self.assertEqual(output, Conversation(past_user_inputs=["hello"], generated_responses=["Hi"]))
Ejemplo n.º 8
0
def convOneLine():
    conv1_start = "Let's watch a movie tonight - any recommendations?"
    conv2_start = "What's your favorite book?"

    conv1 = Conversation(conv1_start)
    conv2 = Conversation(conv2_start)

    conversational_pipeline([conv1, conv2])
    print(conv1)
    print(conv2)
Ejemplo n.º 9
0
def customConversation():

    customConv_input = input(">> ")

    customConv = Conversation(customConv_input)

    conversational_pipeline([customConv])

    while customConv_input != "bye":
        print(customConv)

        customConv_input = input(">> ")
        customConv.add_user_input(customConv_input)
        conversational_pipeline([customConv])
Ejemplo n.º 10
0
    def test_integration_torch_conversation_encoder_decoder(self):
        # When
        tokenizer = AutoTokenizer.from_pretrained(
            "facebook/blenderbot_small-90M")
        model = AutoModelForSeq2SeqLM.from_pretrained(
            "facebook/blenderbot_small-90M")
        nlp = ConversationalPipeline(model=model,
                                     tokenizer=tokenizer,
                                     device=DEFAULT_DEVICE_NUM)

        conversation_1 = Conversation("My name is Sarah and I live in London")
        conversation_2 = Conversation(
            "Going to the movies tonight, What movie would you recommend? ")
        # Then
        self.assertEqual(len(conversation_1.past_user_inputs), 0)
        self.assertEqual(len(conversation_2.past_user_inputs), 0)
        # When
        result = nlp([conversation_1, conversation_2],
                     do_sample=False,
                     max_length=1000)
        # Then
        self.assertEqual(result, [conversation_1, conversation_2])
        self.assertEqual(len(result[0].past_user_inputs), 1)
        self.assertEqual(len(result[1].past_user_inputs), 1)
        self.assertEqual(len(result[0].generated_responses), 1)
        self.assertEqual(len(result[1].generated_responses), 1)
        self.assertEqual(result[0].past_user_inputs[0],
                         "My name is Sarah and I live in London")
        self.assertEqual(
            result[0].generated_responses[0],
            "hi sarah, i live in london as well. do you have any plans for the weekend?",
        )
        self.assertEqual(
            result[1].past_user_inputs[0],
            "Going to the movies tonight, What movie would you recommend? ")
        self.assertEqual(
            result[1].generated_responses[0],
            "i don't know... i'm not really sure. what movie are you going to see?"
        )
        # When
        conversation_1.add_user_input("Not yet, what about you?")
        conversation_2.add_user_input("What's your name?")
        result = nlp([conversation_1, conversation_2],
                     do_sample=False,
                     max_length=1000)
        # Then
        self.assertEqual(result, [conversation_1, conversation_2])
        self.assertEqual(len(result[0].past_user_inputs), 2)
        self.assertEqual(len(result[1].past_user_inputs), 2)
        self.assertEqual(len(result[0].generated_responses), 2)
        self.assertEqual(len(result[1].generated_responses), 2)
        self.assertEqual(result[0].past_user_inputs[1],
                         "Not yet, what about you?")
        self.assertEqual(
            result[0].generated_responses[1],
            "i don't have any plans yet. i'm not sure what to do yet.")
        self.assertEqual(result[1].past_user_inputs[1], "What's your name?")
        self.assertEqual(
            result[1].generated_responses[1],
            "i don't have a name, but i'm going to see a horror movie.")
Ejemplo n.º 11
0
    def test_integration_torch_conversation(self):
        conversation_agent = self.get_pipeline()
        conversation_1 = Conversation(
            "Going to the movies tonight - any suggestions?")
        conversation_2 = Conversation("What's the last book you have read?")
        self.assertEqual(len(conversation_1.past_user_inputs), 0)
        self.assertEqual(len(conversation_2.past_user_inputs), 0)

        with self.assertLogs("transformers", level="WARNING") as log:
            result = conversation_agent([conversation_1, conversation_2],
                                        max_length=48)
            self.assertEqual(len(log.output), 2)
            self.assertIn(
                "You might consider trimming the early phase of the conversation",
                log.output[0])
            self.assertIn("Setting `pad_token_id`", log.output[1])

        # Two conversations in one pass
        self.assertEqual(result, [conversation_1, conversation_2])
        self.assertEqual(
            result,
            [
                Conversation(
                    None,
                    past_user_inputs=[
                        "Going to the movies tonight - any suggestions?"
                    ],
                    generated_responses=["L"],
                ),
                Conversation(
                    None,
                    past_user_inputs=["What's the last book you have read?"],
                    generated_responses=["L"]),
            ],
        )

        # One conversation with history
        conversation_2.add_user_input("Why do you recommend it?")
        with self.assertLogs("transformers", level="WARNING") as log:
            result = conversation_agent(conversation_2, max_length=64)
            self.assertEqual(len(log.output), 3)
            self.assertIn("Cutting history off because it's too long",
                          log.output[0])
            self.assertIn(
                "You might consider trimming the early phase of the conversation",
                log.output[1])
            self.assertIn("Setting `pad_token_id`", log.output[2])

        self.assertEqual(result, conversation_2)
        self.assertEqual(
            result,
            Conversation(
                None,
                past_user_inputs=[
                    "What's the last book you have read?",
                    "Why do you recommend it?"
                ],
                generated_responses=["L", "L"],
            ),
        )
Ejemplo n.º 12
0
 def test_history_cache(self):
     conversation_agent = self.get_pipeline()
     conversation = Conversation(
         "Why do you recommend it?",
         past_user_inputs=["What's the last book you have read?"],
         generated_responses=["b"],
     )
     with self.assertLogs("transformers", level="WARNING") as log:
         _ = conversation_agent(conversation, max_length=64)
         self.assertEqual(len(log.output), 3)
         self.assertIn(
             "Cutting history off because it's too long (63 > 32) for underlying model",
             log.output[0])
         self.assertIn("63 is bigger than 0.9 * max_length: 64",
                       log.output[1])
         self.assertIn("Setting `pad_token_id`", log.output[2])
     self.assertEqual(conversation._index, 1)
     self.assertEqual(
         conversation._history,
         [
             87,
             104,
             97,
             116,
             39,
             115,
             32,
             116,
             104,
             101,
             32,
             108,
             97,
             115,
             116,
             32,
             98,
             111,
             111,
             107,
             32,
             121,
             111,
             117,
             32,
             104,
             97,
             118,
             101,
             32,
             114,
             101,
             97,
             100,
             63,
             259,  # EOS
             98,  # b
             259,  # EOS
         ],
     )
Ejemplo n.º 13
0
def init_convo(author: str, author_display: str
               ):  # helper function to initialize all new conversations
    new_convo = Conversation(f"Hello! My name is {author_display}")
    new_convo.mark_processed()
    new_convo.append_response(f" Hello! I am a {bot_gender} named {bot_name}")
    conversations[author] = new_convo

    return new_convo
Ejemplo n.º 14
0
    def test_integration_torch_conversation(self):
        conversation_agent = self.get_pipeline()
        conversation_1 = Conversation(
            "Going to the movies tonight - any suggestions?")
        conversation_2 = Conversation("What's the last book you have read?")
        self.assertEqual(len(conversation_1.past_user_inputs), 0)
        self.assertEqual(len(conversation_2.past_user_inputs), 0)

        result = conversation_agent([conversation_1, conversation_2],
                                    max_length=48)

        # Two conversations in one pass
        self.assertEqual(result, [conversation_1, conversation_2])
        self.assertEqual(
            result,
            [
                Conversation(
                    None,
                    past_user_inputs=[
                        "Going to the movies tonight - any suggestions?"
                    ],
                    generated_responses=["L"],
                ),
                Conversation(
                    None,
                    past_user_inputs=["What's the last book you have read?"],
                    generated_responses=["L"]),
            ],
        )

        # One conversation with history
        conversation_2.add_user_input("Why do you recommend it?")
        result = conversation_agent(conversation_2, max_length=64)

        self.assertEqual(result, conversation_2)
        self.assertEqual(
            result,
            Conversation(
                None,
                past_user_inputs=[
                    "What's the last book you have read?",
                    "Why do you recommend it?"
                ],
                generated_responses=["L", "L"],
            ),
        )
Ejemplo n.º 15
0
    BlenderbotTokenizer,
)

if __name__ == "__main__":
    import logging

    logger = logging.getLogger("transformers").setLevel(logging.CRITICAL)

    model = BlenderbotForConditionalGeneration.from_pretrained(
        "facebook/blenderbot-400M-distill")
    tokenizer = BlenderbotTokenizer.from_pretrained(
        "facebook/blenderbot-400M-distill")

    convo = ConversationalPipeline(model=model,
                                   tokenizer=tokenizer,
                                   min_length_for_response=0,
                                   framework="pt")

    ipt = input(">>> ")
    dialogue = Conversation(ipt)
    while True:
        try:
            convo(dialogue, num_beams=3, min_length=0, temperature=1.5)
            print(dialogue.generated_responses[-1][1:])
            dialogue.add_user_input(input(">>> "))
            truncate_convo_to_token_limit(dialogue)
        except KeyboardInterrupt:
            break

    print("\n------Dialogue Summary------")
    print(dialogue)
Ejemplo n.º 16
0
    def test_integration_torch_conversation_blenderbot_400M_input_ids(self):
        tokenizer = AutoTokenizer.from_pretrained(
            "facebook/blenderbot-400M-distill")
        model = AutoModelForSeq2SeqLM.from_pretrained(
            "facebook/blenderbot-400M-distill")
        nlp = ConversationalPipeline(model=model, tokenizer=tokenizer)

        # test1
        conversation_1 = Conversation("hello")
        inputs = nlp._parse_and_tokenize([conversation_1])
        self.assertEqual(inputs["input_ids"].tolist(), [[1710, 86, 2]])

        # test2
        conversation_1 = Conversation(
            "I like lasagne.",
            past_user_inputs=["hello"],
            generated_responses=[
                " Do you like lasagne? It is a traditional Italian dish consisting of a shepherd's pie."
            ],
        )
        inputs = nlp._parse_and_tokenize([conversation_1])
        self.assertEqual(
            inputs["input_ids"].tolist(),
            [
                # This should be compared with the same conversation on ParlAI `safe_interactive` demo.
                [
                    1710,  # hello
                    86,
                    228,  # Double space
                    228,
                    946,
                    304,
                    398,
                    6881,
                    558,
                    964,
                    38,
                    452,
                    315,
                    265,
                    6252,
                    452,
                    322,
                    968,
                    6884,
                    3146,
                    278,
                    306,
                    265,
                    617,
                    87,
                    388,
                    75,
                    341,
                    286,
                    521,
                    21,
                    228,  # Double space
                    228,
                    281,  # I like lasagne.
                    398,
                    6881,
                    558,
                    964,
                    21,
                    2,  # EOS
                ]
            ],
        )
Ejemplo n.º 17
0
def firstConversation(text):
    global customConv
    customConv = Conversation(text)
    conversational_pipeline([customConv])
    return customConv.generated_responses[-1]
Ejemplo n.º 18
0
# if USE_GPU:
#     import tensorflow as tf
#     physical_devices = tf.config.list_physical_devices('GPU')
#     tf.config.experimental.set_memory_growth(physical_devices[0]), True)

from transformers import pipeline, Conversation, GPT2TokenizerFast, GPT2LMHeadModel
tokenizer = GPT2TokenizerFast.from_pretrained("gpt2")
model = GPT2LMHeadModel.from_pretrained("gpt2",
                                        pad_token_id=tokenizer.eos_token_id)
conversational_pipeline = pipeline("conversational")

######vConversationv#######

conv1_start = "Let's watch a movie tonight, any recommendations?"

conv1 = Conversation(conv1_start)

conversational_pipeline([conv1])

conv1_next = "What is it about?"

conv1.add_user_input(conv1_next)

conversational_pipeline([conv1])

while conv1_next != "bye":
    print(conv1)
    conv1_next = input()
    conv1.add_user_input(conv1_next)
    print(conversational_pipeline([conv1]))
Ejemplo n.º 19
0
class TextGenerationPipelineTests(MonoInputPipelineCommonMixin,
                                  unittest.TestCase):
    pipeline_task = "conversational"
    small_models = []  # Models tested without the @slow decorator
    large_models = ["microsoft/DialoGPT-medium"
                    ]  # Models tested with the @slow decorator
    valid_inputs = [
        Conversation("Hi there!"),
        [Conversation("Hi there!"),
         Conversation("How are you?")]
    ]
    invalid_inputs = ["Hi there!", Conversation()]

    def _test_pipeline(
        self, nlp
    ):  # e overide the default test method to check that the output is a `Conversation` object
        self.assertIsNotNone(nlp)

        mono_result = nlp(self.valid_inputs[0])
        self.assertIsInstance(mono_result, Conversation)

        multi_result = nlp(self.valid_inputs[1])
        self.assertIsInstance(multi_result, list)
        self.assertIsInstance(multi_result[0], Conversation)
        # Inactive conversations passed to the pipeline raise a ValueError
        self.assertRaises(ValueError, nlp, self.valid_inputs[1])

        for bad_input in self.invalid_inputs:
            self.assertRaises(Exception, nlp, bad_input)
        self.assertRaises(Exception, nlp, self.invalid_inputs)

    @require_torch
    @slow
    def test_integration_torch_conversation(self):
        # When
        nlp = pipeline(task="conversational", device=DEFAULT_DEVICE_NUM)
        conversation_1 = Conversation(
            "Going to the movies tonight - any suggestions?")
        conversation_2 = Conversation("What's the last book you have read?")
        # Then
        self.assertEqual(len(conversation_1.past_user_inputs), 0)
        self.assertEqual(len(conversation_2.past_user_inputs), 0)
        # When
        result = nlp([conversation_1, conversation_2],
                     do_sample=False,
                     max_length=1000)
        # Then
        self.assertEqual(result, [conversation_1, conversation_2])
        self.assertEqual(len(result[0].past_user_inputs), 1)
        self.assertEqual(len(result[1].past_user_inputs), 1)
        self.assertEqual(len(result[0].generated_responses), 1)
        self.assertEqual(len(result[1].generated_responses), 1)
        self.assertEqual(result[0].past_user_inputs[0],
                         "Going to the movies tonight - any suggestions?")
        self.assertEqual(result[0].generated_responses[0], "The Big Lebowski")
        self.assertEqual(result[1].past_user_inputs[0],
                         "What's the last book you have read?")
        self.assertEqual(result[1].generated_responses[0], "The Last Question")
        # When
        conversation_2.add_user_input("Why do you recommend it?")
        result = nlp(conversation_2, do_sample=False, max_length=1000)
        # Then
        self.assertEqual(result, conversation_2)
        self.assertEqual(len(result.past_user_inputs), 2)
        self.assertEqual(len(result.generated_responses), 2)
        self.assertEqual(result.past_user_inputs[1],
                         "Why do you recommend it?")
        self.assertEqual(result.generated_responses[1], "It's a good book.")

    @require_torch
    @slow
    def test_integration_torch_conversation_truncated_history(self):
        # When
        nlp = pipeline(task="conversational",
                       min_length_for_response=24,
                       device=DEFAULT_DEVICE_NUM)
        conversation_1 = Conversation(
            "Going to the movies tonight - any suggestions?")
        # Then
        self.assertEqual(len(conversation_1.past_user_inputs), 0)
        # When
        result = nlp(conversation_1, do_sample=False, max_length=36)
        # Then
        self.assertEqual(result, conversation_1)
        self.assertEqual(len(result.past_user_inputs), 1)
        self.assertEqual(len(result.generated_responses), 1)
        self.assertEqual(result.past_user_inputs[0],
                         "Going to the movies tonight - any suggestions?")
        self.assertEqual(result.generated_responses[0], "The Big Lebowski")
        # When
        conversation_1.add_user_input("Is it an action movie?")
        result = nlp(conversation_1, do_sample=False, max_length=36)
        # Then
        self.assertEqual(result, conversation_1)
        self.assertEqual(len(result.past_user_inputs), 2)
        self.assertEqual(len(result.generated_responses), 2)
        self.assertEqual(result.past_user_inputs[1], "Is it an action movie?")
        self.assertEqual(result.generated_responses[1], "It's a comedy.")
 def get_test_pipeline(self, model, tokenizer, feature_extractor):
     conversation_agent = ConversationalPipeline(model=model,
                                                 tokenizer=tokenizer)
     return conversation_agent, [Conversation("Hi there!")]
    def run_pipeline_test(self, conversation_agent, _):
        # Simple
        outputs = conversation_agent(Conversation("Hi there!"))
        self.assertEqual(
            outputs,
            Conversation(past_user_inputs=["Hi there!"],
                         generated_responses=[ANY(str)]))

        # Single list
        outputs = conversation_agent([Conversation("Hi there!")])
        self.assertEqual(
            outputs,
            Conversation(past_user_inputs=["Hi there!"],
                         generated_responses=[ANY(str)]))

        # Batch
        conversation_1 = Conversation(
            "Going to the movies tonight - any suggestions?")
        conversation_2 = Conversation("What's the last book you have read?")
        self.assertEqual(len(conversation_1.past_user_inputs), 0)
        self.assertEqual(len(conversation_2.past_user_inputs), 0)

        outputs = conversation_agent([conversation_1, conversation_2])
        self.assertEqual(outputs, [conversation_1, conversation_2])
        self.assertEqual(
            outputs,
            [
                Conversation(
                    past_user_inputs=[
                        "Going to the movies tonight - any suggestions?"
                    ],
                    generated_responses=[ANY(str)],
                ),
                Conversation(
                    past_user_inputs=["What's the last book you have read?"],
                    generated_responses=[ANY(str)]),
            ],
        )

        # One conversation with history
        conversation_2.add_user_input("Why do you recommend it?")
        outputs = conversation_agent(conversation_2)
        self.assertEqual(outputs, conversation_2)
        self.assertEqual(
            outputs,
            Conversation(
                past_user_inputs=[
                    "What's the last book you have read?",
                    "Why do you recommend it?"
                ],
                generated_responses=[ANY(str), ANY(str)],
            ),
        )
        with self.assertRaises(ValueError):
            conversation_agent("Hi there!")
        with self.assertRaises(ValueError):
            conversation_agent(Conversation())
        # Conversation have been consumed and are not valid anymore
        # Inactive conversations passed to the pipeline raise a ValueError
        with self.assertRaises(ValueError):
            conversation_agent(conversation_2)
Ejemplo n.º 22
0
class ConversationalPipelineTests(MonoInputPipelineCommonMixin,
                                  unittest.TestCase):
    pipeline_task = "conversational"
    small_models = []  # Models tested without the @slow decorator
    large_models = ["microsoft/DialoGPT-medium"
                    ]  # Models tested with the @slow decorator
    invalid_inputs = ["Hi there!", Conversation()]

    def _test_pipeline(
        self, nlp
    ):  # override the default test method to check that the output is a `Conversation` object
        self.assertIsNotNone(nlp)

        # We need to recreate conversation for successive tests to pass as
        # Conversation objects get *consumed* by the pipeline
        conversation = Conversation("Hi there!")
        mono_result = nlp(conversation)
        self.assertIsInstance(mono_result, Conversation)

        conversations = [
            Conversation("Hi there!"),
            Conversation("How are you?")
        ]
        multi_result = nlp(conversations)
        self.assertIsInstance(multi_result, list)
        self.assertIsInstance(multi_result[0], Conversation)
        # Conversation have been consumed and are not valid anymore
        # Inactive conversations passed to the pipeline raise a ValueError
        self.assertRaises(ValueError, nlp, conversation)
        self.assertRaises(ValueError, nlp, conversations)

        for bad_input in self.invalid_inputs:
            self.assertRaises(Exception, nlp, bad_input)
        self.assertRaises(Exception, nlp, self.invalid_inputs)

    @require_torch
    @slow
    def test_integration_torch_conversation(self):
        # When
        nlp = pipeline(task="conversational", device=DEFAULT_DEVICE_NUM)
        conversation_1 = Conversation(
            "Going to the movies tonight - any suggestions?")
        conversation_2 = Conversation("What's the last book you have read?")
        # Then
        self.assertEqual(len(conversation_1.past_user_inputs), 0)
        self.assertEqual(len(conversation_2.past_user_inputs), 0)
        # When
        result = nlp([conversation_1, conversation_2],
                     do_sample=False,
                     max_length=1000)
        # Then
        self.assertEqual(result, [conversation_1, conversation_2])
        self.assertEqual(len(result[0].past_user_inputs), 1)
        self.assertEqual(len(result[1].past_user_inputs), 1)
        self.assertEqual(len(result[0].generated_responses), 1)
        self.assertEqual(len(result[1].generated_responses), 1)
        self.assertEqual(result[0].past_user_inputs[0],
                         "Going to the movies tonight - any suggestions?")
        self.assertEqual(result[0].generated_responses[0], "The Big Lebowski")
        self.assertEqual(result[1].past_user_inputs[0],
                         "What's the last book you have read?")
        self.assertEqual(result[1].generated_responses[0], "The Last Question")
        # When
        conversation_2.add_user_input("Why do you recommend it?")
        result = nlp(conversation_2, do_sample=False, max_length=1000)
        # Then
        self.assertEqual(result, conversation_2)
        self.assertEqual(len(result.past_user_inputs), 2)
        self.assertEqual(len(result.generated_responses), 2)
        self.assertEqual(result.past_user_inputs[1],
                         "Why do you recommend it?")
        self.assertEqual(result.generated_responses[1], "It's a good book.")

    @require_torch
    @slow
    def test_integration_torch_conversation_truncated_history(self):
        # When
        nlp = pipeline(task="conversational",
                       min_length_for_response=24,
                       device=DEFAULT_DEVICE_NUM)
        conversation_1 = Conversation(
            "Going to the movies tonight - any suggestions?")
        # Then
        self.assertEqual(len(conversation_1.past_user_inputs), 0)
        # When
        result = nlp(conversation_1, do_sample=False, max_length=36)
        # Then
        self.assertEqual(result, conversation_1)
        self.assertEqual(len(result.past_user_inputs), 1)
        self.assertEqual(len(result.generated_responses), 1)
        self.assertEqual(result.past_user_inputs[0],
                         "Going to the movies tonight - any suggestions?")
        self.assertEqual(result.generated_responses[0], "The Big Lebowski")
        # When
        conversation_1.add_user_input("Is it an action movie?")
        result = nlp(conversation_1, do_sample=False, max_length=36)
        # Then
        self.assertEqual(result, conversation_1)
        self.assertEqual(len(result.past_user_inputs), 2)
        self.assertEqual(len(result.generated_responses), 2)
        self.assertEqual(result.past_user_inputs[1], "Is it an action movie?")
        self.assertEqual(result.generated_responses[1], "It's a comedy.")

    @require_torch
    @slow
    def test_integration_torch_conversation_dialogpt_input_ids(self):
        tokenizer = AutoTokenizer.from_pretrained("microsoft/DialoGPT-small")
        model = AutoModelForCausalLM.from_pretrained(
            "microsoft/DialoGPT-small")
        nlp = ConversationalPipeline(model=model, tokenizer=tokenizer)

        conversation_1 = Conversation("hello")
        inputs = nlp._parse_and_tokenize([conversation_1])
        self.assertEqual(inputs["input_ids"].tolist(), [[31373, 50256]])

        conversation_2 = Conversation("how are you ?",
                                      past_user_inputs=["hello"],
                                      generated_responses=["Hi there!"])
        inputs = nlp._parse_and_tokenize([conversation_2])
        self.assertEqual(
            inputs["input_ids"].tolist(),
            [[31373, 50256, 17250, 612, 0, 50256, 4919, 389, 345, 5633, 50256]
             ])

        inputs = nlp._parse_and_tokenize([conversation_1, conversation_2])
        self.assertEqual(
            inputs["input_ids"].tolist(),
            [
                [
                    31373, 50256, 50256, 50256, 50256, 50256, 50256, 50256,
                    50256, 50256, 50256
                ],
                [
                    31373, 50256, 17250, 612, 0, 50256, 4919, 389, 345, 5633,
                    50256
                ],
            ],
        )

    @require_torch
    @slow
    def test_integration_torch_conversation_blenderbot_400M_input_ids(self):
        tokenizer = AutoTokenizer.from_pretrained(
            "facebook/blenderbot-400M-distill")
        model = AutoModelForSeq2SeqLM.from_pretrained(
            "facebook/blenderbot-400M-distill")
        nlp = ConversationalPipeline(model=model, tokenizer=tokenizer)

        # test1
        conversation_1 = Conversation("hello")
        inputs = nlp._parse_and_tokenize([conversation_1])
        self.assertEqual(inputs["input_ids"].tolist(), [[1710, 86, 2]])

        # test2
        conversation_1 = Conversation(
            "I like lasagne.",
            past_user_inputs=["hello"],
            generated_responses=[
                " Do you like lasagne? It is a traditional Italian dish consisting of a shepherd's pie."
            ],
        )
        inputs = nlp._parse_and_tokenize([conversation_1])
        self.assertEqual(
            inputs["input_ids"].tolist(),
            [
                # This should be compared with the same conversation on ParlAI `safe_interactive` demo.
                [
                    1710,  # hello
                    86,
                    228,  # Double space
                    228,
                    946,
                    304,
                    398,
                    6881,
                    558,
                    964,
                    38,
                    452,
                    315,
                    265,
                    6252,
                    452,
                    322,
                    968,
                    6884,
                    3146,
                    278,
                    306,
                    265,
                    617,
                    87,
                    388,
                    75,
                    341,
                    286,
                    521,
                    21,
                    228,  # Double space
                    228,
                    281,  # I like lasagne.
                    398,
                    6881,
                    558,
                    964,
                    21,
                    2,  # EOS
                ]
            ],
        )

    @require_torch
    @slow
    def test_integration_torch_conversation_blenderbot_400M(self):
        tokenizer = AutoTokenizer.from_pretrained(
            "facebook/blenderbot-400M-distill")
        model = AutoModelForSeq2SeqLM.from_pretrained(
            "facebook/blenderbot-400M-distill")
        nlp = ConversationalPipeline(model=model, tokenizer=tokenizer)

        conversation_1 = Conversation("hello")
        result = nlp(conversation_1, )
        self.assertEqual(
            result.generated_responses[0],
            # ParlAI implementation output, we have a different one, but it's our
            # second best, you can check by using num_return_sequences=10
            # " Hello! How are you? I'm just getting ready to go to work, how about you?",
            " Hello! How are you doing today? I just got back from a walk with my dog.",
        )

        conversation_1 = Conversation("Lasagne   hello")
        result = nlp(conversation_1, encoder_no_repeat_ngram_size=3)
        self.assertEqual(
            result.generated_responses[0],
            " Do you like lasagne? It is a traditional Italian dish consisting of a shepherd's pie.",
        )

        conversation_1 = Conversation(
            "Lasagne   hello   Lasagne is my favorite Italian dish. Do you like lasagne?   I like lasagne."
        )
        result = nlp(
            conversation_1,
            encoder_no_repeat_ngram_size=3,
        )
        self.assertEqual(
            result.generated_responses[0],
            " Me too. I like how it can be topped with vegetables, meats, and condiments.",
        )

    @require_torch
    @slow
    def test_integration_torch_conversation_encoder_decoder(self):
        # When
        tokenizer = AutoTokenizer.from_pretrained(
            "facebook/blenderbot_small-90M")
        model = AutoModelForSeq2SeqLM.from_pretrained(
            "facebook/blenderbot_small-90M")
        nlp = ConversationalPipeline(model=model,
                                     tokenizer=tokenizer,
                                     device=DEFAULT_DEVICE_NUM)

        conversation_1 = Conversation("My name is Sarah and I live in London")
        conversation_2 = Conversation(
            "Going to the movies tonight, What movie would you recommend? ")
        # Then
        self.assertEqual(len(conversation_1.past_user_inputs), 0)
        self.assertEqual(len(conversation_2.past_user_inputs), 0)
        # When
        result = nlp([conversation_1, conversation_2],
                     do_sample=False,
                     max_length=1000)
        # Then
        self.assertEqual(result, [conversation_1, conversation_2])
        self.assertEqual(len(result[0].past_user_inputs), 1)
        self.assertEqual(len(result[1].past_user_inputs), 1)
        self.assertEqual(len(result[0].generated_responses), 1)
        self.assertEqual(len(result[1].generated_responses), 1)
        self.assertEqual(result[0].past_user_inputs[0],
                         "My name is Sarah and I live in London")
        self.assertEqual(
            result[0].generated_responses[0],
            "hi sarah, i live in london as well. do you have any plans for the weekend?",
        )
        self.assertEqual(
            result[1].past_user_inputs[0],
            "Going to the movies tonight, What movie would you recommend? ")
        self.assertEqual(
            result[1].generated_responses[0],
            "i don't know... i'm not really sure. what movie are you going to see?"
        )
        # When
        conversation_1.add_user_input("Not yet, what about you?")
        conversation_2.add_user_input("What's your name?")
        result = nlp([conversation_1, conversation_2],
                     do_sample=False,
                     max_length=1000)
        # Then
        self.assertEqual(result, [conversation_1, conversation_2])
        self.assertEqual(len(result[0].past_user_inputs), 2)
        self.assertEqual(len(result[1].past_user_inputs), 2)
        self.assertEqual(len(result[0].generated_responses), 2)
        self.assertEqual(len(result[1].generated_responses), 2)
        self.assertEqual(result[0].past_user_inputs[1],
                         "Not yet, what about you?")
        self.assertEqual(
            result[0].generated_responses[1],
            "i don't have any plans yet. i'm not sure what to do yet.")
        self.assertEqual(result[1].past_user_inputs[1], "What's your name?")
        self.assertEqual(
            result[1].generated_responses[1],
            "i don't have a name, but i'm going to see a horror movie.")
class ConversationalPipelineTests(MonoInputPipelineCommonMixin, unittest.TestCase):
    pipeline_task = "conversational"
    small_models = []  # Models tested without the @slow decorator
    large_models = ["microsoft/DialoGPT-medium"]  # Models tested with the @slow decorator
    invalid_inputs = ["Hi there!", Conversation()]

    def _test_pipeline(
        self, nlp
    ):  # override the default test method to check that the output is a `Conversation` object
        self.assertIsNotNone(nlp)

        # We need to recreate conversation for successive tests to pass as
        # Conversation objects get *consumed* by the pipeline
        conversation = Conversation("Hi there!")
        mono_result = nlp(conversation)
        self.assertIsInstance(mono_result, Conversation)

        conversations = [Conversation("Hi there!"), Conversation("How are you?")]
        multi_result = nlp(conversations)
        self.assertIsInstance(multi_result, list)
        self.assertIsInstance(multi_result[0], Conversation)
        # Conversation have been consumed and are not valid anymore
        # Inactive conversations passed to the pipeline raise a ValueError
        self.assertRaises(ValueError, nlp, conversation)
        self.assertRaises(ValueError, nlp, conversations)

        for bad_input in self.invalid_inputs:
            self.assertRaises(Exception, nlp, bad_input)
        self.assertRaises(Exception, nlp, self.invalid_inputs)

    @require_torch
    @slow
    def test_integration_torch_conversation(self):
        # When
        nlp = pipeline(task="conversational", device=DEFAULT_DEVICE_NUM)
        conversation_1 = Conversation("Going to the movies tonight - any suggestions?")
        conversation_2 = Conversation("What's the last book you have read?")
        # Then
        self.assertEqual(len(conversation_1.past_user_inputs), 0)
        self.assertEqual(len(conversation_2.past_user_inputs), 0)
        # When
        result = nlp([conversation_1, conversation_2], do_sample=False, max_length=1000)
        # Then
        self.assertEqual(result, [conversation_1, conversation_2])
        self.assertEqual(len(result[0].past_user_inputs), 1)
        self.assertEqual(len(result[1].past_user_inputs), 1)
        self.assertEqual(len(result[0].generated_responses), 1)
        self.assertEqual(len(result[1].generated_responses), 1)
        self.assertEqual(result[0].past_user_inputs[0], "Going to the movies tonight - any suggestions?")
        self.assertEqual(result[0].generated_responses[0], "The Big Lebowski")
        self.assertEqual(result[1].past_user_inputs[0], "What's the last book you have read?")
        self.assertEqual(result[1].generated_responses[0], "The Last Question")
        # When
        conversation_2.add_user_input("Why do you recommend it?")
        result = nlp(conversation_2, do_sample=False, max_length=1000)
        # Then
        self.assertEqual(result, conversation_2)
        self.assertEqual(len(result.past_user_inputs), 2)
        self.assertEqual(len(result.generated_responses), 2)
        self.assertEqual(result.past_user_inputs[1], "Why do you recommend it?")
        self.assertEqual(result.generated_responses[1], "It's a good book.")

    @require_torch
    @slow
    def test_integration_torch_conversation_truncated_history(self):
        # When
        nlp = pipeline(task="conversational", min_length_for_response=24, device=DEFAULT_DEVICE_NUM)
        conversation_1 = Conversation("Going to the movies tonight - any suggestions?")
        # Then
        self.assertEqual(len(conversation_1.past_user_inputs), 0)
        # When
        result = nlp(conversation_1, do_sample=False, max_length=36)
        # Then
        self.assertEqual(result, conversation_1)
        self.assertEqual(len(result.past_user_inputs), 1)
        self.assertEqual(len(result.generated_responses), 1)
        self.assertEqual(result.past_user_inputs[0], "Going to the movies tonight - any suggestions?")
        self.assertEqual(result.generated_responses[0], "The Big Lebowski")
        # When
        conversation_1.add_user_input("Is it an action movie?")
        result = nlp(conversation_1, do_sample=False, max_length=36)
        # Then
        self.assertEqual(result, conversation_1)
        self.assertEqual(len(result.past_user_inputs), 2)
        self.assertEqual(len(result.generated_responses), 2)
        self.assertEqual(result.past_user_inputs[1], "Is it an action movie?")
        self.assertEqual(result.generated_responses[1], "It's a comedy.")

    @require_torch
    @slow
    def test_integration_torch_conversation_blenderbot_400M(self):
        tokenizer = AutoTokenizer.from_pretrained("facebook/blenderbot-400M-distill")
        model = AutoModelForSeq2SeqLM.from_pretrained("facebook/blenderbot-400M-distill")
        nlp = ConversationalPipeline(model=model, tokenizer=tokenizer)

        conversation_1 = Conversation("hello")
        result = nlp(
            conversation_1,
        )
        self.assertEqual(
            result.generated_responses[0],
            # ParlAI implementation output, we have a different one, but it's our
            # second best, you can check by using num_return_sequences=10
            # " Hello! How are you? I'm just getting ready to go to work, how about you?",
            " Hello! How are you doing today? I just got back from a walk with my dog.",
        )

        conversation_1 = Conversation(" Lasagne   hello")
        result = nlp(conversation_1, encoder_no_repeat_ngram_size=3)
        self.assertEqual(
            result.generated_responses[0],
            " Lasagne is my favorite Italian dish. Do you like lasagne?",
        )

        conversation_1 = Conversation(
            "Lasagne   hello   Lasagne is my favorite Italian dish. Do you like lasagne?   I like lasagne."
        )
        result = nlp(
            conversation_1,
            encoder_no_repeat_ngram_size=3,
        )
        self.assertEqual(
            result.generated_responses[0],
            # ParlAI implementation output, we have a different one, but it's our
            # second best, you can check by using num_return_sequences=10
            # " Hello! How are you? I'm just getting ready to go to work, how about you?",
            " Lasagne is a traditional Italian dish consisting of a yeasted flatbread typically topped with tomato sauce and cheese.",
        )

    @require_torch
    @slow
    def test_integration_torch_conversation_encoder_decoder(self):
        # When
        tokenizer = AutoTokenizer.from_pretrained("facebook/blenderbot_small-90M")
        model = AutoModelForSeq2SeqLM.from_pretrained("facebook/blenderbot_small-90M")
        nlp = ConversationalPipeline(model=model, tokenizer=tokenizer, device=DEFAULT_DEVICE_NUM)

        conversation_1 = Conversation("My name is Sarah and I live in London")
        conversation_2 = Conversation("Going to the movies tonight, What movie would you recommend? ")
        # Then
        self.assertEqual(len(conversation_1.past_user_inputs), 0)
        self.assertEqual(len(conversation_2.past_user_inputs), 0)
        # When
        result = nlp([conversation_1, conversation_2], do_sample=False, max_length=1000)
        # Then
        self.assertEqual(result, [conversation_1, conversation_2])
        self.assertEqual(len(result[0].past_user_inputs), 1)
        self.assertEqual(len(result[1].past_user_inputs), 1)
        self.assertEqual(len(result[0].generated_responses), 1)
        self.assertEqual(len(result[1].generated_responses), 1)
        self.assertEqual(result[0].past_user_inputs[0], "My name is Sarah and I live in London")
        self.assertEqual(
            result[0].generated_responses[0],
            "hi sarah, i live in london as well. do you have any plans for the weekend?",
        )
        self.assertEqual(
            result[1].past_user_inputs[0], "Going to the movies tonight, What movie would you recommend? "
        )
        self.assertEqual(
            result[1].generated_responses[0], "i don't know... i'm not really sure. what movie are you going to see?"
        )
        # When
        conversation_1.add_user_input("Not yet, what about you?")
        conversation_2.add_user_input("What's your name?")
        result = nlp([conversation_1, conversation_2], do_sample=False, max_length=1000)
        # Then
        self.assertEqual(result, [conversation_1, conversation_2])
        self.assertEqual(len(result[0].past_user_inputs), 2)
        self.assertEqual(len(result[1].past_user_inputs), 2)
        self.assertEqual(len(result[0].generated_responses), 2)
        self.assertEqual(len(result[1].generated_responses), 2)
        self.assertEqual(result[0].past_user_inputs[1], "Not yet, what about you?")
        self.assertEqual(result[0].generated_responses[1], "i don't have any plans yet. i'm not sure what to do yet.")
        self.assertEqual(result[1].past_user_inputs[1], "What's your name?")
        self.assertEqual(result[1].generated_responses[1], "i don't have a name, but i'm going to see a horror movie.")
Ejemplo n.º 24
0
import pdb

from transformers import pipeline, Conversation
conversational_pipe = pipeline('conversational')

conv = Conversation()


def get_response(question):

    conv.add_user_input(question)
    pipe = conversational_pipe([conv])

    responses = pipe.generated_responses

    # print ('conversation_id', conv.conversation_id)
    # print ('past_user_inputs ', pipe.past_user_inputs )
    print('responses', responses)

    return responses[-1]


"""
try:

  Questions = [ 'Let's go to a restaurant',
                'Do you know any cinema around?',
                'Any films related to AI and sci-fi?',
                'Is it rainy day today?',
                'How old are you?' ]