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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
{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "501d0d55-8d15-463d-95cb-1f70d72de7fb",
   "metadata": {
    "scrolled": true
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "--2023-12-30 12:56:11--  https://raw.githubusercontent.com/askplatypus/wikidata-simplequestions/master/annotated_wd_data_train_answerable.txt\n",
      "Resolving raw.githubusercontent.com (raw.githubusercontent.com)... 185.199.108.133, 185.199.109.133, 185.199.110.133, ...\n",
      "Connecting to raw.githubusercontent.com (raw.githubusercontent.com)|185.199.108.133|:443... connected.\n",
      "HTTP request sent, awaiting response... 200 OK\n",
      "Length: 1193868 (1,1M) [text/plain]\n",
      "Saving to: β€˜annotated_wd_data_train_answerable.txt’\n",
      "\n",
      "annotated_wd_data_t 100%[===================>]   1,14M  6,45MB/s    in 0,2s    \n",
      "\n",
      "2023-12-30 12:56:11 (6,45 MB/s) - β€˜annotated_wd_data_train_answerable.txt’ saved [1193868/1193868]\n",
      "\n",
      "--2023-12-30 12:56:11--  https://raw.githubusercontent.com/askplatypus/wikidata-simplequestions/master/annotated_wd_data_valid_answerable.txt\n",
      "Resolving raw.githubusercontent.com (raw.githubusercontent.com)... 185.199.109.133, 185.199.110.133, 185.199.111.133, ...\n",
      "Connecting to raw.githubusercontent.com (raw.githubusercontent.com)|185.199.109.133|:443... connected.\n",
      "HTTP request sent, awaiting response... 200 OK\n",
      "Length: 173187 (169K) [text/plain]\n",
      "Saving to: β€˜annotated_wd_data_valid_answerable.txt’\n",
      "\n",
      "annotated_wd_data_v 100%[===================>] 169,13K  --.-KB/s    in 0,09s   \n",
      "\n",
      "2023-12-30 12:56:12 (1,86 MB/s) - β€˜annotated_wd_data_valid_answerable.txt’ saved [173187/173187]\n",
      "\n",
      "--2023-12-30 12:56:12--  https://raw.githubusercontent.com/askplatypus/wikidata-simplequestions/master/annotated_wd_data_test_answerable.txt\n",
      "Resolving raw.githubusercontent.com (raw.githubusercontent.com)... 185.199.109.133, 185.199.108.133, 185.199.110.133, ...\n",
      "Connecting to raw.githubusercontent.com (raw.githubusercontent.com)|185.199.109.133|:443... connected.\n",
      "HTTP request sent, awaiting response... 200 OK\n",
      "Length: 345052 (337K) [text/plain]\n",
      "Saving to: β€˜annotated_wd_data_test_answerable.txt’\n",
      "\n",
      "annotated_wd_data_t 100%[===================>] 336,96K  --.-KB/s    in 0,1s    \n",
      "\n",
      "2023-12-30 12:56:12 (2,70 MB/s) - β€˜annotated_wd_data_test_answerable.txt’ saved [345052/345052]\n",
      "\n"
     ]
    }
   ],
   "source": [
    "!wget -nc https://raw.githubusercontent.com/askplatypus/wikidata-simplequestions/master/annotated_wd_data_train_answerable.txt\n",
    "!wget -nc https://raw.githubusercontent.com/askplatypus/wikidata-simplequestions/master/annotated_wd_data_valid_answerable.txt\n",
    "!wget -nc https://raw.githubusercontent.com/askplatypus/wikidata-simplequestions/master/annotated_wd_data_test_answerable.txt"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "73af4417-0637-4848-9d35-e734a685ebc4",
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "/home/salnikov/.cache/pypoetry/virtualenvs/kgqa-signatures-J3ZJKtLx-py3.10/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": [
    "import pandas as pd\n",
    "import datasets \n",
    "import numpy as np\n",
    "import random\n",
    "import logging\n",
    "\n",
    "np.random.seed(8)\n",
    "random.seed(8)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "6ffea0dd-3d28-416c-b7c3-c8dd73d5e304",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "DatasetDict({\n",
       "    train: Dataset({\n",
       "        features: ['subject', 'property', 'object', 'question'],\n",
       "        num_rows: 19481\n",
       "    })\n",
       "    valid: Dataset({\n",
       "        features: ['subject', 'property', 'object', 'question'],\n",
       "        num_rows: 2821\n",
       "    })\n",
       "    test: Dataset({\n",
       "        features: ['subject', 'property', 'object', 'question'],\n",
       "        num_rows: 5622\n",
       "    })\n",
       "})"
      ]
     },
     "execution_count": 3,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "dataset = datasets.DatasetDict()\n",
    "for split, data_path in [\n",
    "    (\"train\", \"annotated_wd_data_train_answerable.txt\"),\n",
    "    (\"valid\", \"annotated_wd_data_valid_answerable.txt\"),\n",
    "    (\"test\", \"annotated_wd_data_test_answerable.txt\"),\n",
    "]:\n",
    "    df = pd.read_csv(data_path, names=['subject', 'property', 'object', 'question'], sep='\\t')\n",
    "    dataset[split] = datasets.Dataset.from_pandas(df)\n",
    "\n",
    "dataset"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "f7e71241",
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "import os.path\n",
    "import pickle\n",
    "import warnings\n",
    "\n",
    "from joblib import register_store_backend, numpy_pickle\n",
    "from joblib._store_backends import FileSystemStoreBackend, CacheWarning\n",
    "\n",
    "\n",
    "class FileSystemStoreBackendNoNumpy(FileSystemStoreBackend):\n",
    "    NAME = \"no_numpy\"\n",
    "\n",
    "    def load_item(self, path, verbose=1, msg=None):\n",
    "        \"\"\"Load an item from the store given its path as a list of\n",
    "           strings.\"\"\"\n",
    "        full_path = os.path.join(self.location, *path)\n",
    "\n",
    "        if verbose > 1:\n",
    "            if verbose < 10:\n",
    "                print('{0}...'.format(msg))\n",
    "            else:\n",
    "                print('{0} from {1}'.format(msg, full_path))\n",
    "\n",
    "        mmap_mode = (None if not hasattr(self, 'mmap_mode')\n",
    "                     else self.mmap_mode)\n",
    "\n",
    "        filename = os.path.join(full_path, 'output.pkl')\n",
    "        if not self._item_exists(filename):\n",
    "            raise KeyError(\"Non-existing item (may have been \"\n",
    "                           \"cleared).\\nFile %s does not exist\" % filename)\n",
    "\n",
    "        # file-like object cannot be used when mmap_mode is set\n",
    "        if mmap_mode is None:\n",
    "            with self._open_item(filename, \"rb\") as f:\n",
    "                item = pickle.load(f)\n",
    "        else:\n",
    "            item = numpy_pickle.load(filename, mmap_mode=mmap_mode)\n",
    "        return item\n",
    "\n",
    "    def dump_item(self, path, item, verbose=1):\n",
    "        \"\"\"Dump an item in the store at the path given as a list of\n",
    "           strings.\"\"\"\n",
    "        try:\n",
    "            item_path = os.path.join(self.location, *path)\n",
    "            if not self._item_exists(item_path):\n",
    "                self.create_location(item_path)\n",
    "            filename = os.path.join(item_path, 'output.pkl')\n",
    "            if verbose > 10:\n",
    "                print('Persisting in %s' % item_path)\n",
    "\n",
    "            def write_func(to_write, dest_filename):\n",
    "                mmap_mode = (None if not hasattr(self, 'mmap_mode')\n",
    "                             else self.mmap_mode)\n",
    "                with self._open_item(dest_filename, \"wb\") as f:\n",
    "                    try:\n",
    "                        if mmap_mode is None:\n",
    "                            pickle.dump(to_write, f)\n",
    "                        else:\n",
    "                            numpy_pickle.dump(to_write, f, compress=self.compress)\n",
    "                    except pickle.PicklingError as e:\n",
    "                        # TODO(1.5) turn into error\n",
    "                        warnings.warn(\n",
    "                            \"Unable to cache to disk: failed to pickle \"\n",
    "                            \"output. In version 1.5 this will raise an \"\n",
    "                            f\"exception. Exception: {e}.\",\n",
    "                            FutureWarning\n",
    "                        )\n",
    "\n",
    "            self._concurrency_safe_write(item, filename, write_func)\n",
    "        except Exception as e:  # noqa: E722\n",
    "            warnings.warn(\n",
    "                \"Unable to cache to disk. Possibly a race condition in the \"\n",
    "                f\"creation of the directory. Exception: {e}.\",\n",
    "                CacheWarning\n",
    "            )\n",
    "\n",
    "\n",
    "register_store_backend(FileSystemStoreBackendNoNumpy.NAME, FileSystemStoreBackendNoNumpy)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "id": "41eb3bbd-19bb-4c0d-892c-35478eabc00b",
   "metadata": {},
   "outputs": [],
   "source": [
    "import time\n",
    "from http.client import RemoteDisconnected\n",
    "\n",
    "import requests\n",
    "from joblib import Memory\n",
    "from urllib3.exceptions import ProtocolError\n",
    "\n",
    "\n",
    "SPARQL_API_URL = \"http://127.0.0.1:7001\"\n",
    "CACHE_DIRECTORY = \"wikidata/cache\"\n",
    "\n",
    "logger = logging.getLogger()\n",
    "memory = Memory(CACHE_DIRECTORY, verbose=0, backend=FileSystemStoreBackendNoNumpy.NAME)\n",
    "\n",
    "\n",
    "def execute_wiki_request_with_delays(api_url, params, headers):\n",
    "    response = requests.get(\n",
    "        api_url,\n",
    "        params=params,\n",
    "        headers=headers,\n",
    "    )\n",
    "    to_sleep = 0.2\n",
    "    while response.status_code == 429:\n",
    "        logger.warning(\n",
    "            {\n",
    "                \"msg\": f\"Request to wikidata endpoint failed. Retry.\",\n",
    "                \"params\": params,\n",
    "                \"endpoint\": api_url,\n",
    "                \"response\": {\n",
    "                    \"status_code\": response.status_code,\n",
    "                    \"headers\": dict(response.headers),\n",
    "                },\n",
    "                \"retry_after\": to_sleep,\n",
    "            }\n",
    "        )\n",
    "        if \"retry-after\" in response.headers:\n",
    "            to_sleep += int(response.headers[\"retry-after\"])\n",
    "        to_sleep += 0.5\n",
    "        time.sleep(to_sleep)\n",
    "        response = requests.get(\n",
    "            api_url,\n",
    "            params=params,\n",
    "            headers=headers,\n",
    "        )\n",
    "\n",
    "    return response\n",
    "\n",
    "\n",
    "@memory.cache(ignore=['api_url'])\n",
    "def execute_sparql_request(request: str, api_url: str = SPARQL_API_URL):\n",
    "    params = {\"format\": \"json\", \"query\": request}\n",
    "    headers = {\n",
    "        \"Accept\": \"application/sparql-results+json\",\n",
    "        \"User-Agent\": \"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36\",\n",
    "    }\n",
    "    logger.info(\n",
    "        {\n",
    "            \"msg\": \"Send request to Wikidata\",\n",
    "            \"params\": params,\n",
    "            \"endpoint\": api_url,\n",
    "            \"request\": request\n",
    "        }\n",
    "    )\n",
    "    try:\n",
    "        response = execute_wiki_request_with_delays(api_url, params, headers)\n",
    "    except (ProtocolError, RemoteDisconnected, requests.exceptions.ConnectionError) as e:\n",
    "        logger.error(\n",
    "            {\n",
    "                \"msg\": str(e),\n",
    "                \"request\": request,\n",
    "                \"endpoint\": api_url,\n",
    "            }\n",
    "        )\n",
    "        return None\n",
    "\n",
    "    try:\n",
    "        response = response.json()[\"results\"][\"bindings\"]\n",
    "        logger.debug(\n",
    "            {\n",
    "                \"msg\": \"Received response from Wikidata\",\n",
    "                \"params\": params,\n",
    "                \"endpoint\": api_url,\n",
    "                \"request\": request,\n",
    "                \"response\": response\n",
    "            }\n",
    "        )\n",
    "        return response\n",
    "    except Exception as e:\n",
    "        logger.error(\n",
    "            {\n",
    "                \"msg\": str(e),\n",
    "                \"params\": params,\n",
    "                \"endpoint\": api_url,\n",
    "                \"response\": {\n",
    "                    \"status_code\": response.status_code,\n",
    "                    \"headers\": dict(response.headers),\n",
    "                },\n",
    "            }\n",
    "        )\n",
    "        raise e\n",
    "\n",
    "def get_label(entity_id):\n",
    "    query = \"\"\"\n",
    "    PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#> \n",
    "    PREFIX wd: <http://www.wikidata.org/entity/> \n",
    "    SELECT DISTINCT ?label\n",
    "    WHERE {\n",
    "        wd:<ENTITY> rdfs:label ?label\n",
    "    } \n",
    "    \"\"\".replace(\n",
    "        \"<ENTITY>\", entity_id\n",
    "    )\n",
    "    \n",
    "    for lbl_obj in execute_sparql_request(query):\n",
    "        if lbl_obj['label']['xml:lang'] == 'en':\n",
    "            return lbl_obj['label']['value']"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 25,
   "id": "2568fa09",
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "Map:   0%|          | 0/19481 [00:00<?, ? examples/s]"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "Map: 100%|β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ| 19481/19481 [01:44<00:00, 185.89 examples/s]\n",
      "Map: 100%|β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ| 2821/2821 [00:08<00:00, 334.13 examples/s]\n",
      "Map: 100%|β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ| 5622/5622 [00:15<00:00, 352.59 examples/s]\n"
     ]
    }
   ],
   "source": [
    "dataset = dataset.map(\n",
    "    lambda record: {'object_label': get_label(record['object'])}\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 35,
   "id": "222d50c1",
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "Creating parquet from Arrow format: 100%|β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ| 20/20 [00:00<00:00, 474.06ba/s]\n",
      "Uploading the dataset shards: 100%|β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ| 1/1 [00:02<00:00,  2.07s/it]\n",
      "Creating parquet from Arrow format: 100%|β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ| 3/3 [00:00<00:00, 921.29ba/s]\n",
      "Uploading the dataset shards: 100%|β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ| 1/1 [00:01<00:00,  1.63s/it]\n",
      "Creating parquet from Arrow format: 100%|β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ| 6/6 [00:00<00:00, 1000.75ba/s]\n",
      "Uploading the dataset shards: 100%|β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ| 1/1 [00:01<00:00,  1.73s/it]\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "CommitInfo(commit_url='https://huggingface.co/datasets/s-nlp/sqwd/commit/680b8199969fc0389fc96feb4f3b8be15b2674d0', commit_message='Upload dataset', commit_description='', oid='680b8199969fc0389fc96feb4f3b8be15b2674d0', pr_url=None, pr_revision=None, pr_num=None)"
      ]
     },
     "execution_count": 35,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "dataset.push_to_hub('s-nlp/sqwd', 'answerable', set_default=True)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "2652ed4d",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "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
}