FaustDerLegende's picture
Upload folder using huggingface_hub (part 53)
ff85f82 verified
Raw History Blame Contribute Delete
2.79 kB
"""Shared fixtures. All images are generated programmatically (no binary fixtures shipped)."""
from __future__ import annotations
import sys
from pathlib import Path
import numpy as np
import pytest
from PIL import Image, ImageDraw
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
from pipeline.config import get_paths, load_config # noqa: E402
from pipeline.manifest import Manifest # noqa: E402
def pcb_like(width: int, height: int, seed: int = 0) -> Image.Image:
"""Textured, board-ish RGB image (green base, random 'components'); seed controls layout."""
rng = np.random.default_rng(seed)
base = np.zeros((height, width, 3), dtype=np.uint8)
base[..., 1] = 90
base[..., 0] = 20
noise = rng.integers(0, 40, size=(height, width, 3), dtype=np.uint8)
img = Image.fromarray(np.clip(base + noise, 0, 255).astype(np.uint8))
draw = ImageDraw.Draw(img)
for _ in range(60):
x0, y0 = int(rng.integers(0, width - 30)), int(rng.integers(0, height - 30))
w, h = int(rng.integers(10, 80)), int(rng.integers(10, 60))
color = tuple(int(c) for c in rng.integers(0, 255, size=3))
draw.rectangle([x0, y0, x0 + w, y0 + h], fill=color, outline=(255, 215, 0))
return img
@pytest.fixture
def cfg():
return load_config()
@pytest.fixture
def paths(tmp_path, cfg):
p = get_paths(cfg, tmp_path)
p.ensure()
return p
@pytest.fixture
def manifest(paths):
m = Manifest(paths.manifest_db)
yield m
m.close()
@pytest.fixture
def make_image(tmp_path):
"""Factory: save a synthetic image to disk; returns the Path."""
counter = {"n": 0}
def _make(size=(1000, 800), fmt="JPEG", seed=0, name=None, mode=None, **save_kw) -> Path:
counter["n"] += 1
img = pcb_like(size[0], size[1], seed)
if mode:
img = img.convert(mode)
ext = {"JPEG": "jpg", "PNG": "png", "WEBP": "webp", "GIF": "gif", "BMP": "bmp", "TIFF": "tif"}[fmt]
path = tmp_path / (name or f"img_{counter['n']}.{ext}")
if fmt == "JPEG" and "quality" not in save_kw:
save_kw["quality"] = 95
img.save(path, format=fmt, **save_kw)
return path
return _make
def register_image(manifest, paths, src: Path, status="downloaded", origin="web", **extra) -> str:
"""Copy `src` into the originals store and register it in the manifest."""
import hashlib
import shutil
data = src.read_bytes()
sha = hashlib.sha256(data).hexdigest()
image_id = sha[:16]
dst = paths.originals / f"{image_id}{src.suffix}"
shutil.copyfile(src, dst)
manifest.add_image(image_id=image_id, sha256=sha, origin=origin, orig_path=paths.rel(dst),
filesize=len(data), status=status, **extra)
return image_id