rayochoajr commited on
Commit
fdcf5d4
Β·
verified Β·
1 Parent(s): 784e7de

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +31 -62
app.py CHANGED
@@ -1,42 +1,7 @@
1
- # This script demonstrates the use of the websockets API and the SaveImageWebsocket node to retrieve images directly
2
- # without saving them to disk. It includes a Gradio interface for user interaction.
3
-
4
- # JSON Comment Section
5
- """
6
- {
7
- "inputs": [
8
- {
9
- "type": "text",
10
- "label": "Text Prompt",
11
- "name": "text_prompt",
12
- "default": "masterpiece best quality man"
13
- },
14
- {
15
- "type": "number",
16
- "label": "Seed",
17
- "name": "seed",
18
- "default": 5
19
- },
20
- {
21
- "type": "radio",
22
- "label": "Server",
23
- "name": "server",
24
- "choices": ["AWS Server", "Home Server"],
25
- "default": "Home Server"
26
- }
27
- ],
28
- "outputs": [
29
- {
30
- "type": "image",
31
- "label": "Generated Image",
32
- "name": "generated_image"
33
- }
34
- ]
35
- }
36
- """
37
-
38
  import gradio as gr
39
- import websocket # NOTE: websocket-client (https://github.com/websocket-client/websocket-client)
40
  import uuid
41
  import json
42
  import urllib.request
@@ -44,29 +9,44 @@ import urllib.parse
44
  from PIL import Image
45
  import io
46
 
47
- # Generate a unique client ID for the session
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
48
  client_id = str(uuid.uuid4())
49
 
50
- # Function to queue a prompt to the server
51
  def queue_prompt(prompt, server_address):
52
  p = {"prompt": prompt, "client_id": client_id}
53
  data = json.dumps(p).encode('utf-8')
54
- req = urllib.request.Request("http://{}/prompt".format(server_address), data=data)
55
  return json.loads(urllib.request.urlopen(req).read())
56
 
57
- # Function to retrieve an image from the server
58
  def get_image(filename, subfolder, folder_type, server_address):
59
  data = {"filename": filename, "subfolder": subfolder, "type": folder_type}
60
  url_values = urllib.parse.urlencode(data)
61
- with urllib.request.urlopen("http://{}/view?{}".format(server_address, url_values)) as response:
62
  return response.read()
63
 
64
- # Function to retrieve the history of a prompt from the server
65
  def get_history(prompt_id, server_address):
66
- with urllib.request.urlopen("http://{}/history/{}".format(server_address, prompt_id)) as response:
67
  return json.loads(response.read())
68
 
69
- # Function to get images from the websocket connection
70
  def get_images(ws, prompt, server_address):
71
  prompt_id = queue_prompt(prompt, server_address)['prompt_id']
72
  output_images = {}
@@ -79,7 +59,7 @@ def get_images(ws, prompt, server_address):
79
  data = message['data']
80
  if data['prompt_id'] == prompt_id:
81
  if data['node'] is None:
82
- break # Execution is done
83
  else:
84
  current_node = data['node']
85
  else:
@@ -90,7 +70,7 @@ def get_images(ws, prompt, server_address):
90
 
91
  return output_images
92
 
93
- # Function to generate an image based on the provided text prompt, seed, and server
94
  def generate_image(text_prompt, seed, server):
95
  prompt_text = """
96
  {
@@ -181,21 +161,12 @@ def generate_image(text_prompt, seed, server):
181
  """
182
 
183
  prompt = json.loads(prompt_text)
184
- # Set the text prompt for our positive CLIPTextEncode
185
  prompt["6"]["inputs"]["text"] = text_prompt
186
-
187
- # Set the seed for our KSampler node
188
  prompt["3"]["inputs"]["seed"] = seed
189
-
190
- # Determine the server address based on the selected server
191
  server_address = "3.14.144.23:8188" if server == "AWS Server" else "192.168.50.136:8188"
192
-
193
- # Establish a websocket connection
194
  ws = websocket.WebSocket()
195
- ws.connect("ws://{}/ws?clientId={}".format(server_address, client_id))
196
  images = get_images(ws, prompt, server_address)
197
-
198
- # Get the first image from the output
199
  image = None
200
 
201
  for node_id in images:
@@ -207,11 +178,11 @@ def generate_image(text_prompt, seed, server):
207
 
208
  return image
209
 
210
- # Function to handle cancel request
211
  def cancel_request():
212
  return "Request Cancelled"
213
 
214
- # Gradio Interface using Blocks
215
  with gr.Blocks() as demo:
