Spaces:
Potre1qw
/
Running on Zero

Potre1qw commited on
Commit
9fda697
·
verified ·
1 Parent(s): ba639b2

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +27 -41
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,12 +74,11 @@ def check_server_ready(port):
82
  except requests.RequestException:
83
  return False
84
 
85
-
86
-
87
- @spaces.GPU(duration=190)
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)
@@ -96,13 +87,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 +99,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 +129,15 @@ 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="Core/output"
25
+ INPUT_DIR="Core/input"
26
+ BACKEND_PATH="Core/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(image):
 
 
79
  prefix_filename = str(random.randint(0, 999999))
80
+ prompt = read_prompt_from_file('config.json')
81
+ prompt = json.dumps(prompt, ensure_ascii=False).replace('output_image', prefix_filename)
82
  prompt = json.loads(prompt)
83
 
84
  image = Image.fromarray(image)
 
87
  process = None
88
  new_port = str(random.randint(8123, 8200))
89
 
90
+ try:
91
+ process = subprocess.Popen([sys.executable, BACKEND_PATH, "--listen", "127.0.0.1", "--port", new_port])
 
92
  logger.debug(f'Subprocess started with PID: {process.pid}')
93
+
94
+ for _ in range(40):
 
95
  if check_server_ready(new_port):
96
  break
97
  time.sleep(1)
 
99
  raise TimeoutError("Server did not start in time")
100
 
101
  start_queue(prompt, new_port)
102
+
103
+ timeout = 240
 
104
  start_time = time.time()
105
  while time.time() - start_time < timeout:
106
  latest_image = wait_for_image_with_prefix(OUTPUT_DIR, prefix_filename)
 
129
  logger.debug("process.kill()")
130
  process.kill()
131
 
 
 
132
  if __name__ == "__main__":
133
+ demo = gr.Interface(
134
+ fn=generate_image,
135
+ inputs=[gr.Image(image_mode='RGBA', type="numpy")],
136
+ outputs=[gr.Image(type="numpy", image_mode='RGBA')],
137
+ title="Image Upscaler",
138
+ description="BEST UPSCALER EVER!!!!!"
139
+ )
140
  demo.launch(debug=True)
141
  logger.debug('demo.launch()')
142
 
143
+ logger.info("finish")