Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,9 @@ Todos los cambios importantes de ModpackES quedan en este archivo. El formato si

### Cambiado

- **Frases partidas con su contexto:**
- Un texto con estilos mezclados («Use the » + «Wrench» en dorado + « to rotate») se sigue traduciendo por trozos, para no perder los estilos, pero cada trozo va con la frase entera, para que encaje en ella. Vale para las misiones (FTB Quests, Heracles) y los libros.
- Una línea de una misión o de un libro que no cierra su frase («Right-click the block with») va con el comienzo de la siguiente, además de la anterior y el título que ya llevaba.
- **Libros más fieles al original:** el pedido de libros ya no dice «Escribe de forma clara y natural». Esa frase empujaba al modelo a reescribir en vez de traducir: sin ella, el chrF del banco de libros subió 1,45 (IC 0,80 a 2,12). Vale para todos los libros guía, en JSON o en archivos de idioma.
- **La memoria distingue cada modpack y recuerda lo dudoso:**
- Cada traducción se guarda con su modpack y con su calidad: «ok», o el motivo por el que se aceptó con dudas.
Expand Down
33 changes: 31 additions & 2 deletions src/traductor_es/modulos/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,24 @@ def unidades(texto: str, literal: bool = False) -> list[str]:
return [p for p in candidatos if es_traducible(p) and not parece_clave(p)]


#: Hasta cuántos caracteres de la frase entera de un componente JSON van en la pista de cada trozo.
LARGO_FRASE = 160


def piezas_de(texto: str, pista: str, literal: bool = False) -> list[Pieza]:
"""Las piezas traducibles de un texto, con su pista. Un componente JSON con varios trozos de estilo distinto
(«Use the », «Wrench» en dorado, « to rotate») se traduce por trozos para no perder los estilos; cada uno lleva la
frase entera como contexto, para que encaje en ella."""
partes = unidades(texto, literal)
trozos = json_texto.extraer(texto, literal) or []
if len(partes) < 2 or len(trozos) < 2:
return [Pieza(u, pista) for u in partes]
frase = " ".join("".join(trozos).split())

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Exclude hover text from the visible phrase context

When a component has multiple visible text segments and a hoverEvent.show_text, json_texto.extraer also returns the tooltip text, so this concatenation treats it as part of the visible phrase (for example, combining a label with its tooltip). That unrelated phrase is then added as context to each chunk and can mislead their translations; build the context from the same rendered text run or keep hover text separate.

Useful? React with 👍 / 👎.

frase = frase if len(frase) <= LARGO_FRASE else frase[: LARGO_FRASE - 1] + "…"
extra = f"trozo de la frase «{frase}»"
return [Pieza(u, f"{pista} · {extra}" if pista else extra) for u in partes]

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Keep styled titles identifiable as titles

When an FTB Quests title or book name/title is a multi-part JSON component, this suffix means the hint no longer ends with title or exactly equals libro: title. The title predicates then fail, so con_vecindad does not establish the right title context for following text and may carry over the previous title instead. Preserve the title-field identity separately from the component-context hint.

Useful? React with 👍 / 👎.



def aplicar(texto: str, traducciones: Mapping[str, str], literal: bool = False) -> str:
if not texto.strip() or parece_clave(texto):
return texto
Expand Down Expand Up @@ -103,7 +121,9 @@ def restaurar(self) -> list[Path]: ...

#: Cuántos caracteres de un texto vecino o de un título se mandan como contexto.
LARGO_VECINO = 100
MARCAS_VECINDAD = ("dentro de «", "viene después de «")
MARCAS_VECINDAD = ("dentro de «", "viene después de «", "sigue con «")
#: Una línea que termina así cierra su frase; si no, la frase sigue en la línea siguiente.
_FIN_DE_FRASE = (".", "!", "?", ":", "…", '"', "»", ")", "]")


