# ==================== HARDCODED DATASETS ====================
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."


# ==================== UNIT I ====================
print("\n--- UNIT I ---")

# 1. Pre-processing: Tokenisation, Stopwords, FreqDist
from nltk.tokenize import RegexpTokenizer
from nltk.corpus import stopwords
from nltk.probability import FreqDist

reg_tok = RegexpTokenizer(r'\w+')
stops = set(stopwords.words('english'))
d1_tokens = [[w.lower() for w in reg_tok.tokenize(s)] for s in D1_texts]
filtered_tokens = [w for s in d1_tokens for w in s if w not in stops]
fdist = FreqDist(filtered_tokens)
print("Top 3 FreqDist:", fdist.most_common(3))

# 2. N-gram LM (MLE, Zero Prob) & Smoothing (Laplace, Add-k/Lidstone, Good-Turing, Stupid Backoff)
from nltk.util import ngrams
from nltk.lm import MLE, Laplace, Lidstone, StupidBackoff
from nltk.lm.preprocessing import padded_everygram_pipeline
from nltk.probability import FreqDist, SimpleGoodTuringProbDist

print("Bigrams Sent 0:", list(ngrams(d1_tokens[0], 2)))

# Helper function since NLTK generator exhausts on each .fit()
def fit_lm(model):
    train, vocab = padded_everygram_pipeline(2, d1_tokens)
    model.fit(train, vocab)
    return model

mle = fit_lm(MLE(2))
lap = fit_lm(Laplace(2))
add_k = fit_lm(Lidstone(0.5, 2))
sbo = fit_lm(StupidBackoff(alpha=0.4, order=2))

print("MLE P(man|the):", mle.score("man", ["the"]), "| Zero Prob P(xyz|the):", mle.score("xyz", ["the"]))
print("Laplace:", lap.score("xyz", ["the"]), "| Add-k:", add_k.score("xyz", ["the"]), "| StupidBackoff:", sbo.score("movie", ["the"]))

# Good-Turing Smoothing (Using NLTK SimpleGoodTuringProbDist on bigram counts)
bg_fdist = FreqDist(ngrams(sum(d1_tokens, []), 2))
# Note: SGT requires diverse frequency-of-frequencies; we add dummy counts if corpus is tiny
bg_fdist[('dummy', '1')] = 1; bg_fdist[('dummy', '2')] = 2; bg_fdist[('dummy', '3')] = 3
sgt = SimpleGoodTuringProbDist(bg_fdist)
print("Good-Turing P(saw, the):", sgt.prob(('saw', 'the')), "| Unseen:", sgt.prob(('unseen', 'word')))

# 3. Subword: BPE Tokenization (via GPT2Tokenizer)
from transformers import GPT2Tokenizer

bpe_tok = GPT2Tokenizer.from_pretrained('gpt2')
print("BPE Tokens:", bpe_tok.tokenize(D1_texts[1]))

# 4. Neural LM: Character N-gram LM, RNN LM, LSTM LM, & Temperature Sampling
import torch
import torch.nn as nn
import torch.nn.functional as F
from nltk.lm import Laplace
from nltk.lm.preprocessing import padded_everygram_pipeline

# 4a. Character 3-gram LM
char_tokens = [list(s.lower()) for s in D1_texts]
c_train, c_vocab = padded_everygram_pipeline(3, char_tokens)
char_lm = Laplace(3); char_lm.fit(c_train, c_vocab)
print("Char LM Gen:", "".join(char_lm.generate(10, random_seed=42)))

# 4b. RNN LM & LSTM LM + Temperature Sampling
vocab_u1 = list(set(sum(d1_tokens, [])))
x_u1 = torch.tensor([[vocab_u1.index(w) for w in d1_tokens[0]]])
emb_u1 = nn.Embedding(len(vocab_u1), 8)(x_u1)

rnn_out, _ = nn.RNN(8, 16, batch_first=True)(emb_u1)
lstm_out, _ = nn.LSTM(8, 16, batch_first=True)(emb_u1)
logits_u1 = nn.Linear(16, len(vocab_u1))(lstm_out[:, -1, :]) # Last step logits

