awacke1 commited on
Commit
39e6451
Β·
verified Β·
1 Parent(s): 1f6e4e7

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +42 -8
app.py CHANGED
@@ -347,7 +347,7 @@ def create_pdf_preview(pdf_path: Path):
347
 
348
  # --- Main API Function ---
349
  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)):
350
- if not files and not ai_content.strip(): raise gr.Error("Please conjure some content or upload an image before alchemizing!")
351
  if not layouts: raise gr.Error("You must select a scroll (page layout)!")
352
  if not fonts: raise gr.Error("A scribe needs a font! Please choose one.")
353
  if not EMOJI_FONT_PATH: raise gr.Error("CRITICAL: Cannot generate PDFs. 'NotoColorEmoji-Regular.ttf' not found. Please add it to the app directory.")
@@ -355,10 +355,34 @@ def generate_pdfs_api(files, ai_content, layouts, fonts, num_columns, header_tex
355
  shutil.rmtree(OUTPUT_DIR, ignore_errors=True); shutil.rmtree(PREVIEW_DIR, ignore_errors=True)
356
  OUTPUT_DIR.mkdir(); PREVIEW_DIR.mkdir()
357
 
358
- md_content = ai_content if ai_content and ai_content.strip() else ""
359
- image_files = [Path(f.name) for f in files if Path(f.name).suffix.lower() in ['.png', '.jpg', '.jpeg']] if files else []
360
-
361
- log_updates, generated_pdf_paths = "", []
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
362
 
363
  # Clear emoji cache for each run to save memory
364
  EMOJI_IMAGE_CACHE.clear()
@@ -367,6 +391,7 @@ def generate_pdfs_api(files, ai_content, layouts, fonts, num_columns, header_tex
367
  for font_name in progress.tqdm(fonts, desc=f" enchanting scrolls with {layout_name}..."):
368
  merger = PdfWriter()
369
 
 
370
  if md_content:
371
  md_buffer = io.BytesIO()
372
  story, title = markdown_to_story(md_content, font_name, EMOJI_FONT_NAME, font_size_body, font_size_h1, font_size_h2, font_size_h3)
@@ -387,6 +412,7 @@ def generate_pdfs_api(files, ai_content, layouts, fonts, num_columns, header_tex
387
  md_buffer.seek(0)
388
  merger.append(fileobj=md_buffer)
389
 
 
390
  for img_path in image_files:
391
  try:
392
  with Image.open(img_path) as img: img_width_px, img_height_px = img.size
@@ -398,6 +424,14 @@ def generate_pdfs_api(files, ai_content, layouts, fonts, num_columns, header_tex
398
  merger.append(fileobj=img_buffer)
399
  except Exception as e: log_updates += f"⚠️ Failed to process image {img_path.name}: {e}\n"
400
 
 
 
 
 
 
 
 
 
401
  if len(merger.pages) > 0:
402
  time_str = datetime.datetime.now().strftime('%H%M%S')
403
  clean_layout = layout_name.replace(' ', '')
@@ -455,11 +489,11 @@ with gr.Blocks(theme=theme, title="The PDF Alchemist") as demo:
455
  gr.Markdown("### πŸ€– The Idea Golem")
456
  ai_prompt = gr.Textbox(label="Command the Golem", placeholder="e.g., 'A recipe for a dragon's breath chili...'")
457
  generate_ai_btn = gr.Button("🧠 Animate Golem!")
458
- ai_content_output = gr.Textbox(label="Golem's Manuscript (Editable)", lines=15, interactive=True)
459
  gr.Markdown("<hr style='border-color: #374151;'>")
460
  gr.Markdown("### πŸ“€ Or, Upload Your Treasures")
461
- uploaded_files = gr.File(label="Upload Images (.png, .jpg)", file_count="multiple", file_types=[".png", ".jpg", ".jpeg"])
462
- gr.Markdown("*<p style='font-size:0.8rem; color: #9ca3af;'>Note: The Golem's manuscript takes precedence. Images are always added.</p>*")
463
 
464
  with gr.TabItem("β‘‘ Define Your Canvas 🎨"):
465
  gr.Markdown("### πŸ“ Choose Your Scroll")
 
347
 
348
  # --- Main API Function ---
349
  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)):
350
+ 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!")
351
  if not layouts: raise gr.Error("You must select a scroll (page layout)!")
352
  if not fonts: raise gr.Error("A scribe needs a font! Please choose one.")
353
  if not EMOJI_FONT_PATH: raise gr.Error("CRITICAL: Cannot generate PDFs. 'NotoColorEmoji-Regular.ttf' not found. Please add it to the app directory.")
 
355
  shutil.rmtree(OUTPUT_DIR, ignore_errors=True); shutil.rmtree(PREVIEW_DIR, ignore_errors=True)
356
  OUTPUT_DIR.mkdir(); PREVIEW_DIR.mkdir()
357
 
358
+ # Separate uploaded files by type
359
+ image_files, pdf_files, txt_files = [], [], []
360
+ if files:
361
+ for f in files:
362
+ file_path = Path(f.name)
363
+ ext = file_path.suffix.lower()
364
+ if ext in ['.png', '.jpg', '.jpeg', '.gif', '.bmp', '.tiff']:
365
+ image_files.append(file_path)
366
+ elif ext == '.pdf':
367
+ pdf_files.append(file_path)
368
+ elif ext == '.txt':
369
+ txt_files.append(file_path)
370
+
371
+ log_updates = ""
372
+ # Consolidate all text content
373
+ all_text_content = []
374
+ if ai_content and "Golem awaits" not in ai_content:
375
+ all_text_content.append(ai_content)
376
+
377
+ for txt_path in txt_files:
378
+ try:
379
+ all_text_content.append(txt_path.read_text(encoding='utf-8'))
380
+ except Exception as e:
381
+ log_updates += f"⚠️ Failed to read text file {txt_path.name}: {e}\n"
382
+
383
+ md_content = "\n\n---\n\n".join(all_text_content)
384
+
385
+ generated_pdf_paths = []
386
 
387
  # Clear emoji cache for each run to save memory
388
  EMOJI_IMAGE_CACHE.clear()
 
391
  for font_name in progress.tqdm(fonts, desc=f" enchanting scrolls with {layout_name}..."):
392
  merger = PdfWriter()
393
 
394
+ # 1. Process main text content (AI + TXT)
395
  if md_content:
396
  md_buffer = io.BytesIO()
397
  story, title = markdown_to_story(md_content, font_name, EMOJI_FONT_NAME, font_size_body, font_size_h1, font_size_h2, font_size_h3)
 
412
  md_buffer.seek(0)
413
  merger.append(fileobj=md_buffer)
414
 
415
+ # 2. Append image files
416
  for img_path in image_files:
417
  try:
418
  with Image.open(img_path) as img: img_width_px, img_height_px = img.size
 
424
  merger.append(fileobj=img_buffer)
425
  except Exception as e: log_updates += f"⚠️ Failed to process image {img_path.name}: {e}\n"
426
 
427
+ # 3. Append PDF files
428
+ for pdf_path in pdf_files:
429
+ try:
430
+ merger.append(str(pdf_path))
431
+ except Exception as e:
432
+ log_updates += f"⚠️ Failed to merge PDF {pdf_path.name}: {e}\n"
433
+
434
+ # 4. Write the final merged PDF
435
  if len(merger.pages) > 0:
436
  time_str = datetime.datetime.now().strftime('%H%M%S')
437
  clean_layout = layout_name.replace(' ', '')
 
489
  gr.Markdown("### πŸ€– The Idea Golem")
490
  ai_prompt = gr.Textbox(label="Command the Golem", placeholder="e.g., 'A recipe for a dragon's breath chili...'")
491
  generate_ai_btn = gr.Button("🧠 Animate Golem!")
492
+ ai_content_output = gr.Textbox(label="Golem's Manuscript (Editable)", lines=15, interactive=True, value="# The Golem awaits your command!\n\n")
493
  gr.Markdown("<hr style='border-color: #374151;'>")
494
  gr.Markdown("### πŸ“€ Or, Upload Your Treasures")
495
+ uploaded_files = gr.File(label="Upload Files (Images, PDFs, TXT)", file_count="multiple", file_types=['.png', '.jpg', '.jpeg', '.gif', '.bmp', '.tiff', '.pdf', '.txt'])
496
+ gr.Markdown("*<p style='font-size:0.8rem; color: #9ca3af;'>Note: The Golem's manuscript and .txt files are combined. Images and PDF pages are appended after the text content.</p>*")
497
 
498
  with gr.TabItem("β‘‘ Define Your Canvas 🎨"):
499
  gr.Markdown("### πŸ“ Choose Your Scroll")