Invoke is a leading creative engine that uses image and video generation models to empower professionals, artists, and enthusiasts to generate and create visual media using the latest AI-driven technologies. The solution offers an industry-leading application interface, and serves as the foundation for multiple commercial products.
TypeScript ai-artartificial-intelligencegenerative-artimage-generationimg2imginpaintinglatent-diffusionlinuxmacosoutpaintingstable-diffusiontxt2imgwindows
feat(webv2): import a wildcard folder
joshistoastc636ab1ef5f1
diff --git a/invokeai/frontend/webv2/public/locales/en.json b/invokeai/frontend/webv2/public/locales/en.jsonindex 1b88a76905..79a9b89204 100644--- a/invokeai/frontend/webv2/public/locales/en.json+++ b/invokeai/frontend/webv2/public/locales/en.json@@ -1005,6 +1005,9 @@"importRejectedValueTooLong": "A value is too long","importedCount_one": "Imported {{count}} wildcard","importedCount_other": "Imported {{count}} wildcards",+ "importFiles": "From files…",+ "importFolder": "From a folder…",+ "importNoWildcardFiles": "That folder has no wildcard files in it","couldNotImport": "Could not import these wildcards","couldNotImportAfter": "Stopped after importing {{done}} of {{total}} wildcards","couldNotExport": "Could not export your wildcards",diff --git a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/WildcardTransferActions.tsx b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/WildcardTransferActions.tsxindex b80e4591f8..002b581e18 100644--- a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/WildcardTransferActions.tsx+++ b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/WildcardTransferActions.tsx@@ -9,6 +9,7 @@ import { useGenerationUi } from '@features/generation/ui/GenerationUiContext';import { WildcardImportDialog } from '@features/generation/ui/promptFields/WildcardImportDialog';import {downloadWildcards,+ isSupportedWildcardFile,readWildcardFiles,WILDCARD_IMPORT_ACCEPT,WildcardFileError,@@ -21,6 +22,10 @@ import { useCallback, useRef, useState } from 'react';import { useTranslation } from 'react-i18next';const EXPORT_FORMATS: WildcardExportFormat[] = ['yaml', 'json'];+const IMPORT_SOURCES = ['files', 'folder'] as const;++/** Not in React's DOM typings, and `multiple` comes along with it implicitly. */+const DIRECTORY_INPUT_PROPS = { directory: '', webkitdirectory: '' } as unknown as { webkitdirectory: string };/*** Import and export for the whole catalog.@@ -34,6 +39,7 @@ export const WildcardTransferActions = ({ catalog }: { catalog: WildcardCatalogconst { t } = useTranslation();const { notifications } = useGenerationUi();const fileInputRef = useRef<HTMLInputElement | null>(null);+ const directoryInputRef = useRef<HTMLInputElement | null>(null);const [isBusy, setIsBusy] = useState(false);const [pendingEntries, setPendingEntries] = useState<WildcardImportEntry[] | null>(null);@@ -126,8 +132,6 @@ export const WildcardTransferActions = ({ catalog }: { catalog: WildcardCatalog[catalog.wildcards, reportError, t]);- const pickFiles = useCallback(() => fileInputRef.current?.click(), []);-const handleFileChange = useCallback((event: ChangeEvent<HTMLInputElement>) => {const files = [...(event.currentTarget.files ?? [])];@@ -141,6 +145,29 @@ export const WildcardTransferActions = ({ catalog }: { catalog: WildcardCatalog[startImport]);+ // A folder hands over everything in it, so the readmes and `.DS_Store` are+ // dropped here rather than failing the import the way a named file would.+ const handleDirectoryChange = useCallback(+ (event: ChangeEvent<HTMLInputElement>) => {+ const files = [...(event.currentTarget.files ?? [])].filter(isSupportedWildcardFile);++ event.currentTarget.value = '';++ if (files.length === 0) {+ notifications.info(t('widgets.generate.dynamicPrompts.importNoWildcardFiles'));+ return;+ }++ void startImport(files);+ },+ [notifications, startImport, t]+ );++ const handleImportSelect = useCallback(+ (details: { value: string }) => (details.value === 'folder' ? directoryInputRef : fileInputRef).current?.click(),+ []+ );+const handleExportSelect = useCallback((details: { value: string }) => void runExport(details.value as WildcardExportFormat),[runExport]@@ -155,10 +182,27 @@ export const WildcardTransferActions = ({ catalog }: { catalog: WildcardCatalogreturn (<HStack gap="0.5">- <Button disabled={isBusy} size="2xs" variant="ghost" onClick={pickFiles}>- <UploadIcon />- {t('widgets.generate.dynamicPrompts.import')}- </Button>+ <Menu.Root onSelect={handleImportSelect}>+ <Menu.Trigger asChild>+ <Button disabled={isBusy} size="2xs" variant="ghost">+ <UploadIcon />+ {t('widgets.generate.dynamicPrompts.import')}+ </Button>+ </Menu.Trigger>+ <Portal>+ <Menu.Positioner>+ <MenuContent minW="10rem">+ {IMPORT_SOURCES.map((source) => (+ <Menu.Item key={source} value={source}>+ <Menu.ItemText fontSize="xs">+ {t(`widgets.generate.dynamicPrompts.import${source === 'folder' ? 'Folder' : 'Files'}`)}+ </Menu.ItemText>+ </Menu.Item>+ ))}+ </MenuContent>+ </Menu.Positioner>+ </Portal>+ </Menu.Root><Menu.Root onSelect={handleExportSelect}><Menu.Trigger asChild><Button disabled={isBusy || catalog.wildcards.length === 0} size="2xs" variant="ghost">@@ -189,6 +233,10 @@ export const WildcardTransferActions = ({ catalog }: { catalog: WildcardCatalogtype="file"onChange={handleFileChange}/>+ {/* A second input, because one cannot be both. The a1111 layout nests+ wildcards in folders, and only a directory pick supplies the relative+ path that turns `animals/dogs.txt` into `animals/dogs`. */}+ <input {...DIRECTORY_INPUT_PROPS} hidden ref={directoryInputRef} type="file" onChange={handleDirectoryChange} />{pendingEntries ? (<WildcardImportDialog entries={pendingEntries} onCancel={cancelImport} onConfirm={confirmImport} />) : null}diff --git a/invokeai/frontend/webv2/src/features/generation/ui/wildcardFiles.browser.test.ts b/invokeai/frontend/webv2/src/features/generation/ui/wildcardFiles.browser.test.tsindex f64118ba30..0588c0939b 100644--- a/invokeai/frontend/webv2/src/features/generation/ui/wildcardFiles.browser.test.ts+++ b/invokeai/frontend/webv2/src/features/generation/ui/wildcardFiles.browser.test.ts@@ -1,8 +1,17 @@-import { readWildcardFiles, WildcardFileError } from '@features/generation/ui/wildcardFiles';+import { isSupportedWildcardFile, readWildcardFiles, WildcardFileError } from '@features/generation/ui/wildcardFiles';import { describe, expect, it } from 'vitest';const file = (name: string, contents: string) => new File([contents], name, { type: 'text/plain' });+/** What a directory pick hands over: a name plus the path relative to the root. */+const inFolder = (path: string, contents: string): File => {+ const picked = file(path.slice(path.lastIndexOf('/') + 1), contents);++ Object.defineProperty(picked, 'webkitRelativePath', { value: path });++ return picked;+};+describe('readWildcardFiles', () => {it('reads a text file as one wildcard named after it', async () => {await expect(readWildcardFiles([file('colours.txt', 'red\n# a note\n\ngreen')])).resolves.toEqual([@@ -49,4 +58,37 @@ describe('readWildcardFiles', () => {await expect(readWildcardFiles([file('huge.json', huge)])).rejects.toBeInstanceOf(WildcardFileError);});++ // The whole point of picking a folder: a1111 nests wildcards in directories,+ // and only the relative path says that `dogs.txt` is `animals/dogs`. Picking+ // the two files by hand gives two wildcards both called `dogs`.+ it('turns a folder`s nesting into `/` names', async () => {+ const picked = [inFolder('wildcards/animals/dogs.txt', 'corgi'), inFolder('wildcards/moods/dogs.txt', 'sleepy')];++ await expect(readWildcardFiles(picked)).resolves.toEqual([+ { name: 'wildcards/animals/dogs', values: ['corgi'] },+ { name: 'wildcards/moods/dogs', values: ['sleepy'] },+ ]);+ });+});++describe('isSupportedWildcardFile', () => {+ // A folder pick hands over everything in it, so the ones that are not+ // wildcards get dropped rather than failing the whole import.+ it('keeps the wildcard files and drops the rest', () => {+ const picked = [+ inFolder('wildcards/colours.txt', 'red'),+ inFolder('wildcards/all.yaml', 'a: [b]'),+ inFolder('wildcards/LICENSE', 'text'),+ inFolder('wildcards/README.md', '# notes'),+ inFolder('wildcards/preview.png', 'binary'),+ inFolder('wildcards/.DS_Store', 'binary'),+ ];++ expect(picked.filter(isSupportedWildcardFile).map((entry) => entry.name)).toEqual([+ 'colours.txt',+ 'all.yaml',+ 'LICENSE',+ ]);+ });});diff --git a/invokeai/frontend/webv2/src/features/generation/ui/wildcardFiles.ts b/invokeai/frontend/webv2/src/features/generation/ui/wildcardFiles.tsindex 7276530765..cd40e4b637 100644--- a/invokeai/frontend/webv2/src/features/generation/ui/wildcardFiles.ts+++ b/invokeai/frontend/webv2/src/features/generation/ui/wildcardFiles.ts@@ -56,12 +56,31 @@ const MAX_IMPORT_WILDCARDS = 20_000;* this app all land in the same list — mixing them in one selection is fine, and* duplicate names across files are sorted out later by `planWildcardImport`.*/-/** `a.txt` and a bare `wildcards` yes, `README.md` and `preview.png` no. */+/**+ * `a.txt` and a bare `LICENSE` yes; `README.md`, `preview.png` and `.DS_Store`+ * no. An extensionless file is fair game — a wildcard file has no header to+ * check — but a name that is nothing *but* an extension is a dotfile, and every+ * folder pick brings a few of those along.+ */const isTextWildcardFile = (path: string): boolean => {const name = path.slice(path.lastIndexOf('/') + 1);const dot = name.lastIndexOf('.');- return dot <= 0 || name.slice(dot).toLowerCase() === '.txt';+ return dot < 0 || name.slice(dot).toLowerCase() === '.txt';+};++/**+ * Whether this file is worth handing to `readWildcardFiles` at all.+ *+ * For a file the user picked by name, being unreadable is worth saying out loud,+ * so `readWildcardFiles` throws. A directory pick is the opposite: it hands over+ * everything in the folder, readmes and `.DS_Store` included, and refusing the+ * whole import over one of them would make folder picking useless.+ */+export const isSupportedWildcardFile = (file: File): boolean => {+ const path = getFilePath(file);++ return hasExtension(path, '.yaml', '.yml', '.json') || isTextWildcardFile(path);};export const readWildcardFiles = async (files: readonly File[]): Promise<ParsedWildcard[]> => {