enhancement in english words and others
Build an image with the following files:
docker-compose.yml
server.py
Dockerfile
versoes.txt
commands:
docker compose build kokoro-pt
docker compose up -d kokoro-pt
test:
curl -s -X POST http://localhost:8097/v1/audio/speech
-H "Content-Type: application/json"
-d '{"input":"No menu, home, veja o status do ticket e o NIB 0035... Pode receber a informação por email ou whatsapp... 1. Clique em Home, 2. clique em info","response_format":"wav"}'
--output ./volumes/kokoro-pt/testes/teste.wav
docker-compose.yml:
kokoro-pt:
build:
context: ./volumes/kokoro-pt
dockerfile: Dockerfile
image: kokoro-pt-tts:local
container_name: kokoro-tts
restart: unless-stopped
environment:
- TTS_DEVICE=cuda
deploy:
resources:
reservations:
devices:
- driver: nvidia
count: all
capabilities: [gpu]
ports:
- "8097:8097"
volumes:
- /home/your-path-to/volumes/kokoro-pt/models:/models
healthcheck:
test: ["CMD", "python", "-c", "import urllib.request; urllib.request.urlopen('http://localhost:8097/health')"]
interval: 30s
timeout: 10s
retries: 3
start_period: 90s
Dockerfile:
FROM python:3.11-slim
WORKDIR /app
COPY versoes.txt .
RUN pip install --no-cache-dir torch==2.11.0 --index-url https://download.pytorch.org/whl/cu128
&& pip install --no-cache-dir -c versoes.txt tts_eu_pt fastapi "uvicorn[standard]"
COPY server.py .
ENV HF_HOME=/models
CMD ["uvicorn", "server:app", "--host", "0.0.0.0", "--port", "8097"]
versoes.txt:
bifonia==0.5.5a5
chronologia==0.43.15a1
desacordo_ortografico==0.3.39a3
linguatag==0.4.4a2
numtag==0.22.0a1
o2i-lexicons==0.7.22a2
orthography2ipa==7.127.1a2
ovos-config==2.1.1
ovos-date-parser==0.41.4a2
ovos-number-parser==0.31.4a9
ovos-spec-tools==1.17.1a2
ovos-utils==0.8.5
phonematcher==3.1.6a1
silabificador==2.1.15a4
text2spoken==0.0.2a133
tokenizers==0.23.3
transformers==5.24.1
tts_eu_pt==0.1.1
tugalex==3.0.0a1
tugaphone==1.11.12a4
server.py:
import io, os, re, sys, threading, time, wave
import numpy as np
import torch
from fastapi import FastAPI, Response
from pydantic import BaseModel
from loguru import logger
from tts_eu_pt import TTS, _sentences
from tts_eu_pt import g2p as tts_g2p
from tugaphone import TugaPhonemizer
--- logging ---
logger.remove()
logger.add(sys.stderr, level="WARNING")
--- afinacao (variaveis de ambiente) ---
SR = 24000
TAIL_ABS = float(os.getenv("TTS_TAIL_ABS", "0.01"))
TAIL_REL = float(os.getenv("TTS_TAIL_REL", "0.15"))
TAIL_MARGIN_MS = int(os.getenv("TTS_TAIL_MARGIN_MS", "30"))
TAIL_FADE_MS = int(os.getenv("TTS_TAIL_FADE_MS", "40"))
LAST_MAX_FRAMES = float(os.getenv("TTS_LAST_MAX_FRAMES", "5"))
END_MAX_FRAMES = float(os.getenv("TTS_END_MAX_FRAMES", "3"))
LAST_ATONO_FRAMES = float(os.getenv("TTS_ATONO_LAST_FRAMES", "2"))
END_ATONO_FRAMES = float(os.getenv("TTS_ATONO_END_FRAMES", "1"))
PONTUACAO_DEFAULT = os.getenv("TTS_PONTUACAO", "manter")
NASAIS = os.getenv("TTS_NASAIS", "1") == "1"
DEBUG = os.getenv("TTS_DEBUG", "0") == "1"
MAX_CHARS = int(os.getenv("TTS_MAX_CHARS", "200"))
DEFAULT_SPEED = float(os.getenv("TTS_DEFAULT_SPEED", "0.9"))
PONT = ".,;:!?"
--- modelo ---
tts = TTS(device=os.getenv("TTS_DEVICE") or None)
print(f"cuda disponivel={torch.cuda.is_available()}", flush=True)
print(f"vocabulario tem til combinante (U+0303): {chr(0x303) in tts_g2p.VOCAB}", flush=True)
print(f"vocabulario tem '?': {'?' in tts_g2p.VOCAB} | '.': {'.' in tts_g2p.VOCAB} | '!': {'!' in tts_g2p.VOCAB}", flush=True)
--- G2P correto (TugaPhone) ---
ph = TugaPhonemizer()
_MAX_PHONEMES = tts_g2p.MAX_PHONEME_LEN
if NASAIS:
SYMBOL_MAP_EXTRA = {
"ũ": "u\u0303",
"ĩ": "i\u0303",
"ẽ": "e\u0303",
"õ": "o\u0303",
}
else:
SYMBOL_MAP_EXTRA = {"ũ": "u", "ĩ": "i", "ẽ": "e", "õ": "o"}
Overrides de IPA pontuais (apenas quando validados com /v1/fonemas e escuta)
IPA_OVERRIDES = {
"ˈflɔɾɨʃ": "ˈfloɾɨʃ",
}
_VOGAIS = set("aɐɑeɛɨiɪoɔuʊ")
def _mapear_simbolos(ipa: str) -> str:
"""Substitui simbolos nao suportados pelo Kokoro por equivalentes."""
for orig, novo in tts_g2p.SYMBOL_MAP.items():
ipa = ipa.replace(orig, novo)
for orig, novo in SYMBOL_MAP_EXTRA.items():
ipa = ipa.replace(orig, novo)
vocab = set(tts_g2p.VOCAB.keys())
return "".join(ch for ch in ipa if ch in vocab or ch.isspace())
def _ipa_final(ps: str) -> str:
for orig, novo in IPA_OVERRIDES.items():
ps = ps.replace(orig, novo)
return _mapear_simbolos(ps)
def _final_atono(ps: str) -> bool:
s = ps.strip().rstrip(PONT + " ").replace("\u0303", "")
if not s or s[-1] not in _VOGAIS:
return False
i = s.rfind("ˈ")
if i < 0:
return False
return sum(c in _VOGAIS for c in s[i + 1:]) >= 2
def _fade_out(x: np.ndarray, ms: int = 30) -> np.ndarray:
n = min(int(ms / 1000 * SR), len(x))
if n > 1:
x[-n:] *= np.linspace(1.0, 0.0, n, dtype=np.float32)
return x
def limitar_ultimo(a: np.ndarray, pred_dur, ps: str, lf: float, ef: float) -> np.ndarray:
if pred_dur is None:
return a
d = pred_dur.detach().cpu().numpy().astype("float64").reshape(-1)
if len(d) < 4 or d.sum() <= 0:
return a
factor = len(a) / d.sum()
alinhado = len(d) == len(ps) + 2
p = 0
if alinhado:
while p < len(ps) - 1 and ps[len(ps) - 1 - p] in PONT:
p += 1
fim_tok = d[-1]
if DEBUG:
if alinhado:
n = min(6, len(ps))
par = " ".join(f"{c}:{int(f)}" for c, f in zip(ps[-n:], d[-(n + 1):-1]))
print(f"[dur] fim: {par} | token_fim:{int(fim_tok)} | pont_final={p} | "
f"atono={_final_atono(ps)} limites vogal={lf} fim={ef}", flush=True)
else:
print(f"[dur] len(d)={len(d)} len(ps)={len(ps)} ultimos={d[-5:].tolist()}", flush=True)
if p == 0:
ultimo = d[-2]
if ultimo <= lf and fim_tok <= ef:
return a
corpo = d[:-2].sum()
n = min(int((corpo + min(ultimo, lf) + min(fim_tok, ef)) * factor), len(a))
return _fade_out(a[:n].copy())
iv = len(d) - 2 - p
vogal = d[iv]
cap = lf + ef
fim_audio = min(int((d[:-1].sum() + min(fim_tok, ef)) * factor), len(a))
if vogal <= cap:
if fim_tok <= ef:
return a
return _fade_out(a[:fim_audio].copy())
antes = d[:iv].sum()
s1 = int((antes + cap) * factor)
s2 = int((antes + vogal) * factor)
p1 = a[:s1].copy()
p2 = a[s2:fim_audio].copy()
f = int(0.015 * SR)
if len(p1) > f:
p1[-f:] *= np.linspace(1.0, 0.0, f, dtype=np.float32)
if len(p2) > f:
p2[:f] *= np.linspace(0.0, 1.0, f, dtype=np.float32)
return np.concatenate([p1, p2])
def cortar_fim(audio: np.ndarray) -> np.ndarray:
janela = int(0.01 * SR)
n = len(audio) // janela
if n < 5:
return audio
rms = np.sqrt(np.mean(audio[:n * janela].reshape(n, janela) ** 2, axis=1))
pico = float(rms.max())
if pico <= 0:
return audio
if DEBUG:
cauda = (rms[-40:] / pico).round(2).tolist()
print(f"[tail] pico_rms={pico:.3f} ultimos 400ms (rel.)={cauda}", flush=True)
limiar = max(TAIL_ABS, TAIL_REL * pico)
idx = np.nonzero(rms > limiar)[0]
if len(idx) == 0:
return audio
fim = min((int(idx[-1]) + 1) * janela + int(TAIL_MARGIN_MS / 1000 * SR), len(audio))
out = audio[:fim].copy()
return _fade_out(out, TAIL_FADE_MS)
def _partir(frase: str, limite: int = MAX_CHARS):
if len(frase) <= limite:
return [frase]
pedacos, atual = [], ""
for palavra in frase.split():
atual = f"{atual} {palavra}".strip()
if len(atual) >= limite or (atual.endswith(",") and len(atual) >= limite * 0.5):
pedacos.append(atual)
atual = ""
if atual:
pedacos.append(atual)
return pedacos
def _partes(texto: str, manter: bool = False):
if manter:
frases = [f for f in re.split(r"(?<=[.?!])\s+", texto) if f.strip()]
else:
frases = list(_sentences(texto))
for sentence in frases:
for parte in _partir(sentence):
m = re.search(r"([?!.])\s*$", parte)
base = re.sub(r"[?!.,;:\s]+$", "", parte).strip()
if not base:
continue
yield base + (m.group(1) if (manter and m) else "")
def _gerar(ps: str, speed: float, lf: float | None, ef: float | None) -> np.ndarray:
atono = _final_atono(ps)
if lf is None:
lf = LAST_ATONO_FRAMES if atono else LAST_MAX_FRAMES
if ef is None:
ef = END_ATONO_FRAMES if atono else END_MAX_FRAMES
ref = tts.pack[len(ps) - 1].to(tts.device)
with torch.no_grad():
out = tts.km(ps, ref, float(speed), return_output=True)
audio = out.audio
a = audio.detach().cpu().numpy() if hasattr(audio, "detach") else np.asarray(audio)
a = a.astype(np.float32)
a = limitar_ultimo(a, getattr(out, "pred_dur", None), ps, lf, ef)
return cortar_fim(a)
def sintetizar(texto: str, speed: float = DEFAULT_SPEED, ipa: str | None = None,
last_frames: float | None = None, end_frames: float | None = None,
cortar_ms: int = 0, manter: bool = False) -> np.ndarray:
chunks = []
if ipa:
ps = _ipa_final(ipa)[:_MAX_PHONEMES]
if ps.strip():
chunks.append(_gerar(ps, speed, last_frames, end_frames))
else:
for parte in _partes(texto, manter):
ps = ph.phonemize_sentence(parte, "pt-PT")[:_MAX_PHONEMES]
if not ps.strip():
continue
ps = _ipa_final(ps)
if not ps.strip():
continue
chunks.append(_gerar(ps, speed, last_frames, end_frames))
if not chunks:
return np.zeros(0, dtype=np.float32)
audio = np.concatenate(chunks) if len(chunks) > 1 else chunks[0]
if cortar_ms and cortar_ms > 0:
n = int(cortar_ms / 1000 * SR)
if len(audio) > n + int(0.05 * SR):
audio = _fade_out(audio[:-n].copy(), 20)
return audio
=====================================================================
Normalizacao de texto (portugues de Portugal)
=====================================================================
LETRAS = dict(zip(
"abcdefghijklmnopqrstuvwxyz",
"á bê cê dê é éfe gê agá i jota cápa éle ême éne ó pê quê érre ésse tê u vê dâblio xis ípsilon zê".split()
))
DIGITOS = "zero um dois três quatro cinco seis sete oito nove".split()
UNIDADES = ("zero um dois três quatro cinco seis sete oito nove dez onze doze treze "
"catorze quinze dezasseis dezassete dezoito dezanove").split()
UNIDADES_F = list(UNIDADES)
UNIDADES_F[1], UNIDADES_F[2] = "uma", "duas"
DEZENAS = ["", "", "vinte", "trinta", "quarenta", "cinquenta", "sessenta", "setenta", "oitenta", "noventa"]
CENTENAS = ["", "cento", "duzentos", "trezentos", "quatrocentos", "quinhentos",
"seiscentos", "setecentos", "oitocentos", "novecentos"]
CENTENAS_F = ["", "cento", "duzentas", "trezentas", "quatrocentas", "quinhentas",
"seiscentas", "setecentas", "oitocentas", "novecentas"]
ORDINAIS = {
1: "primeiro", 2: "segundo", 3: "terceiro", 4: "quarto",
5: "quinto", 6: "sexto", 7: "sétimo", 8: "oitavo", 9: "nono",
10: "décimo", 11: "décimo primeiro", 12: "décimo segundo",
13: "décimo terceiro", 14: "décimo quarto", 15: "décimo quinto",
16: "décimo sexto", 17: "décimo sétimo", 18: "décimo oitavo",
19: "décimo nono", 20: "vigésimo",
}
MESES = "janeiro fevereiro março abril maio junho julho agosto setembro outubro novembro dezembro".split()
NAO_EXPANDIR = {"a", "e", "o", "à", "é", "ó"}
Siglas lidas como palavra
SIGLAS_PALAVRA = {
"NIF": "nífe",
"IBAN": "ibãne",
"NIB": "níbe",
"IVA": "iva",
"IMI": "imi",
"BIC": "bique",
}
Siglas soletradas
SIGLAS_LETRAS = {
"PT", "IRS", "IRC", "SNS", "CTT", "EDP", "PSP", "GNR", "ANPC",
"IHRU", "TV", "WC", "SWIFT", "RGPD",
}
SIGLAS_SOLETRADAS_ESPECIAIS = {
"WC": "vê cê",
}
Emprestimos ingleses e provedores com pronuncia ajustada ao contexto PT-PT
PALAVRAS_INGLESAS = {
"menu": "ménu",
"home": "hóume",
"email": "êmaile",
"e-mail": "êmaile",
"emails": "êmailes",
"gmail": "je maile",
"hotmail": "óte maile",
"website": "uebsaite",
"software": "softuer",
"hardware": "harduer",
"dashboard": "dáxebórde",
"feedback": "fidbeque",
"online": "onlain",
"login": "lóguine",
"logout": "lógaute",
"meeting": "mitingue",
"deadline": "dedlain",
"update": "apdeite",
"download": "daunlode",
"upload": "aploude",
"cloud": "claud",
"whatsapp": "uátzápe",
"wi-fi": "uai fai",
"wifi": "uai fai",
"app": "ápe",
"status": "zstátús",
"ticket": "tíquéte",
"info": "infó",
"backup": "bécápe",
}
Nomes proprios e termos de dominio
PALAVRAS = {
"ok": "ôquei",
"teste": "téste",
**PALAVRAS_INGLESAS,
}
Nomes femininos frequentes (para "duas frações", "uma reunião", ...)
NOMES_FEM = {
"fração", "frações", "fracção", "fracções", "assembleia", "assembleias", "reunião", "reuniões",
"quota", "quotas", "fatura", "faturas", "factura", "facturas", "hora", "horas", "semana", "semanas",
"página", "páginas", "casa", "casas", "conta", "contas", "proposta", "propostas", "obra", "obras",
"despesa", "despesas", "votação", "votações", "procuração", "procurações", "ata", "atas",
"pessoa", "pessoas", "vez", "vezes", "chamada", "chamadas", "mensagem", "mensagens",
"garagem", "garagens", "loja", "lojas", "escada", "escadas", "entrada", "entradas", "morada", "moradas",
"sala", "salas", "caixa", "caixas", "porta", "portas", "chave", "chaves", "avaria", "avarias",
"convocatória", "convocatórias", "ordem", "ordens", "parte", "partes", "comum", "comuns",
"reserva", "reservas", "notificação", "notificações", "cobrança", "cobranças",
}
TLDS = {"pt": "pê tê", "com": "com", "org": "org", "net": "net", "eu": "é u"}
SEP_FALADOS = {".": "ponto", "-": "hífen", "_": "sublinhado", "+": "mais", "/": "barra"}
Abreviaturas (padrao, expansao)
ABREVIATURAS = [
# tratamento
(r"\bSra.", "senhora"), (r"\bSr.", "senhor"),
(r"\bDra.", "doutora"), (r"\bDr.", "doutor"),
(r"\bExma.", "excelentíssima"), (r"\bExmo.", "excelentíssimo"),
(r"\bProfa.", "professora"), (r"\bProf.", "professor"),
(r"\bEng.ª", "engenheira"), (r"\bEng.", "engenheiro"),
# moradas e fracoes
(r"\bEsq.", "esquerdo"), (r"\b(?:Dto|Drt|Dt).", "direito"),
(r"(?i:\br/c\b)", "rés do chão"), (r"(?i:\bc/v\b)", "cave"),
(r"\bAv.", "avenida"), (r"\bR.(?=\s+[A-ZÀ-Ý])", "rua"),
(r"\bPç.", "praça"), (r"\bLg.", "largo"), (r"\bTv.", "travessa"),
(r"\bFr.(?=\s)", "fração"),
(r"\bBl.(?=\s)", "bloco"),
# juridico / empresas /
(r"\b[Aa]rts.[º°]?", "artigos"), (r"\b[Aa]rt.[º°]?", "artigo"),
(r"\bDec.-?\s?Lei\b", "decreto-lei"), (r"\bD.L.", "decreto-lei"),
(r"\bLda.?", "limitada"), (r"\bS.\s?A.", "sociedade anónima"),
(r"\bal.", "alínea"),
(r"\bref.ª", "referência"), (r"\bdoc.", "documento"),
(r"\bvenc.", "vencimento"),
# correntes
(r"\be/ou\b", "e ou"), (r"(?i:\bp.\s?f.)", "por favor"), (r"(?i:\bp.\s?ex.)", "por exemplo"),
(r"\betc.", "et cétera"),
(r"\bTel.", "telefone"), (r"\bTlf.", "telefone"), (r"\bTlm.", "telemóvel"),
(r"\b[Nn].º", "número"),
]
ABREVIATURAS = [(re.compile(p), r) for p, r in ABREVIATURAS]
UNIDADES_MEDIDA = [
(re.compile(r"(?<=\d)\sm²2"), " metros quadrados"),
(re.compile(r"(?<=\d)\sm³3"), " metros cúbicos"),
(re.compile(r"(?<=\d)\skm\b"), " quilómetros"),
(re.compile(r"(?<=\d)\skg\b"), " quilos"),
(re.compile(r"(?<=\d)\scm\b"), " centímetros"),
(re.compile(r"(?<=\d)\smm\b"), " milímetros"),
(re.compile(r"(?<=\d)\skW\b"), " quilowatts"),
(re.compile(r"(?<=\d)\sm\b"), " metros"),
]
---------- numeros por extenso ----------
def _ate_999(n: int, fem: bool) -> str:
if n == 0:
return ""
if n == 100:
return "cem"
c, r = divmod(n, 100)
un = UNIDADES_F if fem else UNIDADES
cen = CENTENAS_F if fem else CENTENAS
partes = []
if c:
partes.append(cen[c])
if r:
if r < 20:
partes.append(un[r])
else:
d, u = divmod(r, 10)
partes.append(DEZENAS[d] + (f" e {un[u]}" if u else ""))
return " e ".join(partes)
def _digitos(s: str) -> str:
return " ".join(DIGITOS[int(d)] for d in s if d.isdigit())
def _digitos_em_grupos(s: str, tam: int = 4) -> str:
digs = "".join(ch for ch in s if ch.isdigit())
grupos = [digs[i:i + tam] for i in range(0, len(digs), tam)]
return ", ".join(_digitos(g) for g in grupos if g)
def extenso(n: int, fem: bool = False) -> str:
if n == 0:
return "zero"
if n >= 109:
return _digitos(str(n))
milhoes, resto = divmod(n, 106)
milhares, unid = divmod(resto, 1000)
grupos = []
if milhoes:
grupos.append(("um milhão" if milhoes == 1 else f"{_ate_999(milhoes, False)} milhões", milhoes))
if milhares:
grupos.append(("mil" if milhares == 1 else f"{_ate_999(milhares, fem)} mil", milhares))
if unid:
grupos.append((_ate_999(unid, fem), unid))
texto = grupos[0][0]
for t, v in grupos[1:]:
texto += (" e " if (v < 100 or v % 100 == 0) else " ") + t
return texto
def _fem_palavras(s: str) -> str:
return " ".join(w[:-1] + "a" if w.endswith("o") else w for w in s.split())
---------- NIF, NIB e IBAN ----------
RE_NIF = re.compile(r"\bNIF\s*[:#-]?\s*(\d{9})\b", re.IGNORECASE)
RE_NIB = re.compile(r"\bNIB\s*[:#-]?\s*(\d[\d\s-]{18,26}\d)\b", re.IGNORECASE)
RE_IBAN_NUM = re.compile(r"\bIBAN\s*[:#-]?\s*([A-Z]{2}\d{2}[\s-]?[\dA-Z]{4}(?:[\s-]?[\dA-Z]{4}){3,5})\b", re.IGNORECASE)
RE_IBAN = re.compile(r"\b([A-Z]{2}\d{2}[\s-]?[\dA-Z]{4}(?:[\s-]?[\dA-Z]{4}){3,5})\b")
def _sub_nif(m):
return f"nífe, {_digitos(m.group(1))}"
def _sub_nib(m):
return f"níbe, {_digitos_em_grupos(m.group(1))}"
def _formatar_iban(valor: str) -> str:
raw = re.sub(r"[\s-]", "", valor).upper()
prefixo = " ".join(LETRAS.get(ch.lower(), ch) for ch in raw[:2])
check = _digitos(raw[2:4])
resto = ", ".join(_digitos(raw[i:i + 4]) for i in range(4, len(raw), 4))
return f"ibãne, {prefixo} {check}, {resto}"
def _sub_iban_num(m):
return _formatar_iban(m.group(1))
def _sub_iban(m):
return _formatar_iban(m.group(1))
---------- emails, sites ----------
def expandir_endereco(s: str, dominio: bool = False) -> str:
saida = []
for p in re.split(r"([.-+/])", s):
if not p:
continue
if p in SEP_FALADOS:
saida.append(SEP_FALADOS[p])
continue
t = p.lower()
if t == "www":
saida.append("dâblio dâblio dâblio")
elif dominio and t in TLDS:
saida.append(TLDS[t])
elif len(t) == 1 and t.isalpha():
saida.append(LETRAS.get(t, t))
else:
saida.append(re.sub(r"\d", lambda m: f" {DIGITOS[int(m.group())]} ", t).strip())
return " ".join(saida)
RE_EMAIL = re.compile(r"[\w.+-]+@[\w-]+(?:.[\w-]+)+")
RE_URL = re.compile(r"\b(?:https?://)?www.[\w-]+(?:.[\w-]+)+(?:/[^\s,;])?")
RE_DOMINIO = re.compile(r"\b[a-z0-9][\w-](?:.[\w-]+)*.(?:pt|com|org|net|eu)\b")
def _sub_email(m):
local, dom = m.group(0).split("@", 1)
return f"{_expandir_endereco(local)}, arrôba, {_expandir_endereco(dom, True)}"
def _sub_url(m):
return _expandir_endereco(re.sub(r"^https?://", "", m.group(0)), True)
def _sub_dominio(m):
return _expandir_endereco(m.group(0), True)
---------- listas numeradas ----------
RE_LISTA_LINHA = re.compile(r"^[ \t]*(\d{1,2})[.)][ \t]+(?=\S)", re.M)
RE_LISTA_INLINE = re.compile(r"(?<=[.:;?!] )(\d{1,2})[.)]\s+(?=[A-ZÀ-Ý])")
RE_LISTA_2 = re.compile(r"(?:^|(?<=[.:;?!] ))2[.)]\s+[A-ZÀ-Ý]", re.M)
def _sub_lista(m):
n = int(m.group(1))
return (ORDINAIS.get(n) or extenso(n)) + ", "
---------- horas, datas, dinheiro, telefone ----------
RE_HORA = re.compile(r"(?:(?<!\w)(?P[àÀ]s?)\s+)?(?<![\d:.,])(?P\d{1,2}):(?P\d{2})(?![\d:])")
RE_HORA_H = re.compile(r"(?:(?<!\w)(?P[àÀ]s?)\s+)?(?<![\d:.,])(?P\d{1,2})h(?P\d{2})?\b")
def _sub_hora(m):
h = int(m.group("h"))
mi = int(m.group("m")) if m.group("m") else 0
if h > 24 or mi > 59:
return m.group(0)
prep = m.group("prep")
base = extenso(h, bool(prep) and h in (1, 2))
if mi == 0:
txt = f"{base} {'hora' if h == 1 else 'horas'}"
elif mi == 30:
txt = f"{base} e meia"
else:
txt = f"{base} e {extenso(mi)}"
return (prep + " " if prep else "") + txt
RE_DATA = re.compile(r"\b(\d{1,2})/.-/.-\b")
RE_DATA_CURTA = re.compile(r"(?<![/\d])(\d{1,2})/(\d{1,2})(?![/\d])")
def _sub_data(m):
d, mes = int(m.group(1)), int(m.group(2))
if not (1 <= d <= 31 and 1 <= mes <= 12):
return m.group(0)
dia = "primeiro" if d == 1 else str(d)
return f"{dia} de {MESES[mes - 1]} de {m.group(3)}"
def _sub_data_curta(m):
d, mes = int(m.group(1)), int(m.group(2))
if not (1 <= d <= 31 and 1 <= mes <= 12):
return m.group(0)
return f"{'primeiro' if d == 1 else d} de {MESES[mes - 1]}"
def _dinheiro(inteiro: str, dec: str | None) -> str:
inteiro_limpo = inteiro.replace(".", "")
i = int(inteiro_limpo)
c = int((dec or "0").ljust(2, "0"))
partes = []
if i or not c:
if i == 1:
moeda = "euro"
elif i >= 106 and i % 106 == 0:
moeda = "de euros"
else:
moeda = "euros"
partes.append(f"{extenso(i)} {moeda}")
if c:
partes.append(f"{extenso(c)} {'cêntimo' if c == 1 else 'cêntimos'}")
return " e ".join(partes)
RE_EURO_SUF = re.compile(r"(?<![\w,])(\d{1,3}(?:.\d{3})|\d+)(?:,(\d{1,2}))?\s(?:€|euros?\b)")
RE_EURO_PRE = re.compile(r"€\s*(\d{1,3}(?:.\d{3})*|\d+)(?:,(\d{1,2}))?(?!\d)")
RE_TEL = re.compile(
r"(?<!\d)(?:(?P(?:+|00)351)[\s.-]?)?(?P\d{3})[\s.-]?(?P\d{3})[\s.-]?(?P\d{3})(?!\d)")
RE_POSTAL = re.compile(r"(?<!\d)(\d{4})-(\d{3})(?!\d)")
def _sub_tel(m):
pref = "mais trezentos e cinquenta e um, " if m.group("pref") else ""
return f"{pref}{_digitos(m.group('a'))}, {_digitos(m.group('b'))}, {_digitos(m.group('c'))}"
def _sub_ordinal(m):
n, fem = int(m.group(1)), m.group(2) == "ª"
palavra = ORDINAIS.get(n)
if palavra is None:
return extenso(n, fem)
return _fem_palavras(palavra) if fem else palavra
def _sub_decimal(m):
inteiro, dec = m.group(1).replace(".", ""), m.group(2)
if dec[0] == "0" or len(dec) > 2:
d = _digitos(dec)
else:
d = extenso(int(dec))
return f"{extenso(int(inteiro))} vírgula {d}"
def _sub_inteiro(m):
s = m.group(0)
if len(s) > 1 and s[0] == "0":
return digitos(s)
prox = re.match(r"\s+([^\W\d]+)", m.string[m.end():])
fem = bool(prox and prox.group(1).lower() in NOMES_FEM)
return extenso(int(s), fem)
def preparar(texto: str, manter: bool = False) -> str:
# 1. NIF, NIB, IBAN, emails, sites e dominios
texto = RE_NIF.sub(_sub_nif, texto)
texto = RE_NIB.sub(_sub_nib, texto)
texto = RE_IBAN_NUM.sub(_sub_iban_num, texto)
texto = RE_IBAN.sub(_sub_iban, texto)
texto = RE_EMAIL.sub(_sub_email, texto)
texto = RE_URL.sub(_sub_url, texto)
texto = RE_DOMINIO.sub(_sub_dominio, texto)
# 2. OK -> oquei; siglas; abreviaturas; pronuncias a medida e inglesas
texto = re.sub(r"\b(?:OK|Ok|ok)\b", "ôquei", texto)
texto = re.sub(r"\bcódigo\s+qr\b", "código quê érre", texto, flags=re.IGNORECASE)
texto = re.sub(r"\bqr\s+code\b", "quê érre code", texto, flags=re.IGNORECASE)
for sigla, expansao in SIGLAS_PALAVRA.items():
texto = re.sub(rf"\b{sigla}\b", expansao, texto)
for sigla in SIGLAS_LETRAS:
soletrada = SIGLAS_SOLETRADAS_ESPECIAIS.get(sigla) or " ".join(LETRAS[c.lower()] for c in sigla)
texto = re.sub(rf"\b{sigla}\b", soletrada, texto)
for padrao, repl in ABREVIATURAS:
texto = padrao.sub(repl, texto)
for k, v in PALAVRAS.items():
texto = re.sub(rf"(?<![\w-]){re.escape(k)}(?![\w-])", v, texto, flags=re.IGNORECASE)
# 3a. Listas numeradas, "#1" e marcadores de lista
texto = RE_LISTA_LINHA.sub(_sub_lista, texto)
if RE_LISTA_2.search(texto):
texto = RE_LISTA_INLINE.sub(_sub_lista, texto)
texto = re.sub(r"#\s?(\d+)", r"número \1", texto)
texto = re.sub(r"(?m)^[ \t]*[-•*][ \t]+", "", texto)
# 3b. Limpeza de texto vindo de LLM
texto = re.sub(r"[\U0001F000-\U0001FAFF\u2600-\u27BF\uFE0F]", "", texto)
texto = re.sub(r"[*`#~|<>\[\]{}]", "", texto)
texto = texto.replace("…", ",").replace("...", ",")
texto = re.sub(r"\s*[—–]\s*|\s+-\s+", ", ", texto)
texto = re.sub(r"[()]", ", ", texto)
texto = re.sub(r"[“”\"«»]", "", texto)
texto = texto.replace("&", " e ")
texto = re.sub(r"(?<=[^\W\d_])/(?=[^\W\d_])", " ", texto)
texto = re.sub(r"\s*\n+\s*", ". ", texto)
texto = re.sub(r"([.?!,;:])(\s*\.)+", r"\1", texto)
# 4. Letras em contexto: "Fração A", "Bloco B", "Lote E"...
texto = re.sub(
r"\b([Ff]ração|[Ff]racção|[Ll]etra|[Bb]loco|[Ll]ote|[Ee]ntrada|[Ee]scada)\s+([A-Z])(?=\b|[,.;:?!])",
lambda m: f"{m.group(1)} {LETRAS[m.group(2).lower()]}",
texto,
)
texto = re.sub(r"\bletra\s+([a-z])\b", lambda m: f"letra {LETRAS[m.group(1)]}", texto)
# 5. Maiuscula isolada -> nome da letra
texto = re.sub(
r"\b([A-Z])\b",
lambda m: m.group(1) if m.group(1).lower() in NAO_EXPANDIR
else LETRAS.get(m.group(1).lower(), m.group(1)),
texto,
)
# 6. Datas completas, ordinais, ponto de milhar
texto = RE_DATA.sub(_sub_data, texto)
texto = re.sub(
r"\b(\d+)\.?([ºª°])",
lambda m: _sub_ordinal(re.match(r"(\d+)\.?([ºª])", m.group(0).replace("°", "º"))),
texto,
)
texto = re.sub(r"\b\d{1,3}(?:\.\d{3})+\b", lambda m: m.group(0).replace(".", ""), texto)
# 7. Codigo postal, telefone
texto = RE_POSTAL.sub(lambda m: f"{_digitos(m.group(1))}, {_digitos(m.group(2))}", texto)
texto = RE_TEL.sub(_sub_tel, texto)
# 8. Horas, data curta
texto = RE_HORA.sub(_sub_hora, texto)
texto = RE_HORA_H.sub(_sub_hora, texto)
texto = RE_DATA_CURTA.sub(_sub_data_curta, texto)
# 9. Dinheiro, percentagem, unidades
texto = re.sub(r"\s*/\s*mês\b", " por mês", texto)
texto = re.sub(r"\s*/\s*ano\b", " por ano", texto)
texto = RE_EURO_SUF.sub(lambda m: _dinheiro(m.group(1), m.group(2)), texto)
texto = RE_EURO_PRE.sub(lambda m: _dinheiro(m.group(1), m.group(2)), texto)
texto = re.sub(r"(\d+(?:,\d+)?)\s*%", r"\1 por cento", texto)
for padrao, repl in UNIDADES_MEDIDA:
texto = padrao.sub(repl, texto)
# 10. Decimais e inteiros restantes -> extenso (PT-PT)
texto = re.sub(r"(?<![\d,])(\d+),(\d+)(?![\d,])", _sub_decimal, texto)
texto = re.sub(r"\b\d+\b", _sub_inteiro, texto)
# 11. Limpeza final
texto = re.sub(r"(\s*,){2,}", ",", texto)
texto = re.sub(r"\s+([,.;:?!])", r"\1", texto)
texto = re.sub(r"\s{2,}", " ", texto)
fim = re.search(r"([?!.])[\s]*$", texto)
texto = re.sub(r"[\s?!.,;:…]+$", "", texto).strip()
if manter and fim and texto:
texto += fim.group(1)
return texto
--- aquecimento ---
for t in [
"Olá.",
"Bem-vindo à minha empresa. São dezasseis horas e trinta minutos.",
"Um momento, por favor. A fração B tem uma quota de 12 euros.",
]:
for _ in range(2):
sintetizar(preparar(t))
sintetizar(preparar("A reunião é às 16:40?", True), manter=True)
--- app ---
app = FastAPI()
lock = threading.Lock()
def _manter(valor: str | None) -> bool:
return (valor or PONTUACAO_DEFAULT) == "manter"
class Req(BaseModel):
model: str | None = None
input: str = ""
voice: str | None = None
response_format: str = "wav"
speed: float | None = None
pontuacao: str | None = None
ipa: str | None = None
last_frames: float | None = None
end_frames: float | None = None
cortar_ms: int = 0
class NormReq(BaseModel):
input: str
pontuacao: str | None = None
@app .get("/health")
def health():
return {"ok": True, "cuda": torch.cuda.is_available()}
@app .post("/v1/normalize")
def normalize(r: NormReq):
return {"input": r.input, "texto": preparar(r.input, _manter(r.pontuacao))}
@app .post("/v1/fonemas")
def fonemas(r: NormReq):
manter = _manter(r.pontuacao)
texto = preparar(r.input, manter)
partes = []
with lock:
for parte in _partes(texto, manter):
bruto = ph.phonemize_sentence(parte, "pt-PT")[:_MAX_PHONEMES]
final = _ipa_final(bruto)
partes.append({
"parte": parte,
"ipa_bruto": bruto,
"ipa_final": final,
"fim_atono": _final_atono(final),
})
return {"texto": texto, "pontuacao": "manter" if manter else "remover", "partes": partes}
@app .post("/v1/audio/speech")
def speech(r: Req):
manter = _manter(r.pontuacao)
texto = f"ipa:{r.ipa}" if r.ipa else preparar(r.input, manter)
t0 = time.perf_counter()
speed = r.speed if r.speed is not None else DEFAULT_SPEED
speed = max(0.8, min(speed, 1.15))
with lock:
audio = sintetizar(
texto,
speed=speed,
ipa=r.ipa,
last_frames=r.last_frames,
end_frames=r.end_frames,
cortar_ms=r.cortar_ms,
manter=manter,
)
dt = time.perf_counter() - t0
dur = max(len(audio) / SR, 1e-6)
print(f"{dt:.3f}s | audio {dur:.1f}s | RTF {dt/dur:.3f} | speed={speed} | "
f"pont={'manter' if manter else 'remover'} | texto={texto!r}", flush=True)
pcm = (np.clip(audio, -1, 1) * 32767).astype("<i2").tobytes()
if (r.response_format or "wav").lower() == "pcm":
return Response(pcm, media_type="audio/pcm")
buf = io.BytesIO()
with wave.open(buf, "wb") as w:
w.setnchannels(1)
w.setsampwidth(2)
w.setframerate(SR)
w.writeframes(pcm)
return Response(buf.getvalue(), media_type="audio/wav")