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14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
"""
deck_builder.py β€” Custom PPT Builder (manual slides: text / bullets / table / images).

Compose a deck slide-by-slide without the CMS: each slide carries a title, body
bullet lines, an optional tab-separated table, optionally several images (with
captions), and speaker notes. Slides are built onto YOUR template by cloning its
first slide (logo/header preserved) like the quiz PPT does; without a template
the app falls back to blank 16:9 slides.

Only python-pptx + Pillow are needed here β€” deliberately no Playwright and no
CMS, so this tool keeps working on the HF Space even when the browser-based
tools can't start Chromium.

Layout (deterministic):
  * optional COVER slide first (deck title + subtitle + date)
  * title bar at the top of every content slide
  * images, when present, go in a right-hand band split into equal slots; each
    image is aspect-fitted and centred in its slot with its caption underneath
  * bullets go in the left column (or full width when there are no images)
  * a table renders below the bullets (left column / full width when alone),
    capped at 30 rows x 12 cols, with a styled header row
  * speaker notes are written to the slide's notes pane

Usage:
    generate_deck(slides, template_path=..., out_path=..., text_style="auto",
                  cover={"title": ..., "subtitle": ..., "date": ...})
"""
from __future__ import annotations

import copy
import io
import math
import os
from datetime import datetime, date

from PIL import Image
from pptx import Presentation
from pptx.util import Inches, Pt, Emu
from pptx.oxml.ns import qn
from pptx.dml.color import RGBColor
from pptx.enum.text import PP_ALIGN
from pptx.enum.dml import MSO_FILL
from pptx.enum.text import MSO_ANCHOR

# ── Defaults ────────────────────────────────────────────────────────────────
DEFAULT_TEMPLATE = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))),
                                "database", "ppt_template.pptx")

# ── Limits (the route also enforces these before calling us) ────────────────
MAX_SLIDES = 80
MAX_IMAGES_PER_SLIDE = 8
MAX_IMG_BYTES = 5 * 1024 * 1024
MAX_TABLE_ROWS = 30
MAX_TABLE_COLS = 12

# ── Palette / typography ────────────────────────────────────────────────────
_WHITE = RGBColor(0xFF, 0xFF, 0xFF)
_INK   = RGBColor(0x14, 0x1E, 0x2E)      # near-black, for light templates
_ACCENT = RGBColor(0x18, 0x90, 0xFF)     # IL indigo-blue accent
_MUTED_L = RGBColor(0x8F, 0xB9, 0xE8)    # muted on dark slides
_MUTED_D = RGBColor(0x5A, 0x6C, 0x82)    # muted on light slides
_FONT_TITLE = "Arial Rounded MT Bold"
_FONT_BODY  = "Segoe UI"

# Layout constants (inches).
_TITLE_LEFT = 0.55
_TITLE_TOP  = 0.38
_TITLE_H    = 0.95
_INK_R      = 0.45
_GAP        = 0.30
_BOTTOM     = 0.55
_TABLE_GAP  = 0.16


def parse_pasted_table(text) -> list:
    """Tab-separated clipboard text -> list[list[str]] (rectangular).

    Tolerates \\r newlines and ragged rows (short rows are padded, empty rows
    dropped). Returns [] for blank input.
    """
    rows = []
    for ln in (text or "").splitlines():
        cells = [c.strip() for c in ln.rstrip("\r").split("\t")]
        if not any(cells):
            continue
        rows.append(cells)
    if not rows:
        return []
    width = max(len(r) for r in rows)
    return [r + [""] * (width - len(r)) for r in rows]


def image_verify(data: bytes) -> bool:
    """True if `data` decodes as a readable image (Pillow sniff test)."""
    try:
        Image.open(io.BytesIO(data)).verify()
        return True
    except Exception:  # noqa: BLE001
        return False


