awacke1 commited on
Commit
47411c6
ยท
verified ยท
1 Parent(s): 017c13f

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +581 -0
app.py ADDED
@@ -0,0 +1,581 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import io
2
+ import os
3
+ import re
4
+ import glob
5
+ import textwrap
6
+ from datetime import datetime
7
+ from pathlib import Path
8
+ import streamlit as st
9
+ import pandas as pd
10
+ from PIL import Image
11
+ from reportlab.pdfgen import canvas
12
+ from reportlab.lib.pagesizes import letter, A4
13
+ from reportlab.lib.utils import ImageReader
14
+ from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer, Table, TableStyle, Image as ReportLabImage
15
+ from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
16
+ from reportlab.lib import colors
17
+ from reportlab.pdfbase import pdfmetrics
18
+ from reportlab.pdfbase.ttfonts import TTFont
19
+ import mistune
20
+ import fitz
21
+ import edge_tts
22
+ import asyncio
23
+ import base64
24
+ from urllib.parse import quote
25
+
26
+ # Page config
27
+ st.set_page_config(page_title="PDF & Code Interpreter", layout="wide", page_icon="๐Ÿš€")
28
+
29
+ def delete_asset(path):
30
+ try:
31
+ os.remove(path)
32
+ except Exception as e:
33
+ st.error(f"Error deleting file: {e}")
34
+ st.rerun()
35
+
36
+ async def generate_audio(text, voice, filename):
37
+ communicate = edge_tts.Communicate(text, voice)
38
+ await communicate.save(filename)
39
+ return filename
40
+
41
+ def clean_for_speech(text):
42
+ text = text.replace("#", "")
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]+", flags=re.UNICODE)
55
+ return emoji_pattern.sub('', text)
56
+
57
+ def detect_and_convert_links(text):
58
+ md_link_pattern = re.compile(r'\[(.*?)\]\((https?://[^\s\[\]()<>{}]+)\)')
59
+ text = md_link_pattern.sub(r'<a href="\2" color="blue">\1</a>', text)
60
+ url_pattern = re.compile(r'(?<!href=")(https?://[^\s<>{}]+)', re.IGNORECASE)
61
+ text = url_pattern.sub(r'<a href="\1" color="blue">\1</a>', text)
62
+ return text
63
+
64
+ def apply_emoji_font(text, emoji_font):
65
+ tag_pattern = re.compile(r'(<[^>]+>)')
66
+ segments = tag_pattern.split(text)
67
+ result = []
68
+ emoji_pattern = re.compile(
69
+ r"([\U0001F300-\U0001F5FF"
70
+ r"\U0001F600-\U0001F64F"
71
+ r"\U0001F680-\U0001F6FF"
72
+ r"\U0001F700-\U0001F77F"
73
+ r"\U0001F780-\U0001F7FF"
74
+ r"\U0001F800-\U0001F8FF"
75
+ r"\U0001F900-\U0001F9FF"
76
+ r"\U0001FAD0-\U0001FAD9"
77
+ r"\U0001FA00-\U0001FA6F"
78
+ r"\U0001FA70-\U0001FAFF"
79
+ r"\u2600-\u26FF"
80
+ r"\u2700-\u27BF]+)"
81
+ )
82
+ def replace_emoji(match):
83
+ emoji = match.group(1)
84
+ return f'<font face="{emoji_font}">{emoji}</font>'
85
+ for segment in segments:
86
+ if tag_pattern.match(segment):
87
+ result.append(segment)
88
+ else:
89
+ parts = []
90
+ last_pos = 0
91
+ for match in emoji_pattern.finditer(segment):
92
+ start, end = match.span()
93
+ if last_pos < start:
94
+ parts.append(f'<font face="DejaVuSans">{segment[last_pos:start]}</font>')
95
+ parts.append(replace_emoji(match))
96
+ last_pos = end
97
+ if last_pos < len(segment):
98
+ parts.append(f'<font face="DejaVuSans">{segment[last_pos:]}</font>')
99
+ result.append(''.join(parts))
100
+ return ''.join(result)
101
+
102
+ def markdown_to_pdf_content(markdown_text, add_space_before_numbered, headings_to_fonts):
103
+ lines = markdown_text.strip().split('\n')
104
+ pdf_content = []
105
+ number_pattern = re.compile(r'^\d+(\.\d+)*\.\s')
106
+ heading_pattern = re.compile(r'^(#{1,4})\s+(.+)$')
107
+ first_numbered_seen = False
108
+ for line in lines:
109
+ line = line.strip()
110
+ if not line:
111
+ continue
112
+ if headings_to_fonts and line.startswith('#'):
113
+ heading_match = heading_pattern.match(line)
114
+ if heading_match:
115
+ level = len(heading_match.group(1))
116
+ heading_text = heading_match.group(2).strip()
117
+ formatted_heading = f"<h{level}>{heading_text}</h{level}>"
118
+ pdf_content.append(formatted_heading)
119
+ continue
120
+ is_numbered_line = number_pattern.match(line) is not None
121
+ if add_space_before_numbered and is_numbered_line:
122
+ if first_numbered_seen and not line.startswith("1."):
123
+ pdf_content.append("")
124
+ if not first_numbered_seen:
125
+ first_numbered_seen = True
126
+ line = detect_and_convert_links(line)
127
+ line = re.sub(r'\*\*(.+?)\*\*', r'<b>\1</b>', line)
128
+ line = re.sub(r'\*([^*]+?)\*', r'<b>\1</b>', line)
129
+ pdf_content.append(line)
130
+ total_lines = len(pdf_content)
131
+ return pdf_content, total_lines
132
+
133
+ def create_pdf(markdown_texts, image_files, base_font_size=14, num_columns=2, add_space_before_numbered=True, headings_to_fonts=True, doc_title="Combined Document"):
134
+ if not markdown_texts and not image_files:
135
+ return None
136
+ buffer = io.BytesIO()
137
+ page_width = A4[0] * 2
138
+ page_height = A4[1]
139
+ doc = SimpleDocTemplate(
140
+ buffer,
141
+ pagesize=(page_width, page_height),
142
+ leftMargin=36,
143
+ rightMargin=36,
144
+ topMargin=36,
145
+ bottomMargin=36,
146
+ title=doc_title
147
+ )
148
+ styles = getSampleStyleSheet()
149
+ spacer_height = 10
150
+ try:
151
+ pdfmetrics.registerFont(TTFont("DejaVuSans", "DejaVuSans.ttf"))
152
+ pdfmetrics.registerFont(TTFont("NotoEmoji-Bold", "NotoEmoji-Bold.ttf"))
153
+ except Exception as e:
154
+ st.error(f"Font registration error: {e}")
155
+ return None
156
+ story = []
157
+ for markdown_text in markdown_texts:
158
+ pdf_content, total_lines = markdown_to_pdf_content(markdown_text, add_space_before_numbered, headings_to_fonts)
159
+ total_chars = sum(len(line) for line in pdf_content)
160
+ hierarchy_weight = sum(1.5 if line.startswith("<b>") else 1 for line in pdf_content)
161
+ longest_line_words = max(len(line.split()) for line in pdf_content) if pdf_content else 0
162
+ content_density = total_lines * hierarchy_weight + total_chars / 50
163
+ usable_height = page_height - 72 - spacer_height
164
+ usable_width = page_width - 72
165
+ avg_line_chars = total_chars / total_lines if total_lines > 0 else 50
166
+ col_width = usable_width / num_columns
167
+ min_font_size = 5
168
+ max_font_size = 16
169
+ lines_per_col = total_lines / num_columns if num_columns > 0 else total_lines
170
+ target_height_per_line = usable_height / lines_per_col if lines_per_col > 0 else usable_height
171
+ estimated_font_size = int(target_height_per_line / 1.5)
172
+ adjusted_font_size = max(min_font_size, min(max_font_size, estimated_font_size))
173
+ if avg_line_chars > col_width / adjusted_font_size * 10:
174
+ adjusted_font_size = int(col_width / (avg_line_chars / 10))
175
+ adjusted_font_size = max(min_font_size, adjusted_font_size)
176
+ if longest_line_words > 17 or lines_per_col > 20:
177
+ font_scale = min(17 / max(longest_line_words, 17), 60 / max(lines_per_col, 20))
178
+ adjusted_font_size = max(min_font_size, int(base_font_size * font_scale))
179
+ item_style = ParagraphStyle(
180
+ 'ItemStyle', parent=styles['Normal'], fontName="DejaVuSans",
181
+ fontSize=adjusted_font_size, leading=adjusted_font_size * 1.15, spaceAfter=1,
182
+ linkUnderline=True
183
+ )
184
+ numbered_bold_style = ParagraphStyle(
185
+ 'NumberedBoldStyle', parent=styles['Normal'], fontName="NotoEmoji-Bold",
186
+ fontSize=adjusted_font_size, leading=adjusted_font_size * 1.15, spaceAfter=1,
187
+ linkUnderline=True
188
+ )
189
+ section_style = ParagraphStyle(
190
+ 'SectionStyle', parent=styles['Heading2'], fontName="DejaVuSans",
191
+ textColor=colors.darkblue, fontSize=adjusted_font_size * 1.1, leading=adjusted_font_size * 1.32, spaceAfter=2,
192
+ linkUnderline=True
193
+ )
194
+ columns = [[] for _ in range(num_columns)]
195
+ lines_per_column = total_lines / num_columns if num_columns > 0 else total_lines
196
+ current_line_count = 0
197
+ current_column = 0
198
+ number_pattern = re.compile(r'^\d+(\.\d+)*\.\s')
199
+ for item in pdf_content:
200
+ if current_line_count >= lines_per_column and current_column < num_columns - 1:
201
+ current_column += 1
202
+ current_line_count = 0
203
+ columns[current_column].append(item)
204
+ current_line_count += 1
205
+ column_cells = [[] for _ in range(num_columns)]
206
+ for col_idx, column in enumerate(columns):
207
+ for item in column:
208
+ if isinstance(item, str):
209
+ heading_match = re.match(r'<h(\d)>(.*?)</h\1>', item) if headings_to_fonts else None
210
+ if heading_match:
211
+ level = int(heading_match.group(1))
212
+ heading_text = heading_match.group(2)
213
+ heading_style = ParagraphStyle(
214
+ f'Heading{level}Style',
215
+ parent=styles['Heading1'],
216
+ fontName="DejaVuSans",
217
+ textColor=colors.darkblue if level == 1 else (colors.black if level > 2 else colors.blue),
218
+ fontSize=adjusted_font_size * (1.6 - (level-1)*0.15),
219
+ leading=adjusted_font_size * (1.8 - (level-1)*0.15),
220
+ spaceAfter=4 - (level-1),
221
+ spaceBefore=6 - (level-1),
222
+ linkUnderline=True
223
+ )
224
+ column_cells[col_idx].append(Paragraph(apply_emoji_font(heading_text, "NotoEmoji-Bold"), heading_style))
225
+ elif item.startswith("<b>") and item.endswith("</b>"):
226
+ content = item[3:-4].strip()
227
+ if number_pattern.match(content):
228
+ column_cells[col_idx].append(Paragraph(apply_emoji_font(content, "NotoEmoji-Bold"), numbered_bold_style))
229
+ else:
230
+ column_cells[col_idx].append(Paragraph(apply_emoji_font(content, "NotoEmoji-Bold"), section_style))
231
+ else:
232
+ column_cells[col_idx].append(Paragraph(apply_emoji_font(item, "NotoEmoji-Bold"), item_style))
233
+ else:
234
+ column_cells[col_idx].append(Paragraph(apply_emoji_font(str(item), "NotoEmoji-Bold"), item_style))
235
+ max_cells = max(len(cells) for cells in column_cells) if column_cells else 0
236
+ for cells in column_cells:
237
+ cells.extend([Paragraph("", item_style)] * (max_cells - len(cells)))
238
+ table_data = list(zip(*column_cells)) if column_cells else [[]]
239
+ table = Table(table_data, colWidths=[col_width] * num_columns, hAlign='CENTER')
240
+ table.setStyle(TableStyle([
241
+ ('VALIGN', (0, 0), (-1, -1), 'TOP'),
242
+ ('ALIGN', (0, 0), (-1, -1), 'LEFT'),
243
+ ('BACKGROUND', (0, 0), (-1, -1), colors.white),
244
+ ('GRID', (0, 0), (-1, -1), 0, colors.white),
245
+ ('LINEAFTER', (0, 0), (num_columns-1, -1), 0.5, colors.grey),
246
+ ('LEFTPADDING', (0, 0), (-1, -1), 2),
247
+ ('RIGHTPADDING', (0, 0), (-1, -1), 2),
248
+ ('TOPPADDING', (0, 0), (-1, -1), 1),
249
+ ('BOTTOMPADDING', (0, 0), (-1, -1), 1),
250
+ ]))
251
+ story.append(Spacer(1, spacer_height))
252
+ story.append(table)
253
+ story.append(Spacer(1, spacer_height * 2))
254
+ for img_path in image_files:
255
+ try:
256
+ img = Image.open(img_path)
257
+ img_width, img_height = img.size
258
+ page_width, page_height = A4
259
+ scale = min((page_width - 40) / img_width, (page_height - 40) / img_height)
260
+ new_width = img_width * scale
261
+ new_height = img_height * scale
262
+ story.append(ReportLabImage(img_path, width=new_width, height=new_height))
263
+ story.append(Spacer(1, spacer_height))
264
+ except Exception as e:
265
+ st.warning(f"Could not process image {img_path}: {e}")
266
+ continue
267
+ doc.build(story)
268
+ buffer.seek(0)
269
+ return buffer.getvalue()
270
+
271
+ def pdf_to_image(pdf_bytes):
272
+ if pdf_bytes is None:
273
+ return None
274
+ try:
275
+ doc = fitz.open(stream=pdf_bytes, filetype="pdf")
276
+ images = []
277
+ for page in doc:
278
+ pix = page.get_pixmap(matrix=fitz.Matrix(2.0, 2.0))
279
+ img = Image.frombytes("RGB", [pix.width, pix.height], pix.samples)
280
+ images.append(img)
281
+ doc.close()
282
+ return images
283
+ except Exception as e:
284
+ st.error(f"Failed to render PDF preview: {e}")
285
+ return None
286
+
287
+ def get_video_html(video_path, width="100%"):
288
+ try:
289
+ video_url = f"data:video/mp4;base64,{base64.b64encode(open(video_path, 'rb').read()).decode()}"
290
+ return f'''
291
+ <video width="{width}" controls autoplay muted loop>
292
+ <source src="{video_url}" type="video/mp4">
293
+ Your browser does not support the video tag.
294
+ </video>
295
+ '''
296
+ except Exception as e:
297
+ st.warning(f"Could not load video {video_path}: {e}")
298
+ return ""
299
+
300
+ def display_glossary_entity(k):
301
+ search_urls = {
302
+ "๐Ÿš€๐ŸŒŒArXiv": lambda k: f"https://arxiv.org/search/?query={quote(k)}&searchtype=all",
303
+ "๐Ÿ“–": lambda k: f"https://en.wikipedia.org/wiki/{quote(k)}",
304
+ "๐Ÿ”": lambda k: f"https://www.google.com/search?q={quote(k)}",
305
+ "๐ŸŽฅ": lambda k: f"https://www.youtube.com/results?search_query={quote(k)}",
306
+ }
307
+ links_md = ' '.join([f"[{emoji}]({url(k)})" for emoji, url in search_urls.items()])
308
+ st.markdown(f"**{k}** <small>{links_md}</small>", unsafe_allow_html=True)
309
+
310
+ # Tabs setup
311
+ tab1, tab2 = st.tabs(["๐Ÿ“„ PDF Composer", "๐Ÿงช Code Interpreter"])
312
+
313
+ with tab1:
314
+ st.header("๐Ÿ“„ PDF Composer & Voice Generator ๐Ÿš€")
315
+ # Sidebar PDF text settings
316
+ columns = st.sidebar.slider("Text columns", 1, 3, 2)
317
+ font_family = st.sidebar.selectbox("Font", ["Helvetica", "Times-Roman", "Courier", "DejaVuSans"])
318
+ font_size = st.sidebar.slider("Font size", 6, 24, 14)
319
+ # Markdown input
320
+ md_file = st.file_uploader("Upload Markdown (.md)", type=["md"])
321
+ if md_file:
322
+ md_text = md_file.getvalue().decode("utf-8")
323
+ stem = Path(md_file.name).stem
324
+ else:
325
+ md_text = st.text_area("Or enter markdown text directly", height=200)
326
+ stem = datetime.now().strftime('%Y%m%d_%H%M%S')
327
+ # Convert Markdown to plain text
328
+ renderer = mistune.HTMLRenderer()
329
+ markdown = mistune.create_markdown(renderer=renderer)
330
+ html = markdown(md_text or "")
331
+ plain_text = re.sub(r'<[^>]+>', '', html)
332
+ # Voice settings
333
+ languages = {"English (US)": "en", "English (UK)": "en-uk", "Spanish": "es"}
334
+ voice_choice = st.selectbox("Voice Language", list(languages.keys()))
335
+ voice_lang = languages[voice_choice]
336
+ slow = st.checkbox("Slow Speech")
337
+ VOICES = ["en-US-AriaNeural", "en-US-JennyNeural", "en-GB-SoniaNeural", "en-US-GuyNeural", "en-US-AnaNeural"]
338
+ selected_voice = st.selectbox("Select Voice for TTS", options=VOICES, index=0)
339
+ if st.button("๐Ÿ”Š Generate & Download Voice MP3 from Text"):
340
+ if plain_text.strip():
341
+ voice_file = f"{stem}_{selected_voice}.mp3"
342
+ try:
343
+ cleaned_text = clean_for_speech(plain_text)
344
+ audio_file = asyncio.run(generate_audio(cleaned_text, selected_voice, voice_file))
345
+ st.audio(audio_file)
346
+ with open(audio_file, 'rb') as mp3:
347
+ st.download_button("๐Ÿ“ฅ Download MP3", data=mp3, file_name=voice_file, mime="audio/mpeg")
348
+ except Exception as e:
349
+ st.error(f"Error generating voice: {e}")
350
+ else:
351
+ st.warning("No text to generate voice from.")
352
+ # Image uploads and ordering
353
+ imgs = st.file_uploader("Upload Images for PDF", type=["png", "jpg", "jpeg"], accept_multiple_files=True)
354
+ ordered_images = []
355
+ if imgs:
356
+ df_imgs = pd.DataFrame([{"name": f.name, "order": i} for i, f in enumerate(imgs)])
357
+ edited = st.data_editor(df_imgs, use_container_width=True, num_rows="dynamic")
358
+ for _, row in edited.sort_values("order").iterrows():
359
+ for f in imgs:
360
+ if f.name == row['name']:
361
+ ordered_images.append(f)
362
+ break
363
+ if st.button("๐Ÿ–‹๏ธ Generate PDF with Markdown & Images"):
364
+ if not plain_text.strip() and not ordered_images:
365
+ st.warning("Please provide some text or upload images to generate a PDF.")
366
+ else:
367
+ buf = io.BytesIO()
368
+ c = canvas.Canvas(buf)
369
+ if plain_text.strip():
370
+ page_w, page_h = letter
371
+ margin = 40
372
+ gutter = 20
373
+ col_w = (page_w - 2*margin - (columns-1)*gutter) / columns
374
+ c.setFont(font_family, font_size)
375
+ line_height = font_size * 1.2
376
+ col = 0
377
+ x = margin
378
+ y = page_h - margin
379
+ avg_char_width = font_size * 0.6
380
+ wrap_width = int(col_w / avg_char_width) if avg_char_width > 0 else 100
381
+ for paragraph in plain_text.split("\n"):
382
+ if not paragraph.strip():
383
+ y -= line_height
384
+ if y < margin:
385
+ col += 1
386
+ if col >= columns:
387
+ c.showPage()
388
+ c.setFont(font_family, font_size)
389
+ col = 0
390
+ x = margin + col*(col_w+gutter)
391
+ y = page_h - margin
392
+ continue
393
+ for line in textwrap.wrap(paragraph, wrap_width):
394
+ if y < margin:
395
+ col += 1
396
+ if col >= columns:
397
+ c.showPage()
398
+ c.setFont(font_family, font_size)
399
+ col = 0
400
+ x = margin + col*(col_w+gutter)
401
+ y = page_h - margin
402
+ c.drawString(x, y, line)
403
+ y -= line_height
404
+ y -= line_height
405
+ for img_f in ordered_images:
406
+ try:
407
+ img = Image.open(img_f)
408
+ w, h = img.size
409
+ c.showPage()
410
+ c.setPageSize((w, h))
411
+ c.drawImage(ImageReader(img), 0, 0, w, h, preserveAspectRatio=False)
412
+ except Exception as e:
413
+ st.warning(f"Could not process image {img_f.name}: {e}")
414
+ continue
415
+ c.save()
416
+ buf.seek(0)
417
+ pdf_name = f"{stem}.pdf"
418
+ st.download_button("โฌ‡๏ธ Download PDF", data=buf, file_name=pdf_name, mime="application/pdf")
419
+ st.markdown("---")
420
+ st.subheader("๐Ÿ“‚ Available Assets")
421
+ all_assets = glob.glob("*.*")
422
+ excluded_extensions = ['.py', '.ttf', '.txt']
423
+ excluded_files = ['README.md', 'index.html']
424
+ assets = sorted([
425
+ a for a in all_assets
426
+ if not (a.lower().endswith(tuple(excluded_extensions)) or a in excluded_files)
427
+ and a.lower().endswith(('.md', '.png', '.jpg', '.jpeg'))
428
+ ])
429
+ if 'selected_assets' not in st.session_state:
430
+ st.session_state.selected_assets = []
431
+ if not assets:
432
+ st.info("No available assets found.")
433
+ else:
434
+ for a in assets:
435
+ ext = a.split('.')[-1].lower()
436
+ cols = st.columns([1, 3, 1, 1])
437
+ with cols[0]:
438
+ is_selected = st.checkbox("", key=f"select_{a}", value=a in st.session_state.selected_assets)
439
+ if is_selected and a not in st.session_state.selected_assets:
440
+ st.session_state.selected_assets.append(a)
441
+ elif not is_selected and a in st.session_state.selected_assets:
442
+ st.session_state.selected_assets.remove(a)
443
+ cols[1].write(a)
444
+ try:
445
+ if ext == 'md':
446
+ with open(a, 'r', encoding='utf-8') as f:
447
+ cols[2].download_button("๐Ÿ“ฅ", data=f.read(), file_name=a, mime="text/markdown")
448
+ elif ext in ['png', 'jpg', 'jpeg']:
449
+ with open(a, 'rb') as img_file:
450
+ cols[2].download_button("โฌ‡๏ธ", data=img_file, file_name=a, mime=f"image/{ext}")
451
+ cols[3].button("๐Ÿ—‘๏ธ", key=f"del_{a}", on_click=delete_asset, args=(a,))
452
+ except Exception as e:
453
+ cols[3].error(f"Error handling file {a}: {e}")
454
+ if st.button("๐Ÿ“‘ Generate PDF from Selected Assets"):
455
+ if not st.session_state.selected_assets:
456
+ st.warning("Please select at least one asset to generate a PDF.")
457
+ else:
458
+ markdown_texts = []
459
+ image_files = []
460
+ for a in st.session_state.selected_assets:
461
+ ext = a.split('.')[-1].lower()
462
+ if ext == 'md':
463
+ with open(a, 'r', encoding='utf-8') as f:
464
+ markdown_texts.append(f.read())
465
+ elif ext in ['png', 'jpg', 'jpeg']:
466
+ image_files.append(a)
467
+ with st.spinner("Generating PDF from selected assets..."):
468
+ pdf_bytes = create_pdf(
469
+ markdown_texts=markdown_texts,
470
+ image_files=image_files,
471
+ base_font_size=14,
472
+ num_columns=2,
473
+ add_space_before_numbered=True,
474
+ headings_to_fonts=True,
475
+ doc_title="Combined_Selected_Assets"
476
+ )
477
+ if pdf_bytes:
478
+ pdf_images = pdf_to_image(pdf_bytes)
479
+ if pdf_images:
480
+ st.subheader("Preview of Generated PDF")
481
+ for i, img in enumerate(pdf_images):
482
+ st.image(img, caption=f"Page {i+1}", use_container_width=True)
483
+ prefix = datetime.now().strftime("%Y%m%d_%H%M%S")
484
+ st.download_button(
485
+ label="๐Ÿ’พ Download Combined PDF",
486
+ data=pdf_bytes,
487
+ file_name=f"{prefix}_combined.pdf",
488
+ mime="application/pdf"
489
+ )
490
+ else:
491
+ st.error("Failed to generate PDF.")
492
+ st.markdown("---")
493
+ st.subheader("๐Ÿ–ผ Image Gallery")
494
+ image_files = glob.glob("*.png") + glob.glob("*.jpg") + glob.glob("*.jpeg")
495
+ image_cols = st.slider("Gallery Columns ๐Ÿ–ผ", min_value=1, max_value=15, value=5, key="image_cols")
496
+ if image_files:
497
+ cols = st.columns(image_cols)
498
+ for idx, image_file in enumerate(image_files):
499
+ with cols[idx % image_cols]:
500
+ try:
501
+ img = Image.open(image_file)
502
+ st.image(img, caption=image_file, use_container_width=True)
503
+ display_glossary_entity(os.path.splitext(image_file)[0])
504
+ except Exception as e:
505
+ st.warning(f"Could not load image {image_file}: {e}")
506
+ else:
507
+ st.info("No images found in the current directory.")
508
+ st.markdown("---")
509
+ st.subheader("๐ŸŽฅ Video Gallery")
510
+ video_files = glob.glob("*.mp4")
511
+ video_cols = st.slider("Gallery Columns ๐ŸŽฌ", min_value=1, max_value=5, value=3, key="video_cols")
512
+ if video_files:
513
+ cols = st.columns(video_cols)
514
+ for idx, video_file in enumerate(video_files):
515
+ with cols[idx % video_cols]:
516
+ st.markdown(get_video_html(video_file, width="100%"), unsafe_allow_html=True)
517
+ display_glossary_entity(os.path.splitext(video_file)[0])
518
+ else:
519
+ st.info("No videos found in the current directory.")
520
+
521
+ with tab2:
522
+ st.header("๐Ÿงช Python Code Executor & Demo")
523
+ import io, sys
524
+ from contextlib import redirect_stdout
525
+ DEFAULT_CODE = '''import streamlit as st
526
+ import random
527
+ st.title("๐Ÿ“Š Demo App")
528
+ st.markdown("Random number and color demo")
529
+ col1, col2 = st.columns(2)
530
+ with col1:
531
+ num = st.number_input("Number:", 1, 100, 10)
532
+ mul = st.slider("Multiplier:", 1, 10, 2)
533
+ if st.button("Calc"):
534
+ st.write(num * mul)
535
+ with col2:
536
+ color = st.color_picker("Pick color","#ff0000")
537
+ st.markdown(f'<div style="background:{color};padding:10px;">Color</div>', unsafe_allow_html=True)
538
+ '''
539
+ def extract_python_code(md: str) -> list:
540
+ return re.findall(r"```python\s*(.*?)```", md, re.DOTALL)
541
+ def execute_code(code: str) -> tuple:
542
+ buf = io.StringIO(); local_vars = {}
543
+ try:
544
+ with redirect_stdout(buf):
545
+ exec(code, {}, local_vars)
546
+ return buf.getvalue(), None
547
+ except Exception as e:
548
+ return None, str(e)
549
+ up = st.file_uploader("Upload .py or .md", type=['py', 'md'])
550
+ if 'code' not in st.session_state:
551
+ st.session_state.code = DEFAULT_CODE
552
+ if up:
553
+ text = up.getvalue().decode()
554
+ if up.type == 'text/markdown':
555
+ codes = extract_python_code(text)
556
+ if codes:
557
+ st.session_state.code = codes[0].strip()
558
+ else:
559
+ st.warning("No Python code block found in the markdown file.")
560
+ st.session_state.code = ''
561
+ else:
562
+ st.session_state.code = text.strip()
563
+ st.code(st.session_state.code, language='python')
564
+ else:
565
+ st.session_state.code = st.text_area("๐Ÿ’ป Code Editor", value=st.session_state.code, height=400)
566
+ c1, c2 = st.columns([1, 1])
567
+ if c1.button("โ–ถ๏ธ Run Code"):
568
+ if st.session_state.code.strip():
569
+ out, err = execute_code(st.session_state.code)
570
+ if err:
571
+ st.error(f"Execution Error:\n{err}")
572
+ elif out:
573
+ st.subheader("Output:")
574
+ st.code(out)
575
+ else:
576
+ st.success("Executed with no standard output.")
577
+ else:
578
+ st.warning("No code to run.")
579
+ if c2.button("๐Ÿ—‘๏ธ Clear Code"):
580
+ st.session_state.code = ''
581
+ st.rerun()