{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "### Code to create Mini-Reddit" ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [], "source": [ "from pathlib import Path\n", "from garage.data import image_listing\n", "from PIL import Image\n", "from random import shuffle\n", "import shutil\n", "from tqdm import tqdm\n", "import re\n", "\n", "import numpy as np\n", "import math" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "179443\n" ] } ], "source": [ "reddit_dir = Path(\"~/me/data/reddit\").expanduser()\n", "assert reddit_dir.exists()\n", "subreddit_dir = [d for d in reddit_dir.iterdir() if d.is_dir()]\n", "image_files = image_listing.find_images(reddit_dir)\n", "print(len(image_files))" ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [], "source": [ "output_dir = Path(\"~/me/data/reddit-tiny\").expanduser()\n", "pcnt = 0.05\n", "num_image_files = len(image_files)\n", "num_out_files = int(math.ceil(pcnt*num_image_files))\n", "shuffle(image_files)\n", "num_out_files\n", "output_dir.mkdir()" ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "8973" ] }, "execution_count": 4, "metadata": {}, "output_type": "execute_result" } ], "source": [ "num_out_files" ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [ { "name": "stderr", "output_type": "stream", "text": [ " 0%| | 0/8973 [00:00 Image.MAX_IMAGE_PIXELS: continue\n", " nim = np.array(im)\n", " if len(nim.shape)!= 3 or nim.shape[-1] != 3 : continue\n", "\n", " subreddit = f.relative_to(reddit_dir).parent\n", " \n", " dname = subreddit.name \n", " dname = dname.lower()\n", " if \"porn\" in dname:\n", " dname = dname.replace(\"porn\", \"\")\n", "\n", " subreddit_dir = output_dir / subreddit.parent / dname\n", "\n", " if not subreddit_dir.exists():\n", " subreddit_dir.mkdir()\n", "\n", " \n", " fname = f.stem\n", " fname = re.sub(r'\\W+', '', fname)\n", " fname = fname + f.suffix\n", " fname = fname.lower()\n", " outpath = (output_dir / subreddit_dir/f\"{fname}\").with_suffix(\".jpeg\")\n", "\n", " im.save(outpath)\n", " im.close()\n", " pbar.set_description(f\"writing: {outpath}\")\n", " pbar.update(1)\n", " if(pbar.n == pbar.total) : break\n", " except Exception as e:\n", " pass" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "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.11.2" }, "orig_nbformat": 4 }, "nbformat": 4, "nbformat_minor": 2 }