ballagb19 commited on
Commit
32800ec
·
verified ·
1 Parent(s): 59da50d

Upload captcha_solver/utils/image.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. captcha_solver/utils/image.py +76 -0
captcha_solver/utils/image.py ADDED
@@ -0,0 +1,76 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Image / audio decoding helpers."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import base64
6
+ import io
7
+ from typing import Optional
8
+
9
+ import numpy as np
10
+ from PIL import Image
11
+
12
+
13
+ def decode_base64_image(b64: str) -> bytes:
14
+ """Decode a base64 string to raw image bytes.
15
+
16
+ Strips data URL prefix if present.
17
+ Raises ValueError on bad input.
18
+ """
19
+ if not b64:
20
+ raise ValueError("empty base64 image")
21
+ if "," in b64 and b64.startswith("data:"):
22
+ b64 = b64.split(",", 1)[1]
23
+ try:
24
+ return base64.b64decode(b64, validate=True)
25
+ except Exception as exc:
26
+ raise ValueError(f"invalid base64: {exc}") from exc
27
+
28
+
29
+ def decode_base64_audio(b64: str) -> bytes:
30
+ """Decode a base64 string to raw audio bytes."""
31
+ if not b64:
32
+ raise ValueError("empty base64 audio")
33
+ if "," in b64 and b64.startswith("data:"):
34
+ b64 = b64.split(",", 1)[1]
35
+ try:
36
+ return base64.b64decode(b64, validate=True)
37
+ except Exception as exc:
38
+ raise ValueError(f"invalid base64: {exc}") from exc
39
+
40
+
41
+ def image_to_pil(data: bytes) -> Image.Image:
42
+ """Decode image bytes to a PIL Image. Raises ValueError on failure."""
43
+ try:
44
+ img = Image.open(io.BytesIO(data))
45
+ img.load()
46
+ if img.mode not in ("RGB", "RGBA", "L"):
47
+ img = img.convert("RGB")
48
+ return img
49
+ except Exception as exc:
50
+ raise ValueError(f"could not decode image: {exc}") from exc
51
+
52
+
53
+ def perceptual_hash(data: bytes, size: int = 16) -> str:
54
+ """Compute a perceptual hash of an image for cache lookup.
55
+
56
+ Returns a 64-char hex string. Robust to small JPEG re-encodes
57
+ and minor color shifts.
58
+ """
59
+ img = image_to_pil(data).convert("L").resize((size + 1, size))
60
+ pixels = np.asarray(img, dtype=np.float32)
61
+ diff = pixels[:, 1:] > pixels[:, :-1]
62
+ bits = diff.flatten()
63
+ h = 0
64
+ for bit in bits:
65
+ h = (h << 1) | int(bit)
66
+ return format(h, f"0{size*size // 4}x")
67
+
68
+
69
+ def audio_size_hash(data: bytes) -> str:
70
+ """Cheap audio hash: size + first/last 1KB + sha-like prefix."""
71
+ import hashlib
72
+ h = hashlib.sha256()
73
+ h.update(len(data).to_bytes(8, "big"))
74
+ h.update(data[:1024])
75
+ h.update(data[-1024:])
76
+ return h.hexdigest()[:32]