"""app.py 回歸測試 — 產生可逐位元比較的基準快照。 用法: python tests/regression.py baseline.json # 改完程式後 python tests/regression.py after.json python tests/regression.py --compare baseline.json after.json """ import hashlib import importlib.util import json import subprocess import sys import time from pathlib import Path import numpy as np import pikepdf APP_PATH = Path(__file__).resolve().parent.parent / "app.py" GS = "gs" def load_app(): spec = importlib.util.spec_from_file_location("appmod", str(APP_PATH)) mod = importlib.util.module_from_spec(spec) sys.modules["appmod"] = mod spec.loader.exec_module(mod) return mod # ---------------------------------------------------------------- 測試素材 def make_photo_pdf(path, pages=2): """每頁一張 300dpi 全版彩色圖 + RGB 中性灰文字 + 藍色向量線。""" pdf = pikepdf.new() rng = np.random.default_rng(12345) px = np.zeros((3508, 2480, 3), np.uint8) px[..., 0] = 200 px[..., 2] = 90 px[500:1500, 500:1500, 1] = 180 px[2000:2500, 300:900] = rng.integers(0, 255, (500, 600, 3), dtype=np.uint8) for _ in range(pages): page = pdf.add_blank_page(page_size=(595.28, 841.89)) img = pikepdf.Stream(pdf, px.tobytes()) img["/Type"] = pikepdf.Name("/XObject") img["/Subtype"] = pikepdf.Name("/Image") img["/Width"], img["/Height"] = 2480, 3508 img["/ColorSpace"] = pikepdf.Name("/DeviceRGB") img["/BitsPerComponent"] = 8 content = ( b"q 595.28 0 0 841.89 0 0 cm /Im0 Do Q\n" b"BT /F1 12 Tf 0.25 0.25 0.25 rg 72 700 Td (Hello Print) Tj ET\n" b"BT /F1 4 Tf 0 0 0 rg 72 650 Td (tiny text) Tj ET\n" b"0.5 0.5 0.5 rg 60 60 120 40 re f\n" # 中性灰塊 → 應改單色黑 b"0.2 0.4 0.8 RG 0.1 w 50 300 m 500 300 l S\n" # 細線 + 彩色 b"0 0 1 rg 400 500 60 60 re f\n" # 純藍(不應改) ) page.obj["/Resources"] = pikepdf.Dictionary({ "/XObject": pikepdf.Dictionary({"/Im0": pdf.make_indirect(img)}), "/Font": pikepdf.Dictionary({ "/F1": pdf.make_indirect(pikepdf.Dictionary({ "/Type": pikepdf.Name("/Font"), "/Subtype": pikepdf.Name("/Type1"), "/BaseFont": pikepdf.Name("/Helvetica"), })) }), }) page.obj.Contents = pdf.make_stream(content) pdf.save(str(path)) return path def make_shared_contents_pdf(path, pages=2): """多頁共用同一個 Contents 物件(測 P0-2)。""" pdf = pikepdf.new() sa = pdf.make_stream(b"0.5 0.5 0.5 rg 5 5 50 50 re f\n") sb = pdf.make_stream(b"0 0 1 rg 60 60 50 50 re f\n") contents = pdf.make_indirect(pikepdf.Array([sa, sb])) for _ in range(pages): page = pdf.add_blank_page(page_size=(300, 300)) page.obj["/Contents"] = contents pdf.save(str(path)) return path def make_shared_single_stream_pdf(path, pages=3): """ 多頁共用「單元素 Contents 陣列」內的同一個間接串流。 這是 force_k_black 就地改寫(write_content_stream_in_place)會走的路徑; 單一元素陣列與單一間接串流都應保留共用關係,不可被複製成 N 份。 """ pdf = pikepdf.new() stream = pdf.make_stream(b"0.5 0.5 0.5 rg 5 5 50 50 re f\n") contents = pdf.make_indirect(pikepdf.Array([stream])) for _ in range(pages): page = pdf.add_blank_page(page_size=(300, 300)) page.obj["/Contents"] = contents pdf.save(str(path)) return path def make_shared_resources_pdf(path, pages=3): """多頁共用同一個 Resources 物件(測 P0-3)。""" pdf = pikepdf.new() res = pdf.make_indirect(pikepdf.Dictionary({ "/ColorSpace": pikepdf.Dictionary({ "/CS0": pikepdf.Name("/DeviceRGB"), "/CS1": pikepdf.Name("/DeviceCMYK"), }) })) for _ in range(pages): page = pdf.add_blank_page(page_size=(300, 300)) page.obj["/Resources"] = res page.obj.Contents = pdf.make_stream(b"1 0 0 rg 10 10 100 100 re f\n") pdf.save(str(path)) return path def make_gray_pdf(path, pages=1): """純灰階向量(無點陣圖)→ 測 force_k_black 與細線/小字判定。""" pdf = pikepdf.new() for _ in range(pages): page = pdf.add_blank_page(page_size=(595.28, 841.89)) page.obj.Contents = pdf.make_stream( b"0.3 0.3 0.3 rg 50 50 100 100 re f\n" b"0.25 0.25 0.25 RG 0.2 w 10 200 m 500 200 l S\n" b"0.1 0.1 0.1 rg 20 20 10 10 re f\n" ) pdf.save(str(path)) return path # ---------------------------------------------------------------- 量測工具 def pdf_metrics(path): """抽出版面/色彩/字型等可比較的量化指標。""" m = {} with pikepdf.Pdf.open(str(path)) as pdf: m["pages"] = len(pdf.pages) spaces, contents_objs, res_objs = set(), [], [] for page in pdf.pages: c = page.obj.Contents if isinstance(c, pikepdf.Array): contents_objs.append([o.objgen for o in c]) else: contents_objs.append([c.objgen]) r = page.obj.get("/Resources") if r is not None: res_objs.append(r.objgen) for _, cs in ((page.obj.get("/Resources") or {}).get("/ColorSpace") or {}).items(): spaces.add(str(cs)) m["color_spaces"] = sorted(spaces) m["contents_objgen"] = contents_objs m["resources_objgen"] = res_objs m["distinct_contents_objs"] = len({tuple(x) for sub in contents_objs for x in sub}) r = subprocess.run(["pdffonts", str(path)], capture_output=True, text=True) rows = [l.split() for l in r.stdout.splitlines()[2:] if l.strip() and not set(l.strip()) <= {"-", " "}] m["fonts"] = sorted(row[0] for row in rows if row) m["fonts_embedded"] = sorted( row[0] for row in rows if len(row) >= 6 and row[-5].lower() == "yes" ) r = subprocess.run(["pdfimages", "-list", str(path)], capture_output=True, text=True) imgs = [] for line in r.stdout.splitlines()[2:]: c = line.split() if len(c) >= 14 and c[0].isdigit(): imgs.append({"page": int(c[0]), "color": c[5], "comp": c[6], "xppi": c[-4], "yppi": c[-3]}) m["images"] = imgs r = subprocess.run(["pdfinfo", str(path)], capture_output=True, text=True) for line in r.stdout.splitlines(): if line.startswith(("Pages:", "Page size:", "PDF version:")): k, v = line.split(":", 1) m[k.strip().lower().replace(" ", "_")] = v.strip() return m def read_pam_fast(path): """本測試自己的 PAM 讀取(不依賴 app.py,避免被測物同時是量尺)。""" data = Path(path).read_bytes() end = data.index(b"ENDHDR\n") + 7 hdr = dict(l.split(" ", 1) for l in data[:end].decode("ascii").splitlines() if " " in l) w, h = int(hdr["WIDTH"]), int(hdr["HEIGHT"]) return np.frombuffer(data, np.uint8, count=w * h * 4, offset=end).reshape(h, w, 4) def ink_metrics(pdf_path, dpi=72): """像素級色彩指標:總墨量、四色黑、邊緣墨量。""" import tempfile, shutil d = Path(tempfile.mkdtemp(prefix="inkmetric_")) try: subprocess.run([GS, "-dSAFER", "-dBATCH", "-dNOPAUSE", "-dQUIET", "-sDEVICE=pamcmyk32", f"-r{dpi}", f"-sOutputFile={d/'p%05d.pam'}", str(pdf_path)], check=True, capture_output=True) out = {"pages": 0, "tac_max": 0.0, "tac_mean": 0.0, "rich_black_px": 0, "edge_px_over_5pct": 0, "channel_hist": [0, 0, 0, 0]} tacs, rich, edges = [], 0, 0 for pam in sorted(d.glob("p*.pam")): ink = read_pam_fast(pam) out["pages"] += 1 total = ink.sum(axis=2, dtype=np.uint16) tacs.append(float(total.max()) * 100 / 255) rich += int(((ink[..., 3] >= 128) & (ink[..., :3].min(axis=2) >= 77)).sum()) band = 3 e = np.concatenate([ink[:band].ravel(), ink[-band:].ravel(), ink[:, :band].ravel(), ink[:, -band:].ravel()]) edges += int((e > 13).sum()) for i in range(4): out["channel_hist"][i] += int((ink[..., i] > 0).sum()) out["tac_max"] = max(tacs) if tacs else 0.0 out["tac_mean"] = sum(tacs) / len(tacs) if tacs else 0.0 out["rich_black_px"] = rich out["edge_px_over_5pct"] = edges return out finally: shutil.rmtree(d, ignore_errors=True) def sha256(path): return hashlib.sha256(Path(path).read_bytes()).hexdigest()[:16] # ---------------------------------------------------------------- 主流程 def run(tag, out_path, work_root): app = load_app() work_root = Path(work_root) work_root.mkdir(parents=True, exist_ok=True) results = {"tag": tag, "app_sha256": sha256(APP_PATH)} # --- 素材 --- srcs = { "photo": make_photo_pdf(work_root / "photo.pdf", pages=2), "shared_contents": make_shared_contents_pdf(work_root / "shared_contents.pdf"), "shared_single": make_shared_single_stream_pdf(work_root / "shared_single.pdf"), "shared_resources": make_shared_resources_pdf(work_root / "shared_res.pdf"), "gray": make_gray_pdf(work_root / "gray.pdf"), } results["sources"] = {k: pdf_metrics(v) for k, v in srcs.items()} # --- force_k_black --- fk_dir = work_root / "fk" fk_dir.mkdir(exist_ok=True) results["force_k"] = {} for name, src in srcs.items(): out, msg = app.force_k_black(src, fk_dir) rel = Path(out).name if out else None entry = { "output": rel, "message": msg, "metrics": pdf_metrics(out) if out else None, "ink": ink_metrics(out) if out else None, } results["force_k"][name] = entry # --- 完整 CMYK 轉換(只用一張 1 頁檔,節省時間)--- conv_src = make_photo_pdf(work_root / "conv1.pdf", pages=1) conv_dir = work_root / "conv" conv_dir.mkdir(exist_ok=True) t0 = time.time() out, msg = app.convert_pdf_to_cmyk_profiled(conv_src, conv_dir) dt = time.time() - t0 results["convert"] = { "output": Path(out).name if out else None, "seconds": round(dt, 2), "message_lines": sorted( l for l in msg.splitlines() if l.startswith(("✅", "❌", "⏱️", "📦", "🔧", "🎨", "📐", "🖼️", "⬛", "🔤")) ), "size_bytes": Path(out).stat().st_size if out else 0, } if out: results["convert"]["metrics"] = pdf_metrics(out) results["convert"]["ink"] = ink_metrics(out) # 色彩準確度:與基準相比每個像素的 CMYK 值 results["convert"]["cmyk_checksum"] = cmyk_checksum(out) # --- 預檢函式(用轉換後檔案)--- if out: results["inspectors"] = { "image_resolution": app.inspect_image_resolution(out), "fonts": app.inspect_fonts(out), "pdf_info": app.inspect_pdf_info(out), "page_boxes": app.inspect_page_boxes(out)[0], "ink_report": app.inspect_ink( out, [False] * int(results["convert"]["metrics"]["pages"]) ), "transparency": app.inspect_transparency_overprint_spot(out), "text_lines": app.inspect_text_and_lines(out), "color_modes": app.detect_pdf_color_modes(out), "printer": app.inspect_for_printer(out), } # --- DOCX 字型(若有 soffice)--- results["environment"] = app.build_environment_status() # --- 純函式行為 --- results["functions"] = { "format_pages": { "sorted_input": app.format_pages([1, 2, 3, 5, 8]), "unsorted_input": app.format_pages([8, 1, 3, 2, 5]), "with_duplicates": app.format_pages([3, 1, 1, 2]), "range_merge": app.format_pages([1, 2, 3, 7, 9, 10, 11]), "over_limit": app.format_pages(list(range(1, 40))), }, "evaluate_output_color_spaces": { "rgb": app.evaluate_output_color_spaces({"/DeviceRGB"}), "cmyk": app.evaluate_output_color_spaces({"/DeviceCMYK"}), "empty": app.evaluate_output_color_spaces(set()), }, } # --- process_document 端到端(驗證暫存清理與單次開啟整合)--- e2e_src = make_photo_pdf(work_root / "e2e.pdf", pages=1) e2e_dir = work_root / "e2e_out" e2e_dir.mkdir(exist_ok=True) class NoopProgress: def __call__(self, *a, **k): return None import os old_tmp = app.TMP_ROOT app.TMP_ROOT = e2e_dir # 把暫存導到測試目錄,避免污染 /tmp before_dirs = set(e2e_dir.glob("print_pdf_*")) try: det, out, msg = app.process_document(str(e2e_src), True, NoopProgress()) finally: app.TMP_ROOT = old_tmp created = sorted(p.name for p in set(e2e_dir.glob("print_pdf_*")) - before_dirs) out_report = {} if out: out_report = {"metrics": pdf_metrics(out), "size_bytes": Path(out).stat().st_size} # 只保留結構性欄位,訊息內含時間/路徑會使比對不穩定 results["process_document"] = { "has_output": out is not None, "output": out_report, "work_dirs_created": len(created), "message_sections": sorted( line.split(":")[0] for line in msg.splitlines() if line.startswith(("✅", "❌", "⚠️", "ℹ️")) ), "detection_sections": sorted( line for line in det.splitlines() if line.startswith(("【", "🎨", "📄", "✅", "⚠️", "ℹ️")) ), } # 這批暫存目錄由 atexit 於行程結束時清除,這裡只確認建立數 results["process_document"]["work_dirs_left_in_place"] = len(created) Path(out_path).write_text(json.dumps(results, indent=2, ensure_ascii=False, default=str)) return results def cmyk_checksum(pdf_path, dpi=36): """把轉換結果點陣化成 CMYK,回傳決定性的像素級校驗值。""" import tempfile, shutil, hashlib as _h d = Path(tempfile.mkdtemp(prefix="cksum_")) try: subprocess.run([GS, "-dSAFER", "-dBATCH", "-dNOPAUSE", "-dQUIET", "-sDEVICE=pamcmyk32", f"-r{dpi}", f"-sOutputFile={d/'p%05d.pam'}", str(pdf_path)], check=True, capture_output=True) h = _h.sha256() stats = {"c": [], "m": [], "y": [], "k": []} for i, pam in enumerate(sorted(d.glob("p*.pam"))): ink = read_pam_fast(pam) h.update(ink.tobytes()) if i == 0: for j, ch in enumerate("cmyk"): stats[ch] = [int(ink[..., j].min()), int(ink[..., j].max()), int(ink[..., j].mean())] return {"pixel_sha256": h.hexdigest()[:32], "page0_channel_stats": stats} finally: shutil.rmtree(d, ignore_errors=True) def compare(a_path, b_path): a = json.loads(Path(a_path).read_text()) b = json.loads(Path(b_path).read_text()) diffs, same = [], [] def walk(pa, x, y): if isinstance(x, dict) and isinstance(y, dict): for k in sorted(set(x) | set(y)): walk(f"{pa}.{k}", x.get(k), y.get(k)) elif x != y: diffs.append((pa, x, y)) else: same.append(pa) walk("", a, b) print(f"基準: {a['tag']} (app sha {a['app_sha256']})") print(f"對照: {b['tag']} (app sha {b['app_sha256']})") print(f"\n相同項目: {len(same)} 差異項目: {len(diffs)}\n") if not diffs: print("✅ 完全一致 — 無回歸") return 0 # 分類:預期會變 vs 需注意 expected_prefixes = ( ".force_k", # P0-2/P0-3 修正本來就會改變 ".convert.seconds", # 計時必然浮動 ".tag", ".app_sha256", ".environment", # 可能含版本字串 ) hard, soft = [], [] for path, x, y in diffs: label = "預期" if path.startswith(expected_prefixes) else "❗需檢視" (soft if label == "預期" else hard).append((path, x, y, label)) for group, title in ((hard, "❗ 非預期差異(可能是回歸)"), (soft, "・ 預期差異")): if not group: continue print(f"── {title} ──") for path, x, y, _ in group[:60]: sx, sy = str(x), str(y) if len(sx) > 110: sx = sx[:110] + "…" if len(sy) > 110: sy = sy[:110] + "…" print(f" {path}\n 基準: {sx}\n 對照: {sy}") if len(group) > 60: print(f" …另有 {len(group) - 60} 項") print() return 1 if hard else 0 if __name__ == "__main__": if sys.argv[1] == "--compare": sys.exit(compare(sys.argv[2], sys.argv[3])) tag = sys.argv[1] import tempfile root = Path(tempfile.mkdtemp(prefix=f"regress_{Path(tag).stem}_")) print(f"工作目錄: {root}") res = run(Path(tag).stem, tag, root) print(f"已寫出 {tag}") print(f" convert: {res['convert']['seconds']}s, " f"{res['convert']['size_bytes']} bytes, " f"checksum={res['convert'].get('cmyk_checksum', {}).get('pixel_sha256')}") for name, e in res["force_k"].items(): print(f" force_k[{name}]: {e['message'][:90]}")