dsh-qqbot-muu 0.1.15 → 0.1.21
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +168 -85
- package/client/qqbot-settings.js +13401 -12024
- package/config/modules.json +212 -0
- package/dist/channel-tools.js +21 -10
- package/dist/config.d.ts +14 -0
- package/dist/config.js +573 -449
- package/dist/features/contextless-store.js +247 -247
- package/dist/features/contextless-trim.js +455 -34
- package/dist/features/four-source.js +338 -336
- package/dist/features/group-join-request.js +289 -287
- package/dist/features/local-models.js +1494 -0
- package/dist/features/rotate-summarizer.js +438 -0
- package/dist/features/scenario-detect.js +321 -0
- package/dist/features/scheduler.js +8 -1
- package/dist/features/session-rotate.js +499 -0
- package/dist/features/session-title.js +199 -0
- package/dist/features/style-layer.js +501 -0
- package/dist/features/thinking-log.js +71 -69
- package/dist/gateway/bootstrap.js +1704 -1388
- package/dist/gateway/data-root.js +77 -3
- package/dist/gateway/middleware-setup.js +6 -3
- package/dist/index.js +4 -2
- package/dist/model/settings-reader.js +193 -102
- package/dist/session/session-manager.js +1730 -1587
- package/dist/shared/paths.js +128 -0
- package/dist/shared/settings-io.js +79 -0
- package/dist/transport/inbound.js +20 -1
- package/dist/transport/outbound.js +56 -4
- package/docs/RELEASE_CHECKLIST.md +24 -2
- package/dshqqbot/.qqbot-extensions/hooks/interview-panel.mjs +41 -1
- package/dshqqbot/.qqbot-extensions/inbound/00-vision.mjs +111 -0
- package/dshqqbot/.qqbot-extensions/inbound/aa-memory-recall.mjs +802 -689
- package/dshqqbot/.qqbot-extensions/inbound/ac-image-see.mjs +1 -1
- package/dshqqbot/.qqbot-extensions/inbound/az-feedback.mjs +113 -115
- package/dshqqbot/.qqbot-extensions/inbound/local-answer.mjs +689 -568
- package/dshqqbot/.qqbot-extensions/lib/.pet-form.json +1 -1
- package/dshqqbot/.qqbot-extensions/lib/draw-core.mjs +238 -7
- package/dshqqbot/.qqbot-extensions/lib/local-llm.mjs +455 -394
- package/dshqqbot/.qqbot-extensions/lib/memory-agent.mjs +930 -928
- package/dshqqbot/.qqbot-extensions/lib/memory-core.mjs +537 -537
- package/dshqqbot/.qqbot-extensions/lib/memory-db.mjs +2476 -2245
- package/dshqqbot/.qqbot-extensions/lib/memory-hippo.mjs +18 -0
- package/dshqqbot/.qqbot-extensions/lib/memory.mjs +191 -186
- package/dshqqbot/.qqbot-extensions/lib/plugin-dir.mjs +14 -4
- package/dshqqbot/.qqbot-extensions/lib/scope-util.mjs +84 -0
- package/dshqqbot/.qqbot-extensions/lib/vision.mjs +1 -1
- package/dshqqbot/.qqbot-extensions/outbound/aa-sanitize.mjs +158 -154
- package/dshqqbot/.qqbot-extensions/outbound/ac-media-fix.mjs +5 -1
- package/dshqqbot/.qqbot-extensions/outbound/memory-agent.mjs +121 -130
- package/dshqqbot/.qqbot-extensions/outbound/split-reply.mjs +18 -2
- package/dshqqbot/.qqbot-extensions/outbound/turn-memory.mjs +92 -101
- package/dshqqbot/.qqbot-extensions/tools/draw.mjs +22 -1
- package/dshqqbot/.qqbot-extensions/tools/memory.mjs +178 -120
- package/dshqqbot/.qqbot-extensions/tools/pet_card.mjs +3 -2
- package/dshqqbot/.qqbot-extensions/tools/storyboard.mjs +3 -1
- package/dshqqbot/.qqbot-extensions/vendor/abogus/test-abogus.mjs +128 -126
- package/package.json +119 -111
- package/scripts/__pycache__/fan-mode.cpython-311.pyc +0 -0
- package/scripts/__pycache__/memory-audit.cpython-311.pyc +0 -0
- package/scripts/__pycache__/qq-ip-sync.cpython-311.pyc +0 -0
- package/scripts/__pycache__/qq-whitelist.cpython-311.pyc +0 -0
- package/scripts/_add_maintenance_cfg.py +20 -0
- package/scripts/_bench_keeplease.sh +10 -0
- package/scripts/_dbg_purge.py +15 -0
- package/scripts/_elev.sh +6 -0
- package/scripts/_fix_all_admin.cmd +16 -0
- package/scripts/_livecheck-image.mjs +33 -0
- package/scripts/_livecheck-llm.mjs +34 -0
- package/scripts/_livecheck-tts.mjs +37 -0
- package/scripts/_patch_curve.py +88 -0
- package/scripts/_patch_fan_thermal.py +24 -0
- package/scripts/_tag_tmp.py +13 -0
- package/scripts/adb-broker-client.mjs +87 -0
- package/scripts/adb-broker.mjs +205 -0
- package/scripts/ai-mode.cmd +6 -0
- package/scripts/ai-mode.py +387 -0
- package/scripts/ai-toolkit.py +607 -0
- package/scripts/apply-fan-gpu45.py +51 -0
- package/scripts/bench-fans.py +515 -0
- package/scripts/bench-load-direct.py +63 -0
- package/scripts/boot-tasks-hidden.vbs +20 -0
- package/scripts/boot-tasks.cmd +277 -0
- package/scripts/chat-archive/__pycache__/build-sft-v4.cpython-311.pyc +0 -0
- package/scripts/chat-archive/__pycache__/build-sft.cpython-311.pyc +0 -0
- package/scripts/chat-archive/build-sft-v4.py +566 -0
- package/scripts/chat-archive/build-sft.py +390 -0
- package/scripts/chat-archive/eval-sft.py +155 -0
- package/scripts/chat-archive/extract-memory.py +143 -0
- package/scripts/chat-archive/inventory.py +182 -0
- package/scripts/chat-archive/merge-sft.py +114 -0
- package/scripts/chat-archive/qce-pull.py +217 -0
- package/scripts/chat-archive/qqheader.py +110 -0
- package/scripts/chat-archive/qqkey2.py +113 -0
- package/scripts/chat-archive/qqprobe.py +153 -0
- package/scripts/chat-archive/screen-collect.py +163 -0
- package/scripts/chat-archive/sqlcipher_probe.py +444 -0
- package/scripts/comfy_gen.py +209 -0
- package/scripts/compose-video.py +168 -0
- package/scripts/dl_models.py +45 -0
- package/scripts/draw-now.cmd +18 -0
- package/scripts/dsh-instance-guard.mjs +20 -2
- package/scripts/elev-extra.cmd +25 -0
- package/scripts/episode.py +529 -0
- package/scripts/fan-curve.py +218 -0
- package/scripts/fan-guard.cmd +8 -0
- package/scripts/fan-mode.py +380 -0
- package/scripts/fan_manual_safe.py +33 -0
- package/scripts/fan_restore_manual.py +46 -0
- package/scripts/fc_curves.py +359 -0
- package/scripts/fix-fan-and-timers.cmd +39 -0
- package/scripts/fix_admin_all.py +94 -0
- package/scripts/flows.mjs +224 -0
- package/scripts/gateway.cmd +126 -0
- package/scripts/gen-image.py +420 -0
- package/scripts/gen-video.py +186 -0
- package/scripts/git-askpass.cmd +2 -2
- package/scripts/gpu-mode.py +195 -0
- package/scripts/hw-profile.py +175 -0
- package/scripts/install-schedule.cmd +37 -0
- package/scripts/install-watch.cmd +29 -0
- package/scripts/matte-cutout.py +106 -0
- package/scripts/media-enhance.py +402 -0
- package/scripts/memory-audit.py +581 -0
- package/scripts/migrate-scope.mjs +140 -139
- package/scripts/model-registry.py +519 -0
- package/scripts/openid-audit.mjs +219 -0
- package/scripts/pull-gguf.py +127 -0
- package/scripts/purge-standby.py +151 -0
- package/scripts/qq-connect-login.py +133 -0
- package/scripts/qq-ip-sync-hidden.vbs +5 -0
- package/scripts/qq-ip-sync.py +300 -0
- package/scripts/qq-login-once.cmd +20 -0
- package/scripts/qq-login-qr.py +72 -0
- package/scripts/qq-whitelist-fix.cmd +27 -0
- package/scripts/qq-whitelist-login.cmd +26 -0
- package/scripts/qq-whitelist.cmd +12 -0
- package/scripts/qq-whitelist.py +1452 -0
- package/scripts/quality-compare.py +134 -0
- package/scripts/release-all.mjs +636 -430
- package/scripts/release-check.mjs +244 -226
- package/scripts/resume-coder.cmd +38 -0
- package/scripts/secure-room/index.html +334 -0
- package/scripts/secure-room/server.py +582 -0
- package/scripts/security-check.mjs +164 -0
- package/scripts/selftest-local-llm.mjs +20 -0
- package/scripts/selftest-local-models.mjs +754 -0
- package/scripts/selftest-rotate-style.mjs +308 -0
- package/scripts/shutdown-s5-optional.cmd +21 -0
- package/scripts/sleep-2325.cmd +75 -0
- package/scripts/start-comfyui.cmd +5 -0
- package/scripts/start-strata.cmd +17 -0
- package/scripts/start-strata.vbs +11 -0
- package/scripts/start-watch-hidden.vbs +3 -0
- package/scripts/stickers/auto-tag.mjs +161 -0
- package/scripts/storage.mjs +236 -0
- package/scripts/sync-plugin-copies.mjs +98 -23
- package/scripts/tests/test-qq-whitelist.py +192 -0
- package/scripts/train/__pycache__/train-lora.cpython-311.pyc +0 -0
- package/scripts/train/gguf-quantize.py +92 -0
- package/scripts/train/gguf-to-hf.py +112 -0
- package/scripts/train/merge-lora.py +51 -0
- package/scripts/train/probe-mirrors.sh +12 -0
- package/scripts/train/probe-mirrors2.sh +20 -0
- package/scripts/train/setup-wsl.sh +23 -0
- package/scripts/train/setup-wsl2.sh +25 -0
- package/scripts/train/setup-wsl3.sh +22 -0
- package/scripts/train/setup-wsl4.sh +22 -0
- package/scripts/train/train-lora.py +319 -0
- package/scripts/vram-free.py +104 -0
- package/scripts/wechat-full-pull.mjs +1 -1
- package/settings-host.js +1047 -12
|
@@ -0,0 +1,402 @@
|
|
|
1
|
+
# -*- coding: utf-8 -*-
|
|
2
|
+
"""media-enhance.py —— 生成物的「修复/增强」环节(本地、确定性、零云 token)。
|
|
3
|
+
|
|
4
|
+
为什么单独一个脚本:
|
|
5
|
+
以前链路是 出图 → 直接发出去。模型本身的噪点、发灰、边缘发软没人管,
|
|
6
|
+
视频同理(暗部色噪、对白忽大忽小)。这里把「修复」做成一个**固定参数**的
|
|
7
|
+
可复现步骤,任何调用方(ai-toolkit / episode / 人工)都走同一条路。
|
|
8
|
+
|
|
9
|
+
三种输入、一套契约:
|
|
10
|
+
image 去噪 → 局部对比(CLAHE) → 轻微色彩校正 → 锐化 → 可选 2x Lanczos 放大
|
|
11
|
+
video 时域去噪(hqdn3d) → 锐化 → 可选放大 → 响度归一(loudnorm) + 高通
|
|
12
|
+
audio 高通 → 响度归一(I=-16 LUFS,短视频通用)
|
|
13
|
+
|
|
14
|
+
确定性:没有任何随机数,参数全部写死在 PRESETS 里;同样的输入必然得到同样的输出。
|
|
15
|
+
输出:默认写到 out/<kind>/<yyyy-MM>/enhanced/,同时落一份 -report.json 记录前后指标。
|
|
16
|
+
|
|
17
|
+
用法:
|
|
18
|
+
python scripts/media-enhance.py image -i a.png
|
|
19
|
+
python scripts/media-enhance.py image -i a.png -o b.png --preset anime --scale 2 --json
|
|
20
|
+
python scripts/media-enhance.py video -i a.mp4 -o b.mp4 --json
|
|
21
|
+
python scripts/media-enhance.py audio -i a.wav -o b.wav --json
|
|
22
|
+
python scripts/media-enhance.py probe -i a.mp4 --json # 只看指标,不改文件
|
|
23
|
+
"""
|
|
24
|
+
import argparse
|
|
25
|
+
import json
|
|
26
|
+
import os
|
|
27
|
+
import subprocess
|
|
28
|
+
import sys
|
|
29
|
+
import time
|
|
30
|
+
|
|
31
|
+
CREATE_NO_WINDOW = 0x08000000
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def _resolve_root():
|
|
35
|
+
"""仓库根 = 有 .models 的那一层(插件副本里也能找对)。"""
|
|
36
|
+
here = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
|
37
|
+
cands = []
|
|
38
|
+
for k in ("QQBOT_ROOT", "QQBOT_REPO_ROOT"):
|
|
39
|
+
v = (os.environ.get(k) or "").strip()
|
|
40
|
+
if v:
|
|
41
|
+
cands.append(os.path.abspath(v))
|
|
42
|
+
d = here
|
|
43
|
+
for _ in range(8):
|
|
44
|
+
cands.append(d)
|
|
45
|
+
nd = os.path.dirname(d)
|
|
46
|
+
if nd == d:
|
|
47
|
+
break
|
|
48
|
+
d = nd
|
|
49
|
+
for c in cands:
|
|
50
|
+
try:
|
|
51
|
+
if os.path.isdir(os.path.join(c, ".models")):
|
|
52
|
+
return c
|
|
53
|
+
except Exception:
|
|
54
|
+
continue
|
|
55
|
+
return here
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
ROOT = _resolve_root()
|
|
59
|
+
FFMPEG = os.environ.get("FFMPEG") or os.path.join(ROOT, "bin", "ffmpeg", "ffmpeg.exe")
|
|
60
|
+
FFPROBE = FFMPEG.replace("ffmpeg.exe", "ffprobe.exe")
|
|
61
|
+
|
|
62
|
+
# ── 固定参数(改这里 = 改所有调用方的行为,别在调用方另写一套) ──────────────
|
|
63
|
+
PRESETS = {
|
|
64
|
+
# 写实/摄影:出图常见「轻微颗粒 + 暗部发灰 + 边缘发软」
|
|
65
|
+
# 参数由 2026-12-02 的网格实测确定(tmp/tune-enhance.py):在 1024 归一宽度上
|
|
66
|
+
# 锐度 ~2.2x、平坦区噪点不上升(noise_x ≥ 1.0 才算没变差)。
|
|
67
|
+
"photo": {
|
|
68
|
+
"nlm_h": 4.0, "nlm_hcolor": 5.0, "nlm_template": 7, "nlm_search": 21,
|
|
69
|
+
"clahe_clip": 1.5, "clahe_tile": 8,
|
|
70
|
+
"sat": 1.03,
|
|
71
|
+
"unsharp_radius": 1.2, "unsharp_amount": 0.40,
|
|
72
|
+
"clarity_radius": 9.0, "clarity_amount": 0.14,
|
|
73
|
+
"post_sharpen": 0.18, "scale": 2,
|
|
74
|
+
},
|
|
75
|
+
# 二次元/插画:线条本来锐,去噪要轻,锐化要克制(否则脏边)
|
|
76
|
+
"anime": {
|
|
77
|
+
"nlm_h": 2.5, "nlm_hcolor": 3.0, "nlm_template": 7, "nlm_search": 21,
|
|
78
|
+
"clahe_clip": 1.2, "clahe_tile": 8,
|
|
79
|
+
"sat": 1.02,
|
|
80
|
+
"unsharp_radius": 1.0, "unsharp_amount": 0.30,
|
|
81
|
+
"clarity_radius": 9.0, "clarity_amount": 0.09,
|
|
82
|
+
"post_sharpen": 0.12, "scale": 2,
|
|
83
|
+
},
|
|
84
|
+
# 极轻:只在自动链路里用(不加尺寸,几乎不改观感,只压噪点)
|
|
85
|
+
"light": {
|
|
86
|
+
"nlm_h": 3.0, "nlm_hcolor": 4.0, "nlm_template": 7, "nlm_search": 15,
|
|
87
|
+
"clahe_clip": 1.12, "clahe_tile": 8,
|
|
88
|
+
"sat": 1.01,
|
|
89
|
+
"unsharp_radius": 1.0, "unsharp_amount": 0.25,
|
|
90
|
+
"clarity_radius": 9.0, "clarity_amount": 0.05,
|
|
91
|
+
"post_sharpen": 0.0, "scale": 1,
|
|
92
|
+
},
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
VIDEO_PRESET = {
|
|
96
|
+
# hqdn3d=亮度时域:色度时域:亮度空间:色度空间
|
|
97
|
+
"denoise": "hqdn3d=2:1.5:3:2.25",
|
|
98
|
+
"unsharp": "unsharp=5:5:0.45:3:3:0.0",
|
|
99
|
+
"crf": 18,
|
|
100
|
+
"preset": "medium",
|
|
101
|
+
"loudnorm": "loudnorm=I=-16:TP=-1.5:LRA=11",
|
|
102
|
+
"highpass": "highpass=f=60",
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
AUDIO_PRESET = {"highpass": "highpass=f=70", "loudnorm": "loudnorm=I=-16:TP=-1.5:LRA=11", "rate": 48000}
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def out_dir(kind):
|
|
109
|
+
d = os.path.join(ROOT, "out", kind, time.strftime("%Y-%m"))
|
|
110
|
+
e = os.path.join(d, "enhanced")
|
|
111
|
+
os.makedirs(e, exist_ok=True)
|
|
112
|
+
return e
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def _run(args, timeout=1800):
|
|
116
|
+
p = subprocess.run(args, capture_output=True, text=True, timeout=timeout,
|
|
117
|
+
creationflags=CREATE_NO_WINDOW)
|
|
118
|
+
if p.returncode != 0:
|
|
119
|
+
raise RuntimeError("命令失败(%d): %s" % (p.returncode, (p.stderr or "")[-900:]))
|
|
120
|
+
return p
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
# ── 质量指标(全部整数/浮点确定量,方便前后对比) ──────────────────────────
|
|
124
|
+
ML_NORM_WIDTH = 1024 # 指标一律在「归一宽度」上算,否则 2x 放大后指标不可比
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
def image_metrics(path):
|
|
128
|
+
import cv2
|
|
129
|
+
import numpy as np
|
|
130
|
+
img = cv2.imread(path, cv2.IMREAD_COLOR)
|
|
131
|
+
if img is None:
|
|
132
|
+
raise RuntimeError("读不到图片: %s" % path)
|
|
133
|
+
real_w, real_h = img.shape[1], img.shape[0]
|
|
134
|
+
if real_w > ML_NORM_WIDTH:
|
|
135
|
+
nh = max(1, int(real_h * ML_NORM_WIDTH / real_w))
|
|
136
|
+
img = cv2.resize(img, (ML_NORM_WIDTH, nh), interpolation=cv2.INTER_AREA)
|
|
137
|
+
elif real_w < ML_NORM_WIDTH // 2:
|
|
138
|
+
nh = max(1, int(real_h * ML_NORM_WIDTH / real_w))
|
|
139
|
+
img = cv2.resize(img, (ML_NORM_WIDTH, nh), interpolation=cv2.INTER_LANCZOS4)
|
|
140
|
+
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY).astype(np.float64)
|
|
141
|
+
# 清晰度:拉普拉斯方差(越大越锐)
|
|
142
|
+
sharp = float(cv2.Laplacian(gray, cv2.CV_64F).var())
|
|
143
|
+
# 噪点:平坦区局部标准差的下 8% 分位(边缘/细节不会污染这个数字;
|
|
144
|
+
# 锐化把边缘削出白边也不会让它虚高,只有真正的颗粒才会)
|
|
145
|
+
k = 7
|
|
146
|
+
mu = cv2.blur(gray, (k, k))
|
|
147
|
+
mu2 = cv2.blur(gray * gray, (k, k))
|
|
148
|
+
lstd = np.sqrt(np.maximum(mu2 - mu * mu, 0))
|
|
149
|
+
# 下界 0.05:大平坦区(纯色/纯黑)会让分位数落到 0,除零会让「噪点改善倍数」变成天文数字
|
|
150
|
+
noise = max(float(np.percentile(lstd, 8)), 0.05)
|
|
151
|
+
# 色彩丰富度:Hasler-Süsstrunk
|
|
152
|
+
b, g, r = [img[:, :, i].astype(np.float64) for i in range(3)]
|
|
153
|
+
rg, yb = r - g, 0.5 * (r + g) - b
|
|
154
|
+
colorful = float((np.sqrt(rg.std() ** 2 + yb.std() ** 2) + 0.3 * np.sqrt(rg.mean() ** 2 + yb.mean() ** 2)))
|
|
155
|
+
h, w = gray.shape
|
|
156
|
+
return {"width": real_w, "height": real_h, "metric_width": w,
|
|
157
|
+
"sharpness": round(sharp, 2), "noise_sigma": round(noise, 3),
|
|
158
|
+
"colorfulness": round(colorful, 2), "brightness": round(float(gray.mean()), 2),
|
|
159
|
+
"contrast": round(float(gray.std()), 2),
|
|
160
|
+
"file_kb": round(os.path.getsize(path) / 1024.0, 1)}
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
def probe_video(path):
|
|
164
|
+
p = _run([FFPROBE, "-v", "error", "-print_format", "json", "-show_format", "-show_streams", path], 120)
|
|
165
|
+
d = json.loads(p.stdout)
|
|
166
|
+
v = next((s for s in d.get("streams", []) if s.get("codec_type") == "video"), {})
|
|
167
|
+
a = next((s for s in d.get("streams", []) if s.get("codec_type") == "audio"), None)
|
|
168
|
+
return {
|
|
169
|
+
"width": v.get("width"), "height": v.get("height"),
|
|
170
|
+
"fps": v.get("r_frame_rate"), "codec": v.get("codec_name"),
|
|
171
|
+
"duration": round(float(d.get("format", {}).get("duration") or 0), 2),
|
|
172
|
+
"mb": round(float(d.get("format", {}).get("size") or 0) / 1048576.0, 2),
|
|
173
|
+
"bitrate_kbps": round(float(d.get("format", {}).get("bit_rate") or 0) / 1000.0),
|
|
174
|
+
"audio": None if not a else {"codec": a.get("codec_name"), "rate": a.get("sample_rate"),
|
|
175
|
+
"channels": a.get("channels")},
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
|
|
179
|
+
def loudness(path):
|
|
180
|
+
"""跑一遍 ebur128 拿输入响度(做「修复前/后」的证据,不改文件)。"""
|
|
181
|
+
try:
|
|
182
|
+
p = subprocess.run([FFMPEG, "-hide_banner", "-i", path, "-af", "ebur128", "-f", "null", "-"],
|
|
183
|
+
capture_output=True, text=True, timeout=300, creationflags=CREATE_NO_WINDOW)
|
|
184
|
+
txt = (p.stderr or "")
|
|
185
|
+
idx = txt.rfind("Integrated loudness")
|
|
186
|
+
if idx < 0:
|
|
187
|
+
return None
|
|
188
|
+
seg = txt[idx:idx + 400]
|
|
189
|
+
val = None
|
|
190
|
+
for line in seg.splitlines():
|
|
191
|
+
if "I:" in line:
|
|
192
|
+
val = line.split("I:")[1].strip().split(" ")[0]
|
|
193
|
+
break
|
|
194
|
+
return float(val) if val and val not in ("-inf", "nan") else None
|
|
195
|
+
except Exception:
|
|
196
|
+
return None
|
|
197
|
+
|
|
198
|
+
|
|
199
|
+
# ── 图像增强 ────────────────────────────────────────────────────────────────
|
|
200
|
+
def enhance_image(src, dst="", preset="photo", scale=0, report_path="", compare=True):
|
|
201
|
+
import cv2
|
|
202
|
+
import numpy as np
|
|
203
|
+
if not os.path.exists(src):
|
|
204
|
+
raise RuntimeError("输入不存在: %s" % src)
|
|
205
|
+
cfg = dict(PRESETS.get(preset) or PRESETS["photo"])
|
|
206
|
+
if scale and scale > 0:
|
|
207
|
+
cfg["scale"] = int(scale)
|
|
208
|
+
before = image_metrics(src)
|
|
209
|
+
img = cv2.imread(src, cv2.IMREAD_COLOR)
|
|
210
|
+
if img is None:
|
|
211
|
+
raise RuntimeError("读不到图片(格式不支持?): %s" % src)
|
|
212
|
+
|
|
213
|
+
# 1) 去噪(彩色 NLM;参数固定 → 结果固定)
|
|
214
|
+
den = cv2.fastNlMeansDenoisingColored(img, None, cfg["nlm_h"], cfg["nlm_hcolor"],
|
|
215
|
+
cfg["nlm_template"], cfg["nlm_search"])
|
|
216
|
+
# 2) 局部对比:LAB 的 L 通道 CLAHE(压灰雾,不动色相)
|
|
217
|
+
lab = cv2.cvtColor(den, cv2.COLOR_BGR2LAB)
|
|
218
|
+
l, a, b = cv2.split(lab)
|
|
219
|
+
l = cv2.createCLAHE(clipLimit=cfg["clahe_clip"], tileGridSize=(cfg["clahe_tile"], cfg["clahe_tile"])).apply(l)
|
|
220
|
+
out = cv2.cvtColor(cv2.merge([l, a, b]), cv2.COLOR_LAB2BGR)
|
|
221
|
+
# 3) 轻微饱和校正(LAB 的 a/b 缩放,比 HSV 更不易偏色)
|
|
222
|
+
if abs(cfg["sat"] - 1.0) > 1e-3:
|
|
223
|
+
lab2 = cv2.cvtColor(out, cv2.COLOR_BGR2LAB).astype(np.float32)
|
|
224
|
+
lab2[:, :, 1] = np.clip(128 + (lab2[:, :, 1] - 128) * cfg["sat"], 0, 255)
|
|
225
|
+
lab2[:, :, 2] = np.clip(128 + (lab2[:, :, 2] - 128) * cfg["sat"], 0, 255)
|
|
226
|
+
out = cv2.cvtColor(lab2.astype(np.uint8), cv2.COLOR_LAB2BGR)
|
|
227
|
+
# 4) 反锐化掩膜(恢复模型输出被压缩的细节)
|
|
228
|
+
blur = cv2.GaussianBlur(out, (0, 0), cfg["unsharp_radius"])
|
|
229
|
+
out = cv2.addWeighted(out, 1.0 + cfg["unsharp_amount"], blur, -cfg["unsharp_amount"], 0)
|
|
230
|
+
# 4b) 大半径「清晰度」:只抬中低频对比,让画面不发平(小半径锐化看不出这个)
|
|
231
|
+
if cfg.get("clarity_amount"):
|
|
232
|
+
low = cv2.GaussianBlur(out, (0, 0), cfg.get("clarity_radius", 9.0))
|
|
233
|
+
out = cv2.addWeighted(out, 1.0 + cfg["clarity_amount"], low, -cfg["clarity_amount"], 0)
|
|
234
|
+
# 5) 放大(Lanczos4,比模型直出 1024 更适合当封面/视频关键帧)
|
|
235
|
+
sc = int(cfg["scale"] or 1)
|
|
236
|
+
if sc > 1:
|
|
237
|
+
out = cv2.resize(out, (out.shape[1] * sc, out.shape[0] * sc), interpolation=cv2.INTER_LANCZOS4)
|
|
238
|
+
if cfg["post_sharpen"] > 0:
|
|
239
|
+
blur2 = cv2.GaussianBlur(out, (0, 0), 1.0)
|
|
240
|
+
out = cv2.addWeighted(out, 1.0 + cfg["post_sharpen"], blur2, -cfg["post_sharpen"], 0)
|
|
241
|
+
|
|
242
|
+
dst = dst or os.path.join(out_dir("image"), os.path.splitext(os.path.basename(src))[0] + "-enhanced.png")
|
|
243
|
+
os.makedirs(os.path.dirname(os.path.abspath(dst)), exist_ok=True)
|
|
244
|
+
cv2.imwrite(dst, out, [cv2.IMWRITE_PNG_COMPRESSION, 3])
|
|
245
|
+
after = image_metrics(dst)
|
|
246
|
+
|
|
247
|
+
cmp_path = ""
|
|
248
|
+
if compare:
|
|
249
|
+
try:
|
|
250
|
+
from PIL import Image, ImageDraw
|
|
251
|
+
a_im = Image.open(src).convert("RGB")
|
|
252
|
+
b_im = Image.open(dst).convert("RGB")
|
|
253
|
+
cell = 760
|
|
254
|
+
ah = max(1, int(a_im.height * cell / a_im.width))
|
|
255
|
+
bh = max(1, int(b_im.height * cell / b_im.width))
|
|
256
|
+
sheet = Image.new("RGB", (cell * 2 + 24, max(ah, bh) + 46), (20, 20, 24))
|
|
257
|
+
sheet.paste(a_im.resize((cell, ah), Image.LANCZOS), (8, 34))
|
|
258
|
+
sheet.paste(b_im.resize((cell, bh), Image.LANCZOS), (cell + 16, 34))
|
|
259
|
+
dr = ImageDraw.Draw(sheet)
|
|
260
|
+
dr.text((10, 10), "BEFORE sharp=%.1f noise=%.2f" % (before["sharpness"], before["noise_sigma"]),
|
|
261
|
+
fill=(220, 220, 226))
|
|
262
|
+
dr.text((cell + 18, 10), "AFTER sharp=%.1f noise=%.2f" % (after["sharpness"], after["noise_sigma"]),
|
|
263
|
+
fill=(150, 240, 170))
|
|
264
|
+
cmp_path = os.path.splitext(dst)[0] + "-compare.jpg"
|
|
265
|
+
sheet.save(cmp_path, quality=88)
|
|
266
|
+
except Exception as e:
|
|
267
|
+
cmp_path = ""
|
|
268
|
+
print("[media-enhance] 对比图生成失败(不影响主输出): %s" % e)
|
|
269
|
+
|
|
270
|
+
rep = {"ok": True, "kind": "image", "preset": preset, "scale": sc,
|
|
271
|
+
"input": src, "output": dst, "compare": cmp_path,
|
|
272
|
+
"before": before, "after": after,
|
|
273
|
+
"gain": {"sharpness_x": round(after["sharpness"] / max(before["sharpness"], 1e-6), 2),
|
|
274
|
+
"noise_x": round(before["noise_sigma"] / max(after["noise_sigma"], 0.05), 2)}}
|
|
275
|
+
rp = report_path or os.path.splitext(dst)[0] + "-report.json"
|
|
276
|
+
with open(rp, "w", encoding="utf-8") as f:
|
|
277
|
+
json.dump(rep, f, ensure_ascii=False, indent=2)
|
|
278
|
+
rep["report"] = rp
|
|
279
|
+
return rep
|
|
280
|
+
|
|
281
|
+
|
|
282
|
+
# ── 视频增强 ────────────────────────────────────────────────────────────────
|
|
283
|
+
def enhance_video(src, dst="", scale=1, crf=0, timeout=3600):
|
|
284
|
+
if not os.path.exists(src):
|
|
285
|
+
raise RuntimeError("输入不存在: %s" % src)
|
|
286
|
+
before = probe_video(src)
|
|
287
|
+
loud_before = loudness(src) if before.get("audio") else None
|
|
288
|
+
sc = max(1, int(scale or 1))
|
|
289
|
+
vf = [VIDEO_PRESET["denoise"], VIDEO_PRESET["unsharp"]]
|
|
290
|
+
if sc > 1:
|
|
291
|
+
vf.append("scale=iw*%d:ih*%d:flags=lanczos" % (sc, sc))
|
|
292
|
+
vf.append("format=yuv420p")
|
|
293
|
+
dst = dst or os.path.join(out_dir("video"), os.path.splitext(os.path.basename(src))[0] + "-enhanced.mp4")
|
|
294
|
+
os.makedirs(os.path.dirname(os.path.abspath(dst)), exist_ok=True)
|
|
295
|
+
args = [FFMPEG, "-y", "-i", src, "-vf", ",".join(vf),
|
|
296
|
+
"-c:v", "libx264", "-preset", VIDEO_PRESET["preset"], "-crf", str(crf or VIDEO_PRESET["crf"]),
|
|
297
|
+
"-pix_fmt", "yuv420p"]
|
|
298
|
+
if before.get("audio"):
|
|
299
|
+
args += ["-af", "%s,%s" % (AUDIO_PRESET["highpass"], VIDEO_PRESET["loudnorm"]),
|
|
300
|
+
"-c:a", "aac", "-b:a", "192k", "-ar", str(AUDIO_PRESET["rate"])]
|
|
301
|
+
else:
|
|
302
|
+
args += ["-an"]
|
|
303
|
+
args += ["-movflags", "+faststart", dst]
|
|
304
|
+
t0 = time.time()
|
|
305
|
+
_run(args, timeout)
|
|
306
|
+
after = probe_video(dst)
|
|
307
|
+
rep = {"ok": True, "kind": "video", "scale": sc, "input": src, "output": dst,
|
|
308
|
+
"before": before, "after": after, "loudness_before": loud_before,
|
|
309
|
+
"loudness_after": loudness(dst) if after.get("audio") else None,
|
|
310
|
+
"encode_seconds": round(time.time() - t0, 1)}
|
|
311
|
+
rp = os.path.splitext(dst)[0] + "-report.json"
|
|
312
|
+
with open(rp, "w", encoding="utf-8") as f:
|
|
313
|
+
json.dump(rep, f, ensure_ascii=False, indent=2)
|
|
314
|
+
rep["report"] = rp
|
|
315
|
+
return rep
|
|
316
|
+
|
|
317
|
+
|
|
318
|
+
# ── 音频增强 ────────────────────────────────────────────────────────────────
|
|
319
|
+
def enhance_audio(src, dst="", timeout=600):
|
|
320
|
+
"""高通 → 粗归一 → 精确补偿到 -16 LUFS → 限幅。
|
|
321
|
+
|
|
322
|
+
为什么不用一遍/两遍 loudnorm 就完事:短句(3~5s)里 linear 模式会被峰值限制住,
|
|
323
|
+
落点能差 7dB(实测 -23.2 LUFS),多句拼起来就是「一句响一句轻」。
|
|
324
|
+
这里改成「先粗归一,再量一次 ebur128,按差值补增益,最后限幅」,落点稳定在 ±0.3dB。
|
|
325
|
+
"""
|
|
326
|
+
if not os.path.exists(src):
|
|
327
|
+
raise RuntimeError("输入不存在: %s" % src)
|
|
328
|
+
before = loudness(src)
|
|
329
|
+
dst = dst or os.path.join(out_dir("audio"), os.path.splitext(os.path.basename(src))[0] + "-enhanced.wav")
|
|
330
|
+
os.makedirs(os.path.dirname(os.path.abspath(dst)), exist_ok=True)
|
|
331
|
+
rough = os.path.splitext(dst)[0] + ".rough.wav"
|
|
332
|
+
_run([FFMPEG, "-y", "-i", src, "-af",
|
|
333
|
+
"%s,%s,aresample=%d" % (AUDIO_PRESET["highpass"], AUDIO_PRESET["loudnorm"], AUDIO_PRESET["rate"]),
|
|
334
|
+
"-ac", "2", "-c:a", "pcm_s16le", rough], timeout)
|
|
335
|
+
mid = loudness(rough)
|
|
336
|
+
gain = 0.0 if mid is None else max(-12.0, min(12.0, -16.0 - float(mid)))
|
|
337
|
+
_run([FFMPEG, "-y", "-i", rough, "-af",
|
|
338
|
+
"volume=%.2fdB,alimiter=limit=0.95:level=false" % gain,
|
|
339
|
+
"-ac", "2", "-ar", str(AUDIO_PRESET["rate"]), "-c:a", "pcm_s16le", dst], timeout)
|
|
340
|
+
try:
|
|
341
|
+
os.remove(rough)
|
|
342
|
+
except OSError:
|
|
343
|
+
pass
|
|
344
|
+
after = loudness(dst)
|
|
345
|
+
rep = {"ok": True, "kind": "audio", "input": src, "output": dst,
|
|
346
|
+
"loudness_before": before, "loudness_after": after,
|
|
347
|
+
"gain_db": round(gain, 2), "file_kb": round(os.path.getsize(dst) / 1024.0, 1)}
|
|
348
|
+
rp = os.path.splitext(dst)[0] + "-report.json"
|
|
349
|
+
with open(rp, "w", encoding="utf-8") as f:
|
|
350
|
+
json.dump(rep, f, ensure_ascii=False, indent=2)
|
|
351
|
+
rep["report"] = rp
|
|
352
|
+
return rep
|
|
353
|
+
|
|
354
|
+
|
|
355
|
+
def main(argv=None):
|
|
356
|
+
argv = list(sys.argv[1:] if argv is None else argv)
|
|
357
|
+
force_json = "--json" in argv
|
|
358
|
+
argv = [x for x in argv if x != "--json"]
|
|
359
|
+
ap = argparse.ArgumentParser(description="生成物修复/增强(确定性参数)")
|
|
360
|
+
sub = ap.add_subparsers(dest="cmd", required=True)
|
|
361
|
+
|
|
362
|
+
pi = sub.add_parser("image")
|
|
363
|
+
pi.add_argument("-i", "--input", required=True)
|
|
364
|
+
pi.add_argument("-o", "--out", default="")
|
|
365
|
+
pi.add_argument("--preset", default="photo", choices=list(PRESETS))
|
|
366
|
+
pi.add_argument("--scale", type=int, default=0, help="放大倍数(0=用预设默认,1=不放大)")
|
|
367
|
+
pi.add_argument("--no-compare", action="store_true")
|
|
368
|
+
|
|
369
|
+
pv = sub.add_parser("video")
|
|
370
|
+
pv.add_argument("-i", "--input", required=True)
|
|
371
|
+
pv.add_argument("-o", "--out", default="")
|
|
372
|
+
pv.add_argument("--scale", type=int, default=1)
|
|
373
|
+
pv.add_argument("--crf", type=int, default=0)
|
|
374
|
+
pv.add_argument("--timeout", type=int, default=3600)
|
|
375
|
+
|
|
376
|
+
pa = sub.add_parser("audio")
|
|
377
|
+
pa.add_argument("-i", "--input", required=True)
|
|
378
|
+
pa.add_argument("-o", "--out", default="")
|
|
379
|
+
|
|
380
|
+
pp = sub.add_parser("probe")
|
|
381
|
+
pp.add_argument("-i", "--input", required=True)
|
|
382
|
+
|
|
383
|
+
a = ap.parse_args(argv)
|
|
384
|
+
try:
|
|
385
|
+
if a.cmd == "image":
|
|
386
|
+
rep = enhance_image(a.input, a.out, a.preset, a.scale, compare=not a.no_compare)
|
|
387
|
+
elif a.cmd == "video":
|
|
388
|
+
rep = enhance_video(a.input, a.out, a.scale, a.crf, a.timeout)
|
|
389
|
+
elif a.cmd == "audio":
|
|
390
|
+
rep = enhance_audio(a.input, a.out)
|
|
391
|
+
else:
|
|
392
|
+
rep = {"ok": True, "kind": "probe", "input": a.input, "probe": probe_video(a.input),
|
|
393
|
+
"loudness": loudness(a.input)}
|
|
394
|
+
except Exception as e:
|
|
395
|
+
print(json.dumps({"ok": False, "error": "%s: %s" % (type(e).__name__, e)}, ensure_ascii=False))
|
|
396
|
+
return 4
|
|
397
|
+
print(json.dumps(rep, ensure_ascii=False) if force_json else json.dumps(rep, ensure_ascii=False, indent=2))
|
|
398
|
+
return 0
|
|
399
|
+
|
|
400
|
+
|
|
401
|
+
if __name__ == "__main__":
|
|
402
|
+
sys.exit(main())
|