acupedia-api/app/bootstrap/seed_media/identity.py

63 lines
1.6 KiB
Python

from __future__ import annotations
import re
from pathlib import Path
def require_non_empty_string(value: str, field_name: str) -> str:
value = value.strip()
if not value:
raise ValueError(f"{field_name} must not be empty")
return value
def slugify(value: str) -> str:
value = re.sub(r"[^a-z0-9]+", "-", value.strip().lower())
return value.strip("-")
def build_source_key(*, template_code: str, source_code: str) -> str:
normalized_template = require_non_empty_string(
template_code, "template_code"
).upper()
normalized_source_code = require_non_empty_string(
source_code, "source_code"
)
stable_component = slugify(normalized_source_code)
if not stable_component:
raise ValueError("source_code becomes empty after canonicalization")
return f"{normalized_template}:{stable_component}"
def canonical_media_filename(
*,
template_code: str,
source_code: str,
usage_type: str,
ordinal: int,
extension: str,
) -> str:
source_component = slugify(source_code)
usage_component = slugify(usage_type)
extension = extension.lower()
if not extension.startswith("."):
extension = f".{extension}"
return (
f"{template_code.upper()}--{source_component}--"
f"{usage_component}--{ordinal:02d}{extension}"
)
def build_storage_key(
*,
module_code: str,
template_code: str,
source_code: str,
filename: str,
) -> str:
return (
f"images/{module_code.upper()}/{template_code.upper()}/"
f"{slugify(source_code)}/{Path(filename).name}"
)