|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
import numpy as np |
|
|
import cv2 |
|
|
import json |
|
|
import base64 |
|
|
import os |
|
|
import shutil |
|
|
import hashlib |
|
|
import glob |
|
|
import re |
|
|
|
|
|
def md5(fname): |
|
|
hash_md5 = hashlib.md5() |
|
|
with open(fname, "rb") as f: |
|
|
for chunk in iter(lambda: f.read(4096), b""): |
|
|
hash_md5.update(chunk) |
|
|
return hash_md5.hexdigest() |
|
|
|
|
|
if __name__ == '__main__': |
|
|
|
|
|
dir_book = 'pdfs/jp/徐一平日本语句型辞典' |
|
|
|
|
|
dir = 'data' |
|
|
if os.path.exists(dir): |
|
|
shutil.rmtree(dir) |
|
|
os.makedirs(os.path.join(dir, 'img')) |
|
|
os.makedirs(os.path.join(dir, 'json')) |
|
|
os.makedirs(os.path.join(dir, os.path.basename(dir_book))) |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
pths = glob.glob(dir_book + '/*.jpg', recursive=False) |
|
|
|
|
|
pths = sorted(pths, key=lambda p:( |
|
|
match := re.findall(r'.+?(\d+)\.jpg', p), |
|
|
number := int(match[0]), |
|
|
number |
|
|
)) |
|
|
|
|
|
for idx, pth in enumerate(pths): |
|
|
|
|
|
m5 = md5(pth) |
|
|
p_j = pth.replace('.jpg', '.json') |
|
|
if not os.path.exists(p_j): |
|
|
raise Exception(f'##### error: json not found. {p_j}') |
|
|
|
|
|
imgData = np.fromfile(pth, dtype=np.uint8) |
|
|
img = cv2.imdecode(imgData, cv2.IMREAD_UNCHANGED) |
|
|
img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) |
|
|
|
|
|
success, encoded_image = cv2.imencode(".jpg", img) |
|
|
img_bytes = encoded_image.tobytes() |
|
|
base64_str = base64.b64encode(img_bytes).decode('ascii') |
|
|
|
|
|
img_bytes_restored = base64.b64decode(base64_str) |
|
|
imgdata_restored = np.frombuffer(img_bytes_restored, dtype=np.uint8) |
|
|
img_restored = cv2.imdecode(imgdata_restored, cv2.IMREAD_UNCHANGED) |
|
|
|
|
|
|
|
|
pth_img = os.path.join(dir, 'img/{}.txt'.format(m5)) |
|
|
pth_json = os.path.join(dir, 'json/{}.json'.format(m5)) |
|
|
pth_book = os.path.join(dir, os.path.basename(dir_book)) |
|
|
|
|
|
with open(pth_img, 'w', encoding='utf-8') as f: |
|
|
f.write(base64_str) |
|
|
|
|
|
dest = shutil.copy(p_j, pth_json) |
|
|
|
|
|
dest = shutil.copy(pth, pth_book) |
|
|
|
|
|
if not os.path.exists(pth_img): |
|
|
|
|
|
print( f'Warnnig: no image {pth_img}' ) |
|
|
pass |
|
|
|
|
|
if not os.path.exists(pth_json): |
|
|
|
|
|
pass |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
print( f'one task done. {idx+1} / {len(pths)}' ) |
|
|
|
|
|
break |
|
|
|
|
|
print( 'all task done.' ) |
|
|
|