"""img2pptx.py: turn slide pictures (PNG, JPG or a PDF of pictures) into a PowerPoint file with editable text.

Each slide keeps its picture as the background, with the text painted out, and gets one text box
per paragraph that Tesseract finds (table cells and labels side by side get their own boxes),
in the same place, size and color. Fonts are not matched (every box is Arial) and bold is not found.

  python3 img2pptx.py slides.pdf deck.pptx
  python3 img2pptx.py slide1.png slide2.jpg deck.pptx

Needs Python 3.10+, Tesseract 5 on the PATH, and: pip install python-pptx opencv-python-headless pypdfium2
MIT License. Copyright (c) 2026 Brasspage. https://brasspage.com/image-to-editable-ppt/
"""

import csv
import io
import itertools
import subprocess
import sys
from pathlib import Path

import cv2
import numpy as np
import pypdfium2 as pdfium
from PIL import Image
from pptx import Presentation
from pptx.dml.color import RGBColor
from pptx.util import Emu, Pt

LANG = "eng"
MIN_H = 1400  # Tesseract reads small slide text better when the picture is at least this tall
# Arial: capitals and b, d, h, k, l, t reach about 0.72 of the font size, g, j, p, q, y go 0.21 below the line
ASC = set("bdfhklt0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'\"!?()[]/%&$#@")
DESC = set("gjpqy(),;[]Q")
BULLETS = set("e\u00a2\u00ab\u00b0*+-\u2022\u00a9\u00ae\u00bb")


def pictures(paths):
    for p in paths:
        if p.suffix.lower() == ".pdf":
            for page in pdfium.PdfDocument(str(p)):
                yield page.render(scale=2).to_pil().convert("RGB")
        else:
            yield Image.open(p).convert("RGB")


