"""使用Qwen3-VL和通义文本向量构建小型多模态商品目录。""" from __future__ import annotations import argparse import base64 import json import math import mimetypes import os import time from pathlib import Path from typing import Any, Iterable from jsonschema import validate from openai import OpenAI ROOT = Path(__file__).resolve().parent IMAGE_ROOT = (ROOT / "assets" / "images").resolve() BASE_URL = "https://dashscope.aliyuncs.com/compatible-mode/v1" VISION_MODEL = "qwen3-vl-plus" EMBEDDING_MODEL = "text-embedding-v4" EMBEDDING_DIMENSIONS = 1024 MAX_IMAGE_BYTES = 8 * 1024 * 1024 ALLOWED_SUFFIXES = {".jpg", ".jpeg", ".png", ".webp"} CANONICAL_TAGS = [ "鞋架", "收纳架", "挂钩", "餐椅", "皮革", "金属", "园艺垫", "防水", "家居地垫", "匹克球", "托盘桌", "折叠家具", "白色", "黑色", "绿色", "灰色", "金属支架", "便携", "文字图案", "小户型适用", "仿木纹桌面", "防污垫", "多层置物", "运动主题", "家居装饰", "直背设计", "四腿支撑", ] TAG_ALIASES = { "置鞋架": "鞋架", "鞋子收纳": "鞋架", "储物架": "收纳架", "衣帽钩": "挂钩", "挂衣钩": "挂钩", "椅子": "餐椅", "人造革": "皮革", "换盆垫": "园艺垫", "种植垫": "园艺垫", "门垫": "家居地垫", "脚垫": "家居地垫", "电视托盘": "托盘桌", "折叠桌": "托盘桌", } ANALYSIS_SCHEMA: dict[str, Any] = { "type": "object", "properties": { "item_type": {"type": "string", "minLength": 1, "maxLength": 30}, "color": {"type": "string", "minLength": 1, "maxLength": 30}, "material": {"type": "string", "minLength": 1, "maxLength": 50}, "style": {"type": "string", "minLength": 1, "maxLength": 50}, "tags": { "type": "array", "minItems": 3, "maxItems": 10, "uniqueItems": True, "items": {"type": "string", "minLength": 1, "maxLength": 20}, }, "description": {"type": "string", "minLength": 20, "maxLength": 300}, "caption": {"type": "string", "minLength": 5, "maxLength": 60}, }, "required": [ "item_type", "color", "material", "style", "tags", "description", "caption" ], "additionalProperties": False, } def create_client() -> OpenAI: """创建OpenAI兼容客户端,密钥只从环境变量读取。""" api_key = os.environ.get("DASHSCOPE_API_KEY", "").strip() if not api_key: raise RuntimeError("请先设置环境变量 DASHSCOPE_API_KEY") return OpenAI(api_key=api_key, base_url=BASE_URL, timeout=180) def image_to_data_url(image_path: str | Path) -> str: """只允许读取项目图片目录中的常见图片,并转换为Base64 Data URL。""" path = Path(image_path) if not path.is_absolute(): path = ROOT / path path = path.resolve() if IMAGE_ROOT not in path.parents: raise ValueError("图片必须位于 assets/images 目录") if path.suffix.lower() not in ALLOWED_SUFFIXES: raise ValueError(f"不支持的图片格式:{path.suffix}") if not path.is_file(): raise FileNotFoundError(path) if path.stat().st_size > MAX_IMAGE_BYTES: raise ValueError("图片不能超过8MB") mime = mimetypes.guess_type(path.name)[0] or "image/jpeg" encoded = base64.b64encode(path.read_bytes()).decode("ascii") return f"data:{mime};base64,{encoded}" def usage_dict(response: Any) -> dict[str, int]: usage = getattr(response, "usage", None) return { "prompt_tokens": int(getattr(usage, "prompt_tokens", 0) or 0), "completion_tokens": int(getattr(usage, "completion_tokens", 0) or 0), "total_tokens": int(getattr(usage, "total_tokens", 0) or 0), } def merge_usage(*values: dict[str, int]) -> dict[str, int]: keys = ("prompt_tokens", "completion_tokens", "total_tokens") return {key: sum(value.get(key, 0) for value in values) for key in keys} def parse_json_object(content: str) -> dict[str, Any]: """兼容模型偶尔返回的Markdown代码围栏,并确保顶层是对象。""" text = content.strip() if text.startswith("```"): lines = text.splitlines() text = "\n".join(lines[1:-1]).strip() value = json.loads(text) if not isinstance(value, dict): raise ValueError("模型输出的JSON顶层必须是对象") return value def analyze_image( client: OpenAI, image_path: str | Path, business_context: str = "", ) -> tuple[dict[str, Any], dict[str, Any]]: """让视觉模型一次性返回可入库的商品结构化字段。""" started = time.perf_counter() response = client.chat.completions.create( model=VISION_MODEL, temperature=0.1, response_format={"type": "json_object"}, messages=[ { "role": "system", "content": ( "你是商品目录视觉分析器。只描述图中可见事实,不猜测品牌、尺寸、价格或" "不可见结构。必须输出JSON对象,字段严格为item_type、color、material、" "style、tags、description、caption。全部使用简体中文;tags为3至10个短词;" "caption是适合商品列表展示的中文短标题。" ), }, { "role": "user", "content": [ {"type": "image_url", "image_url": {"url": image_to_data_url(image_path)}}, { "type": "text", "text": ( f"业务上下文:{business_context or '未提供'}。分析图片并输出JSON。" "无法确定的材质或风格请写‘无法仅凭图片确定’,不要虚构。" ), }, ], }, ], ) content = response.choices[0].message.content or "" result = parse_json_object(content) validate(instance=result, schema=ANALYSIS_SCHEMA) metadata = { "model": VISION_MODEL, "elapsed_seconds": round(time.perf_counter() - started, 3), "usage": usage_dict(response), } return result, metadata def embed_texts(client: OpenAI, texts: list[str]) -> tuple[list[list[float]], dict[str, Any]]: if not texts or any(not text.strip() for text in texts): raise ValueError("待向量化文本不能为空") started = time.perf_counter() vectors: list[list[float]] = [] usages: list[dict[str, int]] = [] request_count = 0 # 百炼兼容接口每次最多接收10条文本,主动分批可避免400错误。 for offset in range(0, len(texts), 10): response = client.embeddings.create( model=EMBEDDING_MODEL, input=texts[offset : offset + 10], dimensions=EMBEDDING_DIMENSIONS, ) vectors.extend(item.embedding for item in sorted(response.data, key=lambda item: item.index)) usages.append(usage_dict(response)) request_count += 1 if any(len(vector) != EMBEDDING_DIMENSIONS for vector in vectors): raise RuntimeError("向量维度与配置不一致") return vectors, { "model": EMBEDDING_MODEL, "dimensions": EMBEDDING_DIMENSIONS, "request_count": request_count, "elapsed_seconds": round(time.perf_counter() - started, 3), "usage": merge_usage(*usages), } def cosine_similarity(left: Iterable[float], right: Iterable[float]) -> float: """不依赖NumPy计算余弦相似度,并拒绝维度不一致和零向量。""" a, b = list(left), list(right) if len(a) != len(b) or not a: raise ValueError("向量必须非空且维度一致") denominator = math.sqrt(sum(x * x for x in a)) * math.sqrt(sum(y * y for y in b)) if denominator == 0: raise ValueError("不能计算零向量的余弦相似度") return sum(x * y for x, y in zip(a, b)) / denominator def normalize_tags( tags: list[str], canonical_tags: list[str], tag_vectors: list[list[float]], candidate_vectors: list[list[float]], threshold: float = 0.75, ) -> list[str]: """先处理明确同义词,再用向量相似度吸收近义标签。""" if len(canonical_tags) != len(tag_vectors) or len(tags) != len(candidate_vectors): raise ValueError("标签与向量数量不一致") normalized: list[str] = [] for tag, vector in zip(tags, candidate_vectors): cleaned = tag.strip() exact = TAG_ALIASES.get(cleaned, cleaned if cleaned in canonical_tags else "") if exact: selected = exact else: scores = [cosine_similarity(vector, item) for item in tag_vectors] best_index = max(range(len(scores)), key=scores.__getitem__) selected = canonical_tags[best_index] if scores[best_index] >= threshold else cleaned if selected and selected not in normalized: normalized.append(selected) return normalized def searchable_text(analysis: dict[str, Any], normalized_tags: list[str]) -> str: return ";".join( [ analysis["caption"], analysis["item_type"], analysis["color"], analysis["material"], analysis["style"], "、".join(normalized_tags), analysis["description"], ] ) def build_catalog( client: OpenAI, products_path: str | Path = ROOT / "products.json", ) -> dict[str, Any]: """分析全部图片、统一标签并生成可搜索向量。""" started = time.perf_counter() products = json.loads(Path(products_path).read_text(encoding="utf-8")) if not isinstance(products, list) or not products: raise ValueError("products.json必须是非空数组") records: list[dict[str, Any]] = [] call_usage: list[dict[str, int]] = [] vision_calls: list[dict[str, Any]] = [] for product in products: analysis, metadata = analyze_image( client, ROOT / product["image"], product.get("business_context", "") ) records.append({**product, "analysis": analysis}) vision_calls.append({"id": product["id"], **metadata}) call_usage.append(metadata["usage"]) all_tags = [tag for record in records for tag in record["analysis"]["tags"]] all_vectors, tag_metadata = embed_texts(client, CANONICAL_TAGS + all_tags) canonical_vectors = all_vectors[: len(CANONICAL_TAGS)] candidate_vectors = all_vectors[len(CANONICAL_TAGS) :] offset = 0 for record in records: tags = record["analysis"]["tags"] vectors = candidate_vectors[offset : offset + len(tags)] offset += len(tags) normalized = normalize_tags(tags, CANONICAL_TAGS, canonical_vectors, vectors) record["normalized_tags"] = normalized record["search_text"] = searchable_text(record["analysis"], normalized) search_vectors, search_metadata = embed_texts( client, [record["search_text"] for record in records] ) for record, vector in zip(records, search_vectors): record["embedding"] = vector call_usage.extend([tag_metadata["usage"], search_metadata["usage"]]) return { "models": {"vision": VISION_MODEL, "embedding": EMBEDDING_MODEL}, "embedding_dimensions": EMBEDDING_DIMENSIONS, "records": records, "calls": {"vision": vision_calls, "tag_embeddings": tag_metadata, "catalog_embeddings": search_metadata}, "usage": merge_usage(*call_usage), "elapsed_seconds": round(time.perf_counter() - started, 3), } def rank_by_vector(catalog: dict[str, Any], query_vector: list[float], limit: int = 3) -> list[dict[str, Any]]: ranked = [ { "id": record["id"], "caption": record["analysis"]["caption"], "score": round(cosine_similarity(query_vector, record["embedding"]), 6), } for record in catalog["records"] ] return sorted(ranked, key=lambda item: item["score"], reverse=True)[:limit] def search_text( client: OpenAI, catalog: dict[str, Any], query: str, limit: int = 3 ) -> dict[str, Any]: vectors, metadata = embed_texts(client, [query.strip()]) return {"query": query, "results": rank_by_vector(catalog, vectors[0], limit), **metadata} def search_image( client: OpenAI, catalog: dict[str, Any], image_path: str | Path, limit: int = 3 ) -> dict[str, Any]: analysis, vision_metadata = analyze_image(client, image_path, "这是以图搜商品的查询图片") query_text = searchable_text(analysis, analysis["tags"]) vectors, embedding_metadata = embed_texts(client, [query_text]) return { "analysis": analysis, "query_text": query_text, "results": rank_by_vector(catalog, vectors[0], limit), "calls": {"vision": vision_metadata, "embedding": embedding_metadata}, "usage": merge_usage(vision_metadata["usage"], embedding_metadata["usage"]), } def load_catalog(path: str | Path) -> dict[str, Any]: return json.loads(Path(path).read_text(encoding="utf-8")) def write_json(path: str | Path, value: Any) -> None: Path(path).write_text(json.dumps(value, ensure_ascii=False, indent=2), encoding="utf-8") def main() -> None: parser = argparse.ArgumentParser(description="Qwen3-VL多模态商品目录") subparsers = parser.add_subparsers(dest="command", required=True) build = subparsers.add_parser("build", help="分析图片并建立商品索引") build.add_argument("--output", default="catalog-index.json") text = subparsers.add_parser("text-search", help="用中文文本检索商品") text.add_argument("query") text.add_argument("--index", default="catalog-index.json") image = subparsers.add_parser("image-search", help="用本地图片检索商品") image.add_argument("image") image.add_argument("--index", default="catalog-index.json") args = parser.parse_args() client = create_client() if args.command == "build": result = build_catalog(client) write_json(ROOT / args.output, result) print(f"已生成索引:{ROOT / args.output}") elif args.command == "text-search": print(json.dumps(search_text(client, load_catalog(ROOT / args.index), args.query), ensure_ascii=False, indent=2)) else: print(json.dumps(search_image(client, load_catalog(ROOT / args.index), args.image), ensure_ascii=False, indent=2)) if __name__ == "__main__": main()