lvwerra HF staff commited on
Commit
2fc54f6
β€’
1 Parent(s): e0168d0

Upload StackExchangeProcessing.ipynb

Browse files
Files changed (1) hide show
  1. StackExchangeProcessing.ipynb +563 -0
StackExchangeProcessing.ipynb ADDED
@@ -0,0 +1,563 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "execution_count": 78,
6
+ "id": "7821c501-8c5d-4af6-81cd-caa6ad0bd58c",
7
+ "metadata": {},
8
+ "outputs": [],
9
+ "source": [
10
+ "from datasets import load_dataset\n",
11
+ "from datasets import concatenate_datasets\n",
12
+ "from IPython.display import HTML\n",
13
+ "\n",
14
+ "from tqdm import tqdm\n",
15
+ "import re \n",
16
+ "import numpy as np\n",
17
+ "from markdownify import markdownify as md"
18
+ ]
19
+ },
20
+ {
21
+ "cell_type": "code",
22
+ "execution_count": 2,
23
+ "id": "dc821970-efdb-407f-bd79-59da09323280",
24
+ "metadata": {
25
+ "scrolled": true,
26
+ "tags": []
27
+ },
28
+ "outputs": [
29
+ {
30
+ "name": "stderr",
31
+ "output_type": "stream",
32
+ "text": [
33
+ "Found cached dataset parquet (/home/leandro/.cache/huggingface/datasets/HuggingFaceH4___parquet/HuggingFaceH4--stack-exchange-preferences-1d2bff9ecb5ffe2a/0.0.0/2a3b91fbd88a2c90d1dbbb32b460cf621d31bd5b05b934492fdef7d8d6f236ec)\n"
34
+ ]
35
+ }
36
+ ],
37
+ "source": [
38
+ "ds = load_dataset(\"HuggingFaceH4/stack-exchange-preferences\", split=\"train\", num_proc=16)\n",
39
+ "ds"
40
+ ]
41
+ },
42
+ {
43
+ "cell_type": "code",
44
+ "execution_count": 6,
45
+ "id": "0d8d8729-6d6b-4791-a24a-cb112c399bd0",
46
+ "metadata": {},
47
+ "outputs": [
48
+ {
49
+ "data": {
50
+ "text/html": [
51
+ "<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",
52
+ "\n",
53
+ "<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",
54
+ "\n",
55
+ "<p>What can newbies like me do for the site at this stage besides voting questions and answers?</p>\n"
56
+ ],
57
+ "text/plain": [
58
+ "<IPython.core.display.HTML object>"
59
+ ]
60
+ },
61
+ "execution_count": 6,
62
+ "metadata": {},
63
+ "output_type": "execute_result"
64
+ }
65
+ ],
66
+ "source": [
67
+ "HTML(ds[0][\"question\"])"
68
+ ]
69
+ },
70
+ {
71
+ "cell_type": "code",
72
+ "execution_count": 7,
73
+ "id": "b3b60caa-3bd9-4033-ab1c-90c5b08ef3ec",
74
+ "metadata": {},
75
+ "outputs": [],
76
+ "source": [
77
+ "def lang_callback(el):\n",
78
+ " lang = el['class'][0] if el.has_attr('class') else None\n",
79
+ " \n",
80
+ " if not lang is None:\n",
81
+ " lang = lang.split(\"-\")[-1]\n",
82
+ " return lang"
83
+ ]
84
+ },
85
+ {
86
+ "cell_type": "code",
87
+ "execution_count": 57,
88
+ "id": "de1123a0-7468-4d13-a8d3-4011ace36c3c",
89
+ "metadata": {},
90
+ "outputs": [],
91
+ "source": [
92
+ "def html2md(text):\n",
93
+ " text = md(text, code_language_callback=lang_callback)\n",
94
+ " text = re.sub(r\"\\n\\s*\\n\", \"\\n\\n\", text).strip()\n",
95
+ " return text.encode('utf-8', 'replace').decode()"
96
+ ]
97
+ },
98
+ {
99
+ "cell_type": "code",
100
+ "execution_count": 77,
101
+ "id": "c9da64a0-c753-4d35-9369-b70a7a9fa2f9",
102
+ "metadata": {},
103
+ "outputs": [
104
+ {
105
+ "name": "stdout",
106
+ "output_type": "stream",
107
+ "text": [
108
+ "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",
109
+ "\n",
110
+ "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",
111
+ "\n",
112
+ "What can newbies like me do for the site at this stage besides voting questions and answers?\n",
113
+ "====================\n"
114
+ ]
115
+ }
116
+ ],
117
+ "source": [
118
+ "for i in range(1):\n",
119
+ " text = html2md(ds[i][\"question\"])\n",
120
+ " print(text)\n",
121
+ " print(\"==\"*10)"
122
+ ]
123
+ },
124
+ {
125
+ "cell_type": "code",
126
+ "execution_count": 13,
127
+ "id": "3bf33a2f-fed5-49e7-8046-e813ad172b17",
128
+ "metadata": {},
129
+ "outputs": [
130
+ {
131
+ "data": {
132
+ "text/plain": [
133
+ "49.935"
134
+ ]
135
+ },
136
+ "execution_count": 13,
137
+ "metadata": {},
138
+ "output_type": "execute_result"
139
+ }
140
+ ],
141
+ "source": [
142
+ "np.mean([len(ds[i][\"answers\"])*(len(ds[i][\"answers\"])-1)/2 for i in range(10000)])"
143
+ ]
144
+ },
145
+ {
146
+ "cell_type": "code",
147
+ "execution_count": 58,
148
+ "id": "edc8af18-94a5-49e9-ae73-ce4ba81d9739",
149
+ "metadata": {},
150
+ "outputs": [],
151
+ "source": [
152
+ "def binary_comparison(answers):\n",
153
+ " \"\"\"Returns tuples of answers, first always best\"\"\"\n",
154
+ " pairs = []\n",
155
+ " \n",
156
+ " for i in range(len(answers)-1):\n",
157
+ " for j in range(i+1, len(answers)):\n",
158
+ " if answers[i][\"pm_score\"]>answers[j][\"pm_score\"]:\n",
159
+ " pairs.append((answers[i][\"text\"], answers[j][\"text\"]))\n",
160
+ " elif answers[i][\"pm_score\"]<answers[j][\"pm_score\"]:\n",
161
+ " pairs.append((answers[j][\"text\"], answers[i][\"text\"]))\n",
162
+ " return pairs"
163
+ ]
164
+ },
165
+ {
166
+ "cell_type": "code",
167
+ "execution_count": 63,
168
+ "id": "88afe90e-364e-4b21-898b-1c6ceb9cfd32",
169
+ "metadata": {},
170
+ "outputs": [],
171
+ "source": [
172
+ "def preprocess(examples):\n",
173
+ " \"\"\"Cleans HTML and returns paired answers (j is better than k). Note that this returns more examples (one for each pair per question).\"\"\"\n",
174
+ " \n",
175
+ " MAX_PAIRS_PER_QUESTION = 10\n",
176
+ " n_samples = len(examples[\"qid\"])\n",
177
+ " \n",
178
+ " # initialize empty lists for new samples\n",
179
+ " new_examples = {\"question\": [], \"response_j\": [], \"response_k\": []}\n",
180
+ " for key in examples:\n",
181
+ " new_examples[key] = []\n",
182
+ " \n",
183
+ " for sample_id in range(n_samples):\n",
184
+ " # get pairs where first is always the better one\n",
185
+ " pairs = binary_comparison(examples[\"answers\"][sample_id])\n",
186
+ " n_answers = len(examples[\"answers\"][sample_id])\n",
187
+ " \n",
188
+ " # sample if we get more pairs than maximum\n",
189
+ " if len(pairs) > MAX_PAIRS_PER_QUESTION:\n",
190
+ " indices = np.random.choice(list(range(len(pairs))), MAX_PAIRS_PER_QUESTION, replace=False)\n",
191
+ " pairs = [pairs[i] for i in indices]\n",
192
+ " \n",
193
+ " # construct the samples\n",
194
+ " for pair in pairs:\n",
195
+ " for key in examples:\n",
196
+ " if key==\"question\":\n",
197
+ " new_examples[key].append(html2md(examples[key][sample_id]))\n",
198
+ " else:\n",
199
+ " new_examples[key].append(examples[key][sample_id])\n",
200
+ " new_examples[\"response_j\"].append(html2md(pair[0]))\n",
201
+ " new_examples[\"response_k\"].append(html2md(pair[1]))\n",
202
+ " return new_examples"
203
+ ]
204
+ },
205
+ {
206
+ "cell_type": "code",
207
+ "execution_count": 64,
208
+ "id": "ac06aac5-3953-4321-9f1e-6ff210bee82d",
209
+ "metadata": {},
210
+ "outputs": [
211
+ {
212
+ "data": {
213
+ "application/vnd.jupyter.widget-view+json": {
214
+ "model_id": "",
215
+ "version_major": 2,
216
+ "version_minor": 0
217
+ },
218
+ "text/plain": [
219
+ "Map (num_proc=60): 0%| | 0/10807695 [00:00<?, ? examples/s]"
220
+ ]
221
+ },
222
+ "metadata": {},
223
+ "output_type": "display_data"
224
+ },
225
+ {
226
+ "name": "stderr",
227
+ "output_type": "stream",
228
+ "text": [
229
+ "/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",
230
+ " warnings.warn(\n",
231
+ "/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",
232
+ " warnings.warn(\n",
233
+ "/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",
234
+ " warnings.warn(\n",
235
+ "/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",
236
+ " warnings.warn(\n"
237
+ ]
238
+ }
239
+ ],
240
+ "source": [
241
+ "ds_result = ds.map(preprocess, batch_size=1000, batched=True, num_proc=60)"
242
+ ]
243
+ },
244
+ {
245
+ "cell_type": "code",
246
+ "execution_count": 65,
247
+ "id": "06e3d891-ffde-4762-95d5-39658a1127ef",
248
+ "metadata": {},
249
+ "outputs": [
250
+ {
251
+ "data": {
252
+ "text/plain": [
253
+ "Dataset({\n",
254
+ " features: ['qid', 'question', 'answers', 'date', 'metadata', 'response_j', 'response_k'],\n",
255
+ " num_rows: 26801833\n",
256
+ "})"
257
+ ]
258
+ },
259
+ "execution_count": 65,
260
+ "metadata": {},
261
+ "output_type": "execute_result"
262
+ }
263
+ ],
264
+ "source": [
265
+ "ds_result"
266
+ ]
267
+ },
268
+ {
269
+ "cell_type": "code",
270
+ "execution_count": 47,
271
+ "id": "631416dc-cf19-485d-a2f3-94c9b2cb2bfc",
272
+ "metadata": {},
273
+ "outputs": [
274
+ {
275
+ "data": {
276
+ "text/plain": [
277
+ "{'qid': 1,\n",
278
+ " '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",
279
+ " 'answers': [{'answer_id': 14,\n",
280
+ " 'author': 'Eric Johnson',\n",
281
+ " 'author_id': 43,\n",
282
+ " 'author_profile': 'https://3dprinting.meta.stackexchange.com/users/43',\n",
283
+ " 'pm_score': 2,\n",
284
+ " 'selected': False,\n",
285
+ " '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",
286
+ " {'answer_id': 15,\n",
287
+ " 'author': 'kenorb',\n",
288
+ " 'author_id': 20,\n",
289
+ " 'author_profile': 'https://3dprinting.meta.stackexchange.com/users/20',\n",
290
+ " 'pm_score': 2,\n",
291
+ " 'selected': False,\n",
292
+ " '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",
293
+ " {'answer_id': 41,\n",
294
+ " 'author': 'Zizouz212',\n",
295
+ " 'author_id': 138,\n",
296
+ " 'author_profile': 'https://3dprinting.meta.stackexchange.com/users/138',\n",
297
+ " 'pm_score': 4,\n",
298
+ " 'selected': False,\n",
299
+ " '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",
300
+ " 'date': '2016/01/12',\n",
301
+ " 'metadata': ['https://3dprinting.meta.stackexchange.com/questions/1',\n",
302
+ " 'https://3dprinting.meta.stackexchange.com',\n",
303
+ " 'https://3dprinting.meta.stackexchange.com/users/30/'],\n",
304
+ " '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",
305
+ " '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.'}"
306
+ ]
307
+ },
308
+ "execution_count": 47,
309
+ "metadata": {},
310
+ "output_type": "execute_result"
311
+ }
312
+ ],
313
+ "source": [
314
+ "ds_result[0]"
315
+ ]
316
+ },
317
+ {
318
+ "cell_type": "code",
319
+ "execution_count": 67,
320
+ "id": "2c96653b-7a5a-4cae-a327-b6aa77aa5850",
321
+ "metadata": {},
322
+ "outputs": [],
323
+ "source": [
324
+ "ds_result = ds_result.remove_columns([\"answers\"])"
325
+ ]
326
+ },
327
+ {
328
+ "cell_type": "code",
329
+ "execution_count": 71,
330
+ "id": "15c2e5ee-7c7d-4e98-9e63-e5d37a9354aa",
331
+ "metadata": {},
332
+ "outputs": [
333
+ {
334
+ "data": {
335
+ "text/plain": [
336
+ "{'qid': 5,\n",
337
+ " 'question': 'What are the main differences when using ABS over PLA and vice versa?',\n",
338
+ " 'date': '2016/01/12',\n",
339
+ " 'metadata': ['https://3dprinting.stackexchange.com/questions/5',\n",
340
+ " 'https://3dprinting.stackexchange.com',\n",
341
+ " 'https://3dprinting.stackexchange.com/users/11/'],\n",
342
+ " '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",
343
+ " '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)'}"
344
+ ]
345
+ },
346
+ "execution_count": 71,
347
+ "metadata": {},
348
+ "output_type": "execute_result"
349
+ }
350
+ ],
351
+ "source": [
352
+ "ds_result[199]"
353
+ ]
354
+ },
355
+ {
356
+ "cell_type": "code",
357
+ "execution_count": 72,
358
+ "id": "32834c62-86bb-478b-a95f-b44fc28fe7d8",
359
+ "metadata": {},
360
+ "outputs": [],
361
+ "source": [
362
+ "ds_result = ds_result.shuffle(seed=42)"
363
+ ]
364
+ },
365
+ {
366
+ "cell_type": "code",
367
+ "execution_count": 73,
368
+ "id": "ae6dcb5b-b549-438d-984d-ecd54919afa1",
369
+ "metadata": {},
370
+ "outputs": [
371
+ {
372
+ "data": {
373
+ "text/plain": [
374
+ "Dataset({\n",
375
+ " features: ['qid', 'question', 'date', 'metadata', 'response_j', 'response_k'],\n",
376
+ " num_rows: 26801833\n",
377
+ "})"
378
+ ]
379
+ },
380
+ "execution_count": 73,
381
+ "metadata": {},
382
+ "output_type": "execute_result"
383
+ }
384
+ ],
385
+ "source": [
386
+ "ds_result"
387
+ ]
388
+ },
389
+ {
390
+ "cell_type": "code",
391
+ "execution_count": 74,
392
+ "id": "a5c0d187-aafe-4138-8951-bccdb4777d6d",
393
+ "metadata": {},
394
+ "outputs": [
395
+ {
396
+ "data": {
397
+ "text/plain": [
398
+ "{'qid': 48865595,\n",
399
+ " '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",
400
+ " 'date': '2018/02/19',\n",
401
+ " 'metadata': ['https://Stackoverflow.com/questions/48865595',\n",
402
+ " 'https://Stackoverflow.com',\n",
403
+ " 'https://Stackoverflow.com/users/4715138/'],\n",
404
+ " '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",
405
+ " '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```'}"
406
+ ]
407
+ },
408
+ "execution_count": 74,
409
+ "metadata": {},
410
+ "output_type": "execute_result"
411
+ }
412
+ ],
413
+ "source": [
414
+ "ds_result[0]"
415
+ ]
416
+ },
417
+ {
418
+ "cell_type": "code",
419
+ "execution_count": 75,
420
+ "id": "e32c11d7-a88e-4d92-9dfc-92b2a67c5455",
421
+ "metadata": {},
422
+ "outputs": [],
423
+ "source": [
424
+ "import os\n",
425
+ "import time\n",
426
+ "from multiprocessing import Pool\n",
427
+ "from tqdm import tqdm\n",
428
+ "\n",
429
+ "from huggingface_hub import Repository\n",
430
+ "\n",
431
+ "\n",
432
+ "def save_shard(shard_tuple):\n",
433
+ " \"\"\"Save shard\"\"\"\n",
434
+ " filename, shard = shard_tuple\n",
435
+ " # use to_json instead to save as json file\n",
436
+ " shard.to_parquet(filename)\n",
437
+ "\n",
438
+ "\n",
439
+ "def save_manual_shards(ds, user=\"lvwerra\", remote_dataset_repo=\"stack-exchange-paired\"):\n",
440
+ " \"\"\"Save sharded data\n",
441
+ " Args:\n",
442
+ " ds (Dataset): dataset to be saved\n",
443
+ " user (str): user name\n",
444
+ " remote_dataset_repo (str): remote dataset repository\n",
445
+ " out_path (str): path to save the shards\"\"\"\n",
446
+ " # this will create a folder OUT_PATH that is a clone of REMOTE_DATASET_REPO\n",
447
+ " # you can save the shards inside it and do git add/commit/push to push data to the hub\n",
448
+ " out_path = remote_dataset_repo\n",
449
+ " # if out path doesnt already exist\n",
450
+ " if not os.path.exists(out_path):\n",
451
+ " repo = Repository(\n",
452
+ " local_dir=out_path,\n",
453
+ " clone_from=user + \"/\" + remote_dataset_repo,\n",
454
+ " repo_type=\"dataset\",\n",
455
+ " private=False,\n",
456
+ " use_auth_token=True,\n",
457
+ " git_user=user,\n",
458
+ " )\n",
459
+ "\n",
460
+ " # files will be numerous we save them in a folder called data inside out_path\n",
461
+ " os.mkdir(out_path + \"/data\")\n",
462
+ " SHARD_SIZE = 1000 << 20\n",
463
+ " if ds._indices is not None:\n",
464
+ " dataset_nbytes = ds.data.nbytes * len(ds._indices) / len(ds.data)\n",
465
+ " else:\n",
466
+ " dataset_nbytes = ds.data.nbytes\n",
467
+ " num_shards = int(dataset_nbytes / SHARD_SIZE) + 1\n",
468
+ " print(f\"Number of shards: {num_shards}\")\n",
469
+ "\n",
470
+ " print(\"sharding the dataset\")\n",
471
+ " t_start = time.time()\n",
472
+ " shards = (\n",
473
+ " ds.shard(num_shards=num_shards, index=i, contiguous=True)\n",
474
+ " for i in range(num_shards)\n",
475
+ " )\n",
476
+ " # use f\"{OUT_PATH}/data/train-{index:05d}-of-{num_shards:05d}.json\" instead for json files\n",
477
+ " filenames = (\n",
478
+ " f\"{out_path}/data/train-{index:05d}-of-{num_shards:05d}.parquet\"\n",
479
+ " for index in range(num_shards)\n",
480
+ " )\n",
481
+ "\n",
482
+ " with Pool(16) as p:\n",
483
+ " list(\n",
484
+ " tqdm(\n",
485
+ " p.imap_unordered(save_shard, zip(filenames, shards), chunksize=4),\n",
486
+ " total=num_shards,\n",
487
+ " )\n",
488
+ " )\n",
489
+ " print(f\"Time to save dataset: {time.time()-t_start:.2f}\")\n",
490
+ " # to push dataset to hub do: git add/commit/push inside OUT_PATH"
491
+ ]
492
+ },
493
+ {
494
+ "cell_type": "code",
495
+ "execution_count": 76,
496
+ "id": "a90664eb-5c54-4fae-9a8a-d509bb2abdfe",
497
+ "metadata": {},
498
+ "outputs": [
499
+ {
500
+ "name": "stderr",
501
+ "output_type": "stream",
502
+ "text": [
503
+ "Cloning https://huggingface.co/datasets/lvwerra/stack-exchange-paired into local empty directory.\n"
504
+ ]
505
+ },
506
+ {
507
+ "name": "stdout",
508
+ "output_type": "stream",
509
+ "text": [
510
+ "Number of shards: 72\n",
511
+ "sharding the dataset\n"
512
+ ]
513
+ },
514
+ {
515
+ "name": "stderr",
516
+ "output_type": "stream",
517
+ "text": [
518
+ "100%|β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ| 72/72 [03:50<00:00, 3.20s/it]\n"
519
+ ]
520
+ },
521
+ {
522
+ "name": "stdout",
523
+ "output_type": "stream",
524
+ "text": [
525
+ "Time to save dataset: 231.51\n"
526
+ ]
527
+ }
528
+ ],
529
+ "source": [
530
+ "save_manual_shards(ds_result)"
531
+ ]
532
+ },
533
+ {
534
+ "cell_type": "code",
535
+ "execution_count": null,
536
+ "id": "d62f5a7f-2a23-4e0d-9e49-b29f88ea8c13",
537
+ "metadata": {},
538
+ "outputs": [],
539
+ "source": []
540
+ }
541
+ ],
542
+ "metadata": {
543
+ "kernelspec": {
544
+ "display_name": "Python 3 (ipykernel)",
545
+ "language": "python",
546
+ "name": "python3"
547
+ },
548
+ "language_info": {
549
+ "codemirror_mode": {
550
+ "name": "ipython",
551
+ "version": 3
552
+ },
553
+ "file_extension": ".py",
554
+ "mimetype": "text/x-python",
555
+ "name": "python",
556
+ "nbconvert_exporter": "python",
557
+ "pygments_lexer": "ipython3",
558
+ "version": "3.8.13"
559
+ }
560
+ },
561
+ "nbformat": 4,
562
+ "nbformat_minor": 5
563
+ }