Skip to content

Open-source AI podcast clipper. Generate vertical clips with face tracking and burned-in captions. CLI, MCP server, web app.

7.7 KB
Raw Blame
// Package engine routes podcli subcommands to the Python backend.
package engine

import (
	"bytes"
	"fmt"
	"os"
	"os/exec"
	"path/filepath"
	"runtime"
	"strings"

	"podcli/internal/paths"
)

// stderrFilter drops the macOS/OpenCV/Whisper startup noise the old bash
// launcher stripped with `grep -v`, so native runs aren't louder than before.
// It buffers partial lines and forwards everything else to real stderr.
type stderrFilter struct{ buf []byte }

func isStderrNoise(line string) bool {
	trim := strings.TrimSpace(line)
	return strings.HasPrefix(line, "objc[") ||
		strings.Contains(line, "FP16 is not supported") ||
		strings.HasPrefix(trim, "warnings.warn(") ||
		strings.HasPrefix(trim, "[ WARN:") ||
		strings.HasPrefix(trim, "[WARN:")
}

func (w *stderrFilter) Write(p []byte) (int, error) {
	w.buf = append(w.buf, p...)
	for {
		i := bytes.IndexByte(w.buf, '\n')
		if i < 0 {
			break
		}
		line := w.buf[:i]
		w.buf = w.buf[i+1:]
		if !isStderrNoise(string(line)) {
			os.Stderr.Write(append(line, '\n'))
		}
	}
	return len(p), nil
}

func (w *stderrFilter) flush() {
	if len(w.buf) > 0 && !isStderrNoise(string(w.buf)) {
		os.Stderr.Write(w.buf)
	}
	w.buf = nil
}

// IsHermeticPython reports whether the resolved interpreter is the provisioned
// one (which lacks openai-whisper, so transcription must default to whisper.cpp).
func IsHermeticPython() bool {
	return strings.HasPrefix(Python(), paths.RuntimeDir())
}

func exists(p string) bool {
	_, err := os.Stat(p)
	return err == nil
}

func BackendRoot() (string, bool) {
	if b := os.Getenv("PODCLI_BACKEND"); b != "" && exists(filepath.Join(b, "cli.py")) {
		return b, true
	}
	if dir, err := os.Getwd(); err == nil {
		for {
			cand := filepath.Join(dir, "backend")
			if exists(filepath.Join(cand, "cli.py")) {
				return cand, true
			}
			parent := filepath.Dir(dir)
			if parent == dir {
				break
			}
			dir = parent
		}
	}
	cand := filepath.Join(paths.RuntimeDir(), "backend")
	if exists(filepath.Join(cand, "cli.py")) {
		return cand, true
	}
	return "", false
}

func Python() string {
	if p := os.Getenv("PODCLI_PYTHON"); p != "" {
		return p
	}
	hermetic := []string{
		filepath.Join(paths.RuntimeDir(), "python", "bin", "python3"),
		filepath.Join(paths.RuntimeDir(), "python", "python.exe"),
	}
	for _, p := range hermetic {
		if exists(p) {
			return p
		}
	}
	if root, ok := BackendRoot(); ok {
		venv := filepath.Join(filepath.Dir(root), "venv", "bin", "python3")
		if runtime.GOOS == "windows" {
			venv = filepath.Join(filepath.Dir(root), "venv", "Scripts", "python.exe")
		}
		if exists(venv) {
			return venv
		}
	}
	return "python3"
}

func runtimeBin(sub, name string) string {
	for _, p := range []string{
		filepath.Join(paths.RuntimeDir(), sub, name),
		filepath.Join(paths.RuntimeDir(), sub, name+".exe"),
	} {
		if exists(p) {
			return p
		}
	}
	return ""
}

func FFmpeg() string     { return runtimeBin("ffmpeg", "ffmpeg") }
func FFprobe() string    { return runtimeBin("ffmpeg", "ffprobe") }
func WhisperCLI() string { return runtimeBin("whisper", "whisper-cli") }

func Node() string {
	for _, p := range []string{
		filepath.Join(paths.RuntimeDir(), "node", "bin", "node"),
		filepath.Join(paths.RuntimeDir(), "node", "node.exe"),
	} {
		if exists(p) {
			return p
		}
	}
	return ""
}

func StudioServer() string {
	p := filepath.Join(paths.RuntimeDir(), "studio", "web-server.mjs")
	if exists(p) {
		return p
	}
	return ""
}

func MCPServer() string {
	p := filepath.Join(paths.RuntimeDir(), "studio", "mcp-server.mjs")
	if exists(p) {
		return p
	}
	return ""
}

func SyncScript() string {
	p := filepath.Join(paths.RuntimeDir(), "studio", "sync.mjs")
	if exists(p) {
		return p
	}
	return ""
}

