Spaces:
Runtime error
Runtime error
commit
Browse filesFiles changed (2)
- app.py+117-30
- requirements.txt+2-1
7 unmodified lines89101112133 unmodified lines171819202122232425262728293031323315 unmodified lines495051525354552 unmodified lines58596061626319 unmodified lines838485868788899091925 unmodified lines989910010110210310410510610710810911011111211311411511611711811912012112212318 unmodified lines1421431441451461471481491501511521531541551561571581591601611625 unmodified lines1681691701711721731741751761771781791801811821831841851861871881891907 unmodified linesimport torchvision.transforms as transformsfrom PIL import Imageclass Examples(gr.helpers.Examples):def __init__(self, *args, cached_folder=None, **kwargs):super().__init__(*args, **kwargs, _initiated_directly=False)3 unmodified linesself.create()HF_TOKEN = os.environ.get('HF_KEY')client = Client("Canyu/Diception",max_workers=3,hf_token=HF_TOKEN)map_prompt = {'depth': '[[image2depth]]','normal': '[[image2normal]]','pose': '[[image2pose]]','entity segmentation': '[[image2panoptic coarse]]','point segmentation': '[[image2segmentation]]','semantic segmentation': '[[image2semantic]]',15 unmodified lines# 返回加载的参数内容return additional_paramsdef process_image_check(path_input, prompt):if path_input is None:raise gr.Error("Missing image in the left pane: please upload an image first."2 unmodified linesraise gr.Error("At least 1 prediction type is needed.")19 unmodified linesreturn inputsdef inf(image_path, prompt):print(image_path)print(prompt)inputs = process_image_4(image_path, prompt)# return Nonereturn client.predict(image=handle_file(image_path),5 unmodified linesreturn None, Nonedef run_demo_server():options = ['depth', 'normal', 'entity', 'pose']gradio_theme = gr.themes.Default()with gr.Blocks(theme=gradio_theme,title="Matting",) as demo:with gr.Row():gr.Markdown("# Diception Demo")with gr.Row():gr.Markdown("### All results are generated using the same single model. To facilitate input processing, we separate point-prompted segmentation and semantic segmentation, as they require input points and segmentation targets.")with gr.Row():checkbox_group = gr.CheckboxGroup(choices=options, label="Select options:")with gr.Row():with gr.Column():matting_image_input = gr.Image(label="Input Image",type="filepath",)with gr.Row():matting_image_submit_btn = gr.Button(value="Estimate Matting", variant="primary"18 unmodified linesimg_clear_button.click(clear_cache, outputs=[matting_image_input, matting_image_output])matting_image_submit_btn.click(fn=process_image_check,inputs=[matting_image_input, checkbox_group],outputs=None,preprocess=False,queue=False,).success(# fn=process_pipe_matting,fn=inf,inputs=[matting_image_input,checkbox_group],outputs=[matting_image_output],concurrency_limit=1,)5 unmodified lines),inputs=[],outputs=[matting_image_input,matting_image_output,],queue=False,)gr.Examples(fn=inf,examples=[["assets/person.jpg", ['depth', 'normal', 'entity', 'pose']]],inputs=[matting_image_input, checkbox_group],outputs=[matting_image_output],cache_examples=True,# cache_examples=False,# cached_folder="cache_dir",)demo.queue(api_open=False,7 unmodified lines89101112131415163 unmodified lines202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717215 unmodified lines8889909192939495969798991002 unmodified lines10310410510610710810911011111211311411511611711811912012112212312412519 unmodified lines1451461471481491501511525 unmodified lines15815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019118 unmodified lines2102112122132142152162172182192202212222232242252262275 unmodified lines2332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762777 unmodified linesimport torchvision.transforms as transformsfrom PIL import Imageimport cv2import numpy as npclass Examples(gr.helpers.Examples):def __init__(self, *args, cached_folder=None, **kwargs):super().__init__(*args, **kwargs, _initiated_directly=False)3 unmodified linesself.create()# user click the image to get points, and show the points on the imagedef get_point(img, sel_pix, evt: gr.SelectData):if len(sel_pix) < 5:sel_pix.append((evt.index, 1)) # default foreground_pointimg = cv2.imread(img)img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)# draw pointsfor point, label in sel_pix:cv2.drawMarker(img, point, colors[label], markerType=markers[label], markerSize=20, thickness=5)# if img[..., 0][0, 0] == img[..., 2][0, 0]: # BGR to RGB# img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)print(sel_pix)return img, sel_pix# undo the selected pointdef undo_points(orig_img, sel_pix):if isinstance(orig_img, int): # if orig_img is int, the image if select from examplestemp = cv2.imread(image_examples[orig_img][0])temp = cv2.cvtColor(temp, cv2.COLOR_BGR2RGB)else:temp = cv2.imread(orig_img)temp = cv2.cvtColor(temp, cv2.COLOR_BGR2RGB)# draw pointsif len(sel_pix) != 0:sel_pix.pop()for point, label in sel_pix:cv2.drawMarker(temp, point, colors[label], markerType=markers[label], markerSize=20, thickness=5)if temp[..., 0][0, 0] == temp[..., 2][0, 0]: # BGR to RGBtemp = cv2.cvtColor(temp, cv2.COLOR_BGR2RGB)return temp, sel_pix# HF_TOKEN = os.environ.get('HF_KEY')# client = Client("Canyu/Diception",# max_workers=3,# hf_token=HF_TOKEN)colors = [(255, 0, 0), (0, 255, 0)]markers = [1, 5]map_prompt = {'depth': '[[image2depth]]','normal': '[[image2normal]]','human pose': '[[image2pose]]','entity segmentation': '[[image2panoptic coarse]]','point segmentation': '[[image2segmentation]]','semantic segmentation': '[[image2semantic]]',15 unmodified lines# 返回加载的参数内容return additional_paramsdef process_image_check(path_input, prompt, sel_points, semantic):print('=========== PROCESS IMAGE CHECK ===========')print(f"Image Path: {path_input}")print(f"Prompt: {prompt}")print(f"Selected Points (before processing): {sel_points}")print(f"Semantic Input: {semantic}")print('===========================================')if path_input is None:raise gr.Error("Missing image in the left pane: please upload an image first."2 unmodified linesraise gr.Error("At least 1 prediction type is needed.")if 'point segmentation' in prompt and len(sel_points) == 0:raise gr.Error("At least 1 point is needed.")if 'point segmentation' not in prompt and len(sel_points) != 0:raise gr.Error("You must select 'point segmentation' when performing point segmentation.")if 'semantic segmentation' in prompt and semantic == None:raise gr.Error("Target category is needed.")if 'semantic segmentation' not in prompt and semantic != None:raise gr.Error("You must select 'semantic segmentation' when performing semantic segmentation.")19 unmodified linesreturn inputsdef inf(image_path, prompt, sel_points, semantic):inputs = process_image_4(image_path, prompt, sel_points, semantic)# return Nonereturn client.predict(image=handle_file(image_path),5 unmodified linesreturn None, Nonedef run_demo_server():options = ['depth', 'normal', 'entity segmentation', 'human pose', 'point segmentation', 'semantic segmentation']gradio_theme = gr.themes.Default()with gr.Blocks(theme=gradio_theme,title="Matting",) as demo:selected_points = gr.State([]) # store pointsoriginal_image = gr.State(value=None) # store original image without points, default Nonewith gr.Row():gr.Markdown("# Diception Demo")with gr.Row():gr.Markdown("### All results are generated using the same single model. To facilitate input processing, we separate point-prompted segmentation and semantic segmentation, as they require input points and segmentation targets.")with gr.Row():checkbox_group = gr.CheckboxGroup(choices=options, label="Select options:")with gr.Row():semantic_input = gr.Textbox(label="Category Name (for semantic segmentation only, in COCO)", placeholder="e.g. person/cat/dog/elephant......")with gr.Row():with gr.Column():input_image = gr.Image(label="Input Image",type="filepath",)with gr.Column():with gr.Row():gr.Markdown('You can click on the image to select points prompt. At most 5 point.')undo_button = gr.Button('Undo point')with gr.Row():matting_image_submit_btn = gr.Button(value="Estimate Matting", variant="primary"18 unmodified linesimg_clear_button.click(clear_cache, outputs=[input_image, matting_image_output])matting_image_submit_btn.click(fn=process_image_check,inputs=[input_image, checkbox_group, selected_points, semantic_input],outputs=None,preprocess=False,queue=False,).success(# fn=process_pipe_matting,fn=inf,inputs=[input_image, checkbox_group, selected_points, semantic_input],outputs=[matting_image_output],concurrency_limit=1,)5 unmodified lines),inputs=[],outputs=[input_image,matting_image_output,],queue=False,)# once user upload an image, the original image is stored in `original_image`def store_img(img):return img, [] # when new image is uploaded, `selected_points` should be emptyinput_image.upload(store_img,[input_image],[original_image, selected_points])input_image.select(get_point,[input_image, selected_points],[input_image, selected_points],)undo_button.click(undo_points,[original_image, selected_points],[input_image, selected_points])# gr.Examples(# fn=inf,# examples=[# ["assets/person.jpg", ['depth', 'normal', 'entity segmentation', 'pose']]# ],# inputs=[input_image, checkbox_group],# outputs=[matting_image_output],# cache_examples=True,# # cache_examples=False,# # cached_folder="cache_dir",# )demo.queue(api_open=False,
4 unmodified lines56784 unmodified linestransformersxformerssentencepiecetorchvision4 unmodified lines567894 unmodified linestransformersxformerssentencepiecetorchvisionopencv-python
app.py+117-30
requirements.txt+2-1