craftgamesnetwork/f1t
0
1import gradio as gr2from urllib.parse import urlparse3import requests4import time5import os6 7from utils.gradio_helpers import parse_outputs, process_outputs8 9inputs = []10inputs.append(gr.Image(11 label="Target Image", type="filepath"12))13 14inputs.append(gr.Image(15 label="Swap Image", type="filepath"16))17 18names = ['target_image', 'swap_image']19 20outputs = []21outputs.append(gr.Image())22 23expected_outputs = len(outputs)24def predict(request: gr.Request, *args, progress=gr.Progress(track_tqdm=True)):25 headers = {'Content-Type': 'application/json'}26 27 payload = {"input": {}}28 29 30 base_url = "http://0.0.0.0:7860"31 for i, key in enumerate(names):32 value = args[i]33 if value and (os.path.exists(str(value))):34 value = f"{base_url}/file=" + value35 if value is not None and value != "":36 payload["input"][key] = value37 38 response = requests.post("http://0.0.0.0:5000/predictions", headers=headers, json=payload)39 40 41 if response.status_code == 201:42 follow_up_url = response.json()["urls"]["get"]43 response = requests.get(follow_up_url, headers=headers)44 while response.json()["status"] != "succeeded":45 if response.json()["status"] == "failed":46 raise gr.Error("The submission failed!")47 response = requests.get(follow_up_url, headers=headers)48 time.sleep(1)49 if response.status_code == 200:50 json_response = response.json()51 #If the output component is JSON return the entire output response 52 if(outputs[0].get_config()["name"] == "json"):53 return json_response["output"]54 predict_outputs = parse_outputs(json_response["output"])55 processed_outputs = process_outputs(predict_outputs)56 difference_outputs = expected_outputs - len(processed_outputs)57 # If less outputs than expected, hide the extra ones58 if difference_outputs > 0:59 extra_outputs = [gr.update(visible=False)] * difference_outputs60 processed_outputs.extend(extra_outputs)61 # If more outputs than expected, cap the outputs to the expected number62 elif difference_outputs < 0:63 processed_outputs = processed_outputs[:difference_outputs]64 65 return tuple(processed_outputs) if len(processed_outputs) > 1 else processed_outputs[0]66 else:67 if(response.status_code == 409):68 raise gr.Error(f"Sorry, the Cog image is still processing. Try again in a bit.")69 raise gr.Error(f"The submission failed! Error: {response.status_code}")70 71title = "Demo for face-swap cog image by omniedgeio"72model_description = "Face Swap"73 74app = gr.Interface(75 fn=predict,76 inputs=inputs,77 outputs=outputs,78 title=title,79 description=model_description,80 allow_flagging="never",81)82app.launch(share=True)