# -*- coding: utf-8 -*- """ deck_common.py — infraestructura reutilizable para construir los decks del curso Big Data (Dr. Abel Coronado) con python-pptx. Basado en D:\\BDP\\PPTX\\_build_deck.py, generalizado a una clase Deck y con dos capacidades nuevas que pide la re-ingeniería del curso: - set_notes(slide, texto) -> notas del instructor en cada diapositiva - add_image_prompt_box(slide, ...) -> recuadro estilizado con el PROMPT que generará una imagen (diagramas no-captura) o que un agente Mac/Linux leerá para reemplazarlo por una captura real de ese SO. Uso: from deck_common import * d = Deck("HDFS · Hadoop Distributed File System") s = d.slide("¿Qué es HDFS?") add_bullets(s, [...], 0.5, 1.15, 9.0, 4.0) set_notes(s, "Guion para el instructor…") d.save(r"D:\\BDP\\Curso_BDP\\Semana_2\\Semana_2.pptx") """ import os, copy from PIL import Image from pptx import Presentation from pptx.util import Emu, Inches, Pt from pptx.dml.color import RGBColor from pptx.enum.text import PP_ALIGN, MSO_ANCHOR from pptx.oxml.ns import qn # --- rutas por defecto del paquete del curso --- HERE = os.path.dirname(os.path.abspath(__file__)) ROOT = os.path.dirname(HERE) # D:\BDP\Curso_BDP TEMPLATE = os.path.join(ROOT, "_assets", "template.pptx") ASSETS = os.path.join(ROOT, "_assets", "capturas") # capturas Windows reusables def asset(name): """Ruta a una captura/diagrama del paquete.""" return os.path.join(ASSETS, name) # --- paleta (consistente con el deck HDFS previo) --- BLUE = RGBColor(0x00, 0x98, 0xCD) DARK = RGBColor(0x53, 0x53, 0x53) BLACK = RGBColor(0x20, 0x28, 0x30) GREEN = RGBColor(0x2E, 0x7D, 0x32) RED = RGBColor(0xC6, 0x28, 0x28) WHITE = RGBColor(0xFF, 0xFF, 0xFF) LBLUE = RGBColor(0xE7, 0xF4, 0xFA) AMBER = RGBColor(0xFF, 0xF4, 0xD6) AMBTX = RGBColor(0x6B, 0x52, 0x00) HDRBG = RGBColor(0x00, 0x98, 0xCD) ROWBG = RGBColor(0xF2, 0xF7, 0xFA) PROMPTBG = RGBColor(0xF3, 0xEE, 0xFB) # lila claro para recuadros-prompt PROMPTLN = RGBColor(0x8E, 0x6F, 0xC6) GOLD = RGBColor(0xC0, 0x9A, 0x2B) # oro elegante (banda inferior, marca blanca) _UNIR_BLUE = RGBColor(0x00, 0x98, 0xCD) # azul de la plantilla UNIR (a recolorear a oro) def _regold(shapes): """Recolorea a ORO cualquier relleno sólido azul-UNIR (la banda inferior y la línea de la portada), recursivo en grupos. No toca títulos ni callouts.""" for sp in shapes: if sp.shape_type == 6: # grupo _regold(sp.shapes); continue try: if sp.fill.type == 1 and sp.fill.fore_color.type == 1 and sp.fill.fore_color.rgb == _UNIR_BLUE: sp.fill.fore_color.rgb = GOLD except Exception: pass class Deck: """Encapsula la presentación, su layout y el 'chrome' (barra de título + número de página) clonado de la plantilla UNIR del Dr. Coronado.""" def __init__(self, subtitle, template=TEMPLATE, title_main="Curso de Big Data", author="Dr. Abel Coronado (@abxda)"): self.prs = Presentation(template) self.SW, self.SH = self.prs.slide_width, self.prs.slide_height # localizar layout "Titulo y objetos" (slideLayout13) o el primero self.layout = None for master in self.prs.slide_masters: for lay in master.slide_layouts: if lay.part.partname.endswith('slideLayout13.xml'): self.layout = lay if self.layout is None: self.layout = self.prs.slide_layouts[0] # donantes de chrome desde slide index 1 (antes de borrar) donor = self.prs.slides[1] self._title_donor = self._pagenum_donor = None for sp in donor.shapes: if sp.name == 'Rectangle 2': self._title_donor = copy.deepcopy(sp._element) elif sp.name == 'Rectangle 1': self._pagenum_donor = copy.deepcopy(sp._element) assert self._title_donor is not None and self._pagenum_donor is not None, \ "La plantilla no tiene los donantes Rectangle 1/2" # --- portada + MARCA BLANCA (quitar branding UNIR) --- _UNIR = ("universidad internacional", "rioja", "unir") s1 = self.prs.slides[0] for sp in list(s1.shapes): txt = sp.text_frame.text if sp.has_text_frame else "" # logo (imagen en el pie de la portada) if sp.shape_type == 13 and sp.top is not None and sp.top > Inches(6): sp._element.getparent().remove(sp._element); continue # nombre de la universidad if txt and any(k in txt.lower() for k in _UNIR): sp._element.getparent().remove(sp._element); continue if sp.name == 'Rectangle 7' and sp.has_text_frame and subtitle and sp.text_frame.paragraphs[0].runs: sp.text_frame.paragraphs[0].runs[0].text = subtitle if sp.name == 'Rectangle 6' and title_main and sp.has_text_frame and sp.text_frame.paragraphs[0].runs: sp.text_frame.paragraphs[0].runs[0].text = title_main # quitar el logo UNIR de el/los slide master(s) (aparece en cada diapositiva) for m in self.prs.slide_masters: for sp in list(m.shapes): if sp.shape_type == 13 and sp.top is not None and sp.top > Inches(6): sp._element.getparent().remove(sp._element) elif sp.has_text_frame and any(k in sp.text_frame.text.lower() for k in _UNIR): sp._element.getparent().remove(sp._element) # banda azul -> ORO elegante (master + portada) for m in self.prs.slide_masters: _regold(m.shapes) _regold(s1.shapes) # borrar slides de contenido (conservar portada) xml_slides = self.prs.slides._sldIdLst for sldId in list(xml_slides)[1:]: rId = sldId.get(qn('r:id')) try: self.prs.part.drop_rel(rId) except Exception: pass xml_slides.remove(sldId) def slide(self, title, title_w_in=8.8): sl = self.prs.slides.add_slide(self.layout) for sp in list(sl.shapes): if sp.is_placeholder: sp._element.getparent().remove(sp._element) pn = copy.deepcopy(self._pagenum_donor) sl.shapes._spTree.append(pn) t = copy.deepcopy(self._title_donor) ext = t.find('.//'+qn('a:xfrm')+'/'+qn('a:ext')) if ext is None: ext = t.find('.//'+qn('a:ext')) ext.set('cx', str(int(Inches(title_w_in)))) txbody = t.find(qn('p:txBody')) ps = txbody.findall(qn('a:p')) first_t = ps[0].find('.//'+qn('a:t')) first_t.text = title sl.shapes._spTree.append(t) return sl def save(self, out): os.makedirs(os.path.dirname(out), exist_ok=True) self.prs.save(out) print('SAVED', out, 'slides=', len(self.prs.slides._sldIdLst)) return out # ---------------- helpers de contenido (slide-based) ---------------- def _set_para(p, text, size, color, bold=False, italic=False, font='Arial', align=PP_ALIGN.LEFT, space_after=6): p.alignment = align if space_after is not None: p.space_after = Pt(space_after) run = p.add_run(); run.text = text f = run.font f.size = Pt(size); f.bold = bold; f.italic = italic; f.name = font f.color.rgb = color return run def add_textbox(sl, left, top, width, height, anchor=MSO_ANCHOR.TOP, wrap=True): tb = sl.shapes.add_textbox(Inches(left), Inches(top), Inches(width), Inches(height)) tf = tb.text_frame; tf.word_wrap = wrap tf.vertical_anchor = anchor tf.margin_left = Inches(0.05); tf.margin_right = Inches(0.05) tf.margin_top = Inches(0.02); tf.margin_bottom = Inches(0.02) return tb, tf def add_bullets(sl, items, left, top, width, height, size=18, gap=6): tb, tf = add_textbox(sl, left, top, width, height) first = True for it in items: p = tf.paragraphs[0] if first else tf.add_paragraph() first = False lvl = it.get('level', 0); p.level = lvl sz = it.get('size', size); col = it.get('color', DARK) bold = it.get('bold', False); txt = it.get('text', '') if it.get('bullet', True): txt = ('• ' if lvl == 0 else '– ') + txt _set_para(p, txt, sz, col, bold=bold, space_after=it.get('gap', gap)) return tb def add_para_block(sl, paras, left, top, width, height): tb, tf = add_textbox(sl, left, top, width, height) first = True for it in paras: p = tf.paragraphs[0] if first else tf.add_paragraph() first = False _set_para(p, it['text'], it.get('size',18), it.get('color',DARK), bold=it.get('bold',False), italic=it.get('italic',False), align=it.get('align',PP_ALIGN.LEFT), space_after=it.get('gap',6)) return tb def add_image_fit(sl, path, left, top, maxw, maxh, align='center', valign='top', border=True): iw, ih = Image.open(path).size ar = iw/ih; box_ar = maxw/maxh if ar > box_ar: w = maxw; h = maxw/ar else: h = maxh; w = maxh*ar x = left + (maxw-w)/2 if align=='center' else left y = top + (maxh-h)/2 if valign=='center' else top pic = sl.shapes.add_picture(path, Inches(x), Inches(y), Inches(w), Inches(h)) if border: ln = pic.line; ln.color.rgb = RGBColor(0xCF,0xD8,0xDD); ln.width = Pt(0.75) return pic def add_code(sl, code, left, top, width, height, size=14, fg=RGBColor(0xE8,0xE8,0xE8)): box = sl.shapes.add_shape(1, Inches(left), Inches(top), Inches(width), Inches(height)) box.fill.solid(); box.fill.fore_color.rgb = RGBColor(0x12,0x12,0x12) box.line.color.rgb = RGBColor(0x33,0x3A,0x40); box.line.width = Pt(1) tf = box.text_frame; tf.word_wrap = True tf.margin_left = Inches(0.12); tf.margin_right = Inches(0.1) tf.margin_top = Inches(0.08); tf.margin_bottom = Inches(0.08) tf.vertical_anchor = MSO_ANCHOR.TOP first = True for ln in code.split('\n'): p = tf.paragraphs[0] if first else tf.add_paragraph() first = False p.space_after = Pt(2); p.alignment = PP_ALIGN.LEFT run = p.add_run(); run.text = ln if ln else ' ' f = run.font; f.name = 'Consolas'; f.size = Pt(size) s = ln.strip() if s.startswith('#'): f.color.rgb = RGBColor(0x7A,0xC0,0x70) elif s.startswith('$') or s.startswith('PS '): f.color.rgb = RGBColor(0x7A,0xC8,0xFF) elif s.startswith('>>>') or s.startswith('In ['): f.color.rgb = RGBColor(0xC8,0xA0,0xFF) else: f.color.rgb = fg return box def add_callout(sl, text, left, top, width, height, fill=LBLUE, fg=BLACK, size=15, bold=False, line=BLUE): box = sl.shapes.add_shape(1, Inches(left), Inches(top), Inches(width), Inches(height)) box.fill.solid(); box.fill.fore_color.rgb = fill box.line.color.rgb = line; box.line.width = Pt(1) tf = box.text_frame; tf.word_wrap = True tf.margin_left = Inches(0.12); tf.margin_right = Inches(0.12) tf.vertical_anchor = MSO_ANCHOR.MIDDLE p = tf.paragraphs[0] _set_para(p, text, size, fg, bold=bold, space_after=0) return box def add_warn(sl, text, left, top, width, height, size=15, bold=True): """Callout ámbar para avisos/troubleshooting.""" return add_callout(sl, text, left, top, width, height, fill=AMBER, fg=AMBTX, size=size, bold=bold, line=RGBColor(0xD9,0xA4,0x06)) def add_url(sl, url, left, top, width, size=15): tb, tf = add_textbox(sl, left, top, width, 0.4) p = tf.paragraphs[0] run = p.add_run(); run.text = url f = run.font; f.name='Arial'; f.size=Pt(size); f.color.rgb=BLUE; f.underline=True try: run.hyperlink.address = url.split()[0] if url.startswith('http') else None except Exception: pass return tb def add_table(sl, rows, left, top, width, col_w=None, header=True, fsize=14, hsize=14, row_h=0.34): nr = len(rows); nc = len(rows[0]) gfx = sl.shapes.add_table(nr, nc, Inches(left), Inches(top), Inches(width), Inches(row_h*nr)) tbl = gfx.table if col_w: for i,w in enumerate(col_w): tbl.columns[i].width = Inches(w) for r in range(nr): tbl.rows[r].height = Inches(row_h) for c in range(nc): cell = tbl.cell(r,c) cell.margin_left = Inches(0.08); cell.margin_right=Inches(0.06) cell.margin_top=Inches(0.02); cell.margin_bottom=Inches(0.02) cell.vertical_anchor = MSO_ANCHOR.MIDDLE tf = cell.text_frame; tf.word_wrap=True p = tf.paragraphs[0] run = p.add_run(); run.text = str(rows[r][c]) f = run.font; f.name='Arial' if header and r==0: cell.fill.solid(); cell.fill.fore_color.rgb=HDRBG f.size=Pt(hsize); f.bold=True; f.color.rgb=WHITE else: cell.fill.solid(); cell.fill.fore_color.rgb = ROWBG if r%2 else WHITE f.size=Pt(fsize); f.color.rgb=BLACK return tbl def add_image_prompt_box(sl, prompt, left, top, width, height, kind="imagen", title=None): """Recuadro lila estilizado con el PROMPT que generará una imagen (diagramas no-captura) o el INSTRUCTIVO para que un agente Mac/Linux capture y reemplace. kind: 'imagen' (prompt de generación) o 'captura' (instructivo de captura).""" box = sl.shapes.add_shape(1, Inches(left), Inches(top), Inches(width), Inches(height)) box.fill.solid(); box.fill.fore_color.rgb = PROMPTBG box.line.color.rgb = PROMPTLN; box.line.width = Pt(1.5) # borde punteado ln = box.line._get_or_add_ln() d = ln.makeelement(qn('a:prstDash'), {'val':'dash'}); ln.append(d) tf = box.text_frame; tf.word_wrap = True tf.margin_left = Inches(0.15); tf.margin_right = Inches(0.15) tf.margin_top = Inches(0.12); tf.margin_bottom = Inches(0.12) tf.vertical_anchor = MSO_ANCHOR.TOP hdr = ("🖼️ RECUADRO DE IMAGEN — prompt de generación" if kind == "imagen" else "📸 RECUADRO DE CAPTURA — instructivo para el agente del SO") p = tf.paragraphs[0] _set_para(p, title or hdr, 13, PROMPTLN, bold=True, space_after=6) p2 = tf.add_paragraph() _set_para(p2, prompt, 12, BLACK, italic=True, space_after=0) return box def set_notes(slide, text): """Escribe las notas del instructor en la diapositiva.""" slide.notes_slide.notes_text_frame.text = text return slide