flatcherlee commited on
Commit
63de209
1 Parent(s): a1039a8

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +157 -0
app.py ADDED
@@ -0,0 +1,157 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 wait_for_image_with_prefix(folder, prefix):
37
+ def is_file_ready(file_path):
38
+ initial_size = os.path.getsize(file_path)
39
+ time.sleep(1)
40
+ return initial_size == os.path.getsize(file_path)
41
+
42
+
43
+ files = os.listdir(folder)
44
+ image_files = [f for f in files if f.lower().startswith(prefix.lower()) and
45
+ f.lower().endswith(('.png', '.jpg', '.jpeg'))]
46
+
47
+ if image_files:
48
+ # Sort by modification time to get the latest file
49
+ image_files.sort(key=lambda x: os.path.getmtime(os.path.join(folder, x)), reverse=True)
50
+ latest_image = os.path.join(folder, image_files[0])
51
+
52
+ if is_file_ready(latest_image):
53
+ # Wait a bit more to ensure the file is completely written
54
+ time.sleep(3)
55
+ return latest_image
56
+
57
+
58
+ return None
59
+
60
+
61
+ def delete_image_file(file_path):
62
+ try:
63
+ if os.path.exists(file_path):
64
+ os.remove(file_path)
65
+ logger.debug(f"file {file_path} deleted")
66
+ else:
67
+ logger.debug(f"file {file_path} is not exist")
68
+ except Exception as e:
69
+ logger.debug(f"error {file_path}: {str(e)}")
70
+
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
+
78
+ def check_server_ready(port):
79
+ try:
80
+ response = requests.get(f"{URL}:{port}/history/123", timeout=5)
81
+ return response.status_code == 200
82
+ except requests.RequestException:
83
+ return False
84
+
85
+
86
+
87
+ @spaces.GPU(duration=240)
88
+ def generate_image(prompt, image):
89
+ prefix_filename = str(random.randint(0, 999999))
90
+ prompt = prompt.replace('ComfyUI', prefix_filename)
91
+ prompt = json.loads(prompt)
92
+
93
+ image = Image.fromarray(image)
94
+ image.save(INPUT_DIR + '/input.png', format='PNG')
95
+
96
+ process = None
97
+ new_port = str(random.randint(8123, 8200))
98
+
99
+ try:
100
+ # Запускаем скрипт как подпроцесс
101
+ process = subprocess.Popen([sys.executable, COMF_PATH, "--listen", "127.0.0.1", "--port", new_port])
102
+ logger.debug(f'Subprocess started with PID: {process.pid}')
103
+
104
+ # Ожидание запуска сервера
105
+ for _ in range(30): # Максимум 20 секунд ожидания
106
+ if check_server_ready(new_port):
107
+ break
108
+ time.sleep(1)
109
+ else:
110
+ raise TimeoutError("Server did not start in time")
111
+
112
+ start_queue(prompt, new_port)
113
+
114
+ # Ожидание нового изображения
115
+ timeout = 240 # Максимальное время ожидания в секундах
116
+ start_time = time.time()
117
+ while time.time() - start_time < timeout:
118
+ latest_image = wait_for_image_with_prefix(OUTPUT_DIR, prefix_filename)
119
+ if latest_image:
120
+ logger.debug(f"file is: {latest_image}")
121
+ try:
122
+ return Image.open(latest_image)
123
+ finally:
124
+ delete_image_file(latest_image)
125
+ delete_image_file(INPUT_DIR + '/input.png')
126
+ time.sleep(1)
127
+
128
+ raise TimeoutError("New image was not generated in time")
129
+
130
+ except Exception as e:
131
+ logger.error(f"Error in generate_image: {e}")
132
+
133
+ finally:
134
+ if process and process.poll() is None:
135
+ process.terminate()
136
+ logger.debug("process.terminate()")
137
+ try:
138
+ logger.debug("process.wait(timeout=5)")
139
+ process.wait(timeout=5)
140
+ except subprocess.TimeoutExpired:
141
+ logger.debug("process.kill()")
142
+ process.kill()
143
+
144
+
145
+
146
+ if __name__ == "__main__":
147
+ demo = gr.Interface(fn=generate_image, inputs=[
148
+ "text",
149
+ gr.Image(image_mode='RGBA', type="numpy")
150
+ ],
151
+ outputs=[
152
+ gr.Image(type="numpy", image_mode='RGBA')
153
+ ])
154
+ demo.launch(debug=True)
155
+ logger.debug('demo.launch()')
156
+
157
+ logger.info("Основной скрипт завершил работу.")