Freak-ppa commited on
Commit
e0bd746
·
verified ·
1 Parent(s): 916105a

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +43 -19
app.py CHANGED
@@ -33,21 +33,39 @@ device = torch.cuda.get_device_name(torch.cuda.current_device())
33
  print(device)
34
 
35
 
36
- def get_latest_image(folder):
37
- files = os.listdir(folder)
38
- image_files = [f for f in files if f.lower().endswith(('.png', '.jpg', '.jpeg'))]
39
- image_files.sort(key=lambda x: os.path.getmtime(os.path.join(folder, x)))
40
- latest_image = os.path.join(folder, image_files[-1]) if image_files else None
41
  def is_file_ready(file_path):
42
  initial_size = os.path.getsize(file_path)
43
  time.sleep(0.5)
44
  return initial_size == os.path.getsize(file_path)
45
 
46
- if latest_image:
47
- if is_file_ready(latest_image):
48
- return latest_image
49
- return latest_image
 
 
 
 
 
 
 
 
 
 
 
 
 
50
 
 
 
 
 
 
 
 
 
 
51
 
52
  def start_queue(prompt_workflow):
53
  p = {"prompt": prompt_workflow}
@@ -55,9 +73,9 @@ def start_queue(prompt_workflow):
55
  requests.post(URL, data=data)
56
 
57
 
58
- def check_server_ready():
59
  try:
60
- response = requests.get(f"http://127.0.0.1:8188/history/123", timeout=5)
61
  return response.status_code == 200
62
  except requests.RequestException:
63
  return False
@@ -67,20 +85,21 @@ def check_server_ready():
67
  def generate_image(prompt, image):
68
  prompt = json.loads(prompt)
69
 
70
- previous_image = get_latest_image(OUTPUT_DIR)
71
 
72
  image = Image.fromarray(image)
73
  image.save(INPUT_DIR+'/input.png', format='PNG')
74
 
75
-
 
76
  # Запускаем скрипт как подпроцесс
77
- process = subprocess.Popen([sys.executable, COMF_PATH, "--listen", "127.0.0.1"])
78
  logger.debug(f'Subprocess started with PID: {process.pid}')
79
  latest_image = None
80
  try:
81
  # Ожидание запуска сервера
82
  for _ in range(20): # Максимум 20 секунд ожидания
83
- if check_server_ready(): # Вам нужно реализовать эту функцию
84
  break
85
  time.sleep(1)
86
  else:
@@ -92,9 +111,14 @@ def generate_image(prompt, image):
92
  timeout = 220 # Максимальное время ожидания в секундах
93
  start_time = time.time()
94
  while time.time() - start_time < timeout:
95
- latest_image = get_latest_image(OUTPUT_DIR)
96
  if latest_image != previous_image:
97
- return latest_image
 
 
 
 
 
98
  time.sleep(1)
99
 
100
  raise TimeoutError("New image was not generated in time")
@@ -109,8 +133,8 @@ def generate_image(prompt, image):
109
  try:
110
  process.wait(timeout=5)
111
  except subprocess.TimeoutExpired:
112
- process.kill()
113
-
114
  #logger.error("No new image was generated")
115
  return latest_image
116
 
 
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(0.5)
40
  return initial_size == os.path.getsize(file_path)
41
 
42
+ while True:
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(1)
55
+ return latest_image
56
+
57
+ # If no matching file found, wait before checking again
58
+ time.sleep(1)
59
 
60
+ def delete_image_file(file_path):
61
+ try:
62
+ if os.path.exists(file_path):
63
+ os.remove(file_path)
64
+ logger.debug(f"file {file_path} deleted")
65
+ else:
66
+ logger.debug(f"file {file_path} is not exist")
67
+ except Exception as e:
68
+ logger.debug(f"error {file_path}: {str(e)}")
69
 
70
  def start_queue(prompt_workflow):
71
  p = {"prompt": prompt_workflow}
 
73
  requests.post(URL, data=data)
74
 
75
 
76
+ def check_server_ready(new_port):
77
  try:
78
+ response = requests.get(f"http://127.0.0.1:{new_port}/history/123", timeout=5)
79
  return response.status_code == 200
80
  except requests.RequestException:
81
  return False
 
85
  def generate_image(prompt, image):
86
  prompt = json.loads(prompt)
87
 
88
+ previous_image = None
89
 
90
  image = Image.fromarray(image)
91
  image.save(INPUT_DIR+'/input.png', format='PNG')
92
 
93
+ new_port = random.randint(8188, 8288)
94
+ prefix_filename = random.randint(0, 999999)
95
  # Запускаем скрипт как подпроцесс
96
+ process = subprocess.Popen([sys.executable, COMF_PATH, "--listen", "127.0.0.1", "--port", f"{new_port}"])
97
  logger.debug(f'Subprocess started with PID: {process.pid}')
98
  latest_image = None
99
  try:
100
  # Ожидание запуска сервера
101
  for _ in range(20): # Максимум 20 секунд ожидания
102
+ if check_server_ready(new_port): # Вам нужно реализовать эту функцию
103
  break
104
  time.sleep(1)
105
  else:
 
111
  timeout = 220 # Максимальное время ожидания в секундах
112
  start_time = time.time()
113
  while time.time() - start_time < timeout:
114
+ latest_image = wait_for_image_with_prefix(OUTPUT_DIR, prefix_filename)
115
  if latest_image != previous_image:
116
+ logger.debug(f"file is: {latest_image}")
117
+ with open(latest_image, 'rb') as f:
118
+ photo = file.read()
119
+ logger.debug(f"file bytes size: {len(photo)}")
120
+ delete_image_file(latest_image)
121
+ return io.BytesIO(photo)
122
  time.sleep(1)
123
 
124
  raise TimeoutError("New image was not generated in time")
 
133
  try:
134
  process.wait(timeout=5)
135
  except subprocess.TimeoutExpired:
136
+ process.kill()
137
+
138
  #logger.error("No new image was generated")
139
  return latest_image
140