# %% [markdown]
# # NLP End semester mock notebook

# %%
D1_texts = [
    "I saw the man with the telescope.",
    "The movie was fantastic and thrilling!",
    "Wait, the plot was terrible, boring, and slow.",
    "Awful acting ruined the dull film."
]
D1_labels = [1, 1, 0, 0]
D2 = "It is raining today. Alice, the CEO of International Business Machines, went to Paris. IBM is huge. She loved it."

# %% [markdown]
# ##### Unit I: Text preprocessing, N-gram Language Models, smoothing techniques, BPE, and Neural Language Models.

# %%
# 1. Regex Tokenization (removes punctuation), Stemming, Lemmatization
from nltk.tokenize import RegexpTokenizer
from nltk.stem import PorterStemmer, WordNetLemmatizer

reg_tok = RegexpTokenizer(r'\w+')
ps, wnl = PorterStemmer(), WordNetLemmatizer()
d1_tokens = [[w.lower() for w in reg_tok.tokenize(s)] for s in D1_texts]
print("Tokens:", d1_tokens[1])
print("Stems:", [ps.stem(w) for w in d1_tokens[1]])
print("Lemmas:", [wnl.lemmatize(w, pos='v') for w in d1_tokens[1]])

# %%
# 2a. N-gram Language Model & Smoothing + Sentence Generation (nltk.lm)
from nltk.lm import Laplace, Lidstone
from nltk.lm.preprocessing import padded_everygram_pipeline

train_data, vocab = padded_everygram_pipeline(2, d1_tokens)
lm_lap = Laplace(2) # For Lidstone: Lidstone(gamma=0.5, order=2)
lm_lap.fit(train_data, vocab)
print("Laplace P(man | the):", lm_lap.score("man", ["the"]))
print("Laplace LM Generated:", lm_lap.generate(5, random_seed=42))

# %%
import nltk
from nltk.tag import hmm
from nltk.probability import LaplaceProbDist
import random

tagged_d1 = [nltk.pos_tag(s) for s in d1_tokens]
hmm_model = hmm.HiddenMarkovModelTrainer().train_supervised(tagged_d1, estimator=LaplaceProbDist)
print("Laplace HMM Generated:", [w for w, t in hmm_model.random_sample(random.Random(42), 5)])

# %%
# 3. Subword Tokenization (BPE / WordPiece via HuggingFace Tokenizer)
from transformers import BertTokenizer

# Add local_files_only=True inside from_pretrained() if strictly offline
hf_tok = BertTokenizer.from_pretrained('bert-base-uncased')
print("Subwords:", hf_tok.tokenize(D1_texts[1]))

# %% [markdown]
# ##### Unit II: POS Tagging, CFG/PCFG, parsing techniques, and dependency parsing.

# %%
import nltk
import spacy

nlp = spacy.load("en_core_web_sm")
print("NLTK POS:", nltk.pos_tag(d1_tokens[0]))
print("spaCy POS:", [(t.text, t.pos_) for t in nlp(D1_texts[0])])

# 2. CFG & PCFG for NP / PP-Attachment Ambiguity 
import nltk

cfg = nltk.CFG.fromstring("""
    S -> NP VP
    VP -> V NP | VP PP
    NP -> NP PP | Det N | 'i'
    PP -> P NP
    Det -> 'the'
    N -> 'man' | 'telescope'
    V -> 'saw'
    P -> 'with'
""")
print("CFG Trees for NP Ambiguity:")
for tree in nltk.ChartParser(cfg).parse(d1_tokens[0]):
    tree.pretty_print()

# %%
pcfg = nltk.PCFG.fromstring("""
    S -> NP VP [1.0]
    VP -> V NP [0.7] | VP PP [0.3]
    NP -> NP PP [0.4] | Det N [0.5] | 'i' [0.1]
    PP -> P NP [1.0]
    Det -> 'the' [1.0]
    N -> 'man' [0.5] | 'telescope' [0.5]
    V -> 'saw' [1.0]
    P -> 'with' [1.0]
""")
print("PCFG Best Viterbi Tree:")
for tree in nltk.ViterbiParser(pcfg).parse(d1_tokens[0]):
    tree.pretty_print()

# %%
# 3. Dependency Parsing (spaCy)
import spacy
# print("Dependency Triples:", [(t.text, t.dep_, t.head.text) for t in nlp(D1_texts[0])])

print()
for t in nlp(D1_texts[0]):
    print(f"{t.head}\t\t{t.dep_}\t{t.head.text}")