216
  gr.Markdown("# Image Generation with Websockets API")
217
  gr.Markdown("Generate images using a Websockets API and SaveImageWebsocket node.")
@@ -227,9 +198,7 @@ with gr.Blocks() as demo:
227
  with gr.Column():
228
  output_image = gr.Image(label="Generated Image")
229
 
230
- # Set up button click events
231
  generate_button.click(fn=generate_image, inputs=[text_prompt, seed, server], outputs=output_image)
232
  cancel_button.click(fn=cancel_request, inputs=[], outputs=[])
233
 
234
- # Launch the Gradio interface
235
  demo.launch()
 
1
+ import subprocess
2
+ import threading
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3
  import gradio as gr
4
+ import websocket
5
  import uuid
6
  import json
7
  import urllib.request
 
9
  from PIL import Image
10
  import io
11
 
12
+ # πŸš€ Chapter 1: Install Necessary Packages πŸš€
13
+ def install_packages():
14
+ packages = [
15
+ "gradio",
16
+ "websocket-client",
17
+ "pillow"
18
+ ]
19
+ for package in packages:
20
+ subprocess.check_call(["pip", "install", package])
21
+
22
+ # Use threading to run the installation in the background
23
+ install_thread = threading.Thread(target=install_packages)
24
+ install_thread.start()
25
+ install_thread.join()
26
+
27
+ # 🌟 Chapter 2: Generate Client ID 🌟
28
  client_id = str(uuid.uuid4())
29
 
30
+ # 🌟 Chapter 3: Queue Prompt Function 🌟
31
  def queue_prompt(prompt, server_address):
32
  p = {"prompt": prompt, "client_id": client_id}
33
  data = json.dumps(p).encode('utf-8')
34
+ req = urllib.request.Request(f"http://{server_address}/prompt", data=data)
35
  return json.loads(urllib.request.urlopen(req).read())
36
 
37
+ # 🌟 Chapter 4: Get Image Function 🌟
38
  def get_image(filename, subfolder, folder_type, server_address):
39
  data = {"filename": filename, "subfolder": subfolder, "type": folder_type}
40
  url_values = urllib.parse.urlencode(data)
41
+ with urllib.request.urlopen(f"http://{server_address}/view?{url_values}") as response:
42
  return response.read()
43
 
44
+ # 🌟 Chapter 5: Get History Function 🌟
45
  def get_history(prompt_id, server_address):
46
+ with urllib.request.urlopen(f"http://{server_address}/history/{prompt_id}") as response:
47
  return json.loads(response.read())
48
 
49
+ # 🌟 Chapter 6: Get Images Function 🌟
50
  def get_images(ws, prompt, server_address):
51
  prompt_id = queue_prompt(prompt, server_address)['prompt_id']
52
  output_images = {}
 
59
  data = message['data']
60
  if data['prompt_id'] == prompt_id:
61
  if data['node'] is None:
62
+ break
63
  else:
64
  current_node = data['node']
65
  else:
 
70
 
71
  return output_images
72
 
73
+ # 🌟 Chapter 7: Generate Image Function 🌟
74
  def generate_image(text_prompt, seed, server):
75
  prompt_text = """
76
  {
 
161
  """
162
 
163
  prompt = json.loads(prompt_text)
 
164
  prompt["6"]["inputs"]["text"] = text_prompt
 
 
165
  prompt["3"]["inputs"]["seed"] = seed
 
 
166
  server_address = "3.14.144.23:8188" if server == "AWS Server" else "192.168.50.136:8188"
 
 
167
  ws = websocket.WebSocket()
168
+ ws.connect(f"ws://{server_address}/ws?clientId={client_id}")
169
  images = get_images(ws, prompt, server_address)
 
 
170
  image = None
171
 
172
  for node_id in images:
 
178
 
179
  return image
180
 
181
+ # 🌟 Chapter 8: Cancel Request Function 🌟
182
  def cancel_request():
183
  return "Request Cancelled"
184
 
185
+ # 🌟 Chapter 9: Gradio Interface 🌟
186
  with gr.Blocks() as demo:
187
  gr.Markdown("# Image Generation with Websockets API")
188
  gr.Markdown("Generate images using a Websockets API and SaveImageWebsocket node.")
 
198
  with gr.Column():
199
  output_image = gr.Image(label="Generated Image")
200
 
 
201
  generate_button.click(fn=generate_image, inputs=[text_prompt, seed, server], outputs=output_image)
202
  cancel_button.click(fn=cancel_request, inputs=[], outputs=[])
203
 
 
204
  demo.launch()