mailychee commited on
Commit
2aada5b
·
verified ·
1 Parent(s): 104ed37

Upload 5 files

Browse files
embedded_ragbench_clean.pkl ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d9f9a329ae5e5f6b892ca2eba610d0443bd9e235dc955b9d70373a5702edb865
3
+ size 662724774
map_triplet_rb.pkl ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:2523a30c790004f3921e4c26564a60c46c958655dd23c0521f7e16858c21789b
3
+ size 61965680
rb_filtered_318b.pkl ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:e81c32efca28537d44687add5ef28e9d8da760242c4b1756e28c7746e20818d9
3
+ size 24766909
sgcp (2).ipynb ADDED
@@ -0,0 +1,1025 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "execution_count": 1,
6
+ "id": "c456b0f8-4c68-495d-b2e1-7cffc10728e2",
7
+ "metadata": {},
8
+ "outputs": [
9
+ {
10
+ "name": "stderr",
11
+ "output_type": "stream",
12
+ "text": [
13
+ "/home/ubuntu/miniconda3/lib/python3.11/site-packages/sentence_transformers/cross_encoder/CrossEncoder.py:11: TqdmExperimentalWarning: Using `tqdm.autonotebook.tqdm` in notebook mode. Use `tqdm.tqdm` instead to force console mode (e.g. in jupyter console)\n",
14
+ " from tqdm.autonotebook import tqdm, trange\n"
15
+ ]
16
+ }
17
+ ],
18
+ "source": [
19
+ "from collections import defaultdict, deque\n",
20
+ "import numpy as np\n",
21
+ "import pandas as pd\n",
22
+ "from tqdm.notebook import tqdm\n",
23
+ "from sklearn.metrics.pairwise import cosine_similarity\n",
24
+ "from sentence_transformers import SentenceTransformer\n",
25
+ "from langchain.prompts import PromptTemplate\n",
26
+ "from langchain_core.pydantic_v1 import BaseModel, Field\n",
27
+ "from multiprocessing import Pool\n",
28
+ "import pickle\n",
29
+ "import faiss\n",
30
+ "import warnings\n",
31
+ "warnings.filterwarnings(\"ignore\")"
32
+ ]
33
+ },
34
+ {
35
+ "cell_type": "markdown",
36
+ "id": "7ca0f819-3674-4add-ba3b-c793b79e6ed2",
37
+ "metadata": {
38
+ "jp-MarkdownHeadingCollapsed": true
39
+ },
40
+ "source": [
41
+ "# LLM"
42
+ ]
43
+ },
44
+ {
45
+ "cell_type": "code",
46
+ "execution_count": 2,
47
+ "id": "3eacd9d7-6978-4ac4-92f2-ed64689483ff",
48
+ "metadata": {},
49
+ "outputs": [],
50
+ "source": [
51
+ "from transformers import AutoTokenizer\n",
52
+ "from langchain_community.llms import VLLMOpenAI\n",
53
+ "from langchain_openai import ChatOpenAI\n",
54
+ "\n",
55
+ "\n",
56
+ "inference_server_url = \"http://localhost:8100/v1\"\n",
57
+ "tokenizer = AutoTokenizer.from_pretrained(\"meta-llama/Meta-Llama-3.1-8B-Instruct\")\n",
58
+ "\n",
59
+ "### For Chat OpenAI template\n",
60
+ "llm = ChatOpenAI(\n",
61
+ " model=\"Llama-3.1-8B-Instruct\",\n",
62
+ " openai_api_key=\"EMPTY\",\n",
63
+ " openai_api_base=inference_server_url,\n",
64
+ " temperature=0,\n",
65
+ " streaming= False\n",
66
+ ")"
67
+ ]
68
+ },
69
+ {
70
+ "cell_type": "code",
71
+ "execution_count": 3,
72
+ "id": "454db217-6968-4373-8b7c-76e7ee164031",
73
+ "metadata": {
74
+ "scrolled": true
75
+ },
76
+ "outputs": [
77
+ {
78
+ "data": {
79
+ "text/plain": [
80
+ "AIMessage(content=\"It's nice to meet you. Is there something I can help you with or would you like to chat?\", response_metadata={'token_usage': {'completion_tokens': 23, 'prompt_tokens': 36, 'total_tokens': 59, 'completion_tokens_details': None, 'prompt_tokens_details': None}, 'model_name': 'Llama-3.1-8B-Instruct', 'system_fingerprint': None, 'finish_reason': 'stop', 'logprobs': None}, id='run-cc19a2e1-7f21-4de6-bfb5-0b552f06d7e6-0', usage_metadata={'input_tokens': 36, 'output_tokens': 23, 'total_tokens': 59})"
81
+ ]
82
+ },
83
+ "execution_count": 3,
84
+ "metadata": {},
85
+ "output_type": "execute_result"
86
+ }
87
+ ],
88
+ "source": [
89
+ "llm.invoke(\"Hello\")"
90
+ ]
91
+ },
92
+ {
93
+ "cell_type": "markdown",
94
+ "id": "f32f7238-f817-4fad-b261-0d99bc752365",
95
+ "metadata": {
96
+ "jp-MarkdownHeadingCollapsed": true
97
+ },
98
+ "source": [
99
+ "# Embedding"
100
+ ]
101
+ },
102
+ {
103
+ "cell_type": "code",
104
+ "execution_count": 4,
105
+ "id": "22c0f930-a871-4f59-a22a-19da9e0c9d4e",
106
+ "metadata": {},
107
+ "outputs": [],
108
+ "source": [
109
+ "import json\n",
110
+ "import requests\n",
111
+ "from typing import List\n",
112
+ "from langchain_core.embeddings import Embeddings\n",
113
+ "from tqdm.notebook import tqdm\n",
114
+ "\n",
115
+ "class CustomAPIEmbeddings(Embeddings):\n",
116
+ " def __init__(self, api_url: str, show_progress: bool):\n",
117
+ " self.api_url = api_url\n",
118
+ " self.show_progress = show_progress\n",
119
+ "\n",
120
+ " def embed_documents(self, texts: List[str]) -> List[List[float]]:\n",
121
+ " lst_embedding = []\n",
122
+ " if self.show_progress: # for tqdm embedding\n",
123
+ " for query in tqdm(texts):\n",
124
+ " payload = json.dumps({\n",
125
+ " \"inputs\": query\n",
126
+ " })\n",
127
+ " headers = {\n",
128
+ " 'Content-Type': 'application/json'\n",
129
+ " }\n",
130
+ " try:\n",
131
+ " response = json.loads(\n",
132
+ " requests.request(\"POST\", self.api_url, headers=headers, data=payload).text\n",
133
+ " )\n",
134
+ " lst_embedding.append(response)\n",
135
+ " except Exception as e:\n",
136
+ " print(e)\n",
137
+ " print(requests.request(\"POST\", self.api_url, headers=headers, data=payload).text)\n",
138
+ " else:\n",
139
+ " for query in texts:\n",
140
+ " payload = json.dumps({\n",
141
+ " \"inputs\": query\n",
142
+ " })\n",
143
+ " headers = {\n",
144
+ " 'Content-Type': 'application/json'\n",
145
+ " }\n",
146
+ " try:\n",
147
+ " response = json.loads(\n",
148
+ " requests.request(\"POST\", self.api_url, headers=headers, data=payload).text\n",
149
+ " )\n",
150
+ " lst_embedding.append(response)\n",
151
+ " except Exception as e:\n",
152
+ " print(e)\n",
153
+ " # print(requests.request(\"POST\", self.api_url, headers=headers, data=payload).text)\n",
154
+ "\n",
155
+ " return lst_embedding\n",
156
+ "\n",
157
+ " def embed_query(self, text: str) -> List[float]:\n",
158
+ " return self.embed_documents([text])[0]\n",
159
+ "\n",
160
+ "# Instantiate\n",
161
+ "embeddings = CustomAPIEmbeddings(api_url='http://localhost:8081/embed', show_progress=False)\n"
162
+ ]
163
+ },
164
+ {
165
+ "cell_type": "code",
166
+ "execution_count": 120,
167
+ "id": "4d521cc3-1289-4989-829e-f27cd6bcde05",
168
+ "metadata": {},
169
+ "outputs": [],
170
+ "source": [
171
+ "from transformers import AutoTokenizer\n",
172
+ "\n",
173
+ "tokenizer = AutoTokenizer.from_pretrained(\"BAAI/bge-large-en-v1.5\")"
174
+ ]
175
+ },
176
+ {
177
+ "cell_type": "markdown",
178
+ "id": "f5269674-4496-45ad-81f5-5fcfb7665362",
179
+ "metadata": {},
180
+ "source": [
181
+ "# Load data"
182
+ ]
183
+ },
184
+ {
185
+ "cell_type": "code",
186
+ "execution_count": 5,
187
+ "id": "27ab0473-ad8e-4070-a972-ef4eb003f55c",
188
+ "metadata": {},
189
+ "outputs": [],
190
+ "source": [
191
+ "df = pd.read_csv(\"final_data.csv\")\n",
192
+ "questions = df[\"question\"].to_list()"
193
+ ]
194
+ },
195
+ {
196
+ "cell_type": "code",
197
+ "execution_count": 6,
198
+ "id": "3675ffaa-1606-4f51-86b3-19baa58b797e",
199
+ "metadata": {},
200
+ "outputs": [],
201
+ "source": [
202
+ "with open(\"map_triplet_rb.pkl\",'rb') as f:\n",
203
+ " dct_mapping_triplet = pickle.load(f)\n",
204
+ "with open(\"embedded_ragbench_clean.pkl\",'rb') as f:\n",
205
+ " lst_embedding = pickle.load(f)"
206
+ ]
207
+ },
208
+ {
209
+ "cell_type": "code",
210
+ "execution_count": 7,
211
+ "id": "23313f6c-300f-4e12-b883-fc6df677a4ca",
212
+ "metadata": {},
213
+ "outputs": [
214
+ {
215
+ "data": {
216
+ "text/plain": [
217
+ "(161798, 1024)"
218
+ ]
219
+ },
220
+ "execution_count": 7,
221
+ "metadata": {},
222
+ "output_type": "execute_result"
223
+ }
224
+ ],
225
+ "source": [
226
+ "lst_embedding.shape"
227
+ ]
228
+ },
229
+ {
230
+ "cell_type": "code",
231
+ "execution_count": 7,
232
+ "id": "1c867ac2-14a4-4eb8-8af9-4cfdbf4c42fe",
233
+ "metadata": {},
234
+ "outputs": [],
235
+ "source": [
236
+ "faiss_embeddings = lst_embedding.astype('float32')\n",
237
+ "d = faiss_embeddings.shape[1] # dimension\n",
238
+ "index = faiss.IndexFlatL2(d) # L2 distance index\n",
239
+ "index.add(faiss_embeddings) # add embeddings"
240
+ ]
241
+ },
242
+ {
243
+ "cell_type": "markdown",
244
+ "id": "d38bd5e9-bed9-4213-9b84-d36f44df6064",
245
+ "metadata": {},
246
+ "source": [
247
+ "# Functions"
248
+ ]
249
+ },
250
+ {
251
+ "cell_type": "code",
252
+ "execution_count": 8,
253
+ "id": "4b251e36-6567-40f7-bb32-334e5b342317",
254
+ "metadata": {},
255
+ "outputs": [],
256
+ "source": [
257
+ "def faiss_cosine(query_vector, k=10):\n",
258
+ " query_vector = query_vector.astype('float32')\n",
259
+ " distances, indices = index.search(query_vector, k)\n",
260
+ " return indices.flatten()\n",
261
+ "\t\n",
262
+ "def query_triplet_topk(query, k=10):\n",
263
+ "\tt = tokenizer.encode(query)\n",
264
+ "\tif len(t) > 512:\n",
265
+ "\t\tt = t[:500]\n",
266
+ "\t\tquery = tokenizer.decode(t)\n",
267
+ "\tquery_emb = np.array(embeddings.embed_query(query)).reshape(1,-1)\n",
268
+ "\ttopk_indices_sorted = faiss_cosine(query_emb).tolist()\n",
269
+ "\treturn [dct_mapping_triplet[x] for x in topk_indices_sorted]\n",
270
+ "\n",
271
+ "def format_claim(relations):\n",
272
+ " for rel in relations:\n",
273
+ " rel['r.summary'] = rel['r.summary'].split(\"\\n\\n\")[-1]\n",
274
+ " # return \"\\n\\n\".join(f\"[{i+1}] {doc.page_content}\" for i, doc in enumerate(docs))\n",
275
+ " return \"\\n\\n\".join(f\"{idx+1}. {rel['r.summary']}\" for idx, rel in enumerate(relations))\n",
276
+ "\n",
277
+ "class GradeRelationList(BaseModel):\n",
278
+ " \"\"\"List passage index check on retrieved text.\"\"\"\n",
279
+ " passage_idx: str = Field(\n",
280
+ " description=\"The passage index of relevant chunks, seperated by a comma\"\n",
281
+ " )\n",
282
+ "\t\n",
283
+ "def check_grade_lst(question, text):\n",
284
+ " prompt_text_grader = PromptTemplate(template=\"\"\"<|begin_of_text|><|start_header_id|>system<|end_header_id|> You are a grader assessing relevance \n",
285
+ " of a list of retrieved passages to a user question. The goal is to filter out erroneous retrievals. \\n\n",
286
+ " Return only the passage index whether the passage is relevant to the question. \\n\n",
287
+ " Provide the output as a JSON with passage index seperated by a comma and no premable or explaination.\n",
288
+ " <|eot_id|><|start_header_id|>user<|end_header_id|>\n",
289
+ " Here is the list of retrieved text: \\n\\n {text} \\n\\n\n",
290
+ " Here is the user question: {question} \\n <|eot_id|><|start_header_id|>assistant<|end_header_id|>\n",
291
+ " \"\"\",\n",
292
+ " input_variables=[\"question\", \"text\"]\n",
293
+ " )\n",
294
+ " structured_llm_grader = llm.with_structured_output(GradeRelationList)\n",
295
+ " relation_grader = prompt_text_grader | structured_llm_grader \n",
296
+ " result = relation_grader.invoke({\"question\": question, \"text\": text})\n",
297
+ " # print(result)\n",
298
+ " return result"
299
+ ]
300
+ },
301
+ {
302
+ "cell_type": "code",
303
+ "execution_count": 126,
304
+ "id": "82f27027-7a59-4321-a2ec-40fb20304476",
305
+ "metadata": {
306
+ "scrolled": true
307
+ },
308
+ "outputs": [
309
+ {
310
+ "data": {
311
+ "text/plain": [
312
+ "[36542, 31875, 157831, 123606, 157822, 157830, 36675, 157824, 85354, 79379]"
313
+ ]
314
+ },
315
+ "execution_count": 126,
316
+ "metadata": {},
317
+ "output_type": "execute_result"
318
+ }
319
+ ],
320
+ "source": [
321
+ "query_emb = np.array(embeddings.embed_query(questions[1])).reshape(1,-1)\n",
322
+ "topk_indices_sorted = faiss_cosine(query_emb).tolist()\n",
323
+ "topk_indices_sorted"
324
+ ]
325
+ },
326
+ {
327
+ "cell_type": "code",
328
+ "execution_count": 127,
329
+ "id": "521d7e93-71df-48e2-9fbc-387053845ab2",
330
+ "metadata": {},
331
+ "outputs": [
332
+ {
333
+ "data": {
334
+ "text/plain": [
335
+ "{'n': {'node_type': 'Disease', 'id': 'Covid-19'},\n",
336
+ " 'r': ({'node_type': 'Disease', 'id': 'Covid-19'},\n",
337
+ " 'ORIGINATED_FROM',\n",
338
+ " {'node_type': 'Country', 'id': 'China'}),\n",
339
+ " 'r.summary': '{text: \"Covid-19 originated from China, where 14 out of 38 studied cases were infected, prior to its spread to Europe, where it was first detected on January 27, 2020, and had reported 47 cases across nine countries by February 21, 2020.\"}',\n",
340
+ " 'm': {'node_type': 'Country', 'id': 'China'}}"
341
+ ]
342
+ },
343
+ "execution_count": 127,
344
+ "metadata": {},
345
+ "output_type": "execute_result"
346
+ }
347
+ ],
348
+ "source": [
349
+ "dct_mapping_triplet[36542]"
350
+ ]
351
+ },
352
+ {
353
+ "cell_type": "code",
354
+ "execution_count": 128,
355
+ "id": "9a9ce274-24af-4b33-aca5-58b3d9c5d905",
356
+ "metadata": {},
357
+ "outputs": [
358
+ {
359
+ "data": {
360
+ "application/vnd.jupyter.widget-view+json": {
361
+ "model_id": "19f099f376414e0bb6badf99a1d1496c",
362
+ "version_major": 2,
363
+ "version_minor": 0
364
+ },
365
+ "text/plain": [
366
+ " 0%| | 0/11802 [00:00<?, ?it/s]"
367
+ ]
368
+ },
369
+ "metadata": {},
370
+ "output_type": "display_data"
371
+ },
372
+ {
373
+ "name": "stderr",
374
+ "output_type": "stream",
375
+ "text": [
376
+ "Token indices sequence length is longer than the specified maximum sequence length for this model (593 > 512). Running this sequence through the model will result in indexing errors\n"
377
+ ]
378
+ }
379
+ ],
380
+ "source": [
381
+ "# Query top 10 triplet\n",
382
+ "# lst_triplet_top_k_cos = []\n",
383
+ "# for i in tqdm(questions):\n",
384
+ "# lst_triplet_top_k_cos.append(query_triplet_topk(i))"
385
+ ]
386
+ },
387
+ {
388
+ "cell_type": "code",
389
+ "execution_count": 129,
390
+ "id": "cceb5693-5c83-4175-8362-1b7a2ab442f7",
391
+ "metadata": {},
392
+ "outputs": [],
393
+ "source": [
394
+ "# with open(\"top10_rb.pkl\", \"wb\") as f:\n",
395
+ "# \tpickle.dump(lst_triplet_top_k_cos, f)"
396
+ ]
397
+ },
398
+ {
399
+ "cell_type": "code",
400
+ "execution_count": 131,
401
+ "id": "0d5651de-27a3-430c-865b-a0c8d54dfdbb",
402
+ "metadata": {},
403
+ "outputs": [],
404
+ "source": [
405
+ "map_triplet = {}\n",
406
+ "for i,j in zip(lst_triplet_top_k_cos, questions):\n",
407
+ " map_triplet[j] = i"
408
+ ]
409
+ },
410
+ {
411
+ "cell_type": "code",
412
+ "execution_count": 149,
413
+ "id": "e7e7dfd6-983a-4fb8-91b1-34b23b8faa14",
414
+ "metadata": {},
415
+ "outputs": [],
416
+ "source": [
417
+ "# # Filter triplet\n",
418
+ "# f_triplet = []\n",
419
+ "# for q in tqdm(questions, total=len(questions)):\n",
420
+ "# \trelations = map_triplet[q]\n",
421
+ "# \tcontext = check_grade_lst(q, format_claim(relations)).passage_idx\n",
422
+ "# \tcontext = [int(x) for x in context.split(\",\")]\n",
423
+ "# \tcheck_rels = [relations[x-1] for x in context]\n",
424
+ "# \tf_triplet.append(check_rels)\n",
425
+ "# \tif len(f_triplet) % 10 == 0:\n",
426
+ "# \t\twith open(\"top10_filtered_rb.pkl\", \"wb\") as f:\n",
427
+ "# \t\t\tpickle.dump(f_triplet, f)"
428
+ ]
429
+ },
430
+ {
431
+ "cell_type": "code",
432
+ "execution_count": 163,
433
+ "id": "51dde469-38a2-4268-87ea-429b8b2b5c61",
434
+ "metadata": {},
435
+ "outputs": [
436
+ {
437
+ "data": {
438
+ "text/plain": [
439
+ "'/home/ubuntu/work/minhbc/doan'"
440
+ ]
441
+ },
442
+ "execution_count": 163,
443
+ "metadata": {},
444
+ "output_type": "execute_result"
445
+ }
446
+ ],
447
+ "source": [
448
+ "import os\n",
449
+ "\n",
450
+ "os.getcwd()"
451
+ ]
452
+ },
453
+ {
454
+ "cell_type": "code",
455
+ "execution_count": 9,
456
+ "id": "2955959b-54e1-4c49-bef8-42afa30c6e85",
457
+ "metadata": {},
458
+ "outputs": [],
459
+ "source": [
460
+ "import uuid\n",
461
+ "def filter_triplet(q):\n",
462
+ "\tglobal map_triplet\n",
463
+ "\trelations = map_triplet[q]\n",
464
+ "\ttry:\n",
465
+ "\t\tcontext = check_grade_lst(q, format_claim(relations)).passage_idx\n",
466
+ "\t\tcontext = [int(x) for x in context.split(\",\")]\n",
467
+ "\t\t# Validate context indices\n",
468
+ "\t\t# if any(x <= 0 or x > len(relations) for x in context):\n",
469
+ "\t\t# raise ValueError(\"Invalid index in context\")\n",
470
+ "\t\tf = [relations[x - 1] for x in context]\n",
471
+ "\texcept Exception as e:\n",
472
+ "\t\tprint(f\"Error processing {q}: {e}\")\n",
473
+ "\t\tf = relations # fallback: use all relations\n",
474
+ "\n",
475
+ "\tfile_name = uuid.uuid4()\n",
476
+ "\tto_save = (q, f)\n",
477
+ "\twith open(f\"/home/ubuntu/work/minhbc/doan/ftriplet_318b/{file_name}.pkl\", \"wb\") as file:\n",
478
+ "\t\tpickle.dump(to_save, file)\n",
479
+ "\treturn f"
480
+ ]
481
+ },
482
+ {
483
+ "cell_type": "code",
484
+ "execution_count": 8,
485
+ "id": "416ae401-edf4-4c0c-b992-d4f3b0127e7e",
486
+ "metadata": {},
487
+ "outputs": [],
488
+ "source": [
489
+ "# with Pool(5) as pool:\n",
490
+ "# f_triplets = list(tqdm(pool.imap(filter_triplet, questions), total=len(questions)))"
491
+ ]
492
+ },
493
+ {
494
+ "cell_type": "code",
495
+ "execution_count": 192,
496
+ "id": "90dd9f7d-873d-4188-948c-69e3a108e650",
497
+ "metadata": {},
498
+ "outputs": [],
499
+ "source": [
500
+ "# with open(\"top10_filtered_rb.pkl\", \"wb\") as f:\n",
501
+ "# \tpickle.dump(f_triplets, f)"
502
+ ]
503
+ },
504
+ {
505
+ "cell_type": "markdown",
506
+ "id": "c5fb4a21-17f2-4c33-9e73-7843c9f878df",
507
+ "metadata": {},
508
+ "source": [
509
+ "# KG completion"
510
+ ]
511
+ },
512
+ {
513
+ "cell_type": "code",
514
+ "execution_count": 10,
515
+ "id": "272dbecd-b6aa-4d66-b153-630c1660d08a",
516
+ "metadata": {},
517
+ "outputs": [],
518
+ "source": [
519
+ "from collections import defaultdict, deque"
520
+ ]
521
+ },
522
+ {
523
+ "cell_type": "code",
524
+ "execution_count": 11,
525
+ "id": "965d77e0-062c-4d53-8e14-4424f51c7950",
526
+ "metadata": {},
527
+ "outputs": [],
528
+ "source": [
529
+ "def build_undirected_graph(triplets):\n",
530
+ "\t\"\"\"\n",
531
+ "\tXây đồ thị vô hướng:\n",
532
+ "\t- Mỗi cạnh (m -r-> n) được thêm cả (m->n) và (n->m với r_rev).\n",
533
+ "\t\"\"\"\n",
534
+ "\tgraph = defaultdict(list)\n",
535
+ "\tfor t in triplets:\n",
536
+ "\t\tm_id = t['m']['id']\n",
537
+ "\t\tn_id = t['n']['id']\n",
538
+ "\t\trel = t['r']['id']\n",
539
+ "\t\tsummary = t['r']['summary']\n",
540
+ "\t\t\n",
541
+ "\t\t# chiều xuôi\n",
542
+ "\t\tgraph[m_id].append({\n",
543
+ "\t\t\t'm': {'id': m_id},\n",
544
+ "\t\t\t'r': {'id': rel, 'summary': summary},\n",
545
+ "\t\t\t'n': {'id': n_id}\n",
546
+ "\t\t})\n",
547
+ "\t\t# chiều ngược\n",
548
+ "\t\tgraph[n_id].append({\n",
549
+ "\t\t\t'm': {'id': n_id},\n",
550
+ "\t\t\t'r': {'id': f\"{rel}_rev\", 'summary': summary},\n",
551
+ "\t\t\t'n': {'id': m_id}\n",
552
+ "\t\t})\n",
553
+ "\treturn graph\n",
554
+ "def bfs_all_paths(KG, start, end, max_length):\n",
555
+ "\t\"\"\"\n",
556
+ "\tTrả về list các đường đi (mỗi đường là list các triplet-dicts)\n",
557
+ "\ttừ start -> end với số bước < max_length.\n",
558
+ "\t\"\"\"\n",
559
+ "\tif start not in KG or end not in KG:\n",
560
+ "\t\treturn []\n",
561
+ "\n",
562
+ "\tall_paths = []\n",
563
+ "\tqueue = deque([(start, [])]) # (node hiện tại, path_so_far)\n",
564
+ "\n",
565
+ "\twhile queue:\n",
566
+ "\t\tcurrent, path = queue.popleft()\n",
567
+ "\t\t# print(f\"Cur: {current}\")\n",
568
+ "\t\t# print(f\"Path: {path}\")\n",
569
+ "\t\t# print(f\"KG curr: {KG[current]}\")\n",
570
+ "\t\t\n",
571
+ "\t\tif len(path) >= max_length:\n",
572
+ "\t\t\tcontinue\n",
573
+ "\n",
574
+ "\t\tfor triplet in KG[current]:\n",
575
+ "\t\t\tneighbor = triplet['n']['id']\n",
576
+ "\t\t\t# print(f\"Neigbor: {neighbor}\")\n",
577
+ "\t\t\tnew_path = path + [triplet]\n",
578
+ "\t\t\tif neighbor == end:\n",
579
+ "\t\t\t\tall_paths.append(new_path)\n",
580
+ "\t\t\telse:\n",
581
+ "\t\t\t\tvisited = {t['m']['id'] for t in path} | {t['n']['id'] for t in path}\n",
582
+ "\t\t\t\t# print(f\"visited: {visited}\")\n",
583
+ "\t\t\t\tif neighbor not in visited:\n",
584
+ "\t\t\t\t\tqueue.append((neighbor, new_path))\n",
585
+ "\t\t# print(\"*\"*50)\n",
586
+ "\tfinal = []\n",
587
+ "\tif all_paths is not None:\n",
588
+ "\t\tfor p in all_paths:\n",
589
+ "\t\t\tif p not in final:\n",
590
+ "\t\t\t\tfinal.append(p)\n",
591
+ "\t\tall_paths = final\n",
592
+ "\treturn all_paths\n",
593
+ "\n",
594
+ "# ----------------------------------------\n",
595
+ "# Step 5: Hàm mở rộng subgraph theo độ liên quan\n",
596
+ "# ----------------------------------------\n",
597
+ "def relevance_guided_path_addition(KG, T, question, model, K=100, max_path_length=5):\n",
598
+ "\t\"\"\"\n",
599
+ "\tKG: dict[node_id] -> list of triplet-dicts {'m':{'id'}, 'r':{'id','summary'}, 'n':{'id'}}\n",
600
+ "\tT: list of triplet-dicts (subgraph gốc)\n",
601
+ "\tquestion: str hoặc None\n",
602
+ "\tmodel: object có .embed_query(str) và .encode(list_of_str)\n",
603
+ "\tK: số triplet mới tối đa thêm vào\n",
604
+ "\tmax_path_length: độ dài tối đa mỗi path\n",
605
+ "\tTrả về H = T + selected_triplets\n",
606
+ "\t\"\"\"\n",
607
+ "\t# Step 1: Tập entity từ T\n",
608
+ "\tE_T = {t['m']['id'] for t in T} | {t['n']['id'] for t in T}\n",
609
+ "\t# print(E_T)\n",
610
+ "\n",
611
+ "\t# Step 2: Embedding câu hỏi (nếu có)\n",
612
+ "\tquestion_emb = np.array(model.embed_query(question)) if question else None\n",
613
+ "\n",
614
+ "\t# Step 3: Tạo set key của T để kiểm tra nhanh\n",
615
+ "\tT_keys = {(t['m']['id'], t['r'][\"id\"], t['n']['id']) for t in T}\n",
616
+ "\n",
617
+ "\t# Step 4: Tìm tất cả đường đi giữa mọi cặp trong E_T\n",
618
+ "\tall_paths = []\n",
619
+ "\tfor start in E_T:\n",
620
+ "\t\tfor end in E_T:\n",
621
+ "\t\t\tif start == end:\n",
622
+ "\t\t\t\tcontinue\n",
623
+ "\t\t\tall_paths.extend(bfs_all_paths(KG, start, end, max_path_length))\n",
624
+ "\n",
625
+ "\tif not all_paths:\n",
626
+ "\t\t# print(\"H\")\n",
627
+ "\t\treturn T\n",
628
+ "\n",
629
+ "\t# Step 6: Score từng đường đi\n",
630
+ "\tpath_scores = []\n",
631
+ "\tfor path in all_paths:\n",
632
+ "\t\tsummaries = [triplet['r']['summary'] for triplet in path]\n",
633
+ "\t\tembs = model.embed_query(summaries)\n",
634
+ "\t\tembs = np.array(embs)\n",
635
+ "\t\tif question_emb is not None:\n",
636
+ "\t\t\tsims = cosine_similarity(embs, question_emb.reshape(1, -1)).flatten()\n",
637
+ "\t\t\tscore = float(np.mean(sims)) if sims.size else 0.0\n",
638
+ "\t\telse:\n",
639
+ "\t\t\tscore = 0.0\n",
640
+ "\t\tpath_scores.append((path, score))\n",
641
+ "\n",
642
+ "\t# Step 7: Chọn K triplet mới theo thứ tự score giảm dần\n",
643
+ "\tpath_scores.sort(key=lambda x: x[1], reverse=True)\n",
644
+ "\tpath_scores = path_scores[(len(T)*2-1):]\n",
645
+ "\tselected = []\n",
646
+ "\tselected_keys = set()\n",
647
+ "\tfor path, _ in path_scores:\n",
648
+ "\t\tfor triplet in path:\n",
649
+ "\t\t\tkey = (triplet['m']['id'], triplet['r']['id'], triplet['n']['id'])\n",
650
+ "\t\t\tif key not in T_keys and key not in selected_keys:\n",
651
+ "\t\t\t\tselected.append(triplet)\n",
652
+ "\t\t\t\tselected_keys.add(key)\n",
653
+ "\t\t\t\tif len(selected) >= K:\n",
654
+ "\t\t\t\t\tbreak\n",
655
+ "\t\tif len(selected) >= K:\n",
656
+ "\t\t\tbreak\n",
657
+ "\n",
658
+ "\t# Step 8: Trả về subgraph hoàn chỉnh\n",
659
+ "\tH = T + selected\n",
660
+ "\treturn H\n",
661
+ "\n",
662
+ "def subgraph_completion(task):\n",
663
+ "\tglobal KG\n",
664
+ "\tglobal model\n",
665
+ "\tT, ques, K, max_path_length = task[0], task[1], task[2], task[3]\n",
666
+ "\tresult = relevance_guided_path_addition(KG, T, ques, model, K, max_path_length)\n",
667
+ "\tto_save = (ques, result)\n",
668
+ "\tfile_name = uuid.uuid4()\n",
669
+ "\twith open(f\"/home/ubuntu/work/minhbc/doan/sgcp_318b/{file_name}.pkl\", \"wb\") as file:\n",
670
+ "\t\tpickle.dump(to_save, file)\n",
671
+ "\treturn result\n",
672
+ "\t\n",
673
+ "\t"
674
+ ]
675
+ },
676
+ {
677
+ "cell_type": "code",
678
+ "execution_count": 12,
679
+ "id": "fdbdacc7-2cfb-4168-ac2c-9a816cb9cbae",
680
+ "metadata": {},
681
+ "outputs": [],
682
+ "source": [
683
+ "with open(\"runned.pkl\", \"rb\") as f:\n",
684
+ "\trunned = pickle.load(f)"
685
+ ]
686
+ },
687
+ {
688
+ "cell_type": "code",
689
+ "execution_count": 13,
690
+ "id": "a2f4d12a-1b1d-4852-80c2-e15ae603f043",
691
+ "metadata": {},
692
+ "outputs": [],
693
+ "source": [
694
+ "with open(\"rb_filtered_318b.pkl\", \"rb\") as file:\n",
695
+ "\tftriplets = pickle.load(file)"
696
+ ]
697
+ },
698
+ {
699
+ "cell_type": "code",
700
+ "execution_count": 14,
701
+ "id": "4bd3a65d-0cb6-4379-9b67-d6bd0c1df340",
702
+ "metadata": {},
703
+ "outputs": [
704
+ {
705
+ "data": {
706
+ "application/vnd.jupyter.widget-view+json": {
707
+ "model_id": "ed50a0b5016e457ab206ce0dd422f837",
708
+ "version_major": 2,
709
+ "version_minor": 0
710
+ },
711
+ "text/plain": [
712
+ " 0%| | 0/11802 [00:00<?, ?it/s]"
713
+ ]
714
+ },
715
+ "metadata": {},
716
+ "output_type": "display_data"
717
+ }
718
+ ],
719
+ "source": [
720
+ "n_questions, n_ftriplets = [], []\n",
721
+ "for i in tqdm(range(len(questions))):\n",
722
+ "\tif questions[i] not in runned:\n",
723
+ "\t\tn_questions.append(questions[i])\n",
724
+ "\t\tn_ftriplets.append(ftriplets[i])\n",
725
+ "\t\t"
726
+ ]
727
+ },
728
+ {
729
+ "cell_type": "code",
730
+ "execution_count": 16,
731
+ "id": "0d6a9178-4516-4a79-ad72-9116035eaaea",
732
+ "metadata": {},
733
+ "outputs": [
734
+ {
735
+ "data": {
736
+ "text/plain": [
737
+ "(11026, 11026)"
738
+ ]
739
+ },
740
+ "execution_count": 16,
741
+ "metadata": {},
742
+ "output_type": "execute_result"
743
+ }
744
+ ],
745
+ "source": [
746
+ "len(n_questions), len(n_ftriplets)"
747
+ ]
748
+ },
749
+ {
750
+ "cell_type": "code",
751
+ "execution_count": 17,
752
+ "id": "ae5afc14-e79e-4ca3-b3da-238a5a751c3d",
753
+ "metadata": {},
754
+ "outputs": [
755
+ {
756
+ "data": {
757
+ "application/vnd.jupyter.widget-view+json": {
758
+ "model_id": "c39c4610aedd4e33840a03a9f3c830b7",
759
+ "version_major": 2,
760
+ "version_minor": 0
761
+ },
762
+ "text/plain": [
763
+ " 0%| | 0/11026 [00:00<?, ?it/s]"
764
+ ]
765
+ },
766
+ "metadata": {},
767
+ "output_type": "display_data"
768
+ },
769
+ {
770
+ "data": {
771
+ "text/plain": [
772
+ "11026"
773
+ ]
774
+ },
775
+ "execution_count": 17,
776
+ "metadata": {},
777
+ "output_type": "execute_result"
778
+ }
779
+ ],
780
+ "source": [
781
+ "# Format filter triplet\n",
782
+ "\n",
783
+ "# len(ftriplets)\n",
784
+ "\n",
785
+ "formatted_ftriplets = []\n",
786
+ "for recs in tqdm(n_ftriplets, total=len(n_ftriplets)):\n",
787
+ "\tformatted_rec = []\n",
788
+ "\tfor rec in recs:\n",
789
+ "\t\tsubj = rec['r'][0]['id']\n",
790
+ "\t\trel = rec['r'][1]\n",
791
+ "\t\tobj = rec['r'][2]['id']\n",
792
+ "\t\tsummary = rec['r.summary']\n",
793
+ "\t\tformatted_rec.append({\n",
794
+ "\t\t\t'm': {'id': subj},\n",
795
+ "\t\t\t'r': {'id': rel, 'summary': summary},\n",
796
+ "\t\t\t'n': {'id': obj}\n",
797
+ "\t\t})\n",
798
+ "\tformatted_ftriplets.append(formatted_rec)\n",
799
+ "len(formatted_ftriplets)"
800
+ ]
801
+ },
802
+ {
803
+ "cell_type": "code",
804
+ "execution_count": 18,
805
+ "id": "e05057b6-b363-4a4c-bfcb-fec3e94b5330",
806
+ "metadata": {},
807
+ "outputs": [
808
+ {
809
+ "data": {
810
+ "application/vnd.jupyter.widget-view+json": {
811
+ "model_id": "c28585cc46424213884b132e337b9799",
812
+ "version_major": 2,
813
+ "version_minor": 0
814
+ },
815
+ "text/plain": [
816
+ " 0%| | 0/161798 [00:00<?, ?it/s]"
817
+ ]
818
+ },
819
+ "metadata": {},
820
+ "output_type": "display_data"
821
+ }
822
+ ],
823
+ "source": [
824
+ "KG_data = []\n",
825
+ "for rec in tqdm(dct_mapping_triplet, total=len(dct_mapping_triplet)):\n",
826
+ " subj = rec['r'][0]['id']\n",
827
+ " rel = rec['r'][1]\n",
828
+ " obj = rec['r'][2]['id']\n",
829
+ " summary = rec['r.summary']\n",
830
+ " KG_data.append({\n",
831
+ " 'm': {'id': subj},\n",
832
+ " 'r': {'id': rel, 'summary': summary},\n",
833
+ " 'n': {'id': obj}\n",
834
+ " })\n",
835
+ "KG = build_undirected_graph(KG_data)"
836
+ ]
837
+ },
838
+ {
839
+ "cell_type": "code",
840
+ "execution_count": null,
841
+ "id": "a5bc5d2a-c67b-4877-823c-1609e046056b",
842
+ "metadata": {
843
+ "scrolled": true
844
+ },
845
+ "outputs": [
846
+ {
847
+ "data": {
848
+ "application/vnd.jupyter.widget-view+json": {
849
+ "model_id": "0714e95bf74646ad9198e5f77dc02f26",
850
+ "version_major": 2,
851
+ "version_minor": 0
852
+ },
853
+ "text/plain": [
854
+ " 0%| | 0/11026 [00:00<?, ?it/s]"
855
+ ]
856
+ },
857
+ "metadata": {},
858
+ "output_type": "display_data"
859
+ }
860
+ ],
861
+ "source": [
862
+ "model = embeddings\n",
863
+ "\n",
864
+ "tasks = [(formatted_ftriplets[i], n_questions[i], 10, 2) for i in range(len(n_questions))]\n",
865
+ "with Pool(20) as pool:\n",
866
+ "\tsgcp = list(tqdm(pool.imap(subgraph_completion, tasks), total =len(tasks)))"
867
+ ]
868
+ },
869
+ {
870
+ "cell_type": "code",
871
+ "execution_count": null,
872
+ "id": "03a2650f-638d-4812-abe5-794634232462",
873
+ "metadata": {},
874
+ "outputs": [],
875
+ "source": [
876
+ "with open(\"sgcp_318b.pkl\", \"wb\") as file:\n",
877
+ "\tpickle.dump(sgcp, file)"
878
+ ]
879
+ },
880
+ {
881
+ "cell_type": "code",
882
+ "execution_count": 208,
883
+ "id": "ed560d4d-8caf-49d3-a913-15874b953209",
884
+ "metadata": {},
885
+ "outputs": [
886
+ {
887
+ "data": {
888
+ "text/plain": [
889
+ "[{'m': {'id': 'Immune Response'},\n",
890
+ " 'r': {'id': 'DETERMINES',\n",
891
+ " 'summary': '\"text\": \"The intensity of the immune response, which can be influenced by host genetic factors, determines viral clearance in individuals infected with Hepatitis C Virus, with a strong response leading to spontaneous clearance in up to 15% of cases.\"}'},\n",
892
+ " 'n': {'id': 'Viral Clearance'}},\n",
893
+ " {'m': {'id': 'Oral Swabs'},\n",
894
+ " 'r': {'id': 'INDICATES',\n",
895
+ " 'summary': '{\"text\": \"The presence of viral antigen in oral swabs indicates viral clearance, which is officially confirmed when two consecutive oral swab tests, taken within a 24-hour interval, are negative.\"}'},\n",
896
+ " 'n': {'id': 'Viral Clearance'}},\n",
897
+ " {'m': {'id': 'Host'},\n",
898
+ " 'r': {'id': 'INFECTED_BY',\n",
899
+ " 'summary': '{text: \"The host can be infected by HCV, although in up to 15% of acutely infected individuals, the host\\'s immune system is able to spontaneously clear the virus, with factors such as the intensity of the immune response and genetic factors playing a role in determining viral clearance.\"}'},\n",
900
+ " 'n': {'id': 'Hcv'}}]"
901
+ ]
902
+ },
903
+ "execution_count": 208,
904
+ "metadata": {},
905
+ "output_type": "execute_result"
906
+ }
907
+ ],
908
+ "source": [
909
+ "T = formatted_ftriplets[0]\n",
910
+ "ques = questions[0]\n",
911
+ "T"
912
+ ]
913
+ },
914
+ {
915
+ "cell_type": "code",
916
+ "execution_count": null,
917
+ "id": "8461606b-69ec-474a-9682-27b5022a12df",
918
+ "metadata": {},
919
+ "outputs": [],
920
+ "source": []
921
+ },
922
+ {
923
+ "cell_type": "code",
924
+ "execution_count": 207,
925
+ "id": "80728aa1-7870-45f4-84ef-359bd08963aa",
926
+ "metadata": {},
927
+ "outputs": [
928
+ {
929
+ "data": {
930
+ "text/plain": [
931
+ "[{'m': {'id': 'Immune Response'},\n",
932
+ " 'r': {'id': 'DETERMINES',\n",
933
+ " 'summary': '\"text\": \"The intensity of the immune response, which can be influenced by host genetic factors, determines viral clearance in individuals infected with Hepatitis C Virus, with a strong response leading to spontaneous clearance in up to 15% of cases.\"}'},\n",
934
+ " 'n': {'id': 'Viral Clearance'}},\n",
935
+ " {'m': {'id': 'Oral Swabs'},\n",
936
+ " 'r': {'id': 'INDICATES',\n",
937
+ " 'summary': '{\"text\": \"The presence of viral antigen in oral swabs indicates viral clearance, which is officially confirmed when two consecutive oral swab tests, taken within a 24-hour interval, are negative.\"}'},\n",
938
+ " 'n': {'id': 'Viral Clearance'}},\n",
939
+ " {'m': {'id': 'Host'},\n",
940
+ " 'r': {'id': 'INFECTED_BY',\n",
941
+ " 'summary': '{text: \"The host can be infected by HCV, although in up to 15% of acutely infected individuals, the host\\'s immune system is able to spontaneously clear the virus, with factors such as the intensity of the immune response and genetic factors playing a role in determining viral clearance.\"}'},\n",
942
+ " 'n': {'id': 'Hcv'}},\n",
943
+ " {'m': {'id': 'Viral Clearance'},\n",
944
+ " 'r': {'id': 'DETERMINES_rev',\n",
945
+ " 'summary': '\"text\": \"The intensity of the immune response, which can be influenced by host genetic factors, determines viral clearance in individuals infected with Hepatitis C Virus, with a strong response leading to spontaneous clearance in up to 15% of cases.\"}'},\n",
946
+ " 'n': {'id': 'Immune Response'}},\n",
947
+ " {'m': {'id': 'Viral Clearance'},\n",
948
+ " 'r': {'id': 'INDICATES_rev',\n",
949
+ " 'summary': '{\"text\": \"The presence of viral antigen in oral swabs indicates viral clearance, which is officially confirmed when two consecutive oral swab tests, taken within a 24-hour interval, are negative.\"}'},\n",
950
+ " 'n': {'id': 'Oral Swabs'}},\n",
951
+ " {'m': {'id': 'Hcv'},\n",
952
+ " 'r': {'id': 'INFECTED_BY_rev',\n",
953
+ " 'summary': '{text: \"The host can be infected by HCV, although in up to 15% of acutely infected individuals, the host\\'s immune system is able to spontaneously clear the virus, with factors such as the intensity of the immune response and genetic factors playing a role in determining viral clearance.\"}'},\n",
954
+ " 'n': {'id': 'Host'}},\n",
955
+ " {'m': {'id': 'Hcv'},\n",
956
+ " 'r': {'id': 'DETECTED_IN',\n",
957
+ " 'summary': '{\"text\": \"HCV was detected in 81.8% of patients, with a weak and non-statistically significant association with steatosis, according to simple logistic regression analysis.\"}'},\n",
958
+ " 'n': {'id': 'Patients'}},\n",
959
+ " {'m': {'id': 'Patients'},\n",
960
+ " 'r': {'id': 'COLLECTED_FROM_rev',\n",
961
+ " 'summary': '{text: \"Oral swabs were collected from patients who had received around 10 days of medical treatment upon admission, specifically those with 2019-nCoV infection, in order to investigate the dynamic changes of viral presence and antibody levels.\"}'},\n",
962
+ " 'n': {'id': 'Oral Swabs'}},\n",
963
+ " {'m': {'id': 'Oral Swabs'},\n",
964
+ " 'r': {'id': 'COLLECTED_FROM',\n",
965
+ " 'summary': '{text: \"Oral swabs were collected from patients who had received around 10 days of medical treatment upon admission, specifically those with 2019-nCoV infection, in order to investigate the dynamic changes of viral presence and antibody levels.\"}'},\n",
966
+ " 'n': {'id': 'Patients'}},\n",
967
+ " {'m': {'id': 'Patients'},\n",
968
+ " 'r': {'id': 'DETECTED_IN_rev',\n",
969
+ " 'summary': '{\"text\": \"HCV was detected in 81.8% of patients, with a weak and non-statistically significant association with steatosis, according to simple logistic regression analysis.\"}'},\n",
970
+ " 'n': {'id': 'Hcv'}},\n",
971
+ " {'m': {'id': 'Patients'},\n",
972
+ " 'r': {'id': 'TEST_FOR_rev',\n",
973
+ " 'summary': '{\"text\": \"Oral swabs are used to test for the presence of the virus in patients, particularly during early infection, but negative results from oral swabs do not necessarily rule out the possibility of infection, as patients may still shed the virus through the oral-fecal route, highlighting the importance of serological tests, such as viral IgM and IgG, to confirm infection.\"}'},\n",
974
+ " 'n': {'id': 'Oral Swabs'}},\n",
975
+ " {'m': {'id': 'Oral Swabs'},\n",
976
+ " 'r': {'id': 'TEST_FOR',\n",
977
+ " 'summary': '{\"text\": \"Oral swabs are used to test for the presence of the virus in patients, particularly during early infection, but negative results from oral swabs do not necessarily rule out the possibility of infection, as patients may still shed the virus through the oral-fecal route, highlighting the importance of serological tests, such as viral IgM and IgG, to confirm infection.\"}'},\n",
978
+ " 'n': {'id': 'Patients'}},\n",
979
+ " {'m': {'id': 'Hcv'},\n",
980
+ " 'r': {'id': 'HAS_DISEASE_rev',\n",
981
+ " 'summary': '{text: \"The patients in the study were diagnosed with HCV, a disease that was treated with interferon alpha-2b and monitored through serum HCV-RNA testing and alanine aminotransferase levels to assess sustained response.\"}'},\n",
982
+ " 'n': {'id': 'Patients'}}]"
983
+ ]
984
+ },
985
+ "execution_count": 207,
986
+ "metadata": {},
987
+ "output_type": "execute_result"
988
+ }
989
+ ],
990
+ "source": [
991
+ "\n",
992
+ "relevance_guided_path_addition(KG, T, ques, embeddings, 10, 2)"
993
+ ]
994
+ },
995
+ {
996
+ "cell_type": "code",
997
+ "execution_count": null,
998
+ "id": "2945c9ce-4c42-402d-a1c4-452f5f52a78c",
999
+ "metadata": {},
1000
+ "outputs": [],
1001
+ "source": []
1002
+ }
1003
+ ],
1004
+ "metadata": {
1005
+ "kernelspec": {
1006
+ "display_name": "Python 3 (ipykernel)",
1007
+ "language": "python",
1008
+ "name": "python3"
1009
+ },
1010
+ "language_info": {
1011
+ "codemirror_mode": {
1012
+ "name": "ipython",
1013
+ "version": 3
1014
+ },
1015
+ "file_extension": ".py",
1016
+ "mimetype": "text/x-python",
1017
+ "name": "python",
1018
+ "nbconvert_exporter": "python",
1019
+ "pygments_lexer": "ipython3",
1020
+ "version": "3.11.5"
1021
+ }
1022
+ },
1023
+ "nbformat": 4,
1024
+ "nbformat_minor": 5
1025
+ }
top10_rb.pkl ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:534065e4e7f8099a2dbd7b3df3efe86f87126dcc8b2f07bb119f03e79e96dea7
3
+ size 16551858