def words(img):
    scale = max(1, -(-MIN_H // img.height))  # ceil: 720 px tall -> 2x
    big = (
        img.resize((img.width * scale, img.height * scale), Image.LANCZOS)
        if scale > 1
        else img
    )
    buf = io.BytesIO()
    big.save(buf, "PNG")
    tsv = subprocess.run(
        ["tesseract", "stdin", "stdout", "-l", LANG, "--psm", "3", "tsv"],
        input=buf.getvalue(),
        capture_output=True,
        check=True,
    ).stdout.decode("utf-8")
    out = []
    for r in csv.DictReader(io.StringIO(tsv), delimiter="\t", quoting=csv.QUOTE_NONE):
        conf = float(r["conf"])
        if r["level"] == "5" and r["text"].strip() and conf >= 0:
            box = [int(r[k]) // scale for k in ("left", "top", "width", "height")]
            key = tuple(int(r[k]) for k in ("block_num", "par_num", "line_num"))
            out.append((key, r["text"], conf, box))
    return out


def ink(px, box):
    """The letters: pixels of a word box, plus a margin (Tesseract's boxes can be short), that differ from its border color."""
    x, y, w, h = box
    m = max(2, h // 4)
    x0, y0 = max(0, x - m), max(0, y - m)
    cut = px[y0 : y + h + m, x0 : x + w + m].astype(int)
    edge = np.concatenate([cut[0], cut[-1], cut[:, 0], cut[:, -1]])
    bg = np.median(edge, axis=0)
    return (x0, y0), np.abs(cut - bg).sum(axis=2) > 90


def chunks(row):
    """Split a line where the gap is wider than 1.5 line heights: table cells, labels side by side."""
    h = max(w[1][3] for w in row)
    out = [[row[0]]]
    for prev, w in itertools.pairwise(row):
        if w[1][0] - (prev[1][0] + prev[1][2]) > 1.5 * h:
            out.append([])
        out[-1].append(w)
    return out


def em(row):
    """Font size in pixels: each word's ink height over the share of the font it fills, median of the line."""
    sizes = [
        w[1][3]
        / ((0.72 if ASC & set(w[0]) else 0.52) + (0.21 if DESC & set(w[0]) else 0))
        for w in row
        if w[0] != "\u2022"
    ]
    return float(np.median(sizes or [row[0][1][3] / 0.52]))


def picture(arr):
    """The smaller of PNG and JPEG: PNG for flat slides, JPEG for photos and JPEG sources."""
    best = None
    for fmt, kw in (("PNG", {}), ("JPEG", {"quality": 90})):
        b = io.BytesIO()
        Image.fromarray(arr).save(b, fmt, **kw)
        if best is None or b.tell() < best.tell():
            best = b
    best.seek(0)
    return best


def box(s, rows, k):
    """One text box: rows is a list of lines, each a list of (text, box, color)."""
    boxes = [w[1] for row in rows for w in row]
    x0, y0 = min(b[0] for b in boxes), min(b[1] for b in boxes)
    x1 = max(b[0] + b[2] for b in boxes)
    y1 = max(b[1] + b[3] for b in boxes)
    size = float(np.median([em(row) for row in rows])) * k / 12700
    tops = [min(w[1][1] for w in row) for row in rows]
    pitch = float(np.median(np.diff(tops))) if len(rows) > 1 else 0
    color = np.median([w[2] for row in rows for w in row], axis=0).astype(int)
    tb = s.shapes.add_textbox(
        Emu(int(x0 * k)),
        Emu(int(y0 * k)),
        Emu(int(((x1 - x0) * 1.3 + size * 12700 / k) * k)),
        Emu(int((y1 - y0) * k)),
    )
    tf = tb.text_frame
    tf.word_wrap = False
    tf.margin_left = tf.margin_right = tf.margin_top = tf.margin_bottom = 0
    for i, row in enumerate(rows):
        para = tf.paragraphs[0] if i == 0 else tf.add_paragraph()
        if pitch and i:
            para.line_spacing = Pt(pitch * k / 12700)
        run = para.add_run()
        run.text = " ".join(w[0] for w in row)
        run.font.name = "Arial"
        run.font.size = Pt(max(6, round(size)))
        run.font.color.rgb = RGBColor(*(int(c) for c in color))


def slide(prs, img):
    px = np.array(img)
    mask = np.zeros(px.shape[:2], np.uint8)
    lines = {}
    for key, text, conf, (x, y, w, h) in words(img):
        if conf < 40 and not any(c.isalnum() for c in text):
            continue  # specks of noise read as marks
        (x0, y0), letters = ink(px, (x, y, w, h))
        lh, lw = letters.shape
        mask[y0 : y0 + lh, x0 : x0 + lw][letters] = 255
        color = (
            np.median(px[y0 : y0 + lh, x0 : x0 + lw][letters], axis=0)
            if letters.any()
            else (0, 0, 0)
        )
        lines.setdefault(key, []).append([text, (x, y, w, h), color])
    for row in lines.values():
        lh = max(w[1][3] for w in row)
        first = row[0]
        if set(first[0]) <= BULLETS and max(first[1][2], first[1][3]) < 0.6 * lh:
            first[0] = "\u2022"  # Tesseract reads a bullet dot as e, c or a mark
    mask = cv2.dilate(mask, np.ones((5, 5), np.uint8))
    clean = cv2.inpaint(px, mask, 5, cv2.INPAINT_TELEA)

    s = prs.slides.add_slide(prs.slide_layouts[6])
    k = prs.slide_width / img.width  # EMU per pixel
    s.shapes.add_picture(picture(clean), 0, 0, prs.slide_width, prs.slide_height)
    paras = {}
    for key in sorted(lines):
        paras.setdefault(key[:2], []).append(chunks(lines[key]))
    for rows in paras.values():
        if all(len(c) == 1 for c in rows):
            box(
                s, [c[0] for c in rows], k
            )  # a paragraph stays one box, so it can be edited as one
        else:
            for c in rows:
                for part in c:
                    box(s, [part], k)


def main(args):
    if len(args) < 2 or not args[-1].lower().endswith(".pptx"):
        sys.exit("usage: python3 img2pptx.py <slides.pdf | picture ...> <out.pptx>")
    prs = Presentation()
    n = 0
    for img in pictures([Path(a) for a in args[:-1]]):
        if n == 0:
            prs.slide_width = Emu(12192000)  # 13.333 in, the 16:9 width
            prs.slide_height = Emu(round(12192000 * img.height / img.width))
        slide(prs, img)
        n += 1
    prs.save(args[-1])
    print(f"{n} slides -> {args[-1]}")


if __name__ == "__main__":
    main(sys.argv[1:])
