{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "c305f3ba",
   "metadata": {},
   "outputs": [],
   "source": [
    "import nltk"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "ed46e20d",
   "metadata": {},
   "outputs": [],
   "source": [
    "# nltk.download(\"punkt\")\n",
    "# nltk.download(\"punkt_tab\")\n",
    "# nltk.download(\"punkt_tab\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "754835b1",
   "metadata": {},
   "source": [
    "# preprocessing"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "e144ce7b",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "DR. ELEANOR VANCE couldn't believe her eyes when she visited [https://archive-nlp.org/corpus/test?id=402](https://www.google.com/search?q=https://archive-nlp.org/corpus/test%3Fid%3D402) and downloaded the preliminary benchmark results :) ! \"I'm genuinely thrilled, though Mr. Arthur Vance isn't quite as convinced :(\" she stated during their morning review. Yesterday, Eleanor observed the astronomer with the telescope, and he meticulously documented their findings in a leather notebook. The battery life is phenomenal and the screen is exceptionally bright, yet its heavy chassis remains deeply frustrating. Eleanor carefully placed the financial deposit into a river bank account, wondering whether another bank along the river would offer a better interest rate for their joint capital. Mrs. Vance subsequently handed him his updated itinerary, confident that he would complete their crucial assignment before the weekend deadline.\n"
     ]
    }
   ],
   "source": [
    "corpus = \"\"\n",
    "\n",
    "with open(\"corpus.txt\", \"r\") as file:\n",
    "    corpus = file.read()\n",
    "\n",
    "print(corpus)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "22183e9b",
   "metadata": {},
   "outputs": [],
   "source": [
    "lcorpus = corpus.lower()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "2eafd82f",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "dr. eleanor vance couldn't believe her eyes when she visited  and downloaded the preliminary benchmark results :) ! \"i'm genuinely thrilled, though mr. arthur vance isn't quite as convinced :(\" she stated during their morning review. yesterday, eleanor observed the astronomer with the telescope, and he meticulously documented their findings in a leather notebook. the battery life is phenomenal and the screen is exceptionally bright, yet its heavy chassis remains deeply frustrating. eleanor carefully placed the financial deposit into a river bank account, wondering whether another bank along the river would offer a better interest rate for their joint capital. mrs. vance subsequently handed him his updated itinerary, confident that he would complete their crucial assignment before the weekend deadline.\n"
     ]
    }
   ],
   "source": [
    "import re\n",
    "url_pat = r\"https?://\\S+|www\\.\\S+\"\n",
    "cle = re.sub(url_pat, \"\", lcorpus)\n",
    "cle = re.sub(r\"\\[\", \"\", cle)\n",
    "print(cle)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "70b8e6f6",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "dr. eleanor vance could not believe her eyes when she visited  and downloaded the preliminary benchmark results :) ! \"i am genuinely thrilled, though mr. arthur vance is not quite as convinced :(\" she stated during their morning review. yesterday, eleanor observed the astronomer with the telescope, and he meticulously documented their findings in a leather notebook. the battery life is phenomenal and the screen is exceptionally bright, yet its heavy chassis remains deeply frustrating. eleanor carefully placed the financial deposit into a river bank account, wondering whether another bank along the river would offer a better interest rate for their joint capital. mrs. vance subsequently handed him his updated itinerary, confident that he would complete their crucial assignment before the weekend deadline.\n"
     ]
    }
   ],
   "source": [
    "import contractions\n",
    "\n",
    "expand = contractions.fix(cle)\n",
    "print(expand)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "be2a8d47",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "dr. eleanor vance could not believe her eyes when she visited  and downloaded the preliminary benchmark results <happy> ! \"i am genuinely thrilled, though mr. arthur vance is not quite as convinced <sad>\" she stated during their morning review. yesterday, eleanor observed the astronomer with the telescope, and he meticulously documented their findings in a leather notebook. the battery life is phenomenal and the screen is exceptionally bright, yet its heavy chassis remains deeply frustrating. eleanor carefully placed the financial deposit into a river bank account, wondering whether another bank along the river would offer a better interest rate for their joint capital. mrs. vance subsequently handed him his updated itinerary, confident that he would complete their crucial assignment before the weekend deadline.\n"
     ]
    }
   ],
   "source": [
    "prep = re.sub(r\"\\:\\)\", \"<happy>\",expand)\n",
    "prep = re.sub(r\"\\:\\(\", \"<sad>\",prep)\n",
    "print(prep)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "2d1184bc",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "['dr.', 'eleanor', 'vanc', 'could', 'not', 'believ', 'her', 'eye', 'when', 'she', 'visit', 'and', 'download', 'the', 'preliminari', 'benchmark', 'result', '<', 'happi', '>', '!', '``', 'i', 'am', 'genuin', 'thrill', ',', 'though', 'mr.', 'arthur', 'vanc', 'is', 'not', 'quit', 'as', 'convinc', '<', 'sad', '>', \"''\", 'she', 'state', 'dure', 'their', 'morn', 'review', '.', 'yesterday', ',', 'eleanor', 'observ', 'the', 'astronom', 'with', 'the', 'telescop', ',', 'and', 'he', 'meticul', 'document', 'their', 'find', 'in', 'a', 'leather', 'notebook', '.', 'the', 'batteri', 'life', 'is', 'phenomen', 'and', 'the', 'screen', 'is', 'except', 'bright', ',', 'yet', 'it', 'heavi', 'chassi', 'remain', 'deepli', 'frustrat', '.', 'eleanor', 'care', 'place', 'the', 'financi', 'deposit', 'into', 'a', 'river', 'bank', 'account', ',', 'wonder', 'whether', 'anoth', 'bank', 'along', 'the', 'river', 'would', 'offer', 'a', 'better', 'interest', 'rate', 'for', 'their', 'joint', 'capit', '.', 'mrs.', 'vanc', 'subsequ', 'hand', 'him', 'hi', 'updat', 'itinerari', ',', 'confid', 'that', 'he', 'would', 'complet', 'their', 'crucial', 'assign', 'befor', 'the', 'weekend', 'deadlin', '.']\n",
      "['dr.', 'eleanor', 'vance', 'could', 'not', 'believe', 'her', 'eye', 'when', 'she', 'visited', 'and', 'downloaded', 'the', 'preliminary', 'benchmark', 'result', '<', 'happy', '>', '!', '``', 'i', 'am', 'genuinely', 'thrilled', ',', 'though', 'mr.', 'arthur', 'vance', 'is', 'not', 'quite', 'a', 'convinced', '<', 'sad', '>', \"''\", 'she', 'stated', 'during', 'their', 'morning', 'review', '.', 'yesterday', ',', 'eleanor', 'observed', 'the', 'astronomer', 'with', 'the', 'telescope', ',', 'and', 'he', 'meticulously', 'documented', 'their', 'finding', 'in', 'a', 'leather', 'notebook', '.', 'the', 'battery', 'life', 'is', 'phenomenal', 'and', 'the', 'screen', 'is', 'exceptionally', 'bright', ',', 'yet', 'it', 'heavy', 'chassis', 'remains', 'deeply', 'frustrating', '.', 'eleanor', 'carefully', 'placed', 'the', 'financial', 'deposit', 'into', 'a', 'river', 'bank', 'account', ',', 'wondering', 'whether', 'another', 'bank', 'along', 'the', 'river', 'would', 'offer', 'a', 'better', 'interest', 'rate', 'for', 'their', 'joint', 'capital', '.', 'mrs.', 'vance', 'subsequently', 'handed', 'him', 'his', 'updated', 'itinerary', ',', 'confident', 'that', 'he', 'would', 'complete', 'their', 'crucial', 'assignment', 'before', 'the', 'weekend', 'deadline', '.']\n"
     ]
    }
   ],
   "source": [
    "from nltk.tokenize import word_tokenize\n",
    "from nltk.stem import PorterStemmer, WordNetLemmatizer\n",
    "\n",
    "stemmer = PorterStemmer()\n",
    "lemmatiser = WordNetLemmatizer()\n",
    "corpus_tok = word_tokenize(prep)\n",
    "\n",
    "stem_txt = [stemmer.stem(word) for word in corpus_tok]\n",
    "lemm_txt = [lemmatiser.lemmatize(word) for word in corpus_tok]\n",
    "\n",
    "print(stem_txt)\n",
    "print(lemm_txt)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "776ff8b4",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Prob: 7.6197e-11 | Perplexity: 105.59\n",
      "Generated: deeply eleanor though i wondering deposit his when yesterday vance `` in eleanor > deeply phenomenal `` bright interest <s>\n"
     ]
    }
   ],
   "source": [
    "from collections import w\n",
    "import math, random\n",
    "\n",
    "# 1. Setup counts & vocab\n",
    "toks = [\"<s>\"] + lemm_txt + [\"</s>\"]\n",
    "uni, bi = Counter(toks), Counter(zip(toks[:-1], toks[1:]))\n",
    "V, vocab = len(uni), list(uni.keys())\n",
    "\n",
    "# P(w | prev) lambda\n",
    "prob = lambda u, v: (bi[(u, v)] + 1) / (uni[u] + V)\n",
    "\n",
    "# 2. Probability & Perplexity for a test sequence\n",
    "test = [\"<s>\"] + [lemmatiser.lemmatize(w) for w in word_tokenize(\"this is a test\")] + [\"</s>\"]\n",
    "log_probs = [math.log(prob(u, v)) for u, v in zip(test[:-1], test[1:])]\n",
    "\n",
    "sent_prob = math.exp(sum(log_probs))\n",
    "perplexity = math.exp(-sum(log_probs) / len(log_probs))\n",
    "print(f\"Prob: {sent_prob:.4e} | Perplexity: {perplexity:.2f}\")\n",
    "\n",
    "# 3. Sampling with seed\n",
    "random.seed(42)\n",
    "curr, out = \"<s>\", []\n",
    "for _ in range(20):\n",
    "    curr = random.choices(vocab, weights=[prob(curr, w) for w in vocab])[0]\n",
    "    if curr == \"</s>\": break\n",
    "    out.append(curr)\n",
    "\n",
    "print(\"Generated:\", \" \".join(out))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "aff9c427",
   "metadata": {},
   "source": [
    "# POS + Parsing"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "id": "c3f26908",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "['dr.',\n",
       " 'eleanor',\n",
       " 'vance',\n",
       " 'could',\n",
       " 'not',\n",
       " 'believe',\n",
       " 'her',\n",
       " 'eyes',\n",
       " 'when',\n",
       " 'she',\n",
       " 'visited',\n",
       " 'and',\n",
       " 'downloaded',\n",
       " 'the',\n",
       " 'preliminary',\n",
       " 'benchmark',\n",
       " 'results',\n",
       " '<',\n",
       " 'happy',\n",
       " '>',\n",
       " '!',\n",
       " '``',\n",
       " 'i',\n",
       " 'am',\n",
       " 'genuinely',\n",
       " 'thrilled',\n",
       " ',',\n",
       " 'though',\n",
       " 'mr.',\n",
       " 'arthur',\n",
       " 'vance',\n",
       " 'is',\n",
       " 'not',\n",
       " 'quite',\n",
       " 'as',\n",
       " 'convinced',\n",
       " '<',\n",
       " 'sad',\n",
       " '>',\n",
       " \"''\",\n",
       " 'she',\n",
       " 'stated',\n",
       " 'during',\n",
       " 'their',\n",
       " 'morning',\n",
       " 'review',\n",
       " '.',\n",
       " 'yesterday',\n",
       " ',',\n",
       " 'eleanor',\n",
       " 'observed',\n",
       " 'the',\n",
       " 'astronomer',\n",
       " 'with',\n",
       " 'the',\n",
       " 'telescope',\n",
       " ',',\n",
       " 'and',\n",
       " 'he',\n",
       " 'meticulously',\n",
       " 'documented',\n",
       " 'their',\n",
       " 'findings',\n",
       " 'in',\n",
       " 'a',\n",
       " 'leather',\n",
       " 'notebook',\n",
       " '.',\n",
       " 'the',\n",
       " 'battery',\n",
       " 'life',\n",
       " 'is',\n",
       " 'phenomenal',\n",
       " 'and',\n",
       " 'the',\n",
       " 'screen',\n",
       " 'is',\n",
       " 'exceptionally',\n",
       " 'bright',\n",
       " ',',\n",
       " 'yet',\n",
       " 'its',\n",
       " 'heavy',\n",
       " 'chassis',\n",
       " 'remains',\n",
       " 'deeply',\n",
       " 'frustrating',\n",
       " '.',\n",
       " 'eleanor',\n",
       " 'carefully',\n",
       " 'placed',\n",
       " 'the',\n",
       " 'financial',\n",
       " 'deposit',\n",
       " 'into',\n",
       " 'a',\n",
       " 'river',\n",
       " 'bank',\n",
       " 'account',\n",
       " ',',\n",
       " 'wondering',\n",
       " 'whether',\n",
       " 'another',\n",
       " 'bank',\n",
       " 'along',\n",
       " 'the',\n",
       " 'river',\n",
       " 'would',\n",
       " 'offer',\n",
       " 'a',\n",
       " 'better',\n",
       " 'interest',\n",
       " 'rate',\n",
       " 'for',\n",
       " 'their',\n",
       " 'joint',\n",
       " 'capital',\n",
       " '.',\n",
       " 'mrs.',\n",
       " 'vance',\n",
       " 'subsequently',\n",
       " 'handed',\n",
       " 'him',\n",
       " 'his',\n",
       " 'updated',\n",
       " 'itinerary',\n",
       " ',',\n",
       " 'confident',\n",
       " 'that',\n",
       " 'he',\n",
       " 'would',\n",
       " 'complete',\n",
       " 'their',\n",
       " 'crucial',\n",
       " 'assignment',\n",
       " 'before',\n",
       " 'the',\n",
       " 'weekend',\n",
       " 'deadline',\n",
       " '.']"
      ]
     },
     "execution_count": 10,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "corpus_tok"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "id": "389729e9",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[('dr.', 'NNS'), ('eleanor', 'VBP'), ('vance', 'NN'), ('could', 'MD'), ('not', 'RB'), ('believe', 'VB'), ('her', 'PRP$'), ('eyes', 'NNS'), ('when', 'WRB'), ('she', 'PRP'), ('visited', 'VBD'), ('and', 'CC'), ('downloaded', 'VBD'), ('the', 'DT'), ('preliminary', 'JJ'), ('benchmark', 'NN'), ('results', 'NNS'), ('<', 'VBP'), ('happy', 'JJ'), ('>', 'NN'), ('!', '.'), ('``', '``'), ('i', 'JJ'), ('am', 'VBP'), ('genuinely', 'RB'), ('thrilled', 'VBN'), (',', ','), ('though', 'IN'), ('mr.', 'NN'), ('arthur', 'NN'), ('vance', 'NN'), ('is', 'VBZ'), ('not', 'RB'), ('quite', 'RB'), ('as', 'IN'), ('convinced', 'JJ'), ('<', 'NNP'), ('sad', 'NN'), ('>', 'NN'), (\"''\", \"''\"), ('she', 'PRP'), ('stated', 'VBD'), ('during', 'IN'), ('their', 'PRP$'), ('morning', 'NN'), ('review', 'NN'), ('.', '.'), ('yesterday', 'NN'), (',', ','), ('eleanor', 'RB'), ('observed', 'VBD'), ('the', 'DT'), ('astronomer', 'NN'), ('with', 'IN'), ('the', 'DT'), ('telescope', 'NN'), (',', ','), ('and', 'CC'), ('he', 'PRP'), ('meticulously', 'RB'), ('documented', 'VBD'), ('their', 'PRP$'), ('findings', 'NNS'), ('in', 'IN'), ('a', 'DT'), ('leather', 'NN'), ('notebook', 'NN'), ('.', '.'), ('the', 'DT'), ('battery', 'NN'), ('life', 'NN'), ('is', 'VBZ'), ('phenomenal', 'JJ'), ('and', 'CC'), ('the', 'DT'), ('screen', 'NN'), ('is', 'VBZ'), ('exceptionally', 'RB'), ('bright', 'JJ'), (',', ','), ('yet', 'CC'), ('its', 'PRP$'), ('heavy', 'JJ'), ('chassis', 'NN'), ('remains', 'VBZ'), ('deeply', 'RB'), ('frustrating', 'JJ'), ('.', '.'), ('eleanor', 'VB'), ('carefully', 'RB'), ('placed', 'VBN'), ('the', 'DT'), ('financial', 'JJ'), ('deposit', 'NN'), ('into', 'IN'), ('a', 'DT'), ('river', 'NN'), ('bank', 'NN'), ('account', 'NN'), (',', ','), ('wondering', 'VBG'), ('whether', 'IN'), ('another', 'DT'), ('bank', 'NN'), ('along', 'IN'), ('the', 'DT'), ('river', 'NN'), ('would', 'MD'), ('offer', 'VB'), ('a', 'DT'), ('better', 'JJR'), ('interest', 'NN'), ('rate', 'NN'), ('for', 'IN'), ('their', 'PRP$'), ('joint', 'JJ'), ('capital', 'NN'), ('.', '.'), ('mrs.', 'NN'), ('vance', 'NN'), ('subsequently', 'RB'), ('handed', 'VBD'), ('him', 'PRP'), ('his', 'PRP$'), ('updated', 'JJ'), ('itinerary', 'NN'), (',', ','), ('confident', 'NN'), ('that', 'IN'), ('he', 'PRP'), ('would', 'MD'), ('complete', 'VB'), ('their', 'PRP$'), ('crucial', 'JJ'), ('assignment', 'NN'), ('before', 'IN'), ('the', 'DT'), ('weekend', 'NN'), ('deadline', 'NN'), ('.', '.')]\n"
     ]
    }
   ],
   "source": [
    "from nltk import pos_tag\n",
    "\n",
    "tagged = pos_tag(corpus_tok)\n",
    "print(tagged)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "id": "6252a53d",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "['dr.', 'eleanor', 'vance', 'not', 'believe', 'eyes', 'visited', 'downloaded', 'preliminary', 'benchmark', 'results', '<', 'happy', '>', 'i', 'am', 'genuinely', 'thrilled', 'mr.', 'arthur', 'vance', 'is', 'not', 'quite', 'convinced', '<', 'sad', '>', 'stated', 'morning', 'review', 'yesterday', 'eleanor', 'observed', 'astronomer', 'telescope', 'meticulously', 'documented', 'findings', 'leather', 'notebook', 'battery', 'life', 'is', 'phenomenal', 'screen', 'is', 'exceptionally', 'bright', 'heavy', 'chassis', 'remains', 'deeply', 'frustrating', 'eleanor', 'carefully', 'placed', 'financial', 'deposit', 'river', 'bank', 'account', 'wondering', 'bank', 'river', 'offer', 'better', 'interest', 'rate', 'joint', 'capital', 'mrs.', 'vance', 'subsequently', 'handed', 'updated', 'itinerary', 'confident', 'complete', 'crucial', 'assignment', 'weekend', 'deadline']\n",
      "['her', 'she', 'and', 'the', 'though', 'as', 'she', 'during', 'their', 'the', 'with', 'the', 'and', 'he', 'their', 'in', 'a', 'the', 'and', 'the', 'yet', 'its', 'the', 'into', 'a', 'whether', 'another', 'along', 'the', 'a', 'for', 'their', 'him', 'his', 'that', 'he', 'their', 'before', 'the']\n"
     ]
    }
   ],
   "source": [
    "# Open vs close classes\n",
    "open_prefixes = (\"NN\", \"VB\", \"JJ\", \"RB\")\n",
    "closed_tags = {\"DT\", \"IN\", \"PRP\", \"PRP$\", \"CC\"}\n",
    "\n",
    "open_words = [t for t, p in tagged if (p.startswith(open_prefixes))]\n",
    "closed_words = [t for t, p in tagged if (p in closed_tags)]\n",
    "\n",
    "print(open_words)\n",
    "print(closed_words)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "id": "41a1769b",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Number of parse trees for PP-attachment: 2\n",
      "\n",
      "Tree 1:\n",
      "           S                                              \n",
      "    _______|_________________                              \n",
      "   |                         VP                           \n",
      "   |               __________|____________                 \n",
      "   |              VP                      PP              \n",
      "   |        ______|___                ____|___             \n",
      "   NP      |          NP             |        NP          \n",
      "   |       |       ___|______        |     ___|______      \n",
      " PropN     V      DT         NN      IN   DT         NN   \n",
      "   |       |      |          |       |    |          |     \n",
      "Eleanor observed the     astronomer with the     telescope\n",
      "\n",
      "\n",
      "Tree 2:\n",
      "           S                                              \n",
      "    _______|_________________                              \n",
      "   |                         VP                           \n",
      "   |        _________________|_______                      \n",
      "   |       |                         NP                   \n",
      "   |       |           ______________|____                 \n",
      "   |       |          |                   PP              \n",
      "   |       |          |               ____|___             \n",
      "   NP      |          NP             |        NP          \n",
      "   |       |       ___|______        |     ___|______      \n",
      " PropN     V      DT         NN      IN   DT         NN   \n",
      "   |       |      |          |       |    |          |     \n",
      "Eleanor observed the     astronomer with the     telescope\n",
      "\n"
     ]
    }
   ],
   "source": [
    "from nltk import CFG, ChartParser\n",
    "\n",
    "pp_sentence = \"Eleanor observed the astronomer with the telescope\".split()\n",
    "\n",
    "\n",
    "cfg_grammar = CFG.fromstring(\n",
    "    \"\"\"\n",
    "    S -> NP VP\n",
    "    PP -> IN NP\n",
    "    NP -> PropN | DT NN | NP PP\n",
    "    VP -> V NP | VP PP\n",
    "    PropN -> 'Eleanor'\n",
    "    V -> 'observed'\n",
    "    DT -> 'the'\n",
    "    NN -> 'astronomer' | 'telescope'\n",
    "    IN -> 'with'\n",
    "\"\"\"\n",
    ")\n",
    "\n",
    "parser = ChartParser(cfg_grammar)\n",
    "\n",
    "trees = list(parser.parse(pp_sentence))\n",
    "\n",
    "print(f\"Number of parse trees for PP-attachment: {len(trees)}\")\n",
    "for idx, tree in enumerate(trees, 1):\n",
    "    print(f\"\\nTree {idx}:\")\n",
    "    tree.pretty_print()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "id": "bca93237",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "  Aspect: results      | Opinion: preliminary    | Rel: amod\n",
      "  Aspect: Vance        | Opinion: convinced      | Rel: nsub+acomp/attr\n",
      "  Aspect: life         | Opinion: phenomenal     | Rel: nsub+acomp/attr\n",
      "  Aspect: screen       | Opinion: bright         | Rel: nsub+acomp/attr\n",
      "  Aspect: chassis      | Opinion: heavy          | Rel: amod\n",
      "  Aspect: chassis      | Opinion: frustrating    | Rel: nsub+acomp/attr\n",
      "  Aspect: deposit      | Opinion: financial      | Rel: amod\n",
      "  Aspect: rate         | Opinion: better         | Rel: amod\n",
      "  Aspect: capital      | Opinion: joint          | Rel: amod\n",
      "  Aspect: itinerary    | Opinion: updated        | Rel: amod\n",
      "  Aspect: itinerary    | Opinion: confident      | Rel: amod\n",
      "  Aspect: assignment   | Opinion: crucial        | Rel: amod\n"
     ]
    }
   ],
   "source": [
    "import spacy\n",
    "\n",
    "nlp = spacy.load(\"en_core_web_sm\")\n",
    "\n",
    "doc = nlp(corpus)\n",
    "aspect_opinions = []\n",
    "\n",
    "for token in doc:\n",
    "    if token.dep_ == \"amod\" and token.head.pos_ in (\"NOUN\", \"PROPN\"):\n",
    "        aspect_opinions.append(\n",
    "            (token.head.text, token.text, \"amod\")\n",
    "        )\n",
    "\n",
    "    if token.dep_ == \"nsubj\" and token.pos_ in (\"NOUN\", \"PROPN\"):\n",
    "        verb = token.head\n",
    "\n",
    "        for child in verb.children:\n",
    "            if child.dep_ in (\"acomp\", 'attr') or (child.dep_ == \"conj\" and child.pos == \"ADJ\"):\n",
    "                aspect_opinions.append(\n",
    "                    (token.text, child.text, \"nsub+acomp/attr\")\n",
    "                )\n",
    "\n",
    "for aspect, opinion, pattern in aspect_opinions:\n",
    "    print(f\"  Aspect: {aspect:<12} | Opinion: {opinion:<14} | Rel: {pattern}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "535e0469",
   "metadata": {},
   "source": [
    "# semantics"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "id": "7bf7adc1",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Total 'bank' synsets: 18\n",
      "Wu-Palmer similarity: 0.1429\n",
      "Lesk best sense: depository_financial_institution.n.01 -> a financial institution that accepts deposits and channels t...\n"
     ]
    }
   ],
   "source": [
    "from nltk.corpus import wordnet as wn\n",
    "from nltk.wsd import lesk\n",
    "\n",
    "# nltk.download([\"wordnet\", \"omw-1.4\"], quiet=True)\n",
    "\n",
    "synsets = wn.synsets(\"bank\")\n",
    "print(f\"Total 'bank' synsets: {len(synsets)}\")\n",
    "\n",
    "# Wu-Palmer similarity between financial bank and river bank\n",
    "fin_bank, river_bank = wn.synset(\"bank.n.02\"), wn.synset(\"bank.n.01\")\n",
    "print(f\"Wu-Palmer similarity: {fin_bank.wup_similarity(river_bank):.4f}\")\n",
    "\n",
    "# Lesk Word Sense Disambiguation on context from the corpus\n",
    "sent = \"Eleanor carefully placed the financial deposit into a river bank account\"\n",
    "best_sense = lesk(word_tokenize(sent), \"bank\", \"n\")\n",
    "print(\n",
    "    f\"Lesk best sense: {best_sense.name()} -> {best_sense.definition()[:60]}...\"\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "id": "76e1cfb2",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "Top-2 Retrieval for query 'financial deposit and capital interest rate':\n",
      "  [Score: 0.4532] Eleanor carefully placed the financial deposit into a river bank account, wonder...\n",
      "  [Score: 0.0000] Mrs. Vance subsequently handed him his updated itinerary, confident that he woul...\n"
     ]
    }
   ],
   "source": [
    "from nltk import sent_tokenize\n",
    "from sklearn.feature_extraction.text import TfidfVectorizer\n",
    "from sklearn.metrics.pairwise import cosine_similarity\n",
    "\n",
    "\n",
    "# TF IDF\n",
    "sentences = sent_tokenize(corpus)\n",
    "vectorizer = TfidfVectorizer(stop_words=\"english\")\n",
    "tfidf_matrix = vectorizer.fit_transform(sentences)\n",
    "\n",
    "query = \"financial deposit and capital interest rate\"\n",
    "query_vec = vectorizer.transform([query])\n",
    "sims = cosine_similarity(query_vec, tfidf_matrix).flatten()\n",
    "\n",
    "k = 2\n",
    "top_k_idx = sims.argsort()[-k:][::-1]\n",
    "print(f\"\\nTop-{k} Retrieval for query '{query}':\")\n",
    "for idx in top_k_idx:\n",
    "    print(f\"  [Score: {sims[idx]:.4f}] {sentences[idx][:80]}...\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "id": "a8d58e07",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "PPMI matrix shape: (92, 92) (Non-zero pairs: 423)\n"
     ]
    }
   ],
   "source": [
    "import numpy as np\n",
    "\n",
    "# -------------------------------------------------------------\n",
    "# 3. PPMI Matrix (Window ±2)\n",
    "# -------------------------------------------------------------\n",
    "# Tokenize and normalize sentences for co-occurrence counting\n",
    "tokenized_sents = [\n",
    "    [t.lower() for t in word_tokenize(s) if t.isalnum()] for s in sentences\n",
    "]\n",
    "flat_tokens = [t for s in tokenized_sents for t in s]\n",
    "vocab = sorted(set(flat_tokens))\n",
    "w2i = {w: i for i, w in enumerate(vocab)}\n",
    "\n",
    "# Co-occurrence counts within window ±2\n",
    "window = 2\n",
    "cooccur = Counter()\n",
    "word_counts = Counter(flat_tokens)\n",
    "total_windows = 0\n",
    "\n",
    "for s in tokenized_sents:\n",
    "    for i, target in enumerate(s):\n",
    "        ctx = [\n",
    "            s[j]\n",
    "            for j in range(max(0, i - window), min(len(s), i + window + 1))\n",
    "            if i != j\n",
    "        ]\n",
    "        cooccur.update((target, c) for c in ctx)\n",
    "        total_windows += len(ctx)\n",
    "\n",
    "# Compute Positive Pointwise Mutual Information (PPMI)\n",
    "ppmi_matrix = np.zeros((len(vocab), len(vocab)))\n",
    "for (w1, w2), count in cooccur.items():\n",
    "    p_wc = count / total_windows\n",
    "    p_w = word_counts[w1] / len(flat_tokens)\n",
    "    p_c = word_counts[w2] / len(flat_tokens)\n",
    "    pmi = math.log2(p_wc / (p_w * p_c)) if p_wc > 0 else 0\n",
    "    ppmi_matrix[w2i[w1], w2i[w2]] = max(0.0, pmi)\n",
    "\n",
    "print(\n",
    "    f\"\\nPPMI matrix shape: {ppmi_matrix.shape} (Non-zero pairs: {np.count_nonzero(ppmi_matrix)})\"\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "id": "78522946",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Word2Vec vocab size: 92\n",
      "Embedding shape for 'bank': (50,)\n"
     ]
    }
   ],
   "source": [
    "from gensim.models import Word2Vec\n",
    "\n",
    "# -------------------------------------------------------------\n",
    "# 4. Word2Vec Skip-gram\n",
    "# -------------------------------------------------------------\n",
    "# sg=1 specifies Skip-gram architecture; seed and workers ensure determinism\n",
    "w2v_model = Word2Vec(\n",
    "    sentences=tokenized_sents,\n",
    "    vector_size=50,\n",
    "    window=2,\n",
    "    min_count=1,\n",
    "    sg=1,\n",
    "    seed=42,\n",
    "    workers=1,\n",
    ")\n",
    "\n",
    "print(f\"Word2Vec vocab size: {len(w2v_model.wv.index_to_key)}\")\n",
    "print(f\"Embedding shape for 'bank': {w2v_model.wv['bank'].shape}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "06a66b95",
   "metadata": {},
   "source": [
    "# coreference"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "id": "1744a667",
   "metadata": {},
   "outputs": [],
   "source": [
    "MALE_NAMES, FEMALE_NAMES = {\"arthur\"}, {\"eleanor\"}\n",
    "PRON_MAP = {\n",
    "    **{p: (\"male\", \"sing\") for p in (\"he\", \"him\", \"his\")},\n",
    "    **{p: (\"female\", \"sing\") for p in (\"she\", \"her\", \"hers\")},\n",
    "    **{p: (\"neuter\", \"sing\") for p in (\"it\", \"its\")},\n",
    "    **{\n",
    "        p: (\"unknown\", \"plur\")\n",
    "        for p in (\"they\", \"them\", \"their\", \"theirs\", \"we\", \"us\", \"our\")\n",
    "    },\n",
    "}\n",
    "\n",
    "def get_attr(span):\n",
    "    txt, root = span.text.lower(), span.root.text.lower()\n",
    "    if \"mr.\" in txt:\n",
    "        return \"male\", \"sing\"\n",
    "    if any(h in txt for h in (\"mrs.\", \"ms.\", \"miss\")):\n",
    "        return \"female\", \"sing\"\n",
    "    if root in PRON_MAP:\n",
    "        return PRON_MAP[root]\n",
    "    tokens = {t.text.lower() for t in span}\n",
    "    if tokens & MALE_NAMES:\n",
    "        return \"male\", \"sing\"\n",
    "    if tokens & FEMALE_NAMES:\n",
    "        return \"female\", \"sing\"\n",
    "    return \"neuter\", (\"plur\" if span.root.tag_ in (\"NNS\", \"NNPS\") else \"sing\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "id": "e932bdd4",
   "metadata": {},
   "outputs": [],
   "source": [
    "raw_spans = (\n",
    "    [doc[e.start : e.end] for e in doc.ents]\n",
    "    + [doc[c.start : c.end] for c in doc.noun_chunks]\n",
    "    + [doc[t.i : t.i + 1] for t in doc if t.pos_ == \"PRON\"]\n",
    ")\n",
    "\n",
    "\n",
    "seen = set()\n",
    "unique_spans = [\n",
    "    s\n",
    "    for s in sorted(raw_spans, key=lambda s: (s.start, s.end))\n",
    "    if not ((s.start, s.end) in seen or seen.add((s.start, s.end)))\n",
    "]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "id": "07fdef6c",
   "metadata": {},
   "outputs": [],
   "source": [
    "sents = list(doc.sents)\n",
    "mentions = [\n",
    "    {\n",
    "        \"id\": i,\n",
    "        \"text\": s.text.strip(),\n",
    "        \"head\": s.root.lemma_.lower(),\n",
    "        \"s_idx\": next(idx for idx, sent in enumerate(sents) if s.root in sent),\n",
    "        \"gender\": get_attr(s)[0],\n",
    "        \"number\": get_attr(s)[1],\n",
    "    }\n",
    "    for i, s in enumerate(unique_spans)\n",
    "]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "id": "b446439f",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 3. Mention-Pair Scoring\n",
    "def score(m1, m2):\n",
    "    if (m1[\"gender\"] != m2[\"gender\"] and \"unknown\" not in (m1[\"gender\"], m2[\"gender\"])) or (m1[\"number\"] != m2[\"number\"]):\n",
    "        return -float(\"inf\")\n",
    "    return (\n",
    "        2.0\n",
    "        + (3.0 if m1[\"head\"] == m2[\"head\"] else 0.0)\n",
    "        + (2.0 if m1[\"text\"].lower() in m2[\"text\"].lower() or m2[\"text\"].lower() in m1[\"text\"].lower() else 0.0)\n",
    "        - abs(m2[\"s_idx\"] - m1[\"s_idx\"]) * 0.8\n",
    "    )"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "id": "4890024a",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 4. Best-First Clustering & Chain Building\n",
    "parent = list(range(len(mentions)))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 24,
   "id": "3a50fb9e",
   "metadata": {},
   "outputs": [],
   "source": [
    "def find(i):\n",
    "    if parent[i] != i:\n",
    "        parent[i] = find(parent[i])\n",
    "    return parent[i]\n",
    "\n",
    "\n",
    "for i in range(len(mentions)):\n",
    "    candidates = [(score(mentions[j], mentions[i]), j) for j in range(i)]\n",
    "    valid = [c for c in candidates if c[0] > 1.0]\n",
    "    if valid:\n",
    "        parent[find(i)] = find(max(valid)[1])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 25,
   "id": "8eafb77c",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{0: ['ELEANOR VANCE', 'her', 'she', 'she', 'Eleanor', 'Eleanor', 'Mrs. Vance'],\n",
       " 2: ['her eyes',\n",
       "  'the preliminary benchmark results',\n",
       "  'their',\n",
       "  'their',\n",
       "  'their findings',\n",
       "  'their',\n",
       "  'their'],\n",
       " 4: ['https://archive-nlp.org/corpus/test?id=402](https://www.google.com/search?q=https://archive-nlp.org/corpus/test%3Fid%3D402',\n",
       "  'I',\n",
       "  'their morning review',\n",
       "  'morning',\n",
       "  'Yesterday',\n",
       "  'the astronomer',\n",
       "  'the telescope',\n",
       "  'a leather notebook',\n",
       "  'The battery life',\n",
       "  'the screen',\n",
       "  'its',\n",
       "  'its heavy chassis',\n",
       "  'the financial deposit',\n",
       "  'a river bank account',\n",
       "  'another bank',\n",
       "  'the river',\n",
       "  'a better interest rate',\n",
       "  'their joint capital',\n",
       "  'Vance',\n",
       "  'his updated itinerary',\n",
       "  'their crucial assignment',\n",
       "  'the weekend deadline',\n",
       "  'weekend'],\n",
       " 7: ['Mr. Arthur Vance', 'Arthur Vance', 'he', 'him', 'his', 'he']}"
      ]
     },
     "execution_count": 25,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "chains = {}\n",
    "for m in mentions:\n",
    "    chains.setdefault(find(m[\"id\"]), []).append(m[\"text\"])\n",
    "chains"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 26,
   "id": "48820a18",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Chain 0: ELEANOR VANCE -> her -> she -> Eleanor -> Mrs. Vance\n",
      "Chain 2: her eyes -> the preliminary benchmark results -> their -> their findings\n",
      "Chain 4: https://archive-nlp.org/corpus/test?id=402](https://www.google.com/search?q=https://archive-nlp.org/corpus/test%3Fid%3D402 -> I -> their morning review -> morning -> Yesterday -> the astronomer -> the telescope -> a leather notebook -> The battery life -> the screen -> its -> its heavy chassis -> the financial deposit -> a river bank account -> another bank -> the river -> a better interest rate -> their joint capital -> Vance -> his updated itinerary -> their crucial assignment -> the weekend deadline -> weekend\n",
      "Chain 7: Mr. Arthur Vance -> Arthur Vance -> he -> him -> his\n"
     ]
    }
   ],
   "source": [
    "# Display multi-mention coreference clusters\n",
    "for cid, texts in chains.items():\n",
    "    if len(texts) > 1:\n",
    "        print(f\"Chain {cid}: {' -> '.join(dict.fromkeys(texts))}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "52494875",
   "metadata": {},
   "source": [
    "# BERT"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 27,
   "id": "ff9fc538",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "c053963628994abb8a1bd2f3981eda2c",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "Loading weights:   0%|          | 0/202 [00:00<?, ?it/s]"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "[transformers] \u001b[1mBertForMaskedLM LOAD REPORT\u001b[0m from: bert-base-uncased\n",
      "Key                         | Status     |  | \n",
      "----------------------------+------------+--+-\n",
      "bert.pooler.dense.bias      | UNEXPECTED |  | \n",
      "cls.seq_relationship.weight | UNEXPECTED |  | \n",
      "cls.seq_relationship.bias   | UNEXPECTED |  | \n",
      "bert.pooler.dense.weight    | UNEXPECTED |  | \n",
      "\n",
      "Notes:\n",
      "- UNEXPECTED:\tcan be ignored when loading from different task/architecture; not ok if you expect identical arch.\n"
     ]
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "47878cbf56f24d218c709e45cc79bf12",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "Loading weights:   0%|          | 0/104 [00:00<?, ?it/s]"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "from transformers import pipeline\n",
    "\n",
    "mask_pipe = pipeline(\"fill-mask\", model=\"bert-base-uncased\")\n",
    "sent_pipe = pipeline(\"sentiment-analysis\", model=\"distilbert-base-uncased-finetuned-sst-2-english\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 28,
   "id": "8d843914",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Mask prediction: short\n"
     ]
    }
   ],
   "source": [
    "print(\n",
    "    \"Mask prediction:\",\n",
    "    mask_pipe(\"The battery life is [MASK].\")[0][\"token_str\"],\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 29,
   "id": "36e12ed4",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Sentiment: {'label': 'POSITIVE', 'score': 0.9998623132705688}\n"
     ]
    }
   ],
   "source": [
    "print(\n",
    "    \"Sentiment:\",\n",
    "    sent_pipe(\"The battery life is phenomenal and screen is bright!\")[0],\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 30,
   "id": "c121cddf",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "03baf39ba58c4d6db3749157cf90967c",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "Loading weights:   0%|          | 0/199 [00:00<?, ?it/s]"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "[transformers] \u001b[1mBertForSequenceClassification LOAD REPORT\u001b[0m from: bert-base-uncased\n",
      "Key                                        | Status     | \n",
      "-------------------------------------------+------------+-\n",
      "cls.predictions.transform.dense.bias       | UNEXPECTED | \n",
      "cls.seq_relationship.weight                | UNEXPECTED | \n",
      "cls.predictions.transform.dense.weight     | UNEXPECTED | \n",
      "cls.predictions.transform.LayerNorm.weight | UNEXPECTED | \n",
      "cls.predictions.transform.LayerNorm.bias   | UNEXPECTED | \n",
      "cls.predictions.bias                       | UNEXPECTED | \n",
      "cls.seq_relationship.bias                  | UNEXPECTED | \n",
      "classifier.bias                            | MISSING    | \n",
      "classifier.weight                          | MISSING    | \n",
      "\n",
      "Notes:\n",
      "- UNEXPECTED:\tcan be ignored when loading from different task/architecture; not ok if you expect identical arch.\n",
      "- MISSING:\tthose params were newly initialized because missing from the checkpoint. Consider training on your downstream task.\n"
     ]
    }
   ],
   "source": [
    "from transformers import pipeline, AutoTokenizer, AutoModelForSequenceClassification\n",
    "# fine tune\n",
    "\n",
    "data = {\n",
    "    \"text\": [\n",
    "        \"The battery life is phenomenal\",\n",
    "        \"Screen is exceptionally bright\",\n",
    "        \"Genuinely thrilled with results\",\n",
    "        \"Crucial assignment completed\",\n",
    "        \"Deeply frustrating heavy chassis\",\n",
    "        \"Arthur isn't quite convinced\",\n",
    "        \"Financial loss and terrible rate\",\n",
    "        \"Failed benchmark download completely\",\n",
    "        \"Disappointing and broken screen\",\n",
    "    ],\n",
    "    \"label\": [1, 1, 1, 1, 0, 0, 0, 0, 0],  # 1: Positive, 0: Negative\n",
    "}\n",
    "\n",
    "model_id = \"bert-base-uncased\"\n",
    "tokenizer = AutoTokenizer.from_pretrained(model_id)\n",
    "model = AutoModelForSequenceClassification.from_pretrained(\n",
    "    model_id, num_labels=2\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 31,
   "id": "160f5d59",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "4c1ca8d55bcd4ae08f0f7b405c58737e",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "Map:   0%|          | 0/9 [00:00<?, ? examples/s]"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "from datasets import Dataset\n",
    "\n",
    "ds = Dataset.from_dict(data).map(\n",
    "    lambda b: tokenizer(b[\"text\"], truncation=True, padding=\"max_length\", max_length=16),\n",
    "    batched=True,\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 32,
   "id": "085f342b",
   "metadata": {},
   "outputs": [],
   "source": [
    "import evaluate\n",
    "\n",
    "# Metrics: Accuracy & F1\n",
    "acc_metric = evaluate.load(\"accuracy\")\n",
    "f1_metric = evaluate.load(\"f1\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 33,
   "id": "016eeb68",
   "metadata": {},
   "outputs": [],
   "source": [
    "def compute_metrics(eval_pred):\n",
    "    preds, labels = eval_pred\n",
    "    preds = np.argmax(preds, axis=1)\n",
    "    return {\n",
    "        \"accuracy\": acc_metric.compute(predictions=preds, references=labels)[\n",
    "            \"accuracy\"\n",
    "        ],\n",
    "        \"f1\": f1_metric.compute(predictions=preds, references=labels)[\"f1\"],\n",
    "    }"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 34,
   "id": "218761b7",
   "metadata": {},
   "outputs": [],
   "source": [
    "from transformers import TrainingArguments, Trainer\n",
    "\n",
    "# Minimal training setup\n",
    "args = TrainingArguments(\n",
    "    output_dir=\"./bert_finetuned\",\n",
    "    num_train_epochs=3,\n",
    "    per_device_train_batch_size=3,\n",
    "    learning_rate=2e-5,\n",
    "    logging_steps=1,\n",
    "    report_to=\"none\",\n",
    ")\n",
    "\n",
    "trainer = Trainer(\n",
    "    model=model,\n",
    "    args=args,\n",
    "    train_dataset=ds,\n",
    "    eval_dataset=ds,  # Evaluated on training set for minimal 9-sample sanity run\n",
    "    compute_metrics=compute_metrics,\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 35,
   "id": "90086e89",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "\n",
       "    <div>\n",
       "      \n",
       "      <progress value='9' max='9' style='width:300px; height:20px; vertical-align: middle;'></progress>\n",
       "      [9/9 00:01, Epoch 3/3]\n",
       "    </div>\n",
       "    <table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       " <tr style=\"text-align: left;\">\n",
       "      <th>Step</th>\n",
       "      <th>Training Loss</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <td>1</td>\n",
       "      <td>0.755642</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <td>2</td>\n",
       "      <td>0.713325</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <td>3</td>\n",
       "      <td>0.671005</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <td>4</td>\n",
       "      <td>0.582242</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <td>5</td>\n",
       "      <td>0.559187</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <td>6</td>\n",
       "      <td>0.681336</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <td>7</td>\n",
       "      <td>0.525175</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <td>8</td>\n",
       "      <td>0.480498</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <td>9</td>\n",
       "      <td>0.515872</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table><p>"
      ],
      "text/plain": [
       "<IPython.core.display.HTML object>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "9c2416aae78644ee840ecf48b24ebfc7",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "Writing model shards:   0%|          | 0/1 [00:00<?, ?it/s]"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "text/plain": [
       "TrainOutput(global_step=9, training_loss=0.6093645228279961, metrics={'train_runtime': 8.3994, 'train_samples_per_second': 3.215, 'train_steps_per_second': 1.072, 'total_flos': 221999952960.0, 'train_loss': 0.6093645228279961, 'epoch': 3.0})"
      ]
     },
     "execution_count": 35,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "trainer.train()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 36,
   "id": "14d265b3",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "\n",
       "    <div>\n",
       "      \n",
       "      <progress value='2' max='2' style='width:300px; height:20px; vertical-align: middle;'></progress>\n",
       "      [2/2 00:00]\n",
       "    </div>\n",
       "    "
      ],
      "text/plain": [
       "<IPython.core.display.HTML object>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "text/html": [
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       " <tr style=\"text-align: left;\">\n",
       "      <th>Training Loss</th>\n",
       "      <th>Validation Loss</th>\n",
       "      <th>Step</th>\n",
       "      <th>Accuracy</th>\n",
       "      <th>F1</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <td>0.515872</td>\n",
       "      <td>0.495444</td>\n",
       "      <td>9</td>\n",
       "      <td>1.000000</td>\n",
       "      <td>1.000000</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table><p>"
      ],
      "text/plain": [
       "<IPython.core.display.HTML object>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "Eval Accuracy: 1.0000 | Eval F1: 1.0000\n"
     ]
    }
   ],
   "source": [
    "eval_results = trainer.evaluate()\n",
    "print(\n",
    "    f\"\\nEval Accuracy: {eval_results['eval_accuracy']:.4f} | Eval F1: {eval_results['eval_f1']:.4f}\"\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 37,
   "id": "9a0fa57d",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Inference: 'The updated notebook looks promising' -> Positive\n"
     ]
    }
   ],
   "source": [
    "import torch \n",
    "\n",
    "# Inference on unseen text\n",
    "new_text = \"The updated notebook looks promising\"\n",
    "inputs = tokenizer(new_text, return_tensors=\"pt\", truncation=True, padding=True)\n",
    "inputs = {k: v.to(model.device) for k, v in inputs.items()}\n",
    "\n",
    "with torch.no_grad():\n",
    "    logits = model(**inputs).logits\n",
    "    pred_label = torch.argmax(logits, dim=1).item()\n",
    "\n",
    "print(\n",
    "    f\"Inference: '{new_text}' -> {'Positive' if pred_label == 1 else 'Negative'}\"\n",
    ")"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": ".venv",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.13.12"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