// RunSync reconciles this machine with the podcli Pro workspace. Ships with the
// studio bundle because the sync logic lives on the TypeScript side, alongside
// the clip history and asset registry it reconciles.
func RunSync() (int, error) {
	node, script := Node(), SyncScript()
	if node == "" || script == "" {
		return 1, fmt.Errorf("sync not provisioned: run `podcli setup`")
	}
	cmd := exec.Command(node, script)
	cmd.Stdin, cmd.Stdout, cmd.Stderr = os.Stdin, os.Stdout, os.Stderr
	cmd.Env = nodeEnv()
	if err := cmd.Run(); err != nil {
		if ee, ok := err.(*exec.ExitError); ok {
			return ee.ExitCode(), nil
		}
		return 1, err
	}
	return 0, nil
}

// nodeEnv builds the env a bundled Node server (studio/MCP) needs: the TS
// paths.ts reads these names (note PYTHON_PATH/FFMPEG_PATH differ from the
// PODCLI_* names the Python side uses). Project data stays cwd-local.
func nodeEnv() []string {
	env := os.Environ()
	if root, ok := BackendRoot(); ok {
		env = append(env, "PODCLI_BACKEND="+root)
	}
	// Node spawns the Python backend and passes its own env through, so these must be
	// set here too, not only in Run(). Titles cross that pipe as UTF-8 JSON.
	env = append(env, "PYTHONIOENCODING=utf-8", "PYTHONUTF8=1")
	env = append(env, "PYTHON_PATH="+Python())
	if ff := FFmpeg(); ff != "" {
		env = append(env, "FFMPEG_PATH="+ff)
	}
	if fp := FFprobe(); fp != "" {
		env = append(env, "FFPROBE_PATH="+fp)
	}
	env = append(env, DataEnv()...)
	return env
}

// RunMCP execs the bundled MCP stdio server under hermetic Node. stdout carries
// JSON-RPC, so nothing here may write to it.
func RunMCP() (int, error) {
	node, server := Node(), MCPServer()
	if node == "" || server == "" {
		return 1, fmt.Errorf("MCP server not provisioned: run `podcli setup`")
	}
	cmd := exec.Command(node, server)
	cmd.Stdin, cmd.Stdout, cmd.Stderr = os.Stdin, os.Stdout, os.Stderr
	cmd.Env = nodeEnv()
	if err := cmd.Run(); err != nil {
		if ee, ok := err.(*exec.ExitError); ok {
			return ee.ExitCode(), nil
		}
		return 1, err
	}
	return 0, nil
}

// DataEnv tells the backend where data lives. The brand brain (presets,
// knowledge, assets, history, config) and the transcript cache live in the
// global managed dir so they follow the user across directories; only rendered
// clips go under the working directory (PODCLI_OUTPUT). Explicit env always wins
// so power users and tests can override any single path.
func DataEnv() []string {
	var env []string
	home := paths.Home()
	if os.Getenv("PODCLI_HOME") == "" {
		env = append(env, "PODCLI_HOME="+home)
	}
	if os.Getenv("PODCLI_DATA") == "" {
		env = append(env, "PODCLI_DATA="+filepath.Join(home, "data"))
	}
	if os.Getenv("PODCLI_ENV_FILE") == "" {
		env = append(env, "PODCLI_ENV_FILE="+filepath.Join(home, ".env"))
	}
	if cwd, err := os.Getwd(); err == nil {
		if os.Getenv("PODCLI_CWD") == "" {
			env = append(env, "PODCLI_CWD="+cwd)
		}
		if os.Getenv("PODCLI_OUTPUT") == "" {
			env = append(env, "PODCLI_OUTPUT="+filepath.Join(cwd, "podcli-clips"))
		}
	}
	return env
}

func Run(args []string) (int, error) {
	root, ok := BackendRoot()
	if !ok {
		return 1, fmt.Errorf("python backend not found: set PODCLI_BACKEND or run inside the repo")
	}
	cli := filepath.Join(root, "cli.py")
	full := append([]string{"-W", "ignore::UserWarning", cli}, args...)

	cmd := exec.Command(Python(), full...)
	sf := &stderrFilter{}
	cmd.Stdin, cmd.Stdout, cmd.Stderr = os.Stdin, os.Stdout, sf
	env := append(os.Environ(),
		"OBJC_DISABLE_INITIALIZE_FORK_SAFETY=YES",
		"PYTHONIOENCODING=utf-8",
		"PYTHONUTF8=1",
	)
	if ff := FFmpeg(); ff != "" {
		env = append(env, "PODCLI_FFMPEG="+ff)
	}
	if fp := FFprobe(); fp != "" {
		env = append(env, "PODCLI_FFPROBE="+fp)
	}
	if wc := WhisperCLI(); wc != "" {
		env = append(env, "PODCLI_WHISPER_CLI="+wc)
	}
	if nd := Node(); nd != "" {
		env = append(env, "PODCLI_NODE="+nd)
	}
	if ss := StudioServer(); ss != "" {
		env = append(env, "PODCLI_STUDIO="+filepath.Dir(ss))
	}
	env = append(env, DataEnv()...)
	cmd.Env = env

	err := cmd.Run()
	sf.flush()
	if err != nil {
		if ee, ok := err.(*exec.ExitError); ok {
			return ee.ExitCode(), nil
		}
		return 1, err
	}
	return 0, nil
}