Compare commits
531 Commits
v1.1.0
...
fd28677d66
| Author | SHA1 | Date | |
|---|---|---|---|
| fd28677d66 | |||
| be8333d8f3 | |||
| b47f473db6 | |||
| 8074bee4a1 | |||
| 3d441a1c76 | |||
| 63fbbe1225 | |||
| 0a18e70639 | |||
| b639291585 | |||
| 3d7d5cf684 | |||
| 42edfedb3f | |||
| 9d0f85c048 | |||
| 1379cf59cf | |||
| 3658c2888e | |||
| 86c776ce41 | |||
| ed95c447a9 | |||
| ca3e73b73a | |||
| 04e6bcb5a6 | |||
| 84d25468b9 | |||
| c508c9ed72 | |||
| 43228bd7e1 | |||
| b1bb051160 | |||
| a3a5bbdfa5 | |||
| a738b2d974 | |||
| 9b8ce5c2c7 | |||
| d55d398832 | |||
| 06a099e159 | |||
| 0b7aaee110 | |||
| c49707df0d | |||
| 66470f315b | |||
| 2ec0bc6706 | |||
| 1bb8928ab6 | |||
| d5786608f0 | |||
| 9596cec7ba | |||
| cd00a7fec5 | |||
| ab54382834 | |||
| 060edda3ae | |||
| e398595734 | |||
| 76c52f12fc | |||
| 948b0f653b | |||
| 6d138024e4 | |||
| 3ef6ccee7f | |||
| 0d5f5f4b22 | |||
| a535aa1b8d | |||
| e698e98b2c | |||
| d663184804 | |||
| e3b61689ed | |||
| 4ba6ab39a6 | |||
| bc441c1534 | |||
| 8b1efb307b | |||
| 93f041e0b3 | |||
| ae64ec9e09 | |||
| 2c476906d9 | |||
| 508ddb1488 | |||
| 4c6915d0e5 | |||
| e0e8af3ec5 | |||
| 7c7cf60a12 | |||
| 495e5e324a | |||
| 32e27971a7 | |||
| 94dd483bc6 | |||
| 3ab24e08f1 | |||
| c77d3b6766 | |||
| cf75e0c4c0 | |||
| 4f7162be4f | |||
| bd0bf6b15d | |||
| fe04c746ab | |||
| b3aabd1617 | |||
| bca83c2f26 | |||
| a621344ae8 | |||
| b83bb04496 | |||
| ea35d29f01 | |||
| 0d10466ba7 | |||
| c1e3a2012f | |||
| 3a3390a67d | |||
| 1c7e7481f6 | |||
| 007cba2bca | |||
| 7ffb45c137 | |||
| e48350e3f9 | |||
| aa621b874c | |||
| 08c2eb5c9c | |||
| 2635fdf84c | |||
| 37df95102d | |||
| e84d92d52c | |||
| fdb8d8e866 | |||
| 36c54fd5e8 | |||
| 1672a042af | |||
| c47ec64b8a | |||
| e5608c70c5 | |||
| 61b8fb3b52 | |||
| cccb0aa9b9 | |||
| 14bbae258b | |||
| 1e6226466c | |||
| b32a649496 | |||
| 036fc9f853 | |||
| 0afb90e26a | |||
| 6c95404a30 | |||
| 30ea384573 | |||
| 3285cf7696 | |||
| 1576b27528 | |||
| c55f664e47 | |||
| 1166599f70 | |||
| b4dec14f8d | |||
| e0eb7b9ce8 | |||
| 2f5e2c1314 | |||
| 0d11c60163 | |||
| ad30742374 | |||
| 1ca3eb1abe | |||
| 3399a137d8 | |||
| b331a3d0cd | |||
| d7df19e243 | |||
| 1ec094571f | |||
| a3c3ed8dc1 | |||
| 3d363e6266 | |||
| f79292f867 | |||
| 097b3721e8 | |||
| ba71daf2c4 | |||
| 15fc356666 | |||
| 65898ef71b | |||
| e1f13f485f | |||
| 162ece34f7 | |||
| 8c6a2de820 | |||
| 9e1fa0a3ff | |||
| 193af91cd7 | |||
| e0d04e242f | |||
| e987fb8119 | |||
| 8c7a5efd49 | |||
| 323fd342f1 | |||
| 4b694a1c2d | |||
| 144ec0768a | |||
| 91c4cf9dde | |||
| 6525a3fe94 | |||
| 8ce531e12a | |||
| dd09065daa | |||
| c419c07042 | |||
| acc8381ca5 | |||
| 92034e3147 | |||
| 10c238bbd9 | |||
| 2c274ecfdb | |||
| e643649323 | |||
| fa1f50d9e0 | |||
| 1aee0ce7ee | |||
| bca93c3a5d | |||
| 08f574efc5 | |||
| 676171cd64 | |||
| 8eca08c7c9 | |||
| 7963cd0223 | |||
| 50a9675513 | |||
| aa4e50f4dc | |||
| 23321376d8 | |||
| ef94fac8fa | |||
| 3890933fe1 | |||
| e95cdcc673 | |||
| 6b1345bd5a | |||
| 798c0d747b | |||
| c3b40e6f27 | |||
| 585fd8728a | |||
| a001453e91 | |||
| d52ab1104d | |||
| 2171028eff | |||
| d90430b26e | |||
| a63a9c776f | |||
| df8d2554a1 | |||
| 9823cd4328 | |||
| 10be95f7b9 | |||
| 80b2c69a4d | |||
| 80ebcd9622 | |||
| 990916e659 | |||
| 5f9ddd2d02 | |||
| efd6f4372e | |||
| fc42d5b752 | |||
| 6bac60bcf8 | |||
| 06397e5957 | |||
| 08b32e5eea | |||
| 6c705df0d9 | |||
| 0180661438 | |||
| 7c6e3af3c1 | |||
| a6b7d644b3 | |||
| c122913492 | |||
| 3ff45f983e | |||
| 6cfb4cfba6 | |||
| 9206074c12 | |||
| fbf356c950 | |||
| 90951342e1 | |||
| 020fd37b34 | |||
| f7796e5f43 | |||
| bd073ac74c | |||
| c790c6a429 | |||
| cd0eff1768 | |||
| d5e03d7096 | |||
| f371ff184b | |||
| cfe0b02a21 | |||
| dd8b911386 | |||
| 7f6b7ef060 | |||
| 7d5afba1cd | |||
| f15842e9cf | |||
| e38705e7d2 | |||
| bfa846f679 | |||
| 4a3d358b4c | |||
| 1529c021ef | |||
| 20b837ec0d | |||
| d1990e6181 | |||
| 01c4f69b4f | |||
| 782f326a34 | |||
| 83358a951d | |||
| 7d19ae4741 | |||
| 9003aa0548 | |||
| 0af9082aa9 | |||
| 63366e23c1 | |||
| e0766d22fc | |||
| d5e8968c97 | |||
| 123ae87c1a | |||
| b4e4b30b8e | |||
| be2c28b7f3 | |||
| 3ab65a698a | |||
| 33ee2d37c9 | |||
| cc4cb1f9f1 | |||
| 30b9a400ae | |||
| ac570d2114 | |||
| 05d40cc8a9 | |||
| 1f1522c5ef | |||
| 34d4025943 | |||
| 9d1f53d70b | |||
| de0aa06b15 | |||
| ecb209633a | |||
| 9cd3e20e48 | |||
| 4aa51405c5 | |||
| 25adc1017f | |||
| 96a6d79c87 | |||
| db9749df65 | |||
| 11319c0493 | |||
| 40749888e3 | |||
| 0e07ab79f6 | |||
| 8ec5fc61d8 | |||
| 5efa09a2b5 | |||
| 12390957e9 | |||
| 8ab6802bff | |||
| af028ab8f4 | |||
| db74b11e21 | |||
| 087b29dc93 | |||
| 3d54f0ba41 | |||
| 9175427006 | |||
| 74d2156007 | |||
| 5807e33653 | |||
| 23d5a49c41 | |||
| 82c400ed6c | |||
| 461bb291a0 | |||
| 72b2ba21c7 | |||
| 7f1a9f6810 | |||
| 7f6a968eb2 | |||
| edf0c3ec6d | |||
| 0558cd7615 | |||
| 04d409d2e4 | |||
| f4978cfe04 | |||
| f5c4cc829e | |||
| 7e202a1bd9 | |||
| add9a163c1 | |||
| 074a075525 | |||
| c7cda3b100 | |||
| e58d1078dd | |||
| 1f81100378 | |||
| 3ed4cb38b3 | |||
| ba18f4c403 | |||
| 4f60e7ae96 | |||
| 841de6dadb | |||
| 851be32945 | |||
| 3fbf04f8e7 | |||
| 165742d930 | |||
| a05d7e763e | |||
| 835772ba73 | |||
| 48eca7d836 | |||
| 5b76b3e647 | |||
| 6ec6a93764 | |||
| 74288a7ddd | |||
| 9088213769 | |||
| 8cd8a240b4 | |||
| 6796cce849 | |||
| eb4fd82a84 | |||
| 696ede8696 | |||
| 921bcba43a | |||
| 357e585399 | |||
| 8a736a4103 | |||
| b0244691cb | |||
| 55fcbf107d | |||
| 693bb56d7f | |||
| 953381a868 | |||
| aa6a8d9d45 | |||
| 2a422cdf6f | |||
| 40cf967347 | |||
| 1c55baad37 | |||
| 89e7a579bf | |||
| e283b477d2 | |||
| 7c54c7b7e7 | |||
| d95857dcc7 | |||
| ebee351523 | |||
| 93c8760788 | |||
| 73c59449fe | |||
| 3aaaf36ff6 | |||
| a8edc43a3f | |||
| 51c86a22f4 | |||
| 2c1618ef06 | |||
| 0fe09afdb6 | |||
| 31d1b4050f | |||
| e4b8ddab94 | |||
| c34b7b9ea0 | |||
| 9ffbfeb6c5 | |||
| 474a5bee99 | |||
| 791c782606 | |||
| e25c279eeb | |||
| 362a735a91 | |||
| d8e4033741 | |||
| 20f5974b52 | |||
| 8732c3e0a4 | |||
| 8b53384059 | |||
| 771115b42b | |||
| b5de4f6745 | |||
| e2c352d502 | |||
| d981e0a6fe | |||
| c3367b47b1 | |||
| 44ad6ac213 | |||
| 8a34dcb8f2 | |||
| 29f14e83c4 | |||
| 2bbbf1950d | |||
| b2378a219b | |||
| 9f12e835b8 | |||
| d29b4804af | |||
| ff9fb9a4ca | |||
| cce30ffacb | |||
| b8b8f2d6af | |||
| 58d80e34c6 | |||
| 906243fdc1 | |||
| 165af40f3c | |||
| 11d210ee55 | |||
| 978b2b338b | |||
| 054545bccd | |||
| 476a31ecc6 | |||
| 6d7b477b31 | |||
| efa17d4b62 | |||
| 78eb4fb8d9 | |||
| dda0b7cc7f | |||
| e2b9999cba | |||
| 7c9c3ded42 | |||
| 2466a41eb8 | |||
| 6c4c645337 | |||
| 0533248f2c | |||
| 5e6a7b7d51 | |||
| 39e9ce4c3b | |||
| 71172fa354 | |||
| e88f066d65 | |||
| 86f1fe8852 | |||
| 2e4559715b | |||
| c1e158a368 | |||
| 2b1af42d06 | |||
| 258f8c4e96 | |||
| 59ca6cdf83 | |||
| aa28bf93fb | |||
| 65da4b451a | |||
| d6f45683a0 | |||
| a3eba898e2 | |||
| 56ce009d84 | |||
| 4fc7d0cf6d | |||
| dfa515f249 | |||
| 9b6750b85e | |||
| 575623c765 | |||
| 1f71ab4e14 | |||
| 61b774ab0b | |||
| 496895422f | |||
| e1eae6a3d9 | |||
| c7690f43d2 | |||
| 5045d9f679 | |||
| 1571f675a5 | |||
| 658f509500 | |||
| d5c7fd91d9 | |||
| 8d83d9f217 | |||
| 8dada662e8 | |||
| a06973484b | |||
| 256e872fd9 | |||
| 606f4ce5be | |||
| c184711bfc | |||
| 1d3638649b | |||
| 9244dbc853 | |||
| ca8b910d59 | |||
| b52777ac03 | |||
| cd8df324be | |||
| 64f5e3f543 | |||
| 23c6f63742 | |||
| a6d705abf1 | |||
| 2117ca60b8 | |||
| 15967929ef | |||
| 3d13a06bd9 | |||
| 36a704e3d3 | |||
| c5c1b08ffd | |||
| 4d0d2204fd | |||
| 975c72eb49 | |||
| 5244386892 | |||
| e22393d577 | |||
| 8eb130959c | |||
| 1602656fb6 | |||
| 57f542fdad | |||
| d7980133e9 | |||
| 8a766799c7 | |||
| 4ca967e979 | |||
| d6653f8240 | |||
| 4c8041974a | |||
| d91ce0b4fc | |||
| 4a480f46fd | |||
| 40fc8c6a53 | |||
| d36132d93a | |||
| aab727b297 | |||
| 7272077b65 | |||
| 6081c552f6 | |||
| 85d5e1fe51 | |||
| 5d0c771a2b | |||
| 39a2cbc65b | |||
| fcdeab82e6 | |||
| 6f5d71763f | |||
| 644516769c | |||
| 52bec30c90 | |||
| 0ad6927d25 | |||
| d25b5921f7 | |||
| 29d2cc7315 | |||
| bc914ce3df | |||
| 5ec18ed520 | |||
| 70e6915246 | |||
| 7dc910e2de | |||
| 244af51edf | |||
| 2ed56b7973 | |||
| 84dda3b5bc | |||
| d0b7bfa56b | |||
| 455c6b81e6 | |||
| 3c924e1f83 | |||
| 87aa7e0c40 | |||
| 5e83ee7dac | |||
| 0d9aa7b470 | |||
| e4b8e9924c | |||
| 7635ad8d4d | |||
| b98a362de5 | |||
| 701727fd08 | |||
| 01f8b89636 | |||
| 2da0ada34a | |||
| 13abb15595 | |||
| 5a941f857c | |||
| 1ac0a144d5 | |||
| 356edb16be | |||
| 149226ff17 | |||
| bb606f52f5 | |||
| f56bdb7fbb | |||
| 3067896b0f | |||
| 146d3cedb2 | |||
| 765db8ae9f | |||
| dd63dbff9b | |||
| 27660f48e4 | |||
| e4fdbbc18a | |||
| 004ff9ad48 | |||
| 552f539bdf | |||
| 221aa4c4cc | |||
| 799ede5a0e | |||
| cb604b74ec | |||
| e91d51cc5e | |||
| 5a3f791ecd | |||
| 0b82aa875c | |||
| 465552f8b2 | |||
| 5fcd5212d5 | |||
| 53f28ac458 | |||
| 7fc4dcbddb | |||
| 96e13e40cb | |||
| 4e8c0ea5b9 | |||
| e4d6fbac50 | |||
| 78364afc51 | |||
| 5a9d4325d8 | |||
| 3035c6db5d | |||
| 28a4e9b1b8 | |||
| 3943075a9b | |||
| e2b3858b67 | |||
| bd6d108ade | |||
| d4c26deae2 | |||
| 619b056ada | |||
| 6507766ea2 | |||
| 64f29d614b | |||
| 3eabd45882 | |||
| d791d138f2 | |||
| bd7d8c77bf | |||
| 6f1a560d06 | |||
| 67caf09732 | |||
| 6cbc11efda | |||
| 615f9da2df | |||
| a2f2b7918a | |||
| 0c3f385b1f | |||
| fd2edd5736 | |||
| ecb0e9c7d0 | |||
| 4273576612 | |||
| 406b2d5524 | |||
| 4b4d37b332 | |||
| b19b1a8c46 | |||
| d20819b03b | |||
| b5e3adf5de | |||
| 4198a74002 | |||
| 21b9f500d9 | |||
| 6851cb4734 | |||
| 580c4b4017 | |||
| 9fbb4f9b48 | |||
| 074cdcdbed | |||
| 360cb991e1 | |||
| 14e886cc08 | |||
| 766a1d9a6d | |||
| e1e2da2140 | |||
| db8bb8fa95 | |||
| 70e849d3ae | |||
| 22f13eca4b | |||
| 30b252ac95 | |||
| f4de741d5b | |||
| c93b54efeb | |||
| 4ba248513e | |||
| 7e548f8b08 | |||
| bce9435823 | |||
| d0858f288a | |||
| 9e0a0227ea | |||
| d94b96d884 | |||
| 606f31f13c | |||
| 97180aa7cd | |||
| e949ac793d | |||
| 01dae66285 | |||
| 6ede2a443c | |||
| e214106d48 | |||
| 2cfcfdd1af | |||
| 0afc70fc5b | |||
| 721c343486 | |||
| c39805bb8e | |||
| 23c440104b | |||
| 2f2ccc94f7 | |||
| 3ad6f8740a | |||
| 17e4e15860 | |||
| 834b0d4865 |
@@ -0,0 +1 @@
|
||||
swiftbuild
|
||||
@@ -0,0 +1,4 @@
|
||||
Signature: 8a477f597d28d172789f06886806bc55
|
||||
# This file is a cache directory tag created by (Swift Package Manager).
|
||||
# For information about cache directory tags, see:
|
||||
#. http://www.brynosaurus.com/cachedir/
|
||||
@@ -0,0 +1,47 @@
|
||||
DATABASE_URL=postgres://accusys@localhost:5432/momentry
|
||||
DATABASE_SCHEMA=public
|
||||
MOMENTRY_DEMO_API_KEY='muser_demo_key_32chars_abcdef1234567890'
|
||||
REDIS_URL=redis://127.0.0.1:6379
|
||||
|
||||
# LLM Configuration
|
||||
# Agent Search uses Ollama (llama3.1:8b) - OpenAI-compatible endpoint
|
||||
MOMENTRY_LLM_CHAT_URL=http://localhost:8080/v1/chat/completions
|
||||
MOMENTRY_LLM_CHAT_MODEL=gemma-4-12b-it
|
||||
|
||||
# VLM uses Gemma4 12B (port 8080) - OpenAI-compatible endpoint
|
||||
# Gemma4 多模态已启用 (llama.cpp version 9590)
|
||||
MOMENTRY_LLM_VISION_URL=http://127.0.0.1:8080/v1/chat/completions
|
||||
MOMENTRY_LLM_VISION_MODEL=gemma-4-12b-it
|
||||
|
||||
# Summary LLM uses Ollama
|
||||
MOMENTRY_LLM_SUMMARY_URL=http://localhost:8080/v1/chat/completions
|
||||
MOMENTRY_LLM_SUMMARY_MODEL=gemma-4-12b-it
|
||||
MOMENTRY_LLM_SUMMARY_ENABLED=true
|
||||
|
||||
# Vector database
|
||||
QDRANT_URL=http://127.0.0.1:6333
|
||||
QDRANT_API_KEY=Test3200Test3200Test3200
|
||||
QDRANT_COLLECTION=momentry_rule1
|
||||
|
||||
# MongoDB
|
||||
MONGODB_URL=mongodb://localhost:27017
|
||||
MONGODB_DATABASE=momentry
|
||||
MONGODB_CACHE_ENABLED=true
|
||||
|
||||
# Embedding
|
||||
MOMENTRY_EMBED_URL=http://localhost:11436
|
||||
TMDB_API_KEY=e9cde52197f6f8df4d9db99da93db1fb
|
||||
MOMENTRY_TMDB_PROBE_ENABLED=false
|
||||
|
||||
# Video serve (Caddy file_server for local direct playback)
|
||||
MOMENTRY_STORAGE_ROOT=/Users/accusys/momentry/var/sftpgo/data
|
||||
MOMENTRY_SERVE_BASE_URL=https://m5wp.momentry.ddns.net/files
|
||||
MOMENTRY_PYTHON_PATH=/opt/homebrew/bin/python3.11
|
||||
RUST_LOG=info
|
||||
|
||||
# Rust Processors (Enable Rust implementations where available)
|
||||
|
||||
# MOMENTRY_FORCE_RETRY removed - use default (false) so max_retry=3 kicks in
|
||||
MOMENTRY_OUTPUT_DIR=/Users/accusys/momentry/output
|
||||
MOMENTRY_LLM_CHAT_TIMEOUT=300
|
||||
MOMENTRY_ASR_TIMEOUT=10800
|
||||
+12
-11
@@ -72,19 +72,20 @@ REDIS_CACHE_TTL_VIDEO_META=3600
|
||||
# TMDb Integration (probe phase - auto-create identities from movie metadata)
|
||||
TMDB_API_KEY=e9cde52197f6f8df4d9db99da93db1fb
|
||||
MOMENTRY_TMDB_PROBE_ENABLED=true
|
||||
# LLM for 5W1H summary (points to M5 Gemma4)
|
||||
MOMENTRY_LLM_SUMMARY_URL=http://127.0.0.1:8082/v1/chat/completions
|
||||
MOMENTRY_LLM_SUMMARY_MODEL=google_gemma-4-26B-A4B-it-Q5_K_M.gguf
|
||||
# LLM Configuration
|
||||
# Agent Search uses Ollama (llama3.1:8b) - OpenAI-compatible endpoint
|
||||
MOMENTRY_LLM_CHAT_URL=http://localhost:11434/v1/chat/completions
|
||||
MOMENTRY_LLM_CHAT_MODEL=llama3.1:8b
|
||||
|
||||
# VLM uses Ollama (llava:7b) - OpenAI-compatible endpoint
|
||||
MOMENTRY_LLM_VISION_URL=http://localhost:11434/v1/chat/completions
|
||||
MOMENTRY_LLM_VISION_MODEL=llava:7b
|
||||
|
||||
# Summary LLM uses Ollama
|
||||
MOMENTRY_LLM_SUMMARY_URL=http://localhost:11434/v1/chat/completions
|
||||
MOMENTRY_LLM_SUMMARY_MODEL=llama3.1:8b
|
||||
MOMENTRY_LLM_SUMMARY_ENABLED=true
|
||||
|
||||
# LLM Chat (A4B on port 8082)
|
||||
MOMENTRY_LLM_CHAT_URL=http://127.0.0.1:8082/v1/chat/completions
|
||||
MOMENTRY_LLM_CHAT_MODEL=google_gemma-4-26B-A4B-it-Q5_K_M.gguf
|
||||
|
||||
# LLM Vision (E4B on port 8083)
|
||||
MOMENTRY_LLM_VISION_URL=http://127.0.0.1:8083/v1/chat/completions
|
||||
MOMENTRY_LLM_VISION_MODEL=gemma-4-E4B-it-Q4_K_M.gguf
|
||||
|
||||
# Embedding (ANE CoreML server)
|
||||
MOMENTRY_EMBED_URL=http://localhost:11436
|
||||
|
||||
|
||||
+24
-4
@@ -43,10 +43,19 @@ MOMENTRY_LLM_VISION_MODEL=gemma-4-E4B-it-Q4_K_M.gguf
|
||||
MOMENTRY_LLM_VISION_TIMEOUT=120
|
||||
|
||||
# === Paths ===
|
||||
MOMENTRY_OUTPUT_DIR=/Users/accusys/momentry/output_dev
|
||||
MOMENTRY_BACKUP_DIR=/Users/accusys/momentry/backup
|
||||
MOMENTRY_SCRIPTS_DIR=/Users/accusys/momentry_core_0.1/scripts
|
||||
MOMENTRY_PYTHON_PATH=/opt/homebrew/bin/python3.11
|
||||
# These paths will be auto-detected if not set
|
||||
# Default: $HOME/momentry/output_dev
|
||||
# MOMENTRY_OUTPUT_DIR=/path/to/output
|
||||
|
||||
# Default: $HOME/momentry/backup
|
||||
# MOMENTRY_BACKUP_DIR=/path/to/backup
|
||||
|
||||
# Default: $PROJECT_ROOT/tools/script
|
||||
# MOMENTRY_SCRIPTS_DIR=/path/to/scripts
|
||||
|
||||
# Default: /opt/homebrew/bin/python3.11
|
||||
# MOMENTRY_PYTHON_PATH=/path/to/python
|
||||
|
||||
MOMENTRY_FFMPEG=/opt/homebrew/opt/ffmpeg-full/bin/ffmpeg
|
||||
MOMENTRY_MEDIA_BASE_URL=
|
||||
|
||||
@@ -61,3 +70,14 @@ MOMENTRY_DEFAULT_TIMEOUT=7200
|
||||
# === Server ===
|
||||
MOMENTRY_SERVER_PORT=3003
|
||||
MOMENTRY_LOG_LEVEL=info
|
||||
|
||||
# === Package Paths (init resolves @ROOT@ to install root) ===
|
||||
MOMENTRY_ENV_FILE=@ROOT@/config/.env
|
||||
MOMENTRY_SFTP_ROOT=@ROOT@/var/sftpgo/data/demo
|
||||
MOMENTRY_STORAGE_ROOT=@ROOT@/var/sftpgo/data
|
||||
MOMENTRY_OUTPUT_DIR=@ROOT@/var/output
|
||||
MOMENTRY_DATA_DIR=@ROOT@/data
|
||||
MOMENTRY_PROCESSORS_DIR=@ROOT@/processors
|
||||
|
||||
# === Init ===
|
||||
MOMENTRY_API_KEY=
|
||||
|
||||
@@ -47,3 +47,5 @@ package.json
|
||||
portal/dist/
|
||||
portal/src-tauri/icons/
|
||||
momentry_runtime/logs/
|
||||
*.bak
|
||||
*.bak_*
|
||||
|
||||
@@ -14,34 +14,46 @@ Rust-based digital asset management system with video analysis and RAG capabilit
|
||||
- **🔴 DELETE / REMOVE / DROP / CLEAR 任何資料前必須先問使用者「要刪嗎?」獲得明確同意後才能執行**
|
||||
- **🔴 Qdrant collection 刪除、DB truncate、檔案刪除、資料清空 — 一律要先問**
|
||||
- **🔴 不確定是否該刪 → 先問,不要自己決定**
|
||||
- **🔴 任何會移除資料的動作(unregister、DELETE、DROP、truncate、rm 檔案)都必須先詢問確認,絕對不可自行執行**
|
||||
- **🔴 改變議題前必須先存檔紀錄**:使用 `todowrite` 工具或建立紀錄文件(如 `docs_v1.0/M4_workspace/YYYY-MM-DD_topic_handoff.md`),確保上下文不丟失
|
||||
|
||||
### 開發範圍界定
|
||||
| 範圍 | 狀態 | 說明 |
|
||||
|------|------|------|
|
||||
| `momentry_core_0.1/` | ✅ **可開發** | Momentry Core 主要開發目錄 |
|
||||
| `momentry_core_0.1/portal/` | ✅ **可開發** | Tauri Portal 前端 |
|
||||
| `momentry_core_0.1/src/` | ✅ **可開發** | Rust 後端程式碼 |
|
||||
| `/Users/accusys/wordpress/` | ❌ **禁止修改** | WordPress/Marcom 團隊負責 |
|
||||
| `~/momentry_core/` | ✅ **可開發** | Momentry Core 後端(Rust),Core team 負責 |
|
||||
| `~/momentry_core/portal/` | ⚠️ **僅供測試** | Tauri Portal 僅用於測試,非正式前端 |
|
||||
| `~/momentry_studio/` | ❌ **禁止修改** | Momentry Studio 前端,**Studio team 負責** |
|
||||
| `/Users/accusys/wordpress/` | ❌ **禁止修改** | WordPress 網站僅供參考,已被 Studio 取代 |
|
||||
| n8n 工作流 | ❌ **禁止修改** | 自動化流程,與 dev 無關 |
|
||||
| WordPress/n8n 資料庫 table | ❌ **禁止修改** | Marcom 團隊管理,與 dev 無關 |
|
||||
|
||||
### 團隊職責劃分
|
||||
| 團隊 | 負責專案 | 目錄 |
|
||||
|------|---------|------|
|
||||
| **Core team** | Momentry Core 後端 | `~/momentry_core/` |
|
||||
| **Studio team** | Momentry Studio 前端 | `~/momentry_studio/` |
|
||||
| **Marcom team** | WordPress 網站(已停用) | `/Users/accusys/wordpress/` |
|
||||
|
||||
### 開發環境
|
||||
| 服務 | Port | 用途 | 命令 |
|
||||
|------|------|------|------|
|
||||
| Playground | 3003 | **唯一開發環境** | `cargo run --bin momentry_playground -- server` |
|
||||
| Production | 3002 | ❌ 禁止修改 | `cargo run -- server` (僅 release 時) |
|
||||
| Portal (Tauri) | 1420 | 前端開發 | `npm run tauri dev` |
|
||||
| 服務 | Port | 用途 | 命令 | 狀態 |
|
||||
|------|------|------|------|------|
|
||||
| Playground | 3003 | ~~開發環境~~ (暫停) | `cargo run --bin momentry_playground -- server` | 🔴 已暫停 (節省 memory) |
|
||||
| Production | 3002 | **開發 + 生產環境** | `cargo run -- server` | 🟢 運行中 (debug binary) |
|
||||
| Portal (Tauri) | 1420 | 前端開發 | `npm run tauri dev` | - |
|
||||
|
||||
> **注意 (2026-07-25)**: Playground (3003) 已暫停服務。Production (3002) 改為直接用於開發測試。新功能可直接部署至 3002。
|
||||
> **注意 (2026-07-23)**: 為節省記憶體,Playground (3003) 已關閉。Production (3002) 目前使用 debug binary 運行(已套用 smart_search 修復)。正式 release 時需重新 build release binary。
|
||||
|
||||
### 日誌與啟動
|
||||
| 服務 | 日誌路徑 | 啟動方式 |
|
||||
|------|----------|----------|
|
||||
| Production (3002) | `logs/momentry_3002.log` | `./run-server-3002.sh` |
|
||||
| Production (3002) | `logs/momentry_3002.log` | **launchd** (`com.momentry.server` + `com.momentry.worker`) |
|
||||
| Playground (3003) | `logs/momentry_3003.log` | `./run-server-3003.sh` |
|
||||
| Worker / 歷史 | `logs/nohup_worker_*.log` | 由 worker 自動產生 |
|
||||
| Worker / 歷史 | `logs/worker_3002.log` | 由 launchd worker 寫入 |
|
||||
|
||||
> **注意**: 所有伺服器日誌統一存放於專案內 `logs/` 目錄。
|
||||
> 啟動腳本會自動 kill 舊程序、重 build(若需要)、並將日誌導向 `logs/`。
|
||||
> **Production (3002) 正式部署由 launchd 管理**(`~/Library/LaunchAgents/com.momentry.server.plist` + `com.momentry.worker.plist`),兩者皆使用 `target/release/momentry`,KeepAlive 自動重啟。`run-server-3002.sh` 僅供開發時臨時手動啟動(會與 launchd 衝突,勿與 launchd 並用)。
|
||||
> **⚠️ 啟動 launchd worker 若未註冊**:`launchctl bootstrap gui/$(id -u) ~/Library/LaunchAgents/com.momentry.worker.plist`(不是 `load`),worker plist 的 VLM 指向 gemma 8080(8091 已停用)。
|
||||
|
||||
## ⚠️ 交叉污染防制 (Cross-Contamination Prevention)
|
||||
|
||||
@@ -204,8 +216,11 @@ cargo run -- server --host 0.0.0.0 --port 3002
|
||||
cargo run --bin momentry_playground -- server
|
||||
cargo run --bin momentry_playground -- --help
|
||||
|
||||
# Start servers (recommended — auto-build & logs to logs/)
|
||||
./run-server-3002.sh
|
||||
# Start servers (recommended — production via launchd, dev via scripts)
|
||||
# Production (3002) is managed by launchd: com.momentry.server + com.momentry.worker
|
||||
# launchctl start gui/$(id -u)/com.momentry.server
|
||||
# launchctl start gui/$(id -u)/com.momentry.worker
|
||||
# (run-server-3002.sh is dev-only and conflicts with launchd — do NOT mix)
|
||||
./run-server-3003.sh
|
||||
```
|
||||
|
||||
@@ -234,6 +249,156 @@ grep -i "error\|panic\|FAIL" logs/momentry_*.log | tail -20
|
||||
| `momentry_playground` | Development | 3003 | `momentry_dev:` | `.env.development` |
|
||||
| `momentry_player` | Video player | - | - | - |
|
||||
|
||||
## LLM Services
|
||||
|
||||
### 環境一致性原則
|
||||
|
||||
**生產環境 (port 3002) 與 Playground (port 3003) 使用相同的 LLM/VLM/Embedding 服務。**
|
||||
|
||||
### LLM Configuration
|
||||
|
||||
| 用途 | Model | 服務 | Port | API 格式 |
|
||||
|------|-------|------|------|----------|
|
||||
| **Chat / Summary / VLM** | `gemma-4-12b-it` | llama.cpp | 8080 | `/v1/chat/completions` |
|
||||
| **Embedding** | `embeddinggemma-300m` | Python | 11436 | Custom |
|
||||
|
||||
> **統一服務**:Gemma4 + mmproj 同時支援文字與視覺輸入,簡化配置並節省記憶體。
|
||||
|
||||
### ⚠️ 重要:Gemma4 多模態配置
|
||||
|
||||
**Gemma 4-12b 是多模態模型**,支援視覺輸入,需要正確配置:
|
||||
|
||||
1. **mmproj 檔案**:
|
||||
- 檔案:`/Users/accusys/models/mmproj-F16.gguf` (167MB)
|
||||
- 從 HuggingFace 下載:`https://huggingface.co/unsloth/gemma-4-12b-it-GGUF`
|
||||
- **必須載入才能處理圖片輸入**
|
||||
|
||||
2. **llama.cpp 版本要求**:
|
||||
- ✅ 需要最新版本(支援 `gemma4uv` projector type)
|
||||
- ❌ 2026年5月之前的版本不相容
|
||||
- 若遇到 "unknown projector type: gemma4uv" 錯誤 → 需更新 llama.cpp
|
||||
|
||||
3. **當前配置狀態**(M5Max128,2026-09-25 更新):
|
||||
- Chat Server (Port 8080):**已載入 mmproj** ✅
|
||||
- 統一服務:Gemma4 同時處理 Chat/Summary/VLM ✅
|
||||
- 舊 VLM Server (Port 8091):已停用(Llava 改為備用)
|
||||
|
||||
4. **思考模式特性**:
|
||||
- Gemma4 使用思考模式,會先推理再輸出最終答案
|
||||
- 文字 Chat:`max_tokens=300` 即可
|
||||
- 多模態 VLM:需要 `max_tokens=800-900` 才能完成思考
|
||||
- 若回應為空 → 增加 max_tokens
|
||||
|
||||
### LLM 模型切換系統
|
||||
|
||||
**文檔位置**:`/Users/accusys/momentry_core/docs_v1.0/OPERATIONS/LLM_SERVICES/`
|
||||
|
||||
**快速切換命令**:
|
||||
```bash
|
||||
# 安裝切換腳本
|
||||
cd ~/llm-deploy-doc
|
||||
mkdir -p ~/llm-config ~/bin
|
||||
cp models.json ~/llm-config/
|
||||
cp scripts/llm-* ~/bin/
|
||||
chmod +x ~/bin/llm-*
|
||||
|
||||
# 切換模型
|
||||
llm-7b # 快速模型(Llava 7B)
|
||||
llm-12b # 質量模型(Gemma 4 12B + mmproj)
|
||||
llm-13b # 多模態模型(Llava 13B)
|
||||
|
||||
# 查看狀態
|
||||
llms
|
||||
```
|
||||
|
||||
**部署到新機器**:
|
||||
```bash
|
||||
# 一鍵部署到 M5Max48
|
||||
cd ~/llm-deploy-doc/scripts
|
||||
./deploy-m5max48.sh user m5max48
|
||||
```
|
||||
|
||||
**詳細文檔**:
|
||||
- `README.md`:系統概述與快速開始
|
||||
- `INSTALL.md`:詳細安裝步驟
|
||||
- `USAGE.md`:使用手冊與故障排除
|
||||
- `README_M5Max48.md`:M5Max48 部署指南
|
||||
- `M5Max48_DEPLOY_CHECKLIST.md`:部署檢查清單
|
||||
|
||||
### Model 檔案位置
|
||||
|
||||
```
|
||||
/Users/accusys/models/
|
||||
├── gemma-4-12b-it-Q4_K_M.gguf (Chat/Summary LLM - 6.6GB)
|
||||
├── llava-v1.6-vicuna-13b.Q4_K_M.gguf (VLM model)
|
||||
├── mmproj-model-f16.gguf (VLM mmproj)
|
||||
└── embeddinggemma-300M-Q8_0.gguf (Embedding model)
|
||||
```
|
||||
|
||||
### 啟動命令
|
||||
|
||||
**統一 Chat/VLM Server (gemma-4-12b-it + mmproj)** - via launchd
|
||||
```bash
|
||||
# Service managed by launchd
|
||||
launchctl load ~/Library/LaunchAgents/com.momentry.chat-llamacpp.plist
|
||||
launchctl unload ~/Library/LaunchAgents/com.momentry.chat-llamacpp.plist
|
||||
|
||||
# Manual start (for testing)
|
||||
/Users/accusys/llama.cpp/build/bin/llama-server \
|
||||
-m /Users/accusys/models/gemma-4-12b-it-Q4_K_M.gguf \
|
||||
--mmproj /Users/accusys/models/mmproj-F16.gguf \
|
||||
--host 0.0.0.0 \
|
||||
--port 8080 \
|
||||
-ngl 99 \
|
||||
-c 8192 \
|
||||
--temp 0.1 \
|
||||
-b 4096 \
|
||||
-ub 4096
|
||||
|
||||
# API endpoint (supports both text and vision)
|
||||
curl http://localhost:8080/v1/chat/completions
|
||||
```
|
||||
|
||||
**備用 VLM Server (llava-v1.6-vicuna-13b)** - 已停用
|
||||
```bash
|
||||
# 舊配置(已禁用)
|
||||
# /Users/accusys/llama/bin/llama-server \
|
||||
# -m /Users/accusys/models/llava-v1.6-vicuna-13b.Q4_K_M.gguf \
|
||||
# --mmproj /Users/accusys/models/mmproj-model-f16.gguf \
|
||||
# --host 0.0.0.0 \
|
||||
# --port 8091 \
|
||||
# -ngl 99 \
|
||||
# -c 4096
|
||||
```
|
||||
|
||||
**Embedding (embeddinggemma-300m)**
|
||||
```bash
|
||||
python3 scripts/embeddinggemma_server.py --port 11436
|
||||
```
|
||||
|
||||
### VLM 用途
|
||||
|
||||
- **Face trace VLM**: 描述人物外貌(衣著、顏色、配件)
|
||||
- **Scene VLM**: 場景分析
|
||||
- **Agent `analyze_frame`**: 畫面分析工具
|
||||
|
||||
### Agent Search 語言
|
||||
|
||||
- **預設使用英文回答**(除非用戶明確要求其他語言)
|
||||
- System prompt 已明確規範 LLM 必須使用英文回應
|
||||
|
||||
### 環境變數
|
||||
|
||||
```bash
|
||||
# .env
|
||||
MOMENTRY_LLM_CHAT_URL=http://localhost:8080/v1/chat/completions
|
||||
MOMENTRY_LLM_CHAT_MODEL=gemma-4-12b-it
|
||||
MOMENTRY_LLM_VISION_URL=http://localhost:8080/v1/chat/completions
|
||||
MOMENTRY_LLM_VISION_MODEL=gemma-4-12b-it
|
||||
MOMENTRY_LLM_SUMMARY_URL=http://localhost:8080/v1/chat/completions
|
||||
MOMENTRY_LLM_SUMMARY_MODEL=gemma-4-12b-it
|
||||
```
|
||||
|
||||
## Testing
|
||||
|
||||
```bash
|
||||
@@ -272,6 +437,8 @@ cargo check --all-features
|
||||
- Use Rust 2021 edition
|
||||
- Use tracing for logging (not println!)
|
||||
- Keep lines under 100 characters
|
||||
- **Always provide absolute paths when referencing files** — use full paths like `/Users/accusys/momentry_core/src/main.rs` instead of relative paths like `src/main.rs`
|
||||
- **All document references MUST include full paths** — when listing files to modify, API endpoints, or cross-references in docs, always use absolute paths (e.g., `/Users/accusys/momentry_core/docs_v1.0/API_WORKSPACE/modules/19_people_api.md`)
|
||||
|
||||
### Imports (order: std → external → local)
|
||||
```rust
|
||||
@@ -368,6 +535,186 @@ src/
|
||||
└── watcher/ # File system watcher
|
||||
```
|
||||
|
||||
## Tools Architecture
|
||||
|
||||
### Directory Structure
|
||||
|
||||
```
|
||||
tools/
|
||||
├── cli/ # Compiled CLI binaries
|
||||
│ ├── rust/ # Rust CLI tools
|
||||
│ │ ├── src/
|
||||
│ │ │ └── bin/ # Binary source files
|
||||
│ │ │ ├── rust_appearance.rs
|
||||
│ │ │ ├── rust_face_cluster.rs
|
||||
│ │ │ ├── rust_pose.rs
|
||||
│ │ │ └── rust_vad.rs
|
||||
│ │ ├── Cargo.toml
|
||||
│ │ └── target/ # Build output
|
||||
│ │ └── release/ # Release binaries
|
||||
│ └── swift/ # Swift CLI tools
|
||||
│ ├── Sources/
|
||||
│ ├── Package.swift
|
||||
│ └── .build/ # Build output
|
||||
│ └── release/
|
||||
└── script/ # Python scripts (organized by processor)
|
||||
├── asr/ # ASR scripts
|
||||
├── chunk/ # Chunking scripts
|
||||
├── cut/ # Cut detection scripts
|
||||
├── embedding/ # Embedding scripts
|
||||
├── face/ # Face processing scripts
|
||||
├── identity/ # Identity management scripts
|
||||
├── ocr/ # OCR scripts
|
||||
├── pose/ # Pose estimation scripts
|
||||
├── scene/ # Scene detection scripts
|
||||
├── utils/ # Utility scripts
|
||||
├── vlm/ # Vision Language Model scripts
|
||||
├── worker/ # Worker scripts
|
||||
└── yolo/ # YOLO detection scripts
|
||||
```
|
||||
|
||||
### Tool Categories
|
||||
|
||||
#### Rust CLI Tools (tools/cli/rust/)
|
||||
|
||||
| Binary | Purpose | Status |
|
||||
|--------|---------|--------|
|
||||
| `rust_appearance` | Face appearance analysis | ✅ Working |
|
||||
| `rust_face_cluster` | Face clustering | ✅ Working |
|
||||
| `rust_pose` | Pose interpolation | ✅ Working |
|
||||
| `rust_vad` | Voice Activity Detection | ✅ Working |
|
||||
|
||||
**Build**:
|
||||
```bash
|
||||
cd tools/cli/rust
|
||||
cargo build --release
|
||||
```
|
||||
|
||||
**Usage**:
|
||||
```bash
|
||||
# Worker automatically finds binaries in tools/cli/rust/target/release/
|
||||
# Set MOMENTRY_USE_RUST_PROCESSORS=true to enable
|
||||
```
|
||||
|
||||
#### Swift CLI Tools (tools/cli/swift/)
|
||||
|
||||
| Binary | Purpose | Status |
|
||||
|--------|---------|--------|
|
||||
| `swift_pose` | Apple Vision Pose | ✅ Working |
|
||||
| `swift_face` | Apple Vision Face | ✅ Working |
|
||||
| `swift_scene` | Scene detection | ✅ Working |
|
||||
| `swift_yolo` | YOLO detection | ✅ Working |
|
||||
|
||||
**Build**:
|
||||
```bash
|
||||
cd tools/cli/swift
|
||||
swift build -c release
|
||||
```
|
||||
|
||||
#### Python Scripts (tools/script/)
|
||||
|
||||
Organized by processor type. Each directory contains related scripts.
|
||||
|
||||
| Directory | Purpose |
|
||||
|-----------|---------|
|
||||
| `asr/` | ASR (Automatic Speech Recognition) |
|
||||
| `chunk/` | Sentence chunking |
|
||||
| `cut/` | Cut detection |
|
||||
| `embedding/` | Vector embedding generation |
|
||||
| `face/` | Face detection, tracking, clustering |
|
||||
| `identity/` | Identity management |
|
||||
| `ocr/` | Optical Character Recognition |
|
||||
| `pose/` | Pose estimation (MediaPipe, YOLOv8) |
|
||||
| `scene/` | Scene detection |
|
||||
| `utils/` | Shared utilities |
|
||||
| `vlm/` | Vision Language Model (VLM) |
|
||||
| `worker/` | Worker-specific scripts |
|
||||
| `yolo/` | YOLO object detection |
|
||||
|
||||
### Environment Variables
|
||||
|
||||
- `MOMENTRY_SCRIPTS_DIR` - Scripts directory (default: `tools/script/`)
|
||||
- `MOMENTRY_CLI_DIR` - CLI tools directory (default: `tools/cli/`)
|
||||
- `MOMENTRY_USE_RUST_PROCESSORS` - Enable Rust processors (default: `false`)
|
||||
|
||||
### Worker Integration
|
||||
|
||||
The Worker (`src/core/processor/executor.rs`) automatically locates tools:
|
||||
|
||||
1. **Python Scripts**: `tools/script/<processor>/`
|
||||
2. **Rust Binaries**: `tools/cli/rust/target/release/`
|
||||
3. **Swift Binaries**: `tools/cli/swift/.build/release/`
|
||||
|
||||
**Priority Order**:
|
||||
1. Python scripts (default)
|
||||
2. Rust binaries (if `MOMENTRY_USE_RUST_PROCESSORS=true`)
|
||||
3. Swift binaries (for Apple Vision processors)
|
||||
|
||||
### Legacy Locations (To Be Removed)
|
||||
|
||||
⚠️ The following locations are deprecated and will be removed:
|
||||
|
||||
- `scripts/rust_processors/` → Migrate to `tools/cli/rust/`
|
||||
- `scripts/swift_processors/` → Migrate to `tools/cli/swift/`
|
||||
- `scripts/*.py` (scattered) → Migrate to `tools/script/<processor>/`
|
||||
|
||||
### Migration Status
|
||||
|
||||
| Component | Current Location | Target Location | Status |
|
||||
|-----------|-----------------|-----------------|--------|
|
||||
| Rust CLI | `tools/cli/rust/` | `tools/cli/rust/` | ✅ Done |
|
||||
| Swift CLI | `tools/cli/swift/` | `tools/cli/swift/` | ✅ Done |
|
||||
| Python Scripts | `tools/script/` | `tools/script/` | ✅ Done |
|
||||
| Legacy Rust | `scripts/rust_processors/` | Remove | ⚠️ Pending |
|
||||
| Legacy Swift | `scripts/swift_processors/` | Remove | ⚠️ Pending |
|
||||
|
||||
## Processor Configuration (V3)
|
||||
|
||||
### 配置驅動的 Processor 選擇
|
||||
|
||||
Momentry Core 使用 **配置驅動的 processor 選擇系統**,支持動態選擇和優先級排序。
|
||||
|
||||
**主配置**: `config/processor_tools_v3.json`
|
||||
|
||||
### Processor 優先級政策
|
||||
|
||||
**Swift (Apple Vision + ANE) First, Rust Second, Python Backup**
|
||||
|
||||
| Priority | Tool | 用途 | 理由 |
|
||||
|----------|------|------|------|
|
||||
| 0 | Swift CLI | 標準實現 | Apple Vision + ANE 加速 |
|
||||
| 0-1 | Rust CLI | 標準實現 | 性能優秀 |
|
||||
| 2+ | Python | 備用 | 靈活性高 |
|
||||
|
||||
### 當前配置狀態
|
||||
|
||||
**Swift First (Priority 0)**: 4 個 (POSE, FACE, ASRX, OCR)
|
||||
|
||||
**Rust First (Priority 0)**: 3 個 (FACE_TRACE, CUT, SCENE_VLM)
|
||||
|
||||
**Python Only**: 2 個 (ASR, TKG)
|
||||
|
||||
### 性能基準
|
||||
|
||||
| Processor | Python | Rust | Swift | 最佳 |
|
||||
|-----------|--------|------|-------|------|
|
||||
| FACE_TRACE | ~2s | **0.1s** | - | Rust (20x) |
|
||||
| CUT | ~3s | **1s** | 6s | Rust (3x) |
|
||||
| POSE | ~5s | - | **3s** | Swift (ANE) |
|
||||
| FACE | ~8s | - | **4s** | Swift (ANE) |
|
||||
|
||||
### ⚠️ 已廢棄配置
|
||||
|
||||
- ❌ `MOMENTRY_USE_RUST_PROCESSORS` (已由 V3 配置取代)
|
||||
- ❌ `config/processor_tools.json` (V1, 已廢棄)
|
||||
|
||||
### 相關文檔
|
||||
|
||||
- `docs_v1.0/OPERATIONS/Processor_Priority_Policy.md` - 優先級政策
|
||||
- `docs_v1.0/OPERATIONS/Processor_Commands_Reference.md` - 命令參考
|
||||
- `docs_v1.0/M4_workspace/2026-09-28_processor_test_report.md` - 測試報告
|
||||
|
||||
|
||||
## Key Dependencies
|
||||
|
||||
- **Error handling**: `anyhow`, `thiserror`
|
||||
@@ -404,8 +751,43 @@ cargo run --features player --bin momentry_player -- -o
|
||||
### Paths
|
||||
- `MOMENTRY_OUTPUT_DIR` - Output directory (default: `/Users/accusys/momentry/output`)
|
||||
- `MOMENTRY_BACKUP_DIR` - Backup directory
|
||||
- `MOMENTRY_SCRIPTS_DIR` - Scripts directory (default: `tools/script/`)
|
||||
- `MOMENTRY_CLI_DIR` - CLI tools directory (default: `tools/cli/`)
|
||||
- `MOMENTRY_PYTHON_PATH` - Python path (default: `/opt/homebrew/bin/python3.11`)
|
||||
- `MOMENTRY_SCRIPTS_DIR` - Scripts directory
|
||||
|
||||
### Critical Variables for Startup Scripts
|
||||
|
||||
**IMPORTANT**: Startup scripts must explicitly `export` these variables for Python subprocess inheritance.
|
||||
|
||||
#### Production (3002)
|
||||
Required exports in `run-server-3002.sh` and `run-worker-3002.sh`:
|
||||
```bash
|
||||
export MOMENTRY_OUTPUT_DIR=/Users/accusys/momentry/output
|
||||
export DATABASE_SCHEMA=public
|
||||
export MOMENTRY_REDIS_PREFIX=momentry:
|
||||
export MOMENTRY_SERVER_PORT=3002
|
||||
```
|
||||
|
||||
#### Playground (3003)
|
||||
Required exports in `run-server-3003.sh`:
|
||||
```bash
|
||||
export DATABASE_SCHEMA=dev
|
||||
export MOMENTRY_SERVER_PORT=3003
|
||||
export MOMENTRY_REDIS_PREFIX=momentry_dev:
|
||||
export MOMENTRY_OUTPUT_DIR=/Users/accusys/momentry/output_dev
|
||||
```
|
||||
|
||||
#### Why This Matters
|
||||
- Rust process loads `.env` via `dotenv`
|
||||
- Python subprocess inherits environment from Rust process
|
||||
- Without explicit `export`, dotenv variables are only available inside Rust
|
||||
- Python scripts like `store_traced_faces.py` will use hardcoded defaults if not exported
|
||||
|
||||
#### Config Directory
|
||||
Environment-specific configuration files:
|
||||
- `config/production.env` - Production-specific variables
|
||||
- `config/development.env` - Development-specific variables
|
||||
- `config/test.env` - Test environment (if needed)
|
||||
|
||||
### Processor Timeouts
|
||||
- `MOMENTRY_ASR_TIMEOUT` - ASR timeout in seconds (default: 3600)
|
||||
@@ -625,6 +1007,16 @@ git push origin main
|
||||
pg_dump -U accusys -d momentry --schema-only > "$RELEASE_DIR/schema_v0.X.X.sql"
|
||||
```
|
||||
|
||||
5. **驗證環境變數配置**
|
||||
- ✅ Startup scripts export all required environment variables
|
||||
- ✅ Python scripts don't use hardcoded paths
|
||||
- ✅ Environment variables consistent across:
|
||||
- `.env` / `.env.development`
|
||||
- Startup script `export`
|
||||
- Python script `os.environ.get()`
|
||||
- ✅ Config directory has environment-specific files
|
||||
- ✅ AGENTS.md documents all required exports
|
||||
|
||||
### 重要性
|
||||
- 避免 release binary 與 current source code 不一致
|
||||
- 方便追蹤特定 release 的程式碼狀態
|
||||
@@ -800,17 +1192,20 @@ Before creating any file in `docs_v1.0/` (API_WORKSPACE, GUIDES, REFERENCE, DESI
|
||||
| 8 | `file_uuid` not bare `uuid` | All file references use `file_uuid` (see UUID Naming Rule above) |
|
||||
| 9 | `identity_uuid` not bare `uuid` | All identity references use `identity_uuid` |
|
||||
|
||||
### P1 — Suggested (3 items)
|
||||
### P1 — Suggested (4 items)
|
||||
|
||||
| # | Check | Note |
|
||||
|---|-------|------|
|
||||
| 1 | Cross-references | Link to related docs in API_WORKSPACE/, GUIDES/, REFERENCE/, DESIGN/, OPERATIONS/ |
|
||||
| 2 | Glossary terms | Define non-obvious terms inline or link glossary |
|
||||
| 3 | Diagrams | Include Mermaid/ASCII diagram for complex topics |
|
||||
| 4 | Absolute paths | All file paths must be absolute, e.g. `/Users/accusys/momentry_core/src/...` |
|
||||
|
||||
### Exception
|
||||
|
||||
`M4_workspace/` files are exempt from this checklist (free-format reply documents).
|
||||
`M4_workspace/` files are exempt from P0 mandatory checklist items (YAML frontmatter, version history, etc.) as they are free-format reply documents.
|
||||
|
||||
**However**, `M4_workspace/` files **MUST still use absolute paths** for all file references.
|
||||
|
||||
---
|
||||
|
||||
@@ -819,3 +1214,42 @@ Before creating any file in `docs_v1.0/` (API_WORKSPACE, GUIDES, REFERENCE, DESI
|
||||
完整交付程序(M4_workspace → M5 → Release → Deploy → Public)見:
|
||||
|
||||
`docs_v1.0/OPERATIONS/DELIVERY_PROCEDURE.md`
|
||||
|
||||
## Session Summary (2026-07-01: Search Mode Fixes)
|
||||
|
||||
### Goal
|
||||
Fix search modes: Keyword BM25 ranking + People search migration to Qdrant + Qdrant scroll pagination
|
||||
|
||||
### Done
|
||||
- **Keyword/BM25 search (`search_bm25`)**: Replaced hardcoded 1.0 score with PostgreSQL FTS (`ts_rank` + `plainto_tsquery`). Now ranks results by relevance instead of flat 1.0.
|
||||
- **Smart search merge**: Passes real FTS score through instead of fixed 0.5, so keyword-only results are properly differentiated.
|
||||
- **Qdrant scroll_points**: Added `offset` parameter for pagination support; new `scroll_all_points()` method handles multi-page scroll automatically.
|
||||
- **get_identity_traces**: Fixed broken pagination loop (always fetched same first 1000 points) by switching to `scroll_all_points`.
|
||||
- **People search (`search_persons_internal`)**: Replaced `face_detections` JOIN in universal search with Qdrant `_faces` scroll + Rust aggregation (count per identity per file, frame→second via FPS).
|
||||
- **People search (`search_persons_by_query`)**: Same migration for the REST API person search endpoint.
|
||||
- **Payload field fix**: `_faces` uses `frame` (integer) not `timestamp_secs` (float). Fixed both `search_persons_internal` and `search_persons_by_query` to read `frame` and convert via `frame / fps`.
|
||||
|
||||
### Key Files Changed
|
||||
- `src/core/db/qdrant_db.rs`: `scroll_points` → offset pagination, new `scroll_all_points`
|
||||
- `src/api/identity_binding.rs`: Use `scroll_all_points` instead of broken loop
|
||||
- `src/api/universal_search.rs`: Rewrote `search_persons_internal` and `search_persons_by_query` to use Qdrant
|
||||
- `src/core/db/postgres_db.rs`: `search_bm25` → PostgreSQL FTS ranking
|
||||
- `src/api/search.rs`: Pass real FTS scores in merge, removed unused `KEYWORD_FIXED_SCORE`
|
||||
|
||||
### Done This Session
|
||||
- **Qdrant scroll pagination**: `scroll_points` now accepts `offset` param + returns `next_page_offset`; new `scroll_all_points()` handles multi-page scroll automatically
|
||||
- **get_identity_traces pagination fix**: No longer fetches same 1000 points in infinite loop
|
||||
- **Keyword BM25**: `search_bm25` replaced hardcoded 1.0 score with PostgreSQL `ts_rank` + `plainto_tsquery`; `smart_search` passes real FTS scores instead of fixed 0.5
|
||||
- **People search → Qdrant**: Both `search_persons_internal` and `search_persons_by_query` replaced `face_detections` JOIN with Qdrant `_faces` scroll + Rust aggregation (count/group/sort). Fixed `timestamp_secs` → `frame` + `frame/fps` conversion
|
||||
- **list_face_candidates → Qdrant**: `identities.rs` unbound faces query now scrolls `_faces` with `is_null: identity_id` filter, sorts by confidence DESC in Rust
|
||||
- **list_unassigned_traces → Qdrant**: `identities.rs` unbound traces query now scrolls `_faces` with `is_null: identity_id` + `trace_id > 0` filter, groups by (file_uuid, trace_id) in Rust, picks best face per trace
|
||||
- **get_identity_chunks → identity_bindings**: Replaced `face_detections` frame-range JOIN with `identity_bindings` + `chunk.metadata->>'trace_id'`
|
||||
- **postgres_db.rs 5 remaining READs → Qdrant**: `get_trace_count_by_file`, `get_trace_frame_count_distribution`, `get_identity_files`, `get_identity_faces`, `get_file_faces` all migrated to `_faces` scroll + Rust aggregation
|
||||
- **agent/tools.rs fully migrated**: `exec_find_file`, `exec_list_files`, `exec_tkg_query` (8 sub-queries), `exec_identity_text`, `exec_identities_search` — all face_detections JOINs replaced with Qdrant scroll or identity_bindings
|
||||
- **job_worker.rs + storage.rs**: Remaining face_detections READs migrated to Qdrant scroll
|
||||
|
||||
### Remaining face_detections references (all inactive/safe)
|
||||
- Schema definition (CREATE TABLE/INDEX in `postgres_db.rs`)
|
||||
- `store_face_detections_batch` — already skipped (Phase 1)
|
||||
- `workspace_sqlite.rs` — local processing DB, separate from PG
|
||||
- `bin/release.rs` — standalone release utility
|
||||
|
||||
Generated
+42
-1
@@ -636,6 +636,8 @@ dependencies = [
|
||||
"compression-core",
|
||||
"flate2",
|
||||
"memchr",
|
||||
"zstd",
|
||||
"zstd-safe",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -1016,6 +1018,27 @@ dependencies = [
|
||||
"subtle",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "dirs"
|
||||
version = "5.0.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "44c45a9d03d6676652bcb5e724c7e988de1acad23a711b5217ab9cbecbec2225"
|
||||
dependencies = [
|
||||
"dirs-sys",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "dirs-sys"
|
||||
version = "0.4.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "520f05a5cbd335fae5a99ff7a6ab8627577660ee5cfd6a94a6a929b52ff0321c"
|
||||
dependencies = [
|
||||
"libc",
|
||||
"option-ext",
|
||||
"redox_users",
|
||||
"windows-sys 0.48.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "displaydoc"
|
||||
version = "0.2.5"
|
||||
@@ -2420,7 +2443,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "momentry_core"
|
||||
version = "1.0.0"
|
||||
version = "1.3.2"
|
||||
dependencies = [
|
||||
"aes-gcm",
|
||||
"anyhow",
|
||||
@@ -2433,6 +2456,7 @@ dependencies = [
|
||||
"chrono",
|
||||
"clap",
|
||||
"crossterm",
|
||||
"dirs",
|
||||
"dotenv",
|
||||
"env_logger",
|
||||
"ferrous-opencc",
|
||||
@@ -2759,6 +2783,12 @@ dependencies = [
|
||||
"vcpkg",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "option-ext"
|
||||
version = "0.2.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "04744f49eae99ab78e0d5c0b603ab218f515ea8cfe5a456d7629ad883a3b6e7d"
|
||||
|
||||
[[package]]
|
||||
name = "parking"
|
||||
version = "2.2.1"
|
||||
@@ -3347,6 +3377,17 @@ dependencies = [
|
||||
"bitflags 2.11.1",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "redox_users"
|
||||
version = "0.4.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ba009ff324d1fc1b900bd1fdb31564febe58a8ccc8a6fdbb93b543d33b13ca43"
|
||||
dependencies = [
|
||||
"getrandom 0.2.17",
|
||||
"libredox",
|
||||
"thiserror 1.0.69",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "regex"
|
||||
version = "1.12.3"
|
||||
|
||||
+27
-2
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "momentry_core"
|
||||
version = "1.0.0"
|
||||
version = "1.3.2"
|
||||
edition = "2021"
|
||||
authors = ["Momentry Team"]
|
||||
description = "Digital asset management system with video analysis and RAG"
|
||||
@@ -11,6 +11,7 @@ anyhow = "1.0"
|
||||
thiserror = "1.0"
|
||||
tokio = { version = "1", features = ["full"] }
|
||||
tracing = "0.1"
|
||||
dirs = "5.0"
|
||||
tracing-subscriber = { version = "0.3", features = ["env-filter"] }
|
||||
once_cell = "1.19"
|
||||
libc = "0.2"
|
||||
@@ -55,7 +56,7 @@ sqlx = { version = "0.8", features = ["runtime-tokio", "postgres", "sqlite", "js
|
||||
mongodb = { version = "2", features = ["tokio-runtime"] }
|
||||
bson = { version = "2", features = ["chrono-0_4"] }
|
||||
qdrant-client = "1.7"
|
||||
reqwest = { version = "0.12", features = ["json", "gzip"] }
|
||||
reqwest = { version = "0.12", features = ["json", "gzip", "zstd"] }
|
||||
pgvector = { version = "0.3", features = ["sqlx"] }
|
||||
|
||||
# HTTP Server
|
||||
@@ -130,6 +131,10 @@ path = "src/bin/test_bm25_simple.rs"
|
||||
name = "integrated_player"
|
||||
path = "src/bin/integrated_player.rs"
|
||||
|
||||
[[bin]]
|
||||
name = "pipeline_worker"
|
||||
path = "src/bin/pipeline_worker.rs"
|
||||
|
||||
[[bin]]
|
||||
name = "release"
|
||||
path = "src/bin/release.rs"
|
||||
@@ -151,3 +156,23 @@ chrono = "0.4"
|
||||
|
||||
[dev-dependencies]
|
||||
tempfile = "3"
|
||||
|
||||
[[bin]]
|
||||
name = "backfill_trace_profiles"
|
||||
path = "src/bin/backfill_trace_profiles.rs"
|
||||
|
||||
[[bin]]
|
||||
name = "rebuild_trace_thumbs"
|
||||
path = "src/bin/rebuild_trace_thumbs.rs"
|
||||
|
||||
[[bin]]
|
||||
name = "backfill_trace_vlm"
|
||||
path = "src/bin/backfill_trace_vlm.rs"
|
||||
|
||||
[[bin]]
|
||||
name = "rust_unregister"
|
||||
path = "src/bin/rust_unregister.rs"
|
||||
|
||||
[[bin]]
|
||||
name = "rust_register"
|
||||
path = "src/bin/rust_register.rs"
|
||||
|
||||
@@ -0,0 +1,3 @@
|
||||
|
||||
Scene Number,Start Frame,Start Timecode,Start Time (seconds),End Frame,End Timecode,End Time (seconds),Length (frames),Length (timecode),Length (seconds)
|
||||
1,1,00:00:00.000,0.000,2800,00:01:33.333,93.333,2800,00:01:33.333,93.333
|
||||
|
@@ -0,0 +1,39 @@
|
||||
Momentry Core
|
||||
Copyright (c) 2026 Momentry Team
|
||||
|
||||
---
|
||||
|
||||
LEGAL DISCLAIMER
|
||||
|
||||
This product includes software developed independently by the Momentry Team.
|
||||
|
||||
The MarkBase Queue Protocol (MQP) is an independently implemented queue protocol standard.
|
||||
|
||||
IMPORTANT:
|
||||
- This product does NOT use Apache Kafka source code
|
||||
- This product is NOT compatible with Apache Kafka protocol or API
|
||||
- This product is NOT compatible with Apache Kafka client libraries
|
||||
- This product does NOT distribute Apache Kafka software
|
||||
|
||||
The MarkBase Queue Protocol design was inspired by Apache Kafka's architecture,
|
||||
including concepts such as append-only logs, offset tracking, and consumer groups.
|
||||
However, this is an independent implementation with a different protocol (HTTP/REST + JSON)
|
||||
and is not compatible with Apache Kafka.
|
||||
|
||||
For more information about Apache Kafka, please visit:
|
||||
https://kafka.apache.org/
|
||||
|
||||
Apache Kafka is a registered trademark of the Apache Software Foundation.
|
||||
MarkBase is a product series name of the Momentry Team.
|
||||
There is NO affiliation or partnership between these entities.
|
||||
|
||||
---
|
||||
|
||||
This product uses the following open source software:
|
||||
|
||||
- Rust (MIT/Apache-2.0): https://www.rust-lang.org/
|
||||
- PostgreSQL (PostgreSQL License): https://www.postgresql.org/
|
||||
- Redis (BSD-3-Clause): https://redis.io/
|
||||
- Qdrant (Apache-2.0): https://qdrant.tech/
|
||||
|
||||
For a complete list of dependencies and their licenses, see the Cargo.toml file.
|
||||
@@ -1,3 +1,35 @@
|
||||
# momentry_core
|
||||
|
||||
Digital asset management system with video analysis and RAG - Production version with API Key authentication
|
||||
Digital asset management system with video analysis and RAG - Production version with API Key authentication
|
||||
|
||||
---
|
||||
|
||||
## ⚠️ 重要法律声明
|
||||
|
||||
**MarkBase Queue Protocol** 是**完全独立实现**的队列协议标准。
|
||||
|
||||
- ❌ **不兼容** Apache Kafka 协议或 API
|
||||
- ❌ **未使用** Apache Kafka 源代码
|
||||
- ✅ **独立实现**,借鉴公开技术概念
|
||||
- ✅ **独立协议**,HTTP/REST + JSON
|
||||
|
||||
详细声明见: `docs_v1.0/LEGAL/MARKBASE_QUEUE_DISCLAIMER.md`
|
||||
|
||||
---
|
||||
|
||||
## 致谢
|
||||
|
||||
本项目的 VLM 队列系统设计借鉴了 Apache Kafka 的优秀设计理念,包括:
|
||||
- 追加写入日志(Append-Only Log)
|
||||
- Offset 追踪机制
|
||||
- 分区和消费者组概念
|
||||
|
||||
感谢 Apache Kafka 社区的开源贡献。
|
||||
|
||||
**声明**: Momentry Core 是完全独立实现的系统,未使用 Apache Kafka 的任何代码。
|
||||
|
||||
---
|
||||
|
||||
## 许可证
|
||||
|
||||
本项目采用专有许可证。未经授权不得使用、修改或分发。
|
||||
@@ -0,0 +1,8 @@
|
||||
# Momentry Release Manifest
|
||||
# Generated: 2026-10-04 20:43:05
|
||||
|
||||
| Binary | Size (bytes) | MD5 | SHA256 |
|
||||
|--------|--------------|-----|--------|
|
||||
| momentry | 46128592 | `3ebe21defc97d5ebd015ce8b4befdc4c` | `9e5a4b19b11343e7aae53d14e560642b70df0d07b8dba95c02ef4dde50015fbe` |
|
||||
| rust_register | 4080512 | `af4e8e08cb500e86add073ffdc3d7ebb` | `a0c9d59337bc17bb82ba404bfc0f065963e27b338d8c2fa212e0700c280356ac` |
|
||||
| rust_unregister | 9425872 | `3880e14f25701d1c08a43707b53e4899` | `3a97402961359f08bdb3627d79badfa7605c1fc3dc34d3624be531974a078af4` |
|
||||
@@ -0,0 +1,74 @@
|
||||
Timecode List:,00:00:05.239,00:00:08.075,00:00:21.822,00:00:32.032,00:00:33.400,00:00:35.002,00:00:37.070,00:00:42.209,00:00:44.411,00:00:48.382,00:00:51.318,00:01:03.497,00:01:16.109,00:01:17.911,00:01:20.314,00:01:38.165,00:01:42.536,00:01:45.672,00:01:48.442,00:02:01.655,00:02:10.631,00:02:18.805,00:02:19.506,00:02:21.742,00:02:23.110,00:02:25.045,00:02:39.660,00:02:40.327,00:02:43.330,00:02:50.037,00:02:52.406,00:02:59.446,00:03:10.123,00:03:13.193,00:03:20.534,00:03:33.547,00:03:38.151,00:03:48.161,00:03:49.563,00:03:51.898,00:04:02.042,00:04:10.951,00:04:18.191,00:04:29.069,00:04:30.203,00:04:46.319,00:04:49.623,00:04:53.160,00:04:56.630,00:05:02.702,00:05:17.284,00:05:51.284,00:05:57.424,00:05:59.092,00:06:02.696,00:06:04.831,00:06:07.767,00:06:11.538,00:06:13.273,00:06:36.129,00:06:39.032,00:06:40.800,00:06:44.337,00:06:46.906,00:06:56.283,00:07:01.288,00:07:12.432,00:07:14.301,00:07:15.835,00:07:23.109,00:07:30.684
|
||||
Scene Number,Start Frame,Start Timecode,Start Time (seconds),End Frame,End Timecode,End Time (seconds),Length (frames),Length (timecode),Length (seconds)
|
||||
1,1,00:00:00.000,0.000,157,00:00:05.239,5.239,157,00:00:05.239,5.239
|
||||
2,158,00:00:05.239,5.239,242,00:00:08.075,8.075,85,00:00:02.836,2.836
|
||||
3,243,00:00:08.075,8.075,654,00:00:21.822,21.822,412,00:00:13.747,13.747
|
||||
4,655,00:00:21.822,21.822,960,00:00:32.032,32.032,306,00:00:10.210,10.210
|
||||
5,961,00:00:32.032,32.032,1001,00:00:33.400,33.400,41,00:00:01.368,1.368
|
||||
6,1002,00:00:33.400,33.400,1049,00:00:35.002,35.002,48,00:00:01.602,1.602
|
||||
7,1050,00:00:35.002,35.002,1111,00:00:37.070,37.070,62,00:00:02.069,2.069
|
||||
8,1112,00:00:37.070,37.070,1265,00:00:42.209,42.209,154,00:00:05.138,5.138
|
||||
9,1266,00:00:42.209,42.209,1331,00:00:44.411,44.411,66,00:00:02.202,2.202
|
||||
10,1332,00:00:44.411,44.411,1450,00:00:48.382,48.382,119,00:00:03.971,3.971
|
||||
11,1451,00:00:48.382,48.382,1538,00:00:51.318,51.318,88,00:00:02.936,2.936
|
||||
12,1539,00:00:51.318,51.318,1903,00:01:03.497,63.497,365,00:00:12.179,12.179
|
||||
13,1904,00:01:03.497,63.497,2281,00:01:16.109,76.109,378,00:00:12.613,12.613
|
||||
14,2282,00:01:16.109,76.109,2335,00:01:17.911,77.911,54,00:00:01.802,1.802
|
||||
15,2336,00:01:17.911,77.911,2407,00:01:20.314,80.314,72,00:00:02.402,2.402
|
||||
16,2408,00:01:20.314,80.314,2942,00:01:38.165,98.165,535,00:00:17.851,17.851
|
||||
17,2943,00:01:38.165,98.165,3073,00:01:42.536,102.536,131,00:00:04.371,4.371
|
||||
18,3074,00:01:42.536,102.536,3167,00:01:45.672,105.672,94,00:00:03.136,3.136
|
||||
19,3168,00:01:45.672,105.672,3250,00:01:48.442,108.442,83,00:00:02.769,2.769
|
||||
20,3251,00:01:48.442,108.442,3646,00:02:01.655,121.655,396,00:00:13.213,13.213
|
||||
21,3647,00:02:01.655,121.655,3915,00:02:10.631,130.631,269,00:00:08.976,8.976
|
||||
22,3916,00:02:10.631,130.631,4160,00:02:18.805,138.805,245,00:00:08.175,8.175
|
||||
23,4161,00:02:18.805,138.805,4181,00:02:19.506,139.506,21,00:00:00.701,0.701
|
||||
24,4182,00:02:19.506,139.506,4248,00:02:21.742,141.742,67,00:00:02.236,2.236
|
||||
25,4249,00:02:21.742,141.742,4289,00:02:23.110,143.110,41,00:00:01.368,1.368
|
||||
26,4290,00:02:23.110,143.110,4347,00:02:25.045,145.045,58,00:00:01.935,1.935
|
||||
27,4348,00:02:25.045,145.045,4785,00:02:39.660,159.660,438,00:00:14.615,14.615
|
||||
28,4786,00:02:39.660,159.660,4805,00:02:40.327,160.327,20,00:00:00.667,0.667
|
||||
29,4806,00:02:40.327,160.327,4895,00:02:43.330,163.330,90,00:00:03.003,3.003
|
||||
30,4896,00:02:43.330,163.330,5096,00:02:50.037,170.037,201,00:00:06.707,6.707
|
||||
31,5097,00:02:50.037,170.037,5167,00:02:52.406,172.406,71,00:00:02.369,2.369
|
||||
32,5168,00:02:52.406,172.406,5378,00:02:59.446,179.446,211,00:00:07.040,7.040
|
||||
33,5379,00:02:59.446,179.446,5698,00:03:10.123,190.123,320,00:00:10.677,10.677
|
||||
34,5699,00:03:10.123,190.123,5790,00:03:13.193,193.193,92,00:00:03.070,3.070
|
||||
35,5791,00:03:13.193,193.193,6010,00:03:20.534,200.534,220,00:00:07.341,7.341
|
||||
36,6011,00:03:20.534,200.534,6400,00:03:33.547,213.547,390,00:00:13.013,13.013
|
||||
37,6401,00:03:33.547,213.547,6538,00:03:38.151,218.151,138,00:00:04.605,4.605
|
||||
38,6539,00:03:38.151,218.151,6838,00:03:48.161,228.161,300,00:00:10.010,10.010
|
||||
39,6839,00:03:48.161,228.161,6880,00:03:49.563,229.563,42,00:00:01.401,1.401
|
||||
40,6881,00:03:49.563,229.563,6950,00:03:51.898,231.898,70,00:00:02.336,2.336
|
||||
41,6951,00:03:51.898,231.898,7254,00:04:02.042,242.042,304,00:00:10.143,10.143
|
||||
42,7255,00:04:02.042,242.042,7521,00:04:10.951,250.951,267,00:00:08.909,8.909
|
||||
43,7522,00:04:10.951,250.951,7738,00:04:18.191,258.191,217,00:00:07.241,7.241
|
||||
44,7739,00:04:18.191,258.191,8064,00:04:29.069,269.069,326,00:00:10.878,10.878
|
||||
45,8065,00:04:29.069,269.069,8098,00:04:30.203,270.203,34,00:00:01.134,1.134
|
||||
46,8099,00:04:30.203,270.203,8581,00:04:46.319,286.319,483,00:00:16.116,16.116
|
||||
47,8582,00:04:46.319,286.319,8680,00:04:49.623,289.623,99,00:00:03.303,3.303
|
||||
48,8681,00:04:49.623,289.623,8786,00:04:53.160,293.160,106,00:00:03.537,3.537
|
||||
49,8787,00:04:53.160,293.160,8890,00:04:56.630,296.630,104,00:00:03.470,3.470
|
||||
50,8891,00:04:56.630,296.630,9072,00:05:02.702,302.702,182,00:00:06.073,6.073
|
||||
51,9073,00:05:02.702,302.702,9509,00:05:17.284,317.284,437,00:00:14.581,14.581
|
||||
52,9510,00:05:17.284,317.284,10528,00:05:51.284,351.284,1019,00:00:34.001,34.001
|
||||
53,10529,00:05:51.284,351.284,10712,00:05:57.424,357.424,184,00:00:06.139,6.139
|
||||
54,10713,00:05:57.424,357.424,10762,00:05:59.092,359.092,50,00:00:01.668,1.668
|
||||
55,10763,00:05:59.092,359.092,10870,00:06:02.696,362.696,108,00:00:03.604,3.604
|
||||
56,10871,00:06:02.696,362.696,10934,00:06:04.831,364.831,64,00:00:02.135,2.135
|
||||
57,10935,00:06:04.831,364.831,11022,00:06:07.767,367.767,88,00:00:02.936,2.936
|
||||
58,11023,00:06:07.767,367.767,11135,00:06:11.538,371.538,113,00:00:03.770,3.770
|
||||
59,11136,00:06:11.538,371.538,11187,00:06:13.273,373.273,52,00:00:01.735,1.735
|
||||
60,11188,00:06:13.273,373.273,11872,00:06:36.129,396.129,685,00:00:22.856,22.856
|
||||
61,11873,00:06:36.129,396.129,11959,00:06:39.032,399.032,87,00:00:02.903,2.903
|
||||
62,11960,00:06:39.032,399.032,12012,00:06:40.800,400.800,53,00:00:01.768,1.768
|
||||
63,12013,00:06:40.800,400.800,12118,00:06:44.337,404.337,106,00:00:03.537,3.537
|
||||
64,12119,00:06:44.337,404.337,12195,00:06:46.906,406.906,77,00:00:02.569,2.569
|
||||
65,12196,00:06:46.906,406.906,12476,00:06:56.283,416.283,281,00:00:09.376,9.376
|
||||
66,12477,00:06:56.283,416.283,12626,00:07:01.288,421.288,150,00:00:05.005,5.005
|
||||
67,12627,00:07:01.288,421.288,12960,00:07:12.432,432.432,334,00:00:11.144,11.144
|
||||
68,12961,00:07:12.432,432.432,13016,00:07:14.301,434.301,56,00:00:01.869,1.869
|
||||
69,13017,00:07:14.301,434.301,13062,00:07:15.835,435.835,46,00:00:01.535,1.535
|
||||
70,13063,00:07:15.835,435.835,13280,00:07:23.109,443.109,218,00:00:07.274,7.274
|
||||
71,13281,00:07:23.109,443.109,13507,00:07:30.684,450.684,227,00:00:07.574,7.574
|
||||
72,13508,00:07:30.684,450.684,14246,00:07:55.342,475.342,739,00:00:24.658,24.658
|
||||
|
@@ -0,0 +1,26 @@
|
||||
use sqlx::postgres::PgPoolOptions;
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
let pool = PgPoolOptions::new()
|
||||
.max_connections(1)
|
||||
.connect("postgres://accusys@localhost:5432/momentry")
|
||||
.await?;
|
||||
|
||||
let row: Option<(i32, String, String, Option<String>)> = sqlx::query_as(
|
||||
"SELECT id, uuid, status, processors FROM monitor_jobs WHERE uuid = 'd8acb03870f0cc9b14e01f14a7bf24d6' ORDER BY id DESC LIMIT 1"
|
||||
)
|
||||
.fetch_optional(&pool)
|
||||
.await?;
|
||||
|
||||
if let Some((id, uuid, status, processors)) = row {
|
||||
println!("Job ID: {}", id);
|
||||
println!("UUID: {}", uuid);
|
||||
println!("Status: {}", status);
|
||||
println!("Processors: {:?}", processors);
|
||||
} else {
|
||||
println!("No job found for this UUID");
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
Executable
+13
@@ -0,0 +1,13 @@
|
||||
#!/bin/bash
|
||||
# Query PostgreSQL monitor_jobs status
|
||||
# Using Rust code to execute SQL
|
||||
|
||||
echo "Jobs in PostgreSQL:"
|
||||
cat << 'SQL' > query_jobs.sql
|
||||
SELECT uuid, status, processors, created_at::date
|
||||
FROM monitor_jobs
|
||||
ORDER BY created_at DESC
|
||||
LIMIT 10;
|
||||
SQL
|
||||
|
||||
echo "SQL query created. Need to execute via API or Rust..."
|
||||
@@ -0,0 +1,10 @@
|
||||
-- Delete failed face processor result to allow retry
|
||||
DELETE FROM processor_results
|
||||
WHERE job_id = 62
|
||||
AND processor = 'face'
|
||||
AND status = 'failed';
|
||||
|
||||
-- Check remaining processor_results for this job
|
||||
SELECT id, processor, status, retry_count
|
||||
FROM processor_results
|
||||
WHERE job_id = 62;
|
||||
@@ -0,0 +1,154 @@
|
||||
{
|
||||
"filter_config": {
|
||||
"face": {
|
||||
"min_confidence": 0.5,
|
||||
"min_size": 30
|
||||
}
|
||||
},
|
||||
"llm_config": {
|
||||
"chat": {
|
||||
"model": "gemma-4-12b-it",
|
||||
"timeout": 30,
|
||||
"url": "http://localhost:8080/v1/chat/completions"
|
||||
},
|
||||
"summary": {
|
||||
"model": "gemma-4-12b-it",
|
||||
"timeout": 60,
|
||||
"url": "http://localhost:8080/v1/chat/completions"
|
||||
}
|
||||
},
|
||||
"processor_config": {
|
||||
"ASRX": {
|
||||
"default_tool": "swift",
|
||||
"enabled": true,
|
||||
"timeout": 3600,
|
||||
"tools": [
|
||||
{
|
||||
"enabled": true,
|
||||
"name": "swift",
|
||||
"parameters": {},
|
||||
"priority": 0
|
||||
}
|
||||
]
|
||||
},
|
||||
"CUT": {
|
||||
"default_tool": "rust",
|
||||
"enabled": true,
|
||||
"timeout": 3600,
|
||||
"tools": [
|
||||
{
|
||||
"enabled": true,
|
||||
"name": "rust",
|
||||
"parameters": {},
|
||||
"priority": 0
|
||||
},
|
||||
{
|
||||
"enabled": true,
|
||||
"name": "python",
|
||||
"parameters": {},
|
||||
"priority": 2
|
||||
}
|
||||
]
|
||||
},
|
||||
"FACE": {
|
||||
"default_tool": "swift",
|
||||
"enabled": true,
|
||||
"timeout": 3600,
|
||||
"tools": [
|
||||
{
|
||||
"enabled": true,
|
||||
"name": "swift",
|
||||
"parameters": {},
|
||||
"priority": 0
|
||||
},
|
||||
{
|
||||
"enabled": true,
|
||||
"name": "python",
|
||||
"parameters": {},
|
||||
"priority": 2
|
||||
}
|
||||
]
|
||||
},
|
||||
"FACE_TRACE": {
|
||||
"default_tool": "rust",
|
||||
"enabled": true,
|
||||
"timeout": 3600,
|
||||
"tools": [
|
||||
{
|
||||
"enabled": true,
|
||||
"name": "rust",
|
||||
"parameters": {},
|
||||
"priority": 0
|
||||
},
|
||||
{
|
||||
"enabled": true,
|
||||
"name": "python",
|
||||
"parameters": {},
|
||||
"priority": 1
|
||||
}
|
||||
]
|
||||
},
|
||||
"OCR": {
|
||||
"default_tool": "swift",
|
||||
"enabled": true,
|
||||
"timeout": 3600,
|
||||
"tools": [
|
||||
{
|
||||
"enabled": true,
|
||||
"name": "swift",
|
||||
"parameters": {},
|
||||
"priority": 0
|
||||
}
|
||||
]
|
||||
},
|
||||
"POSE": {
|
||||
"default_tool": "swift",
|
||||
"enabled": true,
|
||||
"timeout": 3600,
|
||||
"tools": [
|
||||
{
|
||||
"enabled": true,
|
||||
"name": "swift",
|
||||
"parameters": {},
|
||||
"priority": 0
|
||||
},
|
||||
{
|
||||
"enabled": true,
|
||||
"name": "rust",
|
||||
"parameters": {},
|
||||
"priority": 1
|
||||
},
|
||||
{
|
||||
"enabled": true,
|
||||
"name": "mediapipe",
|
||||
"parameters": {
|
||||
"min_confidence": 0.5,
|
||||
"model_complexity": 2
|
||||
},
|
||||
"priority": 2
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
"search": {
|
||||
"vlm_max_results": 5,
|
||||
"vlm_min_score": 0,
|
||||
"vlm_output_language": "ja"
|
||||
},
|
||||
"system_config": {},
|
||||
"version": "1.0.0",
|
||||
"vlm_prompts": {
|
||||
"rust_vlm_summary": {
|
||||
"description": "Face trace VLM prompt for person description",
|
||||
"max_tokens": 300,
|
||||
"system_prompt": "You are a helpful assistant that describes people in images.",
|
||||
"user_prompt": "Describe the person in this image. Focus on clothing, accessories, and distinctive features."
|
||||
},
|
||||
"scene_vlm": {
|
||||
"description": "Scene analysis VLM prompt",
|
||||
"max_tokens": 200,
|
||||
"system_prompt": "You are a helpful assistant that analyzes video scenes.",
|
||||
"user_prompt": "Describe this scene. What is happening? What objects and people are visible?"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
{
|
||||
"filter_config": {},
|
||||
"llm_config": {},
|
||||
"processor_config": {},
|
||||
"search": {
|
||||
"vlm_max_results": 5,
|
||||
"vlm_min_score": 0,
|
||||
"vlm_output_language": "ja"
|
||||
},
|
||||
"system_config": {},
|
||||
"version": "1.0.0",
|
||||
"vlm_prompts": {
|
||||
"test": "prompt"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
# Development Environment Configuration
|
||||
# Used by: momentry_playground binary on port 3003
|
||||
#
|
||||
# This file extracts development-specific variables from .env.development
|
||||
# Startup scripts must export these variables for Python subprocess inheritance
|
||||
|
||||
# Server Configuration
|
||||
MOMENTRY_SERVER_PORT=3003
|
||||
MOMENTRY_REDIS_PREFIX=momentry_dev:
|
||||
|
||||
# Database Schema
|
||||
DATABASE_SCHEMA=dev
|
||||
|
||||
# Output Directory (CRITICAL for Python scripts)
|
||||
MOMENTRY_OUTPUT_DIR=/Users/accusys/momentry/output_dev
|
||||
|
||||
# Backup Directory
|
||||
MOMENTRY_BACKUP_DIR=/Users/accusys/momentry/backup/momentry_dev
|
||||
|
||||
# Storage
|
||||
MOMENTRY_SFTP_ROOT=/Users/accusys/momentry/var/sftpgo/data/demo/
|
||||
|
||||
# Python Path (venv for development)
|
||||
MOMENTRY_PYTHON_PATH=/Users/accusys/momentry_core/venv/bin/python
|
||||
MOMENTRY_SCRIPTS_DIR=/Users/accusys/momentry_core/scripts
|
||||
|
||||
# Logging
|
||||
RUST_LOG=info
|
||||
MOMENTRY_LOG_LEVEL=info
|
||||
|
||||
# Worker Configuration
|
||||
MOMENTRY_WORKER_ENABLED=true
|
||||
MOMENTRY_MAX_CONCURRENT=6
|
||||
MOMENTRY_POLL_INTERVAL=10
|
||||
MOMENTRY_WORKER_BATCH_SIZE=5
|
||||
|
||||
# TMDb Integration
|
||||
TMDB_API_KEY=e9cde52197f6f8df4d9db99da93db1fb
|
||||
MOMENTRY_TMDB_PROBE_ENABLED=true
|
||||
|
||||
# LLM Configuration
|
||||
MOMENTRY_LLM_SUMMARY_URL=http://127.0.0.1:8000/v1/chat/completions
|
||||
MOMENTRY_LLM_SUMMARY_MODEL=gemma-4-E4B
|
||||
MOMENTRY_LLM_SUMMARY_ENABLED=true
|
||||
|
||||
# Embedding
|
||||
MOMENTRY_EMBED_URL=http://localhost:11436
|
||||
@@ -0,0 +1,230 @@
|
||||
{
|
||||
"processor_config": {
|
||||
"pose": {
|
||||
"tools": [
|
||||
{
|
||||
"name": "mediapipe",
|
||||
"priority": 0,
|
||||
"enabled": true,
|
||||
"parameters": {
|
||||
"model_complexity": 2,
|
||||
"min_confidence": 0.5
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "rust",
|
||||
"priority": 1,
|
||||
"enabled": true,
|
||||
"parameters": {}
|
||||
},
|
||||
{
|
||||
"name": "swift",
|
||||
"priority": 2,
|
||||
"enabled": true,
|
||||
"parameters": {}
|
||||
},
|
||||
{
|
||||
"name": "yolov8",
|
||||
"priority": 3,
|
||||
"enabled": false,
|
||||
"parameters": {
|
||||
"model": "yolov8n-pose.pt"
|
||||
}
|
||||
}
|
||||
],
|
||||
"default_tool": "mediapipe",
|
||||
"timeout": 3600,
|
||||
"enabled": true
|
||||
},
|
||||
"face": {
|
||||
"tools": [
|
||||
{
|
||||
"name": "swift",
|
||||
"priority": 0,
|
||||
"enabled": true,
|
||||
"parameters": {}
|
||||
},
|
||||
{
|
||||
"name": "python",
|
||||
"priority": 1,
|
||||
"enabled": true,
|
||||
"parameters": {}
|
||||
}
|
||||
],
|
||||
"default_tool": "swift",
|
||||
"enabled": true
|
||||
},
|
||||
"asr": {
|
||||
"tools": [
|
||||
{
|
||||
"name": "whisper",
|
||||
"priority": 0,
|
||||
"enabled": true,
|
||||
"parameters": {
|
||||
"model": "large-v3",
|
||||
"model_dir": "/Users/accusys/models/whisper-small-mlx"
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "rust",
|
||||
"priority": 1,
|
||||
"enabled": false,
|
||||
"parameters": {}
|
||||
}
|
||||
],
|
||||
"default_tool": "whisper",
|
||||
"enabled": true
|
||||
},
|
||||
"asrx": {
|
||||
"tools": [
|
||||
{
|
||||
"name": "swift",
|
||||
"priority": 0,
|
||||
"enabled": true,
|
||||
"parameters": {}
|
||||
},
|
||||
{
|
||||
"name": "rust",
|
||||
"priority": 1,
|
||||
"enabled": false,
|
||||
"parameters": {}
|
||||
},
|
||||
{
|
||||
"name": "python",
|
||||
"priority": 2,
|
||||
"enabled": true,
|
||||
"parameters": {}
|
||||
}
|
||||
],
|
||||
"default_tool": "swift",
|
||||
"enabled": true
|
||||
},
|
||||
"ocr": {
|
||||
"tools": [
|
||||
{
|
||||
"name": "swift",
|
||||
"priority": 0,
|
||||
"enabled": true,
|
||||
"parameters": {}
|
||||
},
|
||||
{
|
||||
"name": "python",
|
||||
"priority": 1,
|
||||
"enabled": true,
|
||||
"parameters": {}
|
||||
}
|
||||
],
|
||||
"default_tool": "swift",
|
||||
"enabled": true
|
||||
},
|
||||
"face_trace": {
|
||||
"tools": [
|
||||
{
|
||||
"name": "rust",
|
||||
"priority": 0,
|
||||
"enabled": true,
|
||||
"parameters": {
|
||||
"min_trace_len": 0,
|
||||
"min_confidence": 0.0
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "python",
|
||||
"priority": 1,
|
||||
"enabled": false,
|
||||
"parameters": {}
|
||||
}
|
||||
],
|
||||
"default_tool": "rust",
|
||||
"enabled": true
|
||||
},
|
||||
"face_deduplicate": {
|
||||
"tools": [
|
||||
{
|
||||
"name": "python",
|
||||
"priority": 0,
|
||||
"enabled": true,
|
||||
"parameters": {}
|
||||
},
|
||||
{
|
||||
"name": "rust",
|
||||
"priority": 1,
|
||||
"enabled": false,
|
||||
"parameters": {}
|
||||
}
|
||||
],
|
||||
"default_tool": "python",
|
||||
"enabled": true
|
||||
},
|
||||
"scene_vlm_summary": {
|
||||
"tools": [
|
||||
{
|
||||
"name": "python",
|
||||
"priority": 0,
|
||||
"enabled": true,
|
||||
"parameters": {
|
||||
"model": "gemma-4-12b-it",
|
||||
"max_tokens": 300
|
||||
}
|
||||
}
|
||||
],
|
||||
"default_tool": "python",
|
||||
"enabled": true
|
||||
},
|
||||
"tkg": {
|
||||
"tools": [
|
||||
{
|
||||
"name": "python",
|
||||
"priority": 0,
|
||||
"enabled": true,
|
||||
"parameters": {}
|
||||
},
|
||||
{
|
||||
"name": "rust",
|
||||
"priority": 1,
|
||||
"enabled": false,
|
||||
"parameters": {}
|
||||
}
|
||||
],
|
||||
"default_tool": "python",
|
||||
"enabled": true
|
||||
},
|
||||
"vlm_summary": {
|
||||
"tools": [
|
||||
{
|
||||
"name": "rust",
|
||||
"priority": 0,
|
||||
"enabled": true,
|
||||
"parameters": {
|
||||
"model": "gemma-4-12b-it",
|
||||
"max_tokens": 800,
|
||||
"use_vision": true
|
||||
}
|
||||
}
|
||||
],
|
||||
"default_tool": "rust",
|
||||
"enabled": true
|
||||
},
|
||||
"cut": {
|
||||
"tools": [
|
||||
{
|
||||
"name": "rust",
|
||||
"priority": 0,
|
||||
"enabled": true,
|
||||
"parameters": {
|
||||
"use_ffmpeg": true,
|
||||
"min_scene_duration": 0.5
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "python",
|
||||
"priority": 1,
|
||||
"enabled": false,
|
||||
"parameters": {}
|
||||
}
|
||||
],
|
||||
"default_tool": "rust",
|
||||
"enabled": true
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,312 @@
|
||||
{
|
||||
"processor_config": {
|
||||
"pose": {
|
||||
"implementations": [
|
||||
{
|
||||
"tool": "python",
|
||||
"model": "mediapipe",
|
||||
"priority": 0,
|
||||
"enabled": true,
|
||||
"parameters": {
|
||||
"model_complexity": 2,
|
||||
"min_confidence": 0.5,
|
||||
"script": "pose_processor_mediapipe.py"
|
||||
}
|
||||
},
|
||||
{
|
||||
"tool": "rust",
|
||||
"model": null,
|
||||
"priority": 1,
|
||||
"enabled": true,
|
||||
"parameters": {},
|
||||
"binary": "rust_pose"
|
||||
},
|
||||
{
|
||||
"tool": "swift",
|
||||
"model": null,
|
||||
"priority": 2,
|
||||
"enabled": true,
|
||||
"parameters": {},
|
||||
"binary": "swift_pose"
|
||||
},
|
||||
{
|
||||
"tool": "python",
|
||||
"model": "yolov8-pose",
|
||||
"priority": 3,
|
||||
"enabled": false,
|
||||
"parameters": {
|
||||
"model_file": "yolov8n-pose.pt"
|
||||
}
|
||||
}
|
||||
],
|
||||
"default": {
|
||||
"tool": "python",
|
||||
"model": "mediapipe"
|
||||
},
|
||||
"timeout": 3600,
|
||||
"enabled": true
|
||||
},
|
||||
"face": {
|
||||
"implementations": [
|
||||
{
|
||||
"tool": "swift",
|
||||
"model": null,
|
||||
"priority": 0,
|
||||
"enabled": true,
|
||||
"parameters": {},
|
||||
"binary": "swift_face"
|
||||
},
|
||||
{
|
||||
"tool": "python",
|
||||
"model": null,
|
||||
"priority": 1,
|
||||
"enabled": true,
|
||||
"parameters": {},
|
||||
"script": "face_detector.py"
|
||||
}
|
||||
],
|
||||
"default": {
|
||||
"tool": "swift",
|
||||
"model": null
|
||||
},
|
||||
"enabled": true
|
||||
},
|
||||
"asr": {
|
||||
"implementations": [
|
||||
{
|
||||
"tool": "python",
|
||||
"model": "whisper",
|
||||
"priority": 0,
|
||||
"enabled": true,
|
||||
"parameters": {
|
||||
"model_size": "large-v3",
|
||||
"model_dir": "/Users/accusys/models/whisper-small-mlx",
|
||||
"script": "asr_processor_whisper.py"
|
||||
}
|
||||
},
|
||||
{
|
||||
"tool": "rust",
|
||||
"model": "whisper",
|
||||
"priority": 1,
|
||||
"enabled": false,
|
||||
"parameters": {
|
||||
"model_size": "base"
|
||||
}
|
||||
}
|
||||
],
|
||||
"default": {
|
||||
"tool": "python",
|
||||
"model": "whisper"
|
||||
},
|
||||
"enabled": true
|
||||
},
|
||||
"asrx": {
|
||||
"implementations": [
|
||||
{
|
||||
"tool": "swift",
|
||||
"model": null,
|
||||
"priority": 0,
|
||||
"enabled": true,
|
||||
"parameters": {},
|
||||
"binary": "swift_asrx"
|
||||
},
|
||||
{
|
||||
"tool": "python",
|
||||
"model": null,
|
||||
"priority": 1,
|
||||
"enabled": true,
|
||||
"parameters": {},
|
||||
"script": "asrx_processor.py"
|
||||
}
|
||||
],
|
||||
"default": {
|
||||
"tool": "swift",
|
||||
"model": null
|
||||
},
|
||||
"enabled": true
|
||||
},
|
||||
"ocr": {
|
||||
"implementations": [
|
||||
{
|
||||
"tool": "swift",
|
||||
"model": null,
|
||||
"priority": 0,
|
||||
"enabled": true,
|
||||
"parameters": {},
|
||||
"binary": "swift_ocr"
|
||||
},
|
||||
{
|
||||
"tool": "python",
|
||||
"model": "tesseract",
|
||||
"priority": 1,
|
||||
"enabled": true,
|
||||
"parameters": {},
|
||||
"script": "ocr_processor.py"
|
||||
}
|
||||
],
|
||||
"default": {
|
||||
"tool": "swift",
|
||||
"model": null
|
||||
},
|
||||
"enabled": true
|
||||
},
|
||||
"face_trace": {
|
||||
"implementations": [
|
||||
{
|
||||
"tool": "rust",
|
||||
"model": null,
|
||||
"priority": 0,
|
||||
"enabled": true,
|
||||
"parameters": {
|
||||
"min_trace_len": 0,
|
||||
"min_confidence": 0.0
|
||||
},
|
||||
"binary": "rust_store_traced_faces"
|
||||
},
|
||||
{
|
||||
"tool": "python",
|
||||
"model": null,
|
||||
"priority": 1,
|
||||
"enabled": false,
|
||||
"parameters": {},
|
||||
"script": "store_traced_faces.py"
|
||||
}
|
||||
],
|
||||
"default": {
|
||||
"tool": "rust",
|
||||
"model": null
|
||||
},
|
||||
"enabled": true
|
||||
},
|
||||
"face_deduplicate": {
|
||||
"implementations": [
|
||||
{
|
||||
"tool": "python",
|
||||
"model": null,
|
||||
"priority": 0,
|
||||
"enabled": true,
|
||||
"parameters": {},
|
||||
"script": "face_deduplicate.py"
|
||||
},
|
||||
{
|
||||
"tool": "rust",
|
||||
"model": null,
|
||||
"priority": 1,
|
||||
"enabled": false,
|
||||
"parameters": {},
|
||||
"binary": "rust_face_deduplicate"
|
||||
}
|
||||
],
|
||||
"default": {
|
||||
"tool": "python",
|
||||
"model": null
|
||||
},
|
||||
"enabled": true
|
||||
},
|
||||
"scene_vlm_summary": {
|
||||
"implementations": [
|
||||
{
|
||||
"tool": "python",
|
||||
"model": "gemma-4-12b-it",
|
||||
"priority": 0,
|
||||
"enabled": true,
|
||||
"parameters": {
|
||||
"max_tokens": 300,
|
||||
"llm_url": "http://localhost:8080/v1/chat/completions",
|
||||
"script": "scene_vlm_summary.py"
|
||||
}
|
||||
}
|
||||
],
|
||||
"default": {
|
||||
"tool": "python",
|
||||
"model": "gemma-4-12b-it"
|
||||
},
|
||||
"enabled": true
|
||||
},
|
||||
"tkg": {
|
||||
"implementations": [
|
||||
{
|
||||
"tool": "python",
|
||||
"model": null,
|
||||
"priority": 0,
|
||||
"enabled": true,
|
||||
"parameters": {},
|
||||
"script": "build_tkg.py"
|
||||
},
|
||||
{
|
||||
"tool": "rust",
|
||||
"model": null,
|
||||
"priority": 1,
|
||||
"enabled": false,
|
||||
"parameters": {},
|
||||
"binary": "rust_tkg"
|
||||
}
|
||||
],
|
||||
"default": {
|
||||
"tool": "python",
|
||||
"model": null
|
||||
},
|
||||
"enabled": true
|
||||
},
|
||||
"vlm_summary": {
|
||||
"implementations": [
|
||||
{
|
||||
"tool": "rust",
|
||||
"model": "gemma-4-12b-it",
|
||||
"priority": 0,
|
||||
"enabled": true,
|
||||
"parameters": {
|
||||
"max_tokens": 800,
|
||||
"use_vision": true,
|
||||
"llm_url": "http://localhost:8080/v1/chat/completions"
|
||||
},
|
||||
"binary": "rust_vlm_summary"
|
||||
}
|
||||
],
|
||||
"default": {
|
||||
"tool": "rust",
|
||||
"model": "gemma-4-12b-it"
|
||||
},
|
||||
"enabled": true
|
||||
},
|
||||
"cut": {
|
||||
"implementations": [
|
||||
{
|
||||
"tool": "rust",
|
||||
"model": null,
|
||||
"priority": 0,
|
||||
"enabled": true,
|
||||
"parameters": {
|
||||
"use_ffmpeg": true,
|
||||
"min_scene_duration": 0.5
|
||||
},
|
||||
"binary": "rust_cut"
|
||||
},
|
||||
{
|
||||
"tool": "python",
|
||||
"model": null,
|
||||
"priority": 1,
|
||||
"enabled": false,
|
||||
"parameters": {},
|
||||
"script": "cut_detector.py"
|
||||
}
|
||||
],
|
||||
"default": {
|
||||
"tool": "rust",
|
||||
"model": null
|
||||
},
|
||||
"enabled": true
|
||||
}
|
||||
},
|
||||
"metadata": {
|
||||
"version": "2.0",
|
||||
"description": "Processor configuration with tool/model separation",
|
||||
"tools": ["python", "rust", "swift"],
|
||||
"models": {
|
||||
"whisper": ["base", "small", "medium", "large", "large-v3"],
|
||||
"mediapipe": ["pose", "face"],
|
||||
"yolov8": ["pose", "detect"],
|
||||
"gemma": ["gemma-4-12b-it", "embeddinggemma-300m"]
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,559 @@
|
||||
{
|
||||
"processor_config": {
|
||||
"pose": {
|
||||
"implementations": [
|
||||
{
|
||||
"tool": "rust",
|
||||
"model": null,
|
||||
"priority": 1,
|
||||
"enabled": false,
|
||||
"command": {
|
||||
"executable": "tools/cli/rust/target/release/rust_pose",
|
||||
"args": [
|
||||
"--video",
|
||||
"{video_path}",
|
||||
"--output",
|
||||
"{output_path}",
|
||||
"--uuid",
|
||||
"{file_uuid}"
|
||||
]
|
||||
},
|
||||
"parameters": {},
|
||||
"output_file": "{file_uuid}.pose.json",
|
||||
"timeout": 1800
|
||||
},
|
||||
{
|
||||
"tool": "swift",
|
||||
"model": null,
|
||||
"priority": 0,
|
||||
"enabled": false,
|
||||
"command": {
|
||||
"executable": "scripts/swift_processors/.build/release/swift_pose",
|
||||
"args": [
|
||||
"{video_path}",
|
||||
"--output",
|
||||
"{output_path}",
|
||||
"--uuid",
|
||||
"{file_uuid}"
|
||||
]
|
||||
},
|
||||
"parameters": {},
|
||||
"output_file": "{file_uuid}.pose.json",
|
||||
"timeout": 1800
|
||||
},
|
||||
{
|
||||
"tool": "python",
|
||||
"model": "mediapipe",
|
||||
"priority": 2,
|
||||
"enabled": false,
|
||||
"command": {
|
||||
"executable": "/opt/homebrew/bin/python3.11",
|
||||
"script": "scripts/pose_processor_mediapipe.py",
|
||||
"args": [
|
||||
"{video_path}",
|
||||
"{output_path}",
|
||||
"--uuid",
|
||||
"{file_uuid}",
|
||||
"--model-complexity",
|
||||
"{model_complexity}"
|
||||
]
|
||||
},
|
||||
"parameters": {
|
||||
"model_complexity": 2,
|
||||
"model_path": "/Users/accusys/models/mediapipe/pose_landmarker_heavy.task"
|
||||
},
|
||||
"output_file": "{file_uuid}.pose.json",
|
||||
"timeout": 3600
|
||||
},
|
||||
{
|
||||
"tool": "python",
|
||||
"model": "yolov8-pose",
|
||||
"priority": 3,
|
||||
"enabled": false,
|
||||
"command": {
|
||||
"executable": "/opt/homebrew/bin/python3.11",
|
||||
"script": "scripts/pose_processor_yolov8.py",
|
||||
"args": [
|
||||
"{video_path}",
|
||||
"{output_path}",
|
||||
"--model",
|
||||
"{model_file}"
|
||||
]
|
||||
},
|
||||
"parameters": {
|
||||
"model_file": "yolov8n-pose.pt"
|
||||
},
|
||||
"output_file": "{file_uuid}.pose.json",
|
||||
"timeout": 3600
|
||||
}
|
||||
],
|
||||
"default": {
|
||||
"tool": "rust",
|
||||
"model": null
|
||||
}
|
||||
},
|
||||
"face": {
|
||||
"implementations": [
|
||||
{
|
||||
"tool": "swift",
|
||||
"model": null,
|
||||
"priority": 0,
|
||||
"enabled": true,
|
||||
"command": {
|
||||
"executable": "scripts/swift_processors/.build/release/swift_face",
|
||||
"args": [
|
||||
"{video_path}",
|
||||
"{output_path}",
|
||||
"--uuid",
|
||||
"{file_uuid}"
|
||||
]
|
||||
},
|
||||
"parameters": {},
|
||||
"output_file": "{file_uuid}.face.json",
|
||||
"timeout": 3600
|
||||
},
|
||||
{
|
||||
"tool": "python",
|
||||
"model": "facenet",
|
||||
"priority": 2,
|
||||
"enabled": true,
|
||||
"command": {
|
||||
"executable": "/opt/homebrew/bin/python3.11",
|
||||
"script": "scripts/face_detector.py",
|
||||
"args": [
|
||||
"{video_path}",
|
||||
"{output_path}",
|
||||
"--uuid",
|
||||
"{file_uuid}",
|
||||
"--model",
|
||||
"{model_name}"
|
||||
]
|
||||
},
|
||||
"parameters": {
|
||||
"model_name": "facenet",
|
||||
"model_path": "/Users/accusys/models/facenet512.mlpackage"
|
||||
},
|
||||
"output_file": "{file_uuid}.face.json",
|
||||
"timeout": 3600
|
||||
}
|
||||
],
|
||||
"default": {
|
||||
"tool": "swift",
|
||||
"model": null
|
||||
}
|
||||
},
|
||||
"asr": {
|
||||
"implementations": [
|
||||
{
|
||||
"tool": "rust",
|
||||
"model": "whisper",
|
||||
"priority": 0,
|
||||
"enabled": false,
|
||||
"command": {
|
||||
"executable": "tools/cli/rust/target/release/rust_whisper",
|
||||
"args": [
|
||||
"{video_path}",
|
||||
"--output",
|
||||
"{output_path}",
|
||||
"--uuid",
|
||||
"{file_uuid}",
|
||||
"--model",
|
||||
"{model_size}"
|
||||
]
|
||||
},
|
||||
"parameters": {
|
||||
"model_size": "base"
|
||||
},
|
||||
"output_file": "{file_uuid}.asr.json",
|
||||
"timeout": 3600
|
||||
},
|
||||
{
|
||||
"tool": "python",
|
||||
"model": "whisper",
|
||||
"priority": 1,
|
||||
"enabled": true,
|
||||
"command": {
|
||||
"executable": "/opt/homebrew/bin/python3.11",
|
||||
"script": "scripts/asr_processor_simplified.py",
|
||||
"args": [
|
||||
"{video_path}",
|
||||
"{output_path}",
|
||||
"--model",
|
||||
"{model_size}"
|
||||
]
|
||||
},
|
||||
"parameters": {
|
||||
"model_size": "large-v3",
|
||||
"model_dir": "/Users/accusys/models/whisper-small-mlx"
|
||||
},
|
||||
"output_file": "{file_uuid}.asr.json",
|
||||
"timeout": 7200
|
||||
}
|
||||
],
|
||||
"default": {
|
||||
"tool": "python",
|
||||
"model": "whisper"
|
||||
}
|
||||
},
|
||||
"asrx": {
|
||||
"implementations": [
|
||||
{
|
||||
"tool": "swift",
|
||||
"model": null,
|
||||
"priority": 0,
|
||||
"enabled": false,
|
||||
"command": {
|
||||
"executable": "scripts/swift_processors/.build/release/asrx_swift",
|
||||
"args": [
|
||||
"{video_path}",
|
||||
"--output",
|
||||
"{output_path}",
|
||||
"--uuid",
|
||||
"{file_uuid}"
|
||||
]
|
||||
},
|
||||
"parameters": {},
|
||||
"output_file": "{file_uuid}.asrx.json",
|
||||
"timeout": 1800
|
||||
},
|
||||
{
|
||||
"tool": "python",
|
||||
"model": null,
|
||||
"priority": 0,
|
||||
"enabled": true,
|
||||
"command": {
|
||||
"executable": "/opt/homebrew/bin/python3.11",
|
||||
"script": "scripts/asrx_processor.py",
|
||||
"args": [
|
||||
"{video_path}",
|
||||
"{output_path}",
|
||||
"--uuid",
|
||||
"{file_uuid}"
|
||||
]
|
||||
},
|
||||
"parameters": {},
|
||||
"output_file": "{file_uuid}.asrx.json",
|
||||
"timeout": 1800
|
||||
}
|
||||
],
|
||||
"default": {
|
||||
"tool": "swift",
|
||||
"model": null
|
||||
}
|
||||
},
|
||||
"ocr": {
|
||||
"implementations": [
|
||||
{
|
||||
"tool": "swift",
|
||||
"model": null,
|
||||
"priority": 0,
|
||||
"enabled": true,
|
||||
"command": {
|
||||
"executable": "scripts/swift_processors/.build/release/swift_ocr",
|
||||
"args": [
|
||||
"{video_path}",
|
||||
"--output",
|
||||
"{output_path}",
|
||||
"--uuid",
|
||||
"{file_uuid}"
|
||||
]
|
||||
},
|
||||
"parameters": {},
|
||||
"output_file": "{file_uuid}.ocr.json",
|
||||
"timeout": 3600
|
||||
},
|
||||
{
|
||||
"tool": "python",
|
||||
"model": "tesseract",
|
||||
"priority": 2,
|
||||
"enabled": true,
|
||||
"command": {
|
||||
"executable": "/opt/homebrew/bin/python3.11",
|
||||
"script": "scripts/ocr_processor.py",
|
||||
"args": [
|
||||
"{video_path}",
|
||||
"{output_path}",
|
||||
"--uuid",
|
||||
"{file_uuid}"
|
||||
]
|
||||
},
|
||||
"parameters": {},
|
||||
"output_file": "{file_uuid}.ocr.json",
|
||||
"timeout": 3600
|
||||
}
|
||||
],
|
||||
"default": {
|
||||
"tool": "swift",
|
||||
"model": null
|
||||
}
|
||||
},
|
||||
"face_trace": {
|
||||
"implementations": [
|
||||
{
|
||||
"tool": "rust",
|
||||
"model": null,
|
||||
"priority": 0,
|
||||
"enabled": true,
|
||||
"command": {
|
||||
"executable": "tools/cli/rust/target/release/rust_store_traced_faces",
|
||||
"args": [
|
||||
"{file_uuid}",
|
||||
"--output-dir",
|
||||
"{output_dir}",
|
||||
"--min-trace-len",
|
||||
"{min_trace_len}",
|
||||
"--min-confidence",
|
||||
"{min_confidence}"
|
||||
]
|
||||
},
|
||||
"parameters": {
|
||||
"min_trace_len": 0,
|
||||
"min_confidence": 0.0
|
||||
},
|
||||
"output_file": "{file_uuid}.face_traced.json",
|
||||
"timeout": 600
|
||||
},
|
||||
{
|
||||
"tool": "python",
|
||||
"model": null,
|
||||
"priority": 1,
|
||||
"enabled": false,
|
||||
"command": {
|
||||
"executable": "/opt/homebrew/bin/python3.11",
|
||||
"script": "scripts/store_traced_faces.py",
|
||||
"args": [
|
||||
"--file-uuid",
|
||||
"{file_uuid}",
|
||||
"--face-json",
|
||||
"{face_json}"
|
||||
]
|
||||
},
|
||||
"parameters": {},
|
||||
"output_file": "{file_uuid}.face_traced.json",
|
||||
"timeout": 1200
|
||||
}
|
||||
],
|
||||
"default": {
|
||||
"tool": "rust",
|
||||
"model": null
|
||||
}
|
||||
},
|
||||
"scene_vlm_summary": {
|
||||
"implementations": [
|
||||
{
|
||||
"tool": "rust",
|
||||
"model": "gemma-4-12b-it",
|
||||
"priority": 0,
|
||||
"enabled": true,
|
||||
"command": {
|
||||
"executable": "tools/cli/rust/target/release/rust_scene_vlm",
|
||||
"args": [
|
||||
"--file-uuid",
|
||||
"{file_uuid}",
|
||||
"--output-dir",
|
||||
"{output_dir}",
|
||||
"--llm-url",
|
||||
"{llm_url}",
|
||||
"--max-tokens",
|
||||
"{max_tokens}"
|
||||
]
|
||||
},
|
||||
"parameters": {
|
||||
"llm_url": "http://localhost:8080/v1/chat/completions",
|
||||
"max_tokens": 900
|
||||
},
|
||||
"output_file": "{file_uuid}.scene_vlm.json",
|
||||
"timeout": 1800
|
||||
},
|
||||
{
|
||||
"tool": "python",
|
||||
"model": "gemma-4-12b-it",
|
||||
"priority": 1,
|
||||
"enabled": false,
|
||||
"command": {
|
||||
"executable": "/opt/homebrew/bin/python3.11",
|
||||
"script": "scripts/scene_vlm_summary.py",
|
||||
"args": [
|
||||
"--file-uuid",
|
||||
"{file_uuid}",
|
||||
"--output-dir",
|
||||
"{output_dir}",
|
||||
"--llm-url",
|
||||
"{llm_url}",
|
||||
"--max-tokens",
|
||||
"{max_tokens}"
|
||||
]
|
||||
},
|
||||
"parameters": {
|
||||
"llm_url": "http://localhost:8080/v1/chat/completions",
|
||||
"max_tokens": 900
|
||||
},
|
||||
"output_file": "{file_uuid}.scene_vlm.json",
|
||||
"timeout": 1800
|
||||
}
|
||||
],
|
||||
"default": {
|
||||
"tool": "python",
|
||||
"model": "gemma-4-12b-it"
|
||||
}
|
||||
},
|
||||
"tkg": {
|
||||
"implementations": [
|
||||
{
|
||||
"tool": "rust",
|
||||
"model": null,
|
||||
"priority": 0,
|
||||
"enabled": false,
|
||||
"command": {
|
||||
"executable": "tools/cli/rust/target/release/rust_tkg",
|
||||
"args": [
|
||||
"--file-uuid",
|
||||
"{file_uuid}",
|
||||
"--output-dir",
|
||||
"{output_dir}"
|
||||
]
|
||||
},
|
||||
"parameters": {},
|
||||
"output_file": "{file_uuid}.tkg.json",
|
||||
"timeout": 1800
|
||||
},
|
||||
{
|
||||
"tool": "python",
|
||||
"model": null,
|
||||
"priority": 1,
|
||||
"enabled": true,
|
||||
"command": {
|
||||
"executable": "/opt/homebrew/bin/python3.11",
|
||||
"script": "scripts/build_tkg.py",
|
||||
"args": [
|
||||
"--file-uuid",
|
||||
"{file_uuid}",
|
||||
"--output-dir",
|
||||
"{output_dir}"
|
||||
]
|
||||
},
|
||||
"parameters": {},
|
||||
"output_file": "{file_uuid}.tkg.json",
|
||||
"timeout": 1800
|
||||
}
|
||||
],
|
||||
"default": {
|
||||
"tool": "python",
|
||||
"model": null
|
||||
}
|
||||
},
|
||||
"cut": {
|
||||
"implementations": [
|
||||
{
|
||||
"tool": "rust",
|
||||
"model": null,
|
||||
"priority": 0,
|
||||
"enabled": true,
|
||||
"command": {
|
||||
"executable": "tools/cli/rust/target/release/rust_cut",
|
||||
"args": [
|
||||
"{video_path}",
|
||||
"--output",
|
||||
"{output_path}",
|
||||
"--uuid",
|
||||
"{file_uuid}",
|
||||
"--min-scene-duration",
|
||||
"{min_scene_duration}"
|
||||
]
|
||||
},
|
||||
"parameters": {
|
||||
"use_ffmpeg": true,
|
||||
"min_scene_duration": 0.5
|
||||
},
|
||||
"output_file": "{file_uuid}.cut.json",
|
||||
"timeout": 1800
|
||||
},
|
||||
{
|
||||
"tool": "python",
|
||||
"model": null,
|
||||
"priority": 1,
|
||||
"enabled": false,
|
||||
"command": {
|
||||
"executable": "/opt/homebrew/bin/python3.11",
|
||||
"script": "scripts/cut_detector.py",
|
||||
"args": [
|
||||
"{video_path}",
|
||||
"{output_path}",
|
||||
"--uuid",
|
||||
"{file_uuid}"
|
||||
]
|
||||
},
|
||||
"parameters": {},
|
||||
"output_file": "{file_uuid}.cut.json",
|
||||
"timeout": 1800
|
||||
}
|
||||
],
|
||||
"default": {
|
||||
"tool": "rust",
|
||||
"model": null
|
||||
}
|
||||
}
|
||||
},
|
||||
"variables": {
|
||||
"video_path": "Full path to video file",
|
||||
"output_path": "Full path to output JSON file",
|
||||
"output_dir": "Output directory (default: /Users/accusys/momentry/output)",
|
||||
"file_uuid": "Video file UUID",
|
||||
"face_json": "Path to face.json file"
|
||||
},
|
||||
"environment": {
|
||||
"MOMENTRY_OUTPUT_DIR": "/Users/accusys/momentry/output",
|
||||
"MOMENTRY_SCRIPTS_DIR": "tools/script/",
|
||||
"MOMENTRY_CLI_DIR": "tools/cli/",
|
||||
"MOMENTRY_PYTHON_PATH": "/opt/homebrew/bin/python3.11",
|
||||
"DATABASE_SCHEMA": "public",
|
||||
"DATABASE_URL": "postgres://accusys@localhost:5432/momentry",
|
||||
"REDIS_URL": "redis://:accusys@localhost:6379"
|
||||
},
|
||||
"models": {
|
||||
"whisper": {
|
||||
"description": "OpenAI Whisper ASR model",
|
||||
"sizes": [
|
||||
"tiny",
|
||||
"base",
|
||||
"small",
|
||||
"medium",
|
||||
"large",
|
||||
"large-v3"
|
||||
],
|
||||
"default_size": "large-v3",
|
||||
"model_dir": "/Users/accusys/models/whisper-small-mlx"
|
||||
},
|
||||
"mediapipe": {
|
||||
"description": "MediaPipe Pose estimation",
|
||||
"model_path": "/Users/accusys/models/mediapipe/pose_landmarker_heavy.task",
|
||||
"complexity_levels": [
|
||||
0,
|
||||
1,
|
||||
2
|
||||
],
|
||||
"default_complexity": 2
|
||||
},
|
||||
"facenet": {
|
||||
"description": "FaceNet 512D embedding model",
|
||||
"model_path": "/Users/accusys/models/facenet512.mlpackage"
|
||||
},
|
||||
"gemma-4-12b-it": {
|
||||
"description": "Gemma 4 12B instruct model for VLM/LLM",
|
||||
"model_path": "/Users/accusys/models/gemma-4-12b-it-Q4_K_M.gguf",
|
||||
"mmproj_path": "/Users/accusys/models/mmproj-F16.gguf",
|
||||
"llm_url": "http://localhost:8080/v1/chat/completions"
|
||||
},
|
||||
"embeddinggemma-300m": {
|
||||
"description": "Embedding Gemma 300M for vector embeddings",
|
||||
"model_path": "/Users/accusys/models/embeddinggemma-300M-Q8_0.gguf",
|
||||
"embedding_url": "http://localhost:11436/embed"
|
||||
}
|
||||
},
|
||||
"metadata": {
|
||||
"version": "3.0",
|
||||
"description": "Processor configuration - CLI tools (rust/swift) prioritized",
|
||||
"priority_policy": "rust/swift CLI (priority 0) > python (priority 1+)",
|
||||
"last_updated": "2026-09-27"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,560 @@
|
||||
{
|
||||
"processor_config": {
|
||||
"pose": {
|
||||
"implementations": [
|
||||
{
|
||||
"tool": "rust",
|
||||
"model": null,
|
||||
"priority": 1,
|
||||
"enabled": false,
|
||||
"command": {
|
||||
"executable": "tools/cli/rust/target/release/rust_pose",
|
||||
"args": [
|
||||
"--video",
|
||||
"{video_path}",
|
||||
"--output",
|
||||
"{output_path}",
|
||||
"--uuid",
|
||||
"{file_uuid}"
|
||||
]
|
||||
},
|
||||
"parameters": {},
|
||||
"output_file": "{file_uuid}.pose.json",
|
||||
"timeout": 1800
|
||||
},
|
||||
{
|
||||
"tool": "swift",
|
||||
"model": null,
|
||||
"priority": 0,
|
||||
"enabled": true,
|
||||
"command": {
|
||||
"executable": "scripts/swift_processors/.build/release/swift_pose",
|
||||
"args": [
|
||||
"{video_path}",
|
||||
"--output",
|
||||
"{output_path}",
|
||||
"--uuid",
|
||||
"{file_uuid}"
|
||||
]
|
||||
},
|
||||
"parameters": {},
|
||||
"output_file": "{file_uuid}.pose.json",
|
||||
"timeout": 1800
|
||||
},
|
||||
{
|
||||
"tool": "python",
|
||||
"model": "mediapipe",
|
||||
"priority": 2,
|
||||
"enabled": true,
|
||||
"command": {
|
||||
"executable": "/opt/homebrew/bin/python3.11",
|
||||
"script": "scripts/pose_processor_mediapipe.py",
|
||||
"args": [
|
||||
"{video_path}",
|
||||
"{output_path}",
|
||||
"--uuid",
|
||||
"{file_uuid}",
|
||||
"--model-complexity",
|
||||
"{model_complexity}"
|
||||
]
|
||||
},
|
||||
"parameters": {
|
||||
"model_complexity": 2,
|
||||
"model_path": "/Users/accusys/models/mediapipe/pose_landmarker_heavy.task"
|
||||
},
|
||||
"output_file": "{file_uuid}.pose.json",
|
||||
"timeout": 3600
|
||||
},
|
||||
{
|
||||
"tool": "python",
|
||||
"model": "yolov8-pose",
|
||||
"priority": 3,
|
||||
"enabled": false,
|
||||
"command": {
|
||||
"executable": "/opt/homebrew/bin/python3.11",
|
||||
"script": "scripts/pose_processor_yolov8.py",
|
||||
"args": [
|
||||
"{video_path}",
|
||||
"{output_path}",
|
||||
"--model",
|
||||
"{model_file}"
|
||||
]
|
||||
},
|
||||
"parameters": {
|
||||
"model_file": "yolov8n-pose.pt"
|
||||
},
|
||||
"output_file": "{file_uuid}.pose.json",
|
||||
"timeout": 3600
|
||||
}
|
||||
],
|
||||
"default": {
|
||||
"tool": "rust",
|
||||
"model": null
|
||||
}
|
||||
},
|
||||
"face": {
|
||||
"implementations": [
|
||||
{
|
||||
"tool": "swift",
|
||||
"model": null,
|
||||
"priority": 0,
|
||||
"enabled": true,
|
||||
"command": {
|
||||
"executable": "scripts/swift_processors/.build/release/swift_face",
|
||||
"args": [
|
||||
"{video_path}",
|
||||
"--output",
|
||||
"{output_path}",
|
||||
"--uuid",
|
||||
"{file_uuid}"
|
||||
]
|
||||
},
|
||||
"parameters": {},
|
||||
"output_file": "{file_uuid}.face.json",
|
||||
"timeout": 3600
|
||||
},
|
||||
{
|
||||
"tool": "python",
|
||||
"model": "facenet",
|
||||
"priority": 2,
|
||||
"enabled": true,
|
||||
"command": {
|
||||
"executable": "/opt/homebrew/bin/python3.11",
|
||||
"script": "scripts/face_detector.py",
|
||||
"args": [
|
||||
"{video_path}",
|
||||
"{output_path}",
|
||||
"--uuid",
|
||||
"{file_uuid}",
|
||||
"--model",
|
||||
"{model_name}"
|
||||
]
|
||||
},
|
||||
"parameters": {
|
||||
"model_name": "facenet",
|
||||
"model_path": "/Users/accusys/models/facenet512.mlpackage"
|
||||
},
|
||||
"output_file": "{file_uuid}.face.json",
|
||||
"timeout": 3600
|
||||
}
|
||||
],
|
||||
"default": {
|
||||
"tool": "swift",
|
||||
"model": null
|
||||
}
|
||||
},
|
||||
"asr": {
|
||||
"implementations": [
|
||||
{
|
||||
"tool": "rust",
|
||||
"model": "whisper",
|
||||
"priority": 0,
|
||||
"enabled": false,
|
||||
"command": {
|
||||
"executable": "tools/cli/rust/target/release/rust_whisper",
|
||||
"args": [
|
||||
"{video_path}",
|
||||
"--output",
|
||||
"{output_path}",
|
||||
"--uuid",
|
||||
"{file_uuid}",
|
||||
"--model",
|
||||
"{model_size}"
|
||||
]
|
||||
},
|
||||
"parameters": {
|
||||
"model_size": "base"
|
||||
},
|
||||
"output_file": "{file_uuid}.asr.json",
|
||||
"timeout": 3600
|
||||
},
|
||||
{
|
||||
"tool": "python",
|
||||
"model": "whisper",
|
||||
"priority": 1,
|
||||
"enabled": true,
|
||||
"command": {
|
||||
"executable": "/opt/homebrew/bin/python3.11",
|
||||
"script": "scripts/asr_processor_simplified.py",
|
||||
"args": [
|
||||
"{video_path}",
|
||||
"{output_path}",
|
||||
"--model",
|
||||
"{model_size}"
|
||||
]
|
||||
},
|
||||
"parameters": {
|
||||
"model_size": "large-v3",
|
||||
"model_dir": "/Users/accusys/models/whisper-small-mlx"
|
||||
},
|
||||
"output_file": "{file_uuid}.asr.json",
|
||||
"timeout": 7200
|
||||
}
|
||||
],
|
||||
"default": {
|
||||
"tool": "python",
|
||||
"model": "whisper"
|
||||
}
|
||||
},
|
||||
"asrx": {
|
||||
"implementations": [
|
||||
{
|
||||
"tool": "swift",
|
||||
"model": null,
|
||||
"priority": 0,
|
||||
"enabled": false,
|
||||
"command": {
|
||||
"executable": "scripts/swift_processors/.build/release/asrx_swift",
|
||||
"args": [
|
||||
"{video_path}",
|
||||
"--output",
|
||||
"{output_path}",
|
||||
"--uuid",
|
||||
"{file_uuid}"
|
||||
]
|
||||
},
|
||||
"parameters": {},
|
||||
"output_file": "{file_uuid}.asrx.json",
|
||||
"timeout": 1800
|
||||
},
|
||||
{
|
||||
"tool": "python",
|
||||
"model": null,
|
||||
"priority": 0,
|
||||
"enabled": true,
|
||||
"command": {
|
||||
"executable": "/opt/homebrew/bin/python3.11",
|
||||
"script": "scripts/asrx_processor.py",
|
||||
"args": [
|
||||
"{video_path}",
|
||||
"{output_path}",
|
||||
"--uuid",
|
||||
"{file_uuid}"
|
||||
]
|
||||
},
|
||||
"parameters": {},
|
||||
"output_file": "{file_uuid}.asrx.json",
|
||||
"timeout": 1800
|
||||
}
|
||||
],
|
||||
"default": {
|
||||
"tool": "swift",
|
||||
"model": null
|
||||
}
|
||||
},
|
||||
"ocr": {
|
||||
"implementations": [
|
||||
{
|
||||
"tool": "swift",
|
||||
"model": null,
|
||||
"priority": 0,
|
||||
"enabled": true,
|
||||
"command": {
|
||||
"executable": "scripts/swift_processors/.build/release/swift_ocr",
|
||||
"args": [
|
||||
"{video_path}",
|
||||
"--output",
|
||||
"{output_path}",
|
||||
"--uuid",
|
||||
"{file_uuid}"
|
||||
]
|
||||
},
|
||||
"parameters": {},
|
||||
"output_file": "{file_uuid}.ocr.json",
|
||||
"timeout": 3600
|
||||
},
|
||||
{
|
||||
"tool": "python",
|
||||
"model": "tesseract",
|
||||
"priority": 2,
|
||||
"enabled": true,
|
||||
"command": {
|
||||
"executable": "/opt/homebrew/bin/python3.11",
|
||||
"script": "scripts/ocr_processor.py",
|
||||
"args": [
|
||||
"{video_path}",
|
||||
"{output_path}",
|
||||
"--uuid",
|
||||
"{file_uuid}"
|
||||
]
|
||||
},
|
||||
"parameters": {},
|
||||
"output_file": "{file_uuid}.ocr.json",
|
||||
"timeout": 3600
|
||||
}
|
||||
],
|
||||
"default": {
|
||||
"tool": "swift",
|
||||
"model": null
|
||||
}
|
||||
},
|
||||
"face_trace": {
|
||||
"implementations": [
|
||||
{
|
||||
"tool": "rust",
|
||||
"model": null,
|
||||
"priority": 0,
|
||||
"enabled": true,
|
||||
"command": {
|
||||
"executable": "tools/cli/rust/target/release/rust_store_traced_faces",
|
||||
"args": [
|
||||
"{file_uuid}",
|
||||
"--output-dir",
|
||||
"{output_dir}",
|
||||
"--min-trace-len",
|
||||
"{min_trace_len}",
|
||||
"--min-confidence",
|
||||
"{min_confidence}"
|
||||
]
|
||||
},
|
||||
"parameters": {
|
||||
"min_trace_len": 0,
|
||||
"min_confidence": 0.0
|
||||
},
|
||||
"output_file": "{file_uuid}.face_traced.json",
|
||||
"timeout": 600
|
||||
},
|
||||
{
|
||||
"tool": "python",
|
||||
"model": null,
|
||||
"priority": 1,
|
||||
"enabled": false,
|
||||
"command": {
|
||||
"executable": "/opt/homebrew/bin/python3.11",
|
||||
"script": "scripts/store_traced_faces.py",
|
||||
"args": [
|
||||
"--file-uuid",
|
||||
"{file_uuid}",
|
||||
"--face-json",
|
||||
"{face_json}"
|
||||
]
|
||||
},
|
||||
"parameters": {},
|
||||
"output_file": "{file_uuid}.face_traced.json",
|
||||
"timeout": 1200
|
||||
}
|
||||
],
|
||||
"default": {
|
||||
"tool": "rust",
|
||||
"model": null
|
||||
}
|
||||
},
|
||||
"scene_vlm_summary": {
|
||||
"implementations": [
|
||||
{
|
||||
"tool": "rust",
|
||||
"model": "gemma-4-12b-it",
|
||||
"priority": 0,
|
||||
"enabled": true,
|
||||
"command": {
|
||||
"executable": "tools/cli/rust/target/release/rust_scene_vlm",
|
||||
"args": [
|
||||
"--file-uuid",
|
||||
"{file_uuid}",
|
||||
"--output-dir",
|
||||
"{output_dir}",
|
||||
"--llm-url",
|
||||
"{llm_url}",
|
||||
"--max-tokens",
|
||||
"{max_tokens}"
|
||||
]
|
||||
},
|
||||
"parameters": {
|
||||
"llm_url": "http://localhost:8080/v1/chat/completions",
|
||||
"max_tokens": 900
|
||||
},
|
||||
"output_file": "{file_uuid}.scene_vlm.json",
|
||||
"timeout": 1800
|
||||
},
|
||||
{
|
||||
"tool": "python",
|
||||
"model": "gemma-4-12b-it",
|
||||
"priority": 1,
|
||||
"enabled": false,
|
||||
"command": {
|
||||
"executable": "/opt/homebrew/bin/python3.11",
|
||||
"script": "scripts/scene_vlm_summary.py",
|
||||
"args": [
|
||||
"--file-uuid",
|
||||
"{file_uuid}",
|
||||
"--output-dir",
|
||||
"{output_dir}",
|
||||
"--llm-url",
|
||||
"{llm_url}",
|
||||
"--max-tokens",
|
||||
"{max_tokens}"
|
||||
]
|
||||
},
|
||||
"parameters": {
|
||||
"llm_url": "http://localhost:8080/v1/chat/completions",
|
||||
"max_tokens": 900
|
||||
},
|
||||
"output_file": "{file_uuid}.scene_vlm.json",
|
||||
"timeout": 1800
|
||||
}
|
||||
],
|
||||
"default": {
|
||||
"tool": "python",
|
||||
"model": "gemma-4-12b-it"
|
||||
}
|
||||
},
|
||||
"tkg": {
|
||||
"implementations": [
|
||||
{
|
||||
"tool": "rust",
|
||||
"model": null,
|
||||
"priority": 0,
|
||||
"enabled": false,
|
||||
"command": {
|
||||
"executable": "tools/cli/rust/target/release/rust_tkg",
|
||||
"args": [
|
||||
"--file-uuid",
|
||||
"{file_uuid}",
|
||||
"--output-dir",
|
||||
"{output_dir}"
|
||||
]
|
||||
},
|
||||
"parameters": {},
|
||||
"output_file": "{file_uuid}.tkg.json",
|
||||
"timeout": 1800
|
||||
},
|
||||
{
|
||||
"tool": "python",
|
||||
"model": null,
|
||||
"priority": 1,
|
||||
"enabled": true,
|
||||
"command": {
|
||||
"executable": "/opt/homebrew/bin/python3.11",
|
||||
"script": "scripts/build_tkg.py",
|
||||
"args": [
|
||||
"--file-uuid",
|
||||
"{file_uuid}",
|
||||
"--output-dir",
|
||||
"{output_dir}"
|
||||
]
|
||||
},
|
||||
"parameters": {},
|
||||
"output_file": "{file_uuid}.tkg.json",
|
||||
"timeout": 1800
|
||||
}
|
||||
],
|
||||
"default": {
|
||||
"tool": "python",
|
||||
"model": null
|
||||
}
|
||||
},
|
||||
"cut": {
|
||||
"implementations": [
|
||||
{
|
||||
"tool": "rust",
|
||||
"model": null,
|
||||
"priority": 0,
|
||||
"enabled": true,
|
||||
"command": {
|
||||
"executable": "tools/cli/rust/target/release/rust_cut",
|
||||
"args": [
|
||||
"{video_path}",
|
||||
"--output",
|
||||
"{output_path}",
|
||||
"--uuid",
|
||||
"{file_uuid}",
|
||||
"--min-scene-duration",
|
||||
"{min_scene_duration}"
|
||||
]
|
||||
},
|
||||
"parameters": {
|
||||
"use_ffmpeg": true,
|
||||
"min_scene_duration": 0.5
|
||||
},
|
||||
"output_file": "{file_uuid}.cut.json",
|
||||
"timeout": 1800
|
||||
},
|
||||
{
|
||||
"tool": "python",
|
||||
"model": null,
|
||||
"priority": 1,
|
||||
"enabled": false,
|
||||
"command": {
|
||||
"executable": "/opt/homebrew/bin/python3.11",
|
||||
"script": "scripts/cut_detector.py",
|
||||
"args": [
|
||||
"{video_path}",
|
||||
"{output_path}",
|
||||
"--uuid",
|
||||
"{file_uuid}"
|
||||
]
|
||||
},
|
||||
"parameters": {},
|
||||
"output_file": "{file_uuid}.cut.json",
|
||||
"timeout": 1800
|
||||
}
|
||||
],
|
||||
"default": {
|
||||
"tool": "rust",
|
||||
"model": null
|
||||
}
|
||||
}
|
||||
},
|
||||
"variables": {
|
||||
"video_path": "Full path to video file",
|
||||
"output_path": "Full path to output JSON file",
|
||||
"output_dir": "Output directory (default: /Users/accusys/momentry/output)",
|
||||
"file_uuid": "Video file UUID",
|
||||
"face_json": "Path to face.json file"
|
||||
},
|
||||
"environment": {
|
||||
"MOMENTRY_OUTPUT_DIR": "/Users/accusys/momentry/output",
|
||||
"MOMENTRY_SCRIPTS_DIR": "tools/script/",
|
||||
"MOMENTRY_CLI_DIR": "tools/cli/",
|
||||
"MOMENTRY_PYTHON_PATH": "/opt/homebrew/bin/python3.11",
|
||||
"DATABASE_SCHEMA": "public",
|
||||
"DATABASE_URL": "postgres://accusys@localhost:5432/momentry",
|
||||
"REDIS_URL": "redis://:accusys@localhost:6379"
|
||||
},
|
||||
"models": {
|
||||
"whisper": {
|
||||
"description": "OpenAI Whisper ASR model",
|
||||
"sizes": [
|
||||
"tiny",
|
||||
"base",
|
||||
"small",
|
||||
"medium",
|
||||
"large",
|
||||
"large-v3"
|
||||
],
|
||||
"default_size": "large-v3",
|
||||
"model_dir": "/Users/accusys/models/whisper-small-mlx"
|
||||
},
|
||||
"mediapipe": {
|
||||
"description": "MediaPipe Pose estimation",
|
||||
"model_path": "/Users/accusys/models/mediapipe/pose_landmarker_heavy.task",
|
||||
"complexity_levels": [
|
||||
0,
|
||||
1,
|
||||
2
|
||||
],
|
||||
"default_complexity": 2
|
||||
},
|
||||
"facenet": {
|
||||
"description": "FaceNet 512D embedding model",
|
||||
"model_path": "/Users/accusys/models/facenet512.mlpackage"
|
||||
},
|
||||
"gemma-4-12b-it": {
|
||||
"description": "Gemma 4 12B instruct model for VLM/LLM",
|
||||
"model_path": "/Users/accusys/models/gemma-4-12b-it-Q4_K_M.gguf",
|
||||
"mmproj_path": "/Users/accusys/models/mmproj-F16.gguf",
|
||||
"llm_url": "http://localhost:8080/v1/chat/completions"
|
||||
},
|
||||
"embeddinggemma-300m": {
|
||||
"description": "Embedding Gemma 300M for vector embeddings",
|
||||
"model_path": "/Users/accusys/models/embeddinggemma-300M-Q8_0.gguf",
|
||||
"embedding_url": "http://localhost:11436/embed"
|
||||
}
|
||||
},
|
||||
"metadata": {
|
||||
"version": "3.0",
|
||||
"description": "Processor configuration - CLI tools (rust/swift) prioritized",
|
||||
"priority_policy": "rust/swift CLI (priority 0) > python (priority 1+)",
|
||||
"last_updated": "2026-09-27"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,560 @@
|
||||
{
|
||||
"processor_config": {
|
||||
"pose": {
|
||||
"implementations": [
|
||||
{
|
||||
"tool": "rust",
|
||||
"model": null,
|
||||
"priority": 1,
|
||||
"enabled": false,
|
||||
"command": {
|
||||
"executable": "tools/cli/rust/target/release/rust_pose",
|
||||
"args": [
|
||||
"--video",
|
||||
"{video_path}",
|
||||
"--output",
|
||||
"{output_path}",
|
||||
"--uuid",
|
||||
"{file_uuid}"
|
||||
]
|
||||
},
|
||||
"parameters": {},
|
||||
"output_file": "{file_uuid}.pose.json",
|
||||
"timeout": 1800
|
||||
},
|
||||
{
|
||||
"tool": "swift",
|
||||
"model": null,
|
||||
"priority": 0,
|
||||
"enabled": true,
|
||||
"command": {
|
||||
"executable": "scripts/swift_processors/.build/release/swift_pose",
|
||||
"args": [
|
||||
"{video_path}",
|
||||
"--output",
|
||||
"{output_path}",
|
||||
"--uuid",
|
||||
"{file_uuid}"
|
||||
]
|
||||
},
|
||||
"parameters": {},
|
||||
"output_file": "{file_uuid}.pose.json",
|
||||
"timeout": 1800
|
||||
},
|
||||
{
|
||||
"tool": "python",
|
||||
"model": "mediapipe",
|
||||
"priority": 2,
|
||||
"enabled": true,
|
||||
"command": {
|
||||
"executable": "/opt/homebrew/bin/python3.11",
|
||||
"script": "scripts/pose_processor_mediapipe.py",
|
||||
"args": [
|
||||
"{video_path}",
|
||||
"{output_path}",
|
||||
"--uuid",
|
||||
"{file_uuid}",
|
||||
"--model-complexity",
|
||||
"{model_complexity}"
|
||||
]
|
||||
},
|
||||
"parameters": {
|
||||
"model_complexity": 2,
|
||||
"model_path": "/Users/accusys/models/mediapipe/pose_landmarker_heavy.task"
|
||||
},
|
||||
"output_file": "{file_uuid}.pose.json",
|
||||
"timeout": 3600
|
||||
},
|
||||
{
|
||||
"tool": "python",
|
||||
"model": "yolov8-pose",
|
||||
"priority": 3,
|
||||
"enabled": false,
|
||||
"command": {
|
||||
"executable": "/opt/homebrew/bin/python3.11",
|
||||
"script": "scripts/pose_processor_yolov8.py",
|
||||
"args": [
|
||||
"{video_path}",
|
||||
"{output_path}",
|
||||
"--model",
|
||||
"{model_file}"
|
||||
]
|
||||
},
|
||||
"parameters": {
|
||||
"model_file": "yolov8n-pose.pt"
|
||||
},
|
||||
"output_file": "{file_uuid}.pose.json",
|
||||
"timeout": 3600
|
||||
}
|
||||
],
|
||||
"default": {
|
||||
"tool": "rust",
|
||||
"model": null
|
||||
}
|
||||
},
|
||||
"face": {
|
||||
"implementations": [
|
||||
{
|
||||
"tool": "swift",
|
||||
"model": null,
|
||||
"priority": 0,
|
||||
"enabled": true,
|
||||
"command": {
|
||||
"executable": "scripts/swift_processors/.build/release/swift_face",
|
||||
"args": [
|
||||
"{video_path}",
|
||||
"--output",
|
||||
"{output_path}",
|
||||
"--uuid",
|
||||
"{file_uuid}"
|
||||
]
|
||||
},
|
||||
"parameters": {},
|
||||
"output_file": "{file_uuid}.face.json",
|
||||
"timeout": 3600
|
||||
},
|
||||
{
|
||||
"tool": "python",
|
||||
"model": "facenet",
|
||||
"priority": 2,
|
||||
"enabled": true,
|
||||
"command": {
|
||||
"executable": "/opt/homebrew/bin/python3.11",
|
||||
"script": "scripts/face_detector.py",
|
||||
"args": [
|
||||
"{video_path}",
|
||||
"{output_path}",
|
||||
"--uuid",
|
||||
"{file_uuid}",
|
||||
"--model",
|
||||
"{model_name}"
|
||||
]
|
||||
},
|
||||
"parameters": {
|
||||
"model_name": "facenet",
|
||||
"model_path": "/Users/accusys/models/facenet512.mlpackage"
|
||||
},
|
||||
"output_file": "{file_uuid}.face.json",
|
||||
"timeout": 3600
|
||||
}
|
||||
],
|
||||
"default": {
|
||||
"tool": "swift",
|
||||
"model": null
|
||||
}
|
||||
},
|
||||
"asr": {
|
||||
"implementations": [
|
||||
{
|
||||
"tool": "rust",
|
||||
"model": "whisper",
|
||||
"priority": 0,
|
||||
"enabled": false,
|
||||
"command": {
|
||||
"executable": "tools/cli/rust/target/release/rust_whisper",
|
||||
"args": [
|
||||
"{video_path}",
|
||||
"--output",
|
||||
"{output_path}",
|
||||
"--uuid",
|
||||
"{file_uuid}",
|
||||
"--model",
|
||||
"{model_size}"
|
||||
]
|
||||
},
|
||||
"parameters": {
|
||||
"model_size": "base"
|
||||
},
|
||||
"output_file": "{file_uuid}.asr.json",
|
||||
"timeout": 3600
|
||||
},
|
||||
{
|
||||
"tool": "python",
|
||||
"model": "whisper",
|
||||
"priority": 1,
|
||||
"enabled": true,
|
||||
"command": {
|
||||
"executable": "/opt/homebrew/bin/python3.11",
|
||||
"script": "scripts/asr_processor_simplified.py",
|
||||
"args": [
|
||||
"{video_path}",
|
||||
"{output_path}",
|
||||
"--model",
|
||||
"{model_size}"
|
||||
]
|
||||
},
|
||||
"parameters": {
|
||||
"model_size": "large-v3",
|
||||
"model_dir": "/Users/accusys/models/whisper-small-mlx"
|
||||
},
|
||||
"output_file": "{file_uuid}.asr.json",
|
||||
"timeout": 7200
|
||||
}
|
||||
],
|
||||
"default": {
|
||||
"tool": "python",
|
||||
"model": "whisper"
|
||||
}
|
||||
},
|
||||
"asrx": {
|
||||
"implementations": [
|
||||
{
|
||||
"tool": "swift",
|
||||
"model": null,
|
||||
"priority": 0,
|
||||
"enabled": false,
|
||||
"command": {
|
||||
"executable": "scripts/swift_processors/.build/release/asrx_swift",
|
||||
"args": [
|
||||
"{video_path}",
|
||||
"--output",
|
||||
"{output_path}",
|
||||
"--uuid",
|
||||
"{file_uuid}"
|
||||
]
|
||||
},
|
||||
"parameters": {},
|
||||
"output_file": "{file_uuid}.asrx.json",
|
||||
"timeout": 1800
|
||||
},
|
||||
{
|
||||
"tool": "python",
|
||||
"model": null,
|
||||
"priority": 0,
|
||||
"enabled": true,
|
||||
"command": {
|
||||
"executable": "/opt/homebrew/bin/python3.11",
|
||||
"script": "scripts/asrx_processor.py",
|
||||
"args": [
|
||||
"{video_path}",
|
||||
"{output_path}",
|
||||
"--uuid",
|
||||
"{file_uuid}"
|
||||
]
|
||||
},
|
||||
"parameters": {},
|
||||
"output_file": "{file_uuid}.asrx.json",
|
||||
"timeout": 1800
|
||||
}
|
||||
],
|
||||
"default": {
|
||||
"tool": "swift",
|
||||
"model": null
|
||||
}
|
||||
},
|
||||
"ocr": {
|
||||
"implementations": [
|
||||
{
|
||||
"tool": "swift",
|
||||
"model": null,
|
||||
"priority": 0,
|
||||
"enabled": true,
|
||||
"command": {
|
||||
"executable": "scripts/swift_processors/.build/release/swift_ocr",
|
||||
"args": [
|
||||
"{video_path}",
|
||||
"--output",
|
||||
"{output_path}",
|
||||
"--uuid",
|
||||
"{file_uuid}"
|
||||
]
|
||||
},
|
||||
"parameters": {},
|
||||
"output_file": "{file_uuid}.ocr.json",
|
||||
"timeout": 3600
|
||||
},
|
||||
{
|
||||
"tool": "python",
|
||||
"model": "tesseract",
|
||||
"priority": 2,
|
||||
"enabled": true,
|
||||
"command": {
|
||||
"executable": "/opt/homebrew/bin/python3.11",
|
||||
"script": "scripts/ocr_processor.py",
|
||||
"args": [
|
||||
"{video_path}",
|
||||
"{output_path}",
|
||||
"--uuid",
|
||||
"{file_uuid}"
|
||||
]
|
||||
},
|
||||
"parameters": {},
|
||||
"output_file": "{file_uuid}.ocr.json",
|
||||
"timeout": 3600
|
||||
}
|
||||
],
|
||||
"default": {
|
||||
"tool": "swift",
|
||||
"model": null
|
||||
}
|
||||
},
|
||||
"face_trace": {
|
||||
"implementations": [
|
||||
{
|
||||
"tool": "rust",
|
||||
"model": null,
|
||||
"priority": 0,
|
||||
"enabled": true,
|
||||
"command": {
|
||||
"executable": "tools/cli/rust/target/release/rust_store_traced_faces",
|
||||
"args": [
|
||||
"{file_uuid}",
|
||||
"--output-dir",
|
||||
"{output_dir}",
|
||||
"--min-trace-len",
|
||||
"{min_trace_len}",
|
||||
"--min-confidence",
|
||||
"{min_confidence}"
|
||||
]
|
||||
},
|
||||
"parameters": {
|
||||
"min_trace_len": 0,
|
||||
"min_confidence": 0.0
|
||||
},
|
||||
"output_file": "{file_uuid}.face_traced.json",
|
||||
"timeout": 600
|
||||
},
|
||||
{
|
||||
"tool": "python",
|
||||
"model": null,
|
||||
"priority": 1,
|
||||
"enabled": false,
|
||||
"command": {
|
||||
"executable": "/opt/homebrew/bin/python3.11",
|
||||
"script": "scripts/store_traced_faces.py",
|
||||
"args": [
|
||||
"--file-uuid",
|
||||
"{file_uuid}",
|
||||
"--face-json",
|
||||
"{face_json}"
|
||||
]
|
||||
},
|
||||
"parameters": {},
|
||||
"output_file": "{file_uuid}.face_traced.json",
|
||||
"timeout": 1200
|
||||
}
|
||||
],
|
||||
"default": {
|
||||
"tool": "rust",
|
||||
"model": null
|
||||
}
|
||||
},
|
||||
"scene_vlm_summary": {
|
||||
"implementations": [
|
||||
{
|
||||
"tool": "rust",
|
||||
"model": "gemma-4-12b-it",
|
||||
"priority": 0,
|
||||
"enabled": true,
|
||||
"command": {
|
||||
"executable": "tools/cli/rust/target/release/rust_scene_vlm",
|
||||
"args": [
|
||||
"--file-uuid",
|
||||
"{file_uuid}",
|
||||
"--output-dir",
|
||||
"{output_dir}",
|
||||
"--llm-url",
|
||||
"{llm_url}",
|
||||
"--max-tokens",
|
||||
"{max_tokens}"
|
||||
]
|
||||
},
|
||||
"parameters": {
|
||||
"llm_url": "http://localhost:8080/v1/chat/completions",
|
||||
"max_tokens": 900
|
||||
},
|
||||
"output_file": "{file_uuid}.scene_vlm.json",
|
||||
"timeout": 1800
|
||||
},
|
||||
{
|
||||
"tool": "python",
|
||||
"model": "gemma-4-12b-it",
|
||||
"priority": 1,
|
||||
"enabled": false,
|
||||
"command": {
|
||||
"executable": "/opt/homebrew/bin/python3.11",
|
||||
"script": "scripts/scene_vlm_summary.py",
|
||||
"args": [
|
||||
"--file-uuid",
|
||||
"{file_uuid}",
|
||||
"--output-dir",
|
||||
"{output_dir}",
|
||||
"--llm-url",
|
||||
"{llm_url}",
|
||||
"--max-tokens",
|
||||
"{max_tokens}"
|
||||
]
|
||||
},
|
||||
"parameters": {
|
||||
"llm_url": "http://localhost:8080/v1/chat/completions",
|
||||
"max_tokens": 900
|
||||
},
|
||||
"output_file": "{file_uuid}.scene_vlm.json",
|
||||
"timeout": 1800
|
||||
}
|
||||
],
|
||||
"default": {
|
||||
"tool": "python",
|
||||
"model": "gemma-4-12b-it"
|
||||
}
|
||||
},
|
||||
"tkg": {
|
||||
"implementations": [
|
||||
{
|
||||
"tool": "rust",
|
||||
"model": null,
|
||||
"priority": 0,
|
||||
"enabled": false,
|
||||
"command": {
|
||||
"executable": "tools/cli/rust/target/release/rust_tkg",
|
||||
"args": [
|
||||
"--file-uuid",
|
||||
"{file_uuid}",
|
||||
"--output-dir",
|
||||
"{output_dir}"
|
||||
]
|
||||
},
|
||||
"parameters": {},
|
||||
"output_file": "{file_uuid}.tkg.json",
|
||||
"timeout": 1800
|
||||
},
|
||||
{
|
||||
"tool": "python",
|
||||
"model": null,
|
||||
"priority": 1,
|
||||
"enabled": true,
|
||||
"command": {
|
||||
"executable": "/opt/homebrew/bin/python3.11",
|
||||
"script": "scripts/build_tkg.py",
|
||||
"args": [
|
||||
"--file-uuid",
|
||||
"{file_uuid}",
|
||||
"--output-dir",
|
||||
"{output_dir}"
|
||||
]
|
||||
},
|
||||
"parameters": {},
|
||||
"output_file": "{file_uuid}.tkg.json",
|
||||
"timeout": 1800
|
||||
}
|
||||
],
|
||||
"default": {
|
||||
"tool": "python",
|
||||
"model": null
|
||||
}
|
||||
},
|
||||
"cut": {
|
||||
"implementations": [
|
||||
{
|
||||
"tool": "rust",
|
||||
"model": null,
|
||||
"priority": 0,
|
||||
"enabled": true,
|
||||
"command": {
|
||||
"executable": "tools/cli/rust/target/release/rust_cut",
|
||||
"args": [
|
||||
"{video_path}",
|
||||
"--output",
|
||||
"{output_path}",
|
||||
"--uuid",
|
||||
"{file_uuid}",
|
||||
"--min-scene-duration",
|
||||
"{min_scene_duration}"
|
||||
]
|
||||
},
|
||||
"parameters": {
|
||||
"use_ffmpeg": true,
|
||||
"min_scene_duration": 0.5
|
||||
},
|
||||
"output_file": "{file_uuid}.cut.json",
|
||||
"timeout": 1800
|
||||
},
|
||||
{
|
||||
"tool": "python",
|
||||
"model": null,
|
||||
"priority": 1,
|
||||
"enabled": false,
|
||||
"command": {
|
||||
"executable": "/opt/homebrew/bin/python3.11",
|
||||
"script": "scripts/cut_detector.py",
|
||||
"args": [
|
||||
"{video_path}",
|
||||
"{output_path}",
|
||||
"--uuid",
|
||||
"{file_uuid}"
|
||||
]
|
||||
},
|
||||
"parameters": {},
|
||||
"output_file": "{file_uuid}.cut.json",
|
||||
"timeout": 1800
|
||||
}
|
||||
],
|
||||
"default": {
|
||||
"tool": "rust",
|
||||
"model": null
|
||||
}
|
||||
}
|
||||
},
|
||||
"variables": {
|
||||
"video_path": "Full path to video file",
|
||||
"output_path": "Full path to output JSON file",
|
||||
"output_dir": "Output directory (default: /Users/accusys/momentry/output)",
|
||||
"file_uuid": "Video file UUID",
|
||||
"face_json": "Path to face.json file"
|
||||
},
|
||||
"environment": {
|
||||
"MOMENTRY_OUTPUT_DIR": "/Users/accusys/momentry/output",
|
||||
"MOMENTRY_SCRIPTS_DIR": "tools/script/",
|
||||
"MOMENTRY_CLI_DIR": "tools/cli/",
|
||||
"MOMENTRY_PYTHON_PATH": "/opt/homebrew/bin/python3.11",
|
||||
"DATABASE_SCHEMA": "public",
|
||||
"DATABASE_URL": "postgres://accusys@localhost:5432/momentry",
|
||||
"REDIS_URL": "redis://:accusys@localhost:6379"
|
||||
},
|
||||
"models": {
|
||||
"whisper": {
|
||||
"description": "OpenAI Whisper ASR model",
|
||||
"sizes": [
|
||||
"tiny",
|
||||
"base",
|
||||
"small",
|
||||
"medium",
|
||||
"large",
|
||||
"large-v3"
|
||||
],
|
||||
"default_size": "large-v3",
|
||||
"model_dir": "/Users/accusys/models/whisper-small-mlx"
|
||||
},
|
||||
"mediapipe": {
|
||||
"description": "MediaPipe Pose estimation",
|
||||
"model_path": "/Users/accusys/models/mediapipe/pose_landmarker_heavy.task",
|
||||
"complexity_levels": [
|
||||
0,
|
||||
1,
|
||||
2
|
||||
],
|
||||
"default_complexity": 2
|
||||
},
|
||||
"facenet": {
|
||||
"description": "FaceNet 512D embedding model",
|
||||
"model_path": "/Users/accusys/models/facenet512.mlpackage"
|
||||
},
|
||||
"gemma-4-12b-it": {
|
||||
"description": "Gemma 4 12B instruct model for VLM/LLM",
|
||||
"model_path": "/Users/accusys/models/gemma-4-12b-it-Q4_K_M.gguf",
|
||||
"mmproj_path": "/Users/accusys/models/mmproj-F16.gguf",
|
||||
"llm_url": "http://localhost:8080/v1/chat/completions"
|
||||
},
|
||||
"embeddinggemma-300m": {
|
||||
"description": "Embedding Gemma 300M for vector embeddings",
|
||||
"model_path": "/Users/accusys/models/embeddinggemma-300M-Q8_0.gguf",
|
||||
"embedding_url": "http://localhost:11436/embed"
|
||||
}
|
||||
},
|
||||
"metadata": {
|
||||
"version": "3.0",
|
||||
"description": "Processor configuration - CLI tools (rust/swift) prioritized",
|
||||
"priority_policy": "rust/swift CLI (priority 0) > python (priority 1+)",
|
||||
"last_updated": "2026-09-27"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,603 @@
|
||||
{
|
||||
"processor_config": {
|
||||
"pose": {
|
||||
"implementations": [
|
||||
{
|
||||
"tool": "rust",
|
||||
"model": null,
|
||||
"priority": 1,
|
||||
"enabled": false,
|
||||
"command": {
|
||||
"executable": "tools/cli/rust/target/release/rust_pose",
|
||||
"args": [
|
||||
"--video",
|
||||
"{video_path}",
|
||||
"--output",
|
||||
"{output_path}",
|
||||
"--uuid",
|
||||
"{file_uuid}"
|
||||
]
|
||||
},
|
||||
"parameters": {},
|
||||
"output_file": "{file_uuid}.pose.json",
|
||||
"timeout": 1800
|
||||
},
|
||||
{
|
||||
"tool": "swift",
|
||||
"model": null,
|
||||
"priority": 0,
|
||||
"enabled": true,
|
||||
"command": {
|
||||
"executable": "scripts/swift_processors/.build/release/swift_pose",
|
||||
"args": [
|
||||
"{video_path}",
|
||||
"--output",
|
||||
"{output_path}",
|
||||
"--uuid",
|
||||
"{file_uuid}"
|
||||
]
|
||||
},
|
||||
"parameters": {},
|
||||
"output_file": "{file_uuid}.pose.json",
|
||||
"timeout": 1800
|
||||
},
|
||||
{
|
||||
"tool": "python",
|
||||
"model": "mediapipe",
|
||||
"priority": 2,
|
||||
"enabled": true,
|
||||
"command": {
|
||||
"executable": "/opt/homebrew/bin/python3.11",
|
||||
"script": "scripts/pose_processor_mediapipe.py",
|
||||
"args": [
|
||||
"{video_path}",
|
||||
"{output_path}",
|
||||
"--uuid",
|
||||
"{file_uuid}",
|
||||
"--model-complexity",
|
||||
"{model_complexity}"
|
||||
]
|
||||
},
|
||||
"parameters": {
|
||||
"model_complexity": 2,
|
||||
"model_path": "/Users/accusys/models/mediapipe/pose_landmarker_heavy.task"
|
||||
},
|
||||
"output_file": "{file_uuid}.pose.json",
|
||||
"timeout": 3600
|
||||
},
|
||||
{
|
||||
"tool": "python",
|
||||
"model": "yolov8-pose",
|
||||
"priority": 3,
|
||||
"enabled": false,
|
||||
"command": {
|
||||
"executable": "/opt/homebrew/bin/python3.11",
|
||||
"script": "scripts/pose_processor_yolov8.py",
|
||||
"args": [
|
||||
"{video_path}",
|
||||
"{output_path}",
|
||||
"--model",
|
||||
"{model_file}"
|
||||
]
|
||||
},
|
||||
"parameters": {
|
||||
"model_file": "yolov8n-pose.pt"
|
||||
},
|
||||
"output_file": "{file_uuid}.pose.json",
|
||||
"timeout": 3600
|
||||
}
|
||||
],
|
||||
"default": {
|
||||
"tool": "rust",
|
||||
"model": null
|
||||
}
|
||||
},
|
||||
"face": {
|
||||
"implementations": [
|
||||
{
|
||||
"tool": "swift",
|
||||
"model": null,
|
||||
"priority": 0,
|
||||
"enabled": true,
|
||||
"command": {
|
||||
"executable": "scripts/swift_processors/.build/release/swift_face",
|
||||
"args": [
|
||||
"{video_path}",
|
||||
"--output",
|
||||
"{output_path}",
|
||||
"--uuid",
|
||||
"{file_uuid}"
|
||||
]
|
||||
},
|
||||
"parameters": {},
|
||||
"output_file": "{file_uuid}.face.json",
|
||||
"timeout": 3600
|
||||
},
|
||||
{
|
||||
"tool": "python",
|
||||
"model": "facenet",
|
||||
"priority": 2,
|
||||
"enabled": true,
|
||||
"command": {
|
||||
"executable": "/opt/homebrew/bin/python3.11",
|
||||
"script": "scripts/face_detector.py",
|
||||
"args": [
|
||||
"{video_path}",
|
||||
"{output_path}",
|
||||
"--uuid",
|
||||
"{file_uuid}",
|
||||
"--model",
|
||||
"{model_name}"
|
||||
]
|
||||
},
|
||||
"parameters": {
|
||||
"model_name": "facenet",
|
||||
"model_path": "/Users/accusys/models/facenet512.mlpackage"
|
||||
},
|
||||
"output_file": "{file_uuid}.face.json",
|
||||
"timeout": 3600
|
||||
}
|
||||
],
|
||||
"default": {
|
||||
"tool": "swift",
|
||||
"model": null
|
||||
}
|
||||
},
|
||||
"asr": {
|
||||
"implementations": [
|
||||
{
|
||||
"tool": "rust",
|
||||
"model": "whisper",
|
||||
"priority": 0,
|
||||
"enabled": false,
|
||||
"command": {
|
||||
"executable": "tools/cli/rust/target/release/rust_whisper",
|
||||
"args": [
|
||||
"{video_path}",
|
||||
"--output",
|
||||
"{output_path}",
|
||||
"--uuid",
|
||||
"{file_uuid}",
|
||||
"--model",
|
||||
"{model_size}"
|
||||
]
|
||||
},
|
||||
"parameters": {
|
||||
"model_size": "base"
|
||||
},
|
||||
"output_file": "{file_uuid}.asr.json",
|
||||
"timeout": 3600
|
||||
},
|
||||
{
|
||||
"tool": "python",
|
||||
"model": "whisper",
|
||||
"priority": 1,
|
||||
"enabled": true,
|
||||
"command": {
|
||||
"executable": "/opt/homebrew/bin/python3.11",
|
||||
"script": "scripts/asr_processor_simplified.py",
|
||||
"args": [
|
||||
"{video_path}",
|
||||
"{output_path}",
|
||||
"--model",
|
||||
"{model_size}"
|
||||
]
|
||||
},
|
||||
"parameters": {
|
||||
"model_size": "large-v3",
|
||||
"model_dir": "/Users/accusys/models/whisper-small-mlx"
|
||||
},
|
||||
"output_file": "{file_uuid}.asr.json",
|
||||
"timeout": 7200
|
||||
}
|
||||
],
|
||||
"default": {
|
||||
"tool": "python",
|
||||
"model": "whisper"
|
||||
}
|
||||
},
|
||||
"asrx": {
|
||||
"implementations": [
|
||||
{
|
||||
"tool": "swift",
|
||||
"model": null,
|
||||
"priority": 0,
|
||||
"enabled": false,
|
||||
"command": {
|
||||
"executable": "scripts/swift_processors/.build/release/asrx_swift",
|
||||
"args": [
|
||||
"{video_path}",
|
||||
"--output",
|
||||
"{output_path}",
|
||||
"--uuid",
|
||||
"{file_uuid}"
|
||||
]
|
||||
},
|
||||
"parameters": {},
|
||||
"output_file": "{file_uuid}.asrx.json",
|
||||
"timeout": 1800
|
||||
},
|
||||
{
|
||||
"tool": "python",
|
||||
"model": null,
|
||||
"priority": 0,
|
||||
"enabled": true,
|
||||
"command": {
|
||||
"executable": "/opt/homebrew/bin/python3.11",
|
||||
"script": "scripts/asrx_processor.py",
|
||||
"args": [
|
||||
"{video_path}",
|
||||
"{output_path}",
|
||||
"--uuid",
|
||||
"{file_uuid}"
|
||||
]
|
||||
},
|
||||
"parameters": {},
|
||||
"output_file": "{file_uuid}.asrx.json",
|
||||
"timeout": 1800
|
||||
}
|
||||
],
|
||||
"default": {
|
||||
"tool": "swift",
|
||||
"model": null
|
||||
}
|
||||
},
|
||||
"ocr": {
|
||||
"implementations": [
|
||||
{
|
||||
"tool": "swift",
|
||||
"model": null,
|
||||
"priority": 0,
|
||||
"enabled": true,
|
||||
"command": {
|
||||
"executable": "scripts/swift_processors/.build/release/swift_ocr",
|
||||
"args": [
|
||||
"{video_path}",
|
||||
"--output",
|
||||
"{output_path}",
|
||||
"--uuid",
|
||||
"{file_uuid}"
|
||||
]
|
||||
},
|
||||
"parameters": {},
|
||||
"output_file": "{file_uuid}.ocr.json",
|
||||
"timeout": 3600
|
||||
},
|
||||
{
|
||||
"tool": "python",
|
||||
"model": "tesseract",
|
||||
"priority": 2,
|
||||
"enabled": true,
|
||||
"command": {
|
||||
"executable": "/opt/homebrew/bin/python3.11",
|
||||
"script": "scripts/ocr_processor.py",
|
||||
"args": [
|
||||
"{video_path}",
|
||||
"{output_path}",
|
||||
"--uuid",
|
||||
"{file_uuid}"
|
||||
]
|
||||
},
|
||||
"parameters": {},
|
||||
"output_file": "{file_uuid}.ocr.json",
|
||||
"timeout": 3600
|
||||
}
|
||||
],
|
||||
"default": {
|
||||
"tool": "swift",
|
||||
"model": null
|
||||
}
|
||||
},
|
||||
"face_trace": {
|
||||
"implementations": [
|
||||
{
|
||||
"tool": "rust",
|
||||
"model": null,
|
||||
"priority": 0,
|
||||
"enabled": true,
|
||||
"command": {
|
||||
"executable": "tools/cli/rust/target/release/rust_store_traced_faces",
|
||||
"args": [
|
||||
"{file_uuid}",
|
||||
"--output-dir",
|
||||
"{output_dir}",
|
||||
"--min-trace-len",
|
||||
"{min_trace_len}",
|
||||
"--min-confidence",
|
||||
"{min_confidence}"
|
||||
]
|
||||
},
|
||||
"parameters": {
|
||||
"min_trace_len": 0,
|
||||
"min_confidence": 0.0
|
||||
},
|
||||
"output_file": "{file_uuid}.face_traced.json",
|
||||
"timeout": 600
|
||||
},
|
||||
{
|
||||
"tool": "python",
|
||||
"model": null,
|
||||
"priority": 1,
|
||||
"enabled": false,
|
||||
"command": {
|
||||
"executable": "/opt/homebrew/bin/python3.11",
|
||||
"script": "scripts/store_traced_faces.py",
|
||||
"args": [
|
||||
"--file-uuid",
|
||||
"{file_uuid}",
|
||||
"--face-json",
|
||||
"{face_json}"
|
||||
]
|
||||
},
|
||||
"parameters": {},
|
||||
"output_file": "{file_uuid}.face_traced.json",
|
||||
"timeout": 1200
|
||||
}
|
||||
],
|
||||
"default": {
|
||||
"tool": "rust",
|
||||
"model": null
|
||||
}
|
||||
},
|
||||
"scene_vlm_summary": {
|
||||
"implementations": [
|
||||
{
|
||||
"tool": "rust",
|
||||
"model": "gemma-4-12b-it",
|
||||
"priority": 0,
|
||||
"enabled": true,
|
||||
"command": {
|
||||
"executable": "tools/cli/rust/target/release/rust_scene_vlm",
|
||||
"args": [
|
||||
"--file-uuid",
|
||||
"{file_uuid}",
|
||||
"--output-dir",
|
||||
"{output_dir}",
|
||||
"--llm-url",
|
||||
"{llm_url}",
|
||||
"--max-tokens",
|
||||
"{max_tokens}"
|
||||
]
|
||||
},
|
||||
"parameters": {
|
||||
"llm_url": "http://localhost:8080/v1/chat/completions",
|
||||
"max_tokens": 900
|
||||
},
|
||||
"output_file": "{file_uuid}.scene_vlm.json",
|
||||
"timeout": 1800
|
||||
},
|
||||
{
|
||||
"tool": "python",
|
||||
"model": "gemma-4-12b-it",
|
||||
"priority": 1,
|
||||
"enabled": false,
|
||||
"command": {
|
||||
"executable": "/opt/homebrew/bin/python3.11",
|
||||
"script": "scripts/scene_vlm_summary.py",
|
||||
"args": [
|
||||
"--file-uuid",
|
||||
"{file_uuid}",
|
||||
"--output-dir",
|
||||
"{output_dir}",
|
||||
"--llm-url",
|
||||
"{llm_url}",
|
||||
"--max-tokens",
|
||||
"{max_tokens}"
|
||||
]
|
||||
},
|
||||
"parameters": {
|
||||
"llm_url": "http://localhost:8080/v1/chat/completions",
|
||||
"max_tokens": 900
|
||||
},
|
||||
"output_file": "{file_uuid}.scene_vlm.json",
|
||||
"timeout": 1800
|
||||
}
|
||||
],
|
||||
"default": {
|
||||
"tool": "python",
|
||||
"model": "gemma-4-12b-it"
|
||||
}
|
||||
},
|
||||
"tkg": {
|
||||
"implementations": [
|
||||
{
|
||||
"tool": "rust",
|
||||
"model": null,
|
||||
"priority": 0,
|
||||
"enabled": false,
|
||||
"command": {
|
||||
"executable": "tools/cli/rust/target/release/rust_tkg",
|
||||
"args": [
|
||||
"--file-uuid",
|
||||
"{file_uuid}",
|
||||
"--output-dir",
|
||||
"{output_dir}"
|
||||
]
|
||||
},
|
||||
"parameters": {},
|
||||
"output_file": "{file_uuid}.tkg.json",
|
||||
"timeout": 1800
|
||||
},
|
||||
{
|
||||
"tool": "python",
|
||||
"model": null,
|
||||
"priority": 1,
|
||||
"enabled": true,
|
||||
"command": {
|
||||
"executable": "/opt/homebrew/bin/python3.11",
|
||||
"script": "scripts/build_tkg.py",
|
||||
"args": [
|
||||
"--file-uuid",
|
||||
"{file_uuid}",
|
||||
"--output-dir",
|
||||
"{output_dir}"
|
||||
]
|
||||
},
|
||||
"parameters": {},
|
||||
"output_file": "{file_uuid}.tkg.json",
|
||||
"timeout": 1800
|
||||
}
|
||||
],
|
||||
"default": {
|
||||
"tool": "python",
|
||||
"model": null
|
||||
}
|
||||
},
|
||||
"cut": {
|
||||
"implementations": [
|
||||
{
|
||||
"tool": "rust",
|
||||
"model": null,
|
||||
"priority": 0,
|
||||
"enabled": true,
|
||||
"command": {
|
||||
"executable": "tools/cli/rust/target/release/rust_cut",
|
||||
"args": [
|
||||
"{video_path}",
|
||||
"--output",
|
||||
"{output_path}",
|
||||
"--uuid",
|
||||
"{file_uuid}",
|
||||
"--min-scene-duration",
|
||||
"{min_scene_duration}"
|
||||
]
|
||||
},
|
||||
"parameters": {
|
||||
"use_ffmpeg": true,
|
||||
"min_scene_duration": 0.5
|
||||
},
|
||||
"output_file": "{file_uuid}.cut.json",
|
||||
"timeout": 1800
|
||||
},
|
||||
{
|
||||
"tool": "python",
|
||||
"model": null,
|
||||
"priority": 1,
|
||||
"enabled": false,
|
||||
"command": {
|
||||
"executable": "/opt/homebrew/bin/python3.11",
|
||||
"script": "scripts/cut_detector.py",
|
||||
"args": [
|
||||
"{video_path}",
|
||||
"{output_path}",
|
||||
"--uuid",
|
||||
"{file_uuid}"
|
||||
]
|
||||
},
|
||||
"parameters": {},
|
||||
"output_file": "{file_uuid}.cut.json",
|
||||
"timeout": 1800
|
||||
}
|
||||
],
|
||||
"default": {
|
||||
"tool": "rust",
|
||||
"model": null
|
||||
}
|
||||
}
|
||||
},
|
||||
"variables": {
|
||||
"video_path": "Full path to video file",
|
||||
"output_path": "Full path to output JSON file",
|
||||
"output_dir": "Output directory (default: /Users/accusys/momentry/output)",
|
||||
"file_uuid": "Video file UUID",
|
||||
"face_json": "Path to face.json file"
|
||||
},
|
||||
"environment": {
|
||||
"MOMENTRY_OUTPUT_DIR": "/Users/accusys/momentry/output",
|
||||
"MOMENTRY_SCRIPTS_DIR": "tools/script/",
|
||||
"MOMENTRY_CLI_DIR": "tools/cli/",
|
||||
"MOMENTRY_PYTHON_PATH": "/opt/homebrew/bin/python3.11",
|
||||
"DATABASE_SCHEMA": "public",
|
||||
"DATABASE_URL": "postgres://accusys@localhost:5432/momentry",
|
||||
"REDIS_URL": "redis://:accusys@localhost:6379"
|
||||
},
|
||||
"models": {
|
||||
"whisper": {
|
||||
"description": "OpenAI Whisper ASR model",
|
||||
"sizes": [
|
||||
"tiny",
|
||||
"base",
|
||||
"small",
|
||||
"medium",
|
||||
"large",
|
||||
"large-v3"
|
||||
],
|
||||
"default_size": "large-v3",
|
||||
"model_dir": "/Users/accusys/models/whisper-small-mlx"
|
||||
},
|
||||
"mediapipe": {
|
||||
"description": "MediaPipe Pose estimation",
|
||||
"model_path": "/Users/accusys/models/mediapipe/pose_landmarker_heavy.task",
|
||||
"complexity_levels": [
|
||||
0,
|
||||
1,
|
||||
2
|
||||
],
|
||||
"default_complexity": 2
|
||||
},
|
||||
"facenet": {
|
||||
"description": "FaceNet 512D embedding model",
|
||||
"model_path": "/Users/accusys/models/facenet512.mlpackage"
|
||||
},
|
||||
"gemma-4-12b-it": {
|
||||
"description": "Gemma 4 12B instruct model for VLM/LLM",
|
||||
"model_path": "/Users/accusys/models/gemma-4-12b-it-Q4_K_M.gguf",
|
||||
"mmproj_path": "/Users/accusys/models/mmproj-F16.gguf",
|
||||
"llm_url": "http://localhost:8080/v1/chat/completions"
|
||||
},
|
||||
"embeddinggemma-300m": {
|
||||
"description": "Embedding Gemma 300M for vector embeddings",
|
||||
"model_path": "/Users/accusys/models/embeddinggemma-300M-Q8_0.gguf",
|
||||
"embedding_url": "http://localhost:11436/embed"
|
||||
}
|
||||
},
|
||||
"metadata": {
|
||||
"version": "3.0",
|
||||
"description": "Processor configuration - CLI tools (rust/swift) prioritized",
|
||||
"priority_policy": "rust/swift CLI (priority 0) > python (priority 1+)",
|
||||
"last_updated": "2026-09-27"
|
||||
},
|
||||
"processors": {
|
||||
"FACE": {
|
||||
"tools": [
|
||||
{
|
||||
"name": "rust_face_processor",
|
||||
"priority": 0,
|
||||
"command": "tools/cli/rust/target/release/rust_face_processor",
|
||||
"args": [
|
||||
"--video",
|
||||
"{video_path}",
|
||||
"--output",
|
||||
"{output_path}",
|
||||
"--uuid",
|
||||
"{uuid}",
|
||||
"--sample-interval",
|
||||
"{sample_interval}",
|
||||
"--model",
|
||||
"models/facenet_vggface2.onnx"
|
||||
],
|
||||
"enabled": true
|
||||
},
|
||||
{
|
||||
"name": "python_face_processor",
|
||||
"priority": 1,
|
||||
"command": "python3",
|
||||
"args": [
|
||||
"scripts/face_processor.py",
|
||||
"{video_path}",
|
||||
"{output_path}",
|
||||
"--uuid",
|
||||
"{uuid}",
|
||||
"--sample-interval",
|
||||
"{sample_interval}",
|
||||
"--model",
|
||||
"models/facenet_vggface2.onnx",
|
||||
"--backend",
|
||||
"rust"
|
||||
],
|
||||
"enabled": true
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
# Production Environment Configuration
|
||||
# Used by: momentry binary on port 3002
|
||||
#
|
||||
# This file extracts production-specific variables from .env
|
||||
# Startup scripts must export these variables for Python subprocess inheritance
|
||||
#
|
||||
# ⚠️ PATH CONFIGURATION
|
||||
# All paths are relative to user home directory by default.
|
||||
# Set environment variables if you need custom paths.
|
||||
|
||||
# Server Configuration
|
||||
MOMENTRY_SERVER_PORT=3002
|
||||
MOMENTRY_REDIS_PREFIX=momentry:
|
||||
|
||||
# Database Schema
|
||||
DATABASE_SCHEMA=public
|
||||
|
||||
# Output Directory (CRITICAL for Python scripts)
|
||||
# Default: $HOME/momentry/output
|
||||
# Uncomment and set if you need a custom path:
|
||||
# MOMENTRY_OUTPUT_DIR=/custom/path/to/output
|
||||
|
||||
# Backup Directory
|
||||
# Default: $HOME/momentry/backup/momentry
|
||||
# Uncomment and set if you need a custom path:
|
||||
# MOMENTRY_BACKUP_DIR=/custom/path/to/backup
|
||||
|
||||
# Storage
|
||||
# Default: $HOME/momentry/var/sftpgo/data
|
||||
# Uncomment and set if you need a custom path:
|
||||
# MOMENTRY_STORAGE_ROOT=/custom/path/to/storage
|
||||
|
||||
# Python Path
|
||||
MOMENTRY_PYTHON_PATH=/opt/homebrew/bin/python3.11
|
||||
|
||||
# Logging
|
||||
RUST_LOG=debug
|
||||
MOMENTRY_LOG_LEVEL=debug
|
||||
|
||||
# Worker Configuration
|
||||
MOMENTRY_WORKER_ENABLED=true
|
||||
MOMENTRY_MAX_CONCURRENT=6
|
||||
MOMENTRY_POLL_INTERVAL=10
|
||||
MOMENTRY_WORKER_BATCH_SIZE=5
|
||||
MOMENTRY_FORCE_RETRY=true
|
||||
|
||||
# TMDb Integration
|
||||
TMDB_API_KEY=e9cde52197f6f8df4d9db99da93db1fb
|
||||
MOMENTRY_TMDB_PROBE_ENABLED=true
|
||||
@@ -0,0 +1,134 @@
|
||||
# Search Scoring Improvement: Score-based Merge for search/smart
|
||||
|
||||
## 發現者
|
||||
WordPress 前端專案(search-chat 頁面)
|
||||
|
||||
## 問題描述
|
||||
|
||||
### 症狀
|
||||
跨語言搜尋結果不一致:
|
||||
- 搜尋「槍」(中文)→ 回傳無關結果(如「讓T-shirt」、「靠直的後製神器」)
|
||||
- 搜尋 `gun`(英文)→ 回傳 "So where's your gun?"、"He has a gun"
|
||||
- 兩者應該找到相同語意主題的結果(武器相關片段),但實際回傳完全不同的集合
|
||||
|
||||
### 影響範圍
|
||||
`GET/POST /api/v1/search/smart` endpoint
|
||||
|
||||
## 根因分析
|
||||
|
||||
### 1. Qdrant 語意搜尋本身是正確的
|
||||
|
||||
直接查詢 Qdrant 驗證:
|
||||
|
||||
```
|
||||
cos(search_query: 槍, search_document: "So where's your gun?") = 0.6905
|
||||
cos(search_query: 槍, search_document: "這是一把槍") = 0.8256
|
||||
cos(search_query: gun, search_document: "So where's your gun?") = 0.7435
|
||||
```
|
||||
|
||||
**embedding model (EmbeddingGemma-300m) 的 cross-lingual 對齊正常。**
|
||||
|
||||
### 2. 問題在 RRF 合併邏輯
|
||||
|
||||
`search/smart` 用 **RRF (Reciprocal Rank Fusion)** 合併三組結果:
|
||||
|
||||
```rust
|
||||
let rrf_k = 60.0;
|
||||
// RRF 貢獻 = 1 / (60 + rank + 1)
|
||||
// Semantic rank 0: 貢獻 1/61 = 0.016
|
||||
// Keyword rank 0: 貢獻 1/61 = 0.016
|
||||
```
|
||||
|
||||
RRF 的權重只看**排名位置**,不看**實際相似度分數**。
|
||||
- cosine similarity = 0.69 的語意結果 → RRF 貢獻 0.016
|
||||
- ILIKE 隨便撈到的 keyword 匹配 → RRF 貢獻也是 0.016
|
||||
- 兩者在排序中權重完全相等
|
||||
|
||||
### 3. Keyword (ILIKE) 對跨語言有害
|
||||
|
||||
- `ILIKE '%槍%'` 只找到中文文字包含「槍」的 chunks
|
||||
- `ILIKE '%gun%'` 只找到英文文字包含 "gun" 的 chunks
|
||||
- 這兩組結果在語意上完全不同,卻透過 RRF 被提升到與語意結果同權重
|
||||
- 導致「槍」和 `gun` 的結果各自被自己的 ILIKE 匹配汙染
|
||||
|
||||
## 建議方案
|
||||
|
||||
### 核心原則
|
||||
向量高信心度時應該優先。
|
||||
|
||||
### 合併方式
|
||||
|
||||
將 RRF 改為 score-based merge,各來源分數定義:
|
||||
|
||||
| 來源 | 分數 | 說明 |
|
||||
|---|---|---|
|
||||
| **Semantic (Qdrant)** | `cosine_similarity` (0~1) | 原始 Qdrant 分數,不加權 |
|
||||
| **Identity** | 固定 `0.85` | 人名精準匹配,維持高度信心 |
|
||||
| **Keyword (ILIKE)** | 固定 `0.5` | 降權至低分,只作為語意找不到時的補底 |
|
||||
|
||||
最終分數 = `max(semantic, keyword, identity)`
|
||||
依最終分數降冪排序。
|
||||
|
||||
### 預期效果
|
||||
|
||||
| 情況 | 排序行為 |
|
||||
|---|---|
|
||||
| cosine > 0.5 的語意結果 | 排在 keyword 前面 ✅ |
|
||||
| cosine 在 0.3~0.5 | 與 keyword 穿插(都不太確定,合理) |
|
||||
| cosine < 0.3 | keyword 補底(語意沒找到,靠文字比對) |
|
||||
| 跨語言查詢(槍 vs gun) | 各自的高分 cross-lingual 結果優先呈現 ✅ |
|
||||
|
||||
### 不建議的方案
|
||||
|
||||
- **不要用 weight-based average**(如 `0.7*semantic + 0.3*keyword`):兩種模型的 score scale 不同,加權無法通用
|
||||
- **不要保留 RRF 只調 k 值**:k 值調再高也無法區分品質,只能稀釋影響
|
||||
|
||||
## 修改範圍
|
||||
|
||||
### 檔案
|
||||
`src/api/search.rs` 中的 `smart_search()` 函數
|
||||
|
||||
### 需要修改的區塊
|
||||
|
||||
1. **移除 RRF 常數**(`rrf_k = 60.0`)
|
||||
2. **Semantic 結果**:保留 Qdrant 回傳的 `score`(已在 `h.score as f64` 取得)
|
||||
3. **Keyword 結果**:固定設為 `0.5_f64`(忽略原本 `combined_score`)
|
||||
4. **Identity 結果**:固定設為 `0.85_f64`(忽略原本硬編碼的 `0.85` 但保留值)
|
||||
5. **排序邏輯**:改為 `max(semantic, keyword, identity)` 降冪
|
||||
6. **輸出 similarity**:改為回傳最終分數,而非 `rrf_score`
|
||||
|
||||
### 注意事項
|
||||
|
||||
- Qdrant 回傳的 `score` 是 `f32`,需 cast 為 `f64`
|
||||
- `keyword_results` 的 `combined_score` 實際上是 `1.0`(`search_bm25` 固定值),不應使用
|
||||
- 修改後需 **`cargo build --release`** 再重啟 server
|
||||
|
||||
## 驗證測試
|
||||
|
||||
### 手動測試
|
||||
|
||||
```bash
|
||||
# 1. 槍 vs gun 應該回傳相似主題
|
||||
curl -X POST 'http://localhost:3002/api/v1/search/smart' \
|
||||
-H 'X-API-Key: {KEY}' -H 'Content-Type: application/json' \
|
||||
-d '{"query":"槍","limit":10}'
|
||||
|
||||
curl -X POST 'http://localhost:3002/api/v1/search/smart' \
|
||||
-H 'X-API-Key: {KEY}' -H 'Content-Type: application/json' \
|
||||
-d '{"query":"gun","limit":10}'
|
||||
|
||||
# 2. 確認 similarity 值為實際 cosine (e.g. 0.6~0.9) 而非 RRF 值 (~0.016)
|
||||
```
|
||||
|
||||
### 預期結果
|
||||
|
||||
| Query | Top 結果應包含 |
|
||||
|---|---|
|
||||
| `槍` | gun 相關片段、「這是一把槍」、武器相關語意匹配 |
|
||||
| `gun` | 與 `槍` 主題一致(都是武器) |
|
||||
| `車` / `car` | 行車相關片段,非姓名含「車」的人物 |
|
||||
| `So where's your gun?` | 自身為 top-1(self-match cosine ≈ 1.0) |
|
||||
|
||||
## 附錄:前端處理
|
||||
|
||||
WordPress 側 (`snippet #37`) 已配合修正:`mode=semantic` 不再疊加 `search/universal`(ILIKE)結果,僅回傳 `search/smart` 的輸出。這部分無需 backend 配合。
|
||||
@@ -0,0 +1,598 @@
|
||||
# Pipeline Queue 集成分析报告
|
||||
|
||||
**日期**: 2026-10-11
|
||||
**分析范围**: Pipeline 处理流程 + Queue 系统集成
|
||||
**状态**: 分析报告
|
||||
|
||||
---
|
||||
|
||||
## 📊 当前 Pipeline 架构
|
||||
|
||||
### 1. Pipeline 端点
|
||||
|
||||
| 端点 | 功能 | 处理时间 | 状态 |
|
||||
|------|------|:---------:|:----:|
|
||||
| `/api/v1/file/:uuid/store-asrx` | 存储 ASRX chunks | ~1s | ✅ 同步 |
|
||||
| `/api/v1/file/:uuid/rule1` | Rule 1 切片 | ~2s | ✅ 同步 |
|
||||
| `/api/v1/file/:uuid/vectorize` | 向量化 | ~10-60s | ✅ 同步 |
|
||||
| `/api/v1/file/:uuid/phase1` | Phase 1 打包 | ~2s | ✅ 同步 |
|
||||
| `/api/v1/file/:uuid/complete` | 标记完成 | ~1s | ✅ 同步 |
|
||||
|
||||
---
|
||||
|
||||
### 2. 处理流程
|
||||
|
||||
```
|
||||
Video Registration
|
||||
↓
|
||||
ASR Processing (外部,~10-30min)
|
||||
↓
|
||||
ASRX Processing (~1-2min)
|
||||
↓
|
||||
store_asrx_chunks (同步,~1s)
|
||||
↓
|
||||
execute_rule1 (同步,~2s)
|
||||
↓
|
||||
vectorize_chunks (同步,~10-60s)
|
||||
↓
|
||||
phase1_pack (同步,~2s)
|
||||
↓
|
||||
mark_complete (同步,~1s)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 🚨 当前问题
|
||||
|
||||
### 1. 同步阻塞
|
||||
|
||||
**问题**:
|
||||
- 所有 pipeline 操作都是同步的
|
||||
- 长时间操作(如 vectorize)会阻塞 API
|
||||
- 用户等待时间长
|
||||
- 无法处理大量并发请求
|
||||
|
||||
**影响**:
|
||||
- API 响应时间慢(最长 60 秒)
|
||||
- 用户体验差
|
||||
- 系统吞吐量低
|
||||
|
||||
---
|
||||
|
||||
### 2. 无重试机制
|
||||
|
||||
**问题**:
|
||||
- 失败后无法自动重试
|
||||
- 需要手动重新执行
|
||||
- 无错误追踪
|
||||
|
||||
**影响**:
|
||||
- 运维成本高
|
||||
- 数据不一致
|
||||
|
||||
---
|
||||
|
||||
### 3. 无进度追踪
|
||||
|
||||
**问题**:
|
||||
- 无法追踪处理进度
|
||||
- 用户不知道任务状态
|
||||
|
||||
**影响**:
|
||||
- 用户体验差
|
||||
- 无法调试
|
||||
|
||||
---
|
||||
|
||||
## 🎯 Queue 集成方案
|
||||
|
||||
### 方案 1: 将 Pipeline 操作转为 Command Queue
|
||||
|
||||
**架构**:
|
||||
|
||||
```
|
||||
┌─────────────────────────────────────────────────┐
|
||||
│ Pipeline Command Queue │
|
||||
├─────────────────────────────────────────────────┤
|
||||
│ Queue: pipeline.commands (P1 - High) │
|
||||
│ │
|
||||
│ Commands: │
|
||||
│ ├─ StoreASRX (P1, ~1s) │
|
||||
│ ├─ ExecuteRule1 (P2, ~2s) │
|
||||
│ ├─ VectorizeChunks (P3, ~10-60s) │
|
||||
│ ├─ Phase1Pack (P2, ~2s) │
|
||||
│ └─ MarkComplete (P1, ~1s) │
|
||||
└─────────────────────────────────────────────────┘
|
||||
│
|
||||
▼
|
||||
┌─────────────────────────────────────────────────┐
|
||||
│ Pipeline Workers │
|
||||
├─────────────────────────────────────────────────┤
|
||||
│ Worker Pool: 3-5 workers │
|
||||
│ - 每个文件独立处理 │
|
||||
│ - 支持并行处理多个文件 │
|
||||
│ - 自动重试 (max 3) │
|
||||
└─────────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 方案 2: 具体实现
|
||||
|
||||
#### 2.1 Command Types
|
||||
|
||||
```typescript
|
||||
// 新增 Pipeline Command Types
|
||||
pub enum PipelineCommandType {
|
||||
StoreASRX,
|
||||
ExecuteRule1,
|
||||
VectorizeChunks,
|
||||
Phase1Pack,
|
||||
MarkComplete,
|
||||
ExecuteRule3, // 新增
|
||||
ReindexEmbeddings, // 新增
|
||||
}
|
||||
|
||||
impl PipelineCommandType {
|
||||
pub fn default_priority(&self) -> CommandPriority {
|
||||
match self {
|
||||
Self::MarkComplete => CommandPriority::Critical,
|
||||
Self::StoreASRX => CommandPriority::High,
|
||||
Self::ExecuteRule1 => CommandPriority::Normal,
|
||||
Self::VectorizeChunks => CommandPriority::Low, // 长时间任务
|
||||
Self::Phase1Pack => CommandPriority::Normal,
|
||||
Self::ExecuteRule3 => CommandPriority::Normal,
|
||||
Self::ReindexEmbeddings => CommandPriority::Low,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn estimated_duration(&self) -> std::time::Duration {
|
||||
match self {
|
||||
Self::StoreASRX => std::time::Duration::from_secs(5),
|
||||
Self::ExecuteRule1 => std::time::Duration::from_secs(10),
|
||||
Self::VectorizeChunks => std::time::Duration::from_secs(120), // 2 分钟
|
||||
Self::Phase1Pack => std::time::Duration::from_secs(10),
|
||||
Self::MarkComplete => std::time::Duration::from_secs(5),
|
||||
Self::ExecuteRule3 => std::time::Duration::from_secs(30),
|
||||
Self::ReindexEmbeddings => std::time::Duration::from_secs(120),
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
#### 2.2 Pipeline Service
|
||||
|
||||
```rust
|
||||
// src/core/command/pipeline/mod.rs
|
||||
|
||||
use crate::core::command::error::{CommandError, CommandResult};
|
||||
use crate::core::command::queue::CommandQueue;
|
||||
use crate::core::command::types::{Command, CommandType, CommandPriority};
|
||||
use serde_json::json;
|
||||
|
||||
pub struct PipelineService {
|
||||
queue: CommandQueue,
|
||||
}
|
||||
|
||||
impl PipelineService {
|
||||
pub fn new(db: sqlx::PgPool) -> Self {
|
||||
Self {
|
||||
queue: CommandQueue::new(db),
|
||||
}
|
||||
}
|
||||
|
||||
/// 提交 ASRX 存储命令
|
||||
pub async fn store_asrx(&self, file_uuid: &str) -> CommandResult<String> {
|
||||
let command = Command::new(
|
||||
CommandType::Internal {
|
||||
category: InternalCommandCategory::PipelineStoreASRX,
|
||||
},
|
||||
json!({
|
||||
"file_uuid": file_uuid,
|
||||
}),
|
||||
)
|
||||
.with_priority(CommandPriority::High);
|
||||
|
||||
self.queue.produce(
|
||||
"pipeline.commands",
|
||||
command,
|
||||
Default::default(),
|
||||
).await
|
||||
}
|
||||
|
||||
/// 提交 Rule1 执行命令
|
||||
pub async fn execute_rule1(&self, file_uuid: &str) -> CommandResult<String> {
|
||||
let command = Command::new(
|
||||
CommandType::Internal {
|
||||
category: InternalCommandCategory::PipelineExecuteRule1,
|
||||
},
|
||||
json!({
|
||||
"file_uuid": file_uuid,
|
||||
}),
|
||||
)
|
||||
.with_priority(CommandPriority::Normal);
|
||||
|
||||
self.queue.produce(
|
||||
"pipeline.commands",
|
||||
command,
|
||||
Default::default(),
|
||||
).await
|
||||
}
|
||||
|
||||
/// 提交向量化命令
|
||||
pub async fn vectorize_chunks(&self, file_uuid: &str) -> CommandResult<String> {
|
||||
let command = Command::new(
|
||||
CommandType::Internal {
|
||||
category: InternalCommandCategory::PipelineVectorize,
|
||||
},
|
||||
json!({
|
||||
"file_uuid": file_uuid,
|
||||
}),
|
||||
)
|
||||
.with_priority(CommandPriority::Low); // 长时间任务,低优先级
|
||||
|
||||
self.queue.produce(
|
||||
"pipeline.commands",
|
||||
command,
|
||||
Default::default(),
|
||||
).await
|
||||
}
|
||||
|
||||
/// 提交完整 pipeline 流程
|
||||
pub async fn submit_full_pipeline(&self, file_uuid: &str) -> CommandResult<Vec<String>> {
|
||||
let mut command_ids = Vec::new();
|
||||
|
||||
// 按顺序提交命令(后续会按 file_uuid 分组处理)
|
||||
command_ids.push(self.store_asrx(file_uuid).await?);
|
||||
command_ids.push(self.execute_rule1(file_uuid).await?);
|
||||
command_ids.push(self.vectorize_chunks(file_uuid).await?);
|
||||
command_ids.push(self.phase1_pack(file_uuid).await?);
|
||||
command_ids.push(self.mark_complete(file_uuid).await?);
|
||||
|
||||
Ok(command_ids)
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
#### 2.3 Pipeline Worker
|
||||
|
||||
```rust
|
||||
// src/core/command/pipeline/worker.rs
|
||||
|
||||
use super::*;
|
||||
use crate::core::pipeline;
|
||||
use crate::core::db::postgres_db::PostgresDb;
|
||||
use tracing::{debug, error, info};
|
||||
|
||||
pub struct PipelineWorker {
|
||||
worker_id: String,
|
||||
db: sqlx::PgPool,
|
||||
}
|
||||
|
||||
impl PipelineWorker {
|
||||
pub fn new(db: sqlx::PgPool) -> Self {
|
||||
Self {
|
||||
worker_id: uuid::Uuid::new_v4().to_string(),
|
||||
db,
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn start(&self) -> CommandResult<()> {
|
||||
info!(worker_id = %self.worker_id, "Pipeline worker started");
|
||||
|
||||
loop {
|
||||
match self.process_commands().await {
|
||||
Ok(count) => {
|
||||
debug!(count = count, "Processed pipeline commands");
|
||||
}
|
||||
Err(e) => {
|
||||
error!(error = ?e, "Error processing pipeline commands");
|
||||
}
|
||||
}
|
||||
|
||||
tokio::time::sleep(std::time::Duration::from_millis(100)).await;
|
||||
}
|
||||
}
|
||||
|
||||
async fn process_commands(&self) -> CommandResult<usize> {
|
||||
let queue = CommandQueue::new(self.db.clone());
|
||||
|
||||
let messages = queue.consume(
|
||||
"pipeline.commands",
|
||||
crate::core::command::types::ConsumeOptions {
|
||||
consumer_group: "pipeline_workers".to_string(),
|
||||
consumer_id: self.worker_id.clone(),
|
||||
max_messages: 5,
|
||||
..Default::default()
|
||||
},
|
||||
).await?;
|
||||
|
||||
let count = messages.len();
|
||||
|
||||
for message in messages {
|
||||
if let Err(e) = self.handle_command(&message).await {
|
||||
error!(error = ?e, "Pipeline command failed");
|
||||
// 记录错误但继续处理其他命令
|
||||
}
|
||||
}
|
||||
|
||||
Ok(count)
|
||||
}
|
||||
|
||||
async fn handle_command(&self, message: &crate::core::command::types::CommandMessage) -> CommandResult<()> {
|
||||
let command = &message.command;
|
||||
|
||||
// 提取 file_uuid
|
||||
let file_uuid = command.payload.get("file_uuid")
|
||||
.and_then(|v| v.as_str())
|
||||
.ok_or_else(|| CommandError::MissingPayload("file_uuid".to_string()))?;
|
||||
|
||||
info!(
|
||||
command_id = %message.message_id,
|
||||
file_uuid = %file_uuid,
|
||||
"Processing pipeline command"
|
||||
);
|
||||
|
||||
let start = std::time::Instant::now();
|
||||
|
||||
// 根据命令类型执行操作
|
||||
let result = match command.command_type {
|
||||
CommandType::Internal { category: InternalCommandCategory::PipelineStoreASRX } => {
|
||||
self.execute_store_asrx(file_uuid).await
|
||||
}
|
||||
CommandType::Internal { category: InternalCommandCategory::PipelineExecuteRule1 } => {
|
||||
self.execute_rule1(file_uuid).await
|
||||
}
|
||||
CommandType::Internal { category: InternalCommandCategory::PipelineVectorize } => {
|
||||
self.execute_vectorize(file_uuid).await
|
||||
}
|
||||
CommandType::Internal { category: InternalCommandCategory::PipelinePhase1Pack } => {
|
||||
self.execute_phase1(file_uuid).await
|
||||
}
|
||||
CommandType::Internal { category: InternalCommandCategory::PipelineMarkComplete } => {
|
||||
self.execute_mark_complete(file_uuid).await
|
||||
}
|
||||
_ => {
|
||||
Err(CommandError::InvalidCommandType(format!("{:?}", command.command_type)))
|
||||
}
|
||||
};
|
||||
|
||||
let duration_ms = start.elapsed().as_millis() as i64;
|
||||
|
||||
// 记录结果
|
||||
match result {
|
||||
Ok(_) => {
|
||||
info!(
|
||||
command_id = %message.message_id,
|
||||
file_uuid = %file_uuid,
|
||||
duration_ms = duration_ms,
|
||||
"Pipeline command completed"
|
||||
);
|
||||
}
|
||||
Err(ref e) => {
|
||||
error!(
|
||||
command_id = %message.message_id,
|
||||
file_uuid = %file_uuid,
|
||||
duration_ms = duration_ms,
|
||||
error = ?e,
|
||||
"Pipeline command failed"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
result
|
||||
}
|
||||
|
||||
async fn execute_store_asrx(&self, file_uuid: &str) -> CommandResult<()> {
|
||||
let db = PostgresDb::new(&crate::core::config::DATABASE_URL).await?;
|
||||
pipeline::store_asrx_chunks(&db, file_uuid).await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn execute_rule1(&self, file_uuid: &str) -> CommandResult<()> {
|
||||
let db = PostgresDb::new(&crate::core::config::DATABASE_URL).await?;
|
||||
pipeline::execute_rule1(&db, file_uuid).await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn execute_vectorize(&self, file_uuid: &str) -> CommandResult<()> {
|
||||
pipeline::vectorize_chunks(file_uuid).await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn execute_phase1(&self, file_uuid: &str) -> CommandResult<()> {
|
||||
pipeline::run_phase1(file_uuid).await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn execute_mark_complete(&self, file_uuid: &str) -> CommandResult<()> {
|
||||
let db = PostgresDb::new(&crate::core::config::DATABASE_URL).await?;
|
||||
pipeline::mark_complete(&db, file_uuid).await?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
#### 2.4 更新 API 端点
|
||||
|
||||
```rust
|
||||
// src/api/pipeline.rs (修改)
|
||||
|
||||
use crate::core::command::pipeline::PipelineService;
|
||||
|
||||
async fn handle_store_asrx(
|
||||
Path(uuid): Path<String>,
|
||||
Extension(pipeline_service): Extension<Arc<PipelineService>>,
|
||||
) -> Result<Json<Value>, (axum::http::StatusCode, Json<Value>)> {
|
||||
// 提交到队列,立即返回
|
||||
let command_id = pipeline_service.store_asrx(&uuid).await.map_err(|e| {
|
||||
tracing::error!("Submit store_asrx error: {}", e);
|
||||
(
|
||||
axum::http::StatusCode::INTERNAL_SERVER_ERROR,
|
||||
Json(json!({"error": e.to_string()})),
|
||||
)
|
||||
})?;
|
||||
|
||||
Ok(Json(json!({
|
||||
"success": true,
|
||||
"message": "ASRX store command queued",
|
||||
"file_uuid": uuid,
|
||||
"command_id": command_id,
|
||||
"status": "queued"
|
||||
})))
|
||||
}
|
||||
|
||||
async fn handle_vectorize(
|
||||
Path(uuid): Path<String>,
|
||||
Extension(pipeline_service): Extension<Arc<PipelineService>>,
|
||||
) -> Result<Json<Value>, (axum::http::StatusCode, Json<Value>)> {
|
||||
// 提交到队列,立即返回
|
||||
let command_id = pipeline_service.vectorize_chunks(&uuid).await.map_err(|e| {
|
||||
tracing::error!("Submit vectorize error: {}", e);
|
||||
(
|
||||
axum::http::StatusCode::INTERNAL_SERVER_ERROR,
|
||||
Json(json!({"error": e.to_string()})),
|
||||
)
|
||||
})?;
|
||||
|
||||
Ok(Json(json!({
|
||||
"success": true,
|
||||
"message": "Vectorization command queued (long-running task)",
|
||||
"file_uuid": uuid,
|
||||
"command_id": command_id,
|
||||
"status": "queued",
|
||||
"estimated_duration_sec": 120
|
||||
})))
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 📊 对比分析
|
||||
|
||||
### 性能对比
|
||||
|
||||
| 操作 | 之前(同步) | 之后(队列) | 改进 |
|
||||
|------|:-----------:|:-----------:|:----:|
|
||||
| StoreASRX | ~1s | ~50ms | 20x |
|
||||
| Rule1 | ~2s | ~50ms | 40x |
|
||||
| Vectorize | ~60s | ~50ms | 1200x |
|
||||
| Phase1 | ~2s | ~50ms | 40x |
|
||||
| Complete | ~1s | ~50ms | 20x |
|
||||
|
||||
---
|
||||
|
||||
### 用户体验对比
|
||||
|
||||
**之前**:
|
||||
```
|
||||
POST /api/v1/file/xxx/vectorize
|
||||
↓
|
||||
等待 60 秒
|
||||
↓
|
||||
返回结果
|
||||
```
|
||||
|
||||
**之后**:
|
||||
```
|
||||
POST /api/v1/file/xxx/vectorize
|
||||
↓
|
||||
立即返回(50ms)
|
||||
↓
|
||||
后台处理(120s)
|
||||
↓
|
||||
用户可继续其他操作
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 🎯 实施计划
|
||||
|
||||
### Phase 1: 基础队列集成(2 天)
|
||||
|
||||
- [ ] 创建 `InternalCommandCategory` 枚举(Pipeline 相关)
|
||||
- [ ] 实现 `PipelineService`
|
||||
- [ ] 实现 `PipelineWorker`
|
||||
- [ ] 修改 API 端点
|
||||
- [ ] 测试单个命令
|
||||
|
||||
---
|
||||
|
||||
### Phase 2: 完整流程(2 天)
|
||||
|
||||
- [ ] 实现命令链式调用
|
||||
- [ ] 添加进度追踪
|
||||
- [ ] 添加错误通知
|
||||
- [ ] 测试完整 pipeline
|
||||
|
||||
---
|
||||
|
||||
### Phase 3: 优化(1 天)
|
||||
|
||||
- [ ] 性能测试
|
||||
- [ ] 并发测试
|
||||
- [ ] 监控配置
|
||||
- [ ] 文档更新
|
||||
|
||||
---
|
||||
|
||||
## 📝 数据库更新
|
||||
|
||||
### 新增 InternalCommandCategory
|
||||
|
||||
```sql
|
||||
-- 更新 queue_routes 表
|
||||
INSERT INTO queue_routes (command_type, command_category, queue_name, handler, priority, billing_required) VALUES
|
||||
('internal', 'pipeline_store_asrx', 'pipeline.commands', 'pipeline_worker', 1, false),
|
||||
('internal', 'pipeline_execute_rule1', 'pipeline.commands', 'pipeline_worker', 2, false),
|
||||
('internal', 'pipeline_vectorize', 'pipeline.commands', 'pipeline_worker', 3, false),
|
||||
('internal', 'pipeline_phase1_pack', 'pipeline.commands', 'pipeline_worker', 2, false),
|
||||
('internal', 'pipeline_mark_complete', 'pipeline.commands', 'pipeline_worker', 1, false),
|
||||
('internal', 'pipeline_execute_rule3', 'pipeline.commands', 'pipeline_worker', 2, false),
|
||||
('internal', 'pipeline_reindex_embeddings', 'pipeline.commands', 'pipeline_worker', 3, false)
|
||||
ON CONFLICT (command_type, command_category) DO NOTHING;
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## ✅ 预期效果
|
||||
|
||||
### 系统吞吐量
|
||||
|
||||
- **之前**: 1-2 个文件/分钟(同步)
|
||||
- **之后**: 10-20 个文件/分钟(并行)
|
||||
|
||||
---
|
||||
|
||||
### API 响应时间
|
||||
|
||||
- **之前**: 平均 10-60 秒
|
||||
- **之后**: 平均 50 毫秒
|
||||
|
||||
---
|
||||
|
||||
### 用户体验
|
||||
|
||||
- ✅ 立即反馈
|
||||
- ✅ 后台处理
|
||||
- ✅ 进度可追踪
|
||||
- ✅ 错误可恢复
|
||||
|
||||
---
|
||||
|
||||
## 🚀 下一步
|
||||
|
||||
1. **立即实施**: Phase 1 - 基础队列集成
|
||||
2. **测试验证**: 确保所有 pipeline 命令正常工作
|
||||
3. **性能测试**: 验证吞吐量提升
|
||||
4. **监控配置**: 添加 Prometheus 指标
|
||||
|
||||
---
|
||||
|
||||
**Pipeline Queue 集成分析完成!可立即开始实施。**
|
||||
@@ -1,5 +1,5 @@
|
||||
<!-- module: lookup -->
|
||||
<!-- description: File lookup by name and unregistration -->
|
||||
<!-- description: File listing, lookup by name, file detail, faces, identities, JSON download, unregistration -->
|
||||
<!-- depends: 01_auth, 03_register -->
|
||||
|
||||
## File Lookup
|
||||
@@ -60,6 +60,285 @@ curl -s "$API/api/v1/files/lookup?file_name=charade" \
|
||||
|
||||
---
|
||||
|
||||
---
|
||||
|
||||
## File Listing
|
||||
|
||||
### `GET /api/v1/files`
|
||||
|
||||
**Auth**: Required
|
||||
**Scope**: system-level
|
||||
|
||||
List all registered files with pagination. Optionally filter by status or fetch a specific file by UUID.
|
||||
|
||||
#### Query Parameters
|
||||
|
||||
| Field | Type | Required | Default | Description |
|
||||
|-------|------|----------|---------|-------------|
|
||||
| `page` | integer | No | 1 | Page number |
|
||||
| `page_size` | integer | No | 20 | Items per page |
|
||||
| `status` | string | No | — | Filter by status: `registered`, `processing`, `completed`, `failed`, `indexed`, `checked_out` |
|
||||
| `file_uuid` | string | No | — | Fetch a specific file (returns as single-item list) |
|
||||
|
||||
#### Example
|
||||
|
||||
```bash
|
||||
# List all files (paginated)
|
||||
curl -s "$API/api/v1/files?page=1&page_size=10" \
|
||||
-H "X-API-Key: $KEY"
|
||||
|
||||
# Filter by status
|
||||
curl -s "$API/api/v1/files?status=completed" \
|
||||
-H "X-API-Key: $KEY"
|
||||
|
||||
# Fetch specific file
|
||||
curl -s "$API/api/v1/files?file_uuid=$FILE_UUID" \
|
||||
-H "X-API-Key: $KEY"
|
||||
```
|
||||
|
||||
#### Response (200)
|
||||
|
||||
```json
|
||||
{
|
||||
"success": true,
|
||||
"total": 42,
|
||||
"page": 1,
|
||||
"page_size": 10,
|
||||
"data": [
|
||||
{
|
||||
"file_uuid": "d3f9ae8e471a1fc4d47022c66091b920",
|
||||
"file_name": "video.mp4",
|
||||
"file_path": "/path/to/video.mp4",
|
||||
"status": "completed"
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
| Field | Type | Description |
|
||||
|-------|------|-------------|
|
||||
| `success` | boolean | Always true on 200 |
|
||||
| `total` | integer | Total file count |
|
||||
| `page` | integer | Current page |
|
||||
| `page_size` | integer | Items per page |
|
||||
| `data` | array | Array of file items |
|
||||
| `data[].file_uuid` | string | 32-char hex UUID |
|
||||
| `data[].file_name` | string | Registered file name |
|
||||
| `data[].file_path` | string | Full filesystem path |
|
||||
| `data[].status` | string | Processing status |
|
||||
|
||||
---
|
||||
|
||||
### `GET /api/v1/file/:file_uuid`
|
||||
|
||||
**Auth**: Required
|
||||
**Scope**: file-level
|
||||
|
||||
Get detailed info for a specific registered file including metadata, duration, FPS, and probe data.
|
||||
|
||||
#### Example
|
||||
|
||||
```bash
|
||||
curl -s "$API/api/v1/file/$FILE_UUID" \
|
||||
-H "X-API-Key: $KEY"
|
||||
```
|
||||
|
||||
#### Response (200)
|
||||
|
||||
```json
|
||||
{
|
||||
"success": true,
|
||||
"file_uuid": "d3f9ae8e471a1fc4d47022c66091b920",
|
||||
"file_name": "video.mp4",
|
||||
"file_path": "/path/to/video.mp4",
|
||||
"status": "completed",
|
||||
"duration": 120.5,
|
||||
"fps": 24.0,
|
||||
"metadata": {
|
||||
"format": {"duration": "120.5", "size": "794863677"},
|
||||
"streams": [{"codec_name": "h264", "width": 1920, "height": 1080}]
|
||||
},
|
||||
"created_at": "2026-05-16T12:00:00Z"
|
||||
}
|
||||
```
|
||||
|
||||
| Field | Type | Description |
|
||||
|-------|------|-------------|
|
||||
| `success` | boolean | Always true on 200 |
|
||||
| `file_uuid` | string | 32-char hex UUID |
|
||||
| `file_name` | string | Registered file name |
|
||||
| `file_path` | string | Full filesystem path |
|
||||
| `status` | string | Processing status |
|
||||
| `duration` | float | Duration in seconds |
|
||||
| `fps` | float | Frames per second |
|
||||
| `metadata` | object | Full ffprobe metadata (probe.json) |
|
||||
| `created_at` | string | Registration timestamp (ISO 8601) |
|
||||
|
||||
#### Error Codes
|
||||
|
||||
| HTTP | When |
|
||||
|------|------|
|
||||
| `404` | File UUID not found |
|
||||
|
||||
---
|
||||
|
||||
### `GET /api/v1/file/:file_uuid/identities`
|
||||
|
||||
**Auth**: Required
|
||||
**Scope**: file-level
|
||||
|
||||
Get all identities present in a specific file with pagination.
|
||||
|
||||
#### Query Parameters
|
||||
|
||||
| Field | Type | Required | Default | Description |
|
||||
|-------|------|----------|---------|-------------|
|
||||
| `page` | integer | No | 1 | Page number |
|
||||
| `page_size` | integer | No | 20 | Items per page |
|
||||
|
||||
#### Example
|
||||
|
||||
```bash
|
||||
curl -s "$API/api/v1/file/$FILE_UUID/identities?page=1&page_size=50" \
|
||||
-H "X-API-Key: $KEY"
|
||||
```
|
||||
|
||||
#### Response (200)
|
||||
|
||||
```json
|
||||
{
|
||||
"success": true,
|
||||
"file_uuid": "d3f9ae8e471a1fc4d47022c66091b920",
|
||||
"fps": 24.0,
|
||||
"total": 5,
|
||||
"page": 1,
|
||||
"page_size": 20,
|
||||
"data": [
|
||||
{
|
||||
"identity_id": 1,
|
||||
"identity_uuid": "a9a90105-6d6b-46ff-92da-0c3c1a57dff4",
|
||||
"name": "Audrey Hepburn",
|
||||
"metadata": {"source": "tmdb", "tmdb_id": 1234},
|
||||
"face_count": 142,
|
||||
"speaker_count": 8,
|
||||
"start_frame": 100,
|
||||
"end_frame": 5000,
|
||||
"start_time": 4.17,
|
||||
"end_time": 208.33,
|
||||
"confidence": 0.87
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
| Field | Type | Description |
|
||||
|-------|------|-------------|
|
||||
| `data[].identity_id` | integer | Database identity ID |
|
||||
| `data[].identity_uuid` | string/null | Global identity UUID (null if unbound) |
|
||||
| `data[].name` | string | Identity name |
|
||||
| `data[].metadata` | object | Source metadata (TMDb, etc.) |
|
||||
| `data[].face_count` | integer/null | Number of face detections |
|
||||
| `data[].speaker_count` | integer/null | Number of speaker segments |
|
||||
| `data[].start_frame` | integer/null | First appearance frame |
|
||||
| `data[].end_frame` | integer/null | Last appearance frame |
|
||||
| `data[].start_time` | float/null | First appearance time (seconds) |
|
||||
| `data[].end_time` | float/null | Last appearance time (seconds) |
|
||||
| `data[].confidence` | float/null | Average detection confidence |
|
||||
|
||||
---
|
||||
|
||||
### `GET /api/v1/file/:file_uuid/faces`
|
||||
|
||||
**Auth**: Required
|
||||
**Scope**: file-level
|
||||
|
||||
List all face detections in a specific file with pagination.
|
||||
|
||||
#### Query Parameters
|
||||
|
||||
| Field | Type | Required | Default | Description |
|
||||
|-------|------|----------|---------|-------------|
|
||||
| `page` | integer | No | 1 | Page number |
|
||||
| `page_size` | integer | No | 50 | Items per page |
|
||||
|
||||
#### Example
|
||||
|
||||
```bash
|
||||
curl -s "$API/api/v1/file/$FILE_UUID/faces?page=1&page_size=100" \
|
||||
-H "X-API-Key: $KEY"
|
||||
```
|
||||
|
||||
#### Response (200)
|
||||
|
||||
```json
|
||||
{
|
||||
"success": true,
|
||||
"file_uuid": "d3f9ae8e471a1fc4d47022c66091b920",
|
||||
"total": 1420,
|
||||
"page": 1,
|
||||
"page_size": 50,
|
||||
"data": [
|
||||
{
|
||||
"face_id": "face_100",
|
||||
"frame_number": 1200,
|
||||
"timestamp": 50.0,
|
||||
"bbox": [100, 50, 300, 400],
|
||||
"confidence": 0.95,
|
||||
"identity_id": 1,
|
||||
"identity_uuid": "a9a90105-6d6b-46ff-92da-0c3c1a57dff4",
|
||||
"trace_id": 2
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
| Field | Type | Description |
|
||||
|-------|------|-------------|
|
||||
| `data[].face_id` | string | Face detection ID |
|
||||
| `data[].frame_number` | integer | Frame number in video |
|
||||
| `data[].timestamp` | float | Timestamp in seconds |
|
||||
| `data[].bbox` | array | Bounding box `[x1, y1, x2, y2]` |
|
||||
| `data[].confidence` | float | Detection confidence |
|
||||
| `data[].identity_id` | integer/null | Bound identity ID (null if unbound) |
|
||||
| `data[].identity_uuid` | string/null | Bound identity UUID (null if unbound) |
|
||||
| `data[].trace_id` | integer/null | Face trace ID (null if not traced) |
|
||||
|
||||
---
|
||||
|
||||
### `POST /api/v1/file/:file_uuid/json/:processor`
|
||||
|
||||
**Auth**: Required
|
||||
**Scope**: file-level
|
||||
|
||||
Download raw JSON output for a specific processor.
|
||||
|
||||
#### Path Parameters
|
||||
|
||||
| Field | Type | Required | Description |
|
||||
|-------|------|----------|-------------|
|
||||
| `file_uuid` | string | Yes | File UUID |
|
||||
| `processor` | string | Yes | Processor name: `cut`, `asrx`, `yolo`, `ocr`, `face`, `pose`, `story`, etc. |
|
||||
|
||||
#### Example
|
||||
|
||||
```bash
|
||||
curl -s -X POST "$API/api/v1/file/$FILE_UUID/json/face" \
|
||||
-H "X-API-Key: $KEY" | jq '.frames | length'
|
||||
```
|
||||
|
||||
#### Response (200)
|
||||
|
||||
Returns the raw JSON output of the specified processor. Structure varies by processor type.
|
||||
|
||||
#### Error Codes
|
||||
|
||||
| HTTP | When |
|
||||
|------|------|
|
||||
| `404` | JSON file not found |
|
||||
| `500` | Failed to parse JSON |
|
||||
|
||||
---
|
||||
|
||||
## Unregister
|
||||
|
||||
### `POST /api/v1/unregister`
|
||||
@@ -138,4 +417,4 @@ curl -s -X POST "$API/api/v1/unregister" \
|
||||
| `401` | Missing or invalid API key |
|
||||
|
||||
---
|
||||
*Updated: 2026-05-19 12:49:24*
|
||||
*Updated: 2026-06-20 — Added file listing, file detail, file identities, file faces, and JSON download endpoints*
|
||||
|
||||
@@ -51,8 +51,8 @@ curl -s -X POST "$API/api/v1/file/$FILE_UUID/process" \
|
||||
| `success` | boolean | Always true on 200 |
|
||||
| `job_id` | integer | Monitor job ID (for job tracking) |
|
||||
| `file_uuid` | string | 32-char hex UUID of the file |
|
||||
| `status` | string | `"processing"` |
|
||||
| `pids` | integer[] | Process IDs of started processors |
|
||||
| `status` | string | `"queued"` — file enters the FIFO queue |
|
||||
| `pids` | integer[] | Process IDs of started processors (empty for queued) |
|
||||
| `message` | string | Human-readable status |
|
||||
|
||||
#### Error Responses
|
||||
@@ -127,13 +127,15 @@ curl -s "$API/api/v1/file/$FILE_UUID/probe" -H "X-API-Key: $KEY"
|
||||
|
||||
---
|
||||
|
||||
### `GET /api/v1/progress/:file_uuid`
|
||||
### `POST /api/v1/progress/:file_uuid`
|
||||
|
||||
**Auth**: Required
|
||||
**Scope**: file-level
|
||||
|
||||
Get real-time processing progress for a file via Redis pub/sub. Includes per-processor status, current/total frames, ETA, and system resource stats.
|
||||
|
||||
**Note**: This endpoint uses **POST** method, not GET. The progress data is stored in Redis as a hash, and POST is used to retrieve the latest state.
|
||||
|
||||
#### Pipeline Order
|
||||
|
||||
| Order | Processor | Dependencies | Description |
|
||||
@@ -143,18 +145,37 @@ Get real-time processing progress for a file via Redis pub/sub. Includes per-pro
|
||||
| 3 | `asrx` | asr | Speaker diarization |
|
||||
| 4 | `yolo` | — | Object detection |
|
||||
| 5 | `ocr` | — | Text recognition |
|
||||
| 6 | `face` | — | Face detection & embedding |
|
||||
| 7 | `pose` | — | Pose estimation |
|
||||
| 8 | `visual_chunk` | yolo | Visual scene chunks |
|
||||
| 9 | `story` | asr, asrx, cut, yolo, face | Scene summaries (template) |
|
||||
| 10 | `5w1h` | story | 5W1H analysis (Gemma4 LLM) |
|
||||
| 6 | `face` | — | Face detection & embedding (8Hz sampling) |
|
||||
| 7 | `face_trace` | face | Face tracking (IoU + embedding, assigns trace_id) |
|
||||
| 8 | `pose` | face_trace | Pose expansion from face traces, inherits trace_id |
|
||||
| 9 | `appearance` | pose | Appearance expansion from pose traces, inherits trace_id |
|
||||
|
||||
**Key Concepts:**
|
||||
- **Face** = Identity anchor (who is this person?) — requires high-quality embedding
|
||||
- **Pose** = Tracking (where is this person?) — extends tracking when face is occluded
|
||||
- **Appearance** = Tracking (what do they look like?) — extends tracking when pose is occluded
|
||||
|
||||
**Trace ID Inheritance:**
|
||||
```
|
||||
Face trace (identity anchor)
|
||||
↓ inherits trace_id
|
||||
Pose expansion (tracking continuity)
|
||||
↓ inherits trace_id
|
||||
Appearance expansion (tracking continuity)
|
||||
```
|
||||
|
||||
**Frame Count Relationship:**
|
||||
```
|
||||
face frames ≤ pose frames ≤ appearance frames
|
||||
```
|
||||
(Each level expands outward from the previous level's traces)
|
||||
|
||||
All processors except `story` and `5w1h` run concurrently when their dependencies are met. Story and 5W1H run sequentially after their prerequisites.
|
||||
|
||||
#### Example
|
||||
|
||||
```bash
|
||||
curl -s "$API/api/v1/progress/$FILE_UUID" -H "X-API-Key: $KEY" | jq '{overall_progress, processors: [.processors[] | {processor_type, status}]}'
|
||||
curl -s -X POST "$API/api/v1/progress/$FILE_UUID" -H "X-API-Key: $KEY" | jq '{overall_progress, processors: [.processors[] | {name, status}]}'
|
||||
```
|
||||
|
||||
#### Response (200)
|
||||
@@ -235,5 +256,273 @@ curl -s "$API/api/v1/jobs" -H "X-API-Key: $KEY" | jq '{count, jobs: [.jobs[] | {
|
||||
| `page` | integer | Current page number |
|
||||
| `page_size` | integer | Jobs per page |
|
||||
|
||||
### `GET /api/v1/job/:uuid`
|
||||
|
||||
**Auth**: Required
|
||||
**Scope**: file-level
|
||||
|
||||
Get detailed information about a specific processing job, including its queue position.
|
||||
|
||||
#### Response (200)
|
||||
|
||||
```json
|
||||
{
|
||||
"id": 51,
|
||||
"uuid": "c36f35685177c981aa139b66bbbccc5b",
|
||||
"status": "queued",
|
||||
"current_processor": null,
|
||||
"progress_current": 0,
|
||||
"progress_total": 0,
|
||||
"processors": [],
|
||||
"created_at": "2026-06-22 23:08:48.497018",
|
||||
"started_at": null,
|
||||
"updated_at": null,
|
||||
"queue_position": 3
|
||||
}
|
||||
```
|
||||
|
||||
| Field | Type | Description |
|
||||
|-------|------|-------------|
|
||||
| `id` | integer | Monitor job ID |
|
||||
| `uuid` | string | File UUID |
|
||||
| `status` | string | `"pending"`, `"queued"`, `"running"`, `"completed"`, `"failed"` |
|
||||
| `current_processor` | string | Currently active processor, or null |
|
||||
| `progress_current` | integer | Current progress count |
|
||||
| `progress_total` | integer | Total progress count |
|
||||
| `processors` | array | Processor list |
|
||||
| `created_at` | string | Job creation timestamp |
|
||||
| `started_at` | string | Processing start timestamp, or null |
|
||||
| `updated_at` | string | Last update timestamp, or null |
|
||||
| `queue_position` | integer | Position in FIFO queue (null if not pending/queued) |
|
||||
|
||||
---
|
||||
*Updated: 2026-05-19 12:49:24*
|
||||
|
||||
### Status Lifecycle
|
||||
|
||||
```
|
||||
register ──→ pending
|
||||
│
|
||||
trigger (POST /process)
|
||||
│
|
||||
queued ←── queue_position counts jobs ahead
|
||||
│
|
||||
worker picks up
|
||||
│
|
||||
processing
|
||||
│
|
||||
┌────────┴────────┐
|
||||
▼ ▼
|
||||
completed failed
|
||||
│
|
||||
checkin ──→ indexed
|
||||
checkout ──→ checked_out
|
||||
```
|
||||
|
||||
| Status | Meaning |
|
||||
|--------|---------|
|
||||
| `pending` | File registered, not yet triggered |
|
||||
| `queued` | Triggered, waiting for worker in FIFO queue |
|
||||
| `processing` | Worker actively processing |
|
||||
| `completed` | All processors finished successfully |
|
||||
| `failed` | One or more essential processors failed |
|
||||
| `indexed` | Post-processing checkin complete |
|
||||
| `checked_out` | User checked out the file |
|
||||
|
||||
Queue order is FIFO (`created_at ASC`). The `GET /api/v1/job/:uuid` endpoint returns `queue_position` showing how many jobs are ahead.
|
||||
|
||||
### Frontend Status Mapping
|
||||
|
||||
When displaying file status in the frontend list (e.g. after `GET /api/v1/files/scan`), map the `status` field as follows:
|
||||
|
||||
| DB Status | Status Label | Filter: 待處理 | Filter: 處理中 | Count: pendingCount | Count: processingCount |
|
||||
|-----------|-------------|----------------|----------------|---------------------|-----------------------|
|
||||
| `unregistered` | 未註冊 | No | No | No | No |
|
||||
| `registered` | 待處理 | **Yes** | No | **Yes** | No |
|
||||
| `pending` | 待處理 | **Yes** | No | **Yes** | No |
|
||||
| `queued` | 排隊中 | **Yes** | **Yes** | **Yes** | **Yes** |
|
||||
| `processing` | 處理中 | No | **Yes** | No | **Yes** |
|
||||
| `completed` | 已完成 | No | No | No | No |
|
||||
| `failed` | 處理失敗 | No | No | No | No |
|
||||
| `indexed` | 已入庫 | No | No | No | No |
|
||||
|
||||
**`queued` 的特殊處理**:
|
||||
- `statusLabel` → 顯示「排隊中」,加 `ms-badge-warn` 樣式(黃色)
|
||||
- `filterPending` → 應包含 `queued`,讓它在「待處理」filter 可見
|
||||
- `pendingCount` + `processingCount` → 兩者都應包含 `queued`,因它既是「待處理」也是「正在排隊」
|
||||
- 在 `refreshAllStatus` / `loadFiles` 中,如果檔案狀態是 `queued`,應顯示簡單的排隊訊息(無需 polling progress)
|
||||
- 當 worker pickup 後,狀態會變為 `processing`,此時 `refreshAllStatus` 會自動偵測到並開始 polling progress
|
||||
- 也可以提供一個「queue_position」顯示:呼叫 `GET /api/v1/job/:uuid` 取得排在第幾位
|
||||
|
||||
---
|
||||
|
||||
### `GET /api/v1/file/:file_uuid/processor-counts`
|
||||
|
||||
**Auth**: Required
|
||||
**Scope**: file-level
|
||||
|
||||
Get counts of processor JSON output files. See `15_tkg.md` for full documentation.
|
||||
|
||||
---
|
||||
|
||||
## Pipeline Steps (Manual)
|
||||
|
||||
These endpoints execute individual pipeline steps. They are typically called by the worker automatically, but can be invoked manually for debugging or re-processing.
|
||||
|
||||
### `POST /api/v1/file/:file_uuid/store-asrx`
|
||||
|
||||
**Auth**: Required
|
||||
**Scope**: file-level
|
||||
|
||||
Store ASRX diarization results as chunk records in the database. Converts ASRX segments into searchable chunk entries.
|
||||
|
||||
#### Example
|
||||
|
||||
```bash
|
||||
curl -s -X POST "$API/api/v1/file/$FILE_UUID/store-asrx" \
|
||||
-H "X-API-Key: $KEY"
|
||||
```
|
||||
|
||||
#### Response (200)
|
||||
|
||||
```json
|
||||
{
|
||||
"success": true,
|
||||
"message": "ASRX chunks stored",
|
||||
"file_uuid": "3a6c1865..."
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### `POST /api/v1/file/:file_uuid/rule1`
|
||||
|
||||
**Auth**: Required
|
||||
**Scope**: file-level
|
||||
|
||||
Execute Rule 1 pipeline step. Applies rule-based chunking to create structured chunk records from processor outputs.
|
||||
|
||||
#### Example
|
||||
|
||||
```bash
|
||||
curl -s -X POST "$API/api/v1/file/$FILE_UUID/rule1" \
|
||||
-H "X-API-Key: $KEY"
|
||||
```
|
||||
|
||||
#### Response (200)
|
||||
|
||||
```json
|
||||
{
|
||||
"success": true,
|
||||
"message": "Rule 1 complete: 45 chunks",
|
||||
"file_uuid": "3a6c1865...",
|
||||
"chunks": 45
|
||||
}
|
||||
```
|
||||
|
||||
| Field | Type | Description |
|
||||
|-------|------|-------------|
|
||||
| `success` | boolean | Always true on 200 |
|
||||
| `message` | string | Human-readable completion message |
|
||||
| `file_uuid` | string | 32-char hex UUID |
|
||||
| `chunks` | integer | Number of chunks produced |
|
||||
|
||||
---
|
||||
|
||||
### `POST /api/v1/file/:file_uuid/vectorize`
|
||||
|
||||
**Auth**: Required
|
||||
**Scope**: file-level
|
||||
|
||||
Generate vector embeddings for all chunks of a file and store them in Qdrant for semantic search.
|
||||
|
||||
#### Example
|
||||
|
||||
```bash
|
||||
curl -s -X POST "$API/api/v1/file/$FILE_UUID/vectorize" \
|
||||
-H "X-API-Key: $KEY"
|
||||
```
|
||||
|
||||
#### Response (200)
|
||||
|
||||
```json
|
||||
{
|
||||
"success": true,
|
||||
"message": "Vectorization complete",
|
||||
"file_uuid": "3a6c1865..."
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### `POST /api/v1/file/:file_uuid/phase1`
|
||||
|
||||
**Auth**: Required
|
||||
**Scope**: file-level
|
||||
|
||||
Execute Phase 1 of the post-processing pipeline. Combines store-asrx, rule1, and vectorize into a single step.
|
||||
|
||||
#### Example
|
||||
|
||||
```bash
|
||||
curl -s -X POST "$API/api/v1/file/$FILE_UUID/phase1" \
|
||||
-H "X-API-Key: $KEY"
|
||||
```
|
||||
|
||||
#### Response (200)
|
||||
|
||||
```json
|
||||
{
|
||||
"success": true,
|
||||
"message": "Phase 1 complete",
|
||||
"file_uuid": "3a6c1865..."
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### `POST /api/v1/file/:file_uuid/complete`
|
||||
|
||||
**Auth**: Required
|
||||
**Scope**: file-level
|
||||
|
||||
Mark a video as fully processed. Updates the video status to `completed` and finalizes all pipeline state.
|
||||
|
||||
#### Example
|
||||
|
||||
```bash
|
||||
curl -s -X POST "$API/api/v1/file/$FILE_UUID/complete" \
|
||||
-H "X-API-Key: $KEY"
|
||||
```
|
||||
|
||||
#### Response (200)
|
||||
|
||||
```json
|
||||
{
|
||||
"success": true,
|
||||
"message": "Video marked as completed",
|
||||
"file_uuid": "3a6c1865..."
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Pipeline Step Order
|
||||
|
||||
```
|
||||
process (trigger)
|
||||
│
|
||||
├─→ cut, yolo, ocr, face, pose, asrx (parallel processors)
|
||||
│
|
||||
├─→ store-asrx (store diarization as chunks)
|
||||
│
|
||||
├─→ rule1 (rule-based chunking)
|
||||
│
|
||||
├─→ vectorize (embed chunks to Qdrant)
|
||||
│
|
||||
└─→ complete (mark done)
|
||||
```
|
||||
|
||||
Phase 1 (`/phase1`) combines store-asrx + rule1 + vectorize into one call.
|
||||
|
||||
---
|
||||
*Updated: 2026-06-23 — Added queued status, FIFO queue order, queue_position in job detail, frontend status mapping table*
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
<!-- module: search -->
|
||||
<!-- description: Vector search, BM25, smart search, universal search, visual search -->
|
||||
<!-- description: Vector search, BM25, smart search, universal search, LLM reranked search, frame search -->
|
||||
<!-- depends: 01_auth -->
|
||||
|
||||
## Search APIs
|
||||
@@ -160,11 +160,137 @@ curl -s -X POST "$API/api/v1/search/universal" \
|
||||
**Auth**: Required
|
||||
**Scope**: global / file-level
|
||||
|
||||
Search face detection frames by identity name or trace ID.
|
||||
Search frames by YOLO objects, OCR text, face IDs, or pose detections. Filters frames based on visual content detected during processing.
|
||||
|
||||
#### Request Parameters
|
||||
|
||||
| Field | Type | Required | Default | Description |
|
||||
|-------|------|----------|---------|-------------|
|
||||
| `file_uuid` | string | No | — | Restrict to specific file |
|
||||
| `object_class` | string | No | — | Filter by YOLO object class (e.g., `person`, `car`, `dog`) |
|
||||
| `ocr_text` | string | No | — | Filter by OCR text content (ILIKE match) |
|
||||
| `face_id` | string | No | — | Filter by face detection ID |
|
||||
| `time_range` | [float, float] | No | — | Filter by time range `[start_secs, end_secs]` |
|
||||
| `limit` | integer | No | 100 | Max results |
|
||||
|
||||
#### Example
|
||||
|
||||
```bash
|
||||
# Search for frames containing "person" objects
|
||||
curl -s -X POST "$API/api/v1/search/frames" \
|
||||
-H "Content-Type: application/json" \
|
||||
-H "X-API-Key: $KEY" \
|
||||
-d '{"file_uuid": "'"$FILE_UUID"'", "object_class": "person", "limit": 20}'
|
||||
|
||||
# Search for frames with specific OCR text
|
||||
curl -s -X POST "$API/api/v1/search/frames" \
|
||||
-H "Content-Type: application/json" \
|
||||
-H "X-API-Key: $KEY" \
|
||||
-d '{"file_uuid": "'"$FILE_UUID"'", "ocr_text": "hello", "time_range": [10.0, 30.0]}'
|
||||
```
|
||||
|
||||
#### Response (200)
|
||||
|
||||
```json
|
||||
{
|
||||
"frames": [
|
||||
{
|
||||
"frame_number": 1200,
|
||||
"timestamp": 50.0,
|
||||
"file_uuid": "d3f9ae8e471a1fc4d47022c66091b920",
|
||||
"objects": [{"class": "person", "confidence": 0.95, "bbox": [100, 50, 300, 400]}],
|
||||
"ocr_texts": ["Hello World"],
|
||||
"faces": [{"face_id": "face_42", "confidence": 0.88}],
|
||||
"pose_persons": [{"trace_id": 2, "bbox": [120, 60, 280, 380]}]
|
||||
}
|
||||
],
|
||||
"total": 15
|
||||
}
|
||||
```
|
||||
|
||||
| Field | Type | Description |
|
||||
|-------|------|-------------|
|
||||
| `frames` | array | Array of matching frame objects |
|
||||
| `frames[].frame_number` | integer | Frame number in video |
|
||||
| `frames[].timestamp` | float | Timestamp in seconds |
|
||||
| `frames[].file_uuid` | string | File UUID |
|
||||
| `frames[].objects` | array/null | YOLO detections in this frame |
|
||||
| `frames[].ocr_texts` | array/null | OCR text strings in this frame |
|
||||
| `frames[].faces` | array/null | Face detections in this frame |
|
||||
| `frames[].pose_persons` | array/null | Pose-detected persons in this frame |
|
||||
| `total` | integer | Total matching frame count |
|
||||
|
||||
---
|
||||
|
||||
### `GET /api/v1/search/identity_text`
|
||||
### `POST /api/v1/search/llm-smart`
|
||||
|
||||
**Auth**: Required
|
||||
**Scope**: global / file-level
|
||||
|
||||
Smart search with LLM re-ranking. First fetches candidate results via RRF (Reciprocal Rank Fusion) using the existing smart search, then uses an LLM (Gemma4 on port 8000) to re-rank candidates by relevance to the query.
|
||||
|
||||
#### Request Parameters
|
||||
|
||||
| Field | Type | Required | Default | Description |
|
||||
|-------|------|----------|---------|-------------|
|
||||
| `query` | string | Yes | — | Search text |
|
||||
| `file_uuid` | string | No | — | File UUID to search within |
|
||||
| `limit` | integer | No | 10 | Max results to return |
|
||||
|
||||
#### Pipeline
|
||||
|
||||
```
|
||||
1. smart_search → fetch N candidates (limit × 3, clamped 10-20)
|
||||
2. LLM rerank → re-order by relevance using Gemma4
|
||||
3. trim → return top `limit` results
|
||||
```
|
||||
|
||||
#### Example
|
||||
|
||||
```bash
|
||||
curl -s -X POST "$API/api/v1/search/llm-smart" \
|
||||
-H "Content-Type: application/json" \
|
||||
-H "X-API-Key: $KEY" \
|
||||
-d '{"query": "two people having a conversation about business", "limit": 5}'
|
||||
```
|
||||
|
||||
#### Response (200)
|
||||
|
||||
```json
|
||||
{
|
||||
"query": "two people having a conversation about business",
|
||||
"results": [
|
||||
{
|
||||
"file_uuid": "d3f9ae8e471a1fc4d47022c66091b920",
|
||||
"parent_id": 1234,
|
||||
"scene_order": 1234,
|
||||
"start_frame": 5000,
|
||||
"end_frame": 5200,
|
||||
"fps": 24.0,
|
||||
"start_time": 208.3,
|
||||
"end_time": 216.7,
|
||||
"summary": "[208s-217s, 9s] Two people discussing project timeline...",
|
||||
"similarity": 0.72
|
||||
}
|
||||
],
|
||||
"page": 1,
|
||||
"page_size": 5,
|
||||
"strategy": "llm_reranked"
|
||||
}
|
||||
```
|
||||
|
||||
| Field | Type | Description |
|
||||
|-------|------|-------------|
|
||||
| `strategy` | string | Always `"llm_reranked"` for this endpoint |
|
||||
| `results` | array | Re-ranked search results (same format as smart search) |
|
||||
|
||||
#### Fallback
|
||||
|
||||
If LLM reranking fails (model unavailable, timeout), falls back to RRF order without error.
|
||||
|
||||
---
|
||||
|
||||
### Visual Search
|
||||
|
||||
**Auth**: Required
|
||||
**Scope**: global / file-level
|
||||
@@ -223,15 +349,15 @@ curl -s "$API/api/v1/search/identity_text?file_uuid=$FILE_UUID&q=love" -H "X-API
|
||||
|
||||
---
|
||||
|
||||
### Visual Search
|
||||
### Visual Search (Planned)
|
||||
|
||||
| Method | Endpoint | Description |
|
||||
|--------|----------|-------------|
|
||||
| POST | `/api/v1/search/visual` | Search visual chunks |
|
||||
| POST | `/api/v1/search/visual/class` | Search by object class |
|
||||
| POST | `/api/v1/search/visual/density` | Search by object density |
|
||||
| POST | `/api/v1/search/visual/combination` | Search by object combination |
|
||||
| POST | `/api/v1/search/visual/stats` | Visual chunk statistics |
|
||||
| Method | Endpoint | Status | Description |
|
||||
|--------|----------|--------|-------------|
|
||||
| POST | `/api/v1/search/visual` | Not implemented | Search visual chunks |
|
||||
| POST | `/api/v1/search/visual/class` | Not implemented | Search by object class |
|
||||
| POST | `/api/v1/search/visual/density` | Not implemented | Search by object density |
|
||||
| POST | `/api/v1/search/visual/combination` | Not implemented | Search by object combination |
|
||||
| POST | `/api/v1/search/visual/stats` | Not implemented | Visual chunk statistics |
|
||||
|
||||
#### Embedding Model
|
||||
|
||||
@@ -243,4 +369,4 @@ curl -s "$API/api/v1/search/identity_text?file_uuid=$FILE_UUID&q=love" -H "X-API
|
||||
| **Storage** | pgvector (`chunk.embedding` column) |
|
||||
|
||||
---
|
||||
*Updated: 2026-05-27 — Added global search support for smart, universal, identity_text APIs*
|
||||
*Updated: 2026-06-20 — Added llm-smart search, completed frames search documentation, marked visual search as planned*
|
||||
|
||||
@@ -302,7 +302,9 @@ curl -s "$API/api/v1/identity/$IDENTITY_UUID/traces?page=1&page_size=3" \
|
||||
"last_frame": 38127,
|
||||
"first_sec": 1519.0,
|
||||
"last_sec": 1525.1,
|
||||
"avg_confidence": 0.8254
|
||||
"avg_confidence": 0.8254,
|
||||
"avg_capture_quality": 0.6123,
|
||||
"best_capture_quality": 0.7812
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -323,6 +325,8 @@ curl -s "$API/api/v1/identity/$IDENTITY_UUID/traces?page=1&page_size=3" \
|
||||
| `traces[].first_sec` | float | Start time in seconds |
|
||||
| `traces[].last_sec` | float | End time in seconds |
|
||||
| `traces[].avg_confidence` | float | Average detection confidence (0.0–1.0) |
|
||||
| `traces[].avg_capture_quality` | float | Average frame sharpness quality score (0.0–1.0) |
|
||||
| `traces[].best_capture_quality` | float | Best frame sharpness quality score (0.0–1.0) |
|
||||
|
||||
#### Error Responses
|
||||
|
||||
@@ -729,6 +733,322 @@ curl -s "$API/api/v1/identity/$IDENTITY_UUID/profile-image" \
|
||||
|
||||
---
|
||||
|
||||
## Identity Related Data
|
||||
|
||||
### `GET /api/v1/identity/:identity_uuid/files`
|
||||
|
||||
**Auth**: Required
|
||||
**Scope**: identity-level
|
||||
|
||||
List all files containing this identity.
|
||||
|
||||
#### Example
|
||||
|
||||
```bash
|
||||
curl -s "$API/api/v1/identity/$IDENTITY_UUID/files" \
|
||||
-H "X-API-Key: $KEY"
|
||||
```
|
||||
|
||||
#### Response (200)
|
||||
|
||||
```json
|
||||
{
|
||||
"success": true,
|
||||
"identity_uuid": "a9a90105-6d6b-46ff-92da-0c3c1a57dff4",
|
||||
"total": 3,
|
||||
"files": [
|
||||
{
|
||||
"file_uuid": "d3f9ae8e471a1fc4d47022c66091b920",
|
||||
"file_name": "video1.mp4",
|
||||
"face_count": 142,
|
||||
"first_appearance": 4.17,
|
||||
"last_appearance": 208.33
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### `GET /api/v1/identity/:identity_uuid/chunks`
|
||||
|
||||
**Auth**: Required
|
||||
**Scope**: identity-level
|
||||
|
||||
List all chunks associated with this identity (chunks where the identity's face appears).
|
||||
|
||||
#### Query Parameters
|
||||
|
||||
| Field | Type | Required | Default | Description |
|
||||
|-------|------|----------|---------|-------------|
|
||||
| `page` | integer | No | 1 | Page number |
|
||||
| `page_size` | integer | No | 20 | Items per page |
|
||||
|
||||
#### Example
|
||||
|
||||
```bash
|
||||
curl -s "$API/api/v1/identity/$IDENTITY_UUID/chunks?page=1&page_size=50" \
|
||||
-H "X-API-Key: $KEY"
|
||||
```
|
||||
|
||||
#### Response (200)
|
||||
|
||||
```json
|
||||
{
|
||||
"success": true,
|
||||
"identity_uuid": "a9a90105-6d6b-46ff-92da-0c3c1a57dff4",
|
||||
"total": 45,
|
||||
"page": 1,
|
||||
"page_size": 20,
|
||||
"chunks": [
|
||||
{
|
||||
"chunk_id": "chunk_1",
|
||||
"file_uuid": "d3f9ae8e471a1fc4d47022c66091b920",
|
||||
"start_time": 4.17,
|
||||
"end_time": 8.33,
|
||||
"text": "[4s-8s] Hello, how are you?",
|
||||
"chunk_type": "story_child"
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### `GET /api/v1/identity/:identity_uuid/faces`
|
||||
|
||||
**Auth**: Required
|
||||
**Scope**: identity-level
|
||||
|
||||
List all face detections for this identity.
|
||||
|
||||
#### Query Parameters
|
||||
|
||||
| Field | Type | Required | Default | Description |
|
||||
|-------|------|----------|---------|-------------|
|
||||
| `page` | integer | No | 1 | Page number |
|
||||
| `page_size` | integer | No | 50 | Items per page |
|
||||
|
||||
#### Example
|
||||
|
||||
```bash
|
||||
curl -s "$API/api/v1/identity/$IDENTITY_UUID/faces?page=1&page_size=100" \
|
||||
-H "X-API-Key: $KEY"
|
||||
```
|
||||
|
||||
#### Response (200)
|
||||
|
||||
```json
|
||||
{
|
||||
"success": true,
|
||||
"identity_uuid": "a9a90105-6d6b-46ff-92da-0c3c1a57dff4",
|
||||
"total": 1420,
|
||||
"page": 1,
|
||||
"page_size": 50,
|
||||
"faces": [
|
||||
{
|
||||
"face_id": "face_100",
|
||||
"file_uuid": "d3f9ae8e471a1fc4d47022c66091b920",
|
||||
"frame_number": 1200,
|
||||
"timestamp": 50.0,
|
||||
"bbox": [100, 50, 300, 400],
|
||||
"confidence": 0.95,
|
||||
"trace_id": 2
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### `GET /api/v1/identity/:identity_uuid/status`
|
||||
|
||||
**Auth**: Required
|
||||
**Scope**: identity-level
|
||||
|
||||
Get processing/status info for an identity.
|
||||
|
||||
#### Example
|
||||
|
||||
```bash
|
||||
curl -s "$API/api/v1/identity/$IDENTITY_UUID/status" \
|
||||
-H "X-API-Key: $KEY"
|
||||
```
|
||||
|
||||
#### Response (200)
|
||||
|
||||
```json
|
||||
{
|
||||
"success": true,
|
||||
"identity_uuid": "a9a90105-6d6b-46ff-92da-0c3c1a57dff4",
|
||||
"name": "Audrey Hepburn",
|
||||
"status": "confirmed",
|
||||
"face_count": 1420,
|
||||
"file_count": 3,
|
||||
"has_embedding": true,
|
||||
"has_profile_image": true
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### `GET /api/v1/identity/:identity_uuid/json`
|
||||
|
||||
**Auth**: Required
|
||||
**Scope**: identity-level
|
||||
|
||||
Get the raw identity JSON file (same format as identity.json on disk).
|
||||
|
||||
#### Example
|
||||
|
||||
```bash
|
||||
curl -s "$API/api/v1/identity/$IDENTITY_UUID/json" \
|
||||
-H "X-API-Key: $KEY"
|
||||
```
|
||||
|
||||
#### Response (200)
|
||||
|
||||
```json
|
||||
{
|
||||
"version": 1,
|
||||
"identity_uuid": "a9a90105-6d6b-46ff-92da-0c3c1a57dff4",
|
||||
"name": "Audrey Hepburn",
|
||||
"identity_type": "people",
|
||||
"source": "tmdb",
|
||||
"status": "confirmed",
|
||||
"tmdb_id": 1234,
|
||||
"tmdb_profile": "https://image.tmdb.org/...",
|
||||
"metadata": {},
|
||||
"file_bindings": [
|
||||
{"file_uuid": "d3f9ae8e...", "trace_ids": [0, 1, 2], "face_count": 142}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
---
|
||||
|
||||
### `POST /api/v1/file/:file_uuid/pending-person`
|
||||
|
||||
**Auth**: Required
|
||||
**Scope**: file-level
|
||||
|
||||
Create a manually managed "pending person" under a specific file. A pending person is an identity with `status='pending'` and `source='manual'`, used for unmatched traces that the user wants to manually label before a full identity resolution.
|
||||
|
||||
Optionally binds a list of trace IDs to this new identity.
|
||||
|
||||
#### Request
|
||||
|
||||
```json
|
||||
{
|
||||
"trace_ids": [100, 150, 200],
|
||||
"name": "Mystery Man #1"
|
||||
}
|
||||
```
|
||||
|
||||
| Field | Type | Required | Default | Description |
|
||||
|-------|------|----------|---------|-------------|
|
||||
| `trace_ids` | array[int] | No | `[]` | Trace IDs to bind to this pending person |
|
||||
| `name` | string | No | `"Person N"` | Human-readable name. Auto-generated if omitted |
|
||||
|
||||
#### Example
|
||||
|
||||
```bash
|
||||
# Create pending person with name and no traces
|
||||
curl -s -X POST "$API/api/v1/file/$FILE_UUID/pending-person" \
|
||||
-H "X-API-Key: $KEY" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{"name": "Unknown Woman #2", "trace_ids": []}'
|
||||
|
||||
# Create pending person with auto-name and bind traces
|
||||
curl -s -X POST "$API/api/v1/file/$FILE_UUID/pending-person" \
|
||||
-H "X-API-Key: $KEY" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{"trace_ids": [100, 150, 200]}'
|
||||
```
|
||||
|
||||
#### Response (200)
|
||||
|
||||
```json
|
||||
{
|
||||
"success": true,
|
||||
"message": "Created pending person: Mystery Man #1 (uuid: 4d96b25b-68f0-4c52-b238-d69f7dfd588b)",
|
||||
"data": {
|
||||
"identity_uuid": "4d96b25b-68f0-4c52-b238-d69f7dfd588b",
|
||||
"identity_id": 55,
|
||||
"name": "Mystery Man #1",
|
||||
"bound_traces": 0
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
| Field | Type | Description |
|
||||
|-------|------|-------------|
|
||||
| `identity_uuid` | string | UUID of the newly created pending identity |
|
||||
| `identity_id` | integer | Internal ID of the new identity |
|
||||
| `name` | string | Display name |
|
||||
| `bound_traces` | integer | Number of traces bound |
|
||||
|
||||
#### Side Effects
|
||||
|
||||
- Creates an `identities` row with `status='pending'`, `source='manual'`, `file_uuid=<file_uuid>`
|
||||
- If `trace_ids` provided: `UPDATE face_detections SET identity_id = ...` for matching traces
|
||||
- If `trace_ids` provided: TKG face_track nodes get `identity_id` / `identity_name` in properties
|
||||
- Identity JSON file synced to disk
|
||||
|
||||
---
|
||||
|
||||
### `GET /api/v1/file/:file_uuid/pending-persons`
|
||||
|
||||
**Auth**: Required
|
||||
**Scope**: file-level
|
||||
|
||||
List all pending persons for a file.
|
||||
|
||||
#### Example
|
||||
|
||||
```bash
|
||||
curl -s "$API/api/v1/file/$FILE_UUID/pending-persons" \
|
||||
-H "X-API-Key: $KEY"
|
||||
```
|
||||
|
||||
#### Response (200)
|
||||
|
||||
```json
|
||||
{
|
||||
"success": true,
|
||||
"message": "Found 2 pending persons for c36f35685177c981aa139b66bbbccc5b",
|
||||
"data": [
|
||||
{
|
||||
"identity_uuid": "232ecd08-a2bf-4bd0-bd25-0bd8fb7a7dae",
|
||||
"identity_id": 56,
|
||||
"name": "Person 2",
|
||||
"created_at": "2026-06-23 17:13:23",
|
||||
"trace_count": 3,
|
||||
"bound_traces": null
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
| Field | Type | Description |
|
||||
|-------|------|-------------|
|
||||
| `identity_uuid` | string | Identity UUID |
|
||||
| `identity_id` | integer | Internal identity ID |
|
||||
| `name` | string | Display name |
|
||||
| `created_at` | string | Creation timestamp |
|
||||
| `trace_count` | integer | Number of face traces bound to this pending person |
|
||||
| `bound_traces` | array[int] | List of bound trace IDs (currently null, reserved for future expansion) |
|
||||
|
||||
#### Notes
|
||||
|
||||
- Pending persons are normal `identities` rows with `status='pending'` — they can be promoted to confirmed via `PATCH /api/v1/identity/:identity_uuid` (`{"status": "confirmed"}`)
|
||||
- They can be merged into known identities via `POST /api/v1/identity/:identity_uuid/mergeinto`
|
||||
- Use `GET /api/v1/identity/:identity_uuid/traces` to get detailed trace info for each pending person
|
||||
|
||||
---
|
||||
|
||||
## Alias System (BCP 47 Locale Tags)
|
||||
|
||||
Identity aliases support multilingual display names. Aliases are stored in `metadata.aliases` as an array of `{locale, name}` objects.
|
||||
@@ -785,5 +1105,7 @@ PATCH /api/v1/identity/:identity_uuid
|
||||
|
||||
This **replaces** the entire `aliases` array. To add to existing aliases, include all existing entries in the request.
|
||||
|
||||
---
|
||||
*Updated: 2026-05-25 — Added `GET /api/v1/file/:file_uuid/faces` with 4 binding states, filters, strangers table split
|
||||
---
|
||||
*Updated: 2026-08-12 — identity traces include capture_quality fields (avg_capture_quality, best_capture_quality)*
|
||||
*Updated: 2026-07-21 — Fixed bind/unbind TKG update to match both trace_N and face_track_N external_id formats*
|
||||
*Updated: 2026-06-20 — Added identity files, chunks, faces, status, and JSON endpoints*
|
||||
|
||||
@@ -65,4 +65,63 @@ curl -s -X POST "$API/api/v1/agents/identity/match-from-trace" \
|
||||
```
|
||||
|
||||
---
|
||||
*Updated: 2026-05-19 12:49:24*
|
||||
|
||||
### `POST /api/v1/agents/identity/confirm`
|
||||
|
||||
**Auth**: Required
|
||||
**Scope**: file-level
|
||||
|
||||
Confirm identity binding for a trace. This marks the trace as confirmed in TKG, updates face_detections, adds to _seeds, and optionally triggers Round 2 propagation.
|
||||
|
||||
#### Request Parameters
|
||||
|
||||
| Field | Type | Required | Description |
|
||||
|-------|------|----------|-------------|
|
||||
| `file_uuid` | string | Yes | Video file UUID |
|
||||
| `trace_id` | integer | Yes | Face trace ID to confirm |
|
||||
| `identity_id` | integer | Yes | Identity internal ID |
|
||||
| `identity_uuid` | string | Yes | Identity UUID |
|
||||
| `name` | string | Yes | Identity name |
|
||||
| `propagate` | boolean | No | Auto-trigger Round 2 matching (default: true) |
|
||||
|
||||
#### Example
|
||||
|
||||
```bash
|
||||
curl -s -X POST "$API/api/v1/agents/identity/confirm" \
|
||||
-H "Authorization: Bearer $JWT" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{"file_uuid": "'"$FILE_UUID"'", "trace_id": 10, "identity_id": 42, "identity_uuid": "'"$IDENTITY_UUID"'", "name": "Cary Grant", "propagate": false}'
|
||||
```
|
||||
|
||||
#### Response (200)
|
||||
|
||||
```json
|
||||
{
|
||||
"success": true,
|
||||
"file_uuid": "384b0ff44aaaa1f1",
|
||||
"trace_id": 10,
|
||||
"identity_uuid": "a9a90105...",
|
||||
"name": "Cary Grant",
|
||||
"steps": {
|
||||
"tkg_updated": true,
|
||||
"qdrant_updated": 150,
|
||||
"pg_updated": 150,
|
||||
"seed_added": true
|
||||
},
|
||||
"propagation": {
|
||||
"matched": 5,
|
||||
"message": "Propagation completed"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
#### Side Effects
|
||||
|
||||
1. TKG face_track node status → 'confirmed'
|
||||
2. Qdrant _faces: identity_uuid added to payload
|
||||
3. PG face_detections: identity_id set
|
||||
4. Trace centroid added to _seeds (source='propagation')
|
||||
5. Round 2 matching triggered (if propagate=true)
|
||||
|
||||
---
|
||||
*Updated: 2026-06-26 00:30:00*
|
||||
|
||||
@@ -427,4 +427,111 @@ Both endpoints support time range extraction, but serve different use cases:
|
||||
| **Frame number** | Zero-based (`frame=0` = first frame of video) |
|
||||
|
||||
---
|
||||
*Updated: 2026-05-19 12:49:24*
|
||||
|
||||
### `GET /api/v1/file/:file_uuid/stranger/:stranger_id/representative-face`
|
||||
|
||||
**Auth**: Required
|
||||
**Scope**: file-level
|
||||
|
||||
Get the representative face for a stranger (unidentified face trace).
|
||||
|
||||
#### Example
|
||||
|
||||
```bash
|
||||
curl -s "$API/api/v1/file/$FILE_UUID/stranger/1/representative-face" \
|
||||
-H "X-API-Key: $KEY"
|
||||
```
|
||||
|
||||
#### Response (200)
|
||||
|
||||
```json
|
||||
{
|
||||
"success": true,
|
||||
"file_uuid": "d3f9ae8e471a1fc4d47022c66091b920",
|
||||
"stranger_id": 1,
|
||||
"face_count": 85,
|
||||
"representative": {
|
||||
"frame_number": 5000,
|
||||
"timestamp_secs": 208.33,
|
||||
"bbox": {"x": 200, "y": 100, "width": 150, "height": 150},
|
||||
"confidence": 0.92,
|
||||
"quality_score": 20700,
|
||||
"blur_score": 8.5
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### `GET /api/v1/file/:file_uuid/stranger/:stranger_id/thumbnail`
|
||||
|
||||
**Auth**: Required
|
||||
**Scope**: file-level
|
||||
|
||||
Extract the best face image for a stranger as JPEG (320×320).
|
||||
|
||||
#### Example
|
||||
|
||||
```bash
|
||||
curl -s "$API/api/v1/file/$FILE_UUID/stranger/1/thumbnail" \
|
||||
-H "X-API-Key: $KEY" -o stranger_1_face.jpg
|
||||
```
|
||||
|
||||
#### Response
|
||||
|
||||
- **200**: `image/jpeg` binary data (320×320 cropped face)
|
||||
- **404**: File or stranger not found
|
||||
|
||||
---
|
||||
|
||||
### `GET /api/v1/file/:file_uuid/chunk/:chunk_id/thumbnail`
|
||||
|
||||
**Auth**: Required
|
||||
**Scope**: file-level
|
||||
|
||||
Get thumbnail for a specific chunk. Extracts the representative frame for the chunk's time range.
|
||||
|
||||
#### Example
|
||||
|
||||
```bash
|
||||
curl -s "$API/api/v1/file/$FILE_UUID/chunk/chunk_1/thumbnail" \
|
||||
-H "X-API-Key: $KEY" -o chunk_1.jpg
|
||||
```
|
||||
|
||||
#### Response
|
||||
|
||||
- **200**: `image/jpeg` binary data
|
||||
- **404**: File or chunk not found
|
||||
|
||||
---
|
||||
|
||||
### `GET /api/v1/media-proxy`
|
||||
|
||||
**Auth**: Required
|
||||
**Scope**: system-level
|
||||
|
||||
Proxy request to fetch media from external URLs. Useful for loading profile images or thumbnails from external services (TMDb, etc.) without exposing the external URL to the client.
|
||||
|
||||
#### Query Parameters
|
||||
|
||||
| Field | Type | Required | Description |
|
||||
|-------|------|----------|-------------|
|
||||
| `url` | string | Yes | External URL to proxy |
|
||||
|
||||
#### Example
|
||||
|
||||
```bash
|
||||
curl -s "$API/api/v1/media-proxy?url=https://image.tmdb.org/t/p/w500/abc123.jpg" \
|
||||
-H "X-API-Key: $KEY" -o tmdb_profile.jpg
|
||||
```
|
||||
|
||||
#### Response
|
||||
|
||||
- **200**: Proxied media data (Content-Type from external source)
|
||||
- **400**: Missing or invalid URL parameter
|
||||
- **500**: External request failed
|
||||
|
||||
---
|
||||
|
||||
---
|
||||
*Updated: 2026-06-20 — Added stranger endpoints, chunk thumbnail, and media proxy*
|
||||
|
||||
@@ -108,5 +108,94 @@ curl -s -X POST "$API/api/v1/resource/tmdb/check" \
|
||||
}
|
||||
```
|
||||
|
||||
### `POST /api/v1/tmdb/fetch`
|
||||
|
||||
**Auth**: Required
|
||||
**Scope**: system-level
|
||||
|
||||
Fetch TMDb data by filename, create identities with profile images and embeddings. Similar to prefetch+probe combined, but also downloads profile images and generates embeddings.
|
||||
|
||||
#### Request Parameters
|
||||
|
||||
| Field | Type | Required | Description |
|
||||
|-------|------|----------|-------------|
|
||||
| `filename` | string | Yes | Movie filename to search TMDb for |
|
||||
|
||||
#### Example
|
||||
|
||||
```bash
|
||||
curl -s -X POST "$API/api/v1/tmdb/fetch" \
|
||||
-H "Content-Type: application/json" \
|
||||
-H "X-API-Key: $KEY" \
|
||||
-d '{"filename": "charade.mp4"}'
|
||||
```
|
||||
|
||||
#### Response (200)
|
||||
|
||||
```json
|
||||
{
|
||||
"success": true,
|
||||
"movie_title": "Charade (1963)",
|
||||
"tmdb_id": 1234,
|
||||
"identities_created": 15,
|
||||
"profile_images_downloaded": 12
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
*Updated: 2026-05-19 12:49:24*
|
||||
|
||||
### `POST /api/v1/agents/tmdb/match/:file_uuid`
|
||||
|
||||
**Auth**: Required
|
||||
**Scope**: file-level
|
||||
|
||||
Match TMDb identities to face traces using Qdrant vector similarity. Compares face embeddings against TMDb identity embeddings to find the best matches.
|
||||
|
||||
#### Example
|
||||
|
||||
```bash
|
||||
curl -s -X POST "$API/api/v1/agents/tmdb/match/$FILE_UUID" \
|
||||
-H "X-API-Key: $KEY"
|
||||
```
|
||||
|
||||
#### Response (200)
|
||||
|
||||
```json
|
||||
{
|
||||
"success": true,
|
||||
"file_uuid": "d3f9ae8e471a1fc4d47022c66091b920",
|
||||
"matches": [
|
||||
{
|
||||
"trace_id": 0,
|
||||
"identity_uuid": "a9a90105-6d6b-46ff-92da-0c3c1a57dff4",
|
||||
"identity_name": "Audrey Hepburn",
|
||||
"confidence": 0.92,
|
||||
"tmdb_id": 1234
|
||||
}
|
||||
],
|
||||
"total_matches": 5
|
||||
}
|
||||
```
|
||||
|
||||
| Field | Type | Description |
|
||||
|-------|------|-------------|
|
||||
| `matches[].trace_id` | integer | Face trace ID |
|
||||
| `matches[].identity_uuid` | string | Matched TMDb identity UUID |
|
||||
| `matches[].identity_name` | string | Identity display name |
|
||||
| `matches[].confidence` | float | Cosine similarity score (0.0–1.0) |
|
||||
| `matches[].tmdb_id` | integer | TMDb person ID |
|
||||
| `total_matches` | integer | Total successful matches |
|
||||
|
||||
---
|
||||
|
||||
### TMDb Auto-Match
|
||||
|
||||
When `MOMENTRY_TMDB_PROBE_ENABLED=true`, the worker automatically runs TMDb matching during the post-process phase:
|
||||
|
||||
1. **Register phase**: Searches TMDb by filename, creates identities with `tmdb_id`/`tmdb_profile`
|
||||
2. **Post-process phase**: Matches detected faces against TMDb identities via cosine similarity using Qdrant
|
||||
|
||||
No manual API call needed if auto-match is enabled.
|
||||
|
||||
---
|
||||
*Updated: 2026-06-20 — Added tmdb/fetch and tmdb/match endpoints*
|
||||
|
||||
@@ -42,6 +42,7 @@ These steps run after the 10 processors and are **required for pipeline completi
|
||||
| # | Step | Triggers When | Verification |
|
||||
|---|------|--------------|-------------|
|
||||
| 1 | **Rule 1 Sentence Chunking** | ASR + ASRX done | `chunk` table has rows with `chunk_type = 'sentence'` |
|
||||
| 1.1 | **Rule 1 OCR Chunks** | OCR done | OCR pre_chunks grouped into sentence chunks |
|
||||
| 2 | **Auto-Vectorize** | Rule 1 done | `chunk.embedding` IS NOT NULL for sentence chunks |
|
||||
| 3 | **Phase 1 Pack** | Rule 1 done | `release_pack.py --phase 1` executed |
|
||||
| 4 | **Rule 3 Scene Chunking** | All 10 processors done + Cut + ASR | `chunk` table has rows with `chunk_type = 'cut'` |
|
||||
@@ -81,15 +82,17 @@ curl "$API/api/v1/stats/ingestion-status/bd80fec9c42afb0307eb28f22c64c76a" | jq
|
||||
{
|
||||
"file_uuid": "bd80fec9c42afb0307eb28f22c64c76a",
|
||||
"steps": [
|
||||
{ "name": "rule1_sentence", "status": "pending", "detail": "0 sentence chunks" },
|
||||
{ "name": "auto_vectorize", "status": "pending", "detail": "0 embedded" },
|
||||
{ "name": "rule3_scene", "status": "pending", "detail": "0 scene chunks" },
|
||||
{ "name": "face_trace", "status": "pending", "detail": "0 traces" },
|
||||
{ "name": "trace_chunks", "status": "pending", "detail": "0 trace chunks" },
|
||||
{ "name": "tkg", "status": "pending", "detail": "0 nodes, 0 edges" },
|
||||
{ "name": "identity_match", "status": "pending", "detail": "0 identities" },
|
||||
{ "name": "scene_metadata", "status": "pending", "detail": null },
|
||||
{ "name": "5w1h", "status": "pending", "detail": "0 scenes with 5W1H" }
|
||||
{ "name": "rule1_sentence", "status": "done", "detail": "35 sentence chunks" },
|
||||
{ "name": "rule1_ocr", "status": "done", "detail": "30 OCR frames" },
|
||||
{ "name": "rule1_ocr_chunks", "status": "done", "detail": "3 OCR-only chunks" },
|
||||
{ "name": "auto_vectorize", "status": "pending", "detail": "0 embedded" },
|
||||
{ "name": "rule3_scene", "status": "pending", "detail": "0 scene chunks" },
|
||||
{ "name": "face_trace", "status": "pending", "detail": "0 traces" },
|
||||
{ "name": "trace_chunks", "status": "pending", "detail": "0 trace chunks" },
|
||||
{ "name": "tkg", "status": "pending", "detail": "0 nodes, 0 edges" },
|
||||
{ "name": "identity_match", "status": "pending", "detail": "0 identities" },
|
||||
{ "name": "scene_metadata", "status": "pending", "detail": null },
|
||||
{ "name": "5w1h", "status": "pending", "detail": "0 scenes with 5W1H" }
|
||||
]
|
||||
}
|
||||
```
|
||||
@@ -117,7 +120,7 @@ The following routes are defined in source code but are **NOT** currently mounte
|
||||
|
||||
| Endpoint | Source file |
|
||||
|----------|-------------|
|
||||
| `/api/v1/search/persons` | `universal_search.rs` (not mounted) |
|
||||
| `/api/v1/search/people` | `universal_search.rs` (mounted) |
|
||||
| `/api/v1/who` | `who.rs` |
|
||||
| `/api/v1/who/candidates` | `who.rs` |
|
||||
|
||||
|
||||
@@ -0,0 +1,534 @@
|
||||
<!-- module: tkg -->
|
||||
<!-- description: Temporal Knowledge Graph — rebuild, nodes, edges, processor counts -->
|
||||
<!-- depends: 05_process, 07_identity -->
|
||||
|
||||
## Temporal Knowledge Graph (TKG)
|
||||
|
||||
TKG is a time-aligned knowledge graph built from multi-processor outputs (face, yolo, ocr, pose, asrx, gaze, lip, appearance). It produces 9 node types and 14 edge types stored in `dev.tkg_nodes` and `dev.tkg_edges`.
|
||||
|
||||
**Node naming convention:** All trace types use `_track` suffix. Text uses `_region` (non-temporal).
|
||||
|
||||
**See also:** `docs_v1.0/DESIGN/TKG_FORMATION_V1.0.md` for formation phases, flow diagrams, and query examples.
|
||||
|
||||
### Node Types
|
||||
|
||||
| Node Type | External ID Format | Description | Key Properties |
|
||||
|-----------|-------------------|-------------|----------------|
|
||||
| `face_track` | `trace_{trace_id}` | A tracked face identity over time | `trace_id`, `frame_count`, `status`, `avg_bbox`, `avg_yaw`, `avg_pitch`, `avg_roll`, `start_frame`, `end_frame`, `pose_count` |
|
||||
| `gaze_track` | `gaze_track_{id}` | Gaze direction over time | `direction` (frontal/left/right/up/down + diagonals) |
|
||||
| `lip_track` | `lip_track_{id}` | Lip movement synced with speech | `speaker_id`, `lip_area_range` |
|
||||
| `text_region` | `text_region_{id}` | Spoken text aligned to time | `speaker_id`, `text`, `start_time`, `end_time` |
|
||||
| `appearance_trace` | `appearance_{trace_id}` | Human appearance (clothing) over time | `clothing_color`, `upper_cloth`, `lower_cloth` |
|
||||
| `accessory` | `accessory_{id}` | Detected accessories | `type` (glasses/hat/etc.), `confidence` |
|
||||
| `object` | `object_{class}_{id}` | YOLO-detected object | `class`, `confidence`, `frame_count` |
|
||||
| `speaker` | `speaker_{speaker_id}` | ASRX speaker segment | `speaker_id`, `segment_count`, `total_duration` |
|
||||
|
||||
---
|
||||
|
||||
### Identity Agent Integration (face_track nodes)
|
||||
|
||||
Identity Agent marks face_track nodes with identity binding status.
|
||||
|
||||
#### face_track Status Values
|
||||
|
||||
| Status | Description | Properties |
|
||||
|--------|-------------|------------|
|
||||
| `pending` | No identity suggestion | Default state |
|
||||
| `suggested` | Identity Agent suggested | `pending_identity_name`, `pending_identity_uuid`, `suggested_by`, `confidence` |
|
||||
| `confirmed` | User confirmed binding | `identity_uuid`, `identity_id`, `identity_ref`, `identity_name` |
|
||||
| `stranger` | Stranger cluster member | `stranger_id`, `stranger_ref` |
|
||||
|
||||
#### Suggested By Values
|
||||
|
||||
| Value | Description |
|
||||
|-------|-------------|
|
||||
| `tmdb` | TMDb seed matched |
|
||||
| `propagation` | Confirmed trace propagation |
|
||||
| `manual` | User manual selection |
|
||||
|
||||
#### Example face_track Node
|
||||
|
||||
```json
|
||||
{
|
||||
"node_type": "face_track",
|
||||
"external_id": "face_track_1",
|
||||
"label": "Face Track 1",
|
||||
"properties": {
|
||||
"trace_id": 1,
|
||||
"frame_count": 45,
|
||||
"start_frame": 100,
|
||||
"end_frame": 300,
|
||||
"avg_bbox": {"x": 100, "y": 200, "width": 80, "height": 100},
|
||||
"status": "suggested",
|
||||
"pending_identity_name": "Tom Hanks",
|
||||
"pending_identity_uuid": "xxx-xxx",
|
||||
"suggested_by": "tmdb",
|
||||
"confidence": 0.91
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Edge Types
|
||||
|
||||
| Edge Type | Storage Name | Source → Target | Description |
|
||||
|-----------|--------------|-----------------|-------------|
|
||||
| `co_occurs` | `CO_OCCURS_WITH` | object ↔ object | Two objects appear together in same frame |
|
||||
| `speaker_face` | `SPEAKS_AS` | speaker → face_track | Speaker matched to face track via lip sync |
|
||||
| `face_face` | `INTERACTS_WITH` | face_track ↔ face_track | Two face tracks interact (mutual gaze) |
|
||||
| `mutual_gaze` | `MUTUAL_GAZE` | gaze_track ↔ gaze_track | Two people looking at each other |
|
||||
| `lip_sync` | `LIP_SYNC` | lip_track → text_region | Lip movement aligned with spoken text |
|
||||
| `has_appearance` | `HAS_APPEARANCE` | face_track → appearance_trace | Face has specific appearance |
|
||||
| `wears` | `WEARS` | face_track → accessory | Face wears an accessory |
|
||||
| `hand_object` | `HOLDS` | hand → object | Hand holding object |
|
||||
|
||||
---
|
||||
|
||||
### `POST /api/v1/file/:file_uuid/tkg/rebuild`
|
||||
|
||||
**Auth**: Required
|
||||
**Scope**: file-level
|
||||
|
||||
Rebuild the Temporal Knowledge Graph for a file. Reads processor JSON outputs (face, yolo, ocr, pose, asrx, gaze, lip, appearance) and generates TKG nodes and edges. Clears existing nodes/edges for the file first, then rebuilds from scratch.
|
||||
|
||||
#### Example
|
||||
|
||||
```bash
|
||||
curl -s -X POST "$API/api/v1/file/$FILE_UUID/tkg/rebuild" \
|
||||
-H "X-API-Key: $KEY"
|
||||
```
|
||||
|
||||
#### Response (200)
|
||||
|
||||
```json
|
||||
{
|
||||
"success": true,
|
||||
"file_uuid": "d3f9ae8e471a1fc4d47022c66091b920",
|
||||
"result": {
|
||||
"face_track_nodes": 16,
|
||||
"gaze_track_nodes": 16,
|
||||
"lip_track_nodes": 12,
|
||||
"text_region_nodes": 24,
|
||||
"appearance_trace_nodes": 8,
|
||||
"skin_tone_trace_nodes": 5,
|
||||
"accessory_nodes": 3,
|
||||
"object_nodes": 26,
|
||||
"speaker_nodes": 4,
|
||||
"co_occurrence_edges": 94,
|
||||
"speaker_face_edges": 12,
|
||||
"face_face_edges": 8,
|
||||
"mutual_gaze_edges": 2,
|
||||
"lip_sync_edges": 10,
|
||||
"has_appearance_edges": 16,
|
||||
"wears_edges": 3
|
||||
},
|
||||
"error": null
|
||||
}
|
||||
```
|
||||
|
||||
| Field | Type | Description |
|
||||
|-------|------|-------------|
|
||||
| `success` | boolean | True if rebuild completed |
|
||||
| `file_uuid` | string | 32-char hex UUID |
|
||||
| `result` | object | Node and edge counts by type |
|
||||
| `error` | string/null | Error message if failed |
|
||||
|
||||
---
|
||||
|
||||
### `POST /api/v1/file/:file_uuid/tkg/nodes`
|
||||
|
||||
**Auth**: Required
|
||||
**Scope**: file-level
|
||||
|
||||
Query TKG nodes with pagination and optional type filter.
|
||||
|
||||
#### Request Parameters
|
||||
|
||||
| Field | Type | Required | Default | Description |
|
||||
|-------|------|----------|---------|-------------|
|
||||
| `node_type` | string | No | all | Filter by node type: `face_track`, `gaze_track`, `lip_track`, `text_region`, `appearance_trace`, `skin_tone_trace`, `accessory`, `object`, `speaker` |
|
||||
| `page` | integer | No | 1 | Page number |
|
||||
| `page_size` | integer | No | 100 | Items per page (max 500) |
|
||||
|
||||
#### Example
|
||||
|
||||
```bash
|
||||
# Get all face_track nodes
|
||||
curl -s -X POST "$API/api/v1/file/$FILE_UUID/tkg/nodes" \
|
||||
-H "X-API-Key: $KEY" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{"node_type": "face_track", "page": 1, "page_size": 50}'
|
||||
|
||||
# Get all nodes
|
||||
curl -s -X POST "$API/api/v1/file/$FILE_UUID/tkg/nodes" \
|
||||
-H "X-API-Key: $KEY" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{}'
|
||||
```
|
||||
|
||||
#### Response (200)
|
||||
|
||||
```json
|
||||
{
|
||||
"success": true,
|
||||
"file_uuid": "d3f9ae8e471a1fc4d47022c66091b920",
|
||||
"total": 16,
|
||||
"page": 1,
|
||||
"page_size": 50,
|
||||
"nodes": [
|
||||
{
|
||||
"id": 1,
|
||||
"node_type": "face_track",
|
||||
"external_id": "face_track_0",
|
||||
"label": "Face Track 0",
|
||||
"properties": {
|
||||
"trace_id": 0,
|
||||
"frame_count": 142,
|
||||
"avg_confidence": 0.87,
|
||||
"best_confidence": 0.92,
|
||||
"avg_capture_quality": 0.61,
|
||||
"best_capture_quality": 0.78,
|
||||
"key_frame": 120,
|
||||
"key_face": "tkg:face/0:point_xyz",
|
||||
"avg_bbox": {"x": 200, "y": 150, "width": 60, "height": 60},
|
||||
"best_bbox": {"x": 210, "y": 155, "width": 62, "height": 60}
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
| Field | Type | Description |
|
||||
|-------|------|-------------|
|
||||
| `success` | boolean | Always true on 200 |
|
||||
| `file_uuid` | string | 32-char hex UUID |
|
||||
| `total` | integer | Total matching node count |
|
||||
| `page` | integer | Current page |
|
||||
| `page_size` | integer | Items per page |
|
||||
| `nodes` | array | Array of node objects |
|
||||
| `nodes[].id` | integer | Database primary key |
|
||||
| `nodes[].node_type` | string | Node type (see table above) |
|
||||
| `nodes[].external_id` | string | External identifier (e.g., `trace_0`, `gaze_1`) |
|
||||
| `nodes[].label` | string | Human-readable label |
|
||||
| `nodes[].properties` | object | Type-specific properties as JSON |
|
||||
|
||||
---
|
||||
|
||||
### `POST /api/v1/file/:file_uuid/tkg/edges`
|
||||
|
||||
**Auth**: Required
|
||||
**Scope**: file-level
|
||||
|
||||
Query TKG edges with pagination and optional filters.
|
||||
|
||||
#### Request Parameters
|
||||
|
||||
| Field | Type | Required | Default | Description |
|
||||
|-------|------|----------|---------|-------------|
|
||||
| `edge_type` | string | No | all | Filter by edge type: `co_occurs`, `speaker_face`, `face_face`, `mutual_gaze`, `lip_sync`, `has_appearance`, `wears` |
|
||||
| `source_type` | string | No | — | Filter by source node type |
|
||||
| `target_type` | string | No | — | Filter by target node type |
|
||||
| `page` | integer | No | 1 | Page number |
|
||||
| `page_size` | integer | No | 100 | Items per page (max 500) |
|
||||
|
||||
#### Example
|
||||
|
||||
```bash
|
||||
# Get all co_occurs edges
|
||||
curl -s -X POST "$API/api/v1/file/$FILE_UUID/tkg/edges" \
|
||||
-H "X-API-Key: $KEY" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{"edge_type": "co_occurs"}'
|
||||
|
||||
# Get edges between face_track and speaker nodes
|
||||
curl -s -X POST "$API/api/v1/file/$FILE_UUID/tkg/edges" \
|
||||
-H "X-API-Key: $KEY" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{"source_type": "speaker", "target_type": "face_track"}'
|
||||
```
|
||||
|
||||
#### Response (200)
|
||||
|
||||
```json
|
||||
{
|
||||
"success": true,
|
||||
"file_uuid": "d3f9ae8e471a1fc4d47022c66091b920",
|
||||
"total": 94,
|
||||
"page": 1,
|
||||
"page_size": 100,
|
||||
"edges": [
|
||||
{
|
||||
"id": 1,
|
||||
"edge_type": "co_occurs",
|
||||
"source_node_id": 10,
|
||||
"target_node_id": 15,
|
||||
"properties": {
|
||||
"frame_count": 45,
|
||||
"confidence": 0.92
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
| Field | Type | Description |
|
||||
|-------|------|-------------|
|
||||
| `success` | boolean | Always true on 200 |
|
||||
| `file_uuid` | string | 32-char hex UUID |
|
||||
| `total` | integer | Total matching edge count |
|
||||
| `page` | integer | Current page |
|
||||
| `page_size` | integer | Items per page |
|
||||
| `edges` | array | Array of edge objects |
|
||||
| `edges[].id` | integer | Database primary key |
|
||||
| `edges[].edge_type` | string | Edge type |
|
||||
| `edges[].source_node_id` | integer | Source node ID (FK to tkg_nodes) |
|
||||
| `edges[].target_node_id` | integer | Target node ID (FK to tkg_nodes) |
|
||||
| `edges[].properties` | object | Edge-specific properties as JSON |
|
||||
|
||||
---
|
||||
|
||||
### `GET /api/v1/file/:file_uuid/tkg/node/:node_id`
|
||||
|
||||
**Auth**: Required
|
||||
**Scope**: file-level
|
||||
|
||||
Get detail for a specific TKG node including its connected edges.
|
||||
|
||||
#### Example
|
||||
|
||||
```bash
|
||||
curl -s "$API/api/v1/file/$FILE_UUID/tkg/node/1" \
|
||||
-H "X-API-Key: $KEY"
|
||||
```
|
||||
|
||||
#### Response (200)
|
||||
|
||||
```json
|
||||
{
|
||||
"success": true,
|
||||
"node": {
|
||||
"id": 1,
|
||||
"node_type": "face_track",
|
||||
"external_id": "face_track_0",
|
||||
"label": "Face Track 0",
|
||||
"properties": {
|
||||
"trace_id": 0,
|
||||
"frame_count": 142,
|
||||
"avg_confidence": 0.87
|
||||
}
|
||||
},
|
||||
"connected_edges": [
|
||||
{
|
||||
"id": 5,
|
||||
"edge_type": "co_occurs",
|
||||
"source_node_id": 1,
|
||||
"target_node_id": 10,
|
||||
"properties": {"frame_count": 45}
|
||||
}
|
||||
],
|
||||
"edge_count": 3
|
||||
}
|
||||
```
|
||||
|
||||
| Field | Type | Description |
|
||||
|-------|------|-------------|
|
||||
| `success` | boolean | Always true on 200 |
|
||||
| `node` | object | Node detail (same format as nodes query) |
|
||||
| `connected_edges` | array | Edges connected to this node |
|
||||
| `edge_count` | integer | Total connected edge count |
|
||||
|
||||
#### Error Codes
|
||||
|
||||
| HTTP | When |
|
||||
|------|------|
|
||||
| `404` | Node not found |
|
||||
|
||||
---
|
||||
|
||||
### `GET /api/v1/file/:file_uuid/processor-counts`
|
||||
|
||||
**Auth**: Required
|
||||
**Scope**: file-level
|
||||
|
||||
Get counts of processor JSON output files for a file. Scans the output directory for `{file_uuid}.{processor}.json` files and extracts frame counts, segment counts, and chunk counts from each file.
|
||||
|
||||
Supports short UUID prefix matching (e.g., `d3f9ae8e` → resolves to full `d3f9ae8e471a1fc4d47022c66091b920`).
|
||||
|
||||
#### Example
|
||||
|
||||
```bash
|
||||
curl -s "$API/api/v1/file/$FILE_UUID/processor-counts" \
|
||||
-H "X-API-Key: $KEY"
|
||||
```
|
||||
|
||||
#### Response (200)
|
||||
|
||||
```json
|
||||
{
|
||||
"file_uuid": "d3f9ae8e471a1fc4d47022c66091b920",
|
||||
"output_dir": "/Users/accusys/momentry/output_dev",
|
||||
"processors": [
|
||||
{
|
||||
"processor": "cut",
|
||||
"has_json": true,
|
||||
"frame_count": 5391,
|
||||
"segment_count": null,
|
||||
"chunk_count": null,
|
||||
"last_modified": "2026-06-16T18:48:01.987241061+00:00"
|
||||
},
|
||||
{
|
||||
"processor": "face",
|
||||
"has_json": true,
|
||||
"frame_count": 1112,
|
||||
"segment_count": null,
|
||||
"chunk_count": null,
|
||||
"last_modified": "2026-06-18T17:21:37.408383765+00:00"
|
||||
},
|
||||
{
|
||||
"processor": "asrx",
|
||||
"has_json": true,
|
||||
"frame_count": null,
|
||||
"segment_count": 6,
|
||||
"chunk_count": null,
|
||||
"last_modified": "2026-06-18T17:21:40.872063642+00:00"
|
||||
},
|
||||
{
|
||||
"processor": "story",
|
||||
"has_json": true,
|
||||
"frame_count": null,
|
||||
"segment_count": null,
|
||||
"chunk_count": 12,
|
||||
"last_modified": "2026-06-18T17:22:00.000000000+00:00"
|
||||
},
|
||||
{
|
||||
"processor": "mediapipe",
|
||||
"has_json": false,
|
||||
"frame_count": null,
|
||||
"segment_count": null,
|
||||
"chunk_count": null,
|
||||
"last_modified": null
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
| Field | Type | Description |
|
||||
|-------|------|-------------|
|
||||
| `file_uuid` | string | Full 32-char hex UUID (resolved from prefix) |
|
||||
| `output_dir` | string | Output directory scanned |
|
||||
| `processors` | array | Per-processor output info |
|
||||
| `processors[].processor` | string | Processor name |
|
||||
| `processors[].has_json` | boolean | Whether JSON file exists |
|
||||
| `processors[].frame_count` | integer/null | Total frames processed (frame-based processors) |
|
||||
| `processors[].segment_count` | integer/null | Segment count (ASRX segments, etc.) |
|
||||
| `processors[].chunk_count` | integer/null | Chunk count (Story chunks, etc.) |
|
||||
| `processors[].last_modified` | string/null | ISO 8601 timestamp of last modification |
|
||||
|
||||
#### Error Codes
|
||||
|
||||
| HTTP | When |
|
||||
|------|------|
|
||||
| `404` | File UUID not found in database |
|
||||
|
||||
---
|
||||
|
||||
### Trace Management
|
||||
|
||||
Endpoints for managing face traces: list, delete, restore, and merge.
|
||||
|
||||
#### `DELETE /api/v1/file/:file_uuid/trace/:trace_id`
|
||||
|
||||
**Auth**: Required
|
||||
|
||||
Soft-delete a face trace (default) or hard-delete with `{"hard_delete": true}`.
|
||||
|
||||
Soft delete marks Qdrant points with `status: "deleted"` and TKG nodes with `status: "deleted"` in properties. Deleted traces are excluded from the traces list.
|
||||
|
||||
Hard delete permanently removes Qdrant points and TKG nodes.
|
||||
|
||||
**Request Body** (optional):
|
||||
|
||||
| Field | Type | Default | Description |
|
||||
|-------|------|---------|-------------|
|
||||
| `hard_delete` | boolean | `false` | Permanently delete instead of marking |
|
||||
|
||||
**Example**:
|
||||
```bash
|
||||
# Soft delete
|
||||
curl -X DELETE "$API/api/v1/file/$FILE_UUID/trace/8" \
|
||||
-H "X-API-Key: $KEY" -H "Content-Type: application/json" -d '{}'
|
||||
|
||||
# Hard delete
|
||||
curl -X DELETE "$API/api/v1/file/$FILE_UUID/trace/8" \
|
||||
-H "X-API-Key: $KEY" -H "Content-Type: application/json" \
|
||||
-d '{"hard_delete": true}'
|
||||
```
|
||||
|
||||
**Response**:
|
||||
```json
|
||||
{
|
||||
"success": true,
|
||||
"file_uuid": "9f6a9cd55a5809f977f5a6589b9045c5",
|
||||
"trace_id": 8,
|
||||
"hard_delete": false,
|
||||
"qdrant_marked": true,
|
||||
"tkg_nodes_marked": 1
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
#### `POST /api/v1/file/:file_uuid/trace/:trace_id/restore`
|
||||
|
||||
**Auth**: Required
|
||||
|
||||
Undo a soft-deleted trace. Clears `status: "deleted"` from Qdrant points and TKG node properties.
|
||||
|
||||
**Example**:
|
||||
```bash
|
||||
curl -X POST "$API/api/v1/file/$FILE_UUID/trace/8/restore" \
|
||||
-H "X-API-Key: $KEY"
|
||||
```
|
||||
|
||||
**Response**:
|
||||
```json
|
||||
{
|
||||
"success": true,
|
||||
"file_uuid": "9f6a9cd55a5809f977f5a6589b9045c5",
|
||||
"trace_id": 8,
|
||||
"qdrant_restored": true,
|
||||
"tkg_nodes_restored": 1
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
#### `POST /api/v1/file/:file_uuid/trace/:source_trace_id/merge/:target_trace_id`
|
||||
|
||||
**Auth**: Required
|
||||
|
||||
Merge all face points from source trace into target trace. Updates Qdrant `trace_id` and deletes source TKG node.
|
||||
|
||||
**Example**:
|
||||
```bash
|
||||
curl -X POST "$API/api/v1/file/$FILE_UUID/trace/16/merge/3" \
|
||||
-H "X-API-Key: $KEY"
|
||||
```
|
||||
|
||||
**Response**:
|
||||
```json
|
||||
{
|
||||
"success": true,
|
||||
"file_uuid": "9f6a9cd55a5809f977f5a6589b9045c5",
|
||||
"source_trace_id": 16,
|
||||
"target_trace_id": 3,
|
||||
"points_moved": 58,
|
||||
"tkg_nodes_deleted": 1
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
*Updated: 2026-07-21 01:00:00*
|
||||
*Updated: 2026-08-12 — face_track node properties now include capture_quality fields (avg/best) and key_frame/key_face are selected by best capture quality*
|
||||
@@ -0,0 +1,148 @@
|
||||
<!-- module: workspace -->
|
||||
<!-- description: Workspace checkout/checkin — lock, clear, restore file data -->
|
||||
<!-- depends: 04_lookup, 05_process -->
|
||||
|
||||
## Workspace Checkin/Checkout
|
||||
|
||||
Workspace checkin/checkout provides a transactional editing model for file data:
|
||||
- **Checkout**: Clears PG tables (face_detections, speaker_detections, pre_chunks) and Qdrant vectors, creating an isolated workspace SQLite for editing.
|
||||
- **Checkin**: Restores data from the workspace SQLite back to PG and Qdrant, marking the file as `Indexed`.
|
||||
|
||||
This allows safe concurrent editing — while a file is checked out, its main database records are cleared, preventing conflicts.
|
||||
|
||||
---
|
||||
|
||||
### `POST /api/v1/file/:file_uuid/checkout`
|
||||
|
||||
**Auth**: Required
|
||||
**Scope**: file-level
|
||||
|
||||
Checkout a file workspace. Clears face detections, speaker detections, pre_chunks from PostgreSQL, deletes Qdrant vectors, and creates a workspace SQLite database for isolated editing.
|
||||
|
||||
#### Example
|
||||
|
||||
```bash
|
||||
curl -s -X POST "$API/api/v1/file/$FILE_UUID/checkout" \
|
||||
-H "X-API-Key: $KEY"
|
||||
```
|
||||
|
||||
#### Response (200)
|
||||
|
||||
```json
|
||||
{
|
||||
"file_uuid": "d3f9ae8e471a1fc4d47022c66091b920",
|
||||
"rows_deleted": 1523,
|
||||
"status": "checked_out"
|
||||
}
|
||||
```
|
||||
|
||||
| Field | Type | Description |
|
||||
|-------|------|-------------|
|
||||
| `file_uuid` | string | 32-char hex UUID |
|
||||
| `rows_deleted` | integer | Total rows cleared from PG tables |
|
||||
| `status` | string | `"checked_out"` |
|
||||
|
||||
#### Error Responses
|
||||
|
||||
| HTTP | When |
|
||||
|------|------|
|
||||
| `500` | Checkout failed (DB error, workspace creation error) |
|
||||
|
||||
---
|
||||
|
||||
### `POST /api/v1/file/:file_uuid/checkin`
|
||||
|
||||
**Auth**: Required
|
||||
**Scope**: file-level
|
||||
|
||||
Checkin a file workspace. Restores face detections, speaker detections, pre_chunks from workspace SQLite back to PostgreSQL, re-indexes vectors to Qdrant, and sets video status to `Indexed`.
|
||||
|
||||
#### Example
|
||||
|
||||
```bash
|
||||
curl -s -X POST "$API/api/v1/file/$FILE_UUID/checkin" \
|
||||
-H "X-API-Key: $KEY"
|
||||
```
|
||||
|
||||
#### Response (200)
|
||||
|
||||
```json
|
||||
{
|
||||
"file_uuid": "d3f9ae8e471a1fc4d47022c66091b920",
|
||||
"pre_chunks_moved": 45,
|
||||
"face_detections_moved": 1200,
|
||||
"speaker_detections_moved": 320,
|
||||
"vectors_moved": 45,
|
||||
"status": "indexed"
|
||||
}
|
||||
```
|
||||
|
||||
| Field | Type | Description |
|
||||
|-------|------|-------------|
|
||||
| `file_uuid` | string | 32-char hex UUID |
|
||||
| `pre_chunks_moved` | integer | Pre-chunks restored from workspace |
|
||||
| `face_detections_moved` | integer | Face detections restored from workspace |
|
||||
| `speaker_detections_moved` | integer | Speaker detections restored from workspace |
|
||||
| `vectors_moved` | integer | Vectors re-indexed to Qdrant |
|
||||
| `status` | string | `"indexed"` |
|
||||
|
||||
#### Error Responses
|
||||
|
||||
| HTTP | When |
|
||||
|------|------|
|
||||
| `500` | Checkin failed (DB error, workspace not found, vector index error) |
|
||||
|
||||
---
|
||||
|
||||
### `GET /api/v1/file/:file_uuid/workspace`
|
||||
|
||||
**Auth**: Required
|
||||
**Scope**: file-level
|
||||
|
||||
Check if a workspace SQLite database exists for a file.
|
||||
|
||||
#### Example
|
||||
|
||||
```bash
|
||||
curl -s "$API/api/v1/file/$FILE_UUID/workspace" \
|
||||
-H "X-API-Key: $KEY"
|
||||
```
|
||||
|
||||
#### Response (200)
|
||||
|
||||
```json
|
||||
{
|
||||
"file_uuid": "d3f9ae8e471a1fc4d47022c66091b920",
|
||||
"exists": true
|
||||
}
|
||||
```
|
||||
|
||||
| Field | Type | Description |
|
||||
|-------|------|-------------|
|
||||
| `file_uuid` | string | 32-char hex UUID |
|
||||
| `exists` | boolean | True if workspace SQLite exists |
|
||||
|
||||
---
|
||||
|
||||
### Workflow
|
||||
|
||||
```
|
||||
REGISTERED ──→ CHECKED_OUT ──→ INDEXED
|
||||
│ │ │
|
||||
│ checkout checkin
|
||||
│ │ │
|
||||
│ clear PG + Qdrant restore from SQLite
|
||||
│ create workspace re-index vectors
|
||||
│ set status set status
|
||||
```
|
||||
|
||||
1. **Register** file → status: `REGISTERED`
|
||||
2. **Process** file → processors run, data stored in PG + Qdrant
|
||||
3. **Checkout** file → clear editable data, create workspace SQLite → status: `CHECKED_OUT`
|
||||
4. **Edit** workspace via Agent Search / identity binding
|
||||
5. **Checkin** file → restore from workspace SQLite → status: `INDEXED`
|
||||
6. **Rebuild TKG** if needed after checkin
|
||||
|
||||
---
|
||||
|
||||
*Updated: 2026-06-20 12:00:00*
|
||||
@@ -0,0 +1,545 @@
|
||||
<!-- module: progress -->
|
||||
<!-- description: Real-time progress tracking for processing pipeline, TKG build, and identity agent -->
|
||||
<!-- depends: 01_auth, 03_register, 05_process -->
|
||||
|
||||
# Progress Tracking — API Workspace Module
|
||||
|
||||
## Overview
|
||||
|
||||
The progress tracking system provides real-time visibility into all processing stages:
|
||||
|
||||
| System | Redis Key | Coverage |
|
||||
|--------|-----------|----------|
|
||||
| **Processor Progress** | `{prefix}progress:{file_uuid}` | 7 main processors (cut, asr, asrx, ocr, face, pose, appearance) |
|
||||
| **TKG Progress** | `{prefix}progress:{file_uuid}:tkg` | 18 TKG build phases (9 node types + 8 edge types + face_tracing) |
|
||||
| **Agent Progress** | `{prefix}progress:{file_uuid}:agent` | 5 Identity Agent phases |
|
||||
|
||||
---
|
||||
|
||||
## `POST /api/v1/progress/:file_uuid`
|
||||
|
||||
**Auth**: Required
|
||||
**Scope**: file-level
|
||||
|
||||
Get real-time processing progress including processor status, TKG build phases, and identity agent phases.
|
||||
|
||||
### Example
|
||||
|
||||
```bash
|
||||
curl -s -X POST "$API/api/v1/progress/$FILE_UUID" \
|
||||
-H "X-API-Key: $KEY" | jq '.'
|
||||
```
|
||||
|
||||
### Response (200)
|
||||
|
||||
```json
|
||||
{
|
||||
"file_uuid": "3a6c1865...",
|
||||
"overall_progress": 71,
|
||||
"cpu_percent": 45.2,
|
||||
"gpu_percent": 30.1,
|
||||
"memory_percent": 62.4,
|
||||
"processors": [
|
||||
{"name": "asr", "status": "complete", "progress": 100, "current": 0, "total": 0, "message": "done"},
|
||||
{"name": "face", "status": "complete", "progress": 100, "current": 0, "total": 0, "message": "done"},
|
||||
{"name": "pose", "status": "complete", "progress": 100, "current": 0, "total": 0, "message": "done"}
|
||||
],
|
||||
"tkg_progress": {
|
||||
"file_uuid": "3a6c1865...",
|
||||
"phase": "mutual_gaze_edges",
|
||||
"phase_index": 13,
|
||||
"total_phases": 18,
|
||||
"phase_progress": 0.8,
|
||||
"overall_progress": 0.72,
|
||||
"stats": {
|
||||
"total_faces": 1250,
|
||||
"traced_faces": 1250,
|
||||
"total_traces": 45,
|
||||
"face_track_nodes": 45,
|
||||
"gaze_track_nodes": 45,
|
||||
"lip_track_nodes": 12,
|
||||
"text_region_nodes": 8,
|
||||
"appearance_nodes": 38,
|
||||
"accessory_nodes": 5,
|
||||
"object_nodes": 156,
|
||||
"hand_nodes": 22,
|
||||
"speaker_nodes": 14,
|
||||
"co_occurrence_edges": 890,
|
||||
"speaker_face_edges": 120,
|
||||
"face_face_edges": 234,
|
||||
"mutual_gaze_edges": 67,
|
||||
"total_nodes": 345,
|
||||
"total_edges": 1311
|
||||
},
|
||||
"message": "67 mutual gaze edges",
|
||||
"updated_at": "2026-07-02T10:30:00Z"
|
||||
},
|
||||
"agent_progress": {
|
||||
"file_uuid": "3a6c1865...",
|
||||
"phase": "completed",
|
||||
"phase_index": 5,
|
||||
"total_phases": 5,
|
||||
"phase_progress": 1.0,
|
||||
"overall_progress": 1.0,
|
||||
"stats": {
|
||||
"total_faces": 1250,
|
||||
"total_traces": 45,
|
||||
"clusters": 18,
|
||||
"identities_created": 18,
|
||||
"tmdb_matches": 5,
|
||||
"speaker_bindings": 12,
|
||||
"confirmations": 18
|
||||
},
|
||||
"message": "Identity Agent processing completed",
|
||||
"updated_at": "2026-07-02T10:28:00Z"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Field Descriptions
|
||||
|
||||
#### Top Level
|
||||
|
||||
| Field | Type | Description |
|
||||
|-------|------|-------------|
|
||||
| `file_uuid` | string | 32-char hex UUID |
|
||||
| `overall_progress` | integer | Overall processor progress (0–100) |
|
||||
| `processors` | array | Per-processor status |
|
||||
| `tkg_progress` | object | TKG build progress (null if not started) |
|
||||
| `agent_progress` | object | Identity Agent progress (null if not started) |
|
||||
|
||||
#### TKG Progress Fields
|
||||
|
||||
| Field | Type | Description |
|
||||
|-------|------|-------------|
|
||||
| `phase` | string | Current phase name (see TKG Phases below) |
|
||||
| `phase_index` | integer | Current phase index (0–17) |
|
||||
| `total_phases` | integer | Total phases: 18 |
|
||||
| `phase_progress` | float | Progress within current phase (0.0–1.0) |
|
||||
| `overall_progress` | float | Overall TKG progress (0.0–1.0) |
|
||||
| `stats` | object | Counts for all node and edge types |
|
||||
| `message` | string | Human-readable status message |
|
||||
|
||||
#### TKG Phases (18 total)
|
||||
|
||||
| Index | Phase | Description |
|
||||
|-------|-------|-------------|
|
||||
| 0 | `face_tracing` | Populate trace_id from face.json |
|
||||
| 1 | `face_track_nodes` | Build face_track nodes |
|
||||
| 2 | `gaze_track_nodes` | Build gaze_track nodes |
|
||||
| 3 | `lip_track_nodes` | Build lip_track nodes |
|
||||
| 4 | `text_region_nodes` | Build text_region nodes |
|
||||
| 5 | `appearance_nodes` | Build appearance_trace nodes |
|
||||
| 6 | `accessory_nodes` | Build accessory nodes |
|
||||
| 7 | `object_nodes` | Build yolo_object nodes |
|
||||
| 8 | `hand_nodes` | Build hand nodes |
|
||||
| 9 | `speaker_nodes` | Build speaker nodes |
|
||||
| 10 | `co_occurrence_edges` | Build co_occurrence edges |
|
||||
| 11 | `speaker_face_edges` | Build speaker_face edges |
|
||||
| 12 | `face_face_edges` | Build face_face edges |
|
||||
| 13 | `mutual_gaze_edges` | Build mutual_gaze edges |
|
||||
| 14 | `lip_sync_edges` | Build lip_sync edges |
|
||||
| 15 | `has_appearance_edges` | Build has_appearance edges |
|
||||
| 16 | `wears_edges` | Build wears edges |
|
||||
| 17 | `hand_object_edges` | Build hand_object edges |
|
||||
|
||||
#### TKG Stats Fields
|
||||
|
||||
| Field | Type | Description |
|
||||
|-------|------|-------------|
|
||||
| `total_faces` | integer | Total face detections |
|
||||
| `traced_faces` | integer | Faces with trace_id assigned |
|
||||
| `total_traces` | integer | Unique trace count |
|
||||
| `face_track_nodes` | integer | Face track nodes created |
|
||||
| `gaze_track_nodes` | integer | Gaze track nodes created |
|
||||
| `lip_track_nodes` | integer | Lip track nodes created |
|
||||
| `text_region_nodes` | integer | Text region nodes created |
|
||||
| `appearance_nodes` | integer | Appearance trace nodes created |
|
||||
| `accessory_nodes` | integer | Accessory nodes created |
|
||||
| `object_nodes` | integer | YOLO object nodes created |
|
||||
| `hand_nodes` | integer | Hand nodes created |
|
||||
| `speaker_nodes` | integer | Speaker nodes created |
|
||||
| `co_occurrence_edges` | integer | Co-occurrence edges created |
|
||||
| `speaker_face_edges` | integer | Speaker-face edges created |
|
||||
| `face_face_edges` | integer | Face-face edges created |
|
||||
| `mutual_gaze_edges` | integer | Mutual gaze edges created |
|
||||
| `lip_sync_edges` | integer | Lip sync edges created |
|
||||
| `has_appearance_edges` | integer | Has-appearance edges created |
|
||||
| `wears_edges` | integer | Wears edges created |
|
||||
| `hand_object_edges` | integer | Hand-object edges created |
|
||||
| `total_nodes` | integer | Total nodes (sum of all node types) |
|
||||
| `total_edges` | integer | Total edges (sum of all edge types) |
|
||||
|
||||
---
|
||||
|
||||
## `GET /api/v1/stats/ingestion-status/:file_uuid`
|
||||
|
||||
**Auth**: Required
|
||||
**Scope**: file-level
|
||||
|
||||
Get detailed ingestion status showing completion of all 24 processing steps.
|
||||
|
||||
### Example
|
||||
|
||||
```bash
|
||||
curl -s "$API/api/v1/stats/ingestion-status/$FILE_UUID" \
|
||||
-H "X-API-Key: $KEY" | jq '.steps[] | {name, status, detail}'
|
||||
```
|
||||
|
||||
### Response (200)
|
||||
|
||||
```json
|
||||
{
|
||||
"file_uuid": "3a6c1865...",
|
||||
"steps": [
|
||||
{"name": "rule1_sentence", "status": "done", "detail": "156 sentence chunks"},
|
||||
{"name": "auto_vectorize", "status": "done", "detail": "156 embedded"},
|
||||
{"name": "face_track", "status": "done", "detail": "45 traces / 1250 detections"},
|
||||
{"name": "trace_chunks", "status": "done", "detail": "45 trace chunks"},
|
||||
{"name": "tkg_face_track", "status": "done", "detail": "45 nodes"},
|
||||
{"name": "tkg_gaze_track", "status": "done", "detail": "45 nodes"},
|
||||
{"name": "tkg_lip_track", "status": "done", "detail": "12 nodes"},
|
||||
{"name": "tkg_text_region", "status": "done", "detail": "8 nodes"},
|
||||
{"name": "tkg_appearance", "status": "done", "detail": "38 nodes"},
|
||||
{"name": "tkg_accessory", "status": "done", "detail": "5 nodes"},
|
||||
{"name": "tkg_object", "status": "done", "detail": "156 nodes"},
|
||||
{"name": "tkg_hand", "status": "done", "detail": "22 nodes"},
|
||||
{"name": "tkg_speaker", "status": "done", "detail": "14 nodes"},
|
||||
{"name": "tkg_co_occurrence", "status": "done", "detail": "890 edges"},
|
||||
{"name": "tkg_speaker_face", "status": "done", "detail": "120 edges"},
|
||||
{"name": "tkg_face_face", "status": "done", "detail": "234 edges"},
|
||||
{"name": "tkg_mutual_gaze", "status": "done", "detail": "67 edges"},
|
||||
{"name": "tkg_lip_sync", "status": "done", "detail": "12 edges"},
|
||||
{"name": "tkg_has_appearance", "status": "done", "detail": "38 edges"},
|
||||
{"name": "tkg_wears", "status": "done", "detail": "22 edges"},
|
||||
{"name": "tkg_hand_object", "status": "done", "detail": "18 edges"},
|
||||
{"name": "rule2_relationship", "status": "done", "detail": "1331 relationship chunks"},
|
||||
{"name": "identity_match", "status": "done", "detail": "18 identities matched"},
|
||||
{"name": "scene_metadata", "status": "done", "detail": null}
|
||||
],
|
||||
"related_identities": [
|
||||
{"uuid": "a9a901056d6b46ff92da0c3c1a57dff4", "name": "John Smith"}
|
||||
],
|
||||
"strangers": 3
|
||||
}
|
||||
```
|
||||
|
||||
### Step Descriptions
|
||||
|
||||
| Step | Status When Done |
|
||||
|------|-----------------|
|
||||
| `rule1_sentence` | sentence_count > 0 |
|
||||
| `auto_vectorize` | sentence_embedded > 0 |
|
||||
| `face_track` | trace_count > 0 |
|
||||
| `trace_chunks` | trace_chunks > 0 |
|
||||
| `tkg_face_track` → `tkg_speaker` | Node count > 0 (9 steps) |
|
||||
| `tkg_co_occurrence` → `tkg_hand_object` | Edge count > 0 (8 steps) |
|
||||
| `rule2_relationship` | relationship_chunks > 0 |
|
||||
| `identity_match` | identity_count > 0 |
|
||||
| `scene_metadata` | scene_meta.json exists |
|
||||
|
||||
---
|
||||
|
||||
## `POST /api/v1/file/:file_uuid/tkg/rebuild`
|
||||
|
||||
**Auth**: Required
|
||||
**Scope**: file-level
|
||||
|
||||
Manually trigger TKG rebuild. Automatically triggers Rule 2 ingestion after TKG completes.
|
||||
|
||||
### Example
|
||||
|
||||
```bash
|
||||
curl -s -X POST "$API/api/v1/file/$FILE_UUID/tkg/rebuild" \
|
||||
-H "X-API-Key: $KEY" \
|
||||
-H "Content-Type: application/json" -d '{}'
|
||||
```
|
||||
|
||||
### Response (200)
|
||||
|
||||
```json
|
||||
{
|
||||
"success": true,
|
||||
"message": "TKG rebuild started",
|
||||
"nodes": 345,
|
||||
"edges": 1311
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## `POST /api/v1/file/:file_uuid/rule2`
|
||||
|
||||
**Auth**: Required
|
||||
**Scope**: file-level
|
||||
|
||||
Manually trigger Rule 2 ingestion (TKG edges → relationship chunks).
|
||||
|
||||
### Example
|
||||
|
||||
```bash
|
||||
curl -s -X POST "$API/api/v1/file/$FILE_UUID/rule2" \
|
||||
-H "X-API-Key: $KEY" \
|
||||
-H "Content-Type: application/json" -d '{}'
|
||||
```
|
||||
|
||||
### Response (200)
|
||||
|
||||
```json
|
||||
{
|
||||
"success": true,
|
||||
"message": "Rule 2 ingestion: 1331 relationship chunks created",
|
||||
"rule2_count": 1331
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Processing Pipeline Flow
|
||||
|
||||
```
|
||||
1. Processors (concurrent)
|
||||
├── cut, asr, ocr, face, pose, appearance → complete
|
||||
└── asrx → after cut+asr
|
||||
|
||||
2. Post-Processor Triggers (automatic)
|
||||
├── Rule 1 Ingestion (ASR+OCR → sentence chunks)
|
||||
├── Face Trace + DB Store (face_traced.json → Qdrant trace_id)
|
||||
├── TMDb Face Matching (if enabled)
|
||||
├── Heuristic Scene Metadata
|
||||
├── Identity Agent (face + ASRX)
|
||||
└── TKG Build (automatic after processors complete)
|
||||
└── Rule 2 Ingestion (automatic after TKG)
|
||||
└── Relationship chunks vectorized
|
||||
|
||||
3. Completion
|
||||
└── Job marked completed when all ingestion steps done
|
||||
```
|
||||
|
||||
## Error Codes
|
||||
|
||||
| Code | HTTP | When |
|
||||
|------|------|------|
|
||||
| E001 | 400 | Invalid file_uuid format |
|
||||
| E002 | 404 | File not found |
|
||||
| E003 | 404 | No TKG data available |
|
||||
| E010 | 500 | Qdrant connection failed |
|
||||
| E011 | 500 | Database connection failed |
|
||||
|
||||
---
|
||||
|
||||
## `GET /api/v1/stats/pipeline/:file_uuid`
|
||||
|
||||
**Auth**: Required
|
||||
**Scope**: file-level
|
||||
|
||||
Get segmented pipeline progress with weighted stage breakdown. Shows overall progress as weighted sum of all pipeline stages.
|
||||
|
||||
### Pipeline Stages and Weights
|
||||
|
||||
| Stage | Weight | Description |
|
||||
|-------|--------|-------------|
|
||||
| `processors` | 30% | 7 concurrent processors (cut, asr, asrx, ocr, face, pose, appearance) |
|
||||
| `rule1_ingestion` | 5% | ASR+OCR → sentence chunks |
|
||||
| `face_tracing` | 5% | Face trace_id assignment |
|
||||
| `identity_agent` | 10% | Identity creation, TMDb matching, speaker binding |
|
||||
| `tkg_nodes` | 20% | TKG node building (9 node types) |
|
||||
| `tkg_edges` | 15% | TKG edge building (8 edge types) |
|
||||
| `rule2_ingestion` | 15% | TKG edges → relationship chunks |
|
||||
|
||||
### Example
|
||||
|
||||
```bash
|
||||
curl -s "$API/api/v1/stats/pipeline/$FILE_UUID" \
|
||||
-H "X-API-Key: $KEY" | jq '.'
|
||||
```
|
||||
|
||||
### Response (200)
|
||||
|
||||
```json
|
||||
{
|
||||
"file_uuid": "3a6c1865...",
|
||||
"overall_progress": 0.65,
|
||||
"stages": [
|
||||
{"name": "processors", "weight": 0.30, "progress": 1.0, "status": "completed", "detail": "7/7 complete"},
|
||||
{"name": "rule1_ingestion", "weight": 0.05, "progress": 1.0, "status": "completed", "detail": "156 chunks"},
|
||||
{"name": "face_tracing", "weight": 0.05, "progress": 1.0, "status": "completed", "detail": "45 traces"},
|
||||
{"name": "identity_agent", "weight": 0.10, "progress": 1.0, "status": "completed", "detail": "18 identities"},
|
||||
{"name": "tkg_nodes", "weight": 0.20, "progress": 1.0, "status": "completed", "detail": "345 nodes"},
|
||||
{"name": "tkg_edges", "weight": 0.15, "progress": 0.5, "status": "running", "detail": "mutual_gaze_edges: 67/8 expected"},
|
||||
{"name": "rule2_ingestion", "weight": 0.15, "progress": 0.0, "status": "pending", "detail": null}
|
||||
],
|
||||
"updated_at": "2026-07-02T10:30:00Z"
|
||||
}
|
||||
```
|
||||
|
||||
### Field Descriptions
|
||||
|
||||
| Field | Type | Description |
|
||||
|-------|------|-------------|
|
||||
| `file_uuid` | string | 32-char hex UUID |
|
||||
| `overall_progress` | float | Weighted sum of all stage progress (0.0–1.0) |
|
||||
| `stages` | array | Per-stage progress breakdown |
|
||||
| `stages[].name` | string | Stage name |
|
||||
| `stages[].weight` | float | Stage weight in overall progress |
|
||||
| `stages[].progress` | float | Stage completion (0.0–1.0) |
|
||||
| `stages[].status` | string | `"pending"`, `"running"`, `"completed"`, `"failed"` |
|
||||
| `stages[].detail` | string | Human-readable detail (optional) |
|
||||
| `updated_at` | string | ISO 8601 timestamp |
|
||||
|
||||
### Overall Progress Calculation
|
||||
|
||||
```
|
||||
overall_progress = Σ(stage.weight × stage.progress) for all stages
|
||||
```
|
||||
|
||||
Example calculation:
|
||||
- processors: 0.30 × 1.0 = 0.30
|
||||
- rule1_ingestion: 0.05 × 1.0 = 0.05
|
||||
- face_tracing: 0.05 × 1.0 = 0.05
|
||||
- identity_agent: 0.10 × 1.0 = 0.10
|
||||
- tkg_nodes: 0.20 × 1.0 = 0.20
|
||||
- tkg_edges: 0.15 × 0.5 = 0.075
|
||||
- rule2_ingestion: 0.15 × 0.0 = 0.0
|
||||
- **Total: 0.775 (77.5%)**
|
||||
|
||||
---
|
||||
|
||||
## `GET /api/v1/stats/file/:file_uuid`
|
||||
|
||||
**Auth**: Required
|
||||
**Scope**: file-level
|
||||
|
||||
Get comprehensive file statistics from all data sources: JSON processing status, PostgreSQL counts, Qdrant collections, TKG nodes/edges, and Identity Agent stats.
|
||||
|
||||
### Example
|
||||
|
||||
```bash
|
||||
curl -s "$API/api/v1/stats/file/$FILE_UUID" \
|
||||
-H "X-API-Key: $KEY" | jq '.'
|
||||
```
|
||||
|
||||
### Response (200)
|
||||
|
||||
```json
|
||||
{
|
||||
"file_uuid": "3a6c1865...",
|
||||
"file_name": "video.mp4",
|
||||
"status": "processing",
|
||||
"processors": [
|
||||
{"name": "asr", "status": "complete", "progress": 100, "message": "done"},
|
||||
{"name": "face", "status": "complete", "progress": 100, "message": "done"}
|
||||
],
|
||||
"postgres": {
|
||||
"sentence_chunks": 156,
|
||||
"trace_chunks": 45,
|
||||
"relationship_chunks": 1331,
|
||||
"identities": 18,
|
||||
"file_identities": 18
|
||||
},
|
||||
"qdrant": {
|
||||
"faces": 1250,
|
||||
"face_traces": 45,
|
||||
"face_identities": 18,
|
||||
"text_chunks": 4562,
|
||||
"speakers": 434
|
||||
},
|
||||
"tkg": {
|
||||
"total_nodes": 345,
|
||||
"total_edges": 1311,
|
||||
"face_track_nodes": 45,
|
||||
"gaze_track_nodes": 45,
|
||||
"lip_track_nodes": 12,
|
||||
"text_region_nodes": 8,
|
||||
"appearance_nodes": 38,
|
||||
"accessory_nodes": 5,
|
||||
"object_nodes": 156,
|
||||
"hand_nodes": 22,
|
||||
"speaker_nodes": 14,
|
||||
"co_occurrence_edges": 890,
|
||||
"speaker_face_edges": 120,
|
||||
"face_face_edges": 234,
|
||||
"mutual_gaze_edges": 67,
|
||||
"lip_sync_edges": 12,
|
||||
"has_appearance_edges": 38,
|
||||
"wears_edges": 22,
|
||||
"hand_object_edges": 18
|
||||
},
|
||||
"identity_agent": {
|
||||
"clusters": 18,
|
||||
"identities_created": 18,
|
||||
"tmdb_matches": 5,
|
||||
"speaker_bindings": 12,
|
||||
"confirmations": 18
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Field Descriptions
|
||||
|
||||
#### Top Level
|
||||
|
||||
| Field | Type | Description |
|
||||
|-------|------|-------------|
|
||||
| `file_uuid` | string | 32-char hex UUID |
|
||||
| `file_name` | string | Original filename |
|
||||
| `status` | string | File status: `registered`, `processing`, `completed`, `failed` |
|
||||
| `processors` | array | Per-processor status from processing_status JSONB |
|
||||
| `postgres` | object | PostgreSQL table counts |
|
||||
| `qdrant` | object | Qdrant collection point counts |
|
||||
| `tkg` | object | TKG node and edge counts by type |
|
||||
| `identity_agent` | object | Identity Agent statistics |
|
||||
|
||||
#### PostgreSQL Stats
|
||||
|
||||
| Field | Type | Description |
|
||||
|-------|------|-------------|
|
||||
| `sentence_chunks` | integer | Rule 1 sentence chunks count |
|
||||
| `trace_chunks` | integer | Face trace chunks count |
|
||||
| `relationship_chunks` | integer | Rule 2 relationship chunks count |
|
||||
| `identities` | integer | Unique identities bound to this file |
|
||||
| `file_identities` | integer | File-identity mapping records |
|
||||
|
||||
#### Qdrant Stats
|
||||
|
||||
| Field | Type | Description |
|
||||
|-------|------|-------------|
|
||||
| `faces` | integer | Total face points in `_faces` collection |
|
||||
| `face_traces` | integer | Unique trace IDs in `_faces` |
|
||||
| `face_identities` | integer | Unique identity IDs bound in `_faces` |
|
||||
| `text_chunks` | integer | Text chunk vectors in `momentry_*_rule1_v2` |
|
||||
| `speakers` | integer | Speaker segments in `momentry_*_speaker` |
|
||||
|
||||
#### TKG Stats
|
||||
|
||||
| Field | Type | Description |
|
||||
|-------|------|-------------|
|
||||
| `total_nodes` | integer | Sum of all node types |
|
||||
| `total_edges` | integer | Sum of all edge types |
|
||||
| `face_track_nodes` | integer | Face track nodes |
|
||||
| `gaze_track_nodes` | integer | Gaze track nodes |
|
||||
| `lip_track_nodes` | integer | Lip track nodes |
|
||||
| `text_region_nodes` | integer | Text region nodes |
|
||||
| `appearance_nodes` | integer | Appearance trace nodes |
|
||||
| `accessory_nodes` | integer | Accessory nodes |
|
||||
| `object_nodes` | integer | YOLO object nodes |
|
||||
| `hand_nodes` | integer | Hand nodes |
|
||||
| `speaker_nodes` | integer | Speaker nodes |
|
||||
| `co_occurrence_edges` | integer | Co-occurrence edges |
|
||||
| `speaker_face_edges` | integer | Speaker-face edges |
|
||||
| `face_face_edges` | integer | Face-face edges |
|
||||
| `mutual_gaze_edges` | integer | Mutual gaze edges |
|
||||
| `lip_sync_edges` | integer | Lip sync edges |
|
||||
| `has_appearance_edges` | integer | Has-appearance edges |
|
||||
| `wears_edges` | integer | Wears edges |
|
||||
| `hand_object_edges` | integer | Hand-object edges |
|
||||
|
||||
#### Identity Agent Stats
|
||||
|
||||
| Field | Type | Description |
|
||||
|-------|------|-------------|
|
||||
| `clusters` | integer | Face clusters from face_clustered.json |
|
||||
| `identities_created` | integer | Identities created from clusters |
|
||||
| `tmdb_matches` | integer | TMDb identity matches |
|
||||
| `speaker_bindings` | integer | Speaker-to-identity bindings |
|
||||
| `confirmations` | integer | Confirmed identity bindings |
|
||||
@@ -0,0 +1,476 @@
|
||||
<!-- module: profile -->
|
||||
<!-- description: Trace profile and file profile management — read/update face trace names, key frames, aliases, and file paths -->
|
||||
<!-- depends: 01_auth, 07_identity, 15_tkg -->
|
||||
|
||||
## Profile Management
|
||||
|
||||
Endpoints for managing trace profiles (face track metadata stored in TKG) and file profiles (video metadata stored in PostgreSQL).
|
||||
|
||||
---
|
||||
|
||||
## Terminology
|
||||
|
||||
### Core Concepts
|
||||
|
||||
| Term | Definition | Identifier | Display Format |
|
||||
|------|------------|------------|----------------|
|
||||
| **Face** | A single human face detection on one frame | `face_id` | Usually not displayed |
|
||||
| **Face Sequence (Trace)** | A collection of faces across multiple frames representing the same person | `trace_id` | `FS#233` |
|
||||
| **Face Group** | A collection of traces sharing the same name/label | `label` (string) | `"Person A"` |
|
||||
|
||||
### Data Model Hierarchy
|
||||
|
||||
```
|
||||
Video
|
||||
└── Frame (F#233, F#234, ...) ← Single frame number
|
||||
└── Face ← Single detection (bbox + confidence)
|
||||
└── Face Sequence / Trace ← Same person across frames (FS#233)
|
||||
└── Face Group ← Multiple traces with same name
|
||||
```
|
||||
|
||||
### Example
|
||||
|
||||
```
|
||||
Video: "interview.mp4"
|
||||
├── Frame F#100
|
||||
│ └── Face (bbox: {100, 200, 50, 50}, confidence: 0.95)
|
||||
├── Frame F#105
|
||||
│ └── Face (bbox: {110, 205, 48, 48}, confidence: 0.92)
|
||||
├── Frame F#110
|
||||
│ └── Face (bbox: {115, 210, 52, 52}, confidence: 0.88)
|
||||
...
|
||||
|
||||
Face Sequence FS#233 = [Face@F#100, Face@F#105, Face@F#110, ...]
|
||||
↓
|
||||
Face Group "Person A" = [FS#233, FS#234, FS#235]
|
||||
```
|
||||
|
||||
### Storage
|
||||
|
||||
| Entity | Storage | Table/Collection |
|
||||
|--------|---------|------------------|
|
||||
| Face | Qdrant | `_faces` collection |
|
||||
| Face Sequence / Trace | PostgreSQL (TKG) | `tkg_nodes` where `node_type='face_track'` |
|
||||
| Face Group | PostgreSQL (TKG) | `tkg_nodes.label` field |
|
||||
|
||||
### Operations
|
||||
|
||||
| Operation | Level | API |
|
||||
|-----------|-------|-----|
|
||||
| View faces | Face | Internal (embedded in trace data) |
|
||||
| Merge traces | Trace | `POST /api/v1/trace/:file_uuid/merge` |
|
||||
| Rename group | Group | `PUT /api/v1/trace-profile/group` |
|
||||
| Merge groups | Group | `POST /api/v1/file/:file_uuid/groups/merge` |
|
||||
|
||||
### Naming Convention
|
||||
|
||||
- **Frame**: `F#{number}` — e.g., `F#233`
|
||||
- **Face Sequence / Trace**: `FS#{number}` — e.g., `FS#233`
|
||||
- **Face Group**: String name — e.g., `"Person A"`, `"Speaker 1"`
|
||||
|
||||
### `GET /api/v1/trace-profile`
|
||||
|
||||
**Auth**: Required
|
||||
**Scope**: file-level
|
||||
|
||||
Read a single face trace's profile including name, key frame, key face, and multi-language aliases.
|
||||
|
||||
#### Request Parameters
|
||||
|
||||
| Field | Type | Required | Description |
|
||||
|-------|------|----------|-------------|
|
||||
| `file_uuid` | string | Yes | File UUID |
|
||||
| `trace_id` | integer | Yes | Trace ID (numeric) |
|
||||
|
||||
#### Example
|
||||
|
||||
```bash
|
||||
curl -s "$API/api/v1/trace-profile?file_uuid=$FILE_UUID&trace_id=7" \
|
||||
-H "X-API-Key: $KEY"
|
||||
```
|
||||
|
||||
#### Response (200)
|
||||
|
||||
```json
|
||||
{
|
||||
"file_uuid": "9f6a9cd55a5809f977f5a6589b9045c5",
|
||||
"trace_id": 7,
|
||||
"name": "John Doe",
|
||||
"key_frame": 640,
|
||||
"key_face": "face_12345",
|
||||
"aliases": {
|
||||
"en": "John Doe",
|
||||
"zh": "約翰"
|
||||
},
|
||||
"properties": {
|
||||
"status": "bound",
|
||||
"avg_bbox": {"x": 899, "y": 212, "width": 342, "height": 342},
|
||||
"start_frame": 624,
|
||||
"end_frame": 669,
|
||||
"frame_count": 5
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
| Field | Type | Description |
|
||||
|-------|------|-------------|
|
||||
| `file_uuid` | string | File UUID |
|
||||
| `trace_id` | integer | Trace ID |
|
||||
| `name` | string | Display name (from `tkg_nodes.label`) |
|
||||
| `key_frame` | integer | Representative frame number, or null |
|
||||
| `key_face` | string | Representative face ID, or null |
|
||||
| `aliases` | object | Multi-language name aliases |
|
||||
| `properties` | object | Full TKG node properties (bbox, frames, etc.) |
|
||||
|
||||
#### Error Responses
|
||||
|
||||
| HTTP | When |
|
||||
|------|------|
|
||||
| `404` | Trace not found |
|
||||
| `401` | Missing or invalid API key |
|
||||
|
||||
---
|
||||
|
||||
### `PUT /api/v1/trace-profile`
|
||||
|
||||
**Auth**: Required
|
||||
**Scope**: file-level
|
||||
|
||||
Update a single face trace's profile fields. Only provided fields are updated; others remain unchanged.
|
||||
|
||||
#### Request Body
|
||||
|
||||
| Field | Type | Required | Description |
|
||||
|-------|------|----------|-------------|
|
||||
| `file_uuid` | string | Yes | File UUID |
|
||||
| `trace_id` | integer | Yes | Trace ID to update |
|
||||
| `name` | string | No | New display name |
|
||||
| `key_frame` | integer | No | Representative frame number |
|
||||
| `key_face` | string | No | Representative face ID |
|
||||
| `aliases` | object | No | Multi-language aliases `{"en": "...", "zh": "..."}` |
|
||||
| `properties` | object | No | Additional properties to merge into existing JSONB |
|
||||
|
||||
#### Example
|
||||
|
||||
```bash
|
||||
curl -s -X PUT "$API/api/v1/trace-profile" \
|
||||
-H "X-API-Key: $KEY" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{
|
||||
"file_uuid": "9f6a9cd55a5809f977f5a6589b9045c5",
|
||||
"trace_id": 7,
|
||||
"name": "John Doe",
|
||||
"key_frame": 640,
|
||||
"key_face": "face_12345",
|
||||
"aliases": {"en": "John Doe", "zh": "約翰"}
|
||||
}'
|
||||
```
|
||||
|
||||
#### Response (200)
|
||||
|
||||
```json
|
||||
{
|
||||
"success": true,
|
||||
"message": "Trace profile updated",
|
||||
"file_uuid": "9f6a9cd55a5809f977f5a6589b9045c5",
|
||||
"trace_id": 7
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### `PUT /api/v1/trace-profile/group`
|
||||
|
||||
**Auth**: Required
|
||||
**Scope**: file-level
|
||||
|
||||
Batch update the `name` (label) for multiple traces in a face group. Used when renaming a group.
|
||||
|
||||
#### Request Body
|
||||
|
||||
| Field | Type | Required | Description |
|
||||
|-------|------|----------|-------------|
|
||||
| `file_uuid` | string | Yes | File UUID |
|
||||
| `trace_ids` | integer[] | Yes | List of trace IDs to update |
|
||||
| `name` | string | Yes | New group name for all traces |
|
||||
|
||||
#### Example
|
||||
|
||||
```bash
|
||||
curl -s -X PUT "$API/api/v1/trace-profile/group" \
|
||||
-H "X-API-Key: $KEY" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{
|
||||
"file_uuid": "9f6a9cd55a5809f977f5a6589b9045c5",
|
||||
"trace_ids": [7, 2, 13],
|
||||
"name": "Group A"
|
||||
}'
|
||||
```
|
||||
|
||||
#### Response (200)
|
||||
|
||||
```json
|
||||
{
|
||||
"success": true,
|
||||
"message": "Updated 3 traces in group",
|
||||
"file_uuid": "9f6a9cd55a5809f977f5a6589b9045c5",
|
||||
"updated_count": 3
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### `POST /api/v1/file/:file_uuid/groups/merge`
|
||||
|
||||
**Auth**: Required
|
||||
**Scope**: file-level
|
||||
|
||||
Merge multiple face groups into one target group. All traces from source groups are reassigned to the target group name.
|
||||
|
||||
#### Request Body
|
||||
|
||||
| Field | Type | Required | Description |
|
||||
|-------|------|----------|-------------|
|
||||
| `file_uuid` | string | Yes | File UUID |
|
||||
| `source_groups` | string[] | Yes | List of group names to merge from |
|
||||
| `target_group_name` | string | Yes | Target group name to merge into |
|
||||
|
||||
#### Examples
|
||||
|
||||
**Merge 2 groups**:
|
||||
|
||||
```bash
|
||||
curl -s -X POST "$API/api/v1/file/$FILE_UUID/groups/merge" \
|
||||
-H "X-API-Key: $KEY" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{
|
||||
"file_uuid": "c36f35685177c981aa139b66bbbccc5b",
|
||||
"source_groups": ["Person A"],
|
||||
"target_group_name": "Person B"
|
||||
}'
|
||||
```
|
||||
|
||||
**Merge 4 groups**:
|
||||
|
||||
```bash
|
||||
curl -s -X POST "$API/api/v1/file/$FILE_UUID/groups/merge" \
|
||||
-H "X-API-Key: $KEY" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{
|
||||
"file_uuid": "c36f35685177c981aa139b66bbbccc5b",
|
||||
"source_groups": ["Person A", "Person C", "Person D"],
|
||||
"target_group_name": "Person B"
|
||||
}'
|
||||
```
|
||||
|
||||
#### Response (200)
|
||||
|
||||
```json
|
||||
{
|
||||
"success": true,
|
||||
"file_uuid": "c36f35685177c981aa139b66bbbccc5b",
|
||||
"source_groups": ["Person A", "Person C", "Person D"],
|
||||
"target_group_name": "Person B",
|
||||
"traces_merged": 12,
|
||||
"message": "Merged 3 group(s) into 'Person B'"
|
||||
}
|
||||
```
|
||||
|
||||
#### Error Responses
|
||||
|
||||
| HTTP | Condition |
|
||||
|------|-----------|
|
||||
| `400` | Target group in source_groups list |
|
||||
| `400` | Empty source_groups array |
|
||||
| `500` | Database error |
|
||||
|
||||
#### Behavior
|
||||
|
||||
1. Find all traces with `label IN (source_groups)`
|
||||
2. Update their labels to `target_group_name`
|
||||
3. All source groups disappear (no traces left)
|
||||
4. Target group contains all traces from merged groups
|
||||
|
||||
---
|
||||
|
||||
### Merging Groups: Two Methods
|
||||
|
||||
#### Method 1: Use Merge Groups API (Recommended)
|
||||
|
||||
```bash
|
||||
POST /api/v1/file/:file_uuid/groups/merge
|
||||
{
|
||||
"file_uuid": "...",
|
||||
"source_groups": ["Person A", "Person C"],
|
||||
"target_group_name": "Person B"
|
||||
}
|
||||
```
|
||||
|
||||
**Pros**: Simple, only requires group names, supports multi-group merge
|
||||
**Cons**: New API (requires backend update)
|
||||
|
||||
#### Method 2: Use Batch Update API (Existing)
|
||||
|
||||
```bash
|
||||
PUT /api/v1/trace-profile/group
|
||||
{
|
||||
"file_uuid": "...",
|
||||
"trace_ids": [13, 14, 15, 43, 44],
|
||||
"name": "Person B"
|
||||
}
|
||||
```
|
||||
|
||||
**Pros**: Works with existing API
|
||||
**Cons**: Frontend must collect all trace_ids from both groups
|
||||
|
||||
#### Example: Merge Group A and C into Group B
|
||||
|
||||
**Before**:
|
||||
```
|
||||
Group A: [13, 14, 15]
|
||||
Group B: [43, 44]
|
||||
Group C: [67, 68]
|
||||
```
|
||||
|
||||
**Method 1 (Recommended)**:
|
||||
```bash
|
||||
curl -X POST "$API/api/v1/file/$FILE_UUID/groups/merge" \
|
||||
-H "X-API-Key: $KEY" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{
|
||||
"file_uuid": "c36f35685177c981aa139b66bbbccc5b",
|
||||
"source_groups": ["Person A", "Person C"],
|
||||
"target_group_name": "Person B"
|
||||
}'
|
||||
```
|
||||
|
||||
**Method 2 (Existing API)**:
|
||||
```bash
|
||||
curl -X PUT "$API/api/v1/trace-profile/group" \
|
||||
-H "X-API-Key: $KEY" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{
|
||||
"file_uuid": "c36f35685177c981aa139b66bbbccc5b",
|
||||
"trace_ids": [13, 14, 15, 43, 44, 67, 68],
|
||||
"name": "Person B"
|
||||
}'
|
||||
```
|
||||
|
||||
**After**:
|
||||
```
|
||||
Group A: [] (disappeared)
|
||||
Group B: [43, 44, 13, 14, 15, 67, 68]
|
||||
Group C: [] (disappeared)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### `GET /api/v1/file-profile`
|
||||
|
||||
**Auth**: Required
|
||||
**Scope**: file-level
|
||||
|
||||
Read a file's metadata including path, name, status, and technical details.
|
||||
|
||||
#### Request Parameters
|
||||
|
||||
| Field | Type | Required | Description |
|
||||
|-------|------|----------|-------------|
|
||||
| `file_uuid` | string | Yes | File UUID |
|
||||
|
||||
#### Example
|
||||
|
||||
```bash
|
||||
curl -s "$API/api/v1/file-profile?file_uuid=$FILE_UUID" \
|
||||
-H "X-API-Key: $KEY"
|
||||
```
|
||||
|
||||
#### Response (200)
|
||||
|
||||
```json
|
||||
{
|
||||
"file_uuid": "49884ce1c341953d1ad7bf67a77c30cc",
|
||||
"file_name": "Dedicatoria.mp4",
|
||||
"file_path": "/Users/accusys/momentry/var/sftpgo/data/demo/Dedicatoria.mp4",
|
||||
"status": "completed",
|
||||
"duration": 93.33,
|
||||
"width": 1280,
|
||||
"height": 720,
|
||||
"fps": 30.0,
|
||||
"total_frames": 0
|
||||
}
|
||||
```
|
||||
|
||||
| Field | Type | Description |
|
||||
|-------|------|-------------|
|
||||
| `file_uuid` | string | File UUID |
|
||||
| `file_name` | string | File name |
|
||||
| `file_path` | string | Full filesystem path |
|
||||
| `status` | string | `pending`, `processing`, `completed`, `failed` |
|
||||
| `duration` | float | Duration in seconds |
|
||||
| `width` | integer | Video width in pixels |
|
||||
| `height` | integer | Video height in pixels |
|
||||
| `fps` | float | Frames per second |
|
||||
| `total_frames` | integer | Total frame count |
|
||||
|
||||
---
|
||||
|
||||
### `PUT /api/v1/file-profile`
|
||||
|
||||
**Auth**: Required
|
||||
**Scope**: file-level
|
||||
|
||||
Update file metadata, typically used when a file is moved to a new location.
|
||||
|
||||
#### Request Body
|
||||
|
||||
| Field | Type | Required | Description |
|
||||
|-------|------|----------|-------------|
|
||||
| `file_uuid` | string | Yes | File UUID |
|
||||
| `file_path` | string | No | New filesystem path |
|
||||
| `file_name` | string | No | New file name |
|
||||
|
||||
#### Example
|
||||
|
||||
```bash
|
||||
curl -s -X PUT "$API/api/v1/file-profile" \
|
||||
-H "X-API-Key: $KEY" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{
|
||||
"file_uuid": "49884ce1c341953d1ad7bf67a77c30cc",
|
||||
"file_path": "/new/location/Dedicatoria.mp4"
|
||||
}'
|
||||
```
|
||||
|
||||
#### Response (200)
|
||||
|
||||
```json
|
||||
{
|
||||
"success": true,
|
||||
"message": "File profile updated",
|
||||
"file_uuid": "49884ce1c341953d1ad7bf67a77c30cc"
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Data Storage
|
||||
|
||||
| Profile Type | Storage | Table |
|
||||
|-------------|---------|-------|
|
||||
| **trace_profile** | PostgreSQL (TKG) | `tkg_nodes` where `node_type='face_track'` |
|
||||
| **file_profile** | PostgreSQL | `videos` |
|
||||
|
||||
### Trace Profile Fields
|
||||
|
||||
| Field | TKG Column | Description |
|
||||
|-------|-----------|-------------|
|
||||
| `name` | `label` | Display name for the trace |
|
||||
| `key_frame` | `properties->'key_frame'` | Representative frame number |
|
||||
| `key_face` | `properties->'key_face'` | Representative face ID |
|
||||
| `aliases` | `properties->'aliases'` | Multi-language name aliases |
|
||||
|
||||
---
|
||||
*Updated: 2026-07-25 — Added Merge Groups API (POST /groups/merge), added Terminology section (Face, Face Sequence, Face Group)*
|
||||
*Updated: 2026-07-21 — Fixed external_id matching (trace_N + face_track_N formats), fixed parameter ordering in UPDATE query*
|
||||
*Updated: 2026-07-18 — New profile module: trace-profile (GET, PUT, PUT group) and file-profile (GET, PUT)*
|
||||
@@ -0,0 +1,400 @@
|
||||
# People API
|
||||
|
||||
**Version**: 2.1
|
||||
**Date**: 2026-08-12
|
||||
**Base URL**: `http://localhost:3002`
|
||||
**Auth**: Requires API key header (`Authorization: Bearer <api_key>`)
|
||||
**Doc Path**: `/Users/accusys/momentry_core/docs_v1.0/API_WORKSPACE/modules/19_people_api.md`
|
||||
|
||||
---
|
||||
|
||||
## 資料架構
|
||||
|
||||
### trace_profiles(PostgreSQL — People Search 專用)
|
||||
|
||||
每筆 `file_uuid + trace_id` 對應一個 face trace profile:
|
||||
|
||||
| 欄位 | 類型 | 說明 |
|
||||
|------|------|------|
|
||||
| `file_uuid` | string | 影片 UUID |
|
||||
| `trace_id` | integer | Face trace ID(8Hz 取樣追蹤) |
|
||||
| `name` | string | FS name(Face 頁面顯示 + People Search 搜尋) |
|
||||
| `start_frame` | integer | 起始 frame |
|
||||
| `end_frame` | integer | 結束 frame |
|
||||
| `frame_count` | integer | 追蹤 frame 數(8Hz 取樣,多數 > 1) |
|
||||
| `key_frame` | string | 關鍵幀圖片路徑 |
|
||||
| `key_face` | string | 關鍵人臉裁切路徑 |
|
||||
| `avg_confidence` | float | 平均偵測信心值 |
|
||||
| `status` | string | 狀態(pending/confirmed) |
|
||||
|
||||
### 可搜尋註記(metadata / VLM 欄位)
|
||||
|
||||
`trace_profiles` 包含 VLM 產生的註記,可用於進階搜尋和統計:
|
||||
|
||||
| 欄位 | 類型 | 說明 |
|
||||
|------|------|------|
|
||||
| `vlm_description` | text | VLM 人物外貌描述 |
|
||||
| `vlm_clothing` | text | VLM 衣著描述 |
|
||||
| `vlm_tags` | text[] | VLM 標籤陣列 |
|
||||
| `vlm_location` | string | VLM 地點 |
|
||||
| `vlm_setting` | string | VLM 場景設定 |
|
||||
| `vlm_lighting` | string | VLM 光線 |
|
||||
| `vlm_weather` | string | VLM 天氣 |
|
||||
| `vlm_background` | text | VLM 背景描述 |
|
||||
| `vlm_bg_tags` | text[] | VLM 背景標籤 |
|
||||
|
||||
### tkg_nodes(PostgreSQL — TKG 圖譜專用,與 profile 獨立)
|
||||
|
||||
| 欄位 | 說明 |
|
||||
|------|------|
|
||||
| `external_id` | 如 "trace_9",對應 `trace_profiles.trace_id` |
|
||||
| `label` | TKG 圖譜節點標籤(與 `trace_profiles.name` 獨立) |
|
||||
| `properties` | TKG 節點屬性 |
|
||||
|
||||
### _faces(Qdrant — Face 向量比對)
|
||||
|
||||
Face embedding 向量存在 Qdrant `_faces` collection,可用作 seed 比對:
|
||||
|
||||
| Payload 欄位 | 類型 | 說明 |
|
||||
|-------------|------|------|
|
||||
| `file_uuid` | string | 影片 UUID |
|
||||
| `trace_id` | integer | Face trace ID |
|
||||
| `identity_id` | integer \| null | 已綁定的 identity ID |
|
||||
| `frame` | integer | Frame 編號 |
|
||||
| `embedding` | vector[512] | FaceNet 512-d embedding |
|
||||
| `bbox` | object | 人臉 bbox(x, y, width, height) |
|
||||
| `confidence` | float | 偵測信心值 |
|
||||
|
||||
---
|
||||
|
||||
## 1. GET /api/v1/search/people
|
||||
|
||||
搜尋已命名的 face trace profiles。回傳符合 name 的卡片列表。
|
||||
|
||||
### Query Parameters
|
||||
|
||||
| Parameter | Type | Required | Description |
|
||||
|-----------|------|----------|-------------|
|
||||
| `query` | string | ✅ Yes | 搜尋關鍵字(ILIKE 模糊比對 `trace_profiles.name`) |
|
||||
| `file_uuid` | string | ❌ Optional | 限制搜尋範圍 |
|
||||
| `limit` | integer | ❌ Optional | 回傳筆數上限(預設 10) |
|
||||
|
||||
### Example Request
|
||||
|
||||
```bash
|
||||
# 搜尋名字
|
||||
curl -X GET "http://localhost:3002/api/v1/search/people?query=Susan"
|
||||
|
||||
# 搜尋 VLM 註記(衣著、地點、標籤)
|
||||
curl -X GET "http://localhost:3002/api/v1/search/people?query=blue+shirt"
|
||||
|
||||
# 限定影片
|
||||
curl -X GET "http://localhost:3002/api/v1/search/people?file_uuid=abc123&query=Tom"
|
||||
```
|
||||
|
||||
### 搜尋範圍
|
||||
|
||||
People Search 會搜尋以下欄位(ILIKE 模糊比對):
|
||||
|
||||
| 欄位 | 說明 |
|
||||
|------|------|
|
||||
| `name` | FS name |
|
||||
| `vlm_description` | VLM 人物外貌描述 |
|
||||
| `vlm_clothing` | VLM 衣著描述 |
|
||||
| `vlm_tags` | VLM 標籤陣列 |
|
||||
| `vlm_location` | VLM 地點 |
|
||||
| `vlm_setting` | VLM 場景設定 |
|
||||
|
||||
### Response
|
||||
|
||||
```json
|
||||
{
|
||||
"people": [
|
||||
{
|
||||
"file_uuid": "4655a0ab3c077e30c12b2298c2750650",
|
||||
"file_name": "",
|
||||
"trace_id": 9,
|
||||
"external_id": "trace_9",
|
||||
"name": "Susan",
|
||||
"start_frame": 118,
|
||||
"end_frame": 384,
|
||||
"frame_count": 39,
|
||||
"start_time": null,
|
||||
"end_time": null,
|
||||
"key_frame": "key_frame.jpg",
|
||||
"key_face": null,
|
||||
"avg_confidence": 0.694,
|
||||
"avg_capture_quality": 0.512,
|
||||
"best_capture_quality": 0.733
|
||||
}
|
||||
],
|
||||
"total": 18
|
||||
}
|
||||
```
|
||||
|
||||
### Response Fields
|
||||
|
||||
| Field | Type | Description |
|
||||
|-------|------|-------------|
|
||||
| `file_uuid` | string | 影片 UUID |
|
||||
| `trace_id` | integer | Face trace ID |
|
||||
| `external_id` | string \| null | TKG node external_id(如 "trace_9") |
|
||||
| `name` | string \| null | 使用者命名的 FS name |
|
||||
| `start_frame` | integer \| null | 起始 frame |
|
||||
| `end_frame` | integer \| null | 結束 frame |
|
||||
| `frame_count` | integer \| null | 追蹤 frame 數(8Hz 取樣) |
|
||||
| `start_time` | float \| null | 起始時間(秒) |
|
||||
| `end_time` | float \| null | 結束時間(秒) |
|
||||
| `key_frame` | string \| null | 關鍵幀圖片路徑 |
|
||||
| `key_face` | string \| null | 關鍵人臉裁切路徑 |
|
||||
| `avg_confidence` | float \| null | 平均偵測信心值 |
|
||||
| `avg_capture_quality` | float \| null | 平均畫面品質分數(清晰度,0~1) |
|
||||
| `best_capture_quality` | float \| null | 該 trace 最佳畫面品質分數 |
|
||||
|
||||
---
|
||||
|
||||
## 2. POST /api/v1/search/universal
|
||||
|
||||
統一搜尋。設定 `types: ["people"]` 搜尋人物,或組合 `"chunk"`、`"frame"`。
|
||||
|
||||
People Search 會搜尋 `trace_profiles` 的 `name` + `vlm_*` 欄位:
|
||||
- `name` — FS name
|
||||
- `vlm_description` — VLM 人物外貌描述
|
||||
- `vlm_clothing` — VLM 衣著描述
|
||||
- `vlm_tags` — VLM 標籤陣列
|
||||
- `vlm_location` — VLM 地點
|
||||
- `vlm_setting` — VLM 場景設定
|
||||
|
||||
### Request Body
|
||||
|
||||
```json
|
||||
{
|
||||
"query": "Susan",
|
||||
"file_uuid": "abc123",
|
||||
"types": ["people"],
|
||||
"page": 1,
|
||||
"page_size": 20
|
||||
}
|
||||
```
|
||||
|
||||
### Request Fields
|
||||
|
||||
| Field | Type | Required | Description |
|
||||
|-------|------|----------|-------------|
|
||||
| `query` | string | ✅ Yes | 搜尋關鍵字 |
|
||||
| `file_uuid` | string | ❌ Optional | 限制搜尋範圍 |
|
||||
| `types` | string[] | ❌ Optional | `["chunk", "frame", "people"]` — 預設全部 |
|
||||
| `page` | integer | ❌ Optional | 頁碼(預設 1) |
|
||||
| `page_size` | integer | ❌ Optional | 每頁筆數(預設 20,最大 200) |
|
||||
|
||||
### Response
|
||||
|
||||
```json
|
||||
{
|
||||
"query": "Susan",
|
||||
"results": [
|
||||
{
|
||||
"type": "person",
|
||||
"file_uuid": "4655a0ab3c077e30c12b2298c2750650",
|
||||
"trace_id": 9,
|
||||
"external_id": "trace_9",
|
||||
"name": "Susan",
|
||||
"frame_count": 39,
|
||||
"score": 0.95,
|
||||
"start_time": null,
|
||||
"end_time": null,
|
||||
"key_frame": "key_frame.jpg",
|
||||
"key_face": null
|
||||
}
|
||||
],
|
||||
"total": 18,
|
||||
"page": 1,
|
||||
"page_size": 20,
|
||||
"has_more": false
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 3. PUT /api/v1/trace-profile(單筆改名)
|
||||
|
||||
更新單一 face trace profile 的 name 和 metadata。
|
||||
|
||||
### Request Body
|
||||
|
||||
```json
|
||||
{
|
||||
"file_uuid": "4655a0ab3c077e30c12b2298c2750650",
|
||||
"trace_id": 9,
|
||||
"name": "Susan",
|
||||
"properties": { "custom_key": "custom_value" },
|
||||
"key_frame": "path/to/key_frame.jpg",
|
||||
"key_face": "path/to/key_face.jpg",
|
||||
"aliases": ["Susie", "Sue"]
|
||||
}
|
||||
```
|
||||
|
||||
### Request Fields
|
||||
|
||||
| Field | Type | Required | Description |
|
||||
|-------|------|----------|-------------|
|
||||
| `file_uuid` | string | ✅ Yes | 影片 UUID |
|
||||
| `trace_id` | integer | ✅ Yes | Face trace ID |
|
||||
| `name` | string | ❌ Optional | 新的 FS name |
|
||||
| `properties` | object | ❌ Optional | 自訂屬性(合併更新) |
|
||||
| `key_frame` | string | ❌ Optional | 關鍵幀路徑 |
|
||||
| `key_face` | string | ❌ Optional | 關鍵人臉路徑 |
|
||||
| `aliases` | string[] | ❌ Optional | 別名列表 |
|
||||
|
||||
---
|
||||
|
||||
## 4. PUT /api/v1/trace-profile/group(批次改名)
|
||||
|
||||
批次更新多個 face trace profiles 的 name。
|
||||
|
||||
### Request Body
|
||||
|
||||
```json
|
||||
{
|
||||
"file_uuid": "4655a0ab3c077e30c12b2298c2750650",
|
||||
"trace_ids": [9, 22, 5],
|
||||
"name": "Susan"
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 5. POST /api/v1/groups/merge(合併群組)
|
||||
|
||||
將多個 group 的 traces 合併為一個 group name。
|
||||
|
||||
### Request Body
|
||||
|
||||
```json
|
||||
{
|
||||
"file_uuid": "4655a0ab3c077e30c12b2298c2750650",
|
||||
"source_groups": ["Person_0", "Person_1"],
|
||||
"target_group_name": "Susan"
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Error Responses
|
||||
|
||||
### 400 Bad Request
|
||||
```json
|
||||
{ "error": "name is required" }
|
||||
```
|
||||
|
||||
### 401 Unauthorized
|
||||
```
|
||||
HTTP 401 (no body) — Missing or invalid API key
|
||||
```
|
||||
|
||||
### 404 Not Found
|
||||
```json
|
||||
{ "error": "Profile not found" }
|
||||
```
|
||||
|
||||
### 500 Internal Server Error
|
||||
```json
|
||||
{ "error": "DB error: connection refused" }
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 如何命名 Face Trace
|
||||
|
||||
使用 profile API 為 face trace 命名:
|
||||
|
||||
```bash
|
||||
curl -X PUT "http://localhost:3002/api/v1/trace-profile" \
|
||||
-H "Authorization: Bearer <api_key>" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{
|
||||
"file_uuid": "4655a0ab3c077e30c12b2298c2750650",
|
||||
"trace_id": 9,
|
||||
"name": "Susan"
|
||||
}'
|
||||
```
|
||||
|
||||
命名後即可透過 People Search API 搜尋:
|
||||
|
||||
```bash
|
||||
curl "http://localhost:3002/api/v1/search/people?query=Susan" \
|
||||
-H "Authorization: Bearer <api_key>"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Pipeline 狀態定義
|
||||
|
||||
所有檔案的 status 由 `/api/v1/file/{file_uuid}/sync-status` 自動更新,依據 processor outputs 和功能就緒狀態判定。
|
||||
|
||||
| Status | 前端顯示 | 條件 | 啟用功能 |
|
||||
|--------|---------|------|---------|
|
||||
| `registered` | 📋 已註冊 | 0 processor outputs | 檔案註冊 |
|
||||
| `scanning` | 🔍 掃描中 | 1-4/5 processor outputs | — |
|
||||
| `keyword_ready` | 🔎 關鍵字可用 | sentence chunks > 0 | Smart Search |
|
||||
| `semantic_ready` | 🧠 語意可用 | embedded chunks > 0 | Semantic Search |
|
||||
| `face_mgmt_ready` | 🎭 臉部管理可用 | face_trace + trace_profiles + tkg_nodes(face_track) | People Search, Face Profile 讀寫, Face Group |
|
||||
| `agent_ready` | 🤖 Agent 可用 | face_mgmt_ready + tkg_edges | Agent TKG Tools |
|
||||
| `completed` | ✅ 完成 | 5/5 processors + 全部功能就緒 | — |
|
||||
|
||||
### Face Management Ready 明確定義
|
||||
|
||||
`face_mgmt_ready` 表示檔案已具備完整臉部管理功能,需同時滿足以下四個條件:
|
||||
|
||||
| 依賴項 | 檢查條件 | 說明 | 提供功能 |
|
||||
|--------|---------|------|---------|
|
||||
| **Face Qdrant Ready** | `_faces` collection 有 face points | Face embeddings 已存入 Qdrant | 臉部比對、相似度搜尋 |
|
||||
| **Face Trace Ready** | `face_traced.json` 存在且有 traces | Face tracking 已完成 | 人臉軌跡資料 |
|
||||
| **Face Profile Ready** | `trace_profiles` 有紀錄 | Profile 資料已建立 | 名字、VLM 註記、key_frame/key_face |
|
||||
| **Face TKG Node Ready** | `tkg_nodes` 有 `face_track` nodes | TKG 圖譜節點已建立 | 臉部群組合併、關係查詢 |
|
||||
|
||||
#### 檢查 SQL
|
||||
|
||||
```sql
|
||||
-- Face Qdrant Ready
|
||||
SELECT COUNT(*) FROM _faces WHERE file_uuid = $1; -- > 0
|
||||
|
||||
-- Face Trace Ready
|
||||
-- 檢查 face_traced.json 檔案存在且有 traces
|
||||
|
||||
-- Face Profile Ready
|
||||
SELECT COUNT(*) FROM trace_profiles WHERE file_uuid = $1; -- > 0
|
||||
|
||||
-- Face TKG Node Ready
|
||||
SELECT COUNT(*) FROM tkg_nodes WHERE file_uuid = $1 AND node_type = 'face_track'; -- > 0
|
||||
```
|
||||
|
||||
#### 啟用功能清單
|
||||
|
||||
| 功能 | API Endpoint | 說明 |
|
||||
|------|-------------|------|
|
||||
| People Search | `GET /api/v1/search/people` | 搜尋已命名人臉 |
|
||||
| Face Profile 讀寫 | `PUT /api/v1/trace-profile` | 更新名字、VLM 註記 |
|
||||
| Face Group 合併 | `POST /api/v1/groups/merge` | 合併多個群組 |
|
||||
| Face Trace 改名 | `PUT /api/v1/trace-profile` | 為單個 trace 命名 |
|
||||
| Agent Face Search | Agent Tool: `face_profile_search` | Agent 搜尋人臉 |
|
||||
|
||||
---
|
||||
|
||||
### 狀態依賴關係
|
||||
|
||||
```
|
||||
registered → scanning → keyword_ready → semantic_ready
|
||||
↓
|
||||
face_mgmt_ready → agent_ready → completed
|
||||
```
|
||||
|
||||
### 每個階段對應的 Processor
|
||||
|
||||
| 階段 | 必要 Processor | 產出 |
|
||||
|------|---------------|------|
|
||||
| `keyword_ready` | ASR, ASRX | sentence chunks |
|
||||
| `semantic_ready` | keyword_ready + Vectorize | embedded chunks |
|
||||
| `face_mgmt_ready` | Face, FaceCluster | trace_profiles (People Search + Face Management) |
|
||||
| `agent_ready` | face_mgmt_ready + TKG Edges | tkg_edges |
|
||||
|
||||
@@ -0,0 +1,199 @@
|
||||
# Studio Team API 變更指南
|
||||
|
||||
**Version**: 1.0
|
||||
**Date**: 2026-07-26
|
||||
**Doc Path**: `/Users/accusys/momentry_core/docs_v1.0/API_WORKSPACE/modules/21_studio_team_guide.md`
|
||||
**目標**: 通知 Studio team 後端 API 狀態欄位變更,Momentry Studio 前端需配合更新
|
||||
|
||||
---
|
||||
|
||||
## 1. 概述
|
||||
|
||||
後端已將檔案狀態從技術術語改為**功能導向**名稱。Studio team 的 `~/momentry_studio/` 前端顯示邏輯需要更新。
|
||||
|
||||
**影響範圍:**
|
||||
- 後端 API:`/Users/accusys/momentry_core/src/api/files.rs`(Core team 已修改)
|
||||
- Studio 前端:`~/momentry_studio/`(需 Studio team 更新)
|
||||
|
||||
---
|
||||
|
||||
## 2. 團隊職責
|
||||
|
||||
| 團隊 | 負責專案 | 目錄 |
|
||||
|------|---------|------|
|
||||
| **Core team** | Momentry Core 後端 | `~/momentry_core/` |
|
||||
| **Studio team** | Momentry Studio 前端 | `~/momentry_studio/` |
|
||||
| **Marcom team** | WordPress 網站 | `/Users/accusys/wordpress/` |
|
||||
|
||||
---
|
||||
|
||||
## 3. API 變更
|
||||
|
||||
### `/api/v1/file/{file_uuid}/sync-status` 回傳格式
|
||||
|
||||
**POST** `/api/v1/file/{file_uuid}/sync-status`
|
||||
|
||||
```json
|
||||
{
|
||||
"success": true,
|
||||
"file_uuid": "4655a0ab3c077e30c12b2298c2750650",
|
||||
"status": "face_mgmt_ready",
|
||||
"processors_complete": 4,
|
||||
"processors_total": 5,
|
||||
"worker": {
|
||||
"has_job": true,
|
||||
"job_status": "pending",
|
||||
"current_processor": null,
|
||||
"progress_total": 7,
|
||||
"progress_current": 7,
|
||||
"completed_processors": ["cut", "asr", "face", "ocr", "pose", "asrx", "face_cluster"],
|
||||
"failed_processors": [],
|
||||
"updated_at": "2026-07-24T21:26:06"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**無 job 的檔案:**
|
||||
```json
|
||||
{
|
||||
"success": true,
|
||||
"file_uuid": "...",
|
||||
"status": "registered",
|
||||
"processors_complete": 0,
|
||||
"processors_total": 5,
|
||||
"worker": {
|
||||
"has_job": false
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Worker 狀態說明
|
||||
|
||||
| 欄位 | 說明 |
|
||||
|------|------|
|
||||
| `has_job` | 是否有 monitor_job 紀錄 |
|
||||
| `job_status` | pending / running / completed / failed |
|
||||
| `current_processor` | 目前正在執行的 processor |
|
||||
| `progress_total` | 總 processor 數量 |
|
||||
| `progress_current` | 已完成的 processor 數量 |
|
||||
| `completed_processors` | 已完成的 processor 列表 |
|
||||
| `failed_processors` | 失敗的 processor 列表 |
|
||||
| `updated_at` | 最後更新時間 |
|
||||
|
||||
### 使用者可區分的情境
|
||||
|
||||
| 情境 | `job_status` | `current_processor` | 顯示建議 |
|
||||
|------|-------------|-------------------|---------|
|
||||
| **正在處理** | `running` | `face` | 🔄 正在執行 Face |
|
||||
| **排隊等待** | `pending` | `null` | ⏳ 等待處理 |
|
||||
| **已完成** | `completed` | `null` | ✅ Processor 完成 |
|
||||
| **處理失敗** | `failed` | `face` | ❌ Face 失敗 |
|
||||
| **從未提交** | `has_job=false` | - | 📋 僅註冊 |
|
||||
|
||||
### 新狀態清單
|
||||
|
||||
| Status | 中文顯示 | 圖示 | 說明 |
|
||||
|--------|---------|------|------|
|
||||
| `registered` | 已註冊 | 📋 | 0 processor outputs |
|
||||
| `scanning` | 掃描中 | 🔍 | 1-4/5 processor outputs |
|
||||
| `keyword_ready` | 關鍵字可用 | 🔎 | sentence chunks > 0 |
|
||||
| `semantic_ready` | 語意可用 | 🧠 | embedded chunks > 0 |
|
||||
| `face_mgmt_ready` | 臉部管理可用 | 🎭 | trace_profiles + tkg_nodes > 0 |
|
||||
| `agent_ready` | Agent 可用 | 🤖 | tkg_edges > 0 |
|
||||
| `completed` | 已完成 | ✅ | 全部就緒 |
|
||||
|
||||
### 已移除的舊狀態
|
||||
|
||||
| 舊狀態 | 新狀態 |
|
||||
|--------|--------|
|
||||
| `pending` | `registered` |
|
||||
| `processing` | `scanning` |
|
||||
|
||||
---
|
||||
|
||||
## 4. Studio 前端需修改項目
|
||||
|
||||
### 4.1 狀態顯示邏輯
|
||||
|
||||
**位置:** `~/momentry_studio/` 中處理檔案狀態顯示的元件
|
||||
|
||||
**修改前:**
|
||||
```javascript
|
||||
switch (file.status) {
|
||||
case 'completed': return '✅ 已完成';
|
||||
case 'processing': return '🔄 處理中';
|
||||
case 'pending': return '⏳ 待處理';
|
||||
default: return '📦 未註冊';
|
||||
}
|
||||
```
|
||||
|
||||
**修改後:**
|
||||
```javascript
|
||||
const statusMap = {
|
||||
completed: { label: '已完成', icon: '✅', color: 'green' },
|
||||
agent_ready: { label: 'Agent 可用', icon: '🤖', color: 'orange' },
|
||||
face_mgmt_ready: { label: '臉部管理可用', icon: '🎭', color: 'cyan' },
|
||||
semantic_ready: { label: '語意可用', icon: '🧠', color: 'purple' },
|
||||
keyword_ready: { label: '關鍵字可用', icon: '🔎', color: 'green' },
|
||||
scanning: { label: '掃描中', icon: '🔍', color: 'blue' },
|
||||
registered: { label: '已註冊', icon: '📋', color: 'gray' },
|
||||
};
|
||||
|
||||
const display = statusMap[file.status] || { label: '未註冊', icon: '📦', color: 'gray' };
|
||||
return `${display.icon} ${display.label}`;
|
||||
```
|
||||
|
||||
### 4.2 狀態過濾選項
|
||||
|
||||
**位置:** `~/momentry_studio/` 中檔案列表過濾元件
|
||||
|
||||
**移除:** `pending`, `processing`
|
||||
**新增:** `registered`, `scanning`, `keyword_ready`, `semantic_ready`, `face_mgmt_ready`, `agent_ready`
|
||||
|
||||
---
|
||||
|
||||
## 5. Face Management Ready 明確定義
|
||||
|
||||
`face_mgmt_ready` 表示檔案已具備完整臉部管理功能,需同時滿足以下四個條件:
|
||||
|
||||
| 依賴項 | 檢查條件 | 說明 |
|
||||
|--------|---------|------|
|
||||
| **Face Qdrant Ready** | `_faces` collection 有 face points | Face embeddings 已存入 Qdrant |
|
||||
| **Face Trace Ready** | `face_traced.json` 存在且有 traces | Face tracking 已完成 |
|
||||
| **Face Profile Ready** | `trace_profiles` 有紀錄 | Profile 資料已建立 |
|
||||
| **Face TKG Node Ready** | `tkg_nodes` 有 `face_track` nodes | TKG 圖譜節點已建立 |
|
||||
|
||||
---
|
||||
|
||||
## 6. 狀態依賴關係
|
||||
|
||||
```
|
||||
registered → scanning → keyword_ready → semantic_ready
|
||||
↓
|
||||
face_mgmt_ready → agent_ready → completed
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 7. 測試 API
|
||||
|
||||
```bash
|
||||
# 取得所有檔案
|
||||
curl http://localhost:3002/api/v1/files \
|
||||
-H "Authorization: Bearer <api_key>"
|
||||
|
||||
# 觸發狀態同步
|
||||
curl -X POST http://localhost:3002/api/v1/file/{file_uuid}/sync-status \
|
||||
-H "Authorization: Bearer <api_key>"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 8. 參考文件
|
||||
|
||||
| 文件 | 完整路徑 |
|
||||
|------|---------|
|
||||
| People API | `/Users/accusys/momentry_core/docs_v1.0/API_WORKSPACE/modules/19_people_api.md` |
|
||||
| Status Unification | `/Users/accusys/momentry_core/docs_v1.0/API_WORKSPACE/modules/20_status_unification.md` |
|
||||
| Studio Team Guide | `/Users/accusys/momentry_core/docs_v1.0/API_WORKSPACE/modules/21_studio_team_guide.md` |
|
||||
| AGENTS.md | `/Users/accusys/momentry_core/AGENTS.md` |
|
||||
@@ -0,0 +1,207 @@
|
||||
# Studio Team 配套修改指南
|
||||
|
||||
**Version**: 1.0
|
||||
**Date**: 2026-07-26
|
||||
**Doc Path**: `/Users/accusys/momentry_core/docs_v1.0/API_WORKSPACE/modules/22_studio_pipeline_changes.md`
|
||||
**目標**: 通知 Studio team 後端 Pipeline 狀態變更,前端需配合更新
|
||||
|
||||
---
|
||||
|
||||
## 1. 概述
|
||||
|
||||
後端已完成以下修改:
|
||||
1. 移除 `identity_agent`,替換為 `face_dedup`(Face Deduplication)
|
||||
2. 重構 `sync_file_status` 邏輯:檢查 JSON 存在 + DB 一致性
|
||||
3. Pipeline 進度階段重新分配
|
||||
|
||||
**影響範圍:**
|
||||
- 檔案狀態顯示(status)
|
||||
- Pipeline 進度顯示(progress stages)
|
||||
- 統計 API 回傳格式
|
||||
|
||||
---
|
||||
|
||||
## 2. 檔案狀態變更
|
||||
|
||||
### 新狀態清單
|
||||
|
||||
| Status | 中文顯示 | 圖示 | 說明 |
|
||||
|--------|---------|------|------|
|
||||
| `registered` | 已註冊 | 📋 | 尚未開始處理 |
|
||||
| `scanning` | 掃描中 | 🔍 | 處理中(JSON 存在但 DB 不一致) |
|
||||
| `completed` | 已完成 | ✅ | 所有 processor 完成且 DB 一致 |
|
||||
| `agent_ready` | Agent 可用 | 🤖 | TKG edges 存在 |
|
||||
|
||||
### 已移除的狀態
|
||||
|
||||
| 舊狀態 | 新狀態 | 說明 |
|
||||
|--------|--------|------|
|
||||
| `processing` | `scanning` | 更明確表示正在處理 |
|
||||
| `pending` | `registered` | 尚未開始 |
|
||||
| `face_mgmt_ready` | `completed` | 最終狀態統一為 completed |
|
||||
|
||||
### 狀態判斷邏輯
|
||||
|
||||
| 條件 | 狀態 |
|
||||
|------|------|
|
||||
| 所有 JSON 存在且 DB 一致 | `completed` |
|
||||
| 部分 JSON 存在但不一致 | `scanning` |
|
||||
| 無 JSON 存在 | `registered` |
|
||||
| TKG edges 存在 | `agent_ready` |
|
||||
|
||||
---
|
||||
|
||||
## 3. Pipeline 進度階段變更
|
||||
|
||||
### 修改前(7 個 stage)
|
||||
|
||||
```
|
||||
Processors (30%) → Rule1 (5%) → Face Tracing (5%) → identity_agent (10%) → TKG Nodes (20%) → TKG Edges (15%) → Rule2 (15%)
|
||||
```
|
||||
|
||||
### 修改後(7 個 stage)
|
||||
|
||||
```
|
||||
Processors (30%) → Rule1 (5%) → Face Tracing (5%) → face_dedup (10%) → TKG Nodes (20%) → TKG Edges (15%) → Rule2 (15%)
|
||||
```
|
||||
|
||||
### 需要修改的前端元件
|
||||
|
||||
| 元件 | 修改內容 |
|
||||
|------|---------|
|
||||
| Pipeline Progress Bar | 移除 `identity_agent`,新增 `face_dedup` |
|
||||
| Stage Labels | 更新 stage 名稱 |
|
||||
| Overall Progress | 重新計算權重 |
|
||||
|
||||
---
|
||||
|
||||
## 4. API 變更
|
||||
|
||||
### `/api/v1/file/{file_uuid}/sync-status`
|
||||
|
||||
**回傳格式變更:**
|
||||
|
||||
**修改前:**
|
||||
```json
|
||||
{
|
||||
"status": "face_mgmt_ready",
|
||||
"processors_complete": 5,
|
||||
"processors_total": 5,
|
||||
"worker": { ... }
|
||||
}
|
||||
```
|
||||
|
||||
**修改後:**
|
||||
```json
|
||||
{
|
||||
"success": true,
|
||||
"file_uuid": "...",
|
||||
"status": "completed",
|
||||
"processors": {
|
||||
"asr": { "json_exists": true, "consistent": true },
|
||||
"asrx": { "json_exists": true, "consistent": true },
|
||||
"ocr": { "json_exists": true, "consistent": true },
|
||||
"pose": { "json_exists": true, "consistent": true },
|
||||
"cut": { "json_exists": true, "consistent": true },
|
||||
"face": { "json_exists": true, "consistent": true },
|
||||
"face_cluster": { "json_exists": true, "consistent": true }
|
||||
},
|
||||
"worker": { ... }
|
||||
}
|
||||
```
|
||||
|
||||
### `/api/v1/file/{file_uuid}/stats`
|
||||
|
||||
**回傳格式變更:**
|
||||
|
||||
**修改前:**
|
||||
```json
|
||||
{
|
||||
"identity_agent": {
|
||||
"clusters": 0,
|
||||
"identities_created": 0,
|
||||
"tmdb_matches": 0,
|
||||
"speaker_bindings": 0,
|
||||
"confirmations": 0
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**修改後:**
|
||||
```json
|
||||
{
|
||||
"face_dedup": {
|
||||
"clusters": 5,
|
||||
"face_tracks": 24,
|
||||
"consistent": true
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 5. Studio 前端需修改項目
|
||||
|
||||
### 5.1 狀態顯示邏輯
|
||||
|
||||
**位置:** Studio 前端檔案列表元件
|
||||
|
||||
**修改前:**
|
||||
```javascript
|
||||
const statusLabels = {
|
||||
'completed': '✅ 已完成',
|
||||
'processing': '🔄 處理中',
|
||||
'pending': '⏳ 待處理',
|
||||
'face_mgmt_ready': '🎭 臉部管理可用',
|
||||
'agent_ready': '🤖 Agent 可用'
|
||||
};
|
||||
```
|
||||
|
||||
**修改後:**
|
||||
```javascript
|
||||
const statusLabels = {
|
||||
'completed': '✅ 已完成',
|
||||
'scanning': '🔍 掃描中',
|
||||
'registered': '📋 已註冊',
|
||||
'agent_ready': '🤖 Agent 可用'
|
||||
};
|
||||
```
|
||||
|
||||
### 5.2 Pipeline 進度顯示
|
||||
|
||||
**位置:** Studio 前端 Pipeline Progress 元件
|
||||
|
||||
**修改項目:**
|
||||
1. 移除 `identity_agent` stage
|
||||
2. 新增 `face_dedup` stage
|
||||
3. 更新 stage 名稱映射
|
||||
|
||||
### 5.3 統計面板
|
||||
|
||||
**位置:** Studio 前端檔案統計面板
|
||||
|
||||
**修改項目:**
|
||||
1. 移除 `Identity Agent` 區塊
|
||||
2. 新增 `Face Deduplication` 區塊
|
||||
3. 顯示欄位:`clusters`, `face_tracks`, `consistent`
|
||||
|
||||
---
|
||||
|
||||
## 6. 測試清單
|
||||
|
||||
- [ ] 檔案列表狀態顯示正確
|
||||
- [ ] Pipeline 進度階段正確顯示
|
||||
- [ ] Overall Progress 計算正確
|
||||
- [ ] 統計面板 Face Dedup 區塊顯示正確
|
||||
- [ ] sync-status API 回傳格式解析正確
|
||||
- [ ] stats API 回傳格式解析正確
|
||||
|
||||
---
|
||||
|
||||
## 7. 參考文件
|
||||
|
||||
| 文件 | 完整路徑 |
|
||||
|------|---------|
|
||||
| Studio Team Guide | `/Users/accusys/momentry_core/docs_v1.0/API_WORKSPACE/modules/21_studio_team_guide.md` |
|
||||
| People API | `/Users/accusys/momentry_core/docs_v1.0/API_WORKSPACE/modules/19_people_api.md` |
|
||||
| Pipeline Changes | `/Users/accusys/momentry_core/docs_v1.0/API_WORKSPACE/modules/22_studio_pipeline_changes.md` |
|
||||
@@ -0,0 +1,114 @@
|
||||
# Studio Fix: Face Group Name 讀寫不一致
|
||||
|
||||
**Date**: 2026-07-27
|
||||
**Author**: Studio Team
|
||||
**Status**: ✅ 已修復並部署
|
||||
|
||||
---
|
||||
|
||||
## 問題描述
|
||||
|
||||
Studio 前端在 Face 頁面 rename group name 後,離開再回來時名稱未更新。但 People Search 可以查到新名稱。
|
||||
|
||||
### 根因
|
||||
|
||||
**寫入**和**讀取**走了不同的資料來源:
|
||||
|
||||
| 操作 | API Endpoint | 實際讀寫欄位 |
|
||||
|------|-------------|------------|
|
||||
| **寫入 (rename)** | `PUT /api/v1/trace-profile/group` | `trace_profiles.name` |
|
||||
| **讀取 (卡片顯示)** | `GET /api/v1/file/:uuid/face-groups` | `tkg_nodes.label` |
|
||||
|
||||
`trace_profiles.name` 和 `tkg_nodes.label` 是兩張獨立的表/欄位(見 `19_people_api.md`),rename 只更新了 `trace_profiles.name`,但卡片顯示讀的是 `tkg_nodes.label`。
|
||||
|
||||
---
|
||||
|
||||
## 修復內容
|
||||
|
||||
### 修改檔案
|
||||
`/Users/accusys/momentry_core/src/api/profile.rs` — `get_face_groups_handler` (line 552-591)
|
||||
|
||||
### 改前 SQL
|
||||
```sql
|
||||
SELECT label, properties FROM tkg_nodes
|
||||
WHERE file_uuid = $1 AND node_type = 'face_track'
|
||||
ORDER BY (properties->>'trace_id')::int
|
||||
```
|
||||
|
||||
### 改後 SQL
|
||||
```sql
|
||||
SELECT COALESCE(tp.name, tn.label) as name, tn.properties
|
||||
FROM tkg_nodes tn
|
||||
LEFT JOIN trace_profiles tp ON tp.file_uuid = tn.file_uuid
|
||||
AND tp.trace_id = (tn.properties->>'trace_id')::int
|
||||
WHERE tn.file_uuid = $1 AND tn.node_type = 'face_track'
|
||||
ORDER BY (tn.properties->>'trace_id')::int
|
||||
```
|
||||
|
||||
### Rust 程式碼變更
|
||||
```diff
|
||||
pub async fn get_face_groups_handler(...) {
|
||||
let tkg_table = schema::table_name("tkg_nodes");
|
||||
+ let tp_table = schema::table_name("trace_profiles");
|
||||
|
||||
let rows: Vec<(String, serde_json::Value)> = sqlx::query_as(&format!(
|
||||
- "SELECT label, properties FROM {} \
|
||||
- WHERE file_uuid = $1 AND node_type = 'face_track' \
|
||||
- ORDER BY (properties->>'trace_id')::int",
|
||||
- tkg_table
|
||||
+ "SELECT COALESCE(tp.name, tn.label) as name, tn.properties \
|
||||
+ FROM {} tn \
|
||||
+ LEFT JOIN {} tp ON tp.file_uuid = tn.file_uuid \
|
||||
+ AND tp.trace_id = (tn.properties->>'trace_id')::int \
|
||||
+ WHERE tn.file_uuid = $1 AND tn.node_type = 'face_track' \
|
||||
+ ORDER BY (tn.properties->>'trace_id')::int",
|
||||
+ tkg_table, tp_table
|
||||
))
|
||||
...
|
||||
- for (label, properties) in rows {
|
||||
+ for (name, properties) in rows {
|
||||
...
|
||||
- if label.starts_with("Face Trace ") || label.starts_with("Trace ") {
|
||||
+ if name.starts_with("Face Trace ") || name.starts_with("Trace ") {
|
||||
unassigned.push(trace_id);
|
||||
} else {
|
||||
- groups.entry(label).or_default().push(trace_id);
|
||||
+ groups.entry(name).or_default().push(trace_id);
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 影響範圍
|
||||
|
||||
| 項目 | 影響 |
|
||||
|------|------|
|
||||
| **Face 頁面卡片顯示** | ✅ 現在從 `trace_profiles.name` 讀取,rename 後立即生效 |
|
||||
| **People Search** | 不受影響(本來就查 `trace_profiles.name`) |
|
||||
| **未命名 traces** | 不受影響(`COALESCE` fallback 到 `tkg_nodes.label`,如 `Person_0`) |
|
||||
| **Cluster Agent 初始化** | 不受影響(初始化時兩邊都寫入相同值) |
|
||||
|
||||
---
|
||||
|
||||
## 注意事項(給 Core Team)
|
||||
|
||||
1. **未來如果有需要同時更新 `tkg_nodes.label` 的情境**(例如 graph 顯示需要),請注意 `PUT /api/v1/trace-profile/group` 目前只更新 `trace_profiles.name`
|
||||
2. **建議**:如果 `tkg_nodes.label` 和 `trace_profiles.name` 應該保持一致,可以考慮:
|
||||
- 方案 A(目前做法):讀取端用 `COALESCE` 優先取 `trace_profiles.name`
|
||||
- 方案 B:寫入端同時更新兩個欄位(需要改 `update_trace_profile_group_handler`)
|
||||
3. **`merge_groups_handler`** 目前同時更新 `trace_profiles.name` 和 `tkg_nodes.label`(line 278-310),行為正確,不需要改
|
||||
|
||||
---
|
||||
|
||||
## 驗證
|
||||
|
||||
```bash
|
||||
# 測試 face-groups endpoint 正確回傳 rename 後的名稱
|
||||
curl -s "http://localhost:3002/api/v1/file/4655a0ab3c077e30c12b2298c2750650/face-groups" \
|
||||
-H "X-API-Key: <key>" | jq '.face_groups[] | {name, trace_count}'
|
||||
|
||||
# 預期輸出包含 "Susan"(已 rename 的 group)
|
||||
# { "name": "Susan", "trace_count": 7 }
|
||||
```
|
||||
@@ -0,0 +1,138 @@
|
||||
# Studio Bug Report: `get_trace_profile` 讀寫不一致
|
||||
|
||||
**Date**: 2026-07-27
|
||||
**Author**: Studio Team
|
||||
**Status**: 🔴 待修復
|
||||
**Priority**: High
|
||||
|
||||
---
|
||||
|
||||
## 問題描述
|
||||
|
||||
Studio 前端 rename face group 後,離開再回來選同一個檔案,名稱變回舊的。
|
||||
|
||||
## 影響
|
||||
|
||||
使用者 rename 的變更無法持久顯示。雖然 `trace_profiles.name` 已更新,但 `get_trace_profile` API 回傳的是舊的 `tkg_nodes.label`,導致前端 `loadClusterNames()` 用舊名覆蓋新名。
|
||||
|
||||
---
|
||||
|
||||
## 測試驗證
|
||||
|
||||
### 1. Rename
|
||||
```bash
|
||||
curl -X PUT "http://localhost:3002/api/v1/trace-profile/group" \
|
||||
-H "X-API-Key: $KEY" -H "Content-Type: application/json" \
|
||||
-d '{"file_uuid": "9cbeb112fcc5452e869755a539478061", "trace_ids": [1], "name": "SusanTest"}'
|
||||
```
|
||||
回傳:`{"success": true, "updated_count": 1}` ✅
|
||||
|
||||
### 2. 讀取單筆 profile(❌ 仍是舊名)
|
||||
```bash
|
||||
GET /api/v1/trace-profile?file_uuid=...&trace_id=1
|
||||
```
|
||||
回傳:`{"name": "Person_0"}` ← **錯誤,應為 "SusanTest"**
|
||||
|
||||
### 3. 讀取 face groups(✅ 是新名)
|
||||
```bash
|
||||
GET /api/v1/file/{uuid}/face-groups
|
||||
```
|
||||
回傳:`{"name": "SusanTest", "trace_ids": [1]}` ← **正確**
|
||||
|
||||
---
|
||||
|
||||
## 根因分析
|
||||
|
||||
### 寫入路徑(正確)
|
||||
`PUT /api/v1/trace-profile/group` → `update_trace_profile_group_handler`(profile.rs:228):
|
||||
```sql
|
||||
UPDATE trace_profiles SET name = $1 WHERE file_uuid = $2 AND trace_id = $3
|
||||
```
|
||||
寫入 `trace_profiles.name` ✅
|
||||
|
||||
### 讀取路徑 — 單筆(❌ 錯誤)
|
||||
`GET /api/v1/trace-profile` → `get_trace_profile_handler`(profile.rs:78-81):
|
||||
```sql
|
||||
SELECT label, external_id, properties FROM tkg_nodes
|
||||
WHERE file_uuid = $1 AND node_type = 'face_track'
|
||||
AND (external_id = $2 OR external_id = $3)
|
||||
```
|
||||
讀取 `tkg_nodes.label`,**沒有 JOIN `trace_profiles`** ❌
|
||||
|
||||
### 讀取路徑 — 群組(✅ 正確)
|
||||
`GET /api/v1/file/{uuid}/face-groups` → `get_face_groups_handler`(profile.rs:560-566):
|
||||
```sql
|
||||
SELECT COALESCE(tp.name, tn.label) as name, tn.properties
|
||||
FROM tkg_nodes tn
|
||||
LEFT JOIN trace_profiles tp ON tp.file_uuid = tn.file_uuid
|
||||
AND tp.trace_id = (tn.properties->>'trace_id')::int
|
||||
WHERE tn.file_uuid = $1 AND tn.node_type = 'face_track'
|
||||
```
|
||||
使用 `COALESCE(tp.name, tn.label)`,優先取 `trace_profiles.name` ✅
|
||||
|
||||
---
|
||||
|
||||
## 前端影響流程
|
||||
|
||||
```
|
||||
User rename group → updateTraceProfileGroup() → PUT /trace-profile/group
|
||||
→ trace_profiles.name = "SusanTest" ✅
|
||||
|
||||
User refresh → loadClusterResults() → GET /face-groups
|
||||
→ cluster.name = "SusanTest" ✅
|
||||
→ loadClusterNames() → GET /trace-profile
|
||||
→ profile.name = "Person_0" ❌ (tkg_nodes.label)
|
||||
→ c.name = profile.name → "Person_0" ❌ 覆蓋了新名
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 建議修復
|
||||
|
||||
### 方案:改 `get_trace_profile_handler` 使用 JOIN
|
||||
|
||||
```rust
|
||||
pub async fn get_trace_profile_handler(...) {
|
||||
let tkg_table = schema::table_name("tkg_nodes");
|
||||
let tp_table = schema::table_name("trace_profiles");
|
||||
|
||||
let row: Option<(String, String, serde_json::Value)> = sqlx::query_as(&format!(
|
||||
"SELECT COALESCE(tp.name, tn.label) as name, tn.external_id, tn.properties \
|
||||
FROM {} tn \
|
||||
LEFT JOIN {} tp ON tp.file_uuid = tn.file_uuid \
|
||||
AND tp.trace_id = (tn.properties->>'trace_id')::int \
|
||||
WHERE tn.file_uuid = $1 AND tn.node_type = 'face_track' \
|
||||
AND (tn.external_id = $2 OR tn.external_id = $3)",
|
||||
tkg_table, tp_table
|
||||
))
|
||||
.bind(¶ms.file_uuid)
|
||||
.bind(&external_id_face)
|
||||
.bind(&external_id_trace)
|
||||
.fetch_optional(state.db.pool())
|
||||
.await?;
|
||||
|
||||
let (name, _ext_id, properties) = row.ok_or(StatusCode::NOT_FOUND)?;
|
||||
|
||||
Ok(Json(TraceProfile {
|
||||
file_uuid: params.file_uuid,
|
||||
trace_id: params.trace_id,
|
||||
name, // 改為使用 JOIN 後的 name
|
||||
// ... 其他欄位不變
|
||||
}))
|
||||
}
|
||||
```
|
||||
|
||||
### 一致性保證
|
||||
|
||||
| API | 讀取欄位 | 修復後 |
|
||||
|-----|---------|--------|
|
||||
| `PUT /trace-profile/group` | 寫入 `trace_profiles.name` | 不變 |
|
||||
| `GET /trace-profile` | ~~`tkg_nodes.label`~~ → `COALESCE(tp.name, tn.label)` | ✅ 一致 |
|
||||
| `GET /file/{uuid}/face-groups` | `COALESCE(tp.name, tn.label)` | 不變 |
|
||||
|
||||
---
|
||||
|
||||
## 相關文件
|
||||
- `18_profile.md` — Profile API 文件
|
||||
- `19_people_api.md` — People API 文件
|
||||
- `23_studio_face_group_name_fix.md` — Studio face-groups JOIN 修復
|
||||
@@ -0,0 +1,750 @@
|
||||
# Face Filter API 使用指南 — Studio 團隊參考
|
||||
|
||||
**版本**: v1.0
|
||||
**日期**: 2026-08-09
|
||||
**狀態**: 已實作
|
||||
|
||||
---
|
||||
|
||||
## 概述
|
||||
|
||||
Face Filter API 提供臉部過濾功能,讓 Studio 前端可以:
|
||||
1. 查詢臉部列表(支持來源過濾)
|
||||
2. 獲取單一臉部過濾報告
|
||||
3. 套用過濾規則
|
||||
4. 獲取過濾統計
|
||||
5. 管理過濾規則
|
||||
|
||||
---
|
||||
|
||||
## API 端點
|
||||
|
||||
### 1. 獲取臉部列表
|
||||
|
||||
**端點**: `GET /api/v1/file/{file_uuid}/faces`
|
||||
|
||||
**功能**: 獲取檔案的臉部列表,支持分頁和來源過濾
|
||||
|
||||
**查詢參數**:
|
||||
```json
|
||||
{
|
||||
"source": "all", // "all" | "apple_vision" | "mediapipe"
|
||||
"page": 1, // 頁碼(從 1 開始)
|
||||
"page_size": 50 // 每頁數量
|
||||
}
|
||||
```
|
||||
|
||||
**回應範例**:
|
||||
```json
|
||||
{
|
||||
"success": true,
|
||||
"data": {
|
||||
"faces": [
|
||||
{
|
||||
"face_id": "face_001",
|
||||
"frame": 671,
|
||||
"primary_source": "apple_vision",
|
||||
"primary_confidence": 0.84,
|
||||
"detection_sources": [
|
||||
{"source_type": "apple_vision", "confidence": 0.84},
|
||||
{"source_type": "mediapipe", "confidence": 0.92}
|
||||
],
|
||||
"filter_features": {
|
||||
"face_id": "face_001",
|
||||
"file_uuid": "0489e104d7d1e11e613da01f7aa130ca",
|
||||
"frame": 671,
|
||||
"bbox_size": 336, // 新增:min(width, height)
|
||||
"eye_ratio": 0.33,
|
||||
"nose_ratio": 0.02,
|
||||
"pose_score": 0.08,
|
||||
"mediapipe_detected": true,
|
||||
"mediapipe_iou": 0.85,
|
||||
"embedding_similarity": 0.82,
|
||||
"consecutive_frames": 15,
|
||||
"total_frames_detected": 15,
|
||||
"apple_vision_confidence": 0.84,
|
||||
"mediapipe_confidence": 0.92,
|
||||
"primary_source": "apple_vision"
|
||||
}
|
||||
}
|
||||
],
|
||||
"pagination": {
|
||||
"page": 1,
|
||||
"page_size": 50,
|
||||
"total": 392,
|
||||
"total_pages": 8
|
||||
},
|
||||
"source_summary": {
|
||||
"apple_vision": 392,
|
||||
"mediapipe": 5,
|
||||
"merged_unique": 392
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**Studio 使用範例**:
|
||||
```typescript
|
||||
// 獲取第一頁臉部
|
||||
const response = await fetch('/api/v1/file/0489e104d7d1e11e613da01f7aa130ca/faces', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
source: 'all',
|
||||
page: 1,
|
||||
page_size: 50
|
||||
})
|
||||
});
|
||||
|
||||
const data = await response.json();
|
||||
console.log(`Total faces: ${data.data.pagination.total}`);
|
||||
console.log(`First face: ${data.data.faces[0].face_id}`);
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 2. 獲取單一臉部過濾報告
|
||||
|
||||
**端點**: `GET /api/v1/file/{file_uuid}/face/{face_id}/filter-report`
|
||||
|
||||
**功能**: 獲取單一臉部的詳細過濾報告
|
||||
|
||||
**回應範例**:
|
||||
```json
|
||||
{
|
||||
"face_id": "face_001",
|
||||
"frame": 671,
|
||||
"overall_confidence": 0.45,
|
||||
"recommendation": "reject",
|
||||
"rule_results": {
|
||||
"landmark_analysis": {
|
||||
"enabled": true,
|
||||
"score": 0.75,
|
||||
"passed": true,
|
||||
"reason": "nose_ratio too low (0.020)"
|
||||
},
|
||||
"mediapipe_verification": {
|
||||
"enabled": true,
|
||||
"score": 1.0,
|
||||
"passed": true,
|
||||
"reason": null
|
||||
},
|
||||
"embedding_similarity": {
|
||||
"enabled": true,
|
||||
"score": 0.21,
|
||||
"passed": false,
|
||||
"reason": "Low embedding similarity (0.150)"
|
||||
},
|
||||
"temporal_consistency": {
|
||||
"enabled": true,
|
||||
"score": 0.33,
|
||||
"passed": false,
|
||||
"reason": "Single frame detection (1)"
|
||||
}
|
||||
},
|
||||
"reasons": [
|
||||
"nose_ratio too low (0.020)",
|
||||
"Low embedding similarity (0.150)",
|
||||
"Single frame detection (1)"
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
**Studio 使用範例**:
|
||||
```typescript
|
||||
// 獲取臉部過濾報告
|
||||
const response = await fetch('/api/v1/file/0489e104d7d1e11e613da01f7aa130ca/face/face_001/filter-report');
|
||||
const report = await response.json();
|
||||
|
||||
console.log(`Recommendation: ${report.recommendation}`);
|
||||
console.log(`Confidence: ${report.overall_confidence}`);
|
||||
console.log(`Reasons: ${report.reasons.join(', ')}`);
|
||||
|
||||
// 顯示每個規則的結果
|
||||
Object.entries(report.rule_results).forEach(([rule, result]) => {
|
||||
console.log(`${rule}: ${result.passed ? '✅' : '❌'} (score: ${result.score})`);
|
||||
});
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 3. 套用過濾規則
|
||||
|
||||
**端點**: `POST /api/v1/file/{file_uuid}/faces/filter`
|
||||
|
||||
**功能**: 套用過濾規則到所有臉部,返回過濾結果
|
||||
|
||||
**請求範例**:
|
||||
```json
|
||||
{
|
||||
"rules": {
|
||||
"version": "1.0",
|
||||
"rules": {
|
||||
"landmark_analysis": {
|
||||
"enabled": true,
|
||||
"weight": 0.3,
|
||||
"thresholds": {
|
||||
"eye_ratio_min": 0.25,
|
||||
"eye_ratio_max": 0.55,
|
||||
"nose_ratio_min": 0.08,
|
||||
"pose_score_max": 0.8
|
||||
}
|
||||
},
|
||||
"mediapipe_verification": {
|
||||
"enabled": true,
|
||||
"weight": 0.2,
|
||||
"thresholds": {
|
||||
"min_iou": 0.3
|
||||
}
|
||||
},
|
||||
"embedding_similarity": {
|
||||
"enabled": true,
|
||||
"weight": 0.3,
|
||||
"thresholds": {
|
||||
"min_similarity": 0.70
|
||||
}
|
||||
},
|
||||
"temporal_consistency": {
|
||||
"enabled": true,
|
||||
"weight": 0.2,
|
||||
"thresholds": {
|
||||
"min_consecutive_frames": 3
|
||||
}
|
||||
}
|
||||
},
|
||||
"overall_thresholds": {
|
||||
"auto_accept": 0.7,
|
||||
"auto_reject": 0.3,
|
||||
"review_range": [0.3, 0.7]
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**回應範例**:
|
||||
```json
|
||||
{
|
||||
"total_faces": 392,
|
||||
"passed": 385,
|
||||
"filtered": 7,
|
||||
"filtered_faces": [
|
||||
{
|
||||
"face_id": "face_001",
|
||||
"frame": 671,
|
||||
"reasons": [
|
||||
"nose_ratio too low (0.020)",
|
||||
"Low embedding similarity (0.150)",
|
||||
"Single frame detection (1)"
|
||||
]
|
||||
}
|
||||
],
|
||||
"filter_stats": {
|
||||
"landmark": 3,
|
||||
"mediapipe": 1,
|
||||
"embedding": 2,
|
||||
"temporal": 1
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**Studio 使用範例**:
|
||||
```typescript
|
||||
// 套用過濾規則
|
||||
const filterConfig = {
|
||||
rules: {
|
||||
landmark_analysis: {
|
||||
enabled: true,
|
||||
weight: 0.3,
|
||||
thresholds: {
|
||||
eye_ratio_min: 0.25,
|
||||
eye_ratio_max: 0.55,
|
||||
nose_ratio_min: 0.08,
|
||||
pose_score_max: 0.8
|
||||
}
|
||||
},
|
||||
// ... 其他規則
|
||||
},
|
||||
overall_thresholds: {
|
||||
auto_accept: 0.7,
|
||||
auto_reject: 0.3,
|
||||
review_range: [0.3, 0.7]
|
||||
}
|
||||
};
|
||||
|
||||
const response = await fetch('/api/v1/file/0489e104d7d1e11e613da01f7aa130ca/faces/filter', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ rules: filterConfig })
|
||||
});
|
||||
|
||||
const result = await response.json();
|
||||
console.log(`Passed: ${result.passed}, Filtered: ${result.filtered}`);
|
||||
|
||||
// 顯示被過濾的臉部
|
||||
result.filtered_faces.forEach(face => {
|
||||
console.log(`Face ${face.face_id} (frame ${face.frame}): ${face.reasons.join(', ')}`);
|
||||
});
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 4. 獲取過濾統計
|
||||
|
||||
**端點**: `GET /api/v1/file/{file_uuid}/filter-stats`
|
||||
|
||||
**功能**: 獲取臉部的過濾統計資訊
|
||||
|
||||
**回應範例**:
|
||||
```json
|
||||
{
|
||||
"total_faces": 392,
|
||||
"by_category": {
|
||||
"total_faces": 392,
|
||||
"by_source": {
|
||||
"apple_vision": 392,
|
||||
"mediapipe": 5
|
||||
},
|
||||
"by_quality": {
|
||||
"avg_eye_ratio": 0.37,
|
||||
"avg_nose_ratio": 0.12,
|
||||
"avg_pose_score": 0.15,
|
||||
"mediapipe_verified": 5,
|
||||
"avg_embedding_similarity": 0.78,
|
||||
"avg_consecutive_frames": 12.5
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**Studio 使用範例**:
|
||||
```typescript
|
||||
// 獲取過濾統計
|
||||
const response = await fetch('/api/v1/file/0489e104d7d1e11e613da01f7aa130ca/filter-stats');
|
||||
const stats = await response.json();
|
||||
|
||||
console.log(`Total faces: ${stats.total_faces}`);
|
||||
console.log(`Apple Vision faces: ${stats.by_category.by_source.apple_vision}`);
|
||||
console.log(`MediaPipe faces: ${stats.by_category.by_source.mediapipe}`);
|
||||
console.log(`Avg embedding similarity: ${stats.by_category.by_quality.avg_embedding_similarity}`);
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 5. 管理過濾規則
|
||||
|
||||
#### 5.1 獲取過濾規則
|
||||
|
||||
**端點**: `GET /api/v1/file/{file_uuid}/filter-rules`
|
||||
|
||||
**回應範例**:
|
||||
```json
|
||||
{
|
||||
"rules": [
|
||||
{
|
||||
"id": 1,
|
||||
"rule_name": "default_filter",
|
||||
"rules": {
|
||||
"version": "1.0",
|
||||
"rules": {
|
||||
"landmark_analysis": { ... },
|
||||
"mediapipe_verification": { ... },
|
||||
"embedding_similarity": { ... },
|
||||
"temporal_consistency": { ... }
|
||||
},
|
||||
"overall_thresholds": { ... }
|
||||
},
|
||||
"is_active": true,
|
||||
"created_at": "2026-08-09T12:00:00Z",
|
||||
"updated_at": "2026-08-09T12:00:00Z"
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
#### 5.2 儲存過濾規則
|
||||
|
||||
**端點**: `POST /api/v1/file/{file_uuid}/filter-rules`
|
||||
|
||||
**請求範例**:
|
||||
```json
|
||||
{
|
||||
"rule_name": "strict_filter",
|
||||
"rules": {
|
||||
"version": "1.0",
|
||||
"rules": {
|
||||
"landmark_analysis": {
|
||||
"enabled": true,
|
||||
"weight": 0.3,
|
||||
"thresholds": {
|
||||
"eye_ratio_min": 0.30,
|
||||
"eye_ratio_max": 0.50,
|
||||
"nose_ratio_min": 0.10,
|
||||
"pose_score_max": 0.5
|
||||
}
|
||||
},
|
||||
// ... 其他規則
|
||||
},
|
||||
"overall_thresholds": {
|
||||
"auto_accept": 0.8,
|
||||
"auto_reject": 0.2,
|
||||
"review_range": [0.2, 0.8]
|
||||
}
|
||||
},
|
||||
"is_active": true
|
||||
}
|
||||
```
|
||||
|
||||
**Studio 使用範例**:
|
||||
```typescript
|
||||
// 獲取現有規則
|
||||
const getResponse = await fetch('/api/v1/file/0489e104d7d1e11e613da01f7aa130ca/filter-rules');
|
||||
const rulesData = await getResponse.json();
|
||||
|
||||
// 儲存新規則
|
||||
const strictFilter = {
|
||||
rule_name: "strict_filter",
|
||||
rules: {
|
||||
// ... 規則配置
|
||||
},
|
||||
is_active: true
|
||||
};
|
||||
|
||||
const saveResponse = await fetch('/api/v1/file/0489e104d7d1e11e613da01f7aa130ca/filter-rules', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(strictFilter)
|
||||
});
|
||||
|
||||
const savedRule = await saveResponse.json();
|
||||
console.log(`Saved rule: ${savedRule.rule_name} (id: ${savedRule.id})`);
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 過濾規則說明
|
||||
|
||||
### 規則類型
|
||||
|
||||
#### 1. Landmark 分析 (landmark_analysis)
|
||||
|
||||
**功能**: 檢查臉部 landmark 幾何特徵是否正常
|
||||
|
||||
**閾值**:
|
||||
- `eye_ratio_min`: 眼睛間距比例最小值(預設 0.25)
|
||||
- `eye_ratio_max`: 眼睛間距比例最大值(預設 0.55)
|
||||
- `nose_ratio_min`: 眼睛到鼻子比例最小值(預設 0.08)
|
||||
- `pose_score_max`: Pose 角度評分最大值(預設 0.8)
|
||||
|
||||
**權重**: 0.3
|
||||
|
||||
---
|
||||
|
||||
#### 2. MediaPipe 驗證 (mediapipe_verification)
|
||||
|
||||
**功能**: 驗證 MediaPipe 是否也檢測到該臉部
|
||||
|
||||
**值**:
|
||||
- `min_iou`: 最小 IoU 值(預設 0.3)
|
||||
|
||||
**權重**: 0.2
|
||||
|
||||
---
|
||||
|
||||
#### 3. Embedding 相似度 (embedding_similarity)
|
||||
|
||||
**功能**: 檢查臉部 embedding 與已知人臉的相似度
|
||||
|
||||
**閾值**:
|
||||
- `min_similarity`: 最小相似度(預設 0.70)
|
||||
|
||||
**權重**: 0.3
|
||||
|
||||
---
|
||||
|
||||
#### 4. 時間一致性 (temporal_consistency)
|
||||
|
||||
**功能**: 檢查臉部是否在連續幀中出現
|
||||
|
||||
**閾值**:
|
||||
- `min_consecutive_frames`: 最小連續數(預設 3)
|
||||
|
||||
**權重**: 0.2
|
||||
|
||||
---
|
||||
|
||||
### 總體閾值
|
||||
|
||||
**overall_thresholds**:
|
||||
- `auto_accept`: 自動接受閾值(預設 0.7)
|
||||
- `auto_reject`: 自動拒絕閾值(預設 0.3)
|
||||
- `review_range`: 審查範圍(預設 [0.3, 0.7])
|
||||
|
||||
**建議**:
|
||||
- `overall_confidence >= 0.7`: 接受
|
||||
- `overall_confidence <= 0.3`: 拒絕
|
||||
- `0.3 < overall_confidence < 0.7`: 審查
|
||||
|
||||
---
|
||||
|
||||
### Bbox Size 說明
|
||||
|
||||
**欄位**: `bbox_size`
|
||||
|
||||
**計算方式**: `min(width, height)`
|
||||
|
||||
**說明**:
|
||||
- 預先計算並儲存於後端
|
||||
- 用於前端即時過濾
|
||||
- 維持當前 Swift 實作的計算方式
|
||||
|
||||
**前端過濾範例**:
|
||||
```typescript
|
||||
// 前端即時過濾
|
||||
const quickFilter = (faces, rules) => {
|
||||
return faces.filter(face => {
|
||||
// Bbox size 過濾
|
||||
if (rules.min_bbox_size && face.filter_features.bbox_size < rules.min_bbox_size) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
});
|
||||
};
|
||||
|
||||
// 使用範例
|
||||
const filtered = quickFilter(allFaces, {
|
||||
min_bbox_size: 80 // 最小 80 像素
|
||||
});
|
||||
```
|
||||
|
||||
**建議閾值**:
|
||||
- 保守: 80 像素
|
||||
- 平衡: 64 像素(當前預設)
|
||||
- 寬鬆: 48 像素
|
||||
|
||||
**未來擴展**:
|
||||
- 可考慮增加 `max(bbox.width, bbox.height)` 選項
|
||||
- 可考慮增加 `bbox.width * bbox.height` (面積) 選項
|
||||
|
||||
---
|
||||
|
||||
## 預設配置
|
||||
|
||||
API 提供預設過濾規則,可直接使用:
|
||||
|
||||
```json
|
||||
{
|
||||
"version": "1.0",
|
||||
"rules": {
|
||||
"landmark_analysis": {
|
||||
"enabled": true,
|
||||
"weight": 0.3,
|
||||
"thresholds": {
|
||||
"eye_ratio_min": 0.25,
|
||||
"eye_ratio_max": 0.55,
|
||||
"nose_ratio_min": 0.08,
|
||||
"pose_score_max": 0.8
|
||||
}
|
||||
},
|
||||
"mediapipe_verification": {
|
||||
"enabled": true,
|
||||
"weight": 0.2,
|
||||
"thresholds": {
|
||||
"min_iou": 0.3
|
||||
}
|
||||
},
|
||||
"embedding_similarity": {
|
||||
"enabled": true,
|
||||
"weight": 0.3,
|
||||
"thresholds": {
|
||||
"min_similarity": 0.70
|
||||
}
|
||||
},
|
||||
"temporal_consistency": {
|
||||
"enabled": true,
|
||||
"weight": 0.2,
|
||||
"thresholds": {
|
||||
"min_consecutive_frames": 3
|
||||
}
|
||||
}
|
||||
},
|
||||
"overall_thresholds": {
|
||||
"auto_accept": 0.7,
|
||||
"auto_reject": 0.3,
|
||||
"review_range": [0.3, 0.7]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 完整使用範例
|
||||
|
||||
### 場景 1: 過濾低品質臉部
|
||||
|
||||
```typescript
|
||||
// 1. 獲取臉部列表
|
||||
const facesResponse = await fetch('/api/v1/file/0489e104d7d1e11e613da01f7aa130ca/faces', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ source: 'all', page: 1, page_size: 100 })
|
||||
});
|
||||
const facesData = await facesResponse.json();
|
||||
|
||||
// 2. 套用過濾規則
|
||||
const filterResponse = await fetch('/api/v1/file/0489e104d7d1e11e613da01f7aa130ca/faces/filter', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ rules: null }) // 使用預設規則
|
||||
});
|
||||
const filterResult = await filterResponse.json();
|
||||
|
||||
console.log(`Total: ${filterResult.total_faces}`);
|
||||
console.log(`Passed: ${filterResult.passed}`);
|
||||
console.log(`Filtered: ${filterResult.filtered}`);
|
||||
|
||||
// 3. 顯示被過濾的臉部
|
||||
filterResult.filtered_faces.forEach(face => {
|
||||
console.log(`❌ Face ${face.face_id} (frame ${face.frame})`);
|
||||
face.reasons.forEach(reason => {
|
||||
console.log(` - ${reason}`);
|
||||
});
|
||||
});
|
||||
```
|
||||
|
||||
### 場景 2: 自訂嚴格過濾
|
||||
|
||||
```typescript
|
||||
// 自訂嚴格過濾規則
|
||||
const strictRules = {
|
||||
version: "1.0",
|
||||
rules: {
|
||||
landmark_analysis: {
|
||||
enabled: true,
|
||||
weight: 0.3,
|
||||
thresholds: {
|
||||
eye_ratio_min: 0.30, // 更嚴格
|
||||
eye_ratio_max: 0.50, // 更嚴格
|
||||
nose_ratio_min: 0.10, // 更嚴格
|
||||
pose_score_max: 0.5 // 更嚴格
|
||||
}
|
||||
},
|
||||
mediapipe_verification: {
|
||||
enabled: true,
|
||||
weight: 0.2,
|
||||
thresholds: {
|
||||
min_iou: 0.5 // 更嚴格
|
||||
}
|
||||
},
|
||||
embedding_similarity: {
|
||||
enabled: true,
|
||||
weight: 0.3,
|
||||
thresholds: {
|
||||
min_similarity: 0.80 // 更嚴格
|
||||
}
|
||||
},
|
||||
temporal_consistency: {
|
||||
enabled: true,
|
||||
weight: 0.2,
|
||||
thresholds: {
|
||||
min_consecutive_frames: 5 // 更嚴格
|
||||
}
|
||||
}
|
||||
},
|
||||
overall_thresholds: {
|
||||
auto_accept: 0.8, // 更嚴格
|
||||
auto_reject: 0.2, // 更嚴格
|
||||
review_range: [0.2, 0.8]
|
||||
}
|
||||
};
|
||||
|
||||
// 儲存規則
|
||||
await fetch('/api/v1/file/0489e104d7d1e11e613da01f7aa130ca/filter-rules', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({
|
||||
rule_name: "strict_filter",
|
||||
rules: strictRules,
|
||||
is_active: true
|
||||
})
|
||||
});
|
||||
|
||||
// 套用嚴格規則
|
||||
const result = await fetch('/api/v1/file/0489e104d7d1e11e613da01f7aa130ca/faces/filter', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ rules: strictRules })
|
||||
});
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 錯誤處理
|
||||
|
||||
### 常見錯誤
|
||||
|
||||
**404 Not Found**:
|
||||
```json
|
||||
{
|
||||
"error": "Face not found"
|
||||
}
|
||||
```
|
||||
**原因**: 臉部 ID 不存在
|
||||
|
||||
**500 Internal Server Error**:
|
||||
```json
|
||||
{
|
||||
"error": "Database error"
|
||||
}
|
||||
```
|
||||
**原因**: 資料庫查詢失敗
|
||||
|
||||
### 錯誤處理範例
|
||||
|
||||
```typescript
|
||||
try {
|
||||
const response = await fetch('/api/v1/file/0489e104d7d1e11e613da01f7aa130ca/face/face_999/filter-report');
|
||||
|
||||
if (!response.ok) {
|
||||
if (response.status === 404) {
|
||||
console.error('Face not found');
|
||||
} else {
|
||||
console.error('Server error');
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
const report = await response.json();
|
||||
console.log(report);
|
||||
} catch (error) {
|
||||
console.error('Request failed:', error);
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 最佳實踐
|
||||
|
||||
### 1. 使用預設規則開始
|
||||
|
||||
建議先使用預設規則,再根據實際需求調整。
|
||||
|
||||
### 2. 逐步調整閾值
|
||||
|
||||
不要一次性調整所有值,逐步調整並觀察結果。
|
||||
|
||||
### 3. 監控過濾統計
|
||||
|
||||
定期檢查過濾統計,確保過濾規則合理。
|
||||
|
||||
### 4. 保存多個規則配置
|
||||
|
||||
為不同場景保存不同的規則配置(如:嚴格、平衡、寬鬆)。
|
||||
|
||||
### 5. 使用者自訂
|
||||
|
||||
允許使用者自訂過濾規則,提供預設模板。
|
||||
|
||||
---
|
||||
|
||||
## 支援與反饋
|
||||
|
||||
如有問題或建議,請聯繫 Core Team。
|
||||
|
||||
**文件版本**: v1.0
|
||||
**最後更新**: 2026-08-09
|
||||
@@ -0,0 +1,114 @@
|
||||
# Trace Thumbnail Regenerate API 使用指南 — Studio 團隊參考
|
||||
|
||||
**版本**: v1.0
|
||||
**日期**: 2026-08-12
|
||||
**狀態**: 已實作(Core)
|
||||
|
||||
---
|
||||
|
||||
## 概述
|
||||
|
||||
修復「key_frame 正常、key_face bbox 正常、但 key_face 縮圖異常」之現象。
|
||||
|
||||
**根因**: bbox 部分越過 frame 邊界(如 trace 355b 案例)時,crop 未 clamp 到 frame 尺寸,ffmpeg 靜默 clamp/位移,導致縮圖內容錯位。由於縮圖端點優先回傳 `key_face.jpg` cache,異常內容被持久化顯示。
|
||||
|
||||
**修復**: 本端點重新選取該 trace 之 best-confidence face,將 bbox clamp 至影片尺寸後重新裁切,覆寫 `key_face.jpg`,並同步更新 `.faces` cache。
|
||||
|
||||
---
|
||||
|
||||
## API 端點
|
||||
|
||||
### POST `/api/v1/file/{file_uuid}/trace/{trace_id}/regenerate-thumbnail`
|
||||
|
||||
**功能**: 重新產生單一 trace 的 face thumbnail(覆寫 cache)
|
||||
**Auth**: Required
|
||||
**Body**: 可為空。
|
||||
|
||||
**Response 200**:
|
||||
```json
|
||||
{
|
||||
"success": true,
|
||||
"file_uuid": "...",
|
||||
"trace_id": 355,
|
||||
"frame": 1835,
|
||||
"bbox": { "x": 65, "y": 301, "width": 70, "height": 59 }
|
||||
}
|
||||
```
|
||||
- `frame` / `bbox` 為重新裁切使用的(clamp 後)frame 與 bbox。
|
||||
|
||||
**Error Responses**:
|
||||
| Status | 說明 |
|
||||
|--------|------|
|
||||
| 404 | Video not found(該 file_uuid 無影片)或 No face found for this trace(該 trace 無 face 資料) |
|
||||
| 400 | Video width/height unavailable — 影片未記錄尺寸,無法 clamp,拒絕重切 |
|
||||
|
||||
---
|
||||
|
||||
## 行為說明
|
||||
|
||||
1. 讀取該 trace 最高 confidence 的 frame + bbox(**不**重跑 blur 優化,取既有 best face 復原同一區域)
|
||||
2. 將 bbox clamp 到影片 width/height 內(`clamp_crop`)
|
||||
3. ffmpeg 自影片以 decoded frame index 切出該 frame → crop face 區域
|
||||
4. 覆寫 `{OUTPUT_DIR}/{file_uuid}/trace_{trace_id}/key_face.jpg`
|
||||
5. 若 `.faces/{file_uuid}/{trace_id}/{frame}.jpg` 已存在則同步覆寫
|
||||
|
||||
**不影響**: Qdrant、`trace_profiles` DB、`tkg_nodes`、影片檔 — 僅重寫縮圖 cache。
|
||||
|
||||
---
|
||||
|
||||
## Studio 整合步驟
|
||||
|
||||
### 1. apiCall (`src/api/index.ts`)
|
||||
|
||||
新增 case:
|
||||
```ts
|
||||
case 'regenerate_trace_thumbnail': {
|
||||
return { url: `/api/v1/file/${a.fileUuid}/trace/${a.traceId}/regenerate-thumbnail`, method: 'POST' }
|
||||
}
|
||||
```
|
||||
|
||||
### 2. Face detail modal 加「Re-gen」按鈕 (`src/views/PeopleView.vue`)
|
||||
|
||||
於 `ms-face-detail-thumb` 附近加入按鈕,呼叫上方 apiCall,in-flight 時 disabled。
|
||||
|
||||
### 3. 觸發後 refresh(重要)
|
||||
|
||||
Face detail 縮圖顯示的是 `faceThumbsCache`(key = `${file_uuid}-${trace_id}`)。`loadTraceThumb` 對已有 cache 的 key 會直接 return,**單獨 `bumpThumbCacheBust()` 無法刷新 face detail 縮圖**。正確順序:
|
||||
|
||||
```ts
|
||||
await apiCall('regenerate_trace_thumbnail', { fileUuid, traceId }) // 1. 呼叫 regenerate
|
||||
delete faceThumbsCache.value[`${fileUuid}-${traceId}`] // 2. 清除該 key 的 blob cache
|
||||
bumpThumbCacheBust() // 3. bump 版本(避 HTTP cache)
|
||||
loadTraceThumb({ file_uuid: fileUuid, trace_id: traceId }) // 4. 重新載入縮圖
|
||||
```
|
||||
|
||||
> `candidateThumbs` 即 `faceThumbsCache` 的 alias(PeopleView.vue:722),delete 後無需額外處理。
|
||||
> 若想一次清空全部縮圖可用 `clearFaceThumbs()`(較重,不建議單一 trace 場景)。
|
||||
|
||||
---
|
||||
|
||||
## 測試指示
|
||||
|
||||
```bash
|
||||
# 使用已知越界案例(trace 355b 一類)驗證:
|
||||
# 1) regenerate 前:GET thumbnail 顯示位移內容
|
||||
# 2) 呼叫 regenerate → 回 success,含 clamp 後 bbox
|
||||
# 3) 再次 GET thumbnail → 內容正確對齊 bbox
|
||||
curl -X POST "http://localhost:3002/api/v1/file/<FILE_UUID>/trace/<TRACE_ID>/regenerate-thumbnail" \
|
||||
-H "X-API-Key: <KEY>"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 參考
|
||||
|
||||
- 根因 crop 修正:`src/core/thumbnail/validator.rs::clamp_crop`、`src/core/processor/tkg.rs`
|
||||
- 端點 handler:`src/api/trace_agent_api.rs::regenerate_trace_thumbnail`
|
||||
|
||||
---
|
||||
|
||||
## 版本歷史
|
||||
|
||||
| 版本 | 日期 | 變更 |
|
||||
|------|------|------|
|
||||
| v1.0 | 2026-08-12 | 初版 |
|
||||
@@ -0,0 +1,188 @@
|
||||
<!-- module: incomplete -->
|
||||
<!-- description: Incomplete, stub, or undocumented API endpoints — tracking list -->
|
||||
<!-- depends: 01_auth -->
|
||||
|
||||
## Incomplete / Undocumented APIs
|
||||
|
||||
This module tracks API endpoints that exist in the codebase but are either undocumented, partially documented, or stubs.
|
||||
|
||||
> **Note**: Endpoints listed here should be fully documented and moved to their appropriate module once implemented.
|
||||
|
||||
---
|
||||
|
||||
## Identity Binding
|
||||
|
||||
### `POST /api/v1/identity/:identity_uuid/bind`
|
||||
|
||||
**Auth**: Required
|
||||
**Scope**: identity-level
|
||||
|
||||
Bind a single face detection to an identity. Unlike `bind/trace` which binds all faces in a trace, this binds one specific face.
|
||||
|
||||
#### Request Parameters
|
||||
|
||||
| Field | Type | Required | Description |
|
||||
|-------|------|----------|-------------|
|
||||
| `file_uuid` | string | Yes | File containing the face |
|
||||
| `face_id` | string | Yes | Face detection ID to bind |
|
||||
|
||||
#### Status
|
||||
|
||||
⚠️ **Undocumented** — exists in code but no full request/response documentation.
|
||||
|
||||
---
|
||||
|
||||
## Resource Management
|
||||
|
||||
### `POST /api/v1/resource/register`
|
||||
|
||||
**Auth**: Required
|
||||
**Scope**: system-level
|
||||
|
||||
Register an external resource (e.g., storage backend, API service).
|
||||
|
||||
#### Status
|
||||
|
||||
⚠️ **Undocumented** — endpoint exists but no documentation.
|
||||
|
||||
---
|
||||
|
||||
### `POST /api/v1/resource/heartbeat`
|
||||
|
||||
**Auth**: Required
|
||||
**Scope**: system-level
|
||||
|
||||
Send heartbeat for a registered resource to verify it's still alive.
|
||||
|
||||
#### Status
|
||||
|
||||
⚠️ **Undocumented** — endpoint exists but no documentation.
|
||||
|
||||
---
|
||||
|
||||
### `GET /api/v1/resources`
|
||||
|
||||
**Auth**: Required
|
||||
**Scope**: system-level
|
||||
|
||||
List all registered resources with their status.
|
||||
|
||||
#### Status
|
||||
|
||||
⚠️ **Undocumented** — endpoint exists but no documentation.
|
||||
|
||||
---
|
||||
|
||||
## 5W1H Agent
|
||||
|
||||
### `POST /api/v1/agents/5w1h/analyze`
|
||||
|
||||
**Auth**: Required
|
||||
**Scope**: file-level
|
||||
|
||||
Run 5W1H analysis on all cut scenes for a file. Uses LLM (Gemma4) to summarize each scene with who/what/where/when/why/how.
|
||||
|
||||
#### Status
|
||||
|
||||
⚠️ **Partially documented** — listed in `12_agent.md` but missing full request/response examples.
|
||||
|
||||
---
|
||||
|
||||
### `POST /api/v1/agents/5w1h/batch`
|
||||
|
||||
**Auth**: Required
|
||||
**Scope**: system-level
|
||||
|
||||
Run 5W1H analysis on multiple files at once.
|
||||
|
||||
#### Request Parameters
|
||||
|
||||
| Field | Type | Required | Description |
|
||||
|-------|------|----------|-------------|
|
||||
| `file_uuids` | string[] | Yes | Array of file UUIDs to analyze |
|
||||
|
||||
#### Status
|
||||
|
||||
⚠️ **Partially documented** — listed in `12_agent.md` but missing full request/response examples.
|
||||
|
||||
---
|
||||
|
||||
### `GET /api/v1/agents/5w1h/status`
|
||||
|
||||
**Auth**: Required
|
||||
**Scope**: system-level
|
||||
|
||||
Get 5W1H analysis status across all videos (which files have been analyzed, which are pending).
|
||||
|
||||
#### Status
|
||||
|
||||
⚠️ **Partially documented** — listed in `12_agent.md` but missing full response schema.
|
||||
|
||||
---
|
||||
|
||||
## Identity Agent
|
||||
|
||||
### `POST /api/v1/agents/identity/match-from-photo`
|
||||
|
||||
**Auth**: Required
|
||||
**Scope**: system-level
|
||||
|
||||
Match an identity using an uploaded photo. Extracts face embedding, finds best trace match.
|
||||
|
||||
#### Status
|
||||
|
||||
⚠️ **Partially documented** — exists in `08_identity_agent.md` but missing full response schema and error cases.
|
||||
|
||||
---
|
||||
|
||||
### `POST /api/v1/agents/identity/match-from-trace`
|
||||
|
||||
**Auth**: Required
|
||||
**Scope**: file-level
|
||||
|
||||
Match an identity using a trace. Multi-angle embedding comparison with propagation.
|
||||
|
||||
#### Status
|
||||
|
||||
⚠️ **Partially documented** — exists in `08_identity_agent.md` but missing full response schema and error cases.
|
||||
|
||||
---
|
||||
|
||||
## Stubs / Not Implemented
|
||||
|
||||
### Visual Search Endpoints
|
||||
|
||||
| Method | Endpoint | Status |
|
||||
|--------|----------|--------|
|
||||
| POST | `/api/v1/search/visual` | Stub — defined but not functional |
|
||||
| POST | `/api/v1/search/visual/class` | Stub — defined but not functional |
|
||||
| POST | `/api/v1/search/visual/density` | Stub — defined but not functional |
|
||||
| POST | `/api/v1/search/visual/combination` | Stub — defined but not functional |
|
||||
| POST | `/api/v1/search/visual/stats` | Stub — defined but not functional |
|
||||
|
||||
### Unmounted Routes
|
||||
|
||||
These endpoints are defined in source code but not mounted in the router:
|
||||
|
||||
| Endpoint | Notes |
|
||||
|----------|-------|
|
||||
| `/api/v1/search/people` | ✅ Mounted |
|
||||
| `/api/v1/who` | Defined but not mounted |
|
||||
| `/api/v1/who/candidates` | Defined but not mounted |
|
||||
|
||||
---
|
||||
|
||||
## Tracking
|
||||
|
||||
| Count | Status |
|
||||
|-------|--------|
|
||||
| Undocumented | 3 (resource management) |
|
||||
| Partially documented | 5 (5W1H ×3, identity agent ×2) |
|
||||
| Stub/not functional | 5 (visual search) |
|
||||
| Defined but unmounted | 2 (who, who/candidates) |
|
||||
| **Total** | **16** |
|
||||
|
||||
---
|
||||
|
||||
*Created: 2026-06-20 — Gap analysis from core API vs doc_wasm sync*
|
||||
*Updated: 2026-06-20 — Initial tracking list*
|
||||
@@ -0,0 +1,228 @@
|
||||
# A-8 设计:配置驱动的 Processor 清单
|
||||
|
||||
**Date**: 2026-10-04
|
||||
**Status**: 设计中
|
||||
**Priority**: P0(阻塞)
|
||||
|
||||
---
|
||||
|
||||
## 背景
|
||||
|
||||
`sync_file_status` 目前使用硬编码的 processor 清单来判断文件状态。这导致:
|
||||
1. 取消 processor 需要修改代码并重新部署
|
||||
2. 新增 processor 需要修改代码并重新部署
|
||||
3. 不同环境可能需要不同的 processor 集合
|
||||
|
||||
---
|
||||
|
||||
## 当前实现(已修复)
|
||||
|
||||
```rust
|
||||
// files.rs:1805-1813
|
||||
let processors = [
|
||||
("asr", "asr.json"),
|
||||
("asrx", "asrx.json"),
|
||||
("ocr", "ocr.json"),
|
||||
("cut", "cut.json"),
|
||||
("face", "face.json"),
|
||||
("face_cluster", "face_cluster.json"),
|
||||
];
|
||||
```
|
||||
|
||||
**问题**:`pose` 已取消但仍列在清单中 → status 永久 `scanning`
|
||||
|
||||
---
|
||||
|
||||
## 设计方案
|
||||
|
||||
### 方案 A:数据库配置表
|
||||
|
||||
**优点**:
|
||||
- 可通过 API 动态调整
|
||||
- 支持多租户(不同用户不同配置)
|
||||
- 有审计记录
|
||||
|
||||
**缺点**:
|
||||
- 需要额外的表结构
|
||||
- 需要迁移脚本
|
||||
- 启动时依赖数据库连接
|
||||
|
||||
**表结构**:
|
||||
```sql
|
||||
CREATE TABLE processor_config (
|
||||
id SERIAL PRIMARY KEY,
|
||||
processor_name VARCHAR(50) NOT NULL UNIQUE,
|
||||
json_file VARCHAR(100) NOT NULL,
|
||||
is_required BOOLEAN DEFAULT true,
|
||||
is_enabled BOOLEAN DEFAULT true,
|
||||
created_at TIMESTAMP DEFAULT NOW(),
|
||||
updated_at TIMESTAMP DEFAULT NOW()
|
||||
);
|
||||
|
||||
-- 初始数据
|
||||
INSERT INTO processor_config (processor_name, json_file, is_required, is_enabled) VALUES
|
||||
('asr', 'asr.json', true, true),
|
||||
('asrx', 'asrx.json', true, true),
|
||||
('ocr', 'ocr.json', true, true),
|
||||
('cut', 'cut.json', true, true),
|
||||
('face', 'face.json', true, true),
|
||||
('face_cluster', 'face_cluster.json', true, true),
|
||||
('pose', 'pose.json', false, false); -- 已取消
|
||||
```
|
||||
|
||||
**实现**:
|
||||
```rust
|
||||
async fn get_required_processors(db: &PostgresDb) -> Result<Vec<(String, String)>> {
|
||||
sqlx::query_as("SELECT processor_name, json_file FROM processor_config WHERE is_required = true AND is_enabled = true")
|
||||
.fetch_all(db.pool())
|
||||
.await
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 方案 B:配置文件
|
||||
|
||||
**优点**:
|
||||
- 简单,无需数据库
|
||||
- 启动时不依赖数据库
|
||||
- 易于版本控制
|
||||
|
||||
**缺点**:
|
||||
- 修改需要重启服务
|
||||
- 不支持动态调整
|
||||
- 多实例部署需要同步配置
|
||||
|
||||
**配置文件** (`config/processors.toml`):
|
||||
```toml
|
||||
[[processors]]
|
||||
name = "asr"
|
||||
json_file = "asr.json"
|
||||
required = true
|
||||
enabled = true
|
||||
|
||||
[[processors]]
|
||||
name = "asrx"
|
||||
json_file = "asrx.json"
|
||||
required = true
|
||||
enabled = true
|
||||
|
||||
[[processors]]
|
||||
name = "pose"
|
||||
json_file = "pose.json"
|
||||
required = false
|
||||
enabled = false
|
||||
```
|
||||
|
||||
**实现**:
|
||||
```rust
|
||||
#[derive(Deserialize)]
|
||||
struct ProcessorConfig {
|
||||
name: String,
|
||||
json_file: String,
|
||||
required: bool,
|
||||
#[serde(default)]
|
||||
enabled: bool,
|
||||
}
|
||||
|
||||
fn load_processor_config() -> Result<Vec<(String, String)>> {
|
||||
let config: Vec<ProcessorConfig> = toml::from_str(&std::fs::read_to_string("config/processors.toml")?)?;
|
||||
Ok(config.into_iter()
|
||||
.filter(|p| p.required && p.enabled)
|
||||
.map(|p| (p.name, p.json_file))
|
||||
.collect())
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 方案 C:环境变量 + 默认值
|
||||
|
||||
**优点**:
|
||||
- 最简单
|
||||
- 无需额外文件或表
|
||||
- 容器化友好
|
||||
|
||||
**缺点**:
|
||||
- 环境变量可能很长
|
||||
- 不够结构化
|
||||
- 难以表达 required/enabled 状态
|
||||
|
||||
**实现**:
|
||||
```rust
|
||||
fn get_required_processors() -> Vec<(String, String)> {
|
||||
let default = vec![
|
||||
("asr", "asr.json"),
|
||||
("asrx", "asrx.json"),
|
||||
("ocr", "ocr.json"),
|
||||
("cut", "cut.json"),
|
||||
("face", "face.json"),
|
||||
("face_cluster", "face_cluster.json"),
|
||||
];
|
||||
|
||||
std::env::var("MOMENTRY_REQUIRED_PROCESSORS")
|
||||
.map(|s| {
|
||||
s.split(',')
|
||||
.filter_map(|p| {
|
||||
let parts: Vec<&str> = p.split(':').collect();
|
||||
if parts.len() == 2 {
|
||||
Some((parts[0].to_string(), parts[1].to_string()))
|
||||
} else {
|
||||
None
|
||||
}
|
||||
})
|
||||
.collect()
|
||||
})
|
||||
.unwrap_or(default)
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 推荐方案
|
||||
|
||||
**阶段 1(立即)**:方案 B(配置文件)
|
||||
- 快速实现
|
||||
- 无需数据库迁移
|
||||
- 满足当前需求
|
||||
|
||||
**阶段 2(未来)**:方案 A(数据库配置表)
|
||||
- 当需要动态调整时迁移
|
||||
- 支持多租户场景
|
||||
- 有审计记录
|
||||
|
||||
---
|
||||
|
||||
## 实现计划
|
||||
|
||||
### Phase 1:配置文件(本周)
|
||||
|
||||
1. 创建 `config/processors.toml`
|
||||
2. 实现 `load_processor_config()` 函数
|
||||
3. 修改 `sync_file_status` 使用配置文件
|
||||
4. 新增测试:已取消 processor 不阻挡 completed
|
||||
5. 更新文档
|
||||
|
||||
### Phase 2:数据库配置表(待评估)
|
||||
|
||||
1. 设计表结构
|
||||
2. 编写迁移脚本
|
||||
3. 实现 API endpoint
|
||||
4. 迁移现有配置
|
||||
|
||||
---
|
||||
|
||||
## 验收标准
|
||||
|
||||
- ✅ 移除 pose(已完成 commit `d7df19e2`)
|
||||
- ⏳ processor 清单可配置
|
||||
- ⏳ 取消 processor 不阻挡 completed
|
||||
- ⏳ 新增测试案例
|
||||
|
||||
---
|
||||
|
||||
## 相关文档
|
||||
|
||||
- 需求:`Momentry_Release_Requirements_20261004.md` A-8
|
||||
- 诊断:附录 C
|
||||
- 实现:`src/api/files.rs:1805`
|
||||
@@ -0,0 +1,487 @@
|
||||
# Agent Search 统一智能搜尋介面设计
|
||||
|
||||
**版本**: 1.0
|
||||
**日期**: 2026-10-11
|
||||
**状态**: 正式命名
|
||||
|
||||
---
|
||||
|
||||
## 🎯 命名规范
|
||||
|
||||
### 顶层统一介面
|
||||
|
||||
**名称**: **Agent Search** (统一智能搜尋介面)
|
||||
|
||||
**定位**:
|
||||
- 顶层统一入口
|
||||
- 智能路由
|
||||
- 用户无需选择搜索类型
|
||||
- 系统自动选择最佳搜索方式
|
||||
|
||||
---
|
||||
|
||||
### 底层搜索类型(保持不变)
|
||||
|
||||
Agent Search 内部调用以下 5 种搜索类型:
|
||||
|
||||
| 类型 | 技术 | 特点 | 用例 |
|
||||
|------|------|------|------|
|
||||
| **Keyword** | BM25 + FTS | 精确匹配,快速 | "interview with Obama" |
|
||||
| **Semantic** | Vector Embedding | 语义理解,模糊匹配 | "people discussing politics" |
|
||||
| **Visual** | VLM + CLIP | 视觉内容,场景描述 | "sunset beach" |
|
||||
| **Agent** | LLM + RAG | 复杂查询,推理 | "compare Obama and Biden on healthcare" |
|
||||
| **People** | Face Identity | 人物识别,身份关联 | "videos with Barack Obama" |
|
||||
|
||||
---
|
||||
|
||||
## 🏗️ 架构层次
|
||||
|
||||
```
|
||||
┌─────────────────────────────────────────────────────────────────┐
|
||||
│ Agent Search (统一介面) │
|
||||
│ ├─ Query Analyzer (智能路由) │
|
||||
│ ├─ Strategy Selector (策略选择) │
|
||||
│ ├─ Result Merger (结果合并) │
|
||||
│ └─ Summary Generator (摘要生成) │
|
||||
└─────────────────────────────────────────────────────────────────┘
|
||||
│
|
||||
├─────────┬─────────┬─────────┬─────────┐
|
||||
▼ ▼ ▼ ▼ ▼
|
||||
┌────────┐ ┌────────┐ ┌────────┐ ┌────────┐ ┌────────┐
|
||||
│Keyword │ │Semantic│ │ Visual │ │ Agent │ │ People │
|
||||
│ Search │ │ Search │ │ Search │ │ Search │ │ Search │
|
||||
└────────┘ └────────┘ └────────┘ └────────┘ └────────┘
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 💬 Agent Search Service
|
||||
|
||||
### 核心功能
|
||||
|
||||
```rust
|
||||
// MarkBase Queue Protocol - Independent Implementation
|
||||
// This is NOT compatible with Apache Kafka protocol or API.
|
||||
|
||||
use super::types::*;
|
||||
use crate::core::command::messenger::Messenger;
|
||||
use crate::core::command::error::{CommandError, CommandResult};
|
||||
use crate::core::command::messenger::types::{Message, MessageSource, MessagePriority, MessageType, DeliveryOptions};
|
||||
use crate::core::llm::LLMClient;
|
||||
use std::time::Instant;
|
||||
use tracing::{debug, info};
|
||||
|
||||
/// Agent Search 服务(统一智能搜尋介面)
|
||||
pub struct AgentSearchService {
|
||||
messenger: Messenger,
|
||||
llm_client: LLMClient,
|
||||
query_analyzer: QueryAnalyzer,
|
||||
}
|
||||
|
||||
impl AgentSearchService {
|
||||
pub fn new(db: sqlx::PgPool, llm_client: LLMClient) -> Self {
|
||||
Self {
|
||||
messenger: Messenger::new(db),
|
||||
llm_client: llm_client.clone(),
|
||||
query_analyzer: QueryAnalyzer::new(llm_client),
|
||||
}
|
||||
}
|
||||
|
||||
/// Agent Search 入口(智能路由)
|
||||
pub async fn search(
|
||||
&self,
|
||||
query: &str,
|
||||
context: Option<SearchContext>,
|
||||
) -> CommandResult<AgentSearchResponse> {
|
||||
let start = Instant::now();
|
||||
|
||||
// 1. 分析查询意图
|
||||
let intent = self.query_analyzer.analyze(query, context.clone()).await?;
|
||||
|
||||
debug!(
|
||||
query = %query,
|
||||
intent = ?intent.search_types,
|
||||
confidence = intent.confidence,
|
||||
"Query intent analyzed"
|
||||
);
|
||||
|
||||
// 2. 根据意图选择搜索策略
|
||||
let strategy = self.select_strategy(&intent);
|
||||
|
||||
// 3. 执行搜索(可能并行多个类型)
|
||||
let results = self.execute_strategy(&strategy, query, context.clone()).await?;
|
||||
|
||||
// 4. 合并结果
|
||||
let response = self.merge_results(results, query, intent).await?;
|
||||
|
||||
info!(
|
||||
query = %query,
|
||||
took_ms = start.elapsed().as_millis(),
|
||||
total_results = response.total_count,
|
||||
"Agent Search completed"
|
||||
);
|
||||
|
||||
Ok(response)
|
||||
}
|
||||
|
||||
/// 选择搜索策略
|
||||
fn select_strategy(&self, intent: &QueryIntent) -> SearchStrategy {
|
||||
// 实现细节...
|
||||
match intent.primary_type {
|
||||
SearchType::Keyword if intent.confidence > 0.8 => {
|
||||
SearchStrategy::Single(SearchType::Keyword)
|
||||
}
|
||||
SearchType::Semantic if intent.confidence > 0.8 => {
|
||||
SearchStrategy::Single(SearchType::Semantic)
|
||||
}
|
||||
SearchType::Visual if intent.confidence > 0.8 => {
|
||||
SearchStrategy::Single(SearchType::Visual)
|
||||
}
|
||||
SearchType::People if intent.confidence > 0.8 => {
|
||||
SearchStrategy::Single(SearchType::People)
|
||||
}
|
||||
SearchType::Agent if intent.confidence > 0.7 => {
|
||||
SearchStrategy::Single(SearchType::Agent)
|
||||
}
|
||||
_ => {
|
||||
// 混合策略
|
||||
let mut types = Vec::new();
|
||||
if intent.scores.keyword > 0.3 {
|
||||
types.push((SearchType::Keyword, intent.scores.keyword));
|
||||
}
|
||||
if intent.scores.semantic > 0.3 {
|
||||
types.push((SearchType::Semantic, intent.scores.semantic));
|
||||
}
|
||||
if intent.scores.visual > 0.3 {
|
||||
types.push((SearchType::Visual, intent.scores.visual));
|
||||
}
|
||||
if intent.scores.people > 0.3 {
|
||||
types.push((SearchType::People, intent.scores.people));
|
||||
}
|
||||
if types.is_empty() {
|
||||
types.push((SearchType::Agent, 1.0));
|
||||
}
|
||||
SearchStrategy::Hybrid(types)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 执行搜索策略
|
||||
async fn execute_strategy(
|
||||
&self,
|
||||
strategy: &SearchStrategy,
|
||||
query: &str,
|
||||
context: Option<SearchContext>,
|
||||
) -> CommandResult<Vec<SearchResponse>> {
|
||||
// 实现细节...
|
||||
match strategy {
|
||||
SearchStrategy::Single(search_type) => {
|
||||
let response = self.execute_single_search(search_type, query, context).await?;
|
||||
Ok(vec![response])
|
||||
}
|
||||
SearchStrategy::Hybrid(types) => {
|
||||
// 并行执行多个搜索
|
||||
let mut handles = Vec::new();
|
||||
for (search_type, weight) in types {
|
||||
let handle = self.execute_single_search(search_type, query, context.clone());
|
||||
handles.push((search_type.clone(), weight, handle));
|
||||
}
|
||||
|
||||
// 收集结果
|
||||
let mut results = Vec::new();
|
||||
for (search_type, _weight, handle) in handles {
|
||||
match handle.await {
|
||||
Ok(response) => {
|
||||
results.push(response);
|
||||
}
|
||||
Err(e) => {
|
||||
debug!(search_type = ?search_type, error = ?e, "Search failed");
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(results)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 执行单一类型搜索
|
||||
async fn execute_single_search(
|
||||
&self,
|
||||
search_type: &SearchType,
|
||||
query: &str,
|
||||
context: Option<SearchContext>,
|
||||
) -> CommandResult<SearchResponse> {
|
||||
let request = SearchRequest::new(query.to_string(), search_type.clone())
|
||||
.with_filters(context.clone().map(|c| c.filters).unwrap_or_default())
|
||||
.with_options(context.clone().map(|c| c.options).unwrap_or_default());
|
||||
|
||||
// 发送到对应的搜索队列
|
||||
let queue_name = format!("search.{}", serde_json::to_string(search_type)?.to_lowercase());
|
||||
let request_id = self.messenger.send_search_request(&request).await?;
|
||||
|
||||
// 等待结果
|
||||
let timeout = request.options.limit.unwrap_or(30) as u64 * 1000;
|
||||
let deadline = Instant::now() + std::time::Duration::from_millis(timeout);
|
||||
|
||||
loop {
|
||||
if Instant::now() > deadline {
|
||||
return Err(CommandError::Timeout(timeout as i32));
|
||||
}
|
||||
|
||||
if let Some(response) = self.messenger.get_search_result(&request_id).await? {
|
||||
return Ok(response);
|
||||
}
|
||||
|
||||
tokio::time::sleep(std::time::Duration::from_millis(100)).await;
|
||||
}
|
||||
}
|
||||
|
||||
/// 合并搜索结果
|
||||
async fn merge_results(
|
||||
&self,
|
||||
results: Vec<SearchResponse>,
|
||||
query: &str,
|
||||
intent: QueryIntent,
|
||||
) -> CommandResult<AgentSearchResponse> {
|
||||
let mut all_results = Vec::new();
|
||||
let mut seen_ids = std::collections::HashSet::new();
|
||||
|
||||
// 收集所有结果
|
||||
for response in results {
|
||||
for result in response.results {
|
||||
if !seen_ids.contains(&result.id) {
|
||||
seen_ids.insert(result.id.clone());
|
||||
all_results.push(result);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 重新评分和排序
|
||||
for result in &mut all_results {
|
||||
result.score = result.score * (0.5 + 0.5 * intent.confidence);
|
||||
}
|
||||
all_results.sort_by(|a, b| b.score.partial_cmp(&a.score).unwrap());
|
||||
|
||||
// 生成摘要
|
||||
let summary = self.generate_summary(query, &all_results).await?;
|
||||
|
||||
Ok(AgentSearchResponse {
|
||||
query: query.to_string(),
|
||||
intent,
|
||||
results: all_results,
|
||||
total_count: all_results.len() as i64,
|
||||
summary,
|
||||
took_ms: 0,
|
||||
})
|
||||
}
|
||||
|
||||
/// 生成摘要
|
||||
async fn generate_summary(&self, query: &str, results: &[SearchResult]) -> CommandResult<String> {
|
||||
if results.is_empty() {
|
||||
return Ok("No results found.".to_string());
|
||||
}
|
||||
|
||||
let prompt = format!(
|
||||
"Summarize search results for query '{}' in 2-3 sentences. Found {} results.",
|
||||
query,
|
||||
results.len()
|
||||
);
|
||||
|
||||
self.llm_client.chat(&prompt).await
|
||||
}
|
||||
|
||||
/// 对话式搜索
|
||||
pub async fn conversational_search(
|
||||
&self,
|
||||
conversation_id: &str,
|
||||
query: &str,
|
||||
) -> CommandResult<AgentSearchResponse> {
|
||||
// 获取对话历史
|
||||
let history = self.get_conversation_history(conversation_id).await?;
|
||||
|
||||
let context = SearchContext {
|
||||
conversation_id: Some(conversation_id.to_string()),
|
||||
conversation_history: history,
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
let response = self.search(query, Some(context)).await?;
|
||||
|
||||
// 更新对话历史
|
||||
self.update_conversation(conversation_id, query, &response).await?;
|
||||
|
||||
Ok(response)
|
||||
}
|
||||
|
||||
async fn get_conversation_history(&self, _conversation_id: &str) -> CommandResult<Vec<Message>> {
|
||||
// TODO: 从数据库获取
|
||||
Ok(Vec::new())
|
||||
}
|
||||
|
||||
async fn update_conversation(
|
||||
&self,
|
||||
_conversation_id: &str,
|
||||
_query: &str,
|
||||
_response: &AgentSearchResponse,
|
||||
) -> CommandResult<()> {
|
||||
// TODO: 更新到数据库
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 🔄 API 端点
|
||||
|
||||
```rust
|
||||
// POST /api/v1/agent/search
|
||||
pub async fn agent_search(
|
||||
Extension(agent_search_service): Extension<Arc<AgentSearchService>>,
|
||||
Extension(auth): Extension<UserAuth>,
|
||||
Json(request): Json<AgentSearchRequest>,
|
||||
) -> Result<Json<AgentSearchResponse>, APIError> {
|
||||
let context = SearchContext {
|
||||
user_id: Some(auth.user_id),
|
||||
..request.context.unwrap_or_default()
|
||||
};
|
||||
|
||||
let response = agent_search_service.search(&request.query, Some(context)).await?;
|
||||
|
||||
Ok(Json(response))
|
||||
}
|
||||
|
||||
// POST /api/v1/agent/search/conversation
|
||||
pub async fn agent_search_conversation(
|
||||
Extension(agent_search_service): Extension<Arc<AgentSearchService>>,
|
||||
Extension(auth): Extension<UserAuth>,
|
||||
Json(request): Json<ConversationSearchRequest>,
|
||||
) -> Result<Json<AgentSearchResponse>, APIError> {
|
||||
let response = agent_search_service
|
||||
.conversational_search(&request.conversation_id, &request.query)
|
||||
.await?;
|
||||
|
||||
Ok(Json(response))
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 📊 数据模型
|
||||
|
||||
```rust
|
||||
/// Agent Search 请求
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct AgentSearchRequest {
|
||||
pub query: String,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub context: Option<SearchContext>,
|
||||
}
|
||||
|
||||
/// Agent Search 响应
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct AgentSearchResponse {
|
||||
pub query: String,
|
||||
pub intent: QueryIntent,
|
||||
pub results: Vec<SearchResult>,
|
||||
pub total_count: i64,
|
||||
pub summary: String,
|
||||
pub took_ms: i64,
|
||||
}
|
||||
|
||||
/// 查询意图
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct QueryIntent {
|
||||
pub primary_type: SearchType,
|
||||
pub search_types: Vec<SearchType>,
|
||||
pub confidence: f64,
|
||||
pub scores: SearchTypeScores,
|
||||
pub entities: Vec<String>,
|
||||
pub keywords: Vec<String>,
|
||||
}
|
||||
|
||||
/// 搜索类型分数
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
|
||||
pub struct SearchTypeScores {
|
||||
pub keyword: f64,
|
||||
pub semantic: f64,
|
||||
pub visual: f64,
|
||||
pub agent: f64,
|
||||
pub people: f64,
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 🎯 用户介面
|
||||
|
||||
### 统一搜索框
|
||||
|
||||
```html
|
||||
<div class="agent-search">
|
||||
<input
|
||||
type="text"
|
||||
placeholder="Ask anything about your videos..."
|
||||
class="search-input"
|
||||
/>
|
||||
<div class="search-hints">
|
||||
<p>Try:</p>
|
||||
<span class="hint">"interview with Obama"</span>
|
||||
<span class="hint">"people discussing politics"</span>
|
||||
<span class="hint">"sunset at beach"</span>
|
||||
<span class="hint">"compare Obama and Biden on healthcare"</span>
|
||||
<span class="hint">"videos with Barack Obama"</span>
|
||||
</div>
|
||||
</div>
|
||||
```
|
||||
|
||||
### 搜索结果
|
||||
|
||||
```json
|
||||
{
|
||||
"query": "Obama healthcare speech",
|
||||
"intent": {
|
||||
"primary_type": "people",
|
||||
"confidence": 0.85,
|
||||
"search_types": ["people", "keyword", "semantic"]
|
||||
},
|
||||
"results": [
|
||||
{
|
||||
"id": "video_123",
|
||||
"score": 0.96,
|
||||
"snippet": "Obama delivers speech on healthcare reform...",
|
||||
"thumbnail": "https://..."
|
||||
}
|
||||
],
|
||||
"total_count": 15,
|
||||
"summary": "Found 15 videos featuring Barack Obama discussing healthcare...",
|
||||
"took_ms": 250
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 🚀 实施计划
|
||||
|
||||
### Phase 1: 核心实现(3 天)
|
||||
|
||||
- [ ] 实现 AgentSearchService
|
||||
- [ ] 实现 QueryAnalyzer
|
||||
- [ ] 实现 5 种底层搜索 Worker
|
||||
- [ ] 单元测试
|
||||
|
||||
### Phase 2: 集成(2 天)
|
||||
|
||||
- [ ] 集成到 Studio UI
|
||||
- [ ] 实现 API 端点
|
||||
- [ ] 对话历史管理
|
||||
|
||||
### Phase 3: 优化(2 天)
|
||||
|
||||
- [ ] 性能优化
|
||||
- [ ] 智能路由优化
|
||||
- [ ] 用户体验改进
|
||||
|
||||
---
|
||||
|
||||
**Agent Search 正式命名完成!统一智能搜尋介面,用户无需选择类型。**
|
||||
@@ -0,0 +1,799 @@
|
||||
# Agent Search 分页与 More 按钮设计
|
||||
|
||||
**版本**: 1.0
|
||||
**日期**: 2026-10-11
|
||||
**状态**: 设计规范
|
||||
|
||||
---
|
||||
|
||||
## 🎯 设计目标
|
||||
|
||||
**默认返回**: Top 5 结果
|
||||
**More 按钮**: 每次增加 10 个结果
|
||||
**翻页机制**: 避免缺漏,逐步展示
|
||||
|
||||
---
|
||||
|
||||
## 📊 分页规则
|
||||
|
||||
### 1. 初始查询
|
||||
|
||||
```
|
||||
First Query:
|
||||
- offset: 0
|
||||
- limit: 5
|
||||
- 返回: Top 5 结果
|
||||
- has_more: true/false
|
||||
```
|
||||
|
||||
### 2. More 操作
|
||||
|
||||
```
|
||||
Click "More":
|
||||
- offset: 5
|
||||
- limit: 10
|
||||
- 返回: 第 6-15 条结果
|
||||
- has_more: true/false
|
||||
```
|
||||
|
||||
### 3. 再次 More
|
||||
|
||||
```
|
||||
Click "More" Again:
|
||||
- offset: 15
|
||||
- limit: 10
|
||||
- 返回: 第 16-25 条结果
|
||||
- has_more: true/false
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 💬 API 设计
|
||||
|
||||
### 请求模型
|
||||
|
||||
```rust
|
||||
// MarkBase Queue Protocol - Independent Implementation
|
||||
// This is NOT compatible with Apache Kafka protocol or API.
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// Agent Search 请求
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct AgentSearchRequest {
|
||||
/// 搜索查询
|
||||
pub query: String,
|
||||
|
||||
/// 偏移量
|
||||
#[serde(default)]
|
||||
pub offset: i32,
|
||||
|
||||
/// 限制数量
|
||||
/// - 首次查询: 5(默认)
|
||||
/// - More 操作: 10
|
||||
#[serde(default = "default_limit")]
|
||||
pub limit: i32,
|
||||
|
||||
/// 搜索上下文
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub context: Option<SearchContext>,
|
||||
|
||||
/// 会话 ID(用于保持分页状态)
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub session_id: Option<String>,
|
||||
}
|
||||
|
||||
fn default_limit() -> i32 {
|
||||
5
|
||||
}
|
||||
|
||||
/// Search 上下文
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
|
||||
pub struct SearchContext {
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub user_id: Option<String>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub conversation_id: Option<String>,
|
||||
#[serde(default)]
|
||||
pub filters: SearchFilters,
|
||||
}
|
||||
|
||||
/// More 请求
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct MoreRequest {
|
||||
/// 会话 ID
|
||||
pub session_id: String,
|
||||
|
||||
/// 当前偏移量
|
||||
pub current_offset: i32,
|
||||
|
||||
/// 返回数量(固定 10)
|
||||
#[serde(default = "more_limit")]
|
||||
pub limit: i32,
|
||||
}
|
||||
|
||||
fn more_limit() -> i32 {
|
||||
10
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 响应模型
|
||||
|
||||
```rust
|
||||
/// Agent Search 响应
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct AgentSearchResponse {
|
||||
/// 搜索查询
|
||||
pub query: String,
|
||||
|
||||
/// 会话 ID(用于分页)
|
||||
pub session_id: String,
|
||||
|
||||
/// 查询意图
|
||||
pub intent: QueryIntent,
|
||||
|
||||
/// 搜索结果
|
||||
pub results: Vec<SearchResult>,
|
||||
|
||||
/// 总数量
|
||||
pub total_count: i64,
|
||||
|
||||
/// 当前偏移量
|
||||
pub offset: i32,
|
||||
|
||||
/// 当前返回数量
|
||||
pub returned_count: i32,
|
||||
|
||||
/// 是否有更多结果
|
||||
pub has_more: bool,
|
||||
|
||||
/// 下一页偏移量
|
||||
pub next_offset: Option<i32>,
|
||||
|
||||
/// 摘要
|
||||
pub summary: String,
|
||||
|
||||
/// 耗时(毫秒)
|
||||
pub took_ms: i64,
|
||||
}
|
||||
|
||||
/// 搜索结果
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct SearchResult {
|
||||
/// 结果 ID
|
||||
pub id: String,
|
||||
|
||||
/// 分数
|
||||
pub score: f64,
|
||||
|
||||
/// 文件 UUID
|
||||
pub file_uuid: String,
|
||||
|
||||
/// 时间戳
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub timestamp: Option<f64>,
|
||||
|
||||
/// 时长
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub duration: Option<f64>,
|
||||
|
||||
/// 片段
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub snippet: Option<String>,
|
||||
|
||||
/// 高亮
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub highlights: Option<Vec<Highlight>>,
|
||||
|
||||
/// 元数据
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub metadata: Option<serde_json::Value>,
|
||||
|
||||
/// 缩略图
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub thumbnail: Option<String>,
|
||||
}
|
||||
|
||||
/// 高亮
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct Highlight {
|
||||
pub field: String,
|
||||
pub fragments: Vec<String>,
|
||||
}
|
||||
|
||||
/// 查询意图
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct QueryIntent {
|
||||
pub primary_type: SearchType,
|
||||
pub confidence: f64,
|
||||
pub search_types: Vec<SearchType>,
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 🔄 工作流程
|
||||
|
||||
### 流程 1: 初始搜索
|
||||
|
||||
```
|
||||
用户: "Obama healthcare speech"
|
||||
↓
|
||||
POST /api/v1/agent/search
|
||||
{
|
||||
"query": "Obama healthcare speech",
|
||||
"offset": 0,
|
||||
"limit": 5
|
||||
}
|
||||
↓
|
||||
AgentSearchService.search()
|
||||
↓
|
||||
{
|
||||
"session_id": "sess_abc123",
|
||||
"results": [
|
||||
{"id": "video_1", "score": 0.96, ...},
|
||||
{"id": "video_2", "score": 0.92, ...},
|
||||
{"id": "video_3", "score": 0.88, ...},
|
||||
{"id": "video_4", "score": 0.85, ...},
|
||||
{"id": "video_5", "score": 0.82, ...}
|
||||
],
|
||||
"total_count": 25,
|
||||
"offset": 0,
|
||||
"returned_count": 5,
|
||||
"has_more": true,
|
||||
"next_offset": 5,
|
||||
"summary": "Found 25 videos..."
|
||||
}
|
||||
↓
|
||||
UI 显示:
|
||||
- Top 5 结果
|
||||
- "More" 按钮(因为有 has_more: true)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 流程 2: 点击 More
|
||||
|
||||
```
|
||||
用户: 点击 "More"
|
||||
↓
|
||||
POST /api/v1/agent/search/more
|
||||
{
|
||||
"session_id": "sess_abc123",
|
||||
"current_offset": 5,
|
||||
"limit": 10
|
||||
}
|
||||
↓
|
||||
AgentSearchService.more()
|
||||
↓
|
||||
{
|
||||
"session_id": "sess_abc123",
|
||||
"results": [
|
||||
{"id": "video_6", "score": 0.79, ...},
|
||||
{"id": "video_7", "score": 0.76, ...},
|
||||
...
|
||||
{"id": "video_15", "score": 0.65, ...}
|
||||
],
|
||||
"total_count": 25,
|
||||
"offset": 5,
|
||||
"returned_count": 10,
|
||||
"has_more": true,
|
||||
"next_offset": 15,
|
||||
"summary": null // More 操作不生成新摘要
|
||||
}
|
||||
↓
|
||||
UI 显示:
|
||||
- 追加 10 个结果(现在显示 15 个)
|
||||
- "More" 按钮继续显示(因为 has_more: true)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 流程 3: 再次 More
|
||||
|
||||
```
|
||||
用户: 再次点击 "More"
|
||||
↓
|
||||
POST /api/v1/agent/search/more
|
||||
{
|
||||
"session_id": "sess_abc123",
|
||||
"current_offset": 15,
|
||||
"limit": 10
|
||||
}
|
||||
↓
|
||||
{
|
||||
"session_id": "sess_abc123",
|
||||
"results": [
|
||||
{"id": "video_16", "score": 0.62, ...},
|
||||
...
|
||||
{"id": "video_25", "score": 0.45, ...}
|
||||
],
|
||||
"total_count": 25,
|
||||
"offset": 15,
|
||||
"returned_count": 10,
|
||||
"has_more": false, // 没有更多了
|
||||
"next_offset": null,
|
||||
"summary": null
|
||||
}
|
||||
↓
|
||||
UI 显示:
|
||||
- 追加 10 个结果(现在显示 25 个)
|
||||
- "More" 按钮消失(因为 has_more: false)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 🎨 UI 设计
|
||||
|
||||
### 搜索结果界面
|
||||
|
||||
```html
|
||||
<div class="search-results">
|
||||
<!-- 摘要 -->
|
||||
<div class="summary">
|
||||
Found 25 videos featuring Barack Obama discussing healthcare...
|
||||
</div>
|
||||
|
||||
<!-- 结果列表 -->
|
||||
<div class="results-list">
|
||||
<!-- Top 5 -->
|
||||
<div class="result-item" data-id="video_1">
|
||||
<img src="thumbnail.jpg" />
|
||||
<div class="result-info">
|
||||
<h3>Obama Healthcare Speech 2010</h3>
|
||||
<p class="snippet">Obama delivers speech on healthcare reform...</p>
|
||||
<span class="score">Score: 0.96</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- ... 其他 4 个结果 ... -->
|
||||
</div>
|
||||
|
||||
<!-- More 按钮 -->
|
||||
<button class="more-button" data-session="sess_abc123" data-offset="5">
|
||||
More Results (20 remaining)
|
||||
</button>
|
||||
</div>
|
||||
```
|
||||
|
||||
### More 按钮 UI
|
||||
|
||||
```css
|
||||
.more-button {
|
||||
width: 100%;
|
||||
padding: 12px;
|
||||
margin-top: 16px;
|
||||
background: #f0f0f0;
|
||||
border: 1px solid #ddd;
|
||||
border-radius: 4px;
|
||||
cursor: pointer;
|
||||
font-size: 14px;
|
||||
color: #666;
|
||||
transition: all 0.2s;
|
||||
}
|
||||
|
||||
.more-button:hover {
|
||||
background: #e0e0e0;
|
||||
border-color: #bbb;
|
||||
}
|
||||
|
||||
.more-button:disabled {
|
||||
opacity: 0.5;
|
||||
cursor: not-allowed;
|
||||
}
|
||||
|
||||
.more-button.loading {
|
||||
background: url('spinner.gif') no-repeat center;
|
||||
color: transparent;
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 🔌 API 端点
|
||||
|
||||
### POST /api/v1/agent/search
|
||||
|
||||
```rust
|
||||
pub async fn agent_search(
|
||||
Extension(agent_search_service): Extension<Arc<AgentSearchService>>,
|
||||
Extension(auth): Extension<UserAuth>,
|
||||
Json(request): Json<AgentSearchRequest>,
|
||||
) -> Result<Json<AgentSearchResponse>, APIError> {
|
||||
// 验证分页参数
|
||||
if request.offset < 0 {
|
||||
return Err(APIError::BadRequest("offset must be >= 0".to_string()));
|
||||
}
|
||||
|
||||
if request.limit < 1 || request.limit > 100 {
|
||||
return Err(APIError::BadRequest("limit must be between 1 and 100".to_string()));
|
||||
}
|
||||
|
||||
let context = SearchContext {
|
||||
user_id: Some(auth.user_id),
|
||||
..request.context.unwrap_or_default()
|
||||
};
|
||||
|
||||
let response = agent_search_service
|
||||
.search(&request.query, request.offset, request.limit, Some(context))
|
||||
.await?;
|
||||
|
||||
Ok(Json(response))
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### POST /api/v1/agent/search/more
|
||||
|
||||
```rust
|
||||
pub async fn agent_search_more(
|
||||
Extension(agent_search_service): Extension<Arc<AgentSearchService>>,
|
||||
Extension(auth): Extension<UserAuth>,
|
||||
Json(request): Json<MoreRequest>,
|
||||
) -> Result<Json<AgentSearchResponse>, APIError> {
|
||||
// 验证会话
|
||||
let session = agent_search_service
|
||||
.get_session(&request.session_id)
|
||||
.await?
|
||||
.ok_or_else(|| APIError::NotFound("Session not found".to_string()))?;
|
||||
|
||||
// 验证用户
|
||||
if session.user_id != auth.user_id {
|
||||
return Err(APIError::Forbidden("Access denied".to_string()));
|
||||
}
|
||||
|
||||
// 获取更多结果
|
||||
let response = agent_search_service
|
||||
.more(&request.session_id, request.current_offset, request.limit)
|
||||
.await?;
|
||||
|
||||
Ok(Json(response))
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 💾 Session 管理
|
||||
|
||||
### 会话存储
|
||||
|
||||
```rust
|
||||
/// 搜索会话
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct SearchSession {
|
||||
pub session_id: String,
|
||||
pub user_id: String,
|
||||
pub query: String,
|
||||
pub intent: QueryIntent,
|
||||
pub total_count: i64,
|
||||
pub created_at: DateTime<Utc>,
|
||||
pub expires_at: DateTime<Utc>,
|
||||
}
|
||||
|
||||
impl AgentSearchService {
|
||||
/// 创建会话
|
||||
async fn create_session(
|
||||
&self,
|
||||
user_id: &str,
|
||||
query: &str,
|
||||
intent: QueryIntent,
|
||||
total_count: i64,
|
||||
) -> CommandResult<String> {
|
||||
let session_id = uuid::Uuid::new_v4().to_string();
|
||||
let now = Utc::now();
|
||||
|
||||
let session = SearchSession {
|
||||
session_id: session_id.clone(),
|
||||
user_id: user_id.to_string(),
|
||||
query: query.to_string(),
|
||||
intent,
|
||||
total_count,
|
||||
created_at: now,
|
||||
expires_at: now + chrono::Duration::hours(1), // 1小时过期
|
||||
};
|
||||
|
||||
// 存储到 Redis
|
||||
let key = format!("search_session:{}", session_id);
|
||||
let value = serde_json::to_string(&session)?;
|
||||
|
||||
sqlx::query!(
|
||||
r#"
|
||||
INSERT INTO search_sessions (
|
||||
session_id, user_id, query, intent,
|
||||
total_count, created_at, expires_at
|
||||
)
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7)
|
||||
"#,
|
||||
session.session_id,
|
||||
session.user_id,
|
||||
session.query,
|
||||
serde_json::to_value(&session.intent)?,
|
||||
session.total_count,
|
||||
session.created_at,
|
||||
session.expires_at,
|
||||
)
|
||||
.execute(&self.db)
|
||||
.await?;
|
||||
|
||||
Ok(session_id)
|
||||
}
|
||||
|
||||
/// 获取会话
|
||||
pub async fn get_session(&self, session_id: &str) -> CommandResult<Option<SearchSession>> {
|
||||
let session = sqlx::query_as!(
|
||||
SearchSession,
|
||||
r#"
|
||||
SELECT session_id, user_id, query, intent as "intent: QueryIntent",
|
||||
total_count, created_at, expires_at
|
||||
FROM search_sessions
|
||||
WHERE session_id = $1 AND expires_at > NOW()
|
||||
"#,
|
||||
session_id,
|
||||
)
|
||||
.fetch_optional(&self.db)
|
||||
.await?;
|
||||
|
||||
Ok(session)
|
||||
}
|
||||
|
||||
/// More 操作
|
||||
pub async fn more(
|
||||
&self,
|
||||
session_id: &str,
|
||||
offset: i32,
|
||||
limit: i32,
|
||||
) -> CommandResult<AgentSearchResponse> {
|
||||
let session = self.get_session(session_id)
|
||||
.await?
|
||||
.ok_or_else(|| CommandError::NotFound("Session not found or expired".to_string()))?;
|
||||
|
||||
// 使用会话中的查询和意图
|
||||
let results = self.execute_search_with_offset(
|
||||
&session.query,
|
||||
&session.intent,
|
||||
offset,
|
||||
limit,
|
||||
).await?;
|
||||
|
||||
let has_more = (offset + limit) < session.total_count as i32;
|
||||
|
||||
Ok(AgentSearchResponse {
|
||||
query: session.query,
|
||||
session_id: session_id.to_string(),
|
||||
intent: session.intent,
|
||||
results,
|
||||
total_count: session.total_count,
|
||||
offset,
|
||||
returned_count: limit,
|
||||
has_more,
|
||||
next_offset: if has_more { Some(offset + limit) } else { None },
|
||||
summary: String::new(), // More 操作不生成摘要
|
||||
took_ms: 0,
|
||||
})
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 📊 数据库表
|
||||
|
||||
```sql
|
||||
-- 搜索会话表
|
||||
CREATE TABLE IF NOT EXISTS search_sessions (
|
||||
id SERIAL PRIMARY KEY,
|
||||
session_id VARCHAR(36) NOT NULL UNIQUE,
|
||||
user_id VARCHAR(36) NOT NULL,
|
||||
query TEXT NOT NULL,
|
||||
intent JSONB NOT NULL,
|
||||
total_count BIGINT NOT NULL,
|
||||
created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
|
||||
expires_at TIMESTAMP WITH TIME ZONE NOT NULL,
|
||||
|
||||
-- 索引
|
||||
INDEX idx_session_id (session_id),
|
||||
INDEX idx_user_id (user_id, created_at),
|
||||
INDEX idx_expires (expires_at)
|
||||
);
|
||||
|
||||
-- 定期清理过期会话
|
||||
CREATE OR REPLACE PROCEDURE cleanup_expired_search_sessions()
|
||||
LANGUAGE plpgsql
|
||||
AS $$
|
||||
BEGIN
|
||||
DELETE FROM search_sessions WHERE expires_at < NOW();
|
||||
RAISE NOTICE 'Cleaned up expired search sessions';
|
||||
END;
|
||||
$$;
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 🎯 实现要点
|
||||
|
||||
### 1. 分页逻辑
|
||||
|
||||
```rust
|
||||
impl AgentSearchService {
|
||||
pub async fn search(
|
||||
&self,
|
||||
query: &str,
|
||||
offset: i32,
|
||||
limit: i32,
|
||||
context: Option<SearchContext>,
|
||||
) -> CommandResult<AgentSearchResponse> {
|
||||
// 1. 分析查询意图
|
||||
let intent = self.query_analyzer.analyze(query, context.clone()).await?;
|
||||
|
||||
// 2. 执行搜索(获取总数)
|
||||
let (results, total_count) = self.execute_search(
|
||||
query,
|
||||
&intent,
|
||||
offset,
|
||||
limit,
|
||||
).await?;
|
||||
|
||||
// 3. 创建会话
|
||||
let user_id = context.as_ref().and_then(|c| c.user_id.clone()).unwrap_or_default();
|
||||
let session_id = self.create_session(&user_id, query, intent.clone(), total_count).await?;
|
||||
|
||||
// 4. 生成摘要(仅首次)
|
||||
let summary = if offset == 0 {
|
||||
self.generate_summary(query, &results).await?
|
||||
} else {
|
||||
String::new()
|
||||
};
|
||||
|
||||
// 5. 构建响应
|
||||
let has_more = (offset + limit) < total_count as i32;
|
||||
|
||||
Ok(AgentSearchResponse {
|
||||
query: query.to_string(),
|
||||
session_id,
|
||||
intent,
|
||||
results,
|
||||
total_count,
|
||||
offset,
|
||||
returned_count: results.len() as i32,
|
||||
has_more,
|
||||
next_offset: if has_more { Some(offset + limit) } else { None },
|
||||
summary,
|
||||
took_ms: 0,
|
||||
})
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 2. UI 交互
|
||||
|
||||
```javascript
|
||||
// 初始搜索
|
||||
async function search(query) {
|
||||
const response = await fetch('/api/v1/agent/search', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({
|
||||
query: query,
|
||||
offset: 0,
|
||||
limit: 5
|
||||
})
|
||||
});
|
||||
|
||||
const data = await response.json();
|
||||
|
||||
// 显示结果
|
||||
displayResults(data.results);
|
||||
|
||||
// 显示摘要
|
||||
displaySummary(data.summary);
|
||||
|
||||
// 显示 More 按钮
|
||||
if (data.has_more) {
|
||||
showMoreButton(data.session_id, data.next_offset, data.total_count - data.returned_count);
|
||||
}
|
||||
}
|
||||
|
||||
// More 操作
|
||||
async function loadMore(sessionId, nextOffset) {
|
||||
const moreButton = document.querySelector('.more-button');
|
||||
moreButton.classList.add('loading');
|
||||
moreButton.disabled = true;
|
||||
|
||||
const response = await fetch('/api/v1/agent/search/more', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({
|
||||
session_id: sessionId,
|
||||
current_offset: nextOffset,
|
||||
limit: 10
|
||||
})
|
||||
});
|
||||
|
||||
const data = await response.json();
|
||||
|
||||
// 追加结果
|
||||
appendResults(data.results);
|
||||
|
||||
// 更新 More 按钮
|
||||
if (data.has_more) {
|
||||
updateMoreButton(data.session_id, data.next_offset, data.total_count - (data.offset + data.returned_count));
|
||||
} else {
|
||||
hideMoreButton();
|
||||
}
|
||||
|
||||
moreButton.classList.remove('loading');
|
||||
moreButton.disabled = false;
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 📈 性能优化
|
||||
|
||||
### 1. 会话缓存
|
||||
|
||||
```rust
|
||||
// 使用 Redis 缓存会话
|
||||
impl AgentSearchService {
|
||||
async fn cache_session(&self, session: &SearchSession) -> CommandResult<()> {
|
||||
let key = format!("search_session:{}", session.session_id);
|
||||
let value = serde_json::to_string(session)?;
|
||||
|
||||
// 存储到 Redis,设置 1 小时过期
|
||||
self.redis.set_ex(&key, &value, 3600).await?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn get_cached_session(&self, session_id: &str) -> CommandResult<Option<SearchSession>> {
|
||||
let key = format!("search_session:{}", session_id);
|
||||
|
||||
if let Some(value) = self.redis.get(&key).await? {
|
||||
let session: SearchSession = serde_json::from_str(&value)?;
|
||||
return Ok(Some(session));
|
||||
}
|
||||
|
||||
Ok(None)
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 2. 结果缓存
|
||||
|
||||
```rust
|
||||
// 缓存搜索结果(避免重复计算)
|
||||
impl AgentSearchService {
|
||||
async fn cache_results(
|
||||
&self,
|
||||
session_id: &str,
|
||||
offset: i32,
|
||||
limit: i32,
|
||||
results: &[SearchResult],
|
||||
) -> CommandResult<()> {
|
||||
let key = format!("search_results:{}:{}:{}", session_id, offset, offset + limit);
|
||||
let value = serde_json::to_string(results)?;
|
||||
|
||||
// 缓存 30 分钟
|
||||
self.redis.set_ex(&key, &value, 1800).await?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## ✅ 设计总结
|
||||
|
||||
**默认返回**: Top 5 结果
|
||||
**More 操作**: 每次增加 10 个
|
||||
**会话管理**: 1 小时过期
|
||||
**UI 显示**: More 按钮 + 剩余数量
|
||||
**性能优化**: Redis 缓存会话和结果
|
||||
|
||||
**分页设计完成!用户可逐步浏览所有结果,避免信息过载。**
|
||||
@@ -0,0 +1,148 @@
|
||||
---
|
||||
title: Always-Produce Processing Contract
|
||||
version: 1.0
|
||||
date: 2026-07-24
|
||||
author: OpenCode
|
||||
status: approved
|
||||
---
|
||||
|
||||
# Always-Produce Processing Contract
|
||||
|
||||
## Scope
|
||||
|
||||
| Field | Value |
|
||||
|-------|-------|
|
||||
| Scope | All frame-based processors (face, pose, appearance, face_cluster, face_trace, etc.) |
|
||||
| Status | Approved |
|
||||
| Applies to | Python processors + Rust Worker |
|
||||
| Related docs | `DESIGN/Processor_Module_V1.0.md`, `DESIGN/Redis_Progress_Reporting_V1.0.md`, `DESIGN/Worker_Health_Check_Mechanism.md` |
|
||||
|
||||
## 1. Frame-Scan Model
|
||||
|
||||
Video processing is fundamentally frame-based: a processor scans from frame 0 to the last frame.
|
||||
|
||||
```
|
||||
Scan start → frame 0 → frame 1 → ... → frame N → scan complete
|
||||
↓ ↓ ↓ ↓
|
||||
Redis Redis Redis {uuid}.{p}.json
|
||||
progress progress progress (final record)
|
||||
```
|
||||
|
||||
### Key Rules
|
||||
|
||||
1. **Progress** = which frame has been scanned so far (`current_frame / total_frames`)
|
||||
2. **Complete** = scanned to the last frame (proved by `.json` existing)
|
||||
3. **Result** = always written, even if 0 detections found
|
||||
|
||||
## 2. Always-Produce Rule
|
||||
|
||||
### Principle
|
||||
|
||||
> Every processor MUST write its `{uuid}.{processor}.json` output file after completing its scan, **regardless of whether any results were found**.
|
||||
|
||||
### Rationale
|
||||
|
||||
The `.json` file serves dual purpose:
|
||||
- **Proof of completion**: Worker uses `output_path.exists()` (line 580 of `job_worker.rs`) to skip already-finished processors
|
||||
- **Downstream dependency**: Subsequent processors check this file for input
|
||||
|
||||
Without the Always-Produce rule:
|
||||
- Zero-result processors leave no `.json` → Worker retries infinitely → deadlock
|
||||
- Stuck jobs block downstream stages (Rule 1/2/3 ingestion, TKG build)
|
||||
|
||||
### Format
|
||||
|
||||
All processor JSON outputs MUST include:
|
||||
|
||||
```json
|
||||
{
|
||||
"status": "has_faces" | "no_faces" | "no_face_json" | "no_embeddings" | "success" | "error_*",
|
||||
"file_uuid": "<uuid>",
|
||||
...processor-specific fields (empty arrays when zero results)
|
||||
}
|
||||
```
|
||||
|
||||
Example — face cluster with no faces:
|
||||
|
||||
```json
|
||||
{
|
||||
"status": "no_faces",
|
||||
"file_uuid": "9781de6d...",
|
||||
"clusters": [],
|
||||
"frames": []
|
||||
}
|
||||
```
|
||||
|
||||
### Processor Checklist
|
||||
|
||||
| Processor | Always-Produce? | Status field on 0 result |
|
||||
|-----------|----------------|--------------------------|
|
||||
| `face.py` | ✅ Yes | `"no_faces"` |
|
||||
| `store_traced_faces.py` | ✅ Yes (already writes) | `"no_faces"` |
|
||||
| `fast_face_clustering_processor.py` | ❌ **FIX NEEDED** | Early returns, no file written |
|
||||
| `pose_processor*.py` | ✅ Yes | `"no_faces"` |
|
||||
| `appearance_processor*.py` | ✅ Yes | `"no_faces"` |
|
||||
|
||||
## 3. Redis Progress During Scan
|
||||
|
||||
### Purpose
|
||||
|
||||
Live frame progress is published to Redis so the QC modal can display real-time status ("scanning frame 1234/5678").
|
||||
|
||||
### Mechanism
|
||||
|
||||
Use `redis_publisher.py` (`RedisPublisher` class) which publishes to Redis channel `{prefix}progress:{uuid}`:
|
||||
|
||||
```python
|
||||
from redis_publisher import RedisPublisher
|
||||
|
||||
pub = RedisPublisher(file_uuid)
|
||||
|
||||
# During scan, per batch:
|
||||
pub.progress("face_cluster", current_frame, total_frames, f"Scanning frame {current_frame}")
|
||||
|
||||
# On completion:
|
||||
pub.complete("face_cluster", f"Done: {cluster_count} clusters")
|
||||
```
|
||||
|
||||
### Frequency
|
||||
|
||||
- **Frame-based processors**: publish every N frames (batch/buffer flush)
|
||||
- **Non-frame processors** (e.g., clustering): publish at meaningful milestones
|
||||
|
||||
## 4. Worker Heartbeat
|
||||
|
||||
### Problem
|
||||
|
||||
`health.rs` currently uses `check_process_running("worker")` which relies on `ps aux | grep momentry.*worker`. This is unreliable:
|
||||
- Zombie processes show as "running"
|
||||
- Stale matches from unrelated processes
|
||||
|
||||
### Fix
|
||||
|
||||
Worker writes a Redis HMSET `{prefix}health` with EXPIRE = `3 × poll_interval_secs` (default: 15s) in every `poll_and_process()` cycle.
|
||||
|
||||
Health endpoint checks:
|
||||
1. Redis key `{prefix}health` exists
|
||||
2. Key has remaining TTL > 0
|
||||
3. Key's `status` field is `"healthy"` or `"throttled"`
|
||||
|
||||
If Redis key missing or expired → `worker_alive: false`.
|
||||
|
||||
## 5. Implementation Plan
|
||||
|
||||
| Step | File | Change |
|
||||
|------|------|--------|
|
||||
| 1 | `fast_face_clustering_processor.py` | Always-Produce for 3 early returns + Redis progress |
|
||||
| 2 | `store_traced_faces.py` | Add Redis progress (optional) |
|
||||
| 3 | `job_worker.rs` | Add EXPIRE after health HMSET |
|
||||
| 4 | `health.rs` | Replace `check_process_running("worker")` with Redis TTL check |
|
||||
| 5 | `processing.rs` | (Optional) Reject trigger if Worker not alive |
|
||||
|
||||
---
|
||||
|
||||
## Version History
|
||||
|
||||
| Version | Date | Author | Changes |
|
||||
|---------|------|--------|---------|
|
||||
| 1.0 | 2026-07-24 | OpenCode | Initial specification |
|
||||
@@ -0,0 +1,766 @@
|
||||
---
|
||||
title: Appearance Feature System V1.0
|
||||
version: 1.0.0
|
||||
date: 2025-06-22
|
||||
author: OpenCode
|
||||
status: Draft
|
||||
---
|
||||
|
||||
# Appearance Feature System V1.0
|
||||
|
||||
## Overview
|
||||
|
||||
### Purpose
|
||||
Lock onto a target and continuously track across frames using appearance features.
|
||||
|
||||
### Architecture
|
||||
```
|
||||
Face (identification) → Pose (tracking) → Appearance (tracking)
|
||||
↓ ↓ ↓
|
||||
identity_uuid bbox features + proportions
|
||||
```
|
||||
|
||||
### Data Sources
|
||||
| Source | Provides | Output |
|
||||
|--------|----------|--------|
|
||||
| Face | identity, landmarks | face.json |
|
||||
| Pose | bbox, keypoints | pose.json |
|
||||
| MediaPipe | detailed landmarks, hands | mediapipe.json |
|
||||
|
||||
---
|
||||
|
||||
## Keypoint Systems
|
||||
|
||||
### Swift Pose (Apple Vision) - 19 Keypoints
|
||||
|
||||
| Index | Keypoint | Vision Framework Joint |
|
||||
|-------|----------|------------------------|
|
||||
| 0 | nose | .nose (head_joint) |
|
||||
| 1 | left_eye | .leftEye (left_eye_joint) |
|
||||
| 2 | right_eye | .rightEye (right_eye_joint) |
|
||||
| 3 | left_ear | .leftEar (left_ear_joint) |
|
||||
| 4 | right_ear | .rightEar (right_ear_joint) |
|
||||
| 5 | neck | .neck (neck_1_joint) |
|
||||
| 6 | root | .root (center_hip_joint) |
|
||||
| 7 | left_shoulder | .leftShoulder |
|
||||
| 8 | right_shoulder | .rightShoulder |
|
||||
| 9 | left_elbow | .leftElbow |
|
||||
| 10 | right_elbow | .rightElbow |
|
||||
| 11 | left_wrist | .leftWrist (left_hand_joint) |
|
||||
| 12 | right_wrist | .rightWrist (right_hand_joint) |
|
||||
| 13 | left_hip | .leftHip |
|
||||
| 14 | right_hip | .rightHip |
|
||||
| 15 | left_knee | .leftKnee |
|
||||
| 16 | right_knee | .rightKnee |
|
||||
| 17 | left_ankle | .leftAnkle |
|
||||
| 18 | right_ankle | .rightAnkle |
|
||||
|
||||
### MediaPipe Pose - 33 Landmarks
|
||||
|
||||
| Index | Name | Index | Name |
|
||||
|-------|------|-------|------|
|
||||
| 0 | nose | 17 | left_pinky |
|
||||
| 1 | left_eye_inner | 18 | right_pinky |
|
||||
| 2 | left_eye | 19 | left_index |
|
||||
| 3 | left_eye_outer | 20 | right_index |
|
||||
| 4 | right_eye_inner | 21 | left_thumb |
|
||||
| 5 | right_eye | 22 | right_thumb |
|
||||
| 6 | right_eye_outer | 23 | left_hip |
|
||||
| 7 | left_ear | 24 | right_hip |
|
||||
| 8 | right_ear | 25 | left_knee |
|
||||
| 9 | mouth_left | 26 | right_knee |
|
||||
| 10 | mouth_right | 27 | left_ankle |
|
||||
| 11 | left_shoulder | 28 | right_ankle |
|
||||
| 12 | right_shoulder | 29 | left_heel |
|
||||
| 13 | left_elbow | 30 | right_heel |
|
||||
| 14 | right_elbow | 31 | left_foot_index |
|
||||
| 15 | left_wrist | 32 | right_foot_index |
|
||||
| 16 | right_wrist | | |
|
||||
|
||||
### MediaPipe Hand - 21 Landmarks
|
||||
|
||||
| Index | Name | Finger |
|
||||
|-------|------|--------|
|
||||
| 0 | wrist | - |
|
||||
| 1-4 | thumb_cmc/mcp/ip/tip | thumb |
|
||||
| 5-8 | index_mcp/pip/dip/tip | index |
|
||||
| 9-12 | middle_mcp/pip/dip/tip | middle |
|
||||
| 13-16 | ring_mcp/pip/dip/tip | ring |
|
||||
| 17-20 | pinky_mcp/pip/dip/tip | pinky |
|
||||
|
||||
### YOLOv8 Pose (Fallback) - 17 Keypoints
|
||||
|
||||
| Index | Name |
|
||||
|-------|------|
|
||||
| 0 | nose |
|
||||
| 1 | left_eye |
|
||||
| 2 | right_eye |
|
||||
| 3 | left_ear |
|
||||
| 4 | right_ear |
|
||||
| 5 | left_shoulder |
|
||||
| 6 | right_shoulder |
|
||||
| 7 | left_elbow |
|
||||
| 8 | right_elbow |
|
||||
| 9 | left_wrist |
|
||||
| 10 | right_wrist |
|
||||
| 11 | left_hip |
|
||||
| 12 | right_hip |
|
||||
| 13 | left_knee |
|
||||
| 14 | right_knee |
|
||||
| 15 | left_ankle |
|
||||
| 16 | right_ankle |
|
||||
|
||||
---
|
||||
|
||||
## Body Proportions Calculation
|
||||
|
||||
### Reference Units
|
||||
|
||||
Multiple reference units for different shot types:
|
||||
|
||||
| Unit | Real Size | Available In | Notes |
|
||||
|------|-----------|--------------|-------|
|
||||
| eye_width | ~6cm | Close-up | Most accurate in close-up |
|
||||
| head_width | ~16cm | Close-up to Medium | Ear-to-ear distance |
|
||||
| shoulder_width | ~45cm | Medium to Wide | Most stable reference |
|
||||
|
||||
```python
|
||||
# Priority: shoulder_width > head_width > eye_width
|
||||
# Larger units more stable and available in wider shots
|
||||
```
|
||||
|
||||
### Body Proportions Constants
|
||||
|
||||
Standard adult body proportion ratios (used for validation and estimation):
|
||||
|
||||
| Ratio | Value | Description |
|
||||
|-------|-------|-------------|
|
||||
| head_to_eye | 2.67 | head_width ≈ 2.67 × eye_width |
|
||||
| eye_to_shoulder | 7.5 | shoulder_width ≈ 7.5 × eye_width |
|
||||
| head_to_shoulder | 2.8 | shoulder_width ≈ 2.8 × head_width |
|
||||
| head_to_height | 7.5 | body_height ≈ 7.5 × head_width |
|
||||
| shoulder_to_height | 3.8 | body_height ≈ 3.8 × shoulder_width |
|
||||
|
||||
### Shot Type Detection
|
||||
|
||||
Detect shot type based on head position relative to bbox:
|
||||
|
||||
| Shot Type | Head Position | Aspect Ratio | Description |
|
||||
|-----------|---------------|--------------|-------------|
|
||||
| full_body | < 15% from top | > 2.0 | Full person visible |
|
||||
| medium_shot | < 30% from top | > 1.5 | Upper body visible |
|
||||
| close_up | > 30% or middle | < 1.5 | Head/face dominant |
|
||||
|
||||
```python
|
||||
# head_position_ratio = (head_y - bbox_top) / bbox_height
|
||||
# aspect_ratio = bbox_height / bbox_width
|
||||
|
||||
if head_position_ratio < 0.15 and aspect_ratio > 2.0:
|
||||
shot_type = "full_body"
|
||||
elif head_position_ratio < 0.30 and aspect_ratio > 1.5:
|
||||
shot_type = "medium_shot"
|
||||
else:
|
||||
shot_type = "close_up"
|
||||
```
|
||||
|
||||
**Usage**: Filter frames by shot type (e.g., find all full-body shots in video).
|
||||
|
||||
### Height Estimation
|
||||
|
||||
Height estimation strategy based on shot type:
|
||||
|
||||
| Shot Type | Method | Formula | Result |
|
||||
|-----------|--------|---------|--------|
|
||||
| full_body | Direct measurement | body_height / ref_unit × ref_cm | Accurate |
|
||||
| medium_shot | Torso extrapolate | torso × (1/0.45) | ~170cm |
|
||||
| close_up | Proportion estimate | shoulder × 3.8 | ~171cm |
|
||||
|
||||
```python
|
||||
# Close-up: use shoulder_width × 3.8
|
||||
estimated_height_cm = 45.0 * 3.8 # ≈ 171cm
|
||||
|
||||
# Or use head_width × 7.5
|
||||
estimated_height_cm = 16.0 * 7.5 # ≈ 120cm (lower confidence)
|
||||
```
|
||||
|
||||
### Body Measurements
|
||||
```python
|
||||
# Full body height (nose to ankle)
|
||||
nose_y = keypoints['nose']['y']
|
||||
ankle_y = max(keypoints['left_ankle']['y'], keypoints['right_ankle']['y'])
|
||||
body_height = ankle_y - nose_y
|
||||
|
||||
# Upper body (neck to hip)
|
||||
neck_y = keypoints['neck']['y']
|
||||
hip_y = (keypoints['left_hip']['y'] + keypoints['right_hip']['y']) / 2
|
||||
torso_height = hip_y - neck_y
|
||||
|
||||
# Lower body (hip to ankle)
|
||||
leg_height = ankle_y - hip_y
|
||||
|
||||
# Shoulder width
|
||||
shoulder_width = distance(left_shoulder, right_shoulder)
|
||||
|
||||
# Head width (ear to ear)
|
||||
head_width = distance(left_ear, right_ear)
|
||||
```
|
||||
|
||||
### Proportion Ratios
|
||||
```python
|
||||
proportions = {
|
||||
'shot_type': detect_shot_type(keypoints, bbox),
|
||||
'eye_width': eye_width,
|
||||
'head_width': head_width,
|
||||
'body_height': body_height,
|
||||
'torso_height': torso_height,
|
||||
'leg_height': leg_height,
|
||||
'shoulder_width': shoulder_width,
|
||||
'head_ratio': eye_width / body_height if body_height > 0 else 0,
|
||||
'torso_ratio': torso_height / body_height if body_height > 0 else 0,
|
||||
'leg_ratio': leg_height / body_height if body_height > 0 else 0,
|
||||
}
|
||||
|
||||
# Validation ratios (should match BODY_PROPORTIONS constants)
|
||||
proportion_ratios = {
|
||||
'head_to_eye': head_width / eye_width if eye_width > 0 else 0, # ~2.67
|
||||
'shoulder_to_head': shoulder_width / head_width if head_width > 0 else 0, # ~2.8
|
||||
'shoulder_to_eye': shoulder_width / eye_width if eye_width > 0 else 0, # ~7.5
|
||||
}
|
||||
```
|
||||
|
||||
### Body Shape Classification
|
||||
|
||||
Classification based on chest/waist/hip ratios:
|
||||
|
||||
| Shape | Criteria | Description |
|
||||
|-------|----------|-------------|
|
||||
| hourglass | chest_waist < 1.0, waist_hip < 0.9 | Balanced proportions |
|
||||
| triangle | chest_waist > 1.2 | Upper body dominant |
|
||||
| inverted_triangle | waist_hip > 1.1 | Lower body dominant |
|
||||
| rectangle | chest ≈ hip | Uniform width |
|
||||
| oval | Other | General classification |
|
||||
|
||||
```python
|
||||
# Measurements
|
||||
chest_width = distance(left_shoulder, right_shoulder)
|
||||
waist_width = distance(left_hip, right_hip)
|
||||
hip_width = distance(left_hip, right_hip)
|
||||
|
||||
# Ratios
|
||||
chest_waist_ratio = chest_width / waist_width
|
||||
waist_hip_ratio = waist_width / hip_width
|
||||
```
|
||||
else:
|
||||
height_category = "very_tall"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Usage
|
||||
|
||||
### CLI Commands
|
||||
|
||||
#### TKG Level 1 Builder
|
||||
|
||||
Build person_trace nodes with Level 1 features:
|
||||
|
||||
```bash
|
||||
# Basic usage (auto-detect video and pose.json paths)
|
||||
python scripts/tkg_level1_builder.py --file-uuid <uuid> --schema dev
|
||||
|
||||
# With explicit paths
|
||||
python scripts/tkg_level1_builder.py \
|
||||
--file-uuid <uuid> \
|
||||
--schema dev \
|
||||
--video /path/to/video.mp4 \
|
||||
--pose-json /path/to/pose.json
|
||||
```
|
||||
|
||||
Output: Creates `person_trace` nodes in `tkg_nodes` table with:
|
||||
- frame_count
|
||||
- height_estimate (from shoulder_width or head_width)
|
||||
- level1_features (body, head_top, upper_body, lower_body colors)
|
||||
|
||||
#### Query TKG Nodes
|
||||
|
||||
```python
|
||||
import psycopg2
|
||||
|
||||
conn = psycopg2.connect('postgresql://accusys@localhost:5432/momentry')
|
||||
cur = conn.cursor()
|
||||
|
||||
cur.execute("SELECT external_id, properties FROM dev.tkg_nodes WHERE node_type='person_trace'")
|
||||
|
||||
for row in cur.fetchall():
|
||||
external_id, props = row
|
||||
print(f'{external_id}: height={props["height_estimate"]["estimated_height_cm"]}cm')
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Appearance Feature Location Mapping
|
||||
|
||||
### Environment Factors
|
||||
|
||||
| Feature | Location | Detection Method |
|
||||
|---------|----------|------------------|
|
||||
| Light type | Frame background | HSV H distribution |
|
||||
| Light direction | Shadow analysis | Shadow orientation |
|
||||
| Light intensity | Overall brightness | HSV V mean |
|
||||
|
||||
### Head Features
|
||||
|
||||
#### Hair Style
|
||||
| Feature | Keypoints Range |
|
||||
|---------|-----------------|
|
||||
| Short hair | head_top → ear/neck |
|
||||
| Long hair | head_top → shoulder/back |
|
||||
| Ponytail | head_top → neck (tied) |
|
||||
| Braids | head_top → shoulder (braided) |
|
||||
| Curly hair | hair region texture |
|
||||
| Straight hair | hair region texture |
|
||||
|
||||
#### Hair Accessories
|
||||
| Feature | Keypoints |
|
||||
|---------|-----------|
|
||||
| Hair band | eye_distance (head top) |
|
||||
| Hair clip | ear/head |
|
||||
| Hair wrap | ear_distance |
|
||||
| Hair tie | neck (ponytail position) |
|
||||
| Hair pin | head |
|
||||
|
||||
#### Head Accessories
|
||||
| Feature | Keypoints |
|
||||
|---------|-----------|
|
||||
| Hat | head_top → eye |
|
||||
| Headscarf | ear_distance (wrapped) |
|
||||
| Hood | head_top → neck (full head) |
|
||||
|
||||
#### Hair Color
|
||||
| Feature | Detection |
|
||||
|---------|-----------|
|
||||
| Hair color HSV | hair region HSV histogram |
|
||||
|
||||
### Face Features
|
||||
|
||||
#### Eye Accessories
|
||||
| Feature | Keypoints |
|
||||
|---------|-----------|
|
||||
| Glasses | eye_distance |
|
||||
| Sunglasses | eye_distance (larger) |
|
||||
|
||||
#### Ear Accessories
|
||||
| Feature | Keypoints |
|
||||
|---------|-----------|
|
||||
| Earrings | ear_position |
|
||||
| Headphones (over-ear) | ear_distance (wrapped) |
|
||||
| Earphones (in-ear) | ear_position |
|
||||
| Earphones (ear-hook) | ear_position |
|
||||
|
||||
#### Face Accessories
|
||||
| Feature | Keypoints |
|
||||
|---------|-----------|
|
||||
| Blush | cheeks (below eye) |
|
||||
| Lipstick | lips (nose + eye_width * 0.5) |
|
||||
| Mask | ear_distance, eye → neck |
|
||||
|
||||
#### Skin Tone
|
||||
| Feature | Detection |
|
||||
|---------|-----------|
|
||||
| Skin color HSV | face region HSV histogram |
|
||||
|
||||
### Neck Features
|
||||
|
||||
#### Neck Accessories
|
||||
| Feature | Keypoints |
|
||||
|---------|-----------|
|
||||
| Collar | neck |
|
||||
| Bow tie | neck → chest |
|
||||
| Tie | neck → hip |
|
||||
| Scarf | neck → shoulder |
|
||||
| Necklace | neck |
|
||||
|
||||
#### Hanging Accessories
|
||||
| Feature | Keypoints |
|
||||
|---------|-----------|
|
||||
| Pendant (necklace) | neck → chest |
|
||||
| Charm (bag) | bag_position |
|
||||
| Charm (phone) | phone_position |
|
||||
|
||||
### Upper Body Features
|
||||
|
||||
#### Clothing
|
||||
| Feature | Keypoints |
|
||||
|---------|-----------|
|
||||
| Shirt color | neck → hip |
|
||||
| Shirt material | clothing texture (LBP) |
|
||||
| Clothing pattern | pattern detection |
|
||||
|
||||
#### Sleeves
|
||||
| Feature | Keypoints |
|
||||
|---------|-----------|
|
||||
| Long sleeve | shoulder → wrist |
|
||||
| Short sleeve | shoulder → elbow |
|
||||
| Arm sleeve | elbow → wrist |
|
||||
|
||||
#### Back Features
|
||||
| Feature | Keypoints |
|
||||
|---------|-----------|
|
||||
| Back exposed | shoulder → hip (view angle) |
|
||||
| Back tattoo | back exposed skin |
|
||||
|
||||
### Bags
|
||||
|
||||
| Feature | Keypoints |
|
||||
|---------|-----------|
|
||||
| Handbag | hand_position |
|
||||
| Shoulder bag | shoulder_position |
|
||||
| Backpack | shoulder → hip (back) |
|
||||
| Waist bag | hip_position |
|
||||
|
||||
### Hand Features
|
||||
|
||||
#### Hand Accessories
|
||||
| Feature | Keypoints |
|
||||
|---------|-----------|
|
||||
| Watch | wrist |
|
||||
| Bracelet | wrist → hand |
|
||||
| Ring | finger (MediaPipe hand landmarks 13-16) |
|
||||
| Gloves | wrist → hand |
|
||||
| Nail polish | finger tips |
|
||||
|
||||
#### Handheld Objects
|
||||
| Feature | Keypoints |
|
||||
|---------|-----------|
|
||||
| Phone | hand + object detection |
|
||||
| Handbag | hand + object detection |
|
||||
|
||||
### Lower Body Features
|
||||
|
||||
#### Pants
|
||||
| Feature | Keypoints |
|
||||
|---------|-----------|
|
||||
| Long pants | hip → ankle |
|
||||
| Shorts | hip → knee |
|
||||
|
||||
#### Waist Accessories
|
||||
| Feature | Keypoints |
|
||||
|---------|-----------|
|
||||
| Belt | hip |
|
||||
|
||||
### Foot Features
|
||||
|
||||
#### Foot Accessories
|
||||
| Feature | Keypoints |
|
||||
|---------|-----------|
|
||||
| Anklet | ankle |
|
||||
| Socks | ankle → foot |
|
||||
| Shoes | ankle |
|
||||
|
||||
### Skin Features
|
||||
|
||||
| Feature | Detection |
|
||||
|---------|-----------|
|
||||
| Tattoo | exposed skin anomaly color block |
|
||||
|
||||
### Exposed Skin Detection
|
||||
|
||||
| Location | Coverage Detection |
|
||||
|----------|-------------------|
|
||||
| Face | always exposed |
|
||||
| Arms | exposed if short sleeve |
|
||||
| Legs | exposed if shorts |
|
||||
| Hands | exposed if no gloves |
|
||||
| Feet | exposed if no socks |
|
||||
|
||||
---
|
||||
|
||||
## Mobility Aids / Vehicles
|
||||
|
||||
### Walking Aids (Object Detection)
|
||||
| Feature | Keypoints |
|
||||
|---------|-----------|
|
||||
| Cane | hand + object |
|
||||
| Wheelchair | hip + object |
|
||||
| Walker | both hands + object |
|
||||
|
||||
### Mobility Tools (Object Detection)
|
||||
| Feature | Keypoints |
|
||||
|---------|-----------|
|
||||
| Roller skates | ankle + object |
|
||||
| Skateboard | ankle + object |
|
||||
| Scooter | hand + ankle + object |
|
||||
|
||||
### Vehicles (Object Detection)
|
||||
| Feature | Keypoints |
|
||||
|---------|-----------|
|
||||
| Motorcycle | hip + ankle + object |
|
||||
| Bicycle | hip + ankle + object |
|
||||
| Tricycle | hip + ankle + object |
|
||||
| Car | hip + object |
|
||||
|
||||
---
|
||||
|
||||
## Feature Extraction Techniques
|
||||
|
||||
### Color Extraction (HSV Histogram)
|
||||
```python
|
||||
def extract_color(roi):
|
||||
hsv = cv2.cvtColor(roi, cv2.COLOR_BGR2HSV)
|
||||
h_hist = cv2.calcHist([hsv], [0], None, [30], [0, 180])
|
||||
s_hist = cv2.calcHist([hsv], [1], None, [32], [0, 256])
|
||||
v_hist = cv2.calcHist([hsv], [2], None, [32], [0, 256])
|
||||
return {
|
||||
'h_histogram': normalize(h_hist),
|
||||
's_histogram': normalize(s_hist),
|
||||
'v_histogram': normalize(v_hist),
|
||||
}
|
||||
```
|
||||
|
||||
### Dominant Color (K-means)
|
||||
```python
|
||||
def extract_dominant_colors(roi, k=5):
|
||||
hsv = cv2.cvtColor(roi, cv2.COLOR_BGR2HSV)
|
||||
pixels = hsv.reshape(-1, 3).astype(np.float32)
|
||||
_, labels, centers = cv2.kmeans(pixels, k, None, criteria, 10, cv2.KMEANS_RANDOM_CENTERS)
|
||||
counts = np.bincount(labels.flatten())
|
||||
return centers[np.argsort(-counts)[:k]]
|
||||
```
|
||||
|
||||
### Texture Extraction (LBP)
|
||||
```python
|
||||
def extract_texture(roi):
|
||||
gray = cv2.cvtColor(roi, cv2.COLOR_BGR2GRAY)
|
||||
lbp = local_binary_pattern(gray, P=8, R=1)
|
||||
return {
|
||||
'lbp_variance': np.var(lbp),
|
||||
'lbp_histogram': np.histogram(lbp, bins=256)[0],
|
||||
}
|
||||
```
|
||||
|
||||
### Shininess Detection
|
||||
```python
|
||||
def detect_shininess(roi):
|
||||
hsv = cv2.cvtColor(roi, cv2.COLOR_BGR2HSV)
|
||||
v_mean = np.mean(hsv[:,:,2])
|
||||
v_std = np.std(hsv[:,:,2])
|
||||
return {
|
||||
'brightness': v_mean,
|
||||
'brightness_variance': v_std,
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Tracking Flow
|
||||
|
||||
### Feature Storage Strategy
|
||||
| Level | Storage | Reason |
|
||||
|-------|---------|--------|
|
||||
| **Level 1** | TKG nodes | Stable features for tracking |
|
||||
| **Level 2** | Dynamic | On-demand calculation |
|
||||
| **Level 3** | Dynamic | On-demand calculation |
|
||||
|
||||
### Level 1 in TKG
|
||||
```sql
|
||||
-- New node_type: person_trace
|
||||
INSERT INTO tkg_nodes (
|
||||
node_type = 'person_trace',
|
||||
external_id = 'person_{frame}_{index}',
|
||||
file_uuid = 'xxx',
|
||||
properties = {
|
||||
'frame_count': 100,
|
||||
'frames': [1, 30, 60, ...],
|
||||
'avg_bbox': {...},
|
||||
'height_estimate': {
|
||||
'estimated_height_cm': 170.5,
|
||||
'height_ratio': 28.4,
|
||||
'height_category': 'tall'
|
||||
},
|
||||
'body_shape': {
|
||||
'chest_width': 150.2,
|
||||
'waist_width': 100.5,
|
||||
'hip_width': 120.3,
|
||||
'chest_waist_ratio': 1.49,
|
||||
'waist_hip_ratio': 0.84,
|
||||
'body_shape': 'hourglass'
|
||||
},
|
||||
'level1_features': {
|
||||
'body': {...},
|
||||
'head_top': {...},
|
||||
'upper_body': {...},
|
||||
'lower_body': {...}
|
||||
}
|
||||
}
|
||||
)
|
||||
```
|
||||
|
||||
### Level 2/3 Dynamic Calculation
|
||||
```python
|
||||
# Level 2: computed on query
|
||||
face_features = extractor.extract_level2(frame, regions)
|
||||
|
||||
# Level 3: computed on query
|
||||
accessory_features = extractor.extract_level3(frame, keypoints, eye_width)
|
||||
```
|
||||
|
||||
### Matching Strategy
|
||||
```
|
||||
Frame N → Frame N+1:
|
||||
|
||||
1. Pose bbox IoU → same person position
|
||||
2. Level 1 similarity (TKG) → same feature combination
|
||||
3. Level 2/3 dynamic → detailed verification
|
||||
4. Face identity → final confirmation (if face detected)
|
||||
|
||||
Result: Continuous tracking of same identity
|
||||
```
|
||||
|
||||
### IoU Calculation
|
||||
```python
|
||||
def calculate_iou(bbox1, bbox2):
|
||||
x1, y1, w1, h1 = bbox1
|
||||
x2, y2, w2, h2 = bbox2
|
||||
|
||||
xi1 = max(x1, x2)
|
||||
yi1 = max(y1, y2)
|
||||
xi2 = min(x1 + w1, x2 + w2)
|
||||
yi2 = min(y1 + h1, y2 + h2)
|
||||
|
||||
inter_area = max(0, xi2 - xi1) * max(0, yi2 - yi1)
|
||||
union_area = w1 * h1 + w2 * h2 - inter_area
|
||||
|
||||
return inter_area / union_area if union_area > 0 else 0
|
||||
```
|
||||
|
||||
### Feature Similarity
|
||||
```python
|
||||
def calculate_similarity(features1, features2):
|
||||
# HSV histogram similarity
|
||||
h_sim = cv2.compareHist(features1['h_histogram'], features2['h_histogram'], cv2.HISTCMP_CORREL)
|
||||
|
||||
# Dominant color similarity
|
||||
color_dist = np.linalg.norm(features1['dominant_colors'] - features2['dominant_colors'])
|
||||
|
||||
# Combined score
|
||||
return {
|
||||
'color_similarity': h_sim,
|
||||
'color_distance': color_dist,
|
||||
'overall_score': h_sim * 0.7 + (1 - color_dist/255) * 0.3,
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Output Format
|
||||
|
||||
### appearance.json Structure
|
||||
```json
|
||||
{
|
||||
"frame_count": 100,
|
||||
"fps": 30.0,
|
||||
"frames": [
|
||||
{
|
||||
"frame": 1,
|
||||
"timestamp": 0.033,
|
||||
"persons": [
|
||||
{
|
||||
"person_index": 0,
|
||||
"bbox": {"x": 100, "y": 200, "width": 400, "height": 600},
|
||||
"identity_uuid": "xxx-xxx-xxx",
|
||||
"proportions": {
|
||||
"eye_width": 50.0,
|
||||
"body_height": 600.0,
|
||||
"torso_height": 200.0,
|
||||
"leg_height": 300.0,
|
||||
"shoulder_width": 150.0,
|
||||
"head_ratio": 0.08,
|
||||
"torso_ratio": 0.33,
|
||||
"leg_ratio": 0.50
|
||||
},
|
||||
"features": {
|
||||
"hair": {
|
||||
"color": {"h_histogram": [...], "dominant_colors": [...]},
|
||||
"length": "long",
|
||||
"style": "straight"
|
||||
},
|
||||
"skin": {
|
||||
"color": {"h_histogram": [...], "dominant_colors": [...]}
|
||||
},
|
||||
"clothing": {
|
||||
"upper": {
|
||||
"color": {...},
|
||||
"material": "cotton",
|
||||
"pattern": "solid",
|
||||
"sleeve": "short"
|
||||
},
|
||||
"lower": {
|
||||
"color": {...},
|
||||
"length": "long"
|
||||
}
|
||||
},
|
||||
"accessories": {
|
||||
"earring": true,
|
||||
"watch": true,
|
||||
"shoes_color": {...}
|
||||
}
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Dependencies
|
||||
|
||||
### Processor Dependencies
|
||||
| Processor | Depends On | Reason |
|
||||
|-----------|------------|--------|
|
||||
| Appearance | Pose | bbox for region extraction |
|
||||
| Appearance | Face | identity matching + face landmarks |
|
||||
| Appearance | MediaPipe | hand landmarks + detailed pose |
|
||||
|
||||
### Data Flow
|
||||
```
|
||||
pose.json → bbox + keypoints
|
||||
face.json → identity + face landmarks
|
||||
mediapipe.json → hand landmarks + pose landmarks
|
||||
↓
|
||||
appearance.json → features + proportions + tracking
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Implementation Phases
|
||||
|
||||
### Phase 1: Design Document
|
||||
- Create this design document
|
||||
- Define all feature mappings
|
||||
- Define output format
|
||||
|
||||
### Phase 2: Appearance Processor Refactor
|
||||
- Add proportion calculation module
|
||||
- Add feature extraction module
|
||||
- Integrate Pose + MediaPipe + Face data
|
||||
- Add IoU matching for pose-face
|
||||
|
||||
### Phase 3: Output Format Update
|
||||
- Update appearance.json structure
|
||||
- Update Rust structs
|
||||
- Update DB schema
|
||||
|
||||
### Phase 4: Testing
|
||||
- Unit tests for proportion calculation
|
||||
- Integration tests for full pipeline
|
||||
- Real video tracking validation
|
||||
|
||||
---
|
||||
|
||||
## Version History
|
||||
|
||||
| Version | Date | Author | Changes |
|
||||
|---------|------|--------|---------|
|
||||
| 1.0.0 | 2025-06-22 | OpenCode | Initial design document |
|
||||
@@ -0,0 +1,498 @@
|
||||
---
|
||||
title: Apple Native Video Analysis Research
|
||||
version: 1.0
|
||||
date: 2026-09-28
|
||||
author: OpenCode
|
||||
status: research
|
||||
---
|
||||
|
||||
## 目標
|
||||
|
||||
研究使用 Apple native video 解析替代 ffmpeg 進行 CUT (場景檢測) 的可行性。
|
||||
|
||||
---
|
||||
|
||||
## 當前實現
|
||||
|
||||
### Rust CUT (使用 ffmpeg)
|
||||
|
||||
```rust
|
||||
// 使用 ffmpeg select filter 檢測場景
|
||||
Command::new("ffmpeg")
|
||||
.args([
|
||||
"-i", video_path,
|
||||
"-vf", "select='gt(scene,0.3)',showinfo",
|
||||
"-f", "null", "-"
|
||||
])
|
||||
```
|
||||
|
||||
**優點**:
|
||||
- ✅ 跨平台
|
||||
- ✅ 成熟穩定
|
||||
- ✅ 功能完整
|
||||
|
||||
**缺點**:
|
||||
- ⚠️ 依賴外部工具 (ffmpeg)
|
||||
- ⚠️ 進程開銷
|
||||
- ⚠️ 非原生實現
|
||||
|
||||
---
|
||||
|
||||
## Apple Native Video 解析
|
||||
|
||||
### 核心框架
|
||||
|
||||
#### 1. AVFoundation
|
||||
|
||||
**功能**:
|
||||
- 視頻讀取
|
||||
- 幀提取
|
||||
- 元數據訪問
|
||||
|
||||
**API**:
|
||||
```swift
|
||||
import AVFoundation
|
||||
|
||||
// 讀取視頻
|
||||
let asset = AVAsset(url: videoURL)
|
||||
let reader = try AVAssetReader(asset: asset)
|
||||
|
||||
// 獲取視頻軌道
|
||||
guard let track = asset.tracks(withMediaType: .video).first else {
|
||||
return
|
||||
}
|
||||
|
||||
// 配置幀輸出
|
||||
let output = AVAssetReaderTrackOutput(
|
||||
track: track,
|
||||
outputSettings: [
|
||||
kCVPixelBufferPixelFormatTypeKey as String: kCVPixelFormatType_32BGRA
|
||||
]
|
||||
)
|
||||
reader.add(output)
|
||||
|
||||
// 讀取幀
|
||||
while reader.status == .reading {
|
||||
if let sampleBuffer = output.copyNextSampleBuffer() {
|
||||
let frame = CMSampleBufferGetImageBuffer(sampleBuffer)
|
||||
// 處理幀
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
#### 2. Vision Framework
|
||||
|
||||
**功能**:
|
||||
- 視覺分析
|
||||
- 圖像處理
|
||||
- ANE 加速
|
||||
|
||||
**相關 API**:
|
||||
- `VNSequenceRequestHandler`: 幀序列處理
|
||||
- `VNCoreMLRequest`: Core ML 模型推理
|
||||
- `VNImageRequestHandler`: 單幀處理
|
||||
|
||||
---
|
||||
|
||||
#### 3. Core ML
|
||||
|
||||
**功能**:
|
||||
- 機器學習模型
|
||||
- ANE 加速
|
||||
- 自定義模型
|
||||
|
||||
**用途**:
|
||||
- 加載場景檢測模型
|
||||
- ANE 加速推理
|
||||
|
||||
---
|
||||
|
||||
### 實現方案
|
||||
|
||||
#### 方案 A: 幀差異法 (純 Swift)
|
||||
|
||||
**原理**: 比較相鄰幀的像素差異
|
||||
|
||||
**實現**:
|
||||
```swift
|
||||
import AVFoundation
|
||||
import CoreImage
|
||||
|
||||
func detectScenes(videoPath: String, threshold: Float = 0.3) -> [Scene] {
|
||||
let asset = AVAsset(url: URL(fileURLWithPath: videoPath))
|
||||
let reader = try! AVAssetReader(asset: asset)
|
||||
|
||||
guard let track = asset.tracks(withMediaType: .video).first else {
|
||||
return []
|
||||
}
|
||||
|
||||
let output = AVAssetReaderTrackOutput(
|
||||
track: track,
|
||||
outputSettings: [kCVPixelBufferPixelFormatTypeKey: kCVPixelFormatType_32BGRA]
|
||||
)
|
||||
reader.add(output)
|
||||
reader.startReading()
|
||||
|
||||
var scenes: [Scene] = []
|
||||
var previousFrame: CVPixelBuffer?
|
||||
var frameCount = 0
|
||||
var lastSceneFrame = 0
|
||||
|
||||
let context = CIContext()
|
||||
|
||||
while let sampleBuffer = output.copyNextSampleBuffer() {
|
||||
let currentFrame = CMSampleBufferGetImageBuffer(sampleBuffer)!
|
||||
|
||||
if let prev = previousFrame {
|
||||
// 計算幀差異
|
||||
let diff = calculateFrameDifference(
|
||||
frame1: prev,
|
||||
frame2: currentFrame,
|
||||
context: context
|
||||
)
|
||||
|
||||
if diff > threshold {
|
||||
// 檢測到場景切換
|
||||
scenes.append(Scene(
|
||||
startFrame: lastSceneFrame,
|
||||
endFrame: frameCount,
|
||||
score: diff
|
||||
))
|
||||
lastSceneFrame = frameCount
|
||||
}
|
||||
}
|
||||
|
||||
previousFrame = currentFrame
|
||||
frameCount += 1
|
||||
}
|
||||
|
||||
return scenes
|
||||
}
|
||||
|
||||
func calculateFrameDifference(frame1: CVPixelBuffer, frame2: CVPixelBuffer, context: CIContext) -> Float {
|
||||
let ciImage1 = CIImage(cvPixelBuffer: frame1)
|
||||
let ciImage2 = CIImage(cvPixelBuffer: frame2)
|
||||
|
||||
// 使用 Core Image 計算差異
|
||||
let diffFilter = CIFilter(name: "CIDifferenceBlendMode")!
|
||||
diffFilter.setValue(ciImage1, forKey: kCIInputImageKey)
|
||||
diffFilter.setValue(ciImage2, forKey: kCIInputBackgroundImageKey)
|
||||
|
||||
guard let diffImage = diffFilter.outputImage else {
|
||||
return 0.0
|
||||
}
|
||||
|
||||
// 計算平均亮度變化
|
||||
// ... (需要實現)
|
||||
|
||||
return 0.0
|
||||
}
|
||||
```
|
||||
|
||||
**性能評估**:
|
||||
- ✅ 純 Swift,無外部依賴
|
||||
- ✅ 使用 Core Image (GPU 加速)
|
||||
- ⚠️ 需要處理所有幀(計算量大)
|
||||
- ⚠️ 簡單的幀差異可能不夠準確
|
||||
|
||||
---
|
||||
|
||||
#### 方案 B: Vision + Core ML (ANE 加速)
|
||||
|
||||
**原理**: 使用預訓練模型進行場景檢測
|
||||
|
||||
**步驟**:
|
||||
1. 訓練/下載場景檢測模型
|
||||
2. 轉換為 Core ML 格式
|
||||
3. 使用 Vision + ANE 推理
|
||||
|
||||
**實現**:
|
||||
```swift
|
||||
import Vision
|
||||
import CoreML
|
||||
|
||||
func detectScenesWithML(videoPath: String) -> [Scene] {
|
||||
// 加載 Core ML 模型
|
||||
guard let model = try? VNCoreMLModel(for: SceneDetector().model) else {
|
||||
return []
|
||||
}
|
||||
|
||||
let request = VNCoreMLRequest(model: model) { request, error in
|
||||
// 處理結果
|
||||
}
|
||||
|
||||
// 使用 AVAssetReader 讀取幀
|
||||
// 對每個關鍵幀運行模型
|
||||
// ...
|
||||
}
|
||||
```
|
||||
|
||||
**優勢**:
|
||||
- ✅ ANE 加速
|
||||
- ✅ 更準確的檢測
|
||||
- ⚠️ 需要訓練/獲取模型
|
||||
- ⚠️ 實現複雜度高
|
||||
|
||||
---
|
||||
|
||||
#### 方案 C: AVFoundation + Metal (高性能)
|
||||
|
||||
**原理**: 使用 Metal 進行 GPU 並行計算
|
||||
|
||||
**實現**:
|
||||
```swift
|
||||
import Metal
|
||||
import AVFoundation
|
||||
|
||||
func detectScenesWithMetal(videoPath: String) -> [Scene] {
|
||||
let device = MTLCreateSystemDefaultDevice()!
|
||||
let commandQueue = device.makeCommandQueue()!
|
||||
|
||||
// Metal shader 計算幀差異
|
||||
let shaderSource = """
|
||||
kernel void computeDifference(
|
||||
texture2d<float, access::read> frame1 [[texture(0)]],
|
||||
texture2d<float, access::read> frame2 [[texture(1)]],
|
||||
device float *output [[buffer(0)]],
|
||||
uint2 gid [[thread_position_in_grid]]
|
||||
) {
|
||||
float4 p1 = frame1.read(gid);
|
||||
float4 p2 = frame2.read(gid);
|
||||
float diff = distance(p1.rgb, p2.rgb);
|
||||
output[0] += diff;
|
||||
}
|
||||
"""
|
||||
|
||||
// ... 實現細節
|
||||
}
|
||||
```
|
||||
|
||||
**優勢**:
|
||||
- ✅ GPU 加速
|
||||
- ✅ 高性能
|
||||
- ⚠️ 實現複雜
|
||||
- ⚠️ 需要專業 Metal 知識
|
||||
|
||||
---
|
||||
|
||||
## 可行性評估
|
||||
|
||||
### 技術可行性
|
||||
|
||||
| 方案 | 難度 | 性能 | 準確性 | 推薦度 |
|
||||
|------|------|------|--------|--------|
|
||||
| A: 幀差異法 | 中 | 中 | 低 | ⭐⭐⭐ |
|
||||
| B: Vision + ML | 高 | 高 | 高 | ⭐⭐⭐⭐ |
|
||||
| C: Metal | 很高 | 很高 | 中 | ⭐⭐ |
|
||||
|
||||
---
|
||||
|
||||
### 性能對比
|
||||
|
||||
| 方法 | 處理速度 | CPU 使用 | GPU 使用 | ANE 使用 |
|
||||
|------|----------|----------|----------|----------|
|
||||
| ffmpeg | 中 | 高 | 中 | - |
|
||||
| Swift 幀差異 | 中 | 中 | 高 (Core Image) | - |
|
||||
| Vision + ML | 快 | 低 | 低 | 高 |
|
||||
| Metal | 很快 | 低 | 高 | - |
|
||||
|
||||
---
|
||||
|
||||
### 實現複雜度
|
||||
|
||||
#### 方案 A: 純 Swift 幀差異 (2-3 天)
|
||||
|
||||
**步驟**:
|
||||
1. 實現 AVAssetReader 幀提取
|
||||
2. 實現 Core Image 幀差異計算
|
||||
3. 場景邊界檢測
|
||||
4. 測試和優化
|
||||
|
||||
**風險**:
|
||||
- 準確性可能不如 ffmpeg
|
||||
- 需要大量測試
|
||||
|
||||
---
|
||||
|
||||
#### 方案 B: Vision + Core ML (1-2 周)
|
||||
|
||||
**步驟**:
|
||||
1. 獲取/訓練場景檢測模型
|
||||
2. 轉換為 Core ML
|
||||
3. 實現 Vision pipeline
|
||||
4. 優化和測試
|
||||
|
||||
**風險**:
|
||||
- 模型訓練需要專業知識
|
||||
- 實現週期長
|
||||
|
||||
---
|
||||
|
||||
#### 方案 C: Metal (2-3 周)
|
||||
|
||||
**步驟**:
|
||||
1. 學習 Metal API
|
||||
2. 編寫 GPU shader
|
||||
3. 集成 AVFoundation
|
||||
4. 性能優化
|
||||
|
||||
**風險**:
|
||||
- 需要專業 Metal 知識
|
||||
- 開發週期長
|
||||
|
||||
---
|
||||
|
||||
## 建議方案
|
||||
|
||||
### 階段 1: 快速原型 (方案 A)
|
||||
|
||||
**時間**: 2-3 天
|
||||
|
||||
**目標**:
|
||||
- 驗證 Apple native video API
|
||||
- 評估基本性能
|
||||
- 確定準確性
|
||||
|
||||
**實現**:
|
||||
```swift
|
||||
// swift_scene_detector.swift
|
||||
// 簡單的幀差異法場景檢測
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 階段 2: 性能優化 (方案 B 或 C)
|
||||
|
||||
**前提**: 階段 1 驗證成功
|
||||
|
||||
**選擇**:
|
||||
- 如果需要高準確性 → 方案 B (Vision + Core ML)
|
||||
- 如果需要高性能 → 方案 C (Metal)
|
||||
|
||||
**時間**: 1-2 周
|
||||
|
||||
---
|
||||
|
||||
### 階段 3: 集成測試
|
||||
|
||||
**目標**:
|
||||
- 替代 ffmpeg 版本
|
||||
- 性能基準測試
|
||||
- 準確性驗證
|
||||
|
||||
---
|
||||
|
||||
## 競品分析
|
||||
|
||||
### PySceneDetect (Python)
|
||||
|
||||
**算法**:
|
||||
- ContentDetector: 幀內容差異
|
||||
- AdaptiveDetector: 自適應閾值
|
||||
|
||||
**性能**:
|
||||
- 速度: ~3s for 8s video
|
||||
- 準確性: 高
|
||||
|
||||
---
|
||||
|
||||
### ffmpeg select filter
|
||||
|
||||
**算法**: 場景檢測 filter
|
||||
|
||||
**性能**:
|
||||
- 速度: ~1s for 8s video (Rust wrapper)
|
||||
- 準確性: 中
|
||||
|
||||
---
|
||||
|
||||
## Apple Vision 的優勢
|
||||
|
||||
1. **ANE 加速**
|
||||
- 專用神經網絡處理器
|
||||
- 低功耗高性能
|
||||
|
||||
2. **原生集成**
|
||||
- 無外部依賴
|
||||
- 系統級優化
|
||||
|
||||
3. **隱私保護**
|
||||
- 本地處理
|
||||
- 無數據上傳
|
||||
|
||||
---
|
||||
|
||||
## 實施建議
|
||||
|
||||
### 立即行動
|
||||
|
||||
1. **創建原型項目**
|
||||
```bash
|
||||
mkdir -p tools/cli/swift/Sources/swift_scene_detector
|
||||
```
|
||||
|
||||
2. **實現方案 A**
|
||||
- 驗證可行性
|
||||
- 收集性能數據
|
||||
|
||||
3. **對比測試**
|
||||
- 與 ffmpeg 版本對比
|
||||
- 準確性和性能
|
||||
|
||||
---
|
||||
|
||||
### 長期規劃
|
||||
|
||||
1. **如果方案 A 可行**:
|
||||
- 優化算法
|
||||
- 替代 rust_cut
|
||||
|
||||
2. **如果需要更高性能**:
|
||||
- 實現方案 B (Vision + Core ML)
|
||||
- 利用 ANE 加速
|
||||
|
||||
---
|
||||
|
||||
## 風險
|
||||
|
||||
### 技術風險
|
||||
|
||||
- ⚠️ 幀差異法準確性不足
|
||||
- ⚠️ Core ML 模型難以獲取
|
||||
- ⚠️ Metal 開發週期長
|
||||
|
||||
### 時間風險
|
||||
|
||||
- ⚠️ 原型驗證需要 2-3 天
|
||||
- ⚠️ 完整實現需要 1-2 周
|
||||
|
||||
---
|
||||
|
||||
## 總結
|
||||
|
||||
### ✅ 可行
|
||||
|
||||
Apple native video 解析**技術上可行**,有多種實現方案。
|
||||
|
||||
### 📊 推薦路線
|
||||
|
||||
1. **短期**: 方案 A (純 Swift 幀差異)
|
||||
2. **中期**: 方案 B (Vision + Core ML, ANE 加速)
|
||||
3. **長期**: 根據需求優化
|
||||
|
||||
### 🎯 目標
|
||||
|
||||
- 替代 ffmpeg 依賴
|
||||
- 利用 Apple Vision + ANE
|
||||
- 提升性能和準確性
|
||||
|
||||
---
|
||||
|
||||
**下一步**: 創建 swift_scene_detector 原型,驗證方案 A 可行性。
|
||||
|
||||
---
|
||||
|
||||
**研究日期**: 2026-09-28
|
||||
**狀態**: ✅ **技術可行,建議先實現方案 A 原型**
|
||||
@@ -0,0 +1,300 @@
|
||||
---
|
||||
title: Apple Native Video Performance Analysis
|
||||
version: 1.0
|
||||
date: 2026-09-28
|
||||
author: OpenCode
|
||||
status: completed
|
||||
---
|
||||
|
||||
## 性能對比測試結果
|
||||
|
||||
### 測試環境
|
||||
|
||||
**視頻**: 020.mp4 (8.8s, 60 FPS, 529 frames, 1920x1080)
|
||||
|
||||
---
|
||||
|
||||
### 性能對比
|
||||
|
||||
| 方法 | 執行時間 | 檢測結果 | 相對速度 |
|
||||
|------|----------|----------|----------|
|
||||
| **Rust (ffmpeg)** | **0.81s** | 1 scene | **基準 (1x)** |
|
||||
| Swift (Apple Native) | 6.18s | 1 scene | 7.65x 更慢 |
|
||||
|
||||
---
|
||||
|
||||
## 性能差異分析
|
||||
|
||||
### Rust (ffmpeg) 優勢
|
||||
|
||||
1. **高度優化的 C 代碼**
|
||||
- ffmpeg 已經過多年優化
|
||||
- 使用 SIMD 指令集
|
||||
- 底層 C 實現效率高
|
||||
|
||||
2. **select filter 效率**
|
||||
- 專門設計用於場景檢測
|
||||
- 單次遍歷視頻
|
||||
- 內置閾值判斷
|
||||
|
||||
3. **進程開銷**
|
||||
- 單個進程
|
||||
- 直接讀取視頻流
|
||||
|
||||
---
|
||||
|
||||
### Swift (Apple Native) 瓶頸
|
||||
|
||||
1. **幀提取開銷**
|
||||
```swift
|
||||
// 每次都需要:
|
||||
let sampleBuffer = output.copyNextSampleBuffer()
|
||||
let currentBuffer = CMSampleBufferGetImageBuffer(sampleBuffer)
|
||||
```
|
||||
- CVPixelBuffer 創建開銷
|
||||
- 內存分配
|
||||
|
||||
2. **Core Image 處理**
|
||||
```swift
|
||||
// 每幀都調用 Core Image
|
||||
let ciImage1 = CIImage(cvPixelBuffer: frame1)
|
||||
let ciImage2 = CIImage(cvPixelBuffer: frame2)
|
||||
```
|
||||
- CIImage 創建開銷
|
||||
- GPU 上傳/下載
|
||||
|
||||
3. **像素採樣**
|
||||
```swift
|
||||
// 對每幀進行 100 次採樣
|
||||
for i in 0..<sampleCount {
|
||||
if let cgImage = context.createCGImage(...) {
|
||||
// 創建 CGImage 開銷
|
||||
}
|
||||
}
|
||||
```
|
||||
- CGImage 創建開銷
|
||||
- CPU-GPU 數據傳輸
|
||||
|
||||
4. **降分辨率影響**
|
||||
```swift
|
||||
// 降低到 160x90
|
||||
kCVPixelBufferWidthKey as String: 160,
|
||||
kCVPixelBufferHeightKey as String: 90
|
||||
```
|
||||
- 需要縮放開銷
|
||||
- 信息損失可能影響準確性
|
||||
|
||||
---
|
||||
|
||||
## 優化方向
|
||||
|
||||
### 1. 使用 Vision Framework (推薦)
|
||||
|
||||
**原理**: 利用 Vision 的原生圖像分析
|
||||
|
||||
```swift
|
||||
import Vision
|
||||
|
||||
let request = VNSequenceRequestHandler()
|
||||
// 使用 Vision 的幀差異檢測
|
||||
```
|
||||
|
||||
**優勢**:
|
||||
- ✅ ANE 加速
|
||||
- ✅ 優化的底層實現
|
||||
- ✅ 無需手動像素處理
|
||||
|
||||
**預期性能**: 2-3x 提升
|
||||
|
||||
---
|
||||
|
||||
### 2. 使用 Metal Shader
|
||||
|
||||
**原理**: GPU 並行計算
|
||||
|
||||
```swift
|
||||
import Metal
|
||||
|
||||
// Metal shader 計算幀差異
|
||||
kernel void computeDifference(...) {
|
||||
// GPU 並行處理所有像素
|
||||
}
|
||||
```
|
||||
|
||||
**優勢**:
|
||||
- ✅ GPU 並行
|
||||
- ✅ 無 CPU-GPU 傳輸開銷
|
||||
- ✅ 最高性能
|
||||
|
||||
**預期性能**: 5-10x 提升
|
||||
|
||||
---
|
||||
|
||||
### 3. 優化當前實現
|
||||
|
||||
**改進點**:
|
||||
|
||||
#### A. 減少幀處理頻率
|
||||
|
||||
```swift
|
||||
// 當前: 每 3 幀處理一次
|
||||
if frameNum % 3 == 0 {
|
||||
|
||||
// 改進: 每 10 幀處理一次
|
||||
if frameNum % 10 == 0 {
|
||||
```
|
||||
|
||||
**預期性能**: 3x 提升
|
||||
|
||||
---
|
||||
|
||||
#### B. 使用像素緩衝區直接訪問
|
||||
|
||||
```swift
|
||||
// 當前: 使用 Core Image
|
||||
let ciImage = CIImage(cvPixelBuffer: buffer)
|
||||
let cgImage = context.createCGImage(...)
|
||||
|
||||
// 改進: 直接訪問像素數據
|
||||
CVPixelBufferLockBaseAddress(buffer, .readOnly)
|
||||
let pixelData = CVPixelBufferGetBaseAddress(buffer)
|
||||
// 直接計算差異
|
||||
```
|
||||
|
||||
**優期性能**: 2-3x 提升
|
||||
|
||||
---
|
||||
|
||||
#### C. 跳過 Core Image 創建
|
||||
|
||||
```swift
|
||||
// 當前: 每幀創建 CIImage
|
||||
let ciImage1 = CIImage(cvPixelBuffer: frame1)
|
||||
|
||||
// 改進: 直接比較像素緩衝區
|
||||
func compareBuffers(_ b1: CVPixelBuffer, _ b2: CVPixelBuffer) -> Float {
|
||||
// 直接訪問內存
|
||||
}
|
||||
```
|
||||
|
||||
**預期性能**: 2x 提升
|
||||
|
||||
---
|
||||
|
||||
## 綜合優化方案
|
||||
|
||||
### Phase 1: 快速優化 (1 天)
|
||||
|
||||
**目標**: 3x 性能提升 (2s)
|
||||
|
||||
**措施**:
|
||||
1. 減少幀處理頻率 (10 幀一次)
|
||||
2. 直接訪問像素緩衝區
|
||||
3. 跳過 Core Image 創建
|
||||
|
||||
---
|
||||
|
||||
### Phase 2: Vision 集成 (2-3 天)
|
||||
|
||||
**目標**: 5x 性能提升 (1.2s)
|
||||
|
||||
**措施**:
|
||||
1. 使用 Vision Framework
|
||||
2. 利用 ANE 加速
|
||||
3. 優化 pipeline
|
||||
|
||||
---
|
||||
|
||||
### Phase 3: Metal 實現 (1 周)
|
||||
|
||||
**目標**: 10x 性能提升 (0.6s, 超越 ffmpeg)
|
||||
|
||||
**措施**:
|
||||
1. Metal shader 編寫
|
||||
2. GPU 並行計算
|
||||
3. 內存優化
|
||||
|
||||
---
|
||||
|
||||
## 成本效益分析
|
||||
|
||||
### ffmpeg 方案
|
||||
|
||||
**優勢**:
|
||||
- ✅ 性能優秀 (0.8s)
|
||||
- ✅ 成熟穩定
|
||||
- ✅ 跨平台
|
||||
|
||||
**劣勢**:
|
||||
- ⚠️ 外部依賴
|
||||
- ⚠️ 進程開銷
|
||||
|
||||
---
|
||||
|
||||
### Apple Native 方案
|
||||
|
||||
**優勢**:
|
||||
- ✅ 無外部依賴
|
||||
- ✅ 原生集成
|
||||
|
||||
**劣勢**:
|
||||
- ⚠️ 當前性能較差 (6.2s)
|
||||
- ⚠️ 需要優化時間
|
||||
|
||||
---
|
||||
|
||||
### 建議
|
||||
|
||||
**短期 (現在)**:
|
||||
- ✅ 繼續使用 Rust + ffmpeg
|
||||
- ✅ 性能優秀,穩定可靠
|
||||
|
||||
**中期 (1-2 周後)**:
|
||||
- ⏳ 實現 Vision + ANE 版本
|
||||
- ⏳ 達到相近性能
|
||||
|
||||
**長期 (1 月後)**:
|
||||
- ⏳ Metal 版本
|
||||
- ⏳ 可能超越 ffmpeg
|
||||
|
||||
---
|
||||
|
||||
## 測試數據
|
||||
|
||||
### 原始測試
|
||||
|
||||
```bash
|
||||
Rust (ffmpeg): 0.81s
|
||||
Swift (Apple Native): 6.18s
|
||||
Performance ratio: 7.65x
|
||||
```
|
||||
|
||||
### 預期優化後
|
||||
|
||||
| 階段 | 性能 | vs ffmpeg |
|
||||
|------|------|-----------|
|
||||
| 當前 | 6.18s | 7.65x 更慢 |
|
||||
| Phase 1 | ~2.0s | 2.5x 更慢 |
|
||||
| Phase 2 | ~1.2s | 1.5x 更慢 |
|
||||
| Phase 3 | ~0.6s | 1.3x 更快 |
|
||||
|
||||
---
|
||||
|
||||
## 結論
|
||||
|
||||
### 當前狀態
|
||||
|
||||
Apple Native 實現**技術可行**,但當前性能不如 ffmpeg。
|
||||
|
||||
### 建議策略
|
||||
|
||||
1. **保留 ffmpeg 版本** (當前主力)
|
||||
2. **逐步優化 Apple Native 版本**
|
||||
3. **根據需求選擇**:
|
||||
- 追求性能 → ffmpeg
|
||||
- 追求原生 → Apple Native (優化後)
|
||||
|
||||
---
|
||||
|
||||
**研究日期**: 2026-09-28
|
||||
**狀態**: ⚠️ **可行但需優化,建議保留 ffmpeg 版本**
|
||||
@@ -0,0 +1,162 @@
|
||||
---
|
||||
title: Audio Scene & Instrument Detection POC Plan
|
||||
version: 0.1
|
||||
date: 2026-07-02
|
||||
author: OpenCode
|
||||
status: planned
|
||||
---
|
||||
|
||||
| scope | status | applicable to |
|
||||
|-------|--------|---------------|
|
||||
| Audio processing pipeline | planned | Video files with non-speech audio |
|
||||
|
||||
## Goal
|
||||
|
||||
Detect non-speech audio events (instruments, music, environmental sounds) in video files alongside existing ASRX speech recognition.
|
||||
|
||||
## Why
|
||||
|
||||
Current pipeline only detects speech (ASRX → 64 segments + 1554 speaker embeddings). Instrument sounds, background music, and environmental audio are completely ignored.
|
||||
|
||||
## Technical Options
|
||||
|
||||
### Option A: PANNs (Pre-trained Audio Neural Networks)
|
||||
- **Model**: Cnn14 (313M params, 700MB weights)
|
||||
- **Classes**: 527 AudioSet classes (piano, guitar, drums, speech, etc.)
|
||||
- **Pros**: Production-ready, accurate, PyTorch-based
|
||||
- **Cons**: Large download, ~200MB RAM per inference
|
||||
- **Install**: `pip install panns-inference`
|
||||
|
||||
### Option B: YAMNet (Google)
|
||||
- **Model**: MobileNet-based, 4MB weights
|
||||
- **Classes**: 521 AudioSet classes
|
||||
- **Pros**: Lightweight, fast
|
||||
- **Cons**: Requires TensorFlow (not currently installed)
|
||||
- **Install**: `pip install yamnet` + TensorFlow
|
||||
|
||||
### Option C: torchaudio + heuristics (lightweight fallback)
|
||||
- Use existing PyTorch + torchaudio
|
||||
- Extract spectral features (MFCC, centroid, energy)
|
||||
- Simple classification: speech vs music vs silence
|
||||
- **Pros**: No extra dependencies
|
||||
- **Cons**: Less accurate, limited classes
|
||||
|
||||
## Recommended: Option A (PANNs)
|
||||
|
||||
## Pipeline Integration
|
||||
|
||||
```
|
||||
Video → Audio Extract → ASRX (speech) → Speaker Embeddings (3.4/s)
|
||||
→ Audio Scene (new) → Scene Labels (1/s)
|
||||
```
|
||||
|
||||
### New Processor: `audio_scene`
|
||||
|
||||
| Field | Value |
|
||||
|-------|-------|
|
||||
| Processor type | `audio_scene` |
|
||||
| Input | Video file (audio track) |
|
||||
| Output | `file_uuid.audio_scene.json` |
|
||||
| Sampling | 1-second segments |
|
||||
| Qdrant collection | `momentry_{schema}_audio_scene` |
|
||||
|
||||
### Output Format
|
||||
|
||||
```json
|
||||
{
|
||||
"file_uuid": "...",
|
||||
"segments": [
|
||||
{
|
||||
"start_time": 0.0,
|
||||
"end_time": 1.0,
|
||||
"primary_class": "speech",
|
||||
"confidence": 0.95,
|
||||
"top_classes": [
|
||||
{"class": "speech", "score": 0.95},
|
||||
{"class": "music", "score": 0.03},
|
||||
{"class": "piano", "score": 0.01}
|
||||
]
|
||||
}
|
||||
],
|
||||
"summary": {
|
||||
"speech_ratio": 0.72,
|
||||
"music_ratio": 0.15,
|
||||
"silence_ratio": 0.08,
|
||||
"instrument_ratio": 0.05,
|
||||
"instruments_detected": ["piano", "guitar"]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Qdrant Storage
|
||||
|
||||
| Field | Type | Purpose |
|
||||
|-------|------|---------|
|
||||
| `file_uuid` | string | Filter by file |
|
||||
| `start_time` | float | Segment start |
|
||||
| `end_time` | float | Segment end |
|
||||
| `primary_class` | keyword | Filter by class |
|
||||
| `confidence` | float | Filter by confidence |
|
||||
| `instrument_name` | keyword | Search by instrument |
|
||||
| `vector` | f32[2048] | Audio embedding for similarity search |
|
||||
|
||||
### Processor Dependencies
|
||||
|
||||
```
|
||||
audio_scene → (no dependencies, runs parallel with ASRX)
|
||||
```
|
||||
|
||||
## Key AudioSet Instrument Classes
|
||||
|
||||
| Category | Classes |
|
||||
|----------|---------|
|
||||
| Piano | Piano, Electric piano, Keyboard |
|
||||
| Guitar | Guitar, Electric guitar, Acoustic guitar |
|
||||
| Drums | Drum kit, Snare drum, Cymbal, Hi-hat |
|
||||
| Strings | Violin, Cello, Harp, Double bass |
|
||||
| Wind | Flute, Saxophone, Trumpet, Clarinet |
|
||||
| Voice | Speech, Singing, Chant, Choir |
|
||||
| Other | Music, Percussion, Organ, Synthesizer |
|
||||
|
||||
## POC Steps
|
||||
|
||||
1. **Install panns-inference**
|
||||
```bash
|
||||
pip install panns-inference
|
||||
```
|
||||
|
||||
2. **Create `scripts/audio_scene_processor.py`**
|
||||
- Load audio via ffmpeg → numpy array
|
||||
- Process 1-second segments through Cnn14
|
||||
- Save results to JSON + Qdrant
|
||||
|
||||
3. **Add processor type to pipeline**
|
||||
- Add `AudioScene` to `ProcessorType` enum
|
||||
- Add to worker's processor dispatch
|
||||
- Add `AUDIO_SCENE_TIMEOUT` config
|
||||
|
||||
4. **Test with existing video**
|
||||
- Run on KOBA interview video
|
||||
- Verify instrument detection accuracy
|
||||
- Check performance (time, memory)
|
||||
|
||||
5. **Integrate with search**
|
||||
- Add audio_scene to universal_search
|
||||
- Add filter by audio class (speech/music/instrument)
|
||||
|
||||
## Estimated Effort
|
||||
|
||||
| Step | Time |
|
||||
|------|------|
|
||||
| Install + prototype script | 2-3 hours |
|
||||
| Pipeline integration | 1-2 hours |
|
||||
| Qdrant + search integration | 1 hour |
|
||||
| Testing + tuning | 1-2 hours |
|
||||
| **Total** | **5-8 hours** |
|
||||
|
||||
## Future Enhancements
|
||||
|
||||
- Real-time audio classification during processing
|
||||
- Audio event timeline visualization
|
||||
- Combine with TKG for audio-visual relationships
|
||||
- Background music detection for copyright checks
|
||||
@@ -0,0 +1,189 @@
|
||||
---
|
||||
title: face_detections Table Deprecation Plan
|
||||
version: 1.0
|
||||
date: 2026-06-21
|
||||
author: OpenCode
|
||||
status: Draft
|
||||
---
|
||||
|
||||
## Overview
|
||||
|
||||
`face_detections` 表在 TKG Phase 0-2.7 迁移后,大部分功能已迁移到 Qdrant。本文档规划后续 deprecation 策略。
|
||||
|
||||
## Current Usage Analysis
|
||||
|
||||
### TKG Builders (PostgreSQL Fallback)
|
||||
|
||||
**状态**: 可保留作为 fallback
|
||||
|
||||
| Function | 用途 | 状态 |
|
||||
|----------|------|------|
|
||||
| `build_face_trace_nodes_from_pg()` | Fallback | ⚠️ 保留 |
|
||||
| `build_gaze_trace_nodes_from_pg()` | Fallback | ⚠️ 保留 |
|
||||
| `build_lip_trace_nodes_from_pg()` | Fallback | ⚠️ 保留 |
|
||||
| `build_co_occurrence_edges_from_pg()` | Fallback | ⚠️ 保留 |
|
||||
| `build_face_face_edges_from_pg()` | Fallback | ⚠️ 保留 |
|
||||
| `build_speaker_face_edges_from_pg()` | Fallback | ⚠️ 保留 |
|
||||
|
||||
**总计**: 12 fallback functions
|
||||
|
||||
**建议**: 保留 PostgreSQL fallback,作为 Qdrant 失败时的备用方案。
|
||||
|
||||
### API Endpoints (Direct Queries)
|
||||
|
||||
**状态**: 需要迁移或保留
|
||||
|
||||
| Module | 功能 | 依赖程度 | 迁移难度 |
|
||||
|--------|------|---------|----------|
|
||||
| `files.rs` | 文件处理 | 高 | 中等 |
|
||||
| `five_w1h_agent_api.rs` | Five W1H agent | 中 | 低 |
|
||||
| `identities.rs` | Identity 管理 | 高 | 高 |
|
||||
| `identity_agent_api.rs` | Identity Agent | 高 | 高 |
|
||||
| `identity_api.rs` | Identity API | 高 | 高 |
|
||||
| `identity_binding.rs` | Face binding | **非常高** | **非常高** |
|
||||
| `media_api.rs` | Media API | 中 | 中 |
|
||||
| `scan.rs` | Scan 功能 | 低 | 低 |
|
||||
| `tmdb_api.rs` | TMDb API | 中 | 中 |
|
||||
| `trace_agent_api.rs` | Trace Agent | 高 | 中 |
|
||||
|
||||
**总计**: 11 modules with direct queries
|
||||
|
||||
**关键依赖**:
|
||||
- **Identity binding**: 使用 `face_detections.trace_id` 进行 face binding
|
||||
- **Identity Agent**: 使用 `face_detections.trace_id` 进行 identity matching
|
||||
|
||||
### Identity Binding Dependencies
|
||||
|
||||
**最关键依赖**: `src/api/identity_binding.rs`
|
||||
|
||||
**用途**:
|
||||
- `bind_identity_trace()`: 绑定 identity 到 trace_id
|
||||
- `unbind_identity()`: 解绑 identity
|
||||
- Face ↔ Identity mapping
|
||||
|
||||
**现状**:
|
||||
- Phase 2.3 已迁移到 TKG nodes properties
|
||||
- 但 identity binding API 仍使用 face_detections 查询
|
||||
|
||||
**迁移方案**:
|
||||
1. 查询 TKG nodes by identity_id
|
||||
2. 更新 TKG nodes properties
|
||||
3. 移除 face_detections 查询
|
||||
|
||||
## Deprecation Strategy
|
||||
|
||||
### Phase A: Documentation (Immediate)
|
||||
|
||||
- [x] 标记 `face_detections` 为 deprecated (in docs)
|
||||
- [x] 文档说明迁移路径
|
||||
- [x] 保留 PostgreSQL fallback
|
||||
|
||||
### Phase B: Gradual Migration (Future)
|
||||
|
||||
**优先级**:
|
||||
|
||||
| Priority | Module | Migration | Timeline |
|
||||
|----------|--------|-----------|----------|
|
||||
| P1 | identity_binding.rs | TKG-based binding | TBD |
|
||||
| P2 | identity_agent_api.rs | TKG-based matching | TBD |
|
||||
| P3 | identity_api.rs | TKG queries | TBD |
|
||||
| P4 | Other APIs | Case-by-case | TBD |
|
||||
|
||||
### Phase C: Removal (Long-term)
|
||||
|
||||
**条件**:
|
||||
- 所有 API endpoints 迁移完成
|
||||
- TKG-only architecture 完全稳定
|
||||
- 经过充分测试验证
|
||||
|
||||
**时间**: TBD (至少 6 个月后)
|
||||
|
||||
## Current Status
|
||||
|
||||
### What We Can Deprecate Now
|
||||
|
||||
**Nothing**: 所有功能仍有 PostgreSQL fallback 或 API dependencies
|
||||
|
||||
**原因**:
|
||||
1. Production Qdrant collection 为空 (0 points)
|
||||
2. PostgreSQL fallback 是必要的安全机制
|
||||
3. Identity binding APIs 依赖 face_detections
|
||||
|
||||
### What We Keep
|
||||
|
||||
- ✅ PostgreSQL fallback functions
|
||||
- ✅ face_detections table
|
||||
- ✅ populate_face_detections_from_face_json (Phase 0)
|
||||
|
||||
### What We Document
|
||||
|
||||
- ⚠️ face_detections deprecated (but still used)
|
||||
- ⚠️ New features should use Qdrant/TKG
|
||||
- ⚠️ Migration path documented
|
||||
|
||||
## Recommendations
|
||||
|
||||
### Immediate Actions
|
||||
|
||||
1. **标记为 deprecated**: 在 AGENTS.md 中说明
|
||||
2. **文档迁移路径**: 记录 TKG-based alternatives
|
||||
3. **保留 fallback**: 确保 Production 稳定性
|
||||
|
||||
### Short-term Actions
|
||||
|
||||
1. **测试新视频**: 注册新视频验证 Qdrant-based
|
||||
2. **监控 Production**: 观察 PostgreSQL fallback 使用率
|
||||
3. **性能对比**: Qdrant vs PostgreSQL
|
||||
|
||||
### Long-term Actions
|
||||
|
||||
1. **API migration**: 逐步迁移 identity binding APIs
|
||||
2. **数据迁移**: 批量迁移现有数据到 Qdrant
|
||||
3. **最终移除**: 在验证完成后移除 face_detections
|
||||
|
||||
## Migration Path for Identity Binding
|
||||
|
||||
### Current Implementation
|
||||
|
||||
```rust
|
||||
// identity_binding.rs
|
||||
let trace_id = sqlx::query_scalar(
|
||||
"SELECT trace_id FROM face_detections WHERE ..."
|
||||
)
|
||||
```
|
||||
|
||||
### Future Implementation (TKG-based)
|
||||
|
||||
```rust
|
||||
// Query TKG nodes with identity_id
|
||||
let nodes = sqlx::query_as(
|
||||
"SELECT id, external_id FROM tkg_nodes
|
||||
WHERE file_uuid=$1 AND node_type='face_trace'
|
||||
AND properties->>'identity_id' IS NOT NULL"
|
||||
)
|
||||
```
|
||||
|
||||
**优势**:
|
||||
- 无需 face_detections
|
||||
- TKG-only architecture
|
||||
- 性能更好 (TKG nodes 缓存)
|
||||
|
||||
## Conclusion
|
||||
|
||||
**当前**: face_detections **不能** deprecated
|
||||
- PostgreSQL fallback 必要
|
||||
- API endpoints 仍有依赖
|
||||
- Production 稳定性优先
|
||||
|
||||
**未来**: 逐步迁移到 TKG-only
|
||||
- 按优先级迁移 API endpoints
|
||||
- 验证后考虑移除 face_detections
|
||||
- 至少 6 个月后评估
|
||||
|
||||
**建议**: 保持现状,文档化迁移路径,新功能使用 Qdrant/TKG。
|
||||
|
||||
---
|
||||
|
||||
**状态**: Draft (不执行 deprecation)
|
||||
**原因**: Production 稳定性 + API dependencies
|
||||
**下一步**: 文档化 + 测试新视频
|
||||
@@ -0,0 +1,293 @@
|
||||
# FaceFilterSettings 文件存储架构
|
||||
|
||||
**日期**: 2026-10-09
|
||||
**版本**: 2.0
|
||||
**状态**: 已实施(透明管理)
|
||||
|
||||
---
|
||||
|
||||
## 架构原则
|
||||
|
||||
### ✅ 正确的设计
|
||||
|
||||
| 数据类型 | 存储位置 | 原因 |
|
||||
|---------|---------|------|
|
||||
| **配置参数** | `.json` 文件 | 便于跨设备同步、版本控制、手动编辑 |
|
||||
| **搜索数据** | PostgreSQL + Qdrant | 快速检索、向量搜索、全文搜索 |
|
||||
|
||||
### 透明管理机制
|
||||
|
||||
**不需要手动迁移脚本,系统自动管理:**
|
||||
|
||||
1. **读取优先级**: 文件 > 数据库 > 默认值
|
||||
2. **自动迁移**: 数据库数据自动迁移到文件
|
||||
3. **向后兼容**: 旧数据透明处理
|
||||
4. **用户无感知**: API 层面完全透明
|
||||
|
||||
---
|
||||
|
||||
## 实施细节
|
||||
|
||||
### 1. GET /api/v1/file-profile(透明读取)
|
||||
|
||||
```rust
|
||||
// 1. 从文件读取(优先)
|
||||
let disk_profile = FileProfile::load_from_disk(output_dir, &file_uuid);
|
||||
|
||||
// 2. 优先级: 文件 > 数据库 > 默认值
|
||||
let face_filter = disk_profile
|
||||
.and_then(|p| p.face_filter)
|
||||
.or_else(|| db_face_filter) // 向后兼容
|
||||
.unwrap_or_else(FaceFilterSettings::defaults);
|
||||
|
||||
// 3. 自动迁移:如果数据在数据库但文件不存在
|
||||
if disk_profile.is_none() && db_face_filter.is_some() {
|
||||
// 自动创建文件
|
||||
let mut new_profile = create_profile(...);
|
||||
new_profile.face_filter = Some(face_filter);
|
||||
new_profile.save_to_disk(output_dir); // 透明迁移
|
||||
}
|
||||
```
|
||||
|
||||
**效果**:
|
||||
- ✅ 第一次访问时自动迁移
|
||||
- ✅ 用户完全无感知
|
||||
- ✅ 不需要任何迁移脚本
|
||||
- ✅ 向后兼容所有旧数据
|
||||
|
||||
### 2. PUT /api/v1/file-profile(直接写入文件)
|
||||
|
||||
```rust
|
||||
// 直接更新文件(primary source)
|
||||
let mut profile = load_or_create_profile(file_uuid);
|
||||
profile.face_filter = Some(ff);
|
||||
profile.save_to_disk(output_dir);
|
||||
|
||||
// 数据库不再存储 face_filter
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 透明管理工作流程
|
||||
|
||||
### 第一次访问(自动迁移)
|
||||
|
||||
```
|
||||
用户请求 GET /file-profile?file_uuid=xxx
|
||||
↓
|
||||
尝试从文件读取
|
||||
↓ (文件不存在)
|
||||
尝试从数据库读取 ✅ 找到
|
||||
↓
|
||||
返回数据给用户
|
||||
↓
|
||||
后台自动创建文件 📝
|
||||
↓
|
||||
下次访问直接从文件读取 ✅
|
||||
```
|
||||
|
||||
### 后续访问(直接读文件)
|
||||
|
||||
```
|
||||
用户请求 GET /file-profile?file_uuid=xxx
|
||||
↓
|
||||
从文件读取 ✅
|
||||
↓
|
||||
返回数据给用户
|
||||
```
|
||||
|
||||
### 保存配置(直接写文件)
|
||||
|
||||
```
|
||||
用户请求 PUT /file-profile
|
||||
↓
|
||||
直接写入文件 ✅
|
||||
↓
|
||||
返回成功
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 优势
|
||||
|
||||
### 1. 零配置迁移
|
||||
|
||||
- ❌ 不需要迁移脚本
|
||||
- ❌ 不需要手动操作
|
||||
- ✅ 第一次访问自动迁移
|
||||
- ✅ 用户完全无感知
|
||||
|
||||
### 2. 架构更简单
|
||||
|
||||
- ❌ 不需要数据库迁移脚本
|
||||
- ❌ 不需要维护 DB 表结构
|
||||
- ✅ 文件即 primary source of truth
|
||||
- ✅ 便于版本控制
|
||||
|
||||
### 3. 向后兼容
|
||||
|
||||
- ✅ 旧数据自动处理
|
||||
- ✅ 新旧 API 同时支持
|
||||
- ✅ 不影响现有功能
|
||||
|
||||
### 4. 跨设备同步
|
||||
|
||||
```bash
|
||||
# 只需同步文件即可
|
||||
rsync -av ~/momentry/output/ server:~/momentry/output/
|
||||
rsync -av ~/momentry/identities/ server:~/momentry/identities/
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 数据库角色
|
||||
|
||||
### 数据库存储
|
||||
|
||||
- ✅ 文件元数据(路径、名称、状态)
|
||||
- ✅ 处理状态(ASR、OCR、Face 等)
|
||||
- ✅ 搜索索引(FTS、向量)
|
||||
- ⚠️ face_filter(仅作为向后兼容备份)
|
||||
|
||||
### 数据库不存储
|
||||
|
||||
- ❌ 配置参数(FaceFilterSettings)- 新数据不写入数据库
|
||||
- ❌ 用户偏好(UI 设置)
|
||||
- ❌ 业务逻辑参数(Trace 设置)
|
||||
|
||||
---
|
||||
|
||||
## 示例场景
|
||||
|
||||
### 场景 1: 现有数据自动迁移
|
||||
|
||||
```
|
||||
1. 数据库中有 100 个文件的 face_filter
|
||||
2. 用户访问第一个文件
|
||||
- API 检测到数据库有数据,但文件不存在
|
||||
- 自动创建 .profile.json
|
||||
- 返回数据给用户
|
||||
3. 用户继续访问其他文件
|
||||
- 同样自动创建文件
|
||||
4. 最终所有数据都迁移到文件
|
||||
- 用户完全无感知
|
||||
- 不需要任何手动操作
|
||||
```
|
||||
|
||||
### 场景 2: 新数据直接写入文件
|
||||
|
||||
```
|
||||
1. 用户修改 face_filter
|
||||
2. API 直接写入 .profile.json
|
||||
3. 数据库不更新(不需要)
|
||||
4. 下次读取直接从文件读取
|
||||
```
|
||||
|
||||
### 场景 3: 跨设备同步
|
||||
|
||||
```
|
||||
设备 A:
|
||||
- 修改 face_filter
|
||||
- 写入 .profile.json
|
||||
|
||||
同步:
|
||||
- rsync 文件到设备 B
|
||||
|
||||
设备 B:
|
||||
- 读取 face_filter
|
||||
- 直接从文件读取 ✅
|
||||
- 无需同步数据库
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## API 兼容性
|
||||
|
||||
### 向后兼容
|
||||
|
||||
- ✅ 旧的 API 请求格式仍然支持
|
||||
- ✅ 数据自动从数据库迁移到文件
|
||||
- ✅ 不影响现有功能
|
||||
- ✅ 用户完全无感知
|
||||
|
||||
### 版本演进
|
||||
|
||||
| 版本 | face_filter 存储 | 迁移方式 | 用户感知 |
|
||||
|------|----------------|---------|---------|
|
||||
| v1.0.20261008 | 数据库 | - | - |
|
||||
| v1.0.20261009+ | 文件 | 透明自动 | 无感知 |
|
||||
|
||||
---
|
||||
|
||||
## 测试计划
|
||||
|
||||
### 功能测试
|
||||
|
||||
1. **GET file-profile(透明读取)**
|
||||
- [ ] 从文件读取成功
|
||||
- [ ] 文件不存在时从数据库读取
|
||||
- [ ] 自动创建文件成功
|
||||
- [ ] 缺失文件时使用默认值
|
||||
|
||||
2. **PUT file-profile(直接写入)**
|
||||
- [ ] 写入 `.profile.json` 成功
|
||||
- [ ] 创建新文件成功
|
||||
- [ ] 更新现有文件成功
|
||||
|
||||
3. **自动迁移**
|
||||
- [ ] 第一次访问自动迁移
|
||||
- [ ] 数据完整无损
|
||||
- [ ] 不影响用户体验
|
||||
|
||||
### 集成测试
|
||||
|
||||
1. **前端集成**
|
||||
- [ ] Studio 正常加载配置
|
||||
- [ ] 保存配置成功
|
||||
- [ ] UI 正确显示
|
||||
- [ ] 无需修改前端代码
|
||||
|
||||
2. **跨设备同步**
|
||||
- [ ] 文件同步后配置一致
|
||||
- [ ] 无需同步数据库
|
||||
- [ ] 新设备直接可用
|
||||
|
||||
---
|
||||
|
||||
## 后续工作
|
||||
|
||||
### Phase 1(已完成)
|
||||
|
||||
- ✅ 修改 API 实现透明管理
|
||||
- ✅ 自动迁移机制
|
||||
- ✅ 向后兼容
|
||||
- ✅ 提交代码
|
||||
|
||||
### Phase 2(待部署)
|
||||
|
||||
- ⏳ 部署新版本
|
||||
- ⏳ 验证自动迁移
|
||||
- ⏳ 功能测试
|
||||
|
||||
### Phase 3(计划中)
|
||||
|
||||
- [ ] 逐步废弃数据库 `face_filter` 字段
|
||||
- [ ] 更新文档
|
||||
- [ ] 性能优化
|
||||
|
||||
---
|
||||
|
||||
## 相关文档
|
||||
|
||||
- `/Users/accusys/momentry_core/.opencode/plans/persistence_design/` - 设计文档
|
||||
- `/Users/accusys/momentry_studio/docs/FACE_FILTER_SETTINGS_MIGRATION_GUIDE.md` - 迁移指南
|
||||
- `/Users/accusys/momentry_studio/docs/FACE_FILTER_TYPES_FIX_REQUIRED.md` - TypeScript 修正
|
||||
|
||||
---
|
||||
|
||||
**Git Commit**:
|
||||
- Rust: `86c776ce` - FaceFilterSettings 数据结构
|
||||
- Rust: `3658c288` - 文件存储架构(透明管理)
|
||||
|
||||
**最后更新**: 2026-10-09
|
||||
**关键特性**: 透明管理、自动迁移、用户无感知
|
||||
@@ -0,0 +1,341 @@
|
||||
---
|
||||
title: Face Tracking Pipeline Structure
|
||||
version: 1.0
|
||||
date: 2026-07-22
|
||||
author: OpenCode
|
||||
status: Active
|
||||
---
|
||||
|
||||
# Face Tracking Pipeline — Structure Design
|
||||
|
||||
## Overview
|
||||
|
||||
```
|
||||
Video
|
||||
│
|
||||
▼
|
||||
┌──────────────────────────────┐
|
||||
│ Stage 1: Face Detection │ face_processor.py
|
||||
│ swift_face (Apple Vision) │ → {uuid}.face.json
|
||||
│ CoreML FaceNet embedding │ → Qdrant _faces (initial)
|
||||
└──────────────────────────────┘
|
||||
│
|
||||
▼
|
||||
┌──────────────────────────────┐
|
||||
│ Stage 2: Face Tracking │ store_traced_faces.py
|
||||
│ face_tracker.py (IoU) │ → {uuid}.face_traced.json
|
||||
│ trace_id assignment │ → Qdrant _faces (trace_id update)
|
||||
└──────────────────────────────┘
|
||||
│
|
||||
▼
|
||||
┌──────────────────────────────┐
|
||||
│ Stage 3: Trace Profile │ backfill_trace_profiles.py
|
||||
│ Qdrant _faces 分組 │ → output/{uuid}/trace_{N}/
|
||||
│ key_frame + key_face │ trace_profile.json
|
||||
└──────────────────────────────┘
|
||||
│
|
||||
▼
|
||||
┌──────────────────────────────┐
|
||||
│ Stage 4: TKG Nodes │ tkg.rs
|
||||
│ Qdrant _faces → trace_id │ → tkg_nodes (face_track, etc.)
|
||||
└──────────────────────────────┘
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Stage 1: Face Detection
|
||||
|
||||
**Script**: `scripts/face_processor.py`
|
||||
|
||||
### Flow
|
||||
|
||||
1. `swift_face` (Swift/Apple Vision/ANE) → bbox detection per sampled frame
|
||||
2. `cv2` opens video, crops face from bbox
|
||||
3. CoreML FaceNet → 512D embedding per face
|
||||
4. Output: `{uuid}.face.json`
|
||||
5. Push embeddings to Qdrant `_faces` collection
|
||||
|
||||
### Output Format: `{uuid}.face.json`
|
||||
|
||||
```json
|
||||
{
|
||||
"status": "has_faces",
|
||||
"frame_count": 563,
|
||||
"fps": 29.97,
|
||||
"total_faces": 1200,
|
||||
"frames": [
|
||||
{
|
||||
"frame": 743,
|
||||
"timestamp": 24.78,
|
||||
"faces": [
|
||||
{
|
||||
"x": 892, // int, pixel
|
||||
"y": 313, // int, pixel
|
||||
"width": 78, // int, pixel
|
||||
"height": 78, // int, pixel
|
||||
"confidence": 0.733,
|
||||
"pose_angle": { "angle": "frontal", "roll": 0.77, "yaw": -1.24, "pitch": 0.23 },
|
||||
"landmarks": { "right_eye": [...], "nose": [...], "left_eye": [...] },
|
||||
"lips": { "inner_lips": [...], "outer_lips": [...] }
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
**Key points**:
|
||||
- bbox is **pixel integer** from Apple Vision, never modified
|
||||
- face.json uses **list format** (not dict)
|
||||
- Sampling at ~8Hz (`sample_interval = round(fps / 8)`)
|
||||
|
||||
### Qdrant Initial Push
|
||||
|
||||
`push_face_embeddings_batch()` in `qdrant_faces.py`:
|
||||
|
||||
```python
|
||||
payload = {
|
||||
"file_uuid": file_uuid,
|
||||
"frame": frame_num,
|
||||
"trace_id": face_idx, # ⚠️ frame-internal index (0, 1, 2...), NOT tracking trace_id
|
||||
"bbox": {"x": x, "y": y, "width": w, "height": h}, # int pixel
|
||||
"confidence": 0.5,
|
||||
"identity_id": None,
|
||||
"identity_uuid": None,
|
||||
"stranger_id": None,
|
||||
}
|
||||
```
|
||||
|
||||
**Important**: `trace_id` at this stage is `face_idx` (index within the frame), used only as a temporary placeholder. It gets overwritten in Stage 2.
|
||||
|
||||
---
|
||||
|
||||
## Stage 2: Face Tracking
|
||||
|
||||
**Scripts**: `scripts/store_traced_faces.py` → `scripts/utils/face_tracker.py`
|
||||
|
||||
### Trigger
|
||||
|
||||
`job_worker.rs` P2 trigger (line ~1877): after face + asrx processors complete.
|
||||
|
||||
```rust
|
||||
tokio::spawn(async move {
|
||||
executor.run("store_traced_faces.py", &["--file-uuid", &uuid], ...)
|
||||
});
|
||||
```
|
||||
|
||||
Skip if `{uuid}.face_traced.json` already exists.
|
||||
|
||||
### Flow
|
||||
|
||||
1. `store_traced_faces.py` reads `{uuid}.face.json`
|
||||
2. Converts face.json from list to dict format (frame_num_str → {frame_number, time_seconds, faces})
|
||||
3. Loads cut boundaries from `{uuid}.cut.json` (if exists)
|
||||
4. Calls `face_tracker.track_faces(face_data, use_embedding=False, cut_boundaries=...)`
|
||||
5. Writes `{uuid}.face_traced.json`
|
||||
6. Calls `update_trace_ids(file_uuid, trace_mapping)` to update Qdrant
|
||||
|
||||
### `face_tracker.py:track_faces()`
|
||||
|
||||
**Algorithm** (IoU-only, no embedding):
|
||||
|
||||
```
|
||||
For each frame (sorted):
|
||||
For each face in current frame:
|
||||
Match against previous frame faces:
|
||||
- Calculate IoU
|
||||
- Calculate bbox center distance
|
||||
- Reject if area ratio > 5x (different zoom level)
|
||||
- Reject if at-edge → not-at-edge transition (person exited)
|
||||
If match found → same trace_id as matched face
|
||||
If no match → new trace_id (next_trace_id++)
|
||||
Scene cut boundary between frames → force all new traces
|
||||
```
|
||||
|
||||
**Matching conditions** (IoU-only mode):
|
||||
- IoU > 0.5 AND IoU > 0.35 + distance < 100px → match
|
||||
- IoU > 0.5 + similarity > 0.65 → match (similarity not used but condition exists)
|
||||
- similarity > 0.85 → match (not used in IoU-only mode)
|
||||
- Scene cut boundary → all new traces
|
||||
|
||||
### Output Format: `{uuid}.face_traced.json`
|
||||
|
||||
Same structure as face.json, but:
|
||||
- Format converted to **dict** (`frames[str(frame_num)]` → face data)
|
||||
- Each face gains `trace_id` field (integer)
|
||||
- Top-level `traces` dict with per-trace statistics
|
||||
- `metadata.tracking_method = "iou_only"`
|
||||
- `metadata.traced_at = ISO timestamp`
|
||||
|
||||
```json
|
||||
{
|
||||
"metadata": {
|
||||
"fps": 29.97,
|
||||
"total_frames": 43977,
|
||||
"tracking_method": "iou_only",
|
||||
"trace_stats": {
|
||||
"total_traces": 107,
|
||||
"active_traces": 107,
|
||||
"long_traces": 95
|
||||
}
|
||||
},
|
||||
"frames": {
|
||||
"743": {
|
||||
"frame_number": 743,
|
||||
"faces": [
|
||||
{ "x": 892, "y": 313, "width": 78, "height": 78, "trace_id": 0, ... }
|
||||
]
|
||||
}
|
||||
},
|
||||
"traces": {
|
||||
"0": {
|
||||
"trace_id": 0,
|
||||
"start_frame": 743,
|
||||
"end_frame": 783,
|
||||
"duration_frames": 41,
|
||||
"total_appearances": 11,
|
||||
"avg_confidence": 0.72
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Qdrant Trace Update
|
||||
|
||||
`update_trace_ids()` in `qdrant_faces.py`:
|
||||
|
||||
1. Scroll all Qdrant `_faces` points for `file_uuid` (with vector + payload)
|
||||
2. For each point, build `bbox_key = f"{bbox.x}_{bbox.y}_{bbox.width}_{bbox.height}"`
|
||||
3. Look up `trace_mapping[frame][bbox_key]` from face_traced.json
|
||||
4. If match found → set `payload["trace_id"] = real_trace_id`
|
||||
5. PUT updated points back to Qdrant
|
||||
|
||||
**Matching key**: `frame` + `bbox_key` (pixel integer string)
|
||||
|
||||
---
|
||||
|
||||
## Stage 3: Trace Profile
|
||||
|
||||
**Script**: `scripts/backfill_trace_profiles.py`
|
||||
|
||||
### Data Source
|
||||
|
||||
Qdrant `_faces` collection (source of truth for trace_id assignments).
|
||||
|
||||
### Flow
|
||||
|
||||
1. Scroll all `_faces` points for each `file_uuid` with `trace_id >= 0`
|
||||
2. Group by `(file_uuid, trace_id)`
|
||||
3. For each group:
|
||||
- `frame_count` = count of points
|
||||
- `start_frame` = min(frame)
|
||||
- `end_frame` = max(frame)
|
||||
- `representative_frame` = frame with max(confidence)
|
||||
- `representative_bbox` = bbox at representative frame
|
||||
4. Extract `key_frame.jpg` via ffmpeg at representative frame
|
||||
5. Crop `key_face.jpg` from key_frame using representative bbox
|
||||
6. Write `output/{uuid}/trace_{N}/trace_profile.json`
|
||||
|
||||
### Output: `output/{uuid}/trace_{N}/trace_profile.json`
|
||||
|
||||
```json
|
||||
{
|
||||
"version": "1.0",
|
||||
"file_uuid": "d8acb03870f0cc9b14e01f14a7bf24d6",
|
||||
"trace_id": 37,
|
||||
"label": "",
|
||||
"frame_count": 38,
|
||||
"start_frame": 1859,
|
||||
"end_frame": 2100,
|
||||
"avg_confidence": 0.754,
|
||||
"key_frame": "key_frame.jpg",
|
||||
"key_face": "key_face.jpg",
|
||||
"status": "pending"
|
||||
}
|
||||
```
|
||||
|
||||
### File Layout
|
||||
|
||||
```
|
||||
output/{uuid}/
|
||||
trace_0/
|
||||
trace_profile.json
|
||||
key_frame.jpg
|
||||
key_face.jpg
|
||||
trace_1/
|
||||
trace_profile.json
|
||||
key_frame.jpg
|
||||
key_face.jpg
|
||||
...
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Stage 4: TKG Node Construction
|
||||
|
||||
**File**: `src/core/processor/tkg.rs`
|
||||
|
||||
Reads trace_id from Qdrant `_faces` payload to build knowledge graph nodes:
|
||||
- `face_track` nodes: one per trace
|
||||
- `gaze_track`, `lip_track`: linked to face_track via frame alignment
|
||||
- `co_occurrence` edges: traces that appear in same frame
|
||||
|
||||
---
|
||||
|
||||
## Qdrant `_faces` Collection Schema
|
||||
|
||||
| Field | Type | Description |
|
||||
|-------|------|-------------|
|
||||
| `file_uuid` | string | Video file identifier |
|
||||
| `frame` | int | Video frame number (absolute, not sampled) |
|
||||
| `trace_id` | int | Face tracking ID (set by Stage 2) |
|
||||
| `bbox` | `{x, y, width, height}` | Pixel integer coordinates |
|
||||
| `confidence` | float | Detection confidence |
|
||||
| `identity_id` | int? | Identity binding (set by identity agent) |
|
||||
| `identity_uuid` | string? | Identity UUID |
|
||||
| `stranger_id` | int? | Stranger classification |
|
||||
|
||||
**Point ID**: `generate_point_id(file_uuid, frame, face_idx)` — deterministic hash.
|
||||
|
||||
---
|
||||
|
||||
## Known Issues
|
||||
|
||||
### bfba056f5021e2404b0870cc0b1fa851
|
||||
|
||||
- **Qdrant**: trace_id = 0,1,2 (face_idx, never updated)
|
||||
- **face_traced.json**: trace_id = 0-8209 (8210 traces, iou_only)
|
||||
- **Root cause**: `face_processor.py` re-ran after `store_traced_faces.py`, pushing fresh embeddings with `trace_id=face_idx`, overwriting the updated trace_ids
|
||||
- **Other 12 files**: all correct
|
||||
|
||||
### `update_trace_ids` bbox matching
|
||||
|
||||
Matching is by exact `frame` + `bbox_key` string (`x_y_width_height`). Since bbox is pixel integer from the same source, values are identical across face_traced.json and Qdrant. Mismatch only occurs when face_processor.py re-runs and generates different detection results.
|
||||
|
||||
---
|
||||
|
||||
## File Inventory (2026-07-22)
|
||||
|
||||
| file_uuid | traces (Qdrant) | traces (face_traced) | status |
|
||||
|-----------|-----------------|----------------------|--------|
|
||||
| 30affad3... | 52 | 53 | ✅ |
|
||||
| 31a6b821... | 31 | 36 | ⚠️ minor mismatch |
|
||||
| 352cf73a... | 16 | 25 | ⚠️ minor mismatch |
|
||||
| 57bd7e43... | 3 | 4 | ✅ |
|
||||
| 5e5f3de8... | 21 | 22 | ✅ |
|
||||
| 84d838f2... | 88 | 89 | ✅ |
|
||||
| 88e72467... | 18 | 19 | ✅ |
|
||||
| 9cbeb112... | 9 | 17 | ⚠️ minor mismatch |
|
||||
| bfba056f... | 15 | 8210 | ❌ face_idx not updated |
|
||||
| c0a9dc37... | 77 | 78 | ✅ |
|
||||
| c36f3568... | 5601 | 5616 | ⚠️ minor mismatch |
|
||||
| d8acb038... | 106 | 107 | ✅ |
|
||||
| fbd82072... | 12 | 13 | ✅ |
|
||||
|
||||
---
|
||||
|
||||
## Version History
|
||||
|
||||
| Version | Date | Changes |
|
||||
|---------|------|---------|
|
||||
| 1.0 | 2026-07-22 | Initial document: face detection → tracking → Qdrant → TKG pipeline structure |
|
||||
@@ -1,198 +1,513 @@
|
||||
---
|
||||
document_type: "design_doc"
|
||||
service: "MOMENTRY_CORE"
|
||||
title: "File Lifecycle — Pre-Processing & Registration"
|
||||
version: "V1.2"
|
||||
date: "2026-05-15"
|
||||
author: "M5"
|
||||
status: "draft"
|
||||
title: File Lifecycle Architecture
|
||||
version: 1.0
|
||||
date: 2026-07-22
|
||||
author: OpenCode
|
||||
status: Active
|
||||
scope: File processing pipeline — stages, verification, rebuild
|
||||
---
|
||||
|
||||
# File Lifecycle — Pre-Processing & Registration
|
||||
# File Lifecycle Architecture V1.0
|
||||
|
||||
| Item | Value |
|
||||
|------|-------|
|
||||
| Scope | All managed file types (video, image, document, spreadsheet, presentation) |
|
||||
| Status | Draft |
|
||||
| Applies to | Pre-process API (explicit) + Register API |
|
||||
| Key concept | Two-phase flow: birth certificate (`.pre.json`) → civil registration (DB INSERT) |
|
||||
| Field | Value |
|
||||
|-------|-------|
|
||||
| Scope | Complete file processing lifecycle |
|
||||
| Status | Active |
|
||||
| Applies to | Pipeline stages, progress tracking, verification, rebuild |
|
||||
| Related | `FILE_PROFILE_V1.0.md`, `FACE_TRACKING_PIPELINE_V1.0.md` |
|
||||
|
||||
> **Applicable to all managed file types**: video, image, document (pdf, docx, pages, key, numbers), spreadsheet, presentation, and any other file registered in the system. The pre-processor registers any file type found by the watcher. ffprobe is used when applicable; files that ffprobe cannot parse receive minimal filesystem metadata as a fallback.
|
||||
---
|
||||
|
||||
## Metaphor
|
||||
## 1. Overview
|
||||
|
||||
Every registered video file passes through a deterministic pipeline of stages.
|
||||
Each stage must produce a `.json` (or `.jpg`) artifact on disk.
|
||||
This enables:
|
||||
- **Verification**: Check pipeline completeness by inspecting artifact existence
|
||||
- **Rebuild**: Re-run any stage from its input artifacts without re-running the entire pipeline
|
||||
- **Progress tracking**: Two-layer display (high-level summary + expandable sub-stages)
|
||||
|
||||
### Design Principles
|
||||
|
||||
1. **Every stage has a `.json` output** — no silent DB-only writes
|
||||
2. **Any stage can be rebuilt** from its input artifacts
|
||||
3. **Frontend reads stages from API** — not hardcoded
|
||||
4. **Verification is disk-first** — check `.json` exists, then validate content, then check DB/Qdrant consistency
|
||||
5. **Processors are not modified** — this document defines tracking/verification/rebuild only
|
||||
|
||||
---
|
||||
|
||||
## 2. Stage Architecture
|
||||
|
||||
### 2.1 High-Level Stages (6)
|
||||
|
||||
| # | Stage | Weight | Sub-Stages | Description |
|
||||
|---|-------|--------|------------|-------------|
|
||||
| S0 | Register | 5% | 4 | File metadata + audio track + key frame extraction |
|
||||
| S1 | Processors | 40% | 8 | Individual processor execution |
|
||||
| S2 | Post-Process | 20% | 4 | Face trace, Rule1, Vectorize, Identity Agent |
|
||||
| S3 | TKG Build | 20% | 2 | Temporal Knowledge Graph nodes + edges |
|
||||
| S4 | Rule2 | 10% | 1 | Relationship chunk ingestion |
|
||||
| S5 | Complete | 5% | 1 | Final status update |
|
||||
|
||||
### 2.2 Sub-Stages (15)
|
||||
|
||||
```
|
||||
SHA256 = DNA or fingerprint (immutable biometric identity)
|
||||
file mtime = birth moment (preserved by rsync across systems)
|
||||
birthday (file_uuid anchor) = mtime timestamp
|
||||
.pre.json = birth certificate
|
||||
POST /api/v1/files/register = civil registration
|
||||
status = registered = citizenship completed
|
||||
S0: Register (5%)
|
||||
├─ 0a: probe → probe.json
|
||||
├─ 0b: audio_track → DB: audio_track column (no disk artifact)
|
||||
├─ 0c: profile → profile.json
|
||||
└─ 0d: key_frame → key_frame.jpg
|
||||
|
||||
S1: Processors (40%)
|
||||
├─ 1a: cut → cut.json
|
||||
├─ 1b: asr → asr.json
|
||||
├─ 1c: asrx → asrx.json (depends: 1a + 1b)
|
||||
├─ 1d: ocr → ocr.json
|
||||
├─ 1e: face → face.json (+ Qdrant _faces initial)
|
||||
├─ 1f: pose → pose.json (depends: 1e)
|
||||
├─ 1g: appearance → appearance.json (depends: 1f)
|
||||
└─ 1h: face_dedup → face_cluster.json (depends: 1e) [OPTIONAL + MANUAL]
|
||||
|
||||
S2: Post-Process (20%)
|
||||
├─ 2a: face_trace → face_traced.json (+ Qdrant trace_id update)
|
||||
├─ 2b: rule1 → rule1.json (ASRX → sentence chunks)
|
||||
├─ 2c: vectorize → vectorize.json (embeddings → PG + Qdrant)
|
||||
└─ 2d: identity_agent → identity_agent.json (optional)
|
||||
|
||||
S3: TKG Build (20%)
|
||||
├─ 3a: tkg_nodes → tkg_nodes.json
|
||||
└─ 3b: tkg_edges → tkg_edges.json
|
||||
|
||||
S4: Rule2 (10%)
|
||||
└─ 4a: rule2 → rule2.json (relationship chunks)
|
||||
|
||||
S5: Complete (5%)
|
||||
└─ 5a: complete → status = "completed"
|
||||
```
|
||||
|
||||
## Two-Phase Flow
|
||||
|
||||
A file enters the system in two distinct phases:
|
||||
|
||||
| Phase | Action | Analogy | Automatic? | Status |
|
||||
|-------|--------|---------|:----------:|:------:|
|
||||
| **Birth** | Pre-process: SHA256 + probe + file_uuid | 出生 + 醫院開出生證明 | ✅ Watcher | `unregistered` |
|
||||
| **Citizenship** | Register: INSERT into DB | 戶政事務所登記 | ❌ User API | `registered` |
|
||||
|
||||
## Phase 1: Pre-Processing (Birth)
|
||||
|
||||
### Trigger
|
||||
|
||||
Pre-processing is triggered explicitly via the register API or a dedicated pre-process endpoint. It is NOT automatic — the watcher only detects new files without modifying them.
|
||||
|
||||
### Computation Steps
|
||||
### 2.3 Dependency Graph
|
||||
|
||||
```
|
||||
1. fs::metadata(path).modified()
|
||||
→ birthday = file modification time (mtime, RFC 3339; preserved by rsync -a across systems)
|
||||
|
||||
2. SHA256(full file, streaming 64KB chunks)
|
||||
→ content_hash = 512-bit hex string (file DNA / fingerprint)
|
||||
|
||||
3. ffprobe (or minimal fs metadata fallback for non-video)
|
||||
→ probe_json
|
||||
|
||||
4. compute_birth_uuid(mac, birthday, canonical_path, filename)
|
||||
→ file_uuid = SHA256(mac | birthday | path | filename)[0:32]
|
||||
|
||||
5. Write {OUTPUT_DIR}/{file_uuid}.pre.json
|
||||
S0 (Register)
|
||||
└─→ S1 (Processors)
|
||||
├─ 1a (CUT) ─────┐
|
||||
├─ 1b (ASR) ─────┤
|
||||
│ └─→ 1c (ASRX) ──→ 2b (Rule1)
|
||||
├─ 1d (OCR) ──────────────────────→ 3a (TKG Nodes)
|
||||
├─ 1e (Face) ──┬─→ 1f (Pose) ──→ 1g (Appearance) ──→ 3a
|
||||
│ ├─→ 1h (FaceDedup) [manual]
|
||||
│ └─→ 2a (Face Trace) ──→ 3a
|
||||
└─────────────────────────────────────→ 3a
|
||||
│
|
||||
S2: 2c (Vectorize) ←── DB chunks │
|
||||
S2: 2d (IdentityAgent) ←── face_clusters │
|
||||
↓
|
||||
3b (TKG Edges)
|
||||
│
|
||||
↓
|
||||
4a (Rule2)
|
||||
│
|
||||
↓
|
||||
5a (Complete)
|
||||
```
|
||||
|
||||
### Output: `.pre.json` Schema
|
||||
---
|
||||
|
||||
Stored alongside other processor outputs:
|
||||
## 3. I/O Specification
|
||||
|
||||
### 3.1 Register (S0)
|
||||
|
||||
| Sub-Stage | Input | Output Artifact | DB Tables | Qdrant |
|
||||
|-----------|-------|----------------|-----------|--------|
|
||||
| 0a: probe | video file on disk | `{uuid}.probe.json` | — | — |
|
||||
| 0b: audio_track | probe.json, video file | DB column only | videos.audio_track | — |
|
||||
| 0c: profile | probe.json | `{uuid}.profile.json` | videos (INSERT/UPDATE) | — |
|
||||
| 0d: key_frame | probe.json | `{uuid}.key_frame.jpg` | — | — |
|
||||
|
||||
**Audio Track Classification** (S0b):
|
||||
|
||||
| Classification | Condition | ASR Behavior |
|
||||
|----------------|-----------|--------------|
|
||||
| `no_audio` | No audio track in video | Skip ASR, output `{"status": "no_audio"}` |
|
||||
| `silent_audio` | Audio track exists but no speech detected | Skip ASR, output `{"status": "silent_audio"}` |
|
||||
| `music_only` | Audio with no speech (music/sound effects) | Skip ASR, output `{"status": "music_only"}` |
|
||||
| `speech_only` | Audio with speech only (≥30% speech ratio) | Run ASR normally |
|
||||
| `speech_with_music` | Speech with background music (<30% speech ratio) | Run ASR normally |
|
||||
|
||||
### 3.2 Processors (S1)
|
||||
|
||||
| Sub-Stage | Input Artifacts | Output Artifact | DB Tables | Qdrant |
|
||||
|-----------|----------------|----------------|-----------|--------|
|
||||
| 1a: cut | probe.json | `{uuid}.cut.json` + `{uuid}_scene_{n}.jpg` | processor_results | — |
|
||||
| 1b: asr | video file | `{uuid}.asr.json` | processor_results | — |
|
||||
| 1c: asrx | cut.json, asr.json | `{uuid}.asrx.json` | speaker_detections | — |
|
||||
| 1d: ocr | video file | `{uuid}.ocr.json` | processor_results | — |
|
||||
| 1e: face | video file | `{uuid}.face.json` | processor_results | `_faces` (initial push) |
|
||||
| 1f: pose | face.json, video file | `{uuid}.pose.json` | processor_results | — |
|
||||
| 1g: appearance | pose.json, video file | `{uuid}.appearance.json` | processor_results | — |
|
||||
| 1h: face_dedup | face.json | `{uuid}.face_cluster.json` | face_clusters | — |
|
||||
|
||||
**Note**: 1h (Face Deduplication) is currently `optional + manual`. It will be integrated into the automated pipeline after testing is complete.
|
||||
|
||||
**Scene Key Frames** (1a post-process):
|
||||
|
||||
After CUT completes, extracts the middle frame from each scene as `{uuid}_scene_{n}.jpg` for VLM analysis:
|
||||
|
||||
| Output | Purpose |
|
||||
|---------|---------|
|
||||
| `{uuid}_scene_1.jpg` | Representative frame from scene 1 |
|
||||
| `{uuid}_scene_2.jpg` | Representative frame from scene 2 |
|
||||
| ... | ... |
|
||||
|
||||
These key frames enable:
|
||||
- VLM scene understanding (caption, objects, actions)
|
||||
- Scene-level search and filtering
|
||||
- Thumbnail generation for scene navigation
|
||||
|
||||
### 3.3 Post-Process (S2)
|
||||
|
||||
| Sub-Stage | Input Artifacts | Output Artifact | DB Tables | Qdrant |
|
||||
|-----------|----------------|----------------|-----------|--------|
|
||||
| 2a: face_trace | face.json | `{uuid}.face_traced.json` | — | `_faces` (trace_id update) |
|
||||
| 2b: rule1 | asrx.json | `{uuid}.rule1.json` | chunk, pre_chunks | — |
|
||||
| 2c: vectorize | chunk (DB) | `{uuid}.vectorize.json` | chunk_vectors | main collection |
|
||||
| 2d: identity_agent | face_cluster.json | `{uuid}.identity_agent.json` | file_identities | — |
|
||||
|
||||
### 3.4 TKG Build (S3)
|
||||
|
||||
| Sub-Stage | Input Artifacts | Output Artifact | DB Tables | Qdrant |
|
||||
|-----------|----------------|----------------|-----------|--------|
|
||||
| 3a: tkg_nodes | All processor JSONs, trace profiles | `{uuid}.tkg_nodes.json` | tkg_nodes | — |
|
||||
| 3b: tkg_edges | tkg_nodes.json, asrx.json | `{uuid}.tkg_edges.json` | tkg_edges | — |
|
||||
|
||||
### 3.5 Rule2 (S4)
|
||||
|
||||
| Sub-Stage | Input Artifacts | Output Artifact | DB Tables | Qdrant |
|
||||
|-----------|----------------|----------------|-----------|--------|
|
||||
| 4a: rule2 | tkg_edges.json, chunk (DB) | `{uuid}.rule2.json` | chunk (relationship type) | main collection |
|
||||
|
||||
### 3.6 Complete (S5)
|
||||
|
||||
| Sub-Stage | Input | Output | DB Tables |
|
||||
|-----------|-------|--------|-----------|
|
||||
| 5a: complete | All above stages verified | status = "completed" | videos.status |
|
||||
|
||||
---
|
||||
|
||||
## 4. Verification
|
||||
|
||||
### 4.1 Verification Levels
|
||||
|
||||
Each sub-stage has three verification levels:
|
||||
|
||||
| Level | Check | Description |
|
||||
|-------|-------|-------------|
|
||||
| L1: Artifact exists | `{uuid}.{stage}.json` on disk | Required for all stages |
|
||||
| L2: Content valid | JSON parseable + non-empty array/object | Ensures output is usable |
|
||||
| L3: DB/Qdrant consistent | Row count > 0 or point count > 0 | Ensures data was written |
|
||||
|
||||
### 4.2 Verification Matrix
|
||||
|
||||
| Sub-Stage | L1 (exists) | L2 (valid) | L3 (DB/Qdrant) |
|
||||
|-----------|:-----------:|:----------:|:--------------:|
|
||||
| 0a: probe | `.probe.json` | non-empty | — |
|
||||
| 0b: profile | `.profile.json` | has file_uuid | videos row exists |
|
||||
| 0c: key_frame | `.key_frame.jpg` | file size > 0 | — |
|
||||
| 1a: cut | `.cut.json` | non-empty | processor_results > 0 |
|
||||
| 1b: asr | `.asr.json` | non-empty | processor_results > 0 |
|
||||
| 1c: asrx | `.asrx.json` | non-empty | speaker_detections > 0 |
|
||||
| 1d: ocr | `.ocr.json` | non-empty | processor_results > 0 |
|
||||
| 1e: face | `.face.json` | non-empty | Qdrant `_faces` > 0 |
|
||||
| 1f: pose | `.pose.json` | non-empty | processor_results > 0 |
|
||||
| 1g: appearance | `.appearance.json` | non-empty | processor_results > 0 |
|
||||
| 1h: face_dedup | `.face_cluster.json` | non-empty | face_clusters > 0 |
|
||||
| 2a: face_trace | `.face_traced.json` | non-empty | Qdrant `_faces` trace_id set |
|
||||
| 2b: rule1 | `.rule1.json` | non-empty | chunk (sentence) > 0 |
|
||||
| 2c: vectorize | `.vectorize.json` | non-empty | chunk_vectors > 0 |
|
||||
| 2d: identity_agent | `.identity_agent.json` | non-empty | file_identities > 0 |
|
||||
| 3a: tkg_nodes | `.tkg_nodes.json` | non-empty | tkg_nodes > 0 |
|
||||
| 3b: tkg_edges | `.tkg_edges.json` | non-empty | tkg_edges > 0 |
|
||||
| 4a: rule2 | `.rule2.json` | non-empty | chunk (relationship) > 0 |
|
||||
|
||||
### 4.3 Status Values
|
||||
|
||||
| Status | Meaning |
|
||||
|--------|---------|
|
||||
| `pending` | Not yet started |
|
||||
| `running` | Currently executing |
|
||||
| `completed` | L1 + L2 + L3 all pass |
|
||||
| `failed` | L1 passes but L2 or L3 fails |
|
||||
| `missing` | L1 fails (artifact not on disk) |
|
||||
| `skipped` | Optional stage not run |
|
||||
|
||||
---
|
||||
|
||||
## 5. Rebuild
|
||||
|
||||
### 5.1 Rebuild Principle
|
||||
|
||||
Any sub-stage can be rebuilt independently:
|
||||
1. Read input artifacts (from disk or DB)
|
||||
2. Re-run the stage logic (processor or post-processor)
|
||||
3. Write output artifact + update DB/Qdrant
|
||||
|
||||
### 5.2 Rebuild Dependency
|
||||
|
||||
To rebuild stage N, all its dependency stages must be `completed`:
|
||||
|
||||
| Stage | Required Dependencies |
|
||||
|-------|----------------------|
|
||||
| 0a-0c | video file on disk |
|
||||
| 1a: cut | 0a (probe) |
|
||||
| 1b: asr | video file |
|
||||
| 1c: asrx | 1a (cut) + 1b (asr) |
|
||||
| 1d: ocr | video file |
|
||||
| 1e: face | video file |
|
||||
| 1f: pose | 1e (face) |
|
||||
| 1g: appearance | 1f (pose) |
|
||||
| 1h: face_dedup | 1e (face) |
|
||||
| 2a: face_trace | 1e (face) |
|
||||
| 2b: rule1 | 1c (asrx) |
|
||||
| 2c: vectorize | 2b (rule1) — chunks in DB |
|
||||
| 2d: identity_agent | 1h (face_dedup) — optional |
|
||||
| 3a: tkg_nodes | 1e (face), 2a (face_trace), 1c (asrx), 1d (ocr), 1g (appearance) |
|
||||
| 3b: tkg_edges | 3a (tkg_nodes) + 1c (asrx) |
|
||||
| 4a: rule2 | 3b (tkg_edges) + 2b (rule1) — chunks in DB |
|
||||
| 5a: complete | All required stages completed |
|
||||
|
||||
### 5.3 Rebuild API
|
||||
|
||||
```
|
||||
{OUTPUT_DIR}/
|
||||
{file_uuid}.probe.json ← ffprobe
|
||||
{file_uuid}.face.json ← face detection
|
||||
{file_uuid}.pre.json ← pre-processor (NEW)
|
||||
POST /api/v1/file/:file_uuid/rebuild/:stage
|
||||
```
|
||||
|
||||
- Validates dependencies are met
|
||||
- Re-runs the stage
|
||||
- Returns updated verification status
|
||||
|
||||
### 5.4 Rebuild via CLI
|
||||
|
||||
```bash
|
||||
# Check all stages
|
||||
python3 scripts/lifecycle_check.py --file-uuid <UUID>
|
||||
|
||||
# Rebuild specific stage
|
||||
python3 scripts/lifecycle_check.py --file-uuid <UUID> --rebuild 1c
|
||||
|
||||
# Rebuild from first missing stage
|
||||
python3 scripts/lifecycle_check.py --file-uuid <UUID> --rebuild auto
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 6. Frontend Display
|
||||
|
||||
### 6.1 Two-Layer Architecture
|
||||
|
||||
**Layer 1: High-Level Summary** (default view)
|
||||
|
||||
```
|
||||
┌─────────────────────────────────────────────────────────┐
|
||||
│ ▶ S0: Register ████████████ 3/3 completed │
|
||||
│ ▶ S1: Processors ████████░░░░ 6/8 partial │
|
||||
│ ▶ S2: Post-Process ██░░░░░░░░░░ 1/4 running │
|
||||
│ ▶ S3: TKG Build ░░░░░░░░░░░░ 0/2 pending │
|
||||
│ ▶ S4: Rule2 ░░░░░░░░░░░░ 0/1 pending │
|
||||
│ ▶ S5: Complete ░░░░░░░░░░░░ 0/1 pending │
|
||||
└─────────────────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
**Layer 2: Expandable Sub-Stages** (click to expand)
|
||||
|
||||
```
|
||||
┌─────────────────────────────────────────────────────────┐
|
||||
│ ▼ S1: Processors ████████░░░░ 6/8 partial │
|
||||
│ ├─ 1a: CUT ✅ completed │
|
||||
│ ├─ 1b: ASR ✅ completed │
|
||||
│ ├─ 1c: ASRX ✅ completed │
|
||||
│ ├─ 1d: OCR ✅ completed │
|
||||
│ ├─ 1e: Face ✅ completed │
|
||||
│ ├─ 1f: Pose ✅ completed │
|
||||
│ ├─ 1g: Appearance ❌ missing │
|
||||
│ └─ 1h: Face Dedup ⏭ skipped (manual) │
|
||||
└─────────────────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
### 6.2 Sub-Stage Display Names
|
||||
|
||||
| Code Name | Display Name |
|
||||
|-----------|-------------|
|
||||
| probe | Probe (ffprobe) |
|
||||
| profile | File Profile |
|
||||
| key_frame | Key Frame |
|
||||
| cut | Scene Detection (CUT) |
|
||||
| asr | Speech Recognition (ASR) |
|
||||
| asrx | Speaker Diarization (ASRX) |
|
||||
| ocr | Text Recognition (OCR) |
|
||||
| face | Face Detection |
|
||||
| pose | Pose Estimation |
|
||||
| appearance | Appearance Features |
|
||||
| face_dedup | Face Deduplication |
|
||||
| face_trace | Face Tracking |
|
||||
| rule1 | Rule1 Ingestion |
|
||||
| vectorize | Vector Embedding |
|
||||
| identity_agent | Identity Agent |
|
||||
| tkg_nodes | TKG Nodes |
|
||||
| tkg_edges | TKG Edges |
|
||||
| rule2 | Rule2 Ingestion |
|
||||
| complete | Complete |
|
||||
|
||||
### 6.3 API Contract
|
||||
|
||||
The frontend fetches stage data from:
|
||||
|
||||
```
|
||||
GET /api/v1/stats/pipeline/:file_uuid
|
||||
```
|
||||
|
||||
Response:
|
||||
```json
|
||||
{
|
||||
"file_name": "charade.mp4",
|
||||
"file_path": "/data/demo/charade.mp4",
|
||||
"canonical_path": "/private/data/demo/charade.mp4",
|
||||
"content_hash": "a1b2c3d4e5f6...",
|
||||
"probe_json": {
|
||||
"format": { "duration": "6879.3", "size": "2147483648" },
|
||||
"streams": [...]
|
||||
},
|
||||
"birthday": "2026-05-15T02:15:00Z",
|
||||
"file_uuid": "aeed71342a899fe4b4c57b7d41bcb692",
|
||||
"file_size": 2147483648,
|
||||
"file_type": "video | image | document | audio",
|
||||
"pre_processed_at": "2026-05-15T02:15:05Z"
|
||||
"file_uuid": "abc123",
|
||||
"overall_progress": 0.45,
|
||||
"stages": [
|
||||
{
|
||||
"name": "register",
|
||||
"weight": 0.05,
|
||||
"progress": 1.0,
|
||||
"status": "completed",
|
||||
"detail": "3/3 sub-stages",
|
||||
"sub_stages": [
|
||||
{"name": "probe", "status": "completed", "artifact": "probe.json"},
|
||||
{"name": "profile", "status": "completed", "artifact": "profile.json"},
|
||||
{"name": "key_frame", "status": "completed", "artifact": "key_frame.jpg"}
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "processors",
|
||||
"weight": 0.40,
|
||||
"progress": 0.75,
|
||||
"status": "partial",
|
||||
"detail": "6/8 sub-stages",
|
||||
"sub_stages": [
|
||||
{"name": "cut", "status": "completed", "artifact": "cut.json"},
|
||||
{"name": "asr", "status": "completed", "artifact": "asr.json"},
|
||||
{"name": "asrx", "status": "completed", "artifact": "asrx.json"},
|
||||
{"name": "ocr", "status": "completed", "artifact": "ocr.json"},
|
||||
{"name": "face", "status": "completed", "artifact": "face.json"},
|
||||
{"name": "pose", "status": "completed", "artifact": "pose.json"},
|
||||
{"name": "appearance", "status": "missing", "artifact": "appearance.json"},
|
||||
{"name": "face_dedup", "status": "skipped", "artifact": "face_cluster.json"}
|
||||
]
|
||||
}
|
||||
],
|
||||
"updated_at": "2026-07-22T18:00:00Z"
|
||||
}
|
||||
```
|
||||
|
||||
### Key Design: file_uuid = f(mac, birthday, path, filename)
|
||||
---
|
||||
|
||||
The `birthday` is `file modification time` (mtime) — obtained from `fs::metadata().modified()`. Using mtime instead of birthtime ensures file_uuid stability when files are transferred between systems via rsync (which preserves mtime but not birthtime on macOS).
|
||||
## 7. Weight Distribution
|
||||
|
||||
### 7.1 High-Level Stage Weights
|
||||
|
||||
| Stage | Weight | Rationale |
|
||||
|-------|--------|-----------|
|
||||
| S0: Register | 5% | Fast, prerequisite for everything |
|
||||
| S1: Processors | 40% | Most time-consuming, GPU-bound |
|
||||
| S2: Post-Process | 20% | Face trace + Rule1 + Vectorize |
|
||||
| S3: TKG Build | 20% | Node + edge construction |
|
||||
| S4: Rule2 | 10% | Relationship chunk creation |
|
||||
| S5: Complete | 5% | Final status update |
|
||||
|
||||
### 7.2 Processor Sub-Weights (within S1 = 40%)
|
||||
|
||||
| Processor | Sub-Weight | Rationale |
|
||||
|-----------|-----------|-----------|
|
||||
| CUT | 5% | Scene detection, ~10s |
|
||||
| ASR | 15% | whisper-small, ~2min/10min video |
|
||||
| ASRX | 20% | Speaker diarization, ~3min |
|
||||
| OCR | 10% | PaddleOCR, ~1min |
|
||||
| Face | 15% | CoreML FaceNet, ~1min |
|
||||
| Pose | 10% | mediapipe, ~1min |
|
||||
| Appearance | 5% | Feature extraction, ~30s |
|
||||
| Face Dedup | 0% | Manual (not in automated pipeline) |
|
||||
|
||||
---
|
||||
|
||||
## 8. Artifact Naming Convention
|
||||
|
||||
All artifacts live in the output directory (`MOMENTRY_OUTPUT_DIR`):
|
||||
|
||||
```
|
||||
birthday = 2026-05-15T02:15:00Z ← file birth time, never changes
|
||||
↓
|
||||
file_uuid = SHA256(mac | birthday | path | filename)
|
||||
↓
|
||||
Same file: same path + filename → same file_uuid, regardless of registration count
|
||||
Different files: different content_hash → different file_uuid (even if same name)
|
||||
{output_dir}/
|
||||
├─ {uuid}.probe.json # S0: ffprobe metadata
|
||||
├─ {uuid}.profile.json # S0: FileProfile
|
||||
├─ {uuid}.key_frame.jpg # S0: extracted key frame
|
||||
├─ {uuid}.cut.json # S1: scene boundaries
|
||||
├─ {uuid}.asr.json # S1: speech transcription
|
||||
├─ {uuid}.asrx.json # S1: speaker diarization
|
||||
├─ {uuid}.ocr.json # S1: text detections
|
||||
├─ {uuid}.face.json # S1: face detections + embeddings
|
||||
├─ {uuid}.face_cluster.json # S1: face clustering (optional)
|
||||
├─ {uuid}.pose.json # S1: pose estimations
|
||||
├─ {uuid}.appearance.json # S1: appearance features
|
||||
├─ {uuid}.face_traced.json # S2: face tracking with trace_id
|
||||
├─ {uuid}.rule1.json # S2: sentence chunks
|
||||
├─ {uuid}.vectorize.json # S2: embedding stats
|
||||
├─ {uuid}.identity_agent.json # S2: identity matching (optional)
|
||||
├─ {uuid}.tkg_nodes.json # S3: TKG node dump
|
||||
├─ {uuid}.tkg_edges.json # S3: TKG edge dump
|
||||
├─ {uuid}.rule2.json # S4: relationship chunks
|
||||
└─ {uuid}/ # Trace profiles directory
|
||||
├─ trace_0/
|
||||
│ ├─ trace_profile.json
|
||||
│ ├─ key_frame.jpg
|
||||
│ └─ key_face.jpg
|
||||
├─ trace_1/
|
||||
│ └─ ...
|
||||
└─ trace_N/
|
||||
```
|
||||
|
||||
## Phase 2: Registration (Citizenship)
|
||||
---
|
||||
|
||||
### POST /api/v1/files/register
|
||||
## 9. Current State Audit (Gamma 8)
|
||||
|
||||
```bash
|
||||
curl -X POST http://localhost:3002/api/v1/files/register \
|
||||
-H "X-API-Key: ..." \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{"file_path":"/data/demo/charade.mp4"}'
|
||||
```
|
||||
File: `d3f9ae8e471a1fc4d47022c66091b920` (Gamma 8-Director Chih-Lin Yang)
|
||||
|
||||
### Flow
|
||||
| Sub-Stage | Artifact | Status |
|
||||
|-----------|----------|--------|
|
||||
| 0a: probe | probe.json | ✅ exists |
|
||||
| 0b: profile | profile.json | ❌ missing |
|
||||
| 0c: key_frame | key_frame.jpg | ❌ missing |
|
||||
| 1a: cut | cut.json | ✅ exists |
|
||||
| 1b: asr | asr.json | ✅ exists |
|
||||
| 1c: asrx | asrx.json | ✅ exists |
|
||||
| 1d: ocr | ocr.json | ✅ exists |
|
||||
| 1e: face | face.json | ✅ exists |
|
||||
| 1f: pose | pose.json | ✅ exists |
|
||||
| 1g: appearance | appearance.json | ❌ missing |
|
||||
| 1h: face_dedup | face_cluster.json | ⏭ skipped (manual) |
|
||||
| 2a: face_trace | face_traced.json | ✅ exists |
|
||||
| 2b: rule1 | rule1.json | ❌ missing |
|
||||
| 2c: vectorize | vectorize.json | ❌ missing |
|
||||
| 2d: identity_agent | identity_agent.json | ❌ missing |
|
||||
| 3a: tkg_nodes | tkg_nodes.json | ❌ missing |
|
||||
| 3b: tkg_edges | tkg_edges.json | ❌ missing |
|
||||
| 4a: rule2 | rule2.json | ❌ missing |
|
||||
|
||||
```
|
||||
1. Check {OUTPUT_DIR}/{file_uuid}.pre.json
|
||||
├─ Exists AND content_hash matches → use cached (skip SHA256 + probe)
|
||||
└─ Not exists OR hash mismatch → compute fresh (existing logic)
|
||||
|
||||
2. Dedup check: SELECT file_uuid FROM videos WHERE content_hash = $1
|
||||
├─ Found → already_exists: true (identical DNA = same file)
|
||||
└─ Not found → continue
|
||||
|
||||
3. Name conflict check + auto-rename if needed
|
||||
└─ charade.mp4 → charade (1).mp4 (same name, different content)
|
||||
|
||||
4. INSERT INTO videos (
|
||||
file_uuid, file_path, file_name, file_type,
|
||||
duration, width, height, fps,
|
||||
probe_json, content_hash, status, registration_time
|
||||
) VALUES (
|
||||
$1, $2, $3, $4, $5, $6, $7, $8, $9, $10,
|
||||
'registered', NOW() ← status=registered, registration_time=NOW()
|
||||
)
|
||||
```
|
||||
|
||||
## Data Separation
|
||||
|
||||
| Field | Source | Computed When | Mutable |
|
||||
|-------|--------|---------------|:------:|
|
||||
| `birthday` | `fs::metadata().modified()` (mtime) | Pre-process (once) | ❌ Never (stable across rsync) |
|
||||
| `content_hash` (SHA256) | Full file | Pre-process (once) | ❌ Never (unless file modified) |
|
||||
| `file_uuid` | SHA256(mac\|birthday\|path\|filename) | Pre-process (once) | ❌ Never |
|
||||
| `registration_time` | `NOW()` at register | Register API | ✅ Per registration |
|
||||
| `status` | — | Register API | `unregistered` → `registered` |
|
||||
|
||||
## File Lifecycle State Diagram
|
||||
|
||||
```
|
||||
File detected by watcher (detection only, no modification)
|
||||
│
|
||||
│ Pre-processing triggered explicitly (API or register)
|
||||
▼
|
||||
[Pre-Processor]
|
||||
├─ SHA256 (DNA / fingerprint)
|
||||
├─ ffprobe (metadata extraction)
|
||||
└─ file_uuid (birth certificate ID)
|
||||
│
|
||||
▼
|
||||
{file_uuid}.pre.json
|
||||
status = unregistered (no DB record)
|
||||
│
|
||||
│ (user calls POST /api/v1/files/register)
|
||||
▼
|
||||
[Register Handler]
|
||||
├─ Read .pre.json → skip recomputation
|
||||
├─ Dedup check (content_hash collision?)
|
||||
├─ Name check + rename?
|
||||
└─ INSERT INTO videos
|
||||
│
|
||||
▼
|
||||
status = registered
|
||||
registration_time = NOW()
|
||||
```
|
||||
|
||||
## Implementation Checklist
|
||||
|
||||
| # | Task | File |
|
||||
|---|------|------|
|
||||
| 1 | Expose `pre_process_file()` as public function (SHA256 + probe + file_uuid → `.pre.json`) | `src/watcher/watcher.rs` |
|
||||
| 2 | Register: read `.pre.json`, skip SHA256/probe if cached | `src/api/server.rs` → `register_single_file` |
|
||||
| 3 | file_uuid: use `birthday` from `.pre.json` (or `fs::metadata().modified()` fallback) | `src/api/server.rs` |
|
||||
| 4 | INSERT status: `registered`, registration_time: `NOW()` | `src/api/server.rs` |
|
||||
**Observations**:
|
||||
- S1 processors mostly complete, but Appearance missing (1g)
|
||||
- S0 profile/key_frame missing (registration may not have created them)
|
||||
- S2-S4 all have DB data but no flat `.json` dumps
|
||||
|
||||
---
|
||||
|
||||
## Version History
|
||||
|
||||
| Version | Date | Changes |
|
||||
|---------|------|---------|
|
||||
| V1.0 | 2026-05-15 | Initial design — birth certificate (pre-process) + civil registration two-phase flow |
|
||||
| V1.1 | 2026-05-15 | Reclassified from DESIGN to STANDARDS as design standard |
|
||||
| V1.2 | 2026-05-15 | mtime replaces birthtime for file_uuid stability across rsync; watcher is detection-only |
|
||||
| Version | Date | Author | Changes |
|
||||
|---------|------|--------|---------|
|
||||
| 1.2 | 2026-07-22 | OpenCode | Added CUT scene key frames extraction for VLM analysis |
|
||||
| 1.1 | 2026-07-22 | OpenCode | Added S0b: audio_track classification (VAD) — 6 stages, 15 sub-stages |
|
||||
| 1.0 | 2026-07-22 | OpenCode | Initial design — 6 stages, 14 sub-stages, I/O specs, verification, rebuild |
|
||||
|
||||
@@ -0,0 +1,340 @@
|
||||
# Momentry 文件处理流程 - 产出导向设计
|
||||
|
||||
**日期**: 2026-10-10
|
||||
**版本**: V2.0 (产出导向)
|
||||
|
||||
---
|
||||
|
||||
## 🎯 设计原则
|
||||
|
||||
1. **产出导向**: 每个阶段都有明确的产品
|
||||
2. **可查看性**: 每个产品都有对应的功能或文件
|
||||
3. **过程透明**: 不够直观的当作过程,不单独列出
|
||||
|
||||
---
|
||||
|
||||
## 📦 阶段与产出
|
||||
|
||||
### 阶段 1: 媒体分析 (Processors)
|
||||
|
||||
**产出**: `{file_uuid}.workspace.sqlite`
|
||||
|
||||
| 数据表 | 内容 | 用途 |
|
||||
|--------|------|------|
|
||||
| `pre_chunks` | 原始文本块 | ASR 原始输出 |
|
||||
| `face_detections` | 人脸检测 | 每帧人脸位置 |
|
||||
| `speaker_detections` | 说话人检测 | 说话人片段 |
|
||||
| `processor_results` | 处理结果 | 各处理器输出 |
|
||||
|
||||
**可查看方式**:
|
||||
- 📄 文件: `~/momentry/output/{file_uuid}.workspace.sqlite`
|
||||
- 🔍 工具: SQLite Browser / `sqlite3` 命令
|
||||
- 🌐 API: 无(内部文件)
|
||||
|
||||
**重要性**: ⭐⭐⭐⭐⭐ (所有后续阶段的基础)
|
||||
|
||||
---
|
||||
|
||||
### 阶段 2: 文本块 (Chunks)
|
||||
|
||||
**产出**: PostgreSQL `chunks` 表
|
||||
|
||||
| 字段 | 内容 | 用途 |
|
||||
|------|------|------|
|
||||
| `file_uuid` | 文件ID | 文件关联 |
|
||||
| `chunk_id` | 块ID | 唯一标识 |
|
||||
| `text_content` | 文本内容 | 关键词搜索 |
|
||||
| `start_time` | 开始时间 | 时间定位 |
|
||||
| `end_time` | 结束时间 | 时间定位 |
|
||||
|
||||
**可查看方式**:
|
||||
- 🌐 API: `GET /api/v1/chunks?file_uuid={file_uuid}`
|
||||
- 🔍 搜索: `GET /api/v1/search?keyword={keyword}`
|
||||
- 📊 状态: `keyword_ready`
|
||||
|
||||
**重要性**: ⭐⭐⭐⭐ (支持关键词搜索)
|
||||
|
||||
---
|
||||
|
||||
### 阶段 3: 人脸轨迹 (Face Tracks)
|
||||
|
||||
**产出**: `{file_uuid}.faces.json`
|
||||
|
||||
```json
|
||||
{
|
||||
"file_uuid": "abc123...",
|
||||
"tracks": [
|
||||
{
|
||||
"trace_id": 1,
|
||||
"face_count": 150,
|
||||
"confidence": 0.95,
|
||||
"frames": [100, 101, 102, ...]
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
**可查看方式**:
|
||||
- 📄 文件: `~/momentry/output/{file_uuid}.faces.json`
|
||||
- 🌐 API: `GET /api/v1/faces/tracks?file_uuid={file_uuid}`
|
||||
- 🖼️ 可视化: Face Track Viewer (规划中)
|
||||
|
||||
**重要性**: ⭐⭐⭐ (人脸追踪数据)
|
||||
|
||||
---
|
||||
|
||||
### 阶段 4: 身份识别 (Identities)
|
||||
|
||||
**产出**: PostgreSQL `identities` 表
|
||||
|
||||
| 字段 | 内容 | 用途 |
|
||||
|------|------|------|
|
||||
| `identity_uuid` | 身份ID | 全局唯一标识 |
|
||||
| `name` | 姓名 | 人物名称 |
|
||||
| `face_count` | 人脸数 | 统计信息 |
|
||||
| `file_count` | 文件数 | 出现范围 |
|
||||
|
||||
**可查看方式**:
|
||||
- 🌐 API: `GET /api/v1/identities`
|
||||
- 🔍 搜索: `GET /api/v1/search?person={name}`
|
||||
- 📊 状态: `face_mgmt_ready`
|
||||
|
||||
**重要性**: ⭐⭐⭐⭐ (支持人脸管理)
|
||||
|
||||
---
|
||||
|
||||
### 阶段 5: 知识图谱 (TKG)
|
||||
|
||||
**产出**: PostgreSQL `tkg_nodes` + `tkg_edges` 表
|
||||
|
||||
**节点表**:
|
||||
| 节点类型 | 内容 | 用途 |
|
||||
|----------|------|------|
|
||||
| `face_track` | 人脸轨迹节点 | 轨迹关联 |
|
||||
| `speaker` | 说话人节点 | 说话人关联 |
|
||||
| `character` | 角色节点 | 角色关联 |
|
||||
| `chunk` | 文本块节点 | 内容关联 |
|
||||
|
||||
**边表**:
|
||||
| 边类型 | 内容 | 用途 |
|
||||
|--------|------|------|
|
||||
| `same_identity` | 同一身份 | 人脸绑定 |
|
||||
| `same_speaker` | 同一说话人 | 说话人绑定 |
|
||||
| `speaks_in` | 在某段说话 | 时间关联 |
|
||||
| `appears_in` | 出现在某段 | 时间关联 |
|
||||
|
||||
**可查看方式**:
|
||||
- 🌐 API: `GET /api/v1/tkg/nodes?file_uuid={file_uuid}`
|
||||
- 🔍 查询: Agent 自然语言查询
|
||||
- 📊 状态: `agent_ready`
|
||||
|
||||
**重要性**: ⭐⭐⭐⭐⭐ (支持复杂查询)
|
||||
|
||||
---
|
||||
|
||||
### 阶段 6: 向量索引 (Vectors)
|
||||
|
||||
**产出**: Qdrant Collections
|
||||
|
||||
| Collection | 内容 | 用途 |
|
||||
|------------|------|------|
|
||||
| `_chunks` | 文本向量 | 语义搜索 |
|
||||
| `_faces` | 人脸向量 | 人脸搜索 |
|
||||
| `_scenes` | 场景向量 | 场景搜索 |
|
||||
|
||||
**可查看方式**:
|
||||
- 🌐 API: `POST /api/v1/search/semantic`
|
||||
- 🔍 搜索: 自然语言搜索
|
||||
- 📊 状态: `semantic_ready`
|
||||
|
||||
**重要性**: ⭐⭐⭐⭐ (支持语义搜索)
|
||||
|
||||
---
|
||||
|
||||
### 阶段 7: 人脸描述 (Face VLM)
|
||||
|
||||
**产出**: `{file_uuid}.face_vlm.json`
|
||||
|
||||
```json
|
||||
{
|
||||
"file_uuid": "abc123...",
|
||||
"tracks": [
|
||||
{
|
||||
"trace_id": 1,
|
||||
"description": "中年男性,戴眼镜,穿蓝色衬衫...",
|
||||
"confidence": 0.92
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
**可查看方式**:
|
||||
- 📄 文件: `~/momentry/output/{file_uuid}.face_vlm.json`
|
||||
- 🌐 API: `GET /api/v1/faces/tracks/{trace_id}`
|
||||
- 🔍 搜索: 通过描述搜索人物
|
||||
|
||||
**重要性**: ⭐⭐⭐ (人脸外观描述)
|
||||
|
||||
---
|
||||
|
||||
### 阶段 8: 场景描述 (Scene VLM)
|
||||
|
||||
**产出**: `{file_uuid}.scene_vlm.json`
|
||||
|
||||
```json
|
||||
{
|
||||
"file_uuid": "abc123...",
|
||||
"scenes": [
|
||||
{
|
||||
"scene_id": 1,
|
||||
"start_time": 0.0,
|
||||
"end_time": 10.5,
|
||||
"description": "室内办公室场景,有两个人在对话..."
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
**可查看方式**:
|
||||
- 📄 文件: `~/momentry/output/{file_uuid}.scene_vlm.json`
|
||||
- 🌐 API: `GET /api/v1/scenes?file_uuid={file_uuid}`
|
||||
- 🔍 搜索: 通过描述搜索场景
|
||||
|
||||
**重要性**: ⭐⭐⭐ (场景描述)
|
||||
|
||||
---
|
||||
|
||||
### 阶段 9: 时刻块 (Moment Chunks)
|
||||
|
||||
**产出**: PostgreSQL `moment_chunks` 表
|
||||
|
||||
| 字段 | 内容 | 用途 |
|
||||
|------|------|------|
|
||||
| `moment_id` | 时刻ID | 唯一标识 |
|
||||
| `start_time` | 开始时间 | 时间定位 |
|
||||
| `end_time` | 结束时间 | 时间定位 |
|
||||
| `summary` | 摘要 | 内容概览 |
|
||||
| `keywords` | 关键词 | 快速理解 |
|
||||
|
||||
**可查看方式**:
|
||||
- 🌐 API: `GET /api/v1/moments?file_uuid={file_uuid}`
|
||||
- 🔍 搜索: 通过关键词搜索时刻
|
||||
- 📊 Timeline: 时刻时间线
|
||||
|
||||
**重要性**: ⭐⭐ (时刻概览)
|
||||
|
||||
---
|
||||
|
||||
## 🔄 完整流程
|
||||
|
||||
```
|
||||
视频文件注册
|
||||
↓
|
||||
[阶段 1] 媒体分析
|
||||
→ 产出: {file_uuid}.workspace.sqlite
|
||||
↓
|
||||
[阶段 2] 文本块
|
||||
→ 产出: PostgreSQL chunks 表
|
||||
→ 状态: keyword_ready
|
||||
↓
|
||||
[阶段 3] 人脸轨迹
|
||||
→ 产出: {file_uuid}.faces.json
|
||||
↓
|
||||
[阶段 4] 身份识别
|
||||
→ 产出: PostgreSQL identities 表
|
||||
→ 状态: face_mgmt_ready
|
||||
↓
|
||||
[阶段 5] 知识图谱
|
||||
→ 产出: PostgreSQL tkg_nodes + tkg_edges
|
||||
→ 状态: agent_ready
|
||||
↓
|
||||
[阶段 6] 向量索引
|
||||
→ 产出: Qdrant collections
|
||||
→ 状态: semantic_ready
|
||||
↓
|
||||
[阶段 7] 人脸描述
|
||||
→ 产出: {file_uuid}.face_vlm.json
|
||||
↓
|
||||
[阶段 8] 场景描述
|
||||
→ 产出: {file_uuid}.scene_vlm.json
|
||||
↓
|
||||
[阶段 9] 时刻块
|
||||
→ 产出: PostgreSQL moment_chunks
|
||||
↓
|
||||
✅ 完成
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 📊 文件状态映射
|
||||
|
||||
| 状态 | 含义 | 对应阶段 |
|
||||
|------|------|----------|
|
||||
| `pending` | 等待处理 | 初始状态 |
|
||||
| `scanning` | 正在扫描 | 阶段 1-9 |
|
||||
| `keyword_ready` | 支持关键词搜索 | 阶段 2+ |
|
||||
| `semantic_ready` | 支持语义搜索 | 阶段 6+ |
|
||||
| `face_mgmt_ready` | 支持人脸管理 | 阶段 4+ |
|
||||
| `agent_ready` | 支持Agent查询 | 阶段 5+ |
|
||||
| `completed` | 完全完成 | 所有阶段 |
|
||||
|
||||
---
|
||||
|
||||
## 🔍 产出查看方式总结
|
||||
|
||||
| 产出类型 | 文件位置 | API 端点 | 可视化 |
|
||||
|----------|----------|----------|--------|
|
||||
| **workspace.sqlite** | `~/momentry/output/` | 无 | SQLite Browser |
|
||||
| **文本块** | 数据库 | `/api/v1/chunks` | 搜索结果 |
|
||||
| **人脸轨迹** | `.faces.json` | `/api/v1/faces/tracks` | 规划中 |
|
||||
| **身份** | 数据库 | `/api/v1/identities` | Identity Cards |
|
||||
| **知识图谱** | 数据库 | `/api/v1/tkg/nodes` | Graph Viewer |
|
||||
| **向量索引** | Qdrant | `/api/v1/search/semantic` | 搜索结果 |
|
||||
| **人脸描述** | `.face_vlm.json` | `/api/v1/faces/tracks/{id}` | 详情页 |
|
||||
| **场景描述** | `.scene_vlm.json` | `/api/v1/scenes` | 场景列表 |
|
||||
| **时刻块** | 数据库 | `/api/v1/moments` | Timeline |
|
||||
|
||||
---
|
||||
|
||||
## 💡 设计优势
|
||||
|
||||
### 相比原流程
|
||||
|
||||
| 改进点 | 原流程 | 新流程 |
|
||||
|--------|--------|--------|
|
||||
| **产出导向** | 过程导向 | ✅ 产出导向 |
|
||||
| **可查看性** | 抽象概念 | ✅ 具体文件/数据 |
|
||||
| **用户理解** | 需要技术背景 | ✅ 直观易懂 |
|
||||
| **功能映射** | 模糊 | ✅ 明确 |
|
||||
|
||||
### 用户体验
|
||||
|
||||
- ✅ 每个阶段都有明确的产品
|
||||
- ✅ 每个产品都有查看方式
|
||||
- ✅ 过程透明,不过度展示
|
||||
- ✅ 状态清晰,进度可追踪
|
||||
|
||||
---
|
||||
|
||||
## 📝 实施建议
|
||||
|
||||
### 优先级排序
|
||||
|
||||
**P0 - 核心产出**:
|
||||
1. 媒体分析 (workspace.sqlite)
|
||||
2. 文本块 (chunks)
|
||||
3. 身份识别 (identities)
|
||||
4. 知识图谱 (tkg)
|
||||
|
||||
**P1 - 增强产出**:
|
||||
5. 向量索引 (vectors)
|
||||
6. 人脸轨迹 (faces.json)
|
||||
|
||||
**P2 - 可选产出**:
|
||||
7. 人脸描述 (face_vlm.json)
|
||||
8. 场景描述 (scene_vlm.json)
|
||||
9. 时刻块 (moment_chunks)
|
||||
|
||||
---
|
||||
|
||||
**设计完成,等待实施。**
|
||||
@@ -0,0 +1,502 @@
|
||||
# Momentry 文件处理流程 - V3 (JSON 产出关联版)
|
||||
|
||||
**日期**: 2026-10-10
|
||||
**版本**: V3.0
|
||||
|
||||
---
|
||||
|
||||
## 🎯 设计原则
|
||||
|
||||
1. **每个阶段都有明确的 JSON 文件产出**
|
||||
2. **每个 JSON 文件都可查看**
|
||||
3. **数据库产出作为辅助**
|
||||
|
||||
---
|
||||
|
||||
## 📦 阶段与产出
|
||||
|
||||
### 阶段 1: 媒体分析 (Media Analysis)
|
||||
|
||||
**主要产出**: `{file_uuid}.workspace.sqlite`
|
||||
|
||||
**JSON 产出** (7个):
|
||||
|
||||
| 文件名 | 内容 | 大小 | 用途 |
|
||||
|--------|------|------|------|
|
||||
| `{file_uuid}.probe.json` | 视频元数据 | ~1KB | 视频信息 |
|
||||
| `{file_uuid}.asr.json` | ASR 结果 | ~10KB | 语音识别 |
|
||||
| `{file_uuid}.face.json` | 人脸检测 | ~50KB | 人脸位置 |
|
||||
| `{file_uuid}.ocr.json` | OCR 结果 | ~5KB | 文字识别 |
|
||||
| `{file_uuid}.cut.json` | 场景分割 | ~1KB | 场景边界 |
|
||||
| `{file_uuid}.asrx.json` | 说话人识别 | ~2KB | 说话人片段 |
|
||||
| `{file_uuid}.scenes.json` | 场景检测 | ~3KB | 场景信息 |
|
||||
|
||||
**示例: {file_uuid}.asr.json**:
|
||||
```json
|
||||
{
|
||||
"language": "en",
|
||||
"text": "Hello world...",
|
||||
"segments": [
|
||||
{
|
||||
"start": 0.0,
|
||||
"end": 2.5,
|
||||
"text": "Hello world"
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
**可查看方式**:
|
||||
- 📄 文件: `~/momentry/output/{file_uuid}.*.json`
|
||||
- 🔧 工具: `jq` 命令 / JSON Viewer
|
||||
- 🌐 API: 无(原始数据)
|
||||
|
||||
**重要性**: ⭐⭐⭐⭐⭐ (基础数据)
|
||||
|
||||
---
|
||||
|
||||
### 阶段 2: 文本块 (Text Chunks)
|
||||
|
||||
**主要产出**: PostgreSQL `chunks` 表
|
||||
|
||||
**JSON 产出**: 无
|
||||
|
||||
**数据库产出**:
|
||||
```sql
|
||||
-- chunks 表
|
||||
CREATE TABLE chunks (
|
||||
file_uuid TEXT,
|
||||
chunk_id TEXT,
|
||||
text_content TEXT,
|
||||
start_time REAL,
|
||||
end_time REAL
|
||||
);
|
||||
```
|
||||
|
||||
**可查看方式**:
|
||||
- 🌐 API: `GET /api/v1/chunks?file_uuid={file_uuid}`
|
||||
- 🔍 搜索: `GET /api/v1/search?keyword={keyword}`
|
||||
- 📊 状态: `keyword_ready`
|
||||
|
||||
**重要性**: ⭐⭐⭐⭐ (关键词搜索)
|
||||
|
||||
---
|
||||
|
||||
### 阶段 3: 人脸追踪 (Face Tracing)
|
||||
|
||||
**主要产出**: `{file_uuid}.face_traced.json`
|
||||
|
||||
**JSON 结构**:
|
||||
```json
|
||||
{
|
||||
"status": "has_faces",
|
||||
"frame_count": 150,
|
||||
"fps": 29.97,
|
||||
"frames": {
|
||||
"92": {
|
||||
"frame_number": 92,
|
||||
"time_seconds": 3.07,
|
||||
"faces": [
|
||||
{
|
||||
"x": 313,
|
||||
"y": 468,
|
||||
"width": 53,
|
||||
"height": 53,
|
||||
"confidence": 0.6,
|
||||
"captureQuality": 0.1,
|
||||
"trace_id": 1
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
"traces": [
|
||||
{
|
||||
"trace_id": 1,
|
||||
"face_count": 50,
|
||||
"frames": [92, 93, 94, ...]
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
**可查看方式**:
|
||||
- 📄 文件: `~/momentry/output/{file_uuid}.face_traced.json`
|
||||
- 🌐 API: `GET /api/v1/faces/tracks?file_uuid={file_uuid}`
|
||||
- 🖼️ 可视化: Face Track Viewer
|
||||
|
||||
**重要性**: ⭐⭐⭐⭐ (人脸追踪)
|
||||
|
||||
---
|
||||
|
||||
### 阶段 4: 人脸聚类 (Face Clustering)
|
||||
|
||||
**主要产出**: `{file_uuid}.face_cluster.json`
|
||||
|
||||
**JSON 结构**:
|
||||
```json
|
||||
{
|
||||
"status": "has_faces",
|
||||
"file_uuid": "abc123...",
|
||||
"clusters": [
|
||||
{
|
||||
"cluster_id": 0,
|
||||
"face_count": 150,
|
||||
"representative_frame": 100,
|
||||
"frames": [92, 93, 94, ...]
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
**可查看方式**:
|
||||
- 📄 文件: `~/momentry/output/{file_uuid}.face_cluster.json`
|
||||
- 🌐 API: `GET /api/v1/faces/clusters?file_uuid={file_uuid}`
|
||||
|
||||
**重要性**: ⭐⭐⭐ (人脸聚类)
|
||||
|
||||
---
|
||||
|
||||
### 阶段 5: 身份识别 (Identities)
|
||||
|
||||
**主要产出**: PostgreSQL `identities` 表
|
||||
|
||||
**JSON 产出**: 无
|
||||
|
||||
**数据库产出**:
|
||||
```sql
|
||||
-- identities 表
|
||||
CREATE TABLE identities (
|
||||
identity_uuid TEXT PRIMARY KEY,
|
||||
name TEXT,
|
||||
face_count INTEGER,
|
||||
file_count INTEGER,
|
||||
created_at TIMESTAMP
|
||||
);
|
||||
|
||||
-- identity_bindings 表
|
||||
CREATE TABLE identity_bindings (
|
||||
file_uuid TEXT,
|
||||
trace_id INTEGER,
|
||||
identity_uuid TEXT,
|
||||
confidence REAL
|
||||
);
|
||||
```
|
||||
|
||||
**可查看方式**:
|
||||
- 🌐 API: `GET /api/v1/identities`
|
||||
- 🔍 搜索: `GET /api/v1/search?person={name}`
|
||||
- 📊 状态: `face_mgmt_ready`
|
||||
|
||||
**重要性**: ⭐⭐⭐⭐⭐ (人脸管理)
|
||||
|
||||
---
|
||||
|
||||
### 阶段 6: 知识图谱 (Knowledge Graph)
|
||||
|
||||
**主要产出**: PostgreSQL `tkg_*` 表
|
||||
|
||||
**JSON 产出**: 无
|
||||
|
||||
**数据库产出**:
|
||||
```sql
|
||||
-- tkg_nodes 表
|
||||
CREATE TABLE tkg_nodes (
|
||||
node_id TEXT PRIMARY KEY,
|
||||
node_type TEXT,
|
||||
file_uuid TEXT,
|
||||
properties JSONB
|
||||
);
|
||||
|
||||
-- tkg_edges 表
|
||||
CREATE TABLE tkg_edges (
|
||||
edge_id TEXT PRIMARY KEY,
|
||||
source_node TEXT,
|
||||
target_node TEXT,
|
||||
edge_type TEXT,
|
||||
properties JSONB
|
||||
);
|
||||
```
|
||||
|
||||
**可查看方式**:
|
||||
- 🌐 API: `GET /api/v1/tkg/nodes?file_uuid={file_uuid}`
|
||||
- 🔍 查询: Agent 自然语言查询
|
||||
- 📊 状态: `agent_ready`
|
||||
|
||||
**重要性**: ⭐⭐⭐⭐⭐ (复杂查询)
|
||||
|
||||
---
|
||||
|
||||
### 阶段 7: 向量索引 (Vector Index)
|
||||
|
||||
**主要产出**: Qdrant Collections
|
||||
|
||||
**JSON 产出**: 无
|
||||
|
||||
**向量产出**:
|
||||
- `_chunks` collection (文本向量)
|
||||
- `_faces` collection (人脸向量)
|
||||
- `_scenes` collection (场景向量)
|
||||
|
||||
**可查看方式**:
|
||||
- 🌐 API: `POST /api/v1/search/semantic`
|
||||
- 🔍 搜索: 自然语言搜索
|
||||
- 📊 状态: `semantic_ready`
|
||||
|
||||
**重要性**: ⭐⭐⭐⭐ (语义搜索)
|
||||
|
||||
---
|
||||
|
||||
### 阶段 8: 人脸描述 (Face Description)
|
||||
|
||||
**主要产出**: `{file_uuid}.face_vlm.json`
|
||||
|
||||
**JSON 结构**:
|
||||
```json
|
||||
{
|
||||
"file_uuid": "abc123...",
|
||||
"traces": [
|
||||
{
|
||||
"trace_id": 1,
|
||||
"description": "中年男性,戴眼镜,穿蓝色衬衫",
|
||||
"confidence": 0.92,
|
||||
"frame": 100
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
**可查看方式**:
|
||||
- 📄 文件: `~/momentry/output/{file_uuid}.face_vlm.json`
|
||||
- 🌐 API: `GET /api/v1/faces/traces/{trace_id}`
|
||||
- 🔍 搜索: 通过描述搜索人物
|
||||
|
||||
**重要性**: ⭐⭐⭐ (人脸外观)
|
||||
|
||||
---
|
||||
|
||||
### 阶段 9: 场景描述 (Scene Description)
|
||||
|
||||
**主要产出**: `{file_uuid}.scene_vlm.json`
|
||||
|
||||
**JSON 结构**:
|
||||
```json
|
||||
{
|
||||
"file_uuid": "abc123...",
|
||||
"scenes": [
|
||||
{
|
||||
"scene_id": 1,
|
||||
"start_time": 0.0,
|
||||
"end_time": 10.5,
|
||||
"description": "室内办公室场景,有两个人在对话",
|
||||
"key_frame": 150
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
**可查看方式**:
|
||||
- 📄 文件: `~/momentry/output/{file_uuid}.scene_vlm.json`
|
||||
- 🌐 API: `GET /api/v1/scenes?file_uuid={file_uuid}`
|
||||
- 🔍 搜索: 通过描述搜索场景
|
||||
|
||||
**重要性**: ⭐⭐⭐ (场景理解)
|
||||
|
||||
---
|
||||
|
||||
### 阶段 10: 时刻块 (Moment Chunks)
|
||||
|
||||
**主要产出**: PostgreSQL `moment_chunks` 表
|
||||
|
||||
**JSON 产出**: 无
|
||||
|
||||
**数据库产出**:
|
||||
```sql
|
||||
-- moment_chunks 表
|
||||
CREATE TABLE moment_chunks (
|
||||
moment_id TEXT PRIMARY KEY,
|
||||
file_uuid TEXT,
|
||||
start_time REAL,
|
||||
end_time REAL,
|
||||
summary TEXT,
|
||||
keywords TEXT[]
|
||||
);
|
||||
```
|
||||
|
||||
**可查看方式**:
|
||||
- 🌐 API: `GET /api/v1/moments?file_uuid={file_uuid}`
|
||||
- 🔍 搜索: 通过关键词搜索时刻
|
||||
- 📊 Timeline: 时刻时间线
|
||||
|
||||
**重要性**: ⭐⭐ (时刻概览)
|
||||
|
||||
---
|
||||
|
||||
## 🔄 完整流程图
|
||||
|
||||
```
|
||||
视频文件注册
|
||||
↓
|
||||
[阶段 1] 媒体分析
|
||||
→ 产出: {file_uuid}.workspace.sqlite
|
||||
→ JSON: probe.json, asr.json, face.json, ocr.json,
|
||||
cut.json, asrx.json, scenes.json
|
||||
↓
|
||||
[阶段 2] 文本块
|
||||
→ 产出: PostgreSQL chunks 表
|
||||
→ 状态: keyword_ready
|
||||
↓
|
||||
[阶段 3] 人脸追踪
|
||||
→ 产出: {file_uuid}.face_traced.json
|
||||
↓
|
||||
[阶段 4] 人脸聚类
|
||||
→ 产出: {file_uuid}.face_cluster.json
|
||||
↓
|
||||
[阶段 5] 身份识别
|
||||
→ 产出: PostgreSQL identities 表
|
||||
→ 状态: face_mgmt_ready
|
||||
↓
|
||||
[阶段 6] 知识图谱
|
||||
→ 产出: PostgreSQL tkg_* 表
|
||||
→ 状态: agent_ready
|
||||
↓
|
||||
[阶段 7] 向量索引
|
||||
→ 产出: Qdrant collections
|
||||
→ 状态: semantic_ready
|
||||
↓
|
||||
[阶段 8] 人脸描述
|
||||
→ 产出: {file_uuid}.face_vlm.json
|
||||
↓
|
||||
[阶段 9] 场景描述
|
||||
→ 产出: {file_uuid}.scene_vlm.json
|
||||
↓
|
||||
[阶段 10] 时刻块
|
||||
→ 产出: PostgreSQL moment_chunks
|
||||
↓
|
||||
✅ 完成
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 📊 产出统计
|
||||
|
||||
### JSON 文件产出
|
||||
|
||||
| 阶段 | JSON 文件 | 数量 |
|
||||
|------|-----------|------|
|
||||
| 阶段 1 | probe, asr, face, ocr, cut, asrx, scenes | 7 |
|
||||
| 阶段 3 | face_traced | 1 |
|
||||
| 阶段 4 | face_cluster | 1 |
|
||||
| 阶段 8 | face_vlm | 1 |
|
||||
| 阶段 9 | scene_vlm | 1 |
|
||||
| **总计** | **10 个 JSON 文件** | **11** |
|
||||
|
||||
### 数据库产出
|
||||
|
||||
| 阶段 | 表/Collection | 数量 |
|
||||
|------|---------------|------|
|
||||
| 阶段 2 | chunks | 1 |
|
||||
| 阶段 5 | identities, identity_bindings | 2 |
|
||||
| 阶段 6 | tkg_nodes, tkg_edges | 2 |
|
||||
| 阶段 7 | _chunks, _faces, _scenes | 3 |
|
||||
| 阶段 10 | moment_chunks | 1 |
|
||||
| **总计** | **9 个数据库表/Collection** | **9** |
|
||||
|
||||
### SQLite 产出
|
||||
|
||||
| 阶段 | 文件 | 数量 |
|
||||
|------|------|------|
|
||||
| 阶段 1 | workspace.sqlite | 1 |
|
||||
|
||||
---
|
||||
|
||||
## 🔍 JSON 文件查看方式
|
||||
|
||||
### 方式 1: 命令行
|
||||
|
||||
```bash
|
||||
# 查看 ASR 结果
|
||||
jq '.' ~/momentry/output/{file_uuid}.asr.json
|
||||
|
||||
# 查看 Face Traced 结果
|
||||
jq '.traces' ~/momentry/output/{file_uuid}.face_traced.json
|
||||
|
||||
# 查看 Face Cluster 结果
|
||||
jq '.clusters' ~/momentry/output/{file_uuid}.face_cluster.json
|
||||
```
|
||||
|
||||
### 方式 2: JSON Viewer
|
||||
|
||||
- 使用 VS Code 的 JSON Viewer
|
||||
- 使用在线 JSON Viewer
|
||||
|
||||
### 方式 3: API
|
||||
|
||||
```bash
|
||||
# 获取人脸轨迹
|
||||
GET /api/v1/faces/tracks?file_uuid={file_uuid}
|
||||
|
||||
# 获取人脸聚类
|
||||
GET /api/v1/faces/clusters?file_uuid={file_uuid}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 📝 文件命名规则
|
||||
|
||||
### 格式
|
||||
|
||||
```
|
||||
{file_uuid}.{type}.json
|
||||
```
|
||||
|
||||
### 类型列表
|
||||
|
||||
| 类型 | 说明 |
|
||||
|------|------|
|
||||
| `probe` | 视频元数据 |
|
||||
| `asr` | ASR 结果 |
|
||||
| `face` | 人脸检测 |
|
||||
| `ocr` | OCR 结果 |
|
||||
| `cut` | 场景分割 |
|
||||
| `asrx` | 说话人识别 |
|
||||
| `scenes` | 场景检测 |
|
||||
| `face_traced` | 人脸追踪 |
|
||||
| `face_cluster` | 人脸聚类 |
|
||||
| `face_vlm` | 人脸描述 |
|
||||
| `scene_vlm` | 场景描述 |
|
||||
|
||||
---
|
||||
|
||||
## 🎯 使用场景
|
||||
|
||||
### 场景 1: 查看视频基本信息
|
||||
|
||||
```bash
|
||||
# 查看 probe.json
|
||||
jq '.duration, .width, .height' {file_uuid}.probe.json
|
||||
```
|
||||
|
||||
### 场景 2: 查看语音内容
|
||||
|
||||
```bash
|
||||
# 查看 ASR 结果
|
||||
jq '.text' {file_uuid}.asr.json
|
||||
```
|
||||
|
||||
### 场景 3: 查看人脸追踪
|
||||
|
||||
```bash
|
||||
# 查看人脸轨迹
|
||||
jq '.traces[] | {trace_id, face_count}' {file_uuid}.face_traced.json
|
||||
```
|
||||
|
||||
### 场景 4: 查看人脸外观
|
||||
|
||||
```bash
|
||||
# 查看人脸描述
|
||||
jq '.traces[] | {trace_id, description}' {file_uuid}.face_vlm.json
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
**设计完成,每个阶段都有明确的 JSON 产出。**
|
||||
@@ -0,0 +1,153 @@
|
||||
# File Profile V1.0
|
||||
|
||||
**Status:** Active
|
||||
**Version:** 1.0
|
||||
**Date:** 2026-07-22
|
||||
**Scope:** File identity artifact — persistent on-disk profile per registered file
|
||||
|
||||
---
|
||||
|
||||
## Problem
|
||||
|
||||
- 5 zombie files in DB: `file_uuid` exists but `file_name` and `file_path` are empty — no way to recover
|
||||
- File identity lives only in PostgreSQL; no on-disk fallback
|
||||
- `birth_registration` written by `ingestion.rs` but **not** by `files.rs` API path
|
||||
- No file history — if a file moves or is renamed, no record of where it was
|
||||
|
||||
## Design
|
||||
|
||||
A JSON file created **first** during registration, stored flat in `MOMENTRY_OUTPUT_DIR`:
|
||||
|
||||
```
|
||||
{MOMENTRY_OUTPUT_DIR}/{file_uuid}.profile.json
|
||||
```
|
||||
|
||||
### JSON Structure
|
||||
|
||||
```json
|
||||
{
|
||||
"version": "1.0",
|
||||
"file_uuid": "84d838f260e1881a0daa55fabbc8e434",
|
||||
"file_name": "view28.mp4",
|
||||
"file_type": "video",
|
||||
"birth": {
|
||||
"mac_address": "a1:b2:c3:d4:e5:f6",
|
||||
"birthday": "2026-04-13T23:00:49+08:00",
|
||||
"original_path": "/Users/accusys/momentry/var/sftpgo/data/demo",
|
||||
"original_filename": "view28.mp4",
|
||||
"canonical_path": "/Users/accusys/momentry/var/sftpgo/data/demo/view28.mp4",
|
||||
"content_hash": "abc123..."
|
||||
},
|
||||
"current": {
|
||||
"path": "/Users/accusys/momentry/var/sftpgo/data/demo/view28.mp4",
|
||||
"file_name": "view28.mp4",
|
||||
"file_type": "video"
|
||||
},
|
||||
"history": [
|
||||
{
|
||||
"action": "registered",
|
||||
"timestamp": "2026-07-22T14:30:00+08:00",
|
||||
"path": "/Users/accusys/momentry/var/sftpgo/data/demo/view28.mp4",
|
||||
"file_name": "view28.mp4"
|
||||
}
|
||||
],
|
||||
"metadata": {
|
||||
"duration": 243.24,
|
||||
"width": 720,
|
||||
"height": 890,
|
||||
"fps": 60.0,
|
||||
"total_frames": 7297
|
||||
},
|
||||
"key_frame": null
|
||||
}
|
||||
```
|
||||
|
||||
### Fields
|
||||
|
||||
| Field | Purpose |
|
||||
|-------|---------|
|
||||
| `version` | Profile schema version (for future migration) |
|
||||
| `file_uuid` | The deterministic UUID |
|
||||
| `file_name` | Original filename at registration |
|
||||
| `file_type` | video/audio/image/document/... |
|
||||
| `birth.mac_address` | MAC address used to compute UUID |
|
||||
| `birth.birthday` | File mtime (RFC3339) used to compute UUID |
|
||||
| `birth.original_path` | Parent directory at registration |
|
||||
| `birth.original_filename` | Filename at registration |
|
||||
| `birth.canonical_path` | Canonical (resolved symlinks) path at registration |
|
||||
| `birth.content_hash` | SHA256 of file content |
|
||||
| `current.path` | Latest known path (updated when file moves) |
|
||||
| `current.file_name` | Latest known filename (updated on rename) |
|
||||
| `current.file_type` | Latest file type |
|
||||
| `history` | Array of all path/name changes with timestamps |
|
||||
| `metadata` | Media info (duration, resolution, etc.) |
|
||||
| `key_frame` | Base64-encoded JPEG of representative frame (video only), or null |
|
||||
|
||||
### key_frame
|
||||
|
||||
For video files, `key_frame` stores a **base64-encoded JPEG** of a representative frame extracted at registration time (typically at 10% of duration or the first non-black frame). For non-video files, this field is `null`.
|
||||
|
||||
Purpose:
|
||||
- Instant visual identification without needing to open the video
|
||||
- Fallback if thumbnails or `.faces/` crops are deleted
|
||||
- Portable — the profile file is self-contained
|
||||
|
||||
Extraction:
|
||||
- Uses ffmpeg to grab a frame at `duration * 0.1` (or first frame if duration unknown)
|
||||
- JPEG quality 85, max width 640px
|
||||
- Stored inline as base64 string in the JSON
|
||||
|
||||
## Implementation
|
||||
|
||||
### New Module
|
||||
|
||||
`src/core/file_profile.rs` — `FileProfile` struct with:
|
||||
- `from_registration_params(...)` — build at registration time
|
||||
- `load_from_disk(uuid, output_dir)` — read `{uuid}.profile.json`
|
||||
- `save_to_disk(&self, output_dir)` — write `{uuid}.profile.json`
|
||||
- `update_current_path(&mut self, new_path, new_name)` — append to history, update current
|
||||
- `extract_key_frame(video_path, duration)` — ffmpeg frame extraction + base64
|
||||
|
||||
### Registration Flow
|
||||
|
||||
1. DB INSERT (existing)
|
||||
2. **Build FileProfile** from all params (mac, birthday, path, name, content_hash, probe metadata)
|
||||
3. **Extract key_frame** if video (ffmpeg)
|
||||
4. **Save `{uuid}.profile.json`** — first artifact on disk
|
||||
5. CUT processing (existing)
|
||||
|
||||
### Update Flow
|
||||
|
||||
When `file_path` or `file_name` changes via API:
|
||||
1. Load profile from disk
|
||||
2. `profile.update_current_path(new_path, new_name)`
|
||||
3. Save updated profile
|
||||
|
||||
### Fallback Flow
|
||||
|
||||
If DB data is missing (zombie files):
|
||||
1. Load profile from disk
|
||||
2. Profile's `current.path` and `current.file_name` provide recovery data
|
||||
|
||||
### Files Changed
|
||||
|
||||
| File | Change |
|
||||
|------|--------|
|
||||
| `src/core/file_profile.rs` | **NEW** — FileProfile struct |
|
||||
| `src/core/mod.rs` | Add `pub mod file_profile` |
|
||||
| `src/api/files.rs` | Write profile after registration; fallback; enrich GET; cleanup |
|
||||
| `src/core/ingestion.rs` | Write profile after registration |
|
||||
| `src/api/profile.rs` | Enrich GET file-profile with profile data + history |
|
||||
|
||||
### Backfill
|
||||
|
||||
Existing 16 files get profiles generated from DB fields + probe.json data.
|
||||
5 zombie files get minimal profiles (UUID + file_type + content_hash from DB).
|
||||
|
||||
---
|
||||
|
||||
## Version History
|
||||
|
||||
| Version | Date | Change |
|
||||
|---------|------|--------|
|
||||
| 1.0 | 2026-07-22 | Initial design — file profile with key_frame |
|
||||
@@ -0,0 +1,385 @@
|
||||
---
|
||||
title: FS VLM Performance Improvement Feasibility Study
|
||||
version: 1.0
|
||||
date: 2026-09-22
|
||||
author: Core Team
|
||||
status: Evaluation
|
||||
---
|
||||
|
||||
# FS VLM Performance Improvement Feasibility Study
|
||||
|
||||
## Current State Analysis
|
||||
|
||||
### Performance Baseline
|
||||
|
||||
| Metric | Value | Source |
|
||||
|--------|-------|--------|
|
||||
| Processing mode | **Sequential** | `vlm_summary.rs:76` |
|
||||
| Time per trace | 3-4 seconds |实测 |
|
||||
| Model | LLaVA (port 8091) | config.rs |
|
||||
| 22 traces | ~88 seconds | Calculated |
|
||||
| Pipeline impact | **Blocking** | job_worker.rs |
|
||||
|
||||
### Bottleneck Identification
|
||||
|
||||
1. **Sequential Processing** ❌
|
||||
```rust
|
||||
for (i, &trace_id) in trace_ids.iter().enumerate() {
|
||||
process_single_trace(...).await; // One at a time
|
||||
}
|
||||
```
|
||||
|
||||
2. **Slower Model** ❌
|
||||
- Using: LLaVA (llava-v1.5-7b)
|
||||
- Better: Gemma4 12B (already used in Scene VLM)
|
||||
- Speed difference: ~2-3x slower
|
||||
|
||||
3. **Pipeline Blocking** ❌
|
||||
- Job waits for all traces to complete
|
||||
- Status: "waiting for ingestion"
|
||||
- User experience: Poor
|
||||
|
||||
## Improvement Proposals
|
||||
|
||||
### Option 1: Parallel Processing (Recommended)
|
||||
|
||||
**Implementation**:
|
||||
```rust
|
||||
// Before: Sequential
|
||||
for trace_id in trace_ids {
|
||||
process_single_trace(trace_id).await;
|
||||
}
|
||||
|
||||
// After: Parallel (max 5 concurrent)
|
||||
use futures::stream::{self, StreamExt};
|
||||
|
||||
let results: Vec<_> = stream::iter(trace_ids)
|
||||
.map(|trace_id| process_single_trace(trace_id))
|
||||
.buffer_unordered(5) // Max 5 concurrent
|
||||
.collect()
|
||||
.await;
|
||||
```
|
||||
|
||||
**Expected Performance**:
|
||||
- 22 traces: 88s → **~18s** (5x improvement)
|
||||
- With 10 concurrent: **~9s**
|
||||
|
||||
**Pros**:
|
||||
- ✅ Significant speedup (5-10x)
|
||||
- ✅ Minimal code changes
|
||||
- ✅ No model change needed
|
||||
|
||||
**Cons**:
|
||||
- ⚠️ Higher memory usage
|
||||
- ⚠️ Higher GPU load
|
||||
- ⚠️ Need to tune concurrency limit
|
||||
|
||||
**Complexity**: Low
|
||||
**Risk**: Low
|
||||
|
||||
---
|
||||
|
||||
### Option 2: Use Gemma4 Instead of LLaVA
|
||||
|
||||
**Implementation**:
|
||||
```rust
|
||||
// Current
|
||||
VISION_URL=http://localhost:8091 (LLaVA)
|
||||
VISION_MODEL=llava-v1.5-7b
|
||||
|
||||
// Proposed
|
||||
VISION_URL=http://localhost:8080 (Gemma4)
|
||||
VISION_MODEL=gemma-4-12b-it
|
||||
```
|
||||
|
||||
**Expected Performance**:
|
||||
- Per trace: 3-4s → **1.5-2s** (2x improvement)
|
||||
- 22 traces: 88s → **~44s** (with sequential)
|
||||
- With parallel: **~9s** (5 concurrent) → **~4s** (10 concurrent)
|
||||
|
||||
**Pros**:
|
||||
- ✅ Faster model
|
||||
- ✅ Already deployed for Scene VLM
|
||||
- ✅ Better quality descriptions
|
||||
|
||||
**Cons**:
|
||||
- ⚠️ Higher GPU memory (12B vs 7B)
|
||||
- ⚠️ Need to verify model compatibility
|
||||
|
||||
**Complexity**: Low
|
||||
**Risk**: Low
|
||||
|
||||
---
|
||||
|
||||
### Option 3: Asynchronous Processing
|
||||
|
||||
**Implementation**:
|
||||
```rust
|
||||
// Spawn in background, don't wait
|
||||
tokio::spawn(async move {
|
||||
generate_vlm_summaries(&db, uuid, output_dir, redis).await;
|
||||
});
|
||||
|
||||
// Pipeline continues immediately
|
||||
// FS VLM runs in background
|
||||
```
|
||||
|
||||
**Expected Performance**:
|
||||
- Pipeline completion: Immediate
|
||||
- FS VLM: Still 88s, but non-blocking
|
||||
- User experience: Much better
|
||||
|
||||
**Pros**:
|
||||
- ✅ No blocking
|
||||
- ✅ Pipeline completes fast
|
||||
- ✅ User can see progress
|
||||
|
||||
**Cons**:
|
||||
- ⚠️ FS VLM still slow
|
||||
- ⚠️ Need progress tracking
|
||||
- ⚠️ Error handling more complex
|
||||
|
||||
**Complexity**: Low
|
||||
**Risk**: Low
|
||||
|
||||
---
|
||||
|
||||
### Option 4: Batch Processing
|
||||
|
||||
**Implementation**:
|
||||
```rust
|
||||
// Combine multiple traces into one VLM call
|
||||
let batch_prompt = format!(
|
||||
"Analyze these {} key frames and describe each:",
|
||||
traces.len()
|
||||
);
|
||||
|
||||
// Single VLM call with multiple images
|
||||
call_llm_vision_batch(images, batch_prompt).await;
|
||||
```
|
||||
|
||||
**Expected Performance**:
|
||||
- Network overhead: Reduced
|
||||
- VLM calls: 22 → 1-3
|
||||
- Total time: **~10-15s**
|
||||
|
||||
**Pros**:
|
||||
- ✅ Reduced network overhead
|
||||
- ✅ Fewer VLM calls
|
||||
|
||||
**Cons**:
|
||||
- ❌ Complex prompt engineering
|
||||
- ❌ Risk of lower quality
|
||||
- ❌ Need to parse batch response
|
||||
|
||||
**Complexity**: Medium
|
||||
**Risk**: Medium
|
||||
|
||||
---
|
||||
|
||||
### Option 5: Smart Filtering
|
||||
|
||||
**Implementation**:
|
||||
```rust
|
||||
// Skip traces that don't need VLM
|
||||
let skip_conditions = vec![
|
||||
frame_count == 1, // Single frame
|
||||
trace_duration < 1.0, // Too short
|
||||
confidence < 0.7, // Low confidence
|
||||
is_blurry, // Poor quality
|
||||
];
|
||||
|
||||
// Only process meaningful traces
|
||||
let filtered: Vec<_> = traces.into_iter()
|
||||
.filter(|t| !skip_any(t))
|
||||
.collect();
|
||||
```
|
||||
|
||||
**Expected Performance**:
|
||||
- 22 traces → **~10-15 traces** (40-50% reduction)
|
||||
- Time: 88s → **~40-60s**
|
||||
|
||||
**Pros**:
|
||||
- ✅ Reduces unnecessary work
|
||||
- ✅ Better resource utilization
|
||||
|
||||
**Cons**:
|
||||
- ⚠️ Need tuning heuristics
|
||||
- ⚠️ May miss important traces
|
||||
|
||||
**Complexity**: Low
|
||||
**Risk**: Low
|
||||
|
||||
---
|
||||
|
||||
## Recommended Strategy
|
||||
|
||||
### Phase 1: Quick Wins (1-2 hours)
|
||||
|
||||
1. **Enable Gemma4** (✅ Fastest to implement)
|
||||
- Update `.env`: `MOMENTRY_LLM_VISION_URL=http://localhost:8080`
|
||||
- Result: **2x speedup**
|
||||
|
||||
2. **Async Processing** (✅ Best UX improvement)
|
||||
- Spawn in background
|
||||
- Don't block pipeline
|
||||
- Result: **Immediate completion**
|
||||
|
||||
### Phase 2: Parallel Processing (2-4 hours)
|
||||
|
||||
3. **Parallel Execution**
|
||||
- Max 5-10 concurrent
|
||||
- Result: **5-10x speedup**
|
||||
|
||||
4. **Combined**:
|
||||
- Gemma4 + Parallel = **10-20x total speedup**
|
||||
- 22 traces: 88s → **4-9s**
|
||||
|
||||
### Phase 3: Optimization (Optional)
|
||||
|
||||
5. **Smart Filtering**
|
||||
- Skip unnecessary traces
|
||||
- Further 40-50% reduction
|
||||
|
||||
## Implementation Plan
|
||||
|
||||
### Step 1: Gemma4 Migration
|
||||
|
||||
**File**: `/Users/accusys/momentry_core/.env`
|
||||
```bash
|
||||
# Current
|
||||
MOMENTRY_LLM_VISION_URL=http://localhost:8091
|
||||
MOMENTRY_LLM_VISION_MODEL=llava-v1.5-7b
|
||||
|
||||
# Change to
|
||||
MOMENTRY_LLM_VISION_URL=http://localhost:8080
|
||||
MOMENTRY_LLM_VISION_MODEL=gemma-4-12b-it
|
||||
```
|
||||
|
||||
**Testing**:
|
||||
```bash
|
||||
# Test single trace
|
||||
curl -X POST http://localhost:8080/v1/chat/completions \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{"model":"gemma-4-12b-it","messages":[...]}'
|
||||
```
|
||||
|
||||
### Step 2: Async Processing
|
||||
|
||||
**File: `/Users/accusys/momentry_core/src/worker/job_worker.rs`
|
||||
|
||||
```rust
|
||||
// Current (blocking)
|
||||
let vlm_done_bool: bool = if vlm_total > 0 {
|
||||
vlm_done_count >= vlm_total
|
||||
} else {
|
||||
true
|
||||
};
|
||||
|
||||
// Proposed (non-blocking)
|
||||
let vlm_done_bool = true; // Skip check
|
||||
if vlm_total > 0 && vlm_done_count < vlm_total {
|
||||
// Spawn in background
|
||||
tokio::spawn(async move {
|
||||
generate_vlm_summaries(&db, uuid, output_dir, redis).await;
|
||||
});
|
||||
}
|
||||
```
|
||||
|
||||
### Step 3: Parallel Processing
|
||||
|
||||
**File: `/Users/accusys/momentry_core/src/core/processor/vlm_summary.rs`
|
||||
|
||||
```rust
|
||||
use futures::stream::{self, StreamExt};
|
||||
|
||||
let results: Vec<_> = stream::iter(trace_ids)
|
||||
.map(|&trace_id| {
|
||||
let db = db.clone();
|
||||
let file_uuid = file_uuid.to_string();
|
||||
let output_dir = output_dir.to_string();
|
||||
async move {
|
||||
process_single_trace(&db, &file_uuid, trace_id, &output_dir, 0, 0).await
|
||||
}
|
||||
})
|
||||
.buffer_unordered(5) // Max 5 concurrent
|
||||
.collect()
|
||||
.await;
|
||||
|
||||
// Aggregate results
|
||||
let (summarized, embedded, errors) = results.into_iter()
|
||||
.filter_map(|r| r.ok())
|
||||
.fold((0, 0, 0), |acc, (s, e)| (acc.0 + s as usize, acc.1 + e as usize, acc.2));
|
||||
```
|
||||
|
||||
## Risk Assessment
|
||||
|
||||
| Risk | Likelihood | Impact | Mitigation |
|
||||
|------|-----------|--------|-----------|
|
||||
| GPU OOM (parallel) | Medium | High | Limit concurrency to 5 |
|
||||
| Gemma4 quality issues | Low | Medium | Test with sample images |
|
||||
| Async error handling | Low | Medium | Add retry logic |
|
||||
| Memory leak | Low | Low | Monitor worker process |
|
||||
|
||||
## Performance Targets
|
||||
|
||||
| Scenario | Current | Target | Improvement |
|
||||
|----------|---------|--------|-------------|
|
||||
| 22 traces (sequential) | 88s | N/A | - |
|
||||
| 22 traces (Gemma4) | 44s | 44s | 2x |
|
||||
| 22 traces (Gemma4 + parallel) | - | **9s** | **10x** |
|
||||
| 22 traces (async) | - | **0s (blocking)** | Immediate |
|
||||
|
||||
## Success Metrics
|
||||
|
||||
1. **Pipeline completion time**: < 10 seconds (after processors)
|
||||
2. **FS VLM completion time**: < 15 seconds (22 traces)
|
||||
3. **User experience**: No "waiting for ingestion"
|
||||
4. **Resource usage**: GPU memory < 16GB
|
||||
|
||||
## Timeline
|
||||
|
||||
- **Phase 1** (Gemma4 + async): 2-4 hours
|
||||
- **Phase 2** (Parallel): 4-8 hours
|
||||
- **Phase 3** (Optimization): Optional
|
||||
|
||||
**Total**: 6-12 hours
|
||||
|
||||
## Conclusion
|
||||
|
||||
**Recommendation**: Implement Phase 1 immediately, then Phase 2.
|
||||
|
||||
**Expected Result**:
|
||||
- Pipeline: Completes immediately
|
||||
- FS VLM: 9-15 seconds for 22 traces (10x improvement)
|
||||
- User experience: Significantly better
|
||||
|
||||
**Decision**: Ready to implement with low risk and high impact.
|
||||
|
||||
---
|
||||
|
||||
## Appendix: Benchmarks
|
||||
|
||||
### Test Setup
|
||||
- Hardware: Apple Silicon M3 Max
|
||||
- GPU Memory: 48GB
|
||||
- Model: Gemma4 12B Q4_K_M
|
||||
- Test file: IMG_9449.mp4 (22 face traces)
|
||||
|
||||
### Results (Projected)
|
||||
|
||||
| Configuration | Time | Speedup |
|
||||
|---------------|------|---------|
|
||||
| Sequential + LLaVA | 88s | 1x |
|
||||
| Sequential + Gemma4 | 44s | 2x |
|
||||
| Parallel (5) + LLaVA | 18s | 5x |
|
||||
| Parallel (5) + Gemma4 | **9s** | **10x** |
|
||||
| Parallel (10) + Gemma4 | **5s** | **18x** |
|
||||
|
||||
### Resource Usage
|
||||
|
||||
| Mode | GPU Memory | CPU | Network |
|
||||
|------|-----------|-----|---------|
|
||||
| Sequential | 6GB | 10% | Low |
|
||||
| Parallel (5) | 10GB | 30% | Medium |
|
||||
| Parallel (10) | 14GB | 50% | High |
|
||||
@@ -0,0 +1,248 @@
|
||||
---
|
||||
title: Face Clustering Config Unification
|
||||
version: 1.0
|
||||
date: 2026-10-01
|
||||
author: OpenCode
|
||||
status: draft
|
||||
---
|
||||
|
||||
## 概述
|
||||
|
||||
統一 Face Clustering 的配置管理,解決當前三處配置不一致的問題。
|
||||
|
||||
---
|
||||
|
||||
## 當前問題
|
||||
|
||||
### 配置分散
|
||||
|
||||
| 位置 | 當前狀態 | 問題 |
|
||||
|------|---------|------|
|
||||
| Rust Binary | `default_value_t = 0.15` | ✅ 已修復 |
|
||||
| Python Script | `CLUSTER_THRESHOLD = 0.15` | ✅ 已修復 |
|
||||
| Rust Worker | `unwrap_or(0.85)` | ✅ 已修復 |
|
||||
|
||||
**問題**: 三處獨立維護,容易不一致
|
||||
|
||||
---
|
||||
|
||||
## 解決方案
|
||||
|
||||
### 方案 1: 統一常量 (推薦)
|
||||
|
||||
**優點**:
|
||||
- 編譯時檢查
|
||||
- 不易出錯
|
||||
- 性能好
|
||||
|
||||
**實現**:
|
||||
|
||||
```rust
|
||||
// src/core/config.rs
|
||||
|
||||
/// Face clustering threshold (similarity)
|
||||
/// Higher = more strict (require higher similarity to cluster together)
|
||||
/// Range: 0.0 - 1.0
|
||||
/// Recommended: 0.85 for general use, 0.90 for strict dedup
|
||||
pub const FACE_CLUSTER_SIMILARITY_THRESHOLD: f64 = 0.85;
|
||||
|
||||
/// Face clustering distance threshold
|
||||
/// Lower = more strict (require smaller distance to cluster together)
|
||||
/// This is 1.0 - SIMILARITY_THRESHOLD
|
||||
pub const FACE_CLUSTER_DISTANCE_THRESHOLD: f64 = 1.0 - FACE_CLUSTER_SIMILARITY_THRESHOLD;
|
||||
```
|
||||
|
||||
**使用**:
|
||||
|
||||
```rust
|
||||
// src/core/processor/face_clustering.rs
|
||||
use crate::core::config::{FACE_CLUSTER_SIMILARITY_THRESHOLD, FACE_CLUSTER_DISTANCE_THRESHOLD};
|
||||
|
||||
let threshold = similarity_threshold.unwrap_or(FACE_CLUSTER_SIMILARITY_THRESHOLD);
|
||||
let distance = 1.0 - threshold;
|
||||
```
|
||||
|
||||
```rust
|
||||
// tools/cli/rust/src/bin/rust_face_cluster.rs
|
||||
use momentry_core::config::FACE_CLUSTER_DISTANCE_THRESHOLD;
|
||||
|
||||
#[arg(long = "threshold", default_value_t = FACE_CLUSTER_DISTANCE_THRESHOLD)]
|
||||
threshold: f64,
|
||||
```
|
||||
|
||||
```python
|
||||
# scripts/face_clustering_processor.py
|
||||
import os
|
||||
|
||||
# 從環境變數讀取,如果沒有則使用 Rust 的默認值
|
||||
CLUSTER_THRESHOLD = float(os.getenv("MOMENTRY_FACE_CLUSTER_THRESHOLD", "0.15"))
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 方案 2: 環境變數
|
||||
|
||||
**優點**:
|
||||
- 可以動態調整
|
||||
- 不需要重新編譯
|
||||
|
||||
**缺點**:
|
||||
- 需要確保所有組件都讀取
|
||||
- 運行時錯誤
|
||||
|
||||
**實現**:
|
||||
|
||||
```bash
|
||||
# .env
|
||||
MOMENTRY_FACE_CLUSTER_THRESHOLD=0.15
|
||||
```
|
||||
|
||||
```rust
|
||||
// src/core/config.rs
|
||||
pub fn face_cluster_threshold() -> f64 {
|
||||
std::env::var("MOMENTRY_FACE_CLUSTER_THRESHOLD")
|
||||
.ok()
|
||||
.and_then(|s| s.parse().ok())
|
||||
.unwrap_or(0.15)
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 方案 3: 配置文件
|
||||
|
||||
**優點**:
|
||||
- 集中管理
|
||||
- 可視化
|
||||
|
||||
**缺點**:
|
||||
- 需要解析
|
||||
- 可能失敗
|
||||
|
||||
**實現**:
|
||||
|
||||
```json
|
||||
// config/face_cluster.json
|
||||
{
|
||||
"threshold": {
|
||||
"similarity": 0.85,
|
||||
"distance": 0.15
|
||||
},
|
||||
"method": "leader",
|
||||
"min_faces_per_trace": 1
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 推薦方案
|
||||
|
||||
**方案 1 (統一常量)** + **方案 2 (環境變數覆蓋)**
|
||||
|
||||
**理由**:
|
||||
1. 默認值使用常量,確保一致性
|
||||
2. 環境變數可以覆蓋,提供靈活性
|
||||
3. 不需要配置文件解析,減少失敗點
|
||||
|
||||
---
|
||||
|
||||
## 實現步驟
|
||||
|
||||
### Step 1: 添加統一常量
|
||||
|
||||
```rust
|
||||
// src/core/config.rs
|
||||
pub const FACE_CLUSTER_SIMILARITY_THRESHOLD: f64 = 0.85;
|
||||
pub const FACE_CLUSTER_DISTANCE_THRESHOLD: f64 = 0.15;
|
||||
```
|
||||
|
||||
### Step 2: 修改 Rust Worker
|
||||
|
||||
```rust
|
||||
// src/core/processor/face_clustering.rs
|
||||
use crate::core::config::FACE_CLUSTER_SIMILARITY_THRESHOLD;
|
||||
|
||||
let threshold = similarity_threshold
|
||||
.or_else(|| std::env::var("MOMENTRY_FACE_CLUSTER_THRESHOLD")
|
||||
.ok()
|
||||
.and_then(|s| s.parse().ok())
|
||||
.map(|d: f64| 1.0 - d))
|
||||
.unwrap_or(FACE_CLUSTER_SIMILARITY_THRESHOLD);
|
||||
```
|
||||
|
||||
### Step 3: 修改 Rust Binary
|
||||
|
||||
```rust
|
||||
// tools/cli/rust/src/bin/rust_face_cluster.rs
|
||||
use momentry_core::config::FACE_CLUSTER_DISTANCE_THRESHOLD;
|
||||
|
||||
#[arg(long = "threshold", default_value_t = FACE_CLUSTER_DISTANCE_THRESHOLD)]
|
||||
threshold: f64,
|
||||
```
|
||||
|
||||
### Step 4: 修改 Python Script
|
||||
|
||||
```python
|
||||
# scripts/face_clustering_processor.py
|
||||
import os
|
||||
|
||||
CLUSTER_THRESHOLD = float(os.getenv("MOMENTRY_FACE_CLUSTER_THRESHOLD", "0.15"))
|
||||
```
|
||||
|
||||
### Step 5: 添加環境變數
|
||||
|
||||
```bash
|
||||
# .env
|
||||
MOMENTRY_FACE_CLUSTER_THRESHOLD=0.15
|
||||
```
|
||||
|
||||
### Step 6: 添加文檔
|
||||
|
||||
```markdown
|
||||
# docs_v1.0/GUIDES/Face_Clustering_Configuration.md
|
||||
|
||||
## Threshold 說明
|
||||
|
||||
- **相似度閾值 (Similarity Threshold)**: 0.0 - 1.0
|
||||
- 越高越嚴格(需要更高相似度才能聚類)
|
||||
- 推薦值: 0.85 (一般用途), 0.90 (嚴格去重)
|
||||
|
||||
- **距離閾值 (Distance Threshold)**: 0.0 - 1.0
|
||||
- 越低越嚴格(需要更小距離才能聚類)
|
||||
- 計算方式: distance = 1.0 - similarity
|
||||
- 推薦值: 0.15 (一般用途), 0.10 (嚴格去重)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 驗證計劃
|
||||
|
||||
### 單元測試
|
||||
|
||||
```rust
|
||||
#[test]
|
||||
fn test_threshold_consistency() {
|
||||
assert_eq!(
|
||||
FACE_CLUSTER_DISTANCE_THRESHOLD,
|
||||
1.0 - FACE_CLUSTER_SIMILARITY_THRESHOLD
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
### 集成測試
|
||||
|
||||
```bash
|
||||
# 測試默認值
|
||||
./tools/cli/rust/target/release/rust_face_cluster --help | grep threshold
|
||||
|
||||
# 測試環境變數覆蓋
|
||||
MOMENTRY_FACE_CLUSTER_THRESHOLD=0.10 ./target/debug/momentry worker --test
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 版本歷史
|
||||
|
||||
| 版本 | 日期 | 變更 |
|
||||
|------|------|------|
|
||||
| 1.0 | 2026-10-01 | 初始版本 |
|
||||
@@ -0,0 +1,339 @@
|
||||
# Face-Pose-Appearance Tracking Design
|
||||
|
||||
**Version**: 1.0
|
||||
**Date**: 2026-07-19
|
||||
**Status**: Ready for Implementation
|
||||
|
||||
---
|
||||
|
||||
## 1. Overview
|
||||
|
||||
本文件定義 Face、Pose、Appearance 的追蹤系統設計,包含:
|
||||
- Trace ID 繼承規則
|
||||
- 擴張邏輯
|
||||
- Appearance 色塊提取
|
||||
- Agent Search 整合
|
||||
|
||||
---
|
||||
|
||||
## 2. Core Concepts
|
||||
|
||||
### 2.1 Identity vs Tracking
|
||||
|
||||
| Processor | Purpose | Description |
|
||||
|-----------|---------|-------------|
|
||||
| **Face** | Identity | Who is this person? 需要高品質 embedding |
|
||||
| **Pose** | Tracking | Where is this person? 當 face occluded 時維持追蹤 |
|
||||
| **Appearance** | Tracking | What do they look like? 當 pose occluded 時維持追蹤 |
|
||||
|
||||
### 2.2 Offline Processing Advantage
|
||||
|
||||
Offline 處理可以先做 face detection,再從 face traces 擴張 pose/appearance:
|
||||
|
||||
```
|
||||
Face Detection → 知道身份錨點
|
||||
↓
|
||||
Face Tracking → 給予 trace_id
|
||||
↓
|
||||
Pose Expansion → 從 face traces 向外擴張
|
||||
↓
|
||||
Appearance Expansion → 從 pose traces 向外擴張
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 3. Processing Pipeline
|
||||
|
||||
### 3.1 Pipeline Order
|
||||
|
||||
| Order | Processor | Dependencies | Output | Description |
|
||||
|-------|-----------|-------------|--------|-------------|
|
||||
| 1 | `cut` | — | cut.json | Scene detection |
|
||||
| 2 | `face` | — | face.json | Face detection (8Hz) + embedding |
|
||||
| 3 | `face_trace` | face | face_traced.json | Face tracking (IoU + embedding) |
|
||||
| 4 | `pose` | face_trace | pose.json | Pose expansion from traces |
|
||||
| 5 | `appearance` | pose | appearance.json | Appearance extraction |
|
||||
| 6 | `asr` | cut | asr.json | Speech-to-text |
|
||||
| 7 | `asrx` | asr | asrx.json | Speaker diarization |
|
||||
|
||||
### 3.2 Sampling Rate
|
||||
|
||||
- **公式**: `sample_interval = floor(fps / 8)`
|
||||
- **確保**: ≥ 8Hz 取樣率
|
||||
- **範例**:
|
||||
- 24fps → interval = 3 → 8Hz
|
||||
- 30fps → interval = 3 → 10Hz
|
||||
- 60fps → interval = 7 → 8.6Hz
|
||||
|
||||
---
|
||||
|
||||
## 4. Trace ID Inheritance
|
||||
|
||||
### 4.1 Inheritance Chain
|
||||
|
||||
```
|
||||
Face Trace (identity anchor)
|
||||
│ trace_id = 1, 2, 3, ...
|
||||
│
|
||||
▼ inherits trace_id
|
||||
Pose Expansion
|
||||
│ same trace_id per person
|
||||
│
|
||||
▼ inherits trace_id
|
||||
Appearance Expansion
|
||||
│ same trace_id per person
|
||||
```
|
||||
|
||||
### 4.2 Frame Count Relationship
|
||||
|
||||
```
|
||||
face_frames ≤ pose_frames ≤ appearance_frames
|
||||
```
|
||||
|
||||
**原因**:
|
||||
- Face: 只有臉部可見的 frames
|
||||
- Pose: Face frames + 擴張 frames(臉被遮但身體可見)
|
||||
- Appearance: Pose frames + 擴張 frames
|
||||
|
||||
### 4.3 Trace Connection
|
||||
|
||||
```
|
||||
Face trace A (frames 1-10) Face trace B (frames 20-30)
|
||||
↘ ↙
|
||||
Pose 連接 (frames 15-18)
|
||||
(同一人,中間臉被遮住)
|
||||
```
|
||||
|
||||
**意義**: Pose 可以連接斷開的 face traces,屬於同一人。
|
||||
|
||||
---
|
||||
|
||||
## 5. Expansion Rules
|
||||
|
||||
### 5.1 Pose Expansion
|
||||
|
||||
**Algorithm**:
|
||||
1. 讀取 face_traced.json,取得每個 trace_id 的 frames
|
||||
2. 對每個 trace 的 frames 向外擴張(逐幀檢查)
|
||||
3. 連續 3 幀無 pose detection → 停止擴張
|
||||
4. 繼承 trace_id
|
||||
5. 輸出 8Hz 取樣
|
||||
|
||||
**Parameters**:
|
||||
|
||||
| Parameter | Value | Description |
|
||||
|-----------|-------|-------------|
|
||||
| `miss_threshold` | 3 | 連續無檢測幀數 |
|
||||
| `output_rate` | 8Hz | 輸出取樣率 |
|
||||
|
||||
### 5.2 Appearance Expansion
|
||||
|
||||
**Algorithm**:
|
||||
1. 讀取 pose.json,取得每個 trace_id 的 frames
|
||||
2. 對每個 pose frame,在 keypoint 位置提取顏色
|
||||
3. 記錄整體亮度
|
||||
4. 輸出 8Hz 取樣
|
||||
|
||||
**Parameters**:
|
||||
|
||||
| Parameter | Value | Description |
|
||||
|-----------|-------|-------------|
|
||||
| `color_radius` | 15 | 顏色取樣半徑(pixels) |
|
||||
| `output_rate` | 8Hz | 輸出取樣率 |
|
||||
|
||||
---
|
||||
|
||||
## 6. Pose Output
|
||||
|
||||
### 6.1 Data Structure
|
||||
|
||||
```json
|
||||
{
|
||||
"frame_count": 1000,
|
||||
"fps": 24.0,
|
||||
"frames": [
|
||||
{
|
||||
"frame": 100,
|
||||
"timestamp": 4.16,
|
||||
"trace_id": 1,
|
||||
"persons": [
|
||||
{
|
||||
"keypoints": [
|
||||
{"name": "nose", "x": 315.9, "y": 364.2, "confidence": 0.85},
|
||||
{"name": "left_shoulder", "x": 290.0, "y": 400.0, "confidence": 0.92}
|
||||
],
|
||||
"bbox": {"x": 280, "y": 350, "width": 100, "height": 200}
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
### 6.2 Bbox Validation
|
||||
|
||||
**原則**: Face bbox 應在 Pose bbox 內,或 IoU > 0.5
|
||||
|
||||
```
|
||||
┌─────────────────────────┐
|
||||
│ Pose bbox │
|
||||
│ ┌─────────┐ │
|
||||
│ │ Face │ │
|
||||
│ │ bbox │ │
|
||||
│ └─────────┘ │
|
||||
└─────────────────────────┘
|
||||
```
|
||||
|
||||
**用途**:
|
||||
- 品質驗證:確保 pose/face 屬於同一人
|
||||
- 匹配追蹤:用 bbox overlap 匹配 face/pose
|
||||
|
||||
---
|
||||
|
||||
## 7. Appearance Output
|
||||
|
||||
### 7.1 Keypoint-based Color Extraction
|
||||
|
||||
**原理**: 在 pose keypoint 位置取周圍平均色
|
||||
|
||||
```
|
||||
Pose Keypoints 座標
|
||||
↓
|
||||
在每個 keypoint 位置取色
|
||||
↓
|
||||
記錄為 appearance
|
||||
```
|
||||
|
||||
### 7.2 Body Part Mapping
|
||||
|
||||
| Keypoints | Body Part | Description |
|
||||
|-----------|-----------|-------------|
|
||||
| nose, eyes, ears | head | 帽子、頭髮顏色 |
|
||||
| shoulders | torso | 上衣顏色 |
|
||||
| hips, knees | legs | 褲子顏色 |
|
||||
| ankles | feet | 鞋子顏色 |
|
||||
|
||||
### 7.3 Data Structure
|
||||
|
||||
```json
|
||||
{
|
||||
"frame_count": 1000,
|
||||
"fps": 24.0,
|
||||
"frames": [
|
||||
{
|
||||
"frame": 100,
|
||||
"timestamp": 4.16,
|
||||
"trace_id": 1,
|
||||
"brightness": 0.75,
|
||||
"colors": {
|
||||
"head": [180, 150, 120],
|
||||
"torso": [255, 50, 50],
|
||||
"legs": [50, 50, 200],
|
||||
"feet": [50, 200, 50]
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
### 7.4 Lighting Record
|
||||
|
||||
```json
|
||||
{
|
||||
"brightness": 0.75
|
||||
}
|
||||
```
|
||||
|
||||
**用途**: 不同光源下的顏色校正
|
||||
|
||||
---
|
||||
|
||||
## 8. VLM Complementary Strategy
|
||||
|
||||
### 8.1 Two-Level Approach
|
||||
|
||||
| Level | Method | Purpose |
|
||||
|-------|--------|---------|
|
||||
| **L1** | Keypoint 快取色 | 快速搜尋、初步候選 |
|
||||
| **L2** | VLM 驗證 | 複雜情況、細節補充(可選) |
|
||||
|
||||
### 8.2 Workflow
|
||||
|
||||
```
|
||||
搜尋「穿紅上衣的人」
|
||||
↓
|
||||
L1: Keypoint 取色搜尋 → Top 20 候選
|
||||
↓
|
||||
L2: VLM 驗證(需要時)→ 確認顏色、補充細節
|
||||
↓
|
||||
最終結果 → Top 10 + 置信度
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 9. Agent Search Integration
|
||||
|
||||
### 9.1 Agent Tool Design
|
||||
|
||||
```python
|
||||
def search_by_appearance(
|
||||
color: str, # "red", "blue", "green"
|
||||
body_part: str, # "torso", "legs", "feet"
|
||||
top_k: int = 10
|
||||
) -> List[SearchResult]:
|
||||
"""
|
||||
搜尋穿特定顏色衣物的人
|
||||
|
||||
Returns:
|
||||
[
|
||||
{"trace_id": 1, "identity": "John", "confidence": 0.85},
|
||||
{"trace_id": 2, "identity": "Mary", "confidence": 0.72},
|
||||
]
|
||||
"""
|
||||
```
|
||||
|
||||
### 9.2 Query Examples
|
||||
|
||||
| User Query | Agent Action |
|
||||
|------------|--------------|
|
||||
| 「穿紅上衣的人是誰?」 | search_by_appearance("red", "torso") → match identity |
|
||||
| 「穿綠鞋子的人」 | search_by_appearance("green", "feet") |
|
||||
| 「戴黑帽子的人」 | search_by_appearance("black", "head") |
|
||||
|
||||
### 9.3 Top-K Strategy
|
||||
|
||||
- **原則**: 找 top 10-20 最相似的
|
||||
- **容許誤差**: 光源、角度差異可接受
|
||||
- **近似即可**: 不需精確匹配
|
||||
|
||||
---
|
||||
|
||||
## 10. Implementation Files
|
||||
|
||||
| Component | File | Status |
|
||||
|-----------|------|--------|
|
||||
| Face Detection | `swift_face.swift` | ✅ Complete |
|
||||
| Face Tracking | `store_traced_faces.py` | ✅ Complete |
|
||||
| Pose Expansion | `swift_pose_expansion.swift` | ✅ Complete |
|
||||
| Appearance Expansion | `swift_appearance_expansion.swift` | ✅ Complete |
|
||||
| Pose Processor | `pose_processor_v2.py` | ✅ Complete |
|
||||
| Appearance Processor | `appearance_processor_v2.py` | ✅ Complete |
|
||||
|
||||
---
|
||||
|
||||
## 11. Testing Checklist
|
||||
|
||||
- [ ] 清除測試檔案重新註冊
|
||||
- [ ] 執行完整流程:face → trace → pose → appearance
|
||||
- [ ] 驗證 trace_id 繼承正確性
|
||||
- [ ] 驗證 frame count 關係 (face ≤ pose ≤ appearance)
|
||||
- [ ] 驗證 bbox 包含關係 (face bbox ⊂ pose bbox)
|
||||
- [ ] 測試 Agent search_by_appearance
|
||||
|
||||
---
|
||||
|
||||
## 12. Version History
|
||||
|
||||
| Version | Date | Changes |
|
||||
|---------|------|---------|
|
||||
| 1.0 | 2026-07-19 | Initial design |
|
||||
@@ -0,0 +1,538 @@
|
||||
---
|
||||
title: Identity Agent V2.0 Redesign
|
||||
version: 2.0
|
||||
date: 2026-07-15
|
||||
author: OpenCode
|
||||
status: Draft
|
||||
---
|
||||
|
||||
# Identity Agent V2.0 重新設計
|
||||
|
||||
## 1. 概述
|
||||
|
||||
### 目的
|
||||
將 face trace 與 seed photos 透過 Qdrant 向量比對,建立 pending people 綁定建議,由用戶確認後升級為 known people。
|
||||
|
||||
### 核心原則
|
||||
|
||||
| 原則 | 說明 |
|
||||
|------|------|
|
||||
| **只綁定,不確認** | Identity Agent 只建立 suggested 綁定,不升級為 confirmed |
|
||||
| **所有綁定都需確認** | 即使 matching 的是已知人物(known people),也要建立 pending 綁定 |
|
||||
| **用戶決定** | 每個新綁定都需要用戶在 UI 上點擊確認 |
|
||||
| **多重綁定** | 一個 trace 可同時匹配多個 seeds,都記錄為建議 |
|
||||
|
||||
### 流程圖
|
||||
|
||||
```
|
||||
┌─────────────────────────────────────────────────────────────┐
|
||||
│ Identity Agent V2.0 │
|
||||
├─────────────────────────────────────────────────────────────┤
|
||||
│ │
|
||||
│ Data Stores: │
|
||||
│ ├─ Qdrant _faces (512D, trace-level faces) │
|
||||
│ ├─ Qdrant _seeds (512D, seed photos per file_uuid) │
|
||||
│ ├─ PG identities (metadata: name, tmdb_id, status) │
|
||||
│ └─ PG tkg_nodes (face_track, status + suggestions) │
|
||||
│ │
|
||||
│ Flow: │
|
||||
│ 1. TMDb/Upload/Name → Seeds (_seeds collection) │
|
||||
│ 2. Identity Agent → Match _seeds vs _faces │
|
||||
│ 3. Write suggestions → TKG + Qdrant (suggested) │
|
||||
│ 4. User Confirm → status = confirmed │
|
||||
│ 5. User Reject → status = stranger │
|
||||
│ │
|
||||
│ Rules: │
|
||||
│ - All bindings start as "suggested" │
|
||||
│ - Even known people get new pending bindings │
|
||||
│ - Multiple suggestions per trace allowed │
|
||||
│ - User confirms each binding individually │
|
||||
│ │
|
||||
└─────────────────────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 2. 種子管理
|
||||
|
||||
### 種子來源
|
||||
|
||||
| 來源 | 觸發方式 | file_uuid 綁定 |
|
||||
|------|----------|---------------|
|
||||
| TMDb probe | 檔案註冊時自動探測 | 探測檔案的 uuid |
|
||||
| 用戶上傳照片 | UI 上傳 face photo | 當前查看檔案的 uuid |
|
||||
| Pending Face 命名 | 選擇 trace 並命名 | 該 face 所在檔案的 uuid |
|
||||
|
||||
### Qdrant _seeds 結構
|
||||
|
||||
```json
|
||||
{
|
||||
"vector": [512 floats],
|
||||
"payload": {
|
||||
"identity_id": 3,
|
||||
"identity_uuid": "69e50666-0c2d-4215-968b-d1fdd820fb7d",
|
||||
"name": "Walter Matthau",
|
||||
"source": "tmdb",
|
||||
"file_uuid": "4bb70f2b0d6d9c1a2900298666189a73",
|
||||
"tmdb_id": 3490,
|
||||
"status": "confirmed",
|
||||
"angles": [
|
||||
{"frame": 100, "embedding": [...]},
|
||||
{"frame": 150, "embedding": [...]}
|
||||
]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### 種子產生流程
|
||||
|
||||
```
|
||||
TMDb Probe
|
||||
→ 下載演員照片
|
||||
→ 提取 face embedding
|
||||
→ Push to _seeds (file_uuid 綁定)
|
||||
|
||||
用戶上傳
|
||||
→ 上傳照片
|
||||
→ 檢測 face + 提取 embedding
|
||||
→ Push to _seeds (file_uuid 綁定)
|
||||
|
||||
Pending Face 命名
|
||||
→ 選擇 trace
|
||||
→ 輸入名稱
|
||||
→ 從 trace 提取 representative embedding
|
||||
→ Push to _seeds (file_uuid 綁定)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 3. 匹配流程
|
||||
|
||||
### 匹配閾值
|
||||
|
||||
| Round | Threshold | Seed Source |
|
||||
|-------|-----------|-------------|
|
||||
| Round 1 | 0.55 | TMDb seeds |
|
||||
| Round 2 | 0.55 | Confirmed traces (propagation) |
|
||||
| Round 3+ | 0.50 | More confirmed traces |
|
||||
| Stranger | 0.40 | Unmatched traces (clustering) |
|
||||
|
||||
### 匹配邏輯
|
||||
|
||||
```python
|
||||
def match_faces_round_1(file_uuid: str) -> dict:
|
||||
"""
|
||||
Returns: {trace_id: [suggestions]}
|
||||
每個 trace 可有多個 suggestions(多重綁定)
|
||||
"""
|
||||
traces = get_trace_representatives(file_uuid)
|
||||
seeds = get_seeds(file_uuid=file_uuid) # 只查該檔案的 seeds
|
||||
|
||||
suggestions = {}
|
||||
|
||||
for trace_id, reps in traces.items():
|
||||
trace_suggestions = []
|
||||
|
||||
for seed in seeds:
|
||||
score = multi_angle_match(seed["embedding"], reps)
|
||||
if score >= TH_ROUND_1:
|
||||
trace_suggestions.append({
|
||||
"identity_id": seed["identity_id"],
|
||||
"identity_uuid": seed["identity_uuid"],
|
||||
"name": seed["name"],
|
||||
"score": round(score, 4),
|
||||
"source": seed["source"],
|
||||
"is_known": seed.get("status") == "confirmed"
|
||||
})
|
||||
|
||||
if trace_suggestions:
|
||||
trace_suggestions.sort(key=lambda x: x["score"], reverse=True)
|
||||
suggestions[trace_id] = trace_suggestions
|
||||
|
||||
return suggestions
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 4. 多重綁定
|
||||
|
||||
### 設計原則
|
||||
|
||||
一個 face trace 可以同時匹配多個 seeds(分數都很高),所有匹配都記錄為建議,由用戶決定選擇哪一個。
|
||||
|
||||
### 範例
|
||||
|
||||
```
|
||||
Trace #432 (7 frames, confidence: 0.83)
|
||||
├─ Walter Matthau (58.6%) ← is_known: true
|
||||
├─ George Kennedy (57.2%) ← is_known: true
|
||||
└─ [Not yet assigned]
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 5. 資料儲存
|
||||
|
||||
### Qdrant _faces payload(多重綁定)
|
||||
|
||||
```json
|
||||
{
|
||||
"file_uuid": "9f880a88e9f027255714906d84865fd4",
|
||||
"trace_id": 432,
|
||||
"frame": 13494,
|
||||
"confidence": 0.829,
|
||||
"bbox": {"x": 272, "y": 38, "width": 87, "height": 87},
|
||||
|
||||
"identity_id": null,
|
||||
"identity_uuid": null,
|
||||
|
||||
"suggestions": [
|
||||
{"identity_id": 3, "identity_uuid": "69e50666...", "name": "Walter Matthau", "score": 0.586, "source": "tmdb", "is_known": true},
|
||||
{"identity_id": 5, "identity_uuid": "102e8ed0...", "name": "George Kennedy", "score": 0.572, "source": "tmdb", "is_known": true}
|
||||
],
|
||||
"suggested_by": "tmdb"
|
||||
}
|
||||
```
|
||||
|
||||
### TKG face_track properties(多重綁定)
|
||||
|
||||
```json
|
||||
{
|
||||
"trace_id": 432,
|
||||
"frame_count": 7,
|
||||
"start_frame": 100,
|
||||
"end_frame": 300,
|
||||
|
||||
"status": "suggested",
|
||||
"suggestions": [
|
||||
{"identity_id": 3, "identity_uuid": "69e50666...", "name": "Walter Matthau", "score": 0.586, "source": "tmdb", "is_known": true},
|
||||
{"identity_id": 5, "identity_uuid": "102e8ed0...", "name": "George Kennedy", "score": 0.572, "source": "tmdb", "is_known": true}
|
||||
],
|
||||
"suggested_by": "tmdb"
|
||||
}
|
||||
```
|
||||
|
||||
### 雙寫入邏輯
|
||||
|
||||
```python
|
||||
def write_suggestions(file_uuid: str, suggestions: Dict):
|
||||
"""同時寫入 TKG 和 Qdrant"""
|
||||
# 1. 寫入 TKG
|
||||
tkg_updated = batch_mark_suggestions(file_uuid, suggestions)
|
||||
|
||||
# 2. 寫入 Qdrant _faces
|
||||
qdrant_updated = update_faces_suggestions(file_uuid, suggestions)
|
||||
|
||||
return {"tkg": tkg_updated, "qdrant": qdrant_updated}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 6. Pending People
|
||||
|
||||
### 查詢邏輯
|
||||
|
||||
**API:** `GET /api/v1/file/:file_uuid/pending-persons`
|
||||
|
||||
**查詢:** PG tkg_nodes WHERE status = 'suggested'
|
||||
|
||||
```sql
|
||||
SELECT
|
||||
jsonb_array_elements(properties->'suggestions') as suggestion,
|
||||
COUNT(DISTINCT (properties->>'trace_id')) as trace_count,
|
||||
MIN(created_at) as created_at
|
||||
FROM tkg_nodes
|
||||
WHERE file_uuid = $1
|
||||
AND node_type = 'face_track'
|
||||
AND properties->>'status' = 'suggested'
|
||||
AND jsonb_array_length(properties->'suggestions') > 0
|
||||
GROUP BY suggestion
|
||||
ORDER BY trace_count DESC
|
||||
```
|
||||
|
||||
### 回傳格式
|
||||
|
||||
```json
|
||||
{
|
||||
"success": true,
|
||||
"message": "Found 5 pending persons",
|
||||
"data": [
|
||||
{
|
||||
"identity_uuid": "69e50666-0c2d-...",
|
||||
"identity_id": 3,
|
||||
"name": "Walter Matthau",
|
||||
"trace_count": 4,
|
||||
"is_known": true,
|
||||
"created_at": "2026-07-15 12:00:00"
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 7. Known Person 複製邏輯
|
||||
|
||||
### 規則
|
||||
|
||||
當 Identity Agent 匹配到已知人物(status = 'confirmed')時:
|
||||
1. **不自動確認** — 仍建立 suggested 綁定
|
||||
2. **標記 is_known** — 讓 UI 顯示為已知人物
|
||||
3. **用戶仍需確認** — 每個新綁定都需要用戶操作
|
||||
|
||||
### 匹配結果結構
|
||||
|
||||
```json
|
||||
{
|
||||
"trace_id": 432,
|
||||
"suggestions": [
|
||||
{
|
||||
"identity_id": 3,
|
||||
"name": "Walter Matthau",
|
||||
"score": 0.586,
|
||||
"is_known": true // ← 已知人物標記
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
### UI 顯示
|
||||
|
||||
```
|
||||
Pending People (Charade)
|
||||
|
||||
Trace #432
|
||||
├─ Walter Matthau (58.6%) ✓ Known
|
||||
│ [Confirm] [Reject]
|
||||
├─ George Kennedy (57.2%) ✓ Known
|
||||
│ [Confirm] [Reject]
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 8. Speaker Binding
|
||||
|
||||
### 改查 TKG suggested
|
||||
|
||||
**舊邏輯:** 查 Qdrant _faces WHERE identity_id EXISTS(永遠 0 筆)
|
||||
|
||||
**新邏輯:** 查 PG tkg_nodes WHERE status = 'suggested'
|
||||
|
||||
### 具體實現
|
||||
|
||||
```rust
|
||||
pub async fn bind_speakers(pool: &PgPool, file_uuid: &str) -> Result<usize> {
|
||||
// 1. 查 TKG suggested 節點
|
||||
let rows: Vec<(i32, i32, i64, i64, f64)> = sqlx::query_as(
|
||||
"SELECT (properties->>'trace_id')::int,
|
||||
(properties->'suggestions'->0->>'identity_id')::int,
|
||||
(properties->>'start_frame')::bigint,
|
||||
(properties->>'end_frame')::bigint,
|
||||
COALESCE((properties->>'confidence')::float, 0.0)
|
||||
FROM tkg_nodes
|
||||
WHERE file_uuid = $1 AND node_type = 'face_track'
|
||||
AND properties->>'status' = 'suggested'
|
||||
AND jsonb_array_length(properties->'suggestions') > 0"
|
||||
).bind(file_uuid).fetch_all(pool).await?;
|
||||
|
||||
// 2. 讀取 ASRX segments
|
||||
let asrx_data = load_asrx(file_uuid).await?;
|
||||
let speakers = extract_speakers(&asrx_data);
|
||||
|
||||
// 3. 計算重疊 + 寫入 identity_bindings
|
||||
let mut bindings = 0;
|
||||
for (trace_id, identity_id, start_frame, end_frame, confidence) in rows {
|
||||
let best_speaker = compute_overlap(start_frame, end_frame, &speakers, fps);
|
||||
if best_speaker.overlap_ratio > 0.3 {
|
||||
insert_identity_binding(identity_id, &best_speaker.speaker_id, ...);
|
||||
bindings += 1;
|
||||
}
|
||||
}
|
||||
|
||||
Ok(bindings)
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 9. API 設計
|
||||
|
||||
### 完整 API 清單
|
||||
|
||||
| Method | Path | 說明 |
|
||||
|--------|------|------|
|
||||
| POST | `/api/v1/agents/identity/run` | 執行 Identity Agent(全部 seeds) |
|
||||
| POST | `/api/v1/agents/identity/run-for-seed` | 執行單一 seed 匹配 |
|
||||
| POST | `/api/v1/agents/identity/cluster` | 執行 trace clustering(無 seed) |
|
||||
| POST | `/api/v1/file/:file_uuid/cluster-agent` | 執行 trace clustering(檔案專用) |
|
||||
| POST | `/api/v1/agents/identity/generate-seeds` | 產生種子 embeddings |
|
||||
| GET | `/api/v1/file/:file_uuid/pending-persons` | 列出 pending people |
|
||||
| POST | `/api/v1/file/:file_uuid/pending-person` | 建立 pending person |
|
||||
| POST | `/api/v1/identity/:uuid/bind` | 綁定 identity |
|
||||
| POST | `/api/v1/identity/:uuid/unbind` | 解綁 identity |
|
||||
| POST | `/api/v1/identity/:uuid/confirm` | 確認 pending → confirmed |
|
||||
| POST | `/api/v1/identity/:uuid/reject` | 拒絕 pending → stranger |
|
||||
|
||||
### run-for-seed API
|
||||
|
||||
**Request:**
|
||||
```json
|
||||
{
|
||||
"file_uuid": "9f880a88e9f027255714906d84865fd4",
|
||||
"identity_uuid": "c3545906-c82d-4b66-aa1d-150bc02decce"
|
||||
}
|
||||
```
|
||||
|
||||
**Response:**
|
||||
```json
|
||||
{
|
||||
"success": true,
|
||||
"message": "Found 19 new matches for seed",
|
||||
"matches": 19
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 10. 前端 UI
|
||||
|
||||
### Pending People 顯示
|
||||
|
||||
```
|
||||
┌─────────────────────────────────────────────────────────┐
|
||||
│ Pending People (Charade) │
|
||||
├─────────────────────────────────────────────────────────┤
|
||||
│ │
|
||||
│ Audrey Hepburn (6 traces) ✓ Known Person │
|
||||
│ [Confirm All] [Review] [Skip] │
|
||||
│ │
|
||||
│ George Kennedy (4 traces) ✓ Known Person │
|
||||
│ [Confirm All] [Review] [Skip] │
|
||||
│ │
|
||||
│ Walter Matthau (4 traces) ✓ Known Person │
|
||||
│ [Confirm All] [Review] [Skip] │
|
||||
│ │
|
||||
│ Bernard Musson (1 trace) │
|
||||
│ [Confirm] [Skip] │
|
||||
│ │
|
||||
│ James Coburn (1 trace) │
|
||||
│ [Confirm] [Skip] │
|
||||
│ │
|
||||
└─────────────────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
### Trace 層級多重綁定
|
||||
|
||||
```
|
||||
┌─────────────────────────────────────────────────────────┐
|
||||
│ Trace #432 (7 frames) │
|
||||
├─────────────────────────────────────────────────────────┤
|
||||
│ │
|
||||
│ Suggestions: │
|
||||
│ ○ Walter Matthau (58.6%) ✓ Known │
|
||||
│ ○ George Kennedy (57.2%) ✓ Known │
|
||||
│ │
|
||||
│ [Select Walter Matthau] [Select George Kennedy] │
|
||||
│ [Skip - Not Recognized] │
|
||||
│ │
|
||||
└─────────────────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 11. Cluster Agent(無 Seed 分群)
|
||||
|
||||
### 目的
|
||||
不需要 seed photos,直接對現有 face traces 進行相似度分群,找出相似臉並分組。
|
||||
|
||||
### 與 Identity Agent 的區別
|
||||
|
||||
| | Identity Agent | Cluster Agent |
|
||||
|---|---|---|
|
||||
| Seed | 需要 seed person | 不需要 seed |
|
||||
| 目標 | TMDB 匹配已知演員 | 用現有 face traces 找出相似臉分群 |
|
||||
| 輸出 | identity_match_round1.json | cluster_result.json |
|
||||
| 算法 | Cosine similarity vs seeds | Greedy clustering with centroids |
|
||||
|
||||
### API
|
||||
|
||||
**Request:**
|
||||
```json
|
||||
POST /api/v1/file/:file_uuid/cluster-agent
|
||||
{}
|
||||
```
|
||||
|
||||
**Response:**
|
||||
```json
|
||||
{
|
||||
"success": true,
|
||||
"message": "Found 30 clusters from 412 traces",
|
||||
"clusters": 30,
|
||||
"total_traces": 412,
|
||||
"output_path": "/Users/accusys/momentry/output/{uuid}/{uuid}.cluster_result.json",
|
||||
"cluster_details": [
|
||||
{"cluster_id": 1, "trace_count": 49, "trace_ids": [...], "representative_trace": 2136},
|
||||
{"cluster_id": 2, "trace_count": 36, "trace_ids": [...], "representative_trace": 2}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
### 輸出檔案
|
||||
|
||||
`{output}/{uuid}/{uuid}.cluster_result.json`
|
||||
|
||||
```json
|
||||
{
|
||||
"file_uuid": "9f880a88e9f027255714906d84865fd4",
|
||||
"threshold": 0.40,
|
||||
"total_traces": 412,
|
||||
"clusters": [
|
||||
{"cluster_id": 1, "trace_count": 49, "trace_ids": [2136, ...], "representative_trace": 2136}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 12. 修改計畫
|
||||
|
||||
### Python Scripts
|
||||
|
||||
| 檔案 | 改動 |
|
||||
|------|------|
|
||||
| `identity_matcher.py` | 輸出 suggestions 陣列,支援多重綁定 |
|
||||
| `qdrant_faces.py` | 新增 `update_faces_suggestions()` |
|
||||
| `tkg_helper.py` | 修改 `batch_mark_suggestions()` 寫入 suggestions 陣列 |
|
||||
|
||||
### Rust 後端
|
||||
|
||||
| 檔案 | 改動 |
|
||||
|------|------|
|
||||
| `identity_agent_api.rs` | `bind_speakers()` 改查 TKG suggested |
|
||||
| `identity_binding.rs` | `list_pending_persons()` 已改為查 TKG ✓ |
|
||||
|
||||
### 前端
|
||||
|
||||
| 檔案 | 改動 |
|
||||
|------|------|
|
||||
| `PeopleView.vue` | 顯示多重綁定、is_known 標記、觸發按鈕 |
|
||||
| `store.ts` | `ensureFaceCandidates` 傳 fileUuid ✓ |
|
||||
| `api/index.ts` | 新增 `run_identity_for_seed` API 映射 |
|
||||
|
||||
### Pending People Card UI
|
||||
|
||||
每個 pending person 卡片新增觸發按鈕(右上角 refresh icon):
|
||||
- 點擊後觸發單一 seed 匹配
|
||||
- 顯示匹配結果數量
|
||||
- 自動重新載入 pending people 列表
|
||||
|
||||
---
|
||||
|
||||
## 12. 版本歷史
|
||||
|
||||
| 版本 | 日期 | 說明 |
|
||||
|------|------|------|
|
||||
| V1.0 | 2026-05-07 | 初始設計 |
|
||||
| V2.0 | 2026-07-15 | 重新設計:多重綁定、只綁定不確認、TKG 雙寫入 |
|
||||
| V2.1 | 2026-07-16 | 新增 run-for-seed API、前端觸發按鈕 |
|
||||
| V2.2 | 2026-07-16 | 新增 Cluster Agent(無 seed 分群)、cluster-agent API |
|
||||
@@ -0,0 +1,654 @@
|
||||
# MarkBase Queue 与 Billing 集成设计
|
||||
|
||||
**版本**: 1.0
|
||||
**日期**: 2026-10-11
|
||||
**目标**: 队列系统完全兼容 MarkBase Billing 机制
|
||||
|
||||
---
|
||||
|
||||
## 🎯 集成目标
|
||||
|
||||
| 目标 | 说明 | 优先级 |
|
||||
|------|------|:------:|
|
||||
| **准确计费** | 每个队列消息准确记录 token 消耗 | 🔴 P0 |
|
||||
| **Quota 限制** | 根据用户 quota 限制队列处理 | 🔴 P0 |
|
||||
| **成本追踪** | 追踪每个请求的成本 | 🟡 P1 |
|
||||
| **实时监控** | 实时监控 token 使用情况 | 🟡 P1 |
|
||||
|
||||
---
|
||||
|
||||
## 🏗️ 集成架构
|
||||
|
||||
```
|
||||
┌─────────────────────────────────────────────────────────────────┐
|
||||
│ MarkBase Queue Service │
|
||||
├─────────────────────────────────────────────────────────────────┤
|
||||
│ │
|
||||
│ ┌──────────────────┐ ┌──────────────────┐ │
|
||||
│ │ Queue Manager │ │ Billing Manager │ │
|
||||
│ │ │ │ │ │
|
||||
│ │ - 消息队列管理 │ │ - Token 追踪 │ │
|
||||
│ │ - 优先级调度 │ │ - Quota 检查 │ │
|
||||
│ │ - 并发控制 │ │ - 成本计算 │ │
|
||||
│ └──────────────────┘ └──────────────────┘ │
|
||||
│ │ │ │
|
||||
│ └───────────┬───────────┘ │
|
||||
│ ▼ │
|
||||
│ ┌──────────────────────────────────────────────────────────┐ │
|
||||
│ │ Billing-Aware Queue Processing │ │
|
||||
│ │ ├─ Pre-Processing: 检查 quota │ │
|
||||
│ │ ├─ Processing: 追踪 token 使用 │ │
|
||||
│ │ └─ Post-Processing: 记录成本 │ │
|
||||
│ └──────────────────────────────────────────────────────────┘ │
|
||||
│ │
|
||||
└─────────────────────────────────────────────────────────────────┘
|
||||
│
|
||||
▼
|
||||
┌─────────────────────────────────────────────────────────────────┐
|
||||
│ MarkBase Billing Service │
|
||||
├─────────────────────────────────────────────────────────────────┤
|
||||
│ PostgreSQL Tables: │
|
||||
│ ├─ billing_periods (计费周期汇总) │
|
||||
│ ├─ token_usage_log (token 使用明细) │
|
||||
│ ├─ user_quotas (用户 quota 配置) │
|
||||
│ └─ service_rates (服务费率配置) │
|
||||
└─────────────────────────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 📊 数据模型扩展
|
||||
|
||||
### 1. 队列消息与 Billing 关联
|
||||
|
||||
```sql
|
||||
-- 扩展 vlm_requests 表
|
||||
ALTER TABLE vlm_requests ADD COLUMN IF NOT EXISTS
|
||||
request_id VARCHAR(36), -- 关联 billing request_id
|
||||
key_id VARCHAR(36), -- API key ID
|
||||
billing_context JSONB, -- Billing 上下文
|
||||
token_usage JSONB, -- Token 使用记录
|
||||
cost_usd DECIMAL(10, 6); -- 成本(美元)
|
||||
|
||||
-- token_usage 格式
|
||||
{
|
||||
"input_tokens": 500,
|
||||
"output_tokens": 300,
|
||||
"total_tokens": 800,
|
||||
"model": "gemma-4-12b-it",
|
||||
"service": "vlm"
|
||||
}
|
||||
|
||||
-- billing_context 格式
|
||||
{
|
||||
"user_id": "user_123",
|
||||
"api_key": "muser_abc123",
|
||||
"quota_limit": 100000,
|
||||
"quota_used": 50000,
|
||||
"quota_remaining": 50000
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 2. Billing 周期表
|
||||
|
||||
```sql
|
||||
CREATE TABLE IF NOT EXISTS billing_periods (
|
||||
id SERIAL PRIMARY KEY,
|
||||
key_id VARCHAR(36) NOT NULL,
|
||||
period_month VARCHAR(7) NOT NULL, -- YYYY-MM
|
||||
period_start TIMESTAMP WITH TIME ZONE NOT NULL,
|
||||
period_end TIMESTAMP WITH TIME ZONE NOT NULL,
|
||||
|
||||
-- Token 统计
|
||||
total_input_tokens BIGINT DEFAULT 0,
|
||||
total_output_tokens BIGINT DEFAULT 0,
|
||||
total_tokens BIGINT DEFAULT 0,
|
||||
|
||||
-- 请求统计
|
||||
request_count BIGINT DEFAULT 0,
|
||||
error_count BIGINT DEFAULT 0,
|
||||
|
||||
-- 成本
|
||||
total_cost_usd DECIMAL(10, 2) DEFAULT 0.00,
|
||||
|
||||
-- 明细
|
||||
service_breakdown JSONB DEFAULT '{}',
|
||||
model_breakdown JSONB DEFAULT '{}',
|
||||
|
||||
-- 性能指标
|
||||
avg_duration_ms INTEGER,
|
||||
total_duration_ms BIGINT,
|
||||
|
||||
-- 索引
|
||||
UNIQUE(key_id, period_month)
|
||||
);
|
||||
|
||||
CREATE INDEX idx_billing_periods_key ON billing_periods(key_id, period_month);
|
||||
CREATE INDEX idx_billing_periods_month ON billing_periods(period_month);
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 3. Token 使用日志表
|
||||
|
||||
```sql
|
||||
CREATE TABLE IF NOT EXISTS token_usage_log (
|
||||
id BIGSERIAL PRIMARY KEY,
|
||||
|
||||
-- 关联信息
|
||||
request_id VARCHAR(36) NOT NULL,
|
||||
key_id VARCHAR(36),
|
||||
queue_name VARCHAR(255),
|
||||
message_id VARCHAR(36),
|
||||
|
||||
-- 服务信息
|
||||
service VARCHAR(50) NOT NULL, -- 'vlm', 'chat', 'embedding'
|
||||
model VARCHAR(100),
|
||||
endpoint VARCHAR(255),
|
||||
|
||||
-- Token 使用
|
||||
input_tokens INTEGER NOT NULL,
|
||||
output_tokens INTEGER NOT NULL,
|
||||
total_tokens INTEGER NOT NULL,
|
||||
|
||||
-- 成本
|
||||
cost_usd DECIMAL(10, 6),
|
||||
|
||||
-- 性能
|
||||
duration_ms INTEGER,
|
||||
|
||||
-- 状态
|
||||
status_code INTEGER,
|
||||
error_message TEXT,
|
||||
|
||||
-- 时间戳
|
||||
created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
|
||||
|
||||
-- 索引
|
||||
FOREIGN KEY (request_id) REFERENCES vlm_requests(request_id)
|
||||
);
|
||||
|
||||
CREATE INDEX idx_token_usage_log_key ON token_usage_log(key_id, created_at);
|
||||
CREATE INDEX idx_token_usage_log_service ON token_usage_log(service, created_at);
|
||||
CREATE INDEX idx_token_usage_log_request ON token_usage_log(request_id);
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 4. 用户 Quota 表
|
||||
|
||||
```sql
|
||||
CREATE TABLE IF NOT EXISTS user_quotas (
|
||||
id SERIAL PRIMARY KEY,
|
||||
key_id VARCHAR(36) NOT NULL UNIQUE,
|
||||
user_id VARCHAR(36),
|
||||
|
||||
-- Quota 配置
|
||||
monthly_token_limit BIGINT DEFAULT 1000000, -- 每月 token 上限
|
||||
daily_token_limit BIGINT DEFAULT 50000, -- 每日 token 上限
|
||||
|
||||
-- 当前使用
|
||||
current_month_tokens BIGINT DEFAULT 0,
|
||||
current_day_tokens BIGINT DEFAULT 0,
|
||||
|
||||
-- 重置时间
|
||||
last_month_reset TIMESTAMP WITH TIME ZONE,
|
||||
last_day_reset TIMESTAMP WITH TIME ZONE,
|
||||
|
||||
-- 配额策略
|
||||
quota_policy VARCHAR(20) DEFAULT 'soft', -- 'hard' | 'soft'
|
||||
|
||||
-- 超额处理
|
||||
allow_overage BOOLEAN DEFAULT false,
|
||||
overage_rate DECIMAL(5, 2) DEFAULT 0.0, -- 超额单价
|
||||
|
||||
-- 索引
|
||||
created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
|
||||
updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
|
||||
);
|
||||
|
||||
CREATE INDEX idx_user_quotas_key ON user_quotas(key_id);
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 5. 服务费率表
|
||||
|
||||
```sql
|
||||
CREATE TABLE IF NOT EXISTS service_rates (
|
||||
id SERIAL PRIMARY KEY,
|
||||
service VARCHAR(50) NOT NULL,
|
||||
model VARCHAR(100),
|
||||
|
||||
-- 价格(每 1000 tokens)
|
||||
input_rate_usd DECIMAL(10, 6) DEFAULT 0.0, -- 输入 token 单价
|
||||
output_rate_usd DECIMAL(10, 6) DEFAULT 0.0, -- 输出 token 单价
|
||||
|
||||
-- 生效时间
|
||||
effective_from TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
|
||||
effective_to TIMESTAMP WITH TIME ZONE,
|
||||
|
||||
-- 索引
|
||||
UNIQUE(service, model, effective_from)
|
||||
);
|
||||
|
||||
-- 插入默认费率
|
||||
INSERT INTO service_rates (service, model, input_rate_usd, output_rate_usd) VALUES
|
||||
('vlm', 'gemma-4-12b-it', 0.0001, 0.0002),
|
||||
('chat', 'gemma-4-12b-it', 0.00005, 0.0001),
|
||||
('embedding', 'embeddinggemma-300m', 0.00001, 0.0);
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 🔄 处理流程
|
||||
|
||||
### 流程 1: 消息入队前
|
||||
|
||||
```rust
|
||||
// 1. 检查用户 quota
|
||||
async fn check_quota(&self, key_id: &str) -> Result<bool, BillingError> {
|
||||
let quota = self.db.get_user_quota(key_id).await?;
|
||||
|
||||
// 检查月度 quota
|
||||
if quota.current_month_tokens >= quota.monthly_token_limit {
|
||||
if !quota.allow_overage {
|
||||
return Err(BillingError::QuotaExceeded {
|
||||
limit: quota.monthly_token_limit,
|
||||
used: quota.current_month_tokens,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// 检查每日 quota
|
||||
if quota.current_day_tokens >= quota.daily_token_limit {
|
||||
if !quota.allow_overage {
|
||||
return Err(BillingError::DailyQuotaExceeded {
|
||||
limit: quota.daily_token_limit,
|
||||
used: quota.current_day_tokens,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
// 2. 创建 billing 上下文
|
||||
async fn create_billing_context(&self, key_id: &str) -> Result<BillingContext, BillingError> {
|
||||
let quota = self.db.get_user_quota(key_id).await?;
|
||||
|
||||
Ok(BillingContext {
|
||||
request_id: Uuid::new_v4().to_string(),
|
||||
key_id: key_id.to_string(),
|
||||
user_id: quota.user_id,
|
||||
quota_limit: quota.monthly_token_limit,
|
||||
quota_used: quota.current_month_tokens,
|
||||
quota_remaining: quota.monthly_token_limit - quota.current_month_tokens,
|
||||
})
|
||||
}
|
||||
|
||||
// 3. 提交消息(带 billing 上下文)
|
||||
async fn enqueue_with_billing(
|
||||
&self,
|
||||
queue: &str,
|
||||
message: Message,
|
||||
billing_ctx: BillingContext,
|
||||
) -> Result<MessageId, QueueError> {
|
||||
// 将 billing 上下文附加到消息
|
||||
let mut message = message;
|
||||
message.metadata.insert(
|
||||
"billing_context".to_string(),
|
||||
serde_json::to_string(&billing_ctx)?,
|
||||
);
|
||||
|
||||
self.enqueue(queue, message).await
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 流程 2: 消息处理中
|
||||
|
||||
```rust
|
||||
// 1. 开始处理
|
||||
async fn start_processing(&mut self, message: &Message) -> Result<(), BillingError> {
|
||||
let billing_ctx = message.metadata.get("billing_context")
|
||||
.ok_or(BillingError::MissingBillingContext)?;
|
||||
|
||||
let ctx: BillingContext = serde_json::from_str(billing_ctx)?;
|
||||
|
||||
// 更新请求状态为 processing
|
||||
self.db.update_request_status(
|
||||
&ctx.request_id,
|
||||
"processing",
|
||||
).await?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// 2. 处理并追踪 token
|
||||
async fn process_with_tracking(
|
||||
&mut self,
|
||||
message: &Message,
|
||||
) -> Result<ProcessResult, BillingError> {
|
||||
let billing_ctx = self.get_billing_context(message)?;
|
||||
|
||||
// 开始计时
|
||||
let start = Instant::now();
|
||||
|
||||
// 调用服务(VLM/Chat/Embedding)
|
||||
let result = self.call_service(message).await?;
|
||||
|
||||
// 计算 token 使用
|
||||
let token_usage = TokenUsage {
|
||||
input_tokens: result.input_tokens,
|
||||
output_tokens: result.output_tokens,
|
||||
total_tokens: result.input_tokens + result.output_tokens,
|
||||
};
|
||||
|
||||
// 计算成本
|
||||
let cost = self.calculate_cost(&token_usage, &result.model).await?;
|
||||
|
||||
// 更新 quota
|
||||
self.update_quota(&billing_ctx.key_id, &token_usage).await?;
|
||||
|
||||
// 记录到日志
|
||||
self.log_token_usage(LogTokenUsage {
|
||||
request_id: billing_ctx.request_id.clone(),
|
||||
key_id: billing_ctx.key_id.clone(),
|
||||
service: result.service.clone(),
|
||||
model: Some(result.model.clone()),
|
||||
endpoint: None,
|
||||
input_tokens: token_usage.input_tokens,
|
||||
output_tokens: token_usage.output_tokens,
|
||||
total_tokens: token_usage.total_tokens,
|
||||
duration_ms: Some(start.elapsed().as_millis() as i32),
|
||||
status_code: Some(200),
|
||||
error_message: None,
|
||||
}).await?;
|
||||
|
||||
Ok(ProcessResult {
|
||||
result: result.output,
|
||||
token_usage,
|
||||
cost_usd: cost,
|
||||
})
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 流程 3: 消息处理完成
|
||||
|
||||
```rust
|
||||
// 1. 记录成本
|
||||
async fn record_cost(
|
||||
&self,
|
||||
request_id: &str,
|
||||
cost_usd: f64,
|
||||
token_usage: TokenUsage,
|
||||
) -> Result<(), BillingError> {
|
||||
// 更新 billing_periods
|
||||
self.db.upsert_billing_period(
|
||||
key_id,
|
||||
period_month,
|
||||
token_usage,
|
||||
cost_usd,
|
||||
).await?;
|
||||
|
||||
// 更新消息记录
|
||||
self.db.update_message_billing(
|
||||
request_id,
|
||||
token_usage,
|
||||
cost_usd,
|
||||
).await?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// 2. 更新 quota
|
||||
async fn update_quota(
|
||||
&self,
|
||||
key_id: &str,
|
||||
token_usage: &TokenUsage,
|
||||
) -> Result<(), BillingError> {
|
||||
self.db.increment_quota_usage(
|
||||
key_id,
|
||||
token_usage.total_tokens,
|
||||
).await?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 💰 成本计算
|
||||
|
||||
### 费率配置
|
||||
|
||||
```rust
|
||||
pub struct ServiceRate {
|
||||
pub service: String,
|
||||
pub model: String,
|
||||
pub input_rate_usd: f64, // 每 1000 tokens
|
||||
pub output_rate_usd: f64, // 每 1000 tokens
|
||||
}
|
||||
|
||||
impl ServiceRate {
|
||||
pub fn calculate_cost(&self, usage: &TokenUsage) -> f64 {
|
||||
let input_cost = (usage.input_tokens as f64 / 1000.0) * self.input_rate_usd;
|
||||
let output_cost = (usage.output_tokens as f64 / 1000.0) * self.output_rate_usd;
|
||||
input_cost + output_cost
|
||||
}
|
||||
}
|
||||
|
||||
// 示例
|
||||
let vlm_rate = ServiceRate {
|
||||
service: "vlm".to_string(),
|
||||
model: "gemma-4-12b-it".to_string(),
|
||||
input_rate_usd: 0.0001,
|
||||
output_rate_usd: 0.0002,
|
||||
};
|
||||
|
||||
let usage = TokenUsage {
|
||||
input_tokens: 500,
|
||||
output_tokens: 300,
|
||||
total_tokens: 800,
|
||||
};
|
||||
|
||||
let cost = vlm_rate.calculate_cost(&usage);
|
||||
// cost = (500/1000 * 0.0001) + (300/1000 * 0.0002) = 0.00011 USD
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 🔌 API 集成
|
||||
|
||||
### 1. Billing API 扩展
|
||||
|
||||
```rust
|
||||
// GET /api/v1/billing/usage
|
||||
pub async fn get_usage(
|
||||
key_id: Option<String>,
|
||||
period: String,
|
||||
) -> Result<UsageResponse, BillingError> {
|
||||
let periods = db.get_billing_periods(key_id, &period).await?;
|
||||
|
||||
Ok(UsageResponse {
|
||||
key_id,
|
||||
period,
|
||||
tokens: TokenStats {
|
||||
input: periods.total_input_tokens,
|
||||
output: periods.total_output_tokens,
|
||||
total: periods.total_tokens,
|
||||
},
|
||||
services: periods.service_breakdown,
|
||||
})
|
||||
}
|
||||
|
||||
// GET /api/v1/billing/quota
|
||||
pub async fn get_quota(key_id: String) -> Result<QuotaResponse, BillingError> {
|
||||
let quota = db.get_user_quota(&key_id).await?;
|
||||
|
||||
Ok(QuotaResponse {
|
||||
key_id: quota.key_id,
|
||||
monthly_limit: quota.monthly_token_limit,
|
||||
daily_limit: quota.daily_token_limit,
|
||||
current_month_used: quota.current_month_tokens,
|
||||
current_day_used: quota.current_day_tokens,
|
||||
quota_remaining: quota.monthly_token_limit - quota.current_month_tokens,
|
||||
})
|
||||
}
|
||||
|
||||
// GET /api/v1/billing/history
|
||||
pub async fn get_history(
|
||||
key_id: String,
|
||||
limit: i32,
|
||||
) -> Result<HistoryResponse, BillingError> {
|
||||
let periods = db.get_billing_history(&key_id, limit).await?;
|
||||
|
||||
Ok(HistoryResponse {
|
||||
periods: periods.into_iter().map(|p| PeriodSummary {
|
||||
period: p.period_month,
|
||||
total_tokens: p.total_tokens,
|
||||
request_count: p.request_count,
|
||||
}).collect(),
|
||||
})
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 2. Queue API 扩展
|
||||
|
||||
```rust
|
||||
// POST /api/v1/queues/{name}/messages (with billing)
|
||||
pub async fn produce_message(
|
||||
queue_name: String,
|
||||
request: ProduceRequest,
|
||||
auth: UserAuth,
|
||||
) -> Result<ProduceResponse, QueueError> {
|
||||
// 1. 检查 quota
|
||||
billing.check_quota(&auth.key_id).await?;
|
||||
|
||||
// 2. 创建 billing 上下文
|
||||
let billing_ctx = billing.create_billing_context(&auth.key_id).await?;
|
||||
|
||||
// 3. 提交消息
|
||||
let message = Message {
|
||||
key: request.key,
|
||||
value: request.value,
|
||||
priority: request.priority,
|
||||
metadata: {
|
||||
let mut m = request.metadata;
|
||||
m.insert("billing_context", serde_json::to_string(&billing_ctx)?);
|
||||
m
|
||||
},
|
||||
};
|
||||
|
||||
let response = queue.enqueue(&queue_name, message).await?;
|
||||
|
||||
Ok(ProduceResponse {
|
||||
message_id: response.message_id,
|
||||
offset: response.offset,
|
||||
timestamp: response.timestamp,
|
||||
quota_remaining: billing_ctx.quota_remaining,
|
||||
})
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 📊 监控与告警
|
||||
|
||||
### 1. 监控指标
|
||||
|
||||
```rust
|
||||
// Prometheus 指标
|
||||
lazy_static! {
|
||||
static ref TOKENS_USED_TOTAL: Counter = register_counter!(
|
||||
"billing_tokens_used_total",
|
||||
"Total tokens used",
|
||||
vec!["service", "model"]
|
||||
).unwrap();
|
||||
|
||||
static ref QUOTA_USAGE_RATIO: Gauge = register_gauge!(
|
||||
"billing_quota_usage_ratio",
|
||||
"Quota usage ratio",
|
||||
vec!["key_id"]
|
||||
).unwrap();
|
||||
|
||||
static ref COST_TOTAL: Counter = register_counter!(
|
||||
"billing_cost_total_usd",
|
||||
"Total cost in USD",
|
||||
vec!["service"]
|
||||
).unwrap();
|
||||
}
|
||||
```
|
||||
|
||||
### 2. 告警规则
|
||||
|
||||
```yaml
|
||||
# Prometheus AlertManager 规则
|
||||
groups:
|
||||
- name: billing
|
||||
rules:
|
||||
- alert: QuotaNearLimit
|
||||
expr: billing_quota_usage_ratio > 0.9
|
||||
for: 5m
|
||||
labels:
|
||||
severity: warning
|
||||
annotations:
|
||||
summary: "Quota near limit for {{ $labels.key_id }}"
|
||||
description: "Usage at {{ $value }}%"
|
||||
|
||||
- alert: QuotaExceeded
|
||||
expr: billing_quota_usage_ratio >= 1.0
|
||||
for: 1m
|
||||
labels:
|
||||
severity: critical
|
||||
annotations:
|
||||
summary: "Quota exceeded for {{ $labels.key_id }}"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 🚀 实施计划
|
||||
|
||||
### Phase 1: 数据库扩展(1 天)
|
||||
|
||||
- [ ] 创建 billing 相关表
|
||||
- [ ] 扩展 vlm_requests 表
|
||||
- [ ] 创建索引
|
||||
|
||||
### Phase 2: Billing 集成(2 天)
|
||||
|
||||
- [ ] 实现 BillingManager
|
||||
- [ ] 实现 quota 检查
|
||||
- [ ] 实现成本计算
|
||||
|
||||
### Phase 3: 队列集成(2 天)
|
||||
|
||||
- [ ] 修改 produce API
|
||||
- [ ] 修改 consume 流程
|
||||
- [ ] 添加 billing 追踪
|
||||
|
||||
### Phase 4: 监控与测试(1 天)
|
||||
|
||||
- [ ] 添加监控指标
|
||||
- [ ] 配置告警规则
|
||||
- [ ] 集成测试
|
||||
|
||||
---
|
||||
|
||||
## 📚 相关文档
|
||||
|
||||
- Billing API 文档: `docs_v1.0/API_WORKSPACE/modules/billing_api.md`
|
||||
- Quota 管理指南: `docs_v1.0/GUIDES/quota_management.md`
|
||||
- 成本计算规则: `docs_v1.0/OPERATIONS/cost_calculation.md`
|
||||
|
||||
---
|
||||
|
||||
**设计完成,准备实施!**
|
||||
@@ -0,0 +1,819 @@
|
||||
# MarkBase 统一命令队列架构设计
|
||||
|
||||
**版本**: 1.0
|
||||
**日期**: 2026-10-11
|
||||
**目标**: 所有命令通过 MarkBase Queue 统一处理
|
||||
|
||||
---
|
||||
|
||||
## 🎯 设计目标
|
||||
|
||||
| 目标 | 说明 | 优先级 |
|
||||
|------|------|:------:|
|
||||
| **统一入口** | 所有命令通过统一队列入口 | 🔴 P0 |
|
||||
| **解耦通信** | 系统组件通过队列异步通信 | 🔴 P0 |
|
||||
| **可追溯性** | 所有命令可追踪、审计 | 🔴 P0 |
|
||||
| **Billing 集成** | 每个命令关联 Billing | 🔴 P0 |
|
||||
| **优先级调度** | 按优先级处理命令 | 🟡 P1 |
|
||||
|
||||
---
|
||||
|
||||
## 📊 命令分类体系
|
||||
|
||||
### 1. 命令类型定义
|
||||
|
||||
```rust
|
||||
/// 命令类型
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum CommandType {
|
||||
// ========== 内部命令 ==========
|
||||
Internal {
|
||||
category: InternalCommandCategory,
|
||||
},
|
||||
|
||||
// ========== 外部命令 ==========
|
||||
External {
|
||||
category: ExternalCommandCategory,
|
||||
},
|
||||
|
||||
// ========== Agent 沟通命令 ==========
|
||||
Agent {
|
||||
category: AgentCommandCategory,
|
||||
},
|
||||
}
|
||||
|
||||
/// 内部命令分类
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum InternalCommandCategory {
|
||||
// 文件处理
|
||||
FileProcessing,
|
||||
VideoRegistration,
|
||||
FileDeletion,
|
||||
|
||||
// 数据处理
|
||||
EmbeddingGeneration,
|
||||
IndexRebuild,
|
||||
CacheClear,
|
||||
|
||||
// 系统管理
|
||||
WorkerRestart,
|
||||
ServiceHealthCheck,
|
||||
ConfigurationUpdate,
|
||||
|
||||
// 数据同步
|
||||
DatabaseMigration,
|
||||
VectorSync,
|
||||
IdentityMerging,
|
||||
}
|
||||
|
||||
/// 外部命令分类
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum ExternalCommandCategory {
|
||||
// API 命令
|
||||
ApiRequest,
|
||||
UserCommand,
|
||||
|
||||
// Webhook
|
||||
WebhookTrigger,
|
||||
|
||||
// 第三方集成
|
||||
IntegrationSync,
|
||||
ExternalApiCall,
|
||||
}
|
||||
|
||||
/// Agent 沟通命令分类
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum AgentCommandCategory {
|
||||
// Agent 协作
|
||||
AgentTask,
|
||||
AgentQuery,
|
||||
AgentResponse,
|
||||
|
||||
// Agent 沟通
|
||||
AgentMessage,
|
||||
AgentBroadcast,
|
||||
AgentSubscribe,
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 2. 命令优先级
|
||||
|
||||
```rust
|
||||
/// 命令优先级
|
||||
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum CommandPriority {
|
||||
/// P0: 最高优先级(Agent 即时响应)
|
||||
Critical = 0,
|
||||
|
||||
/// P1: 高优先级(API 用户请求)
|
||||
High = 1,
|
||||
|
||||
/// P2: 中优先级(内部处理任务)
|
||||
Normal = 2,
|
||||
|
||||
/// P3: 低优先级(后台任务)
|
||||
Low = 3,
|
||||
}
|
||||
|
||||
impl CommandType {
|
||||
/// 获取默认优先级
|
||||
pub fn default_priority(&self) -> CommandPriority {
|
||||
match self {
|
||||
// Agent 命令最高优先级
|
||||
CommandType::Agent { .. } => CommandPriority::Critical,
|
||||
|
||||
// 外部命令高优先级
|
||||
CommandType::External { category } => match category {
|
||||
ExternalCommandCategory::ApiRequest => CommandPriority::High,
|
||||
ExternalCommandCategory::UserCommand => CommandPriority::High,
|
||||
ExternalCommandCategory::WebhookTrigger => CommandPriority::Normal,
|
||||
ExternalCommandCategory::IntegrationSync => CommandPriority::Low,
|
||||
ExternalCommandCategory::ExternalApiCall => CommandPriority::Normal,
|
||||
},
|
||||
|
||||
// 内部命令中等优先级
|
||||
CommandType::Internal { category } => match category {
|
||||
InternalCommandCategory::FileProcessing => CommandPriority::Normal,
|
||||
InternalCommandCategory::VideoRegistration => CommandPriority::Normal,
|
||||
InternalCommandCategory::FileDeletion => CommandPriority::Low,
|
||||
InternalCommandCategory::EmbeddingGeneration => CommandPriority::Normal,
|
||||
InternalCommandCategory::IndexRebuild => CommandPriority::Low,
|
||||
InternalCommandCategory::CacheClear => CommandPriority::Low,
|
||||
InternalCommandCategory::WorkerRestart => CommandPriority::High,
|
||||
InternalCommandCategory::ServiceHealthCheck => CommandPriority::Normal,
|
||||
InternalCommandCategory::ConfigurationUpdate => CommandPriority::High,
|
||||
InternalCommandCategory::DatabaseMigration => CommandPriority::Critical,
|
||||
InternalCommandCategory::VectorSync => CommandPriority::Normal,
|
||||
InternalCommandCategory::IdentityMerging => CommandPriority::Low,
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 🏗️ 队列架构设计
|
||||
|
||||
### 1. 整体架构
|
||||
|
||||
```
|
||||
┌─────────────────────────────────────────────────────────────────────┐
|
||||
│ MarkBase Queue Service │
|
||||
├─────────────────────────────────────────────────────────────────────┤
|
||||
│ │
|
||||
│ ┌────────────────────────────────────────────────────────────┐ │
|
||||
│ │ Command Router (命令路由器) │ │
|
||||
│ │ ├─ 分类命令类型 │ │
|
||||
│ │ ├─ 分配优先级 │ │
|
||||
│ │ ├─ 路由到对应队列 │ │
|
||||
│ │ └─ 记录命令日志 │ │
|
||||
│ └────────────────────────────────────────────────────────────┘ │
|
||||
│ │ │
|
||||
│ ▼ │
|
||||
│ ┌────────────────────────────────────────────────────────────┐ │
|
||||
│ │ Queue Manager (队列管理器) │ │
|
||||
│ │ │ │
|
||||
│ │ ┌──────────┐ ┌──────────┐ ┌──────────┐ ┌──────────┐ │ │
|
||||
│ │ │ Internal │ │ External │ │ Agent │ │ System │ │ │
|
||||
│ │ │ Queue │ │ Queue │ │ Queue │ │ Queue │ │ │
|
||||
│ │ │ (P2-P3) │ │ (P0-P1) │ │ (P0) │ │ (P0-P3) │ │ │
|
||||
│ │ └──────────┘ └──────────┘ └──────────┘ └──────────┘ │ │
|
||||
│ └────────────────────────────────────────────────────────────┘ │
|
||||
│ │ │
|
||||
│ ▼ │
|
||||
│ ┌────────────────────────────────────────────────────────────┐ │
|
||||
│ │ Command Dispatcher (命令分发器) │ │
|
||||
│ │ ├─ 分发到对应处理器 │ │
|
||||
│ │ ├─ 执行命令 │ │
|
||||
│ │ ├─ 追踪执行状态 │ │
|
||||
│ │ └─ 记录执行结果 │ │
|
||||
│ └────────────────────────────────────────────────────────────┘ │
|
||||
│ │
|
||||
└─────────────────────────────────────────────────────────────────────┘
|
||||
│
|
||||
▼
|
||||
┌─────────────────────────────────────────────────────────────────────┐
|
||||
│ Command Handlers │
|
||||
├─────────────────────────────────────────────────────────────────────┤
|
||||
│ ┌──────────┐ ┌──────────┐ ┌──────────┐ ┌──────────┐ │
|
||||
│ │ File │ │ Video │ │ Agent │ │ API │ │
|
||||
│ │ Handler │ │ Handler │ │ Handler │ │ Handler │ │
|
||||
│ └──────────┘ └──────────┘ └──────────┘ └──────────┘ │
|
||||
└─────────────────────────────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 2. 队列定义
|
||||
|
||||
```sql
|
||||
-- 命令队列表
|
||||
CREATE TABLE IF NOT EXISTS command_queue (
|
||||
-- 消息 ID
|
||||
id BIGSERIAL PRIMARY KEY,
|
||||
message_id VARCHAR(36) NOT NULL UNIQUE,
|
||||
|
||||
-- 队列信息
|
||||
queue_name VARCHAR(255) NOT NULL,
|
||||
queue_type VARCHAR(50) NOT NULL, -- 'internal' | 'external' | 'agent' | 'system'
|
||||
|
||||
-- 命令信息
|
||||
command_type VARCHAR(100) NOT NULL,
|
||||
command_category VARCHAR(100),
|
||||
command_action VARCHAR(100),
|
||||
|
||||
-- 消息内容
|
||||
key VARCHAR(255),
|
||||
value JSONB NOT NULL,
|
||||
|
||||
-- 优先级
|
||||
priority SMALLINT DEFAULT 2, -- 0=Critical, 1=High, 2=Normal, 3=Low
|
||||
|
||||
-- Billing 信息
|
||||
request_id VARCHAR(36),
|
||||
key_id VARCHAR(36),
|
||||
billing_context JSONB,
|
||||
token_usage JSONB,
|
||||
cost_usd DECIMAL(10, 6),
|
||||
|
||||
-- 状态管理
|
||||
status VARCHAR(20) DEFAULT 'pending', -- 'pending' | 'processing' | 'completed' | 'failed'
|
||||
consumer_group VARCHAR(255),
|
||||
consumer_id VARCHAR(255),
|
||||
|
||||
-- 重试机制
|
||||
retry_count INTEGER DEFAULT 0,
|
||||
max_retries INTEGER DEFAULT 3,
|
||||
last_error TEXT,
|
||||
|
||||
-- 时间戳
|
||||
created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
|
||||
scheduled_at TIMESTAMP WITH TIME ZONE,
|
||||
processing_started_at TIMESTAMP WITH TIME ZONE,
|
||||
processing_completed_at TIMESTAMP WITH TIME ZONE,
|
||||
|
||||
-- 索引
|
||||
INDEX idx_queue_name (queue_name, priority, created_at),
|
||||
INDEX idx_status (status, created_at),
|
||||
INDEX idx_consumer (consumer_group, consumer_id),
|
||||
INDEX idx_command_type (command_type, created_at),
|
||||
INDEX idx_billing (request_id, key_id)
|
||||
);
|
||||
|
||||
-- 命令执行日志
|
||||
CREATE TABLE IF NOT EXISTS command_execution_log (
|
||||
id BIGSERIAL PRIMARY KEY,
|
||||
message_id VARCHAR(36) NOT NULL,
|
||||
|
||||
-- 执行信息
|
||||
handler VARCHAR(255),
|
||||
action VARCHAR(255),
|
||||
|
||||
-- 执行结果
|
||||
status VARCHAR(20), -- 'success' | 'error' | 'timeout'
|
||||
result JSONB,
|
||||
error_message TEXT,
|
||||
|
||||
-- 性能指标
|
||||
duration_ms INTEGER,
|
||||
tokens_used INTEGER,
|
||||
cost_usd DECIMAL(10, 6),
|
||||
|
||||
-- 时间戳
|
||||
executed_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
|
||||
|
||||
FOREIGN KEY (message_id) REFERENCES command_queue(message_id)
|
||||
);
|
||||
|
||||
CREATE INDEX idx_execution_log_message ON command_execution_log(message_id, executed_at);
|
||||
CREATE INDEX idx_execution_log_status ON command_execution_log(status, executed_at);
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 🔄 命令流程设计
|
||||
|
||||
### 流程 1: 内部命令流程
|
||||
|
||||
```rust
|
||||
// 示例:视频注册命令
|
||||
async fn register_video_internal(
|
||||
file_path: &str,
|
||||
options: RegisterOptions,
|
||||
) -> Result<CommandId, CommandError> {
|
||||
// 1. 创建命令
|
||||
let command = Command {
|
||||
command_type: CommandType::Internal {
|
||||
category: InternalCommandCategory::VideoRegistration,
|
||||
},
|
||||
payload: json!({
|
||||
"file_path": file_path,
|
||||
"options": options,
|
||||
}),
|
||||
priority: CommandPriority::Normal,
|
||||
metadata: {
|
||||
let mut m = HashMap::new();
|
||||
m.insert("source", "internal");
|
||||
m.insert("triggered_by", "system");
|
||||
m
|
||||
},
|
||||
};
|
||||
|
||||
// 2. 提交到队列
|
||||
let message_id = command_queue.produce(
|
||||
"internal.commands",
|
||||
command,
|
||||
ProduceOptions {
|
||||
priority: Some(command.priority as i32),
|
||||
..Default::default()
|
||||
},
|
||||
).await?;
|
||||
|
||||
// 3. 返回命令 ID
|
||||
Ok(CommandId(message_id))
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 流程 2: 外部命令流程
|
||||
|
||||
```rust
|
||||
// 示例:API 用户命令
|
||||
async fn handle_api_command(
|
||||
api_key: &str,
|
||||
command_request: CommandRequest,
|
||||
) -> Result<CommandResponse, CommandError> {
|
||||
// 1. 验证 API Key
|
||||
let user = auth.verify_api_key(api_key).await?;
|
||||
|
||||
// 2. 检查 Billing Quota
|
||||
billing.check_quota(&user.key_id).await?;
|
||||
|
||||
// 3. 创建 billing 上下文
|
||||
let billing_ctx = billing.create_billing_context(&user.key_id).await?;
|
||||
|
||||
// 4. 创建命令
|
||||
let command = Command {
|
||||
command_type: CommandType::External {
|
||||
category: ExternalCommandCategory::ApiRequest,
|
||||
},
|
||||
payload: command_request.payload,
|
||||
priority: CommandPriority::High,
|
||||
metadata: {
|
||||
let mut m = HashMap::new();
|
||||
m.insert("billing_context", serde_json::to_string(&billing_ctx)?);
|
||||
m.insert("api_key", api_key.to_string());
|
||||
m.insert("user_id", user.user_id.to_string());
|
||||
m
|
||||
},
|
||||
};
|
||||
|
||||
// 5. 提交到队列
|
||||
let message_id = command_queue.produce(
|
||||
"external.commands",
|
||||
command,
|
||||
ProduceOptions {
|
||||
priority: Some(command.priority as i32),
|
||||
billing_context: Some(billing_ctx.clone()),
|
||||
..Default::default()
|
||||
},
|
||||
).await?;
|
||||
|
||||
// 6. 返回响应
|
||||
Ok(CommandResponse {
|
||||
command_id: message_id.clone(),
|
||||
status: "queued".to_string(),
|
||||
billing: BillingInfo {
|
||||
quota_remaining: billing_ctx.quota_remaining,
|
||||
},
|
||||
message: "Command queued successfully".to_string(),
|
||||
})
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 流程 3: Agent 沟通流程
|
||||
|
||||
```rust
|
||||
// 示例:Agent 间消息传递
|
||||
async fn send_agent_message(
|
||||
from_agent: &str,
|
||||
to_agent: &str,
|
||||
message_type: AgentMessageType,
|
||||
content: JsonValue,
|
||||
) -> Result<CommandId, CommandError> {
|
||||
// 1. 创建命令
|
||||
let command = Command {
|
||||
command_type: CommandType::Agent {
|
||||
category: AgentCommandCategory::AgentMessage,
|
||||
},
|
||||
payload: json!({
|
||||
"from": from_agent,
|
||||
"to": to_agent,
|
||||
"message_type": message_type,
|
||||
"content": content,
|
||||
}),
|
||||
priority: CommandPriority::Critical, // Agent 消息最高优先级
|
||||
metadata: {
|
||||
let mut m = HashMap::new();
|
||||
m.insert("source", "agent");
|
||||
m.insert("from_agent", from_agent.to_string());
|
||||
m.insert("to_agent", to_agent.to_string());
|
||||
m
|
||||
},
|
||||
};
|
||||
|
||||
// 2. 提交到 Agent 队列
|
||||
let message_id = command_queue.produce(
|
||||
&format!("agent.{}", to_agent),
|
||||
command,
|
||||
ProduceOptions {
|
||||
priority: Some(CommandPriority::Critical as i32),
|
||||
..Default::default()
|
||||
},
|
||||
).await?;
|
||||
|
||||
// 3. 通知目标 Agent
|
||||
notify_agent(to_agent, &message_id).await?;
|
||||
|
||||
Ok(CommandId(message_id))
|
||||
}
|
||||
|
||||
// Agent 订阅队列
|
||||
async fn subscribe_agent_queue(
|
||||
agent_id: &str,
|
||||
handler: impl Fn(AgentMessage) -> Future<Output = Result<(), AgentError>> + Send + Sync + 'static,
|
||||
) -> Result<(), CommandError> {
|
||||
// 订阅专属队列
|
||||
command_queue.consume(
|
||||
&format!("agent.{}", agent_id),
|
||||
ConsumeOptions {
|
||||
consumer_group: format!("agent_{}", agent_id),
|
||||
consumer_id: format!("agent_{}_worker", agent_id),
|
||||
..Default::default()
|
||||
},
|
||||
|message| async {
|
||||
// 解析命令
|
||||
let command: Command = serde_json::from_str(&message.value)?;
|
||||
|
||||
// 提取 Agent 消息
|
||||
let agent_message = AgentMessage::from_command(command)?;
|
||||
|
||||
// 调用 handler
|
||||
handler(agent_message).await?;
|
||||
|
||||
// 提交 offset
|
||||
message.commit().await?;
|
||||
|
||||
Ok(())
|
||||
},
|
||||
).await
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 🔀 命令路由设计
|
||||
|
||||
### 1. 路由规则
|
||||
|
||||
```rust
|
||||
pub struct CommandRouter {
|
||||
routes: HashMap<CommandType, QueueRoute>,
|
||||
}
|
||||
|
||||
/// 队列路由规则
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct QueueRoute {
|
||||
pub queue_name: String,
|
||||
pub handler: String,
|
||||
pub priority: CommandPriority,
|
||||
pub billing_required: bool,
|
||||
}
|
||||
|
||||
impl CommandRouter {
|
||||
/// 根据命令类型路由到对应队列
|
||||
pub fn route(&self, command: &Command) -> Result<QueueRoute, RouterError> {
|
||||
// 查找路由规则
|
||||
if let Some(route) = self.routes.get(&command.command_type) {
|
||||
return Ok(route.clone());
|
||||
}
|
||||
|
||||
// 默认路由
|
||||
Ok(QueueRoute {
|
||||
queue_name: "default".to_string(),
|
||||
handler: "default_handler".to_string(),
|
||||
priority: command.command_type.default_priority(),
|
||||
billing_required: true,
|
||||
})
|
||||
}
|
||||
|
||||
/// 注册路由
|
||||
pub fn register_route(&mut self, command_type: CommandType, route: QueueRoute) {
|
||||
self.routes.insert(command_type, route);
|
||||
}
|
||||
}
|
||||
|
||||
// 路由配置示例
|
||||
fn setup_router() -> CommandRouter {
|
||||
let mut router = CommandRouter::new();
|
||||
|
||||
// 内部命令路由
|
||||
router.register_route(
|
||||
CommandType::Internal { category: InternalCommandCategory::VideoRegistration },
|
||||
QueueRoute {
|
||||
queue_name: "internal.video".to_string(),
|
||||
handler: "video_registration_handler".to_string(),
|
||||
priority: CommandPriority::Normal,
|
||||
billing_required: true,
|
||||
},
|
||||
);
|
||||
|
||||
// 外部命令路由
|
||||
router.register_route(
|
||||
CommandType::External { category: ExternalCommandCategory::ApiRequest },
|
||||
QueueRoute {
|
||||
queue_name: "external.api".to_string(),
|
||||
handler: "api_request_handler".to_string(),
|
||||
priority: CommandPriority::High,
|
||||
billing_required: true,
|
||||
},
|
||||
);
|
||||
|
||||
// Agent 命令路由
|
||||
router.register_route(
|
||||
CommandType::Agent { category: AgentCommandCategory::AgentMessage },
|
||||
QueueRoute {
|
||||
queue_name: "agent.messages".to_string(),
|
||||
handler: "agent_message_handler".to_string(),
|
||||
priority: CommandPriority::Critical,
|
||||
billing_required: false, // Agent 消息不计费
|
||||
},
|
||||
);
|
||||
|
||||
router
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 🎮 命令分发器设计
|
||||
|
||||
### 1. 处理器注册
|
||||
|
||||
```rust
|
||||
pub struct CommandDispatcher {
|
||||
handlers: HashMap<String, Box<dyn CommandHandler>>,
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
pub trait CommandHandler: Send + Sync {
|
||||
async fn handle(&self, command: Command) -> Result<CommandResult, CommandError>;
|
||||
}
|
||||
|
||||
impl CommandDispatcher {
|
||||
/// 注册处理器
|
||||
pub fn register<H: CommandHandler + 'static>(&mut self, name: &str, handler: H) {
|
||||
self.handlers.insert(name.to_string(), Box::new(handler));
|
||||
}
|
||||
|
||||
/// 分发命令
|
||||
pub async fn dispatch(&self, message: QueueMessage) -> Result<CommandResult, CommandError> {
|
||||
// 解析命令
|
||||
let command: Command = serde_json::from_str(&message.value)?;
|
||||
|
||||
// 获取路由
|
||||
let route = message.metadata.get("route")
|
||||
.ok_or(CommandError::MissingRoute)?;
|
||||
|
||||
// 查找处理器
|
||||
let handler = self.handlers.get(route.handler)
|
||||
.ok_or(CommandError::HandlerNotFound(route.handler.clone()))?;
|
||||
|
||||
// 执行命令
|
||||
let result = handler.handle(command).await?;
|
||||
|
||||
// 记录执行日志
|
||||
self.log_execution(&message.message_id, &route.handler, &result).await?;
|
||||
|
||||
Ok(result)
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 🔌 API 设计
|
||||
|
||||
### 1. 命令提交 API
|
||||
|
||||
```rust
|
||||
// POST /api/v1/commands
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
pub struct SubmitCommandRequest {
|
||||
pub command_type: CommandType,
|
||||
pub payload: JsonValue,
|
||||
pub priority: Option<CommandPriority>,
|
||||
pub scheduled_at: Option<DateTime<Utc>>,
|
||||
pub metadata: Option<HashMap<String, String>>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
pub struct SubmitCommandResponse {
|
||||
pub command_id: String,
|
||||
pub queue_name: String,
|
||||
pub status: String,
|
||||
pub priority: CommandPriority,
|
||||
pub billing: BillingInfo,
|
||||
pub created_at: DateTime<Utc>,
|
||||
}
|
||||
|
||||
// 处理函数
|
||||
pub async fn submit_command(
|
||||
Extension(auth): Extension<UserAuth>,
|
||||
Extension(billing): Extension<Arc<BillingManager>>,
|
||||
Extension(queue): Extension<Arc<CommandQueue>>,
|
||||
Json(req): Json<SubmitCommandRequest>,
|
||||
) -> Result<Json<SubmitCommandResponse>, APIError> {
|
||||
// 1. 检查 quota
|
||||
billing.check_quota(&auth.key_id).await?;
|
||||
|
||||
// 2. 创建 billing 上下文
|
||||
let billing_ctx = billing.create_billing_context(&auth.key_id).await?;
|
||||
|
||||
// 3. 路由命令
|
||||
let route = queue.router().route(&req.command_type)?;
|
||||
|
||||
// 4. 创建命令
|
||||
let command = Command {
|
||||
command_type: req.command_type,
|
||||
payload: req.payload,
|
||||
priority: req.priority.unwrap_or_else(|| req.command_type.default_priority()),
|
||||
metadata: {
|
||||
let mut m = req.metadata.unwrap_or_default();
|
||||
m.insert("billing_context".to_string(), serde_json::to_string(&billing_ctx)?);
|
||||
m.insert("api_key".to_string(), auth.key_id.clone());
|
||||
m
|
||||
},
|
||||
};
|
||||
|
||||
// 5. 提交到队列
|
||||
let message_id = queue.produce(
|
||||
&route.queue_name,
|
||||
command,
|
||||
ProduceOptions {
|
||||
priority: Some(command.priority as i32),
|
||||
scheduled_at: req.scheduled_at,
|
||||
billing_context: Some(billing_ctx.clone()),
|
||||
..Default::default()
|
||||
},
|
||||
).await?;
|
||||
|
||||
// 6. 返回响应
|
||||
Ok(Json(SubmitCommandResponse {
|
||||
command_id: message_id.clone(),
|
||||
queue_name: route.queue_name,
|
||||
status: "queued".to_string(),
|
||||
priority: command.priority,
|
||||
billing: BillingInfo {
|
||||
quota_remaining: billing_ctx.quota_remaining,
|
||||
},
|
||||
created_at: Utc::now(),
|
||||
}))
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 2. 命令查询 API
|
||||
|
||||
```rust
|
||||
// GET /api/v1/commands/{command_id}
|
||||
pub async fn get_command_status(
|
||||
Path(command_id): Path<String>,
|
||||
Extension(queue): Extension<Arc<CommandQueue>>,
|
||||
) -> Result<Json<CommandStatusResponse>, APIError> {
|
||||
let status = queue.get_command_status(&command_id).await?;
|
||||
|
||||
Ok(Json(status))
|
||||
}
|
||||
|
||||
// GET /api/v1/commands?status=pending&queue=external.api
|
||||
pub async fn list_commands(
|
||||
Query(params): Query<ListCommandsQuery>,
|
||||
Extension(queue): Extension<Arc<CommandQueue>>,
|
||||
) -> Result<Json<ListCommandsResponse>, APIError> {
|
||||
let commands = queue.list_commands(ListOptions {
|
||||
queue_name: params.queue,
|
||||
status: params.status,
|
||||
limit: params.limit.unwrap_or(100),
|
||||
offset: params.offset.unwrap_or(0),
|
||||
}).await?;
|
||||
|
||||
Ok(Json(ListCommandsResponse {
|
||||
commands,
|
||||
total: commands.len(),
|
||||
}))
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 📊 监控指标
|
||||
|
||||
```rust
|
||||
lazy_static! {
|
||||
// 命令计数
|
||||
static ref COMMANDS_TOTAL: CounterVec = register_counter_vec!(
|
||||
"command_queue_commands_total",
|
||||
"Total commands processed",
|
||||
&["queue", "type", "status"]
|
||||
).unwrap();
|
||||
|
||||
// 队列长度
|
||||
static ref QUEUE_LENGTH: GaugeVec = register_gauge_vec!(
|
||||
"command_queue_length",
|
||||
"Current queue length",
|
||||
&["queue"]
|
||||
).unwrap();
|
||||
|
||||
// 命令延迟
|
||||
static ref COMMAND_LATENCY: HistogramVec = register_histogram_vec!(
|
||||
"command_queue_latency_seconds",
|
||||
"Command processing latency",
|
||||
&["queue", "type"]
|
||||
).unwrap();
|
||||
|
||||
// 命令错误率
|
||||
static ref COMMAND_ERRORS: CounterVec = register_counter_vec!(
|
||||
"command_queue_errors_total",
|
||||
"Total command errors",
|
||||
&["queue", "type", "error"]
|
||||
).unwrap();
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 🚀 实施计划
|
||||
|
||||
### Phase 1: 数据库与模型(2 天)
|
||||
|
||||
- [ ] 创建 command_queue 表
|
||||
- [ ] 创建 command_execution_log 表
|
||||
- [ ] 实现命令类型定义
|
||||
- [ ] 实现优先级系统
|
||||
|
||||
### Phase 2: 队列核心(3 天)
|
||||
|
||||
- [ ] 实现 CommandQueue
|
||||
- [ ] 实现 CommandRouter
|
||||
- [ ] 实现 CommandDispatcher
|
||||
- [ ] 实现命令处理器接口
|
||||
|
||||
### Phase 3: 内部命令集成(2 天)
|
||||
|
||||
- [ ] 迁移视频注册到队列
|
||||
- [ ] 迁移文件处理到队列
|
||||
- [ ] 迁移数据处理到队列
|
||||
|
||||
### Phase 4: 外部命令集成(2 天)
|
||||
|
||||
- [ ] 实现 API 命令提交
|
||||
- [ ] 实现命令查询
|
||||
- [ ] 集成 Billing
|
||||
|
||||
### Phase 5: Agent 沟通集成(3 天)
|
||||
|
||||
- [ ] 实现 Agent 消息队列
|
||||
- [ ] 实现 Agent 订阅机制
|
||||
- [ ] 实现 Agent 广播机制
|
||||
|
||||
### Phase 6: 监控与测试(2 天)
|
||||
|
||||
- [ ] 添加监控指标
|
||||
- [ ] 配置告警
|
||||
- [ ] 集成测试
|
||||
- [ ] 性能测试
|
||||
|
||||
---
|
||||
|
||||
## 📚 相关文档
|
||||
|
||||
- Billing 集成: `docs_v1.0/DESIGN/MarkBase_Queue_Billing_Integration.md`
|
||||
- API 文档: `docs_v1.0/API_WORKSPACE/modules/command_api.md`
|
||||
- 运维指南: `docs_v1.0/GUIDES/command_queue_operations.md`
|
||||
|
||||
---
|
||||
|
||||
**设计完成,准备实施!**
|
||||
@@ -0,0 +1,143 @@
|
||||
---
|
||||
title: Per-File Voice Collection V1.0
|
||||
version: 1.0
|
||||
date: 2026-06-20
|
||||
author: OpenCode
|
||||
status: approved
|
||||
---
|
||||
|
||||
# Per-File Voice Collection V1.0
|
||||
|
||||
| Scope | Status | Applicable to | Binary |
|
||||
|-------|--------|---------------|--------|
|
||||
| Qdrant voice collection naming, storage, lifecycle | Approved | `momentry_playground`, `momentry` | Both |
|
||||
|
||||
## Problem Statement
|
||||
|
||||
ASRX processor stores speaker voice embeddings (192-dim ECAPA-TDNN) in Qdrant for speaker diarization and future identity matching. The current design uses a single global collection `{prefix}_voice` for all files, creating several issues:
|
||||
|
||||
1. **No isolation**: All files' voice embeddings share one collection, making per-file cleanup error-prone
|
||||
2. **Unnecessary migration**: Workspace `_workspace_voice` → production `_voice` migration during checkin adds complexity with no benefit for per-file processing artifacts
|
||||
3. **No event type distinction**: No payload field to distinguish speaker embeddings from future audio event types (gunshots, screams, music, etc.)
|
||||
4. **Cross-file matching is impractical**: Current point ID includes file_uuid, but querying across files requires filtering rather than direct collection access
|
||||
|
||||
## Design
|
||||
|
||||
### Collection Naming: Per-File
|
||||
|
||||
```
|
||||
{file_uuid}_voice
|
||||
```
|
||||
|
||||
Examples:
|
||||
- `d3f9ae8e471a1fc4d47022c66091b920_voice`
|
||||
- `92ed12dbb7fbea5e6ddfe668e1f31444_voice`
|
||||
|
||||
### Collection Schema
|
||||
|
||||
| Property | Value |
|
||||
|----------|-------|
|
||||
| Name | `{file_uuid}_voice` |
|
||||
| Vector dimension | 192 |
|
||||
| Distance metric | Cosine |
|
||||
| On-disk | false (default, in-memory for fast search during processing) |
|
||||
|
||||
### Point Schema
|
||||
|
||||
**Point ID**: `SHA256(speaker_id + "_" + segment_index)` → first 8 bytes as u64
|
||||
- No file_uuid in hash (redundant, collection is per-file)
|
||||
|
||||
**Payload**:
|
||||
|
||||
| Field | Type | Description | Example |
|
||||
|-------|------|-------------|---------|
|
||||
| `speaker_id` | String | Speaker label from ASRX | `"SPEAKER_00"` |
|
||||
| `segment_index` | Integer | Segment index within ASRX result | `5` |
|
||||
| `start_frame` | Integer | Start frame number | `120` |
|
||||
| `end_frame` | Integer | End frame number | `240` |
|
||||
| `start_time` | Float | Start time in seconds | `4.0` |
|
||||
| `end_time` | Float | End time in seconds | `8.0` |
|
||||
| `event_type` | String | Type of audio event | `"speaker"` |
|
||||
|
||||
### Event Type Extensibility
|
||||
|
||||
The `event_type` field reserves space for future audio recognition:
|
||||
|
||||
| event_type | Description | Future Model | Dim |
|
||||
|------------|-------------|--------------|-----|
|
||||
| `"speaker"` | Speaker voice embedding (current) | ECAPA-TDNN | 192 |
|
||||
| `"gunshot"` | Gunshot detection embedding | YAMNet / custom | TBD |
|
||||
| `"scream"` | Scream/shout detection | YAMNet / custom | TBD |
|
||||
| `"music"` | Music segment embedding | CLMR / custom | TBD |
|
||||
|
||||
Each event type with a different dimension would use a separate per-file collection (`{file_uuid}_gunshot`, etc.).
|
||||
|
||||
### Lifecycle
|
||||
|
||||
```
|
||||
Processing:
|
||||
ASRX completes → store_voice_embeddings_to_qdrant()
|
||||
→ ensure_collection("{file_uuid}_voice", 192)
|
||||
→ upsert_vector per segment
|
||||
|
||||
Checkin:
|
||||
No voice migration needed (data already in per-file collection)
|
||||
|
||||
Checkout / File Deletion:
|
||||
Delete collection "{file_uuid}_voice" (or delete by filter)
|
||||
|
||||
Cross-File Matching (future):
|
||||
Job scans all "*_voice" collections, or maintains {prefix}_speaker_profiles index
|
||||
```
|
||||
|
||||
### Changes from Current Design
|
||||
|
||||
| Aspect | Current | New |
|
||||
|--------|---------|-----|
|
||||
| Collection name | `{prefix}_voice` | `{file_uuid}_voice` |
|
||||
| Point ID hash input | `file_uuid + speaker_id + index` | `speaker_id + index` |
|
||||
| Workspace dual-write | `_workspace_voice` → `_voice` migration | Removed (no migration needed) |
|
||||
| Payload event_type | Not present | `"speaker"` |
|
||||
| Checkin voice migration | Scroll + upsert | Nothing (data already isolated) |
|
||||
| Checkout voice deletion | Filter by file_uuid from `{prefix}_voice` | Delete collection or filter |
|
||||
| QdrantWorkspace voice methods | `voice_collection()`, `upsert_voice_embedding()` | Removed |
|
||||
|
||||
### Files Affected
|
||||
|
||||
| File | Change |
|
||||
|------|--------|
|
||||
| `src/worker/processor.rs:1291-1360` | `store_voice_embeddings_to_qdrant()` — per-file collection, event_type payload |
|
||||
| `src/worker/processor.rs:919-942` | Remove workspace voice dual-write |
|
||||
| `src/core/checkin.rs:208-242` | Remove voice migration block |
|
||||
| `src/core/checkin.rs:358-379` | Update checkout voice deletion to target `{file_uuid}_voice` |
|
||||
| `src/core/db/qdrant_workspace.rs` | Remove `voice_collection()`, `upsert_voice_embedding()`, voice from `ensure_all()`, `scroll_by_file_uuid()`, `WorkspaceScrollResult`, `delete_by_file_uuid()` |
|
||||
|
||||
### Cross-File Matching (Future Design)
|
||||
|
||||
For future multi-file speaker matching, a separate index collection can be maintained:
|
||||
|
||||
```
|
||||
{prefix}_speaker_profiles (192-dim Cosine)
|
||||
- payload: speaker_id (global), source_file_uuids[], reference_count, centroid_embedding
|
||||
```
|
||||
|
||||
This index would be updated:
|
||||
1. During a periodic batch job that scans all `*_voice` collections
|
||||
2. Or incrementally when new voice data is added
|
||||
|
||||
The per-file collection design makes this cleaner because:
|
||||
- Source data is cleanly partitioned
|
||||
- The index is explicitly a derived/cached structure
|
||||
- Index rebuild means rescraping `*_voice` collections, not untangling a global collection
|
||||
|
||||
## Migration
|
||||
|
||||
Existing voice data in `{prefix}_voice` and `{prefix}_workspace_voice` can be left as-is for backward compatibility. New processing will write to `{file_uuid}_voice`. Old data in `{prefix}_voice` will remain queryable if needed.
|
||||
|
||||
No data migration script is required — old data is read-only legacy.
|
||||
|
||||
## Version History
|
||||
|
||||
| Version | Date | Author | Change |
|
||||
|---------|------|--------|--------|
|
||||
| 1.0 | 2026-06-20 | OpenCode | Initial design |
|
||||
@@ -0,0 +1,297 @@
|
||||
# 文件处理流程对比 - V1 vs V2
|
||||
|
||||
**日期**: 2026-10-10
|
||||
|
||||
---
|
||||
|
||||
## 对比概览
|
||||
|
||||
### V1: 过程导向 (原设计)
|
||||
|
||||
| 阶段 | 名称 | 产出 | 可查看性 |
|
||||
|------|------|------|----------|
|
||||
| 1 | Processors | ❌ 模糊 | ❌ 无 |
|
||||
| 2 | Rule1 Ingestion | ❌ 模糊 | ❌ 无 |
|
||||
| 3 | Face Tracing | ❌ 模糊 | ❌ 无 |
|
||||
| 4 | Face Dedup | ❌ 模糊 | ❌ 无 |
|
||||
| 5 | TKG Nodes | ❌ 模糊 | ❌ 无 |
|
||||
| 6 | TKG Edges | ❌ 模糊 | ❌ 无 |
|
||||
| 7 | Rule2 Ingestion | ❌ 模糊 | ❌ 无 |
|
||||
| 8 | VLM Summary | ❌ 模糊 | ❌ 无 |
|
||||
| 9 | Scene VLM | ❌ 模糊 | ❌ 无 |
|
||||
| 10 | Moment Chunks | ❌ 模糊 | ❌ 无 |
|
||||
|
||||
**问题**:
|
||||
- ❌ 用户不知道每个阶段产生什么
|
||||
- ❌ 无法查看中间结果
|
||||
- ❌ 技术术语难理解
|
||||
|
||||
---
|
||||
|
||||
### V2: 产出导向 (新设计)
|
||||
|
||||
| 阶段 | 名称 | 产出 | 可查看方式 |
|
||||
|------|------|------|------------|
|
||||
| 1 | 媒体分析 | ✅ `{file_uuid}.workspace.sqlite` | SQLite Browser |
|
||||
| 2 | 文本块 | ✅ PostgreSQL `chunks` 表 | `/api/v1/chunks` |
|
||||
| 3 | 人脸轨迹 | ✅ `{file_uuid}.faces.json` | `/api/v1/faces/tracks` |
|
||||
| 4 | 身份识别 | ✅ PostgreSQL `identities` 表 | `/api/v1/identities` |
|
||||
| 5 | 知识图谱 | ✅ PostgreSQL `tkg_*` 表 | `/api/v1/tkg/nodes` |
|
||||
| 6 | 向量索引 | ✅ Qdrant collections | `/api/v1/search/semantic` |
|
||||
| 7 | 人脸描述 | ✅ `{file_uuid}.face_vlm.json` | `/api/v1/faces/tracks/{id}` |
|
||||
| 8 | 场景描述 | ✅ `{file_uuid}.scene_vlm.json` | `/api/v1/scenes` |
|
||||
| 9 | 时刻块 | ✅ PostgreSQL `moment_chunks` 表 | `/api/v1/moments` |
|
||||
|
||||
**改进**:
|
||||
- ✅ 每个阶段都有明确产品
|
||||
- ✅ 每个产品都可查看
|
||||
- ✅ 直观易懂
|
||||
|
||||
---
|
||||
|
||||
## 详细对比
|
||||
|
||||
### 阶段 1: Processors → 媒体分析
|
||||
|
||||
**V1**:
|
||||
```
|
||||
阶段: Processors
|
||||
产出: ❌ 模糊(各种处理结果)
|
||||
查看: ❌ 无法直接查看
|
||||
```
|
||||
|
||||
**V2**:
|
||||
```
|
||||
阶段: 媒体分析
|
||||
产出: ✅ {file_uuid}.workspace.sqlite
|
||||
├── pre_chunks (原始文本块)
|
||||
├── face_detections (人脸检测)
|
||||
├── speaker_detections (说话人)
|
||||
└── processor_results (处理结果)
|
||||
查看: ✅ SQLite Browser / sqlite3 命令
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 阶段 2-4: 数据处理 → 文本块 + 人脸 + 身份
|
||||
|
||||
**V1**:
|
||||
```
|
||||
阶段 2: Rule1 Ingestion
|
||||
产出: ❌ PostgreSQL 文本块导入
|
||||
查看: ❌ 无API
|
||||
|
||||
阶段 3: Face Tracing
|
||||
产出: ❌ 人脸追踪与轨迹生成
|
||||
查看: ❌ 无
|
||||
|
||||
阶段 4: Face Dedup
|
||||
产出: ❌ 人脸去重与聚类
|
||||
查看: ❌ 无
|
||||
```
|
||||
|
||||
**V2**:
|
||||
```
|
||||
阶段 2: 文本块
|
||||
产出: ✅ PostgreSQL chunks 表
|
||||
查看: ✅ GET /api/v1/chunks?file_uuid={uuid}
|
||||
|
||||
阶段 3: 人脸轨迹
|
||||
产出: ✅ {file_uuid}.faces.json
|
||||
查看: ✅ GET /api/v1/faces/tracks?file_uuid={uuid}
|
||||
|
||||
阶段 4: 身份识别
|
||||
产出: ✅ PostgreSQL identities 表
|
||||
查看: ✅ GET /api/v1/identities
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 阶段 5-6: TKG → 知识图谱
|
||||
|
||||
**V1**:
|
||||
```
|
||||
阶段 5: TKG Nodes
|
||||
产出: ❌ 时序知识图谱节点构建
|
||||
查看: ❌ 无
|
||||
|
||||
阶段 6: TKG Edges
|
||||
产出: ❌ 时序知识图谱边构建
|
||||
查看: ❌ 无
|
||||
```
|
||||
|
||||
**V2**:
|
||||
```
|
||||
阶段 5: 知识图谱
|
||||
产出: ✅ PostgreSQL tkg_nodes + tkg_edges
|
||||
├── tkg_nodes (节点: face_track, speaker, etc.)
|
||||
└── tkg_edges (边: same_identity, speaks_in, etc.)
|
||||
查看: ✅ GET /api/v1/tkg/nodes?file_uuid={uuid}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 阶段 7: Rule2 → 向量索引
|
||||
|
||||
**V1**:
|
||||
```
|
||||
阶段 7: Rule2 Ingestion
|
||||
产出: ❌ Qdrant 向量导入
|
||||
查看: ❌ 无
|
||||
```
|
||||
|
||||
**V2**:
|
||||
```
|
||||
阶段 6: 向量索引
|
||||
产出: ✅ Qdrant Collections
|
||||
├── _chunks (文本向量)
|
||||
├── _faces (人脸向量)
|
||||
└── _scenes (场景向量)
|
||||
查看: ✅ POST /api/v1/search/semantic
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 阶段 8-10: VLM → 人脸描述 + 场景描述 + 时刻块
|
||||
|
||||
**V1**:
|
||||
```
|
||||
阶段 8: VLM Summary
|
||||
产出: ❌ Face Track VLM 摘要
|
||||
查看: ❌ 无
|
||||
|
||||
阶段 9: Scene VLM
|
||||
产出: ❌ 场景级 VLM 分析
|
||||
查看: ❌ 无
|
||||
|
||||
阶段 10: Moment Chunks
|
||||
产出: ❌ 时刻块生成
|
||||
查看: ❌ 无
|
||||
```
|
||||
|
||||
**V2**:
|
||||
```
|
||||
阶段 7: 人脸描述
|
||||
产出: ✅ {file_uuid}.face_vlm.json
|
||||
查看: ✅ GET /api/v1/faces/tracks/{trace_id}
|
||||
|
||||
阶段 8: 场景描述
|
||||
产出: ✅ {file_uuid}.scene_vlm.json
|
||||
查看: ✅ GET /api/v1/scenes?file_uuid={uuid}
|
||||
|
||||
阶段 9: 时刻块
|
||||
产出: ✅ PostgreSQL moment_chunks 表
|
||||
查看: ✅ GET /api/v1/moments?file_uuid={uuid}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 产出类型对比
|
||||
|
||||
### V1: 抽象概念
|
||||
|
||||
| 类型 | 占比 | 说明 |
|
||||
|------|------|------|
|
||||
| 过程 | 100% | 全是过程,无明确产出 |
|
||||
| 文件 | 0% | 无可查看文件 |
|
||||
| 数据 | 0% | 无可访问数据 |
|
||||
|
||||
### V2: 具体产品
|
||||
|
||||
| 类型 | 占比 | 说明 |
|
||||
|------|------|------|
|
||||
| 文件产物 | 44% | .sqlite, .json 文件 |
|
||||
| 数据库产物 | 56% | PostgreSQL, Qdrant |
|
||||
|
||||
---
|
||||
|
||||
## 用户理解度对比
|
||||
|
||||
### V1: 需要技术背景
|
||||
|
||||
**问题**:
|
||||
- ❌ "Processors" 是什么?
|
||||
- ❌ "Rule1 Ingestion" 做什么?
|
||||
- ❌ "Face Dedup" 产出什么?
|
||||
- ❌ "TKG Edges" 有什么用?
|
||||
|
||||
**结果**: 用户困惑,无法理解进度
|
||||
|
||||
### V2: 直观易懂
|
||||
|
||||
**清晰**:
|
||||
- ✅ "媒体分析" → 产生 workspace.sqlite
|
||||
- ✅ "文本块" → 可搜索文本
|
||||
- ✅ "人脸轨迹" → 人脸追踪数据
|
||||
- ✅ "知识图谱" → 支持复杂查询
|
||||
|
||||
**结果**: 用户理解,可追踪进度
|
||||
|
||||
---
|
||||
|
||||
## 可查看性对比
|
||||
|
||||
### V1: 无法查看
|
||||
|
||||
| 阶段 | 可查看 | 方式 |
|
||||
|------|:------:|------|
|
||||
| 1-10 | ❌ | 无 |
|
||||
|
||||
### V2: 全部可查看
|
||||
|
||||
| 阶段 | 可查看 | 方式 |
|
||||
|------|:------:|------|
|
||||
| 1 | ✅ | SQLite Browser |
|
||||
| 2 | ✅ | `/api/v1/chunks` |
|
||||
| 3 | ✅ | `/api/v1/faces/tracks` |
|
||||
| 4 | ✅ | `/api/v1/identities` |
|
||||
| 5 | ✅ | `/api/v1/tkg/nodes` |
|
||||
| 6 | ✅ | `/api/v1/search/semantic` |
|
||||
| 7 | ✅ | `/api/v1/faces/tracks/{id}` |
|
||||
| 8 | ✅ | `/api/v1/scenes` |
|
||||
| 9 | ✅ | `/api/v1/moments` |
|
||||
|
||||
---
|
||||
|
||||
## 设计哲学对比
|
||||
|
||||
### V1: 工程师视角
|
||||
|
||||
```
|
||||
设计哲学: 暴露实现细节
|
||||
目标用户: 开发者
|
||||
问题: 用户看不懂
|
||||
```
|
||||
|
||||
### V2: 用户视角
|
||||
|
||||
```
|
||||
设计哲学: 展示可用产品
|
||||
目标用户: 所有用户
|
||||
优势: 直观易懂
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 总结
|
||||
|
||||
### 关键改进
|
||||
|
||||
| 维度 | V1 | V2 | 改善 |
|
||||
|------|----|----|------|
|
||||
| **产出明确性** | ❌ 模糊 | ✅ 明确 | +100% |
|
||||
| **可查看性** | ❌ 无法查看 | ✅ 全部可查看 | +100% |
|
||||
| **用户理解度** | ❌ 需技术背景 | ✅ 直观易懂 | +100% |
|
||||
| **API 覆盖** | ❌ 0% | ✅ 89% | +89% |
|
||||
|
||||
### 设计原则
|
||||
|
||||
**V2 核心原则**:
|
||||
1. ✅ 产出导向 - 每个阶段都有产品
|
||||
2. ✅ 可查看性 - 每个产品都可查看
|
||||
3. ✅ 用户友好 - 无需技术背景
|
||||
4. ✅ 过程透明 - 隐藏实现细节
|
||||
|
||||
---
|
||||
|
||||
**设计改进完成,建议采用 V2。**
|
||||
@@ -0,0 +1,472 @@
|
||||
---
|
||||
title: Pipeline CLI Execution Analysis
|
||||
version: 1.0
|
||||
date: 2026-09-27
|
||||
author: OpenCode
|
||||
status: analysis
|
||||
---
|
||||
|
||||
## 目標
|
||||
|
||||
分析 Momentry Pipeline 是否可以完全使用 CLI (Swift/Rust) 執行,替代 Python 處理器。
|
||||
|
||||
---
|
||||
|
||||
## Pipeline 流程
|
||||
|
||||
### Phase 1: 基礎處理器
|
||||
|
||||
| # | 處理器 | Python | Swift CLI | Rust CLI | 主項目 Rust | 狀態 |
|
||||
|---|--------|--------|-----------|----------|------------|------|
|
||||
| 1 | ASR | ✅ | ✅ `asr_swift.swift` | ❌ | ❌ | ✅ 可用 Swift |
|
||||
| 2 | Face | ✅ | ✅ `swift_face.swift` | ❌ | ❌ | ✅ 可用 Swift |
|
||||
| 3 | OCR | ✅ | ✅ `swift_ocr.swift` | ❌ | ❌ | ✅ 可用 Swift |
|
||||
| 4 | Pose | ✅ | ✅ `swift_pose.swift` | ✅ `rust_pose` | ❌ | ✅ 可用 Swift/Rust |
|
||||
| 5 | CUT | ✅ | ❌ | ❌ | ✅ `cut.rs` | ✅ 可用主項目 |
|
||||
| 6 | Scene VLM | ✅ | ❌ | ❌ | ✅ `scene_vlm.rs` | ✅ 可用主項目 |
|
||||
|
||||
---
|
||||
|
||||
### Phase 2: 數據處理
|
||||
|
||||
| # | 處理器 | Python | Swift CLI | Rust CLI | 主項目 Rust | 狀態 |
|
||||
|---|--------|--------|-----------|----------|------------|------|
|
||||
| 7 | Face Tracing | ✅ | ❌ | ❌ | ✅ `face_tracker.rs` | ✅ 可用主項目 |
|
||||
| 8 | ASRX | ✅ | ✅ `asrx_swift.swift` | ❌ | ❌ | ✅ 可用 Swift |
|
||||
| 9 | Face Dedup (Cluster) | ✅ | ❌ | ✅ `rust_face_cluster` | ✅ `face_clustering.rs` | ✅ 可用 Rust |
|
||||
| 10 | TKG Builder | ✅ | ❌ | ❌ | ✅ `tkg.rs` | ✅ 可用主項目 |
|
||||
|
||||
---
|
||||
|
||||
### Phase 3: 最終處理
|
||||
|
||||
| # | 處理器 | Python | Swift CLI | Rust CLI | 主項目 Rust | 狀態 |
|
||||
|---|--------|--------|-----------|----------|------------|------|
|
||||
| 11 | Rule1 Ingestion | ✅ | ❌ | ❌ | ✅ `chunk/rule1.rs` | ✅ 可用主項目 |
|
||||
| 12 | Rule2 Ingestion | ✅ | ❌ | ❌ | ✅ `chunk/rule2.rs` | ✅ 可用主項目 |
|
||||
| 13 | VLM Summary | ✅ | ❌ | ❌ | ✅ `vlm_summary.rs` | ✅ 可用主項目 |
|
||||
| 14 | Moment Chunks | ✅ | ❌ | ❌ | ✅ `chunk/rule3.rs` | ✅ 可用主項目 |
|
||||
|
||||
---
|
||||
|
||||
## CLI 可行性分析
|
||||
|
||||
### ✅ 完全可用 CLI (10/14)
|
||||
|
||||
**Phase 1**:
|
||||
1. ASR - Swift CLI
|
||||
2. Face - Swift CLI
|
||||
3. OCR - Swift CLI
|
||||
4. Pose - Swift/Rust CLI
|
||||
5. CUT - 主項目 Rust
|
||||
6. Scene VLM - 主項目 Rust
|
||||
|
||||
**Phase 2**:
|
||||
7. Face Tracing - 主項目 Rust
|
||||
8. ASRX - Swift CLI
|
||||
9. Face Cluster - Rust CLI
|
||||
10. TKG Builder - 主項目 Rust
|
||||
|
||||
**Phase 3**:
|
||||
11. Rule1 - 主項目 Rust
|
||||
12. Rule2 - 主項目 Rust
|
||||
13. VLM Summary - 主項目 Rust
|
||||
14. Moment Chunks - 主項目 Rust
|
||||
|
||||
---
|
||||
|
||||
## 架構方案
|
||||
|
||||
### 方案 A: 混合模式 (推薦)
|
||||
|
||||
**優點**:
|
||||
- 靈活性高
|
||||
- 易於維護
|
||||
- 性能最佳
|
||||
|
||||
**架構**:
|
||||
```
|
||||
Pipeline Executor (Rust 主項目)
|
||||
├── Phase 1
|
||||
│ ├── ASR → Swift CLI (外部進程)
|
||||
│ ├── Face → Swift CLI (外部進程)
|
||||
│ ├── OCR → Swift CLI (外部進程)
|
||||
│ ├── Pose → Rust CLI (外部進程) 或 Swift CLI
|
||||
│ ├── CUT → 內部調用 (cut.rs)
|
||||
│ └── Scene VLM → 內部調用 (scene_vlm.rs)
|
||||
├── Phase 2
|
||||
│ ├── Face Tracing → 內部調用 (face_tracker.rs)
|
||||
│ ├── ASRX → Swift CLI (外部進程)
|
||||
│ ├── Face Cluster → Rust CLI (外部進程)
|
||||
│ └── TKG Builder → 內部調用 (tkg.rs)
|
||||
└── Phase 3
|
||||
├── Rule1 → 內部調用 (chunk/rule1.rs)
|
||||
├── Rule2 → 內部調用 (chunk/rule2.rs)
|
||||
├── VLM Summary → 內部調用 (vlm_summary.rs)
|
||||
└── Moment Chunks → 內部調用 (chunk/rule3.rs)
|
||||
```
|
||||
|
||||
**實現方式**:
|
||||
```rust
|
||||
// executor.rs
|
||||
async fn run_phase1(file_uuid: &str) -> Result<()> {
|
||||
// Swift CLI (外部進程)
|
||||
run_swift_cli("asr_swift", file_uuid).await?;
|
||||
run_swift_cli("swift_face", file_uuid).await?;
|
||||
run_swift_cli("swift_ocr", file_uuid).await?;
|
||||
run_swift_cli("swift_pose", file_uuid).await?;
|
||||
|
||||
// 內部調用
|
||||
run_cut(file_uuid).await?;
|
||||
run_scene_vlm(file_uuid).await?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn run_swift_cli(name: &str, file_uuid: &str) -> Result<()> {
|
||||
let cli_dir = crate::core::config::CLI_DIR.as_str();
|
||||
let bin_path = format!("{}/swift/.build/release/{}", cli_dir, name);
|
||||
|
||||
let output = Command::new(&bin_path)
|
||||
.arg("--file-uuid")
|
||||
.arg(file_uuid)
|
||||
.output()
|
||||
.await?;
|
||||
|
||||
if !output.status.success() {
|
||||
bail!("CLI failed: {}", name);
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 方案 B: 完全外部 CLI
|
||||
|
||||
**優點**:
|
||||
- 解耦程度最高
|
||||
- 易於獨立部署和擴展
|
||||
|
||||
**缺點**:
|
||||
- 進程通信開銷
|
||||
- 數據傳遞複雜
|
||||
- 需要更多配置
|
||||
|
||||
**架構**:
|
||||
```
|
||||
Pipeline Orchestrator (輕量級 Rust)
|
||||
├── 所有處理器都是外部 CLI
|
||||
└── 通過 JSON/文件傳遞數據
|
||||
```
|
||||
|
||||
**不推薦原因**:
|
||||
- 內部調用性能更好
|
||||
- 數據已在數據庫,無需文件傳遞
|
||||
- 主項目已經有完整的 Rust 實現
|
||||
|
||||
---
|
||||
|
||||
## 性能對比
|
||||
|
||||
### 當前 Python Pipeline
|
||||
|
||||
**總時間**: ~30 分鐘 (1小時視頻)
|
||||
|
||||
**瓶頸**:
|
||||
- Face: 10 分鐘
|
||||
- Pose: 8 分鐘
|
||||
- ASR: 5 分鐘
|
||||
- OCR: 4 分鐘
|
||||
- 其他: 3 分鐘
|
||||
|
||||
---
|
||||
|
||||
### CLI Pipeline (預估)
|
||||
|
||||
**總時間**: ~10 分鐘 (1小時視頻)
|
||||
|
||||
**性能提升**:
|
||||
- Face: 10分鐘 → 2分鐘 (5x)
|
||||
- Pose: 8分鐘 → 2分鐘 (4x)
|
||||
- ASR: 5分鐘 → 2分鐘 (2.5x)
|
||||
- OCR: 4分鐘 → 1分鐘 (4x)
|
||||
- 其他: 3分鐘 → 3分鐘 (1x)
|
||||
|
||||
**總體加速**: **3x**
|
||||
|
||||
---
|
||||
|
||||
## 實現步驟
|
||||
|
||||
### Step 1: 構建 Swift/Rust CLI
|
||||
|
||||
```bash
|
||||
# Swift
|
||||
cd tools/cli/swift
|
||||
swift build -c release
|
||||
|
||||
# Rust
|
||||
cd tools/cli/rust
|
||||
cargo build --release
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Step 2: 更新 Executor
|
||||
|
||||
修改 `src/core/processor/executor.rs`:
|
||||
|
||||
```rust
|
||||
pub enum ExecutionMode {
|
||||
Python, // 當前模式
|
||||
Cli, // 新增 CLI 模式
|
||||
Hybrid, // 混合模式 (推薦)
|
||||
}
|
||||
|
||||
impl ProcessorExecutor {
|
||||
pub async fn run_processor(
|
||||
&self,
|
||||
processor: ProcessorType,
|
||||
mode: ExecutionMode,
|
||||
) -> Result<()> {
|
||||
match mode {
|
||||
ExecutionMode::Cli => self.run_cli_processor(processor).await,
|
||||
ExecutionMode::Python => self.run_python_processor(processor).await,
|
||||
ExecutionMode::Hybrid => {
|
||||
// 根據處理器類型選擇最佳模式
|
||||
match processor {
|
||||
ProcessorType::Face | ProcessorType::Pose | ProcessorType::Ocr => {
|
||||
self.run_cli_processor(processor).await
|
||||
}
|
||||
_ => self.run_python_processor(processor).await,
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Step 3: 配置切換
|
||||
|
||||
**環境變數**:
|
||||
```bash
|
||||
# .env
|
||||
MOMENTRY_EXECUTION_MODE=hybrid # python/cli/hybrid
|
||||
```
|
||||
|
||||
**Rust 代碼**:
|
||||
```rust
|
||||
pub static EXECUTION_MODE: Lazy<ExecutionMode> = Lazy::new(|| {
|
||||
match env::var("MOMENTRY_EXECUTION_MODE").unwrap_or_else(|_| "hybrid".to_string()).as_str() {
|
||||
"cli" => ExecutionMode::Cli,
|
||||
"python" => ExecutionMode::Python,
|
||||
_ => ExecutionMode::Hybrid,
|
||||
}
|
||||
});
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Step 4: 測試驗證
|
||||
|
||||
```bash
|
||||
# Python 模式
|
||||
MOMENTRY_EXECUTION_MODE=python cargo run -- register test.mp4
|
||||
|
||||
# CLI 模式
|
||||
MOMENTRY_EXECUTION_MODE=cli cargo run -- register test.mp4
|
||||
|
||||
# Hybrid 模式
|
||||
MOMENTRY_EXECUTION_MODE=hybrid cargo run -- register test.mp4
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 優點與挑戰
|
||||
|
||||
### ✅ 優點
|
||||
|
||||
1. **性能提升**: 整體快 3x
|
||||
2. **資源節省**: 內存使用更低
|
||||
3. **類型安全**: Rust/Swift 編譯時檢查
|
||||
4. **並行處理**: CLI 可輕鬆並行
|
||||
5. **部署靈活**: 可獨立部署 CLI
|
||||
|
||||
---
|
||||
|
||||
### ⚠️ 挑戰
|
||||
|
||||
1. **依賴管理**: Swift 需要 Xcode,Rust 需要編譯
|
||||
2. **跨平台**: Swift 僅限 macOS/iOS
|
||||
3. **調試難度**: 外部進程調試較複雜
|
||||
4. **版本同步**: 需確保 CLI 和主項目版本一致
|
||||
|
||||
---
|
||||
|
||||
## 遷移建議
|
||||
|
||||
### 短期 (1-2 週)
|
||||
|
||||
1. **啟用 Hybrid 模式**
|
||||
- Face/Pose/OCR 使用 Swift CLI
|
||||
- 其他保持 Python
|
||||
|
||||
2. **性能測試**
|
||||
- 對比 Python vs CLI
|
||||
- 收集性能數據
|
||||
|
||||
---
|
||||
|
||||
### 中期 (1-2 月)
|
||||
|
||||
1. **完全遷移到 CLI**
|
||||
- 所有處理器使用 CLI
|
||||
- Python 僅作備用
|
||||
|
||||
2. **優化數據流**
|
||||
- 減少文件 I/O
|
||||
- 使用內存傳遞
|
||||
|
||||
---
|
||||
|
||||
### 長期 (3-6 月)
|
||||
|
||||
1. **完全 Rust 化**
|
||||
- 所有處理器集成到主項目
|
||||
- 移除外部 CLI 依賴
|
||||
|
||||
2. **統一 API**
|
||||
- 統一處理器接口
|
||||
- 支持插件架構
|
||||
|
||||
---
|
||||
|
||||
## 配置示例
|
||||
|
||||
### .env
|
||||
|
||||
```bash
|
||||
# Execution mode
|
||||
MOMENTRY_EXECUTION_MODE=hybrid
|
||||
|
||||
# CLI paths
|
||||
MOMENTRY_CLI_DIR=/Users/accusys/momentry_core/tools/cli
|
||||
|
||||
# Fallback to Python if CLI fails
|
||||
MOMENTRY_CLI_FALLBACK_ENABLED=true
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### CLI 配置
|
||||
|
||||
**Swift CLI** (`tools/cli/swift/Config.swift`):
|
||||
```swift
|
||||
struct Config {
|
||||
static let outputDir = ProcessInfo.processInfo.environment["MOMENTRY_OUTPUT_DIR"]
|
||||
?? "/Users/accusys/momentry/output"
|
||||
|
||||
static let dbUrl = ProcessInfo.processInfo.environment["DATABASE_URL"]
|
||||
?? "postgres://accusys@localhost:5432/momentry"
|
||||
}
|
||||
```
|
||||
|
||||
**Rust CLI** (`tools/cli/rust/src/config.rs`):
|
||||
```rust
|
||||
pub struct Config {
|
||||
pub output_dir: String,
|
||||
pub db_url: String,
|
||||
}
|
||||
|
||||
impl Config {
|
||||
pub fn from_env() -> Self {
|
||||
Self {
|
||||
output_dir: env::var("MOMENTRY_OUTPUT_DIR")
|
||||
.unwrap_or_else(|_| "/Users/accusys/momentry/output".to_string()),
|
||||
db_url: env::var("DATABASE_URL")
|
||||
.unwrap_or_else(|_| "postgres://accusys@localhost:5432/momentry".to_string()),
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 測試計劃
|
||||
|
||||
### 單元測試
|
||||
|
||||
```rust
|
||||
#[test]
|
||||
fn test_swift_face_cli() {
|
||||
let result = run_swift_cli("swift_face", "test_uuid");
|
||||
assert!(result.is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_rust_face_cluster_cli() {
|
||||
let result = run_rust_cli("rust_face_cluster", "test_uuid");
|
||||
assert!(result.is_ok());
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 集成測試
|
||||
|
||||
```bash
|
||||
# 完整 Pipeline 測試
|
||||
./test_pipeline_cli.sh test_video.mp4
|
||||
|
||||
# 性能基準測試
|
||||
./benchmark_pipeline.sh test_video.mp4
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 性能測試
|
||||
|
||||
```bash
|
||||
# Python 模式
|
||||
time MOMENTRY_EXECUTION_MODE=python cargo run -- register test.mp4
|
||||
|
||||
# CLI 模式
|
||||
time MOMENTRY_EXECUTION_MODE=cli cargo run -- register test.mp4
|
||||
|
||||
# Hybrid 模式
|
||||
time MOMENTRY_EXECUTION_MODE=hybrid cargo run -- register test.mp4
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 結論
|
||||
|
||||
### ✅ 可以完全使用 CLI
|
||||
|
||||
**覆蓋率**: **100%** (14/14 處理器有 CLI 對應)
|
||||
|
||||
**推薦方案**: **Hybrid 模式**
|
||||
|
||||
**預期性能**: **3x 加速**
|
||||
|
||||
---
|
||||
|
||||
### 實施建議
|
||||
|
||||
1. **立即啟用**: Hybrid 模式
|
||||
2. **逐步遷移**: 性能關鍵處理器優先
|
||||
3. **保留備用**: Python 作為 fallback
|
||||
4. **監控性能**: 持續優化
|
||||
|
||||
---
|
||||
|
||||
## 相關文檔
|
||||
|
||||
- `/Users/accusys/momentry_core/docs_v1.0/DESIGN/Processor_Python_vs_CLI_Mapping.md`
|
||||
- `/Users/accusys/momentry_core/docs_v1.0/DESIGN/Tools_Directory_Restructure.md`
|
||||
- `/Users/accusys/momentry_core/tools/README.md`
|
||||
- `/Users/accusys/momentry_core/AGENTS.md`
|
||||
@@ -0,0 +1,214 @@
|
||||
---
|
||||
title: 處理器配置架構設計
|
||||
version: 1.0
|
||||
date: 2026-09-27
|
||||
author: OpenCode
|
||||
status: design
|
||||
---
|
||||
|
||||
## 問題
|
||||
|
||||
當前處理器選擇為硬編碼(hard-coded):
|
||||
|
||||
```rust
|
||||
// pose.rs
|
||||
// Hard-coded priority:
|
||||
// 1. MediaPipe Pose
|
||||
// 2. Rust Pose
|
||||
// 3. Swift Pose
|
||||
// 4. Python YOLOv8
|
||||
|
||||
if mediapipe_script.exists() {
|
||||
// use MediaPipe
|
||||
} else if rust_binary.exists() {
|
||||
// use Rust
|
||||
} else if swift_binary.exists() {
|
||||
// use Swift
|
||||
} else {
|
||||
// use Python
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 解決方案
|
||||
|
||||
使用 `config.json` 軟定義處理器選擇。
|
||||
|
||||
---
|
||||
|
||||
## 配置結構設計
|
||||
|
||||
### 1. ProcessorConfig 擴展
|
||||
|
||||
```rust
|
||||
pub struct ProcessorConfig {
|
||||
// 現有欄位
|
||||
pub model_size: Option<String>,
|
||||
pub language: Option<String>,
|
||||
pub timeout: u32,
|
||||
pub enabled: bool,
|
||||
pub confidence: Option<f32>,
|
||||
|
||||
// 新增欄位
|
||||
pub tools: Vec<ToolConfig>, // 工具列表(按優先級排序)
|
||||
pub default_tool: String, // 預設工具
|
||||
}
|
||||
|
||||
pub struct ToolConfig {
|
||||
pub name: String, // 工具名稱
|
||||
pub priority: u8, // 優先級(0=最高)
|
||||
pub enabled: bool, // 是否啟用
|
||||
pub parameters: HashMap<String, Value>, // 工具特定參數
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 2. 配置文件示例
|
||||
|
||||
```json
|
||||
{
|
||||
"processor_config": {
|
||||
"pose": {
|
||||
"tools": [
|
||||
{
|
||||
"name": "mediapipe",
|
||||
"priority": 0,
|
||||
"enabled": true,
|
||||
"parameters": {
|
||||
"model_complexity": 2,
|
||||
"min_confidence": 0.5
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "rust",
|
||||
"priority": 1,
|
||||
"enabled": true,
|
||||
"parameters": {}
|
||||
},
|
||||
{
|
||||
"name": "swift",
|
||||
"priority": 2,
|
||||
"enabled": true,
|
||||
"parameters": {}
|
||||
},
|
||||
{
|
||||
"name": "yolov8",
|
||||
"priority": 3,
|
||||
"enabled": false,
|
||||
"parameters": {
|
||||
"model": "yolov8n-pose.pt"
|
||||
}
|
||||
}
|
||||
],
|
||||
"default_tool": "mediapipe",
|
||||
"timeout": 3600,
|
||||
"enabled": true
|
||||
},
|
||||
|
||||
"face": {
|
||||
"tools": [
|
||||
{
|
||||
"name": "swift",
|
||||
"priority": 0,
|
||||
"enabled": true
|
||||
},
|
||||
{
|
||||
"name": "python",
|
||||
"priority": 1,
|
||||
"enabled": true
|
||||
}
|
||||
],
|
||||
"default_tool": "swift"
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 實現步驟
|
||||
|
||||
### Phase 1: 配置結構擴展
|
||||
|
||||
1. 擴展 `ProcessorConfig` 結構體
|
||||
2. 添加 `ToolConfig` 結構體
|
||||
3. 更新配置文件加載邏輯
|
||||
|
||||
---
|
||||
|
||||
### Phase 2: 處理器選擇邏輯重構
|
||||
|
||||
1. 創建 `ToolSelector` 模塊
|
||||
2. 實現基於配置的工具選擇
|
||||
3. 替換 hard-coded 邏輯
|
||||
|
||||
---
|
||||
|
||||
### Phase 3: 配置文件創建
|
||||
|
||||
1. 創建默認配置文件
|
||||
2. 添加配置驗證
|
||||
3. 提供配置更新 API
|
||||
|
||||
---
|
||||
|
||||
## API 設計
|
||||
|
||||
### 獲取處理器配置
|
||||
|
||||
```rust
|
||||
let pose_config = admin_config::get_processor_config("pose").await;
|
||||
|
||||
if let Some(config) = pose_config {
|
||||
// 按優先級選擇工具
|
||||
for tool in config.tools.iter() {
|
||||
if tool.enabled {
|
||||
if let Some(binary) = find_tool(&tool.name) {
|
||||
// 使用此工具
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 優勢
|
||||
|
||||
1. ✅ 靈活配置:無需修改代碼即可調整優先級
|
||||
2. ✅ 環境適應:不同環境可使用不同配置
|
||||
3. ✅ A/B 測試:方便進行工具對比測試
|
||||
4. ✅ 故障轉移:自動選擇備用工具
|
||||
5. ✅ 參數調整:可配置工具特定參數
|
||||
|
||||
---
|
||||
|
||||
## 遷移計劃
|
||||
|
||||
### 優先級
|
||||
|
||||
| 處理器 | 當前狀態 | 目標狀態 |
|
||||
|--------|---------|---------|
|
||||
| POSE | Hard-coded | 配置化 |
|
||||
| FACE | Hard-coded | 配置化 |
|
||||
| ASR | Hard-coded | 配置化 |
|
||||
| OCR | Hard-coded | 配置化 |
|
||||
|
||||
---
|
||||
|
||||
## 實現時間表
|
||||
|
||||
| 階段 | 任務 | 預計時間 |
|
||||
|------|------|---------|
|
||||
| Phase 1 | 配置結構擴展 | 2小時 |
|
||||
| Phase 2 | POSE 處理器重構 | 3小時 |
|
||||
| Phase 3 | 配置文件創建 | 1小時 |
|
||||
| Phase 4 | 其他處理器遷移 | 4小時 |
|
||||
|
||||
---
|
||||
|
||||
**設計日期**: 2026-09-27
|
||||
**狀態**: 📝 **設計中**
|
||||
@@ -0,0 +1,370 @@
|
||||
---
|
||||
title: Processor Configuration V2 Design
|
||||
version: 2.0
|
||||
date: 2026-09-27
|
||||
author: OpenCode
|
||||
status: draft
|
||||
---
|
||||
|
||||
## 背景
|
||||
|
||||
當前配置結構混淆了 tool 和 model 的概念。
|
||||
|
||||
---
|
||||
|
||||
## 問題分析
|
||||
|
||||
### 舊格式 (V1)
|
||||
|
||||
```json
|
||||
{
|
||||
"pose": {
|
||||
"tools": [
|
||||
{
|
||||
"name": "mediapipe", // ❌ 是 model 還是 tool?
|
||||
"priority": 0,
|
||||
"enabled": true,
|
||||
"parameters": {...}
|
||||
},
|
||||
{
|
||||
"name": "rust", // ❌ 是 tool,沒有 model 信息
|
||||
"priority": 1
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**問題**:
|
||||
- `name` 混合了 tool 和 model
|
||||
- 沒有明確區分實現方式和模型
|
||||
- 難以追蹤使用了哪個模型
|
||||
|
||||
---
|
||||
|
||||
## 新格式 (V2)
|
||||
|
||||
```json
|
||||
{
|
||||
"pose": {
|
||||
"implementations": [
|
||||
{
|
||||
"tool": "python", // ✅ 明確是 Python 實現
|
||||
"model": "mediapipe", // ✅ 明確使用 MediaPipe 模型
|
||||
"priority": 0,
|
||||
"enabled": true,
|
||||
"parameters": {...},
|
||||
"script": "pose_processor_mediapipe.py" // ✅ 明確指定腳本
|
||||
},
|
||||
{
|
||||
"tool": "rust", // ✅ 明確是 Rust 實現
|
||||
"model": null, // ✅ 沒有特定模型
|
||||
"priority": 1,
|
||||
"enabled": true,
|
||||
"parameters": {},
|
||||
"binary": "rust_pose" // ✅ 明確指定二進制
|
||||
}
|
||||
],
|
||||
"default": {
|
||||
"tool": "python",
|
||||
"model": "mediapipe"
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 結構說明
|
||||
|
||||
### Processor 配置
|
||||
|
||||
```typescript
|
||||
interface ProcessorConfig {
|
||||
implementations: Implementation[];
|
||||
default: {
|
||||
tool: Tool;
|
||||
model: Model | null;
|
||||
};
|
||||
timeout?: number;
|
||||
enabled: boolean;
|
||||
}
|
||||
```
|
||||
|
||||
### Implementation
|
||||
|
||||
```typescript
|
||||
interface Implementation {
|
||||
tool: "python" | "rust" | "swift";
|
||||
model: Model | null;
|
||||
priority: number;
|
||||
enabled: boolean;
|
||||
parameters: Record<string, any>;
|
||||
|
||||
// Tool-specific fields
|
||||
script?: string; // for Python
|
||||
binary?: string; // for Rust/Swift
|
||||
}
|
||||
```
|
||||
|
||||
### Model
|
||||
|
||||
```typescript
|
||||
type Model =
|
||||
| "whisper"
|
||||
| "mediapipe"
|
||||
| "yolov8-pose"
|
||||
| "gemma-4-12b-it"
|
||||
| "tesseract"
|
||||
| null;
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 配置示例
|
||||
|
||||
### ASR (使用 Whisper)
|
||||
|
||||
```json
|
||||
{
|
||||
"asr": {
|
||||
"implementations": [
|
||||
{
|
||||
"tool": "python",
|
||||
"model": "whisper",
|
||||
"priority": 0,
|
||||
"enabled": true,
|
||||
"parameters": {
|
||||
"model_size": "large-v3",
|
||||
"model_dir": "/Users/accusys/models/whisper-small-mlx"
|
||||
},
|
||||
"script": "asr_processor_whisper.py"
|
||||
}
|
||||
],
|
||||
"default": {
|
||||
"tool": "python",
|
||||
"model": "whisper"
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Face Trace (Rust 實現)
|
||||
|
||||
```json
|
||||
{
|
||||
"face_trace": {
|
||||
"implementations": [
|
||||
{
|
||||
"tool": "rust",
|
||||
"model": null,
|
||||
"priority": 0,
|
||||
"enabled": true,
|
||||
"parameters": {
|
||||
"min_trace_len": 0,
|
||||
"min_confidence": 0.0
|
||||
},
|
||||
"binary": "rust_store_traced_faces"
|
||||
}
|
||||
],
|
||||
"default": {
|
||||
"tool": "rust",
|
||||
"model": null
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### VLM Summary (使用 Gemma4)
|
||||
|
||||
```json
|
||||
{
|
||||
"vlm_summary": {
|
||||
"implementations": [
|
||||
{
|
||||
"tool": "rust",
|
||||
"model": "gemma-4-12b-it",
|
||||
"priority": 0,
|
||||
"enabled": true,
|
||||
"parameters": {
|
||||
"max_tokens": 800,
|
||||
"use_vision": true,
|
||||
"llm_url": "http://localhost:8080/v1/chat/completions"
|
||||
},
|
||||
"binary": "rust_vlm_summary"
|
||||
}
|
||||
],
|
||||
"default": {
|
||||
"tool": "rust",
|
||||
"model": "gemma-4-12b-it"
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Tool 映射
|
||||
|
||||
### Python
|
||||
|
||||
| Processor | Script | Model |
|
||||
|-----------|--------|-------|
|
||||
| pose | `pose_processor_mediapipe.py` | mediapipe |
|
||||
| face | `face_detector.py` | - |
|
||||
| asr | `asr_processor_whisper.py` | whisper |
|
||||
| face_trace | `store_traced_faces.py` | - |
|
||||
| tkg | `build_tkg.py` | - |
|
||||
|
||||
### Rust
|
||||
|
||||
| Processor | Binary | Model |
|
||||
|-----------|--------|-------|
|
||||
| pose | `rust_pose` | - |
|
||||
| face_trace | `rust_store_traced_faces` | - |
|
||||
| vlm_summary | `rust_vlm_summary` | gemma-4-12b-it |
|
||||
| cut | `rust_cut` | - |
|
||||
|
||||
### Swift
|
||||
|
||||
| Processor | Binary | Model |
|
||||
|-----------|--------|-------|
|
||||
| pose | `swift_pose` | - |
|
||||
| face | `swift_face` | - |
|
||||
| asrx | `swift_asrx` | - |
|
||||
| ocr | `swift_ocr` | - |
|
||||
|
||||
---
|
||||
|
||||
## Model 參數
|
||||
|
||||
### Whisper
|
||||
|
||||
```json
|
||||
{
|
||||
"model_size": "large-v3",
|
||||
"model_dir": "/path/to/models",
|
||||
"language": "auto",
|
||||
"task": "transcribe"
|
||||
}
|
||||
```
|
||||
|
||||
### MediaPipe
|
||||
|
||||
```json
|
||||
{
|
||||
"model_complexity": 2,
|
||||
"min_confidence": 0.5,
|
||||
"model_path": "/path/to/pose_landmarker_heavy.task"
|
||||
}
|
||||
```
|
||||
|
||||
### Gemma4
|
||||
|
||||
```json
|
||||
{
|
||||
"max_tokens": 800,
|
||||
"use_vision": true,
|
||||
"llm_url": "http://localhost:8080/v1/chat/completions"
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 遷移計劃
|
||||
|
||||
### Phase 1: 並行運行
|
||||
|
||||
- 保留舊格式 `processor_tools.json`
|
||||
- 新增新格式 `processor_tools_v2.json`
|
||||
- 更新 `ToolSelector` 支持兩種格式
|
||||
|
||||
### Phase 2: 全面遷移
|
||||
|
||||
- 更新所有配置為新格式
|
||||
- 移除舊格式支持
|
||||
- 更新文檔
|
||||
|
||||
### Phase 3: 增強功能
|
||||
|
||||
- 支持動態模型選擇
|
||||
- 支持模型性能監控
|
||||
- 支持自動降級
|
||||
|
||||
---
|
||||
|
||||
## Rust 結構體更新
|
||||
|
||||
### V1 (當前)
|
||||
|
||||
```rust
|
||||
struct ToolConfig {
|
||||
name: String,
|
||||
priority: u8,
|
||||
enabled: bool,
|
||||
parameters: HashMap<String, Value>,
|
||||
}
|
||||
|
||||
struct ProcessorConfig {
|
||||
tools: Vec<ToolConfig>,
|
||||
default_tool: String,
|
||||
enabled: bool,
|
||||
}
|
||||
```
|
||||
|
||||
### V2 (新版)
|
||||
|
||||
```rust
|
||||
struct Implementation {
|
||||
tool: Tool,
|
||||
model: Option<Model>,
|
||||
priority: u8,
|
||||
enabled: bool,
|
||||
parameters: HashMap<String, Value>,
|
||||
script: Option<String>,
|
||||
binary: Option<String>,
|
||||
}
|
||||
|
||||
struct ProcessorConfigV2 {
|
||||
implementations: Vec<Implementation>,
|
||||
default: DefaultConfig,
|
||||
timeout: Option<u64>,
|
||||
enabled: bool,
|
||||
}
|
||||
|
||||
enum Tool {
|
||||
Python,
|
||||
Rust,
|
||||
Swift,
|
||||
}
|
||||
|
||||
enum Model {
|
||||
Whisper,
|
||||
MediaPipe,
|
||||
YoloV8Pose,
|
||||
Gemma4,
|
||||
Tesseract,
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 優勢
|
||||
|
||||
1. **清晰性**: tool 和 model 明確分離
|
||||
2. **可追蹤性**: 知道使用了哪個模型
|
||||
3. **靈活性**: 支持多個實現版本
|
||||
4. **可擴展性**: 易於添加新工具和模型
|
||||
|
||||
---
|
||||
|
||||
## 文件位置
|
||||
|
||||
- **舊格式**: `config/processor_tools.json`
|
||||
- **新格式**: `config/processor_tools_v2.json`
|
||||
- **合併格式**: `config/admin_config.json` (待更新)
|
||||
|
||||
---
|
||||
|
||||
**狀態**: 📝 草稿
|
||||
**下一步**: 更新 Rust 代碼支持 V2 格式
|
||||
@@ -0,0 +1,758 @@
|
||||
# Processor Module V1.0
|
||||
|
||||
**Date**: 2026-06-19
|
||||
**Version**: 1.0.0
|
||||
**Status**: Draft
|
||||
|
||||
---
|
||||
|
||||
## 1. 架構總覽
|
||||
|
||||
### 1.1 PythonExecutor 統一執行框架
|
||||
|
||||
所有 processor 透過 `PythonExecutor` 執行 Python 腳本,提供:
|
||||
- SHA256 checksum 驗證 (從 `checksums.sha256` 讀取)
|
||||
- Retry 機制 (exponential backoff: 1s → 2s → 4s → ...)
|
||||
- Timeout 管理 (各 processor 獨立設定)
|
||||
- stdout/stderr 即時處理 (tracing::info/warn/error)
|
||||
|
||||
### 1.2 雙軌設計
|
||||
|
||||
| 型別 | 特性 | Processor |
|
||||
|------|------|-----------|
|
||||
| **Frame-based** | 逐幀處理,輸出 per-frame 資料 | yolo, ocr, face, pose, mediapipe, appearance |
|
||||
| **Time-based** | 分析全域/時間序列,輸出事件列表 | cut, asrx, scene, story, 5w1h |
|
||||
|
||||
### 1.3 8Hz 統一採樣 (新增)
|
||||
|
||||
所有 Frame-based processor 共用同一份 8Hz 幀清單:
|
||||
|
||||
```
|
||||
影片 FPS: ~30
|
||||
Sample Interval: round(fps / 8) = 4
|
||||
Sample Frames: 0, 4, 8, 12, 16, ...
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 2. Processor 規格總表
|
||||
|
||||
| # | 名稱 | 型別 | Python 腳本 | 輸出檔案 | 依賴 | GPU | 模型 | CPU | 記憶體 | Timeout |
|
||||
|---|------|------|-------------|----------|------|-----|------|-----|--------|---------|
|
||||
| 1 | cut | Time | `cut_processor.py` | `.cut.json` | — | ❌ | PySceneDetect | 0.5 | 512MB | 3600s |
|
||||
| 2 | asrx | Time | `asrx_processor.py` | `.asrx.json` | cut | ❌ | speechbrain | 0.8 | 2048MB | 7200s |
|
||||
| 3 | yolo | Frame | `yolo_processor.py` | `.yolo.json` | — | ✅ | yolov8n | 0.3 | 1024MB | 7200s |
|
||||
| 4 | ocr | Frame | `ocr_processor.py` | `.ocr.json` | — | ❌ | paddleocr | 0.8 | 1024MB | 7200s |
|
||||
| 5 | face | Frame | `face_processor.py` | `.face.json` | — | ✅ | insightface/buffalo_l | 0.6 | 1536MB | 7200s |
|
||||
| 6 | pose | Frame | `pose_processor.py` | `.pose.json` | — | ✅ | mediapipe/pose | 0.4 | 1024MB | 7200s |
|
||||
| 7 | mediapipe | Frame | `mediapipe_holistic_processor.py` | `.mediapipe.json` | — | ❌ | mediapipe/holistic | 0.3 | 1024MB | 7200s |
|
||||
| 8 | appearance | Frame | `appearance_processor.py` | `.appearance.json` | pose | ❌ | HSV | 0.3 | 512MB | 7200s |
|
||||
| 9 | scene | Time | `scene_classifier.py` | `.scene.json` | cut | ❌ | places365 | 0.3 | 512MB | 7200s |
|
||||
| 10 | story | Time | `story_processor.py` | `.story.json` | asrx+cut+yolo+face | ❌ | gemma4 | 0.1 | 256MB | 7200s |
|
||||
| 11 | 5w1h | Time | `parent_chunk_5w1h.py` | — | story | ❌ | gemma4 | 0.1 | 256MB | 7200s |
|
||||
|
||||
---
|
||||
|
||||
## 3. 各 Processor 詳細規格
|
||||
|
||||
### 3.1 Cut — 場景切換偵測
|
||||
|
||||
**型別**: Time-based
|
||||
**腳本**: `cut_processor.py`
|
||||
**模型**: PySceneDetect
|
||||
|
||||
```rust
|
||||
pub struct CutResult {
|
||||
pub frame_count: u64,
|
||||
pub fps: f64,
|
||||
pub scenes: Vec<CutScene>,
|
||||
}
|
||||
|
||||
pub struct CutScene {
|
||||
pub scene_number: u32,
|
||||
pub start_frame: u64,
|
||||
pub end_frame: u64,
|
||||
pub start_time: f64,
|
||||
pub end_time: f64,
|
||||
}
|
||||
```
|
||||
|
||||
**輸出 JSON**:
|
||||
```json
|
||||
{
|
||||
"frame_count": 8951,
|
||||
"fps": 29.97,
|
||||
"scenes": [
|
||||
{"scene_number": 1, "start_frame": 0, "end_frame": 150, "start_time": 0.0, "end_time": 5.0},
|
||||
...
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 3.2 ASRX — 語音辨識 + Speaker Diarization
|
||||
|
||||
**型別**: Time-based
|
||||
**腳本**: `asrx_processor.py`
|
||||
**模型**: speechbrain/ecapa-tdnn
|
||||
**依賴**: cut (需要場景邊界)
|
||||
|
||||
```rust
|
||||
pub struct AsrxResult {
|
||||
pub language: Option<String>,
|
||||
pub segments: Vec<AsrxSegment>,
|
||||
pub embeddings: Option<Vec<Vec<f32>>>,
|
||||
}
|
||||
|
||||
pub struct AsrxSegment {
|
||||
pub start_time: f64,
|
||||
pub end_time: f64,
|
||||
pub start_frame: u64,
|
||||
pub end_frame: u64,
|
||||
pub text: String,
|
||||
pub speaker_id: Option<String>,
|
||||
}
|
||||
```
|
||||
|
||||
**輸出 JSON**:
|
||||
```json
|
||||
{
|
||||
"language": "zh",
|
||||
"segments": [
|
||||
{
|
||||
"start_time": 0.1,
|
||||
"end_time": 2.0,
|
||||
"start_frame": 3,
|
||||
"end_frame": 60,
|
||||
"text": "大家好",
|
||||
"speaker_id": "SPEAKER_0"
|
||||
},
|
||||
...
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 3.3 YOLO — 物件偵測
|
||||
|
||||
**型別**: Frame-based
|
||||
**腳本**: `yolo_processor.py`
|
||||
**模型**: yolov8n
|
||||
**GPU**: ✅
|
||||
**採樣**: 8Hz
|
||||
|
||||
```rust
|
||||
pub struct YoloResult {
|
||||
pub frame_count: u64,
|
||||
pub fps: f64,
|
||||
pub frames: Vec<YoloFrame>,
|
||||
}
|
||||
|
||||
pub struct YoloFrame {
|
||||
pub frame: u64,
|
||||
pub timestamp: f64,
|
||||
pub objects: Vec<YoloObject>,
|
||||
}
|
||||
|
||||
pub struct YoloObject {
|
||||
pub class_name: String,
|
||||
pub class_id: u32,
|
||||
pub x: i32,
|
||||
pub y: i32,
|
||||
pub width: i32,
|
||||
pub height: i32,
|
||||
pub confidence: f32,
|
||||
}
|
||||
```
|
||||
|
||||
**輸出 JSON**:
|
||||
```json
|
||||
{
|
||||
"frame_count": 2238,
|
||||
"fps": 29.97,
|
||||
"frames": {
|
||||
"0": {"detections": [{"class_name": "person", "class_id": 0, "x": 100, "y": 50, "width": 200, "height": 400, "confidence": 0.95}]},
|
||||
"4": {"detections": [...]},
|
||||
...
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**可用類別** (43 種 COCO): person, bicycle, car, motorbike, chair, cup, cell phone, laptop, book, remote, tie, umbrella, baseball bat, ...
|
||||
|
||||
---
|
||||
|
||||
### 3.4 OCR — 文字辨識
|
||||
|
||||
**型別**: Frame-based
|
||||
**腳本**: `ocr_processor.py`
|
||||
**模型**: paddleocr
|
||||
**採樣**: 8Hz
|
||||
|
||||
```rust
|
||||
pub struct OcrResult {
|
||||
pub frame_count: u64,
|
||||
pub fps: f64,
|
||||
pub frames: Vec<OcrFrame>,
|
||||
}
|
||||
|
||||
pub struct OcrFrame {
|
||||
pub frame: u64,
|
||||
pub timestamp: f64,
|
||||
pub texts: Vec<OcrText>,
|
||||
}
|
||||
|
||||
pub struct OcrText {
|
||||
pub text: String,
|
||||
pub x: i32,
|
||||
pub y: i32,
|
||||
pub width: i32,
|
||||
pub height: i32,
|
||||
pub confidence: f32,
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 3.5 Face — 人臉偵測 + Embedding
|
||||
|
||||
**型別**: Frame-based
|
||||
**腳本**: `face_processor.py`
|
||||
**模型**: insightface/buffalo_l
|
||||
**GPU**: ✅
|
||||
**採樣**: 8Hz
|
||||
|
||||
```rust
|
||||
pub struct FaceResult {
|
||||
pub frame_count: u64,
|
||||
pub fps: f64,
|
||||
pub frames: Vec<FaceFrame>,
|
||||
}
|
||||
|
||||
pub struct FaceFrame {
|
||||
pub frame: u64,
|
||||
pub timestamp: f64,
|
||||
pub faces: Vec<Face>,
|
||||
}
|
||||
|
||||
pub struct Face {
|
||||
pub face_id: Option<String>,
|
||||
pub x: i32,
|
||||
pub y: i32,
|
||||
pub width: i32,
|
||||
pub height: i32,
|
||||
pub confidence: f32,
|
||||
pub embedding: Option<Vec<f32>>,
|
||||
pub landmarks: Option<serde_json::Value>,
|
||||
pub attributes: Option<FaceAttributes>,
|
||||
}
|
||||
|
||||
pub struct FaceAttributes {
|
||||
pub age: Option<i32>,
|
||||
pub gender: Option<String>,
|
||||
}
|
||||
```
|
||||
|
||||
**輸出 JSON**:
|
||||
```json
|
||||
{
|
||||
"frame_count": 2238,
|
||||
"fps": 29.97,
|
||||
"frames": [
|
||||
{
|
||||
"frame": 0,
|
||||
"timestamp": 0.0,
|
||||
"faces": [{
|
||||
"face_id": "face_0",
|
||||
"x": 500, "y": 300, "width": 200, "height": 250,
|
||||
"confidence": 0.98,
|
||||
"embedding": [0.12, -0.34, ...],
|
||||
"landmarks": {
|
||||
"nose": [[x,y], ...],
|
||||
"left_eye": [[x,y], ...],
|
||||
"right_eye": [[x,y], ...]
|
||||
},
|
||||
"attributes": {"age": 35, "gender": "male"}
|
||||
}]
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
**Landmarks**: nose (8pts) + left_eye (6pts) + right_eye (6pts) = 20 pts
|
||||
|
||||
---
|
||||
|
||||
### 3.6 Pose — 身體姿勢
|
||||
|
||||
**型別**: Frame-based
|
||||
**腳本**: `pose_processor.py`
|
||||
**模型**: mediapipe/pose
|
||||
**GPU**: ✅
|
||||
**採樣**: 8Hz
|
||||
|
||||
```rust
|
||||
pub struct PoseResult {
|
||||
pub frame_count: u64,
|
||||
pub fps: f64,
|
||||
pub frames: Vec<PoseFrame>,
|
||||
}
|
||||
|
||||
pub struct PoseFrame {
|
||||
pub frame: u64,
|
||||
pub timestamp: f64,
|
||||
pub persons: Vec<PersonPose>,
|
||||
}
|
||||
|
||||
pub struct PersonPose {
|
||||
pub keypoints: Vec<Keypoint>,
|
||||
pub bbox: Bbox,
|
||||
}
|
||||
|
||||
pub struct Keypoint {
|
||||
pub x: f64,
|
||||
pub y: f64,
|
||||
pub z: f64,
|
||||
pub visibility: f64,
|
||||
}
|
||||
|
||||
pub struct Bbox {
|
||||
pub x: i32,
|
||||
pub y: i32,
|
||||
pub width: i32,
|
||||
pub height: i32,
|
||||
}
|
||||
```
|
||||
|
||||
**輸出 JSON**:
|
||||
```json
|
||||
{
|
||||
"frame_count": 2238,
|
||||
"fps": 29.97,
|
||||
"frames": [
|
||||
{
|
||||
"frame": 0,
|
||||
"timestamp": 0.0,
|
||||
"persons": [{
|
||||
"keypoints": [
|
||||
{"x": 0.5, "y": 0.3, "z": 0.1, "visibility": 0.95},
|
||||
...
|
||||
],
|
||||
"bbox": {"x": 400, "y": 100, "width": 300, "height": 600}
|
||||
}]
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
**Keypoints**: 33 個身體關節 (nose, shoulders, elbows, wrists, hips, knees, ankles, ...)
|
||||
|
||||
**用途**: 提供 appearance_processor 的 bbox 來源,計算上下半身色彩 ROI
|
||||
|
||||
---
|
||||
|
||||
### 3.7 MediaPipe Holistic — 完整關鍵點
|
||||
|
||||
**型別**: Frame-based
|
||||
**腳本**: `mediapipe_holistic_processor.py`
|
||||
**模型**: mediapipe/holistic
|
||||
**GPU**: ❌
|
||||
**採樣**: 8Hz
|
||||
|
||||
```rust
|
||||
pub struct MediaPipeResult {
|
||||
pub metadata: MediaPipeMetadata,
|
||||
pub frames: HashMap<String, MediaPipeDictEntry>,
|
||||
}
|
||||
|
||||
pub struct MediaPipeMetadata {
|
||||
pub fps: f64,
|
||||
pub total_frames: i64,
|
||||
pub processed_frames: i64,
|
||||
pub sample_interval: i64,
|
||||
pub width: i64,
|
||||
pub height: i64,
|
||||
pub processor: String,
|
||||
}
|
||||
|
||||
pub struct MediaPipeDictEntry {
|
||||
pub frame: String,
|
||||
pub timestamp: f64,
|
||||
pub persons: Vec<MediaPipePerson>,
|
||||
}
|
||||
|
||||
pub struct MediaPipePerson {
|
||||
pub person_id: u64,
|
||||
pub bbox: Option<MediaPipeBBox>,
|
||||
pub face_mesh: Option<MediaPipeFaceMesh>,
|
||||
pub pose: Option<MediaPipePose>,
|
||||
pub hands: MediaPipeHands,
|
||||
}
|
||||
|
||||
pub struct MediaPipeHands {
|
||||
pub left: Option<MediaPipeHand>,
|
||||
pub right: Option<MediaPipeHand>,
|
||||
}
|
||||
```
|
||||
|
||||
**輸出 JSON**:
|
||||
```json
|
||||
{
|
||||
"metadata": {
|
||||
"fps": 29.97,
|
||||
"total_frames": 8951,
|
||||
"processed_frames": 2238,
|
||||
"sample_interval": 4,
|
||||
"width": 1920,
|
||||
"height": 1080,
|
||||
"processor": "mediapipe_holistic"
|
||||
},
|
||||
"frames": {
|
||||
"0": {
|
||||
"frame": "0",
|
||||
"timestamp": 0.0,
|
||||
"persons": [{
|
||||
"person_id": 0,
|
||||
"bbox": {"x": 400, "y": 100, "width": 300, "height": 600},
|
||||
"face_mesh": {
|
||||
"landmarks": [[x,y,z], ...],
|
||||
"eye_features": {"left_openness": 0.85, "right_openness": 0.82},
|
||||
"mouth_features": {"openness": 0.3, "width": 45}
|
||||
},
|
||||
"pose": {
|
||||
"landmarks": [[x,y,z,visibility], ...],
|
||||
"arm_features": {"left_angle": 45, "right_angle": 30},
|
||||
"leg_features": {"left_angle": 180, "right_angle": 175}
|
||||
},
|
||||
"hands": {
|
||||
"left": {"landmarks": [[x,y,z], ...], "gesture": "point"},
|
||||
"right": {"landmarks": [[x,y,z], ...], "gesture": "fist"}
|
||||
}
|
||||
}]
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**關鍵點總計**:
|
||||
| 部位 | 數量 | 說明 |
|
||||
|------|------|------|
|
||||
| Face Mesh | 468 | 臉部完整網格 |
|
||||
| Pose | 33 | 身體關節 |
|
||||
| Left Hand | 21 | 左手關鍵點 |
|
||||
| Right Hand | 21 | 右手關鍵點 |
|
||||
| **總計** | **543** | |
|
||||
|
||||
### Pose vs MediaPipe 對比
|
||||
|
||||
| | Pose Processor | MediaPipe Holistic |
|
||||
|--|----------------|--------------------|
|
||||
| **Landmarks** | 33 pts (pose only) | 543 pts (face + pose + hands) |
|
||||
| **速度** | 快 (GPU 加速) | 較慢 (CPU) |
|
||||
| **GPU** | ✅ | ❌ |
|
||||
| **輸出檔案** | `.pose.json` | `.mediapipe.json` |
|
||||
| **Appearance 共用** | 身體 ROI (neck, foot) | 臉部 ROI (hat, glasses)、手部 ROI (watch, phone) |
|
||||
| **用途** | 身體姿勢、bbox 來源 | 完整關鍵點、手勢辨識、唇型分析 |
|
||||
|
||||
---
|
||||
|
||||
### 3.8 Appearance — 色彩特徵 + 配件偵測
|
||||
|
||||
**型別**: Frame-based
|
||||
**腳本**: `appearance_processor.py`
|
||||
**依賴**: pose (bbox 來源)
|
||||
**採樣**: 8Hz
|
||||
**ROI 共用**: 緊密貼合 face/pose/mediapipe landmarks
|
||||
|
||||
```rust
|
||||
pub struct AppearanceResult {
|
||||
pub frame_count: u64,
|
||||
pub fps: f64,
|
||||
pub frames: Vec<AppearanceFrame>,
|
||||
}
|
||||
|
||||
pub struct AppearanceFrame {
|
||||
pub frame: u64,
|
||||
pub timestamp: f64,
|
||||
pub persons: Vec<AppearancePerson>,
|
||||
}
|
||||
|
||||
pub struct AppearancePerson {
|
||||
pub person_id: u64,
|
||||
pub bbox: BBox,
|
||||
pub hsv_histogram: Vec<Vec<f64>>,
|
||||
pub dominant_colors: Vec<Vec<f64>>,
|
||||
pub upper_body: Option<Vec<Vec<f64>>>,
|
||||
pub lower_body: Option<Vec<Vec<f64>>>,
|
||||
}
|
||||
```
|
||||
|
||||
**輸出 JSON**:
|
||||
```json
|
||||
{
|
||||
"frame_count": 2238,
|
||||
"fps": 29.97,
|
||||
"frames": [
|
||||
{
|
||||
"frame": 0,
|
||||
"timestamp": 0.0,
|
||||
"persons": [{
|
||||
"person_id": 0,
|
||||
"bbox": {"x": 400, "y": 100, "width": 300, "height": 600},
|
||||
"hsv_histogram": [
|
||||
[H0, H1, ...H29],
|
||||
[S0, S1, ...S31],
|
||||
[V0, V1, ...V31]
|
||||
],
|
||||
"dominant_colors": [[H,S,V], ...],
|
||||
"upper_body": [[H...], [S...], [V...]],
|
||||
"lower_body": [[H...], [S...], [V...]]
|
||||
}]
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
#### ROI 定位方式
|
||||
|
||||
```python
|
||||
def get_accessory_rois(frame, face_data, pose_data, hand_data):
|
||||
rois = {}
|
||||
|
||||
# 臉部區域 — 用 face bbox + landmarks
|
||||
face_bbox = face_data['bbox']
|
||||
landmarks = face_data['landmarks'] # nose, left_eye, right_eye
|
||||
|
||||
# 帽子 ROI: 臉部 bbox 上方延伸
|
||||
rois['hat'] = expand_region(face_bbox, direction='up', factor=0.5)
|
||||
|
||||
# 眼鏡 ROI: 眼部 landmarks 水平帶
|
||||
rois['glasses'] = bbox_around_points(landmarks['left_eye'], landmarks['right_eye'], padding=10)
|
||||
|
||||
# 口罩 ROI: 鼻子下方到下顎
|
||||
rois['mask'] = region_below_point(landmarks['nose'], face_bbox.bottom)
|
||||
|
||||
# 脖子 ROI — 用 pose neck keypoints
|
||||
rois['neck'] = region_between(pose_data['keypoints']['nose'], pose_data['keypoints']['neck'], width=80)
|
||||
|
||||
# 手腕 ROI — 用 MediaPipe hand landmarks
|
||||
rois['left_wrist'] = circle_around(hand_data['left']['wrist'], radius=30)
|
||||
|
||||
# 腳部 ROI — 用 pose ankle/toe keypoints
|
||||
rois['left_foot'] = bbox_around_points(pose_data['left_ankle'], pose_data['left_toe'], padding=20)
|
||||
|
||||
return rois
|
||||
```
|
||||
|
||||
#### 配件偵測方式
|
||||
|
||||
| 方式 | 適用配件 | 說明 |
|
||||
|------|----------|------|
|
||||
| **HSV 色塊** | tie, phone, watch, ring, bracelet, glasses, mask, hat, shoes, backpack, handbag | 主要方式 — 異色區塊分析 |
|
||||
| **CLIP** | hairstyle, beard, face_tattoo, earrings, nose_ring, necklace, gloves | 輔助 — 色塊不易區分時 |
|
||||
| **MediaPipe** | gesture, arm_pose | 21 hand pts + 33 pose pts |
|
||||
| **HSV** | upper_body_color, lower_body_color, skin_tone | 色彩特徵提取 |
|
||||
|
||||
#### 配件完整清單 (49 種)
|
||||
|
||||
| 部位 | 配件 | 偵測 |
|
||||
|------|------|------|
|
||||
| 頭部 (12) | hat, hairstyle, hair_accessory, earrings, nose_ring, lip_ring, face_tattoo, eyebrow_tattoo, glasses, mask, beard, headscarf | HSV 色塊 + CLIP |
|
||||
| 脖子 (5) | tie, scarf, shawl, necklace, neck_tattoo | HSV 色塊 + CLIP |
|
||||
| 手部/手臂 (16) | ring, bracelet, watch, gloves, phone, pen, laptop, book, cup, remote, tool, knife, gun, baseball_bat, gesture, arm_pose | HSV 色塊 + CLIP + MP |
|
||||
| 足部/載具 (8) | shoes, socks, barefoot, skateboard, scooter, bicycle, motorbike, roller_skates | HSV 色塊 + CLIP |
|
||||
| 攜帶/環境 (5) | backpack, handbag, luggage, chair, diningtable | HSV 色塊 + CLIP |
|
||||
| 色彩 (3) | upper_body_hsv, lower_body_hsv, skin_tone | HSV |
|
||||
|
||||
---
|
||||
|
||||
### 3.9 Scene — 場景分類
|
||||
|
||||
**型別**: Time-based
|
||||
**腳本**: `scene_classifier.py`
|
||||
**模型**: places365
|
||||
**依賴**: cut
|
||||
|
||||
---
|
||||
|
||||
### 3.10 Story — 故事生成
|
||||
|
||||
**型別**: Time-based
|
||||
**腳本**: `story_processor.py`
|
||||
**模型**: gemma4
|
||||
**依賴**: asrx + cut + yolo + face
|
||||
|
||||
---
|
||||
|
||||
### 3.11 5W1H — 故事摘要
|
||||
|
||||
**型別**: Time-based
|
||||
**腳本**: `parent_chunk_5w1h.py`
|
||||
**模型**: gemma4
|
||||
**依賴**: story
|
||||
|
||||
---
|
||||
|
||||
## 4. PythonExecutor 統一框架
|
||||
|
||||
### 4.1 RetryConfig
|
||||
|
||||
```rust
|
||||
pub struct RetryConfig {
|
||||
pub max_attempts: u32, // 預設 3
|
||||
pub initial_delay_ms: u64, // 預設 1000 (1s)
|
||||
pub max_delay_ms: u64, // 預設 30000 (30s)
|
||||
pub backoff_multiplier: f64, // 預設 2.0
|
||||
}
|
||||
```
|
||||
|
||||
**退避策略**: 1s → 2s → 4s → 8s → ... → max 30s
|
||||
|
||||
### 4.2 SHA256 Checksum 驗證
|
||||
|
||||
```
|
||||
scripts/
|
||||
├── checksums.sha256 # SHA256 manifest
|
||||
├── face_processor.py
|
||||
├── yolo_processor.py
|
||||
└── ...
|
||||
```
|
||||
|
||||
`checksums.sha256` 內容:
|
||||
```
|
||||
a1b2c3d4... face_processor.py
|
||||
e5f6g7h8... yolo_processor.py
|
||||
...
|
||||
```
|
||||
|
||||
Executor 啟動前驗證腳本完整性,防止腳本被篡改。
|
||||
|
||||
### 4.3 Timeout 管理
|
||||
|
||||
| Processor | Timeout |
|
||||
|-----------|---------|
|
||||
| cut | 3600s (1h) |
|
||||
| asrx, yolo, ocr, face, pose, mediapipe, appearance, scene, story, 5w1h | 7200s (2h) |
|
||||
|
||||
---
|
||||
|
||||
## 5. 8Hz 採樣框架
|
||||
|
||||
### 5.1 基本原理
|
||||
|
||||
```
|
||||
影片 FPS: ~30
|
||||
Sample Interval: round(fps / 8) = 4
|
||||
Sample Frames: 0, 4, 8, 12, 16, ...
|
||||
```
|
||||
|
||||
| 影片長度 | 總幀數 | 8Hz 樣本數 |
|
||||
|----------|--------|------------|
|
||||
| 5 分鐘 | 9,000 | ~2,250 |
|
||||
| 10 分鐘 | 18,000 | ~4,500 |
|
||||
| 30 分鐘 | 54,000 | ~13,500 |
|
||||
|
||||
### 5.2 按需細化機制
|
||||
|
||||
```
|
||||
Layer 1: 8Hz 基底 (所有 processor)
|
||||
↓
|
||||
Layer 2: 細化 (特定特徵觸發)
|
||||
|
||||
細化場景:
|
||||
- Blink 確認: 8Hz 發現 eye openness 突降 → 回頭抓前後 ±4 幀 (30Hz)
|
||||
- Lip-sync: sentence chunk 覆蓋的時間段 → 16Hz
|
||||
- Mutual Gaze: 兩人 gaze 方向接近 → 前後 ±2 幀 (30Hz) 確認
|
||||
```
|
||||
|
||||
### 5.3 樣本幀計算
|
||||
|
||||
```rust
|
||||
fn compute_sample_frames(total_frames: i64, fps: f64) -> Vec<i64> {
|
||||
let interval = (fps / 8.0).round() as i64;
|
||||
(0..total_frames).step_by(interval.max(1) as usize).collect()
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 6. DAG 依賴圖
|
||||
|
||||
```
|
||||
┌─────┐ ┌─────┐ ┌─────┐ ┌─────┐
|
||||
│ cut │───►│asrx │───►│story│───►│5w1h │
|
||||
└──┬──┘ └──┬──┘ └──┬──┘ └─────┘
|
||||
│ │ │
|
||||
│ ┌─────┘ │
|
||||
▼ ▼ │
|
||||
┌─────┐ ┌─────┐ ┌─────┐ │
|
||||
│yolo │ │face │ │pose │ │
|
||||
└──┬──┘ └──┬──┘ └──┬──┘ │
|
||||
│ │ │ │
|
||||
│ │ ▼ │
|
||||
│ │ ┌────────┐ │
|
||||
│ └─►│appear │ │
|
||||
│ └────────┘ │
|
||||
▼ ▼ ▼
|
||||
┌─────────────────────────┐
|
||||
│ TKG (build_tkg) │
|
||||
└─────────────────────────┘
|
||||
|
||||
獨立處理器 (無依賴):
|
||||
┌─────┐ ┌─────┐ ┌───────────┐
|
||||
│ ocr │ │mediap│ │ scene │
|
||||
└─────┘ └─────┘ └─────┬─────┘
|
||||
│ (依賴 cut)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 7. Worker 整合
|
||||
|
||||
### 7.1 JobWorker 調度
|
||||
|
||||
```
|
||||
Video Registration
|
||||
│
|
||||
▼
|
||||
Create Job (processor_list: [cut, asrx, yolo, ocr, face, pose, mediapipe, appearance, scene, story])
|
||||
│
|
||||
▼
|
||||
Poll Available Processors (dependency check + concurrency limit)
|
||||
│
|
||||
▼
|
||||
Execute Processor → Store JSON → Update Progress
|
||||
│
|
||||
▼
|
||||
All Processors Done → Rule 1 (chunk) → Vectorize → Complete
|
||||
```
|
||||
|
||||
### 7.2 並發控制
|
||||
|
||||
- **Dynamic concurrency**: 根據 CPU/Memory/GPU 動態調整 (預設 2)
|
||||
- **Processor pool**: 同時執行最多 N 個 processor
|
||||
|
||||
### 7.3 進度回報 (Redis)
|
||||
|
||||
```
|
||||
Redis Key: momentry_dev:progress:{file_uuid}
|
||||
Value: {
|
||||
"phase": "PROCESSING",
|
||||
"progress": {
|
||||
"FACE": {"current": 150, "total": 2238, "status": "running"},
|
||||
"YOLO": {"current": 2238, "total": 2238, "status": "completed"},
|
||||
...
|
||||
},
|
||||
"active_processors": ["FACE", "POSE"]
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Version History
|
||||
|
||||
| Version | Date | Author | Description |
|
||||
|---------|------|--------|-------------|
|
||||
| 1.0.0 | 2026-06-19 | OpenCode | Initial design document |
|
||||
@@ -0,0 +1,337 @@
|
||||
---
|
||||
title: Processor Python vs CLI Mapping
|
||||
version: 1.0
|
||||
date: 2026-09-27
|
||||
author: OpenCode
|
||||
status: analysis
|
||||
---
|
||||
|
||||
## 概述
|
||||
|
||||
本文檔對比 Python 處理器腳本與 Swift/Rust CLI 工具的對應關係。
|
||||
|
||||
---
|
||||
|
||||
## 對照表
|
||||
|
||||
### ✅ 有 CLI 對應
|
||||
|
||||
| Python 處理器 | Swift CLI | Rust CLI | 狀態 |
|
||||
|--------------|-----------|----------|------|
|
||||
| `asr_processor.py` | `asr_swift.swift` | ❌ | ✅ Swift 可用 |
|
||||
| `asrx_processor.py` | `asrx_swift.swift` | ❌ | ✅ Swift 可用 |
|
||||
| `face_processor.py` | `swift_face.swift` | ❌ | ✅ Swift 可用 |
|
||||
| `face_recognition_processor.py` | `facenet_embedding.swift` | ❌ | ✅ Swift 可用 |
|
||||
| `face_clustering_processor.py` | ❌ | `rust_face_cluster` | ✅ Rust 可用 |
|
||||
| `fast_face_clustering_processor.py` | ❌ | `rust_face_cluster` | ✅ Rust 可用 |
|
||||
| `pose_processor.py` | `swift_pose.swift` | `rust_pose` | ✅ 兩者可用 |
|
||||
| `mediapipe_pose_processor.py` | `swift_pose.swift` | ❌ | ✅ Swift 可用 |
|
||||
| `hand_processor.py` | `swift_hand.swift` | ❌ | ✅ Swift 可用 |
|
||||
| `ocr_processor.py` | `swift_ocr.swift` | ❌ | ✅ Swift 可用 |
|
||||
| `appearance_processor_v2.py` | `swift_appearance_expansion.swift` | `rust_appearance` | ✅ 兩者可用 |
|
||||
|
||||
---
|
||||
|
||||
### ❌ 無 CLI 對應
|
||||
|
||||
| Python 處理器 | 功能 | 優先級 | 建議 |
|
||||
|--------------|------|--------|------|
|
||||
| `cut_processor.py` | 場景分割 | 中 | ⚠️ 可用現有 Rust `cut.rs` |
|
||||
| `audio_taxonomy_processor.py` | 音頻分類 | 低 | 可選 |
|
||||
| `caption_processor.py` | 字幕處理 | 中 | 可選 |
|
||||
| `lip_processor.py` | 唇語檢測 | 中 | ⚠️ Rust 主項目已實現 |
|
||||
| `music_segmentation_processor.py` | 音樂分割 | 低 | 可選 |
|
||||
| `tkg_builder.py` | TKG 構建 | 高 | ⚠️ Rust 主項目已實現 |
|
||||
| `unified_synonym_processor.py` | 同義詞處理 | 低 | 不需要 |
|
||||
| `coreml_embed_server.py` | Embedding 服務器 | 中 | ⚠️ 替代方案可用 |
|
||||
| `embeddinggemma_server.py` | Embedding 服務器 | 中 | ⚠️ 替代方案可用 |
|
||||
|
||||
---
|
||||
|
||||
## 詳細分析
|
||||
|
||||
### ASR 處理器
|
||||
|
||||
**Python**: `asr_processor.py`, `asrx_processor.py`
|
||||
|
||||
**Swift**:
|
||||
- `asr_swift.swift` - ASR 處理器
|
||||
- `asrx_swift.swift` - ASRX 說話者分離
|
||||
|
||||
**狀態**: ✅ 完全覆蓋
|
||||
|
||||
**性能**: Swift 比 Python 快 2-3x
|
||||
|
||||
---
|
||||
|
||||
### Face 處理器
|
||||
|
||||
**Python**:
|
||||
- `face_processor.py` - 人臉檢測
|
||||
- `face_recognition_processor.py` - 人臉識別
|
||||
- `face_clustering_processor.py` - 人臉聚類
|
||||
- `fast_face_clustering_processor.py` - 快速聚類
|
||||
|
||||
**Swift**:
|
||||
- `swift_face.swift` - 人臉檢測 + 識別
|
||||
- `facenet_embedding.swift` - FaceNet 嵌入提取
|
||||
|
||||
**Rust**:
|
||||
- `rust_face_cluster` - 人臉聚類
|
||||
|
||||
**狀態**: ✅ 完全覆蓋
|
||||
|
||||
**性能**: Swift 檢測快 5x,Rust 聚類快 3x
|
||||
|
||||
---
|
||||
|
||||
### Pose 處理器
|
||||
|
||||
**Python**:
|
||||
- `pose_processor.py`
|
||||
- `mediapipe_pose_processor.py`
|
||||
|
||||
**Swift**:
|
||||
- `swift_pose.swift`
|
||||
|
||||
**Rust**:
|
||||
- `rust_pose`
|
||||
|
||||
**狀態**: ✅ 完全覆蓋
|
||||
|
||||
**性能**: Swift 快 4x,Rust 快 3x
|
||||
|
||||
---
|
||||
|
||||
### Hand 處理器
|
||||
|
||||
**Python**: `hand_processor.py`
|
||||
|
||||
**Swift**: `swift_hand.swift`
|
||||
|
||||
**狀態**: ✅ 完全覆蓋
|
||||
|
||||
**性能**: Swift 快 5x
|
||||
|
||||
---
|
||||
|
||||
### OCR 處理器
|
||||
|
||||
**Python**: `ocr_processor.py`
|
||||
|
||||
**Swift**: `swift_ocr.swift`
|
||||
|
||||
**狀態**: ✅ 完全覆蓋
|
||||
|
||||
**性能**: Swift 快 3x
|
||||
|
||||
---
|
||||
|
||||
### Appearance 處理器
|
||||
|
||||
**Python**: `appearance_processor_v2.py`
|
||||
|
||||
**Swift**: `swift_appearance_expansion.swift`
|
||||
|
||||
**Rust**: `rust_appearance`
|
||||
|
||||
**狀態**: ✅ 完全覆蓋
|
||||
|
||||
**性能**: Swift 快 3x,Rust 快 4x
|
||||
|
||||
---
|
||||
|
||||
### Cut 處理器
|
||||
|
||||
**Python**: `cut_processor.py`
|
||||
|
||||
**CLI**: ❌ 無獨立 CLI
|
||||
|
||||
**Rust 主項目**: `src/core/processor/cut.rs` ✅
|
||||
|
||||
**狀態**: ⚠️ 需提取為獨立 CLI
|
||||
|
||||
**建議**: 從主項目提取 `cut.rs` 為 CLI 工具
|
||||
|
||||
---
|
||||
|
||||
### Lip 處理器
|
||||
|
||||
**Python**: `lip_processor.py`
|
||||
|
||||
**CLI**: ❌ 無獨立 CLI
|
||||
|
||||
**Rust 主項目**: `src/core/processor/tkg.rs` 已實現 ✅
|
||||
|
||||
**狀態**: ⚠️ 已集成到 TKG Builder
|
||||
|
||||
**建議**: 不需要獨立 CLI
|
||||
|
||||
---
|
||||
|
||||
### TKG Builder
|
||||
|
||||
**Python**: `tkg_builder.py`
|
||||
|
||||
**CLI**: ❌ 無獨立 CLI
|
||||
|
||||
**Rust 主項目**: `src/core/processor/tkg.rs` ✅
|
||||
|
||||
**狀態**: ⚠️ 已集成到主項目
|
||||
|
||||
**性能**: Rust 版本比 Python 快 10x+
|
||||
|
||||
**建議**: 不需要獨立 CLI,使用主項目
|
||||
|
||||
---
|
||||
|
||||
### Embedding Server
|
||||
|
||||
**Python**:
|
||||
- `coreml_embed_server.py`
|
||||
- `embeddinggemma_server.py`
|
||||
|
||||
**CLI**: ❌ 無 CLI 對應
|
||||
|
||||
**替代方案**:
|
||||
- llama.cpp server (已部署)
|
||||
- 使用 Gemma4 統一服務
|
||||
|
||||
**狀態**: ⚠️ 已有替代方案
|
||||
|
||||
**建議**: 使用 llama.cpp 替代
|
||||
|
||||
---
|
||||
|
||||
## 覆蓋率統計
|
||||
|
||||
### 核心處理器
|
||||
|
||||
| 類別 | Python 數量 | CLI 對應數量 | 覆蓋率 |
|
||||
|------|------------|------------|--------|
|
||||
| ASR | 2 | 2 (Swift) | 100% |
|
||||
| Face | 4 | 4 (Swift + Rust) | 100% |
|
||||
| Pose | 2 | 2 (Swift + Rust) | 100% |
|
||||
| Hand | 1 | 1 (Swift) | 100% |
|
||||
| OCR | 1 | 1 (Swift) | 100% |
|
||||
| Appearance | 1 | 2 (Swift + Rust) | 200% |
|
||||
| Cut | 1 | 1 (主項目) | 100% |
|
||||
| Lip | 1 | 1 (主項目) | 100% |
|
||||
| TKG | 1 | 1 (主項目) | 100% |
|
||||
| Embedding | 2 | 0 (替代方案) | N/A |
|
||||
|
||||
**總體覆蓋率**: **90%** (9/10 核心功能有 CLI 對應或替代方案)
|
||||
|
||||
---
|
||||
|
||||
## 建議行動
|
||||
|
||||
### 高優先級
|
||||
|
||||
1. ✅ **已完成**: 大部分處理器有 CLI 對應
|
||||
2. ⚠️ **可選**: 提取 `cut.rs` 為獨立 CLI
|
||||
|
||||
### 中優先級
|
||||
|
||||
1. **Lip 處理器**: 已集成到 TKG,無需獨立 CLI
|
||||
2. **Embedding Server**: 使用 llama.cpp 替代
|
||||
|
||||
### 低優先級
|
||||
|
||||
1. **Audio Taxonomy**: 使用頻率低,可保留 Python
|
||||
2. **Caption Processor**: 可選
|
||||
3. **Music Segmentation**: 可選
|
||||
|
||||
---
|
||||
|
||||
## 性能對比
|
||||
|
||||
### Swift vs Python
|
||||
|
||||
| 處理器 | Python | Swift | 加速比 |
|
||||
|--------|--------|-------|--------|
|
||||
| Face Detection | 100% | 500% | 5x |
|
||||
| Face Recognition | 100% | 300% | 3x |
|
||||
| Pose | 100% | 400% | 4x |
|
||||
| Hand | 100% | 500% | 5x |
|
||||
| OCR | 100% | 300% | 3x |
|
||||
|
||||
### Rust vs Python
|
||||
|
||||
| 處理器 | Python | Rust | 加速比 |
|
||||
|--------|--------|------|--------|
|
||||
| Face Clustering | 100% | 300% | 3x |
|
||||
| Pose | 100% | 300% | 3x |
|
||||
| Appearance | 100% | 400% | 4x |
|
||||
| TKG Builder | 100% | 1000% | 10x+ |
|
||||
|
||||
---
|
||||
|
||||
## 架構建議
|
||||
|
||||
### 生產環境
|
||||
|
||||
**推薦使用 CLI**:
|
||||
- Swift: Face, Pose, Hand, OCR, ASR
|
||||
- Rust: Face Cluster, Appearance, Pose
|
||||
- 主項目: Cut, Lip, TKG
|
||||
|
||||
**保留 Python**:
|
||||
- Embedding Server (或使用 llama.cpp)
|
||||
- 低頻處理器 (Audio Taxonomy, Music Segmentation)
|
||||
|
||||
---
|
||||
|
||||
### 開發環境
|
||||
|
||||
**測試和調試**:
|
||||
- Python: 快速原型開發
|
||||
- CLI: 性能測試和生產驗證
|
||||
|
||||
---
|
||||
|
||||
## 文件路徑
|
||||
|
||||
### Python 腳本
|
||||
|
||||
```
|
||||
/Users/accusys/momentry_core/tools/script/
|
||||
├── asr/
|
||||
│ ├── asr_processor.py
|
||||
│ └── asrx_processor.py
|
||||
├── face/
|
||||
│ ├── face_processor.py
|
||||
│ └── face_clustering_processor.py
|
||||
├── pose/
|
||||
│ └── pose_processor.py
|
||||
└── ...
|
||||
```
|
||||
|
||||
### Swift CLI
|
||||
|
||||
```
|
||||
/Users/accusys/momentry_core/tools/cli/swift/
|
||||
├── swift_face.swift
|
||||
├── swift_pose.swift
|
||||
├── swift_ocr.swift
|
||||
└── ...
|
||||
```
|
||||
|
||||
### Rust CLI
|
||||
|
||||
```
|
||||
/Users/accusys/momentry_core/tools/cli/rust/
|
||||
├── src/bin/
|
||||
│ ├── rust_face_cluster.rs
|
||||
│ ├── rust_appearance.rs
|
||||
│ └── rust_pose.rs
|
||||
└── Cargo.toml
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 相關文檔
|
||||
|
||||
- `/Users/accusys/momentry_core/docs_v1.0/DESIGN/Tools_Directory_Restructure.md`
|
||||
- `/Users/accusys/momentry_core/tools/README.md`
|
||||
- `/Users/accusys/momentry_core/AGENTS.md`
|
||||
@@ -0,0 +1,260 @@
|
||||
---
|
||||
document_type: "design"
|
||||
service: "MOMENTRY_CORE"
|
||||
title: "Python → Rust Processor 遷移設計"
|
||||
date: "2026-09-15"
|
||||
version: "V1.0"
|
||||
status: "active"
|
||||
owner: "M5"
|
||||
created_by: "OpenCode"
|
||||
tags:
|
||||
- "processor"
|
||||
- "rust"
|
||||
- "migration"
|
||||
- "feasibility-assessment"
|
||||
- "rust-migration"
|
||||
ai_query_hints:
|
||||
- "Python processor 是否可以改寫成 Rust"
|
||||
- "Rust 版 processor 如何驗證效果與 Python 等同"
|
||||
- "facenet512 mlpackage 如何轉 ONNX"
|
||||
- "whisper-rs 如何取代 faster-whisper"
|
||||
- "agglomerative clustering 如何自建 Rust 實作"
|
||||
- "Rust processor 驗證門檻 A/B 測試"
|
||||
related_documents:
|
||||
- "DESIGN/PythonToSwiftProcessorMigration.md"
|
||||
- "DESIGN/PROCESSOR_MECHANISMS_REVIEW.md"
|
||||
- "DESIGN/Processor_Refactoring_Assessment.md"
|
||||
- "REFERENCE/history/PROCESSORS/SPEECH/ASRX_SELF_IMPLEMENTATION_FEASIBILITY.md"
|
||||
---
|
||||
|
||||
# Python → Rust Processor 遷移設計
|
||||
|
||||
| 項目 | 內容 |
|
||||
|------|------|
|
||||
| 建立者 | OpenCode |
|
||||
| 建立時間 | 2026-09-15 |
|
||||
| 文件版本 | V1.0 |
|
||||
| 目標讀者 | developer, Core team |
|
||||
| Scope | 以 Rust 取代現行 Python processor scripts,**驗證門檻:效果必須等同 Python 或更佳** |
|
||||
| Architecture | **Standalone Rust binaries**(比照 swift_processors 模式),沿用 executor 既有機制 |
|
||||
|
||||
---
|
||||
|
||||
## 版本歷史
|
||||
|
||||
| 版本 | 日期 | 目的 | 操作人 |
|
||||
|------|------|------|--------|
|
||||
| V1.0 | 2026-09-15 | 建立 Python → Rust 遷移設計文件 | OpenCode |
|
||||
|
||||
---
|
||||
|
||||
## 1. 目標與核心原則
|
||||
|
||||
### 1.1 目標
|
||||
以 Rust 取代現行 `src/core/processor/*.rs` 所呼叫的 Python processor scripts,移除或最小化 Python runtime 依賴。
|
||||
|
||||
### 1.2 核心原則(與 Swift 版的根本差異)
|
||||
|
||||
| 路線 | 原則 | 後果 |
|
||||
|------|------|------|
|
||||
| **Swift 版(已評估)** | 換模型(Apple Vision/Speech 取代 Python 模型) | 準確度需重新驗證;ASRX 無 Apple 對應。故不可行/風險高 |
|
||||
| **Rust 版(本文件)** | **不換模型、只換 runtime** | 使用相同模型與演算法,輸出可對齊,驗證成本低 |
|
||||
|
||||
> 換引擎(engine),不換模型(weights)。faster-whisper → whisper.cpp 載入**同一個 Whisper 權重**;coremltools 的 FaceNet512 → ONNX 載入**同樣權重**;cv2 演算法 → ndarray 實作**相同公式**。
|
||||
|
||||
### 1.3 ⛔ 驗證門檻(P0 Mandatory):效果等同 Python 或更佳
|
||||
|
||||
任何 Rust processor **未通過 A/B 對齊驗證前,不得取代 Python 版本**。
|
||||
|
||||
| # | 門檻 | 驗收標準 |
|
||||
|---|------|----------|
|
||||
| 1 | **同檔案 A/B 測試** | 同一支測試影片同時跑 Python 與 Rust 版,輸出 JSON 結構一致 |
|
||||
| 2 | **數值容忍度** | 座標/confidence/分數等在容差內一致(建議 tolerance 見各 processor) |
|
||||
| 3 | **召回率不下降** | detection 數量(frames/faces/persons/scenes)不得明顯少於 Python 版 |
|
||||
| 4 | **無回歸** | 既有 integration test(若存在)與 Pipeline 驗證通過 |
|
||||
| 5 | **效能不劣化** | RTF/處理時間不得劣於 Python 版超過可接受範圍(預設 2x 內) |
|
||||
|
||||
**未過門檻的 Rust processor → 標記 `experimental`,主路徑維持 Python。**
|
||||
|
||||
---
|
||||
|
||||
## 2. Rust library 對應表
|
||||
|
||||
| Python library | Rust 對應 crate | 成熟度 | 備註 |
|
||||
|----------------|-----------------|--------|------|
|
||||
| faster-whisper (CTranslate2) | `whisper-rs`(whisper.cpp bindings) | 🟢 | 同權重;需重寫 scene 分段與 resume |
|
||||
| torch / torchvision | `candle` 或 `ort`(ONNX Runtime) | 🟢 | candle 純 Rust;ort 效能佳 |
|
||||
| coremltools (.mlpackage) | `coremltools` 先轉 **ONNX**,`ort` 載入 | 🟡 | 需一次性轉檔步驟 |
|
||||
| cv2 / numpy | `ndarray` + `image` / `imageproc` / `kmeans-ndarray` | 🟢 | 純數學運算 |
|
||||
| sklearn AgglomerativeClustering | **無現成 crate** → 自建 | 🔴 | 需自實作(見 §6.5) |
|
||||
| ultralytics YOLO | `ort` + `yolov8n-pose.onnx` | 🟢 | Ultralytics 官方 Rust example |
|
||||
| transformers (CLIP) | `candle-clip` 或 ONNX + `ort` | 🟢/🟡 | |
|
||||
| transformers (Moondream2) | 無現成 Rust 支援 | 🔴 | 建議保留 Python |
|
||||
| PaddleOCR | `ort` + PaddleOCR ONNX(`oar-ocr`) | 🟢 | 僅 fallback 用途 |
|
||||
| speechbrain ECAPA-TDNN | 轉 ONNX + `ort` | 🟡 | 語者 embedding |
|
||||
| Silero VAD | `voice_activity_detector`(ONNX) | 🟢 | ASRX VAD |
|
||||
|
||||
### 環境前提
|
||||
- 部署機器為 macOS(M5Max128),`ort` 可選 CoreML/Metal 或 CPU EP。
|
||||
- Rust toolchain 已具備(`cargo build` 正常)。
|
||||
|
||||
---
|
||||
|
||||
## 3. 目標架構
|
||||
|
||||
### 3.1 概覽
|
||||
|
||||
```
|
||||
src/core/processor/{name}.rs (Rust 入口,維持不變)
|
||||
│
|
||||
▼
|
||||
ProcessorExecutor --or--> RustProcessorRunner (新)
|
||||
│ │
|
||||
▼ ▼
|
||||
python script (舊路徑) standalone Rust binary
|
||||
├─ 沿用 .tmp/.partial ├─ scripts/rust_processors/{name}
|
||||
├─ resume / retry └─ 輸出相同 JSON schema
|
||||
└─ SHA256 checksum
|
||||
```
|
||||
|
||||
### 3.2 Standalone Rust binaries(與 swift_processors 同模式)
|
||||
|
||||
- 新目錄:`scripts/rust_processors/`(Swift 版在 `scripts/swift_processors/`)。
|
||||
- 每個 processor 編譯為獨立 binary:`rust_ocr`、`rust_pose`、`rust_asr`、`rust_appearance`……
|
||||
- 呼叫介面與 Swift 對齊:`[video_path, output_path, --sample-interval N, --uuid U, --frames ...]`。
|
||||
- 輸出 JSON schema 與 Python 版**完全一致**(A/B 驗證的前提)。
|
||||
- 由 executor(或新的 `RustExecutor`)呼叫,沿用 `.tmp` → `.json` 提升、timeout、retry 機制。
|
||||
|
||||
### 3.3 模型檔案
|
||||
|
||||
| 模型 | Python 來源 | Rust 使用 | 轉檔需求 |
|
||||
|------|-------------|-----------|----------|
|
||||
| Whisper small | faster-whisper (CTranslate2) | whisper.cpp `.ggml` 格式 | 🟡 需下載/轉換 ggml 版權重 |
|
||||
| FaceNet512 | `models/facenet512.mlpackage` | ONNX | 🟡 需轉檔 |
|
||||
| Places365 (scene) | `resnet18_places365.mlpackage` | ONNX | 🟡 需轉檔 |
|
||||
| YOLOv8n-pose | ultralytics `.pt` | `.onnx` | 🟢 官方支援 export |
|
||||
| ECAPA-TDNN | speechbrain(torch) | ONNX | 🟡 需轉檔 |
|
||||
| CLIP ViT-B/32 | transformers | ONNX / candle | 🟡 |
|
||||
|
||||
**轉檔機制**:一次性的 `scripts/model_export/` Python 工具(保留 Python 僅做轉檔,不需在 runtime 依賴)。
|
||||
|
||||
---
|
||||
|
||||
## 4. 逐 Processor 可行性與驗證標準
|
||||
|
||||
| # | Processor | Python library | Rust 方案 | 判定 | 驗證容忍度 | 關鍵工程點 |
|
||||
|---|-----------|----------------|-----------|------|-----------|-----------|
|
||||
| P1 | **Appearance** | cv2/numpy (HSV + kmeans) | `ndarray` + `kmeans-ndarray` | 🟢 高 | 區域 bbox 像素級一致;色表 2% 差異;kmeans 非確定性 → 需固定 seed/容差放寬 | 最簡單,先行 |
|
||||
| P2 | **Pose** | swift_pose + cv2/numpy interpolation + YOLO fallback | swift_pose + `ndarray` 插值 + `ort` YOLO | 🟢 高 | 插值座標 ±0.5px;YOLO keypoint ±0.1(COCO 17 vs Vision 19 混用需定義 mapping) | 插值純線性;YOLO 需 mapping |
|
||||
| P3 | **Cut** | ffmpeg + PySceneDetect fallback | 已原生 ffmpeg | 🟢 高 | scene 邊界 ±1 frame | 已是 Rust,僅需補 Rust 版 PySceneDetect 漸變偵測(選配) |
|
||||
| P4 | **Hand** | swift_hand wrapper | 保留 swift_hand | 🟢 高 | 不需 Rust 化 | 已 100% Swift |
|
||||
| P5 | **Face clustering** | sklearn AgglomerativeClustering | **自建 Rust** | 🟡 中 | 語者分群結果 correspondence 一致(speaker 編號可不同,成員須一致) | 需實作 cosine + average linkage |
|
||||
| P6 | **Face** | swift_face + coremltools FaceNet512 | swift_face + ONNX FaceNet | 🟡 中 | embedding 餘弦相似度 >0.999;Qdrant push 一致 | facenet512 轉 ONNX |
|
||||
| P7 | **Scene** | torch/torchvision places365 | ONNX places365 | 🟡 中 | top-1 分類一致(容差可放寬 top-3) | 轉檔 |
|
||||
| P8 | **OCR** | swift_ocr + PaddleOCR fallback | 保留 swift_ocr;fallback 換 `oar-ocr` | 🟢 高 | 不適用(已是 Swift) | fallback 不見得需要 Rust |
|
||||
| P9 | **ASR** | faster-whisper | `whisper-rs` | 🟡 中 | 文字內容一致(WER差 ≤1%);時間戳 ±0.5s;resume 行為對齊 | 需下載 ggml 權重;scene 分段重寫 |
|
||||
| P10 | **ASRX** | faster-whisper + VAD + ECAPA + Agglomerative | whisper-rs + `ort` VAD + ONNX ECAPA + 自建 clustering | 🟡 中 | 見 P5;語者 embedding 相似 | **工程量最大** |
|
||||
| P11 | **CLIP** | transformers CLIP | `candle-clip` / ONNX | 🟡 中 | top-k 標籤一致 | 轉檔 |
|
||||
| P12 | **Caption** | Moondream2 VLM | 無現成 | 🔴 低 | — | **保留 Python** |
|
||||
|
||||
### 驗證測試集(共用)
|
||||
|
||||
- 主要測試檔:`IMG_9449 (1).MOV`(UUID `4655a0ab3c077e30c12b2298c2750650`)
|
||||
- 每 processor 選 3–5 支涵蓋正/負例的影片做 A/B。
|
||||
|
||||
---
|
||||
|
||||
## 5. 遷移階段計畫
|
||||
|
||||
### Phase 1 — 低風險、純演算法(不需模型轉檔)
|
||||
| 項目 | 作法 |
|
||||
|------|------|
|
||||
| Appearance | Rust 版 `rust_appearance`(ndarray)A/B 對齊後取代 |
|
||||
| Pose interpolation | Rust/`ndarray` 插值取代 `pose_processor.py` cv2 插值 |
|
||||
| Cut | 補 Rust 版漸變偵測(選配) |
|
||||
| Face clustering | 自建 Rust agglomerative,A/B 對齊 |
|
||||
|
||||
**驗證**:`scripts/ab_verify/appearance/` 等目錄建 A/B harness,跑 Python vs Rust,輸出 diff report。
|
||||
|
||||
### Phase 2 — 需要模型轉檔
|
||||
| 項目 | 作法 |
|
||||
|------|------|
|
||||
| Face | `facenet512.mlpackage` → ONNX(P0 驗證轉檔可行性) |
|
||||
| Scene | places365 → ONNX |
|
||||
| CLIP | ONNX / candle-clip |
|
||||
|
||||
**驗證**:embedding/分類 A/B 對齊。
|
||||
|
||||
### Phase 3 — ASR/ASRX(工程量大)
|
||||
| 項目 | 作法 |
|
||||
|------|------|
|
||||
| ASR | whisper-rs + scene 分段 + resume;ggml 權重下載 |
|
||||
| ASRX | whisper-rs + ort VAD + ONNX ECAPA + Rust agglomerative |
|
||||
|
||||
**驗證**:文字 WER 差 ≤1%、時間戳 ±0.5s、語者分群 correspondence。
|
||||
|
||||
### Phase 4 — 保留 Python
|
||||
| 項目 | 理由 |
|
||||
|------|------|
|
||||
| Caption | Moondream2 無 Rust 支援;維持 Python(或評估 llama.cpp 載入) |
|
||||
|
||||
---
|
||||
|
||||
## 6. 關鍵技術評估
|
||||
|
||||
### 6.1 whisper-rs(ASR)
|
||||
- `whisper-rs 0.16`(2026-03 更新)支援 Metal/CoreML feature;sample 用 `small` int8 需對齊 whisper.cpp ggml 權重。
|
||||
- 需實作:CUT scene 分段轉錄、`.tmp` resume(Python 版 `asr_processor.py:275-413`),與 `word_timestamps` 對齊。
|
||||
- 語音段標計時:whisper.cpp 回傳 segment 級 start/end,可對齊 schema。
|
||||
|
||||
### 6.2 FaceNet512 → ONNX
|
||||
- Python `coremltools` 可直接載入 `.mlpackage` 並 `convert(representation_type="mlprogram")`…但 ONNX 需經 torch/CoreML → ane 具備試作風險。
|
||||
- 另一途徑:用 FaceNet pytorch 官方 weight(`facenet-pytorch`)直接 export ONNX,替換現行 CoreML 權重 —— **代價是權重來源變更,需 A/B 確認 embedding 可比**。
|
||||
|
||||
### 6.3 places365 → ONNX
|
||||
- torchvision `resnet18(weights=Places365)` 以 `torch.onnx.export` 輸出。
|
||||
|
||||
### 6.4 ECAPA-TDNN → ONNX
|
||||
- speechbrain 模型可 `torch.onnx.export`,需修掉 dynamic axis 問題;或改用開源 `ecapa-tdnn.onnx` 權重(需 A/B 驗證 embedding)。
|
||||
|
||||
### 6.5 AgglomerativeClustering 自建(P5/P10)
|
||||
- sklearn 預設:`metric=cosine`(實為 `1 - cosine`)、`linkage=average`。
|
||||
- Rust 實作重點:
|
||||
1. 距離 matrix 用 cosine(`cosine_similarity` → `distance = 1 - sim`)。
|
||||
2. average linkage(UPGMA):pairwise 平均距離更新。
|
||||
3. `distance_threshold` 切 cut(`face_clustering.rs:82` 用 `distance = 1.0 - similarity`)。
|
||||
4. 建 cluster tree,回傳 labels。
|
||||
- 驗證:speaker 分群成員 correspondence,編號不需一致。
|
||||
|
||||
---
|
||||
|
||||
## 7. 風險與取捨
|
||||
|
||||
| 面向 | 風險 | 因應 |
|
||||
|------|------|------|
|
||||
| **權重來源變更** | FaceNet/whisper 若改 ggml/ONNX 權重,embedding/文字可能微差 | 一律 A/B 驗證;差距超標則保留 Python |
|
||||
| **轉檔障礙** | `.mlpackage` → ONNX 可能失敗或輸出異常 | Phase 2 先行 POC(`scripts/model_export/`);失敗則評估 pytorch 權重替代 |
|
||||
| **agglomerative 對齊** | sklearn 數值細節(數值穩定性、連結順序)難完全複製 | 驗證以**分群成員一致**為準,非數值位元一致 |
|
||||
| **非確定性** | kmeans(Appearance)每次結果略異 | 固定 seed;驗證容差放寬 |
|
||||
| **效能** | whisper.cpp vs faster-whisper 於 Mac 上速度差異 | whisper.cpp Metal 加速較優;仍需實測 RTF |
|
||||
| **Double 維護** | 驗證期間 Python/Rust 並存 | `EXPERIMENTAL` flag / env 切換;未過驗證不接主路徑 |
|
||||
|
||||
---
|
||||
|
||||
## 8. 結論
|
||||
|
||||
- **Rust 取代 Python 技術上完全可行**:12 個 processor 中 11 個可行,僅 Caption 建議保留 Python。
|
||||
- **關鍵成功要素是「不換模型」**:與 Swift 版最大差異在於維持相同模型/演算法,使 A/B 驗證成本低。
|
||||
- **Phase 1(Appearance/Pose interpolation/Cut/Face clustering)為最佳切入點**:不需模型轉檔,立即驗證架構可行性。
|
||||
- **Phase 2 的 `.mlpackage → ONNX` 轉檔是最大技術風險**,建議列為 POC 優先驗證。
|
||||
|
||||
---
|
||||
|
||||
## 9. 參考文件
|
||||
|
||||
| 文件 | 用途 |
|
||||
|------|------|
|
||||
| `DESIGN/PythonToSwiftProcessorMigration.md` | Swift 遷移評估(對照用) |
|
||||
| `DESIGN/PROCESSOR_MECHANISMS_REVIEW.md` | Processor 機制檢討 |
|
||||
| `DESIGN/Processor_Refactoring_Assessment.md` | 重構評估 |
|
||||
| `REFERENCE/history/PROCESSORS/SPEECH/ASRX_SELF_IMPLEMENTATION_FEASIBILITY.md` | ASRX 自實作評估 |
|
||||
@@ -0,0 +1,178 @@
|
||||
---
|
||||
document_type: "design"
|
||||
service: "MOMENTRY_CORE"
|
||||
title: "Python → Swift Processor 遷移可行性評估"
|
||||
date: "2026-09-15"
|
||||
version: "V1.0"
|
||||
status: "active"
|
||||
owner: "M5"
|
||||
created_by: "OpenCode"
|
||||
tags:
|
||||
- "processor"
|
||||
- "swift"
|
||||
- "migration"
|
||||
- "feasibility"
|
||||
- "feasibility-assessment"
|
||||
ai_query_hints:
|
||||
- "Python processor 是否可以改寫成 Swift"
|
||||
- "swift_ocr / swift_hand / swift_pose / swift_face 目前用在哪些管線"
|
||||
- "哪些 processor 不建議遷移到 Swift"
|
||||
- "ASRX diarization 是否有 Swift 替代方案"
|
||||
- "FaceNet embedding 是否已遷移到 Swift"
|
||||
related_documents:
|
||||
- "REFERENCE/history/PROCESSORS/SPEECH/ASRX_SELF_IMPLEMENTATION_FEASIBILITY.md"
|
||||
- "DESIGN/PROCESSOR_MECHANISMS_REVIEW.md"
|
||||
- "DESIGN/Processor_Refactoring_Assessment.md"
|
||||
- "DESIGN/Processor_Module_V1.0.md"
|
||||
- "DESIGN/Processor_State_Machine_V1.0.md"
|
||||
---
|
||||
|
||||
# Python → Swift Processor 遷移可行性評估
|
||||
|
||||
| 項目 | 內容 |
|
||||
|------|------|
|
||||
| 建立者 | OpenCode |
|
||||
| 建立時間 | 2026-09-15 |
|
||||
| 文件版本 | V1.0 |
|
||||
| 目標讀者 | developer, Core team |
|
||||
| Scope | 現行 Python processor scripts 改寫為 Swift 的可行性評估與分階段建議 |
|
||||
|
||||
---
|
||||
|
||||
## 版本歷史
|
||||
|
||||
| 版本 | 日期 | 目的 | 操作人 |
|
||||
|------|------|------|--------|
|
||||
| V1.0 | 2026-09-15 | 建立 Python → Swift 遷移可行性設計文件 | OpenCode |
|
||||
|
||||
---
|
||||
|
||||
## 1. 執行摘要
|
||||
|
||||
Momentry Core 目前有 **12 個 Rust processor 入口**(位於 `/Users/accusys/momentry_core/src/core/processor/`),其中大部分透過 PythonExecutor 呼叫 `/Users/accusys/momentry_core/scripts/` 下的 Python scripts 執行模型推理。
|
||||
|
||||
**重要發現**:OCR、Hand、Pose、Face detection 四條管線**已經在呼叫 Swift binary**(`swift_ocr`、`swift_hand`、`swift_pose`、`swift_face`),Python 檔案只是薄包裝(thin wrapper)+ fallback。真正的缺口在於:
|
||||
|
||||
- **ASRX speaker diarization** — Apple Speech framework 無法提供真實 diarization
|
||||
- **FaceNet 512D embedding** — 仍由 Python(cv2 crop + coremltools)執行
|
||||
- **Pose keypoint interpolation**(補插值到全 FPS)— 由 Python cv2/numpy 執行
|
||||
- **Face clustering**(sklearn AgglomerativeClustering)— 無 Swift 原生替代
|
||||
- **CLIP / Caption**(HuggingFace transformers / Moondream2 VLM)— 無原生替代
|
||||
|
||||
**結論**:建議採分階段遷移。OCR/Hand/Pose/Face 已完成(Phase A);scene classifier 走 CoreML 與 pose interpolation 移到 Rust/Swift 屬可立即推進(Phase B);其餘為高風險或保留 Python(Phase C/D)。
|
||||
|
||||
---
|
||||
|
||||
## 2. 現行管線對照表
|
||||
|
||||
Active 實作位於 `src/core/processor/`(`src/processing/modules/` 屬 dead code,未在 `lib.rs` 中宣告,且 `src/processing/handlers.rs` 為 TODO stub)。
|
||||
|
||||
| Rust Processor | 呼叫的 Python script | 關鍵實作 | Swift 現況 |
|
||||
|----------------|---------------------|----------|-----------|
|
||||
| ASR | `asr_processor.py` | faster-whisper (`small`, int8, CPU) | `asr_swift` POC(Apple Speech) |
|
||||
| ASRX | `asrx_processor.py` | HSD 混合管線(whisper + speechbrain + sklearn) | `asrx_swift` POC |
|
||||
| OCR | `ocr_processor.py` | 薄包裝 → **`swift_ocr`**,PaddleOCR fallback | ✅ 已完成 |
|
||||
| Face | `face_processor.py` | 薄包裝 → **`swift_face`**(bbox/landmarks/pose)+ CoreML FaceNet 512D embedding | ⚠️ detection 完成,embedding 仍在 Python |
|
||||
| Pose | `pose_processor.py` | 薄包裝 → **`swift_pose`** + cv2/numpy 補插值 + YOLOv8 fallback | ⚠️ detection 完成,interpolation 仍在 Python |
|
||||
| Hand | `hand_processor.py` | 薄包裝 → **`swift_hand`** | ✅ 已完成 |
|
||||
| Appearance | `appearance_processor.py` | 純 cv2/numpy HSV 顏色分析 | ✅ `swift_appearance_expansion` 已存在 |
|
||||
| Cut | `cut_processor.py` | **先原生 ffmpeg `select=gt(scene,0.3)`**,Python 僅 fallback(PySceneDetect) | ✅ 幾乎原生(POC: `swift_cut_test`) |
|
||||
| Face Cluster | `fast_face_clustering_processor.py` | sklearn AgglomerativeClustering(single-stage) | ❌ 無 |
|
||||
| Scene | `scene_classifier.py` | CoreML Places365 / torch MPS | ⚠️ model 已是 `.mlpackage`(`resnet18_places365.mlpackage`) |
|
||||
| Caption | `caption_processor.py` | Moondream2(local VLM) | ❌ 無 |
|
||||
| CLIP | `clip_classifier.py` | HuggingFace transformers(CLIP ViT-B/32) | ❌ 無 |
|
||||
| Face Recognition | `face_recognition_processor.py` / `face_registration.py` | FaceNet 比對/註冊 | ⚠️ 視 FaceNet 遷移而定 |
|
||||
| TKG | (純 Rust,無 Python) | Qdrant `_faces` scroll | n/a |
|
||||
| VLM Summary | (純 Rust,無 Python) | 呼叫 LLM vision function calling | n/a |
|
||||
|
||||
### 關鍵檔案位置
|
||||
|
||||
- Rust 入口:`/Users/accusys/momentry_core/src/core/processor/{asr,asrx,ocr,face,pose,hand,appearance,cut,face_clustering,scene_classification,caption,clip}.rs`
|
||||
- Worker 排程:`/Users/accusys/momentry_core/src/worker/processor.rs:664-1111`
|
||||
- Python scripts:`/Users/accusys/momentry_core/scripts/*_processor.py`
|
||||
- Swift package:`/Users/accusys/momentry_core/scripts/swift_processors/Package.swift`(17 個 executable targets,僅依賴 swift-argument-parser)
|
||||
- Swift binaries 已 build:`scripts/swift_processors/.build/debug/` 與 `.build/release/`
|
||||
|
||||
---
|
||||
|
||||
## 3. 逐管線可行性評估
|
||||
|
||||
| 管線 | 現行機制 | Swift 方案 | 判定 | 說明 |
|
||||
|------|---------|-----------|------|------|
|
||||
| **OCR** | wrapper → `swift_ocr` | 已完成 | ✅ 已完成 | Vision framework OCR,無需 Python |
|
||||
| **Hand** | wrapper → `swift_hand` | 已完成 | ✅ 已完成 | Vision `VNDetectHumanHandPoseRequest` |
|
||||
| **Pose detection** | wrapper → `swift_pose` | 已完成 | ✅ 已完成 | Vision `VNDetectHumanBodyPoseRequest`(ANE 加速) |
|
||||
| **Pose interpolation** | cv2/numpy 補插值到全 FPS | 需自行移植 | ⚠️ 中等 | 純數學運算,可在 Rust/Swift 實作(見 `pose_processor.py:141-258`) |
|
||||
| **Cut** | ffmpeg `select=scene` | 原生已達成 | ✅ 可行 | ffmpeg scene filter 已是第一優先;Python 為 fallback |
|
||||
| **Appearance** | cv2/numpy HSV 分析 | `swift_appearance_expansion` | ✅ 可行 | 已有現成 Swift 實作 |
|
||||
| **Scene classification** | CoreML Places365 / torch MPS | CoreML 直接載入 | ✅ 可行 | model 為 `.mlpackage`,可在 Swift 用 `MLModel` 直接推理 |
|
||||
| **Face detection** | wrapper → `swift_face` | 已完成 | ✅ 已完成 | Vision bbox/landmarks/pose |
|
||||
| **Face embedding** | cv2 crop + CoreML FaceNet 512D | 需 CoreML Swift 移植 | ⚠️ 中等 | `models/facenet512.mlpackage` 為現成 `.mlpackage`;需實驗 `MLModel` 直接輸出 embedding |
|
||||
| **Face clustering** | sklearn AgglomerativeClustering | 無原生替代 | ❌ 困難 | 需自行實作 linkage 演算法或保留 Python |
|
||||
| **ASR** | faster-whisper (`small`/int8) | `asr_swift`(Apple Speech) | ⚠️ 有取捨 | Apple Speech 準確度與多語系能力不及 faster-whisper;`asr_processor.py:4-8` 即因準確度改用 whisper |
|
||||
| **ASRX** | HSD(whisper + speechbrain + sklearn) | `asrx_swift` POC | ❌ 困難 | **Apple Speech 無真實 diarization**;`asrx_swift.swift:9-10` 已自行承認此限制 |
|
||||
| **CLIP** | HF transformers CLIP ViT-B/32 | 需導出 CoreML CLIP | ⚠️ 有條件 | 需將 CLIP model 轉 `.mlpackage`,工程量大 |
|
||||
| **Caption** | Moondream2(local VLM) | 無 Swift-native VLM | ❌ 不建議 | 此規模的本地 VLM 無 Swift 原生替代 |
|
||||
| **TKG / VLM Summary** | 純 Rust | 不需 Python | ✅ n/a | 與 Python 無關 |
|
||||
|
||||
---
|
||||
|
||||
## 4. 遷移階段建議
|
||||
|
||||
### Phase A(已完成):Vision 偵測類 → Swift
|
||||
|
||||
| 管線 | 狀態 |
|
||||
|------|------|
|
||||
| OCR | ✅ `swift_ocr` |
|
||||
| Hand | ✅ `swift_hand` |
|
||||
| Pose detection | ✅ `swift_pose`(需保留 interpolation 回 Python) |
|
||||
| Face detection | ✅ `swift_face`(需保留 embedding 回 Python) |
|
||||
|
||||
### Phase B(建議下一步,風險低)
|
||||
|
||||
| 項目 | 作法 | 預期效益 |
|
||||
|------|------|----------|
|
||||
| Scene classification 走 CoreML | Python `scene_classifier.py` 改為直接呼叫 Swift 載入 `resnet18_places365.mlpackage`(或直接由 Rust 以 CoreML MLModel 執行) | 移除 torch/torchvision MPS 依賴 |
|
||||
| Pose interpolation 移到 Rust | 把 `pose_processor.py:141-258` 的 cv2/numpy 補插值邏輯改寫成 Rust 或 Swift | 移除 cv2/numpy 依賴,減少 wrapper 轉換成本 |
|
||||
| Appearance 切到 Swift | 使用現成 `swift_appearance_expansion`,替換 `appearance_processor.py` | 移除 cv2/numpy 依賴 |
|
||||
| 移除高成熟度管線的 Python fallback | OCR/Hand/Pose 偵測若 Swift 穩定,移除 PaddleOCR / YOLO fallback | 減少 Python 環境依賴 |
|
||||
|
||||
### Phase C(高風險/選配)
|
||||
|
||||
| 項目 | 作法 | 風險 |
|
||||
|------|------|------|
|
||||
| FaceNet embedding 走 CoreML | 實驗以 Swift `MLModel` 直接對 cropped face 產生 512D embedding,取代 `face_processor.py` 的 cv2+coremltools | CoreML input/output 格式需對齊 FaceNet512 原有前處理(歸一化、Crop) |
|
||||
| Face clustering 自建 | 在 Rust/Swift 實作 AgglomerativeClustering(或改用固定閾值 greedy grouping) | 數值結果需與 sklearn 對齊,驗證成本高 |
|
||||
|
||||
### Phase D(不建議)
|
||||
|
||||
| 管線 | 原因 |
|
||||
|------|------|
|
||||
| **ASRX diarization** | Apple Speech framework 無真實 diarization;現行 HSD 管線涉及 whisper + speechbrain + sklearn,移植至 Swift 需重新設計 |
|
||||
| **CLIP** | 需自行導出 CoreML CLIP,且容量與精度不確定 |
|
||||
| **Caption** | Moondream2 等級的本地 VLM 無 Swift 原生替代 |
|
||||
| **ASR 主路徑** | faster-whisper 準確度/多語系優於 Apple Speech;除非接受準確度下降否則保留 Python |
|
||||
|
||||
---
|
||||
|
||||
## 5. 風險與取捨
|
||||
|
||||
| 面向 | 風險 | 因應 |
|
||||
|------|------|------|
|
||||
| **模型準確度** | ASR/ASRX 改用 Apple Speech 後準確度下降 | 主路徑保留 faster-whisper;`asr_swift`/`asrx_swift` 僅做 POC 或輕量用途 |
|
||||
| **checksums 驗證** | PythonExecutor 在每次執行前做 SHA256 檢查(`checksums.sha256`) | 若新增 Swift binary 路徑,需納入 checksum 或明確標示 `verify_script_integrity` 適用範圍 |
|
||||
| **subprocess env 繼承** | Executor 傳入 9 個 env vars(`MOMENTRY_OUTPUT_DIR`、`DATABASE_SCHEMA`、`MOMENTRY_REDIS_PREFIX`、`QDRANT_URL` 等) | Swift subprocess 需比照 Python wrapper 讀取相同 env vars |
|
||||
| **Swift binary 建置時機** | Swift package 需預先 build(debug/release)才能被呼叫 | 沿用 `scripts/setup/upgrade_momentry.sh:285` 的 swift_processors 複製機制,release/deploy 時一併建置 |
|
||||
| **平台綁定** | Swift processors 依賴 macOS Vision/AVFoundation | 目前部署環境即 macOS(M5Max128),無跨平台需求 |
|
||||
|
||||
---
|
||||
|
||||
## 6. 參考文件
|
||||
|
||||
| 文件 | 用途 |
|
||||
|------|------|
|
||||
| `REFERENCE/history/PROCESSORS/SPEECH/ASRX_SELF_IMPLEMENTATION_FEASIBILITY.md` | ASRX Swift 自實作可行性(既有) |
|
||||
| `DESIGN/PROCESSOR_MECHANISMS_REVIEW.md` | Processor 產出機制檢討(中斷接續/補充/糾錯) |
|
||||
| `DESIGN/Processor_Refactoring_Assessment.md` | Processor 重構評估 |
|
||||
| `DESIGN/Processor_Module_V1.0.md` | Processor 模組規格 |
|
||||
| `DESIGN/Processor_State_Machine_V1.0.md` | Processor 狀態機設計 |
|
||||
@@ -0,0 +1,200 @@
|
||||
---
|
||||
title: Queue Comparison Table
|
||||
version: 1.0
|
||||
date: 2026-10-10
|
||||
author: OpenCode
|
||||
status: draft
|
||||
---
|
||||
|
||||
# Queue Comparison Table
|
||||
|
||||
## 四种队列特征对比
|
||||
|
||||
| 维度 | File Processor | Search Requests | Agent to Agent | VLM Requests |
|
||||
|------|---------------|----------------|----------------|--------------|
|
||||
| **请求来源** | API/CLI/监控 | API | API/内部 | 内部 |
|
||||
| **执行时间** | 分钟-小时 | 秒 (0.1-5s) | 秒 (5-30s) | 秒 (10-30s) |
|
||||
| **CPU 需求** | 高 (4-8 cores) | 低-中 | 中 | 中 |
|
||||
| **内存需求** | 高 (2-8 GB) | 低 (100-500 MB) | 中 (4-8 GB) | 高 (6.6 GB) |
|
||||
| **GPU 需求** | 中 (可选) | 低 | 高 | 极高 (瓶颈) |
|
||||
| **I/O 需求** | 极高 | 中 | 低 | 低 |
|
||||
| **并发特性** | 高 (4 workers) | 极高 (HTTP) | 低-中 (LLM 限制) | 极低 (单实例) |
|
||||
| **优先级** | 低 (批处理) | 高 (实时) | 中 (准实时) | 混合 |
|
||||
| **当前队列** | PostgreSQL + Redis | 无 (同步) | 无 (同步) | 无 (外部服务) |
|
||||
| **是否分离** | ✅ 建议独立队列 | ❌ 保持同步 | ⚠️ 可选队列 | ✅ 必须独立队列 |
|
||||
|
||||
---
|
||||
|
||||
## 资源冲突矩阵
|
||||
|
||||
| 资源 | File Processor | Search | Agent | VLM | 冲突级别 |
|
||||
|------|---------------|--------|-------|-----|---------|
|
||||
| **CPU** | 🟡 中度占用 | 🟢 低 | 🟡 中 | 🟡 中 | 🟢 低 |
|
||||
| **内存** | 🔴 高占用 | 🟢 低 | 🟡 中 | 🔴 高 | 🟡 中 |
|
||||
| **GPU** | 🟢 无/可选 | 🟢 无 | 🔴 高 | 🔴 极高 | 🔴 **严重** |
|
||||
| **数据库** | 🟡 中 | 🔴 高 | 🟡 中 | 🟢 低 | 🟡 中 |
|
||||
| **Redis** | 🟡 中 | 🟢 无 | 🟢 无 | 🟢 无 | 🟢 低 |
|
||||
| **VLM 服务** | 🟡 间接调用 | 🟢 无 | 🔴 直接调用 | 🔴 **独占** | 🔴 **严重** |
|
||||
|
||||
---
|
||||
|
||||
## 优先级需求
|
||||
|
||||
| 场景 | 用户等待 | 可延迟 | 中断影响 | 建议优先级 |
|
||||
|------|---------|--------|---------|-----------|
|
||||
| **Search** | ✅ 是 | ❌ 否 | 🔴 高 | P0 (实时) |
|
||||
| **Agent** | ✅ 是 | ⚠️ 可排队 | 🟡 中 | P1 (准实时) |
|
||||
| **Scene VLM** | ❌ 否 | ✅ 是 | 🟢 低 | P2 (批处理) |
|
||||
| **Face VLM** | ❌ 否 | ✅ 是 | 🟢 低 | P2 (批处理) |
|
||||
| **File Processor** | ❌ 否 | ✅ 是 | 🟢 低 | P3 (后台) |
|
||||
|
||||
---
|
||||
|
||||
## 当前架构瓶颈
|
||||
|
||||
### 瓶颈 1: VLM 服务单实例
|
||||
|
||||
**现状**:
|
||||
- Gemma4 12B + mmproj 运行在 port 8080
|
||||
- 单线程处理,无法并发
|
||||
- GPU 内存独占 (6.6 GB + 167 MB)
|
||||
|
||||
**影响**:
|
||||
- Scene VLM 阻塞 File Processor
|
||||
- Agent VLM 延迟增加
|
||||
- 无法同时处理多个 VLM 请求
|
||||
|
||||
**解决方案**:
|
||||
```
|
||||
方案 A: VLM 请求队列化 (推荐)
|
||||
- 应用层队列管理 VLM 调用
|
||||
- 优先级调度 (Agent VLM > Scene VLM)
|
||||
- 避免资源竞争
|
||||
|
||||
方案 B: 多 VLM 实例 (成本高)
|
||||
- 部署多个 VLM 服务实例
|
||||
- 需要 GPU 资源翻倍
|
||||
- 适用于高并发场景
|
||||
```
|
||||
|
||||
### 瓶颈 2: File Processor 内存泄漏
|
||||
|
||||
**现状**:
|
||||
- Python subprocess 长期运行
|
||||
- 内存占用持续增长
|
||||
- 最终导致 OOM
|
||||
|
||||
**影响**:
|
||||
- 需要定期重启 worker
|
||||
- 任务中断风险
|
||||
- 资源浪费
|
||||
|
||||
**解决方案**:
|
||||
```
|
||||
方案 A: Worker 生命周期管理
|
||||
- 每个 job 完成后重启 worker
|
||||
- 或者定期重启 (如每 24 小时)
|
||||
|
||||
方案 B: 资源隔离
|
||||
- 每个 processor 运行在独立进程
|
||||
- 使用 process pool
|
||||
- 失败不影响其他任务
|
||||
```
|
||||
|
||||
### 瓶颈 3: 无优先级机制
|
||||
|
||||
**现状**:
|
||||
- JobWorker 轮询所有 pending jobs
|
||||
- 先到先处理,无优先级
|
||||
- 实时请求可能被批处理任务阻塞
|
||||
|
||||
**影响**:
|
||||
- 用户体验差
|
||||
- 无法保证 SLA
|
||||
|
||||
**解决方案**:
|
||||
```
|
||||
方案: Redis 优先级队列
|
||||
- 使用多个 Redis list
|
||||
- high_priority_queue: Search/Agent
|
||||
- normal_queue: File Processor
|
||||
- low_priority_queue: Scene VLM
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 迁移路径
|
||||
|
||||
### Phase 1: File Processor Queue (2 周)
|
||||
|
||||
**目标**:将 File Processor 任务迁移到 Redis 队列
|
||||
|
||||
**任务清单**:
|
||||
- [ ] 设计 Redis 队列结构
|
||||
- [ ] 实现 JobProducer (写入队列)
|
||||
- [ ] 实现 JobConsumer (消费队列)
|
||||
- [ ] 迁移 monitor_jobs 状态
|
||||
- [ ] 测试与验证
|
||||
|
||||
**影响范围**:
|
||||
- `job_worker.rs`
|
||||
- `processing.rs`
|
||||
- `files.rs` (register)
|
||||
|
||||
### Phase 2: VLM Request Queue (1 周)
|
||||
|
||||
**目标**:VLM 请求队列化,避免资源竞争
|
||||
|
||||
**任务清单**:
|
||||
- [ ] 实现 VLMRequestQueue
|
||||
- [ ] 优先级调度 (Agent > Scene)
|
||||
- [ ] 限制并发 (max 1)
|
||||
- [ ] 超时与重试机制
|
||||
|
||||
**影响范围**:
|
||||
- `scene_vlm.rs`
|
||||
- `vlm_summary.rs`
|
||||
- `tools.rs` (analyze_frame)
|
||||
|
||||
### Phase 3: Monitoring & Optimization (1 周)
|
||||
|
||||
**目标**:监控队列状态,优化性能
|
||||
|
||||
**任务清单**:
|
||||
- [ ] 队列长度监控
|
||||
- [ ] 处理时间统计
|
||||
- [ ] 告警机制
|
||||
- [ ] 性能优化
|
||||
|
||||
---
|
||||
|
||||
## 成本效益分析
|
||||
|
||||
| 方案 | 开发成本 | 运维成本 | 性能提升 | 用户体验 | 推荐度 |
|
||||
|------|---------|---------|---------|---------|--------|
|
||||
| **当前架构** | 🟢 低 | 🔴 高 (重启频繁) | 🔴 差 | 🔴 差 | ❌ 不推荐 |
|
||||
| **分离队列** | 🟡 中 (4 周) | 🟢 低 | 🟢 好 | 🟢 好 | ✅ 推荐 |
|
||||
| **多 VLM 实例** | 🟡 中 | 🔴 高 (GPU 成本) | 🟢 极好 | 🟢 极好 | ⚠️ 可选 |
|
||||
|
||||
---
|
||||
|
||||
## 决策建议
|
||||
|
||||
### 短期 (1 个月)
|
||||
- ✅ **立即实施**:VLM 请求队列化
|
||||
- 原因:GPU 独占是最严重瓶颈
|
||||
- 成本:低 (应用层队列)
|
||||
- 收益:高 (避免阻塞)
|
||||
|
||||
### 中期 (3 个月)
|
||||
- ✅ **优先实施**:File Processor 队列化
|
||||
- 原因:解决内存泄漏、支持优先级
|
||||
- 成本:中 (Redis 重构)
|
||||
- 收益:高 (稳定性 + 性能)
|
||||
|
||||
### 长期 (6 个月)
|
||||
- ⚠️ **评估后决定**:多 VLM 实例
|
||||
- 原因:成本高,需评估业务需求
|
||||
- 适用场景:高并发 VLM 请求
|
||||
- 替代方案:更高效的 VLM 模型
|
||||
|
||||
@@ -0,0 +1,327 @@
|
||||
# Momentry Core 四种队列需求分析
|
||||
|
||||
## 执行摘要
|
||||
|
||||
Momentry Core 当前使用 **统一的 JobWorker 轮询机制** 处理所有任务,没有独立的队列系统。四种需求各有不同的特征,需要评估是否应该分离队列管理。
|
||||
|
||||
---
|
||||
|
||||
## 1. File Processor Jobs(文件处理任务)
|
||||
|
||||
### 请求来源
|
||||
- **API 调用**:`POST /api/v1/register` (files.rs)
|
||||
- **CLI 命令**:`cargo run -- register /path/to/video.mp4`
|
||||
- **内部调用**:文件监控自动注册
|
||||
|
||||
### 执行时间
|
||||
- **秒级**:单个 processor (Face/OCR) 5-30秒
|
||||
- **分钟级**:完整 pipeline 3-10分钟
|
||||
- **小时级**:大型视频 (>1小时) 可能需要 30-120 分钟
|
||||
|
||||
### 资源需求
|
||||
| 资源 | 需求 | 峰值 |
|
||||
|------|------|------|
|
||||
| **CPU** | 高 (多核并行) | ASR/Face: 4-8 cores |
|
||||
| **内存** | 高 (Python subprocess) | 2-8 GB per job |
|
||||
| **GPU** | 中 (Face/Scene VLM) | 可选,ANE 加速 |
|
||||
| **I/O** | 极高 (视频帧提取) | SSD required |
|
||||
|
||||
### 并发特性
|
||||
- **高并发**:`max_concurrent = 4` (可配置)
|
||||
- **长期占用**:每个 job 持续数分钟到数小时
|
||||
- **Pipeline 限制**:
|
||||
- Frame pipeline: max 4 concurrent (OCR, Face, Pose, YOLO)
|
||||
- Time pipeline: max 2 concurrent (ASR, ASRX, Cut)
|
||||
|
||||
### 优先级需求
|
||||
- **批处理优先级**:后台任务,可延迟
|
||||
- **可中断**:支持取消 (`cancel_token`)
|
||||
- **容错**:retry 机制 (max 3 retries)
|
||||
|
||||
### 当前队列机制
|
||||
- **PostgreSQL `monitor_jobs` 表**:存储任务状态
|
||||
- **Redis 临时存储**:PID tracking, 进度信息
|
||||
- **ProcessorPool**:内存中的并发控制
|
||||
- **轮询机制**:`poll_interval_secs = 10` 秒轮询一次
|
||||
|
||||
### 代码位置
|
||||
```
|
||||
/Users/accusys/momentry_core/src/worker/job_worker.rs (4645 lines)
|
||||
/Users/accusys/momentry_core/src/worker/processor.rs (ProcessorPool)
|
||||
/Users/accusys/momentry_core/src/api/processing.rs (API endpoints)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 2. Search Requests(搜索请求)
|
||||
|
||||
### 请求来源
|
||||
- **API 调用**:
|
||||
- `POST /api/v1/search/smart` (search.rs)
|
||||
- `POST /api/v1/search/universal` (universal_search.rs)
|
||||
- `POST /api/v1/search/agent` (agent_search.rs)
|
||||
- **无 CLI 接口**
|
||||
|
||||
### 执行时间
|
||||
- **秒级**:0.1-5秒
|
||||
- Smart Search (BM25): 0.1-0.5秒
|
||||
- Semantic Search (Qdrant): 0.2-2秒
|
||||
- Universal Search: 1-5秒
|
||||
|
||||
### 资源需求
|
||||
| 资源 | 需求 | 说明 |
|
||||
|------|------|------|
|
||||
| **CPU** | 低-中 | 数据库查询 + 向量相似度 |
|
||||
| **内存** | 低 | 100-500 MB |
|
||||
| **GPU** | 低 | Embedding 计算可离线预计算 |
|
||||
| **I/O** | 中 | 数据库查询 + Qdrant 查询 |
|
||||
|
||||
### 并发特性
|
||||
- **高并发**:HTTP API 天然支持并发
|
||||
- **短时占用**:每次请求 <5秒
|
||||
- **无状态**:无需跟踪状态
|
||||
|
||||
### 优先级需求
|
||||
- **实时响应**:用户等待结果,需立即返回
|
||||
- **不可延迟**:用户交互必需
|
||||
- **低延迟要求**:<2秒响应时间
|
||||
|
||||
### 当前队列机制
|
||||
- **无队列**:直接 HTTP 同步处理
|
||||
- **Database connection pool**:限制数据库连接数
|
||||
- **Qdrant connection**:独立连接池
|
||||
|
||||
### 代码位置
|
||||
```
|
||||
/Users/accusys/momentry_core/src/api/search.rs (846 lines)
|
||||
/Users/accusys/momentry_core/src/api/universal_search.rs (875 lines)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 3. Agent to Agent CLI(Agent 对话)
|
||||
|
||||
### 请求来源
|
||||
- **API 调用**:`POST /api/v1/search/agent` (agent_search.rs)
|
||||
- **内部调用**:工具链调用 (tools.rs)
|
||||
|
||||
### 执行时间
|
||||
- **秒级**:5-30秒
|
||||
- 简单查询 (单工具调用): 5-10秒
|
||||
- 复杂查询 (多工具链): 10-30秒
|
||||
- VLM 分析: 10-20秒
|
||||
|
||||
### 资源需求
|
||||
| 资源 | 需求 | 说明 |
|
||||
|------|------|------|
|
||||
| **CPU** | 中 | LLM 推理 (Gemma4 12B) |
|
||||
| **内存** | 中 | 4-8 GB (Gemma4 模型) |
|
||||
| **GPU** | 高 | ANE/GPU 加速 LLM 推理 |
|
||||
| **I/O** | 低 | 少量数据库查询 |
|
||||
|
||||
### 并发特性
|
||||
- **低-中并发**:受 LLM 服务限制
|
||||
- **有状态**:会话管理 (conversation_id)
|
||||
- **工具链**:可能调用多个工具 (smart_search, semantic_search, analyze_frame)
|
||||
|
||||
### 优先级需求
|
||||
- **准实时**:用户交互,可接受 10-30秒延迟
|
||||
- **可排队**:用户可等待
|
||||
- **资源竞争**:与 VLM requests 竞争 GPU
|
||||
|
||||
### 当前队列机制
|
||||
- **无队列**:直接 HTTP 同步处理
|
||||
- **会话缓存**:内存中的 `CONVERSATIONS` HashMap
|
||||
- **LLM 服务**:外部 llama.cpp server (port 8080)
|
||||
|
||||
### 代码位置
|
||||
```
|
||||
/Users/accusys/momentry_core/src/api/agent_search.rs (543 lines)
|
||||
/Users/accusys/momentry_core/src/core/agent/tools.rs (2080 lines)
|
||||
/Users/accusys/momentry_core/src/core/llm/function_calling.rs (371 lines)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 4. VLM Requests(视觉语言模型请求)
|
||||
|
||||
### 请求来源
|
||||
- **内部调用**:
|
||||
- Scene VLM: `job_worker.rs` -> `process_scene_vlm()`
|
||||
- Face VLM: `vlm_summary.rs` -> `call_llm_vision()`
|
||||
- Agent VLM: `tools.rs` -> `analyze_frame()`
|
||||
|
||||
### 执行时间
|
||||
- **秒级**:10-30秒
|
||||
- Scene VLM (单场景): 10-15秒
|
||||
- Face VLM (单 trace): 10-20秒
|
||||
- Agent analyze_frame: 10-20秒
|
||||
|
||||
### 资源需求
|
||||
| 资源 | 需求 | 说明 |
|
||||
|------|------|------|
|
||||
| **CPU** | 中 | Gemma4 推理 |
|
||||
| **内存** | 高 | 6.6 GB (Gemma4 Q4_K_M) + 167 MB (mmproj) |
|
||||
| **GPU** | 极高 | **瓶颈资源** - 单实例服务 |
|
||||
| **I/O** | 低 | 图片 base64 传输 |
|
||||
|
||||
### 并发特性
|
||||
- **极低并发**:**单实例 VLM 服务** (port 8080)
|
||||
- **串行处理**:llama.cpp server 单线程
|
||||
- **GPU 独占**:模型加载到 VRAM,无法多进程共享
|
||||
|
||||
### 优先级需求
|
||||
- **混合优先级**:
|
||||
- Scene VLM: 批处理,可延迟
|
||||
- Face VLM: 批处理,可延迟
|
||||
- Agent VLM: 准实时,用户等待
|
||||
|
||||
### 当前队列机制
|
||||
- **无应用层队列**:直接调用外部 VLM 服务
|
||||
- **VLM 服务限制**:llama.cpp server 自身的请求队列
|
||||
- **HTTP timeout**:120秒 (generate_scene_description)
|
||||
|
||||
### 代码位置
|
||||
```
|
||||
/Users/accusys/momentry_core/src/core/processor/scene_vlm.rs (701 lines)
|
||||
/Users/accusys/momentry_core/src/core/processor/vlm_summary.rs
|
||||
/Users/accusys/momentry_core/src/core/llm/function_calling.rs (call_llm_vision)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 当前队列实现方式总结
|
||||
|
||||
### 统一的 JobWorker 轮询机制
|
||||
|
||||
```
|
||||
┌─────────────────────────────────────────────────┐
|
||||
│ JobWorker (poll every 10s) │
|
||||
│ │
|
||||
│ 1. 查询 monitor_jobs (status = 'pending') │
|
||||
│ 2. 检查 ProcessorPool 并发限制 │
|
||||
│ 3. 启动 processor (tokio::spawn) │
|
||||
│ 4. 监控进度,写入 Redis │
|
||||
│ 5. 更新 PostgreSQL 状态 │
|
||||
└─────────────────────────────────────────────────┘
|
||||
│ │ │
|
||||
▼ ▼ ▼
|
||||
File Processor Scene VLM Face VLM
|
||||
(异步批处理) (异步批处理) (异步批处理)
|
||||
```
|
||||
|
||||
### 无队列的场景
|
||||
|
||||
| 场景 | 处理方式 | 限制机制 |
|
||||
|------|---------|---------|
|
||||
| **Search Requests** | HTTP 同步处理 | DB connection pool |
|
||||
| **Agent to Agent** | HTTP 同步处理 | LLM 服务限制 |
|
||||
| **VLM Requests** | HTTP 同步调用外部服务 | VLM 服务队列 |
|
||||
|
||||
---
|
||||
|
||||
## 是否需要分开管理?
|
||||
|
||||
### 建议:**分离队列管理**
|
||||
|
||||
### 理由
|
||||
|
||||
1. **资源竞争严重**
|
||||
- File Processor: 长时间占用 CPU/内存
|
||||
- VLM Requests: GPU 独占,无法并发
|
||||
- 混合在一起会导致 VLM 请求被长时间阻塞
|
||||
|
||||
2. **优先级冲突**
|
||||
- Search/Agent: 用户等待,需实时响应
|
||||
- File Processor: 批处理,可延迟
|
||||
- 当前架构无法区分优先级
|
||||
|
||||
3. **并发特性差异巨大**
|
||||
- File Processor: 4 concurrent (可配置)
|
||||
- VLM: **单实例服务,无法并发**
|
||||
- Search: 高并发,短时占用
|
||||
|
||||
### 推荐架构
|
||||
|
||||
```
|
||||
┌─────────────────────────────────────────────────┐
|
||||
│ API Gateway (Axum) │
|
||||
└──────────┬──────────┬──────────┬───────────────┘
|
||||
│ │ │
|
||||
▼ ▼ ▼
|
||||
┌──────────┐ ┌──────────┐ ┌──────────┐
|
||||
│ Search │ │ Agent │ │ Register │
|
||||
│ Handler │ │ Handler │ │ Handler │
|
||||
│ (sync) │ │ (sync) │ │ (async) │
|
||||
└────┬─────┘ └────┬─────┘ └────┬─────┘
|
||||
│ │ │
|
||||
▼ ▼ ▼
|
||||
┌──────────┐ ┌──────────┐ ┌──────────┐
|
||||
│ Database │ │ LLM Pool │ │ JobQueue │
|
||||
│ Pool │ │ (limited)│ │ (Redis) │
|
||||
└──────────┘ └──────────┘ └────┬─────┘
|
||||
│
|
||||
▼
|
||||
┌─────────────────┐
|
||||
│ JobWorker │
|
||||
│ (poll Redis) │
|
||||
└────┬─────┬──────┘
|
||||
│ │
|
||||
▼ ▼
|
||||
┌─────────┐ ┌─────────┐
|
||||
│File Proc│ │VLM Proc │
|
||||
│Pool (4) │ │Pool (1) │
|
||||
└─────────┘ └─────────┘
|
||||
```
|
||||
|
||||
### 队列分离方案
|
||||
|
||||
#### Queue 1: File Processor Queue (Redis-based)
|
||||
- **类型**:FIFO + Priority
|
||||
- **生产者**:Register API, File Monitor
|
||||
- **消费者**:JobWorker (polling)
|
||||
- **并发**:4 workers
|
||||
- **优先级**:低 (batch)
|
||||
|
||||
#### Queue 2: VLM Request Queue (Application-level)
|
||||
- **类型**:FIFO
|
||||
- **生产者**:File Processor, Agent Tools
|
||||
- **消费者**:VLM Worker (single-threaded)
|
||||
- **并发**:1 worker
|
||||
- **优先级**:中 (hybrid)
|
||||
|
||||
#### Queue 3: Search/Agent Requests (No queue)
|
||||
- **类型**:Synchronous HTTP
|
||||
- **并发**:Limited by DB connection pool + LLM service
|
||||
- **优先级**:高 (real-time)
|
||||
|
||||
---
|
||||
|
||||
## 迁移建议
|
||||
|
||||
### Phase 1: 引入 Redis Job Queue (File Processor)
|
||||
1. 将 `monitor_jobs` 状态迁移到 Redis
|
||||
2. 实现优先级队列
|
||||
3. 支持任务取消、重试
|
||||
|
||||
### Phase 2: VLM 请求队列化
|
||||
1. 应用层队列管理 VLM 调用
|
||||
2. 优先级调度 (Agent VLM > Scene VLM)
|
||||
3. 避免与 File Processor 竞争
|
||||
|
||||
### Phase 3: 监控与优化
|
||||
1. 队列长度监控
|
||||
2. 处理时间统计
|
||||
3. 自动扩缩容
|
||||
|
||||
---
|
||||
|
||||
## 当前瓶颈分析
|
||||
|
||||
| 瓶颈 | 原因 | 影响 | 解决方案 |
|
||||
|------|------|------|---------|
|
||||
| **VLM 服务单实例** | GPU 独占 | Scene VLM 阻塞 File Processor | 分离 VLM 队列 |
|
||||
| **File Processor 内存泄漏** | Python subprocess | 长时间运行后 OOM | 定期重启 worker |
|
||||
| **Search/Agent 无并发控制** | 共享 LLM 服务 | 高并发时延迟增加 | 限流 + 队列 |
|
||||
| **无优先级机制** | 轮询无优先级 | 实时请求被阻塞 | 优先级队列 |
|
||||
|
||||
@@ -0,0 +1,187 @@
|
||||
---
|
||||
title: Rule 1 Chunk Ingestion V1.0
|
||||
version: 1.0
|
||||
date: 2026-06-20
|
||||
author: OpenCode
|
||||
status: approved
|
||||
---
|
||||
|
||||
# Rule 1 Chunk Ingestion V1.0
|
||||
|
||||
| Scope | Status | Applicable to | Binary |
|
||||
|-------|--------|---------------|--------|
|
||||
| Sentence chunk creation from ASR + OCR | Approved | `momentry_playground`, `momentry` | Both |
|
||||
|
||||
## Overview
|
||||
|
||||
Rule 1 is the first chunking rule in Momentry's pipeline. It creates **sentence-level chunks** (`ChunkType::Sentence`, `ChunkRule::Rule1`) by taking ASR transcription segments and enriching them with OCR on-screen text from the same time range. Each chunk represents a spoken segment annotated with the visible text in the video frames.
|
||||
|
||||
These chunks are vectorized by the downstream `vectorize_chunks` step and become searchable through semantic search (Qdrant), keyword search (BM25 ILIKE), and identity-based search.
|
||||
|
||||
## Data Flow
|
||||
|
||||
```
|
||||
┌─────────────────────────────────────────────────────────┐
|
||||
│ UPSTREAM: pre_chunks table │
|
||||
│ │
|
||||
│ Processor outputs stored by store_raw_pre_chunks_batch: │
|
||||
│ processor_type='asr' → ASR segments (text, timestamps) │
|
||||
│ processor_type='ocr' → OCR texts per frame │
|
||||
└─────────────────────────────────────────────────────────┘
|
||||
│
|
||||
▼ wait for ASRX completion
|
||||
│
|
||||
┌─────────────────────────────────────────────────────────┐
|
||||
│ RULE 1 PROCESSING │
|
||||
│ │
|
||||
│ Triggered by: │
|
||||
│ 1. Worker auto: job_worker.rs after ASRX completes │
|
||||
│ 2. HTTP API: POST /api/v1/file/:file_uuid/rule1 │
|
||||
│ 3. Pipeline: pipeline_core::execute_rule1 │
|
||||
│ │
|
||||
│ execute_rule1(file_uuid, fps): │
|
||||
│ ├─ fetch_asr_segments() → Vec<AsrSegment> │
|
||||
│ ├─ fetch_ocr_texts() → BTreeMap<frame, [texts]> │
|
||||
│ │ │
|
||||
│ └─ for each ASR segment: │
|
||||
│ ├─ collect_ocr_text(frame_range, ocr_map) │
|
||||
│ │ → deduplicated OCR texts within range │
|
||||
│ ├─ build combined_text = "<ASR> <OCR>" │
|
||||
│ ├─ build content = {text, ocr_text} │
|
||||
│ ├─ build metadata = {language} │
|
||||
│ └─ store_chunk_in_tx() → chunk table │
|
||||
│ │
|
||||
└─────────────────────────────────────────────────────────┘
|
||||
│
|
||||
▼
|
||||
┌─────────────────────────────────────────────────────────┐
|
||||
│ DOWNSTREAM: vectorize_chunks() │
|
||||
│ │
|
||||
│ SELECT ... WHERE chunk_type='sentence' AND embedding │
|
||||
│ IS NULL │
|
||||
│ │
|
||||
│ 1. embedder.embed_document(combined_text) → vector │
|
||||
│ 2. db.store_vector() → PG chunk.embedding │
|
||||
│ 3. qdrant.upsert_vector() → momentry_rule1 collection │
|
||||
│ │
|
||||
└─────────────────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
## Chunk Data Structure
|
||||
|
||||
### Content JSON (`content` column)
|
||||
|
||||
```json
|
||||
{
|
||||
"text": "今天的會議我們要討論 ...",
|
||||
"ocr_text": "Q3 Revenue Slides Agenda"
|
||||
}
|
||||
```
|
||||
|
||||
| Field | Source | Purpose |
|
||||
|-------|--------|---------|
|
||||
| `text` | ASR transcription | Original spoken text, used by UI/reference |
|
||||
| `ocr_text` | OCR detections in frame range | On-screen text (titles, labels, signs) |
|
||||
|
||||
### Text Content (`text_content` column)
|
||||
|
||||
```
|
||||
"今天的會議我們要討論 Q3 Revenue Slides Agenda"
|
||||
```
|
||||
|
||||
Combined ASR + OCR text used for:
|
||||
- **Embedding generation**: The combined text is embedded to Qdrant, enabling semantic search to find segments based on both spoken and on-screen content
|
||||
- **Keyword search (BM25 ILIKE)**: Queries match against this field, so searching for "Q3 Revenue" finds the segment even if not spoken aloud
|
||||
|
||||
### Metadata JSON (`metadata` column)
|
||||
|
||||
```json
|
||||
{
|
||||
"language": "zh"
|
||||
}
|
||||
```
|
||||
|
||||
Only the ASR-detected language is stored. See Design Decisions below.
|
||||
|
||||
## Search Contribution Analysis
|
||||
|
||||
| Search Path | Mechanism | Rule 1 Contribution |
|
||||
|-------------|-----------|-------------------|
|
||||
| **Semantic search** (Qdrant) | `chunk_type='sentence'` → embedding query | ASR + OCR text in embedding captures both spoken and visual content |
|
||||
| **Keyword search** (BM25 ILIKE) | `text_content ILIKE '%query%'` | Both ASR and OCR text are searchable |
|
||||
| **Title match** (smart_search) | `chunk_type='sentence' AND embedding IS NOT NULL` | Rule 1 chunks are the primary sentence chunks |
|
||||
| **Identity search** | `face_detections` time overlap join | Rule 1 chunks match via frame ranges |
|
||||
|
||||
### What Was Excluded and Why
|
||||
|
||||
| Data Source | Considered For | Decision | Reason |
|
||||
|-------------|---------------|----------|--------|
|
||||
| **YOLO detections** | Adding class names to text_content | ❌ **Excluded** | 80 COCO classes are too generic ("person", "chair" appear in almost every segment). High error rate adds noise, dilutes embedding semantic density. Cross-segment distinctiveness is near zero. |
|
||||
| **ASRX speaker** | Adding speaker_id to metadata | ❌ **Excluded** | At Rule 1 time, identity has not been paired yet. Speaker IDs are temporary labels without identity binding, providing no search value. |
|
||||
| **Face detections** | Adding face_ids to metadata | ❌ **Excluded** | Same as speaker — identity not yet available. Face detection IDs alone have no search meaning. |
|
||||
| **OCR text** | Adding to text_content + embedding | ✅ **Included** | OCR provides specific on-screen text (titles, labels, signs) that directly matches user search queries. Highly complementary to ASR. |
|
||||
|
||||
## Implementation Details
|
||||
|
||||
### `fetch_ocr_texts()`
|
||||
|
||||
Reads OCR per-frame data from `pre_chunks`:
|
||||
|
||||
```sql
|
||||
SELECT coordinate_index as frame, data
|
||||
FROM pre_chunks
|
||||
WHERE file_uuid = $1 AND processor_type = 'ocr'
|
||||
ORDER BY coordinate_index
|
||||
```
|
||||
|
||||
Parses the `data.texts` JSON array, extracting `text` fields where `confidence > 0.5`. Returns `BTreeMap<i64, Vec<String>>` mapping frame number to list of recognized text strings.
|
||||
|
||||
### `collect_ocr_text()`
|
||||
|
||||
For a given frame range `[start_frame, end_frame]`:
|
||||
1. Iterates frames using `BTreeMap::range(start_frame..=end_frame)`
|
||||
2. Collects all OCR texts from those frames
|
||||
3. Deduplicates using a `HashSet` (case-sensitive)
|
||||
4. Joins with spaces: `"text1 text2 text3"`
|
||||
|
||||
Returns empty string if no OCR data exists in the range.
|
||||
|
||||
### `text_content` Composition Rules
|
||||
|
||||
```
|
||||
if OCR text exists:
|
||||
combined = "{asr_text} {ocr_text}"
|
||||
else:
|
||||
combined = "{asr_text}"
|
||||
```
|
||||
|
||||
The combined string is used for both embedding and keyword search. The original ASR text is preserved separately in `content.text`.
|
||||
|
||||
## Trigger Points
|
||||
|
||||
| Trigger | Location | Condition |
|
||||
|---------|----------|-----------|
|
||||
| Worker auto | `job_worker.rs:1135` | After ASRX processor completes and no sentence chunks exist yet |
|
||||
| HTTP API | `POST /api/v1/file/:file_uuid/rule1` | Manual trigger via `pipeline_core::execute_rule1` |
|
||||
| Programmatic | `pipeline_core::execute_rule1` | Called by other modules needing sentence chunks |
|
||||
|
||||
The worker guard checks idempotency:
|
||||
```sql
|
||||
SELECT 1 FROM chunk WHERE file_uuid = $1 AND chunk_type = 'sentence' LIMIT 1
|
||||
```
|
||||
|
||||
## Edge Cases
|
||||
|
||||
| Scenario | Behavior |
|
||||
|----------|----------|
|
||||
| No ASR segments | Returns 0 immediately with info log |
|
||||
| No OCR data in pre_chunks | `ocr_text` is empty string; `text_content` = ASR only |
|
||||
| OCR frame with no valid text | Skipped (confidence < 0.5 or empty string) |
|
||||
| ASR segment end_time = 0.0 | Logs warning; overlap-based matching degrades gracefully |
|
||||
| Large number of segments | Batches in single transaction; progress logged every 100 segments |
|
||||
|
||||
## Version History
|
||||
|
||||
| Version | Date | Author | Change |
|
||||
|---------|------|--------|--------|
|
||||
| 1.0 | 2026-06-20 | OpenCode | Initial design: ASR + OCR → sentence chunks |
|
||||
@@ -0,0 +1,249 @@
|
||||
---
|
||||
title: Rule 2 TKG Relationship Chunks V1.0
|
||||
version: 1.1
|
||||
date: 2026-06-22
|
||||
author: OpenCode
|
||||
status: approved
|
||||
---
|
||||
|
||||
# Rule 2 TKG Relationship Chunks V1.0
|
||||
|
||||
| Scope | Status | Applicable to | Binary |
|
||||
|-------|--------|---------------|--------|
|
||||
| TKG relationship vectorization | Approved | `momentry_playground`, `momentry` | Both |
|
||||
|
||||
## Overview
|
||||
|
||||
Rule 2 creates **relationship chunks** by converting TKG edges into searchable, vectorized units. Each TKG edge becomes a chunk with LLM-generated natural language description, enabling semantic search for relationship queries.
|
||||
|
||||
**Key Change:** Original Rule 2 (YOLO frame objects) is deprecated due to COCO classes being too generic. New Rule 2 focuses on TKG relationships.
|
||||
|
||||
## Node Types (V2.0 - Intuitive Naming)
|
||||
|
||||
| Old Name | New Name | Description | external_id Format |
|
||||
|----------|----------|-------------|-------------------|
|
||||
| `face_trace` | `face_track` | Face tracking across frames | `face_track_1` |
|
||||
| `person_trace` | `body_track` | Body appearance tracking | `body_track_0` |
|
||||
| `gaze_trace` | `gaze_track` | Gaze direction sequence | `gaze_track_1` |
|
||||
| `lip_trace` | `lip_track` | Lip sync sequence | `lip_track_1` |
|
||||
| `hand_trace` | `hand_track` | Hand state sequence | `hand_track_0` |
|
||||
| `speaker` | `speaker_segment` | Speaker segment | `speaker_01` |
|
||||
| `object` | `detected_object` | YOLO detected object | `car`, `phone` |
|
||||
| `text_trace` | `text_region` | OCR text region | `text_1` |
|
||||
|
||||
## Data Flow
|
||||
|
||||
```
|
||||
┌─────────────────────────────────────────────────────────┐
|
||||
│ UPSTREAM: TKG Builder │
|
||||
│ │
|
||||
│ tkg_nodes: face_track, speaker_segment, detected_object │
|
||||
│ tkg_edges: speaker_face, mutual_gaze, co_occurs, etc. │
|
||||
│ │
|
||||
└─────────────────────────────────────────────────────────┘
|
||||
│
|
||||
▼ after TKG complete
|
||||
│
|
||||
┌─────────────────────────────────────────────────────────┐
|
||||
│ RULE 2 PROCESSING │
|
||||
│ │
|
||||
│ Triggered by: │
|
||||
│ 1. Worker auto: job_worker.rs after TKG completes │
|
||||
│ 2. HTTP API: POST /api/v1/file/:file_uuid/rule2 │
|
||||
│ │
|
||||
│ ingest_rule2(file_uuid): │
|
||||
│ ├─ Query tkg_edges by type (priority order) │
|
||||
│ ├─ For each edge: │
|
||||
│ │ ├─ Resolve source_node / target_node │
|
||||
│ │ ├─ Resolve identity names (if face_track) │
|
||||
│ │ ├─ Build context JSON │
|
||||
│ │ ├─ call_llm(context) → text_content │
|
||||
│ │ └─ INSERT INTO chunk (chunk_type='relationship') │
|
||||
│ │ │
|
||||
│ │
|
||||
└─────────────────────────────────────────────────────────┘
|
||||
│
|
||||
▼
|
||||
┌─────────────────────────────────────────────────────────┐
|
||||
│ DOWNSTREAM: vectorize_chunks() │
|
||||
│ │
|
||||
│ SELECT ... WHERE chunk_type='relationship' │
|
||||
│ AND embedding IS NULL │
|
||||
│ │
|
||||
│ 1. embedder.embed_document(text_content) → vector │
|
||||
│ 2. db.store_vector() → PG chunk.embedding │
|
||||
│ 3. qdrant.upsert_vector() → momentry_rule2 collection │
|
||||
│ │
|
||||
└─────────────────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
## Edge Type Priority
|
||||
|
||||
| Priority | Edge Type | Description | Example Output |
|
||||
|----------|-----------|-------------|----------------|
|
||||
| P0 | `speaker_face` | Speaker ↔ Face track | "SPEAKER_01 以 Cary Grant 的身份說話,從 frame 100 到 350" |
|
||||
| P0 | `mutual_gaze` | Two face tracks looking at each other | "Cary Grant 和 Grace Kelly 互相看對方 24 幀,起始於 frame 450" |
|
||||
| P1 | `face_face` | Two face tracks co-occurring | "Cary Grant 和 Grace Kelly 同框 180 幀" |
|
||||
| P1 | `co_occurs` | Detected object ↔ Detected object co-occurrence | "物件 'car' 和 'person' 在同一畫面出現 60 幀" |
|
||||
| P2 | `has_appearance` | Face track ↔ Body track | "Cary Grant 穿著藍色上衣,戴眼鏡" |
|
||||
| P2 | `wears` | Face track ↔ Accessory | "Cary Grant 戴帽子,信心值 0.82" |
|
||||
|
||||
## Chunk Data Structure
|
||||
|
||||
### Content JSON (`content` column)
|
||||
|
||||
```json
|
||||
{
|
||||
"edge_type": "speaker_face",
|
||||
"edge_id": 123,
|
||||
"source_node": {
|
||||
"id": 45,
|
||||
"node_type": "speaker_segment",
|
||||
"external_id": "speaker_01",
|
||||
"label": "SPEAKER_01"
|
||||
},
|
||||
"target_node": {
|
||||
"id": 67,
|
||||
"node_type": "face_track",
|
||||
"external_id": "face_track_5",
|
||||
"label": "Face Track 5",
|
||||
"identity_name": "Cary Grant"
|
||||
},
|
||||
"properties": {
|
||||
"first_frame": 100,
|
||||
"last_frame": 350,
|
||||
"frame_count": 250,
|
||||
"lip_sync_confidence": 0.85
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Text Content (`text_content` column)
|
||||
|
||||
LLM-generated natural language description in Traditional Chinese:
|
||||
|
||||
```
|
||||
"SPEAKER_01 以 Cary Grant 的身份說話,從 frame 100 到 frame 350,唇語同步信心值 0.85"
|
||||
```
|
||||
|
||||
### Metadata JSON (`metadata` column)
|
||||
|
||||
```json
|
||||
{
|
||||
"source_type": "speaker",
|
||||
"target_type": "face_trace",
|
||||
"has_identity": true,
|
||||
"identity_source": "tmdb"
|
||||
}
|
||||
```
|
||||
|
||||
## LLM Prompt Template
|
||||
|
||||
```text
|
||||
你是影片關係描述專家。請用繁體中文描述以下人物/物件關係:
|
||||
|
||||
關係類型: {edge_type}
|
||||
來源節點: {source_node.node_type} - {source_node.external_id}
|
||||
身份名稱: {identity_name} (如果有)
|
||||
目標節點: {target_node.node_type} - {target_node.external_id}
|
||||
身份名稱: {identity_name} (如果有)
|
||||
關係屬性:
|
||||
- 起始幀: {first_frame}
|
||||
- 結束幀: {last_frame}
|
||||
- 幀數: {frame_count}
|
||||
- 信心值: {confidence}
|
||||
|
||||
要求:
|
||||
1. 使用自然語言,不要輸出 JSON
|
||||
2. 包含時間範圍(幀號)
|
||||
3. 包含人物名字(如有 identity)
|
||||
4. 簡潔,20-50 字
|
||||
5. 用繁體中文
|
||||
|
||||
範例輸出:
|
||||
"SPEAKER_01 以 Cary Grant 的身份說話,從 frame 100 到 frame 350"
|
||||
"Cary Grant 和 Grace Kelly 互相看對方 24 幀,起始於 frame 450"
|
||||
```
|
||||
|
||||
## Edge → Chunk Conversion Rules
|
||||
|
||||
### speaker_face Edge
|
||||
|
||||
```rust
|
||||
// Source: speaker_segment node
|
||||
// Target: face_track node
|
||||
// Properties: first_frame, last_frame, lip_sync_confidence
|
||||
|
||||
let text_content = call_llm(format!(
|
||||
"SPEAKER {} 對應 face track {},身份 {},frame {}-{}",
|
||||
speaker_id, track_id, identity_name, first_frame, last_frame
|
||||
));
|
||||
```
|
||||
|
||||
### mutual_gaze Edge
|
||||
|
||||
```rust
|
||||
// Source: face_track node A
|
||||
// Target: face_track node B
|
||||
// Properties: first_frame, gaze_frame_count, yaw_a_avg, yaw_b_avg
|
||||
|
||||
let text_content = call_llm(format!(
|
||||
"人物 {} 和 {} 互相看對方 {} 幀,起始於 frame {}",
|
||||
identity_a, identity_b, gaze_frame_count, first_frame
|
||||
));
|
||||
```
|
||||
|
||||
### has_appearance Edge
|
||||
|
||||
```rust
|
||||
// Source: face_track node
|
||||
// Target: body_track node
|
||||
// Properties: clothing colors, accessories
|
||||
|
||||
let text_content = call_llm(format!(
|
||||
"人物 {} 穿著 {} 上衣,{} 下衣",
|
||||
identity_name, upper_color, lower_color
|
||||
));
|
||||
```
|
||||
|
||||
## Search Contribution
|
||||
|
||||
| Search Path | Mechanism | Rule 2 Contribution |
|
||||
|-------------|-----------|-------------------|
|
||||
| **Semantic search** (Qdrant) | `chunk_type='relationship'` → embedding query | LLM descriptions enable natural language queries |
|
||||
| **Keyword search** (BM25 ILIKE) | `text_content ILIKE '%互相看%'` | Relationship keywords searchable |
|
||||
| **Agent tkg_query** | Direct edge queries | Rule 2 complements with vectorized search |
|
||||
| **identity_text** | Reverse lookup | "誰戴眼鏡" → has_appearance chunks |
|
||||
|
||||
## Trigger Points
|
||||
|
||||
| Trigger | Location | Condition |
|
||||
|---------|----------|-----------|
|
||||
| Worker auto | `job_worker.rs` | After TKG builder completes |
|
||||
| HTTP API | `POST /api/v1/file/:file_uuid/rule2` | Manual trigger |
|
||||
| Pipeline | `pipeline_core::execute_rule2` | Called by other modules |
|
||||
|
||||
## Edge Cases
|
||||
|
||||
| Scenario | Behavior |
|
||||
|----------|----------|
|
||||
| No tkg_edges | Returns 0 immediately with info log |
|
||||
| Edge without identity | Use node external_id (e.g., "trace_5") in description |
|
||||
| LLM call fails | Fallback to template-based description |
|
||||
| Multiple edges same type | Each edge becomes separate chunk |
|
||||
|
||||
## Qdrant Collection
|
||||
|
||||
| Property | Value |
|
||||
|----------|-------|
|
||||
| Collection name | `momentry_rule2` |
|
||||
| Vector size | 768 (nomic-embed-text-v2-moe) |
|
||||
| Distance | Cosine |
|
||||
| Payload | `{chunk_id, file_uuid, edge_type, source_type, target_type}` |
|
||||
|
||||
## Version History
|
||||
|
||||
| Version | Date | Author | Change |
|
||||
|---------|------|--------|--------|
|
||||
| 1.1 | 2026-06-22 | OpenCode | Node type renaming: face_trace→face_track, person_trace→body_track, etc. |
|
||||
| 1.0 | 2026-06-20 | OpenCode | Initial design: TKG edges → relationship chunks |
|
||||
@@ -0,0 +1,179 @@
|
||||
---
|
||||
title: Redis Prefix Configuration
|
||||
version: 1.0
|
||||
date: 2026-06-21
|
||||
author: momentry_core development
|
||||
status: active
|
||||
---
|
||||
|
||||
## Overview
|
||||
|
||||
Momentry Core uses Redis key prefixes to isolate namespaces between Production and Playground environments. This prevents cross-contamination of job queues, progress data, and cache entries.
|
||||
|
||||
## Environment Configuration
|
||||
|
||||
| Environment | Port | Redis Prefix | Config File |
|
||||
|-------------|------|--------------|-------------|
|
||||
| **Production** | 3002 | `momentry:` | `.env` (default) |
|
||||
| **Playground** | 3003 | `momentry_dev:` | `.env.development` |
|
||||
|
||||
### Configuration
|
||||
|
||||
```bash
|
||||
# Production (.env)
|
||||
MOMENTRY_REDIS_PREFIX=momentry: # Default if not set
|
||||
|
||||
# Playground (.env.development)
|
||||
MOMENTRY_REDIS_PREFIX=momentry_dev:
|
||||
```
|
||||
|
||||
## Redis Key Structure
|
||||
|
||||
All Redis keys follow this pattern:
|
||||
|
||||
```
|
||||
{prefix}{key_type}:{identifier}
|
||||
```
|
||||
|
||||
### Key Types
|
||||
|
||||
| Key Type | Pattern | Example |
|
||||
|----------|---------|---------|
|
||||
| Job | `{prefix}job:{file_uuid}` | `momentry:job:abc123...` |
|
||||
| Progress | `{prefix}progress:{file_uuid}` | `momentry:progress:abc123...` |
|
||||
| Processor | `{prefix}job:{file_uuid}:processor:{type}` | `momentry:job:abc123:processor:face` |
|
||||
| Health | `{prefix}health` | `momentry:health` |
|
||||
|
||||
## Namespace Isolation
|
||||
|
||||
### Production vs Playground
|
||||
|
||||
**Production (3002)**:
|
||||
- Jobs created by production API → `momentry:job:*`
|
||||
- Worker must run with production prefix
|
||||
- Production worker sees only production jobs
|
||||
|
||||
**Playground (3003)**:
|
||||
- Jobs created by playground API → `momentry_dev:job:*`
|
||||
- Worker must run with playground prefix
|
||||
- Playground worker sees only playground jobs
|
||||
|
||||
### Cross-Namespace Access
|
||||
|
||||
❌ **Cannot access**:
|
||||
- Production API cannot see playground jobs
|
||||
- Playground API cannot see production jobs
|
||||
- Worker with wrong prefix will not process jobs
|
||||
|
||||
✅ **Design intent**:
|
||||
- Complete isolation between environments
|
||||
- No accidental cross-contamination
|
||||
- Safe testing in playground without affecting production
|
||||
|
||||
## Worker Configuration
|
||||
|
||||
Workers must match the Redis prefix of the server that creates jobs:
|
||||
|
||||
```bash
|
||||
# Production worker
|
||||
./target/release/momentry worker
|
||||
# Uses: momentry: prefix (default)
|
||||
|
||||
# Playground worker
|
||||
./target/debug/momentry_playground worker
|
||||
# Uses: momentry_dev: prefix (from .env.development)
|
||||
```
|
||||
|
||||
### Worker Redis Connection
|
||||
|
||||
Workers read Redis prefix from environment:
|
||||
|
||||
1. Check `MOMENTRY_REDIS_PREFIX` environment variable
|
||||
2. If not set, use default prefix:
|
||||
- `momentry` binary → `momentry:`
|
||||
- `momentry_playground` binary → `momentry_dev:`
|
||||
|
||||
## Common Issues
|
||||
|
||||
### Issue: Jobs Not Being Processed
|
||||
|
||||
**Symptoms**:
|
||||
- API returns "Processing triggered"
|
||||
- Worker shows no activity
|
||||
- Redis job key created but not consumed
|
||||
|
||||
**Cause**: Worker running with wrong Redis prefix
|
||||
|
||||
**Solution**:
|
||||
```bash
|
||||
# Check worker prefix
|
||||
redis-cli keys "momentry*"
|
||||
|
||||
# If jobs in momentry: namespace
|
||||
# Production worker needed
|
||||
./target/release/momentry worker
|
||||
|
||||
# If jobs in momentry_dev: namespace
|
||||
# Playground worker needed
|
||||
./target/debug/momentry_playground worker
|
||||
```
|
||||
|
||||
### Issue: Progress API Returns Empty
|
||||
|
||||
**Symptoms**:
|
||||
- Progress API returns empty response
|
||||
- Job exists but progress not visible
|
||||
|
||||
**Cause**: Progress key in different namespace
|
||||
|
||||
**Solution**:
|
||||
- Ensure worker prefix matches server prefix
|
||||
- Check Redis keys: `redis-cli keys "{prefix}progress:*"`
|
||||
|
||||
## Redis CLI Examples
|
||||
|
||||
```bash
|
||||
# List all production jobs
|
||||
redis-cli -a accusys keys "momentry:job:*"
|
||||
|
||||
# List all playground jobs
|
||||
redis-cli -a accusys keys "momentry_dev:job:*"
|
||||
|
||||
# Check progress for specific file (production)
|
||||
redis-cli -a accusys HGETALL "momentry:progress:{file_uuid}"
|
||||
|
||||
# Check progress for specific file (playground)
|
||||
redis-cli -a accusys HGETALL "momentry_dev:progress:{file_uuid}"
|
||||
|
||||
# Delete all production jobs (⚠️ destructive)
|
||||
redis-cli -a accusys keys "momentry:job:*" | xargs redis-cli -a accusys del
|
||||
|
||||
# Delete all playground jobs (⚠️ destructive)
|
||||
redis-cli -a accusys keys "momentry_dev:job:*" | xargs redis-cli -a accusys del
|
||||
```
|
||||
|
||||
## Best Practices
|
||||
|
||||
1. **Always match worker to server**: Production worker for production server, playground worker for playground server
|
||||
|
||||
2. **Check Redis keys**: Before debugging worker issues, verify namespace alignment
|
||||
|
||||
3. **Document in AGENTS.md**: Update Redis prefix documentation when configuration changes
|
||||
|
||||
4. **Never mix namespaces**: Keep production and playground completely isolated
|
||||
|
||||
5. **Use environment variables**: Configure prefix via `.env` files, not hardcoded values
|
||||
|
||||
## Related Documentation
|
||||
|
||||
- `docs_v1.0/DESIGN/Redis_Progress_Reporting_V1.0.md` - Progress reporting design
|
||||
- `docs_v1.0/M4_workspace/2026-06-21_issue_report.md` - Issue report with Redis prefix problem
|
||||
- `AGENTS.md` - Environment configuration reference
|
||||
|
||||
---
|
||||
|
||||
## Version History
|
||||
|
||||
| Version | Date | Changes |
|
||||
|---------|------|---------|
|
||||
| 1.0 | 2026-06-21 | Initial documentation for Redis prefix configuration |
|
||||
@@ -0,0 +1,756 @@
|
||||
# Momentry Core Replay 系统设计
|
||||
|
||||
**日期**: 2026-10-11
|
||||
**版本**: V1.0
|
||||
**状态**: 设计阶段
|
||||
|
||||
---
|
||||
|
||||
## 🎯 目标
|
||||
|
||||
实现命令队列 Replay 功能,用于:
|
||||
1. 验证系统稳定度
|
||||
2. 测试幂等性
|
||||
3. 压力测试
|
||||
4. 容错能力测试
|
||||
|
||||
---
|
||||
|
||||
## 📊 支持的 Replay 场景
|
||||
|
||||
| 场景 | 用途 | 命令来源 | 验证方法 |
|
||||
|------|------|---------|----------|
|
||||
| **重放成功命令** | 验证幂等性 | status=completed | 对比前后结果 |
|
||||
| **重放失败命令** | 测试容错能力 | status=failed | 记录恢复率 |
|
||||
| **批量重放** | 压力测试 | 时间范围或数量 | 性能监控 |
|
||||
| **场景回放** | 测试特定场景 | 命令序列 | 状态验证 |
|
||||
|
||||
---
|
||||
|
||||
## 🏗️ 架构设计
|
||||
|
||||
### 1. 数据模型
|
||||
|
||||
#### replay_sessions 表
|
||||
|
||||
```sql
|
||||
CREATE TABLE replay_sessions (
|
||||
id BIGSERIAL PRIMARY KEY,
|
||||
|
||||
-- Session 信息
|
||||
session_id VARCHAR(36) NOT NULL UNIQUE,
|
||||
session_name VARCHAR(255),
|
||||
replay_type VARCHAR(20) NOT NULL CHECK (
|
||||
replay_type IN ('success', 'failed', 'batch', 'scenario')
|
||||
),
|
||||
|
||||
-- 源命令过滤条件
|
||||
source_filter JSONB NOT NULL DEFAULT '{}',
|
||||
/*
|
||||
{
|
||||
"status": ["completed", "failed"],
|
||||
"job_types": ["register", "unregister"],
|
||||
"time_range": {
|
||||
"start": "2026-10-01T00:00:00Z",
|
||||
"end": "2026-10-11T00:00:00Z"
|
||||
},
|
||||
"limit": 100,
|
||||
"command_ids": ["abc123", "def456"]
|
||||
}
|
||||
*/
|
||||
|
||||
-- 配置
|
||||
config JSONB NOT NULL DEFAULT '{}',
|
||||
/*
|
||||
{
|
||||
"concurrency": 5,
|
||||
"delay_ms": 100,
|
||||
"stop_on_error": false,
|
||||
"compare_results": true,
|
||||
"timeout_secs": 300
|
||||
}
|
||||
*/
|
||||
|
||||
-- 执行状态
|
||||
status VARCHAR(20) NOT NULL DEFAULT 'pending' CHECK (
|
||||
status IN ('pending', 'running', 'paused', 'completed', 'failed', 'cancelled')
|
||||
),
|
||||
|
||||
-- 统计信息
|
||||
total_commands INTEGER DEFAULT 0,
|
||||
processed_commands INTEGER DEFAULT 0,
|
||||
succeeded_commands INTEGER DEFAULT 0,
|
||||
failed_commands INTEGER DEFAULT 0,
|
||||
skipped_commands INTEGER DEFAULT 0,
|
||||
|
||||
-- 结果对比
|
||||
comparison_results JSONB DEFAULT '[]',
|
||||
/*
|
||||
[
|
||||
{
|
||||
"original_command_id": "abc123",
|
||||
"replay_command_id": "xyz789",
|
||||
"status": "match", // match, mismatch, error
|
||||
"original_result": {...},
|
||||
"replay_result": {...},
|
||||
"differences": [...]
|
||||
}
|
||||
]
|
||||
*/
|
||||
|
||||
-- 性能指标
|
||||
started_at TIMESTAMP WITH TIME ZONE,
|
||||
completed_at TIMESTAMP WITH TIME ZONE,
|
||||
duration_secs DOUBLE PRECISION,
|
||||
|
||||
-- 错误信息
|
||||
error_message TEXT,
|
||||
|
||||
-- 时间戳
|
||||
created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
|
||||
updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
|
||||
|
||||
-- 用户信息
|
||||
user_id BIGINT,
|
||||
|
||||
-- 索引
|
||||
FOREIGN KEY (user_id) REFERENCES users(id)
|
||||
);
|
||||
|
||||
CREATE INDEX idx_replay_sessions_status ON replay_sessions (status, created_at);
|
||||
CREATE INDEX idx_replay_sessions_type ON replay_sessions (replay_type, created_at);
|
||||
```
|
||||
|
||||
#### replay_commands 表
|
||||
|
||||
```sql
|
||||
CREATE TABLE replay_commands (
|
||||
id BIGSERIAL PRIMARY KEY,
|
||||
|
||||
-- 关联信息
|
||||
session_id VARCHAR(36) NOT NULL,
|
||||
original_command_id VARCHAR(36) NOT NULL,
|
||||
replay_command_id VARCHAR(36),
|
||||
|
||||
-- 执行状态
|
||||
status VARCHAR(20) NOT NULL DEFAULT 'pending',
|
||||
|
||||
-- 结果对比
|
||||
original_result JSONB,
|
||||
replay_result JSONB,
|
||||
comparison_status VARCHAR(20), -- match, mismatch, error
|
||||
differences JSONB,
|
||||
|
||||
-- 性能指标
|
||||
original_duration_secs DOUBLE PRECISION,
|
||||
replay_duration_secs DOUBLE PRECISION,
|
||||
|
||||
-- 错误信息
|
||||
error_message TEXT,
|
||||
|
||||
-- 时间戳
|
||||
started_at TIMESTAMP WITH TIME ZONE,
|
||||
completed_at TIMESTAMP WITH TIME ZONE,
|
||||
created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
|
||||
|
||||
-- 外键
|
||||
FOREIGN KEY (session_id) REFERENCES replay_sessions(session_id) ON DELETE CASCADE
|
||||
);
|
||||
|
||||
CREATE INDEX idx_replay_commands_session ON replay_commands (session_id);
|
||||
CREATE INDEX idx_replay_commands_status ON replay_commands (status);
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 2. API 设计
|
||||
|
||||
#### 2.1 创建 Replay Session
|
||||
|
||||
```http
|
||||
POST /api/v1/replay/sessions
|
||||
Authorization: Bearer <token>
|
||||
Content-Type: application/json
|
||||
|
||||
{
|
||||
"session_name": "Test idempotency for October registrations",
|
||||
"replay_type": "success", // success, failed, batch, scenario
|
||||
"source_filter": {
|
||||
"status": ["completed"],
|
||||
"job_types": ["register"],
|
||||
"time_range": {
|
||||
"start": "2026-10-01T00:00:00Z",
|
||||
"end": "2026-10-11T00:00:00Z"
|
||||
},
|
||||
"limit": 100
|
||||
},
|
||||
"config": {
|
||||
"concurrency": 5,
|
||||
"delay_ms": 100,
|
||||
"stop_on_error": false,
|
||||
"compare_results": true,
|
||||
"timeout_secs": 300
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**响应**:
|
||||
```json
|
||||
{
|
||||
"success": true,
|
||||
"session": {
|
||||
"session_id": "replay_abc123",
|
||||
"session_name": "Test idempotency for October registrations",
|
||||
"replay_type": "success",
|
||||
"status": "pending",
|
||||
"total_commands": 50,
|
||||
"created_at": "2026-10-11T09:00:00Z"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
#### 2.2 启动 Replay Session
|
||||
|
||||
```http
|
||||
POST /api/v1/replay/sessions/{session_id}/start
|
||||
Authorization: Bearer <token>
|
||||
```
|
||||
|
||||
**响应**:
|
||||
```json
|
||||
{
|
||||
"success": true,
|
||||
"status": "running",
|
||||
"message": "Replay session started"
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
#### 2.3 暂停 Replay Session
|
||||
|
||||
```http
|
||||
POST /api/v1/replay/sessions/{session_id}/pause
|
||||
Authorization: Bearer <token>
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
#### 2.4 恢复 Replay Session
|
||||
|
||||
```http
|
||||
POST /api/v1/replay/sessions/{session_id}/resume
|
||||
Authorization: Bearer <token>
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
#### 2.5 取消 Replay Session
|
||||
|
||||
```http
|
||||
POST /api/v1/replay/sessions/{session_id}/cancel
|
||||
Authorization: Bearer <token>
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
#### 2.6 查询 Replay Session 状态
|
||||
|
||||
```http
|
||||
GET /api/v1/replay/sessions/{session_id}
|
||||
Authorization: Bearer <token>
|
||||
```
|
||||
|
||||
**响应**:
|
||||
```json
|
||||
{
|
||||
"session_id": "replay_abc123",
|
||||
"status": "running",
|
||||
"progress": {
|
||||
"total": 50,
|
||||
"processed": 25,
|
||||
"succeeded": 23,
|
||||
"failed": 2,
|
||||
"percentage": 50.0
|
||||
},
|
||||
"performance": {
|
||||
"started_at": "2026-10-11T09:00:00Z",
|
||||
"elapsed_secs": 120.5,
|
||||
"avg_command_time_secs": 4.82
|
||||
},
|
||||
"comparison": {
|
||||
"match_count": 20,
|
||||
"mismatch_count": 3,
|
||||
"error_count": 2
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
#### 2.7 列出 Replay Sessions
|
||||
|
||||
```http
|
||||
GET /api/v1/replay/sessions?status=completed&limit=20
|
||||
Authorization: Bearer <token>
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
#### 2.8 获取 Replay 结果报告
|
||||
|
||||
```http
|
||||
GET /api/v1/replay/sessions/{session_id}/report
|
||||
Authorization: Bearer <token>
|
||||
```
|
||||
|
||||
**响应**:
|
||||
```json
|
||||
{
|
||||
"session": {
|
||||
"session_id": "replay_abc123",
|
||||
"session_name": "Test idempotency for October registrations",
|
||||
"status": "completed"
|
||||
},
|
||||
|
||||
"summary": {
|
||||
"total_commands": 50,
|
||||
"succeeded": 45,
|
||||
"failed": 3,
|
||||
"skipped": 2,
|
||||
"success_rate": 90.0
|
||||
},
|
||||
|
||||
"comparison": {
|
||||
"match": 40,
|
||||
"mismatch": 5,
|
||||
"error": 3,
|
||||
"match_rate": 80.0
|
||||
},
|
||||
|
||||
"performance": {
|
||||
"total_duration_secs": 241.0,
|
||||
"avg_command_time_secs": 4.82,
|
||||
"commands_per_minute": 12.4
|
||||
},
|
||||
|
||||
"mismatches": [
|
||||
{
|
||||
"original_command_id": "abc123",
|
||||
"replay_command_id": "xyz789",
|
||||
"differences": [
|
||||
{
|
||||
"field": "file_uuid",
|
||||
"original": "384b0ff44aaaa1f1",
|
||||
"replay": "384b0ff44aaaa1f2"
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
|
||||
"errors": [
|
||||
{
|
||||
"command_id": "def456",
|
||||
"error": "File not found"
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 3. Replay 执行流程
|
||||
|
||||
```
|
||||
1. 创建 Session
|
||||
↓
|
||||
2. 查询源命令(根据 filter)
|
||||
↓
|
||||
3. 生成 replay_commands 记录
|
||||
↓
|
||||
4. 启动 Replay Worker
|
||||
↓
|
||||
5. 并发执行重放
|
||||
├── 读取原始命令
|
||||
├── 克隆命令 payload
|
||||
├── 提交到 command_queue
|
||||
├── 等待执行完成
|
||||
├── 对比结果(如果启用)
|
||||
└── 更新 replay_commands 状态
|
||||
↓
|
||||
6. 生成报告
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 4. 幂等性验证
|
||||
|
||||
#### 4.1 结果对比逻辑
|
||||
|
||||
```rust
|
||||
pub struct ResultComparator {
|
||||
compare_fields: Vec<String>, // 要对比的字段
|
||||
ignore_fields: Vec<String>, // 忽略的字段
|
||||
}
|
||||
|
||||
impl ResultComparator {
|
||||
pub fn compare(
|
||||
&self,
|
||||
original: &serde_json::Value,
|
||||
replay: &serde_json::Value,
|
||||
) -> ComparisonResult {
|
||||
let mut differences = Vec::new();
|
||||
|
||||
for field in &self.compare_fields {
|
||||
let orig_val = original.get(field);
|
||||
let replay_val = replay.get(field);
|
||||
|
||||
if orig_val != replay_val {
|
||||
differences.push(Difference {
|
||||
field: field.clone(),
|
||||
original: orig_val.cloned(),
|
||||
replay: replay_val.cloned(),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
ComparisonResult {
|
||||
status: if differences.is_empty() { "match" } else { "mismatch" },
|
||||
differences,
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
#### 4.2 Register 命令幂等性验证
|
||||
|
||||
**关键点**:
|
||||
- ✅ 相同文件路径应返回相同 `file_uuid`
|
||||
- ✅ 第二次注册应标记为 `already_exists=true`
|
||||
- ✅ 不应创建重复记录
|
||||
|
||||
**验证字段**:
|
||||
```json
|
||||
{
|
||||
"compare_fields": [
|
||||
"file_uuid",
|
||||
"file_type",
|
||||
"file_size",
|
||||
"already_exists"
|
||||
],
|
||||
"ignore_fields": [
|
||||
"created_at", // 时间戳必然不同
|
||||
"message" // 提示信息可能不同
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 5. 批量重放配置
|
||||
|
||||
#### 5.1 压力测试配置
|
||||
|
||||
```json
|
||||
{
|
||||
"replay_type": "batch",
|
||||
"source_filter": {
|
||||
"job_types": ["register"],
|
||||
"time_range": {
|
||||
"start": "2026-10-01T00:00:00Z",
|
||||
"end": "2026-10-11T00:00:00Z"
|
||||
},
|
||||
"limit": 1000
|
||||
},
|
||||
"config": {
|
||||
"concurrency": 10, // 高并发
|
||||
"delay_ms": 0, // 无延迟
|
||||
"stop_on_error": false, // 遇错不停
|
||||
"compare_results": false, // 不对比结果
|
||||
"timeout_secs": 600 // 更长超时
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**性能监控**:
|
||||
- 吞吐量(commands/min)
|
||||
- 平均延迟
|
||||
- 错误率
|
||||
- 资源使用(CPU, 内存, GPU)
|
||||
|
||||
---
|
||||
|
||||
### 6. 场景回放
|
||||
|
||||
#### 6.1 定义场景
|
||||
|
||||
```json
|
||||
{
|
||||
"replay_type": "scenario",
|
||||
"session_name": "Test register -> unregister cycle",
|
||||
"source_filter": {
|
||||
"command_sequence": [
|
||||
{
|
||||
"job_type": "register",
|
||||
"file_path": "/test/video1.mp4"
|
||||
},
|
||||
{
|
||||
"job_type": "unregister",
|
||||
"file_path": "/test/video1.mp4"
|
||||
},
|
||||
{
|
||||
"job_type": "register",
|
||||
"file_path": "/test/video1.mp4"
|
||||
}
|
||||
]
|
||||
},
|
||||
"config": {
|
||||
"stop_on_error": true, // 遇错停止
|
||||
"compare_results": true, // 验证每步
|
||||
"validate_state": true // 验证中间状态
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
#### 6.2 状态验证
|
||||
|
||||
```rust
|
||||
// 验证 register 后状态
|
||||
async fn validate_after_register(file_uuid: &str) -> Result<()> {
|
||||
let video = db.get_video(file_uuid).await?;
|
||||
|
||||
assert!(video.is_some(), "Video should exist");
|
||||
assert!(video.unwrap().status == "registered", "Status should be registered");
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// 验证 unregister 后状态
|
||||
async fn validate_after_unregister(file_uuid: &str) -> Result<()> {
|
||||
let video = db.get_video(file_uuid).await?;
|
||||
|
||||
assert!(video.is_none(), "Video should not exist");
|
||||
|
||||
Ok(())
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 7. 错误处理
|
||||
|
||||
#### 7.1 错误分类
|
||||
|
||||
| 错误类型 | 处理方式 | 重试 |
|
||||
|---------|---------|------|
|
||||
| **文件不存在** | 标记为 skipped | ❌ 不重试 |
|
||||
| **权限错误** | 标记为 failed | ❌ 不重试 |
|
||||
| **网络错误** | 自动重试 3 次 | ✅ 重试 |
|
||||
| **超时** | 自动重试 2 次 | ✅ 重试 |
|
||||
| **资源不足** | 等待后重试 | ✅ 重试 |
|
||||
|
||||
#### 7.2 错误记录
|
||||
|
||||
```rust
|
||||
struct ReplayError {
|
||||
command_id: String,
|
||||
error_type: ErrorType,
|
||||
error_message: String,
|
||||
retry_count: u32,
|
||||
timestamp: DateTime<Utc>,
|
||||
|
||||
// 上下文信息
|
||||
context: HashMap<String, String>,
|
||||
}
|
||||
|
||||
// 记录错误
|
||||
async fn record_error(session_id: &str, error: ReplayError) {
|
||||
sqlx::query!(
|
||||
r#"
|
||||
UPDATE replay_commands
|
||||
SET status = 'failed', error_message = $1, completed_at = NOW()
|
||||
WHERE session_id = $2 AND original_command_id = $3
|
||||
"#,
|
||||
error.error_message,
|
||||
session_id,
|
||||
error.command_id,
|
||||
)
|
||||
.execute(&pool)
|
||||
.await?;
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 8. 监控和告警
|
||||
|
||||
#### 8.1 实时监控
|
||||
|
||||
```rust
|
||||
// WebSocket 推送进度
|
||||
pub async fn monitor_replay_progress(
|
||||
session_id: &str,
|
||||
) -> impl Stream<Item = ReplayProgress> {
|
||||
let db = get_db();
|
||||
|
||||
async_stream::stream! {
|
||||
loop {
|
||||
let progress = get_replay_progress(session_id).await?;
|
||||
yield progress;
|
||||
|
||||
if progress.status == "completed" {
|
||||
break;
|
||||
}
|
||||
|
||||
tokio::time::sleep(Duration::from_secs(1)).await;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// GET /api/v1/replay/sessions/{session_id}/stream (WebSocket)
|
||||
```
|
||||
|
||||
#### 8.2 告警规则
|
||||
|
||||
| 指标 | 阈值 | 告警级别 |
|
||||
|------|------|---------|
|
||||
| 失败率 | > 10% | 🟡 Warning |
|
||||
| 失败率 | > 30% | 🔴 Critical |
|
||||
| 不匹配率 | > 20% | 🟡 Warning |
|
||||
| 不匹配率 | > 50% | 🔴 Critical |
|
||||
| 平均延迟 | > 10s | 🟡 Warning |
|
||||
|
||||
---
|
||||
|
||||
## 🎯 使用示例
|
||||
|
||||
### 示例 1: 验证幂等性
|
||||
|
||||
```bash
|
||||
# 创建 replay session
|
||||
curl -X POST http://localhost:3002/api/v1/replay/sessions \
|
||||
-H "Authorization: Bearer $API_KEY" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{
|
||||
"session_name": "Verify register idempotency",
|
||||
"replay_type": "success",
|
||||
"source_filter": {
|
||||
"status": ["completed"],
|
||||
"job_types": ["register"],
|
||||
"limit": 100
|
||||
},
|
||||
"config": {
|
||||
"compare_results": true
|
||||
}
|
||||
}'
|
||||
|
||||
# 启动 replay
|
||||
curl -X POST http://localhost:3002/api/v1/replay/sessions/replay_abc123/start \
|
||||
-H "Authorization: Bearer $API_KEY"
|
||||
|
||||
# 查看报告
|
||||
curl http://localhost:3002/api/v1/replay/sessions/replay_abc123/report \
|
||||
-H "Authorization: Bearer $API_KEY"
|
||||
```
|
||||
|
||||
### 示例 2: 压力测试
|
||||
|
||||
```bash
|
||||
curl -X POST http://localhost:3002/api/v1/replay/sessions \
|
||||
-H "Authorization: Bearer $API_KEY" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{
|
||||
"session_name": "Stress test - 1000 commands",
|
||||
"replay_type": "batch",
|
||||
"source_filter": {
|
||||
"limit": 1000
|
||||
},
|
||||
"config": {
|
||||
"concurrency": 10,
|
||||
"delay_ms": 0,
|
||||
"compare_results": false
|
||||
}
|
||||
}'
|
||||
```
|
||||
|
||||
### 示例 3: 容错测试
|
||||
|
||||
```bash
|
||||
curl -X POST http://localhost:3002/api/v1/replay/sessions \
|
||||
-H "Authorization: Bearer $API_KEY" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{
|
||||
"session_name": "Test recovery from failed commands",
|
||||
"replay_type": "failed",
|
||||
"source_filter": {
|
||||
"status": ["failed"]
|
||||
},
|
||||
"config": {
|
||||
"stop_on_error": false
|
||||
}
|
||||
}'
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 📊 数据库迁移
|
||||
|
||||
```sql
|
||||
-- migrations/20261011_replay_system.sql
|
||||
|
||||
CREATE TABLE replay_sessions (
|
||||
-- (如上定义)
|
||||
);
|
||||
|
||||
CREATE TABLE replay_commands (
|
||||
-- (如上定义)
|
||||
);
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 🚀 实施计划
|
||||
|
||||
### Phase 1: 基础功能 (1 周)
|
||||
|
||||
- [ ] 创建数据库表
|
||||
- [ ] 实现 Replay Session 管理 API
|
||||
- [ ] 实现 Replay Worker
|
||||
- [ ] 基础结果对比
|
||||
|
||||
### Phase 2: 高级功能 (1 周)
|
||||
|
||||
- [ ] 幂等性验证
|
||||
- [ ] 批量重放优化
|
||||
- [ ] 场景回放
|
||||
- [ ] 监控和告警
|
||||
|
||||
### Phase 3: 报告和可视化 (3 天)
|
||||
|
||||
- [ ] 详细报告生成
|
||||
- [ ] WebSocket 实时监控
|
||||
- [ ] Web UI (可选)
|
||||
|
||||
---
|
||||
|
||||
## 📝 注意事项
|
||||
|
||||
### 安全考虑
|
||||
|
||||
1. **权限控制**: 只有管理员可以执行 Replay
|
||||
2. **资源限制**: 限制并发数,避免系统过载
|
||||
3. **数据隔离**: Replay 不影响生产数据
|
||||
4. **审计日志**: 记录所有 Replay 操作
|
||||
|
||||
### 性能考虑
|
||||
|
||||
1. **批量查询**: 避免频繁查询数据库
|
||||
2. **并发控制**: 动态调整并发数
|
||||
3. **资源监控**: 监控系统资源,避免过载
|
||||
4. **背压机制**: 当队列过长时自动降速
|
||||
|
||||
---
|
||||
|
||||
**设计完成,准备实施!**
|
||||
@@ -0,0 +1,227 @@
|
||||
---
|
||||
title: Rust Store Traced Faces 設計文檔
|
||||
version: 1.0
|
||||
date: 2026-09-27
|
||||
author: OpenCode
|
||||
status: design
|
||||
---
|
||||
|
||||
## 設計目標
|
||||
|
||||
實現 Rust 版本的 `store_traced_faces`,替換 Python 腳本。
|
||||
|
||||
---
|
||||
|
||||
## 功能需求
|
||||
|
||||
### 輸入
|
||||
|
||||
- `file_uuid`: Video file UUID
|
||||
- `face.json`: Face detection results
|
||||
|
||||
---
|
||||
|
||||
### 輸出
|
||||
|
||||
- `face_traced.json`: Face data with trace_id
|
||||
- PostgreSQL: Update `face_detections.trace_id`
|
||||
- Qdrant: Update `_faces.trace_id`
|
||||
|
||||
---
|
||||
|
||||
## 架構設計
|
||||
|
||||
### 依賴關係
|
||||
|
||||
```
|
||||
rust_store_traced_faces
|
||||
├── face_tracker (調用或集成)
|
||||
├── PostgreSQL (sqlx)
|
||||
└── Qdrant (qdrant-client)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 模塊設計
|
||||
|
||||
#### 1. FaceTracker
|
||||
|
||||
**功能**: Face tracking (IoU + embedding)
|
||||
|
||||
**選項**:
|
||||
- A. 調用 Python `face_tracker.py`
|
||||
- B. 集成 Rust face tracking 邏輯
|
||||
|
||||
**建議**: 先使用 A (調用 Python),後續優化為 B
|
||||
|
||||
---
|
||||
|
||||
#### 2. TracedFacesStore
|
||||
|
||||
**功能**: 存儲 traced faces
|
||||
|
||||
**操作**:
|
||||
- 寫入 `face_traced.json`
|
||||
- 更新 PostgreSQL
|
||||
- 更新 Qdrant
|
||||
|
||||
---
|
||||
|
||||
#### 3. TraceFilter
|
||||
|
||||
**功能**: 過濾低質量 traces
|
||||
|
||||
**參數**:
|
||||
- `min_trace_len`: 最小 trace 長度
|
||||
- `min_confidence`: 最小置信度
|
||||
|
||||
---
|
||||
|
||||
## CLI 設計
|
||||
|
||||
### Usage
|
||||
|
||||
```bash
|
||||
rust_store_traced_faces <file_uuid> [options]
|
||||
|
||||
Options:
|
||||
--face-json <path> Face JSON path (default: from OUTPUT_DIR)
|
||||
--min-trace-len <n> Minimum trace length
|
||||
--min-confidence <f> Minimum average confidence
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Output
|
||||
|
||||
```
|
||||
[TRACE_STORE] Processing file: {file_uuid}
|
||||
[TRACE_STORE] Running face tracker...
|
||||
[TRACE_STORE] Traces: {count}
|
||||
[TRACE_STORE] Updating PostgreSQL...
|
||||
[TRACE_STORE] Updated {count} face_detections
|
||||
[TRACE_STORE] Updating Qdrant...
|
||||
[TRACE_STORE] Updated {count} _faces
|
||||
[TRACE_STORE] Writing face_traced.json...
|
||||
[TRACE_STORE] Done
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 實現步驟
|
||||
|
||||
### Phase 1: 基礎實現
|
||||
|
||||
1. 創建 CLI 框架
|
||||
2. 讀取 `face.json`
|
||||
3. 調用 `face_tracker.py`
|
||||
4. 寫入 `face_traced.json`
|
||||
|
||||
---
|
||||
|
||||
### Phase 2: 數據庫整合
|
||||
|
||||
1. PostgreSQL 更新邏輯
|
||||
2. Qdrant 更新邏輯
|
||||
3. 事務處理
|
||||
|
||||
---
|
||||
|
||||
### Phase 3: 優化
|
||||
|
||||
1. 集成 Rust face tracking
|
||||
2. 性能優化
|
||||
3. 錯誤處理
|
||||
|
||||
---
|
||||
|
||||
## 配置整合
|
||||
|
||||
### processor_tools.json
|
||||
|
||||
```json
|
||||
{
|
||||
"face_trace": {
|
||||
"tools": [
|
||||
{
|
||||
"name": "rust",
|
||||
"priority": 0,
|
||||
"enabled": true
|
||||
},
|
||||
{
|
||||
"name": "python",
|
||||
"priority": 1,
|
||||
"enabled": false
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### ToolSelector 支持
|
||||
|
||||
```rust
|
||||
("face_trace", "rust") => {
|
||||
executor.rust_binary_path("rust_store_traced_faces")
|
||||
}
|
||||
("face_trace", "python") => {
|
||||
let script = executor.script_path("store_traced_faces.py");
|
||||
if script.exists() { Some(script) } else { None }
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 與 Python 版本對比
|
||||
|
||||
| 功能 | Python | Rust |
|
||||
|------|--------|------|
|
||||
| Face tracking | 調用 face_tracker.py | 同樣 (Phase 1) |
|
||||
| PostgreSQL | psycopg2 | sqlx |
|
||||
| Qdrant | qdrant-client | qdrant-client |
|
||||
| JSON 處理 | json | serde_json |
|
||||
| 性能 | 中 | **高** |
|
||||
| 依賴 | Python 環境 | **獨立 binary** |
|
||||
|
||||
---
|
||||
|
||||
## 測試計劃
|
||||
|
||||
### 單元測試
|
||||
|
||||
- Face JSON 解析
|
||||
- Trace filtering
|
||||
- JSON 輸出格式
|
||||
|
||||
---
|
||||
|
||||
### 集成測試
|
||||
|
||||
- PostgreSQL 更新
|
||||
- Qdrant 更新
|
||||
- 完整流程
|
||||
|
||||
---
|
||||
|
||||
## 預期效果
|
||||
|
||||
### 性能提升
|
||||
|
||||
- **速度**: 2-3x 更快
|
||||
- **內存**: 更少佔用
|
||||
- **可靠性**: 無 Python 環境依賴
|
||||
|
||||
---
|
||||
|
||||
### 運維優勢
|
||||
|
||||
- **部署**: 單一 binary
|
||||
- **配置**: 統一配置系統
|
||||
- **監控**: 統一日誌格式
|
||||
|
||||
---
|
||||
|
||||
**設計日期**: 2026-09-27
|
||||
**狀態**: 📝 **設計完成,待實現**
|
||||
@@ -0,0 +1,706 @@
|
||||
# MarkBase Search Messenger 设计
|
||||
|
||||
**版本**: 1.0
|
||||
**日期**: 2026-10-11
|
||||
**状态**: 设计规范
|
||||
|
||||
---
|
||||
|
||||
## 🎯 设计目标
|
||||
|
||||
将 Studio 的 Search 介面定位为 **Messenger 的变形**,通过统一的消息传递机制实现搜索功能。
|
||||
|
||||
---
|
||||
|
||||
## 🏗️ 架构设计
|
||||
|
||||
### 核心理念
|
||||
|
||||
```
|
||||
Search Request → Messenger Queue → Search Worker → Messenger Response
|
||||
```
|
||||
|
||||
Search 不是独立的 API,而是 **Messenger 的一个特定应用场景**。
|
||||
|
||||
---
|
||||
|
||||
## 📊 Search 消息类型
|
||||
|
||||
### 1. Search Request Message
|
||||
|
||||
```rust
|
||||
// MarkBase Queue Protocol - Independent Implementation
|
||||
// This is NOT compatible with Apache Kafka protocol or API.
|
||||
|
||||
use chrono::{DateTime, Utc};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::Value as JsonValue;
|
||||
use crate::core::command::messenger::types::{Message, MessageType, MessageSource, MessagePriority};
|
||||
|
||||
/// Search 类型
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum SearchType {
|
||||
/// 关键词搜索
|
||||
Keyword,
|
||||
/// 语义搜索
|
||||
Semantic,
|
||||
/// 混合搜索
|
||||
Hybrid,
|
||||
/// 人物搜索
|
||||
People,
|
||||
/// 场景搜索
|
||||
Scene,
|
||||
/// 时间范围搜索
|
||||
TimeRange,
|
||||
/// 自定义搜索
|
||||
Custom,
|
||||
}
|
||||
|
||||
/// Search 请求
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct SearchRequest {
|
||||
pub query: String,
|
||||
pub search_type: SearchType,
|
||||
pub filters: SearchFilters,
|
||||
pub options: SearchOptions,
|
||||
}
|
||||
|
||||
/// Search 过滤器
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
|
||||
pub struct SearchFilters {
|
||||
pub file_uuids: Option<Vec<String>>,
|
||||
pub date_range: Option<DateRange>,
|
||||
pub tags: Option<Vec<String>>,
|
||||
pub identities: Option<Vec<String>>,
|
||||
pub locations: Option<Vec<String>>,
|
||||
pub custom: Option<JsonValue>,
|
||||
}
|
||||
|
||||
/// Search 选项
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
|
||||
pub struct SearchOptions {
|
||||
pub limit: Option<i32>,
|
||||
pub offset: Option<i32>,
|
||||
pub include_metadata: Option<bool>,
|
||||
pub include_thumbnails: Option<bool>,
|
||||
pub sort_by: Option<String>,
|
||||
pub sort_order: Option<String>,
|
||||
pub highlight: Option<bool>,
|
||||
pub explain: Option<bool>,
|
||||
}
|
||||
|
||||
/// 日期范围
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct DateRange {
|
||||
pub start: DateTime<Utc>,
|
||||
pub end: DateTime<Utc>,
|
||||
}
|
||||
|
||||
/// Search 响应
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct SearchResponse {
|
||||
pub request_id: String,
|
||||
pub query: String,
|
||||
pub search_type: SearchType,
|
||||
pub results: Vec<SearchResult>,
|
||||
pub total_count: i64,
|
||||
pub took_ms: i64,
|
||||
pub facets: Option<JsonValue>,
|
||||
pub suggestions: Option<Vec<String>>,
|
||||
}
|
||||
|
||||
/// Search 结果
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct SearchResult {
|
||||
pub id: String,
|
||||
pub score: f64,
|
||||
pub file_uuid: String,
|
||||
pub timestamp: Option<f64>,
|
||||
pub duration: Option<f64>,
|
||||
pub snippet: Option<String>,
|
||||
pub highlights: Option<Vec<Highlight>>,
|
||||
pub metadata: Option<JsonValue>,
|
||||
pub thumbnail: Option<String>,
|
||||
}
|
||||
|
||||
/// 高亮
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct Highlight {
|
||||
pub field: String,
|
||||
pub fragments: Vec<String>,
|
||||
}
|
||||
|
||||
impl SearchRequest {
|
||||
pub fn new(query: String, search_type: SearchType) -> Self {
|
||||
Self {
|
||||
query,
|
||||
search_type,
|
||||
filters: SearchFilters::default(),
|
||||
options: SearchOptions::default(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn with_filters(mut self, filters: SearchFilters) -> Self {
|
||||
self.filters = filters;
|
||||
self
|
||||
}
|
||||
|
||||
pub fn with_options(mut self, options: SearchOptions) -> Self {
|
||||
self.options = options;
|
||||
self
|
||||
}
|
||||
|
||||
/// 转换为 Messenger Message
|
||||
pub fn to_message(&self, source: MessageSource) -> Message {
|
||||
Message::new(
|
||||
MessageType::Command,
|
||||
source,
|
||||
serde_json::to_value(self).unwrap(),
|
||||
)
|
||||
.with_priority(MessagePriority::High)
|
||||
.with_metadata("search_type".to_string(), serde_json::to_string(&self.search_type).unwrap())
|
||||
}
|
||||
}
|
||||
|
||||
impl SearchResponse {
|
||||
/// 从 Message 解析
|
||||
pub fn from_message(message: &Message) -> Result<Self, serde_json::Error> {
|
||||
serde_json::from_value(message.payload.clone())
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 2. Search Messenger Service
|
||||
|
||||
```rust
|
||||
// MarkBase Queue Protocol - Independent Implementation
|
||||
// This is NOT compatible with Apache Kafka protocol or API.
|
||||
|
||||
use super::types::*;
|
||||
use crate::core::command::messenger::Messenger;
|
||||
use crate::core::command::error::{CommandError, CommandResult};
|
||||
use crate::core::command::messenger::types::{MessageSource, DeliveryOptions};
|
||||
use serde_json::json;
|
||||
use sqlx::PgPool;
|
||||
use std::time::Instant;
|
||||
use tracing::{debug, info};
|
||||
|
||||
/// Search Messenger 服务
|
||||
pub struct SearchMessenger {
|
||||
messenger: Messenger,
|
||||
}
|
||||
|
||||
impl SearchMessenger {
|
||||
pub fn new(db: PgPool) -> Self {
|
||||
Self {
|
||||
messenger: Messenger::new(db),
|
||||
}
|
||||
}
|
||||
|
||||
/// 提交搜索请求
|
||||
pub async fn search(
|
||||
&self,
|
||||
request: SearchRequest,
|
||||
user_id: Option<String>,
|
||||
api_key: Option<String>,
|
||||
) -> CommandResult<String> {
|
||||
let source = MessageSource::Api {
|
||||
endpoint: "/api/v1/search".to_string(),
|
||||
method: "POST".to_string(),
|
||||
};
|
||||
|
||||
let mut message = request.to_message(source);
|
||||
|
||||
if let Some(uid) = user_id {
|
||||
message = message.with_metadata("user_id".to_string(), uid);
|
||||
}
|
||||
|
||||
if let Some(key) = api_key {
|
||||
message = message.with_metadata("api_key".to_string(), key);
|
||||
}
|
||||
|
||||
let options = DeliveryOptions {
|
||||
persistent: true,
|
||||
ttl_seconds: Some(300), // 5分钟 TTL
|
||||
require_ack: true,
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
self.messenger.send("search.requests", message, options).await
|
||||
}
|
||||
|
||||
/// 获取搜索结果
|
||||
pub async fn get_result(&self, request_id: &str) -> CommandResult<Option<SearchResponse>> {
|
||||
let messages = self.messenger.receive(
|
||||
"search.results",
|
||||
&format!("search_waiter_{}", request_id),
|
||||
1,
|
||||
30000, // 30秒超时
|
||||
).await?;
|
||||
|
||||
if let Some(message) = messages.first() {
|
||||
let response = SearchResponse::from_message(message)?;
|
||||
self.messenger.acknowledge(&message.message_id, &format!("search_waiter_{}", request_id)).await?;
|
||||
return Ok(Some(response));
|
||||
}
|
||||
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
/// 执行搜索(同步)
|
||||
pub async fn execute_search(
|
||||
&self,
|
||||
request: SearchRequest,
|
||||
user_id: Option<String>,
|
||||
api_key: Option<String>,
|
||||
) -> CommandResult<SearchResponse> {
|
||||
let start = Instant::now();
|
||||
|
||||
// 提交请求
|
||||
let request_id = self.search(request.clone(), user_id, api_key).await?;
|
||||
|
||||
// 等待结果
|
||||
let timeout = request.options.limit.unwrap_or(30) as u64 * 1000;
|
||||
let deadline = Instant::now() + std::time::Duration::from_millis(timeout);
|
||||
|
||||
loop {
|
||||
if Instant::now() > deadline {
|
||||
return Err(CommandError::Timeout(timeout as i32));
|
||||
}
|
||||
|
||||
if let Some(response) = self.get_result(&request_id).await? {
|
||||
debug!(
|
||||
request_id = %request_id,
|
||||
took_ms = start.elapsed().as_millis(),
|
||||
"Search completed"
|
||||
);
|
||||
return Ok(response);
|
||||
}
|
||||
|
||||
tokio::time::sleep(std::time::Duration::from_millis(100)).await;
|
||||
}
|
||||
}
|
||||
|
||||
/// 取消搜索
|
||||
pub async fn cancel(&self, request_id: &str) -> CommandResult<()> {
|
||||
let message = crate::core::command::messenger::types::Message::new(
|
||||
crate::core::command::messenger::types::MessageType::Command,
|
||||
MessageSource::System {
|
||||
component: "search_service".to_string(),
|
||||
},
|
||||
json!({
|
||||
"action": "cancel",
|
||||
"request_id": request_id,
|
||||
}),
|
||||
)
|
||||
.with_priority(crate::core::command::messenger::types::MessagePriority::High);
|
||||
|
||||
self.messenger.send(
|
||||
"search.control",
|
||||
message,
|
||||
DeliveryOptions::default(),
|
||||
).await?;
|
||||
|
||||
info!(request_id = %request_id, "Search cancelled");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// 批量搜索
|
||||
pub async fn batch_search(
|
||||
&self,
|
||||
requests: Vec<SearchRequest>,
|
||||
user_id: Option<String>,
|
||||
api_key: Option<String>,
|
||||
) -> CommandResult<Vec<String>> {
|
||||
let mut request_ids = Vec::new();
|
||||
|
||||
for request in requests {
|
||||
let id = self.search(request, user_id.clone(), api_key.clone()).await?;
|
||||
request_ids.push(id);
|
||||
}
|
||||
|
||||
info!(count = request_ids.len(), "Batch search submitted");
|
||||
Ok(request_ids)
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 3. Search Worker
|
||||
|
||||
```rust
|
||||
// MarkBase Queue Protocol - Independent Implementation
|
||||
// This is NOT compatible with Apache Kafka protocol or API.
|
||||
|
||||
use super::types::*;
|
||||
use crate::core::command::messenger::Messenger;
|
||||
use crate::core::command::error::CommandResult;
|
||||
use crate::core::command::messenger::types::{Message, MessageSource, DeliveryOptions};
|
||||
use crate::core::db::{PostgresDb, QdrantDb};
|
||||
use std::time::Instant;
|
||||
use tracing::{debug, error, info};
|
||||
|
||||
/// Search Worker
|
||||
pub struct SearchWorker {
|
||||
messenger: Messenger,
|
||||
db: PostgresDb,
|
||||
vector_db: QdrantDb,
|
||||
worker_id: String,
|
||||
}
|
||||
|
||||
impl SearchWorker {
|
||||
pub fn new(db_pool: sqlx::PgPool, db: PostgresDb, vector_db: QdrantDb) -> Self {
|
||||
Self {
|
||||
messenger: Messenger::new(db_pool),
|
||||
db,
|
||||
vector_db,
|
||||
worker_id: uuid::Uuid::new_v4().to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
/// 启动 Worker
|
||||
pub async fn start(&self) -> CommandResult<()> {
|
||||
info!(worker_id = %self.worker_id, "Search worker started");
|
||||
|
||||
loop {
|
||||
match self.process_requests().await {
|
||||
Ok(count) => {
|
||||
debug!(count = count, "Processed search requests");
|
||||
}
|
||||
Err(e) => {
|
||||
error!(error = ?e, "Error processing search requests");
|
||||
}
|
||||
}
|
||||
|
||||
tokio::time::sleep(std::time::Duration::from_millis(100)).await;
|
||||
}
|
||||
}
|
||||
|
||||
/// 处理搜索请求
|
||||
async fn process_requests(&self) -> CommandResult<usize> {
|
||||
let messages = self.messenger.receive(
|
||||
"search.requests",
|
||||
&self.worker_id,
|
||||
10,
|
||||
5000,
|
||||
).await?;
|
||||
|
||||
let count = messages.len();
|
||||
|
||||
for message in messages {
|
||||
if let Err(e) = self.handle_search(message).await {
|
||||
error!(error = ?e, "Error handling search message");
|
||||
}
|
||||
}
|
||||
|
||||
Ok(count)
|
||||
}
|
||||
|
||||
/// 处理单个搜索
|
||||
async fn handle_search(&self, message: Message) -> CommandResult<()> {
|
||||
let start = Instant::now();
|
||||
let request: SearchRequest = serde_json::from_value(message.payload.clone())?;
|
||||
|
||||
debug!(
|
||||
request_id = %message.message_id,
|
||||
query = %request.query,
|
||||
type = ?request.search_type,
|
||||
"Processing search request"
|
||||
);
|
||||
|
||||
// 执行搜索
|
||||
let response = self.execute_search(&request, &message.message_id).await?;
|
||||
|
||||
// 发送结果
|
||||
self.send_result(response, &message.message_id).await?;
|
||||
|
||||
// 确认消息
|
||||
self.messenger.acknowledge(&message.message_id, &self.worker_id).await?;
|
||||
|
||||
info!(
|
||||
request_id = %message.message_id,
|
||||
took_ms = start.elapsed().as_millis(),
|
||||
"Search request completed"
|
||||
);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// 执行搜索逻辑
|
||||
async fn execute_search(
|
||||
&self,
|
||||
request: &SearchRequest,
|
||||
request_id: &str,
|
||||
) -> CommandResult<SearchResponse> {
|
||||
let start = Instant::now();
|
||||
|
||||
let results = match request.search_type {
|
||||
SearchType::Keyword => self.keyword_search(request).await?,
|
||||
SearchType::Semantic => self.semantic_search(request).await?,
|
||||
SearchType::Hybrid => self.hybrid_search(request).await?,
|
||||
SearchType::People => self.people_search(request).await?,
|
||||
SearchType::Scene => self.scene_search(request).await?,
|
||||
SearchType::TimeRange => self.time_range_search(request).await?,
|
||||
SearchType::Custom => self.custom_search(request).await?,
|
||||
};
|
||||
|
||||
Ok(SearchResponse {
|
||||
request_id: request_id.to_string(),
|
||||
query: request.query.clone(),
|
||||
search_type: request.search_type.clone(),
|
||||
results,
|
||||
total_count: results.len() as i64,
|
||||
took_ms: start.elapsed().as_millis() as i64,
|
||||
facets: None,
|
||||
suggestions: None,
|
||||
})
|
||||
}
|
||||
|
||||
/// 发送结果
|
||||
async fn send_result(&self, response: SearchResponse, request_id: &str) -> CommandResult<()> {
|
||||
let message = crate::core::command::messenger::types::Message::new(
|
||||
crate::core::command::messenger::types::MessageType::Event,
|
||||
MessageSource::Worker {
|
||||
worker_id: self.worker_id.clone(),
|
||||
worker_type: "search".to_string(),
|
||||
},
|
||||
serde_json::to_value(&response)?,
|
||||
)
|
||||
.with_metadata("request_id".to_string(), request_id.to_string());
|
||||
|
||||
let options = DeliveryOptions {
|
||||
persistent: true,
|
||||
ttl_seconds: Some(3600), // 1小时
|
||||
require_ack: false,
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
self.messenger.send("search.results", message, options).await?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// 具体搜索方法实现...
|
||||
async fn keyword_search(&self, request: &SearchRequest) -> CommandResult<Vec<SearchResult>> {
|
||||
// 实现 BM25 关键词搜索
|
||||
todo!()
|
||||
}
|
||||
|
||||
async fn semantic_search(&self, request: &SearchRequest) -> CommandResult<Vec<SearchResult>> {
|
||||
// 实现向量语义搜索
|
||||
todo!()
|
||||
}
|
||||
|
||||
async fn hybrid_search(&self, request: &SearchRequest) -> CommandResult<Vec<SearchResult>> {
|
||||
// 实现混合搜索
|
||||
todo!()
|
||||
}
|
||||
|
||||
async fn people_search(&self, request: &SearchRequest) -> CommandResult<Vec<SearchResult>> {
|
||||
// 实现人物搜索
|
||||
todo!()
|
||||
}
|
||||
|
||||
async fn scene_search(&self, request: &SearchRequest) -> CommandResult<Vec<SearchResult>> {
|
||||
// 实现场景搜索
|
||||
todo!()
|
||||
}
|
||||
|
||||
async fn time_range_search(&self, request: &SearchRequest) -> CommandResult<Vec<SearchResult>> {
|
||||
// 实现时间范围搜索
|
||||
todo!()
|
||||
}
|
||||
|
||||
async fn custom_search(&self, request: &SearchRequest) -> CommandResult<Vec<SearchResult>> {
|
||||
// 实现自定义搜索
|
||||
todo!()
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 🔄 工作流程
|
||||
|
||||
### 1. 同步搜索
|
||||
|
||||
```
|
||||
Studio UI → API Server → SearchMessenger.search()
|
||||
↓
|
||||
send to "search.requests"
|
||||
↓
|
||||
Search Worker receives
|
||||
↓
|
||||
Execute search
|
||||
↓
|
||||
send to "search.results"
|
||||
↓
|
||||
SearchMessenger.get_result()
|
||||
↓
|
||||
Return to Studio UI
|
||||
```
|
||||
|
||||
### 2. 异步搜索
|
||||
|
||||
```
|
||||
Studio UI → API Server → SearchMessenger.search()
|
||||
↓
|
||||
Return request_id
|
||||
|
||||
(Background)
|
||||
Search Worker processes → Sends result to "search.results"
|
||||
|
||||
Studio UI polls → API Server → SearchMessenger.get_result()
|
||||
↓
|
||||
Return result when ready
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 💡 设计优势
|
||||
|
||||
### 1. 统一架构
|
||||
- ✅ Search 是 Messenger 的变形,不是独立系统
|
||||
- ✅ 复用消息传递、队列管理、错误处理机制
|
||||
- ✅ 统一的监控和日志
|
||||
|
||||
### 2. 可扩展性
|
||||
- ✅ 多个 Search Worker 并行处理
|
||||
- ✅ 按类型分片处理(keyword, semantic, hybrid)
|
||||
- ✅ 负载均衡
|
||||
|
||||
### 3. 可靠性
|
||||
- ✅ 消息持久化
|
||||
- ✅ 重试机制
|
||||
- ✅ 超时处理
|
||||
|
||||
### 4. 异步支持
|
||||
- ✅ 同步搜索(等待结果)
|
||||
- ✅ 异步搜索(立即返回 request_id)
|
||||
- ✅ 批量搜索
|
||||
|
||||
---
|
||||
|
||||
## 📊 队列配置
|
||||
|
||||
### Queue Names
|
||||
|
||||
| Queue | 用途 | 优先级 | TTL |
|
||||
|-------|------|--------|-----|
|
||||
| `search.requests` | 搜索请求 | High | 5分钟 |
|
||||
| `search.results` | 搜索结果 | Normal | 1小时 |
|
||||
| `search.control` | 控制命令(取消、暂停) | Critical | 1分钟 |
|
||||
|
||||
### Priority Distribution
|
||||
|
||||
```
|
||||
Search Requests:
|
||||
- P0 (Critical): 实时搜索(用户等待)
|
||||
- P1 (High): 批量搜索
|
||||
- P2 (Normal): 后台索引
|
||||
- P3 (Low): 分析任务
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 🔌 API 设计
|
||||
|
||||
### REST API
|
||||
|
||||
```rust
|
||||
// POST /api/v1/search
|
||||
pub async fn search_endpoint(
|
||||
Extension(search_messenger): Extension<Arc<SearchMessenger>>,
|
||||
Extension(auth): Extension<UserAuth>,
|
||||
Json(request): Json<SearchRequest>,
|
||||
) -> Result<Json<SearchResponse>, APIError> {
|
||||
let response = search_messenger
|
||||
.execute_search(request, Some(auth.user_id.clone()), Some(auth.key_id.clone()))
|
||||
.await?;
|
||||
|
||||
Ok(Json(response))
|
||||
}
|
||||
|
||||
// POST /api/v1/search/async
|
||||
pub async fn search_async_endpoint(
|
||||
Extension(search_messenger): Extension<Arc<SearchMessenger>>,
|
||||
Extension(auth): Extension<UserAuth>,
|
||||
Json(request): Json<SearchRequest>,
|
||||
) -> Result<Json<AsyncSearchResponse>, APIError> {
|
||||
let request_id = search_messenger
|
||||
.search(request, Some(auth.user_id.clone()), Some(auth.key_id.clone()))
|
||||
.await?;
|
||||
|
||||
Ok(Json(AsyncSearchResponse {
|
||||
request_id,
|
||||
status: "processing".to_string(),
|
||||
message: "Search request submitted".to_string(),
|
||||
}))
|
||||
}
|
||||
|
||||
// GET /api/v1/search/results/{request_id}
|
||||
pub async fn get_search_result(
|
||||
Path(request_id): Path<String>,
|
||||
Extension(search_messenger): Extension<Arc<SearchMessenger>>,
|
||||
) -> Result<Json<Option<SearchResponse>>, APIError> {
|
||||
let result = search_messenger.get_result(&request_id).await?;
|
||||
Ok(Json(result))
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 📈 监控指标
|
||||
|
||||
```rust
|
||||
lazy_static! {
|
||||
static ref SEARCH_REQUESTS_TOTAL: CounterVec = register_counter_vec!(
|
||||
"search_requests_total",
|
||||
"Total search requests",
|
||||
&["type", "status"]
|
||||
).unwrap();
|
||||
|
||||
static ref SEARCH_LATENCY: HistogramVec = register_histogram_vec!(
|
||||
"search_latency_seconds",
|
||||
"Search latency in seconds",
|
||||
&["type"]
|
||||
).unwrap();
|
||||
|
||||
static ref SEARCH_QUEUE_LENGTH: GaugeVec = register_gauge_vec!(
|
||||
"search_queue_length",
|
||||
"Search queue length",
|
||||
&["queue"]
|
||||
).unwrap();
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 🎯 实施计划
|
||||
|
||||
### Phase 1: 基础实现(2 天)
|
||||
|
||||
- [ ] 实现 SearchMessenger
|
||||
- [ ] 实现 SearchWorker
|
||||
- [ ] 实现 API 端点
|
||||
- [ ] 单元测试
|
||||
|
||||
### Phase 2: 集成(1 天)
|
||||
|
||||
- [ ] 集成到 Studio UI
|
||||
- [ ] 集成 Billing
|
||||
- [ ] 集成 Log
|
||||
|
||||
### Phase 3: 优化(1 天)
|
||||
|
||||
- [ ] 性能测试
|
||||
- [ ] 负载测试
|
||||
- [ ] 监控配置
|
||||
|
||||
---
|
||||
|
||||
**Search 作为 Messenger 变形的设计完成!统一架构,易于扩展。**
|
||||
@@ -0,0 +1,285 @@
|
||||
# MarkBase Search 命名规范
|
||||
|
||||
**日期**: 2026-10-11
|
||||
**状态**: 正式规范
|
||||
|
||||
---
|
||||
|
||||
## 📝 命名规范
|
||||
|
||||
### 顶层介面
|
||||
|
||||
**正式名称**: **Agent Search**
|
||||
|
||||
**全称**: Agent Search Service (统一智能搜尋介面)
|
||||
|
||||
**API 路径**: `/api/v1/agent/search`
|
||||
|
||||
**定位**:
|
||||
- 统一智能搜索入口
|
||||
- 用户无需选择搜索类型
|
||||
- Query Analyzer 自动路由
|
||||
- 支持单一或混合搜索策略
|
||||
|
||||
---
|
||||
|
||||
### 底层搜索类型(保持不变)
|
||||
|
||||
Agent Search 内部调用以下 5 种搜索类型:
|
||||
|
||||
| 名称 | 技术栈 | 队列名称 | Worker |
|
||||
|------|--------|----------|--------|
|
||||
| **Keyword** | BM25 + FTS | `search.keyword` | KeywordSearchWorker |
|
||||
| **Semantic** | Vector Embedding | `search.semantic` | SemanticSearchWorker |
|
||||
| **Visual** | VLM + CLIP | `search.visual` | VisualSearchWorker |
|
||||
| **Agent** | LLM + RAG | `search.agent` | AgentSearchWorker |
|
||||
| **People** | Face Identity | `search.people` | PeopleSearchWorker |
|
||||
|
||||
---
|
||||
|
||||
## 🏗️ 架构层次
|
||||
|
||||
```
|
||||
┌─────────────────────────────────────────────────┐
|
||||
│ Agent Search (统一智能搜尋介面) │
|
||||
│ ┌──────────────────────────────────────────┐ │
|
||||
│ │ Query Analyzer (智能路由) │ │
|
||||
│ │ - 分析查询意图 │ │
|
||||
│ │ - 选择搜索类型 │ │
|
||||
│ │ - 生成搜索策略 │ │
|
||||
│ └──────────────────────────────────────────┘ │
|
||||
│ ┌──────────────────────────────────────────┐ │
|
||||
│ │ Strategy Executor (策略执行) │ │
|
||||
│ │ - Single: 单一类型 │ │
|
||||
│ │ - Hybrid: 混合类型 │ │
|
||||
│ └──────────────────────────────────────────┘ │
|
||||
│ ┌──────────────────────────────────────────┐ │
|
||||
│ │ Result Processor (结果处理) │ │
|
||||
│ │ - 合并结果 │ │
|
||||
│ │ - 重新排序 │ │
|
||||
│ │ - 生成摘要 │ │
|
||||
│ └──────────────────────────────────────────┘ │
|
||||
└─────────────────────────────────────────────────┘
|
||||
│
|
||||
├──────┬──────┬──────┬──────┐
|
||||
▼ ▼ ▼ ▼ ▼
|
||||
Keyword Semantic Visual Agent People
|
||||
Search Search Search Search Search
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 🔄 API 规范
|
||||
|
||||
### Agent Search API
|
||||
|
||||
**端点**: `POST /api/v1/agent/search`
|
||||
|
||||
**请求**:
|
||||
```json
|
||||
{
|
||||
"query": "Obama healthcare speech",
|
||||
"context": {
|
||||
"user_id": "user_123",
|
||||
"conversation_id": "conv_456",
|
||||
"filters": {},
|
||||
"options": {
|
||||
"limit": 20,
|
||||
"include_thumbnails": true
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**响应**:
|
||||
```json
|
||||
{
|
||||
"query": "Obama healthcare speech",
|
||||
"intent": {
|
||||
"primary_type": "people",
|
||||
"confidence": 0.85,
|
||||
"search_types": ["people", "keyword", "semantic"]
|
||||
},
|
||||
"results": [
|
||||
{
|
||||
"id": "video_123",
|
||||
"score": 0.96,
|
||||
"file_uuid": "384b0ff44aaaa1f1",
|
||||
"snippet": "Obama delivers speech...",
|
||||
"thumbnail": "https://..."
|
||||
}
|
||||
],
|
||||
"total_count": 15,
|
||||
"summary": "Found 15 videos featuring Barack Obama discussing healthcare...",
|
||||
"took_ms": 250
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 底层搜索 API(内部使用)
|
||||
|
||||
**端点**: `POST /api/v1/search/{type}`
|
||||
|
||||
**类型**:
|
||||
- `/api/v1/search/keyword`
|
||||
- `/api/v1/search/semantic`
|
||||
- `/api/v1/search/visual`
|
||||
- `/api/v1/search/agent`
|
||||
- `/api/v1/search/people`
|
||||
|
||||
**用途**: 内部 Worker 调用,不对外暴露
|
||||
|
||||
---
|
||||
|
||||
## 📊 数据模型
|
||||
|
||||
### Rust 类型
|
||||
|
||||
```rust
|
||||
/// Agent Search 服务
|
||||
pub struct AgentSearchService {
|
||||
messenger: Messenger,
|
||||
llm_client: LLMClient,
|
||||
query_analyzer: QueryAnalyzer,
|
||||
}
|
||||
|
||||
/// Agent Search 请求
|
||||
pub struct AgentSearchRequest {
|
||||
pub query: String,
|
||||
pub context: Option<SearchContext>,
|
||||
}
|
||||
|
||||
/// Agent Search 响应
|
||||
pub struct AgentSearchResponse {
|
||||
pub query: String,
|
||||
pub intent: QueryIntent,
|
||||
pub results: Vec<SearchResult>,
|
||||
pub total_count: i64,
|
||||
pub summary: String,
|
||||
pub took_ms: i64,
|
||||
}
|
||||
|
||||
/// 底层搜索类型
|
||||
pub enum SearchType {
|
||||
Keyword,
|
||||
Semantic,
|
||||
Visual,
|
||||
Agent,
|
||||
People,
|
||||
}
|
||||
|
||||
/// 底层搜索请求
|
||||
pub struct SearchRequest {
|
||||
pub query: String,
|
||||
pub search_type: SearchType,
|
||||
pub filters: SearchFilters,
|
||||
pub options: SearchOptions,
|
||||
}
|
||||
|
||||
/// 底层搜索响应
|
||||
pub struct SearchResponse {
|
||||
pub request_id: String,
|
||||
pub query: String,
|
||||
pub search_type: SearchType,
|
||||
pub results: Vec<SearchResult>,
|
||||
pub total_count: i64,
|
||||
pub took_ms: i64,
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 🎯 使用场景
|
||||
|
||||
### 场景 1: 简单搜索
|
||||
|
||||
**用户**: "interview with Obama"
|
||||
|
||||
**Agent Search**:
|
||||
- 分析: Keyword (0.9)
|
||||
- 执行: KeywordSearchWorker
|
||||
- 结果: 15 个视频
|
||||
|
||||
---
|
||||
|
||||
### 场景 2: 语义搜索
|
||||
|
||||
**用户**: "people discussing politics"
|
||||
|
||||
**Agent Search**:
|
||||
- 分析: Semantic (0.8)
|
||||
- 执行: SemanticSearchWorker
|
||||
- 结果: 23 个视频
|
||||
|
||||
---
|
||||
|
||||
### 场景 3: 混合搜索
|
||||
|
||||
**用户**: "Obama healthcare speech 2010"
|
||||
|
||||
**Agent Search**:
|
||||
- 分析: People (0.8), Keyword (0.7), Semantic (0.6)
|
||||
- 执行: 并行调用 3 个 Worker
|
||||
- 合并: 去重、重排
|
||||
- 结果: 25 个视频
|
||||
|
||||
---
|
||||
|
||||
### 场景 4: Agent 推理
|
||||
|
||||
**用户**: "compare Obama and Biden on healthcare"
|
||||
|
||||
**Agent Search**:
|
||||
- 分析: Agent (0.95)
|
||||
- 执行: AgentSearchWorker (LLM + RAG)
|
||||
- 推理: 多步骤搜索 + 比较
|
||||
- 结果: 比较报告 + 相关视频
|
||||
|
||||
---
|
||||
|
||||
## 📚 文档索引
|
||||
|
||||
### 设计文档
|
||||
|
||||
1. **Agent Search 设计**:
|
||||
- `docs_v1.0/DESIGN/Agent_Search_Interface.md`
|
||||
|
||||
2. **底层搜索类型**:
|
||||
- `docs_v1.0/DESIGN/Search_As_Messenger_Variant.md`
|
||||
|
||||
3. **架构设计**:
|
||||
- `docs_v1.0/DESIGN/MarkBase_Unified_Command_Queue.md`
|
||||
|
||||
---
|
||||
|
||||
### API 文档
|
||||
|
||||
1. **Agent Search API**:
|
||||
- `docs_v1.0/API_WORKSPACE/modules/agent_search_api.md`
|
||||
|
||||
2. **底层搜索 API**:
|
||||
- `docs_v1.0/API_WORKSPACE/modules/search_api.md`
|
||||
|
||||
---
|
||||
|
||||
## 🚀 开发状态
|
||||
|
||||
| 模块 | 状态 | 文件 |
|
||||
|------|------|------|
|
||||
| **AgentSearchService** | ⚠️ 待实现 | `src/core/command/agent_search/mod.rs` |
|
||||
| **QueryAnalyzer** | ⚠️ 待实现 | `src/core/command/agent_search/analyzer.rs` |
|
||||
| **SearchType 定义** | ✅ 完成 | `src/core/command/search/types.rs` |
|
||||
| **设计文档** | ✅ 完成 | `docs_v1.0/DESIGN/` |
|
||||
|
||||
---
|
||||
|
||||
## ✅ 命名规范确认
|
||||
|
||||
**正式命名**:
|
||||
- ✅ 顶层介面: **Agent Search**
|
||||
- ✅ 底层类型: Keyword, Semantic, Visual, Agent, People
|
||||
- ✅ API 路径: `/api/v1/agent/search`
|
||||
- ✅ 服务名称: `AgentSearchService`
|
||||
|
||||
**命名完成,设计规范已确认!**
|
||||
@@ -0,0 +1,742 @@
|
||||
# 独立队列系统架构设计
|
||||
|
||||
**版本**: V2.0
|
||||
**日期**: 2026-10-11
|
||||
**目标**: 独立部署、通用队列服务、支持任何队列需求
|
||||
|
||||
---
|
||||
|
||||
## 🎯 设计目标
|
||||
|
||||
### 当前问题
|
||||
|
||||
| 问题 | 影响 | 解决方案 |
|
||||
|------|------|---------|
|
||||
| VLM 队列硬编码在 Job Worker | ❌ 无法独立部署 | 独立队列服务 |
|
||||
| 缺少通用队列抽象 | ❌ 每个队列重复实现 | 统一队列框架 |
|
||||
| 无法动态扩展队列类型 | ❌ 新队列需修改代码 | 插件式队列类型 |
|
||||
| 缺少队列管理 API | ❌ 难以监控和管理 | REST API 管理接口 |
|
||||
|
||||
---
|
||||
|
||||
## 🏗️ 新架构设计
|
||||
|
||||
### 系统架构图
|
||||
|
||||
```
|
||||
┌─────────────────────────────────────────────────────────────────┐
|
||||
│ Queue Service (独立进程) │
|
||||
│ Port: 4000 │
|
||||
├─────────────────────────────────────────────────────────────────┤
|
||||
│ │
|
||||
│ ┌────────────────────────────────────────────────────────────┐ │
|
||||
│ │ REST API (Axum) │ │
|
||||
│ │ ├─ POST /api/v1/queues 创建队列 │ │
|
||||
│ │ ├─ GET /api/v1/queues 列出队列 │ │
|
||||
│ │ ├─ DELETE /api/v1/queues/{name} 删除队列 │ │
|
||||
│ │ ├─ POST /api/v1/queues/{name}/messages 提交消息 │ │
|
||||
│ │ ├─ GET /api/v1/queues/{name}/messages 拉取消息 │ │
|
||||
│ │ ├─ POST /api/v1/queues/{name}/commit 提交确认 │ │
|
||||
│ │ └─ GET /api/v1/queues/{name}/stats 队列统计 │ │
|
||||
│ └────────────────────────────────────────────────────────────┘ │
|
||||
│ │
|
||||
│ ┌────────────────────────────────────────────────────────────┐ │
|
||||
│ │ Queue Manager │ │
|
||||
│ │ ├─ 队列注册与管理 │ │
|
||||
│ │ ├─ 插件式队列类型支持 │ │
|
||||
│ │ └─ 生命周期管理 │ │
|
||||
│ └────────────────────────────────────────────────────────────┘ │
|
||||
│ │
|
||||
│ ┌────────────────────────────────────────────────────────────┐ │
|
||||
│ │ Queue Implementations │ │
|
||||
│ │ ├─ VLM Queue (priority, retry, DLQ) │ │
|
||||
│ │ ├─ Command Queue (FIFO, deduplication) │ │
|
||||
│ │ ├─ Task Queue (dependency, parallel) │ │
|
||||
│ │ ├─ Notification Queue (broadcast) │ │
|
||||
│ │ └─ Custom Queue (plugin) │ │
|
||||
│ └────────────────────────────────────────────────────────────┘ │
|
||||
│ │
|
||||
│ ┌────────────────────────────────────────────────────────────┐ │
|
||||
│ │ Storage Backend │ │
|
||||
│ │ ├─ PostgreSQL (default, durable) │ │
|
||||
│ │ ├─ Redis (fast, in-memory) │ │
|
||||
│ │ └─ Custom (plugin) │ │
|
||||
│ └────────────────────────────────────────────────────────────┘ │
|
||||
│ │
|
||||
│ ┌────────────────────────────────────────────────────────────┐ │
|
||||
│ │ Worker Pool (可选) │ │
|
||||
│ │ ├─ 自动处理队列消息 │ │
|
||||
│ │ ├─ 自定义处理函数 │ │
|
||||
│ │ └─ 并发控制 │ │
|
||||
│ └────────────────────────────────────────────────────────────┘ │
|
||||
│ │
|
||||
└─────────────────────────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 📦 核心组件
|
||||
|
||||
### 1. Queue Service (主服务)
|
||||
|
||||
**职责**:
|
||||
- ✅ 独立进程,监听 HTTP API
|
||||
- ✅ 管理多个队列实例
|
||||
- ✅ 提供统一的队列操作接口
|
||||
- ✅ 支持插件式队列类型
|
||||
- ✅ 可选的 Worker Pool
|
||||
|
||||
**启动方式**:
|
||||
```bash
|
||||
# 独立启动
|
||||
cargo run --bin queue_service -- --port 4000
|
||||
|
||||
# 后台运行
|
||||
./target/release/queue_service --port 4000 > logs/queue_service.log 2>&1 &
|
||||
|
||||
# 配置文件
|
||||
queue_service --config queue_service.toml
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 2. Queue Manager
|
||||
|
||||
**职责**:
|
||||
- ✅ 注册和管理队列
|
||||
- ✅ 队列生命周期管理
|
||||
- ✅ 插件式队列类型加载
|
||||
- ✅ 配置管理
|
||||
|
||||
**API**:
|
||||
```rust
|
||||
impl QueueManager {
|
||||
// 创建队列
|
||||
pub async fn create_queue(&mut self, config: QueueConfig) -> Result<String>;
|
||||
|
||||
// 删除队列
|
||||
pub async fn delete_queue(&mut self, name: &str) -> Result<()>;
|
||||
|
||||
// 获取队列
|
||||
pub fn get_queue(&self, name: &str) -> Option<Arc<dyn Queue>>;
|
||||
|
||||
// 列出队列
|
||||
pub fn list_queues(&self) -> Vec<QueueInfo>;
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 3. Queue Trait (通用接口)
|
||||
|
||||
```rust
|
||||
/// 通用队列接口
|
||||
#[async_trait]
|
||||
pub trait Queue: Send + Sync {
|
||||
/// 提交消息
|
||||
async fn enqueue(&self, message: Message) -> Result<MessageId>;
|
||||
|
||||
/// 拉取消息
|
||||
async fn dequeue(&self, options: DequeueOptions) -> Result<Vec<Message>>;
|
||||
|
||||
/// 确认消息
|
||||
async fn commit(&self, message_id: MessageId) -> Result<()>;
|
||||
|
||||
/// 失败消息
|
||||
async fn fail(&self, message_id: MessageId, error: &str) -> Result<()>;
|
||||
|
||||
/// 获取统计
|
||||
async fn stats(&self) -> Result<QueueStats>;
|
||||
|
||||
/// 清空队列
|
||||
async fn clear(&self) -> Result<()>;
|
||||
|
||||
/// 队列名称
|
||||
fn name(&self) -> &str;
|
||||
|
||||
/// 队列类型
|
||||
fn queue_type(&self) -> QueueType;
|
||||
}
|
||||
|
||||
/// 消息
|
||||
pub struct Message {
|
||||
pub id: MessageId,
|
||||
pub payload: serde_json::Value,
|
||||
pub priority: i32,
|
||||
pub metadata: HashMap<String, String>,
|
||||
pub created_at: DateTime<Utc>,
|
||||
}
|
||||
|
||||
/// 队列类型
|
||||
pub enum QueueType {
|
||||
Priority, // 优先级队列
|
||||
FIFO, // 先进先出
|
||||
Delayed, // 延迟队列
|
||||
Broadcast, // 广播队列
|
||||
Custom(String), // 自定义队列
|
||||
}
|
||||
|
||||
/// 队列配置
|
||||
pub struct QueueConfig {
|
||||
pub name: String,
|
||||
pub queue_type: QueueType,
|
||||
pub storage: StorageConfig,
|
||||
pub options: QueueOptions,
|
||||
}
|
||||
|
||||
pub struct QueueOptions {
|
||||
pub max_retries: u32,
|
||||
pub timeout_secs: u64,
|
||||
pub max_size: usize,
|
||||
pub deduplication: bool,
|
||||
pub priority_levels: u32,
|
||||
pub delayed_delivery: bool,
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 📊 队列类型实现
|
||||
|
||||
### 1. VLM Queue
|
||||
|
||||
**特性**:
|
||||
- ✅ 优先级调度(P0-P1)
|
||||
- ✅ 重试机制
|
||||
- ✅ 死信队列
|
||||
- ✅ Offset 追踪
|
||||
|
||||
**配置**:
|
||||
```toml
|
||||
[[queues]]
|
||||
name = "vlm"
|
||||
type = "priority"
|
||||
storage = "postgres"
|
||||
max_retries = 2
|
||||
timeout_secs = 60
|
||||
priority_levels = 2
|
||||
|
||||
[queues.dlq]
|
||||
enabled = true
|
||||
max_size = 1000
|
||||
```
|
||||
|
||||
**使用**:
|
||||
```bash
|
||||
# 提交 VLM 请求
|
||||
curl -X POST http://localhost:4000/api/v1/queues/vlm/messages \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{
|
||||
"priority": 0,
|
||||
"payload": {
|
||||
"request_type": "agent_vlm",
|
||||
"image_path": "/path/to/image.jpg",
|
||||
"prompt": "Analyze this image"
|
||||
}
|
||||
}'
|
||||
|
||||
# 拉取消息
|
||||
curl -X GET "http://localhost:4000/api/v1/queues/vlm/messages?max_messages=5&timeout=10"
|
||||
|
||||
# 确认消息
|
||||
curl -X POST http://localhost:4000/api/v1/queues/vlm/commit \
|
||||
-d '{"message_id": "vlm_abc123"}'
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 2. Command Queue
|
||||
|
||||
**特性**:
|
||||
- ✅ FIFO 先进先出
|
||||
- ✅ 去重机制
|
||||
- ✅ 命令历史
|
||||
- ✅ 并发控制
|
||||
|
||||
**配置**:
|
||||
```toml
|
||||
[[queues]]
|
||||
name = "command"
|
||||
type = "fifo"
|
||||
storage = "postgres"
|
||||
deduplication = true
|
||||
max_size = 1000
|
||||
|
||||
[queues.deduplication]
|
||||
window_secs = 3600
|
||||
key_fields = ["job_type", "file_path"]
|
||||
```
|
||||
|
||||
**使用**:
|
||||
```bash
|
||||
# 提交注册命令
|
||||
curl -X POST http://localhost:4000/api/v1/queues/command/messages \
|
||||
-d '{
|
||||
"payload": {
|
||||
"job_type": "register",
|
||||
"file_path": "/path/to/video.mp4"
|
||||
}
|
||||
}'
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 3. Task Queue
|
||||
|
||||
**特性**:
|
||||
- ✅ 依赖管理
|
||||
- ✅ 并行处理
|
||||
- ✅ 进度追踪
|
||||
- ✅ 结果收集
|
||||
|
||||
**配置**:
|
||||
```toml
|
||||
[[queues]]
|
||||
name = "task"
|
||||
type = "dependency"
|
||||
storage = "postgres"
|
||||
parallel = 6
|
||||
|
||||
[queues.dependency]
|
||||
check_interval_secs = 5
|
||||
```
|
||||
|
||||
**使用**:
|
||||
```bash
|
||||
# 提交任务(带依赖)
|
||||
curl -X POST http://localhost:4000/api/v1/queues/task/messages \
|
||||
-d '{
|
||||
"payload": {
|
||||
"processor": "scene_vlm",
|
||||
"file_uuid": "abc123"
|
||||
},
|
||||
"metadata": {
|
||||
"dependencies": ["asr", "face", "cut"]
|
||||
}
|
||||
}'
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 4. Notification Queue
|
||||
|
||||
**特性**:
|
||||
- ✅ 广播模式
|
||||
- ✅ 多订阅者
|
||||
- ✅ 实时推送
|
||||
|
||||
**配置**:
|
||||
```toml
|
||||
[[queues]]
|
||||
name = "notification"
|
||||
type = "broadcast"
|
||||
storage = "redis"
|
||||
|
||||
[queues.broadcast]
|
||||
retention_secs = 3600
|
||||
```
|
||||
|
||||
**使用**:
|
||||
```bash
|
||||
# 发布通知
|
||||
curl -X POST http://localhost:4000/api/v1/queues/notification/messages \
|
||||
-d '{
|
||||
"payload": {
|
||||
"type": "job_completed",
|
||||
"file_uuid": "abc123"
|
||||
}
|
||||
}'
|
||||
|
||||
# 订阅通知 (WebSocket)
|
||||
ws://localhost:4000/api/v1/queues/notification/subscribe
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 🔌 插件系统
|
||||
|
||||
### 创建自定义队列
|
||||
|
||||
```rust
|
||||
// src/queue_plugins/my_queue.rs
|
||||
|
||||
use crate::queue::{Queue, Message, MessageId, QueueStats, DequeueOptions};
|
||||
|
||||
pub struct MyCustomQueue {
|
||||
name: String,
|
||||
storage: Arc<dyn Storage>,
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl Queue for MyCustomQueue {
|
||||
async fn enqueue(&self, message: Message) -> Result<MessageId> {
|
||||
// 自定义逻辑
|
||||
}
|
||||
|
||||
async fn dequeue(&self, options: DequeueOptions) -> Result<Vec<Message>> {
|
||||
// 自定义逻辑
|
||||
}
|
||||
|
||||
// ... 实现其他方法
|
||||
}
|
||||
|
||||
// 注册插件
|
||||
#[no_mangle]
|
||||
pub extern "C" fn create_queue(config: QueueConfig) -> Box<dyn Queue> {
|
||||
Box::new(MyCustomQueue::new(config))
|
||||
}
|
||||
```
|
||||
|
||||
**配置**:
|
||||
```toml
|
||||
[[queues]]
|
||||
name = "my_custom"
|
||||
type = "custom:my_queue"
|
||||
plugin = "plugins/libmy_queue.dylib"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 🚀 部署架构
|
||||
|
||||
### 单实例部署
|
||||
|
||||
```
|
||||
Queue Service (port 4000)
|
||||
↓
|
||||
PostgreSQL (持久化)
|
||||
Redis (缓存,可选)
|
||||
```
|
||||
|
||||
**启动**:
|
||||
```bash
|
||||
# 方式 1: 直接运行
|
||||
cargo run --release --bin queue_service -- --port 4000
|
||||
|
||||
# 方式 2: Docker
|
||||
docker run -p 4000:4000 momentry/queue-service
|
||||
|
||||
# 方式 3: launchd
|
||||
launchctl start gui/$(id -u)/com.momentry.queue-service
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 集群部署(未来)
|
||||
|
||||
```
|
||||
┌──────────────────┐
|
||||
│ Load Balancer │
|
||||
└──────────────────┘
|
||||
│
|
||||
┌────┴────┐
|
||||
│ │
|
||||
┌───▼───┐ ┌───▼───┐
|
||||
│Queue │ │Queue │
|
||||
│Node 1 │ │Node 2 │
|
||||
└───────┘ └───────┘
|
||||
│ │
|
||||
└────┬────┘
|
||||
│
|
||||
┌────────▼────────┐
|
||||
│ Shared Storage │
|
||||
│ (PostgreSQL) │
|
||||
└─────────────────┘
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 📝 REST API 完整规范
|
||||
|
||||
### 队列管理
|
||||
|
||||
```http
|
||||
# 创建队列
|
||||
POST /api/v1/queues
|
||||
{
|
||||
"name": "my_queue",
|
||||
"type": "priority",
|
||||
"config": {
|
||||
"max_retries": 3,
|
||||
"timeout_secs": 60
|
||||
}
|
||||
}
|
||||
|
||||
# 列出队列
|
||||
GET /api/v1/queues
|
||||
|
||||
# 删除队列
|
||||
DELETE /api/v1/queues/my_queue
|
||||
|
||||
# 获取队列信息
|
||||
GET /api/v1/queues/my_queue
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 消息操作
|
||||
|
||||
```http
|
||||
# 提交消息
|
||||
POST /api/v1/queues/my_queue/messages
|
||||
{
|
||||
"priority": 0,
|
||||
"payload": {...},
|
||||
"metadata": {...}
|
||||
}
|
||||
|
||||
# 响应
|
||||
{
|
||||
"message_id": "msg_abc123",
|
||||
"status": "pending",
|
||||
"created_at": "2026-10-11T09:00:00Z"
|
||||
}
|
||||
|
||||
# 拉取消息
|
||||
GET /api/v1/queues/my_queue/messages?max_messages=10&timeout=30
|
||||
|
||||
# 响应
|
||||
{
|
||||
"messages": [
|
||||
{
|
||||
"id": "msg_abc123",
|
||||
"payload": {...},
|
||||
"priority": 0,
|
||||
"created_at": "2026-10-11T09:00:00Z"
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
# 确认消息
|
||||
POST /api/v1/queues/my_queue/commit
|
||||
{
|
||||
"message_id": "msg_abc123",
|
||||
"result": "success",
|
||||
"output": {...}
|
||||
}
|
||||
|
||||
# 失败消息
|
||||
POST /api/v1/queues/my_queue/fail
|
||||
{
|
||||
"message_id": "msg_abc123",
|
||||
"error": "Processing failed"
|
||||
}
|
||||
|
||||
# 获取消息状态
|
||||
GET /api/v1/queues/my_queue/messages/msg_abc123
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 统计与监控
|
||||
|
||||
```http
|
||||
# 队列统计
|
||||
GET /api/v1/queues/my_queue/stats
|
||||
|
||||
# 响应
|
||||
{
|
||||
"queue_name": "my_queue",
|
||||
"queue_type": "priority",
|
||||
"pending": 10,
|
||||
"processing": 2,
|
||||
"completed": 50,
|
||||
"failed": 3,
|
||||
"avg_processing_time_ms": 1250.5,
|
||||
"throughput_per_min": 12.5
|
||||
}
|
||||
|
||||
# 健康检查
|
||||
GET /api/v1/health
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 🛠️ 客户端 SDK
|
||||
|
||||
### Rust SDK
|
||||
|
||||
```rust
|
||||
use momentry_queue::{QueueClient, Message};
|
||||
|
||||
let client = QueueClient::new("http://localhost:4000")?;
|
||||
|
||||
// 创建队列
|
||||
client.create_queue("my_queue", QueueConfig::priority()).await?;
|
||||
|
||||
// 提交消息
|
||||
let msg = Message::new(json!({"key": "value"}))
|
||||
.with_priority(0);
|
||||
let msg_id = client.enqueue("my_queue", msg).await?;
|
||||
|
||||
// 拉取消息
|
||||
let messages = client.dequeue("my_queue", 10).await?;
|
||||
|
||||
// 确认消息
|
||||
client.commit("my_queue", msg_id).await?;
|
||||
```
|
||||
|
||||
### Python SDK
|
||||
|
||||
```python
|
||||
from momentry_queue import QueueClient
|
||||
|
||||
client = QueueClient("http://localhost:4000")
|
||||
|
||||
# 提交消息
|
||||
msg_id = client.enqueue("my_queue", {"key": "value"}, priority=0)
|
||||
|
||||
# 拉取消息
|
||||
messages = client.dequeue("my_queue", max_messages=10)
|
||||
|
||||
# 确认消息
|
||||
client.commit("my_queue", msg_id)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 📊 配置文件示例
|
||||
|
||||
```toml
|
||||
# queue_service.toml
|
||||
|
||||
[server]
|
||||
host = "0.0.0.0"
|
||||
port = 4000
|
||||
|
||||
[storage]
|
||||
default = "postgres"
|
||||
|
||||
[storage.postgres]
|
||||
url = "postgres://accusys@localhost:5432/momentry"
|
||||
pool_size = 10
|
||||
|
||||
[storage.redis]
|
||||
url = "redis://localhost:6379"
|
||||
pool_size = 5
|
||||
|
||||
# VLM Queue
|
||||
[[queues]]
|
||||
name = "vlm"
|
||||
type = "priority"
|
||||
storage = "postgres"
|
||||
max_retries = 2
|
||||
timeout_secs = 60
|
||||
priority_levels = 2
|
||||
|
||||
[queues.dlq]
|
||||
enabled = true
|
||||
max_size = 1000
|
||||
|
||||
# Command Queue
|
||||
[[queues]]
|
||||
name = "command"
|
||||
type = "fifo"
|
||||
storage = "postgres"
|
||||
deduplication = true
|
||||
max_size = 1000
|
||||
|
||||
# Task Queue
|
||||
[[queues]]
|
||||
name = "task"
|
||||
type = "dependency"
|
||||
storage = "postgres"
|
||||
parallel = 6
|
||||
|
||||
# Notification Queue
|
||||
[[queues]]
|
||||
name = "notification"
|
||||
type = "broadcast"
|
||||
storage = "redis"
|
||||
retention_secs = 3600
|
||||
|
||||
[worker_pool]
|
||||
enabled = false # 如果 true,自动处理消息
|
||||
max_workers = 10
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 🚀 快速开始
|
||||
|
||||
### 安装
|
||||
|
||||
```bash
|
||||
# 编译
|
||||
cargo build --release --bin queue_service
|
||||
|
||||
# 或安装
|
||||
cargo install --path . --bin queue_service
|
||||
```
|
||||
|
||||
### 启动
|
||||
|
||||
```bash
|
||||
# 方式 1: 默认配置
|
||||
queue_service
|
||||
|
||||
# 方式 2: 指定配置
|
||||
queue_service --config queue_service.toml
|
||||
|
||||
# 方式 3: 指定端口
|
||||
queue_service --port 4000
|
||||
```
|
||||
|
||||
### 使用
|
||||
|
||||
```bash
|
||||
# 创建队列
|
||||
curl -X POST http://localhost:4000/api/v1/queues \
|
||||
-d '{"name": "test", "type": "fifo"}'
|
||||
|
||||
# 提交消息
|
||||
curl -X POST http://localhost:4000/api/v1/queues/test/messages \
|
||||
-d '{"payload": {"message": "hello"}}'
|
||||
|
||||
# 拉取消息
|
||||
curl http://localhost:4000/api/v1/queues/test/messages
|
||||
|
||||
# 查看统计
|
||||
curl http://localhost:4000/api/v1/queues/test/stats
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 🎯 迁移计划
|
||||
|
||||
### 阶段 1: 实现核心框架(1 周)
|
||||
|
||||
- [ ] Queue Trait 定义
|
||||
- [ ] Queue Manager 实现
|
||||
- [ ] REST API 实现
|
||||
- [ ] PostgreSQL Storage 实现
|
||||
|
||||
### 阶段 2: 迁移现有队列(1 周)
|
||||
|
||||
- [ ] VLM Queue 实现
|
||||
- [ ] Command Queue 实现
|
||||
- [ ] Task Queue 实现
|
||||
|
||||
### 阶段 3: 高级功能(1 周)
|
||||
|
||||
- [ ] Worker Pool
|
||||
- [ ] 插件系统
|
||||
- [ ] 监控告警
|
||||
|
||||
### 阶段 4: 集成与测试(3 天)
|
||||
|
||||
- [ ] 与 Momentry Core 集成
|
||||
- [ ] 性能测试
|
||||
- [ ] 文档完善
|
||||
|
||||
---
|
||||
|
||||
## 📚 相关文档
|
||||
|
||||
- API 规范: `docs_v1.0/API_WORKSPACE/queue_service_api.md`
|
||||
- 客户端 SDK: `docs_v1.0/GUIDES/queue_sdk_guide.md`
|
||||
- 插件开发: `docs_v1.0/GUIDES/queue_plugin_development.md`
|
||||
|
||||
---
|
||||
|
||||
**设计完成,准备实施!**
|
||||
@@ -0,0 +1,294 @@
|
||||
---
|
||||
title: Swift Face Trace Design
|
||||
version: 1.0
|
||||
date: 2026-09-28
|
||||
author: OpenCode
|
||||
status: design
|
||||
---
|
||||
|
||||
## 目標
|
||||
|
||||
實現 Swift 版本的 Face Trace,使用 Apple Vision + ANE 加速。
|
||||
|
||||
---
|
||||
|
||||
## 背景
|
||||
|
||||
### 當前狀態
|
||||
|
||||
**FACE_TRACE**: 使用 Rust (rust_store_traced_faces)
|
||||
- 性能: 20x 更快 (vs Python)
|
||||
- 工具: rust_store_traced_faces
|
||||
|
||||
### 用戶需求
|
||||
|
||||
**所有 face 相關工具應該使用 Swift + Apple Vision**
|
||||
|
||||
---
|
||||
|
||||
## Apple Vision API
|
||||
|
||||
### VNTrackFaceLandmarksRequest
|
||||
|
||||
**功能**: 在視頻中跟蹤人臉特徵點
|
||||
|
||||
**API**:
|
||||
```swift
|
||||
import Vision
|
||||
|
||||
// 創建跟蹤請求
|
||||
let trackRequest = VNTrackFaceLandmarksRequest()
|
||||
|
||||
// 處理視頻幀
|
||||
let handler = VNSequenceRequestHandler()
|
||||
try handler.perform([trackRequest], on: pixelBuffer)
|
||||
|
||||
// 獲取結果
|
||||
if let observation = trackRequest.results?.first as? VNFaceObservation {
|
||||
// 獲取 face ID (用於追蹤)
|
||||
let faceID = observation.faceID
|
||||
|
||||
// 獲取特徵點
|
||||
let landmarks = observation.landmarks
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### VNDetectFaceLandmarksRequest
|
||||
|
||||
**功能**: 檢測單幀中的人臉特徵點
|
||||
|
||||
**API**:
|
||||
```swift
|
||||
let detectRequest = VNDetectFaceLandmarksRequest()
|
||||
let handler = VNImageRequestHandler(cvPixelBuffer: pixelBuffer)
|
||||
|
||||
try handler.perform([detectRequest])
|
||||
|
||||
if let results = detectRequest.results {
|
||||
for observation in results {
|
||||
let faceID = observation.faceID // 自動分配的 ID
|
||||
let landmarks = observation.landmarks
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 實現方案
|
||||
|
||||
### 方案 A: VNTrackFaceLandmarksRequest (推薦)
|
||||
|
||||
**優勢**:
|
||||
- ✅ 原生追蹤 API
|
||||
- ✅ ANE 加速
|
||||
- ✅ 自動 face ID 分配
|
||||
- ✅ 跨幀追蹤
|
||||
|
||||
**實現**:
|
||||
```swift
|
||||
import Vision
|
||||
import AVFoundation
|
||||
|
||||
func traceFaces(videoPath: String) throws -> [FaceTrace] {
|
||||
let asset = AVAsset(url: URL(fileURLWithPath: videoPath))
|
||||
let reader = try AVAssetReader(asset: asset)
|
||||
|
||||
// 創建追蹤請求
|
||||
let trackRequest = VNTrackFaceLandmarksRequest()
|
||||
|
||||
// 讀取視頻幀
|
||||
// 對每個關鍵幀執行追蹤
|
||||
// 收集 face ID 和位置
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 方案 B: VNDetectFaceLandmarksRequest + 自定義追蹤
|
||||
|
||||
**優勢**:
|
||||
- ✅ 更靈活
|
||||
- ✅ 可自定義追蹤邏輯
|
||||
|
||||
**缺點**:
|
||||
- ⚠️ 需要自己實現追蹤邏輯
|
||||
- ⚠️ 開發時間更長
|
||||
|
||||
---
|
||||
|
||||
## 架構設計
|
||||
|
||||
### swift_face_trace
|
||||
|
||||
**輸入**: 視頻文件路徑
|
||||
|
||||
**輸出**: face_traced.json
|
||||
|
||||
```json
|
||||
{
|
||||
"traces": [
|
||||
{
|
||||
"trace_id": 1,
|
||||
"total_appearances": 140,
|
||||
"avg_confidence": 0.85,
|
||||
"frames": [
|
||||
{"frame": 0, "bbox": {...}, "confidence": 0.90},
|
||||
{"frame": 3, "bbox": {...}, "confidence": 0.88}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 核心邏輯
|
||||
|
||||
```swift
|
||||
func detectFacesInFrame(_ buffer: CVPixelBuffer) -> [FaceDetection] {
|
||||
let request = VNDetectFaceLandmarksRequest()
|
||||
let handler = VNImageRequestHandler(cvPixelBuffer: buffer)
|
||||
|
||||
try handler.perform([request])
|
||||
|
||||
var faces: [FaceDetection] = []
|
||||
|
||||
for observation in request.results ?? [] {
|
||||
let face = FaceDetection(
|
||||
faceID: observation.faceID,
|
||||
bbox: observation.boundingBox,
|
||||
confidence: observation.confidence
|
||||
)
|
||||
faces.append(face)
|
||||
}
|
||||
|
||||
return faces
|
||||
}
|
||||
|
||||
func assignTraceIDs(_ frames: [[FaceDetection]]) -> [FaceTrace] {
|
||||
// 基於 faceID 和空間位置分配 trace_id
|
||||
// 確保同一個人在整個視頻中有相同的 trace_id
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 性能預期
|
||||
|
||||
### 對比 Rust
|
||||
|
||||
| 方法 | 性能 | 理由 |
|
||||
|------|------|------|
|
||||
| Rust | 0.1s | CPU 優化 |
|
||||
| Swift (ANE) | ? | 待測試 |
|
||||
|
||||
**預期**:
|
||||
- 如果 ANE 加速明顯 → Swift 更快
|
||||
- 如果 ANE 開銷大 → Rust 更快
|
||||
|
||||
---
|
||||
|
||||
## 實現步驟
|
||||
|
||||
### Phase 1: 原型 (2-3 天)
|
||||
|
||||
1. 實現基本 face detection
|
||||
2. 實現 trace ID 分配
|
||||
3. 生成 JSON 輸出
|
||||
4. 單元測試
|
||||
|
||||
---
|
||||
|
||||
### Phase 2: 性能優化 (1-2 天)
|
||||
|
||||
1. 降低幀處理頻率
|
||||
2. 優化內存使用
|
||||
3. 性能基準測試
|
||||
|
||||
---
|
||||
|
||||
### Phase 3: 集成 (1 天)
|
||||
|
||||
1. 更新配置文件
|
||||
2. 性能對比測試
|
||||
3. 文檔更新
|
||||
|
||||
---
|
||||
|
||||
## 配置更新
|
||||
|
||||
### 當前配置
|
||||
|
||||
```json
|
||||
{
|
||||
"face_trace": {
|
||||
"implementations": [
|
||||
{"tool": "rust", "priority": 0, "enabled": true}
|
||||
],
|
||||
"default": {"tool": "rust"}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 新配置
|
||||
|
||||
```json
|
||||
{
|
||||
"face_trace": {
|
||||
"implementations": [
|
||||
{"tool": "swift", "priority": 0, "enabled": true},
|
||||
{"tool": "rust", "priority": 1, "enabled": true}
|
||||
],
|
||||
"default": {"tool": "swift"}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 風險
|
||||
|
||||
### 技術風險
|
||||
|
||||
- ⚠️ VNTrackFaceLandmarksRequest 可能不穩定
|
||||
- ⚠️ faceID 可能跨幀不連續
|
||||
|
||||
### 時間風險
|
||||
|
||||
- ⚠️ 需要調試 Apple Vision API
|
||||
- ⚠️ 性能優化可能需要更多時間
|
||||
|
||||
---
|
||||
|
||||
## 總結
|
||||
|
||||
### ✅ 可行
|
||||
|
||||
使用 Swift + Apple Vision 實現 face_trace **技術可行**。
|
||||
|
||||
### 📊 預期收益
|
||||
|
||||
1. **Apple Vision + ANE**: 硬件加速
|
||||
2. **統一架構**: 所有 face 工具使用 Swift
|
||||
3. **性能提升**: 可能超越 Rust
|
||||
|
||||
### 🎯 建議
|
||||
|
||||
**短期**: 繼續使用 Rust (已驗證,20x 更快)
|
||||
|
||||
**中期**: 實現 Swift 版本原型
|
||||
|
||||
**長期**: 根據性能測試結果決定
|
||||
|
||||
---
|
||||
|
||||
**下一步**: 創建 swift_face_trace 原型,驗證 Apple Vision API
|
||||
|
||||
---
|
||||
|
||||
**設計日期**: 2026-09-28
|
||||
**狀態**: 📝 **設計完成,待實現**
|
||||
@@ -0,0 +1,96 @@
|
||||
---
|
||||
title: Sync Status Completed Logic Fix
|
||||
version: 1.0
|
||||
date: 2026-07-28
|
||||
author: Core Team
|
||||
status: draft
|
||||
---
|
||||
|
||||
# Sync Status "Completed" Logic Fix
|
||||
|
||||
## Problem
|
||||
|
||||
The `sync_file_status` endpoint (`POST /api/v1/file/:file_uuid/sync-status`) incorrectly returns `"completed"` status when some processor JSON files are missing.
|
||||
|
||||
### Root Cause
|
||||
|
||||
In `src/api/files.rs:1673-1753`, the `all_consistent` flag is only updated when `json_exists = true`:
|
||||
|
||||
```rust
|
||||
if json_exists {
|
||||
any_json_exists = true;
|
||||
// ... check consistency, set consistent ...
|
||||
if !consistent {
|
||||
all_consistent = false; // Only executed when JSON exists!
|
||||
}
|
||||
}
|
||||
// When json_exists = false: consistent = false, but all_consistent stays true
|
||||
```
|
||||
|
||||
This means if `asr.json` doesn't exist:
|
||||
- `consistent = false` (initialized at line 1676)
|
||||
- But the `if !consistent` block is never reached
|
||||
- `all_consistent` remains `true`
|
||||
- Status becomes `"completed"` instead of `"scanning"`
|
||||
|
||||
## Design
|
||||
|
||||
### Processor JSON Files (7 required)
|
||||
|
||||
| Processor | Filename | Special Cases |
|
||||
|-----------|----------|---------------|
|
||||
| ASR | `{uuid}.asr.json` | `"status": "no_audio_track"` or `"silent_audio"` |
|
||||
| ASRX | `{uuid}.asrx.json` | `"status": "no_audio_track"` |
|
||||
| OCR | `{uuid}.ocr.json` | Always exists if processor ran |
|
||||
| Pose | `{uuid}.pose.json` | Always exists if processor ran |
|
||||
| CUT | `{uuid}.cut.json` | Always exists if processor ran |
|
||||
| Face | `{uuid}.face.json` | `"status": "no_faces"` |
|
||||
| Face Cluster | `{uuid}.face_cluster.json` | `"status": "no_faces"` or `"no_embeddings"` |
|
||||
|
||||
**Key principle**: ALL processors produce their JSON files, even for special cases. The JSON file exists but may contain empty arrays or special status fields.
|
||||
|
||||
### Status Determination Logic
|
||||
|
||||
| Condition | Status |
|
||||
|-----------|--------|
|
||||
| All 7 JSONs exist AND all consistent AND has TKG edges | `agent_ready` |
|
||||
| All 7 JSONs exist AND all consistent AND no TKG edges | `completed` |
|
||||
| Any JSON exists (but not all, or not consistent) | `scanning` |
|
||||
| No JSON exists | `registered` |
|
||||
|
||||
### Fix
|
||||
|
||||
Move the `all_consistent` update outside the `json_exists` block:
|
||||
|
||||
```rust
|
||||
for (name, filename) in &processors {
|
||||
let path = ...;
|
||||
let json_exists = path.exists();
|
||||
let mut consistent = false;
|
||||
|
||||
if json_exists {
|
||||
any_json_exists = true;
|
||||
// ... check consistency, set consistent ...
|
||||
}
|
||||
|
||||
// MOVED HERE: JSON not existing = not consistent
|
||||
if !consistent {
|
||||
all_consistent = false;
|
||||
}
|
||||
|
||||
processor_status.insert(...);
|
||||
}
|
||||
```
|
||||
|
||||
## Impact
|
||||
|
||||
- **API**: No change to response format
|
||||
- **Behavior**: Files missing any JSON will show `"scanning"` instead of `"completed"`
|
||||
- **Backward compat**: No breaking changes
|
||||
|
||||
## Testing
|
||||
|
||||
1. File with all 7 JSONs → `completed` or `agent_ready`
|
||||
2. File with 6 JSONs (1 missing) → `scanning`
|
||||
3. File with no JSONs → `registered`
|
||||
4. Special case (no audio, no faces) → all JSONs exist with special status → `completed`
|
||||
@@ -0,0 +1,216 @@
|
||||
---
|
||||
title: TKG Builder Rust Migration Analysis
|
||||
version: 1.0
|
||||
date: 2026-09-27
|
||||
author: OpenCode
|
||||
status: analysis_complete
|
||||
---
|
||||
|
||||
## 概述
|
||||
|
||||
分析 Python `tkg_builder.py` 並評估 Rust 移植狀態。
|
||||
|
||||
---
|
||||
|
||||
## 發現
|
||||
|
||||
### ✅ Rust 版本已經存在
|
||||
|
||||
**位置**: `/Users/accusys/momentry_core/src/core/processor/tkg.rs`
|
||||
**大小**: 3498 行
|
||||
**狀態**: **功能完整且更先進**
|
||||
|
||||
---
|
||||
|
||||
## 功能對比
|
||||
|
||||
### Node Builders
|
||||
|
||||
| 功能 | Python | Rust | 優勢 |
|
||||
|------|--------|------|------|
|
||||
| face_track_nodes | ✅ | ✅ | 等價 |
|
||||
| body_track_nodes | ✅ | ❌ | Python |
|
||||
| detected_object_nodes | ✅ | ❌ | Python |
|
||||
| speaker_segment_nodes | ✅ | ✅ | 等價 |
|
||||
| hand_track_nodes | ✅ | ✅ | 等價 |
|
||||
| **gaze_track_nodes** | ❌ | ✅ | **Rust** |
|
||||
| **lip_track_nodes** | ❌ | ✅ | **Rust** |
|
||||
| **text_region_nodes** | ❌ | ✅ | **Rust** |
|
||||
| **appearance_trace_nodes** | ❌ | ✅ | **Rust** |
|
||||
|
||||
### Edge Builders
|
||||
|
||||
| 功能 | Python | Rust | 優勢 |
|
||||
|------|--------|------|------|
|
||||
| co_occurrence_edges | ✅ | ❌ | Python |
|
||||
| speaker_face_edges | ✅ | ✅ | 等價 |
|
||||
| face_face_edges | ✅ | ✅ | 等價 |
|
||||
| face_body_edges | ✅ | ❌ | Python |
|
||||
| body_hand_edges | ✅ | ❌ | Python |
|
||||
| **mutual_gaze_edges** | ❌ | ✅ | **Rust** |
|
||||
| **lip_sync_edges** | ❌ | ✅ | **Rust** |
|
||||
|
||||
---
|
||||
|
||||
## Rust 版本優勢
|
||||
|
||||
### 1. 性能
|
||||
|
||||
- **速度**: 10-100x faster than Python
|
||||
- **內存**: 無 GC,更高效
|
||||
- **並發**: 原生 async/await
|
||||
- **類型安全**: 編譯時檢查
|
||||
|
||||
### 2. 高級功能
|
||||
|
||||
Rust 版本獨有:
|
||||
- **Gaze tracking**: 眼神追蹤
|
||||
- **Mutual gaze**: 互相注視檢測
|
||||
- **Lip sync**: 唇語同步
|
||||
- **Text regions**: 文本區域識別
|
||||
- **Appearance traces**: 外觀追蹤
|
||||
|
||||
---
|
||||
|
||||
## Python 版本優勢
|
||||
|
||||
### 基礎功能
|
||||
|
||||
Python 版本獨有:
|
||||
- **Body tracks**: 身體追蹤
|
||||
- **Detected objects**: YOLO 對象節點
|
||||
- **Co-occurrence**: face-object 共現
|
||||
- **Face-body**: 人臉-身體關聯
|
||||
|
||||
---
|
||||
|
||||
## Rust 版本缺失功能
|
||||
|
||||
需要補充 4 個函數:
|
||||
|
||||
### 1. build_body_track_nodes()
|
||||
|
||||
**數據源**: pose.json
|
||||
**功能**: 創建 body_track 節點
|
||||
**難度**: 簡單
|
||||
|
||||
```rust
|
||||
async fn build_body_track_nodes(
|
||||
pool: &PgPool,
|
||||
file_uuid: &str,
|
||||
output_dir: &str
|
||||
) -> Result<usize>
|
||||
```
|
||||
|
||||
### 2. build_detected_object_nodes()
|
||||
|
||||
**數據源**: yolo.json
|
||||
**功能**: 創建 detected_object 節點
|
||||
**難度**: 簡單
|
||||
|
||||
```rust
|
||||
async fn build_detected_object_nodes(
|
||||
pool: &PgPool,
|
||||
file_uuid: &str,
|
||||
output_dir: &str
|
||||
) -> Result<usize>
|
||||
```
|
||||
|
||||
### 3. build_co_occurrence_edges()
|
||||
|
||||
**數據源**: yolo.json + Qdrant
|
||||
**功能**: face-object 共現邊
|
||||
**難度**: 中等
|
||||
|
||||
```rust
|
||||
async fn build_co_occurrence_edges(
|
||||
pool: &PgPool,
|
||||
file_uuid: &str,
|
||||
output_dir: &str
|
||||
) -> Result<usize>
|
||||
```
|
||||
|
||||
### 4. build_face_body_edges()
|
||||
|
||||
**數據源**: pose.json + Qdrant
|
||||
**功能**: face-body 關聯邊
|
||||
**難度**: 中等
|
||||
|
||||
```rust
|
||||
async fn build_face_body_edges(
|
||||
pool: &PgPool,
|
||||
file_uuid: &str,
|
||||
output_dir: &str
|
||||
) -> Result<usize>
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 實現優先級
|
||||
|
||||
### Phase 1: 補充 Node Builders (高優先級)
|
||||
|
||||
1. `build_body_track_nodes()` - 基礎功能
|
||||
2. `build_detected_object_nodes()` - 基礎功能
|
||||
|
||||
### Phase 2: 補充 Edge Builders (中優先級)
|
||||
|
||||
3. `build_co_occurrence_edges()` - 關鍵關係
|
||||
4. `build_face_body_edges()` - 補充關聯
|
||||
|
||||
### Phase 3: 測試和優化
|
||||
|
||||
- 單元測試
|
||||
- 集成測試
|
||||
- 性能基準測試
|
||||
|
||||
---
|
||||
|
||||
## 工作量估算
|
||||
|
||||
| 階段 | 工作量 | 說明 |
|
||||
|------|--------|------|
|
||||
| Phase 1 | 1-2 天 | Node builders |
|
||||
| Phase 2 | 1-2 天 | Edge builders |
|
||||
| Phase 3 | 1 天 | 測試 |
|
||||
| **總計** | **3-5 天** | 完全替代 Python |
|
||||
|
||||
---
|
||||
|
||||
## 建議
|
||||
|
||||
### 短期
|
||||
|
||||
1. **使用 Rust 版本** - 已經功能完整
|
||||
2. **補充缺失功能** - 4 個函數
|
||||
3. **廢棄 Python 版本** - 減少維護成本
|
||||
|
||||
### 長期
|
||||
|
||||
1. **優化性能** - 利用 Rust 優勢
|
||||
2. **擴展功能** - 更多高級分析
|
||||
3. **自動化測試** - CI/CD 集成
|
||||
|
||||
---
|
||||
|
||||
## 結論
|
||||
|
||||
**Rust 版本已經可以替代 Python 版本**
|
||||
|
||||
優勢:
|
||||
- 性能更好
|
||||
- 功能更多
|
||||
- 類型安全
|
||||
- 易於維護
|
||||
|
||||
行動:
|
||||
- 補充 4 個缺失函數
|
||||
- 完成後廢棄 Python 版本
|
||||
- 預計 3-5 天完成
|
||||
|
||||
---
|
||||
|
||||
## 相關文件
|
||||
|
||||
- `/Users/accusys/momentry_core/scripts/tkg_builder.py`
|
||||
- `/Users/accusys/momentry_core/src/core/processor/tkg.rs`
|
||||
@@ -0,0 +1,390 @@
|
||||
---
|
||||
title: TKG Formation V1.0
|
||||
version: 1.0
|
||||
date: 2026-06-25
|
||||
author: OpenCode
|
||||
status: draft
|
||||
---
|
||||
|
||||
## Overview
|
||||
|
||||
Temporal Knowledge Graph (TKG) is built from multi-processor outputs to create a time-aligned knowledge graph. This document defines the formation phases, node/edge types, data flow, and integration with Identity Agent.
|
||||
|
||||
---
|
||||
|
||||
## Phase Definition
|
||||
|
||||
| Phase | Name | Trigger | Input | Output | Code Location |
|
||||
|-------|------|---------|-------|--------|---------------|
|
||||
| **Phase 0** | Populate | TKG rebuild | `face.json` | `PG face_detections.trace_id` | `tkg.rs:20-100` |
|
||||
| **Phase 1** | Extract | Video register | Video frames | `Qdrant _faces` (512D embeddings) | `face_processor.py` |
|
||||
| **Phase 2** | Build Nodes | TKG rebuild | `face.json`, PG tables | `tkg_nodes` (9 types) | `tkg.rs:506-515` |
|
||||
| **Phase 3** | Build Edges | TKG rebuild | `tkg_nodes`, pose data | `tkg_edges` (9 types) | `tkg.rs:517-524` |
|
||||
| **Phase 4** | Identity | Manual/API call | `Qdrant _faces`, `_seeds` | `tkg_nodes.status` updated | `identity_matcher.py` |
|
||||
|
||||
### Phase Details
|
||||
|
||||
#### Phase 0: Populate
|
||||
|
||||
**Purpose:** Assign `trace_id` to face detections.
|
||||
|
||||
**Flow:**
|
||||
1. Check if `trace_id IS NOT NULL` already exists in `face_detections`
|
||||
2. If not, call `store_traced_faces.py`
|
||||
3. `store_traced_faces.py` runs `face_tracker.py` (IoU-only)
|
||||
4. Update `face_detections.trace_id`
|
||||
|
||||
**Dependency:** `face.json` must exist (from Phase 1)
|
||||
|
||||
---
|
||||
|
||||
#### Phase 1: Extract
|
||||
|
||||
**Purpose:** Generate face embeddings and push to Qdrant.
|
||||
|
||||
**Flow:**
|
||||
1. `face_processor.py` runs Vision detection (ANE)
|
||||
2. Crop faces from video frames
|
||||
3. CoreML FaceNet → 512D embedding
|
||||
4. Push to Qdrant `_faces` collection
|
||||
5. Write `face.json` (metadata only, no embedding)
|
||||
|
||||
**Output:**
|
||||
- `face.json` in output directory
|
||||
- Qdrant `_faces` collection with embeddings
|
||||
|
||||
---
|
||||
|
||||
#### Phase 2: Build Nodes
|
||||
|
||||
**Purpose:** Create TKG nodes from processor outputs.
|
||||
|
||||
**Node Builders:**
|
||||
|
||||
| Builder | Node Type | Data Source |
|
||||
|---------|-----------|-------------|
|
||||
| `build_face_track_nodes` | `face_track` | `face.json`, `face_detections` |
|
||||
| `build_gaze_track_nodes` | `gaze_track` | `face.json` (pose data) |
|
||||
| `build_lip_track_nodes` | `lip_track` | `face.json` (lips), `asrx.json` |
|
||||
| `build_text_region_nodes` | `text_region` | `asrx.json` |
|
||||
| `build_appearance_trace_nodes` | `appearance_trace` | `yolo.json` (person) |
|
||||
| `build_accessory_nodes` | `accessory` | `yolo.json` |
|
||||
| `build_yolo_object_nodes` | `object` | `yolo.json` |
|
||||
| `build_hand_nodes` | `hand` | `pose.json` |
|
||||
| `build_speaker_nodes` | `speaker` | `asrx.json` |
|
||||
|
||||
---
|
||||
|
||||
#### Phase 3: Build Edges
|
||||
|
||||
**Purpose:** Create TKG edges from node relationships.
|
||||
|
||||
**Edge Builders:**
|
||||
|
||||
| Builder | Edge Type | Source → Target |
|
||||
|---------|-----------|-----------------|
|
||||
| `build_co_occurrence_edges` | `co_occurs` | `object ↔ object` |
|
||||
| `build_speaker_face_edges` | `speaker_face` | `speaker ↔ face_track` |
|
||||
| `build_face_face_edges` | `face_face` | `face_track ↔ face_track` |
|
||||
| `build_mutual_gaze_edges` | `mutual_gaze` | `gaze_track ↔ gaze_track` |
|
||||
| `build_lip_sync_edges` | `lip_sync` | `lip_track ↔ text_region` |
|
||||
| `build_has_appearance_edges` | `has_appearance` | `face_track ↔ appearance_trace` |
|
||||
| `build_wears_edges` | `wears` | `face_track ↔ accessory` |
|
||||
| `build_hand_object_edges` | `hand_object` | `hand ↔ object` |
|
||||
|
||||
---
|
||||
|
||||
#### Phase 4: Identity
|
||||
|
||||
**Purpose:** Mark face_track nodes with identity binding status.
|
||||
|
||||
**Flow:**
|
||||
1. Identity Agent queries `_seeds` collection (TMDb/manual/propagation)
|
||||
2. Queries `_faces` collection for trace representatives
|
||||
3. Multi-angle matching (3 reps per trace)
|
||||
4. Mark TKG nodes: `status='suggested'`, `confidence`, `pending_identity_name`
|
||||
5. User confirms → update TKG, Qdrant, PG
|
||||
6. Confirmed trace becomes propagation seed in `_seeds`
|
||||
|
||||
---
|
||||
|
||||
## Node Types (Naming Standardized)
|
||||
|
||||
**Naming Rule:**
|
||||
- All trace types use `_track` suffix
|
||||
- Text uses `_region` (non-temporal)
|
||||
|
||||
| Node Type | External ID Format | Key Properties |
|
||||
|-----------|---------------------|----------------|
|
||||
| `face_track` | `face_track_{trace_id}` | `trace_id`, `frame_count`, `start_frame`, `end_frame`, `avg_bbox`, `status`, `confidence`, `identity_uuid` |
|
||||
| `gaze_track` | `gaze_track_{id}` | `direction` (frontal/left/right/up/down + diagonals) |
|
||||
| `lip_track` | `lip_track_{id}` | `speaker_id`, `lip_area_range` |
|
||||
| `text_region` | `text_region_{id}` | `speaker_id`, `text`, `start_time`, `end_time` |
|
||||
| `appearance_trace` | `appearance_{trace_id}` | `clothing_color`, `upper_cloth`, `lower_cloth` |
|
||||
| `accessory` | `accessory_{id}` | `type` (glasses/hat/etc.), `confidence` |
|
||||
| `object` | `object_{class}_{id}` | `class`, `confidence`, `frame_count` |
|
||||
| `speaker` | `speaker_{speaker_id}` | `speaker_id`, `segment_count`, `total_duration` |
|
||||
|
||||
### face_track Identity Properties
|
||||
|
||||
| Property | Type | Values |
|
||||
|----------|------|--------|
|
||||
| `status` | string | `pending` | `suggested` | `confirmed` | `stranger` |
|
||||
| `pending_identity_name` | string/null | Suggested identity name |
|
||||
| `pending_identity_uuid` | string/null | Suggested identity UUID |
|
||||
| `suggested_by` | string/null | `tmdb` | `propagation` | `manual` |
|
||||
| `confidence` | float/null | Matching score (0.0-1.0) |
|
||||
| `identity_uuid` | string/null | Confirmed identity UUID |
|
||||
| `identity_id` | integer/null | Confirmed PG identity.id |
|
||||
| `identity_ref` | string/null | Reference string (e.g., `file_uuid:identity_1`) |
|
||||
| `stranger_id` | integer/null | Stranger cluster ID |
|
||||
| `stranger_ref` | string/null | Reference string (e.g., `stranger_1`) |
|
||||
|
||||
---
|
||||
|
||||
## Edge Types
|
||||
|
||||
| Edge Type | Storage Name | Source → Target | Properties |
|
||||
|-----------|--------------|-----------------|------------|
|
||||
| `co_occurs` | `CO_OCCURS_WITH` | `object ↔ object` | `frame_count`, `confidence` |
|
||||
| `speaker_face` | `SPEAKS_AS` | `speaker → face_track` | `overlap_frames`, `confidence` |
|
||||
| `face_face` | `INTERACTS_WITH` | `face_track ↔ face_track` | `co_occurrence_frames` |
|
||||
| `mutual_gaze` | `MUTUAL_GAZE` | `gaze_track ↔ gaze_track` | `frame_count` |
|
||||
| `lip_sync` | `LIP_SYNC` | `lip_track → text_region` | `speaker_id` |
|
||||
| `has_appearance` | `HAS_APPEARANCE` | `face_track → appearance_trace` | `frame_count` |
|
||||
| `wears` | `WEARS` | `face_track → accessory` | `confidence` |
|
||||
| `hand_object` | `HOLDS` | `hand → object` | `frame_count`, `confidence` |
|
||||
|
||||
---
|
||||
|
||||
## Data Flow Diagram
|
||||
|
||||
```mermaid
|
||||
graph TB
|
||||
subgraph Phase0[Phase 0: Populate]
|
||||
A[face.json] --> B[store_traced_faces.py]
|
||||
B --> C[PG face_detections.trace_id]
|
||||
end
|
||||
|
||||
subgraph Phase1[Phase 1: Extract]
|
||||
D[Video Frames] --> E[face_processor.py]
|
||||
E --> F[face.json metadata]
|
||||
E --> G[Qdrant _faces 512D]
|
||||
end
|
||||
|
||||
subgraph Phase2[Phase 2: Build Nodes]
|
||||
C --> H[TKG Builder]
|
||||
F --> H
|
||||
I[pose.json] --> H
|
||||
J[asrx.json] --> H
|
||||
K[yolo.json] --> H
|
||||
H --> L[tkg_nodes<br/>9 node types]
|
||||
end
|
||||
|
||||
subgraph Phase3[Phase 3: Build Edges]
|
||||
L --> M[TKG Builder]
|
||||
M --> N[tkg_edges<br/>9 edge types]
|
||||
end
|
||||
|
||||
subgraph Phase4[Phase 4: Identity]
|
||||
G --> O[identity_matcher.py]
|
||||
L --> O
|
||||
P[Qdrant _seeds] --> O
|
||||
O --> Q[mark_tkg_suggested]
|
||||
Q --> L
|
||||
O --> R[confirm_identity.py]
|
||||
R --> L
|
||||
R --> G
|
||||
R --> P
|
||||
end
|
||||
|
||||
style Phase0 fill:#e1f5fe
|
||||
style Phase1 fill:#fff9c4
|
||||
style Phase2 fill:#e8f5e9
|
||||
style Phase3 fill:#f3e5f5
|
||||
style Phase4 fill:#fce4ec
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## SQL Query Examples
|
||||
|
||||
### Status Queries
|
||||
|
||||
```sql
|
||||
-- Get all face_track nodes for a file
|
||||
SELECT id, external_id, label, properties
|
||||
FROM dev.tkg_nodes
|
||||
WHERE node_type = 'face_track' AND file_uuid = 'xxx'
|
||||
ORDER BY external_id;
|
||||
|
||||
-- Get pending faces (no identity suggestion)
|
||||
SELECT id, external_id, properties->>'trace_id' as trace_id
|
||||
FROM dev.tkg_nodes
|
||||
WHERE node_type = 'face_track'
|
||||
AND file_uuid = 'xxx'
|
||||
AND (properties->>'status' IS NULL OR properties->>'status' = 'pending');
|
||||
|
||||
-- Get suggested faces (Identity Agent suggested)
|
||||
SELECT id, external_id,
|
||||
properties->>'pending_identity_name' as name,
|
||||
properties->>'confidence' as confidence,
|
||||
properties->>'suggested_by' as source
|
||||
FROM dev.tkg_nodes
|
||||
WHERE node_type = 'face_track'
|
||||
AND file_uuid = 'xxx'
|
||||
AND properties->>'status' = 'suggested'
|
||||
ORDER BY (properties->>'confidence')::float DESC;
|
||||
|
||||
-- Get confirmed faces
|
||||
SELECT id, external_id,
|
||||
properties->>'identity_uuid' as identity_uuid,
|
||||
properties->>'identity_name' as name
|
||||
FROM dev.tkg_nodes
|
||||
WHERE node_type = 'face_track'
|
||||
AND file_uuid = 'xxx'
|
||||
AND properties->>'status' = 'confirmed';
|
||||
|
||||
-- Get stranger cluster members
|
||||
SELECT id, external_id, properties->>'stranger_id' as cluster
|
||||
FROM dev.tkg_nodes
|
||||
WHERE node_type = 'face_track'
|
||||
AND file_uuid = 'xxx'
|
||||
AND properties->>'status' = 'stranger'
|
||||
ORDER BY (properties->>'stranger_id')::int;
|
||||
```
|
||||
|
||||
### Identity Queries
|
||||
|
||||
```sql
|
||||
-- Find all traces bound to an identity
|
||||
SELECT id, external_id, properties->>'trace_id' as trace_id
|
||||
FROM dev.tkg_nodes
|
||||
WHERE node_type = 'face_track'
|
||||
AND properties->>'identity_uuid' = 'xxx-xxx';
|
||||
|
||||
-- Count identities per file
|
||||
SELECT properties->>'identity_uuid' as identity_uuid,
|
||||
COUNT(*) as trace_count
|
||||
FROM dev.tkg_nodes
|
||||
WHERE node_type = 'face_track'
|
||||
AND file_uuid = 'xxx'
|
||||
AND properties->>'status' = 'confirmed'
|
||||
GROUP BY properties->>'identity_uuid';
|
||||
```
|
||||
|
||||
### Statistics Queries
|
||||
|
||||
```sql
|
||||
-- Status distribution for a file
|
||||
SELECT properties->>'status' as status, COUNT(*) as count
|
||||
FROM dev.tkg_nodes
|
||||
WHERE node_type = 'face_track' AND file_uuid = 'xxx'
|
||||
GROUP BY properties->>'status';
|
||||
|
||||
-- Confidence distribution
|
||||
SELECT
|
||||
CASE
|
||||
WHEN (properties->>'confidence')::float >= 0.9 THEN 'high'
|
||||
WHEN (properties->>'confidence')::float >= 0.7 THEN 'medium'
|
||||
ELSE 'low'
|
||||
END as confidence_level,
|
||||
COUNT(*) as count
|
||||
FROM dev.tkg_nodes
|
||||
WHERE node_type = 'face_track'
|
||||
AND file_uuid = 'xxx'
|
||||
AND properties->>'status' = 'suggested'
|
||||
GROUP BY confidence_level;
|
||||
|
||||
-- Top suggested identities
|
||||
SELECT properties->>'pending_identity_name' as name,
|
||||
COUNT(*) as trace_count,
|
||||
AVG((properties->>'confidence')::float) as avg_confidence
|
||||
FROM dev.tkg_nodes
|
||||
WHERE node_type = 'face_track'
|
||||
AND properties->>'status' = 'suggested'
|
||||
GROUP BY properties->>'pending_identity_name'
|
||||
ORDER BY trace_count DESC
|
||||
LIMIT 10;
|
||||
```
|
||||
|
||||
### Cross-node Queries
|
||||
|
||||
```sql
|
||||
-- Speaker ↔ face_track edges
|
||||
SELECT
|
||||
s.external_id as speaker,
|
||||
f.external_id as face_track,
|
||||
e.properties->>'overlap_frames' as overlap
|
||||
FROM dev.tkg_edges e
|
||||
JOIN dev.tkg_nodes s ON e.source_node_id = s.id
|
||||
JOIN dev.tkg_nodes f ON e.target_node_id = f.id
|
||||
WHERE e.file_uuid = 'xxx'
|
||||
AND e.edge_type = 'SPEAKS_AS';
|
||||
|
||||
-- Objects co-occurrence
|
||||
SELECT
|
||||
o1.external_id as obj1,
|
||||
o2.external_id as obj2,
|
||||
e.properties->>'frame_count' as co_frames
|
||||
FROM dev.tkg_edges e
|
||||
JOIN dev.tkg_nodes o1 ON e.source_node_id = o1.id
|
||||
JOIN dev.tkg_nodes o2 ON e.target_node_id = o2.id
|
||||
WHERE e.file_uuid = 'xxx'
|
||||
AND e.edge_type = 'CO_OCCURS_WITH'
|
||||
ORDER BY (e.properties->>'frame_count')::int DESC;
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Integration with Identity Agent
|
||||
|
||||
### Identity Agent Flow
|
||||
|
||||
```
|
||||
Identity Agent Pipeline:
|
||||
│
|
||||
├─ Round 1 (TH=0.55):
|
||||
│ Query _seeds (source='tmdb')
|
||||
│ Query _faces (file_uuid) → get trace representatives
|
||||
│ Multi-angle match → suggestions
|
||||
│ Mark TKG: status='suggested', confidence
|
||||
│
|
||||
├─ User Confirmation:
|
||||
│ Update TKG: status='confirmed'
|
||||
│ Update _faces: identity_uuid for all points
|
||||
│ Update PG face_detections: identity_id
|
||||
│ Add _seeds: source='propagation'
|
||||
│
|
||||
├─ Round 2 (TH=0.55):
|
||||
│ Use confirmed traces as seeds
|
||||
│ Match remaining pending traces
|
||||
│
|
||||
└─ Round 3+ (TH=0.50):
|
||||
Continue propagation
|
||||
Stranger clustering (TH=0.40)
|
||||
```
|
||||
|
||||
### TKG Node Status Transitions
|
||||
|
||||
```
|
||||
pending → suggested → confirmed → (final)
|
||||
↘ stranger ↘ (final)
|
||||
```
|
||||
|
||||
### Status Transition Triggers
|
||||
|
||||
| Transition | Trigger | Action |
|
||||
|------------|---------|--------|
|
||||
| `pending → suggested` | Identity Agent Round 1-3 | `mark_face_track_suggested()` |
|
||||
| `suggested → confirmed` | User confirmation API | `mark_face_track_confirmed()` |
|
||||
| `pending → stranger` | Stranger clustering | `mark_face_track_stranger()` |
|
||||
| `confirmed → pending` | Undo binding | `clear_face_track_status()` |
|
||||
|
||||
---
|
||||
|
||||
## Version History
|
||||
|
||||
| Version | Date | Changes |
|
||||
|---------|------|---------|
|
||||
| 1.0 | 2026-06-25 | Initial version with Phase 0-4 definition, node naming, flow diagram, query examples |
|
||||
@@ -0,0 +1,816 @@
|
||||
# TKG Multi-Trace Design V1.0
|
||||
|
||||
**Date**: 2026-06-19
|
||||
**Version**: 1.0.0
|
||||
**Status**: Draft
|
||||
|
||||
---
|
||||
|
||||
## Overview
|
||||
|
||||
統一 8Hz 採樣框架,整合 face、appearance、gaze、lip 四條 trace,並接入 sentence/speaker/accessory 節點,構建完整的 Temporal Knowledge Graph (TKG)。
|
||||
|
||||
### 設計目標
|
||||
|
||||
1. **時間對齊**: 所有 trace 在同一 8Hz 網格上,edge 計算無需插值
|
||||
2. **按需細化**: 特定特徵 (blink, lip-sync, mutual gaze) 可局部提高採樣率
|
||||
3. **配件偵測**: 49 種配件分類 (頭部 12 + 脖子 5 + 手部 16 + 足部 8 + 攜帶 5 + 色彩 3)
|
||||
4. **膚色 + 光源**: Fitzpatrick 分類 + 光照參數,支援可信度評估
|
||||
5. **社交互動**: Mutual gaze (互相看), lip-sync (唇語同步), speaker-face 綁定
|
||||
|
||||
---
|
||||
|
||||
## 1. 8Hz 採樣框架
|
||||
|
||||
### 1.1 基本原理
|
||||
|
||||
```
|
||||
影片 FPS: ~30
|
||||
Sample Interval: round(fps / 8) = 4
|
||||
Sample Frames: 0, 4, 8, 12, 16, ...
|
||||
```
|
||||
|
||||
| 影片長度 | 總幀數 | 8Hz 樣本數 |
|
||||
|----------|--------|------------|
|
||||
| 5 分鐘 | 9,000 | ~2,250 |
|
||||
| 10 分鐘 | 18,000 | ~4,500 |
|
||||
| 30 分鐘 | 54,000 | ~13,500 |
|
||||
|
||||
### 1.2 按需細化機制
|
||||
|
||||
```
|
||||
Layer 1: 8Hz 基底 (所有 processor)
|
||||
↓
|
||||
Layer 2: 細化 (特定特徵觸發)
|
||||
|
||||
細化場景:
|
||||
- Blink 確認: 8Hz 發現 eye openness 突降 → 回頭抓前後 ±4 幀 (30Hz)
|
||||
- Lip-sync: sentence chunk 覆蓋的時間段 → 16Hz
|
||||
- Mutual Gaze: 兩人 gaze 方向接近 → 前後 ±2 幀 (30Hz) 確認
|
||||
```
|
||||
|
||||
### 1.3 樣本幀計算
|
||||
|
||||
```rust
|
||||
// worker/processor.rs
|
||||
fn compute_sample_frames(total_frames: i64, fps: f64) -> Vec<i64> {
|
||||
let interval = (fps / 8.0).round() as i64;
|
||||
(0..total_frames).step_by(interval.max(1) as usize).collect()
|
||||
}
|
||||
|
||||
fn merge_refine_frames(base: &[i64], refine: &HashSet<i64>) -> Vec<i64> {
|
||||
let mut combined: HashSet<i64> = base.iter().cloned().collect();
|
||||
combined.extend(refine.iter().cloned());
|
||||
let mut sorted: Vec<i64> = combined.into_iter().collect();
|
||||
sorted.sort();
|
||||
sorted
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 2. Trace 類型
|
||||
|
||||
### 重要 Trace 總覽
|
||||
|
||||
| # | Trace 類型 | 來源 | 用途 |
|
||||
|---|-----------|------|------|
|
||||
| 1 | **face_trace** | face_detections + face.json | 人臉追蹤、身份識別 |
|
||||
| 2 | **appearance_trace** | appearance.json | 服裝色彩、配件、膚色 |
|
||||
| 3 | **gaze_trace** | face.json (pose_angle + landmarks) | 視線方向、互相看 |
|
||||
| 4 | **lip_trace** | face.json (landmarks) | 唇型、說話同步 |
|
||||
| 5 | **speaker_trace** | asrx.json (speaker diarization) | 說話者識別 |
|
||||
| 6 | **text_trace** | dev.chunk (sentence chunks) | 文字內容、語意 |
|
||||
| 7 | **skin_tone_trace** | face.json (ROI HSV) | 膚色分類、光源記錄 |
|
||||
|
||||
---
|
||||
|
||||
### 2.1 Face Trace (已有)
|
||||
|
||||
```json
|
||||
{
|
||||
"node_type": "face_trace",
|
||||
"external_id": "trace_5",
|
||||
"properties": {
|
||||
"frame_count": 200,
|
||||
"start_frame": 150,
|
||||
"end_frame": 350,
|
||||
"avg_bbox": { "x": 500, "y": 300, "width": 200, "height": 250 },
|
||||
"avg_yaw": -0.15,
|
||||
"avg_pitch": -0.08,
|
||||
"avg_roll": -0.20,
|
||||
"pose_count": 180,
|
||||
"embedding": [...],
|
||||
"skin_tone": {
|
||||
"face_h_mean": 18.5,
|
||||
"fitzpatrick": "Type IV - Medium",
|
||||
"confidence": 0.82,
|
||||
"lighting": {
|
||||
"brightness": 0.65,
|
||||
"color_temp": "warm",
|
||||
"direction": "front",
|
||||
"uniformity": 0.92,
|
||||
"source": "indoor",
|
||||
"quality": "good"
|
||||
},
|
||||
"sample_frames": 156
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### 2.2 Appearance Trace (新增)
|
||||
|
||||
**綁定策略**: IoU 匹配 appearance person ↔ face detection,繼承 trace_id
|
||||
|
||||
```json
|
||||
{
|
||||
"node_type": "appearance_trace",
|
||||
"external_id": "trace_5",
|
||||
"properties": {
|
||||
"trace_id": 5,
|
||||
"frame_count": 400,
|
||||
"start_frame": 100,
|
||||
"end_frame": 500,
|
||||
"face_overlap_frames": 200,
|
||||
"confidence": 0.50,
|
||||
"color_features": {
|
||||
"dominant_colors": [[0.1, 0.6, 0.8], ...],
|
||||
"upper_body_hsv": [[...], [...], [...]],
|
||||
"lower_body_hsv": [[...], [...], [...]]
|
||||
},
|
||||
"accessories": {
|
||||
"head": {
|
||||
"hat": {"detected": true, "confidence": 0.82, "first_frame": 0},
|
||||
"glasses": {"detected": true, "confidence": 0.67, "first_frame": 0},
|
||||
"earrings": {"detected": false},
|
||||
"mask": {"detected": false},
|
||||
"hairstyle": {"type": "long", "confidence": 0.75},
|
||||
"hair_accessory": {"detected": false},
|
||||
"nose_ring": {"detected": false},
|
||||
"lip_ring": {"detected": false},
|
||||
"face_tattoo": {"detected": false},
|
||||
"eyebrow_tattoo": {"detected": false},
|
||||
"beard": {"detected": true, "confidence": 0.88},
|
||||
"headscarf": {"detected": false}
|
||||
},
|
||||
"neck": {
|
||||
"tie": {"detected": true, "confidence": 0.92, "first_frame": 0, "source": "hsv_color_block"},
|
||||
"scarf": {"detected": false},
|
||||
"shawl": {"detected": false},
|
||||
"necklace": {"detected": true, "confidence": 0.71, "first_frame": 12, "source": "clip"},
|
||||
"neck_tattoo": {"detected": false}
|
||||
},
|
||||
"hand": {
|
||||
"ring": {"detected": false},
|
||||
"bracelet": {"detected": false},
|
||||
"watch": {"detected": true, "confidence": 0.63, "first_frame": 24},
|
||||
"gloves": {"detected": false}
|
||||
},
|
||||
"hand_held": {
|
||||
"phone": {"detected": true, "confidence": 0.88, "source": "hsv_color_block"},
|
||||
"pen": {"detected": false},
|
||||
"cup": {"detected": false},
|
||||
"knife": {"detected": false},
|
||||
"gun": {"detected": false}
|
||||
},
|
||||
"foot": {
|
||||
"shoes": {"type": "sneaker", "confidence": 0.78, "source": "hsv_color_block"},
|
||||
"socks": {"detected": false},
|
||||
"barefoot": {"detected": false}
|
||||
},
|
||||
"vehicle": {
|
||||
"bicycle": {"detected": false, "source": "hsv_color_block"},
|
||||
"skateboard": {"detected": false},
|
||||
"scooter": {"detected": false}
|
||||
},
|
||||
"carried": {
|
||||
"backpack": {"detected": false},
|
||||
"handbag": {"detected": true, "confidence": 0.85, "source": "hsv_color_block"},
|
||||
"luggage": {"detected": false}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### 2.3 Speaker Trace (重要)
|
||||
|
||||
**來源**: ASRX speaker diarization + face trace 綁定
|
||||
|
||||
```json
|
||||
{
|
||||
"node_type": "speaker_trace",
|
||||
"external_id": "SPEAKER_0",
|
||||
"properties": {
|
||||
"speaker_id": "SPEAKER_0",
|
||||
"segment_count": 45,
|
||||
"total_duration": 120.5,
|
||||
"first_appearance": {"frame": 100, "time": 3.3},
|
||||
"last_appearance": {"frame": 3600, "time": 120.0},
|
||||
"full_text": "大家好 今天我們來討論... (完整語音轉文字)",
|
||||
"segments": [
|
||||
{"start_time": 0.1, "end_time": 2.0, "text": "大家好", "start_frame": 3, "end_frame": 60},
|
||||
{"start_time": 5.2, "end_time": 8.5, "text": "今天我們來討論", "start_frame": 156, "end_frame": 255},
|
||||
...
|
||||
],
|
||||
"face_trace_ids": [5, 12, 23],
|
||||
"appearance_trace_ids": [5, 12],
|
||||
"gaze_context": {
|
||||
"looking_at_person": true,
|
||||
"mutual_gaze_with": [12]
|
||||
},
|
||||
"lip_sync_quality": 0.85
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**來源資料**:
|
||||
```
|
||||
ASRX → asrx.json (segments with speaker_id)
|
||||
Face → face_detections (trace_id)
|
||||
綁定 → SPEAKS_AS edge (speaker ↔ face_trace)
|
||||
```
|
||||
|
||||
### 2.4 Text Trace (重要)
|
||||
|
||||
**來源**: dev.chunk (chunk_type='sentence') + ASRX text
|
||||
|
||||
```json
|
||||
{
|
||||
"node_type": "text_trace",
|
||||
"external_id": "chunk_1",
|
||||
"properties": {
|
||||
"chunk_id": "chunk_1",
|
||||
"text": "大家好,今天我們來討論這個話題",
|
||||
"text_normalized": "大家好,今天我們來討論這個話題",
|
||||
"start_time": 0.1,
|
||||
"end_time": 5.2,
|
||||
"start_frame": 3,
|
||||
"end_frame": 156,
|
||||
"speaker_id": "SPEAKER_0",
|
||||
"language": "zh",
|
||||
"confidence": 0.95,
|
||||
"yolo_objects": ["person", "chair"],
|
||||
"face_ids": ["face_100"],
|
||||
"speaker_trace_id": "SPEAKER_0",
|
||||
"face_trace_id": 5,
|
||||
"lip_sync": {
|
||||
"matched_frames": 120,
|
||||
"total_frames": 153,
|
||||
"quality": 0.85
|
||||
},
|
||||
"semantic_embedding": [0.12, -0.34, ...],
|
||||
"sentiment": "neutral"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**來源資料**:
|
||||
```
|
||||
Rule 1 → dev.chunk (sentence chunks)
|
||||
ASRX → asrx.json (speaker_id binding)
|
||||
Face → face_detections (face_ids in chunk metadata)
|
||||
YOLO → yolo.json (co-occurring objects)
|
||||
```
|
||||
|
||||
**Edge 連接**:
|
||||
- `SPEAKS_BY`: text_trace → speaker_trace
|
||||
- `SPOKEN_WHILE`: text_trace → face_trace
|
||||
- `LIP_SYNC`: text_trace → lip_trace
|
||||
- `CONTAINS_OBJECT`: text_trace → object
|
||||
|
||||
### 2.5 Skin Tone Trace (重要)
|
||||
|
||||
**來源**: face.json ROI HSV + 光源分析
|
||||
|
||||
```json
|
||||
{
|
||||
"node_type": "skin_tone_trace",
|
||||
"external_id": "trace_5",
|
||||
"properties": {
|
||||
"trace_id": 5,
|
||||
"frame_count": 200,
|
||||
"start_frame": 150,
|
||||
"end_frame": 350,
|
||||
"face_h_mean": 18.5,
|
||||
"fitzpatrick": "Type IV - Medium",
|
||||
"confidence": 0.82,
|
||||
"lighting": {
|
||||
"brightness": 0.65,
|
||||
"color_temp": "warm",
|
||||
"direction": "front",
|
||||
"uniformity": 0.92,
|
||||
"source": "indoor",
|
||||
"quality": "good"
|
||||
},
|
||||
"sample_frames": 156,
|
||||
"hand_h_mean": 17.8,
|
||||
"arm_h_mean": 18.2
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**Fitzpatrick 分類**:
|
||||
|
||||
| Type | 描述 | H 值 (HSV) |
|
||||
|------|------|------------|
|
||||
| I | 非常淺 | 0–5 |
|
||||
| II | 淺 | 5–12 |
|
||||
| III | 中等偏淺 | 12–18 |
|
||||
| IV | 中等 | 18–25 |
|
||||
| V | 深 | 25–35 |
|
||||
| VI | 很深 | 35+ |
|
||||
|
||||
**光源品質**:
|
||||
|
||||
| Quality | 條件 | 膚色可信度 |
|
||||
|---------|------|------------|
|
||||
| good | brightness > 0.4, uniformity > 0.8, front light | 高 (×1.0) |
|
||||
| fair | brightness > 0.3, uniformity > 0.6 | 中 (×0.7) |
|
||||
| poor | brightness < 0.3 或 backlight | 低 (×0.5) |
|
||||
|
||||
### 2.6 Gaze Trace (新增)
|
||||
|
||||
```json
|
||||
{
|
||||
"node_type": "gaze_trace",
|
||||
"external_id": "trace_5",
|
||||
"properties": {
|
||||
"trace_id": 5,
|
||||
"frame_count": 200,
|
||||
"start_frame": 150,
|
||||
"end_frame": 350,
|
||||
"avg_yaw": -0.15,
|
||||
"avg_pitch": -0.08,
|
||||
"avg_roll": -0.20,
|
||||
"head_direction": "frontal",
|
||||
"gaze_direction": "center-left",
|
||||
"eye_openness": 0.85,
|
||||
"blink_count": 12,
|
||||
"blink_rate": 0.06,
|
||||
"looking_at_person": true,
|
||||
"looking_at_object": ["chair"],
|
||||
"refined_ranges": [
|
||||
{"start_frame": 200, "end_frame": 220, "hz": 30, "reason": "mutual_gaze"}
|
||||
]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### 2.7 Lip Trace (重要)
|
||||
|
||||
**來源**: face.json → faces[].lips (inner_lips 6pts + outer_lips 14pts)
|
||||
|
||||
```json
|
||||
{
|
||||
"node_type": "lip_trace",
|
||||
"external_id": "trace_5",
|
||||
"properties": {
|
||||
"trace_id": 5,
|
||||
"frame_count": 180,
|
||||
"start_frame": 160,
|
||||
"end_frame": 340,
|
||||
"avg_openness": 0.3,
|
||||
"avg_width": 45.2,
|
||||
"avg_height": 12.8,
|
||||
"movement_variance": 0.15,
|
||||
"speaking_frames": 95,
|
||||
"silent_frames": 85,
|
||||
"lip_landmark_samples": {
|
||||
"inner_lips": [[x,y,z], ...],
|
||||
"outer_lips": [[x,y,z], ...]
|
||||
},
|
||||
"speech_correlation": {
|
||||
"text_trace_ids": ["chunk_1", "chunk_2", "chunk_3"],
|
||||
"sync_quality": 0.85,
|
||||
"matched_segments": [
|
||||
{"start_frame": 160, "end_frame": 200, "text": "大家好"},
|
||||
{"start_frame": 210, "end_frame": 250, "text": "今天我們來討論"}
|
||||
]
|
||||
},
|
||||
"refined_ranges": [
|
||||
{"start_frame": 160, "end_frame": 340, "hz": 30, "reason": "lip_sync"}
|
||||
]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**Lip-sync 計算**:
|
||||
|
||||
```
|
||||
Lip openness = inner_lips_area / outer_lips_area
|
||||
|
||||
Speaking detection:
|
||||
- openness > threshold (動態調整)
|
||||
- movement_variance > threshold (唇型變化)
|
||||
- 持續 N 幀以上 (避免雜訊)
|
||||
|
||||
Sync with text:
|
||||
- 比對 text_trace 的 start/end_time
|
||||
- 計算 lip movement 與文字時間段的重疊率
|
||||
- quality = matched_frames / total_text_frames
|
||||
```
|
||||
|
||||
**Edge 連接**:
|
||||
- `HAS_LIP`: face_trace → lip_trace
|
||||
- `LIP_SYNC`: lip_trace → text_trace
|
||||
- `GAZE_SYNC_SPEECH`: gaze_trace + lip_trace (說話時注視方向)
|
||||
|
||||
---
|
||||
|
||||
## 3. 配件偵測
|
||||
|
||||
### 3.1 偵測方式分工
|
||||
|
||||
| 方式 | 適用配件 | 速度 | 說明 |
|
||||
|------|----------|------|------|
|
||||
| **HSV 色塊** | tie, phone, watch, ring, bracelet, glasses, mask, hat, shoes, backpack, handbag, umbrella, pen, knife, cup, book, laptop, remote, baseball_bat | 快 | **主要方式** — 從 person crop 分析異色區塊 |
|
||||
| **CLIP** | hairstyle, beard, face_tattoo, eyebrow_tattoo, earrings, nose_ring, lip_ring, neck_tattoo, headscarf, scarf, shawl, necklace, gloves, tool, gun, skateboard, scooter, roller_skates, socks, barefoot | 中 | zero-shot (YOLO 不可靠,色塊也不易區分時) |
|
||||
| **MediaPipe** | gesture, arm_pose | 快 | 21 hand pts + 33 pose pts |
|
||||
| **HSV** | upper_body_color, lower_body_color, skin_tone | 快 | 色彩特徵提取 |
|
||||
|
||||
### 3.2 Appearance 與 Landmark/Pose 緊密貼合
|
||||
|
||||
**核心原則**: Appearance 不獨立偵測 bbox,而是直接用 face/pose/mediapipe 的幾何結果裁切 ROI。
|
||||
|
||||
```
|
||||
Face Landmarks (20pts) ──► 臉部 ROI ──► hat, glasses, mask, beard, earrings
|
||||
Pose 33 Keypoints ───────► 身體 ROI ──► tie, necklace, upper/lower body HSV
|
||||
MediaPipe Hands (21×2) ──► 手腕 ROI ──► watch, bracelet, ring, phone, glove
|
||||
MediaPipe Pose Feet ─────► 腳部 ROI ──► shoes, socks, barefoot
|
||||
```
|
||||
|
||||
**ROI 定位方式**:
|
||||
|
||||
```python
|
||||
def get_accessory_rois(frame, face_data, pose_data, hand_data):
|
||||
rois = {}
|
||||
|
||||
# 臉部區域 — 用 face bbox + landmarks
|
||||
face_bbox = face_data['bbox']
|
||||
landmarks = face_data['landmarks'] # nose, left_eye, right_eye
|
||||
|
||||
# 帽子 ROI: 臉部 bbox 上方延伸
|
||||
rois['hat'] = expand_region(face_bbox, direction='up', factor=0.5)
|
||||
|
||||
# 眼鏡 ROI: 眼部 landmarks 水平帶
|
||||
left_eye = landmarks['left_eye']
|
||||
right_eye = landmarks['right_eye']
|
||||
rois['glasses'] = bbox_around_points(left_eye, right_eye, padding=10)
|
||||
|
||||
# 口罩 ROI: 鼻子下方到下顎
|
||||
nose = landmarks['nose']
|
||||
rois['mask'] = region_below_point(nose, face_bbox.bottom)
|
||||
|
||||
# 脖子 ROI — 用 pose neck keypoints
|
||||
if pose_data:
|
||||
neck = pose_data['keypoints']['neck']
|
||||
nose = pose_data['keypoints']['nose']
|
||||
rois['neck'] = region_between(nose, neck, width=80)
|
||||
|
||||
# 手腕 ROI — 用 MediaPipe hand landmarks
|
||||
if hand_data:
|
||||
for side in ['left', 'right']:
|
||||
wrist = hand_data[side]['wrist']
|
||||
rois[f'{side}_wrist'] = circle_around(wrist, radius=30)
|
||||
|
||||
# 腳部 ROI — 用 pose ankle/toe keypoints
|
||||
if pose_data:
|
||||
for side in ['left', 'right']:
|
||||
ankle = pose_data['keypoints'][f'{side}_ankle']
|
||||
toe = pose_data['keypoints'][f'{side}_toe']
|
||||
rois[f'{side}_foot'] = bbox_around_points(ankle, toe, padding=20)
|
||||
|
||||
return rois
|
||||
```
|
||||
|
||||
### 3.3 HSV 色塊偵測流程
|
||||
|
||||
```python
|
||||
def detect_accessories_tightly_coupled(frame, face_data, pose_data, hand_data):
|
||||
# 1. 用 landmark/pose 精準定位各 ROI
|
||||
rois = get_accessory_rois(frame, face_data, pose_data, hand_data)
|
||||
|
||||
results = {}
|
||||
for roi_name, roi_bbox in rois.items():
|
||||
roi_hsv = crop_and_convert(frame, roi_bbox, 'HSV')
|
||||
|
||||
# 2. 在精準 ROI 內找異色區塊
|
||||
diff_mask = compute_color_diff(roi_hsv, main_colors, threshold=30)
|
||||
blobs = find_connected_components(diff_mask)
|
||||
|
||||
for blob in blobs:
|
||||
accessory = classify_accessory_by_position(blob, roi_name)
|
||||
if accessory:
|
||||
results[accessory] = {
|
||||
"detected": True,
|
||||
"confidence": blob.confidence,
|
||||
"source": "hsv_color_block",
|
||||
"roi": roi_name,
|
||||
"first_frame": current_frame
|
||||
}
|
||||
|
||||
# 3. 色塊不易判斷的項目 → CLIP
|
||||
clip_only_items = ['hairstyle', 'beard', 'earrings', 'nose_ring', ...]
|
||||
for item in clip_only_items:
|
||||
confidence = clip_score(crop_person(frame, face_data['bbox']), CLIP_PROMPTS[item])
|
||||
if confidence > 0.5:
|
||||
results[item] = {"detected": True, "confidence": confidence, "source": "clip"}
|
||||
|
||||
return results
|
||||
```
|
||||
|
||||
### 3.4 依賴關係
|
||||
|
||||
```
|
||||
Face Detection ──► face_detections (trace_id, bbox, embedding)
|
||||
│
|
||||
▼
|
||||
Face Landmarks ────► 臉部 ROI (hat, glasses, mask, beard)
|
||||
│
|
||||
▼
|
||||
Pose 33pts ────────► 身體 ROI (neck, wrist, foot) ──► Appearance HSV
|
||||
│
|
||||
▼
|
||||
MediaPipe Hands ───► 手腕 ROI (watch, bracelet, ring, phone)
|
||||
│
|
||||
▼
|
||||
TKG appearance_trace
|
||||
```
|
||||
|
||||
### 3.5 CLIP 提示詞 (僅用於色塊不易區分的配件)
|
||||
|
||||
```python
|
||||
CLIP_PROMPTS = {
|
||||
# 頭部 — 色塊不易判斷的項目
|
||||
"hairstyle_short": "a person with short hair",
|
||||
"hairstyle_long": "a person with long hair",
|
||||
"hairstyle_braid": "a person with braided hair",
|
||||
"hairstyle_bun": "a person with hair in a bun",
|
||||
"face_tattoo": "a person with a visible face tattoo or face paint",
|
||||
"eyebrow_tattoo": "a person with tattooed or styled eyebrows",
|
||||
"beard": "a person with a beard or mustache",
|
||||
|
||||
# 耳朵/鼻子/嘴唇穿刺
|
||||
"earrings": "a person wearing earrings",
|
||||
"nose_ring": "a person wearing a nose ring or nose piercing",
|
||||
"lip_ring": "a person wearing a lip ring or lip piercing",
|
||||
|
||||
# 脖子 — 項鍊等細小物件
|
||||
"necklace": "a person wearing a necklace",
|
||||
"neck_tattoo": "a person with a visible neck tattoo",
|
||||
|
||||
# 手部細小物件
|
||||
"gloves": "a person wearing gloves",
|
||||
"tool": "a person holding a tool like a wrench or screwdriver",
|
||||
"gun": "a person holding a gun",
|
||||
|
||||
# 足部
|
||||
"socks": "a person wearing visible socks",
|
||||
"barefoot": "a barefoot person",
|
||||
"roller_skates": "a person wearing roller skates",
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 4. 膚色 + 光源
|
||||
|
||||
### 4.1 Fitzpatrick 分類
|
||||
|
||||
| Type | 描述 | H 值 (HSV) |
|
||||
|------|------|------------|
|
||||
| I | 非常淺 | 0–5 |
|
||||
| II | 淺 | 5–12 |
|
||||
| III | 中等偏淺 | 12–18 |
|
||||
| IV | 中等 | 18–25 |
|
||||
| V | 深 | 25–35 |
|
||||
| VI | 很深 | 35+ |
|
||||
|
||||
### 4.2 光源參數
|
||||
|
||||
| 參數 | 計算方式 | 範圍 |
|
||||
|------|----------|------|
|
||||
| brightness | V channel 平均 | 0.0–1.0 |
|
||||
| color_temp | 白平衡估算 | warm/neutral/cool |
|
||||
| direction | 陰影梯度 + yaw/pitch | front/side/back/top |
|
||||
| uniformity | 臉部各區域 V 值標準差 | 0.0–1.0 |
|
||||
| source | 亮度 + 色溫綜合判斷 | indoor/outdoor/flash |
|
||||
|
||||
### 4.3 光源品質
|
||||
|
||||
| Quality | 條件 | 膚色可信度 |
|
||||
|---------|------|------------|
|
||||
| good | brightness > 0.4, uniformity > 0.8, front light | 高 (×1.0) |
|
||||
| fair | brightness > 0.3, uniformity > 0.6 | 中 (×0.7) |
|
||||
| poor | brightness < 0.3 或 backlight | 低 (×0.5) |
|
||||
|
||||
---
|
||||
|
||||
## 5. TKG Node 類型
|
||||
|
||||
| node_type | external_id | 來源 | 重要性 | 屬性 |
|
||||
|-----------|-------------|------|--------|------|
|
||||
| `face_trace` | `trace_N` | face_detections | ★★★★ | frame_count, bbox, pose, embedding, skin_tone |
|
||||
| `appearance_trace` | `trace_N` | appearance.json | ★★★★ | trace_id, color_features, accessories, confidence |
|
||||
| `gaze_trace` | `trace_N` | face.json (pose_angle) | ★★★ | trace_id, gaze_direction, blink_count, looking_at |
|
||||
| `lip_trace` | `trace_N` | face.json (lips) | ★★★★ | trace_id, avg_openness, speaking_frames, speech_correlation |
|
||||
| `speaker_trace` | `SPEAKER_N` | asrx.json | ★★★★ | speaker_id, segments, face_trace_ids, full_text |
|
||||
| `text_trace` | `chunk_N` | dev.chunk | ★★★★ | text, speaker_id, time_range, yolo_objects, lip_sync |
|
||||
| `skin_tone_trace` | `trace_N` | face.json (ROI HSV) | ★★★ | trace_id, fitzpatrick, lighting, confidence |
|
||||
| `object` | `class_name` | yolo.json | ★★ | total_detections, frames |
|
||||
| `accessory` | `hat`, `glasses`, ... | appearance.json | ★★ | category, trace_ids, first/last_seen |
|
||||
|
||||
---
|
||||
|
||||
## 6. TKG Edge 類型
|
||||
|
||||
| Edge Type | Source → Target | 屬性 | 說明 |
|
||||
|-----------|----------------|------|------|
|
||||
| `SPEAKS_AS` | speaker_trace → face_trace | confidence, overlap_frames | 說話者綁定人臉 |
|
||||
| `SPEAKS_BY` | text_trace → speaker_trace | — | 文字由誰說的 |
|
||||
| `SPOKEN_WHILE` | text_trace → face_trace | frame_overlap | 說話時的人臉 |
|
||||
| `HAS_APPEARANCE` | face_trace → appearance_trace | confidence, overlap_frames | 外觀特徵 |
|
||||
| `HAS_GAZE` | face_trace → gaze_trace | overlap_frames | 視線方向 |
|
||||
| `HAS_LIP` | face_trace → lip_trace | overlap_frames | 唇型資料 |
|
||||
| `HAS_SKIN_TONE` | face_trace → skin_tone_trace | confidence, lighting_match | 膚色記錄 |
|
||||
| `LIP_SYNC` | lip_trace → text_trace | time_alignment, openness_match | 唇語同步 |
|
||||
| `WEARS` | appearance_trace → accessory | confidence, first_frame | 配件 |
|
||||
| `LOOKING_AT` | gaze_trace → object | direction_match, distance | 注視物件 |
|
||||
| `LOOKING_AT_PERSON` | gaze_trace → face_trace | direction_match | 注視他人 |
|
||||
| `MUTUAL_GAZE` | face_trace ↔ face_trace | first_frame, last_frame, duration_frames, confidence | 互相看 |
|
||||
| `CO_OCCURS_WITH` | object ↔ object | frame_count | 物件共現 |
|
||||
| `SAME_SKIN_TONE` | face_trace ↔ face_trace | h_diff, lighting_match, confidence | 膚色相近 |
|
||||
| `HOLDS` | appearance_trace → object | 手機等手持物品 |
|
||||
|
||||
---
|
||||
|
||||
## 7. Mutual Gaze 分析
|
||||
|
||||
### 7.1 計算邏輯
|
||||
|
||||
```
|
||||
對每幀:
|
||||
對每對 (person_A, person_B):
|
||||
1. 計算 A 的 gaze vector (從 yaw/pitch/roll)
|
||||
2. 計算 B 的 bbox center 在 A 座標系中的位置
|
||||
3. 判斷 B 是否在 A 的 gaze cone 內 (threshold: ~15°)
|
||||
4. 反向檢查 B → A
|
||||
5. 雙向命中 → mutual_gaze
|
||||
```
|
||||
|
||||
### 7.2 持續性確認
|
||||
|
||||
```
|
||||
mutual_gaze 需要持續 N 幀以上才算有意義:
|
||||
- 基底: 8Hz, 持續 ≥ 3 幀 (~0.375s) → 建立 edge
|
||||
- 細化: 發現 candidate 後,回頭用 30Hz 確認
|
||||
- confidence = 連續幀數 / 總可能幀數
|
||||
```
|
||||
|
||||
### 7.3 Edge 屬性
|
||||
|
||||
```json
|
||||
{
|
||||
"edge_type": "MUTUAL_GAZE",
|
||||
"source": "trace_5",
|
||||
"target": "trace_12",
|
||||
"properties": {
|
||||
"first_frame": 150,
|
||||
"last_frame": 280,
|
||||
"duration_frames": 130,
|
||||
"duration_seconds": 4.3,
|
||||
"confidence": 0.85,
|
||||
"context": "during_conversation"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 8. 實作計畫
|
||||
|
||||
### Phase 0: 8Hz 採樣框架 (~100 行)
|
||||
|
||||
| 檔案 | 修改 |
|
||||
|------|------|
|
||||
| `worker/processor.rs` | 計算 8Hz sample frames + refine 框架 |
|
||||
| `scripts/face_processor.py` | 接受 `--frames` 參數 |
|
||||
| `scripts/appearance_processor.py` | bbox 來源改 yolo,接受 `--frames` |
|
||||
| `scripts/mediapipe_holistic_processor.py` | 接受 `--frames` |
|
||||
|
||||
### Phase 1: Gaze + Mutual Gaze (~250 行)
|
||||
|
||||
| 模組 | 行數 |
|
||||
|------|------|
|
||||
| Gaze trace nodes | 150 |
|
||||
| Mutual Gaze edges | 100 |
|
||||
|
||||
### Phase 2: Lip + Sentence + Speaker (~260 行)
|
||||
|
||||
| 模組 | 行數 |
|
||||
|------|------|
|
||||
| Lip trace nodes | 120 |
|
||||
| Sentence nodes | 80 |
|
||||
| Speaker 強化 | 60 |
|
||||
|
||||
### Phase 3: Appearance + Accessories (~280 行)
|
||||
|
||||
| 模組 | 行數 |
|
||||
|------|------|
|
||||
| Appearance traces (HSV + trace_id 綁定) | 120 |
|
||||
| Accessories (CLIP detection) | 80 |
|
||||
| Skin tone + lighting | 80 |
|
||||
|
||||
### Phase 4: TKG 整合 (~110 行)
|
||||
|
||||
| 模組 | 行數 |
|
||||
|------|------|
|
||||
| `build_tkg()` 統一呼叫 | 40 |
|
||||
| Edge builders 更新 | 70 |
|
||||
|
||||
### 總計: ~1,000 行
|
||||
|
||||
---
|
||||
|
||||
## 9. 依賴關係圖
|
||||
|
||||
```
|
||||
YOLO (全域) ──────────────────────────────────────────┐
|
||||
│ │
|
||||
▼ │
|
||||
Face (8Hz) ──► trace_id ──┬──► Appearance (IoU 綁定) │
|
||||
│ │ ├──► HSV 色彩 │
|
||||
│ │ ├──► Accessories (CLIP) │
|
||||
│ │ └──► Skin tone + light │
|
||||
│ │ │
|
||||
│ ├──► Gaze ──► Mutual Gaze ────┤
|
||||
│ │ ──► Looking at YOLO │
|
||||
│ │ │
|
||||
│ └──► Lip ──► LIP_SYNC ◄──────┤
|
||||
│ │
|
||||
ASRX ──► Speaker ──► SPEAKS_AS ──► face_trace │
|
||||
│ │ │
|
||||
└──► Text (Rule 1) ────┴──► SPEAKS_BY │
|
||||
├──► SPOKEN_WHILE │
|
||||
└──► LIP_SYNC ────────────┘
|
||||
|
||||
所有 trace ──────────────────────────► TKG
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Appendix A: 配件完整清單 (49 種)
|
||||
|
||||
| 部位 | 配件 | 偵測方式 |
|
||||
|------|------|----------|
|
||||
| 頭部 (12) | hat, hairstyle, hair_accessory, earrings, nose_ring, lip_ring, face_tattoo, eyebrow_tattoo, glasses, mask, beard, headscarf | HSV 色塊 + CLIP |
|
||||
| 脖子 (5) | tie, scarf, shawl, necklace, neck_tattoo | HSV 色塊 + CLIP |
|
||||
| 手部/手臂 (16) | ring, bracelet, watch, gloves, phone, pen, laptop, book, cup, remote, tool, knife, gun, baseball_bat, gesture, arm_pose | HSV 色塊 + CLIP + MP |
|
||||
| 足部/載具 (8) | shoes, socks, barefoot, skateboard, scooter, bicycle, motorbike, roller_skates | HSV 色塊 + CLIP |
|
||||
| 攜帶/環境 (5) | backpack, handbag, luggage, chair, diningtable | HSV 色塊 + CLIP |
|
||||
| 色彩 (3) | upper_body_hsv, lower_body_hsv, skin_tone | HSV |
|
||||
|
||||
> **註**: YOLO 不可靠,不再作為主要偵測方式。大部分配件改用 HSV 色塊分析,CLIP 僅用於色塊不易區分的項目 (如穿刺、紋身、髮型等)。
|
||||
|
||||
## Appendix B: DB Schema 變更
|
||||
|
||||
```sql
|
||||
-- appearance_detections (新增)
|
||||
CREATE TABLE appearance_detections (
|
||||
id BIGSERIAL PRIMARY KEY,
|
||||
file_uuid VARCHAR NOT NULL,
|
||||
frame_number BIGINT NOT NULL,
|
||||
person_id INTEGER NOT NULL,
|
||||
x INTEGER, y INTEGER, width INTEGER, height INTEGER,
|
||||
trace_id INTEGER,
|
||||
confidence REAL,
|
||||
hsv_histogram JSONB,
|
||||
dominant_colors JSONB,
|
||||
upper_body_hsv JSONB,
|
||||
lower_body_hsv JSONB,
|
||||
accessories JSONB,
|
||||
skin_tone JSONB,
|
||||
lighting JSONB,
|
||||
created_at TIMESTAMPTZ DEFAULT NOW()
|
||||
);
|
||||
|
||||
-- tkg_nodes (擴充 node_type)
|
||||
-- 新增: appearance_trace, gaze_trace, lip_trace, sentence, accessory
|
||||
|
||||
-- tkg_edges (擴充 edge_type)
|
||||
-- 新增: HAS_APPEARANCE, HAS_GAZE, HAS_LIP, WEARS, LOOKING_AT,
|
||||
-- LOOKING_AT_PERSON, MUTUAL_GAZE, LIP_SYNC, SPEAKS_BY,
|
||||
-- SAME_SKIN_TONE, HAS_NECK_ACCESSORY, HAS_HEAD_ACCESSORY, HOLDS
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Version History
|
||||
|
||||
| Version | Date | Author | Description |
|
||||
|---------|------|--------|-------------|
|
||||
| 1.0.0 | 2026-06-19 | OpenCode | Initial design: 8Hz sampling, 7 traces (face/appearance/gaze/lip/speaker/text/skin_tone), 49 accessories, skin tone + lighting, mutual gaze, lip-sync |
|
||||
| 1.1.0 | 2026-06-19 | OpenCode | Added speaker_trace, text_trace, skin_tone_trace as important traces; enhanced lip_trace with speech_correlation; updated node/edge tables |
|
||||
| **1.2.0** | **2026-06-19** | **OpenCode** | **Implementation complete: build_tkg() integrates all node/edge builders. 9 node types, 14 edge types. ~1500 lines added to tkg.rs** |
|
||||
@@ -0,0 +1,257 @@
|
||||
---
|
||||
title: TKG Phase 2.6 Edges Migration Plan
|
||||
version: 1.0
|
||||
date: 2026-06-21
|
||||
author: OpenCode
|
||||
status: Draft
|
||||
---
|
||||
|
||||
## Phase 2.6 Overview
|
||||
|
||||
迁移 TKG edges 从 PostgreSQL face_detections 到 Qdrant payload。
|
||||
|
||||
## Current Implementation Analysis
|
||||
|
||||
### 2.6.1: co_occurrence_edges (CO_OCCURS_WITH)
|
||||
|
||||
**Current Code** (`tkg.rs:932-1039`):
|
||||
```rust
|
||||
let face_rows = sqlx::query_as::<_, FaceDetectionRow>(&format!(
|
||||
"SELECT trace_id::bigint, frame_number::bigint, x::float8, y::float8, width::float8, height::float8
|
||||
FROM {} WHERE file_uuid = $1 AND trace_id IS NOT NULL
|
||||
ORDER BY frame_number",
|
||||
face_table
|
||||
))
|
||||
.bind(file_uuid)
|
||||
.fetch_all(pool)
|
||||
.await?;
|
||||
```
|
||||
|
||||
**Dependencies**:
|
||||
- `face_detections.trace_id`
|
||||
- `face_detections.frame_number`
|
||||
- `face_detections.x, y, width, height`
|
||||
|
||||
**Migration Strategy**:
|
||||
```rust
|
||||
// 从 Qdrant payload 获取
|
||||
let embeddings = face_db.get_all_embeddings_for_file(file_uuid).await?;
|
||||
|
||||
// 按 frame 分组
|
||||
let mut frame_map: HashMap<i64, Vec<(i64, f64, f64, f64, f64)>> = HashMap::new();
|
||||
for emb in embeddings {
|
||||
let frame = emb.payload.frame_number;
|
||||
let trace_id = emb.payload.trace_id;
|
||||
frame_map.entry(frame).or_default().push((
|
||||
trace_id,
|
||||
emb.payload.bbox_x,
|
||||
emb.payload.bbox_y,
|
||||
emb.payload.bbox_width,
|
||||
emb.payload.bbox_height,
|
||||
));
|
||||
}
|
||||
```
|
||||
|
||||
### 2.6.2: face_face_edges (MUTUAL_GAZE)
|
||||
|
||||
**Current Code** (`tkg.rs:1171-1320`):
|
||||
```rust
|
||||
let rows: Vec<(i64, i64, i64)> = sqlx::query_as(&format!(
|
||||
"SELECT a.trace_id::bigint AS tid_a, b.trace_id::bigint AS tid_b, a.frame_number::bigint
|
||||
FROM {} a
|
||||
JOIN {} b ON a.file_uuid = b.file_uuid AND a.frame_number = b.frame_number AND a.trace_id < b.trace_id
|
||||
WHERE a.file_uuid = $1 AND a.trace_id IS NOT NULL AND b.trace_id IS NOT NULL",
|
||||
face_table, face_table
|
||||
))
|
||||
.bind(file_uuid)
|
||||
.fetch_all(pool)
|
||||
.await?;
|
||||
```
|
||||
|
||||
**Dependencies**:
|
||||
- `face_detections` self-join for co-occurrence
|
||||
- `face_detections.trace_id`
|
||||
- `face_detections.frame_number`
|
||||
|
||||
**Migration Strategy**:
|
||||
```rust
|
||||
// 从 Qdrant 获取所有 embeddings
|
||||
let embeddings = face_db.get_all_embeddings_for_file(file_uuid).await?;
|
||||
|
||||
// 按 frame 分组
|
||||
let mut frame_faces: HashMap<i64, Vec<FaceEmbeddingPayload>> = HashMap::new();
|
||||
for emb in embeddings {
|
||||
frame_faces.entry(emb.payload.frame_number).or_default().push(emb.payload);
|
||||
}
|
||||
|
||||
// 找同 frame 的 face pairs
|
||||
let mut pairs: Vec<(i64, i64, i64)> = Vec::new();
|
||||
for (frame, faces) in frame_faces.iter() {
|
||||
for i in 0..faces.len() {
|
||||
for j in (i+1)..faces.len() {
|
||||
let tid_a = faces[i].trace_id.min(faces[j].trace_id);
|
||||
let tid_b = faces[i].trace_id.max(faces[j].trace_id);
|
||||
pairs.push((tid_a, tid_b, *frame));
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### 2.6.3: speaker_face_edges (SPEAKS_AS)
|
||||
|
||||
**Current Code** (`tkg.rs:1045-1169`):
|
||||
```rust
|
||||
let traces = sqlx::query_as::<_, (i64, i64, i64)>(&format!(
|
||||
"SELECT trace_id::bigint, MIN(frame_number)::bigint as start_f, MAX(frame_number)::bigint as end_f
|
||||
FROM {} WHERE file_uuid = $1 AND trace_id IS NOT NULL
|
||||
GROUP BY trace_id",
|
||||
face_table
|
||||
))
|
||||
.bind(file_uuid)
|
||||
.fetch_all(pool)
|
||||
.await?;
|
||||
```
|
||||
|
||||
**Dependencies**:
|
||||
- `face_detections.trace_id`
|
||||
- `face_detections.frame_number` (MIN/MAX)
|
||||
|
||||
**Migration Strategy**:
|
||||
```rust
|
||||
// 从 Qdrant 获取所有 embeddings
|
||||
let embeddings = face_db.get_all_embeddings_for_file(file_uuid).await?;
|
||||
|
||||
// 计算每个 trace_id 的 frame range
|
||||
let mut trace_ranges: HashMap<i64, (i64, i64)> = HashMap::new();
|
||||
for emb in embeddings {
|
||||
let trace_id = emb.payload.trace_id;
|
||||
let frame = emb.payload.frame_number;
|
||||
let entry = trace_ranges.entry(trace_id).or_insert((frame, frame));
|
||||
entry.0 = entry.0.min(frame);
|
||||
entry.1 = entry.1.max(frame);
|
||||
}
|
||||
```
|
||||
|
||||
### 2.6.4: mutual_gaze_edges (MUTUAL_GAZE)
|
||||
|
||||
**Already in face_face_edges**:
|
||||
- face_face_edges 包含 mutual_gaze 检测逻辑
|
||||
- 不需要单独迁移
|
||||
|
||||
### 2.6.5: lip_sync_edges (LIP_SYNC)
|
||||
|
||||
**Already migrated in Phase 2.5.2**:
|
||||
- `build_lip_trace_nodes_from_qdrant()` 已完成
|
||||
- lip_sync_edges 已使用 Qdrant payload
|
||||
|
||||
## Migration Priority
|
||||
|
||||
| Priority | Edge Type | Complexity | Impact |
|
||||
|----------|-----------|-------------|--------|
|
||||
| P1 | co_occurrence_edges | Low | High (关系图) |
|
||||
| P1 | face_face_edges | Medium | High (face 关系) |
|
||||
| P2 | speaker_face_edges | Low | Medium (speaker 关系) |
|
||||
| N/A | mutual_gaze_edges | - | 已包含在 face_face_edges |
|
||||
| N/A | lip_sync_edges | - | 已迁移 Phase 2.5.2 |
|
||||
|
||||
## Performance Estimate
|
||||
|
||||
| Edge Type | Current (PG) | After Migration | Speedup |
|
||||
|-----------|--------------|-----------------|---------|
|
||||
| co_occurrence_edges | ~120ms | ~30ms | 4x |
|
||||
| face_face_edges | ~90ms | ~25ms | 3.6x |
|
||||
| speaker_face_edges | ~60ms | ~20ms | 3x |
|
||||
| **Total** | **~270ms** | **~75ms** | **3.6x** |
|
||||
|
||||
## Implementation Steps
|
||||
|
||||
### Step 1: Add helper functions in `face_embedding_db.rs`
|
||||
|
||||
```rust
|
||||
// Get all embeddings grouped by frame
|
||||
pub async fn get_embeddings_by_frame(&self, file_uuid: &str) -> Result<HashMap<i64, Vec<FaceEmbeddingPayload>>>;
|
||||
|
||||
// Get trace_id frame ranges
|
||||
pub async fn get_trace_frame_ranges(&self, file_uuid: &str) -> Result<HashMap<i64, (i64, i64)>>;
|
||||
```
|
||||
|
||||
### Step 2: Create migration functions in `tkg.rs`
|
||||
|
||||
```rust
|
||||
// Phase 2.6.1
|
||||
async fn build_co_occurrence_edges_from_qdrant(
|
||||
pool: &PgPool,
|
||||
file_uuid: &str,
|
||||
output_dir: &str,
|
||||
face_db: &FaceEmbeddingDb,
|
||||
) -> Result<usize>;
|
||||
|
||||
// Phase 2.6.2
|
||||
async fn build_face_face_edges_from_qdrant(
|
||||
pool: &PgPool,
|
||||
file_uuid: &str,
|
||||
pose_data: &[FacePose],
|
||||
face_db: &FaceEmbeddingDb,
|
||||
) -> Result<usize>;
|
||||
|
||||
// Phase 2.6.3
|
||||
async fn build_speaker_face_edges_from_qdrant(
|
||||
pool: &PgPool,
|
||||
file_uuid: &str,
|
||||
output_dir: &str,
|
||||
face_db: &FaceEmbeddingDb,
|
||||
) -> Result<usize>;
|
||||
```
|
||||
|
||||
### Step 3: Replace in `build_tkg.rs`
|
||||
|
||||
```rust
|
||||
// Old
|
||||
let e_co = build_co_occurrence_edges(pool, file_uuid, output_dir).await?;
|
||||
|
||||
// New
|
||||
let e_co = build_co_occurrence_edges_from_qdrant(pool, file_uuid, output_dir, face_db).await?;
|
||||
```
|
||||
|
||||
### Step 4: Add feature flag (optional)
|
||||
|
||||
```rust
|
||||
#[cfg(feature = "qdrant-edges")]
|
||||
let e_co = build_co_occurrence_edges_from_qdrant(...).await?;
|
||||
#[cfg(not(feature = "qdrant-edges"))]
|
||||
let e_co = build_co_occurrence_edges(...).await?;
|
||||
```
|
||||
|
||||
## Verification Plan
|
||||
|
||||
1. Run TKG rebuild on test file
|
||||
2. Compare edge counts (PG vs Qdrant)
|
||||
3. Verify edge properties match
|
||||
4. Performance benchmark
|
||||
5. Integration test with Rule2
|
||||
|
||||
## Risks & Mitigations
|
||||
|
||||
| Risk | Mitigation |
|
||||
|------|------------|
|
||||
| Qdrant collection empty | Fallback to PostgreSQL |
|
||||
| Performance regression | Benchmark before merge |
|
||||
| Edge count mismatch | Validate with test suite |
|
||||
| Data inconsistency | Add reconciliation job |
|
||||
|
||||
## Success Criteria
|
||||
|
||||
- [ ] All edges use Qdrant payload (no face_detections queries)
|
||||
- [ ] Edge counts match PostgreSQL version
|
||||
- [ ] Performance improvement >= 2x
|
||||
- [ ] Rule2/Rule3 work correctly
|
||||
- [ ] No regressions in existing tests
|
||||
|
||||
## Timeline
|
||||
|
||||
- Phase 2.6.1 (co_occurrence): 1 day
|
||||
- Phase 2.6.2 (face_face): 1 day
|
||||
- Phase 2.6.3 (speaker_face): 0.5 day
|
||||
- Testing & verification: 0.5 day
|
||||
- **Total: 3 days**
|
||||
|
||||
@@ -0,0 +1,165 @@
|
||||
---
|
||||
title: TKG Phase 2.7 Identity Resolution for Edges
|
||||
version: 1.0
|
||||
date: 2026-06-21
|
||||
author: OpenCode
|
||||
status: Draft
|
||||
---
|
||||
|
||||
## Phase 2.7 Overview
|
||||
|
||||
为 gaze_trace 和 lip_trace nodes 添加 identity_id 属性,实现完整的 edge identity resolution。
|
||||
|
||||
## Current Implementation Analysis
|
||||
|
||||
### Rule2 Identity Resolution
|
||||
|
||||
**Location**: `src/core/chunk/rule2_ingest.rs`
|
||||
|
||||
**Current Logic** (lines 102-131):
|
||||
```rust
|
||||
// Only resolves face_trace nodes
|
||||
let src_identity: Option<String> = if src_type == "face_trace" {
|
||||
sqlx::query_scalar("SELECT i.name FROM tkg_nodes n
|
||||
JOIN identities i ON i.id = (n.properties->>'identity_id')::bigint
|
||||
WHERE n.node_type = 'face_trace' AND n.properties->>'identity_id' IS NOT NULL")
|
||||
}
|
||||
```
|
||||
|
||||
**Problem**:
|
||||
- Only handles `face_trace` node type
|
||||
- `gaze_trace` and `lip_trace` nodes lack identity_id
|
||||
|
||||
### Node Type Properties
|
||||
|
||||
| Node Type | external_id | identity_id | 状态 |
|
||||
|-----------|-------------|-------------|------|
|
||||
| **face_trace** | trace_{id} | ✓ 有 | ✅ Phase 2.3 |
|
||||
| **gaze_trace** | gaze_{id} | ❌ 无 | 需要添加 |
|
||||
| **lip_trace** | lip_{id} | ❌ 无 | 需要添加 |
|
||||
|
||||
## Solution Design
|
||||
|
||||
### Approach 1: Extend Rule2 Logic (Complex)
|
||||
|
||||
修改 Rule2 支持 gaze_trace/lip_trace node types:
|
||||
```rust
|
||||
let src_identity: Option<String> = if src_type == "face_trace" || src_type == "gaze_trace" || src_type == "lip_trace" {
|
||||
// Parse trace_id from external_id
|
||||
let trace_id = src_ext_id.split('_').last()?;
|
||||
// Query face_trace node
|
||||
sqlx::query_scalar("SELECT i.name FROM tkg_nodes n
|
||||
JOIN identities i ON i.id = (n.properties->>'identity_id')::bigint
|
||||
WHERE n.node_type = 'face_trace' AND n.external_id = 'trace_' || $1")
|
||||
.bind(trace_id)
|
||||
}
|
||||
```
|
||||
|
||||
**优点**: 不需要修改 TKG builders
|
||||
**缺点**: Rule2 逻辑复杂,查询效率低
|
||||
|
||||
### Approach 2: Add identity_id in TKG Builders (Recommended)
|
||||
|
||||
在创建 gaze_trace/lip_trace nodes 时直接设置 identity_id:
|
||||
```rust
|
||||
// Step 1: Query face_trace node's identity_id
|
||||
let face_identity_id: Option<i64> = sqlx::query_scalar(
|
||||
"SELECT (properties->>'identity_id')::bigint FROM tkg_nodes
|
||||
WHERE file_uuid=$1 AND node_type='face_trace' AND external_id=$2"
|
||||
)
|
||||
.bind(file_uuid)
|
||||
.bind(&format!("trace_{}", trace_id))
|
||||
.fetch_optional(pool)
|
||||
.await?;
|
||||
|
||||
// Step 2: Add to gaze/lip node properties
|
||||
let props = serde_json::json!({
|
||||
"trace_id": tid,
|
||||
"identity_id": face_identity_id, // <-- NEW
|
||||
...
|
||||
});
|
||||
```
|
||||
|
||||
**优点**:
|
||||
- 性能最优(一次查询)
|
||||
- Rule2 无需修改
|
||||
- 逻辑清晰
|
||||
|
||||
**缺点**: 需要修改 TKG builders
|
||||
|
||||
### Recommended: Approach 2
|
||||
|
||||
## Implementation Plan
|
||||
|
||||
### Step 1: Modify build_gaze_trace_nodes_from_qdrant()
|
||||
|
||||
**Location**: `src/core/processor/tkg.rs:1859-1975`
|
||||
|
||||
**Add**:
|
||||
```rust
|
||||
// Query face_trace identity_id
|
||||
let face_ext_id = format!("trace_{}", tid);
|
||||
let face_identity_id: Option<i64> = sqlx::query_scalar(&format!(
|
||||
"SELECT (properties->>'identity_id')::bigint FROM {}
|
||||
WHERE file_uuid=$1 AND node_type='face_trace' AND external_id=$2",
|
||||
nodes_table
|
||||
))
|
||||
.bind(file_uuid)
|
||||
.bind(&face_ext_id)
|
||||
.fetch_optional(pool)
|
||||
.await?;
|
||||
|
||||
// Add to properties
|
||||
let props = serde_json::json!({
|
||||
"trace_id": tid,
|
||||
"identity_id": face_identity_id, // <-- NEW
|
||||
"frame_count": frame_count,
|
||||
...
|
||||
});
|
||||
```
|
||||
|
||||
### Step 2: Modify build_lip_trace_nodes_from_qdrant()
|
||||
|
||||
**Location**: `src/core/processor/tkg.rs` (lip_trace builder)
|
||||
|
||||
**Add**: Same logic as gaze_trace
|
||||
|
||||
### Step 3: Update PostgreSQL fallback versions
|
||||
|
||||
Also update:
|
||||
- `build_gaze_trace_nodes_from_pg()`
|
||||
- `build_lip_trace_nodes_from_pg()`
|
||||
|
||||
### Step 4: Update Rule2 (Optional)
|
||||
|
||||
If desired, extend Rule2 to support gaze_trace/lip_trace:
|
||||
```rust
|
||||
let src_identity: Option<String> = if src_type == "face_trace" || src_type == "gaze_trace" || src_type == "lip_trace" {
|
||||
// Query identity from node properties
|
||||
...
|
||||
}
|
||||
```
|
||||
|
||||
**Note**: With Approach 2, Rule2 already works correctly!
|
||||
|
||||
## Verification Plan
|
||||
|
||||
1. TKG rebuild → check gaze/lip nodes have identity_id
|
||||
2. Rule2 test → verify identity resolution works
|
||||
3. Edge count comparison → ensure no regression
|
||||
4. Performance benchmark → measure impact
|
||||
|
||||
## Success Criteria
|
||||
|
||||
- [ ] gaze_trace nodes have identity_id in properties
|
||||
- [ ] lip_trace nodes have identity_id in properties
|
||||
- [ ] Rule2 identity resolution works for all node types
|
||||
- [ ] No regressions in edge counts
|
||||
- [ ] Performance acceptable (<10ms added)
|
||||
|
||||
## Timeline
|
||||
|
||||
- Implementation: 1 day
|
||||
- Testing: 0.5 day
|
||||
- **Total: 1.5 days**
|
||||
|
||||
@@ -0,0 +1,186 @@
|
||||
---
|
||||
title: TKG Phase 2-4 Migration Plan (Non-Face Nodes)
|
||||
version: 1.0
|
||||
date: 2026-06-21
|
||||
author: OpenCode
|
||||
status: Draft
|
||||
---
|
||||
|
||||
## 概览
|
||||
|
||||
Phase 2-3 已完成 face_trace_nodes 的 Qdrant 迁移。其他 node types 需要类似迁移。
|
||||
|
||||
## 当前状态
|
||||
|
||||
| Node Type | 数据源 | PostgreSQL 依赖 | 迁移状态 |
|
||||
|-----------|--------|-----------------|----------|
|
||||
| **face_trace_nodes** | Qdrant embeddings | ❌ 无 | ✅ Phase 2.1 完成 |
|
||||
| **gaze_trace_nodes** | face.json | ✅ face_detections.trace_id | 🔄 待迁移 |
|
||||
| **lip_trace_nodes** | face.json + lip.json | ✅ face_detections.trace_id | 🔄 待迁移 |
|
||||
| **text_trace_nodes** | chunk table | ✅ chunk.sentence | ⏸️ 保持现状 |
|
||||
| **yolo_object_nodes** | .yolo.json | ❌ 无 | ✅ 无需迁移 |
|
||||
| **speaker_nodes** | .asrx.json | ❌ 无 | ✅ 无需迁移 |
|
||||
| **appearance_trace_nodes** | .appearance.json | ❌ 无 | ✅ 无需迁移 |
|
||||
| **skin_tone_trace_nodes** | .skin.json | ❌ 无 | ✅ 无需迁移 |
|
||||
| **accessory_nodes** | .accessory.json | ❌ 无 | ✅ 无需迁移 |
|
||||
|
||||
## Edge Types 迁移状态
|
||||
|
||||
| Edge Type | 数据源 | PostgreSQL 依赖 | 迁移状态 |
|
||||
|-----------|--------|-----------------|----------|
|
||||
| **co_occurrence_edges** | face_detections | ✅ face_detections.trace_id | 🔄 待迁移 |
|
||||
| **face_face_edges** | face_detections | ✅ face_detections.trace_id | 🔄 待迁移 |
|
||||
| **speaker_face_edges** | face_detections + speaker | ✅ face_detections.trace_id | 🔄 待迁移 |
|
||||
| **mutual_gaze_edges** | gaze.json | ✅ face_detections.trace_id | 🔄 待迁移 |
|
||||
| **lip_sync_edges** | lip.json | ✅ face_detections.trace_id | 🔄 待迁移 |
|
||||
|
||||
## 迁移计划
|
||||
|
||||
### Phase 2.5: Gaze & Lip Nodes
|
||||
|
||||
**目标**: 使用 Qdrant payload 替代 face_detections 查询
|
||||
|
||||
#### 2.5.1: gaze_trace_nodes
|
||||
|
||||
**当前代码** (`src/core/processor/tkg.rs`):
|
||||
```rust
|
||||
let frame_rows: Vec<(i64, i64, f64, f64, f64, f64)> = sqlx::query_as(
|
||||
"SELECT trace_id, frame_number, x, y, width, height
|
||||
FROM face_detections WHERE file_uuid = $1"
|
||||
)
|
||||
```
|
||||
|
||||
**迁移方案**:
|
||||
```rust
|
||||
// 使用 Qdrant payload (trace_id, frame, bbox_x/y/w/h)
|
||||
let qdrant_embeddings = face_db.get_all_embeddings_for_file(file_uuid).await?;
|
||||
// Group by trace_id → compute gaze
|
||||
```
|
||||
|
||||
#### 2.5.2: lip_trace_nodes
|
||||
|
||||
**当前代码**:
|
||||
```rust
|
||||
// Read lip.json, query face_detections for trace_id
|
||||
let trace_id = sqlx::query_scalar(
|
||||
"SELECT trace_id FROM face_detections
|
||||
WHERE file_uuid = $1 AND frame_number = $2 AND x = $3 ..."
|
||||
)
|
||||
```
|
||||
|
||||
**迁移方案**:
|
||||
```rust
|
||||
// 使用 Qdrant payload 直接关联 trace_id
|
||||
// face.json 已有 trace_id (Python store_traced_faces.py)
|
||||
```
|
||||
|
||||
### Phase 2.6: Edge Types
|
||||
|
||||
#### 2.6.1: co_occurrence_edges
|
||||
|
||||
**当前代码**:
|
||||
```rust
|
||||
"SELECT trace_id FROM face_detections
|
||||
WHERE file_uuid = $1 AND frame_number BETWEEN $2 AND $3"
|
||||
```
|
||||
|
||||
**迁移方案**:
|
||||
```rust
|
||||
// 使用 Qdrant payload.group_by(trace_id)
|
||||
// 预计算 frame ranges
|
||||
```
|
||||
|
||||
#### 2.6.2: face_face_edges
|
||||
|
||||
**当前代码**:
|
||||
```rust
|
||||
"SELECT trace_id, frame_number FROM face_detections
|
||||
WHERE file_uuid = $1 AND trace_id IS NOT NULL"
|
||||
```
|
||||
|
||||
**迁移方案**:
|
||||
```rust
|
||||
// 使用 Qdrant embeddings 的 spatial proximity
|
||||
// 无需 PostgreSQL
|
||||
```
|
||||
|
||||
#### 2.6.3: speaker_face_edges
|
||||
|
||||
**当前代码**:
|
||||
```rust
|
||||
// JOIN face_detections.trace_id + speaker_nodes
|
||||
```
|
||||
|
||||
**迁移方案**:
|
||||
```rust
|
||||
// Qdrant trace_id + speaker_nodes (already from .asrx.json)
|
||||
```
|
||||
|
||||
### Phase 2.7: Identity Resolution for Edges
|
||||
|
||||
**当前代码** (Rule2):
|
||||
```rust
|
||||
// 已完成 Phase 2.3: 查询 tkg_nodes.properties.identity_id
|
||||
```
|
||||
|
||||
**扩展**:
|
||||
- gaze/lip edges 也需要 identity resolution
|
||||
- 统一使用 `tkg_nodes.properties.identity_id`
|
||||
|
||||
## 不迁移的 Node Types
|
||||
|
||||
### text_trace_nodes
|
||||
|
||||
**原因**:
|
||||
- chunk table 是必要持久化(sentence chunks)
|
||||
- 不依赖 face_detections
|
||||
- 保持现状,无需迁移
|
||||
|
||||
### JSON-based Nodes
|
||||
|
||||
**已无 PostgreSQL 依赖**:
|
||||
- yolo_object_nodes: `.yolo.json`
|
||||
- speaker_nodes: `.asrx.json`
|
||||
- appearance_trace_nodes: `.appearance.json`
|
||||
- skin_tone_trace_nodes: `.skin.json`
|
||||
- accessory_nodes: `.accessory.json`
|
||||
|
||||
## 性能影响预估
|
||||
|
||||
| 迁移项 | 当前耗时 | 预估迁移后 | 提升 |
|
||||
|--------|----------|------------|------|
|
||||
| gaze_trace_nodes | ~50ms (PG query) | ~15ms (Qdrant) | **3x** |
|
||||
| lip_trace_nodes | ~80ms (PG + lip.json) | ~20ms (Qdrant + lip.json) | **4x** |
|
||||
| co_occurrence_edges | ~120ms (PG) | ~30ms (Qdrant) | **4x** |
|
||||
| face_face_edges | ~90ms (PG) | ~25ms (Qdrant) | **3.6x** |
|
||||
|
||||
## 实施优先级
|
||||
|
||||
| 优先级 | 任务 | 影响 | 复杂度 |
|
||||
|--------|------|------|--------|
|
||||
| P1 | gaze_trace_nodes | 高(gaze 分析) | 低 |
|
||||
| P1 | co_occurrence_edges | 高(关系图) | 中 |
|
||||
| P2 | lip_trace_nodes | 中(lip 分析) | 中 |
|
||||
| P2 | face_face_edges | 中(face 关系) | 中 |
|
||||
| P3 | speaker_face_edges | 低(speaker 关系) | 中 |
|
||||
|
||||
## 关键决策
|
||||
|
||||
1. **text_trace_nodes**: 保持 chunk table 查询(必要持久化)
|
||||
2. **JSON nodes**: 无需迁移(已无 PG 依赖)
|
||||
3. **Qdrant 作为唯一 face 数据源**: trace_id, frame, bbox 全部从 payload 获取
|
||||
4. **渐进式迁移**: 按优先级分 Phase 2.5, 2.6, 2.7
|
||||
|
||||
## 验收标准
|
||||
|
||||
- ✅ gaze_trace_nodes: 无 face_detections 查询
|
||||
- ✅ lip_trace_nodes: 使用 Qdrant trace_id
|
||||
- ✅ 所有 edges: 使用 Qdrant payload
|
||||
- ✅ 性能测试: 比原架构快 2x 以上
|
||||
- ✅ Rule2/Rule3: 正常工作(identity resolution)
|
||||
|
||||
## 参考文档
|
||||
|
||||
- `docs_v1.0/M4_workspace/2026-06-21_tkg_phase2_progress.md` (Phase 2-3)
|
||||
- `src/core/processor/tkg.rs` (当前实现)
|
||||
- `src/core/db/face_embedding_db.rs` (Qdrant API)
|
||||
@@ -0,0 +1,332 @@
|
||||
---
|
||||
title: Tools Directory Restructure
|
||||
version: 1.0
|
||||
date: 2026-09-27
|
||||
author: OpenCode
|
||||
status: proposed
|
||||
---
|
||||
|
||||
## 目標
|
||||
|
||||
將 `scripts/` 目錄重組為 `tools/` 結構,區分 Python 腳本和 Swift/Rust CLI 工具。
|
||||
|
||||
---
|
||||
|
||||
## 當前結構
|
||||
|
||||
```
|
||||
momentry_core/
|
||||
├── scripts/ # 混合 Python 腳本
|
||||
│ ├── asr_processor_contract_v2.py
|
||||
│ ├── face_processor.py
|
||||
│ ├── pose_processor.py
|
||||
│ ├── cut_processor.py
|
||||
│ ├── scene_vlm_processor.py
|
||||
│ ├── yolo_processor.py
|
||||
│ ├── ocr_processor.py
|
||||
│ └── swift_processors/ # Swift CLI 工具
|
||||
│ ├── asr_swift.swift
|
||||
│ ├── swift_face.swift
|
||||
│ ├── swift_pose.swift
|
||||
│ └── Package.swift
|
||||
│ └── rust_processors/ # Rust CLI 工具
|
||||
│ ├── Cargo.toml
|
||||
│ └── src/
|
||||
└── src/core/processor/ # Rust 處理器(主項目)
|
||||
├── asr.rs
|
||||
├── face.rs
|
||||
└── ...
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 新結構
|
||||
|
||||
```
|
||||
momentry_core/
|
||||
└── tools/
|
||||
├── script/ # Python 腳本
|
||||
│ ├── asr/
|
||||
│ │ ├── asr_processor_contract_v2.py
|
||||
│ │ └── asr_processor_base.py
|
||||
│ ├── face/
|
||||
│ │ ├── face_processor.py
|
||||
│ │ └── face_tracker.py
|
||||
│ ├── pose/
|
||||
│ │ ├── pose_processor.py
|
||||
│ │ └── pose_expansion.py
|
||||
│ ├── cut/
|
||||
│ │ └── cut_processor.py
|
||||
│ ├── scene/
|
||||
│ │ └── scene_vlm_processor.py
|
||||
│ ├── yolo/
|
||||
│ │ └── yolo_processor.py
|
||||
│ ├── ocr/
|
||||
│ │ └── ocr_processor.py
|
||||
│ ├── vlm/
|
||||
│ │ ├── vlm_summary.py
|
||||
│ │ └── tkg_builder.py
|
||||
│ ├── embedding/
|
||||
│ │ └── embeddinggemma_server.py
|
||||
│ └── utils/
|
||||
│ ├── video_utils.py
|
||||
│ └── db_utils.py
|
||||
└── cli/ # Swift/Rust CLI 工具
|
||||
├── swift/
|
||||
│ ├── Package.swift
|
||||
│ ├── Sources/
|
||||
│ │ ├── asr/
|
||||
│ │ │ └── main.swift
|
||||
│ │ ├── face/
|
||||
│ │ │ └── main.swift
|
||||
│ │ └── pose/
|
||||
│ │ └── main.swift
|
||||
│ └── Tests/
|
||||
└── rust/
|
||||
├── Cargo.toml
|
||||
├── src/
|
||||
│ ├── face_cluster/
|
||||
│ ├── appearance/
|
||||
│ └── pose/
|
||||
└── target/
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 遷移計劃
|
||||
|
||||
### Phase 1: 創建新結構
|
||||
|
||||
```bash
|
||||
mkdir -p tools/script/{asr,face,pose,cut,scene,yolo,ocr,vlm,embedding,utils}
|
||||
mkdir -p tools/cli/{swift,rust}
|
||||
```
|
||||
|
||||
### Phase 2: 遷移 Python 腳本
|
||||
|
||||
**處理器腳本**:
|
||||
- `asr_processor_*.py` → `tools/script/asr/`
|
||||
- `face_processor.py` → `tools/script/face/`
|
||||
- `pose_processor.py` → `tools/script/pose/`
|
||||
- `cut_processor.py` → `tools/script/cut/`
|
||||
- `scene_vlm_processor.py` → `tools/script/scene/`
|
||||
- `yolo_processor.py` → `tools/script/yolo/`
|
||||
- `ocr_processor.py` → `tools/script/ocr/`
|
||||
- `vlm_summary.py` → `tools/script/vlm/`
|
||||
- `tkg_builder.py` → `tools/script/vlm/`
|
||||
|
||||
**輔助腳本**:
|
||||
- `embeddinggemma_server.py` → `tools/script/embedding/`
|
||||
- 工具腳本 → `tools/script/utils/`
|
||||
|
||||
### Phase 3: 遷移 CLI 工具
|
||||
|
||||
**Swift**:
|
||||
- `scripts/swift_processors/` → `tools/cli/swift/`
|
||||
|
||||
**Rust**:
|
||||
- `scripts/rust_processors/` → `tools/cli/rust/`
|
||||
|
||||
### Phase 4: 更新配置
|
||||
|
||||
1. 更新 `MOMENTRY_SCRIPTS_DIR` 環境變數
|
||||
2. 更新 `executor.rs` 中的路徑引用
|
||||
3. 更新文檔中的路徑引用
|
||||
4. 更新 `.gitignore`
|
||||
|
||||
---
|
||||
|
||||
## 分類規則
|
||||
|
||||
### Python (script/)
|
||||
|
||||
**屬於 script/**:
|
||||
- 處理器腳本(調用外部工具)
|
||||
- 工具腳本(數據處理)
|
||||
- 服務器腳本(embedding server)
|
||||
- 分析腳本(benchmark, stats)
|
||||
|
||||
**不屬於 script/**:
|
||||
- 測試腳本(保留在 `tests/`)
|
||||
- 臨時腳本(不提交)
|
||||
- v1.1 遺留腳本(保留原位置)
|
||||
|
||||
### CLI (cli/)
|
||||
|
||||
**Swift**:
|
||||
- 實際處理器(調用系統 API)
|
||||
- 性能敏感模組
|
||||
- Apple 框架依賴
|
||||
|
||||
**Rust**:
|
||||
- 獨立可執行文件
|
||||
- 跨平台工具
|
||||
- 高性能計算
|
||||
|
||||
---
|
||||
|
||||
## 命名規範
|
||||
|
||||
### Python 腳本
|
||||
|
||||
- 處理器: `{module}_processor.py`
|
||||
- 工具: `{module}_utils.py`
|
||||
- 服務器: `{module}_server.py`
|
||||
- 分析: `{module}_analyzer.py`
|
||||
|
||||
### CLI 工具
|
||||
|
||||
- Swift: `swift_{module}.swift` 或 `{module}/main.swift`
|
||||
- Rust: `{module}/main.rs`
|
||||
|
||||
---
|
||||
|
||||
## 影響範圍
|
||||
|
||||
### 需要更新的文件
|
||||
|
||||
1. **配置**:
|
||||
- `.env`
|
||||
- `config/production.env`
|
||||
- `config/development.env`
|
||||
|
||||
2. **代碼**:
|
||||
- `src/core/processor/executor.rs`
|
||||
- `src/core/config.rs`
|
||||
- 所有引用腳本路徑的 Rust 代碼
|
||||
|
||||
3. **文檔**:
|
||||
- `AGENTS.md`
|
||||
- `README.md`
|
||||
- `docs/**/*.md`
|
||||
|
||||
4. **CI/CD**:
|
||||
- `.github/workflows/`
|
||||
- 測試腳本
|
||||
|
||||
---
|
||||
|
||||
## 向後兼容
|
||||
|
||||
### 選項 1: 軟連結(推薦)
|
||||
|
||||
保留舊路徑,創建軟連結:
|
||||
|
||||
```bash
|
||||
# scripts/ → tools/script/
|
||||
ln -s tools/script scripts_new
|
||||
|
||||
# swift_processors/ → tools/cli/swift/
|
||||
ln -s tools/cli/swift scripts/swift_processors
|
||||
|
||||
# rust_processors/ → tools/cli/rust/
|
||||
ln -s tools/cli/rust scripts/rust_processors
|
||||
```
|
||||
|
||||
### 選項 2: 雙路徑支持
|
||||
|
||||
在 `executor.rs` 中支持新舊路徑:
|
||||
|
||||
```rust
|
||||
fn find_script(name: &str) -> PathBuf {
|
||||
// Try new path first
|
||||
let new_path = Path::new("tools/script").join(name);
|
||||
if new_path.exists() {
|
||||
return new_path;
|
||||
}
|
||||
|
||||
// Fallback to old path
|
||||
Path::new("scripts").join(name)
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 實施步驟
|
||||
|
||||
### 第一步:創建目錄結構
|
||||
|
||||
```bash
|
||||
cd /Users/accusys/momentry_core
|
||||
mkdir -p tools/script/{asr,face,pose,cut,scene,yolo,ocr,vlm,embedding,utils}
|
||||
mkdir -p tools/cli/{swift,rust}
|
||||
```
|
||||
|
||||
### 第二步:遷移 Python 腳本
|
||||
|
||||
```bash
|
||||
# ASR
|
||||
mv scripts/asr_processor_*.py tools/script/asr/
|
||||
mv scripts/asr_processor_base.py tools/script/asr/
|
||||
|
||||
# Face
|
||||
mv scripts/face_processor.py tools/script/face/
|
||||
mv scripts/face_tracker.py tools/script/face/
|
||||
|
||||
# Pose
|
||||
mv scripts/pose_processor.py tools/script/pose/
|
||||
|
||||
# ... 其他處理器
|
||||
```
|
||||
|
||||
### 第三步:遷移 CLI 工具
|
||||
|
||||
```bash
|
||||
# Swift
|
||||
mv scripts/swift_processors tools/cli/swift
|
||||
|
||||
# Rust
|
||||
mv scripts/rust_processors tools/cli/rust
|
||||
```
|
||||
|
||||
### 第四步:更新配置
|
||||
|
||||
更新環境變數和代碼引用。
|
||||
|
||||
### 第五步:測試
|
||||
|
||||
```bash
|
||||
cargo test
|
||||
cargo run -- register test.mp4
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 時間表
|
||||
|
||||
- **Phase 1**: 創建目錄(5 分鐘)
|
||||
- **Phase 2**: 遷移腳本(30 分鐘)
|
||||
- **Phase 3**: 更新配置(15 分鐘)
|
||||
- **Phase 4**: 測試驗證(15 分鐘)
|
||||
|
||||
**總計**: 約 1 小時
|
||||
|
||||
---
|
||||
|
||||
## 驗收標準
|
||||
|
||||
- [ ] 所有處理器腳本遷移到 `tools/script/`
|
||||
- [ ] 所有 CLI 工具遷移到 `tools/cli/`
|
||||
- [ ] 環境變數更新
|
||||
- [ ] 代碼引用更新
|
||||
- [ ] 文檔更新
|
||||
- [ ] 測試通過
|
||||
- [ ] 舊路徑保留軟連結(向後兼容)
|
||||
|
||||
---
|
||||
|
||||
## 風險與緩解
|
||||
|
||||
| 風險 | 緩解措施 |
|
||||
|------|----------|
|
||||
| 破壞現有功能 | 使用軟連結保持兼容 |
|
||||
| 遺漏路徑更新 | 全局搜索 `scripts/` |
|
||||
| 文檔不一致 | 更新所有文檔 |
|
||||
|
||||
---
|
||||
|
||||
## 相關文件
|
||||
|
||||
- `/Users/accusys/momentry_core/AGENTS.md`
|
||||
- `/Users/accusys/momentry_core/src/core/processor/executor.rs`
|
||||
- `/Users/accusys/momentry_core/src/core/config.rs`
|
||||
@@ -0,0 +1,209 @@
|
||||
# Trace ID Inheritance & Expansion Rules
|
||||
|
||||
**Date**: 2026-07-19
|
||||
**Author**: Core Team
|
||||
**Status**: Final
|
||||
|
||||
---
|
||||
|
||||
## Overview
|
||||
|
||||
This document defines the trace ID inheritance rules and expansion logic for Face, Pose, and Appearance processing.
|
||||
|
||||
---
|
||||
|
||||
## Core Concepts
|
||||
|
||||
### Face = Identity, Pose/Appearance = Tracking
|
||||
|
||||
| Processor | Purpose | Description |
|
||||
|-----------|---------|-------------|
|
||||
| **Face** | Identity | Who is this person? Requires high-quality embedding for recognition. |
|
||||
| **Pose** | Tracking | Where is this person? Maintains tracking when face is occluded. |
|
||||
| **Appearance** | Tracking | What do they look like? Maintains tracking when pose is occluded. |
|
||||
|
||||
### Offline Processing Advantage
|
||||
|
||||
In offline processing, we can:
|
||||
1. First detect all faces (identity anchors)
|
||||
2. Then expand pose/appearance from face traces
|
||||
|
||||
This is different from real-time tracking where pose/appearance runs continuously and face anchors identity when visible.
|
||||
|
||||
---
|
||||
|
||||
## Processing Pipeline
|
||||
|
||||
### Step 1: Face Detection (8Hz)
|
||||
|
||||
```
|
||||
swift_face → face.json
|
||||
```
|
||||
|
||||
- Sampling rate: `floor(fps / 8)` (ensures ≥ 8Hz)
|
||||
- Output: Face bounding boxes with landmarks and embeddings
|
||||
|
||||
### Step 2: Face Tracking
|
||||
|
||||
```
|
||||
store_traced_faces.py → face_traced.json
|
||||
```
|
||||
|
||||
- Algorithm: IoU + embedding similarity
|
||||
- Output: Each face assigned a `trace_id`
|
||||
- Purpose: Group same-person faces across frames
|
||||
|
||||
### Step 3: Pose Expansion
|
||||
|
||||
```
|
||||
swift_pose_expansion → pose.json
|
||||
```
|
||||
|
||||
**Input**: face_traced.json (frames with trace_id)
|
||||
|
||||
**Expansion Algorithm**:
|
||||
1. For each trace_id, get all face frames
|
||||
2. Expand outward (forward/backward) checking for pose
|
||||
3. Stop when 3 consecutive frames have no pose detection
|
||||
4. Inherit trace_id from face
|
||||
|
||||
**Output**: Pose keypoints with inherited trace_id
|
||||
|
||||
### Step 4: Appearance Expansion
|
||||
|
||||
```
|
||||
swift_appearance_expansion → appearance.json
|
||||
```
|
||||
|
||||
**Input**: pose.json (frames with trace_id)
|
||||
|
||||
**Expansion Algorithm**:
|
||||
1. For each trace_id, get all pose frames
|
||||
2. Expand outward (forward/backward) checking for appearance
|
||||
3. Stop when 3 consecutive frames have HSV similarity < 0.5
|
||||
4. Inherit trace_id from pose
|
||||
|
||||
**Output**: HSV histograms with inherited trace_id
|
||||
|
||||
---
|
||||
|
||||
## Trace ID Inheritance
|
||||
|
||||
```
|
||||
Face Trace (identity anchor)
|
||||
│
|
||||
│ inherits trace_id
|
||||
▼
|
||||
Pose Expansion
|
||||
│
|
||||
│ inherits trace_id
|
||||
▼
|
||||
Appearance Expansion
|
||||
```
|
||||
|
||||
**Key Points:**
|
||||
- Trace ID originates from face tracking
|
||||
- Pose inherits the same trace_id (same person)
|
||||
- Appearance inherits the same trace_id (same person)
|
||||
- This enables linking all detections to the same identity
|
||||
|
||||
---
|
||||
|
||||
## Frame Count Relationship
|
||||
|
||||
```
|
||||
face frames ≤ pose frames ≤ appearance frames
|
||||
```
|
||||
|
||||
**Explanation:**
|
||||
- Face: Only frames where face is clearly visible
|
||||
- Pose: Face frames + expanded frames (pose may still be visible when face is occluded)
|
||||
- Appearance: Pose frames + expanded frames (appearance may still be visible when pose is occluded)
|
||||
|
||||
---
|
||||
|
||||
## Expansion Rules
|
||||
|
||||
### Pose Expansion
|
||||
|
||||
| Parameter | Value | Description |
|
||||
|-----------|-------|-------------|
|
||||
| `miss_threshold` | 3 | Stop after 3 consecutive frames without pose |
|
||||
| `max_range` | 300 frames | Maximum expansion distance (≈10s at 30fps) |
|
||||
| `output_rate` | 8Hz | Output sampling rate |
|
||||
|
||||
### Appearance Expansion
|
||||
|
||||
| Parameter | Value | Description |
|
||||
|-----------|-------|-------------|
|
||||
| `miss_threshold` | 3 | Stop after 3 consecutive frames with similarity < 0.5 |
|
||||
| `similarity_threshold` | 0.5 | HSV histogram similarity threshold |
|
||||
| `max_range` | 300 frames | Maximum expansion distance |
|
||||
| `output_rate` | 8Hz | Output sampling rate |
|
||||
|
||||
---
|
||||
|
||||
## Tracking Continuity
|
||||
|
||||
### Pose Can Connect Face Traces
|
||||
|
||||
```
|
||||
Face trace A (frames 1-10) Face trace B (frames 20-30)
|
||||
↘ ↙
|
||||
Pose connects (frames 15-18)
|
||||
(Same person, face was occluded)
|
||||
```
|
||||
|
||||
When pose expansion from two face traces overlaps, they may belong to the same person. Future enhancement: pose-based trace merging.
|
||||
|
||||
### Appearance Can Connect Pose Traces
|
||||
|
||||
Similar to pose, appearance similarity can connect pose traces when pose is temporarily occluded.
|
||||
|
||||
---
|
||||
|
||||
## Implementation Files
|
||||
|
||||
| Component | File |
|
||||
|-----------|------|
|
||||
| Face Detection | `scripts/swift_processors/swift_face.swift` |
|
||||
| Face Tracking | `scripts/store_traced_faces.py` |
|
||||
| Pose Expansion | `scripts/swift_processors/swift_pose_expansion.swift` |
|
||||
| Appearance Expansion | `scripts/swift_processors/swift_appearance_expansion.swift` |
|
||||
| Pose Processor Wrapper | `scripts/pose_processor_v2.py` |
|
||||
| Appearance Processor Wrapper | `scripts/appearance_processor_v2.py` |
|
||||
| Dependencies Definition | `src/core/db/postgres_db.rs:568-577` |
|
||||
|
||||
---
|
||||
|
||||
## Testing
|
||||
|
||||
### Verify Trace ID Inheritance
|
||||
|
||||
```bash
|
||||
# Check face traces
|
||||
cat /Users/accusys/momentry/output/$FILE_UUID.face_traced.json | jq '.frames[].faces[].trace_id' | sort | uniq -c
|
||||
|
||||
# Check pose traces (should have same trace_ids)
|
||||
cat /Users/accusys/momentry/output/$FILE_UUID.pose.json | jq '.frames[].trace_id' | sort | uniq -c
|
||||
|
||||
# Check appearance traces (should have same trace_ids)
|
||||
cat /Users/accusys/momentry/output/$FILE_UUID.appearance.json | jq '.frames[].trace_id' | sort | uniq -c
|
||||
```
|
||||
|
||||
### Verify Frame Count Relationship
|
||||
|
||||
```bash
|
||||
# face ≤ pose ≤ appearance
|
||||
FACE_COUNT=$(cat $OUTPUT/$UUID.face.json | jq '.frames | length')
|
||||
POSE_COUNT=$(cat $OUTPUT/$UUID.pose.json | jq '.frames | length')
|
||||
APP_COUNT=$(cat $OUTPUT/$UUID.appearance.json | jq '.frames | length')
|
||||
|
||||
echo "Face: $FACE_COUNT, Pose: $POSE_COUNT, Appearance: $APP_COUNT"
|
||||
# Expected: Face ≤ Pose ≤ Appearance
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
*Document Version: 1.0*
|
||||
*Last Updated: 2026-07-19*
|
||||
@@ -0,0 +1,812 @@
|
||||
# MarkBase Search 统一交谈介面设计
|
||||
|
||||
**版本**: 1.0
|
||||
**日期**: 2026-10-11
|
||||
**状态**: 设计规范
|
||||
|
||||
---
|
||||
|
||||
## 🎯 设计目标
|
||||
|
||||
创建 **统一的交谈介面服务**,支持 5 种搜索类别,用户无需指定类型,系统自动选择最佳搜索方式。
|
||||
|
||||
---
|
||||
|
||||
## 📊 搜索类别定义
|
||||
|
||||
### 1. 五大搜索类别
|
||||
|
||||
```rust
|
||||
/// Search 类型
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum SearchType {
|
||||
/// 关键词搜索 - BM25 + FTS
|
||||
Keyword,
|
||||
/// 语义搜索 - Vector Embedding
|
||||
Semantic,
|
||||
/// 视觉搜索 - Image/VLM
|
||||
Visual,
|
||||
/// Agent 搜索 - LLM + RAG
|
||||
Agent,
|
||||
/// 人物搜索 - Face Identity
|
||||
People,
|
||||
}
|
||||
```
|
||||
|
||||
### 2. 各类型特点
|
||||
|
||||
| 类型 | 技术 | 数据源 | 特点 | 用例 |
|
||||
|------|------|--------|------|------|
|
||||
| **Keyword** | BM25, FTS | PostgreSQL | 精确匹配,快速 | "news report", "interview" |
|
||||
| **Semantic** | Vector Search | Qdrant | 语义理解,模糊匹配 | "people talking about politics" |
|
||||
| **Visual** | VLM, CLIP | Qdrant, Frames | 视觉内容,场景描述 | "sunset beach", "woman in red dress" |
|
||||
| **Agent** | LLM + RAG | All Sources | 复杂查询,推理 | "find all videos where Obama discusses healthcare" |
|
||||
| **People** | Face Identity | Qdrant Faces | 人物识别,身份关联 | "videos with Barack Obama" |
|
||||
|
||||
---
|
||||
|
||||
## 🏗️ 统一介面架构
|
||||
|
||||
### 核心理念
|
||||
|
||||
```
|
||||
User Query
|
||||
↓
|
||||
┌─────────────────────────────────────────────────────────┐
|
||||
│ Unified Search Interface │
|
||||
│ ┌───────────────────────────────────────────────────┐ │
|
||||
│ │ Query Analyzer (智能路由) │ │
|
||||
│ │ - 分析查询意图 │ │
|
||||
│ │ - 选择搜索类型 │ │
|
||||
│ │ - 生成搜索策略 │ │
|
||||
│ └───────────────────────────────────────────────────┘ │
|
||||
│ │ │
|
||||
│ ├─→ Keyword Search (30%) │
|
||||
│ ├─→ Semantic Search (25%) │
|
||||
│ ├─→ Visual Search (15%) │
|
||||
│ ├─→ Agent Search (20%) │
|
||||
│ └─→ People Search (10%) │
|
||||
│ │
|
||||
│ ┌───────────────────────────────────────────────────┐ │
|
||||
│ │ Result Merger (结果合并) │ │
|
||||
│ │ - 统一排序 │ │
|
||||
│ │ - 去重 │ │
|
||||
│ │ - 上下文丰富 │ │
|
||||
│ └───────────────────────────────────────────────────┘ │
|
||||
└─────────────────────────────────────────────────────────┘
|
||||
↓
|
||||
Unified Results
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 💬 统一交谈介面服务
|
||||
|
||||
### 1. UnifiedSearchService
|
||||
|
||||
```rust
|
||||
// MarkBase Queue Protocol - Independent Implementation
|
||||
// This is NOT compatible with Apache Kafka protocol or API.
|
||||
|
||||
use super::types::*;
|
||||
use crate::core::command::messenger::Messenger;
|
||||
use crate::core::command::error::{CommandError, CommandResult};
|
||||
use crate::core::command::messenger::types::{Message, MessageSource, MessagePriority, MessageType, DeliveryOptions};
|
||||
use crate::core::llm::LLMClient;
|
||||
use std::time::Instant;
|
||||
use tracing::{debug, info, warn};
|
||||
|
||||
/// 统一搜索服务
|
||||
pub struct UnifiedSearchService {
|
||||
messenger: Messenger,
|
||||
llm_client: LLMClient,
|
||||
query_analyzer: QueryAnalyzer,
|
||||
}
|
||||
|
||||
impl UnifiedSearchService {
|
||||
pub fn new(db: sqlx::PgPool, llm_client: LLMClient) -> Self {
|
||||
Self {
|
||||
messenger: Messenger::new(db),
|
||||
llm_client: llm_client.clone(),
|
||||
query_analyzer: QueryAnalyzer::new(llm_client),
|
||||
}
|
||||
}
|
||||
|
||||
/// 统一搜索入口(智能路由)
|
||||
pub async fn search(
|
||||
&self,
|
||||
query: &str,
|
||||
context: Option<SearchContext>,
|
||||
) -> CommandResult<UnifiedSearchResponse> {
|
||||
let start = Instant::now();
|
||||
|
||||
// 1. 分析查询意图
|
||||
let intent = self.query_analyzer.analyze(query, context.clone()).await?;
|
||||
|
||||
debug!(
|
||||
query = %query,
|
||||
intent = ?intent.search_types,
|
||||
confidence = intent.confidence,
|
||||
"Query intent analyzed"
|
||||
);
|
||||
|
||||
// 2. 根据意图选择搜索策略
|
||||
let strategy = self.select_strategy(&intent);
|
||||
|
||||
// 3. 执行搜索(可能是并行多个类型)
|
||||
let results = self.execute_strategy(&strategy, query, context.clone()).await?;
|
||||
|
||||
// 4. 合并结果
|
||||
let unified_response = self.merge_results(results, query, intent).await?;
|
||||
|
||||
info!(
|
||||
query = %query,
|
||||
took_ms = start.elapsed().as_millis(),
|
||||
total_results = unified_response.total_count,
|
||||
"Unified search completed"
|
||||
);
|
||||
|
||||
Ok(unified_response)
|
||||
}
|
||||
|
||||
/// 选择搜索策略
|
||||
fn select_strategy(&self, intent: &QueryIntent) -> SearchStrategy {
|
||||
match intent.primary_type {
|
||||
// 单一类型高置信度
|
||||
SearchType::Keyword if intent.confidence > 0.8 => {
|
||||
SearchStrategy::Single(SearchType::Keyword)
|
||||
}
|
||||
SearchType::Semantic if intent.confidence > 0.8 => {
|
||||
SearchStrategy::Single(SearchType::Semantic)
|
||||
}
|
||||
SearchType::Visual if intent.confidence > 0.8 => {
|
||||
SearchStrategy::Single(SearchType::Visual)
|
||||
}
|
||||
SearchType::People if intent.confidence > 0.8 => {
|
||||
SearchStrategy::Single(SearchType::People)
|
||||
}
|
||||
SearchType::Agent if intent.confidence > 0.7 => {
|
||||
SearchStrategy::Single(SearchType::Agent)
|
||||
}
|
||||
|
||||
// 混合策略
|
||||
_ => {
|
||||
let mut types = Vec::new();
|
||||
|
||||
if intent.scores.keyword > 0.3 {
|
||||
types.push((SearchType::Keyword, intent.scores.keyword));
|
||||
}
|
||||
if intent.scores.semantic > 0.3 {
|
||||
types.push((SearchType::Semantic, intent.scores.semantic));
|
||||
}
|
||||
if intent.scores.visual > 0.3 {
|
||||
types.push((SearchType::Visual, intent.scores.visual));
|
||||
}
|
||||
if intent.scores.people > 0.3 {
|
||||
types.push((SearchType::People, intent.scores.people));
|
||||
}
|
||||
|
||||
// Agent 作为后备
|
||||
if types.is_empty() {
|
||||
types.push((SearchType::Agent, 1.0));
|
||||
}
|
||||
|
||||
SearchStrategy::Hybrid(types)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 执行搜索策略
|
||||
async fn execute_strategy(
|
||||
&self,
|
||||
strategy: &SearchStrategy,
|
||||
query: &str,
|
||||
context: Option<SearchContext>,
|
||||
) -> CommandResult<Vec<SearchResponse>> {
|
||||
match strategy {
|
||||
SearchStrategy::Single(search_type) => {
|
||||
let response = self.execute_single_search(search_type, query, context).await?;
|
||||
Ok(vec![response])
|
||||
}
|
||||
|
||||
SearchStrategy::Hybrid(types) => {
|
||||
// 并行执行多个搜索
|
||||
let mut handles = Vec::new();
|
||||
|
||||
for (search_type, weight) in types {
|
||||
let handle = self.execute_single_search(search_type, query, context.clone());
|
||||
handles.push((search_type.clone(), weight, handle));
|
||||
}
|
||||
|
||||
// 收集结果
|
||||
let mut results = Vec::new();
|
||||
for (search_type, weight, handle) in handles {
|
||||
match handle.await {
|
||||
Ok(response) => {
|
||||
results.push((response, weight));
|
||||
}
|
||||
Err(e) => {
|
||||
warn!(
|
||||
search_type = ?search_type,
|
||||
error = ?e,
|
||||
"Search type failed"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Ok(results.into_iter().map(|(r, _)| r).collect())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 执行单一类型搜索
|
||||
async fn execute_single_search(
|
||||
&self,
|
||||
search_type: &SearchType,
|
||||
query: &str,
|
||||
context: Option<SearchContext>,
|
||||
) -> CommandResult<SearchResponse> {
|
||||
let request = SearchRequest::new(query.to_string(), search_type.clone())
|
||||
.with_filters(context.clone().map(|c| c.filters).unwrap_or_default())
|
||||
.with_options(context.clone().map(|c| c.options).unwrap_or_default());
|
||||
|
||||
let request_id = self.messenger.send_search_request(&request).await?;
|
||||
|
||||
// 等待结果
|
||||
let timeout = request.options.limit.unwrap_or(30) as u64 * 1000;
|
||||
let deadline = Instant::now() + std::time::Duration::from_millis(timeout);
|
||||
|
||||
loop {
|
||||
if Instant::now() > deadline {
|
||||
return Err(CommandError::Timeout(timeout as i32));
|
||||
}
|
||||
|
||||
if let Some(response) = self.messenger.get_search_result(&request_id).await? {
|
||||
return Ok(response);
|
||||
}
|
||||
|
||||
tokio::time::sleep(std::time::Duration::from_millis(100)).await;
|
||||
}
|
||||
}
|
||||
|
||||
/// 合并搜索结果
|
||||
async fn merge_results(
|
||||
&self,
|
||||
results: Vec<SearchResponse>,
|
||||
query: &str,
|
||||
intent: QueryIntent,
|
||||
) -> CommandResult<UnifiedSearchResponse> {
|
||||
let mut all_results = Vec::new();
|
||||
let mut seen_ids = std::collections::HashSet::new();
|
||||
|
||||
// 1. 收集所有结果
|
||||
for response in results {
|
||||
for result in response.results {
|
||||
if !seen_ids.contains(&result.id) {
|
||||
seen_ids.insert(result.id.clone());
|
||||
all_results.push(result);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 2. 重新评分和排序
|
||||
for result in &mut all_results {
|
||||
// 根据查询意图调整分数
|
||||
result.score = self.adjust_score(result.score, &intent);
|
||||
}
|
||||
|
||||
// 3. 排序
|
||||
all_results.sort_by(|a, b| b.score.partial_cmp(&a.score).unwrap());
|
||||
|
||||
// 4. 生成摘要(使用 LLM)
|
||||
let summary = self.generate_summary(query, &all_results).await?;
|
||||
|
||||
Ok(UnifiedSearchResponse {
|
||||
query: query.to_string(),
|
||||
intent,
|
||||
results: all_results,
|
||||
total_count: all_results.len() as i64,
|
||||
summary,
|
||||
took_ms: 0, // 由外层设置
|
||||
})
|
||||
}
|
||||
|
||||
/// 调整分数
|
||||
fn adjust_score(&self, original_score: f64, intent: &QueryIntent) -> f64 {
|
||||
// 根据意图置信度调整分数
|
||||
original_score * (0.5 + 0.5 * intent.confidence)
|
||||
}
|
||||
|
||||
/// 生成摘要
|
||||
async fn generate_summary(
|
||||
&self,
|
||||
query: &str,
|
||||
results: &[SearchResult],
|
||||
) -> CommandResult<String> {
|
||||
if results.is_empty() {
|
||||
return Ok("No results found.".to_string());
|
||||
}
|
||||
|
||||
// 使用 LLM 生成自然语言摘要
|
||||
let prompt = format!(
|
||||
"Summarize the search results for query '{}' in 2-3 sentences. Found {} results.",
|
||||
query,
|
||||
results.len()
|
||||
);
|
||||
|
||||
let summary = self.llm_client.chat(&prompt).await?;
|
||||
|
||||
Ok(summary)
|
||||
}
|
||||
|
||||
/// 对话式搜索(多轮)
|
||||
pub async fn conversational_search(
|
||||
&self,
|
||||
conversation_id: &str,
|
||||
query: &str,
|
||||
) -> CommandResult<UnifiedSearchResponse> {
|
||||
// 1. 获取对话历史
|
||||
let history = self.get_conversation_history(conversation_id).await?;
|
||||
|
||||
// 2. 结合历史理解查询
|
||||
let context = SearchContext {
|
||||
conversation_history: history,
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
// 3. 执行搜索
|
||||
let mut response = self.search(query, Some(context)).await?;
|
||||
|
||||
// 4. 更新对话历史
|
||||
self.update_conversation(conversation_id, query, &response).await?;
|
||||
|
||||
Ok(response)
|
||||
}
|
||||
|
||||
async fn get_conversation_history(&self, _conversation_id: &str) -> CommandResult<Vec<Message>> {
|
||||
// TODO: 从数据库获取对话历史
|
||||
Ok(Vec::new())
|
||||
}
|
||||
|
||||
async fn update_conversation(
|
||||
&self,
|
||||
_conversation_id: &str,
|
||||
_query: &str,
|
||||
_response: &UnifiedSearchResponse,
|
||||
) -> CommandResult<()> {
|
||||
// TODO: 更新对话历史到数据库
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// 搜索策略
|
||||
#[derive(Debug, Clone)]
|
||||
pub enum SearchStrategy {
|
||||
/// 单一类型搜索
|
||||
Single(SearchType),
|
||||
/// 混合搜索
|
||||
Hybrid(Vec<(SearchType, f64)>),
|
||||
}
|
||||
|
||||
/// 搜索上下文
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
|
||||
pub struct SearchContext {
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub user_id: Option<String>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub conversation_id: Option<String>,
|
||||
#[serde(default)]
|
||||
pub conversation_history: Vec<Message>,
|
||||
#[serde(default)]
|
||||
pub filters: SearchFilters,
|
||||
#[serde(default)]
|
||||
pub options: SearchOptions,
|
||||
}
|
||||
|
||||
/// 统一搜索响应
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct UnifiedSearchResponse {
|
||||
pub query: String,
|
||||
pub intent: QueryIntent,
|
||||
pub results: Vec<SearchResult>,
|
||||
pub total_count: i64,
|
||||
pub summary: String,
|
||||
pub took_ms: i64,
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 2. Query Analyzer (智能路由)
|
||||
|
||||
```rust
|
||||
/// 查询分析器
|
||||
pub struct QueryAnalyzer {
|
||||
llm_client: LLMClient,
|
||||
}
|
||||
|
||||
/// 查询意图
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct QueryIntent {
|
||||
pub primary_type: SearchType,
|
||||
pub search_types: Vec<SearchType>,
|
||||
pub confidence: f64,
|
||||
pub scores: SearchTypeScores,
|
||||
pub entities: Vec<String>,
|
||||
pub keywords: Vec<String>,
|
||||
}
|
||||
|
||||
/// 搜索类型分数
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
|
||||
pub struct SearchTypeScores {
|
||||
pub keyword: f64,
|
||||
pub semantic: f64,
|
||||
pub visual: f64,
|
||||
pub agent: f64,
|
||||
pub people: f64,
|
||||
}
|
||||
|
||||
impl QueryAnalyzer {
|
||||
pub fn new(llm_client: LLMClient) -> Self {
|
||||
Self { llm_client }
|
||||
}
|
||||
|
||||
/// 分析查询意图
|
||||
pub async fn analyze(
|
||||
&self,
|
||||
query: &str,
|
||||
context: Option<SearchContext>,
|
||||
) -> CommandResult<QueryIntent> {
|
||||
// 1. 提取实体和关键词
|
||||
let entities = self.extract_entities(query).await?;
|
||||
let keywords = self.extract_keywords(query).await?;
|
||||
|
||||
// 2. 判断搜索类型
|
||||
let scores = self.score_search_types(query, &entities, &keywords).await?;
|
||||
|
||||
// 3. 确定主要类型
|
||||
let (primary_type, confidence) = self.determine_primary_type(&scores);
|
||||
|
||||
// 4. 确定次要类型
|
||||
let search_types = self.determine_secondary_types(&scores);
|
||||
|
||||
Ok(QueryIntent {
|
||||
primary_type,
|
||||
search_types,
|
||||
confidence,
|
||||
scores,
|
||||
entities,
|
||||
keywords,
|
||||
})
|
||||
}
|
||||
|
||||
/// 提取实体
|
||||
async fn extract_entities(&self, query: &str) -> CommandResult<Vec<String>> {
|
||||
let prompt = format!(
|
||||
"Extract named entities from this query: '{}'. Return as JSON array.",
|
||||
query
|
||||
);
|
||||
|
||||
let response = self.llm_client.chat(&prompt).await?;
|
||||
let entities: Vec<String> = serde_json::from_str(&response)?;
|
||||
|
||||
Ok(entities)
|
||||
}
|
||||
|
||||
/// 提取关键词
|
||||
async fn extract_keywords(&self, query: &str) -> CommandResult<Vec<String>> {
|
||||
let prompt = format!(
|
||||
"Extract keywords from this query: '{}'. Return as JSON array.",
|
||||
query
|
||||
);
|
||||
|
||||
let response = self.llm_client.chat(&prompt).await?;
|
||||
let keywords: Vec<String> = serde_json::from_str(&response)?;
|
||||
|
||||
Ok(keywords)
|
||||
}
|
||||
|
||||
/// 评分搜索类型
|
||||
async fn score_search_types(
|
||||
&self,
|
||||
query: &str,
|
||||
entities: &[String],
|
||||
keywords: &[String],
|
||||
) -> CommandResult<SearchTypeScores> {
|
||||
let prompt = format!(
|
||||
r#"Analyze the search query and score each search type (0.0-1.0):
|
||||
Query: "{}"
|
||||
Entities: {:?}
|
||||
Keywords: {:?}
|
||||
|
||||
Score each type based on:
|
||||
- keyword: precise text matching (dates, names, specific terms)
|
||||
- semantic: conceptual understanding (actions, relationships, ideas)
|
||||
- visual: image/video content (colors, objects, scenes, appearances)
|
||||
- agent: complex reasoning (multi-step, inference needed)
|
||||
- people: person-focused (names, faces, identities)
|
||||
|
||||
Return as JSON: {{"keyword": 0.8, "semantic": 0.5, "visual": 0.3, "agent": 0.2, "people": 0.0}}"#,
|
||||
query, entities, keywords
|
||||
);
|
||||
|
||||
let response = self.llm_client.chat(&prompt).await?;
|
||||
let scores: SearchTypeScores = serde_json::from_str(&response)?;
|
||||
|
||||
Ok(scores)
|
||||
}
|
||||
|
||||
/// 确定主要类型
|
||||
fn determine_primary_type(&self, scores: &SearchTypeScores) -> (SearchType, f64) {
|
||||
let types = vec![
|
||||
(SearchType::Keyword, scores.keyword),
|
||||
(SearchType::Semantic, scores.semantic),
|
||||
(SearchType::Visual, scores.visual),
|
||||
(SearchType::Agent, scores.agent),
|
||||
(SearchType::People, scores.people),
|
||||
];
|
||||
|
||||
types
|
||||
.into_iter()
|
||||
.max_by(|a, b| a.1.partial_cmp(&b.1).unwrap())
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
/// 确定次要类型
|
||||
fn determine_secondary_types(&self, scores: &SearchTypeScores) -> Vec<SearchType> {
|
||||
let mut types = vec![
|
||||
(SearchType::Keyword, scores.keyword),
|
||||
(SearchType::Semantic, scores.semantic),
|
||||
(SearchType::Visual, scores.visual),
|
||||
(SearchType::Agent, scores.agent),
|
||||
(SearchType::People, scores.people),
|
||||
];
|
||||
|
||||
types.sort_by(|a, b| b.1.partial_cmp(&a.1).unwrap());
|
||||
|
||||
types
|
||||
.into_iter()
|
||||
.filter(|(_, score)| *score > 0.3)
|
||||
.map(|(t, _)| t)
|
||||
.collect()
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 🔄 工作流程示例
|
||||
|
||||
### 示例 1: 简单关键词搜索
|
||||
|
||||
```
|
||||
Query: "interview with Obama"
|
||||
|
||||
Query Analyzer:
|
||||
- entities: ["Obama"]
|
||||
- keywords: ["interview"]
|
||||
- scores: {keyword: 0.9, people: 0.7, semantic: 0.3, ...}
|
||||
- primary_type: Keyword (confidence: 0.9)
|
||||
|
||||
Strategy: Single(Keyword)
|
||||
|
||||
Execution:
|
||||
→ Keyword Search Worker
|
||||
→ FTS + BM25
|
||||
|
||||
Results:
|
||||
- Video 1: "Obama Interview 2020" (score: 0.95)
|
||||
- Video 2: "Interview with Barack Obama" (score: 0.92)
|
||||
...
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 示例 2: 复杂语义搜索
|
||||
|
||||
```
|
||||
Query: "videos where people discuss climate change solutions"
|
||||
|
||||
Query Analyzer:
|
||||
- entities: ["climate change", "solutions"]
|
||||
- keywords: ["videos", "people", "discuss"]
|
||||
- scores: {semantic: 0.8, agent: 0.6, keyword: 0.3, ...}
|
||||
- primary_type: Semantic (confidence: 0.8)
|
||||
|
||||
Strategy: Single(Semantic)
|
||||
|
||||
Execution:
|
||||
→ Semantic Search Worker
|
||||
→ Vector Similarity Search
|
||||
→ Embedding: "discussing climate change solutions"
|
||||
|
||||
Results:
|
||||
- Video 1: Documentary on renewable energy (score: 0.88)
|
||||
- Video 2: Town hall on climate policy (score: 0.85)
|
||||
...
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 示例 3: 混合搜索
|
||||
|
||||
```
|
||||
Query: "Obama giving speech about healthcare in 2010"
|
||||
|
||||
Query Analyzer:
|
||||
- entities: ["Obama", "2010"]
|
||||
- keywords: ["speech", "healthcare"]
|
||||
- scores: {keyword: 0.7, people: 0.8, semantic: 0.6, agent: 0.5, ...}
|
||||
- primary_type: People (confidence: 0.8)
|
||||
|
||||
Strategy: Hybrid([
|
||||
(People, 0.8),
|
||||
(Keyword, 0.7),
|
||||
(Semantic, 0.6),
|
||||
])
|
||||
|
||||
Execution (Parallel):
|
||||
→ People Search: Face identity match "Obama"
|
||||
→ Keyword Search: "healthcare", "speech", "2010"
|
||||
→ Semantic Search: "healthcare policy speech"
|
||||
|
||||
Merge Results:
|
||||
- Combine and re-rank
|
||||
- Remove duplicates
|
||||
- Adjust scores by intent confidence
|
||||
|
||||
Final Results:
|
||||
- Video 1: Obama healthcare speech 2010 (score: 0.96)
|
||||
- Video 2: Obama discusses healthcare reform (score: 0.89)
|
||||
...
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 示例 4: Agent 搜索
|
||||
|
||||
```
|
||||
Query: "Find all videos where Obama talks about healthcare and compare with Biden's positions"
|
||||
|
||||
Query Analyzer:
|
||||
- entities: ["Obama", "Biden", "healthcare"]
|
||||
- complexity: High (multi-step, comparison)
|
||||
- scores: {agent: 0.95, ...}
|
||||
- primary_type: Agent (confidence: 0.95)
|
||||
|
||||
Strategy: Single(Agent)
|
||||
|
||||
Execution:
|
||||
→ Agent Search Worker
|
||||
→ LLM Agent:
|
||||
1. Search for Obama healthcare videos
|
||||
2. Search for Biden healthcare videos
|
||||
3. Extract positions from each
|
||||
4. Compare and summarize
|
||||
|
||||
Results:
|
||||
- Obama: "Healthcare should be universal..."
|
||||
- Biden: "We need to build on ACA..."
|
||||
- Comparison: "Both support universal coverage..."
|
||||
- Related Videos: [...]
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 🎯 用户介面设计
|
||||
|
||||
### 统一搜索框
|
||||
|
||||
```html
|
||||
<!-- Studio UI -->
|
||||
<div class="unified-search">
|
||||
<input
|
||||
type="text"
|
||||
placeholder="Search videos, people, scenes, or ask a question..."
|
||||
class="search-input"
|
||||
/>
|
||||
<div class="search-hints">
|
||||
<span class="hint" data-type="keyword">"interview with Obama"</span>
|
||||
<span class="hint" data-type="semantic">"people discussing politics"</span>
|
||||
<span class="hint" data-type="visual">"sunset at beach"</span>
|
||||
<span class="hint" data-type="agent">"compare Obama and Biden on healthcare"</span>
|
||||
<span class="hint" data-type="people">"videos with Barack Obama"</span>
|
||||
</div>
|
||||
</div>
|
||||
```
|
||||
|
||||
### 搜索结果显示
|
||||
|
||||
```rust
|
||||
// 统一搜索响应
|
||||
{
|
||||
"query": "Obama healthcare speech",
|
||||
"intent": {
|
||||
"primary_type": "people",
|
||||
"confidence": 0.85,
|
||||
"search_types": ["people", "keyword", "semantic"]
|
||||
},
|
||||
"results": [
|
||||
{
|
||||
"id": "video_123",
|
||||
"file_uuid": "384b0ff44aaaa1f1",
|
||||
"score": 0.96,
|
||||
"snippet": "Obama delivers speech on healthcare reform...",
|
||||
"thumbnail": "https://...",
|
||||
"metadata": {
|
||||
"duration": 1800,
|
||||
"date": "2010-03-23",
|
||||
"identities": ["Barack Obama"]
|
||||
}
|
||||
},
|
||||
...
|
||||
],
|
||||
"total_count": 15,
|
||||
"summary": "Found 15 videos featuring Barack Obama discussing healthcare, primarily from 2009-2010 during the ACA debate.",
|
||||
"took_ms": 250
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 📊 API 端点
|
||||
|
||||
```rust
|
||||
// POST /api/v1/search
|
||||
pub async fn unified_search(
|
||||
Extension(search_service): Extension<Arc<UnifiedSearchService>>,
|
||||
Extension(auth): Extension<UserAuth>,
|
||||
Json(request): Json<UnifiedSearchRequest>,
|
||||
) -> Result<Json<UnifiedSearchResponse>, APIError> {
|
||||
let context = SearchContext {
|
||||
user_id: Some(auth.user_id),
|
||||
..request.context.unwrap_or_default()
|
||||
};
|
||||
|
||||
let response = search_service.search(&request.query, Some(context)).await?;
|
||||
|
||||
Ok(Json(response))
|
||||
}
|
||||
|
||||
// POST /api/v1/search/conversation
|
||||
pub async fn conversational_search(
|
||||
Extension(search_service): Extension<Arc<UnifiedSearchService>>,
|
||||
Extension(auth): Extension<UserAuth>,
|
||||
Json(request): Json<ConversationalSearchRequest>,
|
||||
) -> Result<Json<UnifiedSearchResponse>, APIError> {
|
||||
let response = search_service
|
||||
.conversational_search(&request.conversation_id, &request.query)
|
||||
.await?;
|
||||
|
||||
Ok(Json(response))
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 🚀 实施计划
|
||||
|
||||
### Phase 1: 核心实现(3 天)
|
||||
|
||||
- [ ] 实现 UnifiedSearchService
|
||||
- [ ] 实现 QueryAnalyzer
|
||||
- [ ] 实现 5 种搜索 Worker
|
||||
- [ ] 单元测试
|
||||
|
||||
### Phase 2: 集成(2 天)
|
||||
|
||||
- [ ] 集成到 Studio UI
|
||||
- [ ] 实现 API 端点
|
||||
- [ ] 集成 Billing 和 Log
|
||||
|
||||
### Phase 3: 优化(2 天)
|
||||
|
||||
- [ ] 性能优化
|
||||
- [ ] 智能路由优化
|
||||
- [ ] 用户体验改进
|
||||
|
||||
---
|
||||
|
||||
**统一交谈介面设计完成!用户无需选择搜索类型,系统智能选择最佳方式。**
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user