Spaces:
Runtime error
Runtime error
Commit ·
dd0ab9f
1
Parent(s): e803877
refactor
Browse filesFiles changed (5)
- app.py+2-1
- helpers.pyAdded+46
- models.py+5-187
- pipelines.pyAdded+126
- segmentation.pyAdded+55
6 unmodified lines789101112136 unmodified linesimport osimport timefrom models import make_image_controlnet, make_inpainting, segment_imagefrom config import HEIGHT, WIDTH, POS_PROMPT, NEG_PROMPT, COLOR_MAPPING, map_colors, map_colors_rgbfrom palette import COLOR_MAPPING_CATEGORYfrom preprocessing import preprocess_seg_mask, get_image, get_mask6 unmodified lines78910111213146 unmodified linesimport osimport timefrom models import make_image_controlnet, make_inpaintingfrom segmentation import segment_imagefrom config import HEIGHT, WIDTH, POS_PROMPT, NEG_PROMPT, COLOR_MAPPING, map_colors, map_colors_rgbfrom palette import COLOR_MAPPING_CATEGORYfrom preprocessing import preprocess_seg_mask, get_image, get_mask
12345678910111213141516171819202122232425262728293031323334353637383940414243444546import gcimport torchfrom scipy.signal import fftconvolvefrom PIL import Image
def flush(): gc.collect() torch.cuda.empty_cache()
def convolution(mask: Image.Image, size=9) -> Image: """Method to blur the mask Args: mask (Image): masking image size (int, optional): size of the blur. Defaults to 9. Returns: Image: blurred mask """ mask = np.array(mask.convert("L")) conv = np.ones((size, size)) / size**2 mask_blended = fftconvolve(mask, conv, 'same') mask_blended = mask_blended.astype(np.uint8).copy()
border = size
# replace borders with original values mask_blended[:border, :] = mask[:border, :] mask_blended[-border:, :] = mask[-border:, :] mask_blended[:, :border] = mask[:, :border] mask_blended[:, -border:] = mask[:, -border:]
return Image.fromarray(mask_blended).convert("L")
def postprocess_image_masking(inpainted: Image, image: Image, mask: Image) -> Image: """Method to postprocess the inpainted image Args: inpainted (Image): inpainted image image (Image): original image mask (Image): mask Returns: Image: inpainted image """ final_inpainted = Image.composite(inpainted.convert("RGBA"), image.convert("RGBA"), mask) return final_inpainted.convert("RGB")7 unmodified lines8910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218354 unmodified lines2382392402412422432442452462472482492 unmodified lines2522532542552562572582592602612622632642652662672682692702712722732742752762772782792807 unmodified linesimport timeimport numpy as npfrom PIL import Imagefrom time import perf_counterfrom contextlib import contextmanagerfrom scipy.signal import fftconvolvefrom PIL import ImageFilterfrom transformers import AutoImageProcessor, UperNetForSemanticSegmentationfrom diffusers import ControlNetModel, UniPCMultistepSchedulerfrom diffusers import StableDiffusionInpaintPipelinefrom config import WIDTH, HEIGHTfrom palette import ade_palettefrom stable_diffusion_controlnet_inpaint_img2img import StableDiffusionControlNetInpaintImg2ImgPipelineLOGGING = logging.getLogger(__name__)def flush():gc.collect()torch.cuda.empty_cache()class ControlNetPipeline:def __init__(self):self.in_use = Falseself.controlnet = ControlNetModel.from_pretrained("BertChristiaens/controlnet-seg-room", torch_dtype=torch.float16)self.pipe = StableDiffusionControlNetInpaintImg2ImgPipeline.from_pretrained("runwayml/stable-diffusion-inpainting",controlnet=self.controlnet,safety_checker=None,torch_dtype=torch.float16)self.pipe.scheduler = UniPCMultistepScheduler.from_config(self.pipe.scheduler.config)self.pipe.enable_xformers_memory_efficient_attention()self.pipe = self.pipe.to("cuda")self.waiting_queue = []self.count = 0@propertydef queue_size(self):return len(self.waiting_queue)def __call__(self, **kwargs):self.count += 1number = self.countself.waiting_queue.append(number)# wait until the next number in the queue is the current numberwhile self.waiting_queue[0] != number:print(f"Wait for your turn {number} in queue {self.waiting_queue}")time.sleep(0.5)pass# it's your turn, so remove the number from the queue# and call the functionprint("It's the turn of", self.count)results = self.pipe(**kwargs)self.waiting_queue.pop(0)flush()return resultsclass SDPipeline:def __init__(self):self.pipe = StableDiffusionInpaintPipeline.from_pretrained("stabilityai/stable-diffusion-2-inpainting",torch_dtype=torch.float16,safety_checker=None,)self.pipe.enable_xformers_memory_efficient_attention()self.pipe = self.pipe.to("cuda")self.waiting_queue = []self.count = 0@propertydef queue_size(self):return len(self.waiting_queue)def __call__(self, **kwargs):self.count += 1number = self.countself.waiting_queue.append(number)# wait until the next number in the queue is the current numberwhile self.waiting_queue[0] != number:print(f"Wait for your turn {number} in queue {self.waiting_queue}")time.sleep(0.5)pass# it's your turn, so remove the number from the queue# and call the functionprint("It's the turn of", self.count)results = self.pipe(**kwargs)self.waiting_queue.pop(0)flush()return resultsdef convolution(mask: Image.Image, size=9) -> Image:"""Method to blur the maskArgs:mask (Image): masking imagesize (int, optional): size of the blur. Defaults to 9.Returns:Image: blurred mask"""mask = np.array(mask.convert("L"))conv = np.ones((size, size)) / size**2mask_blended = fftconvolve(mask, conv, 'same')mask_blended = mask_blended.astype(np.uint8).copy()border = size# replace borders with original valuesmask_blended[:border, :] = mask[:border, :]mask_blended[-border:, :] = mask[-border:, :]mask_blended[:, :border] = mask[:, :border]mask_blended[:, -border:] = mask[:, -border:]return Image.fromarray(mask_blended).convert("L")def postprocess_image_masking(inpainted: Image, image: Image, mask: Image) -> Image:"""Method to postprocess the inpainted imageArgs:inpainted (Image): inpainted imageimage (Image): original imagemask (Image): maskReturns:Image: inpainted image"""final_inpainted = Image.composite(inpainted.convert("RGBA"), image.convert("RGBA"), mask)return final_inpainted.convert("RGB")@st.experimental_singleton(max_entries=5)def get_controlnet() -> ControlNetModel:"""Method to load the controlnet modelReturns:ControlNetModel: controlnet model"""pipe = ControlNetPipeline()return pipe@st.experimental_singleton(max_entries=5)def get_segmentation_pipeline() -> Tuple[AutoImageProcessor, UperNetForSemanticSegmentation]:"""Method to load the segmentation pipelineReturns:Tuple[AutoImageProcessor, UperNetForSemanticSegmentation]: segmentation pipeline"""image_processor = AutoImageProcessor.from_pretrained("openmmlab/upernet-convnext-small")image_segmentor = UperNetForSemanticSegmentation.from_pretrained("openmmlab/upernet-convnext-small")return image_processor, image_segmentor@st.experimental_singleton(max_entries=5)def get_inpainting_pipeline() -> StableDiffusionInpaintPipeline:"""Method to load the inpainting pipelineReturns:StableDiffusionInpaintPipeline: inpainting pipeline"""pipe = SDPipeline()return pipe@torch.inference_mode()def make_image_controlnet(image: np.ndarray,54 unmodified linesList[Image.Image]: list of generated images"""pipe = get_inpainting_pipeline()mask_image_postproc = convolution(mask_image)flush()st.success(f"{pipe.queue_size} images in the queue, can take up to {(pipe.queue_size+1) * 10} seconds")generated_image = pipe(image=image,mask_image=Image.fromarray((mask_image * 255).astype(np.uint8)),prompt=positive_prompt,negative_prompt=negative_prompt,num_inference_steps=20,2 unmodified lines).images[0]generated_image = postprocess_image_masking(generated_image, image, mask_image_postproc)return image_@torch.inference_mode()@torch.autocast('cuda')def segment_image(image: Image) -> Image:"""Method to segment imageArgs:image (Image): input imageReturns:Image: segmented image"""image_processor, image_segmentor = get_segmentation_pipeline()pixel_values = image_processor(image, return_tensors="pt").pixel_valueswith torch.no_grad():outputs = image_segmentor(pixel_values)seg = image_processor.post_process_semantic_segmentation(outputs, target_sizes=[image.size[::-1]])[0]color_seg = np.zeros((seg.shape[0], seg.shape[1], 3), dtype=np.uint8)palette = np.array(ade_palette())for label, color in enumerate(palette):color_seg[seg == label, :] = colorcolor_seg = color_seg.astype(np.uint8)seg_image = Image.fromarray(color_seg).convert('RGB')return seg_image7 unmodified lines891011121314151617181920212223242554 unmodified lines808182838485868788899091922 unmodified lines959697987 unmodified linesimport timeimport numpy as npfrom PIL import Imagefrom PIL import ImageFilterfrom diffusers import ControlNetModel, UniPCMultistepSchedulerfrom config import WIDTH, HEIGHTfrom palette import ade_palettefrom stable_diffusion_controlnet_inpaint_img2img import StableDiffusionControlNetInpaintImg2ImgPipelinefrom helpers import flush, postprocess_image_masking, convolutionfrom pipelines import ControlNetPipeline, SDPipeline, get_inpainting_pipeline, get_controlnetLOGGING = logging.getLogger(__name__)@torch.inference_mode()def make_image_controlnet(image: np.ndarray,54 unmodified linesList[Image.Image]: list of generated images"""pipe = get_inpainting_pipeline()mask_image = Image.fromarray((mask_image * 255).astype(np.uint8))mask_image_postproc = convolution(mask_image)flush()st.success(f"{pipe.queue_size} images in the queue, can take up to {(pipe.queue_size+1) * 10} seconds")generated_image = pipe(image=image,mask_image=mask_image,prompt=positive_prompt,negative_prompt=negative_prompt,num_inference_steps=20,2 unmodified lines).images[0]generated_image = postprocess_image_masking(generated_image, image, mask_image_postproc)return generated_image
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126import loggingfrom typing import List, Tuple, Dict
import streamlit as stimport torchimport gcimport timeimport numpy as npfrom PIL import Imagefrom time import perf_counterfrom contextlib import contextmanagerfrom scipy.signal import fftconvolvefrom PIL import ImageFilter
from diffusers import ControlNetModel, UniPCMultistepSchedulerfrom diffusers import StableDiffusionInpaintPipeline
from config import WIDTH, HEIGHTfrom stable_diffusion_controlnet_inpaint_img2img import StableDiffusionControlNetInpaintImg2ImgPipelinefrom helpers import flush
LOGGING = logging.getLogger(__name__)
class ControlNetPipeline: def __init__(self): self.in_use = False self.controlnet = ControlNetModel.from_pretrained( "BertChristiaens/controlnet-seg-room", torch_dtype=torch.float16)
self.pipe = StableDiffusionControlNetInpaintImg2ImgPipeline.from_pretrained( "runwayml/stable-diffusion-inpainting", controlnet=self.controlnet, safety_checker=None, torch_dtype=torch.float16 )
self.pipe.scheduler = UniPCMultistepScheduler.from_config(self.pipe.scheduler.config) self.pipe.enable_xformers_memory_efficient_attention() self.pipe = self.pipe.to("cuda") self.waiting_queue = [] self.count = 0 @property def queue_size(self): return len(self.waiting_queue) def __call__(self, **kwargs): self.count += 1 number = self.count
self.waiting_queue.append(number) # wait until the next number in the queue is the current number while self.waiting_queue[0] != number: print(f"Wait for your turn {number} in queue {self.waiting_queue}") time.sleep(0.5) pass
# it's your turn, so remove the number from the queue # and call the function print("It's the turn of", self.count) results = self.pipe(**kwargs) self.waiting_queue.pop(0) flush() return results class SDPipeline: def __init__(self): self.pipe = StableDiffusionInpaintPipeline.from_pretrained( "stabilityai/stable-diffusion-2-inpainting", torch_dtype=torch.float16, safety_checker=None, )
self.pipe.enable_xformers_memory_efficient_attention() self.pipe = self.pipe.to("cuda") self.waiting_queue = [] self.count = 0 @property def queue_size(self): return len(self.waiting_queue) def __call__(self, **kwargs): self.count += 1 number = self.count
self.waiting_queue.append(number) # wait until the next number in the queue is the current number while self.waiting_queue[0] != number: print(f"Wait for your turn {number} in queue {self.waiting_queue}") time.sleep(0.5) pass
# it's your turn, so remove the number from the queue # and call the function print("It's the turn of", self.count) results = self.pipe(**kwargs) self.waiting_queue.pop(0) flush() return results
@st.experimental_singleton(max_entries=5)def get_controlnet(): """Method to load the controlnet model Returns: ControlNetModel: controlnet model """ pipe = ControlNetPipeline() return pipe
@st.experimental_singleton(max_entries=5)def get_inpainting_pipeline(): """Method to load the inpainting pipeline Returns: StableDiffusionInpaintPipeline: inpainting pipeline """ pipe = SDPipeline() return pipe12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455import loggingfrom typing import List, Tuple, Dict
import streamlit as stimport torchimport gcimport numpy as npfrom PIL import Image
from transformers import AutoImageProcessor, UperNetForSemanticSegmentation
from palette import ade_palette
LOGGING = logging.getLogger(__name__)
def flush(): gc.collect() torch.cuda.empty_cache()
@st.experimental_singleton(max_entries=5)def get_segmentation_pipeline() -> Tuple[AutoImageProcessor, UperNetForSemanticSegmentation]: """Method to load the segmentation pipeline Returns: Tuple[AutoImageProcessor, UperNetForSemanticSegmentation]: segmentation pipeline """ image_processor = AutoImageProcessor.from_pretrained("openmmlab/upernet-convnext-small") image_segmentor = UperNetForSemanticSegmentation.from_pretrained( "openmmlab/upernet-convnext-small") return image_processor, image_segmentor
@torch.inference_mode()@torch.autocast('cuda')def segment_image(image: Image) -> Image: """Method to segment image Args: image (Image): input image Returns: Image: segmented image """ image_processor, image_segmentor = get_segmentation_pipeline() pixel_values = image_processor(image, return_tensors="pt").pixel_values with torch.no_grad(): outputs = image_segmentor(pixel_values)
seg = image_processor.post_process_semantic_segmentation( outputs, target_sizes=[image.size[::-1]])[0] color_seg = np.zeros((seg.shape[0], seg.shape[1], 3), dtype=np.uint8) palette = np.array(ade_palette()) for label, color in enumerate(palette): color_seg[seg == label, :] = color color_seg = color_seg.astype(np.uint8) seg_image = Image.fromarray(color_seg).convert('RGB') return seg_imageapp.py+2-1
helpers.pyAdded+46
models.py+5-187
pipelines.pyAdded+126
segmentation.pyAdded+55