Spaces:
Sleeping
Sleeping
File size: 4,797 Bytes
1deaa99 422d177 1deaa99 422d177 1deaa99 ce70fab 1deaa99 e0bd746 743f9ff e0bd746 1deaa99 e0bd746 1deaa99 c5039f3 1deaa99 c5039f3 1deaa99 c5039f3 1deaa99 916105a 422d177 04a422a 422d177 7bedcd0 c5039f3 e0bd746 c5039f3 1deaa99 c5039f3 1deaa99 c5039f3 1deaa99 916105a 1deaa99 e0bd746 c5039f3 e0bd746 c5039f3 1deaa99 c5039f3 1deaa99 c5039f3 1deaa99 c5039f3 1deaa99 d250e84 1deaa99 |
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 |
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
URL = config('URL')
OUTPUT_DIR = config('OUTPUT_DIR')
INPUT_DIR = config('INPUT_DIR')
COMF_PATH = config('COMF_PATH')
import torch
import spaces
print(f"Is CUDA available: {torch.cuda.is_available()}")
print(f"CUDA device: {torch.cuda.get_device_name(torch.cuda.current_device())}")
print(torch.version.cuda)
device = torch.cuda.get_device_name(torch.cuda.current_device())
print(device)
def wait_for_image_with_prefix(folder, prefix):
def is_file_ready(file_path):
initial_size = os.path.getsize(file_path)
time.sleep(0.5)
return initial_size == os.path.getsize(file_path)
while True:
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(1)
return latest_image
# If no matching file found, wait before checking again
time.sleep(1)
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):
p = {"prompt": prompt_workflow}
data = json.dumps(p).encode('utf-8')
requests.post(URL, data=data)
def check_server_ready():
try:
response = requests.get(f"http://127.0.0.1:8188/history/123", timeout=5)
return response.status_code == 200
except requests.RequestException:
return False
queue_reqs=set()
@spaces.GPU(duration=240)
def generate_image(prompt, image):
prompt = json.loads(prompt)
image = Image.fromarray(image)
image.save(INPUT_DIR+'/input.png', format='PNG')
prefix_filename = random.randint(0, 999999)
queue_reqs.add(prefix_filename)
process = None
try:
# Запускаем скрипт как подпроцесс
process = subprocess.Popen([sys.executable, COMF_PATH, "--listen", "127.0.0.1"])
logger.debug(f'Subprocess started with PID: {process.pid}')
# Ожидание запуска сервера
for _ in range(20): # Максимум 20 секунд ожидания
if check_server_ready():
break
time.sleep(1)
else:
raise TimeoutError("Server did not start in time")
start_queue(prompt)
# Ожидание нового изображения
timeout = 220 # Максимальное время ожидания в секундах
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:
with open(latest_image, 'rb') as f:
photo = f.read()
logger.debug(f"file bytes size: {len(photo)}")
return io.BytesIO(photo)
finally:
delete_image_file(latest_image)
time.sleep(1)
raise TimeoutError("New image was not generated in time")
except Exception as e:
logger.error(f"Error in generate_image: {e}")
return None
finally:
queue_reqs.remove(prefix_filename)
if len(queue_reqs) == 0 and process and process.poll() is None:
process.terminate()
try:
process.wait(timeout=5)
except subprocess.TimeoutExpired:
process.kill()
if __name__ == "__main__":
demo = gr.Interface(fn=generate_image, inputs=[
"text",
gr.Image(image_mode='RGBA', type="numpy")
],
outputs=[
gr.Image(type="numpy", image_mode='RGBA')
])
demo.launch(debug=True)
logger.debug('demo.launch()')
logger.info("Основной скрипт завершил работу.") |