""" 实现web界面 """ from pathlib import Path import gradio as gr from detect import detect from util import get_all_weights app_introduce = """ # CycleGAN 功能:上传本地文件、选择转换风格 """ css = """ # :root{ # --block-background-fill: #f3f3f3; # } footer{ display:none!important; } """ demo = gr.Blocks( # theme=gr.themes.Soft(), css=css ) def add_img(img): imgs = [] for style in get_all_weights(): fake_img = detect(img, style=style) imgs.append(fake_img) return imgs def tab1(label="上传单张图片"): default_img_paths = [ [Path.cwd().joinpath("./imgs/horse.jpg"), "horse2zebra"], [Path.cwd().joinpath("./imgs/monet.jpg"), "monet2photo"], ] with gr.Tab(label): with gr.Row(): with gr.Column(): img = gr.Image(type="pil", label="选择需要进行风格转换的图片") style = gr.Dropdown(choices=get_all_weights(), label="转换的风格") detect_btn = gr.Button("♻️风格转换") with gr.Column(): out_img = gr.Image(label="风格图") detect_btn.click(fn=detect, inputs=[img, style], outputs=[out_img]) gr.Examples(default_img_paths, inputs=[img, style]) def tab2(label="单图多风格试转换"): with gr.Tab(label): with gr.Row(): with gr.Column(scale=1): img = gr.Image(type="pil", label="选择需要进行风格转换的图片") gr.Markdown("上传一张图片,会将所有风格推理一遍。") btn = gr.Button("♻️风格转换") with gr.Column(scale=2): gallery = gr.Gallery( label="风格图", elem_id="gallery", ).style(grid=[3], height="auto") btn.click(fn=add_img, inputs=[img], outputs=gallery) def tab3(label="参数设置"): from detect import opt with gr.Tab(label): with gr.Column(): for k, v in sorted(vars(opt).items()): if type(v) == bool: gr.Checkbox(label=k, value=v) elif type(v) == (int or float): gr.Number(label=k, value=v) elif type(v) == list: gr.CheckboxGroup(label=k, value=v) else: gr.Textbox(label=k, value=v) with demo: gr.Markdown(app_introduce) tab1() tab2() tab3() if __name__ == "__main__": demo.launch(share=True) # 如果不以`demo`命名,`gradio app.py`会报错`Error loading ASGI app. Attribute "demo.app" not found in module "app".` # 注意gradio库的reload.py的头信息 $ gradio app.py my_demo, to use variable names other than "demo" # my_demo 是定义的变量。离谱o(╥﹏╥)o