def _norm_slide(spec) -> dict:
    spec = spec or {}
    images = []
    for im in spec.get("images") or []:
        if isinstance(im, dict):
            if im.get("data"):
                images.append({"data": im["data"],
                               "caption": str(im.get("caption") or "").strip()})
        elif isinstance(im, (bytes, bytearray)):
            images.append({"data": bytes(im), "caption": ""})
    return {
        "title": str(spec.get("title") or "").strip(),
        "body": [str(x).strip() for x in (spec.get("body") or []) if str(x or "").strip()],
        "table": str(spec.get("table") or "").strip(),
        "notes": str(spec.get("notes") or "").strip(),
        "images": images,
    }


def _is_empty(slide) -> bool:
    return not (slide["title"] or slide["body"] or slide["table"] or slide["images"])


def _style_run(run, size, color, bold=False, font=_FONT_BODY):
    run.font.name = font
    run.font.size = Pt(size)
    run.font.bold = bold
    run.font.color.rgb = color


def _add_textbox(slide, left, top, width, height):
    tb = slide.shapes.add_textbox(Inches(left), Inches(top), Inches(width), Inches(height))
    tf = tb.text_frame
    tf.word_wrap = True
    tf.margin_left = Inches(0.04)
    tf.margin_right = Inches(0.04)
    tf.margin_top = Inches(0.02)
    tf.margin_bottom = Inches(0.02)
    return tb


def _fit_title(slide, title, left, top, width, height, size, color, font, align=PP_ALIGN.LEFT):
    tb = _add_textbox(slide, left, top, width, height)
    p = tb.text_frame.paragraphs[0]
    p.alignment = align
    r = p.add_run()
    r.text = title
    _style_run(r, size, color, bold=True, font=font)
    est_w = len(title) * size * 0.62 * 12700          # pt -> EMU rough estimate
    avail = (Inches(width) - tb.text_frame.margin_left - tb.text_frame.margin_right)
    if est_w > avail and len(title) > 4:
        r.font.size = Pt(max(int(size * avail / est_w), 18))
    return tb


def _add_rule(slide, left, top, width, height=Inches(0.025)):
    from pptx.enum.shapes import MSO_SHAPE
    bar = slide.shapes.add_shape(MSO_SHAPE.RECTANGLE, Inches(left), Inches(top),
                                 Inches(width), height)
    bar.fill.solid()
    bar.fill.fore_color.rgb = _ACCENT
    bar.line.fill.background()
    bar.shadow.inherit = False


# ── Template machinery (same approach as ppt_api) ───────────────────────────
def _duplicate_slide(prs, src):
    new = prs.slides.add_slide(src.slide_layout)
    for shp in list(new.shapes):
        shp._element.getparent().remove(shp._element)
    rId_map = {}
    for rId, rel in src.part.rels.items():
        if "notesSlide" in rel.reltype:
            continue
        if rel.is_external:
            rId_map[rId] = new.part.rels.get_or_add_ext_rel(rel.reltype, rel._target_ref)
        else:
            rId_map[rId] = new.part.relate_to(rel._target, rel.reltype)
    for shp in src.shapes:
        el = copy.deepcopy(shp._element)
        for attr in (qn("r:embed"), qn("r:link")):
            for node in el.iter():
                if node.get(attr) in rId_map:
                    node.set(attr, rId_map[node.get(attr)])
        new.shapes._spTree.append(el)
    return new


def _remove_slide(prs, index):
    lst = prs.slides._sldIdLst
    lst.remove(list(lst)[index])


def _strip_placeholders(slide):
    """Drop the quiz template's 'Q.' + 'Topic Name' shapes so custom content
    doesn't collide; the logo/header stay."""
    for shp in list(slide.shapes):
        try:
            txt = shp.text_frame.text.strip()
        except Exception:                                   # noqa: BLE001
            continue
        if txt.rstrip(".") == "Q" or "Topic Name" in txt:
            shp._element.getparent().remove(shp._element)


