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 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# JACKET V1 のデータセットに wikipedia のコンテキストを追加したデータセットの作成\n",
    "\n",
    "- https://sites.google.com/view/project-aio/dataset?authuser=0\n",
    "\n",
    "の CC BY-SA 4.0 DEED 該当データをもとに、Wikipedia のコンテキスト追加した HuggingFace Dataset を作成する\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "# JAQKET データセットを取得\n",
    "\n",
    "from dataclasses import dataclass\n",
    "import json\n",
    "import urllib.request\n",
    "import random\n",
    "\n",
    "random.seed(42)\n",
    "\n",
    "# https://sites.google.com/view/project-aio/dataset?authuser=0\n",
    "# 以下のURLのデータは、ライセンスが CC BY-SA 4.0 DEED\n",
    "\n",
    "jaqket_urls = [\n",
    "    \"https://jaqket.s3.ap-northeast-1.amazonaws.com/data/aio_02/aio_01_dev.jsonl\",\n",
    "    \"https://jaqket.s3.ap-northeast-1.amazonaws.com/data/aio_02/aio_01_test.jsonl\",\n",
    "    \"https://jaqket.s3.ap-northeast-1.amazonaws.com/data/aio_02/aio_01_unused.jsonl\",\n",
    "]\n",
    "\n",
    "\n",
    "@dataclass\n",
    "class JaqketQuestion_:\n",
    "    qid: str\n",
    "    question: str\n",
    "    original_question: str\n",
    "    answer_entity: str\n",
    "    answer_candidates: list[str]\n",
    "    answer_candidates_shuffled: list[str]\n",
    "    label: int\n",
    "    original_answer: str | None = None\n",
    "\n",
    "\n",
    "@dataclass\n",
    "class JaqketQuestion:\n",
    "    qid: str\n",
    "    competition: str\n",
    "    timestamp: str\n",
    "    section: str\n",
    "    number: str\n",
    "    original_question: str\n",
    "    original_answer: str | None\n",
    "    original_additional_info: str | None\n",
    "    question: str\n",
    "    answers: list[str]\n",
    "\n",
    "\n",
    "def load_jaqket(urls: list[str]):\n",
    "    res = []\n",
    "    for url in urls:\n",
    "        with urllib.request.urlopen(url) as f:\n",
    "            # f は 1行ごとに処理\n",
    "            data = [json.loads(line.decode(\"utf-8\")) for line in f]\n",
    "        for d in data:\n",
    "            try:\n",
    "                res.append(JaqketQuestion(**d))\n",
    "            except Exception as e:\n",
    "                # d.keys\n",
    "                print(d.keys())\n",
    "                raise e\n",
    "    return res\n",
    "\n",
    "\n",
    "jacket_data = load_jaqket(jaqket_urls)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(4600, 10)"
      ]
     },
     "execution_count": 2,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "import pandas as pd\n",
    "\n",
    "jacket_df = pd.DataFrame(jacket_data)\n",
    "jacket_df.shape"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>qid</th>\n",
       "      <th>competition</th>\n",
       "      <th>timestamp</th>\n",
       "      <th>section</th>\n",
       "      <th>number</th>\n",
       "      <th>original_question</th>\n",
       "      <th>original_answer</th>\n",
       "      <th>original_additional_info</th>\n",
       "      <th>question</th>\n",
       "      <th>answers</th>\n",
       "      <th>answer</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>QA20CAPR-0002</td>\n",
       "      <td>第1回AI王</td>\n",
       "      <td>2019/12/25</td>\n",
       "      <td>開発データ問題 (dev1)</td>\n",
       "      <td>2</td>\n",
       "      <td>明治時代に西洋から伝わった「テーブル・ターニング」に起源を持つ占いの一種で、50音表などを記...</td>\n",
       "      <td>コックリさん</td>\n",
       "      <td></td>\n",
       "      <td>明治時代に西洋から伝わった「テーブル・ターニング」に起源を持つ占いの一種で、50音表などを記...</td>\n",
       "      <td>[コックリさん]</td>\n",
       "      <td>コックリさん</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "             qid competition   timestamp         section number  \\\n",
       "0  QA20CAPR-0002      第1回AI王  2019/12/25  開発データ問題 (dev1)      2   \n",
       "\n",
       "                                   original_question original_answer  \\\n",
       "0  明治時代に西洋から伝わった「テーブル・ターニング」に起源を持つ占いの一種で、50音表などを記...          コックリさん   \n",
       "\n",
       "  original_additional_info                                           question  \\\n",
       "0                           明治時代に西洋から伝わった「テーブル・ターニング」に起源を持つ占いの一種で、50音表などを記...   \n",
       "\n",
       "    answers  answer  \n",
       "0  [コックリさん]  コックリさん  "
      ]
     },
     "execution_count": 3,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# none は \"\" に変換\n",
    "jacket_df = jacket_df.fillna(\"\")\n",
    "# answers の最初の一つを入れる\n",
    "jacket_df.loc[:, \"answer\"] = jacket_df[\"answers\"].apply(lambda x: x[0])\n",
    "jacket_df.head(1)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [],
   "source": [
    "train_df = jacket_df"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "/home/yu1/miniconda3/envs/llm-sc/lib/python3.10/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": [
    "from datasets.download import DownloadManager\n",
    "from datasets import load_dataset\n",
    "from sentence_transformers import SentenceTransformer\n",
    "import faiss\n",
    "\n",
    "# wikipedia 日本語データセットのロード\n",
    "wikija_dataset = load_dataset(\n",
    "    path=\"singletongue/wikipedia-utils\",\n",
    "    name=\"passages-c400-jawiki-20230403\",\n",
    "    split=\"train\",\n",
    ")\n",
    "# faiss index のダウンロード\n",
    "dm = DownloadManager()\n",
    "index_local_path = dm.download(\n",
    "    f\"https://huggingface.co/datasets/hotchpotch/wikipedia-passages-jawiki-embeddings/resolve/main/faiss_indexes/passages-c400-jawiki-20230403/multilingual-e5-large-query/index_IVF2048_PQ256.faiss\"\n",
    ")\n",
    "# index_local_path = dm.download(\n",
    "#     f\"https://huggingface.co/datasets/hotchpotch/wikipedia-passages-jawiki-embeddings/resolve/main/faiss_indexes/passages-c400-jawiki-20230403/multilingual-e5-large-passage/index_IVF2048_PQ256.faiss\"\n",
    "# )\n",
    "# faiss index のロード\n",
    "faiss_index = faiss.read_index(index_local_path)\n",
    "\n",
    "# embeddings へ変換するモデルのロード\n",
    "emb_model = SentenceTransformer(\"intfloat/multilingual-e5-large\", device=\"cuda\")\n",
    "emb_model.max_seq_length = 512"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(2, 1024)"
      ]
     },
     "execution_count": 6,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# embeddings へ変換\n",
    "def texts_to_embs(model, texts, prefix=\"query: \"):\n",
    "    texts = [prefix + text for text in texts]\n",
    "    return model.encode(texts, normalize_embeddings=True)\n",
    "\n",
    "\n",
    "texts_to_embs(emb_model, [\"こんにちは\", \"こんばんは\"]).shape"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(3919, 12)"
      ]
     },
     "execution_count": 7,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# wikipedia のデータから、RAG検索して Top-N に正解の単語が含まれているデータのみを抽出する\n",
    "\n",
    "\n",
    "def df_correct_answer_add_context(df, top_n=3):\n",
    "    # faiss index で検索して、top-N に正解があれば、その context を追加してそのデータのみを返す\n",
    "    df = df.copy().reset_index(drop=True)\n",
    "    df[\"context\"] = None\n",
    "    texts = df[\"question\"].tolist()\n",
    "    embs = texts_to_embs(emb_model, texts)\n",
    "    scores, indexes = faiss_index.search(embs, top_n)\n",
    "    for pos, (score, index) in enumerate(zip(scores, indexes)):\n",
    "        df_data = df.iloc[pos]\n",
    "        answer = df_data[\"answer\"]\n",
    "        target_texts = []\n",
    "        for s, i in zip(score, index):\n",
    "            data = wikija_dataset[int(i)]  # type: ignore\n",
    "            target_texts.append(data[\"title\"] + \" \" + data[\"text\"])  # type: ignore\n",
    "        check_text = str(target_texts)\n",
    "        # 検索結果に対象文字列を含むか\n",
    "        if answer in check_text:\n",
    "            df.at[pos, \"context\"] = target_texts\n",
    "    # top3_text が None でないデータのみ返す\n",
    "    return df[df[\"context\"].notnull()]\n",
    "\n",
    "\n",
    "train_df = df_correct_answer_add_context(train_df, 3)\n",
    "train_df.shape"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>qid</th>\n",
       "      <th>question</th>\n",
       "      <th>answer</th>\n",
       "      <th>context</th>\n",
       "      <th>answers</th>\n",
       "      <th>competition</th>\n",
       "      <th>timestamp</th>\n",
       "      <th>section</th>\n",
       "      <th>number</th>\n",
       "      <th>original_question</th>\n",
       "      <th>original_answer</th>\n",
       "      <th>original_additional_info</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>QA20CAPR-0002</td>\n",
       "      <td>明治時代に西洋から伝わった「テーブル・ターニング」に起源を持つ占いの一種で、50音表などを記...</td>\n",
       "      <td>コックリさん</td>\n",
       "      <td>[コックリさん その起源は明確ではないが、レオナルド・ダ・ヴィンチが自著において「テーブル・...</td>\n",
       "      <td>[コックリさん]</td>\n",
       "      <td>第1回AI王</td>\n",
       "      <td>2019/12/25</td>\n",
       "      <td>開発データ問題 (dev1)</td>\n",
       "      <td>2</td>\n",
       "      <td>明治時代に西洋から伝わった「テーブル・ターニング」に起源を持つ占いの一種で、50音表などを記...</td>\n",
       "      <td>コックリさん</td>\n",
       "      <td></td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "             qid                                           question  answer  \\\n",
       "0  QA20CAPR-0002  明治時代に西洋から伝わった「テーブル・ターニング」に起源を持つ占いの一種で、50音表などを記...  コックリさん   \n",
       "\n",
       "                                             context   answers competition  \\\n",
       "0  [コックリさん その起源は明確ではないが、レオナルド・ダ・ヴィンチが自著において「テーブル・...  [コックリさん]      第1回AI王   \n",
       "\n",
       "    timestamp         section number  \\\n",
       "0  2019/12/25  開発データ問題 (dev1)      2   \n",
       "\n",
       "                                   original_question original_answer  \\\n",
       "0  明治時代に西洋から伝わった「テーブル・ターニング」に起源を持つ占いの一種で、50音表などを記...          コックリさん   \n",
       "\n",
       "  original_additional_info  \n",
       "0                           "
      ]
     },
     "execution_count": 8,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# qid, question, answer, context が先頭のカラムに来るように並び替える。過去のカラムも残す\n",
    "new_columns = [\"qid\", \"question\", \"answer\", \"context\", \"answers\"]\n",
    "new_columns.extend([c for c in train_df.columns if c not in new_columns])\n",
    "train_df = train_df[new_columns]\n",
    "train_df.head(1)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [],
   "source": [
    "import datasets\n",
    "\n",
    "# pandas to dataset\n",
    "train_dataset = datasets.Dataset.from_pandas(train_df)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "Dataset({\n",
       "    features: ['qid', 'question', 'answer', 'context', 'answers', 'competition', 'timestamp', 'section', 'number', 'original_question', 'original_answer', 'original_additional_info', '__index_level_0__'],\n",
       "    num_rows: 3919\n",
       "})"
      ]
     },
     "execution_count": 10,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "train_dataset"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "((2939, 12), (980, 12))"
      ]
     },
     "execution_count": 11,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 25% を validation にする\n",
    "valid_df = train_df.sample(frac=0.25, random_state=42)\n",
    "train_df = train_df.drop(valid_df.index)\n",
    "train_df = train_df.reset_index(drop=True)\n",
    "valid_df = valid_df.reset_index(drop=True)\n",
    "# shape\n",
    "train_df.shape, valid_df.shape"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [],
   "source": [
    "from datasets import Dataset\n",
    "\n",
    "train_ds = Dataset.from_pandas(train_df)\n",
    "valid_ds = Dataset.from_pandas(valid_df)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [],
   "source": [
    "dataset_hf_path = \"hotchpotch/jaqket_v1_qa_wikija_context\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "Creating parquet from Arrow format: 100%|██████████| 3/3 [00:00<00:00, 116.44ba/s]\n",
      "Uploading the dataset shards: 100%|██████████| 1/1 [00:02<00:00,  2.39s/it]\n",
      "Creating parquet from Arrow format: 100%|██████████| 1/1 [00:00<00:00, 58.50ba/s]\n",
      "Uploading the dataset shards: 100%|██████████| 1/1 [00:01<00:00,  2.00s/it]\n",
      "README.md: 100%|██████████| 715/715 [00:00<00:00, 3.93MB/s]\n"
     ]
    }
   ],
   "source": [
    "train_ds.push_to_hub(dataset_hf_path, split=\"train\")\n",
    "valid_ds.push_to_hub(dataset_hf_path, split=\"validation\")"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "llm-sc",
   "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": 2
}