Skip to content

Commit b53ea4d

Browse files
committed
[week5] Simplify the project format to ipython notebook
1 parent a2b1892 commit b53ea4d

File tree

4 files changed

+803
-1
lines changed

4 files changed

+803
-1
lines changed

README.md

+1-1
Original file line numberDiff line numberDiff line change
@@ -46,4 +46,4 @@ Two options here:
4646

4747
It might take a significant amount of time and resources to run the assignments code, but we expect that an average laptop is enough to accomplish the tasks. All assignments were tested in the Docker on Mac with 8GB RAM. If you have memory errors, that could be caused by not tested configurations or inefficient code. Consider reporting these cases or double-checking your code.
4848

49-
For the final project, you will need to set up AWS machine - see [AWS tutorial here](AWS-tutorial.md). You are also welcome to try it out earlier during the course.
49+
If you want to run the code of the course on the AWS machine, we've prepared the [AWS tutorial here](AWS-tutorial.md).

week5/dialogue_manager.py

+90
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,90 @@
1+
import os
2+
from sklearn.metrics.pairwise import pairwise_distances_argmin
3+
4+
from chatterbot import ChatBot
5+
from chatterbot.trainers import ChatterBotCorpusTrainer
6+
from utils import *
7+
8+
9+
class ThreadRanker(object):
10+
def __init__(self, paths):
11+
self.word_embeddings, self.embeddings_dim = load_embeddings(paths['WORD_EMBEDDINGS'])
12+
self.thread_embeddings_folder = paths['THREAD_EMBEDDINGS_FOLDER']
13+
14+
def __load_embeddings_by_tag(self, tag_name):
15+
embeddings_path = os.path.join(self.thread_embeddings_folder, tag_name + ".pkl")
16+
thread_ids, thread_embeddings = unpickle_file(embeddings_path)
17+
return thread_ids, thread_embeddings
18+
19+
def get_best_thread(self, question, tag_name):
20+
""" Returns id of the most similar thread for the question.
21+
The search is performed across the threads with a given tag.
22+
"""
23+
thread_ids, thread_embeddings = self.__load_embeddings_by_tag(tag_name)
24+
25+
# HINT: you have already implemented a similar routine in the 3rd assignment.
26+
27+
question_vec = #### YOUR CODE HERE ####
28+
best_thread = #### YOUR CODE HERE ####
29+
30+
return thread_ids[best_thread]
31+
32+
33+
class DialogueManager(object):
34+
def __init__(self, paths):
35+
print("Loading resources...")
36+
37+
# Intent recognition:
38+
self.intent_recognizer = unpickle_file(paths['INTENT_RECOGNIZER'])
39+
self.tfidf_vectorizer = unpickle_file(paths['TFIDF_VECTORIZER'])
40+
41+
self.ANSWER_TEMPLATE = 'I think its about %s\nThis thread might help you: https://stackoverflow.com/questions/%s'
42+
43+
# Goal-oriented part:
44+
self.tag_classifier = unpickle_file(paths['TAG_CLASSIFIER'])
45+
self.thread_ranker = ThreadRanker(paths)
46+
self.__init_chitchat_bot()
47+
48+
def __init_chitchat_bot(self):
49+
"""Initializes self.chitchat_bot with some conversational model."""
50+
51+
# Hint: you might want to create and train chatterbot.ChatBot here.
52+
# Create an instance of the ChatBot class.
53+
# Create a trainer (chatterbot.trainers.ChatterBotCorpusTrainer) for the ChatBot.
54+
# Train the ChatBot with "chatterbot.corpus.english" param.
55+
56+
########################
57+
#### YOUR CODE HERE ####
58+
########################
59+
60+
# remove this when you're done
61+
raise NotImplementedError(
62+
"Open dialogue_manager.py and fill with your code. In case of Google Colab, download"
63+
"(https://github.com/hse-aml/natural-language-processing/blob/master/project/dialogue_manager.py), "
64+
"edit locally and upload using '> arrow on the left edge' -> Files -> UPLOAD")
65+
66+
def generate_answer(self, question):
67+
"""Combines stackoverflow and chitchat parts using intent recognition."""
68+
69+
# Recognize intent of the question using `intent_recognizer`.
70+
# Don't forget to prepare question and calculate features for the question.
71+
72+
prepared_question = #### YOUR CODE HERE ####
73+
features = #### YOUR CODE HERE ####
74+
intent = #### YOUR CODE HERE ####
75+
76+
# Chit-chat part:
77+
if intent == 'dialogue':
78+
# Pass question to chitchat_bot to generate a response.
79+
response = #### YOUR CODE HERE ####
80+
return response
81+
82+
# Goal-oriented part:
83+
else:
84+
# Pass features to tag_classifier to get predictions.
85+
tag = #### YOUR CODE HERE ####
86+
87+
# Pass prepared_question to thread_ranker to get predictions.
88+
thread_id = #### YOUR CODE HERE ####
89+
90+
return self.ANSWER_TEMPLATE % (tag, thread_id)