def _auto_text_is_dark(prs) -> bool:
    """Probe slide 0 / layout / master background fill; True if it looks light
    (so we should use dark text). Falls back to False (white text, the branded
    template) when the background isn't an explicit solid colour."""
    for holder in (lambda: prs.slides[0].background,
                   lambda: prs.slides[0].slide_layout.background,
                   lambda: prs.slide_masters[0].background):
        try:
            fill = holder().fill
            if fill.type == MSO_FILL.SOLID:
                rgb = fill.fore_color.rgb
                lum = 0.299 * rgb[0] + 0.587 * rgb[1] + 0.114 * rgb[2]
                return lum >= 140
        except Exception:                                   # noqa: BLE001
            continue
    return False


# ── Building blocks ─────────────────────────────────────────────────────────
def _add_cover(prs, slide, cover, dark_text):
    ink = _INK if dark_text else _WHITE
    muted = _MUTED_D if dark_text else _MUTED_L
    title = str(cover.get("title") or "").strip() or "Presentation"
    sub   = str(cover.get("subtitle") or "").strip()
    when  = str(cover.get("date") or "").strip() or date.today().strftime("%d %b %Y")
    w = prs.slide_width

    # Eyebrow.
    _fit_title(slide, "PRESENTATION", 0.8, 2.35, (w / 914400) - 1.6, 0.4, 14,
               _ACCENT, _FONT_BODY, align=PP_ALIGN.CENTER)
    # Title.
    _fit_title(slide, title, 0.8, 2.75, (w / 914400) - 1.6, 1.2, 46,
               ink, _FONT_TITLE, align=PP_ALIGN.CENTER)
    # Accent rule under the title.
    _add_rule(slide, ((w / 914400) / 2) - 1.1, 4.02, 2.2)
    # Subtitle + date.
    if sub:
        tb = _add_textbox(slide, 0.8, 4.18, (w / 914400) - 1.6, 0.6)
        p = tb.text_frame.paragraphs[0]
        p.alignment = PP_ALIGN.CENTER
        r = p.add_run(); r.text = sub
        _style_run(r, 20, muted, bold=False)
    tb = _add_textbox(slide, 0.8, 4.75, (w / 914400) - 1.6, 0.4)
    p = tb.text_frame.paragraphs[0]
    p.alignment = PP_ALIGN.CENTER
    r = p.add_run(); r.text = when
    _style_run(r, 14, muted, bold=False)


def _add_bullets(slide, x, y, w, h, lines, dark_text):
    ink = _INK if dark_text else _WHITE
    tb = _add_textbox(slide, x, y, w, h)
    for i, line in enumerate(lines):
        p = tb.text_frame.paragraphs[0] if i == 0 else tb.text_frame.add_paragraph()
        p.space_before = Pt(2)
        p.space_after = Pt(2)
        r = p.add_run()
        r.text = "β€’  " + line
        _style_run(r, 18, ink, bold=False)
    return tb


def _fit_picture(slide, prs, data, x, y, slot_w, slot_h):
    im = Image.open(io.BytesIO(data))
    aspect = im.size[1] / im.size[0]
    w = slot_w
    h = w * aspect
    if h > slot_h:
        h = slot_h
        w = h / aspect
    ox = (slot_w - w) / 2
    oy = (slot_h - h) / 2
    return slide.shapes.add_picture(io.BytesIO(data),
                                    Inches(x + ox), Inches(y + oy),
                                    width=Inches(w), height=Inches(h))


def _add_images(slide, prs, images, x, y, band_w, band_h, dark_text):
    muted = _MUTED_D if dark_text else _MUTED_L
    n = len(images)
    cols = 1 if n <= 3 else 2
    rows = math.ceil(n / cols)
    gap = 0.18
    slot_w = (band_w - (cols - 1) * gap) / cols
    slot_h = (band_h - (rows - 1) * gap) / rows
    for idx, img in enumerate(images):
        c_, r_ = idx % cols, idx // cols
        sx = x + c_ * (slot_w + gap)
        sy = y + r_ * (slot_h + gap)
        cap_h = 0.32 if img["caption"] else 0.0
        _fit_picture(slide, prs, img["data"], sx, sy, slot_w, slot_h - cap_h)
        if cap_h:
            cb = _add_textbox(slide, sx, sy + slot_h - cap_h + 0.03, slot_w, cap_h - 0.03)
            pr = cb.text_frame.paragraphs[0]
            pr.alignment = PP_ALIGN.CENTER
            run = pr.add_run()
            run.text = img["caption"]
            _style_run(run, 12, muted, bold=False)


