"""QA scenario building: tile normalization, image download, scenario generation.""" from pathlib import Path from config.spaces import SPACES_BUCKET from qa.constants import QA_IMAGE_EXTENSIONS, QA_TILE_ALIASES, QA_TILE_DESCRIPTIONS from services.spaces.upload import spaces_client def qa_safe_filename(value: str, fallback: str = "image") -> str: stem = "".join(char.lower() if char.isalnum() else "-" for char in value).strip("-") while "--" in stem: stem = stem.replace("--", "-") return (stem or fallback)[:90] def normalize_qa_tile(tile_name: str) -> str: name = str(tile_name).strip() return QA_TILE_ALIASES.get(name, name) def qa_tile_description(tile_name: str, supplied_descriptions: dict[str, str]) -> str: return supplied_descriptions.get(tile_name) or QA_TILE_DESCRIPTIONS.get(tile_name) or f"{tile_name} flooring material" def parse_tile_descriptions(values) -> dict[str, str]: descriptions: dict[str, str] = {} if not isinstance(values, list): return descriptions for value in values: if not isinstance(value, str) or ":" not in value: continue name, description = value.split(":", 1) normalized = normalize_qa_tile(name) if normalized and description.strip(): descriptions[normalized] = description.strip() return descriptions def build_qa_scenarios(downloaded_images: list[dict], tiles: list[str], descriptions: dict[str, str]): scenarios = [] for image in downloaded_images: image_name = Path(image["key"]).stem for tile in tiles: scenarios.append({ "imagePath": str(image["path"]), "keyword": "floor", "roomName": f"{image_name}", "surfaceClass": "floor", "textureName": tile, "textureDescription": qa_tile_description(tile, descriptions), "expectedDirectionDescription": ( "The applied material direction should follow the floor perspective and should not look arbitrarily rotated." ), }) return scenarios def download_qa_images(run_id: str, image_keys: list[str]): from qa.store import qa_run_root client = spaces_client() images_dir = qa_run_root(run_id) / "images" images_dir.mkdir(parents=True, exist_ok=True) downloaded = [] for index, key in enumerate(image_keys, start=1): extension = Path(key).suffix.lower() if extension not in QA_IMAGE_EXTENSIONS: extension = ".jpg" destination = images_dir / f"{index:03d}-{qa_safe_filename(Path(key).stem)}{extension}" client.download_file(SPACES_BUCKET, key, str(destination)) downloaded.append({"key": key, "path": destination}) return downloaded