もじょえんじにあ……共感できる?

日常のメモ。日々これ共感。へたれでしょほてきなIT?

ちゃんとepubをパースするのDeath

以前にポストしたものは

いいかげんに、.opfを見て、だいたいそうなってれば概ね読める

的な雑スクリプトでした。で、読めないのをみつけちゃったのでxhtmlを読むようにした版death。

テキトーなのはあまりかわってないので、実体ファイルが2階層以上だと対応できまセン!

なにも入れないとxhtmlモード、argv[1]以降に、tradと入れるとテキトーモード、そのうえで、imageorderといれると.opfの順番を無視してイメージについてる番号でソートするモードdeath。

例のごとく動作保証もなにもありまセン!いつもどーり変数名もヒドいdeath!

#!/bin/env python3
import sys, os
from zipfile import ZipFile
from PIL import Image
import pillow_avif
ep = ".epub"
zp = ".zip"
mode = []
imgodr,xhtml,trad = 'imageorder', 'xhtml', 'trad'
xhm = 'media-type="application/xhtml'
options = (imgodr, xhtml)

def imgnum(s):
    b = [x for x in s if x.isnumeric()]
    lb = len(b)
    if lb % 2 == 0:
        sb = int(lb/2)
        if b[:sb] == b[sb:]: b = b[:sb]
    try: c = int(''.join(b))
    except: c = 0
    return c

def gethref(xxl):
    xxl = [x for x in xxl if 'href="' in x]
    xxl = [x.split('href=')[1] for x in xxl]
    xxl = [x.split('"')[1] for x in xxl]
    return xxl

if len(sys.argv) > 1:
    for x in options:
        if x in sys.argv: mode.append(x)
else: mode = [xhtml]

print("Mode:", mode)
for root, dirs, files in os.walk("./"):
    for f in files:
        if not f.endswith(ep): continue
        basef = f.split(ep)[0]
        try:
            os.mkdir(basef)
        except FileExistsError:
            pass#print("exist")
        with ZipFile(f) as epzip:
            epzip.extractall(basef)
        zpf = zp[1:]+basef
        try:
            os.mkdir(zpf)
        except FileExistsError:
            pass#print("exist")

for root, dirs, files in os.walk("./"):
    opf = [f for f in files if f.endswith(".opf")]
    if not opf: continue
    print(root, opf[0])
    opfi = '/'.join([root,opf[0]])
    ix = 1
    dr = root.split('/')[:-1]
    dr[-1] = zp[1:] + dr[-1]
    zpf = '/'.join(dr)
    print(root)
    print(zpf)
    with open(opfi) as f:
        if xhtml in mode:
            ll = []
            xl = gethref([x for x in f.readlines() if xhm in x])
            #print(xl)
            for xh in xl:
                xhi = '/'.join([root,xh])
                with open(xhi) as xf:
                    xll = [x for x in xf.readlines() if '<img' in x]
                    if not xll: continue
                    xll = [x.split('src=')[1] for x in xll]
                    xll = [x.split('"')[1] for x in xll]
                    #print(xh, xll)
                    ll += xll
        else:
            ll = gethref([x for x in f.readlines() if 'media-type="image' in x])
            if imgodr in mode: ll = sorted(ll,key=imgnum)
        for l in ll:
            rn = '/'.join([root, l])
            if not os.path.exists(rn) and l.startswith('../'): rn = '/'.join([root, l[3:]])
            #print(rn, l)
            bn = rn.split('/')[-1].split('.')[0]
            wn ='{:03d}.avif'.format(ix)
            print(bn, wn) # bn is printable only...
            img = Image.open(rn)
            img.save('/'.join([zpf,wn]), format="AVIF")
            ix += 1