import nltk

# PREPROCESSING

corpus = ""
with open("corpus.txt", "r") as file:
    corpus = file.read()
print(corpus)
print()

lower = corpus.lower()
print(lower)

import re
nourl = re.sub(r"https?://\S+", "", lower)
print(nourl)

import contractions
nocontrac = contractions.fix(nourl)
print(nocontrac)

# happy sad
emotion = re.sub(r"\:\)", "<happy>", nocontrac)
emotion = re.sub(r"\:\(", "<sad>", emotion)
print(emotion)

reg_tok = re.findall(r'\w+', emotion)
print(reg_tok)

# stemming
# from nltk.stem import PorterStemmer, WordNetLemmatizer
# stem = PorterStemmer()
# lemm = WordNetLemmatizer()
# stemmed = [stem.stem(word) for word in reg_tok]    
# print(stemmed)
# lemmaed = [lemm.lemmatize(word) for word in reg_tok]
# print(lemmaed)

# Bigram
# first split on setance
sents = nltk.sent_tokenize(emotion)
# print(sents)
tok_sents = [re.findall(r'\w+', s) for s in sents]
print(tok_sents)

from nltk.lm.preprocessing import padded_everygram_pipeline
train_data, vocab = padded_everygram_pipeline(2, tok_sents)
print(train_data)

from nltk.lm import Laplace
model = Laplace(2)
model.fit(train_data, vocab)
p = model.score('eleanor', ['dr'])
print(p)

test_bi = list(zip(tok_sents[0][:-1], tok_sents[0][1:]))
sent_prob = math.prod(model.score(v, [u]) for u, v in test_bi)
ppl = model.perplexity(test_bi)

sample = model.generate(15, text_seed=['<s>'], random_seed=42)

print(f"P('eleanor'|'dr'): {p:.4f}")
print(f'Sentence Prob:   {sent_prob:.4e}')
print(f'Perplexity:      {ppl:.4f}')
print(f"Sample:          {' '.join(sample)}")