Files
unicut/data-quality/scripts/site/00_lint_dist.py
T
jinghui dde45fb4e9 feat(quickvideo): AI一键出片自动生成视频封面
- aiQuickVideo.ts 新增 generateQuickVideoCover(): 标题+图片→封面
  (视觉模型看图/纯文本降级/标题模板兜底, 远程图转dataURL防过期)
- QuickVideo.tsx: 第1步封面与文案并行生成, 第4步封面预览行,
  封面插时间轴最前3秒, 未就绪拦截确认, resetAll清理
- 新增 E2E 脚本 scripts/e2e_quickvideo_cover.py (mock网关, 10项断言全过)
- lint: doc.88531.cn 入 allowlist, lan 文档示例豁免 (external_refs=0)
- 文档: CHANGELOG/README/about.md 教程同步
2026-11-17 17:50:51 +08:00

513 lines
21 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
00_lint_dist.py — UniCut 站点 dist 产物静态 lint(断网可用检查)
对构建产物做全量静态扫描,回答三个问题:
1. 还有哪些外部 URL?(按 host 聚合 + file:line 明细,区分「会真发起请求」与
「只是字符串/命名空间/文档」)
2. 懒加载 chunk 的 import 指向哪里?有没有指向外域的 chunk?
3. 音视频 / 字体 / SDK 的引用位置与当前取值是什么?本地文件是否齐全?
用法:
python3 data-quality/scripts/site/00_lint_dist.py [--dist dist] [--out 报告.md]
[--json 报告.json] [--no-fail]
退出码:外部网络引用(external_refs)为 0 时 0,否则 1(--no-fail 时恒 0)。
报告里的「不可消除项」= external_ref_allowlist.txt 里登记的、位于第三方压缩产物内部、
无法在不改动 vendored 代码的前提下删除的字符串,每条都带原因。
"""
import argparse
import bisect
import json
import os
import re
import sys
import time
from collections import Counter, defaultdict
from urllib.parse import urlparse
HERE = os.path.dirname(os.path.abspath(__file__))
REPO = os.path.dirname(os.path.dirname(os.path.dirname(HERE)))
ALLOWLIST = os.path.join(HERE, 'external_ref_allowlist.txt')
# 二进制扩展名:直接跳过(不解码扫描)
BIN_EXT = {
'.png', '.jpg', '.jpeg', '.gif', '.webp', '.ico', '.bmp', '.avif', '.mp4', '.webm',
'.mov', '.m4v', '.mp3', '.m4a', '.aac', '.wav', '.ogg', '.flac', '.woff', '.woff2',
'.ttf', '.otf', '.eot', '.wasm', '.data', '.bin', '.onnx', '.tflite', '.task',
'.glb', '.gltf', '.zip', '.gz', '.br', '.pak', '.db', '.ico',
}
TEXT_EXT = {
'.html', '.htm', '.js', '.mjs', '.cjs', '.css', '.less', '.json', '.svg', '.txt',
'.md', '.webmanifest', '.map', '.xml', '.ts', '.tsx', '.conf', '.csv',
}
# 少量无扩展名但其实是文本的文件
TEXT_NAMES = {'LICENSE', 'README', 'Makefile', 'CNAME', '.well-known'}
# 会真发起网络请求才算「外部依赖」的已知远程域(无 scheme 命中也算)
KNOWN_HOST_RE = None # main() 里编译
KNOWN_REMOTE_HOSTS = [
'esm.video.h5ds.com', 'esm-debug.video.h5ds.com', # video-core-sdk 远程 CDN 前缀
'audio01.h5ds.com', 'qkgzjp.h5ds.com', # 远程音频域
'cdn.h5ds.com', 'video.h5ds.com', 'fvideo.h5ds.com', 'videomix.h5ds.com',
'water.i.h5ds.com', 'lf3-static.bytednsdoc.com', 'byteblacksmith.com',
'unpkg.com', 'cdn.jsdelivr.net', 'registry.npmmirror.com', 'cdnjs.cloudflare.com',
'fonts.googleapis.com', 'fonts.gstatic.com', 'map.qq.com', 'apis.map.qq.com',
'player.bilibili.com', 'player.vimeo.com', 'www.youtube.com',
]
URL_RE = re.compile(r'https?://[^\s"\'`<>()\[\]{}\\,;]+')
# 字面量里带 scheme 的资源引用(含模板字符串里的完整地址)
ASSET_URL_RE = re.compile(
r'(?<![\w$./@:\-])[\w$./@\-]{1,300}\.(?:mp3|m4a|aac|wav|ogg|mp4|webm|mov|m4v|jpg|jpeg|png|gif|webp|svg|ico|'
r'woff2?|ttf|otf|eot|wasm|task|onnx|tflite|json|js|css|lottie)(?:\?[^\s"\'`]*)?')
IMPORT_RE = re.compile(r'import\(\s*["\'`]([^"\'`]+)["\'`]\s*\)')
WORKER_RE = re.compile(r'new\s+Worker\(\s*["\'`]([^"\'`]+)["\'`]')
MEDIA_FONT_EXT = {
'mp3', 'm4a', 'aac', 'wav', 'ogg', 'mp4', 'webm', 'mov', 'm4v',
'woff', 'woff2', 'ttf', 'otf', 'eot', 'wasm', 'task', 'onnx', 'tflite',
}
SDK_MARKERS = ('video-core-sdk', 'ffmpeg', 'tesseract', 'ort.', 'mediapipe', 'effectcanvas',
'lame', 'medianinfo', 'mp4box', 'opencv', 'onnxruntime')
def is_probably_text(path):
ext = os.path.splitext(path)[1].lower()
if ext in BIN_EXT:
return False
if ext in TEXT_EXT or os.path.basename(path) in TEXT_NAMES:
return True
if ext:
return False
try:
with open(path, 'rb') as f:
head = f.read(4096)
return b'\x00' not in head
except OSError:
return False
def load_allowlist():
"""每行:regex<TAB>类别<TAB>原因"""
rules = []
if not os.path.exists(ALLOWLIST):
return rules
for raw in open(ALLOWURLS_FILE if False else ALLOWLIST, encoding='utf-8'):
line = raw.strip()
if not line or line.startswith('#'):
continue
parts = line.split('\t')
if len(parts) < 3:
continue
try:
rules.append((re.compile(parts[0]), parts[1], parts[2]))
except re.error:
print('[warn] allowlist 正则无效:', parts[0], file=sys.stderr)
return rules
NAMESPACE_HOSTS = {'www.w3.org', 'purl.org', 'schemas.openxmlformats.org', 'www.opengis.net',
# pdf.js XFA/XMP:XML 命名空间与 schema 标识符(xmlns:xfa=...、startsWith判断),
# 浏览器不会发起请求,与 w3.org 同类
'www.xfa.org', 'ns.adobe.com'}
DOC_EXT = {'.md', '.map', '.txt'}
def ext_of(relpath):
return os.path.splitext(relpath)[1].lower()
def classify(url, relpath, allow_rules):
"""返回 (category, reason)。category ∈ namespace|local|lan|doc|sourcemap|allow|net"""
try:
host = urlparse(url).netloc.lower().split('@')[-1].split(':')[0]
except Exception:
host = ''
ext = os.path.splitext(relpath)[1].lower()
if host in NAMESPACE_HOSTS:
return 'namespace', 'XML/SVG 命名空间 URI,浏览器不发起请求'
if host in ('localhost', '127.0.0.1', '0.0.0.0', '::1', '[::1]'):
if os.path.splitext(relpath)[1].lower() in DOC_EXT:
return 'doc', '文档里写的本机示例地址,不会发起请求'
return 'local', '本机地址(残留的开发期配置)'
if re.match(r'^(192\.168\.\d+|10\.\d+|172\.(1[6-9]|2\d|3[01])|169\.254)\.\d+$', host):
if ext in DOC_EXT:
return 'doc', '文档里写的内网示例地址,不会发起请求'
return 'lan', '内网地址,仍会发起网络请求'
if ext in DOC_EXT:
return 'doc', '文档/Source Map 文件'
if relpath in ('stats.html',) or relpath.endswith('/stats.html'):
return 'sourcemap', 'rollup 可视化报告,不被页面引用'
for rx, cat, reason in allow_rules:
if rx.search(url):
return cat, reason
return 'net', '未登记的外部 URL'
class LineIndex:
"""O(log n) 行号查询:大体积压缩产物(单行几 MB 的 JS)上避免 O(n^2)。"""
def __init__(self, text):
self.nl = [m.start() for m in re.finditer('\n', text)]
def line(self, pos):
return bisect.bisect_right(self.nl, pos) + 1
def line_of(text, pos):
return text.count('\n', 0, pos) + 1
def snippet(text, pos, width=70):
a, b = max(0, pos - width), min(len(text), pos + width)
return text[a:b].replace('\n', '\\n')
def main():
ap = argparse.ArgumentParser()
ap.add_argument('--dist', default=os.path.join(REPO, 'dist'))
ap.add_argument('--out', default=None)
ap.add_argument('--json', dest='json_out', default=None)
ap.add_argument('--no-fail', action='store_true')
ap.add_argument('--max-rows', type=int, default=200)
args = ap.parse_args()
dist = os.path.abspath(args.dist)
if not os.path.isdir(dist):
print('dist 不存在:', dist, file=sys.stderr)
return 2
t0 = time.time()
allow_rules = load_allowlist()
# 预先收集 dist 内所有文件,避免上万次 os.path.exists 系统调用
dist_files = set()
for root, dirs, files in os.walk(dist):
for fn in files:
dist_files.add(os.path.relpath(os.path.join(root, fn), dist).replace(os.sep, '/'))
global KNOWN_HOST_RE
KNOWN_HOST_RE = re.compile(r'(?<![\w.-])(' + '|'.join(re.escape(h) for h in KNOWN_REMOTE_HOSTS) + r')(?![\w-])')
url_hits = [] # {url, host, file, line, cat, reason, ctx}
text_files = skipped_bin = 0
known_host_hits = [] # 无 scheme 的已知远程域命中
media_refs = [] # 音视频/字体/SDK 引用
lazy_imports = [] # 懒加载 chunk
missing_local = []
for root, dirs, files in os.walk(dist):
dirs.sort()
for fn in sorted(files):
p = os.path.join(root, fn)
rel = os.path.relpath(p, dist).replace(os.sep, '/')
if not is_probably_text(p):
skipped_bin += 1
continue
text_files += 1
try:
text = open(p, encoding='utf-8', errors='replace').read()
except OSError:
continue
li = LineIndex(text)
seen_in_file = set()
for m in URL_RE.finditer(text):
url = m.group(0).rstrip('.,;:!?"\'')
cat, reason = classify(url, rel, allow_rules)
key = (url, li.line(m.start()))
if key in seen_in_file:
continue
seen_in_file.add(key)
url_hits.append({
'url': url, 'host': urlparse(url).netloc.lower(), 'file': rel,
'line': key[1], 'cat': cat, 'reason': reason,
'ctx': snippet(text, m.start()),
})
# 无 scheme 的已知远程域(例如 SDK 里拼出来的 host)。
# 文档/SourceMap 里出现域名只是一句话,不会发起请求,跳过。
for m in ([] if ext_of(rel) in DOC_EXT else KNOWN_HOST_RE.finditer(text)):
h = m.group(0)
key = (h, li.line(m.start()))
if key in seen_in_file:
continue
seen_in_file.add(key)
# 无 scheme 命中同样走一遍 allowlist:vendored 产物里的注释/元数据字符串
# 不该被判成外部依赖,但未登记的一律算 net
cat, reason = classify('http://' + h, rel, allow_rules)
if cat == 'net':
reason = '已知远程域(无 scheme 命中,未登记进允许清单)'
known_host_hits.append({
'url': h, 'host': h, 'file': rel, 'line': key[1],
'cat': cat, 'reason': reason,
'ctx': snippet(text, m.start()),
})
if rel.endswith(('.js', '.mjs', '.cjs', '.html')):
for rx, kind in ((IMPORT_RE, 'import()'), (WORKER_RE, 'new Worker')):
for m in rx.finditer(text):
lazy_imports.append({
'file': rel, 'line': li.line(m.start()), 'kind': kind,
'target': m.group(1),
})
if rel.endswith(('.map', '.md')):
pass # 文档/SourceMap 不做资源引用扫描
elif rel.endswith(('.js', '.mjs', '.cjs', '.css', '.html', '.json')):
for m in ASSET_URL_RE.finditer(text):
val = m.group(0)
if val.startswith(('data:', 'blob:')):
continue
if val.startswith('/node_modules/'):
continue # 构建期路径,运行时不会请求
line = li.line(m.start())
ext = val.rsplit('.', 1)[-1].split('?')[0].lower()
interesting = ext in MEDIA_FONT_EXT or any(k in val for k in SDK_MARKERS)
if not interesting:
continue
entry = {'file': rel, 'line': line, 'value': val, 'ext': ext,
'ctx': snippet(text, m.start(), 60)}
if val.startswith('http'):
entry['state'] = 'external'
elif val.startswith('//'):
# 协议相对地址只有「权威段带点」才真的是外域;
# //wasm/xxx.wasm 这类是第三方胶水代码里的文件路径
auth = val[2:].split('/')[0].split(':')[0]
if '.' in auth:
entry['state'] = 'external'
else:
entry['state'] = 'relative'
elif val.startswith('/'):
key = val.lstrip('/').split('?')[0]
entry['state'] = 'local-ok' if key in dist_files else 'local-missing'
if entry['state'] == 'local-missing':
missing_local.append(entry.copy())
else:
entry['state'] = 'relative'
media_refs.append(entry)
# manifest.json 里的远程前缀
manifest_info = []
for root, dirs, files in os.walk(dist):
for fn in files:
if fn != 'manifest.json':
continue
p = os.path.join(root, fn)
rel = os.path.relpath(p, dist).replace(os.sep, '/')
try:
data = json.load(open(p, encoding='utf-8'))
except Exception as e:
manifest_info.append({'file': rel, 'error': str(e)})
continue
flat = data if isinstance(data, dict) else {}
picked = {k: v for k, v in flat.items()
if isinstance(v, str) and ('prefix' in k or 'host' in k or 'url' in k)}
manifest_info.append({'file': rel, 'keys': picked})
# ---- 汇总 ----
by_cat = Counter(h['cat'] for h in url_hits)
ext_refs = ([h for h in url_hits if h['cat'] in ('net', 'lan', 'local')]
+ [h for h in known_host_hits if h['cat'] in ('net', 'lan', 'local')])
external_refs = len({(h['file'], h['line'], h['url']) for h in ext_refs})
by_host = defaultdict(lambda: Counter())
host_example = {}
for h in url_hits:
by_host[h['host']][h['cat']] += 1
host_example.setdefault(h['host'], '%s:%s' % (h['file'], h['line']))
for h in known_host_hits:
by_host[h['host']][h['cat']] += 1
host_example.setdefault(h['host'], '%s:%s' % (h['file'], h['line']))
ts = time.strftime('%Y%m%d-%H%M%S')
out_md = args.out or os.path.join(REPO, 'data-quality', 'reports', 'site', ts + '-lint-dist.md')
out_json = args.json_out or out_md.replace('.md', '.json')
ext_counter = Counter(r['ext'] for r in media_refs)
media_font_refs = [r for r in media_refs if r['ext'] in MEDIA_FONT_EXT]
sdk_refs = [r for r in media_refs if any(k in r['value'] for k in SDK_MARKERS)]
def rows(items, n=None):
return items if n is None else items[:n]
L = []
A = L.append
A('# UniCut dist 断网可用 lint 报告')
A('')
A('- 扫描目录:`%s`' % dist)
A('- 时间:%s(耗时 %.1fs)' % (time.strftime('%Y-%m-%d %H:%M:%S'), time.time() - t0))
A('- 文本文件 %d 个 / 跳过二进制 %d 个' % (text_files, skipped_bin))
A('')
A('## 结论')
A('')
A('| 指标 | 数值 |')
A('| --- | --- |')
A('| **外部网络引用 external_refs(必须为 0)** | **%d** |' % external_refs)
A('| URL 出现总次数(含命名空间/文档) | %d |' % (len(url_hits) + len(known_host_hits)))
A('| 其中 namespace(w3.org 等命名空间) | %d |' % by_cat.get('namespace', 0))
A('| 其中 doc / sourcemap(文档、SourceMap、可视化报告) | %d |' %
(by_cat.get('doc', 0) + by_cat.get('sourcemap', 0)))
A('| 其中 allowlist(vendored 产物内字符串,见附录) | %d |' % by_cat.get('allow', 0))
A('| 其中 local(本机地址残留) | %d |' % by_cat.get('local', 0))
A('| 其中 lan(内网地址,仍发请求) | %d |' % by_cat.get('lan', 0))
A('| 音视频/字体/SDK 引用(去重后条目) | %d |' % len(media_refs))
A('| 其中指向外域 | %d |' % sum(1 for r in media_refs if r['state'] == 'external'))
A('| 其中本地缺失 | %d |' % len(missing_local))
A('')
A('**判定:%s**' % ('✅ 通过:dist 内没有任何会发起外网请求的引用'
if external_refs == 0 else '❌ 未通过:存在 %d 处外部网络引用' % external_refs))
A('')
A('## 1. 外部 URL 按 host 聚合')
A('')
A('| host | 次数 | 分类 | 示例位置 |')
A('| --- | --- | --- | --- |')
for host, cats in sorted(by_host.items(), key=lambda kv: (-sum(kv[1].values()), kv[0])):
A('| %s | %d | %s | `%s` |' % (host or '(空)', sum(cats.values()),
', '.join('%s×%d' % (k, v) for k, v in cats.most_common()),
host_example.get(host, '')))
A('')
A('## 2. 外部网络引用明细(必须为 0)')
A('')
if ext_refs:
A('| # | file:line | URL | 说明 |')
A('| --- | --- | --- | --- |')
for i, h in enumerate(rows(ext_refs, args.max_rows), 1):
A('| %d | `%s:%s` | `%s` | %s |' % (i, h['file'], h['line'], h['url'], h['reason']))
if len(ext_refs) > args.max_rows:
A('')
A('> 其余 %d 行见 JSON 报告。' % (len(ext_refs) - args.max_rows))
else:
A('无。')
A('')
A('## 3. 懒加载 chunk import')
A('')
A('共 %d 处动态 import / Worker 创建。' % len(lazy_imports))
A('')
external_chunks = [x for x in lazy_imports if x['target'].startswith('http')]
if external_chunks:
A('⚠️ 指向外域的 chunk:')
for x in external_chunks[:50]:
A('- `%s:%s` %s → `%s`' % (x['file'], x['line'], x['kind'], x['target']))
else:
A('全部指向同源相对路径(`/homeAssets/...` 等),无外域 chunk。')
A('')
A('<details><summary>完整清单(前 200 条)</summary>')
A('')
for x in rows(lazy_imports, 200):
A('- `%s:%s` %s → `%s`' % (x['file'], x['line'], x['kind'], x['target']))
A('')
A('</details>')
A('')
A('## 4. 音视频 / 字体 / SDK 引用')
A('')
A('扩展名分布:' + ', '.join('%s×%d' % (k, v) for k, v in ext_counter.most_common()))
A('')
A('### 4.1 指向外域(必须为 0)')
A('')
ext_media = [r for r in media_refs if r['state'] == 'external']
if ext_media:
for r in rows(ext_media, args.max_rows):
A('- `%s:%s` → `%s`' % (r['file'], r['line'], r['value']))
else:
A('无。')
A('')
A('### 4.2 本地路径但文件缺失(功能降级 / TODO)')
A('')
if missing_local:
for r in rows(missing_local, args.max_rows):
A('- `%s:%s` → `%s`' % (r['file'], r['line'], r['value']))
else:
A('无。')
A('')
A('### 4.3 字体 / 音视频 / 关键 SDK 取值抽样')
A('')
A('| file:line | 取值 | 状态 |')
A('| --- | --- | --- |')
for r in rows(media_font_refs, 80):
A('| `%s:%s` | `%s` | %s |' % (r['file'], r['line'], r['value'], r['state']))
A('')
A('<details><summary>SDK 相关引用(%d 条)</summary>' % len(sdk_refs))
A('')
for r in rows(sdk_refs, 120):
A('- `%s:%s` → `%s`(%s)' % (r['file'], r['line'], r['value'], r['state']))
A('')
A('</details>')
A('')
A('## 5. assets/manifest.json 远程前缀')
A('')
if manifest_info:
for m in manifest_info:
A('- `%s`:' % m['file'])
if 'error' in m:
A(' - 解析失败:%s' % m['error'])
elif m.get('keys'):
for k, v in m['keys'].items():
A(' - `%s` = `%s`' % (k, v))
else:
A(' - 无 remote_prefix / preview_prefix 等远程前缀字段')
else:
A('dist 内没有 `assets/manifest.json`(video-core-sdk 未随包发布远程前缀清单)。')
A('')
A('## 6. TODO 与不可消除项')
A('')
A('### 6.1 allowlist(vendored 产物内、无法在不改第三方代码的前提下删除的字符串)')
A('')
allow_by_reason = defaultdict(Counter)
for h in url_hits:
if h['cat'] == 'allow':
allow_by_reason[h['reason']][h['host']] += 1
if allow_by_reason:
for reason, hosts in allow_by_reason.items():
A('- %s:%s' % (reason, ', '.join('%s×%d' % (k, v) for k, v in hosts.most_common())))
else:
A('无。')
A('')
A('### 6.2 本地资源缺失 / 功能降级(详见 4.2)')
A('')
if missing_local:
for r in rows(missing_local, 60):
A('- [ ] `%s`(`%s:%s`)' % (r['value'], r['file'], r['line']))
else:
A('- [x] 无缺失的本地音视频/字体/SDK 资源。')
A('')
A('## 附录:报告文件')
A('')
A('- JSON:`%s`' % os.path.relpath(out_json, REPO))
A('- 允许清单:`%s`' % os.path.relpath(ALLOWLIST, REPO))
A('')
os.makedirs(os.path.dirname(out_md), exist_ok=True)
open(out_md, 'w', encoding='utf-8').write('\n'.join(L))
json.dump({
'dist': dist,
'external_refs': external_refs,
'by_category': dict(by_cat),
'known_host_hits': known_host_hits,
'url_hits': url_hits,
'lazy_imports': lazy_imports,
'media_refs': media_refs,
'missing_local': missing_local,
'manifest': manifest_info,
'files': {'text': text_files, 'binary_skipped': skipped_bin},
'report_md': out_md,
}, open(out_json, 'w', encoding='utf-8'), ensure_ascii=False, indent=2)
print('external_refs = %d' % external_refs)
print('报告:', out_md)
return 0 if (external_refs == 0 or args.no_fail) else 1
if __name__ == '__main__':
sys.exit(main())