File size: 7,468 Bytes
0f1836a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
{
 "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"
    }
   }
  }
 ]
}