File size: 29,260 Bytes
e13b6e9
 
 
 
 
 
96b5748
cbf77e5
96b5748
 
cbf77e5
04a1711
96b5748
1f6e4e7
e13b6e9
96b5748
e13b6e9
96b5748
e13b6e9
 
04a1711
e13b6e9
 
 
96b5748
 
 
 
 
 
 
 
 
e13b6e9
04a1711
5fe90b3
 
e13b6e9
 
 
 
96b5748
 
1f6e4e7
 
 
 
96b5748
 
1f6e4e7
96b5748
 
 
 
04a1711
 
1f6e4e7
 
 
 
 
04a1711
96b5748
 
 
 
 
 
 
 
 
 
 
 
 
 
 
04a1711
96b5748
 
 
 
 
 
 
 
 
 
 
 
 
1f6e4e7
 
 
 
 
 
 
 
 
 
 
96b5748
1f6e4e7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
96b5748
04a1711
96b5748
04a1711
96b5748
04a1711
96b5748
04a1711
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1f6e4e7
e13b6e9
96b5748
04a1711
 
 
 
 
 
 
 
1f6e4e7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
96b5748
 
182d632
96b5748
 
 
04a1711
96b5748
 
5fe90b3
96b5748
 
 
04a1711
 
 
 
96b5748
 
 
04a1711
96b5748
 
 
 
 
 
 
 
 
 
1f6e4e7
 
 
 
 
 
 
 
 
 
 
 
04a1711
 
1f6e4e7
04a1711
 
 
 
 
96b5748
 
1f6e4e7
 
96b5748
04a1711
5fe90b3
1f6e4e7
96b5748
5fe90b3
e13b6e9
04a1711
 
 
 
 
1f6e4e7
 
 
5fe90b3
1f6e4e7
 
 
 
 
 
 
 
 
 
 
04a1711
 
cbf77e5
e13b6e9
04a1711
e13b6e9
 
04a1711
 
 
 
 
96b5748
 
04a1711
 
 
 
 
 
e13b6e9
96b5748
04a1711
39e6451
04a1711
 
1f6e4e7
5fe90b3
e13b6e9
 
 
39e6451
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
04a1711
1f6e4e7
 
 
04a1711
 
 
 
39e6451
04a1711
 
 
 
96b5748
04a1711
 
 
 
 
 
 
 
 
 
 
 
 
 
 
39e6451
04a1711
 
 
 
96b5748
04a1711
 
 
96b5748
04a1711
 
39e6451
 
 
 
 
 
 
 
04a1711
 
 
 
 
 
 
 
96b5748
 
 
e13b6e9
04a1711
e13b6e9
96b5748
e13b6e9
 
04a1711
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
aa6da1a
04a1711
 
aa6da1a
e13b6e9
aa6da1a
 
 
 
04a1711
aa6da1a
 
 
 
 
39e6451
aa6da1a
 
 
 
 
04a1711
 
 
aa6da1a
 
 
04a1711
 
 
aa6da1a
 
 
04a1711
 
 
 
 
 
 
aa6da1a
 
04a1711
 
 
 
 
 
 
 
 
aa6da1a
04a1711
 
aa6da1a
04a1711
 
 
 
 
96b5748
04a1711
 
 
 
 
 
 
 
 
 
 
e13b6e9
 
04a1711
 
1f6e4e7
04a1711
1f6e4e7
04a1711
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
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
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
import gradio as gr
from pathlib import Path
import datetime
import re
import os
import shutil
import fitz  # PyMuPDF
from PIL import Image
from collections import defaultdict
import io
from pypdf import PdfWriter
import random

from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer, Table, TableStyle, PageBreak, BaseDocTemplate, Frame, PageTemplate, Image as ReportLabImage, Flowable
from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
from reportlab.lib.pagesizes import letter, A4, legal, landscape
from reportlab.lib.units import inch
from reportlab.lib import colors
from reportlab.pdfbase import pdfmetrics
from reportlab.pdfbase.ttfonts import TTFont
from functools import partial

