DmitryPlant commited on
Commit
ff474d8
·
1 Parent(s): 3a4474d

refactor(backend): rename png_b64_to_bgr to img_b64_to_bgr and add JPEG test

Browse files
Files changed (3) hide show
  1. analysis/encoding.py +13 -10
  2. app.py +2 -2
  3. tests/test_encoding.py +21 -4
analysis/encoding.py CHANGED
@@ -1,11 +1,12 @@
1
  import base64
 
2
 
3
  import cv2
4
  import numpy as np
5
 
6
 
7
- _DATA_URI_PREFIX = "data:image/png;base64,"
8
- _DATA_URI_PREFIX_JPEG = "data:image/jpeg;base64,"
9
 
10
 
11
  def bgr_to_png_b64(img: np.ndarray) -> str:
@@ -13,16 +14,18 @@ def bgr_to_png_b64(img: np.ndarray) -> str:
13
  ok, buf = cv2.imencode(".png", img)
14
  if not ok:
15
  raise ValueError("cv2.imencode failed")
16
- return _DATA_URI_PREFIX + base64.b64encode(buf.tobytes()).decode("ascii")
17
 
18
 
19
- def png_b64_to_bgr(encoded: str) -> np.ndarray:
20
- """Decode a data: URI (PNG or JPEG) or raw base64 image back to a BGR/grayscale array."""
21
- if encoded.startswith(_DATA_URI_PREFIX):
22
- encoded = encoded[len(_DATA_URI_PREFIX):]
23
- elif encoded.startswith(_DATA_URI_PREFIX_JPEG):
24
- encoded = encoded[len(_DATA_URI_PREFIX_JPEG):]
25
- raw = base64.b64decode(encoded)
 
 
26
  arr = np.frombuffer(raw, dtype=np.uint8)
27
  img = cv2.imdecode(arr, cv2.IMREAD_UNCHANGED)
28
  if img is None:
 
1
  import base64
2
+ import re
3
 
4
  import cv2
5
  import numpy as np
6
 
7
 
8
+ _PNG_DATA_URI_PREFIX = "data:image/png;base64,"
9
+ _DATA_URI_RE = re.compile(r"^data:image/[a-zA-Z0-9.+-]+;base64,")
10
 
11
 
12
  def bgr_to_png_b64(img: np.ndarray) -> str:
 
14
  ok, buf = cv2.imencode(".png", img)
15
  if not ok:
16
  raise ValueError("cv2.imencode failed")
17
+ return _PNG_DATA_URI_PREFIX + base64.b64encode(buf.tobytes()).decode("ascii")
18
 
19
 
20
+ def img_b64_to_bgr(encoded: str) -> np.ndarray:
21
+ """Decode any base64-encoded image (PNG, JPEG, ...) — with or without a
22
+ ``data:image/<fmt>;base64,`` prefix — into a BGR/grayscale ndarray.
23
+
24
+ cv2.imdecode auto-detects the format from the bytes' magic header, so
25
+ the URI prefix (if present) is only used to strip non-base64 bytes.
26
+ """
27
+ stripped = _DATA_URI_RE.sub("", encoded, count=1)
28
+ raw = base64.b64decode(stripped)
29
  arr = np.frombuffer(raw, dtype=np.uint8)
30
  img = cv2.imdecode(arr, cv2.IMREAD_UNCHANGED)
31
  if img is None:
app.py CHANGED
@@ -4,7 +4,7 @@ from fastapi import FastAPI, HTTPException
4
  from fastapi.middleware.cors import CORSMiddleware
5
  from pydantic import BaseModel, Field
6
 
7
- from analysis.encoding import bgr_to_png_b64, png_b64_to_bgr
8
  from analysis.params import AnalysisParams
9
  from analysis.pipeline import run
10
  from analysis.scoring import score
@@ -47,7 +47,7 @@ def health() -> dict[str, str]:
47
  @app.post("/analyze")
48
  def analyze(req: AnalyzeRequest) -> dict[str, Any]:
49
  try:
50
- img = png_b64_to_bgr(req.image_b64)
51
  except ValueError as e:
52
  raise HTTPException(status_code=400, detail=f"decode failed: {e}") from e
53
 
 
4
  from fastapi.middleware.cors import CORSMiddleware
5
  from pydantic import BaseModel, Field
6
 
