Files
CenaForge/clipper/app/config.py
T
MateuusandClaude Opus 5.5 84f30bbc2d CenaForge: primeira versão pública
Gerador de vídeos narrativos (Godot + FFmpeg), painel Next.js, serviço de voz,
Clipador de lives e Publicador para YouTube, TikTok e Instagram.

Inclui a leitura das visualizações dos posts para o Dashboard e o botão
"Publicar no <rede>" nos cartões das publicações.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 16:35:09 -03:00

131 lines
5.3 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""Configuração do Clipador, lida de clipper/.env (e do ambiente, que tem prioridade)."""
from __future__ import annotations
import os
import shutil
import sys
from dataclasses import dataclass
from pathlib import Path
CLIPPER_DIR = Path(__file__).resolve().parent.parent
REPO_ROOT = CLIPPER_DIR.parent
PORT_RANGE = (4500, 4599)
class ConfigError(RuntimeError):
"""Configuração inválida: o serviço não sobe."""
def read_env_file(path: Path) -> dict[str, str]:
if not path.is_file():
return {}
values: dict[str, str] = {}
for line in path.read_text(encoding="utf-8").splitlines():
if "=" not in line or line.lstrip().startswith("#"):
continue
name, value = line.split("=", 1)
values[name.strip()] = value.strip()
return values
def _find_tool(env_name: str, names: list[str], extra_dirs: list[Path]) -> str | None:
if os.environ.get(env_name):
return os.environ[env_name]
for directory in extra_dirs:
for name in names:
for ext in ("", ".exe"):
candidate = directory / f"{name}{ext}"
if candidate.is_file():
return str(candidate)
for name in names:
found = shutil.which(name)
if found:
return found
return None
@dataclass(frozen=True)
class Settings:
service_key: str
port: int
segment_s: int
poll_s: int
keep_hours: float
language: str
encoder: str
data_dir: Path
clips_dir: Path
ffmpeg: str | None
ffprobe: str | None
streamlink: str | None
voice_url: str | None
voice_key: str | None
judge_provider: str
judge_model: str
judge_min_score: float
@staticmethod
def load(env_file: Path | None = None, **overrides: object) -> "Settings":
env = {**read_env_file(env_file or CLIPPER_DIR / ".env"), **os.environ}
voice_env = read_env_file(REPO_ROOT / "voice" / ".env")
def num(name: str, default: float, minimum: float = 0) -> float:
raw = env.get(name, "")
try:
value = float(raw) if raw else default
except ValueError as exc:
raise ConfigError(f"{name} precisa ser número") from exc
if value < minimum:
raise ConfigError(f"{name} precisa ser >= {minimum}")
return value
port = int(num("CLIPPER_PORT", 4520, 1))
if not PORT_RANGE[0] <= port <= PORT_RANGE[1]:
raise ConfigError(f"CLIPPER_PORT={port} fora da faixa {PORT_RANGE[0]}–{PORT_RANGE[1]} do CenaForge")
venv_scripts = CLIPPER_DIR / ".venv" / ("Scripts" if sys.platform == "win32" else "bin")
def repo_dir(name: str, default: Path) -> Path:
"""Pasta opcional (CLIPPER_DATA_DIR/CLIPPER_OUTPUT_DIR) para isolar uma instância de teste. Precisa ficar
dentro do repositório: blocos e cortes são gravados no banco com caminho relativo ao repo."""
raw = env.get(name, "").strip()
if not raw:
return default
path = Path(raw)
path = (path if path.is_absolute() else REPO_ROOT / path).resolve()
if not path.is_relative_to(REPO_ROOT.resolve()):
raise ConfigError(f"{name} precisa ficar dentro do repositório ({REPO_ROOT})")
return REPO_ROOT / path.relative_to(REPO_ROOT.resolve())
settings = Settings(
service_key=env.get("CLIPPER_SERVICE_KEY", ""),
port=port,
# CLIPPER_QUALITY não é mais lida: a qualidade de gravação é `capture.quality` (canal/sessão, painel).
segment_s=int(num("CLIPPER_SEGMENT_S", 30, 5)),
poll_s=int(num("CLIPPER_POLL_S", 60, 15)),
keep_hours=num("CLIPPER_KEEP_HOURS", 6, 0),
language=env.get("CLIPPER_LANGUAGE", "pt-BR") or "pt-BR",
encoder=env.get("CLIPPER_ENCODER", "auto") or "auto",
data_dir=repo_dir("CLIPPER_DATA_DIR", REPO_ROOT / "data" / "clipper"),
# output/ é servido pelo painel (/api/files): os cortes prontos ficam lá.
clips_dir=repo_dir("CLIPPER_OUTPUT_DIR", REPO_ROOT / "output" / "clipper"),
ffmpeg=_find_tool("FFMPEG_BIN", ["ffmpeg"], []),
ffprobe=_find_tool("FFPROBE_BIN", ["ffprobe"], []),
streamlink=_find_tool("STREAMLINK_BIN", ["streamlink"], [venv_scripts]),
voice_url=f"http://127.0.0.1:{voice_env.get('VOICE_PORT') or '4510'}" if voice_env.get("VOICE_SERVICE_KEY") else None,
voice_key=voice_env.get("VOICE_SERVICE_KEY") or None,
# Valores iniciais do juiz; depois quem manda é o painel (tabela settings do banco do Clipador).
judge_provider=(env.get("CLIPPER_JUDGE_PROVIDER") or "codex").lower(),
judge_model=env.get("CLIPPER_JUDGE_MODEL", ""),
judge_min_score=num("CLIPPER_JUDGE_MIN_SCORE", 6, 0),
)
if settings.judge_provider not in ("codex", "claude", "off"):
raise ConfigError("CLIPPER_JUDGE_PROVIDER precisa ser codex, claude ou off")
if settings.encoder not in ("auto", "libx264", "h264_nvenc"):
raise ConfigError("CLIPPER_ENCODER precisa ser auto, libx264 ou h264_nvenc")
if overrides:
from dataclasses import replace
settings = replace(settings, **overrides) # type: ignore[arg-type]
return settings