rollback to last stable
Browse files2 unmodified lines3456789101112138 unmodified lines2223242526272829303178 unmodified lines1101111121131141151161171181 unmodified line1201211221231241251263 unmodified lines1301311321331341351361371381391401417 unmodified lines14915015115215315415513 unmodified lines1691701711721731741757 unmodified lines1831841851861871881891901912 unmodified linesimport torchfrom loadimg import load_imgfrom torchvision import transformsfrom transformers import AutoModelForImageSegmentationfrom diffusers import FluxFillPipelinefrom PIL import Image, ImageOpstorch.set_float32_matmul_precision(["high", "highest"][0])birefnet = AutoModelForImageSegmentation.from_pretrained("ZhengPeng7/BiRefNet", trust_remote_code=True8 unmodified lines])pipe = FluxFillPipeline.from_pretrained("black-forest-labs/FLUX.1-Fill-dev", torch_dtype=torch.bfloat16).to("cuda")def prepare_image_and_mask(image,78 unmodified linesimage = load_img(image).convert("RGB")image_size = image.sizeinput_images = transform_image(image).unsqueeze(0).to("cuda")# Predictionwith torch.no_grad():preds = birefnet(input_images)[-1].sigmoid().cpu()pred = preds[0].squeeze()pred_pil = transforms.ToPILImage()(pred)mask = pred_pil.resize(image_size)1 unmodified linereturn image@spaces.GPUdef main(*args):api_num = args[0]args = args[1:]3 unmodified linesreturn outpaint(*args)elif api_num == 3:return inpaint(*args)rmbg_tab = gr.Interface(fn=main,inputs=[gr.Number(1, visible=False),"image",gr.Text("", label="url"),],7 unmodified linesoutpaint_tab = gr.Interface(fn=main,inputs=[gr.Number(2, visible=False),gr.Image(label="image", type="pil"),gr.Number(label="padding top"),gr.Number(label="padding bottom"),13 unmodified linesinpaint_tab = gr.Interface(fn=main,inputs=[gr.Number(3, visible=False),gr.Image(label="image", type="pil"),gr.Image(label="mask", type="pil"),gr.Text(label="prompt"),7 unmodified linesdescription="it is recommended that you use https://github.com/la-voliere/react-mask-editor when creating an image mask in JS and then inverse it before sending it to this space",)demo = gr.TabbedInterface([rmbg_tab, outpaint_tab, inpaint_tab],["remove background", "outpainting", "inpainting"],title="Utilities that require GPU",)2 unmodified lines34567891011121314151617181920212223242526272829308 unmodified lines39404142434478 unmodified lines1231241251261271281291301311321 unmodified line1341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971983 unmodified lines2022032042052062072082092102112122132142152162172182197 unmodified lines22722822923023123223313 unmodified lines2472482492502512522537 unmodified lines2612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333342 unmodified linesimport torchfrom loadimg import load_imgfrom torchvision import transformsfrom transformers import AutoModelForImageSegmentation, pipelinefrom diffusers import FluxFillPipelinefrom PIL import Image, ImageOps# from sam2.sam2_image_predictor import SAM2ImagePredictorimport numpy as npfrom simple_lama_inpainting import SimpleLamafrom contextlib import contextmanager@contextmanagerdef float32_high_matmul_precision():torch.set_float32_matmul_precision("high")try:yieldfinally:torch.set_float32_matmul_precision("highest")pipe = FluxFillPipeline.from_pretrained("black-forest-labs/FLUX.1-Fill-dev", torch_dtype=torch.bfloat16).to("cuda")birefnet = AutoModelForImageSegmentation.from_pretrained("ZhengPeng7/BiRefNet", trust_remote_code=True8 unmodified lines])def prepare_image_and_mask(image,78 unmodified linesimage = load_img(image).convert("RGB")image_size = image.sizeinput_images = transform_image(image).unsqueeze(0).to("cuda")with float32_high_matmul_precision():# Predictionwith torch.no_grad():preds = birefnet(input_images)[-1].sigmoid().cpu()pred = preds[0].squeeze()pred_pil = transforms.ToPILImage()(pred)mask = pred_pil.resize(image_size)1 unmodified linereturn image# def mask_generation(image=None, d=None):# # use bfloat16 for the entire notebook# # torch.autocast("cuda", dtype=torch.bfloat16).__enter__()# # # turn on tfloat32 for Ampere GPUs (https://pytorch.org/docs/stable/notes/cuda.html#tensorfloat-32-tf32-on-ampere-devices)# # if torch.cuda.get_device_properties(0).major >= 8:# # torch.backends.cuda.matmul.allow_tf32 = True# # torch.backends.cudnn.allow_tf32 = True# d = eval(d) # convert this to dictionary# with torch.inference_mode(), torch.autocast("cuda", dtype=torch.bfloat16):# predictor = SAM2ImagePredictor.from_pretrained("facebook/sam2.1-hiera-large")# predictor.set_image(image)# input_point = np.array(d["input_points"])# input_label = np.array(d["input_labels"])# masks, scores, logits = predictor.predict(# point_coords=input_point,# point_labels=input_label,# multimask_output=True,# )# sorted_ind = np.argsort(scores)[::-1]# masks = masks[sorted_ind]# scores = scores[sorted_ind]# logits = logits[sorted_ind]# out = []# for i in range(len(masks)):# m = Image.fromarray(masks[i] * 255).convert("L")# comp = Image.composite(image, m, m)# out.append((comp, f"image {i}"))# return outdef erase(image=None, mask=None):simple_lama = SimpleLama()image = load_img(image)mask = load_img(mask).convert("L")return simple_lama(image, mask)# Initialize Whisper modelwhisper = pipeline(task="automatic-speech-recognition",model="openai/whisper-large-v3",chunk_length_s=30,device="cuda" if torch.cuda.is_available() else "cpu",)def transcribe(audio, task="transcribe"):if audio is None:raise gr.Error("No audio file submitted!")text = whisper(audio, batch_size=8, generate_kwargs={"task": task}, return_timestamps=True)["text"]return text@spaces.GPU(duration=120)def main(*args):api_num = args[0]args = args[1:]3 unmodified linesreturn outpaint(*args)elif api_num == 3:return inpaint(*args)# elif api_num == 4:# return mask_generation(*args)elif api_num == 5:return erase(*args)elif api_num == 6:return transcribe(*args)rmbg_tab = gr.Interface(fn=main,inputs=[gr.Number(1, interactive=False),"image",gr.Text("", label="url"),],7 unmodified linesoutpaint_tab = gr.Interface(fn=main,inputs=[gr.Number(2, interactive=False),gr.Image(label="image", type="pil"),gr.Number(label="padding top"),gr.Number(label="padding bottom"),13 unmodified linesinpaint_tab = gr.Interface(fn=main,inputs=[gr.Number(3, interactive=False),gr.Image(label="image", type="pil"),gr.Image(label="mask", type="pil"),gr.Text(label="prompt"),7 unmodified linesdescription="it is recommended that you use https://github.com/la-voliere/react-mask-editor when creating an image mask in JS and then inverse it before sending it to this space",)# sam2_tab = gr.Interface(# main,# inputs=[# gr.Number(4, interactive=False),# gr.Image(type="pil"),# gr.Text(),# ],# outputs=gr.Gallery(),# examples=[# [# 4,# "./assets/truck.jpg",# '{"input_points": [[500, 375], [1125, 625]], "input_labels": [1, 0]}',# ]# ],# api_name="sam2",# cache_examples=False,# )erase_tab = gr.Interface(main,inputs=[gr.Number(5, interactive=False),gr.Image(type="pil"),gr.Image(type="pil"),],outputs=gr.Image(),examples=[[5,"./assets/rocket.png","./assets/Inpainting mask.png",]],api_name="erase",cache_examples=False,)transcribe_tab = gr.Interface(fn=main,inputs=[gr.Number(6, interactive=False),gr.Audio(type="filepath"),gr.Radio(["transcribe", "translate"], label="Task", value="transcribe"),],outputs="text",api_name="transcribe",description="Upload an audio file to extract text using Whisper Large V3",)demo = gr.TabbedInterface([rmbg_tab,outpaint_tab,inpaint_tab,# sam2_tab,erase_tab,transcribe_tab,],["remove background","outpainting","inpainting",# "sam2","erase","transcribe",],title="Utilities that require GPU",)
app.py+158-15