# --- Configuration & Setup ---
CWD = Path.cwd()
LAYOUTS = {
    "A4 Portrait": {"size": A4},
    "A4 Landscape": {"size": landscape(A4)},
    "Letter Portrait": {"size": letter},
    "Letter Landscape": {"size": landscape(letter)},
    "Legal Portrait": {"size": legal},
    "Legal Landscape": {"size": landscape(legal)},
}
OUTPUT_DIR = CWD / "generated_pdfs"
PREVIEW_DIR = CWD / "previews"
FONT_DIR = CWD # Assumes fonts are in the same directory as the script

# Create necessary directories
OUTPUT_DIR.mkdir(exist_ok=True)
PREVIEW_DIR.mkdir(exist_ok=True)


# --- Font & Emoji Handling ---

# Global cache for rendered emoji images to avoid re-rendering the same emoji
EMOJI_IMAGE_CACHE = {}
EMOJI_FONT_PATH = None # Will be set in register_local_fonts

def register_local_fonts():
    """Finds and registers all .ttf files from the application's base directory."""
    global EMOJI_FONT_PATH
    print("--- Font Registration Process Starting ---")
    text_font_names = []
    emoji_font_name = None
    
    noto_emoji_path = FONT_DIR / "NotoColorEmoji-Regular.ttf"
    if not noto_emoji_path.exists():
        print(f"CRITICAL: Color Emoji font not found at {noto_emoji_path}.")
        print("Please download 'NotoColorEmoji-Regular.ttf' and place it in the application directory for color emojis to work.")
    else:
        EMOJI_FONT_PATH = str(noto_emoji_path)


    print(f"Scanning for fonts in: {FONT_DIR.absolute()}")
    font_files = list(FONT_DIR.glob("*.ttf"))
    print(f"Found {len(font_files)} .ttf files: {[f.name for f in font_files]}")

    for font_path in font_files:
        try:
            font_name = font_path.stem
            pdfmetrics.registerFont(TTFont(font_name, str(font_path)))
            pdfmetrics.registerFont(TTFont(f"{font_name}-Bold", str(font_path)))
            pdfmetrics.registerFont(TTFont(f"{font_name}-Italic", str(font_path)))
            pdfmetrics.registerFont(TTFont(f"{font_name}-BoldItalic", str(font_path)))
            pdfmetrics.registerFontFamily(font_name, normal=font_name, bold=f"{font_name}-Bold", italic=f"{font_name}-Italic", boldItalic=f"{font_name}-BoldItalic")

            if "notocoloremoji-regular" in font_name.lower():
                emoji_font_name = font_name
            elif "notoemoji" not in font_name.lower():
                text_font_names.append(font_name)
        except Exception as e:
            print(f"Could not register font {font_path.name}: {e}")

    if not text_font_names:
        print("WARNING: No text fonts found. Adding 'Helvetica' as a default.")
        text_font_names.append('Helvetica')

    print(f"Successfully registered user-selectable fonts: {text_font_names}")
    print(f"Emoji font set to: {emoji_font_name}")
    print("--- Font Registration Process Finished ---")
    return sorted(text_font_names), emoji_font_name

def render_emoji_as_image(emoji_char, size_pt):
    """
    Renders a single emoji character as a transparent PNG image in memory using PyMuPDF.
    This is the magic to get color emojis into the PDF.
    """
    if not EMOJI_FONT_PATH:
        return None # Cannot render without the font file
    
    # Check cache first
    if (emoji_char, size_pt) in EMOJI_IMAGE_CACHE:
        return EMOJI_IMAGE_CACHE[(emoji_char, size_pt)]

    try:
        # Use fitz to draw the emoji with its color font onto a temporary surface
        rect = fitz.Rect(0, 0, size_pt * 1.5, size_pt * 1.5)
        doc = fitz.open()
        page = doc.new_page(width=rect.width, height=rect.height)
        
        # Insert the text with the color emoji font
        page.insert_font(fontname="emoji", fontfile=EMOJI_FONT_PATH)
        page.insert_text(fitz.Point(0, size_pt * 1.1), emoji_char, fontname="emoji", fontsize=size_pt)
        
        # Render to a pixmap (PNG)
        pix = page.get_pixmap(alpha=True, dpi=300) # High DPI for quality
        doc.close()

        # Convert to a PIL Image and save to a byte buffer
        img_buffer = io.BytesIO(pix.tobytes("png"))
        img_buffer.seek(0)

        # Cache the result
        EMOJI_IMAGE_CACHE[(emoji_char, size_pt)] = img_buffer
        return img_buffer

    except Exception as e:
        print(f"Could not render emoji {emoji_char}: {e}")
        return None

