Spaces:
Sleeping
Sleeping
Julian Bilcke commited on
Commit ·
faf4ba4
1
Parent(s): 9bcdb59
added suggestion from user + work on the progressive loader
Browse filesFiles changed (17)
- .env+3
- src/app/engine/render.ts+4
- src/app/interface/settings-dialog/defaultSettings.ts+1
- src/app/interface/settings-dialog/getSettings.ts+1
- src/app/interface/settings-dialog/index.tsx+15
- src/app/interface/settings-dialog/localStorageKeys.ts+1
- src/app/main.tsx+65-53
- src/app/queries/getStory.ts+13-13
- src/app/queries/getStoryContinuation.ts+53-81
- src/app/queries/mockLLMResponse.ts+2-2
- src/app/queries/predictNextPanels.tsAdded+95
- src/lib/cleanJson.ts+1-1
- src/lib/dirtyCaptionCleaner.ts → src/lib/dirtyGeneratedPanelCleaner.tsRenamed+6-8
- src/lib/dirtyLLMJsonParser.ts → src/lib/dirtyGeneratedPanelsParser.tsRenamed+3-3
- src/lib/dirtyLLMResponseCleaner.ts+1-1
- src/lib/parseBadJSON.ts+4-4
- src/types.ts+8-1
52 unmodified lines53545556575852 unmodified lines# If you decided to use a Hugging Face Inference API model for the RENDERING engineRENDERING_HF_INFERENCE_API_REFINER_MODEL="stabilityai/stable-diffusion-xl-refiner-1.0"# An experimental RENDERING engine (sorry it is not very documented yet, so you can use one of the other engines)RENDERING_VIDEOCHAIN_API_URL="http://localhost:7860"52 unmodified lines53545556575859606152 unmodified lines# If you decided to use a Hugging Face Inference API model for the RENDERING engineRENDERING_HF_INFERENCE_API_REFINER_MODEL="stabilityai/stable-diffusion-xl-refiner-1.0"# If your model returns a different file type (eg. jpg or webp) change it hereRENDERING_HF_INFERENCE_API_FILE_TYPE="image/png"# An experimental RENDERING engine (sorry it is not very documented yet, so you can use one of the other engines)RENDERING_VIDEOCHAIN_API_URL="http://localhost:7860"
14 unmodified lines15161718192056 unmodified lines77787980818233 unmodified lines116117118119120121136 unmodified lines25825926026126226314 unmodified linesconst serverHuggingfaceInferenceApiModel = `${process.env.RENDERING_HF_INFERENCE_API_BASE_MODEL || ""}`const serverHuggingfaceInferenceApiModelRefinerModel = `${process.env.RENDERING_HF_INFERENCE_API_REFINER_MODEL || ""}`const serverHuggingfaceInferenceApiModelTrigger = `${process.env.RENDERING_HF_INFERENCE_API_MODEL_TRIGGER || ""}`const serverReplicateApiKey = `${process.env.AUTH_REPLICATE_API_TOKEN || ""}`const serverReplicateApiModel = `${process.env.RENDERING_REPLICATE_API_MODEL || ""}`56 unmodified lineslet huggingfaceApiUrl = serverHuggingfaceApiUrllet huggingfaceInferenceApiModelRefinerModel = serverHuggingfaceInferenceApiModelRefinerModellet huggingfaceInferenceApiModelTrigger = serverHuggingfaceInferenceApiModelTriggerconst placeholder = "<USE YOUR OWN TOKEN>"33 unmodified lineshuggingfaceApiKey = settings.huggingfaceApiKeyhuggingfaceInferenceApiModel = settings.huggingfaceInferenceApiModelhuggingfaceInferenceApiModelTrigger = settings.huggingfaceInferenceApiModelTrigger}try {136 unmodified linesmethod: "POST",headers: {"Content-Type": "application/json",Authorization: `Bearer ${huggingfaceApiKey}`,},body: JSON.stringify({14 unmodified lines1516171819202156 unmodified lines7879808182838433 unmodified lines118119120121122123124136 unmodified lines26126226326426526626714 unmodified linesconst serverHuggingfaceInferenceApiModel = `${process.env.RENDERING_HF_INFERENCE_API_BASE_MODEL || ""}`const serverHuggingfaceInferenceApiModelRefinerModel = `${process.env.RENDERING_HF_INFERENCE_API_REFINER_MODEL || ""}`const serverHuggingfaceInferenceApiModelTrigger = `${process.env.RENDERING_HF_INFERENCE_API_MODEL_TRIGGER || ""}`const serverHuggingfaceInferenceApiFileType = `${process.env.RENDERING_HF_INFERENCE_API_FILE_TYPE || ""}`const serverReplicateApiKey = `${process.env.AUTH_REPLICATE_API_TOKEN || ""}`const serverReplicateApiModel = `${process.env.RENDERING_REPLICATE_API_MODEL || ""}`56 unmodified lineslet huggingfaceApiUrl = serverHuggingfaceApiUrllet huggingfaceInferenceApiModelRefinerModel = serverHuggingfaceInferenceApiModelRefinerModellet huggingfaceInferenceApiModelTrigger = serverHuggingfaceInferenceApiModelTriggerlet huggingfaceInferenceApiFileType = serverHuggingfaceInferenceApiFileTypeconst placeholder = "<USE YOUR OWN TOKEN>"33 unmodified lineshuggingfaceApiKey = settings.huggingfaceApiKeyhuggingfaceInferenceApiModel = settings.huggingfaceInferenceApiModelhuggingfaceInferenceApiModelTrigger = settings.huggingfaceInferenceApiModelTriggerhuggingfaceInferenceApiFileType = settings.huggingfaceInferenceApiFileType}try {136 unmodified linesmethod: "POST",headers: {"Content-Type": "application/json",Accept: huggingfaceInferenceApiFileType,Authorization: `Bearer ${huggingfaceApiKey}`,},body: JSON.stringify({
5 unmodified lines678910115 unmodified lineshuggingfaceApiKey: "",huggingfaceInferenceApiModel: "stabilityai/stable-diffusion-xl-base-1.0",huggingfaceInferenceApiModelTrigger: "",replicateApiKey: "",replicateApiModel: "stabilityai/sdxl",replicateApiModelVersion: "da77bc59ee60423279fd632efb4795ab731d9e3ca9705ef3341091fb989b7eaf",5 unmodified lines67891011125 unmodified lineshuggingfaceApiKey: "",huggingfaceInferenceApiModel: "stabilityai/stable-diffusion-xl-base-1.0",huggingfaceInferenceApiModelTrigger: "",huggingfaceInferenceApiFileType: "image/png",replicateApiKey: "",replicateApiModel: "stabilityai/sdxl",replicateApiModelVersion: "da77bc59ee60423279fd632efb4795ab731d9e3ca9705ef3341091fb989b7eaf",
12 unmodified lines13141516171812 unmodified lineshuggingfaceApiKey: getValidString(localStorage?.getItem?.(localStorageKeys.huggingfaceApiKey), defaultSettings.huggingfaceApiKey),huggingfaceInferenceApiModel: getValidString(localStorage?.getItem?.(localStorageKeys.huggingfaceInferenceApiModel), defaultSettings.huggingfaceInferenceApiModel),huggingfaceInferenceApiModelTrigger: getValidString(localStorage?.getItem?.(localStorageKeys.huggingfaceInferenceApiModelTrigger), defaultSettings.huggingfaceInferenceApiModelTrigger),replicateApiKey: getValidString(localStorage?.getItem?.(localStorageKeys.replicateApiKey), defaultSettings.replicateApiKey),replicateApiModel: getValidString(localStorage?.getItem?.(localStorageKeys.replicateApiModel), defaultSettings.replicateApiModel),replicateApiModelVersion: getValidString(localStorage?.getItem?.(localStorageKeys.replicateApiModelVersion), defaultSettings.replicateApiModelVersion),12 unmodified lines1314151617181912 unmodified lineshuggingfaceApiKey: getValidString(localStorage?.getItem?.(localStorageKeys.huggingfaceApiKey), defaultSettings.huggingfaceApiKey),huggingfaceInferenceApiModel: getValidString(localStorage?.getItem?.(localStorageKeys.huggingfaceInferenceApiModel), defaultSettings.huggingfaceInferenceApiModel),huggingfaceInferenceApiModelTrigger: getValidString(localStorage?.getItem?.(localStorageKeys.huggingfaceInferenceApiModelTrigger), defaultSettings.huggingfaceInferenceApiModelTrigger),huggingfaceInferenceApiFileType: getValidString(localStorage?.getItem?.(localStorageKeys.huggingfaceInferenceApiFileType), defaultSettings.huggingfaceInferenceApiFileType),replicateApiKey: getValidString(localStorage?.getItem?.(localStorageKeys.replicateApiKey), defaultSettings.replicateApiKey),replicateApiModel: getValidString(localStorage?.getItem?.(localStorageKeys.replicateApiModel), defaultSettings.replicateApiModel),replicateApiModelVersion: getValidString(localStorage?.getItem?.(localStorageKeys.replicateApiModelVersion), defaultSettings.replicateApiModelVersion),
42 unmodified lines43444546474899 unmodified lines14814915015115215342 unmodified lineslocalStorageKeys.huggingfaceInferenceApiModelTrigger,defaultSettings.huggingfaceInferenceApiModelTrigger)const [replicateApiKey, setReplicateApiKey] = useLocalStorage<string>(localStorageKeys.replicateApiKey,defaultSettings.replicateApiKey99 unmodified linesvalue={huggingfaceInferenceApiModel}/></Field><p className="text-sm text-zinc-700">Using a LoRA? Don't forget the trigger keyword! Also you will want to use the "Neutral" style.</p>42 unmodified lines4344454647484950515299 unmodified lines15215315415515615715815916016116216316416516616716842 unmodified lineslocalStorageKeys.huggingfaceInferenceApiModelTrigger,defaultSettings.huggingfaceInferenceApiModelTrigger)const [huggingfaceInferenceApiFileType, setHuggingfaceInferenceApiFileType] = useLocalStorage<string>(localStorageKeys.huggingfaceInferenceApiFileType,defaultSettings.huggingfaceInferenceApiFileType)const [replicateApiKey, setReplicateApiKey] = useLocalStorage<string>(localStorageKeys.replicateApiKey,defaultSettings.replicateApiKey99 unmodified linesvalue={huggingfaceInferenceApiModel}/></Field><Field><Label>The file type supported by the model (jpg, webp..):</Label><InputclassName="font-mono"placeholder="Inference API file type"onChange={(x) => {setHuggingfaceInferenceApiFileType(x.target.value)}}value={huggingfaceInferenceApiFileType}/></Field><p className="text-sm text-zinc-700">Using a LoRA? Don't forget the trigger keyword! Also you will want to use the "Neutral" style.</p>
5 unmodified lines678910115 unmodified lineshuggingfaceApiKey: "CONF_AUTH_HF_API_TOKEN",huggingfaceInferenceApiModel: "CONF_RENDERING_HF_INFERENCE_API_BASE_MODEL",huggingfaceInferenceApiModelTrigger: "CONF_RENDERING_HF_INFERENCE_API_BASE_MODEL_TRIGGER",replicateApiKey: "CONF_AUTH_REPLICATE_API_TOKEN",replicateApiModel: "CONF_RENDERING_REPLICATE_API_MODEL",replicateApiModelVersion: "CONF_RENDERING_REPLICATE_API_MODEL_VERSION",5 unmodified lines67891011125 unmodified lineshuggingfaceApiKey: "CONF_AUTH_HF_API_TOKEN",huggingfaceInferenceApiModel: "CONF_RENDERING_HF_INFERENCE_API_BASE_MODEL",huggingfaceInferenceApiModelTrigger: "CONF_RENDERING_HF_INFERENCE_API_BASE_MODEL_TRIGGER",huggingfaceInferenceApiFileType: "CONF_RENDERING_HF_INFERENCE_API_FILE_TYPE",replicateApiKey: "CONF_AUTH_REPLICATE_API_TOKEN",replicateApiModel: "CONF_RENDERING_REPLICATE_API_MODEL",replicateApiModelVersion: "CONF_RENDERING_REPLICATE_API_MODEL_VERSION",
9 unmodified lines101112131415161726 unmodified lines44454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241259 unmodified linesimport { getStory } from "./queries/getStory"import { BottomBar } from "./interface/bottom-bar"import { Page } from "./interface/page"import { LLMResponse } from "@/types"import { joinWords } from "@/lib/joinWords"export default function Main() {const [_isPending, startTransition] = useTransition()26 unmodified lines// I don't think we are going to need a rate limiter on the LLM part anymoreconst enableRateLimiter = false // `${process.env.NEXT_PUBLIC_ENABLE_RATE_LIMITER}` === "true"let llmResponse: LLMResponse = []const [stylePrompt, userStoryPrompt] = prompt.split("||").map(x => x.trim())try {llmResponse = await getStory({preset,prompt: joinWords([ userStoryPrompt ]),nbTotalPanels})console.log("LLM responded:", llmResponse)} catch (err) {console.log("LLM step failed due to:", err)console.log("we are now switching to a degraded mode, using 4 similar panels")llmResponse = []for (let p = 0; p < nbTotalPanels; p++) {llmResponse.push({panel: p,instructions: joinWords([stylePrompt,userStoryPrompt,`${".".repeat(p)}`,]),caption: "(Sorry, LLM generation failed: using degraded mode)"})}console.error(err)}// we have to limit the size of the prompt, otherwise the rest of the style won't be followedlet limitedStylePrompt = stylePrompt.trim().slice(0, 77).trim()if (limitedStylePrompt.length !== stylePrompt.length) {console.log("Sorry folks, the style prompt was cut to:", limitedStylePrompt)}// new experimental prompt: let's drop the user prompt, and only use the styleconst lightPanelPromptPrefix = joinWords(preset.imagePrompt(limitedStylePrompt))// this prompt will be used if the LLM generation failedconst degradedPanelPromptPrefix = joinWords([...preset.imagePrompt(limitedStylePrompt),// we re-inject the story, thenuserStoryPrompt])const newPanels: string[] = []const newCaptions: string[] = []setWaitABitMore(true)console.log("Panel prompts for SDXL:")for (let p = 0; p < nbTotalPanels; p++) {newCaptions.push(llmResponse[p]?.caption.trim() || "...")const newPanel = joinWords([// what we do here is that ideally we give full control to the LLM for prompting,// unless there was a catastrophic failure, in that case we preserve the original promptllmResponse[p]?.instructions? lightPanelPromptPrefix: degradedPanelPromptPrefix,llmResponse[p]?.instructions])newPanels.push(newPanel)console.log(newPanel)}setCaptions(newCaptions)setPanels(newPanels)setTimeout(() => {setGeneratingStory(false)setWaitABitMore(false)}, enableRateLimiter ? 12000 : 0)})}, [prompt, preset?.label, nbTotalPanels]) // important: we need to react to preset changes too9 unmodified lines10111213141516171826 unmodified lines454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361379 unmodified linesimport { getStory } from "./queries/getStory"import { BottomBar } from "./interface/bottom-bar"import { Page } from "./interface/page"import { GeneratedPanel } from "@/types"import { joinWords } from "@/lib/joinWords"import { getStoryContinuation } from "./queries/getStoryContinuation"export default function Main() {const [_isPending, startTransition] = useTransition()26 unmodified lines// I don't think we are going to need a rate limiter on the LLM part anymoreconst enableRateLimiter = false // `${process.env.NEXT_PUBLIC_ENABLE_RATE_LIMITER}` === "true"const [stylePrompt, userStoryPrompt] = prompt.split("||").map(x => x.trim())// we have to limit the size of the prompt, otherwise the rest of the style won't be followedlet limitedStylePrompt = stylePrompt.trim().slice(0, 77).trim()if (limitedStylePrompt.length !== stylePrompt.length) {console.log("Sorry folks, the style prompt was cut to:", limitedStylePrompt)}// new experimental prompt: let's drop the user prompt, and only use the styleconst lightPanelPromptPrefix = joinWords(preset.imagePrompt(limitedStylePrompt))// this prompt will be used if the LLM generation failedconst degradedPanelPromptPrefix = joinWords([...preset.imagePrompt(limitedStylePrompt),// we re-inject the story, thenuserStoryPrompt])let existingPanels: GeneratedPanel[] = []const newPanelsPrompts: string[] = []const newCaptions: string[] = []const nbPanelsToGenerate = 2for (let currentPanel = 0;currentPanel < nbTotalPanels;currentPanel += nbPanelsToGenerate) {if (currentPanel > (nbTotalPanels / 2)) {console.log("good, we are half way there, hold tight!")// setWaitABitMore(true)}try {const candidatePanels = await getStoryContinuation({preset,stylePrompt,userStoryPrompt,nbPanelsToGenerate,existingPanels,})console.log("LLM generated some new panels:", candidatePanels)existingPanels.push(...candidatePanels)console.log(`Converting the ${nbPanelsToGenerate} new panels into image prompts..`)const startAt = currentPanelconst endAt = currentPanel + nbPanelsToGeneratefor (let p = startAt; p < endAt; p++) {newCaptions.push(existingPanels[p]?.caption.trim() || "...")const newPanel = joinWords([// what we do here is that ideally we give full control to the LLM for prompting,// unless there was a catastrophic failure, in that case we preserve the original promptexistingPanels[p]?.instructions? lightPanelPromptPrefix: degradedPanelPromptPrefix,existingPanels[p]?.instructions])newPanelsPrompts.push(newPanel)console.log(`Image prompt for panel ${p} => "${newPanel}"`)}// update the frontendconsole.log("updating the frontend..")setCaptions(newCaptions)setPanels(newPanelsPrompts)setGeneratingStory(false)} catch (err) {console.log("failed to generate the story, aborting here")setGeneratingStory(false)break}}/*setTimeout(() => {setGeneratingStory(false)setWaitABitMore(false)}, enableRateLimiter ? 12000 : 0)*/})}, [prompt, preset?.label, nbTotalPanels]) // important: we need to react to preset changes too
123456789101112132 unmodified lines161718192021222324252627282930313233342 unmodified lines3738394041424320 unmodified lines646566676869707172731 unmodified line757677787980814 unmodified lines8687888990import { dirtyLLMJsonParser } from "@/lib/dirtyLLMJsonParser"import { dirtyCaptionCleaner } from "@/lib/dirtyCaptionCleaner"import { predict } from "./predict"import { Preset } from "../engine/presets"import { LLMResponse } from "@/types"import { cleanJson } from "@/lib/cleanJson"import { createZephyrPrompt } from "@/lib/createZephyrPrompt"export const getStory = async ({preset,prompt = "",2 unmodified linespreset: Preset;prompt: string;nbTotalPanels: number;}): Promise<LLMResponse> => {// throw new Error("Planned maintenance")// In case you need to quickly debug the RENDERING engine you can uncomment this:// return mockLLMResponseconst query = createZephyrPrompt([{role: "system",content: [`You are a writer specialized in ${preset.llmPrompt}`,`Please write detailed drawing instructions and a short (2-3 sentences long) speech caption for the ${nbTotalPanels} panels of a new story. Please make sure each of the ${nbTotalPanels} panels include info about character gender, age, origin, clothes, colors, location, lights, etc.`,`Give your response as a VALID JSON array like this: \`Array<{ panel: number; instructions: string; caption: string}>\`.`,// `Give your response as Markdown bullet points.`,`Be brief in your ${nbTotalPanels} instructions and narrative captions, don't add your own comments. The whole story must be captivating, smart, entertaining. Be straight to the point, and never reply things like "Sure, I can.." etc. Reply using valid JSON.`].filter(item => item).join("\n")2 unmodified linesrole: "user",content: `The story is: ${prompt}`,}]) + "\n[{"let result = ""20 unmodified lines// console.log("Raw response from LLM:", result)const tmp = cleanJson(result)let llmResponse: LLMResponse = []try {llmResponse = dirtyLLMJsonParser(tmp)} catch (err) {// console.log(`failed to read LLM response: ${err}`)// console.log(`original response was:`, result)1 unmodified line// in case of failure here, it might be because the LLM hallucinated a completely different response,// such as markdown. There is no real solution.. but we can try a fallback:llmResponse = (tmp.split("*").map(item => item.trim()).map((cap, i) => ({4 unmodified lines)}return llmResponse.map(res => dirtyCaptionCleaner(res))}123456789101112132 unmodified lines161718192021222324252627282930313233342 unmodified lines3738394041424320 unmodified lines646566676869707172731 unmodified line757677787980814 unmodified lines8687888990import { predict } from "./predict"import { Preset } from "../engine/presets"import { GeneratedPanels } from "@/types"import { cleanJson } from "@/lib/cleanJson"import { createZephyrPrompt } from "@/lib/createZephyrPrompt"import { dirtyGeneratedPanelCleaner } from "@/lib/dirtyGeneratedPanelCleaner"import { dirtyGeneratedPanelsParser } from "@/lib/dirtyGeneratedPanelsParser"export const getStory = async ({preset,prompt = "",2 unmodified linespreset: Preset;prompt: string;nbTotalPanels: number;}): Promise<GeneratedPanels> => {// throw new Error("Planned maintenance")// In case you need to quickly debug the RENDERING engine you can uncomment this:// return mockGeneratedPanelsconst query = createZephyrPrompt([{role: "system",content: [`You are a writer specialized in ${preset.llmPrompt}`,`Please write detailed drawing instructions and short (2-3 sentences long) speech captions for the ${nbTotalPanels} panels of a new story. Please make sure each of the ${nbTotalPanels} panels include info about character gender, age, origin, clothes, colors, location, lights, etc.`,`Give your response as a VALID JSON array like this: \`Array<{ panel: number; instructions: string; caption: string; }>\`.`,// `Give your response as Markdown bullet points.`,`Be brief in your ${nbTotalPanels} instructions and narrative captions, don't add your own comments. The whole story must be captivating, smart, entertaining. Be straight to the point, and never reply things like "Sure, I can.." etc. Reply using valid JSON.`].filter(item => item).join("\n")2 unmodified linesrole: "user",content: `The story is: ${prompt}`,}]) + "\n```[{"let result = ""20 unmodified lines// console.log("Raw response from LLM:", result)const tmp = cleanJson(result)let GeneratedPanels: GeneratedPanels = []try {GeneratedPanels = dirtyGeneratedPanelsParser(tmp)} catch (err) {// console.log(`failed to read LLM response: ${err}`)// console.log(`original response was:`, result)1 unmodified line// in case of failure here, it might be because the LLM hallucinated a completely different response,// such as markdown. There is no real solution.. but we can try a fallback:GeneratedPanels = (tmp.split("*").map(item => item.trim()).map((cap, i) => ({4 unmodified lines)}return GeneratedPanels.map(res => dirtyGeneratedPanelCleaner(res))}
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596import { dirtyLLMJsonParser } from "@/lib/dirtyLLMJsonParser"import { dirtyCaptionCleaner } from "@/lib/dirtyCaptionCleaner"import { predict } from "./predict"import { Preset } from "../engine/presets"import { LLMResponse } from "@/types"import { cleanJson } from "@/lib/cleanJson"import { createZephyrPrompt } from "@/lib/createZephyrPrompt"export const getStoryContinuation = async ({preset,prompt = "",nbTotalPanels = 2,previousCaptions = [],}: {preset: Preset;prompt: string;nbTotalPanels: number;previousCaptions: string[];}): Promise<LLMResponse> => {// throw new Error("Planned maintenance")// In case you need to quickly debug the RENDERING engine you can uncomment this:// return mockLLMResponseconst previousCaptionsTemplate = previousCaptions.length? `To help you, here are the previous panels and their captions (note: if you see an anomaly here eg. no caption or the same description repeated multiple times, do not hesitate to fix the story): ${JSON.stringify(previousCaptions, null, 2)}`: ''const query = createZephyrPrompt([{role: "system",content: [`You are a writer specialized in ${preset.llmPrompt}`,`Please write detailed drawing instructions and a short (2-3 sentences long) speech caption for the next ${nbTotalPanels} panels of a new story, but keep it open-ended (it will be continued and expanded later). Please make sure each of those ${nbTotalPanels} panels include info about character gender, age, origin, clothes, colors, location, lights, etc.`,`Give your response as a VALID JSON array like this: \`Array<{ panel: number; instructions: string; caption: string}>\`.`,// `Give your response as Markdown bullet points.`,`Be brief in your ${nbTotalPanels} instructions and narrative captions, don't add your own comments. The captions must be captivating, smart, entertaining. Be straight to the point, and never reply things like "Sure, I can.." etc. Reply using valid JSON.`].filter(item => item).join("\n")},{role: "user",content: `The story is about: ${prompt}.${previousCaptionsTemplate}`,}]) + "\n[{"let result = ""try {// console.log(`calling predict(${query}, ${nbTotalPanels})`)result = `${await predict(query, nbTotalPanels) || ""}`.trim()if (!result.length) {throw new Error("empty result!")}} catch (err) {// console.log(`prediction of the story failed, trying again..`)try {result = `${await predict(query+".", nbTotalPanels) || ""}`.trim()if (!result.length) {throw new Error("empty result!")}} catch (err) {console.error(`prediction of the story failed again 💩`)throw new Error(`failed to generate the story ${err}`)}}// console.log("Raw response from LLM:", result)const tmp = cleanJson(result)let llmResponse: LLMResponse = []try {llmResponse = dirtyLLMJsonParser(tmp)} catch (err) {// console.log(`failed to read LLM response: ${err}`)// console.log(`original response was:`, result)// in case of failure here, it might be because the LLM hallucinated a completely different response,// such as markdown. There is no real solution.. but we can try a fallback:llmResponse = (tmp.split("*").map(item => item.trim()).map((cap, i) => ({panel: i,caption: cap,instructions: cap,})))}return llmResponse.map(res => dirtyCaptionCleaner(res))}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768import { Preset } from "../engine/presets"import { GeneratedPanel } from "@/types"import { predictNextPanels } from "./predictNextPanels"import { joinWords } from "@/lib/joinWords"export const getStoryContinuation = async ({preset,stylePrompt = "",userStoryPrompt = "",nbPanelsToGenerate = 2,existingPanels = [],}: {preset: Preset;stylePrompt: string;userStoryPrompt: string;nbPanelsToGenerate: number;existingPanels: GeneratedPanel[];}): Promise<GeneratedPanel[]> => {let panels: GeneratedPanel[] = []const startAt: number = existingPanels.at(-1)?.panel || existingPanels.length || 0const endAt: number = startAt + nbPanelsToGeneratetry {const prompt = joinWords([ userStoryPrompt ])const panelCandidates: GeneratedPanel[] = await predictNextPanels({preset,prompt,nbPanelsToGenerate,existingPanels,})console.log("LLM responded with panels:", panelCandidates)// we clean the output from the LLM// most importantly, we need to adjust the panel index,// to start from where we last finishedfor (let p = startAt; p < endAt; p++) {panels.push({panel: p,instructions: `${panelCandidates[p]?.instructions || ""}`,caption: `${panelCandidates[p]?.caption || ""}`,})}} catch (err) {console.log("LLM step failed due to:", err)console.log("we are now switching to a degraded mode, using 4 similar panels")panels = []for (let p = startAt; p < endAt; p++) {panels.push({panel: p,instructions: joinWords([stylePrompt,userStoryPrompt,`${".".repeat(p)}`,]),caption: "(Sorry, LLM generation failed: using degraded mode)"})}console.error(err)} finally {return panels}}
123456import { LLMResponse } from "@/types"export const mockLLMResponse: LLMResponse = [{"panel": 1,"instructions": "wide shot of detective walking towards a UFO crash site","caption": "Detective Jameson investigates a UFO crash in the desert"123456import { GeneratedPanels } from "@/types"export const mockGeneratedPanels: GeneratedPanels = [{"panel": 1,"instructions": "wide shot of detective walking towards a UFO crash site","caption": "Detective Jameson investigates a UFO crash in the desert"
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
import { predict } from "./predict"import { Preset } from "../engine/presets"import { GeneratedPanel } from "@/types"import { cleanJson } from "@/lib/cleanJson"import { createZephyrPrompt } from "@/lib/createZephyrPrompt"import { dirtyGeneratedPanelCleaner } from "@/lib/dirtyGeneratedPanelCleaner"import { dirtyGeneratedPanelsParser } from "@/lib/dirtyGeneratedPanelsParser"
export const predictNextPanels = async ({ preset, prompt = "", nbPanelsToGenerate = 2, existingPanels = [],}: { preset: Preset; prompt: string; nbPanelsToGenerate: number; existingPanels: GeneratedPanel[];}): Promise<GeneratedPanel[]> => { // throw new Error("Planned maintenance") // In case you need to quickly debug the RENDERING engine you can uncomment this: // return mockGeneratedPanels
const existingPanelsTemplate = existingPanels.length ? ` To help you, here are the previous panels and their captions (note: if you see an anomaly here eg. no caption or the same description repeated multiple times, do not hesitate to fix the story): ${JSON.stringify(existingPanels, null, 2)}` : ''
const query = createZephyrPrompt([ { role: "system", content: [ `You are a writer specialized in ${preset.llmPrompt}`, `Please write detailed drawing instructions and short (2-3 sentences long) speech captions for the next ${nbPanelsToGenerate} panels of a new story, but keep it open-ended (it will be continued and expanded later). Please make sure each of those ${nbPanelsToGenerate} panels include info about character gender, age, origin, clothes, colors, location, lights, etc.`, `Give your response as a VALID JSON array like this: \`Array<{ panel: number; instructions: string; caption: string; }>\`.`, // `Give your response as Markdown bullet points.`, `Be brief in your ${nbPanelsToGenerate} instructions and narrative captions, don't add your own comments. The captions must be captivating, smart, entertaining. Be straight to the point, and never reply things like "Sure, I can.." etc. Reply using valid JSON.` ].filter(item => item).join("\n") }, { role: "user", content: `The story is about: ${prompt}.${existingPanelsTemplate}`, } ]) + "\n```[{"
let result = ""
try { // console.log(`calling predict(${query}, ${nbTotalPanels})`) result = `${await predict(query, nbPanelsToGenerate) || ""}`.trim() if (!result.length) { throw new Error("empty result!") } } catch (err) { // console.log(`prediction of the story failed, trying again..`) try { result = `${await predict(query+".", nbPanelsToGenerate) || ""}`.trim() if (!result.length) { throw new Error("empty result!") } } catch (err) { console.error(`prediction of the story failed again 💩`) throw new Error(`failed to generate the story ${err}`) } }
// console.log("Raw response from LLM:", result) const tmp = cleanJson(result) let generatedPanels: GeneratedPanel[] = []
try { generatedPanels = dirtyGeneratedPanelsParser(tmp) } catch (err) { // console.log(`failed to read LLM response: ${err}`) // console.log(`original response was:`, result)
// in case of failure here, it might be because the LLM hallucinated a completely different response, // such as markdown. There is no real solution.. but we can try a fallback:
generatedPanels = ( tmp.split("*") .map(item => item.trim()) .map((cap, i) => ({ panel: i, caption: cap, instructions: cap, })) ) }
return generatedPanels.map(res => dirtyGeneratedPanelCleaner(res))}123456import { dirtyLLMResponseCleaner } from "./dirtyLLMResponseCleaner"export function cleanJson(input: string) {if (input.includes('```')) {input = input.split('```')[0]123456import { dirtyLLMResponseCleaner } from "./dirtyLLMResponseCleaner"export function cleanJson(input: string): string {if (input.includes('```')) {input = input.split('```')[0]
12345678910111213141516export function dirtyCaptionCleaner({panel,instructions,caption}: {panel: number;instructions: string;caption: string}) {let newCaption = caption.split(":").pop()?.trim() || ""let newInstructions = (// need to remove from LLM garbage here, too(instructions.split(":").pop() || "").replaceAll("Draw a", "").replaceAll("Draw the", "").replaceAll("Draw", "")1234567891011121314import { GeneratedPanel } from "@/types"export function dirtyGeneratedPanelCleaner({panel,instructions,caption}: GeneratedPanel): GeneratedPanel {let newCaption = `${caption || ""}`.split(":").pop()?.trim() || ""let newInstructions = (// need to remove from LLM garbage here, too(`${instructions || ""}`.split(":").pop() || "").replaceAll("Draw a", "").replaceAll("Draw the", "").replaceAll("Draw", "")
123456781 unmodified line10111213141516import { LLMResponse } from "@/types"import { cleanJson } from "./cleanJson"import { parseBadJSON } from "./parseBadJSON"export function dirtyLLMJsonParser(input: string): LLMResponse {if (input.includes("```")) {input = input.split("```")[0]1 unmodified line// we only keep what's after the first [let jsonOrNot = cleanJson(input)const jsonData = parseBadJSON(jsonOrNot) as LLMResponseconst results = jsonData.map((item, i) => {let panel = i123456781 unmodified line10111213141516import { GeneratedPanel } from "@/types"import { cleanJson } from "./cleanJson"import { parseBadJSON } from "./parseBadJSON"export function dirtyGeneratedPanelsParser(input: string): GeneratedPanel[] {if (input.includes("```")) {input = input.split("```")[0]1 unmodified line// we only keep what's after the first [let jsonOrNot = cleanJson(input)const jsonData = parseBadJSON(jsonOrNot) as GeneratedPanel[]const results = jsonData.map((item, i) => {let panel = i
1234export function dirtyLLMResponseCleaner(input: string) {let str = (`${input || ""}`// a summary of all the weird hallucinations I saw it make..1234export function dirtyLLMResponseCleaner(input: string): string {let str = (`${input || ""}`// a summary of all the weird hallucinations I saw it make..
1234567899 unmodified lines192021222324import { LLMResponse } from "@/types"export function parseBadJSON(jsonLikeString: string): LLMResponse {try {return JSON.parse(jsonLikeString) as LLMResponse} catch (err) {var regex = /\{\s*"panel":\s*(\d+),\s*"instructions"\s*:\s*"([^"]+)",\s*"caption":\s*"([^"]*)"\s*\}/gs;9 unmodified linesresults.push(json);}return results as LLMResponse}}1234567899 unmodified lines192021222324import { GeneratedPanels } from "@/types"export function parseBadJSON(jsonLikeString: string): GeneratedPanels {try {return JSON.parse(jsonLikeString) as GeneratedPanels} catch (err) {var regex = /\{\s*"panel":\s*(\d+),\s*"instructions"\s*:\s*"([^"]+)",\s*"caption":\s*"([^"]*)"\s*\}/gs;9 unmodified linesresults.push(json);}return results as GeneratedPanels}}
86 unmodified lines8788899091929360 unmodified lines15415515615715815986 unmodified lineserror?: string}export type LLMResponse = Array<{panel: number; instructions: string; caption: string }>export type LLMEngine =| "INFERENCE_API"60 unmodified lineshuggingfaceApiKey: stringhuggingfaceInferenceApiModel: stringhuggingfaceInferenceApiModelTrigger: stringreplicateApiKey: stringreplicateApiModel: stringreplicateApiModelVersion: string86 unmodified lines8788899091929394959697989960 unmodified lines16016116216316416516686 unmodified lineserror?: string}export type GeneratedPanel = {panel: numberinstructions: stringcaption: string}export type GeneratedPanels = GeneratedPanel[]export type LLMEngine =| "INFERENCE_API"60 unmodified lineshuggingfaceApiKey: stringhuggingfaceInferenceApiModel: stringhuggingfaceInferenceApiModelTrigger: stringhuggingfaceInferenceApiFileType: stringreplicateApiKey: stringreplicateApiModel: stringreplicateApiModelVersion: string
.env+3
src/app/engine/render.ts+4
src/app/interface/settings-dialog/defaultSettings.ts+1
src/app/interface/settings-dialog/getSettings.ts+1
src/app/interface/settings-dialog/index.tsx+15
src/app/interface/settings-dialog/localStorageKeys.ts+1
src/app/main.tsx+65-53
src/app/queries/getStory.ts+13-13
src/app/queries/getStoryContinuation.ts+53-81
src/app/queries/mockLLMResponse.ts+2-2
src/app/queries/predictNextPanels.tsAdded+95
src/lib/cleanJson.ts+1-1
src/lib/dirtyCaptionCleaner.ts → src/lib/dirtyGeneratedPanelCleaner.tsRenamed+6-8
src/lib/dirtyLLMJsonParser.ts → src/lib/dirtyGeneratedPanelsParser.tsRenamed+3-3
src/lib/dirtyLLMResponseCleaner.ts+1-1
src/lib/parseBadJSON.ts+4-4
src/types.ts+8-1