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
Runs: a prompt in another language reaches the model in English
Adarsh5be39df03cbf
diff --git a/src/lib/prompt-language.ts b/src/lib/prompt-language.tsnew file mode 100644index 00000000..09e32318--- /dev/null+++ b/src/lib/prompt-language.ts@@ -0,0 +1,86 @@+/**+ * Is a prompt written in a language other than English? A quick check with no model: picture and video models follow+ * English prompts best, so a run asks the text helper for an English version only when this says so+ * (src/server/english-prompt.ts). Words in quotes, @handles, <tags>, links and numbers are left out first: they stay as+ * written whatever the language.+ *+ * Two signals:+ * - letters of another script (Cyrillic, Greek, Arabic, Hebrew, Devanagari and other Indic scripts, Thai, CJK, Hangul…)+ * make up more than 30% of the letters;+ * - in the Latin script, at least two words that are common in another language (or carry its accents: ă, ș, ñ, ç, ß,+ * ł…) and more of them than common English words. Words that are also English (a, in, on, die, son…) count for+ * neither side.+ */++/** Common words of other Latin-script languages that English prompts don't use, with and without their accents. */+const OTHER = new Set(+ [+ // Spanish+ "el la los las del que y una unos unas por para muy pero sobre como más mas este esta esto estos sus su lo se mujer hombre chica chico fondo foto fotografía imagen cámara camara blanca blanco negra roja rojo azul hacer quiero",+ // French+ "le les des du une et avec dans sur est sont pas qui au aux ce cette ces sa ses très tres sous femme homme fille blanche noire bleu faire veux",+ // German+ "der das und mit ein eine einen einem ist auf im nicht von vom dem sehr frau mann mädchen hintergrund bild weiß weiss schwarz blau machen",+ // Portuguese+ "os uma com não nao da dos das na em mulher homem fundo sem muito ao branca branco preta preto vermelho azul fazer quero",+ // Italian+ "il gli della delle dello nel nella sul sulla che uno sono uomo ragazza sfondo molto senza bianco nera rosso voglio",+ // Romanian+ "si și cu este sunt trebuie sa să fie nu ca acum pe din cel cea mai foarte fara fără femeie barbat bărbat fata fată fundal alb alba albă albe negru neagra neagră rosu roșu rosie roșie albastru albastra albastră camasa cămașă cămasa rochie sau unei unui vreau fă fa schimba schimbă",+ // Dutch+ "het een voor niet zijn vrouw meisje achtergrond zwart rood blauw maken",+ // Polish, Czech, Slovak, Croatian+ "się nie jest jak oraz kobieta mężczyzna tle biały czarny czerwony niebieski je ve žena muž pozadí bílá černá jsou",+ // Turkish+ "ve bir ile için bu çok kadın erkek arka beyaz siyah kırmızı mavi",+ // Indonesian and Malay+ "dan yang di dengan ini itu untuk wanita pria latar putih hitam merah biru",+ // Tagalog+ "ang ng mga sa babae lalaki puti itim pula",+ ]+ .join(" ")+ .split(" "),+);++/** Common English words of prompts: function words and the words of pictures and edits. */+const ENGLISH = new Set(+ (+ "the of at with and is are to for from by her his their its this that these those it as be was were will should must " ++ "into onto over under behind near next front back while wearing wears holding standing sitting walking looking " ++ "woman man girl boy person people model portrait photo photograph picture image shot close up wide full body " ++ "background light lighting soft hard golden hour night day sunset street city studio scene style cinematic " ++ "white black red blue green yellow pink purple orange grey gray brown silver gold dark bright " ++ "make change turn add remove replace keep same instead like now new old young small large big very " ++ "dress shirt jacket suit hair face eyes hand hands smile smiling camera slow fast moves turns looks walks"+ ).split(" "),+);++/** Accented Latin letters English words don't carry. */+const ACCENTS = /[ăâîșşțţãõñçàèìòùáéíóúêôûäöüßøåæœłńśźżčřšžěůőűğıİ]/i;++/** The parts of a prompt that stay as written in any language: quoted words, @handles, <tags>, links, numbers. */+function plainWords(text: string): string {+ return text+ .replace(/"[^"]*"|“[^”]*”|„[^“”]*[“”]|«[^»]*»|「[^」]*」|『[^』]*』/g, " ")+ .replace(/https?:\/\/\S+/g, " ")+ .replace(/<[^>]{1,40}>/g, " ")+ .replace(/@[\p{L}\p{N}_.-]+/gu, " ")+ .replace(/\p{N}+/gu, " ");+}++/** Does this prompt read as another language than English (see the top of the file)? */+export function needsEnglish(text: string | undefined | null): boolean {+ if (!text) return false;+ const words = plainWords(text);+ const letters = words.match(/\p{L}/gu) ?? [];+ if (!letters.length) return false;+ const other = letters.filter((l) => !/\p{Script=Latin}/u.test(l)).length;+ if (other / letters.length > 0.3) return true;+ let en = 0;+ let fo = 0;+ for (const w of words.toLowerCase().match(/[\p{L}']+/gu) ?? []) {+ if (ENGLISH.has(w)) en++;+ else if (OTHER.has(w) || ACCENTS.test(w)) fo++;+ }+ return fo >= 2 && fo > en;+}diff --git a/src/server/english-prompt.ts b/src/server/english-prompt.tsnew file mode 100644index 00000000..bbe2eb54--- /dev/null+++ b/src/server/english-prompt.ts@@ -0,0 +1,71 @@+import "server-only";+import type { MediaKind, Operation } from "@/lib/catalog/types";+import { needsEnglish } from "@/lib/prompt-language";+import { llmText, type LlmTextOptions } from "./enhance";++/**+ * A prompt in another language, in English for the model: picture and video models follow English prompts best. The+ * person keeps seeing their own words; only the model gets the English version. It runs only when needsEnglish says the+ * prompt is in another language, and only for operations whose prompt describes the picture or the clip (never words to+ * be spoken, sung, written or translated). With no text helper, or an answer that doesn't look like a prompt, the run+ * keeps the words as typed.+ */++/** The most a prompt is sent for an English version (longer ones go as they are). */+export const ENGLISH_MAX_CHARS = 2000;++/** The operations whose prompt says what the picture or clip shows: these get the English version. */+const DESCRIBES = new Set<Operation>(["t2i", "edit", "inpaint", "outpaint", "t2v", "i2v", "flf2v", "ref2v", "v2v", "extend", "motion-transfer", "remove-object", "video-swap", "video-insert", "keyframes", "text-to-3d"]);++export const takesEnglish = (kind: MediaKind, op: Operation): boolean => (kind === "image" || kind === "video" || kind === "model3d") && DESCRIBES.has(op);++/** Would a run's prompt get an English version (another language, an operation that describes, not too long)? */+export const wantsEnglish = (prompt: string | undefined, kind: MediaKind, op: Operation): boolean =>+ !!prompt && prompt.length <= ENGLISH_MAX_CHARS && takesEnglish(kind, op) && needsEnglish(prompt);++export const ENGLISH_SYSTEM = `You translate prompts for image and video generation models into English.+Rules:+- Answer with the English prompt only: no preamble, no notes, no quotes around the answer.+- Translate every word, also words typed without their accents. Keep the meaning, every detail and the order. Add nothing new.+- Keep exactly as written and in the same place: words inside quotes, names, brands, @handles, tags in angle brackets such as <Picture 1>, references such as "Image 1", numbers and units.+- Say only what the result should show. Never write not, no, without or don't: write what should be there instead.+- An edit instruction stays an instruction: say what to change and to what, and what to keep the same.+Examples:+camasa trebuie sa fie alba, nu albastru deschis ca acum+Make the shirt white.+quita el sombrero y que no tenga gafas+Remove the hat and the glasses.+<Picture 1> в красном платье, без шляпы+<Picture 1> in a red dress, bare head.+Mach den Himmel klar, ohne Wolken, und ändere das Auto nicht+Make the sky clear and cloudless, and keep the car the same.`;++/** The helper's answer as a prompt: trimmed, a wrapper of quotes or a "Prompt:" label taken off; null when it isn't one. */+export function cleanEnglish(answer: string | null | undefined, original: string): string | null {+ if (!answer) return null;+ let s = answer.replace(/^```\w*\n?|```$/g, "").trim();+ s = s.replace(/^(english( prompt)?|prompt|translation)\s*:\s*/i, "").trim();+ if (/^(["“'])[\s\S]*(["”'])$/.test(s) && !/^["“']/.test(original.trim())) s = s.slice(1, -1).trim();+ if (!s) return null;+ // A prompt, not a chat: far longer than the words given means the model said more than the prompt.+ if (s.length > original.length * 3 + 200) return null;+ return s;+}++/**+ * The English version of a run's prompt, or null when the run keeps its words (English already, an operation whose words+ * aren't a description, too long, or no helper answered). `ask` is the text helper (llmText), replaced in tests.+ */+export async function englishPrompt(+ prompt: string,+ kind: MediaKind,+ op: Operation,+ o: { open?: boolean; waitMs?: number; ask?: (system: string, user: string, opts: LlmTextOptions) => Promise<string | null> } = {},+): Promise<string | null> {+ if (!wantsEnglish(prompt, kind, op)) return null;+ const ask = o.ask ?? llmText;+ // The open engine's runs are free: a local model or the free helper, never a paid API.+ const answer = await ask(ENGLISH_SYSTEM, prompt, { task: "translate", waitMs: o.waitMs ?? 20_000, timeoutMs: 30_000, ...(o.open && { ollamaOnly: true }) }).catch(() => null);+ const english = cleanEnglish(answer, prompt);+ return english && english !== prompt ? english : null;+}diff --git a/src/server/generations.ts b/src/server/generations.tsindex f049a3f5..0c4bb19b 100644--- a/src/server/generations.ts+++ b/src/server/generations.ts@@ -81,6 +81,7 @@ import { FIX_FACES, FIX_FACES_AFTER_PARAM, fixFacesAfterStep, wantsFixFacesAfterimport { createH3TwoKRun, createRegenerateRun, keepsH3Latent, regenHeld, regenSwitchedOff } from "./regenerate";import { H3_2K_STEPS_NOTE, h3TwoKRequests, REGEN_COPY, REGEN_MODEL, regenerateGraphLoras, wantsH3TwoK } from "@/lib/catalog/regenerate";import { enhancePrompt, enhanceSoulWords, ideogramCaption } from "./enhance";+import { englishPrompt, wantsEnglish } from "./english-prompt";import { kandinskyPrompt } from "@/lib/kandinsky-prompt";import { filmLookRun } from "./film-look";import { takesFilmLooks } from "@/lib/film-looks";@@ -3792,9 +3793,25 @@ async function handOver(id: string, route: ModelRoute, providerId: ProviderId, pconst captioned = plan.model.options.promptFormat === "ideogram4";// A layout's prompt is compiled boxes (plan.layout): the enhancer would rewrite them, so it never runs on one.const laidOut = !!plan.layout || carriesLayout(req.params?.extra);+ // A prompt in another language goes to the model in English (src/server/english-prompt.ts). The run keeps the words+ // as typed, so the person sees their own. A Soul look stays as it is: only the person's words are read. A layout, a+ // caption given as JSON and an H3 layout keep their form.+ let soulWords = plan.soul?.words;+ if (prompt && !laidOut && !(captioned && parseCaption(prompt)) && !inH3Layout(prompt)) {+ const at = soulWords ? prompt.indexOf(soulWords) : -1;+ const words = soulWords && at >= 0 ? soulWords : prompt;+ if (wantsEnglish(words, plan.model.kind, plan.op)) {+ update(id, { message: "Preparing the prompt" });+ const english = await englishPrompt(words, plan.model.kind, plan.op, { open: plan.model.engine === "open" }).catch(() => null);+ if (english && soulWords && at >= 0) {+ prompt = prompt.slice(0, at) + english + prompt.slice(at + soulWords.length);+ soulWords = english;+ } else if (english) prompt = english;+ }+ }if (req.params?.enhancePrompt && prompt && !captioned && !laidOut) {update(id, { message: "Enhancing prompt" });- const words = plan.soul?.words;+ const words = soulWords;const at = words ? prompt.indexOf(words) : -1;if (words && at >= 0) {// Soul: only the user's words are expanded (60–120 words of subject, wardrobe, place, light); the look stays as it is.diff --git a/tests/english-prompt-run.test.ts b/tests/english-prompt-run.test.tsnew file mode 100644index 00000000..0d53bcaf--- /dev/null+++ b/tests/english-prompt-run.test.ts@@ -0,0 +1,74 @@+import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";+import { startFakeFal, type FakeCloud } from "./helpers/fake-cloud";+import { tempDir } from "./helpers/temp-dir";++/**+ * A prompt in another language reaches the model in English, and the run keeps the words as typed. The text helper is a+ * stand-in (llmText), and fal.ai is the stand-in of tests/helpers/fake-cloud.ts: no real key, no paid call.+ */+process.env.FUOBE_DATA_DIR = tempDir("fuobe-english-prompt-");+process.env.COMFYUI_URL = "http://127.0.0.1:9";+delete process.env.FUOBE_PASSWORD;+globalThis.__fuobeTestDiskFree = 1e13;++const asked: string[] = [];+let answer: string | null = "A model in a red silk dress on the beach, golden light";+vi.mock("@/server/enhance", async (original) => ({+ ...(await original<typeof import("@/server/enhance")>()),+ llmText: async (_system: string, user: string) => {+ asked.push(user);+ return answer;+ },+}));++const { setSetting } = await import("@/server/settings");+const { createGenerations, getGeneration } = await import("@/server/generations");+type GenerationRequest = import("@/lib/catalog/types").GenerationRequest;++let fal: FakeCloud;+beforeAll(async () => {+ fal = await startFakeFal();+ globalThis.__fuobeTestFalUrl = fal.url;+ fal.keys["stand-in-fal-key"] = "good";+ fal.pollsToFinish = 0;+ setSetting("falKey", "stand-in-fal-key");+});+afterAll(async () => {+ globalThis.__fuobeTestFalUrl = undefined;+ await fal.close();+});++/** One picture of `prompt` on Seedream 5 Pro: the prompt fal got, and the run as the person sees it. */+async function run(prompt: string): Promise<{ sent: string; shown: string }> {+ fal.log.length = 0;+ const [g] = createGenerations({ feature: "image", modelId: "seedream-5-pro", engine: "cloud", prompt } as GenerationRequest);+ for (let i = 0; i < 1500 && !["failed", "succeeded", "canceled"].includes(getGeneration(g.id)!.status); i++) await new Promise((r) => setTimeout(r, 10));+ const done = getGeneration(g.id)!;+ expect(done.status, done.error ?? "").toBe("succeeded");+ const submit = fal.log.find((r) => r.method === "POST" && !r.path.startsWith("/storage/"))!;+ return { sent: JSON.parse(submit.body).prompt, shown: done.prompt ?? "" };+}++describe("a prompt in another language", () => {+ it("goes to the model in English; the person still sees their own words", async () => {+ const hindi = "समुद्र तट पर लाल रेशमी पोशाक में एक मॉडल, सुनहरी रोशनी";+ const { sent, shown } = await run(hindi);+ expect(asked).toEqual([hindi]);+ expect(sent).toBe("A model in a red silk dress on the beach, golden light");+ expect(shown).toBe(hindi);+ });++ it("an English prompt goes as typed, with no helper asked", async () => {+ asked.length = 0;+ const { sent } = await run("A model in a red silk dress on the beach, golden light");+ expect(sent).toBe("A model in a red silk dress on the beach, golden light");+ expect(asked).toEqual([]);+ });++ it("with no helper answer, the words go as typed", async () => {+ answer = null;+ const ro = "o femeie cu rochie rosie pe plaja, fundal alb";+ const { sent } = await run(ro);+ expect(sent).toBe(ro);+ });+});diff --git a/tests/prompt-language.test.ts b/tests/prompt-language.test.tsnew file mode 100644index 00000000..22dc7c31--- /dev/null+++ b/tests/prompt-language.test.ts@@ -0,0 +1,104 @@+import { describe, expect, it, vi } from "vitest";+import { needsEnglish } from "@/lib/prompt-language";+import { cleanEnglish, ENGLISH_SYSTEM, englishPrompt, takesEnglish } from "@/server/english-prompt";++describe("needsEnglish: is a prompt in another language", () => {+ it.each([+ ["Romanian, typed without accents", "camasa trebuie sa fie alba, nu albastru deschis ca acum"],+ ["Romanian, with accents", "Fă cămașa albă"],+ ["Spanish", "una mujer con vestido rojo en la playa al atardecer"],+ ["French", "une femme en robe rouge sur la plage"],+ ["German", "Eine Frau im roten Kleid am Strand"],+ ["Portuguese", "Uma mulher de vestido vermelho na praia"],+ ["Italian", "Una donna con un vestito rosso sulla spiaggia"],+ ["Dutch", "Een vrouw in een rode jurk op het strand"],+ ["Polish", "Kobieta w czerwonej sukience na plaży"],+ ["Turkish", "Plajda kırmızı elbiseli bir kadın"],+ ["Indonesian", "Seorang wanita dengan gaun merah di pantai"],+ ["Hindi", "समुद्र तट पर लाल पोशाक में एक महिला"],+ ["Russian", "Женщина в красном платье на пляже"],+ ["Japanese", "ビーチで赤いドレスを着た女性"],+ ["Chinese", "海滩上穿红裙的女人"],+ ["Arabic", "امرأة ترتدي فستانا أحمر على الشاطئ"],+ ["Korean", "해변에서 빨간 드레스를 입은 여자"],+ ])("%s", (_name, text) => {+ expect(needsEnglish(text)).toBe(true);+ });++ it.each([+ "A fashion model in an ivory silk gown on a marble terrace at golden hour, editorial photograph",+ "Seiko watch on a wrist, close up, 85mm",+ "make the shirt white",+ "A woman walking in La Paz at night",+ "Portrait of Dan, cinematic lighting",+ 'A neon sign that says "Bună seara, prieteni" over a bar',+ "@mira in a red dress, Image 1 style",+ "Kendrick wearing Dior Homme, studio portrait",+ "<Picture 1> walks toward the camera",+ "cyberpunk alley, rain, neon, 35mm",+ "",+ ])("leaves English as it is: %s", (text) => {+ expect(needsEnglish(text)).toBe(false);+ });+});++describe("englishPrompt: the model gets the prompt in English", () => {+ const RO = "camasa trebuie sa fie alba, nu albastru deschis ca acum";++ it("asks the text helper once, as a translate task, and cleans the answer", async () => {+ const ask = vi.fn(async () => '"Make the shirt white."');+ expect(await englishPrompt(RO, "image", "edit", { ask })).toBe("Make the shirt white.");+ expect(ask).toHaveBeenCalledTimes(1);+ const [system, user, opts] = ask.mock.calls[0] as unknown as [string, string, Record<string, unknown>];+ expect(system).toBe(ENGLISH_SYSTEM);+ expect(user).toBe(RO);+ expect(opts).toMatchObject({ task: "translate" });+ expect(opts.ollamaOnly).toBeUndefined();+ });++ it("an open-engine run asks no paid API", async () => {+ const ask = vi.fn(async () => "Make the shirt white.");+ await englishPrompt(RO, "image", "edit", { ask, open: true });+ expect((ask.mock.calls[0] as unknown as [string, string, Record<string, unknown>])[2]).toMatchObject({ ollamaOnly: true });+ });++ it("asks nothing for English, or for words that are spoken, sung or written", async () => {+ const ask = vi.fn(async () => "x");+ expect(await englishPrompt("A woman in a red dress on a beach", "image", "t2i", { ask })).toBeNull();+ expect(await englishPrompt(RO, "audio", "tts", { ask })).toBeNull();+ expect(await englishPrompt(RO, "audio", "music", { ask })).toBeNull();+ expect(await englishPrompt(RO, "video", "avatar", { ask })).toBeNull();+ expect(await englishPrompt(RO, "text", "write", { ask })).toBeNull();+ expect(ask).not.toHaveBeenCalled();+ });++ it("keeps the words as typed when no helper answers, it fails, or it answers with more than a prompt", async () => {+ expect(await englishPrompt(RO, "image", "edit", { ask: async () => null })).toBeNull();+ expect(await englishPrompt(RO, "image", "edit", { ask: async () => Promise.reject(new Error("down")) })).toBeNull();+ expect(await englishPrompt(RO, "image", "edit", { ask: async () => "Sure! ".repeat(200) })).toBeNull();+ });++ it("covers picture, clip and 3D descriptions only", () => {+ for (const op of ["t2i", "edit", "inpaint", "t2v", "i2v", "ref2v", "extend"] as const) expect(takesEnglish(op.endsWith("v") || op === "extend" ? "video" : "image", op)).toBe(true);+ expect(takesEnglish("model3d", "text-to-3d")).toBe(true);+ expect(takesEnglish("audio", "sfx")).toBe(false);+ expect(takesEnglish("text", "translate")).toBe(false);+ });+});++describe("cleanEnglish", () => {+ it("takes off a label, a code fence and wrapping quotes", () => {+ expect(cleanEnglish("English prompt: Make the shirt white.", "x")).toBe("Make the shirt white.");+ expect(cleanEnglish("```\nMake the shirt white.\n```", "x")).toBe("Make the shirt white.");+ expect(cleanEnglish("“Make the shirt white.”", "x")).toBe("Make the shirt white.");+ });++ it("keeps quotes the prompt itself starts with", () => {+ expect(cleanEnglish('"Hola" written in neon', '"Hola" escrito en neón')).toBe('"Hola" written in neon');+ });++ it("gives nothing for an empty answer", () => {+ expect(cleanEnglish(" ", "x")).toBeNull();+ expect(cleanEnglish(null, "x")).toBeNull();+ });+});