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.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
# SPDX-License-Identifier: AGPL-3.0-only
# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
from .factory_base import Factory, seeder
# ASCII: must survive JSON escaping, a PNG text chunk and a JPEG comment.
SENTINEL = "media-sentinel-prompt"
VIDEO_ID = "media-video-clip"
SANDBOX_SESSION = "media-sandbox-session"
SANDBOX_FILE = "notes.txt"
SEARCH_IMAGE_ID = "a1b2c3d4e5f6"
MODEL_ID = "media-local-model-Q4_K_M"
IMAGE_LINK_QUERY: dict[str, str] = {}
VIDEO_LINK_QUERY: dict[str, str] = {}
AUDIO_LINK_QUERY: dict[str, str] = {}
def _image_meta() -> dict:
return {
"prompt": SENTINEL,
"negative_prompt": None,
"width": 8,
"height": 8,
"steps": 1,
"guidance": 1.0,
"seed": 7,
"model": "media/none",
"created_at": 1767225600.0,
}
@seeder("media-image")
def seed_image(account) -> dict[str, str]:
from PIL import Image
from core.inference import image_gallery
from routes.inference import _sign_image_id
from utils.account_context import run_as
image = Image.new("RGB", (8, 8), (10, 20, 30))
record = run_as(account, image_gallery.save, image, _image_meta())
IMAGE_LINK_QUERY["token"] = run_as(account, _sign_image_id, record["id"])
return {"image_id": record["id"]}
# Seeded in both accounts so only the item lookup can refuse, not a missing project.
MEDIA_PROJECT_ID = "media-project"
def _calling_account(actor: str):
"""The account the matrix sends this actor's request as, when it has one of its own."""
from auth import storage
from utils.account_context import OWNER
return {"owner": OWNER, "wrong": storage.get_account("bob")}.get(actor)
def _seed_media_project(account) -> None:
from storage import studio_db
from utils.account_context import run_as
run_as(
account,
studio_db.upsert_chat_project,
{"id": MEDIA_PROJECT_ID, "name": SENTINEL, "createdAt": 1000, "updatedAt": 1000},
)
@seeder("media-image-project")
def seed_image_and_project(account, actor: str = "right") -> dict[str, str]:
params = seed_image(account)
_seed_media_project(account)
caller = _calling_account(actor)
if caller is not None:
_seed_media_project(caller)
return params
def _wav_bytes() -> bytes:
import io
import wave
buf = io.BytesIO()
with wave.open(buf, "wb") as handle:
handle.setnchannels(1)
handle.setsampwidth(2)
handle.setframerate(8000)
handle.writeframes(b"\x00\x00" * 64)
return buf.getvalue()
@seeder("media-audio")
def seed_audio(account) -> dict[str, str]:
from core.inference import audio_gallery
from routes.inference import _sign_audio_id
from utils.account_context import run_as
meta = {
"prompt": SENTINEL,
"model": "media/none",
"audio_type": "speech",
"sample_rate": 8000,
"duration_s": 0.008,
"created_at": "2026-01-01T00:00:00+00:00",
}
record = run_as(account, audio_gallery.save, _wav_bytes(), meta)
AUDIO_LINK_QUERY["token"] = run_as(account, _sign_audio_id, record["id"])
return {"audio_id": record["id"]}
@seeder("media-audio-group")
def seed_audio_group(account) -> dict[str, str]:
from core.inference import audio_gallery
from utils.account_context import run_as
meta = {
"prompt": SENTINEL,
"model": "media/none",
"audio_type": "audiocpp_sep",
"workflow": "separate",
"role": "vocals",
"group_id": "matrixgroup",
"sample_rate": 8000,
"duration_s": 0.008,
"created_at": "2026-01-01T00:00:00+00:00",
}
run_as(account, audio_gallery.save, _wav_bytes(), meta)
return {"group_id": "matrixgroup"}
@seeder("media-audio-converted")
def seed_converted_audio(account) -> dict[str, str]:
import tempfile
from pathlib import Path
from core.inference import audio_gallery
from utils.account_context import run_as
meta = {
"prompt": SENTINEL,
"model": "media/none",
"audio_type": "speech",
"workflow": "convert",
"sample_rate": 8000,
"duration_s": 0.008,
"created_at": "2026-01-01T00:00:00+00:00",
}
with tempfile.TemporaryDirectory() as scratch:
source = Path(scratch) / "source.wav"
source.write_bytes(_wav_bytes())
record = run_as(account, audio_gallery.save, _wav_bytes(), meta, source)
return {"audio_id": record["id"]}
@seeder("media-audio-project")
def seed_audio_and_project(account, actor: str = "right") -> dict[str, str]:
params = seed_audio(account)
_seed_media_project(account)
caller = _calling_account(actor)
if caller is not None:
_seed_media_project(caller)
return params
@seeder("media-audio-input")
def seed_audio_input(account) -> dict[str, str]:
import hashlib
from core.inference import audio_inputs
from utils.account_context import run_as
data = _wav_bytes()
def save() -> dict:
directory = audio_inputs.inputs_dir()
upload = directory / ".matrix.upload.tmp"
upload.write_bytes(data)
try:
record, _ = audio_inputs._finish_upload(
directory, upload, hashlib.sha256(data).hexdigest(), SENTINEL, len(data)
)
finally:
upload.unlink(missing_ok = True)
return record
return {"input_id": run_as(account, save)["id"]}
@seeder("media-audio-voice")
def seed_audio_voice(account) -> dict[str, str]:
import tempfile
from pathlib import Path
from core.inference import audio_voices
from utils.account_context import run_as
with tempfile.TemporaryDirectory() as scratch:
source = Path(scratch) / "voice.wav"
source.write_bytes(_wav_bytes())
record = run_as(account, audio_voices.create, source, {"name": SENTINEL})
return {"voice_id": record["id"]}
@seeder("media-transcript")
def seed_transcript(account) -> dict[str, str]:
from core.inference import transcript_gallery
from utils.account_context import run_as
record = run_as(
account,
transcript_gallery.save,
{"text": SENTINEL, "model": "media/none"},
"Recording",
)
return {"transcript_id": record["id"]}
def _mp4_bytes() -> bytes:
import io
import av
buf = io.BytesIO()
with av.open(buf, "w", format = "mp4") as container:
stream = container.add_stream("libx264", rate = 8)
stream.width, stream.height, stream.pix_fmt = 64, 64, "yuv420p"
stream.options = {"crf": "40", "preset": "ultrafast"}
for index in range(4):
frame = av.VideoFrame(64, 64, "yuv420p")
for plane in frame.planes:
plane.update(bytes([16 + index * 40]) * plane.buffer_size)
for packet in stream.encode(frame):
container.mux(packet)
for packet in stream.encode():
container.mux(packet)
return buf.getvalue()
@seeder("media-video")
def seed_video(account) -> dict[str, str]:
from core.inference import video_gallery
from routes.video import _sign_video_id
from utils.account_context import run_as
meta = {
"prompt": SENTINEL,
"negative_prompt": None,
"width": 64,
"height": 64,
"num_frames": 4,
"fps": 8,
"duration_s": 0.5,
"steps": 1,
"guidance": 1.0,
"seed": 7,
"model": "media/none",
"created_at": "2026-01-01T00:00:00+00:00",
}
run_as(account, video_gallery.save, _mp4_bytes(), meta, VIDEO_ID)
VIDEO_LINK_QUERY["token"] = run_as(account, _sign_video_id, VIDEO_ID)
return {"video_id": VIDEO_ID}
@seeder("media-video-project")
def seed_video_and_project(account, actor: str = "right") -> dict[str, str]:
params = seed_video(account)
_seed_media_project(account)
caller = _calling_account(actor)
if caller is not None:
_seed_media_project(caller)
return params
@seeder("media-search-image")
def seed_search_image(account) -> dict[str, str]:
import io
from PIL import Image
from core.inference import search_images
from utils.account_context import run_as
buf = io.BytesIO()
Image.new("RGB", (8, 8), (200, 100, 50)).save(
buf, format = "JPEG", comment = SENTINEL.encode("ascii")
)
directory = run_as(account, search_images._cache_dir)
(directory / f"{SEARCH_IMAGE_ID}.jpg").write_bytes(buf.getvalue())
return {"image_id": SEARCH_IMAGE_ID}
@seeder("media-sandbox")
def seed_sandbox(account) -> dict[str, str]:
import os
from core.inference.tools import get_sandbox_workdir
from utils.account_context import run_as
workdir = run_as(account, get_sandbox_workdir, SANDBOX_SESSION)
with open(os.path.join(workdir, SANDBOX_FILE), "w", encoding = "utf-8") as handle:
handle.write(SENTINEL)
return {"session_id": SANDBOX_SESSION, "filename": SANDBOX_FILE}
@seeder("media-monitor")
def seed_monitor(account) -> dict[str, str]:
from core.inference.api_monitor import api_monitor
from utils.account_context import run_as
entry_id = run_as(
account,
api_monitor.start,
endpoint = "/v1/chat/completions",
method = "POST",
model = "media/none",
prompt = SENTINEL,
subject = account.username,
)
return {"entry_id": entry_id}
@seeder("media-model")
def seed_model(account) -> dict[str, str]:
import struct
from core.inference import local_model_resolver
from routes import inference
from storage import studio_db
from utils.account_context import run_as
from utils.paths import workspace_root
folder = run_as(account, workspace_root) / "local-models"
folder.mkdir(parents = True, exist_ok = True)
header = b"GGUF" + struct.pack("<I", 3) + struct.pack("<QQ", 0, 0)
(folder / f"{MODEL_ID}.gguf").write_bytes(header + b"\x00" * 256)
run_as(account, studio_db.add_scan_folder_with_status, str(folder))
# Drop the catalog's 30s memo so the request rescans.
inference._CATALOG_CACHE.update(at = 0.0, models = [])
inference._managed_catalogs.clear()
inference._SERVABLE_SCAN_CACHE["entry"] = None
local_model_resolver.invalidate_index()
return {"model_id": MODEL_ID}
@seeder("media-queue-job")
def seed_queue_job(account) -> dict[str, str]:
"""A waiting image job, placed straight in the queue so no worker renders it."""
import uuid
from core.inference.image_queue import ImageJob
from models.inference import DiffusionGenerateRequest
from routes import inference
job = ImageJob(
id = uuid.uuid4().hex[:12],
account_id = account.account_id,
account = account,
request = DiffusionGenerateRequest(prompt = SENTINEL),
)
inference._get_image_queue()._jobs.append(job)
return {"job_id": job.id}
_LINK_IS_THE_CREDENTIAL = (
"the signed link is the credential rather than the bearer, so every holder of it is served "
"while the minting account is active"
)
FACTORIES = {
"routes.inference:GET:/images/gallery/{image_id}/file": Factory(
"media-image", fragment = SENTINEL
),
"routes.inference:GET:/images/gallery/{image_id}/file-signed": Factory(
"media-image",
fragment = SENTINEL,
query = IMAGE_LINK_QUERY,
owner = (200,),
wrong = (200,),
unauthenticated = (200,),
reason = _LINK_IS_THE_CREDENTIAL,
),
"routes.inference:GET:/images/gallery/{image_id}/signed-url": Factory(
"media-image", fragment = "file-signed"
),
"routes.inference:PATCH:/images/gallery/{image_id}": Factory(
"media-image", {"archived": True}, fragment = SENTINEL
),
"routes.inference:DELETE:/images/gallery/{image_id}": Factory("media-image"),
"routes.inference:POST:/images/queue/{job_id}/cancel": Factory(
"media-queue-job", fragment = "cancelled"
),
"routes.inference:POST:/images/queue/{job_id}/move": Factory(
"media-queue-job", body = {"index": 0}, fragment = SENTINEL
),
"routes.inference:POST:/images/gallery/{image_id}/move": Factory(
"media-image", {"after_id": None}, fragment = SENTINEL
),
"routes.inference:POST:/images/gallery/{image_id}/project": Factory(
"media-image-project", {"project_id": MEDIA_PROJECT_ID}, fragment = "sandbox"
),
"routes.inference:GET:/audio/gallery/{audio_id}/file": Factory("media-audio"),
"routes.inference:GET:/audio/gallery/{audio_id}/signed-url": Factory(
"media-audio", fragment = "file-signed"
),
"routes.inference:GET:/audio/gallery/{audio_id}/file-signed": Factory(
"media-audio",
query = AUDIO_LINK_QUERY,
owner = (200,),
wrong = (200,),
unauthenticated = (200,),
reason = _LINK_IS_THE_CREDENTIAL,
),
"routes.inference:GET:/audio/gallery/{audio_id}/source/file": Factory("media-audio-converted"),
"routes.inference:PATCH:/audio/gallery/{audio_id}": Factory(
"media-audio", {"archived": True}, fragment = SENTINEL
),
"routes.inference:DELETE:/audio/gallery/{audio_id}": Factory("media-audio"),
"routes.inference:DELETE:/audio/gallery/group/{group_id}": Factory("media-audio-group"),
"routes.inference:POST:/audio/gallery/{audio_id}/move": Factory(
"media-audio", {"after_id": None}, fragment = SENTINEL
),
"routes.inference:POST:/audio/gallery/{audio_id}/project": Factory(
"media-audio-project", {"project_id": MEDIA_PROJECT_ID}, fragment = "sandbox"
),
"routes.inference:GET:/audio/inputs/{input_id}/file": Factory("media-audio-input"),
"routes.inference:DELETE:/audio/inputs/{input_id}": Factory("media-audio-input"),
"routes.inference:POST:/audio/inputs/{input_id}/transcribe": Factory(
"media-audio-input",
{"model": "media/none"},
right = (404,),
fragment = "Model not found",
self_expected = (409,),
reason = "no speech-to-text model is available, so transcription itself refuses",
),
"routes.inference:PATCH:/audio/voices/{voice_id}": Factory(
"media-audio-voice", {"name": "renamed"}, fragment = "renamed"
),
"routes.inference:DELETE:/audio/voices/{voice_id}": Factory("media-audio-voice"),
"routes.inference:GET:/audio/voices/{voice_id}/file": Factory("media-audio-voice"),
"routes.inference:GET:/audio/transcripts/{transcript_id}": Factory(
"media-transcript", fragment = SENTINEL
),
"routes.inference:PATCH:/audio/transcripts/{transcript_id}": Factory(
"media-transcript", {"archived": True}, fragment = SENTINEL
),
"routes.inference:DELETE:/audio/transcripts/{transcript_id}": Factory("media-transcript"),
"routes.video:GET:/video/gallery/{video_id}/file": Factory("media-video"),
"routes.video:GET:/video/gallery/{video_id}/file-signed": Factory(
"media-video",
query = VIDEO_LINK_QUERY,
owner = (200,),
wrong = (200,),
unauthenticated = (200,),
reason = _LINK_IS_THE_CREDENTIAL,
),
"routes.video:GET:/video/gallery/{video_id}/signed-url": Factory(
"media-video", fragment = "file-signed"
),
"routes.video:GET:/video/gallery/{video_id}/export": Factory("media-video"),
"routes.video:GET:/video/gallery/{video_id}/frame": Factory("media-video"),
"routes.video:POST:/video/gallery/{video_id}/audio-input": Factory(
"media-video",
{},
right = (400,),
self_expected = (400,),
fragment = "no audio track",
reason = "the seeded clip is silent, so past the ownership check the extract refuses",
),
"routes.video:PATCH:/video/gallery/{video_id}": Factory(
"media-video", {"archived": True}, fragment = SENTINEL
),
"routes.video:DELETE:/video/gallery/{video_id}": Factory("media-video"),
"routes.video:POST:/video/gallery/{video_id}/move": Factory(
"media-video", {"after_id": None}, fragment = SENTINEL
),
"routes.video:POST:/video/gallery/{video_id}/project": Factory(
"media-video-project", {"project_id": MEDIA_PROJECT_ID}, fragment = "sandbox"
),
"routes.video:GET:/videos/{video_id}": Factory("media-video", fragment = SENTINEL),
"routes.video:GET:/videos/{video_id}/content": Factory("media-video"),
"routes.video:DELETE:/videos/{video_id}": Factory("media-video", fragment = VIDEO_ID),
"routes.inference:GET:/search-images/{image_id}": Factory(
"media-search-image", fragment = SENTINEL
),
"routes.inference:GET:/monitor/{entry_id}": Factory("media-monitor", fragment = SENTINEL),
"routes.inference:GET:/models/{model_id:path}": Factory("media-model", fragment = MODEL_ID),
"routes.inference:GET:/sandbox/{session_id}": Factory(
"media-sandbox",
fragment = SANDBOX_FILE,
absent = SANDBOX_FILE,
owner = (200,),
wrong = (200,),
reason = "a session id resolves inside the caller's own sandbox root, so another account "
"is listed its own empty directory rather than refused",
),
"routes.inference:GET:/sandbox/{session_id}/{filename:path}": Factory(
"media-sandbox", fragment = SENTINEL
),
"routes.inference:HEAD:/sandbox/{session_id}/{filename:path}": Factory("media-sandbox"),
}
_NPU_INSTALLATION_MODEL = (
"an NPU model id names FastFlowLM's one per-installation model store, not an account's "
"object, and the route is owner-only (policy.require_owner), so no account owns it"
)
SKIPPED = {
"routes.inference:POST:/sandbox/{session_id}/reveal": (
"opens the backend host's file manager, so a success spawns xdg-open on a machine with "
"no desktop session and the only in-process outcome is the 500 that failure maps to"
),
"routes.inference:POST:/sandbox/{session_id}/upload": (
"needs a multipart body the JSON matrix client cannot send, so every actor stops at the "
"same 422; the folder resolves inside the caller's own sandbox root (test_sandbox_upload)"
),
"routes.inference:POST:/sandbox/{session_id}/open": (
"launches the backend host's default app for the file and is owner-only "
"(require_installation_owner), so no account other than the installation's own reaches it"
),
"routes.npu:DELETE:/models/{model_id}": _NPU_INSTALLATION_MODEL,
"routes.npu:POST:/models/{model_id}/download": _NPU_INSTALLATION_MODEL,
"routes.npu:GET:/models/{model_id}/download": _NPU_INSTALLATION_MODEL,
"routes.video_restyle:GET:/video/restyle/{job_id}/{kind}.mp4": (
"serves the in-memory restyle runner's current job, not a stored object, so there is "
"nothing to seed; media_path answers only the job's own account "
"(test_runner_hides_another_accounts_job)"
),
}