# -*- coding: utf-8 -*-"""Title encoding/decoding module for folder name serialization.This module provides functions to validate, encode, and decode titles for usein folder names. The allowed character set is intentionally restricted toensure cross-platform compatibility and reversible encoding.Allowed characters in title: a-z, A-Z, 0-9, spaceEncoding rules:- Space → Hyphen (-)- Consecutive spaces → Single hyphen- Leading/trailing spaces → TrimmedDecoding rules:- Hyphen → Space- Invalid characters → Space (then normalized)"""importstring# Allowed characters in title: letters, digits, spaceALLOWED_CHARS=frozenset(string.ascii_letters+string.digits+" ")
[docs]classTitleValidationError(ValueError):"""Raised when a title contains invalid characters."""def__init__(self,title:str,invalid_chars:set[str]):self.title=titleself.invalid_chars=invalid_charschars_display=", ".join(repr(c)forcinsorted(invalid_chars))super().__init__(f"Title contains invalid characters: {chars_display}. "f"Only letters, digits, and spaces are allowed.")
[docs]defvalidate_title(title:str)->None:""" Validate that a title contains only allowed characters. Allowed characters: a-z, A-Z, 0-9, space :param title: The title string to validate :raises TitleValidationError: If title contains invalid characters """invalid_chars=set(title)-ALLOWED_CHARSifinvalid_chars:raiseTitleValidationError(title,invalid_chars)
[docs]defis_valid_title(title:str)->bool:""" Check if a title contains only allowed characters. :param title: The title string to check :returns: True if valid, False otherwise """returnset(title)<=ALLOWED_CHARS
[docs]defencode_title(title:str)->str:""" Encode a title for use in folder names. Converts spaces to hyphens. Multiple consecutive spaces become a single hyphen. Leading and trailing spaces are trimmed. :param title: The title string to encode (must be valid) :returns: Encoded string suitable for folder names :raises TitleValidationError: If title contains invalid characters """validate_title(title)# split() handles: leading/trailing spaces, consecutive spacesreturn"-".join(title.split())
[docs]defdecode_title(encoded:str)->str:""" Decode a folder name title back to the original title. Converts hyphens back to spaces. Any invalid characters encountered (from manual folder editing) are replaced with spaces, then normalized. :param encoded: The encoded string from folder name :returns: Decoded title with spaces """# Replace hyphens with spacesdecoded=encoded.replace("-"," ")# Replace any invalid characters with spaces (handles manual edits)chars=[cifcinALLOWED_CHARSelse" "forcindecoded]decoded="".join(chars)# Normalize: trim and collapse consecutive spacesreturn" ".join(decoded.split())