dsh-ppt 0.33.0 → 0.35.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (33) hide show
  1. package/CHANGELOG.md +42 -0
  2. package/README.en.md +8 -10
  3. package/README.md +8 -10
  4. package/docs/USAGE.en.md +44 -35
  5. package/docs/USAGE.md +45 -36
  6. package/docs/VALIDATION.md +8 -0
  7. package/lib/client.js +116 -17
  8. package/lib/ecosystem.js +10 -0
  9. package/lib/execution.js +36 -5
  10. package/lib/tools.js +74 -4
  11. package/lib/types.d.ts +79 -1
  12. package/lib/workbench.js +255 -14
  13. package/package.json +2 -2
  14. package/skills/dsh-ppt/SKILL.md +34 -31
  15. package/skills/dsh-ppt/package.json +1 -1
  16. package/skills/dsh-ppt/references/office-pack.md +124 -0
  17. package/skills/dsh-ppt/references/research-plan.md +93 -62
  18. package/skills/dsh-ppt/scripts/build-deck.mjs +109 -3
  19. package/skills/dsh-ppt/scripts/deck-absorb.mjs +21 -0
  20. package/skills/dsh-ppt/scripts/deck-advanced.mjs +330 -37
  21. package/skills/dsh-ppt/scripts/deck-brand-kit.mjs +257 -0
  22. package/skills/dsh-ppt/scripts/deck-charts-exec.mjs +805 -0
  23. package/skills/dsh-ppt/scripts/deck-chrome.mjs +47 -1
  24. package/skills/dsh-ppt/scripts/deck-compose.mjs +386 -0
  25. package/skills/dsh-ppt/scripts/deck-core.mjs +136 -16
  26. package/skills/dsh-ppt/scripts/deck-delivery.mjs +750 -17
  27. package/skills/dsh-ppt/scripts/deck-evidence.mjs +811 -118
  28. package/skills/dsh-ppt/scripts/deck-export.mjs +652 -0
  29. package/skills/dsh-ppt/scripts/deck-i18n.mjs +170 -0
  30. package/skills/dsh-ppt/scripts/deck-layouts.mjs +72 -8
  31. package/skills/dsh-ppt/scripts/deck-media.mjs +22 -0
  32. package/skills/dsh-ppt/scripts/deck-office.mjs +1455 -14
  33. package/skills/dsh-ppt/scripts/deck-remix.mjs +471 -0
@@ -17,11 +17,13 @@
17
17
  * 经智能导演 + smartLayout 生成 5–20 页高品味演示文稿。
18
18
  */
19
19
 
20
- import { lstatSync, readFileSync } from 'node:fs'
20
+ import { lstatSync, mkdirSync, readdirSync, readFileSync, writeFileSync } from 'node:fs'
21
21
  import { createRequire } from 'node:module'
22
- import { basename, extname, posix, resolve } from 'node:path'
23
- import { inflateRawSync } from 'node:zlib'
22
+ import { basename, extname, join, posix, resolve } from 'node:path'
23
+ import { inflateRawSync, inflateSync } from 'node:zlib'
24
24
  import { promoteMarkdownSlides, inferThemeFromContent } from './deck-director.mjs'
25
+ import { buildHybridEnrichmentPlan, mergeHybridEvidence } from './deck-evidence.mjs'
26
+ import { loadWorkspaceBrandKit } from './deck-brand-kit.mjs'
25
27
 
26
28
  const MAX_OFFICE_BYTES = 32 * 1024 * 1024
27
29
  const MAX_ENTRY_BYTES = 32 * 1024 * 1024
@@ -208,8 +210,8 @@ function readOfficeInput(options = {}) {
208
210
  extname(sourceName).slice(1) ||
209
211
  extname(resolvedPath).slice(1)
210
212
  ).toLowerCase().trim()
