File size: 61,816 Bytes
bab67db
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
---

license: creativeml-openrail-m
---


# PureDanbooru Dataset

![WarriorMama777/PureDanbooru](https://raw.githubusercontent.com/WarriorMama777/imgup/68e92130ebe2abaaa27c2953d96e8ce8859f7dd1/img/__Repository/huggingface/AI/PureDanbooru/WebAssets_heroimage_PureDanbooru_comp001.webp "WarriorMama777_huggingface_PureDanbooru")

WarriorMama777/PureDanbooru

## 概要

このデータセットはDanbooruをメインに700万枚のイラストで構成された大規模な画像データセットです。

特徴は以下の通りです。

- Danbooruのタグを純粋に維持した未検閲のトレーニング用データセット。Danbooruのユーザーたちが地道に長年作業してきたタグ付けの作業がピュアに維持されています。
- 丁寧な前処理、およびトレーニング用にデータを整形済み。sd-scriptsのFinetuningにほぼ準拠した形でトレーニング用Jsonが提供されており、箱から出してすぐに使えます。

* * *

## Table of Contents

- [PureDanbooru Dataset](#puredanbooru-dataset)
  - [概要](#概要)
  - [Table of Contents](#table-of-contents)
  - [データセットの詳細](#データセットの詳細)
    - [画像の収集](#画像の収集)
      - [内容](#内容)
      - [ダウンロードコマンド例](#ダウンロードコマンド例)
    - [前処理ツール](#前処理ツール)
    - [サイズ](#サイズ)
    - [画像の種類と形式および削減率](#画像の種類と形式および削減率)
    - [タグとメタデータ](#タグとメタデータ)
      - [メタデータ](#メタデータ)
      - [タグ](#タグ)
        - [形式](#形式)
        - [変換処理](#変換処理)
      - [キャプション](#キャプション)
      - [json](#json)
        - [相対パス](#相対パス)
        - [相対パスでもデータセットの画像を読めるようにする](#相対パスでもデータセットの画像を読めるようにする)
        - [絶対パス](#絶対パス)
        - [変換処理サンプルコマンド](#変換処理サンプルコマンド)
        - [編集方法](#編集方法)
  - [使用方法](#使用方法)
    - [ダウンロード](#ダウンロード)
      - [すべてダウンロード](#すべてダウンロード)
      - [特定のディレクトリをダウンロード](#特定のディレクトリをダウンロード)
    - [解凍方法](#解凍方法)
    - [使用例](#使用例)
  - [データセットの構造](#データセットの構造)
    - [ファイル構成](#ファイル構成)
    - [データ形式](#データ形式)
  - [ライセンス](#ライセンス)
  - [引用](#引用)
  - [謝辞](#謝辞)
  - [連絡先情報](#連絡先情報)
  - [更新履歴](#更新履歴)
  - [免責事項](#免責事項)
- [-----English------](#-----english------)
- [PureDanbooru Dataset](#puredanbooru-dataset-1)
  - [Overview](#overview)
  - [Dataset Details](#dataset-details)
    - [Image Collection](#image-collection)
      - [Content](#content)
      - [Download Command Example](#download-command-example)
    - [Preprocessing Tool](#preprocessing-tool)
    - [Size](#size)
    - [Types and Formats of Images and Reduction Rate](#types-and-formats-of-images-and-reduction-rate)
    - [Tags and Metadata](#tags-and-metadata)
      - [Metadata](#metadata)
      - [Tags](#tags)
        - [Format](#format)
        - [Conversion Process](#conversion-process)
      - [Captions](#captions)
        - [👁‍🗨VLM Test Result Sample (Anime illustration)](#vlm-test-result-sample-anime-illustration)
      - [json](#json-1)
        - [Relative Path](#relative-path)
        - [Making dataset images readable with relative paths](#making-dataset-images-readable-with-relative-paths)
        - [Absolute Path](#absolute-path)
        - [Sample Command for Conversion Process](#sample-command-for-conversion-process)
        - [Editing Method](#editing-method)
  - [Usage](#usage)
    - [Download](#download)
      - [Download Everything](#download-everything)
      - [Download Specific Directories](#download-specific-directories)
    - [How to Decompress](#how-to-decompress)
    - [Usage Example](#usage-example)
  - [Dataset structure](#dataset-structure)
    - [Directory structure](#directory-structure)
    - [Data Format](#data-format)
  - [License](#license)
  - [Citation](#citation)
  - [Acknowledgements](#acknowledgements)
  - [Contact Information](#contact-information)
  - [Update History](#update-history)
  - [Disclaimer](#disclaimer)

* * *

## データセットの詳細

画像は主にDanbooruのイラストレーションで構成されています(Danbooruの一部のタグは隠されており有料会員しか閲覧できないので、その部分をGelbooru等から補填しています)。

### 画像の収集

主にDanbooruからgallery-dlを使用して収集したデータセットです。収集方法の詳細は以下の通りです。

- **収集方法**:
  
    - Danbooruのクエリを用いて特定の検索ワードに対するURLを取得し、gallery-dlのためのコマンドリストを作成。
    - 画像IDを15,000ごとに分割し、2024年4月時点でDanbooruに存在していたほぼすべての画像を数日から数週間かけて収集。
- **画像フィルタリング**:
  
    - スコアがマイナスの画像を除外。
    - 画像サイズが10KB以上15MB以下のものに限定。これは、非常に大きなキャンバスサイズの画像が収集作業の妨げになるのを防ぐためです。
- **注意点**:
  - 収集過程でリクエストを大量に送信した結果、CloudflareからBANを受け、生IPではDanbooruから画像をダウンロードできなくなりました🥺 このため、VPNを使用して作業を継続しましたが、この方法は推奨しません。

#### 内容

- 初板
    - Danbooru|id1 ~ id7440000

#### ダウンロードコマンド例

- Danbooruの検索クエリ:`score:>-1 id:1..15000 filetype:png,jpg,webp filesize:10kb..15m`
- gallery-dlのダウンロードコマンド例:`gallery-dl "https://danbooru.donmai.us/posts?tags=score%3A%3E-1+id%3A1..15000+filetype%3Apng%2Cjpg%2Cwebp+filesize%3A10kb..15M&z=5" -d "D:\dataset\danbooru\images_by_15000id" --write-metadata`

### 前処理ツール

データセットの規模と複雑性に対応するため、前処理スクリプトライブラリを同時に開発する必要がありました。このライブラリ"data-kitchen"は、すべてがAI によってプログラミングされたシンプルなコードで構成されていますが、データセットを構築する上での様々なタスクを効率的に処理することができました。  
このカスタム前処理ライブラリのおかげで、データセットの構築プロセスが合理化され、大規模な画像コレクションを作成することができました。  
[![WarriorMama777/data-kitchen](https://raw.githubusercontent.com/WarriorMama777/imgup/main/img/__Repository/Github/data-kitchen/WebAssets_heroimage_data-kitchen_03_comp001.webp)](https://github.com/WarriorMama777/data-kitchen)

### サイズ

- 画像/メタデータ/タグテキスト:それぞれ約700万
- 画像総ファイルサイズ:約1.3TB (圧縮時&解凍時)
- データセットjson:約2000万行、約40億文字数

### 画像の種類と形式および削減率

画像はすべて以下の形式に前処理されています。

- 画像形式:webp
- 品質:90
- 長辺が2048pxになるようにリサイズ
- 透過背景は白背景に変換

これによって、7.86 TB だった圧縮前のデータ量が、圧縮後には 1.3 TB になりました。これはデータ量を約 83.47% 削減したことになります。

### タグとメタデータ

#### メタデータ

メタデータはgallery-dlの`--write-metadata`を使ってDanbooruのオリジナルな情報を収集しています。  
具体的には以下のような形式で保存されています。

```json

{

    "id": 1,

    "created_at": "2005-05-23T23:35:31.000-04:00",

    "uploader_id": 1,

    "score": 715,

    "source": "http://www.biwa.ne.jp/~kyogoku/nekotama.jpg",

    "md5": "d34e4cf0a437a5d65f8e82b7bcd02606",

    "last_comment_bumped_at": "2024-03-11T16:09:34.477-04:00",

    "rating": "s",

    "image_width": 459,

    "image_height": 650,

    "tag_string": "1girl 2000s_(style) white_border white_thighhighs",

    "fav_count": 1101,

    "file_ext": "jpg",

    "last_noted_at": null,

    "parent_id": 57501,

    "has_children": false,

    "approver_id": null,

    "tag_count_general": 61,

    "tag_count_artist": 1,

    "tag_count_character": 1,

    "tag_count_copyright": 2,

    "file_size": 127238,

    "up_score": 702,

    "down_score": -3,

    "is_pending": false,

    "is_flagged": false,

    "is_deleted": false,

    "tag_count": 69,

    "updated_at": "2024-02-23T23:16:23.261-05:00",

    "is_banned": false,

    "pixiv_id": null,

    "last_commented_at": "2024-05-23T13:44:46.633-04:00",

    "has_active_children": false,

    "bit_flags": 0,

    "tag_count_meta": 4,

    "has_large": false,

    "has_visible_children": false,

    "media_asset": {

        "id": 1,

        "created_at": "2005-05-23T23:35:31.000-04:00",

        "updated_at": "2023-02-23T03:15:45.265-05:00",

        "md5": "d34e4cf0a437a5d65f8e82b7bcd02606",

        "file_ext": "jpg",

        "file_size": 127238,

        "image_width": 459,

        "image_height": 650,

        "duration": null,

        "status": "active",

        "file_key": "wUufKEivb",

        "is_public": true,

        "pixel_hash": "9c877dd5674d7fa251ce2de0c956fd36",

        "variants": [

            {

                "type": "180x180",

                "url": "https://cdn.donmai.us/180x180/d3/4e/d34e4cf0a437a5d65f8e82b7bcd02606.jpg",

                "width": 127,

                "height": 180,

                "file_ext": "jpg"

            },

            {

                "type": "360x360",

                "url": "https://cdn.donmai.us/360x360/d3/4e/d34e4cf0a437a5d65f8e82b7bcd02606.jpg",

                "width": 254,

                "height": 360,

                "file_ext": "jpg"

            },

            {

                "type": "720x720",

                "url": "https://cdn.donmai.us/720x720/d3/4e/d34e4cf0a437a5d65f8e82b7bcd02606.webp",

                "width": 459,

                "height": 650,

                "file_ext": "webp"

            },

            {

                "type": "original",

                "url": "https://cdn.donmai.us/original/d3/4e/d34e4cf0a437a5d65f8e82b7bcd02606.jpg",

                "width": 459,

                "height": 650,

                "file_ext": "jpg"

            }

        ]

    },

    "tag_string_general": "1girl 2000s_(style) white_thighhighs",

    "tag_string_character": "kousaka_tamaki",

    "tag_string_copyright": "to_heart_(series) to_heart_2",

    "tag_string_artist": "kyogoku_shin",

    "tag_string_meta": "bad_id bad_link commentary translated",

    "file_url": "https://cdn.donmai.us/original/d3/4e/d34e4cf0a437a5d65f8e82b7bcd02606.jpg",

    "large_file_url": "https://cdn.donmai.us/original/d3/4e/d34e4cf0a437a5d65f8e82b7bcd02606.jpg",

    "preview_file_url": "https://cdn.donmai.us/180x180/d3/4e/d34e4cf0a437a5d65f8e82b7bcd02606.jpg",

    "filename": "d34e4cf0a437a5d65f8e82b7bcd02606",

    "extension": "jpg",

    "date": "2005-05-24 03:35:31",

    "tags": [

        "1girl",

        "white_thighhighs"

    ],

    "tags_artist": [

        "kyogoku_shin"

    ],

    "tags_character": [

        "kousaka_tamaki"

    ],

    "tags_copyright": [

        "to_heart_(series)",

        "to_heart_2"

    ],

    "tags_general": [

        "1girl",

        "2000s_(style)",

        "white_thighhighs"

    ],

    "tags_meta": [

        "bad_id",

        "bad_link",

        "commentary",

        "translated"

    ],

    "search_tags": "score:>-1 id:1..15000 filetype:png,jpg,webp filesize:10kb..5M",

    "category": "danbooru",

    "subcategory": "tag"

}

```

#### タグ

##### 形式

タグはメタデータから以下のような形式に変換されています。

```txt

tenmaso,rozen_maiden,suiseiseki,illustration,|||,1girl,brown_hair,corset,dress,drill_hair,frills,green_dress,green_eyes,hat,heterochromia,lolita_fashion,long_hair,long_sleeves,red_eyes,ribbon,simple_background,solo,twin_drills,twintails,very_long_hair,|||,rating_g

```

タグは、下記のコマンドによってメタデータから以下のような形式に変換されています。

- Danbooruメタデータからプレーンテキストに変換された純粋なタグ
- すべてのタグに`illustration`を付与
- sd-scriptsで次のように指定することで使用できるセパレータ`|||`を、タグテキストの先頭と末尾に付与しています。:`--keep_tokens_separator="|||"`
- 並び順|「アーティスト名→作品名→キャラクター名→`illustration,|||`→タグテキスト→`|||`→レーティング」

##### 変換処理

タグはdata-kitchen/metadata_converter_danbooru.pyを使ってメタデータからプレーンテキストに変換され、tagフォルダに保存されています。変換処理のサンプルコマンドは以下のような形式になります。コマンドの具体的な内容については、data-kitchenリポジトリを確認してください。

```bash

python metadata_converter_danbooru.py --metadata_order "tag_string_artist" "tag_string_copyright" "tag_string_character" "tag_string_general" "rating" --dir "H:\dataset\metadata\Danbooru\images_by_15000id_01" --save_dir "H:\dataset\tag\Danbooru\images_by_15000id_01" --insert_custom_text 3 "`illustration,|||`" 4 "|||" --recursive --preserve_own_folder --preserve_structure --gc_disable --by_folder

```

#### キャプション

現状、次のような理由からキャプションは付属していません。

- ローカルで処理するにはコンピュータ等のリソースに限界がある
- 日本語性能の良いオープンソースVLMモデルが存在しない

CogVLMやMini-CPMは素晴らしいですが、ほとんど英語しか理解できず、多言語のOCRはできないようです。Gpt4oは本当に完璧ですが有料です。

どういうことか気になる人は、以下のトグルを確認してください🥺

<details><summary>👁‍🗨VLM Test Result Sample (Anime illustration)</summary>

▼Test01:OCR

![](https://files.catbox.moe/kj33g7.jpg)

プロンプト

> Please write a caption. It's a brief sentence that describes an image. Summarize it objectively and concisely, logically describing the main focus, actions, and context of the image. Start with the overall picture and then add specific details. Avoid personal opinions and non-essential details, and do not discuss the atmosphere of the scene or the emotions it may evoke. If there is text in the image, read it like OCR and describe it in the language it is written in (do not translate it into English unnecessarily). For background art, accurately describe objects and situations in the background. If there are no people, only describe the background. If there are characters, accurately describe features such as clothing and appearance. Summarize and describe this image in one paragraph. The base language for the description is English, but note that this does not apply to the OCR transcription function.

* * *

CogVLM2

> A young woman with short, dark hair and red eyes is captured in a moment of singing into a microphone. She wears a traditional kimono adorned with floral patterns, suggesting a cultural or celebratory event. The background is simple, with soft, warm colors and Japanese text, which may indicate the lyrics or a poetic context for her performance.

GLM 4v 9B  
[cuuupid/glm-4v-9b – Run with an API on Replicate](https://replicate.com/cuuupid/glm-4v-9b)

> The image depicts an animated character with short, dark blue hair and red eyes holding a microphone, suggesting they are singing or speaking. The character is dressed in a traditional Japanese kimono with a floral pattern in shades of blue and purple. The background is plain white with Japanese text in a casual script, likely lyrics or a poem, to the right of the character

Gpt4o

> The image depicts an anime-style character with short dark blue hair and red eyes, dressed in a traditional blue floral kimono. The character is holding a microphone and appears to be singing. Surrounding the character, there is Japanese text: "勇気の鈴が りんりんりーん ♪ ふしぎな冒険 るんるんるーん ♪".> なんのキャラクターか分かりますか?

> ChatGPT  
> はい、このキャラクターは『アイドルマスター シャイニーカラーズ』に登場する杜野凛世(もりの りんぜ)です。彼女は283プロダクションに所属するアイドルの一人で、静かでおしとやかな性格が特徴です。

* * *

▼Test02:キャラクター理解

![](https://i.imgur.com/qqBXPd5.jpeg)

CogVLM2:EN

> In a library setting, a young woman with short blue hair and glasses is engrossed in reading a green book. Beside her, a young woman with long brown hair tied in a ponytail leans in, her hand resting on the other woman's head, possibly in a gesture of comfort or to draw attention to something in the book.

Gpt4o

> The image depicts two characters from the anime "Sailor Moon." On the left is Makoto Kino (Sailor Jupiter), with long brown hair tied in a ponytail and green eyes, wearing a school uniform with a green collar and lacing detail. She is resting her head on one hand and using her other hand to pat the head of Ami Mizuno (Sailor Mercury), who has short blue hair and is wearing glasses. Ami is reading a green book and also dressed in a school uniform with a blue collar. The background features bookshelves filled with colorful books.

</details>

#### json

jsonフォルダには、タグと画像を結びつけたトレーニング用メタデータjsonファイルが保存されています。

##### 相対パス

相対パスで記載されたJson形式は以下のようになっています。

```json

{

  "Danbooru\\images_by_15000id_01\\id_1__15000\\danbooru_1_d34e4cf0a437a5d65f8e82b7bcd02606.webp": {

    "tags": "kyogoku_shin,to_heart_(series),to_heart_2,kousaka_tamaki,illustration,|||,1girl,2000s_(style),white_thighhighs,|||,rating_s"

  },

  "Danbooru\\images_by_15000id_01\\id_1__15000\\danbooru_2_710fd9cba4ef37260f9152ffa9d154d8.webp": {

    "tags": "nakamura_hisashi,cardcaptor_sakura,comic_party,leaf_(studio),to_heart_(series),to_heart_2,trigun,card_master_peach,haga_reiko,kuhonbutsu_taishi,sendou_kazuki,takase_mizuki,yoshio_(leaf),yuzuhara_konomi,illustration,|||,2boys,2girls,ahoge,,|||,rating_s"

  }

}

```

##### 相対パスでもデータセットの画像を読めるようにする

⚠sd-scriptsは現在、相対パスで記載されたJsonを読み込みません。以下のようにコードを変更する必要があります。

`train_util.py` スクリプトで相対パスに基づいてデータセットを正しく読み込めるように修正するには、次のように`train_util.py`スクリプトを修正します。具体的には、`abs_path` を設定する部分で、`os.path.exists` を使用する際に、相対パスが `subset.image_dir` からの相対パスであることを考慮して、そのパスを絶対パスに変換する処理を追加します。これによって、スクリプトがある場所に依存せずに、指定されたデータセットディレクトリ内のファイルを正しく参照できるようになります。

修正前のコード部分:

```python

                if os.path.exists(image_key):

                    abs_path = image_key

                else:

                    paths = glob_images(subset.image_dir, image_key)

                    if len(paths) > 0:

                        abs_path = paths[0]

```

修正後のコード:

```python

                # 相対パスを絶対パスに変換するためのパスを結合

                potential_path = os.path.join(subset.image_dir, image_key)

                if os.path.exists(potential_path):

                    abs_path = potential_path

                else:

                    # glob_imagesを使って、ディレクトリ内でマッチするファイルを探す

                    paths = glob_images(subset.image_dir, image_key)

                    if len(paths) > 0:

                        abs_path = paths[0]

```

この変更により、`image_key``subset.image_dir` からの相対パスである場合、そのパスを `subset.image_dir` に基づいて絶対パスに変換し、存在するかどうかをチェックします。`image_key` が直接存在しない場合に限り、`glob_images` 関数を使用してマッチするファイルを探します。これにより、入力された相対パスが機能し、データセットを正しく読み込むことができるようになります。

##### 絶対パス

現状、sd-scriptsは絶対パスであればコードを修正しなくても正しく画像を読み込むようです。  
そのため絶対パスで記載されたJsonも同梱しています。形式は以下のようになっています。

```json

{

  "H:\\Resources\\Resources_AI\\__Dataset\\forLeaningImages\\__Danbooru\\__BooruDiffusion\\dataset\\image\\Danbooru\\images_by_15000id_01\\id_1__15000\\danbooru_1_d34e4cf0a437a5d65f8e82b7bcd02606.webp": {

    "tags": "kyogoku_shin,to_heart_(series),to_heart_2,kousaka_tamaki,illustration,|||,1girl,2000s_(style),white_thighhighs,|||,rating_s"

  }

}

```

ただし記載されているパスはデータセット構築時のローカルのWindows環境下でのパスであり役に立ちませんので、適宜置換する必要があります。たとえばクラウド環境下(Runpod等)に置く場合は以下のように置換する必要があるでしょう

置換元:`H:\\Resources\\Resources_AI\\__Dataset\\forLeaningImages\\__Danbooru\\__BooruDiffusion\\dataset\\image`  
置換先:`\\workspace\\__MyFolder\\image`

##### 変換処理サンプルコマンド

変換処理のサンプルコマンドは以下のような形式になります。コマンドの具体的な内容については、data-kitchenリポジトリを確認してください。

```bash

python metadata_merger.py --dir_base "H:\dataset\Danbooru\image\images_by_15000id_01\id_1__15000" --dir_append_data "H:\dataset\Danbooru\tag\images_by_15000id_01\id_1__15000" --dir_save_json "H:\dataset\Danbooru\json\datasets_metadata.json" --append_data_key tags --save_full_path

```

##### 編集方法

データセット用のjsonは非常に巨大で、一番大きいもので2000万の行、42億のテキストがあるため、編集する際はまともなテキストエディタで開いてください。  
推奨:Notepad++  
非推奨:VSCODE、EmEditor Free、メモ帳など

## 使用方法

### ダウンロード

ダウンロードはhuggingface-cliを推奨します。事前にhuggingface-cliが使えるようにインストールてください。

```bash

pip install huggingface-hub

```

#### すべてダウンロード

このデータセットをすべてダウンロードするには以下を実行します。  
huggingfaceへのログインが求められた場合、huggingfaceのアクセストークンを入力してください。huggingfaceのアクセストークンを持っていない場合、huggingfaceでアクセストークンを作成してください。

```bash

huggingface-cli download WarriorMama777/PureDanbooru --repo-type dataset --local-dir "<download_directory_path>"

```

gitでも可能ですが、ダウンロード総量が肥大化するため非推奨です。

```bash

git lfs clone https://huggingface.co/WarriorMama777/PureDanbooru

```

#### 特定のディレクトリをダウンロード

特定のディレクトリをダウンロードするには、以下のコマンドを使用します:

```bash

huggingface-cli download WarriorMama777/PureDanbooru --repo-type dataset --local-dir "<download_directory_path>" --include <directory_to_download>

```

- `<repo_id>` はダウンロードしたいリポジトリのID(例:`username/model_name`- `<repo_type>` はリポジトリのタイプ(`model``dataset``space`のいずれか)
- `<download_directory_path>` はダウンロードしたファイルの保存先ディレクトリパス
- `<directory_to_download>` はリポジトリ内でダウンロードしたいディレクトリのパス

### 解凍方法

データセットはほとんどすべてがtarで圧縮されています。  
tarを解凍する方法は様々ですが、以下にdata-kitchenの圧縮・解凍スクリプトを用いた解凍方法を記載しておきます。  
コマンドの具体的な内容については、data-kitchenリポジトリを確認してください。

```bash

python packer.py --unpack --dir ".\image\Danbooru\images_by_15000id_01" --dir_save ".\image\Danbooru\images_by_15000id_01" --by_pack

```

### 使用例

実際にsd-scriptsを使用して学習する場合、以下のようになるでしょう。  
以下は`workspace``__MyFolder`というディレクトリを作成し、そこにPureDanbooruをダウンロード、解凍した場合を想定しています。  
ただしtomlを使用して行う方法もありますので、その場合は各自でお調べください。

```bash

accelerate launch --num_processes=4 --multi_gpu --num_machines=1 --gpu_ids=0,1,2,3 sdxl_train.py --pretrained_model_name_or_path "/workspace/stable-diffusion-webui/models/Stable-diffusion/sdxl.safetensors" --in_json "/workspace/__MyFolder/json/datasets_metadata_danbooru_images_by_15000id_01-02_hiddentag_relative-path.json" --train_data_dir "/workspace/__MyFolder/image" --output_dir "/workspace/__MyFolder/model" --precision "float" --save_precision "float" --mixed_precision "fp16" --xformers --gradient_checkpointing --enable_bucket --save_model_as "safetensors" --resolution 1024 --train_batch_size 16 --max_train_epochs 20 --save_every_n_epochs 2 --optimizer_type "prodigy" --learning_rate 1 --lr_scheduler_num_cycles 5 --lr_scheduler "cosine" --output_name "Finetuning_SDXL_PureDanbooru_v1_prodigy" --max_token_length 225 --shuffle_caption --seed 42 --logging_dir "/workspace/__MyFolder/log" --log_prefix=Finetuning_SDXL_PureDanbooru_v1_prodigy --fp8_base --optimizer_args "d_coef=0.8" "decouple=True" "weight_decay=0.01"  "use_bias_correction=True" "safeguard_warmup=True" "betas=0.9,0.99" "eps=1e-08" --keep_tokens_separator="|||" --noise_offset 0.05 --noise_offset_random_strength

```

## データセットの構造

### ファイル構成

.  
├── alphachannel  
│ └── Danbooru  
│ ├── images_by_15000id_01  

│ │ ├── id_1__15000.tar  

│ │ ├── ~~~~~~~~~~~~  

│ │ └── id_3330001__3345000.tar  

│ └── images_by_15000id_02  

│ ├── id_3345001__3360000.tar  

│ ├── ~~~~~~~~~~~~  

│ └── id_7425001__7440000.tar  
├── duplicate_image  

│ ├── Danbooru  

│ │ ├── images_by_15000id_01  
│ │ │ ├── id_1__15000.tar  

│ │ │ ├── ~~~~~~~~~~~~  

│ │ │ └── id_3330001__3345000.tar  

│ │ └── images_by_15000id_02  
│ │ ├── id_3345001__3360000.tar  

│ │ ├── ~~~~~~~~~~~~  

│ │ └── id_7425001__7440000.tar  

│ └── Gelbooru  

│ ├── hidden_tag_01.tar  

│ ├── hidden_tag_02.tar  

│ └── hidden_tag_03.tar  

├── image  

│ ├── Danbooru  

│ │ ├── images_by_15000id_01  
│ │ │ ├── id_1__15000.tar  

│ │ │ ├── ~~~~~~~~~~~~  

│ │ │ └── id_3330001__3345000.tar  

│ │ └── images_by_15000id_02  
│ │ ├── id_3345001__3360000.tar  

│ │ ├── ~~~~~~~~~~~~  

│ │ └── id_7425001__7440000.tar  

│ └── Gelbooru  

├── json  

│ ├── datasets_metadata_danbooru_images_by_15000id_01-02_full-path.json  
│ ├── datasets_metadata_danbooru_images_by_15000id_01-02_hiddentag_full-path.json  
│ ├── datasets_metadata_danbooru_images_by_15000id_01-02_hiddentag_relative-path.json  
│ └── datasets_metadata_danbooru_images_by_15000id_01-02_relative-path.json  

├── metadata  

│ ├── Danbooru  

│ │ ├── images_by_15000id_01  
│ │ │ ├── id_1__15000.tar  

│ │ │ ├── ~~~~~~~~~~~~  

│ │ │ └── id_3330001__3345000.tar  

│ │ └── images_by_15000id_02  
│ │ ├── id_3345001__3360000.tar  

│ │ ├──~~~~~~~~~~~~  

│ │ └── id_7425001__7440000.tar  

│ └── Gelbooru  

│ ├── hidden_tag_01.tar  

│ ├── hidden_tag_02.tar  

│ └── hidden_tag_03.tar  

└── tag  

├── Danbooru  

│ ├── images_by_15000id_01  
│ │ ├── id_1__15000.tar  

│ │ ├──~~~~~~~~~~~~  

│ │ └── id_3330001__3345000.tar  

│ └── images_by_15000id_02  
│ ├── id_3345001__3360000.tar  

│ ├── ~~~~~~~~~~~~  

│ └── id_7425001__7440000.tar  

└── Gelbooru  

├── hidden_tag_01.tar  

├── hidden_tag_02.tar  

└── hidden_tag_03.tar



### データ形式



これはtarで固めたデータセットをアップロードしただけの素朴なデータセットです。  

SQL🥃? Datasets🤗?? Dask🍡??? Croissant🥐??????? Parquet🤯?????????  

なにもわからない。



## ライセンス



creativeml-openrail-m



## 引用



強制ではありませんが、引用する場合は以下の形式を使用すると良いでしょう。



```

WarriorMama777. (2024). "PureDanbooru" (Version 1.0). Hugging Face. https://huggingface.co/datasets/WarriorMama777/PureDanbooru

```



## 謝辞



Danbooruおよび、Danbooruで長年にわたって地道にタグ付け作業してきたユーザーの仕事に感謝します。アーティストの皆様に対しては一方的に謝辞を送ることは控えますが、それぞれの仕事に対して敬意を表します。



## 連絡先情報



当huggingfaceリポジトリのディスカッション欄へどうぞ。



## 更新履歴



| バージョン | 日付  | 変更内容 |

| --- | --- | --- |

| v1.0.0 | 2024-07-07 | 初板  |



## 免責事項



<details><summary>READ MORE: Disclaimer (JPN)</summary> 1. AIの学習等における機械学習時の著作物の利用については、日本国著作権法第三十条の四第二項「情報解析(多数の著作物その他の大量の情報から、当該情報を構成する言語、音、影像その他の要素に係る情報を抽出し、比較、分類その他の解析を行うことをいう。第四十七条の五第一項第二号において同じ。)の用に供する場合」を参照し行っております。 [著作権法 | e-Gov法令検索: デジタル庁](https://elaws.e-gov.go.jp/document?lawid=345AC0000000048#Mp-At_30) 2. 著作物の掲載にあたっては、私的使用や研究目的である場合、商品化の資料として使用する場合(但し、商品化されるものが著作物の主たる利用目的となる場合にはこの限りではない)、批評・論評・報道での利用である場合、パロディや二次創作としてオリジナリティを発揮する場合等の例外的な著作物の使用が認められるケースに該当すると考え掲載しています。 3. 当該学習データセットは、わいせつな視覚コンテンツを直ちに表示されないよう配慮されており、学習データセットによる投稿が公共の場においてわいせつな内容を表示することを意図するものではありません。 なお、著作権者の意に反する利用や不当な利益を得る利用は避けるべきであり、著作権保有者によって正当な理由をもって当該データセットの関係する過半数の関係者から申し立てされた場合、掲載は速やかに中止されることが保証されます。 また本人は、使用する機械学習データセット中に、著作権者の権利を十分に尊重していないと評価され得る可能性を持つ情報源からのデータが含まれ得ることを認識しており、開発者等関係者が依拠すべき法律の整備等の動向について適切な監視と管理の義務を負っています。 本人は、法律や倫理に反する行為を意図しておらず、著作権者を含むイラストレーター及びアーティスト等の権利を尊重し、人工知能の開発を進めることに努めます。</details>



# -----English------



# PureDanbooru Dataset



![WarriorMama777/PureDanbooru](https://raw.githubusercontent.com/WarriorMama777/imgup/68e92130ebe2abaaa27c2953d96e8ce8859f7dd1/img/__Repository/huggingface/AI/PureDanbooru/WebAssets_heroimage_PureDanbooru_comp001.webp "WarriorMama777_huggingface_PureDanbooru")



WarriorMama777/PureDanbooru



## Overview



This dataset is a large-scale image dataset composed of 7 million illustrations, primarily from Danbooru.



Its features are as follows:



- An uncensored training dataset that purely maintains Danbooru tags. The tagging work that Danbooru users have diligently carried out over many years is purely maintained.

- Carefully preprocessed and formatted data for training. Training JSON is provided in a format compliant with sd-scripts Finetuning, ready to use out of the box.



## Dataset Details



The images are mainly composed of illustrations from Danbooru (some tags on Danbooru are hidden and can only be viewed by paid members, so those parts are supplemented from sources like Gelbooru).



### Image Collection



This dataset was mainly collected from Danbooru using gallery-dl. The details of the collection method are as follows:



- **Collection Method**:

  

    - Created a command list for gallery-dl by obtaining URLs for specific search words using Danbooru queries.

    - Divided image IDs into groups of 15,000 and collected almost all images that existed on Danbooru as of April 2024 over a period of several days to several weeks.

- **Image Filtering**:

  

    - Excluded images with negative scores.

    - Limited to images with file sizes between 10KB and 15MB. This is to prevent very large canvas size images from hindering the collection process.

- **Note**:

  

    - As a result of sending a large number of requests during the collection process, I was banned by Cloudflare and could no longer download images from Danbooru using a raw IP 🥺 Therefore, I continued my work using a VPN, but this method is not recommended.



#### Content



- Initial version

    - Danbooru | id1 ~ id7440000



#### Download Command Example



- Danbooru search query: `score:>-1 id:1..15000 filetype:png,jpg,webp filesize:10kb..15m`

- gallery-dl download command example: `gallery-dl "https://danbooru.donmai.us/posts?tags=score%3A%3E-1+id%3A1..15000+filetype%3Apng%2Cjpg%2Cwebp+filesize%3A10kb..15M&z=5" -d "D:\dataset\danbooru\images_by_15000id" --write-metadata`



### Preprocessing Tool



To handle the scale and complexity of the dataset, I needed to simultaneously develop a preprocessing script library. This library "data-kitchen" consists entirely of simple code programmed by AI, but it was able to efficiently process various tasks in building the dataset.  

Thanks to this custom preprocessing library, the dataset construction process was streamlined, allowing me to create a large-scale image collection.  

[](https://github.com/WarriorMama777/data-kitchen)



![WarriorMama777/data-kitchen](https://raw.githubusercontent.com/WarriorMama777/imgup/main/img/__Repository/Github/data-kitchen/WebAssets_heroimage_data-kitchen_03_comp001.webp)



WarriorMama777/data-kitchen



### Size



- Images/Metadata/Tag text: About 7 million each

- Total image file size: About 1.3TB (when compressed & uncompressed)

- Dataset json: About 20 million lines, about 4 billion characters



### Types and Formats of Images and Reduction Rate



All images have been preprocessed to the following format:



- Image format: webp

- Quality: 90

- Resized so that the long side becomes 2048px

- Transparent backgrounds converted to white backgrounds



This reduced the pre-compression data volume of 7.86 TB to 1.3 TB after compression. This represents a data volume reduction of about 83.47%.



### Tags and Metadata



#### Metadata



Metadata is collected using gallery-dl's `--write-metadata` to gather original information from Danbooru.  

Specifically, it is saved in the following format:



```json

{

    "id": 1,

    "created_at": "2005-05-23T23:35:31.000-04:00",
    "uploader_id": 1,

    "score": 715,

    "source": "http://www.biwa.ne.jp/~kyogoku/nekotama.jpg",

    "md5": "d34e4cf0a437a5d65f8e82b7bcd02606",

    "last_comment_bumped_at": "2024-03-11T16:09:34.477-04:00",

    "rating": "s",

    "image_width": 459,

    "image_height": 650,

    "tag_string": "1girl 2000s_(style) white_border white_thighhighs",

    "fav_count": 1101,

    "file_ext": "jpg",

    "last_noted_at": null,

    "parent_id": 57501,

    "has_children": false,

    "approver_id": null,

    "tag_count_general": 61,

    "tag_count_artist": 1,

    "tag_count_character": 1,

    "tag_count_copyright": 2,

    "file_size": 127238,

    "up_score": 702,

    "down_score": -3,

    "is_pending": false,

    "is_flagged": false,

    "is_deleted": false,

    "tag_count": 69,

    "updated_at": "2024-02-23T23:16:23.261-05:00",

    "is_banned": false,

    "pixiv_id": null,

    "last_commented_at": "2024-05-23T13:44:46.633-04:00",

    "has_active_children": false,

    "bit_flags": 0,

    "tag_count_meta": 4,

    "has_large": false,

    "has_visible_children": false,

    "media_asset": {

        "id": 1,

        "created_at": "2005-05-23T23:35:31.000-04:00",

        "updated_at": "2023-02-23T03:15:45.265-05:00",

        "md5": "d34e4cf0a437a5d65f8e82b7bcd02606",

        "file_ext": "jpg",

        "file_size": 127238,

        "image_width": 459,

        "image_height": 650,

        "duration": null,

        "status": "active",

        "file_key": "wUufKEivb",

        "is_public": true,

        "pixel_hash": "9c877dd5674d7fa251ce2de0c956fd36",

        "variants": [

            {

                "type": "180x180",

                "url": "https://cdn.donmai.us/180x180/d3/4e/d34e4cf0a437a5d65f8e82b7bcd02606.jpg",

                "width": 127,

                "height": 180,

                "file_ext": "jpg"

            },

            {

                "type": "360x360",

                "url": "https://cdn.donmai.us/360x360/d3/4e/d34e4cf0a437a5d65f8e82b7bcd02606.jpg",

                "width": 254,

                "height": 360,

                "file_ext": "jpg"

            },

            {

                "type": "720x720",

                "url": "https://cdn.donmai.us/720x720/d3/4e/d34e4cf0a437a5d65f8e82b7bcd02606.webp",

                "width": 459,

                "height": 650,

                "file_ext": "webp"

            },

            {

                "type": "original",

                "url": "https://cdn.donmai.us/original/d3/4e/d34e4cf0a437a5d65f8e82b7bcd02606.jpg",

                "width": 459,

                "height": 650,

                "file_ext": "jpg"

            }

        ]

    },

    "tag_string_general": "1girl 2000s_(style) white_thighhighs",

    "tag_string_character": "kousaka_tamaki",

    "tag_string_copyright": "to_heart_(series) to_heart_2",

    "tag_string_artist": "kyogoku_shin",

    "tag_string_meta": "bad_id bad_link commentary translated",

    "file_url": "https://cdn.donmai.us/original/d3/4e/d34e4cf0a437a5d65f8e82b7bcd02606.jpg",

    "large_file_url": "https://cdn.donmai.us/original/d3/4e/d34e4cf0a437a5d65f8e82b7bcd02606.jpg",

    "preview_file_url": "https://cdn.donmai.us/180x180/d3/4e/d34e4cf0a437a5d65f8e82b7bcd02606.jpg",

    "filename": "d34e4cf0a437a5d65f8e82b7bcd02606",

    "extension": "jpg",

    "date": "2005-05-24 03:35:31",

    "tags": [

        "1girl",

        "white_thighhighs"

    ],

    "tags_artist": [

        "kyogoku_shin"

    ],

    "tags_character": [

        "kousaka_tamaki"

    ],

    "tags_copyright": [

        "to_heart_(series)",

        "to_heart_2"

    ],

    "tags_general": [

        "1girl",

        "2000s_(style)",

        "white_thighhighs"

    ],

    "tags_meta": [

        "bad_id",

        "bad_link",

        "commentary",

        "translated"

    ],

    "search_tags": "score:>-1 id:1..15000 filetype:png,jpg,webp filesize:10kb..5M",

    "category": "danbooru",

    "subcategory": "tag"

}

```


#### Tags

##### Format

Tags are converted from metadata to the following format:

```txt

tenmaso,rozen_maiden,suiseiseki,illustration,|||,1girl,brown_hair,corset,dress,drill_hair,frills,green_dress,green_eyes,hat,heterochromia,lolita_fashion,long_hair,long_sleeves,red_eyes,ribbon,simple_background,solo,twin_drills,twintails,very_long_hair,|||,rating_g

```

Tags are converted from metadata to the following format using these commands:

- Pure tags converted from Danbooru metadata to plain text
- `illustration` is added to all tags
- The separator `|||` is added to the beginning and end of the tag text, which can be used by specifying it in sd-scripts as follows: `--keep_tokens_separator="|||"`
- Order | "Artist name → Work name → Character name → `illustration,|||` → Tag text → `|||` → Rating"

##### Conversion Process

Tags are converted from metadata to plain text using data-kitchen/metadata_converter_danbooru.py and saved in the tag folder. A sample command for the conversion process is in the following format. For specific details about the command, please check the data-kitchen repository.

```bash

python metadata_converter_danbooru.py --metadata_order "tag_string_artist" "tag_string_copyright" "tag_string_character" "tag_string_general" "rating" --dir "H:\dataset\metadata\Danbooru\images_by_15000id_01" --save_dir "H:\dataset\tag\Danbooru\images_by_15000id_01" --insert_custom_text 3 "`illustration,|||`" 4 "|||" --recursive --preserve_own_folder --preserve_structure --gc_disable --by_folder

```

#### Captions

Currently, captions are not included for the following reasons:

- There are limitations in computer and other resources for local processing
- There are no open-source VLM models with good Japanese performance

CogVLM and Mini-CPM are excellent, but they seem to understand almost only English and can't perform multilingual OCR. GPT4o is truly perfect but it's paid.

If you want to know what this means, check it out below 🥺

##### 👁‍🗨VLM Test Result Sample (Anime illustration)

▼Test01: OCR

![](https://files.catbox.moe/kj33g7.jpg)

Prompt

> Please write a caption. It's a brief sentence that describes an image. Summarize it objectively and concisely, logically describing the main focus, actions, and context of the image. Start with the overall picture and then add specific details. Avoid personal opinions and non-essential details, and do not discuss the atmosphere of the scene or the emotions it may evoke. If there is text in the image, read it like OCR and describe it in the language it is written in (do not translate it into English unnecessarily). For background art, accurately describe objects and situations in the background. If there are no people, only describe the background. If there are characters, accurately describe features such as clothing and appearance. Summarize and describe this image in one paragraph. The base language for the description is English, but note that this does not apply to the OCR transcription function.

* * *

CogVLM2

> A young woman with short, dark hair and red eyes is captured in a moment of singing into a microphone. She wears a traditional kimono adorned with floral patterns, suggesting a cultural or celebratory event. The background is simple, with soft, warm colors and Japanese text, which may indicate the lyrics or a poetic context for her performance.

GLM 4v 9B  
[cuuupid/glm-4v-9b – Run with an API on Replicate](https://replicate.com/cuuupid/glm-4v-9b)

> The image depicts an animated character with short, dark blue hair and red eyes holding a microphone, suggesting they are singing or speaking. The character is dressed in a traditional Japanese kimono with a floral pattern in shades of blue and purple. The background is plain white with Japanese text in a casual script, likely lyrics or a poem, to the right of the character

Gpt4o

> The image depicts an anime-style character with short dark blue hair and red eyes, dressed in a traditional blue floral kimono. The character is holding a microphone and appears to be singing. Surrounding the character, there is Japanese text: "勇気の鈴が りんりんりーん ♪ ふしぎな冒険 るんるんるーん ♪".> なんのキャラクターか分かりますか?

> ChatGPT  
> はい、このキャラクターは『アイドルマスター シャイニーカラーズ』に登場する杜野凛世(もりの りんぜ)です。彼女は283プロダクションに所属するアイドルの一人で、静かでおしとやかな性格が特徴です。

* * *

▼Test02: Understanding the characters

![](https://i.imgur.com/qqBXPd5.jpeg)

CogVLM2:EN

> In a library setting, a young woman with short blue hair and glasses is engrossed in reading a green book. Beside her, a young woman with long brown hair tied in a ponytail leans in, her hand resting on the other woman's head, possibly in a gesture of comfort or to draw attention to something in the book.

Gpt4o

> The image depicts two characters from the anime "Sailor Moon." On the left is Makoto Kino (Sailor Jupiter), with long brown hair tied in a ponytail and green eyes, wearing a school uniform with a green collar and lacing detail. She is resting her head on one hand and using her other hand to pat the head of Ami Mizuno (Sailor Mercury), who has short blue hair and is wearing glasses. Ami is reading a green book and also dressed in a school uniform with a blue collar. The background features bookshelves filled with colorful books.

#### json

The json folder contains training metadata json files that link tags and images.

##### Relative Path

The Json format with relative paths is as follows:

```json

{

  "Danbooru\\images_by_15000id_01\\id_1__15000\\danbooru_1_d34e4cf0a437a5d65f8e82b7bcd02606.webp": {

    "tags": "kyogoku_shin,to_heart_(series),to_heart_2,kousaka_tamaki,illustration,|||,1girl,2000s_(style),white_thighhighs,|||,rating_s"

  },

  "Danbooru\\images_by_15000id_01\\id_1__15000\\danbooru_2_710fd9cba4ef37260f9152ffa9d154d8.webp": {

    "tags": "nakamura_hisashi,cardcaptor_sakura,comic_party,leaf_(studio),to_heart_(series),to_heart_2,trigun,card_master_peach,haga_reiko,kuhonbutsu_taishi,sendou_kazuki,takase_mizuki,yoshio_(leaf),yuzuhara_konomi,illustration,|||,2boys,2girls,ahoge,,|||,rating_s"

  }

}

```

##### Making dataset images readable with relative paths

⚠ Currently, sd-scripts does not read Json written with relative paths. The code needs to be modified as follows:

To modify the `train_util.py` script to correctly read the dataset based on relative paths, you need to modify the `train_util.py` script as follows. Specifically, when setting `abs_path`, add a process to convert the relative path to an absolute path, considering that the relative path is relative to `subset.image_dir` when using `os.path.exists`. This allows the script to correctly reference files in the specified dataset directory without depending on where the script is located.

Before modification:

```python

                if os.path.exists(image_key):

                    abs_path = image_key

                else:

                    paths = glob_images(subset.image_dir, image_key)

                    if len(paths) > 0:

                        abs_path = paths[0]

```

After modification:

```python

                # Combine paths to convert relative path to absolute path

                potential_path = os.path.join(subset.image_dir, image_key)

                if os.path.exists(potential_path):

                    abs_path = potential_path

                else:

                    # Use glob_images to find matching files in the directory

                    paths = glob_images(subset.image_dir, image_key)

                    if len(paths) > 0:

                        abs_path = paths[0]

```

With this change, if `image_key` is a relative path from `subset.image_dir`, it converts the path to an absolute path based on `subset.image_dir` and checks if it exists. Only if `image_key` doesn't exist directly, it uses the `glob_images` function to find matching files. This allows the input relative paths to function and correctly load the dataset.

##### Absolute Path

Currently, it seems that sd-scripts can correctly read images with absolute paths without modifying the code.  
Therefore, I've also included Json written with absolute paths. The format is as follows:

```json

{

  "H:\\Resources\\Resources_AI\\__Dataset\\forLeaningImages\\__Danbooru\\__BooruDiffusion\\dataset\\image\\Danbooru\\images_by_15000id_01\\id_1__15000\\danbooru_1_d34e4cf0a437a5d65f8e82b7bcd02606.webp": {

    "tags": "kyogoku_shin,to_heart_(series),to_heart_2,kousaka_tamaki,illustration,|||,1girl,2000s_(style),white_thighhighs,|||,rating_s"

  }

}

```

However, the paths listed are from the local Windows environment at the time of dataset construction and are not useful, so they need to be replaced as appropriate. For example, if you're placing it in a cloud environment (like Runpod), you'll need to replace it as follows:

Replace from: `H:\\Resources\\Resources_AI\\__Dataset\\forLeaningImages\\__Danbooru\\__BooruDiffusion\\dataset\\image`  
Replace to: `\\workspace\\__MyFolder\\image`

##### Sample Command for Conversion Process

The sample command for the conversion process is in the following format. For specific details about the command, please check the data-kitchen repository.

```bash

python metadata_merger.py --dir_base "H:\dataset\Danbooru\image\images_by_15000id_01\id_1__15000" --dir_append_data "H:\dataset\Danbooru\tag\images_by_15000id_01\id_1__15000" --dir_save_json "H:\dataset\Danbooru\json\datasets_metadata.json" --append_data_key tags --save_full_path

```

##### Editing Method

The json for the dataset is extremely large, with the largest having 20 million lines and 4.2 billion characters of text, so please use a decent text editor when editing.  
Recommended: Notepad++  
Not recommended: VSCODE, EmEditor Free, Notepad, etc.

## Usage

### Download

I recommend using huggingface-cli for downloading. Please install huggingface-cli in advance so that it can be used.

```bash

pip install huggingface-hub

```

#### Download Everything

To download this entire dataset, execute the following:  
If you're asked to log in to huggingface, enter your huggingface access token. If you don't have a huggingface access token, create one on huggingface.

```bash

huggingface-cli download WarriorMama777/PureDanbooru --repo-type dataset --local-dir "<download_directory_path>"

```

It's also possible with git, but not recommended as the total download size becomes bloated.

```bash

git lfs clone https://huggingface.co/WarriorMama777/PureDanbooru

```

#### Download Specific Directories

To download specific directories, use the following command:

```bash

huggingface-cli download WarriorMama777/PureDanbooru --repo-type dataset --local-dir "<download_directory_path>" --include <directory_to_download>

```

- `<repo_id>` is the ID of the repository you want to download (e.g., `username/model_name`)
- `<repo_type>` is the type of repository (`model`, `dataset`, or `space`)
- `<download_directory_path>` is the directory path where you want to save the downloaded files
- `<directory_to_download>` is the path of the directory you want to download within the repository

### How to Decompress

Almost all of the dataset is compressed with tar.  
There are various ways to decompress tar, but I'll describe how to decompress using the compression/decompression script from data-kitchen.  
For specific details about the command, please check the data-kitchen repository.

```bash

python packer.py --unpack --dir ".\image\Danbooru\images_by_15000id_01" --dir_save ".\image\Danbooru\images_by_15000id_01" --by_pack

```

### Usage Example

When actually using sd-scripts for training, it would be like this:  
The following assumes that you've created a `__MyFolder` directory in `workspace` and downloaded and decompressed PureDanbooru there.  
However, there's also a method using toml, so please research that on your own if you prefer.

```bash

accelerate launch --num_processes=4 --multi_gpu --num_machines=1 --gpu_ids=0,1,2,3 sdxl_train.py --pretrained_model_name_or_path "/workspace/stable-diffusion-webui/models/Stable-diffusion/sdxl.safetensors" --in_json "/workspace/__MyFolder/json/datasets_metadata_danbooru_images_by_15000id_01-02_hiddentag_relative-path.json" --train_data_dir "/workspace/__MyFolder/image" --output_dir "/workspace/__MyFolder/model" --precision "float" --save_precision "float" --mixed_precision "fp16" --xformers --gradient_checkpointing --enable_bucket --save_model_as "safetensors" --resolution 1024 --train_batch_size 16 --max_train_epochs 20 --save_every_n_epochs 2 --optimizer_type "prodigy" --learning_rate 1 --lr_scheduler_num_cycles 5 --lr_scheduler "cosine" --output_name "Finetuning_SDXL_PureDanbooru_v1_prodigy" --max_token_length 225 --shuffle_caption --seed 42 --logging_dir "/workspace/__MyFolder/log" --log_prefix=Finetuning_SDXL_PureDanbooru_v1_prodigy --fp8_base --optimizer_args "d_coef=0.8" "decouple=True" "weight_decay=0.01"  "use_bias_correction=True" "safeguard_warmup=True" "betas=0.9,0.99" "eps=1e-08" --keep_tokens_separator="|||" --noise_offset 0.05 --noise_offset_random_strength

```

## Dataset structure

### Directory structure

.  
├── alphachannel  
│ └── Danbooru  
│ ├── images_by_15000id_01  

│ │ ├── id_1__15000.tar  

│ │ ├── ~~~~~~~~~~~~  

│ │ └── id_3330001__3345000.tar  

│ └── images_by_15000id_02  

│ ├── id_3345001__3360000.tar  

│ ├── ~~~~~~~~~~~~  

│ └── id_7425001__7440000.tar  
├── duplicate_image  

│ ├── Danbooru  

│ │ ├── images_by_15000id_01  
│ │ │ ├── id_1__15000.tar  

│ │ │ ├── ~~~~~~~~~~~~  

│ │ │ └── id_3330001__3345000.tar  

│ │ └── images_by_15000id_02  
│ │ ├── id_3345001__3360000.tar  

│ │ ├── ~~~~~~~~~~~~  

│ │ └── id_7425001__7440000.tar  

│ └── Gelbooru  

│ ├── hidden_tag_01.tar  

│ ├── hidden_tag_02.tar  

│ └── hidden_tag_03.tar  

├── image  

│ ├── Danbooru  

│ │ ├── images_by_15000id_01  
│ │ │ ├── id_1__15000.tar  

│ │ │ ├── ~~~~~~~~~~~~  

│ │ │ └── id_3330001__3345000.tar  

│ │ └── images_by_15000id_02  
│ │ ├── id_3345001__3360000.tar  

│ │ ├── ~~~~~~~~~~~~  

│ │ └── id_7425001__7440000.tar  

│ └── Gelbooru  

├── json  

│ ├── datasets_metadata_danbooru_images_by_15000id_01-02_full-path.json  
│ ├── datasets_metadata_danbooru_images_by_15000id_01-02_hiddentag_full-path.json  
│ ├── datasets_metadata_danbooru_images_by_15000id_01-02_hiddentag_relative-path.json  
│ └── datasets_metadata_danbooru_images_by_15000id_01-02_relative-path.json  

├── metadata  

│ ├── Danbooru  

│ │ ├── images_by_15000id_01  
│ │ │ ├── id_1__15000.tar  

│ │ │ ├── ~~~~~~~~~~~~  

│ │ │ └── id_3330001__3345000.tar  

│ │ └── images_by_15000id_02  
│ │ ├── id_3345001__3360000.tar  

│ │ ├──~~~~~~~~~~~~  

│ │ └── id_7425001__7440000.tar  

│ └── Gelbooru  

│ ├── hidden_tag_01.tar  

│ ├── hidden_tag_02.tar  

│ └── hidden_tag_03.tar  

└── tag  

├── Danbooru  

│ ├── images_by_15000id_01  
│ │ ├── id_1__15000.tar  

│ │ ├──~~~~~~~~~~~~  

│ │ └── id_3330001__3345000.tar  

│ └── images_by_15000id_02  
│ ├── id_3345001__3360000.tar  

│ ├── ~~~~~~~~~~~~  

│ └── id_7425001__7440000.tar  

└── Gelbooru  

├── hidden_tag_01.tar  

├── hidden_tag_02.tar  

└── hidden_tag_03.tar



### Data Format



This is a simple dataset that just uploads tar-compressed data.  

SQL🥃? Datasets🤗?? Dask🍡??? Croissant🥐??????? Parquet🤯?????????  

I don't understand any of it.



## License



creativeml-openrail-m



## Citation



While not mandatory, if you wish to cite this dataset, you could use the following format:



```

WarriorMama777. (2024). "PureDanbooru" (Version 1.0). Hugging Face. https://huggingface.co/datasets/WarriorMama777/PureDanbooru

```



## Acknowledgements



I'm grateful to Danbooru and the users who have diligently tagged on Danbooru over the years. I refrain from unilaterally sending thanks to the artists, but I respect each of their works.



## Contact Information



Please use the discussion section of this huggingface repository.



## Update History



| Version | Date | Changes |

| --- | --- | --- |

| v1.0.0 | 2024-07-07 | Initial release |



## Disclaimer



※To prevent errors through translation, it is posted in the original text.



<details><summary>READ MORE: Disclaimer (JPN)</summary> 1. AIの学習等における機械学習時の著作物の利用については、日本国著作権法第三十条の四第二項「情報解析(多数の著作物その他の大量の情報から、当該情報を構成する言語、音、影像その他の要素に係る情報を抽出し、比較、分類その他の解析を行うことをいう。第四十七条の五第一項第二号において同じ。)の用に供する場合」を参照し行っております。 [著作権法 | e-Gov法令検索: デジタル庁](https://elaws.e-gov.go.jp/document?lawid=345AC0000000048#Mp-At_30) 2. 著作物の掲載にあたっては、私的使用や研究目的である場合、商品化の資料として使用する場合(但し、商品化されるものが著作物の主たる利用目的となる場合にはこの限りではない)、批評・論評・報道での利用である場合、パロディや二次創作としてオリジナリティを発揮する場合等の例外的な著作物の使用が認められるケースに該当すると考え掲載しています。 3. 当該学習データセットは、わいせつな視覚コンテンツを直ちに表示されないよう配慮されており、学習データセットによる投稿が公共の場においてわいせつな内容を表示することを意図するものではありません。 なお、著作権者の意に反する利用や不当な利益を得る利用は避けるべきであり、著作権保有者によって正当な理由をもって当該データセットの関係する過半数の関係者から申し立てされた場合、掲載は速やかに中止されることが保証されます。 また本人は、使用する機械学習データセット中に、著作権者の権利を十分に尊重していないと評価され得る可能性を持つ情報源からのデータが含まれ得ることを認識しており、開発者等関係者が依拠すべき法律の整備等の動向について適切な監視と管理の義務を負っています。 本人は、法律や倫理に反する行為を意図しておらず、著作権者を含むイラストレーター及びアーティスト等の権利を尊重し、人工知能の開発を進めることに努めます。</details>