addsw11 commited on
Commit
d190d23
1 Parent(s): 21b8fc2

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +31 -38
app.py CHANGED
@@ -1,3 +1,4 @@
 
1
  import gradio as gr
2
  import numpy as np
3
  import random
@@ -16,22 +17,18 @@ from decouple import config
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):
@@ -39,7 +36,6 @@ def wait_for_image_with_prefix(folder, prefix):
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'))]
@@ -54,10 +50,8 @@ def wait_for_image_with_prefix(folder, prefix):
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):
@@ -68,13 +62,11 @@ def delete_image_file(file_path):
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)
@@ -82,13 +74,16 @@ def check_server_ready(port):
82
  except requests.RequestException:
83
  return False
84
 
85
-
86
-
87
- @spaces.GPU(duration=175)
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')
@@ -96,13 +91,11 @@ def generate_image(prompt, image):
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(40): # Максимум 20 секунд ожидания
106
  if check_server_ready(new_port):
107
  break
108
  time.sleep(1)
@@ -110,9 +103,8 @@ def generate_image(prompt, image):
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)
@@ -141,17 +133,18 @@ def generate_image(prompt, image):
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("Основной скрипт завершил работу.")
 
1
+ import spaces
2
  import gradio as gr
3
  import numpy as np
4
  import random
 
17
  from pathlib import Path
18
  from PIL import Image
19
  import io
 
 
 
 
 
 
20
  import torch
21
 
 
22
 
23
+ URL="http://127.0.0.1"
24
+ OUTPUT_DIR="ComfyUI/output"
25
+ INPUT_DIR="ComfyUI/input"
26
+ BACKEND_PATH="ComfyUI/main.py"
27
+
28
 
29
+ def read_prompt_from_file(filename):
30
+ with open(filename, 'r', encoding='utf-8') as file:
31
+ return json.load(file)
32
 
33
  def wait_for_image_with_prefix(folder, prefix):
34
  def is_file_ready(file_path):
 
36
  time.sleep(1)
37
  return initial_size == os.path.getsize(file_path)
38
 
 
39
  files = os.listdir(folder)
40
  image_files = [f for f in files if f.lower().startswith(prefix.lower()) and
41
  f.lower().endswith(('.png', '.jpg', '.jpeg'))]
 
50
  time.sleep(3)
51
  return latest_image
52
 
 
53
  return None
54
 
 
55
  def delete_image_file(file_path):
56
  try:
57
  if os.path.exists(file_path):
 
62
  except Exception as e:
63
  logger.debug(f"error {file_path}: {str(e)}")
64
 
 
65
  def start_queue(prompt_workflow, port):
66
  p = {"prompt": prompt_workflow}
67
  data = json.dumps(p).encode('utf-8')
68
  requests.post(f"{URL}:{port}/prompt", data=data)
69
 
 
70
  def check_server_ready(port):
71
  try:
72
  response = requests.get(f"{URL}:{port}/history/123", timeout=5)
 
74
  except requests.RequestException:
75
  return False
76
 
77
+ @spaces.GPU(duration=170)
 
 
78
  def generate_image(prompt, image):
79
  prefix_filename = str(random.randint(0, 999999))
80
+ try:
81
+ prompt = prompt.replace('ComfyUI', prefix_filename)
82
+ prompt = json.loads(prompt)
83
+ except:
84
+ prompt = read_prompt_from_file('config.json')
85
+ prompt = json.dumps(prompt, ensure_ascii=False).replace('output_image', prefix_filename)
86
+ prompt = json.loads(prompt)
87
 
88
  image = Image.fromarray(image)
89
  image.save(INPUT_DIR + '/input.png', format='PNG')
 
91
  process = None
92
  new_port = str(random.randint(8123, 8200))
93
 
94
+ try:
95
+ process = subprocess.Popen([sys.executable, BACKEND_PATH, "--listen", "127.0.0.1", "--port", new_port])
 
96
  logger.debug(f'Subprocess started with PID: {process.pid}')
97
+
98
+ for _ in range(40):
 
99
  if check_server_ready(new_port):
100
  break
101
  time.sleep(1)
 
103
  raise TimeoutError("Server did not start in time")
104
 
105
  start_queue(prompt, new_port)
106
+
107
+ timeout = 240
 
108
  start_time = time.time()
109
  while time.time() - start_time < timeout:
110
  latest_image = wait_for_image_with_prefix(OUTPUT_DIR, prefix_filename)
 
133
  logger.debug("process.kill()")
134
  process.kill()
135
 
 
 
136
  if __name__ == "__main__":
137
+ demo = gr.Interface(
138
+ fn=generate_image,
139
+ inputs=[
140
  "text",
141
  gr.Image(image_mode='RGBA', type="numpy")
142
  ],
143
+ outputs=[gr.Image(type="numpy", image_mode='RGBA')],
144
+ title="Image Upscaler",
145
+ description="BEST UPSCALER EVER!!!!!"
146
+ )
147
  demo.launch(debug=True)
148
  logger.debug('demo.launch()')
149
 
150
+ logger.info("finish")