{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.10.12","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"gpu","dataSources":[{"sourceType":"datasetVersion","sourceId":5807888,"datasetId":3335974,"databundleVersionId":5884620},{"sourceType":"datasetVersion","sourceId":11282395,"datasetId":7053929,"databundleVersionId":11701009},{"sourceType":"datasetVersion","sourceId":11282071,"datasetId":7053688,"databundleVersionId":11700642},{"sourceType":"datasetVersion","sourceId":11280450,"datasetId":7052486,"databundleVersionId":11698796}],"dockerImageVersionId":30919,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"import pandas as pd\n\ndf = pd.read_csv('/kaggle/input/d-qa-v3/distortion_processed.csv')\n\ndf['Question']=\"What is the distorted part?\"\n\nimport re\n\ndef find_answer_start(context, answer):\n match = re.search(re.escape(answer.strip()), context)\n return match.start() if match else -1\n\n# Chuyển đổi DataFrame thành định dạng cho mô hình QA\nquestions = df[\"Question\"].tolist()\ncontexts = df[\"Patient Question\"].tolist()\nanswer_ = df[\"processed_substrings\"].tolist()\n\nanswers = []\nfor i, row in df.iterrows():\n if pd.isna(row[\"processed_substrings\"]): # Không có câu trả lời\n answer = {\"text\": [\"\"], \"answer_start\": [-1]} \n else:\n start_idx = find_answer_start(row[\"Patient Question\"], answer_[i])\n answer = {\n \"text\": [row[\"processed_substrings\"]],\n \"answer_start\": [start_idx]\n }\n answers.append(answer)\n\n\n\n# Tạo dataset theo định dạng của Hugging Face\nqa_data = {\n \"distortion\": df[\"Dominant Distortion\"].tolist(),\n \"question\": questions,\n \"context\": df[\"Patient Question\"].tolist(),\n \"answers\": answers\n}\n\n#Chuyển sang Dataset của Hugging Face\nfrom datasets import Dataset\ndataset = Dataset.from_dict(qa_data)\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-04-09T02:49:04.123373Z","iopub.execute_input":"2026-04-09T02:49:04.123801Z","iopub.status.idle":"2026-04-09T02:49:07.702176Z","shell.execute_reply.started":"2026-04-09T02:49:04.123770Z","shell.execute_reply":"2026-04-09T02:49:07.701266Z"}},"outputs":[],"execution_count":1},{"cell_type":"code","source":"# dataset = dataset.train_test_split(test_size=0.2, seed=42)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-04-09T02:49:07.703325Z","iopub.execute_input":"2026-04-09T02:49:07.703649Z","iopub.status.idle":"2026-04-09T02:49:07.707440Z","shell.execute_reply.started":"2026-04-09T02:49:07.703626Z","shell.execute_reply":"2026-04-09T02:49:07.706400Z"}},"outputs":[],"execution_count":2},{"cell_type":"code","source":"# dataset","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-04-09T02:49:07.709576Z","iopub.execute_input":"2026-04-09T02:49:07.709829Z","iopub.status.idle":"2026-04-09T02:49:07.735105Z","shell.execute_reply.started":"2026-04-09T02:49:07.709809Z","shell.execute_reply":"2026-04-09T02:49:07.734071Z"}},"outputs":[],"execution_count":3},{"cell_type":"code","source":"def predict_answer(question, context):\n # Tokenize with overflow & offset mapping\n inputs = tokenizer(\n question,\n context,\n return_tensors=\"pt\",\n max_length=512,\n truncation=\"only_second\",\n stride=256,\n return_overflowing_tokens=True,\n return_offsets_mapping=True,\n padding=\"max_length\",\n )\n\n # Pop những thông tin không phải input cho model\n offset_mapping = inputs.pop(\"offset_mapping\")\n overflow_mapping = inputs.pop(\"overflow_to_sample_mapping\")\n\n input_ids = inputs[\"input_ids\"]\n # print(\"Số đoạn context:\", input_ids.shape[0])\n inputs = {k: v.to(device) for k, v in inputs.items()}\n\n with torch.no_grad():\n outputs = model(**inputs)\n\n start_logits = outputs.start_logits\n end_logits = outputs.end_logits\n\n best_score = float('-inf')\n best_answer = \"\"\n\n for i in range(len(start_logits)):\n start_logit = start_logits[i]\n end_logit = end_logits[i]\n offsets = offset_mapping[i]\n\n start_index = torch.argmax(start_logit).item()\n end_index = torch.argmax(end_logit).item()\n\n # Kiểm tra chỉ số có hợp lệ không\n if (\n start_index >= len(offsets)\n or end_index >= len(offsets)\n or offsets[start_index] is None\n or offsets[end_index] is None\n ):\n continue\n\n start_char = offsets[start_index][0]\n end_char = offsets[end_index][1]\n\n score = start_logit[start_index] + end_logit[end_index]\n # print(score)\n if score > best_score and start_char < end_char:\n best_score = score\n best_answer = context[start_char:end_char]\n\n return best_answer","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-04-09T02:49:07.736360Z","iopub.execute_input":"2026-04-09T02:49:07.736718Z","iopub.status.idle":"2026-04-09T02:49:07.762185Z","shell.execute_reply.started":"2026-04-09T02:49:07.736682Z","shell.execute_reply":"2026-04-09T02:49:07.761018Z"}},"outputs":[],"execution_count":4},{"cell_type":"code","source":"from collections import Counter\nimport string\n\n# Hàm tính toán Exact Match và F1 (như đã trình bày trước đó)\ndef calculate_exact_match(predictions, ground_truths):\n exact_match = 0\n for pred, truth in zip(predictions, ground_truths):\n if pred.strip().lower() == truth.strip().lower():\n exact_match += 1\n return exact_match / len(predictions)\n\ndef calculate_f1_score(predictions, ground_truths):\n def f1(pred, truth):\n pred_tokens = normalize_text(pred).split()\n truth_tokens = normalize_text(truth).split()\n\n # Trường hợp cả hai chuỗi đều rỗng\n if not pred_tokens and not truth_tokens:\n return 1.0 # Có thể cho là F1 score hoàn hảo trong trường hợp này\n\n common_tokens = Counter(pred_tokens) & Counter(truth_tokens)\n num_common = sum(common_tokens.values())\n\n if num_common == 0:\n return 0.0 # Trả về giá trị 0 nếu không có sự giao nhau\n\n precision = num_common / len(pred_tokens) if len(pred_tokens) > 0 else 0\n recall = num_common / len(truth_tokens) if len(truth_tokens) > 0 else 0\n\n if precision + recall == 0:\n return 0.0 # Tránh trường hợp chia cho 0\n\n return 2 * (precision * recall) / (precision + recall)\n\n f1_scores = [f1(pred, truth) for pred, truth in zip(predictions, ground_truths)]\n return sum(f1_scores) / len(f1_scores)\n\n\ndef normalize_text(text):\n return text.translate(str.maketrans(\"\", \"\", string.punctuation)).lower()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-04-09T02:49:07.762952Z","iopub.execute_input":"2026-04-09T02:49:07.763265Z","iopub.status.idle":"2026-04-09T02:49:07.821812Z","shell.execute_reply.started":"2026-04-09T02:49:07.763226Z","shell.execute_reply":"2026-04-09T02:49:07.820355Z"}},"outputs":[],"execution_count":5},{"cell_type":"code","source":"import torch\nimport numpy as np\nfrom datasets import Dataset\nfrom transformers import AutoTokenizer, AutoModelForQuestionAnswering\nfrom torch.utils.data import DataLoader\nfrom transformers import default_data_collator\nfrom tqdm.auto import tqdm\n\n# Tokenizer\nmodel_checkpoint = \"bert-base-cased\"\ntokenizer = AutoTokenizer.from_pretrained(model_checkpoint)\n\n# Preprocessing function\ndef preprocess_examples(examples):\n questions = [q.strip() for q in examples[\"question\"]]\n inputs = tokenizer(\n questions,\n examples[\"context\"],\n max_length=512,\n truncation=\"only_second\",\n stride=256,\n return_overflowing_tokens=True,\n return_offsets_mapping=True,\n padding=\"max_length\",\n )\n \n offset_mapping = inputs.pop(\"offset_mapping\")\n sample_map = inputs.pop(\"overflow_to_sample_mapping\")\n answers = examples[\"answers\"]\n start_positions, end_positions = [], []\n \n for i, offsets in enumerate(offset_mapping):\n sample_idx = sample_map[i]\n answer = answers[sample_idx]\n if len(answer[\"text\"]) == 0:\n start_positions.append(0)\n end_positions.append(0)\n else:\n start_char = answer[\"answer_start\"][0]\n end_char = start_char + len(answer[\"text\"][0])\n sequence_ids = inputs.sequence_ids(i)\n \n idx = 0\n while sequence_ids[idx] != 1:\n idx += 1\n context_start = idx\n while idx < len(sequence_ids) and sequence_ids[idx] == 1:\n idx += 1\n context_end = idx - 1\n \n if offsets[context_start][0] > start_char or offsets[context_end][1] < end_char:\n start_positions.append(0)\n end_positions.append(0)\n else:\n idx = context_start\n while idx <= context_end and offsets[idx][0] <= start_char:\n idx += 1\n start_positions.append(idx - 1)\n \n idx = context_end\n while idx >= context_start and offsets[idx][1] >= end_char:\n idx -= 1\n end_positions.append(idx + 1)\n \n inputs[\"start_positions\"] = start_positions\n inputs[\"end_positions\"] = end_positions\n return inputs\n\n# Apply preprocessing\ndataset_processed = dataset.map(preprocess_examples, batched=True, remove_columns=dataset.column_names)\ndataset_splited = dataset_processed.train_test_split(test_size=0.2, seed=42)\n\ndataset.set_format(\"torch\")\ntrain_dataloader = DataLoader(dataset_splited['train'], batch_size=3, shuffle=True, collate_fn=default_data_collator)\ntest_dataloader = DataLoader(dataset_splited['test'], batch_size=3, shuffle=False, collate_fn=default_data_collator)\n\n# Model and optimizer\nmodel = AutoModelForQuestionAnswering.from_pretrained(model_checkpoint)\ndevice = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\nmodel.to(device)\noptimizer = torch.optim.AdamW(model.parameters(), lr=2e-5)\n\n# Training loop\nnum_epochs = 20\nprogress_bar = tqdm(range(len(train_dataloader) * num_epochs))\n\ndataset = Dataset.from_dict(qa_data)\ndataset = dataset.train_test_split(test_size=0.2, seed=42)\n\nfor epoch in range(num_epochs):\n model.train()\n for batch in train_dataloader:\n batch = {k: v.to(device) for k, v in batch.items()}\n optimizer.zero_grad()\n outputs = model(**batch)\n loss = outputs.loss\n loss.backward()\n optimizer.step()\n progress_bar.update(1)\n predictions = []\n references = []\n model.eval()\n # Lặp qua từng dòng trong tập test\n for example in dataset['test']:\n question = example[\"question\"]\n context = example[\"context\"]\n ground_truth = example[\"answers\"][\"text\"][0]\n \n # Dự đoán câu trả lời\n result = predict_answer(question, context)\n \n # Thêm vào danh sách đánh giá\n predictions.append(result)\n references.append(ground_truth)\n \n \n # Tính Exact Match và F1\n em = calculate_exact_match(predictions, references)\n f1 = calculate_f1_score(predictions, references)\n \n print(f\"Exact Match: {em * 100:.2f}%\")\n print(f\"F1 Score: {f1:.4f}\")\n print(f\"Epoch {epoch + 1} completed.\")\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-04-09T02:49:08.670359Z","iopub.execute_input":"2026-04-09T02:49:08.670795Z","execution_failed":"2026-04-08T19:52:18.847Z"}},"outputs":[{"output_type":"display_data","data":{"text/plain":"tokenizer_config.json: 0%| | 0.00/49.0 [00:00 0 else 0\n recall = num_common / len(truth_tokens) if len(truth_tokens) > 0 else 0\n\n if precision + recall == 0:\n return 0.0 # Tránh trường hợp chia cho 0\n\n return 2 * (precision * recall) / (precision + recall)\n\n f1_scores = [f1(pred, truth) for pred, truth in zip(predictions, ground_truths)]\n return sum(f1_scores) / len(f1_scores)\n\n\ndef normalize_text(text):\n return text.translate(str.maketrans(\"\", \"\", string.punctuation)).lower()\n\n#Chuẩn bị dữ liệu từ qa_data\n# predictions = []\n# references = []\n\n# for i in range(len(qa_data[\"question\"])):\n# question = qa_data[\"question\"][i]\n# context = qa_data[\"context\"][i]\n# ground_truth = qa_data[\"answers\"][i][\"text\"][0]\n\n# # Dự đoán câu trả lời cho từng câu hỏi\n# result = predict_answer(question, context)\n# qa_data[\"predict\"][i]= result\n# # Thêm vào danh sách đánh giá\n# predictions.append(result)\n# references.append(ground_truth)\n\n# predictions = []\n# references = []\n\n# # Lặp qua từng dòng trong tập test\n# for example in dataset['test']:\n# question = example[\"question\"]\n# context = example[\"context\"]\n# ground_truth = example[\"answers\"][\"text\"][0]\n\n# # Dự đoán câu trả lời\n# result = predict_answer(question, context)\n\n# # Thêm vào danh sách đánh giá\n# predictions.append(result)\n# references.append(ground_truth)\n\n\n# # Tính Exact Match và F1\n# em = calculate_exact_match(predictions, references)\n# f1 = calculate_f1_score(predictions, references)\n\n# print(f\"Exact Match: {em * 100:.2f}%\")\n# print(f\"F1 Score: {f1:.4f}\")\n\n# qa_data[\"predict\"] = [] # Tạo danh sách rỗng trước\n\n# for i in range(len(qa_data[\"question\"])):\n# question = qa_data[\"question\"][i]\n# context = qa_data[\"context\"][i]\n# ground_truth = qa_data[\"answers\"][i][\"text\"][0]\n\n# # Dự đoán câu trả lời cho từng câu hỏi\n# result = predict_answer(question, context)\n\n# qa_data[\"predict\"].append(result) # Thêm kết quả dự đoán\n\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-09-29T04:49:23.854050Z","iopub.execute_input":"2025-09-29T04:49:23.854337Z","iopub.status.idle":"2025-09-29T04:49:23.862356Z","shell.execute_reply.started":"2025-09-29T04:49:23.854316Z","shell.execute_reply":"2025-09-29T04:49:23.861378Z"}},"outputs":[],"execution_count":4},{"cell_type":"code","source":"import pandas as pd\n\n# Chuyển dict thành DataFrame\ndf_qa = pd.DataFrame(qa_data)\n","metadata":{"trusted":true,"execution":{"execution_failed":"2025-05-19T01:36:39.991Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"df_qa.to_csv('distorted.csv', index = False)","metadata":{"trusted":true,"execution":{"execution_failed":"2025-05-19T01:36:39.991Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":" df['Distorted part']=df['Distorted part'].fillna('')","metadata":{"trusted":true,"execution":{"execution_failed":"2025-05-19T01:36:39.991Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"references","metadata":{"trusted":true,"execution":{"execution_failed":"2025-05-19T01:36:39.991Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"qa_data[\"context\"][91]","metadata":{"trusted":true,"execution":{"execution_failed":"2025-05-19T01:36:39.991Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"df.head()","metadata":{"trusted":true,"execution":{"execution_failed":"2025-05-19T01:36:39.992Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"df['Distorted part'][91]","metadata":{"trusted":true,"execution":{"execution_failed":"2025-05-19T01:36:39.992Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"df['Longest Match'][91]","metadata":{"trusted":true,"execution":{"execution_failed":"2025-05-19T01:36:39.992Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"qa_data[\"answers\"][91]","metadata":{"trusted":true,"execution":{"execution_failed":"2025-05-19T01:36:39.992Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"for i in range(len(references)):\n print(references[i])\n print(predictions[i])","metadata":{"trusted":true,"execution":{"execution_failed":"2025-05-19T01:36:39.992Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"predictions[2]","metadata":{"trusted":true,"execution":{"execution_failed":"2025-05-19T01:36:39.992Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"references","metadata":{"trusted":true,"execution":{"execution_failed":"2025-05-19T01:36:39.992Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"predictions[0]","metadata":{"trusted":true,"execution":{"execution_failed":"2025-05-19T01:36:39.992Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"references[0]","metadata":{"trusted":true,"execution":{"execution_failed":"2025-05-19T01:36:39.992Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Load pipeline\nquestion_answerer = pipeline(\"question-answering\", model=model, tokenizer=tokenizer)\n\n# Example inference\nfor i in range(len(qa_data[\"question\"])):\n question = qa_data[\"question\"][i]\n context = qa_data[\"context\"][i]\n result = question_answerer(question=question, context=context)\n print(\"Answer:\", result[\"answer\"])\n print(\"Start index:\", result[\"start\"])\n print(\"End index:\", result[\"end\"])\n print(\"Confidence score:\", result[\"score\"])\n print(f\"Question: {question}\")\n print(f\"Predicted Answer: {result['answer']}\\n\")\n break","metadata":{"trusted":true,"execution":{"execution_failed":"2025-05-19T01:36:39.992Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"len(\"I don’t really know how to explain the situation. \")","metadata":{"trusted":true,"execution":{"execution_failed":"2025-05-19T01:36:39.992Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"qa_data","metadata":{"trusted":true,"execution":{"execution_failed":"2025-05-19T01:36:39.993Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null}]}