Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -10,702 +10,299 @@ import fitz
|
|
| 10 |
import edge_tts
|
| 11 |
import asyncio
|
| 12 |
import base64
|
| 13 |
-
|
| 14 |
from datetime import datetime
|
| 15 |
-
from pathlib import Path
|
| 16 |
from PIL import Image
|
| 17 |
from reportlab.pdfgen import canvas
|
| 18 |
-
from reportlab.lib.pagesizes import letter, A4, legal, A3, A5,
|
| 19 |
from reportlab.lib.utils import ImageReader
|
| 20 |
-
from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer, Table, TableStyle, Image as ReportLabImage
|
| 21 |
from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
|
| 22 |
from reportlab.lib import colors
|
| 23 |
from reportlab.pdfbase import pdfmetrics
|
| 24 |
from reportlab.pdfbase.ttfonts import TTFont
|
| 25 |
from urllib.parse import quote
|
| 26 |
|
| 27 |
-
#
|
| 28 |
-
|
|
|
|
| 29 |
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 36 |
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
return filename
|
| 41 |
|
| 42 |
-
def
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
r"\U0001F600-\U0001F64F"
|
| 47 |
-
r"\U0001F680-\U0001F6FF"
|
| 48 |
-
r"\U0001F700-\U0001F77F"
|
| 49 |
-
r"\U0001F780-\U0001F7FF"
|
| 50 |
-
r"\U0001F800-\U0001F8FF"
|
| 51 |
-
r"\U0001F900-\U0001F9FF"
|
| 52 |
-
r"\U0001FA00-\U0001FA6F"
|
| 53 |
-
r"\U0001FA70-\U0001FAFF"
|
| 54 |
-
r"\u2600-\u26FF"
|
| 55 |
-
r"\u2700-\u27BF]+", flags=re.UNICODE)
|
| 56 |
-
return emoji_pattern.sub('', text)
|
| 57 |
|
| 58 |
-
def
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
url_pattern = re.compile(r'(?<!href=")(https?://[^\s<>{}]+)', re.IGNORECASE)
|
| 62 |
-
text = url_pattern.sub(r'<a href="\1" color="blue">\1</a>', text)
|
| 63 |
-
return text
|
| 64 |
|
| 65 |
-
def apply_emoji_font(text, emoji_font):
|
| 66 |
-
tag_pattern = re.compile(r'(<[^>]+>)')
|
| 67 |
-
segments = tag_pattern.split(text)
|
| 68 |
-
result = []
|
| 69 |
-
emoji_pattern = re.compile(
|
| 70 |
-
r"([\U0001F300-\U0001F5FF"
|
| 71 |
-
r"\U0001F600-\U0001F64F"
|
| 72 |
-
r"\U0001F680-\U0001F6FF"
|
| 73 |
-
r"\U0001F700-\U0001F77F"
|
| 74 |
-
r"\U0001F780-\U0001F7FF"
|
| 75 |
-
r"\U0001F800-\U0001F8FF"
|
| 76 |
-
r"\U0001F900-\U0001F9FF"
|
| 77 |
-
r"\U0001FAD0-\U0001FAD9"
|
| 78 |
-
r"\U0001FA00-\U0001FA6F"
|
| 79 |
-
r"\U0001FA70-\U0001FAFF"
|
| 80 |
-
r"\u2600-\u26FF"
|
| 81 |
-
r"\u2700-\u27BF]+)"
|
| 82 |
-
)
|
| 83 |
-
def replace_emoji(match):
|
| 84 |
-
emoji = match.group(1)
|
| 85 |
-
return f'<font face="{emoji_font}">{emoji}</font>'
|
| 86 |
-
for segment in segments:
|
| 87 |
-
if tag_pattern.match(segment):
|
| 88 |
-
result.append(segment)
|
| 89 |
-
else:
|
| 90 |
-
parts = []
|
| 91 |
-
last_pos = 0
|
| 92 |
-
for match in emoji_pattern.finditer(segment):
|
| 93 |
-
start, end = match.span()
|
| 94 |
-
if last_pos < start:
|
| 95 |
-
parts.append(f'<font face="DejaVuSans">{segment[last_pos:start]}</font>')
|
| 96 |
-
parts.append(replace_emoji(match))
|
| 97 |
-
last_pos = end
|
| 98 |
-
if last_pos < len(segment):
|
| 99 |
-
parts.append(f'<font face="DejaVuSans">{segment[last_pos:]}</font>')
|
| 100 |
-
result.append(''.join(parts))
|
| 101 |
-
return ''.join(result)
|
| 102 |
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
first_numbered_seen = False
|
| 109 |
-
for line in lines:
|
| 110 |
-
line = line.strip()
|
| 111 |
-
if not line:
|
| 112 |
-
continue
|
| 113 |
-
if headings_to_fonts and line.startswith('#'):
|
| 114 |
-
heading_match = heading_pattern.match(line)
|
| 115 |
-
if heading_match:
|
| 116 |
-
level = len(heading_match.group(1))
|
| 117 |
-
heading_text = heading_match.group(2).strip()
|
| 118 |
-
formatted_heading = f"<h{level}>{heading_text}</h{level}>"
|
| 119 |
-
pdf_content.append(formatted_heading)
|
| 120 |
-
continue
|
| 121 |
-
is_numbered_line = number_pattern.match(line) is not None
|
| 122 |
-
if add_space_before_numbered and is_numbered_line:
|
| 123 |
-
if first_numbered_seen and not line.startswith("1."):
|
| 124 |
-
pdf_content.append("")
|
| 125 |
-
if not first_numbered_seen:
|
| 126 |
-
first_numbered_seen = True
|
| 127 |
-
line = detect_and_convert_links(line)
|
| 128 |
-
line = re.sub(r'\*\*(.+?)\*\*', r'<b>\1</b>', line)
|
| 129 |
-
line = re.sub(r'\*([^*]+?)\*', r'<b>\1</b>', line)
|
| 130 |
-
pdf_content.append(line)
|
| 131 |
-
total_lines = len(pdf_content)
|
| 132 |
-
return pdf_content, total_lines
|
| 133 |
|
| 134 |
-
|
| 135 |
-
|
| 136 |
-
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
|
| 141 |
-
|
| 142 |
-
elif page_size == "Letter":
|
| 143 |
-
page_dimensions = letter
|
| 144 |
-
elif page_size == "Legal":
|
| 145 |
-
page_dimensions = legal
|
| 146 |
-
elif page_size == "A3":
|
| 147 |
-
page_dimensions = A3
|
| 148 |
-
elif page_size == "A5":
|
| 149 |
-
page_dimensions = A5
|
| 150 |
-
else:
|
| 151 |
-
page_dimensions = A4 # Default fallback
|
| 152 |
|
| 153 |
-
|
| 154 |
-
page_height = page_dimensions[1]
|
| 155 |
-
|
| 156 |
-
doc = SimpleDocTemplate(
|
| 157 |
-
buffer,
|
| 158 |
-
pagesize=(page_width, page_height),
|
| 159 |
-
leftMargin=36,
|
| 160 |
-
rightMargin=36,
|
| 161 |
-
topMargin=36,
|
| 162 |
-
bottomMargin=36,
|
| 163 |
-
title=doc_title
|
| 164 |
-
)
|
| 165 |
-
styles = getSampleStyleSheet()
|
| 166 |
-
spacer_height = 10
|
| 167 |
-
try:
|
| 168 |
-
pdfmetrics.registerFont(TTFont("DejaVuSans", "DejaVuSans.ttf"))
|
| 169 |
-
pdfmetrics.registerFont(TTFont("NotoEmoji-Bold", "NotoEmoji-Bold.ttf"))
|
| 170 |
-
except Exception as e:
|
| 171 |
-
st.error(f"Font registration error: {e}")
|
| 172 |
-
return None
|
| 173 |
-
story = []
|
| 174 |
-
for markdown_text in markdown_texts:
|
| 175 |
-
pdf_content, total_lines = markdown_to_pdf_content(markdown_text, add_space_before_numbered, headings_to_fonts)
|
| 176 |
-
total_chars = sum(len(line) for line in pdf_content)
|
| 177 |
-
hierarchy_weight = sum(1.5 if line.startswith("<b>") else 1 for line in pdf_content)
|
| 178 |
-
longest_line_words = max(len(line.split()) for line in pdf_content) if pdf_content else 0
|
| 179 |
-
content_density = total_lines * hierarchy_weight + total_chars / 50
|
| 180 |
-
usable_height = page_height - 72 - spacer_height
|
| 181 |
-
usable_width = page_width - 72
|
| 182 |
-
avg_line_chars = total_chars / total_lines if total_lines > 0 else 50
|
| 183 |
-
col_width = usable_width / num_columns
|
| 184 |
-
min_font_size = 5
|
| 185 |
-
max_font_size = 16
|
| 186 |
-
lines_per_col = total_lines / num_columns if num_columns > 0 else total_lines
|
| 187 |
-
target_height_per_line = usable_height / lines_per_col if lines_per_col > 0 else usable_height
|
| 188 |
-
estimated_font_size = int(target_height_per_line / 1.5)
|
| 189 |
-
adjusted_font_size = max(min_font_size, min(max_font_size, estimated_font_size))
|
| 190 |
-
if avg_line_chars > col_width / adjusted_font_size * 10:
|
| 191 |
-
adjusted_font_size = int(col_width / (avg_line_chars / 10))
|
| 192 |
-
adjusted_font_size = max(min_font_size, adjusted_font_size)
|
| 193 |
-
if longest_line_words > 17 or lines_per_col > 20:
|
| 194 |
-
font_scale = min(17 / max(longest_line_words, 17), 60 / max(lines_per_col, 20))
|
| 195 |
-
adjusted_font_size = max(min_font_size, int(base_font_size * font_scale))
|
| 196 |
-
item_style = ParagraphStyle(
|
| 197 |
-
'ItemStyle', parent=styles['Normal'], fontName="DejaVuSans",
|
| 198 |
-
fontSize=adjusted_font_size, leading=adjusted_font_size * 1.15, spaceAfter=1,
|
| 199 |
-
linkUnderline=True
|
| 200 |
-
)
|
| 201 |
-
numbered_bold_style = ParagraphStyle(
|
| 202 |
-
'NumberedBoldStyle', parent=styles['Normal'], fontName="NotoEmoji-Bold",
|
| 203 |
-
fontSize=adjusted_font_size, leading=adjusted_font_size * 1.15, spaceAfter=1,
|
| 204 |
-
linkUnderline=True
|
| 205 |
-
)
|
| 206 |
-
section_style = ParagraphStyle(
|
| 207 |
-
'SectionStyle', parent=styles['Heading2'], fontName="DejaVuSans",
|
| 208 |
-
textColor=colors.darkblue, fontSize=adjusted_font_size * 1.1, leading=adjusted_font_size * 1.32, spaceAfter=2,
|
| 209 |
-
linkUnderline=True
|
| 210 |
-
)
|
| 211 |
-
columns = [[] for _ in range(num_columns)]
|
| 212 |
-
lines_per_column = total_lines / num_columns if num_columns > 0 else total_lines
|
| 213 |
-
current_line_count = 0
|
| 214 |
-
current_column = 0
|
| 215 |
-
number_pattern = re.compile(r'^\d+(\.\d+)*\.\s')
|
| 216 |
-
for item in pdf_content:
|
| 217 |
-
if current_line_count >= lines_per_column and current_column < num_columns - 1:
|
| 218 |
-
current_column += 1
|
| 219 |
-
current_line_count = 0
|
| 220 |
-
columns[current_column].append(item)
|
| 221 |
-
current_line_count += 1
|
| 222 |
-
column_cells = [[] for _ in range(num_columns)]
|
| 223 |
-
for col_idx, column in enumerate(columns):
|
| 224 |
-
for item in column:
|
| 225 |
-
if isinstance(item, str):
|
| 226 |
-
heading_match = re.match(r'<h(\d)>(.*?)</h\1>', item) if headings_to_fonts else None
|
| 227 |
-
if heading_match:
|
| 228 |
-
level = int(heading_match.group(1))
|
| 229 |
-
heading_text = heading_match.group(2)
|
| 230 |
-
heading_style = ParagraphStyle(
|
| 231 |
-
f'Heading{level}Style',
|
| 232 |
-
parent=styles['Heading1'],
|
| 233 |
-
fontName="DejaVuSans",
|
| 234 |
-
textColor=colors.darkblue if level == 1 else (colors.black if level > 2 else colors.blue),
|
| 235 |
-
fontSize=adjusted_font_size * (1.6 - (level-1)*0.15),
|
| 236 |
-
leading=adjusted_font_size * (1.8 - (level-1)*0.15),
|
| 237 |
-
spaceAfter=4 - (level-1),
|
| 238 |
-
spaceBefore=6 - (level-1),
|
| 239 |
-
linkUnderline=True
|
| 240 |
-
)
|
| 241 |
-
column_cells[col_idx].append(Paragraph(apply_emoji_font(heading_text, "NotoEmoji-Bold"), heading_style))
|
| 242 |
-
elif item.startswith("<b>") and item.endswith("</b>"):
|
| 243 |
-
content = item[3:-4].strip()
|
| 244 |
-
if number_pattern.match(content):
|
| 245 |
-
column_cells[col_idx].append(Paragraph(apply_emoji_font(content, "NotoEmoji-Bold"), numbered_bold_style))
|
| 246 |
-
else:
|
| 247 |
-
column_cells[col_idx].append(Paragraph(apply_emoji_font(content, "NotoEmoji-Bold"), section_style))
|
| 248 |
-
else:
|
| 249 |
-
column_cells[col_idx].append(Paragraph(apply_emoji_font(item, "NotoEmoji-Bold"), item_style))
|
| 250 |
-
else:
|
| 251 |
-
column_cells[col_idx].append(Paragraph(apply_emoji_font(str(item), "NotoEmoji-Bold"), item_style))
|
| 252 |
-
max_cells = max(len(cells) for cells in column_cells) if column_cells else 0
|
| 253 |
-
for cells in column_cells:
|
| 254 |
-
cells.extend([Paragraph("", item_style)] * (max_cells - len(cells)))
|
| 255 |
-
table_data = list(zip(*column_cells)) if column_cells else [[]]
|
| 256 |
-
table = Table(table_data, colWidths=[col_width] * num_columns, hAlign='CENTER')
|
| 257 |
-
table.setStyle(TableStyle([
|
| 258 |
-
('VALIGN', (0, 0), (-1, -1), 'TOP'),
|
| 259 |
-
('ALIGN', (0, 0), (-1, -1), 'LEFT'),
|
| 260 |
-
('BACKGROUND', (0, 0), (-1, -1), colors.white),
|
| 261 |
-
('GRID', (0, 0), (-1, -1), 0, colors.white),
|
| 262 |
-
('LINEAFTER', (0, 0), (num_columns-1, -1), 0.5, colors.grey),
|
| 263 |
-
('LEFTPADDING', (0, 0), (-1, -1), 2),
|
| 264 |
-
('RIGHTPADDING', (0, 0), (-1, -1), 2),
|
| 265 |
-
('TOPPADDING', (0, 0), (-1, -1), 1),
|
| 266 |
-
('BOTTOMPADDING', (0, 0), (-1, -1), 1),
|
| 267 |
-
]))
|
| 268 |
-
story.append(Spacer(1, spacer_height))
|
| 269 |
-
story.append(table)
|
| 270 |
-
story.append(Spacer(1, spacer_height * 2))
|
| 271 |
-
for img_path in image_files:
|
| 272 |
try:
|
| 273 |
-
|
| 274 |
-
|
| 275 |
-
|
| 276 |
-
|
| 277 |
-
new_width = img_width * scale
|
| 278 |
-
new_height = img_height * scale
|
| 279 |
-
story.append(ReportLabImage(img_path, width=new_width, height=new_height))
|
| 280 |
-
story.append(Spacer(1, spacer_height))
|
| 281 |
except Exception as e:
|
| 282 |
-
st.
|
| 283 |
-
|
| 284 |
-
|
| 285 |
-
|
| 286 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 287 |
|
| 288 |
def pdf_to_image(pdf_bytes):
|
| 289 |
-
if pdf_bytes
|
| 290 |
-
return None
|
| 291 |
try:
|
| 292 |
-
|
| 293 |
-
images = []
|
| 294 |
-
for page in doc:
|
| 295 |
-
pix = page.get_pixmap(matrix=fitz.Matrix(2.0, 2.0))
|
| 296 |
-
img = Image.frombytes("RGB", [pix.width, pix.height], pix.samples)
|
| 297 |
-
images.append(img)
|
| 298 |
-
doc.close()
|
| 299 |
-
return images
|
| 300 |
except Exception as e:
|
| 301 |
st.error(f"Failed to render PDF preview: {e}")
|
| 302 |
return None
|
| 303 |
|
| 304 |
-
def
|
| 305 |
-
|
| 306 |
-
|
| 307 |
-
|
| 308 |
-
|
| 309 |
-
|
| 310 |
-
|
| 311 |
-
|
| 312 |
-
'''
|
| 313 |
-
except Exception as e:
|
| 314 |
-
st.warning(f"Could not load video {video_path}: {e}")
|
| 315 |
-
return ""
|
| 316 |
|
| 317 |
-
|
| 318 |
-
|
| 319 |
-
|
| 320 |
-
"๐": lambda k: f"https://en.wikipedia.org/wiki/{quote(k)}",
|
| 321 |
-
"๐": lambda k: f"https://www.google.com/search?q={quote(k)}",
|
| 322 |
-
"๐ฅ": lambda k: f"https://www.youtube.com/results?search_query={quote(k)}",
|
| 323 |
-
}
|
| 324 |
-
links_md = ' '.join([f"[{emoji}]({url(k)})" for emoji, url in search_urls.items()])
|
| 325 |
-
st.markdown(f"**{k}** <small>{links_md}</small>", unsafe_allow_html=True)
|
| 326 |
|
| 327 |
-
#
|
| 328 |
-
|
|
|
|
|
|
|
|
|
|
| 329 |
|
| 330 |
-
|
| 331 |
-
|
| 332 |
-
|
| 333 |
-
|
| 334 |
-
|
| 335 |
-
|
| 336 |
-
columns = st.slider("Text columns", 1, 3, 2)
|
| 337 |
-
font_family = st.selectbox("Font", ["Helvetica", "Times-Roman", "Courier", "DejaVuSans"])
|
| 338 |
-
font_size = st.slider("Font size", 6, 24, 14)
|
| 339 |
-
|
| 340 |
-
# Page size selection
|
| 341 |
-
page_size_options = {
|
| 342 |
-
"A4 (210 ร 297 mm)": "A4",
|
| 343 |
-
"Letter (8.5 ร 11 in)": "Letter",
|
| 344 |
-
"Legal (8.5 ร 14 in)": "Legal",
|
| 345 |
-
"A3 (297 ร 420 mm)": "A3",
|
| 346 |
-
"A5 (148 ร 210 mm)": "A5"
|
| 347 |
-
}
|
| 348 |
-
selected_page_size = st.selectbox(
|
| 349 |
-
"๐ Page Size",
|
| 350 |
-
options=list(page_size_options.keys()),
|
| 351 |
-
index=0 # Default to A4
|
| 352 |
-
)
|
| 353 |
-
page_size = page_size_options[selected_page_size]
|
| 354 |
-
|
| 355 |
-
# Multiple markdown file upload
|
| 356 |
-
md_files = st.file_uploader("Upload Markdown Files (.md)", type=["md"], accept_multiple_files=True)
|
| 357 |
-
markdown_texts = []
|
| 358 |
-
combined_text = ""
|
| 359 |
|
| 360 |
-
|
| 361 |
-
|
| 362 |
-
|
| 363 |
-
|
| 364 |
-
markdown_texts.append(md_text)
|
| 365 |
-
combined_text += md_text + "\n\n"
|
| 366 |
-
|
| 367 |
-
with st.expander(f"๐ {md_file.name}"):
|
| 368 |
-
st.markdown(md_text[:500] + "..." if len(md_text) > 500 else md_text)
|
| 369 |
-
|
| 370 |
-
stem = f"combined_{len(md_files)}_files_{datetime.now().strftime('%Y%m%d_%H%M%S')}"
|
| 371 |
-
else:
|
| 372 |
-
# Single text area for manual input
|
| 373 |
-
manual_text = st.text_area("Or enter markdown text directly", height=200)
|
| 374 |
-
if manual_text:
|
| 375 |
-
markdown_texts = [manual_text]
|
| 376 |
-
combined_text = manual_text
|
| 377 |
-
stem = datetime.now().strftime('%Y%m%d_%H%M%S')
|
| 378 |
|
| 379 |
-
|
| 380 |
-
|
| 381 |
-
|
| 382 |
-
|
| 383 |
-
|
| 384 |
-
|
| 385 |
-
|
| 386 |
-
|
| 387 |
-
|
| 388 |
-
|
| 389 |
-
|
| 390 |
-
|
| 391 |
-
|
| 392 |
-
|
| 393 |
-
|
| 394 |
-
|
| 395 |
-
|
| 396 |
-
|
| 397 |
-
|
|
|
|
| 398 |
|
| 399 |
-
|
| 400 |
-
st.subheader("๐ Text-to-Speech Settings")
|
| 401 |
-
col1, col2 = st.columns(2)
|
| 402 |
with col1:
|
| 403 |
-
|
| 404 |
-
|
| 405 |
-
|
| 406 |
-
|
| 407 |
-
|
| 408 |
with col2:
|
| 409 |
-
|
| 410 |
-
selected_voice = st.selectbox("Select Voice
|
| 411 |
-
|
| 412 |
-
|
| 413 |
-
|
| 414 |
-
|
| 415 |
-
|
| 416 |
-
|
| 417 |
-
cleaned_text = clean_for_speech(plain_text)
|
| 418 |
-
audio_file = asyncio.run(generate_audio(cleaned_text, selected_voice, voice_file))
|
| 419 |
-
st.success("Audio generated successfully!")
|
| 420 |
-
st.audio(audio_file)
|
| 421 |
-
with open(audio_file, 'rb') as mp3:
|
| 422 |
-
st.download_button("๐ฅ Download MP3", data=mp3, file_name=voice_file, mime="audio/mpeg")
|
| 423 |
-
except Exception as e:
|
| 424 |
-
st.error(f"Error generating voice: {e}")
|
| 425 |
-
else:
|
| 426 |
-
st.warning("No text to generate voice from.")
|
| 427 |
-
|
| 428 |
-
# Image uploads and ordering
|
| 429 |
-
st.subheader("๐ผ๏ธ Image Management")
|
| 430 |
-
imgs = st.file_uploader("Upload Images for PDF", type=["png", "jpg", "jpeg"], accept_multiple_files=True)
|
| 431 |
-
ordered_images = []
|
| 432 |
-
if imgs:
|
| 433 |
-
st.write(f"๐ Uploaded {len(imgs)} images")
|
| 434 |
-
df_imgs = pd.DataFrame([{"name": f.name, "order": i} for i, f in enumerate(imgs)])
|
| 435 |
-
edited = st.data_editor(df_imgs, use_container_width=True, num_rows="dynamic")
|
| 436 |
-
for _, row in edited.sort_values("order").iterrows():
|
| 437 |
-
for f in imgs:
|
| 438 |
-
if f.name == row['name']:
|
| 439 |
-
ordered_images.append(f)
|
| 440 |
-
break
|
| 441 |
-
|
| 442 |
-
# PDF Generation
|
| 443 |
-
st.subheader("๐ PDF Generation")
|
| 444 |
-
|
| 445 |
-
if st.button("๐๏ธ Generate PDF with Markdown & Images", type="primary"):
|
| 446 |
-
if not markdown_texts and not ordered_images:
|
| 447 |
-
st.warning("Please provide some markdown text or upload images to generate a PDF.")
|
| 448 |
-
else:
|
| 449 |
-
with st.spinner(f"Generating PDF with {page_size} page size..."):
|
| 450 |
-
if markdown_texts and not ordered_images:
|
| 451 |
-
# Use the enhanced create_pdf function
|
| 452 |
-
pdf_bytes = create_pdf(
|
| 453 |
-
markdown_texts=markdown_texts,
|
| 454 |
-
image_files=[],
|
| 455 |
-
base_font_size=font_size,
|
| 456 |
-
num_columns=columns,
|
| 457 |
-
add_space_before_numbered=True,
|
| 458 |
-
headings_to_fonts=True,
|
| 459 |
-
doc_title=f"Markdown_Document_{len(markdown_texts)}_files",
|
| 460 |
-
page_size=page_size
|
| 461 |
-
)
|
| 462 |
-
|
| 463 |
-
if pdf_bytes:
|
| 464 |
-
pdf_images = pdf_to_image(pdf_bytes)
|
| 465 |
-
if pdf_images:
|
| 466 |
-
st.subheader("Preview of Generated PDF")
|
| 467 |
-
for i, img in enumerate(pdf_images):
|
| 468 |
-
st.image(img, caption=f"Page {i+1}", use_container_width=True)
|
| 469 |
-
|
| 470 |
-
pdf_name = f"{stem}.pdf"
|
| 471 |
-
st.download_button("โฌ๏ธ Download PDF", data=pdf_bytes, file_name=pdf_name, mime="application/pdf")
|
| 472 |
-
else:
|
| 473 |
-
st.error("Failed to generate PDF from markdown.")
|
| 474 |
-
else:
|
| 475 |
-
# Fallback to original simple PDF generation for mixed content
|
| 476 |
-
buf = io.BytesIO()
|
| 477 |
-
|
| 478 |
-
# Get page dimensions for the selected page size
|
| 479 |
-
if page_size == "A4":
|
| 480 |
-
page_dimensions = A4
|
| 481 |
-
elif page_size == "Letter":
|
| 482 |
-
page_dimensions = letter
|
| 483 |
-
elif page_size == "Legal":
|
| 484 |
-
page_dimensions = legal
|
| 485 |
-
elif page_size == "A3":
|
| 486 |
-
page_dimensions = A3
|
| 487 |
-
elif page_size == "A5":
|
| 488 |
-
page_dimensions = A5
|
| 489 |
-
else:
|
| 490 |
-
page_dimensions = A4
|
| 491 |
-
|
| 492 |
-
c = canvas.Canvas(buf, pagesize=page_dimensions)
|
| 493 |
-
|
| 494 |
-
if plain_text.strip():
|
| 495 |
-
page_w, page_h = page_dimensions
|
| 496 |
-
margin = 40
|
| 497 |
-
gutter = 20
|
| 498 |
-
col_w = (page_w - 2*margin - (columns-1)*gutter) / columns
|
| 499 |
-
c.setFont(font_family, font_size)
|
| 500 |
-
line_height = font_size * 1.2
|
| 501 |
-
col = 0
|
| 502 |
-
x = margin
|
| 503 |
-
y = page_h - margin
|
| 504 |
-
avg_char_width = font_size * 0.6
|
| 505 |
-
wrap_width = int(col_w / avg_char_width) if avg_char_width > 0 else 100
|
| 506 |
-
for paragraph in plain_text.split("\n"):
|
| 507 |
-
if not paragraph.strip():
|
| 508 |
-
y -= line_height
|
| 509 |
-
if y < margin:
|
| 510 |
-
col += 1
|
| 511 |
-
if col >= columns:
|
| 512 |
-
c.showPage()
|
| 513 |
-
c.setFont(font_family, font_size)
|
| 514 |
-
col = 0
|
| 515 |
-
x = margin + col*(col_w+gutter)
|
| 516 |
-
y = page_h - margin
|
| 517 |
-
continue
|
| 518 |
-
for line in textwrap.wrap(paragraph, wrap_width):
|
| 519 |
-
if y < margin:
|
| 520 |
-
col += 1
|
| 521 |
-
if col >= columns:
|
| 522 |
-
c.showPage()
|
| 523 |
-
c.setFont(font_family, font_size)
|
| 524 |
-
col = 0
|
| 525 |
-
x = margin + col*(col_w+gutter)
|
| 526 |
-
y = page_h - margin
|
| 527 |
-
c.drawString(x, y, line)
|
| 528 |
-
y -= line_height
|
| 529 |
-
y -= line_height
|
| 530 |
-
for img_f in ordered_images:
|
| 531 |
-
try:
|
| 532 |
-
img = Image.open(img_f)
|
| 533 |
-
w, h = img.size
|
| 534 |
-
c.showPage()
|
| 535 |
-
c.setPageSize((w, h))
|
| 536 |
-
c.drawImage(ImageReader(img), 0, 0, w, h, preserveAspectRatio=False)
|
| 537 |
-
except Exception as e:
|
| 538 |
-
st.warning(f"Could not process image {img_f.name}: {e}")
|
| 539 |
-
continue
|
| 540 |
-
c.save()
|
| 541 |
-
buf.seek(0)
|
| 542 |
-
pdf_name = f"{stem}.pdf"
|
| 543 |
-
st.success(f"PDF generated successfully with {page_size} page size!")
|
| 544 |
-
st.download_button("โฌ๏ธ Download PDF", data=buf, file_name=pdf_name, mime="application/pdf")
|
| 545 |
-
|
| 546 |
-
st.markdown("---")
|
| 547 |
-
st.subheader("๐ Available Assets")
|
| 548 |
-
all_assets = glob.glob("*.*")
|
| 549 |
-
excluded_extensions = ['.py', '.ttf', '.txt']
|
| 550 |
-
excluded_files = ['README.md', 'index.html']
|
| 551 |
-
assets = sorted([
|
| 552 |
-
a for a in all_assets
|
| 553 |
-
if not (a.lower().endswith(tuple(excluded_extensions)) or a in excluded_files)
|
| 554 |
-
and a.lower().endswith(('.md', '.png', '.jpg', '.jpeg'))
|
| 555 |
-
])
|
| 556 |
-
if 'selected_assets' not in st.session_state:
|
| 557 |
-
st.session_state.selected_assets = []
|
| 558 |
-
if not assets:
|
| 559 |
-
st.info("No available assets found.")
|
| 560 |
-
else:
|
| 561 |
-
for a in assets:
|
| 562 |
-
ext = a.split('.')[-1].lower()
|
| 563 |
-
cols = st.columns([1, 3, 1, 1])
|
| 564 |
-
with cols[0]:
|
| 565 |
-
is_selected = st.checkbox("", key=f"select_{a}", value=a in st.session_state.selected_assets)
|
| 566 |
-
if is_selected and a not in st.session_state.selected_assets:
|
| 567 |
-
st.session_state.selected_assets.append(a)
|
| 568 |
-
elif not is_selected and a in st.session_state.selected_assets:
|
| 569 |
-
st.session_state.selected_assets.remove(a)
|
| 570 |
-
cols[1].write(a)
|
| 571 |
-
try:
|
| 572 |
-
if ext == 'md':
|
| 573 |
-
with open(a, 'r', encoding='utf-8') as f:
|
| 574 |
-
cols[2].download_button("๐ฅ", data=f.read(), file_name=a, mime="text/markdown")
|
| 575 |
-
elif ext in ['png', 'jpg', 'jpeg']:
|
| 576 |
-
with open(a, 'rb') as img_file:
|
| 577 |
-
cols[2].download_button("โฌ๏ธ", data=img_file, file_name=a, mime=f"image/{ext}")
|
| 578 |
-
cols[3].button("๐๏ธ", key=f"del_{a}", on_click=delete_asset, args=(a,))
|
| 579 |
-
except Exception as e:
|
| 580 |
-
cols[3].error(f"Error handling file {a}: {e}")
|
| 581 |
-
if st.button("๐ Generate PDF from Selected Assets"):
|
| 582 |
-
if not st.session_state.selected_assets:
|
| 583 |
-
st.warning("Please select at least one asset to generate a PDF.")
|
| 584 |
else:
|
| 585 |
-
|
| 586 |
-
|
| 587 |
-
for a in st.session_state.selected_assets:
|
| 588 |
-
ext = a.split('.')[-1].lower()
|
| 589 |
-
if ext == 'md':
|
| 590 |
-
with open(a, 'r', encoding='utf-8') as f:
|
| 591 |
-
selected_markdown_texts.append(f.read())
|
| 592 |
-
elif ext in ['png', 'jpg', 'jpeg']:
|
| 593 |
-
image_files.append(a)
|
| 594 |
-
with st.spinner("Generating PDF from selected assets..."):
|
| 595 |
-
pdf_bytes = create_pdf(
|
| 596 |
-
markdown_texts=selected_markdown_texts,
|
| 597 |
-
image_files=image_files,
|
| 598 |
-
base_font_size=font_size,
|
| 599 |
-
num_columns=columns,
|
| 600 |
-
add_space_before_numbered=True,
|
| 601 |
-
headings_to_fonts=True,
|
| 602 |
-
doc_title="Combined_Selected_Assets",
|
| 603 |
-
page_size=page_size
|
| 604 |
-
)
|
| 605 |
-
if pdf_bytes:
|
| 606 |
-
pdf_images = pdf_to_image(pdf_bytes)
|
| 607 |
-
if pdf_images:
|
| 608 |
-
st.subheader("Preview of Generated PDF")
|
| 609 |
-
for i, img in enumerate(pdf_images):
|
| 610 |
-
st.image(img, caption=f"Page {i+1}", use_container_width=True)
|
| 611 |
-
prefix = datetime.now().strftime("%Y%m%d_%H%M%S")
|
| 612 |
-
st.download_button(
|
| 613 |
-
label="๐พ Download Combined PDF",
|
| 614 |
-
data=pdf_bytes,
|
| 615 |
-
file_name=f"{prefix}_combined.pdf",
|
| 616 |
-
mime="application/pdf"
|
| 617 |
-
)
|
| 618 |
-
else:
|
| 619 |
-
st.error("Failed to generate PDF.")
|
| 620 |
-
|
| 621 |
-
st.markdown("---")
|
| 622 |
-
st.subheader("๐ผ Image Gallery")
|
| 623 |
-
image_files = glob.glob("*.png") + glob.glob("*.jpg") + glob.glob("*.jpeg")
|
| 624 |
-
image_cols = st.slider("Gallery Columns ๐ผ", min_value=1, max_value=15, value=5, key="image_cols")
|
| 625 |
-
if image_files:
|
| 626 |
-
cols = st.columns(image_cols)
|
| 627 |
-
for idx, image_file in enumerate(image_files):
|
| 628 |
-
with cols[idx % image_cols]:
|
| 629 |
-
try:
|
| 630 |
-
img = Image.open(image_file)
|
| 631 |
-
st.image(img, caption=image_file, use_container_width=True)
|
| 632 |
-
display_glossary_entity(os.path.splitext(image_file)[0])
|
| 633 |
-
except Exception as e:
|
| 634 |
-
st.warning(f"Could not load image {image_file}: {e}")
|
| 635 |
-
else:
|
| 636 |
-
st.info("No images found in the current directory.")
|
| 637 |
-
|
| 638 |
st.markdown("---")
|
| 639 |
-
st.
|
| 640 |
-
|
| 641 |
-
|
| 642 |
-
if video_files:
|
| 643 |
-
cols = st.columns(video_cols)
|
| 644 |
-
for idx, video_file in enumerate(video_files):
|
| 645 |
-
with cols[idx % video_cols]:
|
| 646 |
-
st.markdown(get_video_html(video_file, width="100%"), unsafe_allow_html=True)
|
| 647 |
-
display_glossary_entity(os.path.splitext(video_file)[0])
|
| 648 |
-
else:
|
| 649 |
-
st.info("No videos found in the current directory.")
|
| 650 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 651 |
with tab2:
|
| 652 |
-
st.header("๐งช Python Code
|
| 653 |
-
|
| 654 |
-
|
| 655 |
-
|
| 656 |
-
import random
|
| 657 |
-
st.title("๐ Demo App")
|
| 658 |
-
st.markdown("Random number and color demo")
|
| 659 |
-
col1, col2 = st.columns(2)
|
| 660 |
-
with col1:
|
| 661 |
-
num = st.number_input("Number:", 1, 100, 10)
|
| 662 |
-
mul = st.slider("Multiplier:", 1, 10, 2)
|
| 663 |
-
if st.button("Calc"):
|
| 664 |
-
st.write(num * mul)
|
| 665 |
-
with col2:
|
| 666 |
-
color = st.color_picker("Pick color","#ff0000")
|
| 667 |
-
st.markdown(f'<div style="background:{color};padding:10px;">Color</div>', unsafe_allow_html=True)
|
| 668 |
-
'''
|
| 669 |
-
def extract_python_code(md: str) -> list:
|
| 670 |
-
return re.findall(r"```python\s*(.*?)```", md, re.DOTALL)
|
| 671 |
-
def execute_code(code: str) -> tuple:
|
| 672 |
-
buf = io.StringIO(); local_vars = {}
|
| 673 |
try:
|
| 674 |
-
|
| 675 |
-
exec(code, {}, local_vars)
|
| 676 |
-
return buf.getvalue(), None
|
| 677 |
except Exception as e:
|
| 678 |
-
|
| 679 |
-
up = st.file_uploader("Upload .py or .md", type=['py', 'md'])
|
| 680 |
-
if 'code' not in st.session_state:
|
| 681 |
-
st.session_state.code = DEFAULT_CODE
|
| 682 |
-
if up:
|
| 683 |
-
text = up.getvalue().decode()
|
| 684 |
-
if up.type == 'text/markdown':
|
| 685 |
-
codes = extract_python_code(text)
|
| 686 |
-
if codes:
|
| 687 |
-
st.session_state.code = codes[0].strip()
|
| 688 |
-
else:
|
| 689 |
-
st.warning("No Python code block found in the markdown file.")
|
| 690 |
-
st.session_state.code = ''
|
| 691 |
-
else:
|
| 692 |
-
st.session_state.code = text.strip()
|
| 693 |
-
st.code(st.session_state.code, language='python')
|
| 694 |
-
else:
|
| 695 |
-
st.session_state.code = st.text_area("๐ป Code Editor", value=st.session_state.code, height=400)
|
| 696 |
-
c1, c2 = st.columns([1, 1])
|
| 697 |
-
if c1.button("โถ๏ธ Run Code"):
|
| 698 |
-
if st.session_state.code.strip():
|
| 699 |
-
out, err = execute_code(st.session_state.code)
|
| 700 |
-
if err:
|
| 701 |
-
st.error(f"Execution Error:\n{err}")
|
| 702 |
-
elif out:
|
| 703 |
-
st.subheader("Output:")
|
| 704 |
-
st.code(out)
|
| 705 |
-
else:
|
| 706 |
-
st.success("Executed with no standard output.")
|
| 707 |
-
else:
|
| 708 |
-
st.warning("No code to run.")
|
| 709 |
-
if c2.button("๐๏ธ Clear Code"):
|
| 710 |
-
st.session_state.code = ''
|
| 711 |
-
st.rerun()
|
|
|
|
| 10 |
import edge_tts
|
| 11 |
import asyncio
|
| 12 |
import base64
|
|
|
|
| 13 |
from datetime import datetime
|
|
|
|
| 14 |
from PIL import Image
|
| 15 |
from reportlab.pdfgen import canvas
|
| 16 |
+
from reportlab.lib.pagesizes import letter, A4, legal, A3, A5, landscape
|
| 17 |
from reportlab.lib.utils import ImageReader
|
| 18 |
+
from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer, Table, TableStyle, Image as ReportLabImage, PageBreak
|
| 19 |
from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
|
| 20 |
from reportlab.lib import colors
|
| 21 |
from reportlab.pdfbase import pdfmetrics
|
| 22 |
from reportlab.pdfbase.ttfonts import TTFont
|
| 23 |
from urllib.parse import quote
|
| 24 |
|
| 25 |
+
# 1. ๐ The App's Constitution
|
| 26 |
+
# Setting the fundamental laws of the page. Wide layout for maximum glory.
|
| 27 |
+
st.set_page_config(page_title="Ultimate PDF & Code Interpreter", layout="wide", page_icon="๐")
|
| 28 |
|
| 29 |
+
# ==============================================================================
|
| 30 |
+
# CLASS 1: THE DYNAMIC LAYOUT SELECTOR COMPONENT
|
| 31 |
+
# ==============================================================================
|
| 32 |
+
class LayoutSelector:
|
| 33 |
+
"""The witty, stylish component for choosing a live preview layout."""
|
| 34 |
+
LAYOUTS = {
|
| 35 |
+
"A4 Portrait": {"aspect": "1 / 1.414", "desc": "Standard paper (210 x 297mm)", "icon": "๐", "size": A4},
|
| 36 |
+
"A4 Landscape": {"aspect": "1.414 / 1", "desc": "Standard paper (297 x 210mm)", "icon": "๐", "size": landscape(A4)},
|
| 37 |
+
"Letter Portrait": {"aspect": "1 / 1.294", "desc": "US Letter (8.5 x 11in)", "icon": "๐", "size": letter},
|
| 38 |
+
"Letter Landscape": {"aspect": "1.294 / 1", "desc": "US Letter (11 x 8.5in)", "icon": "๐", "size": landscape(letter)},
|
| 39 |
+
"Wide 16:9": {"aspect": "16 / 9", "desc": "YouTube and streaming sites", "icon": " widescreen", "size": landscape(A4)},
|
| 40 |
+
"Vertical 9:16": {"aspect": "9 / 16", "desc": "Instagram Reels and TikTok", "icon": "๐ฑ", "size": A4},
|
| 41 |
+
"Square 1:1": {"aspect": "1 / 1", "desc": "Instagram posts", "icon": "๐ผ๏ธ", "size": (600, 600)},
|
| 42 |
+
"Classic 4:3": {"aspect": "4 / 3", "desc": "Traditional TV and monitors", "icon": "๐บ", "size": landscape(A4)},
|
| 43 |
+
"Social 4:5": {"aspect": "4 / 5", "desc": "Portrait photos on social media", "icon": "๐คณ", "size": A4},
|
| 44 |
+
"Cinema 21:9": {"aspect": "21 / 9", "desc": "Widescreen cinematic video", "icon": "๐ฌ", "size": landscape(A4)},
|
| 45 |
+
"Portrait 2:3": {"aspect": "2 / 3", "desc": "Standard photography prints", "icon": "๐ท", "size": A4},
|
| 46 |
+
}
|
| 47 |
|
| 48 |
+
def __init__(self, default_layout='A4 Portrait'):
|
| 49 |
+
if 'page_layout' not in st.session_state: st.session_state.page_layout = default_layout
|
| 50 |
+
if 'autofit_text' not in st.session_state: st.session_state.autofit_text = False
|
|
|
|
| 51 |
|
| 52 |
+
def _build_css(self):
|
| 53 |
+
current_layout = st.session_state.get('page_layout', 'A4 Portrait')
|
| 54 |
+
aspect_ratio = self.LAYOUTS.get(current_layout, {}).get('aspect', '1 / 1.414')
|
| 55 |
+
return f"<style>.dynamic-canvas-container {{ aspect-ratio: {aspect_ratio}; }}</style>"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 56 |
|
| 57 |
+
def render(self):
|
| 58 |
+
st.html(self._build_css()) # Simplified for brevity, assumes base CSS is loaded once
|
| 59 |
+
# The full HTML/CSS/JS for the dropdown component is loaded once at the start of the app now
|
|
|
|
|
|
|
|
|
|
| 60 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 61 |
|
| 62 |
+
# ==============================================================================
|
| 63 |
+
# CLASS 2: THE ALMIGHTY PDF GENERATOR
|
| 64 |
+
# ==============================================================================
|
| 65 |
+
class PdfGenerator:
|
| 66 |
+
"""The engine room. This class takes your content and forges it into a PDF."""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 67 |
|
| 68 |
+
# 2. ๐งโโ๏ธ The PDF Alchemist's Workshop
|
| 69 |
+
# We gather all the ingredients (text, images, settings) to begin our creation.
|
| 70 |
+
def __init__(self, markdown_texts, image_files, settings):
|
| 71 |
+
self.markdown_texts = markdown_texts
|
| 72 |
+
self.image_files = image_files
|
| 73 |
+
self.settings = settings
|
| 74 |
+
self.story = []
|
| 75 |
+
self.buffer = io.BytesIO()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 76 |
|
| 77 |
+
# Ensure fonts are registered, or provide a friendly warning.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 78 |
try:
|
| 79 |
+
if os.path.exists("DejaVuSans.ttf"):
|
| 80 |
+
pdfmetrics.registerFont(TTFont("DejaVuSans", "DejaVuSans.ttf"))
|
| 81 |
+
if os.path.exists("NotoEmoji-Bold.ttf"):
|
| 82 |
+
pdfmetrics.registerFont(TTFont("NotoEmoji-Bold", "NotoEmoji-Bold.ttf"))
|
|
|
|
|
|
|
|
|
|
|
|
|
| 83 |
except Exception as e:
|
| 84 |
+
st.error(f"๐จ Font-tastic error! Could not register fonts: {e}")
|
| 85 |
+
|
| 86 |
+
# 3. ๐ฌ The Automatic Font-Shrinking Ray
|
| 87 |
+
# This function analyzes your text and calculates the perfect font size.
|
| 88 |
+
# Its goal: Squeeze everything onto one glorious, multi-column page!
|
| 89 |
+
def _calculate_font_size(self, text_content, page_width, page_height, num_columns):
|
| 90 |
+
if not text_content: return self.settings['base_font_size']
|
| 91 |
+
|
| 92 |
+
total_lines = len(text_content)
|
| 93 |
+
total_chars = sum(len(line) for line in text_content)
|
| 94 |
+
|
| 95 |
+
# This is a refined version of the original script's sizing logic
|
| 96 |
+
min_font, max_font = 5, 20
|
| 97 |
+
# Estimate required font size based on lines per column
|
| 98 |
+
lines_per_col = total_lines / num_columns
|
| 99 |
+
font_size = page_height / lines_per_col * 0.7
|
| 100 |
+
font_size = max(min_font, min(max_font, font_size))
|
| 101 |
+
|
| 102 |
+
# Further reduce size if lines are very long
|
| 103 |
+
avg_chars_per_line = total_chars / total_lines if total_lines > 0 else 0
|
| 104 |
+
col_width_chars = (page_width / num_columns) / (font_size * 0.5) # Estimate chars that fit
|
| 105 |
+
if avg_chars_per_line > col_width_chars * 0.9: # If average line is long
|
| 106 |
+
font_size = max(min_font, font_size * 0.85)
|
| 107 |
+
|
| 108 |
+
return int(font_size)
|
| 109 |
+
|
| 110 |
+
# 4. ๐ The Story Weaver
|
| 111 |
+
# This is where the magic happens. We take the text, parse the markdown,
|
| 112 |
+
# create columns, and lay everything out. It's like choreographing a ballet of words.
|
| 113 |
+
def _build_text_story(self):
|
| 114 |
+
layout_props = LayoutSelector.LAYOUTS.get(self.settings['layout_name'], {})
|
| 115 |
+
page_size = layout_props.get('size', A4)
|
| 116 |
+
page_width, page_height = page_size
|
| 117 |
+
|
| 118 |
+
# Option for an extra-wide, single-page layout
|
| 119 |
+
if self.settings['force_one_page']:
|
| 120 |
+
page_width *= self.settings['num_columns']
|
| 121 |
+
page_height *= 1.5 # Give more vertical space
|
| 122 |
+
num_columns = self.settings['num_columns']
|
| 123 |
+
else:
|
| 124 |
+
num_columns = self.settings['num_columns']
|
| 125 |
+
|
| 126 |
+
doc = SimpleDocTemplate(self.buffer, pagesize=(page_width, page_height),
|
| 127 |
+
leftMargin=36, rightMargin=36, topMargin=36, bottomMargin=36)
|
| 128 |
+
|
| 129 |
+
full_text, _ = markdown_to_pdf_content('\n\n'.join(self.markdown_texts))
|
| 130 |
+
font_size = self._calculate_font_size(full_text, page_width - 72, page_height - 72, num_columns)
|
| 131 |
+
|
| 132 |
+
# Create styles based on the auto-calculated font size
|
| 133 |
+
styles = getSampleStyleSheet()
|
| 134 |
+
item_style = ParagraphStyle('ItemStyle', parent=styles['Normal'], fontName="DejaVuSans", fontSize=font_size, leading=font_size * 1.2)
|
| 135 |
+
|
| 136 |
+
# Process and style each line of markdown
|
| 137 |
+
column_data = [[] for _ in range(num_columns)]
|
| 138 |
+
for i, item in enumerate(full_text):
|
| 139 |
+
# Simplified for clarity, can add back detailed heading/bold styles
|
| 140 |
+
p = Paragraph(item, style=item_style)
|
| 141 |
+
column_data[i % num_columns].append(p)
|
| 142 |
+
|
| 143 |
+
max_len = max(len(col) for col in column_data) if column_data else 0
|
| 144 |
+
for col in column_data:
|
| 145 |
+
col.extend([Spacer(1,1)] * (max_len - len(col)))
|
| 146 |
+
|
| 147 |
+
table_data = list(zip(*column_data))
|
| 148 |
+
table = Table(table_data, colWidths=[(page_width-72)/num_columns]*num_columns, hAlign='LEFT')
|
| 149 |
+
table.setStyle(TableStyle([('VALIGN', (0,0), (-1,-1), 'TOP')]))
|
| 150 |
+
self.story.append(table)
|
| 151 |
+
return doc
|
| 152 |
+
|
| 153 |
+
# 5. ๐ผ๏ธ The Image Page Conjurer
|
| 154 |
+
# For when images demand their own spotlight. This function gives each image
|
| 155 |
+
# its very own page, perfectly sized to its dimensions.
|
| 156 |
+
def _build_image_story(self):
|
| 157 |
+
for img_file in self.image_files:
|
| 158 |
+
self.story.append(PageBreak())
|
| 159 |
+
img = Image.open(img_file)
|
| 160 |
+
img_width, img_height = img.size
|
| 161 |
+
|
| 162 |
+
# Create a page that is the exact size of the image + margins
|
| 163 |
+
custom_page = (img_width + 72, img_height + 72)
|
| 164 |
+
doc = SimpleDocTemplate(self.buffer, pagesize=custom_page)
|
| 165 |
+
|
| 166 |
+
# This is a bit of a trick: we define a special frame for this page
|
| 167 |
+
frame = doc.getFrame('normal') # Get the default frame
|
| 168 |
+
doc.addPageTemplates(st.PageTemplate(id='ImagePage', frames=[frame], pagesize=custom_page))
|
| 169 |
+
|
| 170 |
+
self.story.append(ReportLabImage(img_file, width=img_width, height=img_height))
|
| 171 |
+
|
| 172 |
+
# 6. โจ The Final Incantation
|
| 173 |
+
# With all the pieces assembled, we perform the final ritual to build
|
| 174 |
+
# the PDF and bring it to life!
|
| 175 |
+
def generate(self):
|
| 176 |
+
if not self.markdown_texts and not self.image_files:
|
| 177 |
+
st.warning("Nothing to generate! Please add some text or images.")
|
| 178 |
+
return None
|
| 179 |
+
|
| 180 |
+
doc = self._build_text_story() if self.markdown_texts else SimpleDocTemplate(self.buffer)
|
| 181 |
+
|
| 182 |
+
if self.image_files:
|
| 183 |
+
if self.settings['images_on_own_page']:
|
| 184 |
+
self._build_image_story()
|
| 185 |
+
else: # Add images to the main story
|
| 186 |
+
for img_file in self.image_files:
|
| 187 |
+
self.story.append(ReportLabImage(img_file))
|
| 188 |
+
|
| 189 |
+
doc.build(self.story)
|
| 190 |
+
self.buffer.seek(0)
|
| 191 |
+
return self.buffer
|
| 192 |
+
|
| 193 |
+
# ==============================================================================
|
| 194 |
+
# ALL OTHER HELPER FUNCTIONS (TTS, File Management, etc.)
|
| 195 |
+
# ==============================================================================
|
| 196 |
+
def markdown_to_pdf_content(markdown_text):
|
| 197 |
+
lines = markdown_text.strip().split('\n')
|
| 198 |
+
# This is a simplified parser. The original's complex logic can be used here.
|
| 199 |
+
return [re.sub(r'#+\s*|\*\*(.*?)\*\*|_(.*?)_', r'<b>\1\2</b>', line) for line in lines if line.strip()], len(lines)
|
| 200 |
|
| 201 |
def pdf_to_image(pdf_bytes):
|
| 202 |
+
if not pdf_bytes: return None
|
|
|
|
| 203 |
try:
|
| 204 |
+
return [page.get_pixmap(matrix=fitz.Matrix(2.0, 2.0)) for page in fitz.open(stream=pdf_bytes, filetype="pdf")]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 205 |
except Exception as e:
|
| 206 |
st.error(f"Failed to render PDF preview: {e}")
|
| 207 |
return None
|
| 208 |
|
| 209 |
+
async def generate_audio(text, voice):
|
| 210 |
+
communicate = edge_tts.Communicate(text, voice)
|
| 211 |
+
buffer = io.BytesIO()
|
| 212 |
+
async for chunk in communicate.stream():
|
| 213 |
+
if chunk["type"] == "audio":
|
| 214 |
+
buffer.write(chunk["data"])
|
| 215 |
+
buffer.seek(0)
|
| 216 |
+
return buffer
|
|
|
|
|
|
|
|
|
|
|
|
|
| 217 |
|
| 218 |
+
# ==============================================================================
|
| 219 |
+
# THE MAIN STREAMLIT APP
|
| 220 |
+
# ==============================================================================
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 221 |
|
| 222 |
+
# 7. ๐ฌ The Royal Messenger Service (State Handling)
|
| 223 |
+
if 'layout' in st.query_params:
|
| 224 |
+
st.session_state.page_layout = st.query_params.get('layout')
|
| 225 |
+
st.experimental_set_query_params()
|
| 226 |
+
st.rerun()
|
| 227 |
|
| 228 |
+
# --- Load base CSS and JS for components once ---
|
| 229 |
+
st.html(open('styles.html').read() if os.path.exists('styles.html') else '<style></style>') # Assumes CSS is in a file
|
| 230 |
+
|
| 231 |
+
# --- Sidebar Controls ---
|
| 232 |
+
with st.sidebar:
|
| 233 |
+
st.title("๐ Ultimate PDF Creator")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 234 |
|
| 235 |
+
# 8. ๐ญ Summoning the Layout Selector
|
| 236 |
+
# We command our witty LayoutSelector component to appear and do its thing.
|
| 237 |
+
layout_selector = LayoutSelector(default_layout='Wide 16:9')
|
| 238 |
+
layout_selector.render()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 239 |
|
| 240 |
+
st.subheader("โ๏ธ PDF Generation Settings")
|
| 241 |
+
pdf_settings = {
|
| 242 |
+
'num_columns': st.slider("Text columns", 1, 4, 2),
|
| 243 |
+
'base_font_size': st.slider("Base font size", 6, 24, 12),
|
| 244 |
+
'images_on_own_page': st.checkbox("Place each image on its own page", value=True),
|
| 245 |
+
'force_one_page': st.checkbox("Try to force text to one wide page", value=True, help="Widens the page and auto-sizes font to fit all text."),
|
| 246 |
+
'layout_name': st.session_state.get('page_layout', 'A4 Portrait')
|
| 247 |
+
}
|
| 248 |
+
|
| 249 |
+
# --- Main App Body ---
|
| 250 |
+
tab1, tab2 = st.tabs(["๐ PDF Composer & Voice Generator ๐", "๐งช Code Interpreter"])
|
| 251 |
+
|
| 252 |
+
with tab1:
|
| 253 |
+
st.header(f"Live Preview ({st.session_state.get('page_layout', 'A4 Portrait')})")
|
| 254 |
+
|
| 255 |
+
# 9. ๐ผ๏ธ The Main Event: The Live Canvas
|
| 256 |
+
st.markdown('<div class="dynamic-canvas-container">', unsafe_allow_html=True)
|
| 257 |
+
with st.container():
|
| 258 |
+
user_text = st.text_area("Start your masterpiece here...", height=300, key="main_content")
|
| 259 |
+
st.markdown('</div>', unsafe_allow_html=True)
|
| 260 |
|
| 261 |
+
col1, col2 = st.columns([0.6, 0.4])
|
|
|
|
|
|
|
| 262 |
with col1:
|
| 263 |
+
st.subheader("๐ค Upload Your Content")
|
| 264 |
+
md_files = st.file_uploader("Upload Markdown Files (.md)", type=["md"], accept_multiple_files=True)
|
| 265 |
+
img_files = st.file_uploader("Upload Images (.png, .jpg)", type=["png", "jpg", "jpeg"], accept_multiple_files=True)
|
| 266 |
+
|
|
|
|
| 267 |
with col2:
|
| 268 |
+
st.subheader("๐ Text-to-Speech")
|
| 269 |
+
selected_voice = st.selectbox("Select Voice", ["en-US-AriaNeural", "en-GB-SoniaNeural", "en-US-JennyNeural"])
|
| 270 |
+
if st.button("Generate Audio from Text ๐ค"):
|
| 271 |
+
full_text = user_text + ''.join(f.getvalue().decode() for f in md_files)
|
| 272 |
+
if full_text.strip():
|
| 273 |
+
with st.spinner("Warming up vocal cords..."):
|
| 274 |
+
audio_buffer = asyncio.run(generate_audio(full_text, selected_voice))
|
| 275 |
+
st.audio(audio_buffer, format="audio/mpeg")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 276 |
else:
|
| 277 |
+
st.warning("Please provide some text first!")
|
| 278 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 279 |
st.markdown("---")
|
| 280 |
+
if st.button("Forge my PDF! โ๏ธ", type="primary", use_container_width=True):
|
| 281 |
+
markdown_texts = [user_text] + [f.getvalue().decode() for f in md_files]
|
| 282 |
+
markdown_texts = [text for text in markdown_texts if text.strip()]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 283 |
|
| 284 |
+
with st.spinner("The PDF elves are hard at work... ๐งโโ๏ธ"):
|
| 285 |
+
pdf_gen = PdfGenerator(markdown_texts, img_files, pdf_settings)
|
| 286 |
+
pdf_bytes = pdf_gen.generate()
|
| 287 |
+
|
| 288 |
+
if pdf_bytes:
|
| 289 |
+
st.success("Your PDF has been forged!")
|
| 290 |
+
st.download_button(label="๐ฅ Download PDF", data=pdf_bytes, file_name="generated_document.pdf", mime="application/pdf")
|
| 291 |
+
|
| 292 |
+
st.subheader("๐ PDF Preview")
|
| 293 |
+
pix_list = pdf_to_image(pdf_bytes.getvalue())
|
| 294 |
+
if pix_list:
|
| 295 |
+
for i, pix in enumerate(pix_list):
|
| 296 |
+
st.image(pix.tobytes("png"), caption=f"Page {i+1}")
|
| 297 |
+
else:
|
| 298 |
+
st.error("The PDF forging failed. Check your inputs and try again.")
|
| 299 |
+
|
| 300 |
with tab2:
|
| 301 |
+
st.header("๐งช Python Code Interpreter")
|
| 302 |
+
st.info("This is the original code interpreter. Paste your Python code below to run it.")
|
| 303 |
+
code = st.text_area("Code Editor", height=400, value="import streamlit as st\nst.balloons()")
|
| 304 |
+
if st.button("Run Code โถ๏ธ"):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 305 |
try:
|
| 306 |
+
exec(code)
|
|
|
|
|
|
|
| 307 |
except Exception as e:
|
| 308 |
+
st.error(f"๐ฑ Code went kaboom! Error: {e}")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|