image.pro\recipe\recipe.mbt

87.1% · 148 / 170 points · 525 lines

Background color reports the state of each line. Underlined characters mark exact instrumented byte offsets; hover them to inspect the visit count.

  1. 1///|
  2. 2/// # Recipe 层:一次调用完成一件业务事
  3. 3///
  4. 4/// 本包其余文件是「零实现的再导出」,只有本文件有实现。放这里的原因:
  5. 5/// Recipe 天然需要 codec(编解码)+ process(算子)两头,而 `image.pro` 是唯一
  6. 6/// 已经同时依赖两边的入口包;四个出口(CLI / wasm / MCP / 页面)都能直接用。
  7. 7///
  8. 8/// 与 Primitive 的区别是**输入输出都是业务语义**(字节进、字节出);
  9. 9/// 与 CLI 的区别是**不碰文件系统**,所以库包四目标(native/wasm-gc/js/wasm)都能编。
  10. 10
  11. 11///|
  12. 12/// 运行参数。数值型约束一律用 0 表示"不启用",避免 Option 在四个出口的 ABI 上各写一套。
  13. 13pub(all) struct RecipeOpts {
  14. 14 format : @types.ImageFormat
  15. 15 longest : Int32
  16. 16 max_bytes : Int32
  17. 17 quality : Int32
  18. 18 block : Int32
  19. 19 /// strict 档全图模糊半径;0 表示按 `max(2, block)` 推导。
  20. 20 blur_radius : Int32
  21. 21 policy : String
  22. 22 regions : Array[@types.Region]
  23. 23}
  24. 24
  25. 25///|
  26. 26/// 默认参数:不约束最长边与体积、质量 85、打码块 8、policy=standard、无区域。
  27. 27pub fn RecipeOpts::new() -> RecipeOpts {
  28. 28● {
  29. 29 format: @types.ImageFormat::Unknown,
  30. 30 longest: 0,
  31. 31 max_bytes: 0,
  32. 32 quality: 85,
  33. 33 block: 8,
  34. 34 blur_radius: 0,
  35. 35 policy: "standard",
  36. 36 regions: [],
  37. 37 }
  38. 38}
  39. 39
  40. 40///|
  41. 41/// 一步回执。`bytes` 为该步产物的字节数,非编码步填 -1;`width/height` 同理由 -1 占位。
  42. 42/// `ms` 是"从上一次打点到这一步结束"的墙钟毫秒,计划层(`plan_recipe`)填 -1(没真跑)。
  43. 43pub(all) struct StepRec {
  44. 44 name : String
  45. 45 note : String
  46. 46 width : Int32
  47. 47 height : Int32
  48. 48 bytes : Int32
  49. 49 ms : Double
  50. 50}
  51. 51
  52. 52///|
  53. 53/// 一次执行里的"上一个打点"。Recipe 全程同步单线程,所以用包级 Ref 而不是给 30 处
  54. 54/// `steps.push` 各加两个参数:每处只多一行 `ms: seg_ms(),`。
  55. 55let rc_seg : Ref[@bench.Timestamp?] = { val: None, }
  56. 56
  57. 57///|
  58. 58fn rc_seg_start() -> Unit {
  59. 59● rc_seg.val = Some(@bench.monotonic_clock_start())
  60. 60}
  61. 61
  62. 62///|
  63. 63/// 距上一次打点(或 `rc_seg_start`)的毫秒数,并把打点推进到现在。
  64. 64/// `monotonic_clock_end` 给微秒,这里除以 1000。
  65. 65fn seg_ms() -> Double {
  66. 66● let now = @bench.monotonic_clock_start()
  67. 67● let us = match rc_seg.val {
  68. 68● Some(t) => @bench.monotonic_clock_end(t)
  69. 69● None => 0.0
  70. 70 }
  71. 71 rc_seg.val = Some(now)
  72. 72 us / 1000.0
  73. 73}
  74. 74
  75. 75///|
  76. 76/// 执行回执:最终像素 + 编码字节 + 逐步记录。
  77. 77/// `redacted` / `blurred` 只有 sanitize 有语义,其余 Recipe 恒为 0 / false;
  78. 78/// `codes` 只有 code-intake 有语义,其余 Recipe 为空数组。
  79. 79pub(all) struct RecipeResult {
  80. 80 recipe : String
  81. 81 image : @types.Image
  82. 82 bytes : Bytes
  83. 83 format : @types.ImageFormat
  84. 84 steps : Array[StepRec]
  85. 85 quality : Int32
  86. 86 redacted : Int32
  87. 87 blurred : Bool
  88. 88 codes : Array[CodeHit]
  89. 89}
  90. 90
  91. 91///|
  92. 92/// 已注册的 Recipe 名,顺序即文档顺序。
  93. 93pub fn recipe_names() -> Array[String] {
  94. 94● [
  95. 95 "sanitize", "thumb", "avatar", "code-intake", "thumb-batch", "doc-scan", "ecom-white",
  96. 96 "redact-id",
  97. 97 ]
  98. 98}
  99. 99
  100. 100///|
  101. 101/// 一句话用途;未知名字返回空串(由 `run_recipe` 负责报错)。
  102. 102pub fn recipe_about(name : String) -> String {
  103. 103● match name {
  104. 104 "sanitize" =>
  105. 105● "剥元数据 + 已知区域块均值打码,输出可外发版本(policy: metadata/standard/strict)"
  106. 106 "thumb" =>
  107. 107● "按最长边等比缩小,可选体积上限(超限自动降质量二分)"
  108. 108● "avatar" => "中心方形裁切后等比缩放,输出正方形头像"
  109. 109 "code-intake" =>
  110. 110● "识别图里的条码/二维码,输出结构化记录(不改像素,bytes 原样返回)"
  111. 111 "thumb-batch" =>
  112. 112● "多图批量缩略:逐张同一条缩略逻辑,回执给每张尺寸/字节与批量合计(不留解码帧)"
  113. 113 "doc-scan" =>
  114. 114● "拍照文档增强:灰度 + CLAHE 去光照 + 自适应二值化,steps 里记文本行数前后对比"
  115. 115 "ecom-white" =>
  116. 116● "电商白底图:边框估背景 → 距离掩膜 → 最大连通域 → 掩膜收缩 → 白底合成 → 方形补齐"
  117. 117 "redact-id" =>
  118. 118● "证件/票据脱敏:自动命中条码区 + 手工框,实心黑覆盖(不可逆),编码即剥元数据"
  119. 119● _ => ""
  120. 120 }
  121. 121}
  122. 122
  123. 123///|
  124. 124/// 该格式是否有质量轴(只有它有,体积二分才成立)。
  125. 125fn has_quality_axis(fmt : @types.ImageFormat) -> Bool {
  126. 126● match fmt {
  127. 127● @types.ImageFormat::Jpeg => true
  128. 128○ @types.ImageFormat::Webp => true
  129. 129● _ => false
  130. 130 }
  131. 131}
  132. 132
  133. 133///|
  134. 134/// 按质量编码一次,错误统一转成库错误码。
  135. 135fn encode_at(
  136. 136 img : @types.Image,
  137. 137 fmt : @types.ImageFormat,
  138. 138 q : Int32,
  139. 139) -> Bytes raise @types.ImageError {
  140. 140● @lib.save_image_with_quality(img, fmt, q) catch {
  141. 141○ e => raise @types.image_error_from_load(e)
  142. 142 }
  143. 143}
  144. 144
  145. 145///|
  146. 146/// 解码 + 记录一步。
  147. 147fn step_decode(
  148. 148 data : Bytes,
  149. 149 steps : Array[StepRec],
  150. 150) -> @types.Image raise @types.ImageError {
  151. 151● let img = @lib.load_from_bytes_auto(data) catch {
  152. 152● e => raise @types.image_error_from_load(e)
  153. 153 }
  154. 154● steps.push({
  155. 155 name: "decode",
  156. 156 note: "",
  157. 157 width: img.width,
  158. 158 height: img.height,
  159. 159 bytes: -1,
  160. 160● ms: seg_ms(),
  161. 161 })
  162. 162 img
  163. 163}
  164. 164
  165. 165///|
  166. 166/// 编码进预算(纯试算,不写 steps):先按给定质量编;超限且格式有质量轴时二分降质量。
  167. 167/// 无质量轴或最低档都超限 → `LimitBytes`,真实体积写进消息(调用方据此换格式或缩尺寸)。
  168. 168fn encode_fit(
  169. 169 img : @types.Image,
  170. 170 fmt : @types.ImageFormat,
  171. 171 quality : Int32,
  172. 172 max_bytes : Int32,
  173. 173) -> (Bytes, Int32) raise @types.ImageError {
  174. 174● let q0 = if quality <= 0 { 85 } else if quality > 100 { 100 } else { quality }
  175. 175● let first = encode_at(img, fmt, q0)
  176. 176● let n0 = first.length().to_int()
  177. 177 if max_bytes <= 0 || n0 <= max_bytes {
  178. 178● return (first, q0)
  179. 179 }
  180. 180● if !has_quality_axis(fmt) {
  181. 181● raise @types.ImageError::Process(
  182. 182 @types.ErrorCode::LimitBytes,
  183. 183 "该格式无质量轴,\{n0} 字节已超上限 \{max_bytes}:换 jpeg/webp 或先缩尺寸",
  184. 184 )
  185. 185 }
  186. 186 let mut lo = 1
  187. 187 let mut hi = q0
  188. 188 let mut best : Bytes? = None
  189. 189 let mut best_q = 0
  190. 190 let mut best_n = n0
  191. 191 while lo <= hi {
  192. 192● let mid = (lo + hi) / 2
  193. 193● let b = encode_at(img, fmt, mid)
  194. 194● let nb = b.length().to_int()
  195. 195 if nb <= max_bytes {
  196. 196● best = Some(b)
  197. 197 best_q = mid
  198. 198 best_n = nb
  199. 199 lo = mid + 1
  200. 200 } else {
  201. 201● hi = mid - 1
  202. 202 }
  203. 203 }
  204. 204● match best {
  205. 205● Some(b) => (b, best_q)
  206. 206 None =>
  207. 207● raise @types.ImageError::Process(
  208. 208 @types.ErrorCode::LimitBytes,
  209. 209 "质量降到 1 仍有 \{best_n} 字节,超过上限 \{max_bytes}:换格式或先缩尺寸",
  210. 210 )
  211. 211 }
  212. 212}
  213. 213
  214. 214///|
  215. 215/// 记一步的编码包装:试算成功后把真实质量与体积写进回执。
  216. 216fn step_encode(
  217. 217 img : @types.Image,
  218. 218 fmt : @types.ImageFormat,
  219. 219 quality : Int32,
  220. 220 max_bytes : Int32,
  221. 221 steps : Array[StepRec],
  222. 222) -> (Bytes, Int32) raise @types.ImageError {
  223. 223● let (bytes, q) = encode_fit(img, fmt, quality, max_bytes)
  224. 224● steps.push({
  225. 225 name: "encode",
  226. 226 note: "quality=\{q}",
  227. 227 width: img.width,
  228. 228 height: img.height,
  229. 229● bytes: bytes.length().to_int(),
  230. 230● ms: seg_ms(),
  231. 231 })
  232. 232 (bytes, q)
  233. 233}
  234. 234
  235. 235///|
  236. 236/// 最长边等比尺寸;`longest` 为 0 或不小于原图长边时返回原尺寸。
  237. 237fn fit_longest(img : @types.Image, longest : Int32) -> (Int32, Int32) {
  238. 238● if longest <= 0 {
  239. 239● return (img.width, img.height)
  240. 240 }
  241. 241 let lw = img.width
  242. 242 let lh = img.height
  243. 243◐ let long = if lw >= lh { lw } else { lh }
  244. 244 if longest >= long {
  245. 245● return (lw, lh)
  246. 246 }
  247. 247● @transform.thumbnail_dims(lw, lh, longest)
  248. 248}
  249. 249
  250. 250///|
  251. 251/// 编码格式选择:带 alpha 用 png,否则 jpeg;调用方指定(非 Unknown)时优先用指定的。
  252. 252fn pick_format(
  253. 253 img : @types.Image,
  254. 254 want : @types.ImageFormat,
  255. 255) -> @types.ImageFormat {
  256. 256● match want {
  257. 257 @types.ImageFormat::Unknown =>
  258. 258● if @lib.has_alpha(img) {
  259. 259● @types.ImageFormat::Png
  260. 260 } else {
  261. 261● @types.ImageFormat::Jpeg
  262. 262 }
  263. 263● f => f
  264. 264 }
  265. 265}
  266. 266
  267. 267///|
  268. 268/// sanitize:policy 决定做几步。
  269. 269/// - metadata:只做重编码(EXIF/GPS/ICC/内嵌缩略图不进新容器);
  270. 270/// - standard:有 regions 就把每块打成均值块,没有就等同 metadata;
  271. 271/// - strict:没有 regions 时全图打码,之后无论是否有区域都追加全图模糊。
  272. 272fn recipe_sanitize(
  273. 273 data : Bytes,
  274. 274 opts : RecipeOpts,
  275. 275) -> RecipeResult raise @types.ImageError {
  276. 276● let steps : Array[StepRec] = []
  277. 277 let policy = opts.policy
  278. 278 if policy != "metadata" && policy != "standard" && policy != "strict" {
  279. 279● raise @types.ImageError::Process(
  280. 280 @types.ErrorCode::InvalidArgument,
  281. 281 "policy 只能是 metadata / standard / strict(收到 \{policy})",
  282. 282 )
  283. 283 }
  284. 284● let mut img = step_decode(data, steps)
  285. 285 let use_regions = policy == "standard" || policy == "strict"
  286. 286 let use_blur = policy == "strict"
  287. 287 let mut redacted = 0
  288. 288 if use_regions {
  289. 289● if opts.regions.length() == 0 {
  290. 290● if use_blur {
  291. 291● img = @filter.redact_blocks_all(img, opts.block)
  292. 292 redacted = 1
  293. 293 }
  294. 294 } else {
  295. 295● for r in opts.regions {
  296. 296● img = @filter.redact_blocks(img, r, opts.block)
  297. 297 redacted += 1
  298. 298 }
  299. 299 }
  300. 300 }
  301. 301 if use_blur {
  302. 302● let radius = if opts.blur_radius > 0 {
  303. 303● opts.blur_radius
  304. 304● } else if opts.block < 2 {
  305. 305○ 2
  306. 306 } else {
  307. 307● opts.block
  308. 308 }
  309. 309● img = @filter.box_blur(img, radius) catch {
  310. 310○ e => raise @types.image_error_from_load(e)
  311. 311 }
  312. 312 }
  313. 313● steps.push({
  314. 314 name: "policy",
  315. 315 note: "\{policy} regions=\{redacted} blur=\{use_blur}",
  316. 316 width: -1,
  317. 317 height: -1,
  318. 318 bytes: -1,
  319. 319● ms: seg_ms(),
  320. 320 })
  321. 321● let fmt0 = pick_format(img, opts.format)
  322. 322● let (bytes, q) = step_encode(img, fmt0, opts.quality, opts.max_bytes, steps)
  323. 323 {
  324. 324 recipe: "sanitize",
  325. 325 image: img,
  326. 326 bytes,
  327. 327 format: fmt0,
  328. 328 steps,
  329. 329 quality: q,
  330. 330 redacted,
  331. 331 blurred: use_blur,
  332. 332 codes: [],
  333. 333 }
  334. 334}
  335. 335
  336. 336///|
  337. 337/// thumb:只缩不裁,纵横比不变。
  338. 338fn recipe_thumb(
  339. 339 data : Bytes,
  340. 340 opts : RecipeOpts,
  341. 341) -> RecipeResult raise @types.ImageError {
  342. 342● let steps : Array[StepRec] = []
  343. 343● let mut img = step_decode(data, steps)
  344. 344● let (tw, th) = fit_longest(img, opts.longest)
  345. 345 if tw != img.width || th != img.height {
  346. 346● img = @transform.resize_to_contain(
  347. 347 img,
  348. 348 tw,
  349. 349 th,
  350. 350● Array::make(img.channels, (255 : Byte)),
  351. 351 ) catch {
  352. 352○ e => raise @types.image_error_from_load(e)
  353. 353 }
  354. 354● steps.push({
  355. 355 name: "resize",
  356. 356 note: "",
  357. 357 width: img.width,
  358. 358 height: img.height,
  359. 359 bytes: -1,
  360. 360● ms: seg_ms(),
  361. 361 })
  362. 362 }
  363. 363● let fmt0 = pick_format(img, opts.format)
  364. 364 let mut cur = img
  365. 365 let mut res : (Bytes, Int32)? = None
  366. 366 let mut tries = 0
  367. 367 while res is None && tries < 5 {
  368. 368● let attempt = Some(encode_fit(cur, fmt0, opts.quality, opts.max_bytes)) catch {
  369. 369● @types.ImageError::Process(@types.ErrorCode::LimitBytes, _) => None
  370. 370○ e => raise e
  371. 371 }
  372. 372● match attempt {
  373. 373● Some(v) => res = Some(v)
  374. 374● None => {
  375. 375 // 质量已到底仍装不下:按 4/5 缩长边再来一次(thumb 的语义就是"缩到装得下")
  376. 376 if opts.max_bytes <= 0 {
  377. 377○ break
  378. 378 }
  379. 379◐ let side = if cur.width >= cur.height { cur.width } else { cur.height }
  380. 380 let next = side * 4 / 5
  381. 381 if next < 16 || next >= side {
  382. 382○ break
  383. 383 }
  384. 384● let (nw, nh) = fit_longest(cur, next)
  385. 385● cur = @transform.resize_to_contain(
  386. 386 cur,
  387. 387 nw,
  388. 388 nh,
  389. 389● Array::make(cur.channels, (255 : Byte)),
  390. 390 ) catch {
  391. 391○ e => raise @types.image_error_from_load(e)
  392. 392 }
  393. 393● steps.push({
  394. 394 name: "resize",
  395. 395 note: "fit-budget",
  396. 396 width: cur.width,
  397. 397 height: cur.height,
  398. 398 bytes: -1,
  399. 399● ms: seg_ms(),
  400. 400 })
  401. 401 tries = tries + 1
  402. 402 }
  403. 403 }
  404. 404 }
  405. 405● match res {
  406. 406● Some((b, q0)) => {
  407. 407● steps.push({
  408. 408 name: "encode",
  409. 409 note: "quality=\{q0}",
  410. 410 width: cur.width,
  411. 411 height: cur.height,
  412. 412● bytes: b.length().to_int(),
  413. 413● ms: seg_ms(),
  414. 414 })
  415. 415 {
  416. 416 recipe: "thumb",
  417. 417 image: cur,
  418. 418 bytes: b,
  419. 419 format: fmt0,
  420. 420 steps,
  421. 421 quality: q0,
  422. 422 redacted: 0,
  423. 423 blurred: false,
  424. 424 codes: [],
  425. 425 }
  426. 426 }
  427. 427● None => {
  428. 428● let n0 = @lib.save_image_with_quality(cur, fmt0, 1) catch {
  429. 429○ e => raise @types.image_error_from_load(e)
  430. 430 }
  431. 431 raise @types.ImageError::Process(
  432. 432 @types.ErrorCode::LimitBytes,
  433. 433 "缩到 \{cur.width}x\{cur.height} 且质量 1 仍有 \{n0.length().to_int()} 字节,超过上限 \{opts.max_bytes}:换格式或调高上限",
  434. 434 )
  435. 435 }
  436. 436 }
  437. 437}
  438. 438
  439. 439///|
  440. 440/// avatar:先按中心取正方形,再缩到目标边长(`longest` 即边长,0 默认 256)。
  441. 441fn recipe_avatar(
  442. 442 data : Bytes,
  443. 443 opts : RecipeOpts,
  444. 444) -> RecipeResult raise @types.ImageError {
  445. 445● let steps : Array[StepRec] = []
  446. 446● let mut img = step_decode(data, steps)
  447. 447◐ let side = if img.width < img.height { img.width } else { img.height }
  448. 448 let ox = (img.width - side) / 2
  449. 449 let oy = (img.height - side) / 2
  450. 450 if side != img.width || side != img.height {
  451. 451● img = @transform.crop(img, ox, oy, side, side) catch {
  452. 452○ e => raise @types.image_error_from_load(e)
  453. 453 }
  454. 454● steps.push({
  455. 455 name: "crop",
  456. 456 note: "center",
  457. 457 width: side,
  458. 458 height: side,
  459. 459 bytes: -1,
  460. 460● ms: seg_ms(),
  461. 461 })
  462. 462 }
  463. 463● let target = if opts.longest <= 0 { 256 } else { opts.longest }
  464. 464 if target != side {
  465. 465● img = @transform.resize_to_cover(img, target, target) catch {
  466. 466○ e => raise @types.image_error_from_load(e)
  467. 467 }
  468. 468● steps.push({
  469. 469 name: "resize",
  470. 470 note: "",
  471. 471 width: target,
  472. 472 height: target,
  473. 473 bytes: -1,
  474. 474● ms: seg_ms(),
  475. 475 })
  476. 476 }
  477. 477● let fmt0 = pick_format(img, opts.format)
  478. 478● let (bytes, q) = step_encode(img, fmt0, opts.quality, opts.max_bytes, steps)
  479. 479 {
  480. 480 recipe: "avatar",
  481. 481 image: img,
  482. 482 bytes,
  483. 483 format: fmt0,
  484. 484 steps,
  485. 485 quality: q,
  486. 486 redacted: 0,
  487. 487 blurred: false,
  488. 488 codes: [],
  489. 489 }
  490. 490}
  491. 491
  492. 492///|
  493. 493/// 统一入口:名字 → 实现。未知名字报 `invalid_argument` 并列出可用名,
  494. 494/// 不返回空结果(空结果会让调用方以为"处理成功了但输出为空")。
  495. 495pub fn run_recipe(
  496. 496 name : String,
  497. 497 data : Bytes,
  498. 498 opts : RecipeOpts,
  499. 499) -> RecipeResult raise @types.ImageError {
  500. 500● rc_seg_start()
  501. 501● match name {
  502. 502● "sanitize" => recipe_sanitize(data, opts)
  503. 503● "thumb" => recipe_thumb(data, opts)
  504. 504● "avatar" => recipe_avatar(data, opts)
  505. 505● "code-intake" => recipe_code_intake(data, opts)
  506. 506● "thumb-batch" => recipe_thumb_batch(data, opts)
  507. 507● "doc-scan" => recipe_doc_scan(data, opts)
  508. 508● "ecom-white" => recipe_ecom_white(data, opts)
  509. 509● "redact-id" => recipe_redact_id(data, opts)
  510. 510● _ => {
  511. 511 let mut names = ""
  512. 512● let all = recipe_names()
  513. 513● for i in 0..<all.length() {
  514. 514● if i > 0 {
  515. 515● names = names + ", "
  516. 516 }
  517. 517 names = names + all[i]
  518. 518 }
  519. 519 raise @types.ImageError::Process(
  520. 520 @types.ErrorCode::InvalidArgument,
  521. 521 "未知 recipe: \{name}(可用: \{names})",
  522. 522 )
  523. 523 }
  524. 524 }
  525. 525}