temp = 0.7 # Temperature < 1.0 sharpens distribution, > 1.0 flattens
probs_temp = F.softmax(logits_u1 / temp, dim=-1)
sampled_idx = torch.multinomial(probs_temp, 1).item()
print("LSTM Temp-Sampled Next Word:", vocab_u1[sampled_idx])


# ==================== UNIT II ====================
print("\n--- UNIT II ---")

# 1. POS Tagging: spaCy, NLTK, Universal Tagset, HMM, Regexp & Backoff Chain
import nltk
import spacy
from nltk.tag import hmm, DefaultTagger, RegexpTagger, UnigramTagger

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

train_pos = [nltk.pos_tag(s) for s in d1_tokens]
hmm_tagger = hmm.HiddenMarkovModelTrainer().train_supervised(train_pos)
print("HMM POS:", hmm_tagger.tag(d1_tokens[0]))

# Backoff Chain: Unigram -> Regexp -> Default('NN')
t0 = DefaultTagger('NN')
t1 = RegexpTagger([(r'.*ing$', 'VBG'), (r'.*ed$', 'VBD')], backoff=t0)
t2 = UnigramTagger(train_pos, backoff=t1)
print("Backoff Tagger:", t2.tag(d1_tokens[1]))

# 2. Grammar: CFG, CNF Conversion, PCFG, & Treebank Rules
import nltk
from nltk.corpus import treebank

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'
""")
cnf_cfg = cfg.to_chomsky_normal_form()
print("CNF Productions (First 4):", cnf_cfg.productions()[:4])
print("Treebank Productions (First 3):", treebank.parsed_sents()[0].productions()[:3])

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]
""")

# 3. Parsing: Chart (CKY/Earley), Viterbi, Recursive Descent, Shift-Reduce, & Chunking
import nltk

print("Chart (CKY/Earley) Trees:")
for tree in nltk.ChartParser(cfg).parse(d1_tokens[0]): print(tree)

print("Viterbi Best Tree:")
for tree in nltk.ViterbiParser(pcfg).parse(d1_tokens[0]): print(tree)

# Non-left-recursive grammar for RecursiveDescent & ShiftReduce
simple_cfg = nltk.CFG.fromstring("S -> NP VP\nVP -> V NP\nNP -> 'i' | 'the' 'man'\nV -> 'saw'")
print("Recursive Descent:", list(nltk.RecursiveDescentParser(simple_cfg).parse(['i', 'saw', 'the', 'man'])))
print("Shift-Reduce:", list(nltk.ShiftReduceParser(simple_cfg).parse(['i', 'saw', 'the', 'man'])))

# Chunking (NP Chunking using RegexpParser)
chunker = nltk.RegexpParser("NP: {<DT>?<JJ>*<NN.*>}")
print("Chunk Tree:", chunker.parse(nltk.pos_tag(d1_tokens[0])))

# 4. Dependency Parsing: Relations, SVO, Tree Depth, & Arc-Standard Simulation
import spacy

doc_u2 = nlp(D1_texts[0])
print("Dep Relations:", [(t.text, t.dep_, t.head.text) for t in doc_u2])

svo = [(t.text, t.head.text, [c.text for c in t.head.children if "obj" in c.dep_]) for t in doc_u2 if "subj" in t.dep_]
print("SVO Triple:", svo)

# Tree depth: max path length from any token up to the root
depth = max(len(list(t.ancestors)) for t in doc_u2)
print("Dependency Tree Depth:", depth)

# Arc-Standard Transition System Simulator (Stack, Buffer, Actions)
stack, buf, arcs = ['ROOT'], ['i', 'saw', 'man'], []
for act in ['S', 'S', 'LA', 'S', 'RA', 'RA']: # S=Shift, LA=Left-Arc, RA=Right-Arc
    if act == 'S': stack.append(buf.pop(0))
    elif act == 'LA': arcs.append((stack[-1], stack.pop(-2)))
    elif act == 'RA': arcs.append((stack[-2], stack.pop(-1)))
print("Arc-Standard Result Arcs:", arcs)


# ==================== UNIT III ====================
print("\n--- UNIT III ---")

# 1. WordNet: Synonyms, Antonyms, Hyponyms, Hypernyms, Meronyms, Path Sim, & WSD (Lesk)
from nltk.corpus import wordnet as wn
from nltk.wsd import lesk

