diff --git a/src/valeria/renderer.py b/src/valeria/renderer.py index 6c2b6a4..f30d5be 100644 --- a/src/valeria/renderer.py +++ b/src/valeria/renderer.py @@ -288,7 +288,9 @@ def _renderizar_visual( ) for i, png in enumerate(paginas_png): - w_emu, h_emu = _calcular_dims_emu(png, content_w_emu, content_h_emu) + w_emu, h_emu = _preparar_imagen_visual( + png, content_w_emu, content_h_emu + ) para = doc.add_paragraph() pf = para.paragraph_format # Padding cero arriba y abajo para que la imagen pegue al tope @@ -326,39 +328,68 @@ def _renderizar_visual( return destino -def _calcular_dims_emu( +def _preparar_imagen_visual( png_path: Path, area_w_emu: int, area_h_emu: int, ) -> tuple[int, int]: """ - Calcula (width_emu, height_emu) para que la imagen ocupe la mayor - superficie posible del área, preservando aspect ratio. + Garantiza que la imagen llene SIEMPRE todo el alto del área, + preservando aspect ratio. Devuelve (width_emu, height_emu) para + pasar a `add_picture`. - Estrategia height-first: - 1. Llena el alto (h = area_h_emu). - 2. Calcula el ancho proporcional usando los píxeles del PNG. - 3. Si el ancho resultante excede el área, cae a width-first - (caso de inputs en landscape). + Casos según la proporción del PNG vs la del área: - Trabaja con enteros EMU para que el valor que termine en el XML - coincida exactamente con el área de contenido y no haya redondeo - cm→EMU acumulado. + - PNG igual o más estrecho que el área (aspect ≤ area_aspect): + alto = area_h_emu (completo) + ancho = proporcional (queda menor que area_w_emu) + El centrado horizontal del párrafo cubre el sobrante. + + - PNG más ancho que el área (aspect > area_aspect): + el PNG se RECORTA en sitio (Pillow) cortando los lados de + forma simétrica hasta que su aspect coincida con el del área. + alto = area_h_emu, ancho = area_w_emu (calza exacto). + + El recorte muta el PNG en disco. Es seguro porque los PNGs viven + en /tmp/valeria//pngs-* y se borran al final del + procesamiento. La operación es idempotente: si ya está recortado al + aspect del área, una segunda llamada no hace nada. """ from PIL import Image + with Image.open(str(png_path)) as im: iw, ih = im.size if iw <= 0 or ih <= 0: return area_w_emu, area_h_emu - # Height-first: alto = todo el área, ancho proporcional. - h_emu = area_h_emu - w_emu = (area_h_emu * iw) // ih - if w_emu > area_w_emu: - # Landscape → cap por ancho. - w_emu = area_w_emu - h_emu = (area_w_emu * ih) // iw - return w_emu, h_emu + area_aspect = area_w_emu / area_h_emu # ancho / alto + img_aspect = iw / ih + + if img_aspect <= area_aspect: + # Cabe sin recortar. Alto al máximo, ancho proporcional. + h_emu = area_h_emu + w_emu = (area_h_emu * iw) // ih + return w_emu, h_emu + + # Imagen demasiado ancha → recortar los lados (crop centrado) hasta + # que la proporción coincida con la del área. + new_iw = int(ih * area_aspect) + if new_iw <= 0 or new_iw >= iw: + # Salvavidas; no debería pasar bajo las condiciones de arriba. + return area_w_emu, area_h_emu + left = (iw - new_iw) // 2 + right = left + new_iw + with Image.open(str(png_path)) as im: + recortada = im.crop((left, 0, right, ih)) + recortada.save(str(png_path), "PNG") + log.info( + "renderer.visual.recortado", + png=str(png_path), + pixels_original=f"{iw}x{ih}", + pixels_recortado=f"{new_iw}x{ih}", + recortado_lados_px=iw - new_iw, + ) + return area_w_emu, area_h_emu def _renderizar( diff --git a/tests/test_visual_dims.py b/tests/test_visual_dims.py new file mode 100644 index 0000000..6c04514 --- /dev/null +++ b/tests/test_visual_dims.py @@ -0,0 +1,107 @@ +"""Tests del cálculo y crop de la imagen para modo visual.""" +from pathlib import Path + +import pytest + +from valeria.renderer import _preparar_imagen_visual + +# Área de contenido carta: 17.59 x 18.94 cm +AREA_W_EMU = 17_590_000 * 36 // 10 # ≈ 6_332_400 +AREA_H_EMU = 18_940_000 * 36 // 10 # ≈ 6_818_400 +# Recalculo exacto: +EMU_POR_CM = 360000 +AREA_W_EMU = int(17.59 * EMU_POR_CM) # 6_332_400 +AREA_H_EMU = int(18.94 * EMU_POR_CM) # 6_818_400 +AREA_ASPECT = AREA_W_EMU / AREA_H_EMU # ≈ 0.929 + + +def _png(tmp_path: Path, w: int, h: int, color: str = "red") -> Path: + """Genera un PNG sólido del tamaño dado.""" + from PIL import Image + p = tmp_path / f"{w}x{h}.png" + im = Image.new("RGB", (w, h), color) + im.save(str(p), "PNG") + return p + + +def test_portrait_no_recorta_y_llena_alto(tmp_path: Path): + """PNG portrait (1275x1650, aspect 0.77) cabe → alto al máximo, + ancho proporcional menor que el área.""" + p = _png(tmp_path, 1275, 1650) + w_emu, h_emu = _preparar_imagen_visual(p, AREA_W_EMU, AREA_H_EMU) + + # Alto: lleno + assert h_emu == AREA_H_EMU + # Ancho: proporcional, menor que el área + assert w_emu < AREA_W_EMU + esperado_w = (AREA_H_EMU * 1275) // 1650 + assert w_emu == esperado_w + # PNG no debe haberse modificado en píxeles + from PIL import Image + with Image.open(str(p)) as im: + assert im.size == (1275, 1650) + + +def test_cuadrado_recorta_y_llena_ambos(tmp_path: Path): + """PNG 1:1 es más ancho (en proporción) que el área 0.93 → recorta.""" + p = _png(tmp_path, 1500, 1500) + w_emu, h_emu = _preparar_imagen_visual(p, AREA_W_EMU, AREA_H_EMU) + + # Después del recorte calza el área entera + assert h_emu == AREA_H_EMU + assert w_emu == AREA_W_EMU + # PNG en disco fue recortado a la proporción del área + from PIL import Image + with Image.open(str(p)) as im: + new_iw, new_ih = im.size + assert new_ih == 1500 # alto intacto + esperado_iw = int(1500 * AREA_ASPECT) + assert new_iw == esperado_iw + assert new_iw < 1500 + + +def test_landscape_recorta_fuerte(tmp_path: Path): + """PNG 16:9 (aspect 1.78) muy ancho → recorta agresivo.""" + p = _png(tmp_path, 1600, 900) + w_emu, h_emu = _preparar_imagen_visual(p, AREA_W_EMU, AREA_H_EMU) + assert h_emu == AREA_H_EMU + assert w_emu == AREA_W_EMU + from PIL import Image + with Image.open(str(p)) as im: + new_iw, _ = im.size + esperado = int(900 * AREA_ASPECT) # ~836 + assert new_iw == esperado + assert new_iw < 1600 + + +def test_idempotente_segunda_llamada_no_recorta(tmp_path: Path): + """Una imagen ya recortada no debe mutarse en sitio una segunda vez.""" + p = _png(tmp_path, 1500, 1500) + _preparar_imagen_visual(p, AREA_W_EMU, AREA_H_EMU) + from PIL import Image + with Image.open(str(p)) as im: + size_post_1 = im.size + + w_emu, h_emu = _preparar_imagen_visual(p, AREA_W_EMU, AREA_H_EMU) + # El alto sigue lleno; el ancho puede quedar 1-2 EMU por debajo de + # AREA_W_EMU por floor() en el crop original. Lo importante: el + # archivo no se vuelve a tocar. + assert h_emu == AREA_H_EMU + assert abs(w_emu - AREA_W_EMU) < AREA_W_EMU // 100 # < 1% + with Image.open(str(p)) as im: + size_post_2 = im.size + assert size_post_2 == size_post_1 + + +def test_exactamente_aspect_del_area_no_recorta(tmp_path: Path): + """Si el PNG ya tiene exactamente el aspect del área, no se toca.""" + # Construyo un PNG con exactamente el aspect del área + ih = 1000 + iw = int(ih * AREA_ASPECT) + p = _png(tmp_path, iw, ih) + w_emu, h_emu = _preparar_imagen_visual(p, AREA_W_EMU, AREA_H_EMU) + assert h_emu == AREA_H_EMU + # w_emu puede ser ≤ AREA_W_EMU según camino tomado + from PIL import Image + with Image.open(str(p)) as im: + assert im.size == (iw, ih)