Skip to content

armgit / fuobe

Public Imported from GitHub
0

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.

Edit text: a transparent layer goes on a backdrop its text stands out from before detection

Claude53646733e8b1
diff --git a/src/components/layers/tools.tsx b/src/components/layers/tools.tsx
index dbdc018f..c0af2b31 100644
--- a/src/components/layers/tools.tsx
+++ b/src/components/layers/tools.tsx
@@ -55,6 +55,7 @@ import {
nativeSize,
needsDetectedSize,
placeTextBlocks,
+ readableBackdrop,
reframeDoc,
RELIGHT_DIRECTIONS,
RELIGHT_LIGHTS,
@@ -251,6 +252,14 @@ function useRun() {
};
}
+/** A blank canvas of a size. */
+function blankCanvas(w: number, h: number): [HTMLCanvasElement, CanvasRenderingContext2D] {
+ const c = document.createElement("canvas");
+ c.width = w;
+ c.height = h;
+ return [c, c.getContext("2d")!];
+}
+
// ---------------------------------------------------------------------------
// Layer Decomposition (and Separate layer)
@@ -489,13 +498,33 @@ function EditTextTool() {
useEffect(() => () => setHighlight(null), [setHighlight]);
const changes = textChanges(rows);
+ const [preparing, setPreparing] = useState(false);
const detecting = !!detect && isRunning(detect);
const detectCost = costLabel(detector.model, isDemo(detector.model));
- const startDetect = () => {
+ const startDetect = async () => {
setLoadedFor(null);
setRestored(false);
setUnreadable(false);
- void go({ tool: "text-detect", target, modelId: detector.modelId, label: "Detect text" });
+ setPreparing(true);
+ // A transparent layer (a decomposition's text) goes on a backdrop its text stands out from.
+ let image: string | undefined;
+ if (node) {
+ try {
+ const c = await renderNative(node, 2048);
+ const bg = readableBackdrop(c.getContext("2d")!.getImageData(0, 0, c.width, c.height).data);
+ if (bg) {
+ const [flat, f] = blankCanvas(c.width, c.height);
+ f.fillStyle = bg;
+ f.fillRect(0, 0, c.width, c.height);
+ f.drawImage(c, 0, 0);
+ image = await uploadRender(flat, `${node.name}-text`);
+ }
+ } catch {
+ // The layer goes as it is.
+ }
+ }
+ setPreparing(false);
+ void go({ tool: "text-detect", target, image, modelId: detector.modelId, label: "Detect text" });
};
const addLine = () => {
setTyping(true);
@@ -514,7 +543,7 @@ function EditTextTool() {
<div className="space-y-2">
<ModelSelect tool="text-detect" value={detector.modelId} onChange={detector.setModelId} label="Detector" />
{detector.model && TOOL_MODELS["text-detect"][engine].length > 1 && <p className="text-[11px] text-pretty text-subtle-foreground">{detector.model.tagline}</p>}
- <Button variant="secondary" className="w-full rounded-full" onClick={startDetect} disabled={busy || detecting || !detector.model}>
+ <Button variant="secondary" className="w-full rounded-full" onClick={() => void startDetect()} disabled={busy || preparing || detecting || !detector.model}>
{detecting ? <Loader2 className="animate-spin" /> : <Type />} {detecting ? "Reading the text…" : "Detect text"}
</Button>
<p className="text-center font-mono text-[11px] text-subtle-foreground">{detectCost}</p>
@@ -525,7 +554,7 @@ function EditTextTool() {
{unreadable ? "Could not read the text on this image." : "No text was found on this image."}
</p>
)}
- {detect && isFailed(detect) && <JobState job={detect} failedTitle="Could not read the text on this image." onRetry={startDetect} />}
+ {detect && isFailed(detect) && <JobState job={detect} failedTitle="Could not read the text on this image." onRetry={() => void startDetect()} />}
{!typing && (
<button type="button" className="mx-auto block text-[12px] font-medium text-brand-text hover:underline" onClick={addLine}>
Type the lines instead
@@ -576,7 +605,7 @@ function EditTextTool() {
<div className="flex items-center gap-2">
<Tooltip>
<TooltipTrigger asChild>
- <Button variant="ghost" size="icon" aria-label={found ? "Detect text again" : "Detect text"} onClick={startDetect} disabled={busy || detecting || !detector.model}>
+ <Button variant="ghost" size="icon" aria-label={found ? "Detect text again" : "Detect text"} onClick={() => void startDetect()} disabled={busy || preparing || detecting || !detector.model}>
{detecting ? <Loader2 className="animate-spin" /> : <RefreshCw />}
</Button>
</TooltipTrigger>
@@ -858,14 +887,6 @@ function RegionalTool() {
// ---------------------------------------------------------------------------
// Inpaint (brush an area, say what goes there)
-/** A blank canvas of a size. */
-function blankCanvas(w: number, h: number): [HTMLCanvasElement, CanvasRenderingContext2D] {
- const c = document.createElement("canvas");
- c.width = w;
- c.height = h;
- return [c, c.getContext("2d")!];
-}
-
function InpaintTool() {
const { doc, isDemo, jobs, setMode, mode, paint, setPaint, paintVersion, brushSize, setBrushSize } = useEditor();
const { target, node } = useTarget();
diff --git a/src/lib/layers.ts b/src/lib/layers.ts
index 8ed5404f..99b69a4d 100644
--- a/src/lib/layers.ts
+++ b/src/lib/layers.ts
@@ -1011,6 +1011,27 @@ export function needsDetectedSize(meta: Record<string, unknown> | undefined): bo
return !asSize(meta?.size) && detectedBlocks(meta).some((o) => !!rawBox(o)?.px);
}
+/**
+ * The backdrop a transparent layer goes on before a detector reads it (detectors see no alpha, and
+ * transparent pixels read as black): white under dark text, black under light text. Null when the
+ * layer has no transparency to fill.
+ */
+export function readableBackdrop(rgba: ArrayLike<number>): "#ffffff" | "#000000" | null {
+ let sum = 0;
+ let n = 0;
+ let clear = false;
+ for (let i = 0; i + 3 < rgba.length; i += 4) {
+ const a = rgba[i + 3];
+ if (a < 250) clear = true;
+ if (a > 128) {
+ sum += 0.2126 * rgba[i] + 0.7152 * rgba[i + 1] + 0.0722 * rgba[i + 2];
+ n++;
+ }
+ }
+ if (!clear) return null;
+ return n && sum / n > 140 ? "#000000" : "#ffffff";
+}
+
/** Lay detected blocks out in the document: their 0–1 boxes inside the frame the detector read (doc px). */
export function placeTextBlocks(blocks: TextBlock[], frame: Box): (TextRow & { box: Box | null })[] {
const [fx, fy, fw, fh] = frame;
diff --git a/tests/layers.test.ts b/tests/layers.test.ts
index 12b369c6..15d096fa 100644
--- a/tests/layers.test.ts
+++ b/tests/layers.test.ts
@@ -50,6 +50,7 @@ import {
inpaintPrompt,
needsDetectedSize,
placeTextBlocks,
+ readableBackdrop,
coverage,
defaultLayers,
exportScale,
@@ -457,6 +458,17 @@ describe("edit text", () => {
expect(needsDetectedSize({ textBlocks: [{ text: "x", bbox: { x: 0.1, y: 0.2, width: 0.3, height: 0.1 } }] })).toBe(false);
});
+ it("puts a transparent layer on a backdrop its text stands out from before detection", () => {
+ const px = (...p: number[][]) => p.flat();
+ // Opaque: nothing to fill.
+ expect(readableBackdrop(px([10, 10, 10, 255], [250, 250, 250, 255]))).toBeNull();
+ // Dark text on transparency → white; light text → black.
+ expect(readableBackdrop(px([20, 20, 30, 255], [0, 0, 0, 0], [0, 0, 0, 0]))).toBe("#ffffff");
+ expect(readableBackdrop(px([255, 255, 240, 255], [250, 250, 250, 200], [0, 0, 0, 0]))).toBe("#000000");
+ // Nothing visible at all: white.
+ expect(readableBackdrop(px([0, 0, 0, 0]))).toBe("#ffffff");
+ });
+
it("lays detected lines out in the frame the detector read, like the cloud route's blocks", () => {
const rows = placeTextBlocks(
[