Spaces:
Runtime error
Runtime error
Update brief.py
Browse files12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455import gradio as grfrom PIL import Imagefrom diffusers import StableDiffusionImg2ImgPipelineimport torch# Detect devicedevice = "cuda" if torch.cuda.is_available() else "cpu"dtype = torch.float16 if device == "cuda" else torch.float32# Load the model with appropriate dtypepipe = StableDiffusionImg2ImgPipeline.from_pretrained("runwayml/stable-diffusion-v1-5",torch_dtype=dtype,use_safetensors=True).to(device)# Resize uploaded image to selected aspect ratiodef resize_to_aspect(image, aspect_ratio):width, height = image.sizeaspect_map = {"1:1": (min(width, height), min(width, height)),"16:9": (width, int(width * 9 / 16)),"4:5": (width, int(width * 5 / 4)),"9:16": (int(height * 9 / 16), height)}target_w, target_h = aspect_map.get(aspect_ratio, (width, height))image = image.resize((target_w, target_h))return imagedef resize_to_512(image):return image.resize((512, 512))## Generate new image from prompt and reference imagedef generate_img(product_img, prompt, aspect_ratio):resized_img = resize_to_aspect(product_img, aspect_ratio).convert("RGB")resized_img = resize_to_512(resized_img) # Required by the modeloutput = pipe(prompt=prompt, image=resized_img, strength=0.75, guidance_scale=7.5)return output.images[0]# Gradio UIgr.Interface(fn=generate_img,inputs=[gr.Image(type="pil", label="Upload Product Image"),gr.Textbox(label="Prompt", placeholder="Describe what you want to generate"),gr.Dropdown(["1:1", "16:9", "4:5", "9:16"], label="Aspect Ratio", value="1:1")],# outputs=gr.Image(label="Generated Image", type="pil"),outputs=gr.Image(label='Download Image'),title="Image-to-Image Product Generator",description="upload a product image, describe your idea, and select the output aspect ratio.").launch()1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374import gradio as grfrom PIL import Imageimport numpy as npfrom transformers import CLIPSegProcessor, CLIPSegForImageSegmentationfrom matplotlib.colors import to_rgbimport reimport cv2# Load modelprocessor = CLIPSegProcessor.from_pretrained("CIDAS/clipseg-rd64-refined")model = CLIPSegForImageSegmentation.from_pretrained("CIDAS/clipseg-rd64-refined")def parse_color(color_str):"""Converts a color string (hex, name, or rgba(...)) to an RGB tuple."""try:if isinstance(color_str, str):if color_str.startswith("rgba("):# Extract the 3 RGB componentsnumbers = list(map(float, re.findall(r"[\d.]+", color_str)))if len(numbers) >= 3:r, g, b = numbers[:3]return int(r), int(g), int(b)else:# Use named or hex colorreturn tuple(int(255 * c) for c in to_rgb(color_str))except Exception:passraise ValueError(f"Invalid color format: {color_str}. Use hex like '#ff0000', color name like 'red', or rgba format.")def apply_mask(image: Image.Image, prompt: str, color: str) -> Image.Image:# Process the input image and promptinputs = processor(text=prompt, images=image, return_tensors="pt")outputs = model(**inputs)preds = outputs.logits[0]# Get the binary mask from predictionsmask = preds.sigmoid().detach().cpu().numpy()mask = (mask > 0.5).astype(np.uint8)# Convert image to RGBAimage_np = np.array(image.convert("RGBA"))# Resize mask to match image sizemask_resized = cv2.resize(mask, (image_np.shape[1], image_np.shape[0]))mask_3d = np.stack([mask_resized] * 4, axis=-1) # Extend mask to 3D# Convert the color string to an RGB tuplecolor_rgb = parse_color(color)overlay_color = np.array([*color_rgb, 128], dtype=np.uint8) # RGBA with alpha 128# Create an overlay with the selected coloroverlay = np.zeros_like(image_np, dtype=np.uint8)overlay[:] = overlay_color# Apply the mask to the imagemasked_image = np.where(mask_3d == 1, overlay, image_np)return Image.fromarray(masked_image)# Gradio Interfaceiface = gr.Interface(fn=apply_mask,inputs=[gr.Image(type="pil", label="Input Image"),gr.Textbox(label="Segmentation Prompt", placeholder="e.g., helmet, road, sky"),gr.ColorPicker(label="Mask Color", value="#ff0000")],outputs=gr.Image(type="pil", label="Segmented Image"),title="CLIPSeg Image Masking",description="Upload an image, input a prompt (e.g., 'person', 'sky'), and pick a mask color.")iface.launch()
brief.py+69-50