def _recortar(texto: str) -> str:
Expand All @@ -119,7 +139,7 @@ def con_vecindad(piezas: Sequence[Pieza], es_titulo: Callable[[Pieza], bool]) ->
"""
titulo = anterior = ""
salida: list[Pieza] = []
for p in piezas:
for i, p in enumerate(piezas):
if es_titulo(p):
titulo, anterior = _recortar(p.texto), ""
salida.append(p)
Expand All @@ -129,11 +149,20 @@ def con_vecindad(piezas: Sequence[Pieza], es_titulo: Callable[[Pieza], bool]) ->
partes.append(f"dentro de «{titulo}»")
if anterior:
partes.append(f"viene después de «{anterior}»")
# Una línea que no cierra su frase («Right-click the block») sigue en la siguiente: se manda su comienzo
siguiente = piezas[i + 1] if i + 1 < len(piezas) else None
if siguiente is not None and not es_titulo(siguiente) and not _cierra_frase(p.texto):
partes.append(f"sigue con «{_recortar(siguiente.texto)}»")
salida.append(Pieza(p.texto, " · ".join(partes), p.ambito))
anterior = _recortar(p.texto)
return salida


def _cierra_frase(texto: str) -> bool:
limpio = re.sub(r"(?:[§&][0-9a-fk-or]|\$\([^)]*\))+$", "", texto.strip(), flags=re.I).rstrip()
return not limpio or limpio.endswith(_FIN_DE_FRASE)


def quitar_vecindad(pista: str) -> str:
"""La pista sin lo que agrega `con_vecindad` (para medir cuánto aporta)."""
return " · ".join(parte for parte in pista.split(" · ") if not parte.startswith(MARCAS_VECINDAD))
Expand Down
4 changes: 2 additions & 2 deletions src/traductor_es/modulos/libros.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
from ..fuentes.contenedores import Carpeta
from ..fuentes.recursos import Fuente
from ..nucleo.mascara import es_traducible
from .base import Contexto, Pieza, Resumen, aplicar, con_vecindad, parece_clave, unidades
from .base import Contexto, Pieza, Resumen, aplicar, con_vecindad, parece_clave, piezas_de
from .cambios import Lugar

AMBITO = "libro"
Expand Down Expand Up @@ -208,7 +208,7 @@ def _preparar_json(self, a: _Archivo, texto: str, campos: frozenset[str]) -> Non
if c.campo in campos and not c.texto.strip().startswith("#") and not parece_clave(c.texto)
]
a.piezas = con_vecindad(
[Pieza(u, f"libro: {c.campo}") for c in elegidas for u in unidades(c.texto)],
[p for c in elegidas for p in piezas_de(c.texto, f"libro: {c.campo}")],
lambda p: p.pista in ("libro: name", "libro: title"),
)

Expand Down
10 changes: 4 additions & 6 deletions src/traductor_es/modulos/misiones.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
from pathlib import Path

from ..formatos import json_cadenas, nbt, snbt
from .base import Contexto, Pieza, Resumen, aplicar, con_vecindad, contar, unidades
from .base import Contexto, Pieza, Resumen, aplicar, con_vecindad, contar, piezas_de, unidades
from .cambios import Lugar

AMBITO = "mision"
Expand Down Expand Up @@ -167,7 +167,7 @@ def _trabajo_snbt(
) -> _Trabajo:
cadenas = [c for c in snbt.escanear(src) if filtro(c)]
piezas = con_vecindad(
[Pieza(u, f"misión: {c.campo}") for c in cadenas if c.inicio not in fijos for u in unidades(c.texto)],
[p for c in cadenas if c.inicio not in fijos for p in piezas_de(c.texto, f"misión: {c.campo}")],
_es_titulo,
)

Expand Down Expand Up @@ -244,9 +244,7 @@ def _nbt(self, raiz: Path) -> Iterator[_Trabajo]:
textos = [c for c in nbt.cadenas(arbol) if c.campo in CAMPOS_FTBQ]
if not textos:
continue
piezas = con_vecindad(
[Pieza(u, f"misión: {c.campo}") for c in textos for u in unidades(c.texto)], _es_titulo
)
piezas = con_vecindad([p for c in textos for p in piezas_de(c.texto, f"misión: {c.campo}")], _es_titulo)

def generar(
trad: Mapping[str, str], original: bytes = original, compresion: nbt.Compresion = compresion
Expand Down Expand Up @@ -311,7 +309,7 @@ def _preparar(self) -> Iterator[_Trabajo]:
elegidas = [(c, lit) for c in cadenas for ok, lit in [self._es_texto(c)] if ok]
if not elegidas:
continue
piezas = [Pieza(u, f"misión: {c.campo}") for c, lit in elegidas for u in unidades(c.texto, lit)]
piezas = [p for c, lit in elegidas for p in piezas_de(c.texto, f"misión: {c.campo}", lit)]
bom = original.startswith(b"\xef\xbb\xbf")

def generar(
Expand Down
32 changes: 32 additions & 0 deletions tests/test_contexto_de_trozos.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
"""Trozos de un componente JSON con su frase entera, y líneas que siguen en la siguiente con su continuación."""

from __future__ import annotations

from traductor_es.modulos.base import Pieza, con_vecindad, piezas_de, quitar_vecindad

_COMPONENTE = '["", {"text": "Use the "}, {"text": "Wrench", "color": "gold"}, {"text": " to rotate blocks."}]'


def test_cada_trozo_lleva_la_frase_entera() -> None:
piezas = piezas_de(_COMPONENTE, "misión: description")
assert [p.texto for p in piezas] == ["Use the ", "Wrench", " to rotate blocks."]
assert all(p.pista == "misión: description · trozo de la frase «Use the Wrench to rotate blocks.»" for p in piezas)


def test_un_texto_normal_o_un_componente_de_un_trozo_no_cambia() -> None:
assert piezas_de("Craft a Wrench", "misión: title") == [Pieza("Craft a Wrench", "misión: title")]
assert piezas_de('{"text": "Hola"}', "x") == [Pieza("Hola", "x")]


def test_una_linea_que_no_cierra_su_frase_lleva_la_siguiente() -> None:
piezas = [
Pieza("The Basics", "misión: title"),
Pieza("Right-click the block with", "misión: description"),
Pieza("the &6Wrench&r to rotate it.", "misión: description"),
Pieza("Then sneak.", "misión: description"),
]
salida = con_vecindad(piezas, lambda p: p.pista.endswith("title"))
assert "sigue con «the &6Wrench&r to rotate it.»" in salida[1].pista
assert "sigue con" not in salida[2].pista # termina en punto: la frase cierra ahí
assert "sigue con" not in salida[3].pista # es la última
assert quitar_vecindad(salida[1].pista) == "misión: description"
Loading