File size: 14,595 Bytes
5978ca5 137bf65 5978ca5 137bf65 5978ca5 137bf65 5978ca5 eb34529 5978ca5 eb34529 5978ca5 eb34529 5978ca5 eb34529 137bf65 eb34529 5978ca5 eb34529 5978ca5 eb34529 137bf65 eb34529 5978ca5 eb34529 137bf65 eb34529 137bf65 5978ca5 eb34529 5978ca5 eb34529 137bf65 eb34529 5978ca5 eb34529 5978ca5 eb34529 5978ca5 137bf65 5978ca5 137bf65 5978ca5 eb34529 5978ca5 eb34529 5978ca5 eb34529 5978ca5 eb34529 137bf65 eb34529 137bf65 5978ca5 eb34529 137bf65 eb34529 137bf65 eb34529 137bf65 eb34529 137bf65 5978ca5 eb34529 5978ca5 137bf65 eb34529 5978ca5 eb34529 5978ca5 eb34529 137bf65 eb34529 137bf65 eb34529 5978ca5 eb34529 137bf65 5978ca5 137bf65 5978ca5 eb34529 5978ca5 eb34529 5978ca5 eb34529 137bf65 5978ca5 eb34529 137bf65 eb34529 137bf65 eb34529 137bf65 eb34529 5978ca5 eb34529 5978ca5 eb34529 5978ca5 eb34529 5978ca5 eb34529 137bf65 eb34529 137bf65 eb34529 5978ca5 eb34529 137bf65 eb34529 137bf65 eb34529 5978ca5 eb34529 5978ca5 137bf65 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 |
import io
import os
import re
import glob
import textwrap
import base64
import sys
from datetime import datetime
from pathlib import Path
from contextlib import redirect_stdout
import streamlit as st
import pandas as pd
from PIL import Image
from reportlab.pdfgen import canvas
from reportlab.lib.pagesizes import letter
from reportlab.lib.utils import ImageReader
from reportlab.pdfbase import pdfmetrics
from reportlab.pdfbase.ttfonts import TTFont
import mistune
from gtts import gTTS
# --- Helper Functions ---
# ποΈ Deletes a specified file and reruns the app.
def delete_asset(path):
"""Safely deletes a file if it exists and reruns the Streamlit app."""
try:
os.remove(path)
except OSError as e:
st.error(f"Error deleting file {path}: {e}")
st.rerun()
# π₯ Gets text input from either a file upload or a text area.
def get_text_input(file_uploader_label, accepted_types, text_area_label):
"""
Provides UI for uploading a text file or entering text manually.
Returns the text content and a filename stem.
"""
md_text = ""
stem = datetime.now().strftime('%Y%m%d_%H%M%S')
uploaded_file = st.file_uploader(file_uploader_label, type=accepted_types)
if uploaded_file:
md_text = uploaded_file.getvalue().decode("utf-8")
stem = Path(uploaded_file.name).stem
else:
md_text = st.text_area(text_area_label, height=200, value="## Your Markdown Here\n\nEnter your markdown text, or upload a file.")
# Convert markdown to plain text for processing
renderer = mistune.HTMLRenderer()
markdown = mistune.create_markdown(renderer=renderer)
html = markdown(md_text or "")
plain_text = re.sub(r'<[^>]+>', '', html)
return plain_text, stem
# π£οΈ Generates an MP3 voice file from text using gTTS.
def generate_voice_file(text, lang, is_slow, filename):
"""
Creates an MP3 from text, saves it, and provides it for playback and download.
"""
if not text.strip():
st.warning("No text to generate voice from.")
return
voice_file_path = f"{filename}.mp3"
try:
tts = gTTS(text=text, lang=lang, slow=is_slow)
tts.save(voice_file_path)
st.audio(voice_file_path)
with open(voice_file_path, 'rb') as fp:
st.download_button("π₯ Download MP3", data=fp, file_name=voice_file_path, mime="audio/mpeg")
except Exception as e:
st.error(f"Failed to generate audio: {e}")
# π Creates a PDF document from text and images.
def generate_pdf(text_content, images, pdf_params):
"""
Generates a PDF buffer from text and a list of images based on specified parameters.
"""
buf = io.BytesIO()
# --- Register Custom Fonts ---
for font_path in pdf_params.get('ttf_files', []):
try:
font_name = Path(font_path).stem
pdfmetrics.registerFont(TTFont(font_name, font_path))
except Exception as e:
st.warning(f"Could not register font {font_path}: {e}")
c = canvas.Canvas(buf)
page_w, page_h = letter
margin = 40
gutter = 20
col_w = (page_w - 2 * margin - (pdf_params['columns'] - 1) * gutter) / pdf_params['columns']
# Use registered font name, which is the stem of the file path
font_name_to_use = Path(pdf_params['font_family']).stem if ".ttf" in pdf_params['font_family'] else pdf_params['font_family']
c.setFont(font_name_to_use, pdf_params['font_size'])
line_height = pdf_params['font_size'] * 1.2
# Estimate characters per line for wrapping
# 0.6 is a common factor for average character width vs font size
wrap_width = int(col_w / (pdf_params['font_size'] * 0.6)) if pdf_params['font_size'] > 0 else 50
y = page_h - margin
col_idx = 0
# --- Render Text ---
for paragraph in text_content.split("\n"):
wrapped_lines = textwrap.wrap(paragraph, wrap_width) if paragraph.strip() else [""]
for line in wrapped_lines:
if y < margin:
col_idx += 1
if col_idx >= pdf_params['columns']:
c.showPage()
c.setFont(font_name_to_use, pdf_params['font_size'])
col_idx = 0
y = page_h - margin
x = margin + col_idx * (col_w + gutter)
c.drawString(x, y, line)
y -= line_height
y -= line_height # Add extra space for paragraph breaks
# --- Render Images ---
for img_file in images:
try:
# Handle both file paths and uploaded file objects
img = Image.open(img_file)
w, h = img.size
c.showPage()
c.setPageSize((w, h))
c.drawImage(ImageReader(img), 0, 0, w, h, preserveAspectRatio=True, mask='auto')
except Exception as e:
img_name = img_file.name if hasattr(img_file, 'name') else img_file
st.warning(f"Could not process image {img_name}: {e}")
continue
c.save()
buf.seek(0)
return buf
# ποΈ Displays a list of generated assets with download/delete options.
def show_asset_manager():
"""Scans for local files and displays them with management controls."""
st.markdown("---")
st.subheader("π Available Assets")
assets = sorted(glob.glob("*.*"))
if not assets:
st.info("No assets generated yet.")
return
for asset_path in assets:
# Avoid showing the script itself
if asset_path.endswith('.py'):
continue
ext = Path(asset_path).suffix.lower()
cols = st.columns([3, 1, 1])
cols[0].write(f"`{asset_path}`")
try:
with open(asset_path, 'rb') as fp:
file_bytes = fp.read()
if ext == '.pdf':
cols[1].download_button("π₯", data=file_bytes, file_name=asset_path, mime="application/pdf", key=f"dl_{asset_path}")
elif ext == '.mp3':
cols[1].audio(file_bytes)
elif ext in ['.png', '.jpg', '.jpeg']:
cols[1].image(file_bytes, width=60)
except Exception as e:
cols[1].error("Error")
cols[2].button("ποΈ", key=f"del_{asset_path}", on_click=delete_asset, args=(asset_path,))
# π§© Shows a demo of how to use the functions with file lists
def show_batch_processing_demo(pdf_params):
"""Finds local files and shows how to process them."""
st.markdown("---")
st.subheader("π§© Batch Processing Demo")
st.info("This section demonstrates how you could call the PDF generation function programmatically with lists of files.")
md_files = glob.glob("*.md")
img_files = glob.glob("*.png") + glob.glob("*.jpg")
if not md_files or not img_files:
st.warning("To run the demo, please ensure there is at least one `.md` file and one image (`.png`/`.jpg`) in the directory.")
return
st.write("Found the following files to use for the demo:")
st.write(f"**Markdown file:** `{md_files[0]}`")
st.write(f"**Image files:** `{', '.join(img_files)}`")
if st.button("π§ͺ Run Demo with Above Files"):
md_file_str = md_files[0]
img_files_str = ",".join(img_files)
# --- Example of programmatic execution ---
# 1. Read the markdown file
with open(md_file_str, 'r') as f:
text_content = f.read()
# 2. Open the image files (generate_pdf expects file-like objects or paths)
image_objects = img_files # Pass paths directly
# 3. Call the generator function
pdf_buffer = generate_pdf(text_content, image_objects, pdf_params)
# 4. Provide for download
st.download_button(
"β¬οΈ Download Batch Demo PDF",
data=pdf_buffer,
file_name="batch_demo_output.pdf",
mime="application/pdf"
)
st.success("Batch demo PDF generated!")
# π Renders the entire UI and logic for the Python code interpreter.
def render_code_interpreter():
"""Sets up the UI and execution logic for the code interpreter tab."""
st.header("π§ͺ Python Code Executor & Demo")
# --- Nested Helper Functions for this Tab ---
def extract_python_code(md_text):
return re.findall(r"```python\s*(.*?)```", md_text, re.DOTALL)
def execute_code(code_str):
output_buffer = io.StringIO()
try:
# The exec function will have access to globally imported libraries
exec_globals = {
"st": st,
"glob": glob,
"base64": base64,
"io": io,
"canvas": canvas,
"letter": letter
}
with redirect_stdout(output_buffer):
exec(code_str, exec_globals)
return output_buffer.getvalue(), None
except Exception as e:
return None, str(e)
# --- Main Logic for the Tab ---
DEFAULT_CODE = """
import streamlit as st
import glob
import base64
import io
from reportlab.pdfgen import canvas
from reportlab.lib.pagesizes import letter
st.title("π Enhanced Demo App")
st.markdown("This demo shows file galleries and base64 PDF downloads.")
# --- Image Gallery ---
with st.expander("πΌοΈ Show Image Files in Directory"):
image_files = glob.glob("*.png") + glob.glob("*.jpg")
if not image_files:
st.write("No image files found.")
else:
st.image(image_files)
# --- PDF Gallery ---
with st.expander("π Show PDF Files in Directory"):
pdf_files = glob.glob("*.pdf")
if not pdf_files:
st.write("No PDF files found.")
else:
st.write(pdf_files)
# --- PDF Generation and Download ---
if st.button("Generate Demo PDF & Download Link"):
# 1. Create PDF in memory
buffer = io.BytesIO()
p = canvas.Canvas(buffer, pagesize=letter)
p.drawString(100, 750, "This is a demo PDF generated from the code interpreter.")
p.showPage()
p.save()
# 2. Encode PDF to Base64
b64 = base64.b64encode(buffer.getvalue()).decode()
# 3. Create download link
href = f'<a href="data:application/pdf;base64,{b64}" download="demo_from_code.pdf">Download Generated PDF</a>'
st.markdown(href, unsafe_allow_html=True)
st.success("PDF generated! Click the link above to download.")
"""
if 'code' not in st.session_state:
st.session_state.code = DEFAULT_CODE
uploaded_file = st.file_uploader("Upload .py or .md", type=['py', 'md'], key="code_uploader")
if uploaded_file:
file_content = uploaded_file.getvalue().decode()
if uploaded_file.type == 'text/markdown':
codes = extract_python_code(file_content)
st.session_state.code = codes[0] if codes else ''
else:
st.session_state.code = file_content
st.session_state.code = st.text_area("π» Code Editor", value=st.session_state.code, height=400)
c1, c2 = st.columns(2)
if c1.button("βΆοΈ Run Code", use_container_width=True):
output, err = execute_code(st.session_state.code)
st.subheader("Output")
if err:
st.error(err)
if output: # Show output even if empty, to confirm it ran
st.code(output, language='text')
if not err:
st.success("Executed successfully.")
if c2.button("ποΈ Clear Code", use_container_width=True):
st.session_state.code = ''
st.rerun()
# --- Main App ---
def main():
"""Main function to run the Streamlit application."""
st.set_page_config(page_title="PDF & Code Interpreter", layout="wide", page_icon="π")
tab1, tab2 = st.tabs(["π PDF Composer", "π§ͺ Code Interpreter"])
with tab1:
st.header("π PDF Composer & Voice Generator π")
# --- Sidebar Controls ---
st.sidebar.title("PDF Settings")
# --- Dynamic Font Loading ---
ttf_files = glob.glob("*.ttf")
standard_fonts = ["Helvetica", "Times-Roman", "Courier"]
available_fonts = ttf_files + standard_fonts
default_font_index = 0 if ttf_files else 0 # Default to first ttf or Helvetica
pdf_params = {
'columns': st.sidebar.slider("Text columns", 1, 3, 1),
'font_family': st.sidebar.selectbox("Font", available_fonts, index=default_font_index),
'font_size': st.sidebar.slider("Font size", 6, 48, 12),
'ttf_files': ttf_files
}
# --- Main UI ---
plain_text, filename_stem = get_text_input(
"Upload Markdown (.md)", ["md"], "Or enter markdown text directly"
)
st.subheader("π£οΈ Voice Generation")
languages = {"English (US)": "en", "English (UK)": "en-uk", "Spanish": "es"}
voice_choice = st.selectbox("Voice Language", list(languages.keys()))
slow_speech = st.checkbox("Slow Speech")
if st.button("π Generate Voice MP3"):
generate_voice_file(plain_text, languages[voice_choice], slow_speech, filename_stem)
st.subheader("πΌοΈ Image Upload")
uploaded_images = st.file_uploader(
"Upload Images for PDF", type=["png", "jpg", "jpeg"], accept_multiple_files=True
)
ordered_images = []
if uploaded_images:
df_imgs = pd.DataFrame([{"name": f.name, "order": i} for i, f in enumerate(uploaded_images)])
edited_df = st.data_editor(df_imgs, use_container_width=True, key="img_order_editor")
image_map = {f.name: f for f in uploaded_images}
for _, row in edited_df.sort_values("order").iterrows():
if row['name'] in image_map:
ordered_images.append(image_map[row['name']])
st.subheader("ποΈ PDF Generation")
if st.button("Generate PDF from UI"):
if not plain_text.strip() and not ordered_images:
st.warning("Please provide some text or images to generate a PDF.")
else:
pdf_buffer = generate_pdf(plain_text, ordered_images, pdf_params)
st.download_button(
"β¬οΈ Download PDF",
data=pdf_buffer,
file_name=f"{filename_stem}.pdf",
mime="application/pdf"
)
show_asset_manager()
show_batch_processing_demo(pdf_params)
with tab2:
render_code_interpreter()
if __name__ == "__main__":
main()
|