# %% [markdown]
# ##### Unit III: WordNet, vector space models, similarity measures, word embeddings, and text classification algorithms.

# %%
# 1. WordNet: Synsets, Definitions, Hypernyms, Path/Wu-Palmer Similarity
from nltk.corpus import wordnet as wn

s1, s2 = wn.synsets('dance')[0], wn.synsets('film')[0]
print(f"Def: {s1.definition()} | Hypernyms: {s1.hypernyms()}")
print(f"Def: {s2.definition()} | Hypernyms: {s2.hypernyms()}")
print("Wu-Palmer Similarity:", s1.wup_similarity(s2))

# %%
# 2. Vector Space Models (BoW & TF-IDF) + Cosine Similarity
from sklearn.feature_extraction.text import CountVectorizer, TfidfVectorizer
from sklearn.metrics.pairwise import cosine_similarity

bow = CountVectorizer().fit_transform(D1_texts)
tfidf = TfidfVectorizer().fit_transform(D1_texts)
print(tfidf)

# %%
print("Cosine Similarity (Sent 0 vs Sent 1):", cosine_similarity(tfidf[0], tfidf[1])[0][0])

# %%
import spacy
print("Vector Similarity:", nlp("movie").similarity(nlp("film")))

# %%
# 4. Text Classification (Multinomial Naive Bayes)
from sklearn.naive_bayes import MultinomialNB

clf = MultinomialNB().fit(tfidf, D1_labels)
print("Classifier Predictions:", clf.predict(tfidf))

# %% [markdown]
# ##### Unit IV: coreference resolution, RNN-based models, machine translation, and evaluation metrics.

# %%
# 1. Coreference Resolution Suite on D2
import spacy
doc_d2 = nlp(D2)

# %%
# 1a. Mention Detection (Noun Chunks + Named Entities)
mentions = [chunk.text for chunk in doc_d2.noun_chunks]
print("1a. Mentions:", mentions)

# %%
# 1b. Pleonastic "It" Detection (non-referential 'it' attached to weather/cognitive/modal verbs)
pleonastic_verbs = {"rain", "snow", "seem", "appear", "be"}
for t in doc_d2:
    if t.lower_ == "it":
        is_pleo = (t.head.lemma_ in pleonastic_verbs) or any(c.lemma_ in pleonastic_verbs for c in t.head.children)
        print(f"1b. '{t.text}' (head: '{t.head.text}') -> Pleonastic?: {is_pleo}")

# %%
# 1c. Appositive Detection (using spaCy 'appos' dependency tag)
print("1c. Appositives:", [(t.head.text, t.text) for t in doc_d2 if t.dep_ == "appos"])

# %%
# 1d. Alias / Acronym Matching (Initials match)
acro = lambda s: "".join(w[0].upper() for w in s.split() if w[0].isupper())

for i, m1 in enumerate(mentions):
    for m2 in mentions[i+1:]:
        if len(m1) > 1 and (acro(m1) == m2 or acro(m2) == m1):
            print(f"1d. Alias Match: '{m1}' <-> '{m2}'")

# %%
# 1e. Pronoun Resolution (Referential pronouns only, skipping pleonastic 'it')
ants = [e.text for e in doc_d2.ents]
print(ants)

for t in doc_d2:
    if t.pos_ == "PRON" and t.head.lemma_ not in pleonastic_verbs:
        target = ants[0] if t.lower_ in ["she", "her", "he"] else ants[-1]
        print(f"1e. Pronoun Resolution: '{t.text}' -> '{target}'")

# %%
# 1f. Mention-Pair Model (Binary Classifier on Pair Features: [exact_match, alias_match, is_pronoun])
from sklearn.linear_model import LogisticRegression

pairs = [("Alice", "She"), ("International Business Machines", "IBM"), ("Alice", "Paris"), ("IBM", "Paris")]
y_coref = [1, 1, 0, 0] # 1 = Coreferent, 0 = Not Coreferent

featurize = lambda m1, m2: [int(m1 == m2), int(acro(m1) == m2), int(m2.lower() in ["she", "it", "her"])]
X_coref = [featurize(a, b) for a, b in pairs]
mp_clf = LogisticRegression().fit(X_coref, y_coref)

print("1f. Mention-Pair Predictions:\n", list(zip(pairs, mp_clf.predict(X_coref))))

# %% [markdown]
# ###### RNN THING

# %%
# 2. BiLSTM Forward Pass & Output Generation on D2
import torch
import torch.nn as nn
from nltk.tokenize import RegexpTokenizer

