Spaces:
Potre1qw
/
Running on Zero

File size: 7,023 Bytes
9fda697
63de209
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9fda697
e06a87d
 
 
9fda697
63de209
9fda697
 
 
63de209
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
182fc10
cc4291a
63de209
cc4291a
 
 
 
 
 
 
63de209
 
 
 
 
 
 
9fda697
 
63de209
9fda697
 
63de209
 
 
 
 
 
 
9fda697
 
63de209
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
182fc10
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
63de209
9fda697
182fc10
cc4291a
 
182fc10
 
cc4291a
9fda697
 
 
 
63de209
 
 
9fda697
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
import spaces
import gradio as gr
import numpy as np
import random
import multiprocessing
import subprocess
import sys
import time
import signal
import json
import os
import requests

from loguru import logger
from decouple import config

from pathlib import Path
from PIL import Image
import io
import torch


URL="http://127.0.0.1"
OUTPUT_DIR="ComfyUI/output"
INPUT_DIR="ComfyUI/input"
BACKEND_PATH="ComfyUI/main.py"


def read_prompt_from_file(filename):
    with open(filename, 'r', encoding='utf-8') as file:
        return json.load(file)

def wait_for_image_with_prefix(folder, prefix):
    def is_file_ready(file_path):
        initial_size = os.path.getsize(file_path)
        time.sleep(1)
        return initial_size == os.path.getsize(file_path)

    files = os.listdir(folder)
    image_files = [f for f in files if f.lower().startswith(prefix.lower()) and
                   f.lower().endswith(('.png', '.jpg', '.jpeg'))]

    if image_files:
        # Sort by modification time to get the latest file
        image_files.sort(key=lambda x: os.path.getmtime(os.path.join(folder, x)), reverse=True)
        latest_image = os.path.join(folder, image_files[0])

        if is_file_ready(latest_image):
            # Wait a bit more to ensure the file is completely written
            time.sleep(3)
            return latest_image

    return None

def delete_image_file(file_path):
    try:
        if os.path.exists(file_path):
            os.remove(file_path)
            logger.debug(f"file {file_path} deleted")
        else:
            logger.debug(f"file {file_path} is not exist")
    except Exception as e:
        logger.debug(f"error {file_path}: {str(e)}")

def start_queue(prompt_workflow, port):
    p = {"prompt": prompt_workflow}
    data = json.dumps(p).encode('utf-8')
    requests.post(f"{URL}:{port}/prompt", data=data)

def check_server_ready(port):
    try:
        response = requests.get(f"{URL}:{port}/history/123", timeout=5)
        return response.status_code == 200
    except requests.RequestException:
        return False


def generate_image(prompt, image):
    prefix_filename = str(random.randint(0, 999999))
    try:
        prompt = prompt.replace('ComfyUI', prefix_filename)
        prompt = json.loads(prompt)
    except:
        prompt = read_prompt_from_file('config.json')
        prompt = json.dumps(prompt, ensure_ascii=False).replace('output_image', prefix_filename)
        prompt = json.loads(prompt)

    image = Image.fromarray(image)
    image.save(INPUT_DIR + '/input.png', format='PNG')

    process = None
    new_port = str(random.randint(8123, 8200))

    try:        
        process = subprocess.Popen([sys.executable, BACKEND_PATH, "--listen", "127.0.0.1", "--port", new_port])
        logger.debug(f'Subprocess started with PID: {process.pid}')
      
        for _ in range(40): 
            if check_server_ready(new_port):
                break
            time.sleep(1)
        else:
            raise TimeoutError("Server did not start in time")

        start_queue(prompt, new_port)
        
        timeout = 240
        start_time = time.time()
        while time.time() - start_time < timeout:
            latest_image = wait_for_image_with_prefix(OUTPUT_DIR, prefix_filename)
            if latest_image:
                logger.debug(f"file is: {latest_image}")
                try:
                    return Image.open(latest_image)
                finally:
                    delete_image_file(latest_image)
                    delete_image_file(INPUT_DIR + '/input.png')
            time.sleep(1)

        raise TimeoutError("New image was not generated in time")

    except Exception as e:
        logger.error(f"Error in generate_image: {e}")        

    finally:        
        if process and process.poll() is None:
            process.terminate()
            logger.debug("process.terminate()")
            try:
                logger.debug("process.wait(timeout=5)")
                process.wait(timeout=5)
            except subprocess.TimeoutExpired:
                logger.debug("process.kill()")
                process.kill()



@spaces.GPU(duration=50)
def generate_image_50(prompt, image):
  return generate_image(prompt, image)

@spaces.GPU(duration=70)
def generate_image_70(prompt, image):
  return generate_image(prompt, image)

@spaces.GPU(duration=90)
def generate_image_90(prompt, image):
  return generate_image(prompt, image)

@spaces.GPU(duration=110)
def generate_image_110(prompt, image):
  return generate_image(prompt, image)

@spaces.GPU(duration=130)
def generate_image_130(prompt, image):
  return generate_image(prompt, image)

@spaces.GPU(duration=150)
def generate_image_150(prompt, image):
  return generate_image(prompt, image)

@spaces.GPU(duration=170)
def generate_image_170(prompt, image):
  return generate_image(prompt, image)

@spaces.GPU(duration=190) 
def generate_image_190(prompt, image):
  return generate_image(prompt, image)

@spaces.GPU(duration=200)
def generate_image_200(prompt, image):
  return generate_image(prompt, image)

@spaces.GPU(duration=210)
def generate_image_210(prompt, image):
  return generate_image(prompt, image)

@spaces.GPU(duration=220)
def generate_image_220(prompt, image):
  return generate_image(prompt, image)

@spaces.GPU(duration=230)
def generate_image_230(prompt, image):
  return generate_image(prompt, image)

@spaces.GPU(duration=240)
def generate_image_240(prompt, image):
  return generate_image(prompt, image)


def generate_image_wrapper(prompt, image, duration):
    if duration == "50":
        return generate_image_50(prompt, image)
    elif duration == "70":
        return generate_image_70(prompt, image)
    elif duration == "90":
        return generate_image_90(prompt, image)
    elif duration == "110":
        return generate_image_110(prompt, image)
    elif duration == "130":
        return generate_image_130(prompt, image)
    elif duration == "150":
        return generate_image_150(prompt, image)
    elif duration == "170":
        return generate_image_170(prompt, image)
    elif duration == "190":
        return generate_image_190(prompt, image)
    elif duration == "200":
        return generate_image_200(prompt, image)
    elif duration == "210":
        return generate_image_210(prompt, image)
    elif duration == "220":
        return generate_image_220(prompt, image)
    elif duration == "230":
        return generate_image_230(prompt, image)
    elif duration == "240":
        return generate_image_240(prompt, image)
    else:
        return generate_image_170(prompt, image)

if __name__ == "__main__":
    demo = gr.Interface(
        fn=generate_image_wrapper,
        inputs=[
        "text",
        gr.Image(image_mode='RGBA', type="numpy"),
        "text"
    ],
        outputs=[gr.Image(type="numpy", image_mode='RGBA')],
        title="Image Upscaler",
        description="BEST UPSCALER EVER!!!!!"
    )
    demo.launch(debug=True)
    logger.debug('demo.launch()')

    logger.info("finish")