功能迭代
This commit is contained in:
1 parent
8e03c99cab
commit
9e87a4002a
23 files changed
+553
-38
No files matched your search
@@ -0,0 +1,102 @@
|
||||
"""为三款产品准备无中文的产品图与英文规格图。"""
|
||||
|
||||
from pathlib import Path
|
||||
from PIL import Image, ImageDraw, ImageFont, ImageOps
|
||||
|
||||
|
||||
SOURCE_ROOT = Path(r"C:\Users\29506\Desktop\cy\鸿遇工贸\产品图片")
|
||||
OUTPUT_ROOT = Path(r"E:\work\shangyuan\shoplix\output\product-import")
|
||||
FONT_REGULAR = Path(r"C:\Windows\Fonts\arial.ttf")
|
||||
FONT_BOLD = Path(r"C:\Windows\Fonts\arialbd.ttf")
|
||||
|
||||
PRODUCTS = {
|
||||
"HY-001": {
|
||||
"folder": "Protective Cover Trimmer Head - White HY-001",
|
||||
"name": "Protective Cover Trimmer Head - White",
|
||||
"files": [
|
||||
"O1CN01D8S3e9G83iC2XrKe_!!2217056636432-0-cib.jpg_.webp",
|
||||
"O1CN01OEkLBL7Ic8J2R3rs_!!2217056636432-0-cib.jpg_.webp",
|
||||
"O1CN01spYFDTqxaDF2R3rs_!!2217056636432-0-cib.jpg_.webp",
|
||||
"O1CN01t8mmPN9FSiF2R3rs_!!2217056636432-0-cib.jpg_.webp",
|
||||
],
|
||||
"specs": [("Material", "Metal + aluminum"), ("Dimensions", "80.5 × 80.5 × 23 mm"),
|
||||
("Net weight", "200 g"), ("Application", "Grass trimming")],
|
||||
},
|
||||
"HY-012": {
|
||||
"folder": "Large Aluminum Cylinder Trimmer Head HY-012",
|
||||
"name": "Large Aluminum Cylinder Trimmer Head",
|
||||
"files": [
|
||||
"O1CN01TZ4um7NgP8B1chua_!!2217056636432-0-cib.jpg_.webp",
|
||||
"O1CN01vpinbZvGDlK1chua_!!2217056636432-0-cib.jpg_.webp",
|
||||
"O1CN01zCrsDO1J0OE1chua_!!2217056636432-0-cib.jpg_.webp",
|
||||
],
|
||||
"specs": [("Material", "Aluminum alloy"), ("Dimensions", "45 × 45 × 55 mm"),
|
||||
("Net weight", "400 g"), ("Application", "Grass trimming")],
|
||||
},
|
||||
"HY-032": {
|
||||
"folder": "European-Type Trimmer Head - Orange HY-032",
|
||||
"name": "European-Type Trimmer Head - Orange",
|
||||
"files": [
|
||||
"O1CN01unDmzQcaXFC2b8G8_!!2217056636432-0-cib.jpg_.webp",
|
||||
"O1CN01UyV2HS9YFAC2b8G8_!!2217056636432-0-cib.jpg_.webp",
|
||||
"O1CN01wsHSM4JvXdD2b8G8_!!2217056636432-0-cib.jpg_.webp",
|
||||
],
|
||||
"specs": [("Material", "Engineering plastic + metal"), ("Dimensions", "145 × 145 × 75 mm"),
|
||||
("Net weight", "485 g"), ("Application", "Grass trimming")],
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def font(size: int, bold: bool = False) -> ImageFont.FreeTypeFont:
|
||||
"""加载用于英文详情图的系统字体。"""
|
||||
return ImageFont.truetype(str(FONT_BOLD if bold else FONT_REGULAR), size)
|
||||
|
||||
|
||||
def save_clean_image(source: Path, target: Path) -> None:
|
||||
"""将无中文的原图统一转为高质量 JPEG。"""
|
||||
image = Image.open(source).convert("RGB")
|
||||
image.save(target, "JPEG", quality=92, optimize=True)
|
||||
|
||||
|
||||
def create_specification_card(model: str, config: dict, product_image: Path, target: Path) -> None:
|
||||
"""基于实拍图生成全英文规格详情图。"""
|
||||
canvas = Image.new("RGB", (1200, 1200), "#f5f7f6")
|
||||
draw = ImageDraw.Draw(canvas)
|
||||
draw.rectangle((0, 0, 1200, 165), fill="#176b5b")
|
||||
draw.text((70, 48), config["name"], font=font(44, True), fill="white")
|
||||
draw.text((72, 108), model, font=font(25), fill="#d7eee7")
|
||||
product = Image.open(product_image).convert("RGB")
|
||||
product = ImageOps.contain(product, (540, 650))
|
||||
x = 70 + (540 - product.width) // 2
|
||||
y = 230 + (650 - product.height) // 2
|
||||
canvas.paste(product, (x, y))
|
||||
draw.rounded_rectangle((660, 230, 1130, 910), radius=22, fill="white", outline="#dce4e1", width=2)
|
||||
draw.text((710, 282), "Product specifications", font=font(30, True), fill="#16221f")
|
||||
row_y = 370
|
||||
for label, value in config["specs"]:
|
||||
draw.text((710, row_y), label.upper(), font=font(17, True), fill="#71817c")
|
||||
draw.text((710, row_y + 34), value, font=font(25), fill="#17211f")
|
||||
draw.line((710, row_y + 86, 1080, row_y + 86), fill="#e5eae8", width=2)
|
||||
row_y += 125
|
||||
draw.text((70, 1030), "OEM & wholesale inquiries are welcome", font=font(30, True), fill="#176b5b")
|
||||
draw.text((70, 1082), "Confirm machine compatibility before ordering.", font=font(23), fill="#64736e")
|
||||
canvas.save(target, "JPEG", quality=93, optimize=True)
|
||||
|
||||
|
||||
def main() -> None:
|
||||
"""输出三款产品的清洁图库和英文规格图。"""
|
||||
OUTPUT_ROOT.mkdir(parents=True, exist_ok=True)
|
||||
for model, config in PRODUCTS.items():
|
||||
product_dir = OUTPUT_ROOT / model
|
||||
product_dir.mkdir(parents=True, exist_ok=True)
|
||||
source_dir = SOURCE_ROOT / config["folder"]
|
||||
prepared = []
|
||||
for index, filename in enumerate(config["files"], start=1):
|
||||
target = product_dir / f"{model.lower()}-{index}.jpg"
|
||||
save_clean_image(source_dir / filename, target)
|
||||
prepared.append(target)
|
||||
create_specification_card(model, config, prepared[0], product_dir / f"{model.lower()}-specifications-en.jpg")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,120 @@
|
||||
"""上传三款产品图片,并更新英文详情与规格属性。"""
|
||||
|
||||
from pathlib import Path
|
||||
from html import escape
|
||||
import requests
|
||||
|
||||
|
||||
BASE_URL = "http://127.0.0.1:8081/api/admin/v1"
|
||||
SITE_CODE = "SIT0000000000001"
|
||||
IMAGE_ROOT = Path(r"E:\work\shangyuan\shoplix\output\product-import")
|
||||
|
||||
PRODUCT_DATA = {
|
||||
"HY-001": {
|
||||
"intro": "A durable protective-cover trimmer head supplied with replaceable nylon lines for efficient grass trimming and routine garden maintenance.",
|
||||
"features": ["Metal and aluminum construction", "Compact protective-cover design", "Replaceable nylon trimming lines", "Suitable for garden and landscape maintenance"],
|
||||
"specifications": [("General", "Material", "Metal + aluminum", ""), ("Dimensions", "Size", "80.5 × 80.5 × 23", "mm"), ("Dimensions", "Net weight", "200", "g"), ("Application", "Use", "Grass trimming", "")],
|
||||
},
|
||||
"HY-012": {
|
||||
"intro": "A heavy-duty aluminum cylinder trimmer head designed for reliable line feeding, quick line replacement and demanding garden-tool applications.",
|
||||
"features": ["Thickened aluminum-alloy housing", "Quick and convenient line replacement", "Multiple line outlets for efficient cutting", "OEM and wholesale supply available"],
|
||||
"specifications": [("General", "Material", "Aluminum alloy", ""), ("Dimensions", "Diameter", "45", "mm"), ("Dimensions", "Height", "55", "mm"), ("Dimensions", "Net weight", "400", "g"), ("Application", "Use", "Grass trimming", "")],
|
||||
},
|
||||
"HY-032": {
|
||||
"intro": "A European-style orange trimmer head combining a robust housing, practical line-feeding structure and broad compatibility for grass-cutting equipment.",
|
||||
"features": ["European-style trimmer-head design", "Engineering-plastic and metal construction", "Large 145 mm working diameter", "Suitable for garden and landscape maintenance"],
|
||||
"specifications": [("General", "Material", "Engineering plastic + metal", ""), ("Dimensions", "Length", "145", "mm"), ("Dimensions", "Width", "145", "mm"), ("Dimensions", "Height", "75", "mm"), ("Dimensions", "Net weight", "485", "g"), ("Application", "Use", "Grass trimming", "")],
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def login(session: requests.Session) -> None:
|
||||
"""登录运营后台并保持会话。"""
|
||||
response = session.post(f"{BASE_URL}/auth/login", json={"username": "admin", "password": "Shoplix@2026"}, timeout=30)
|
||||
response.raise_for_status()
|
||||
|
||||
|
||||
def find_product(session: requests.Session, model: str) -> dict:
|
||||
"""按型号查找产品并读取完整详情。"""
|
||||
response = session.post(f"{BASE_URL}/products/list", json={"siteCode": SITE_CODE}, timeout=30)
|
||||
response.raise_for_status()
|
||||
item = next((row for row in response.json().get("items", []) if row.get("model") == model), None)
|
||||
if item is None:
|
||||
raise RuntimeError(f"Product not found: {model}")
|
||||
detail = session.post(f"{BASE_URL}/products/detail", json={"siteCode": SITE_CODE, "productCode": item["productCode"]}, timeout=30)
|
||||
detail.raise_for_status()
|
||||
return detail.json()
|
||||
|
||||
|
||||
def find_existing_media(session: requests.Session, filename: str) -> dict | None:
|
||||
"""复用已经上传的同名素材,避免重复写入。"""
|
||||
response = session.post(f"{BASE_URL}/media/page", json={"siteCode": SITE_CODE, "mediaType": "IMAGE", "keyword": filename, "tagName": "", "pageNo": 1, "pageSize": 30}, timeout=30)
|
||||
response.raise_for_status()
|
||||
return next((item for item in response.json().get("items", []) if item.get("originalFileName") == filename), None)
|
||||
|
||||
|
||||
def upload_image(session: requests.Session, path: Path, model: str) -> dict:
|
||||
"""上传单张产品图并返回素材信息。"""
|
||||
existing = find_existing_media(session, path.name)
|
||||
if existing:
|
||||
return existing
|
||||
with path.open("rb") as file_handle:
|
||||
response = session.post(f"{BASE_URL}/media/upload", data={"siteCode": SITE_CODE, "altText": f"{model} product image"}, files={"file": (path.name, file_handle, "image/jpeg")}, timeout=120)
|
||||
response.raise_for_status()
|
||||
return response.json()
|
||||
|
||||
|
||||
def build_content(detail: dict, config: dict, media: list[dict]) -> str:
|
||||
"""生成包含英文卖点和实拍图的产品详情 HTML。"""
|
||||
name = escape(detail["productName"])
|
||||
features = "".join(f"<li>{escape(item)}</li>" for item in config["features"])
|
||||
image_blocks = "".join(
|
||||
f'<figure style="margin:24px 0;text-align:center"><img src="{escape(item["url"])}" alt="{name}" style="max-width:100%;height:auto" /></figure>'
|
||||
for item in media[1:3]
|
||||
)
|
||||
return (
|
||||
f"<h2>{name}</h2><p>{escape(config['intro'])}</p>"
|
||||
f"<h3>Key features</h3><ul>{features}</ul>{image_blocks}"
|
||||
"<h3>OEM & wholesale service</h3><p>Custom packaging, product configuration and bulk-order support are available. Please confirm machine compatibility before ordering.</p>"
|
||||
)
|
||||
|
||||
|
||||
def update_product(session: requests.Session, model: str, detail: dict, config: dict, media: list[dict]) -> None:
|
||||
"""保存产品多图、英文详情和英文规格属性。"""
|
||||
specifications = [
|
||||
{"groupName": group, "name": name, "value": value, "unit": unit, "sortNo": index}
|
||||
for index, (group, name, value, unit) in enumerate(config["specifications"], start=1)
|
||||
]
|
||||
attributes = [
|
||||
{"attributeCode": None, "attributeName": name, "value": f"{value}{(' ' + unit) if unit else ''}", "unit": unit, "sortNo": index}
|
||||
for index, (_, name, value, unit) in enumerate(config["specifications"], start=1)
|
||||
]
|
||||
request = {
|
||||
"productCode": detail["productCode"], "siteCode": SITE_CODE,
|
||||
"primaryCategoryCode": detail.get("primaryCategoryCode"), "productName": detail["productName"],
|
||||
"slug": detail["slug"], "model": detail.get("model"), "summary": config["intro"],
|
||||
"productContent": build_content(detail, config, media),
|
||||
"contentTemplateCode": detail.get("contentTemplateCode") or "", "templatePosition": detail.get("templatePosition") or "AFTER",
|
||||
"coverMediaCode": media[0]["mediaCode"],
|
||||
"images": [{"mediaCode": item["mediaCode"], "sortNo": index} for index, item in enumerate(media)],
|
||||
"featured": detail.get("featured", False), "inquiryEnabled": detail.get("inquiryEnabled", True),
|
||||
"sortNo": detail.get("sortNo", 0), "status": detail["status"],
|
||||
"specifications": specifications, "attributes": attributes,
|
||||
}
|
||||
response = session.post(f"{BASE_URL}/products/save", json=request, timeout=60)
|
||||
response.raise_for_status()
|
||||
|
||||
|
||||
def main() -> None:
|
||||
"""完成三款产品的素材上传和数据更新。"""
|
||||
with requests.Session() as session:
|
||||
login(session)
|
||||
for model, config in PRODUCT_DATA.items():
|
||||
detail = find_product(session, model)
|
||||
media = [upload_image(session, path, model) for path in sorted((IMAGE_ROOT / model).glob("*.jpg"))]
|
||||
update_product(session, model, detail, config, media)
|
||||
print(f"Updated {model}: {len(media)} images")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in new issue
Block a user