# --- AI Content Generation (Simulation) ---

def generate_ai_content_api(prompt):
    """
    Simulates a call to an LLM to generate markdown content.
    """
    if not prompt:
        return "# The Golem awaits your command!\n\nPlease enter a prompt in the box above and click '๐Ÿง  Animate Golem!' to get started. I can help you write reports, stories, poems, and more! โœจ"

    import time
    time.sleep(1.5)

    sample_story = f"""
# The Quest for the Sunstone โ˜€๏ธ

Long ago, in the mystical land of Aerthos, a creeping shadow began to fall across the valleys. The once-vibrant flowers ๐ŸŒธ drooped, and the rivers ran slow. The elders knew the cause: the light of the Sunstone, hidden deep within Mount Cinder, was fading.

## The Prophecy ๐Ÿ“œ

An ancient prophecy spoke of a hero who would rekindle the stone. It read:
> When darkness drapes the verdant ground,
> A soul of courage shall be found.
> Through trials of fire ๐Ÿ”ฅ, wit, and might,
> They'll bring once more the sacred light.

## The Chosen One ๐Ÿฆธโ€โ™€๏ธ

A young woman named Elara, known for her kindness and bravery, was chosen. She accepted the quest, her only companions a loyal wolf ๐Ÿบ and a map gifted by the village shaman.

### The Journey Begins
Elara's journey was fraught with peril. She navigated enchanted forests and crossed treacherous chasms.

| Trial            | Location          | Challenge                              |
|------------------|-------------------|----------------------------------------|
| The Whispering   | The Gloomwood     | Resist maddening whispers of despair   |
| The Riddle of    | Sphinx Gate       | Answer three impossible questions      |
| The Fiery Path   | The Magma Caverns | Walk barefoot across burning embers    |

Finally, she reached the heart of the mountain. There, resting on a pedestal, was the dim Sunstone. Pouring her own hope and courage into it, the stone blazed with renewed life, banishing the shadows from Aerthos forever. The people rejoiced, and Elara became a legend.
"""
    return f"# Golem's Vision for: '{prompt}'\n\n{sample_story}"


# --- PDF Generation & Handling ---

def _draw_header_footer(canvas, doc, header_text, footer_text, title):
    """Draws the header and footer on each page."""
    canvas.saveState()
    page_num = canvas.getPageNumber()
    
    final_footer_text = footer_text.replace("[Page #]", str(page_num)).replace("[Total Pages]", str(doc.page))
    final_header_text = header_text.replace("[Page #]", str(page_num)).replace("[Title]", title)

    if final_header_text:
        canvas.setFont('Helvetica', 9)
        canvas.setFillColor(colors.grey)
        canvas.drawRightString(doc.width + doc.leftMargin, doc.height + doc.topMargin + 0.25*inch, final_header_text)

    if final_footer_text:
        canvas.setFont('Helvetica', 9)
        canvas.setFillColor(colors.grey)
        canvas.drawString(doc.leftMargin, doc.bottomMargin - 0.25*inch, final_footer_text)

    canvas.restoreState()