syn = wn.synsets('good')[0]
s_movie, s_film = wn.synsets('movie')[0], wn.synsets('film')[0]
print("Synonyms:", syn.lemma_names())
print("Antonyms:", [a.name() for l in syn.lemmas() for a in l.antonyms()])
print("Hypernyms:", s_movie.hypernyms(), "| Hyponyms:", s_movie.hyponyms()[:2])
print("Part Meronyms (car):", wn.synsets('car')[0].part_meronyms()[:3])
print("Path Similarity:", s_movie.path_similarity(s_film))
print("Lesk WSD:", lesk(d1_tokens[0], 'telescope').definition())

# 2. Vector Models: BoW (Term-Document), TF-IDF, Co-occurrence Matrix, & LSA/SVD
import numpy as np
from sklearn.feature_extraction.text import CountVectorizer, TfidfVectorizer
from sklearn.decomposition import TruncatedSVD

bow = CountVectorizer().fit_transform(D1_texts).toarray() # Term-Document Matrix
tfidf = TfidfVectorizer().fit_transform(D1_texts).toarray()
co_occurrence = np.dot(bow.T, bow) # Word-Word Co-occurrence = X^T * X
lsa = TruncatedSVD(n_components=2).fit_transform(tfidf)
print("BoW:", bow.shape, "| Co-occurrence:", co_occurrence.shape, "| LSA:", lsa.shape)

# 3. Similarity & Distance: Jaccard, Cosine, & Euclidean
from nltk.metrics import jaccard_distance
from sklearn.metrics.pairwise import cosine_similarity, euclidean_distances

jaccard_sim = 1 - jaccard_distance(set(d1_tokens[0]), set(d1_tokens[1]))
cos_sim = cosine_similarity([tfidf[0]], [tfidf[1]])[0][0]
euc_dist = euclidean_distances([tfidf[0]], [tfidf[1]])[0][0]
print(f"Jaccard Sim: {jaccard_sim:.3f} | Cosine Sim: {cos_sim:.3f} | Euclidean Dist: {euc_dist:.3f}")

# 4. Embeddings: Word2Vec, FastText, & BERT Contextual Vectors
from gensim.models import Word2Vec, FastText
from transformers import BertTokenizer, BertModel

w2v = Word2Vec(d1_tokens, vector_size=8, min_count=1)
ft = FastText(d1_tokens, vector_size=8, min_count=1)
print("W2V 'movie':", w2v.wv['movie'].shape, "| FastText OOV 'movies':", ft.wv['movies'].shape)

b_tok = BertTokenizer.from_pretrained('bert-base-uncased')
b_mod = BertModel.from_pretrained('bert-base-uncased')
ctx_vecs = b_mod(**b_tok(D1_texts[0], return_tensors='pt')).last_hidden_state
print("BERT Contextual Vectors Shape:", ctx_vecs.shape)

# 5. Classifiers: Naive Bayes, Logistic Regression, kNN, & SVM
from sklearn.naive_bayes import MultinomialNB
from sklearn.linear_model import LogisticRegression
from sklearn.neighbors import KNeighborsClassifier
from sklearn.svm import SVC

for name, clf in [("NB", MultinomialNB()), ("LR", LogisticRegression()), ("kNN", KNeighborsClassifier(n_neighbors=2)), ("SVM", SVC())]:
    preds = clf.fit(tfidf, D1_labels).predict(tfidf)
    print(f"{name} Predictions:", preds)


# ==================== UNIT IV ====================
print("\n--- UNIT IV ---")

# 1. Coreference: Mentions, Pleonastic "it", Appositives, Alias, Pronoun Res, Mention-Pair
import spacy
from sklearn.linear_model import LogisticRegression

doc_d2 = nlp(D2)
mentions = [c.text for c in doc_d2.noun_chunks]
print("1a. Mentions:", mentions)

pleo_verbs = {"rain", "snow", "seem", "appear", "be"}
for t in doc_d2:
    if t.lower_ == "it":
        print(f"1b. '{t.text}' (head: {t.head.text}) Pleonastic?:", t.head.lemma_ in pleo_verbs)

print("1c. Appositives:", [(t.head.text, t.text) for t in doc_d2 if t.dep_ == "appos"])

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: {m1} <-> {m2}")

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

