import io import re import os import glob import asyncio import hashlib import unicodedata import streamlit as st from PIL import Image import fitz import edge_tts 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 st.set_page_config(layout="wide", initial_sidebar_state="collapsed") async def generate_audio(text, voice): filename = f"{hashlib.md5(text.encode()).hexdigest()}_{voice}.mp3" communicate = edge_tts.Communicate(text, voice) await communicate.save(filename) return filename 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'{emoji}' segments = [] last_pos = 0 for match in emoji_pattern.finditer(text): start, end = match.span() if last_pos < start: segments.append(f'{text[last_pos:start]}') segments.append(replace_emoji(match)) last_pos = end if last_pos < len(text): segments.append(f'{text[last_pos:]}') return ''.join(segments) def markdown_to_pdf_content(markdown_text, render_with_bold, auto_bold_numbers): lines = markdown_text.strip().split('\n') pdf_content = [] number_pattern = re.compile(r'^\d+\.\s') for line in lines: line = line.strip() if not line or line.startswith('# '): continue if render_with_bold: line = re.sub(r'\*\*(.*?)\*\*', r'\1', line) if auto_bold_numbers and number_pattern.match(line): if not (line.startswith("") and line.endswith("")): line = f"{line}" pdf_content.append(line) total_lines = len(pdf_content) return pdf_content, total_lines def create_pdf(markdown_text, base_font_size, render_with_bold, auto_bold_numbers, enlarge_numbered, num_columns): 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() spacer_height = 10 section_spacer_height = 15 pdf_content, total_lines = markdown_to_pdf_content(markdown_text, render_with_bold, auto_bold_numbers) item_style = ParagraphStyle( 'ItemStyle', parent=styles['Normal'], fontName="DejaVuSans", fontSize=base_font_size, leading=base_font_size * 1.15, spaceAfter=1 ) bold_style = ParagraphStyle( 'BoldStyle', parent=styles['Normal'], fontName="NotoEmoji-Bold", fontSize=base_font_size, leading=base_font_size * 1.15, spaceAfter=1 ) numbered_bold_style = ParagraphStyle( 'NumberedBoldStyle', parent=styles['Normal'], fontName="NotoEmoji-Bold", fontSize=base_font_size + 1 if enlarge_numbered else base_font_size, leading=(base_font_size + 1) * 1.15 if enlarge_numbered else base_font_size * 1.15, spaceAfter=1 ) section_style = ParagraphStyle( 'SectionStyle', parent=styles['Heading2'], fontName="DejaVuSans", textColor=colors.darkblue, fontSize=base_font_size * 1.1, leading=base_font_size * 1.32, spaceAfter=2 ) try: available_font_files = glob.glob("*.ttf") if not available_font_files: st.error("No .ttf font files found in the current directory.") return selected_font_path = None for f in available_font_files: if "NotoEmoji-Bold" in f: selected_font_path = f break if selected_font_path: pdfmetrics.registerFont(TTFont("NotoEmoji-Bold", selected_font_path)) pdfmetrics.registerFont(TTFont("DejaVuSans", "DejaVuSans.ttf")) except Exception as e: st.error(f"Font registration error: {e}") return 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 item in pdf_content: 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, str) and item.startswith("") and item.endswith(""): content = item[3:-4].strip() if number_pattern.match(content): column_cells[col_idx].append(Paragraph(apply_emoji_font(content, "NotoEmoji-Bold"), numbered_bold_style)) else: column_cells[col_idx].append(Paragraph(apply_emoji_font(content, "NotoEmoji-Bold"), section_style)) else: column_cells[col_idx].append(Paragraph(apply_emoji_font(item, "DejaVuSans"), 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 = [Spacer(1, spacer_height), 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 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 ๐Ÿ”ฎ. """ 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: st.markdown("### PDF Options") selected_md = st.selectbox("Select Markdown File", options=md_options, index=0 if md_options else -1) available_font_files = {os.path.splitext(os.path.basename(f))[0]: f for f in glob.glob("*.ttf")} selected_font_name = st.selectbox("Select Emoji Font", options=list(available_font_files.keys()), index=list(available_font_files.keys()).index("NotoEmoji-Bold") if "NotoEmoji-Bold" in available_font_files else 0) base_font_size = st.slider("Font Size (points)", min_value=6, max_value=16, value=8, step=1) render_with_bold = st.checkbox("Render with Bold Formatting (remove ** markers)", value=True, key="render_with_bold") auto_bold_numbers = st.checkbox("Auto Bold Numbered Lines", value=True, key="auto_bold_numbers") enlarge_numbered = st.checkbox("Enlarge Font Size for Numbered Lines", value=True, key="enlarge_numbered") 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 if md_options and selected_md: with open(f"{selected_md}.md", "w", encoding="utf-8") as f: f.write(edited_markdown) st.experimental_rerun() st.download_button(label="Save Markdown", data=st.session_state.markdown_content, file_name=f"{selected_md}.md" if selected_md else "default.md", mime="text/markdown") st.markdown("### Text-to-Speech") VOICES = ["en-US-AriaNeural", "en-US-JennyNeural", "en-GB-SoniaNeural", "en-US-GuyNeural", "en-US-AnaNeural"] selected_voice = st.selectbox("Select Voice for TTS", options=VOICES, index=0) if st.button("Generate Audio"): audio_file = asyncio.run(generate_audio(st.session_state.markdown_content, selected_voice)) st.audio(audio_file) with open(audio_file, "rb") as f: audio_bytes = f.read() st.download_button("Download Audio", data=audio_bytes, file_name=os.path.basename(audio_file), mime="audio/mpeg") with st.spinner("Generating PDF..."): pdf_bytes = create_pdf(st.session_state.markdown_content, base_font_size, render_with_bold, auto_bold_numbers, enlarge_numbered, num_columns) 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="output.pdf", mime="application/pdf")