CoolFace
Apppublic

ginipick/chmodel

sourceHugging Faceupdated 2y agoView on Hugging Face
0likes
app.py132 linesDownload Raw Back to root
1import gradio as gr2from urllib.parse import urlparse3import requests4import time5import os6 7from utils.gradio_helpers import parse_outputs, process_outputs8 9names = ['prompt', 'negative_prompt', 'subject', 'number_of_outputs', 'number_of_images_per_pose', 'randomise_poses', 'output_format', 'output_quality', 'seed']10 11def predict(request: gr.Request, *args, progress=gr.Progress(track_tqdm=True)):12    headers = {'Content-Type': 'application/json'}13 14    payload = {"input": {}}15    16    17    base_url = "http://0.0.0.0:7860"18    for i, key in enumerate(names):19        value = args[i]20        if value and (os.path.exists(str(value))):21            value = f"{base_url}/file=" + value22        if value is not None and value != "":23            payload["input"][key] = value24 25    response = requests.post("http://0.0.0.0:5000/predictions", headers=headers, json=payload)26 27    28    if response.status_code == 201:29        follow_up_url = response.json()["urls"]["get"]30        response = requests.get(follow_up_url, headers=headers)31        while response.json()["status"] != "succeeded":32            if response.json()["status"] == "failed":33                raise gr.Error("The submission failed!")34            response = requests.get(follow_up_url, headers=headers)35            time.sleep(1)36    if response.status_code == 200:37        json_response = response.json()38        #If the output component is JSON return the entire output response 39        if(outputs[0].get_config()["name"] == "json"):40            return json_response["output"]41        predict_outputs = parse_outputs(json_response["output"])42        processed_outputs = process_outputs(predict_outputs)        43        return tuple(processed_outputs) if len(processed_outputs) > 1 else processed_outputs[0]44    else:45        if(response.status_code == 409):46            raise gr.Error(f"Sorry, the Cog image is still processing. Try again in a bit.")47        raise gr.Error(f"The submission failed! Error: {response.status_code}")48 49title = "Demo for consistent-character cog image by fofr"50description = "얼굴 유지 + 프롬프트로 이미지 생성"51 52css="""53#col-container{54    margin: 0 auto;55    max-width: 1400px;56    text-align: left;57}58"""59with gr.Blocks(css=css) as app:60    with gr.Column(elem_id="col-container"):61        gr.HTML(f"""62        <h2 style="text-align: center;'캐릭터 이미지'63        <p style="text-align: center;">{description}</p>64        """)65 66        with gr.Row():67            with gr.Column(scale=1):68                prompt = gr.Textbox(69                    label="Prompt", info='''Describe the subject. Include clothes and hairstyle for more consistency.'''70                )71        72                subject = gr.Image(73                    label="Subject", type="filepath"74                )75 76                submit_btn = gr.Button("Submit")77 78                with gr.Accordion(label="Advanced Settings", open=False):79                    80                    negative_prompt = gr.Textbox(81                        label="Negative Prompt", info='''Things you do not want to see in your image''',82                        value="text, watermark, lowres, low quality, worst quality, deformed, glitch, low contrast, noisy, saturation, blurry"83                    )84 85                    with gr.Row():86 87                        number_of_outputs = gr.Slider(88                            label="Number Of Outputs", info='''The number of images to generate.''', value=2,89                            minimum=1, maximum=4, step=1,90                        )91                        92                        number_of_images_per_pose = gr.Slider(93                            label="Number Of Images Per Pose", info='''The number of images to generate for each pose.''', value=1,94                            minimum=1, maximum=4, step=1,95                        )96 97                    with gr.Row():98                        99                        randomise_poses = gr.Checkbox(100                            label="Randomise Poses", info='''Randomise the poses used.''', value=True101                        )102                        103                        output_format = gr.Dropdown(104                            choices=['webp', 'jpg', 'png'], label="output_format", info='''Format of the output images''', value="webp"105                        )106                    107                    with gr.Row():108                        109                        output_quality = gr.Number(110                            label="Output Quality", info='''Quality of the output images, from 0 to 100. 100 is best quality, 0 is lowest quality.''', value=80111                        )112                        113                        seed = gr.Number(114                            label="Seed", info='''Set a seed for reproducibility. Random by default.''', value=None115                        )116 117            with gr.Column(scale=1.5):118                consistent_results = gr.Gallery(label="Consistent Results")119 120    inputs = [prompt, negative_prompt, subject, number_of_outputs, number_of_images_per_pose, randomise_poses, output_format, output_quality, seed]121    outputs = [consistent_results]122 123    submit_btn.click(124        fn = predict,125        inputs = inputs,126        outputs = outputs,127        show_api = False128    )129 130app.queue(max_size=12, api_open=False).launch(share=False, show_api=False, show_error=True)131 132