Centralize exact subcategory selectors
This commit is contained in:
+29
-4
@@ -422,6 +422,30 @@ def find_category(categories: list[dict[str, Any]], name_or_slug: str) -> dict[s
|
||||
return None
|
||||
|
||||
|
||||
def exact_subcategory_selector(category: dict[str, Any], subcategory: dict[str, Any]) -> str:
|
||||
return f"{category.get('name')} / {subcategory.get('name')}"
|
||||
|
||||
|
||||
def split_exact_subcategory_choice(
|
||||
categories: list[dict[str, Any]],
|
||||
subcategory_choice: str,
|
||||
) -> tuple[dict[str, Any], str] | None:
|
||||
choice = str(subcategory_choice or "").strip()
|
||||
if not choice or " / " not in choice:
|
||||
return None
|
||||
candidates: list[tuple[int, dict[str, Any], str]] = []
|
||||
for category in categories:
|
||||
for category_label in (category.get("name", ""), category.get("slug", "")):
|
||||
category_label = str(category_label).strip()
|
||||
prefix = f"{category_label} / "
|
||||
if category_label and choice.lower().startswith(prefix.lower()):
|
||||
candidates.append((len(prefix), category, choice[len(prefix) :].strip()))
|
||||
if candidates:
|
||||
_length, category, subcategory_name = max(candidates, key=lambda candidate: candidate[0])
|
||||
return category, subcategory_name
|
||||
return None
|
||||
|
||||
|
||||
def _base_cast_counts(women_count: int, men_count: int) -> tuple[int, int]:
|
||||
women_count = max(0, int(women_count))
|
||||
men_count = max(0, int(men_count))
|
||||
@@ -467,10 +491,11 @@ def find_subcategory(
|
||||
) -> tuple[dict[str, Any], dict[str, Any], int, int]:
|
||||
women_count, men_count = _base_cast_counts(women_count, men_count)
|
||||
if subcategory_choice and subcategory_choice != random_subcategory and " / " in subcategory_choice:
|
||||
category_name, subcategory_name = subcategory_choice.split(" / ", 1)
|
||||
category = find_category(categories, category_name)
|
||||
if not category:
|
||||
exact_choice = split_exact_subcategory_choice(categories, subcategory_choice)
|
||||
if not exact_choice:
|
||||
category_name = str(subcategory_choice).split(" / ", 1)[0]
|
||||
raise ValueError(f"Unknown category in subcategory picker: {category_name}")
|
||||
category, subcategory_name = exact_choice
|
||||
wanted = subcategory_name.strip().lower()
|
||||
for subcategory in category["subcategories"]:
|
||||
if subcategory["name"].lower() == wanted or subcategory["slug"].lower() == wanted:
|
||||
@@ -485,7 +510,7 @@ def find_subcategory(
|
||||
f"women_count={women_count}, men_count={men_count}"
|
||||
)
|
||||
return category, subcategory, adjusted_women_count, adjusted_men_count
|
||||
raise ValueError(f"Unknown subcategory '{subcategory_name}' for category '{category_name}'")
|
||||
raise ValueError(f"Unknown subcategory '{subcategory_name}' for category '{category['name']}'")
|
||||
|
||||
if category_choice == "custom_random":
|
||||
if not categories:
|
||||
|
||||
Reference in New Issue
Block a user