This repository was archived by the owner on Dec 26, 2025. It is now read-only.
forked from pschroedl/StreamDiffusion
-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathmain.py
More file actions
3255 lines (2726 loc) · 167 KB
/
Copy pathmain.py
File metadata and controls
3255 lines (2726 loc) · 167 KB
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
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from fastapi import FastAPI, WebSocket, HTTPException, WebSocketDisconnect, UploadFile, File, Response
from fastapi.responses import StreamingResponse, JSONResponse
from fastapi.middleware.cors import CORSMiddleware
from fastapi.staticfiles import StaticFiles
from fastapi import Request
import markdown2
import logging
import uuid
import time
from types import SimpleNamespace
import asyncio
import os
import time
import mimetypes
import torch
import tempfile
from pathlib import Path
import yaml
from config import config, Args
from util import pil_to_frame, pt_to_frame, bytes_to_pil, bytes_to_pt
from connection_manager import ConnectionManager, ServerFullException
from img2img import Pipeline
from input_control import InputManager, GamepadInput
# fix mime error on windows
mimetypes.add_type("application/javascript", ".js")
THROTTLE = 1.0 / 120
def load_controlnet_registry():
"""Load ControlNet registry from YAML config file"""
try:
registry_path = Path(__file__).parent / "controlnet_registry.yaml"
with open(registry_path, 'r') as f:
config_data = yaml.safe_load(f)
# Extract the available_controlnets section
return config_data.get('available_controlnets', {})
except Exception as e:
logging.error(f"load_controlnet_registry: Failed to load ControlNet registry: {e}")
# Fallback to empty registry
return {}
def load_default_settings():
"""Load default settings from YAML config file"""
try:
registry_path = Path(__file__).parent / "controlnet_registry.yaml"
with open(registry_path, 'r') as f:
config_data = yaml.safe_load(f)
return config_data.get('defaults', {})
except Exception as e:
logging.error(f"load_default_settings: Failed to load default settings: {e}")
# Fallback to hardcoded defaults
return {
'guidance_scale': 1.1,
'delta': 0.7,
'num_inference_steps': 50,
'seed': 2,
't_index_list': [35, 45],
'ipadapter_scale': 1.0,
'normalize_prompt_weights': True,
'normalize_seed_weights': True,
'prompt': "Portrait of The Joker halloween costume, face painting, with , glare pose, detailed, intricate, full of colour, cinematic lighting, trending on artstation, 8k, hyperrealistic, focused, extreme details, unreal engine 5 cinematic, masterpiece"
}
# Load ControlNet registry from config file
AVAILABLE_CONTROLNETS = load_controlnet_registry()
DEFAULT_SETTINGS = load_default_settings()
# Configure logging
def setup_logging(log_level: str = "INFO"):
"""Setup logging configuration for the application"""
# Convert string to logging level
numeric_level = getattr(logging, log_level.upper(), logging.INFO)
# Configure root logger
logging.basicConfig(
level=numeric_level,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
datefmt='%Y-%m-%d %H:%M:%S'
)
# Set up logger for streamdiffusion modules
streamdiffusion_logger = logging.getLogger('streamdiffusion')
streamdiffusion_logger.setLevel(numeric_level)
# Set up logger for this application
app_logger = logging.getLogger('realtime_img2img')
app_logger.setLevel(numeric_level)
return app_logger
# Initialize logger
logger = setup_logging(config.log_level)
class App:
def __init__(self, config: Args):
self.args = config
self.pipeline = None # Pipeline created lazily when needed
self.app = FastAPI()
self.conn_manager = ConnectionManager()
self.fps_counter = []
self.last_fps_update = time.time()
# Store uploaded ControlNet config separately
self.uploaded_controlnet_config = None
self.runtime_controlnet_config = None # Active runtime config (starts from YAML)
self.config_needs_reload = False # Track when pipeline needs recreation
# Store current resolution for pipeline recreation
self.new_width = 512
self.new_height = 512
# Store uploaded style image persistently
self.uploaded_style_image = None
# Initialize input manager for controller support
self.input_manager = InputManager()
self.init_app()
def cleanup(self):
"""Cleanup resources when app is shutting down"""
logger.info("App cleanup: Starting application cleanup...")
if self.pipeline:
self._cleanup_pipeline(self.pipeline)
self.pipeline = None
logger.info("App cleanup: Completed application cleanup")
def _handle_input_parameter_update(self, parameter_name: str, value: float) -> None:
"""Handle parameter updates from input controls"""
try:
if not self.pipeline or not hasattr(self.pipeline, 'stream'):
logger.warning(f"_handle_input_parameter_update: No pipeline available for parameter {parameter_name}")
return
# Map parameter names to pipeline update methods
if parameter_name == 'guidance_scale':
self.pipeline.update_stream_params(guidance_scale=value)
elif parameter_name == 'delta':
self.pipeline.update_stream_params(delta=value)
elif parameter_name == 'num_inference_steps':
self.pipeline.update_stream_params(num_inference_steps=int(value))
elif parameter_name == 'seed':
self.pipeline.update_stream_params(seed=int(value))
elif parameter_name == 'ipadapter_scale':
self.pipeline.update_stream_params(ipadapter_config={'scale': value})
elif parameter_name == 'ipadapter_weight_type':
# For weight type, we need to convert the numeric value to a string
weight_types = ["linear", "ease in", "ease out", "ease in-out", "reverse in-out",
"weak input", "weak output", "weak middle", "strong middle",
"style transfer", "composition", "strong style transfer",
"style and composition", "style transfer precise", "composition precise"]
index = int(value) % len(weight_types)
self.pipeline.update_ipadapter_weight_type(weight_types[index])
elif parameter_name.startswith('controlnet_') and parameter_name.endswith('_strength'):
# Handle ControlNet strength parameters
import re
match = re.match(r'controlnet_(\d+)_strength', parameter_name)
if match:
index = int(match.group(1))
# Use existing ControlNet strength update logic
current_config = self._get_current_controlnet_config()
if current_config and index < len(current_config):
current_config[index]['conditioning_scale'] = float(value)
# Apply the updated config via unified API
self.pipeline.update_stream_params(controlnet_config=current_config)
elif parameter_name.startswith('controlnet_') and '_preprocessor_' in parameter_name:
# Handle ControlNet preprocessor parameters
match = re.match(r'controlnet_(\d+)_preprocessor_(.+)', parameter_name)
if match:
controlnet_index = int(match.group(1))
param_name = match.group(2)
# Use the same approach as the API endpoint
current_config = self._get_current_controlnet_config()
if current_config and controlnet_index < len(current_config):
# Update preprocessor_params for the specified controlnet
if 'preprocessor_params' not in current_config[controlnet_index]:
current_config[controlnet_index]['preprocessor_params'] = {}
current_config[controlnet_index]['preprocessor_params'][param_name] = value
self.pipeline.update_stream_params(controlnet_config=current_config)
elif parameter_name.startswith('prompt_weight_'):
# Handle prompt blending weights
match = re.match(r'prompt_weight_(\d+)', parameter_name)
if match:
index = int(match.group(1))
# Get current prompt list from unified state and update specific weight
state = self.pipeline.stream.get_stream_state()
current_prompts = state.get('prompt_list', [])
if current_prompts and index < len(current_prompts):
updated_prompts = list(current_prompts)
updated_prompts[index] = (updated_prompts[index][0], float(value))
self.pipeline.update_stream_params(prompt_list=updated_prompts)
elif parameter_name.startswith('seed_weight_'):
# Handle seed blending weights
match = re.match(r'seed_weight_(\d+)', parameter_name)
if match:
index = int(match.group(1))
# Get current seed list from unified state and update specific weight
state = self.pipeline.stream.get_stream_state()
current_seeds = state.get('seed_list', [])
if current_seeds and index < len(current_seeds):
updated_seeds = list(current_seeds)
updated_seeds[index] = (updated_seeds[index][0], float(value))
self.pipeline.update_stream_params(seed_list=updated_seeds)
else:
logger.warning(f"_handle_input_parameter_update: Unknown parameter {parameter_name}")
logger.info(f"_handle_input_parameter_update: Updated {parameter_name} to {value}")
except Exception as e:
logger.error(f"_handle_input_parameter_update: Failed to update {parameter_name}: {e}")
def _get_controlnet_pipeline(self):
"""Get the ControlNet pipeline from the main pipeline structure"""
if not self.pipeline:
return None
stream = self.pipeline.stream
# Module-aware: module installs expose preprocessors on stream
if hasattr(stream, 'preprocessors'):
return stream
# Check if stream has nested stream (IPAdapter wrapper)
if hasattr(stream, 'stream') and hasattr(stream.stream, 'preprocessors'):
return stream.stream
# New module path on stream
if hasattr(stream, '_controlnet_module'):
return stream._controlnet_module
return None
def _get_current_controlnet_config(self):
"""Get the current ControlNet configuration state from the pipeline"""
cn_pipeline = self._get_controlnet_pipeline()
if not cn_pipeline or not hasattr(cn_pipeline, 'controlnets'):
return []
current_config = []
for i, controlnet in enumerate(cn_pipeline.controlnets):
model_id = getattr(controlnet, 'model_id', f'controlnet_{i}')
scale = cn_pipeline.controlnet_scales[i] if hasattr(cn_pipeline, 'controlnet_scales') and i < len(cn_pipeline.controlnet_scales) else 1.0
config = {
'model_id': model_id,
'conditioning_scale': scale,
'preprocessor': getattr(cn_pipeline.preprocessors[i], '__class__.__name__', '').replace('Preprocessor', '').lower() if cn_pipeline.preprocessors[i] else None,
'enabled': True,
'preprocessor_params': getattr(cn_pipeline.preprocessors[i], 'params', {}) if cn_pipeline.preprocessors[i] else {}
}
current_config.append(config)
return current_config
def init_app(self):
# Enhanced CORS for API-only development mode
if self.args.api_only:
# More permissive CORS for development
self.app.add_middleware(
CORSMiddleware,
allow_origins=["http://localhost:5173", "http://127.0.0.1:5173", "*"], # Include common Vite dev ports
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
else:
# Standard CORS for production
self.app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# Set up input manager callback for parameter updates
self.input_manager.set_parameter_update_callback(self._handle_input_parameter_update)
@self.app.websocket("/api/ws/{user_id}")
async def websocket_endpoint(user_id: uuid.UUID, websocket: WebSocket):
try:
await self.conn_manager.connect(
user_id, websocket, self.args.max_queue_size
)
await handle_websocket_data(user_id)
except ServerFullException as e:
logging.error(f"Server Full: {e}")
finally:
await self.conn_manager.disconnect(user_id)
logging.info(f"User disconnected: {user_id}")
async def handle_websocket_data(user_id: uuid.UUID):
if not self.conn_manager.check_user(user_id):
return HTTPException(status_code=404, detail="User not found")
last_time = time.time()
try:
while True:
if (
self.args.timeout > 0
and time.time() - last_time > self.args.timeout
):
await self.conn_manager.send_json(
user_id,
{
"status": "timeout",
"message": "Your session has ended",
},
)
await self.conn_manager.disconnect(user_id)
return
data = await self.conn_manager.receive_json(user_id)
if data is None:
break
if data["status"] == "next_frame":
params = await self.conn_manager.receive_json(user_id)
params = Pipeline.InputParams(**params)
params = SimpleNamespace(**params.dict())
# Check if we need image data based on pipeline
need_image = True
if self.pipeline and hasattr(self.pipeline, 'pipeline_mode'):
# Need image for img2img OR for txt2img with ControlNets
has_controlnets = self.pipeline.use_config and self.pipeline.config and 'controlnets' in self.pipeline.config
need_image = self.pipeline.pipeline_mode == "img2img" or has_controlnets
elif self.uploaded_controlnet_config and 'mode' in self.uploaded_controlnet_config:
# Need image for img2img OR for txt2img with ControlNets
has_controlnets = 'controlnets' in self.uploaded_controlnet_config
need_image = self.uploaded_controlnet_config['mode'] == "img2img" or has_controlnets
if need_image:
image_data = await self.conn_manager.receive_bytes(user_id)
if len(image_data) == 0:
await self.conn_manager.send_json(
user_id, {"status": "send_frame"}
)
continue
# Always use direct bytes-to-tensor conversion for efficiency
params.image = bytes_to_pt(image_data)
else:
params.image = None
await self.conn_manager.update_data(user_id, params)
except Exception as e:
logging.error(f"Websocket Error: {e}, {user_id} ")
await self.conn_manager.disconnect(user_id)
@self.app.get("/api/queue")
async def get_queue_size():
queue_size = self.conn_manager.get_user_count()
return JSONResponse({"queue_size": queue_size})
@self.app.get("/api/stream/{user_id}")
async def stream(user_id: uuid.UUID, request: Request):
try:
# Create pipeline if it doesn't exist yet
if self.pipeline is None:
if self.uploaded_controlnet_config:
logger.info("stream: Creating pipeline with ControlNet config...")
self.pipeline = self._create_pipeline_with_config()
else:
logger.info("stream: Creating default pipeline...")
self.pipeline = self._create_default_pipeline()
logger.info("stream: Pipeline created successfully")
try:
acc = getattr(self.args, 'acceleration', None)
logger.debug(f"stream: acceleration={acc}, use_config={getattr(self.pipeline, 'use_config', False)}")
stream_obj = getattr(self.pipeline, 'stream', None)
unet_obj = getattr(stream_obj, 'unet', None)
is_trt = unet_obj is not None and hasattr(unet_obj, 'engine') and hasattr(unet_obj, 'stream')
logger.debug(f"stream: unet_is_trt={is_trt}, has_ipadapter={getattr(self.pipeline, 'has_ipadapter', False)}")
if is_trt:
logger.debug(f"stream: unet.use_ipadapter={getattr(unet_obj, 'use_ipadapter', None)}, num_ip_layers={getattr(unet_obj, 'num_ip_layers', None)}")
if hasattr(stream_obj, 'ipadapter_scale'):
try:
scale_val = getattr(stream_obj, 'ipadapter_scale')
if hasattr(scale_val, 'shape'):
logger.debug(f"stream: ipadapter_scale tensor shape={tuple(scale_val.shape)}")
else:
logger.debug(f"stream: ipadapter_scale scalar={scale_val}")
except Exception:
pass
logger.debug(f"stream: ipadapter_weight_type={getattr(stream_obj, 'ipadapter_weight_type', None)}")
except Exception:
logger.exception("stream: failed to log pipeline state after creation")
# Recreate pipeline if config changed (but not resolution - that's handled separately)
elif self.config_needs_reload or (self.uploaded_controlnet_config and not (self.pipeline.use_config and self.pipeline.config and 'controlnets' in self.pipeline.config)) or (self.uploaded_controlnet_config and not self.pipeline.use_config):
if self.config_needs_reload:
logger.info("stream: Recreating pipeline with new ControlNet config...")
else:
logger.info("stream: Upgrading to ControlNet pipeline...")
# Properly cleanup the old pipeline before creating new one
old_pipeline = self.pipeline
self.pipeline = None
if old_pipeline:
self._cleanup_pipeline(old_pipeline)
old_pipeline = None
# Create new pipeline
if self.uploaded_controlnet_config:
self.pipeline = self._create_pipeline_with_config()
else:
self.pipeline = self._create_default_pipeline()
self.config_needs_reload = False # Reset the flag
logger.info("stream: Pipeline recreated successfully")
async def generate():
while True:
frame_start_time = time.time()
await self.conn_manager.send_json(
user_id, {"status": "send_frame"}
)
params = await self.conn_manager.get_latest_data(user_id)
if params is None:
continue
try:
try:
stream_obj = getattr(self.pipeline, 'stream', None)
unet_obj = getattr(stream_obj, 'unet', None)
is_trt = unet_obj is not None and hasattr(unet_obj, 'engine') and hasattr(unet_obj, 'stream')
logger.debug(f"generate: calling predict; acceleration={getattr(self.args, 'acceleration', None)}, is_trt={is_trt}, mode={getattr(self.pipeline, 'pipeline_mode', None)}, has_ipadapter={getattr(self.pipeline, 'has_ipadapter', False)}, has_controlnet={(self.pipeline.use_config and self.pipeline.config and 'controlnets' in self.pipeline.config) if getattr(self.pipeline, 'use_config', False) else False}")
img = getattr(params, 'image', None)
if isinstance(img, torch.Tensor):
logger.debug(f"generate: params.image tensor shape={tuple(img.shape)}, dtype={img.dtype}")
else:
logger.debug(f"generate: params.image type={type(img).__name__}")
if is_trt:
logger.debug(f"generate: unet.use_ipadapter={getattr(unet_obj, 'use_ipadapter', None)}, num_ip_layers={getattr(unet_obj, 'num_ip_layers', None)}")
try:
base_scale = getattr(stream_obj, 'ipadapter_scale', None)
if base_scale is not None:
if hasattr(base_scale, 'shape'):
logger.debug(f"generate: base ipadapter_scale shape={tuple(base_scale.shape)}")
else:
logger.debug(f"generate: base ipadapter_scale scalar={base_scale}")
logger.debug(f"generate: ipadapter_weight_type={getattr(stream_obj, 'ipadapter_weight_type', None)}")
except Exception:
pass
except Exception:
logger.exception("generate: pre-predict logging failed")
image = self.pipeline.predict(params)
if image is None:
logger.error("generate: predict returned None image; skipping frame")
continue
# Use appropriate frame conversion based on output type
if self.pipeline.output_type == "pt":
frame = pt_to_frame(image)
else:
frame = pil_to_frame(image)
except Exception as e:
logger.exception(f"generate: predict failed with exception: {e}")
continue
# Update FPS counter
frame_time = time.time() - frame_start_time
self.fps_counter.append(frame_time)
if len(self.fps_counter) > 30: # Keep last 30 frames
self.fps_counter.pop(0)
yield frame
if self.args.debug:
logger.debug(f"Time taken: {time.time() - frame_start_time}")
# Add delay for testing - 1 frame per second
# await asyncio.sleep(1.0)
return StreamingResponse(
generate(),
media_type="multipart/x-mixed-replace;boundary=frame",
headers={"Cache-Control": "no-cache"},
)
except Exception as e:
logging.error(f"Streaming Error: {e}, {user_id} ")
return HTTPException(status_code=404, detail="User not found")
# route to setup frontend
@self.app.get("/api/settings")
async def settings():
# Use Pipeline class directly for schema info (doesn't require instance)
info_schema = Pipeline.Info.schema()
info = Pipeline.Info()
if info.page_content:
page_content = markdown2.markdown(info.page_content)
input_params = Pipeline.InputParams.schema()
# Add ControlNet information
controlnet_info = self._get_controlnet_info()
# Add IPAdapter information
ipadapter_info = self._get_ipadapter_info()
# Add LoRA information
lora_info = self._get_lora_info()
# Include config prompt if available, otherwise use default
config_prompt = None
if self.uploaded_controlnet_config and 'prompt' in self.uploaded_controlnet_config:
config_prompt = self.uploaded_controlnet_config['prompt']
elif not config_prompt:
config_prompt = DEFAULT_SETTINGS.get('prompt')
# Get current t_index_list from pipeline or config
current_t_index_list = None
if self.pipeline and hasattr(self.pipeline.stream, 't_list'):
current_t_index_list = self.pipeline.stream.t_list
elif self.uploaded_controlnet_config and 't_index_list' in self.uploaded_controlnet_config:
current_t_index_list = self.uploaded_controlnet_config['t_index_list']
else:
# Default values
current_t_index_list = DEFAULT_SETTINGS.get('t_index_list', [35, 45])
# Get current acceleration setting
current_acceleration = self.args.acceleration
# Get current resolution
current_resolution = f"{self.new_width}x{self.new_height}"
# Add aspect ratio for display
aspect_ratio = self._calculate_aspect_ratio(self.new_width, self.new_height)
if aspect_ratio:
current_resolution += f" ({aspect_ratio})"
if self.uploaded_controlnet_config and 'acceleration' in self.uploaded_controlnet_config:
current_acceleration = self.uploaded_controlnet_config['acceleration']
# Get current streaming parameters (default values or from pipeline if available)
current_guidance_scale = DEFAULT_SETTINGS.get('guidance_scale', 1.1)
current_delta = DEFAULT_SETTINGS.get('delta', 0.7)
current_num_inference_steps = DEFAULT_SETTINGS.get('num_inference_steps', 50)
current_seed = DEFAULT_SETTINGS.get('seed', 2)
# Negative prompt (for UI)
current_negative_prompt = DEFAULT_SETTINGS.get('negative_prompt', '')
if self.pipeline and hasattr(self.pipeline.stream, 'get_stream_state'):
state = self.pipeline.stream.get_stream_state()
current_guidance_scale = state.get('guidance_scale', DEFAULT_SETTINGS.get('guidance_scale', 1.1))
current_delta = state.get('delta', DEFAULT_SETTINGS.get('delta', 0.7))
current_num_inference_steps = state.get('num_inference_steps', DEFAULT_SETTINGS.get('num_inference_steps', 50))
current_seed = state.get('current_seed', DEFAULT_SETTINGS.get('seed', 2))
# try to get negative prompt from pipeline if available
try:
current_negative_prompt = getattr(self.pipeline, 'negative_prompt', current_negative_prompt)
except Exception:
pass
elif self.uploaded_controlnet_config:
current_guidance_scale = self.uploaded_controlnet_config.get('guidance_scale', DEFAULT_SETTINGS.get('guidance_scale', 1.1))
current_delta = self.uploaded_controlnet_config.get('delta', DEFAULT_SETTINGS.get('delta', 0.7))
current_num_inference_steps = self.uploaded_controlnet_config.get('num_inference_steps', DEFAULT_SETTINGS.get('num_inference_steps', 50))
current_seed = self.uploaded_controlnet_config.get('seed', DEFAULT_SETTINGS.get('seed', 2))
current_negative_prompt = self.uploaded_controlnet_config.get('negative_prompt', current_negative_prompt)
# Get prompt and seed blending configuration from uploaded config or pipeline
prompt_blending_config = None
seed_blending_config = None
# First try to get from current pipeline if available
if self.pipeline and hasattr(self.pipeline.stream, 'get_stream_state'):
state = self.pipeline.stream.get_stream_state()
current_prompts = state.get('prompt_list', [])
current_seeds = state.get('seed_list', [])
if current_prompts:
prompt_blending_config = current_prompts
if current_seeds:
seed_blending_config = current_seeds
# If not available from pipeline, get from uploaded config and normalize
if not prompt_blending_config:
prompt_blending_config = self._normalize_prompt_config(self.uploaded_controlnet_config)
if not seed_blending_config:
seed_blending_config = self._normalize_seed_config(self.uploaded_controlnet_config)
# Get current normalize weights settings
normalize_prompt_weights = True # default
normalize_seed_weights = True # default
if self.pipeline and hasattr(self.pipeline.stream, 'get_stream_state'):
state = self.pipeline.stream.get_stream_state()
normalize_prompt_weights = state.get('normalize_prompt_weights', True)
normalize_seed_weights = state.get('normalize_seed_weights', True)
elif self.uploaded_controlnet_config:
normalize_prompt_weights = self.uploaded_controlnet_config.get('normalize_weights', True)
normalize_seed_weights = self.uploaded_controlnet_config.get('normalize_weights', True)
# Get current skip_diffusion setting
current_skip_diffusion = False # default
if self.pipeline and hasattr(self.pipeline, 'stream') and hasattr(self.pipeline.stream, 'skip_diffusion'):
current_skip_diffusion = self.pipeline.stream.skip_diffusion
elif self.uploaded_controlnet_config:
current_skip_diffusion = self.uploaded_controlnet_config.get('skip_diffusion', False)
# Determine current model id for UI badge
model_id_for_ui = ''
if self.pipeline and hasattr(self.pipeline, 'config') and self.pipeline.config:
model_id_for_ui = self.pipeline.config.get('model_id', '')
elif self.uploaded_controlnet_config and 'model_id' in self.uploaded_controlnet_config:
model_id_for_ui = self.uploaded_controlnet_config['model_id']
else:
model_id_for_ui = DEFAULT_SETTINGS.get('model_id', '')
# Build config values for UI defaults from uploaded config
config_values = {}
if self.uploaded_controlnet_config:
for key in [
'prompt',
'negative_prompt',
'guidance_scale',
'delta',
'num_inference_steps',
'seed',
'frame_buffer_size',
'use_denoising_batch',
'use_lcm_lora',
'use_tiny_vae',
'use_taesd',
'cfg_type',
'safety_checker',
]:
if key in self.uploaded_controlnet_config:
config_values[key] = self.uploaded_controlnet_config[key]
return JSONResponse(
{
"info": info_schema,
"input_params": input_params,
"max_queue_size": self.args.max_queue_size,
"page_content": page_content if info.page_content else "",
"pipeline_active": bool(self.pipeline) and hasattr(self.pipeline, 'stream'),
"controlnet": controlnet_info,
"ipadapter": ipadapter_info,
"lora": lora_info,
"config_prompt": config_prompt,
"t_index_list": current_t_index_list,
"acceleration": current_acceleration,
"guidance_scale": current_guidance_scale,
"delta": current_delta,
"num_inference_steps": current_num_inference_steps,
"seed": current_seed,
"negative_prompt": current_negative_prompt,
"current_resolution": current_resolution,
"prompt_blending": prompt_blending_config,
"seed_blending": seed_blending_config,
"normalize_prompt_weights": normalize_prompt_weights,
"normalize_seed_weights": normalize_seed_weights,
"skip_diffusion": current_skip_diffusion,
"model_id": model_id_for_ui,
"config_values": config_values,
}
)
@self.app.post("/api/controlnet/upload-config")
async def upload_controlnet_config(file: UploadFile = File(...)):
"""Upload and load a new ControlNet YAML configuration"""
try:
if not file.filename.endswith(('.yaml', '.yml')):
raise HTTPException(status_code=400, detail="File must be a YAML file")
# Save uploaded file temporarily
content = await file.read()
# Parse YAML content
try:
config_data = yaml.safe_load(content.decode('utf-8'))
except yaml.YAMLError as e:
raise HTTPException(status_code=400, detail=f"Invalid YAML format: {str(e)}")
# YAML is source of truth - completely replace any runtime modifications
self.uploaded_controlnet_config = config_data
self.runtime_controlnet_config = None # Clear any runtime additions
self.config_needs_reload = True # Mark that pipeline needs recreation
logger.info(f"upload_controlnet_config: YAML uploaded - resetting ControlNet configuration to source of truth")
# Log IPAdapter configuration for debugging
# Get config prompt if available
config_prompt = config_data.get('prompt', None)
# Get negative prompt if available
config_negative_prompt = config_data.get('negative_prompt', None)
# Get t_index_list from config if available
t_index_list = config_data.get('t_index_list', DEFAULT_SETTINGS.get('t_index_list', [35, 45]))
# Get acceleration from config if available
config_acceleration = config_data.get('acceleration', self.args.acceleration)
# Get width and height from config if available
config_width = config_data.get('width', None)
config_height = config_data.get('height', None)
# Update resolution if width/height are specified in config
if config_width is not None and config_height is not None:
try:
# Validate resolution
if config_width % 64 != 0 or config_height % 64 != 0:
raise HTTPException(status_code=400, detail="Resolution must be multiples of 64")
if not (384 <= config_width <= 1024) or not (384 <= config_height <= 1024):
raise HTTPException(status_code=400, detail="Resolution must be between 384 and 1024")
# Update the resolution
self.new_width = config_width
self.new_height = config_height
logger.info(f"upload_controlnet_config: Updated resolution to {config_width}x{config_height}")
except Exception as e:
logging.error(f"upload_controlnet_config: Failed to update resolution: {e}")
# Don't fail the upload, just log the error
# Normalize prompt and seed configurations for frontend
normalized_prompt_blending = self._normalize_prompt_config(config_data)
normalized_seed_blending = self._normalize_seed_config(config_data)
# Debug logging
logger.debug(f"upload_controlnet_config: Raw prompt_blending in config: {config_data.get('prompt_blending', 'NOT FOUND')}")
logger.debug(f"upload_controlnet_config: Raw seed_blending in config: {config_data.get('seed_blending', 'NOT FOUND')}")
logger.debug(f"upload_controlnet_config: Normalized prompt blending: {normalized_prompt_blending}")
logger.debug(f"upload_controlnet_config: Normalized seed blending: {normalized_seed_blending}")
# Get other streaming parameters from config
config_guidance_scale = config_data.get('guidance_scale', 1.1)
config_delta = config_data.get('delta', 0.7)
config_num_inference_steps = config_data.get('num_inference_steps', 50)
config_seed = config_data.get('seed', 2)
# Get normalization settings
config_normalize_weights = config_data.get('normalize_weights', True)
# Calculate current resolution string for frontend
current_resolution = f"{self.new_width}x{self.new_height}"
aspect_ratio = self._calculate_aspect_ratio(self.new_width, self.new_height)
if aspect_ratio:
current_resolution += f" ({aspect_ratio})"
# Get updated IPAdapter info for response
response_ipadapter_info = self._get_ipadapter_info()
# Prepare config_values for UI defaults
config_values = {}
for key in [
'prompt',
'negative_prompt',
'guidance_scale',
'delta',
'num_inference_steps',
'seed',
'frame_buffer_size',
'use_denoising_batch',
'use_lcm_lora',
'use_tiny_vae',
'use_taesd',
'cfg_type',
'safety_checker',
]:
if key in config_data:
config_values[key] = config_data[key]
return JSONResponse({
"status": "success",
"message": "ControlNet configuration uploaded successfully",
"controls_updated": True, # Flag for frontend to update controls
"controlnet": self._get_controlnet_info(),
"ipadapter": response_ipadapter_info, # Include updated IPAdapter info
"config_prompt": config_prompt,
"negative_prompt": config_negative_prompt,
"model_id": config_data.get('model_id', ''),
"t_index_list": t_index_list,
"acceleration": config_acceleration,
"guidance_scale": config_guidance_scale,
"delta": config_delta,
"num_inference_steps": config_num_inference_steps,
"seed": config_seed,
"prompt_blending": normalized_prompt_blending,
"seed_blending": normalized_seed_blending,
"current_resolution": current_resolution, # Include updated resolution
"normalize_prompt_weights": config_normalize_weights,
"normalize_seed_weights": config_normalize_weights,
"config_values": config_values,
# Include pipeline hooks info
"image_preprocessing": self._get_hook_info("image_preprocessing"),
"image_postprocessing": self._get_hook_info("image_postprocessing"),
"latent_preprocessing": self._get_hook_info("latent_preprocessing"),
"latent_postprocessing": self._get_hook_info("latent_postprocessing"),
})
except Exception as e:
logging.error(f"upload_controlnet_config: Failed to upload config: {e}")
raise HTTPException(status_code=500, detail=f"Failed to upload configuration: {str(e)}")
@self.app.get("/api/controlnet/info")
async def get_controlnet_info():
"""Get current ControlNet configuration info"""
return JSONResponse({"controlnet": self._get_controlnet_info()})
@self.app.get("/api/blending/current")
async def get_current_blending_config():
"""Get current prompt and seed blending configurations"""
try:
if self.pipeline and hasattr(self.pipeline, 'stream') and hasattr(self.pipeline.stream, 'get_stream_state'):
state = self.pipeline.stream.get_stream_state(include_caches=False)
return JSONResponse({
"prompt_blending": state.get("prompt_list", []),
"seed_blending": state.get("seed_list", []),
"normalize_prompt_weights": state.get("normalize_prompt_weights", True),
"normalize_seed_weights": state.get("normalize_seed_weights", True),
"has_config": self.uploaded_controlnet_config is not None,
"pipeline_active": True
})
# Fallback to uploaded config normalization when pipeline not initialized
prompt_blending_config = self._normalize_prompt_config(self.uploaded_controlnet_config)
seed_blending_config = self._normalize_seed_config(self.uploaded_controlnet_config)
normalize_weights = self.uploaded_controlnet_config.get('normalize_weights', True) if self.uploaded_controlnet_config else True
return JSONResponse({
"prompt_blending": prompt_blending_config,
"seed_blending": seed_blending_config,
"normalize_prompt_weights": normalize_weights,
"normalize_seed_weights": normalize_weights,
"has_config": self.uploaded_controlnet_config is not None,
"pipeline_active": False
})
except Exception as e:
logging.error(f"get_current_blending_config: Failed to get blending config: {e}")
raise HTTPException(status_code=500, detail=f"Failed to get blending config: {str(e)}")
@self.app.post("/api/controlnet/update-strength")
async def update_controlnet_strength(request: Request):
"""Update ControlNet strength in real-time"""
try:
data = await request.json()
controlnet_index = data.get("index")
strength = data.get("strength")
if controlnet_index is None or strength is None:
raise HTTPException(status_code=400, detail="Missing index or strength parameter")
# Check if ControlNet is enabled using config system
if not self.pipeline:
raise HTTPException(status_code=400, detail="Pipeline is not initialized")
# Check if we're using config mode and have controlnets configured
controlnet_enabled = (self.pipeline.use_config and
self.pipeline.config and
'controlnets' in self.pipeline.config)
if not controlnet_enabled:
raise HTTPException(status_code=400, detail="ControlNet is not enabled")
# Update ControlNet strength using consolidated API
current_config = self._get_current_controlnet_config()
logger.info(f"update_controlnet_strength: Current config: {current_config}")
if controlnet_index >= len(current_config):
raise HTTPException(status_code=400, detail=f"ControlNet index {controlnet_index} out of range")
# Update only the conditioning_scale for the specified controlnet
old_strength = current_config[controlnet_index]['conditioning_scale']
current_config[controlnet_index]['conditioning_scale'] = float(strength)
logger.info(f"update_controlnet_strength: Updating ControlNet {controlnet_index} strength from {old_strength} to {strength}")
logger.info(f"update_controlnet_strength: Sending config: {current_config}")
self.pipeline.update_stream_params(controlnet_config=current_config)
logger.info(f"update_controlnet_strength: update_stream_params call completed")
return JSONResponse({
"status": "success",
"message": f"Updated ControlNet {controlnet_index} strength to {strength}"
})
except Exception as e:
logging.error(f"update_controlnet_strength: Failed to update strength: {e}")
raise HTTPException(status_code=500, detail=f"Failed to update strength: {str(e)}")
@self.app.get("/api/controlnet/available")
async def get_available_controlnets():
"""Get list of available ControlNets that can be added"""
try:
# Detect current model architecture to filter appropriate ControlNets
model_type = "sd15" # Default fallback
if self.pipeline and hasattr(self.pipeline, 'config') and self.pipeline.config:
# Try to determine model type from config
model_id = self.pipeline.config.get('model_id', '')
if 'sdxl' in model_id.lower() or 'xl' in model_id.lower():
model_type = "sdxl"
available = AVAILABLE_CONTROLNETS.get(model_type, [])
# Filter out already active ControlNets
current_controlnets = []
# Check runtime config first, then fall back to uploaded config
if self.runtime_controlnet_config and 'controlnets' in self.runtime_controlnet_config:
current_controlnets = [cn.get('model_id', '') for cn in self.runtime_controlnet_config['controlnets']]
elif self.uploaded_controlnet_config and 'controlnets' in self.uploaded_controlnet_config:
current_controlnets = [cn.get('model_id', '') for cn in self.uploaded_controlnet_config['controlnets']]
filtered_available = []
for cn in available:
if cn['model_id'] not in current_controlnets:
filtered_available.append(cn)
return JSONResponse({
"status": "success",
"available_controlnets": filtered_available,
"model_type": model_type
})
except Exception as e:
logging.error(f"get_available_controlnets: Failed to get available ControlNets: {e}")
raise HTTPException(status_code=500, detail=f"Failed to get available ControlNets: {str(e)}")
@self.app.post("/api/controlnet/add")
async def add_controlnet(request: Request):
"""Add a ControlNet from the predefined list"""
try:
data = await request.json()
controlnet_id = data.get("controlnet_id")
conditioning_scale = data.get("conditioning_scale", None)
if not controlnet_id:
raise HTTPException(status_code=400, detail="Missing controlnet_id parameter")
# Find the ControlNet definition
controlnet_def = None
for model_type, controlnets in AVAILABLE_CONTROLNETS.items():
for cn in controlnets:
if cn['id'] == controlnet_id:
controlnet_def = cn
break
if controlnet_def:
break
if not controlnet_def:
raise HTTPException(status_code=400, detail=f"ControlNet {controlnet_id} not found in registry")
# Use provided scale or default
if conditioning_scale is None:
conditioning_scale = controlnet_def['default_scale']
# Initialize runtime config from YAML if not already done
if self.runtime_controlnet_config is None:
if self.uploaded_controlnet_config:
# Copy from YAML (deep copy to avoid modifying original)
import copy
self.runtime_controlnet_config = copy.deepcopy(self.uploaded_controlnet_config)
else:
# Create minimal config if no YAML exists
self.runtime_controlnet_config = {'controlnets': []}
# Ensure controlnets key exists in runtime config
if 'controlnets' not in self.runtime_controlnet_config:
self.runtime_controlnet_config['controlnets'] = []
# Create new ControlNet entry
new_controlnet = {
'model_id': controlnet_def['model_id'],
'conditioning_scale': conditioning_scale,
'preprocessor': controlnet_def['default_preprocessor'],
'preprocessor_params': controlnet_def.get('preprocessor_params', {}),
'enabled': True
}
# Add to runtime config (not YAML)
self.runtime_controlnet_config['controlnets'].append(new_controlnet)
# Update pipeline using consolidated API
try:
current_config = self._get_current_controlnet_config()
current_config.append(new_controlnet)
self.pipeline.update_stream_params(controlnet_config=current_config)
logger.info(f"add_controlnet: Successfully added ControlNet using consolidated API")
except Exception as e:
logger.error(f"add_controlnet: Failed to add ControlNet: {e}")
# Mark for reload as fallback
self.config_needs_reload = True
logger.info(f"add_controlnet: Added {controlnet_def['name']} with scale {conditioning_scale}")
# Return updated ControlNet info immediately
updated_info = self._get_controlnet_info()
added_index = len(self.runtime_controlnet_config['controlnets']) - 1
return JSONResponse({
"status": "success",
"message": f"Added {controlnet_def['name']}",
"controlnet_index": added_index,
"controlnet_info": updated_info