diff --git a/src/cli/commands/report.ts b/src/cli/commands/report.ts index 0604ff6..538534a 100644 --- a/src/cli/commands/report.ts +++ b/src/cli/commands/report.ts @@ -4,15 +4,15 @@ import { runCapabilityResult } from "../helpers.js"; import { booleanOption, numberOption, stringOption } from "../parser.js"; import { outputOptions, printJson } from "../printer.js"; import { CliError, usageError } from "../../core/errors.js"; -import { renderReportFile, saveReportMarkdown, validateReportFile } from "../../domains/seal/reports/files.js"; +import { exportReportPackage, renderReportFile, saveReportMarkdown, validateReportFile } from "../../domains/seal/reports/files.js"; import type { MonthlyReportResult } from "../../domains/seal/reports/monthly.js"; import { loadReviews, reviewFilePath, writeReview } from "../../domains/seal/reports/review-store.js"; import type { ParsedArgs } from "../types.js"; /** Tenant-free commands: dispatch these before resolving enterprise configuration or authentication. */ -export async function handleLocalReportCommand(action: "validate" | "render", args: ParsedArgs) { +export async function handleLocalReportCommand(action: "validate" | "render" | "export", args: ParsedArgs) { const file = args.command[2] ?? stringOption(args.options.file); - if (!file) throw usageError(`Usage: seal-use report ${action} <报告文件.md>${action === "render" ? " --out <产物路径词干>" : ""}`); + if (!file) throw usageError(`Usage: seal-use report ${action} <报告文件.md>${action === "render" ? " --out <产物路径词干>" : action === "export" ? " --out <目标文件夹>" : ""}`); if ("python" in args.options) throw usageError("报告工具已移除 Python 依赖,请去掉 --python 参数。"); if (action === "validate") { const result = await validateReportFile(file); @@ -21,7 +21,16 @@ export async function handleLocalReportCommand(action: "validate" | "render", ar return; } const out = stringOption(args.options.out) ?? stringOption(args.options.o); - if (!out) throw usageError("Usage: seal-use report render <报告文件.md> --out <产物路径词干>"); + if (!out) throw usageError(`Usage: seal-use report ${action} <报告文件.md> --out <${action === "export" ? "目标文件夹" : "产物路径词干"}>`); + if (action === "export") { + const result = await exportReportPackage(file, { + out, format: stringOption(args.options.format), width: numberOption(args.options.width), + chrome: stringOption(args.options.chrome), overwrite: booleanOption(args.options.overwrite) + }); + printJson(result, outputOptions(args.options)); + if (!result.validation.valid) throw new CliError("报告校验未通过,未生成完整导出包。请按 validation.issues 修正后重试。", 1); + return; + } const result = await renderReportFile(file, { out, format: stringOption(args.options.format), width: numberOption(args.options.width), chrome: stringOption(args.options.chrome), overwrite: booleanOption(args.options.overwrite) diff --git a/src/cli/help.ts b/src/cli/help.ts index 1b89b8c..124c079 100644 --- a/src/cli/help.ts +++ b/src/cli/help.ts @@ -648,6 +648,19 @@ export const HELP_REGISTRY: AreaHelp[] = [ ], description: "No enterprise login. Validation failure produces JSON issues and no artifacts. Validation and HTML use the bundled runtime; PNG/PDF need Chrome/Chromium. No Python or Pillow required. First use of math fetches and caches KaTeX resources. Markdown parsing is bundled, with no runtime npm/npx dependency." }, + { + name: "export", + summary: "Package Markdown, local 4x assets, self-contained HTML, and PDF into a dedicated directory", + usage: ["seal-use report export <报告.md> --out <输出目录> [--format ]"], + options: [ + { flag: "--out ", description: "Dedicated output directory for the report bundle" }, + { flag: "--format ", description: "all (default), html, or pdf" }, + { flag: "--width ", description: "PNG viewport width, default 1200" }, + { flag: "--chrome ", description: "Chrome/Chromium executable; otherwise auto-detected" }, + { flag: "--overwrite", description: "Explicitly permit replacing existing output files" } + ], + description: "Bundles the report into a clean single directory: includes the Markdown with its .md.assets/ companion folder, plus self-contained HTML and print-ready PDF." + }, { name: "review set", summary: "Record one human adjudication (who was right: AI or human) for a document", diff --git a/src/cli/runner.ts b/src/cli/runner.ts index 309dbae..d1b15d7 100755 --- a/src/cli/runner.ts +++ b/src/cli/runner.ts @@ -224,7 +224,7 @@ async function dispatch(argv: string[], runtime: CliRuntime) { return; } - if (area === "report" && (action === "validate" || action === "render")) { + if (area === "report" && (action === "validate" || action === "render" || action === "export")) { await (await import("./commands/report.js")).handleLocalReportCommand(action, args); return; } diff --git a/src/domains/seal/reports/browser.ts b/src/domains/seal/reports/browser.ts index 5d07905..fd2f447 100644 --- a/src/domains/seal/reports/browser.ts +++ b/src/domains/seal/reports/browser.ts @@ -1,6 +1,6 @@ import { spawn } from "node:child_process" -import { accessSync, constants, existsSync, readdirSync, readFileSync, statSync, writeFileSync } from "node:fs" -import { homedir } from "node:os" +import { accessSync, constants, existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs" +import { homedir, tmpdir } from "node:os" import { dirname, join } from "node:path" import { pathToFileURL } from "node:url" import { CliError, validationError } from "../../../core/errors.js" @@ -54,11 +54,11 @@ export function findReportChrome(explicit?: string): string { return path } -function chrome(binary: string, profile: string, args: string[]): Promise { +function chrome(binary: string, profile: string, args: string[], scaleFactor = 1): Promise { return new Promise((resolve, reject) => { const child = spawn(binary, [ "--headless", "--disable-gpu", "--hide-scrollbars", `--user-data-dir=${profile}`, - "--no-first-run", "--no-default-browser-check", "--force-device-scale-factor=1", + "--no-first-run", "--no-default-browser-check", `--force-device-scale-factor=${scaleFactor}`, "--run-all-compositor-stages-before-draw", ...args ], { stdio: ["ignore", "pipe", "pipe"] }) let title = "", tail = "", diagnostic = "", settled = false @@ -136,3 +136,38 @@ export async function renderBrowserArtifacts(html: string, formats: string[], wi if (!existsSync(`${stem}.pdf`) || statSync(`${stem}.pdf`).size === 0) throw new CliError("浏览器未生成 PDF 文件。", 1) } } + +/** 渲染独立 HTML/SVG 图表为高清晰度 PNG 图片 Buffer(默认 4x 超高分屏/印刷级采样)。 */ +export async function renderHtmlToImageBuffer(options: { + html: string; + width: number; + height: number; + scale?: number; + chrome?: string; +}): Promise { + const binary = findReportChrome(options.chrome) + const stage = mkdtempSync(join(tmpdir(), "seal-chart-render-")) + const profile = join(stage, "profile") + mkdirSync(profile, { mode: 0o700 }) + const htmlFile = join(stage, "index.html") + const pngFile = join(stage, "output.png") + writeFileSync(htmlFile, options.html, "utf8") + try { + await chrome( + binary, + profile, + [ + `--screenshot=${pngFile}`, + `--window-size=${options.width},${options.height}`, + "--virtual-time-budget=10000", + pathToFileURL(htmlFile).href + ], + options.scale ?? 4 + ) + if (!existsSync(pngFile)) throw new CliError("Chrome 截图渲染失败,未产出图片文件。", 1) + return readFileSync(pngFile) + } finally { + rmSync(stage, { recursive: true, force: true }) + } +} + diff --git a/src/domains/seal/reports/charts/venn.test.ts b/src/domains/seal/reports/charts/venn.test.ts index 258a8e8..6c98f6a 100644 --- a/src/domains/seal/reports/charts/venn.test.ts +++ b/src/domains/seal/reports/charts/venn.test.ts @@ -1,5 +1,9 @@ import { describe, expect, test } from "bun:test"; -import { renderVennAccuracySvg } from "./venn.js"; +import { renderVennAccuracyPng, renderVennAccuracySvg } from "./venn.js"; +import { pngDimensions } from "../png.js"; +import { writeFileSync, unlinkSync } from "node:fs"; +import { join } from "node:path"; +import { tmpdir } from "node:os"; describe("renderVennAccuracySvg", () => { test("generates valid SVG with correct computed differences and labels", () => { @@ -14,13 +18,13 @@ describe("renderVennAccuracySvg", () => { expect(svg).toContain("92.08%"); expect(svg).toContain("83.33%"); expect(svg).toContain("75.42%"); - // aiOnly = 92.08 - 75.42 = 16.66% or 16.67% expect(svg).toContain("16.66%"); - // humanOnly = 83.33 - 75.42 = 7.91% expect(svg).toContain("7.91%"); - expect(svg).toContain("AI审核准确"); + expect(svg).toContain("审核准确"); expect(svg).toContain("人工审核准确"); - expect(svg).toContain("AI与人工都准确"); + expect(svg).toContain("与人工都准确"); + expect(svg).toContain('clipPath id="left-circle-clip"'); + expect(svg).toContain('fill="#9ed4eb"'); }); test("supports customized labels and dimensions", () => { @@ -44,3 +48,27 @@ describe("renderVennAccuracySvg", () => { expect(svg).toContain("10.00%"); }); }); + +describe("renderVennAccuracyPng", () => { + test("generates high-DPI 4x PNG buffer matching 3840x1600 resolution", async () => { + const buffer = await renderVennAccuracyPng({ + aiAccuracy: 92.08, + humanAccuracy: 83.33, + bothAccurate: 75.42, + scale: 4 + }); + + expect(buffer).toBeDefined(); + expect(buffer.length).toBeGreaterThan(10_000); + + const tmpFile = join(tmpdir(), `test-venn-${Date.now()}.png`); + try { + writeFileSync(tmpFile, buffer); + const dims = pngDimensions(tmpFile); + expect(dims.width).toBe(3840); + expect(dims.height).toBe(1600); + } finally { + try { unlinkSync(tmpFile); } catch {} + } + }, 15000); +}); diff --git a/src/domains/seal/reports/charts/venn.ts b/src/domains/seal/reports/charts/venn.ts index 9c2c980..e1cfbff 100644 --- a/src/domains/seal/reports/charts/venn.ts +++ b/src/domains/seal/reports/charts/venn.ts @@ -1,3 +1,5 @@ +import { renderHtmlToImageBuffer } from "../browser.js"; + export interface VennAccuracyOptions { aiAccuracy: number; humanAccuracy: number; @@ -9,6 +11,20 @@ export interface VennAccuracyOptions { height?: number; } +export interface VennPngOptions extends VennAccuracyOptions { + /** 渲染清晰度倍率:默认 4x 超高分屏/印刷级采样 (3840×1600),兼顾 4K 屏点对点与极端放大清晰度 */ + scale?: number; + chrome?: string; +} + +function formatLabelWithAiKerning(label: string, aiSpacing = "1.5px", restSpacing = "0px"): string { + if (label.startsWith("AI")) { + const rest = label.slice(2); + return `AI${rest ? `${rest}` : ""}`; + } + return restSpacing !== "0px" ? `${label}` : label; +} + /** * 自动生成 AI 与人工审核准确率对比的精美矢量维恩交集图 (SVG)。 * 100% 纯代码矢量计算,无位图缩放模糊,离线自包含,杜绝外部 OSS 图床与水印。 @@ -21,46 +37,84 @@ export function renderVennAccuracySvg(options: VennAccuracyOptions): string { aiLabel = "AI审核准确", humanLabel = "人工审核准确", bothLabel = "AI与人工都准确", - width = 920, + width = 960, height = 400 } = options; const aiOnly = Math.max(0, Number((aiAccuracy - bothAccurate).toFixed(2))); const humanOnly = Math.max(0, Number((humanAccuracy - bothAccurate).toFixed(2))); - const fmt = (v: number) => `${v.toFixed(2)}%`; - return ` - + return ` + + + + + + - - + - - + + - - ${fmt(aiOnly)} + + - - - ${aiLabel} - (总准确率${fmt(aiAccuracy)}) + + - - ${fmt(bothAccurate)} + + + ${formatLabelWithAiKerning(aiLabel, "1.5px")} + (总准确率${fmt(aiAccuracy)}) + + + - - - ${bothLabel} + + ${fmt(aiOnly)} - - ${fmt(humanOnly)} + + ${fmt(bothAccurate)} - - - ${humanLabel} - (总准确率${fmt(humanAccuracy)}) + + ${fmt(humanOnly)} + + + + + + + ${humanLabel} + (总准确率${fmt(humanAccuracy)}) + + + + + + + ${formatLabelWithAiKerning(bothLabel, "2px", "1px")} `; } + +/** + * 采用本地 Headless Chrome 原生渲染管线输出高清晰度维恩图 PNG 图片。 + * 默认 4x 超高分采样 (3840×1600),完美匹配 24 寸 4K 屏与高精度 PDF 导出。 + */ +export async function renderVennAccuracyPng(options: VennPngOptions): Promise { + const svg = renderVennAccuracySvg(options); + const width = options.width ?? 960; + const height = options.height ?? 400; + const scale = options.scale ?? 4; + const html = `${svg}`; + + return renderHtmlToImageBuffer({ + html, + width, + height, + scale, + chrome: options.chrome + }); +} diff --git a/src/domains/seal/reports/files.test.ts b/src/domains/seal/reports/files.test.ts index c0017da..2abd9fc 100644 --- a/src/domains/seal/reports/files.test.ts +++ b/src/domains/seal/reports/files.test.ts @@ -94,7 +94,7 @@ describe("bundled report templates", () => { writeFileSync(file, "existing"); expect(() => saveReportMarkdown(BUILTIN_MONTHLY_TEMPLATE, BUILTIN_TEMPLATE_PATH, file)).toThrow("--overwrite"); expect(readFileSync(file, "utf8")).toBe("existing"); - expect(existsSync(join(dir, "report.assets"))).toBe(false); + expect(existsSync(join(dir, "report.md.assets"))).toBe(false); }); }); @@ -185,4 +185,20 @@ describe("local report CLI", () => { expect(result.artifacts.map((artifact) => artifact.format)).toEqual(["html", "png"]); expect(existsSync(out + ".png")).toBe(true); }); + + test("export packages Markdown, .md.assets, self-contained HTML, and PDF into a single directory", async () => { + const dir = workspace(); + writeFileSync(join(dir, "chart.svg"), 'chart'); + const file = localReport(dir, validReport + "\n![chart](chart.svg)\n"); + const packageDir = join(dir, "my-report-bundle"); + const result = await runCli(["report", "export", file, "--out", packageDir, "--format", "html"]); + expect(result.exitCode).toBe(0); + const parsed = JSON.parse(result.stdout); + expect(parsed.packageDir).toBe(packageDir); + expect(existsSync(join(packageDir, "报告.md"))).toBe(true); + expect(existsSync(join(packageDir, "报告.md.assets"))).toBe(true); + expect(existsSync(join(packageDir, "报告.md.assets", "1-chart.svg"))).toBe(true); + expect(existsSync(join(packageDir, "报告.html"))).toBe(true); + }); }); + diff --git a/src/domains/seal/reports/files.ts b/src/domains/seal/reports/files.ts index c8e00a0..17d7624 100644 --- a/src/domains/seal/reports/files.ts +++ b/src/domains/seal/reports/files.ts @@ -31,7 +31,7 @@ function checkOutput(path: string, overwrite = false) { /** Export the Markdown and its local images together, without changing a custom template's source assets. */ export function saveReportMarkdown(content: string, templatePath: string, output: string, overwrite = false) { const file = resolve(output); - const assetDir = `${basename(file, extname(file))}.assets`; + const assetDir = `${basename(file)}.assets`; const files = new Map(); const images = new Map(); const savedContent = content.replace(/(!\[[^\]]*\]\()([^)\n]+)(\))/g, (match, before: string, source: string, after: string) => { @@ -103,3 +103,46 @@ export async function renderReportFile(file: string, options: ReportRenderOption rmSync(stage, { recursive: true, force: true }) } } + +export type ReportPackageOptions = { + out: string; + format?: string; + width?: number; + chrome?: string; + overwrite?: boolean; +}; + +/** + * 将报告整包导出至独立目录中(单层文件夹收拢,零散落)。 + * 目录内包含: + * - .md 及 .md.assets/ (含全部 4x 超高清原图) + * - .html (自包含单文件) + * - .pdf (打印级 PDF) + */ +export async function exportReportPackage(file: string, options: ReportPackageOptions) { + const sourcePath = inputFile(file); + const targetDir = resolve(options.out); + const stem = basename(sourcePath, extname(sourcePath)); + mkdirSync(targetDir, { recursive: true }); + + const targetMd = join(targetDir, `${stem}.md`); + const content = readFileSync(sourcePath, "utf8"); + const saved = saveReportMarkdown(content, sourcePath, targetMd, options.overwrite); + + const renderResult = await renderReportFile(saved.file, { + out: join(targetDir, stem), + format: options.format ?? "all", + width: options.width, + chrome: options.chrome, + overwrite: options.overwrite + }); + + return { + packageDir: targetDir, + markdown: saved.file, + assets: saved.assets, + validation: renderResult.validation, + artifacts: renderResult.artifacts + }; +} + diff --git a/src/domains/seal/reports/templates/assets/图1-准确率对比.svg b/src/domains/seal/reports/templates/assets/图1-准确率对比.svg index 0a1e632..3f170da 100644 --- a/src/domains/seal/reports/templates/assets/图1-准确率对比.svg +++ b/src/domains/seal/reports/templates/assets/图1-准确率对比.svg @@ -1,32 +1,51 @@ - - + + + + + + + - - + - - + + - - 16.67% + + - - - AI审核准确 - (总准确率92.08%) + + - - 75.42% + + + AI审核准确 + (总准确率92.08%) + + + - - - AI与人工都准确 + + 16.66% - - 7.92% + + 75.42% - - - 人工审核准确 - (总准确率83.33%) + + 7.91% + + + + + + + 人工审核准确 + (总准确率83.33%) + + + + + + + AI与人工都准确