imgcli\cli_recipe.mbt

98.5% · 263 / 267 points · 366 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/// `imgtool recipe <name> <in> <out>` —— Recipe 层的 CLI 出口。
  3. 3///
  4. 4/// 与 `sanitize` 子命令的分工:`sanitize` 是这条业务的历史 CLI 实现(自己解码、自己打码、
  5. 5/// 自己选格式),`recipe` 走库层 `image.pro` 的注册表与执行器,因此 native / wasm / MCP
  6. 6/// 拿到的步骤回执与 CLI 完全同源。两条并存到 S24 收口,届时 `sanitize` 改为委托。
  7. 7
  8. 8///|
  9. 9fn to_type_regions(rs : Array[Region]) -> Array[@types.Region] {
  10. 10● let out : Array[@types.Region] = []
  11. 11 for r in rs {
  12. 12● out.push({ x: r.x, y: r.y, w: r.w, h: r.h, })
  13. 13 }
  14. 14 out
  15. 15}
  16. 16
  17. 17///|
  18. 18
  19. 19///|
  20. 20/// 毫秒截到 1 微秒(三位小数):`monotonic_clock` 的 Double 带 16 位尾巴,回执里不需要。
  21. 21fn ms3(v : Double) -> Double {
  22. 22● let n = (v * 1000.0 + 0.5).to_int()
  23. 23● n.to_double() / 1000.0
  24. 24}
  25. 25
  26. 26///|
  27. 27fn recipe_steps_json(steps : Array[@recipe.StepRec]) -> @json.Json {
  28. 28● let items : Array[@json.Json] = []
  29. 29 for s in steps {
  30. 30● let item : Out = {
  31. 31● "step": jstr(s.name),
  32. 32● "note": jstr(s.note),
  33. 33● "width": jnum(s.width),
  34. 34● "height": jnum(s.height),
  35. 35● "bytes": jnum(s.bytes),
  36. 36● "ms": @json.Json::number(ms3(s.ms)),
  37. 37 }
  38. 38● items.push(@json.Json::object(item))
  39. 39 }
  40. 40● @json.Json::array(items)
  41. 41}
  42. 42
  43. 43///|
  44. 44/// `code-intake` 的产物:命中数组。其余 Recipe 恒为空数组,仍照常输出以保持字段稳定。
  45. 45fn recipe_codes_json(codes : Array[@recipe.CodeHit]) -> @json.Json {
  46. 46● let items : Array[@json.Json] = []
  47. 47 for c in codes {
  48. 48● let item : Out = {
  49. 49● "kind": jstr(c.kind),
  50. 50● "data": jstr(c.data),
  51. 51● "confidence": @json.Json::number(c.confidence),
  52. 52● "x": jnum(c.x),
  53. 53● "y": jnum(c.y),
  54. 54● "width": jnum(c.width),
  55. 55● "height": jnum(c.height),
  56. 56 }
  57. 57● items.push(@json.Json::object(item))
  58. 58 }
  59. 59● @json.Json::array(items)
  60. 60}
  61. 61
  62. 62///|
  63. 63fn plan_steps_json(steps : Array[@recipe.PlanStep]) -> @json.Json {
  64. 64● let items : Array[@json.Json] = []
  65. 65 for s in steps {
  66. 66● let item : Out = {
  67. 67● "step": jstr(s.name),
  68. 68● "note": jstr(s.note),
  69. 69● "width": jnum(s.width),
  70. 70● "height": jnum(s.height),
  71. 71 }
  72. 72● items.push(@json.Json::object(item))
  73. 73 }
  74. 74● @json.Json::array(items)
  75. 75}
  76. 76
  77. 77///|
  78. 78/// 计划回执:`--dry-run` 的主出口,只读容器头,不解像素。
  79. 79fn plan_body(p : @recipe.RecipePlan, dst : String) -> Out {
  80. 80● {
  81. 81● "src_format": jstr(p.src_format),
  82. 82● "src_width": jnum(p.src_width),
  83. 83● "src_height": jnum(p.src_height),
  84. 84● "src_channels": jnum(p.src_channels),
  85. 85● "out_width": jnum(p.out_width),
  86. 86● "out_height": jnum(p.out_height),
  87. 87● "steps": plan_steps_json(p.steps),
  88. 88● "step_count": jnum(p.steps.length()),
  89. 89● "decode_pixels": jnum(p.decode_pixels.to_int()),
  90. 90● "peak_frame_bytes": jnum(p.peak_frame_bytes.to_int()),
  91. 91● "budget": @json.Json::object({
  92. 92● "axis": jstr(p.budget_axis),
  93. 93● "max_bytes": jnum(p.budget_bytes),
  94. 94● "solve": jstr(if p.budget_axis == "" { "none" } else { "runtime" }),
  95. 95● "check": jstr(if p.budget_axis == "" { "none" } else { "deferred" }),
  96. 96 }),
  97. 97● "dst": jstr(dst),
  98. 98● "will_write": jbool(dst != ""),
  99. 99 }
  100. 100}
  101. 101
  102. 102///|
  103. 103fn cmd_recipe(flags : Flags) -> Out raise @types.ImageError {
  104. 104● let pos = flags.positional
  105. 105● if pos.length() < 2 {
  106. 106● raise @types.ImageError::Process(
  107. 107 @types.ErrorCode::InvalidArgument,
  108. 108 "用法: imgtool recipe <sanitize|thumb|avatar|code-intake|thumb-batch|doc-scan|ecom-white|redact-id> <in> [out] [--longest N] [--max-bytes N] [--quality N] [--policy metadata|standard|strict] [--block N] [--region x,y,w,h;...] [--dry-run|--preview]",
  109. 109 )
  110. 110 }
  111. 111 let name = pos[0]
  112. 112 if name == "thumb-batch" {
  113. 113● return cmd_recipe_batch(pos, flags)
  114. 114 }
  115. 115 let src = pos[1]
  116. 116● let dst = if pos.length() >= 3 { pos[2] } else { "" }
  117. 117● let raw_regions = match flags.values.get("regions") {
  118. 118● Some(v) => v
  119. 119 None =>
  120. 120● match flags.values.get("region") {
  121. 121● Some(v) => v
  122. 122● None => ""
  123. 123 }
  124. 124 }
  125. 125 let opts : @recipe.RecipeOpts = {
  126. 126● format: out_format(flags, dst, @types.ImageFormat::Unknown),
  127. 127● longest: flags.int("longest", 0),
  128. 128● max_bytes: flags.int("max-bytes", 0),
  129. 129● quality: flags.int("quality", 85),
  130. 130 block: if name == "ecom-white" {
  131. 131● flags.int("tol", 36)
  132. 132 } else {
  133. 133● flags.int("block", 8)
  134. 134 },
  135. 135● blur_radius: flags.int("blur", 0),
  136. 136● policy: flags.str("policy", "standard"),
  137. 137● regions: to_type_regions(parse_regions(raw_regions)),
  138. 138 }
  139. 139● let input = src_bytes(src)
  140. 140● let dry = flags.has("dry-run")
  141. 141● let preview = flags.has("preview")
  142. 142 // 两种"不落盘":plan(不解码)与 preview(真跑不写),写盘判定统一走 no_write
  143. 143 let no_write = dry || preview
  144. 144 // `--dry-run` 只出计划(毫秒级,不解码);`--preview` 是"真跑不写"(要真字节就得付解码代价)
  145. 145 if dry && !preview {
  146. 146● let p = @recipe.plan_recipe(name, input, opts)
  147. 147● let plan : Out = plan_body(p, dst)
  148. 148● plan["recipe"] = jstr(p.recipe)
  149. 149● plan["about"] = jstr(@recipe.recipe_about(p.recipe))
  150. 150● plan["src"] = jstr(src)
  151. 151● plan["mode"] = jstr("plan")
  152. 152● plan["dry_run"] = jbool(true)
  153. 153● plan["wrote"] = jbool(false)
  154. 154● return result(plan)
  155. 155 }
  156. 156● let res = @recipe.run_recipe(name, input, opts)
  157. 157 // code-intake 不改像素:没给 out 就别落盘,给了 out 才写原字节
  158. 158 let to_stdout = if dst == "" {
  159. 159● false
  160. 160 } else {
  161. 161● emit_bytes(dst, res.bytes, no_write)
  162. 162 }
  163. 163● result({
  164. 164● "recipe": jstr(res.recipe),
  165. 165● "about": jstr(@recipe.recipe_about(res.recipe)),
  166. 166● "src": jstr(src),
  167. 167● "dst": jstr(dst),
  168. 168● "format": jstr(format_name(res.format)),
  169. 169● "bytes": jnum(res.bytes.length().to_int()),
  170. 170● "width": jnum(res.image.width),
  171. 171● "height": jnum(res.image.height),
  172. 172● "channels": jnum(res.image.channels),
  173. 173● "quality": jnum(res.quality),
  174. 174● "policy": jstr(opts.policy),
  175. 175● "max_bytes": jnum(opts.max_bytes),
  176. 176● "steps": recipe_steps_json(res.steps),
  177. 177● "code_count": jnum(res.codes.length()),
  178. 178● "codes": recipe_codes_json(res.codes),
  179. 179 // 脱敏块数与是否整图模糊:sanitize / redact-id 的验收口径,其它 Recipe 恒 0 / false
  180. 180● "redacted": jnum(res.redacted),
  181. 181● "blurred": jbool(res.blurred),
  182. 182● "mode": jstr(if no_write { "preview" } else { "apply" }),
  183. 183● "dry_run": jbool(no_write),
  184. 184● "wrote": jbool(!no_write && dst != ""),
  185. 185● "to_stdout": jbool(to_stdout),
  186. 186 })
  187. 187}
  188. 188
  189. 189///|
  190. 190/// `imgtool recipes` —— 列出注册表,给 agent 发现能力用(不读文件、不需要输入)。
  191. 191fn cmd_recipes(_flags : Flags) -> Out {
  192. 192● let items : Array[@json.Json] = []
  193. 193● for n in @recipe.recipe_names() {
  194. 194● let item : Out = { "name": jstr(n), "about": jstr(@recipe.recipe_about(n)) }
  195. 195● items.push(@json.Json::object(item))
  196. 196 }
  197. 197● result({
  198. 198● "count": jnum(@recipe.recipe_names().length()),
  199. 199● "recipes": @json.Json::array(items),
  200. 200 })
  201. 201}
  202. 202
  203. 203///|
  204. 204/// 取路径的文件名主干(去目录、去最后一个扩展名)。批量落盘要按原文件名派生输出名。
  205. 205fn stem_of(path : String) -> String {
  206. 206● let n = path.length()
  207. 207 let mut last_sep = -1
  208. 208 for i in 0..<n {
  209. 209● let c = path[i]
  210. 210 if c == '/' || c == '\\' {
  211. 211● last_sep = i
  212. 212 }
  213. 213 }
  214. 214 let start = last_sep + 1
  215. 215 let mut dot = n
  216. 216 for i in start..<n {
  217. 217● if path[i] == '.' {
  218. 218● dot = i
  219. 219 }
  220. 220 }
  221. 221● path[start:dot].to_owned()
  222. 222}
  223. 223
  224. 224///|
  225. 225/// 批量落盘的输出路径:`<out-dir>/<原名主干><suffix>.<ext>`,`out-dir` 为空或是 `.` 时留在当前目录。
  226. 226fn out_path_of(
  227. 227 out_dir : String,
  228. 228 suffix : String,
  229. 229 name : String,
  230. 230 ext : String,
  231. 231) -> String {
  232. 232● let file = stem_of(name) + suffix + "." + ext
  233. 233 if out_dir == "." || out_dir == "" {
  234. 234● file
  235. 235● } else if out_dir.has_suffix("\\") || out_dir.has_suffix("/") {
  236. 236● out_dir + file
  237. 237 } else {
  238. 238● out_dir + "\\" + file
  239. 239 }
  240. 240}
  241. 241
  242. 242///|
  243. 243/// `imgtool recipe thumb-batch <in...> [--out-dir DIR] [--suffix _t]` —— 多图批量缩略。
  244. 244///
  245. 245/// 不给 `--out-dir` 就只出回执(不落盘),避免"调一次批量顺手写一堆文件"。
  246. 246/// 给了则每张落到 `<out-dir>/<原名主干><suffix>.<格式扩展名>`。
  247. 247/// `--dry-run` 逐张出计划(不落盘、不解像素);`--preview` 真跑一遍但不写。
  248. 248fn cmd_recipe_batch(
  249. 249 pos : Array[String],
  250. 250 flags : Flags,
  251. 251) -> Out raise @types.ImageError {
  252. 252● if pos.length() < 2 {
  253. 253○ raise @types.ImageError::Process(
  254. 254 @types.ErrorCode::InvalidArgument,
  255. 255 "用法: imgtool recipe thumb-batch <in...> [--out-dir DIR] [--suffix _t] [--longest N] [--max-bytes N] [--quality N] [--format X] [--dry-run|--preview]",
  256. 256 )
  257. 257 }
  258. 258● let out_dir = flags.str("out-dir", "")
  259. 259● let suffix = flags.str("suffix", "_t")
  260. 260● let dry = flags.has("dry-run")
  261. 261● let preview = flags.has("preview")
  262. 262 // 两种"不落盘":plan(不解码)与 preview(真跑不写),写盘判定统一走 no_write
  263. 263 let no_write = dry || preview
  264. 264● let fmt = out_format(flags, "", @types.ImageFormat::Unknown)
  265. 265 let opts : @recipe.RecipeOpts = {
  266. 266 format: fmt,
  267. 267● longest: flags.int("longest", 0),
  268. 268● max_bytes: flags.int("max-bytes", 0),
  269. 269● quality: flags.int("quality", 85),
  270. 270● block: flags.int("block", 8),
  271. 271● blur_radius: flags.int("blur", 0),
  272. 272● policy: flags.str("policy", "standard"),
  273. 273 regions: [],
  274. 274 }
  275. 275 let inputs : Array[(String, Bytes)] = []
  276. 276● for i in 1..<pos.length() {
  277. 277● inputs.push((pos[i], src_bytes(pos[i])))
  278. 278 }
  279. 279 if dry && !preview {
  280. 280 // 计划模式:逐张只读头。扩展名在 `--format` 未指定时按 PNG 猜(标 ext_guess)
  281. 281● let guess = fmt == @types.ImageFormat::Unknown
  282. 282● let ext0 = if guess { "png" } else { format_name(fmt) }
  283. 283 let items : Array[@json.Json] = []
  284. 284 let mut px_sum : Int64 = 0
  285. 285 let mut px_peak : Int64 = 0
  286. 286 for inp in inputs {
  287. 287● let p = @recipe.plan_recipe("thumb", inp.1, opts)
  288. 288 px_sum = px_sum + p.decode_pixels
  289. 289 if p.decode_pixels > px_peak {
  290. 290● px_peak = p.decode_pixels
  291. 291 }
  292. 292 let item : Out = {
  293. 293● "name": jstr(inp.0),
  294. 294● "out": jstr(out_path_of(out_dir, suffix, inp.0, ext0)),
  295. 295● "ext_guess": jbool(guess),
  296. 296● "src_format": jstr(p.src_format),
  297. 297● "src_width": jnum(p.src_width),
  298. 298● "src_height": jnum(p.src_height),
  299. 299● "out_width": jnum(p.out_width),
  300. 300● "out_height": jnum(p.out_height),
  301. 301● "steps": plan_steps_json(p.steps),
  302. 302● "decode_pixels": jnum(p.decode_pixels.to_int()),
  303. 303 }
  304. 304● items.push(@json.Json::object(item))
  305. 305 }
  306. 306 let plan : Out = {
  307. 307● "recipe": jstr("thumb-batch"),
  308. 308● "about": jstr(@recipe.recipe_about("thumb-batch")),
  309. 309● "mode": jstr("plan"),
  310. 310● "count": jnum(inputs.length()),
  311. 311● "out_dir": jstr(out_dir),
  312. 312● "suffix": jstr(suffix),
  313. 313● "peak_frame_pixels": jnum(px_peak.to_int()),
  314. 314● "total_decode_pixels": jnum(px_sum.to_int()),
  315. 315● "max_bytes": jnum(opts.max_bytes),
  316. 316◐ "budget_solve": jstr(if opts.max_bytes > 0 { "runtime" } else { "none" }),
  317. 317● "items": @json.Json::array(items),
  318. 318● "dry_run": jbool(true),
  319. 319● "wrote": jbool(false),
  320. 320● "written": jnum(0),
  321. 321● "will_write": jbool(out_dir != ""),
  322. 322 }
  323. 323● return result(plan)
  324. 324 }
  325. 325● let batch = @recipe.run_thumb_batch(inputs, opts)
  326. 326 let write = out_dir != "" && !no_write
  327. 327 if write {
  328. 328● ensure_dir(out_dir)
  329. 329 }
  330. 330 let items : Array[@json.Json] = []
  331. 331 for it in batch.items {
  332. 332● let ext = format_name(it.format)
  333. 333● let path = out_path_of(out_dir, suffix, it.name, ext)
  334. 334 if write {
  335. 335● write_bytes(path, it.bytes)
  336. 336 }
  337. 337 let item : Out = {
  338. 338● "name": jstr(it.name),
  339. 339● "out": jstr(path),
  340. 340● "format": jstr(ext),
  341. 341● "width": jnum(it.width),
  342. 342● "height": jnum(it.height),
  343. 343● "src_width": jnum(it.src_width),
  344. 344● "src_height": jnum(it.src_height),
  345. 345● "quality": jnum(it.quality),
  346. 346● "bytes": jnum(it.bytes.length().to_int()),
  347. 347● "steps": recipe_steps_json(it.steps),
  348. 348 }
  349. 349● items.push(@json.Json::object(item))
  350. 350 }
  351. 351● result({
  352. 352● "recipe": jstr("thumb-batch"),
  353. 353● "about": jstr(@recipe.recipe_about("thumb-batch")),
  354. 354◐ "mode": jstr(if no_write { "preview" } else { "apply" }),
  355. 355● "count": jnum(batch.items.length()),
  356. 356● "out_dir": jstr(out_dir),
  357. 357● "suffix": jstr(suffix),
  358. 358● "total_in_bytes": jnum(batch.total_in_bytes),
  359. 359● "total_out_bytes": jnum(batch.total_out_bytes),
  360. 360● "peak_frame_pixels": jnum(batch.peak_frame_pixels),
  361. 361● "items": @json.Json::array(items),
  362. 362● "dry_run": jbool(no_write),
  363. 363● "wrote": jbool(write),
  364. 364◐ "written": jnum(if write { batch.items.length() } else { 0 }),
  365. 365 })
  366. 366}