File size: 6,590 Bytes
eb37276 2d603f3 eb37276 dd6fc57 eb37276 2d603f3 eb37276 2d603f3 eb37276 |
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 |
"""
Reads and commits differences from difference_cache.jsonl files to database
Uses batch commit to speed up commit process
"""
import glob
from random import choice
from db import *
import os
import json
from tqdm import tqdm
def is_different(diff_0, diff_1):
if not diff_0 and not diff_1:
return False
return True
def get_differences(filepath):
"""
Reads differences from difference_cache.jsonl
Returns list of differences
"""
differences = {}
with open(filepath, 'r') as file:
for line in file:
try:
loaded_dict = json.loads(line)
if not loaded_dict['difference']:
continue
if not is_different(loaded_dict['difference'][0], loaded_dict['difference'][1]):
continue
differences[loaded_dict['id']] = loaded_dict['difference']
except:
pass
return differences
def commit_differences(differences):
"""
Commits differences to database
Returns number of differences committed
"""
for ids in tqdm(differences):
if not is_different(differences[ids][0], differences[ids][1]):
continue
commit_difference(ids, differences[ids])
def commit_difference(id, difference):
"""
Commits difference to database
"""
if difference:
post_by_id = Post.get_by_id(id)
new_dict, old_dict = difference
for keys in new_dict:
if keys not in old_dict:
post_by_id.__setattr__(keys, new_dict[keys])
else:
# replace old value with new value
if "tag" not in keys:
print(f"Warning: {keys} is not a tag")
current_value = post_by_id.__getattribute__(keys)
target_values_to_remove = old_dict[keys]
target_values_to_add = new_dict[keys]
# remove old values
for name in target_values_to_remove:
if name in (tag.name for tag in current_value):
#print(f"{name} is in {[tag.name for tag in current_value]}, removing")
current_value.remove(Tag.get(Tag.name == name))
# add new values
for values in target_values_to_add:
# no int values allowed
assert isinstance(values, str), f"Error: {values} is not a string"
tag = Tag.get_or_none(Tag.name == values)
if tag is None:
print(f"Warning: {values} is not in database, adding")
tag = Tag.create(name=values, 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)
# commit changes
post_by_id.save()
else:
return
def main(filepath="difference_cache.jsonl"):
print(f"Reading differences from {filepath}")
differences = get_differences(filepath)
with db.atomic():# commit all changes at once
commit_differences(differences)
# sample random post from differences and show
sample_post_id = choice(list(differences.keys()))
print(f"Sample Post: {sample_post_id}")
print(f"Sample Difference: {differences[sample_post_id]}")
# get real state of post
post = Post.get_by_id(sample_post_id)
for fields in FIELDS_TO_EXTRACT:
attr = post.__getattribute__(FIELDS_TO_EXTRACT[fields])
if isinstance(attr, list):
print(f"{fields}: {[tag.name for tag in attr]}")
else:
print(f"{fields}: {attr}")
FIELDS_TO_EXTRACT = {
'id': 'id',
'created_at': 'created_at',
'source': 'source',
'rating': 'rating',
'score': 'score',
'fav_count': 'fav_count',
'tag_list_general': 'tag_list_general',
'tag_list_artist': 'tag_list_artist',
'tag_list_character': 'tag_list_character',
'tag_list_copyright': 'tag_list_copyright',
'tag_list_meta': 'tag_list_meta',
}
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"}
string = ""
# start printing
string += f"Post {post_id}\n"
for field in fields:
string += f"\t{field}: {pretty_print_tags(post.__getattribute__(field))}\n"
return string
def save_post(idx:int):
folder = "danbooru2023_fixed"
dump = {}
if not os.path.exists(f"{folder}/posts"):
os.makedirs(f"{folder}/posts")
post = Post.get_by_id(idx)
with open(f"{folder}/posts/{idx}.json",'w') as file:
for field in FIELDS_TO_EXTRACT:
dump[field] = post.__getattribute__(FIELDS_TO_EXTRACT[field])
# if list, convert to list of string instead of tag objects
if isinstance(dump[field], list):
dump[field] = [tag.name for tag in dump[field]]
json.dump(dump, file)
def test():
"""
This is a test function that you can test without running the entire script
"""
print(pretty_print(6719955))
diff = {"id": 6719955, "difference": [{"tag_list_general": ["virtual_youtuber"], "tag_list_character": ["otonose_kanade"], "tag_list_artist": ["jb_jagbung"], "tag_list_copyright": ["hololive", "hololive_dev_is"]}, {"tag_list_general": ["sad_keanu_(meme)"], "tag_list_character": ["regloss_(hololive)"], "tag_list_artist": ["xt0y4x"], "tag_list_copyright": ["tokino_sora_(old_design)", "juufuutei_raden"]}]}
# test, simulate commit, do not commit
with db.atomic() as transaction:
commit_difference(diff['id'], diff['difference'])
print(pretty_print(6719955))
transaction.rollback()
print(pretty_print(6719955))
def test2():
"""
After commit, you can check if now the post is different
"""
print(pretty_print(6719955))
if __name__ == "__main__":
jsonl_files = glob.glob(r"G:\database\finished\*.jsonl")
# sort by number
jsonl_files.sort()
for file in tqdm(jsonl_files):
main(file)
|