Spaces:
Runtime error
Runtime error
File size: 7,415 Bytes
adca06c fcfe31f adca06c 338e4fe fcfe31f adca06c 338e4fe adca06c 338e4fe adca06c 338e4fe adca06c 338e4fe adca06c 338e4fe adca06c 338e4fe adca06c 338e4fe adca06c 338e4fe adca06c 338e4fe adca06c 338e4fe adca06c 338e4fe adca06c 338e4fe adca06c 338e4fe adca06c 338e4fe adca06c 338e4fe | 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 | 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.")
|