{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "287d21e7",
   "metadata": {},
   "source": [
    "# Retrieval system"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "cf8b80de",
   "metadata": {},
   "source": [
    "## Embedding Similarity Search plain code"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "id": "9dca35cc",
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "import torch\n",
    "from sentence_transformers import SentenceTransformer\n",
    "import json\n",
    "\n",
    "device = \"cuda:0\"\n",
    "model = SentenceTransformer(\"../models/law_bert\", device=device)\n",
    "\n",
    "def get_top_k(query_embedding, data, k=5):\n",
    "    query_tensor = torch.tensor(query_embedding)\n",
    "    query_tensor = query_tensor.float()\n",
    "\n",
    "    data_tensors_list = []\n",
    "    for item in data:\n",
    "        embedding_tensor = torch.tensor(item[\"embedding\"])\n",
    "        embedding_tensor = embedding_tensor.float()\n",
    "        data_tensors_list.append(embedding_tensor)\n",
    "\n",
    "    data_tensor = torch.stack(data_tensors_list)\n",
    "\n",
    "    query_norm = query_tensor / query_tensor.norm(dim=0)\n",
    "\n",
    "    data_norm = data_tensor / data_tensor.norm(dim=1, keepdim=True)\n",
    "\n",
    "    similarities = torch.matmul(data_norm, query_norm)\n",
    "\n",
    "    top_k_scores, top_k_indices = torch.topk(similarities, k=k)\n",
    "\n",
    "    top_k_results = []\n",
    "    for j in range(len(top_k_indices)):\n",
    "        index = top_k_indices[j].item()\n",
    "        result = {\n",
    "            \"article_number\": data[index][\"article_number\"],\n",
    "            \"article_title\": data[index][\"article_title\"],\n",
    "            \"text\": data[index][\"text\"],\n",
    "            \"score\": float(top_k_scores[j])\n",
    "        }\n",
    "        top_k_results.append(result)\n",
    "\n",
    "    return top_k_results\n",
    "\n",
    "data_path = \"../data/new/\"\n",
    "children = os.listdir(data_path)\n",
    "\n",
    "sentences = []\n",
    "for child in children:\n",
    "    with open(data_path + child, \"r\", encoding=\"utf-8\") as read:\n",
    "        for line in read:\n",
    "            objz = json.loads(line)\n",
    "            objz[\"embedding\"] = model.encode(objz[\"article_title\"] + \"\\n\" + objz[\"text\"]).flatten()\n",
    "            sentences.append(objz)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "id": "257d0ba1",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Accuracy: 90.0%\n"
     ]
    }
   ],
   "source": [
    "queries = [\n",
    "    (\"NLĐ bị sa thải có được trả lương hay không?\", 48),\n",
    "    (\"Người sử dụng lao động được sa thải người lao động nữ đang mang thai không?\",137 ),\n",
    "    (\"Quy định về điều chuyển nhân sự được quy định như thế nào?\", 29),\n",
    "    (\"Người lao động được thuê làm giám đốc doanh nghiệp Nhà nước được hưởng các chế độ về tiền lương, thưởng như thế nào?\", 5),\n",
    "    (\"Làm việc 8h một ngày thì được nghỉ giữa giờ ít nhất bao nhiêu phút?\", 105),\n",
    "    (\"Người sử dụng lao động đào tạo nghề nghiệp và phát triển kỹ năng nghề cho người lao động như thế nào?\", 59),\n",
    "    (\"Nguyên tắc cho thuê lại lao động là gì?\", 53),\n",
    "    (\"Thời hạn của thỏa ước lao động tập thể như thế nào?\", 78),\n",
    "    (\"Hợp đồng lao động được giao kết theo hình thức nào?\", 14),\n",
    "    (\"Nội dung về đào tạo lao động có bắt buộc phải ghi vào hợp đồng lao động?\", 21)\n",
    "]\n",
    "\n",
    "correct = 0\n",
    "\n",
    "for query in queries:\n",
    "    top_matches = get_top_k(model.encode(query[0]).flatten(), sentences, k=5)\n",
    "    for item in top_matches:\n",
    "        if str(query[1]) == str(item[\"article_number\"]):\n",
    "            correct +=1 \n",
    "            break\n",
    "print(f\"Accuracy: {correct / 10 * 100}%\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "49a4d53b",
   "metadata": {},
   "source": [
    "## Embedding Similarity Search using FAISS"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "5afcac99",
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "C:\\Users\\Tri\\AppData\\Local\\Temp\\ipykernel_18880\\1491288163.py:9: LangChainDeprecationWarning: The class `HuggingFaceEmbeddings` was deprecated in LangChain 0.2.2 and will be removed in 1.0. An updated version of the class exists in the :class:`~langchain-huggingface package and should be used instead. To use it run `pip install -U :class:`~langchain-huggingface` and import as `from :class:`~langchain_huggingface import HuggingFaceEmbeddings``.\n",
      "  embeddings_ = HuggingFaceEmbeddings(\n",
      "c:\\Users\\Tri\\anaconda3\\envs\\tvpl\\lib\\site-packages\\tqdm\\auto.py:21: TqdmWarning: IProgress not found. Please update jupyter and ipywidgets. See https://ipywidgets.readthedocs.io/en/stable/user_install.html\n",
      "  from .autonotebook import tqdm as notebook_tqdm\n"
     ]
    }
   ],
   "source": [
    "import json\n",
    "import os\n",
    "from langchain_community.embeddings import HuggingFaceEmbeddings\n",
    "from langchain_community.vectorstores import FAISS\n",
    "from langchain_huggingface import HuggingFaceEmbeddings\n",
    "from langchain_core.documents import Document\n",
    "\n",
    "data_path = \"../data/new/\"\n",
    "children = os.listdir(data_path)\n",
    "embeddings_ = HuggingFaceEmbeddings(\n",
    "        model_name=\"../models/law_bert\"\n",
    "    )\n",
    "docs = []\n",
    "for child in children:\n",
    "    with open(data_path + child, \"r\", encoding=\"utf-8\") as read:\n",
    "        for line in read:\n",
    "            objz = json.loads(line)\n",
    "            docs.append(Document(\n",
    "                page_content=objz[\"article_title\"] + \"\\n\" + objz[\"text\"],\n",
    "                metadata={\"demuc\": objz[\"article_number\"]},\n",
    "            ))\n",
    "vector = FAISS.from_documents(docs, embeddings_)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "id": "107a92b1",
   "metadata": {},
   "outputs": [],
   "source": [
    "retriever = vector.as_retriever(\n",
    "        search_type=\"similarity\",\n",
    "        search_kwargs={\"k\": 5},\n",
    "    )"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "id": "cb5bb7b2",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Accuracy: 90.0%\n"
     ]
    }
   ],
   "source": [
    "queries = [\n",
    "    (\"NLĐ bị sa thải có được trả lương hay không?\", 48),\n",
    "    (\"Người sử dụng lao động được sa thải người lao động nữ đang mang thai không?\",137 ),\n",
    "    (\"Quy định về điều chuyển nhân sự được quy định như thế nào?\", 29),\n",
    "    (\"Người lao động được thuê làm giám đốc doanh nghiệp Nhà nước được hưởng các chế độ về tiền lương, thưởng như thế nào?\", 5),\n",
    "    (\"Làm việc 8h một ngày thì được nghỉ giữa giờ ít nhất bao nhiêu phút?\", 105),\n",
    "    (\"Người sử dụng lao động đào tạo nghề nghiệp và phát triển kỹ năng nghề cho người lao động như thế nào?\", 59),\n",
    "    (\"Nguyên tắc cho thuê lại lao động là gì?\", 53),\n",
    "    (\"Thời hạn của thỏa ước lao động tập thể như thế nào?\", 78),\n",
    "    (\"Hợp đồng lao động được giao kết theo hình thức nào?\", 14),\n",
    "    (\"Nội dung về đào tạo lao động có bắt buộc phải ghi vào hợp đồng lao động?\", 21)\n",
    "]\n",
    "\n",
    "correct = 0\n",
    "for query in queries:\n",
    "    retrieved_docs = retriever.invoke(query[0])\n",
    "    for doc in retrieved_docs:\n",
    "        if str(doc.metadata[\"demuc\"]) == str(query[1]):\n",
    "            correct += 1\n",
    "            break\n",
    "\n",
    "print(f\"Accuracy: {correct / 10 * 100}%\")"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "tvpl",
   "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.9.21"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
