nyanko7 commited on
Commit
7f467ad
1 Parent(s): 60dbf82

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +115 -0
app.py ADDED
@@ -0,0 +1,115 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import numpy as np
3
+ import time
4
+ import requests
5
+ import json
6
+ import os
7
+ import tempfile
8
+ import logging
9
+ from PIL import Image
10
+ from io import BytesIO
11
+
12
+ odnapi = os.getenv("odnapi_url")
13
+ fetapi = os.getenv("fetapi_url")
14
+ auth_token = os.getenv("auth_token")
15
+
16
+ # Setup a logger
17
+ logging.basicConfig(level=logging.INFO)
18
+ logger = logging.getLogger(__name__)
19
+
20
+ def download_image_from_url(url):
21
+ response = requests.get(url)
22
+ img = Image.open(BytesIO(response.content))
23
+ tmp = tempfile.NamedTemporaryFile(delete=False)
24
+ img.save(tmp, 'PNG')
25
+ tmp.close()
26
+ return tmp.name
27
+
28
+ def fetch_image(url):
29
+ try:
30
+ response = requests.get(url)
31
+ return Image.open(BytesIO(response.content))
32
+ except requests.exceptions.RequestException as e:
33
+ logger.error(f"Failed to fetch image")
34
+ raise
35
+
36
+ def split_image(img):
37
+ width, height = img.size
38
+ width_cut = width // 2
39
+ height_cut = height // 2
40
+ return [
41
+ img.crop((0, 0, width_cut, height_cut)),
42
+ img.crop((width_cut, 0, width, height_cut)),
43
+ img.crop((0, height_cut, width_cut, height)),
44
+ img.crop((width_cut, height_cut, width, height))
45
+ ]
46
+
47
+ def save_image(img, suffix='.png'):
48
+ with tempfile.NamedTemporaryFile(delete=False, suffix=suffix) as tmp:
49
+ img.save(tmp, 'PNG')
50
+ return tmp.name
51
+
52
+ def download_and_split_image(url):
53
+ img = fetch_image(url)
54
+ images = split_image(img)
55
+ return [save_image(i) for i in images]
56
+
57
+ def niji_api(prompt):
58
+ try:
59
+ response = requests.post(fetapi, headers={'Content-Type': 'application/json'}, data=json.dumps({'msg': prompt}))
60
+ response.raise_for_status() # Check for HTTP errors.
61
+ except requests.exceptions.RequestException as e:
62
+ logger.error(f"Failed to make POST request")
63
+ raise ValueError("Invalid Response")
64
+ data = response.json()
65
+ message_id = data['messageId']
66
+ progress = 0
67
+ while progress < 100:
68
+ try:
69
+ response = requests.get(f'{odnapi}/message/{message_id}', headers={'Authorization': auth_token})
70
+ response.raise_for_status()
71
+ except requests.exceptions.RequestException as e:
72
+ logger.warning(f"Failure in getting message response")
73
+ continue
74
+ data = response.json()
75
+ progress = data.get('progress', 0)
76
+ if progress_image_url:= data.get('progressImageUrl'):
77
+ yield [(img, f"{progress}% done") for img in download_and_split_image(progress_image_url)]
78
+ time.sleep(1)
79
+ # Process the final image urls
80
+ image_urls = data['response']['imageUrls']
81
+ yield [(download_image_from_url(iurl), f"image {idx}/4") for idx, iurl in enumerate(image_urls)]
82
+
83
+ with gr.Blocks() as demo:
84
+ gr.HTML('''
85
+ <div style="text-align: center; max-width: 650px; margin: 0 auto;">
86
+ <div style="
87
+ display: inline-flex;
88
+ gap: 0.8rem;
89
+ font-size: 1.75rem;
90
+ justify-content: center;
91
+ margin-bottom: 10px;
92
+ ">
93
+ <h1 style="font-weight: 900; align-items: center; margin-bottom: 7px; margin-top: 20px;">
94
+ MidJourney / NijiJourney Playground 🎨
95
+ </h1>
96
+ </div>
97
+ <div>
98
+ <p style="align-items: center; margin-bottom: 7px;">
99
+ Demo for the <a href="https://MidJourney.com/" target="_blank">MidJourney</a>, add a text prompt for what you want to draw
100
+ </div>
101
+ </div>
102
+ ''')
103
+ with gr.Column(variant="panel"):
104
+ with gr.Row():
105
+ text = gr.Textbox(
106
+ label="Enter your prompt",
107
+ value="1girl,long hair,looking at viewer,kawaii,serafuku --s 250 --niji 5",
108
+ max_lines=1,
109
+ container=False,
110
+ )
111
+ btn = gr.Button("Generate image", scale=0)
112
+ gallery = gr.Gallery(label="Generated images", show_label=False, elem_id="gallery", height="4096")
113
+ btn.click(niji_api, text, gallery)
114
+
115
+ demo.launch(debug=True, enable_queue=True)