awacke1's picture
Update app.py
f83c4d5 verified
raw
history blame
16.9 kB
import io
import re
import streamlit as st
import glob
import os
from PIL import Image
import fitz
from reportlab.lib.pagesizes import A4
from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer, Table, TableStyle
from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
from reportlab.lib import colors
from reportlab.pdfbase import pdfmetrics
from reportlab.pdfbase.ttfonts import TTFont
import unicodedata
st.set_page_config(layout="wide", initial_sidebar_state="collapsed")
def create_pdf_tab(default_markdown):
# Dynamically load all .ttf fonts from the current directory
font_files = glob.glob("*.ttf")
if not font_files:
st.error("No .ttf font files found in the current directory. Please add some, e.g., NotoEmoji-Regular.ttf.")
return
available_fonts = {os.path.splitext(os.path.basename(f))[0]: f for f in font_files}
# Sidebar configuration
with st.sidebar:
selected_font_name = st.selectbox("Select Font", options=list(available_fonts.keys()), index=0 if "NotoEmoji-Regular" in available_fonts else 0)
selected_font_path = available_fonts[selected_font_name]
base_font_size = st.slider("Font Size (points)", min_value=6, max_value=16, value=9, step=1)
plain_text_mode = st.checkbox("Render as Plain Text (Preserve Bold Only)", value=False)
auto_bold_numbers = st.checkbox("Auto-Bold Numbered Lines", value=False)
num_columns = st.selectbox("Number of Columns", options=[1, 2, 3, 4, 5, 6], index=3)
if 'markdown_content' not in st.session_state:
st.session_state.markdown_content = default_markdown
edited_markdown = st.text_area("Modify the markdown content below:", value=st.session_state.markdown_content, height=300)
if st.button("Update PDF"):
st.session_state.markdown_content = edited_markdown
st.rerun()
st.download_button(label="Save Markdown", data=st.session_state.markdown_content, file_name="deities_guide.md", mime="text/markdown")
# Register the selected font and a fallback font
try:
pdfmetrics.registerFont(TTFont(selected_font_name, selected_font_path))
# Register a fallback font (e.g., Helvetica) for non-emoji text
pdfmetrics.registerFont(TTFont("Helvetica", "Helvetica.ttf")) # Ensure Helvetica is available
except Exception as e:
st.error(f"Failed to register font {selected_font_name}: {e}")
return
# Emoji font application with fallback
def apply_emoji_font(text, emoji_font):
emoji_pattern = re.compile(
r"([\U0001F300-\U0001F5FF" # Miscellaneous Symbols and Pictographs
r"\U0001F600-\U0001F64F" # Emoticons
r"\U0001F680-\U0001F6FF" # Transport and Map Symbols
r"\U0001F700-\U0001F77F" # Alchemical Symbols
r"\U0001F780-\U0001F7FF" # Geometric Shapes Extended
r"\U0001F800-\U0001F8FF" # Supplemental Arrows-C
r"\U0001F900-\U0001F9FF" # Supplemental Symbols and Pictographs
r"\U0001FA00-\U0001FA6F" # Chess Symbols
r"\U0001FA70-\U0001FAFF" # Symbols and Pictographs Extended-A
r"\u2600-\u26FF" # Miscellaneous Symbols (e.g., ⚡ U+26A1)
r"\u2700-\u27BF]+" # Dingbats (e.g., ✝ U+271D)
r")"
)
def replace_emoji(match):
emoji = match.group(1)
# Normalize emoji to avoid multi-codepoint issues (e.g., combining characters)
emoji = unicodedata.normalize('NFC', emoji)
# Wrap emoji in font tag; if it doesn’t render, it’ll fall back to text
return f'<font face="{emoji_font}">{emoji}</font>'
# Split text into segments: emoji and non-emoji
segments = []
last_pos = 0
for match in emoji_pattern.finditer(text):
start, end = match.span()
# Add non-emoji text with Helvetica
if last_pos < start:
segments.append(f'<font face="Helvetica">{text[last_pos:start]}</font>')
# Add emoji with the selected font
segments.append(replace_emoji(match))
last_pos = end
# Add remaining non-emoji text
if last_pos < len(text):
segments.append(f'<font face="Helvetica">{text[last_pos:]}</font>')
return ''.join(segments)
# Markdown to PDF content
def markdown_to_pdf_content(markdown_text, plain_text_mode, auto_bold_numbers):
lines = markdown_text.strip().split('\n')
pdf_content = []
number_pattern = re.compile(r'^\d+\.\s')
if plain_text_mode:
for line in lines:
line = line.strip()
if not line or line.startswith('# '):
continue
bold_pattern = re.compile(r'\*\*(.*?)\*\*')
line = bold_pattern.sub(r'<b>\1</b>', line)
pdf_content.append(line)
else:
for line in lines:
line = line.strip()
if not line or line.startswith('# '):
continue
if line.startswith('## ') or line.startswith('### '):
text = line.replace('## ', '').replace('### ', '').strip()
pdf_content.append(f"<b>{text}</b>")
elif auto_bold_numbers and number_pattern.match(line):
pdf_content.append(f"<b>{line}</b>")
else:
pdf_content.append(line.strip())
total_lines = len(pdf_content)
return pdf_content, total_lines
# Create PDF
def create_pdf(markdown_text, base_font_size, plain_text_mode, num_columns, auto_bold_numbers):
buffer = io.BytesIO()
page_width = A4[0] * 2
page_height = A4[1]
doc = SimpleDocTemplate(buffer, pagesize=(page_width, page_height), leftMargin=36, rightMargin=36, topMargin=36, bottomMargin=36)
styles = getSampleStyleSheet()
story = []
spacer_height = 10
section_spacer_height = 15
pdf_content, total_lines = markdown_to_pdf_content(markdown_text, plain_text_mode, auto_bold_numbers)
item_font_size = base_font_size
section_font_size = base_font_size * 1.1
# Define styles with explicit font names
section_style = ParagraphStyle(
'SectionStyle', parent=styles['Heading2'], fontName="Helvetica-Bold",
textColor=colors.darkblue, fontSize=section_font_size, leading=section_font_size * 1.2, spaceAfter=2
)
item_style = ParagraphStyle(
'ItemStyle', parent=styles['Normal'], fontName="Helvetica",
fontSize=item_font_size, leading=item_font_size * 1.15, spaceAfter=1
)
story.append(Spacer(1, spacer_height))
columns = [[] for _ in range(num_columns)]
lines_per_column = total_lines / num_columns if num_columns > 0 else total_lines
current_line_count = 0
current_column = 0
number_pattern = re.compile(r'^\d+\.\s')
for i, item in enumerate(pdf_content):
if i > 0 and number_pattern.match(item.replace('<b>', '').replace('</b>', '')):
columns[current_column].append(Spacer(1, section_spacer_height))
if current_line_count >= lines_per_column and current_column < num_columns - 1:
current_column += 1
current_line_count = 0
columns[current_column].append(item)
current_line_count += 1
column_cells = [[] for _ in range(num_columns)]
for col_idx, column in enumerate(columns):
for item in column:
if isinstance(item, Spacer):
column_cells[col_idx].append(item)
elif isinstance(item, str) and item.startswith('<b>'):
text = item.replace('<b>', '').replace('</b>', '')
column_cells[col_idx].append(Paragraph(apply_emoji_font(text, selected_font_name), section_style))
else:
column_cells[col_idx].append(Paragraph(apply_emoji_font(item, selected_font_name), item_style))
max_cells = max(len(cells) for cells in column_cells) if column_cells else 0
for cells in column_cells:
cells.extend([Paragraph("", item_style)] * (max_cells - len(cells)))
col_width = (page_width - 72) / num_columns if num_columns > 0 else page_width - 72
table_data = list(zip(*column_cells)) if column_cells else [[]]
table = Table(table_data, colWidths=[col_width] * num_columns, hAlign='CENTER')
table.setStyle(TableStyle([
('VALIGN', (0, 0), (-1, -1), 'TOP'), ('ALIGN', (0, 0), (-1, -1), 'LEFT'),
('BACKGROUND', (0, 0), (-1, -1), colors.white), ('GRID', (0, 0), (-1, -1), 0, colors.white),
('LINEAFTER', (0, 0), (num_columns-1, -1), 0.5, colors.grey),
('LEFTPADDING', (0, 0), (-1, -1), 2), ('RIGHTPADDING', (0, 0), (-1, -1), 2),
('TOPPADDING', (0, 0), (-1, -1), 1), ('BOTTOMPADDING', (0, 0), (-1, -1), 1),
]))
story.append(table)
doc.build(story)
buffer.seek(0)
return buffer.getvalue()
# PDF to image
def pdf_to_image(pdf_bytes):
try:
doc = fitz.open(stream=pdf_bytes, filetype="pdf")
images = []
for page in doc:
pix = page.get_pixmap(matrix=fitz.Matrix(2.0, 2.0))
img = Image.frombytes("RGB", [pix.width, pix.height], pix.samples)
images.append(img)
doc.close()
return images
except Exception as e:
st.error(f"Failed to render PDF preview: {e}")
return None
# Main logic
with st.spinner("Generating PDF..."):
pdf_bytes = create_pdf(st.session_state.markdown_content, base_font_size, plain_text_mode, num_columns, auto_bold_numbers)
with st.container():
pdf_images = pdf_to_image(pdf_bytes)
if pdf_images:
for img in pdf_images:
st.image(img, use_container_width=True)
else:
st.info("Download the PDF to view it locally.")
with st.sidebar:
st.download_button(label="Download PDF", data=pdf_bytes, file_name="deities_guide.pdf", mime="application/pdf")
# Your default markdown content remains unchanged
default_markdown = """# Deities Guide: Mythology and Moral Lessons 🌟
1. 📜 Introduction
- Purpose: Explore deities, spirits, saints, and beings with their stories and morals.
- Usage: Guide for learning and storytelling across traditions.
- Themes: Justice, faith, hubris, redemption, cosmic order.
2. 🛠️ Core Concepts of Divinity
- Powers: Creation, omniscience, shapeshifting across entities.
- Life Cycle: Mortality, immortality, transitions such as saints and avatars.
- Communication: Omens, visions, miracles from gods and spirits.
3. ⚡ Standard Abilities
- Creation: Gods and spirits shape worlds, such as Allah and Vishnu.
- Influence: Saints and prophets intercede, for example, Muhammad and Paul.
- Transformation: Angels and avatars shift forms, like Gabriel and Krishna.
- Knowledge: Foresight or revelation, as seen with the Holy Spirit and Brahma.
- Judgment: Divine authority, exemplified by Yahweh and Yama.
4. ⏳ Mortality and Immortality
- Gods: Eternal, such as Allah and Shiva.
- Spirits: Realm-bound, like jinn and devas.
- Saints/Prophets: Mortal to divine, for instance, Moses and Rama.
- Beings: Limbo states, such as cherubim and rakshasas.
- Lessons: Faith and duty define transitions.
5. 🌠 Ascension and Signs
- Paths: Birth, deeds, revelation, as with Jesus and Arjuna.
- Signs: Miracles and prophecies, like those in the Quran and Gita.
- Morals: Obedience and devotion shape destiny.
6. 🎲 Storytelling and Games
- Portrayal: Gods, spirits, and saints in narratives or RPGs.
- Dynamics: Clerics, imams, and sadhus serve higher powers.
- Balance: Power versus personality for depth.
7. 🎮 Dungeon Mastering Beings
- Gods: Epic scope, such as Allah and Vishnu.
- Spirits: Local influence, like jinn and apsaras.
- Saints: Moral anchors, for example, St. Francis and Ali.
8. 🙏 Devotee Relationships
- Clerics: Serve gods, such as Krishna’s priests.
- Mediums: Channel spirits, like jinn whisperers.
- Faithful: Venerate saints and prophets, for instance, Fatima’s followers.
9. 🦅 American Indian Traditions
- Coyote, Raven, White Buffalo Woman: Trickster kin and wise mother.
- Relation: Siblings and guide teach balance.
- Lesson: Chaos breeds wisdom.
10. ⚔️ Arthurian Legends
- Merlin, Morgan le Fay, Arthur: Mentor, rival, son.
- Relation: Family tests loyalty.
- Lesson: Honor versus betrayal.
11. 🏛️ Babylonian Mythology
- Marduk, Tiamat, Ishtar: Son, mother, lover.
- Relation: Kinship drives order.
- Lesson: Power reshapes chaos.
12. ✝️ Christian Trinity
- God (Yahweh), Jesus, Holy Spirit: Father, Son, Spirit.
- Relation: Divine family redeems.
- Lesson: Faith restores grace.
13. 😇 Christian Saints & Angels
- St. Michael, Gabriel, Mary: Warrior, messenger, mother.
- Relation: Heavenly kin serve God.
- Lesson: Duty upholds divine will.
14. 🍀 Celtic Mythology
- Lugh, Morrigan, Cernunnos: Son, mother, father.
- Relation: Family governs cycles.
- Lesson: Courage in fate.
15. 🌄 Central American Traditions
- Quetzalcoatl, Tezcatlipoca, Huitzilopochtli: Brothers and war son.
- Relation: Sibling rivalry creates.
- Lesson: Sacrifice builds worlds.
16. 🐉 Chinese Mythology
- Jade Emperor, Nuwa, Sun Wukong: Father, mother, rebel son.
- Relation: Family enforces harmony.
- Lesson: Duty curbs chaos.
17. 🐙 Cthulhu Mythos
- Cthulhu, Nyarlathotep, Yog-Sothoth: Elder kin.
- Relation: Cosmic trio overwhelms.
- Lesson: Insignificance humbles.
18. ☥ Egyptian Mythology
- Ra, Osiris, Isis: Father, son, mother.
- Relation: Family ensures renewal.
- Lesson: Justice prevails.
19. ❄️ Finnish Mythology
- Väinämöinen, Louhi, Ukko: Son, mother, father.
- Relation: Kinship tests wisdom.
- Lesson: Perseverance wins.
20. 🏛️ Greek Mythology
- Zeus, Hera, Athena: Father, mother, daughter.
- Relation: Family rules with tension.
- Lesson: Hubris meets wisdom.
21. 🕉️ Hindu Trimurti
- Brahma, Vishnu, Shiva: Creator, preserver, destroyer.
- Relation: Divine trio cycles existence.
- Lesson: Balance sustains life.
22. 🌺 Hindu Avatars & Devis
- Krishna, Rama, Durga: Sons and fierce mother.
- Relation: Avatars and goddess protect dharma.
- Lesson: Duty defeats evil.
23. 🌸 Japanese Mythology
- Amaterasu, Susanoo, Tsukuyomi: Sister, brothers.
- Relation: Siblings balance cosmos.
- Lesson: Harmony versus chaos.
24. 🗡️ Melnibonean Legends
- Arioch, Xiombarg, Elric: Lords and mortal son.
- Relation: Pact binds chaos.
- Lesson: Power corrupts.
25. ☪️ Muslim Divine & Messengers
- Allah, Muhammad, Gabriel: God, prophet, angel.
- Relation: Messenger reveals divine will.
- Lesson: Submission brings peace.
26. 👻 Muslim Spirits & Kin
- Jinn, Iblis, Khidr: Spirits and guide defy or aid.
- Relation: Supernatural kin test faith.
- Lesson: Obedience versus rebellion.
27. 🏰 Nehwon Legends
- Death, Ningauble, Sheelba: Fateful trio.
- Relation: Guides shape destiny.
- Lesson: Cunning defies fate.
28. 🧝 Nonhuman Traditions
- Corellon, Moradin, Gruumsh: Elf, dwarf, orc fathers.
- Relation: Rivals define purpose.
- Lesson: Community endures.
29. ᚱ Norse Mythology
- Odin, Frigg, Loki: Father, mother, trickster son.
- Relation: Family faces doom.
- Lesson: Sacrifice costs.
30. 🗿 Sumerian Mythology
- Enki, Inanna, Anu: Son, daughter, father.
- Relation: Kin wield knowledge.
- Lesson: Ambition shapes.
31. 📚 Appendices
- Planes: Realms of gods, spirits, saints, such as Paradise and Svarga.
- Symbols: Rituals and artifacts of faith.
- Charts: Domains and duties for devotees.
32. 🌌 Planes of Existence
- Heaven/Paradise: Christian/Muslim abode.
- Svarga: Hindu divine realm.
- Underworld: Spirits linger, for example, Sheol and Naraka.
33. 🕍 Temple Trappings
- Cross/Crescent: Christian/Muslim faith.
- Mandalas: Hindu devotion.
- Relics: Saints’ and prophets’ legacy.
34. 📊 Clerical Chart
- Gods: Domains, such as creation and mercy.
- Spirits: Influence, like guidance and mischief.
- Saints/Prophets: Virtues, for instance, justice and prophecy.
"""
create_pdf_tab(default_markdown)