v106-v109 童装支持 + 标题模板外部化 + 模板导出增强

- 新增男童/女童检测(gender_from_category 优先判童装)与童装场景图生成
  (configs/kids_features.yaml:模特/场景/服装风格,同一商品固定同一组)
- 童装 SPU 字段映射:kids_type→SPU商品属性-类型、kids_age→适用年龄段、
  target_audience 按性别映射、kids_type_map 女童「上衣」→「针织上衣」
- 标题生成提示词外部化:prompts/title_prompt_{1,2,3}.md + config.yaml 路由表
- 模板多站点匹配:经营站点可配多个,命中任意一个即匹配
- 种草图生成失败自动重试(seed_shot.retries,换场景/模特/风格)
- 模板导出新增 Preview 文件夹(成功产品 _composite.oss.jpg + result.xlsx)
- 修复 SKU 尺码未按从小到大排序(_size_rank 支持单一年龄码 6Y/10Y)
This commit is contained in:
2026-09-01 17:24:23 +08:00
parent 3dc594cf57
commit d68cc3b9e3
20 changed files with 826 additions and 136 deletions
+248 -6
View File
@@ -137,6 +137,84 @@ def _map_season(value: Any, gender: Optional[str], season_map: Optional[Dict[str
return mapping.get(str(value), value)
# 适用人群值字典映射:db target_audience 值 → 童装模板下拉框选项(男童/女童互映射)。
# 女童模板遇到 target_audience="男童" 时映射为「女童」;男童模板遇到「女童」时映射为「男童」。
# 该字典为「内置默认」,运行时可被 config.yaml 顶层 target_audience_map.kids 覆盖(缺失/留空回退这里)。
_TARGET_AUDIENCE_KIDS_MAP = {
"girl_kids": {"男童": "女童"},
"boy_kids": {"女童": "男童"},
}
def _resolve_target_audience_map(config: Optional[Dict[str, Any]]) -> Dict[str, Any]:
"""从 config 读取可配置适用人群映射(config.target_audience_map.kids),缺失/留空回退内置默认。"""
if not config:
return {g: dict(m) for g, m in _TARGET_AUDIENCE_KIDS_MAP.items()}
kids = None
try:
tm = config.get("target_audience_map") or {}
kids = (tm.get("kids") or {}) if isinstance(tm, dict) else {}
except Exception: # noqa: BLE001
kids = {}
if not isinstance(kids, dict) or not kids:
return {g: dict(m) for g, m in _TARGET_AUDIENCE_KIDS_MAP.items()}
merged = {g: dict(m) for g, m in _TARGET_AUDIENCE_KIDS_MAP.items()}
for g, m in kids.items():
if isinstance(m, dict):
merged.setdefault(str(g), {}).update(
{str(k): v for k, v in m.items() if v not in (None, "")})
return merged
def _map_target_audience(value: Any, gender: Optional[str],
kids_map: Optional[Dict[str, Any]] = None) -> Any:
"""适用人群值按童装性别映射(仅 spu.target_audience 字段):gender 为 boy_kids/girl_kids 时
查适用人群映射表(默认内置、可由 config 覆盖,找不到保留原值),如「男童」→「女童」。"""
if gender not in ("boy_kids", "girl_kids") or value in (None, ""):
return value
mapping = kids_map if kids_map is not None else _TARGET_AUDIENCE_KIDS_MAP
return mapping.get(gender, {}).get(str(value), value)
# kids_type 值字典映射:db kids_type 值 → 模板「SPU商品属性-类型」下拉框选项(仅女童模板映射)。
# 女童模板遇到 kids_type="上衣" 时映射为「针织上衣」;男童模板保留原值。
# 该字典为「内置默认」,运行时可被 config.yaml 顶层 kids_type_map.girl_kids 覆盖(缺失/留空回退这里)。
_KIDS_TYPE_GIRL_MAP = {
"girl_kids": {"上衣": "针织上衣"},
}
def _resolve_kids_type_map(config: Optional[Dict[str, Any]]) -> Dict[str, Any]:
"""从 config 读取可配置 kids_type 映射(config.kids_type_map),缺失/留空回退内置默认。"""
if not config:
return {g: dict(m) for g, m in _KIDS_TYPE_GIRL_MAP.items()}
kids = None
try:
ktm = config.get("kids_type_map") or {}
kids = ktm if isinstance(ktm, dict) else {}
except Exception: # noqa: BLE001
kids = {}
if not isinstance(kids, dict) or not kids:
return {g: dict(m) for g, m in _KIDS_TYPE_GIRL_MAP.items()}
merged = {g: dict(m) for g, m in _KIDS_TYPE_GIRL_MAP.items()}
for g, m in kids.items():
if isinstance(m, dict):
merged.setdefault(str(g), {}).update(
{str(k): v for k, v in m.items() if v not in (None, "")})
return merged
def _map_kids_type(value: Any, gender: Optional[str],
kids_type_map: Optional[Dict[str, Any]] = None) -> Any:
"""kids_type 值按童装性别映射(仅 spu.kids_type 字段):gender 为 girl_kids 时
查 kids_type 映射表(默认内置、可由 config 覆盖,找不到保留原值),如「上衣」→「针织上衣」。
男童/成人保留原值。"""
if gender != "girl_kids" or value in (None, ""):
return value
mapping = kids_type_map if kids_type_map is not None else _KIDS_TYPE_GIRL_MAP
return mapping.get("girl_kids", {}).get(str(value), value)
def _template_gender(template_path: str) -> Optional[str]:
"""通过表头解析模版「类目」判断男装/女装:类目含「男」→male;含「女」→female;都不含→None。
用于成分值映射(女装模板下拉框是「中文+英文」格式,需字典映射;男装保留 db 值)。"""
@@ -170,7 +248,10 @@ def _size_rank(size) -> tuple:
return (2, 3 + int(m.group(1)), s)
if s.isdigit(): # 数字码:90/100/110...
return (1, int(s), s)
m = re.fullmatch(r"(\d+)\s*[-/]\s*(\d+)\s*(?:M|Y|YRS|YR)?", s) # 童装年龄码
m = re.fullmatch(r"(\d+)\s*(?:M|Y|YRS|YR)", s) # 单一年龄码6Y/10Y/18M
if m:
return (3, float(m.group(1)), s)
m = re.fullmatch(r"(\d+)\s*[-/]\s*(\d+)\s*(?:M|Y|YRS|YR)?", s) # 童装年龄码范围:1-2Y/6/7Y
if m:
return (3, (int(m.group(1)) + int(m.group(2))) / 2.0, s)
m = re.search(r"(\d+(?:\.\d+)?)\s*(?:CM)?\s*[X*]", s) # 尺寸规格:30*40/12CM X 12CM
@@ -332,13 +413,20 @@ def _build_spu_row(spu: Dict[str, Any], spu_code: str,
component_map: Optional[Dict[str, Any]] = None,
season_map: Optional[Dict[str, Any]] = None,
pattern_map: Optional[Dict[str, Any]] = None,
oss_code: str = "") -> Dict[str, Any]:
target_audience_map: Optional[Dict[str, Any]] = None,
kids_type_map: Optional[Dict[str, Any]] = None,
oss_code: str = "",
model_info: Optional[Dict[str, str]] = None) -> Dict[str, Any]:
"""构造一行 SPU(固定字段:SKC货号=当前生成货号、风格=休闲、商品产地=中国大陆、产地省份=广东省;多颜色时用色值区分)。
fabric 填「面料弹性」列(fabric_headers,如 SPU商品属性-面料弹性,检测到才填 spu.fabric)。
component_1/2/3 按性别映射(gender=female 时查成分映射表 component_map,男装/None 保留原值;
material 字段不经过任何映射,原样透传)。
season 按性别映射(gender=female 时查季节映射表 season_map,如「四季」→「ALL/全球/所有」)。
pattern 按性别映射(gender=female 时空值查图案映射表 pattern_map,如空值→「卡通」)。"""
pattern 按性别映射(gender=female 时空值查图案映射表 pattern_map,如空值→「卡通」)。
target_audience 按童装性别映射(gender=boy_kids/girl_kids 时查适用人群映射表 target_audience_map
如「男童」→「女童」)。
kids_type 按童装性别映射(gender=girl_kids 时查 kids_type 映射表 kids_type_map,如「上衣」→「针织上衣」;
男童保留原值)。"""
row: Dict[str, Any] = {
"基础信息-商品层级": "spu",
"SKC货号": oss_code or spu_code, # SKC货号 = 当前生成货号 oss_code(无则回退 spu_code
@@ -357,12 +445,30 @@ def _build_spu_row(spu: Dict[str, Any], spu_code: str,
v = _map_season(v, gender, season_map)
elif dbk == "pattern":
v = _map_pattern(v, gender, pattern_map)
elif dbk == "target_audience":
v = _map_target_audience(v, gender, target_audience_map)
if v not in (None, ""):
row[header] = v
fabric = spu.get("fabric")
if fabric not in (None, "") and fabric_headers:
for h in fabric_headers:
row[h] = fabric
if model_info:
if model_info.get("model"):
row["试穿模特"] = model_info["model"]
if model_info.get("size"):
row["试穿尺码"] = model_info["size"]
if model_info.get("feel"):
row["试穿感受"] = model_info["feel"]
# 童装(男童/女童):kids_type → SPU商品属性-类型(女童查 kids_type 映射表,如「上衣」→「针织上衣」),
# kids_age → 适用年龄段(仅童装模板填)
if gender in ("boy_kids", "girl_kids"):
for dbk, header in (("kids_type", "SPU商品属性-类型"), ("kids_age", "适用年龄段")):
v = spu.get(dbk)
if dbk == "kids_type":
v = _map_kids_type(v, gender, kids_type_map)
if v not in (None, ""):
row[header] = v
return row
@@ -416,6 +522,81 @@ def _read_range_values(ws, ref: str) -> Optional[set]:
return set(opts) if opts else None
def _resolve_named_range(router, values) -> Optional[set]:
"""级联下拉:INDIRECT 引用的单元格值可能是名称引用(如「欧美尺码常规」)。
从 defined names 解析该名称对应的区域(可能跨表,如 ProductSizeSpec!$B$6:$I$6),
读取区域内容作为真实选项(如 S/M/L/XL/XXL/XXXL)。解析不到返回 None。"""
wb = router.ws.parent
resolved = set()
for v in values:
name = str(v).strip()
if name not in wb.defined_names:
continue
ref = wb.defined_names[name].value # 如 ProductSizeSpec!$B$6:$I$6
sheet_name, _, cell_ref = ref.partition("!")
if not cell_ref:
continue
ws = wb[sheet_name] if sheet_name in wb.sheetnames else router.ws
opts = _read_range_values(ws, cell_ref)
if opts:
resolved |= opts
return resolved if resolved else None
def _read_range_values_any(router, ref: str) -> Optional[set]:
"""读取单元格/区域内的非空值集合,支持跨表(Sheet!$A$1:$A$5);解析失败返回 None。"""
sheet_name, _, cell_ref = ref.partition("!")
if cell_ref:
ws = router.ws.parent[sheet_name] if sheet_name in router.ws.parent.sheetnames else router.ws
else:
ws = router.ws
cell_ref = ref
return _read_range_values(ws, cell_ref)
def _read_dropdown_options(router, col: Optional[int]) -> Optional[set]:
"""读取指定列(col)的 dataValidation 下拉选项集合;无下拉/非 list/无值 返回 None。
支持内联列表("S,M,L")、引用区域(=Sheet!$A$1:$A$5)、跨表引用(Sheet!$A$1:$A$5)、
INDIRECT 动态引用(含名称引用级联)。"""
import re
from openpyxl.utils import get_column_letter
if col is None:
return None
lf = get_column_letter(col)
dvs = getattr(router.ws, "data_validations", None)
if dvs is None:
return None
for dv in dvs.dataValidation:
if getattr(dv, "type", "") != "list":
continue
if lf not in str(getattr(dv, "sqref", "")):
continue
f = (getattr(dv, "formula1", "") or "").strip()
if not f:
continue
# 动态引用 INDIRECT(...):尝试解析引用的单元格/区域内容;无法解析 → None
m = re.match(r"^=?INDIRECT\((.+)\)$", f, re.IGNORECASE)
if m:
opts = _read_range_values(router.ws, m.group(1).strip())
if opts:
named = _resolve_named_range(router, opts)
if named:
return named
return opts if opts else None
# 引用区域(可能跨表:Sheet!$A$1:$A$5 或 =Sheet!$A$1:$A$5
ref = f[1:] if f.startswith("=") else f
if ":" in ref:
opts = _read_range_values_any(router, ref)
return opts if opts else None
# 内联列表("S,M,L" / "S;M;L" / "SML"
sep = "" if "" in f else (";" if ";" in f else ",")
opts = [x.strip().strip('"') for x in f.split(sep) if x.strip()]
return set(opts) if opts else None
return None
def _read_size_options(router) -> Optional[set]:
"""读取「尺码」列的 dataValidation 下拉选项集合;无下拉/非 list/无值 返回 None。
@@ -443,6 +624,12 @@ def _read_size_options(router) -> Optional[set]:
m = re.match(r"^=?INDIRECT\((.+)\)$", f, re.IGNORECASE)
if m:
opts = _read_range_values(router.ws, m.group(1).strip())
if opts:
# 级联下拉:INDIRECT 引用的单元格值可能是名称引用(如「欧美尺码常规」),
# 从 defined names 解析对应命名区域(跨表)得到真实尺码选项
named = _resolve_named_range(router, opts)
if named:
return named
return opts if opts else None
# 引用区域(=Sheet!$A$1:$A$5 或 Sheet!$A$1:$A$5
ref = f[1:] if f.startswith("=") else f
@@ -461,6 +648,45 @@ def _find_sku_category_headers(router) -> List[str]:
return [str(k) for k in router.column_map if "SKU分类" in str(k)]
def _read_model_info(router, sku_sizes: Optional[set]) -> Dict[str, str]:
"""读取模板「模特信息」三属性(试穿模特/试穿尺码/试穿感受)的 SPU 行填写值。
优先用模板数据区已有值(校验通过才用):
- 试穿模特:值须在下拉框选项内(如 ModalConfig 表)
- 试穿感受:值须在 [偏小/合身/偏大] 内
- 试穿尺码:值须是商品有效尺码(sku 尺码之一)
模板无值或校验失败 → 默认值:试穿模特=下拉框第一个、试穿感受=合身、试穿尺码=L。"""
col_model = router.column_map.get("试穿模特") or router.column_map.get("模特信息-试穿模特")
col_size = router.column_map.get("试穿尺码") or router.column_map.get("模特信息-试穿尺码")
col_feel = router.column_map.get("试穿感受") or router.column_map.get("模特信息-试穿感受")
model_opts = _read_dropdown_options(router, col_model) if col_model else None
feel_opts = _read_dropdown_options(router, col_feel) if col_feel else None
# 模板数据区(第 6 行起)已有值
tpl_model = tpl_size = tpl_feel = None
ws = router.ws
for r in range(6, min(ws.max_row, 30) + 1):
if col_model and tpl_model is None and ws.cell(r, col_model).value not in (None, ""):
tpl_model = str(ws.cell(r, col_model).value).strip()
if col_size and tpl_size is None and ws.cell(r, col_size).value not in (None, ""):
tpl_size = str(ws.cell(r, col_size).value).strip()
if col_feel and tpl_feel is None and ws.cell(r, col_feel).value not in (None, ""):
tpl_feel = str(ws.cell(r, col_feel).value).strip()
# 试穿模特:模板值在下拉框内才用,否则下拉框第一个
if tpl_model and model_opts and tpl_model in model_opts:
model = tpl_model
elif model_opts:
model = sorted(model_opts)[0]
else:
model = tpl_model or ""
# 试穿感受:模板值在 [偏小/合身/偏大] 内才用,否则「合身」
feel = tpl_feel if tpl_feel and feel_opts and tpl_feel in feel_opts else "合身"
# 试穿尺码:模板值是有效尺码才用,否则「L」
size = tpl_size if tpl_size and (not sku_sizes or tpl_size in sku_sizes) else "L"
return {"model": model, "size": size, "feel": feel}
def _find_sku_qty_headers(router) -> List[str]:
"""定位「SKU数量」列(排除「SKU数量单位」列);匹配到多个时全部返回。"""
return [str(k) for k in router.column_map if "SKU数量" in str(k) and "单位" not in str(k)]
@@ -698,6 +924,8 @@ def _insert_product_block(
component_map: Optional[Dict[str, Any]] = None,
season_map: Optional[Dict[str, Any]] = None,
pattern_map: Optional[Dict[str, Any]] = None,
target_audience_map: Optional[Dict[str, Any]] = None,
kids_type_map: Optional[Dict[str, Any]] = None,
suggested_price_ratio: float = 0.0,
suggested_price_headers: Optional[List[str]] = None,
suggested_unit_headers: Optional[List[str]] = None,
@@ -723,12 +951,14 @@ def _insert_product_block(
skus = _read_skus(db_path, spu_code, sc)
if not skus:
raise ValueError(f"SKU {sc} 不存在于 db(款号 {spu_code}")
skus_by_color.append((sc, skus))
skus_by_color.append((sc, sorted(skus, key=lambda sk: _size_rank(sk.get("size")))))
images = [str(i) for i in (images or []) if i]
color_col = router.resolve_col("色值(主规格)")
block_rows: List[int] = []
size_options = _read_size_options(router) # 尺码下拉框选项(sku.size 不在其中则跳过该 SKU 行)
sku_sizes = {sk.get("size") for _, skus in skus_by_color for sk in skus if sk.get("size")}
model_info = _read_model_info(router, sku_sizes) # 模特信息三属性(试穿模特/试穿尺码/试穿感受)
if spu_per_color:
# 单 SPU 多色:1 个 SPU 行(无色值,SPU 级信息由 _fill_design_fields 填充)
@@ -737,7 +967,9 @@ def _insert_product_block(
_build_spu_row(spu, spu_code, fabric_headers=fabric_headers,
gender=gender, component_map=component_map,
season_map=season_map, pattern_map=pattern_map,
oss_code=oss_code),
target_audience_map=target_audience_map,
kids_type_map=kids_type_map,
oss_code=oss_code, model_info=model_info),
match="exact",
))
for ci, (sc, skus) in enumerate(skus_by_color):
@@ -778,7 +1010,9 @@ def _insert_product_block(
_build_spu_row(spu, spu_code, fabric_headers=fabric_headers,
gender=gender, component_map=component_map,
season_map=season_map, pattern_map=pattern_map,
oss_code=oss_code), match="exact"))
target_audience_map=target_audience_map,
kids_type_map=kids_type_map,
oss_code=oss_code, model_info=model_info), match="exact"))
multi_variant = len(skus_by_color) > 1
for ci, (sc, skus) in enumerate(skus_by_color):
first = skus[0]
@@ -841,6 +1075,8 @@ def export_product(
component_map: Optional[Dict[str, Any]] = None,
season_map: Optional[Dict[str, Any]] = None,
pattern_map: Optional[Dict[str, Any]] = None,
target_audience_map: Optional[Dict[str, Any]] = None,
kids_type_map: Optional[Dict[str, Any]] = None,
) -> Path:
"""生成商品上传"已填写"模板(支持多产品合并到同一文件)。
@@ -893,6 +1129,8 @@ def export_product(
component_map=component_map,
season_map=season_map,
pattern_map=pattern_map,
target_audience_map=target_audience_map,
kids_type_map=kids_type_map,
suggested_price_ratio=suggested_price_ratio,
suggested_price_headers=suggested_price_headers,
@@ -920,6 +1158,8 @@ def export_products(
component_map: Optional[Dict[str, Any]] = None,
season_map: Optional[Dict[str, Any]] = None,
pattern_map: Optional[Dict[str, Any]] = None,
target_audience_map: Optional[Dict[str, Any]] = None,
kids_type_map: Optional[Dict[str, Any]] = None,
) -> Path:
"""批量合并导出:所有产品一次性写入同一模板,只打开/保存一次。
@@ -967,6 +1207,8 @@ def export_products(
component_map=component_map,
season_map=season_map,
pattern_map=pattern_map,
target_audience_map=target_audience_map,
kids_type_map=kids_type_map,
suggested_price_ratio=suggested_price_ratio,
suggested_price_headers=suggested_price_headers,