week5/utils.py

+76
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,76 @@
1+
import nltk
2+
import pickle
3+
import re
4+
import numpy as np
5+
6+
nltk.download('stopwords')
7+
from nltk.corpus import stopwords
8+
9+
# Paths for all resources for the bot.
10+
RESOURCE_PATH = {
11+
'INTENT_RECOGNIZER': 'intent_recognizer.pkl',
12+
'TAG_CLASSIFIER': 'tag_classifier.pkl',
13+
'TFIDF_VECTORIZER': 'tfidf_vectorizer.pkl',
14+
'THREAD_EMBEDDINGS_FOLDER': 'thread_embeddings_by_tags',
15+
'WORD_EMBEDDINGS': 'data/word_embeddings.tsv',
16+
}
17+
18+
19+
def text_prepare(text):
20+
"""Performs tokenization and simple preprocessing."""
21+
replace_by_space_re = re.compile('[/(){}\[\]\|@,;]')
22+
good_symbols_re = re.compile('[^0-9a-z #+_]')
23+
stopwords_set = set(stopwords.words('english'))
24+
25+
text = text.lower()
26+
text = replace_by_space_re.sub(' ', text)
27+
text = good_symbols_re.sub('', text)
28+
text = ' '.join([x for x in text.split() if x and x not in stopwords_set])
29+
30+
return text.strip()
31+
32+
33+
def load_embeddings(embeddings_path):
34+
"""Loads pre-trained word embeddings from tsv file.
35+
Args:
36+
embeddings_path - path to the embeddings file.
37+
Returns:
38+
embeddings - dict mapping words to vectors;
39+
embeddings_dim - dimension of the vectors.
40+
"""
41+
42+
# Hint: you have already implemented a similar routine in the 3rd assignment.
43+
# Note that here you also need to know the dimension of the loaded embeddings.
44+
# When you load the embeddings, use numpy.float32 type as dtype
45+
46+
########################
47+
#### YOUR CODE HERE ####
48+
########################
49+
50+
# remove this when you're done
51+
raise NotImplementedError(
52+
"Open utils.py and fill with your code. In case of Google Colab, download"
53+
"(https://github.com/hse-aml/natural-language-processing/blob/master/project/utils.py), "
54+
"edit locally and upload using '> arrow on the left edge' -> Files -> UPLOAD")
55+
56+
57+
def question_to_vec(question, embeddings, dim):
58+
"""Transforms a string to an embedding by averaging word embeddings."""
59+
60+
# Hint: you have already implemented exactly this function in the 3rd assignment.
61+
62+
########################
63+
#### YOUR CODE HERE ####
64+
########################
65+
66+
# remove this when you're done
67+
raise NotImplementedError(
68+
"Open utils.py and fill with your code. In case of Google Colab, download"
69+
"(https://github.com/hse-aml/natural-language-processing/blob/master/project/utils.py), "
70+
"edit locally and upload using '> arrow on the left edge' -> Files -> UPLOAD")
71+
72+
73+
def unpickle_file(filename):
74+
"""Returns the result of unpickling the file content."""
75+
with open(filename, 'rb') as f:
76+
return pickle.load(f)

0 commit comments

Comments
 (0)