ペーパーバック版で、20 行以上ある物と紙の 1 行に収まらない物の 18 本です。番号は紙の「写し用:…#cN(コード N)」と同じです。中身は本文と同じで、ここで新しく足した物はありません。
紙版の商品頁: Amazon(ペーパーバック・A5・152 頁)。電子版は Kindle 版。
電子版(Kindle)から写す場合は、この頁は要りません。
# -*- coding: utf-8 -*-
"""EPUB の参照の整合だけを見る(manifest 実在・zip の未記載・spine の idref・本文と nav のリンク先と #fragment・画像の未記載)。
使い方: python3 refcheck.py 本.epub"""
import sys, zipfile, posixpath
import xml.etree.ElementTree as ET
path = sys.argv[1]
z = zipfile.ZipFile(path); names = set(z.namelist())
c = ET.fromstring(z.read("META-INF/container.xml"))
opf_path = c.find(".//{urn:oasis:names:tc:opendocument:xmlns:container}rootfile").get("full-path")
base = posixpath.dirname(opf_path)
opf = ET.fromstring(z.read(opf_path)); ns = {"o": "http://www.idpf.org/2007/opf"}
items = {it.get("id"): posixpath.normpath(posixpath.join(base, it.get("href"))) for it in opf.findall(".//o:manifest/o:item", ns)}
ng = []
for iid, full in items.items():
if full not in names: ng.append(f"manifest にあるが zip に無い: {full}(id={iid})")
listed = set(items.values()) | {"mimetype", "META-INF/container.xml", opf_path}
for n in sorted(names - listed):
if not n.endswith("/"): ng.append(f"zip にあるが manifest に無い: {n}")
spine = [ir.get("idref") for ir in opf.findall(".//o:spine/o:itemref", ns)]
for idref in spine:
if idref not in items: ng.append(f"spine の idref が manifest に無い: {idref}")
for iid, full in items.items():
if full.endswith(".xhtml") and iid not in spine: ng.append(f"manifest にあるが spine に無い章: {full}(id={iid})")
ids = {}
for full in [f for f in items.values() if f.endswith(".xhtml") and f in names]:
doc = ET.fromstring(z.read(full)); ids[full] = {el.get("id") for el in doc.iter() if el.get("id")}
for full in ids:
doc = ET.fromstring(z.read(full)); d = posixpath.dirname(full)
for el in doc.iter():
tag = el.tag.split("}")[-1]
ref = el.get("src") if tag in ("img", "image") else (el.get("href") if tag == "a" else None)
if not ref or ref.startswith(("http:", "https:", "mailto:")): continue
file, _, frag = ref.partition("#")
target = posixpath.normpath(posixpath.join(d, file)) if file else full
if target not in names: ng.append(f"{full}: リンク先が zip に無い: {ref}")
elif target not in items.values(): ng.append(f"{full}: リンク先が manifest に無い: {ref}")
elif frag and target in ids and frag not in ids[target]: ng.append(f"{full}: リンク先に id が無い: {ref}")
print(("OK" if not ng else "\n".join("NG: " + x for x in ng)), "\t<-", path)grep -oE '<a [^>]*>[^<]*</a>' OEBPS/nav.xhtml | sed -E 's/<[^>]+>//g'
grep -hoE '<h[1-6][^>]*>.*</h[1-6]>' OEBPS/*.xhtml | sed -E 's/<rt>[^<]*<\/rt>//g; s/<[^>]+>//g'# tr の外にある td(td の直前の開きタグが tr でも td でもない)
grep -oE '<(tr|td|th|table)[ >]' OEBPS/*.xhtml | awk -F: '{print $2}' | tr -d '<> ' | awk 'prev!="tr" && prev!="td" && prev!="th" && ($1=="td"||$1=="th"){n++} {prev=$1} END{print n+0}'
# p の中の table
grep -cE '<p[^>]*>[^<]*<table' OEBPS/*.xhtml | awk -F: '{s+=$2} END{print s+0}'
# 引用符の無い属性(Word の Web ページ保存の型)
grep -cE '<(table|td|tr|th)[^>]* [a-z]+=[^"'"'"' >]' OEBPS/*.xhtml | awk -F: '{s+=$2} END{print s+0}'# 1. 本文の ul/ol の数(0 なのに箇条書きのある本は、全部が段落になっている)
ls OEBPS/*.xhtml | grep -v nav.xhtml | xargs grep -cE '<(ul|ol)[ >]' | awk -F: '{s+=$2} END{print s+0}'
# 2. ul/ol の直下か li の直後に li 以外(EPUBCheck RSC-005・その行だけ番号を失う)
grep -oE '</li>\s*<(div|p|span)[ >]|<(ul|ol)[^>]*>\s*<(div|p|span)[ >]' OEBPS/*.xhtml | wc -l
# 3. CSS だけでリストにしている箱(容器も印も出ない)
grep -cE 'display\s*:\s*list-item' OEBPS/*.css | awk -F: '{s+=$2} END{print s+0}'# -*- coding: utf-8 -*-
"""入稿前に EPUB の箇条書き(ul・ol)だけを一覧する(標準ライブラリのみ)。
python3 list_check.py 本.epub [...]
出す物: CSS の list-style-type の文字列値・::marker・list-style-image・list-style:none・display:list-item(Kindle Previewer が黙って捨てる
か『リストではない』扱いにする書き方)、本文ファイルごとに ul/ol の数・reversed(捨てられる)・li 以外の子(EPUBCheck が止める)・
ul/ol の外で手書きした『・』『1.』の段落(リストにならず字として残る)。"""
import sys,zipfile,re
from xml.etree import ElementTree as ET
X="{http://www.w3.org/1999/xhtml}"
def local(t): return t.split("}")[-1]
def check(path):
z=zipfile.ZipFile(path); names=z.namelist()
css=re.sub(r"/\*.*?\*/","","\n".join(z.read(n).decode("utf-8","replace") for n in names if n.endswith(".css")),flags=re.S)
print(path); bad=0; none_sel=set(); li_sel=set()
for sel,body in re.findall(r'([^{}]+)\{([^}]*)\}',css):
sel=sel.strip()
if sel.startswith("nav"): continue # 目次の nav ol は list-style none が定石
m=re.search(r'list-style(?:-type)?\s*:\s*([^;]+)',body)
if m:
v=m.group(1).strip()
if re.search(r'["\']',v): print(f" CSS: {sel} の印が文字列 {v}(Previewer は黙って既定の印に戻す)"); bad+=1
elif "none" in v.split(): none_sel.add(sel); print(f" CSS: {sel} が list-style none(リストでなくなる。手書きの印だけが残る)")
if re.search(r'list-style-image\s*:',body): print(f" CSS: {sel} に list-style-image(Previewer は黙って既定の印に戻す)"); bad+=1
if "::marker" in sel or ":marker" in sel: print(f" CSS: {sel}(::marker の差し替えは Previewer が黙って捨てる)"); bad+=1
if re.search(r'display\s*:\s*list-item',body): li_sel.add(sel); print(f" CSS: {sel} に display:list-item(ul/ol 無しではリストにならない・印も出ない)"); bad+=1
for n in sorted(x for x in names if x.endswith((".xhtml",".html")) and not x.endswith("nav.xhtml")):
raw=z.read(n)
try: root=ET.fromstring(raw)
except ET.ParseError as e: print(f" {n}: XML として読めない({e})"); bad+=1; continue
body=root.find(X+"body")
if body is None: continue
notes=[]; lists=[el for el in body.iter() if local(el.tag) in ("ul","ol")]
for el in lists:
if el.get("reversed") is not None: notes.append("ol reversed(Previewer は黙って捨て、昇順になる)"); bad+=1
others=[local(c.tag) for c in el if local(c.tag) not in ("li","script","template")]
if others: notes.append(f"<{local(el.tag)}> の子に li 以外 {others}(EPUBCheck RSC-005・その行だけ番号を失う)"); bad+=1
parent={c:p for p in root.iter() for c in p}
def in_list(el):
p=parent.get(el)
while p is not None:
if local(p.tag) in ("ul","ol"): return True
p=parent.get(p)
return False
manual=0
for el in body.iter():
if local(el.tag) not in ("p","div") or in_list(el): continue
t="".join(el.itertext()).strip()
if re.match(r"^([・•●■◆※○]|[0-90-9]{1,2}[..、))]|[一二三四五六七八九十]{1,2}[..、])",t): manual+=1
if manual: notes.append(f"ul/ol の外で印や番号を手書きした段落 {manual}(リストにはならないが字としては残る)")
if lists or notes: print(f" {n}: ul/ol {len(lists)} "+" / ".join(notes))
print(f" 判定: {'OK' if bad==0 else f'要確認 {bad} 件'}")
for p in sys.argv[1:]: check(p)grep -rnE '<svg|\.svg"' --include='*.xhtml' --include='*.css' --include='*.opf' . # 1 行でも出れば ET が落ちる(object+img 代替なら通る)
grep -rnP '[\x{E000}-\x{F8FF}\x{F0000}-\x{10FFFD}]|&#x?[0-9A-Fa-f]+;' --include='*.xhtml' . # PUA の外字文字(数値参照も)。@font-face が無ければ ☐ に書き換わる
grep -rnE '<svg|<math' --include='*.xhtml' . && grep -nE 'properties="[^"]*(svg|mathml)' *.opf # 前が出て後が出なければ OPF-014grep -rnE '<object[^>]*>\s*</object>' --include='*.xhtml' . # 代替の無い object(消える)
grep -rlE '@font-face' --include='*.css' --include='*.xhtml' . || echo 'font-face なし(PUA は ☐ になる)'
python3 -c "from fontTools.ttLib import TTFont;import sys;print(0xE000 in TTFont(sys.argv[1]).getBestCmap())" fonts/gaiji.ttf # 埋め込む TTF にその符号位置があるかgrep -rnoE '<img[^>]*(gaiji|外字)[^>]*>' --include='*.xhtml' . | head # 外字画像の置き場所
grep -nE 'img[^{]*\{[^}]*(width[^}]*height|height[^}]*width)' *.css # 幅と高さの両方(幅が捨てられる)
grep -nE 'img[^{]*\{[^}]*[0-9]px' *.css # px 指定(em とは別の値になる)
python3 -c "from PIL import Image;import sys;[print(f,Image.open(f).size) for f in sys.argv[1:]]" *.png # 元画像の画素数grep -nE 'img[^{]*\{[^}]*width[^}]*height|img[^{]*\{[^}]*height[^}]*width' *.css | grep -E '[0-9](px|pt|mm|cm|in)' # 幅と高さの両方を絶対単位で(崩れる)
grep -rnoE '<img[^>]*width="[0-9]+"[^>]*height="[0-9]+"[^>]*>' --include='*.xhtml' . | head # 属性の幅と高さ(CSS の height より残る)
grep -nE 'img[^{]*\{[^}]*[0-9](vw|vh)' *.css # vh/vw(捨てられる)grep -nE 'img[^{]*\{[^}]*width\s*:\s*[0-9.]+(px|pt|mm)' *.css | grep -vE 'height\s*:\s*[0-9.]+(px|pt|mm)' # 幅だけ px(図版が 6 割になる)
grep -nE 'img[^{]*\{[^}]*height\s*:\s*[0-9.]+(px|pt|mm)' *.css # 高さ px(等倍。幅と両方書いても高さが勝つ)
grep -rnoE '<p[^>]*>[^<]*<img[^>]*>' --include='*.xhtml' . | head # 段落の中の img(ここだけ 1.136 倍で崩れる)grep -nE 'writing-mode\s*:\s*vertical-rl' *.css # 縦書きなら高さが勝つ・無ければ横書きで幅が勝つ(OPF の primary-writing-mode だけでは決まらない)
grep -nE 'img[^{]*\{[^}]*height\s*:\s*[0-9.]+(px|pt|mm)' *.css | grep -vE 'width\s*:\s*[0-9.]+(px|pt|mm)' # 高さだけ px(横書きなら 0.6 倍)
for f in *.png *.jpg; do python3 -c "from PIL import Image,sys;im=Image.open('$f');print('$f',im.size)"; done | awk '$2+0>1920||$3+0>1920' # 長辺 1920 超(縮められる)grep -c '","Supported","Success","' 出力先/Summary_Log.csv # 1 なら KPF が出た。0 なら ET 落ちか失敗grep -oE 'media-type="image/[a-z+]+"' *.opf | sort | uniq -c # PNG/GIF が何枚あるか(全部 品質 99 の JPEG になり膨らむ)
for f in *.png; do python3 -c "from PIL import Image;im=Image.open('$f');print('$f',im.mode)"; done | grep -E ' (RGBA|LA|P)$' # 透過・パレット(白に合成/14 倍)
for f in *.jpg; do python3 -c "from PIL import Image;im=Image.open('$f');print('$f',im.mode,im.getexif().get(274))"; done | grep -E ' L |[^ ]+ (3|6|8)$' # グレー JPEG(再符号化)・EXIF 回転 3/6/8(回らない)# -*- coding: utf-8 -*-
"""em_restore.py 原稿.docx 変換後.epub 出力.epub (v3・2026-11-10 14:00)
Word の圏点(w:em)を pandoc が捨てた後の EPUB に、docx 側から圏点の語を拾い直して text-emphasis を入れ直す。
手順: document.xml の段落(w:p=本文・見出し・表のセル・箇条書きを含む)ごとに run を読み、w:em 付きの run の文字列と、
その段落の素の文字列(w:t 連結)を取る。隣り合う run が同じ圏点なら 1 語に繋ぐ(Word は校正の印やスペルチェックで語の途中を
run に割る)。EPUB の xhtml で同じ素の文字列を持つブロック(p・h1〜h6・li・td・th・dt・dd)を探し、その中の圏点の語を
<span class="emph-<val>"> で包む。語の中にタグ(太字など)が割り込んでいれば、タグをまたがずに文字の切れ目ごとに包む。
同じ段落内に同じ語が 2 回あれば docx 側の出現順で対応させる。
v3: 脚注(footnotes.xml)・文末脚注(endnotes.xml)の段落も読む(pandoc は aside の中の p に出す)。段落の照合は空白・改行を除き、
EPUB 側の注番号リンク(footnote-ref)を除いて比べる(Word の改行だけの段落=w:br は pandoc で <br /> と改行文字になる)。
テキストボックス(w:txbxContent)の中の段落は pandoc が本文に出さないので復元できず、数だけ別に報告する。CSS を 1 本追加し、OPF の manifest に登録する。
圏点の値→text-emphasis: dot→filled sesame(和文の慣習=黒ゴマ)、comma→filled sesame、circle→open circle、
underDot→filled dot + text-emphasis-position: under right。復元した数・語/段落が見つからなかった数を出す。"""
import sys, zipfile, re, html
MAP={"dot":"filled sesame","comma":"filled sesame","circle":"open circle","underDot":"filled dot"}
POS={"underDot":"under right"}
BLOCK=r'(p|h[1-6]|li|td|th|dt|dd)'
docx, src, dst = sys.argv[1:4]
zd=zipfile.ZipFile(docx)
xml="".join(zd.read(n).decode() for n in ("word/document.xml","word/footnotes.xml","word/endnotes.xml") if n in zd.namelist())
xml=re.sub(r'<mc:Fallback>.*?</mc:Fallback>', '', xml, flags=re.S) # AlternateContent の予備(VML)は Choice と同じ中身=二重に数えない
tb_xml="".join(m.group(0) for m in re.finditer(r'<w:txbxContent>.*?</w:txbxContent>', xml, re.S)) # 箱の中の段落は外の段落の入れ子なので先に抜く
xml=re.sub(r'<w:txbxContent>.*?</w:txbxContent>', '', xml, flags=re.S)
NORM=lambda t: re.sub(r'\s+','',t)
paras=[] # (plain_text, [(word, val), ...], in_textbox)
for in_tb,src_xml in ((False,xml),(True,tb_xml)):
for pm in re.finditer(r'<w:p[ >].*?</w:p>', src_xml, re.S):
p=pm.group(0); plain=[]; ems=[]
for rm in re.finditer(r'<w:r[ >].*?</w:r>', p, re.S):
r=rm.group(0); t="".join(html.unescape(x) for x in re.findall(r'<w:t[^>]*>(.*?)</w:t>', r, re.S))
if not t: continue
plain.append(t); em=re.search(r'<w:em w:val="([^"]+)"', r); val=em.group(1) if em else None
if val and ems and ems[-1][1]==val and ems[-1][2]==len(plain)-1: ems[-1]=(ems[-1][0]+t, val, len(plain)) # 隣の run と同じ圏点=1 語に繋ぐ
elif val: ems.append((t, val, len(plain)))
if ems: paras.append((NORM("".join(plain)), [(w,v) for w,v,_ in ems], in_tb))
z=zipfile.ZipFile(src); names=z.namelist(); files={n:z.read(n) for n in names}; z.close()
restored=0; missing=0; used_vals=set(); found=set()
def wrap(body, word, val, start):
"""body(タグ入り)の start 以降で素の文字列 word を探し、タグをまたがず文字片ごとに span で包む。返り値は (新 body, 次の探索位置) か None"""
segs=[(m.start(),m.end(),m.group(0).startswith("<")) for m in re.finditer(r'<[^>]+>|[^<]+', body)]
plain=""; idx=[] # idx[i] = body 内の位置(素の i 文字目)
for a,b,tag in segs:
if tag: continue
for j in range(a,b):
if j<start: continue
plain+=body[j]; idx.append(j)
w=html.escape(word,quote=False); k=plain.find(w)
if k<0: return None
pos=[idx[k+i] for i in range(len(w))]; out=body[:pos[0]]; i=0
while i<len(pos):
j=i
while j+1<len(pos) and pos[j+1]==pos[j]+1: j+=1
out+=f'<span class="emph-{val}">'+body[pos[i]:pos[j]+1]+'</span>'
if j+1<len(pos): out+=body[pos[j]+1:pos[j+1]]
i=j+1
return out+body[pos[-1]+1:], len(out)
for n in names:
if not n.endswith(".xhtml") or "nav" in n: continue
s=files[n].decode()
for plain, ems, in_tb in paras:
hits=[]
for pm in re.finditer(r'<'+BLOCK+r'(?:\s[^>]*)?>(.*?)</\1>', s, re.S):
b=re.sub(r'<a\b[^>]*class="footnote-ref"[^>]*>.*?</a>','',pm.group(2),flags=re.S)
if NORM(html.unescape(re.sub(r'<[^>]+>','',b)))==plain:
hits.append(pm)
if not in_tb: break # 箱の段落は複数回出る変換器もあるので全部に当てる(pandoc 3.9 は 1 回)
if not hits: continue
found.add(plain)
for m in reversed(hits):
body=m.group(2); nxt=0
for word,val in ems:
r=wrap(body, word, val, nxt)
if r is None: missing+=1; continue
body,nxt=r; restored+=1; used_vals.add(val)
s=s[:m.start(2)]+body+s[m.end(2):]
if '<link rel="stylesheet" type="text/css" href="../styles/emph.css"' not in s and used_vals:
s=s.replace("</head>",'<link rel="stylesheet" type="text/css" href="../styles/emph.css" />\n</head>',1)
files[n]=s.encode()
css="".join(f".emph-{v} {{ -epub-text-emphasis: {MAP[v]}; -webkit-text-emphasis: {MAP[v]}; text-emphasis: {MAP[v]};"+(f" -epub-text-emphasis-position: {POS[v]}; -webkit-text-emphasis-position: {POS[v]}; text-emphasis-position: {POS[v]};" if v in POS else "")+" }\n" for v in sorted(used_vals))
cssname=[n for n in names if n.endswith(".css")]
base=cssname[0].rsplit("/",1)[0]+"/" if cssname and "/" in cssname[0] else "EPUB/styles/"
cssn=base+"emph.css"; files[cssn]=css.encode()
opf=[n for n in names if n.endswith(".opf")][0]; o=files[opf].decode()
href=cssn.split("/",1)[1] if cssn.startswith("EPUB/") else cssn
o=o.replace("</manifest>",f'<item id="emph-css" href="{href}" media-type="text/css" />\n</manifest>',1); files[opf]=o.encode()
paras_missing=sum(1 for plain,_,_ in paras if plain not in found)
tb_all=sum(1 for p in paras if p[2]); tb_missing=sum(1 for p in paras if p[2] and p[0] not in found)
zz=zipfile.ZipFile(dst,"w")
zz.writestr(zipfile.ZipInfo("mimetype"), files["mimetype"], compress_type=zipfile.ZIP_STORED)
for n in names+([cssn] if cssn not in names else []):
if n=="mimetype": continue
zz.writestr(n, files[n], compress_type=zipfile.ZIP_DEFLATED)
zz.close()
print(f"docx 圏点の語 {sum(len(e) for _,e,_ in paras)} 件(段落 {len(paras)})→ 復元 {restored}・語が見つからず {missing}・段落が見つからず {paras_missing}・CSS {cssn} 値 {sorted(used_vals)}"+(f"・うちテキストボックスの段落 {tb_all}(見つからず {tb_missing}=AlternateContent の外に裸で置かれた箱は pandoc が本文に出さない)" if tb_all else ""))# -*- coding: utf-8 -*-
"""unbox.py 原稿.docx 出力.docx (v1・2026-11-10 15:00)
Word のテキストボックスの中身を、箱を抱えている段落の直後に通常の段落として移し、箱そのものは原稿から外す(docx→docx)。
pandoc 3.9 は Word 2010 以降の箱(mc:AlternateContent)だけを読み、しかも箱の中身を宿主段落の代わりに出す(宿主の文字が消える)。
裸の箱(w:drawing だけ・w:pict だけ)は中身ごと黙って消える。どちらも変換の前にこのスクリプトを通せば起きない。
手順: document.xml(と footnotes.xml/endnotes.xml)の一番外の段落(w:p)を入れ子の深さを数えて切り出し、段落の中の
mc:AlternateContent/裸の w:drawing/裸の w:pict のうち w:txbxContent を持つ物だけを対象にする(図版の w:drawing は触らない)。
箱 1 つにつき最初の w:txbxContent(AlternateContent なら Choice 側=Fallback と同じ中身)の段落を取り出し、箱を宿主の run から外し、
宿主に文字があれば取り出した段落を宿主段落の直後に並べる(宿主の文字は残る)。宿主が空(印刷所テンプレの扉・奥付はこの形)でも同じで、
空の宿主はそのまま残す(pandoc は空の段落を捨てるので、実物テンプレの出力は素と同一になる)。他の部品(styles・footnotes・画像)は手を付けない。
標準ライブラリだけ。箱の数・移した段落数・宿主に自分の文字があった数を出す。"""
import sys, zipfile, re
src, dst = sys.argv[1:3]
P_OPEN=re.compile(r'<w:p(?=[ >/])'); P_CLOSE='</w:p>'
def top_paras(xml):
"""一番外の w:p の (start,end) を入れ子の深さで切り出す(箱の中の w:p は外の段落の入れ子)"""
out=[]; depth=0; start=None; i=0
for m in re.finditer(r'<w:p(?=[ >/])[^>]*?(/?)>|</w:p>', xml):
if m.group(0)==P_CLOSE:
depth-=1
if depth==0: out.append((start,m.end()))
elif m.group(1)=='/':
if depth==0: out.append((m.start(),m.end()))
else:
if depth==0: start=m.start()
depth+=1
return out
def box_paras(container):
m=re.search(r'<w:txbxContent>(.*?)</w:txbxContent>', container, re.S)
if not m: return None
inner=m.group(1); return [inner[a:b] for a,b in top_paras(inner)]
def strip_run(run):
"""箱を外した後の run に文字・改行・タブ・図・注番号が無ければ run ごと消す"""
return '' if not re.search(r'<w:(t|br|tab|drawing|pict|footnoteReference|endnoteReference|sym)[ />]', run) else run
stats={"alt":0,"drawing":0,"pict":0,"moved":0,"host_text":0,"host_empty":0}
def unbox_para(p):
kinds=[("alt",r'<mc:AlternateContent>.*?</mc:AlternateContent>'),("drawing",r'<w:drawing>.*?</w:drawing>'),("pict",r'<w:pict>.*?</w:pict>')]
moved=[]
for kind,pat in kinds:
def rep(m):
paras=box_paras(m.group(0))
if paras is None: return m.group(0) # 箱でない図版はそのまま
stats[kind]+=1; moved.extend(paras); return ''
p=re.sub(pat, rep, p, flags=re.S)
if not moved: return p
p=re.sub(r'<w:r[ >].*?</w:r>', lambda m: strip_run(m.group(0)), p, flags=re.S)
own="".join(re.findall(r'<w:t[^>]*>(.*?)</w:t>', p, re.S)).strip()
stats["moved"]+=len(moved)
if own: stats["host_text"]+=1
else: # 宿主が空(実物テンプレの扉・奥付はこの形)=改行だけの run も外して空の段落として残す(pandoc は空の段落を捨て、空の見出しは素と同じ形で残す)
stats["host_empty"]+=1
p=re.sub(r'<w:r[ >].*?</w:r>', lambda m: '' if not re.search(r'<w:(t|drawing|pict|footnoteReference|endnoteReference|sym)[ />]', m.group(0)) else m.group(0), p, flags=re.S)
if '<w:sectPr' not in p: return "".join(moved) # 文字も図も無い宿主は段落ごと外す(見出し書式の空段落を残すと pandoc が空の h1 と目次項目を作り EPUBCheck RSC-005 になる)
return p+"".join(moved) # 箱の段落は宿主の直後に並べる(宿主の文字は残る・裸の箱も読まれる)
def process(xml):
out=[]; pos=0
for a,b in top_paras(xml):
out.append(xml[pos:a]); out.append(unbox_para(xml[a:b])); pos=b
out.append(xml[pos:]); return "".join(out)
z=zipfile.ZipFile(src); items=[(i.filename,z.read(i.filename)) for i in z.infolist()]; z.close()
zz=zipfile.ZipFile(dst,"w",zipfile.ZIP_DEFLATED)
for n,b in items:
if n in ("word/document.xml","word/footnotes.xml","word/endnotes.xml"): b=process(b.decode("utf-8")).encode("utf-8")
zz.writestr(n,b)
zz.close()
print(f"{src} → {dst}: 箱 {stats['alt']+stats['drawing']+stats['pict']}(AlternateContent {stats['alt']}・裸 drawing {stats['drawing']}・裸 pict {stats['pict']})・移した段落 {stats['moved']}・宿主に自分の文字があった段落 {stats['host_text']}・宿主が空の段落 {stats['host_empty']}")import zipfile, re
src, dst = "原稿.docx", "原稿-fix.docx"
zi = zipfile.ZipFile(src); zo = zipfile.ZipFile(dst, "w", zipfile.ZIP_DEFLATED)
for it in zi.infolist():
d = zi.read(it.filename)
if it.filename == "word/styles.xml": d = re.sub(r'<w:rFonts [^>]*/>', '<w:rFonts w:ascii="MS 明朝" w:hAnsi="MS 明朝" w:eastAsia="MS 明朝" w:cs="MS 明朝"/>', d.decode(), count=1).encode()
zo.writestr(it, d)
zo.close()# -*- coding: utf-8 -*-
"""EPUB の脚注を 4 事故+本文側 3 つで検品する(標準ライブラリのみ・読み取りのみ)。
python3 fn4_check.py 本.epub [...] 要確認が 1 つでもあれば終了コード 1"""
import sys, zipfile, re, posixpath
from urllib.parse import unquote
A = re.compile(r'<a\b([^>]*)>(.*?)</a>', re.S)
ASIDE = re.compile(r'<(aside|div|p|section)\b([^>]*)>', re.S) # 印は要素名でなく epub:type="footnote" で付く(2026-11-24 実測)
attr = lambda s, k: (re.search(r'\b%s="([^"]*)"' % k, s) or [None, None])[1]
def lastnum(s):
m = re.findall(r"\d+", s.translate(str.maketrans("0123456789", "0123456789")))
return m[-1] if m else None
def check(path):
z = zipfile.ZipFile(path); names = set(z.namelist()); out = []
opf = next((n for n in names if n.endswith(".opf")), None)
o = z.read(opf).decode("utf-8", "replace") if opf else ""; base = posixpath.dirname(opf) if opf else ""
items = {attr(m, "id"): posixpath.normpath(posixpath.join(base, attr(m, "href"))) for m in re.findall(r'<item\b[^>]*>', o)}
spine = [items.get(i) for i in re.findall(r'<itemref\b[^>]*\bidref="([^"]+)"', o)]
css = "".join(z.read(n).decode("utf-8", "replace") for n in names if n.endswith(".css"))
docs = sorted(n for n in names if n.lower().endswith((".xhtml", ".html")))
cssnum = re.search(r'::?(after|before)\s*\{[^}]*content\s*:[^}]*counter', css) # 番号を CSS counter で付ける形は錨の中身が空でも番号が焼かれる
text = {n: z.read(n).decode("utf-8", "replace") for n in docs}
def resolve(n, h): # href → (file, id小文字)
f, frag = (h.split("#", 1) + [""])[:2]
return (posixpath.normpath(posixpath.join(posixpath.dirname(n), unquote(f))) if f else n, unquote(frag).lower())
ids = {}; notes = {}; inner = {}; backs = []; refs = []; npos = {}; innerrefs = []
for n in docs:
t = text[n]; seen = {}
if n not in items.values(): out.append(f" {n} 要確認: manifest に無い(注の本文が本から消える)")
for i in re.findall(r'\sid="([^"]*)"', t): seen.setdefault(i.lower(), []).append(i)
ids[n] = seen
for v in seen.values():
if len(v) > 1: out.append(f" {n} 要確認: id が重複(大文字小文字も同一視): {v}(最初の 1 つに結ばれ、残りの注は段落になる)")
for m in ASIDE.finditer(t):
tag, a = m.group(1), m.group(2)
if not re.search(r'epub:type="[^"]*\b(footnote|rearnote|endnote)\b', a): continue
i = (attr(a, "id") or "?").lower(); body = t[m.end():t.find(f"</{tag}>", m.end())]
notes[(n, i)] = body; npos[(n, i)] = m.start()
if re.sub(r"<[^>]+>", "", body).replace(" ", "").replace("\u3000", "").strip() == "" and "<img" not in body: out.append(f" {n}#{i} 要確認: 注の本文が空(印が落ち、番号の文字だけ本文に残る。Word の書き忘れた脚注はこの形)")
for j in re.findall(r'\sid="([^"]*)"', body): inner[(n, j.lower())] = (n, i)
if re.search(r'\b(rearnote|endnote)\b', a): out.append(f" {n}#{i} 要確認: epub:type が rearnote/endnote(印は footnote にしか付かない)")
for bm in A.finditer(body):
ba = bm.group(1); h = attr(ba, "href")
if h is None: continue
if "noteref" in ba: innerrefs.append((n, i) + resolve(n, h)); continue # 入れ子の注か、戻りリンクへの誤用かは全文を読んだ後で判定
if h == "": out.append(f" {n}#{i} 要確認: 戻りリンクの href が空(章の先頭へ飛ぶ)")
elif h.startswith("http"): out.append(f" {n}#{i} 要確認: 戻りリンクが外部 URL")
elif "#" not in h: out.append(f" {n}#{i} 要確認: 戻りリンクがファイル名だけ(ファイルの先頭へ飛ぶ)")
else:
tf, frag = resolve(n, h)
if (tf, frag) == (n, i): out.append(f" {n}#{i} 要確認: 戻りリンクが自分自身")
elif tf not in text or frag not in ids.get(tf, {}) and tf in text: backs.append((n, i, tf, frag, True))
else: backs.append((n, i, tf, frag, False))
for m in A.finditer(t):
a, lab = m.group(1), re.sub(r"<[^>]+>", "", m.group(2)).strip(); h = attr(a, "href")
if h is None or ("noteref" not in a and "doc-noteref" not in a): continue
tf, frag = resolve(n, h); refs.append((n, tf, frag, lab, a, m.start()))
if lab == "" and "<img" not in m.group(2) and not cssnum: out.append(f" {n} →#{frag} 要確認: 注番号の中身が空(印が付かず押す物も無い)")
if re.search(r'aside[^{}]*\{[^}]*display\s*:\s*none', css): out.append(" CSS 要確認: aside を display:none で隠している(注が本ごと消える)")
for n, i, tf, frag in innerrefs:
if (tf, frag) not in notes and (tf, frag) not in inner: out.append(f" {n}#{i} 要確認: 戻りリンクに noteref(注番号の側だけに付ける)")
hit = {}; src = {}
for n, tf, frag, lab, a, pos in refs:
if 'epub:type="noteref"' not in a: out.append(f" {n} 「{lab}」 要確認: noteref が epub:type に無い(印が付かない)")
if tf not in text or frag not in ids.get(tf, {}):
out.append(f" {n} 「{lab}」→{posixpath.basename(tf)}#{frag} 要確認: 飛び先が無い(W14001・注が本に入らない)"); continue
key = (tf, frag) if (tf, frag) in notes else inner.get((tf, frag))
if key is None: out.append(f" {n} 「{lab}」→#{frag} 要確認: 飛び先に epub:type=footnote が無い(印が付かない)"); continue
hit.setdefault((tf, frag), []).append(lab); src.setdefault(key, set()).add(n)
if tf == n and key in npos and npos[key] < pos: out.append(f" {n} 「{lab}」→#{frag} 要確認: 同じファイルで注(epub:type=footnote)が注番号より前にある(印が付かず段落になる)")
d, e = lastnum(lab), lastnum(frag)
if d and e and d != e: out.append(f" {n} 「{lab}」→#{frag} 要確認: 見える番号と id の末尾の番号が違う(取り違えの疑い。章ごとの振り直しなら id に章の印 c2-fn1 を入れる)")
if tf != n and tf in spine and n in spine and spine.index(tf) < spine.index(n): out.append(f" {n} 「{lab}」→{posixpath.basename(tf)} 要確認: 注のファイルが spine で参照より前(印が付かない)")
for k, v in hit.items():
if len(v) > 1: out.append(f" {posixpath.basename(k[0])}#{k[1]} 要確認: 同じ飛び先を {len(v)} か所が指す {v}(2 つ目以降の注は段落になる)")
for k in notes:
if k not in src: out.append(f" {posixpath.basename(k[0])}#{k[1]} 要確認: 参照されない注(印が付かず本文の段落になる)")
for n, i, tf, frag, missing in backs:
if missing: out.append(f" {n}#{i} 要確認: 戻りリンクの飛び先 {posixpath.basename(tf)}#{frag} が無い(W14001・番号が押せない文字になる)")
elif (n, i) in src and tf not in src[(n, i)]: out.append(f" {n}#{i} 要確認: 戻りリンクが参照元と別のファイル {posixpath.basename(tf)} へ")
print(path); print("\n".join(out) if out else " 要確認なし"); return len(out)
if __name__ == "__main__":
sys.exit(1 if sum(check(p) for p in sys.argv[1:]) else 0)# -*- coding: utf-8 -*-
# 使い方: python3 kpf_read.py 本.kpf (標準ライブラリだけ・読み取りのみ)
import sys, zipfile, sqlite3, tempfile, re
kpf = sys.argv[1]
z = zipfile.ZipFile(kpf)
raw = b"".join(z.read(n) for n in z.namelist() if n.endswith("book.kdf"))
path = tempfile.mktemp(suffix=".kdf")
open(path, "wb").write(raw[:1024] + raw[2048:]) # 1024 バイト目からの 1024 バイトを抜く
db = sqlite3.connect(path)
frags = {i: (v if isinstance(v, bytes) else str(v).encode())
for i, t, v in db.execute("select id, payload_type, payload_value from fragments")}
secs = [k for k in frags if re.match(r"c[0-9A-Za-z]+$", k)]
MARK = b"\x01\xb7r\x01\xc7" # 脚注(ポップアップ)の印。注本文の断片にだけ付く
marked = [k for k, v in frags.items() if MARK in v]
its = [k for k, v in frags.items() if b"IS_TARGET_SECTION" in v]
print("断片の数:", len(frags))
print("節(c〜)の数:", len(secs))
print("脚注の印を持つ断片(注として結ばれた注の数):", len(marked), marked)
print("IS_TARGET_SECTION を持つ断片(節ごとに 1 つ):", len(its))
print("生バイトで IS_TARGET_SECTION を数えた数(参考・数え過ぎる):", raw.count(b"IS_TARGET_SECTION"))