d2_toks = RegexpTokenizer(r'\w+').tokenize(D2.lower())
print(d2_toks)
vocab = list(set(d2_toks))
x = torch.tensor([[vocab.index(w) for w in d2_toks]]) # Input token IDs [1, seq_len]
print(x)

emb = nn.Embedding(len(vocab), 8)(x)
# print(emb)

# %%
# Option A: BiLSTM (bidirectional=True doubles output dim from 16 to 32)
bilstm_out, (h_n, c_n) = nn.LSTM(8, 16, bidirectional=True, batch_first=True)(emb)
logits_bilstm = nn.Linear(32, len(vocab))(bilstm_out)
pred_ids_bilstm = torch.argmax(logits_bilstm, dim=-1)[0]
print("BiLSTM Output Tokens:", [vocab[i] for i in pred_ids_bilstm])

# %%
# 3. Evaluation Metrics: BLEU & METEOR
from nltk.translate.bleu_score import sentence_bleu, SmoothingFunction
from nltk.translate.meteor_score import meteor_score
from nltk.tokenize import RegexpTokenizer

ref = [RegexpTokenizer(r'\w+').tokenize("Alice went to Paris")]
cand = RegexpTokenizer(r'\w+').tokenize("Alice traveled to Paris")
print("BLEU Score:", sentence_bleu(ref, cand, smoothing_function=SmoothingFunction().method1))
print("METEOR Score:", meteor_score(ref, cand))

# %% [markdown]
# ##### Unit V (Using D1):
# 
# - hyperparameters (hidden_size, num_hidden_layers, num_attention_heads, vocab_size).
# - Compute Max Pooling over a sentence's token embeddings from the BERT output hidden states (last_hidden_state).
# - Run a forward/training pass of BertForSequenceClassification on D1 with its labels.
# - Use BertForNextSentencePrediction to evaluate if sentence 2 follows sentence 1.

# %%
!export HF_HUB_OFFLINE=1

# %% [markdown]
# ###### BERT configs

# %%
# 1. Load BERT & Print Hyperparameters + 2. Compute Max Pooling over a Sentence
import torch
from transformers import BertTokenizer, BertModel

hf_tok = BertTokenizer.from_pretrained('bert-base-uncased')
bert_base = BertModel.from_pretrained('bert-base-uncased', attn_implementation="eager")

# %%
import transformers
cfg_b = bert_base.config
# print(help(transformers.models.bert.configuration_bert.BertConfig))

# %%
print(f"BERT Config -> Layers: {cfg_b.num_hidden_layers}, \nHeads: {cfg_b.num_attention_heads}, \nHidden: {cfg_b.hidden_size}, \nVocab: {cfg_b.vocab_size}")

# %%
# Forward pass on D1[0]
inp = hf_tok(D1_texts[0], return_tensors='pt')
out = bert_base(**inp, output_attentions=True)
hidden = out.last_hidden_state # [1, seq_len, 768]
hidden

# %%
cls_emb = hidden[:, 0, :]
mean_pool = hidden.mean(dim=1)
max_pool, _ = hidden.max(dim=1)
print("CLS Shape:", cls_emb.shape, "| Mean Pool:", mean_pool.shape, "| Max Pool:", max_pool.shape)

# %%
# 2d. Attention Weights (Tuple of 12 layers -> Layer 0 shape: [batch, heads, seq_len, seq_len])
print("Layer 0 Attention Weights Shape:", out.attentions[0].shape)

# %% [markdown]
# ###### NSP

# %%
# 4. BERT Next Sentence Prediction (NSP) & Sequence Classification
import torch
from torch.nn.functional import softmax
from transformers import BertForNextSentencePrediction

# 4a. Next Sentence Prediction (Index 0 = IsNext, Index 1 = NotNext)
bert_nsp = BertForNextSentencePrediction.from_pretrained('bert-base-uncased')
nsp_logits = bert_nsp(**hf_tok(D1_texts[1], D1_texts[2], return_tensors='pt')).logits

# %%
print("Logits:", nsp_logits)
print("Probabilities (IsNext vs NotNext):", softmax(nsp_logits, dim=1)[0])

# %% [markdown]
# ###### Classification

# %%
from transformers import BertForSequenceClassification

bert_clf = BertForSequenceClassification.from_pretrained('bert-base-uncased', num_labels=2)
out_clf = bert_clf(**hf_tok(D1_texts, padding=True, truncation=True, return_tensors='pt'), labels=torch.tensor(D1_labels))
print("BERT Clf Loss:", out_clf.loss.item())

# %%




