Defter77 commited on
Commit
c1657c7
·
verified ·
1 Parent(s): 18758d9

Upload app.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. app.py +57 -57
app.py CHANGED
@@ -12,7 +12,13 @@ import spaces
12
 
13
  # ComfyUI API endpoint - use localhost instead of 127.0.0.1
14
  COMFY_API = "http://localhost:8188/api"
15
- WORKFLOW_PATH = "/app/workflows/Workflow_12_11.json"
 
 
 
 
 
 
16
 
17
  # Load the workflow template
18
  try:
@@ -26,12 +32,21 @@ except Exception as e:
26
  def is_comfyui_running():
27
  """Check if ComfyUI server is running and accessible"""
28
  try:
29
- response = requests.get(f"{COMFY_API}/system_stats", timeout=5)
30
  return response.status_code == 200
31
  except Exception as e:
32
  print(f"ComfyUI server check failed: {str(e)}")
33
  return False
34
 
 
 
 
 
 
 
 
 
 
35
  def queue_prompt(prompt):
36
  """Send a prompt to ComfyUI for processing"""
37
  if not is_comfyui_running():
@@ -39,7 +54,7 @@ def queue_prompt(prompt):
39
 
40
  p = {"prompt": prompt}
41
  try:
42
- response = requests.post(f"{COMFY_API}/prompt", json=p, timeout=30)
43
  return response.json()
44
  except Exception as e:
45
  print(f"Error queuing prompt: {str(e)}")
@@ -51,7 +66,7 @@ def get_image(filename, subfolder, folder_type):
51
  return None
52
 
53
  try:
54
- response = requests.get(f"{COMFY_API}/view?filename={filename}&subfolder={subfolder}&type={folder_type}", timeout=30)
55
  return Image.open(io.BytesIO(response.content))
56
  except Exception as e:
57
  print(f"Error getting image {filename}: {str(e)}")
@@ -70,13 +85,18 @@ def upload_image(image, filename):
70
  if isinstance(image, np.ndarray):
71
  image = Image.fromarray(image)
72
 
 
 
 
 
 
73
  img_byte_arr = io.BytesIO()
74
- image.save(img_byte_arr, format='PNG')
75
  img_byte_arr.seek(0)
76
  files = {"image": (filename, img_byte_arr.getvalue())}
77
 
78
- # Use a longer timeout for uploading images
79
- response = requests.post(f"{COMFY_API}/upload/image", files=files, timeout=60)
80
  return response.json()
81
  except requests.exceptions.ConnectionError as e:
82
  error_msg = f"Connection error when uploading image: {str(e)}"
@@ -93,7 +113,7 @@ def check_progress(prompt_id):
93
  return {"error": "ComfyUI server is not running"}
94
 
95
  try:
96
- response = requests.get(f"{COMFY_API}/history/{prompt_id}", timeout=30)
97
  return response.json()
98
  except Exception as e:
99
  print(f"Error checking progress: {str(e)}")
@@ -102,8 +122,10 @@ def check_progress(prompt_id):
102
  @spaces.GPU
103
  def generate_avatar(player_image, pose_image, shirt_image, player_name, team_name, age_gender_bg, shirt_color, style):
104
  """Generate a football player avatar using ComfyUI workflow"""
 
105
  if not is_comfyui_running():
106
- return None, "Error: ComfyUI server is not running. Please try again later."
 
107
 
108
  # Upload images to ComfyUI
109
  print("Uploading player image...")
@@ -170,7 +192,7 @@ def generate_avatar(player_image, pose_image, shirt_image, player_name, team_nam
170
  # Wait for the processing to complete
171
  status = "Generating avatar..."
172
  retries = 0
173
- max_retries = 60 # 5 minutes timeout
174
 
175
  while retries < max_retries:
176
  time.sleep(5)
@@ -216,6 +238,18 @@ def create_interface():
216
  gr.Markdown("# Football Player Avatar Generator")
217
  gr.Markdown("Create stylized football player avatars from photos")
218
 
 
 
 
 
 
 
 
 
 
 
 
 
219
  with gr.Row():
220
  with gr.Column():
221
  player_image = gr.Image(label="Upload Player Photo", type="pil")
@@ -246,32 +280,20 @@ def create_interface():
246
  ]
247
  style = gr.Dropdown(label="Art Style", choices=style_options, value=style_options[0])
248
 
 
 
 
 
249
  generate_button = gr.Button("Generate Avatar", variant="primary")
250
 
251
  with gr.Column():
252
  output_image = gr.Image(label="Generated Avatar")
253
  status_text = gr.Textbox(label="Status", interactive=False)
