Telegram-Bot / content /pdf_generator.py
H3y-sam's picture
Upload 54 files
94b42f2 verified
Raw History Blame Contribute Delete
21.7 kB
"""
pdf_generator.py β€” Branded Weekly Digest PDF Generator
CrazyLearners | t.me/xcrazylearners
Layout (LaTeX-inspired with fpdf2):
β€’ Cover page β€” title, channel name, date, branding banner
β€’ TOC page β€” list of subjects + chapters
β€’ Content β€” Subject divider β†’ Chapter card β†’ body text (justified)
β€’ Every page β€” header with logo-text + footer with page no. + channel link
β€’ Last page β€” CrazyLearners branding / call-to-action
Fonts used (built-in fpdf2, no external download needed):
Helvetica β€” sans-serif (headings, UI chrome)
Courier β€” monospace (formula blocks)
"""
import os
import re
import logging
from datetime import datetime
from fpdf import FPDF
logger = logging.getLogger(__name__)
# ─── Brand constants ────────────────────────────────────────────────────────────
BRAND_NAME = "CrazyLearners"
BRAND_HANDLE = "@xcrazylearners"
BRAND_LINK = "t.me/xcrazylearners"
BRAND_TAGLINE = "Learn Smarter. Score Higher."
# Colour palette (R, G, B)
C_BRAND_DARK = (15, 23, 42) # near-black navy β€” cover bg simulation (border)
C_BRAND_PURPLE = (79, 70, 229) # indigo-600 β€” primary accent
C_BRAND_TEAL = (20, 184, 166) # teal-500 β€” secondary accent
C_SECTION_RED = (220, 38, 38) # red-600 β€” subject headings
C_CHAPTER_BLU = (37, 99, 235) # blue-600 β€” chapter headings
C_BODY = (30, 30, 30) # near-black β€” body text
C_LIGHT_GREY = (200, 200, 200) # divider lines
C_WHITE = (255, 255, 255)
C_MID_GREY = (120, 120, 120) # captions / footnotes
C_GOLD = (217, 119, 6) # amber-600 β€” highlight boxes
# ─── Text helpers ────────────────────────────────────────────────────────────────
def _strip_markdown(text: str) -> str:
"""Remove Markdown markers but preserve structure."""
if not text:
return ""
# Bold / Italic markers
text = re.sub(r'\*{1,3}(.*?)\*{1,3}', r'\1', text, flags=re.DOTALL)
text = re.sub(r'_{1,2}(.*?)_{1,2}', r'\1', text, flags=re.DOTALL)
# Inline code β†’ keep content, drop backticks
text = re.sub(r'`([^`]*)`', r'\1', text)
# Fenced code blocks β€” keep content
text = re.sub(r'```(?:\w+)?\n(.*?)```', r'\1', text, flags=re.DOTALL)
# Decorative separator lines (━━━ etc.)
text = re.sub(r'[━─=]{3,}', '---', text)
# Hashtags
text = re.sub(r'#\w+', '', text)
# Footer / brand lines already embedded in posts (we'll add our own)
text = re.sub(r'(CrazyLearners|xcrazylearners|t\.me/)', '', text, flags=re.I)
return text.strip()
def _safe_latin1(text: str) -> str:
"""
fpdf2's built-in fonts (Helvetica/Courier) only support Latin-1.
Map common Unicode symbols to ASCII equivalents; drop the rest.
"""
replacements = {
'\u2192': '->', '\u2190': '<-', '\u2194': '<->',
'\u2260': '!=', '\u2248': '~=', '\u2265': '>=',
'\u2264': '<=', '\u00b1': '+/-', '\u00d7': 'x',
'\u00f7': '/', '\u03b1': 'alpha', '\u03b2': 'beta',
'\u03b3': 'gamma', '\u03b4': 'delta', '\u03c0': 'pi',
'\u03bb': 'lambda', '\u03bc': 'mu', '\u03c3': 'sigma',
'\u03c9': 'omega', '\u00b2': '^2', '\u00b3': '^3',
'\u221a': 'sqrt', '\u221e': 'inf', '\u2211': 'sum',
'\u222b': 'int', '\u2202': 'd', '\u0394': 'Delta',
'\u03a9': 'Omega', '\u2019': "'", '\u2018': "'",
'\u201c': '"', '\u201d': '"',
'\u2022': '-', '\u2023': '>', '\u25cf': '*',
'\u2713': '[OK]', '\u2714': '[OK]', '\u2718': '[X]',
# Emojis β€” strip completely (map to empty string or label)
'\U0001f4da': '[BOOK]', '\U0001f4dd': '[NOTE]',
'\U0001f4a1': '[TIP]', '\U0001f3af': '[TARGET]',
'\U0001f525': '[FIRE]', '\U0001f9e0': '[BRAIN]',
'\U00002705': '[OK]', '\U0000274c': '[X]',
'\U000026a0': '[WARN]',
}
for uni, asc in replacements.items():
text = text.replace(uni, asc)
# Drop any remaining non-latin1 characters
text = text.encode('latin-1', errors='ignore').decode('latin-1')
# Collapse excessive blank lines
text = re.sub(r'\n{3,}', '\n\n', text)
return text.strip()
def _clean(text: str) -> str:
"""Full pipeline: strip markdown β†’ safe latin-1."""
return _safe_latin1(_strip_markdown(text))
# ─── PDF Class ───────────────────────────────────────────────────────────────────
class BrandedPDF(FPDF):
"""
CrazyLearners branded PDF with LaTeX-inspired layout.
Each page has a top header bar and a bottom footer bar.
"""
def __init__(self, channel_label: str, content_type_label: str):
super().__init__(orientation='P', unit='mm', format='A4')
self.channel_label = _safe_latin1(channel_label)
self.content_type_label = _safe_latin1(content_type_label)
self.set_margins(left=18, top=28, right=18)
self.set_auto_page_break(auto=True, margin=22)
# ── Header (auto-called on every new page except cover) ──────────────────
def header(self):
if self.page == 1:
return # cover page handles its own layout
# Top rule
self.set_draw_color(*C_BRAND_PURPLE)
self.set_line_width(0.8)
self.line(10, 10, 200, 10)
# Brand name (left)
self.set_xy(10, 12)
self.set_font('Helvetica', 'B', 9)
self.set_text_color(*C_BRAND_PURPLE)
self.cell(80, 6, BRAND_NAME.upper(), align='L')
# Channel label (right)
self.set_xy(110, 12)
self.set_font('Helvetica', '', 8)
self.set_text_color(*C_MID_GREY)
self.cell(80, 6, self.channel_label, align='R')
self.ln(4)
# ── Footer ───────────────────────────────────────────────────────────────
def footer(self):
if self.page == 1:
return
self.set_y(-14)
self.set_draw_color(*C_LIGHT_GREY)
self.set_line_width(0.3)
self.line(10, self.get_y(), 200, self.get_y())
self.ln(1)
self.set_font('Helvetica', 'I', 7.5)
self.set_text_color(*C_MID_GREY)
# Left: page number
self.set_x(10)
self.cell(60, 5, f'Page {self.page_no()}', align='L')
# Centre: content type
self.set_x(70)
self.cell(60, 5, self.content_type_label, align='C')
# Right: channel link
self.set_x(130)
self.cell(60, 5, BRAND_LINK, align='R')
# ── Helpers ───────────────────────────────────────────────────────────────
def _hline(self, color=C_LIGHT_GREY, width=0.3, lm=18, rm=192):
self.set_draw_color(*color)
self.set_line_width(width)
self.line(lm, self.get_y(), rm, self.get_y())
def _filled_rect(self, x, y, w, h, fill_color, radius=2.0):
"""Draw a filled rounded rectangle (section card background)."""
self.set_fill_color(*fill_color)
self.set_draw_color(*fill_color)
self.rounded_rect(x, y, w, h, radius, style='F')
def _section_pill(self, label: str):
"""Draw a coloured pill/badge for the subject label."""
pill_w = 50
pill_h = 8
pill_x = self.l_margin
pill_y = self.get_y()
self._filled_rect(pill_x, pill_y, pill_w, pill_h,
fill_color=C_BRAND_PURPLE)
self.set_xy(pill_x, pill_y)
self.set_font('Helvetica', 'B', 9)
self.set_text_color(*C_WHITE)
self.cell(pill_w, pill_h, label.upper(), align='C')
self.ln(pill_h + 3)
self.set_text_color(*C_BODY)
def _chapter_card(self, chapter: str):
"""Light teal card behind chapter heading."""
card_x = self.l_margin
card_y = self.get_y()
card_w = self.epw # effective page width
card_h = 9
# Light teal fill
self.set_fill_color(230, 255, 252)
self.set_draw_color(*C_BRAND_TEAL)
self.set_line_width(0.4)
self.rounded_rect(card_x, card_y, card_w, card_h, 2, style='FD')
self.set_xy(card_x + 3, card_y + 1.5)
self.set_font('Helvetica', 'B', 10)
self.set_text_color(*C_CHAPTER_BLU)
self.cell(card_w - 6, 6, f' Chapter: {_safe_latin1(chapter)}')
self.ln(card_h + 2)
self.set_text_color(*C_BODY)
def _body_text(self, text: str):
"""
Render body text with LaTeX-like paragraph handling.
Lines starting with '-', '*', or a number followed by '.' are bullet points.
Lines with ALL CAPS or ending with ':' are treated as sub-headings.
"""
paragraphs = text.split('\n')
self.set_font('Helvetica', '', 9.5)
self.set_text_color(*C_BODY)
for para in paragraphs:
para = para.strip()
if not para:
self.ln(2.5)
continue
# Horizontal rule placeholder
if para.startswith('---'):
self._hline(C_LIGHT_GREY, 0.2)
self.ln(2)
continue
# Sub-heading detection: ends with ':' or ALL-CAPS short line
is_subhead = (
(para.endswith(':') and len(para) < 80) or
(para.isupper() and len(para) < 60)
)
if is_subhead:
self.ln(1)
self.set_font('Helvetica', 'B', 9.5)
self.set_text_color(*C_BRAND_PURPLE)
self.multi_cell(0, 5.5, para, align='L')
self.set_font('Helvetica', '', 9.5)
self.set_text_color(*C_BODY)
self.ln(0.5)
continue
# Bullet points
if re.match(r'^[-*\u2022]\s+', para):
bullet_text = re.sub(r'^[-*\u2022]\s+', '', para)
self.set_x(self.l_margin + 5)
self.set_font('Helvetica', '', 9.5)
self.cell(4, 5.5, '-')
self.multi_cell(self.epw - 9, 5.5, _safe_latin1(bullet_text), align='L')
continue
# Numbered list
if re.match(r'^\d+[.)]\s+', para):
self.set_x(self.l_margin + 2)
self.multi_cell(0, 5.5, _safe_latin1(para), align='L')
continue
# Normal paragraph β€” justified
self.multi_cell(0, 5.5, _safe_latin1(para), align='J')
self.ln(1)
# ─── Cover Page ─────────────────────────────────────────────────────────────────
def _draw_cover(pdf: BrandedPDF, channel_name: str,
content_type_label: str, week_range: str):
"""
Draw a premium-looking cover page:
top accent bar | title block | meta block | branding block
"""
A4_W, A4_H = 210, 297
# ── Top accent bar (full width) ──
pdf.set_fill_color(*C_BRAND_PURPLE)
pdf.rect(0, 0, A4_W, 18, style='F')
# Brand name in the bar
pdf.set_xy(0, 4)
pdf.set_font('Helvetica', 'B', 11)
pdf.set_text_color(*C_WHITE)
pdf.cell(A4_W, 10, BRAND_NAME.upper() + ' | ' + BRAND_HANDLE, align='C')
# ── Second teal stripe ──
pdf.set_fill_color(*C_BRAND_TEAL)
pdf.rect(0, 18, A4_W, 4, style='F')
# ── Central title block ──
pdf.set_xy(20, 65)
pdf.set_font('Helvetica', 'B', 28)
pdf.set_text_color(*C_BRAND_DARK)
pdf.multi_cell(170, 14, _safe_latin1(content_type_label).upper(), align='C')
# Underline the title
title_y = pdf.get_y() + 2
pdf.set_draw_color(*C_BRAND_PURPLE)
pdf.set_line_width(1.2)
pdf.line(45, title_y, 165, title_y)
pdf.ln(10)
# Channel name
pdf.set_font('Helvetica', 'B', 16)
pdf.set_text_color(*C_BRAND_PURPLE)
pdf.cell(0, 12, _safe_latin1(channel_name), align='C', new_x='LMARGIN', new_y='NEXT')
# Week range
pdf.set_font('Helvetica', '', 12)
pdf.set_text_color(*C_MID_GREY)
pdf.cell(0, 8, week_range, align='C', new_x='LMARGIN', new_y='NEXT')
pdf.ln(6)
# Tagline
pdf.set_font('Helvetica', 'I', 12)
pdf.set_text_color(*C_GOLD)
pdf.cell(0, 8, BRAND_TAGLINE, align='C', new_x='LMARGIN', new_y='NEXT')
pdf.ln(40)
# ── Bottom branding box ──
box_y = A4_H - 70
pdf.set_fill_color(245, 245, 255)
pdf.set_draw_color(*C_BRAND_PURPLE)
pdf.set_line_width(0.5)
pdf.rounded_rect(20, box_y, A4_W - 40, 45, 4, style='FD')
pdf.set_xy(20, box_y + 6)
pdf.set_font('Helvetica', 'B', 11)
pdf.set_text_color(*C_BRAND_PURPLE)
pdf.cell(A4_W - 40, 8, 'JOIN OUR COMMUNITY', align='C', new_x='LMARGIN', new_y='NEXT')
pdf.set_x(20)
pdf.set_font('Helvetica', '', 10)
pdf.set_text_color(*C_BODY)
pdf.cell(A4_W - 40, 7,
'Daily Notes | Formula Sheets | PYQ Sessions | MCQ Polls',
align='C', new_x='LMARGIN', new_y='NEXT')
pdf.set_x(20)
pdf.set_font('Helvetica', 'B', 12)
pdf.set_text_color(*C_BRAND_TEAL)
pdf.cell(A4_W - 40, 9, BRAND_LINK, align='C', new_x='LMARGIN', new_y='NEXT')
pdf.set_x(20)
pdf.set_font('Helvetica', '', 9)
pdf.set_text_color(*C_MID_GREY)
pdf.cell(A4_W - 40, 7,
f'Generated: {datetime.now().strftime("%d %b %Y, %I:%M %p IST")}',
align='C')
# ── Bottom stripe ──
pdf.set_fill_color(*C_BRAND_TEAL)
pdf.rect(0, A4_H - 12, A4_W, 12, style='F')
pdf.set_xy(0, A4_H - 10)
pdf.set_font('Helvetica', 'I', 8)
pdf.set_text_color(*C_WHITE)
pdf.cell(A4_W, 8, 'Free for personal use. Share freely!', align='C')
# ─── Table of Contents ───────────────────────────────────────────────────────────
def _draw_toc(pdf: BrandedPDF, grouped: dict):
pdf.add_page()
pdf.set_font('Helvetica', 'B', 16)
pdf.set_text_color(*C_BRAND_PURPLE)
pdf.cell(0, 12, 'TABLE OF CONTENTS', new_x='LMARGIN', new_y='NEXT', align='C')
pdf.set_draw_color(*C_BRAND_PURPLE)
pdf.set_line_width(0.6)
pdf.line(18, pdf.get_y(), 192, pdf.get_y())
pdf.ln(6)
entry_num = 1
for subj, chapters in grouped.items():
pdf.set_font('Helvetica', 'B', 11)
pdf.set_text_color(*C_SECTION_RED)
pdf.cell(0, 8, f'{subj}', new_x='LMARGIN', new_y='NEXT')
pdf.set_font('Helvetica', '', 10)
pdf.set_text_color(*C_BODY)
for chap in chapters.keys():
safe_chap = _safe_latin1(chap)
# Dot leader
pdf.set_x(pdf.l_margin + 6)
pdf.cell(4, 6.5, str(entry_num) + '.')
pdf.cell(130, 6.5, safe_chap[:65])
entry_num += 1
pdf.ln(6.5)
pdf.ln(2)
# ─── Back / CTA page ─────────────────────────────────────────────────────────────
def _draw_back_page(pdf: BrandedPDF):
pdf.add_page()
A4_W = 210
pdf.ln(30)
pdf.set_font('Helvetica', 'B', 22)
pdf.set_text_color(*C_BRAND_PURPLE)
pdf.cell(0, 14, 'Keep Learning, Keep Growing!', align='C', new_x='LMARGIN', new_y='NEXT')
pdf.set_font('Helvetica', 'I', 13)
pdf.set_text_color(*C_MID_GREY)
pdf.cell(0, 9, BRAND_TAGLINE, align='C', new_x='LMARGIN', new_y='NEXT')
pdf.ln(20)
# Info box
box_y = pdf.get_y()
pdf.set_fill_color(240, 240, 255)
pdf.set_draw_color(*C_BRAND_PURPLE)
pdf.set_line_width(0.5)
pdf.rounded_rect(25, box_y, A4_W - 50, 80, 5, style='FD')
pdf.set_xy(25, box_y + 10)
pdf.set_font('Helvetica', 'B', 13)
pdf.set_text_color(*C_BRAND_PURPLE)
pdf.cell(A4_W - 50, 10, 'What we offer daily:', align='C', new_x='LMARGIN', new_y='NEXT')
items = [
'[NOTE] Short Notes & Formula Sheets',
'[TARGET] PYQ Questions with Solutions',
'[BRAIN] Memory Tricks & Mnemonics',
'[FIRE] MCQ Poll Sessions (10 Questions)',
'[TIP] Concept Recaps & Mock Questions',
]
pdf.set_font('Helvetica', '', 11)
pdf.set_text_color(*C_BODY)
for item in items:
pdf.set_x(35)
pdf.cell(A4_W - 70, 9, item, new_x='LMARGIN', new_y='NEXT')
pdf.ln(25)
pdf.set_font('Helvetica', 'B', 16)
pdf.set_text_color(*C_BRAND_TEAL)
pdf.cell(0, 12, BRAND_LINK, align='C', new_x='LMARGIN', new_y='NEXT')
pdf.set_font('Helvetica', '', 10)
pdf.set_text_color(*C_MID_GREY)
pdf.cell(0, 8, 'Tap the link in Telegram to join!', align='C')
# Bottom bar
pdf.set_fill_color(*C_BRAND_PURPLE)
pdf.rect(0, 285, A4_W, 12, style='F')
pdf.set_xy(0, 287)
pdf.set_font('Helvetica', 'I', 8)
pdf.set_text_color(*C_WHITE)
pdf.cell(A4_W, 8, f'{BRAND_NAME} | {BRAND_LINK} | Free to share!', align='C')
# ─── Public API ──────────────────────────────────────────────────────────────────
def create_digest_pdf(channel_name: str, content_type_label: str,
archive_items: list) -> str:
"""
Creates a branded, LaTeX-inspired chapter-wise PDF from archived posts.
Args:
channel_name: Human-readable channel label (e.g. "JEE Advanced Daily")
content_type_label: e.g. "Short Notes" or "Formula Sheet"
archive_items: List of dicts: [{subject, chapter, text, date}, ...]
Returns:
Absolute path to the generated PDF, or None on failure.
"""
if not archive_items:
logger.warning("create_digest_pdf called with empty archive_items")
return None
try:
pdf = BrandedPDF(channel_name, content_type_label)
# ── Cover page (page 1) ──
pdf.add_page()
now = datetime.now()
week_start = now.strftime("%d %b") # approximate β€” Sunday digest
week_range = f'Week of {week_start} {now.year}'
_draw_cover(pdf, channel_name, f'Weekly {content_type_label}', week_range)
# ── Group archive by Subject β†’ Chapter ──
grouped: dict = {}
for item in archive_items:
subj = str(item.get('subject', 'General')).title()
chap = str(item.get('chapter', 'General'))
text = str(item.get('text', ''))
grouped.setdefault(subj, {}).setdefault(chap, []).append(text)
# ── Table of Contents (page 2) ──
_draw_toc(pdf, grouped)
# ── Content pages ──
for subj, chapters in grouped.items():
pdf.add_page()
# Subject section header
pdf.ln(2)
pdf.set_font('Helvetica', 'B', 14)
pdf.set_text_color(*C_SECTION_RED)
pdf._section_pill(subj)
pdf.set_draw_color(*C_SECTION_RED)
pdf.set_line_width(0.5)
pdf.line(pdf.l_margin, pdf.get_y(), 192, pdf.get_y())
pdf.ln(5)
for chap, texts in chapters.items():
# Chapter card
pdf._chapter_card(chap)
# Body content
for raw_text in texts:
cleaned = _clean(raw_text)
if not cleaned:
continue
pdf._body_text(cleaned)
pdf.ln(3)
# Thin separator between chapters
pdf.set_draw_color(*C_LIGHT_GREY)
pdf.set_line_width(0.2)
pdf.line(pdf.l_margin, pdf.get_y(), 192, pdf.get_y())
pdf.ln(6)
# ── Back / CTA page ──
_draw_back_page(pdf)
# ── Save ──
output_dir = "data/digests"
os.makedirs(output_dir, exist_ok=True)
timestamp = datetime.now().strftime("%Y%m%d_%H%M")
safe_ch = re.sub(r'[^\w]', '_', channel_name)
safe_ct = re.sub(r'[^\w]', '_', content_type_label)
filename = f"CrazyLearners_{safe_ch}_{safe_ct}_{timestamp}.pdf"
file_path = os.path.join(os.getcwd(), output_dir, filename)
pdf.output(file_path)
logger.info(f"[OK] Branded PDF generated: {file_path} ({len(archive_items)} items)")
return file_path
except Exception as e:
logger.error(f"[ERR] PDF generation failed: {e}", exc_info=True)
return None