Calliope 1.0

This commit is contained in:
Benjiyaya
2026-07-28 05:29:46 +08:00
commit 83784ff4dc
5 changed files with 4095 additions and 0 deletions
+133
View File
@@ -0,0 +1,133 @@
# Calliope
Calliope is a local-first story-to-video studio. You type a story idea; Calliope drafts a storyline with beats, characters, and locations, writes a per-scene script, then generates a video clip per scene by driving your own ComfyUI install. When the clips are done, one click stitches them into a finished film with crossfades and matched loudness (ffmpeg). Everything runs on your machine: projects live in SQLite, media lives in folders, and no cloud service is involved beyond the LLM endpoint you point it at.
## Download & run (Windows)
1. Grab **`Calliope-win-x64.zip`** from the [latest release](../../releases).
2. Unzip it anywhere writable (avoid `Program Files`).
3. Run `win-unpacked\Calliope.exe`.
No installer, no dev setup. First launch shows a splash while the backend boots. Windows SmartScreen will warn on first run (unsigned binary) — that's expected.
**Portable:** your projects, database, generated media, and settings live next to the app:
```text
<app>\resources\backend\data\ projects database + generated assets
<app>\resources\backend\calliope_config.json created when you save Settings
```
Move or copy the whole unzipped folder to relocate the app together with its data.
<img width="1702" height="1041" alt="Screenshot 2026-07-28 045615" src="https://github.com/user-attachments/assets/e5450a46-d8f9-48fe-8163-5efffaeccb0e" />
<img width="1702" height="1049" alt="Screenshot 2026-07-28 052215" src="https://github.com/user-attachments/assets/703c3def-c992-41f7-8fef-bb2c7ef51535" />
<img width="1697" height="1047" alt="Screenshot 2026-07-28 052242" src="https://github.com/user-attachments/assets/84618fe3-1f33-4482-bbe1-b8d13866bd96" />
<img width="1686" height="967" alt="Screenshot 2026-07-28 052349" src="https://github.com/user-attachments/assets/193af234-3862-467b-9087-373ffcd26d4a" />
## Requirements
- **Windows 10/11**
- **A running ComfyUI install**, with the models your workflows need already set up
- **An OpenAI-compatible LLM endpoint** — local (LM Studio, Ollama, etc.) or hosted
- **ffmpeg on PATH** — needed for film export
## First run
Open the app, go to **Settings**, and set:
1. **LLM** — base URL, model name, and API key of your OpenAI-compatible endpoint
2. **ComfyUI** — the base URL of your running ComfyUI (e.g. `http://127.0.0.1:8188`)
Leave **Dry-run** off — it is meant for testing and produces placeholder results instead of real generations.
## Using the app
The app walks a project through four stages — **Story, Assets, Script, Video**:
- **Story:** describe your idea and generate a draft storyline with beats, characters, and locations. Generating again replaces the current draft — the UI asks for confirmation first. Edit anything by hand before moving on.
- **Assets:** each character and location has its own **Image prompt**. Pick a workflow and shared settings (width/height/etc.) at the top, then click Generate per entity to produce reference images on your ComfyUI. Regenerate any single entity without touching the others.
- **Script:** generate (or regenerate) the per-scene script. Scenes link back to the characters and locations from the Story stage.
- **Video:** each scene gets a **Generate** button that queues a clip job on ComfyUI with the right prompt and reference images. Clips save to local disk and appear in the scene timeline.
- **Film view:** once scenes have clips, **Export film** stitches them with ffmpeg: every clip is normalized to 1080p30, joined with 0.5s crossfades, and loudness-normalized into one final file.
- When everything is done the project is automatically marked **Completed**.
**Playground** is a free-form generation page outside the project pipeline: run any imported workflow with arbitrary inputs, upload your own files (image / video / audio) as inputs, and optionally attach a result to a project as an asset.
## ComfyUI workflows (important)
Calliope does **not** hardcode Comfy node IDs. It discovers editable nodes from **role tags** in the node titles of an **API Format** workflow JSON. The `ComfyAPI/` folder in this repo contains ready-to-import example workflows (LTX-2.3 ref2vid, krea2 t2i).
### 1. Tag your nodes in ComfyUI
Rename the input/output nodes so their titles carry a role tag:
```text
Display Name (Input:role)
Display Name (Output:role)
```
The display name can be anything, in any language. The `:role` part is the contract. Examples:
```text
Main Prompt (Input:prompt)
Neg (Input:negative)
W (Input:width)
H (Input:height)
Char Ref (Input:character)
Env Ref (Input:location)
Result (Output:image)
Clip (Output:video)
```
### 2. Canonical roles
Input roles:
| Role | Aliases | Filled by |
|---|---|---|
| `prompt` | `positive` | Entity Image prompt (Assets), scene/job prompt |
| `negative` | `neg` | Negative prompt when provided |
| `width` | `w` | Shared form / defaults |
| `height` | `h` | Shared form / defaults |
| `character` | `char`, `portrait`, `sheet`, `face`, `ref` | Character reference path |
| `location` | `loc`, `environment`, `env`, `background`, `scene` | Location reference path |
| `image` | `img` | Generic image input |
| `seed` | — | Shared form |
Output roles:
| Role | Aliases |
|---|---|
| `image` | `img` |
| `video` | `vid` |
Unknown roles still show up in the dynamic form; they just get no special auto-fill. Plain `(Input)` / `(Output)` without a role still works through a deprecated label fallback, so old workflows keep working — but tag new workflows with explicit roles.
### 3. Export the workflow
In ComfyUI, use **Save (API Format)** — not the regular UI workflow graph format. Calliope only understands API Format JSON.
### 4. Import into Calliope
Settings → Workflows → import the JSON → **analyze** → check the preview shows the expected **role** next to each input → save → enable the workflow where you want to use it (Assets, Playground, per scene).
### 5. Troubleshooting
If ComfyUI "doesn't know what to generate" or jobs come back empty:
- The workflow title must be literally `(Input:prompt)` — not only `(Input)` — for prompts to land reliably.
- Check the job payload: `input_values` for that node must be non-empty (blanks are stripped before submission).
- Make sure **Dry-run** is off in Settings (default is off).
- An unreachable ComfyUI fails the job honestly — Calliope never silently fakes images. Check the base URL and that ComfyUI is running.
### 6. HTTP only
Calliope talks to ComfyUI purely over its HTTP API: it uploads reference files with `POST /upload/image`, patches the workflow JSON and queues it via `POST /prompt`, polls `/history/{prompt_id}`, and downloads the results. It **never reads or writes ComfyUI's local `input/` / `output/` folders** — any folder paths stay configured on the ComfyUI side, not in Calliope.
## Source code
The app source (FastAPI backend, SvelteKit frontend) is not published yet — this repo currently ships the packaged app (via Releases), the Electron shell (`electron/`), and example ComfyUI workflows (`ComfyAPI/`).
+103
View File
@@ -0,0 +1,103 @@
# Calliope — Electron shell
Portable Windows packaging for the Calliope story-to-video studio.
Double-click `Calliope.exe` → the FastAPI backend starts → the window opens the UI.
No installer, no code signing, no vite — the backend serves the built SPA at its
own origin, so there is zero CORS/API-base configuration.
## Prerequisites
- `calliope-backend/.venv` set up (`pip install -e ".[dev]"` + `pyinstaller`)
- `calliope-web/node_modules` installed
- `electron/node_modules` installed (`npm install` in this folder — once)
## Build (one command)
```bash
cd electron
npm run build:all
```
This chains:
1. `build:web` — `npm run build` in `calliope-web/` (fresh SPA in `calliope-web/build/`)
2. `build:backend` — PyInstaller (`calliope-backend/calliope.spec`) →
`calliope-backend/dist/calliope-backend/` (onedir, SPA bundled as `calliope/static`)
3. `dist` — electron-builder `dir` target → `electron/dist/win-unpacked/`
Then zip for distribution:
```bash
npm run zip # → electron/dist/Calliope-win-x64.zip
```
## Run
- Packaged: `electron/dist/win-unpacked/Calliope.exe` (or unzip the zip anywhere
writable and run `win-unpacked/Calliope.exe`). First launch shows a splash while
the backend boots; a failure page appears if it cannot start.
- Dev (shell against the source backend in `calliope-backend/.venv`):
`npm start` in this folder.
Ports: tries 8247, then 8248→8250. If a healthy Calliope backend already answers
on a candidate port (e.g. a dev instance), it is reused instead of spawning a
second one. Set `CALLIOPE_PORT=<n>` to pin the preferred port.
> Note: the backend reads host/port from env (`CALLIOPE_HOST`/`CALLIOPE_PORT`),
> not argv — there is no CLI parser in `calliope.main`. The shell sets both.
> Also: if `ELECTRON_RUN_AS_NODE=1` is set in your environment, Electron will not
> start as an app — unset it before launching.
## Where user data lives
Everything is **portable**, next to the backend exe — never `%TEMP%`, never the
source tree:
```
<app>/resources/backend/calliope-backend.exe
<app>/resources/backend/data/ created on first run (fresh, empty)
<app>/resources/backend/data/calliope.db SQLite database
<app>/resources/backend/data/assets/ generated assets / uploads
<app>/resources/backend/calliope_config.json created only when you save Settings
```
This works because `calliope-backend/src/calliope/config.py` anchors
`BACKEND_ROOT` to `sys.executable`'s folder when running frozen
(`getattr(sys, "frozen", False)`); non-frozen dev behavior is unchanged.
The package ships with **no** `data/` and **no** `calliope_config.json` —
fresh users get a fresh database and sane in-memory defaults.
Move/copy the whole unzipped folder to relocate the app + its data together.
Avoid `Program Files` (not writable without elevation).
## Updating backend / frontend
- UI changed → `npm run build:web` then rebuild (`build:backend` + `dist`).
The spec packs `calliope-web/build/` directly; the copy in
`calliope-backend/src/calliope/static/` is only used by the dev server.
- Backend Python changed → `npm run build:backend && npm run dist`.
- To ship an update, re-zip. Users replace the app folder; their `data/` and
`calliope_config.json` survive if they keep those two paths (they sit outside
`_internal/`, directly in `resources/backend/`).
## Implementation notes
- `main.js`: single-instance lock; spawns `resources/backend/calliope-backend.exe`
(hidden, `windowsHide`) with `CALLIOPE_HOST`/`CALLIOPE_PORT`; polls
`/api/health` up to 30 s; loads `http://127.0.0.1:<port>/`; kills the backend on
`before-quit` / `window-all-closed` / `exit` / `SIGINT` / `SIGTERM`.
- Backend exe console stays ON (`console=True` in `calliope.spec`) so users can
run it from a terminal for diagnostics; the shell always hides it.
- asar stays enabled: only the JS shell is packed (`resources/app.asar`); the
backend lives in `extraResources` → `resources/backend/` and writes beside
itself, so asar is irrelevant to storage.
## Known rough edges
- Default Electron icon (no custom `.ico` yet).
- Full-page reload (F5) on a deep route (`/project/123`) returns JSON 404 —
Starlette `StaticFiles(html=True)` has no SPA fallback. In-app navigation is
client-side and unaffected; the window always starts at `/`, which works.
- Force-killing `Calliope.exe` (Task Manager → End task with /F) can orphan
`calliope-backend.exe`; the next launch simply reuses it if it is healthy.
- Windows SmartScreen will warn on first run (unsigned binary).
+216
View File
@@ -0,0 +1,216 @@
// Calliope Electron shell.
//
// Starts the FastAPI backend (PyInstaller exe in packaged mode, venv python in
// dev), waits for /api/health, then loads the SPA the backend serves at its own
// origin — so no CORS or API-base handling is needed here.
const { app, BrowserWindow, Menu } = require('electron');
const { spawn } = require('node:child_process');
const http = require('node:http');
const net = require('node:net');
const path = require('node:path');
const HOST = '127.0.0.1';
// CALLIOPE_PORT env pins the preferred port (handy for testing alongside a dev
// backend on 8247); otherwise the chain below is tried in order.
const PREFERRED_PORT = Number(process.env.CALLIOPE_PORT) || 8247;
const PORT_CANDIDATES = [...new Set([PREFERRED_PORT, 8247, 8248, 8249, 8250])];
const HEALTH_TIMEOUT_MS = 30_000;
let backendChild = null;
let mainWindow = null;
// ---------- small helpers ----------
function healthOk(port) {
return new Promise((resolve) => {
const req = http.get({ host: HOST, port, path: '/api/health', timeout: 1500 }, (res) => {
res.resume();
resolve(res.statusCode === 200);
});
req.on('timeout', () => {
req.destroy();
resolve(false);
});
req.on('error', () => resolve(false));
});
}
function portBusy(port) {
return new Promise((resolve) => {
const srv = net.createServer();
srv.once('error', () => resolve(true));
srv.once('listening', () => srv.close(() => resolve(false)));
srv.listen(port, HOST);
});
}
function sleep(ms) {
return new Promise((r) => setTimeout(r, ms));
}
// ---------- backend process ----------
function backendLaunch() {
if (app.isPackaged) {
// extraResources copied the onedir PyInstaller output to resources/backend/.
// Frozen config.py anchors data/ and calliope_config.json next to this exe.
const exe = path.join(process.resourcesPath, 'backend', 'calliope-backend.exe');
return { cmd: exe, args: [], cwd: path.dirname(exe) };
}
// Dev: run the source backend from its venv; storage stays in calliope-backend/data.
const backendRoot = path.resolve(__dirname, '..', 'calliope-backend');
const py = path.join(backendRoot, '.venv', 'Scripts', 'python.exe');
return { cmd: py, args: ['-m', 'calliope.main'], cwd: backendRoot };
}
function killBackend() {
if (backendChild && backendChild.exitCode === null && !backendChild.killed) {
try {
backendChild.kill(); // TerminateProcess on Windows
} catch {
/* already gone */
}
}
backendChild = null;
}
async function waitForHealth(port, child, spawnErrorRef) {
const deadline = Date.now() + HEALTH_TIMEOUT_MS;
while (Date.now() < deadline) {
if (spawnErrorRef.err) throw spawnErrorRef.err;
if (child && child.exitCode !== null) {
throw new Error(`backend exited early (code ${child.exitCode})`);
}
if (await healthOk(port)) return;
await sleep(500);
}
throw new Error(`no /api/health response within ${HEALTH_TIMEOUT_MS / 1000}s`);
}
async function startBackend() {
let lastErr = null;
for (const port of PORT_CANDIDATES) {
// Stale/previous instance already serving? Reuse it — no second backend.
if (await healthOk(port)) {
console.log(`[calliope] backend already healthy on :${port} — reusing it`);
return port;
}
if (await portBusy(port)) {
console.log(`[calliope] :${port} is busy (not a Calliope backend) — trying next port`);
continue;
}
const { cmd, args, cwd } = backendLaunch();
// NOTE: the backend reads host/port from settings/env, NOT argv (there is no
// CLI parser). --host/--port are passed for future CLI support; the env vars
// below are what actually bind the port.
const fullArgs = [...args, '--host', HOST, '--port', String(port)];
console.log(`[calliope] spawning ${cmd} ${fullArgs.join(' ')} (cwd=${cwd})`);
const spawnErrorRef = { err: null };
backendChild = spawn(cmd, fullArgs, {
cwd,
env: { ...process.env, CALLIOPE_HOST: HOST, CALLIOPE_PORT: String(port) },
windowsHide: true, // never flash a console window for the backend
stdio: ['ignore', 'pipe', 'pipe'],
});
backendChild.on('error', (err) => {
spawnErrorRef.err = err;
});
// Mirror backend logs into our stdout (visible when launched from a terminal).
backendChild.stdout?.on('data', (d) => process.stdout.write(`[backend] ${d}`));
backendChild.stderr?.on('data', (d) => process.stderr.write(`[backend] ${d}`));
try {
await waitForHealth(port, backendChild, spawnErrorRef);
console.log(`[calliope] backend healthy on :${port}`);
return port;
} catch (err) {
console.error(`[calliope] backend on :${port} failed: ${err.message}`);
lastErr = err;
killBackend();
}
}
throw lastErr || new Error(`no free port among ${PORT_CANDIDATES.join(', ')}`);
}
// ---------- window ----------
function inlinePage(title, message) {
const html = `<!doctype html>
<html><head><meta charset="utf-8"><title>${title}</title>
<style>
body{margin:0;height:100vh;display:flex;flex-direction:column;align-items:center;justify-content:center;
background:#0a0a0c;color:#e7e7ea;font:14px/1.6 system-ui,sans-serif;text-align:center}
h1{font-size:20px;font-weight:600;margin:0 0 12px}
p{color:#9a9aa3;max-width:520px;margin:4px 16px}
.spin{width:28px;height:28px;margin-bottom:20px;border:3px solid #2a2a30;border-top-color:#7c7cf0;
border-radius:50%;animation:r .8s linear infinite}
@keyframes r{to{transform:rotate(360deg)}}
code{background:#17171c;padding:2px 6px;border-radius:4px}
</style></head>
<body><div class="spin" style="display:${title === 'Calliope' ? 'block' : 'none'}"></div>
<h1>${title}</h1><p>${message}</p></body></html>`;
return 'data:text/html;charset=utf-8,' + encodeURIComponent(html);
}
function createWindow() {
Menu.setApplicationMenu(null);
mainWindow = new BrowserWindow({
width: 1440,
height: 900,
backgroundColor: '#0a0a0c',
autoHideMenuBar: true,
show: true,
webPreferences: { contextIsolation: true, nodeIntegration: false },
});
mainWindow.loadURL(inlinePage('Calliope', 'Starting the local studio…'));
}
async function boot() {
createWindow();
try {
const port = await startBackend();
await mainWindow.loadURL(`http://${HOST}:${port}/`);
} catch (err) {
console.error('[calliope] fatal:', err);
await mainWindow.loadURL(
inlinePage(
'Calliope failed to start',
`The backend could not be started (${String(err.message || err)}). ` +
`If a previous run hung, close it or run <code>end.bat</code>, then try again.`
)
);
}
}
// ---------- lifecycle ----------
const gotLock = app.requestSingleInstanceLock();
if (!gotLock) {
app.quit();
} else {
app.on('second-instance', () => {
if (mainWindow) {
if (mainWindow.isMinimized()) mainWindow.restore();
mainWindow.focus();
}
});
app.whenReady().then(boot);
app.on('before-quit', killBackend);
app.on('window-all-closed', () => {
killBackend();
app.quit();
});
// Cover terminal kill paths so no orphan calliope-backend.exe is left behind.
process.on('exit', killBackend);
for (const sig of ['SIGINT', 'SIGTERM']) {
process.on(sig, () => {
killBackend();
app.quit();
});
}
}
+3594
View File
File diff suppressed because it is too large Load Diff
+49
View File
@@ -0,0 +1,49 @@
{
"name": "calliope-shell",
"productName": "Calliope",
"version": "1.0.0",
"private": true,
"description": "Electron shell for the Calliope local story-to-video studio",
"main": "main.js",
"scripts": {
"start": "electron .",
"dist": "electron-builder --win dir",
"build:web": "cd ../calliope-web && npm run build",
"build:backend": "cd ../calliope-backend && .venv/Scripts/python.exe -m PyInstaller calliope.spec --noconfirm",
"build:all": "npm run build:web && npm run build:backend && npm run dist",
"zip": "powershell -NoProfile -Command \"Compress-Archive -Path 'dist/win-unpacked' -DestinationPath 'dist/Calliope-win-x64.zip' -Force\""
},
"build": {
"appId": "com.calliope.app",
"productName": "Calliope",
"asar": true,
"files": [
"main.js",
"package.json"
],
"extraResources": [
{
"from": "../calliope-backend/dist/calliope-backend",
"to": "backend",
"filter": [
"**/*",
"!data/**",
"!data",
"!calliope_config.json"
]
}
],
"win": {
"target": [
"dir"
]
},
"directories": {
"output": "dist"
}
},
"devDependencies": {
"electron": "^43.2.0",
"electron-builder": "^26.15.3"
}
}