来源仓库:jxc/ai-fresh-delivery 来源提交:f0b1a180e2deb7e4673b9d1c8542619f7bc0f73d 快照树: 09f679334ff38f0ff25e907961c94a8223bcaedd(与来源 HEAD 工作树逐字节一致,3801 个文件) 按约定本仓库不带任何历史提交:来源仓库的历史中含真实凭据 (生产 SSH 私钥 deploy/id_rsa_tencent、server/.env、.env.tencent/.env.production/.env.gitea、 deploy/小程序AppSecret.txt,其中 MP_APPSECRET / S3 AccessKey 经哈希比对与线上同值), 整包推送会把这些凭据永久带入本仓库,故只取「当前版本」的单提交快照。 供应商系统后续开发自本提交开始。
215 lines
6.6 KiB
JavaScript
215 lines
6.6 KiB
JavaScript
#!/usr/bin/env node
|
|
/**
|
|
* 从各租户 inspections 导出有验收照的图片到目录(按商品名 item_name),供视觉预训练。
|
|
* 设计:docs/design/20260901-inspection-vision-dataset-opencv.md
|
|
*
|
|
* 用法(生产机 /opt/ai-fresh-delivery/server):
|
|
* node scripts/export-inspection-vision-dataset.mjs
|
|
* node scripts/export-inspection-vision-dataset.mjs --out=/tmp/inspection-vision-raw --limit=100
|
|
* node scripts/export-inspection-vision-dataset.mjs --tar
|
|
*/
|
|
import fs from 'fs';
|
|
import path from 'path';
|
|
import { fileURLToPath, pathToFileURL } from 'url';
|
|
import { createRequire } from 'module';
|
|
import { spawnSync } from 'child_process';
|
|
|
|
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
|
const serverRoot = path.resolve(__dirname, '..');
|
|
const require = createRequire(path.join(serverRoot, 'package.json'));
|
|
require('dotenv').config({ path: path.join(serverRoot, '.env') });
|
|
|
|
const BUCKET = 'inspection-photos';
|
|
|
|
function argValue(name, fallback) {
|
|
const hit = process.argv.find((a) => a.startsWith(`${name}=`));
|
|
return hit ? hit.slice(name.length + 1) : fallback;
|
|
}
|
|
|
|
const outRoot = path.resolve(argValue('--out', '/tmp/inspection-vision-raw'));
|
|
const limit = Number(argValue('--limit', '0')) || 0;
|
|
const doTar = process.argv.includes('--tar');
|
|
const tarPath = argValue('--tar-path', '/tmp/inspection-vision-raw.tar.gz');
|
|
|
|
/** 商品名作目录名:去掉 Windows 非法字符,限制长度 */
|
|
function safeProductName(name) {
|
|
let s = String(name || '')
|
|
.trim()
|
|
.replace(/[<>:"/\\|?*\x00-\x1f]/g, '_')
|
|
.replace(/[. ]+$/g, '')
|
|
.replace(/\s+/g, ' ');
|
|
if (!s) return '';
|
|
return s.slice(0, 80);
|
|
}
|
|
|
|
function safeFilePart(s) {
|
|
return String(s || '')
|
|
.trim()
|
|
.replace(/[<>:"/\\|?*\x00-\x1f]/g, '_')
|
|
.slice(0, 80);
|
|
}
|
|
|
|
const { pool } = await import(pathToFileURL(path.join(serverRoot, 'dist/db.js')).href);
|
|
const { getStorageProvider } = await import(
|
|
pathToFileURL(path.join(serverRoot, 'dist/services/storageProvider/index.js')).href
|
|
);
|
|
|
|
const storage = getStorageProvider();
|
|
|
|
const schemas = (
|
|
await pool.query(`
|
|
SELECT nspname
|
|
FROM pg_namespace
|
|
WHERE nspname LIKE 'tenant_%' AND nspname <> 'tenant_template'
|
|
ORDER BY nspname
|
|
`)
|
|
).rows.map((r) => r.nspname);
|
|
|
|
fs.mkdirSync(outRoot, { recursive: true });
|
|
|
|
const manifest = {
|
|
bucket: BUCKET,
|
|
label_key: 'item_name',
|
|
exported_at: new Date().toISOString(),
|
|
items: [],
|
|
missing: [],
|
|
skipped_no_name: 0,
|
|
downloaded: 0,
|
|
failed: 0,
|
|
};
|
|
|
|
let remaining = limit > 0 ? limit : Infinity;
|
|
|
|
for (const sch of schemas) {
|
|
const has = await pool.query(`SELECT to_regclass($1) IS NOT NULL AS ok`, [`${sch}.inspections`]);
|
|
if (!has.rows[0]?.ok) continue;
|
|
|
|
const branchGuess = sch.replace(/^tenant_/i, '').toUpperCase();
|
|
const q = await pool.query(`
|
|
SELECT
|
|
id::text AS id,
|
|
NULLIF(TRIM(sku_code), '') AS sku_code,
|
|
NULLIF(TRIM(COALESCE(item_name, '')), '') AS item_name,
|
|
NULLIF(TRIM(COALESCE(branch_code, '')), '') AS branch_code,
|
|
NULLIF(TRIM(COALESCE(order_code, '')), '') AS order_code,
|
|
inspection_photos
|
|
FROM ${sch}.inspections
|
|
WHERE inspection_time IS NOT NULL
|
|
AND COALESCE(array_length(inspection_photos, 1), 0) > 0
|
|
ORDER BY inspection_time DESC NULLS LAST, id
|
|
`);
|
|
|
|
for (const row of q.rows) {
|
|
if (remaining <= 0) break;
|
|
const productName = safeProductName(row.item_name);
|
|
if (!productName) {
|
|
manifest.skipped_no_name += 1;
|
|
continue;
|
|
}
|
|
const sku = String(row.sku_code || '').trim();
|
|
const branch = safeFilePart(row.branch_code || branchGuess) || 'UNK';
|
|
const photos = Array.isArray(row.inspection_photos) ? row.inspection_photos : [];
|
|
const classDir = path.join(outRoot, productName);
|
|
fs.mkdirSync(classDir, { recursive: true });
|
|
|
|
for (let i = 0; i < photos.length; i++) {
|
|
if (remaining <= 0) break;
|
|
const objectKey = String(photos[i] || '').trim();
|
|
if (!objectKey) continue;
|
|
|
|
const ext = path.extname(objectKey).toLowerCase() || '.jpg';
|
|
const base = `${branch}_${safeFilePart(row.id)}_${i}${ext}`;
|
|
const dest = path.join(classDir, base);
|
|
const rel = path.join(productName, base).replace(/\\/g, '/');
|
|
|
|
try {
|
|
if (fs.existsSync(dest) && fs.statSync(dest).size > 0) {
|
|
manifest.items.push({
|
|
item_name: productName,
|
|
sku_code: sku,
|
|
branch_code: branch,
|
|
inspection_id: row.id,
|
|
order_code: row.order_code,
|
|
source_path: objectKey,
|
|
local_path: rel,
|
|
reused: true,
|
|
});
|
|
manifest.downloaded += 1;
|
|
remaining -= 1;
|
|
continue;
|
|
}
|
|
|
|
const obj = await storage.getObject(BUCKET, objectKey);
|
|
if (!obj?.buffer?.byteLength) {
|
|
manifest.missing.push({
|
|
schema: sch,
|
|
item_name: productName,
|
|
sku_code: sku,
|
|
source_path: objectKey,
|
|
inspection_id: row.id,
|
|
});
|
|
continue;
|
|
}
|
|
fs.writeFileSync(dest, obj.buffer);
|
|
manifest.items.push({
|
|
item_name: productName,
|
|
sku_code: sku,
|
|
branch_code: branch,
|
|
inspection_id: row.id,
|
|
order_code: row.order_code,
|
|
source_path: objectKey,
|
|
local_path: rel,
|
|
bytes: obj.buffer.byteLength,
|
|
});
|
|
manifest.downloaded += 1;
|
|
remaining -= 1;
|
|
if (manifest.downloaded % 50 === 0) {
|
|
console.log(`[export] downloaded ${manifest.downloaded} ...`);
|
|
}
|
|
} catch (err) {
|
|
manifest.failed += 1;
|
|
manifest.missing.push({
|
|
schema: sch,
|
|
item_name: productName,
|
|
sku_code: sku,
|
|
source_path: objectKey,
|
|
inspection_id: row.id,
|
|
error: String(err?.message || err),
|
|
});
|
|
}
|
|
}
|
|
}
|
|
if (remaining <= 0) break;
|
|
}
|
|
|
|
manifest.distinct_names = new Set(manifest.items.map((x) => x.item_name)).size;
|
|
fs.writeFileSync(path.join(outRoot, 'manifest.json'), JSON.stringify(manifest, null, 2));
|
|
|
|
console.log(
|
|
JSON.stringify(
|
|
{
|
|
out: outRoot,
|
|
downloaded: manifest.downloaded,
|
|
distinct_names: manifest.distinct_names,
|
|
missing: manifest.missing.length,
|
|
skipped_no_name: manifest.skipped_no_name,
|
|
failed: manifest.failed,
|
|
},
|
|
null,
|
|
2
|
|
)
|
|
);
|
|
|
|
await pool.end();
|
|
|
|
if (doTar) {
|
|
const parent = path.dirname(outRoot);
|
|
const base = path.basename(outRoot);
|
|
const r = spawnSync('tar', ['-czf', tarPath, '-C', parent, base], { stdio: 'inherit' });
|
|
if (r.status !== 0) {
|
|
console.error('tar failed', r.status);
|
|
process.exit(r.status || 1);
|
|
}
|
|
console.log('tar:', tarPath);
|
|
}
|