def markdown_to_story(markdown_text: str, font_name: str, emoji_font: str, font_size_body: int, font_size_h1: int, font_size_h2: int, font_size_h3: int):
    """Converts markdown to a ReportLab story, turning emojis into inline images for full color support."""
    styles = getSampleStyleSheet()
    
    leading_body = font_size_body * 1.4
    style_normal = ParagraphStyle('BodyText', fontName=font_name, fontSize=font_size_body, leading=leading_body, spaceAfter=6)
    style_h1 = ParagraphStyle('h1', parent=styles['h1'], fontName=font_name, fontSize=font_size_h1, leading=font_size_h1*1.2, spaceBefore=12, textColor=colors.HexColor("#a855f7"))
    style_h2 = ParagraphStyle('h2', parent=styles['h2'], fontName=font_name, fontSize=font_size_h2, leading=font_size_h2*1.2, spaceBefore=10, textColor=colors.HexColor("#6366f1"))
    style_h3 = ParagraphStyle('h3', parent=styles['h3'], fontName=font_name, fontSize=font_size_h3, leading=font_size_h3*1.2, spaceBefore=8, textColor=colors.HexColor("#3b82f6"))
    style_code = ParagraphStyle('Code', fontName='Courier', backColor=colors.HexColor("#333333"), textColor=colors.HexColor("#f472b6"), borderWidth=1, borderColor=colors.HexColor("#444444"), padding=8, leading=12, fontSize=9)
    style_table_header = ParagraphStyle('TableHeader', parent=style_normal, fontName=f"{font_name}-Bold" if font_name != 'Helvetica' else 'Helvetica-Bold')

    # This regex is the key: it finds and captures all emoji sequences.
    emoji_pattern = re.compile(f"([{re.escape(''.join(map(chr, range(0x1f600, 0x1f650))))}"
                               f"{re.escape(''.join(map(chr, range(0x1f300, 0x1f5ff))))}"
                               f"{re.escape(''.join(map(chr, range(0x1f900, 0x1f9ff))))}"
                               f"{re.escape(''.join(map(chr, range(0x2600, 0x26ff))))}"
                               f"{re.escape(''.join(map(chr, range(0x2700, 0x27bf))))}]+)")

    def create_flowables_for_line(text, style):
        """Splits a line of text into text and emoji images, returning a list of flowables."""
        parts = emoji_pattern.split(text)
        flowables = []
        for part in parts:
            if not part: continue
            if emoji_pattern.match(part):
                # It's an emoji, render it as an image
                for emoji_char in part: # Render one by one in case they are clumped
                    img_buffer = render_emoji_as_image(emoji_char, style.fontSize)
                    if img_buffer:
                        # Create an image that is sized relative to the font
                        img = ReportLabImage(img_buffer, height=style.fontSize * 1.2, width=style.fontSize * 1.2)
                        flowables.append(img)
            else:
                # It's regular text, create a Paragraph
                # Apply markdown for bold/italic within this text segment
                formatted_part = re.sub(r'_(.*?)_', r'<i>\1</i>', re.sub(r'\*\*(.*?)\*\*', r'<b>\1</b>', part))
                flowables.append(Paragraph(formatted_part, style))
        
        if not flowables:
            return [Spacer(0, 0)]
            
        # Use a table to keep all flowables on the same line(s)
        table = Table([flowables], colWidths=[None]*len(flowables))
        table.setStyle(TableStyle([('VALIGN', (0,0), (-1,-1), 'MIDDLE'),
                                     ('LEFTPADDING', (0,0), (-1,-1), 0),
                                     ('RIGHTPADDING', (0,0), (-1,-1), 0),
                                     ]))
        return [table]

    story = []
    lines = markdown_text.split('\n')
    
    in_code_block, in_table = False, False
    code_block_text, table_data = "", []
    first_heading = True
    document_title = "Untitled Document"

    for line in lines:
        stripped_line = line.strip()

        if stripped_line.startswith("```"):
            if in_code_block:
                escaped_code = code_block_text.replace('&', '&amp;').replace('<', '&lt;').replace('>', '&gt;')
                story.append(Paragraph(escaped_code.replace('\n', '<br/>'), style_code))
                story.append(Spacer(1, 0.1 * inch))
                in_code_block, code_block_text = False, ""
            else: in_code_block = True
            continue
        if in_code_block:
            code_block_text += line + '\n'; continue
        
        if stripped_line.startswith('|'):
            if not in_table: in_table = True
            if all(c in '-|: ' for c in stripped_line): continue
            cells = [cell.strip() for cell in stripped_line.strip('|').split('|')]
            table_data.append(cells)
            continue
        if in_table:
            in_table = False
            if table_data:
                # Table processing needs to create flowables for each cell
                processed_table_data = []
                for row in table_data:
                    processed_row = [create_flowables_for_line(cell, style_normal)[0] for cell in row]
                    processed_table_data.append(processed_row)

                # Style header separately
                header_row = [create_flowables_for_line(cell, style_table_header)[0] for cell in table_data[0]]

                final_table_data = [header_row] + processed_table_data[1:]

                table = Table(final_table_data, hAlign='LEFT', repeatRows=1)
                table.setStyle(TableStyle([
                    ('BACKGROUND', (0, 0), (-1, 0), colors.HexColor("#4a044e")),
                    ('TEXTCOLOR', (0, 0), (-1, 0), colors.whitesmoke), # Note: this may not affect paragraphs
                    ('GRID', (0, 0), (-1, -1), 1, colors.HexColor("#6b21a8")),
                    ('VALIGN', (0,0), (-1,-1), 'MIDDLE'),
                    ('TOPPADDING', (0,0), (-1,-1), 6),
                    ('BOTTOMPADDING', (0,0), (-1,-1), 6),
                ]))
                story.append(table); story.append(Spacer(1, 0.2 * inch))
            table_data = []
            continue


        if not stripped_line: continue

        content, style, bullet_text = stripped_line, style_normal, None
        
        if stripped_line.startswith("# "):
            if not first_heading: story.append(PageBreak())
            content, style = stripped_line.lstrip('# '), style_h1
            if first_heading: document_title = content
            first_heading = False
        elif stripped_line.startswith("## "): content, style = stripped_line.lstrip('## '), style_h2
        elif stripped_line.startswith("### "): content, style = stripped_line.lstrip('### '), style_h3
        elif stripped_line.startswith(("- ", "* ")): 
            content = stripped_line[2:]
            bullet_text = 'โ€ข      ' # Using spaces for indentation
        
        # Now, process the content into flowables (text + emoji images)
        line_flowables = create_flowables_for_line(content, style)

        if bullet_text:
            # For lists, put the bullet and the content table in another table
            bullet_p = Paragraph(bullet_text, style)
            list_item_table = Table([[bullet_p] + line_flowables], colWidths=[style.fontSize*1.5] + [None]*len(line_flowables))
            list_item_table.setStyle(TableStyle([('VALIGN', (0,0), (-1,-1), 'TOP'), ('LEFTPADDING', (0,0), (-1,-1), 0), ('RIGHTPADDING', (0,0), (-1,-1), 0)]))
            story.append(list_item_table)
        else:
            story.extend(line_flowables)
        
    return story, document_title

