{ "metadata": { "kernelspec": { "language": "python", "display_name": "Python 3", "name": "python3" }, "language_info": { "name": "python", "version": "3.7.12", "mimetype": "text/x-python", "codemirror_mode": { "name": "ipython", "version": 3 }, "pygments_lexer": "ipython3", "nbconvert_exporter": "python", "file_extension": ".py" } }, "nbformat_minor": 4, "nbformat": 4, "cells": [ { "cell_type": "code", "source": [ "import json\n", "import cv2\n", "import os\n", "import re\n", "import requests\n", "import numpy as np\n", "import base64\n", "import urllib\n", "import traceback\n", "import threading\n", "import time\n", "from concurrent.futures import ThreadPoolExecutor, wait\n", "from tqdm.notebook import tqdm\n", "from pathlib import Path\n", "from PIL import Image\n", "\n", "headers = {\n", " \"user-agent\": \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/109.0.0.0 Safari/537.36\",\n", "}\n", "headers_pixiv = {\n", " \"user-agent\": \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/109.0.0.0 Safari/537.36\",\n", " 'referer': 'https://www.pixiv.net/'\n", "}\n", "banned_tags = ['furry', \"realistic\", \"3d\", \"1940s_(style)\",\"1950s_(style)\",\"1960s_(style)\",\"1970s_(style)\",\"1980s_(style)\",\"1990s_(style)\",\"retro_artstyle\",\"screentones\",\"pixel_art\",\"magazine_scan\",\"scan\"]\n", "bad_tags = [\"absurdres\",\"jpeg_artifacts\", \"highres\", \"translation_request\", \"translated\", \"commentary\", \"commentary_request\", \"commentary_typo\", \"character_request\", \"bad_id\", \"bad_link\", \"bad_pixiv_id\", \"bad_twitter_id\", \"bad_tumblr_id\", \"bad_deviantart_id\", \"bad_nicoseiga_id\", \"md5_mismatch\", \"cosplay_request\", \"artist_request\", \"wide_image\", \"author_request\", \"artist_name\"]\n", "\n", "def save_img(img_id, img,tags):\n", " output_dir = Path(f\"imgs\")\n", " output_dir.mkdir(exist_ok=True)\n", " img_path = output_dir / f'{img_id}.jpg'\n", " cv2.imwrite(str(img_path), cv2.cvtColor((img * 255).astype(\"uint8\"), cv2.COLOR_RGB2BGR))\n", " with open(output_dir / f'{img_id}.txt',\"w\") as f:\n", " tags = \", \".join(tags).replace(\"_\",\" \").strip()\n", " f.write(tags)\n", "\n", "def rescale(image, output_size):\n", " h,w = image.shape[:2]\n", " r = max(output_size / h, output_size / w)\n", " new_h, new_w = int(h * r), int(w * r)\n", " return cv2.resize(image,(new_w, new_h))\n", "\n", "def getImage(img_id, retry=0):\n", " def retry_fun(msg):\n", " if retry < 3:\n", " time.sleep(3)\n", " print(f\"{img_id} {msg}, retry\")\n", " return getImage(img_id, retry + 1)\n", " else:\n", " return None\n", " url = f'https://danbooru.donmai.us/posts/{img_id}.json'\n", " try:\n", " res = requests.get(url=url, headers=headers, timeout=20)\n", " if res.status_code == 404:\n", " print(f\"{img_id} get image failed\")\n", " return None\n", " success = res.status_code == 200\n", " except requests.exceptions.RequestException:\n", " success = False\n", " if not success:\n", " return retry_fun(\"get image failed\")\n", "\n", " res = json.loads(res.text)\n", " if res[\"file_ext\"] not in [\"jpg\", \"png\"]:\n", " return None\n", " img_url = None\n", " if 'file_url' in res:\n", " img_url = res[\"file_url\"]\n", " elif 'source' in res and 'i.pximg.net' in res['source']:\n", " img_url = res['source']\n", " if img_url is None:\n", " return None\n", " tags = res[\"tag_string\"]\n", " tags = tags.split()\n", " tags = [tag for tag in tags if tag not in bad_tags]\n", " for tag in banned_tags:\n", " if tag in tags:\n", " return None\n", " try:\n", " img_res = requests.get(url=img_url, headers=headers_pixiv, timeout=20)\n", " if img_res.status_code == 404:\n", " print(f\"{img_id} download failed\")\n", " return None\n", " success = img_res.status_code == 200\n", " except requests.exceptions.RequestException:\n", " success = False\n", " if not success:\n", " return retry_fun(\"download failed\")\n", "\n", " img = cv2.imdecode(np.frombuffer(img_res.content, np.uint8), cv2.IMREAD_UNCHANGED)\n", " if img is None:\n", " return retry_fun(\"image decode failed\")\n", " img = img.astype(np.float32) / np.iinfo(img.dtype).max\n", " if min(img.shape[:2]) < 400:\n", " return None\n", " if img.shape[0]*img.shape[1] > 25000000:\n", " return None\n", " if img.shape[-1] == 4:\n", " alpha = img[:, :, -1][:, :, np.newaxis]\n", " img = (1 - alpha) * 1 + alpha * img[:, :, :-1]\n", " if len(img.shape) < 3 or img.shape[-1] == 1:\n", " img = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR)\n", " if min(img.shape[:2]) > 768:\n", " img = rescale(img, 768)\n", " img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n", " return img, tags\n", "\n", "def download_all(start_id, end_id, worker_num=4):\n", " global image_total_count\n", " image_total_count = 0\n", " image_list = list(reversed(range(end_id, start_id)))\n", " progres = tqdm(total=len(image_list))\n", " max_num = len(image_list)\n", " last = {\"id\":-1}\n", " def work_fn(iid, idx):\n", " try:\n", " img_tags = getImage(iid)\n", " if img_tags is not None:\n", " save_img(iid,img_tags[0],img_tags[1])\n", " progres.update(1)\n", " except Exception as e:\n", " traceback.print_exc()\n", " pool = ThreadPoolExecutor(max_workers=worker_num)\n", " all_task = []\n", " for i, iid in enumerate(image_list):\n", " all_task.append(pool.submit(work_fn, iid,i))\n", " wait(all_task)\n", " pool.shutdown()" ], "metadata": { "_uuid": "8f2839f25d086af736a60e9eeb907d3b93b6e0e5", "_cell_guid": "b1076dfc-b9ad-4769-8c92-a6c4dae69d19", "execution": { "iopub.status.busy": "2023-02-14T11:44:24.070496Z", "iopub.execute_input": "2023-02-14T11:44:24.071422Z", "iopub.status.idle": "2023-02-14T11:44:24.430445Z", "shell.execute_reply.started": "2023-02-14T11:44:24.071315Z", "shell.execute_reply": "2023-02-14T11:44:24.429283Z" }, "trusted": true, "pycharm": { "name": "#%%\n" } }, "execution_count": 1, "outputs": [] }, { "cell_type": "code", "execution_count": null, "outputs": [], "source": [ "download_all(6019085,6019085 - 50000,8)" ], "metadata": { "collapsed": false, "pycharm": { "name": "#%%\n" } } } ] }