From 1717e05b070fbbcfd4d2c01cacd928651a355fd6 Mon Sep 17 00:00:00 2001 From: yibo Date: Fri, 5 Jun 2026 17:02:23 +0800 Subject: [PATCH] feat(lifelog/photolog): 微信联系人头像 → 人脸锚点 + 自动认人 --- lifelog-recorder/.gitignore | 3 +++ lifelog-recorder/app/src/main/kotlin/com/lemon/lifelog/PhotologScreen.kt | 60 ++++++++++++++++++++++++++++++++++++++++++------------------ lifelog-recorder/app/src/main/kotlin/com/lemon/lifelog/PhotologViewModel.kt | 14 ++++++++++++++ lifelog-recorder/app/src/main/kotlin/com/lemon/lifelog/data/AppDatabase.kt | 11 +++++++++-- lifelog-recorder/app/src/main/kotlin/com/lemon/lifelog/data/Daos.kt | 10 ++++++++++ lifelog-recorder/app/src/main/kotlin/com/lemon/lifelog/data/Entities.kt | 2 ++ lifelog-recorder/app/src/main/kotlin/com/lemon/lifelog/vision/FaceMatcher.kt | 54 ++++++++++++++++++++++++++++++++++-------------------- lifelog-recorder/app/src/main/kotlin/com/lemon/lifelog/vision/PhotoProcessor.kt | 18 +++++------------- lifelog-recorder/app/src/main/kotlin/com/lemon/lifelog/vision/WeChatEnrollWorker.kt | 93 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ server/services/wechat/extract-wechat-avatars.py | 82 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 10 files changed, 294 insertions(+), 53 deletions(-) create mode 100644 lifelog-recorder/app/src/main/kotlin/com/lemon/lifelog/vision/WeChatEnrollWorker.kt create mode 100644 server/services/wechat/extract-wechat-avatars.py diff --git a/lifelog-recorder/.gitignore b/lifelog-recorder/.gitignore index 573ccab..dd56d32 100644 --- a/lifelog-recorder/.gitignore +++ b/lifelog-recorder/.gitignore @@ -18,3 +18,6 @@ keys.properties # 录音恢复备份(DB 误清后从设备抢救的原始音频,勿入库) _recovered_segments_*/ + +# 微信联系人头像/姓名(enrollment 用,敏感 PII,勿入库) +_wx_enroll/ diff --git a/lifelog-recorder/app/src/main/kotlin/com/lemon/lifelog/PhotologScreen.kt b/lifelog-recorder/app/src/main/kotlin/com/lemon/lifelog/PhotologScreen.kt index d188bef..533eda3 100644 --- a/lifelog-recorder/app/src/main/kotlin/com/lemon/lifelog/PhotologScreen.kt +++ b/lifelog-recorder/app/src/main/kotlin/com/lemon/lifelog/PhotologScreen.kt @@ -280,26 +280,50 @@ private fun TagFaceDialog( @Composable private fun PeopleList(vm: PhotologViewModel, persons: List, onOpen: (Long) -> Unit) { var renameFor by remember { mutableStateOf(null) } - if (persons.isEmpty()) { - Box(Modifier.fillMaxSize().padding(24.dp), contentAlignment = Alignment.Center) { - Text("还没有人物。去「照片」里点一张脸标注,就会自动建立人物并归类照片。", style = MaterialTheme.typography.bodyMedium) + val enrollReady = remember { vm.wechatEnrollReady() } + var enrollTapped by remember { mutableStateOf(false) } + + Column(modifier = Modifier.fillMaxSize()) { + if (enrollReady) { + Row( + modifier = Modifier.fillMaxWidth().padding(12.dp), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(8.dp), + ) { + Button(onClick = { vm.enrollWeChat(); enrollTapped = true }) { Text("从微信导入联系人") } + Text( + if (enrollTapped) "后台建锚点中,人物会陆续出现…" else "用头像建人脸锚点,照片自动认人", + style = MaterialTheme.typography.labelSmall, + ) + } + HorizontalDivider() } - return - } - LazyColumn(modifier = Modifier.fillMaxSize().padding(12.dp), verticalArrangement = Arrangement.spacedBy(6.dp)) { - items(persons, key = { it.id }) { p -> - val count by produceState(0, p.id) { value = withContext(Dispatchers.IO) { vm.repo.faces.countForPerson(p.id) } } - Card(modifier = Modifier.fillMaxWidth().clickable { onOpen(p.id) }) { - Row( - modifier = Modifier.fillMaxWidth().padding(14.dp), - horizontalArrangement = Arrangement.SpaceBetween, - verticalAlignment = Alignment.CenterVertically, - ) { - Column { - Text(p.name, style = MaterialTheme.typography.titleSmall) - Text("$count 张人脸" + (if (p.voiceSpeakerId != null) " · 已绑声纹" else ""), style = MaterialTheme.typography.labelSmall) + if (persons.isEmpty()) { + Box(Modifier.fillMaxSize().padding(24.dp), contentAlignment = Alignment.Center) { + Text("还没有人物。点上方「从微信导入联系人」,或去「照片」里点一张脸标注。", style = MaterialTheme.typography.bodyMedium) + } + } else { + LazyColumn(modifier = Modifier.fillMaxSize().padding(12.dp), verticalArrangement = Arrangement.spacedBy(6.dp)) { + items(persons, key = { it.id }) { p -> + val count by produceState(0, p.id) { value = withContext(Dispatchers.IO) { vm.repo.faces.countForPerson(p.id) } } + Card(modifier = Modifier.fillMaxWidth().clickable { onOpen(p.id) }) { + Row( + modifier = Modifier.fillMaxWidth().padding(14.dp), + horizontalArrangement = Arrangement.SpaceBetween, + verticalAlignment = Alignment.CenterVertically, + ) { + Column(modifier = Modifier.weight(1f)) { + Text(p.name, maxLines = 1, overflow = TextOverflow.Ellipsis, style = MaterialTheme.typography.titleSmall) + Text( + "$count 张人脸" + + (if (p.contactRef != null) " · 微信" else "") + + (if (p.voiceSpeakerId != null) " · 声纹" else ""), + style = MaterialTheme.typography.labelSmall, + ) + } + TextButton(onClick = { renameFor = p }) { Text("重命名") } + } } - TextButton(onClick = { renameFor = p }) { Text("重命名") } } } } diff --git a/lifelog-recorder/app/src/main/kotlin/com/lemon/lifelog/PhotologViewModel.kt b/lifelog-recorder/app/src/main/kotlin/com/lemon/lifelog/PhotologViewModel.kt index 5d057f4..5f6cacf 100644 --- a/lifelog-recorder/app/src/main/kotlin/com/lemon/lifelog/PhotologViewModel.kt +++ b/lifelog-recorder/app/src/main/kotlin/com/lemon/lifelog/PhotologViewModel.kt @@ -8,9 +8,13 @@ import androidx.lifecycle.viewModelScope import com.lemon.lifelog.data.Person import com.lemon.lifelog.data.Photo import com.lemon.lifelog.data.Repository +import androidx.work.ExistingWorkPolicy +import androidx.work.OneTimeWorkRequestBuilder +import androidx.work.WorkManager import com.lemon.lifelog.vision.FaceMatcher import com.lemon.lifelog.vision.ImageUtil import com.lemon.lifelog.vision.PhotoScheduler +import com.lemon.lifelog.vision.WeChatEnrollWorker import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import kotlinx.coroutines.withContext @@ -70,6 +74,16 @@ class PhotologViewModel(app: Application) : AndroidViewModel(app) { viewModelScope.launch { repo.persons.updateName(personId, name.trim()) } } + /** 设备上是否已备好微信 enroll 数据(Mac 推过来的头像+清单)。 */ + fun wechatEnrollReady(): Boolean = + File(getApplication().filesDir, "wx_enroll/enroll.json").exists() + + /** 触发后台把微信头像建成人脸锚点(幂等,已在跑则忽略)。 */ + fun enrollWeChat() { + val req = OneTimeWorkRequestBuilder().build() + WorkManager.getInstance(getApplication()).enqueueUniqueWork("wx-enroll", ExistingWorkPolicy.KEEP, req) + } + fun deletePhoto(photoId: Long) { viewModelScope.launch { withContext(Dispatchers.IO) { diff --git a/lifelog-recorder/app/src/main/kotlin/com/lemon/lifelog/data/AppDatabase.kt b/lifelog-recorder/app/src/main/kotlin/com/lemon/lifelog/data/AppDatabase.kt index e5d872c..f327cda 100644 --- a/lifelog-recorder/app/src/main/kotlin/com/lemon/lifelog/data/AppDatabase.kt +++ b/lifelog-recorder/app/src/main/kotlin/com/lemon/lifelog/data/AppDatabase.kt @@ -20,7 +20,7 @@ import androidx.sqlite.db.SupportSQLiteDatabase Photo::class, Face::class, ], - version = 4, + version = 5, exportSchema = false, ) abstract class AppDatabase : RoomDatabase() { @@ -64,6 +64,13 @@ abstract class AppDatabase : RoomDatabase() { } } + /** v0.7 photolog:persons 加人脸锚点 embedding(微信头像/标注样本)。 */ + private val MIGRATION_4_5 = object : Migration(4, 5) { + override fun migrate(db: SupportSQLiteDatabase) { + db.execSQL("ALTER TABLE `persons` ADD COLUMN `faceEmbedding` BLOB") + } + } + fun get(ctx: Context): AppDatabase = instance ?: synchronized(this) { instance ?: Room.databaseBuilder( @@ -71,7 +78,7 @@ abstract class AppDatabase : RoomDatabase() { AppDatabase::class.java, "lifelog.db", ) - .addMigrations(MIGRATION_2_3, MIGRATION_3_4) + .addMigrations(MIGRATION_2_3, MIGRATION_3_4, MIGRATION_4_5) // 不再 fallbackToDestructiveMigration:以后改 schema 必须写 Migration, // 否则启动直接抛 IllegalStateException(fail-loud),绝不静默清掉真实录音。 .build() diff --git a/lifelog-recorder/app/src/main/kotlin/com/lemon/lifelog/data/Daos.kt b/lifelog-recorder/app/src/main/kotlin/com/lemon/lifelog/data/Daos.kt index 7e81c2a..85910a4 100644 --- a/lifelog-recorder/app/src/main/kotlin/com/lemon/lifelog/data/Daos.kt +++ b/lifelog-recorder/app/src/main/kotlin/com/lemon/lifelog/data/Daos.kt @@ -221,6 +221,16 @@ interface PersonDao { @Query("SELECT * FROM persons WHERE id = :id") suspend fun get(id: Long): Person? + @Query("SELECT * FROM persons WHERE contactRef = :ref LIMIT 1") + suspend fun getByContactRef(ref: String): Person? + + /** 有人脸锚点的人(匹配 gallery 用)。 */ + @Query("SELECT * FROM persons WHERE faceEmbedding IS NOT NULL") + suspend fun anchors(): List + + @Query("UPDATE persons SET faceEmbedding = :emb WHERE id = :id") + suspend fun updateFaceEmbedding(id: Long, emb: ByteArray) + @Query("UPDATE persons SET name = :name WHERE id = :id") suspend fun updateName(id: Long, name: String) diff --git a/lifelog-recorder/app/src/main/kotlin/com/lemon/lifelog/data/Entities.kt b/lifelog-recorder/app/src/main/kotlin/com/lemon/lifelog/data/Entities.kt index 8c5be18..1285db4 100644 --- a/lifelog-recorder/app/src/main/kotlin/com/lemon/lifelog/data/Entities.kt +++ b/lifelog-recorder/app/src/main/kotlin/com/lemon/lifelog/data/Entities.kt @@ -95,6 +95,8 @@ data class Person( /** 微信/通讯录联系人引用(如 "wechat:wxid_xxx"),null = 手动建 */ val contactRef: String? = null, val avatarPath: String? = null, + /** 人脸锚点 embedding(512维 LE bytes,来自头像或标注样本),用于自动认人;null = 还没有 */ + val faceEmbedding: ByteArray? = null, val createdAt: Long = System.currentTimeMillis(), ) diff --git a/lifelog-recorder/app/src/main/kotlin/com/lemon/lifelog/vision/FaceMatcher.kt b/lifelog-recorder/app/src/main/kotlin/com/lemon/lifelog/vision/FaceMatcher.kt index 9dd4d6d..27eef30 100644 --- a/lifelog-recorder/app/src/main/kotlin/com/lemon/lifelog/vision/FaceMatcher.kt +++ b/lifelog-recorder/app/src/main/kotlin/com/lemon/lifelog/vision/FaceMatcher.kt @@ -3,36 +3,50 @@ package com.lemon.lifelog.vision import com.lemon.lifelog.data.Repository /** - * 人脸归属匹配(与声纹的 SpeakerMatcher 同构)。 - * 标注一张脸到某 Person 后,把所有未归属的脸跟已命名的脸库比余弦,自动回填。 + * 人脸归属匹配(与声纹 SpeakerMatcher 同构)。 + * 匹配 gallery = 人物锚点(微信头像 embedding) + 已标注的脸样本。 */ object FaceMatcher { - private const val THRESH = PhotoProcessor.THRESH + const val THRESH = PhotoProcessor.THRESH - /** 把 [faceId] 指派给 [personId],然后回填其它未归属的脸。 */ + /** 当前所有 (personId, embedding):人物锚点 + 已标注脸。 */ + suspend fun gallery(repo: Repository): List> { + val out = ArrayList>() + for (p in repo.persons.anchors()) { + p.faceEmbedding?.let { out.add(p.id to ImageUtil.unpackEmbedding(it)) } + } + for (f in repo.faces.allWithEmbedding()) { + if (f.personId != null && f.embedding != null) { + out.add(f.personId!! to ImageUtil.unpackEmbedding(f.embedding!!)) + } + } + return out + } + + /** 给一个 embedding 在 gallery 里找最佳人物,余弦 ≥ THRESH 返回 (personId, sim),否则 null。 */ + fun match(gallery: List>, emb: FloatArray): Pair? { + var bestId: Long? = null + var bestSim = THRESH + for ((pid, g) in gallery) { + val c = FaceEngine.cosine(emb, g) + if (c > bestSim) { bestSim = c; bestId = pid } + } + return bestId?.let { it to bestSim } + } + + /** 标注一张脸到某 Person,然后回填其它未归属的脸。 */ suspend fun assignAndBackfill(repo: Repository, faceId: Long, personId: Long) { repo.faces.assignPerson(faceId, personId, 1f) backfillAll(repo) } - /** - * 对所有未归属的脸:跟已命名脸库做最近邻,余弦 ≥ THRESH 则归属。 - * 反复一轮即可(新归属的脸不会再扩大已命名集合的语义)。 - */ + /** 对所有未归属的脸跑一遍匹配(新建人物锚点 / 标注后调用)。 */ suspend fun backfillAll(repo: Repository) { - val gallery = repo.faces.allWithEmbedding() - .filter { it.personId != null && it.embedding != null } - .map { it.personId!! to ImageUtil.unpackEmbedding(it.embedding!!) } - if (gallery.isEmpty()) return + val g = gallery(repo) + if (g.isEmpty()) return for (f in repo.faces.unassigned()) { - val emb = ImageUtil.unpackEmbedding(f.embedding!!) - var bestId: Long? = null - var bestSim = THRESH - for ((pid, g) in gallery) { - val c = FaceEngine.cosine(emb, g) - if (c > bestSim) { bestSim = c; bestId = pid } - } - if (bestId != null) repo.faces.assignPerson(f.id, bestId, bestSim) + val m = match(g, ImageUtil.unpackEmbedding(f.embedding!!)) + if (m != null) repo.faces.assignPerson(f.id, m.first, m.second) } } } diff --git a/lifelog-recorder/app/src/main/kotlin/com/lemon/lifelog/vision/PhotoProcessor.kt b/lifelog-recorder/app/src/main/kotlin/com/lemon/lifelog/vision/PhotoProcessor.kt index 6760171..f3cf162 100644 --- a/lifelog-recorder/app/src/main/kotlin/com/lemon/lifelog/vision/PhotoProcessor.kt +++ b/lifelog-recorder/app/src/main/kotlin/com/lemon/lifelog/vision/PhotoProcessor.kt @@ -40,26 +40,18 @@ class PhotoProcessor( if (caption != null) repo.photos.updateCaption(photo.id, caption, "vl") - // 已命名 Person 的人脸样本(personId != null)→ 匹配新脸。 - val gallery = repo.faces.allWithEmbedding() - .filter { it.personId != null && it.embedding != null } - .map { it.personId!! to ImageUtil.unpackEmbedding(it.embedding!!) } - + // 匹配 gallery = 微信头像锚点 + 已标注脸样本。 + val gallery = FaceMatcher.gallery(repo) for (fr in faces) { - var bestId: Long? = null - var bestSim = THRESH - for ((pid, emb) in gallery) { - val c = FaceEngine.cosine(fr.embedding, emb) - if (c > bestSim) { bestSim = c; bestId = pid } - } + val m = FaceMatcher.match(gallery, fr.embedding) repo.faces.insert( Face( photoId = photo.id, left = fr.face.x1, top = fr.face.y1, right = fr.face.x2, bottom = fr.face.y2, detScore = fr.face.score, embedding = ImageUtil.packEmbedding(fr.embedding), - personId = bestId, - personSim = if (bestId != null) bestSim else null, + personId = m?.first, + personSim = m?.second, ), ) } diff --git a/lifelog-recorder/app/src/main/kotlin/com/lemon/lifelog/vision/WeChatEnrollWorker.kt b/lifelog-recorder/app/src/main/kotlin/com/lemon/lifelog/vision/WeChatEnrollWorker.kt new file mode 100644 index 0000000..a7b8ff2 --- /dev/null +++ b/lifelog-recorder/app/src/main/kotlin/com/lemon/lifelog/vision/WeChatEnrollWorker.kt @@ -0,0 +1,93 @@ +package com.lemon.lifelog.vision + +import android.content.Context +import android.util.Log +import androidx.work.CoroutineWorker +import androidx.work.WorkerParameters +import com.lemon.lifelog.data.Person +import com.lemon.lifelog.data.Repository +import org.json.JSONArray +import java.io.File +import java.util.concurrent.atomic.AtomicBoolean + +/** + * 把微信联系人头像建成人脸锚点:读 filesDir/wx_enroll/enroll.json([{username,name}])+ + * avatars/{username}.jpg,对每张头像用**端上 FaceEngine** 检测,恰 1 张脸就建 Person + * (contactRef=wechat:username, avatarPath, faceEmbedding)。之后照片人脸自动认出联系人。 + * + * 必须用端上 FaceEngine(与照片人脸同一引擎)才能跨比;不能用 Mac insightface 的 embedding。 + * 单轮有时间预算,超了 retry 续;按 contactRef 幂等。 + */ +class WeChatEnrollWorker(ctx: Context, params: WorkerParameters) : CoroutineWorker(ctx, params) { + + override suspend fun doWork(): Result { + if (!isRunning.compareAndSet(false, true)) return Result.success() + try { + val dir = File(applicationContext.filesDir, "wx_enroll") + val manifest = File(dir, "enroll.json") + if (!manifest.exists()) { + Log.w(TAG, "no enroll.json at ${manifest.path}") + return Result.success() + } + val arr = JSONArray(manifest.readText()) + val repo = Repository(applicationContext) + val engine = FaceEngine.load(applicationContext) + var enrolled = 0 + var scanned = 0 + var hitDeadline = false + val deadline = System.currentTimeMillis() + RUN_BUDGET_MS + try { + for (i in 0 until arr.length()) { + if (System.currentTimeMillis() > deadline) { hitDeadline = true; break } + val o = arr.getJSONObject(i) + val username = o.optString("username") + val name = o.optString("name").ifBlank { username } + val ref = "wechat:$username" + if (repo.persons.getByContactRef(ref) != null) continue // 幂等 + + val avatar = File(dir, "avatars/$username.jpg") + if (!avatar.exists()) continue + val bmp = ImageUtil.decodeOriented(avatar.absolutePath, reqMax = 640) ?: continue + scanned++ + try { + val det = engine.detect(bmp) + if (det.size == 1) { + val emb = engine.embed(bmp, det[0].kps) + repo.persons.insert( + Person( + name = name, + contactRef = ref, + avatarPath = avatar.absolutePath, + faceEmbedding = ImageUtil.packEmbedding(emb), + ), + ) + enrolled++ + } + } catch (t: Throwable) { + Log.w(TAG, "enroll $username failed: ${t.message}") + } finally { + bmp.recycle() + } + } + } finally { + engine.close() + } + // 用新锚点回填已处理照片里的未归属脸。 + FaceMatcher.backfillAll(repo) + Log.i(TAG, "本轮 enroll $enrolled(扫 $scanned),deadline=$hitDeadline") + return if (hitDeadline) Result.retry() else Result.success() + } catch (t: Throwable) { + Log.e(TAG, "worker failed", t) + return Result.retry() + } finally { + isRunning.set(false) + } + } + + companion object { + const val TAG = "WeChatEnroll" + /** 单轮预算 8min(端上 ~0.4s/张),超了 retry 续;WorkManager ~10min 上限内。 */ + const val RUN_BUDGET_MS = 8 * 60 * 1000L + private val isRunning = AtomicBoolean(false) + } +} diff --git a/server/services/wechat/extract-wechat-avatars.py b/server/services/wechat/extract-wechat-avatars.py new file mode 100644 index 0000000..693f201 --- /dev/null +++ b/server/services/wechat/extract-wechat-avatars.py @@ -0,0 +1,82 @@ +#!/usr/bin/env python3 +""" +微信联系人头像提取 —— 给 lifelog/photolog 的人脸锚点 enrollment 备数据。 + +流程(在 Mac 上跑,需要 `brew install sqlcipher`): + 1. adb 把设备上的 EnMicroMsg.db 拉到本地(需 root)。 + 2. 用微信的 SQLCipher 配方解密:key + cipher_compatibility=1 + page 1024。 + 3. join rcontact ⨝ img_flag,筛真人(verifyFlag=0,排除群/公众号/企业微信/系统号), + img_flag.reserved1 = 高清头像 URL(wx.qlogo.cn,公开可拉)。 + 4. 并行下载头像 → avatars/{username}.jpg。 + 5. (可选)insightface 估"有脸"覆盖率,导出 oneface 清单。 + +产物(敏感 PII,勿入库)放 lifelog-recorder/_wx_enroll/:contacts.json / avatars/ / oneface_usernames.json +然后 push 到设备 filesDir/wx_enroll/,app「从微信导入联系人」用端上 FaceEngine 建锚点。 + + DB key / 路径因设备而异,见 android-wechat-tracker-sqlcipher.js(key 'e03ce81', + 路径 /data/data/com.tencent.mm/MicroMsg//EnMicroMsg.db)。 + +用法: + python3 extract-wechat-avatars.py /tmp/EnMicroMsg.db e03ce81 ./_wx_enroll +""" +import sys, os, json, subprocess, urllib.request, concurrent.futures + +REAL_PERSON_SQL = """ +SELECT r.username AS username, + COALESCE(NULLIF(r.conRemark,''), NULLIF(r.nickname,''), r.username) AS name, + f.reserved1 AS avatar +FROM rcontact r JOIN img_flag f ON f.username=r.username +WHERE r.verifyFlag=0 + AND r.username NOT LIKE '%@chatroom' + AND r.username NOT LIKE 'gh_%' + AND r.username NOT LIKE '%@openim' + AND r.username NOT IN ('weixin','filehelper','fmessage','medianote','floatbottle', + 'qmessage','qqmail','newsapp','officialaccounts','helper_entry','exmail_tool', + 'mphelper','brandsessionholder') + AND f.reserved1 LIKE 'http%'; +""" + + +def decrypt_and_query(db_path, key): + script = (f'PRAGMA key="{key}";\nPRAGMA cipher_compatibility=1;\n' + f'PRAGMA cipher_page_size=1024;\n.mode json\n{REAL_PERSON_SQL}\n') + out = subprocess.run(['sqlcipher', db_path], input=script, + capture_output=True, text=True).stdout + return json.loads(out[out.index('['):]) # 跳过开头 PRAGMA 的 "ok" + + +def download(items, out_dir): + os.makedirs(out_dir, exist_ok=True) + + def dl(it): + dest = os.path.join(out_dir, it['username'] + '.jpg') + if os.path.exists(dest) and os.path.getsize(dest) > 0: + return True + try: + req = urllib.request.Request(it['avatar'], headers={'User-Agent': 'Mozilla/5.0'}) + b = urllib.request.urlopen(req, timeout=12).read() + if len(b) < 200: + return False + open(dest, 'wb').write(b) + return True + except Exception: + return False + + with concurrent.futures.ThreadPoolExecutor(max_workers=24) as ex: + return sum(1 for r in ex.map(dl, items) if r) + + +def main(): + db_path, key, out_root = sys.argv[1], sys.argv[2], sys.argv[3] + os.makedirs(out_root, exist_ok=True) + items = decrypt_and_query(db_path, key) + json.dump(items, open(os.path.join(out_root, 'contacts.json'), 'w'), ensure_ascii=False) + print(f'真人联系人(有头像): {len(items)}') + n = download(items, os.path.join(out_root, 'avatars')) + print(f'头像下载: {n}') + print('下一步:(可选)insightface 估覆盖率导出 oneface_usernames.json,' + '再 push 到设备 filesDir/wx_enroll/,app 内「从微信导入联系人」。') + + +if __name__ == '__main__': + main() -- libgit2 0.21.4