FIX: Separate STATUS logger level

This commit is contained in:
Gourieff 2023-10-19 03:36:40 +07:00
parent 4e877445ba
commit 6be9162b1a
7 changed files with 53 additions and 35 deletions

View File

@ -114,7 +114,7 @@ def apply_logging_patch(console_logging_level):
logger.setLevel(logging.WARNING) logger.setLevel(logging.WARNING)
elif console_logging_level == 1: elif console_logging_level == 1:
patch_insightface(*patched_functions) patch_insightface(*patched_functions)
logger.setLevel(logging.INFO) logger.setLevel(logging.STATUS)
elif console_logging_level == 2: elif console_logging_level == 2:
patch_insightface(*original_functions) patch_insightface(*original_functions)
logger.setLevel(logging.INFO) logger.setLevel(logging.STATUS)

View File

@ -89,7 +89,7 @@ def reactor_api(_: gr.Blocks, app: FastAPI):
result_file_path = default_file_path() result_file_path = default_file_path()
try: try:
result[0].save(result_file_path, format='PNG') result[0].save(result_file_path, format='PNG')
logger.info("Result has been saved to: %s", result_file_path) logger.status("Result has been saved to: %s", result_file_path)
except Exception as e: except Exception as e:
logger.error("Error while saving result: %s",e) logger.error("Error while saving result: %s",e)
return {"image": api.encode_pil_to_base64(result[0])} return {"image": api.encode_pil_to_base64(result[0])}

View File

