Spaces:
Building
on
Zero
Building
on
Zero
Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,150 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import gradio as gr
|
2 |
+
import numpy as np
|
3 |
+
import random
|
4 |
+
import multiprocessing
|
5 |
+
import subprocess
|
6 |
+
import sys
|
7 |
+
import time
|
8 |
+
import signal
|
9 |
+
import json
|
10 |
+
import os
|
11 |
+
import requests
|
12 |
+
|
13 |
+
from loguru import logger
|
14 |
+
from decouple import config
|
15 |
+
|
16 |
+
from pathlib import Path
|
17 |
+
from PIL import Image
|
18 |
+
import io
|
19 |
+
|
20 |
+
URL="http://127.0.0.1"
|
21 |
+
OUTPUT_DIR = config('OUTPUT_DIR')
|
22 |
+
INPUT_DIR = config('INPUT_DIR')
|
23 |
+
COMF_PATH = config('COMF_PATH')
|
24 |
+
|
25 |
+
import torch
|
26 |
+
|
27 |
+
import spaces
|
28 |
+
|
29 |
+
print(f"Is CUDA available: {torch.cuda.is_available()}")
|
30 |
+
print(f"CUDA device: {torch.cuda.get_device_name(torch.cuda.current_device())}")
|
31 |
+
print(torch.version.cuda)
|
32 |
+
device = torch.cuda.get_device_name(torch.cuda.current_device())
|
33 |
+
print(device)
|
34 |
+
|
35 |
+
|
36 |
+
def read_prompt_from_file(filename):
|
37 |
+
with open(filename, 'r', encoding='utf-8') as file:
|
38 |
+
return json.load(file)
|
39 |
+
|
40 |
+
def wait_for_image_with_prefix(folder, prefix):
|
41 |
+
def is_file_ready(file_path):
|
42 |
+
initial_size = os.path.getsize(file_path)
|
43 |
+
time.sleep(1)
|
44 |
+
return initial_size == os.path.getsize(file_path)
|
45 |
+
|
46 |
+
files = os.listdir(folder)
|
47 |
+
image_files = [f for f in files if f.lower().startswith(prefix.lower()) and
|
48 |
+
f.lower().endswith(('.png', '.jpg', '.jpeg'))]
|
49 |
+
|
50 |
+
if image_files:
|
51 |
+
# Sort by modification time to get the latest file
|
52 |
+
image_files.sort(key=lambda x: os.path.getmtime(os.path.join(folder, x)), reverse=True)
|
53 |
+
latest_image = os.path.join(folder, image_files[0])
|
54 |
+
|
55 |
+
if is_file_ready(latest_image):
|
56 |
+
# Wait a bit more to ensure the file is completely written
|
57 |
+
time.sleep(3)
|
58 |
+
return latest_image
|
59 |
+
|
60 |
+
return None
|
61 |
+
|
62 |
+
def delete_image_file(file_path):
|
63 |
+
try:
|
64 |
+
if os.path.exists(file_path):
|
65 |
+
os.remove(file_path)
|
66 |
+
logger.debug(f"file {file_path} deleted")
|
67 |
+
else:
|
68 |
+
logger.debug(f"file {file_path} is not exist")
|
69 |
+
except Exception as e:
|
70 |
+
logger.debug(f"error {file_path}: {str(e)}")
|
71 |
+
|
72 |
+
def start_queue(prompt_workflow, port):
|
73 |
+
p = {"prompt": prompt_workflow}
|
74 |
+
data = json.dumps(p).encode('utf-8')
|
75 |
+
requests.post(f"{URL}:{port}/prompt", data=data)
|
76 |
+
|
77 |
+
def check_server_ready(port):
|
78 |
+
try:
|
79 |
+
response = requests.get(f"{URL}:{port}/history/123", timeout=5)
|
80 |
+
return response.status_code == 200
|
81 |
+
except requests.RequestException:
|
82 |
+
return False
|
83 |
+
|
84 |
+
@spaces.GPU(duration=195)
|
85 |
+
def generate_image(image):
|
86 |
+
prefix_filename = str(random.randint(0, 999999))
|
87 |
+
prompt = read_prompt_from_file('good_upscaler.json')
|
88 |
+
prompt = json.dumps(prompt, ensure_ascii=False).replace('ComfyUI', prefix_filename)
|
89 |
+
prompt = json.loads(prompt)
|
90 |
+
|
91 |
+
image = Image.fromarray(image)
|
92 |
+
image.save(INPUT_DIR + '/input.png', format='PNG')
|
93 |
+
|
94 |
+
process = None
|
95 |
+
new_port = str(random.randint(8123, 8200))
|
96 |
+
|
97 |
+
try:
|
98 |
+
process = subprocess.Popen([sys.executable, COMF_PATH, "--listen", "127.0.0.1", "--port", new_port])
|
99 |
+
logger.debug(f'Subprocess started with PID: {process.pid}')
|
100 |
+
|
101 |
+
for _ in range(40):
|
102 |
+
if check_server_ready(new_port):
|
103 |
+
break
|
104 |
+
time.sleep(1)
|
105 |
+
else:
|
106 |
+
raise TimeoutError("Server did not start in time")
|
107 |
+
|
108 |
+
start_queue(prompt, new_port)
|
109 |
+
|
110 |
+
timeout = 240
|
111 |
+
start_time = time.time()
|
112 |
+
while time.time() - start_time < timeout:
|
113 |
+
latest_image = wait_for_image_with_prefix(OUTPUT_DIR, prefix_filename)
|
114 |
+
if latest_image:
|
115 |
+
logger.debug(f"file is: {latest_image}")
|
116 |
+
try:
|
117 |
+
return Image.open(latest_image)
|
118 |
+
finally:
|
119 |
+
delete_image_file(latest_image)
|
120 |
+
delete_image_file(INPUT_DIR + '/input.png')
|
121 |
+
time.sleep(1)
|
122 |
+
|
123 |
+
raise TimeoutError("New image was not generated in time")
|
124 |
+
|
125 |
+
except Exception as e:
|
126 |
+
logger.error(f"Error in generate_image: {e}")
|
127 |
+
|
128 |
+
finally:
|
129 |
+
if process and process.poll() is None:
|
130 |
+
process.terminate()
|
131 |
+
logger.debug("process.terminate()")
|
132 |
+
try:
|
133 |
+
logger.debug("process.wait(timeout=5)")
|
134 |
+
process.wait(timeout=5)
|
135 |
+
except subprocess.TimeoutExpired:
|
136 |
+
logger.debug("process.kill()")
|
137 |
+
process.kill()
|
138 |
+
|
139 |
+
if __name__ == "__main__":
|
140 |
+
demo = gr.Interface(
|
141 |
+
fn=generate_image,
|
142 |
+
inputs=[gr.Image(image_mode='RGBA', type="numpy")],
|
143 |
+
outputs=[gr.Image(type="numpy", image_mode='RGBA')],
|
144 |
+
title="Image Upscaler",
|
145 |
+
description="This is an upscaler that increases the resolution of your image to 16 megapixels. Upload an image to get started!"
|
146 |
+
)
|
147 |
+
demo.launch(debug=True)
|
148 |
+
logger.debug('demo.launch()')
|
149 |
+
|
150 |
+
logger.info("finish")
|