File size: 18,562 Bytes
65669b4 |
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 |
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):
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., NotoColorEmoji-Regular.ttf and DejaVuSans.ttf.")
return
available_fonts = {os.path.splitext(os.path.basename(f))[0]: f for f in font_files}
md_files = [f for f in glob.glob("*.md") if os.path.basename(f) != "README.md"]
md_options = [os.path.splitext(os.path.basename(f))[0] for f in md_files]
with st.sidebar:
selected_md = st.selectbox("Select Markdown File", options=md_options, index=0 if md_options else -1)
selected_font_name = st.selectbox("Select Emoji Font", options=list(available_fonts.keys()), index=0 if "NotoColorEmoji-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 or not md_options:
st.session_state.markdown_content = default_markdown
if md_options and selected_md:
with open(f"{selected_md}.md", "r", encoding="utf-8") as f:
st.session_state.markdown_content = f.read()
edited_markdown = st.text_area("Modify the markdown content below:", value=st.session_state.markdown_content, height=300, key=f"markdown_{selected_md}_{selected_font_name}_{num_columns}")
if st.button("Update PDF"):
st.session_state.markdown_content = edited_markdown
with open(f"{selected_md}.md", "w", encoding="utf-8") as f:
f.write(edited_markdown)
st.rerun()
st.download_button(label="Save Markdown", data=st.session_state.markdown_content, file_name=f"{selected_md}.md", mime="text/markdown")
if not md_options:
st.warning("No .md files found in the directory (excluding README.md). Using default content.")
return
try:
pdfmetrics.registerFont(TTFont(selected_font_name, selected_font_path))
pdfmetrics.registerFont(TTFont("DejaVuSans", "DejaVuSans.ttf"))
except Exception as e:
st.error(f"Failed to register fonts: {e}. Ensure both {selected_font_name}.ttf and DejaVuSans.ttf are in the directory.")
return
def apply_emoji_font(text, emoji_font):
emoji_pattern = re.compile(
r"([\U0001F300-\U0001F5FF"
r"\U0001F600-\U0001F64F"
r"\U0001F680-\U0001F6FF"
r"\U0001F700-\U0001F77F"
r"\U0001F780-\U0001F7FF"
r"\U0001F800-\U0001F8FF"
r"\U0001F900-\U0001F9FF"
r"\U0001FA00-\U0001FA6F"
r"\U0001FA70-\U0001FAFF"
r"\u2600-\u26FF"
r"\u2700-\u27BF]+)"
)
def replace_emoji(match):
emoji = match.group(1)
emoji = unicodedata.normalize('NFC', emoji)
return f'<font face="{emoji_font}">{emoji}</font>'
segments = []
last_pos = 0
for match in emoji_pattern.finditer(text):
start, end = match.span()
if last_pos < start:
segments.append(f'<font face="DejaVuSans">{text[last_pos:start]}</font>')
segments.append(replace_emoji(match))
last_pos = end
if last_pos < len(text):
segments.append(f'<font face="DejaVuSans">{text[last_pos:]}</font>')
return ''.join(segments)
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
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
section_style = ParagraphStyle(
'SectionStyle', parent=styles['Heading2'], fontName="DejaVuSans",
textColor=colors.darkblue, fontSize=section_font_size, leading=section_font_size * 1.2, spaceAfter=2
)
item_style = ParagraphStyle(
'ItemStyle', parent=styles['Normal'], fontName="DejaVuSans",
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()
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
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")
default_markdown = """# Deities Guide: Mythology and Moral Lessons ๐โจ
1. ๐ **Introduction**
- **Purpose**: Explore deities, spirits, saints, and beings with their epic stories and morals! ๐๐
- **Usage**: A 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 like saints and avatars ๐.
- **Communication**: Omens ๐ฉ๏ธ, visions ๐๏ธ, miracles โจ from gods and spirits.
3. โก **Standard Abilities**
- **Creation**: Gods and spirits shape worlds, e.g., Allah ๐ and Vishnu ๐.
- **Influence**: Saints and prophets intercede, like Muhammad ๐ and Paul โ๏ธ.
- **Transformation**: Angels and avatars shift forms, e.g., Gabriel ๐ and Krishna ๐ฆ.
- **Knowledge**: Foresight ๐ฎ or revelation ๐, as with the Holy Spirit ๐๏ธ and Brahma ๐ง .
- **Judgment**: Divine authority ๐, e.g., Yahweh โ๏ธ and Yama ๐.
4. โณ **Mortality and Immortality**
- **Gods**: Eternal โฐ, like Allah ๐ and Shiva ๐๏ธ.
- **Spirits**: Realm-bound ๐ , e.g., jinn ๐ฅ and devas โจ.
- **Saints/Prophets**: Mortal to divine ๐โก๏ธ๐, e.g., Moses ๐ and Rama ๐น.
- **Beings**: Limbo states โ, like 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 ๐ช vs. personality ๐ for depth.
7. ๐ฎ **Dungeon Mastering Beings**
- **Gods**: Epic scope ๐, e.g., Allah โจ and Vishnu ๐.
- **Spirits**: Local influence ๐๏ธ, like jinn ๐ฅ and apsaras ๐.
- **Saints**: Moral anchors โ, e.g., St. Francis ๐พ and Ali โ๏ธ.
8. ๐ **Devotee Relationships**
- **Clerics**: Serve gods, e.g., Krishnaโs priests ๐ฆ.
- **Mediums**: Channel spirits, like jinn whisperers ๐ฅ๐๏ธ.
- **Faithful**: Venerate saints and prophets, e.g., 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 ๐ก๏ธ vs. 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 ๐ถ vs. 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 ๐ง vs. 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, e.g., 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, e.g., Sheol โฐ๏ธ and Naraka ๐ฅ.
33. ๐ **Temple Trappings**
- **Cross/Crescent**: Christian/Muslim faith โ๏ธโช๏ธ.
- **Mandalas**: Hindu devotion ๐.
- **Relics**: Saintsโ and prophetsโ legacy ๐๏ธ.
34. ๐ **Clerical Chart**
- **Gods**: Domains, e.g., creation ๐ and mercy โค๏ธ.
- **Spirits**: Influence, like guidance ๐ฟ and mischief ๐.
- **Saints/Prophets**: Virtues, e.g., justice โ๏ธ and prophecy ๐ฎ.
"""
create_pdf_tab(default_markdown) |