Files
yiyezhqiu-refactored/tools/acceptance/pdf_palette.py
T

110 lines
5.6 KiB
Python

"""Compare native reference colors and check all scopes on explicit copies."""
from __future__ import annotations
import argparse
from collections import Counter
from dataclasses import asdict
import json
import os
from pathlib import Path
import sys
import threading
from pypdf import PdfReader
from pypdf.generic import ContentStream
from dx_productivity.features.pdf_export.exporter import export_project
from dx_productivity.features.pdf_export.models import ExportScope, PdfExportSettings
from dx_productivity.features.pdf_export.settings import save_settings
def color_operations(path):
reader = PdfReader(path)
colors = Counter()
for page in reader.pages:
def inspect(stream, resources):
for operands, operator in ContentStream(stream, reader).operations:
if operator in (b'RG', b'rg'):
colors[tuple(round(float(value), 4) for value in operands)] += 1
elif operator == b'Do':
obj = resources['/XObject'][operands[0]].get_object()
if obj.get('/Subtype') == '/Form':
inspect(obj, obj.get('/Resources', resources))
inspect(page.get_contents(), page['/Resources'])
return colors
def main():
parser = argparse.ArgumentParser()
parser.add_argument('--audio', required=True, type=Path)
parser.add_argument('--pon', required=True, type=Path)
parser.add_argument('--reference-source', required=True, type=Path)
parser.add_argument('--evidence', required=True, type=Path)
parser.add_argument('--resume-scopes', action='store_true')
options = parser.parse_args()
base = options.evidence.resolve()
base.mkdir(parents=True, exist_ok=True)
inherited_wdir = os.environ.get('WDIR')
configs = {str(path): path.read_bytes() for project in (options.audio, options.pon)
for path in project.parent.rglob('*')
if path.is_file() and path.name.casefold() in ('dxdesigner.xml', project.name.casefold(), 'sch2pdf.ini')}
results = []
for name, project, scope, block, sheet, expected in (
('audio', options.audio, ExportScope.PROJECT, '', '', 1),
('pon-page', options.pon, ExportScope.CURRENT_PAGE, 'PON', '03_FLASH', 1),
('pon-block', options.pon, ExportScope.BLOCK, 'PON', '', 17),
('pon-project', options.pon, ExportScope.PROJECT, '', '', 24),
):
settings = PdfExportSettings(project, scope, block, base / name, True)
if options.resume_scopes:
runs = sorted((base / 'state/DxProductivity/pdf-runs').glob('*/request.json'))
matching = [run for run in runs if Path(json.loads(run.read_text(encoding='utf-8'))['output']).parent == settings.output_dir]
if matching:
run = matching[-1].parent
request = json.loads((run / 'request.json').read_text(encoding='utf-8'))
result = json.loads((run / 'result.json').read_text(encoding='utf-8'))
assert request['print_theme'] == 'reference' and result['state'] == 'success'
assert len(PdfReader(result['output']).pages) == expected
results.append({'output_path': result['output'], 'pages': expected, 'run_dir': str(run), 'state': 'success'})
print(f'RESUMED VERIFIED SCOPE {name} pages={expected}', flush=True)
continue
result = export_project(settings, threading.Event(), print, active_block_name=block,
active_sheet_name=sheet, local_app_data=base / 'state', overwrite=True)
assert result.state == 'success', result.message
assert result.pages == expected, asdict(result)
results.append(asdict(result))
save_settings(settings, config_path=base / f'{name}-settings.json')
print(f'PASS REFERENCE SCOPE {name} pages={result.pages}', flush=True)
sys.path.insert(0, str(options.reference_source))
from mentor_pdf_export.models import ExportOptions
from mentor_pdf_export.profiles import prepare_native_environment, build_command
from mentor_pdf_export.engine import run_engine
from dx_productivity.features.pdf_export.engine import discover_engine
reference_run = base / 'original-tool-reference'
reference_run.mkdir(exist_ok=True)
reference_pdf = reference_run / 'reference.pdf'
profile = ExportOptions(print_theme='reference', font_mapping='arial', legacy_gbk=True, stop_at='')
command = build_command(discover_engine(), options.audio, reference_pdf, profile)
assert run_engine(command, options.audio.parent, reference_run, threading.Event(), 180,
print, env=prepare_native_environment(reference_run, profile)) == 0
ours = color_operations(results[0]['output_path'])
reference = color_operations(reference_pdf)
assert ours == reference, (ours, reference)
for rgb in ((1., 0., 0.), (0., 0., 1.), (0., .502, .502), (.502, 0., .502), (0., .502, 0.)):
assert ours[rgb] > 0, (rgb, ours)
assert os.environ.get('WDIR') == inherited_wdir
for path, before in configs.items():
assert Path(path).read_bytes() == before, f'Source configuration changed: {path}'
report = {'scopes': results, 'reference_pdf': str(reference_pdf),
'colors_match_reference': True,
'colors': {str(rgb): count for rgb, count in ours.items()},
'source_configuration_unchanged': list(configs), 'parent_wdir_unchanged': True}
(base / 'palette-acceptance.json').write_text(json.dumps(report, ensure_ascii=False, indent=2, default=str), encoding='utf-8')
print('PASS PDF REFERENCE PALETTE AND ALL SCOPES', json.dumps(report['colors']), flush=True)
if __name__ == '__main__':
main()