Ao dividir _shared.py em admin/api/*.py ontem, o cálculo `Path(__file__).resolve().parent.parent / "code"` foi copiado sem ajustar para o nível de diretório novo. No arquivo original (admin/models_api.py, direto em admin/) dois `.parent` chegavam na raiz do repo. Em admin/api/shared.py, um nível mais fundo, dois `.parent` param em admin/ — e admin/code nunca existiu. sys.path nunca recebia code/, então toda ação que passa por `server` (analisar voz, aplicar decisões) crashava o app com ModuleNotFoundError: server_tools. O bug sobreviveu a duas rodadas de validação da sessão anterior — lint zero, 1454 testes verdes, comando testado manualmente pela ponte — porque todos rodam num venv com install editável (__editable__.fcp_mcp_server.pth) que já deixa fcpxml/server_tools importáveis por conta própria, mascarando qualquer erro no cálculo manual de sys.path. Só o app real, no fallback sem uv, expõe o bug. Correção: o cálculo de sys.path sai de cada módulo de comando (estava duplicado em nove arquivos) e passa a existir uma única vez em admin/api/__init__.py, que roda antes de qualquer submódulo — nenhum precisa mais da própria cópia. O teste de regressão precisou de duas tentativas pelo mesmo motivo do bug: a primeira versão também passava com o bug presente, por rodar no mesmo venv "de sorte". Só ficou confiável isolando um subprocess que remove site-packages do sys.path antes de importar — confirmado nos dois sentidos, falha com o bug reintroduzido e passa com a correção (TestCodeDirResolution). Detalhe completo, incluindo por que o comando manual não pegou: Engine/docs/05_EXPERIENCIAS.md #25. Lint zerado, 1457 testes passando (3 novos), app compilado. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
123 lines
4.8 KiB
Python
123 lines
4.8 KiB
Python
"""Edições no projeto: silêncio, corte por texto, preenchimento, marcadores.
|
|
|
|
Extraído de models_api.py — a tabela de comandos segue lá.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import asyncio
|
|
from pathlib import Path
|
|
|
|
from fcpxml.model_manager import (
|
|
load_silence_config,
|
|
save_silence_config,
|
|
)
|
|
|
|
from . import shared
|
|
from .shared import (
|
|
_derived_output,
|
|
_emit_no_change_or_error,
|
|
)
|
|
|
|
|
|
def cmd_remove_silences(args: dict) -> int:
|
|
"""Run the canonical server silence remover into a suffixed copy."""
|
|
path = str(args.get("path", ""))
|
|
if not path or not Path(path).exists():
|
|
shared.emit({"ok": False, "error": "Arquivo de projeto não encontrado."})
|
|
return 1
|
|
try:
|
|
from server import handle_remove_media_silence
|
|
|
|
output = _derived_output(path, "_silence_removed", args)
|
|
contents = asyncio.run(handle_remove_media_silence({**args, "filepath": path, "output_path": output}))
|
|
message = "\n".join(getattr(content, "text", str(content)) for content in contents)
|
|
if not Path(output).exists():
|
|
return _emit_no_change_or_error(path, message)
|
|
shared.emit({"ok": True, "path": output, "message": message})
|
|
return 0
|
|
except Exception as exc:
|
|
shared.emit({"ok": False, "error": str(exc)})
|
|
return 1
|
|
|
|
def cmd_edit_by_transcript(args: dict) -> int:
|
|
"""Cut (or keep only) spoken phrases, using each media's cached transcript."""
|
|
path = str(args.get("path", ""))
|
|
phrases = args.get("phrases") or []
|
|
if not path or not Path(path).exists():
|
|
shared.emit({"ok": False, "error": "Arquivo de projeto não encontrado."})
|
|
return 1
|
|
if not isinstance(phrases, list) or not [p for p in phrases if str(p).strip()]:
|
|
shared.emit({"ok": False, "error": "Informe ao menos uma frase para cortar."})
|
|
return 1
|
|
try:
|
|
from server import handle_edit_by_transcript
|
|
|
|
output = _derived_output(path, "_transcript_edit", args)
|
|
contents = asyncio.run(handle_edit_by_transcript({**args, "filepath": path, "output_path": output}))
|
|
message = "\n".join(getattr(content, "text", str(content)) for content in contents)
|
|
if not Path(output).exists():
|
|
shared.emit({"ok": False, "error": message})
|
|
return 1
|
|
shared.emit({"ok": True, "path": output, "message": message})
|
|
return 0
|
|
except Exception as exc:
|
|
shared.emit({"ok": False, "error": str(exc)})
|
|
return 1
|
|
|
|
def cmd_remove_filler_words(args: dict) -> int:
|
|
"""Cut filler words (um, uh, ...) out, using each media's cached transcript."""
|
|
path = str(args.get("path", ""))
|
|
if not path or not Path(path).exists():
|
|
shared.emit({"ok": False, "error": "Arquivo de projeto não encontrado."})
|
|
return 1
|
|
try:
|
|
from server import handle_remove_filler_words
|
|
|
|
output = _derived_output(path, "_defillered", args)
|
|
contents = asyncio.run(handle_remove_filler_words({**args, "filepath": path, "output_path": output}))
|
|
message = "\n".join(getattr(content, "text", str(content)) for content in contents)
|
|
if not Path(output).exists():
|
|
return _emit_no_change_or_error(path, message)
|
|
shared.emit({"ok": True, "path": output, "message": message})
|
|
return 0
|
|
except Exception as exc:
|
|
shared.emit({"ok": False, "error": str(exc)})
|
|
return 1
|
|
|
|
def cmd_transcript_markers(args: dict) -> int:
|
|
"""Add a marker per transcribed segment, using each media's cached transcript."""
|
|
path = str(args.get("path", ""))
|
|
if not path or not Path(path).exists():
|
|
shared.emit({"ok": False, "error": "Arquivo de projeto não encontrado."})
|
|
return 1
|
|
try:
|
|
from server import handle_transcript_markers
|
|
|
|
output = _derived_output(path, "_transcript_markers", args)
|
|
contents = asyncio.run(handle_transcript_markers({**args, "filepath": path, "output_path": output}))
|
|
message = "\n".join(getattr(content, "text", str(content)) for content in contents)
|
|
if not Path(output).exists():
|
|
shared.emit({"ok": False, "error": message})
|
|
return 1
|
|
shared.emit({"ok": True, "path": output, "message": message})
|
|
return 0
|
|
except Exception as exc:
|
|
shared.emit({"ok": False, "error": str(exc)})
|
|
return 1
|
|
|
|
def cmd_silence_config(args: dict) -> int:
|
|
"""Read the persisted silence thresholds (noise floor, duration, padding)."""
|
|
shared.emit({"ok": True, **load_silence_config()})
|
|
return 0
|
|
|
|
def cmd_set_silence_config(args: dict) -> int:
|
|
"""Persist silence thresholds. Only the given fields change."""
|
|
config = save_silence_config(
|
|
noise_db=args.get("noise_db"),
|
|
min_silence=args.get("min_silence"),
|
|
padding=args.get("padding"),
|
|
)
|
|
shared.emit({"ok": True, **config})
|
|
return 0
|