Micro_component_dataset / tests /test_pipeline.py
FaustDerLegende's picture
Upload folder using huggingface_hub (part 100)
4c01f30 verified
Raw History Blame Contribute Delete
7.52 kB
"""Unit test suite for pipeline modules."""
from __future__ import annotations
import tempfile
import unittest
from pathlib import Path
import numpy as np
from PIL import Image, PngImagePlugin
from pipeline.config import load_config, load_taxonomy, load_queries, get_paths
from pipeline.manifest import Manifest, normalize_url
from pipeline.queries import build_queries
from pipeline.validator import validate_image
from pipeline.processor import normalize_image
from pipeline.dedup import compute_hashes, find_duplicate_groups
class TestPipeline(unittest.TestCase):
def setUp(self):
self.cfg = load_config()
self.temp_dir_obj = tempfile.TemporaryDirectory()
self.tmp_dir = Path(self.temp_dir_obj.name)
self.paths = get_paths(self.cfg, base=self.tmp_dir)
self.paths.ensure()
self.db_path = self.paths.manifest_db
self.manifest = Manifest(self.db_path)
def tearDown(self):
self.manifest.close()
self.temp_dir_obj.cleanup()
def test_url_normalization(self):
url = "HTTPS://Example.com:443/path/to/img.jpg?utm_source=test&gclid=123&ref=abc#section"
norm = normalize_url(url)
self.assertEqual(norm, "https://example.com/path/to/img.jpg?ref=abc")
def test_manifest_sources_and_hits(self):
url = "https://example.com/test_board.jpg"
is_new = self.manifest.add_hit(url, "bing", "PCB socket", class_hint="cpu_socket")
self.assertTrue(is_new)
pending = self.manifest.pending_sources()
self.assertEqual(len(pending), 1)
self.assertEqual(pending[0]["url_norm"], "https://example.com/test_board.jpg")
self.manifest.mark_source(pending[0]["url_norm"], status="downloaded", image_id="img_001")
pending_after = self.manifest.pending_sources()
self.assertEqual(len(pending_after), 0)
def test_manifest_image_lifecycle(self):
inserted = self.manifest.add_image(
image_id="abc12345",
sha256="1234567890abcdef",
orig_path="originals/abc12345.jpg",
status="downloaded",
)
self.assertTrue(inserted)
img = self.manifest.get_image("abc12345")
self.assertIsNotNone(img)
self.assertEqual(img["status"], "downloaded")
self.manifest.update_image("abc12345", status="validated", width=1000, height=800)
img_updated = self.manifest.get_image("abc12345")
self.assertEqual(img_updated["status"], "validated")
self.assertEqual(img_updated["width"], 1000)
def test_query_builder(self):
qcfg = load_queries(self.cfg)
queries = build_queries(qcfg)
self.assertGreater(len(queries), 0)
classes = {q.class_hint for q in queries}
self.assertIn("cpu_socket", classes)
self.assertIn("ic_chip", classes)
def test_validator(self):
# Valid PCB image with noise so PNG/JPEG size > 5000 bytes
test_img_path = self.tmp_dir / "valid_pcb.png"
arr = np.random.randint(0, 255, (800, 1000, 3), dtype=np.uint8)
img = Image.fromarray(arr)
img.save(test_img_path, format="PNG")
res = validate_image(test_img_path, self.cfg["validate"])
self.assertTrue(res.ok)
self.assertEqual(res.width, 1000)
self.assertEqual(res.height, 800)
# Too small file test (< 5000 bytes)
small_img_path = self.tmp_dir / "small.jpg"
small_img = Image.new("RGB", (100, 100), color=(0, 0, 0))
small_img.save(small_img_path, format="JPEG")
res_small = validate_image(small_img_path, self.cfg["validate"])
self.assertFalse(res_small.ok)
self.assertEqual(res_small.reason, "too_small_file")
# Low resolution test (> 5000 bytes via noise, but < 480px short side)
lowres_path = self.tmp_dir / "low_res.png"
lowres_arr = np.random.randint(0, 255, (300, 300, 3), dtype=np.uint8)
lowres_img = Image.fromarray(lowres_arr)
lowres_img.save(lowres_path, format="PNG")
self.assertGreater(lowres_path.stat().st_size, 5000)
res_lowres = validate_image(lowres_path, self.cfg["validate"])
self.assertFalse(res_lowres.ok)
self.assertEqual(res_lowres.reason, "low_resolution")
def test_ai_metadata_validation(self):
ai_img_path = self.tmp_dir / "ai_gen.png"
arr = np.random.randint(0, 255, (800, 1000, 3), dtype=np.uint8)
img = Image.fromarray(arr)
png_info = PngImagePlugin.PngInfo()
png_info.add_text("Software", "Midjourney v6.0")
img.save(ai_img_path, format="PNG", pnginfo=png_info)
res = validate_image(ai_img_path, self.cfg["validate"])
self.assertFalse(res.ok)
self.assertEqual(res.reason, "ai_generated_metadata")
def test_processor(self):
test_rgba_path = self.tmp_dir / "rgba_pcb.png"
arr = np.random.randint(0, 255, (900, 1200, 4), dtype=np.uint8)
img = Image.fromarray(arr, mode="RGBA")
img.save(test_rgba_path, format="PNG")
dst_path = self.tmp_dir / "normalized_pcb.jpg"
res = normalize_image(test_rgba_path, dst_path, self.cfg["process"])
self.assertTrue(dst_path.exists())
self.assertEqual(res.width, 1200)
with Image.open(dst_path) as norm_img:
self.assertEqual(norm_img.mode, "RGB")
def test_dedup_hashes(self):
img_path = self.tmp_dir / "dedup_test.jpg"
arr = np.random.randint(0, 255, (600, 600, 3), dtype=np.uint8)
img = Image.fromarray(arr)
img.save(img_path, format="JPEG")
hashes = compute_hashes(img_path)
self.assertIn("phash", hashes)
self.assertIn("dhash", hashes)
self.assertIn("phash_flip", hashes)
self.assertIn("dhash_flip", hashes)
def test_cli_all_subcommand_parser(self):
import subprocess
res = subprocess.run(
[".venv/bin/python3", "scraper.py", "all", "--help"],
capture_output=True,
text=True,
cwd=str(Path(__file__).resolve().parent.parent)
)
self.assertEqual(res.returncode, 0)
self.assertIn("--max-num", res.stdout)
def test_splitter(self):
from pipeline.splitter import run as run_splitter
self.manifest.add_image(image_id="img1", sha256="sha1", status="deduped", cluster_id="c1", orig_path="orig1.jpg")
self.manifest.add_image(image_id="img2", sha256="sha2", status="deduped", cluster_id="c1", orig_path="orig2.jpg")
self.manifest.add_image(image_id="img3", sha256="sha3", status="deduped", cluster_id="c2", orig_path="orig3.jpg")
splits_dir = self.tmp_dir / "splits"
stats = run_splitter(self.manifest, self.cfg, self.tmp_dir, splits_dir, copy_files=False)
self.assertEqual(stats["total_split"], 3)
# Check cluster_id integrity: img1 and img2 must be in the same split
img1 = self.manifest.get_image("img1")
img2 = self.manifest.get_image("img2")
self.assertEqual(img1["split"], img2["split"])
def test_cli_split_subcommand_parser(self):
import subprocess
res = subprocess.run(
[".venv/bin/python3", "scraper.py", "split", "--help"],
capture_output=True,
text=True,
cwd=str(Path(__file__).resolve().parent.parent)
)
self.assertEqual(res.returncode, 0)
self.assertIn("--train-ratio", res.stdout)
if __name__ == "__main__":
unittest.main()