pairs = [("Alice", "She"), ("International Business Machines", "IBM"), ("Alice", "Paris")]
X_mp = [[int(a == b), int(acro(a) == b), int(b.lower() in ["she", "it"])] for a, b in pairs]
mp_clf = LogisticRegression().fit(X_mp, [1, 1, 0])
print("1f. Mention-Pair Preds:", mp_clf.predict(X_mp))

# 2. RNN Models: BiLSTM, Stacked GRU, Encoder-Decoder, & Teacher Forcing
import random
import torch
import torch.nn as nn
from nltk.tokenize import RegexpTokenizer

d2_toks = RegexpTokenizer(r'\w+').tokenize(D2.lower())
v_d2 = list(set(d2_toks))
x_d2 = torch.tensor([[v_d2.index(w) for w in d2_toks]])
emb_d2 = nn.Embedding(len(v_d2), 8)(x_d2)

bilstm_out, _ = nn.LSTM(8, 16, bidirectional=True, batch_first=True)(emb_d2)
gru_out, _ = nn.GRU(8, 16, num_layers=2, batch_first=True)(emb_d2)
print("BiLSTM Preds:", [v_d2[i] for i in torch.argmax(nn.Linear(32, len(v_d2))(bilstm_out)[0], dim=-1)[:4]])
print("Stacked GRU Preds:", [v_d2[i] for i in torch.argmax(nn.Linear(16, len(v_d2))(gru_out)[0], dim=-1)[:4]])

# Encoder-Decoder with Teacher Forcing
enc = nn.LSTM(8, 16, batch_first=True)
dec = nn.LSTM(8, 16, batch_first=True)
fc_out = nn.Linear(16, len(v_d2))
_, (h, c) = enc(emb_d2)

dec_in = emb_d2[:, 0:1, :] # Start token embedding
tf_ratio = 0.5
tf_preds = []
for t in range(1, 5):
    out_step, (h, c) = dec(dec_in, (h, c))
    pred_tok = fc_out(out_step).argmax(-1)
    tf_preds.append(v_d2[pred_tok.item()])
    # Teacher Forcing: pass ground-truth target token with probability tf_ratio
    dec_in = emb_d2[:, t:t+1, :] if random.random() < tf_ratio else nn.Embedding(len(v_d2), 8)(pred_tok)
print("Encoder-Decoder (Teacher Forcing) Output:", tf_preds)

# 3. Machine Translation: Greedy, Beam Search, & Back-Translation
from transformers import AutoTokenizer, AutoModelForSeq2SeqLM

# Using tiny T5 / MarianMT (or any cached Seq2Seq model)
mt_tok = AutoTokenizer.from_pretrained('t5-small')
mt_mod = AutoModelForSeq2SeqLM.from_pretrained('t5-small')

inp_mt = mt_tok("translate English to French: Alice went to Paris.", return_tensors="pt")
greedy_out = mt_mod.generate(**inp_mt, num_beams=1, max_new_tokens=15)
beam_out = mt_mod.generate(**inp_mt, num_beams=4, early_stopping=True, max_new_tokens=15)
fr_text = mt_tok.decode(beam_out[0], skip_special_tokens=True)
print("Greedy MT:", mt_tok.decode(greedy_out[0], skip_special_tokens=True))
print("Beam Search MT:", fr_text)

# Back-Translation (Translating target language back to source to augment/verify)
back_inp = mt_tok(f"translate French to English: {fr_text}", return_tensors="pt")
back_out = mt_mod.generate(**back_inp, max_new_tokens=15)
print("Back-Translated:", mt_tok.decode(back_out[0], skip_special_tokens=True))

# 4. MT Evaluation: BLEU, chrF, METEOR, & Edit Distance
from nltk.translate.bleu_score import sentence_bleu, SmoothingFunction
from nltk.translate.chrf_score import sentence_chrf
from nltk.translate.meteor_score import meteor_score
from nltk.metrics.distance import edit_distance

ref_str, cand_str = "Alice went to Paris", "Alice traveled to Paris"
ref_tok, cand_tok = [ref_str.split()], cand_str.split()

print("BLEU:", sentence_bleu(ref_tok, cand_tok, smoothing_function=SmoothingFunction().method1))
print("chrF:", sentence_chrf(ref_str, cand_str))
print("METEOR:", meteor_score(ref_tok, cand_tok))
print("Edit Distance:", edit_distance(ref_str, cand_str))


