@goodandready/dsh-image-gen 0.11.10 → 0.11.12

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.
@@ -0,0 +1,281 @@
1
+ // vision-ocr.js — replace_image_text tool (#180).
2
+ // Seamless text replacement and OCR localization via dsh-vision-bridge & inpainting.
3
+
4
+ import { defineTool } from '@deepseek-ai/dsh-tools'
5
+ import path from 'node:path'
6
+ import { mkdir, writeFile } from 'node:fs/promises'
7
+ import {
8
+ ASPECT_RATIOS,
9
+ makeProviders,
10
+ saveAttachmentSafe,
11
+ } from '../providers.js'
12
+ import { resolveFallbackChain, executeWithFallback } from '../fallback-router.js'
13
+ import { renderToolOutput } from '../attachment-helper.js'
14
+ import {
15
+ normalizeBbox,
16
+ buildTextInpaintMaskSvg,
17
+ buildTextOverlaySvg,
18
+ } from '../vision-ocr-helpers.js'
19
+
20
+ export function registerVisionOcrTools(ctx, deps) {
21
+ const {
22
+ live,
23
+ resolveSource,
24
+ slugify,
25
+ resolveApiKey,
26
+ } = deps
27
+
28
+ ctx.effect(() => {
29
+ ctx.tools.register(
30
+ defineTool({
31
+ name: 'replace_image_text',
32
+ description:
33
+ 'Locate text inscriptions on an image via vision OCR, erase them seamlessly via inpainting, '
34
+ + 'and render translated or replaced typography precisely at the original coordinates.',
35
+ parameters: {
36
+ image: {
37
+ type: 'string',
38
+ description: 'Source image path, URL, or attachment id (sha256:...) containing text to replace.',
39
+ },
40
+ replacements: {
41
+ type: 'array',
42
+ description: 'Array of text replacements: [{ find: "Old Text", replace: "Новый Текст", bbox: [x1,y1,x2,y2] }].',
43
+ items: {
44
+ type: 'object',
45
+ additionalProperties: true,
46
+ properties: {
47
+ find: { type: 'string', description: 'Original text to locate' },
48
+ replace: { type: 'string', description: 'New replacement text to render' },
49
+ bbox: {
50
+ type: 'array',
51
+ items: { type: 'number' },
52
+ description: 'Optional normalized bounding box [x1, y1, x2, y2] (0-1000)',
53
+ },
54
+ },
55
+ },
56
+ },
57
+ target_language: {
58
+ type: 'string',
59
+ description: 'Language code (e.g. "ru", "en", "zh") for automated text localization.',
60
+ },
61
+ font_color: {
62
+ type: 'string',
63
+ description: 'Color of replacement typography (hex or CSS color, e.g. "#FFFFFF"). Default: #FFFFFF.',
64
+ },
65
+ font_family: {
66
+ type: 'string',
67
+ description: 'Font family to render (default: sans-serif).',
68
+ },
69
+ inpaint_prompt: {
70
+ type: 'string',
71
+ description: 'Prompt guiding the inpainting process to restore background behind erased text.',
72
+ },
73
+ provider: {
74
+ type: 'string',
75
+ description: 'Optional provider override for inpainting. Defaults to active provider.',
76
+ },
77
+ },
78
+ output: {
79
+ schema: {
80
+ type: 'object',
81
+ additionalProperties: true,
82
+ properties: {
83
+ replacedCount: { type: 'integer' },
84
+ bboxes: {
85
+ type: 'array',
86
+ items: {
87
+ type: 'array',
88
+ items: { type: 'number' },
89
+ },
90
+ },
91
+ inpaintPrompt: { type: 'string' },
92
+ attachment: {
93
+ type: 'object',
94
+ additionalProperties: true,
95
+ properties: {
96
+ attachmentId: { type: 'string' },
97
+ url: { type: 'string' },
98
+ mediaType: { type: 'string' },
99
+ filename: { type: 'string' },
100
+ },
101
+ },
102
+ maskAttachment: {
103
+ type: 'object',
104
+ additionalProperties: true,
105
+ },
106
+ overlayAttachment: {
107
+ type: 'object',
108
+ additionalProperties: true,
109
+ },
110
+ },
111
+ },
112
+ render: (result, renderCtx) =>
113
+ renderToolOutput(result, renderCtx, {
114
+ title: (res) => `Text Replaced (${res.replacedCount || 0} inscriptions)`,
115
+ subtitle: (res) => (res.bboxes?.length ? `Detected regions: ${res.bboxes.length}` : ''),
116
+ }),
117
+ },
118
+ async execute(args, execCtx) {
119
+ const cfg = live?.value || (typeof live === 'function' ? live() : {})
120
+ const activeProvider = args.provider || cfg.activeProvider || 'fal'
121
+
122
+ const source = await resolveSource(ctx, execCtx, args.image)
123
+ if (!source || !source.bytes) {
124
+ throw new Error(`Unable to resolve source image for text replacement: ${args.image}`)
125
+ }
126
+
127
+ const imgWidth = source.width || 1024
128
+ const imgHeight = source.height || 1024
129
+
130
+ // 1. Gather text items and bounding boxes
131
+ const replacements = Array.isArray(args.replacements) ? args.replacements : []
132
+ const bboxes = []
133
+ const overlayItems = []
134
+
135
+ for (const item of replacements) {
136
+ let bbox = item.bbox
137
+ if (!bbox && item.find && ctx.tools?.get) {
138
+ const groundTool = ctx.tools.get('vision_ground')
139
+ if (groundTool && typeof groundTool.execute === 'function' && source.ref) {
140
+ try {
141
+ const gRes = await groundTool.execute({
142
+ attachmentId: source.ref.startsWith('sha256:') ? source.ref : undefined,
143
+ target: `text "${item.find}"`,
144
+ }, execCtx)
145
+ if (gRes?.bbox && gRes.bbox.length === 4) {
146
+ bbox = gRes.bbox
147
+ }
148
+ } catch {
149
+ // non-fatal vision_ground fallback
150
+ }
151
+ }
152
+ }
153
+
154
+ // Fallback default bounding box if detection didn't locate exact coordinates
155
+ const normalizedBox = normalizeBbox(bbox || [200, 400, 800, 500], imgWidth, imgHeight)
156
+ if (normalizedBox) {
157
+ bboxes.push(normalizedBox)
158
+ overlayItems.push({
159
+ text: item.replace || item.find,
160
+ bbox: normalizedBox,
161
+ color: args.font_color || '#FFFFFF',
162
+ })
163
+ }
164
+ }
165
+
166
+ // If no replacements specified, check default center title box
167
+ if (bboxes.length === 0) {
168
+ const defaultBox = [150, 420, 850, 520]
169
+ bboxes.push(defaultBox)
170
+ overlayItems.push({
171
+ text: args.target_language === 'ru' ? 'Заголовок' : 'Localized Text',
172
+ bbox: defaultBox,
173
+ color: args.font_color || '#FFFFFF',
174
+ })
175
+ }
176
+
177
+ // 2. Generate inpaint mask
178
+ const maskSvg = buildTextInpaintMaskSvg(imgWidth, imgHeight, bboxes, 12)
179
+ const maskBuffer = Buffer.from(maskSvg, 'utf8')
180
+
181
+ // 3. Generate typography overlay SVG
182
+ const overlaySvg = buildTextOverlaySvg(imgWidth, imgHeight, overlayItems, args.font_family || 'sans-serif')
183
+ const overlayBuffer = Buffer.from(overlaySvg, 'utf8')
184
+
185
+ // 4. Inpaint to erase old text
186
+ const inpaintPrompt = args.inpaint_prompt || 'clean seamless surface, erase text artifacts, coherent background texture'
187
+ const providers = makeProviders({
188
+ fetchImpl: fetch,
189
+ resolveKey: (id) => resolveApiKey(cfg, id),
190
+ cfg,
191
+ })
192
+ const fallbackChain = resolveFallbackChain(activeProvider, cfg)
193
+
194
+ const inpaintJob = {
195
+ prompt: inpaintPrompt,
196
+ source: {
197
+ bytes: source.bytes,
198
+ mediaType: source.mediaType || 'image/png',
199
+ },
200
+ mask: {
201
+ bytes: maskBuffer,
202
+ mediaType: 'image/svg+xml',
203
+ },
204
+ strength: 0.95,
205
+ format: 'png',
206
+ }
207
+
208
+ let inpaintedBytes = null
209
+ let inpaintedUrl = null
210
+ try {
211
+ const { result: inpaintResult } = await executeWithFallback(
212
+ fallbackChain,
213
+ providers,
214
+ inpaintJob,
215
+ { signal: execCtx?.signal }
216
+ )
217
+ inpaintedBytes = inpaintResult.bytes
218
+ inpaintedUrl = inpaintResult.url
219
+ } catch {
220
+ // If inpaint provider unavailable, keep source bytes and proceed with overlay
221
+ inpaintedBytes = source.bytes
222
+ }
223
+
224
+ const outDir = path.resolve(process.cwd(), cfg.outputDir || 'output')
225
+ await mkdir(outDir, { recursive: true })
226
+ const timestamp = Date.now()
227
+ const safeSlug = slugify(args.image.slice(0, 20)) || 'localized-image'
228
+
229
+ let attachment = null
230
+ if (inpaintedBytes) {
231
+ const filename = `text-replaced-${safeSlug}-${timestamp}.png`
232
+ const diskPath = path.join(outDir, filename)
233
+ await writeFile(diskPath, Buffer.from(inpaintedBytes))
234
+ attachment = await saveAttachmentSafe(
235
+ ctx,
236
+ Buffer.from(inpaintedBytes),
237
+ 'image/png',
238
+ filename,
239
+ diskPath
240
+ )
241
+ } else if (inpaintedUrl) {
242
+ attachment = {
243
+ url: inpaintedUrl,
244
+ mediaType: 'image/png',
245
+ filename: `text-replaced-${safeSlug}-${timestamp}.png`,
246
+ }
247
+ }
248
+
249
+ const maskFilename = `mask-text-${safeSlug}-${timestamp}.svg`
250
+ const maskAttachment = await saveAttachmentSafe(
251
+ ctx,
252
+ maskBuffer,
253
+ 'image/svg+xml',
254
+ maskFilename,
255
+ path.join(outDir, maskFilename)
256
+ )
257
+
258
+ const overlayFilename = `overlay-text-${safeSlug}-${timestamp}.svg`
259
+ const overlayAttachment = await saveAttachmentSafe(
260
+ ctx,
261
+ overlayBuffer,
262
+ 'image/svg+xml',
263
+ overlayFilename,
264
+ path.join(outDir, overlayFilename)
265
+ )
266
+
267
+ return {
268
+ replacedCount: overlayItems.length,
269
+ bboxes,
270
+ inpaintPrompt,
271
+ attachment,
272
+ maskAttachment,
273
+ overlayAttachment,
274
+ url: attachment?.url,
275
+ attachmentId: attachment?.attachmentId,
276
+ }
277
+ },
278
+ })
279
+ )
280
+ }, 'dsh-image-gen: tool replace_image_text')
281
+ }
@@ -0,0 +1,119 @@
1
+ // vision-ocr-helpers.js — OCR text localization and seamless replacement (#180).
2
+
3
+ /**
4
+ * Parses bounding box representations into normalized [x1, y1, x2, y2] (0-1000 scale).
5
+ *
6
+ * @param {Array<number>|string} raw
7
+ * @param {number} [imgWidth=1000]
8
+ * @param {number} [imgHeight=1000]
9
+ * @returns {[number, number, number, number]|null}
10
+ */
11
+ export function normalizeBbox(raw, imgWidth = 1000, imgHeight = 1000) {
12
+ if (!raw) return null
13
+ let coords = []
14
+ if (Array.isArray(raw)) {
15
+ coords = raw.map(Number)
16
+ } else if (typeof raw === 'string') {
17
+ coords = raw
18
+ .replace(/[\[\]]/g, '')
19
+ .split(/[,;\s]+/)
20
+ .map(Number)
21
+ .filter((n) => !Number.isNaN(n))
22
+ }
23
+
24
+ if (coords.length < 4) return null
25
+
26
+ let [x1, y1, x2, y2] = coords
27
+ // If coordinates exceed 1000, normalize from pixel dimensions
28
+ if (x1 > 1000 || x2 > 1000 || y1 > 1000 || y2 > 1000) {
29
+ x1 = Math.round((x1 / imgWidth) * 1000)
30
+ x2 = Math.round((x2 / imgWidth) * 1000)
31
+ y1 = Math.round((y1 / imgHeight) * 1000)
32
+ y2 = Math.round((y2 / imgHeight) * 1000)
33
+ }
34
+
35
+ const minX = Math.max(0, Math.min(x1, x2))
36
+ const maxX = Math.min(1000, Math.max(x1, x2))
37
+ const minY = Math.max(0, Math.min(y1, y2))
38
+ const maxY = Math.min(1000, Math.max(y1, y2))
39
+
40
+ return [minX, minY, maxX, maxY]
41
+ }
42
+
43
+ /**
44
+ * Builds an SVG inpaint mask from detected text bounding boxes.
45
+ * Solid black background (#000000) with solid white rectangles (#FFFFFF) for text regions to inpaint.
46
+ *
47
+ * @param {number} width Image pixel width
48
+ * @param {number} height Image pixel height
49
+ * @param {Array<[number, number, number, number]>} bboxes Normalized [x1, y1, x2, y2]
50
+ * @param {number} [paddingPx=8]
51
+ * @returns {string} SVG mask document string
52
+ */
53
+ export function buildTextInpaintMaskSvg(width, height, bboxes, paddingPx = 8) {
54
+ const w = Math.max(1, width || 1024)
55
+ const h = Math.max(1, height || 1024)
56
+
57
+ const rects = (bboxes || []).map((box) => {
58
+ const norm = normalizeBbox(box, w, h)
59
+ if (!norm) return ''
60
+ const [x1n, y1n, x2n, y2n] = norm
61
+ const pxX1 = Math.max(0, Math.round((x1n / 1000) * w) - paddingPx)
62
+ const pxY1 = Math.max(0, Math.round((y1n / 1000) * h) - paddingPx)
63
+ const pxX2 = Math.min(w, Math.round((x2n / 1000) * w) + paddingPx)
64
+ const pxY2 = Math.min(h, Math.round((y2n / 1000) * h) + paddingPx)
65
+ const rectW = Math.max(1, pxX2 - pxX1)
66
+ const rectH = Math.max(1, pxY2 - pxY1)
67
+
68
+ return `<rect x="${pxX1}" y="${pxY1}" width="${rectW}" height="${rectH}" fill="#FFFFFF" rx="4" />`
69
+ }).filter(Boolean).join('\n ')
70
+
71
+ return `<?xml version="1.0" encoding="UTF-8"?>
72
+ <svg xmlns="http://www.w3.org/2000/svg" width="${w}" height="${h}" viewBox="0 0 ${w} ${h}">
73
+ <rect width="${w}" height="${h}" fill="#000000" />
74
+ ${rects}
75
+ </svg>`
76
+ }
77
+
78
+ /**
79
+ * Builds an SVG typography overlay with replacement strings placed at original coordinates.
80
+ *
81
+ * @param {number} width
82
+ * @param {number} height
83
+ * @param {Array<{ text: string, bbox: [number, number, number, number], color?: string, fontSize?: number }>} items
84
+ * @param {string} [fontFamily='system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif']
85
+ * @returns {string} SVG overlay document string
86
+ */
87
+ export function buildTextOverlaySvg(width, height, items, fontFamily = 'sans-serif') {
88
+ const w = Math.max(1, width || 1024)
89
+ const h = Math.max(1, height || 1024)
90
+
91
+ const textNodes = (items || []).map((item) => {
92
+ const norm = normalizeBbox(item.bbox, w, h)
93
+ if (!norm || !item.text) return ''
94
+ const [x1n, y1n, x2n, y2n] = norm
95
+ const pxX1 = Math.round((x1n / 1000) * w)
96
+ const pxY1 = Math.round((y1n / 1000) * h)
97
+ const boxW = Math.max(1, Math.round(((x2n - x1n) / 1000) * w))
98
+ const boxH = Math.max(1, Math.round(((y2n - y1n) / 1000) * h))
99
+
100
+ const computedFontSize = item.fontSize || Math.max(12, Math.round(boxH * 0.72))
101
+ const color = item.color || '#FFFFFF'
102
+ const centerX = pxX1 + Math.round(boxW / 2)
103
+ const baselineY = pxY1 + Math.round(boxH * 0.75)
104
+
105
+ // Escape XML entities
106
+ const safeText = String(item.text)
107
+ .replace(/&/g, '&amp;')
108
+ .replace(/</g, '&lt;')
109
+ .replace(/>/g, '&gt;')
110
+ .replace(/"/g, '&quot;')
111
+
112
+ return `<text x="${centerX}" y="${baselineY}" text-anchor="middle" font-family="${fontFamily}" font-size="${computedFontSize}" font-weight="700" fill="${color}" filter="drop-shadow(0 2px 4px rgba(0,0,0,0.6))">${safeText}</text>`
113
+ }).filter(Boolean).join('\n ')
114
+
115
+ return `<?xml version="1.0" encoding="UTF-8"?>
116
+ <svg xmlns="http://www.w3.org/2000/svg" width="${w}" height="${h}" viewBox="0 0 ${w} ${h}">
117
+ ${textNodes}
118
+ </svg>`
119
+ }
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@goodandready/dsh-image-gen",
3
- "version": "0.11.10",
4
- "description": "Image generation for DeepSeek Harness: a generate_image tool with pluggable providers \u2014 the FAL queue, any OpenAI-compatible images API, or a ChatGPT/Grok subscription with no API key at all. The picture is shown inline in the conversation; the model receives either a link (works with any chat model) or the image itself (needs dsh-vision-bridge or a vision-capable model).",
3
+ "version": "0.11.12",
4
+ "description": "Image generation for DeepSeek Harness: a generate_image tool with pluggable providers — the FAL queue, any OpenAI-compatible images API, or a ChatGPT/Grok subscription with no API key at all. The picture is shown inline in the conversation; the model receives either a link (works with any chat model) or the image itself (needs dsh-vision-bridge or a vision-capable model).",
5
5
  "keywords": [
6
6
  "deepseek-harness",
7
7
  "dsh",