@ -266,11 +266,11 @@ class FaceSwapScript(scripts.Script):
if self.source is not None: if self.source is not None:
apply_logging_patch(console_logging_level) apply_logging_patch(console_logging_level)
if isinstance(p, StableDiffusionProcessingImg2Img) and swap_in_source: if isinstance(p, StableDiffusionProcessingImg2Img) and swap_in_source:
logger.info("Working: source face index %s, target face index %s", self.source_faces_index, self.faces_index) logger.status("Working: source face index %s, target face index %s", self.source_faces_index, self.faces_index)
for i in range(len(p.init_images)): for i in range(len(p.init_images)):
if len(p.init_images) > 1: if len(p.init_images) > 1:
logger.info("Swap in %s", i) logger.status("Swap in %s", i)
result, output, swapped = swap_face( result, output, swapped = swap_face(
self.source, self.source,
p.init_images[i], p.init_images[i],
@ -311,14 +311,14 @@ class FaceSwapScript(scripts.Script):
# result_info: List = processed.infotexts # result_info: List = processed.infotexts
if self.swap_in_generated: if self.swap_in_generated:
logger.info("Working: source face index %s, target face index %s", self.source_faces_index, self.faces_index) logger.status("Working: source face index %s, target face index %s", self.source_faces_index, self.faces_index)
if self.source is not None: if self.source is not None:
for i,(img,info) in enumerate(zip(orig_images, orig_infotexts)): for i,(img,info) in enumerate(zip(orig_images, orig_infotexts)):
if check_process_halt(): if check_process_halt():
postprocess_run = False postprocess_run = False
break break
if len(orig_images) > 1: if len(orig_images) > 1:
logger.info("Swap in %s", i) logger.status("Swap in %s", i)
result, output, swapped = swap_face( result, output, swapped = swap_face(
self.source, self.source,
img, img,
@ -371,7 +371,7 @@ class FaceSwapScript(scripts.Script):
return return
if self.source is not None: if self.source is not None:
logger.info("Working: source face index %s, target face index %s", self.source_faces_index, self.faces_index) logger.status("Working: source face index %s, target face index %s", self.source_faces_index, self.faces_index)
image: Image.Image = script_pp.image image: Image.Image = script_pp.image
result, output, swapped = swap_face( result, output, swapped = swap_face(
self.source, self.source,

View File

@ -3,6 +3,7 @@ from collections import Counter
from PIL import Image from PIL import Image
from math import isqrt, ceil from math import isqrt, ceil
from typing import List from typing import List
import logging
from modules.images import FilenameGenerator, get_next_sequence_number from modules.images import FilenameGenerator, get_next_sequence_number
from modules import shared, script_callbacks from modules import shared, script_callbacks
@ -100,3 +101,19 @@ def get_image_path(image, path, basename, seed=None, prompt=None, extension='png
fullfn = params.filename fullfn = params.filename
return fullfn return fullfn
def addLoggingLevel(levelName, levelNum, methodName=None):
if not methodName:
methodName = levelName.lower()
def logForLevel(self, message, *args, **kwargs):
if self.isEnabledFor(levelNum):
self._log(levelNum, message, args, **kwargs)
def logToRoot(message, *args, **kwargs):
logging.log(levelNum, message, *args, **kwargs)
logging.addLevelName(levelNum, levelName)
setattr(logging, levelName, levelNum)
setattr(logging.getLoggerClass(), methodName, logForLevel)
setattr(logging, methodName, logToRoot)

View File

@ -4,6 +4,7 @@ import sys
from modules import shared from modules import shared
from scripts.reactor_globals import IS_RUN from scripts.reactor_globals import IS_RUN
from scripts.reactor_helpers import addLoggingLevel
class ColoredFormatter(logging.Formatter): class ColoredFormatter(logging.Formatter):
@ -29,8 +30,8 @@ class ColoredFormatter(logging.Formatter):
logger = logging.getLogger("ReActor") logger = logging.getLogger("ReActor")
logger.propagate = False logger.propagate = False
# Custom Level name # Add Custom Level
logging.addLevelName(logging.INFO, "STATUS") addLoggingLevel("STATUS", logging.INFO - 5)
# Add handler if we don't have one. # Add handler if we don't have one.
if not logger.handlers: if not logger.handlers:
@ -41,8 +42,8 @@ if not logger.handlers:
logger.addHandler(handler) logger.addHandler(handler)
# Configure logger # Configure logger
loglevel_string = getattr(shared.cmd_opts, "reactor_loglevel", "INFO") loglevel_string = getattr(shared.cmd_opts, "reactor_loglevel", "STATUS")
loglevel = getattr(logging, loglevel_string.upper(), "info") loglevel = getattr(logging, loglevel_string.upper(), "status")
logger.setLevel(loglevel) logger.setLevel(loglevel)
def set_Run(value): def set_Run(value):

View File

@ -58,12 +58,12 @@ def check_process_halt(msgforced: bool = False):
global MESSAGED_STOPPED, MESSAGED_SKIPPED global MESSAGED_STOPPED, MESSAGED_SKIPPED
if state.interrupted: if state.interrupted:
if not MESSAGED_STOPPED or msgforced: if not MESSAGED_STOPPED or msgforced:
logger.info("Stopped by User") logger.status("Stopped by User")
MESSAGED_STOPPED = True MESSAGED_STOPPED = True
return True return True
if state.skipped: if state.skipped:
if not MESSAGED_SKIPPED or msgforced: if not MESSAGED_SKIPPED or msgforced:
logger.info("Skipped by User") logger.status("Skipped by User")
MESSAGED_SKIPPED = True MESSAGED_SKIPPED = True
return True return True
return False return False
@ -102,7 +102,7 @@ def restore_face(image: Image, enhancement_options: EnhancementOptions):
if enhancement_options.face_restorer is not None: if enhancement_options.face_restorer is not None:
original_image = result_image.copy() original_image = result_image.copy()
logger.info("Restoring the face with %s", enhancement_options.face_restorer.name()) logger.status("Restoring the face with %s", enhancement_options.face_restorer.name())
numpy_image = np.array(result_image) numpy_image = np.array(result_image)
if enhancement_options.face_restorer.name() == "CodeFormer": if enhancement_options.face_restorer.name() == "CodeFormer":
numpy_image = codeformer_model.codeformer.restore( numpy_image = codeformer_model.codeformer.restore(
@ -125,7 +125,7 @@ def upscale_image(image: Image, enhancement_options: EnhancementOptions):
if enhancement_options.upscaler is not None and enhancement_options.upscaler.name != "None": if enhancement_options.upscaler is not None and enhancement_options.upscaler.name != "None":
original_image = result_image.copy() original_image = result_image.copy()
logger.info( logger.status(
"Upscaling with %s scale = %s", "Upscaling with %s scale = %s",
enhancement_options.upscaler.name, enhancement_options.upscaler.name,
enhancement_options.scale, enhancement_options.scale,
@ -181,15 +181,15 @@ def get_face_gender(
face_gender = gender_detected face_gender = gender_detected
if face_gender == "None": if face_gender == "None":
return None, 0 return None, 0
logger.info("%s Face %s: Detected Gender -%s-", operated, face_index, face_gender) logger.status("%s Face %s: Detected Gender -%s-", operated, face_index, face_gender)
if (gender_condition == 1 and face_gender == "F") or (gender_condition == 2 and face_gender == "M"): if (gender_condition == 1 and face_gender == "F") or (gender_condition == 2 and face_gender == "M"):
logger.info("OK - Detected Gender matches Condition") logger.status("OK - Detected Gender matches Condition")
try: try:
return sorted(face, key=lambda x: x.bbox[0])[face_index], 0 return sorted(face, key=lambda x: x.bbox[0])[face_index], 0
except IndexError: except IndexError:
return None, 0 return None, 0
else: else:
logger.info("WRONG - Detected Gender doesn't match Condition") logger.status("WRONG - Detected Gender doesn't match Condition")
return sorted(face, key=lambda x: x.bbox[0])[face_index], 1 return sorted(face, key=lambda x: x.bbox[0])[face_index], 1
def get_face_age(face, face_index): def get_face_age(face, face_index):
@ -210,7 +210,7 @@ def get_face_age(face, face_index):
# return get_face_single(img_data, face, face_index=face_index, det_size=det_size_half, gender_source=gender_source, gender_target=gender_target) # return get_face_single(img_data, face, face_index=face_index, det_size=det_size_half, gender_source=gender_source, gender_target=gender_target)
def half_det_size(det_size): def half_det_size(det_size):
logger.info("Trying to halve 'det_size' parameter") logger.status("Trying to halve 'det_size' parameter")
return (det_size[0] // 2, det_size[1] // 2) return (det_size[0] // 2, det_size[1] // 2)
def analyze_faces(img_data: np.ndarray, det_size=(640, 640)): def analyze_faces(img_data: np.ndarray, det_size=(640, 640)):
@ -299,24 +299,24 @@ def swap_face(
output_info: str = "" output_info: str = ""
swapped = 0 swapped = 0
logger.info("Analyzing Source Image...") logger.status("Analyzing Source Image...")
source_faces = analyze_faces(source_img) source_faces = analyze_faces(source_img)
if source_faces is not None: if source_faces is not None:
logger.info("Analyzing Target Image...") logger.status("Analyzing Target Image...")
target_faces = analyze_faces(target_img) target_faces = analyze_faces(target_img)
logger.info("Detecting Source Face, Index = %s", source_faces_index[0]) logger.status("Detecting Source Face, Index = %s", source_faces_index[0])
source_face, wrong_gender, source_age, source_gender = get_face_single(source_img, source_faces, face_index=source_faces_index[0], gender_source=gender_source) source_face, wrong_gender, source_age, source_gender = get_face_single(source_img, source_faces, face_index=source_faces_index[0], gender_source=gender_source)
if source_age != "None" or source_gender != "None": if source_age != "None" or source_gender != "None":
logger.info("Detected: -%s- y.o. %s", source_age, source_gender) logger.status("Detected: -%s- y.o. %s", source_age, source_gender)
output_info = f"SourceFaceIndex={source_faces_index[0]};Age={source_age};Gender={source_gender}\n" output_info = f"SourceFaceIndex={source_faces_index[0]};Age={source_age};Gender={source_gender}\n"
output.append(output_info) output.append(output_info)
if len(source_faces_index) != 0 and len(source_faces_index) != 1 and len(source_faces_index) != len(faces_index): if len(source_faces_index) != 0 and len(source_faces_index) != 1 and len(source_faces_index) != len(faces_index):
logger.info("Source Faces must have no entries (default=0), one entry, or same number of entries as target faces.") logger.status("Source Faces must have no entries (default=0), one entry, or same number of entries as target faces.")
elif source_face is not None: elif source_face is not None:
result = target_img result = target_img
@ -328,10 +328,10 @@ def swap_face(
if check_process_halt(): if check_process_halt():
return result_image, [], 0 return result_image, [], 0
if len(source_faces_index) > 1 and source_face_idx > 0: if len(source_faces_index) > 1 and source_face_idx > 0:
logger.info("Detecting Source Face, Index = %s", source_faces_index[source_face_idx]) logger.status("Detecting Source Face, Index = %s", source_faces_index[source_face_idx])
source_face, wrong_gender, source_age, source_gender = get_face_single(source_img, source_faces, face_index=source_faces_index[source_face_idx], gender_source=gender_source) source_face, wrong_gender, source_age, source_gender = get_face_single(source_img, source_faces, face_index=source_faces_index[source_face_idx], gender_source=gender_source)
if source_age != "None" or source_gender != "None": if source_age != "None" or source_gender != "None":
logger.info("Detected: -%s- y.o. %s", source_age, source_gender) logger.status("Detected: -%s- y.o. %s", source_age, source_gender)
output_info = f"SourceFaceIndex={source_faces_index[source_face_idx]};Age={source_age};Gender={source_gender}\n" output_info = f"SourceFaceIndex={source_faces_index[source_face_idx]};Age={source_age};Gender={source_gender}\n"
output.append(output_info) output.append(output_info)
@ -339,16 +339,16 @@ def swap_face(
source_face_idx += 1 source_face_idx += 1
if source_face is not None and wrong_gender == 0: if source_face is not None and wrong_gender == 0:
logger.info("Detecting Target Face, Index = %s", face_num) logger.status("Detecting Target Face, Index = %s", face_num)
target_face, wrong_gender, target_age, target_gender = get_face_single(target_img, target_faces, face_index=face_num, gender_target=gender_target) target_face, wrong_gender, target_age, target_gender = get_face_single(target_img, target_faces, face_index=face_num, gender_target=gender_target)
if target_age != "None" or target_gender != "None": if target_age != "None" or target_gender != "None":
logger.info("Detected: -%s- y.o. %s", target_age, target_gender) logger.status("Detected: -%s- y.o. %s", target_age, target_gender)
output_info = f"TargetFaceIndex={face_num};Age={target_age};Gender={target_gender}\n" output_info = f"TargetFaceIndex={face_num};Age={target_age};Gender={target_gender}\n"
output.append(output_info) output.append(output_info)
if target_face is not None and wrong_gender == 0: if target_face is not None and wrong_gender == 0:
logger.info("Swapping Source into Target") logger.status("Swapping Source into Target")
result = face_swapper.get(result, target_face, source_face) result = face_swapper.get(result, target_face, source_face)
swapped += 1 swapped += 1
@ -364,7 +364,7 @@ def swap_face(
return result_image, output, swapped return result_image, output, swapped
else: else:
logger.info(f"No target face found for {face_num}") logger.status(f"No target face found for {face_num}")
elif wrong_gender == 1: elif wrong_gender == 1:
wrong_gender = 0 wrong_gender = 0
@ -378,7 +378,7 @@ def swap_face(
return result_image, output, swapped return result_image, output, swapped
else: else:
logger.info(f"No source face found for face number {source_face_idx}.") logger.status(f"No source face found for face number {source_face_idx}.")
result_image = Image.fromarray(cv2.cvtColor(result, cv2.COLOR_BGR2RGB)) result_image = Image.fromarray(cv2.cvtColor(result, cv2.COLOR_BGR2RGB))
@ -386,8 +386,8 @@ def swap_face(
result_image = enhance_image(result_image, enhancement_options) result_image = enhance_image(result_image, enhancement_options)
else: else:
logger.info("No source face(s) in the provided Index") logger.status("No source face(s) in the provided Index")
else: else:
logger.info("No source face(s) found") logger.status("No source face(s) found")
return result_image, output, swapped return result_image, output, swapped

View File

@ -6,5 +6,5 @@ from scripts.reactor_logger import logger, get_Run, set_Run
is_run = get_Run() is_run = get_Run()
if not is_run: if not is_run:
logger.info(f"Running {version_flag}") logger.status(f"Running {version_flag}")
set_Run(True) set_Run(True)