r3lax jainr3 commited on
Commit
e416e25
·
0 Parent(s):

Duplicate from jainr3/diffusiondb-pixelart

Browse files

Co-authored-by: Rahul Jain <jainr3@users.noreply.huggingface.co>

.gitattributes ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ *.7z filter=lfs diff=lfs merge=lfs -text
2
+ *.arrow filter=lfs diff=lfs merge=lfs -text
3
+ *.bin filter=lfs diff=lfs merge=lfs -text
4
+ *.bz2 filter=lfs diff=lfs merge=lfs -text
5
+ *.ckpt filter=lfs diff=lfs merge=lfs -text
6
+ *.ftz filter=lfs diff=lfs merge=lfs -text
7
+ *.gz filter=lfs diff=lfs merge=lfs -text
8
+ *.h5 filter=lfs diff=lfs merge=lfs -text
9
+ *.joblib filter=lfs diff=lfs merge=lfs -text
10
+ *.lfs.* filter=lfs diff=lfs merge=lfs -text
11
+ *.lz4 filter=lfs diff=lfs merge=lfs -text
12
+ *.mlmodel filter=lfs diff=lfs merge=lfs -text
13
+ *.model filter=lfs diff=lfs merge=lfs -text
14
+ *.msgpack filter=lfs diff=lfs merge=lfs -text
15
+ *.npy filter=lfs diff=lfs merge=lfs -text
16
+ *.npz filter=lfs diff=lfs merge=lfs -text
17
+ *.onnx filter=lfs diff=lfs merge=lfs -text
18
+ *.ot filter=lfs diff=lfs merge=lfs -text
19
+ *.parquet filter=lfs diff=lfs merge=lfs -text
20
+ *.pb filter=lfs diff=lfs merge=lfs -text
21
+ *.pickle filter=lfs diff=lfs merge=lfs -text
22
+ *.pkl filter=lfs diff=lfs merge=lfs -text
23
+ *.pt filter=lfs diff=lfs merge=lfs -text
24
+ *.pth filter=lfs diff=lfs merge=lfs -text
25
+ *.rar filter=lfs diff=lfs merge=lfs -text
26
+ *.safetensors filter=lfs diff=lfs merge=lfs -text
27
+ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
28
+ *.tar.* filter=lfs diff=lfs merge=lfs -text
29
+ *.tflite filter=lfs diff=lfs merge=lfs -text
30
+ *.tgz filter=lfs diff=lfs merge=lfs -text
31
+ *.wasm filter=lfs diff=lfs merge=lfs -text
32
+ *.xz filter=lfs diff=lfs merge=lfs -text
33
+ *.zip filter=lfs diff=lfs merge=lfs -text
34
+ *.zst filter=lfs diff=lfs merge=lfs -text
35
+ *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ # Audio files - uncompressed
37
+ *.pcm filter=lfs diff=lfs merge=lfs -text
38
+ *.sam filter=lfs diff=lfs merge=lfs -text
39
+ *.raw filter=lfs diff=lfs merge=lfs -text
40
+ # Audio files - compressed
41
+ *.aac filter=lfs diff=lfs merge=lfs -text
42
+ *.flac filter=lfs diff=lfs merge=lfs -text
43
+ *.mp3 filter=lfs diff=lfs merge=lfs -text
44
+ *.ogg filter=lfs diff=lfs merge=lfs -text
45
+ *.wav filter=lfs diff=lfs merge=lfs -text
46
+ # Image files - uncompressed
47
+ *.bmp filter=lfs diff=lfs merge=lfs -text
48
+ *.gif filter=lfs diff=lfs merge=lfs -text
49
+ *.png filter=lfs diff=lfs merge=lfs -text
50
+ *.tiff filter=lfs diff=lfs merge=lfs -text
51
+ # Image files - compressed
52
+ *.jpg filter=lfs diff=lfs merge=lfs -text
53
+ *.jpeg filter=lfs diff=lfs merge=lfs -text
54
+ *.webp filter=lfs diff=lfs merge=lfs -text
.gitignore ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ *.log
2
+ .DS_Store
3
+ git-add.py
README.md ADDED
@@ -0,0 +1,281 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ layout: default
3
+ title: Home
4
+ nav_order: 1
5
+ has_children: false
6
+
7
+ annotations_creators:
8
+ - no-annotation
9
+ language:
10
+ - en
11
+ language_creators:
12
+ - found
13
+ license:
14
+ - cc0-1.0
15
+ multilinguality:
16
+ - multilingual
17
+ pretty_name: DiffusionDB-Pixelart
18
+ size_categories:
19
+ - n>1T
20
+ source_datasets:
21
+ - modified
22
+ tags:
23
+ - stable diffusion
24
+ - prompt engineering
25
+ - prompts
26
+ task_categories:
27
+ - text-to-image
28
+ - image-to-text
29
+ task_ids:
30
+ - image-captioning
31
+ ---
32
+
33
+ # DiffusionDB-Pixelart
34
+
35
+ ## Table of Contents
36
+
37
+ - [DiffusionDB](#diffusiondb)
38
+ - [Table of Contents](#table-of-contents)
39
+ - [Dataset Description](#dataset-description)
40
+ - [Dataset Summary](#dataset-summary)
41
+ - [Supported Tasks and Leaderboards](#supported-tasks-and-leaderboards)
42
+ - [Languages](#languages)
43
+ - [Subset](#subset)
44
+ - [Dataset Structure](#dataset-structure)
45
+ - [Data Instances](#data-instances)
46
+ - [Data Fields](#data-fields)
47
+ - [Dataset Metadata](#dataset-metadata)
48
+ - [Metadata Schema](#metadata-schema)
49
+ - [Data Splits](#data-splits)
50
+ - [Loading Data Subsets](#loading-data-subsets)
51
+ - [Method 1: Using Hugging Face Datasets Loader](#method-1-using-hugging-face-datasets-loader)
52
+ - [Dataset Creation](#dataset-creation)
53
+ - [Curation Rationale](#curation-rationale)
54
+ - [Source Data](#source-data)
55
+ - [Initial Data Collection and Normalization](#initial-data-collection-and-normalization)
56
+ - [Who are the source language producers?](#who-are-the-source-language-producers)
57
+ - [Annotations](#annotations)
58
+ - [Annotation process](#annotation-process)
59
+ - [Who are the annotators?](#who-are-the-annotators)
60
+ - [Personal and Sensitive Information](#personal-and-sensitive-information)
61
+ - [Considerations for Using the Data](#considerations-for-using-the-data)
62
+ - [Social Impact of Dataset](#social-impact-of-dataset)
63
+ - [Discussion of Biases](#discussion-of-biases)
64
+ - [Other Known Limitations](#other-known-limitations)
65
+ - [Additional Information](#additional-information)
66
+ - [Dataset Curators](#dataset-curators)
67
+ - [Licensing Information](#licensing-information)
68
+ - [Citation Information](#citation-information)
69
+ - [Contributions](#contributions)
70
+
71
+ ## Dataset Description
72
+
73
+ - **Homepage:** [DiffusionDB homepage](https://poloclub.github.io/diffusiondb)
74
+ - **Repository:** [DiffusionDB repository](https://github.com/poloclub/diffusiondb)
75
+ - **Distribution:** [DiffusionDB Hugging Face Dataset](https://huggingface.co/datasets/poloclub/diffusiondb)
76
+ - **Paper:** [DiffusionDB: A Large-scale Prompt Gallery Dataset for Text-to-Image Generative Models](https://arxiv.org/abs/2210.14896)
77
+
78
+ ### Dataset Summary
79
+
80
+ **This is a subset of the DiffusionDB 2M dataset which has been turned into pixel-style art.**
81
+
82
+ DiffusionDB is the first large-scale text-to-image prompt dataset. It contains **14 million** images generated by Stable Diffusion using prompts and hyperparameters specified by real users.
83
+
84
+ DiffusionDB is publicly available at [🤗 Hugging Face Dataset](https://huggingface.co/datasets/poloclub/diffusiondb).
85
+
86
+ ### Supported Tasks and Leaderboards
87
+
88
+ The unprecedented scale and diversity of this human-actuated dataset provide exciting research opportunities in understanding the interplay between prompts and generative models, detecting deepfakes, and designing human-AI interaction tools to help users more easily use these models.
89
+
90
+ ### Languages
91
+
92
+ The text in the dataset is mostly English. It also contains other languages such as Spanish, Chinese, and Russian.
93
+
94
+ ### Subset
95
+
96
+ DiffusionDB provides two subsets (DiffusionDB 2M and DiffusionDB Large) to support different needs. The pixelated version of the data was taken from the DiffusionDB 2M and has 2000 examples only.
97
+
98
+ |Subset|Num of Images|Num of Unique Prompts|Size|Image Directory|Metadata Table|
99
+ |:--|--:|--:|--:|--:|--:|
100
+ |DiffusionDB-pixelart|2k|~1.5k|~1.6GB|`images/`|`metadata.parquet`|
101
+
102
+ Images in DiffusionDB-pixelart are stored in `png` format.
103
+
104
+ ## Dataset Structure
105
+
106
+ We use a modularized file structure to distribute DiffusionDB. The 2k images in DiffusionDB-pixelart are split into folders, where each folder contains 1,000 images and a JSON file that links these 1,000 images to their prompts and hyperparameters.
107
+
108
+ ```bash
109
+ # DiffusionDB 2k
110
+ ./
111
+ ├── images
112
+ │ ├── part-000001
113
+ │ │ ├── 3bfcd9cf-26ea-4303-bbe1-b095853f5360.png
114
+ │ │ ├── 5f47c66c-51d4-4f2c-a872-a68518f44adb.png
115
+ │ │ ├── 66b428b9-55dc-4907-b116-55aaa887de30.png
116
+ │ │ ├── [...]
117
+ │ │ └── part-000001.json
118
+ │ ├── part-000002
119
+ │ ├── part-000003
120
+ │ ├── [...]
121
+ │ └── part-002000
122
+ └── metadata.parquet
123
+ ```
124
+
125
+ These sub-folders have names `part-0xxxxx`, and each image has a unique name generated by [UUID Version 4](https://en.wikipedia.org/wiki/Universally_unique_identifier). The JSON file in a sub-folder has the same name as the sub-folder. Each image is a `PNG` file (DiffusionDB-pixelart). The JSON file contains key-value pairs mapping image filenames to their prompts and hyperparameters.
126
+
127
+
128
+ ### Data Instances
129
+
130
+ For example, below is the image of `ec9b5e2c-028e-48ac-8857-a52814fd2a06.png` and its key-value pair in `part-000001.json`.
131
+
132
+ <img width="300" src="https://datasets-server.huggingface.co/assets/jainr3/diffusiondb-pixelart/--/2k_all/train/0/image/image.png">
133
+
134
+ ```json
135
+ {
136
+ "ec9b5e2c-028e-48ac-8857-a52814fd2a06.png": {
137
+ "p": "doom eternal, game concept art, veins and worms, muscular, crustacean exoskeleton, chiroptera head, chiroptera ears, mecha, ferocious, fierce, hyperrealism, fine details, artstation, cgsociety, zbrush, no background ",
138
+ "se": 3312523387,
139
+ "c": 7.0,
140
+ "st": 50,
141
+ "sa": "k_euler"
142
+ },
143
+ }
144
+ ```
145
+
146
+ ### Data Fields
147
+
148
+ - key: Unique image name
149
+ - `p`: Text
150
+
151
+ ### Dataset Metadata
152
+
153
+ To help you easily access prompts and other attributes of images without downloading all the Zip files, we include a metadata table `metadata.parquet` for DiffusionDB-pixelart.
154
+
155
+ Two tables share the same schema, and each row represents an image. We store these tables in the Parquet format because Parquet is column-based: you can efficiently query individual columns (e.g., prompts) without reading the entire table.
156
+
157
+ Below are three random rows from `metadata.parquet`.
158
+
159
+ | image_name | prompt | part_id | seed | step | cfg | sampler | width | height | user_name | timestamp | image_nsfw | prompt_nsfw |
160
+ |:-----------------------------------------|:-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|----------:|-----------:|-------:|------:|----------:|--------:|---------:|:-----------------------------------------------------------------|:--------------------------|-------------:|--------------:|
161
+ | 0c46f719-1679-4c64-9ba9-f181e0eae811.png | a small liquid sculpture, corvette, viscous, reflective, digital art | 1050 | 2026845913 | 50 | 7 | 8 | 512 | 512 | c2f288a2ba9df65c38386ffaaf7749106fed29311835b63d578405db9dbcafdb | 2022-08-11 09:05:00+00:00 | 0.0845108 | 0.00383462 |
162
+ | a00bdeaa-14eb-4f6c-a303-97732177eae9.png | human sculpture of lanky tall alien on a romantic date at italian restaurant with smiling woman, nice restaurant, photography, bokeh | 905 | 1183522603 | 50 | 10 | 8 | 512 | 768 | df778e253e6d32168eb22279a9776b3cde107cc82da05517dd6d114724918651 | 2022-08-19 17:55:00+00:00 | 0.692934 | 0.109437 |
163
+ | 6e5024ce-65ed-47f3-b296-edb2813e3c5b.png | portrait of barbaric spanish conquistador, symmetrical, by yoichi hatakenaka, studio ghibli and dan mumford | 286 | 1713292358 | 50 | 7 | 8 | 512 | 640 | 1c2e93cfb1430adbd956be9c690705fe295cbee7d9ac12de1953ce5e76d89906 | 2022-08-12 03:26:00+00:00 | 0.0773138 | 0.0249675 |
164
+
165
+ #### Metadata Schema
166
+
167
+ `metadata.parquet` schema:
168
+
169
+ |Column|Type|Description|
170
+ |:---|:---|:---|
171
+ |`image_name`|`string`|Image UUID filename.|
172
+ |`text`|`string`|The text prompt used to generate this image.|
173
+
174
+ > **Warning**
175
+ > Although the Stable Diffusion model has an NSFW filter that automatically blurs user-generated NSFW images, this NSFW filter is not perfect—DiffusionDB still contains some NSFW images. Therefore, we compute and provide the NSFW scores for images and prompts using the state-of-the-art models. The distribution of these scores is shown below. Please decide an appropriate NSFW score threshold to filter out NSFW images before using DiffusionDB in your projects.
176
+
177
+ <img src="https://i.imgur.com/1RiGAXL.png" width="100%">
178
+
179
+ ### Data Splits
180
+
181
+ For DiffusionDB-pixelart, we split 2k images into folders where each folder contains 1,000 images and a JSON file.
182
+
183
+ ### Loading Data Subsets
184
+
185
+ DiffusionDB is large! However, with our modularized file structure, you can easily load a desirable number of images and their prompts and hyperparameters. In the [`example-loading.ipynb`](https://github.com/poloclub/diffusiondb/blob/main/notebooks/example-loading.ipynb) notebook, we demonstrate three methods to load a subset of DiffusionDB. Below is a short summary.
186
+
187
+ #### Method 1: Using Hugging Face Datasets Loader
188
+
189
+ You can use the Hugging Face [`Datasets`](https://huggingface.co/docs/datasets/quickstart) library to easily load prompts and images from DiffusionDB. We pre-defined 16 DiffusionDB subsets (configurations) based on the number of instances. You can see all subsets in the [Dataset Preview](https://huggingface.co/datasets/poloclub/diffusiondb/viewer/all/train).
190
+
191
+ ```python
192
+ import numpy as np
193
+ from datasets import load_dataset
194
+
195
+ # Load the dataset with the `2k_random_1k` subset
196
+ dataset = load_dataset('jainr3/diffusiondb-pixelart', '2k_random_1k')
197
+ ```
198
+
199
+ ## Dataset Creation
200
+
201
+ ### Curation Rationale
202
+
203
+ Recent diffusion models have gained immense popularity by enabling high-quality and controllable image generation based on text prompts written in natural language. Since the release of these models, people from different domains have quickly applied them to create award-winning artworks, synthetic radiology images, and even hyper-realistic videos.
204
+
205
+ However, generating images with desired details is difficult, as it requires users to write proper prompts specifying the exact expected results. Developing such prompts requires trial and error, and can often feel random and unprincipled. Simon Willison analogizes writing prompts to wizards learning “magical spells”: users do not understand why some prompts work, but they will add these prompts to their “spell book.” For example, to generate highly-detailed images, it has become a common practice to add special keywords such as “trending on artstation” and “unreal engine” in the prompt.
206
+
207
+ Prompt engineering has become a field of study in the context of text-to-text generation, where researchers systematically investigate how to construct prompts to effectively solve different down-stream tasks. As large text-to-image models are relatively new, there is a pressing need to understand how these models react to prompts, how to write effective prompts, and how to design tools to help users generate images.
208
+ To help researchers tackle these critical challenges, we create DiffusionDB, the first large-scale prompt dataset with 14 million real prompt-image pairs.
209
+
210
+ ### Source Data
211
+
212
+ #### Initial Data Collection and Normalization
213
+
214
+ We construct DiffusionDB by scraping user-generated images on the official Stable Diffusion Discord server. We choose Stable Diffusion because it is currently the only open-source large text-to-image generative model, and all generated images have a CC0 1.0 Universal Public Domain Dedication license that waives all copyright and allows uses for any purpose. We choose the official [Stable Diffusion Discord server](https://discord.gg/stablediffusion) because it is public, and it has strict rules against generating and sharing illegal, hateful, or NSFW (not suitable for work, such as sexual and violent content) images. The server also disallows users to write or share prompts with personal information.
215
+
216
+ #### Who are the source language producers?
217
+
218
+ The language producers are users of the official [Stable Diffusion Discord server](https://discord.gg/stablediffusion).
219
+
220
+ ### Annotations
221
+
222
+ The dataset does not contain any additional annotations.
223
+
224
+ #### Annotation process
225
+
226
+ [N/A]
227
+
228
+ #### Who are the annotators?
229
+
230
+ [N/A]
231
+
232
+ ### Personal and Sensitive Information
233
+
234
+ The authors removed the discord usernames from the dataset.
235
+ We decide to anonymize the dataset because some prompts might include sensitive information: explicitly linking them to their creators can cause harm to creators.
236
+
237
+ ## Considerations for Using the Data
238
+
239
+ ### Social Impact of Dataset
240
+
241
+ The purpose of this dataset is to help develop better understanding of large text-to-image generative models.
242
+ The unprecedented scale and diversity of this human-actuated dataset provide exciting research opportunities in understanding the interplay between prompts and generative models, detecting deepfakes, and designing human-AI interaction tools to help users more easily use these models.
243
+
244
+ It should note that we collect images and their prompts from the Stable Diffusion Discord server. The Discord server has rules against users generating or sharing harmful or NSFW (not suitable for work, such as sexual and violent content) images. The Stable Diffusion model used in the server also has an NSFW filter that blurs the generated images if it detects NSFW content. However, it is still possible that some users had generated harmful images that were not detected by the NSFW filter or removed by the server moderators. Therefore, DiffusionDB can potentially contain these images. To mitigate the potential harm, we provide a [Google Form](https://forms.gle/GbYaSpRNYqxCafMZ9) on the [DiffusionDB website](https://poloclub.github.io/diffusiondb/) where users can report harmful or inappropriate images and prompts. We will closely monitor this form and remove reported images and prompts from DiffusionDB.
245
+
246
+ ### Discussion of Biases
247
+
248
+ The 14 million images in DiffusionDB have diverse styles and categories. However, Discord can be a biased data source. Our images come from channels where early users could use a bot to use Stable Diffusion before release. As these users had started using Stable Diffusion before the model was public, we hypothesize that they are AI art enthusiasts and are likely to have experience with other text-to-image generative models. Therefore, the prompting style in DiffusionDB might not represent novice users. Similarly, the prompts in DiffusionDB might not generalize to domains that require specific knowledge, such as medical images.
249
+
250
+ ### Other Known Limitations
251
+
252
+ **Generalizability.** Previous research has shown a prompt that works well on one generative model might not give the optimal result when used in other models.
253
+ Therefore, different models can need users to write different prompts. For example, many Stable Diffusion prompts use commas to separate keywords, while this pattern is less seen in prompts for DALL-E 2 or Midjourney. Thus, we caution researchers that some research findings from DiffusionDB might not be generalizable to other text-to-image generative models.
254
+
255
+ ## Additional Information
256
+
257
+ ### Dataset Curators
258
+
259
+ DiffusionDB is created by [Jay Wang](https://zijie.wang), [Evan Montoya](https://www.linkedin.com/in/evan-montoya-b252391b4/), [David Munechika](https://www.linkedin.com/in/dmunechika/), [Alex Yang](https://alexanderyang.me), [Ben Hoover](https://www.bhoov.com), [Polo Chau](https://faculty.cc.gatech.edu/~dchau/).
260
+
261
+
262
+ ### Licensing Information
263
+
264
+ The DiffusionDB dataset is available under the [CC0 1.0 License](https://creativecommons.org/publicdomain/zero/1.0/).
265
+ The Python code in this repository is available under the [MIT License](https://github.com/poloclub/diffusiondb/blob/main/LICENSE).
266
+
267
+ ### Citation Information
268
+
269
+ ```bibtex
270
+ @article{wangDiffusionDBLargescalePrompt2022,
271
+ title = {{{DiffusionDB}}: {{A}} Large-Scale Prompt Gallery Dataset for Text-to-Image Generative Models},
272
+ author = {Wang, Zijie J. and Montoya, Evan and Munechika, David and Yang, Haoyang and Hoover, Benjamin and Chau, Duen Horng},
273
+ year = {2022},
274
+ journal = {arXiv:2210.14896 [cs]},
275
+ url = {https://arxiv.org/abs/2210.14896}
276
+ }
277
+ ```
278
+
279
+ ### Contributions
280
+
281
+ If you have any questions, feel free to [open an issue](https://github.com/poloclub/diffusiondb/issues/new) or contact the original author [Jay Wang](https://zijie.wang).
diffusiondb-pixelart.py ADDED
@@ -0,0 +1,324 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Original Copyright 2022 Jay Wang, Evan Montoya, David Munechika, Alex Yang, Ben Hoover, Polo Chau
2
+ # MIT License
3
+ """Loading script for DiffusionDB."""
4
+
5
+ import re
6
+ import numpy as np
7
+ import pandas as pd
8
+
9
+ from json import load, dump
10
+ from os.path import join, basename
11
+ from huggingface_hub import hf_hub_url
12
+
13
+ import datasets
14
+
15
+ # Find for instance the citation on arxiv or on the dataset repo/website
16
+ _CITATION = """\
17
+ @article{wangDiffusionDBLargescalePrompt2022,
18
+ title = {{{DiffusionDB}}: {{A}} Large-Scale Prompt Gallery Dataset for Text-to-Image Generative Models},
19
+ author = {Wang, Zijie J. and Montoya, Evan and Munechika, David and Yang, Haoyang and Hoover, Benjamin and Chau, Duen Horng},
20
+ year = {2022},
21
+ journal = {arXiv:2210.14896 [cs]},
22
+ url = {https://arxiv.org/abs/2210.14896}
23
+ }
24
+ """
25
+
26
+ # You can copy an official description
27
+ _DESCRIPTION = """
28
+ DiffusionDB is the first large-scale text-to-image prompt dataset. It contains 2
29
+ million images generated by Stable Diffusion using prompts and hyperparameters
30
+ specified by real users. The unprecedented scale and diversity of this
31
+ human-actuated dataset provide exciting research opportunities in understanding
32
+ the interplay between prompts and generative models, detecting deepfakes, and
33
+ designing human-AI interaction tools to help users more easily use these models.
34
+ """
35
+
36
+ _HOMEPAGE = "https://poloclub.github.io/diffusiondb"
37
+ _LICENSE = "CC0 1.0"
38
+ _VERSION = datasets.Version("0.9.1")
39
+
40
+ # Programmatically generate the URLs for different parts
41
+ # hf_hub_url() provides a more flexible way to resolve the file URLs
42
+ # https://huggingface.co/datasets/jainr3/diffusiondb-pixelart/resolve/main/images/part-000001.zip
43
+ _URLS = {}
44
+ _PART_IDS = range(1, 3)
45
+
46
+ for i in _PART_IDS:
47
+ _URLS[i] = hf_hub_url(
48
+ "jainr3/diffusiondb-pixelart",
49
+ filename=f"images/part-{i:06}.zip",
50
+ repo_type="dataset",
51
+ )
52
+
53
+
54
+ # Add the metadata parquet URL as well
55
+ _URLS["metadata"] = hf_hub_url(
56
+ "jainr3/diffusiondb-pixelart", filename="metadata.parquet", repo_type="dataset"
57
+ )
58
+
59
+ _SAMPLER_DICT = {
60
+ 1: "ddim",
61
+ 2: "plms",
62
+ 3: "k_euler",
63
+ 4: "k_euler_ancestral",
64
+ 5: "ddik_heunm",
65
+ 6: "k_dpm_2",
66
+ 7: "k_dpm_2_ancestral",
67
+ 8: "k_lms",
68
+ 9: "others",
69
+ }
70
+
71
+
72
+ class DiffusionDBConfig(datasets.BuilderConfig):
73
+ """BuilderConfig for DiffusionDB."""
74
+
75
+ def __init__(self, part_ids, **kwargs):
76
+ """BuilderConfig for DiffusionDB.
77
+ Args:
78
+ part_ids([int]): A list of part_ids.
79
+ **kwargs: keyword arguments forwarded to super.
80
+ """
81
+ super(DiffusionDBConfig, self).__init__(version=_VERSION, **kwargs)
82
+ self.part_ids = part_ids
83
+
84
+
85
+ class DiffusionDB(datasets.GeneratorBasedBuilder):
86
+ """A large-scale text-to-image prompt gallery dataset based on Stable Diffusion."""
87
+
88
+ BUILDER_CONFIGS = []
89
+
90
+ # Programmatically generate configuration options (HF requires to use a string
91
+ # as the config key)
92
+ for num_k in [1, 2]:
93
+ for sampling in ["first", "random"]:
94
+ num_k_str = f"{num_k}k" if num_k < 1000 else f"{num_k // 1000}m"
95
+ subset_str = "2k_"
96
+
97
+ if sampling == "random":
98
+ # Name the config
99
+ cur_name = subset_str + "random_" + num_k_str
100
+
101
+ # Add a short description for each config
102
+ cur_description = (
103
+ f"Random {num_k_str} images with their prompts and parameters"
104
+ )
105
+
106
+ # Sample part_ids
107
+ total_part_ids = _PART_IDS
108
+ part_ids = np.random.choice(
109
+ total_part_ids, num_k, replace=False
110
+ ).tolist()
111
+ else:
112
+ # Name the config
113
+ cur_name = subset_str + "first_" + num_k_str
114
+
115
+ # Add a short description for each config
116
+ cur_description = f"The first {num_k_str} images in this dataset with their prompts and parameters"
117
+
118
+ # Sample part_ids
119
+ total_part_ids = _PART_IDS
120
+ part_ids = total_part_ids[1 : num_k + 1]
121
+
122
+ # Create configs
123
+ BUILDER_CONFIGS.append(
124
+ DiffusionDBConfig(
125
+ name=cur_name,
126
+ part_ids=part_ids,
127
+ description=cur_description,
128
+ ),
129
+ )
130
+
131
+
132
+ # Need to manually add all (2k)
133
+ BUILDER_CONFIGS.append(
134
+ DiffusionDBConfig(
135
+ name="2k_all",
136
+ part_ids=_PART_IDS,
137
+ description="All images with their prompts and parameters",
138
+ ),
139
+ )
140
+
141
+ # We also prove a text-only option, which loads the metadata parquet file
142
+ BUILDER_CONFIGS.append(
143
+ DiffusionDBConfig(
144
+ name="2k_text_only",
145
+ part_ids=[],
146
+ description="Only include all prompts and parameters (no image)",
147
+ ),
148
+ )
149
+
150
+
151
+ # Default to only load 1k random images
152
+ DEFAULT_CONFIG_NAME = "2k_random_1k"
153
+
154
+ def _info(self):
155
+ """Specify the information of DiffusionDB."""
156
+
157
+ if "text_only" in self.config.name:
158
+ features = datasets.Features(
159
+ {
160
+ "image_name": datasets.Value("string"),
161
+ "text": datasets.Value("string"),
162
+ #"part_id": datasets.Value("uint16"),
163
+ #"seed": datasets.Value("uint32"),
164
+ #"step": datasets.Value("uint16"),
165
+ #"cfg": datasets.Value("float32"),
166
+ #"sampler": datasets.Value("string"),
167
+ #"width": datasets.Value("uint16"),
168
+ #"height": datasets.Value("uint16"),
169
+ #"user_name": datasets.Value("string"),
170
+ #"timestamp": datasets.Value("timestamp[us, tz=UTC]"),
171
+ #"image_nsfw": datasets.Value("float32"),
172
+ #"prompt_nsfw": datasets.Value("float32"),
173
+ },
174
+ )
175
+
176
+ else:
177
+ features = datasets.Features(
178
+ {
179
+ "image": datasets.Image(),
180
+ "text": datasets.Value("string"),
181
+ #"seed": datasets.Value("uint32"),
182
+ #"step": datasets.Value("uint16"),
183
+ #"cfg": datasets.Value("float32"),
184
+ #"sampler": datasets.Value("string"),
185
+ #"width": datasets.Value("uint16"),
186
+ #"height": datasets.Value("uint16"),
187
+ #"user_name": datasets.Value("string"),
188
+ #"timestamp": datasets.Value("timestamp[us, tz=UTC]"),
189
+ #"image_nsfw": datasets.Value("float32"),
190
+ #"prompt_nsfw": datasets.Value("float32"),
191
+ },
192
+ )
193
+
194
+ return datasets.DatasetInfo(
195
+ description=_DESCRIPTION,
196
+ features=features,
197
+ supervised_keys=None,
198
+ homepage=_HOMEPAGE,
199
+ license=_LICENSE,
200
+ citation=_CITATION,
201
+ )
202
+
203
+ def _split_generators(self, dl_manager):
204
+ # If several configurations are possible (listed in BUILDER_CONFIGS),
205
+ # the configuration selected by the user is in self.config.name
206
+
207
+ # dl_manager is a datasets.download.DownloadManager that can be used to
208
+ # download and extract URLS It can accept any type or nested list/dict
209
+ # and will give back the same structure with the url replaced with path
210
+ # to local files. By default the archives will be extracted and a path
211
+ # to a cached folder where they are extracted is returned instead of the
212
+ # archive
213
+
214
+ # Download and extract zip files of all sampled part_ids
215
+ data_dirs = []
216
+ json_paths = []
217
+
218
+ # Resolve the urls
219
+ urls = _URLS
220
+
221
+ for cur_part_id in self.config.part_ids:
222
+ cur_url = urls[cur_part_id]
223
+ data_dir = dl_manager.download_and_extract(cur_url)
224
+
225
+ data_dirs.append(data_dir)
226
+ json_paths.append(join(data_dir, f"part-{cur_part_id:06}.json"))
227
+
228
+ # Also download the metadata table
229
+ metadata_path = dl_manager.download(urls["metadata"])
230
+
231
+ return [
232
+ datasets.SplitGenerator(
233
+ name=datasets.Split.TRAIN,
234
+ # These kwargs will be passed to _generate_examples
235
+ gen_kwargs={
236
+ "data_dirs": data_dirs,
237
+ "json_paths": json_paths,
238
+ "metadata_path": metadata_path,
239
+ },
240
+ ),
241
+ ]
242
+
243
+ def _generate_examples(self, data_dirs, json_paths, metadata_path):
244
+ # This method handles input defined in _split_generators to yield
245
+ # (key, example) tuples from the dataset.
246
+ # The `key` is for legacy reasons (tfds) and is not important in itself,
247
+ # but must be unique for each example.
248
+
249
+ # Load the metadata parquet file if the config is text_only
250
+ if "text_only" in self.config.name:
251
+ metadata_df = pd.read_parquet(metadata_path)
252
+ for _, row in metadata_df.iterrows():
253
+ yield row["image_name"], {
254
+ "image_name": row["image_name"],
255
+ "text": row["prompt"],
256
+ #"part_id": row["part_id"],
257
+ #"seed": row["seed"],
258
+ #"step": row["step"],
259
+ #"cfg": row["cfg"],
260
+ #"sampler": _SAMPLER_DICT[int(row["sampler"])],
261
+ #"width": row["width"],
262
+ #"height": row["height"],
263
+ #"user_name": row["user_name"],
264
+ #"timestamp": None
265
+ #if pd.isnull(row["timestamp"])
266
+ #else row["timestamp"],
267
+ #"image_nsfw": row["image_nsfw"],
268
+ #"prompt_nsfw": row["prompt_nsfw"],
269
+ }
270
+
271
+ else:
272
+ num_data_dirs = len(data_dirs)
273
+ assert num_data_dirs == len(json_paths)
274
+
275
+ # Read the metadata table (only rows with the needed part_ids)
276
+ part_ids = []
277
+ for path in json_paths:
278
+ cur_id = int(re.sub(r"part-(\d+)\.json", r"\1", basename(path)))
279
+ part_ids.append(cur_id)
280
+
281
+ # We have to use pandas here to make the dataset preview work (it
282
+ # uses streaming mode)
283
+
284
+ print(metadata_path)
285
+
286
+ metadata_table = pd.read_parquet(
287
+ metadata_path,
288
+ filters=[("part_id", "in", part_ids)],
289
+ )
290
+
291
+ # Iterate through all extracted zip folders for images
292
+ for k in range(num_data_dirs):
293
+ cur_data_dir = data_dirs[k]
294
+ cur_json_path = json_paths[k]
295
+
296
+ json_data = load(open(cur_json_path, "r", encoding="utf8"))
297
+
298
+ for img_name in json_data:
299
+ img_params = json_data[img_name]
300
+ img_path = join(cur_data_dir, img_name)
301
+
302
+ # Query the metadata
303
+ query_result = metadata_table.query(f'`image_name` == "{img_name}"')
304
+
305
+ # Yields examples as (key, example) tuples
306
+ yield img_name, {
307
+ "image": {
308
+ "path": img_path,
309
+ "bytes": open(img_path, "rb").read(),
310
+ },
311
+ "text": img_params["p"],
312
+ #"seed": int(img_params["se"]),
313
+ #"step": int(img_params["st"]),
314
+ #"cfg": float(img_params["c"]),
315
+ #"sampler": img_params["sa"],
316
+ #"width": query_result["width"].to_list()[0],
317
+ #"height": query_result["height"].to_list()[0],
318
+ #"user_name": query_result["user_name"].to_list()[0],
319
+ #"timestamp": None
320
+ #if pd.isnull(query_result["timestamp"].to_list()[0])
321
+ #else query_result["timestamp"].to_list()[0],
322
+ #"image_nsfw": query_result["image_nsfw"].to_list()[0],
323
+ #"prompt_nsfw": query_result["prompt_nsfw"].to_list()[0],
324
+ }
images/part-000001.zip ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:89c10b2e60a529636ed34492bee016eaae1d23015cf5de1b83763fed54fd07dd
3
+ size 10036434
images/part-000002.zip ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:087c8324707560a6045d7a10aa92367f98fe44493eaa961771752ff6bf8288ac
3
+ size 9415809
metadata.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:eecd341187bc91c07f5994ad0660d40228ea025616fd57a509bef8323677c68f
3
+ size 194548652