from db import * import json import os from tqdm import tqdm from functools import cache from datetime import datetime @cache def get_or_create_tag(tag_name: str, tag_type: str, optional_tag_id: int = None): """ Get a tag if it exists, otherwise create it. """ tag = Tag.get_or_none(Tag.name == tag_name) if tag is None: if optional_tag_id is not None: assert isinstance(optional_tag_id, int), f"optional_tag_id must be an integer, not {type(optional_tag_id)}" tag = Tag.create(id=optional_tag_id, name=tag_name, type=tag_type, popularity=0) else: tag = Tag.create(name=tag_name, type=tag_type, popularity=0) return tag def create_tag_or_use(tag_name: str, tag_type: str, optional_tag_id: int = None): """ Create a tag if it does not exist, otherwise return the existing tag. This function also increments the popularity of the tag. """ tag = get_or_create_tag(tag_name, tag_type, optional_tag_id) # we don't have to check tag type since its unique tag.popularity = 1 return tag def iterate_jsonl(file_path: str): """ Iterate through a jsonl file and yield each line as a dictionary. """ with open(file_path, "r") as f: for line in f: yield json.loads(line) JSONL_RATING_CONVERSION = { "q": "questionable", "s": "sensitive", "e": "explicit", "g": "general" } def create_tags(tag_string:str, tag_type:str): """ Create tags from a tag string. """ for tag in tag_string.split(" "): if not tag or tag.isspace(): continue tag = create_tag_or_use(tag, tag_type) yield tag def create_post(json_data, policy="ignore"): """ Create a post from a json dictionary. Policy can be 'ignore' or 'replace' Note that file_url, large_file_url, and preview_file_url are optional. """ assert "id" in json_data, "id is not in json_data" post_id = json_data["id"] #"updated_at": "2024-05-19T01:30:25.096-04:00" all_tags = [] all_tags += [create_tags(json_data["tag_string_general"], "general")] all_tags += [create_tags(json_data["tag_string_artist"], "artist")] all_tags += [create_tags(json_data["tag_string_character"], "character")] all_tags += [create_tags(json_data["tag_string_copyright"], "copyright")] all_tags += [create_tags(json_data["tag_string_meta"], "meta")] if Post.get_or_none(Post.id == post_id) is not None: if policy == "ignore": print(f"Post {post_id} already exists") return elif policy == "replace": # get existing post, compare updated_at, delete if necessary current_post = Post.get_by_id(post_id) if current_post.updated_at == json_data["updated_at"]: print(f"Post {post_id} already exists") return # compare the date datetime_current = datetime.fromisoformat(current_post.updated_at) datetime_new = datetime.fromisoformat(json_data["updated_at"]) if datetime_new <= datetime_current: print(f"Post {post_id} is older than the existing post") return print(f"Post {post_id} is being replaced, old updated_at: {current_post.updated_at}, new updated_at: {json_data['updated_at']}") Post.delete_by_id(post_id) else: raise ValueError(f"Unknown policy {policy}, must be 'ignore' or 'replace'") post = Post.create(id=post_id, created_at=json_data["created_at"], uploader_id=json_data["uploader_id"], source=json_data["source"], md5=json_data.get("md5", None), parent_id=json_data["parent_id"], has_children=json_data["has_children"], is_deleted=json_data["is_deleted"], is_banned=json_data["is_banned"], pixiv_id=json_data["pixiv_id"], has_active_children=json_data["has_active_children"], bit_flags=json_data["bit_flags"], has_large=json_data["has_large"], has_visible_children=json_data["has_visible_children"], image_width=json_data["image_width"], image_height=json_data["image_height"], file_size=json_data["file_size"], file_ext=json_data["file_ext"], rating=JSONL_RATING_CONVERSION[json_data["rating"]], score=json_data["score"], up_score=json_data["up_score"], down_score=json_data["down_score"], fav_count=json_data["fav_count"], file_url=json_data.get("file_url", None), large_file_url=json_data.get("large_file_url", None), preview_file_url=json_data.get("preview_file_url", None), updated_at=json_data["updated_at"], #tag_list=json_data["tag_string"] ) for tags in all_tags: for tag in tags: PostTagRelation.create(post=post, tag=tag) return post def read_and_create_posts(file_path: str, policy="ignore"): """ Read a jsonl file and create the posts in the database. Policy can be 'ignore' or 'replace' """ for json_data in iterate_jsonl(file_path): create_post(json_data, policy) #print(f"Created post {json_data['id']}") def create_db_from_folder(folder_path: str, policy="ignore"): """ Create a database from a folder of jsonl files. This recursively searches the folder for jsonl files. Policy can be 'ignore' or 'replace' """ global db assert db is not None, "Database is not loaded" all_jsonl_files = [] for root, dirs, files in os.walk(folder_path): for file in files: if file.endswith(".jsonl"): all_jsonl_files.append(os.path.join(root, file)) with db.atomic(): for file in tqdm(all_jsonl_files[::-1]): read_and_create_posts(file, policy) def sanity_check(order="random"): """ Print out a random post and its informations """ if order == "random": random_post = Post.select().order_by(fn.Random()).limit(1).get() else: random_post = Post.select().limit(1).get() print(f"Post id : {random_post.id}") print(f"Post tags: {random_post.tag_list}, {len(random_post.tag_list)} tags, {random_post.tag_count} tags") print(f"Post general tags: {random_post.tag_list_general}, {len(random_post.tag_list_general)} tags, {random_post.tag_count_general} tags") print(f"Post artist tags: {random_post.tag_list_artist}, {len(random_post.tag_list_artist)} tags, {random_post.tag_count_artist} tags") print(f"Post character tags: {random_post.tag_list_character}, {len(random_post.tag_list_character)} tags, {random_post.tag_count_character} tags") print(f"Post copyright tags: {random_post.tag_list_copyright}, {len(random_post.tag_list_copyright)} tags, {random_post.tag_count_copyright} tags") print(f"Post meta tags: {random_post.tag_list_meta}, {len(random_post.tag_list_meta)} tags, {random_post.tag_count_meta} tags") print(f"Post rating: {random_post.rating}") print(f"Post score: {random_post.score}") print(f"Post fav_count: {random_post.fav_count}") print(f"Post source: {random_post.source}") print(f"Post created_at: {random_post.created_at}") print(f"Post file_url: {random_post.file_url}") print(f"Post large_file_url: {random_post.large_file_url}") print(f"Post preview_file_url: {random_post.preview_file_url}") print(f"Post image_width: {random_post.image_width}") print(f"Post image_height: {random_post.image_height}") print(f"Post file_size: {random_post.file_size}") print(f"Post file_ext: {random_post.file_ext}") print(f"Post uploader_id: {random_post.uploader_id}") print(f"Post pixiv_id: {random_post.pixiv_id}") print(f"Post has_children: {random_post.has_children}") print(f"Post is_deleted: {random_post.is_deleted}") print(f"Post is_banned: {random_post.is_banned}") print(f"Post has_active_children: {random_post.has_active_children}") print(f"Post has_large: {random_post.has_large}") print(f"Post has_visible_children: {random_post.has_visible_children}") print(f"Post bit_flags: {random_post.bit_flags}") print(f"Post updated_at: {random_post.updated_at}") if __name__ == "__main__": db = load_db("danbooru2023.db") #read_and_create_posts(r"C:\sqlite\0_99.jsonl") sanity_check() #create_db_from_folder(r'D:\danbooru\post_danboorus', 'replace') # if you have a folder of jsonl files