def _add_table(slide, prs, rows, x, y, w, h, dark_text, warnings):
    n_rows = min(len(rows), MAX_TABLE_ROWS)
    n_cols = min(max(len(r) for r in rows), MAX_TABLE_COLS)
    if n_rows < len(rows) or n_cols > MAX_TABLE_COLS:
        warnings.append(f"table truncated to {n_rows}x{n_cols}")

    gf = slide.shapes.add_table(n_rows, n_cols, Inches(x), Inches(y), Inches(w), Inches(h))
    tbl = gf.table

    # Proportional column widths.
    weights = []
    for c in range(n_cols):
        weights.append(max(1, min(max(len(r[c]) for r in rows if c < len(r)), 40)))
    total_w = sum(weights)
    avail_w = Inches(w)
    for c in range(n_cols):
        tbl.columns[c].width = int(Emu(avail_w) * (weights[c] / total_w))

    body_fill = "F2F6FB" if dark_text else "103A66"
    body_ink = _INK if dark_text else _WHITE
    # Header + body font scaled to fit the available height.
    base = 13 if n_rows <= 6 else (12 if n_rows <= 10 else 11)
    for r in range(n_rows):
        tbl.rows[r].height = Inches(max(0.30, h / n_rows))
        for c in range(n_cols):
            cell = tbl.cell(r, c)
            cell.margin_left = Inches(0.06)
            cell.margin_right = Inches(0.06)
            cell.margin_top = Inches(0.02)
            cell.margin_bottom = Inches(0.02)
            cell.vertical_anchor = MSO_ANCHOR.MIDDLE
            txt = rows[r][c] if c < len(rows[r]) else ""
            p = cell.text_frame.paragraphs[0]
            p.alignment = PP_ALIGN.CENTER if r == 0 else PP_ALIGN.LEFT
            run = p.add_run()
            run.text = txt
            if r == 0:
                cell.fill.solid()
                cell.fill.fore_color.rgb = _ACCENT
                _style_run(run, base, _WHITE, bold=True)
            else:
                cell.fill.solid()
                cell.fill.fore_color.rgb = RGBColor.from_string(body_fill)
                _style_run(run, base, body_ink, bold=False)