7
+ from analysis.encoding import bgr_to_png_b64, img_b64_to_bgr
8
  from analysis.params import AnalysisParams
9
  from analysis.pipeline import run
10
  from analysis.scoring import score
 
47
  @app.post("/analyze")
48
  def analyze(req: AnalyzeRequest) -> dict[str, Any]:
49
  try:
50
+ img = img_b64_to_bgr(req.image_b64)
51
  except ValueError as e:
52
  raise HTTPException(status_code=400, detail=f"decode failed: {e}") from e
53
 
tests/test_encoding.py CHANGED
@@ -1,8 +1,10 @@
1
  import base64
 
2
 
 
3
  import numpy as np
4
 
5
- from analysis.encoding import bgr_to_png_b64, png_b64_to_bgr
6
 
7
 
8
  def test_round_trip_preserves_bgr_bytes():
@@ -10,7 +12,7 @@ def test_round_trip_preserves_bgr_bytes():
10
  img = rng.integers(0, 255, size=(64, 64, 3), dtype=np.uint8)
11
  encoded = bgr_to_png_b64(img)
12
  assert encoded.startswith("data:image/png;base64,")
13
- decoded = png_b64_to_bgr(encoded)
14
  assert decoded.shape == img.shape
15
  # PNG is lossless: bytes match exactly
16
  assert np.array_equal(decoded, img)
@@ -20,12 +22,27 @@ def test_decodes_raw_base64_without_data_uri_prefix():
20
  img = np.zeros((4, 4, 3), dtype=np.uint8)
21
  encoded = bgr_to_png_b64(img)
22
  raw_b64 = encoded.removeprefix("data:image/png;base64,")
23
- assert np.array_equal(png_b64_to_bgr(raw_b64), img)
24
 
25
 
26
  def test_round_trip_grayscale():
27
  img = np.arange(64, dtype=np.uint8).reshape(8, 8)
28
  encoded = bgr_to_png_b64(img)
29
- decoded = png_b64_to_bgr(encoded)
30
  assert decoded.shape == img.shape
31
  assert np.array_equal(decoded, img)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import base64
2
+ from pathlib import Path
3
 
4
+ import cv2
5
  import numpy as np
6
 
7
+ from analysis.encoding import bgr_to_png_b64, img_b64_to_bgr
8
 
9
 
10
  def test_round_trip_preserves_bgr_bytes():
 
12
  img = rng.integers(0, 255, size=(64, 64, 3), dtype=np.uint8)
13
  encoded = bgr_to_png_b64(img)
14
  assert encoded.startswith("data:image/png;base64,")
15
+ decoded = img_b64_to_bgr(encoded)
16
  assert decoded.shape == img.shape
17
  # PNG is lossless: bytes match exactly
18
  assert np.array_equal(decoded, img)
 
22
  img = np.zeros((4, 4, 3), dtype=np.uint8)
23
  encoded = bgr_to_png_b64(img)
24
  raw_b64 = encoded.removeprefix("data:image/png;base64,")
25
+ assert np.array_equal(img_b64_to_bgr(raw_b64), img)
26
 
27
 
28
  def test_round_trip_grayscale():
29
  img = np.arange(64, dtype=np.uint8).reshape(8, 8)
30
  encoded = bgr_to_png_b64(img)
31
+ decoded = img_b64_to_bgr(encoded)
32
  assert decoded.shape == img.shape
33
  assert np.array_equal(decoded, img)
34
+
35
+
36
+ def test_decodes_jpeg_with_jpeg_data_uri_prefix():
37
+ # A real JPEG from the dataset: confirm the decoder accepts the
38
+ # data:image/jpeg;base64, prefix and recovers a valid BGR ndarray.
39
+ sample = Path(__file__).resolve().parent.parent.parent / "dataset" / "photo_2026-01-22_19-20-24.jpg"
40
+ raw = sample.read_bytes()
41
+ encoded = "data:image/jpeg;base64," + base64.b64encode(raw).decode()
42
+ decoded = img_b64_to_bgr(encoded)
43
+ assert decoded.ndim == 3
44
+ assert decoded.dtype == np.uint8
45
+ # The same bytes loaded via cv2.imread should match what cv2.imdecode produced.
46
+ reference = cv2.imread(str(sample))
47
+ assert decoded.shape == reference.shape
48
+ assert np.array_equal(decoded, reference)