Files
tangzhuan-yu/app/specification.py
T
jinghui b3377dccd6 feat: 躺赚鱼 v3.6.2 —— xianyu-auto-reply 深度定制版首发
新增: 实时热卖榜(11分类/想要人数排序/热门搜索词热度)、价格监控(目标价通知/卖家信用筛选/销量下限/AI精准监控)、
一键转卖(收藏自动加载/改价直发/详情直达)、AI回复免费token(ai.88531.cn)、API密钥掩码、
推理模型兼容修复、商品本地编辑、授权系统接入(在线人数/版本/公告)、品牌更名躺赚鱼。

README 重写为项目介绍(改动清单/优势/真实截图/两种安装方式/体验地址 tzy.88531.cn/使用引导),
原版 README 完整保留为 README.upstream.md。
2026-11-16 01:00:59 +08:00

118 lines
4.2 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""Utilities for parsing and comparing Xianyu product specifications."""
from __future__ import annotations
import json
import re
import unicodedata
from typing import Any, Dict, List, Mapping, Optional, Tuple
DEFAULT_SPEC_KEY = "__default__"
# 规格文本里没写维度名时使用的默认维度。闲鱼上大量商品的规格就是一段纯文本
# ("1-5页"、"套餐A"),并没有"名=值"结构。强制要求配对会让这类商品无法保存
# 发货配置,界面上只看得到一个 400。
FALLBACK_SPEC_NAME = "规格"
_PAIR_SEPARATOR_RE = re.compile(r"\s*(?:[|;,\n\r、]+|\+)\s*")
_KEY_VALUE_RE = re.compile(r"^\s*([^=:]+?)\s*[=:]\s*(.+?)\s*$")
_WHITESPACE_RE = re.compile(r"\s+")
def normalize_component(value: Any) -> str:
"""Normalize a specification dimension or value for stable comparison."""
text = unicodedata.normalize("NFKC", str(value or ""))
text = _WHITESPACE_RE.sub(" ", text).strip()
return text.casefold()
def parse_specification(
value: Any = None,
*,
spec_name: Optional[str] = None,
spec_value: Optional[str] = None,
) -> Dict[str, str]:
"""Parse structured or textual specification data into normalized pairs."""
raw_pairs: List[Tuple[Any, Any]] = []
if isinstance(value, Mapping):
raw_pairs.extend(value.items())
elif isinstance(value, str):
text = unicodedata.normalize("NFKC", value).strip()
if text:
if text.startswith("{"):
try:
decoded = json.loads(text)
if isinstance(decoded, Mapping):
raw_pairs.extend(decoded.items())
except (TypeError, ValueError, json.JSONDecodeError):
pass
if not raw_pairs:
for segment in _PAIR_SEPARATOR_RE.split(text):
segment = segment.strip()
if not segment:
continue
match = _KEY_VALUE_RE.match(segment)
if match:
raw_pairs.append((match.group(1), match.group(2)))
else:
# 没有"名=值"结构的纯文本,整段当作规格值。
# 闲鱼很多商品的规格就长这样,直接丢弃会让发货配置存不下去。
raw_pairs.append((FALLBACK_SPEC_NAME, segment))
if spec_name and spec_value and not raw_pairs:
raw_pairs.append((spec_name, spec_value))
normalized: Dict[str, str] = {}
for key, raw_value in raw_pairs:
normalized_key = normalize_component(key)
normalized_value = normalize_component(raw_value)
if normalized_key and normalized_value:
existing_value = normalized.get(normalized_key)
if existing_value is not None and existing_value != normalized_value:
return {}
normalized[normalized_key] = normalized_value
return normalized
def canonicalize_specification(
value: Any = None,
*,
spec_name: Optional[str] = None,
spec_value: Optional[str] = None,
allow_default: bool = False,
) -> Tuple[str, Dict[str, str]]:
"""Return a stable specification key and normalized payload."""
payload = parse_specification(
value,
spec_name=spec_name,
spec_value=spec_value,
)
if not payload:
return (DEFAULT_SPEC_KEY if allow_default else ""), {}
key = "|".join(f"{name}={payload[name]}" for name in sorted(payload))
return key, payload
def specification_text(payload: Mapping[str, Any]) -> str:
"""Format a specification payload for logs and UI."""
parts = []
for key, value in payload.items():
clean_key = str(key or "").strip()
clean_value = str(value or "").strip()
if clean_key and clean_value:
parts.append(f"{clean_key}={clean_value}")
return " | ".join(parts)
def combine_legacy_specification(spec_name: Any, spec_value: Any) -> str:
"""Combine legacy single-pair fields without losing an existing multi-pair value."""
name = str(spec_name or "").strip()
value = str(spec_value or "").strip()
if not name or not value:
return ""
return f"{name}={value}"