254
-
255
- # Add ComfyUI status indicator
256
- comfy_status = gr.Textbox(label="ComfyUI Server Status", interactive=False)
257
- check_comfy_button = gr.Button("Check ComfyUI Server Status")
258
-
259
- def check_comfy_server():
260
- if is_comfyui_running():
261
- return "✅ ComfyUI server is running"
262
- else:
263
- return "❌ ComfyUI server is not running"
264
-
265
- check_comfy_button.click(
266
- fn=check_comfy_server,
267
- inputs=[],
268
- outputs=[comfy_status]
269
- )
270
 
271
  # Load default images for pose and shirt
272
  try:
273
- default_pose = Image.open("/app/ComfyUI/input/pose4.jpg")
274
- default_shirt = Image.open("/app/ComfyUI/input/paita2.jpg")
275
  pose_image.value = default_pose
276
  shirt_image.value = default_shirt
277
  except Exception as e:
@@ -285,11 +307,11 @@ def create_interface():
285
  )
286
 
287
  # Add examples
288
- if os.path.exists("/app/ComfyUI/input"):
289
  example_images = []
290
- for filename in os.listdir("/app/ComfyUI/input"):
291
  if filename.lower().endswith(('.png', '.jpg', '.jpeg')):
292
- example_images.append(os.path.join("/app/ComfyUI/input", filename))
293
 
294
  if example_images:
295
  gr.Examples(
@@ -299,32 +321,10 @@ def create_interface():
299
 
300
  return demo
301
 
302
- # Check for ComfyUI server and launch the app
303
  if __name__ == "__main__":
304
- # Check if ComfyUI is running
305
- retry_count = 0
306
- max_retries = 12 # 2 minutes (10 seconds between retries)
307
- comfy_running = False
308
-
309
- while retry_count < max_retries and not comfy_running:
310
- try:
311
- print(f"Checking if ComfyUI is running (attempt {retry_count+1}/{max_retries})...")
312
- response = requests.get(f"{COMFY_API}/system_stats", timeout=5)
313
- if response.status_code == 200:
314
- print("ComfyUI is running, starting Gradio interface...")
315
- comfy_running = True
316
- break
317
- except Exception as e:
318
- print(f"ComfyUI check failed: {str(e)}")
319
-
320
- retry_count += 1
321
- print(f"Waiting for ComfyUI to start... (attempt {retry_count}/{max_retries})")
322
- time.sleep(10)
323
-
324
- if not comfy_running:
325
- print("WARNING: Could not connect to ComfyUI server. The application may not function correctly.")
326
- print("Starting Gradio interface anyway...")
327
-
328
- # Create and launch the interface
329
  demo = create_interface()
330
  demo.launch(server_name="0.0.0.0", server_port=7860, share=False)
 
12
 
13
  # ComfyUI API endpoint - use localhost instead of 127.0.0.1
14
  COMFY_API = "http://localhost:8188/api"
15
+
16
+ # Get workflow path from environment variable or use default
17
+ WORKFLOW_PATH = os.environ.get("WORKFLOW_PATH", "/tmp/workflows/Workflow_12_11.json")
18
+
19
+ # Input and output directories (configured in ComfyUI via start.sh)
20
+ INPUT_DIR = "/tmp/comfyui_input"
21
+ OUTPUT_DIR = "/tmp/comfyui_output"
22
 
23
  # Load the workflow template
24
  try:
 
32
  def is_comfyui_running():
33
  """Check if ComfyUI server is running and accessible"""
34
  try:
35
+ response = requests.get(f"{COMFY_API}/system_stats", timeout=2)
36
  return response.status_code == 200
37
  except Exception as e:
38
  print(f"ComfyUI server check failed: {str(e)}")
39
  return False
40
 
41
+ def wait_for_comfyui(timeout=60):
42
+ """Wait for ComfyUI to be available, with a timeout"""
43
+ start_time = time.time()
44
+ while time.time() - start_time < timeout:
45
+ if is_comfyui_running():
46
+ return True
47
+ time.sleep(2)
48
+ return False
49
+
50
  def queue_prompt(prompt):
51
  """Send a prompt to ComfyUI for processing"""
52
  if not is_comfyui_running():
 
54
 
55
  p = {"prompt": prompt}
56
  try:
57
+ response = requests.post(f"{COMFY_API}/prompt", json=p, timeout=10)
58
  return response.json()
59
  except Exception as e:
60
  print(f"Error queuing prompt: {str(e)}")
 
66
  return None
67
 
68
  try:
69
+ response = requests.get(f"{COMFY_API}/view?filename={filename}&subfolder={subfolder}&type={folder_type}", timeout=10)
70
  return Image.open(io.BytesIO(response.content))
71
  except Exception as e:
72
  print(f"Error getting image {filename}: {str(e)}")
 
85
  if isinstance(image, np.ndarray):
86
  image = Image.fromarray(image)
87
 
88
+ # Resize image if it's too large
89
+ max_size = (1024, 1024)
90
+ if image.width > max_size[0] or image.height > max_size[1]:
91
+ image.thumbnail(max_size, Image.LANCZOS)
92
+
93
  img_byte_arr = io.BytesIO()
94
+ image.save(img_byte_arr, format='PNG', optimize=True)
95
  img_byte_arr.seek(0)
96
  files = {"image": (filename, img_byte_arr.getvalue())}
97
 
98
+ # Use a shorter timeout for uploading images
99
+ response = requests.post(f"{COMFY_API}/upload/image", files=files, timeout=20)
100
  return response.json()
101
  except requests.exceptions.ConnectionError as e:
102
  error_msg = f"Connection error when uploading image: {str(e)}"
 
113
  return {"error": "ComfyUI server is not running"}
114
 
115
  try:
116
+ response = requests.get(f"{COMFY_API}/history/{prompt_id}", timeout=10)
117
  return response.json()
118
  except Exception as e:
119
  print(f"Error checking progress: {str(e)}")
 
122
  @spaces.GPU
123
  def generate_avatar(player_image, pose_image, shirt_image, player_name, team_name, age_gender_bg, shirt_color, style):
124
  """Generate a football player avatar using ComfyUI workflow"""
125
+ # First check if ComfyUI is running
126
  if not is_comfyui_running():
127
+ if not wait_for_comfyui(timeout=30):
128
+ return None, "Error: ComfyUI server is not available. Please try again in a few minutes."
129
 
130
  # Upload images to ComfyUI
131
  print("Uploading player image...")
 
192
  # Wait for the processing to complete
193
  status = "Generating avatar..."
194
  retries = 0
195
+ max_retries = 30 # Reduce timeout to 2.5 minutes
196
 
197
  while retries < max_retries:
198
  time.sleep(5)
 
238
  gr.Markdown("# Football Player Avatar Generator")
239
  gr.Markdown("Create stylized football player avatars from photos")
240
 
241
+ # Add ComfyUI status indicator at the top
242
+ comfy_status = gr.Textbox(label="ComfyUI Server Status", interactive=False, value="Checking...")
243
+
244
+ def check_comfy_server():
245
+ if is_comfyui_running():
246
+ return "✅ ComfyUI server is running"
247
+ else:
248
+ return "❌ ComfyUI server is not running - the app may not work correctly"
249
+
250
+ # Auto-check status when loading
251
+ demo.load(fn=check_comfy_server, outputs=comfy_status)
252
+
253
  with gr.Row():
254
  with gr.Column():
255
  player_image = gr.Image(label="Upload Player Photo", type="pil")
 
280
  ]