211
- if (!['xlsx', 'csv', 'tsv', 'docx'].includes(rawExt)) {
212
- fail('仅支持导入 .xlsx、.csv、.tsv 或 .docx 文件,当前格式:' + (rawExt || '未知'))
213
+ if (!['xlsx', 'csv', 'tsv', 'docx', 'pdf'].includes(rawExt)) {
214
+ fail('仅支持导入 .xlsx、.csv、.tsv、.docx 或 .pdf 文件,当前格式:' + (rawExt || '未知'))
213
215
  }
214
216
 
215
217
  return {
@@ -1030,6 +1032,7 @@ function profileTabularWorkbook(sheets, fileName, en) {
1030
1032
  title: baseTitle,
1031
1033
  language: en ? 'en' : 'zh',
1032
1034
  slides,
1035
+ _sheets: sheets,
1033
1036
  stats: {
1034
1037
  sourceFormat: extname(fileName).slice(1).toLowerCase() || 'xlsx',
1035
1038
  sheetCount: sheets.length,
@@ -1432,6 +1435,8 @@ function parseDocxArchive(bytes, fileName) {
1432
1435
  title,
1433
1436
  language: en ? 'en' : 'zh',
1434
1437
  slides: promoted,
1438
+ _rawSections: sections,
1439
+ _embeddedMedia: [...mediaDataUris.values()],
1435
1440
  stats: {
1436
1441
  sourceFormat: 'docx',
1437
1442
  sectionCount: sections.length,
@@ -1444,27 +1449,1321 @@ function parseDocxArchive(bytes, fileName) {
1444
1449
  }
1445
1450
 
1446
1451
  // ---------------------------------------------------------------------------
1447
- // Public API: extractOfficeSource & importOfficeDeck
1452
+ // Zero-dep Pure-Node .pdf Text & Section Extractor (FlateDecode + BT/ET + UTF-16BE)
1453
+ // ---------------------------------------------------------------------------
1454
+
1455
+ function decodeUtf16BeBytes(bytes) {
1456
+ let out = ''
1457
+ for (let i = 0; i + 1 < bytes.length; i += 2) {
1458
+ out += String.fromCharCode((bytes[i] << 8) | bytes[i + 1])
1459
+ }
1460
+ return out
1461
+ }
1462
+
1463
+ function decodePdfLiteralString(raw) {
1464
+ const bytes = []
1465
+ for (let i = 0; i < raw.length; i += 1) {
1466
+ const ch = raw[i]
1467
+ if (ch === '\\' && i + 1 < raw.length) {
1468
+ const next = raw[i + 1]
1469
+ if (next === 'n') { bytes.push(0x0a); i += 1 }
1470
+ else if (next === 'r') { bytes.push(0x0d); i += 1 }
1471
+ else if (next === 't') { bytes.push(0x09); i += 1 }
1472
+ else if (next === 'b') { bytes.push(0x08); i += 1 }
1473
+ else if (next === 'f') { bytes.push(0x0c); i += 1 }
1474
+ else if (next === '\r' || next === '\n') {
1475
+ i += 1
1476
+ if (next === '\r' && raw[i + 1] === '\n') i += 1
1477
+ } else if (next >= '0' && next <= '7') {
1478
+ let oct = next
1479
+ if (raw[i + 2] >= '0' && raw[i + 2] <= '7') {
1480
+ oct += raw[i + 2]
1481
+ if (raw[i + 3] >= '0' && raw[i + 3] <= '7') oct += raw[i + 3]
1482
+ }
1483
+ bytes.push(Number.parseInt(oct, 8) & 0xff)
1484
+ i += oct.length
1485
+ } else {
1486
+ bytes.push(next.charCodeAt(0) & 0xff)
1487
+ i += 1
1488
+ }
1489
+ } else {
1490
+ bytes.push(ch.charCodeAt(0) & 0xff)
1491
+ }
1492
+ }
1493
+ if (bytes.length >= 2 && bytes[0] === 0xfe && bytes[1] === 0xff) {
1494
+ return decodeUtf16BeBytes(bytes.slice(2))
1495
+ }
1496
+ const buf = Buffer.from(bytes)
1497
+ const utf8 = buf.toString('utf8')
1498
+ return utf8.includes('\uFFFD') ? buf.toString('latin1') : utf8
1499
+ }
1500
+
1501
+ function decodePdfHexString(hexRaw, cmap) {
1502
+ const cleanHex = String(hexRaw ?? '').replace(/[^0-9A-Fa-f]/g, '')
1503
+ if (!cleanHex) return ''
1504
+ const padded = cleanHex.length % 2 === 1 ? cleanHex + '0' : cleanHex
1505
+ const bytes = []
1506
+ for (let i = 0; i < padded.length; i += 2) {
1507
+ bytes.push(Number.parseInt(padded.slice(i, i + 2), 16))
1508
+ }
1509
+ if (bytes.length >= 2 && bytes[0] === 0xfe && bytes[1] === 0xff) {
1510
+ return decodeUtf16BeBytes(bytes.slice(2))
1511
+ }
1512
+ if (cmap && cmap.size > 0) {
1513
+ let mapped = ''
1514
+ let hits = 0
1515
+ if (padded.length % 4 === 0) {
1516
+ for (let i = 0; i < padded.length; i += 4) {
1517
+ const key = padded.slice(i, i + 4).toUpperCase()
1518
+ if (cmap.has(key)) { mapped += cmap.get(key); hits += 1 }
1519
+ }
1520
+ if (hits > 0) return mapped
1521
+ }
1522
+ for (let i = 0; i < padded.length; i += 2) {
1523
+ const key = padded.slice(i, i + 2).toUpperCase()
1524
+ if (cmap.has(key)) { mapped += cmap.get(key); hits += 1 }
1525
+ }
1526
+ if (hits > 0) return mapped
1527
+ }
1528
+ if (bytes.length >= 2 && bytes.length % 2 === 0 && bytes.some((b, idx) => idx % 2 === 0 && b >= 0x4e && b <= 0x9f)) {
1529
+ return decodeUtf16BeBytes(bytes)
1530
+ }
1531
+ const buf = Buffer.from(bytes)
1532
+ const utf8 = buf.toString('utf8')
1533
+ return utf8.includes('\uFFFD') ? buf.toString('latin1') : utf8
1534
+ }
1535
+
1536
+ function parseToUnicodeCmap(text, cmap) {
1537
+ for (const m of text.matchAll(/beginbfchar([\s\S]*?)endbfchar/g)) {
1538
+ for (const pair of m[1].matchAll(/<([0-9A-Fa-f]+)>\s*<([0-9A-Fa-f]+)>/g)) {
1539
+ const src = pair[1].toUpperCase()
1540
+ const dst = decodePdfHexString('FEFF' + pair[2], null)
1541
+ if (dst) cmap.set(src, dst)
1542
+ }
1543
+ }
1544
+ for (const m of text.matchAll(/beginbfrange([\s\S]*?)endbfrange/g)) {
1545
+ for (const rng of m[1].matchAll(/<([0-9A-Fa-f]+)>\s*<([0-9A-Fa-f]+)>\s*<([0-9A-Fa-f]+)>/g)) {
1546
+ const start = Number.parseInt(rng[1], 16)
1547
+ const end = Number.parseInt(rng[2], 16)
1548
+ const dstStart = Number.parseInt(rng[3], 16)
1549
+ const width = rng[1].length
1550
+ if (Number.isFinite(start) && Number.isFinite(end) && end >= start && end - start <= 256) {
1551
+ for (let code = start; code <= end; code += 1) {
1552
+ const key = code.toString(16).toUpperCase().padStart(width, '0')
1553
+ cmap.set(key, String.fromCodePoint(dstStart + (code - start)))
1554
+ }
1555
+ }
1556
+ }
1557
+ }
1558
+ }
1559
+
1560
+ function extractLinesFromPdfContent(contentStr, cmap) {
1561
+ const lines = []
1562
+ let current = ''
1563
+ const flush = () => {
1564
+ const cleaned = current.replace(/[\u0000-\u0008\u000B\u000C\u000E-\u001F]+/g, ' ').replace(/\s+/g, ' ').trim()
1565
+ if (cleaned.length >= 2) lines.push(cleaned)
1566
+ current = ''
1567
+ }
1568
+
1569
+ const btBlocks = [...contentStr.matchAll(/BT\b([\s\S]*?)\bET\b/g)].map(m => m[1])
1570
+ const targets = btBlocks.length > 0 ? btBlocks : [contentStr]
1571
+
1572
+ for (const block of targets) {
1573
+ let i = 0
1574
+ while (i < block.length) {
1575
+ const ch = block[i]
1576
+ if (ch === '(') {
1577
+ // Parse balanced literal string
1578
+ let depth = 1
1579
+ let start = i + 1
1580
+ i += 1
1581
+ while (i < block.length && depth > 0) {
1582
+ if (block[i] === '\\') { i += 2; continue }
1583
+ if (block[i] === '(') depth += 1
1584
+ else if (block[i] === ')') depth -= 1
1585
+ i += 1
1586
+ }
1587
+ const literal = block.slice(start, i - 1)
1588
+ const after = block.slice(i, i + 12)
1589
+ if (/^\s*(?:Tj|'|")/.test(after)) {
1590
+ current += decodePdfLiteralString(literal)
1591
+ if (/^\s*(?:'|")/.test(after)) flush()
1592
+ }
1593
+ } else if (ch === '<' && block[i + 1] !== '<') {
1594
+ const end = block.indexOf('>', i + 1)
1595
+ if (end > i) {
1596
+ const hex = block.slice(i + 1, end)
1597
+ const after = block.slice(end + 1, end + 12)
1598
+ if (/^\s*(?:Tj|'|")/.test(after)) {
1599
+ current += decodePdfHexString(hex, cmap)
1600
+ }
1601
+ i = end + 1
1602
+ continue
1603
+ }
1604
+ i += 1
1605
+ } else if (ch === '[') {
1606
+ // Parse TJ array
1607
+ let j = i + 1
1608
+ let chunk = ''
1609
+ while (j < block.length && block[j] !== ']') {
1610
+ if (block[j] === '(') {
1611
+ let depth = 1
1612
+ const sStart = j + 1
1613
+ j += 1
1614
+ while (j < block.length && depth > 0) {
1615
+ if (block[j] === '\\') { j += 2; continue }
1616
+ if (block[j] === '(') depth += 1
1617
+ else if (block[j] === ')') depth -= 1
1618
+ j += 1
1619
+ }
1620
+ chunk += decodePdfLiteralString(block.slice(sStart, j - 1))
1621
+ } else if (block[j] === '<' && block[j + 1] !== '<') {
1622
+ const hEnd = block.indexOf('>', j + 1)
1623
+ if (hEnd > j) {
1624
+ chunk += decodePdfHexString(block.slice(j + 1, hEnd), cmap)
1625
+ j = hEnd + 1
1626
+ } else j += 1
1627
+ } else if (block[j] === '-' || (block[j] >= '0' && block[j] <= '9')) {
1628
+ const numMatch = /^-?\d+(?:\.\d+)?/.exec(block.slice(j))
1629
+ if (numMatch) {
1630
+ if (Number(numMatch[0]) <= -180 && chunk && !chunk.endsWith(' ')) chunk += ' '
1631
+ j += numMatch[0].length
1632
+ } else j += 1
1633
+ } else {
1634
+ j += 1
1635
+ }
1636
+ }
1637
+ const after = block.slice(j + 1, j + 10)
1638
+ if (/^\s*TJ\b/.test(after)) {
1639
+ current += chunk
1640
+ }
1641
+ i = j + 1
1642
+ } else {
1643
+ // Detect line-break operators T*, Td, TD, Tm
1644
+ if ((ch === 'T' && (block[i + 1] === '*' || block[i + 1] === 'd' || block[i + 1] === 'D' || block[i + 1] === 'm'))
1645
+ && (i === 0 || /\s/.test(block[i - 1]))
1646
+ && (i + 2 >= block.length || /\s/.test(block[i + 2]))) {
1647
+ if (current.trim()) flush()
1648
+ i += 2
1649
+ continue
1650
+ }
1651
+ i += 1
1652
+ }
1653
+ }
1654
+ flush()
1655
+ }
1656
+ return lines
1657
+ }
1658
+
1659
+ export function extractPdfText(bytes) {
1660
+ const buf = Buffer.isBuffer(bytes) ? bytes : Buffer.from(bytes)
1661
+ const head = buf.subarray(0, Math.min(1024, buf.length)).toString('latin1')
1662
+ if (!head.includes('%PDF-')) {
1663
+ fail('无效的 PDF 文件头(缺少 %PDF- 标识)', 'Invalid PDF header')
1664
+ }
1665
+ const latin = buf.toString('latin1')
1666
+ if (/\/Encrypt\b/.test(latin)) {
1667
+ fail('当前 PDF 已加密,暂不支持直接解析加密 PDF,请先解除密码保护后重试', 'Encrypted PDF is not supported')
1668
+ }
1669
+
1670
+ let docTitle = ''
1671
+ const titleLit = /\/Title\s*\(([^()]{1,240})\)/.exec(latin)
1672
+ const titleHex = /\/Title\s*<([0-9A-Fa-f]{4,480})>/.exec(latin)
1673
+ if (titleLit) docTitle = cleanLine(decodePdfLiteralString(titleLit[1]))
1674
+ else if (titleHex) docTitle = cleanLine(decodePdfHexString(titleHex[1], null))
1675
+
1676
+ const decodedStreams = []
1677
+ const cmap = new Map()
1678
+ const streamToken = Buffer.from('stream')
1679
+ const endstreamToken = Buffer.from('endstream')
1680
+
1681
+ let pos = 0
1682
+ while (pos < buf.length) {
1683
+ const sIdx = buf.indexOf(streamToken, pos)
1684
+ if (sIdx < 0) break
1685
+ // Ensure "stream" is followed by \r\n or \n (not "endstream")
1686
+ const prevByte = sIdx > 0 ? buf[sIdx - 1] : 0x20
1687
+ if (prevByte === 0x64 /* 'd' in endstream */) {
1688
+ pos = sIdx + 6
1689
+ continue
1690
+ }
1691
+ let dataStart = sIdx + 6
1692
+ if (buf[dataStart] === 0x0d && buf[dataStart + 1] === 0x0a) dataStart += 2
1693
+ else if (buf[dataStart] === 0x0a) dataStart += 1
1694
+ else { pos = sIdx + 6; continue }
1695
+
1696
+ const eIdx = buf.indexOf(endstreamToken, dataStart)
1697
+ if (eIdx < 0) break
1698
+ let dataEnd = eIdx
1699
+ while (dataEnd > dataStart && (buf[dataEnd - 1] === 0x0a || buf[dataEnd - 1] === 0x0d)) dataEnd -= 1
1700
+
1701
+ const dictWindow = buf.subarray(Math.max(0, sIdx - 420), sIdx).toString('latin1')
1702
+ const isImage = /\/Subtype\s*\/Image\b/.test(dictWindow)
1703
+ const isFlate = /\/FlateDecode\b/.test(dictWindow)
1704
+ if (!isImage && dataEnd > dataStart && dataEnd - dataStart <= MAX_ENTRY_BYTES) {
1705
+ const rawSlice = buf.subarray(dataStart, dataEnd)
1706
+ let outBuf = rawSlice
1707
+ if (isFlate) {
1708
+ try {
1709
+ outBuf = inflateSync(rawSlice, { maxOutputLength: MAX_ENTRY_BYTES })
1710
+ } catch {
1711
+ try {
1712
+ outBuf = inflateRawSync(rawSlice, { maxOutputLength: MAX_ENTRY_BYTES })
1713
+ } catch {
1714
+ outBuf = null
1715
+ }
1716
+ }
1717
+ }
1718
+ if (outBuf && outBuf.length > 0) {
1719
+ const textStr = outBuf.toString('latin1')
1720
+ if (textStr.includes('beginbfchar') || textStr.includes('beginbfrange')) {
1721
+ parseToUnicodeCmap(textStr, cmap)
1722
+ } else if (textStr.includes('BT') || textStr.includes('Tj') || textStr.includes('TJ')) {
1723
+ decodedStreams.push(textStr)
1724
+ }
1725
+ }
1726
+ }
1727
+ pos = eIdx + 9
1728
+ }
1729
+
1730
+ const allLines = []
1731
+ for (const s of decodedStreams) {
1732
+ allLines.push(...extractLinesFromPdfContent(s, cmap))
1733
+ }
1734
+ // Deduplicate adjacent identical lines while preserving reading order
1735
+ const deduped = []
1736
+ for (const line of allLines) {
1737
+ if (!line || (deduped.length > 0 && deduped[deduped.length - 1] === line)) continue
1738
+ deduped.push(line)
1739
+ }
1740
+
1741
+ return {
1742
+ title: docTitle,
1743
+ lines: deduped,
1744
+ streamCount: decodedStreams.length,
1745
+ }
1746
+ }
1747
+
1748
+ function isLikelyPdfHeading(line, prevBlankOrStart) {
1749
+ const s = cleanLine(line)
1750
+ if (s.length < 3 || s.length > 52) return false
1751
+ if (/[。!?.!?;;]$/.test(s)) return false
1752
+ if (/^(?:[一二三四五六七八九十]+[、..]|第[一二三四五六七八九十\d]+[章节部分]|\d+(?:\.\d+)?[\s、..]|Chapter\s+\d+|Section\s+\d+|Part\s+\d+)/i.test(s)) {
1753
+ return true
1754
+ }
1755
+ if (prevBlankOrStart && s.length <= 32 && !/[,,::]/.test(s)) return true
1756
+ return false
1757
+ }
1758
+
1759
+ function parsePdfDocument(bytes, fileName, langHint) {
1760
+ const { title: metaTitle, lines } = extractPdfText(bytes)
1761
+ if (lines.length === 0) {
1762
+ fail('未在 PDF 中检测到可提取文本(可能为纯扫描图片 PDF,请先 OCR 转换为文本或 Word/Markdown 后再导入)', 'No extractable text found in PDF (likely scanned image PDF)')
1763
+ }
1764
+
1765
+ const sample = [metaTitle, ...lines.slice(0, 30)].join(' ')
1766
+ const en = langHint ? langHint === 'en' : (sample.match(/[\u3400-\u9fff]/g) || []).length < 4
1767
+ const fallbackTitle = cleanLine(fileName.replace(/\.[^.]+$/, '')) || (en ? 'PDF Presentation' : 'PDF 报告汇报')
1768
+ const firstLine = lines[0] || ''
1769
+ const title = (metaTitle && metaTitle.length >= 2 && metaTitle.length <= 80)
1770
+ ? metaTitle
1771
+ : (firstLine.length >= 4 && firstLine.length <= 56 && !/[。!?.!?]$/.test(firstLine) ? firstLine : fallbackTitle)
1772
+
1773
+ const bodyLines = title === firstLine ? lines.slice(1) : lines
1774
+ const sections = []
1775
+ let current = null
1776
+
1777
+ for (let i = 0; i < bodyLines.length; i += 1) {
1778
+ const line = bodyLines[i]
1779
+ if (isLikelyPdfHeading(line, i === 0 || (current && current.bullets.length >= 4))) {
1780
+ if (current && current.bullets.length > 0) sections.push(current)
1781
+ current = { title: line, bullets: [] }
1782
+ } else {
1783
+ if (!current) {
1784
+ current = { title: en ? 'Executive Highlights' : '核心要点提炼', bullets: [] }
1785
+ }
1786
+ current.bullets.push(line)
1787
+ if (current.bullets.length >= 6 && i + 1 < bodyLines.length) {
1788
+ sections.push(current)
1789
+ current = null
1790
+ }
1791
+ }
1792
+ }
1793
+ if (current && current.bullets.length > 0) sections.push(current)
1794
+
1795
+ const slides = []
1796
+ slides.push({
1797
+ layout: 'cover',
1798
+ kicker: en ? 'PDF BRIEFING' : 'PDF 报告拆解',
1799
+ title,
1800
+ subtitle: en
1801
+ ? `Synthesized from ${fileName} (${sections.length} key sections)`
1802
+ : `自动提取自 ${fileName}(共提炼 ${sections.length} 组核心章节)`,
1803
+ })
1804
+
1805
+ if (sections.length >= 3) {
1806
+ slides.push({
1807
+ layout: 'agenda',
1808
+ kicker: en ? 'AGENDA' : '内容结构',
1809
+ title: en ? 'Report Structure & Key Findings' : '文档核心章节与脉络总览',
1810
+ items: sections.slice(0, 6).map((sec, idx) => ({
1811
+ tag: String(idx + 1).padStart(2, '0'),
1812
+ title: sec.title.slice(0, 40),
1813
+ text: sec.bullets[0] ? sec.bullets[0].slice(0, 56) : '',
1814
+ })),
1815
+ })
1816
+ }
1817
+
1818
+ for (let idx = 0; idx < sections.length && slides.length < 18; idx += 1) {
1819
+ const sec = sections[idx]
1820
+ slides.push({
1821
+ layout: 'bullets',
1822
+ kicker: String(idx + 1).padStart(2, '0'),
1823
+ title: sec.title,
1824
+ bullets: sec.bullets.slice(0, 5),
1825
+ source: fileName,
1826
+ })
1827
+ }
1828
+
1829
+ slides.push({
1830
+ layout: 'closing',
1831
+ variant: 'cta-cards',
1832
+ kicker: en ? 'SUMMARY' : '核心结论与行动',
1833
+ title: en ? 'Key conclusions and recommended next actions' : '核心结论复盘与下一步推进计划',
1834
+ subtitle: en ? `Source PDF: ${fileName}` : `原始 PDF 文档:${fileName}`,
1835
+ items: sections.slice(0, 3).map((s, idx) => ({
1836
+ tag: `0${idx + 1}`,
1837
+ title: s.title.slice(0, 36),
1838
+ text: s.bullets[0] ? s.bullets[0].slice(0, 56) : '',
1839
+ })),
1840
+ })
1841
+
1842
+ const promoted = promoteMarkdownSlides(slides, { explicitSmartLayout: true })
1843
+ return {
1844
+ title,
1845
+ language: en ? 'en' : 'zh',
1846
+ slides: promoted,
1847
+ _rawSections: sections,
1848
+ stats: {
1849
+ sourceFormat: 'pdf',
1850
+ lineCount: lines.length,
1851
+ sectionCount: sections.length,
1852
+ slideCount: promoted.length,
1853
+ },
1854
+ }
1855
+ }
1856
+
1857
+ // ---------------------------------------------------------------------------
1858
+ // Zero-dep Local Image Inspector (PNG / JPEG / WebP header parser + Smart Photo Role)
1859
+ // ---------------------------------------------------------------------------
1860
+
1861
+ const PORTRAIT_HINT_RE = /(?:team|founder|ceo|cto|people|person|portrait|avatar|staff|speaker|headshot|团队|合影|人像|人物|头像|嘉宾|讲师|员工|领导)/i
1862
+ const COVER_HINT_RE = /(?:cover|hero|banner|keynote|title|overview|封面|主图|全景|头图|开场)/i
1863
+ const MOBILE_HINT_RE = /(?:mobile|phone|ios|android|app|wechat|miniapp|手机|移动端|小程序|竖屏)/i
1864
+ const BROWSER_HINT_RE = /(?:ui|screen|screenshot|dashboard|web|browser|demo|console|admin|portal|界面|截图|看板|系统|后台|工作台|网页|演示)/i
1865
+
1866
+ function parseImageDimensions(bytes) {
1867
+ if (!bytes || bytes.length < 16) return null
1868
+ // PNG: IHDR width/height at offsets 16..23
1869
+ if (bytes[0] === 0x89 && bytes[1] === 0x50 && bytes[2] === 0x4e && bytes[3] === 0x47 && bytes.length >= 24) {
1870
+ return { mime: 'image/png', width: bytes.readUInt32BE(16), height: bytes.readUInt32BE(20) }
1871
+ }
1872
+ // JPEG: scan SOF0/1/2/3/5/6/7/9/10/11/13/14/15 markers
1873
+ if (bytes[0] === 0xff && bytes[1] === 0xd8) {
1874
+ let offset = 2
1875
+ while (offset + 4 < bytes.length) {
1876
+ if (bytes[offset] !== 0xff) break
1877
+ while (offset < bytes.length && bytes[offset] === 0xff) offset += 1
1878
+ const marker = bytes[offset]
1879
+ offset += 1
1880
+ if (marker === 0xd9 || marker === 0xda) break
1881
+ if (marker === 0x01 || (marker >= 0xd0 && marker <= 0xd7)) continue
1882
+ if (offset + 2 > bytes.length) break
1883
+ const len = bytes.readUInt16BE(offset)
1884
+ if (len < 2 || offset + len > bytes.length) break
1885
+ if ([0xc0, 0xc1, 0xc2, 0xc3, 0xc5, 0xc6, 0xc7, 0xc9, 0xca, 0xcb, 0xcd, 0xce, 0xcf].includes(marker) && len >= 7) {
1886
+ return { mime: 'image/jpeg', height: bytes.readUInt16BE(offset + 3), width: bytes.readUInt16BE(offset + 5) }
1887
+ }
1888
+ offset += len
1889
+ }
1890
+ return { mime: 'image/jpeg', width: 0, height: 0 }
1891
+ }
1892
+ // WebP: VP8 / VP8L / VP8X
1893
+ if (bytes.length >= 30 && bytes.toString('ascii', 0, 4) === 'RIFF' && bytes.toString('ascii', 8, 12) === 'WEBP') {
1894
+ const chunk = bytes.toString('ascii', 12, 16)
1895
+ if (chunk === 'VP8 ') {
1896
+ return { mime: 'image/webp', width: bytes.readUInt16LE(26) & 0x3fff, height: bytes.readUInt16LE(28) & 0x3fff }
1897
+ }
1898
+ if (chunk === 'VP8L') {
1899
+ const bits = bytes.readUInt32LE(21)
1900
+ return { mime: 'image/webp', width: (bits & 0x3fff) + 1, height: ((bits >> 14) & 0x3fff) + 1 }
1901
+ }
1902
+ if (chunk === 'VP8X') {
1903
+ const w = 1 + (bytes[24] | (bytes[25] << 8) | (bytes[26] << 16))
1904
+ const h = 1 + (bytes[27] | (bytes[28] << 8) | (bytes[29] << 16))
1905
+ return { mime: 'image/webp', width: w, height: h }
1906
+ }
1907
+ }
1908
+ return null
1909
+ }
1910
+
1911
+ export function inspectImageBytes(bytes, fileName = 'image.png') {
1912
+ const buf = Buffer.isBuffer(bytes) ? bytes : Buffer.from(bytes)
1913
+ const dims = parseImageDimensions(buf)
1914
+ const width = dims?.width || 0
1915
+ const height = dims?.height || 0
1916
+ const aspectRatio = width > 0 && height > 0 ? Math.round((width / height) * 100) / 100 : 1
1917
+ const orientation = width > 0 && height > 0
1918
+ ? (aspectRatio >= 1.15 ? 'landscape' : (aspectRatio <= 0.85 ? 'portrait' : 'square'))
1919
+ : 'unknown'
1920
+ const baseName = cleanLine(fileName.replace(/\.[^.]+$/, ''))
1921
+ const isPortraitSubject = orientation === 'portrait' || PORTRAIT_HINT_RE.test(baseName)
1922
+ const recommendedFocalPoint = isPortraitSubject ? 'top' : 'center'
1923
+
1924
+ let recommendedRole = 'section'
1925
+ let recommendedLayout = 'image-right'
1926
+ if (COVER_HINT_RE.test(baseName) && orientation !== 'portrait') {
1927
+ recommendedRole = 'cover'
1928
+ recommendedLayout = 'cover'
1929
+ } else if (MOBILE_HINT_RE.test(baseName) || (orientation === 'portrait' && aspectRatio <= 0.68)) {
1930
+ recommendedRole = 'mockup-mobile'
1931
+ recommendedLayout = 'mockup[mobile]'
1932
+ } else if (BROWSER_HINT_RE.test(baseName)) {
1933
+ recommendedRole = 'mockup-browser'
1934
+ recommendedLayout = 'mockup[browser]'
1935
+ } else if (orientation === 'landscape' && width >= 1200 && height >= 650) {
1936
+ recommendedRole = 'section'
1937
+ recommendedLayout = 'image-right'
1938
+ }
1939
+
1940
+ return {
1941
+ fileName,
1942
+ label: baseName || fileName,
1943
+ mime: dims?.mime || detectImageMime(buf) || 'image/png',
1944
+ sizeBytes: buf.length,
1945
+ width,
1946
+ height,
1947
+ aspectRatio,
1948
+ orientation,
1949
+ recommendedRole,
1950
+ recommendedLayout,
1951
+ recommendedFocalPoint,
1952
+ }
1953
+ }
1954
+
1955
+ export function inspectLocalImage(filePath, cwd = '.') {
1956
+ const full = resolve(String(cwd || '.'), String(filePath || '').trim())
1957
+ const stat = lstatSync(full)
1958
+ if (!stat.isFile() || stat.isSymbolicLink() || stat.size > MAX_IMAGE_BYTES) {
1959
+ fail('图片需为 5 MiB 内的普通文件:' + full)
1960
+ }
1961
+ const bytes = readFileSync(full)
1962
+ return {
1963
+ path: full,
1964
+ ...inspectImageBytes(bytes, basename(full)),
1965
+ }
1966
+ }
1967
+
1968
+ // ---------------------------------------------------------------------------
1969
+ // Natural-Language Instructions Parser & Smart Filter Helpers
1970
+ // ---------------------------------------------------------------------------
1971
+
1972
+ function parseUserInstructions(rawInstructions = '') {
1973
+ const text = cleanLine(rawInstructions)
1974
+ if (!text) return { raw: '', targetSlides: null, skipAgenda: false, focusTerms: [], coverHints: [], mockupHints: [] }
1975
+
1976
+ const slideMatch = /(?:约|大概|控制[在为]?|一共|总共|做|生成)?\s*(\d{1,2})\s*(?:页|张|slides?|pages?)/i.exec(text)
1977
+ const parsedCount = slideMatch ? Number(slideMatch[1]) : null
1978
+ const targetSlides = Number.isInteger(parsedCount) && parsedCount >= 3 && parsedCount <= 40 ? parsedCount : null
1979
+ const skipAgenda = /不要目录|跳过目录|无需目录|no\s+agenda|skip\s+agenda/i.test(text)
1980
+
1981
+ const coverHints = []
1982
+ const mockupHints = []
1983
+ for (const m of text.matchAll(/([A-Za-z0-9_\u4e00-\u9fa5-]+\.(?:png|jpe?g|webp))\s*(?:放|做|当|作为|用于|in|as|on)?\s*(封面|cover|主图|hero|样机|mockup|手机|浏览器|截图)/gi)) {
1984
+ const fn = m[1].toLowerCase()
1985
+ if (/封面|cover|主图|hero/i.test(m[2])) coverHints.push(fn)
1986
+ else mockupHints.push(fn)
1987
+ }
1988
+
1989
+ const focusTerms = text
1990
+ .replace(/[,。;:、,.!!??()()【】[\]「」"'`]/g, ' ')
1991
+ .split(/\s+/)
1992
+ .map(t => t.trim())
1993
+ .filter(t => t.length >= 2 && !/^(?:帮我|请把|生成|制作|一个|一份|按照|要求|控制|左右|不要|跳过|封面|目录|ppt|deck|slides?|pages?|with|from|the|and|for)$/i.test(t))
1994
+ .slice(0, 14)
1995
+
1996
+ return { raw: text, targetSlides, skipAgenda, focusTerms, coverHints, mockupHints }
1997
+ }
1998
+
1999
+ function filterSheetsByInclude(sheets, includeSheets) {
2000
+ if (!Array.isArray(includeSheets) || includeSheets.length === 0) return sheets
2001
+ const needles = includeSheets.map(s => String(s ?? '').trim().toLowerCase()).filter(Boolean)
2002
+ if (needles.length === 0) return sheets
2003
+ const filtered = sheets.filter(sh => {
2004
+ const name = String(sh.name || '').toLowerCase()
2005
+ return needles.some(n => name === n || name.includes(n))
2006
+ })
2007
+ return filtered.length > 0 ? filtered : sheets
2008
+ }
2009
+
2010
+ function applyMaxSlidesBudget(slides, maxSlides, focusTerms = []) {
2011
+ if (!Number.isInteger(maxSlides) || maxSlides < 3 || slides.length <= maxSlides) return slides
2012
+ const first = slides[0]
2013
+ const last = slides[slides.length - 1]
2014
+ const hasCover = first?.layout === 'cover'
2015
+ const hasClosing = last?.layout === 'closing'
2016
+ const middle = slides.slice(hasCover ? 1 : 0, hasClosing ? -1 : undefined)
2017
+ const keepBudget = Math.max(1, maxSlides - (hasCover ? 1 : 0) - (hasClosing ? 1 : 0))
2018
+ if (middle.length <= keepBudget) return slides
2019
+
2020
+ const scored = middle.map((slide, origIdx) => {
2021
+ const hay = [slide.kicker, slide.title, slide.subtitle, slide.takeaway, ...(slide.bullets || [])].filter(Boolean).join(' ').toLowerCase()
2022
+ let score = 0
2023
+ if (slide.layout === 'kpi') score += 5
2024
+ if (slide.layout === 'chart-split' || slide.layout === 'sankey' || slide.layout === 'gantt' || slide.layout === 'marimekko') score += 4
2025
+ if (slide.layout === 'mockup' || slide.layout === 'image-right' || slide.layout === 'image-left') score += 3.5
2026
+ if (slide.layout === 'table' && /附录|Appendix|明细/i.test(`${slide.kicker || ''} ${slide.title || ''}`)) score -= 2.5
2027
+ if (slide.layout === 'agenda') score -= 1.5
2028
+ for (const term of focusTerms) {
2029
+ if (hay.includes(term.toLowerCase())) score += 3
2030
+ }
2031
+ return { slide, origIdx, score }
2032
+ })
2033
+
2034
+ const chosen = [...scored]
2035
+ .sort((a, b) => b.score - a.score || a.origIdx - b.origIdx)
2036
+ .slice(0, keepBudget)
2037
+ .sort((a, b) => a.origIdx - b.origIdx)
2038
+ .map(x => x.slide)
2039
+
2040
+ return [
2041
+ ...(hasCover ? [first] : []),
2042
+ ...chosen,
2043
+ ...(hasClosing ? [last] : []),
2044
+ ]
2045
+ }
2046
+
2047
+ // ---------------------------------------------------------------------------
2048
+ // Live Excel-to-dataModel Binder (bindDataModel: true)
2049
+ // ---------------------------------------------------------------------------
2050
+
2051
+ function buildAutoDataModelFromSheets(sheetEntries = []) {
2052
+ if (!Array.isArray(sheetEntries) || sheetEntries.length === 0) return null
2053
+ const sources = []
2054
+ const metrics = []
2055
+ const bindingsBySheet = new Map()
2056
+
2057
+ for (let sIdx = 0; sIdx < sheetEntries.length && sources.length < 6; sIdx += 1) {
2058
+ const entry = sheetEntries[sIdx]
2059
+ const rows = entry?.rows
2060
+ if (!Array.isArray(rows) || rows.length < 2) continue
2061
+ const headers = rows[0].slice(0, 12)
2062
+ const dataRows = rows.slice(1, 30)
2063
+ const cols = profileColumns([headers, ...dataRows])
2064
+ const numCols = cols.filter(c => c.isNumeric)
2065
+ if (numCols.length === 0) continue
2066
+
2067
+ const sourceId = `sheet${sources.length + 1}`
2068
+ const cleanRows = [
2069
+ headers.map(h => cleanLine(h) || 'Col'),
2070
+ ...dataRows.map(r => headers.map((_, ci) => {
2071
+ const p = parseCellNumber(r[ci])
2072
+ if (cols[ci]?.isNumeric && p.ok) {
2073
+ return p.isPercent ? `${p.num}%` : p.num
2074
+ }
2075
+ return cleanLine(r[ci] ?? '')
2076
+ })),
2077
+ ]
2078
+ sources.push({
2079
+ id: sourceId,
2080
+ name: cleanLine(entry.name || sourceId).slice(0, 100),
2081
+ kind: 'table',
2082
+ rows: cleanRows,
2083
+ })
2084
+
2085
+ const primaryCol = numCols[0]
2086
+ const colLetter = String.fromCharCode(65 + primaryCol.index)
2087
+ const catCol = cols.find(c => !c.isNumeric) || cols[0]
2088
+ const boundCells = []
2089
+ for (let rIdx = 0; rIdx < dataRows.length && metrics.length < 48; rIdx += 1) {
2090
+ const p = primaryCol.parsed[rIdx]
2091
+ if (!p?.ok) continue
2092
+ const cellAddr = `${colLetter}${rIdx + 2}`
2093
+ const metricId = `${sourceId}r${rIdx + 2}c${primaryCol.index + 1}`
2094
+ const rowLabel = cleanLine(dataRows[rIdx][catCol.index] || `Row${rIdx + 1}`)
2095
+ metrics.push({
2096
+ id: metricId,
2097
+ label: `${entry.name} · ${rowLabel} (${primaryCol.header})`.slice(0, 110),
2098
+ kind: 'source',
2099
+ source: { sourceId, cell: cellAddr },
2100
+ format: {
2101
+ style: primaryCol.isPercentCol ? 'percent' : 'number',
2102
+ digits: primaryCol.isPercentCol ? 1 : (Number.isInteger(p.num) ? 0 : 1),
2103
+ ...(!primaryCol.isPercentCol && primaryCol.unit ? { unit: primaryCol.unit.slice(0, 20) } : {}),
2104
+ },
2105
+ })
2106
+ boundCells.push({ rowIndex: rIdx, metricId, value: p.num, label: rowLabel })
2107
+ }
2108
+ if (boundCells.length > 0) {
2109
+ bindingsBySheet.set(entry.name, { sourceId, primaryCol, boundCells })
2110
+ }
2111
+ }
2112
+
2113
+ if (sources.length === 0 || metrics.length === 0) return null
2114
+ return {
2115
+ dataModel: { schemaVersion: 1, sources, metrics },
2116
+ bindingsBySheet,
2117
+ }
2118
+ }
2119
+
2120
+ function bindSlidesWithAutoDataModel(slides, autoBound) {
2121
+ if (!autoBound || !autoBound.bindingsBySheet?.size) return slides
2122
+ const usedMetrics = new Set()
2123
+ return slides.map((slide) => {
2124
+ // Bind first matching chart-split single-series primary values to {{metricId}}
2125
+ if ((slide.layout === 'chart-split' || slide.layout === 'chart') && slide.chart && Array.isArray(slide.chart.series) && slide.chart.series.length > 0) {
2126
+ const binding = autoBound.bindingsBySheet.get(slide.kicker)
2127
+ if (binding && slide.chart.kind !== 'waterfall') {
2128
+ const s0 = slide.chart.series[0]
2129
+ if (Array.isArray(s0.values) && s0.values.length === binding.boundCells.length) {
2130
+ const nextSeries = slide.chart.series.map((ser, idx) => {
2131
+ if (idx !== 0) return ser
2132
+ return {
2133
+ ...ser,
2134
+ values: binding.boundCells.map((bc) => {
2135
+ usedMetrics.add(bc.metricId)
2136
+ return `{{${bc.metricId}}}`
2137
+ }),
2138
+ }
2139
+ })
2140
+ return { ...slide, chart: { ...slide.chart, series: nextSeries } }
2141
+ }
2142
+ }
2143
+ }
2144
+ // Bind peak KPI item on Executive Summary KPI slide when available
2145
+ if (slide.layout === 'kpi' && Array.isArray(slide.items) && slide.items.length > 0) {
2146
+ const nextItems = slide.items.map((it) => {
2147
+ for (const [sheetName, binding] of autoBound.bindingsBySheet.entries()) {
2148
+ if (String(it.title || it.tag || '').includes(sheetName) && binding.boundCells.length > 0) {
2149
+ const peak = binding.boundCells.reduce((b, c) => (c.value > b.value ? c : b), binding.boundCells[0])
2150
+ usedMetrics.add(peak.metricId)
2151
+ const { unit: _dropUnit, ...restItem } = it
2152
+ return {
2153
+ ...restItem,
2154
+ value: `{{${peak.metricId}}}`,
2155
+ }
2156
+ }
2157
+ }
2158
+ return it
2159
+ })
2160
+ return { ...slide, items: nextItems }
2161
+ }
2162
+ return slide
2163
+ })
2164
+ }
2165
+
2166
+ // ---------------------------------------------------------------------------
2167
+ // Multi-Source Pack Ingestion (Directory or Mixed filePaths[] -> 1 Deck + Evidence Ledger)
1448
2168
  // ---------------------------------------------------------------------------
1449
2169
 
2170
+ const PACK_DOC_EXTS = new Set(['.docx', '.pdf'])
2171
+ const PACK_DATA_EXTS = new Set(['.xlsx', '.csv', '.tsv'])
2172
+ const PACK_IMG_EXTS = new Set(['.png', '.jpg', '.jpeg', '.webp'])
2173
+ const MAX_PACK_FILES = 12
2174
+
2175
+ function packFilePriority(filePath) {
2176
+ const ext = extname(filePath).toLowerCase()
2177
+ if (PACK_DOC_EXTS.has(ext)) return 0
2178
+ if (PACK_DATA_EXTS.has(ext)) return 1
2179
+ if (PACK_IMG_EXTS.has(ext)) return 2
2180
+ return 9
2181
+ }
2182
+
2183
+ function readImageAsDataUri(resolvedFile) {
2184
+ const stat = lstatSync(resolvedFile)
2185
+ if (!stat.isFile() || stat.isSymbolicLink() || stat.size > MAX_IMAGE_BYTES) return null
2186
+ const ext = extname(resolvedFile).toLowerCase()
2187
+ const mime = ext === '.png' ? 'image/png' : ext === '.webp' ? 'image/webp' : 'image/jpeg'
2188
+ const buf = readFileSync(resolvedFile)
2189
+ return `data:${mime};base64,${buf.toString('base64')}`
2190
+ }
2191
+
2192
+ function collectPackFiles(rawFilePaths, cwd, signal) {
2193
+ const resolvedFiles = []
2194
+ for (const fp of rawFilePaths) {
2195
+ abort(signal)
2196
+ const full = resolve(cwd, String(fp ?? '').trim())
2197
+ let st
2198
+ try { st = lstatSync(full) } catch { fail('找不到素材路径:' + full, 'Source path not found: ' + full) }
2199
+ if (st.isSymbolicLink()) continue
2200
+ if (st.isDirectory()) {
2201
+ const names = readdirSync(full).filter(n => !n.startsWith('.')).sort((a, b) => a.localeCompare(b))
2202
+ for (const n of names) {
2203
+ const child = join(full, n)
2204
+ try {
2205
+ const cst = lstatSync(child)
2206
+ if (!cst.isFile() || cst.isSymbolicLink()) continue
2207
+ const ext = extname(child).toLowerCase()
2208
+ if (PACK_DOC_EXTS.has(ext) || PACK_DATA_EXTS.has(ext) || PACK_IMG_EXTS.has(ext)) {
2209
+ resolvedFiles.push(child)
2210
+ }
2211
+ } catch { /* ignore unreadable child */ }
2212
+ }
2213
+ } else if (st.isFile()) {
2214
+ const ext = extname(full).toLowerCase()
2215
+ if (PACK_DOC_EXTS.has(ext) || PACK_DATA_EXTS.has(ext) || PACK_IMG_EXTS.has(ext)) {
2216
+ resolvedFiles.push(full)
2217
+ } else {
2218
+ fail('多源融合暂不支持该文件格式:' + basename(full))
2219
+ }
2220
+ }
2221
+ }
2222
+ const uniqueFiles = [...new Set(resolvedFiles)]
2223
+ .sort((a, b) => packFilePriority(a) - packFilePriority(b) || basename(a).localeCompare(basename(b)))
2224
+ .slice(0, MAX_PACK_FILES)
2225
+ if (uniqueFiles.length === 0) {
2226
+ fail('目录中未找到可导入的素材文件(支持 .xlsx / .csv / .tsv / .docx / .pdf / .png / .jpg / .webp)', 'No supported source files found')
2227
+ }
2228
+ return uniqueFiles
2229
+ }
2230
+
2231
+ function resolvePhotoRole(photoMeta, explicitRoles = {}, parsedInstr = null) {
2232
+ const fnameLower = photoMeta.fileName.toLowerCase()
2233
+ const stemLower = photoMeta.label.toLowerCase()
2234
+ for (const [k, v] of Object.entries(explicitRoles || {})) {
2235
+ const kl = String(k).toLowerCase()
2236
+ if (kl === fnameLower || kl === stemLower || fnameLower.includes(kl)) {
2237
+ const role = String(v || '').trim().toLowerCase()
2238
+ if (['cover', 'mockup', 'mockup-mobile', 'mockup-browser', 'gallery', 'full-bleed', 'section'].includes(role)) {
2239
+ return role
2240
+ }
2241
+ }
2242
+ }
2243
+ if (parsedInstr?.coverHints?.some(h => h === fnameLower || fnameLower.includes(h))) return 'cover'
2244
+ if (parsedInstr?.mockupHints?.some(h => h === fnameLower || fnameLower.includes(h))) {
2245
+ return photoMeta.orientation === 'portrait' ? 'mockup-mobile' : 'mockup-browser'
2246
+ }
2247
+ return photoMeta.recommendedRole
2248
+ }
2249
+
1450
2250
  /**
1451
- * Extract structured slides & metadata from `.xlsx`, `.csv`, `.tsv`, or `.docx`.
1452
- * Zero external new dependencies (uses Node zlib inflateRawSync + lazy csv-parse).
2251
+ * 精炼素材包体检模式(`inspectOnly: true`):
2252
+ * 零耗 Token 防爆:只输出结构化摘要(Excel 统计极值+推荐图型+前5行预览、Word/PDF 章节摘要+表格维度+内嵌图尺寸、
2253
+ * 照片像素/比例/防裁歪建议、本地 `[E1..Ek]` 证据台账,以及 Mode C 外部权威检索补充计划),供 AI 按用户要求精准编排 PPT。
1453
2254
  */
1454
- export async function extractOfficeSource(options = {}) {
2255
+ export async function inspectOfficePack(options = {}) {
2256
+ abort(options.signal)
2257
+ const cwd = resolve(String(options.cwd ?? '.'))
2258
+ const rawList = Array.isArray(options.filePaths) && options.filePaths.length > 0
2259
+ ? options.filePaths
2260
+ : [options.filePath ?? options.path].filter(Boolean)
2261
+ if (rawList.length === 0) {
2262
+ fail('inspectOfficePack 需提供 filePath 或 filePaths')
2263
+ }
2264
+
2265
+ const uniqueFiles = collectPackFiles(rawList, cwd, options.signal)
2266
+ const todayYm = new Date().toISOString().slice(0, 7)
2267
+ const sources = []
2268
+ const excelSheets = []
2269
+ const docSections = []
2270
+ const photos = []
2271
+ const localEvidence = []
2272
+ let cjkHits = 0
2273
+ let primaryTopic = cleanLine(options.title || '')
2274
+
2275
+ for (let idx = 0; idx < uniqueFiles.length; idx += 1) {
2276
+ abort(options.signal)
2277
+ const file = uniqueFiles[idx]
2278
+ const fname = basename(file)
2279
+ const ext = extname(file).toLowerCase()
2280
+ const stat = lstatSync(file)
2281
+ const evId = `E${idx + 1}`
2282
+
2283
+ sources.push({ fileName: fname, path: file, format: ext.slice(1), sizeBytes: stat.size })
2284
+
2285
+ if (PACK_IMG_EXTS.has(ext)) {
2286
+ const meta = inspectLocalImage(file, cwd)
2287
+ cjkHits += (meta.label.match(/[\u3400-\u9fff]/g) || []).length
2288
+ photos.push({ ...meta, evidenceId: evId })
2289
+ localEvidence.push({
2290
+ id: evId,
2291
+ origin: 'local-file',
2292
+ claim: `本地视觉素材「${meta.label}」(${meta.width}×${meta.height}, ${meta.orientation})`,
2293
+ source: fname,
2294
+ date: todayYm,
2295
+ confidence: 'verified',
2296
+ })
2297
+ continue
2298
+ }
2299
+
2300
+ const single = await extractSingleOfficeFile({ ...options, filePath: file, filePaths: undefined })
2301
+ if (!primaryTopic && single.title) primaryTopic = single.title
2302
+ const sample = [single.title, ...(single.slides || []).slice(0, 4).map(s => s.title || '')].join(' ')
2303
+ cjkHits += (sample.match(/[\u3400-\u9fff]/g) || []).length
2304
+
2305
+ if (PACK_DATA_EXTS.has(ext)) {
2306
+ const rawSheets = single._sheets || []
2307
+ for (const sh of rawSheets) {
2308
+ const headers = sh.rows[0] || []
2309
+ const dataRows = sh.rows.slice(1)
2310
+ const cols = profileColumns(sh.rows)
2311
+ const numCols = cols.filter(c => c.isNumeric)
2312
+ const catCol = cols.find(c => !c.isNumeric) || cols[0]
2313
+ const profiled = buildNumericSheetSlides(sh, options.lang === 'en')
2314
+ const firstSlide = profiled.slides[0]
2315
+ const topMetrics = numCols.slice(0, 3).map(nc => {
2316
+ const vals = nc.parsed.filter(p => p.ok).map(p => p.num)
2317
+ const sum = vals.reduce((a, b) => a + b, 0)
2318
+ const max = vals.length ? Math.max(...vals) : 0
2319
+ const min = vals.length ? Math.min(...vals) : 0
2320
+ const avg = vals.length ? sum / vals.length : 0
2321
+ const maxRowIdx = nc.parsed.findIndex(p => p.ok && p.num === max)
2322
+ return {
2323
+ column: nc.header,
2324
+ unit: nc.unit,
2325
+ isPercent: nc.isPercentCol,
2326
+ sum: Number(sum.toFixed(2)),
2327
+ avg: Number(avg.toFixed(2)),
2328
+ min: Number(min.toFixed(2)),
2329
+ max: Number(max.toFixed(2)),
2330
+ peakCategory: maxRowIdx >= 0 ? (dataRows[maxRowIdx]?.[catCol.index] || '') : '',
2331
+ }
2332
+ })
2333
+ excelSheets.push({
2334
+ sourceFile: fname,
2335
+ evidenceId: evId,
2336
+ sheetName: sh.name,
2337
+ bannerTitle: sh.bannerTitle || '',
2338
+ rowCount: dataRows.length,
2339
+ colCount: headers.length,
2340
+ headers,
2341
+ topMetrics,
2342
+ recommendedLayout: firstSlide?.layout || 'table',
2343
+ recommendedChartKind: firstSlide?.chart?.kind || firstSlide?.layout || 'table',
2344
+ ...(firstSlide?.chart ? { chartSpec: firstSlide.chart } : {}),
2345
+ rowsPreview: sh.rows.slice(0, 6),
2346
+ })
2347
+ }
2348
+ localEvidence.push({
2349
+ id: evId,
2350
+ origin: 'local-file',
2351
+ claim: `${fname} 数据工作簿(${rawSheets.length} 张表,${single.stats?.totalRows ?? 0} 条记录)`,
2352
+ source: fname,
2353
+ date: todayYm,
2354
+ confidence: 'verified',
2355
+ })
2356
+ } else {
2357
+ // .docx or .pdf
2358
+ const rawSecs = single._rawSections || []
2359
+ const embeddedMedia = Array.isArray(single._embeddedMedia) ? single._embeddedMedia : []
2360
+ let cachedImgMap = new Map()
2361
+ if (embeddedMedia.length > 0) {
2362
+ try {
2363
+ const cacheDir = join(cwd, '.dsh-ppt', 'office-media-cache')
2364
+ mkdirSync(cacheDir, { recursive: true })
2365
+ for (let mIdx = 0; mIdx < embeddedMedia.length; mIdx += 1) {
2366
+ const em = embeddedMedia[mIdx]
2367
+ const b64 = String(em.dataUri || '').split(',')[1]
2368
+ if (!b64) continue
2369
+ const buf = Buffer.from(b64, 'base64')
2370
+ const meta = inspectImageBytes(buf, em.name || `docx-img-${mIdx + 1}.png`)
2371
+ const safeName = `${basename(fname, extname(fname)).replace(/[^A-Za-z0-9_-]/g, '_')}-${mIdx + 1}-${basename(em.name || 'img.png').replace(/[^A-Za-z0-9._-]/g, '_')}`
2372
+ const outPath = join(cacheDir, safeName)
2373
+ writeFileSync(outPath, buf)
2374
+ cachedImgMap.set(em.dataUri, { ...meta, path: outPath })
2375
+ }
2376
+ } catch { /* read-only cwd: fall back to metadata only */ }
2377
+ }
2378
+ for (const sec of rawSecs.slice(0, 20)) {
2379
+ const secImages = (sec.images || []).map((im) => {
2380
+ const cached = cachedImgMap.get(im.src)
2381
+ return cached
2382
+ ? { fileName: cached.fileName, path: cached.path, width: cached.width, height: cached.height, orientation: cached.orientation, recommendedFocalPoint: cached.recommendedFocalPoint }
2383
+ : { fileName: im.alt || 'embedded.png' }
2384
+ })
2385
+ docSections.push({
2386
+ sourceFile: fname,
2387
+ evidenceId: evId,
2388
+ heading: sec.title,
2389
+ level: sec.level || 2,
2390
+ bulletCount: sec.bullets?.length || 0,
2391
+ summaryBullets: (sec.bullets || []).slice(0, 4).map(b => cleanLine(b).slice(0, 110)),
2392
+ tableCount: sec.tables?.length || 0,
2393
+ tableDims: (sec.tables || []).map(t => `${t.length}x${t[0]?.length || 0}`),
2394
+ hasMermaid: (sec.mermaids?.length || 0) > 0,
2395
+ hasFormula: (sec.formulas?.length || 0) > 0,
2396
+ ...(secImages.length > 0 ? { embeddedImages: secImages } : {}),
2397
+ })
2398
+ }
2399
+ localEvidence.push({
2400
+ id: evId,
2401
+ origin: 'local-file',
2402
+ claim: cleanLine(`${single.title}(${rawSecs.length} 组章节)`).slice(0, 120),
2403
+ source: fname,
2404
+ date: todayYm,
2405
+ confidence: 'verified',
2406
+ })
2407
+ }
2408
+ }
2409
+
2410
+ const en = options.lang ? options.lang === 'en' : cjkHits < 4
2411
+ const topic = primaryTopic || (en ? 'Material Pack Presentation' : '多源素材汇报')
2412
+ const brandKit = loadWorkspaceBrandKit(cwd)
2413
+
2414
+ const enrichmentPlan = buildHybridEnrichmentPlan({
2415
+ topic,
2416
+ instructions: options.instructions || '',
2417
+ localAssets: { excelSheets, docSections, photos },
2418
+ localEvidence,
2419
+ lang: en ? 'en' : 'zh',
2420
+ preferredSources: brandKit?.preferredSources,
2421
+ blockedDomains: brandKit?.blockedDomains,
2422
+ })
2423
+
2424
+ const mdLines = [
2425
+ `# ${en ? 'Material Pack Dossier' : '本地素材包精炼档案'}:${topic}`,
2426
+ '',
2427
+ `- **${en ? 'Files' : '文件清单'}**:${sources.map(s => `${s.fileName} (${s.format})`).join(' · ')}`,
2428
+ ...(excelSheets.length ? [
2429
+ '',
2430
+ `## ${en ? 'Excel / Tabular Sheets' : '数据表画像'} (${excelSheets.length})`,
2431
+ ...excelSheets.map(sh => `- **${sh.sheetName}** (${sh.rowCount}×${sh.colCount}, [${sh.evidenceId}]) → 推荐 \`${sh.recommendedLayout}\` / \`${sh.recommendedChartKind}\`;核心指标:${sh.topMetrics.map(m => `${m.column} 峰值 ${m.peakCategory}=${m.max}${m.unit}`).join(',') || sh.headers.join('/')}`),
2432
+ ] : []),
2433
+ ...(docSections.length ? [
2434
+ '',
2435
+ `## ${en ? 'Word / PDF Sections' : '文档核心章节'} (${docSections.length})`,
2436
+ ...docSections.slice(0, 12).map(d => `- **${d.heading}** ([${d.evidenceId}], ${d.bulletCount} 条要点${d.tableCount ? `, ${d.tableCount} 表格` : ''}${d.embeddedImages?.length ? `, ${d.embeddedImages.length} 内嵌图` : ''}):${d.summaryBullets[0] || ''}`),
2437
+ ] : []),
2438
+ ...(photos.length ? [
2439
+ '',
2440
+ `## ${en ? 'Photos & Visual Assets' : '本地图片与配图体检'} (${photos.length})`,
2441
+ ...photos.map(p => `- **${p.fileName}** (${p.width}×${p.height} · ${p.orientation}, [${p.evidenceId}]) → 建议角色 \`${p.recommendedRole}\` / 版式 \`${p.recommendedLayout}\` / 焦点 \`focalPoint: "${p.recommendedFocalPoint}"\``),
2442
+ ] : []),
2443
+ '',
2444
+ enrichmentPlan.planMarkdown,
2445
+ ]
2446
+
2447
+ return {
2448
+ ok: true,
2449
+ inspectOnly: true,
2450
+ topic,
2451
+ language: en ? 'en' : 'zh',
2452
+ sources,
2453
+ excelSheets,
2454
+ docSections,
2455
+ photos,
2456
+ localEvidence,
2457
+ enrichmentPlan,
2458
+ dossierMarkdown: mdLines.join('\n'),
2459
+ }
2460
+ }
2461
+
2462
+ async function extractMultiSourcePack(rawFilePaths, options = {}) {
2463
+ const cwd = resolve(String(options.cwd ?? '.'))
2464
+ const uniqueFiles = collectPackFiles(rawFilePaths, cwd, options.signal)
2465
+ const parsedInstr = parseUserInstructions(options.instructions || '')
2466
+ const explicitPhotoRoles = options.photoRoles && typeof options.photoRoles === 'object' ? options.photoRoles : {}
2467
+
2468
+ const todayYm = new Date().toISOString().slice(0, 7)
2469
+ const evidence = []
2470
+ const bodySlides = []
2471
+ const sourceSummaries = []
2472
+ const collectedSheets = []
2473
+ const pendingPhotos = []
2474
+ const formatCounts = { docs: 0, tables: 0, images: 0 }
2475
+ let detectedEn = options.lang === 'en'
2476
+ let cjkHits = 0
2477
+
2478
+ for (let idx = 0; idx < uniqueFiles.length; idx += 1) {
2479
+ abort(options.signal)
2480
+ const file = uniqueFiles[idx]
2481
+ const fname = basename(file)
2482
+ const ext = extname(file).toLowerCase()
2483
+ const evId = `E${idx + 1}`
2484
+
2485
+ if (PACK_IMG_EXTS.has(ext)) {
2486
+ const dataUri = readImageAsDataUri(file)
2487
+ if (!dataUri) continue
2488
+ const meta = inspectLocalImage(file, cwd)
2489
+ const role = resolvePhotoRole(meta, explicitPhotoRoles, parsedInstr)
2490
+ formatCounts.images += 1
2491
+ cjkHits += (meta.label.match(/[\u3400-\u9fff]/g) || []).length
2492
+ evidence.push({
2493
+ id: evId,
2494
+ origin: 'local-file',
2495
+ claim: `视觉素材「${meta.label}」来自本地图片文件`,
2496
+ source: fname,
2497
+ date: todayYm,
2498
+ confidence: 'verified',
2499
+ })
2500
+ pendingPhotos.push({
2501
+ ...meta,
2502
+ role,
2503
+ dataUri,
2504
+ evId,
2505
+ })
2506
+ sourceSummaries.push({ file: fname, title: meta.label, evId })
2507
+ continue
2508
+ }
2509
+
2510
+ const single = await extractSingleOfficeFile({ ...options, filePath: file, filePaths: undefined })
2511
+ if (PACK_DOC_EXTS.has(ext)) formatCounts.docs += 1
2512
+ else {
2513
+ formatCounts.tables += 1
2514
+ if (Array.isArray(single._sheets)) collectedSheets.push(...single._sheets)
2515
+ }
2516
+
2517
+ const innerBody = (single.slides || []).filter(s => !['cover', 'closing', 'agenda'].includes(s.layout))
2518
+ const sampleText = [single.title, ...innerBody.slice(0, 3).map(s => s.title || '')].join(' ')
2519
+ cjkHits += (sampleText.match(/[\u3400-\u9fff]/g) || []).length
2520
+
2521
+ const summaryClaim = cleanLine(
2522
+ `${single.title}${innerBody[0]?.title && innerBody[0].title !== single.title ? ':' + innerBody[0].title : ''}`
2523
+ ).slice(0, 96)
2524
+ evidence.push({
2525
+ id: evId,
2526
+ origin: 'local-file',
2527
+ claim: summaryClaim || `来自 ${fname} 的业务资料`,
2528
+ source: fname,
2529
+ date: todayYm,
2530
+ confidence: 'verified',
2531
+ })
2532
+ sourceSummaries.push({ file: fname, title: single.title || fname, evId })
2533
+
2534
+ for (const s of innerBody) {
2535
+ if (bodySlides.length >= 26) break
2536
+ bodySlides.push({
2537
+ ...s,
2538
+ source: s.source || fname,
2539
+ evidenceIds: [...new Set([...(Array.isArray(s.evidenceIds) ? s.evidenceIds : []), evId])],
2540
+ })
2541
+ }
2542
+ }
2543
+
2544
+ if (!options.lang) detectedEn = cjkHits < 4
2545
+ const en = detectedEn
2546
+
2547
+ // Smart Photo Choreography: Cover Hero / Device Mockup / Section Pair / Multi-Photo Gallery
2548
+ let coverPhoto = null
2549
+ const remainingGallery = []
2550
+
2551
+ for (const ph of pendingPhotos) {
2552
+ if (ph.role === 'cover' && !coverPhoto) {
2553
+ coverPhoto = ph
2554
+ continue
2555
+ }
2556
+ if (ph.role === 'mockup' || ph.role === 'mockup-mobile' || ph.role === 'mockup-browser') {
2557
+ const variant = ph.role === 'mockup-mobile' || (ph.role === 'mockup' && ph.orientation === 'portrait') ? 'mobile' : 'browser'
2558
+ bodySlides.push({
2559
+ layout: 'mockup',
2560
+ variant,
2561
+ kicker: `PRODUCT · ${ph.evId}`,
2562
+ title: en ? `${ph.label}: Live interface showcase` : `${ph.label}:核心产品界面展示`,
2563
+ image: { src: ph.dataUri, alt: ph.label, fit: 'cover', focalPoint: ph.recommendedFocalPoint },
2564
+ bullets: [
2565
+ en ? `Captured from ${ph.fileName} (${ph.width}×${ph.height})` : `原始界面素材:${ph.fileName}(${ph.width}×${ph.height})`,
2566
+ en ? 'Embedded in crisp device frame with focal crop preserved' : '自动匹配设备画框与焦点裁切,确保界面清晰呈现',
2567
+ ],
2568
+ source: ph.fileName,
2569
+ evidenceIds: [ph.evId],
2570
+ })
2571
+ continue
2572
+ }
2573
+ if (ph.role === 'full-bleed') {
2574
+ bodySlides.push({
2575
+ layout: 'image',
2576
+ variant: 'full-bleed',
2577
+ kicker: `VISUAL · ${ph.evId}`,
2578
+ title: ph.label,
2579
+ image: { src: ph.dataUri, alt: ph.label, fit: 'cover', focalPoint: ph.recommendedFocalPoint },
2580
+ source: ph.fileName,
2581
+ evidenceIds: [ph.evId],
2582
+ })
2583
+ continue
2584
+ }
2585
+ if (ph.role === 'gallery') {
2586
+ remainingGallery.push(ph)
2587
+ continue
2588
+ }
2589
+
2590
+ // Try keyword-matching photo to an existing text/bullets slide without chart/image
2591
+ const tokens = ph.label.toLowerCase().split(/[\s_-]+/).filter(t => t.length >= 2)
2592
+ const matchIdx = tokens.length > 0
2593
+ ? bodySlides.findIndex(s =>
2594
+ !s.image && !s.images && !s.chart && ['bullets', 'cards', 'callout'].includes(s.layout) &&
2595
+ tokens.some(tk => `${s.title || ''} ${s.kicker || ''}`.toLowerCase().includes(tk))
2596
+ )
2597
+ : -1
2598
+
2599
+ if (matchIdx >= 0) {
2600
+ const target = bodySlides[matchIdx]
2601
+ const pairedBullets = Array.isArray(target.bullets) && target.bullets.length > 0
2602
+ ? target.bullets.slice(0, 4)
2603
+ : (Array.isArray(target.items) ? target.items.slice(0, 4).map(it => `**${it.title || it.tag || ''}**:${it.text || ''}`) : [])
2604
+ bodySlides[matchIdx] = {
2605
+ ...target,
2606
+ layout: 'image-right',
2607
+ variant: 'framed',
2608
+ bullets: pairedBullets,
2609
+ items: undefined,
2610
+ image: { src: ph.dataUri, alt: ph.label, fit: 'cover', focalPoint: ph.recommendedFocalPoint },
2611
+ evidenceIds: [...new Set([...(target.evidenceIds || []), ph.evId])],
2612
+ }
2613
+ } else {
2614
+ remainingGallery.push(ph)
2615
+ }
2616
+ }
2617
+
2618
+ // Group remaining photos into crisp 2-4 photo gallery slides, or single framed image slide
2619
+ if (remainingGallery.length >= 2) {
2620
+ for (let g = 0; g < remainingGallery.length; g += 4) {
2621
+ const chunk = remainingGallery.slice(g, g + 4)
2622
+ if (chunk.length === 1) {
2623
+ const ph = chunk[0]
2624
+ bodySlides.push({
2625
+ layout: 'image',
2626
+ variant: 'framed',
2627
+ kicker: `VISUAL · ${ph.evId}`,
2628
+ title: ph.label,
2629
+ image: { src: ph.dataUri, alt: ph.label, fit: 'contain', caption: ph.fileName },
2630
+ source: ph.fileName,
2631
+ evidenceIds: [ph.evId],
2632
+ })
2633
+ } else {
2634
+ bodySlides.push({
2635
+ layout: 'image',
2636
+ variant: 'gallery',
2637
+ kicker: en ? 'VISUAL GALLERY' : '现场与视觉图集',
2638
+ title: en ? `Visual Evidence Showcase (${chunk.length} Assets)` : `核心视觉实景图集(共 ${chunk.length} 组素材)`,
2639
+ images: chunk.map(ph => ({
2640
+ src: ph.dataUri,
2641
+ alt: ph.label,
2642
+ fit: 'cover',
2643
+ focalPoint: ph.recommendedFocalPoint,
2644
+ caption: ph.label,
2645
+ })),
2646
+ source: chunk.map(ph => ph.fileName).join(' · '),
2647
+ evidenceIds: chunk.map(ph => ph.evId),
2648
+ })
2649
+ }
2650
+ }
2651
+ } else if (remainingGallery.length === 1) {
2652
+ const ph = remainingGallery[0]
2653
+ bodySlides.push({
2654
+ layout: 'image',
2655
+ variant: 'framed',
2656
+ kicker: `VISUAL · ${ph.evId}`,
2657
+ title: ph.label,
2658
+ image: { src: ph.dataUri, alt: ph.label, fit: 'contain', caption: ph.fileName },
2659
+ source: ph.fileName,
2660
+ evidenceIds: [ph.evId],
2661
+ })
2662
+ }
2663
+
2664
+ const defaultPackTitle = cleanLine(options.title || '')
2665
+ || (options.filePath && lstatSync(resolve(cwd, String(options.filePath))).isDirectory()
2666
+ ? basename(resolve(cwd, String(options.filePath)))
2667
+ : (sourceSummaries[0]?.title || (en ? 'Multi-Source Executive Briefing' : '多源资料融合汇报')))
2668
+
2669
+ const partsDesc = []
2670
+ if (formatCounts.docs > 0) partsDesc.push(en ? `${formatCounts.docs} doc(s)` : `${formatCounts.docs} 份文档/PDF`)
2671
+ if (formatCounts.tables > 0) partsDesc.push(en ? `${formatCounts.tables} table(s)` : `${formatCounts.tables} 份数据表`)
2672
+ if (formatCounts.images > 0) partsDesc.push(en ? `${formatCounts.images} visual(s)` : `${formatCounts.images} 张视觉素材`)
2673
+
2674
+ const coverSlide = {
2675
+ layout: 'cover',
2676
+ kicker: en ? 'MULTI-SOURCE BRIEFING' : '多源素材融合汇报',
2677
+ title: defaultPackTitle,
2678
+ subtitle: en
2679
+ ? `Synthesized from ${uniqueFiles.length} local files (${partsDesc.join(' · ')}) with [E1–E${evidence.length}] provenance`
2680
+ : `融合 ${uniqueFiles.length} 份本地资料(${partsDesc.join(' · ')}),全篇自动绑定 [E1–E${evidence.length}] 溯源台账`,
2681
+ ...(coverPhoto
2682
+ ? {
2683
+ image: {
2684
+ src: coverPhoto.dataUri,
2685
+ alt: coverPhoto.label,
2686
+ fit: 'cover',
2687
+ focalPoint: coverPhoto.recommendedFocalPoint,
2688
+ },
2689
+ evidenceIds: [coverPhoto.evId],
2690
+ }
2691
+ : {}),
2692
+ }
2693
+
2694
+ const mergedSlides = [coverSlide]
2695
+
2696
+ if (sourceSummaries.length >= 2 && !parsedInstr.skipAgenda) {
2697
+ mergedSlides.push({
2698
+ layout: 'agenda',
2699
+ kicker: en ? 'SOURCE PACK' : '资料目录',
2700
+ title: en ? 'Integrated Source Pack & Evidence Index' : '融合资料脉络与证据编号总览',
2701
+ items: sourceSummaries.slice(0, 6).map((item) => ({
2702
+ tag: item.evId,
2703
+ title: item.title.slice(0, 38),
2704
+ text: item.file,
2705
+ })),
2706
+ })
2707
+ }
2708
+
2709
+ mergedSlides.push(...bodySlides)
2710
+ mergedSlides.push({
2711
+ layout: 'closing',
2712
+ variant: 'cta-cards',
2713
+ kicker: en ? 'NEXT STEPS' : '结论与后续推进',
2714
+ title: en ? 'Consolidated Findings & Action Plan' : '跨资料结论汇总与下一步推进计划',
2715
+ subtitle: en ? `${uniqueFiles.length} verified local sources indexed` : `共溯源 ${uniqueFiles.length} 份本地原始资料`,
2716
+ items: sourceSummaries.slice(0, 3).map((s) => ({
2717
+ tag: s.evId,
2718
+ title: s.title.slice(0, 36),
2719
+ text: s.file,
2720
+ })),
2721
+ })
2722
+
2723
+ const effectiveMaxSlides = Number.isInteger(options.maxSlides) ? options.maxSlides : parsedInstr.targetSlides
2724
+ const budgetedSlides = applyMaxSlidesBudget(mergedSlides, effectiveMaxSlides, parsedInstr.focusTerms)
2725
+
2726
+ return {
2727
+ ok: true,
2728
+ importedFrom: uniqueFiles.join(', '),
2729
+ importedFiles: uniqueFiles,
2730
+ title: defaultPackTitle,
2731
+ language: en ? 'en' : 'zh',
2732
+ slides: budgetedSlides,
2733
+ evidence,
2734
+ _sheets: collectedSheets,
2735
+ stats: {
2736
+ sourceFormat: 'multi-source-pack',
2737
+ fileCount: uniqueFiles.length,
2738
+ docCount: formatCounts.docs,
2739
+ tableCount: formatCounts.tables,
2740
+ imageCount: formatCounts.images,
2741
+ evidenceCount: evidence.length,
2742
+ slideCount: budgetedSlides.length,
2743
+ },
2744
+ }
2745
+ }
2746
+
2747
+ async function extractSingleOfficeFile(options = {}) {
1455
2748
  abort(options.signal)
1456
2749
  const input = readOfficeInput(options)
1457
2750
  const enHint = options.lang === 'en'
2751
+ const parsedInstr = parseUserInstructions(options.instructions || '')
1458
2752
 
1459
2753
  if (input.format === 'xlsx') {
1460
- const { sheets } = parseXlsxArchive(input.bytes)
2754
+ const parsed = parseXlsxArchive(input.bytes)
2755
+ const sheets = filterSheetsByInclude(parsed.sheets, options.includeSheets)
1461
2756
  const sample = sheets.flatMap(s => s.rows.slice(0, 5).flat()).join(' ')
1462
2757
  const en = options.lang ? enHint : (sample.match(/[\u3400-\u9fff]/g) || []).length < 4
1463
2758
  const profiled = profileTabularWorkbook(sheets, input.fileName, en)
2759
+ const maxBudget = Number.isInteger(options.maxSlides) ? options.maxSlides : parsedInstr.targetSlides
2760
+ const finalSlides = applyMaxSlidesBudget(profiled.slides, maxBudget, parsedInstr.focusTerms)
1464
2761
  return {
1465
2762
  ok: true,
1466
2763
  importedFrom: input.resolvedPath,
1467
2764
  ...profiled,
2765
+ slides: finalSlides,
2766
+ stats: { ...profiled.stats, slideCount: finalSlides.length },
1468
2767
  }
1469
2768
  }
1470
2769
 
@@ -1474,27 +2773,90 @@ export async function extractOfficeSource(options = {}) {
1474
2773
  const en = options.lang ? enHint : (sample.match(/[\u3400-\u9fff]/g) || []).length < 4
1475
2774
  const sheetTitle = cleanLine(input.fileName.replace(/\.[^.]+$/, '')) || (en ? 'Dataset' : '数据表')
1476
2775
  const profiled = profileTabularWorkbook([{ name: sheetTitle, bannerTitle: '', rows }], input.fileName, en)
2776
+ const maxBudget = Number.isInteger(options.maxSlides) ? options.maxSlides : parsedInstr.targetSlides
2777
+ const finalSlides = applyMaxSlidesBudget(profiled.slides, maxBudget, parsedInstr.focusTerms)
1477
2778
  return {
1478
2779
  ok: true,
1479
2780
  importedFrom: input.resolvedPath,
1480
2781
  ...profiled,
2782
+ slides: finalSlides,
2783
+ stats: { ...profiled.stats, slideCount: finalSlides.length },
2784
+ }
2785
+ }
2786
+
2787
+ if (input.format === 'pdf') {
2788
+ const parsedPdf = parsePdfDocument(input.bytes, input.fileName, options.lang)
2789
+ let slides = parsedPdf.slides
2790
+ if (parsedInstr.skipAgenda) slides = slides.filter(s => s.layout !== 'agenda')
2791
+ const maxBudget = Number.isInteger(options.maxSlides) ? options.maxSlides : parsedInstr.targetSlides
2792
+ slides = applyMaxSlidesBudget(slides, maxBudget, parsedInstr.focusTerms)
2793
+ return {
2794
+ ok: true,
2795
+ importedFrom: input.resolvedPath,
2796
+ ...parsedPdf,
2797
+ slides,
2798
+ stats: { ...parsedPdf.stats, slideCount: slides.length },
1481
2799
  }
1482
2800
  }
1483
2801
 
1484
2802
  const parsedDocx = parseDocxArchive(input.bytes, input.fileName)
2803
+ let slides = parsedDocx.slides
2804
+ if (parsedInstr.skipAgenda) slides = slides.filter(s => s.layout !== 'agenda')
2805
+ const maxBudget = Number.isInteger(options.maxSlides) ? options.maxSlides : parsedInstr.targetSlides
2806
+ slides = applyMaxSlidesBudget(slides, maxBudget, parsedInstr.focusTerms)
1485
2807
  return {
1486
2808
  ok: true,
1487
2809
  importedFrom: input.resolvedPath,
1488
2810
  ...parsedDocx,
2811
+ slides,
2812
+ stats: { ...parsedDocx.stats, slideCount: slides.length },
1489
2813
  }
1490
2814
  }
1491
2815
 
2816
+ // ---------------------------------------------------------------------------
2817
+ // Public API: extractOfficeSource & importOfficeDeck
2818
+ // ---------------------------------------------------------------------------
2819
+
1492
2820
  /**
1493
- * Import an Office document (.xlsx / .csv / .tsv / .docx) directly into a full dsh-ppt deck
1494
- * (HTML slideshow + 100% native editable PPTX + JSON project + optional handout/one-pager).
2821
+ * Extract structured slides & metadata from `.xlsx`, `.csv`, `.tsv`, `.docx`, `.pdf`,
2822
+ * OR a multi-source pack (directory path or `filePaths[]` combining docs + tables + PDF + images).
2823
+ * Pass `inspectOnly: true` to return a compact Material Dossier + Hybrid Authoritative Enrichment Plan without building slides.
2824
+ */
2825
+ export async function extractOfficeSource(options = {}) {
2826
+ abort(options.signal)
2827
+ if (options.inspectOnly === true) {
2828
+ return inspectOfficePack(options)
2829
+ }
2830
+ if (Array.isArray(options.filePaths) && options.filePaths.length > 0) {
2831
+ return extractMultiSourcePack(options.filePaths, options)
2832
+ }
2833
+ const rawPath = String(options.filePath ?? options.path ?? '').trim()
2834
+ if (rawPath && options.bytes === undefined) {
2835
+ const resolved = resolve(String(options.cwd ?? '.'), rawPath)
2836
+ try {
2837
+ const st = lstatSync(resolved)
2838
+ if (st.isDirectory()) {
2839
+ return extractMultiSourcePack([resolved], options)
2840
+ }
2841
+ if (st.isFile() && PACK_IMG_EXTS.has(extname(resolved).toLowerCase())) {
2842
+ return extractMultiSourcePack([resolved], options)
2843
+ }
2844
+ } catch { /* fall through to readOfficeInput error */ }
2845
+ }
2846
+ return extractSingleOfficeFile(options)
2847
+ }
2848
+
2849
+ /**
2850
+ * Import an Office/PDF document or multi-source folder pack directly into a full dsh-ppt deck
2851
+ * (HTML slideshow + 100% native editable PPTX + JSON project + optional live dataModel binding,
2852
+ * hybrid external authoritative evidence merge, and reverse exports).
2853
+ * When `inspectOnly: true`, returns the compact Material Dossier + Mode C Enrichment Plan without writing files.
1495
2854
  */
1496
2855
  export async function importOfficeDeck(options = {}) {
1497
2856
  abort(options.signal)
2857
+ if (options.inspectOnly === true) {
2858
+ return inspectOfficePack(options)
2859
+ }
1498
2860
  const extracted = await extractOfficeSource(options)
1499
2861
  const { buildDeckAsync } = await import('./deck-advanced.mjs')
1500
2862
 
@@ -1507,27 +2869,103 @@ export async function importOfficeDeck(options = {}) {
1507
2869
  : requestedTheme
1508
2870
 
1509
2871
  const baseFileName = options.fileName ||
1510
- cleanLine(basename(extracted.importedFrom || title).replace(/\.[^.]+$/, '')) ||
2872
+ (extracted.stats?.sourceFormat === 'multi-source-pack'
2873
+ ? title
2874
+ : cleanLine(basename(extracted.importedFrom || title).replace(/\.[^.]+$/, ''))) ||
1511
2875
  title
1512
2876
 
1513
2877
  const brand = options.chromeStyle
1514
2878
  ? { ...(options.brand && typeof options.brand === 'object' ? options.brand : {}), chromeStyle: options.chromeStyle }
1515
2879
  : options.brand
1516
2880
 
2881
+ let finalSlides = extracted.slides
2882
+ let autoDataModel
2883
+ if (options.bindDataModel === true && Array.isArray(extracted._sheets) && extracted._sheets.length > 0) {
2884
+ const bound = buildAutoDataModelFromSheets(extracted._sheets)
2885
+ if (bound) {
2886
+ autoDataModel = bound.dataModel
2887
+ finalSlides = bindSlidesWithAutoDataModel(finalSlides, bound)
2888
+ }
2889
+ }
2890
+
2891
+ // Merge local evidence + optional external authoritative web-research evidence with zero ID collisions
2892
+ const localEv = Array.isArray(extracted.evidence) && extracted.evidence.length > 0
2893
+ ? extracted.evidence
2894
+ : (Array.isArray(options.evidence) && options.evidence.length > 0
2895
+ ? [{
2896
+ id: 'E1',
2897
+ origin: 'local-file',
2898
+ claim: cleanLine(`${title} 本地原始资料`),
2899
+ source: basename(extracted.importedFrom || title),
2900
+ date: new Date().toISOString().slice(0, 7),
2901
+ confidence: 'verified',
2902
+ }]
2903
+ : [])
2904
+ let mergedEvidence = localEv
2905
+ let hybridMergeInfo
2906
+ if (Array.isArray(options.evidence) && options.evidence.length > 0) {
2907
+ const cwd = resolve(String(options.cwd ?? '.'))
2908
+ const kit = loadWorkspaceBrandKit(cwd)
2909
+ const merged = mergeHybridEvidence(localEv, options.evidence, {
2910
+ preferredSources: kit?.preferredSources,
2911
+ blockedDomains: kit?.blockedDomains,
2912
+ })
2913
+ mergedEvidence = merged.evidence
2914
+ hybridMergeInfo = {
2915
+ localCount: merged.localCount,
2916
+ externalCount: merged.externalCount,
2917
+ remappedIds: merged.remappedIds,
2918
+ }
2919
+ // Add an authoritative external benchmark synthesis slide if external evidence wasn't already referenced
2920
+ const extOnly = merged.evidence.filter(e => e.origin === 'web-research')
2921
+ if (extOnly.length > 0) {
2922
+ const en = lang === 'en'
2923
+ const closingIdx = finalSlides.findIndex(s => s.layout === 'closing')
2924
+ const extSlide = {
2925
+ layout: 'cards',
2926
+ variant: 'pillars',
2927
+ kicker: en ? 'EXTERNAL BENCHMARKS' : '权威外部基准对标',
2928
+ title: en
2929
+ ? `Authoritative External Context Anchors ${extOnly.length} Key Benchmarks`
2930
+ : `外部权威基准校准核心判断(共引入 ${extOnly.length} 项权威外源)`,
2931
+ items: extOnly.slice(0, 4).map((e) => ({
2932
+ tag: `${e.id}${e.tier ? ` · T${e.tier}` : ''}`,
2933
+ title: cleanLine(e.source).slice(0, 28),
2934
+ text: cleanLine(e.claim).slice(0, 72) + (e.claimType === 'forecast' ? (en ? ' (Forecast)' : '(预计)') : ''),
2935
+ })),
2936
+ evidenceIds: extOnly.map(e => e.id),
2937
+ takeaway: en
2938
+ ? 'Internal metrics are benchmarked against verified external Tier 1/2 sources; full provenance is recorded in the Evidence Appendix.'
2939
+ : '内部数据已与外部权威基准完成双轨对标,完整出处、年份与原文链接详见附录溯源清单。',
2940
+ }
2941
+ if (closingIdx >= 0) {
2942
+ finalSlides = [...finalSlides.slice(0, closingIdx), extSlide, ...finalSlides.slice(closingIdx)]
2943
+ } else {
2944
+ finalSlides = [...finalSlides, extSlide]
2945
+ }
2946
+ }
2947
+ }
2948
+
1517
2949
  const built = await buildDeckAsync({
1518
2950
  title,
1519
- slides: extracted.slides,
2951
+ slides: finalSlides,
1520
2952
  theme: inferred,
1521
2953
  persona,
1522
2954
  lang,
1523
2955
  motion: options.motion,
2956
+ motionProfile: options.motionProfile,
1524
2957
  brand,
2958
+ ...(autoDataModel ? { dataModel: autoDataModel } : {}),
2959
+ ...(Array.isArray(mergedEvidence) && mergedEvidence.length > 0
2960
+ ? { evidence: mergedEvidence, evidenceAppendix: options.evidenceAppendix !== false }
2961
+ : {}),
1525
2962
  outputDir: options.outputDir || options.outDir || '.',
1526
2963
  fileName: baseFileName,
1527
2964
  overwrite: options.overwrite === true,
1528
2965
  smartLayout: false,
1529
2966
  handout: options.handout === true,
1530
2967
  onePager: options.onePager === true,
2968
+ ...(Array.isArray(options.exports) && options.exports.length > 0 ? { exports: options.exports } : {}),
1531
2969
  ...(options.targetMinutes !== undefined ? { targetMinutes: options.targetMinutes } : {}),
1532
2970
  cwd: options.cwd,
1533
2971
  signal: options.signal,
@@ -1536,6 +2974,9 @@ export async function importOfficeDeck(options = {}) {
1536
2974
  return {
1537
2975
  ...built,
1538
2976
  importedFrom: extracted.importedFrom,
2977
+ ...(extracted.importedFiles ? { importedFiles: extracted.importedFiles } : {}),
2978
+ ...(autoDataModel ? { dataModelBound: true, boundMetricCount: autoDataModel.metrics.length } : {}),
2979
+ ...(hybridMergeInfo ? { hybridEvidence: hybridMergeInfo } : {}),
1539
2980
  officeStats: extracted.stats,
1540
2981
  }
1541
2982
  }