R87/consistent-character
0
1import gradio as gr2from urllib.parse import urlparse3import requests4import time5import os6import re7from gradio_client import Client8 9is_shared_ui = True if "fffiloni/consistent-character" in os.environ['SPACE_ID'] else False10def safety_check(user_prompt, token):11 12 client = Client("fffiloni/safety-checker-bot", hf_token=token)13 response = client.predict(14 source_space="consistent-character space",15 user_prompt=user_prompt,16 api_name="/infer"17 )18 print(response)19 20 return response21 22from utils.gradio_helpers import parse_outputs, process_outputs23 24names = ['prompt', 'negative_prompt', 'subject', 'number_of_outputs', 'number_of_images_per_pose', 'randomise_poses', 'output_format', 'output_quality', 'seed']25 26def predict(request: gr.Request, *args, progress=gr.Progress(track_tqdm=True)):27 print(f"""28 —/n29 {args[0]}30 """)31 if args[0] == '' or args[0] is None:32 raise gr.Error(f"You forgot to provide a prompt.")33 34 try:35 if is_shared_ui:36 hf_token = os.environ.get("HF_TOKEN")37 38 is_safe = safety_check(args[0], hf_token)39 print(is_safe)40 41 match = re.search(r'\bYes\b', is_safe)42 43 if match:44 status = 'Yes'45 else:46 status = None47 else:48 status = None49 50 if status == "Yes" :51 raise gr.Error("Do not ask for such things.")52 else:53 54 headers = {'Content-Type': 'application/json'}55 56 payload = {"input": {}}57 58 59 base_url = "http://0.0.0.0:7860"60 for i, key in enumerate(names):61 value = args[i]62 if value and (os.path.exists(str(value))):63 value = f"{base_url}/gradio_api/file=" + value64 if value is not None and value != "":65 payload["input"][key] = value66 67 response = requests.post("http://0.0.0.0:5000/predictions", headers=headers, json=payload)68 69 70 if response.status_code == 201:71 follow_up_url = response.json()["urls"]["get"]72 response = requests.get(follow_up_url, headers=headers)73 while response.json()["status"] != "succeeded":74 if response.json()["status"] == "failed":75 raise gr.Error("The submission failed!")76 response = requests.get(follow_up_url, headers=headers)77 time.sleep(1)78 if response.status_code == 200:79 json_response = response.json()80 #If the output component is JSON return the entire output response 81 if(outputs[0].get_config()["name"] == "json"):82 return json_response["output"]83 predict_outputs = parse_outputs(json_response["output"])84 processed_outputs = process_outputs(predict_outputs) 85 return tuple(processed_outputs) if len(processed_outputs) > 1 else processed_outputs[0]86 else:87 if(response.status_code == 409):88 raise gr.Error(f"Sorry, the Cog image is still processing. Try again in a bit.")89 raise gr.Error(f"The submission failed! Error: {response.status_code}")90 91 except Exception as e:92 # Handle any other type of error93 raise gr.Error(f"An error occurred: {e}")94 95title = "Demo for consistent-character cog image by fofr"96description = "Create images of a given character in different poses • running cog image by fofr"97 98css="""99#col-container{100 margin: 0 auto;101 max-width: 1400px;102 text-align: left;103}104"""105with gr.Blocks(css=css) as app:106 with gr.Column(elem_id="col-container"):107 gr.Markdown("# Consistent Character Workflow")108 gr.Markdown("### Create images of a given character in different poses • running cog image by fofr")109 110 gr.HTML("""111 <div style="display:flex;column-gap:4px;">112 <a href="https://huggingface.co/spaces/fffiloni/consistent-character?duplicate=true">113 <img src="https://huggingface.co/datasets/huggingface/badges/resolve/main/duplicate-this-space-sm.svg" alt="Duplicate this Space">114 </a>115 <p> to skip the queue and use custom prompts116 </div>117 """)118 119 with gr.Row():120 with gr.Column(scale=2):121 if is_shared_ui:122 prompt = gr.Textbox(123 label="Prompt", info='''Duplicate the space to you personal account for custom prompt''',124 value="a person, darkblue suit, black tie, white pocket",125 interactive=False126 )127 else:128 prompt = gr.Textbox(129 label="Prompt", info='''Describe the subject. Include clothes and hairstyle for more consistency.''',130 value="a person, darkblue suit, black tie, white pocket",131 interactive=True132 )133 134 subject = gr.Image(135 label="Subject", type="filepath"136 )137 138 submit_btn = gr.Button("Submit")139 140 with gr.Accordion(label="Advanced Settings", open=False):141 142 negative_prompt = gr.Textbox(143 label="Negative Prompt", info='''Things you do not want to see in your image''',144 value="text, watermark, lowres, low quality, worst quality, deformed, glitch, low contrast, noisy, saturation, blurry"145 )146 147 with gr.Row():148 149 number_of_outputs = gr.Slider(150 label="Number Of Outputs", info='''The number of images to generate.''', value=4,151 minimum=1, maximum=4, step=1,152 )153 154 number_of_images_per_pose = gr.Slider(155 label="Number Of Images Per Pose", info='''The number of images to generate for each pose.''', value=1,156 minimum=1, maximum=4, step=1,157 )158 159 with gr.Row():160 161 randomise_poses = gr.Checkbox(162 label="Randomise Poses", info='''Randomise the poses used.''', value=True163 )164 165 output_format = gr.Dropdown(166 choices=['webp', 'jpg', 'png'], label="output_format", info='''Format of the output images''', value="webp"167 )168 169 with gr.Row():170 171 output_quality = gr.Number(172 label="Output Quality", info='''Quality of the output images, from 0 to 100. 100 is best quality, 0 is lowest quality.''', value=80173 )174 175 seed = gr.Number(176 label="Seed", info='''Set a seed for reproducibility. Random by default.''', value=None177 )178 179 with gr.Column(scale=3):180 consistent_results = gr.Gallery(label="Consistent Results")181 182 inputs = [prompt, negative_prompt, subject, number_of_outputs, number_of_images_per_pose, randomise_poses, output_format, output_quality, seed]183 outputs = [consistent_results]184 185 submit_btn.click(186 fn = predict,187 inputs = inputs,188 outputs = outputs,189 show_api = False190 )191 192app.queue(max_size=12, api_open=False).launch(share=False, show_api=False, show_error=True)193 194 