KBlueLeaf AngelBottomless commited on
Commit
740a4e4
1 Parent(s): 5a6b5e4

Fix DB and update until post id 7349999 (#3)

Browse files

- Fix DB and update until post id 7349999 (ad69f1277fc07e9c310e75242ca60e11b870c421)


Co-authored-by: AngelBottomless@aria4th <AngelBottomless@users.noreply.huggingface.co>

Files changed (3) hide show
  1. create_db.py +164 -0
  2. danbooru2023.db +2 -2
  3. db.py +80 -35
create_db.py ADDED
@@ -0,0 +1,164 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from db import *
2
+ import json
3
+ import os
4
+ from tqdm import tqdm
5
+ from functools import cache
6
+
7
+ @cache
8
+ def get_or_create_tag(tag_name: str, tag_type: str, optional_tag_id: int = None):
9
+ """
10
+ Get a tag if it exists, otherwise create it.
11
+ """
12
+ tag = Tag.get_or_none(Tag.name == tag_name)
13
+ if tag is None:
14
+ if optional_tag_id is not None:
15
+ assert isinstance(optional_tag_id, int), f"optional_tag_id must be an integer, not {type(optional_tag_id)}"
16
+ tag = Tag.create(id=optional_tag_id, name=tag_name, type=tag_type, popularity=0)
17
+ else:
18
+ tag = Tag.create(name=tag_name, type=tag_type, popularity=0)
19
+ return tag
20
+
21
+ def create_tag_or_use(tag_name: str, tag_type: str, optional_tag_id: int = None):
22
+ """
23
+ Create a tag if it does not exist, otherwise return the existing tag.
24
+ This function also increments the popularity of the tag.
25
+ """
26
+ tag = get_or_create_tag(tag_name, tag_type, optional_tag_id)
27
+ # we don't have to check tag type since its unique
28
+ tag.popularity = 1
29
+ return tag
30
+
31
+ def iterate_jsonl(file_path: str):
32
+ """
33
+ Iterate through a jsonl file and yield each line as a dictionary.
34
+ """
35
+ with open(file_path, "r") as f:
36
+ for line in f:
37
+ yield json.loads(line)
38
+
39
+ JSONL_RATING_CONVERSION = {
40
+ "q": "questionable",
41
+ "s": "sensitive",
42
+ "e": "explicit",
43
+ "g": "general"
44
+ }
45
+
46
+ def create_tags(tag_string:str, tag_type:str):
47
+ """
48
+ Create tags from a tag string.
49
+ """
50
+ for tag in tag_string.split(" "):
51
+ if not tag or tag.isspace():
52
+ continue
53
+ tag = create_tag_or_use(tag, tag_type)
54
+ yield tag
55
+
56
+ def create_post(json_data, policy="ignore"):
57
+ """
58
+ Create a post from a json dictionary.
59
+ Policy can be 'ignore' or 'replace'
60
+ Note that file_url, large_file_url, and preview_file_url are optional.
61
+ """
62
+ assert "id" in json_data, "id is not in json_data"
63
+ post_id = json_data["id"]
64
+ all_tags = []
65
+ all_tags += [create_tags(json_data["tag_string_general"], "general")]
66
+ all_tags += [create_tags(json_data["tag_string_artist"], "artist")]
67
+ all_tags += [create_tags(json_data["tag_string_character"], "character")]
68
+ all_tags += [create_tags(json_data["tag_string_copyright"], "copyright")]
69
+ all_tags += [create_tags(json_data["tag_string_meta"], "meta")]
70
+ if Post.get_or_none(Post.id == post_id) is not None:
71
+ if policy == "ignore":
72
+ print(f"Post {post_id} already exists")
73
+ return
74
+ elif policy == "replace":
75
+ Post.delete_by_id(post_id)
76
+ else:
77
+ raise ValueError(f"Unknown policy {policy}, must be 'ignore' or 'replace'")
78
+ post = Post.create(id=post_id, created_at=json_data["created_at"],
79
+ uploader_id=json_data["uploader_id"],
80
+ source=json_data["source"], md5=json_data.get("md5", None),
81
+ parent_id=json_data["parent_id"], has_children=json_data["has_children"],
82
+ is_deleted=json_data["is_deleted"], is_banned=json_data["is_banned"],
83
+ pixiv_id=json_data["pixiv_id"], has_active_children=json_data["has_active_children"],
84
+ bit_flags=json_data["bit_flags"], has_large=json_data["has_large"],
85
+ has_visible_children=json_data["has_visible_children"], image_width=json_data["image_width"],
86
+ image_height=json_data["image_height"], file_size=json_data["file_size"],
87
+ file_ext=json_data["file_ext"], rating=JSONL_RATING_CONVERSION[json_data["rating"]], score=json_data["score"],
88
+ up_score=json_data["up_score"], down_score=json_data["down_score"], fav_count=json_data["fav_count"],
89
+ file_url=json_data.get("file_url", None), large_file_url=json_data.get("large_file_url", None),
90
+ preview_file_url=json_data.get("preview_file_url", None),
91
+ #tag_list=json_data["tag_string"]
92
+ )
93
+ for tags in all_tags:
94
+ for tag in tags:
95
+ PostTagRelation.create(post=post, tag=tag)
96
+ return post
97
+
98
+ def read_and_create_posts(file_path: str, policy="ignore"):
99
+ """
100
+ Read a jsonl file and create the posts in the database.
101
+ Policy can be 'ignore' or 'replace'
102
+ """
103
+ for json_data in iterate_jsonl(file_path):
104
+ create_post(json_data, policy)
105
+ #print(f"Created post {json_data['id']}")
106
+
107
+ def create_db_from_folder(folder_path: str, policy="ignore"):
108
+ """
109
+ Create a database from a folder of jsonl files.
110
+ This recursively searches the folder for jsonl files.
111
+ Policy can be 'ignore' or 'replace'
112
+ """
113
+ global db
114
+ assert db is not None, "Database is not loaded"
115
+ all_jsonl_files = []
116
+ for root, dirs, files in os.walk(folder_path):
117
+ for file in files:
118
+ if file.endswith(".jsonl"):
119
+ all_jsonl_files.append(os.path.join(root, file))
120
+ with db.atomic():
121
+ for file in tqdm(all_jsonl_files):
122
+ read_and_create_posts(file, policy)
123
+
124
+ def sanity_check(order="random"):
125
+ """
126
+ Print out a random post and its informations
127
+ """
128
+ if order == "random":
129
+ random_post = Post.select().order_by(fn.Random()).limit(1).get()
130
+ else:
131
+ random_post = Post.select().limit(1).get()
132
+ print(f"Post id : {random_post.id}")
133
+ print(f"Post tags: {random_post.tag_list}, {len(random_post.tag_list)} tags, {random_post.tag_count} tags")
134
+ print(f"Post general tags: {random_post.tag_list_general}, {len(random_post.tag_list_general)} tags, {random_post.tag_count_general} tags")
135
+ print(f"Post artist tags: {random_post.tag_list_artist}, {len(random_post.tag_list_artist)} tags, {random_post.tag_count_artist} tags")
136
+ print(f"Post character tags: {random_post.tag_list_character}, {len(random_post.tag_list_character)} tags, {random_post.tag_count_character} tags")
137
+ print(f"Post copyright tags: {random_post.tag_list_copyright}, {len(random_post.tag_list_copyright)} tags, {random_post.tag_count_copyright} tags")
138
+ print(f"Post meta tags: {random_post.tag_list_meta}, {len(random_post.tag_list_meta)} tags, {random_post.tag_count_meta} tags")
139
+ print(f"Post rating: {random_post.rating}")
140
+ print(f"Post score: {random_post.score}")
141
+ print(f"Post fav_count: {random_post.fav_count}")
142
+ print(f"Post source: {random_post.source}")
143
+ print(f"Post created_at: {random_post.created_at}")
144
+ print(f"Post file_url: {random_post.file_url}")
145
+ print(f"Post large_file_url: {random_post.large_file_url}")
146
+ print(f"Post preview_file_url: {random_post.preview_file_url}")
147
+ print(f"Post image_width: {random_post.image_width}")
148
+ print(f"Post image_height: {random_post.image_height}")
149
+ print(f"Post file_size: {random_post.file_size}")
150
+ print(f"Post file_ext: {random_post.file_ext}")
151
+ print(f"Post uploader_id: {random_post.uploader_id}")
152
+ print(f"Post pixiv_id: {random_post.pixiv_id}")
153
+ print(f"Post has_children: {random_post.has_children}")
154
+ print(f"Post is_deleted: {random_post.is_deleted}")
155
+ print(f"Post is_banned: {random_post.is_banned}")
156
+ print(f"Post has_active_children: {random_post.has_active_children}")
157
+ print(f"Post has_large: {random_post.has_large}")
158
+ print(f"Post has_visible_children: {random_post.has_visible_children}")
159
+ print(f"Post bit_flags: {random_post.bit_flags}")
160
+
161
+ if __name__ == "__main__":
162
+ db = load_db("danbooru2023.db")
163
+ #read_and_create_posts(r"C:\sqlite\0_99.jsonl")
164
+ #create_db_from_folder(r'D:\danbooru-0319') # if you have a folder of jsonl files
danbooru2023.db CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:82901925689e08817e369a8cc8e9934bfac828473fa319ac4fd5541c484cc718
3
- size 15443382272
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:dc54df5f67ecf571263dae8d5513076b2ddde6178ff6e963cc41fd9a3df82baa
3
+ size 18653368320
db.py CHANGED
@@ -1,8 +1,8 @@
 
1
  import sqlite3
2
 
3
  from peewee import *
4
 
5
-
6
  class MemoryConnection(sqlite3.Connection):
7
  def __init__(self, dbname, *args, **kwargs):
8
  load_conn = sqlite3.connect(dbname)
@@ -34,16 +34,13 @@ class SqliteMemDatabase(SqliteDatabase):
34
  finally:
35
  save_conn.close()
36
 
37
-
38
  db: SqliteDatabase = None
39
  tag_cache_map = {}
40
 
41
-
42
- def get_tag_by_id(id):
43
- if id not in tag_cache_map:
44
- tag_cache_map[id] = Tag.get_by_id(id)
45
- return tag_cache_map[id]
46
-
47
 
48
  class EnumField(IntegerField):
49
  def __init__(self, enum_list, *args, **kwargs):
@@ -85,11 +82,9 @@ class Tag(BaseModel):
85
  return f"<Tag '{self.name}'>"
86
 
87
  def __repr__(self):
88
- from objprint import objstr
89
-
90
  return f"<Tag|#{self.id}|{self.name}|{self.type[:2]}>"
91
 
92
-
93
  class Post(BaseModel):
94
  id = IntegerField(primary_key=True)
95
  created_at = CharField()
@@ -117,20 +112,36 @@ class Post(BaseModel):
117
  down_score = IntegerField()
118
  fav_count = IntegerField()
119
 
120
- file_url = CharField()
121
- large_file_url = CharField()
122
- preview_file_url = CharField()
123
 
124
- _tags: ManyToManyField
125
  _tags_cache = None
126
- _tag_list = TextField(column_name="tag_list")
127
 
128
- tag_count = IntegerField()
129
- tag_count_general = IntegerField()
130
- tag_count_artist = IntegerField()
131
- tag_count_character = IntegerField()
132
- tag_count_copyright = IntegerField()
133
- tag_count_meta = IntegerField()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
134
 
135
  @property
136
  def tag_list(self):
@@ -158,6 +169,19 @@ class Post(BaseModel):
158
  def tag_list_meta(self):
159
  return [tag for tag in self.tag_list if tag.type == "meta"]
160
 
 
 
 
 
 
 
 
 
 
 
 
 
 
161
 
162
  class PostTagRelation(BaseModel):
163
  post = ForeignKeyField(Post, backref="post_tags")
@@ -170,26 +194,47 @@ tags.bind(Post, "_tags", set_attribute=True)
170
 
171
  def load_db(db_file: str):
172
  global db
 
173
  db = SqliteDatabase(db_file)
174
  Post._meta.database = db
175
  Tag._meta.database = db
176
  PostTagRelation._meta.database = db
 
177
  db.connect()
178
-
179
-
180
- if __name__ == "__main__":
181
- load_db("danbooru2023.db")
182
- post = Post.get_by_id(1)
183
- print(post.tag_count_general, len(post.tag_list_general), post.tag_list_general)
184
- print(post.tag_count_artist, len(post.tag_list_artist), post.tag_list_artist)
 
 
 
 
 
 
 
 
 
185
  print(
186
- post.tag_count_character, len(post.tag_list_character), post.tag_list_character
187
  )
188
  print(
189
- post.tag_count_copyright, len(post.tag_list_copyright), post.tag_list_copyright
190
  )
191
- print(post.tag_count_meta, len(post.tag_list_meta), post.tag_list_meta)
 
192
 
193
- tag = Tag.select().where(Tag.name == "umamusume").first()
194
- print(tag)
195
- print(len(tag.posts))
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
  import sqlite3
3
 
4
  from peewee import *
5
 
 
6
  class MemoryConnection(sqlite3.Connection):
7
  def __init__(self, dbname, *args, **kwargs):
8
  load_conn = sqlite3.connect(dbname)
 
34
  finally:
35
  save_conn.close()
36
 
 
37
  db: SqliteDatabase = None
38
  tag_cache_map = {}
39
 
40
+ def get_tag_by_id(tag_id):
41
+ if tag_id not in tag_cache_map:
42
+ tag_cache_map[tag_id] = Tag.get_by_id(tag_id)
43
+ return tag_cache_map[tag_id]
 
 
44
 
45
  class EnumField(IntegerField):
46
  def __init__(self, enum_list, *args, **kwargs):
 
82
  return f"<Tag '{self.name}'>"
83
 
84
  def __repr__(self):
85
+ #from objprint import objstr
 
86
  return f"<Tag|#{self.id}|{self.name}|{self.type[:2]}>"
87
 
 
88
  class Post(BaseModel):
89
  id = IntegerField(primary_key=True)
90
  created_at = CharField()
 
112
  down_score = IntegerField()
113
  fav_count = IntegerField()
114
 
115
+ file_url = CharField(null=True)
116
+ large_file_url = CharField(null=True)
117
+ preview_file_url = CharField(null=True)
118
 
119
+ _tags: ManyToManyField = None # set by tags.bind
120
  _tags_cache = None
 
121
 
122
+ @property
123
+ def tag_count(self):
124
+ return len(self.tag_list) if self.tag_list else 0
125
+
126
+ @property
127
+ def tag_count_general(self):
128
+ return len(self.tag_list_general) if self.tag_list else 0
129
+
130
+ @property
131
+ def tag_count_artist(self):
132
+ return len(self.tag_list_artist) if self.tag_list else 0
133
+
134
+ @property
135
+ def tag_count_character(self):
136
+ return len(self.tag_list_character) if self.tag_list else 0
137
+
138
+ @property
139
+ def tag_count_copyright(self):
140
+ return len(self.tag_list_copyright) if self.tag_list else 0
141
+
142
+ @property
143
+ def tag_count_meta(self):
144
+ return len(self.tag_list_meta) if self.tag_list else 0
145
 
146
  @property
147
  def tag_list(self):
 
169
  def tag_list_meta(self):
170
  return [tag for tag in self.tag_list if tag.type == "meta"]
171
 
172
+ # create table LocalPost Table that can contain "filepath", "latentpath"
173
+ class LocalPost(BaseModel):
174
+ # Usage : LocalPost.create(filepath="path/to/file", latentpath="path/to/latent", post=post)
175
+ id = IntegerField(primary_key=True)
176
+ filepath = CharField(null=True)
177
+ latentpath = CharField(null=True)
178
+ post = ForeignKeyField(Post, backref="localpost")
179
+
180
+ def __str__(self):
181
+ return f"<LocalPost '{self.filepath}'>"
182
+
183
+ def __repr__(self):
184
+ return f"<LocalPost|#{self.id}|{self.filepath}|{self.latentpath}|{self.post}>"
185
 
186
  class PostTagRelation(BaseModel):
187
  post = ForeignKeyField(Post, backref="post_tags")
 
194
 
195
  def load_db(db_file: str):
196
  global db
197
+ file_exists = os.path.exists(db_file)
198
  db = SqliteDatabase(db_file)
199
  Post._meta.database = db
200
  Tag._meta.database = db
201
  PostTagRelation._meta.database = db
202
+ LocalPost._meta.database = db
203
  db.connect()
204
+ print("Database connected.")
205
+ if not file_exists:
206
+ db.create_tables([Post, Tag, PostTagRelation])
207
+ db.create_tables([LocalPost])
208
+ db.commit()
209
+ print("Database initialized.")
210
+ assert db is not None, "Database is not loaded"
211
+ return db
212
+
213
+ def print_post_info(post):
214
+ """
215
+ Debugging function to print out a post's tags
216
+ """
217
+ print(f"Post id : {post.id}")
218
+ print("General Tags: ", post.tag_count_general, len(post.tag_list_general), post.tag_list_general)
219
+ print("Artist Tags: ", post.tag_count_artist, len(post.tag_list_artist), post.tag_list_artist)
220
  print(
221
+ "Character Tags: ", post.tag_count_character, len(post.tag_list_character), post.tag_list_character
222
  )
223
  print(
224
+ "Copyright Tags: ", post.tag_count_copyright, len(post.tag_list_copyright), post.tag_list_copyright
225
  )
226
+ print("Meta Tags: ", post.tag_count_meta, len(post.tag_list_meta), post.tag_list_meta)
227
+
228
 
229
+ if __name__ == "__main__":
230
+ db_existed = os.path.exists("danbooru2023.db")
231
+ db = load_db("danbooru2023.db")
232
+ if db_existed:
233
+ # run sanity check
234
+ post = Post.get_by_id(1)
235
+ print_post_info(post)
236
+ tag = Tag.select().where(Tag.name == "kousaka_kirino").get()
237
+ print(f"Tag {tag} has {len(tag.posts)} posts")
238
+ # get last post
239
+ post = Post.select().order_by(Post.id.desc()).limit(1).get()
240
+ print_post_info(post)