Spaces:
Runtime error
Runtime error
Update src/streamlit_app.py
Browse files12345678910111213141516171819202122232425262728293031323334353637383940import altair as altimport numpy as npimport pandas as pdimport streamlit as st"""# Welcome to Streamlit!Edit `/streamlit_app.py` to customize this app to your heart's desire :heart:.If you have any questions, checkout our [documentation](https://docs.streamlit.io) and [communityforums](https://discuss.streamlit.io).In the meantime, below is an example of what you can do with just a few lines of code:"""num_points = st.slider("Number of points in spiral", 1, 10000, 1100)num_turns = st.slider("Number of turns in spiral", 1, 300, 31)indices = np.linspace(0, 1, num_points)theta = 2 * np.pi * num_turns * indicesradius = indicesx = radius * np.cos(theta)y = radius * np.sin(theta)df = pd.DataFrame({"x": x,"y": y,"idx": indices,"rand": np.random.randn(num_points),})st.altair_chart(alt.Chart(df, height=700, width=700).mark_point(filled=True).encode(x=alt.X("x", axis=None),y=alt.Y("y", axis=None),color=alt.Color("idx", legend=None, scale=alt.Scale()),size=alt.Size("rand", legend=None, scale=alt.Scale(range=[1, 150])),))123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188import osimport sysimport subprocessimport tracebackimport streamlit as stfrom PIL import Image, ImageOps# === 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 it gracefully if not availabletry:import rawpyRAWPY_AVAILABLE = Trueexcept Exception:RAWPY_AVAILABLE = Falsest.warning("β οΈ rawpy unavailable; CR2/RAW reading won't be supported in this environment.")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.title("π¨ Dresma Editor")st.write("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 ===aspect_or_dim = st.text_input("π Aspect ratio or specific dimensions (e.g., 5:4 or 3000,2000)", "")dpi_input = st.text_input("π¨οΈ Target DPI (e.g., 300)", "")color_choice = st.selectbox("π¨ Color mode", ["Keep original", "sRGB", "Adobe RGB (simulated)", "CMYK"])min_input = st.text_input("πΎ Minimum file size (MB)", "")max_input = st.text_input("πΎ Maximum file size (MB)", "")formats_input = st.text_input("πΈ Output formats (comma-separated, e.g., jpg,png,tiff,psd)", "")process_btn = st.button("π Start Processing")# === 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)if process_btn and uploaded_files:try:# Save uploads locallyfor file in uploaded_files:with open(os.path.join(upload_dir, file.name), "wb") as f:f.write(file.getbuffer())# === Parse Inputs ===if not aspect_or_dim:width = height = Noneelse: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 * 1000except Exception:width = height = Nonetry:dpi = int(dpi_input) if dpi_input else Noneexcept ValueError:dpi = Nonecolor_mode = Noneif color_choice == "CMYK":color_mode = "CMYK"elif color_choice in ["sRGB", "Adobe RGB (simulated)"]:color_mode = "RGB"try:min_size = float(min_input) if min_input else Noneexcept ValueError:min_size = Nonetry:max_size = float(max_input) if max_input else Noneexcept ValueError:max_size = Noneif not formats_input:out_exts = Noneelse: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 Nonest.info("π Processing images... please wait!")# === Process each image ===for file in os.listdir(upload_dir):file_path = os.path.join(upload_dir, file)if not os.path.isfile(file_path):continuetry:img = open_image(file_path)# Resizeif width and height:img = img.resize((width, height))# DPIif dpi is not None:img.info['dpi'] = (dpi, dpi)# Colorif 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 is not None else [orig_ext]base_name = os.path.splitext(file)[0]for fmt in formats_to_save:chosen_ext = "jpg" if fmt == "jpeg" else fmtout_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_copywith 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)except Exception as e:st.error(f"β Error processing {file}: {e}")traceback.print_exc()st.success("π All images processed successfully!")# === Provide download links ===for file in os.listdir(download_dir):out_path = os.path.join(download_dir, file)with open(out_path, "rb") as f:st.download_button(label=f"β¬οΈ Download {file}", data=f, file_name=file)except Exception as e:st.error(f"Unexpected error: {e}")traceback.print_exc()else:st.info("β¬οΈ Upload images and click **Start Processing** to begin.")
src/streamlit_app.py+186-38