AngelBottomless's picture
Fix bug in tag list adding, the tags were not correctly being added
cbf0e03 verified
import os
import json
import requests
import glob
from tqdm import tqdm
from db import *
def yield_posts(file_dir=r"G:\database\post", from_id=0, end_id=7110548):
"""
Yields the posts
"""
# using listdir instead of glob because glob is slow
files = []
# walk through all files
for root, dirs, filenames in os.walk(file_dir):
for filename in filenames:
if "_" not in filename:
continue
# 0_19.jsonl -> 0, 19
start_id, end_id = filename.split(".")[0].split("_")
start_id = int(start_id)
end_id = int(end_id)
if start_id > end_id:
continue
if end_id < from_id:
continue
files.append(os.path.join(root, filename))
print(f"Total {len(files)} files")
for file in files:
with open(file, 'r') as f:
yield from f.readlines()
def add_post_if_not_exist(post_string):
try:
post_data = json.loads(post_string)
except Exception as e:
print(f"Exception: {e} when loading {post_string}")
return
post_id = post_data['id']
if (post:=Post.get_or_none(Post.id == post_id)) is not None:
# check if it has valid tag list
if not post.tag_list:
# remove post
Post.delete_by_id(post_id)
else:
return
# prepare tags first
for keys in ["tag_string_general", "tag_string_artist", "tag_string_character", "tag_string_meta", "tag_string", "tag_string_copyright"]:
if keys not in post_data:
raise Exception(f"Error: {keys} not in {post_data}")
values = post_data[keys]
if not values:
continue
if not isinstance(values, list):
values = values.split(" ")
current_value = []
for value in values:
tag = Tag.get_or_none(name=value)
if tag is None:
tag = Tag.create(name=value, type=keys.split("_")[-1], popularity=0)
# assert unique, tag should not be iterable
assert not isinstance(tag, list), f"Error: {tag} is iterable"
current_value.append(tag.id)
post_data[keys.replace("tag_string", "tag_list")] = current_value
post_data[keys.replace("tag_string", "tag_count")] = len(current_value)
# add post
data = dict(
id=post_id,
created_at=post_data.get('created_at', None),
source=post_data.get('source', ""),
rating=post_data.get('rating', 'q'),
score=post_data.get('score', 0),
up_score=post_data.get('up_score', 0),
down_score=post_data.get('down_score', 0),
fav_count=post_data.get('fav_count', 0),
tag_list_general=post_data.get('tag_list_general', []),
tag_list_artist=post_data.get('tag_list_artist', []),
tag_list_character=post_data.get('tag_list_character', []),
tag_list_meta=post_data.get('tag_list_meta', []),
tag_list=post_data.get('tag_list', []),
tag_list_copyright=post_data.get('tag_list_copyright', []),
tag_count_general=post_data.get('tag_count_general', 0),
tag_count_artist=post_data.get('tag_count_artist', 0),
tag_count_character=post_data.get('tag_count_character', 0),
tag_count_meta=post_data.get('tag_count_meta', 0),
tag_count=post_data.get('tag_count', 0),
tag_count_copyright=post_data.get('tag_count', 0),
uploader_id=post_data.get('uploader_id', 0),
md5=post_data.get('md5', None),
parent_id=post_data.get('parent_id', None),
has_children=post_data.get('has_children', False),
is_deleted=post_data.get('is_deleted', False),
is_banned=post_data.get('is_banned', False),
pixiv_id=post_data.get('pixiv_id', None),
has_active_children=post_data.get('has_active_children', False),
bit_flags=post_data.get('bit_flags', 0),
has_large=post_data.get('has_large', False),
has_visible_children=post_data.get('has_visible_children', False),
image_width=post_data.get('image_width', 0),
image_height=post_data.get('image_height', 0),
file_size=post_data.get('file_size', 0),
file_ext=post_data.get('file_ext', "jpg"),
file_url=post_data.get('file_url', ""),
large_file_url=post_data.get('large_file_url', ""),
preview_file_url=post_data.get('preview_file_url', "")
)
#print(data)
# create from dict
Post.create(**data)
#print(f"Added post {post_id}")
def pretty_print(post_id:int) -> str:
"""
Returns a pretty printed post
"""
post = Post.get_by_id(post_id)
def pretty_print_tag(tag):
"""
Returns a pretty printed tag
"""
return f"{tag.name}({tag.id})"
def pretty_print_tags(tags):
"""
Returns a pretty printed list of tags
"""
return ", ".join([pretty_print_tag(tag) for tag in tags])
fields = {"tag_list_general", "tag_list_artist", "tag_list_character", "tag_list_meta", "tag_list_copyright", "tag_list"}
string = ""
# start printing
string += f"Post {post_id}\n"
for field in fields:
string += f"\t{field}: {pretty_print_tags(post.__getattribute__(field))}\n"
counting_fields = {"tag_count_general", "tag_count_artist", "tag_count_character", "tag_count_meta", "tag_count"}
for field in counting_fields:
string += f"\t{field}: {post.__getattribute__(field)}\n"
return string
def main():
last_post_id = Post.select().order_by(Post.id.desc()).get().id
print(f"Last post id: {last_post_id}")
with db.atomic():
pbar = tqdm(total=7110548 - last_post_id)
for post_string in yield_posts(from_id=last_post_id):
try:
add_post_if_not_exist(post_string)
except Exception as e:
if isinstance(e, KeyboardInterrupt):
raise e
print(f"Exception: {e} when adding {post_string}")
raise e
pbar.update(1)
print("Done")
print(pretty_print(7110347))
if __name__ == "__main__":
main()
#print(pretty_print(7110347))