# ── Orchestrator ────────────────────────────────────────────────────────────
def generate_deck(slides, template_path=None, out_path=None, log=print,
                  text_style="auto", cover=None):
    """Generate a custom deck from slide specs. Returns (out_path, warnings).

    `slides`: list of specs {title, body:[...], table, notes, images:[{data,
    caption}]}. `cover`: None or {title, subtitle, date}. `text_style`: "auto"
    (probe the template) | "dark-bg" (white text) | "light-bg" (dark text).
    """
    warnings: list = []
    specs = [_norm_slide(s) for s in (slides or [])]
    specs = [s for s in specs if not _is_empty(s)]
    skipped = len(slides or []) - len(specs)
    if skipped:
        warnings.append(f"{skipped} empty slide(s) skipped")
    if not specs and not cover:
        raise ValueError("No slides to build (all were empty).")

    if template_path is None:
        template_path = DEFAULT_TEMPLATE
    if out_path is None:
        out_path = os.path.join(os.path.dirname(os.path.abspath(__file__)),
                                f"custom_deck_{datetime.now():%Y%m%d_%H%M%S}.pptx")

    branded = bool(template_path) and os.path.exists(template_path)
    if branded:
        prs = Presentation(template_path)
        branded = len(prs.slides) >= 1
    if not branded:
        prs = Presentation()
        prs.slide_width = Inches(13.33)
        prs.slide_height = Inches(7.5)
        log("INFO: no usable template β€” blank 16:9 slides")

    # Text colour decision.
    if text_style == "dark-bg":
        dark_text = False
    elif text_style == "light-bg":
        dark_text = True
    else:                                          # auto
        dark_text = _auto_text_is_dark(prs) if branded else True

    def new_slide():
        if branded:
            slide = _duplicate_slide(prs, prs.slides[0])
            _strip_placeholders(slide)
        else:
            slide = prs.slides.add_slide(prs.slide_layouts[6])
        return slide

    ink = _INK if dark_text else _WHITE

    # ── Cover slide (optional, emitted first) ─────────────────────────────
    if cover:
        _add_cover(prs, new_slide(), cover, dark_text)

    # ── Content slides ─────────────────────────────────────────────────────
    w_in = prs.slide_width / 914400
    h_in = prs.slide_height / 914400
    content_top = _TITLE_TOP + _TITLE_H + _GAP
    content_h = h_in - content_top - _BOTTOM

    for spec in specs:
        slide = new_slide()
        title = spec["title"]
        body = spec["body"]
        rows = parse_pasted_table(spec["table"]) if spec["table"] else []
        images = spec["images"]

        if title:
            _fit_title(slide, title, _TITLE_LEFT, _TITLE_TOP,
                       w_in - _TITLE_LEFT - _INK_R, _TITLE_H, 26, ink, _FONT_TITLE)
            _add_rule(slide, _TITLE_LEFT + 0.06, _TITLE_TOP + _TITLE_H - 0.12, 1.1)

        # Lay out the content band: images right, body/table left.
        if images:
            band_x = w_in - _INK_R - min(5.2, (w_in - _TITLE_LEFT - _INK_R) * 0.42)
            band_w = w_in - _INK_R - band_x
            body_w = band_x - _TITLE_LEFT - _GAP
        else:
            band_x = _TITLE_LEFT
            band_w = w_in - _TITLE_LEFT - _INK_R
            body_w = band_w

        left_free = not body and not rows
        if images and left_free:
            _add_images(slide, prs, images, _TITLE_LEFT, content_top,
                        w_in - _TITLE_LEFT - _INK_R, content_h, dark_text)
            continue

        if images:
            _add_images(slide, prs, images, band_x, content_top, band_w, content_h,
                        dark_text)

        # Body + table share the left area (bullets on top, table below).
        if rows and body:
            body_h = content_h * 0.42
            table_h = content_h - body_h - _TABLE_GAP
        elif rows:
            body_h = 0
            table_h = content_h
        else:
            body_h = content_h
            table_h = 0
        if body:
            _add_bullets(slide, _TITLE_LEFT, content_top, body_w, body_h, body, dark_text)
        if rows:
            _add_table(slide, prs, rows, _TITLE_LEFT,
                       content_top + body_h + (_TABLE_GAP if body else 0),
                       body_w, table_h, dark_text, warnings)

        if spec["notes"]:
            try:
                slide.notes_slide.notes_text_frame.text = spec["notes"]
            except Exception:                                   # noqa: BLE001
                pass

    # Drop the seeded template slide we cloned from.
    if branded and len(prs.slides) > 1:
        _remove_slide(prs, 0)

    prs.save(out_path)
    log(f"Saved {len(prs.slides)} slide(s) -> {out_path}")
    return out_path, warnings


if __name__ == "__main__":
    import sys
    buf = io.BytesIO()
    Image.new("RGB", (640, 400), "#1a4f8b").save(buf, "PNG")
    demo = [
        {"title": "First principles", "body": ["Point one", "Point two"],
         "images": [{"data": buf.getvalue(), "caption": "Fig 1. demo"}]},
        {"title": "A comparison", "table": "Property\tValue\nSpeed\tVery fast\nPrice\tFree"},
        {"title": "Notes slide", "notes": "Explainer for the presenter."},
    ]
    p, w = generate_deck(demo, out_path=sys.argv[1] if len(sys.argv) > 1 else "demo_deck.pptx")
    print(p, w)