awacke1 commited on
Commit
06678db
·
verified ·
1 Parent(s): 2ad273f

Delete backup1.app.py

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