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3
+ import re
4
+ import streamlit as st
5
+
6
+ # Must be the very first Streamlit command.
7
+ st.set_page_config(layout="wide", initial_sidebar_state="collapsed")
8
+
9
+ from PIL import Image
10
+ import fitz # PyMuPDF
11
+
12
+ from reportlab.lib.pagesizes import A4
13
+ from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer, Table, TableStyle
14
+ from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
15
+ from reportlab.lib import colors
16
+ from reportlab.pdfbase import pdfmetrics
17
+ from reportlab.pdfbase.ttfonts import TTFont
18
+
19
+ # ---------------------------------------------------------------
20
+ # Define available NotoEmoji fonts (assumed in the base directory)
21
+ available_fonts = {
22
+ "NotoEmoji Variable": "NotoEmoji-VariableFont_wght.ttf",
23
+ "NotoEmoji Bold": "NotoEmoji-Bold.ttf",
24
+ "NotoEmoji Light": "NotoEmoji-Light.ttf",
25
+ "NotoEmoji Medium": "NotoEmoji-Medium.ttf",
26
+ "NotoEmoji Regular": "NotoEmoji-Regular.ttf",
27
+ "NotoEmoji SemiBold": "NotoEmoji-SemiBold.ttf"
28
+ }
29
+
30
+ # Sidebar: Let the user choose the NotoEmoji font.
31
+ selected_font_name = st.sidebar.selectbox(
32
+ "Select NotoEmoji Font",
33
+ options=list(available_fonts.keys())
34
+ )
35
+ selected_font_path = available_fonts[selected_font_name]
36
+
37
+ # Register the chosen emoji font with ReportLab.
38
+ pdfmetrics.registerFont(TTFont(selected_font_name, selected_font_path))
39
+
40
+ # ---------------------------------------------------------------
41
+ # Helper function to wrap emoji characters with a font tag.
42
+ def apply_emoji_font(text, emoji_font):
43
+ emoji_pattern = re.compile(
44
+ r"([\U0001F300-\U0001F5FF"
45
+ r"\U0001F600-\U0001F64F"
46
+ r"\U0001F680-\U0001F6FF"
47
+ r"\U0001F700-\U0001F77F"
48
+ r"\U0001F780-\U0001F7FF"
49
+ r"\U0001F800-\U0001F8FF"
50
+ r"\U0001F900-\U0001F9FF"
51
+ r"\U0001FA00-\U0001FA6F"
52
+ r"\U0001FA70-\U0001FAFF"
53
+ r"\u2600-\u26FF"
54
+ r"\u2700-\u27BF]+)"
55
+ )
56
+ return emoji_pattern.sub(r'<font face="{}">\1</font>'.format(emoji_font), text)
57
+
58
+ # ---------------------------------------------------------------
59
+ # Default markdown content with your Deities Guide.
60
+ default_markdown = """# 🌟 Deities Guide: Mythology and Moral Lessons 🌟
61
+
62
+ ## 1. 📜 Introduction
63
+ 1. Purpose: Explore deities, spirits, saints, and beings with their stories and morals.
64
+ 2. Usage: Guide for learning and storytelling across traditions.
65
+ 3. Themes: Justice, faith, hubris, redemption, cosmic order.
66
+
67
+ ## 2. 🛠️ Core Concepts of Divinity
68
+ 1. Powers: Creation, omniscience, shapeshifting across entities.
69
+ 2. Life Cycle: Mortality, immortality, transitions (e.g., saints, avatars).
70
+ 3. Communication: Omens, visions, miracles from gods and spirits.
71
+
72
+ ### 2.1. ⚡ Standard Abilities
73
+ 1. Creation: Gods and spirits shape worlds (e.g., Allah, Vishnu).
74
+ 2. Influence: Saints, prophets intercede (e.g., Muhammad, Paul).
75
+ 3. Transformation: Angels, avatars shift forms (e.g., Gabriel, Krishna).
76
+ 4. Knowledge: Foresight or revelation (e.g., Holy Spirit, Brahma).
77
+ 5. Judgment: Divine authority (e.g., Yahweh, Yama).
78
+
79
+ ### 2.2. ⏳ Mortality and Immortality
80
+ 1. Gods: Eternal (e.g., Allah, Shiva).
81
+ 2. Spirits: Realm-bound (e.g., jinn, devas).
82
+ 3. Saints/Prophets: Mortal to divine (e.g., Moses, Rama).
83
+ 4. Beings: Limbo states (e.g., cherubim, rakshasas).
84
+ 5. Lessons: Faith, duty define transitions.
85
+
86
+ ### 2.3. 🌠 Ascension and Signs
87
+ 1. Paths: Birth, deeds, revelation (e.g., Jesus, Arjuna).
88
+ 2. Signs: Miracles, prophecies (e.g., Quran, Gita).
89
+ 3. Morals: Obedience, devotion shape destiny.
90
+
91
+ ## 3. 🎲 Storytelling and Games
92
+ 1. Portrayal: Gods, spirits, saints in narratives or RPGs.
93
+ 2. Dynamics: Clerics, imams, sadhus serve higher powers.
94
+ 3. Balance: Power vs. personality for depth.
95
+
96
+ ### 3.1. 🎮 Dungeon Mastering Beings
97
+ 1. Gods: Epic scope (e.g., Allah, Vishnu).
98
+ 2. Spirits: Local influence (e.g., jinn, apsaras).
99
+ 3. Saints: Moral anchors (e.g., St. Francis, Ali).
100
+
101
+ ### 3.2. 🙏 Devotee Relationships
102
+ 1. Clerics: Serve gods (e.g., Krishna’s priests).
103
+ 2. Mediums: Channel spirits (e.g., jinn whisperers).
104
+ 3. Faithful: Venerate saints/prophets (e.g., Fatima’s followers).
105
+
106
+ ## 4. 🌐 Traditions and Legends
107
+ *(Top three figures—gods, spirits, saints, beings—with relationships and morals)*
108
+ 1. **American Indian** 🦅
109
+ 1. Coyote, Raven, White Buffalo Woman: Trickster kin and wise mother.
110
+ 2. Relation: Siblings and guide teach balance.
111
+ 3. Lesson: Chaos breeds wisdom.
112
+ 2. **Arthurian** ⚔️
113
+ 1. Merlin, Morgan le Fay, Arthur: Mentor, rival, son.
114
+ 2. Relation: Family tests loyalty.
115
+ 3. Lesson: Honor vs. betrayal.
116
+ 3. **Babylonian** 🏛️
117
+ 1. Marduk, Tiamat, Ishtar: Son, mother, lover.
118
+ 2. Relation: Kinship drives order.
119
+ 3. Lesson: Power reshapes chaos.
120
+ 4. **Christian: Trinity** ✝️
121
+ 1. God (Yahweh), Jesus, Holy Spirit: Father, Son, Spirit.
122
+ 2. Relation: Divine family redeems.
123
+ 3. Lesson: Faith restores grace.
124
+ 5. **Christian: Saints & Angels** 😇
125
+ 1. St. Michael, Gabriel, Mary: Warrior, messenger, mother.
126
+ 2. Relation: Heavenly kin serve God.
127
+ 3. Lesson: Duty upholds divine will.
128
+ 6. **Celtic** 🍀
129
+ 1. Lugh, Morrigan, Cernunnos: Son, mother, father.
130
+ 2. Relation: Family governs cycles.
131
+ 3. Lesson: Courage in fate.
132
+ 7. **Central American** 🌄
133
+ 1. Quetzalcoatl, Tezcatlipoca, Huitzilopochtli: Brothers and war son.
134
+ 2. Relation: Sibling rivalry creates.
135
+ 3. Lesson: Sacrifice builds worlds.
136
+ 8. **Chinese** 🐉
137
+ 1. Jade Emperor, Nuwa, Sun Wukong: Father, mother, rebel son.
138
+ 2. Relation: Family enforces harmony.
139
+ 3. Lesson: Duty curbs chaos.
140
+ 9. **Cthulhu** 🐙
141
+ 1. Cthulhu, Nyarlathotep, Yog-Sothoth: Elder kin.
142
+ 2. Relation: Cosmic trio overwhelms.
143
+ 3. Lesson: Insignificance humbles.
144
+ 10. **Egyptian** ☥
145
+ 1. Ra, Osiris, Isis: Father, son, mother.
146
+ 2. Relation: Family ensures renewal.
147
+ 3. Lesson: Justice prevails.
148
+ 11. **Finnish** ❄️
149
+ 1. Väinämöinen, Louhi, Ukko: Son, mother, father.
150
+ 2. Relation: Kinship tests wisdom.
151
+ 3. Lesson: Perseverance wins.
152
+ 12. **Greek** 🏛️
153
+ 1. Zeus, Hera, Athena: Father, mother, daughter.
154
+ 2. Relation: Family rules with tension.
155
+ 3. Lesson: Hubris meets wisdom.
156
+ 13. **Hindu: Trimurti** 🕉️
157
+ 1. Brahma, Vishnu, Shiva: Creator, preserver, destroyer.
158
+ 2. Relation: Divine trio cycles existence.
159
+ 3. Lesson: Balance sustains life.
160
+ 14. **Hindu: Avatars & Devis** 🌺
161
+ 1. Krishna, Rama, Durga: Sons and fierce mother.
162
+ 2. Relation: Avatars and goddess protect dharma.
163
+ Gabri 3. Lesson: Duty defeats evil.
164
+ 15. **Japanese** 🌸
165
+ 1. Amaterasu, Susanoo, Tsukuyomi: Sister, brothers.
166
+ 2. Relation: Siblings balance cosmos.
167
+ 3. Lesson: Harmony vs. chaos.
168
+ 16. **Melnibonean** 🗡️
169
+ 1. Arioch, Xiombarg, Elric: Lords and mortal son.
170
+ 2. Relation: Pact binds chaos.
171
+ 3. Lesson: Power corrupts.
172
+ 17. **Muslim: Divine & Messengers** ☪️
173
+ 1. Allah, Muhammad, Gabriel: God, prophet, angel.
174
+ 2. Relation: Messenger reveals divine will.
175
+ 3. Lesson: Submission brings peace.
176
+ 18. **Muslim: Spirits & Kin** 👻
177
+ 1. Jinn, Iblis, Khidr: Spirits and guide defy or aid.
178
+ 2. Relation: Supernatural kin test faith.
179
+ 3. Lesson: Obedience vs. rebellion.
180
+ 19. **Nehwon** 🏰
181
+ 1. Death, Ningauble, Sheelba: Fateful trio.
182
+ 2. Relation: Guides shape destiny.
183
+ 3. Lesson: Cunning defies fate.
184
+ 20. **Nonhumans’** 🧝
185
+ 1. Corellon, Moradin, Gruumsh: Elf, dwarf, orc fathers.
186
+ 2. Relation: Rivals define purpose.
187
+ 3. Lesson: Community endures.
188
+ 21. **Norse** ᚱ
189
+ 1. Odin, Frigg, Loki: Father, mother, trickster son.
190
+ 2. Relation: Family faces doom.
191
+ 3. Lesson: Sacrifice costs.
192
+ 22. **Sumerian** 🗿
193
+ 1. Enki, Inanna, Anu: Son, daughter, father.
194
+ 2. Relation: Kin wield knowledge.
195
+ 3. Lesson: Ambition shapes.
196
+
197
+ ## 5. 📚 Appendices
198
+ 1. Planes: Realms of gods, spirits, saints (e.g., Paradise, Svarga).
199
+ 2. Symbols: Rituals and artifacts of faith.
200
+ 3. Charts: Domains and duties for devotees.
201
+
202
+ ### 5.1. 🌌 Planes of Existence
203
+ 1. Heaven/Paradise: Christian/Muslim abode.
204
+ 2. Svarga: Hindu divine realm.
205
+ 3. Underworld: Spirits linger (e.g., Sheol, Naraka).
206
+
207
+ ### 5.2. 🕍 Temple Trappings
208
+ 1. Cross/Crescent: Christian/Muslim faith.
209
+ 2. Mandalas: Hindu devotion.
210
+ 3. Relics: Saints’ and prophets’ legacy.
211
+
212
+ ### 5.3. 📊 Clerical Chart
213
+ 1. Gods: Domains (e.g., creation, mercy).
214
+ 2. Spirits: Influence (e.g., guidance, mischief).
215
+ 3. Saints/Prophets: Virtues (e.g., justice, prophecy).
216
+ """
217
+
218
+ # ---------------------------------------------------------------
219
+ # Process markdown into a two-page layout for the PDF.
220
+ def markdown_to_pdf_content(markdown_text):
221
+ lines = markdown_text.strip().split('\n')
222
+ pdf_content = []
223
+ in_list_item = False
224
+ current_item = None
225
+ sub_items = []
226
+
227
+ for line in lines:
228
+ line = line.strip()
229
+ if not line:
230
+ continue
231
+
232
+ if line.startswith('# '):
233
+ # Skip the main title for now, added separately.
234
+ pass
235
+ elif line.startswith('## '):
236
+ if current_item and sub_items:
237
+ pdf_content.append([current_item, sub_items])
238
+ sub_items = []
239
+ current_item = None
240
+ section = line.replace('## ', '').strip()
241
+ pdf_content.append(f"<b>{section}</b>")
242
+ in_list_item = False
243
+ elif re.match(r'^\d+\.', line):
244
+ if current_item and sub_items:
245
+ pdf_content.append([current_item, sub_items])
246
+ sub_items = []
247
+ current_item = line.strip()
248
+ in_list_item = True
249
+ elif line.startswith('- ') and in_list_item:
250
+ sub_items.append(line.strip())
251
+ elif re.match(r'^\d+\.\d+\.', line):
252
+ if current_item and sub_items:
253
+ pdf_content.append([current_item, sub_items])
254
+ sub_items = []
255
+ current_item = line.strip()
256
+ in_list_item = True
257
+ else:
258
+ if not in_list_item:
259
+ pdf_content.append(line.strip())
260
+
261
+ if current_item and sub_items:
262
+ pdf_content.append([current_item, sub_items])
263
+
264
+ # Split into two pages (roughly balanced).
265
+ total_items = sum(1 + len(subs) if isinstance(item, list) else 1 for item in pdf_content)
266
+ target_per_page = total_items // 2
267
+ page1_content = []
268
+ page2_content = []
269
+ current_count = 0
270
+
271
+ for item in pdf_content:
272
+ item_count = 1 + (len(item[1]) if isinstance(item, list) else 0)
273
+ if current_count < target_per_page or len(page1_content) == 0:
274
+ page1_content.append(item)
275
+ current_count += item_count
276
+ else:
277
+ page2_content.append(item)
278
+
279
+ return page1_content, page2_content
280
+
281
+ # ---------------------------------------------------------------
282
+ # Create the PDF with two pages.
283
+ def create_main_pdf(markdown_text, base_font_size=10, auto_size=False):
284
+ buffer = io.BytesIO()
285
+ doc = SimpleDocTemplate(
286
+ buffer,
287
+ pagesize=A4,
288
+ leftMargin=36,
289
+ rightMargin=36,
290
+ topMargin=36,
291
+ bottomMargin=36
292
+ )
293
+
294
+ styles = getSampleStyleSheet()
295
+ story = []
296
+ spacer_height = 10
297
+ page1_content, page2_content = markdown_to_pdf_content(markdown_text)
298
+
299
+ total_items = sum(1 + len(subs) if isinstance(item, list) else 1 for item in page1_content + page2_content)
300
+ if auto_size:
301
+ base_font_size = max(6, min(12, 400 / total_items)) # Adjusted for two pages.
302
+
303
+ item_font_size = base_font_size
304
+ subitem_font_size = base_font_size * 0.9
305
+ section_font_size = base_font_size * 1.2
306
+ title_font_size = min(16, base_font_size * 1.5)
307
+
308
+ # Define ParagraphStyles using Helvetica for normal text.
309
+ title_style = ParagraphStyle(
310
+ 'Heading1',
311
+ parent=styles['Heading1'],
312
+ fontName="Helvetica-Bold",
313
+ textColor=colors.darkblue,
314
+ alignment=1,
315
+ fontSize=title_font_size
316
+ )
317
+
318
+ section_style = ParagraphStyle(
319
+ 'SectionStyle',
320
+ parent=styles['Heading2'],
321
+ fontName="Helvetica-Bold",
322
+ textColor=colors.darkblue,
323
+ fontSize=section_font_size,
324
+ leading=section_font_size * 1.2,
325
+ spaceAfter=2
326
+ )
327
+
328
+ item_style = ParagraphStyle(
329
+ 'ItemStyle',
330
+ parent=styles['Normal'],
331
+ fontName="Helvetica",
332
+ fontSize=item_font_size,
333
+ leading=item_font_size * 1.2,
334
+ spaceAfter=1
335
+ )
336
+
337
+ subitem_style = ParagraphStyle(
338
+ 'SubItemStyle',
339
+ parent=styles['Normal'],
340
+ fontName="Helvetica",
341
+ fontSize=subitem_font_size,
342
+ leading=subitem_font_size * 1.2,
343
+ leftIndent=10,
344
+ spaceAfter=1
345
+ )
346
+
347
+ # Page 1
348
+ story.append(Paragraph(apply_emoji_font("Deities Guide: Mythology and Moral Lessons", selected_font_name), title_style))
349
+ story.append(Spacer(1, spacer_height))
350
+
351
+ for item in page1_content:
352
+ if isinstance(item, str) and item.startswith('<b>'):
353
+ text = item.replace('<b>', '').replace('</b>', '')
354
+ story.append(Paragraph(apply_emoji_font(text, selected_font_name), section_style))
355
+ elif isinstance(item, list):
356
+ main_item, sub_items = item
357
+ story.append(Paragraph(apply_emoji_font(main_item, selected_font_name), item_style))
358
+ for sub_item in sub_items:
359
+ story.append(Paragraph(apply_emoji_font(sub_item, selected_font_name), subitem_style))
360
+ else:
361
+ story.append(Paragraph(apply_emoji_font(item, selected_font_name), item_style))
362
+
363
+ story.append(Spacer(1, A4[1] - sum(p.minHeight() for p in story) - 72)) # Fill page.
364
+
365
+ # Page 2
366
+ story.append(Paragraph(apply_emoji_font("Deities Guide: Continued", selected_font_name), title_style))
367
+ story.append(Spacer(1, spacer_height))
368
+
369
+ for item in page2_content:
370
+ if isinstance(item, str) and item.startswith('<b>'):
371
+ text = item.replace('<b>', '').replace('</b>', '')
372
+ story.append(Paragraph(apply_emoji_font(text, selected_font_name), section_style))
373
+ elif isinstance(item, list):
374
+ main_item, sub_items = item
375
+ story.append(Paragraph(apply_emoji_font(main_item, selected_font_name), item_style))
376
+ for sub_item in sub_items:
377
+ story.append(Paragraph(apply_emoji_font(sub_item, selected_font_name), subitem_style))
378
+ else:
379
+ story.append(Paragraph(apply_emoji_font(item, selected_font_name), item_style))
380
+
381
+ doc.build(story)
382
+ buffer.seek(0)
383
+ return buffer.getvalue()
384
+
385
+ # ---------------------------------------------------------------
386
+ # Convert PDF bytes to an image for preview using PyMuPDF.
387
+ def pdf_to_image(pdf_bytes):
388
+ try:
389
+ doc = fitz.open(stream=pdf_bytes, filetype="pdf")
390
+ images = []
391
+ for page in doc:
392
+ pix = page.get_pixmap(matrix=fitz.Matrix(2.0, 2.0))
393
+ img = Image.frombytes("RGB", [pix.width, pix.height], pix.samples)
394
+ images.append(img)
395
+ doc.close()
396
+ return images
397
+ except Exception as e:
398
+ st.error(f"Failed to render PDF preview: {e}")
399
+ return None
400
+
401
+ # ---------------------------------------------------------------
402
+ # Sidebar options for text size.
403
+ with st.sidebar:
404
+ auto_size = st.checkbox("Auto-size text", value=True)
405
+ if not auto_size:
406
+ base_font_size = st.slider("Base Font Size (points)", min_value=6, max_value=16, value=10, step=1)
407
+ else:
408
+ base_font_size = 10
409
+ st.info("Font size will auto-adjust between 6-12 points based on content length.")
410
+
411
+ # Persist markdown content in session state.
412
+ if 'markdown_content' not in st.session_state:
413
+ st.session_state.markdown_content = default_markdown
414
+
415
+ # ---------------------------------------------------------------
416
+ # Generate the PDF.
417
+ with st.spinner("Generating PDF..."):
418
+ pdf_bytes = create_main_pdf(st.session_state.markdown_content, base_font_size, auto_size)
419
+
420
+ # Display PDF preview.
421
+ with st.container():
422
+ pdf_images = pdf_to_image(pdf_bytes)
423
+ if pdf_images:
424
+ for i, img in enumerate(pdf_images):
425
+ st.image(img, caption=f"Page {i+1}", use_container_width=True)
426
+ else:
427
+ st.info("Download the PDF to view it locally.")
428
+
429
+ # PDF Download button.
430
+ st.download_button(
431
+ label="Download PDF",
432
+ data=pdf_bytes,
433
+ file_name="deities_guide.pdf",
434
+ mime="application/pdf"
435
+ )
436
+
437
+ # Markdown editor.
438
+ edited_markdown = st.text_area(
439
+ "Modify the markdown content below:",
440
+ value=st.session_state.markdown_content,
441
+ height=300
442
+ )
443
+
444
+ # Update PDF on button click.
445
+ if st.button("Update PDF"):
446
+ st.session_state.markdown_content = edited_markdown
447
+ st.experimental_rerun()
448
+
449
+ # Markdown Download button.
450
+ st.download_button(
451
+ label="Save Markdown",
452
+ data=st.session_state.markdown_content,
453
+ file_name="deities_guide.md",
454
+ mime="text/markdown"
455
+ )