Lupara90 commited on
Commit
aa3776e
·
verified ·
1 Parent(s): 12eaa16

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +65 -33
app.py CHANGED
@@ -10,14 +10,16 @@ import torch
10
  import spaces
11
 
12
  # ==========================================
13
- # 1. Install Dependencies Natively
14
  # ==========================================
15
  required_packages = [
16
  "safetensors", "scipy", "tqdm", "psutil", "einops",
17
  "transformers", "tokenizers", "sentencepiece", "torchsde",
18
- "huggingface-hub", "aiohttp", "yarl", "av", "blake3"
 
19
  ]
20
 
 
21
  for package in required_packages:
22
  try:
23
  __import__(package.replace("-", "_"))
@@ -25,42 +27,66 @@ for package in required_packages:
25
  print(f"Installing missing dependency: {package}")
26
  subprocess.run([sys.executable, "-m", "pip", "install", package], check=True)
27
 
28
- # ==========================================
29
- # 2. Clone ComfyUI & Start Background Server
30
- # ==========================================
31
  COMFYUI_DIR = os.path.abspath("ComfyUI")
32
-
33
  if not os.path.exists(COMFYUI_DIR):
34
- print("Cloning ComfyUI...")
35
  subprocess.run(["git", "clone", "https://github.com/comfyanonymous/ComfyUI.git", COMFYUI_DIR], check=True)
36
 
37
- # Start ComfyUI as a separate background process using CPU mode for startup safety
38
- print("Launching ComfyUI background server...")
39
- comfy_process = subprocess.Popen(
40
- [sys.executable, os.path.join(COMFYUI_DIR, "main.py"), "--listen", "127.0.0.1", "--port", "8188", "--cpu"],
41
- stdout=subprocess.DEVNULL,
42
- stderr=subprocess.DEVNULL
43
- )
44
-
45
- # Wait a few seconds for the local server to warm up
46
- time.sleep(5)
47
 
48
  # ==========================================
49
- # 3. Define GPU Inference Function
50
  # ==========================================
51
- @spaces.GPU(duration=60)
52
  def generate_image(user_prompt):
53
  if not os.path.exists("workflow_api.json"):
 
54
  return None
55
 
56
  with open("workflow_api.json", "r") as f:
57
  prompt_workflow = json.load(f)
58
 
59
- # Inject the prompt into your specific node ID (Change '6' if your text encoder is different)
60
  if "6" in prompt_workflow and "inputs" in prompt_workflow["6"]:
61
  prompt_workflow["6"]["inputs"]["text"] = user_prompt
62
 
63
- # Send the workflow JSON payload to the ComfyUI local API
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
64
  p = {"prompt": prompt_workflow}
65
  data = json.dumps(p).encode('utf-8')
66
  req = urllib.request.Request("http://127.0.0.1:8188/prompt", data=data, headers={'Content-Type': 'application/json'})
@@ -68,30 +94,36 @@ def generate_image(user_prompt):
68
  try:
69
  with urllib.request.urlopen(req) as response:
70
  res = json.loads(response.read().decode('utf-8'))
71
- prompt_id = res['prompt_id']
72
- print(f"Workflow enqueued successfully. Prompt ID: {prompt_id}")
73
  except Exception as e:
74
- print(f"Failed to communicate with ComfyUI API: {e}")
 
75
  return None
76
 
77
- # Wait for the generation to complete by polling the output folder
78
- output_dir = os.path.join(COMFYUI_DIR, "output")
79
- for _ in range(60): # Poll for up to 60 seconds
80
  time.sleep(1)
81
  if os.path.exists(output_dir):
82
  files = [os.path.join(output_dir, f) for f in os.listdir(output_dir) if os.path.isfile(os.path.join(output_dir, f))]
83
  if files:
84
- # Return the newest generated file
85
- return max(files, key=os.path.getmtime)
86
-
87
- return None
 
 
 
 
 
 
88
 
89
  # ==========================================
90
- # 4. Gradio Interface
91
  # ==========================================
92
  with gr.Blocks() as demo:
93
  gr.Markdown("# My Custom ComfyUI App")
94
- gr.Markdown("Enter a prompt below to run your custom ComfyUI workflow live.")
95
 
96
  with gr.Row():
97
  with gr.Column():
 
10
  import spaces
11
 
12
  # ==========================================
13
+ # 1. Install Dependencies Natively at Startup
14
  # ==========================================
15
  required_packages = [
16
  "safetensors", "scipy", "tqdm", "psutil", "einops",
17
  "transformers", "tokenizers", "sentencepiece", "torchsde",
18
+ "huggingface-hub", "aiohttp", "yarl", "av", "blake3",
19
+ "sqlalchemy", "alembic", "comfy-aimdo"
20
  ]
21
 
22
+ print("Checking system requirements...")
23
  for package in required_packages:
