{ "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": [ "

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" ], "text/plain": [ "" ] }, "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\"] 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:00I 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\\n

If you are looking at getting a 3D printer, you could ask about different features listed and why they make prints better.

\\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': '

That\\'s the goal of the site, learn, research and ask.

\\n\\n

While you learn, you can always perform other tasks such as:

\\n\\n\\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': '

Vote!

\\n\\n

Private Betas love, love, love votes. Without votes, it\\'s difficult to attain privileges, get rewards, and help push us out to public beta.

\\n\\n

Ask Questions!

\\n\\n

I 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

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!

\\n\\n

Participate!

\\n\\n

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 :)

\\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\\n\\n \\n\\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 }