nexus00400/Text2Image-SD
0
1import os2import time3import io4import streamlit as st5from huggingface_hub import InferenceClient6 7st.set_page_config(page_title="Generator imagini", layout="centered")8 9st.title("Generator de imagini (via Stable Diffusion, Hugging Face)")10st.caption("Serverless Inference API routed by Hugging Face • returns image bytes (no URL).")11 12with st.sidebar:13 st.header("Setări")14 hf_token = st.text_input("HF_TOKEN (User Access Token)", type="password", help="Creează un token din Hugging Face → Settings → Access Tokens. Dă permisiuni pentru Inference Providers.")15 provider = st.selectbox("Provider", ["hf-inference", "replicate", ], index = 0)16 model = st.text_input("Model ID", value="stabilityai/stable-diffusion-xl-base-1.0")17 width = st.number_input("Lățime", min_value=256, max_value=1536, step=64, value=1024)18 height = st.number_input("Înălțime", min_value=256, max_value=1536, step=64, value=1024)19 steps = st.slider("Număr pași (num_inference_steps)", 1, 80, 20)20 guidance = st.slider("Guidance scale", 0.0, 20.0, 3.5, 0.5)21 seed = st.number_input("Seed (0 = aleator)", min_value=0, max_value=2**31-1, value=0, step=1)22 negative_prompt = st.text_input("Negative prompt (opțional)", value="")23 st.markdown("---")24 st.markdown("**Estimare cost/imag:** completează preț GPU/oră pentru a estima costul unei imagini (vezi docs).")25 gpu_hr_rate = st.number_input("GPU $/oră (ex: T4 ~0.5, L4 ~0.8)", min_value=0.0, value=0.5, step=0.1)26 27prompt = st.text_area("Prompt", placeholder="Samurai with swords dashing through bamboo trees", height=120)28 29col1, col2 = st.columns([1,1])30with col1:31 generate = st.button("Generate")32with col2:33 clear = st.button("Clear")34 35if clear:36 st.session_state.pop("last_image_bytes", None)37 st.session_state.pop("last_duration", None)38 39if generate:40 if not hf_token:41 st.error("Introduce HF_TOKEN în sidebar.")42 st.stop()43 # Build client44 client = InferenceClient(provider=provider, api_key=hf_token)45 46 params = {47 "num_inference_steps": int(steps),48 "guidance_scale": float(guidance),49 "width": int(width),50 "height": int(height),51 }52 if negative_prompt:53 params["negative_prompt"] = negative_prompt54 if seed and seed != 0:55 params["seed"] = int(seed)56 57 t0 = time.time()58 # text_to_image returns a PIL.Image for some providers; for uniformity, get raw bytes via raw http59 # but InferenceClient.text_to_image() already returns PIL.Image for supported providers including hf-inference.60 # We'll use it and then save to bytes for download.61 image = client.text_to_image(prompt, model=model, **params)62 duration = time.time() - t063 64 # Save to bytes65 buf = io.BytesIO()66 image.save(buf, format="PNG")67 img_bytes = buf.getvalue()68 69 st.session_state["last_image_bytes"] = img_bytes70 st.session_state["last_duration"] = duration71 72if "last_image_bytes" in st.session_state:73 st.subheader("Rezultat")74 st.image(st.session_state["last_image_bytes"], caption=f"Generat în {st.session_state['last_duration']:.2f}s", use_container_width=True)75 # Download76 st.download_button("⬇️ Descarcă PNG", data=st.session_state["last_image_bytes"], file_name="output.png", mime="image/png")77 # Cost estimate78 if gpu_hr_rate and st.session_state.get("last_duration"):79 seconds = float(st.session_state["last_duration"])80 cost = (gpu_hr_rate / 3600.0) * seconds81 st.info(f"Estimare cost/imag (pe {gpu_hr_rate:.2f} $/h): **${cost:.4f}** · timp: {seconds:.2f}s")82else:83 st.info("Completează promptul și apasă **Generează**.")84 85st.markdown("---")86st.caption("Notă: API-ul returnează **bytes** (nu URL). Aplicația salvează local și oferă buton de descărcare.")87 