import os import sys import subprocess import traceback import streamlit as st from PIL import Image, ImageOps import io import zipfile # === Auto-install missing dependencies === def install_missing_packages(): required = ["pillow", "pytoshop", "six"] for pkg in required: try: __import__(pkg) except ImportError: subprocess.check_call([sys.executable, "-m", "pip", "install", pkg]) install_missing_packages() # Attempt rawpy, but handle gracefully if not available try: import rawpy RAWPY_AVAILABLE = True except Exception: RAWPY_AVAILABLE = False st.warning("⚠️ rawpy unavailable; CR2/RAW reading won't be supported.") from pytoshop import user, enums # === Setup Folders === root_dir = os.getcwd() upload_dir = os.path.join(root_dir, "upload") download_dir = os.path.join(root_dir, "download") os.makedirs(upload_dir, exist_ok=True) os.makedirs(download_dir, exist_ok=True) st.set_page_config(page_title="Dresma Editor", page_icon="🎨", layout="centered") st.title("🎨 Dresma Editor") st.caption("Convert, resize, and optimize your images easily!") # === File uploader === uploaded_files = st.file_uploader("📁 Upload your images", type=["jpg", "jpeg", "png", "tiff", "psd", "cr2"], accept_multiple_files=True) # === Inputs === col1, col2 = st.columns(2) with col1: aspect_or_dim = st.text_input("📏 Aspect ratio or dimensions", placeholder="5:4 or 3000,2000") dpi_input = st.text_input("🖨️ Target DPI", placeholder="e.g. 300") with col2: color_choice = st.selectbox("🎨 Color mode", ["Keep original", "sRGB", "Adobe RGB (simulated)", "CMYK"]) formats_input = st.text_input("📸 Output formats", placeholder="jpg,png,tiff,psd") min_input, max_input = st.columns(2) with min_input: min_size = st.text_input("Min file size (MB)", "") with max_input: max_size = st.text_input("Max file size (MB)", "") process_btn = st.button("🚀 Process Images") # === Helper === def open_image(path): ext = os.path.splitext(path)[1].lower() if ext == ".cr2" and RAWPY_AVAILABLE: with rawpy.imread(path) as raw: rgb = raw.postprocess() return Image.fromarray(rgb) else: return Image.open(path) def process_images(): # Save uploads for file in uploaded_files: with open(os.path.join(upload_dir, file.name), "wb") as f: f.write(file.getbuffer()) # Parse aspect ratio/dimensions if not aspect_or_dim: width = height = None else: try: if "," in aspect_or_dim: width, height = map(int, aspect_or_dim.split(",")) else: ar_w, ar_h = map(int, aspect_or_dim.split(":")) width, height = ar_w * 1000, ar_h * 1000 except Exception: width = height = None try: dpi = int(dpi_input) if dpi_input else None except ValueError: dpi = None color_mode = None if color_choice == "CMYK": color_mode = "CMYK" elif color_choice in ["sRGB", "Adobe RGB (simulated)"]: color_mode = "RGB" # Output formats if not formats_input: out_exts = None else: allowed = {"jpg", "jpeg", "png", "tiff", "psd"} requested = [] for token in [t.strip() for t in formats_input.split(",") if t.strip()]: fmt = token.replace("jpeg", "jpg") if fmt in allowed: requested.append(fmt) out_exts = requested if requested else None processed_files = [] with st.spinner("⚙️ Processing your images... please wait"): for file in os.listdir(upload_dir): file_path = os.path.join(upload_dir, file) if not os.path.isfile(file_path): continue try: img = open_image(file_path) # Resize if width and height: img = img.resize((width, height)) # DPI if dpi is not None: img.info['dpi'] = (dpi, dpi) # Color if color_mode == "CMYK" and img.mode != "CMYK": img = img.convert("CMYK") elif color_mode == "RGB" and img.mode != "RGB": img = img.convert("RGB") orig_ext = os.path.splitext(file)[1].lstrip(".").lower() or "jpg" formats_to_save = out_exts if out_exts else [orig_ext] base_name = os.path.splitext(file)[0] for fmt in formats_to_save: chosen_ext = "jpg" if fmt == "jpeg" else fmt out_file = os.path.join(download_dir, f"{base_name}.{chosen_ext}") img_copy = img.copy() if chosen_ext == "psd": try: if img_copy.mode not in ("CMYK", "RGB", "RGBA"): img_copy = img_copy.convert("RGB") psd = user.nested_layers.new_document( mode=enums.ColorMode.cmyk if img_copy.mode == "CMYK" else enums.ColorMode.rgb, size=img_copy.size ) psd.image = img_copy with open(out_file, "wb") as f: psd.write(f) except Exception: img_copy.save(out_file, format="TIFF") elif chosen_ext == "jpg": if img_copy.mode != "RGB": img_copy = img_copy.convert("RGB") img_copy.save(out_file, format="JPEG", dpi=(dpi, dpi) if dpi else None, quality=95) elif chosen_ext == "png": img_copy.save(out_file, format="PNG", dpi=(dpi, dpi) if dpi else None) elif chosen_ext == "tiff": img_copy.save(out_file, format="TIFF", dpi=(dpi, dpi) if dpi else None) else: img_copy.save(out_file, dpi=(dpi, dpi) if dpi else None) processed_files.append(out_file) except Exception as e: st.error(f"❌ Error processing {file}: {e}") traceback.print_exc() return processed_files if process_btn and uploaded_files: results = process_images() if results: st.success(f"🎉 Processed {len(results)} image(s) successfully!") # Show previews and download buttons for path in results: with open(path, "rb") as f: data = f.read() st.image(path, caption=os.path.basename(path), use_container_width=True) st.download_button("⬇️ Download " + os.path.basename(path), data=data, file_name=os.path.basename(path)) # Offer ZIP download zip_buffer = io.BytesIO() with zipfile.ZipFile(zip_buffer, "w") as zf: for path in results: zf.write(path, os.path.basename(path)) st.download_button("📦 Download All as ZIP", data=zip_buffer.getvalue(), file_name="dresma_output.zip") elif process_btn and not uploaded_files: st.warning("⚠️ Please upload at least one image first.") else: st.info("⬆️ Upload images, then click **Process Images** to begin.")