Skip to content

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.

5.2 KB
Raw Blame
import { IconButton } from '@invoke-ai/ui-library';
import { toast } from 'features/toast/toast';
import type { ChangeEvent } from 'react';
import { memo, useCallback, useRef } from 'react';
import { useTranslation } from 'react-i18next';
import { PiUploadSimpleBold } from 'react-icons/pi';
import { useUpdateModelImageMutation, useUpdateModelMutation } from 'services/api/endpoints/models';
import type { AnyModelConfigWithExternal } from 'services/api/types';

import { dataUrlToFile, isImageDataUrl, validateImportData } from './modelSettingsIO';

type Props = {
  modelConfig: AnyModelConfigWithExternal;
};

export const ModelSettingsImportButton = memo(({ modelConfig }: Props) => {
  const { t } = useTranslation();
  const fileInputRef = useRef<HTMLInputElement>(null);
  const [updateModel] = useUpdateModelMutation();
  const [updateModelImage] = useUpdateModelImageMutation();

  const applySettings = useCallback(
    async (data: Record<string, unknown>) => {
      const body: Record<string, unknown> = {};
      const skippedFields: string[] = [];

      const importableFields = [
        'name',
        'description',
        'source_url',
        'default_settings',
        'trigger_phrases',
        'cpu_only',
      ] as const;

      for (const field of importableFields) {
        if (!(field in data) || data[field] === undefined || data[field] === null) {
          continue;
        }
        if (field in modelConfig) {
          body[field] = data[field];
        } else {
          skippedFields.push(field);
        }
      }

      const coverImageDataUrl =
        'cover_image' in data && typeof data.cover_image === 'string' && isImageDataUrl(data.cover_image)
          ? data.cover_image
          : null;

      if (Object.keys(body).length === 0 && !coverImageDataUrl) {
        if (skippedFields.length > 0) {
          toast({
            id: 'SETTINGS_IMPORT_INCOMPATIBLE',
            title: t('modelManager.settingsImportIncompatible'),
            status: 'warning',
          });
        }
        return;
      }

      let appliedAnything = false;
      if (Object.keys(body).length > 0) {
        try {
          await updateModel({
            key: modelConfig.key,
            body,
          }).unwrap();
          appliedAnything = true;
        } catch {
          toast({
            id: 'SETTINGS_IMPORT_FAILED',
            title: t('modelManager.settingsImportFailed'),
            status: 'error',
          });
          return;
        }
      }

      if (coverImageDataUrl) {
        const imageFile = dataUrlToFile(coverImageDataUrl, `${modelConfig.key}.png`);
        if (!imageFile) {
          skippedFields.push('cover_image');
        } else {
          try {
            await updateModelImage({ key: modelConfig.key, image: imageFile }).unwrap();
            appliedAnything = true;
          } catch {
            skippedFields.push('cover_image');
          }
        }
      }

      if (!appliedAnything) {
        toast({
          id: 'SETTINGS_IMPORT_FAILED',
          title: t('modelManager.settingsImportFailed'),
          status: 'error',
        });
        return;
      }

      if (skippedFields.length > 0) {
        toast({
          id: 'SETTINGS_IMPORTED',
          title: t('modelManager.settingsImportedPartial', { fields: skippedFields.join(', ') }),
          status: 'warning',
        });
      } else {
        toast({
          id: 'SETTINGS_IMPORTED',
          title: t('modelManager.settingsImported'),
          status: 'success',
        });
      }
    },
    [modelConfig, updateModel, updateModelImage, t]
  );

  const handleFileChange = useCallback(
    (e: ChangeEvent<HTMLInputElement>) => {
      const file = e.target.files?.[0];
      if (!file) {
        return;
      }

      const reader = new FileReader();
      reader.onload = (event) => {
        try {
          const json = JSON.parse(event.target?.result as string);
          if (!validateImportData(json)) {
            toast({
              id: 'SETTINGS_IMPORT_INVALID',
              title: t('modelManager.settingsImportInvalidFile'),
              status: 'error',
            });
            return;
          }
          applySettings(json);
        } catch {
          toast({
            id: 'SETTINGS_IMPORT_INVALID',
            title: t('modelManager.settingsImportInvalidFile'),
            status: 'error',
          });
        }
      };
      reader.onerror = () => {
        toast({
          id: 'SETTINGS_IMPORT_INVALID',
          title: t('modelManager.settingsImportInvalidFile'),
          status: 'error',
        });
      };
      reader.readAsText(file);

      // Reset the input so the same file can be re-selected
      e.target.value = '';
    },
    [applySettings, t]
  );

  const handleClick = useCallback(() => {
    fileInputRef.current?.click();
  }, []);

  return (
    <>
      <IconButton
        size="sm"
        icon={<PiUploadSimpleBold />}
        aria-label={t('modelManager.importSettings')}
        tooltip={t('modelManager.importSettings')}
        onClick={handleClick}
      />
      <input ref={fileInputRef} type="file" accept=".json" onChange={handleFileChange} style={{ display: 'none' }} />
    </>
  );
});

ModelSettingsImportButton.displayName = 'ModelSettingsImportButton';