def create_pdf_preview(pdf_path: Path):
    """Generates a PNG preview of the first page of a PDF."""
    preview_path = PREVIEW_DIR / f"{pdf_path.stem}.png"
    try:
        doc = fitz.open(pdf_path)
        page = doc.load_page(0)
        pix = page.get_pixmap(dpi=150)
        pix.save(str(preview_path))
        doc.close()
        return str(preview_path)
    except Exception as e:
        print(f"Could not create preview for {pdf_path.name}: {e}")
        try:
            img = Image.new('RGB', (400, 500), color = '#111827')
            img.save(str(preview_path))
            return str(preview_path)
        except: return None

# --- Main API Function ---
def generate_pdfs_api(files, ai_content, layouts, fonts, num_columns, header_text, footer_text, font_size_body, font_size_h1, font_size_h2, font_size_h3, margin_top, margin_bottom, margin_left, margin_right, progress=gr.Progress(track_tqdm=True)):
    if not files and (not ai_content or "Golem awaits" in ai_content): raise gr.Error("Please conjure some content or upload a file before alchemizing!")
    if not layouts: raise gr.Error("You must select a scroll (page layout)!")
    if not fonts: raise gr.Error("A scribe needs a font! Please choose one.")
    if not EMOJI_FONT_PATH: raise gr.Error("CRITICAL: Cannot generate PDFs. 'NotoColorEmoji-Regular.ttf' not found. Please add it to the app directory.")

    shutil.rmtree(OUTPUT_DIR, ignore_errors=True); shutil.rmtree(PREVIEW_DIR, ignore_errors=True)
    OUTPUT_DIR.mkdir(); PREVIEW_DIR.mkdir()

    # Separate uploaded files by type
    image_files, pdf_files, txt_files = [], [], []
    if files:
        for f in files:
            file_path = Path(f.name)
            ext = file_path.suffix.lower()
            if ext in ['.png', '.jpg', '.jpeg', '.gif', '.bmp', '.tiff']:
                image_files.append(file_path)
            elif ext == '.pdf':
                pdf_files.append(file_path)
            elif ext == '.txt':
                txt_files.append(file_path)

    log_updates = ""
    # Consolidate all text content
    all_text_content = []
    if ai_content and "Golem awaits" not in ai_content:
        all_text_content.append(ai_content)

    for txt_path in txt_files:
        try:
            all_text_content.append(txt_path.read_text(encoding='utf-8'))
        except Exception as e:
            log_updates += f"โš ๏ธ Failed to read text file {txt_path.name}: {e}\n"
    
    md_content = "\n\n---\n\n".join(all_text_content)
    
    generated_pdf_paths = []
    
    # Clear emoji cache for each run to save memory
    EMOJI_IMAGE_CACHE.clear()

    for layout_name in progress.tqdm(layouts, desc=" brewing potions..."):
        for font_name in progress.tqdm(fonts, desc=f" enchanting scrolls with {layout_name}..."):
            merger = PdfWriter()
            
            # 1. Process main text content (AI + TXT)
            if md_content:
                md_buffer = io.BytesIO()
                story, title = markdown_to_story(md_content, font_name, EMOJI_FONT_NAME, font_size_body, font_size_h1, font_size_h2, font_size_h3)
                pagesize = LAYOUTS[layout_name]["size"]
                
                doc = BaseDocTemplate(md_buffer, pagesize=pagesize,
                                      leftMargin=margin_left*inch, rightMargin=margin_right*inch,
                                      topMargin=margin_top*inch, bottomMargin=margin_bottom*inch)
                
                frame_width = (doc.width / num_columns) - (num_columns - 1) * 0.1*inch
                frames = [Frame(doc.leftMargin + i * (frame_width + 0.2*inch), doc.bottomMargin, frame_width, doc.height, id=f'col_{i}') for i in range(num_columns)]
                
                header_footer_callback = partial(_draw_header_footer, header_text=header_text, footer_text=footer_text, title=title)
                page_template = PageTemplate(id='main_template', frames=frames, onPage=header_footer_callback)
                doc.addPageTemplates([page_template])

                doc.build(story)
                md_buffer.seek(0)
                merger.append(fileobj=md_buffer)

            # 2. Append image files
            for img_path in image_files:
                try:
                    with Image.open(img_path) as img: img_width_px, img_height_px = img.size
                    img_width_pt, img_height_pt = img_width_px * (inch / 72), img_height_px * (inch / 72)
                    img_buffer = io.BytesIO()
                    img_doc = SimpleDocTemplate(img_buffer, pagesize=(img_width_pt, img_height_pt), leftMargin=0, rightMargin=0, topMargin=0, bottomMargin=0)
                    img_doc.build([ReportLabImage(img_path, width=img_width_pt, height=img_height_pt)])
                    img_buffer.seek(0)
                    merger.append(fileobj=img_buffer)
                except Exception as e: log_updates += f"โš ๏ธ Failed to process image {img_path.name}: {e}\n"

            # 3. Append PDF files
            for pdf_path in pdf_files:
                try:
                    merger.append(str(pdf_path))
                except Exception as e:
                    log_updates += f"โš ๏ธ Failed to merge PDF {pdf_path.name}: {e}\n"

            # 4. Write the final merged PDF
            if len(merger.pages) > 0:
                time_str = datetime.datetime.now().strftime('%H%M%S')
                clean_layout = layout_name.replace(' ', '')
                filename = f"Scroll_{clean_layout}_{font_name}_x{num_columns}_{time_str}.pdf"
                output_path = OUTPUT_DIR / filename
                with open(output_path, "wb") as f: merger.write(f)
                generated_pdf_paths.append(output_path)
                log_updates += f"โœ… Successfully alchemized: {filename}\n"

    gallery_previews = [create_pdf_preview(p) for p in generated_pdf_paths]
    final_gallery = [g for g in gallery_previews if g is not None]
    
    return final_gallery, log_updates if log_updates else "โœจ All scrolls alchemized successfully! โœจ", [str(p) for p in generated_pdf_paths]

