caelum0x d56639a594
Some checks are pending
build-images / api (push) Waiting to run
build-images / worker-gpu (push) Waiting to run
build-images / web (push) Waiting to run
codeql / Analyze (javascript-typescript) (push) Waiting to run
codeql / Analyze (python) (push) Waiting to run
perf / API hot-path micro-smoke (budgeted) (push) Waiting to run
perf / Desktop engine crates (release build check) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (comfy-workflow-schema) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (effects-core) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (eventbus-types) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (growth-analytics) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (trends-schema) (push) Waiting to run
vision2026-ci / API phase modules (ruff + pytest) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (provider-adapter-kit) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (publishing-connectors) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (render-core) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (shot-template-schema) (push) Waiting to run
vision2026-ci / Python SDK resource tests (push) Waiting to run
vision2026-ci / Desktop engine crates (test + clippy + fmt) (push) Waiting to run
vision2026-ci / Alembic upgrade + drift check (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (caption-engine) (push) Waiting to run
Menivor — open source release (MIT), free to use and fork
Paid, hosted product at menivor.com, now retired as a company project.
Fresh squashed history of the cleaned working tree (secret-scanned,
no .env, no customer data, no outreach logs). Built on
MoneyPrinterTurbo (MIT, harry0703) — see NOTICE.
2026-12-04 02:10:26 +03:00

259 lines
8.7 KiB
Python

"""server.py — freegen local HTTP sidecar for the Menivor desktop app.
Runs on http://127.0.0.1:8765/api/v1 and speaks the same wire protocol as
api.menivor.com/api/v1, so the desktop app can point its API base at this
sidecar for fully local, $0 generation.
Free for users — local generation is never gated. Revenue comes from optional
extras: cloud rendering, auto-posting, and team plans.
Supported job kinds
-------------------
image_from_prompt — FLUX.1-schnell 4-bit still (stills.py)
assemble — clips/stills + Kokoro voice + captions → mp4 (assemble.py)
voiceover — Kokoro TTS → WAV
Start
-----
source .venv/bin/activate
python server.py # port 8765
# or from any directory:
/path/to/freegen/.venv/bin/python /path/to/freegen/server.py
The desktop app switches to local mode by setting its API base URL to
http://127.0.0.1:8765/api/v1
See videogen/docs/freegen-desktop.md for the full desktop integration guide.
"""
from __future__ import annotations
import asyncio
import os
import sys
import time
import uuid
from pathlib import Path
from typing import Any
# Add this directory to sys.path so stills / assemble are importable
sys.path.insert(0, str(Path(__file__).parent))
from fastapi import FastAPI, HTTPException, BackgroundTasks
from fastapi.responses import FileResponse
from pydantic import BaseModel
app = FastAPI(title="Freegen local sidecar", version="1.0.0")
# ── job store (in-memory, single process) ────────────────────────────────────
# Maps job_id -> dict with keys: kind, state, progress, result_url, error, params
# state: 0=pending, 1=complete, -1=failed
_jobs: dict[str, dict[str, Any]] = {}
_results_dir = Path(os.environ.get("FREEGEN_RESULTS", str(Path.home() / ".cache" / "freegen" / "results")))
_results_dir.mkdir(parents=True, exist_ok=True)
STATE_PENDING = 0
STATE_COMPLETE = 1
STATE_FAILED = -1
def _new_job(kind: str, params: dict) -> str:
job_id = str(uuid.uuid4())
_jobs[job_id] = {
"job_id": job_id,
"kind": kind,
"state": STATE_PENDING,
"progress": 0,
"result_url": "",
"preview_url": "",
"poster_url": "",
"error": "",
"retry_eligible": False,
"created_at": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
"params": params,
}
return job_id
def _job_response(job_id: str) -> dict:
j = _jobs[job_id].copy()
j.pop("params", None)
return j
# ── background task runners ──────────────────────────────────────────────────
def _run_image_from_prompt(job_id: str, params: dict) -> None:
_jobs[job_id]["progress"] = 5
try:
from stills import generate_still
out_path = _results_dir / f"{job_id}.png"
generate_still(
prompt=params["prompt"],
out=out_path,
seed=params.get("seed"),
lora=params.get("lora_path"),
steps=params.get("steps", 4),
saved_model=params.get("saved_model"),
)
_jobs[job_id]["progress"] = 100
_jobs[job_id]["state"] = STATE_COMPLETE
_jobs[job_id]["result_url"] = f"http://127.0.0.1:8765/results/{job_id}.png"
_jobs[job_id]["preview_url"] = _jobs[job_id]["result_url"]
except SystemExit as e:
_jobs[job_id]["state"] = STATE_FAILED
_jobs[job_id]["error"] = str(e)
except Exception as e:
_jobs[job_id]["state"] = STATE_FAILED
_jobs[job_id]["error"] = repr(e)
def _run_assemble(job_id: str, params: dict) -> None:
_jobs[job_id]["progress"] = 5
try:
from assemble import assemble
out_path = _results_dir / f"{job_id}.mp4"
assemble(
shots=params["shots"],
out=out_path,
voice_blend=params.get("voice_blend", "af_heart:1.0"),
speed=params.get("speed", 1.0),
music=params.get("music"),
product_name=params.get("product_name", "Menivor"),
product_url=params.get("product_url", "menivor.com"),
)
_jobs[job_id]["progress"] = 100
_jobs[job_id]["state"] = STATE_COMPLETE
_jobs[job_id]["result_url"] = f"http://127.0.0.1:8765/results/{job_id}.mp4"
_jobs[job_id]["preview_url"] = _jobs[job_id]["result_url"]
except SystemExit as e:
_jobs[job_id]["state"] = STATE_FAILED
_jobs[job_id]["error"] = str(e)
except Exception as e:
_jobs[job_id]["state"] = STATE_FAILED
_jobs[job_id]["error"] = repr(e)
def _run_voiceover(job_id: str, params: dict) -> None:
_jobs[job_id]["progress"] = 5
try:
from assemble import synthesise
out_path = _results_dir / f"{job_id}.wav"
synthesise(
text=params["text"],
blend=params.get("blend", "af_heart:1.0"),
speed=params.get("speed", 1.0),
out_wav=out_path,
)
_jobs[job_id]["progress"] = 100
_jobs[job_id]["state"] = STATE_COMPLETE
_jobs[job_id]["result_url"] = f"http://127.0.0.1:8765/results/{job_id}.wav"
except Exception as e:
_jobs[job_id]["state"] = STATE_FAILED
_jobs[job_id]["error"] = repr(e)
_RUNNERS = {
"image_from_prompt": _run_image_from_prompt,
"assemble": _run_assemble,
"voiceover": _run_voiceover,
}
# ── API endpoints (match api.menivor.com/api/v1 contract) ────────────────────
class Envelope(BaseModel):
data: Any
@app.get("/api/v1/me")
def me():
"""Connection check — desktop app uses this to verify the sidecar is running."""
return {"data": {
"id": "local",
"email": "local@freegen",
"workspace_id": "local",
"plan": "freegen",
}}
@app.get("/api/v1/pilot/capabilities")
def capabilities():
"""Tell the desktop app what this engine supports."""
return {"data": {
"mode": "local",
"generation": {"reels": True, "broll": True},
"product": {"runtime": {"storage_ready": True}},
"freegen": True,
}}
class JobCreateBody(BaseModel):
kind: str
params: dict = {}
@app.post("/api/v1/jobs")
def create_job(body: JobCreateBody, background_tasks: BackgroundTasks):
"""Create a generation job and start it in the background."""
kind = body.kind
runner = _RUNNERS.get(kind)
if runner is None:
raise HTTPException(status_code=400, detail=f"unsupported job kind: {kind!r}. "
f"Supported: {list(_RUNNERS)}")
job_id = _new_job(kind, body.params)
background_tasks.add_task(runner, job_id, body.params)
return {"data": _job_response(job_id)}
@app.get("/api/v1/jobs")
def list_jobs(limit: int = 20, offset: int = 0):
jobs = list(reversed(list(_jobs.values())))
page = [_job_response(j["job_id"]) for j in jobs[offset: offset + limit]]
return {"data": {"jobs": page}}
@app.get("/api/v1/jobs/{job_id}")
def get_job(job_id: str):
if job_id not in _jobs:
raise HTTPException(status_code=404, detail="job not found")
return {"data": _job_response(job_id)}
@app.delete("/api/v1/jobs/{job_id}")
def delete_job(job_id: str):
if job_id not in _jobs:
raise HTTPException(status_code=404, detail="job not found")
del _jobs[job_id]
return {"data": {"deleted": True}}
# Serve result files directly (no R2 in local mode — the desktop app streams from here)
@app.get("/results/{filename}")
def get_result(filename: str):
path = _results_dir / filename
if not path.exists():
raise HTTPException(status_code=404, detail="result file not found")
media_type = "image/png" if filename.endswith(".png") else (
"video/mp4" if filename.endswith(".mp4") else "audio/wav"
)
return FileResponse(str(path), media_type=media_type)
# ── health check endpoint ────────────────────────────────────────────────────
@app.get("/health")
def health():
return {"status": "ok", "engine": "freegen-local"}
# ── main ─────────────────────────────────────────────────────────────────────
if __name__ == "__main__":
import uvicorn
port = int(os.environ.get("FREEGEN_PORT", "8765"))
print(f"[freegen] local sidecar starting on http://127.0.0.1:{port}/api/v1")
print(f"[freegen] results directory: {_results_dir}")
print(f"[freegen] to use with the desktop app, set API base to:")
print(f" http://127.0.0.1:{port}/api/v1")
uvicorn.run(app, host="127.0.0.1", port=port, log_level="warning")