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>
107 lines
4.2 KiB
Python
107 lines
4.2 KiB
Python
"""Escolha do dispositivo de inferência: GPU NVIDIA (CUDA) quando houver e funcionar; senão CPU.
|
|
|
|
No Windows as DLLs do CUDA (cuBLAS, cuDNN) vêm de pacotes pip `nvidia-*-cu12` e da pasta `torch/lib`.
|
|
Elas precisam ser registradas ANTES de importar ctranslate2/torch, ou o CUDA "existe" mas a carga falha.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import logging
|
|
import os
|
|
import sys
|
|
from dataclasses import dataclass
|
|
from pathlib import Path
|
|
|
|
log = logging.getLogger("cenaforge_voice")
|
|
_registered = False
|
|
|
|
|
|
@dataclass(frozen=True)
|
|
class DeviceInfo:
|
|
kind: str # "cuda" | "cpu"
|
|
name: str | None # nome da GPU, quando houver
|
|
reason: str # por que caiu nesse dispositivo (vai para o /v1/status e para o log)
|
|
|
|
|
|
def register_cuda_dlls() -> None:
|
|
"""Coloca as pastas de DLL do CUDA (pip nvidia-* e torch/lib) no caminho de busca do Windows."""
|
|
global _registered
|
|
if _registered or sys.platform != "win32":
|
|
_registered = True
|
|
return
|
|
_registered = True
|
|
for site in {Path(p) for p in sys.path if p.endswith("site-packages")}:
|
|
candidates = list((site / "nvidia").glob("*/bin")) + [site / "torch" / "lib"]
|
|
for folder in candidates:
|
|
if folder.is_dir():
|
|
os.add_dll_directory(str(folder))
|
|
os.environ["PATH"] = f"{folder}{os.pathsep}{os.environ.get('PATH', '')}"
|
|
|
|
|
|
def resolve_device(setting: str) -> DeviceInfo:
|
|
"""`auto` testa o CUDA de verdade (contagem de GPUs no CTranslate2/torch); `cpu` desliga o CUDA de vez."""
|
|
if setting == "cpu":
|
|
# Também impede o Applio (torch) de pegar a GPU por conta própria.
|
|
os.environ["CUDA_VISIBLE_DEVICES"] = ""
|
|
return DeviceInfo("cpu", None, "VOICE_DEVICE=cpu")
|
|
register_cuda_dlls()
|
|
count = 0
|
|
try:
|
|
import ctranslate2
|
|
|
|
count = ctranslate2.get_cuda_device_count()
|
|
except Exception as exc: # noqa: BLE001 - qualquer falha de driver/DLL = sem CUDA
|
|
log.warning("cuda: ctranslate2 não enxergou a GPU (%s)", type(exc).__name__)
|
|
name = _gpu_name()
|
|
if count > 0:
|
|
busy = gpu_busy_reason() if setting == "auto" else None
|
|
if busy:
|
|
# Medido: com um jogo usando a placa (99%, 7,2/8 GB), 6,5 s de fala levaram minutos na GPU contra
|
|
# ~3 s na CPU. No auto, GPU ocupada na subida = CPU (e o Applio também, pelo CUDA_VISIBLE_DEVICES).
|
|
os.environ["CUDA_VISIBLE_DEVICES"] = ""
|
|
log.warning("cuda: %s; usando CPU (force com VOICE_DEVICE=cuda)", busy)
|
|
return DeviceInfo("cpu", name, busy)
|
|
return DeviceInfo("cuda", name, "GPU NVIDIA detectada")
|
|
if setting == "cuda":
|
|
log.warning("cuda: VOICE_DEVICE=cuda, mas nenhuma GPU utilizável foi encontrada; usando CPU")
|
|
return DeviceInfo("cpu", None, "sem GPU NVIDIA utilizável")
|
|
|
|
|
|
MIN_FREE_MIB = 2048 # Whisper small/turbo em float16 + RVC cabem com folga em ~2 GB
|
|
MAX_BUSY_PERCENT = 85
|
|
|
|
|
|
def gpu_busy_reason() -> str | None:
|
|
"""Pergunta ao nvidia-smi (argumentos fixos) quanto da GPU 0 está livre. Ocupada demais → motivo; senão None."""
|
|
import subprocess
|
|
|
|
try:
|
|
out = subprocess.run(
|
|
["nvidia-smi", "--query-gpu=memory.free,utilization.gpu", "--format=csv,noheader,nounits"],
|
|
capture_output=True, text=True, timeout=10, check=True,
|
|
).stdout.splitlines()[0]
|
|
free_mib, util = (int(part.strip()) for part in out.split(","))
|
|
except Exception: # noqa: BLE001 - sem nvidia-smi ou saída estranha: não bloqueia a GPU
|
|
return None
|
|
if free_mib < MIN_FREE_MIB or util >= MAX_BUSY_PERCENT:
|
|
return f"GPU ocupada por outro programa ({util}% de uso, {free_mib} MiB livres)"
|
|
return None
|
|
|
|
|
|
def _gpu_name() -> str | None:
|
|
try:
|
|
import torch
|
|
|
|
if torch.cuda.is_available():
|
|
return torch.cuda.get_device_name(0)
|
|
except Exception: # noqa: BLE001 - torch ausente (instalação sem RVC) ou sem CUDA
|
|
return None
|
|
return None
|
|
|
|
|
|
def stt_compute_type(setting: str, device: DeviceInfo) -> str:
|
|
"""`auto`: float16 na GPU (rápido, sem perda perceptível), int8 na CPU (medido no dropsz_voice)."""
|
|
if setting != "auto":
|
|
return setting
|
|
return "float16" if device.kind == "cuda" else "int8"
|