manangarg commited on
Commit
855805d
1 Parent(s): 3f1faef

created app.py

Browse files
Files changed (1) hide show
  1. app.py +69 -0
app.py ADDED
@@ -0,0 +1,69 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import io
2
+ from PIL import Image
3
+ from IPython.display import Image as IPImage
4
+ import requests
5
+ import json
6
+ import gradio as gr
7
+
8
+ model_id_list = ['stablediffusionapi/dreamshaper-v7', 'runwayml/stable-diffusion-v1-5', 'stabilityai/stable-diffusion-2-1', 'digiplay/DreamShaper_7', 'hakurei/waifu-diffusion']
9
+
10
+ #Text-to-image endpoint
11
+ def get_completion(inputs, model_id, hf_api_key, parameters=None):
12
+ ENDPOINT_URL='https://api-inference.huggingface.co/models/{}'.format(model_id)
13
+ headers = {
14
+ "Authorization": f"Bearer {hf_api_key}",
15
+ "Content-Type": "application/json"
16
+ }
17
+ data = { "inputs": inputs }
18
+ if parameters is not None:
19
+ data.update({"parameters": parameters})
20
+ response = requests.request("POST",
21
+ ENDPOINT_URL,
22
+ headers=headers,
23
+ data=json.dumps(data))
24
+ if 'error' in str(response.content):
25
+ return None
26
+ else:
27
+ return IPImage(response.content)
28
+
29
+ # A helper function to convert the bytes string into PIL image to send to API
30
+ def bytes_to_pil_image(img_bytes):
31
+ byte_stream = io.BytesIO(img_bytes)
32
+ pil_image = Image.open(byte_stream)
33
+ return pil_image
34
+
35
+ def generate(hf_api_key, prompt):
36
+ outputs = []
37
+ for model_id in model_id_list:
38
+ output = get_completion(prompt, model_id, hf_api_key)
39
+ if output == None:
40
+ outputs.append(output)
41
+ else:
42
+ pil_image = bytes_to_pil_image(output.data) # Use the corrected function here
43
+ outputs.append(pil_image)
44
+ return outputs
45
+
46
+ with gr.Blocks() as demo:
47
+ gr.Markdown("# Image Generation")
48
+ with gr.Row():
49
+ hf_api_key = gr.Textbox(label="API Key")
50
+ with gr.Row():
51
+ with gr.Column(scale=4):
52
+ prompt = gr.Textbox(label="Your prompt") #Give prompt some real estate
53
+ with gr.Column(scale=1, min_width=50):
54
+ btn = gr.Button("Submit") #Submit button side by side!
55
+ with gr.Row():
56
+ with gr.Column():
57
+ output1 = gr.Image(label= model_id_list[0])
58
+ with gr.Column():
59
+ output2 = gr.Image(label= model_id_list[1])
60
+ with gr.Row():
61
+ with gr.Column():
62
+ output3 = gr.Image(label= model_id_list[2])
63
+ with gr.Column():
64
+ output4 = gr.Image(label= model_id_list[3])
65
+ with gr.Column():
66
+ output5 = gr.Image(label= model_id_list[4])
67
+ btn.click(fn=generate, inputs=[hf_api_key, prompt], outputs=[output1,output2,output3,output4,output5])
68
+ gr.close_all()
69
+ demo.launch()