File size: 24,835 Bytes
2fc54f6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 78,
   "id": "7821c501-8c5d-4af6-81cd-caa6ad0bd58c",
   "metadata": {},
   "outputs": [],
   "source": [
    "from datasets import load_dataset\n",
    "from datasets import concatenate_datasets\n",
    "from IPython.display import HTML\n",
    "\n",
    "from tqdm import tqdm\n",
    "import re \n",
    "import numpy as np\n",
    "from markdownify import markdownify as md"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "dc821970-efdb-407f-bd79-59da09323280",
   "metadata": {
    "scrolled": true,
    "tags": []
   },
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "Found cached dataset parquet (/home/leandro/.cache/huggingface/datasets/HuggingFaceH4___parquet/HuggingFaceH4--stack-exchange-preferences-1d2bff9ecb5ffe2a/0.0.0/2a3b91fbd88a2c90d1dbbb32b460cf621d31bd5b05b934492fdef7d8d6f236ec)\n"
     ]
    }
   ],
   "source": [
    "ds = load_dataset(\"HuggingFaceH4/stack-exchange-preferences\", split=\"train\", num_proc=16)\n",
    "ds"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "0d8d8729-6d6b-4791-a24a-cb112c399bd0",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<p>I have been wanting to learn about 3D printing a long time so I really want this site to succeed but I have no previous experience with the subject. </p>\n",
       "\n",
       "<p>I was wondering how can I help the site at this early stage. I thought about asking about how to get started with 3D printing but SE explicitly discourages \"easy\" questions in the private beta.</p>\n",
       "\n",
       "<p>What can newbies like me do for the site at this stage besides voting questions and answers?</p>\n"
      ],
      "text/plain": [
       "<IPython.core.display.HTML object>"
      ]
     },
     "execution_count": 6,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "HTML(ds[0][\"question\"])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "b3b60caa-3bd9-4033-ab1c-90c5b08ef3ec",
   "metadata": {},
   "outputs": [],
   "source": [
    "def lang_callback(el):\n",
    "    lang = el['class'][0] if el.has_attr('class') else None\n",
    "    \n",
    "    if not lang is None:\n",
    "        lang = lang.split(\"-\")[-1]\n",
    "    return lang"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 57,
   "id": "de1123a0-7468-4d13-a8d3-4011ace36c3c",
   "metadata": {},
   "outputs": [],
   "source": [
    "def html2md(text):\n",
    "    text = md(text, code_language_callback=lang_callback)\n",
    "    text = re.sub(r\"\\n\\s*\\n\", \"\\n\\n\", text).strip()\n",
    "    return text.encode('utf-8', 'replace').decode()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 77,
   "id": "c9da64a0-c753-4d35-9369-b70a7a9fa2f9",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "I have been wanting to learn about 3D printing a long time so I really want this site to succeed but I have no previous experience with the subject. \n",
      "\n",
      "I was wondering how can I help the site at this early stage. I thought about asking about how to get started with 3D printing but SE explicitly discourages \"easy\" questions in the private beta.\n",
      "\n",
      "What can newbies like me do for the site at this stage besides voting questions and answers?\n",
      "====================\n"
     ]
    }
   ],
   "source": [
    "for i in range(1):\n",
    "    text = html2md(ds[i][\"question\"])\n",
    "    print(text)\n",
    "    print(\"==\"*10)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "id": "3bf33a2f-fed5-49e7-8046-e813ad172b17",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "49.935"
      ]
     },
     "execution_count": 13,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "np.mean([len(ds[i][\"answers\"])*(len(ds[i][\"answers\"])-1)/2 for i in range(10000)])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 58,
   "id": "edc8af18-94a5-49e9-ae73-ce4ba81d9739",
   "metadata": {},
   "outputs": [],
   "source": [
    "def binary_comparison(answers):\n",
    "    \"\"\"Returns tuples of answers, first always best\"\"\"\n",
    "    pairs = []\n",
    "    \n",
    "    for i in range(len(answers)-1):\n",
    "        for j in range(i+1, len(answers)):\n",
    "            if answers[i][\"pm_score\"]>answers[j][\"pm_score\"]:\n",
    "                pairs.append((answers[i][\"text\"], answers[j][\"text\"]))\n",
    "            elif answers[i][\"pm_score\"]<answers[j][\"pm_score\"]:\n",
    "                pairs.append((answers[j][\"text\"], answers[i][\"text\"]))\n",
    "    return pairs"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 63,
   "id": "88afe90e-364e-4b21-898b-1c6ceb9cfd32",
   "metadata": {},
   "outputs": [],
   "source": [
    "def preprocess(examples):\n",
    "    \"\"\"Cleans HTML and returns paired answers (j is better than k). Note that this returns more examples (one for each pair per question).\"\"\"\n",
    "    \n",
    "    MAX_PAIRS_PER_QUESTION = 10\n",
    "    n_samples = len(examples[\"qid\"])\n",
    "    \n",
    "    # initialize empty lists for new samples\n",
    "    new_examples = {\"question\": [], \"response_j\": [], \"response_k\": []}\n",
    "    for key in examples:\n",
    "        new_examples[key] = []\n",
    "    \n",
    "    for sample_id in range(n_samples):\n",
    "        # get pairs where first is always the better one\n",
    "        pairs = binary_comparison(examples[\"answers\"][sample_id])\n",
    "        n_answers = len(examples[\"answers\"][sample_id])\n",
    "        \n",
    "        # sample if we get more pairs than maximum\n",
    "        if len(pairs) > MAX_PAIRS_PER_QUESTION:\n",
    "            indices = np.random.choice(list(range(len(pairs))), MAX_PAIRS_PER_QUESTION, replace=False)\n",
    "            pairs = [pairs[i] for i in indices]\n",
    "        \n",
    "        # construct the samples\n",
    "        for pair in pairs:\n",
    "            for key in examples:\n",
    "                if key==\"question\":\n",
    "                    new_examples[key].append(html2md(examples[key][sample_id]))\n",
    "                else:\n",
    "                    new_examples[key].append(examples[key][sample_id])\n",
    "            new_examples[\"response_j\"].append(html2md(pair[0]))\n",
    "            new_examples[\"response_k\"].append(html2md(pair[1]))\n",
    "    return new_examples"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 64,
   "id": "ac06aac5-3953-4321-9f1e-6ff210bee82d",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "Map (num_proc=60):   0%|          | 0/10807695 [00:00<?, ? examples/s]"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "/opt/conda/envs/jupyter/lib/python3.8/site-packages/bs4/__init__.py:435: MarkupResemblesLocatorWarning: The input looks more like a filename than markup. You may want to open this file and pass the filehandle into Beautiful Soup.\n",
      "  warnings.warn(\n",
      "/opt/conda/envs/jupyter/lib/python3.8/site-packages/bs4/__init__.py:435: MarkupResemblesLocatorWarning: The input looks more like a filename than markup. You may want to open this file and pass the filehandle into Beautiful Soup.\n",
      "  warnings.warn(\n",
      "/opt/conda/envs/jupyter/lib/python3.8/site-packages/bs4/__init__.py:435: MarkupResemblesLocatorWarning: The input looks more like a filename than markup. You may want to open this file and pass the filehandle into Beautiful Soup.\n",
      "  warnings.warn(\n",
      "/opt/conda/envs/jupyter/lib/python3.8/site-packages/bs4/__init__.py:435: MarkupResemblesLocatorWarning: The input looks more like a filename than markup. You may want to open this file and pass the filehandle into Beautiful Soup.\n",
      "  warnings.warn(\n"
     ]
    }
   ],
   "source": [
    "ds_result = ds.map(preprocess, batch_size=1000, batched=True, num_proc=60)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 65,
   "id": "06e3d891-ffde-4762-95d5-39658a1127ef",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "Dataset({\n",
       "    features: ['qid', 'question', 'answers', 'date', 'metadata', 'response_j', 'response_k'],\n",
       "    num_rows: 26801833\n",
       "})"
      ]
     },
     "execution_count": 65,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "ds_result"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 47,
   "id": "631416dc-cf19-485d-a2f3-94c9b2cb2bfc",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'qid': 1,\n",
       " 'question': 'I have been wanting to learn about 3D printing a long time so I really want this site to succeed but I have no previous experience with the subject. \\n\\nI was wondering how can I help the site at this early stage. I thought about asking about how to get started with 3D printing but SE explicitly discourages \"easy\" questions in the private beta.\\n\\nWhat can newbies like me do for the site at this stage besides voting questions and answers?',\n",
       " 'answers': [{'answer_id': 14,\n",
       "   'author': 'Eric Johnson',\n",
       "   'author_id': 43,\n",
       "   'author_profile': 'https://3dprinting.meta.stackexchange.com/users/43',\n",
       "   'pm_score': 2,\n",
       "   'selected': False,\n",
       "   'text': '<p>I would suggest doing a bit of basic research on 3D printing (including reading questions and answers).  From these you will learn more about it and hopefull you will have new questions about 3D printing that can be asked.  </p>\\n\\n<p>If you are looking at getting a 3D printer, you could ask about different features listed and why they make prints better.</p>\\n'},\n",
       "  {'answer_id': 15,\n",
       "   'author': 'kenorb',\n",
       "   'author_id': 20,\n",
       "   'author_profile': 'https://3dprinting.meta.stackexchange.com/users/20',\n",
       "   'pm_score': 2,\n",
       "   'selected': False,\n",
       "   'text': '<p>That\\'s the goal of the site, learn, research and ask.</p>\\n\\n<p>While you learn, you can always perform other tasks such as:</p>\\n\\n<ul>\\n<li>improve quality posts by proposing edits,</li>\\n<li>be active in meta (propose new ideas or write your opinion which are always welcomed),</li>\\n<li>review <a href=\"https://3dprinting.stackexchange.com/review\">moderation queues</a>,</li>\\n<li>housekeeping - help to keep things organised (e.g. tags),</li>\\n<li>propose descriptions for wiki tags,</li>\\n<li>vote on questions, down-vote bad or propose changes on low-quality posts,</li>\\n<li>and so on.</li>\\n</ul>\\n'},\n",
       "  {'answer_id': 41,\n",
       "   'author': 'Zizouz212',\n",
       "   'author_id': 138,\n",
       "   'author_profile': 'https://3dprinting.meta.stackexchange.com/users/138',\n",
       "   'pm_score': 4,\n",
       "   'selected': False,\n",
       "   'text': '<h1>Vote!</h1>\\n\\n<p>Private Betas love, love, <em>love</em> votes. Without votes, it\\'s difficult to attain privileges, get rewards, and help push us out to public beta.</p>\\n\\n<h1>Ask Questions!</h1>\\n\\n<p>I know you said this:</p>\\n\\n<blockquote>\\n  <p>I thought about asking about how to get started with 3D printing but SE explicitly discourages \"easy\" questions in the private beta.</p>\\n</blockquote>\\n\\n<p>But here\\'s the catch. \"Easy\" isn\\'t defined. If you have an \"easy\" question, but it is specific, high-quality, and to the point, and you can show some effort in it, then, please, go ahead and ask it!</p>\\n\\n<h1>Participate!</h1>\\n\\n<p>You have a voice in our meta discussions as well. You also have the authority to suggest edits, to posts, tag wikis, and tag excerpts. They also get you +2 rep for each that is approved, which can help bring you more afloat. You can also give your opinion in scope, by casting close and reopen votes as well :)</p>\\n'}],\n",
       " 'date': '2016/01/12',\n",
       " 'metadata': ['https://3dprinting.meta.stackexchange.com/questions/1',\n",
       "  'https://3dprinting.meta.stackexchange.com',\n",
       "  'https://3dprinting.meta.stackexchange.com/users/30/'],\n",
       " 'response_j': 'Vote!\\n=====\\n\\nPrivate Betas love, love, *love* votes. Without votes, it\\'s difficult to attain privileges, get rewards, and help push us out to public beta.\\n\\nAsk Questions!\\n==============\\n\\nI know you said this:\\n\\n> \\n> I thought about asking about how to get started with 3D printing but SE explicitly discourages \"easy\" questions in the private beta.\\n> \\n> \\n> \\n\\nBut here\\'s the catch. \"Easy\" isn\\'t defined. If you have an \"easy\" question, but it is specific, high-quality, and to the point, and you can show some effort in it, then, please, go ahead and ask it!\\n\\nParticipate!\\n============\\n\\nYou have a voice in our meta discussions as well. You also have the authority to suggest edits, to posts, tag wikis, and tag excerpts. They also get you +2 rep for each that is approved, which can help bring you more afloat. You can also give your opinion in scope, by casting close and reopen votes as well :)',\n",
       " 'response_k': 'I would suggest doing a bit of basic research on 3D printing (including reading questions and answers). From these you will learn more about it and hopefull you will have new questions about 3D printing that can be asked. \\n\\nIf you are looking at getting a 3D printer, you could ask about different features listed and why they make prints better.'}"
      ]
     },
     "execution_count": 47,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "ds_result[0]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 67,
   "id": "2c96653b-7a5a-4cae-a327-b6aa77aa5850",
   "metadata": {},
   "outputs": [],
   "source": [
    "ds_result = ds_result.remove_columns([\"answers\"])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 71,
   "id": "15c2e5ee-7c7d-4e98-9e63-e5d37a9354aa",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'qid': 5,\n",
       " 'question': 'What are the main differences when using ABS over PLA and vice versa?',\n",
       " 'date': '2016/01/12',\n",
       " 'metadata': ['https://3dprinting.stackexchange.com/questions/5',\n",
       "  'https://3dprinting.stackexchange.com',\n",
       "  'https://3dprinting.stackexchange.com/users/11/'],\n",
       " 'response_j': \"Paraphrasing [this](http://www.protoparadigm.com/news-updates/the-difference-between-abs-and-pla-for-3d-printing/) site. Feel free to add suggestions in the form of comments and I will try to incorporate them.\\n\\nSummary\\n\\n* ABS: Stronger, machinable, more flexible, and more temperature\\nresistant than PLA. Typically printed on a heated bed. Warping is a common problem when printing ABS.\\n* PLA: Wider range of filaments available, easier and in some cases faster to print. Not as strong as ABS and the fact that its biodegradable could be seen as both a benefit and a drawback.\\n\\nMaterial Properties:\\n\\n* ABS: Strong plastic with mild flexibility. Naturally beige in color. Can be filled and sanded. Higher temperature. Easy to recycle.\\n* PLA: Not as strong as ABS but more rigid. Naturally transparent. More difficult to fill and sand. Can sag in hot temperatures. Sourced from organic matter so it can be broken down in commercial compost facilities.\\n\\nPart Accuracy:\\n\\n* ABS: Part warping is a significant issue. Sharp corners will often be rounded.\\n* PLA: Less heat required contributes to less warping. Becomes more liquid at common extruder temperatures so finer details can be printed.\\n\\nSafety and Handling:\\n\\n* ABS: Strong burning/melting plastic smell is present when printing ABS. Health concerns have been raised regarding airborne ultrafine particles generated while printing with ABS ([ref](https://dx.doi.org/10.1016%2Fj.atmosenv.2013.06.050)). ABS will absorb moisture causing popping when the moisture enters the hot end. This leads to discontinuities in the print job.\\n* PLA: Doesn't smell as strongly when printing due to its organic nature. Moisture can also be absorbed into PLA and can irreversibly damage it.\",\n",
       " 'response_k': '> \\n> PLA/ABS general and thermal properties\\n> \\n> \\n> \\n\\n![PLA vs ABS general properties PLA ABS Performance Higher strength Higher rigidity Stronger layer bond Higher impact resistance Higher flexibility Higher temperature resistance higher Tg Quality Sharper details features corners surfaces Process Lower warping Better color Les particle emissions Lower risk of jamming](https://i.stack.imgur.com/atDXf.png)'}"
      ]
     },
     "execution_count": 71,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "ds_result[199]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 72,
   "id": "32834c62-86bb-478b-a95f-b44fc28fe7d8",
   "metadata": {},
   "outputs": [],
   "source": [
    "ds_result = ds_result.shuffle(seed=42)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 73,
   "id": "ae6dcb5b-b549-438d-984d-ecd54919afa1",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "Dataset({\n",
       "    features: ['qid', 'question', 'date', 'metadata', 'response_j', 'response_k'],\n",
       "    num_rows: 26801833\n",
       "})"
      ]
     },
     "execution_count": 73,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "ds_result"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 74,
   "id": "a5c0d187-aafe-4138-8951-bccdb4777d6d",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'qid': 48865595,\n",
       " 'question': 'I am using [AGM maps](https://angular-maps.com/) for my angular 4 application, there I am facing issues, I will be having the multiple markers which are fetched from api as an array of Latitude and Longitude. I want to set the zoom level exactly covering all the markers on the map. Even if one marker in one country and other in some other country also, It should set the zoom level on load to show all the markers on the map.\\n Is there a way to do that in AGM angular maps? Could anyone please help me',\n",
       " 'date': '2018/02/19',\n",
       " 'metadata': ['https://Stackoverflow.com/questions/48865595',\n",
       "  'https://Stackoverflow.com',\n",
       "  'https://Stackoverflow.com/users/4715138/'],\n",
       " 'response_j': 'Since September 2018 there is the [`AgmFitBounds`](https://angular-maps.com/api-docs/agm-core/directives/agmfitbounds) directive. Super easy.\\n\\n```\\n<agm-map\\n  style=\"width:100vw; height:100vh;\"\\n  [fitBounds]=\"true\">\\n\\n  <agm-marker\\n    *ngFor=\"let location of locations\"\\n    [latitude]=\"location.latitude\"\\n    [longitude]=\"location.longitude\"\\n    [agmFitBounds]=\"true\"></agm-marker>\\n</agm-map>\\n\\n```',\n",
       " 'response_k': '@renil-babu\\n\\nInstead of doing the `fitBounds` on `mapReady`, you have to do it in your adding markers subscription block\\n\\n```\\n      const bounds: LatLngBounds = new google.maps.LatLngBounds();\\n      for (const mm of this.markers) {\\n        bounds.extend(new google.maps.LatLng(mm.lat, mm.lng));\\n      }\\n      // @ts-ignore\\n      this.agmMap._mapsWrapper.fitBounds(bounds);\\n\\n```'}"
      ]
     },
     "execution_count": 74,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "ds_result[0]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 75,
   "id": "e32c11d7-a88e-4d92-9dfc-92b2a67c5455",
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "import time\n",
    "from multiprocessing import Pool\n",
    "from tqdm import tqdm\n",
    "\n",
    "from huggingface_hub import Repository\n",
    "\n",
    "\n",
    "def save_shard(shard_tuple):\n",
    "    \"\"\"Save shard\"\"\"\n",
    "    filename, shard = shard_tuple\n",
    "    # use to_json instead to save as json file\n",
    "    shard.to_parquet(filename)\n",
    "\n",
    "\n",
    "def save_manual_shards(ds, user=\"lvwerra\", remote_dataset_repo=\"stack-exchange-paired\"):\n",
    "    \"\"\"Save sharded data\n",
    "    Args:\n",
    "        ds (Dataset): dataset to be saved\n",
    "        user (str): user name\n",
    "        remote_dataset_repo (str): remote dataset repository\n",
    "        out_path (str): path to save the shards\"\"\"\n",
    "    # this will create a folder OUT_PATH that is a clone of REMOTE_DATASET_REPO\n",
    "    # you can save the shards inside it and do git add/commit/push to push data to the hub\n",
    "    out_path = remote_dataset_repo\n",
    "    # if out path doesnt already exist\n",
    "    if not os.path.exists(out_path):\n",
    "        repo = Repository(\n",
    "            local_dir=out_path,\n",
    "            clone_from=user + \"/\" + remote_dataset_repo,\n",
    "            repo_type=\"dataset\",\n",
    "            private=False,\n",
    "            use_auth_token=True,\n",
    "            git_user=user,\n",
    "        )\n",
    "\n",
    "    # files will be numerous we save them in a folder called data inside out_path\n",
    "    os.mkdir(out_path + \"/data\")\n",
    "    SHARD_SIZE = 1000 << 20\n",
    "    if ds._indices is not None:\n",
    "        dataset_nbytes = ds.data.nbytes * len(ds._indices) / len(ds.data)\n",
    "    else:\n",
    "        dataset_nbytes = ds.data.nbytes\n",
    "    num_shards = int(dataset_nbytes / SHARD_SIZE) + 1\n",
    "    print(f\"Number of shards: {num_shards}\")\n",
    "\n",
    "    print(\"sharding the dataset\")\n",
    "    t_start = time.time()\n",
    "    shards = (\n",
    "        ds.shard(num_shards=num_shards, index=i, contiguous=True)\n",
    "        for i in range(num_shards)\n",
    "    )\n",
    "    # use f\"{OUT_PATH}/data/train-{index:05d}-of-{num_shards:05d}.json\" instead for json files\n",
    "    filenames = (\n",
    "        f\"{out_path}/data/train-{index:05d}-of-{num_shards:05d}.parquet\"\n",
    "        for index in range(num_shards)\n",
    "    )\n",
    "\n",
    "    with Pool(16) as p:\n",
    "        list(\n",
    "            tqdm(\n",
    "                p.imap_unordered(save_shard, zip(filenames, shards), chunksize=4),\n",
    "                total=num_shards,\n",
    "            )\n",
    "        )\n",
    "    print(f\"Time to save dataset: {time.time()-t_start:.2f}\")\n",
    "    # to push dataset to hub do: git add/commit/push inside OUT_PATH"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 76,
   "id": "a90664eb-5c54-4fae-9a8a-d509bb2abdfe",
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "Cloning https://huggingface.co/datasets/lvwerra/stack-exchange-paired into local empty directory.\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Number of shards: 72\n",
      "sharding the dataset\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "100%|β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ| 72/72 [03:50<00:00,  3.20s/it]\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Time to save dataset: 231.51\n"
     ]
    }
   ],
   "source": [
    "save_manual_shards(ds_result)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "d62f5a7f-2a23-4e0d-9e49-b29f88ea8c13",
   "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.8.13"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}