Spaces:
Runtime error
Runtime error
Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,60 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
|
| 2 |
+
import streamlit as st
|
| 3 |
+
import torch
|
| 4 |
+
from diffusers import StableDiffusionPipeline
|
| 5 |
+
from PIL import Image
|
| 6 |
+
import cloudinary
|
| 7 |
+
import cloudinary.uploader
|
| 8 |
+
from cloudinary.utils import cloudinary_url
|
| 9 |
+
|
| 10 |
+
# ---- Cloudinary Configuration ----
|
| 11 |
+
cloudinary.config(
|
| 12 |
+
cloud_name=st.secrets["CLOUDINARY"]["cloud_name"],
|
| 13 |
+
api_key=st.secrets["CLOUDINARY"]["api_key"],
|
| 14 |
+
api_secret=st.secrets["CLOUDINARY"]["api_secret"],
|
| 15 |
+
secure=True
|
| 16 |
+
)
|
| 17 |
+
|
| 18 |
+
# ---- Cloudinary Upload Function ----
|
| 19 |
+
def upload_to_cloudinary(image_path):
|
| 20 |
+
try:
|
| 21 |
+
upload_result = cloudinary.uploader.upload(image_path)
|
| 22 |
+
public_id = upload_result["public_id"]
|
| 23 |
+
|
| 24 |
+
# Optional: Create optimized or transformed URLs
|
| 25 |
+
optimized_url, _ = cloudinary_url(public_id, fetch_format="auto", quality="auto")
|
| 26 |
+
auto_crop_url, _ = cloudinary_url(public_id, width=500, height=500, crop="auto", gravity="auto")
|
| 27 |
+
|
| 28 |
+
return upload_result["secure_url"] # or return optimized_url / auto_crop_url
|
| 29 |
+
except Exception as e:
|
| 30 |
+
print(f"Upload failed: {e}")
|
| 31 |
+
return None
|
| 32 |
+
|
| 33 |
+
# ---- Load Stable Diffusion Model ----
|
| 34 |
+
@st.cache_resource
|
| 35 |
+
def load_model():
|
| 36 |
+
pipe = StableDiffusionPipeline.from_pretrained(
|
| 37 |
+
"runwayml/stable-diffusion-v1-5", torch_dtype=torch.float16
|
| 38 |
+
)
|
| 39 |
+
return pipe.to("cuda" if torch.cuda.is_available() else "cpu")
|
| 40 |
+
|
| 41 |
+
pipe = load_model()
|
| 42 |
+
|
| 43 |
+
# ---- Streamlit App UI ----
|
| 44 |
+
st.title("🎨 Text-to-Image Generator")
|
| 45 |
+
prompt = st.text_input("Enter your prompt (e.g. 'a cute cat on a bike')")
|
| 46 |
+
|
| 47 |
+
if st.button("Generate Image") and prompt:
|
| 48 |
+
with st.spinner("Generating..."):
|
| 49 |
+
image = pipe(prompt).images[0]
|
| 50 |
+
image_path = "generated_image.png"
|
| 51 |
+
image.save(image_path)
|
| 52 |
+
|
| 53 |
+
# Upload image to Cloudinary
|
| 54 |
+
image_url = upload_to_cloudinary(image_path)
|
| 55 |
+
|
| 56 |
+
if image_url:
|
| 57 |
+
st.image(image_url, caption="Generated via Stable Diffusion")
|
| 58 |
+
st.markdown(f"[🔗 Click to view full image]({image_url})")
|
| 59 |
+
else:
|
| 60 |
+
st.error("❌ Failed to upload image.")
|