File size: 12,227 Bytes
479fcf6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "debeec92",
   "metadata": {
    "tags": []
   },
   "source": [
    "## Gathering NER Dataset"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "b83776e8",
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "from datasets import DatasetDict\n",
    "from transformers import AutoTokenizer\n",
    "\n",
    "dataset = DatasetDict.load_from_disk().remove_columns([\"token_type_ids\", \"attention_mask\"])\n",
    "\n",
    "tokenizer = AutoTokenizer.from_pretrained(\"./../tokenizer\")\n",
    "tokenizer.pad_token_id = 0\n",
    "tokenizer.pad_token = \"<|padding|>\"\n",
    "tokenizer.padding_size = \"right\"\n",
    "\n",
    "# new tokens for prompting\n",
    "num_new_tokens = tokenizer.add_tokens([\"<|startofprompt|>\", \"<|sepofprompt|>\", \"<|endofprompt|>\"])\n",
    "# new tokens for entities\n",
    "tokenizer.add_tokens([\"<|entity:PER|>\", \"<|entity:LOC|>\", \"<|entity:ORG|>\", \"<|entity|>\", \"<|detectentities|>\"])\n",
    "# new tokens for images\n",
    "tokenizer.add_tokens([\"<|startofimage|>\", \"<|endofimage|>\"])\n",
    "tokenizer.add_tokens([ f\"<|image:{tkn}|>\" for tkn in range(16000)])\n",
    "\n",
    "tokenizer.save_pretrained(\"./tokenizer\")\n",
    "\n",
    "print(\"Total Vocab Size:\", len(tokenizer))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "f2a95871-6e2d-4b96-bc36-8febac09d795",
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "tokenizer = AutoTokenizer.from_pretrained(\"./tokenizer\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "a706dd6d-e9b2-4e42-baf1-7d17cd93c54f",
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "from tqdm import tqdm\n",
    "import string\n",
    "import os\n",
    "import re\n",
    "\n",
    "audio_paths = sorted(os.listdir(\"./mp3\"))\n",
    "txt_paths = sorted(os.listdir(\"./txt\"))\n",
    "data = np.load(\"tokens.npz\")\n",
    "audio_tokens = [data[key] for key in data.keys()]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ce8bb550-8149-438c-9ca5-b12681f36476",
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "def tag_entities(text):\n",
    "    \n",
    "    patterns = {\n",
    "        \"PER\": r'\\|(.*?)\\]',\n",
    "        \"LOC\": r'\\$(.*?)\\]',\n",
    "        \"ORG\": r'\\{(.*?)\\]'\n",
    "    }\n",
    "    \n",
    "    entities = []\n",
    "\n",
    "    for entity, pattern in patterns.items():\n",
    "        matches = re.findall(pattern, text)\n",
    "        text = re.sub(pattern, lambda m: f'<|entity:{entity}|>{m.group(1)}<|entity|>', text)\n",
    "        entities += matches\n",
    "\n",
    "    return text, entities\n",
    "\n",
    "data = []\n",
    "\n",
    "for idx in tqdm(range(len(txt_paths))):\n",
    "    \n",
    "    with open(os.path.join(\"./txt\", txt_paths[idx])) as f:\n",
    "        txt = f.read()\n",
    "        \n",
    "    text, entities = tag_entities(txt.lower())\n",
    "    \n",
    "    audio_token = audio_tokens[idx]\n",
    "    \n",
    "    prompt = \"\".join([f\"<|audio:{tkn}|>\" for tkn in audio_token]) + \"<|detectentities|><|startofprompt|><|endofprompt|>\" + \"<|startoftranscript|>\" + text + \"<|endoftranscript|>\"\n",
    "    \n",
    "    try:\n",
    "        outputs = tokenizer(prompt, truncation=True, padding=\"max_length\", max_length=2048)\n",
    "        data.append({\n",
    "            \"audio_tokens\": audio_token,\n",
    "            \"raw_text\": text,\n",
    "            \"transcript\": txt.translate(str.maketrans('', '', string.punctuation)).lower(),\n",
    "            \"entities\": entities,\n",
    "            \"prompt\": prompt,\n",
    "            \"input_ids\": outputs[\"input_ids\"],\n",
    "            \"attention_mask\": output[\"attention_mask\"]\n",
    "        })\n",
    "    except:\n",
    "        print(idx)\n",
    "        continue\n",
    "        \n",
    "from datasets import Dataset\n",
    "import pandas as pd\n",
    "\n",
    "ds = Dataset.from_pandas(pd.DataFrame(data))\n",
    "\n",
    "ds.save_to_disk(\"entity_tokenized\")\n",
    "ds.push_to_hub(\"darshanmakwana/entity_tokenized\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "38191f9a-2a11-4bb2-a885-ef303d6c43f7",
   "metadata": {
    "tags": []
   },
   "source": [
    "## Validating Model"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "id": "710a1144-46a1-43d4-9bf9-1c01569b26d4",
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "from transformers import GPT2LMHeadModel, AutoTokenizer\n",
    "from datasets import Dataset\n",
    "import torch\n",
    "\n",
    "dataset_name = \"entity_tokenized\"\n",
    "tokenizer_path = \"./../tokenizer\"\n",
    "max_length = 2048\n",
    "device = \"cuda:0\"\n",
    "dtype = torch.float16\n",
    "\n",
    "dataset = Dataset.load_from_disk(dataset_name)\n",
    "\n",
    "tokenizer = AutoTokenizer.from_pretrained(tokenizer_path)\n",
    "tokenizer.pad_token_id = 0\n",
    "tokenizer.pad_token = \"<|padding|>\"\n",
    "tokenizer.padding_side = \"left\"\n",
    "\n",
    "# new tokens for prompting\n",
    "num_new_tokens = tokenizer.add_tokens([\"<|startofprompt|>\", \"<|sepofprompt|>\", \"<|endofprompt|>\"])\n",
    "# new tokens for entities\n",
    "tokenizer.add_tokens([\"<|entity:PER|>\", \"<|entity:LOC|>\", \"<|entity:ORG|>\", \"<|entity|>\", \"<|detectentities|>\"])\n",
    "\n",
    "model = GPT2LMHeadModel.from_pretrained(\"./out/checkpoint-20000\").to(device).to(dtype).eval()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "id": "cea0d8c4-5c56-47eb-934a-86293bed6afa",
   "metadata": {
    "tags": []
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "114.073974609375"
      ]
     },
     "execution_count": 21,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "sum([param.numel() for param in model.parameters()]) / (1024 * 1024)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "id": "529ca732-569f-4b7d-8448-1f16b35a6694",
   "metadata": {
    "tags": []
   },
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "100%|β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ| 8/8 [00:27<00:00,  3.42s/it]\n"
     ]
    }
   ],
   "source": [
    "from eval_model import process\n",
    "from math import ceil\n",
    "from tqdm import tqdm\n",
    "import re\n",
    "\n",
    "def extract_entities(text):\n",
    "    \n",
    "    patterns = {\n",
    "        \"PER\": r'<\\|entity:PER\\|>(.*?)<\\|entity\\|>',\n",
    "        \"LOC\": r'<\\|entity:LOC\\|>(.*?)<\\|entity\\|>',\n",
    "        \"ORG\": r'<\\|entity:ORG\\|>(.*?)<\\|entity\\|>'\n",
    "    }\n",
    "    \n",
    "    entities = []\n",
    "\n",
    "    for entity, pattern in patterns.items():\n",
    "        matches = re.findall(pattern, text)\n",
    "        text = re.sub(pattern, lambda m: f'{m.group(1)}', text)\n",
    "        entities += [process(match) for match in matches]\n",
    "\n",
    "    return text, entities\n",
    "\n",
    "def preprocess(sample):\n",
    "    prompt = \"\".join([f\"<|audio:{tkn}|>\" for tkn in sample[\"audio_tokens\"]]) + \"<|detectentities|><|startofprompt|><|endofprompt|>\" + \"<|startoftranscript|>\"\n",
    "    return {\"prompt\": prompt}\n",
    "\n",
    "dataset = dataset.map(preprocess)\n",
    "dataset = dataset.select(list(range(0, 1000)))\n",
    "\n",
    "eot_token = tokenizer.encode(\"<|endoftranscript|>\")[0]\n",
    "\n",
    "batch_size = 128\n",
    "texts = []\n",
    "tp = 0\n",
    "fp = 0\n",
    "tn = 0\n",
    "\n",
    "for idx in tqdm(range(ceil(len(dataset)/batch_size))):\n",
    "\n",
    "    input_ids = tokenizer(dataset[idx * batch_size: (idx + 1) * batch_size][\"prompt\"], return_tensors=\"pt\", padding=True, truncation=True).input_ids.to(model.device)\n",
    "    par = input_ids.shape[-1]\n",
    "\n",
    "    generations = model.generate(\n",
    "        input_ids,\n",
    "        max_new_tokens=max_length,\n",
    "        eos_token_id = eot_token\n",
    "    )\n",
    "    texts += tokenizer.batch_decode(generations[:, par:], skip_special_tokens=True)\n",
    "\n",
    "#     transcript, pred_entities = extract_entities(transcripts[0])\n",
    "    \n",
    "#     entities = sample[\"entities\"]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "id": "5ce4384e-8771-487e-86e1-de5489ee4e59",
   "metadata": {
    "tags": []
   },
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "100%|β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ| 1000/1000 [00:04<00:00, 241.04it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Precision: 69.53846153846153\n",
      "Recall: 69.32515337423312\n",
      "F1 Score: 69.43164362519201\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "\n"
     ]
    }
   ],
   "source": [
    "tp = 0\n",
    "fp = 0\n",
    "fn = 0\n",
    "\n",
    "for idx in tqdm(range(len(dataset))):\n",
    "    \n",
    "    transcript, entities = extract_entities(texts[idx])\n",
    "\n",
    "    for entity in entities:\n",
    "        if entity in dataset[idx][\"entities\"]:\n",
    "            tp += 1\n",
    "        else:\n",
    "            fp += 1\n",
    "    for entity in dataset[idx][\"entities\"]:\n",
    "        if entity not in entities:\n",
    "            fn += 1\n",
    "            \n",
    "pre = tp / (tp + fp) * 100\n",
    "recall = tp / (tp + fn) * 100\n",
    "print(\"Precision:\", pre)\n",
    "print(\"Recall:\", recall)\n",
    "print(\"F1 Score:\", 2 / ((1/pre) + (1/recall)))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ed0fad1a-bb30-446e-83a9-4a972fdb7766",
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "## Train Iter   Precision    Recall   F1 Score\n",
    "    16000         68.80      69.27     69.03\n",
    "    17000         72.92      70.78     71.83\n",
    "    18000         76.78      75.34     76.05\n",
    "    19000         81.78      80.92     81.34\n",
    "    20000         85.05      80.74     82.84"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "id": "113df077-c31c-4b57-876e-b19942100306",
   "metadata": {
    "tags": []
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "81.34772710510141"
      ]
     },
     "execution_count": 16,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "2 / ((1/81.78) + (1/80.92))"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "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.10.12"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}