diff --git a/canvas_node.py b/canvas_node.py index 8fb423b..b820c66 100644 --- a/canvas_node.py +++ b/canvas_node.py @@ -26,28 +26,38 @@ import io import sys import os -try: - from python.log_system import create_module_logger - - _module_logger = create_module_logger(__name__) - log_debug = _module_logger.debug - log_info = _module_logger.info - log_warn = _module_logger.warning - log_error = _module_logger.error - log_exception = _module_logger.exception - - log_info("Logger initialized for canvas_node") -except ImportError as e: +try: + from python.log_system import create_module_logger + + log = create_module_logger(__name__) + + log.info("Logger initialized for canvas_node") +except ImportError as e: print(f"Warning: Logger module not available: {e}") - def log_debug(*args): print("[DEBUG]", *args) - def log_info(*args): print("[INFO]", *args) - def log_warn(*args): print("[WARN]", *args) - def log_error(*args): print("[ERROR]", *args) - def log_exception(*args): - print("[ERROR]", *args) - traceback.print_exc() + class _FallbackLogger: + @staticmethod + def debug(*args, **kwargs): print("[DEBUG]", *args) + + @staticmethod + def info(*args, **kwargs): print("[INFO]", *args) + + @staticmethod + def warning(*args, **kwargs): print("[WARN]", *args) + + @staticmethod + def error(*args, **kwargs): print("[ERROR]", *args) + + @staticmethod + def exception(*args, **kwargs): + print("[ERROR]", *args) + traceback.print_exc() + + @staticmethod + def fatal(*args, **kwargs): print("[FATAL]", *args) + + log = _FallbackLogger() torch.set_float32_matmul_precision('high') @@ -85,7 +95,7 @@ class BiRefNet(torch.nn.Module): return [output] -class LayerForgeNode: +class LayerForgeNode: _canvas_data_storage = {} _storage_lock = threading.Lock() @@ -115,7 +125,7 @@ class LayerForgeNode: current_execution = self.get_execution_id() if current_execution != self.__class__._canvas_cache['last_execution_id']: - log_info(f"New execution detected: {current_execution}") + log.info(f"New execution detected: {current_execution}") self.__class__._canvas_cache['image'] = None self.__class__._canvas_cache['mask'] = None self.__class__._canvas_cache['last_execution_id'] = current_execution @@ -123,12 +133,12 @@ class LayerForgeNode: if persistent.get('image') is not None: self.__class__._canvas_cache['image'] = persistent['image'] - log_info("Restored image from persistent cache") + log.info("Restored image from persistent cache") if persistent.get('mask') is not None: self.__class__._canvas_cache['mask'] = persistent['mask'] - log_info("Restored mask from persistent cache") + log.info("Restored mask from persistent cache") except Exception as e: - log_error(f"Error restoring cache: {str(e)}") + log.error(f"Error restoring cache: {str(e)}") def get_execution_id(self): @@ -136,7 +146,7 @@ class LayerForgeNode: return str(int(time.time() * 1000)) except Exception as e: - log_error(f"Error getting execution ID: {str(e)}") + log.error(f"Error getting execution ID: {str(e)}") return None def update_persistent_cache(self): @@ -146,9 +156,9 @@ class LayerForgeNode: 'image': self.__class__._canvas_cache['image'], 'mask': self.__class__._canvas_cache['mask'] } - log_debug("Updated persistent cache") + log.debug("Updated persistent cache") except Exception as e: - log_error(f"Error updating persistent cache: {str(e)}") + log.error(f"Error updating persistent cache: {str(e)}") def track_data_flow(self, stage, status, data_info=None): @@ -158,9 +168,9 @@ class LayerForgeNode: 'status': status, 'data_info': data_info } - log_debug(f"Data Flow [{self.flow_id}] - Stage: {stage}, Status: {status}") + log.debug(f"Data Flow [{self.flow_id}] - Stage: {stage}, Status: {status}") if data_info: - log_debug(f"Data Info: {data_info}") + log.debug(f"Data Info: {data_info}") self.__class__._canvas_cache['data_flow_status'][self.flow_id] = flow_status @@ -205,7 +215,7 @@ class LayerForgeNode: return input_image except Exception as e: - log_error(f"Error in add_image_to_canvas: {str(e)}") + log.error(f"Error in add_image_to_canvas: {str(e)}") return None def add_mask_to_canvas(self, input_mask, input_image): @@ -233,7 +243,7 @@ class LayerForgeNode: return input_mask except Exception as e: - log_error(f"Error in add_mask_to_canvas: {str(e)}") + log.error(f"Error in add_mask_to_canvas: {str(e)}") return None _processing_lock = threading.Lock() @@ -243,14 +253,14 @@ class LayerForgeNode: try: if not self.__class__._processing_lock.acquire(blocking=False): - log_warn(f"Process already in progress for node {node_id}, skipping...") + log.warning(f"Process already in progress for node {node_id}, skipping...") return self.get_cached_data() - log_info(f"Lock acquired. Starting process_canvas_image for node_id: {node_id} (fallback unique_id: {unique_id})") + log.info(f"Lock acquired. Starting process_canvas_image for node_id: {node_id} (fallback unique_id: {unique_id})") # Always store fresh input data, even if None, to clear stale data - log_info(f"Storing input data for node {node_id} - Image: {input_image is not None}, Mask: {input_mask is not None}") + log.info(f"Storing input data for node {node_id} - Image: {input_image is not None}, Mask: {input_mask is not None}") with self.__class__._storage_lock: input_data = {} @@ -263,7 +273,7 @@ class LayerForgeNode: input_image = input_image.unsqueeze(0) batch_size = input_image.shape[0] - log_info(f"Processing batch of {batch_size} image(s)") + log.info(f"Processing batch of {batch_size} image(s)") if batch_size == 1: # Single image - keep backward compatibility @@ -277,7 +287,7 @@ class LayerForgeNode: input_data['input_image'] = f"data:image/png;base64,{img_str}" input_data['input_image_width'] = pil_img.width input_data['input_image_height'] = pil_img.height - log_debug(f"Stored single input image: {pil_img.width}x{pil_img.height}") + log.debug(f"Stored single input image: {pil_img.width}x{pil_img.height}") else: # Multiple images - store as array images_array = [] @@ -294,10 +304,10 @@ class LayerForgeNode: 'width': pil_img.width, 'height': pil_img.height }) - log_debug(f"Stored batch image {i+1}/{batch_size}: {pil_img.width}x{pil_img.height}") + log.debug(f"Stored batch image {i+1}/{batch_size}: {pil_img.width}x{pil_img.height}") input_data['input_images_batch'] = images_array - log_info(f"Stored batch of {batch_size} images") + log.info(f"Stored batch of {batch_size} images") if input_mask is not None: # Convert mask tensor to base64 @@ -317,7 +327,7 @@ class LayerForgeNode: pil_mask.save(mask_buffered, format="PNG") mask_str = base64.b64encode(mask_buffered.getvalue()).decode() input_data['input_mask'] = f"data:image/png;base64,{mask_str}" - log_debug(f"Stored input mask: {pil_mask.width}x{pil_mask.height}") + log.debug(f"Stored input mask: {pil_mask.width}x{pil_mask.height}") input_data['fit_on_add'] = fit_on_add @@ -333,14 +343,14 @@ class LayerForgeNode: canvas_data = self.__class__._canvas_data_storage.pop(storage_key, None) if canvas_data: - log_info(f"Canvas data found for node {storage_key} from WebSocket") + log.info(f"Canvas data found for node {storage_key} from WebSocket") if canvas_data.get('image'): image_data = canvas_data['image'].split(',')[1] image_bytes = base64.b64decode(image_data) pil_image = Image.open(io.BytesIO(image_bytes)).convert('RGB') image_array = np.array(pil_image).astype(np.float32) / 255.0 processed_image = torch.from_numpy(image_array)[None,] - log_debug(f"Image loaded from WebSocket, shape: {processed_image.shape}") + log.debug(f"Image loaded from WebSocket, shape: {processed_image.shape}") if canvas_data.get('mask'): mask_data = canvas_data['mask'].split(',')[1] @@ -348,33 +358,33 @@ class LayerForgeNode: pil_mask = Image.open(io.BytesIO(mask_bytes)).convert('L') mask_array = np.array(pil_mask).astype(np.float32) / 255.0 processed_mask = torch.from_numpy(mask_array)[None,] - log_debug(f"Mask loaded from WebSocket, shape: {processed_mask.shape}") + log.debug(f"Mask loaded from WebSocket, shape: {processed_mask.shape}") else: - log_warn(f"No canvas data found for node {storage_key} in WebSocket cache.") + log.warning(f"No canvas data found for node {storage_key} in WebSocket cache.") if processed_image is None: - log_warn(f"Processed image is still None, creating default blank image.") + log.warning(f"Processed image is still None, creating default blank image.") processed_image = torch.zeros((1, 512, 512, 3), dtype=torch.float32) if processed_mask is None: - log_warn(f"Processed mask is still None, creating default blank mask.") + log.warning(f"Processed mask is still None, creating default blank mask.") processed_mask = torch.zeros((1, 512, 512), dtype=torch.float32) - log_debug(f"About to return output - Image shape: {processed_image.shape}, Mask shape: {processed_mask.shape}") + log.debug(f"About to return output - Image shape: {processed_image.shape}, Mask shape: {processed_mask.shape}") self.update_persistent_cache() - log_info(f"Successfully returning processed image and mask") + log.info(f"Successfully returning processed image and mask") return (processed_image, processed_mask) except Exception as e: - log_exception(f"Error in process_canvas_image: {str(e)}") + log.exception(f"Error in process_canvas_image: {str(e)}") return (None, None) finally: if self.__class__._processing_lock.locked(): self.__class__._processing_lock.release() - log_debug(f"Process completed for node {node_id}, lock released") + log.debug(f"Process completed for node {node_id}, lock released") def get_cached_data(self): return { @@ -454,13 +464,13 @@ class LayerForgeNode: for node_id in nodes_to_remove: del cls._websocket_data[node_id] - log_debug(f"Cleaned up old WebSocket data for node {node_id}") + log.debug(f"Cleaned up old WebSocket data for node {node_id}") if nodes_to_remove: - log_info(f"Cleaned up {len(nodes_to_remove)} old WebSocket entries") + log.info(f"Cleaned up {len(nodes_to_remove)} old WebSocket entries") except Exception as e: - log_error(f"Error during WebSocket cleanup: {str(e)}") + log.error(f"Error during WebSocket cleanup: {str(e)}") @classmethod def setup_routes(cls): @@ -488,7 +498,7 @@ class LayerForgeNode: 'timestamp': time.time() } - log_info(f"Received canvas data for node {node_id} via WebSocket") + log.info(f"Received canvas data for node {node_id} via WebSocket") ack_payload = { 'type': 'ack', @@ -496,43 +506,43 @@ class LayerForgeNode: 'status': 'success' } await ws.send_json(ack_payload) - log_debug(f"Sent ACK for node {node_id}") + log.debug(f"Sent ACK for node {node_id}") except Exception as e: - log_error(f"Error processing WebSocket message: {e}") + log.error(f"Error processing WebSocket message: {e}") await ws.send_json({'status': 'error', 'message': str(e)}) elif msg.type == web.WSMsgType.ERROR: - log_error(f"WebSocket connection closed with exception {ws.exception()}") + log.error(f"WebSocket connection closed with exception {ws.exception()}") - log_info("WebSocket connection closed") + log.info("WebSocket connection closed") return ws @PromptServer.instance.routes.get("/layerforge/get_input_data/{node_id}") async def get_input_data(request): try: node_id = request.match_info["node_id"] - log_debug(f"Checking for input data for node: {node_id}") + log.debug(f"Checking for input data for node: {node_id}") with cls._storage_lock: input_key = f"{node_id}_input" input_data = cls._canvas_data_storage.get(input_key, None) if input_data: - log_info(f"Input data found for node {node_id}, sending to frontend") + log.info(f"Input data found for node {node_id}, sending to frontend") return web.json_response({ 'success': True, 'has_input': True, 'data': input_data }) else: - log_debug(f"No input data found for node {node_id}") + log.debug(f"No input data found for node {node_id}") return web.json_response({ 'success': True, 'has_input': False }) except Exception as e: - log_error(f"Error in get_input_data: {str(e)}") + log.error(f"Error in get_input_data: {str(e)}") return web.json_response({ 'success': False, 'error': str(e) @@ -542,15 +552,15 @@ class LayerForgeNode: async def clear_input_data(request): try: node_id = request.match_info["node_id"] - log_info(f"Clearing input data for node: {node_id}") + log.info(f"Clearing input data for node: {node_id}") with cls._storage_lock: input_key = f"{node_id}_input" if input_key in cls._canvas_data_storage: del cls._canvas_data_storage[input_key] - log_info(f"Input data cleared for node {node_id}") + log.info(f"Input data cleared for node {node_id}") else: - log_debug(f"No input data to clear for node {node_id}") + log.debug(f"No input data to clear for node {node_id}") return web.json_response({ 'success': True, @@ -558,7 +568,7 @@ class LayerForgeNode: }) except Exception as e: - log_error(f"Error in clear_input_data: {str(e)}") + log.error(f"Error in clear_input_data: {str(e)}") return web.json_response({ 'success': False, 'error': str(e) @@ -568,11 +578,11 @@ class LayerForgeNode: async def get_canvas_data(request): try: node_id = request.match_info["node_id"] - log_debug(f"Received request for node: {node_id}") + log.debug(f"Received request for node: {node_id}") cache_data = cls._canvas_cache - log_debug(f"Cache content: {cache_data}") - log_debug(f"Image in cache: {cache_data['image'] is not None}") + log.debug(f"Cache content: {cache_data}") + log.debug(f"Image in cache: {cache_data['image'] is not None}") response_data = { 'success': True, @@ -599,7 +609,7 @@ class LayerForgeNode: return web.json_response(response_data) except Exception as e: - log_error(f"Error in get_canvas_data: {str(e)}") + log.error(f"Error in get_canvas_data: {str(e)}") return web.json_response({ 'success': False, 'error': str(e) @@ -623,7 +633,7 @@ class LayerForgeNode: 'images': images_data }) except Exception as e: - log_error(f"Error in get_latest_images_route: {str(e)}") + log.error(f"Error in get_latest_images_route: {str(e)}") return web.json_response({ 'success': False, 'error': str(e) @@ -663,11 +673,11 @@ class LayerForgeNode: 'error': 'file_path is required' }, status=400) - log_info(f"Attempting to load image from path: {file_path}") + log.info(f"Attempting to load image from path: {file_path}") # Check if file exists and is accessible if not os.path.exists(file_path): - log_warn(f"File not found: {file_path}") + log.warning(f"File not found: {file_path}") return web.json_response({ 'success': False, 'error': f'File not found: {file_path}' @@ -693,7 +703,7 @@ class LayerForgeNode: img.save(buffered, format="PNG") img_str = base64.b64encode(buffered.getvalue()).decode('utf-8') - log_info(f"Successfully loaded image from path: {file_path}") + log.info(f"Successfully loaded image from path: {file_path}") return web.json_response({ 'success': True, 'image_data': f"data:image/png;base64,{img_str}", @@ -702,14 +712,14 @@ class LayerForgeNode: }) except Exception as img_error: - log_error(f"Error processing image file {file_path}: {str(img_error)}") + log.error(f"Error processing image file {file_path}: {str(img_error)}") return web.json_response({ 'success': False, 'error': f'Error processing image file: {str(img_error)}' }, status=500) except Exception as e: - log_error(f"Error in load_image_from_path_route: {str(e)}") + log.error(f"Error in load_image_from_path_route: {str(e)}") return web.json_response({ 'success': False, 'error': str(e) @@ -724,148 +734,148 @@ class LayerForgeNode: else: self.cached_image = image_data - def get_cached_image(self): - - if self.cached_image: - buffered = io.BytesIO() - self.cached_image.save(buffered, format="PNG") - img_str = base64.b64encode(buffered.getvalue()).decode() - return f"data:image/png;base64,{img_str}" - return None - - -def _get_birefnet_base_paths(): - paths = [] - - comfy_models_dir = getattr(folder_paths, "models_dir", None) - if comfy_models_dir: - paths.append(os.path.join(comfy_models_dir, "BiRefNet")) - - legacy_models_dir = os.path.join( - os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))), - "models", - "BiRefNet" - ) - paths.append(legacy_models_dir) - - unique_paths = [] - seen = set() - for path in paths: - normalized = os.path.normpath(path) - if normalized not in seen: - seen.add(normalized) - unique_paths.append(path) - - return unique_paths - - -def _is_valid_birefnet_model_dir(path): - if not os.path.isdir(path): - return False - - try: - files = os.listdir(path) - except OSError: - return False - - has_config = "config.json" in files - has_model = "model.safetensors" in files or "pytorch_model.bin" in files - has_backbone = "backbone_swin.pth" in files or "swin_base_patch4_window12_384_22kto1k.pth" in files - has_birefnet = "birefnet.pth" in files or any(f.endswith(".pth") for f in files) - - return has_config and (has_model or has_backbone or has_birefnet) - - -def _find_local_birefnet_model(): - for base_path in _get_birefnet_base_paths(): - if not os.path.isdir(base_path): - continue - - if _is_valid_birefnet_model_dir(base_path): - return base_path - - try: - existing_items = os.listdir(base_path) - except OSError: - continue - - model_subdirs = [ - d for d in existing_items - if os.path.isdir(os.path.join(base_path, d)) and - (d.startswith("models--") or d == "ZhengPeng7--BiRefNet") - ] - - for subdir in model_subdirs: - snapshots_path = os.path.join(base_path, subdir, "snapshots") - if not os.path.isdir(snapshots_path): - continue - - try: - snapshot_dirs = os.listdir(snapshots_path) - except OSError: - continue - - for snapshot in snapshot_dirs: - snapshot_path = os.path.join(snapshots_path, snapshot) - if _is_valid_birefnet_model_dir(snapshot_path): - return snapshot_path - - return None - - -class BiRefNetMatting: - def __init__(self): - self.model = None - self.model_path = None - self.model_cache = {} - self.base_paths = _get_birefnet_base_paths() - - def load_model(self, model_path): - from json.decoder import JSONDecodeError - try: - if model_path not in self.model_cache: - local_model_path = _find_local_birefnet_model() - cache_dir = self.base_paths[0] if self.base_paths else None - - if local_model_path: - log_info(f"Loading BiRefNet model from local path {local_model_path}...") - try: - self.model = AutoModelForImageSegmentation.from_pretrained( - local_model_path, - trust_remote_code=True - ) - self.model.eval() - if torch.cuda.is_available(): - self.model = self.model.cuda() - self.model_cache[model_path] = self.model - log_info("Model loaded successfully from local disk") - return - except Exception as local_error: - log_warn(f"Failed to load local BiRefNet model from {local_model_path}: {str(local_error)}") - log_info("Falling back to Hugging Face model loading") - - full_model_path = cache_dir or "BiRefNet" - log_info(f"Loading BiRefNet model from Hugging Face cache {full_model_path}...") - try: - # Try loading with additional configuration to handle compatibility issues - self.model = AutoModelForImageSegmentation.from_pretrained( - "ZhengPeng7/BiRefNet", - trust_remote_code=True, - cache_dir=cache_dir, - # Add force_download=False to use cached version if available - force_download=False, - # Add local_files_only=False to allow downloading if needed - local_files_only=False - ) + def get_cached_image(self): + + if self.cached_image: + buffered = io.BytesIO() + self.cached_image.save(buffered, format="PNG") + img_str = base64.b64encode(buffered.getvalue()).decode() + return f"data:image/png;base64,{img_str}" + return None + + +def _get_birefnet_base_paths(): + paths = [] + + comfy_models_dir = getattr(folder_paths, "models_dir", None) + if comfy_models_dir: + paths.append(os.path.join(comfy_models_dir, "BiRefNet")) + + legacy_models_dir = os.path.join( + os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))), + "models", + "BiRefNet" + ) + paths.append(legacy_models_dir) + + unique_paths = [] + seen = set() + for path in paths: + normalized = os.path.normpath(path) + if normalized not in seen: + seen.add(normalized) + unique_paths.append(path) + + return unique_paths + + +def _is_valid_birefnet_model_dir(path): + if not os.path.isdir(path): + return False + + try: + files = os.listdir(path) + except OSError: + return False + + has_config = "config.json" in files + has_model = "model.safetensors" in files or "pytorch_model.bin" in files + has_backbone = "backbone_swin.pth" in files or "swin_base_patch4_window12_384_22kto1k.pth" in files + has_birefnet = "birefnet.pth" in files or any(f.endswith(".pth") for f in files) + + return has_config and (has_model or has_backbone or has_birefnet) + + +def _find_local_birefnet_model(): + for base_path in _get_birefnet_base_paths(): + if not os.path.isdir(base_path): + continue + + if _is_valid_birefnet_model_dir(base_path): + return base_path + + try: + existing_items = os.listdir(base_path) + except OSError: + continue + + model_subdirs = [ + d for d in existing_items + if os.path.isdir(os.path.join(base_path, d)) and + (d.startswith("models--") or d == "ZhengPeng7--BiRefNet") + ] + + for subdir in model_subdirs: + snapshots_path = os.path.join(base_path, subdir, "snapshots") + if not os.path.isdir(snapshots_path): + continue + + try: + snapshot_dirs = os.listdir(snapshots_path) + except OSError: + continue + + for snapshot in snapshot_dirs: + snapshot_path = os.path.join(snapshots_path, snapshot) + if _is_valid_birefnet_model_dir(snapshot_path): + return snapshot_path + + return None + + +class BiRefNetMatting: + def __init__(self): + self.model = None + self.model_path = None + self.model_cache = {} + self.base_paths = _get_birefnet_base_paths() + + def load_model(self, model_path): + from json.decoder import JSONDecodeError + try: + if model_path not in self.model_cache: + local_model_path = _find_local_birefnet_model() + cache_dir = self.base_paths[0] if self.base_paths else None + + if local_model_path: + log.info(f"Loading BiRefNet model from local path {local_model_path}...") + try: + self.model = AutoModelForImageSegmentation.from_pretrained( + local_model_path, + trust_remote_code=True + ) + self.model.eval() + if torch.cuda.is_available(): + self.model = self.model.cuda() + self.model_cache[model_path] = self.model + log.info("Model loaded successfully from local disk") + return + except Exception as local_error: + log.warning(f"Failed to load local BiRefNet model from {local_model_path}: {str(local_error)}") + log.info("Falling back to Hugging Face model loading") + + full_model_path = cache_dir or "BiRefNet" + log.info(f"Loading BiRefNet model from Hugging Face cache {full_model_path}...") + try: + # Try loading with additional configuration to handle compatibility issues + self.model = AutoModelForImageSegmentation.from_pretrained( + "ZhengPeng7/BiRefNet", + trust_remote_code=True, + cache_dir=cache_dir, + # Add force_download=False to use cached version if available + force_download=False, + # Add local_files_only=False to allow downloading if needed + local_files_only=False + ) self.model.eval() if torch.cuda.is_available(): self.model = self.model.cuda() self.model_cache[model_path] = self.model - log_info("Model loaded successfully from Hugging Face") + log.info("Model loaded successfully from Hugging Face") except AttributeError as e: if "'Config' object has no attribute 'is_encoder_decoder'" in str(e): - log_error("Compatibility issue detected with transformers library. This has been fixed in the code.") - log_error("If you're still seeing this error, please clear the model cache and try again.") + log.error("Compatibility issue detected with transformers library. This has been fixed in the code.") + log.error("If you're still seeing this error, please clear the model cache and try again.") raise RuntimeError( "Model configuration compatibility issue detected. " f"Please delete the model cache directory '{full_model_path}' and restart ComfyUI. " @@ -874,14 +884,14 @@ class BiRefNetMatting: else: raise e except JSONDecodeError as e: - log_error(f"JSONDecodeError: Failed to load model from {full_model_path}. The model's config.json may be corrupted.") + log.error(f"JSONDecodeError: Failed to load model from {full_model_path}. The model's config.json may be corrupted.") raise RuntimeError( "The matting model's configuration file (config.json) appears to be corrupted. " f"Please manually delete the directory '{full_model_path}' and try again. " "This will force a fresh download of the model." ) from e except Exception as e: - log_error(f"Failed to load model from Hugging Face: {str(e)}") + log.error(f"Failed to load model from Hugging Face: {str(e)}") # Re-raise with a more informative message raise RuntimeError( "Failed to download or load the matting model. " @@ -891,12 +901,12 @@ class BiRefNetMatting: ) from e else: self.model = self.model_cache[model_path] - log_debug("Using cached model") + log.debug("Using cached model") except Exception as e: # Catch the re-raised exception or any other error - log_error(f"Error loading model: {str(e)}") - log_exception("Model loading failed") + log.error(f"Error loading model: {str(e)}") + log.exception("Model loading failed") raise # Re-raise the exception to be caught by the execute method def preprocess_image(self, image): @@ -922,7 +932,7 @@ class BiRefNetMatting: return image_tensor except Exception as e: - log_error(f"Error preprocessing image: {str(e)}") + log.error(f"Error preprocessing image: {str(e)}") return None def execute(self, image, model_path, threshold=0.5, refinement=1): @@ -936,25 +946,25 @@ class BiRefNetMatting: else: original_size = image.size[::-1] - log_debug(f"Original size: {original_size}") + log.debug(f"Original size: {original_size}") processed_image = self.preprocess_image(image) if processed_image is None: raise Exception("Failed to preprocess image") - log_debug(f"Processed image shape: {processed_image.shape}") + log.debug(f"Processed image shape: {processed_image.shape}") with torch.no_grad(): outputs = self.model(processed_image) result = outputs[-1].sigmoid().cpu() - log_debug(f"Model output shape: {result.shape}") + log.debug(f"Model output shape: {result.shape}") if result.dim() == 3: result = result.unsqueeze(1) # 添加通道维度 elif result.dim() == 2: result = result.unsqueeze(0).unsqueeze(0) # 添加batch和通道维度 - log_debug(f"Reshaped result shape: {result.shape}") + log.debug(f"Reshaped result shape: {result.shape}") result = F.interpolate( result, @@ -962,7 +972,7 @@ class BiRefNetMatting: mode='bilinear', align_corners=True ) - log_debug(f"Resized result shape: {result.shape}") + log.debug(f"Resized result shape: {result.shape}") result = result.squeeze() # 移除多余的维度 ma = torch.max(result) @@ -1013,30 +1023,30 @@ async def check_matting_model(request): "message": "The 'transformers' library is required for the matting feature. Please install it by running: pip install transformers" }) - # Check if model exists in cache - local_model_path = _find_local_birefnet_model() - - if local_model_path: - # Model files exist, assume it's ready - log_info(f"BiRefNet model files detected at {local_model_path}") - return web.json_response({ - "available": True, - "reason": "ready", - "message": "Model is ready to use", - "model_path": local_model_path - }) - else: - searched_paths = _get_birefnet_base_paths() - log_info(f"BiRefNet model not found in any of: {searched_paths}") - return web.json_response({ - "available": False, - "reason": "not_downloaded", - "message": "The matting model needs to be downloaded. This will happen automatically when you first use the matting feature (requires internet connection).", - "model_path": searched_paths[0] if searched_paths else None - }) + # Check if model exists in cache + local_model_path = _find_local_birefnet_model() + + if local_model_path: + # Model files exist, assume it's ready + log.info(f"BiRefNet model files detected at {local_model_path}") + return web.json_response({ + "available": True, + "reason": "ready", + "message": "Model is ready to use", + "model_path": local_model_path + }) + else: + searched_paths = _get_birefnet_base_paths() + log.info(f"BiRefNet model not found in any of: {searched_paths}") + return web.json_response({ + "available": False, + "reason": "not_downloaded", + "message": "The matting model needs to be downloaded. This will happen automatically when you first use the matting feature (requires internet connection).", + "model_path": searched_paths[0] if searched_paths else None + }) except Exception as e: - log_error(f"Error checking matting model: {str(e)}") + log.error(f"Error checking matting model: {str(e)}") return web.json_response({ "available": False, "reason": "error", @@ -1048,14 +1058,14 @@ async def matting(request): global _matting_lock if not TRANSFORMERS_AVAILABLE: - log_error("Matting request failed: 'transformers' library is not installed.") + log.error("Matting request failed: 'transformers' library is not installed.") return web.json_response({ "error": "Dependency Not Found", "details": "The 'transformers' library is required for the matting feature. Please install it by running: pip install transformers" }, status=400) if _matting_lock is not None: - log_warn("Matting already in progress, rejecting request") + log.warning("Matting already in progress, rejecting request") return web.json_response({ "error": "Another matting operation is in progress", "details": "Please wait for the current operation to complete" @@ -1063,13 +1073,13 @@ async def matting(request): _matting_lock = True try: - log_info("Received matting request") + log.info("Received matting request") data = await request.json() matting_instance = BiRefNetMatting() image_tensor, original_alpha = convert_base64_to_tensor(data["image"]) - log_debug(f"Input image shape: {image_tensor.shape}") + log.debug(f"Input image shape: {image_tensor.shape}") matted_image, alpha_mask = matting_instance.execute( image_tensor, @@ -1087,19 +1097,19 @@ async def matting(request): }) except RequestsConnectionError as e: - log_error(f"Connection error during matting model download: {e}") + log.error(f"Connection error during matting model download: {e}") return web.json_response({ "error": "Network Connection Error", "details": "Failed to download the matting model from Hugging Face. Please check your internet connection." }, status=400) except RuntimeError as e: - log_error(f"Runtime error during matting: {e}") + log.error(f"Runtime error during matting: {e}") return web.json_response({ "error": "Matting Model Error", "details": str(e) }, status=500) except Exception as e: - log_exception(f"Error in matting endpoint: {e}") + log.exception(f"Error in matting endpoint: {e}") # Check for offline error message from Hugging Face if "Offline mode is enabled" in str(e) or "Can't load 'ZhengPeng7/BiRefNet' offline" in str(e): return web.json_response({ @@ -1113,7 +1123,7 @@ async def matting(request): }, status=500) finally: _matting_lock = None - log_debug("Matting lock released") + log.debug("Matting lock released") def convert_base64_to_tensor(base64_str): @@ -1146,7 +1156,7 @@ def convert_base64_to_tensor(base64_str): return img_tensor, None except Exception as e: - log_error(f"Error in convert_base64_to_tensor: {str(e)}") + log.error(f"Error in convert_base64_to_tensor: {str(e)}") raise @@ -1193,6 +1203,6 @@ def convert_tensor_to_base64(tensor, alpha_mask=None, original_alpha=None): return f"data:image/png;base64,{img_str}" except Exception as e: - log_error(f"Error in convert_tensor_to_base64: {str(e)}") - log_debug(f"Tensor shape: {tensor.shape}, dtype: {tensor.dtype}") + log.error(f"Error in convert_tensor_to_base64: {str(e)}") + log.debug(f"Tensor shape: {tensor.shape}, dtype: {tensor.dtype}") raise diff --git a/js/BatchPreviewManager.js b/js/BatchPreviewManager.js index 6e355cc..233f684 100644 --- a/js/BatchPreviewManager.js +++ b/js/BatchPreviewManager.js @@ -1,4 +1,4 @@ -import { createModuleLogger } from "./utils/LoggerUtils.js"; +import { createModuleLogger } from "./log_system/log_funcs.js"; const log = createModuleLogger('BatchPreviewManager'); export class BatchPreviewManager { constructor(canvas, initialPosition = { x: 0, y: 0 }, generationArea = null) { diff --git a/js/Canvas.js b/js/Canvas.js index 66f8692..2838f58 100644 --- a/js/Canvas.js +++ b/js/Canvas.js @@ -11,7 +11,7 @@ import { CanvasRenderer } from "./CanvasRenderer.js"; import { CanvasIO } from "./CanvasIO.js"; import { ImageReferenceManager } from "./ImageReferenceManager.js"; import { BatchPreviewManager } from "./BatchPreviewManager.js"; -import { createModuleLogger } from "./utils/LoggerUtils.js"; +import { createModuleLogger } from "./log_system/log_funcs.js"; import { debounce, createCanvas } from "./utils/CommonUtils.js"; import { MaskEditorIntegration } from "./MaskEditorIntegration.js"; import { CanvasSelection } from "./CanvasSelection.js"; diff --git a/js/CanvasIO.js b/js/CanvasIO.js index 75f58f7..b33dcf0 100644 --- a/js/CanvasIO.js +++ b/js/CanvasIO.js @@ -1,5 +1,5 @@ import { createCanvas } from "./utils/CommonUtils.js"; -import { createModuleLogger } from "./utils/LoggerUtils.js"; +import { createModuleLogger } from "./log_system/log_funcs.js"; import { showErrorNotification } from "./utils/NotificationUtils.js"; import { webSocketManager } from "./utils/WebSocketManager.js"; import { scaleImageToFit, createImageFromSource, tensorToImageData, createImageFromImageData } from "./utils/ImageUtils.js"; diff --git a/js/CanvasInteractions.js b/js/CanvasInteractions.js index 50d019a..5bf60e5 100644 --- a/js/CanvasInteractions.js +++ b/js/CanvasInteractions.js @@ -1,4 +1,4 @@ -import { createModuleLogger } from "./utils/LoggerUtils.js"; +import { createModuleLogger } from "./log_system/log_funcs.js"; import { snapToGrid, getSnapAdjustment } from "./utils/CommonUtils.js"; const log = createModuleLogger('CanvasInteractions'); export class CanvasInteractions { diff --git a/js/CanvasLayers.js b/js/CanvasLayers.js index ae816af..dd6373e 100644 --- a/js/CanvasLayers.js +++ b/js/CanvasLayers.js @@ -1,5 +1,5 @@ import { saveImage } from "./db.js"; -import { createModuleLogger } from "./utils/LoggerUtils.js"; +import { createModuleLogger } from "./log_system/log_funcs.js"; import { generateUUID, generateUniqueFileName, createCanvas } from "./utils/CommonUtils.js"; import { withErrorHandling, createValidationError } from "./ErrorHandler.js"; import { showErrorNotification } from "./utils/NotificationUtils.js"; diff --git a/js/CanvasLayersPanel.js b/js/CanvasLayersPanel.js index 048852f..be8785d 100644 --- a/js/CanvasLayersPanel.js +++ b/js/CanvasLayersPanel.js @@ -1,4 +1,4 @@ -import { createModuleLogger } from "./utils/LoggerUtils.js"; +import { createModuleLogger } from "./log_system/log_funcs.js"; import { iconLoader, LAYERFORGE_TOOLS } from "./utils/IconLoader.js"; import { createCanvas } from "./utils/CommonUtils.js"; import { addStylesheet, getUrl } from "./utils/ResourceManager.js"; diff --git a/js/CanvasRenderer.js b/js/CanvasRenderer.js index 6223d6d..067832f 100644 --- a/js/CanvasRenderer.js +++ b/js/CanvasRenderer.js @@ -1,4 +1,4 @@ -import { createModuleLogger } from "./utils/LoggerUtils.js"; +import { createModuleLogger } from "./log_system/log_funcs.js"; const log = createModuleLogger('CanvasRenderer'); export class CanvasRenderer { constructor(canvas) { diff --git a/js/CanvasSelection.js b/js/CanvasSelection.js index f0d3fd2..28a6b0d 100644 --- a/js/CanvasSelection.js +++ b/js/CanvasSelection.js @@ -1,4 +1,4 @@ -import { createModuleLogger } from "./utils/LoggerUtils.js"; +import { createModuleLogger } from "./log_system/log_funcs.js"; import { generateUUID } from "./utils/CommonUtils.js"; const log = createModuleLogger('CanvasSelection'); export class CanvasSelection { diff --git a/js/CanvasState.js b/js/CanvasState.js index 3fb28b9..4b725ab 100644 --- a/js/CanvasState.js +++ b/js/CanvasState.js @@ -1,5 +1,5 @@ import { getCanvasState, setCanvasState, saveImage, getImage } from "./db.js"; -import { createModuleLogger } from "./utils/LoggerUtils.js"; +import { createModuleLogger } from "./log_system/log_funcs.js"; import { showAlertNotification } from "./utils/NotificationUtils.js"; import { generateUUID, cloneLayers, getStateSignature, debounce, createCanvas } from "./utils/CommonUtils.js"; const log = createModuleLogger('CanvasState'); diff --git a/js/CanvasView.js b/js/CanvasView.js index 5d052c6..bec5b6a 100644 --- a/js/CanvasView.js +++ b/js/CanvasView.js @@ -9,7 +9,7 @@ import { Canvas } from "./Canvas.js"; import { clearAllCanvasStates, getCanvasState, setCanvasState } from "./db.js"; import { ImageCache } from "./ImageCache.js"; import { createCanvas } from "./utils/CommonUtils.js"; -import { createModuleLogger } from "./utils/LoggerUtils.js"; +import { createModuleLogger } from "./log_system/log_funcs.js"; import { showErrorNotification, showSuccessNotification, showInfoNotification, showWarningNotification } from "./utils/NotificationUtils.js"; import { iconLoader, LAYERFORGE_TOOLS } from "./utils/IconLoader.js"; import { setupSAMDetectorHook } from "./SAMDetectorIntegration.js"; diff --git a/js/CustomShapeMenu.js b/js/CustomShapeMenu.js index 4dd0353..ef28700 100644 --- a/js/CustomShapeMenu.js +++ b/js/CustomShapeMenu.js @@ -1,4 +1,4 @@ -import { createModuleLogger } from "./utils/LoggerUtils.js"; +import { createModuleLogger } from "./log_system/log_funcs.js"; import { addStylesheet, getUrl } from "./utils/ResourceManager.js"; const log = createModuleLogger('CustomShapeMenu'); export class CustomShapeMenu { diff --git a/js/ErrorHandler.js b/js/ErrorHandler.js index 6741857..4fe1d4c 100644 --- a/js/ErrorHandler.js +++ b/js/ErrorHandler.js @@ -2,7 +2,7 @@ * ErrorHandler - Centralna obsługa błędów * Eliminuje powtarzalne wzorce obsługi błędów w całym projekcie */ -import { createModuleLogger } from "./utils/LoggerUtils.js"; +import { createModuleLogger } from "./log_system/log_funcs.js"; const log = createModuleLogger('ErrorHandler'); /** * Typy błędów w aplikacji diff --git a/js/ImageCache.js b/js/ImageCache.js index e8eb996..7337011 100644 --- a/js/ImageCache.js +++ b/js/ImageCache.js @@ -1,4 +1,4 @@ -import { createModuleLogger } from "./utils/LoggerUtils.js"; +import { createModuleLogger } from "./log_system/log_funcs.js"; const log = createModuleLogger('ImageCache'); export class ImageCache { constructor() { diff --git a/js/ImageReferenceManager.js b/js/ImageReferenceManager.js index 34a36ce..991416c 100644 --- a/js/ImageReferenceManager.js +++ b/js/ImageReferenceManager.js @@ -1,5 +1,5 @@ import { removeImage, getAllImageIds } from "./db.js"; -import { createModuleLogger } from "./utils/LoggerUtils.js"; +import { createModuleLogger } from "./log_system/log_funcs.js"; const log = createModuleLogger('ImageReferenceManager'); export class ImageReferenceManager { constructor(canvas) { diff --git a/js/MaskEditorIntegration.js b/js/MaskEditorIntegration.js index 3e52b14..573a987 100644 --- a/js/MaskEditorIntegration.js +++ b/js/MaskEditorIntegration.js @@ -2,7 +2,7 @@ import { app } from "../../scripts/app.js"; // @ts-ignore import { ComfyApp } from "../../scripts/app.js"; -import { createModuleLogger } from "./utils/LoggerUtils.js"; +import { createModuleLogger } from "./log_system/log_funcs.js"; import { showErrorNotification } from "./utils/NotificationUtils.js"; import { uploadImageBlob } from "./utils/ImageUploadUtils.js"; import { processImageToMask, processMaskForViewport } from "./utils/MaskProcessingUtils.js"; diff --git a/js/MaskTool.js b/js/MaskTool.js index 80f3f13..56d4bac 100644 --- a/js/MaskTool.js +++ b/js/MaskTool.js @@ -1,4 +1,4 @@ -import { createModuleLogger } from "./utils/LoggerUtils.js"; +import { createModuleLogger } from "./log_system/log_funcs.js"; import { createCanvas } from "./utils/CommonUtils.js"; const log = createModuleLogger('Mask_tool'); export class MaskTool { diff --git a/js/SAMDetectorIntegration.js b/js/SAMDetectorIntegration.js index 4f07961..936e282 100644 --- a/js/SAMDetectorIntegration.js +++ b/js/SAMDetectorIntegration.js @@ -1,6 +1,6 @@ // @ts-ignore import { ComfyApp } from "../../scripts/app.js"; -import { createModuleLogger } from "./utils/LoggerUtils.js"; +import { createModuleLogger } from "./log_system/log_funcs.js"; import { showInfoNotification, showSuccessNotification, showErrorNotification } from "./utils/NotificationUtils.js"; import { uploadCanvasAsImage, uploadImageBlob } from "./utils/ImageUploadUtils.js"; import { processImageToMask } from "./utils/MaskProcessingUtils.js"; diff --git a/js/ShapeTool.js b/js/ShapeTool.js index 05c7960..067d1b2 100644 --- a/js/ShapeTool.js +++ b/js/ShapeTool.js @@ -1,4 +1,4 @@ -import { createModuleLogger } from "./utils/LoggerUtils.js"; +import { createModuleLogger } from "./log_system/log_funcs.js"; const log = createModuleLogger('ShapeTool'); export class ShapeTool { constructor(canvas) { diff --git a/js/db.js b/js/db.js index dd889c6..8113d8a 100644 --- a/js/db.js +++ b/js/db.js @@ -1,4 +1,4 @@ -import { createModuleLogger } from "./utils/LoggerUtils.js"; +import { createModuleLogger } from "./log_system/log_funcs.js"; const log = createModuleLogger('db'); const DB_NAME = 'CanvasNodeDB'; const STATE_STORE_NAME = 'CanvasState'; diff --git a/js/utils/ClipboardManager.js b/js/utils/ClipboardManager.js index 32afbd5..4f85f75 100644 --- a/js/utils/ClipboardManager.js +++ b/js/utils/ClipboardManager.js @@ -1,4 +1,4 @@ -import { createModuleLogger } from "./LoggerUtils.js"; +import { createModuleLogger } from "../log_system/log_funcs.js"; import { showNotification, showInfoNotification, showErrorNotification, showWarningNotification } from "./NotificationUtils.js"; import { withErrorHandling, createValidationError, createNetworkError, createFileError } from "../ErrorHandler.js"; import { safeClipspacePaste } from "./ClipspaceUtils.js"; diff --git a/js/utils/ClipspaceUtils.js b/js/utils/ClipspaceUtils.js index bf09afb..70e3e16 100644 --- a/js/utils/ClipspaceUtils.js +++ b/js/utils/ClipspaceUtils.js @@ -1,4 +1,4 @@ -import { createModuleLogger } from "./LoggerUtils.js"; +import { createModuleLogger } from "../log_system/log_funcs.js"; // @ts-ignore import { ComfyApp } from "../../../scripts/app.js"; const log = createModuleLogger('ClipspaceUtils'); diff --git a/js/utils/IconLoader.js b/js/utils/IconLoader.js index 3d51b23..b2b207a 100644 --- a/js/utils/IconLoader.js +++ b/js/utils/IconLoader.js @@ -1,4 +1,4 @@ -import { createModuleLogger } from "./LoggerUtils.js"; +import { createModuleLogger } from "../log_system/log_funcs.js"; import { createCanvas } from "./CommonUtils.js"; import { withErrorHandling, createValidationError } from "../ErrorHandler.js"; const log = createModuleLogger('IconLoader'); diff --git a/js/utils/ImageAnalysis.js b/js/utils/ImageAnalysis.js index 35c05c7..66e43ba 100644 --- a/js/utils/ImageAnalysis.js +++ b/js/utils/ImageAnalysis.js @@ -1,4 +1,4 @@ -import { createModuleLogger } from "./LoggerUtils.js"; +import { createModuleLogger } from "../log_system/log_funcs.js"; import { createCanvas } from "./CommonUtils.js"; import { withErrorHandling, createValidationError } from "../ErrorHandler.js"; const log = createModuleLogger('ImageAnalysis'); diff --git a/js/utils/ImageUploadUtils.js b/js/utils/ImageUploadUtils.js index 22cbdcb..5e11fb4 100644 --- a/js/utils/ImageUploadUtils.js +++ b/js/utils/ImageUploadUtils.js @@ -1,6 +1,6 @@ // @ts-ignore import { api } from "../../../scripts/api.js"; -import { createModuleLogger } from "./LoggerUtils.js"; +import { createModuleLogger } from "../log_system/log_funcs.js"; import { withErrorHandling, createValidationError, createNetworkError } from "../ErrorHandler.js"; const log = createModuleLogger('ImageUploadUtils'); /** diff --git a/js/utils/ImageUtils.js b/js/utils/ImageUtils.js index 19c4538..31774fb 100644 --- a/js/utils/ImageUtils.js +++ b/js/utils/ImageUtils.js @@ -1,4 +1,4 @@ -import { createModuleLogger } from "./LoggerUtils.js"; +import { createModuleLogger } from "../log_system/log_funcs.js"; import { withErrorHandling, createValidationError } from "../ErrorHandler.js"; import { createCanvas } from "./CommonUtils.js"; const log = createModuleLogger('ImageUtils'); diff --git a/js/utils/MaskProcessingUtils.js b/js/utils/MaskProcessingUtils.js index 091a399..1d0cc58 100644 --- a/js/utils/MaskProcessingUtils.js +++ b/js/utils/MaskProcessingUtils.js @@ -1,4 +1,4 @@ -import { createModuleLogger } from "./LoggerUtils.js"; +import { createModuleLogger } from "../log_system/log_funcs.js"; import { createCanvas } from "./CommonUtils.js"; import { withErrorHandling, createValidationError } from "../ErrorHandler.js"; const log = createModuleLogger('MaskProcessingUtils'); diff --git a/js/utils/NotificationUtils.js b/js/utils/NotificationUtils.js index e72929e..f57ebcd 100644 --- a/js/utils/NotificationUtils.js +++ b/js/utils/NotificationUtils.js @@ -8,7 +8,7 @@ description: Notification Utilities (Toast System) // 1. IMPORTS & DEPENDENCIES // ========================================== // Comment out or adjust this import if copying to a project that does not use AzLogs -import { createModuleLogger } from "./LoggerUtils.js"; +import { createModuleLogger } from "../log_system/log_funcs.js"; const CONFIG = { // Project display name (used in notifications tag and message prefix cleaning) PROJECT_NAME: "Layer Forge", diff --git a/js/utils/PreviewUtils.js b/js/utils/PreviewUtils.js index 94eda61..f89d219 100644 --- a/js/utils/PreviewUtils.js +++ b/js/utils/PreviewUtils.js @@ -1,4 +1,4 @@ -import { createModuleLogger } from "./LoggerUtils.js"; +import { createModuleLogger } from "../log_system/log_funcs.js"; import { withErrorHandling, createValidationError } from "../ErrorHandler.js"; const log = createModuleLogger('PreviewUtils'); /** diff --git a/js/utils/ResourceManager.js b/js/utils/ResourceManager.js index a652d36..8ed767d 100644 --- a/js/utils/ResourceManager.js +++ b/js/utils/ResourceManager.js @@ -1,6 +1,6 @@ // @ts-ignore import { $el } from "../../../scripts/ui.js"; -import { createModuleLogger } from "./LoggerUtils.js"; +import { createModuleLogger } from "../log_system/log_funcs.js"; import { withErrorHandling, createValidationError, createNetworkError } from "../ErrorHandler.js"; const log = createModuleLogger('ResourceManager'); export const addStylesheet = withErrorHandling(function (url) { diff --git a/js/utils/WebSocketManager.js b/js/utils/WebSocketManager.js index dc26feb..4093962 100644 --- a/js/utils/WebSocketManager.js +++ b/js/utils/WebSocketManager.js @@ -1,4 +1,4 @@ -import { createModuleLogger } from "./LoggerUtils.js"; +import { createModuleLogger } from "../log_system/log_funcs.js"; import { withErrorHandling, createValidationError, createNetworkError } from "../ErrorHandler.js"; const log = createModuleLogger('WebSocketManager'); class WebSocketManager { diff --git a/js/utils/mask_utils.js b/js/utils/mask_utils.js index 0f92098..9d0c1b7 100644 --- a/js/utils/mask_utils.js +++ b/js/utils/mask_utils.js @@ -1,4 +1,4 @@ -import { createModuleLogger } from "./LoggerUtils.js"; +import { createModuleLogger } from "../log_system/log_funcs.js"; import { withErrorHandling, createValidationError } from "../ErrorHandler.js"; const log = createModuleLogger('MaskUtils'); export function new_editor(app) { diff --git a/python/__init__.py b/python/__init__.py index f3715c2..10c8969 100644 --- a/python/__init__.py +++ b/python/__init__.py @@ -1,4 +1,5 @@ # This file makes the 'python' directory a package. -from . import logger +from . import log_system +from .log_system import logger -__all__ = ['logger'] +__all__ = ['log_system', 'logger'] diff --git a/src/BatchPreviewManager.ts b/src/BatchPreviewManager.ts index 1819b55..6f8301d 100644 --- a/src/BatchPreviewManager.ts +++ b/src/BatchPreviewManager.ts @@ -1,4 +1,4 @@ -import {createModuleLogger} from "./utils/LoggerUtils.js"; +import {createModuleLogger} from "./log_system/log_funcs.js"; import type { Canvas } from './Canvas'; import type { Layer, Point } from './types'; diff --git a/src/Canvas.ts b/src/Canvas.ts index 7e29b97..c49a01f 100644 --- a/src/Canvas.ts +++ b/src/Canvas.ts @@ -17,7 +17,7 @@ import {CanvasRenderer} from "./CanvasRenderer.js"; import {CanvasIO} from "./CanvasIO.js"; import {ImageReferenceManager} from "./ImageReferenceManager.js"; import {BatchPreviewManager} from "./BatchPreviewManager.js"; -import {createModuleLogger} from "./utils/LoggerUtils.js"; +import {createModuleLogger} from "./log_system/log_funcs.js"; import { debounce, createCanvas } from "./utils/CommonUtils.js"; import {MaskEditorIntegration} from "./MaskEditorIntegration.js"; import {CanvasSelection} from "./CanvasSelection.js"; diff --git a/src/CanvasIO.ts b/src/CanvasIO.ts index 3212b0e..cb656e0 100644 --- a/src/CanvasIO.ts +++ b/src/CanvasIO.ts @@ -1,5 +1,5 @@ import { createCanvas } from "./utils/CommonUtils.js"; -import { createModuleLogger } from "./utils/LoggerUtils.js"; +import { createModuleLogger } from "./log_system/log_funcs.js"; import { showErrorNotification } from "./utils/NotificationUtils.js"; import { webSocketManager } from "./utils/WebSocketManager.js"; import { scaleImageToFit, createImageFromSource, tensorToImageData, createImageFromImageData } from "./utils/ImageUtils.js"; diff --git a/src/CanvasInteractions.ts b/src/CanvasInteractions.ts index fc1f6e9..8c4a6dd 100644 --- a/src/CanvasInteractions.ts +++ b/src/CanvasInteractions.ts @@ -1,4 +1,4 @@ -import { createModuleLogger } from "./utils/LoggerUtils.js"; +import { createModuleLogger } from "./log_system/log_funcs.js"; import { snapToGrid, getSnapAdjustment } from "./utils/CommonUtils.js"; import type { Canvas } from './Canvas'; import type { Layer, Point } from './types'; diff --git a/src/CanvasLayers.ts b/src/CanvasLayers.ts index e66f5c8..8bf788e 100644 --- a/src/CanvasLayers.ts +++ b/src/CanvasLayers.ts @@ -1,5 +1,5 @@ import {saveImage, removeImage} from "./db.js"; -import {createModuleLogger} from "./utils/LoggerUtils.js"; +import {createModuleLogger} from "./log_system/log_funcs.js"; import {generateUUID, generateUniqueFileName, createCanvas} from "./utils/CommonUtils.js"; import {withErrorHandling, createValidationError} from "./ErrorHandler.js"; import {showErrorNotification, showSuccessNotification} from "./utils/NotificationUtils.js"; diff --git a/src/CanvasLayersPanel.ts b/src/CanvasLayersPanel.ts index dfa8261..2ebd00c 100644 --- a/src/CanvasLayersPanel.ts +++ b/src/CanvasLayersPanel.ts @@ -1,4 +1,4 @@ -import { createModuleLogger } from "./utils/LoggerUtils.js"; +import { createModuleLogger } from "./log_system/log_funcs.js"; import { iconLoader, LAYERFORGE_TOOLS } from "./utils/IconLoader.js"; import { createCanvas } from "./utils/CommonUtils.js"; import { addStylesheet, getUrl } from "./utils/ResourceManager.js"; diff --git a/src/CanvasRenderer.ts b/src/CanvasRenderer.ts index 1ba81b7..d60206e 100644 --- a/src/CanvasRenderer.ts +++ b/src/CanvasRenderer.ts @@ -1,4 +1,4 @@ -import {createModuleLogger} from "./utils/LoggerUtils.js"; +import {createModuleLogger} from "./log_system/log_funcs.js"; const log = createModuleLogger('CanvasRenderer'); diff --git a/src/CanvasSelection.ts b/src/CanvasSelection.ts index f0de041..ab85d2d 100644 --- a/src/CanvasSelection.ts +++ b/src/CanvasSelection.ts @@ -1,4 +1,4 @@ -import { createModuleLogger } from "./utils/LoggerUtils.js"; +import { createModuleLogger } from "./log_system/log_funcs.js"; import { generateUUID } from "./utils/CommonUtils.js"; const log = createModuleLogger('CanvasSelection'); diff --git a/src/CanvasState.ts b/src/CanvasState.ts index 5687662..a074bd9 100644 --- a/src/CanvasState.ts +++ b/src/CanvasState.ts @@ -1,5 +1,5 @@ import {getCanvasState, setCanvasState, saveImage, getImage} from "./db.js"; -import {createModuleLogger} from "./utils/LoggerUtils.js"; +import {createModuleLogger} from "./log_system/log_funcs.js"; import {showAlertNotification, showAllNotificationTypes} from "./utils/NotificationUtils.js"; import {generateUUID, cloneLayers, getStateSignature, debounce, createCanvas} from "./utils/CommonUtils.js"; import {withErrorHandling} from "./ErrorHandler.js"; diff --git a/src/CanvasView.ts b/src/CanvasView.ts index d47c2c4..2b9185c 100644 --- a/src/CanvasView.ts +++ b/src/CanvasView.ts @@ -15,7 +15,7 @@ import {Canvas} from "./Canvas.js"; import {clearAllCanvasStates, getCanvasState, setCanvasState} from "./db.js"; import {ImageCache} from "./ImageCache.js"; import {generateUniqueFileName, createCanvas} from "./utils/CommonUtils.js"; -import {createModuleLogger} from "./utils/LoggerUtils.js"; +import {createModuleLogger} from "./log_system/log_funcs.js"; import {showErrorNotification, showSuccessNotification, showInfoNotification, showWarningNotification} from "./utils/NotificationUtils.js"; import { iconLoader, LAYERFORGE_TOOLS } from "./utils/IconLoader.js"; import { registerImageInClipspace, startSAMDetectorMonitoring, setupSAMDetectorHook } from "./SAMDetectorIntegration.js"; diff --git a/src/CustomShapeMenu.ts b/src/CustomShapeMenu.ts index 15b44da..48747f3 100644 --- a/src/CustomShapeMenu.ts +++ b/src/CustomShapeMenu.ts @@ -1,4 +1,4 @@ -import {createModuleLogger} from "./utils/LoggerUtils.js"; +import {createModuleLogger} from "./log_system/log_funcs.js"; import { addStylesheet, getUrl } from "./utils/ResourceManager.js"; import type { Canvas } from './Canvas'; diff --git a/src/ErrorHandler.ts b/src/ErrorHandler.ts index 69192c0..3b98782 100644 --- a/src/ErrorHandler.ts +++ b/src/ErrorHandler.ts @@ -3,7 +3,7 @@ * Eliminuje powtarzalne wzorce obsługi błędów w całym projekcie */ -import {createModuleLogger} from "./utils/LoggerUtils.js"; +import {createModuleLogger} from "./log_system/log_funcs.js"; const log = createModuleLogger('ErrorHandler'); diff --git a/src/ImageCache.ts b/src/ImageCache.ts index 4e6337c..9d448d0 100644 --- a/src/ImageCache.ts +++ b/src/ImageCache.ts @@ -1,4 +1,4 @@ -import {createModuleLogger} from "./utils/LoggerUtils.js"; +import {createModuleLogger} from "./log_system/log_funcs.js"; import type { ImageDataPixel } from './types'; const log = createModuleLogger('ImageCache'); diff --git a/src/ImageReferenceManager.ts b/src/ImageReferenceManager.ts index ca28180..e9aba05 100644 --- a/src/ImageReferenceManager.ts +++ b/src/ImageReferenceManager.ts @@ -1,5 +1,5 @@ import {removeImage, getAllImageIds} from "./db.js"; -import {createModuleLogger} from "./utils/LoggerUtils.js"; +import {createModuleLogger} from "./log_system/log_funcs.js"; import type { Canvas } from './Canvas'; import type { Layer, CanvasState } from './types'; diff --git a/src/MaskEditorIntegration.ts b/src/MaskEditorIntegration.ts index cbca603..53c1e5d 100644 --- a/src/MaskEditorIntegration.ts +++ b/src/MaskEditorIntegration.ts @@ -4,7 +4,7 @@ import {app} from "../../scripts/app.js"; import {ComfyApp} from "../../scripts/app.js"; // @ts-ignore import {api} from "../../scripts/api.js"; -import { createModuleLogger } from "./utils/LoggerUtils.js"; +import { createModuleLogger } from "./log_system/log_funcs.js"; import { showErrorNotification } from "./utils/NotificationUtils.js"; import { uploadCanvasAsImage, uploadCanvasWithMaskAsImage, uploadImageBlob } from "./utils/ImageUploadUtils.js"; import { processImageToMask, processMaskForViewport } from "./utils/MaskProcessingUtils.js"; diff --git a/src/MaskTool.ts b/src/MaskTool.ts index c8eb1a2..94590af 100644 --- a/src/MaskTool.ts +++ b/src/MaskTool.ts @@ -1,4 +1,4 @@ -import {createModuleLogger} from "./utils/LoggerUtils.js"; +import {createModuleLogger} from "./log_system/log_funcs.js"; import { createCanvas } from "./utils/CommonUtils.js"; import type { Canvas } from './Canvas'; import type { Point, CanvasState } from './types'; diff --git a/src/SAMDetectorIntegration.ts b/src/SAMDetectorIntegration.ts index af9c58f..f6eb32e 100644 --- a/src/SAMDetectorIntegration.ts +++ b/src/SAMDetectorIntegration.ts @@ -2,7 +2,7 @@ import { api } from "../../scripts/api.js"; // @ts-ignore import { ComfyApp } from "../../scripts/app.js"; -import { createModuleLogger } from "./utils/LoggerUtils.js"; +import { createModuleLogger } from "./log_system/log_funcs.js"; import { showInfoNotification, showSuccessNotification, showErrorNotification } from "./utils/NotificationUtils.js"; import { uploadCanvasAsImage, uploadImageBlob } from "./utils/ImageUploadUtils.js"; import { processImageToMask } from "./utils/MaskProcessingUtils.js"; diff --git a/src/ShapeTool.ts b/src/ShapeTool.ts index aefe614..7366275 100644 --- a/src/ShapeTool.ts +++ b/src/ShapeTool.ts @@ -1,4 +1,4 @@ -import { createModuleLogger } from "./utils/LoggerUtils.js"; +import { createModuleLogger } from "./log_system/log_funcs.js"; import type { Canvas } from './Canvas.js'; import type { Point, Layer } from './types.js'; diff --git a/src/db.ts b/src/db.ts index 2d73aaa..5eacea1 100644 --- a/src/db.ts +++ b/src/db.ts @@ -1,4 +1,4 @@ -import {createModuleLogger} from "./utils/LoggerUtils.js"; +import {createModuleLogger} from "./log_system/log_funcs.js"; const log = createModuleLogger('db'); diff --git a/src/utils/ClipboardManager.ts b/src/utils/ClipboardManager.ts index 2eef1e6..996d0e1 100644 --- a/src/utils/ClipboardManager.ts +++ b/src/utils/ClipboardManager.ts @@ -1,4 +1,4 @@ -import {createModuleLogger} from "./LoggerUtils.js"; +import {createModuleLogger} from "../log_system/log_funcs.js"; import { showNotification, showInfoNotification, showErrorNotification, showWarningNotification } from "./NotificationUtils.js"; import { withErrorHandling, createValidationError, createNetworkError, createFileError } from "../ErrorHandler.js"; import { safeClipspacePaste } from "./ClipspaceUtils.js"; diff --git a/src/utils/ClipspaceUtils.ts b/src/utils/ClipspaceUtils.ts index 7402da4..ad78a37 100644 --- a/src/utils/ClipspaceUtils.ts +++ b/src/utils/ClipspaceUtils.ts @@ -1,4 +1,4 @@ -import { createModuleLogger } from "./LoggerUtils.js"; +import { createModuleLogger } from "../log_system/log_funcs.js"; // @ts-ignore import { ComfyApp } from "../../../scripts/app.js"; diff --git a/src/utils/IconLoader.ts b/src/utils/IconLoader.ts index 3eae143..1a43b67 100644 --- a/src/utils/IconLoader.ts +++ b/src/utils/IconLoader.ts @@ -1,4 +1,4 @@ -import { createModuleLogger } from "./LoggerUtils.js"; +import { createModuleLogger } from "../log_system/log_funcs.js"; import { createCanvas } from "./CommonUtils.js"; import { withErrorHandling, createValidationError } from "../ErrorHandler.js"; diff --git a/src/utils/ImageAnalysis.ts b/src/utils/ImageAnalysis.ts index ed350e7..955a98c 100644 --- a/src/utils/ImageAnalysis.ts +++ b/src/utils/ImageAnalysis.ts @@ -1,4 +1,4 @@ -import { createModuleLogger } from "./LoggerUtils.js"; +import { createModuleLogger } from "../log_system/log_funcs.js"; import { createCanvas } from "./CommonUtils.js"; import { withErrorHandling, createValidationError } from "../ErrorHandler.js"; diff --git a/src/utils/ImageUploadUtils.ts b/src/utils/ImageUploadUtils.ts index 713303c..d84d553 100644 --- a/src/utils/ImageUploadUtils.ts +++ b/src/utils/ImageUploadUtils.ts @@ -1,6 +1,6 @@ // @ts-ignore import { api } from "../../../scripts/api.js"; -import { createModuleLogger } from "./LoggerUtils.js"; +import { createModuleLogger } from "../log_system/log_funcs.js"; import { withErrorHandling, createValidationError, createNetworkError } from "../ErrorHandler.js"; const log = createModuleLogger('ImageUploadUtils'); diff --git a/src/utils/ImageUtils.ts b/src/utils/ImageUtils.ts index d7d0cba..72f6e47 100644 --- a/src/utils/ImageUtils.ts +++ b/src/utils/ImageUtils.ts @@ -1,4 +1,4 @@ -import {createModuleLogger} from "./LoggerUtils.js"; +import {createModuleLogger} from "../log_system/log_funcs.js"; import {withErrorHandling, createValidationError} from "../ErrorHandler.js"; import { createCanvas } from "./CommonUtils.js"; import type { Tensor, ImageDataPixel } from '../types'; diff --git a/src/utils/MaskProcessingUtils.ts b/src/utils/MaskProcessingUtils.ts index 89df6dc..eb929da 100644 --- a/src/utils/MaskProcessingUtils.ts +++ b/src/utils/MaskProcessingUtils.ts @@ -1,4 +1,4 @@ -import { createModuleLogger } from "./LoggerUtils.js"; +import { createModuleLogger } from "../log_system/log_funcs.js"; import { createCanvas } from "./CommonUtils.js"; import { convertToImage } from "./ImageUtils.js"; import { withErrorHandling, createValidationError } from "../ErrorHandler.js"; diff --git a/src/utils/NotificationUtils.ts b/src/utils/NotificationUtils.ts index 5fae050..e4a2395 100644 --- a/src/utils/NotificationUtils.ts +++ b/src/utils/NotificationUtils.ts @@ -9,7 +9,7 @@ description: Notification Utilities (Toast System) // 1. IMPORTS & DEPENDENCIES // ========================================== // Comment out or adjust this import if copying to a project that does not use AzLogs -import { createModuleLogger } from "./LoggerUtils.js"; +import { createModuleLogger } from "../log_system/log_funcs.js"; // ========================================== // 2. CONFIGURATION diff --git a/src/utils/PreviewUtils.ts b/src/utils/PreviewUtils.ts index 4e9ab7e..6803fa8 100644 --- a/src/utils/PreviewUtils.ts +++ b/src/utils/PreviewUtils.ts @@ -1,4 +1,4 @@ -import { createModuleLogger } from "./LoggerUtils.js"; +import { createModuleLogger } from "../log_system/log_funcs.js"; import { withErrorHandling, createValidationError } from "../ErrorHandler.js"; import type { ComfyNode } from '../types'; diff --git a/src/utils/ResourceManager.ts b/src/utils/ResourceManager.ts index e33cbb5..d84013e 100644 --- a/src/utils/ResourceManager.ts +++ b/src/utils/ResourceManager.ts @@ -1,6 +1,6 @@ // @ts-ignore import { $el } from "../../../scripts/ui.js"; -import { createModuleLogger } from "./LoggerUtils.js"; +import { createModuleLogger } from "../log_system/log_funcs.js"; import { withErrorHandling, createValidationError, createNetworkError } from "../ErrorHandler.js"; const log = createModuleLogger('ResourceManager'); diff --git a/src/utils/WebSocketManager.ts b/src/utils/WebSocketManager.ts index c0bf6c3..206770f 100644 --- a/src/utils/WebSocketManager.ts +++ b/src/utils/WebSocketManager.ts @@ -1,4 +1,4 @@ -import {createModuleLogger} from "./LoggerUtils.js"; +import {createModuleLogger} from "../log_system/log_funcs.js"; import { withErrorHandling, createValidationError, createNetworkError } from "../ErrorHandler.js"; import type { WebSocketMessage, AckCallbacks } from "../types.js"; diff --git a/src/utils/mask_utils.ts b/src/utils/mask_utils.ts index 4d82f4e..7fc1007 100644 --- a/src/utils/mask_utils.ts +++ b/src/utils/mask_utils.ts @@ -1,4 +1,4 @@ -import {createModuleLogger} from "./LoggerUtils.js"; +import {createModuleLogger} from "../log_system/log_funcs.js"; import { withErrorHandling, createValidationError } from "../ErrorHandler.js"; import type { Canvas } from '../Canvas.js'; // @ts-ignore diff --git a/tests/test_entrypoint_integration.py b/tests/test_entrypoint_integration.py index fbc9a8f..87ccd95 100644 --- a/tests/test_entrypoint_integration.py +++ b/tests/test_entrypoint_integration.py @@ -78,7 +78,7 @@ def _install_runtime_stubs(monkeypatch, tmp_path): monkeypatch.setitem(sys.modules, "tqdm", tqdm) # Avoid creating project log files while the entry point is imported. - from python.logger import logger + from python.log_system import logger monkeypatch.setattr(logger, "configure", lambda config: logger) diff --git a/tests/test_log_system.mjs b/tests/test_log_system.mjs index 7169741..5f06485 100644 --- a/tests/test_log_system.mjs +++ b/tests/test_log_system.mjs @@ -1,9 +1,8 @@ import assert from 'node:assert/strict'; import test from 'node:test'; -import { Logger, LogLevel } from '../js/log_system/logger.js'; +import { Logger, LogLevel, logger as sharedLogger } from '../js/log_system/logger.js'; import { createModuleLogger, withErrorLogging } from '../js/log_system/log_funcs.js'; -import * as legacyLogger from '../js/logger.js'; function silenceConsole() { @@ -20,7 +19,7 @@ function silenceConsole() { } -test('canonical logger handles levels, retention, callsites, and compatibility exports', () => { +test('canonical logger handles levels, retention, and callsites', () => { const restoreConsole = silenceConsole(); try { const logger = new Logger(); @@ -52,7 +51,7 @@ test('canonical logger handles levels, retention, callsites, and compatibility e logger.setEnabled(false); assert.equal(logger.isLevelEnabled('LayerForge.test', LogLevel.ERROR), false); - assert.equal(legacyLogger.Logger, Logger); + assert.equal(sharedLogger.constructor, Logger); assert.equal(typeof createModuleLogger('LayerForge.test').error, 'function'); } finally { restoreConsole();