dsh-design-studio 0.15.0 → 0.16.1

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.
package/lib/index.js CHANGED
@@ -53,6 +53,7 @@ import { createInspiration } from './inspire.js'
53
53
  import { createLibraryRoutes } from './gallery/routes.js'
54
54
  import { createMarket } from './gallery/market.js'
55
55
  import { createMarketRoutes } from './gallery/market-routes.js'
56
+ import { createPhotos, loadPhotoIndex, searchPhotos, onlyByTheme, isPhotoAsset, orientOf, MAX_PHOTOS } from './photos.js'
56
57
  import { createTracker, parseTarget, findRule, KINDS } from './core.js'
57
58
  import { createDrafts } from './draft.js'
58
59
  import { createHistory } from './history.js'
@@ -63,7 +64,7 @@ import { createBrowser } from './browser.js'
63
64
  import { designOf, fitSize, metaOfFile, sizeOf, pickScreens, measureAll, shootAll, cropIssues, formatMeasure, issueSnapshot, formatShots, whereOf, MAX_SCREENS, MAX_SIZES, MAX_SHOTS, MAX_CROPS } from './look.js'
64
65
  import { SYSTEMS_DIR, extractSystem, listSystems, setDefault, skillSection } from './system.js'
65
66
  import { readTweaks, applyTweaks, lintTweaks } from './tweaks.js'
66
- import { FRAMEWORKS, detectProject, projectFor, defaultFramework, buildHandoff, compareScreens, implUrl, defaultDest, pickedDest, within } from './handoff.js'
67
+ import { FRAMEWORKS, detectProject, projectFor, defaultFramework, buildHandoff, compareScreens, implUrl, defaultDest, pickedDest, within, pinRoots } from './handoff.js'
67
68
 
68
69
  export const name = 'dsh-design-studio'
69
70
  export const inject = ['webServer']
@@ -89,7 +90,7 @@ const SKILL_RANK = 600 // 和 DSH 自带的技能同一档;用户 / 项目里
89
90
  * 几行之间靠这个互通(同一个包里的模块 Node 只加载一次):工作台起来后放 tracker、无头浏览器(browser);
90
91
  * 「自动打开预览」那行开着时 autoOpen > 0
91
92
  */
92
- export const studio = { tracker: null, autoOpen: 0, offline: 0, check: null, browser: null, market: null, log: () => {} }
93
+ export const studio = { tracker: null, autoOpen: 0, offline: 0, check: null, browser: null, market: null, photos: null, sessionCwd: null, log: () => {} }
93
94
 
94
95
  /** 设计技能:模型做界面设计时加载(DSH 的 skill 工具),也能让用户手动调 */
95
96
  export const designSkill = {
@@ -503,6 +504,69 @@ export const handoffTool = {
503
504
  },
504
505
  }
505
506
 
507
+ const ORIENT = { landscape: '横图', portrait: '竖图', square: '方图' }
508
+
509
+ /** find_photos 工具:从自带照片库按描述找图,复制进设计目录(图用本地文件,分享、导出、离线预览都带得走) */
510
+ export const photoTool = {
511
+ name: 'find_photos',
512
+ description:
513
+ '从设计台自带的照片库里按描述找照片,复制进设计目录的 assets/,返回能直接写进 HTML 的相对路径和替代文字。' +
514
+ '民宿酒店、餐饮、奶茶咖啡、健身、美妆、服饰、教育、旅行风景这类靠照片说话的设计,需要头图、封面、商品图时用,别画插画冒充照片。' +
515
+ '库里是 AI 生成的示意图;用户给了自己的照片就用用户的。',
516
+ parameters: specToJsonSchema({
517
+ query: { type: 'string', required: true, description: '要什么样的照片,中文英文都行,带上题材和画面,如「民宿 卧室」「奶茶 手拿」「gym interior」' },
518
+ dir: { type: 'string', description: '这套设计的文件夹(绝对路径或相对会话目录),图放进它的 assets/。不填用正在预览的设计目录' },
519
+ count: { type: 'number', description: `要几张,1–${MAX_PHOTOS},默认 3` },
520
+ ratio: { type: 'string', enum: Object.keys(ORIENT), description: 'landscape 横图、portrait 竖图、square 方图;不够时会补别的比例(用 object-fit: cover 裁)' },
521
+ }),
522
+ output: {
523
+ schema: { type: 'object', additionalProperties: false, properties: { text: { type: 'string' } }, required: ['text'] },
524
+ render: (_args, value) => [{ type: 'text', text: value.text }],
525
+ },
526
+ async execute(args, exec) {
527
+ const id = toolSession(exec, '找照片')
528
+ const a = args || {}
529
+ const photos = studio.photos
530
+ if (!photos) return { text: '这个版本的设计台没带照片库。这次用 CSS / SVG 画,并告诉用户这里需要一张什么样的照片。' }
531
+ const query = typeof a.query === 'string' ? a.query.trim() : ''
532
+ if (!query) return { text: 'query 不能空:写要什么样的照片,如「民宿 卧室」。' }
533
+ const cwd = studio.sessionCwd ? await studio.sessionCwd(id) : studio.tracker.cwdOf(id)
534
+ const t = studio.tracker.stateOf(id).target
535
+ const root = t && t.kind === 'file' ? t.root : ''
536
+ const dir = typeof a.dir === 'string' && a.dir.trim() ? resolvePath(a.dir, cwd) : root
537
+ if (!dir) return { text: '不知道放哪:先建好这套设计的文件夹,把路径写进 dir。' }
538
+ const allowed = pinRoots([cwd, root])
539
+ if (!allowed(dir)) return { text: `${dir} 不在会话目录(${cwd})里,图不能放那儿。放进这套设计自己的文件夹。` }
540
+ const ratio = Object.hasOwn(ORIENT, a.ratio) ? a.ratio : ''
541
+ const search = (used) => searchPhotos(photos.index, { query, ratio, count: a.count, used, seed: dir })
542
+ // 先搜一遍:库里没有就不用下载
543
+ if (!search(new Set()).length) {
544
+ const names = Object.values(photos.index.themes).map((x) => x.label).join('、')
545
+ return { text: `库里没有符合「${query}」的照片。现有题材:${names}。换个说法再找;实在没有就用 CSS / SVG 画,并告诉用户这里需要一张什么样的照片。` }
546
+ }
547
+ try {
548
+ const placed = await photos.provide({ dir, allowed, pick: search })
549
+ const want = Math.min(MAX_PHOTOS, Math.max(1, Math.floor(Number(a.count)) || 3))
550
+ const broad = onlyByTheme(photos.index, { query })
551
+ const few = !broad && placed.length < want ? `具体画面只找到这 ${placed.length} 张;要更多就只写题材再搜一次。\n` : ''
552
+ const list = placed.map(({ p, rel }, i) => `${i + 1}. ${rel}(${ORIENT[orientOf(p.w, p.h)]} ${p.w}×${p.h})alt:${p.alt} / ${p.altEn}`)
553
+ return {
554
+ text:
555
+ `${broad ? `按题材找到 ${placed.length} 张(没有和「${query}」里具体画面对得上的标签,看描述合不合适再用;不合适就用 CSS / SVG 画,并告诉用户这里需要什么样的照片)` : `找到 ${placed.length} 张`},已放进 ${path.join(dir, 'assets')}:\n${list.join('\n')}\n${few}` +
556
+ '这是按关键词找的,先看上面的描述和需求对不对得上,对不上的别用(没用上的图不会进分享包)。\n' +
557
+ '用法:<img src="assets/文件名" alt="…"> 配 object-fit: cover;alt 按界面语言选一个;HTML 不在这个文件夹时改相对路径。\n' +
558
+ '这些是 AI 生成的示意图,不是用户真实的店铺或产品:别写「实拍」,也别把图上的场景当事实写进文案;做完告诉用户上线前换成真实照片。',
559
+ }
560
+ } catch (e) {
561
+ studio.log(e)
562
+ if (e && e.code === 'off') return { text: '「设计库不联网」开着,照片库下载不了。这次用 CSS / SVG 画,并告诉用户:关掉这个开关就能用自带照片。' }
563
+ if (e && e.code === 'link') return { text: `${path.join(dir, 'assets')} 指向了这个文件夹外面,图不能放那儿。` }
564
+ if (e && /^(EACCES|EPERM|EROFS|ENOTDIR|EEXIST|ENOSPC)$/.test(e.code || '')) return { text: `${path.join(dir, 'assets')} 写不进去(${e.code})。换一个文件夹,或者这次用 CSS / SVG 画。` }
565
+ return { text: '照片库这会儿下载不了(网络问题)。这次先用 CSS / SVG 画,并告诉用户这里需要一张什么样的照片,稍后可以再试。' }
566
+ }
567
+ },
568
+ }
569
+
506
570
  /** compare_design 工具:设计稿的一屏和做出来的页面按同样尺寸截图,逐像素比 */
