Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -1,15 +1,15 @@
|
|
1 |
import os
|
2 |
-
|
3 |
-
import websocket
|
4 |
-
import uuid
|
5 |
import json
|
|
|
|
|
6 |
import urllib.request
|
7 |
import urllib.parse
|
8 |
-
import
|
9 |
-
|
10 |
-
import io
|
11 |
-
import base64
|
12 |
from dotenv import load_dotenv
|
|
|
|
|
13 |
|
14 |
# Load environment variables from the .env file
|
15 |
load_dotenv()
|
@@ -17,18 +17,11 @@ load_dotenv()
|
|
17 |
# Initialize Flask app
|
18 |
app = Flask(__name__)
|
19 |
|
20 |
-
# Set server and websocket addresses from environment variables
|
21 |
-
# server_address = "https://gosign-de-comfyui.hf.space"
|
22 |
-
# ws_address = "wss://gosign-de-comfyui.hf.space/ws"
|
23 |
-
|
24 |
# Set server and websocket addresses from environment variables
|
25 |
server_address = os.getenv("SERVER_ADDRESS")
|
26 |
ws_address = os.getenv("WS_ADDRESS")
|
27 |
|
28 |
-
#
|
29 |
-
print(f"Server Address: {server_address}")
|
30 |
-
print(f"WebSocket Address: {ws_address}")
|
31 |
-
|
32 |
client_id = str(uuid.uuid4())
|
33 |
|
34 |
def make_request(url, data=None, headers=None):
|
@@ -40,7 +33,7 @@ def queue_prompt(prompt, token):
|
|
40 |
payload = {"prompt": prompt, "client_id": client_id}
|
41 |
data = json.dumps(payload).encode('utf-8')
|
42 |
headers = {
|
43 |
-
'Authorization': f'Bearer {token}',
|
44 |
'Content-Type': 'application/json'
|
45 |
}
|
46 |
return make_request(f"{server_address}/prompt", data=data, headers=headers)
|
@@ -48,19 +41,13 @@ def queue_prompt(prompt, token):
|
|
48 |
def get_image(filename, subfolder, image_type, token):
|
49 |
url_values = {'filename': filename, 'subfolder': subfolder, 'type': image_type}
|
50 |
url = f"{server_address}/view?{urllib.parse.urlencode(url_values)}"
|
51 |
-
|
52 |
req = urllib.request.Request(url)
|
53 |
req.add_header("Authorization", f"Bearer {token}")
|
54 |
-
|
55 |
-
# Debugging output
|
56 |
-
print(f"Request URL: {url}")
|
57 |
-
print(f"Request Headers: {req.headers}")
|
58 |
-
|
59 |
try:
|
60 |
return urllib.request.urlopen(req).read()
|
61 |
except urllib.error.HTTPError as e:
|
62 |
print(f"HTTP Error: {e.code} - {e.reason}")
|
63 |
-
print(e.read())
|
64 |
raise
|
65 |
|
66 |
def get_history(prompt_id, token):
|
@@ -94,6 +81,7 @@ def get_images(ws, prompt, token):
|
|
94 |
output_images[node_id] = images_output
|
95 |
|
96 |
return output_images
|
|
|
97 |
# Default route for home welcome
|
98 |
@app.route('/')
|
99 |
def home():
|
@@ -107,14 +95,10 @@ def generate_image():
|
|
107 |
# Extract the token from the request headers
|
108 |
token = request.headers.get('Authorization')
|
109 |
|
110 |
-
# Ensure the token is present and in the correct format
|
111 |
if token is None:
|
112 |
return jsonify({'error': 'No token provided'}), 400
|
113 |
-
# If the token does not have a 'Bearer' prefix, use the entire token
|
114 |
if token.startswith("Bearer "):
|
115 |
token = token.split(" ")[1] # Extract the actual token if 'Bearer ' exists
|
116 |
-
else:
|
117 |
-
token = token # Use the entire token if there's no 'Bearer ' prefix
|
118 |
|
119 |
# Base64 decode the encoded token
|
120 |
token = base64.b64decode(token).decode("utf-8")
|
@@ -124,8 +108,6 @@ def generate_image():
|
|
124 |
|
125 |
text_prompt = data['text_prompt']
|
126 |
|
127 |
-
# file_path = '/Users/muhammadwaqas/gosign/comfyui-api/workflow_api.json'
|
128 |
-
|
129 |
# Get the path to the current file's directory
|
130 |
current_dir = os.path.dirname(os.path.abspath(__file__))
|
131 |
file_path = os.path.join(current_dir, 'workflow_api.json')
|
@@ -145,17 +127,17 @@ def generate_image():
|
|
145 |
images = get_images(ws, prompt, token)
|
146 |
ws.close()
|
147 |
|
148 |
-
|
149 |
|
150 |
for node_id in images:
|
151 |
for image_data in images[node_id]:
|
152 |
image = Image.open(io.BytesIO(image_data))
|
153 |
-
|
154 |
-
image.
|
155 |
-
|
156 |
-
|
157 |
|
158 |
-
return jsonify({'images':
|
159 |
|
160 |
@app.route('/get_image/<filename>', methods=['GET'])
|
161 |
def get_image_file(filename):
|
|
|
1 |
import os
|
2 |
+
import io
|
|
|
|
|
3 |
import json
|
4 |
+
import base64
|
5 |
+
import random
|
6 |
import urllib.request
|
7 |
import urllib.parse
|
8 |
+
import websocket
|
9 |
+
import uuid
|
|
|
|
|
10 |
from dotenv import load_dotenv
|
11 |
+
from flask import Flask, request, jsonify, render_template
|
12 |
+
from PIL import Image
|
13 |
|
14 |
# Load environment variables from the .env file
|
15 |
load_dotenv()
|
|
|
17 |
# Initialize Flask app
|
18 |
app = Flask(__name__)
|
19 |
|
|
|
|
|
|
|
|
|
20 |
# Set server and websocket addresses from environment variables
|
21 |
server_address = os.getenv("SERVER_ADDRESS")
|
22 |
ws_address = os.getenv("WS_ADDRESS")
|
23 |
|
24 |
+
# Generate a unique client ID
|
|
|
|
|
|
|
25 |
client_id = str(uuid.uuid4())
|
26 |
|
27 |
def make_request(url, data=None, headers=None):
|
|
|
33 |
payload = {"prompt": prompt, "client_id": client_id}
|
34 |
data = json.dumps(payload).encode('utf-8')
|
35 |
headers = {
|
36 |
+
'Authorization': f'Bearer {token}',
|
37 |
'Content-Type': 'application/json'
|
38 |
}
|
39 |
return make_request(f"{server_address}/prompt", data=data, headers=headers)
|
|
|
41 |
def get_image(filename, subfolder, image_type, token):
|
42 |
url_values = {'filename': filename, 'subfolder': subfolder, 'type': image_type}
|
43 |
url = f"{server_address}/view?{urllib.parse.urlencode(url_values)}"
|
|
|
44 |
req = urllib.request.Request(url)
|
45 |
req.add_header("Authorization", f"Bearer {token}")
|
|
|
|
|
|
|
|
|
|
|
46 |
try:
|
47 |
return urllib.request.urlopen(req).read()
|
48 |
except urllib.error.HTTPError as e:
|
49 |
print(f"HTTP Error: {e.code} - {e.reason}")
|
50 |
+
print(e.read())
|
51 |
raise
|
52 |
|
53 |
def get_history(prompt_id, token):
|
|
|
81 |
output_images[node_id] = images_output
|
82 |
|
83 |
return output_images
|
84 |
+
|
85 |
# Default route for home welcome
|
86 |
@app.route('/')
|
87 |
def home():
|
|
|
95 |
# Extract the token from the request headers
|
96 |
token = request.headers.get('Authorization')
|
97 |
|
|
|
98 |
if token is None:
|
99 |
return jsonify({'error': 'No token provided'}), 400
|
|
|
100 |
if token.startswith("Bearer "):
|
101 |
token = token.split(" ")[1] # Extract the actual token if 'Bearer ' exists
|
|
|
|
|
102 |
|
103 |
# Base64 decode the encoded token
|
104 |
token = base64.b64decode(token).decode("utf-8")
|
|
|
108 |
|
109 |
text_prompt = data['text_prompt']
|
110 |
|
|
|
|
|
111 |
# Get the path to the current file's directory
|
112 |
current_dir = os.path.dirname(os.path.abspath(__file__))
|
113 |
file_path = os.path.join(current_dir, 'workflow_api.json')
|
|
|
127 |
images = get_images(ws, prompt, token)
|
128 |
ws.close()
|
129 |
|
130 |
+
output_images_base64 = []
|
131 |
|
132 |
for node_id in images:
|
133 |
for image_data in images[node_id]:
|
134 |
image = Image.open(io.BytesIO(image_data))
|
135 |
+
buffered = io.BytesIO()
|
136 |
+
image.save(buffered, format="PNG")
|
137 |
+
img_str = base64.b64encode(buffered.getvalue()).decode("utf-8")
|
138 |
+
output_images_base64.append(img_str)
|
139 |
|
140 |
+
return jsonify({'images': output_images_base64})
|
141 |
|
142 |
@app.route('/get_image/<filename>', methods=['GET'])
|
143 |
def get_image_file(filename):
|