# utils.py import streamlit as st import re import base64 from PIL import Image import io MAX_FILE_SIZE_MB = 5 # Maximum file size in megabytes @st.cache_data def cached_st_latex(latex_string, key): """Caches the results of st.latex.""" return st.latex(latex_string, key=key) def render_latex(text): """ Renders LaTeX in the text using st.latex and caching. """ if "latex_segments" not in st.session_state: st.session_state.latex_segments = [] i = 1 while True: placeholder = f"$$latex{i}$$" if placeholder in text: latex_original = st.session_state.latex_segments[i - 1] cached_st_latex(latex_original, key=f"latex_{i}") text = text.replace(placeholder, f"$${latex_original}$$") i += 1 else: break # Find and store new LaTeX segments, while rendering existing. matches = re.findall(r'\$\$(.*?)\$\$', text, re.DOTALL) for match in matches: if match not in st.session_state.latex_segments: st.session_state.latex_segments.append(match) return text def process_image(uploaded_file): """ Processes the uploaded image: converts to RGB and returns base64 data. Supports: JPEG, PNG, GIF, WebP. """ if uploaded_file.size > MAX_FILE_SIZE_MB * 1024 * 1024: raise ValueError(f"File size too large. Maximum allowed size is {MAX_FILE_SIZE_MB} MB.") try: img = Image.open(uploaded_file) # Check and convert formats as needed if img.format not in ("JPEG", "PNG", "GIF", "WEBP"): raise ValueError(f"Unsupported image format: {img.format}") if img.format != "JPEG": if img.format == "PNG" and 'transparency' in img.info: # Handle transparency for PNG img = img.convert("RGBA") background = Image.new("RGBA", img.size, (255, 255, 255)) img = Image.alpha_composite(background, img).convert("RGB") elif img.format == "GIF" and img.is_animated: # Handle animation for GIF frames = [] for frame in range(img.n_frames): img.seek(frame) frames.append(img.convert("RGB")) buffered = io.BytesIO() # loop=0 for an infinite animation, frames[0].save(buffered, format="GIF", save_all=True, append_images=frames[1:], loop=0) image_data = base64.b64encode(buffered.getvalue()).decode("utf-8") return image_data, "gif" else: img = img.convert("RGB") # Convert other formats to RGB buffered = io.BytesIO() img.save(buffered, format="JPEG") # Always save as JPEG for consistency image_data = base64.b64encode(buffered.getvalue()).decode("utf-8") return image_data, "jpeg" except (IOError, ValueError, AttributeError) as e: raise ValueError(f"Failed to process image: {e}") from e