The open creative studio on ComfyUI: images, video, 3D and audio on open weights, on your own GPU or the cloud. Camera motions, effects, apps, Cinema, Layers, Image to 3D and an AI agent.
TypeScript ai-videocomfyuicreative-toolsgenerative-aiideogramimage-generationimage-to-3dimage-to-videoltx-videominimax-h3nextjsopen-sourceopen-weightsqwen-imagetext-to-imagevideo-generationwan
OCR: the open engine reads text lines with OvisOCR3, answers parsed into lines and boxes
Claudefad39c86c5a0
diff --git a/src/lib/catalog/models.ts b/src/lib/catalog/models.tsindex 6ab3bd22..ac807e5c 100644--- a/src/lib/catalog/models.ts+++ b/src/lib/catalog/models.ts@@ -224,6 +224,17 @@ const open: ModelDef[] = [],},}),+ o({+ // Layers' Edit text on the open engine (Florence-2 / Ideogram on the cloud): the lines and their boxes.+ id: "oss-ocr-lines",+ name: "OvisOCR3",+ vendor: "ATH-MaaS",+ family: "qwen-llm",+ kind: "text",+ tagline: "Every line of text in an image, with its box · 3 GB GPU · Apache-2.0",+ routes: [comfy("ocr", "ocr-lines-qwen35", "OvisOCR3 0.8B (a Qwen3.5 OCR fine-tune) on core TextGenerate; boxes come back 0–1000")],+ options: { promptless: true, maxImages: 1 },+ }),o({id: "oss-seedvr2-image",name: "SeedVR2 (image)",diff --git a/src/lib/ocr.ts b/src/lib/ocr.tsnew file mode 100644index 00000000..acc59861--- /dev/null+++ b/src/lib/ocr.ts@@ -0,0 +1,170 @@+/**+ * Reading what an open OCR model answers (`ocr-lines-qwen35`: OvisOCR3 or a Qwen3.5 checkpoint through+ * ComfyUI's TextGenerate) into Fuobe's OCR output: `OutputFile.text` = the lines, `meta.lines` =+ * `[{text, bbox: [x, y, w, h]}]` as fractions of the image (what Florence-2's cloud route gives too).+ *+ * The models are asked for a bare JSON array `[{"bbox": [x0, y0, x1, y1], "text"}]` with corners scaled+ * to 0–1000, and mostly answer that way. The general Qwen3.5 checkpoints wrap it in ```json fences and+ * use `bbox_2d` / `text_content`; a long answer can stop mid-list at the token limit. All of that reads.+ */++export interface OcrLine {+ text: string;+ /** [x, y, w, h] as 0–1 fractions of the image; absent when the model gave no usable box. */+ bbox?: [number, number, number, number];+}++export interface OcrFrame {+ width?: number;+ height?: number;+ /** "relative-1000" (the default) or "pixels". */+ coords?: string;+}++export interface OcrParse {+ lines: OcrLine[];+ /** False when the answer held no list of lines at all (prose, an error, an empty answer). */+ ok: boolean;+}++const FENCE = /```[a-z]*\s*([\s\S]*?)(?:```|$)/i;++/** The JSON inside an answer: the fenced part when there is one, from the first bracket on. */+function jsonPart(answer: string): string {+ const fenced = FENCE.exec(answer);+ const body = (fenced ? fenced[1] : answer).trim();+ const start = body.search(/[[{]/);+ return start < 0 ? "" : body.slice(start);+}++function tryJson(s: string): unknown {+ try {+ return JSON.parse(s);+ } catch {+ return undefined;+ }+}++/**+ * Parse the JSON of an answer, keeping what it finished when it was cut off: a list that stops in the+ * middle of an item keeps the items before it.+ */+function parseLenient(s: string): unknown {+ const whole = tryJson(s);+ if (whole !== undefined) return whole;+ // Text after the JSON ("Here are the lines: [...] Hope this helps").+ const end = s.lastIndexOf("]");+ if (end > 0) {+ const cut = tryJson(s.slice(0, end + 1));+ if (cut !== undefined) return cut;+ }+ // Cut off at the token limit: close the list after the last complete item.+ if (s.startsWith("[")) {+ for (let i = s.lastIndexOf("}"); i > 0; i = s.lastIndexOf("}", i - 1)) {+ const v = tryJson(`${s.slice(0, i + 1)}]`);+ if (v !== undefined) return v;+ }+ }+ return undefined;+}++const finite = (n: unknown): n is number => typeof n === "number" && Number.isFinite(n);+const toNum = (v: unknown): number | undefined => (finite(v) ? v : typeof v === "string" && v.trim() && Number.isFinite(Number(v)) ? Number(v) : undefined);++/** The four corners of a box in any of the shapes the models use: [x0, y0, x1, y1], {x0…} / {x_min…}, or a quad of points. */+function corners(v: unknown): [number, number, number, number] | undefined {+ if (Array.isArray(v)) {+ if (v.length === 4 && v.every((n) => toNum(n) !== undefined)) return v.map((n) => toNum(n)!) as [number, number, number, number];+ // A polygon: [[x, y], …] or a flat [x0, y0, x1, y1, …] of 8 numbers.+ const pts = v.every((p) => Array.isArray(p) && p.length >= 2) ? (v as unknown[][]).map((p) => [toNum(p[0]), toNum(p[1])]) : v.length >= 6 && v.length % 2 === 0 ? Array.from({ length: v.length / 2 }, (_, i) => [toNum(v[2 * i]), toNum(v[2 * i + 1])]) : [];+ if (pts.length >= 3 && pts.every(([x, y]) => x !== undefined && y !== undefined)) {+ const xs = pts.map(([x]) => x!);+ const ys = pts.map(([, y]) => y!);+ return [Math.min(...xs), Math.min(...ys), Math.max(...xs), Math.max(...ys)];+ }+ return undefined;+ }+ if (v && typeof v === "object") {+ const o = v as Record<string, unknown>;+ const x0 = toNum(o.x0 ?? o.x_min ?? o.xmin ?? o.left);+ const y0 = toNum(o.y0 ?? o.y_min ?? o.ymin ?? o.top);+ const x1 = toNum(o.x1 ?? o.x_max ?? o.xmax ?? o.right);+ const y1 = toNum(o.y1 ?? o.y_max ?? o.ymax ?? o.bottom);+ if ([x0, y0, x1, y1].every((n) => n !== undefined)) return [x0!, y0!, x1!, y1!];+ }+ return undefined;+}++const TEXT_KEYS = ["text", "text_content", "content", "label", "words", "transcription"] as const;+const BOX_KEYS = ["bbox", "bbox_2d", "box", "bounding_box", "quad", "polygon", "points"] as const;++/** The list of items in a parsed answer: the array itself, or the first array under a known key. */+function itemsOf(v: unknown): unknown[] | undefined {+ if (Array.isArray(v)) return v;+ if (!v || typeof v !== "object") return undefined;+ const o = v as Record<string, unknown>;+ for (const k of ["lines", "text_lines", "results", "items", "data", "ocr"]) if (Array.isArray(o[k])) return o[k] as unknown[];+ // A single line on its own.+ return TEXT_KEYS.some((k) => typeof o[k] === "string") ? [o] : undefined;+}++const r4 = (n: number) => Math.round(n * 10000) / 10000;+const clamp01 = (n: number) => Math.min(1, Math.max(0, n));++/**+ * The size the corners are measured in: 1000 for the relative boxes the instruction asks for, 1 for+ * boxes that are already fractions, the frame's pixels when it says the corners are pixels.+ */+function unitsFor(all: [number, number, number, number][], frame?: OcrFrame): [number, number] {+ const sized = !!frame && finite(frame.width) && finite(frame.height) && frame.width > 0 && frame.height > 0;+ if (sized && frame.coords === "pixels") return [frame.width!, frame.height!];+ const max = Math.max(0, ...all.flat());+ if (max <= 1.0001) return [1, 1];+ // Past 1000 the model answered in the pixels of the picture it saw (older Qwen-VL habits).+ return max > 1000.5 && sized ? [frame.width!, frame.height!] : [1000, 1000];+}++/** A model's OCR answer as lines with 0–1 boxes, in the order it read them. */+export function parseOcrLines(answer: string | null | undefined, frame?: OcrFrame): OcrParse {+ const items = itemsOf(parseLenient(jsonPart(answer ?? "")));+ if (!items) return { lines: [], ok: false };+ const read = items.flatMap((it): { text: string; box?: [number, number, number, number] }[] => {+ if (typeof it === "string") return it.trim() ? [{ text: it.trim() }] : [];+ if (!it || typeof it !== "object") return [];+ const o = it as Record<string, unknown>;+ const key = TEXT_KEYS.find((k) => typeof o[k] === "string");+ const text = key ? (o[key] as string).replace(/\s+/g, " ").trim() : "";+ if (!text) return [];+ const box = BOX_KEYS.map((k) => corners(o[k])).find(Boolean);+ return [{ text, box }];+ });+ const [ux, uy] = unitsFor(+ read.flatMap((l) => (l.box ? [l.box] : [])),+ frame,+ );+ const lines = read.map(({ text, box }): OcrLine => {+ if (!box) return { text };+ // Corners in either order; boxes that reach past the image are kept to it.+ const x0 = clamp01(Math.min(box[0], box[2]) / ux);+ const y0 = clamp01(Math.min(box[1], box[3]) / uy);+ const x1 = clamp01(Math.max(box[0], box[2]) / ux);+ const y1 = clamp01(Math.max(box[1], box[3]) / uy);+ return x1 > x0 && y1 > y0 ? { text, bbox: [r4(x0), r4(y0), r4(x1 - x0), r4(y1 - y0)] } : { text };+ });+ return { lines, ok: true };+}++/** The workflow's second output: the size the model saw, `{"width", "height", "coords"}`. */+export function parseOcrFrame(text: string | null | undefined): OcrFrame | undefined {+ const v = tryJson(jsonPart(text ?? ""));+ if (!v || typeof v !== "object" || Array.isArray(v)) return undefined;+ const o = v as Record<string, unknown>;+ const width = toNum(o.width);+ const height = toNum(o.height);+ const coords = typeof o.coords === "string" ? o.coords : undefined;+ if (width === undefined && height === undefined && !coords) return undefined;+ return { ...(width !== undefined ? { width } : {}), ...(height !== undefined ? { height } : {}), ...(coords ? { coords } : {}) };+}++/** OutputFile.text of an OCR result: one line per line read. */+export const ocrText = (lines: OcrLine[]): string => lines.map((l) => l.text).join("\n");diff --git a/src/server/providers/comfyui.ts b/src/server/providers/comfyui.tsindex 3a647fd8..68bd45ee 100644--- a/src/server/providers/comfyui.ts+++ b/src/server/providers/comfyui.ts@@ -33,6 +33,7 @@ import { guessKind } from "@/lib/catalog/payload";import { CLICK_OPEN_PROBLEM, HAND_OFF, REMOVE_SCENE, targetPhrase } from "@/lib/catalog/remove-object";import type { GenInput, MediaKind, ModelRoute, Operation } from "@/lib/catalog/types";import { probeMedia, type MediaInfo } from "@/lib/media-probe";+import { ocrText, parseOcrFrame, parseOcrLines, type OcrFrame } from "@/lib/ocr";import { getSetting, isCandidate, savedSetting } from "../settings";import { decodePng, encodePng } from "../png";import { readRef } from "../storage";@@ -259,11 +260,16 @@ export function collectOutputs(entry: HistoryEntry, manifest: ManifestWorkflow |.filter((o) => o.role === "language").map((o) => textsOf(outputs[o.node])[0]?.trim()).find(Boolean);+ // OCR: the size the model saw (a PreviewAny "frame") goes with the lines it read.+ const frame = declared+ .filter((o) => o.role === "frame")+ .map((o) => parseOcrFrame(textsOf(outputs[o.node]).join("\n")))+ .find(Boolean);const files: ComfyOutput[] = [];const pick = (type: string) => {for (const nodeId of order) {const spec: ManifestOutput | undefined = declared.find((o) => o.node === nodeId);- if (spec?.role === "language") continue;+ if (spec?.role === "language" || spec?.role === "frame") continue;const ui = outputs[nodeId] ?? {};const texts = textsOf(ui);const found: { key: string; f: HistoryFile }[] = [];@@ -271,6 +277,11 @@ export function collectOutputs(entry: HistoryEntry, manifest: ManifestWorkflow |if (!Array.isArray(val)) continue;for (const f of val) if (isFile(f) && f.type === type) found.push({ key, f });}+ // OCR lines (SaveText .json): the model's answer, read into lines with boxes.+ if (spec?.role === "lines" && texts.length) {+ if (type === "output") files.push(ocrOutput(texts.join("\n"), frame));+ continue;+ }// A text output with no file (PreviewAny): keep the words.if (!found.length && type === "output" && spec?.kind === "text" && texts.length) {const text = texts.join("\n");@@ -312,6 +323,18 @@ function textOutput(o: ComfyOutput, text: string | undefined, spec: ManifestOutpreturn { ...o, kind: "text", ...(text !== undefined ? { text } : {}), ...(Object.keys(meta).length ? { meta } : {}) };}+/**+ * An OCR answer as Fuobe's OCR output (the shape Florence-2's cloud route gives): the lines as plain+ * text, `meta.lines` [{text, bbox: [x, y, w, h] 0–1}] and `meta.size`, the picture the model read. An+ * answer with no list in it keeps its words, with no lines and `meta.unreadable`.+ */+function ocrOutput(answer: string, frame: OcrFrame | undefined): ComfyOutput {+ const { lines, ok } = parseOcrLines(answer, frame);+ const text = ok ? ocrText(lines) : answer.trim();+ const size = frame?.width && frame.height ? [frame.width, frame.height] : undefined;+ return { url: dataUrl(Buffer.from(text), "text/plain"), kind: "text", contentType: "text/plain", text, meta: { lines, ...(size ? { size } : {}), ...(ok ? {} : { unreadable: true }) } };+}+/** Layers: download each RGBA layer once, add its bounding box (from alpha) and hand the bytes on as a data URL. */async function withLayerBoxes(outputs: ComfyOutput[]): Promise<ComfyOutput[]> {return Promise.all(diff --git a/tests/ocr.test.ts b/tests/ocr.test.tsnew file mode 100644index 00000000..c20cca72--- /dev/null+++ b/tests/ocr.test.ts@@ -0,0 +1,84 @@+import { describe, expect, it } from "vitest";+import { ocrText, parseOcrFrame, parseOcrLines } from "@/lib/ocr";++// What ocr-lines-qwen35 answered on the research posters (docs/research/comfyui-oss-4.md §a): OvisOCR3+// answers bare JSON with bbox/text, the general Qwen3.5 checkpoints fence it and say bbox_2d/text_content.+const OVIS = '[{"bbox": [62, 96, 594, 205], "text": "SUMMER SALE"}, {"bbox": [62, 250, 480, 300], "text": "Everything must go"}]';+const QWEN = '```json\n[\n {"bbox_2d": [62, 96, 594, 205], "text_content": "SUMMER SALE"},\n {"bbox_2d": [700, 820, 940, 880], "text_content": "SAVE 30%"}\n]\n```';++describe("OCR answers → lines with 0–1 boxes", () => {+ it("reads OvisOCR3's bare JSON: corners 0–1000 become [x, y, w, h] fractions, spaces tidied", () => {+ const { lines, ok } = parseOcrLines(OVIS);+ expect(ok).toBe(true);+ expect(lines).toEqual([+ { text: "SUMMER SALE", bbox: [0.062, 0.096, 0.532, 0.109] },+ { text: "Everything must go", bbox: [0.062, 0.25, 0.418, 0.05] },+ ]);+ expect(ocrText(lines)).toBe("SUMMER SALE\nEverything must go");+ });++ it("strips ```json fences and takes bbox_2d / text_content", () => {+ const { lines } = parseOcrLines(QWEN);+ expect(lines.map((l) => l.text)).toEqual(["SUMMER SALE", "SAVE 30%"]);+ expect(lines[1].bbox).toEqual([0.7, 0.82, 0.24, 0.06]);+ });++ it("keeps the lines a cut-off answer finished, and reads JSON inside prose", () => {+ const cut = '```json\n[{"bbox": [10, 10, 500, 60], "text": "ONE"}, {"bbox": [10, 80, 500, 130], "text": "TWO"}, {"bbox": [10, 150, 5';+ expect(parseOcrLines(cut).lines.map((l) => l.text)).toEqual(["ONE", "TWO"]);+ expect(parseOcrLines(`Here are the lines: ${OVIS} Hope that helps!`).lines).toHaveLength(2);+ // The list's closing bracket was all that was missing.+ expect(parseOcrLines('[{"bbox":[1,2,300,40],"text":"A"},{"bbox":[1,50,300,90],"text":"B"}').lines.map((l) => l.text)).toEqual(["A", "B"]);+ });++ it("takes boxes that are already fractions, and pixel corners past 1000 in the frame's size", () => {+ expect(parseOcrLines('[{"bbox": [0.1, 0.2, 0.5, 0.3], "text": "Hi"}]').lines[0].bbox).toEqual([0.1, 0.2, 0.4, 0.1]);+ const frame = { width: 1280, height: 960 };+ expect(parseOcrLines('[{"bbox": [128, 96, 1152, 192], "text": "Wide"}]', frame).lines[0].bbox).toEqual([0.1, 0.1, 0.8, 0.1]);+ // Under 1000 the boxes stay relative (what the instruction asks for), size or not.+ expect(parseOcrLines('[{"bbox": [100, 100, 600, 200], "text": "Rel"}]', frame).lines[0].bbox).toEqual([0.1, 0.1, 0.5, 0.1]);+ expect(parseOcrLines('[{"bbox": [128, 96, 640, 192], "text": "Px"}]', { ...frame, coords: "pixels" }).lines[0].bbox).toEqual([0.1, 0.1, 0.4, 0.1]);+ });++ it("puts swapped corners in order, keeps boxes on the image, and drops what isn't a line", () => {+ const { lines } = parseOcrLines(+ JSON.stringify([+ { bbox: [600, 300, 100, 200], text: "Swapped" },+ { bbox: [900, 900, 1080, 1040], text: "Edge" },+ { bbox: [5, 5, 5, 40], text: "Flat box" },+ { bbox: [1, 2, 3], text: "Short box" },+ { bbox: [1, 2, 3, 4], text: " " },+ "Loose string",+ 42,+ null,+ ]),+ );+ expect(lines).toEqual([+ { text: "Swapped", bbox: [0.1, 0.2, 0.5, 0.1] },+ { text: "Edge", bbox: [0.9, 0.9, 0.1, 0.1] },+ { text: "Flat box" },+ { text: "Short box" },+ { text: "Loose string" },+ ]);+ });++ it("reads other shapes models use: a quad of points, x_min… keys, a {lines} wrapper", () => {+ const quad = parseOcrLines('{"lines": [{"polygon": [[100, 100], [400, 110], [400, 200], [100, 190]], "content": "Quad"}]}').lines[0];+ expect(quad).toEqual({ text: "Quad", bbox: [0.1, 0.1, 0.3, 0.1] });+ const keys = parseOcrLines('[{"box": {"x_min": 0, "y_min": 500, "x_max": 250, "y_max": 750}, "label": "Keys"}]').lines[0];+ expect(keys).toEqual({ text: "Keys", bbox: [0, 0.5, 0.25, 0.25] });+ });++ it("says when the answer holds no list at all (an empty list is a picture without text)", () => {+ expect(parseOcrLines("I can't see any text, sorry.")).toEqual({ lines: [], ok: false });+ expect(parseOcrLines("")).toEqual({ lines: [], ok: false });+ expect(parseOcrLines(undefined)).toEqual({ lines: [], ok: false });+ expect(parseOcrLines("```json\n[]\n```")).toEqual({ lines: [], ok: true });+ });++ it("reads the frame output: the size the model saw", () => {+ expect(parseOcrFrame('{"width": 1280, "height": 960, "coords": "relative-1000"}')).toEqual({ width: 1280, height: 960, coords: "relative-1000" });+ expect(parseOcrFrame("not json")).toBeUndefined();+ expect(parseOcrFrame("[1, 2]")).toBeUndefined();+ });+});