# --- Gradio UI Definition ---
AVAILABLE_FONTS, EMOJI_FONT_NAME = register_local_fonts()

# A custom, magical theme
theme = gr.themes.Base(
    primary_hue=gr.themes.colors.purple,
    secondary_hue=gr.themes.colors.indigo,
    neutral_hue=gr.themes.colors.gray,
    font=(gr.themes.GoogleFont("MedievalSharp"), "ui-sans-serif", "system-ui", "sans-serif"),
).set(
    body_background_fill="#111827",
    body_background_fill_dark="#111827",
    body_text_color="#d1d5db",
    body_text_color_dark="#d1d5db",
    button_primary_background_fill="#a855f7",
    button_primary_background_fill_dark="#a855f7",
    button_primary_text_color="#ffffff",
    button_primary_text_color_dark="#ffffff",
    button_secondary_background_fill="#6366f1",
    button_secondary_background_fill_dark="#6366f1",
    button_secondary_text_color="#ffffff",
    button_secondary_text_color_dark="#ffffff",
    block_background_fill="#1f2937",
    block_background_fill_dark="#1f2937",
    block_label_background_fill="#1f2937",
    block_label_background_fill_dark="#1f2937",
    block_title_text_color="#a855f7",
    block_title_text_color_dark="#a855f7",
    input_background_fill="#374151",
    input_background_fill_dark="#374151",
)

