Skip to content

Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.

5.7 KB
Raw Blame
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0

import { SectionBox } from "@/components/section-box";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { Spinner } from "@/components/ui/spinner";
import {
  type DiffusionLoraInfo,
  listDiffusionLoras,
} from "@/features/images/api";
import { matchCatalogId } from "@/features/images/train/diffusion-train-deploy";
import { ImageAdd02Icon } from "@hugeicons/core-free-icons";
import { useEffect, useState } from "react";
import { exportDiffusionLora } from "../api/export-api";
import { savedLabel } from "../constants";

function imageLoraLabel(lora: DiffusionLoraInfo, clashes: boolean): string {
  const tags = [...lora.families, ...(lora.fine_tuned ? ["fine-tuned"] : [])];
  const name = clashes
    ? `${lora.display_name} [${lora.id}]`
    : lora.display_name;
  return tags.length > 0 ? `${name} (${tags.join(", ")})` : name;
}

export function ImageLoraExportCard({ preselect }: { preselect?: string }) {
  const [loras, setLoras] = useState<DiffusionLoraInfo[] | null>(null);
  const [loraId, setLoraId] = useState("");
  const [saveDirectory, setSaveDirectory] = useState("image-loras");
  const [running, setRunning] = useState(false);
  const [result, setResult] = useState<{ ok: boolean; text: string } | null>(
    null,
  );

  useEffect(() => {
    let cancelled = false;
    listDiffusionLoras()
      // Only adapters on disk: curated hub entries are already downloadable from their repo.
      .then((list) => {
        if (!cancelled) {
          setLoras(list.filter((l) => l.source === "local"));
        }
      })
      .catch(() => {
        if (!cancelled) {
          setLoras([]);
        }
      });
    return () => {
      cancelled = true;
    };
  }, []);

  // From a finished image run: pick it and scroll here, since the text-model card above shows no runs.
  useEffect(() => {
    const id = preselect ? matchCatalogId(loras ?? [], preselect) : undefined;
    if (!id) {
      return;
    }
    setLoraId(id);
    document
      .getElementById("image-lora-id")
      ?.scrollIntoView({ behavior: "smooth", block: "center" });
  }, [preselect, loras]);

  const canExport = !running && loraId !== "" && saveDirectory.trim() !== "";

  async function handleExport() {
    setRunning(true);
    setResult(null);
    try {
      const response = await exportDiffusionLora({
        lora_id: loraId,
        save_directory: saveDirectory.trim(),
      });
      setResult({
        ok: true,
        text: `Saved to ${savedLabel(String(response.details?.output_path ?? saveDirectory))}. To use it on another install, copy that folder over and add it from Images > LoRAs > Folders.`,
      });
    } catch (error) {
      setResult({
        ok: false,
        text: error instanceof Error ? error.message : String(error),
      });
    } finally {
      setRunning(false);
    }
  }

  return (
    <SectionBox
      icon={ImageAdd02Icon}
      chipTint="var(--chart-1)"
      title="Export an image LoRA"
      description="Save a copy of an image generation LoRA you trained (or added) on the Images page: the .safetensors adapter plus its .json metadata. Any Unsloth install lists it again from a custom models folder."
    >
      <div className="flex flex-col gap-6">
        <div className="grid gap-4 @md/train-section:grid-cols-2">
          <div className="flex flex-col gap-2">
            <label
              htmlFor="image-lora-id"
              className="flex items-center gap-1.5 text-xs font-medium text-muted-foreground"
            >
              Image LoRA
            </label>
            <Select value={loraId} onValueChange={setLoraId}>
              <SelectTrigger id="image-lora-id" className="w-full">
                <SelectValue
                  placeholder={
                    loras === null
                      ? "Loading…"
                      : loras.length === 0
                        ? "No image LoRAs found"
                        : "Select an image LoRA…"
                  }
                />
              </SelectTrigger>
              <SelectContent>
                {(loras ?? []).map((l) => (
                  <SelectItem key={l.id} value={l.id}>
                    {imageLoraLabel(
                      l,
                      (loras ?? []).some(
                        (o) =>
                          o.id !== l.id && o.display_name === l.display_name,
                      ),
                    )}
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
          </div>
          <div className="flex flex-col gap-2">
            <label
              htmlFor="image-lora-save"
              className="flex items-center gap-1.5 text-xs font-medium text-muted-foreground"
            >
              Save directory
            </label>
            <Input
              id="image-lora-save"
              value={saveDirectory}
              onChange={(e) => setSaveDirectory(e.target.value)}
            />
          </div>
        </div>
        <div className="flex items-center justify-between gap-3">
          <p
            className={
              result?.ok === false
                ? "text-xs text-destructive"
                : "text-xs text-muted-foreground"
            }
          >
            {result?.text ?? "A plain file copy: no model load or GPU needed."}
          </p>
          <Button variant="dark" disabled={!canExport} onClick={handleExport}>
            {running && <Spinner />}
            Export
          </Button>
        </div>
      </div>
    </SectionBox>
  );
}