backend: 交付网站后端 + 本地自助管理后台 + 测试工程(已脱敏)
范围由店主圈定:网页后端 / 自助后端、本地的自助管理后台、 用于测试的 Blender 工程、以及部署层的反代片段。 出站纪律:所有指向真实环境的值(域名/端口/盘符路径/IP/账户名)已替换为占位; 代码里本来就没有硬编码凭据(令牌走文件与环境变量)。 Blender 工程因内嵌绝对路径,做了等长替换(文件字节数未变,结构完好)。 两份交接文档各含《我们的思路与方法》,并要求对方回: 问题分析 + 改正意见 + 他改了什么(含是否动到接口/字段/数据格式)。
This commit is contained in:
@@ -0,0 +1,125 @@
|
||||
# 交付包 · 卡密 / 自助渲染下单(后端 + 工具)
|
||||
|
||||
> **交付方**:苏达(网站运维与技术提供)
|
||||
> **收件方**:外部协作者
|
||||
> **日期**:2026-10-05
|
||||
> **本次交付由店主拍板,范围就是他圈定的**:网站后端 + 工具后端,全部脱敏,各配交接文档。
|
||||
|
||||
---
|
||||
|
||||
## 包里有什么(按店主划的交付范围)
|
||||
|
||||
| 店主说的 | 落在哪 | 里面是什么 | 交接文档 |
|
||||
|---|---|---|---|
|
||||
| **网页后端 / 自助后端** | `backend-site/` | 网站服务端全部逻辑:下单、卡密生命周期、队列、支付回调、打包下载、小票 + 管理 CLI + PNG 结构核验 | `backend-site/交接说明.md` |
|
||||
| **本地的自助管理后台** | `backend-tools/` | 局域网开单后台(带 PIN 锁)+ 纯本机开单工具 + 渲染机 + Blender 出图脚本 + 部署/启动脚本 | `backend-tools/交接说明.md` |
|
||||
| **用于测试的工程** | `模板/` | 三个 Blender 模板工程(已脱敏,可直接打开渲染) | `模板/说明.md` |
|
||||
| **其他需要的** | `deploy/` | 反向代理的路由与限流片段(部署层)+ 这一层的取舍说明 | `deploy/nginx-片段.md` |
|
||||
|
||||
---
|
||||
|
||||
## ⭐ 我们要你回的东西(这次交付的主要目的)
|
||||
|
||||
请你读完代码后,**各回一份**回执(就放在对应目录下,文件名 `回执-<你的名字>.md`),
|
||||
每份包含三段:
|
||||
|
||||
1. **问题分析** —— 你看到的问题/风险/坏味道,**分轻重**(会丢钱/丢数据/能被人打的排前面),
|
||||
尽量**指到具体函数或行**,并说清**什么条件下会踩到**。
|
||||
2. **改正意见** —— 每条给出你建议的改法,以及**代价**(改起来多大、会不会影响别处)。
|
||||
3. **你改了什么** —— 如果你直接动手改了,逐条列:
|
||||
```
|
||||
文件 / 函数: 为什么改: 改成什么(一句话):
|
||||
⚠️ 有没有动接口路径 / 请求响应字段 / 数据格式: ← 这三样动了我们必须知道
|
||||
你怎么验证的:
|
||||
```
|
||||
|
||||
> 两份交接文档里各有两个**我们自己拿不准的具体问题**,也请顺手回答一下。
|
||||
|
||||
**"你改了什么"为什么单独要一段**:这套系统是**两台机器上各跑一份代码**
|
||||
(服务器一份、店里电脑一份),两边靠接口对齐。你只改了其中一份、
|
||||
或者改了字段名却没标出来,我们这边会**静默出不来图** —— 不报错、就是没图,
|
||||
这种最难查。所以请务必标清楚。
|
||||
|
||||
---
|
||||
|
||||
## ⚠️ 三条纪律
|
||||
|
||||
1. **私有交付**:请勿外传、勿公开、勿镜像(含截图和片段)。
|
||||
里面的**占位值**(域名、端口、路径、IP)请**保持原样**,不要替换成任何真实地址。
|
||||
2. **不要为了"跑起来"去补真实凭据**:这份代码**设计上就跑不起来**(见下),
|
||||
我们是给你**读**的,不是给你部署的。要看运行效果用 `模板/` 那三个工程。
|
||||
3. **有看不懂的先问再改**,别猜 —— 猜错的表现是"静默失效",不报错。
|
||||
|
||||
---
|
||||
|
||||
## 关于"跑不起来"这件事(不是疏漏,是刻意的)
|
||||
|
||||
出站纪律要求:**任何离开我们机器的代码,先脱敏**。所以:
|
||||
|
||||
- 站点/支付平台的**域名** → `example.com` 系列(RFC 2606 保留域,永远不会指向真站)
|
||||
- **端口** → 中性数字(不是真端口)
|
||||
- **目录、盘符路径** → `<DATA_DIR>` / `<WORKER_DIR>` / `<WIN-PATH>` 这类占位
|
||||
- **家里出口 IP、局域网 IP** → `<LOCAL-IP>` 这类占位
|
||||
- **密钥 / 令牌的值** → 代码里本来就**没有硬编码**(全走文件与环境变量),所以这一项是干净的
|
||||
|
||||
**保留未换的**(说明一下,免得你以为我们漏了):
|
||||
- `localhost` —— 回环地址,通用值,不指向任何真实主机
|
||||
- `1000 / 1024 / 2048 / 4096` —— 是**出图分辨率**,业务常量,不是端口
|
||||
- **品牌笔名** —— 属公开署名,按我们的署名口径保留
|
||||
|
||||
---
|
||||
|
||||
## 关于 `模板/` 里那三个工程
|
||||
|
||||
渲染是**拿 Blender 模板工程 + 买家的皮肤贴图**渲出来的。要真跑一遍看效果,
|
||||
你需要模板 —— 所以店主选了三个给你:
|
||||
|
||||
| 文件 | 用途 |
|
||||
|---|---|
|
||||
| `1站立正反.blend` | 最基础的一个(站立,正反两面),**先用它把链路跑通** |
|
||||
| `4海边自拍.blend` | 场景类的,带环境(测"场景重"的时候用) |
|
||||
| `5不看爆炸.blend` | **另一个场景**(动感类),用来验证"换一个场景是不是也对" |
|
||||
|
||||
> 三个合起来约 45MB。**名字前面那个数字就是模板编号**,
|
||||
> 代码里 `TEMPLATES` 那张表就是靠编号对应的(一一对应,别改文件名)。
|
||||
|
||||
**渲染环境**:Blender 4.x,命令行后台模式(`-b --factory-startup`),
|
||||
Windows 下用 `pythonw.exe` 起。具体参数看 `backend-tools/make_order.py` 顶部的用法说明。
|
||||
|
||||
---
|
||||
|
||||
## 我们的思路与方法(两份交接文档里各有一节详版)
|
||||
|
||||
代码能看出"做了什么",看不出"为什么这么做、踩过什么坑"。所以两份交接文档里
|
||||
各加了一节**《我们的思路与方法》**,把这几样都摊开了,**请你连做法本身一起评**:
|
||||
|
||||
- **给自己定的硬规矩** —— 例:正常买家一步都不许多加(防探测改动不能误伤付钱的人);
|
||||
收钱的数字一律以服务器为准;状态话术不许骗人;同一件事的逻辑只写一处。
|
||||
- **干活的方法** —— 例:改一处要顺着所有调用点核一遍;同一个东西存两处时,
|
||||
先问"读取方按哪个字段找";前端必须真在浏览器里点一遍(一批 bug 在接口层根本测不出来);
|
||||
部署完要核对"跑的是不是新代码"。
|
||||
- **付过学费的坑** —— 例:静默失败最贵(不报错、不崩、就是没效果);
|
||||
显示层会骗人(订单算对了但界面从另一个来源取数);"改完不生效"是这套系统最高频的坑。
|
||||
|
||||
每份最后还有**三个我们拿不准的"做法"**请你表态(要不要换技术栈、单机多单怎么设计、
|
||||
部署不生效有没有更稳的机制)。
|
||||
|
||||
> 我们更想要的是**对做法的批评**,不只是对某几行代码的。如果整套思路就是错的,请直说。
|
||||
|
||||
---
|
||||
|
||||
## 交付清单(自查用)
|
||||
|
||||
- [x] 网站后端:`server.py` / `admin.py` / `pngcheck.py`,已脱敏
|
||||
- [x] 工具后端:19 个文件(含 `.bat` / `.ps1` / `.html` / 共用的 `skincheck.js` / Blender 脚本),已脱敏
|
||||
- [x] 两份交接文档(含《我们的思路与方法》)
|
||||
- [x] 三个模板工程,已脱敏(等长替换,文件字节数未变)
|
||||
- [x] 逐文件 SHA-256 清单(`交付清单.md`)
|
||||
- [x] 机器逐类扫描:**0 命中**(域名含大小写变体 / 端口 / 各类路径 / IP / 邮箱 / 密钥特征 /
|
||||
分享链里夹的群号与授权参数 / 第三方人名 / 长数字串)
|
||||
- [x] **独立第二双眼睛复查**(由另一个 agent 独立扫、不采信我们的自述结论)
|
||||
—— **它抓出了 3 处我们漏的**(Windows 账户名从路径与 SSH 用户名两处漏出、
|
||||
一处换过但仍像真路径的 `/srv`、一处把真端口换成了另一个像真端口的数)
|
||||
**以及 2 处"引用了却没带上"的缺件**(共用的质检脚本、打包脚本),全部已修并复扫 0 命中。
|
||||
- [ ] **故意没带的**(不是漏):运行期的数据文件(卡密池、订单、皮肤、成品、心跳、
|
||||
价格表、凭据文件等)—— 那些是**真实经营数据**,不在交付范围里。
|
||||
@@ -0,0 +1,537 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
金钻工坊 · 渲染下单 —— 管理工具(**只在本机跑**,不开公网入口)
|
||||
|
||||
python3 admin.py gen 50 --batch 2026-09-30 --value 6 批量生成 50 个码(导出 CSV)
|
||||
python3 admin.py gen 1 --tpl wheat --n-fix 3 张数卡密:这张码只能出 3 张
|
||||
python3 admin.py edit <卡密> --n-fix 5 / --unlimited / --lock-tpl / --off
|
||||
改一张还没用掉的卡密(张数/锁模板/停用)
|
||||
python3 admin.py codes [--used|--unused] 看码库
|
||||
python3 admin.py ls [waiting|working|done|failed] 看订单
|
||||
python3 admin.py show <订单号> 看单详情
|
||||
python3 admin.py retry <订单号> 把单子退回队列重渲
|
||||
python3 admin.py calls 看「呼叫金钻」记录
|
||||
python3 admin.py sweep 清理超过保留期的成品
|
||||
python3 admin.py stat 概览
|
||||
python3 admin.py audit [行数] 看兑换码失败/被拒记录
|
||||
"""
|
||||
import csv, json, os, shutil, sys, time
|
||||
from datetime import datetime, timedelta
|
||||
|
||||
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
||||
import server as S # noqa: E402
|
||||
|
||||
|
||||
def cmd_gen(argv):
|
||||
# ⚠️ 2026-10-01 实踩:`gen --help` 会被当成普通参数 → **直接生成 10 张真码**。
|
||||
# 管理工具绝不能"看个帮助就产生副作用"。
|
||||
if any(a in ("-h", "--help") for a in argv):
|
||||
print("""gen 用法:
|
||||
gen 50 生成 50 张(一张码一张图)
|
||||
gen 20 --platform 爱发电 打平台标记(买家填码时会显示来源并预选模板)
|
||||
gen 20 --n-fix 1 固定张数:这张码只能出 1 张
|
||||
gen 5 --n-free 不限张数
|
||||
gen 20 --unlimited --direct 不限张数 + 直发(不用确认收货,直接给原图)
|
||||
gen 10 --tpl wheat 预选模板(买家填码自动勾上)
|
||||
gen 20 --platform 爱发电 --n-fix 1 --export payplatform.txt
|
||||
★ 顺手导出「一行一码」纯文本,直接贴进爱发电的自动发货卡池""")
|
||||
return 0
|
||||
n = int(argv[0]) if argv and argv[0].isdigit() else 10
|
||||
batch, value, platform, tpl, is_set, direct = "", 6, "", "", False, False
|
||||
n_fix, n_max, lock_tpl, n_free, export = 0, 0, False, False, ""
|
||||
for i, a in enumerate(argv):
|
||||
if a == "--batch" and i + 1 < len(argv):
|
||||
batch = argv[i + 1]
|
||||
if a == "--value" and i + 1 < len(argv):
|
||||
value = argv[i + 1]
|
||||
# 第三方平台的标记:闲鱼 / B站工坊 …(金钻 2026-09-30)
|
||||
# 买家填码时页面会显示「来自闲鱼 · 麦田萤火」并自动预选模板,不用他自己挑
|
||||
if a == "--platform" and i + 1 < len(argv):
|
||||
platform = argv[i + 1]
|
||||
# --export 文件名:导出一份「一行一码」的纯文本。
|
||||
# 金钻 2026-10-01(P4):爱发电的「自动发货」= 你填一池子卡密,买家付款它自己发一张。
|
||||
# 这里直接产出能整段粘进去的文本,省掉手工挑码。
|
||||
if a in ("--export", "--dlv") and i + 1 < len(argv):
|
||||
export = argv[i + 1]
|
||||
if a == "--tpl" and i + 1 < len(argv):
|
||||
tpl = argv[i + 1]
|
||||
# --set = 套装卡密:一张码管一整套(全部皮肤 × 全部模板)
|
||||
if a == "--set":
|
||||
is_set = True
|
||||
# --direct = 金钻自己发的码(个人收款卖的):不用等确认收货,看完预览直接下
|
||||
if a == "--direct":
|
||||
direct = True
|
||||
# 张数卡密(金钻 2026-09-30 晚):
|
||||
# --n-fix 3 → 这张码**只能出 3 张**(模板随便改,张数不能多也不能少)
|
||||
# --n-max 10 → 最多 10 张(不限张数也可以封个顶)
|
||||
# --lock-tpl → 码里带的模板锁死,买家不能改
|
||||
if a in ("--n-fix", "--n-max") and i + 1 < len(argv):
|
||||
try:
|
||||
if a == "--n-fix":
|
||||
n_fix = int(argv[i + 1])
|
||||
else:
|
||||
n_max = int(argv[i + 1])
|
||||
except ValueError:
|
||||
print("❌ %s 要跟一个整数" % a)
|
||||
return
|
||||
if a == "--lock-tpl":
|
||||
lock_tpl = True
|
||||
# --unlimited → 不限张数(买家想出几张出几张;老规矩「一张码一张图」也解除)
|
||||
if a == "--unlimited":
|
||||
n_free = True
|
||||
# --tpl 支持逗号分隔多个(套装卡密:一张码预选一组模板)
|
||||
tpl_list = [x.strip() for x in tpl.split(",") if x.strip()]
|
||||
bad = [x for x in tpl_list if x not in S.TPL_KEYS]
|
||||
if bad:
|
||||
print("❌ 模板 key 不认识:%s\n 可选:%s" % (",".join(bad), " / ".join(S.TPL_KEYS)))
|
||||
return
|
||||
tpl = ",".join(tpl_list)
|
||||
if lock_tpl and not tpl:
|
||||
print("❌ --lock-tpl 要跟 --tpl 一起用(没有模板,锁什么?)")
|
||||
return
|
||||
if n_free and n_fix:
|
||||
print("❌「不限张数」和「固定张数」只能选一个")
|
||||
return
|
||||
made = S.gen_codes(n, batch, value, platform, tpl, is_set=is_set, direct=direct,
|
||||
n_fix=n_fix, n_max=n_max, lock_tpl=lock_tpl, n_free=n_free)
|
||||
stamp = S.now().strftime("%Y%m%d-%H%M%S")
|
||||
out = os.path.join(S.ROOT, "exports", "codes-%s.csv" % stamp)
|
||||
os.makedirs(os.path.dirname(out), exist_ok=True)
|
||||
# ⚠️ 同一秒连开两批会撞名互相覆盖(2026-09-30 实踩)→ 撞了就在后面加 -2/-3
|
||||
n_dup = 1
|
||||
while os.path.exists(out):
|
||||
n_dup += 1
|
||||
out = os.path.join(S.ROOT, "exports", "codes-%s-%d.csv" % (stamp, n_dup))
|
||||
with open(out, "w", newline="", encoding="utf-8-sig") as f:
|
||||
w = csv.writer(f)
|
||||
w.writerow(["兑换码", "面额", "批次", "平台", "模板", "固定张数", "不限张数",
|
||||
"最多张数", "锁定模板"])
|
||||
for c in made:
|
||||
w.writerow([c, value, batch, platform, tpl, n_fix or "",
|
||||
"是" if n_free else "", n_max or "", "是" if lock_tpl else ""])
|
||||
print("已生成 %d 个兑换码(面额 ¥%s,批次 %s,平台 %s,模板 %s%s%s%s%s)"
|
||||
% (len(made), value, batch or "-", platform or "-", tpl or "-",
|
||||
",★套装(一张管一整套)" if is_set else "",
|
||||
",◆直发(不用等收货)" if direct else "",
|
||||
(",张数固定 %d 张" % n_fix) if n_fix
|
||||
else ((",不限张数" if n_free else ",最多 %d 张" % n_max) if (n_free or n_max) else ",一张码一张图"),
|
||||
",🔒模板锁定不能改" if lock_tpl else ""))
|
||||
for c in made:
|
||||
print(" " + c)
|
||||
print("\nCSV: %s" % out)
|
||||
|
||||
# ---- 发卡文本(金钻 2026-10-01 P4:爱发电/闲鱼「自动发货」直接整段粘)----
|
||||
if export:
|
||||
ex_dir = os.path.join(S.ROOT, "exports")
|
||||
os.makedirs(ex_dir, exist_ok=True)
|
||||
p = export if os.path.isabs(export) else os.path.join(ex_dir, export)
|
||||
with open(p, "w", encoding="utf-8") as f:
|
||||
f.write("\n".join(made) + "\n")
|
||||
os.chmod(p, 0o640)
|
||||
print("""
|
||||
发卡文本: %s (%d 行,一行一码,可直接整段粘贴)
|
||||
▸ 爱发电:创作中心 → 商品 → 编辑 → 发货方式「自动发货」→ 把那几行粘进去 → 保存
|
||||
买家付款后爱发电自动发一张给他,他到 shop.example.com/order/ 点「卡密下单」填码就行
|
||||
▸ 闲鱼/B站工坊:发货时复制一行发给买家
|
||||
⚠️ 这份文本等于钱,别发群里、别进公开仓库(已设 640 权限)""" % (p, len(made)))
|
||||
return 0
|
||||
|
||||
|
||||
def cmd_codes(argv):
|
||||
codes = S.load_codes()
|
||||
flt = argv[0] if argv else ""
|
||||
for c, v in sorted(codes.items()):
|
||||
if flt == "--used" and not v.get("used"):
|
||||
continue
|
||||
if flt == "--unused" and v.get("used"):
|
||||
continue
|
||||
q = ("固定 %d 张" % v["n_fix"]) if v.get("n_fix") else \
|
||||
("不限张数" if v.get("n_free") else (("最多 %d 张" % v["n_max"]) if v.get("n_max") else "1 码 1 张"))
|
||||
stt = {"active": "可用", "bound": "已激活", "used": "已核销",
|
||||
"inactive": "停用"}.get(S.code_state(v), "?")
|
||||
tags = "%s%s%s%s" % (
|
||||
("【%s】" % v["platform"]) if v.get("platform") else "",
|
||||
("【%s】" % v["tpl"]) if v.get("tpl") else "",
|
||||
"🔒" if v.get("lock_tpl") else "",
|
||||
"◆直发" if v.get("direct") else "")
|
||||
print("%s %-6s 张数=%-8s %s 订单=%s %s" % (
|
||||
c, stt, q, tags, v.get("order") or "-",
|
||||
v.get("ts") or v.get("bound_at") or ""))
|
||||
stc = [S.code_state(v) for v in codes.values()]
|
||||
print("\n合计 %d 张:可用 %d / 已激活 %d / 已核销 %d / 停用 %d"
|
||||
% (len(codes), stc.count("active"), stc.count("bound"),
|
||||
stc.count("used"), stc.count("inactive")))
|
||||
|
||||
|
||||
def cmd_edit(argv):
|
||||
"""改一张还没用掉的卡密(张数 / 锁定模板 / 直发 / 停用…)。
|
||||
|
||||
金钻 2026-09-30 晚:「这个也给你开 api,方便我管理和你介入」
|
||||
用法:
|
||||
admin.py edit <卡密> --n-fix 5 固定出 5 张(不能多也不能少)
|
||||
admin.py edit <卡密> --unlimited 改成不限张数
|
||||
admin.py edit <卡密> --n-max 20 封顶 20 张
|
||||
admin.py edit <卡密> --lock-tpl 模板锁死(要码里已有模板)
|
||||
admin.py edit <卡密> --unlock-tpl 解锁模板
|
||||
admin.py edit <卡密> --tpl wheat,sakura 换一组模板
|
||||
admin.py edit <卡密> --off / --on 停用 / 启用
|
||||
"""
|
||||
if not argv:
|
||||
print(cmd_edit.__doc__)
|
||||
return
|
||||
code, p = argv[0], {}
|
||||
for i, a in enumerate(argv):
|
||||
nxt = argv[i + 1] if i + 1 < len(argv) else None
|
||||
if a == "--n-fix" and nxt:
|
||||
p["n_fix"] = nxt
|
||||
elif a == "--n-max" and nxt:
|
||||
p["n_max"] = nxt
|
||||
elif a == "--unlimited":
|
||||
p["unlimited"] = True
|
||||
elif a == "--tpl" and nxt:
|
||||
p["tpls"] = [x.strip() for x in nxt.split(",") if x.strip()]
|
||||
elif a == "--lock-tpl":
|
||||
p["lock_tpl"] = True
|
||||
elif a == "--unlock-tpl":
|
||||
p["lock_tpl"] = False
|
||||
elif a == "--direct":
|
||||
p["direct"] = True
|
||||
elif a == "--no-direct":
|
||||
p["direct"] = False
|
||||
elif a == "--set":
|
||||
p["set"] = True
|
||||
elif a == "--no-set":
|
||||
p["set"] = False
|
||||
elif a == "--off":
|
||||
p["state"] = "inactive"
|
||||
elif a == "--on":
|
||||
p["state"] = "active"
|
||||
elif a == "--platform" and nxt:
|
||||
p["platform"] = nxt
|
||||
if not p:
|
||||
print("没给要改什么 —— 看用法:")
|
||||
print(cmd_edit.__doc__)
|
||||
return
|
||||
ok, e, info = S.edit_code(code, p)
|
||||
if not ok:
|
||||
print("❌ " + e)
|
||||
return
|
||||
print("✅ %s 改好了:张数 %s | 模板 %s%s | 直发 %s | 状态 %s"
|
||||
% (info["code"],
|
||||
(("固定 %d 张" % info["n_fix"]) if info["n_fix"]
|
||||
else (("最多 %d 张" % info["n_max"]) if info["n_max"] else "不限")),
|
||||
",".join(info["tpls"]) or "自由选",
|
||||
"(🔒锁定)" if info["lock_tpl"] else "",
|
||||
"是" if info["direct"] else "否", info["state"]))
|
||||
|
||||
|
||||
def cmd_ls(argv):
|
||||
st = argv[0] if argv else None
|
||||
rows = S.list_orders((st,) if st else None)
|
||||
if not rows:
|
||||
print("(没有订单)")
|
||||
return
|
||||
for m in sorted(rows, key=lambda x: x.get("created") or ""):
|
||||
print("%-10s %-8s %-19s %d 张 %s %s" % (
|
||||
m["oid"], m.get("state"), m.get("created", ""),
|
||||
len(m.get("templates") or []), m.get("arm"),
|
||||
",".join(m.get("templates") or [])))
|
||||
print("\n共 %d 单" % len(rows))
|
||||
|
||||
|
||||
def cmd_show(argv):
|
||||
if not argv:
|
||||
sys.exit("用法: admin.py show <订单号>")
|
||||
m = S.read_meta(argv[0])
|
||||
if not m:
|
||||
sys.exit("没有这个订单")
|
||||
m2 = dict(m)
|
||||
m2.pop("token", None)
|
||||
print(json.dumps(m2, ensure_ascii=False, indent=1))
|
||||
|
||||
|
||||
def cmd_retry(argv):
|
||||
if not argv:
|
||||
sys.exit("用法: admin.py retry <订单号>")
|
||||
oid = argv[0]
|
||||
m = S.read_meta(oid)
|
||||
if not m:
|
||||
sys.exit("没有这个订单")
|
||||
m["state"] = "waiting"
|
||||
m["note"] = "管理员退回重渲"
|
||||
m["started"] = m["finished"] = None
|
||||
S.write_meta(oid, m)
|
||||
print("%s 已退回队列" % oid)
|
||||
|
||||
|
||||
def cmd_calls(argv):
|
||||
try:
|
||||
for line in open(S.CALLS_FILE, encoding="utf-8"):
|
||||
if line.strip():
|
||||
r = json.loads(line)
|
||||
print("%s 订单=%s IP=%s %s" % (r["ts"], r.get("order") or "-",
|
||||
r.get("ip"), "已通知" if r.get("notified") else "未通知"))
|
||||
except OSError:
|
||||
print("(没有呼叫记录)")
|
||||
|
||||
|
||||
def cmd_sweep(argv):
|
||||
"""清过期成品 + **核销卡密**(金钻 2026-09-30 晚:「核销要等开放下载后 72 小时」)。
|
||||
|
||||
到期口径改用 S.expire_at():确认收货/直发出图之后 72 小时(没开放下载的用创建时间兜底)。
|
||||
⚠️ 删文件之前先把卡密核销 —— 否则文件没了、码还挂在「已激活」,账永远对不上。
|
||||
"""
|
||||
n = freed = settled = 0
|
||||
for oid in list(os.listdir(S.ORDERS)):
|
||||
d = os.path.join(S.ORDERS, oid)
|
||||
m = S.read_meta(oid)
|
||||
if not m:
|
||||
continue
|
||||
exp = S.expire_at(m)
|
||||
if exp is None or exp > datetime.now(S.CST):
|
||||
continue
|
||||
settled += S.settle_codes(oid, "订单到期清理(开放下载满 %dh)" % S.KEEP_HOURS)
|
||||
for root, _, files in os.walk(d):
|
||||
for f in files:
|
||||
try:
|
||||
freed += os.path.getsize(os.path.join(root, f))
|
||||
except OSError:
|
||||
pass
|
||||
shutil.rmtree(d, ignore_errors=True)
|
||||
n += 1
|
||||
# 文件还在、但开放下载已满 72 小时的,也一起核销
|
||||
settled += sum(x[1] for x in S.settle_due())
|
||||
print("清理 %d 单,释放 %.1f MB,核销卡密 %d 张" % (n, freed / 1048576, settled))
|
||||
|
||||
|
||||
def cmd_audit(argv):
|
||||
n = int(argv[0]) if argv and argv[0].isdigit() else 40
|
||||
try:
|
||||
lines = [l for l in open(S.LOG_FILE, encoding="utf-8").read().splitlines()
|
||||
if ("兑换码失败" in l or "拒绝" in l)]
|
||||
except OSError:
|
||||
lines = []
|
||||
for l in lines[-n:]:
|
||||
print(l)
|
||||
print("\n共 %d 条异常记录" % len(lines))
|
||||
|
||||
|
||||
def cmd_activate(argv):
|
||||
"""网页下单:买家付了款,激活这一单 → 进队列开渲。"""
|
||||
oid = (argv[0] if argv else "").strip().upper()
|
||||
if not oid:
|
||||
print("用法: activate <订单号>")
|
||||
return
|
||||
m = S.read_meta(oid)
|
||||
if not m:
|
||||
print("没有这个订单:%s" % oid)
|
||||
return
|
||||
st = m.get("state")
|
||||
if st not in ("unpaid", "paid"):
|
||||
print("订单 %s 现在是「%s」,不是待付款,没动它" % (oid, st))
|
||||
return
|
||||
m["state"] = "waiting"
|
||||
m["paid_at"] = S.now().isoformat(timespec="seconds")
|
||||
with S.LOCK:
|
||||
S.write_meta(oid, m)
|
||||
print("✅ 订单 %s 已激活 → 进入排队" % oid)
|
||||
print(" 模板:%s | 分辨率:%s | 码:%s"
|
||||
% (",".join(m.get("templates") or []), m.get("res"), ",".join(m.get("codes") or [])))
|
||||
|
||||
|
||||
def cmd_pending(argv):
|
||||
"""列出待付款的网页单(等你收钱激活的)"""
|
||||
rows = S.list_orders(("unpaid", "paid"))
|
||||
if not rows:
|
||||
print("没有待付款 / 待激活的网页单")
|
||||
return
|
||||
for m in rows:
|
||||
tag = "★买家已报付款" if m.get("state") == "paid" else "还没付款"
|
||||
print("%s %-12s ¥%-5s %s 张 %s 码 %s"
|
||||
% (m["oid"], tag, m.get("amount") or (S.PRICE_UNIT * len(m.get("templates") or [] or [1])),
|
||||
len(m.get("templates") or []), ",".join(m.get("templates") or []),
|
||||
",".join(m.get("codes") or [])))
|
||||
print("\n共 %d 单 —— 确认到账后跑:python3 admin.py activate <订单号>" % len(rows))
|
||||
|
||||
|
||||
def cmd_stat(argv):
|
||||
codes = S.load_codes()
|
||||
st = [S.code_state(v) for v in codes.values()]
|
||||
print("卡密 %d 张(可用 %d / 已激活 %d / 已核销 %d / 停用 %d)"
|
||||
% (len(codes), st.count("active"), st.count("bound"),
|
||||
st.count("used"), st.count("inactive")))
|
||||
hb = S.heartbeat()
|
||||
print("渲染机 %s 最后心跳 %s" % ("在线" if hb["online"] else "离线", hb["last_seen"]))
|
||||
for st in ("unpaid", "paid", "waiting", "working", "done", "failed"):
|
||||
print("订单 %-8s %d" % (st, len(S.list_orders((st,)))))
|
||||
total = 0
|
||||
for root, _, files in os.walk(S.ROOT):
|
||||
for f in files:
|
||||
try:
|
||||
total += os.path.getsize(os.path.join(root, f))
|
||||
except OSError:
|
||||
pass
|
||||
print("数据占用 %.1f MB" % (total / 1048576))
|
||||
|
||||
|
||||
def cmd_price(argv):
|
||||
"""价格档位(金钻 2026-10-01:「按张数和优惠设置专属购买价格链接」)
|
||||
|
||||
看: python3 admin.py price
|
||||
设: python3 admin.py price set 3 15 http<WIN-PATH>
|
||||
(第 3 档 = 买 3 张 ¥15,付款按钮就跳这个商品链接;链接可省 = 用总链接)
|
||||
删: python3 admin.py price rm 3
|
||||
单价: python3 admin.py price per 6 (没配档位的张数按这个算)
|
||||
"""
|
||||
d = S.price_tiers()
|
||||
tiers = d.get("tiers") or {}
|
||||
if not argv:
|
||||
print("单价(没配档位时):¥%g/张" % d["per"])
|
||||
print("%-6s %-8s %s" % ("张数", "价格", "专属商品链接"))
|
||||
for k in sorted(tiers, key=lambda x: int(x) if x.isdigit() else 99):
|
||||
t = tiers[k] or {}
|
||||
print("%-6s ¥%-7s %s" % (k, t.get("price"), t.get("payplatform") or "(用总链接)"))
|
||||
if not tiers:
|
||||
print("(还没配任何档位)")
|
||||
print("\n设一档:python3 admin.py price set 3 15 http<WIN-PATH>")
|
||||
return
|
||||
sub = argv[0]
|
||||
if sub == "per" and len(argv) > 1:
|
||||
d["per"] = float(argv[1])
|
||||
elif sub == "set" and len(argv) > 2:
|
||||
n, price = argv[1], argv[2]
|
||||
if not n.isdigit() or int(n) < 1:
|
||||
raise SystemExit("张数要正整数")
|
||||
tiers[n] = {"price": float(price), "payplatform": (argv[3] if len(argv) > 3 else "").strip()}
|
||||
elif sub == "rm" and len(argv) > 1:
|
||||
tiers.pop(argv[1], None)
|
||||
else:
|
||||
raise SystemExit("用法:price / price per N / price set N 价格 [链接] / price rm N")
|
||||
d["tiers"] = tiers
|
||||
S.jsave(S.PRICES_FILE, d)
|
||||
try:
|
||||
os.chmod(S.PRICES_FILE, 0o644)
|
||||
except OSError:
|
||||
pass
|
||||
print("改好了 —— 现在:")
|
||||
cmd_price([])
|
||||
|
||||
|
||||
def cmd_gift(argv):
|
||||
"""福利券(金钻 2026-10-01「赛博鸡蛋」):一批**免费、免付费、只限张数**的码,买家自取。
|
||||
|
||||
看: python3 admin.py gift
|
||||
开一批:python3 admin.py gift new 赛博鸡蛋 --count 50 --n-fix 1
|
||||
加 --tpl sakura --lock → 只让领的人试这个新模板(试玩券)
|
||||
加 --days 7 → 7 天后自动收摊
|
||||
加 --no-direct → 领到的券也要走「确认收货」才给原图(默认直发)
|
||||
补货:python3 admin.py gift add <批次id> --count 20
|
||||
收摊:python3 admin.py gift off <批次id> (已领到手的券不受影响)
|
||||
|
||||
⚠️ 建/补/收的逻辑全在 server.py(gift_batch_new / gift_batch_add / gift_batch_off)——
|
||||
金钻电脑上那块**面板**(ys_admin.py 的「免费码」区块)调的是同一批函数。
|
||||
**改规则只改 server.py 那一处**,别在这儿再写一遍(两边必漂移)。
|
||||
"""
|
||||
|
||||
def show_all():
|
||||
rows = S.gift_batches()["batches"] # 每次现读:刚建/补完的批次要立刻看见
|
||||
if not rows:
|
||||
print("(还没有福利券批次)")
|
||||
return
|
||||
print("%-16s %-16s %-6s %-6s %-8s %s" % ("批次", "名字", "总数", "已领", "还剩", "限制"))
|
||||
for b in rows:
|
||||
st = S.gift_stat(b["id"])
|
||||
lim = "%d 张/人" % int(b.get("each") or 1)
|
||||
lim += ",锁模板 %s" % b["tpl"] if b.get("lock_tpl") else ""
|
||||
lim += ",%s 到期" % b["expire"] if b.get("expire") else ""
|
||||
if not b.get("enabled", True):
|
||||
lim += "(已收摊)"
|
||||
print("%-16s %-16s %-6d %-6d %-8d %s"
|
||||
% (b["id"], b.get("name") or "", st["total"], st["claimed"], st["left"], lim))
|
||||
|
||||
if not argv:
|
||||
show_all()
|
||||
return
|
||||
sub = argv[0]
|
||||
if sub == "new" and len(argv) > 1:
|
||||
name = argv[1]
|
||||
op = {"count": 20, "n-fix": 1, "each": 1, "tpl": "", "lock": False,
|
||||
"days": 0, "note": "", "direct": True, "kind": "render", "free": False}
|
||||
i = 2
|
||||
while i < len(argv):
|
||||
a = argv[i]
|
||||
if a == "--count" and i + 1 < len(argv):
|
||||
op["count"] = int(argv[i + 1]); i += 2
|
||||
elif a == "--n-fix" and i + 1 < len(argv):
|
||||
op["n-fix"] = int(argv[i + 1]); i += 2
|
||||
elif a == "--each" and i + 1 < len(argv):
|
||||
op["each"] = int(argv[i + 1]); i += 2
|
||||
elif a == "--tpl" and i + 1 < len(argv):
|
||||
op["tpl"] = argv[i + 1]; i += 2
|
||||
elif a == "--days" and i + 1 < len(argv):
|
||||
op["days"] = int(argv[i + 1]); i += 2
|
||||
elif a == "--note" and i + 1 < len(argv):
|
||||
op["note"] = argv[i + 1]; i += 2
|
||||
elif a == "--lock":
|
||||
op["lock"] = True; i += 1
|
||||
elif a == "--kind" and i + 1 < len(argv):
|
||||
op["kind"] = argv[i + 1]; i += 2 # render/standee/keychain/poster…
|
||||
elif a == "--n-free":
|
||||
op["free"] = True; i += 1 # 不限张数
|
||||
elif a == "--no-direct":
|
||||
op["direct"] = False; i += 1
|
||||
else:
|
||||
i += 1
|
||||
try:
|
||||
bid, codes = S.gift_batch_new(
|
||||
name, count=op["count"], n_fix=op["n-fix"], n_free=op["free"],
|
||||
tpl=op["tpl"], lock_tpl=op["lock"], days=op["days"],
|
||||
note=op["note"], kind=op["kind"], direct=op["direct"], each=op["each"])
|
||||
except ValueError as e:
|
||||
raise SystemExit(str(e))
|
||||
print("批次 id:%s(把这个贴给别人也行:福利页会自动列出来)" % bid)
|
||||
print("生了 %d 张券。" % len(codes))
|
||||
show_all()
|
||||
elif sub == "add" and len(argv) > 1:
|
||||
bid = argv[1]
|
||||
n, direct = 20, None
|
||||
i = 2
|
||||
while i < len(argv):
|
||||
if argv[i] == "--count" and i + 1 < len(argv):
|
||||
n = int(argv[i + 1]); i += 2
|
||||
elif argv[i] == "--no-direct":
|
||||
direct = False; i += 1
|
||||
elif argv[i] == "--direct":
|
||||
direct = True; i += 1
|
||||
else:
|
||||
i += 1
|
||||
try:
|
||||
got = S.gift_batch_add(bid, n, direct=direct)
|
||||
except ValueError as e:
|
||||
raise SystemExit(str(e))
|
||||
print("补了 %d 张(批次 %s)" % (len(got), bid))
|
||||
show_all()
|
||||
elif sub == "off" and len(argv) > 1:
|
||||
try:
|
||||
S.gift_batch_off(argv[1])
|
||||
except ValueError as e:
|
||||
raise SystemExit(str(e))
|
||||
print("已收摊(已领到手的券照常用):%s" % argv[1])
|
||||
show_all()
|
||||
else:
|
||||
raise SystemExit("用法见文件头注释")
|
||||
|
||||
|
||||
CMDS = {"gen": cmd_gen, "codes": cmd_codes, "ls": cmd_ls, "show": cmd_show,
|
||||
"gift": cmd_gift,
|
||||
"price": cmd_price,
|
||||
"retry": cmd_retry, "calls": cmd_calls, "sweep": cmd_sweep, "stat": cmd_stat,
|
||||
"audit": cmd_audit, "activate": cmd_activate, "pending": cmd_pending,
|
||||
"edit": cmd_edit}
|
||||
|
||||
if __name__ == "__main__":
|
||||
if len(sys.argv) < 2 or sys.argv[1] not in CMDS:
|
||||
print(__doc__)
|
||||
sys.exit(1)
|
||||
CMDS[sys.argv[1]](sys.argv[2:])
|
||||
@@ -0,0 +1,133 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""PNG 结构核验 —— 防「夹带私货」:有人在文件尾部或元数据块里塞任意数据,
|
||||
改图看不出来,但能夹带任意字节(图片里藏文件 / 藏提示词 / 藏脚本)。
|
||||
|
||||
**只做结构判断,不解码像素** —— 零依赖、零成本、零误判。
|
||||
|
||||
判定分三档:
|
||||
拒(reject)
|
||||
* 签名不对 / 没有 IHDR / 块结构损坏或截断
|
||||
* **IEND 之后还有字节** ← 最常见的尾部夹带
|
||||
* 未知的「关键块」(首字母大写且不在白名单)→ 后面可能跟着必须解析的语义
|
||||
* **APNG(acTL)** → 多帧能藏额外画面,剥掉 acTL 会留下孤儿 fcTL
|
||||
剥(strip,不算错)
|
||||
* tEXt / zTXt / iTXt / eXIf / tIME → 元数据,很多编辑器会自动加,剥掉不影响成图
|
||||
过(pass)
|
||||
* IHDR / PLTE / IDAT / IEND / tRNS / gAMA / cHRM / sRGB / iCCP / bKGD / pHYs / sBIT
|
||||
|
||||
⚠️ 这份逻辑在前端也有一份镜像(`skincheck.js` 的 `checkPngBytes`)。
|
||||
两边必须一致 —— 前端负责**拦**(给人看的原因),后端负责**剥**(存下来的是干净字节)。
|
||||
改一边记得改另一边,`tests/png_struct_test.py` 里有共享用例。
|
||||
"""
|
||||
|
||||
import struct
|
||||
import zlib
|
||||
|
||||
SIG = b"\x89PNG\r\n\x1a\n"
|
||||
|
||||
# 直接剥掉的辅助块(不报错)
|
||||
STRIP = {b"tEXt", b"zTXt", b"iTXt", b"eXIf", b"tIME", b"sPLT", b"hIST"}
|
||||
|
||||
# 允许出现的关键块
|
||||
CRITICAL_OK = {b"IHDR", b"PLTE", b"IDAT", b"IEND"}
|
||||
|
||||
MAX_CHUNKS = 4096 # 防"超多小块"这种结构型 DoS
|
||||
|
||||
|
||||
def scan(data):
|
||||
"""核验并清洗。
|
||||
|
||||
返回 (ok, reason, clean_bytes, notes)
|
||||
ok=False 时 clean 为 None
|
||||
"""
|
||||
notes = []
|
||||
|
||||
if not isinstance(data, (bytes, bytearray)):
|
||||
return False, "数据格式不对", None, notes
|
||||
data = bytes(data)
|
||||
if len(data) < 8 + 25 or data[:8] != SIG:
|
||||
return False, "不是 PNG 文件", None, notes
|
||||
|
||||
off = 8
|
||||
out = bytearray(SIG)
|
||||
n_chunks = 0
|
||||
seen_ihdr = False
|
||||
seen_idat = False
|
||||
seen_iend = False
|
||||
|
||||
while off < len(data):
|
||||
if n_chunks > MAX_CHUNKS:
|
||||
return False, "PNG 结构异常(块数量过多)", None, notes
|
||||
if off + 8 > len(data):
|
||||
return False, "PNG 文件损坏(块头不完整)", None, notes
|
||||
|
||||
(ln,) = struct.unpack(">I", data[off:off + 4])
|
||||
ctype = data[off + 4:off + 8]
|
||||
end = off + 12 + ln
|
||||
if ln > len(data) or end > len(data):
|
||||
return False, "PNG 文件损坏(块数据不完整)", None, notes
|
||||
|
||||
chunk = data[off:end]
|
||||
n_chunks += 1
|
||||
|
||||
# CRC 自检(不一致只记一笔,不拒 —— 目标是防夹带,不是查完整性)
|
||||
try:
|
||||
want = struct.unpack(">I", chunk[-4:])[0]
|
||||
got = zlib.crc32(chunk[4:-4]) & 0xFFFFFFFF
|
||||
if want != got:
|
||||
notes.append("块 %s 的 CRC 对不上" % ctype.decode("latin-1"))
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
if ctype == b"IHDR":
|
||||
if len(out) != 8:
|
||||
return False, "PNG 结构异常(IHDR 不在最前)", None, notes
|
||||
seen_ihdr = True
|
||||
out += chunk
|
||||
|
||||
elif ctype == b"IEND":
|
||||
seen_iend = True
|
||||
tail = len(data) - end # ← 尾部夹带就在这里露馅
|
||||
if tail > 0:
|
||||
return False, ("图片尾部夹带了 %d 字节额外数据(正常 PNG 到 IEND 就该结束)" % tail), None, notes
|
||||
out += chunk
|
||||
off = end
|
||||
break
|
||||
|
||||
elif ctype == b"acTL":
|
||||
return False, "这是动画 PNG(APNG),请用普通静态 PNG", None, notes
|
||||
|
||||
elif ctype == b"IDAT":
|
||||
seen_idat = True
|
||||
out += chunk
|
||||
|
||||
elif ctype in (b"PLTE", b"tRNS", b"gAMA", b"cHRM", b"sRGB", b"iCCP", b"bKGD", b"pHYs", b"sBIT"):
|
||||
out += chunk
|
||||
|
||||
elif ctype in STRIP:
|
||||
notes.append("已剥掉元数据块 %s" % ctype.decode("latin-1"))
|
||||
|
||||
else:
|
||||
critical = not (ctype[0] & 0x20) # PNG 规范:首字母大写 = 关键块
|
||||
if critical and ctype not in CRITICAL_OK:
|
||||
return False, ("图片里有无法识别的内容块 %s" % ctype.decode("latin-1", "replace")), None, notes
|
||||
notes.append("已剥掉附加块 %s" % ctype.decode("latin-1", "replace"))
|
||||
|
||||
off = end
|
||||
|
||||
if not seen_ihdr:
|
||||
return False, "PNG 缺少 IHDR(不是完整图片)", None, notes
|
||||
if not seen_idat:
|
||||
return False, "PNG 缺少图像数据(IDAT)", None, notes
|
||||
if not seen_iend:
|
||||
return False, "PNG 没有正常结束(缺 IEND)", None, notes
|
||||
|
||||
return True, "", bytes(out), notes
|
||||
|
||||
|
||||
def size_of(data):
|
||||
"""只读 IHDR 拿宽高(不解码像素)。"""
|
||||
if len(data) < 33 or data[:8] != SIG or data[12:16] != b"IHDR":
|
||||
return None
|
||||
w, h = struct.unpack(">II", data[16:24])
|
||||
return w, h
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,247 @@
|
||||
# 交接说明 · 网站后端(卡密 / 自助渲染下单)
|
||||
|
||||
> **交付方**:苏达(网站运维与技术提供)
|
||||
> **收件方**:外部协作者
|
||||
> **日期**:2026-10-05
|
||||
> **一句话**:这是一个**零依赖单进程**的下单/卡密/队列后端,跑在一台小机器上。
|
||||
> 请你重点看**安全与并发**,并给我们**问题分析 + 改正意见**(见最后一节)。
|
||||
|
||||
---
|
||||
|
||||
## 一、这一份是什么
|
||||
|
||||
「自助模板渲染」的**服务端**:买家在网页挑模板、传皮肤、填卡密下单;
|
||||
服务器登记订单、排队;家里那台渲染机上线后自动领单、出图、回传;
|
||||
买家再回来下载。**目标是无人值守** —— 不用人 24 小时盯着。
|
||||
|
||||
```
|
||||
买家 → 网页(本地质检→选模板→填卡密→核对)→ POST /api/submit
|
||||
↓ 核销卡密 + 落盘订单目录
|
||||
服务器 → 队列(订单 meta 里的一个 state 字段:waiting/working/done/failed)
|
||||
渲染机 → 每 20s:POST /hb → POST /claim → GET /skin/<单号>
|
||||
→ Blender 渲染 → POST /progress(进度)→ POST /finish(一张一次)
|
||||
买家 → GET /api/order/<单号>?t=<口令> → 下载 /api/dl/<单号>/<i>?t=<口令>
|
||||
```
|
||||
|
||||
**为什么"渲染机是主动出站"**:家里那台机器没有公网入口,所以**服务器从不连它**,
|
||||
全靠它自己定时来拉。心跳超过阈值没更新 → 页面显示「渲染机离线」。
|
||||
|
||||
---
|
||||
|
||||
## 二、技术栈与运行方式
|
||||
|
||||
| 项 | 值 |
|
||||
|---|---|
|
||||
| 语言 / 依赖 | **Python 3,纯标准库,零第三方依赖**(连 Web 框架都没用,`BaseHTTPRequestHandler`) |
|
||||
| 进程 | 单进程,由 systemd 托管;内存上限被 cgroup 卡住(小机器上防它吃爆) |
|
||||
| 监听 | **只绑回环**,公网由 nginx 反代过去(后端自己不对外开端口) |
|
||||
| 账号 | 跑在专用非 root 用户下 |
|
||||
| 数据 | 全在本地文件 + 一个 SQLite(无外部服务) |
|
||||
| 规模 | 单机单进程,日单量个位数到几十 |
|
||||
|
||||
**为什么不用框架**:这台机器很小(1G 多内存),装一个 Web 框架 + 一堆传递依赖不划算,
|
||||
而且这台机器**不允许跑重活**(视频转码这类会把它拖死)。纯标准库启动快、内存稳。
|
||||
|
||||
---
|
||||
|
||||
## 三、文件清单
|
||||
|
||||
| 文件 | 行数 | 干什么 |
|
||||
|---|---|---|
|
||||
| `server.py` | ~3100 | **全部服务端逻辑**:路由、订单状态机、卡密生命周期、限流、PNG 结构核验的调用方、爱发电回调、打包下载、小票生成 |
|
||||
| `admin.py` | ~540 | 命令行管理工具:发卡密 / 看队列 / 重渲 / 清过期 / 审计被拦记录 |
|
||||
| `pngcheck.py` | ~130 | PNG **结构**核验(不解码像素):防「夹带私货」——尾部塞字节、未知关键块、APNG |
|
||||
|
||||
> 这三个文件是**自足**的:没有 import 本项目之外的模块。
|
||||
|
||||
---
|
||||
|
||||
## 四、对外接口
|
||||
|
||||
全部挂在 `/order/api/` 下(nginx 反代);下面路径已按脱敏规则替换过前缀,**看形状别看字面**。
|
||||
|
||||
| 方法 | 路径 | 谁用 | 说明 |
|
||||
|---|---|---|---|
|
||||
| GET | `/api/status` | 页面轮询 | 渲染机在线?队列长度 |
|
||||
| POST | `/api/submit` | 页面 | 皮肤(base64) + 模板数组 + 卡密数组 + 臂型 → 返回 `{order, token}` |
|
||||
| POST | `/api/add-skin` | 页面 | 追补一张皮肤(多皮肤单) |
|
||||
| POST | `/api/set-templates` | 页面 | 改/补模板(可只改某一张皮肤的) |
|
||||
| GET | `/api/order/<单号>?t=<口令>` | 页面 | 状态 + 可下载文件清单 + 进度 + 预计耗时 |
|
||||
| GET | `/api/dl/<单号>/<i>?t=<口令>` | 买家 | 下载成品(未收货只能拿预览) |
|
||||
| GET | `/api/zip/<单号>?t=` | 买家 | 整单原图打 zip(先落临时文件再边读边发) |
|
||||
| GET | `/api/receipt/<单号>?t=` | 买家 | 小票纯文本(`&dl=1` 变附件) |
|
||||
| POST | `/api/accept` | 买家 | 确认收货 → 才放原图 |
|
||||
| POST | `/api/paid` | 买家 | 「我付好了」 |
|
||||
| POST | `/api/activate` | 买家 | 用卡密**激活自己那一单**(码认单,不开新单) |
|
||||
| POST | `/api/redo` | 买家 | 重渲(支持只重出勾中的那几张) |
|
||||
| POST | `/api/call` | 页面 | 呼叫店主(同 IP 限次) |
|
||||
| POST | `/api/feedback` | 页面 | 反馈(落盘 + 通知) |
|
||||
| GET | `/api/payinfo` | 页面 | 付款方式(链接/收款码) |
|
||||
| POST | `/api/payplatform-hook` | 支付平台回调 | **不验签,改成拿开放接口反查这笔单**(见下) |
|
||||
| POST | `/api/hb` `/api/claim` `/api/skin/<单号>` `/api/progress` `/api/finish` `/api/fail` | **渲染机** | 都要请求头里的 worker token |
|
||||
| GET/POST | `/api/admin/*` | **本机后台面板** | 头里带 admin token **且**来源 IP 必须是家里出口 IP |
|
||||
|
||||
### 支付回调的处理顺序(这段是重点,欢迎挑刺)
|
||||
|
||||
```
|
||||
① 标题含"测试" → 只记账
|
||||
② 幂等:同一平台单号重推 → 回同一张卡密
|
||||
③ 反查不到 / 未付款 → 只记账 + 标 need_human,**绝不发卡密**
|
||||
④ 金额比对:
|
||||
少付(paid + 0.005 < need)→ **闸门拦死**,不激活不发码,记 need_human
|
||||
多付 → 照样激活出图,但记 over 待人工看一眼
|
||||
⑤ 认单优先级:自定义订单号 > 留言里的卡密 > 留言里的订单号 > 「只有一笔待付款单金额对得上」
|
||||
(两笔及以上一律人工,绝不乱认)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 五、数据形状(都是文件/JSON,没有数据库表)
|
||||
|
||||
| 路径 | 内容 |
|
||||
|---|---|
|
||||
| `<DATA_DIR>/codes.json` | 卡密池:`{码: {state, platform, tpl, n_fix, n_free, n_max, lock_tpl, oid, order, batch}}` |
|
||||
| `<DATA_DIR>/orders/<单号>/meta.json` | 订单:状态、皮肤数组、模板、金额、时间、条款留证、进度 |
|
||||
| `<DATA_DIR>/orders/<单号>/skins/` | 买家皮肤原图(落盘前已过 PNG 结构核验并剥掉元数据块) |
|
||||
| `<DATA_DIR>/orders/<单号>/out/` | 成品(标准压缩 + 无压缩 两个版本/张) |
|
||||
| `<DATA_DIR>/worker_token`、`admin_token` | 两把**互不通用**的令牌(文件权限 600) |
|
||||
| `<DATA_DIR>/home_ips.json` | 渲染机心跳认出来的「家里的出口 IP」 |
|
||||
| `<DATA_DIR>/calls.jsonl` | 「呼叫店主」记录 |
|
||||
| `<DATA_DIR>/upload.log` 等 | 审计留痕 |
|
||||
|
||||
### 卡密生命周期(**激活 ≠ 核销**,这是刻意分开的)
|
||||
|
||||
```
|
||||
active 可用
|
||||
↓ 买家点提交
|
||||
bound **已激活** —— 被这一单占住,不能用于别的单;但还没核销
|
||||
↓ 成品开放下载满 72 小时(或直发单从渲完起算)
|
||||
used **已核销** —— 终态
|
||||
inactive 停用(网页单等付款 / 手动停用)
|
||||
```
|
||||
|
||||
⚠️ 触发核销的只有两处,**删文件之前必须先核销**,否则文件没了码还挂在"已激活"。
|
||||
|
||||
---
|
||||
|
||||
## 六、已经做了的防护(请你对着挑漏)
|
||||
|
||||
| 防护 | 做法 |
|
||||
|---|---|
|
||||
| 卡密暴力破解 | 31 字符取 12 位 ≈ 7.9e17 组合;**单 IP 连错 15 次 → 冷却 15 分钟** |
|
||||
| 灌单 | 单 IP 10 分钟最多开 6 单;提交接口在 nginx 上单独限流 |
|
||||
| 探测 | **「订单不存在」与「口令错」返回同一个 404**(不承认站上有这单) |
|
||||
| 占盘 | 磁盘剩余低于阈值**停止收单** |
|
||||
| 夹带私货 | PNG 结构核验:拒尾部追加 / 未知关键块 / APNG;剥掉文本与 EXIF 类元数据块 |
|
||||
| 取皮肤 | 必须带 worker token |
|
||||
| 管理接口 | **两道门**:token + 来源 IP 必须是家里出口 IP(公网别处扫到也是 403) |
|
||||
| 路径穿越 | slug 白名单 + realpath 前缀校验 |
|
||||
|
||||
---
|
||||
|
||||
## 七、⚠️ 脱敏说明(**重要:这份代码不能直接跑**)
|
||||
|
||||
按我们的出站纪律,**所有指向真实环境的值都换成了占位**:
|
||||
|
||||
| 类别 | 替换成 |
|
||||
|---|---|
|
||||
| 站点域名 / 支付平台域名 | `shop.example.com` / `pay-platform.example` |
|
||||
| 监听端口、面板端口 | 中性数字(`8080`/`8081`/`8082`…)—— **不是真值** |
|
||||
| 数据 / 程序 / 工作目录 | `<DATA_DIR>` / `<APP_DIR>` / `<WORKER_DIR>` |
|
||||
| Windows 盘符路径 | `<WIN-PATH>` / `<ARCHIVE_DIR>` / `<TOOLS_DIR>` |
|
||||
| 家里出口 IP / 局域网 IP | `<HOME-LAN-IP>` / `<LOCAL-IP>` |
|
||||
| 通配绑定地址 | `<ALL-INTERFACES>` |
|
||||
| 密钥 / 令牌**值** | 本来就没有硬编码——全走文件与环境变量,所以代码里是干净的 |
|
||||
|
||||
**保留未换的**:`localhost`(回环,通用值)、渲染分辨率 `1000/1024/2048/4096`(业务常量)、
|
||||
以及**品牌笔名**(属公开署名)。
|
||||
|
||||
**包里没有的**(⚠️ 别去找,是刻意不给):
|
||||
- 任何真实卡密、订单、买家皮肤与成品图
|
||||
- 两把令牌、任何密钥、任何账号凭据
|
||||
- 数据库/运行数据、备份
|
||||
- 私有仓库地址、内部文档
|
||||
|
||||
---
|
||||
|
||||
## 八、⭐ 我们要你交给我们的东西(**这一份的主要目的**)
|
||||
|
||||
请你读完之后**回一份文档**(放在同一个仓库里就行,文件名 `回执-<你的名字>.md`),至少包含三部分:
|
||||
|
||||
1. **问题分析** —— 你看到的问题、风险、坏味道。分个轻重(会导致丢钱/丢数据/被人打的,排前面)。
|
||||
请**尽量指到具体函数/行**,并说清**触发条件**(什么输入、什么并发时序会踩到)。
|
||||
2. **改正意见** —— 每条给**你建议怎么改**(不一定要写代码,说清思路和代价也行)。
|
||||
如果有**更简单的整体方案**(比如"这段根本该换个做法"),也请直说,别客气。
|
||||
3. **你改了什么** —— 如果你直接动手改了,请逐条列:
|
||||
```
|
||||
文件 / 函数:
|
||||
为什么改:
|
||||
改成什么(一句话说清):
|
||||
有没有动到接口路径、请求/响应字段、数据格式(**这三样动了我们必须知道**):
|
||||
你怎么验证的(跑过什么、看到什么):
|
||||
```
|
||||
⚠️ **改了接口/数据格式一定要单独标出来** —— 渲染机那边是另一台机器上的另一份代码,
|
||||
两边不同步会**静默出不来图**。
|
||||
|
||||
**另外请你顺手回答两个具体问题**(我们自己拿不准):
|
||||
- 爱发电那条线**"不验签、改成拿开放接口反查"**,你认为够不够硬?有没有更好的做法?
|
||||
- 订单状态机(`unpaid → paid → waiting → working → done/failed`)在**部分失败**时
|
||||
(比如 3 张图渲出 2 张)你建议怎么收口?
|
||||
|
||||
|
||||
---
|
||||
|
||||
## 九、我们的思路与方法(**请你连这套做法一起评**)
|
||||
|
||||
代码能看出的是一部分;**为什么这么做、踩过什么坑**,在代码里看不到。这一节补上,
|
||||
**并且希望你连"做法"本身一起挑** —— 如果我们整套思路就是错的,那比某个函数写错更要紧。
|
||||
|
||||
### 9.1 我们给自己定的几条硬规矩
|
||||
|
||||
| 规矩 | 为什么 |
|
||||
|---|---|
|
||||
| **无人值守优先**:机器的活不该让人 24 小时待命 | 这行的买家半夜下单是常态,靠人盯必然漏 |
|
||||
| **正常用户一步都不多加**:每加一道防探测,先问"正常买家会不会被误伤" | 防的是坏人,误伤的是给你钱的人。两者冲突时**先保买家** |
|
||||
| **收钱的数字一律以服务器订单为准**,本地状态只能当兜底 | 踩过:恢复订单时本地状态是空的,按本地算出错的金额去拼付款链接 → 买家少付 → 闸门拦死。**同一行显示两个来源的数,必然自相矛盾** |
|
||||
| **状态话术不许骗人** | 踩过:没付款的单子被兜底文案说成"正在排队"。宁可说"没取到订单信息",也不给假安心 |
|
||||
| **出错要说清是什么、下一步怎么办**,不引导用户猜 | 报错是给人看的,不是给日志看的 |
|
||||
| **同一件事的逻辑只写一处** | "CLI 一套、后台面板一套"必然漂移 —— 出现过面板和命令行生成出两种卡密 |
|
||||
|
||||
### 9.2 我们干活的方法(改这块代码时照着来)
|
||||
|
||||
1. **改一处 → 顺着所有调用点核一遍**。可见性逻辑被好几个入口调用,改了一处、
|
||||
别的入口还传旧参数 → 出现"导航正常、首页却说没有可见内容"这种**看着像站坏了**的现象。
|
||||
2. **同一个东西存在两处时,先问"读取方是按哪个字段找的"**。改写入方不改读取方 =
|
||||
写进去了、读的还是旧的(踩过:换了皮肤文件、但路径字段没跟着改,买家看到"重渲了还是旧图")。
|
||||
3. **前端必须真的在浏览器里点一遍**。有一批 bug 在 API 层**根本测不出来**
|
||||
(页面上某个渲染函数调了不存在的名字 → 每次进第 2 步就抛异常 → 页面看着"就是没反应")。
|
||||
4. **部署完要核对"跑的是不是新代码"**,不是"部署脚本说成功了"。
|
||||
踩过:脚本全程报成功、功能静默缺失 —— 旧进程还活着,计划任务的"运行"不会替换它。
|
||||
5. **自测的每一个负例各用一份新数据**。复用同一份的话,第一条成功就把它消耗了,
|
||||
后面几条测的其实是"已经用过了"—— **全绿,但什么都没测到**。
|
||||
6. **测完必须清场**。测试产生的记录不许留在管理员看得见的列表里。
|
||||
|
||||
### 9.3 我们付过学费的坑(这些是"不要重复踩"清单)
|
||||
|
||||
- **静默失败最贵**:不报错、不崩,就是没效果 —— 比抛异常难查十倍。
|
||||
所以我们宁可让它**响亮地失败**(比如离线就不显示预计时间、宁可说"没取到")。
|
||||
- **显示层会骗人**:订单本身算对了,但界面从另一个来源取数 → 用户看到的是错的。
|
||||
**凡是"从 A 推导出 B"的函数,在别处读 B 之前都要先调一次它**。
|
||||
- **文件重复投递**:渲染机与服务器之间"一张图一次"回传,是因为一次全传会撞体积上限。
|
||||
- **重试要有上限也能收敛**:部分失败必须显式收尾,否则订单会永远停在"渲染中"、被反复重渲。
|
||||
|
||||
### 9.4 我们最想要你评的三件"做法"
|
||||
|
||||
1. **"不验签、改成拿开放接口反查"**这个取舍,你认同吗?(我们手头没有对方的公钥,与其猜算法不如反查)
|
||||
2. **订单状态机在部分失败时怎么收口**(3 张渲出 2 张)—— 我们现在靠"显式收尾",你觉得够不够。
|
||||
3. **这套"单文件纯标准库"的写法**:好处是零依赖零安装、小机器跑得动;
|
||||
代价是路由/校验/序列化全得自己写。**换你,你会不会上框架?** 请直说。
|
||||
|
||||
---
|
||||
|
||||
## 十、边界
|
||||
|
||||
- 这份是**私有交付**,**请勿外传 / 勿镜像 / 勿公开**(含截图、片段)。
|
||||
- 里面是**占位值**,请不要替换成任何真实地址再提交回来。
|
||||
- 有看不懂的先问,别猜着改 —— 猜错了我们这边会静默坏掉。
|
||||
- 你可以自由重构,但**动了接口/数据格式要按第 8 节单独标出来**。
|
||||
@@ -0,0 +1,8 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
# 核对渲染机进程:是不是这次部署之后起来的(光看"在线"不够 —— 旧进程也报在线)
|
||||
$ps = @(Get-CimInstance Win32_Process | Where-Object { $_.CommandLine -like '*ys_worker.py*' })
|
||||
Write-Host "渲染机进程数:$($ps.Count)"
|
||||
foreach ($p in $ps) {
|
||||
$age = [math]::Round(((Get-Date) - $p.CreationDate).TotalMinutes, 1)
|
||||
Write-Host (" PID {0} 启动于 {1} 已运行 {2} 分钟" -f $p.ProcessId, $p.CreationDate, $age)
|
||||
}
|
||||
@@ -0,0 +1,124 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
把渲染机(worker)装到 Windows 宿主机上。
|
||||
链路:本机 → VM(ssh <跳板>) → Windows 宿主(<LOCAL-IP>)
|
||||
|
||||
用法:python3 <WORKER_DIR>/deploy.py
|
||||
前提:宿主那台开着、隧道通(ssh <跳板> 能 echo 出东西)
|
||||
"""
|
||||
import json, os, subprocess, sys, time
|
||||
|
||||
SRC = "<WORKER_DIR>"
|
||||
STAGE = "<TMP_OUT>"
|
||||
HOST_DIR = "<WIN-PATH>"
|
||||
KEY_HOST = "<SSH-KEY>"
|
||||
KEY_VM = "<SSH-KEY>"
|
||||
|
||||
|
||||
def sh(cmd, timeout=180):
|
||||
r = subprocess.run(cmd, shell=True, capture_output=True, text=True, timeout=timeout)
|
||||
return r.returncode, ((r.stdout or "") + (r.stderr or "")).strip()
|
||||
|
||||
|
||||
def step(title, cmd, timeout=180):
|
||||
print("\n=== %s ===" % title)
|
||||
rc, out = sh(cmd, timeout)
|
||||
print(out[-2500:] if out else "(无输出)")
|
||||
return rc, out
|
||||
|
||||
|
||||
def main():
|
||||
# 0) 先确认隧道
|
||||
rc, out = sh("ssh -o ConnectTimeout=10 -o BatchMode=yes <跳板> 'echo vm-ok'", 40)
|
||||
if "vm-ok" not in out:
|
||||
sys.exit("隧道不通:先确认 VM 和宿主机都开着(%s)" % out[:200])
|
||||
|
||||
# 1) 组装 staging
|
||||
os.makedirs(STAGE, exist_ok=True)
|
||||
for f in ("ys_worker.py", "ys_local.py", "local.html", "ys_admin.py",
|
||||
"run_worker.bat", "open_local.bat", "run_admin.bat", "stop_admin.bat",
|
||||
"stop_worker.bat", "show_log.bat", "install_worker.ps1",
|
||||
"pack_archive.bat", "pack_archive.ps1", "chk_worker.ps1"):
|
||||
data = open(os.path.join(SRC, f), "rb").read()
|
||||
if f.endswith(".ps1") and not data.startswith(b"\xef\xbb\xbf"):
|
||||
data = b"\xef\xbb\xbf" + data # BOM:让 PowerShell 正确读中文
|
||||
# ⚠️ 幂等:源文件已带 BOM 就不要再加,加两次 PowerShell 开头会多出乱码字符
|
||||
open(os.path.join(STAGE, f), "wb").write(data)
|
||||
token = open("<DATA_DIR>/worker_token", encoding="utf-8").read().strip()
|
||||
# 开单后台的令牌(金钻电脑上那块面板用)—— 和渲染机 token 是两把,互不通用
|
||||
atok = open("<DATA_DIR>/admin_token", encoding="utf-8").read().strip()
|
||||
with open(os.path.join(STAGE, "config.json"), "w", encoding="utf-8") as f:
|
||||
json.dump({"server": "http<WIN-PATH>", "token": token,
|
||||
"admin_token": atok,
|
||||
# 模板已统一收进「头图\模板\」(2026-09-30)
|
||||
"tpl_root": r"<ARCHIVE_DIR>",
|
||||
# 在线检查 10 分钟一次(金钻 9-30);领单仍 20 秒,别改大
|
||||
"hb_every": 600,
|
||||
"poll": 20,
|
||||
"blender": r"<PROJECT_DIR>"},
|
||||
f, ensure_ascii=False, indent=1)
|
||||
mk = "<MAKE_ORDER_DIR>/make_order.py"
|
||||
open(os.path.join(STAGE, "make_order.py"), "wb").write(open(mk, "rb").read())
|
||||
# 质检代码必须是同一份 —— 从网页那边取,绝不手工复制
|
||||
open(os.path.join(STAGE, "skincheck.js"), "wb").write(
|
||||
open("<SITE_DIR>/skincheck.js", "rb").read())
|
||||
|
||||
sizes = {f: os.path.getsize(os.path.join(STAGE, f)) for f in sorted(os.listdir(STAGE))}
|
||||
print("待传文件:")
|
||||
for k, v in sizes.items():
|
||||
print(" %-22s %6d 字节" % (k, v))
|
||||
|
||||
# 2) 本机 → VM
|
||||
step("本机 → VM", "scp -i %s -P <SSH-PORT> -o StrictHostKeyChecking=accept-new -r %s shopowner@localhos<WIN-PATH>" % (KEY_VM, STAGE))
|
||||
|
||||
# 3) VM 上跑一段脚本,把文件推到宿主并核对(引号地狱 → 用脚本文件)
|
||||
vm_sh = r'''#!/bin/sh
|
||||
set -e
|
||||
rm -rf <TMP_WORK> && mkdir -p <TMP_WORK>
|
||||
cp <TMP_OUT>/* <TMP_WORK>/
|
||||
SSH="ssh -i KEY -o StrictHostKeyChecking=accept-new -o ConnectTimeout=10 user0@<LOCAL-IP>"
|
||||
SCP="scp -i KEY -o StrictHostKeyChecking=accept-new -o ConnectTimeout=10"
|
||||
$SSH "if not exist <WORKER_DIR> mkdir <WORKER_DIR>" || true
|
||||
$SSH "if not exist <TOOLS_DIR> mkdir <TOOLS_DIR>" || true
|
||||
# ⚠️ 以前这里是**写死的文件名清单** —— 结果新加的 pack_archive.* 传不上去,
|
||||
# 本地打印"待传文件"看着传了,宿主上根本没有(2026-09-30 实踩第 3 次"改 A 忘 B")。
|
||||
# 改成自动带上 staging 里除 make_order.py 之外的全部文件。
|
||||
WLIST=""
|
||||
for f in <TMP_WORK>/*; do
|
||||
case "$f" in */make_order.py) continue;; esac
|
||||
WLIST="$WLIST $f"
|
||||
done
|
||||
$SCP $WLIST "user0@<LOCAL-IP>:<WIN-PATH>"
|
||||
$SCP <TMP_WORK>/make_order.py "user0@<LOCAL-IP>:<WIN-PATH>"
|
||||
echo "--- <WORKER_DIR> ---"
|
||||
$SSH "dir <WORKER_DIR>"
|
||||
echo "--- <TOOLS_DIR>\\make_order.py ---"
|
||||
$SSH "dir <TOOLS_DIR>\\make_order.py"
|
||||
'''.replace("KEY", KEY_HOST)
|
||||
open("<TMP_SCRIPT>", "w", newline="\n").write(vm_sh)
|
||||
step("本机 → VM(推送脚本)", "scp -i %s -P <SSH-PORT> <TMP_SCRIPT> shopowner@localhost:<TMP_SCRIPT>" % KEY_VM)
|
||||
step("VM → 宿主 推送", "ssh <跳板> 'sh <TMP_SCRIPT>'", 300)
|
||||
|
||||
# 4) 跑安装脚本
|
||||
step("宿主上执行安装",
|
||||
"ssh <跳板> \"ssh -i %s -o StrictHostKeyChecking=accept-new user0@<LOCAL-IP> "
|
||||
"'powershell -ExecutionPolicy Bypass -File <WIN-PATH>'\"" % KEY_HOST, 300)
|
||||
|
||||
# 5) 服务器侧复核心跳
|
||||
time.sleep(20)
|
||||
step("核对渲染机进程是不是新的",
|
||||
"ssh <跳板> \"ssh -i %s -o StrictHostKeyChecking=accept-new user0@<LOCAL-IP> "
|
||||
"'powershell -NoProfile -ExecutionPolicy Bypass -File <WORKER_DIR>\\chk_worker.ps1'\"" % KEY_HOST, 120)
|
||||
|
||||
rc, out = sh("curl -s http<WIN-PATH>", 30)
|
||||
print("\n=== 服务器看到的渲染机状态 ===")
|
||||
print(out)
|
||||
if '"online":true' in out.replace(" ", ""): # 先去空格再比;之前比的是带空格的串,永远为假
|
||||
print("✅ 渲染机已上线")
|
||||
else:
|
||||
print("⚠️ 还没看到心跳,看宿主 <WORKER_DIR>\\worker.log")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,170 @@
|
||||
# YS render worker installer —— 在 Windows 宿主机上跑(金钻工坊·渲染下单)
|
||||
# 做四件事:找 pythonw → 修好 run_worker.bat → 注册开机自启 → 桌面放开关 → 立刻启动
|
||||
$ErrorActionPreference = 'Continue'
|
||||
$DIR = '<WORKER_DIR>'
|
||||
Write-Host "=== YS 渲染机 安装 ==="
|
||||
|
||||
# 1) 找 pythonw.exe
|
||||
$pw = (Get-Command pythonw.exe -ErrorAction SilentlyContinue).Source
|
||||
if (-not $pw) {
|
||||
$c = Get-ChildItem -Path "$env:LOCALAPPDATA\Programs\Python", "<WIN_DIR>*", "<PROGRAM_DIR>" `
|
||||
-Filter pythonw.exe -Recurse -ErrorAction SilentlyContinue | Select-Object -First 1
|
||||
if ($c) { $pw = $c.FullName }
|
||||
}
|
||||
if (-not $pw) { Write-Host "ERROR: 找不到 pythonw.exe,先把 Python 装上"; exit 1 }
|
||||
Write-Host "pythonw = $pw"
|
||||
|
||||
# 2) 把两个 .bat 里的占位符换成真实路径
|
||||
$bat = Join-Path $DIR 'run_worker.bat'
|
||||
if (Test-Path $bat) {
|
||||
$t = Get-Content $bat -Raw
|
||||
$t = $t -replace '__PYTHONW__', $pw
|
||||
[IO.File]::WriteAllText($bat, $t, [Text.Encoding]::ASCII)
|
||||
Write-Host "run_worker.bat 已修好"
|
||||
} else { Write-Host "ERROR: 缺 run_worker.bat"; exit 1 }
|
||||
|
||||
# 本机开单工具用 python.exe(要留个黑框,崩了能看见)
|
||||
$py = (Get-Command python.exe -ErrorAction SilentlyContinue).Source
|
||||
if (-not $py) { $py = $pw -replace 'pythonw\.exe$', 'python.exe' }
|
||||
$bat2 = Join-Path $DIR 'open_local.bat'
|
||||
if (Test-Path $bat2) {
|
||||
$t2 = Get-Content $bat2 -Raw
|
||||
$t2 = $t2 -replace '__PYTHON__', $py
|
||||
[IO.File]::WriteAllText($bat2, $t2, [Text.Encoding]::ASCII)
|
||||
Write-Host "open_local.bat 已修好 (python=$py)"
|
||||
} else { Write-Host "!! 缺 open_local.bat,本机开单工具没法一键启动" }
|
||||
|
||||
# 开单后台(金钻 2026-09-30:家里电脑上点着用的,局域网 8081)
|
||||
# 用 pythonw(不留黑框);⚠️ 两个占位符都要替,只替一个会留个 __PYTHONW__ 在文件里
|
||||
$bat3 = Join-Path $DIR 'run_admin.bat'
|
||||
if (Test-Path $bat3) {
|
||||
$t3 = Get-Content $bat3 -Raw
|
||||
$t3 = $t3 -replace '__PYTHONW__', $pw
|
||||
$t3 = $t3 -replace '__PYTHON__', $py
|
||||
[IO.File]::WriteAllText($bat3, $t3, [Text.Encoding]::ASCII)
|
||||
Write-Host "run_admin.bat 已修好 (pythonw=$pw)"
|
||||
} else { Write-Host "!! 缺 run_admin.bat,开单后台没法一键启动" }
|
||||
|
||||
# 3) 开机自启(登录时启动,不需要管理员)
|
||||
schtasks /Delete /TN "YS-Render-Worker" /F 2>$null | Out-Null
|
||||
schtasks /Create /TN "YS-Render-Worker" /TR "`"$bat`"" /SC ONLOGON /RL LIMITED /F | Out-Null
|
||||
if ($LASTEXITCODE -eq 0) { Write-Host "已注册开机自启:YS-Render-Worker" }
|
||||
else { Write-Host "!! 注册开机自启失败(可手动跑 run_worker.bat)" }
|
||||
|
||||
# 开单后台也随登录自启(局域网服务,手机同 WiFi 直接开;不需要就删掉这个计划任务)
|
||||
if (Test-Path $bat3) {
|
||||
schtasks /Delete /TN "YS-Admin-Panel" /F 2>$null | Out-Null
|
||||
# ⚠️ 计划任务**直接调 pythonw 且不带 --open** —— 走 bat 的话会带 --open,开机就弹一个网页出来
|
||||
schtasks /Create /TN "YS-Admin-Panel" /TR "`"$pw`" `"$DIR\ys_admin.py`"" /SC ONLOGON /RL LIMITED /F | Out-Null
|
||||
if ($LASTEXITCODE -eq 0) { Write-Host "已注册开机自启:YS-Admin-Panel(开单后台)" }
|
||||
else { Write-Host "!! 开单后台自启注册失败(点开始菜单「开单后台」也能起)" }
|
||||
}
|
||||
|
||||
# 4) 桌面放三个开关
|
||||
$desk = [Environment]::GetFolderPath('Desktop')
|
||||
$sh = New-Object -ComObject WScript.Shell
|
||||
function MkLink([string]$name, [string]$target, [string]$desc) {
|
||||
$p = Join-Path $desk $name
|
||||
$l = $sh.CreateShortcut($p)
|
||||
$l.TargetPath = $target
|
||||
$l.WorkingDirectory = $DIR
|
||||
$l.Description = $desc
|
||||
$l.Save()
|
||||
if (Test-Path $p) { Write-Host "桌面快捷方式:$name" }
|
||||
}
|
||||
# ⚠️ 金钻 2026-09-30:桌面别撒一地 —— 全部进开始菜单「金钻工坊」,桌面只留一个入口。
|
||||
# 以前是往桌面逐个放 5 个快捷方式,桌面就花了。
|
||||
$GROUP = '金钻工坊'
|
||||
$start = Join-Path ([Environment]::GetFolderPath('Programs')) $GROUP
|
||||
New-Item -ItemType Directory -Force -Path $start | Out-Null
|
||||
function MkIn([string]$folder, [string]$name, [string]$target, [string]$desc) {
|
||||
$p = Join-Path $folder $name
|
||||
$l = $sh.CreateShortcut($p)
|
||||
$l.TargetPath = $target
|
||||
$l.WorkingDirectory = $DIR
|
||||
$l.Description = $desc
|
||||
$l.Save()
|
||||
if (Test-Path $p) { Write-Host "快捷方式:$folder\$name" }
|
||||
}
|
||||
$shortcutItems = @(
|
||||
@('本机开单', 'open_local.bat', '平台单:本机出图,不联网、不用卡密'),
|
||||
@('开单后台', 'run_admin.bat', '生成卡密 / 激活订单(局域网,手机同 WiFi 也能开)'),
|
||||
@('开单后台-停止', 'stop_admin.bat', '关掉开单后台'),
|
||||
@('打包留档', 'pack_archive.bat', '把在线订单压成一个 zip,方便整个拖网盘'),
|
||||
@('渲染机-启动', 'run_worker.bat', '启动影塑渲染机'),
|
||||
@('渲染机-停止', 'stop_worker.bat', '停止影塑渲染机'),
|
||||
@('渲染机-看日志', 'show_log.bat', '查看渲染机日志与服务器队列')
|
||||
)
|
||||
foreach ($it in $shortcutItems) {
|
||||
MkIn $start ($it[0] + '.lnk') (Join-Path $DIR $it[1]) $it[2]
|
||||
# 顺手把以前撒在桌面上的清掉(只删苏达建的这几个名字)
|
||||
$dp = Join-Path $desk ($it[0] + '.lnk')
|
||||
if (Test-Path $dp) { Remove-Item $dp -Force }
|
||||
}
|
||||
$dg = Join-Path $desk "$GROUP.lnk"
|
||||
if (Test-Path $dg) { Remove-Item $dg -Force }
|
||||
MkIn $desk "$GROUP.lnk" $start "金钻工坊:本机开单 / 渲染机开关 / 打包留档"
|
||||
|
||||
# 5) 立刻启动
|
||||
# ⚠️ 不能用 Start-Process —— 通过 SSH 起的进程会随会话结束被带走(2026-09-30 实踩:
|
||||
# 安装时显示"已运行",session 一断 worker 就没了,订单干等在队列里没人领)。
|
||||
# 走计划任务启动,由 Task Scheduler 持有,跟 SSH 会话无关。
|
||||
# ⚠️⚠️ 必须先停掉正在跑的旧进程再起新的!
|
||||
# 2026-09-30 实踩:部署脚本从头到尾都"成功",但渲染机进程是早上 09:19 起的,
|
||||
# 跑了一整天旧代码 —— 序号登记、条款留证、看门狗全都没生效,
|
||||
# 而且现象极具迷惑性(能出图、不报错,只是新功能静默缺失)。
|
||||
# 计划任务 /Run 对已在运行的实例不会替换,所以必须显式杀。
|
||||
$old = Get-CimInstance Win32_Process | Where-Object { $_.CommandLine -like '*ys_worker.py*' }
|
||||
if ($old) {
|
||||
foreach ($p in $old) {
|
||||
Write-Host "停掉旧渲染机进程 PID $($p.ProcessId)(启动于 $($p.CreationDate))"
|
||||
Stop-Process -Id $p.ProcessId -Force -ErrorAction SilentlyContinue
|
||||
}
|
||||
Start-Sleep -Seconds 3
|
||||
}
|
||||
schtasks /Run /TN "YS-Render-Worker" 2>$null | Out-Null
|
||||
if ($LASTEXITCODE -ne 0) { Start-Process -FilePath $bat -WindowStyle Hidden }
|
||||
|
||||
# 开单后台:同一套「先杀旧、再起新」——不然跑着的还是昨天的代码(这个坑在渲染机上踩过)
|
||||
if (Test-Path $bat3) {
|
||||
$oldA = Get-CimInstance Win32_Process | Where-Object { $_.CommandLine -like '*ys_admin.py*' }
|
||||
foreach ($p in $oldA) {
|
||||
Write-Host "停掉旧开单后台进程 PID $($p.ProcessId)(启动于 $($p.CreationDate))"
|
||||
Stop-Process -Id $p.ProcessId -Force -ErrorAction SilentlyContinue
|
||||
}
|
||||
if ($oldA) { Start-Sleep -Seconds 2 }
|
||||
schtasks /Run /TN "YS-Admin-Panel" 2>$null | Out-Null
|
||||
if ($LASTEXITCODE -ne 0) { Start-Process -FilePath $bat3 -WindowStyle Hidden }
|
||||
# ⚠️ 进程要几秒才出现、接口要十几秒才通 —— 检查**放在这个重试循环里**,
|
||||
# 放在循环外面会误报「没起来 / 接口不通」(2026-09-30 一晚踩了三次)
|
||||
$pa = $null
|
||||
for ($i = 1; $i -le 6; $i++) {
|
||||
Start-Sleep -Seconds 3
|
||||
$pa = Get-CimInstance Win32_Process | Where-Object { $_.CommandLine -like '*ys_admin.py*' }
|
||||
if ($pa) {
|
||||
try {
|
||||
# ⚠️ 2026-10-01 起面板有 PIN 锁:自检只能打免锁的 /api/health(state 会 401 → 自检误报"没起来")
|
||||
$code = (Invoke-WebRequest -UseBasicParsing 'htt<WIN-PATH>' -TimeoutSec 25).Content
|
||||
Write-Host "开单后台:已运行 (PID $($pa.ProcessId -join ','))(局域网 htt<WIN-PATH>"
|
||||
Write-Host "开单后台自检:$($code.Substring(0, [Math]::Min(200, $code.Length)))"
|
||||
break
|
||||
} catch { }
|
||||
}
|
||||
}
|
||||
if (-not $pa) { Write-Host "!! 开单后台没起来,看 <WORKER_DIR>\admin.log" }
|
||||
}
|
||||
Start-Sleep -Seconds 10
|
||||
|
||||
# 6) 自检:进程 + 服务器心跳
|
||||
$proc = Get-CimInstance Win32_Process | Where-Object { $_.CommandLine -like '*ys_worker.py*' }
|
||||
if ($proc) { Write-Host "进程:已运行 (PID $($proc.ProcessId -join ','))" }
|
||||
else { Write-Host "!! 进程没起来,去 <WORKER_DIR>\worker.log 看原因" }
|
||||
try {
|
||||
$s = (Invoke-WebRequest -UseBasicParsing 'http<WIN-PATH>' -TimeoutSec 20).Content
|
||||
Write-Host "服务器状态:$s"
|
||||
} catch { Write-Host "!! 连不上服务器:$_" }
|
||||
if (Test-Path (Join-Path $DIR 'worker.log')) {
|
||||
Write-Host "--- worker.log 末尾 ---"
|
||||
Get-Content (Join-Path $DIR 'worker.log') -Tail 15
|
||||
}
|
||||
Write-Host "=== 安装完成 ==="
|
||||
@@ -0,0 +1,409 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width,initial-scale=1">
|
||||
<title>本机开单 · 金钻工坊(平台单)</title>
|
||||
<style>
|
||||
:root{
|
||||
--bg:#08090a; --surface:rgba(255,255,255,.02); --line:rgba(255,255,255,.08); --line-soft:rgba(255,255,255,.05);
|
||||
--txt:#f7f8f8; --txt-2:#d0d6e0; --txt-3:#8a8f98; --txt-4:#62666d;
|
||||
--acc:#3ecf8e; --acc-hi:#4ade9f; --acc-hover:#37b87f;
|
||||
--ok:#3ecf8e; --ok-t:#5fd8a2; --warn:#d29922; --warn-t:#e0b355; --bad:#da3633; --bad-t:#f08a7c;
|
||||
}
|
||||
|
||||
/* ↓ 统一动效 token(金钻系四界面同值;本页跑在家里电脑上,引不到 /assets/tokens.css,
|
||||
照 tokens.css 复制同一份值 —— 改值要两边一起改) */
|
||||
:root{
|
||||
--ease-out:cubic-bezier(.23,1,.32,1); --ease-in-out:cubic-bezier(.77,0,.175,1);
|
||||
--d-press:100ms; --d-hover:150ms; --d-pop:200ms; --d-modal:240ms; --d-exit:180ms;
|
||||
}
|
||||
*{box-sizing:border-box}
|
||||
body{margin:0;background:var(--bg);color:var(--txt-2);position:relative;padding:0 0 60px;
|
||||
font:15px/1.7 'OPPO Sans',system-ui,-apple-system,'PingFang SC','Microsoft YaHei',sans-serif;
|
||||
-webkit-font-smoothing:antialiased}
|
||||
body::before{content:"";position:fixed;inset:0 0 auto 0;height:40vh;pointer-events:none;
|
||||
background:radial-gradient(70% 100% at 50% 0%,rgba(62,207,142,.05),transparent 72%)}
|
||||
.wrap{max-width:860px;margin:0 auto;padding:0 20px;position:relative;z-index:1}
|
||||
header{border-bottom:1px solid var(--line-soft);background:rgba(8,9,10,.86);position:sticky;top:0;z-index:9;
|
||||
backdrop-filter:blur(12px)}
|
||||
.hd{display:flex;align-items:center;gap:12px;padding:15px 0 13px;flex-wrap:wrap}
|
||||
h1{font-size:16px;margin:0;font-weight:700;color:var(--txt);letter-spacing:-.2px}
|
||||
.hd .sub{font-size:12px;color:var(--txt-4)}
|
||||
.badge{margin-left:auto;font-size:12px;padding:4px 11px;border:1px solid var(--line-soft);
|
||||
border-radius:9999px;color:var(--txt-3);white-space:nowrap}
|
||||
.card{background:var(--surface);border:1px solid var(--line-soft);border-radius:8px;padding:22px;margin:16px 0}
|
||||
h2{font-size:16px;margin:0 0 4px;font-weight:700;color:var(--txt)}
|
||||
.hint{font-size:13px;color:var(--txt-4);margin:5px 0 18px;line-height:1.8}
|
||||
.drop{border:1px dashed rgba(255,255,255,.14);border-radius:8px;padding:32px 18px;text-align:center;
|
||||
cursor:pointer;transition:border-color var(--d-pop) var(--ease-out),background-color var(--d-pop) var(--ease-out)}
|
||||
.drop:hover,.drop.over{border-color:rgba(62,207,142,.55);background:rgba(62,207,142,.05)}
|
||||
.drop .big{font-size:14.5px;font-weight:700;color:var(--txt-2);margin-bottom:5px}
|
||||
.drop .small{font-size:12.5px;color:var(--txt-4)}
|
||||
.split{display:grid;gap:20px}
|
||||
@media(min-width:680px){.split{grid-template-columns:200px 1fr;align-items:start}}
|
||||
.preview{border:1px solid var(--line-soft);border-radius:8px;padding:12px;text-align:center}
|
||||
.preview canvas{width:100%;max-width:176px;image-rendering:pixelated;border-radius:4px;
|
||||
background:linear-gradient(45deg,#141618 25%,transparent 25%,transparent 75%,#141618 75%),
|
||||
linear-gradient(45deg,#141618 25%,#0d0f10 25%,#0d0f10 75%,#141618 75%);
|
||||
background-size:11px 11px;background-position:0 0,5.5px 5.5px}
|
||||
.preview .fn{font-size:11.5px;color:var(--txt-4);margin-top:10px;word-break:break-all}
|
||||
.item{display:flex;gap:12px;padding:12px 14px;border-radius:6px;font-size:13.5px;background:rgba(255,255,255,.015);margin-bottom:8px}
|
||||
.item.warn{background:rgba(210,153,34,.055)}
|
||||
.item.bad{background:rgba(218,54,51,.055)}
|
||||
.tag{display:inline-flex;align-items:center;gap:7px;font-size:12px;color:var(--txt-4);flex:none;margin-top:1px;white-space:nowrap}
|
||||
.tag::before{content:"";width:6px;height:6px;border-radius:50%;background:currentColor}
|
||||
.item.ok .tag::before{background:var(--ok)}
|
||||
.item.warn .tag::before{background:var(--warn)}
|
||||
.item.bad .tag::before{background:var(--bad)}
|
||||
.bd{flex:1;min-width:0}
|
||||
.t{font-weight:700;color:var(--txt-2)}
|
||||
.d{font-size:12.5px;color:var(--txt-4);margin-top:5px;line-height:1.75}
|
||||
.tpls{display:grid;gap:12px;grid-template-columns:repeat(auto-fill,minmax(150px,1fr))}
|
||||
.tpl{border:1px solid var(--line);border-radius:8px;cursor:pointer;position:relative;overflow:hidden;
|
||||
background:rgba(255,255,255,.015);transition:.15s}
|
||||
.tpl:hover{border-color:rgba(255,255,255,.16);background:rgba(255,255,255,.03)}
|
||||
.tpl.sel{border-color:var(--acc);box-shadow:inset 0 0 0 1px var(--acc)}
|
||||
.tpl .thumb{aspect-ratio:1/1;display:flex;align-items:center;justify-content:center;background:#0d0f10;
|
||||
border-bottom:1px solid var(--line-soft);position:relative}
|
||||
.tpl .thumb::before{content:"";position:absolute;top:0;left:0;right:0;height:2px;background:var(--tone,#8a8f98);opacity:.5}
|
||||
.tpl .thumb svg{color:var(--tone,#8a8f98)}
|
||||
.tpl .meta{padding:11px 12px}
|
||||
.tpl .n{font-size:13px;font-weight:700;color:var(--txt-2)}
|
||||
.tpl .s{font-size:11.5px;color:var(--txt-4);margin-top:3px}
|
||||
.tpl .pick{position:absolute;top:9px;right:9px;width:18px;height:18px;border-radius:4px;font-size:11px;
|
||||
border:1px solid rgba(255,255,255,.2);background:rgba(8,9,10,.7);display:flex;align-items:center;
|
||||
justify-content:center;color:transparent}
|
||||
.tpl.sel .pick{background:var(--acc);border-color:var(--acc);color:#07150e}
|
||||
input.t{width:100%;background:rgba(255,255,255,.035);border:1px solid rgba(255,255,255,.13);
|
||||
border-radius:6px;color:var(--txt);padding:12px 14px;font:13.5px/1.6 inherit}
|
||||
input.t:focus{outline:none;border-color:var(--acc-hi);background:rgba(62,207,142,.05)}
|
||||
input.t::placeholder{color:#7c8290}
|
||||
.btns{display:flex;gap:10px;margin-top:18px;flex-wrap:wrap}
|
||||
button{font:inherit;border-radius:6px;padding:11px 18px;border:1px solid var(--line);
|
||||
background-color:rgba(255,255,255,.02);color:var(--txt-2);cursor:pointer;font-size:13.5px;font-weight:700;
|
||||
transition:border-color var(--d-hover) var(--ease-out),background-color var(--d-hover) var(--ease-out),
|
||||
color var(--d-hover) var(--ease-out),transform var(--d-press) var(--ease-out)}
|
||||
button:active:not(:disabled){transform:scale(.985)}
|
||||
button:hover:not(:disabled){background:rgba(255,255,255,.05);border-color:rgba(255,255,255,.14);color:var(--txt)}
|
||||
button.pri{background:var(--acc);border-color:var(--acc);color:#07150e;flex:1;min-width:180px}
|
||||
button.pri:hover:not(:disabled){background:var(--acc-hover);border-color:var(--acc-hover)}
|
||||
button:disabled{opacity:.32;cursor:not-allowed}
|
||||
.warnbar{padding:13px 15px;border-radius:6px;font-size:13px;background:rgba(210,153,34,.08);
|
||||
border:1px solid rgba(210,153,34,.24);color:var(--txt-3);margin-bottom:14px;line-height:1.75}
|
||||
.errbar{padding:13px 15px;border-radius:6px;font-size:13px;background:rgba(218,54,51,.08);
|
||||
border:1px solid rgba(218,54,51,.24);color:var(--txt-3);margin:14px 0;line-height:1.75;white-space:pre-wrap}
|
||||
.bar{height:3px;border-radius:2px;background:rgba(255,255,255,.07);overflow:hidden;margin:16px 0 10px}
|
||||
.bar i{display:block;height:100%;background:var(--acc);width:0;transition:width .4s var(--ease-out)}
|
||||
.res{display:grid;gap:14px;grid-template-columns:repeat(auto-fill,minmax(190px,1fr));margin-top:6px}
|
||||
.res .one{border:1px solid var(--line);border-radius:8px;overflow:hidden}
|
||||
.res img{width:100%;display:block;background:#0d0f10}
|
||||
.res .cap{padding:10px 12px;font-size:12px;color:var(--txt-4)}
|
||||
.res .cap b{color:var(--txt-2);font-size:13px;display:block;margin-bottom:3px}
|
||||
.res .dls{margin-top:7px;line-height:2}
|
||||
.res a{color:var(--acc-hi);text-decoration:none;font-size:12.5px}
|
||||
footer{text-align:center;font-size:11.5px;color:var(--txt-4);padding:34px 20px 0;line-height:2}
|
||||
.toast{position:fixed;left:50%;bottom:30px;transform:translate(-50%,12px);opacity:0;z-index:90;
|
||||
background:#16181b;border:1px solid var(--line);border-radius:6px;padding:11px 17px;font-size:13.5px;
|
||||
color:var(--txt-2);pointer-events:none;max-width:88vw;
|
||||
/* 2026-10-02 统一:toast 180ms --ease-out(原 .2s 内建 ease) */
|
||||
transition:opacity var(--d-exit) var(--ease-out),transform var(--d-exit) var(--ease-out)}
|
||||
.toast.show{opacity:1;transform:translate(-50%,0)}
|
||||
|
||||
/* ---------- 动效降级:prefers-reduced-motion(2026-10-02 补,原来完全没有)---------- */
|
||||
@media (prefers-reduced-motion:reduce){
|
||||
*{animation-duration:1ms!important;animation-iteration-count:1!important}
|
||||
.toast,.toast.show{transform:translate(-50%,0)}
|
||||
button:active:not(:disabled){transform:none}
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<header><div class="wrap hd">
|
||||
<h1>本机开单</h1>
|
||||
<span class="sub">平台单 · 只在这台电脑上能打开</span>
|
||||
<span class="badge" id="health">体检中…</span>
|
||||
</div></header>
|
||||
|
||||
<div class="wrap">
|
||||
<div id="syswarn"></div>
|
||||
|
||||
<div class="card">
|
||||
<h2>1 · 皮肤</h2>
|
||||
<p class="hint">把买家发的皮肤图拖进来,或点一下选。质检规则和网页版是同一份代码。</p>
|
||||
<details style="margin:10px 0 0;font-size:12.5px;color:var(--dim)">
|
||||
<summary style="cursor:pointer">发给买家的说明(可直接复制)</summary>
|
||||
<pre style="white-space:pre-wrap;font:12px/1.7 inherit;margin:9px 0 0;padding:10px 11px;
|
||||
border-left:2px solid var(--line);background:rgba(255,255,255,.02);border-radius:0 6px 6px 0">只提供渲染服务,不对皮肤内容与渲染结果作合规担保。
|
||||
皮肤由买家自行提供,其内容合法性由提供者负责;
|
||||
因皮肤内容(含夹带数据、隐藏信息、违规图案)产生的任何后果,由提供者承担。
|
||||
模板质量问题由金钻负责维护修复,非质量问题不予重做。
|
||||
一经发现违法内容,将立即停止服务、删除相关文件、拒绝后续接单。</pre>
|
||||
</details>
|
||||
<div class="drop" id="drop">
|
||||
<svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.6"
|
||||
stroke-linecap="round" stroke-linejoin="round" style="display:block;margin:0 auto 12px;color:var(--txt-3)">
|
||||
<path d="M12 15V4"/><path d="M8 8l4-4 4 4"/><path d="M4 15v3a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-3"/></svg>
|
||||
<div class="big">点击选择皮肤文件</div>
|
||||
<div class="small">或把 .png 拖到这里 / 直接粘贴图片</div>
|
||||
</div>
|
||||
<input type="file" id="file" accept="image/png" hidden>
|
||||
<div id="pvwrap" style="display:none;margin-top:18px">
|
||||
<div class="split">
|
||||
<div class="preview"><canvas id="pv" width="64" height="64"></canvas><div class="fn" id="pvName"></div></div>
|
||||
<div id="report"></div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="card" id="card2">
|
||||
<h2>2 · 模板</h2>
|
||||
<p class="hint">勾几个就出几张。一次渲一张,不会把机器顶满。</p>
|
||||
<div class="tpls" id="tpls"></div>
|
||||
<div style="margin-top:18px">
|
||||
<div class="hint" style="margin:0 0 9px">出图分辨率 —— 越高越慢。
|
||||
<b style="color:var(--txt-3)">默认 1000 是网易我的世界头图的标准分辨率</b>,文件名不带数字;
|
||||
换别的分辨率才写进文件名(如 飞跃樱花林2048.png)</div>
|
||||
<div class="seg" id="resSeg"></div>
|
||||
</div>
|
||||
<div style="margin-top:16px">
|
||||
<input class="t" id="note" placeholder="买家备注(选填,会记进留档,比如闲鱼订单号 / 昵称)">
|
||||
</div>
|
||||
<div class="btns">
|
||||
<button class="pri" id="go" disabled>开始渲染</button>
|
||||
<button class="ghost" id="clear">清空</button>
|
||||
</div>
|
||||
<div id="progWrap" style="display:none">
|
||||
<div class="bar"><i id="bar"></i></div>
|
||||
<div class="hint" id="progTxt" style="margin:0"></div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="card" id="card3" style="display:none">
|
||||
<h2>3 · 出图</h2>
|
||||
<p class="hint" id="resHint"></p>
|
||||
<p class="hint" style="margin-top:-6px">每张模板出<b style="color:var(--txt-3)">两张</b>:标准压缩(发预览/常规交付)+ 无压缩 16bit(客户要高清时给)。两张都发过去。</p>
|
||||
<div class="res" id="res"></div>
|
||||
<div class="btns">
|
||||
<button id="open">打开留档文件夹</button>
|
||||
<button class="ghost" id="again">再开一单</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<footer>
|
||||
本工具只监听 localhost · 不联网 · 不上传 · 不需要兑换码<br>
|
||||
所有文件都留在你自己电脑上 · <a href="#" id="quit" style="color:var(--txt-4)">退出工具</a>
|
||||
</footer>
|
||||
</div>
|
||||
<div class="toast" id="toast"></div>
|
||||
|
||||
<script src="skincheck.js"></script>
|
||||
<script>
|
||||
const $=(s,r=document)=>r.querySelector(s), $$=(s,r=document)=>Array.from(r.querySelectorAll(s));
|
||||
function toast(m){const t=$('#toast');t.textContent=m;t.classList.add('show');
|
||||
clearTimeout(t._h);t._h=setTimeout(()=>t.classList.remove('show'),2600);}
|
||||
|
||||
const TEMPLATES=[
|
||||
{k:'stand', n:'站立正反', s:'正面站立 · 干净背景', c:'#8a8f98'},
|
||||
{k:'standb', n:'站立正反(虚化)', s:'同款 + 景深虚化', c:'#6f7680'},
|
||||
{k:'wheat', n:'麦田萤火', s:'麦田 · 暖光 · 萤火', c:'#a8863a'},
|
||||
{k:'beach', n:'海边自拍', s:'海面 · 天光', c:'#4a7fa5'},
|
||||
{k:'boom', n:'不看爆炸', s:'身后爆炸 · 不回头', c:'#a2563f'},
|
||||
{k:'sakura', n:'飞跃樱花林', s:'樱花 · 动态', c:'#b07a92'},
|
||||
{k:'airship', n:'空艇巡游', s:'飞空艇 · 巡航', c:'#5e7f8f'}
|
||||
];
|
||||
const S={skin:null,fileName:'',analysis:null,report:null,sel:[],job:null,timer:null,res:1000};
|
||||
|
||||
/* 分辨率:文件名就是它。耗时按像素数粗估(1000² ≈ 40 秒 GPU 打底) */
|
||||
const RES=[{v:1000,t:'网易头图标准 · 约 40 秒'},
|
||||
{v:1024,t:'约 45 秒'},
|
||||
{v:2048,t:'约 2.5 分钟'},
|
||||
{v:4096,t:'约 10 分钟'}];
|
||||
RES.forEach(r=>{
|
||||
const lb=document.createElement('label');
|
||||
lb.innerHTML=r.v+'<small>'+r.t+'</small>';
|
||||
if(r.v===S.res) lb.classList.add('sel');
|
||||
lb.onclick=()=>{ S.res=r.v;
|
||||
document.querySelectorAll('#resSeg label').forEach(x=>x.classList.remove('sel'));
|
||||
lb.classList.add('sel'); };
|
||||
$('#resSeg').appendChild(lb);
|
||||
});
|
||||
|
||||
/* ---------- 渲染模板卡片 ---------- */
|
||||
TEMPLATES.forEach(t=>{
|
||||
const el=document.createElement('div');
|
||||
el.className='tpl'; el.dataset.k=t.k; el.style.setProperty('--tone',t.c);
|
||||
el.innerHTML='<div class="thumb"><div class="ph">'
|
||||
+'<svg width="40" height="40" viewBox="0 0 24 24" fill="none" stroke="currentColor"'
|
||||
+' stroke-width="1.1" stroke-linejoin="round" opacity=".42"><path d="M12 2.6 21 7.3v9.4L12 21.4 3 16.7V7.3z"/>'
|
||||
+'<path d="M3 7.3l9 4.7 9-4.7M12 12v9.4"/></svg></div></div>'
|
||||
+'<div class="meta"><div class="n"></div><div class="s"></div></div><div class="pick">✓</div>';
|
||||
el.querySelector('.n').textContent=t.n; el.querySelector('.s').textContent=t.s;
|
||||
el.onclick=()=>{
|
||||
const i=S.sel.indexOf(t.k);
|
||||
if(i>=0) S.sel.splice(i,1); else { if(S.sel.length>=10) return toast('一次最多 10 张'); S.sel.push(t.k); }
|
||||
el.classList.toggle('sel'); syncGo();
|
||||
};
|
||||
$('#tpls').appendChild(el);
|
||||
});
|
||||
|
||||
/* ---------- 皮肤上传 + 质检(复用 skincheck.js) ---------- */
|
||||
const drop=$('#drop'), fileIn=$('#file');
|
||||
drop.onclick=()=>fileIn.click();
|
||||
fileIn.onchange=e=>{ if(e.target.files[0]) loadFile(e.target.files[0]); };
|
||||
['dragenter','dragover'].forEach(ev=>drop.addEventListener(ev,e=>{e.preventDefault();drop.classList.add('over');}));
|
||||
['dragleave','drop'].forEach(ev=>drop.addEventListener(ev,e=>{e.preventDefault();drop.classList.remove('over');}));
|
||||
drop.addEventListener('drop',e=>{ const f=e.dataTransfer.files[0]; if(f) loadFile(f); });
|
||||
window.addEventListener('paste',e=>{
|
||||
for(const it of (e.clipboardData||{}).items||[]){
|
||||
if(it.type.startsWith('image/')){ const f=it.getAsFile(); if(f) return loadFile(f); }
|
||||
}
|
||||
});
|
||||
|
||||
function loadFile(f){
|
||||
if(!/png$/i.test(f.name) && f.type!=='image/png') return toast('只支持 .png 皮肤文件');
|
||||
/* PNG 结构核验 —— 和网页那份是同一个 checkPngBytes(skincheck.js),防夹带 */
|
||||
const rb=new FileReader();
|
||||
rb.onload=()=>{
|
||||
let st; try{ st=checkPngBytes(new Uint8Array(rb.result)); }catch(e){ st={ok:true}; }
|
||||
if(st && st.ok===false) return toast('这张图没通过安全核验:'+st.reason);
|
||||
if(st && st.notes && st.notes.length) toast('提示:'+st.notes.join(';')+'(不影响出图)');
|
||||
const fr=new FileReader();
|
||||
fr.onload=()=>{ const im=new Image();
|
||||
im.onload=()=>runCheck(im,f.name,im.width,im.height);
|
||||
im.onerror=()=>toast('这张图读不出来,换一张试试');
|
||||
im.src=fr.result; };
|
||||
fr.readAsDataURL(f);
|
||||
};
|
||||
rb.readAsArrayBuffer(f);
|
||||
}
|
||||
|
||||
function runCheck(img,name,w,h){
|
||||
const a=analyze(img,w,h);
|
||||
const rep=buildReport(a);
|
||||
S.skin=img; S.fileName=name; S.analysis=a; S.report=rep;
|
||||
|
||||
const c=$('#pv'); c.width=64; c.height=64;
|
||||
const g=c.getContext('2d'); g.imageSmoothingEnabled=false;
|
||||
g.clearRect(0,0,64,64); g.drawImage(img,0,0,64,64);
|
||||
$('#pvName').textContent=name+' ('+a.origW+'×'+a.origH+')';
|
||||
$('#pvwrap').style.display='';
|
||||
|
||||
const box=$('#report'); box.innerHTML='';
|
||||
rep.items.forEach(it=>{
|
||||
const d=document.createElement('div'); d.className='item '+it.lv;
|
||||
const tg=document.createElement('span'); tg.className='tag'; tg.textContent=it.tag;
|
||||
const bd=document.createElement('div'); bd.className='bd';
|
||||
const t=document.createElement('div'); t.className='t'; t.textContent=it.t;
|
||||
const dd=document.createElement('div'); dd.className='d'; dd.textContent=it.d;
|
||||
bd.appendChild(t); bd.appendChild(dd); d.appendChild(tg); d.appendChild(bd);
|
||||
box.appendChild(d);
|
||||
});
|
||||
if(rep.hasBad){
|
||||
const d=document.createElement('div'); d.className='item bad';
|
||||
d.innerHTML='<span class="tag">不通过</span><div class="bd"><div class="t">这张皮肤不能直接渲</div>'
|
||||
+'<div class="d">上面标了不通过的问题得先解决。请买家换一张标准皮肤。</div></div>';
|
||||
box.appendChild(d);
|
||||
}
|
||||
syncGo();
|
||||
}
|
||||
|
||||
/* ---------- 提交 ---------- */
|
||||
function tplName(k){ const t=TEMPLATES.find(x=>x.k===k); return t?t.n:k; }
|
||||
function syncGo(){ $('#go').disabled = !(S.skin && S.sel.length && !(S.report&&S.report.hasBad)); }
|
||||
|
||||
$('#go').onclick=async()=>{
|
||||
if(!S.skin) return toast('先选皮肤');
|
||||
if(!S.sel.length) return toast('先勾模板');
|
||||
if(S.report&&S.report.hasBad) return toast('质检不通过,不能提交');
|
||||
$('#go').disabled=true;
|
||||
$('#progWrap').style.display=''; $('#card3').style.display='none';
|
||||
// 皮肤转 base64 送本机接口
|
||||
const c=document.createElement('canvas');
|
||||
c.width=S.analysis.origW; c.height=S.analysis.origH;
|
||||
const g=c.getContext('2d'); g.imageSmoothingEnabled=false;
|
||||
g.drawImage(S.skin,0,0,S.analysis.origW,S.analysis.origH);
|
||||
const data=c.toDataURL('image/png');
|
||||
const st=await (await fetch('/api/render',{method:'POST',headers:{'Content-Type':'application/json'},
|
||||
body:JSON.stringify({skin:data,fileName:S.fileName,templates:S.sel,res:S.res,
|
||||
arm:(S.analysis.arm&&S.analysis.arm.model)||'',note:$('#note').value.trim()})})).json();
|
||||
if(!st.ok){ $('#go').disabled=false; $('#progWrap').style.display='none'; return toast(st.error||'提交失败'); }
|
||||
S.job=st.job; poll();
|
||||
};
|
||||
|
||||
async function poll(){
|
||||
const j=await (await fetch('/api/job/'+S.job)).json();
|
||||
const pct=Math.round(((j.current-1)/j.total)*100);
|
||||
$('#bar').style.width=Math.max(pct,j.state==='done'?100:4)+'%';
|
||||
const ahead = Math.max((j.queue_pos||1) - 1, 0);
|
||||
$('#progTxt').textContent =
|
||||
j.state==='queued' ? (ahead>0 ? ('排队中 · 前面还有 '+ahead+' 单(一张一张来,不并行)')
|
||||
: '马上开始…')
|
||||
: j.state==='running' ? ('正在渲染第 '+j.current+' / '+j.total+' 张 · '+(j.res||1000)+'px'
|
||||
+'(每张出标准+无压缩两张)')
|
||||
: j.state==='done' ? '全部完成' : '出错了';
|
||||
if(j.state==='running'||j.state==='queued'){ S.timer=setTimeout(poll,2000); return; }
|
||||
clearTimeout(S.timer);
|
||||
$('#go').disabled=false;
|
||||
if(j.state==='error' && !j.results.length){
|
||||
$('#card3').style.display=''; $('#resHint').textContent='';
|
||||
$('#res').innerHTML='<div class="errbar">'+(j.error||'渲染失败')+'</div>'; return;
|
||||
}
|
||||
$('#card3').style.display='';
|
||||
$('#resHint').textContent='共 '+j.results.length+' 张'+(j.errors&&j.errors.length?('(有 '+j.errors.length+' 张失败)'):'');
|
||||
const box=$('#res'); box.innerHTML='';
|
||||
// 按序号分组:一个模板 = 一张卡片,里面挂【标准压缩】+【无压缩 16bit】两个下载
|
||||
const groups=[];
|
||||
j.results.forEach((r,i)=>{ let g=groups.find(x=>x.seq===r.seq);
|
||||
if(!g){ g={seq:r.seq,tpl:r.tpl,sec:r.sec,tplName:tplName(r.tpl),items:[]}; groups.push(g); }
|
||||
g.items.push({i:i,r:r}); });
|
||||
groups.forEach(g=>{
|
||||
const d=document.createElement('div'); d.className='one';
|
||||
d.innerHTML='<img src="/api/file/'+S.job+'/'+g.items[0].i+'?t='+Date.now()+'" alt="">'
|
||||
+'<div class="cap"><b></b><span></span><div class="dls"></div></div>';
|
||||
d.querySelector('b').textContent=g.tplName||g.tpl;
|
||||
d.querySelector('span').textContent='序号 '+g.seq+' · '+(g.items[0].r.res||1000)+'px · 渲染 '+g.sec+' 秒';
|
||||
const dl=d.querySelector('.dls');
|
||||
g.items.forEach(it=>{
|
||||
const a=document.createElement('a');
|
||||
a.href='/api/file/'+S.job+'/'+it.i; a.setAttribute('download',it.r.name);
|
||||
a.textContent='↓ '+it.r.kind; dl.appendChild(a); dl.appendChild(document.createTextNode(' '));
|
||||
});
|
||||
box.appendChild(d);
|
||||
});
|
||||
if(j.errors&&j.errors.length){
|
||||
const e=document.createElement('div'); e.className='errbar'; e.textContent='失败:'+j.errors.join('\n');
|
||||
box.appendChild(e);
|
||||
}
|
||||
S.job=j.id; toast('出图完成');
|
||||
}
|
||||
|
||||
$('#quit').onclick=async e=>{ e.preventDefault();
|
||||
if(!confirm('关闭本机开单工具?(渲染机不受影响,还会继续接网页的单)')) return;
|
||||
await fetch('/api/quit',{method:'POST'}); document.body.innerHTML='<div class="wrap" style="padding:80px 20px;text-align:center;color:var(--txt-4)">工具已关闭,可以关掉这个页面了。</div>';
|
||||
};
|
||||
$('#open').onclick=async()=>{
|
||||
const r=await (await fetch('/api/openfolder',{method:'POST',headers:{'Content-Type':'application/json'},
|
||||
body:JSON.stringify({job:S.job})})).json();
|
||||
toast(r.ok?'已打开文件夹':(r.error||'打不开'));
|
||||
};
|
||||
$('#again').onclick=()=>{ S.sel=[]; $$('#tpls .tpl').forEach(e=>e.classList.remove('sel'));
|
||||
$('#note').value=''; $('#card3').style.display='none'; $('#progWrap').style.display='none'; syncGo(); };
|
||||
|
||||
/* ---------- 体检 ---------- */
|
||||
(async()=>{
|
||||
const a=await (await fetch('/api/status')).json();
|
||||
const bad=[];
|
||||
if(!a.blender_ok) bad.push('没找到 blender.exe —— 请在 config.json 里填 blender 路径');
|
||||
if(!a.make_order_ok) bad.push('没找到渲染脚本 make_order.py('+a.make_order+')');
|
||||
if(a.missing.length) bad.push('缺 '+a.missing.length+' 个模板文件:'+a.missing.join('、'));
|
||||
$('#health').textContent = a.blender_ok && !a.missing.length && a.make_order_ok ? '就绪' : '有问题';
|
||||
if(bad.length){
|
||||
const w=document.createElement('div'); w.className='warnbar';
|
||||
w.innerHTML='<b>先看这里:</b><br>'+bad.join('<br>');
|
||||
$('#syswarn').appendChild(w);
|
||||
}
|
||||
})();
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,651 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
商单渲染流程自动化(宿主 Windows 用)—— 跑起来 0 token
|
||||
|
||||
金钻 2026-09-19 原话:
|
||||
「如果方便的话可以直接写个脚本,到时候如果不需要修改的话,直接按流程,
|
||||
复制所需工程到商单文件夹往后补一个新的编号。皮肤也放进去。
|
||||
然后根据皮肤粗细臂去选择对应集合,渲染出图」
|
||||
|
||||
一条命令完成:
|
||||
1. 成品文件夹用成品名(`飞跃樱花林` / `飞跃樱花林1080`),重名自动加 -2
|
||||
2. 新建成品文件夹;工程复制到**临时目录**(原文件不动,渲完就删)
|
||||
3. 皮肤先放进成品文件夹
|
||||
4. 自动判定皮肤是【粗臂 classic 4px】还是【细臂 slim 3px】
|
||||
5. 按判定切换场景里的 粗臂 / 细臂 集合(view layer exclude)
|
||||
6. 换皮肤贴图(pack 打包)
|
||||
7. 渲染出图 → 017\\飞跃樱花林.png + 017\\飞跃樱花林无压缩版.png
|
||||
(默认 1000 不带数字;换分辨率才带,如 飞跃樱花林1080.png。越高越慢)
|
||||
8. 写 _CHANGES.md 与 _make_order.log
|
||||
|
||||
用法:
|
||||
blender.exe -b --factory-startup --python make_order.py -- ^
|
||||
--template "<ARCHIVE_DIR>" ^
|
||||
--skin "<WIN-PATH>" ^
|
||||
--orders-dir "<ARCHIVE_DIR>" ^
|
||||
[--block-texture "<WIN-PATH>"] [--num 017] [--out-name 麦田萤火] ^
|
||||
[--res 2048] [--out-dir "...\\商单\\麦田萤火"] [--keep-blend] ^
|
||||
[--no-uncompressed] [--no-render] [--dry-run]
|
||||
|
||||
要点(踩过的坑,别改回去):
|
||||
* 必须 `-b --factory-startup` —— 宿主 Blender 装了 MMD 系 addon,不 factory-startup
|
||||
时会重复注册崩(ValueError: register_class(...): already registered)。
|
||||
* 但 factory-startup 会丢掉用户的 Cycles GPU 偏好 → 掉回 CPU,**慢 10 倍**
|
||||
(实测 1000×1000 / 180 samples:GPU 37.4s vs CPU 378.9s)。
|
||||
所以脚本里 setup_render_device() 显式切 GPU,别删。
|
||||
* 判臂型用 bpy.data.images 读 alpha,不依赖 PIL;注意 img.pixels 是 **bottom-up**,
|
||||
取像素必须翻转 y。
|
||||
* 渲染耗时长(CPU 下 6 分钟+),从我这边跑要走后台 + 轮询日志,别用前台 timeout。
|
||||
* **工程文件不保留**(2026-09-30 金钻):一份 .blend 二十多兆,攒起来受不住。
|
||||
工程复制到 tempfile.mkdtemp() 的临时目录,渲完立刻删;`--keep-blend` 只在调试时用。
|
||||
成品文件夹里只有:皮肤 + 成图 + 订单信息.json。
|
||||
* **臂集合名/层级各模板都不一样**(实测三种):1~4 顶层 `粗臂`/`细臂`;
|
||||
5~6 嵌在 `Collection` 里叫 `Player Wide Rig`/`Player Slim Rig`;
|
||||
7 顶层 `01_角色_粗臂`/`02_角色_细臂`。
|
||||
→ find_layer() 递归整棵树 + 中英双认(WIDE_KEYS/SLIM_KEYS)。
|
||||
写死任一种都会让模板 exit 5 渲不出来(5/6/7 全中过)。
|
||||
* 皮肤 `img.pack()` 必须在改 filepath **之前** —— 工程现在在临时目录,
|
||||
先改路径的话 pack 会拿相对路径去 <WIN-PATH> 找源文件,报 not found。
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import atexit
|
||||
import os
|
||||
import re
|
||||
import shutil
|
||||
import sys
|
||||
import tempfile
|
||||
import time
|
||||
import traceback
|
||||
|
||||
import bpy
|
||||
|
||||
LOGLINES = []
|
||||
|
||||
# ---- 成品命名(金钻 2026-09-30 定稿)----
|
||||
# 默认分辨率 1000 → <模板名>.png + <模板名>无压缩版.png
|
||||
# 其它分辨率 N → <模板名>N.png + <模板名>N无压缩版.png
|
||||
# 例:飞跃樱花林 在 1000 → 飞跃樱花林.png / 飞跃樱花林无压缩版.png
|
||||
# 飞跃樱花林 在 1080 → 飞跃樱花林1080.png / 飞跃樱花林1080无压缩版.png
|
||||
DEFAULT_RES = 1000
|
||||
UNC_SUFFIX = "无压缩"
|
||||
|
||||
|
||||
def out_base(out_name, res):
|
||||
"""模板名 + (非默认分辨率才带数字)"""
|
||||
res = int(res)
|
||||
return out_name if res == DEFAULT_RES else "%s%d" % (out_name, res)
|
||||
|
||||
|
||||
def make_out_dir(root, base):
|
||||
"""成品文件夹用成品名(金钻 2026-09-30):`飞跃樱花林` / `飞跃樱花林1080`。
|
||||
同名已存在就往后加 -2 / -3 —— 同一个模板被买两次不能互相覆盖。
|
||||
序号仍然记在文件夹里的 订单信息.json(好查账)。"""
|
||||
d = os.path.join(root, base)
|
||||
n = 2
|
||||
while os.path.exists(d):
|
||||
d = os.path.join(root, "%s-%d" % (base, n))
|
||||
n += 1
|
||||
os.makedirs(d, exist_ok=True)
|
||||
return d
|
||||
|
||||
|
||||
def std_name(out_name, res):
|
||||
return out_base(out_name, res) + ".png"
|
||||
|
||||
|
||||
def unc_name(out_name, res):
|
||||
return out_base(out_name, res) + UNC_SUFFIX + ".png"
|
||||
|
||||
|
||||
def log(*a):
|
||||
s = " ".join(str(x) for x in a)
|
||||
LOGLINES.append(s)
|
||||
print("[MAKE-ORDER] " + s, flush=True)
|
||||
|
||||
|
||||
def parse_args():
|
||||
argv = sys.argv
|
||||
if "--" in argv:
|
||||
argv = argv[argv.index("--") + 1:]
|
||||
else:
|
||||
argv = []
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("--template", required=True, help="干净模板 .blend 绝对路径")
|
||||
ap.add_argument("--skin", required=True, help="皮肤 png 绝对路径")
|
||||
ap.add_argument("--orders-dir", required=True, help="商单根目录绝对路径")
|
||||
ap.add_argument("--out-dir", default=None,
|
||||
help="直接指定成品文件夹(调用方用来做重名处理;给了就不再用 --num)")
|
||||
ap.add_argument("--keep-blend", action="store_true",
|
||||
help="调试用:保留临时工程文件(默认渲完就删)")
|
||||
ap.add_argument("--block-texture", default=None, help="可选:方块贴图 png")
|
||||
ap.add_argument("--num", default=None, help="手动指定商单编号(3 位)")
|
||||
ap.add_argument("--out-name", default=None, help="出图名,默认取模板名去编号前缀")
|
||||
ap.add_argument("--res", type=int, default=DEFAULT_RES,
|
||||
help="渲染分辨率。默认 1000(文件名不带数字);换别的值会写进文件名。"
|
||||
"越高越慢:1000≈40s、2048≈2.5min、4096≈10min")
|
||||
ap.add_argument("--skin-material", default=None, help="皮肤材质名(默认自动找)")
|
||||
# 金钻 2026-10-01:页面让买家手动改粗/细臂,但以前**根本没传进来** —— 永远按自动判定走,
|
||||
# 买家改了也白改。现在由渲染机按「这张皮肤」的臂型传进来(多皮肤单每张各自一个臂型)。
|
||||
ap.add_argument("--arm", default="auto", choices=["auto", "classic", "slim"],
|
||||
help="粗臂(classic)/细臂(slim);auto=按皮肤自动判定(默认)")
|
||||
ap.add_argument("--uncompressed", action=argparse.BooleanOptionalAction, default=True,
|
||||
help="输出 16bit 无压缩版(默认开;要关就 --no-uncompressed)")
|
||||
ap.add_argument("--no-render", action="store_true")
|
||||
ap.add_argument("--dry-run", action="store_true")
|
||||
return ap.parse_args(argv)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- 编号 / 目录
|
||||
|
||||
def next_order_number(orders_dir, forced=None):
|
||||
if forced:
|
||||
return forced
|
||||
n = 0
|
||||
for name in os.listdir(orders_dir):
|
||||
m = re.fullmatch(r"(\d{3})", name)
|
||||
if m and os.path.isdir(os.path.join(orders_dir, name)):
|
||||
n = max(n, int(m.group(1)))
|
||||
return "%03d" % (n + 1)
|
||||
|
||||
|
||||
# ------------------------------------------------------- 皮肤臂型判定(核心)
|
||||
|
||||
def _px(img, x, y, w, h):
|
||||
"""取 (x,y) alpha,y 从左上往下数;bpy pixels 是左下起 → 翻转 y。"""
|
||||
yy = h - 1 - y
|
||||
return img.pixels[(yy * w + x) * 4 + 3]
|
||||
|
||||
|
||||
def detect_arm_model(skin_abs):
|
||||
"""读皮肤 alpha 判粗臂/细臂。返回 (model, score, notes)
|
||||
model: 'classic'(粗臂 4px) / 'slim'(细臂 3px) / 'unknown'
|
||||
依据:64x64 标准布局,右臂区 (40,16)-(55,31)。
|
||||
粗臂:每个 4x4 面填满 → 侧面行 y=25 在 x40..55 无透明列;top/bottom 面各占 4px
|
||||
细臂:每个 4x4 面只用 3x3 → 每 4px 段第 4 列透明
|
||||
"""
|
||||
notes = []
|
||||
img = bpy.data.images.load(skin_abs, check_existing=False)
|
||||
try:
|
||||
ow, oh = img.size
|
||||
# 皮肤分辨率不固定:64 是基准,128/256/512/1024…都是同一套 64 网格的整倍数放大,
|
||||
# 一律缩到 64×64 再判臂型(和下单页的判定保持完全一致)。
|
||||
if ow != oh:
|
||||
return "unknown", 0, "非正方形 %dx%d(旧版 2:1,无独立左右臂/腿)" % (ow, oh)
|
||||
if ow < 64:
|
||||
return "unknown", 0, "尺寸过小 %dx%d" % (ow, oh)
|
||||
if ow != 64:
|
||||
img.scale(64, 64)
|
||||
w, h = img.size
|
||||
classic = 0
|
||||
slim = 0
|
||||
|
||||
# 判据1:侧面行 y=25,x=40..55 的透明列数
|
||||
nt = sum(1 for x in range(40, 56) if _px(img, x, 25, w, h) == 0.0)
|
||||
if nt >= 2:
|
||||
slim += 1
|
||||
else:
|
||||
classic += 1
|
||||
notes.append("side-row(y25) transparent cols=%d" % nt)
|
||||
|
||||
# 判据2/3:top/bottom 面第 4 列是否存在(细臂该列为空)
|
||||
for (x, lab) in ((47, "top-face-4th"), (51, "bottom-face-4th")):
|
||||
if _px(img, x, 17, w, h) == 0.0:
|
||||
slim += 1
|
||||
notes.append("%s alpha=0" % lab)
|
||||
else:
|
||||
classic += 1
|
||||
notes.append("%s opaque" % lab)
|
||||
|
||||
# 判据4:y16..19 里 x44..51 的有效列数(粗臂 8,细臂 6)
|
||||
cols = sum(1 for x in range(44, 52)
|
||||
if any(_px(img, x, y, w, h) > 0 for y in range(16, 20)))
|
||||
if cols <= 6:
|
||||
slim += 1
|
||||
else:
|
||||
classic += 1
|
||||
notes.append("face-active cols=%d/8" % cols)
|
||||
|
||||
model = "slim" if slim > classic else "classic"
|
||||
return model, max(slim, classic), "; ".join(notes)
|
||||
finally:
|
||||
try:
|
||||
bpy.data.images.remove(img)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
# ------------------------------------------------------------- 场景操作
|
||||
|
||||
def find_skin_node(mat_name=None, skin_abs=None):
|
||||
"""找皮肤图像纹理节点。返回 (material, node) 或 (None, None)
|
||||
|
||||
⚠️ 2026-10-01 踩坑(金钻报:「空艇那张皮肤还是默认皮肤材质」):
|
||||
老逻辑是「名字里带 skin/皮肤 就选,否则**拿第一个贴图节点**」。
|
||||
空艇模板里第一个贴图节点不是角色皮肤(大概是环境/天空),于是换了个寂寞 ——
|
||||
角色身上还是模板自带的默认皮肤,而"站立正反"因为节点名带 skin 所以正常。
|
||||
新逻辑:**给每个候选节点打分挑最高的**,并把候选全打日志(下次出问题一眼看得出)。
|
||||
分:材质/图片名带 skin|皮肤 +3;图片尺寸 == 上传皮肤的尺寸 +2;≤128 的小图 +1
|
||||
都不沾(全是大背景图)→ 才退回第一个,并明确警告。
|
||||
"""
|
||||
pairs = []
|
||||
for m in bpy.data.materials:
|
||||
if not m.use_nodes or not m.node_tree:
|
||||
continue
|
||||
for n in m.node_tree.nodes:
|
||||
if n.type == "TEX_IMAGE" and n.image is not None:
|
||||
pairs.append((m, n))
|
||||
if not pairs:
|
||||
return None, None
|
||||
if mat_name:
|
||||
for m, n in pairs:
|
||||
if m.name == mat_name:
|
||||
log("皮肤节点 → 按参数指定材质 %s" % m.name)
|
||||
return m, n
|
||||
log("⚠️ 指定材质 %r 没找到,改走自动打分" % mat_name)
|
||||
|
||||
def size_of(img):
|
||||
try:
|
||||
return (int(img.size[0]), int(img.size[1]))
|
||||
except Exception:
|
||||
return (0, 0)
|
||||
|
||||
want = (0, 0)
|
||||
if skin_abs:
|
||||
try:
|
||||
tmp = bpy.data.images.load(skin_abs, check_existing=False)
|
||||
want = size_of(tmp)
|
||||
except Exception:
|
||||
want = (0, 0)
|
||||
|
||||
board = []
|
||||
for m, n in pairs:
|
||||
nm = (m.name or "") + " " + (n.image.name or "") + " " + (n.image.filepath or "")
|
||||
low = nm.lower()
|
||||
s = 0
|
||||
if "skin" in low or "皮肤" in nm:
|
||||
s += 3
|
||||
w, h = size_of(n.image)
|
||||
if want != (0, 0) and (w, h) == want:
|
||||
s += 2
|
||||
if 0 < w <= 128 and 0 < h <= 128:
|
||||
s += 1
|
||||
board.append((s, m, n, (w, h)))
|
||||
board.sort(key=lambda x: -x[0])
|
||||
log("贴图节点候选:%s" % ";".join(
|
||||
"%s/%s %sx%s 分=%d" % (mm.name, (nn.image.name or "?"), wh[0], wh[1], sc)
|
||||
for sc, mm, nn, wh in board))
|
||||
best = board[0]
|
||||
if best[0] == 0:
|
||||
log("⚠️ 没有节点沾『皮肤』特征(全是大图?) → 按第一个来,可能渲出默认皮肤")
|
||||
# ⭐ 2026-10-01:**同分的全都要换**。空艇模板里有「角色皮肤_粗臂 / 角色皮肤_细臂」
|
||||
# 两个皮肤材质(模板作者自己那套工作皮肤),只换排第一的那个 → 用细臂集合渲染时
|
||||
# 角色身上还是模板自带的深褐色皮肤(金钻报的"还是默认皮肤"就是这原因)。
|
||||
# 只认"最高分"这一档,是为了不误伤 64x64 的杂图(那张模板里还有床 blue/purple,
|
||||
# 同尺寸但名字不含 skin,分更低 → 不会被换)。
|
||||
picked = [x for x in board if x[0] == best[0]]
|
||||
log("皮肤节点 → 选中 %d 个(分=%d):%s"
|
||||
% (len(picked), best[0], "、".join(x[1].name + "/" + x[2].name for x in picked)))
|
||||
return picked
|
||||
|
||||
|
||||
def swap_image(node, new_abs, rel_to_blend):
|
||||
"""给图像纹理节点换图并打包。
|
||||
|
||||
⚠️ 顺序不能反:**必须先 pack() 再改 filepath**。
|
||||
先改 filepath 的话,Blender 会拿那个相对路径去找源文件;工程一旦不在
|
||||
皮肤旁边(现在工程走临时目录),就会报
|
||||
RuntimeError: Unable to pack file, source path '<WIN_DIR>' not found
|
||||
(2026-09-30 实踩:`//_assets/` 是相对 .blend 所在目录解析的,
|
||||
.blend 搬去 temp 后就不指向皮肤了。)
|
||||
"""
|
||||
old = node.image
|
||||
img = bpy.data.images.load(new_abs, check_existing=False)
|
||||
try:
|
||||
img.pack() # 此刻 filepath 还是绝对路径,找得到源文件
|
||||
except Exception as e:
|
||||
log("⚠️ pack 失败(皮肤仍能用于本次渲染,只是工程不自包含): %r" % e)
|
||||
img.filepath = rel_to_blend # 已打包,路径只剩记录意义
|
||||
node.image = img
|
||||
node.interpolation = "Closest"
|
||||
try:
|
||||
node.image.colorspace_settings.name = "sRGB"
|
||||
except Exception:
|
||||
pass
|
||||
if old is not None and old.users == 0:
|
||||
try:
|
||||
bpy.data.images.remove(old)
|
||||
except Exception:
|
||||
pass
|
||||
return img
|
||||
|
||||
|
||||
# 粗臂/细臂集合在各模板里叫什么,都不一定 —— 2026-09-30 实测三种:
|
||||
# 1~4 :顶层 `粗臂` / `细臂`
|
||||
# 5~6 :**嵌在 `Collection` 里**,叫 `Player Wide Rig` / `Player Slim Rig`(英文)
|
||||
# 7 :顶层 `01_角色_粗臂` / `02_角色_细臂`
|
||||
# 所以判定必须 ① 递归整棵树 ② 中英双认。写死任何一种都会漏。
|
||||
WIDE_KEYS = ("粗臂", "wide rig", "wide_rig", "wide-rig")
|
||||
SLIM_KEYS = ("细臂", "slim rig", "slim_rig", "slim-rig")
|
||||
|
||||
|
||||
def find_layer(root, keys):
|
||||
"""在**整棵**集合树里找名字命中 keys 的层(广度优先,先浅后深)。
|
||||
|
||||
广度优先很重要:1~4 的顶层 `粗臂` 里还嵌着一个 `Player Wide Rig`,
|
||||
先命中外层才是对的(切外层等于整体切换)。
|
||||
"""
|
||||
queue = [root]
|
||||
while queue:
|
||||
cur = queue.pop(0)
|
||||
for ch in cur.children:
|
||||
low = ch.name.lower()
|
||||
if any(k.lower() in low for k in keys):
|
||||
return ch
|
||||
queue.append(ch)
|
||||
return None
|
||||
|
||||
|
||||
def set_arm_rig(model):
|
||||
"""按臂型切换粗臂/细臂。返回 (ok, msg)。
|
||||
|
||||
⚠️ **找不到不是错误**:真遇到既没中文也没英文臂集合的模板,
|
||||
说明那套模板本来就只有一套角色、不需要切 —— 这种情况要放行继续渲染。
|
||||
(早先版本直接 return False,导致 5/6/7 三个模板全部 exit 5 渲不出来。)
|
||||
"""
|
||||
lc = bpy.context.view_layer.layer_collection
|
||||
wide = find_layer(lc, WIDE_KEYS)
|
||||
slim = find_layer(lc, SLIM_KEYS)
|
||||
if wide is None and slim is None:
|
||||
return True, "此模板没有粗臂/细臂集合,跳过切臂型(按单角色渲)"
|
||||
if wide is not None:
|
||||
wide.exclude = (model != "classic")
|
||||
if slim is not None:
|
||||
slim.exclude = (model != "slim")
|
||||
return True, "粗臂[%s].exclude=%s / 细臂[%s].exclude=%s" % (
|
||||
wide.name if wide else "缺", wide.exclude if wide else "-",
|
||||
slim.name if slim else "缺", slim.exclude if slim else "-")
|
||||
|
||||
|
||||
def visible_armatures():
|
||||
out = []
|
||||
for o in bpy.data.objects:
|
||||
if o.type == "ARMATURE":
|
||||
try:
|
||||
if o.visible_get():
|
||||
out.append(o.name)
|
||||
except Exception:
|
||||
pass
|
||||
return out
|
||||
|
||||
|
||||
def setup_render_device():
|
||||
"""--factory-startup 不加载用户偏好 → Cycles 会掉回 CPU(慢 10 倍)。
|
||||
这里显式把渲染设备切到 GPU。返回描述串。"""
|
||||
sc = bpy.context.scene
|
||||
info = []
|
||||
try:
|
||||
if not hasattr(sc, "cycles"):
|
||||
return "no-cycles"
|
||||
sc.cycles.device = "GPU"
|
||||
addon = bpy.context.preferences.addons.get("cycles")
|
||||
if addon is None:
|
||||
return "GPU 已设但找不到 cycles 偏好面板(可能仍走 CPU)"
|
||||
cp = addon.preferences
|
||||
for dt in ("OPTIX", "CUDA", "HIP", "ONEAPI"):
|
||||
try:
|
||||
cp.compute_device_type = dt
|
||||
info.append("type=%s" % dt)
|
||||
break
|
||||
except Exception:
|
||||
continue
|
||||
cp.get_devices()
|
||||
used = []
|
||||
for d in cp.devices:
|
||||
if d.type != "CPU":
|
||||
d.use = True
|
||||
used.append(d.name)
|
||||
if not used:
|
||||
for d in cp.devices:
|
||||
d.use = True
|
||||
info.append("devices=%s" % (", ".join(used) if used else "CPU-only"))
|
||||
except Exception as e:
|
||||
info.append("设置失败:%r" % e)
|
||||
return "; ".join(info)
|
||||
|
||||
|
||||
def render_to(out_dir, out_name, res, do_render=True, uncompressed=False):
|
||||
sc = bpy.context.scene
|
||||
sc.render.resolution_x = res
|
||||
sc.render.resolution_y = res
|
||||
sc.render.resolution_percentage = 100
|
||||
sc.render.image_settings.file_format = "PNG"
|
||||
dev = setup_render_device()
|
||||
log("渲染设备 %s" % dev)
|
||||
target = os.path.join(out_dir, out_name + ".png")
|
||||
sc.render.filepath = target
|
||||
if not do_render:
|
||||
return target, False
|
||||
t0 = time.time()
|
||||
bpy.ops.render.render(write_still=True)
|
||||
dt = time.time() - t0
|
||||
# compositor 若带 File Output,可能写到别处;兜底找最新 png
|
||||
if not os.path.exists(target):
|
||||
cands = [f for f in os.listdir(out_dir) if f.lower().endswith(".png")]
|
||||
if cands:
|
||||
newest = max(cands, key=lambda f: os.path.getmtime(os.path.join(out_dir, f)))
|
||||
target = os.path.join(out_dir, newest)
|
||||
unc = None
|
||||
if uncompressed:
|
||||
unc = os.path.join(out_dir, out_name + UNC_SUFFIX + ".png")
|
||||
ok = False
|
||||
# 先试「从已渲好的 Render Result 直接另存」—— 省掉一次完整渲染(一张约 37s)
|
||||
try:
|
||||
sc.render.image_settings.file_format = "PNG"
|
||||
sc.render.image_settings.color_depth = "16"
|
||||
sc.render.image_settings.compression = 0
|
||||
rr = bpy.data.images.get("Render Result")
|
||||
if rr is not None:
|
||||
rr.save_render(filepath=unc, scene=sc)
|
||||
ok = os.path.exists(unc) and os.path.getsize(unc) > 1024
|
||||
except Exception as e:
|
||||
log("无压缩版直接另存失败,回退到重渲: %r" % e)
|
||||
if not ok:
|
||||
# 兜底:老老实实再渲一遍(慢一倍,但保证有图)
|
||||
try:
|
||||
sc.render.filepath = unc
|
||||
bpy.ops.render.render(write_still=True)
|
||||
ok = os.path.exists(unc) and os.path.getsize(unc) > 1024
|
||||
except Exception as e:
|
||||
log("无压缩版重渲也失败: %r" % e)
|
||||
log("无压缩版 %s %s" % ("OK" if ok else "FAIL", unc))
|
||||
if not ok:
|
||||
unc = None
|
||||
return target, dt, unc
|
||||
|
||||
|
||||
# ------------------------------------------------------------------- main
|
||||
|
||||
def main():
|
||||
a = parse_args()
|
||||
t_start = time.time()
|
||||
|
||||
for p, lab in ((a.template, "template"), (a.skin, "skin"), (a.orders_dir, "orders-dir")):
|
||||
if not os.path.exists(p):
|
||||
log("FATAL %s 不存在: %s" % (lab, p))
|
||||
return 2
|
||||
|
||||
tpl_name = os.path.basename(a.template)
|
||||
blend_name = re.sub(r"^\d+", "", os.path.splitext(tpl_name)[0]) or os.path.splitext(tpl_name)[0]
|
||||
out_name = a.out_name or blend_name
|
||||
base = out_base(out_name, a.res)
|
||||
|
||||
# 成品文件夹用成品名(模板名[+分辨率]);重名加 -2。
|
||||
# 工程文件不放这里 —— 走临时目录,渲完就删(金钻:不保留工程文件,避免累计拖慢)。
|
||||
if a.out_dir:
|
||||
order_dir = a.out_dir
|
||||
os.makedirs(order_dir, exist_ok=True)
|
||||
num = os.path.basename(order_dir)
|
||||
elif a.num:
|
||||
num = a.num
|
||||
order_dir = os.path.join(a.orders_dir, num)
|
||||
os.makedirs(order_dir, exist_ok=True)
|
||||
else:
|
||||
order_dir = make_out_dir(a.orders_dir, base)
|
||||
num = os.path.basename(order_dir)
|
||||
log("编号 %s" % num)
|
||||
log("成品目录 %s" % order_dir)
|
||||
log("模板 %s" % tpl_name)
|
||||
log("出图名 %s" % base)
|
||||
|
||||
if a.dry_run:
|
||||
log("DRY-RUN 只做目录/复制/判定,不改场景不渲染")
|
||||
|
||||
# --- 1) 临时工程目录(每次一份全新副本;渲完删掉)---
|
||||
work = tempfile.mkdtemp(prefix="ys_order_%s_" % re.sub(r"\W+", "_", base))
|
||||
if not a.keep_blend:
|
||||
# ⚠️ 工程文件不保留(金钻:一份 .blend 二十多兆,攒起来受不住)。
|
||||
# 任何返回路径都要清掉 —— atexit 兜底,正常结束前再显式删一次。
|
||||
atexit.register(shutil.rmtree, work, True)
|
||||
dst_blend = os.path.join(work, tpl_name)
|
||||
shutil.copy2(a.template, dst_blend)
|
||||
log("临时工程 %s(渲完删除)" % dst_blend)
|
||||
|
||||
# --- 2) 素材 ---
|
||||
# ⚠️ 皮肤**先放进成品文件夹**(金钻 2026-09-30):渲染失败也留得下素材
|
||||
skin_abs = os.path.join(order_dir, os.path.basename(a.skin))
|
||||
if not os.path.exists(skin_abs) or os.path.abspath(skin_abs) != os.path.abspath(a.skin):
|
||||
shutil.copy2(a.skin, skin_abs)
|
||||
log("皮肤 → %s" % skin_abs)
|
||||
block_abs = None
|
||||
if a.block_texture and os.path.exists(a.block_texture):
|
||||
block_abs = os.path.join(order_dir, os.path.basename(a.block_texture))
|
||||
if not os.path.exists(block_abs):
|
||||
shutil.copy2(a.block_texture, block_abs)
|
||||
log("方块贴图 → %s" % block_abs)
|
||||
|
||||
# --- 3) 臂型判定 ---
|
||||
model, score, notes = detect_arm_model(skin_abs)
|
||||
log("臂型判定 %s (票数 %d) | %s" % (model.upper(), score, notes))
|
||||
if a.arm != "auto" and a.arm != model:
|
||||
# 指定优先:买家/金钻在页面上手动改过就听他的(自动判定只写进日志备查)
|
||||
log("臂型指定 %s(自动判定是 %s)→ 按指定的走" % (a.arm.upper(), model.upper()))
|
||||
model = a.arm
|
||||
if model == "unknown":
|
||||
log("FATAL 皮肤尺寸不支持,无法判定臂型")
|
||||
return 3
|
||||
|
||||
if a.dry_run:
|
||||
log("DRY-RUN 结束,未开 Blender 场景。耗时 %.1fs" % (time.time() - t_start))
|
||||
_write_log(order_dir, num, model, notes, a, out_name, None)
|
||||
return 0
|
||||
|
||||
# --- 4) 打开副本,改场景 ---
|
||||
bpy.ops.wm.open_mainfile(filepath=dst_blend)
|
||||
log("已打开 %s" % dst_blend)
|
||||
|
||||
picked = find_skin_node(a.skin_material, skin_abs)
|
||||
if not picked:
|
||||
log("FATAL 场景里找不到可用的图像纹理节点")
|
||||
return 4
|
||||
rel = "//" + os.path.basename(skin_abs) # 图片已 pack,路径仅作记录
|
||||
# ⚠️ 2026-10-01 实踩:一开始写成"每个节点各 load+pack 一次",空艇这种双皮肤材质模板
|
||||
# 直接让 Blender 崩掉(退出码 9)。正确做法是**只加载打包一次**,多个节点共用同一张图。
|
||||
try:
|
||||
img = bpy.data.images.load(skin_abs, check_existing=False)
|
||||
try:
|
||||
img.pack() # 此刻 filepath 还是绝对路径,找得到源文件
|
||||
except Exception as e:
|
||||
log("⚠️ pack 失败(皮肤仍能用于本次渲染,只是工程不自包含): %r" % e)
|
||||
img.filepath = rel # 已打包,路径只剩记录意义
|
||||
# ⚠️ board 里每项是**四元组** (分数, 材质, 节点, 尺寸) ——
|
||||
# 写成 `for mat, node in picked` 会 ValueError: too many values to unpack
|
||||
# (2026-10-01 实踩:空艇+站立两个模板全因此渲染失败,退出码 4)
|
||||
for _sc, mat, node, _wh in picked:
|
||||
node.image = img
|
||||
log("换皮肤 材质=%s 节点=%s → %s(已打包)" % (mat.name, node.name, rel))
|
||||
except Exception as e:
|
||||
log("FATAL 换皮肤失败:%r" % e)
|
||||
return 4
|
||||
|
||||
ok, msg = set_arm_rig(model)
|
||||
log("选集合 %s | %s" % ("OK" if ok else "FAIL", msg))
|
||||
if not ok: # 现在只有"真找不到"才会走到这(正常模板不会)
|
||||
return 5
|
||||
log("可见骨架 %s" % ", ".join(visible_armatures()))
|
||||
|
||||
log("工程 不保存(渲完随临时目录一起删)")
|
||||
|
||||
# --- 5) 渲染 ---
|
||||
# 成品命名见文件顶部 out_base():默认 1000 不带数字,其它分辨率带数字。
|
||||
target, dt, unc = render_to(order_dir, base, a.res,
|
||||
do_render=not a.no_render,
|
||||
uncompressed=a.uncompressed)
|
||||
# 渲完立刻删工程:别把 20 多兆的 .blend 留在盘上
|
||||
if a.keep_blend:
|
||||
log("临时工程 保留(--keep-blend):%s" % work)
|
||||
else:
|
||||
shutil.rmtree(work, ignore_errors=True)
|
||||
log("临时工程 已删除(不保留 .blend)")
|
||||
if a.no_render:
|
||||
unc = None
|
||||
log("跳过渲染(--no-render)")
|
||||
else:
|
||||
log("渲染完成 %s (%.1fs)" % (target, dt if isinstance(dt, float) else 0))
|
||||
log("成品 %s + %s" % (std_name(out_name, a.res), unc_name(out_name, a.res)))
|
||||
|
||||
_write_log(order_dir, num, model, notes, a, out_name, target)
|
||||
log("全部完成 耗时 %.1fs" % (time.time() - t_start))
|
||||
return 0
|
||||
|
||||
|
||||
def _write_log(order_dir, num, model, notes, a, out_name, target):
|
||||
stamp = time.strftime("%Y-%m-%d %H:%M:%S")
|
||||
body = [
|
||||
"# 商单 %s —— 自动生成(make_order.py)" % num,
|
||||
"",
|
||||
"生成时间:%s" % stamp,
|
||||
"",
|
||||
"## 输入",
|
||||
"- 模板:`%s`" % a.template,
|
||||
"- 皮肤:`%s`" % os.path.basename(a.skin),
|
||||
"- 方块贴图:%s" % (os.path.basename(a.block_texture) if a.block_texture else "(无)"),
|
||||
"",
|
||||
"## 自动判定",
|
||||
"- **皮肤臂型:%s**(%s)" % (model.upper(), notes),
|
||||
"- 集合切换:%s" % ("粗臂" if model == "classic" else "细臂"),
|
||||
"",
|
||||
"## 输出",
|
||||
"- 工程:`%s`" % os.path.basename(a.template),
|
||||
"- 出图:`%s`%s" % (std_name(out_name, a.res),
|
||||
("、`%s`" % unc_name(out_name, a.res)) if target else ""),
|
||||
"",
|
||||
"## 说明",
|
||||
"皮肤臂型判定依据(64x64 标准布局,右臂区 40..55 / 16..31):",
|
||||
"- 侧面行 y=25 在 x40..55 的透明列数:细臂每 4px 段留 1 列空 → ≥2 列透明",
|
||||
"- top/bottom 面第 4 列(x=47 / x=51):细臂该列为空",
|
||||
"- y16..19 中 x44..51 的有效列数:粗臂 8 列,细臂 6 列",
|
||||
"四项投票多数决;票数接近时请人工复核。",
|
||||
"",
|
||||
"---",
|
||||
"",
|
||||
"### 运行日志",
|
||||
"",
|
||||
"```",
|
||||
] + LOGLINES + ["```", ""]
|
||||
try:
|
||||
with open(os.path.join(order_dir, "_CHANGES.md"), "w", encoding="utf-8") as f:
|
||||
f.write("\n".join(body))
|
||||
with open(os.path.join(order_dir, "_make_order.log"), "w", encoding="utf-8") as f:
|
||||
f.write("\n".join(LOGLINES) + "\n")
|
||||
except Exception as e:
|
||||
print("write log failed: %r" % e)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
try:
|
||||
sys.exit(main())
|
||||
except Exception:
|
||||
traceback.print_exc()
|
||||
log("FATAL 未捕获异常")
|
||||
sys.exit(9)
|
||||
@@ -0,0 +1,4 @@
|
||||
@echo off
|
||||
cd /d %~dp0
|
||||
start "ys_local" /min "__PYTHON__" "%~dp0ys_local.py"
|
||||
exit
|
||||
@@ -0,0 +1,2 @@
|
||||
@echo off
|
||||
powershell -NoProfile -ExecutionPolicy Bypass -File "%~dp0pack_archive.ps1"
|
||||
@@ -0,0 +1,53 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
# 打包留档 —— 一键把「在线订单」压成带日期的 zip,方便传网盘
|
||||
# ⚠️ 本文件含中文,必须存成 UTF-8 **带 BOM**(PowerShell 5.1 不认无 BOM 的 UTF-8)
|
||||
param([switch]$NoPause) # -NoPause:非交互场景(远程测试)用
|
||||
$ErrorActionPreference = 'Stop'
|
||||
|
||||
$ARCH = '<ARCHIVE_DIR>'
|
||||
$OUT = '<ARCHIVE_DIR>'
|
||||
$KEEP = 3 # 只留最近 3 个包,别把盘撑满
|
||||
|
||||
if (-not (Test-Path $ARCH)) { Write-Host "找不到留档目录:$ARCH"; exit 1 }
|
||||
New-Item -ItemType Directory -Force -Path $OUT | Out-Null
|
||||
|
||||
# 先算大小,让金钻心里有数
|
||||
$files = @(Get-ChildItem -Path $ARCH -Recurse -File -ErrorAction SilentlyContinue)
|
||||
if ($files.Count -eq 0) { Write-Host "留档目录还是空的,没有要打包的。"; exit 0 }
|
||||
$mb = [math]::Round((($files | Measure-Object -Property Length -Sum).Sum)/1MB, 1)
|
||||
|
||||
$stamp = Get-Date -Format 'yyyyMMdd_HHmmss'
|
||||
$zip = Join-Path $OUT ("在线订单_$stamp.zip")
|
||||
|
||||
Write-Host "准备打包:$($files.Count) 个文件 / $mb MB"
|
||||
Write-Host "输出:$zip"
|
||||
Write-Host ""
|
||||
|
||||
# ⚠️ PNG 本身已是压缩数据,再压省不了多少,用 Optimal 纯烧时间(实测 35MB 花了 4 分半)。
|
||||
# Fastest 快得多,体积几乎一样 —— 金钻 9-30:「压缩率不高的话就亏」。
|
||||
$t0 = Get-Date
|
||||
Compress-Archive -Path $ARCH -DestinationPath $zip -CompressionLevel Fastest -Force
|
||||
$sec = [math]::Round(((Get-Date) - $t0).TotalSeconds, 1)
|
||||
|
||||
$zmb = [math]::Round((Get-Item $zip).Length/1MB, 1)
|
||||
$ratio = if ($mb -gt 0) { [math]::Round(100*$zmb/$mb) } else { 0 }
|
||||
$saved = if ($mb -gt 0) { [math]::Round(100 - $ratio) } else { 0 }
|
||||
Write-Host "打包完成:$zmb MB(原 $mb MB,省 $saved%) 用了 $sec 秒"
|
||||
if ($saved -lt 15) {
|
||||
Write-Host " ⚠️ 这次省得不多 —— 图本来就是压缩过的。"
|
||||
Write-Host " 打包主要是为了**把一堆文件变成一个**,方便整个拖网盘。"
|
||||
}
|
||||
|
||||
# 清老包,只留最近 KEEP 个
|
||||
$old = @(Get-ChildItem -Path $OUT -Filter '在线订单_*.zip' |
|
||||
Sort-Object LastWriteTime -Descending | Select-Object -Skip $KEEP)
|
||||
foreach ($f in $old) { Write-Host "清掉旧包:$($f.Name)"; Remove-Item $f.FullName -Force }
|
||||
|
||||
Write-Host ""
|
||||
Write-Host "把这个文件拖进网盘就行 —— 上面那行就是路径:"
|
||||
Write-Host $zip
|
||||
Write-Host ""
|
||||
if (-not $NoPause) {
|
||||
Write-Host "按任意键关闭…"
|
||||
$null = $Host.UI.RawUI.ReadKey('NoEcho,IncludeKeyDown')
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
@echo off
|
||||
cd /d %~dp0
|
||||
rem 金钻工坊 · 开单后台(局域网 8081)。用 pythonw 起,不留黑框;
|
||||
rem --open = 顺便把浏览器打开;要停就点「开单后台-停止」。
|
||||
rem ⚠️ 不要在这里加 timeout —— 通过 SSH 跑时 timeout.exe 会因为「输入重定向不支持」报错退出(2026-09-30 实踩)。
|
||||
start "ys_admin" /min "__PYTHONW__" "%~dp0ys_admin.py" --open
|
||||
exit /b 0
|
||||
@@ -0,0 +1,16 @@
|
||||
@echo off
|
||||
rem ============================================================
|
||||
rem 金钻工坊 · 一键面板 (2026-10-04)
|
||||
rem 渲染机 worker + 开单工具(8082) + 管理面板(8081) 一次拉起来,
|
||||
rem 只打开一个页面(8081),开单工具在页面里用标签页切换。
|
||||
rem 每个服务都有单实例保护:已经跑着的不会重复启动。
|
||||
rem 注意:ys_local 用 python.exe(它要 print 到控制台),
|
||||
rem worker/admin 用 pythonw.exe(不留黑框)。
|
||||
rem ============================================================
|
||||
cd /d %~dp0
|
||||
set PYEXE=<WIN_DIR>\user0\AppData\Local\Programs\Python\Python312\python.exe
|
||||
set PYW=<WIN_DIR>\user0\AppData\Local\Programs\Python\Python312\pythonw.exe
|
||||
start "ys_worker" /min "%PYW%" "%~dp0ys_worker.py"
|
||||
start "ys_local" /min "%PYEXE%" "%~dp0ys_local.py"
|
||||
start "ys_admin" /min "%PYW%" "%~dp0ys_admin.py" --open
|
||||
exit /b 0
|
||||
@@ -0,0 +1,6 @@
|
||||
@echo off
|
||||
cd /d %~dp0
|
||||
echo Starting YS render worker (background)...
|
||||
start "ys_worker" /min "__PYTHONW__" "%~dp0ys_worker.py"
|
||||
timeout /t 2 >nul
|
||||
echo Done. Log: %~dp0worker.log
|
||||
@@ -0,0 +1,9 @@
|
||||
@echo off
|
||||
cd /d %~dp0
|
||||
echo ===== YS render worker log (last 40 lines) =====
|
||||
powershell -NoProfile -Command "if (Test-Path '%~dp0worker.log') { Get-Content '%~dp0worker.log' -Tail 40 } else { 'worker.log not found' }"
|
||||
echo.
|
||||
echo ===== Server queue status =====
|
||||
powershell -NoProfile -Command "try { (Invoke-WebRequest -UseBasicParsing 'http<WIN-PATH>' -TimeoutSec 15).Content } catch { 'cannot reach server' }"
|
||||
echo.
|
||||
pause
|
||||
@@ -0,0 +1,245 @@
|
||||
/* =========================================================
|
||||
皮肤质检(共用)—— 网页下单页 和 本机开单工具 共用这一份
|
||||
⚠️ 绝对不要复制成两份:两边判定一旦不一致,
|
||||
就会出现「网页说能渲、本地渲不出来」这种最难查的 bug。
|
||||
========================================================= */
|
||||
/* ---------------- 标准 64 网格分区(来自 MC 皮肤规范) ----------------
|
||||
⚠️ 手臂区粗臂(4px)/细臂(3px)分区不同,必须按判定结果取用。
|
||||
实测教训:细臂皮肤若用粗臂的 4px 框去统计,会有 2.94% 被当成「主体镂空」
|
||||
→ 直接被红牌拦下(其实是正常皮肤那一列本来就空着)。 */
|
||||
const BASE = {
|
||||
head:[[8,0,16,8],[16,0,24,8],[0,8,8,16],[8,8,16,16],[16,8,24,16],[24,8,32,16]],
|
||||
body:[[20,16,28,20],[28,16,36,20],[16,20,20,32],[20,20,28,32],[28,20,32,32],[32,20,40,32]],
|
||||
legR:[[4,16,8,20],[8,16,12,20],[0,20,4,32],[4,20,8,32],[8,20,12,32],[12,20,16,32]],
|
||||
legL:[[20,48,24,52],[24,48,28,52],[16,52,20,64],[20,52,24,64],[24,52,28,64],[28,52,32,64]]
|
||||
};
|
||||
const ARM = {
|
||||
classic:{
|
||||
armR:[[44,16,48,20],[48,16,52,20],[40,20,44,32],[44,20,48,32],[48,20,52,32],[52,20,56,32]],
|
||||
armL:[[36,48,40,52],[40,48,44,52],[32,52,36,64],[36,52,40,64],[40,52,44,64],[44,52,48,64]]
|
||||
},
|
||||
slim:{
|
||||
/* 细臂:手臂宽 3px,顶/底面也只用 3 列(第 4 列是空的)
|
||||
—— 这正是渲染端两条判据(x=47 / x=51 处 y=17 镂空)在测的特征。
|
||||
若这里按 4px 画,皮肤会被自己的质检判成「粗臂」(3粗/1细),自相矛盾。 */
|
||||
armR:[[44,16,47,20],[48,16,51,20],[40,20,44,32],[44,20,47,32],[47,20,50,32],[50,20,54,32]],
|
||||
armL:[[36,48,39,52],[40,48,43,52],[32,52,36,64],[36,52,39,64],[39,52,42,64],[42,52,46,64]]
|
||||
}
|
||||
};
|
||||
const OVL = {
|
||||
头外层:[[32,0,64,16]], 身外层:[[16,32,40,48]], 右臂外层:[[40,32,56,48]],
|
||||
左臂外层:[[48,48,64,64]], 右腿外层:[[0,32,16,48]], 左腿外层:[[16,48,32,64]]
|
||||
};
|
||||
const ARM_GROUPS = {右臂:'armR', 左臂:'armL'};
|
||||
|
||||
/* ---------------- 皮肤分析 ---------------- */
|
||||
function analyze(img, origW, origH){
|
||||
const c = document.createElement('canvas');
|
||||
c.width = 64; c.height = 64;
|
||||
const g = c.getContext('2d', {willReadFrequently:true});
|
||||
g.imageSmoothingEnabled = false;
|
||||
g.clearRect(0,0,64,64);
|
||||
g.drawImage(img, 0, 0, 64, 64);
|
||||
const D = g.getImageData(0,0,64,64).data;
|
||||
const A = (x,y) => D[((y*64)+x)*4+3];
|
||||
|
||||
/* --- 1. 尺寸 ---
|
||||
皮肤分辨率没有"标准值"这回事:64 是基准,往上 128/192/256/512/1024…都是同一个
|
||||
64 网格的整倍数放大,所以只要【正方形 + 64 的整倍数】就是标准皮肤。
|
||||
另外把 16/32 这类小图和其它正方形尺寸也识别出来(标注非常规、允许人工确认继续)。
|
||||
非正方形 = 旧版 2:1(64×32),没有独立左右臂/腿纹理,模板渲不了。 */
|
||||
const sq = (origW === origH);
|
||||
const mult64 = sq && origW >= 64 && origW % 64 === 0;
|
||||
const legacy = (origH * 2 === origW) || (!sq && origW > origH);
|
||||
const tooBig = (origW > 4096 || origH > 4096);
|
||||
const tooSmall = sq && origW < 16;
|
||||
|
||||
/* --- 2. 臂型(与 make_order.py 同算法:4 票制) --- */
|
||||
const arm = (function(){
|
||||
let slim=0, classic=0; const v=[];
|
||||
let nt=0; for(let x=40;x<56;x++) if(A(x,25)===0) nt++;
|
||||
const c1 = nt>=2 ? 'slim' : 'classic';
|
||||
c1==='slim'?slim++:classic++;
|
||||
v.push({n:'侧面行 y=25 透明列数', val:nt+' 列', r:c1==='slim'?'细臂':'粗臂'});
|
||||
|
||||
const pairs=[[47,'顶面第 4 列 x=47'],[51,'底面第 4 列 x=51']];
|
||||
for(const [x,lab] of pairs){
|
||||
const empty = A(x,17)===0;
|
||||
empty?slim++:classic++;
|
||||
v.push({n:lab, val:empty?'镂空':'已涂色', r:empty?'细臂':'粗臂'});
|
||||
}
|
||||
let cols=0; for(let x=44;x<52;x++){
|
||||
let has=false; for(let y=16;y<20;y++) if(A(x,y)>0){has=true;break;}
|
||||
if(has) cols++;
|
||||
}
|
||||
const c4 = cols<=6 ? 'slim' : 'classic';
|
||||
c4==='slim'?slim++:classic++;
|
||||
v.push({n:'y16-19 有效列数 x44-51', val:cols+'/8', r:c4==='slim'?'细臂':'粗臂'});
|
||||
|
||||
const model = slim>classic ? 'slim':'classic';
|
||||
const conf = Math.max(slim,classic);
|
||||
return {model, slim, classic, conf, certain: conf>=3, votes:v};
|
||||
})();
|
||||
|
||||
/* --- 3. 分层像素统计(手臂区按判定出的臂型取框,见上方教训) --- */
|
||||
function stat(rects){
|
||||
let total=0, clear=0, semi=0;
|
||||
for(const r of rects){
|
||||
for(let y=r[1];y<r[3];y++) for(let x=r[0];x<r[2];x++){
|
||||
const a=A(x,y); total++;
|
||||
if(a===0) clear++; else if(a<255) semi++;
|
||||
}
|
||||
}
|
||||
return {total, clear, semi, clearPct: total?clear/total*100:0, semiPct: total?semi/total*100:0};
|
||||
}
|
||||
const AR = arm.model==='slim' ? ARM.slim : ARM.classic;
|
||||
const baseAll=[], ovlAll=[], partStat={};
|
||||
const groups=[['头',BASE.head],['身体',BASE.body],['右臂',AR.armR],['左臂',AR.armL],
|
||||
['右腿',BASE.legR],['左腿',BASE.legL]];
|
||||
for(const [cn,rs] of groups){ baseAll.push(...rs); partStat[cn]=stat(rs); }
|
||||
for(const rs of Object.values(OVL)) ovlAll.push(...rs);
|
||||
const base = stat(baseAll), ovl = stat(ovlAll);
|
||||
|
||||
/* --- 4. 颜色数(判断是不是像素风皮肤) --- */
|
||||
const seen=new Set();
|
||||
for(let i=0;i<D.length;i+=4){
|
||||
if(D[i+3] < 8) continue;
|
||||
seen.add((D[i]>>3<<10)|(D[i+1]>>3<<5)|(D[i+2]>>3));
|
||||
if(seen.size>6000) break;
|
||||
}
|
||||
|
||||
return {sq, mult64, legacy, tooBig, tooSmall, origW, origH, arm, base, ovl, partStat, colors:seen.size};
|
||||
}
|
||||
|
||||
/* ---------------- 生成检测报告 ---------------- */
|
||||
function buildReport(a){
|
||||
const out=[]; let hasBad=false, hasWarn=false;
|
||||
const push=(lv,tag,t,d)=>{out.push({lv,tag,t,d});
|
||||
if(lv==='bad')hasBad=true; if(lv==='warn')hasWarn=true;};
|
||||
|
||||
/* 尺寸:只要正方形 + 64 的整倍数都算标准;放大倍数直接说出来 */
|
||||
const sz = a.origW+'×'+a.origH;
|
||||
const times = a.mult64 ? (a.origW/64) : 0;
|
||||
if(a.mult64){
|
||||
push('ok','通过','图片规格 '+sz,
|
||||
times===1 ? '标准皮肤尺寸(64 网格)'
|
||||
: times+" 倍高清皮肤("+times+"×"+times+" 像素块,会按 64 网格解析,出图精度不受影响)");
|
||||
} else if(a.tooBig){
|
||||
push('bad','不通过','图片规格 '+sz,'图太大了(上限 4096×4096)。请先缩到 1024 或 512 再传。');
|
||||
} else if(a.tooSmall){
|
||||
push('bad','不通过','图片规格 '+sz,'图太小了(最小 16×16),装不下一套皮肤的分区。');
|
||||
} else if(a.legacy){
|
||||
push('bad','不通过','图片规格 '+sz,'这是旧版 2:1 皮肤(没有独立的左臂/左腿纹路),模板无法正确渲染,需要的是正方形皮肤。');
|
||||
} else if(a.sq){
|
||||
push('warn','注意','图片规格 '+sz,
|
||||
'能识别,但不是 64 的整倍数(如 64 / 128 / 256 / 512 / 1024),也不是标准皮肤分区比例。'
|
||||
+'会按 64 网格缩放解析;如果皮肤本身是照标准画的,通常也能出图,但有错位风险 —— 你确认没问题就勾下面的「无视风险」。');
|
||||
} else {
|
||||
push('bad','不通过','图片规格 '+sz,'这不是皮肤比例(应为正方形,或旧版的 2:1)。请确认传的是皮肤图。');
|
||||
}
|
||||
|
||||
/* 是否像皮肤 */
|
||||
if(a.colors>3000) push('warn','注意','图片来源看着不像皮肤','画面颜色数异常多('+a.colors+'+ 色),像素风皮肤一般不到几百色。确认没有传错图(比如误传照片或渲染成品图)。');
|
||||
else push('ok','通过','像素风检查','颜色数 '+a.colors+',符合像素风皮肤特征');
|
||||
|
||||
/* 主体层镂空 */
|
||||
const bp=a.base.clearPct;
|
||||
const badParts=Object.entries(a.partStat).filter(([,s])=>s.clearPct>1.5).map(([n,s])=>n+'('+s.clearPct.toFixed(1)+'%)');
|
||||
if(bp>2){
|
||||
push('bad','不通过','主体层有大量镂空','皮肤本体共有 '+bp.toFixed(1)+'% 的像素是全透明的'
|
||||
+(badParts.length?',集中部位:'+badParts.join('、'):'')+'。渲染出来身体会「漏空」,请先把本体补实再提交。');
|
||||
}else if(bp>0.2){
|
||||
push('warn','注意','主体层有小面积镂空','本体有 '+bp.toFixed(1)+'% 的像素是透明的'
|
||||
+(badParts.length?',主要在:'+badParts.join('、'):'')+'。多数情况能正常出图,少数会在成图上看到细小的透光点。');
|
||||
}else{
|
||||
push('ok','通过','主体层完整','本体没有明显镂空');
|
||||
}
|
||||
|
||||
/* 半透明 */
|
||||
const semiN = a.base.semi + a.ovl.semi;
|
||||
if(a.base.semi>30){
|
||||
push('warn','注意','存在半透明像素','本体层有 '+a.base.semi+' 个半透明像素(alpha 不是全实心)。渲染边缘可能出现毛边或色差。');
|
||||
}else if(semiN>0){
|
||||
push('warn','注意','存在少量半透明像素','全图 '+semiN+' 个半透明像素,通常不影响出图,但边缘可能略有杂色。');
|
||||
}else{
|
||||
push('ok','通过','透明度正常','未发现半透明像素');
|
||||
}
|
||||
|
||||
/* 外层 */
|
||||
const op=a.ovl.clearPct;
|
||||
if(a.ovl.total && op>99.5){
|
||||
push('ok','通过','外层(第二层)未使用','这套皮肤没有用外套/帽子层,属正常情况');
|
||||
}else if(a.ovl.total && op<2){
|
||||
push('warn','注意','外层几乎铺满','外层(帽子/外套)几乎每一格都有颜色。如果本意是「只有部分外套」,可能是不小心整层涂满了。');
|
||||
}else{
|
||||
push('ok','通过','外层覆盖正常','外层(帽子/外套)有内容也有留白,符合常见皮肤画法');
|
||||
}
|
||||
|
||||
/* 臂型 */
|
||||
if(a.arm.certain){
|
||||
push('ok','通过','手臂规格 · '+(a.arm.model==='classic'?'粗臂(Steve 4px)':'细臂(Alex 3px)'),
|
||||
'判定明确(' + Math.max(a.arm.slim,a.arm.classic) + '/4 项)。渲染时会用' + (a.arm.model==='classic'?'粗臂':'细臂') + '模型。若你觉得不对,可在下面手动改。');
|
||||
}else{
|
||||
push('warn','注意','手臂规格判定不确定',
|
||||
'4 项检验只命中 '+Math.max(a.arm.slim,a.arm.classic)+' 项('+(a.arm.classic)+' 粗 / '+(a.arm.slim)+' 细),这类皮肤容易判错。'
|
||||
+'请自己在下面确认一下手臂是粗的还是细的——判错会导致皮肤整体错位。');
|
||||
}
|
||||
return {items:out, hasBad, hasWarn};
|
||||
}
|
||||
|
||||
|
||||
/* ---------------- PNG 结构核验(防夹带私货) ----------------
|
||||
⚠️ 这份是 /opt/order-app/pngcheck.py 的**镜像**,两边判定必须一致:
|
||||
前端负责「拦」(给人看明白的原因),后端负责「剥」(存下来的是干净字节)。
|
||||
改一边必须同步改另一边 —— 共享用例在 /opt/order-app/tests/png_struct_test.py。
|
||||
拦什么:尾部夹带 / 未知关键块 / APNG / 结构损坏 / 非 PNG
|
||||
只警告:tEXt 等元数据块(很多编辑器会加,后端会剥掉,不算错)
|
||||
u8: Uint8Array(整个文件字节)→ {ok, reason, notes}
|
||||
------------------------------------------------------------- */
|
||||
function checkPngBytes(u8){
|
||||
const notes=[];
|
||||
const bad=(why)=>({ok:false, reason:why, notes:notes});
|
||||
const SIG=[0x89,0x50,0x4E,0x47,0x0D,0x0A,0x1A,0x0A];
|
||||
if(!u8 || u8.length < 33) return bad('不是 PNG 文件');
|
||||
for(let i=0;i<8;i++){ if(u8[i]!==SIG[i]) return bad('不是 PNG 文件'); }
|
||||
|
||||
const STRIP=['tEXt','zTXt','iTXt','eXIf','tIME','sPLT','hIST'];
|
||||
const OK_CRIT=['IHDR','PLTE','IDAT','IEND'];
|
||||
const OK_ANC=['PLTE','tRNS','gAMA','cHRM','sRGB','iCCP','bKGD','pHYs','sBIT'];
|
||||
const rd=(o)=>((u8[o]<<24)>>>0)+(u8[o+1]<<16)+(u8[o+2]<<8)+u8[o+3];
|
||||
const typ=(o)=>String.fromCharCode(u8[o],u8[o+1],u8[o+2],u8[o+3]);
|
||||
|
||||
let off=8, n=0, seenIhdr=false, seenIdat=false, seenIend=false;
|
||||
while(off < u8.length){
|
||||
if(++n > 4096) return bad('PNG 结构异常(块数量过多)');
|
||||
if(off+8 > u8.length) return bad('PNG 文件损坏(块头不完整)');
|
||||
const ln=rd(off), t=typ(off+4), end=off+12+ln;
|
||||
if(end > u8.length) return bad('PNG 文件损坏(块数据不完整)');
|
||||
if(t==='IHDR'){
|
||||
if(off!==8) return bad('PNG 结构异常(IHDR 不在最前)');
|
||||
seenIhdr=true;
|
||||
}else if(t==='IEND'){
|
||||
seenIend=true;
|
||||
const tail=u8.length-end;
|
||||
if(tail>0) return bad('图片尾部夹带了 '+tail+' 字节额外数据(正常 PNG 到 IEND 就该结束)');
|
||||
break;
|
||||
}else if(t==='acTL'){
|
||||
return bad('这是动画 PNG(APNG),请用普通静态 PNG');
|
||||
}else if(t==='IDAT'){
|
||||
seenIdat=true;
|
||||
}else if(OK_ANC.indexOf(t)>=0){
|
||||
/* 允许 */
|
||||
}else if(STRIP.indexOf(t)>=0){
|
||||
notes.push('已剥掉元数据块 '+t);
|
||||
}else{
|
||||
const critical = (u8[off+4] & 0x20) === 0; /* PNG 规范:首字母大写=关键块 */
|
||||
if(critical && OK_CRIT.indexOf(t)<0) return bad('图片里有无法识别的内容块 '+t);
|
||||
notes.push('已剥掉附加块 '+t);
|
||||
}
|
||||
off=end;
|
||||
}
|
||||
if(!seenIhdr) return bad('PNG 缺少 IHDR(不是完整图片)');
|
||||
if(!seenIdat) return bad('PNG 缺少图像数据(IDAT)');
|
||||
if(!seenIend) return bad('PNG 没有正常结束(缺 IEND)');
|
||||
return {ok:true, reason:'', notes:notes};
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
@echo off
|
||||
echo Stopping YS admin panel...
|
||||
powershell -NoProfile -Command "Get-CimInstance Win32_Process | Where-Object { $_.CommandLine -like '*ys_admin.py*' } | ForEach-Object { Stop-Process -Id $_.ProcessId -Force -ErrorAction SilentlyContinue }"
|
||||
echo Stopped.
|
||||
timeout /t 3 >nul
|
||||
@@ -0,0 +1,5 @@
|
||||
@echo off
|
||||
echo Stopping YS render worker...
|
||||
powershell -NoProfile -Command "Get-CimInstance Win32_Process | Where-Object { $_.CommandLine -like '*ys_worker.py*' } | ForEach-Object { Stop-Process -Id $_.ProcessId -Force -ErrorAction SilentlyContinue }"
|
||||
echo Stopped. (Server side will show the machine as offline.)
|
||||
timeout /t 3 >nul
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,411 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
金钻工坊 · 本机开单工具(平台单专用)
|
||||
|
||||
给「闲鱼 / B站工坊」这类聊天下单的买家出图用:
|
||||
|
||||
双击桌面「本机开单」→ 浏览器打开 htt<WIN-PATH>
|
||||
→ 拖皮肤进去(同样自动质检)→ 勾模板 → 点开始
|
||||
→ 本机 Blender 出图(标准压缩 + 16bit 无压缩,两张)→ 下载 / 打开文件夹 → 贴回闲鱼
|
||||
|
||||
安全设计(金钻 2026-09-30 提出「别人会暴力破解吧」):
|
||||
* 只监听 localhost —— 公网、局域网都连不进来,根本没有暴露面
|
||||
* 不联网、不上传、不要兑换码、不碰服务器
|
||||
|
||||
渲染队列(金钻 2026-09-30:「也是渲染队列,不要一口气并行,会卡炸的」):
|
||||
* **只有一个渲染线程**(qworker)→ 任何时刻至多一个 Blender 在跑
|
||||
* 多单进来排队 FIFO,页面显示「前面还有 N 单」
|
||||
* 一张图渲完才开下一张;串行是硬约束,不是性能优化
|
||||
"""
|
||||
import base64
|
||||
import collections
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import socket
|
||||
import subprocess
|
||||
import threading
|
||||
import time
|
||||
import traceback
|
||||
import urllib.parse
|
||||
import webbrowser
|
||||
from datetime import datetime
|
||||
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||||
|
||||
import ys_worker as W # 复用:配置 / 模板表 / Blender 查找 / 日志
|
||||
|
||||
HERE = os.path.dirname(os.path.abspath(__file__))
|
||||
PORT = 8082
|
||||
# ⚠️ 2026-10-04:单实例锁必须用**独立端口** —— 以前它 bind 的是 PORT(8082),
|
||||
# 紧接着 ThreadingHTTPServer 又要 bind 8082,Windows 上会直接 WinError 10013
|
||||
# ("访问权限不允许的方式做套接字尝试")。ys_worker 用的 8083,这里用 8084。
|
||||
LOCK_PORT = 8084
|
||||
JOBS = {} # job_id -> dict
|
||||
JOB_LOCK = threading.Lock()
|
||||
|
||||
# ⚠️ 渲染队列:只有一个消费线程 → 至多一个 Blender 在跑
|
||||
JOBQ = collections.deque()
|
||||
QCOND = threading.Condition()
|
||||
|
||||
|
||||
# ------------------------------------------------------------------ 队列
|
||||
def enqueue(job_id):
|
||||
with QCOND:
|
||||
JOBQ.append(job_id)
|
||||
_refresh_positions()
|
||||
QCOND.notify()
|
||||
|
||||
|
||||
def _refresh_positions():
|
||||
for i, jid in enumerate(JOBQ):
|
||||
j = JOBS.get(jid)
|
||||
if j is not None:
|
||||
j["queue_pos"] = i + 1
|
||||
|
||||
|
||||
_queue_started = False
|
||||
|
||||
|
||||
def start_queue():
|
||||
"""起唯一的渲染线程(幂等)。main() 会调;测试也直接调它。"""
|
||||
global _queue_started
|
||||
if _queue_started:
|
||||
return False
|
||||
_queue_started = True
|
||||
threading.Thread(target=qworker, daemon=True).start()
|
||||
return True
|
||||
|
||||
|
||||
def qworker():
|
||||
"""唯一干活的人。串行是硬要求,别改成并行。"""
|
||||
while True:
|
||||
with QCOND:
|
||||
while not JOBQ:
|
||||
QCOND.wait()
|
||||
jid = JOBQ.popleft()
|
||||
_refresh_positions()
|
||||
try:
|
||||
run_job(jid)
|
||||
except Exception:
|
||||
j = JOBS.get(jid)
|
||||
if j is not None:
|
||||
j.update(state="error", error=traceback.format_exc()[-400:])
|
||||
|
||||
|
||||
# ------------------------------------------------------------------ 工具
|
||||
def local_archive():
|
||||
"""本机单的留档根目录(和网页订单分开放,但共用同一套序号)"""
|
||||
return W.CFG.get("local_archive") or os.path.join(W.CFG["archive"], "本地")
|
||||
|
||||
|
||||
def now_s():
|
||||
return datetime.now().strftime("%Y-%m-%d %H:%M:%S")
|
||||
|
||||
|
||||
def scan_assets():
|
||||
"""体检:Blender / 模板 / 渲染脚本 都在不在(页面进来就先告诉你,别等渲到一半才报错)"""
|
||||
blender = W.find_blender()
|
||||
tpl_root = W.CFG["tpl_root"]
|
||||
missing = []
|
||||
for k, fn in W.TEMPLATES.items():
|
||||
if not os.path.exists(os.path.join(tpl_root, fn)):
|
||||
missing.append(fn)
|
||||
return {
|
||||
"blender": blender,
|
||||
"blender_ok": bool(blender),
|
||||
"tpl_root": tpl_root,
|
||||
"make_order": W.CFG["make_order"],
|
||||
"make_order_ok": os.path.exists(W.CFG["make_order"]),
|
||||
"archive": local_archive(),
|
||||
"templates": {k: {"file": fn, "ok": os.path.exists(os.path.join(tpl_root, fn))}
|
||||
for k, fn in W.TEMPLATES.items()},
|
||||
"missing": missing,
|
||||
}
|
||||
|
||||
|
||||
def open_browser(url):
|
||||
"""只在 Windows 上自动开浏览器。
|
||||
服务器/无桌面环境调 xdg-open 会去连 D-Bus,起不来还刷错误,没必要。"""
|
||||
if os.name != "nt" and not os.environ.get("YS_OPEN_BROWSER"):
|
||||
return
|
||||
try:
|
||||
webbrowser.open(url)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
# ------------------------------------------------------------------ 渲染
|
||||
def write_png(dataurl, dest):
|
||||
if "," in dataurl:
|
||||
dataurl = dataurl.split(",", 1)[1]
|
||||
with open(dest, "wb") as f:
|
||||
f.write(base64.b64decode(dataurl))
|
||||
|
||||
|
||||
def pick_outputs(d, tpl_key, res):
|
||||
"""挑出这一单的两张成品。命名规则(金钻 2026-09-30 定稿,见 ys_worker.deliver_names):
|
||||
默认 1000 → 飞跃樱花林.png + 飞跃樱花林无压缩版.png
|
||||
其它 N → 飞跃樱花林N.png + 飞跃樱花林N无压缩版.png
|
||||
找不到就退回"目录里有的",别让一次改名把成品弄丢。"""
|
||||
sn, un = W.deliver_names(tpl_key, res)
|
||||
std = os.path.join(d, sn)
|
||||
if not os.path.exists(std):
|
||||
cands = [f for f in sorted(os.listdir(d))
|
||||
if f.lower().endswith(".png") and W.UNC_SUFFIX not in f]
|
||||
std = os.path.join(d, cands[0]) if cands else None
|
||||
unc = os.path.join(d, un)
|
||||
if not os.path.exists(unc):
|
||||
cands = [f for f in sorted(os.listdir(d))
|
||||
if f.lower().endswith(".png") and W.UNC_SUFFIX in f]
|
||||
unc = os.path.join(d, cands[0]) if cands else None
|
||||
return std, unc
|
||||
|
||||
|
||||
def run_job(job_id):
|
||||
j = JOBS[job_id]
|
||||
j["state"] = "running"
|
||||
j["queue_pos"] = 0
|
||||
try:
|
||||
blender = W.find_blender()
|
||||
if not blender:
|
||||
j.update(state="error", error="找不到 blender.exe(把路径填进 config.json 的 blender 字段)")
|
||||
return
|
||||
work = os.path.join(HERE, "work")
|
||||
os.makedirs(work, exist_ok=True)
|
||||
# 用买家原始文件名建临时皮肤 —— 留档文件夹里要看到客户给的那张图叫什么
|
||||
safe = re.sub(r'[\\/:*?"<>|]+', "_", (j.get("fileName") or "skin.png")).strip() or "skin.png"
|
||||
if not safe.lower().endswith(".png"):
|
||||
safe += ".png"
|
||||
skin = os.path.join(work, safe)
|
||||
write_png(j["skin"], skin)
|
||||
j["skin"] = None # 立刻丢掉 base64,别占内存
|
||||
|
||||
root = local_archive()
|
||||
os.makedirs(root, exist_ok=True)
|
||||
|
||||
for idx, tk in enumerate(j["templates"]):
|
||||
j["current"] = idx + 1
|
||||
fname = W.TEMPLATES.get(tk)
|
||||
if not fname:
|
||||
j["errors"].append("未知模板:%s" % tk)
|
||||
continue
|
||||
tpl = os.path.join(W.CFG["tpl_root"], fname)
|
||||
if not os.path.exists(tpl):
|
||||
j["errors"].append("%s:模板文件不存在" % fname)
|
||||
continue
|
||||
|
||||
out_name = W.tpl_base(tk)
|
||||
res = int(j.get("res") or W.DEFAULT_RES)
|
||||
# 不加 --uncompressed:这个开关现在默认就是开的(金钻:两张都要发顾客)
|
||||
# 成品文件夹用成品名;皮肤先放进去;工程走临时目录,渲完删
|
||||
d, dbase = W.prepare_out_dir(root, tk, res, skin)
|
||||
cmd = [blender, "-b", "--factory-startup", "--python", W.CFG["make_order"], "--",
|
||||
"--template", tpl, "--skin", skin,
|
||||
"--orders-dir", root, "--out-dir", d, "--res", str(res)]
|
||||
W.log("[本机单] 渲染 %s → %s(%d px)" % (fname, os.path.basename(d), res))
|
||||
okr, tail, dt, note = W.run_blender(cmd)
|
||||
if not okr:
|
||||
j["errors"].append("%s:%s" % (fname, note))
|
||||
continue
|
||||
seq = W.next_seq({"来源": "本机开单(平台单)", "模板": out_name,
|
||||
"成品文件夹": os.path.basename(d), "分辨率": res,
|
||||
"皮肤文件": os.path.basename(skin), "备注": j.get("note") or "",
|
||||
"耗时秒": round(dt, 1)})
|
||||
|
||||
std, unc = pick_outputs(d, tk, res)
|
||||
if not std:
|
||||
j["errors"].append("%s:渲染完成但没找到 png" % fname)
|
||||
continue
|
||||
if not unc:
|
||||
j["errors"].append("%s:无压缩版没生成(只出了标准版)" % fname)
|
||||
|
||||
info = {"序号": seq, "文件夹": os.path.basename(d),
|
||||
"来源": "本机开单(平台单)", "模板": out_name, "模板key": tk,
|
||||
"分辨率": res, "皮肤文件": os.path.basename(skin), "手臂规格": j.get("arm"),
|
||||
"条款版本": W.TERMS_VERSION,
|
||||
"条款说明": "仅提供渲染服务;皮肤内容合法性由提供者负责",
|
||||
"买家备注": j.get("note") or "", "渲染完成时间": now_s(),
|
||||
"渲染耗时秒": round(dt, 1),
|
||||
"交付件": [os.path.basename(x) for x in (std, unc) if x]}
|
||||
try:
|
||||
with open(os.path.join(d, "订单信息.json"), "w", encoding="utf-8") as f:
|
||||
json.dump(info, f, ensure_ascii=False, indent=1)
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
sn, un = W.deliver_names(tk, res)
|
||||
j["results"].append({"seq": seq, "tpl": tk, "res": res, "kind": "标准压缩",
|
||||
"name": sn, "path": std, "dir": d, "sec": round(dt, 1)})
|
||||
if unc:
|
||||
j["results"].append({"seq": seq, "tpl": tk, "res": res, "kind": "无压缩(16bit)",
|
||||
"name": un, "path": unc, "dir": d, "sec": round(dt, 1)})
|
||||
W.log("[本机单] 完成 %s → %s(%.1fs,两张)" % (fname, std, dt))
|
||||
|
||||
j["state"] = "done" if j["results"] else "error"
|
||||
if not j["results"]:
|
||||
j["error"] = ";".join(j["errors"])[:400] or "没有产出任何图片"
|
||||
j["finished"] = now_s()
|
||||
except subprocess.TimeoutExpired:
|
||||
j.update(state="error", error="渲染超时(超过 1 小时)")
|
||||
except Exception:
|
||||
j.update(state="error", error=traceback.format_exc()[-400:])
|
||||
finally:
|
||||
try:
|
||||
if skin and os.path.exists(skin):
|
||||
os.remove(skin)
|
||||
except (OSError, NameError):
|
||||
pass
|
||||
|
||||
|
||||
# ------------------------------------------------------------------ HTTP
|
||||
class H(BaseHTTPRequestHandler):
|
||||
protocol_version = "HTTP/1.1"
|
||||
server_version = "ys-local"
|
||||
|
||||
def log_message(self, fmt, *a): # 静音,别刷屏
|
||||
pass
|
||||
|
||||
def send(self, code, body, ctype="application/json; charset=utf-8", extra=None):
|
||||
if isinstance(body, str):
|
||||
body = body.encode("utf-8")
|
||||
self.send_response(code)
|
||||
self.send_header("Content-Type", ctype)
|
||||
self.send_header("Content-Length", str(len(body)))
|
||||
self.send_header("Cache-Control", "no-store")
|
||||
for k, v in (extra or {}).items():
|
||||
self.send_header(k, v)
|
||||
self.end_headers()
|
||||
try:
|
||||
self.wfile.write(body)
|
||||
except (BrokenPipeError, ConnectionResetError):
|
||||
pass
|
||||
|
||||
def js(self, obj, code=200):
|
||||
self.send(code, json.dumps(obj, ensure_ascii=False))
|
||||
|
||||
def static(self, name, ctype):
|
||||
p = os.path.join(HERE, name)
|
||||
if not os.path.exists(p):
|
||||
return self.send(404, "missing", "text/plain; charset=utf-8")
|
||||
with open(p, "rb") as f:
|
||||
self.send(200, f.read(), ctype)
|
||||
|
||||
def do_GET(self):
|
||||
u = urllib.parse.urlparse(self.path)
|
||||
p = u.path
|
||||
if p in ("/", "/index.html"):
|
||||
return self.static("local.html", "text/html; charset=utf-8")
|
||||
if p == "/skincheck.js":
|
||||
return self.static("skincheck.js", "application/javascript; charset=utf-8")
|
||||
if p == "/api/status":
|
||||
return self.js(scan_assets())
|
||||
|
||||
m = re.fullmatch(r"/api/job/([A-Za-z0-9]+)", p)
|
||||
if m:
|
||||
j = JOBS.get(m.group(1))
|
||||
if not j:
|
||||
return self.js({"ok": False, "error": "任务不存在"}, 404)
|
||||
return self.js({k: v for k, v in j.items() if k != "skin"})
|
||||
|
||||
m = re.fullmatch(r"/api/file/([A-Za-z0-9]+)/(\d+)", p)
|
||||
if m:
|
||||
j = JOBS.get(m.group(1))
|
||||
if not j:
|
||||
return self.send(404, "no job", "text/plain")
|
||||
i = int(m.group(2))
|
||||
if i >= len(j["results"]):
|
||||
return self.send(404, "no file", "text/plain")
|
||||
r = j["results"][i]
|
||||
with open(r["path"], "rb") as f:
|
||||
# ⚠️ HTTP 头只能是 latin-1,中文文件名直接扔 UnicodeEncodeError
|
||||
# → 连接被掐断(浏览器看就是「下载失败」)。必须 ASCII 回退名 + RFC 5987。
|
||||
ascii_name = r["name"].encode("ascii", "replace").decode("ascii").replace("?", "_")
|
||||
cd = ("inline; filename=\"%s\"; filename*=UTF-8''%s"
|
||||
% (ascii_name, urllib.parse.quote(r["name"], safe="")))
|
||||
return self.send(200, f.read(), "image/png", {"Content-Disposition": cd})
|
||||
return self.send(404, "not found", "text/plain; charset=utf-8")
|
||||
|
||||
def do_POST(self):
|
||||
u = urllib.parse.urlparse(self.path)
|
||||
n = int(self.headers.get("Content-Length") or 0)
|
||||
if n > 64 * 1024 * 1024:
|
||||
return self.js({"ok": False, "error": "请求过大"}, 413)
|
||||
try:
|
||||
d = json.loads(self.rfile.read(n) or b"{}") if n else {}
|
||||
except ValueError:
|
||||
return self.js({"ok": False, "error": "请求体不合法"}, 400)
|
||||
|
||||
if u.path == "/api/render":
|
||||
tpls = [t for t in (d.get("templates") or []) if t in W.TEMPLATES][:10]
|
||||
if not d.get("skin") or not tpls:
|
||||
return self.js({"ok": False, "error": "缺皮肤或缺模板"}, 400)
|
||||
st = scan_assets()
|
||||
if not st["blender_ok"]:
|
||||
return self.js({"ok": False, "error": "没找到 blender.exe"}, 400)
|
||||
jid = "%s%04d" % (datetime.now().strftime("%H%M%S"), len(JOBS))
|
||||
JOBS[jid] = {"id": jid, "state": "queued", "queue_pos": 0, "created": now_s(),
|
||||
"skin": d["skin"], "fileName": d.get("fileName") or "skin.png",
|
||||
"templates": tpls, "arm": d.get("arm") or "",
|
||||
"res": int(d.get("res") or W.DEFAULT_RES),
|
||||
"note": (d.get("note") or "")[:200],
|
||||
"total": len(tpls), "current": 0, "results": [], "errors": []}
|
||||
enqueue(jid) # ← 进队列,由唯一的渲染线程串行处理
|
||||
return self.js({"ok": True, "job": jid})
|
||||
|
||||
if u.path == "/api/openfolder":
|
||||
j = JOBS.get(d.get("job") or "")
|
||||
if not j or not j.get("results"):
|
||||
return self.js({"ok": False, "error": "还没有产出"}, 400)
|
||||
folder = j["results"][0]["dir"]
|
||||
try:
|
||||
if hasattr(os, "startfile"): # Windows
|
||||
os.startfile(folder)
|
||||
else:
|
||||
subprocess.Popen(["xdg-open", folder])
|
||||
return self.js({"ok": True, "folder": folder})
|
||||
except Exception as e:
|
||||
return self.js({"ok": False, "error": "%s 目录:%s" % (e, folder)}, 500)
|
||||
|
||||
if u.path == "/api/quit":
|
||||
self.js({"ok": True})
|
||||
threading.Thread(target=lambda: (time.sleep(0.4), os._exit(0)), daemon=True).start()
|
||||
return
|
||||
|
||||
return self.js({"ok": False, "error": "not found"}, 404)
|
||||
|
||||
|
||||
def single_instance():
|
||||
"""只允许开一个:不然两个页面同时开两个 Blender 会把机器顶满"""
|
||||
s = socket.socket()
|
||||
try:
|
||||
s.bind(("localhost", LOCK_PORT))
|
||||
s.listen(1)
|
||||
return s
|
||||
except OSError:
|
||||
return None
|
||||
|
||||
|
||||
def main():
|
||||
W.load_cfg()
|
||||
lock = single_instance()
|
||||
if not lock:
|
||||
print("本机开单工具已经在跑了,直接打开 htt<WIN-PATH>" % PORT)
|
||||
open_browser("htt<WIN-PATH>" % PORT)
|
||||
time.sleep(4)
|
||||
return
|
||||
start_queue() # 唯一的渲染线程
|
||||
a = scan_assets()
|
||||
print("=" * 56)
|
||||
print(" 金钻工坊 · 本机开单工具(平台单)")
|
||||
print(" 地址 htt<WIN-PATH> (只有这台电脑能开)" % PORT)
|
||||
print(" Blender %s" % (a["blender"] or "❌ 没找到"))
|
||||
print(" 模板 %s(缺 %d 个)" % (a["tpl_root"], len(a["missing"])))
|
||||
print(" 留档 %s" % a["archive"])
|
||||
print(" 队列 串行,一次只开一个 Blender")
|
||||
print("=" * 56, flush=True)
|
||||
open_browser("htt<WIN-PATH>" % PORT)
|
||||
ThreadingHTTPServer(("localhost", PORT), H).serve_forever()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,663 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
金钻工坊 · 渲染下单 —— 宿主机渲染机(worker)
|
||||
|
||||
开机启动后自动干活:
|
||||
心跳上报 → 拉一单 → 下载皮肤 → 用 Blender 按模板出图 → 回传服务器 → 永久留档
|
||||
|
||||
留档(金钻要求:时间 / 序号 / 兑换码 / 皮肤 / 成图):
|
||||
<ARCHIVE_DIR>
|
||||
模板.blend、_assets\\skin.png、<模板名>.png、订单信息.json
|
||||
|
||||
只在需要时连服务器(出站),服务器从不主动连你。
|
||||
"""
|
||||
import base64, json, os, re, shutil, signal, socket, subprocess, sys, threading, time, traceback
|
||||
import urllib.request, urllib.error
|
||||
from datetime import datetime
|
||||
|
||||
HERE = os.path.dirname(os.path.abspath(__file__))
|
||||
|
||||
# ---- 成品命名(金钻 2026-09-30 定稿,和 make_order.py 必须一致)----
|
||||
# 默认 1000 → <模板名>.png + <模板名>无压缩.png
|
||||
# 其它 N → <模板名>N.png + <模板名>N无压缩.png
|
||||
DEFAULT_RES = 1000
|
||||
UNC_SUFFIX = "无压缩"
|
||||
# 服务条款版本 —— 与网页 index.html / 后端 server.py 必须一致(2026-09-30 金钻定)
|
||||
TERMS_VERSION = "2026-10-01.1"
|
||||
|
||||
# ---------------------------------------------------------------- 配置
|
||||
CFG = {
|
||||
"server": "http<WIN-PATH>",
|
||||
"token": "",
|
||||
"tpl_root": r"<ARCHIVE_DIR>",
|
||||
"make_order": r"<TOOLS_DIR>\make_order.py",
|
||||
"archive": r"<ARCHIVE_DIR>",
|
||||
"blender": "", # 留空 = 自动查找
|
||||
"res": DEFAULT_RES, # 出图分辨率;文件名规则见上
|
||||
"poll": 20
|
||||
}
|
||||
TEMPLATES = { # key 必须和下单页一致
|
||||
"stand": "1站立正反.blend",
|
||||
"standb": "2站立正反加虚化.blend",
|
||||
"wheat": "3麦田萤火.blend",
|
||||
"beach": "4海边自拍.blend",
|
||||
"boom": "5不看爆炸.blend",
|
||||
"sakura": "6飞跃樱花林.blend",
|
||||
"airship": "7空艇巡游.blend",
|
||||
}
|
||||
def tpl_base(tpl_key):
|
||||
"""模板中文名(去掉文件名开头的序号):3麦田萤火.blend → 麦田萤火"""
|
||||
return re.sub(r"^\d+", "", os.path.splitext(TEMPLATES.get(tpl_key, tpl_key))[0])
|
||||
|
||||
|
||||
def out_base(tpl_key, res):
|
||||
res = int(res or DEFAULT_RES)
|
||||
b = tpl_base(tpl_key)
|
||||
return b if res == DEFAULT_RES else "%s%d" % (b, res)
|
||||
|
||||
|
||||
def deliver_names(tpl_key, res):
|
||||
b = out_base(tpl_key, res)
|
||||
return b + ".png", b + UNC_SUFFIX + ".png"
|
||||
|
||||
|
||||
def prepare_out_dir(root, tpl_key, res, skin_path):
|
||||
"""建成品文件夹并**先把皮肤放进去**(金钻 2026-09-30)。
|
||||
文件夹名 = 成品名(`飞跃樱花林` / `飞跃樱花林1080`);重名加 -2/-3,
|
||||
同一个模板被买两次不能互相覆盖。返回 (文件夹, 成品基名)。"""
|
||||
base = out_base(tpl_key, res)
|
||||
d = os.path.join(root, base)
|
||||
n = 2
|
||||
while os.path.exists(d):
|
||||
d = os.path.join(root, "%s-%d" % (base, n))
|
||||
n += 1
|
||||
os.makedirs(d, exist_ok=True)
|
||||
if skin_path and os.path.exists(skin_path):
|
||||
dst = os.path.join(d, os.path.basename(skin_path))
|
||||
if os.path.abspath(dst) != os.path.abspath(skin_path):
|
||||
shutil.copy2(skin_path, dst)
|
||||
return d, base
|
||||
|
||||
|
||||
LOCK_PORT = 8083 # 单实例锁
|
||||
LOG = os.path.join(HERE, "worker.log")
|
||||
|
||||
|
||||
def log(*a):
|
||||
line = "[%s] %s" % (datetime.now().strftime("%Y-%m-%d %H:%M:%S"), " ".join(str(x) for x in a))
|
||||
print(line, flush=True)
|
||||
try:
|
||||
if os.path.exists(LOG) and os.path.getsize(LOG) > 2 * 1024 * 1024:
|
||||
shutil.move(LOG, LOG + ".old")
|
||||
with open(LOG, "a", encoding="utf-8") as f:
|
||||
f.write(line + "\n")
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
|
||||
def load_cfg():
|
||||
p = os.path.join(HERE, "config.json")
|
||||
if os.path.exists(p):
|
||||
try:
|
||||
CFG.update(json.load(open(p, encoding="utf-8")))
|
||||
except Exception as e:
|
||||
log("config.json 读取失败:%r(用默认值继续)" % e)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- HTTP
|
||||
def http(path, obj=None, raw=False, timeout=120, tries=1, gap=5):
|
||||
"""调服务器。tries>1 时网络抖动会自己重试。
|
||||
|
||||
⚠️ 2026-09-30 晚实踩:原来只接 HTTPError,**网络层的异常直接抛出去**。
|
||||
那次是无压缩(约 10MB)回传时 TLS 断了一下(`EOF occurred in violation of protocol`),
|
||||
异常一路冒到轮询循环 → 这一单**剩下的模板全没渲**,还得等 45 分钟退回重来。
|
||||
所以:网络异常要么在重试里消化掉,要么返回「失败」让调用方按普通失败处理。
|
||||
"""
|
||||
url = CFG["server"].rstrip("/") + path
|
||||
data = json.dumps(obj).encode("utf-8") if obj is not None else None
|
||||
req = urllib.request.Request(url, data=data, method="POST" if data else "GET")
|
||||
req.add_header("Content-Type", "application/json")
|
||||
req.add_header("X-Worker-Token", CFG.get("token") or "")
|
||||
last = None
|
||||
for i in range(max(1, tries)):
|
||||
try:
|
||||
with urllib.request.urlopen(req, timeout=timeout) as r:
|
||||
body = r.read()
|
||||
return (r.status, body if raw else json.loads(body))
|
||||
except urllib.error.HTTPError as e:
|
||||
return (e.code, e.read() if raw else {"ok": False, "error": "HTTP %d" % e.code})
|
||||
except (urllib.error.URLError, OSError, ValueError) as e:
|
||||
last = e
|
||||
if i < tries - 1:
|
||||
log("网络异常,%ds 后重试(第 %d/%d 次):%r" % (gap, i + 1, tries, e))
|
||||
time.sleep(gap)
|
||||
return (0, {"ok": False, "error": "网络异常 %r" % last})
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- Blender
|
||||
def find_blender():
|
||||
if CFG.get("blender") and os.path.exists(CFG["blender"]):
|
||||
return CFG["blender"]
|
||||
cands = []
|
||||
for base in (r"<PROGRAM_DIR>", r"<PROGRAM_DIR>",
|
||||
r"<PROGRAM_DIR>", r"<WIN_DIR>", r"<WIN_DIR>"):
|
||||
if os.path.isdir(base):
|
||||
for d in sorted(os.listdir(base), reverse=True):
|
||||
p = os.path.join(base, d, "blender.exe")
|
||||
if os.path.exists(p):
|
||||
cands.append(p)
|
||||
cands.append(os.path.join(base, d, "blender-launcher.exe"))
|
||||
for p in cands:
|
||||
if p.lower().endswith("blender.exe") and os.path.exists(p):
|
||||
return p
|
||||
return ""
|
||||
|
||||
|
||||
# ===== 序号登记(金钻 2026-09-30:专门用一个文件存,不依赖文件夹)=====
|
||||
# ⚠️ 以前靠扫文件夹名推序号 —— 文件夹一改名/挪地方序号就乱。
|
||||
# 现在序号写在登记文件里,文件夹怎么动都不影响连续性。
|
||||
SEQ_FILE_NAME = "_序号登记.json"
|
||||
|
||||
|
||||
def seq_file():
|
||||
return os.path.join(CFG["archive"], SEQ_FILE_NAME)
|
||||
|
||||
|
||||
def _seed_seq_from_folders():
|
||||
"""登记文件第一次用(或丢了)时,从老文件夹名估个起点,别从 001 重来。"""
|
||||
n = 0
|
||||
try:
|
||||
for name in os.listdir(CFG["archive"]):
|
||||
m = re.fullmatch(r"(\d{3})", name)
|
||||
if m:
|
||||
n = max(n, int(m.group(1)))
|
||||
except OSError:
|
||||
pass
|
||||
return n
|
||||
|
||||
|
||||
def next_seq(rec=None):
|
||||
"""领一个新序号,写进登记文件。返回整数序号。
|
||||
|
||||
登记明细里记下:时间 / 来源 / 订单号 / 兑换码 / 模板 / 成品文件夹 / 分辨率 ——
|
||||
「看号就知道是第几单、谁的单、出的哪个模板」。
|
||||
写文件用 tmp + os.replace 原子替换,断电也不会写坏。
|
||||
"""
|
||||
os.makedirs(CFG["archive"], exist_ok=True)
|
||||
p = seq_file()
|
||||
d = {}
|
||||
if os.path.exists(p):
|
||||
try:
|
||||
with open(p, encoding="utf-8") as f:
|
||||
d = json.load(f) or {}
|
||||
except Exception as e:
|
||||
log("⚠️ 序号登记文件读不动(%r),按 0 起算" % e)
|
||||
d = {}
|
||||
if not isinstance(d.get("last"), int):
|
||||
d["last"] = _seed_seq_from_folders()
|
||||
d["_起点说明"] = "首次创建:按已有文件夹名估的起点"
|
||||
n = int(d["last"]) + 1
|
||||
d["last"] = n
|
||||
r = dict(rec or {})
|
||||
r.setdefault("序号", n)
|
||||
r.setdefault("时间", time.strftime("%Y-%m-%d %H:%M:%S"))
|
||||
d.setdefault("明细", []).append(r)
|
||||
d["明细"] = d["明细"][-1000:] # 只留最近 1000 条,别把文件撑大
|
||||
tmp = p + ".tmp"
|
||||
try:
|
||||
with open(tmp, "w", encoding="utf-8") as f:
|
||||
json.dump(d, f, ensure_ascii=False, indent=1)
|
||||
os.replace(tmp, p)
|
||||
except OSError as e:
|
||||
log("⚠️ 序号登记写失败:%r" % e)
|
||||
return n
|
||||
|
||||
|
||||
# ===== Blender 看门狗(金钻 2026-09-30:卡到十分钟就关掉重开再渲)=====
|
||||
BLENDER_TIMEOUT = 600 # 单张 10 分钟;4096 实测 ~10 分钟内,够用
|
||||
BLENDER_RETRY = 1 # 卡住就杀掉重开一次;再卡就判失败,别死循环
|
||||
|
||||
|
||||
def _kill_tree(proc):
|
||||
"""连子进程一起杀。Blender 会开子进程,只杀父进程会留孤儿继续吃 GPU。
|
||||
|
||||
Windows 用 taskkill /T 杀整棵树;其它平台 fallback 到 proc.kill()
|
||||
—— 这样在 Linux 上也能跑测试。
|
||||
"""
|
||||
if os.name == "nt":
|
||||
try:
|
||||
subprocess.run(["taskkill", "/F", "/T", "/PID", str(proc.pid)],
|
||||
capture_output=True, timeout=30)
|
||||
return
|
||||
except Exception as e:
|
||||
log("⚠️ taskkill 失败 pid=%s:%r(改用 proc.kill)" % (proc.pid, e))
|
||||
# POSIX:连**整个进程组**一起杀。
|
||||
# 只 kill 父进程的话,子进程还活着占着 stdout 管道 → communicate() 白等 30 秒(实测踩过)
|
||||
try:
|
||||
os.killpg(os.getpgid(proc.pid), signal.SIGKILL)
|
||||
except Exception:
|
||||
try:
|
||||
proc.kill()
|
||||
except Exception as e:
|
||||
log("⚠️ 杀进程失败 pid=%s:%r" % (proc.pid, e))
|
||||
|
||||
|
||||
SKIN_DIAG = [] # 最近几次渲染里"皮肤节点认了谁"的日志 —— 回传服务器,云端直接查
|
||||
# (2026-10-01:空艇模板渲染出默认皮肤,只能远程到宿主翻日志才知道它挑了谁)
|
||||
|
||||
|
||||
def note_skin_diag(tpl_key, out):
|
||||
"""从 Blender 输出里挑出与"皮肤节点判定"有关的几行,留着回传。"""
|
||||
for ln in (out or "").splitlines():
|
||||
s = ln.strip()
|
||||
if ("皮肤节点" in s) or ("贴图节点候选" in s) or s.startswith("皮肤 "):
|
||||
SKIN_DIAG.append("[%s] %s" % (tpl_key, s[:220]))
|
||||
if len(SKIN_DIAG) > 12:
|
||||
del SKIN_DIAG[:-12]
|
||||
|
||||
|
||||
# 从 Blender 的一行输出里抠进度:`Sample 12/128`、`Rendered 3/8 Tiles`… 抠不到就返回 None
|
||||
_PCT_RES = [
|
||||
re.compile(r"(?:Sample|Path Tracing Sample|Rendered|Rendering|Tiles)\D{0,20}?(\d+)\s*/\s*(\d+)"),
|
||||
re.compile(r"(\d+)\s*/\s*(\d+)\s*(?:tiles|samples)", re.I),
|
||||
]
|
||||
|
||||
|
||||
def blender_pct(line):
|
||||
"""Blender 那行输出 → 百分比;认不出来就 None(金钻 2026-10-04:进度要给买家看)。"""
|
||||
if not line or "/" not in line:
|
||||
return None
|
||||
for rx in _PCT_RES:
|
||||
m = rx.search(line)
|
||||
if not m:
|
||||
continue
|
||||
try:
|
||||
a, b = int(m.group(1)), int(m.group(2))
|
||||
except ValueError:
|
||||
continue
|
||||
if b > 0 and 0 <= a <= b:
|
||||
return int(a * 100.0 / b)
|
||||
return None
|
||||
|
||||
|
||||
def run_blender(cmd, timeout=None, retry=None, on_progress=None):
|
||||
"""带超时看门狗的渲染。返回 (ok, 输出尾巴, 耗时秒, 说明)。
|
||||
|
||||
「关掉重新打开」= 直接重跑同一条命令 —— 工程每次都是**从干净模板新复制的副本**,
|
||||
所以重开等于全新开始,能救掉偶发卡死(GPU 驱动抽风、贴图读挂等)。
|
||||
|
||||
on_progress(pct):渲的过程中有进度就回调(金钻 2026-10-04)。它在**读输出的线程**上跑,
|
||||
所以:不许抛异常、不许阻塞太久(回调里已经有节流 + 超时)。
|
||||
"""
|
||||
timeout = timeout or BLENDER_TIMEOUT
|
||||
retry = BLENDER_RETRY if retry is None else retry
|
||||
t_all = time.time()
|
||||
last = ""
|
||||
for attempt in range(retry + 1):
|
||||
try:
|
||||
kw = {}
|
||||
if os.name != "nt":
|
||||
kw["start_new_session"] = True # 自成进程组,超时能整组杀干净
|
||||
p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
|
||||
text=True, encoding="utf-8", errors="replace", bufsize=1, **kw)
|
||||
except OSError as e:
|
||||
return False, "", time.time() - t_all, "启动 Blender 失败:%r" % e
|
||||
# 输出交给**独立线程**读:一边攒全文,一边挑进度行回调。
|
||||
# 主线程只负责等它结束 / 超时 —— 超时看门狗的行为和以前完全一样。
|
||||
buf = []
|
||||
|
||||
def _pump():
|
||||
try:
|
||||
tail = ""
|
||||
while True:
|
||||
chunk = p.stdout.read(512)
|
||||
if not chunk:
|
||||
break
|
||||
tail += chunk
|
||||
# ⚠️ Blender 的进度条是**回车原地刷新**的(`... Sample 4/128\r`),
|
||||
# 按"行"读(for line in stdout)压根读不到 —— 2026-10-04 金钻要
|
||||
# 「按 blender 的完成度」才发现。所以这里 \n 和 \r 都当分隔符切。
|
||||
while True:
|
||||
cuts = [i for i in (tail.find("\n"), tail.find("\r")) if i >= 0]
|
||||
if not cuts:
|
||||
break
|
||||
i = min(cuts)
|
||||
line, tail = tail[:i + 1], tail[i + 1:]
|
||||
buf.append(line)
|
||||
if on_progress:
|
||||
pct = blender_pct(line)
|
||||
if pct is not None:
|
||||
try:
|
||||
on_progress(pct)
|
||||
except Exception:
|
||||
pass
|
||||
if tail:
|
||||
buf.append(tail)
|
||||
except Exception:
|
||||
pass
|
||||
th = threading.Thread(target=_pump, daemon=True)
|
||||
th.start()
|
||||
try:
|
||||
p.wait(timeout=timeout)
|
||||
th.join(timeout=15)
|
||||
out = "".join(buf)
|
||||
if p.returncode == 0:
|
||||
return True, out or "", time.time() - t_all, ""
|
||||
# ⚠️ 以前只留 400 字,结果失败时看不到自己打的 FATAL 行(2026-10-01 查空艇报错时踩到)
|
||||
_txt = (out or "").strip()
|
||||
_keys = [ln.strip() for ln in _txt.splitlines()
|
||||
if any(k in ln for k in ("FATAL", "MAKE-ORDER", "Error", "Traceback", "错误"))]
|
||||
last = "Blender 退出码 %s:%s" % (
|
||||
p.returncode,
|
||||
(" | ".join(_keys[-6:]) + " | " if _keys else "") + _txt[-1200:])
|
||||
log("渲染失败:%s" % last)
|
||||
except subprocess.TimeoutExpired:
|
||||
log("⚠️ 渲染卡住超过 %d 秒 —— 杀掉,重新打开再渲" % timeout)
|
||||
_kill_tree(p)
|
||||
try:
|
||||
p.wait(timeout=10) # 收尸;整组杀过就该立刻返回
|
||||
except Exception:
|
||||
pass
|
||||
last = "渲染卡住超过 %d 秒(已杀掉重开)" % timeout
|
||||
if attempt < retry:
|
||||
log("↻ 重开渲染(第 %d 次尝试)" % (attempt + 2))
|
||||
return False, "", time.time() - t_all, last
|
||||
|
||||
|
||||
def render_one(tpl_key, skin_path, order_meta, res=DEFAULT_RES, arm="auto", on_progress=None):
|
||||
"""渲染一张,返回 (成功?, png路径 或 错误信息)
|
||||
|
||||
arm:这张皮肤的臂型(auto/classic/slim)。多皮肤单里**每张皮肤各自一个臂型**,
|
||||
由调用方从服务器给的皮肤清单里带下来(金钻 2026-10-01:以前压根没传,买家手改无效)。
|
||||
"""
|
||||
fname = TEMPLATES.get(tpl_key)
|
||||
if not fname:
|
||||
return False, "未知模板 key:%s" % tpl_key
|
||||
tpl = os.path.join(CFG["tpl_root"], fname)
|
||||
if not os.path.exists(tpl):
|
||||
return False, "模板文件不存在:%s" % tpl
|
||||
blender = find_blender()
|
||||
if not blender:
|
||||
return False, "找不到 blender.exe(请在 config.json 里指定 blender 路径)"
|
||||
if not os.path.exists(CFG["make_order"]):
|
||||
return False, "找不到 make_order.py:%s" % CFG["make_order"]
|
||||
|
||||
out_name = tpl_base(tpl_key)
|
||||
# 文件夹用成品名,皮肤先放进去;工程走临时目录,渲完删(金钻:不留 .blend)
|
||||
order_dir, base = prepare_out_dir(CFG["archive"], tpl_key, res, skin_path)
|
||||
cmd = [blender, "-b", "--factory-startup", "--python", CFG["make_order"], "--",
|
||||
"--template", tpl, "--skin", skin_path, "--arm", arm or "auto",
|
||||
"--orders-dir", CFG["archive"], "--out-dir", order_dir, "--res", str(int(res))]
|
||||
# 某个模板的皮肤材质名固定不下来时,可以在 config.json 里钉死:
|
||||
# "skin_materials": {"airship": "材质名"}
|
||||
# (2026-10-01:空艇模板自动找皮肤节点找错,先留好这个后门口子)
|
||||
_sm = (CFG.get("skin_materials") or {}).get(tpl_key)
|
||||
if _sm:
|
||||
cmd += ["--skin-material", _sm]
|
||||
log("渲染 %s(模板 %s,臂型 %s)" % (tpl_key, fname, arm or "auto"))
|
||||
okr, tail, dt, note = run_blender(cmd, on_progress=on_progress)
|
||||
note_skin_diag(tpl_key, tail) # 不管成没成,先把"皮肤节点认了谁"记下来
|
||||
if not okr:
|
||||
return False, note
|
||||
|
||||
# 找成品:优先 <名称>.png(命名规则见 out_base),其次目录里最新的 png
|
||||
cand = os.path.join(order_dir, base + ".png")
|
||||
if not os.path.exists(cand):
|
||||
pngs = [f for f in os.listdir(order_dir) if f.lower().endswith(".png")]
|
||||
pngs = [f for f in pngs if "无压缩" not in f and f != "1000.png"] or pngs
|
||||
if not pngs:
|
||||
return False, "渲染完成但没找到 png(看 %s)" % order_dir
|
||||
cand = os.path.join(order_dir, sorted(pngs, key=lambda f: os.path.getmtime(
|
||||
os.path.join(order_dir, f)))[-1])
|
||||
|
||||
# 渲染成功才领序号(失败的图不占号),并登记进专门的文件
|
||||
seq = next_seq({
|
||||
"来源": "网页订单",
|
||||
"订单号": order_meta.get("oid"),
|
||||
"兑换码": order_meta.get("codes") or [],
|
||||
"模板": out_name,
|
||||
"成品文件夹": os.path.basename(order_dir),
|
||||
"分辨率": res,
|
||||
"耗时秒": round(dt, 1),
|
||||
})
|
||||
|
||||
# 金钻要的留档:时间 / 序号 / 兑换码
|
||||
info = {
|
||||
"序号": seq,
|
||||
"订单号": order_meta.get("oid"),
|
||||
"兑换码": order_meta.get("codes") or [],
|
||||
"模板": out_name,
|
||||
"模板key": tpl_key,
|
||||
"成品文件夹": os.path.basename(order_dir),
|
||||
"分辨率": res,
|
||||
"皮肤文件": "skin.png",
|
||||
"客户提交时间": order_meta.get("created"),
|
||||
"渲染完成时间": datetime.now().isoformat(timespec="seconds"),
|
||||
"渲染耗时秒": round(dt, 1),
|
||||
"手臂规格": (arm if arm and arm != "auto" else order_meta.get("arm")),
|
||||
"条款版本": order_meta.get("terms_v") or TERMS_VERSION,
|
||||
}
|
||||
try:
|
||||
with open(os.path.join(order_dir, "订单信息.json"), "w", encoding="utf-8") as f:
|
||||
json.dump(info, f, ensure_ascii=False, indent=1)
|
||||
except OSError as e:
|
||||
log("写 订单信息.json 失败:%r" % e)
|
||||
# 无压缩版(make_order 默认就会生成):<名称>无压缩版.png
|
||||
unc = os.path.join(order_dir, out_base(tpl_key, res) + UNC_SUFFIX + ".png")
|
||||
if not os.path.exists(unc):
|
||||
cands = [f for f in sorted(os.listdir(order_dir))
|
||||
if f.lower().endswith(".png") and UNC_SUFFIX in f]
|
||||
unc = os.path.join(order_dir, cands[0]) if cands else None
|
||||
if not unc or not os.path.exists(unc):
|
||||
unc = None
|
||||
log("⚠️ 无压缩版没生成,这次只交标准版")
|
||||
log("完成 %s → %s(序号 %03d,%.1fs,%s)" % (tpl_key, cand, seq, dt, "两张" if unc else "一张"))
|
||||
return True, {"std": cand, "unc": unc, "seq": seq, "sec": round(dt, 1)}
|
||||
# seq = 留档序号(小票/订单信息里印);sec = 这张渲了多久(服务器拿它估下一单的时间)
|
||||
|
||||
|
||||
def deliver_names_for(skin_i, tk, res, dedup=True):
|
||||
"""第 skin_i 张皮肤、模板 tk 的交付名。
|
||||
|
||||
⚠️ 只有**同一个模板被多张皮肤用到**时才需要加 -2/-3(不加会在服务器同一个目录里互相覆盖)。
|
||||
不同皮肤用不同模板(金钻的常见用法:A 出麦田、B 出樱花)就保持干净的名字。
|
||||
"""
|
||||
sn, un = deliver_names(tk, res)
|
||||
if skin_i <= 0 or not dedup:
|
||||
return sn, un
|
||||
k = "-%d" % (skin_i + 1)
|
||||
|
||||
def ins(n):
|
||||
return (n[:-4] + k + ".png") if n.lower().endswith(".png") else (n + k)
|
||||
return ins(sn), ins(un)
|
||||
|
||||
|
||||
def handle_order(o):
|
||||
oid = o["oid"]
|
||||
tpls = o.get("templates") or []
|
||||
order_res = int(o.get("res") or CFG.get("res") or DEFAULT_RES)
|
||||
log("领到订单 %s:%d 张 %s" % (oid, len(tpls), ",".join(tpls)))
|
||||
|
||||
# ---- 皮肤清单(金钻 2026-10-01:多皮肤单 = **每张皮肤 × 每个模板**出图)----
|
||||
# 服务器在 /claim 里把清单带下来:[{id,fileName,arm}]。老单没有就按 1 张算。
|
||||
skins = o.get("skins") or [{"id": "s1", "fileName": "skin.png", "arm": "auto"}]
|
||||
tpls = o.get("templates") or []
|
||||
order_res = int(o.get("res") or CFG.get("res") or DEFAULT_RES)
|
||||
# 只重渲勾选的那几张(金钻 2026-10-04:「不需要重渲的就不用再重渲了,费力不讨好」)
|
||||
# 服务器给了清单就只干这几个模板 —— 换皮肤时清单是空的,那就还是整单重出。
|
||||
redo_tpls = [t for t in (o.get("redo_tpls") or []) if t]
|
||||
if redo_tpls:
|
||||
for sk in skins:
|
||||
sk["tpls"] = [t for t in (sk.get("tpls") or tpls) if t in redo_tpls]
|
||||
log("这一单只重渲:%s" % "、".join(redo_tpls))
|
||||
# ⚠️ 张数 = **各皮肤自己挑的模板加起来**(金钻 2026-10-01:不是乘法)
|
||||
# ⚠️ 只重渲一部分时,total 要**加上保留下来的那几张** —— 服务器是按 total 判断"收满了"的,
|
||||
# 少了这个数就会在最后一张还没传完时提前标完成(2026-10-04 自测踩到,少了一张无压缩版)。
|
||||
_keep = int(o.get("keep_n") or 0) if redo_tpls else 0
|
||||
plan = _keep + sum(len(sk.get("tpls") or tpls) for sk in skins) * 2
|
||||
log("领到订单 %s:%d 张皮肤,共 %d 张图(%s)"
|
||||
% (oid, len(skins), plan // 2,
|
||||
"; ".join("%s→%s" % (sk.get("fileName") or "?", "、".join(sk.get("tpls") or tpls))
|
||||
for sk in skins)))
|
||||
|
||||
work = os.path.join(HERE, "work")
|
||||
os.makedirs(work, exist_ok=True)
|
||||
|
||||
# 同一个模板被多张皮肤用到 → 交付名才加 -2/-3(不同模板就保持干净名字)
|
||||
cnt = {}
|
||||
for _sk in skins:
|
||||
for _tk in (_sk.get("tpls") or tpls):
|
||||
cnt[_tk] = cnt.get(_tk, 0) + 1
|
||||
dup_tpls = set(k for k, n in cnt.items() if n > 1)
|
||||
|
||||
# ---- 进度上报(金钻 2026-10-04:买家要看得见渲到哪了)----
|
||||
# 报进度**绝不能影响出图**:节流 2 秒一次,失败一律吞掉。
|
||||
def report_progress(idx, total, pct, tpl=""):
|
||||
try:
|
||||
http("/progress", {"oid": oid, "idx": idx, "total": total,
|
||||
"pct": pct, "tpl": tpl}, timeout=20)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
ok_n, errs = 0, []
|
||||
img_i = 0
|
||||
for si, sk in enumerate(skins):
|
||||
sid = sk.get("id") or ("s%d" % (si + 1))
|
||||
# 每张皮肤各自下载、各自臂型(A 可能粗臂、B 可能细臂)
|
||||
skin = os.path.join(work, "skin_%s_%s.png" % (oid, sid))
|
||||
st, data = http("/skin/%s/%s" % (oid, sid), raw=True, timeout=60)
|
||||
if st != 200 or not data:
|
||||
errs.append("皮肤 %s:服务器取皮肤失败 HTTP %s" % (sid, st))
|
||||
log("皮肤 %s 取不下来 HTTP %s" % (sid, st))
|
||||
continue
|
||||
with open(skin, "wb") as f:
|
||||
f.write(data)
|
||||
arm = (sk.get("arm") or "auto")
|
||||
|
||||
# 这张皮肤**只出它自己挑的模板**(没写就退回订单级那份,兼容老单)
|
||||
for tk in (sk.get("tpls") or tpls):
|
||||
img_i += 1
|
||||
_last = [0.0]
|
||||
|
||||
def _prog(pct, _tk=tk, _i=img_i, _last=_last):
|
||||
t = time.time()
|
||||
if pct < 100 and t - _last[0] < 2.0: # 节流:2 秒最多报一次
|
||||
return
|
||||
_last[0] = t
|
||||
report_progress(_i, plan // 2, pct, _tk)
|
||||
|
||||
report_progress(img_i, plan // 2, 0, tk) # 这张开始了
|
||||
try:
|
||||
ok, res = render_one(tk, skin, o, order_res, arm=arm, on_progress=_prog)
|
||||
except subprocess.TimeoutExpired:
|
||||
ok, res = False, "渲染超时(看门狗已重开过一次仍卡住)"
|
||||
except Exception as e:
|
||||
ok, res = False, "异常 %r" % e
|
||||
if not ok:
|
||||
errs.append("%s(皮肤%d):%s" % (tk, si + 1, res))
|
||||
log("失败 %s" % res)
|
||||
continue
|
||||
# 一张模板交两个文件:标准压缩 + 无压缩版(金钻:两张都发顾客)
|
||||
sn, un = deliver_names_for(si, tk, order_res, dedup=(tk in dup_tpls))
|
||||
files = [("标准压缩", sn, res.get("std")),
|
||||
("无压缩(16bit)", un, res.get("unc"))]
|
||||
for kind, name, path in files:
|
||||
if not path:
|
||||
continue
|
||||
try:
|
||||
with open(path, "rb") as f:
|
||||
png = base64.b64encode(f.read()).decode()
|
||||
except OSError as e:
|
||||
errs.append("%s(%s):读图失败 %r" % (tk, kind, e))
|
||||
continue
|
||||
# 一次一个文件回传;total = 这一单最终会交回的文件总数
|
||||
# tries=3:图上一次上传要几 MB~十几 MB,网络抖一下很常见,别为这个白渲一遍
|
||||
st, j = http("/finish", {"oid": oid, "total": plan,
|
||||
"results": [{"tpl": tk, "name": name, "png": png,
|
||||
"kind": kind, "skin": sid,
|
||||
# 耗时只跟「标准压缩」报一次:两个文件报两遍会把样本记重
|
||||
"sec": (res.get("sec") if kind == "标准压缩" else None),
|
||||
"seq": res.get("seq")}]},
|
||||
timeout=300, tries=3, gap=8)
|
||||
if st == 200 and j.get("ok"):
|
||||
log("回传 %s 皮肤%s [%s](服务器已收 %s / 计划 %d)"
|
||||
% (tk, sid, kind, j.get("n"), plan))
|
||||
else:
|
||||
errs.append("%s-%s:回传失败 %s" % (tk, kind, (j or {}).get("error")))
|
||||
ok_n += 1
|
||||
|
||||
if ok_n == 0:
|
||||
http("/fail", {"oid": oid, "note": ("全部渲染失败:" + ";".join(errs))[:280],
|
||||
"diag": SKIN_DIAG[:8], "log_tail": "\n".join(errs)[-3800:]})
|
||||
log("订单 %s 全部失败" % oid)
|
||||
return
|
||||
# ⚠️ 有失败时必须有始有终:否则 files < total,单子会永远卡在 working,
|
||||
# 45 分钟后被当成"渲染机中断"退回队列 → 无限重试。这里显式收单。
|
||||
http("/finish", {"oid": oid, "close": True, "diag": SKIN_DIAG[:8],
|
||||
"note": ("部分失败:" + ";".join(errs))[:280] if errs else "",
|
||||
"results": []}, tries=3, gap=8)
|
||||
log("订单 %s 处理完毕:成功 %d/%d%s" % (oid, ok_n, len(tpls), "(有失败)" if errs else ""))
|
||||
|
||||
|
||||
def single_instance():
|
||||
s = socket.socket()
|
||||
try:
|
||||
s.bind(("localhost", LOCK_PORT))
|
||||
s.listen(1)
|
||||
return s
|
||||
except OSError:
|
||||
return None
|
||||
|
||||
|
||||
def main():
|
||||
load_cfg()
|
||||
once = "--once" in sys.argv # 只跑一轮就退出(手动补单 / 测试用)
|
||||
if not once:
|
||||
lock = single_instance()
|
||||
if not lock:
|
||||
log("已经有一个 worker 在跑了,这次退出")
|
||||
return
|
||||
log("渲染机上线 | 服务器 %s | 模板目录 %s | 留档 %s"
|
||||
% (CFG["server"], CFG["tpl_root"], CFG["archive"]))
|
||||
host = socket.gethostname()
|
||||
# 心跳(在线检查)与领单**分开计时**:
|
||||
# 心跳 = 服务器判断"渲染机还在不在"的唯一依据,也是唯一会造成误判的地方;
|
||||
# 领单 = 买家体验,慢一分钟买家就多等一分钟。
|
||||
# 默认心跳 **600 秒(10 分钟)**(金钻 9-30:有人来了网页会立刻查一次,所以不用频繁上报)。
|
||||
# ⚠️ 代价:渲染机真的挂了,最长要 25 分钟才判定为离线(见服务器 OFFLINE_AFTER)。
|
||||
# 启动时会立刻发一次心跳,所以"金钻刚开机"这种情形是即时准的。
|
||||
hb_every = int(CFG.get("hb_every") or 600) # 在线检查 10 分钟一次(金钻 9-30 定)
|
||||
poll = int(CFG.get("poll") or 20)
|
||||
# ⚠️⚠️ 心跳必须**自己一个线程**(金钻 2026-10-01 反馈:「开着电脑还显示设备离线,刷几次才正常」)。
|
||||
# 原来心跳和领单/渲染挤在同一个循环里 —— 一渲就是几十秒到十几分钟(4096 要 10 分钟),
|
||||
# 这期间心跳发不出去;要是连着几单、或某次上传卡住,超过服务器 OFFLINE_AFTER(1500 秒)
|
||||
# 就被判「离线」,**电脑明明开着、还在干活**。
|
||||
def hb_loop():
|
||||
while True:
|
||||
try:
|
||||
st, j = http("/hb", {"host": host}, timeout=30)
|
||||
if st != 200:
|
||||
log("心跳失败 HTTP %s" % st)
|
||||
except Exception:
|
||||
log("心跳异常:\n" + traceback.format_exc()[-400:])
|
||||
time.sleep(hb_every)
|
||||
threading.Thread(target=hb_loop, daemon=True).start()
|
||||
while True:
|
||||
try:
|
||||
st, o = http("/claim", {}, timeout=60)
|
||||
if st == 403:
|
||||
log("令牌不对(config.json 里的 token 要跟服务器 worker_token 一致)")
|
||||
time.sleep(300)
|
||||
continue
|
||||
if st == 200 and o.get("order"):
|
||||
handle_order(o["order"])
|
||||
except Exception:
|
||||
log("轮询异常:\n" + traceback.format_exc()[-800:])
|
||||
if once:
|
||||
log("--once:跑完这一轮就退出")
|
||||
return
|
||||
time.sleep(poll)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,185 @@
|
||||
# 交接说明 · 工具后端(渲染机 + 本机开单工具 + 开单后台)
|
||||
|
||||
> **交付方**:苏达(网站运维与技术提供)
|
||||
> **收件方**:外部协作者
|
||||
> **日期**:2026-10-05
|
||||
> **一句话**:这是跑在**店主自己那台 Windows 电脑**上的一整套工具:渲染机、
|
||||
> 局域网开单后台、纯本机开单工具。请你重点看**健壮性与"静默失败"**,
|
||||
> 并给我们**问题分析 + 改正意见**(见最后一节)。
|
||||
|
||||
---
|
||||
|
||||
## 一、这一份是什么
|
||||
|
||||
跟「网站后端」配套的**本地侧**。因为店里那台电脑没有公网入口,所以它**只做出站**:
|
||||
主动来服务器领单、渲染、回传。
|
||||
|
||||
```
|
||||
<WORKER_DIR>\
|
||||
├─ ys_worker.py 渲染机主程序(开机自启的计划任务;轮询领单 → 调 Blender → 回传)
|
||||
├─ ys_admin.py 开单后台(局域网面板:发卡密 / 激活订单 / 免费码),自带 PIN 锁
|
||||
├─ ys_local.py 纯本机开单工具(不联网、不上传、不要卡密;拖皮肤→勾模板→出图)
|
||||
├─ local.html 本机开单工具的页面(ys_local.py 内嵌服务它)
|
||||
├─ make_order.py Blender 出图脚本(渲染机调用它;改模板/分辨率/臂型都在这)
|
||||
├─ install_worker.ps1 / chk_worker.ps1 / pack_archive.ps1
|
||||
└─ run_*.bat / stop_*.bat / open_local.bat / show_log.bat
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 二、技术栈与运行方式
|
||||
|
||||
| 项 | 值 |
|
||||
|---|---|
|
||||
| 语言 / 依赖 | **Python 3,纯标准库**(`ys_admin.py` 连 HTML 都内嵌在单文件里) |
|
||||
| 渲染 | Blender **命令行后台模式**(`-b --factory-startup --python make_order.py`) |
|
||||
| 进程托管 | Windows 计划任务(**开机自启**);面板另有独立计划任务 |
|
||||
| 网络 | **只做出站**(来服务器领单/回传);本机工具与面板只监听本机/局域网 |
|
||||
| 关键约束 | ⚠️ **任何时刻只允许一个 Blender 在跑** —— 同时跑两个会把机器顶满(渲染队列是硬约束,不是优化) |
|
||||
|
||||
---
|
||||
|
||||
## 三、三条链路
|
||||
|
||||
### ① 渲染机(`ys_worker.py`)
|
||||
```
|
||||
每 20s POST /hb(心跳) ← 心跳在**独立线程**里,不然一渲染就发不出去被判离线
|
||||
POST /claim(领单)
|
||||
GET /api/skin/<单号> ← 取买家皮肤(必须带 worker token)
|
||||
Blender 渲染(一张一次 POST /finish)
|
||||
中途每 2s POST /progress ← 抠 Blender 输出的百分比
|
||||
```
|
||||
|
||||
### ② 开单后台(`ys_admin.py`,局域网)
|
||||
四块:① 生成卡密 ② 待激活订单(一键激活进队列)③ 最近卡密 ④ 免费码(福利券)批次管理。
|
||||
**自带 PIN 锁**:首次打开自己设 4~12 位数字,存**加盐 sha256**(不是明文),12 小时免输;
|
||||
校验在服务端,直接打接口也会 401。
|
||||
|
||||
### ③ 纯本机开单(`ys_local.py` + `local.html`,只监听回环)
|
||||
给**平台单**(聊天里成交的买家)用:拖皮肤 → 同一套质检 → 勾模板 → 本机 Blender 出图 → 下载。
|
||||
**不联网、不上传、不要卡密**,所以网站上根本没有入口(避免卡密被暴力试)。
|
||||
|
||||
---
|
||||
|
||||
## 四、几个刻意做出的设计(欢迎质疑)
|
||||
|
||||
| 设计 | 为什么 |
|
||||
|---|---|
|
||||
| 渲染串行(一个队列一个消费线程) | 两个 Blender 同时跑会把机器顶满 |
|
||||
| Blender 超时 600s,卡住就**连整个进程组一起杀**再重跑 | 只杀父进程的话子进程还占着管道,`communicate()` 会白等 30 秒 |
|
||||
| 命名逻辑**只写两处且必须一致**(`make_order.py` 与 `ys_worker.py`) | 散落硬编码过,判过一次 bug |
|
||||
| 未压缩版**不重渲**:从已渲好的渲染结果直接另存 | 省一次完整渲染(一张约 37 秒);失败再回退重渲 |
|
||||
| 质检代码只有一份(前后端共用同一个 js) | 两边判定一旦漂移,会出现「网页说能渲、本机渲不出来」这种最难查的 bug |
|
||||
| 部署脚本**先显式杀旧进程再起新的** | 计划任务的"运行"对已在跑的实例不替换 → 新代码静默不生效 |
|
||||
| 成品不保留 `.blend` 工程 | 太大,磁盘受不住;工程渲完立刻删 |
|
||||
|
||||
---
|
||||
|
||||
## 五、⚠️ 脱敏说明(**这份也不能直接跑**)
|
||||
|
||||
| 类别 | 替换成 |
|
||||
|---|---|
|
||||
| 站点域名 / 支付平台域名 | `shop.example.com` / `pay-platform.example` |
|
||||
| 端口 | 中性数字(**不是真值**) |
|
||||
| 程序 / 数据 / 工作目录 | `<WORKER_DIR>` / `<DATA_DIR>` / `<APP_DIR>` |
|
||||
| Windows 盘符路径 | `<WIN-PATH>` / `<ARCHIVE_DIR>` / `<TOOLS_DIR>` / `<PROGRAM_DIR>` |
|
||||
| 局域网与出口 IP | `<LOCAL-IP>` / `<HOME-LAN-IP>` |
|
||||
| 通配绑定 | `<ALL-INTERFACES>` |
|
||||
| 跳板与密钥文件名 | `<SSH-KEY>` / `<跳板>` |
|
||||
|
||||
**保留未换的**:`localhost`、分辨率常量 `1000/1024/2048/4096`、品牌笔名。
|
||||
|
||||
**包里没有的**:真实卡密/订单/皮肤/成品、两把令牌、模板工程(**模板单独给**,见包根目录说明)、
|
||||
任何密钥凭据、私有仓库地址。
|
||||
|
||||
---
|
||||
|
||||
## 六、⚠️ 已知缺口(我们知道的,不用你重复发现)
|
||||
|
||||
1. **没有内容审核** —— 结构合法的 PNG 但内容违规照样能过(技术拦不住,靠人)。
|
||||
2. **留档只增不减** —— 成品的永久留档目录会慢慢攒满盘。
|
||||
3. **预览水印是"防君子"** —— 512 宽 + 平铺水印,拦不住认真截图去水印的人。
|
||||
4. **渲染机真挂了,最长要 25 分钟才判定离线**(心跳周期 × 容错次数的代价)。
|
||||
|
||||
---
|
||||
|
||||
## 七、⭐ 我们要你交给我们的东西(**这一份的主要目的**)
|
||||
|
||||
同样请回一份 `回执-<你的名字>.md`,含三部分:
|
||||
|
||||
1. **问题分析** —— 你看到的 bug、健壮性问题、坏味道。**特别欢迎**指这几类:
|
||||
- **静默失败**:出错了但看着"一切正常"的地方(我们被这个坑过好几次)
|
||||
- **状态不一致**:显示与真实不一致(比如界面说排队中、实际没领单)
|
||||
- **部署/重启类**:改了不生效、旧进程没替换、两边版本漂移
|
||||
- **并发/时序**:心跳与渲染抢资源、超时与重试互相打架
|
||||
2. **改正意见** —— 每条说清**怎么改 + 代价**。
|
||||
3. **你改了什么** —— 逐条列(同网站后端那份的格式):
|
||||
```
|
||||
文件 / 函数: 为什么改: 改成什么:
|
||||
⚠️ 有没有动接口路径 / 请求响应字段 / 数据格式(动了必须单独标):
|
||||
怎么验证的:
|
||||
```
|
||||
|
||||
**另外请你顺手回答两个具体问题**:
|
||||
- `ys_worker.py` 的**部署不生效**(旧进程还在跑)这类问题,除了"先杀再起",有没有更稳的办法?
|
||||
- 渲染队列现在是**单线程串行**。如果要在一台机器上同时支持多单,
|
||||
你觉得该怎么做才**不会把机器顶满**?(先说方案,不用实现)
|
||||
|
||||
---
|
||||
|
||||
## 八、我们的思路与方法(**请你连这套做法一起评**)
|
||||
|
||||
代码能看出一部分;**为什么这么做、踩过什么坑**,代码里看不到。这一节补上,
|
||||
**希望你连"做法"本身一起挑** —— 整套思路要是错的,比某个函数写错更要紧。
|
||||
|
||||
### 8.1 我们给自己定的硬规矩
|
||||
|
||||
| 规矩 | 为什么 |
|
||||
|---|---|
|
||||
| **机器只做出站**:店里那台没有公网入口,所以服务器从不连它,全靠它自己定时来拉 | 不给家用网络开任何入站口子;代价是"渲染机真挂了,最长要过一会儿才判离线" |
|
||||
| **任何时刻只允许一个渲染在跑** | 两个同时跑会把机器顶满 —— 这是**硬约束不是优化**,所以做成 FIFO 队列 |
|
||||
| **渲染串行、队列单消费者** | 同上;宁可让买家多等,也不让机器崩 |
|
||||
| **命名/路径这类"两边都要知道"的规则只写两处且必须一致** | 散落硬编码过一次,修的时候漏了地方 |
|
||||
| **质检逻辑只有一份,前后端共用** | 两边判定一旦漂移,会出现"网页说能渲、本机渲不出来"这种最难查的 bug |
|
||||
| **不保留巨大的中间产物** | 工程文件渲完立刻删(磁盘受不住);需要保留的从已渲结果直接另存,不重渲一遍 |
|
||||
|
||||
### 8.2 我们干活的方法(改这套工具时照着来)
|
||||
|
||||
1. **长驻进程必须交给任务计划/系统托管**,不能用"临时起一个"。
|
||||
踩过:从远程会话里起的进程,**会话一断就被系统回收** —— 装完看着"已运行",
|
||||
几十秒后就没了,订单干等在队列里没人领。表现是"看起来一切正常"。
|
||||
2. **部署 = 先明确杀掉旧进程,再起新的**。多数"重启/运行"命令对**已在运行的实例不会替换**,
|
||||
于是新代码静默不生效。部署后必须核对**进程的启动时间**,光看"在线"没用(旧进程也报在线)。
|
||||
3. **判断"活没活"要看真实产物**,不看脚本自述。`Set-Content` 类写入要回读、看字节数;
|
||||
端口要真连一次;图要真存在。
|
||||
4. **卡死要连整个进程组一起杀**。只杀父进程的话子进程还占着输出管道,读取方会白等很久
|
||||
(实测:只杀父 → 64 秒才返回;连组杀 → 4 秒)。
|
||||
5. **进度要自己吐日志,并且按 `\r` 和 `\n` 都切**。渲染器的进度条是**原地回车刷新**的,
|
||||
按 `\n` 逐行读会**一条都读不到**(看着像"没有进度",其实进度一直在刷)。
|
||||
6. **每台机器的配置里不放凭据**,凭据由部署流程单独推(密钥与规则分离)。
|
||||
7. **中文不要进 `.bat`**,中文一律放带 BOM 的 `.ps1` 里;编码错了会**连累后面的行**一起崩。
|
||||
|
||||
### 8.3 我们付过学费的坑("不要重复踩"清单)
|
||||
|
||||
- **"改完不生效"是这套系统最高频的坑**,而且从不报错:旧进程在跑、计划任务不替换、
|
||||
两边版本漂移 —— 三种都会表现成"功能没反应"。
|
||||
- **静默半死**:某一步抛异常 → 后面的渲染链全断 → 页面看着"就是没反应",
|
||||
只有开发者控制台才有线索。所以我们加了"出错要能看到原因"的要求。
|
||||
- **从 A 推导出 B 的函数,在别处读 B 之前必须先调一次**(同一个形状我们踩了两次)。
|
||||
- **同名文件被覆盖 + 地址不变 = 用户以为没更新**(缓存/同名双杀)。
|
||||
|
||||
### 8.4 我们最想要你评的三件"做法"
|
||||
|
||||
1. **部署不生效**这类问题,除了"先杀再起",**有没有更稳的机制**?
|
||||
2. **单机多单**:现在是严格串行。如果要在同一台机器上支持多单,你会怎么设计才**不会把机器顶满**?
|
||||
3. **"纯标准库单文件"**这套(零依赖零安装、小机器跑得动)换你你会不会换技术栈?请直说。
|
||||
|
||||
---
|
||||
|
||||
## 九、边界
|
||||
|
||||
- **私有交付,请勿外传 / 勿公开 / 勿镜像**。
|
||||
- 占位值保持原样,**不要**替换成真实地址再交回来。
|
||||
- 你可以自由重构,但**动了接口/数据格式要按第 7 节单独标出来** ——
|
||||
这套工具跟服务器那份代码是**两台机器上各一份**,不同步会静默坏掉。
|
||||
- 有看不懂的先问再改,别猜。
|
||||
@@ -0,0 +1,100 @@
|
||||
# 部署层 · 反向代理片段(脱敏版)
|
||||
|
||||
> 后端**只绑本机回环**,对外全部由 nginx 反代。这一份是跟 `/order/` 相关的路由与限流,
|
||||
> 给你看**路由是怎么接的、限额是怎么设的**。值已按脱敏规则替换,**照形状看,别照字面抄**。
|
||||
|
||||
---
|
||||
|
||||
## 一、限流区(定义在 nginx 的 http 层)
|
||||
|
||||
```nginx
|
||||
# 下单相关:一般接口 90 次/分钟,提交接口单独收紧到 10 次/分钟
|
||||
limit_req_zone $binary_remote_addr zone=<ZONE_ORDER>:1m rate=90r/m;
|
||||
limit_req_zone $binary_remote_addr zone=<ZONE_SUBMIT>:1m rate=10r/m;
|
||||
```
|
||||
|
||||
**为什么给提交接口单独一条**:它是唯一会**收上传**的入口,也是最值得刷的入口。
|
||||
别的接口刷快一点无所谓(就是查状态),提交接口必须压住。
|
||||
|
||||
---
|
||||
|
||||
## 二、`/order/api/` 的路由
|
||||
|
||||
```nginx
|
||||
# ① 提交接口:单独限流 + 单独放宽请求体
|
||||
location = /order/api/submit {
|
||||
limit_req zone=<ZONE_SUBMIT> burst=5 nodelay;
|
||||
limit_req_status 429;
|
||||
client_max_body_size 4m; # 皮肤是 base64 进来的
|
||||
proxy_pass http://localhost:<PORT>/api/submit;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr; # 后端要拿它做「单 IP 限单」
|
||||
proxy_read_timeout 120s;
|
||||
add_header Cache-Control "no-store" always;
|
||||
}
|
||||
|
||||
# ② 回传接口:**单独一条**,因为成品一张 1~3MB(base64 后更大)
|
||||
# ⚠️ nginx 的 `location =` 精确匹配**优先于**前缀匹配 ——
|
||||
# 想只给这一个路径放宽体积,不能靠下面那条前缀规则
|
||||
location = /order/api/finish {
|
||||
limit_req zone=<ZONE_ORDER> burst=40 nodelay;
|
||||
limit_req_status 429;
|
||||
client_max_body_size 16m;
|
||||
proxy_pass http://localhost:<PORT>/api/finish;
|
||||
# ...
|
||||
}
|
||||
|
||||
# ③ 其余接口
|
||||
location /order/api/ {
|
||||
limit_req zone=<ZONE_ORDER> burst=40 nodelay;
|
||||
limit_req_status 429;
|
||||
proxy_pass http://localhost:<PORT>/api/;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
# ...
|
||||
}
|
||||
```
|
||||
|
||||
⚠️ **打包下载(zip)那条要另外配**:`proxy_buffering off` + 更长的 `proxy_read_timeout`,
|
||||
因为它是**先落临时文件再边读边发**的,不能在 nginx 这层再缓存一份(小机器内存受不住)。
|
||||
|
||||
---
|
||||
|
||||
## 三、买家那边的路由(订单链接)
|
||||
|
||||
```nginx
|
||||
location ~ "^/order/[A-Za-z0-9]{6,16}$" {
|
||||
try_files /order/index.html =404;
|
||||
add_header Cache-Control "no-store" always;
|
||||
add_header X-Robots-Tag "noindex, nofollow, noarchive" always;
|
||||
}
|
||||
|
||||
# 兜底:/order/ 下面找不到的路径一律给下单页,**绝不给 404**
|
||||
location /order/ {
|
||||
try_files $uri $uri/ /order/index.html;
|
||||
add_header Cache-Control "no-store" always;
|
||||
add_header X-Robots-Tag "noindex, nofollow, noarchive" always;
|
||||
}
|
||||
```
|
||||
|
||||
**这两条的用意,请你连做法一起评**:
|
||||
|
||||
1. **`^/order/<6~16位>` 这条必须有**。买家拿到的是 `/order/<订单号>?t=<取件码>`,
|
||||
没有这条路由会掉到主站规则**直接 404** —— 而买家一关页面就**再也找不回订单**。
|
||||
(页面文案还写着"请记下订单号用于查询下载",那就成了骗人。)
|
||||
2. **兜底那条绝不能返回 404**。买家从聊天软件复制链接**常夹进不可见字符**
|
||||
(实测踩到:路径里多了个零宽空格 → 404),看着就像**网站坏了**。
|
||||
给下单页最差只是"没找到那一单",页面自己会提示。
|
||||
3. **正则里的 `{6,16}` 必须用引号包住**,否则 nginx 会把花括号当配置块起始,
|
||||
报 `unknown directive`(实测踩到)。
|
||||
4. **`no-store` + `noindex`**:订单页带取件码,不该被缓存也不该被搜索引擎收录
|
||||
(一是降曝光,二是链接本身就是凭证)。
|
||||
|
||||
---
|
||||
|
||||
## 四、这一层我们没做的事(也算"做法",欢迎质疑)
|
||||
|
||||
- **没上 WAF / 没有额外防护层**:这台机器很小,装不下重的东西;
|
||||
防护全在后端自己的限流 + 两把令牌 + 来源 IP 门上。
|
||||
- **没做多机/负载均衡**:单机单进程,够用。
|
||||
- **HTTPS 用自动签发的证书**,续期自动化,没有额外动作。
|
||||
@@ -0,0 +1,37 @@
|
||||
# 交付清单(自查用)
|
||||
|
||||
> 生成:2026-10-05 18:52 共 29 个文件 合计 44.7 MB
|
||||
|
||||
| 文件 | 字节 | SHA-256 |
|
||||
|---|---|---|
|
||||
| `README.md` | 7,532 | `e551e8da39ec955f6d2a25fdd724e2949dffccb6de83d0121df62a8944e909bc` |
|
||||
| `backend-site/admin.py` | 24,214 | `3b9818c063e4c7297d3052cad4ff2a88941b4d07b85e2e5eaf495eed35d3f484` |
|
||||
| `backend-site/pngcheck.py` | 4,945 | `ccec7ab21b0399da651029ffa5781bad498e0905b31a1102f6ba3e3f01e8594d` |
|
||||
| `backend-site/server.py` | 160,560 | `9470b057f9eaf1927d06917ac5909fb0e733a4b44a04c039b82bbd907b9f2a62` |
|
||||
| `backend-site/交接说明.md` | 14,711 | `6b98b87c0f061760ec73e78036cf563b1c27fc8dead2324685b7218b61c9be72` |
|
||||
| `backend-tools/chk_worker.ps1` | 486 | `939a42cafa0954347f28d69e75b8af407ed1dab870cc3956fa8b7c5eb55e372f` |
|
||||
| `backend-tools/deploy.py` | 5,694 | `bf2cf47e715a3663faba5f1125ca9dee57596fd59664e2898515985924a0cc8c` |
|
||||
| `backend-tools/install_worker.ps1` | 8,902 | `95c339f2a69359fd1c980fb649217bb18371d9ba0b06eadce049b58537c11c1e` |
|
||||
| `backend-tools/local.html` | 23,026 | `c02fe7ed5bf39f329120c1ce6a01dcd2db675a37061fd5d57d8519dffc818a97` |
|
||||
| `backend-tools/make_order.py` | 28,388 | `e8e2ebb473501a0b914b9c2941d9e8505e9b92f0880190cf7f588d5fe27f233e` |
|
||||
| `backend-tools/open_local.bat` | 81 | `cf91a0f9bbf18db6b082874131aacb8bc04924bf68d355481a9445b26c46ab30` |
|
||||
| `backend-tools/pack_archive.bat` | 86 | `e2c6683d0b353ae8f68d9f9c0430c486aa733c57c6d2f4e7802bdd5e53783c00` |
|
||||
| `backend-tools/pack_archive.ps1` | 2,467 | `9fa2956e1d3718876fea3ad2b5576fab94087a0b73d00f43c5b443c821e1c06a` |
|
||||
| `backend-tools/run_admin.bat` | 417 | `49bab3f66e3f1419f2aab4e8d1835a5bc2f64395d6575605ec000d78c635c1c2` |
|
||||
| `backend-tools/run_panel.bat` | 911 | `c34eb6fb6d4808026c5432727de59e726632eadf2da49ee581477938c0194b0a` |
|
||||
| `backend-tools/run_worker.bat` | 176 | `3148827f6bd6967a9fb93f0ec9ba98e85cf8a26ac5160a6e6bab6369b2a3792a` |
|
||||
| `backend-tools/show_log.bat` | 422 | `fde479d7e8383863a3054b44d267d568a7c9c48df98a59175e03810e51156202` |
|
||||
| `backend-tools/skincheck.js` | 13,011 | `dc9c65ac8b8551aaa42ca7399517bb1d6c28956c4c80997132f16862e1239b8d` |
|
||||
| `backend-tools/stop_admin.bat` | 281 | `9b38682234f2e07b58c478c939f4f1d58cefe9624b13d0af2656d5522fd5509d` |
|
||||
| `backend-tools/stop_worker.bat` | 332 | `f7c8ab10d1d03d7a75c2fcb3343bec0c6d52409ef5cc6dd68c0f9e342e0077b4` |
|
||||
| `backend-tools/ys_admin.py` | 58,367 | `05878039c3728fc119c75ad76f216298d6c82e6cc19b79024090a89d8cc7fc84` |
|
||||
| `backend-tools/ys_local.py` | 17,021 | `27948a19f45aa984e0f9ffc88b6cd85bbe127e8f4ceff272fd189a49524fec1f` |
|
||||
| `backend-tools/ys_worker.py` | 30,465 | `ab6cdff13ce16ed15363c28cf016628b378a1ec255d2b8eeb62566cf38631eb9` |
|
||||
| `backend-tools/交接说明.md` | 11,008 | `731c591b545c4332c3ad5336910a78e5dfb8b6541da6f33e8f4e70bb3b7dab48` |
|
||||
| `deploy/nginx-片段.md` | 4,145 | `183179dc694e1f2ac3a791f3c96aa6f7d292b1968276ae1af4d850e26fbf78d0` |
|
||||
| `模板/1站立正反.blend` | 16,486,783 | `985dc61aeaa6eaaf5dc87ccbba6dfd4e1c5eb95468f7d0a9610d47aff14cb9dc` |
|
||||
| `模板/4海边自拍.blend` | 18,101,431 | `629df363d00e73e18820bddb6b7b92d7dbdd55d0f5c98de5378c76a48b705183` |
|
||||
| `模板/5不看爆炸.blend` | 11,849,599 | `3bb67516632e206c89fe44e2cf04667f5e34e1eab70e395c00830555e033e223` |
|
||||
| `模板/说明.md` | 2,775 | `491fa0587a9ff662a8e8893d0657eb412d87af8161de19abeba993e5a8ff4675` |
|
||||
|
||||
> 用途:对方收到后可以逐文件核哈希,确认传输没损坏 / 没被改动。
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -0,0 +1,50 @@
|
||||
# 三个 Blender 模板工程(给你跑测试用)
|
||||
|
||||
> 渲染 = **模板工程** + 买家的皮肤贴图。要真跑一遍看效果,你需要模板,
|
||||
> 所以店主挑了三个给你。**名字前面的数字就是模板编号**,代码里的 `TEMPLATES` 表靠它对应。
|
||||
|
||||
| 文件 | 编号 | 为什么给你这个 |
|
||||
|---|---|---|
|
||||
| `1站立正反.blend` | 1 | **最基础**:站立、正反两面。**先用它把链路跑通** |
|
||||
| `4海边自拍.blend` | 4 | **场景类的**(带环境),测"场景重"的情况 |
|
||||
| `5不看爆炸.blend` | 5 | **另一个场景**(爆炸/动感类),测"跟站立那个不一样的行为" |
|
||||
|
||||
**渲染环境**:Blender **4.x**,命令行后台模式:
|
||||
```
|
||||
blender -b --factory-startup --python make_order.py -- --skin <皮肤.png> --num <序号> --out <输出目录> --res 1000
|
||||
```
|
||||
完整参数看 `backend-tools/make_order.py` 顶部的用法说明。
|
||||
|
||||
---
|
||||
|
||||
## ⚠️ 这三个文件也**脱敏过**,说明一下动了什么
|
||||
|
||||
Blender 会把**绝对路径**写进工程文件里,所以直接给会把店主的机器信息一起带出去。
|
||||
我们做了**等长替换**(`.blend` 靠长度前缀存字符串,**长度一变文件就废**,
|
||||
所以只能等长换,不能删不能加):
|
||||
|
||||
| 原本 | 换成 | 处数 | 说明 |
|
||||
|---|---|---|---|
|
||||
| `C:\Users\<账户名>` | `C:\Users\user0` | 1 / 6983 / 0 | 抹掉 Windows 账户名 |
|
||||
| `<盘符>:\<习惯用的工程目录>` | `<盘符>:\assets0` | 136 / 14 / 12 | 抹掉习惯用的工程盘路径 |
|
||||
|
||||
(`4海边自拍` 那个数字大,是因为它引用了一批 Blender 插件的资源清单,每一条都带完整路径。)
|
||||
|
||||
**已核对**:
|
||||
- 替换后**文件字节数一个没变**(`1站立正反` 16,486,783 / `4海边自拍` 18,101,431 / `5不看爆炸` 11,849,599)—— 结构没被破坏
|
||||
- 里面**没有**中文目录名的长路径(也就是说不会泄露工程目录的命名)
|
||||
- 里面**没有**邮箱、域名、密钥
|
||||
|
||||
**请你帮我们确认一件事**:这三个工程在你那边**能正常打开并且能渲出图**吗?
|
||||
(我们改的是路径字符串,理论上不影响渲染,但只有你真跑一遍才算数 ——
|
||||
如果打不开或渲出来是灰的,说明我们动坏了,请立刻告诉我们,我们给没动过的版本。)
|
||||
|
||||
---
|
||||
|
||||
## 用它们做什么
|
||||
|
||||
1. **跑通**:用 `1站立正反` 走一遍完整链路(皮肤 → 渲染 → 出图,标准压缩 + 无压缩两张)。
|
||||
2. **测场景**:用 `4海边自拍` 看有没有跟 `1站立正反` 不一样的行为。
|
||||
3. **测场景差异**:用 `5不看爆炸`(动感场景),看有没有跟 `1站立正反` 不一样的行为。
|
||||
|
||||
跑的过程中如果发现**代码**的问题,按那份交接文档最后两节的要求写回执就行。
|
||||
Reference in New Issue
Block a user