281
  style = gr.Dropdown(label="Art Style", choices=style_options, value=style_options[0])
282
 
283
+ # Add manual server check button
284
+ check_comfy_button = gr.Button("Check ComfyUI Server Status")
285
+ check_comfy_button.click(fn=check_comfy_server, outputs=comfy_status)
286
+
287
  generate_button = gr.Button("Generate Avatar", variant="primary")
288
 
289
  with gr.Column():
290
  output_image = gr.Image(label="Generated Avatar")
291
  status_text = gr.Textbox(label="Status", interactive=False)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
292
 
293
  # Load default images for pose and shirt
294
  try:
295
+ default_pose = Image.open(os.path.join(INPUT_DIR, "pose4.jpg"))
296
+ default_shirt = Image.open(os.path.join(INPUT_DIR, "paita2.jpg"))
297
  pose_image.value = default_pose
298
  shirt_image.value = default_shirt
299
  except Exception as e:
 
307
  )
308
 
309
  # Add examples
310
+ if os.path.exists(INPUT_DIR):
311
  example_images = []
312
+ for filename in os.listdir(INPUT_DIR):
313
  if filename.lower().endswith(('.png', '.jpg', '.jpeg')):
314
+ example_images.append(os.path.join(INPUT_DIR, filename))
315
 
316
  if example_images:
317
  gr.Examples(
 
321
 
322
  return demo
323
 
324
+ # Start the app
325
  if __name__ == "__main__":
326
+ # Create and launch the interface without waiting for ComfyUI
327
+ # The interface will handle ComfyUI availability checks when needed
328
+ print("Starting Gradio interface...")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
329
  demo = create_interface()
330
  demo.launch(server_name="0.0.0.0", server_port=7860, share=False)