507
571
  export const compareTool = {
508
572
  name: 'compare_design',
@@ -712,9 +776,15 @@ export function apply(ctx) {
712
776
  studio.tracker = tracker
713
777
  studio.log = log
714
778
  studio.market = market
779
+ const photoIndex = loadPhotoIndex()
780
+ const photos = photoIndex ? createPhotos({ market, index: photoIndex, log }) : null
781
+ studio.photos = photos
782
+ studio.sessionCwd = sessionCwd
715
783
  return () => {
716
784
  if (studio.tracker === tracker) { studio.tracker = null; studio.log = () => {} }
717
785
  if (studio.market === market) { market.abort(); studio.market = null }
786
+ if (studio.photos === photos) studio.photos = null
787
+ if (studio.sessionCwd === sessionCwd) studio.sessionCwd = null
718
788
  }
719
789
  }, 'dsh-design-studio: tracker')
720
790
  // check_design / look_design 用的无头浏览器:用到时才开,闲置自己关,这一行停用时关掉
@@ -1046,7 +1116,10 @@ export function apply(ctx) {
1046
1116
  const strict = library.strictHtml(page) || (v > 0 && library.strictVersions(t.root))
1047
1117
  const nonce = strict ? crypto.randomBytes(16).toString('base64') : ''
1048
1118
  const lead = strict ? strictMeta(nonce) + ERR_CATCHER.replace('<script>', `<script nonce="${nonce}">`) : ERR_CATCHER
1049
- const html = bundle(strict ? defang(page.toString('utf8')) : page.toString('utf8'), { key, read, base: href, lead, tail: inlinePicker(fs.readFileSync(PICKER_FILE, 'utf8'), parent, href, nonce) })
1119
+ let html = bundle(strict ? defang(page.toString('utf8')) : page.toString('utf8'), { key, read, base: href, lead, tail: inlinePicker(fs.readFileSync(PICKER_FILE, 'utf8'), parent, href, nonce) })
1120
+ // 打包后图片变成 data: 地址,文件名没了:把用到的 AI 示意图记在页面里,导出时照样提醒
1121
+ const aiNames = [...deps].filter((x) => isPhotoAsset(x)).map((x) => path.basename(x))
1122
+ if (aiNames.length) html = html.replace(lead, () => `${lead}<meta name="ddp-ai-photos" content="${aiNames.join(',').replace(/[^a-z0-9.,-]/gi, '')}">`)
1050
1123
  // 用到的文件太多就不列(null = 右侧栏不按文件筛,目录里一有改动就重新打包)
1051
1124
  json(res, 200, { html, deps: deps.size > 200 ? null : [...deps], strict })
1052
1125
  } catch (e) {
package/lib/look.js CHANGED
@@ -478,12 +478,14 @@ function metricsLine(m) {
478
478
  */
479
479
  /** 一条问题认得出是同一个(复查时比上次修好了哪些、新出了哪些) */
480
480
  const issueKey = (it) => `${it.type}|${it.sel}|${it.text || ''}|${it.msg || ''}|${it.src || ''}`
481
+ // 复查时比较用:同一个原因的叠字,叠在哪儿都算同一个
482
+ const compareKey = (it) => (it.type === 'overlap' && it.cause && it.cause.sel ? `overlap|cause|${it.cause.sel}|${it.cause.prop}` : issueKey(it))
481
483
  const rowKey = (r, dark) => `${r.key}|${r.w}x${r.h}${dark ? '|dark' : ''}`
482
484
 
483
485
  /** 这次量出来的(每屏每种尺寸一组问题),下次复查拿来比 */
484
486
  export function issueSnapshot(rows, dark = false) {
485
487
  const out = new Map()
486
- for (const r of rows) if (!r.error) out.set(rowKey(r, dark), new Set(r.issues.map(issueKey)))
488
+ for (const r of rows) if (!r.error) out.set(rowKey(r, dark), new Set(r.issues.map(compareKey)))
487
489
  return out
488
490
  }
489
491
 
@@ -508,18 +510,26 @@ export function formatMeasure(rows, { sizes, where, missing = [], more = 0, dark
508
510
  const failed = rows.filter((r) => r.error).length
509
511
  // 和上次同样的屏、同样的尺寸比:修好了几个、新出了几个(新的在清单里标出来)
510
512
  const fresh = new Set()
511
- let fixed = 0
513
+ const gone = new Set()
514
+ const wasThere = new Set()
515
+ const unsure = new Set() // 上次有、这次这个尺寸没量成:不知道还在不在
516
+ const nowThere = new Set(rows.flatMap((r) => r.issues.map((it) => `${r.key}|${compareKey(it)}`)))
512
517
  let compared = 0
513
518
  if (prev) {
514
519
  for (const r of rows) {
515
- const before = r.error ? null : prev.get(rowKey(r, dark))
520
+ const before = prev.get(rowKey(r, dark))
516
521
  if (!before) continue
522
+ for (const k of before) (r.error ? unsure : wasThere).add(`${r.key}|${k}`)
523
+ if (r.error) continue
517
524
  compared++
518
- const now = new Set(r.issues.map(issueKey))
519
- for (const k of before) if (!now.has(k)) fixed++
525
+ const now = new Set(r.issues.map(compareKey))
526
+ for (const k of before) if (!now.has(k)) gone.add(`${r.key}|${k}`)
520
527
  for (const k of now) if (!before.has(k)) fresh.add(`${r.key}|${k}`)
521
528
  }
522
529
  }
530
+ // 和「发现 N 个」同一个单位:一个问题在几种尺寸上都出现算一个。这屏别的尺寸上还在的不算修好,换了个尺寸出现的也不算新出
531
+ const fixed = [...gone].filter((k) => !nowThere.has(k) && !unsure.has(k)).length
532
+ for (const k of fresh) if (wasThere.has(k) || unsure.has(k)) fresh.delete(k)
523
533
  const sz = sizes.map(([w, h]) => sizeText(w, h)).join('、')
524
534
  const status = failed === rows.length
525
535
  ? '一次都没量成,这次检查没完成(原因见下)。'
@@ -557,7 +567,7 @@ export function formatMeasure(rows, { sizes, where, missing = [], more = 0, dark
557
567
  let i = 0
558
568
  for (const [k, { it, at }] of seen) {
559
569
  if (sameCause.has(`${key}|${k}`)) continue
560
- const tag = (fresh.has(`${key}|${k}`) ? '[新] ' : '') + (at.length < ok && mine.length > 1 ? `[${at.join('、')}] ` : '')
570
+ const tag = (fresh.has(`${key}|${compareKey(it)}`) ? '[新] ' : '') + (at.length < ok && mine.length > 1 ? `[${at.join('、')}] ` : '')
561
571
  const what = [it.sel, it.text ? `「${it.text}」` : ''].filter(Boolean).join('')
562
572
  const pic = pics.get(`${key}|${k}`)
563
573
  const upper = pic && pic.k === `${key}|${k}` && pic.upper ? `;${pic.upper === 'self' ? `「${String(it.text || '').slice(0, 12)}」` : `「${String(it.otherText || '').slice(0, 12)}」`}画在上面` : ''
@@ -0,0 +1 @@
1
+ {"format":1,"package":"dsh-design-photos","version":"1.0.0","generic":["特写","俯拍","内景","环境","细节","产品","店内","门店","一排","现代","航拍","质地","工具","外观","器械","器具","瓶子","罐子","手","手部","手拿","早晨","清晨","傍晚","黄昏","日出","interior","detail","product","store","shop","room","row","modern","texture","tools","equipment","exterior","aerial","view","table","hand","hands","bottle","bottles","jar","city","street"],"themes":{"hotel":{"label":"民宿酒店","words":["民宿","酒店","客栈","旅馆","住宿","宾馆","度假村","hotel","homestay","guesthouse","inn","resort","bnb","lodging","airbnb"]},"food":{"label":"餐饮","words":["餐饮","餐厅","饭店","美食","外卖","小吃","restaurant","food","dining","bistro","meal"]},"drink":{"label":"奶茶咖啡","words":["奶茶","咖啡","茶饮","饮品","咖啡馆","咖啡店","milk tea","coffee","cafe","bubble tea","beverage","tea shop","drink"]},"fitness":{"label":"健身","words":["健身","运动","撸铁","训练","减脂","gym","fitness","workout","training","sport"]},"beauty":{"label":"美妆","words":["美妆","护肤","化妆","美容","spa","beauty","skincare","cosmetics","makeup"]},"fashion":{"label":"服饰","words":["服饰","服装","穿搭","女装","男装","时尚","潮牌","fashion","clothing","apparel","streetwear"]},"education":{"label":"教育","words":["教育","学校","培训","课程","学习","学生","考研","留学","education","school","course","learning","student","university","study","tutoring"]},"scenery":{"label":"旅行风景","words":["风景","旅行","旅游","景点","山水","户外","徒步","露营","攻略","travel","scenery","tourism","nature","outdoor","hiking","camping","trip"]}},"photos":[{"id":"hotel-01","theme":"hotel","w":1200,"h":800,"size":138410,"sha256":"254e3ccd9006699d70babb67de7d02d5ad8a5e8fbea87a693771ebdc09ba81f3","alt":"山村民宿的卧室,亚麻床品,窗外晨雾","altEn":"Guesthouse bedroom in a mountain village with linen bedding and morning mist outside","tags":["卧室","客房","床","山景","乡村","木梁","bedroom","room","bed","village","rustic"]},{"id":"hotel-02","theme":"hotel","w":1200,"h":800,"size":151540,"sha256":"875107fd24349f61872e1db0208a2a15372ac70b11ff883b8d9c21f3eb3073dc","alt":"黄昏的民宿庭院,石板路和灯笼","altEn":"Guesthouse courtyard at dusk with stone paths and warm lanterns","tags":["庭院","院子","灯笼","黄昏","外观","古建","courtyard","lantern","dusk","exterior"]},{"id":"hotel-03","theme":"hotel","w":1200,"h":800,"size":90673,"sha256":"cd1bec0acb2ae0f1153621ae8ee3a26868e6a4242f82ba97711600f55e194657","alt":"现代酒店客房,落地窗外是城市","altEn":"Modern hotel room with a floor-to-ceiling window over the city","tags":["客房","卧室","城市","落地窗","现代","商务","room","bedroom","city","modern","business"]},{"id":"hotel-04","theme":"hotel","w":1200,"h":800,"size":175642,"sha256":"be2a98ed8f7e18cf39a1ccff7206a86b2db96325f6ba800e1f36a7d6bda32a7f","alt":"木露台上的茶桌,远处是梯田","altEn":"Wooden terrace with a tea table overlooking terraced hills","tags":["露台","阳台","茶","梯田","山景","terrace","balcony","tea","view","hills"]},{"id":"hotel-05","theme":"hotel","w":800,"h":1200,"size":149771,"sha256":"c907907c200b3a9fb3b44932b155b1b1ce8bf40288e3b0aee171f448030cf05c","alt":"窗边的石头浴缸和叠好的毛巾","altEn":"Stone bathtub by a window with folded towels","tags":["浴缸","卫浴","浴室","毛巾","bathtub","bathroom","bath","towel"]},{"id":"hotel-06","theme":"hotel","w":800,"h":1200,"size":130691,"sha256":"a1f098558d2958fc6781a98de5c389e37421d1c097f363462dbf14ee5e9e378c","alt":"挂着纸灯笼的木楼梯","altEn":"Narrow wooden staircase lit by paper lanterns","tags":["楼梯","灯笼","走廊","stairs","staircase","lantern","hallway"]},{"id":"hotel-07","theme":"hotel","w":1200,"h":1200,"size":153618,"sha256":"678682eb63697ac25bb7e3a44a30e668d8969eb862352bed9afce59c01db0f79","alt":"白色床铺上的早餐托盘","altEn":"Breakfast tray on a neatly made white bed","tags":["早餐","床","托盘","咖啡","breakfast","bed","tray"]},{"id":"hotel-08","theme":"hotel","w":1200,"h":1200,"size":170165,"sha256":"39ace7f0e89341ba37ef412320d092b07bf2d452effd48603044ec96bf3c9a43","alt":"床头柜上的台灯、书和陶杯","altEn":"Bedside table with a lamp, a book and a ceramic cup","tags":["床头","台灯","细节","陶杯","bedside","lamp","detail"]},{"id":"food-01","theme":"food","w":1200,"h":800,"size":179909,"sha256":"f6d1f46c3ef49baa75941b9d4c7fe36c94948e1699c60bb2ce609dc5d0dfbe9a","alt":"俯拍一桌家常中餐","altEn":"Overhead view of a family-style Chinese dinner table","tags":["中餐","家常菜","私房菜","一桌菜","俯拍","聚餐","chinese","family","table","dinner"]},{"id":"food-02","theme":"food","w":1200,"h":800,"size":100584,"sha256":"6a621918cf96f86efc213756c975d7e39563f37ce5074906000bde60194a7497","alt":"灯光温暖的餐厅内景,餐桌已摆好","altEn":"Warmly lit restaurant interior with set tables","tags":["餐厅","内景","环境","餐桌","店内","interior","restaurant","table"]},{"id":"food-03","theme":"food","w":1200,"h":800,"size":102091,"sha256":"1384312b05a6a3f4a264954bdc6f351aad93d5e9e7991a39b033f0bde9005173","alt":"后厨里厨师的手在摆盘意面","altEn":"Chef plating pasta in a professional kitchen","tags":["厨师","摆盘","后厨","意面","西餐","chef","plating","kitchen","pasta","western"]},{"id":"food-04","theme":"food","w":1200,"h":800,"size":177275,"sha256":"922b252f6227d20713b0ece2af6701476e879064f58b0c7cf954346891aa31a3","alt":"沸腾的火锅和周围的新鲜食材","altEn":"Bubbling hot pot surrounded by fresh ingredients","tags":["火锅","火锅店","涮","食材","红汤","hotpot","hot pot","ingredients"]},{"id":"food-05","theme":"food","w":800,"h":1200,"size":103614,"sha256":"65e3f17e151413bb6be67658578eeb6ca05d315f76479558fc2deb505a932762","alt":"热气腾腾的牛肉面特写","altEn":"Close-up of a steaming bowl of beef noodles","tags":["牛肉面","面条","汤面","面馆","特写","noodles","noodle","beef","soup"]},{"id":"food-06","theme":"food","w":800,"h":1200,"size":115618,"sha256":"2a58fa11c6a6bf6149df5b41c72e62a023ef98049e629a8e82bb4f6944ed6403","alt":"木板上的汉堡和薯条","altEn":"Burger and fries on a wooden board","tags":["汉堡","薯条","快餐","burger","fries","fast food"]},{"id":"food-07","theme":"food","w":1200,"h":1200,"size":199114,"sha256":"d02b785684da1a847daa8667b0b30c05950e11ad30d0b496463b20daaad11ef7","alt":"黑色石板上的寿司拼盘","altEn":"Sushi platter on dark slate","tags":["寿司","日料","拼盘","sushi","japanese","platter"]},{"id":"food-08","theme":"food","w":1200,"h":1200,"size":165741,"sha256":"01ccc4d288fa8e108b9b43e45ce25a9ad7e7b1756732c99dc62b6e83dac1fd5b","alt":"陶瓷盘里的莓果蛋糕","altEn":"A slice of berry cake on a ceramic plate","tags":["蛋糕","甜品","莓果","烘焙","cake","dessert","bakery","berry"]},{"id":"drink-01","theme":"drink","w":1200,"h":800,"size":83245,"sha256":"6b2f994c2fa581142407a1b59f6a22422ba5405e6c5f61ded29149485d5c6f2d","alt":"咖啡师在吧台倒拉花","altEn":"Barista pouring latte art at a cafe counter","tags":["拉花","拿铁","咖啡师","吧台","barista","latte art","counter"]},{"id":"drink-02","theme":"drink","w":1200,"h":800,"size":116279,"sha256":"8b7318ca0ebc446a8234565523ed003d72ad24cd5193ba943c83657bc39c992b","alt":"明亮的奶茶店内景","altEn":"Bright pastel milk tea shop interior","tags":["门店","店内","内景","环境","奶茶店","interior","shop","store"]},{"id":"drink-03","theme":"drink","w":1200,"h":800,"size":87990,"sha256":"98b0e59030215cb8029b4d64eb85e86c046f355d79a615536d2307067f9a8298","alt":"吧台上一排冰果茶","altEn":"A row of iced fruit teas on a counter","tags":["果茶","水果茶","冰饮","一排","fruit tea","iced","row"]},{"id":"drink-04","theme":"drink","w":1200,"h":800,"size":107263,"sha256":"5c78d9b6706418f35553c2ef3311ffb98ec87bc4999e4bb6d259571536416af7","alt":"木桌上的手冲壶和咖啡豆","altEn":"Pour-over kettle and coffee beans on a wooden table","tags":["手冲","咖啡豆","器具","pour over","beans","kettle"]},{"id":"drink-05","theme":"drink","w":800,"h":1200,"size":79773,"sha256":"2f9bdc9ff80e7cc24da045dd27d5c933184ad9c1ac544d97c27c7ac7ff89e02a","alt":"手拿黑糖珍珠奶茶","altEn":"Hand holding brown sugar boba milk tea","tags":["珍珠","黑糖","手拿","奶茶","boba","brown sugar","hand"]},{"id":"drink-06","theme":"drink","w":800,"h":1200,"size":98633,"sha256":"62fc1f3ff153abd6fc8ccb148106575611ec347b9d3cce14dfa4547a2c5aad2b","alt":"阳光窗台上的冰美式","altEn":"Iced americano on a sunny window ledge","tags":["美式","冰咖啡","窗台","americano","iced"]},{"id":"drink-07","theme":"drink","w":1200,"h":1200,"size":201635,"sha256":"dc4e7c353cc0801b48fd742116139364844dd84fe04f753c7d1c8a12fd60b94f","alt":"俯拍抹茶拿铁","altEn":"Matcha latte from above with leaf art","tags":["抹茶","拿铁","俯拍","matcha","latte"]},{"id":"drink-08","theme":"drink","w":1200,"h":1200,"size":164754,"sha256":"4e30afa6d0583578241c22a7d2ad00d8e434187b3ed5a4bd35c1127e03a65686","alt":"挂着水珠的冰柠檬茶特写","altEn":"Iced lemon tea close up with condensation","tags":["柠檬茶","柠檬","冰饮","特写","lemon","iced tea"]},{"id":"fitness-01","theme":"fitness","w":1200,"h":800,"size":154138,"sha256":"f0aad68474bfa60297bb24a1cc64cf7c569826cf6aea49374f0006029fda924b","alt":"晨光里的现代健身房","altEn":"Empty modern gym with racks in morning light","tags":["健身房","器械","内景","环境","gym","interior","equipment"]},{"id":"fitness-02","theme":"fitness","w":1200,"h":800,"size":99682,"sha256":"2eee4f39fe1fc3032cacbfeeba2aa4c77ddb237d4e36ec849d4830114f87b6ba","alt":"坐在长凳上系鞋带的运动员","altEn":"Athlete tying shoes on a bench","tags":["系鞋带","运动员","准备","athlete","shoes","bench"]},{"id":"fitness-03","theme":"fitness","w":1200,"h":800,"size":97032,"sha256":"64b228ad2dd03e044acbf899441ee344afb004efcef379f0c6d018aba4cb761d","alt":"安静的瑜伽教室和卷好的垫子","altEn":"Quiet yoga studio with rolled mats","tags":["瑜伽","瑜伽垫","教室","普拉提","yoga","mat","studio","pilates"]},{"id":"fitness-04","theme":"fitness","w":1200,"h":800,"size":117122,"sha256":"25a01fda03949e17d14e8d38eb15d84cd0e8990711e9e42a0cbba8819648ca46","alt":"日出时山脊上的越野跑者","altEn":"Trail runner on a ridge at sunrise","tags":["跑步","越野","户外","日出","runner","running","trail","sunrise"]},{"id":"fitness-05","theme":"fitness","w":800,"h":1200,"size":66573,"sha256":"4699daa0a7d29889ce167bb0c366da4d99d671ae367b83fb7a457b8b1d42e39e","alt":"一排哑铃,浅景深","altEn":"A rack of dumbbells","tags":["哑铃","力量","器械","dumbbell","weights","strength"]},{"id":"fitness-06","theme":"fitness","w":800,"h":1200,"size":101974,"sha256":"47b55918170ca812f862798185ffeae49e7152fe7a47f459d7a0b239e4dc051a","alt":"背对镜头做引体向上","altEn":"Person doing pull-ups, seen from behind","tags":["引体向上","力量","训练","背部","pull up","training","back"]},{"id":"fitness-07","theme":"fitness","w":1200,"h":1200,"size":168091,"sha256":"94423411396abd5dd8ee12983eedf9213b30cfc7216c9cbc58db4781b9f1beb9","alt":"橡胶地板上的壶铃和毛巾","altEn":"Kettlebell and a folded towel on a gym floor","tags":["壶铃","毛巾","kettlebell","towel"]},{"id":"fitness-08","theme":"fitness","w":1200,"h":1200,"size":223754,"sha256":"40dd77d270cc485312442af4e4ef413787d13af663ace08ce763187fcfab1ae3","alt":"鸡肉米饭蔬菜的健身餐盒","altEn":"Meal prep box with chicken, rice and greens","tags":["健身餐","减脂餐","餐盒","饮食","meal prep","diet","nutrition"]},{"id":"beauty-01","theme":"beauty","w":1200,"h":800,"size":79141,"sha256":"2dbce4d80476c8dab61239d9b0f729a62a3ba1e79233bebdbaa80d04aa3a2e09","alt":"石板上的无标签护肤瓶","altEn":"Unlabeled skincare bottles on a stone slab","tags":["护肤品","瓶子","产品","skincare","bottles","product"]},{"id":"beauty-02","theme":"beauty","w":1200,"h":800,"size":173538,"sha256":"b5aad48a96e4e2c5cb3116542d0da3b992b6ae3ecf48176a6d2cc94feb7c51bc","alt":"明亮的美发沙龙内景","altEn":"Bright hair salon interior with mirrors and chairs","tags":["沙龙","美发","理发店","内景","环境","salon","hair","interior"]},{"id":"beauty-03","theme":"beauty","w":1200,"h":800,"size":122012,"sha256":"a20af994a9de2e79b695ceaaff1d97618ed75551b288f16f3db54a86bee55966","alt":"浅色布面上的化妆刷和口红","altEn":"Makeup brushes and a lipstick on pale fabric","tags":["化妆刷","口红","彩妆","makeup","brushes","lipstick"]},{"id":"beauty-04","theme":"beauty","w":1200,"h":800,"size":142878,"sha256":"97729a6131f254d69bd5102bb04767304a14bf478cc1c924341b9ca2f5e510ae","alt":"石板上的一抹面霜,质地特写","altEn":"A smear of face cream on a stone slab, macro","tags":["面霜","质地","特写","护肤","cream","texture","swatch"]},{"id":"beauty-05","theme":"beauty","w":800,"h":1200,"size":48775,"sha256":"616b0022012ad2290b444f2b0790e980231c1d6546c84a9342c6f732f170b0ce","alt":"琥珀色精华滴管瓶","altEn":"Amber serum dropper bottle with a falling drop","tags":["精华","滴管","产品","serum","dropper","bottle"]},{"id":"beauty-06","theme":"beauty","w":800,"h":1200,"size":133940,"sha256":"0de9e8acbbeea878a29ecd4fe7d99ade20606843cb98a9a844b7ed9bae0c674f","alt":"理发台上的梳子、剪刀和喷壶","altEn":"Comb, scissors and a spray bottle on a salon counter","tags":["美发","梳子","剪刀","工具","hair","comb","scissors","tools"]},{"id":"beauty-07","theme":"beauty","w":1200,"h":1200,"size":148218,"sha256":"2590ae92b4a5c683bb21fc1cac69c074e7c4abe91b9334b18476bb5b7f1ccd60","alt":"俯拍打开的面霜罐","altEn":"Open cream jar from above","tags":["面霜","罐子","质地","cream","jar","texture"]},{"id":"beauty-08","theme":"beauty","w":1200,"h":1200,"size":169318,"sha256":"2fb0adc2d4fc6dd121e0b5497def5039430695546cebabe4599a3a7e17e20868","alt":"亚麻布上几瓶裸色系指甲油","altEn":"Unlabeled nail polish bottles in neutral shades on linen","tags":["美甲","指甲油","瓶子","nail","polish","manicure"]},{"id":"fashion-01","theme":"fashion","w":1200,"h":800,"size":133856,"sha256":"263ff2d11876c035db2b6296b7f759f49159dc8fe88786c7efa1eee7c16345f4","alt":"安静的买手店内景和衣架","altEn":"Calm boutique interior with garment rails","tags":["门店","买手店","衣架","内景","环境","boutique","store","interior","rack"]},{"id":"fashion-02","theme":"fashion","w":1200,"h":800,"size":144129,"sha256":"f0ae6d3f91802b0bd6d680cba86e62bce29b99d68655e008671ca7c8659805c7","alt":"木桌上叠好的针织衫","altEn":"Stack of folded knitwear on a wooden table","tags":["针织","毛衣","叠放","knitwear","sweater","folded"]},{"id":"fashion-03","theme":"fashion","w":1200,"h":800,"size":104779,"sha256":"cb259f548056ded0c70cf8d7944b2b3e09303cf109f09142fa8acac1f5c04756","alt":"穿长大衣走在街头,只拍颈部以下","altEn":"Person in a long coat on a city street, cropped from the neck down","tags":["大衣","街拍","穿搭","秋冬","coat","street","outfit"]},{"id":"fashion-04","theme":"fashion","w":1200,"h":800,"size":147191,"sha256":"20bb7f62d2edcb3ad8d98d8470c8121bd68e998207be07cc699a3e3c372cd253","alt":"水泥台阶上的白色运动鞋","altEn":"White sneakers on a concrete step","tags":["鞋","运动鞋","小白鞋","球鞋","鞋子","鞋店","sneakers","shoes"]},{"id":"fashion-05","theme":"fashion","w":800,"h":1200,"size":53324,"sha256":"f227a5ed7b7472343b6fc2bbe1eb405086e1c7c5623ae49b271c119f89374574","alt":"纯色背景前的一身穿搭,只拍颈部以下","altEn":"Full outfit against a plain backdrop, cropped from the neck down","tags":["穿搭","全身","棚拍","模特","outfit","lookbook","model"]},{"id":"fashion-06","theme":"fashion","w":800,"h":1200,"size":94625,"sha256":"021615dfb09d9ee2fcccc7075d917382b526f72c0f4a4afbc8d388f2fdd57ced","alt":"木椅上的皮质手提包","altEn":"Leather handbag on a wooden chair","tags":["包","包包","手提包","皮具","handbag","bag","leather"]},{"id":"fashion-07","theme":"fashion","w":1200,"h":1200,"size":307215,"sha256":"c664bee71b338d211bcda5785aed281bfc91ef22954ab45387b30624ae5a86f6","alt":"牛仔布和缝线微距","altEn":"Denim fabric and stitching, macro","tags":["牛仔","面料","细节","denim","fabric","detail"]},{"id":"fashion-08","theme":"fashion","w":1200,"h":1200,"size":186512,"sha256":"92efbae6cc39e04c746ec1c1a6c9cf02aab3786d92dec3492a35ecd93fa39ce8","alt":"手腕上的极简手表","altEn":"Minimal watch on a wrist","tags":["手表","配饰","手腕","watch","accessory","wrist"]},{"id":"education-01","theme":"education","w":1200,"h":800,"size":109110,"sha256":"4347848477c27cbe5b9687d9480098de33e1193deb9d312af829e7618d8726a4","alt":"明亮的空教室和干净的黑板","altEn":"Bright empty classroom with a clean board","tags":["教室","课桌","黑板","classroom","desks","board"]},{"id":"education-02","theme":"education","w":1200,"h":800,"size":130299,"sha256":"67e1a6081bb41148de95cf363155953c98cceba86d4126c29dc35264ddedfd19","alt":"图书馆书架间看书的学生,背对镜头","altEn":"Students reading among tall library shelves, seen from behind","tags":["图书馆","书架","阅读","library","shelves","reading"]},{"id":"education-03","theme":"education","w":1200,"h":800,"size":99192,"sha256":"9d0805006ed8e5c20c75ef895ce60726124cdf1c856cf708ddb19c68a340c216","alt":"书桌上的笔记本、电脑和咖啡","altEn":"Study desk with an open notebook, a laptop and coffee","tags":["书桌","笔记本","自习","网课","线上课","desk","notebook","laptop","online"]},{"id":"education-04","theme":"education","w":1200,"h":800,"size":129687,"sha256":"05d33e1266ff46f7cf65d24bfb67106f6f90200cffb738ca54c8a2f4cd5ee66a","alt":"孩子的手在用彩铅画画","altEn":"Child drawing with colored pencils","tags":["少儿","画画","彩铅","美术","child","kids","drawing","art"]},{"id":"education-05","theme":"education","w":800,"h":1200,"size":133474,"sha256":"608c8db6555a748c12113c410b49e649ce5121a0c2a2c8933786971ebe6011c8","alt":"窗边叠放的书","altEn":"Stack of books beside a window","tags":["书","书本","阅读","books","reading"]},{"id":"education-06","theme":"education","w":800,"h":1200,"size":153082,"sha256":"faf4e461a1d475f2dd2d70f4319689223d2aeb4ded40e2553f10ec99ddc99bc1","alt":"背书包走在校园小路上的学生","altEn":"Student with a backpack on a leafy campus path","tags":["校园","书包","学生","大学","campus","backpack","university"]},{"id":"education-07","theme":"education","w":1200,"h":1200,"size":95697,"sha256":"0d0d8661485eefd46a9caf1aaf277e6f20a03e918ba9351cfdd697405640abfd","alt":"手握笔写笔记的特写","altEn":"Hand writing in a notebook, close up","tags":["写字","笔记","手","writing","notes","pen"]},{"id":"education-08","theme":"education","w":1200,"h":1200,"size":132941,"sha256":"f5c0f5500a00e6ec9d08cea7c3dd471b75da3a5bff35b9c820b040f9bbf9514d","alt":"实验室里装着彩色液体的烧杯","altEn":"Laboratory beakers with colored liquids","tags":["实验","科学","烧杯","化学","lab","science","beaker","chemistry"]},{"id":"scenery-01","theme":"scenery","w":1200,"h":800,"size":80724,"sha256":"ab534b36e0122c59e87b9f5bbd800a6c37b9e13844f046f2f307b6ccb9c92de8","alt":"晨雾中的山和小村庄","altEn":"Misty mountains with a small village at dawn","tags":["山","雾","村庄","清晨","mountain","mist","village","dawn"]},{"id":"scenery-02","theme":"scenery","w":1200,"h":800,"size":78867,"sha256":"0a4a9b64924e1030f2e5ba04aba8a98da68619dbf9ae770d48bba47940071c4c","alt":"蓝调时刻的城市天际线","altEn":"City skyline at blue hour","tags":["城市","天际线","夜景","city","skyline","night"]},{"id":"scenery-03","theme":"scenery","w":1200,"h":800,"size":171114,"sha256":"fa5d995378aa9ea21e1d92d865dffc4acf54ca8f20284d266f4962b3597a850c","alt":"航拍碧绿海滩","altEn":"Aerial view of a turquoise beach","tags":["海","海滩","海边","海景","海岛","航拍","sea","beach","island","aerial"]},{"id":"scenery-04","theme":"scenery","w":1200,"h":800,"size":290900,"sha256":"52186e49dc6e69a091339dfb6faf8f1b3619e3f9ade601b618bd8ba70bb73e57","alt":"秋天的林间小路","altEn":"Forest path in autumn","tags":["森林","秋天","小路","树林","forest","autumn","path"]},{"id":"scenery-05","theme":"scenery","w":800,"h":1200,"size":197974,"sha256":"586dcc78beecce178555c48660e93b335461bdc470fe86cf9d98b45c985a9b98","alt":"绿色峡谷里的瀑布","altEn":"Waterfall in a green gorge","tags":["瀑布","峡谷","水","waterfall","gorge"]},{"id":"scenery-06","theme":"scenery","w":800,"h":1200,"size":170992,"sha256":"05f8b352c265d20478053a816c7f680a528f8282bea0abeef4ef97f8cd68c0a3","alt":"傍晚挂红灯笼的古镇小巷","altEn":"Old town alley with red lanterns in the evening","tags":["古镇","小巷","灯笼","傍晚","old town","alley","lantern"]},{"id":"scenery-07","theme":"scenery","w":1200,"h":1200,"size":125041,"sha256":"9a2dc0b3b834a711b7e7e57ec65c6e8ee59fdfddc5a37b0cce8d015ba640d65d","alt":"光影分明的沙漠沙丘","altEn":"Desert dunes with long shadows","tags":["沙漠","沙丘","desert","dunes"]},{"id":"scenery-08","theme":"scenery","w":1200,"h":1200,"size":149955,"sha256":"23505c6428e0f686fb999d3a18045ceb324ca6bdc6249dd5c61adbd5a8284bb0","alt":"平静湖面上的木船和倒影","altEn":"Calm lake with a wooden boat and its reflection","tags":["湖","船","倒影","lake","boat","reflection"]}]}
package/lib/photos.js ADDED
@@ -0,0 +1,265 @@
1
+ /**
2
+ * 自带照片库:AI 提前生成、人工挑过的示意照片。模型调 find_photos 按描述找,图复制进设计目录,页面用本地文件。
3
+ *
4
+ * - 目录 photos-index.json 随插件发(描述、标签、尺寸、sha256),搜索不联网。
5
+ * - 图在 npm 包 dsh-design-photos 里,第一次用到才下载;每张按目录里钉死的 sha256 核对,镜像换了图也不认。
6
+ * - 「设计库不联网」开着就不下载(走 market 的 fetchPackage,开关在那边)。
7
+ * - 复制进设计目录的文件名都带 ai-photo- 前缀:转代码时认这个前缀提醒「上线前换成真实照片」,用户一眼也看得出。
8
+ */
9
+ import crypto from 'node:crypto'
10
+ import fs from 'node:fs'
11
+ import os from 'node:os'
12
+ import path from 'node:path'
13
+ import { fileURLToPath } from 'node:url'
14
+ import { vcmp } from './gallery/market.js'
15
+
16
+ export const PHOTO_PREFIX = 'ai-photo-'
17
+ export const PHOTOS_CACHE = process.env.DSH_DESIGN_PHOTOS_CACHE || path.join(os.homedir(), '.dsh', 'cache', 'dsh-design-studio', 'photos')
18
+ export const MAX_PHOTOS = 8
19
+ const INDEX_FILE = fileURLToPath(new URL('./photos-index.json', import.meta.url))
20
+ const ID_RE = /^[a-z0-9]+(-[a-z0-9]+)*$/
21
+ const CAP = 60 * 1024 * 1024
22
+ const LIMITS = { files: 1000, file: 4 * 1024 * 1024, total: 120 * 1024 * 1024 }
23
+ const RETRY_MS = 60e3 // 下载失败后隔多久才再试(模型连着调不用每次都等超时)
24
+ // 一次下一个大包:比市场目录的默认超时长得多,每个源 60 秒,总共 2 分钟
25
+ const TIMING = { stagger: 8000, each: 60000, total: 120000 }
26
+
27
+ const sha256 = (b) => crypto.createHash('sha256').update(b).digest('hex')
28
+ const norm = (s) => String(s || '').normalize('NFKC').toLowerCase()
29
+ const ascii = (s) => /^[a-z0-9 -]+$/.test(s)
30
+
31
+ export const orientOf = (w, h) => (w > h * 1.1 ? 'landscape' : h > w * 1.1 ? 'portrait' : 'square')
32
+
33
+ /** 读目录;格式不对的条目不要(目录随插件发,这里只防手滑) */
34
+ export function loadPhotoIndex(file = INDEX_FILE) {
35
+ let raw
36
+ try { raw = JSON.parse(fs.readFileSync(file, 'utf8')) } catch { return null }
37
+ if (!raw || raw.format !== 1 || typeof raw.package !== 'string' || typeof raw.version !== 'string' || !Array.isArray(raw.photos)) return null
38
+ const themes = raw.themes && typeof raw.themes === 'object' ? raw.themes : {}
39
+ const photos = raw.photos.filter((p) => p && ID_RE.test(String(p.id)) && /^[0-9a-f]{64}$/.test(String(p.sha256)) && p.w > 0 && p.h > 0 && themes[p.theme])
40
+ return { ...raw, themes, photos }
41
+ }
42
+
43
+ const dicts = new WeakMap()
44
+ /** 题材词表 + 全部中文词(长的在前);标签里含本题材词的也算题材词(「奶茶店」「健身房」「运动鞋」) */
45
+ function dictOf(index) {
46
+ let d = dicts.get(index)
47
+ if (d) return d
48
+ const base = {}
49
+ const words = {}
50
+ const cjk = new Set()
51
+ for (const [k, v] of Object.entries(index.themes)) {
52
+ base[k] = new Set((Array.isArray(v.words) ? v.words : []).map(norm).filter(Boolean))
53
+ words[k] = new Set(base[k])
54
+ }
55
+ for (const p of index.photos) {
56
+ for (const t of Array.isArray(p.tags) ? p.tags : []) {
57
+ const x = norm(t)
58
+ if (!x) continue
59
+ if (!ascii(x)) cjk.add(x)
60
+ if (!ascii(x) && [...base[p.theme]].some((w) => !ascii(w) && x.includes(w))) words[p.theme].add(x)
61
+ }
62
+ }
63
+ for (const set of Object.values(words)) for (const w of set) if (!ascii(w)) cjk.add(w)
64
+ const phrases = new Set()
65
+ for (const set of Object.values(words)) for (const w of set) if (ascii(w) && w.includes(' ')) phrases.add(w)
66
+ for (const p of index.photos) for (const t of Array.isArray(p.tags) ? p.tags : []) { const x = norm(t); if (ascii(x) && x.includes(' ')) phrases.add(x) }
67
+ const allBase = new Set(Object.values(base).flatMap((x) => [...x]))
68
+ const generic = new Set((Array.isArray(index.generic) ? index.generic : []).map(norm))
69
+ d = { base, allBase, generic, words, terms: [...cjk].sort((a, b) => b.length - a.length), phrases: [...phrases].sort((a, b) => b.length - a.length) }
70
+ dicts.set(index, d)
71
+ return d
72
+ }
73
+
74
+ const singular = (w) => (w.length > 3 && w.endsWith('s') && !w.endsWith('ss') ? w.slice(0, -1) : w)
75
+ const singularAll = (s) => s.split(' ').map(singular).join(' ')
76
+
77
+ /**
78
+ * 查询里命中了哪些词。中文最长词优先吃掉(「运动鞋」不再算「运动」);
79
+ * 单字词只认单独成段的(「海报」「水果」不算「海」「水」)。
80
+ * 英文先按原词归成单数,短语也先吃掉(「meal prep」不再算「meal」,「milk teas」算「milk tea」),其余按整词。
81
+ */
82
+ function matcherOf(dict, query) {
83
+ const q = norm(query)
84
+ const got = new Set()
85
+ let plain = ` ${singularAll(q.replace(/[^a-z0-9]+/g, ' ').trim())} `
86
+ for (const t of dict.phrases) {
87
+ const needle = ` ${singularAll(t)} `
88
+ if (plain.includes(needle)) { got.add(t); plain = plain.split(needle).join(' ') }
89
+ }
90
+ const words = new Set(plain.split(/\s+/).filter((w) => w.length >= 2))
91
+ let rest = q
92
+ for (const t of dict.terms) {
93
+ if ([...t].length > 1 && rest.includes(t)) { got.add(t); rest = rest.split(t).join(' ') }
94
+ }
95
+ const singles = new Set(dict.terms.filter((t) => [...t].length === 1))
96
+ for (const seg of rest.split(/[^\p{Script=Han}]+/u)) if (singles.has(seg)) got.add(seg)
97
+ return (t) => {
98
+ const x = norm(t)
99
+ if (!x) return false
100
+ if (!ascii(x)) return got.has(x)
101
+ return x.includes(' ') ? got.has(x) : words.has(singular(x))
102
+ }
103
+ }
104
+
105
+ /**
106
+ * 按描述搜:先看具体画面(标签),对上了的只要它们,同题材的优先(宁少勿滥,准确的画面不会被题材词挡掉);
107
+ * 一个都没对上才按题材挑。题材词本身、「特写」「内景」这类通用修饰词不算对上画面,只帮排序。
108
+ * 这套设计已经用过的排最后,内容比横竖要紧;同分时按 seed 打散(同一套设计结果稳定,不同设计不总是同几张)。
109
+ */
110
+ export function searchPhotos(index, opts = {}) {
111
+ const { count = 3 } = opts
112
+ const n = Math.min(MAX_PHOTOS, Math.max(1, Math.floor(Number(count)) || 3))
113
+ return scan(index, opts).rows.slice(0, n).map((r) => r.p)
114
+ }
115
+
116
+ /** 这次只命中了题材、没有对得上的具体画面(工具要照实告诉模型,让它看描述再决定用不用) */
117
+ export const onlyByTheme = (index, opts) => { const r = scan(index, opts); return r.rows.length > 0 && !r.specific }
118
+
119
+ function scan(index, { query, ratio = '', used = new Set(), seed = '' } = {}) {
120
+ const dict = dictOf(index)
121
+ const hit = matcherOf(dict, query)
122
+ const themeScore = {}
123
+ let best = 0
124
+ for (const k of Object.keys(index.themes)) {
125
+ themeScore[k] = [...dict.words[k]].filter(hit).length
126
+ best = Math.max(best, themeScore[k])
127
+ }
128
+ const all = index.photos.map((p) => {
129
+ const hits = (Array.isArray(p.tags) ? p.tags : []).filter(hit).map(norm).filter((t) => !dict.allBase.has(t))
130
+ const core = hits.filter((t) => !dict.generic.has(t)).length
131
+ return { p, core, mods: hits.length - core, theme: themeScore[p.theme], seen: used.has(p.id) ? 1 : 0, fit: ratio && orientOf(p.w, p.h) === ratio ? 1 : 0, rank: sha256(`${seed}\n${p.id}`) }
132
+ })
133
+ const exact = all.filter((r) => r.core > 0)
134
+ const specific = exact.length > 0
135
+ const inBest = best ? exact.filter((r) => r.theme === best) : []
136
+ const rows = specific ? (inBest.length ? inBest : exact) : best ? all.filter((r) => r.theme === best) : []
137
+ rows.sort((a, b) => a.seen - b.seen || b.core - a.core || b.mods - a.mods || b.theme - a.theme || b.fit - a.fit || (a.rank < b.rank ? -1 : a.rank > b.rank ? 1 : 0))
138
+ return { rows, specific }
139
+ }
140
+
141
+ /** 设计目录里已经放了哪几张(按文件名认,同一套设计别老用同一张) */
142
+ export function usedPhotos(dir, index) {
143
+ const out = new Set()
144
+ let names = []
145
+ try { names = fs.readdirSync(path.join(dir, 'assets')) } catch { return out }
146
+ const ids = new Set(index.photos.map((p) => p.id))
147
+ for (const n of names) {
148
+ const m = n.startsWith(PHOTO_PREFIX) && n.endsWith('.jpg') ? n.slice(PHOTO_PREFIX.length, -4) : ''
149
+ if (m && ids.has(m)) out.add(m)
150
+ }
151
+ return out
152
+ }
153
+
154
+ /** 目录(或它里面的页面)用了几张 AI 示意图:转代码时提醒 */
155
+ export const isPhotoAsset = (name) => path.basename(String(name)).startsWith(PHOTO_PREFIX)
156
+
157
+ export function createPhotos({ market, index = loadPhotoIndex(), cacheDir = PHOTOS_CACHE, log = () => {}, now = Date.now } = {}) {
158
+ let inflight = null
159
+ let failedAt = -Infinity
160
+ let lastErr = null
161
+ const dirOf = () => path.join(cacheDir, index.version)
162
+ const fileOf = (p) => path.join(dirOf(), `${p.id}.jpg`)
163
+ const okFile = (p) => {
164
+ try { return sha256(fs.readFileSync(fileOf(p))) === p.sha256 } catch { return false }
165
+ }
166
+ const ready = () => {
167
+ // 判断「下过了没有」只看大小(每次全算哈希没必要);真正复制之前逐张核对
168
+ return index.photos.every((p) => { try { return fs.statSync(fileOf(p)).size === p.size } catch { return false } })
169
+ }
170
+
171
+ async function download() {
172
+ const files = await market.fetchPackage(index.package, index.version, {
173
+ cap: CAP,
174
+ limits: LIMITS,
175
+ timing: TIMING,
176
+ // 在抢下载的回调里核对:哪个源的图不对,算它失败,接着等别的源
177
+ check: (list) => {
178
+ const by = new Map(list.map((f) => [f.path, f.data]))
179
+ const out = []
180
+ for (const p of index.photos) {
181
+ const data = by.get(`photos/${p.id}.jpg`)
182
+ if (!data || sha256(data) !== p.sha256) { const e = new Error('photo mismatch'); e.code = 'mismatch'; throw e }
183
+ out.push({ p, data })
184
+ }
185
+ return out
186
+ },
187
+ })
188
+ const dir = dirOf()
189
+ fs.mkdirSync(dir, { recursive: true })
190
+ for (const { p, data } of files) {
191
+ const tmp = `${fileOf(p)}.${process.pid}.tmp`
192
+ fs.writeFileSync(tmp, data)
193
+ fs.renameSync(tmp, fileOf(p))
194
+ }
195
+ // 只清比自己旧的版本(另一个配置里更新的插件下的不能动)
196
+ for (const n of fs.readdirSync(cacheDir)) {
197
+ if (/^\d+\.\d+\.\d+/.test(n) && vcmp(n, index.version) < 0) try { fs.rmSync(path.join(cacheDir, n), { recursive: true, force: true }) } catch (e) { log(e) }
198
+ }
199
+ }
200
+
201
+ /** 保证图都在缓存里;失败抛错(err.code:off = 不联网开着) */
202
+ function ensure() {
203
+ if (ready()) return Promise.resolve()
204
+ if (inflight) return inflight
205
+ if (now() - failedAt < RETRY_MS && lastErr) return Promise.reject(lastErr)
206
+ inflight = download().then(
207
+ () => { failedAt = -Infinity; lastErr = null; inflight = null },
208
+ (e) => { inflight = null; log(e); if (e && e.code === 'off') { failedAt = -Infinity; lastErr = null } else { failedAt = now(); lastErr = e } throw e },
209
+ )
210
+ return inflight
211
+ }
212
+
213
+ /**
214
+ * 把 picks 复制进 <dir>/assets/,返回 [{ p, rel }]。全程同步,真实路径就在写之前核对。
215
+ * allowed(真实路径) 说这个目录能不能写;同名文件已经在了就不动(可能是用户换成了自己的照片);assets 指到外面就不写。
216
+ */
217
+ function place(dir, picks, allowed = () => true) {
218
+ const denied = () => Object.assign(new Error('outside'), { code: 'link' })
219
+ let probe = path.resolve(dir)
220
+ while (!fs.existsSync(probe)) {
221
+ const up = path.dirname(probe)
222
+ if (up === probe) break
223
+ probe = up
224
+ }
225
+ if (!allowed(fs.realpathSync(probe))) throw denied()
226
+ const assets = path.join(dir, 'assets')
227
+ fs.mkdirSync(assets, { recursive: true })
228
+ const realDir = fs.realpathSync(dir)
229
+ const realAssets = fs.realpathSync(assets)
230
+ if (!allowed(realDir) || realAssets !== path.join(realDir, 'assets')) throw denied()
231
+ const out = []
232
+ for (const p of picks) {
233
+ if (!okFile(p)) {
234
+ // 缓存里这张坏了:删掉,下次 ensure 会重新下
235
+ try { fs.rmSync(fileOf(p), { force: true }) } catch (e) { log(e) }
236
+ throw Object.assign(new Error(`bad cached photo ${p.id}`), { code: 'mismatch' })
237
+ }
238
+ const name = `${PHOTO_PREFIX}${p.id}.jpg`
239
+ try {
240
+ fs.copyFileSync(fileOf(p), path.join(realAssets, name), fs.constants.COPYFILE_EXCL)
241
+ } catch (e) {
242
+ if (!e || e.code !== 'EEXIST') throw e
243
+ }
244
+ out.push({ p, rel: `assets/${name}` })
245
+ }
246
+ return out
247
+ }
248
+
249
+ /**
250
+ * 下载 → 看这套设计用过哪些 → 选图 → 复制。下载之后全程同步,同一目录并发调用不会选到同一批。
251
+ * pick(used) 返回要的图;缓存有坏图时重下一次。
252
+ */
253
+ async function provide({ dir, allowed, pick }) {
254
+ await ensure()
255
+ try {
256
+ return place(dir, pick(usedPhotos(dir, index)), allowed)
257
+ } catch (e) {
258
+ if (!e || e.code !== 'mismatch') throw e
259
+ }
260
+ await ensure()
261
+ return place(dir, pick(usedPhotos(dir, index)), allowed)
262
+ }
263
+
264
+ return { index, ready, ensure, place, provide }
265
+ }