photo-service.js
9.85 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
/**
* PhotoService — 多模态资产关联服务
*
* 功能:
* detectFaces(imagePath) → 调用 Python face_recognition,返回人脸数组
* linkPhotoToPerson(imagePath, nameOrId, meta) → 关联照片到联系人(Asset:photo 节点 + CONTAINS 边)
* extractExif(imagePath) → 提取 JPEG EXIF GPS/时间信息
*/
const { spawn } = require('child_process');
const path = require('path');
const fs = require('fs');
const { getGraphStore } = require('../../db/GraphStore');
class PhotoService {
constructor(photoDirOrFile) {
this.photoDirOrFile = photoDirOrFile;
}
/**
* 调用 Python face_recognition,返回人脸列表
* @param {string} imagePath
* @returns {Promise<Array<{faceId, bbox, encoding}>>}
*/
async detectFaces(imagePath) {
return new Promise((resolve, reject) => {
const scriptPath = path.join(__dirname, 'face_recognizer.py');
const py = spawn('python3', [scriptPath, 'detect', imagePath]);
let out = '';
let errOut = '';
py.stdout.on('data', d => { out += d; });
py.stderr.on('data', d => { errOut += d; });
py.on('close', code => {
if (code === 0) {
try {
resolve(JSON.parse(out));
} catch (e) {
resolve([]); // 解析失败时返回空数组(graceful fallback)
}
} else {
reject(new Error('face_recognizer failed: ' + (errOut || out)));
}
});
py.on('error', err => {
// python3 不存在时 graceful fallback
resolve([]);
});
});
}
/**
* 将照片作为 Asset 节点关联到指定 Person
* @param {string} imagePath - 照片文件绝对路径
* @param {string} personNameOrId - 联系人姓名或节点 id
* @param {object} meta - 额外元数据(可选)
* @returns {Promise<{assetId, personId, exif}>}
*/
async linkPhotoToPerson(imagePath, personNameOrId, meta = {}) {
const g = getGraphStore();
// 查找联系人
let person = g.getNode(personNameOrId);
if (!person || person._type !== 'Person') {
const results = g.findByName(personNameOrId, 'Person');
person = results[0] || null;
}
if (!person) {
throw new Error(`未找到联系人:${personNameOrId}`);
}
// 提取 EXIF
let exif = null;
try {
exif = await this.extractExif(imagePath);
} catch { /* EXIF 提取失败不阻断主流程 */ }
// 创建 Asset:photo 节点
const fileName = path.basename(imagePath);
const assetData = {
type: 'photo',
name: fileName,
filePath: imagePath,
source: 'local',
...meta,
};
if (exif) {
if (exif.lat !== undefined && exif.lng !== undefined) {
assetData.lat = exif.lat;
assetData.lng = exif.lng;
}
if (exif.datetime) {
assetData.takenAt = exif.datetime;
}
}
const asset = g.createNode('Asset', assetData);
// 创建 CONTAINS 边(Person → Asset)
g.createEdge(person.id, asset.id, 'CONTAINS');
return {
assetId: asset.id,
personId: person.id,
personName: person.name,
exif,
};
}
/**
* 简单解析 JPEG EXIF GPS 数据(纯 Node.js,不依赖外部库)
*
* 仅读取 APP1 段中的 GPS IFD,提取纬度、经度、拍摄时间。
* 如果文件不是 JPEG 或没有 GPS 数据,返回 null。
*
* @param {string} imagePath
* @returns {Promise<{lat, lng, datetime}|null>}
*/
async extractExif(imagePath) {
return new Promise((resolve) => {
try {
const fd = fs.openSync(imagePath, 'r');
// 读取前 64KB 以覆盖 EXIF 段
const bufSize = 65536;
const buf = Buffer.alloc(bufSize);
const bytesRead = fs.readSync(fd, buf, 0, bufSize, 0);
fs.closeSync(fd);
const data = buf.slice(0, bytesRead);
// JPEG 魔数检查
if (data[0] !== 0xFF || data[1] !== 0xD8) {
resolve(null);
return;
}
// 查找 APP1 段(0xFF 0xE1)
let offset = 2;
let exifBuf = null;
while (offset < data.length - 4) {
if (data[offset] !== 0xFF) break;
const marker = data[offset + 1];
const segLen = data.readUInt16BE(offset + 2);
if (marker === 0xE1) {
// 检查 'Exif\0\0' 签名
if (data.slice(offset + 4, offset + 10).toString('ascii') === 'Exif\0\0') {
exifBuf = data.slice(offset + 10, offset + 2 + segLen);
break;
}
}
offset += 2 + segLen;
}
if (!exifBuf) {
resolve(null);
return;
}
// 解析 TIFF 字节序
const isLittleEndian = exifBuf.slice(0, 2).toString('ascii') === 'II';
const readUInt16 = (buf, off) =>
isLittleEndian ? buf.readUInt16LE(off) : buf.readUInt16BE(off);
const readUInt32 = (buf, off) =>
isLittleEndian ? buf.readUInt32LE(off) : buf.readUInt32BE(off);
// IFD0 偏移
const ifd0Offset = readUInt32(exifBuf, 4);
const numEntries = readUInt16(exifBuf, ifd0Offset);
let gpsIFDOffset = null;
let dateTimeStr = null;
for (let i = 0; i < numEntries; i++) {
const entryOffset = ifd0Offset + 2 + i * 12;
if (entryOffset + 12 > exifBuf.length) break;
const tag = readUInt16(exifBuf, entryOffset);
if (tag === 0x8825) {
// GPSInfo IFD pointer
gpsIFDOffset = readUInt32(exifBuf, entryOffset + 8);
} else if (tag === 0x0132) {
// DateTime (ASCII)
const count = readUInt32(exifBuf, entryOffset + 4);
const valOff = count <= 4
? entryOffset + 8
: readUInt32(exifBuf, entryOffset + 8);
try {
dateTimeStr = exifBuf.slice(valOff, valOff + 19).toString('ascii');
} catch { /* skip */ }
}
}
if (!gpsIFDOffset) {
resolve(dateTimeStr ? { datetime: dateTimeStr } : null);
return;
}
// 解析 GPS IFD
let lat = null, lng = null, latRef = 'N', lngRef = 'E';
const gpsEntries = readUInt16(exifBuf, gpsIFDOffset);
for (let i = 0; i < gpsEntries; i++) {
const entryOffset = gpsIFDOffset + 2 + i * 12;
if (entryOffset + 12 > exifBuf.length) break;
const tag = readUInt16(exifBuf, entryOffset);
const type = readUInt16(exifBuf, entryOffset + 2);
const count = readUInt32(exifBuf, entryOffset + 4);
const valOff = count * (type === 5 ? 8 : 1) > 4
? readUInt32(exifBuf, entryOffset + 8)
: entryOffset + 8;
if (tag === 0x0001) {
// GPSLatitudeRef
latRef = exifBuf.slice(valOff, valOff + 1).toString('ascii');
} else if (tag === 0x0003) {
// GPSLongitudeRef
lngRef = exifBuf.slice(valOff, valOff + 1).toString('ascii');
} else if (tag === 0x0002 && type === 5 && count === 3) {
// GPSLatitude (3 rationals: degrees, minutes, seconds)
lat = this._parseGPSRational(exifBuf, valOff, readUInt32);
} else if (tag === 0x0004 && type === 5 && count === 3) {
// GPSLongitude
lng = this._parseGPSRational(exifBuf, valOff, readUInt32);
}
}
const result = {};
if (lat !== null) result.lat = latRef === 'S' ? -lat : lat;
if (lng !== null) result.lng = lngRef === 'W' ? -lng : lng;
if (dateTimeStr) result.datetime = dateTimeStr;
resolve(Object.keys(result).length > 0 ? result : null);
} catch (e) {
resolve(null); // 任何错误都 graceful fallback
}
});
}
/** 解析 GPS 有理数(度/分/秒 → 十进制度) */
_parseGPSRational(buf, offset, readUInt32) {
try {
const degN = readUInt32(buf, offset);
const degD = readUInt32(buf, offset + 4);
const minN = readUInt32(buf, offset + 8);
const minD = readUInt32(buf, offset + 12);
const secN = readUInt32(buf, offset + 16);
const secD = readUInt32(buf, offset + 20);
const deg = degD ? degN / degD : 0;
const min = minD ? minN / minD : 0;
const sec = secD ? secN / secD : 0;
return deg + min / 60 + sec / 3600;
} catch {
return null;
}
}
}
module.exports = { PhotoService };