# ==================== UNIT V ====================
print("\n--- UNIT V ---")

# 1. Attention: Self-Attention, Multi-Head Attention, Positional Encoding, & Encoder Layer
import math
import torch
import torch.nn as nn
import torch.nn.functional as F

x = torch.randn(1, 5, 16)
sa_w = F.softmax((x @ x.transpose(-2, -1)) / math.sqrt(16), dim=-1)
sa_out = sa_w @ x
mha_out, mha_w = nn.MultiheadAttention(16, 4, batch_first=True)(x, x, x)
pos_enc = x + nn.Embedding(50, 16)(torch.arange(5).unsqueeze(0))
enc_layer = nn.TransformerEncoderLayer(d_model=16, nhead=4, batch_first=True)(pos_enc)
print("Shapes -> SA:", sa_out.shape, "| MHA:", mha_out.shape, "| PosEnc:", pos_enc.shape, "| EncLayer:", enc_layer.shape)

# 2. Transformer: GPT Decoding & Top-k Sampling
import torch
import torch.nn.functional as F
from transformers import GPT2Tokenizer, GPT2LMHeadModel

gpt_tok = GPT2Tokenizer.from_pretrained('gpt2')
gpt_mod = GPT2LMHeadModel.from_pretrained('gpt2')
g_inp = gpt_tok("The movie was", return_tensors='pt')

gen = gpt_mod.generate(**g_inp, max_new_tokens=5, do_sample=True, top_k=50, pad_token_id=gpt_tok.eos_token_id)
print("GPT Top-k Decoded:", gpt_tok.decode(gen[0]))

# 3. BERT: Config, WordPiece, CLS, Mean Pooling, Attention Weights, MLM, NSP, & PLL
import torch
import torch.nn.functional as F
from transformers import BertTokenizer, BertModel, BertForMaskedLM, BertForNextSentencePrediction

hf_tok = BertTokenizer.from_pretrained('bert-base-uncased')
bert_base = BertModel.from_pretrained('bert-base-uncased', attn_implementation="eager")
print("BERT Config:", bert_base.config.hidden_size, bert_base.config.num_hidden_layers, bert_base.config.num_attention_heads)
print("WordPiece:", hf_tok.tokenize("unaffable playing"))

b_inp = hf_tok(D1_texts[0], return_tensors='pt')
b_out = bert_base(**b_inp, output_attentions=True)
cls_emb = b_out.last_hidden_state[:, 0, :]
mean_pool = b_out.last_hidden_state.mean(dim=1)
print("CLS:", cls_emb.shape, "| MeanPool:", mean_pool.shape, "| Attn Weights:", b_out.attentions[0].shape)

# MLM & Pseudo-Log-Likelihood (PLL)
bert_mlm = BertForMaskedLM.from_pretrained('bert-base-uncased')
m_inp = hf_tok("The movie was [MASK] and thrilling!", return_tensors='pt')
m_idx = (m_inp.input_ids == hf_tok.mask_token_id).nonzero(as_tuple=True)[1]
print("MLM Predicted:", hf_tok.decode(bert_mlm(**m_inp).logits[0, m_idx].argmax(-1)))

ids = b_inp.input_ids[0]
pll = 0.0
for i in range(1, len(ids) - 1):
    m_ids = ids.clone(); m_ids[i] = hf_tok.mask_token_id
    with torch.no_grad(): logits = bert_mlm(m_ids.unsqueeze(0)).logits[0, i]
    pll += F.log_softmax(logits, dim=-1)[ids[i]].item()
print("Pseudo-Log-Likelihood (PLL):", pll)

# NSP
bert_nsp = BertForNextSentencePrediction.from_pretrained('bert-base-uncased')
nsp_out = bert_nsp(**hf_tok(D1_texts[1], D1_texts[2], return_tensors='pt')).logits
print("NSP IsNext?:", torch.argmax(nsp_out).item() == 0)

# 4. NER: bert-base-NER
from transformers import pipeline

ner_pipe = pipeline("ner", model="dslim/bert-base-NER", aggregation_strategy="simple")
print("BERT NER Entities:", [(e['word'], e['entity_group']) for e in ner_pipe(D2)])