awacke1 commited on
Commit
8a6361d
·
verified ·
1 Parent(s): 1aca559

Delete backup3.app.py

Browse files
Files changed (1) hide show
  1. backup3.app.py +0 -387
backup3.app.py DELETED
@@ -1,387 +0,0 @@
1
- import io
2
- import re
3
- import streamlit as st
4
- import glob
5
- import os
6
- from PIL import Image
7
- import fitz
8
- from reportlab.lib.pagesizes import A4
9
- from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer, Table, TableStyle
10
- from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
11
- from reportlab.lib import colors
12
- from reportlab.pdfbase import pdfmetrics
13
- from reportlab.pdfbase.ttfonts import TTFont
14
- import unicodedata
15
-
16
- st.set_page_config(layout="wide", initial_sidebar_state="collapsed")
17
-
18
- def create_pdf_tab(default_markdown):
19
- font_files = glob.glob("*.ttf")
20
- if not font_files:
21
- st.error("No .ttf font files found in the current directory. Please add some, e.g., NotoColorEmoji-Regular.ttf and DejaVuSans.ttf.")
22
- return
23
- available_fonts = {os.path.splitext(os.path.basename(f))[0]: f for f in font_files}
24
-
25
- with st.sidebar:
26
- selected_font_name = st.selectbox("Select Emoji Font", options=list(available_fonts.keys()), index=0 if "NotoColorEmoji-Regular" in available_fonts else 0)
27
- selected_font_path = available_fonts[selected_font_name]
28
- base_font_size = st.slider("Font Size (points)", min_value=6, max_value=16, value=9, step=1)
29
- plain_text_mode = st.checkbox("Render as Plain Text (Preserve Bold Only)", value=False)
30
- auto_bold_numbers = st.checkbox("Auto-Bold Numbered Lines", value=False)
31
- num_columns = st.selectbox("Number of Columns", options=[1, 2, 3, 4, 5, 6], index=3)
32
-
33
- if 'markdown_content' not in st.session_state:
34
- st.session_state.markdown_content = default_markdown
35
-
36
- edited_markdown = st.text_area("Modify the markdown content below:", value=st.session_state.markdown_content, height=300)
37
- if st.button("Update PDF"):
38
- st.session_state.markdown_content = edited_markdown
39
- st.rerun()
40
-
41
- st.download_button(label="Save Markdown", data=st.session_state.markdown_content, file_name="deities_guide.md", mime="text/markdown")
42
-
43
- try:
44
- pdfmetrics.registerFont(TTFont(selected_font_name, selected_font_path))
45
- pdfmetrics.registerFont(TTFont("DejaVuSans", "DejaVuSans.ttf"))
46
- except Exception as e:
47
- st.error(f"Failed to register fonts: {e}. Ensure both {selected_font_name}.ttf and DejaVuSans.ttf are in the directory.")
48
- return
49
-
50
- def apply_emoji_font(text, emoji_font):
51
- emoji_pattern = re.compile(
52
- r"([\U0001F300-\U0001F5FF"
53
- r"\U0001F600-\U0001F64F"
54
- r"\U0001F680-\U0001F6FF"
55
- r"\U0001F700-\U0001F77F"
56
- r"\U0001F780-\U0001F7FF"
57
- r"\U0001F800-\U0001F8FF"
58
- r"\U0001F900-\U0001F9FF"
59
- r"\U0001FA00-\U0001FA6F"
60
- r"\U0001FA70-\U0001FAFF"
61
- r"\u2600-\u26FF"
62
- r"\u2700-\u27BF]+)"
63
- )
64
-
65
- def replace_emoji(match):
66
- emoji = match.group(1)
67
- emoji = unicodedata.normalize('NFC', emoji)
68
- return f'<font face="{emoji_font}">{emoji}</font>'
69
-
70
- segments = []
71
- last_pos = 0
72
- for match in emoji_pattern.finditer(text):
73
- start, end = match.span()
74
- if last_pos < start:
75
- segments.append(f'<font face="DejaVuSans">{text[last_pos:start]}</font>')
76
- segments.append(replace_emoji(match))
77
- last_pos = end
78
- if last_pos < len(text):
79
- segments.append(f'<font face="DejaVuSans">{text[last_pos:]}</font>')
80
- return ''.join(segments)
81
-
82
- def markdown_to_pdf_content(markdown_text, plain_text_mode, auto_bold_numbers):
83
- lines = markdown_text.strip().split('\n')
84
- pdf_content = []
85
- number_pattern = re.compile(r'^\d+\.\s')
86
-
87
- if plain_text_mode:
88
- for line in lines:
89
- line = line.strip()
90
- if not line or line.startswith('# '):
91
- continue
92
- bold_pattern = re.compile(r'\*\*(.*?)\*\*')
93
- line = bold_pattern.sub(r'<b>\1</b>', line)
94
- pdf_content.append(line)
95
- else:
96
- for line in lines:
97
- line = line.strip()
98
- if not line or line.startswith('# '):
99
- continue
100
- if line.startswith('## ') or line.startswith('### '):
101
- text = line.replace('## ', '').replace('### ', '').strip()
102
- pdf_content.append(f"<b>{text}</b>")
103
- elif auto_bold_numbers and number_pattern.match(line):
104
- pdf_content.append(f"<b>{line}</b>")
105
- else:
106
- pdf_content.append(line.strip())
107
-
108
- total_lines = len(pdf_content)
109
- return pdf_content, total_lines
110
-
111
- def create_pdf(markdown_text, base_font_size, plain_text_mode, num_columns, auto_bold_numbers):
112
- buffer = io.BytesIO()
113
- page_width = A4[0] * 2
114
- page_height = A4[1]
115
- doc = SimpleDocTemplate(buffer, pagesize=(page_width, page_height), leftMargin=36, rightMargin=36, topMargin=36, bottomMargin=36)
116
- styles = getSampleStyleSheet()
117
- story = []
118
- spacer_height = 10
119
- section_spacer_height = 15
120
- pdf_content, total_lines = markdown_to_pdf_content(markdown_text, plain_text_mode, auto_bold_numbers)
121
-
122
- item_font_size = base_font_size
123
- section_font_size = base_font_size * 1.1
124
-
125
- section_style = ParagraphStyle(
126
- 'SectionStyle', parent=styles['Heading2'], fontName="DejaVuSans",
127
- textColor=colors.darkblue, fontSize=section_font_size, leading=section_font_size * 1.2, spaceAfter=2
128
- )
129
- item_style = ParagraphStyle(
130
- 'ItemStyle', parent=styles['Normal'], fontName="DejaVuSans",
131
- fontSize=item_font_size, leading=item_font_size * 1.15, spaceAfter=1
132
- )
133
-
134
- story.append(Spacer(1, spacer_height))
135
- columns = [[] for _ in range(num_columns)]
136
- lines_per_column = total_lines / num_columns if num_columns > 0 else total_lines
137
- current_line_count = 0
138
- current_column = 0
139
-
140
- number_pattern = re.compile(r'^\d+\.\s')
141
- for i, item in enumerate(pdf_content):
142
- if i > 0 and number_pattern.match(item.replace('<b>', '').replace('</b>', '')):
143
- columns[current_column].append(Spacer(1, section_spacer_height))
144
-
145
- if current_line_count >= lines_per_column and current_column < num_columns - 1:
146
- current_column += 1
147
- current_line_count = 0
148
- columns[current_column].append(item)
149
- current_line_count += 1
150
-
151
- column_cells = [[] for _ in range(num_columns)]
152
- for col_idx, column in enumerate(columns):
153
- for item in column:
154
- if isinstance(item, Spacer):
155
- column_cells[col_idx].append(item)
156
- elif isinstance(item, str) and item.startswith('<b>'):
157
- text = item.replace('<b>', '').replace('</b>', '')
158
- column_cells[col_idx].append(Paragraph(apply_emoji_font(text, selected_font_name), section_style))
159
- else:
160
- column_cells[col_idx].append(Paragraph(apply_emoji_font(item, selected_font_name), item_style))
161
-
162
- max_cells = max(len(cells) for cells in column_cells) if column_cells else 0
163
- for cells in column_cells:
164
- cells.extend([Paragraph("", item_style)] * (max_cells - len(cells)))
165
-
166
- col_width = (page_width - 72) / num_columns if num_columns > 0 else page_width - 72
167
- table_data = list(zip(*column_cells)) if column_cells else [[]]
168
- table = Table(table_data, colWidths=[col_width] * num_columns, hAlign='CENTER')
169
- table.setStyle(TableStyle([
170
- ('VALIGN', (0, 0), (-1, -1), 'TOP'), ('ALIGN', (0, 0), (-1, -1), 'LEFT'),
171
- ('BACKGROUND', (0, 0), (-1, -1), colors.white), ('GRID', (0, 0), (-1, -1), 0, colors.white),
172
- ('LINEAFTER', (0, 0), (num_columns-1, -1), 0.5, colors.grey),
173
- ('LEFTPADDING', (0, 0), (-1, -1), 2), ('RIGHTPADDING', (0, 0), (-1, -1), 2),
174
- ('TOPPADDING', (0, 0), (-1, -1), 1), ('BOTTOMPADDING', (0, 0), (-1, -1), 1),
175
- ]))
176
-
177
- story.append(table)
178
- doc.build(story)
179
- buffer.seek(0)
180
- return buffer.getvalue()
181
-
182
- def pdf_to_image(pdf_bytes):
183
- try:
184
- doc = fitz.open(stream=pdf_bytes, filetype="pdf")
185
- images = []
186
- for page in doc:
187
- pix = page.get_pixmap(matrix=fitz.Matrix(2.0, 2.0))
188
- img = Image.frombytes("RGB", [pix.width, pix.height], pix.samples)
189
- images.append(img)
190
- doc.close()
191
- return images
192
- except Exception as e:
193
- st.error(f"Failed to render PDF preview: {e}")
194
- return None
195
-
196
- with st.spinner("Generating PDF..."):
197
- pdf_bytes = create_pdf(st.session_state.markdown_content, base_font_size, plain_text_mode, num_columns, auto_bold_numbers)
198
-
199
- with st.container():
200
- pdf_images = pdf_to_image(pdf_bytes)
201
- if pdf_images:
202
- for img in pdf_images:
203
- st.image(img, use_container_width=True)
204
- else:
205
- st.info("Download the PDF to view it locally.")
206
-
207
- with st.sidebar:
208
- st.download_button(label="Download PDF", data=pdf_bytes, file_name="deities_guide.pdf", mime="application/pdf")
209
-
210
- default_markdown = """# Deities Guide: Mythology and Moral Lessons 🌟✨
211
-
212
- 1. 📜 **Introduction**
213
- - **Purpose**: Explore deities, spirits, saints, and beings with their epic stories and morals! 🌍📖
214
- - **Usage**: A guide for learning and storytelling across traditions. 🎭✍️
215
- - **Themes**: Justice ⚖️, faith 🙏, hubris 😤, redemption 🌈, cosmic order 🌌.
216
-
217
- 2. 🛠️ **Core Concepts of Divinity**
218
- - **Powers**: Creation 🌍, omniscience 👁️‍🗨️, shapeshifting 🦋 across entities.
219
- - **Life Cycle**: Mortality 💀, immortality ✨, transitions like saints and avatars 🌟.
220
- - **Communication**: Omens 🌩️, visions 👁️, miracles ✨ from gods and spirits.
221
-
222
- 3. ⚡ **Standard Abilities**
223
- - **Creation**: Gods and spirits shape worlds, e.g., Allah 🌍 and Vishnu 🌀.
224
- - **Influence**: Saints and prophets intercede, like Muhammad 🕌 and Paul ✝️.
225
- - **Transformation**: Angels and avatars shift forms, e.g., Gabriel 😇 and Krishna 🦚.
226
- - **Knowledge**: Foresight 🔮 or revelation 📜, as with the Holy Spirit 🕊️ and Brahma 🧠.
227
- - **Judgment**: Divine authority 👑, e.g., Yahweh ⚖️ and Yama 💀.
228
-
229
- 4. ⏳ **Mortality and Immortality**
230
- - **Gods**: Eternal ⏰, like Allah 🌟 and Shiva 🕉️.
231
- - **Spirits**: Realm-bound 🌠, e.g., jinn 🔥 and devas ✨.
232
- - **Saints/Prophets**: Mortal to divine 🌍➡️🌌, e.g., Moses 📜 and Rama 🏹.
233
- - **Beings**: Limbo states ❓, like cherubim 😇 and rakshasas 👹.
234
- - **Lessons**: Faith 🙏 and duty ⚙️ define transitions.
235
-
236
- 5. 🌠 **Ascension and Signs**
237
- - **Paths**: Birth 👶, deeds 🛡️, revelation 📖, as with Jesus ✝️ and Arjuna 🏹.
238
- - **Signs**: Miracles ✨ and prophecies 🔮, like those in the Quran 📘 and Gita 📚.
239
- - **Morals**: Obedience 🧎 and devotion ❤️ shape destiny 🌟.
240
-
241
- 6. 🎲 **Storytelling and Games**
242
- - **Portrayal**: Gods, spirits, and saints in narratives or RPGs 🎮📜.
243
- - **Dynamics**: Clerics ⛪, imams 🕌, and sadhus 🧘 serve higher powers.
244
- - **Balance**: Power 💪 vs. personality 😊 for depth.
245
-
246
- 7. 🎮 **Dungeon Mastering Beings**
247
- - **Gods**: Epic scope 🌌, e.g., Allah ✨ and Vishnu 🌀.
248
- - **Spirits**: Local influence 🏞️, like jinn 🔥 and apsaras 💃.
249
- - **Saints**: Moral anchors ⚓, e.g., St. Francis 🐾 and Ali ⚔️.
250
-
251
- 8. 🙏 **Devotee Relationships**
252
- - **Clerics**: Serve gods, e.g., Krishna’s priests 🦚.
253
- - **Mediums**: Channel spirits, like jinn whisperers 🔥👁️.
254
- - **Faithful**: Venerate saints and prophets, e.g., Fatima’s followers 🌹.
255
-
256
- 9. 🦅 **American Indian Traditions**
257
- - **Coyote, Raven, White Buffalo Woman**: Trickster kin 🦊🐦 and wise mother 🐃.
258
- - **Relation**: Siblings and guide teach balance ⚖️.
259
- - **Lesson**: Chaos 🌪️ breeds wisdom 🧠.
260
-
261
- 10. ⚔️ **Arthurian Legends**
262
- - **Merlin, Morgan le Fay, Arthur**: Mentor 🧙, rival 🧙‍♀️, son 👑.
263
- - **Relation**: Family tests loyalty 🤝.
264
- - **Lesson**: Honor 🛡️ vs. betrayal 🗡️.
265
-
266
- 11. 🏛️ **Babylonian Mythology**
267
- - **Marduk, Tiamat, Ishtar**: Son ⚔️, mother 🌊, lover ❤️.
268
- - **Relation**: Kinship drives order 🏰.
269
- - **Lesson**: Power 💪 reshapes chaos 🌪️.
270
-
271
- 12. ✝️ **Christian Trinity**
272
- - **God (Yahweh), Jesus, Holy Spirit**: Father 👑, Son ✝️, Spirit 🕊️.
273
- - **Relation**: Divine family redeems 🌈.
274
- - **Lesson**: Faith 🙏 restores grace ✨.
275
-
276
- 13. 😇 **Christian Saints & Angels**
277
- - **St. Michael, Gabriel, Mary**: Warrior ⚔️, messenger 📜, mother 🌹.
278
- - **Relation**: Heavenly kin serve God 👑.
279
- - **Lesson**: Duty ⚙️ upholds divine will 🌟.
280
-
281
- 14. 🍀 **Celtic Mythology**
282
- - **Lugh, Morrigan, Cernunnos**: Son ☀️, mother 🦇, father 🦌.
283
- - **Relation**: Family governs cycles 🌍.
284
- - **Lesson**: Courage 💪 in fate 🎲.
285
-
286
- 15. 🌄 **Central American Traditions**
287
- - **Quetzalcoatl, Tezcatlipoca, Huitzilopochtli**: Brothers 🐍🐆 and war son ⚔️.
288
- - **Relation**: Sibling rivalry creates 🌍.
289
- - **Lesson**: Sacrifice 🩸 builds worlds 🏰.
290
-
291
- 16. 🐉 **Chinese Mythology**
292
- - **Jade Emperor, Nuwa, Sun Wukong**: Father 👑, mother 🐍, rebel son 🐒.
293
- - **Relation**: Family enforces harmony 🎶.
294
- - **Lesson**: Duty ⚙️ curbs chaos 🌪️.
295
-
296
- 17. 🐙 **Cthulhu Mythos**
297
- - **Cthulhu, Nyarlathotep, Yog-Sothoth**: Elder kin 🐙👁️‍🗨️🌌.
298
- - **Relation**: Cosmic trio overwhelms 😱.
299
- - **Lesson**: Insignificance 🌌 humbles 🙇.
300
-
301
- 18. ☥ **Egyptian Mythology**
302
- - **Ra, Osiris, Isis**: Father ☀️, son ⚰️, mother 🌟.
303
- - **Relation**: Family ensures renewal 🔄.
304
- - **Lesson**: Justice ⚖️ prevails.
305
-
306
- 19. ❄️ **Finnish Mythology**
307
- - **Väinämöinen, Louhi, Ukko**: Son 🎶, mother ❄️, father ⚡.
308
- - **Relation**: Kinship tests wisdom 🧠.
309
- - **Lesson**: Perseverance 🏋️ wins.
310
-
311
- 20. 🏛️ **Greek Mythology**
312
- - **Zeus, Hera, Athena**: Father ⚡, mother 👑, daughter 🦇.
313
- - **Relation**: Family rules with tension ⚔️.
314
- - **Lesson**: Hubris 😤 meets wisdom 🧠.
315
-
316
- 21. 🕉️ **Hindu Trimurti**
317
- - **Brahma, Vishnu, Shiva**: Creator 🌀, preserver 🛡️, destroyer 🔥.
318
- - **Relation**: Divine trio cycles existence 🔄.
319
- - **Lesson**: Balance ⚖️ sustains life 🌍.
320
-
321
- 22. 🌺 **Hindu Avatars & Devis**
322
- - **Krishna, Rama, Durga**: Sons 🦚🏹 and fierce mother 🗡️.
323
- - **Relation**: Avatars and goddess protect dharma ⚖️.
324
- - **Lesson**: Duty ⚙️ defeats evil 👹.
325
-
326
- 23. 🌸 **Japanese Mythology**
327
- - **Amaterasu, Susanoo, Tsukuyomi**: Sister ☀️, brothers 🌊🌙.
328
- - **Relation**: Siblings balance cosmos 🌌.
329
- - **Lesson**: Harmony 🎶 vs. chaos 🌪️.
330
-
331
- 24. 🗡️ **Melnibonean Legends**
332
- - **Arioch, Xiombarg, Elric**: Lords 👑 and mortal son ⚔️.
333
- - **Relation**: Pact binds chaos 🌪️.
334
- - **Lesson**: Power 💪 corrupts 😈.
335
-
336
- 25. ☪️ **Muslim Divine & Messengers**
337
- - **Allah, Muhammad, Gabriel**: God 🌟, prophet 🕌, angel 😇.
338
- - **Relation**: Messenger reveals divine will 📜.
339
- - **Lesson**: Submission 🙇 brings peace ☮️.
340
-
341
- 26. 👻 **Muslim Spirits & Kin**
342
- - **Jinn, Iblis, Khidr**: Spirits 🔥😈 and guide 🌿 defy or aid.
343
- - **Relation**: Supernatural kin test faith 🙏.
344
- - **Lesson**: Obedience 🧎 vs. rebellion 😡.
345
-
346
- 27. 🏰 **Nehwon Legends**
347
- - **Death, Ningauble, Sheelba**: Fateful trio 💀👁️‍🗨️🌿.
348
- - **Relation**: Guides shape destiny 🎲.
349
- - **Lesson**: Cunning 🧠 defies fate ⚰️.
350
-
351
- 28. 🧝 **Nonhuman Traditions**
352
- - **Corellon, Moradin, Gruumsh**: Elf 🧝, dwarf ⛏️, orc 🗡️ fathers.
353
- - **Relation**: Rivals define purpose ⚔️.
354
- - **Lesson**: Community 🤝 endures.
355
-
356
- 29. ᚱ **Norse Mythology**
357
- - **Odin, Frigg, Loki**: Father 👁️, mother 👑, trickster son 🦊.
358
- - **Relation**: Family faces doom ⚡.
359
- - **Lesson**: Sacrifice 🩸 costs.
360
-
361
- 30. 🗿 **Sumerian Mythology**
362
- - **Enki, Inanna, Anu**: Son 🌊, daughter ❤️, father 🌌.
363
- - **Relation**: Kin wield knowledge 🧠.
364
- - **Lesson**: Ambition 🌟 shapes.
365
-
366
- 31. 📚 **Appendices**
367
- - **Planes**: Realms of gods, spirits, saints, e.g., Paradise 🌈 and Svarga ✨.
368
- - **Symbols**: Rituals 🕉️ and artifacts 🗿 of faith.
369
- - **Charts**: Domains and duties for devotees 📊.
370
-
371
- 32. 🌌 **Planes of Existence**
372
- - **Heaven/Paradise**: Christian/Muslim abode 🌟.
373
- - **Svarga**: Hindu divine realm ✨.
374
- - **Underworld**: Spirits linger, e.g., Sheol ⚰️ and Naraka 🔥.
375
-
376
- 33. 🕍 **Temple Trappings**
377
- - **Cross/Crescent**: Christian/Muslim faith ✝️☪️.
378
- - **Mandalas**: Hindu devotion 🌀.
379
- - **Relics**: Saints’ and prophets’ legacy 🗝️.
380
-
381
- 34. 📊 **Clerical Chart**
382
- - **Gods**: Domains, e.g., creation 🌍 and mercy ❤️.
383
- - **Spirits**: Influence, like guidance 🌿 and mischief 😈.
384
- - **Saints/Prophets**: Virtues, e.g., justice ⚖️ and prophecy 🔮.
385
- """
386
-
387
- create_pdf_tab(default_markdown)