24
  try:
25
  __import__(package.replace("-", "_"))
 
27
  print(f"Installing missing dependency: {package}")
28
  subprocess.run([sys.executable, "-m", "pip", "install", package], check=True)
29
 
30
+ # Ensure ComfyUI codebase is present
 
 
31
  COMFYUI_DIR = os.path.abspath("ComfyUI")
 
32
  if not os.path.exists(COMFYUI_DIR):
33
+ print("Cloning ComfyUI framework...")
34
  subprocess.run(["git", "clone", "https://github.com/comfyanonymous/ComfyUI.git", COMFYUI_DIR], check=True)
35
 
 
 
 
 
 
 
 
 
 
 
36
 
37
  # ==========================================
38
+ # 2. Dynamic GPU Inference Function
39
  # ==========================================
40
+ @spaces.GPU(duration=120) # Extended duration to account for boot + generation
41
  def generate_image(user_prompt):
42
  if not os.path.exists("workflow_api.json"):
43
+ print("Error: workflow_api.json missing from root directory.")
44
  return None
45
 
46
  with open("workflow_api.json", "r") as f:
47
  prompt_workflow = json.load(f)
48
 
49
+ # Inject your prompt layout (Verify if '6' matches your CLIP Text Encode node ID)
50
  if "6" in prompt_workflow and "inputs" in prompt_workflow["6"]:
51
  prompt_workflow["6"]["inputs"]["text"] = user_prompt
52
 
53
+ # Clear out any previous remnants in the output directory to avoid old file matching
54
+ output_dir = os.path.join(COMFYUI_DIR, "output")
55
+ if os.path.exists(output_dir):
56
+ for f in os.listdir(output_dir):
57
+ try:
58
+ os.remove(os.path.join(output_dir, f))
59
+ except Exception:
60
+ pass
61
+
62
+ # Launch ComfyUI inside the GPU environment so it inherits the allocated CUDA device
63
+ print("ZeroGPU allocated. Launching ComfyUI server instance...")
64
+ comfy_process = subprocess.Popen(
65
+ [sys.executable, os.path.join(COMFYUI_DIR, "main.py"), "--listen", "127.0.0.1", "--port", "8188", "--highvram"],
66
+ stdout=subprocess.PIPE,
67
+ stderr=subprocess.STDOUT,
68
+ text=True
69
+ )
70
+
71
+ # Poll local port until the server is alive and ready to receive API inputs
72
+ server_ready = False
73
+ for _ in range(20):
74
+ time.sleep(1)
75
+ try:
76
+ with urllib.request.urlopen("http://127.0.0.1:8188/history", timeout=1) as r:
77
+ if r.status == 200:
78
+ server_ready = True
79
+ break
80
+ except Exception:
81
+ continue
82
+
83
+ if not server_ready:
84
+ print("ComfyUI server failed to initialize within time constraints.")
85
+ comfy_process.terminate()
86
+ return None
87
+
88
+ # Enqueue the workflow configuration payload
89
+ print("Server online. Enqueueing workflow...")
90
  p = {"prompt": prompt_workflow}
91
  data = json.dumps(p).encode('utf-8')
92
  req = urllib.request.Request("http://127.0.0.1:8188/prompt", data=data, headers={'Content-Type': 'application/json'})
 
94
  try:
95
  with urllib.request.urlopen(req) as response:
96
  res = json.loads(response.read().decode('utf-8'))
97
+ print(f"Workflow running. Prompt ID: {res['prompt_id']}")
 
98
  except Exception as e:
99
+ print(f"API execution dispatch failed: {e}")
100
+ comfy_process.terminate()
101
  return None
102
 
103
+ # Track output directory for the newly compiled image asset
104
+ generated_image_path = None
105
+ for _ in range(90): # Allow up to 90 seconds for execution processing
106
  time.sleep(1)
107
  if os.path.exists(output_dir):
108
  files = [os.path.join(output_dir, f) for f in os.listdir(output_dir) if os.path.isfile(os.path.join(output_dir, f))]
109
  if files:
110
+ generated_image_path = max(files, key=os.path.getmtime)
111
+ print(f"Asset generation complete: {generated_image_path}")
112
+ break
113
+
114
+ # Clean up the server process gracefully to free resources
115
+ comfy_process.terminate()
116
+ comfy_process.wait()
117
+
118
+ return generated_image_path
119
+
120
 
121
  # ==========================================
122
+ # 3. Gradio Web Interface Layout
123
  # ==========================================
124
  with gr.Blocks() as demo:
125
  gr.Markdown("# My Custom ComfyUI App")
126
+ gr.Markdown("Enter a prompt below to run your custom ComfyUI workflow live via ZeroGPU allocations.")
127
 
128
  with gr.Row():
129
  with gr.Column():