with gr.Blocks(theme=theme, title="The PDF Alchemist") as demo:
    gr.Markdown("# โœจ The PDF Alchemist โœจ")
    gr.Markdown("A single-page grimoire to turn your ideas into beautifully crafted PDF scrolls. Use the power of AI or upload your own treasures.")

    with gr.Row(equal_height=False):
        # --- LEFT COLUMN: INPUTS & CONTROLS ---
        with gr.Column(scale=2):
            with gr.Group():
                with gr.Accordion("๐Ÿ“œ Content Crucible (Your Ingredients)", open=True):
                    gr.Markdown("### ๐Ÿค– Command Your Idea Golem")
                    ai_prompt = gr.Textbox(label="Incantation (Prompt)", placeholder="e.g., 'A recipe for a dragon's breath chili...'")
                    generate_ai_btn = gr.Button("๐Ÿง  Animate Golem!")
                    ai_content_output = gr.Textbox(label="Golem's Manuscript (Editable)", lines=10, interactive=True, value="# The Golem awaits your command!\n\n")
                    
                    gr.Markdown("<hr style='border-color: #374151; margin-top: 20px; margin-bottom: 20px;'>")
                    
                    gr.Markdown("### ๐Ÿ“ค Add Your Physical Treasures")
                    uploaded_files = gr.File(label="Upload Files (Images, PDFs, TXT)", file_count="multiple", file_types=['.png', '.jpg', '.jpeg', '.gif', '.bmp', '.tiff', '.pdf', '.txt'])
                    gr.Markdown("*<p style='font-size:0.8rem; color: #9ca3af;'>The Golem's manuscript and .txt files are combined. Images and PDF pages are appended after the text.</p>*")

            with gr.Group():
                with gr.Accordion("๐Ÿ“ Arcane Blueprints (Layout & Structure)", open=True):
                    gr.Markdown("### Page & Column Spells")
                    selected_layouts = gr.CheckboxGroup(choices=list(LAYOUTS.keys()), label="Page Layouts", value=["A4 Portrait"])
                    num_columns_slider = gr.Slider(label="Number of Text Columns", minimum=1, maximum=4, step=1, value=1)
                    
                    gr.Markdown("<hr style='border-color: #374151; margin-top: 20px; margin-bottom: 20px;'>")

                    gr.Markdown("### Header & Footer Runes")
                    gr.Markdown("<p style='font-size:0.8rem; color: #9ca3af;'>Use `[Page #]` and `[Title]`. `[Total Pages]` works best in the footer.</p>")
                    header_input = gr.Textbox(label="Header Inscription", value="[Title]", placeholder="e.g., Arcane Folio - [Page #]")
                    footer_input = gr.Textbox(label="Footer Inscription", value="Page [Page #] of [Total Pages]", placeholder="e.g., Top Secret - Page [Page #]")

            with gr.Group():
                with gr.Accordion("๐Ÿ’… Stylist's Sanctum (Fonts & Margins)", open=True):
                    gr.Markdown("### ๐Ÿ”ค Master the Glyphs")
                    selected_fonts = gr.CheckboxGroup(choices=AVAILABLE_FONTS, label="Fonts", value=[AVAILABLE_FONTS[0]] if AVAILABLE_FONTS else [])
                    font_size_body_slider = gr.Slider(label="Body Text Size (pt)", minimum=8, maximum=16, step=1, value=10)
                    with gr.Row():
                        font_size_h1_slider = gr.Slider(label="H1 Size", minimum=16, maximum=32, step=1, value=24)
                        font_size_h2_slider = gr.Slider(label="H2 Size", minimum=14, maximum=28, step=1, value=18)
                        font_size_h3_slider = gr.Slider(label="H3 Size", minimum=12, maximum=24, step=1, value=14)
                    
                    gr.Markdown("<hr style='border-color: #374151; margin-top: 20px; margin-bottom: 20px;'>")

                    gr.Markdown("### ๐Ÿ“ Set Your Boundaries (inches)")
                    with gr.Row():
                        margin_top_slider = gr.Slider(label="Top", minimum=0.25, maximum=1.5, step=0.05, value=0.75)
                        margin_bottom_slider = gr.Slider(label="Bottom", minimum=0.25, maximum=1.5, step=0.05, value=0.75)
                    with gr.Row():
                        margin_left_slider = gr.Slider(label="Left", minimum=0.25, maximum=1.5, step=0.05, value=0.75)
                        margin_right_slider = gr.Slider(label="Right", minimum=0.25, maximum=1.5, step=0.05, value=0.75)

            # --- Main Generate Button ---
            generate_pdfs_btn = gr.Button("๐Ÿ”ฎ Alchemize PDF!", variant="primary", size="lg")

        # --- RIGHT COLUMN: OUTPUTS ---
        with gr.Column(scale=3):
            gr.Markdown("### ๐Ÿ–ผ๏ธ The Scrying Pool (Previews)")
            gallery_output = gr.Gallery(label="Generated PDF Previews", show_label=False, elem_id="gallery", columns=2, height=700, object_fit="contain")
            log_output = gr.Markdown(label="Alchemist's Log", value="Your log of successful transmutations will appear here...")
            downloadable_files_output = gr.Files(label="Collect Your Scrolls")
            
    # --- API Calls & Examples ---
    generate_ai_btn.click(fn=generate_ai_content_api, inputs=[ai_prompt], outputs=[ai_content_output])
    
    inputs_list = [uploaded_files, ai_content_output, selected_layouts, selected_fonts, num_columns_slider, header_input, footer_input, font_size_body_slider, font_size_h1_slider, font_size_h2_slider, font_size_h3_slider, margin_top_slider, margin_bottom_slider, margin_left_slider, margin_right_slider]
    outputs_list = [gallery_output, log_output, downloadable_files_output]
    generate_pdfs_btn.click(fn=generate_pdfs_api, inputs=inputs_list, outputs=outputs_list)

    gr.Examples(
        examples=[["A technical summary of how alchemy works"], ["A short poem about a grumpy gnome"], ["A sample agenda for a wizard's council meeting"]],
        inputs=[ai_prompt], outputs=[ai_content_output], fn=generate_ai_content_api, cache_examples=False
    )

if __name__ == "__main__":
    if not (FONT_DIR / "NotoColorEmoji-Regular.ttf").exists():
        print("\n" + "="*80)
        print("CRITICAL WARNING: 'NotoColorEmoji-Regular.ttf' not found.")
        print("Please download it from Google Fonts and place it in the script's directory for emojis to render correctly.")
        print("The application will fail to generate PDFs without it.")
        print("="*80 + "\n")
    if not any("MedievalSharp" in s for s in AVAILABLE_FONTS):
        print("\n" + "="*80)
        print("WARNING: 'MedievalSharp' font not found for the default theme.")
        print("Please download it from Google Fonts to get the intended 'alchemist' look.")
        print("The app will fall back to another font.")
        print("="*80 + "\n")
    
    demo.launch(debug=True)