跨境卖家往往要把同一款商品上架到 Shopee、Lazada、Amazon、TikTok Shop 和独立站,而且要用好几种语言。大语言模型可以根据一份商品资料表格,一夜之间为数百个商品写出标题、卖点和描述的初稿。本文编写一个小巧的 Python 脚本:读取 CSV 文件,调用 Ollama 中的本地模型(或任意兼容 OpenAI 的 AI API)为每种语言生成一条 Listing,并把结果写入新的 CSV 文件,由你审核后再导入各平台的上架模板。
新建一个表格,每个商品占一行,以 UTF-8 编码保存为 products.csv(在 Excel 中另存为 CSV UTF-8 格式)。列名可以自行决定,所有列都会传给模型,但脚本要求必须有一个取值唯一的 sku 列:
sku,name,category,specs,keywords
LS-01,Bamboo laptop stand,Office,"6 height levels; fits 10-17 inch laptops; foldable; 1.1 kg; natural bamboo","laptop stand, bamboo, ergonomic"
BT-07,Wireless earbuds,Audio,"Bluetooth 5.3; 30 h playback with case; IPX5; USB-C charging","wireless earbuds, bluetooth, sport"
资料越精确(材质、尺寸、适配型号、包装清单等),生成的结果就越好、越安全,因为脚本会要求模型只使用这些资料。
apt install -y python3-venv
python3 -m venv /opt/listing
/opt/listing/bin/pip install openai
openai Python 库既能对接 Ollama 的 OpenAI 兼容接口,也适用于大多数 AI 服务商,因此同一个脚本既可以调用本地模型,也可以调用云端模型。Ollama 的部署方法请参阅使用 Ollama 部署本地大模型。
cat > /opt/listing/listing.py <<'EOF2'
import csv, json, os, re, sys, time
from openai import OpenAI
client = OpenAI(base_url=os.environ.get("AI_BASE_URL", "http://127.0.0.1:11434/v1"),
api_key=os.environ.get("AI_API_KEY", "ollama"))
MODEL = os.environ.get("AI_MODEL", "qwen2.5:7b")
LANGS = [l.strip() for l in os.environ.get("LANGS", "English").split(",")]
SYSTEM = """You write e-commerce product listings for online marketplaces.
Use only the product facts provided. Never invent features, materials,
certifications, prices or delivery promises. No exaggerated claims.
Return JSON only, in this format:
{"title": "...", "bullets": ["...", "...", "...", "...", "..."], "description": "..."}
title: at most 120 characters, main keyword first.
bullets: 5 short points, each starting with the benefit.
description: 80 to 150 words of plain text."""
def ask(product, lang):
prompt = f"Write the listing in {lang}.\nProduct facts:\n{json.dumps(product, ensure_ascii=False)}"
for attempt in range(3):
r = client.chat.completions.create(model=MODEL, temperature=0.4, messages=[
{"role": "system", "content": SYSTEM}, {"role": "user", "content": prompt}])
m = re.search(r"\{.*\}", r.choices[0].message.content or "", re.S)
try:
data = json.loads(m.group(0))
if data.get("title") and isinstance(data.get("bullets"), list) and data.get("description"):
return data
except (AttributeError, ValueError):
pass
time.sleep(2)
raise RuntimeError(f"no valid answer for {product['sku']} / {lang}")
src, dst = sys.argv[1], sys.argv[2]
done = set()
if os.path.exists(dst):
with open(dst, encoding="utf-8-sig") as f:
done = {(r["sku"], r["language"]) for r in csv.DictReader(f)}
with open(src, encoding="utf-8-sig") as f:
products = list(csv.DictReader(f))
new_file = not os.path.exists(dst)
with open(dst, "a", newline="", encoding="utf-8-sig") as f: # utf-8-sig: Excel shows every language correctly
w = csv.writer(f)
if new_file:
w.writerow(["sku", "language", "title", "bullets", "description"])
for p in products:
for lang in LANGS:
if (p["sku"], lang) in done:
continue
d = ask(p, lang)
w.writerow([p["sku"], lang, str(d["title"]).strip(),
"\n".join(str(b).strip() for b in d["bullets"]), str(d["description"]).strip()])
f.flush()
print(p["sku"], lang, "done", flush=True)
EOF2
脚本要求模型以 JSON 格式返回,会检查返回内容,不合格时最多重试三次。每完成一行就立即写入文件;再次运行时会跳过输出文件中已有的商品和语言,因此任务中断后只需重新运行,就会从中断处继续。
cd /data/listings
LANGS="English,Thai,Malay,Japanese" nohup /opt/listing/bin/python /opt/listing/listing.py \
products.csv listings.csv > listing.log 2>&1 &
tail -f listing.log
在 CPU 服务器上,7B 模型生成一条 Listing 通常需要几十秒,因此 500 个商品、四种语言的任务大约要跑一整夜。如果想改用云端模型,只需设置任意兼容 OpenAI 的 API 的地址、密钥和模型名称:
AI_BASE_URL=https://ai.example.com/v1 AI_API_KEY=sk-your-key AI_MODEL=cloud-chat \
LANGS="English,Thai" /opt/listing/bin/python /opt/listing/listing.py products.csv listings.csv
请仅在 AI 服务商支持的地区、按其服务条款使用。
listings.csv,按语言筛选。SYSTEM,例如禁用词列表、使用英式还是美式英语、不使用表情符号等。SYSTEM 中,模型会高度模仿它的结构和语气。qwen2.5:14b 等更大的模型写出的泰语、马来语和越南语明显更好,代价是速度更慢、内存占用更多。电商平台关注的是内容是否准确、是否合规,搜索引擎关注的是内容是否对用户有帮助。经过人工审核、准确具体的 Listing 没有问题;而批量生产、含有错误或虚构宣称的文案,无论是谁写的都存在风险。
说明模型连续三次返回的都不是有效的 JSON。重新执行同一条命令即可(会从中断处继续),也可以调低温度或换用更大的模型。
可以。如需批量抠图并制作白底主图,请参阅使用 rembg 批量去除商品图片背景。
如果按以上步骤操作后问题仍未解决,请提交工单联系 IMIDC 7×24 技术支持,并附上服务器 IP、所用模型、执行过的命令以及 listing.log 的最后几行,方便工程师快速定位。