q6 commited on
Commit
d548b02
·
1 Parent(s): 80a3417

Classify ComfyUI stealth PNG metadata

Browse files
Files changed (1) hide show
  1. backend/app.py +19 -13
backend/app.py CHANGED
@@ -67,6 +67,8 @@ THUMB_DIR = Path(tempfile.gettempdir()) / "pixif2-thumbs"
67
  PAGE_URL_CACHE_MAX_AGE = 1800
68
  WEBP_SCALE = 0.4
69
  WEBP_QUALITY = 82
 
 
70
 
71
  app = FastAPI()
72
  ACTIVE_TASKS = {}
@@ -798,23 +800,27 @@ def determine_exif_type(fields):
798
  return None
799
 
800
 
801
- def byteize(alpha):
802
- alpha = alpha.T.reshape((-1,))
803
- alpha = alpha[: (alpha.shape[0] // 8) * 8]
804
- alpha = np.bitwise_and(alpha, 1)
805
- alpha = alpha.reshape((-1, 8))
806
- return np.packbits(alpha, axis=1)
 
 
 
 
807
 
808
 
809
  def has_stealth_png_bytes(data):
810
  try:
811
  image = Image.open(io.BytesIO(data))
812
- if "A" not in image.getbands():
813
- return False
814
- alpha = np.array(image.getchannel("A"))
815
- arr = byteize(alpha).flatten()
816
- magic = b"stealth_pngcomp"
817
- return bytes(arr[: len(magic)]) == magic
818
  except Exception:
819
  return False
820
 
@@ -833,7 +839,7 @@ async def scan_post(post_id, session, post_sem, exif_sem, img_sem):
833
  for url in image_urls:
834
  img_data = await fetch_image(session, url, img_sem)
835
  if img_data and has_stealth_png_bytes(img_data):
836
- return post_id, url, EXIF_TYPE_TO_CODE.get("stealth")
837
  return post_id, None, None
838
  except Exception:
839
  return post_id, None, None
 
67
  PAGE_URL_CACHE_MAX_AGE = 1800
68
  WEBP_SCALE = 0.4
69
  WEBP_QUALITY = 82
70
+ STEALTH_ALPHA_SIGS = (b"stealth_pnginfo", b"stealth_pngcomp")
71
+ STEALTH_RGB_SIGS = (b"stealth_rgbinfo", b"stealth_rgbcomp")
72
 
73
  app = FastAPI()
74
  ACTIVE_TASKS = {}
 
800
  return None
801
 
802
 
803
+ def byteize(bits):
804
+ bits = bits[: (bits.shape[0] // 8) * 8]
805
+ bits = np.bitwise_and(bits, 1)
806
+ bits = bits.reshape((-1, 8))
807
+ return np.packbits(bits, axis=1).flatten()
808
+
809
+
810
+ def has_magic(arr, sigs):
811
+ raw = bytes(byteize(arr)[: max(len(sig) for sig in sigs)])
812
+ return any(raw.startswith(sig) for sig in sigs)
813
 
814
 
815
  def has_stealth_png_bytes(data):
816
  try:
817
  image = Image.open(io.BytesIO(data))
818
+ if "A" in image.getbands():
819
+ alpha = np.array(image.getchannel("A")).T.reshape((-1,))
820
+ if has_magic(alpha, STEALTH_ALPHA_SIGS):
821
+ return True
822
+ rgb = np.array(image.convert("RGB")).transpose((1, 0, 2)).reshape((-1,))
823
+ return has_magic(rgb, STEALTH_RGB_SIGS)
824
  except Exception:
825
  return False
826
 
 
839
  for url in image_urls:
840
  img_data = await fetch_image(session, url, img_sem)
841
  if img_data and has_stealth_png_bytes(img_data):
842
+ return post_id, url, EXIF_TYPE_TO_CODE.get("comfy")
843
  return post_id, None, None
844
  except Exception:
845
  return post_id, None, None