Compare commits
9
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
3b8cf24974 | ||
|
|
1c12ead5a1 | ||
|
|
9999aba5e6 | ||
|
|
c092ab5f83 | ||
|
|
9299b68680 | ||
|
|
49f50a8f44 | ||
|
|
99104abcf2 | ||
|
|
6a5c3044f7 | ||
|
|
f8eb7ec66e |
No files matched your search
Generated
+572
-21
@@ -8,6 +8,24 @@ version = "2.0.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa"
|
||||
|
||||
[[package]]
|
||||
name = "aligned"
|
||||
version = "0.4.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ee4508988c62edf04abd8d92897fca0c2995d907ce1dfeaf369dac3716a40685"
|
||||
dependencies = [
|
||||
"as-slice",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "aligned-vec"
|
||||
version = "0.6.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "dc890384c8602f339876ded803c97ad529f3842aba97f6392b3dba0dd171769b"
|
||||
dependencies = [
|
||||
"equator",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "alloc-no-stdlib"
|
||||
version = "2.0.4"
|
||||
@@ -23,18 +41,108 @@ dependencies = [
|
||||
"alloc-no-stdlib",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "anyhow"
|
||||
version = "1.0.104"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470"
|
||||
|
||||
[[package]]
|
||||
name = "arbitrary"
|
||||
version = "1.5.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3bc62ac97cc33321f50863d514c3bc38a453947a8f9e781137e47c7401020aed"
|
||||
|
||||
[[package]]
|
||||
name = "arg_enum_proc_macro"
|
||||
version = "0.3.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0ae92a5119aa49cdbcf6b9f893fe4e1d98b04ccbf82ee0584ad948a44a734dea"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 2.0.119",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "arrayvec"
|
||||
version = "0.7.8"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d3fb67a6e08acf24fdeccbac2cb6ac4305825bd1f117462e0e6f2f193345ad56"
|
||||
|
||||
[[package]]
|
||||
name = "as-slice"
|
||||
version = "0.2.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "516b6b4f0e40d50dcda9365d53964ec74560ad4284da2e7fc97122cd83174516"
|
||||
dependencies = [
|
||||
"stable_deref_trait",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "autocfg"
|
||||
version = "1.5.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53"
|
||||
|
||||
[[package]]
|
||||
name = "av-scenechange"
|
||||
version = "0.14.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0f321d77c20e19b92c39e7471cf986812cbb46659d2af674adc4331ef3f18394"
|
||||
dependencies = [
|
||||
"aligned",
|
||||
"anyhow",
|
||||
"arg_enum_proc_macro",
|
||||
"arrayvec",
|
||||
"log",
|
||||
"num-rational",
|
||||
"num-traits",
|
||||
"pastey",
|
||||
"rayon",
|
||||
"thiserror",
|
||||
"v_frame",
|
||||
"y4m",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "av1-grain"
|
||||
version = "0.2.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8cfddb07216410377231960af4fcab838eaa12e013417781b78bd95ee22077f8"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"arrayvec",
|
||||
"log",
|
||||
"nom",
|
||||
"num-rational",
|
||||
"v_frame",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "avif-serialize"
|
||||
version = "0.8.9"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e7178fe5f7d460b13895ebb9dcb28a3a6216d2df2574a0806cb51b555d297f38"
|
||||
dependencies = [
|
||||
"arrayvec",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "bitflags"
|
||||
version = "2.13.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06"
|
||||
|
||||
[[package]]
|
||||
name = "bitstream-io"
|
||||
version = "4.10.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7eff00be299a18769011411c9def0d827e8f2d7bf0c3dbf53633147a8867fd1f"
|
||||
dependencies = [
|
||||
"no_std_io2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "block-buffer"
|
||||
version = "0.10.4"
|
||||
@@ -54,6 +162,12 @@ dependencies = [
|
||||
"alloc-stdlib",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "built"
|
||||
version = "0.8.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "5c0e531d93d39c34eef561e929e8a7f86d77a5af08aac4f6d6e39976c51858e9"
|
||||
|
||||
[[package]]
|
||||
name = "bumpalo"
|
||||
version = "3.20.3"
|
||||
@@ -86,6 +200,18 @@ version = "0.1.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8f1fe948ff07f4bd06c30984e69f5b4899c516a3ef74f34df92a2df2ab535495"
|
||||
|
||||
[[package]]
|
||||
name = "cc"
|
||||
version = "1.9.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "877bf67ac8e52449eb2f9e98a344ea163beb70dd1f9eebe3cc5357dcfeaee4df"
|
||||
dependencies = [
|
||||
"find-msvc-tools",
|
||||
"jobserver",
|
||||
"libc",
|
||||
"shlex",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "cfg-if"
|
||||
version = "1.0.5"
|
||||
@@ -173,6 +299,26 @@ version = "1.19.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0e9c71c2167ca323c882b99918929403426e2373ea17242ff5653e0d5e1058be"
|
||||
|
||||
[[package]]
|
||||
name = "equator"
|
||||
version = "0.4.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4711b213838dfee0117e3be6ac926007d7f433d7bbe33595975d4190cb07e6fc"
|
||||
dependencies = [
|
||||
"equator-macro",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "equator-macro"
|
||||
version = "0.4.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "44f23cf4b44bfce11a86ace86f8a73ffdec849c9fd00a386a53d278bd9e81fb3"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 2.0.119",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "fax"
|
||||
version = "0.2.7"
|
||||
@@ -188,6 +334,12 @@ dependencies = [
|
||||
"simd-adler32",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "find-msvc-tools"
|
||||
version = "0.1.15"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1c66915cc5391097de7a2b0b972e8505aa33c0df401fd3a6811dbdb32881ba48"
|
||||
|
||||
[[package]]
|
||||
name = "flate2"
|
||||
version = "1.1.10"
|
||||
@@ -233,6 +385,29 @@ dependencies = [
|
||||
"version_check",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "getrandom"
|
||||
version = "0.3.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "899def5c37c4fd7b2664648c28120ecec138e4d395b459e5ca34f9cce2dd77fd"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"libc",
|
||||
"r-efi 5.3.0",
|
||||
"wasip2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "getrandom"
|
||||
version = "0.4.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"libc",
|
||||
"r-efi 6.0.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "gif"
|
||||
version = "0.14.2"
|
||||
@@ -283,12 +458,54 @@ dependencies = [
|
||||
"quick-error",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "imgref"
|
||||
version = "1.12.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6e44b0a4eaa4c82f441d50a963f2d5f05a787240aeee097597033e72accfd22f"
|
||||
|
||||
[[package]]
|
||||
name = "interpolate_name"
|
||||
version = "0.2.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c34819042dc3d3971c46c2190835914dfbe0c3c13f61449b2997f4e9722dfa60"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 2.0.119",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "itertools"
|
||||
version = "0.14.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2b192c782037fadd9cfa75548310488aabdbf3d2da73885b31bd0abd03351285"
|
||||
dependencies = [
|
||||
"either",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "itoa"
|
||||
version = "1.0.18"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682"
|
||||
|
||||
[[package]]
|
||||
name = "jixel"
|
||||
version = "0.3.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "278a75e12caacec34be774d62ad05e45fc0b6a52d1f4e9f7fbc0209ecdf794f3"
|
||||
|
||||
[[package]]
|
||||
name = "jobserver"
|
||||
version = "0.1.35"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1c00acbd29eabad4a2392fa0e921c874934dbbf4194312ad20f04a0ed67a3cb3"
|
||||
dependencies = [
|
||||
"getrandom 0.4.3",
|
||||
"libc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "jpeg-decoder"
|
||||
version = "0.3.2"
|
||||
@@ -498,20 +715,35 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ce5d3ddc6d3fa000eb1536d85e147bfe31aacaba692ed6a876f95cb7c855be78"
|
||||
|
||||
[[package]]
|
||||
name = "lightcraft-codecs"
|
||||
version = "0.6.0"
|
||||
source = "git+https://github.com/storytold/lightcraft?rev=0dd6593d9db55a17ab559261bac4d766f015c345#0dd6593d9db55a17ab559261bac4d766f015c345"
|
||||
name = "libfuzzer-sys"
|
||||
version = "0.4.13"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a9fd2f41a1cba099f79a0b6b6c35656cf7c03351a7bae8ff0f28f25270f929d2"
|
||||
dependencies = [
|
||||
"arbitrary",
|
||||
"cc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "lightcraft-codecs"
|
||||
version = "0.10.0"
|
||||
source = "git+https://github.com/storytold/lightcraft?rev=5fe74557eca64638b1f9015c9769f7e52a889fa2#5fe74557eca64638b1f9015c9769f7e52a889fa2"
|
||||
dependencies = [
|
||||
"avif-serialize",
|
||||
"bytemuck",
|
||||
"image",
|
||||
"image-webp",
|
||||
"jixel",
|
||||
"jpeg-decoder",
|
||||
"jpeg-encoder",
|
||||
"jxl-oxide",
|
||||
"lightcraft-color",
|
||||
"lightcraft-geom",
|
||||
"lightcraft-raster",
|
||||
"moxcms 0.9.1",
|
||||
"png",
|
||||
"rav1e",
|
||||
"ravif",
|
||||
"rayon",
|
||||
"serde",
|
||||
"thiserror",
|
||||
@@ -522,8 +754,8 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "lightcraft-color"
|
||||
version = "0.6.0"
|
||||
source = "git+https://github.com/storytold/lightcraft?rev=0dd6593d9db55a17ab559261bac4d766f015c345#0dd6593d9db55a17ab559261bac4d766f015c345"
|
||||
version = "0.10.0"
|
||||
source = "git+https://github.com/storytold/lightcraft?rev=5fe74557eca64638b1f9015c9769f7e52a889fa2#5fe74557eca64638b1f9015c9769f7e52a889fa2"
|
||||
dependencies = [
|
||||
"lightcraft-geom",
|
||||
"serde",
|
||||
@@ -531,8 +763,8 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "lightcraft-develop"
|
||||
version = "0.6.0"
|
||||
source = "git+https://github.com/storytold/lightcraft?rev=0dd6593d9db55a17ab559261bac4d766f015c345#0dd6593d9db55a17ab559261bac4d766f015c345"
|
||||
version = "0.10.0"
|
||||
source = "git+https://github.com/storytold/lightcraft?rev=5fe74557eca64638b1f9015c9769f7e52a889fa2#5fe74557eca64638b1f9015c9769f7e52a889fa2"
|
||||
dependencies = [
|
||||
"lightcraft-color",
|
||||
"lightcraft-geom",
|
||||
@@ -543,8 +775,8 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "lightcraft-faces"
|
||||
version = "0.6.0"
|
||||
source = "git+https://github.com/storytold/lightcraft?rev=0dd6593d9db55a17ab559261bac4d766f015c345#0dd6593d9db55a17ab559261bac4d766f015c345"
|
||||
version = "0.10.0"
|
||||
source = "git+https://github.com/storytold/lightcraft?rev=5fe74557eca64638b1f9015c9769f7e52a889fa2#5fe74557eca64638b1f9015c9769f7e52a889fa2"
|
||||
dependencies = [
|
||||
"matrixmultiply",
|
||||
"ndarray",
|
||||
@@ -557,16 +789,41 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "lightcraft-geom"
|
||||
version = "0.6.0"
|
||||
source = "git+https://github.com/storytold/lightcraft?rev=0dd6593d9db55a17ab559261bac4d766f015c345#0dd6593d9db55a17ab559261bac4d766f015c345"
|
||||
version = "0.10.0"
|
||||
source = "git+https://github.com/storytold/lightcraft?rev=5fe74557eca64638b1f9015c9769f7e52a889fa2#5fe74557eca64638b1f9015c9769f7e52a889fa2"
|
||||
dependencies = [
|
||||
"serde",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "lightcraft-inpaint"
|
||||
version = "0.10.0"
|
||||
source = "git+https://github.com/storytold/lightcraft?rev=5fe74557eca64638b1f9015c9769f7e52a889fa2#5fe74557eca64638b1f9015c9769f7e52a889fa2"
|
||||
dependencies = [
|
||||
"rayon",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "lightcraft-merge"
|
||||
version = "0.10.0"
|
||||
source = "git+https://github.com/storytold/lightcraft?rev=5fe74557eca64638b1f9015c9769f7e52a889fa2#5fe74557eca64638b1f9015c9769f7e52a889fa2"
|
||||
dependencies = [
|
||||
"lightcraft-codecs",
|
||||
"lightcraft-color",
|
||||
"lightcraft-geom",
|
||||
"lightcraft-meta",
|
||||
"lightcraft-raster",
|
||||
"lightcraft-raw",
|
||||
"lightcraft-scenes",
|
||||
"rayon",
|
||||
"serde",
|
||||
"thiserror",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "lightcraft-meta"
|
||||
version = "0.6.0"
|
||||
source = "git+https://github.com/storytold/lightcraft?rev=0dd6593d9db55a17ab559261bac4d766f015c345#0dd6593d9db55a17ab559261bac4d766f015c345"
|
||||
version = "0.10.0"
|
||||
source = "git+https://github.com/storytold/lightcraft?rev=5fe74557eca64638b1f9015c9769f7e52a889fa2#5fe74557eca64638b1f9015c9769f7e52a889fa2"
|
||||
dependencies = [
|
||||
"lightcraft-geom",
|
||||
"lightcraft-tiff",
|
||||
@@ -576,12 +833,13 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "lightcraft-pipeline"
|
||||
version = "0.6.0"
|
||||
source = "git+https://github.com/storytold/lightcraft?rev=0dd6593d9db55a17ab559261bac4d766f015c345#0dd6593d9db55a17ab559261bac4d766f015c345"
|
||||
version = "0.10.0"
|
||||
source = "git+https://github.com/storytold/lightcraft?rev=5fe74557eca64638b1f9015c9769f7e52a889fa2#5fe74557eca64638b1f9015c9769f7e52a889fa2"
|
||||
dependencies = [
|
||||
"lightcraft-color",
|
||||
"lightcraft-develop",
|
||||
"lightcraft-geom",
|
||||
"lightcraft-inpaint",
|
||||
"lightcraft-raster",
|
||||
"lightcraft-raw",
|
||||
"rayon",
|
||||
@@ -590,8 +848,8 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "lightcraft-raster"
|
||||
version = "0.6.0"
|
||||
source = "git+https://github.com/storytold/lightcraft?rev=0dd6593d9db55a17ab559261bac4d766f015c345#0dd6593d9db55a17ab559261bac4d766f015c345"
|
||||
version = "0.10.0"
|
||||
source = "git+https://github.com/storytold/lightcraft?rev=5fe74557eca64638b1f9015c9769f7e52a889fa2#5fe74557eca64638b1f9015c9769f7e52a889fa2"
|
||||
dependencies = [
|
||||
"lightcraft-color",
|
||||
"lightcraft-geom",
|
||||
@@ -601,9 +859,10 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "lightcraft-raw"
|
||||
version = "0.6.0"
|
||||
source = "git+https://github.com/storytold/lightcraft?rev=0dd6593d9db55a17ab559261bac4d766f015c345#0dd6593d9db55a17ab559261bac4d766f015c345"
|
||||
version = "0.10.0"
|
||||
source = "git+https://github.com/storytold/lightcraft?rev=5fe74557eca64638b1f9015c9769f7e52a889fa2#5fe74557eca64638b1f9015c9769f7e52a889fa2"
|
||||
dependencies = [
|
||||
"jpeg-encoder",
|
||||
"jxl-oxide",
|
||||
"lightcraft-color",
|
||||
"lightcraft-geom",
|
||||
@@ -618,15 +877,41 @@ dependencies = [
|
||||
"zune-jpeg",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "lightcraft-scenes"
|
||||
version = "0.10.0"
|
||||
source = "git+https://github.com/storytold/lightcraft?rev=5fe74557eca64638b1f9015c9769f7e52a889fa2#5fe74557eca64638b1f9015c9769f7e52a889fa2"
|
||||
dependencies = [
|
||||
"lightcraft-color",
|
||||
"lightcraft-raster",
|
||||
"rayon",
|
||||
"serde",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "lightcraft-tiff"
|
||||
version = "0.6.0"
|
||||
source = "git+https://github.com/storytold/lightcraft?rev=0dd6593d9db55a17ab559261bac4d766f015c345#0dd6593d9db55a17ab559261bac4d766f015c345"
|
||||
version = "0.10.0"
|
||||
source = "git+https://github.com/storytold/lightcraft?rev=5fe74557eca64638b1f9015c9769f7e52a889fa2#5fe74557eca64638b1f9015c9769f7e52a889fa2"
|
||||
dependencies = [
|
||||
"serde",
|
||||
"thiserror",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "log"
|
||||
version = "0.4.34"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f9f8bd3e56ce4dfc153cf470fffbfa98c7620958b312ca5c3a4b8d5181fd13c6"
|
||||
|
||||
[[package]]
|
||||
name = "loop9"
|
||||
version = "0.1.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0fae87c125b03c1d2c0150c90365d7d6bcc53fb73a9acaef207d2d065860f062"
|
||||
dependencies = [
|
||||
"imgref",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "matrixmultiply"
|
||||
version = "0.3.11"
|
||||
@@ -637,6 +922,16 @@ dependencies = [
|
||||
"rawpointer",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "maybe-rayon"
|
||||
version = "0.1.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8ea1f30cedd69f0a2954655f7188c6a834246d2bcf1e315e2ac40c4b24dc9519"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"rayon",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "memchr"
|
||||
version = "2.8.3"
|
||||
@@ -698,6 +993,46 @@ dependencies = [
|
||||
"rawpointer",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "new_debug_unreachable"
|
||||
version = "1.0.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "650eef8c711430f1a879fdd01d4745a7deea475becfb90269c06775983bbf086"
|
||||
|
||||
[[package]]
|
||||
name = "no_std_io2"
|
||||
version = "0.9.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "418abd1b6d34fbf6cae440dc874771b0525a604428704c76e48b29a5e67b8003"
|
||||
dependencies = [
|
||||
"memchr",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "nom"
|
||||
version = "8.0.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "df9761775871bdef83bee530e60050f7e54b1105350d6884eb0fb4f46c2f9405"
|
||||
dependencies = [
|
||||
"memchr",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "noop_proc_macro"
|
||||
version = "0.3.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0676bb32a98c1a483ce53e500a81ad9c3d5b3f7c920c28c24e9cb0980d0b5bc8"
|
||||
|
||||
[[package]]
|
||||
name = "num-bigint"
|
||||
version = "0.4.8"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c89e69e7e0f03bea5ef08013795c25018e101932225a656383bd384495ecc367"
|
||||
dependencies = [
|
||||
"num-integer",
|
||||
"num-traits",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "num-complex"
|
||||
version = "0.4.6"
|
||||
@@ -707,6 +1042,17 @@ dependencies = [
|
||||
"num-traits",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "num-derive"
|
||||
version = "0.4.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ed3955f1a9c7c0c15e092f9c887db08b1fc683305fdf6eb6684f22555355e202"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 2.0.119",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "num-integer"
|
||||
version = "0.1.47"
|
||||
@@ -716,6 +1062,17 @@ dependencies = [
|
||||
"num-traits",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "num-rational"
|
||||
version = "0.4.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f83d14da390562dca69fc84082e73e548e1ad308d24accdedd2720017cb37824"
|
||||
dependencies = [
|
||||
"num-bigint",
|
||||
"num-integer",
|
||||
"num-traits",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "num-traits"
|
||||
version = "0.2.19"
|
||||
@@ -731,15 +1088,31 @@ version = "1.21.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50"
|
||||
|
||||
[[package]]
|
||||
name = "paste"
|
||||
version = "1.0.15"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "57c0d7b74b563b49d38dae00a0c37d4d6de9b432382b2892f0574ddcae73fd0a"
|
||||
|
||||
[[package]]
|
||||
name = "pastey"
|
||||
version = "0.1.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "35fb2e5f958ec131621fdd531e9fc186ed768cbe395337403ae56c17a74c68ec"
|
||||
|
||||
[[package]]
|
||||
name = "photoreport-engine"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"lightcraft-codecs",
|
||||
"lightcraft-color",
|
||||
"lightcraft-develop",
|
||||
"lightcraft-geom",
|
||||
"lightcraft-merge",
|
||||
"lightcraft-meta",
|
||||
"lightcraft-pipeline",
|
||||
"lightcraft-raster",
|
||||
"lightcraft-raw",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"thiserror",
|
||||
@@ -808,6 +1181,15 @@ dependencies = [
|
||||
"portable-atomic",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "ppv-lite86"
|
||||
version = "0.2.21"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "85eae3c4ed2f50dcfe72643da4befc30deadb458a9b590d720cde2f2b1e97da9"
|
||||
dependencies = [
|
||||
"zerocopy",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "proc-macro2"
|
||||
version = "1.0.107"
|
||||
@@ -817,6 +1199,25 @@ dependencies = [
|
||||
"unicode-ident",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "profiling"
|
||||
version = "1.0.18"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3d595e54a326bc53c1c197b32d295e14b169e3cfeaa8dc82b529f947fba6bcf5"
|
||||
dependencies = [
|
||||
"profiling-procmacros",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "profiling-procmacros"
|
||||
version = "1.0.18"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4488a4a36b9a4ba6b9334a32a39971f77c1436ec82c38707bce707699cc3bbcb"
|
||||
dependencies = [
|
||||
"quote",
|
||||
"syn 2.0.119",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "pxfm"
|
||||
version = "0.1.30"
|
||||
@@ -847,6 +1248,97 @@ dependencies = [
|
||||
"proc-macro2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "r-efi"
|
||||
version = "5.3.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "69cdb34c158ceb288df11e18b4bd39de994f6657d83847bdffdbd7f346754b0f"
|
||||
|
||||
[[package]]
|
||||
name = "r-efi"
|
||||
version = "6.0.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf"
|
||||
|
||||
[[package]]
|
||||
name = "rand"
|
||||
version = "0.9.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b9ef1d0d795eb7d84685bca4f72f3649f064e6641543d3a8c415898726a57b41"
|
||||
dependencies = [
|
||||
"rand_chacha",
|
||||
"rand_core",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rand_chacha"
|
||||
version = "0.9.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d3022b5f1df60f26e1ffddd6c66e8aa15de382ae63b3a0c1bfc0e4d3e3f325cb"
|
||||
dependencies = [
|
||||
"ppv-lite86",
|
||||
"rand_core",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rand_core"
|
||||
version = "0.9.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "76afc826de14238e6e8c374ddcc1fa19e374fd8dd986b0d2af0d02377261d83c"
|
||||
dependencies = [
|
||||
"getrandom 0.3.4",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rav1e"
|
||||
version = "0.8.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "43b6dd56e85d9483277cde964fd1bdb0428de4fec5ebba7540995639a21cb32b"
|
||||
dependencies = [
|
||||
"aligned-vec",
|
||||
"arbitrary",
|
||||
"arg_enum_proc_macro",
|
||||
"arrayvec",
|
||||
"av-scenechange",
|
||||
"av1-grain",
|
||||
"bitstream-io",
|
||||
"built",
|
||||
"cfg-if",
|
||||
"interpolate_name",
|
||||
"itertools",
|
||||
"libc",
|
||||
"libfuzzer-sys",
|
||||
"log",
|
||||
"maybe-rayon",
|
||||
"new_debug_unreachable",
|
||||
"noop_proc_macro",
|
||||
"num-derive",
|
||||
"num-traits",
|
||||
"paste",
|
||||
"profiling",
|
||||
"rand",
|
||||
"rand_chacha",
|
||||
"simd_helpers",
|
||||
"thiserror",
|
||||
"v_frame",
|
||||
"wasm-bindgen",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "ravif"
|
||||
version = "0.13.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e52310197d971b0f5be7fe6b57530dcd27beb35c1b013f29d66c1ad73fbbcc45"
|
||||
dependencies = [
|
||||
"avif-serialize",
|
||||
"imgref",
|
||||
"loop9",
|
||||
"quick-error",
|
||||
"rav1e",
|
||||
"rayon",
|
||||
"rgb",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rawpointer"
|
||||
version = "0.2.1"
|
||||
@@ -873,6 +1365,12 @@ dependencies = [
|
||||
"crossbeam-utils",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rgb"
|
||||
version = "0.8.53"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "47b34b781b31e5d73e9fbc8689c70551fd1ade9a19e3e28cfec8580a79290cc4"
|
||||
|
||||
[[package]]
|
||||
name = "rustversion"
|
||||
version = "1.0.23"
|
||||
@@ -933,18 +1431,39 @@ dependencies = [
|
||||
"digest",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "shlex"
|
||||
version = "2.0.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba"
|
||||
|
||||
[[package]]
|
||||
name = "simd-adler32"
|
||||
version = "0.3.10"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3a219298ac11a56ea9a6d2120044824d6f01aeb034955e7af7bc16858527deea"
|
||||
|
||||
[[package]]
|
||||
name = "simd_helpers"
|
||||
version = "0.1.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "95890f873bec569a0362c235787f3aca6e1e887302ba4840839bcc6459c42da6"
|
||||
dependencies = [
|
||||
"quote",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "slab"
|
||||
version = "0.4.12"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5"
|
||||
|
||||
[[package]]
|
||||
name = "stable_deref_trait"
|
||||
version = "1.2.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596"
|
||||
|
||||
[[package]]
|
||||
name = "syn"
|
||||
version = "2.0.119"
|
||||
@@ -1032,12 +1551,32 @@ version = "1.0.26"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d245f478577f809a851594d02313b640fb437e0bb33866753cff937863096954"
|
||||
|
||||
[[package]]
|
||||
name = "v_frame"
|
||||
version = "0.3.9"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "666b7727c8875d6ab5db9533418d7c764233ac9c0cff1d469aec8fa127597be2"
|
||||
dependencies = [
|
||||
"aligned-vec",
|
||||
"num-traits",
|
||||
"wasm-bindgen",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "version_check"
|
||||
version = "0.9.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a"
|
||||
|
||||
[[package]]
|
||||
name = "wasip2"
|
||||
version = "1.0.4+wasi-0.2.12"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b67efb37e106e55ce722a510d6b5f9c17f083e5fc79afc2badeb12cc313d9487"
|
||||
dependencies = [
|
||||
"wit-bindgen",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "wasm-bindgen"
|
||||
version = "0.2.129"
|
||||
@@ -1099,6 +1638,18 @@ version = "0.1.12"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a28ac98ddc8b9274cb41bb4d9d4d5c425b6020c50c46f25559911905610b4a88"
|
||||
|
||||
[[package]]
|
||||
name = "wit-bindgen"
|
||||
version = "0.57.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1ebf944e87a7c253233ad6766e082e3cd714b5d03812acc24c318f549614536e"
|
||||
|
||||
[[package]]
|
||||
name = "y4m"
|
||||
version = "0.8.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7a5a4b21e1a62b67a2970e6831bc091d7b87e119e7f9791aef9702e3bef04448"
|
||||
|
||||
[[package]]
|
||||
name = "zerocopy"
|
||||
version = "0.8.62"
|
||||
|
||||
+10
-6
@@ -10,12 +10,16 @@ publish = false
|
||||
|
||||
[workspace.dependencies]
|
||||
# LightCraft is consumed, never forked. Bump `rev` deliberately and run the reference-image tests.
|
||||
lightcraft-develop = { git = "https://github.com/storytold/lightcraft", rev = "0dd6593d9db55a17ab559261bac4d766f015c345" }
|
||||
lightcraft-codecs = { git = "https://github.com/storytold/lightcraft", rev = "0dd6593d9db55a17ab559261bac4d766f015c345", default-features = false }
|
||||
lightcraft-pipeline = { git = "https://github.com/storytold/lightcraft", rev = "0dd6593d9db55a17ab559261bac4d766f015c345" }
|
||||
lightcraft-raster = { git = "https://github.com/storytold/lightcraft", rev = "0dd6593d9db55a17ab559261bac4d766f015c345" }
|
||||
lightcraft-geom = { git = "https://github.com/storytold/lightcraft", rev = "0dd6593d9db55a17ab559261bac4d766f015c345" }
|
||||
lightcraft-faces = { git = "https://github.com/storytold/lightcraft", rev = "0dd6593d9db55a17ab559261bac4d766f015c345" }
|
||||
lightcraft-develop = { git = "https://github.com/storytold/lightcraft", rev = "5fe74557eca64638b1f9015c9769f7e52a889fa2" }
|
||||
lightcraft-codecs = { git = "https://github.com/storytold/lightcraft", rev = "5fe74557eca64638b1f9015c9769f7e52a889fa2", default-features = false }
|
||||
lightcraft-pipeline = { git = "https://github.com/storytold/lightcraft", rev = "5fe74557eca64638b1f9015c9769f7e52a889fa2" }
|
||||
lightcraft-raster = { git = "https://github.com/storytold/lightcraft", rev = "5fe74557eca64638b1f9015c9769f7e52a889fa2" }
|
||||
lightcraft-geom = { git = "https://github.com/storytold/lightcraft", rev = "5fe74557eca64638b1f9015c9769f7e52a889fa2" }
|
||||
lightcraft-faces = { git = "https://github.com/storytold/lightcraft", rev = "5fe74557eca64638b1f9015c9769f7e52a889fa2" }
|
||||
lightcraft-merge = { git = "https://github.com/storytold/lightcraft", rev = "5fe74557eca64638b1f9015c9769f7e52a889fa2" }
|
||||
lightcraft-raw = { git = "https://github.com/storytold/lightcraft", rev = "5fe74557eca64638b1f9015c9769f7e52a889fa2" }
|
||||
lightcraft-color = { git = "https://github.com/storytold/lightcraft", rev = "5fe74557eca64638b1f9015c9769f7e52a889fa2" }
|
||||
lightcraft-meta = { git = "https://github.com/storytold/lightcraft", rev = "5fe74557eca64638b1f9015c9769f7e52a889fa2" }
|
||||
serde = { version = "1", features = ["derive"] }
|
||||
serde_json = "1"
|
||||
thiserror = "2"
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
-- Faces in archive videos: appearances (a face followed through frames) in the events' face groups.
|
||||
ALTER TABLE "cloud_videos" ADD COLUMN "faces_status" "FacesStatus" NOT NULL DEFAULT 'NONE';
|
||||
CREATE INDEX "cloud_videos_faces_status_idx" ON "cloud_videos"("faces_status");
|
||||
|
||||
CREATE TABLE "video_faces" (
|
||||
"id" UUID NOT NULL,
|
||||
"video_id" UUID NOT NULL,
|
||||
"group_id" UUID,
|
||||
"start_ms" INTEGER NOT NULL,
|
||||
"end_ms" INTEGER NOT NULL,
|
||||
"at_ms" INTEGER NOT NULL,
|
||||
"x0" DOUBLE PRECISION NOT NULL,
|
||||
"y0" DOUBLE PRECISION NOT NULL,
|
||||
"x1" DOUBLE PRECISION NOT NULL,
|
||||
"y1" DOUBLE PRECISION NOT NULL,
|
||||
"score" DOUBLE PRECISION NOT NULL,
|
||||
"sharpness" DOUBLE PRECISION,
|
||||
"embedding" DOUBLE PRECISION[] DEFAULT ARRAY[]::DOUBLE PRECISION[],
|
||||
"model" TEXT NOT NULL,
|
||||
"frames" INTEGER NOT NULL,
|
||||
"frame_key" TEXT NOT NULL,
|
||||
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
CONSTRAINT "video_faces_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
CREATE INDEX "video_faces_video_id_idx" ON "video_faces"("video_id");
|
||||
CREATE INDEX "video_faces_group_id_idx" ON "video_faces"("group_id");
|
||||
ALTER TABLE "video_faces" ADD CONSTRAINT "video_faces_video_id_fkey" FOREIGN KEY ("video_id") REFERENCES "cloud_videos"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
ALTER TABLE "video_faces" ADD CONSTRAINT "video_faces_group_id_fkey" FOREIGN KEY ("group_id") REFERENCES "face_groups"("id") ON DELETE SET NULL ON UPDATE CASCADE;
|
||||
|
||||
-- Videos already made, in organizations with face recognition on (as their photos): their faces are found next.
|
||||
UPDATE "cloud_videos" v SET "faces_status" = 'PENDING'
|
||||
FROM "cloud_sources" s JOIN "organizations" o ON o."id" = s."organization_id"
|
||||
WHERE v."source_id" = s."id" AND o."biometrics_enabled" AND v."status" = 'DONE';
|
||||
@@ -0,0 +1,2 @@
|
||||
-- AlterTable
|
||||
ALTER TABLE "organizations" ADD COLUMN "real_estate_enabled" BOOLEAN NOT NULL DEFAULT false;
|
||||
@@ -62,6 +62,8 @@ model Organization {
|
||||
/// Face recognition is biometric data: off unless enabled with a recorded legal basis.
|
||||
biometricsEnabled Boolean @default(false) @map("biometrics_enabled")
|
||||
biometricsLegalBasis String? @map("biometrics_legal_basis")
|
||||
/// Interior brackets. Off: the area is hidden and its routes refuse work. Sports ingest is unchanged.
|
||||
realEstateEnabled Boolean @default(false) @map("real_estate_enabled")
|
||||
createdAt DateTime @default(now()) @map("created_at")
|
||||
updatedAt DateTime @updatedAt @map("updated_at")
|
||||
|
||||
@@ -695,6 +697,7 @@ model FaceGroup {
|
||||
person Person? @relation("confirmed", fields: [personId], references: [id], onDelete: SetNull)
|
||||
suggested Person? @relation("suggested", fields: [suggestedPersonId], references: [id], onDelete: SetNull)
|
||||
faces Face[]
|
||||
videoFaces VideoFace[]
|
||||
rejections FaceGroupRejection[]
|
||||
|
||||
@@index([eventId])
|
||||
@@ -1747,18 +1750,58 @@ model CloudVideo {
|
||||
storageKey String? @map("storage_key")
|
||||
/// Size of the web copy.
|
||||
webBytes BigInt? @map("web_bytes")
|
||||
/// Faces in the video (frames through the same engine as the photos): NONE (organization without biometrics),
|
||||
/// PENDING, RUNNING, DONE, FAILED.
|
||||
facesStatus FacesStatus @default(NONE) @map("faces_status")
|
||||
createdAt DateTime @default(now()) @map("created_at")
|
||||
updatedAt DateTime @updatedAt @map("updated_at")
|
||||
|
||||
source CloudSource @relation(fields: [sourceId], references: [id], onDelete: Cascade)
|
||||
folder CloudFolder @relation(fields: [folderId], references: [id], onDelete: Cascade)
|
||||
faces VideoFace[]
|
||||
|
||||
@@unique([sourceId, fileId])
|
||||
@@index([status, sourceId])
|
||||
@@index([folderId, status, path])
|
||||
@@index([facesStatus])
|
||||
@@map("cloud_videos")
|
||||
}
|
||||
|
||||
/// One appearance of a face in an archive video: the same face followed through consecutive frames (each frame
|
||||
/// analysed by the same engine as the photos). It joins the event's face groups like a photo's face, so naming,
|
||||
/// suggestions, "não é" and false positives are the photos' own.
|
||||
model VideoFace {
|
||||
id String @id @default(uuid()) @db.Uuid
|
||||
videoId String @map("video_id") @db.Uuid
|
||||
groupId String? @map("group_id") @db.Uuid
|
||||
/// When it is on screen (ms from the start), and the frame it is clearest in.
|
||||
startMs Int @map("start_ms")
|
||||
endMs Int @map("end_ms")
|
||||
atMs Int @map("at_ms")
|
||||
/// Box in that frame, in fractions (0 to 1, y down).
|
||||
x0 Float
|
||||
y0 Float
|
||||
x1 Float
|
||||
y1 Float
|
||||
score Float
|
||||
sharpness Float?
|
||||
/// Mean of the appearance's sharp embeddings (unit length), from `model`.
|
||||
embedding Float[] @default([])
|
||||
model String
|
||||
/// Frames it was found in.
|
||||
frames Int
|
||||
/// That frame as a JPEG in storage (shown when the face is reviewed).
|
||||
frameKey String @map("frame_key")
|
||||
createdAt DateTime @default(now()) @map("created_at")
|
||||
|
||||
video CloudVideo @relation(fields: [videoId], references: [id], onDelete: Cascade)
|
||||
group FaceGroup? @relation(fields: [groupId], references: [id], onDelete: SetNull)
|
||||
|
||||
@@index([videoId])
|
||||
@@index([groupId])
|
||||
@@map("video_faces")
|
||||
}
|
||||
|
||||
/// What one viewer may see, written when they sign in. Later pages read this row; they do not call the cloud again.
|
||||
/// Shares stay as they were at sign-in until the session ends.
|
||||
model ArchiveGrant {
|
||||
|
||||
@@ -26,6 +26,7 @@ import { registerUploadRoutes } from "./library/uploads.js";
|
||||
import { IngestService } from "./ingest/service.js";
|
||||
import { CorrectionRecorder } from "./autopilot/learning.js";
|
||||
import { registerAutopilotRoutes } from "./autopilot/routes.js";
|
||||
import { registerRealEstateRoutes } from "./realestate/routes.js";
|
||||
import { registerDevelopRoutes } from "./develop/routes.js";
|
||||
import { DevelopService } from "./develop/service.js";
|
||||
import { registerFaceRoutes } from "./faces/routes.js";
|
||||
@@ -196,6 +197,7 @@ export async function buildApp({ config, db, realtime, fetchImpl, reporter: give
|
||||
const develop = new DevelopService({ db, storage, signer, broadcaster, log: app.log, onHumanEdit: (id) => corrections.schedule(id) });
|
||||
await registerDevelopRoutes(app, { db, sessions, develop });
|
||||
await registerAutopilotRoutes(app, { db, sessions });
|
||||
await registerRealEstateRoutes(app, { db, sessions });
|
||||
// Shop: the public sites read galleries and place orders; the worker renders the bought files.
|
||||
const print = new PrintService({ db, storage, signer, broadcaster, log: app.log, secret: config.JWT_SECRET, secrets, stripeApiUrl: config.STRIPE_API_URL, ...(fetchImpl && { fetchImpl }) });
|
||||
const notifications = new Notifications(db, (err) => app.log.warn({ err }, "notifications: not written"));
|
||||
|
||||
@@ -10,6 +10,7 @@ import type { UrlSigner } from "../storage/storage.js";
|
||||
import { publishedPhotos } from "./gallery.js";
|
||||
import { isNationalSide } from "./match.js";
|
||||
import type { Viewer } from "./viewer.js";
|
||||
import { videoFaceCrop, videoScope } from "./video-faces.js";
|
||||
|
||||
/**
|
||||
* People in the archive, for its viewers: who appears in the galleries they may see (named from faces), all the
|
||||
@@ -260,7 +261,42 @@ export async function registerArchivePeopleRoutes(app: FastifyInstance, deps: De
|
||||
}
|
||||
const chosen = onePerPhoto(hits).slice(0, query.limit);
|
||||
const photos = scope ? await photoCards(chosen, scope) : [];
|
||||
// The videos they appear in (named or probable), each with its clearest frame and every moment.
|
||||
const visible = await visibleFolders(v);
|
||||
const seen =
|
||||
visible === "all" || visible.length
|
||||
? await db.$queryRaw<{ id: string; video_id: string; folder_id: string; name: string; confirmed: boolean; score: number | null; start_ms: number; end_ms: number; x0: number; y0: number; x1: number; y1: number; width: number | null; height: number | null; duration_ms: number | null; sharpness: number | null }[]>`
|
||||
SELECT vf.id, vf.video_id, cv.folder_id, cv.path AS name, (g.person_id IS NOT NULL) AS confirmed, g.suggestion_score AS score,
|
||||
vf.start_ms, vf.end_ms, vf.x0, vf.y0, vf.x1, vf.y1, cv.width, cv.height, cv.duration_ms, vf.sharpness
|
||||
FROM video_faces vf
|
||||
JOIN face_groups g ON g.id = vf.group_id AND g.ignored_at IS NULL
|
||||
JOIN cloud_videos cv ON cv.id = vf.video_id AND ${videoScope(sourceId, visible)}
|
||||
WHERE g.person_id = ${personId}::uuid OR (${query.level === "all"} AND g.person_id IS NULL AND g.suggested_person_id = ${personId}::uuid)
|
||||
ORDER BY vf.start_ms`
|
||||
: [];
|
||||
const byVideo = new Map<string, typeof seen>();
|
||||
for (const r of seen) byVideo.set(r.video_id, [...(byVideo.get(r.video_id) ?? []), r]);
|
||||
const galleries = await galleryInfo(seen.map((r) => r.folder_id));
|
||||
const videos = [...byVideo.entries()].map(([videoId, list]) => {
|
||||
const clearest = list.reduce((a, b) => ((b.sharpness ?? 0) > (a.sharpness ?? 0) ? b : a));
|
||||
return {
|
||||
id: videoId,
|
||||
name: clearest.name.split("/").pop(),
|
||||
level: list.some((r) => r.confirmed) ? ("confirmed" as const) : ("probable" as const),
|
||||
durationMs: clearest.duration_ms,
|
||||
width: clearest.width,
|
||||
height: clearest.height,
|
||||
face: videoFaceCrop(signer, clearest),
|
||||
moments: list.map((r) => ({ startMs: r.start_ms, endMs: r.end_ms })),
|
||||
thumb: signer.videoUrl(videoId, "thumb"),
|
||||
poster: signer.videoUrl(videoId, "poster"),
|
||||
src: signer.videoUrl(videoId, "web"),
|
||||
download: signer.videoUrl(videoId, "download"),
|
||||
gallery: galleries.get(clearest.folder_id) ?? null,
|
||||
};
|
||||
});
|
||||
return {
|
||||
videos,
|
||||
person: { id: person.id, name: person.name, club: person.club, number: person.number, reference: person.referenceKey ? signer.personUrl(person.id) : null },
|
||||
counts: { confirmed: photos.filter((p) => p.level === "confirmed").length, probable: photos.filter((p) => p.level === "probable").length, similar: photos.filter((p) => p.level === "similar").length },
|
||||
photos,
|
||||
|
||||
@@ -9,6 +9,7 @@ import type { UrlSigner } from "../storage/storage.js";
|
||||
import { galleryMemberIds } from "./gallery.js";
|
||||
import { clubKey, faceBox } from "./people.js";
|
||||
import type { Viewer } from "./viewer.js";
|
||||
import { videoFaceCrop, videoScope } from "./video-faces.js";
|
||||
|
||||
/**
|
||||
* Face review for archive viewers who may edit on the cloud. Rights come from the cloud, never from here:
|
||||
@@ -51,14 +52,28 @@ const Recognition = z.object({ enabled: z.boolean(), removeConfirmed: z.boolean(
|
||||
export async function registerArchiveReviewRoutes(app: FastifyInstance, deps: Deps) {
|
||||
const { db, signer, faces, viewerOf, editableFolders } = deps;
|
||||
|
||||
/** Indexed files of the source the viewer may edit, as a condition on `cf`; null when none. */
|
||||
const editScope = async (v: Viewer): Promise<{ sql: Prisma.Sql; all: boolean } | null> => {
|
||||
/**
|
||||
* Indexed files of the source the viewer may edit, as a condition on `cf` (photos) and on `cv` (videos); null when
|
||||
* none.
|
||||
*/
|
||||
const editScope = async (v: Viewer): Promise<{ sql: Prisma.Sql; vsql: Prisma.Sql; vedit: Prisma.Sql; all: boolean } | null> => {
|
||||
const editable = await editableFolders(v);
|
||||
if (editable !== "all" && !editable.length) return null;
|
||||
const base = Prisma.sql`cf.source_id = ${v.s}::uuid AND cf.status = 'DONE' AND cf.photo_id IS NOT NULL`;
|
||||
return editable === "all" ? { sql: base, all: true } : { sql: Prisma.sql`${base} AND cf.folder_id = ANY(${editable}::uuid[])`, all: false };
|
||||
return editable === "all"
|
||||
? { sql: base, vsql: videoScope(v.s, "all"), vedit: videoScope(v.s, "all", { edit: true }), all: true }
|
||||
: { sql: Prisma.sql`${base} AND cf.folder_id = ANY(${editable}::uuid[])`, vsql: videoScope(v.s, editable), vedit: videoScope(v.s, editable, { edit: true }), all: false };
|
||||
};
|
||||
|
||||
/**
|
||||
* What a face group holds within a scope: its photos' faces and its videos' appearances, one row each (`item` is
|
||||
* the photo or the video), so a group of a video only is reviewed like any other.
|
||||
*/
|
||||
const members = (scope: { sql: Prisma.Sql; vsql: Prisma.Sql }) => Prisma.sql`
|
||||
SELECT f.group_id, f.photo_id AS item, false AS video FROM faces f JOIN cloud_files cf ON cf.photo_id = f.photo_id AND ${scope.sql}
|
||||
UNION ALL
|
||||
SELECT vf.group_id, vf.video_id AS item, true AS video FROM video_faces vf JOIN cloud_videos cv ON cv.id = vf.video_id AND ${scope.vsql}`;
|
||||
|
||||
const log = (v: Viewer, action: string, data: { personId?: string | null; groupId?: string | null; faces?: number }) =>
|
||||
db.archiveFaceAction.create({ data: { sourceId: v.s, viewer: v.n, action, personId: data.personId ?? null, groupId: data.groupId ?? null, faces: data.faces ?? 0 } });
|
||||
|
||||
@@ -73,9 +88,10 @@ export async function registerArchiveReviewRoutes(app: FastifyInstance, deps: De
|
||||
const scope = await editScope(v);
|
||||
if (!scope) return 0;
|
||||
const [row] = await db.$queryRaw<{ n: number }[]>`
|
||||
WITH m AS (${members(scope)})
|
||||
SELECT count(DISTINCT g.id)::int AS n
|
||||
FROM face_groups g JOIN faces f ON f.group_id = g.id JOIN cloud_files cf ON cf.photo_id = f.photo_id
|
||||
WHERE g.person_id IS NULL AND g.suggested_person_id IS NOT NULL AND g.ignored_at IS NULL AND ${scope.sql}`;
|
||||
FROM face_groups g JOIN m ON m.group_id = g.id
|
||||
WHERE g.person_id IS NULL AND g.suggested_person_id IS NOT NULL AND g.ignored_at IS NULL`;
|
||||
return row?.n ?? 0;
|
||||
})()
|
||||
: 0;
|
||||
@@ -135,7 +151,7 @@ export async function registerArchiveReviewRoutes(app: FastifyInstance, deps: De
|
||||
const folder = await db.cloudFolder.findFirst({ where: { id: query.gallery, sourceId: v.s }, include: { event: true } });
|
||||
if (!folder) throw notFound("gallery_not_found");
|
||||
const ids = await galleryMemberIds(db, v.s, folder);
|
||||
scope = { sql: Prisma.sql`${editable.sql} AND cf.folder_id = ANY(${ids}::uuid[])`, all: false };
|
||||
scope = { sql: Prisma.sql`${editable.sql} AND cf.folder_id = ANY(${ids}::uuid[])`, vsql: Prisma.sql`${editable.vsql} AND cv.folder_id = ANY(${ids}::uuid[])`, vedit: Prisma.sql`${editable.vedit} AND cv.folder_id = ANY(${ids}::uuid[])`, all: false };
|
||||
gallery = { id: folder.id, title: folder.event ? eventName(folder.event) : (folder.path.split("/").filter(Boolean).pop() ?? folder.path) };
|
||||
}
|
||||
const condition: Record<z.infer<typeof Status>, Prisma.Sql> = {
|
||||
@@ -147,11 +163,12 @@ export async function registerArchiveReviewRoutes(app: FastifyInstance, deps: De
|
||||
};
|
||||
const person = query.person ? Prisma.sql`AND (g.person_id = ${query.person}::uuid OR g.suggested_person_id = ${query.person}::uuid OR EXISTS (SELECT 1 FROM face_group_rejections r WHERE r.group_id = g.id AND r.person_id = ${query.person}::uuid))` : Prisma.empty;
|
||||
const [groups, counts, queue] = await Promise.all([
|
||||
db.$queryRaw<{ id: string; event_id: string; person_id: string | null; suggested_person_id: string | null; suggestion_score: number | null; ignored_at: Date | null; size: number; photos: number }[]>`
|
||||
SELECT g.id, g.event_id, g.person_id, g.suggested_person_id, g.suggestion_score, g.ignored_at, g.size, count(DISTINCT f.photo_id)::int AS photos
|
||||
db.$queryRaw<{ id: string; event_id: string; person_id: string | null; suggested_person_id: string | null; suggestion_score: number | null; ignored_at: Date | null; size: number; photos: number; videos: number }[]>`
|
||||
WITH m AS (${members(scope)})
|
||||
SELECT g.id, g.event_id, g.person_id, g.suggested_person_id, g.suggestion_score, g.ignored_at, g.size,
|
||||
count(DISTINCT m.item) FILTER (WHERE NOT m.video)::int AS photos, count(DISTINCT m.item) FILTER (WHERE m.video)::int AS videos
|
||||
FROM face_groups g
|
||||
JOIN faces f ON f.group_id = g.id
|
||||
JOIN cloud_files cf ON cf.photo_id = f.photo_id AND ${scope.sql}
|
||||
JOIN m ON m.group_id = g.id
|
||||
WHERE ${condition[query.status]} ${person}
|
||||
GROUP BY g.id
|
||||
ORDER BY g.suggestion_score DESC NULLS LAST, g.size DESC, g.id
|
||||
@@ -164,14 +181,13 @@ export async function registerArchiveReviewRoutes(app: FastifyInstance, deps: De
|
||||
WHEN g.suggested_person_id IS NOT NULL THEN 'suggested'
|
||||
WHEN EXISTS (SELECT 1 FROM face_group_rejections r WHERE r.group_id = g.id) THEN 'rejected'
|
||||
WHEN g.size >= 2 THEN 'unnamed' END AS status
|
||||
FROM face_groups g JOIN faces f ON f.group_id = g.id JOIN cloud_files cf ON cf.photo_id = f.photo_id AND ${scope.sql}
|
||||
FROM face_groups g JOIN (${members(scope)}) m ON m.group_id = g.id
|
||||
WHERE TRUE ${person}
|
||||
) s WHERE s.status IS NOT NULL GROUP BY s.status`,
|
||||
db.$queryRaw<{ id: string; name: string; club: string | null; number: string | null; reference: boolean; groups: number }[]>`
|
||||
SELECT p.id, p.name, p.club, p.number, p.reference_key IS NOT NULL AS reference, count(DISTINCT g.id)::int AS groups
|
||||
FROM face_groups g
|
||||
JOIN faces f ON f.group_id = g.id
|
||||
JOIN cloud_files cf ON cf.photo_id = f.photo_id AND ${scope.sql}
|
||||
JOIN (${members(scope)}) m ON m.group_id = g.id
|
||||
JOIN people p ON p.id = g.suggested_person_id
|
||||
WHERE g.person_id IS NULL AND g.ignored_at IS NULL
|
||||
GROUP BY p.id ORDER BY count(DISTINCT g.id) DESC, p.name LIMIT 200`,
|
||||
@@ -192,6 +208,16 @@ export async function registerArchiveReviewRoutes(app: FastifyInstance, deps: De
|
||||
where: { id: { in: [...new Set(samples.map((s) => s.photo_id))] } },
|
||||
select: { id: true, width: true, height: true, renderedSeq: true, developSnapshot: true },
|
||||
});
|
||||
// And the clearest appearances in its videos (the frame each is clearest in).
|
||||
const videoSamples = ids.length
|
||||
? await db.$queryRaw<{ group_id: string; id: string; video_id: string; at_ms: number; x0: number; y0: number; x1: number; y1: number; width: number | null; height: number | null }[]>`
|
||||
SELECT group_id, id, video_id, at_ms, x0, y0, x1, y1, width, height FROM (
|
||||
SELECT vf.group_id, vf.id, vf.video_id, vf.at_ms, vf.x0, vf.y0, vf.x1, vf.y1, cv.width, cv.height,
|
||||
row_number() OVER (PARTITION BY vf.group_id ORDER BY vf.sharpness DESC NULLS LAST, vf.score DESC) AS rank
|
||||
FROM video_faces vf JOIN cloud_videos cv ON cv.id = vf.video_id AND ${scope.vsql}
|
||||
WHERE vf.group_id = ANY(${ids}::uuid[])
|
||||
) s WHERE rank <= 8`
|
||||
: [];
|
||||
const photoById = new Map(photos.map((p) => [p.id, p]));
|
||||
const peopleIds = [...new Set(groups.flatMap((g) => [g.person_id, g.suggested_person_id]).filter((x): x is string => !!x))];
|
||||
const [people, events, rejections] = await Promise.all([
|
||||
@@ -216,19 +242,25 @@ export async function registerArchiveReviewRoutes(app: FastifyInstance, deps: De
|
||||
id: g.id,
|
||||
size: g.size,
|
||||
photos: g.photos,
|
||||
videos: g.videos,
|
||||
score: g.suggestion_score,
|
||||
person: personOut(g.person_id),
|
||||
suggested: personOut(g.suggested_person_id),
|
||||
ignored: !!g.ignored_at,
|
||||
notThem: rejections.filter((r) => r.groupId === g.id).map((r) => ({ id: r.person.id, name: r.person.name, by: r.by })),
|
||||
event: e ? { title: eventName(e), startsAt: e.startsAt } : null,
|
||||
faces: samples
|
||||
.filter((s) => s.group_id === g.id)
|
||||
.flatMap((s) => {
|
||||
const p = photoById.get(s.photo_id);
|
||||
if (!p) return [];
|
||||
return [{ id: s.id, photoId: s.photo_id, src: signer.url(s.photo_id, "preview", p.renderedSeq), box: faceBox(s, p), aspect: p.width && p.height ? p.width / p.height : 1.5 }];
|
||||
}),
|
||||
faces: (() => {
|
||||
const fromPhotos = samples
|
||||
.filter((s) => s.group_id === g.id)
|
||||
.flatMap((s) => {
|
||||
const p = photoById.get(s.photo_id);
|
||||
if (!p) return [];
|
||||
return [{ id: s.id, photoId: s.photo_id as string | null, src: signer.url(s.photo_id, "preview", p.renderedSeq), box: faceBox(s, p), aspect: p.width && p.height ? p.width / p.height : 1.5 }];
|
||||
});
|
||||
const fromVideos = videoSamples.filter((s) => s.group_id === g.id).map((s) => ({ id: s.id, photoId: null, video: { id: s.video_id, atMs: s.at_ms }, ...videoFaceCrop(signer, s) }));
|
||||
// Both kinds on the card when the group has both.
|
||||
return [...fromPhotos.slice(0, fromVideos.length ? 6 : 8), ...fromVideos].slice(0, 8);
|
||||
})(),
|
||||
};
|
||||
}),
|
||||
};
|
||||
@@ -243,11 +275,15 @@ export async function registerArchiveReviewRoutes(app: FastifyInstance, deps: De
|
||||
if (!scope) throw forbidden("archive_edit_required");
|
||||
const group = await db.faceGroup.findFirst({ where: { id: groupId, organization: { cloudSources: { some: { id: sourceId } } } } });
|
||||
if (!group) throw notFound("group_not_found");
|
||||
// Every photo of the group must be one the viewer may edit (in this source).
|
||||
// Every photo and video of the group must be one the viewer may edit (in this source).
|
||||
const [rights] = await db.$queryRaw<{ total: number; editable: number }[]>`
|
||||
SELECT count(DISTINCT f.photo_id)::int AS total,
|
||||
count(DISTINCT f.photo_id) FILTER (WHERE EXISTS (SELECT 1 FROM cloud_files cf WHERE cf.photo_id = f.photo_id AND ${scope.sql}))::int AS editable
|
||||
FROM faces f WHERE f.group_id = ${groupId}::uuid`;
|
||||
SELECT count(*)::int AS total, count(*) FILTER (WHERE ok)::int AS editable FROM (
|
||||
SELECT DISTINCT f.photo_id AS item, EXISTS (SELECT 1 FROM cloud_files cf WHERE cf.photo_id = f.photo_id AND ${scope.sql}) AS ok
|
||||
FROM faces f WHERE f.group_id = ${groupId}::uuid
|
||||
UNION
|
||||
SELECT DISTINCT vf.video_id AS item, EXISTS (SELECT 1 FROM cloud_videos cv WHERE cv.id = vf.video_id AND ${scope.vedit}) AS ok
|
||||
FROM video_faces vf WHERE vf.group_id = ${groupId}::uuid
|
||||
) items`;
|
||||
if (!rights || rights.total === 0 || rights.editable < rights.total) throw forbidden("archive_edit_required");
|
||||
try {
|
||||
if (body.action === "confirm") {
|
||||
|
||||
@@ -62,16 +62,24 @@ export async function registerArchiveRoutes(app: FastifyInstance, deps: { db: Db
|
||||
const files = await db.cloudFile.groupBy({ by: ["sourceId", "status"], where: { sourceId: { in: sourceIds } }, _count: { _all: true } });
|
||||
const folders = await db.cloudFolder.groupBy({ by: ["sourceId", "matchedBy"], where: { sourceId: { in: sourceIds }, ...GALLERY }, _count: { _all: true } });
|
||||
const videos = await db.cloudVideo.groupBy({ by: ["sourceId", "status"], where: { sourceId: { in: sourceIds } }, _count: { _all: true } });
|
||||
// Faces in the videos made (videos waiting for their copy are not waiting for faces yet).
|
||||
const videoFaces = await db.cloudVideo.groupBy({ by: ["sourceId", "facesStatus"], where: { sourceId: { in: sourceIds }, status: "DONE", facesStatus: { not: "NONE" } }, _count: { _all: true } });
|
||||
// The pace: images indexed in the last 15 minutes, per hour.
|
||||
const recent = await db.cloudFile.groupBy({ by: ["sourceId"], where: { sourceId: { in: sourceIds }, status: "DONE", updatedAt: { gte: new Date(Date.now() - 15 * 60_000) } }, _count: { _all: true } });
|
||||
const out = new Map<string, Record<string, number>>();
|
||||
const get = (id: string) => out.get(id) ?? out.set(id, { pending: 0, done: 0, failed: 0, galleries: 0, games: 0, named: 0, unmatched: 0, perHour: 0, videos: 0, videosPending: 0, videosFailed: 0 }).get(id)!;
|
||||
const get = (id: string) => out.get(id) ?? out.set(id, { pending: 0, done: 0, failed: 0, galleries: 0, games: 0, named: 0, unmatched: 0, perHour: 0, videos: 0, videosPending: 0, videosFailed: 0, videoFacesPending: 0, videoFacesDone: 0, videoFacesFailed: 0 }).get(id)!;
|
||||
for (const v of videos) {
|
||||
const c = get(v.sourceId);
|
||||
if (v.status === "DONE") c.videos! += v._count._all;
|
||||
else if (v.status === "FAILED") c.videosFailed! += v._count._all;
|
||||
else c.videosPending! += v._count._all;
|
||||
}
|
||||
for (const v of videoFaces) {
|
||||
const c = get(v.sourceId);
|
||||
if (v.facesStatus === "DONE") c.videoFacesDone! += v._count._all;
|
||||
else if (v.facesStatus === "FAILED") c.videoFacesFailed! += v._count._all;
|
||||
else c.videoFacesPending! += v._count._all;
|
||||
}
|
||||
for (const r of recent) get(r.sourceId).perHour = r._count._all * 4;
|
||||
for (const f of files) {
|
||||
const c = get(f.sourceId);
|
||||
@@ -102,7 +110,7 @@ export async function registerArchiveRoutes(app: FastifyInstance, deps: { db: Db
|
||||
nextScanAt: s.nextScanAt,
|
||||
lastError: s.lastError,
|
||||
loginUrl: loginUrl ?? archive.pendingLoginUrl(s),
|
||||
counts: { pending: 0, done: 0, failed: 0, galleries: 0, games: 0, named: 0, unmatched: 0, perHour: 0, videos: 0, videosPending: 0, videosFailed: 0, ...c },
|
||||
counts: { pending: 0, done: 0, failed: 0, galleries: 0, games: 0, named: 0, unmatched: 0, perHour: 0, videos: 0, videosPending: 0, videosFailed: 0, videoFacesPending: 0, videoFacesDone: 0, videoFacesFailed: 0, ...c },
|
||||
});
|
||||
|
||||
const loadSource = async (req: Parameters<typeof requireMembership>[1], sourceId: string, role: "EDITOR" | "ADMIN") => {
|
||||
|
||||
@@ -15,7 +15,7 @@ import { ingestWindow } from "../library/events.js";
|
||||
import { waitUntil } from "../lib/idle.js";
|
||||
import type { LocalStorage } from "../storage/storage.js";
|
||||
import { CloudClient, cleanBase, pollLogin, startLogin, type CloudEntry } from "./nextcloud.js";
|
||||
import { makeWebCopy, VIDEO, VideoToolMissing, type VideoTools } from "./video.js";
|
||||
import { makeWebCopy, VIDEO, VIDEO_FILES, VideoToolMissing, type VideoTools } from "./video.js";
|
||||
import { teamSideRows } from "./directory.js";
|
||||
import { galleryAssignments } from "./gallery.js";
|
||||
import { canonicalTeam, competitionLabel, describeFolder, exhibitionName, type FolderGame, isExhibition, isInitials, isTeamName, knownVersus, lisbonDay, parseFolder, pastOrToday, pickFixture, seasonOf, slashSides, teamMatcher } from "./match.js";
|
||||
@@ -880,9 +880,19 @@ export class ArchiveService {
|
||||
// Their faces belonged to the other event's groups: taken out of them, and found again in the new event.
|
||||
await db.face.deleteMany({ where: { photoId: { in: moving } } });
|
||||
await db.photo.updateMany({ where: { id: { in: moving }, facesStatus: { in: ["DONE", "FAILED", "RUNNING"] } }, data: { facesStatus: "PENDING" } });
|
||||
if (previous) await db.faceGroup.deleteMany({ where: { eventId: previous, faces: { none: {} } } });
|
||||
if (previous) await db.faceGroup.deleteMany({ where: { eventId: previous, faces: { none: {} }, videoFaces: { none: {} } } });
|
||||
}
|
||||
}
|
||||
// Its videos' faces were in the other event's groups too: looked for again in the new event.
|
||||
// Also from no event at all: their faces could not be put in any group until now.
|
||||
const moved = previous !== eventId ? await db.cloudVideo.findMany({ where: { folderId, facesStatus: { in: ["DONE", "FAILED", "RUNNING"] } }, select: { id: true } }) : [];
|
||||
if (moved.length) {
|
||||
const frames = await db.videoFace.findMany({ where: { videoId: { in: moved.map((v) => v.id) } }, select: { frameKey: true } });
|
||||
await db.videoFace.deleteMany({ where: { videoId: { in: moved.map((v) => v.id) } } });
|
||||
await db.cloudVideo.updateMany({ where: { id: { in: moved.map((v) => v.id) } }, data: { facesStatus: "PENDING" } });
|
||||
for (const f of frames) if (this.deps.storage) await this.deps.storage.remove(f.frameKey).catch(() => undefined);
|
||||
if (previous) await db.faceGroup.deleteMany({ where: { eventId: previous, faces: { none: {} }, videoFaces: { none: {} } } });
|
||||
}
|
||||
// An event the archive made and that nothing uses any more goes.
|
||||
if (previous && previous !== eventId) await this.dropIfEmpty(previous);
|
||||
if (previous !== eventId || folder.matchedBy !== matchedBy) await this.markDirectoryDirty(folder.sourceId);
|
||||
@@ -1136,12 +1146,24 @@ export class ArchiveService {
|
||||
await mkdir(out);
|
||||
const made = await this.cpu.run(() => makeWebCopy(videoTools, original, out));
|
||||
const key = storage.videoKey(video.source.organizationId, video.id);
|
||||
// The new files take the place of an older copy (a changed video).
|
||||
await rm(storage.resolve(key), { recursive: true, force: true });
|
||||
// The new files take the place of an older copy (a changed video); the faces' frames are left to the face worker.
|
||||
for (const name of Object.values(VIDEO_FILES)) await storage.remove(`${key}/${name}`);
|
||||
for (const name of await readdir(out)) if (name !== "frame.jpg") await storage.adopt(path.join(out, name), `${key}/${name}`);
|
||||
// Its faces next, like a photo's: only where the organization has face recognition on.
|
||||
const org = await db.organization.findUnique({ where: { id: video.source.organizationId }, select: { biometricsEnabled: true } });
|
||||
await db.cloudVideo.update({
|
||||
where: { id: videoId },
|
||||
data: { status: "DONE", error: null, storageKey: key, durationMs: made.durationMs, width: made.width, height: made.height, capturedAt: made.capturedAt, webBytes: BigInt(made.webBytes) },
|
||||
data: {
|
||||
status: "DONE",
|
||||
error: null,
|
||||
storageKey: key,
|
||||
durationMs: made.durationMs,
|
||||
width: made.width,
|
||||
height: made.height,
|
||||
capturedAt: made.capturedAt,
|
||||
webBytes: BigInt(made.webBytes),
|
||||
facesStatus: org?.biometricsEnabled ? "PENDING" : "NONE",
|
||||
},
|
||||
});
|
||||
} catch (err) {
|
||||
const message = (err as Error).message;
|
||||
|
||||
@@ -0,0 +1,63 @@
|
||||
import { Prisma } from "../generated/prisma/client.js";
|
||||
import type { Db } from "../db.js";
|
||||
import type { UrlSigner } from "../storage/storage.js";
|
||||
|
||||
/**
|
||||
* Faces in archive videos as the viewers see them: each appearance (a face followed through frames) is in an event's
|
||||
* face group like a photo's face, so it is named (the group is confirmed), probable (the group has a suggestion) or
|
||||
* nobody yet. Only videos of published folders count.
|
||||
*/
|
||||
export interface VideoPerson {
|
||||
id: string;
|
||||
name: string;
|
||||
level: "confirmed" | "probable";
|
||||
/** First time on screen, and every appearance (to jump to each). */
|
||||
startMs: number;
|
||||
moments: { startMs: number; endMs: number }[];
|
||||
}
|
||||
|
||||
/** Who appears in each of these videos, named or probable, with when. */
|
||||
export async function peopleInVideos(db: Db, videoIds: string[]): Promise<Map<string, VideoPerson[]>> {
|
||||
const out = new Map<string, VideoPerson[]>();
|
||||
if (!videoIds.length) return out;
|
||||
const rows = await db.$queryRaw<{ video_id: string; person_id: string; name: string; confirmed: boolean; start_ms: number; end_ms: number }[]>`
|
||||
SELECT vf.video_id, p.id AS person_id, p.name, (g.person_id IS NOT NULL) AS confirmed, vf.start_ms, vf.end_ms
|
||||
FROM video_faces vf
|
||||
JOIN face_groups g ON g.id = vf.group_id AND g.ignored_at IS NULL
|
||||
JOIN people p ON p.id = COALESCE(g.person_id, g.suggested_person_id)
|
||||
WHERE vf.video_id = ANY(${videoIds}::uuid[])
|
||||
ORDER BY vf.start_ms`;
|
||||
for (const r of rows) {
|
||||
const list = out.get(r.video_id) ?? [];
|
||||
let person = list.find((p) => p.id === r.person_id);
|
||||
if (!person) {
|
||||
person = { id: r.person_id, name: r.name, level: r.confirmed ? "confirmed" : "probable", startMs: r.start_ms, moments: [] };
|
||||
list.push(person);
|
||||
}
|
||||
person.moments.push({ startMs: r.start_ms, endMs: r.end_ms });
|
||||
out.set(r.video_id, list);
|
||||
}
|
||||
for (const list of out.values()) list.sort((a, b) => (a.level === b.level ? a.startMs - b.startMs : a.level === "confirmed" ? -1 : 1));
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* A video scope on `cv` like the photos' on `cf`: the source and (unless all) these folders. What viewers see is
|
||||
* only made videos of published folders; what an editor may change (`edit`) is every video of their folders, as for
|
||||
* the photos, so a video being made again or a folder taken off the site never locks a face group.
|
||||
*/
|
||||
export function videoScope(sourceId: string, folders: string[] | "all", opts: { edit?: boolean } = {}): Prisma.Sql {
|
||||
const base = opts.edit
|
||||
? Prisma.sql`cv.source_id = ${sourceId}::uuid`
|
||||
: Prisma.sql`cv.source_id = ${sourceId}::uuid AND cv.status = 'DONE' AND EXISTS (SELECT 1 FROM cloud_folders pub WHERE pub.id = cv.folder_id AND pub.published)`;
|
||||
return folders === "all" ? base : Prisma.sql`${base} AND cv.folder_id = ANY(${folders}::uuid[])`;
|
||||
}
|
||||
|
||||
/** An appearance as a face crop: its frame (signed), the box in it and the frame's shape. */
|
||||
export function videoFaceCrop(signer: UrlSigner, f: { id: string; x0: number; y0: number; x1: number; y1: number; width: number | null; height: number | null }) {
|
||||
return {
|
||||
src: signer.videoFaceUrl(f.id),
|
||||
box: { x0: f.x0, y0: f.y0, x1: f.x1, y1: f.y1 },
|
||||
aspect: f.width && f.height ? f.width / f.height : 16 / 9,
|
||||
};
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
import { spawn } from "node:child_process";
|
||||
import { createReadStream, existsSync } from "node:fs";
|
||||
import { stat } from "node:fs/promises";
|
||||
import { readdir, stat } from "node:fs/promises";
|
||||
import path from "node:path";
|
||||
import type { FastifyReply } from "fastify";
|
||||
import sharp from "sharp";
|
||||
@@ -157,6 +157,17 @@ export async function makeWebCopy(tools: VideoTools, input: string, dir: string)
|
||||
return { ...copy, capturedAt: original.capturedAt, webBytes: (await stat(web)).size };
|
||||
}
|
||||
|
||||
/**
|
||||
* Frames of a video at `fps` a second (JPEG, the video's own size), for face analysis: the files in time order;
|
||||
* frame i is at i / fps seconds from the start of the part read (`part`: from, and how long; the whole video
|
||||
* without it).
|
||||
*/
|
||||
export async function extractFrames(tools: VideoTools, input: string, dir: string, fps: number, part?: { fromMs: number; lengthMs: number }): Promise<string[]> {
|
||||
const window = part ? ["-ss", (part.fromMs / 1000).toFixed(3), "-t", (part.lengthMs / 1000).toFixed(3)] : [];
|
||||
await run(tools.ffmpeg, ["-hide_banner", "-nostdin", "-loglevel", "error", "-y", ...window, "-i", input, "-vf", `fps=${fps}`, "-q:v", "3", path.join(dir, "frame_%06d.jpg")], "ffmpeg");
|
||||
return (await readdir(dir)).filter((f) => /^frame_\d+\.jpg$/.test(f)).sort().map((f) => path.join(dir, f));
|
||||
}
|
||||
|
||||
/** A `Range: bytes=…` header against a file's size: the part to send, `null` for the whole file, `"bad"` when it cannot be met. */
|
||||
export function parseRange(header: string | undefined, size: number): { start: number; end: number } | null | "bad" {
|
||||
if (!header) return null;
|
||||
|
||||
@@ -17,6 +17,7 @@ import { registerArchiveDownloadRoutes } from "./downloads.js";
|
||||
import { registerArchiveReviewRoutes } from "./review.js";
|
||||
import type { ArchiveService } from "./service.js";
|
||||
import { sendFile, VIDEO_FILES, VIDEO_VARIANTS } from "./video.js";
|
||||
import { peopleInVideos } from "./video-faces.js";
|
||||
|
||||
/**
|
||||
* The archive for people outside the organization (the federation, the clubs, the press): they sign in with
|
||||
@@ -581,6 +582,8 @@ export async function registerArchiveViewerRoutes(
|
||||
? await db.cloudVideo.findMany({ where: { folderId: { in: ids }, status: "DONE", storageKey: { not: null } }, orderBy: { path: "asc" }, take: 200 })
|
||||
: [];
|
||||
const videoTotal = await db.cloudVideo.count({ where: { folderId: { in: ids }, status: "DONE", storageKey: { not: null } } });
|
||||
// Who appears in each video (named, or probable), and when: the player jumps to them.
|
||||
const inVideos = await peopleInVideos(db, videos.map((x) => x.id));
|
||||
const facePhotos = await db.photo.findMany({
|
||||
where: { id: { in: sharpest.map((f) => f.photo_id) } },
|
||||
select: { id: true, width: true, height: true, renderedSeq: true, developSnapshot: true },
|
||||
@@ -606,7 +609,14 @@ export async function registerArchiveViewerRoutes(
|
||||
GROUP BY ROLLUP (f.photo_id)`
|
||||
: [];
|
||||
const pendingOf = new Map(waiting.filter((w) => w.photo_id).map((w) => [w.photo_id!, Number(w.n)]));
|
||||
const pending = reviews ? Number(waiting.find((w) => !w.photo_id)?.n ?? 0) : undefined;
|
||||
// And the appearances in the gallery's videos waiting for one.
|
||||
const [videoWaiting] = reviews
|
||||
? await db.$queryRaw<{ n: number }[]>`
|
||||
SELECT count(*)::int AS n FROM video_faces vf
|
||||
JOIN face_groups g ON g.id = vf.group_id AND g.person_id IS NULL AND g.suggested_person_id IS NOT NULL AND g.ignored_at IS NULL
|
||||
JOIN cloud_videos cv ON cv.id = vf.video_id AND cv.folder_id = ANY(${ids}::uuid[]) AND cv.status = 'DONE'`
|
||||
: [];
|
||||
const pending = reviews ? Number(waiting.find((w) => !w.photo_id)?.n ?? 0) + Number(videoWaiting?.n ?? 0) : undefined;
|
||||
return {
|
||||
id: shown.id,
|
||||
...(pending !== undefined && { pending }),
|
||||
@@ -640,6 +650,7 @@ export async function registerArchiveViewerRoutes(
|
||||
poster: signer.videoUrl(x.id, "poster"),
|
||||
src: signer.videoUrl(x.id, "web"),
|
||||
download: signer.videoUrl(x.id, "download"),
|
||||
people: inVideos.get(x.id) ?? [],
|
||||
...(onCloud && { cloudUrl: `${base}/f/${x.fileId}` }),
|
||||
})),
|
||||
photos: files.map((f) => ({
|
||||
@@ -701,6 +712,16 @@ export async function registerArchiveViewerRoutes(
|
||||
});
|
||||
});
|
||||
|
||||
/** The frame an appearance in a video is clearest in (its face, when reviewed), by signed URL. */
|
||||
app.get("/v1/files/video-faces/:faceId", async (req, reply) => {
|
||||
const { faceId } = z.object({ faceId: z.uuid() }).parse(req.params);
|
||||
const { exp, sig } = VideoFileQuery.parse(req.query);
|
||||
if (!signer.verifyVideoFace(faceId, exp, sig)) throw notFound("file_not_found");
|
||||
const face = await db.videoFace.findUnique({ where: { id: faceId }, select: { frameKey: true, video: { select: { folder: { select: { published: true } } } } } });
|
||||
if (!face || !face.video.folder.published || !(await deps.storage.exists(face.frameKey))) throw notFound("file_not_found");
|
||||
return sendFile(reply, deps.storage.resolve(face.frameKey), undefined, { "content-type": "image/jpeg", "cache-control": "private, max-age=3600" });
|
||||
});
|
||||
|
||||
await registerArchivePeopleRoutes(app, { db, signer, viewerOf, visibleFolders });
|
||||
await registerArchiveReviewRoutes(app, {
|
||||
db,
|
||||
|
||||
@@ -60,6 +60,8 @@ const Env = z.object({
|
||||
ARCHIVE_VIDEO_CONCURRENCY: z.coerce.number().int().nonnegative().default(1),
|
||||
/** ffmpeg and ffprobe (archive videos). On PATH by default (apt install ffmpeg). */
|
||||
FFMPEG_BIN: z.string().default("ffmpeg"),
|
||||
/** Frames a second looked at for faces in archive videos (each one analysed like a photo). */
|
||||
ARCHIVE_VIDEO_FACE_FPS: z.coerce.number().positive().max(30).default(5),
|
||||
FFPROBE_BIN: z.string().default("ffprobe"),
|
||||
/** Read competitions, squads and fixtures from Liga Portugal, FPF and FPA (worker). "off" to disable. */
|
||||
SPORTS_SYNC: z.enum(["on", "off"]).default("on"),
|
||||
|
||||
@@ -307,6 +307,11 @@ export async function registerFaceRoutes(
|
||||
faces_boosted_at = (SELECT e.face_boosted_at FROM events e WHERE e.id = p.event_id),
|
||||
updated_at = now()
|
||||
WHERE p.organization_id = ${orgId}::uuid AND p.status = 'READY' AND p.faces_status = 'NONE'`;
|
||||
// And the archive's videos already made.
|
||||
await db.$executeRaw`
|
||||
UPDATE cloud_videos AS v SET faces_status = 'PENDING', updated_at = now()
|
||||
FROM cloud_sources s
|
||||
WHERE v.source_id = s.id AND s.organization_id = ${orgId}::uuid AND v.status = 'DONE' AND v.faces_status = 'NONE'`;
|
||||
}
|
||||
return { enabled: org.biometricsEnabled, legalBasis: org.biometricsLegalBasis };
|
||||
});
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import sharp from "sharp";
|
||||
import { expandCodes, parseCodeList } from "@photoreport/metadata";
|
||||
import type { Db } from "../db.js";
|
||||
import { Prisma } from "../generated/prisma/client.js";
|
||||
@@ -20,11 +21,32 @@ import { JERSEY_MIN_SCORE, majorityNumber, type NumberVote } from "./votes.js";
|
||||
import { numberContext, numbersIn, rosterOf, type NumberContext } from "./numbers.js";
|
||||
import { addToMean, cosine, inFocus, mergeMeans, MIN_SHARPNESS, THRESHOLDS } from "./math.js";
|
||||
import type { FaceEngine } from "./process.js";
|
||||
import { FaceFollower } from "./track.js";
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { mkdir, mkdtemp, readFile, rm } from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import path from "node:path";
|
||||
import { extractFrames, type VideoTools } from "../archive/video.js";
|
||||
|
||||
/** Faces this small (fraction of the photo's longer side) are crowd, not subjects. */
|
||||
const MIN_FACE_SIDE = 0.012;
|
||||
/** A photo left RUNNING this long is no longer being analysed (the worker stopped mid-photo). */
|
||||
export const STALE_RUNNING_MS = 10 * 60_000;
|
||||
/** Video appearances put in groups per transaction. */
|
||||
const VIDEO_GROUP_BATCH = 400;
|
||||
/** A video is read for faces this much at a time. */
|
||||
const VIDEO_PART_MS = 60_000;
|
||||
/** A video being read is touched after every part (a minute of video); untouched this long, its run is gone. */
|
||||
const STALE_VIDEO_MS = 30 * 60_000;
|
||||
/** A video whose faces failed is tried again after this long. */
|
||||
const RETRY_FAILED_VIDEO_MS = 6 * 3600_000;
|
||||
/** Long side of the frame kept for each appearance (shown when its face is reviewed). */
|
||||
const VIDEO_FRAME_SIZE = 960;
|
||||
|
||||
/** A video's run was taken over by a newer request (moved to another event, its web copy made again). */
|
||||
class VideoRunSuperseded extends Error {}
|
||||
/** The worker is stopping: the video goes back in the queue. */
|
||||
class VideoRunStopped extends Error {}
|
||||
/** Photos taken inside this window (or just arrived, when they have no date) are read before the older archive. */
|
||||
const RECENT_FACES = Prisma.sql`interval '30 days'`;
|
||||
|
||||
@@ -49,6 +71,10 @@ export class FaceService {
|
||||
engine?: FaceEngine | undefined;
|
||||
/** The shirt-number model (workers/ml/jersey), when one has been trained. */
|
||||
jersey?: { read(original: string, box: Box): Promise<JerseyReading> } | undefined;
|
||||
/** ffmpeg, to take frames out of archive videos (their faces go through the same engine as the photos). */
|
||||
videoTools?: VideoTools | undefined;
|
||||
/** Frames per second looked at in a video. */
|
||||
videoFps?: number | undefined;
|
||||
},
|
||||
) {}
|
||||
|
||||
@@ -96,6 +122,7 @@ export class FaceService {
|
||||
where: { facesStatus: "RUNNING", updatedAt: { lt: new Date(now.getTime() - STALE_RUNNING_MS) } },
|
||||
data: { facesStatus: "PENDING" },
|
||||
});
|
||||
await this.requeueVideos(now);
|
||||
return r.count;
|
||||
}
|
||||
|
||||
@@ -125,6 +152,11 @@ export class FaceService {
|
||||
* while a toggle raced their ingest): queue them. Cheap; the worker runs it at start and every minute.
|
||||
*/
|
||||
async queueMissed(): Promise<number> {
|
||||
// Archive videos made while face recognition was off, or before their faces were looked for.
|
||||
await this.deps.db.$executeRaw`
|
||||
UPDATE cloud_videos AS v SET faces_status = 'PENDING', updated_at = now()
|
||||
FROM cloud_sources s JOIN organizations o ON o.id = s.organization_id
|
||||
WHERE v.source_id = s.id AND o.biometrics_enabled AND v.status = 'DONE' AND v.faces_status = 'NONE'`;
|
||||
// A boosted event keeps that place in the queue for photos that were missed, not only the ones already pending.
|
||||
return Number(
|
||||
await this.deps.db.$executeRaw`
|
||||
@@ -216,6 +248,143 @@ export class FaceService {
|
||||
}
|
||||
}
|
||||
|
||||
/** Archive videos whose faces are to be found, oldest request first (the photos go before them). */
|
||||
async claimVideos(limit: number): Promise<string[]> {
|
||||
if (limit <= 0 || !this.deps.engine || !this.deps.videoTools) return [];
|
||||
const rows = await this.deps.db.$queryRaw<{ id: string }[]>`
|
||||
UPDATE cloud_videos SET faces_status = 'RUNNING', updated_at = now()
|
||||
WHERE id IN (
|
||||
SELECT v.id FROM cloud_videos v
|
||||
WHERE v.faces_status = 'PENDING' AND v.status = 'DONE' AND v.storage_key IS NOT NULL
|
||||
ORDER BY v.updated_at
|
||||
LIMIT ${limit}
|
||||
FOR UPDATE OF v SKIP LOCKED
|
||||
)
|
||||
RETURNING id`;
|
||||
return rows.map((r) => r.id);
|
||||
}
|
||||
|
||||
/**
|
||||
* The faces of one archive video, the photos' way: frames taken from its web copy (`videoFps` a second, a minute at
|
||||
* a time), each analysed by the same engine with the same filters (size, focus, sharpness), the same face followed
|
||||
* through consecutive frames as one appearance, and each appearance put in the event's face groups like a photo's
|
||||
* face. The run is the video's while it stays RUNNING: a newer request (its folder moved to another event, its web
|
||||
* copy made again) takes it over and this run's result is dropped. Never throws.
|
||||
*/
|
||||
async processVideo(videoId: string): Promise<void> {
|
||||
const { db, storage, log, engine, videoTools } = this.deps;
|
||||
const dir = await mkdtemp(path.join(tmpdir(), "pr-video-faces-"));
|
||||
const written: string[] = [];
|
||||
try {
|
||||
if (!engine || !videoTools) throw new Error("face engine or ffmpeg not configured");
|
||||
const video = await db.cloudVideo.findUniqueOrThrow({ where: { id: videoId } });
|
||||
if (!video.storageKey) throw new Error("video has no web copy");
|
||||
const fps = this.deps.videoFps ?? 5;
|
||||
const web = storage.resolve(`${video.storageKey}/web.mp4`);
|
||||
// A glimpse of under half a second is a face in the crowd or a false detection, not someone on screen.
|
||||
const follower = new FaceFollower({ same: this.thresholds(engine.model).group, minSharpness: MIN_SHARPNESS, minFrames: Math.max(1, Math.ceil(fps / 2)) });
|
||||
// A minute at a time: a whole game is tens of thousands of frames, and only each appearance's clearest frame
|
||||
// is kept on disk between parts.
|
||||
const length = video.durationMs ?? 0;
|
||||
let frames = 0;
|
||||
for (let fromMs = 0, part = 0; fromMs === 0 || fromMs < length; fromMs += VIDEO_PART_MS, part++) {
|
||||
if (this.stoppingVideos) throw new VideoRunStopped();
|
||||
const partDir = path.join(dir, `part_${part}`);
|
||||
await mkdir(partDir);
|
||||
const files = await extractFrames(videoTools, web, partDir, fps, length ? { fromMs, lengthMs: VIDEO_PART_MS } : undefined);
|
||||
for (const [i, file] of files.entries()) {
|
||||
if (this.stoppingVideos) throw new VideoRunStopped();
|
||||
const analysis = await engine.analyse(file);
|
||||
const faces = inFocus(analysis.faces.filter((f) => Math.max(f.x1 - f.x0, f.y1 - f.y0) >= MIN_FACE_SIDE));
|
||||
follower.add({
|
||||
at: fromMs + Math.round((i * 1000) / fps),
|
||||
file,
|
||||
faces: faces.map((f) => ({ x0: f.x0, y0: f.y0, x1: f.x1, y1: f.y1, score: f.score, sharpness: f.sharpness ?? null, embedding: f.embedding ?? [] })),
|
||||
});
|
||||
}
|
||||
frames += files.length;
|
||||
const keep = follower.keep();
|
||||
for (const file of files) if (!keep.has(file)) await rm(file, { force: true });
|
||||
// Still at it (a run that stops being touched is taken back by the stale check); and still ours.
|
||||
const still = await db.cloudVideo.updateMany({ where: { id: videoId, facesStatus: "RUNNING" }, data: { facesStatus: "RUNNING" } });
|
||||
if (!still.count) throw new VideoRunSuperseded();
|
||||
if (!length) break;
|
||||
}
|
||||
const appearances = follower.finish();
|
||||
// The frame of each appearance is kept (what a reviewer sees), small, beside the video's web copy.
|
||||
const kept: { id: string; key: string; a: (typeof appearances)[number] }[] = [];
|
||||
for (const a of appearances) {
|
||||
const id = randomUUID();
|
||||
const key = `${video.storageKey}/faces/${id}.jpg`;
|
||||
await storage.write(key, await sharp(await readFile(a.best.file)).resize(VIDEO_FRAME_SIZE, VIDEO_FRAME_SIZE, { fit: "inside", withoutEnlargement: true }).jpeg({ quality: 80 }).toBuffer());
|
||||
written.push(key);
|
||||
kept.push({ id, key, a });
|
||||
}
|
||||
const old = await db.videoFace.findMany({ where: { videoId }, select: { frameKey: true } });
|
||||
await db.$transaction(async (tx) => {
|
||||
// Only if the video is still this run's (a newer request set it PENDING meanwhile: that one wins).
|
||||
const ours = await tx.cloudVideo.updateMany({ where: { id: videoId, facesStatus: "RUNNING" }, data: { facesStatus: "DONE" } });
|
||||
if (!ours.count) throw new VideoRunSuperseded();
|
||||
await tx.videoFace.deleteMany({ where: { videoId } });
|
||||
for (const { id, key, a } of kept) {
|
||||
await tx.videoFace.create({
|
||||
data: {
|
||||
id,
|
||||
videoId,
|
||||
startMs: a.startMs,
|
||||
endMs: a.endMs,
|
||||
atMs: a.best.at,
|
||||
x0: a.best.x0,
|
||||
y0: a.best.y0,
|
||||
x1: a.best.x1,
|
||||
y1: a.best.y1,
|
||||
score: a.best.score,
|
||||
sharpness: a.best.sharpness,
|
||||
embedding: a.embedding,
|
||||
model: engine.model,
|
||||
frames: a.frames,
|
||||
frameKey: key,
|
||||
},
|
||||
});
|
||||
}
|
||||
});
|
||||
written.length = 0;
|
||||
for (const o of old) await storage.remove(o.frameKey).catch(() => undefined);
|
||||
// The folder's event as it is now (it may have changed during a long run).
|
||||
const eventId = (await db.cloudVideo.findUnique({ where: { id: videoId }, select: { folder: { select: { eventId: true } } } }))?.folder.eventId;
|
||||
if (eventId) await this.groupEvent(eventId);
|
||||
log.info({ videoId, frames, appearances: kept.length }, "faces: video analysed");
|
||||
} catch (err) {
|
||||
for (const key of written) await storage.remove(key).catch(() => undefined);
|
||||
if (err instanceof VideoRunSuperseded) {
|
||||
log.info({ videoId }, "faces: video asked again meanwhile, this run dropped");
|
||||
} else if (err instanceof VideoRunStopped) {
|
||||
// The worker is stopping (a deploy): the video goes back in the queue, to be read again from the start.
|
||||
await db.cloudVideo.updateMany({ where: { id: videoId, facesStatus: "RUNNING" }, data: { facesStatus: "PENDING" } }).catch(() => {});
|
||||
} else {
|
||||
log.warn({ videoId, err: (err as Error).message }, "faces: video analysis failed");
|
||||
await db.cloudVideo.updateMany({ where: { id: videoId, facesStatus: "RUNNING" }, data: { facesStatus: "FAILED" } }).catch(() => {});
|
||||
}
|
||||
} finally {
|
||||
await rm(dir, { recursive: true, force: true });
|
||||
}
|
||||
}
|
||||
|
||||
private stoppingVideos = false;
|
||||
|
||||
/** Videos being read stop at the next frame and go back in the queue (the worker is stopping). */
|
||||
stopVideos(): void {
|
||||
this.stoppingVideos = true;
|
||||
}
|
||||
|
||||
/** Videos left RUNNING by a worker that is gone, and failed ones after a while, back in the queue. */
|
||||
async requeueVideos(now = new Date()): Promise<number> {
|
||||
const { db } = this.deps;
|
||||
const stale = await db.cloudVideo.updateMany({ where: { facesStatus: "RUNNING", updatedAt: { lt: new Date(now.getTime() - STALE_VIDEO_MS) } }, data: { facesStatus: "PENDING" } });
|
||||
const failed = await db.cloudVideo.updateMany({ where: { facesStatus: "FAILED", status: "DONE", updatedAt: { lt: new Date(now.getTime() - RETRY_FAILED_VIDEO_MS) } }, data: { facesStatus: "PENDING" } });
|
||||
return stale.count + failed.count;
|
||||
}
|
||||
|
||||
/**
|
||||
* Puts every ungrouped face of the event into the closest group (or a new one), then names photos of
|
||||
* confirmed groups and refreshes suggestions. Serialised per event.
|
||||
@@ -232,7 +401,8 @@ export class FaceService {
|
||||
where: { groupId: null, photo: { eventId }, NOT: { embedding: { isEmpty: true } }, OR: [{ sharpness: null }, { sharpness: { gte: MIN_SHARPNESS } }] },
|
||||
orderBy: { createdAt: "asc" },
|
||||
});
|
||||
for (const face of loose) {
|
||||
// The closest group of the event, or a new one: a photo's face and a video's appearance alike.
|
||||
const place = async (face: { embedding: number[]; model: string }): Promise<FaceGroup> => {
|
||||
const { group: match } = this.thresholds(face.model);
|
||||
let best: FaceGroup | undefined;
|
||||
let bestScore = -1;
|
||||
@@ -252,6 +422,10 @@ export class FaceService {
|
||||
group = await tx.faceGroup.create({ data: { organizationId: event.organizationId, eventId, centroid: face.embedding, size: 1, model: face.model } });
|
||||
groups.push(group);
|
||||
}
|
||||
return group;
|
||||
};
|
||||
for (const face of loose) {
|
||||
const group = await place(face);
|
||||
await tx.face.update({ where: { id: face.id }, data: { groupId: group.id } });
|
||||
if (group.personId) touchedPhotos.add(face.photoId);
|
||||
}
|
||||
@@ -259,11 +433,65 @@ export class FaceService {
|
||||
},
|
||||
{ timeout: 30_000 },
|
||||
);
|
||||
await this.groupVideoFaces(eventId, organizationId);
|
||||
await this.nameConfirmedPhotos([...touchedPhotos]);
|
||||
await this.refreshSuggestions(eventId);
|
||||
this.deps.broadcaster.library(organizationId, { type: "faces.updated", eventId });
|
||||
}
|
||||
|
||||
/**
|
||||
* The appearances in the event's archive videos (their folder's event) that have no group yet, into the closest
|
||||
* group or a new one: the photos' rule (`groupEvent`), but a few hundred at a time, each batch in its own short
|
||||
* transaction (a whole game can bring thousands), the groups written once per batch.
|
||||
*/
|
||||
private async groupVideoFaces(eventId: string, organizationId: string): Promise<void> {
|
||||
const { db } = this.deps;
|
||||
for (;;) {
|
||||
const placed = await db.$transaction(
|
||||
async (tx) => {
|
||||
await tx.$executeRaw`SELECT pg_advisory_xact_lock(hashtext(${`faces:${eventId}`}))`;
|
||||
const loose = await tx.videoFace.findMany({
|
||||
where: { groupId: null, video: { folder: { eventId } }, NOT: { embedding: { isEmpty: true } } },
|
||||
select: { id: true, embedding: true, model: true },
|
||||
orderBy: { createdAt: "asc" },
|
||||
take: VIDEO_GROUP_BATCH,
|
||||
});
|
||||
if (!loose.length) return 0;
|
||||
const groups = (await tx.faceGroup.findMany({ where: { eventId }, select: { id: true, centroid: true, size: true, model: true } })).map((g) => ({ ...g, fresh: false, members: [] as string[] }));
|
||||
for (const face of loose) {
|
||||
const { group: match } = this.thresholds(face.model);
|
||||
let best: (typeof groups)[number] | undefined;
|
||||
let bestScore = -1;
|
||||
for (const g of groups) {
|
||||
if (g.model !== face.model) continue;
|
||||
const s = cosine(g.centroid, face.embedding);
|
||||
if (s > bestScore) {
|
||||
bestScore = s;
|
||||
best = g;
|
||||
}
|
||||
}
|
||||
if (best && bestScore >= match) {
|
||||
best.centroid = addToMean(best.centroid, best.size, face.embedding);
|
||||
best.size++;
|
||||
best.members.push(face.id);
|
||||
} else {
|
||||
groups.push({ id: randomUUID(), centroid: face.embedding, size: 1, model: face.model, fresh: true, members: [face.id] });
|
||||
}
|
||||
}
|
||||
for (const g of groups) {
|
||||
if (!g.members.length) continue;
|
||||
if (g.fresh) await tx.faceGroup.create({ data: { id: g.id, organizationId, eventId, centroid: g.centroid, size: g.size, model: g.model } });
|
||||
else await tx.faceGroup.update({ where: { id: g.id }, data: { centroid: g.centroid, size: g.size } });
|
||||
await tx.videoFace.updateMany({ where: { id: { in: g.members } }, data: { groupId: g.id } });
|
||||
}
|
||||
return loose.length;
|
||||
},
|
||||
{ timeout: 60_000 },
|
||||
);
|
||||
if (placed < VIDEO_GROUP_BATCH) return;
|
||||
}
|
||||
}
|
||||
|
||||
/** Suggests a person for each open group: best match among confirmed people, if clearly ahead. */
|
||||
/**
|
||||
* Groups of the event named as the same person become one card (the largest takes the others' faces): one place
|
||||
@@ -282,6 +510,7 @@ export class FaceService {
|
||||
const [target, ...rest] = list as [(typeof named)[number], ...typeof named];
|
||||
await db.$transaction([
|
||||
db.face.updateMany({ where: { groupId: { in: rest.map((g) => g.id) } }, data: { groupId: target.id } }),
|
||||
db.videoFace.updateMany({ where: { groupId: { in: rest.map((g) => g.id) } }, data: { groupId: target.id } }),
|
||||
db.faceGroup.update({
|
||||
where: { id: target.id },
|
||||
data: { centroid: mergeMeans(list.map((g) => ({ mean: g.centroid, count: g.size }))), size: list.reduce((n, g) => n + g.size, 0) },
|
||||
@@ -623,6 +852,7 @@ export class FaceService {
|
||||
const personId = target.personId ?? source.personId;
|
||||
await db.$transaction([
|
||||
db.face.updateMany({ where: { groupId: sourceId }, data: { groupId: targetId } }),
|
||||
db.videoFace.updateMany({ where: { groupId: sourceId }, data: { groupId: targetId } }),
|
||||
db.faceGroup.update({
|
||||
where: { id: targetId },
|
||||
data: { centroid: mergeMeans([{ mean: source.centroid, count: source.size }, { mean: target.centroid, count: target.size }]), size: source.size + target.size, personId },
|
||||
@@ -817,6 +1047,7 @@ export async function dropCrossSportSuggestions(db: Db): Promise<number> {
|
||||
|
||||
export class FaceWorker {
|
||||
private inFlight = 0;
|
||||
private videosInFlight = 0;
|
||||
private timer: NodeJS.Timeout | undefined;
|
||||
private stopped = false;
|
||||
private ticking = false;
|
||||
@@ -845,6 +1076,7 @@ export class FaceWorker {
|
||||
void this.service.requeueStale();
|
||||
let missedAt = 0;
|
||||
let failedAt = 0;
|
||||
let videosCheckedAt = Date.now();
|
||||
const tick = async () => {
|
||||
this.ticking = true;
|
||||
try {
|
||||
@@ -859,14 +1091,33 @@ export class FaceWorker {
|
||||
const n = await this.service.requeueFailed();
|
||||
if (n) this.opts.log.info({ photos: n }, "faces: failed photos queued again");
|
||||
}
|
||||
if (Date.now() - videosCheckedAt > 10 * 60_000) {
|
||||
videosCheckedAt = Date.now();
|
||||
const n = await this.service.requeueVideos();
|
||||
if (n) this.opts.log.info({ videos: n }, "faces: videos queued again");
|
||||
}
|
||||
for (const id of await this.service.claimReferences(5)) await this.service.processReference(id);
|
||||
const ids = await this.service.claim(this.opts.concurrency - this.inFlight);
|
||||
// Archive videos one at a time, in one of the engine's places: with photos always arriving (a live game,
|
||||
// the archive's backlog) a video waiting for the photos to stop would never start. With a single place the
|
||||
// photos keep it, and a video waits until they leave it free.
|
||||
const startVideo = async () => {
|
||||
for (const id of await this.service.claimVideos(1)) {
|
||||
this.videosInFlight++;
|
||||
void this.service.processVideo(id).finally(() => {
|
||||
this.videosInFlight--;
|
||||
});
|
||||
}
|
||||
};
|
||||
const shared = this.opts.concurrency > 1;
|
||||
if (shared && this.videosInFlight === 0 && this.inFlight < this.opts.concurrency) await startVideo();
|
||||
const ids = await this.service.claim(this.opts.concurrency - this.inFlight - (shared ? this.videosInFlight : 0));
|
||||
for (const id of ids) {
|
||||
this.inFlight++;
|
||||
void this.service.process(id).finally(() => {
|
||||
this.inFlight--;
|
||||
});
|
||||
}
|
||||
if (!shared && !ids.length && this.inFlight === 0 && this.videosInFlight === 0) await startVideo();
|
||||
} catch (err) {
|
||||
this.opts.log.warn({ err }, "faces: poll failed");
|
||||
} finally {
|
||||
@@ -880,7 +1131,9 @@ export class FaceWorker {
|
||||
async stop(timeoutMs = 25_000): Promise<void> {
|
||||
this.stopped = true;
|
||||
if (this.timer) clearTimeout(this.timer);
|
||||
const drained = await waitUntil(() => !this.ticking && this.inFlight === 0, { timeoutMs });
|
||||
// A video being read can take long: it stops at the next frame and goes back in the queue.
|
||||
this.service.stopVideos();
|
||||
const drained = await waitUntil(() => !this.ticking && this.inFlight === 0 && this.videosInFlight === 0, { timeoutMs });
|
||||
if (!drained) this.opts.log.warn({ inFlight: this.inFlight }, "faces: stop timed out with work still running");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { followFaces, iou, type Frame, type FrameFace } from "./track.js";
|
||||
|
||||
const vec = (i: number, wobble = 0) => {
|
||||
const v = new Array<number>(8).fill(0);
|
||||
v[i] = 1;
|
||||
v[(i + 1) % 8] = wobble;
|
||||
const n = Math.sqrt(1 + wobble * wobble);
|
||||
return v.map((x) => x / n);
|
||||
};
|
||||
const face = (x: number, emb: number[], sharpness: number | null = 100, score = 0.9): FrameFace => ({ x0: x, y0: 0.2, x1: x + 0.1, y1: 0.35, score, sharpness, embedding: emb });
|
||||
const frames = (list: FrameFace[][], fps = 5): Frame[] => list.map((faces, i) => ({ at: (i * 1000) / fps, file: `f${i}.jpg`, faces }));
|
||||
const opts = { same: 0.55, minSharpness: 45 };
|
||||
|
||||
describe("following faces through a video", () => {
|
||||
it("makes one appearance of a face seen frame after frame, with when and its clearest frame", () => {
|
||||
const a = followFaces(
|
||||
frames([[face(0.1, vec(0))], [face(0.11, vec(0, 0.1), 80)], [face(0.12, vec(0, 0.2), 300, 0.95)], [face(0.13, vec(0))]]),
|
||||
opts,
|
||||
);
|
||||
expect(a).toHaveLength(1);
|
||||
expect(a[0]).toMatchObject({ startMs: 0, endMs: 600, frames: 4, best: { at: 400, file: "f2.jpg", sharpness: 300 } });
|
||||
expect(Math.hypot(...a[0]!.embedding)).toBeCloseTo(1, 5);
|
||||
});
|
||||
|
||||
it("keeps two people apart in the same frames, even when they swap places", () => {
|
||||
const a = followFaces(
|
||||
frames([
|
||||
[face(0.1, vec(0)), face(0.6, vec(3))],
|
||||
[face(0.35, vec(0)), face(0.35, vec(3))],
|
||||
[face(0.6, vec(0)), face(0.1, vec(3))],
|
||||
]),
|
||||
opts,
|
||||
);
|
||||
expect(a).toHaveLength(2);
|
||||
expect(a.map((x) => x.frames)).toEqual([3, 3]);
|
||||
expect(a.map((x) => x.embedding.indexOf(Math.max(...x.embedding))).sort()).toEqual([0, 3]);
|
||||
});
|
||||
|
||||
it("joins a face missed for a moment, and starts again after a long absence", () => {
|
||||
const empty: FrameFace[] = [];
|
||||
const short = followFaces(frames([[face(0.1, vec(0))], empty, empty, [face(0.1, vec(0))]]), opts);
|
||||
expect(short).toHaveLength(1);
|
||||
const long = followFaces(frames([[face(0.1, vec(0))], ...Array.from({ length: 10 }, () => empty), [face(0.1, vec(0))]]), opts);
|
||||
expect(long.map((x) => [x.startMs, x.endMs])).toEqual([
|
||||
[0, 0],
|
||||
[2200, 2200],
|
||||
]);
|
||||
});
|
||||
|
||||
it("drops what was never seen sharply, like a blurred face in a photo", () => {
|
||||
expect(followFaces(frames([[face(0.1, vec(0), 10)], [face(0.1, vec(0), 20)]]), opts)).toEqual([]);
|
||||
// Followed through its blurred frames, but the embedding and the frame are the sharp one's.
|
||||
const a = followFaces(frames([[face(0.1, vec(0, 0.3), 10)], [face(0.1, vec(0), 200)]]), opts);
|
||||
expect(a[0]).toMatchObject({ frames: 2, best: { file: "f1.jpg" } });
|
||||
});
|
||||
|
||||
it("leaves out a glimpse shorter than asked (a face in the crowd, a false detection)", () => {
|
||||
const list = frames([[face(0.1, vec(0)), face(0.6, vec(3))], [face(0.1, vec(0))], [face(0.1, vec(0))]]);
|
||||
expect(followFaces(list, { ...opts, minFrames: 2 }).map((a) => a.frames)).toEqual([3]);
|
||||
expect(followFaces(list, opts)).toHaveLength(2);
|
||||
});
|
||||
|
||||
it("measures how much two boxes overlap", () => {
|
||||
expect(iou(face(0.1, []), face(0.1, []))).toBeCloseTo(1);
|
||||
expect(iou(face(0.1, []), face(0.5, []))).toBe(0);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,158 @@
|
||||
import { cosine } from "./math.js";
|
||||
|
||||
/**
|
||||
* Following faces through a video's frames. Each sampled frame is analysed like a photo (same engine, same
|
||||
* filters); a face is the same appearance as one seen just before when it looks like it (embedding) and is about
|
||||
* where it was (box). One appearance is then one face to review, not one per frame.
|
||||
*/
|
||||
export interface FrameFace {
|
||||
x0: number;
|
||||
y0: number;
|
||||
x1: number;
|
||||
y1: number;
|
||||
score: number;
|
||||
sharpness: number | null;
|
||||
embedding: number[];
|
||||
}
|
||||
|
||||
export interface Frame {
|
||||
/** When in the video (ms). */
|
||||
at: number;
|
||||
/** The frame's file (its clearest face's frame is kept). */
|
||||
file: string;
|
||||
faces: FrameFace[];
|
||||
}
|
||||
|
||||
export interface Appearance {
|
||||
startMs: number;
|
||||
endMs: number;
|
||||
/** The clearest sighting: its frame, time and box. */
|
||||
best: FrameFace & { at: number; file: string };
|
||||
/** Mean of the sharp sightings' embeddings, unit length (what is compared with the face groups). */
|
||||
embedding: number[];
|
||||
frames: number;
|
||||
}
|
||||
|
||||
export interface TrackOptions {
|
||||
/** How alike two sightings must be to be one appearance (the face groups' threshold). */
|
||||
same: number;
|
||||
/** A face may be missed this long (turned away, behind someone) and still be the same appearance. */
|
||||
maxGapMs?: number;
|
||||
/** Below this a sighting is followed but does not count for the embedding (as photos: not grouped). */
|
||||
minSharpness: number;
|
||||
/** Fewer sightings than this is a passing glimpse (a face in the crowd, a false detection): not an appearance. */
|
||||
minFrames?: number;
|
||||
}
|
||||
|
||||
interface Track {
|
||||
/** How many frames it was seen in, and when last (the sightings themselves are not kept: a long video has many). */
|
||||
count: number;
|
||||
lastAt: number;
|
||||
last: FrameFace & { at: number };
|
||||
first: number;
|
||||
/** The clearest sharp sighting, and the sum of the sharp sightings' embeddings. */
|
||||
best: (FrameFace & { at: number; file: string }) | null;
|
||||
sum: number[] | null;
|
||||
sharp: number;
|
||||
}
|
||||
|
||||
/** Overlap of two boxes (intersection over union). */
|
||||
export function iou(a: FrameFace, b: FrameFace): number {
|
||||
const w = Math.max(0, Math.min(a.x1, b.x1) - Math.max(a.x0, b.x0));
|
||||
const h = Math.max(0, Math.min(a.y1, b.y1) - Math.max(a.y0, b.y0));
|
||||
const inter = w * h;
|
||||
const union = (a.x1 - a.x0) * (a.y1 - a.y0) + (b.x1 - b.x0) * (b.y1 - b.y0) - inter;
|
||||
return union > 0 ? inter / union : 0;
|
||||
}
|
||||
|
||||
const unit = (v: number[]): number[] => {
|
||||
const n = Math.sqrt(v.reduce((s, x) => s + x * x, 0));
|
||||
return n > 0 ? v.map((x) => x / n) : v;
|
||||
};
|
||||
|
||||
const sharpEnough = (f: FrameFace, min: number) => f.sharpness == null || f.sharpness >= min;
|
||||
|
||||
/**
|
||||
* Follows faces frame after frame (in time order), so a long video can be read a part at a time: `add` each frame,
|
||||
* `keep` says which frame files are still needed (the clearest sighting of each appearance), `finish` gives the
|
||||
* appearances. Each frame's faces are matched to the open appearances, most alike first, one face per appearance
|
||||
* per frame; a face still near where the appearance was counts as more alike (a turned head changes the embedding
|
||||
* more than the place). Appearances never seen sharply are dropped: like a blurred face in a photo, they cannot be
|
||||
* compared with anyone.
|
||||
*/
|
||||
export class FaceFollower {
|
||||
private readonly open: Track[] = [];
|
||||
private readonly closed: Track[] = [];
|
||||
private readonly maxGap: number;
|
||||
|
||||
constructor(private readonly opts: TrackOptions) {
|
||||
this.maxGap = opts.maxGapMs ?? 1500;
|
||||
}
|
||||
|
||||
add(frame: Frame): void {
|
||||
const { open, closed } = this;
|
||||
// Appearances not seen for too long are over.
|
||||
for (let i = open.length - 1; i >= 0; i--) if (frame.at - open[i]!.last.at > this.maxGap) closed.push(...open.splice(i, 1));
|
||||
const pairs: { t: number; f: number; s: number }[] = [];
|
||||
frame.faces.forEach((face, f) => {
|
||||
if (!face.embedding.length) return;
|
||||
open.forEach((track, t) => {
|
||||
const look = cosine(track.last.embedding, face.embedding);
|
||||
const near = iou(track.last, face);
|
||||
// Where it was helps; it never makes a stranger the same person.
|
||||
const s = look + 0.15 * near;
|
||||
if (look >= this.opts.same - (near > 0.3 ? 0.1 : 0)) pairs.push({ t, f, s });
|
||||
});
|
||||
});
|
||||
pairs.sort((a, b) => b.s - a.s);
|
||||
const usedT = new Set<number>();
|
||||
const usedF = new Set<number>();
|
||||
for (const p of pairs) {
|
||||
if (usedT.has(p.t) || usedF.has(p.f)) continue;
|
||||
usedT.add(p.t);
|
||||
usedF.add(p.f);
|
||||
const face = frame.faces[p.f]!;
|
||||
this.sight(open[p.t]!, face, frame);
|
||||
}
|
||||
frame.faces.forEach((face, f) => {
|
||||
if (usedF.has(f) || !face.embedding.length) return;
|
||||
const track: Track = { count: 0, lastAt: frame.at, last: { ...face, at: frame.at }, best: null, sum: null, sharp: 0, first: frame.at };
|
||||
this.sight(track, face, frame);
|
||||
open.push(track);
|
||||
});
|
||||
}
|
||||
|
||||
private sight(track: Track, face: FrameFace, frame: Frame): void {
|
||||
const at = { ...face, at: frame.at, file: frame.file };
|
||||
track.count++;
|
||||
track.lastAt = frame.at;
|
||||
track.last = { ...face, at: frame.at };
|
||||
if (!sharpEnough(face, this.opts.minSharpness)) return;
|
||||
track.sharp++;
|
||||
if (!track.sum) track.sum = new Array<number>(face.embedding.length).fill(0);
|
||||
for (let i = 0; i < track.sum.length; i++) track.sum[i]! += face.embedding[i] ?? 0;
|
||||
// The clearest: sharpness times confidence (confidence alone when the engine gives no sharpness).
|
||||
const clear = (f: FrameFace) => (f.sharpness ?? 1) * f.score;
|
||||
if (!track.best || clear(face) > clear(track.best)) track.best = at;
|
||||
}
|
||||
|
||||
/** The frame files still needed: the clearest sighting of every appearance so far. */
|
||||
keep(): Set<string> {
|
||||
return new Set([...this.open, ...this.closed].flatMap((t) => (t.best ? [t.best.file] : [])));
|
||||
}
|
||||
|
||||
finish(): Appearance[] {
|
||||
return [...this.closed, ...this.open]
|
||||
.flatMap((t): Appearance[] =>
|
||||
t.best && t.sum && t.count >= (this.opts.minFrames ?? 1) ? [{ startMs: t.first, endMs: t.lastAt, best: t.best, embedding: unit(t.sum), frames: t.count }] : [],
|
||||
)
|
||||
.sort((a, b) => a.startMs - b.startMs);
|
||||
}
|
||||
}
|
||||
|
||||
/** The appearances in a video's frames, all at once (see `FaceFollower`). */
|
||||
export function followFaces(frames: Frame[], opts: TrackOptions): Appearance[] {
|
||||
const follower = new FaceFollower(opts);
|
||||
for (const frame of [...frames].sort((a, b) => a.at - b.at)) follower.add(frame);
|
||||
return follower.finish();
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { waitUntil } from "../lib/idle.js";
|
||||
import { FaceWorker, type FaceService } from "./service.js";
|
||||
|
||||
const quiet = { info() {}, warn() {}, error() {}, debug() {} } as never;
|
||||
|
||||
/** A queue that never empties of photos (a live game, the archive's backlog) and has one video waiting. */
|
||||
function busyQueue() {
|
||||
const running = { photos: 0, videos: 0, most: 0 };
|
||||
let videos = ["v1"];
|
||||
const finish = () => new Promise<void>((r) => setTimeout(r, 20));
|
||||
const service = {
|
||||
queueMissed: async () => 0,
|
||||
requeueFailed: async () => 0,
|
||||
requeueVideos: async () => 0,
|
||||
requeueStale: async () => 0,
|
||||
claimReferences: async () => [],
|
||||
processReference: async () => {},
|
||||
claim: async (limit: number) => Array.from({ length: Math.max(0, limit) }, (_, i) => `p${i}`),
|
||||
process: async () => {
|
||||
running.photos++;
|
||||
running.most = Math.max(running.most, running.photos + running.videos);
|
||||
await finish();
|
||||
running.photos--;
|
||||
},
|
||||
claimVideos: async (limit: number) => {
|
||||
const out = videos.slice(0, limit);
|
||||
videos = videos.slice(limit);
|
||||
return out;
|
||||
},
|
||||
processVideo: async () => {
|
||||
running.videos++;
|
||||
running.most = Math.max(running.most, running.photos + running.videos);
|
||||
await finish();
|
||||
running.videos--;
|
||||
started.push("v1");
|
||||
},
|
||||
stopVideos: () => {},
|
||||
};
|
||||
const started: string[] = [];
|
||||
return { service: service as unknown as FaceService, running, started };
|
||||
}
|
||||
|
||||
describe("the face worker", () => {
|
||||
it("starts an archive video while photos keep arriving, in one of the engine's places", async () => {
|
||||
const { service, running, started } = busyQueue();
|
||||
const worker = new FaceWorker(service, { concurrency: 3, intervalMs: 5, log: quiet });
|
||||
worker.start();
|
||||
expect(await waitUntil(() => started.length > 0, { timeoutMs: 2000 })).toBe(true);
|
||||
await worker.stop(2000);
|
||||
// Never more at once than the engine has places.
|
||||
expect(running.most).toBeLessThanOrEqual(3);
|
||||
});
|
||||
|
||||
it("with a single place, leaves it to the photos while they keep arriving", async () => {
|
||||
const { service, started } = busyQueue();
|
||||
const worker = new FaceWorker(service, { concurrency: 1, intervalMs: 5, log: quiet });
|
||||
worker.start();
|
||||
await new Promise((r) => setTimeout(r, 200));
|
||||
await worker.stop(2000);
|
||||
expect(started).toEqual([]);
|
||||
});
|
||||
});
|
||||
@@ -5,6 +5,10 @@ import exifr from "exifr";
|
||||
* IPTC already in an incoming file (camera presets, or a photo captioned in Lightroom/Photo Mechanic).
|
||||
* XMP is read first: it is always UTF-8. IIM is the fallback, and Lightroom and Photo Mechanic on the Mac write
|
||||
* it in Mac Roman without saying so ("Pavilh‹o" for "Pavilhão"), which is repaired here.
|
||||
*
|
||||
* LightCraft's metadata reader is what the engine uses for capture (time, exposure, camera). It does not
|
||||
* keep the Photo Mechanic pad (headline, event, credit, people, contacts, job id and the rest), so this
|
||||
* reader stays for those fields.
|
||||
*/
|
||||
|
||||
// Mac Roman 0x80–0x9F (the range that betrays it: in Latin-1 these are control characters).
|
||||
|
||||
@@ -6,6 +6,12 @@ import { type FocusHint, focusFromTags } from "./focus.js";
|
||||
* The camera details Photo Mechanic shows beyond the ones with their own column (stored in `photos.exif`), for
|
||||
* its variables: {comp}, {flash}, {meteringmode}, {program}, {white}, {lens35}, {owner}, {artist}... Readable
|
||||
* strings, as Photo Mechanic writes them.
|
||||
*
|
||||
* Capture time and exposure are also read by the develop engine through LightCraft (`photoreport_engine::capture`:
|
||||
* EXIF, then IPTC, then XMP, including CR3). JPEG ingest stays on this reader: it runs in process, event routing
|
||||
* assumes Lisbon when the camera wrote no UTC offset, and these variables include owner, firmware, colour space,
|
||||
* resolution and the focus SubjectArea, which that metadata struct does not carry. Its focus point covers two
|
||||
* Sony bodies only.
|
||||
*/
|
||||
export type CameraExtra = Pick<
|
||||
PmPhoto,
|
||||
|
||||
@@ -30,7 +30,13 @@ export async function registerMeRoutes(app: FastifyInstance, deps: { db: Db; ses
|
||||
user: { id: user.id, email: user.email, name: user.name, locale: user.locale },
|
||||
memberships: user.memberships.map((m) => ({
|
||||
role: m.role,
|
||||
organization: { id: m.organization.id, slug: m.organization.slug, name: m.organization.name, mode: m.organization.mode },
|
||||
organization: {
|
||||
id: m.organization.id,
|
||||
slug: m.organization.slug,
|
||||
name: m.organization.name,
|
||||
mode: m.organization.mode,
|
||||
realEstateEnabled: m.organization.realEstateEnabled,
|
||||
},
|
||||
})),
|
||||
preferences: { editorModules: user.preferences?.editorModules ?? ["crop", "basic"] },
|
||||
};
|
||||
|
||||
@@ -0,0 +1,89 @@
|
||||
import { groupBrackets, type BracketFrame } from "@photoreport/metadata";
|
||||
import type { FastifyInstance } from "fastify";
|
||||
import { z } from "zod";
|
||||
import { requireAuth, requireMembership } from "../auth/guard.js";
|
||||
import type { SessionService } from "../auth/sessions.js";
|
||||
import type { Db } from "../db.js";
|
||||
import { conflict } from "../lib/errors.js";
|
||||
|
||||
const OrgParams = z.object({ orgId: z.uuid() });
|
||||
const SettingBody = z.object({ enabled: z.boolean() });
|
||||
|
||||
const optionalText = z.string().trim().max(300).nullable().optional();
|
||||
const optionalNumber = z.number().nullable().optional();
|
||||
|
||||
const FrameBody = z.object({
|
||||
id: z.string().trim().min(1).max(400),
|
||||
fileName: optionalText,
|
||||
capturedAt: z.iso.datetime().nullable().optional(),
|
||||
cameraSerial: optionalText,
|
||||
cameraMake: optionalText,
|
||||
cameraModel: optionalText,
|
||||
focalLength: optionalNumber,
|
||||
aperture: optionalNumber,
|
||||
iso: optionalNumber,
|
||||
width: optionalNumber,
|
||||
height: optionalNumber,
|
||||
exposureBias: optionalNumber,
|
||||
exposureTime: optionalNumber,
|
||||
});
|
||||
|
||||
const GroupBody = z.object({ frames: z.array(FrameBody).max(4000) });
|
||||
|
||||
/**
|
||||
* The interior-bracket area. It never touches sports ingest: files stay on the photographer's
|
||||
* computer and only the exposure metadata is sent, to be grouped. Merging the frames is later.
|
||||
*/
|
||||
export async function registerRealEstateRoutes(app: FastifyInstance, deps: { db: Db; sessions: SessionService }) {
|
||||
const { db } = deps;
|
||||
const authenticate = requireAuth(deps.sessions);
|
||||
|
||||
app.get("/v1/orgs/:orgId/real-estate", { preHandler: authenticate }, async (req) => {
|
||||
const { orgId } = OrgParams.parse(req.params);
|
||||
await requireMembership(db, req, orgId, "PHOTOGRAPHER");
|
||||
const org = await db.organization.findUniqueOrThrow({ where: { id: orgId }, select: { realEstateEnabled: true } });
|
||||
return { enabled: org.realEstateEnabled };
|
||||
});
|
||||
|
||||
/** Owners show or hide the area. Hiding it does not delete anything already made. */
|
||||
app.put("/v1/orgs/:orgId/real-estate", { preHandler: authenticate }, async (req) => {
|
||||
const { orgId } = OrgParams.parse(req.params);
|
||||
const body = SettingBody.parse(req.body);
|
||||
await requireMembership(db, req, orgId, "OWNER");
|
||||
const org = await db.organization.update({ where: { id: orgId }, data: { realEstateEnabled: body.enabled }, select: { realEstateEnabled: true } });
|
||||
return { enabled: org.realEstateEnabled };
|
||||
});
|
||||
|
||||
/** Groups a shoot into one stack per angle. Refuses while the area is hidden. */
|
||||
app.post("/v1/orgs/:orgId/real-estate/groups", { preHandler: authenticate }, async (req) => {
|
||||
const { orgId } = OrgParams.parse(req.params);
|
||||
await requireMembership(db, req, orgId, "PHOTOGRAPHER");
|
||||
const org = await db.organization.findUniqueOrThrow({ where: { id: orgId }, select: { realEstateEnabled: true } });
|
||||
if (!org.realEstateEnabled) throw conflict("real_estate_disabled");
|
||||
const body = GroupBody.parse(req.body);
|
||||
return groupBrackets(body.frames.map(finiteFrame));
|
||||
});
|
||||
}
|
||||
|
||||
function finite(value: number | null | undefined): number | null {
|
||||
if (value == null || !Number.isFinite(value)) return null;
|
||||
return value;
|
||||
}
|
||||
|
||||
function finiteFrame(frame: z.infer<typeof FrameBody>): BracketFrame {
|
||||
return {
|
||||
id: frame.id,
|
||||
fileName: frame.fileName ?? null,
|
||||
capturedAt: frame.capturedAt ?? null,
|
||||
cameraSerial: frame.cameraSerial ?? null,
|
||||
cameraMake: frame.cameraMake ?? null,
|
||||
cameraModel: frame.cameraModel ?? null,
|
||||
focalLength: finite(frame.focalLength),
|
||||
aperture: finite(frame.aperture),
|
||||
iso: finite(frame.iso),
|
||||
width: finite(frame.width),
|
||||
height: finite(frame.height),
|
||||
exposureBias: finite(frame.exposureBias),
|
||||
exposureTime: finite(frame.exposureTime),
|
||||
};
|
||||
}
|
||||
@@ -119,6 +119,16 @@ export class UrlSigner {
|
||||
return `/v1/files/videos/${videoId}/${variant}?exp=${exp}&sig=${this.mac(videoId, `video-${variant}`, exp)}`;
|
||||
}
|
||||
|
||||
/** Signed URL of the frame an appearance in a video is clearest in (shown when its face is reviewed). */
|
||||
videoFaceUrl(videoFaceId: string): string {
|
||||
const exp = this.expiry();
|
||||
return `/v1/files/video-faces/${videoFaceId}?exp=${exp}&sig=${this.mac(videoFaceId, "video-face", exp)}`;
|
||||
}
|
||||
|
||||
verifyVideoFace(videoFaceId: string, exp: number, sig: string): boolean {
|
||||
return this.verifyVideo(videoFaceId, "face", exp, sig);
|
||||
}
|
||||
|
||||
verifyVideo(videoId: string, variant: string, exp: number, sig: string): boolean {
|
||||
if (!Number.isFinite(exp) || exp < Math.floor(this.now() / 1000)) return false;
|
||||
const expected = Buffer.from(this.mac(videoId, `video-${variant}`, exp));
|
||||
|
||||
@@ -105,7 +105,8 @@ const renders = renderEngine ? new RenderWorker(develop, { concurrency: capacity
|
||||
const sportsService = new SportsService({ db, storage, log, fetch });
|
||||
// Archive clouds: walked for new galleries, each image indexed as a preview whose original stays in the cloud.
|
||||
// A big backlog: many downloads from the cloud in flight, previews made by as many as the machine's share.
|
||||
const archiveService = new ArchiveService({ db, secrets, log, ingest, syncSquads: (id) => sportsService.syncEventSquads(id), ligaSeason: (season) => sportsService.importLigaSeason(season), fpaSeason: (season) => sportsService.importFpaSeason(season), storageRoot: config.STORAGE_ROOT, minFreeBytes: config.ARCHIVE_MIN_FREE_GB * 1e9, cpuSlots: capacity.archiveBurst, localDirs: localDirs(config.ARCHIVE_LOCAL_DIRS), storage, videoTools: findVideoTools({ ffmpeg: config.FFMPEG_BIN, ffprobe: config.FFPROBE_BIN }, homedir()) });
|
||||
const videoTools = findVideoTools({ ffmpeg: config.FFMPEG_BIN, ffprobe: config.FFPROBE_BIN }, homedir());
|
||||
const archiveService = new ArchiveService({ db, secrets, log, ingest, syncSquads: (id) => sportsService.syncEventSquads(id), ligaSeason: (season) => sportsService.importLigaSeason(season), fpaSeason: (season) => sportsService.importFpaSeason(season), storageRoot: config.STORAGE_ROOT, minFreeBytes: config.ARCHIVE_MIN_FREE_GB * 1e9, cpuSlots: capacity.archiveBurst, localDirs: localDirs(config.ARCHIVE_LOCAL_DIRS), storage, videoTools });
|
||||
const archive = new ArchiveWorker(archiveService, { concurrency: capacity.archive, burst: capacity.archiveDownloads, intervalMs: 2000, log, pressure: new Pressure(), videos: config.ARCHIVE_VIDEO_CONCURRENCY });
|
||||
const deliveryService = new DeliveryService({ db, storage, secrets, broadcaster, log, develop, originals: archiveService, notifications: new Notifications(db, (err) => log.warn({ err }, "notifications: not written")) });
|
||||
// Every arrival goes on to the destinations that take all of them (one's own backup of the originals).
|
||||
@@ -132,7 +133,7 @@ const faceEngine =
|
||||
const jersey = faceEngine && config.JERSEY_MODEL_DIR ? await JerseyModel.load(config.JERSEY_MODEL_DIR) : undefined;
|
||||
if (jersey) log.info({ dir: config.JERSEY_MODEL_DIR }, "shirt-number model loaded");
|
||||
const faces = faceEngine
|
||||
? new FaceWorker(new FaceService({ db, storage, broadcaster, log, engine: faceEngine, jersey }), {
|
||||
? new FaceWorker(new FaceService({ db, storage, broadcaster, log, engine: faceEngine, jersey, videoTools, videoFps: config.ARCHIVE_VIDEO_FACE_FPS }), {
|
||||
concurrency: capacity.faces,
|
||||
intervalMs: 1000,
|
||||
log,
|
||||
|
||||
@@ -9,6 +9,8 @@ import { galleryAssignments } from "../src/archive/gallery.js";
|
||||
import { canonicalTeam, describeFolder, directorySides, exhibitionName, galleryRoot, isExhibition, isInitials, isTeam, knownVersus, lisbonDay, parseFolder, pickFixture, teamLabel, teamMatcher, type FixtureCandidate } from "../src/archive/match.js";
|
||||
import { CloudClient, parseMultistatus } from "../src/archive/nextcloud.js";
|
||||
import { ArchiveService, localDirs } from "../src/archive/service.js";
|
||||
import { FaceService } from "../src/faces/service.js";
|
||||
import type { FaceAnalysis, FaceEngine } from "../src/faces/process.js";
|
||||
import { execFileSync } from "node:child_process";
|
||||
import { SecretBox } from "../src/delivery/secrets.js";
|
||||
import { IngestService } from "../src/ingest/service.js";
|
||||
@@ -1540,6 +1542,194 @@ describe("archive from a Nextcloud", () => {
|
||||
await ctx.app.inject({ method: "POST", url: `/v1/cloud-sources/${source.id}/scan`, headers: bearer(token) });
|
||||
expect((await ctx.db.cloudVideo.findFirstOrThrow({ where: { path: { endsWith: "Treino.mp4" } } })).status).toBe("PENDING");
|
||||
}, 60_000);
|
||||
|
||||
it.skipIf(!hasFfmpeg)("finds faces in videos the photos' way: same groups, same suggestions, reviewed and named, and shown with when", async () => {
|
||||
const game = "/FPA/Fotos/2025_2026/Competições Nacionais/PO01/20250913 - SCP x ABC";
|
||||
cloud.add(`${game}/Golo 1.mp4`, mp4(640, 360));
|
||||
await ctx.db.organization.update({ where: { id: orgId }, data: { biometricsEnabled: true, biometricsLegalBasis: "teste" } });
|
||||
const source = await connect();
|
||||
cloud.authorised = true;
|
||||
await ctx.app.inject({ method: "GET", url: `/v1/cloud-sources/${source.id}`, headers: bearer(token) });
|
||||
const storage = new LocalStorage(storageRoot);
|
||||
const videoWorker = new ArchiveService({ db: ctx.db, secrets: new SecretBox(KEY), log: quiet, fetchImpl: fetchProxy, storage, videoTools: { ffmpeg: "ffmpeg", ffprobe: "ffprobe" } });
|
||||
await videoWorker.scan(source.id);
|
||||
for (const id of await worker.claim(10)) await worker.index(id);
|
||||
for (const id of await videoWorker.claimVideos(5)) await videoWorker.indexVideo(id);
|
||||
const video = await ctx.db.cloudVideo.findFirstOrThrow();
|
||||
expect(video).toMatchObject({ status: "DONE", facesStatus: "PENDING" });
|
||||
const facesCount = async () => (await ctx.app.inject({ method: "GET", url: `/v1/orgs/${orgId}/cloud-sources`, headers: bearer(token) })).json().sources[0].counts;
|
||||
expect(await facesCount()).toMatchObject({ videoFacesPending: 1, videoFacesDone: 0 });
|
||||
|
||||
// Rita in the photos and the first second of the video; someone else from 0.8 s on, in the video only.
|
||||
const rita = unitVec(1);
|
||||
const other = unitVec(2);
|
||||
const at = (x: number, emb: number[]) => ({ x0: x, y0: 0.2, x1: x + 0.12, y1: 0.4, score: 0.95, sharpness: 120, landmarks: [] as [number, number][], embedding: emb });
|
||||
const engine: FaceEngine = {
|
||||
model: "auraface-v1",
|
||||
async analyse(file: string): Promise<FaceAnalysis> {
|
||||
const frame = /frame_(\d+)\.jpg$/.exec(file);
|
||||
if (!frame) return { width: 2048, height: 1365, faces: [at(0.4, rita)] };
|
||||
const i = Number(frame[1]);
|
||||
return { width: 640, height: 360, faces: [...(i <= 6 ? [at(0.1, rita)] : []), ...(i >= 5 ? [at(0.6, other)] : [])] };
|
||||
},
|
||||
async close() {},
|
||||
};
|
||||
const faces = new FaceService({ db: ctx.db, storage, broadcaster: new MemoryBroadcaster(), log: quiet, engine, videoTools: { ffmpeg: "ffmpeg", ffprobe: "ffprobe" }, videoFps: 5 });
|
||||
await ctx.db.person.create({ data: { organizationId: orgId, name: "Rita Sousa", centroid: rita, model: "auraface-v1", faceCount: 5 } });
|
||||
await ctx.db.photo.updateMany({ data: { facesStatus: "PENDING" } });
|
||||
for (let ids = await faces.claim(10); ids.length; ids = await faces.claim(10)) for (const id of ids) await faces.process(id);
|
||||
expect(await faces.claimVideos(1)).toEqual([video.id]);
|
||||
await faces.processVideo(video.id);
|
||||
|
||||
// Two appearances, each with when it is on screen and its frame; Rita's joins the group of her photos' faces.
|
||||
const appearances = await ctx.db.videoFace.findMany({ where: { videoId: video.id }, orderBy: { startMs: "asc" } });
|
||||
expect(appearances.map((a) => [a.startMs, a.endMs, a.frames])).toEqual([
|
||||
[0, 1000, 6],
|
||||
[800, 1800, 6],
|
||||
]);
|
||||
expect(await storage.exists(appearances[0]!.frameKey)).toBe(true);
|
||||
const photoFace = await ctx.db.face.findFirstOrThrow({ where: { photo: { originalName: "PS_0001.jpg" } } });
|
||||
expect(appearances[0]!.groupId).toBe(photoFace.groupId);
|
||||
expect(appearances[1]!.groupId).not.toBe(photoFace.groupId);
|
||||
const ritaGroup = await ctx.db.faceGroup.findUniqueOrThrow({ where: { id: photoFace.groupId! }, include: { suggested: true } });
|
||||
expect(ritaGroup.suggested?.name).toBe("Rita Sousa");
|
||||
expect((await ctx.db.cloudVideo.findUniqueOrThrow({ where: { id: video.id } })).facesStatus).toBe("DONE");
|
||||
expect(await facesCount()).toMatchObject({ videoFacesPending: 0, videoFacesDone: 1, videoFacesFailed: 0 });
|
||||
|
||||
// An editor of the game's folder reviews it: the card carries the video's frame, and confirming names both.
|
||||
const po01 = cloud.idOf("/FPA/Fotos/2025_2026/Competições Nacionais/PO01");
|
||||
cloud.viewers.set("abc", { password: "abc-pass", shared: [po01], edit: [po01] });
|
||||
cloud.authorised = false;
|
||||
cloud.loginAs = "abc";
|
||||
const { state } = (await ctx.app.inject({ method: "POST", url: `/v1/archive/${source.id}/login` })).json() as { state: string };
|
||||
cloud.authorised = true;
|
||||
const club = ((await ctx.app.inject({ method: "POST", url: "/v1/archive/login/poll", payload: { state } })).json() as { token: string }).token;
|
||||
const as = { authorization: `Archive ${club}` };
|
||||
let res = await ctx.app.inject({ method: "GET", url: `/v1/archive/${source.id}/review?status=suggested`, headers: as });
|
||||
const card = (res.json().groups as { id: string; photos: number; videos: number; faces: { src: string; video?: { id: string; atMs: number } }[] }[]).find((g) => g.id === ritaGroup.id)!;
|
||||
expect(card).toMatchObject({ photos: 2, videos: 1 });
|
||||
const frame = card.faces.find((f) => f.video)!;
|
||||
expect(frame.video).toMatchObject({ id: video.id });
|
||||
res = await ctx.app.inject({ method: "GET", url: frame.src });
|
||||
expect([res.statusCode, res.headers["content-type"]]).toEqual([200, "image/jpeg"]);
|
||||
expect((await ctx.app.inject({ method: "GET", url: frame.src.replace(/sig=[^&]+/, "sig=AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA") })).statusCode).toBe(404);
|
||||
|
||||
// Before: probable in the gallery's video. After confirming: named, with when.
|
||||
const gameFolder = await ctx.db.cloudFolder.findFirstOrThrow({ where: { path: game } });
|
||||
const peopleOfVideo = async () => ((await ctx.app.inject({ method: "GET", url: `/v1/archive/galleries/${gameFolder.id}`, headers: as })).json().videos[0].people as { name: string; level: string; startMs: number; moments: unknown[] }[]);
|
||||
expect(await peopleOfVideo()).toEqual([expect.objectContaining({ name: "Rita Sousa", level: "probable", startMs: 0 })]);
|
||||
res = await ctx.app.inject({ method: "POST", url: `/v1/archive/${source.id}/review/groups/${ritaGroup.id}`, headers: as, payload: { action: "confirm" } });
|
||||
expect(res.statusCode).toBe(200);
|
||||
expect(await peopleOfVideo()).toEqual([{ id: ritaGroup.suggestedPersonId, name: "Rita Sousa", level: "confirmed", startMs: 0, moments: [{ startMs: 0, endMs: 1000 }] }]);
|
||||
|
||||
// Her page lists the video, with its frame and the moments to jump to.
|
||||
res = await ctx.app.inject({ method: "GET", url: `/v1/archive/${source.id}/people/${ritaGroup.suggestedPersonId}`, headers: as });
|
||||
expect(res.json().videos).toEqual([expect.objectContaining({ id: video.id, name: "Golo 1.mp4", level: "confirmed", moments: [{ startMs: 0, endMs: 1000 }], gallery: expect.objectContaining({ id: gameFolder.id }) })]);
|
||||
|
||||
// A viewer without edit rights cannot act on a group that has the video.
|
||||
cloud.viewers.set("ler", { password: "ler-pass", shared: [po01] });
|
||||
cloud.authorised = false;
|
||||
cloud.loginAs = "ler";
|
||||
const s2 = ((await ctx.app.inject({ method: "POST", url: `/v1/archive/${source.id}/login` })).json() as { state: string }).state;
|
||||
cloud.authorised = true;
|
||||
const reader = ((await ctx.app.inject({ method: "POST", url: "/v1/archive/login/poll", payload: { state: s2 } })).json() as { token: string }).token;
|
||||
const otherGroup = appearances[1]!.groupId!;
|
||||
res = await ctx.app.inject({ method: "POST", url: `/v1/archive/${source.id}/review/groups/${otherGroup}`, headers: { authorization: `Archive ${reader}` }, payload: { action: "ignore" } });
|
||||
expect(res.statusCode).toBe(403);
|
||||
|
||||
// The folder moved to another event: its video's faces are looked for again there, never left in the old groups.
|
||||
const fixture = await ctx.db.sportsFixture.findFirstOrThrow({ where: { externalId: "g2" } });
|
||||
await videoWorker.setFolderEvent(gameFolder.id, { fixtureId: fixture.id });
|
||||
expect(await ctx.db.videoFace.count({ where: { videoId: video.id } })).toBe(0);
|
||||
expect((await ctx.db.cloudVideo.findUniqueOrThrow({ where: { id: video.id } })).facesStatus).toBe("PENDING");
|
||||
expect(await storage.exists(appearances[0]!.frameKey)).toBe(false);
|
||||
}, 90_000);
|
||||
|
||||
it.skipIf(!hasFfmpeg)("reads a long video a minute at a time: one face on screen throughout is one appearance", async () => {
|
||||
const game = "/FPA/Fotos/2025_2026/Competições Nacionais/PO01/20250913 - SCP x ABC";
|
||||
cloud.add(`${game}/Jogo.mp4`, execFileSync("ffmpeg", ["-hide_banner", "-loglevel", "error", "-f", "lavfi", "-i", "testsrc=size=160x90:rate=5:duration=65", "-c:v", "mpeg4", "-f", "mp4", "-movflags", "frag_keyframe+empty_moov", "pipe:1"], { maxBuffer: 64 * 1024 * 1024 }));
|
||||
await ctx.db.organization.update({ where: { id: orgId }, data: { biometricsEnabled: true, biometricsLegalBasis: "teste" } });
|
||||
const source = await connect();
|
||||
cloud.authorised = true;
|
||||
await ctx.app.inject({ method: "GET", url: `/v1/cloud-sources/${source.id}`, headers: bearer(token) });
|
||||
const storage = new LocalStorage(storageRoot);
|
||||
const videoWorker = new ArchiveService({ db: ctx.db, secrets: new SecretBox(KEY), log: quiet, fetchImpl: fetchProxy, storage, videoTools: { ffmpeg: "ffmpeg", ffprobe: "ffprobe" } });
|
||||
await videoWorker.scan(source.id);
|
||||
for (const id of await videoWorker.claimVideos(5)) await videoWorker.indexVideo(id);
|
||||
const video = await ctx.db.cloudVideo.findFirstOrThrow();
|
||||
const someone = unitVec(7);
|
||||
let analysed = 0;
|
||||
const engine: FaceEngine = {
|
||||
model: "auraface-v1",
|
||||
async analyse(): Promise<FaceAnalysis> {
|
||||
analysed++;
|
||||
return { width: 160, height: 90, faces: [{ x0: 0.4, y0: 0.2, x1: 0.55, y1: 0.5, score: 0.9, sharpness: 100, landmarks: [], embedding: someone }] };
|
||||
},
|
||||
async close() {},
|
||||
};
|
||||
const faces = new FaceService({ db: ctx.db, storage, broadcaster: new MemoryBroadcaster(), log: quiet, engine, videoTools: { ffmpeg: "ffmpeg", ffprobe: "ffprobe" }, videoFps: 2 });
|
||||
expect(await faces.claimVideos(1)).toEqual([video.id]);
|
||||
await faces.processVideo(video.id);
|
||||
expect(analysed).toBeGreaterThanOrEqual(128);
|
||||
const appearances = await ctx.db.videoFace.findMany({ where: { videoId: video.id } });
|
||||
expect(appearances).toHaveLength(1);
|
||||
expect(appearances[0]!.startMs).toBe(0);
|
||||
expect(appearances[0]!.endMs).toBeGreaterThan(64_000);
|
||||
expect(appearances[0]!.frames).toBe(analysed);
|
||||
}, 120_000);
|
||||
|
||||
it.skipIf(!hasFfmpeg)("never keeps a stale video result: asked again meanwhile, it is dropped; a stopping worker puts it back", async () => {
|
||||
const game = "/FPA/Fotos/2025_2026/Competições Nacionais/PO01/20250913 - SCP x ABC";
|
||||
cloud.add(`${game}/Golo 1.mp4`, mp4(640, 360));
|
||||
await ctx.db.organization.update({ where: { id: orgId }, data: { biometricsEnabled: true, biometricsLegalBasis: "teste" } });
|
||||
const source = await connect();
|
||||
cloud.authorised = true;
|
||||
await ctx.app.inject({ method: "GET", url: `/v1/cloud-sources/${source.id}`, headers: bearer(token) });
|
||||
const storage = new LocalStorage(storageRoot);
|
||||
const videoWorker = new ArchiveService({ db: ctx.db, secrets: new SecretBox(KEY), log: quiet, fetchImpl: fetchProxy, storage, videoTools: { ffmpeg: "ffmpeg", ffprobe: "ffprobe" } });
|
||||
await videoWorker.scan(source.id);
|
||||
for (const id of await videoWorker.claimVideos(5)) await videoWorker.indexVideo(id);
|
||||
const video = await ctx.db.cloudVideo.findFirstOrThrow();
|
||||
const someone = unitVec(9);
|
||||
let onFirst: (() => Promise<void>) | null = null;
|
||||
const engine: FaceEngine = {
|
||||
model: "auraface-v1",
|
||||
async analyse(): Promise<FaceAnalysis> {
|
||||
const hook = onFirst;
|
||||
onFirst = null;
|
||||
if (hook) await hook();
|
||||
return { width: 640, height: 360, faces: [{ x0: 0.4, y0: 0.2, x1: 0.55, y1: 0.5, score: 0.9, sharpness: 100, landmarks: [], embedding: someone }] };
|
||||
},
|
||||
async close() {},
|
||||
};
|
||||
const faces = new FaceService({ db: ctx.db, storage, broadcaster: new MemoryBroadcaster(), log: quiet, engine, videoTools: { ffmpeg: "ffmpeg", ffprobe: "ffprobe" }, videoFps: 5 });
|
||||
|
||||
// Asked again while being read (its folder moved, its copy made again): this run writes nothing.
|
||||
expect(await faces.claimVideos(1)).toEqual([video.id]);
|
||||
onFirst = async () => void (await ctx.db.cloudVideo.update({ where: { id: video.id }, data: { facesStatus: "PENDING" } }));
|
||||
await faces.processVideo(video.id);
|
||||
expect(await ctx.db.videoFace.count()).toBe(0);
|
||||
expect((await ctx.db.cloudVideo.findUniqueOrThrow({ where: { id: video.id } })).facesStatus).toBe("PENDING");
|
||||
|
||||
// The next run is the one that counts.
|
||||
expect(await faces.claimVideos(1)).toEqual([video.id]);
|
||||
await faces.processVideo(video.id);
|
||||
expect(await ctx.db.videoFace.count()).toBe(1);
|
||||
expect((await ctx.db.cloudVideo.findUniqueOrThrow({ where: { id: video.id } })).facesStatus).toBe("DONE");
|
||||
|
||||
// A worker stopping mid-video (a deploy) puts it back in the queue, its earlier faces untouched.
|
||||
await ctx.db.cloudVideo.update({ where: { id: video.id }, data: { facesStatus: "PENDING" } });
|
||||
expect(await faces.claimVideos(1)).toEqual([video.id]);
|
||||
onFirst = async () => faces.stopVideos();
|
||||
await faces.processVideo(video.id);
|
||||
expect((await ctx.db.cloudVideo.findUniqueOrThrow({ where: { id: video.id } })).facesStatus).toBe("PENDING");
|
||||
expect(await ctx.db.videoFace.count()).toBe(1);
|
||||
|
||||
// Left RUNNING by a worker that is gone, and failed ones after a while: back in the queue.
|
||||
await ctx.db.$executeRaw`UPDATE cloud_videos SET faces_status = 'RUNNING', updated_at = now() - interval '2 hours'`;
|
||||
expect(await faces.requeueVideos()).toBe(1);
|
||||
expect((await ctx.db.cloudVideo.findUniqueOrThrow({ where: { id: video.id } })).facesStatus).toBe("PENDING");
|
||||
}, 90_000);
|
||||
});
|
||||
|
||||
const hasFfmpeg = (() => {
|
||||
@@ -1561,3 +1751,10 @@ function mp4(width: number, height: number): Buffer {
|
||||
"-f", "mp4", "-movflags", "frag_keyframe+empty_moov", "pipe:1",
|
||||
], { maxBuffer: 64 * 1024 * 1024 });
|
||||
}
|
||||
|
||||
/** A unit vector of the embedder's length, different for each seed. */
|
||||
function unitVec(seed: number): number[] {
|
||||
const v = Array.from({ length: 512 }, (_, i) => Math.sin(seed * 977 + i * 13.37));
|
||||
const n = Math.hypot(...v);
|
||||
return v.map((x) => x / n);
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
import { afterAll, beforeAll, beforeEach, describe, expect, it } from "vitest";
|
||||
import { bearer, createTestApp, login, resetDb, seedUser, type TestContext } from "./helpers.js";
|
||||
|
||||
let ctx: TestContext;
|
||||
beforeAll(async () => {
|
||||
ctx = await createTestApp();
|
||||
});
|
||||
afterAll(async () => {
|
||||
await ctx.app.close();
|
||||
await ctx.db.$disconnect();
|
||||
});
|
||||
beforeEach(() => resetDb(ctx.db));
|
||||
|
||||
const at = (ms: number) => new Date(Date.parse("2026-10-21T10:00:00.000Z") + ms).toISOString();
|
||||
|
||||
function shot(id: string, bias: number, ms: number) {
|
||||
return {
|
||||
id,
|
||||
fileName: `${id}.CR3`,
|
||||
capturedAt: at(ms),
|
||||
cameraSerial: "body",
|
||||
focalLength: 16,
|
||||
aperture: 8,
|
||||
iso: 100,
|
||||
exposureBias: bias,
|
||||
exposureTime: 0.01,
|
||||
};
|
||||
}
|
||||
|
||||
describe("real estate", () => {
|
||||
it("stays off until the owner turns it on, and then groups a bracket without taking the files", async () => {
|
||||
const { org } = await seedUser(ctx.db, "[email protected]", { org: "casa", role: "OWNER" });
|
||||
await seedUser(ctx.db, "[email protected]", { org: "casa", role: "PHOTOGRAPHER" });
|
||||
await seedUser(ctx.db, "[email protected]", { org: "casa", role: "CLIENT" });
|
||||
const owner = await login(ctx.app, "[email protected]");
|
||||
const photographer = await login(ctx.app, "[email protected]");
|
||||
const client = await login(ctx.app, "[email protected]");
|
||||
const orgId = org!.id;
|
||||
const url = `/v1/orgs/${orgId}/real-estate`;
|
||||
|
||||
const me = await ctx.app.inject({ method: "GET", url: "/v1/me", headers: bearer(owner.body.accessToken) });
|
||||
expect(me.json().memberships[0].organization.realEstateEnabled).toBe(false);
|
||||
|
||||
const hidden = await ctx.app.inject({
|
||||
method: "POST",
|
||||
url: `${url}/groups`,
|
||||
headers: bearer(owner.body.accessToken),
|
||||
payload: { frames: [shot("a", -2, 0), shot("b", 0, 200), shot("c", 2, 400)] },
|
||||
});
|
||||
expect(hidden.statusCode).toBe(409);
|
||||
expect(hidden.json().error).toBe("real_estate_disabled");
|
||||
|
||||
const asPhotographer = await ctx.app.inject({
|
||||
method: "PUT",
|
||||
url,
|
||||
headers: bearer(photographer.body.accessToken),
|
||||
payload: { enabled: true },
|
||||
});
|
||||
expect(asPhotographer.statusCode).toBe(403);
|
||||
|
||||
const on = await ctx.app.inject({ method: "PUT", url, headers: bearer(owner.body.accessToken), payload: { enabled: true } });
|
||||
expect(on.json()).toEqual({ enabled: true });
|
||||
|
||||
const asClient = await ctx.app.inject({
|
||||
method: "POST",
|
||||
url: `${url}/groups`,
|
||||
headers: bearer(client.body.accessToken),
|
||||
payload: { frames: [shot("a", -2, 0)] },
|
||||
});
|
||||
expect(asClient.statusCode).toBe(403);
|
||||
|
||||
const grouped = await ctx.app.inject({
|
||||
method: "POST",
|
||||
url: `${url}/groups`,
|
||||
headers: bearer(photographer.body.accessToken),
|
||||
payload: {
|
||||
frames: [shot("a", -2, 0), shot("b", 0, 200), shot("c", 2, 400), shot("solo", 0, 30_000)],
|
||||
},
|
||||
});
|
||||
expect(grouped.statusCode).toBe(200);
|
||||
expect(grouped.json()).toEqual({ stacks: [{ frameIds: ["a", "b", "c"] }], aside: ["solo"] });
|
||||
});
|
||||
});
|
||||
@@ -16,6 +16,7 @@ import { LoginPage } from "./pages/LoginPage.js";
|
||||
import { MembersPage } from "./pages/MembersPage.js";
|
||||
import { MetadataPage } from "./pages/MetadataPage.js";
|
||||
import { PreferencesPage } from "./pages/PreferencesPage.js";
|
||||
import { RealEstatePage } from "./pages/RealEstatePage.js";
|
||||
import { Shell } from "./pages/Shell.js";
|
||||
|
||||
function Gate() {
|
||||
@@ -40,6 +41,7 @@ function Gate() {
|
||||
<Route path="members" element={<MembersPage />} />
|
||||
<Route path="preferences" element={<PreferencesPage />} />
|
||||
<Route path="help" element={<HelpPage />} />
|
||||
<Route path="real-estate" element={<RealEstatePage />} />
|
||||
<Route path="*" element={<p className="p-6 text-sm text-muted">{t.notFound}</p>} />
|
||||
</Route>
|
||||
<Route path="/login" element={<Navigate to="/" replace />} />
|
||||
|
||||
@@ -19,14 +19,30 @@ export interface WasmPhoto {
|
||||
free(): void;
|
||||
}
|
||||
|
||||
export interface BracketJob {
|
||||
push(bytes: Uint8Array): void;
|
||||
merge(maxEdge: number): BracketMerge;
|
||||
free(): void;
|
||||
}
|
||||
|
||||
export interface BracketMerge {
|
||||
readonly width: number;
|
||||
readonly height: number;
|
||||
jpeg(): Uint8Array;
|
||||
free(): void;
|
||||
}
|
||||
|
||||
export interface EngineModule {
|
||||
default(init?: { module_or_path: string }): Promise<unknown>;
|
||||
/** Capture metadata JSON from LightCraft. `{}` when the file has none. */
|
||||
readCaptureMeta(bytes: Uint8Array): string;
|
||||
controls(): string;
|
||||
defaultSettings(): string;
|
||||
apply(settings: string, command: string): string;
|
||||
value(settings: string, id: string): number;
|
||||
isUnedited(settings: string): boolean;
|
||||
Photo: new (bytes: Uint8Array, maxEdge: number) => WasmPhoto;
|
||||
BracketJob: new () => BracketJob;
|
||||
}
|
||||
|
||||
const BASE = `${import.meta.env.BASE_URL ?? "/"}engine/`;
|
||||
|
||||
@@ -205,6 +205,40 @@ export const t = {
|
||||
disable: "Desligar",
|
||||
enabled: "Ligado",
|
||||
},
|
||||
realEstate: {
|
||||
nav: "Imobiliário",
|
||||
title: "Imobiliário",
|
||||
setting: "Imobiliário",
|
||||
settingHelp: "Zona à parte para interiores em bracket. Desligada, desaparece do menu. O FTP e a biblioteca de jogos não mudam.",
|
||||
enable: "Ligar",
|
||||
disable: "Desligar",
|
||||
enabled: "Ligado",
|
||||
off: "Desligado",
|
||||
intro: "Larga os ficheiros de um imóvel. Cada ângulo são várias exposições da mesma posição, normalmente três. Os ficheiros ficam neste computador; para agrupar só seguem os dados de exposição.",
|
||||
step: "Cada ângulo é fundido aqui, neste computador, pelo motor de imagem. A janela vem da exposição escura e a sala da clara.",
|
||||
fusing: "A fundir este ângulo…",
|
||||
fuseFailed: "Não deu para fundir este ângulo.",
|
||||
previewAlt: (n: number) => `Ângulo ${n} fundido`,
|
||||
choose: "Escolher ficheiros",
|
||||
chooseFolder: "Escolher pasta",
|
||||
dropHint: "ou larga uma pasta aqui",
|
||||
reading: (done: number, total: number) => `A ler ${done} de ${total}…`,
|
||||
noPhotos: "Não há fotografias nesta seleção. Um ficheiro XMP só acompanha o raw.",
|
||||
support: (n: number) => (n === 1 ? "1 ficheiro de apoio (XMP e semelhantes) não é uma fotografia." : `${n} ficheiros de apoio (XMP e semelhantes) não são fotografias.`),
|
||||
asideMore: (n: number) => `e mais ${n}`,
|
||||
stacks: (n: number) => (n === 1 ? "1 ângulo" : `${n} ângulos`),
|
||||
aside: (n: number) => (n === 1 ? "1 fotografia fica de fora" : `${n} fotografias ficam de fora`),
|
||||
asideHelp: "Não entram num bracket de pelo menos três exposições, com a luz e a sombra afastadas.",
|
||||
angle: (n: number, frames: number) => `Ângulo ${n} · ${frames === 1 ? "1 exposição" : `${frames} exposições`}`,
|
||||
bias: (value: string) => `${value} EV`,
|
||||
noBias: "exposição sem compensação",
|
||||
noExposure: "sem dados de exposição",
|
||||
disabled: "O imobiliário está desligado. O proprietário liga-o em Preferências.",
|
||||
none: "Nenhum ângulo com três ou mais exposições.",
|
||||
errors: {
|
||||
real_estate_disabled: "O imobiliário está desligado nesta organização.",
|
||||
} as Record<string, string>,
|
||||
},
|
||||
uploading: (done: number, total: number) => `A enviar ${done} de ${total}`,
|
||||
uploaded: (n: number) => (n === 1 ? "1 foto enviada" : `${n} fotos enviadas`),
|
||||
uploadFailed: (n: number) => `${n} com erro`,
|
||||
|
||||
@@ -114,4 +114,25 @@ describe("library store", () => {
|
||||
expect(s.photos.map((p) => p.id)).toEqual(["a", "live"]);
|
||||
expect(s.loading).toBe(false);
|
||||
});
|
||||
|
||||
it("replaces expired file urls from the cache and keeps a mark made while the list was loading", () => {
|
||||
const stale = { thumb: "/v1/files/photos/a/thumb?exp=1&v=2", preview: "/old-preview?v=2", source: "/old-source" };
|
||||
const fresh = { thumb: "/v1/files/photos/a/thumb?exp=9&v=2", preview: "/new-preview?v=2", source: "/new-source" };
|
||||
let s = libraryReducer(initialLibrary, { type: "load", scope: "e1" });
|
||||
s = libraryReducer(s, { type: "loaded", scope: "e1", photos: [photo("a", "1", { urls: stale })], done: false });
|
||||
s = libraryReducer(s, { type: "patch", ids: ["a"], patch: { flag: "PICK" } });
|
||||
s = libraryReducer(s, { type: "loaded", scope: "e1", photos: [photo("a", "1", { urls: fresh, flag: "NONE" })], done: true, drop: ["a"] });
|
||||
expect(s.photos[0]).toMatchObject({ flag: "PICK", urls: fresh });
|
||||
});
|
||||
|
||||
it("does not roll a thumbnail back to an older render that the list still has", () => {
|
||||
const shown = { thumb: "/thumb?v=4", preview: "/preview?v=4", source: "/source" };
|
||||
const older = { thumb: "/thumb?v=3", preview: "/preview?v=3", source: "/source" };
|
||||
let s = libraryReducer(initialLibrary, { type: "load", scope: "e1" });
|
||||
s = libraryReducer(s, { type: "loaded", scope: "e1", photos: [photo("a", "1", { urls: older })], done: false });
|
||||
s = libraryReducer(s, { type: "message", message: { type: "photo.rendered", photoId: "a", renderedSeq: 4, urls: { thumb: shown.thumb, preview: shown.preview } } });
|
||||
s = libraryReducer(s, { type: "loaded", scope: "e1", photos: [photo("a", "1", { urls: older })], done: true, drop: ["a"] });
|
||||
expect(s.photos[0]!.urls.thumb).toBe(shown.thumb);
|
||||
expect(s.photos[0]!.urls.preview).toBe(shown.preview);
|
||||
});
|
||||
});
|
||||
@@ -44,6 +44,29 @@ function inScope(scope: string | null, photo: PhotoSummary): boolean {
|
||||
return scope === "inbox" ? photo.eventId === null : photo.eventId === scope;
|
||||
}
|
||||
|
||||
/** Edit version in a signed file URL (`v`). A render that arrived while the list was loading must not be rolled back. */
|
||||
function renderedVersion(url: string): number {
|
||||
const match = /[?&]v=(\d+)/.exec(url);
|
||||
if (!match) return 0;
|
||||
return Number(match[1]);
|
||||
}
|
||||
|
||||
/**
|
||||
* The folder is drawn from the last visit before the network answers. Marks made in that moment stay,
|
||||
* but the signed file URLs from that visit expire, so the server's signatures take their place.
|
||||
*/
|
||||
function withFreshFileUrls(current: PhotoSummary, incoming: PhotoSummary | undefined): PhotoSummary {
|
||||
if (!incoming) return current;
|
||||
let next = current;
|
||||
if (current.status !== "READY" && incoming.status !== current.status) {
|
||||
next = { ...next, status: incoming.status };
|
||||
if (incoming.error) next = { ...next, error: incoming.error };
|
||||
}
|
||||
if (renderedVersion(incoming.urls.thumb) < renderedVersion(current.urls.thumb)) return next;
|
||||
if (current.urls.thumb === incoming.urls.thumb && current.urls.preview === incoming.urls.preview && current.urls.source === incoming.urls.source) return next;
|
||||
return { ...next, urls: incoming.urls };
|
||||
}
|
||||
|
||||
/** The server's copy replaces a local photo: what was done to it here stays (it is being sent too). */
|
||||
function replaceLocal(state: LibraryState, local: PhotoSummary, server: PhotoSummary): LibraryState {
|
||||
const keep: Partial<PhotoSummary> = {
|
||||
@@ -67,10 +90,11 @@ export function libraryReducer(state: LibraryState, action: LibraryAction): Libr
|
||||
// A cached folder is shown first. Once the server has answered, photos that were only in that cache
|
||||
// (they have since moved to another event) leave. Anything that arrived meanwhile stays.
|
||||
const drop = new Set(action.drop ?? []);
|
||||
const incoming = new Set(action.photos.map((p) => p.id));
|
||||
const incoming = new Map(action.photos.map((p) => [p.id, p]));
|
||||
const prior = drop.size ? state.photos.filter((p) => !drop.has(p.id) || incoming.has(p.id)) : state.photos;
|
||||
const seen = new Set(prior.map((p) => p.id));
|
||||
const photos = [...prior, ...action.photos.filter((p) => !seen.has(p.id))];
|
||||
const refreshed = prior.map((p) => withFreshFileUrls(p, incoming.get(p.id)));
|
||||
const seen = new Set(refreshed.map((p) => p.id));
|
||||
const photos = [...refreshed, ...action.photos.filter((p) => !seen.has(p.id))];
|
||||
// The active photo from another module (or the last visit): selected as soon as its page arrives.
|
||||
if (state.wanted && photos.some((p) => p.id === state.wanted)) {
|
||||
const id = state.wanted;
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { DEFAULT_MODULES, MODULES, type Module } from "@photoreport/contracts";
|
||||
import { ApiError } from "@photoreport/sdk";
|
||||
import { useState } from "react";
|
||||
import { useAuth } from "../auth.js";
|
||||
import { LocalCatalog } from "../desktop/LocalCatalog.js";
|
||||
@@ -11,9 +12,12 @@ import { PageHeader } from "./Shell.js";
|
||||
const CHOOSABLE = MODULES.filter((m) => m !== "advanced");
|
||||
|
||||
export function PreferencesPage() {
|
||||
const { api, me, reload } = useAuth();
|
||||
const { api, me, reload, organization, role } = useAuth();
|
||||
const [selected, setSelected] = useState<Module[]>(me?.preferences.editorModules ?? [...DEFAULT_MODULES]);
|
||||
const [status, setStatus] = useState<"idle" | "saved" | "error">("idle");
|
||||
const [realEstateError, setRealEstateError] = useState<string | null>(null);
|
||||
const [realEstateBusy, setRealEstateBusy] = useState(false);
|
||||
const realEstateOn = organization?.realEstateEnabled === true;
|
||||
|
||||
const toggle = async (module: Module) => {
|
||||
const next = selected.includes(module) ? selected.filter((m) => m !== module) : [...selected, module];
|
||||
@@ -52,6 +56,43 @@ export function PreferencesPage() {
|
||||
))}
|
||||
</ul>
|
||||
</section>
|
||||
{role === "OWNER" && organization && (
|
||||
<section className="max-w-2xl px-6 pb-6">
|
||||
<div className="border border-line bg-panel">
|
||||
<div className="panel-head">
|
||||
<span>{t.realEstate.setting}</span>
|
||||
<span className={realEstateOn ? "text-ok" : "text-faint"}>{realEstateOn ? t.realEstate.enabled : t.realEstate.off}</span>
|
||||
</div>
|
||||
<div className="space-y-3 p-4">
|
||||
<p className="text-[13px] text-muted">{t.realEstate.settingHelp}</p>
|
||||
{realEstateError && <p className="text-[12px] text-danger">{realEstateError}</p>}
|
||||
<div className="flex justify-end">
|
||||
<button
|
||||
disabled={realEstateBusy}
|
||||
onClick={() => {
|
||||
setRealEstateBusy(true);
|
||||
setRealEstateError(null);
|
||||
void (async () => {
|
||||
try {
|
||||
await api.setRealEstate(organization.id, !realEstateOn);
|
||||
await reload();
|
||||
} catch (err) {
|
||||
const code = err instanceof ApiError ? err.code : "";
|
||||
setRealEstateError(t.realEstate.errors[code] ?? t.unexpectedError);
|
||||
} finally {
|
||||
setRealEstateBusy(false);
|
||||
}
|
||||
})();
|
||||
}}
|
||||
className="h-8 border border-black bg-cell px-4 text-[13px] hover:bg-cell-on disabled:opacity-50"
|
||||
>
|
||||
{realEstateOn ? t.realEstate.disable : t.realEstate.enable}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
)}
|
||||
{isDesktop() && <LocalCatalog />}
|
||||
</>
|
||||
);
|
||||
|
||||
@@ -0,0 +1,109 @@
|
||||
import type { BracketFrame } from "@photoreport/metadata";
|
||||
import { groupBrackets } from "@photoreport/metadata";
|
||||
import type { ApiClient, Me, Organization } from "@photoreport/sdk";
|
||||
import { render, screen } from "@testing-library/react";
|
||||
import userEvent from "@testing-library/user-event";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { App } from "../App.js";
|
||||
|
||||
vi.mock("../library/realtime.js", () => ({
|
||||
useLibraryLive: () => "live",
|
||||
onSocketLive: () => () => undefined,
|
||||
}));
|
||||
vi.mock("../realestate/fuse.js", () => ({
|
||||
fuseBracket: () => Promise.resolve(new Blob([Uint8Array.from([0xff, 0xd8])], { type: "image/jpeg" })),
|
||||
}));
|
||||
|
||||
const staged = vi.hoisted(() => ({ frames: new Map<string, BracketFrame>() }));
|
||||
|
||||
vi.mock("../realestate/readFrame.js", async () => {
|
||||
const actual = await vi.importActual<typeof import("../realestate/readFrame.js")>("../realestate/readFrame.js");
|
||||
return {
|
||||
...actual,
|
||||
readBracketFile: (file: File) => Promise.resolve(staged.frames.get(file.name) ?? { id: file.name, fileName: file.name }),
|
||||
};
|
||||
});
|
||||
|
||||
const org = (realEstateEnabled: boolean): Organization => ({ id: "o1", slug: "fpa", name: "FPA", mode: "AGENCY", realEstateEnabled });
|
||||
|
||||
function me(role: Me["memberships"][number]["role"], realEstateEnabled: boolean): Me {
|
||||
return {
|
||||
user: { id: "u1", email: "[email protected]", name: "Ana", locale: "pt-PT" },
|
||||
memberships: [{ role, organization: org(realEstateEnabled) }],
|
||||
preferences: { editorModules: ["crop", "basic"] },
|
||||
};
|
||||
}
|
||||
|
||||
function fakeApi(who: Me, overrides: Partial<Record<keyof ApiClient, unknown>> = {}): ApiClient {
|
||||
return {
|
||||
client: "web",
|
||||
resume: vi.fn().mockResolvedValue(true),
|
||||
me: vi.fn().mockResolvedValue(who),
|
||||
listEvents: vi.fn().mockResolvedValue({ events: [], inboxCount: 0 }),
|
||||
listPhotos: vi.fn().mockResolvedValue({ photos: [], total: 0 }),
|
||||
absolute: (path: string) => path,
|
||||
groupRealEstate: vi.fn(async (_orgId: string, frames: BracketFrame[]) => groupBrackets(frames)),
|
||||
setRealEstate: vi.fn().mockResolvedValue({ enabled: true }),
|
||||
...overrides,
|
||||
} as unknown as ApiClient;
|
||||
}
|
||||
|
||||
const at = (ms: number) => new Date(Date.parse("2026-10-21T10:00:00.000Z") + ms).toISOString();
|
||||
|
||||
function shot(name: string, bias: number, ms: number): BracketFrame {
|
||||
return {
|
||||
id: name,
|
||||
fileName: name,
|
||||
capturedAt: at(ms),
|
||||
cameraSerial: "body",
|
||||
focalLength: 16,
|
||||
aperture: 8,
|
||||
iso: 100,
|
||||
exposureBias: bias,
|
||||
exposureTime: 0.01,
|
||||
};
|
||||
}
|
||||
|
||||
describe("real estate area", () => {
|
||||
beforeEach(() => {
|
||||
URL.createObjectURL = () => "blob:fused";
|
||||
URL.revokeObjectURL = () => undefined;
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
staged.frames.clear();
|
||||
window.history.pushState({}, "", "/");
|
||||
});
|
||||
|
||||
it("stays out of the menu until the organization turns it on", async () => {
|
||||
render(<App api={fakeApi(me("PHOTOGRAPHER", false))} />);
|
||||
expect(await screen.findByText(/Ainda não chegaram fotografias/)).toBeTruthy();
|
||||
expect(screen.queryByRole("link", { name: "Imobiliário" })).toBeNull();
|
||||
});
|
||||
|
||||
it("groups a dropped bracket and leaves the loose frame out", async () => {
|
||||
staged.frames.set("a.cr3", shot("a.cr3", -2, 0));
|
||||
staged.frames.set("b.cr3", shot("b.cr3", 0, 200));
|
||||
staged.frames.set("c.cr3", shot("c.cr3", 2, 400));
|
||||
staged.frames.set("solo.cr3", shot("solo.cr3", 0, 30_000));
|
||||
const api = fakeApi(me("PHOTOGRAPHER", true));
|
||||
render(<App api={api} />);
|
||||
await userEvent.click(await screen.findByRole("link", { name: "Imobiliário" }));
|
||||
const input = screen.getByLabelText("Escolher ficheiros");
|
||||
await userEvent.upload(input, [new File(["a"], "a.cr3"), new File(["b"], "b.cr3"), new File(["c"], "c.cr3"), new File(["s"], "solo.cr3")]);
|
||||
expect(await screen.findByText("1 ângulo")).toBeTruthy();
|
||||
expect(screen.getByText("Ângulo 1 · 3 exposições")).toBeTruthy();
|
||||
expect(await screen.findByRole("img", { name: "Ângulo 1 fundido" })).toBeTruthy();
|
||||
expect(screen.getByText("1 fotografia fica de fora")).toBeTruthy();
|
||||
expect(screen.getByText("solo.cr3 · 0 EV")).toBeTruthy();
|
||||
expect(api.groupRealEstate).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it("lets the owner show the area from preferences", async () => {
|
||||
window.history.pushState({}, "", "/preferences");
|
||||
const api = fakeApi(me("OWNER", false));
|
||||
render(<App api={api} />);
|
||||
await userEvent.click(await screen.findByRole("button", { name: "Ligar" }));
|
||||
expect(api.setRealEstate).toHaveBeenCalledWith("o1", true);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,274 @@
|
||||
import type { BracketFrame } from "@photoreport/metadata";
|
||||
import { ApiError, hasRole, type RealEstateGrouping } from "@photoreport/sdk";
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import { useAuth } from "../auth.js";
|
||||
import { t } from "../i18n.js";
|
||||
import { fuseBracket } from "../realestate/fuse.js";
|
||||
import { fillFromSidecar, pairKey, partitionBracketFiles, readBracketFile } from "../realestate/readFrame.js";
|
||||
import { PageHeader } from "./Shell.js";
|
||||
|
||||
const READ_AT_ONCE = 4;
|
||||
|
||||
/**
|
||||
* Interior brackets, separate from the sports library. The files stay on this computer. The server
|
||||
* only receives exposure metadata and says which frames belong to the same angle; the develop
|
||||
* engine merges each angle in the browser.
|
||||
*/
|
||||
export function RealEstatePage() {
|
||||
const { api, organization, role } = useAuth();
|
||||
const enabled = organization?.realEstateEnabled === true && role !== null && hasRole(role, "PHOTOGRAPHER");
|
||||
const [busy, setBusy] = useState(false);
|
||||
const busyRef = useRef(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [frames, setFrames] = useState<BracketFrame[]>([]);
|
||||
const [files, setFiles] = useState<Map<string, File>>(new Map());
|
||||
const [result, setResult] = useState<RealEstateGrouping | null>(null);
|
||||
const [progress, setProgress] = useState<{ done: number; total: number } | null>(null);
|
||||
const [support, setSupport] = useState(0);
|
||||
|
||||
const take = async (list: File[]) => {
|
||||
const split = partitionBracketFiles(list);
|
||||
if ((split.images.length === 0 && split.sidecars.length === 0 && split.other === 0) || busyRef.current || !organization) return;
|
||||
busyRef.current = true;
|
||||
setBusy(true);
|
||||
setError(null);
|
||||
setResult(null);
|
||||
setFrames([]);
|
||||
setFiles(new Map());
|
||||
setSupport(split.sidecars.length + split.other);
|
||||
setProgress({ done: 0, total: split.images.length + split.sidecars.length });
|
||||
try {
|
||||
if (split.images.length === 0) {
|
||||
setError(t.realEstate.noPhotos);
|
||||
return;
|
||||
}
|
||||
let done = 0;
|
||||
const total = split.images.length + split.sidecars.length;
|
||||
const readOne = async (file: File) => {
|
||||
try {
|
||||
return await readBracketFile(file);
|
||||
} finally {
|
||||
done += 1;
|
||||
setProgress({ done, total });
|
||||
}
|
||||
};
|
||||
const read = await mapPool(split.images, READ_AT_ONCE, readOne);
|
||||
const sidecars = await mapPool(split.sidecars, READ_AT_ONCE, readOne);
|
||||
const byKey = new Map(split.sidecars.map((file, index) => [pairKey(file.webkitRelativePath || file.name), sidecars[index]!]));
|
||||
const merged = read.map((frame, index) => {
|
||||
const image = split.images[index];
|
||||
const extra = image ? byKey.get(pairKey(image.webkitRelativePath || image.name)) : undefined;
|
||||
return extra ? fillFromSidecar(frame, extra) : frame;
|
||||
});
|
||||
setFrames(merged);
|
||||
const paired = new Map<string, File>();
|
||||
merged.forEach((frame, index) => {
|
||||
const file = split.images[index];
|
||||
if (file) paired.set(frame.id, file);
|
||||
});
|
||||
setFiles(paired);
|
||||
setResult(await api.groupRealEstate(organization.id, merged));
|
||||
} catch (err) {
|
||||
const code = err instanceof ApiError ? err.code : "";
|
||||
setError(t.realEstate.errors[code] ?? t.unexpectedError);
|
||||
} finally {
|
||||
busyRef.current = false;
|
||||
setBusy(false);
|
||||
setProgress(null);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<PageHeader title={t.realEstate.title} />
|
||||
<section className="max-w-3xl p-6">
|
||||
{!enabled ? (
|
||||
<p className="text-sm text-muted">{t.realEstate.disabled}</p>
|
||||
) : (
|
||||
<>
|
||||
<p className="text-sm text-muted">{t.realEstate.intro}</p>
|
||||
<p className="mt-2 text-sm text-muted">{t.realEstate.step}</p>
|
||||
<div
|
||||
className="mt-5 border border-dashed border-line bg-panel px-4 py-8 text-center"
|
||||
onDragOver={(event) => event.preventDefault()}
|
||||
onDrop={(event) => {
|
||||
event.preventDefault();
|
||||
void filesFromDrop(event.dataTransfer).then((files) => take(files));
|
||||
}}
|
||||
>
|
||||
<div className="flex flex-wrap items-center justify-center gap-3">
|
||||
<label className="inline-flex h-9 cursor-pointer items-center bg-accent px-4 font-display text-[15px] font-semibold uppercase tracking-wide text-white hover:bg-accent-strong">
|
||||
{t.realEstate.choose}
|
||||
<input
|
||||
aria-label={t.realEstate.choose}
|
||||
className="sr-only"
|
||||
type="file"
|
||||
multiple
|
||||
disabled={busy}
|
||||
onChange={(event) => {
|
||||
const list = event.target.files ? [...event.target.files] : [];
|
||||
event.target.value = "";
|
||||
void take(list);
|
||||
}}
|
||||
/>
|
||||
</label>
|
||||
<label className="inline-flex h-9 cursor-pointer items-center border border-line bg-panel px-4 font-display text-[15px] font-semibold uppercase tracking-wide text-ink hover:border-faint">
|
||||
{t.realEstate.chooseFolder}
|
||||
<input
|
||||
aria-label={t.realEstate.chooseFolder}
|
||||
className="sr-only"
|
||||
type="file"
|
||||
multiple
|
||||
disabled={busy}
|
||||
{...{ webkitdirectory: "", directory: "" }}
|
||||
onChange={(event) => {
|
||||
const list = event.target.files ? [...event.target.files] : [];
|
||||
event.target.value = "";
|
||||
void take(list);
|
||||
}}
|
||||
/>
|
||||
</label>
|
||||
</div>
|
||||
<p className="mt-3 text-[13px] text-faint">{t.realEstate.dropHint}</p>
|
||||
</div>
|
||||
{busy && progress && <p className="mt-4 text-sm text-muted">{t.realEstate.reading(progress.done, progress.total)}</p>}
|
||||
{error && <p className="mt-4 text-sm text-danger">{error}</p>}
|
||||
{support > 0 && <p className="mt-4 text-sm text-muted">{t.realEstate.support(support)}</p>}
|
||||
{result && <Grouping frames={frames} files={files} result={result} />}
|
||||
</>
|
||||
)}
|
||||
</section>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
function Grouping({ frames, files, result }: { frames: BracketFrame[]; files: Map<string, File>; result: RealEstateGrouping }) {
|
||||
const byId = new Map(frames.map((frame) => [frame.id, frame]));
|
||||
return (
|
||||
<div className="mt-6 space-y-4">
|
||||
<p className="text-sm text-ink">{t.realEstate.stacks(result.stacks.length)}</p>
|
||||
{result.stacks.length === 0 && <p className="text-sm text-muted">{t.realEstate.none}</p>}
|
||||
<ul className="space-y-3">
|
||||
{result.stacks.map((stack, index) => (
|
||||
<li key={`${index}-${stack.frameIds[0] ?? ""}`} className="border border-line bg-panel">
|
||||
<p className="border-b border-line px-3 py-2 text-[13px] font-semibold">{t.realEstate.angle(index + 1, stack.frameIds.length)}</p>
|
||||
<AnglePreview index={index} ids={stack.frameIds} files={files} />
|
||||
<ul className="px-3 py-2 text-[13px] text-muted">
|
||||
{stack.frameIds.map((id) => (
|
||||
<li key={id}>{line(byId.get(id), id)}</li>
|
||||
))}
|
||||
</ul>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
{result.aside.length > 0 && (
|
||||
<div>
|
||||
<p className="text-sm text-ink">{t.realEstate.aside(result.aside.length)}</p>
|
||||
<p className="mt-1 text-[13px] text-faint">{t.realEstate.asideHelp}</p>
|
||||
<ul className="mt-2 text-[13px] text-muted">
|
||||
{result.aside.slice(0, 12).map((id) => (
|
||||
<li key={id}>{line(byId.get(id), id)}</li>
|
||||
))}
|
||||
{result.aside.length > 12 && <li>{t.realEstate.asideMore(result.aside.length - 12)}</li>}
|
||||
</ul>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function AnglePreview({ index, ids, files }: { index: number; ids: string[]; files: Map<string, File> }) {
|
||||
const [url, setUrl] = useState<string | null>(null);
|
||||
const [failed, setFailed] = useState(false);
|
||||
const key = ids.join("\n");
|
||||
useEffect(() => {
|
||||
const stack = ids.map((id) => files.get(id)).filter((file): file is File => file instanceof File);
|
||||
if (stack.length < 2) {
|
||||
setFailed(true);
|
||||
return;
|
||||
}
|
||||
let cancelled = false;
|
||||
let objectUrl = "";
|
||||
setUrl(null);
|
||||
setFailed(false);
|
||||
fuseBracket(stack)
|
||||
.then((blob) => {
|
||||
if (cancelled) return;
|
||||
objectUrl = URL.createObjectURL(blob);
|
||||
setUrl(objectUrl);
|
||||
})
|
||||
.catch(() => {
|
||||
if (!cancelled) setFailed(true);
|
||||
});
|
||||
return () => {
|
||||
cancelled = true;
|
||||
if (objectUrl) URL.revokeObjectURL(objectUrl);
|
||||
};
|
||||
// `key` is the stack. `files` is replaced as a whole when a new folder is read.
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [key, files]);
|
||||
if (failed) return <p className="px-3 py-2 text-[13px] text-danger">{t.realEstate.fuseFailed}</p>;
|
||||
if (!url) return <p className="px-3 py-2 text-[13px] text-muted">{t.realEstate.fusing}</p>;
|
||||
return <img alt={t.realEstate.previewAlt(index + 1)} className="block w-full" src={url} />;
|
||||
}
|
||||
|
||||
function line(frame: BracketFrame | undefined, id: string): string {
|
||||
const name = frame?.fileName || id;
|
||||
return `${name} · ${exposureLabel(frame)}`;
|
||||
}
|
||||
|
||||
function exposureLabel(frame: BracketFrame | undefined): string {
|
||||
if (!frame || (frame.exposureBias == null && (frame.exposureTime == null || frame.exposureTime <= 0))) return t.realEstate.noExposure;
|
||||
if (frame.exposureBias == null) return t.realEstate.noBias;
|
||||
return formatBias(frame.exposureBias);
|
||||
}
|
||||
|
||||
function formatBias(value: number): string {
|
||||
const rounded = Math.round(value * 10) / 10;
|
||||
const text = Number.isInteger(rounded) ? String(rounded) : rounded.toFixed(1);
|
||||
if (rounded > 0) return t.realEstate.bias(`+${text}`);
|
||||
return t.realEstate.bias(text);
|
||||
}
|
||||
|
||||
async function mapPool<T, R>(items: readonly T[], limit: number, fn: (item: T) => Promise<R>): Promise<R[]> {
|
||||
const out: R[] = new Array(items.length);
|
||||
let next = 0;
|
||||
const workers = Array.from({ length: Math.min(limit, items.length) }, async () => {
|
||||
while (next < items.length) {
|
||||
const index = next;
|
||||
next += 1;
|
||||
out[index] = await fn(items[index]!);
|
||||
}
|
||||
});
|
||||
await Promise.all(workers);
|
||||
return out;
|
||||
}
|
||||
|
||||
async function filesFromDrop(data: DataTransfer): Promise<File[]> {
|
||||
const entries: FileSystemEntry[] = [];
|
||||
for (const item of data.items) {
|
||||
const entry = item.webkitGetAsEntry?.();
|
||||
if (entry) entries.push(entry);
|
||||
}
|
||||
if (entries.length === 0) return [...data.files];
|
||||
const nested = await Promise.all(entries.map((entry) => filesInEntry(entry)));
|
||||
return nested.flat();
|
||||
}
|
||||
|
||||
async function filesInEntry(entry: FileSystemEntry): Promise<File[]> {
|
||||
if (entry.name.startsWith(".")) return [];
|
||||
if (entry.isFile) {
|
||||
const file = await new Promise<File>((resolve, reject) => (entry as FileSystemFileEntry).file(resolve, reject));
|
||||
return file.name.startsWith(".") ? [] : [file];
|
||||
}
|
||||
if (!entry.isDirectory) return [];
|
||||
const reader = (entry as FileSystemDirectoryEntry).createReader();
|
||||
const children: FileSystemEntry[] = [];
|
||||
for (;;) {
|
||||
const batch = await new Promise<FileSystemEntry[]>((resolve, reject) => reader.readEntries(resolve, reject));
|
||||
if (batch.length === 0) break;
|
||||
children.push(...batch);
|
||||
}
|
||||
const nested = await Promise.all(children.map((child) => filesInEntry(child)));
|
||||
return nested.flat();
|
||||
}
|
||||
@@ -111,6 +111,16 @@ export function Shell() {
|
||||
</NavLink>
|
||||
</>
|
||||
)}
|
||||
{organization?.realEstateEnabled === true && role !== null && hasRole(role, "PHOTOGRAPHER") && (
|
||||
<>
|
||||
<span aria-hidden="true" className="text-[#3a3a3a]">
|
||||
|
|
||||
</span>
|
||||
<NavLink to="/real-estate" className={moduleClass}>
|
||||
{t.realEstate.nav}
|
||||
</NavLink>
|
||||
</>
|
||||
)}
|
||||
</nav>
|
||||
|
||||
<Bell />
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
import { loadEngine } from "../develop/engine.js";
|
||||
|
||||
/** Long side of each frame. The engine bins a raw mosaic down to this instead of demosaicing it whole. */
|
||||
const PREVIEW_EDGE = 1024;
|
||||
|
||||
/**
|
||||
* Merge one angle with the develop engine (LightCraft's HDR merge) and return a JPEG preview.
|
||||
* The files stay in this browser; nothing is uploaded.
|
||||
*/
|
||||
export async function fuseBracket(files: File[]): Promise<Blob> {
|
||||
const engine = await loadEngine();
|
||||
const job = new engine.BracketJob();
|
||||
try {
|
||||
for (const file of files) {
|
||||
job.push(new Uint8Array(await file.arrayBuffer()));
|
||||
}
|
||||
const merged = job.merge(PREVIEW_EDGE);
|
||||
try {
|
||||
const jpeg = new Uint8Array(merged.jpeg());
|
||||
return new Blob([jpeg], { type: "image/jpeg" });
|
||||
} finally {
|
||||
merged.free();
|
||||
}
|
||||
} finally {
|
||||
job.free();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { bracketFileRole, fileStem, fillFromSidecar, frameFromCapture, pairKey, partitionBracketFiles, readBracketFile } from "./readFrame.js";
|
||||
|
||||
describe("frameFromCapture", () => {
|
||||
it("reads the engine's capture JSON, including a zero compensation", () => {
|
||||
const frame = frameFromCapture("id", "IMG_0001.CR3", {
|
||||
cameraMake: "Canon",
|
||||
cameraModel: "EOS R5",
|
||||
cameraSerial: "123",
|
||||
focalLength: 16,
|
||||
aperture: 8,
|
||||
iso: 100,
|
||||
width: 8192,
|
||||
height: 5464,
|
||||
exposureBias: 0,
|
||||
exposureTime: 0.01,
|
||||
capturedAt: "2026-10-21T10:00:00",
|
||||
});
|
||||
expect(frame).toMatchObject({
|
||||
id: "id",
|
||||
fileName: "IMG_0001.CR3",
|
||||
cameraMake: "Canon",
|
||||
cameraModel: "EOS R5",
|
||||
cameraSerial: "123",
|
||||
focalLength: 16,
|
||||
aperture: 8,
|
||||
iso: 100,
|
||||
width: 8192,
|
||||
height: 5464,
|
||||
exposureBias: 0,
|
||||
exposureTime: 0.01,
|
||||
capturedAt: "2026-10-21T10:00:00",
|
||||
});
|
||||
});
|
||||
|
||||
it("keeps the name when the file has no header", () => {
|
||||
expect(frameFromCapture("id", "IMG_0002.CR3", undefined)).toEqual({ id: "id", fileName: "IMG_0002.CR3" });
|
||||
});
|
||||
});
|
||||
|
||||
describe("bracket files", () => {
|
||||
it("treats an XMP next to a CR3 as a sidecar, not a photo", () => {
|
||||
expect(bracketFileRole("PSR10071.CR3")).toBe("image");
|
||||
expect(bracketFileRole("PSR10071.XMP")).toBe("sidecar");
|
||||
expect(bracketFileRole("notes.txt")).toBe("other");
|
||||
expect(fileStem("folder/PSR10071.XMP")).toBe("psr10071");
|
||||
expect(pairKey("Imovel/PSR10071.CR3")).toBe(pairKey("Imovel/PSR10071.XMP"));
|
||||
expect(pairKey("Sala/PSR10071.CR3")).not.toBe(pairKey("Quarto/PSR10071.CR3"));
|
||||
const cr3 = new File(["r"], "PSR10071.CR3");
|
||||
const xmp = new File(["x"], "PSR10071.XMP");
|
||||
const note = new File(["n"], "notes.txt");
|
||||
const split = partitionBracketFiles([cr3, xmp, note]);
|
||||
expect(split.images).toEqual([cr3]);
|
||||
expect(split.sidecars).toEqual([xmp]);
|
||||
expect(split.other).toBe(1);
|
||||
});
|
||||
|
||||
it("lets the sidecar fill an exposure the raw did not carry", () => {
|
||||
const raw = frameFromCapture("raw", "PSR10071.CR3", { cameraMake: "Canon", exposureTime: 0.01 });
|
||||
const side = frameFromCapture("side", "PSR10071.XMP", { cameraMake: "Other", exposureBias: -2, exposureTime: 0.5 });
|
||||
expect(fillFromSidecar(raw, side)).toMatchObject({ cameraMake: "Canon", exposureBias: -2, exposureTime: 0.01 });
|
||||
});
|
||||
|
||||
it("uses the reader it is given", async () => {
|
||||
const file = new File(["raw"], "PSR10071.CR3");
|
||||
const frame = await readBracketFile(file, () => JSON.stringify({ exposureBias: -2, exposureTime: 1 / 125 }));
|
||||
expect(frame.fileName).toBe("PSR10071.CR3");
|
||||
expect(frame.exposureBias).toBe(-2);
|
||||
expect(frame.exposureTime).toBeCloseTo(0.008);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,154 @@
|
||||
import type { BracketFrame } from "@photoreport/metadata";
|
||||
import { loadEngine } from "../develop/engine.js";
|
||||
|
||||
/**
|
||||
* How a dropped file participates in a bracket. Sidecars are not frames: an XMP next to a raw only
|
||||
* fills exposure the raw itself did not carry. Anything else (notes, previews) is ignored.
|
||||
*/
|
||||
export type BracketFileRole = "image" | "sidecar" | "other";
|
||||
|
||||
const IMAGE_EXTENSIONS = new Set([
|
||||
"cr2",
|
||||
"cr3",
|
||||
"crw",
|
||||
"nef",
|
||||
"nrw",
|
||||
"arw",
|
||||
"srf",
|
||||
"sr2",
|
||||
"raf",
|
||||
"orf",
|
||||
"rw2",
|
||||
"pef",
|
||||
"srw",
|
||||
"x3f",
|
||||
"3fr",
|
||||
"iiq",
|
||||
"erf",
|
||||
"kdc",
|
||||
"mrw",
|
||||
"dng",
|
||||
"raw",
|
||||
"jpg",
|
||||
"jpeg",
|
||||
"tif",
|
||||
"tiff",
|
||||
"png",
|
||||
"webp",
|
||||
"heic",
|
||||
"heif",
|
||||
]);
|
||||
|
||||
export function fileStem(name: string): string {
|
||||
const base = name.split(/[/\\]/).pop() ?? name;
|
||||
const dot = base.lastIndexOf(".");
|
||||
return (dot <= 0 ? base : base.slice(0, dot)).toLowerCase();
|
||||
}
|
||||
|
||||
/** Same folder and stem, so `Imovel/PSR10071.CR3` pairs with `Imovel/PSR10071.XMP`. */
|
||||
export function pairKey(name: string): string {
|
||||
const normalized = name.replaceAll("\\", "/");
|
||||
const slash = normalized.lastIndexOf("/");
|
||||
const dir = slash < 0 ? "" : normalized.slice(0, slash).toLowerCase();
|
||||
return `${dir}/${fileStem(normalized)}`;
|
||||
}
|
||||
|
||||
export function bracketFileRole(name: string): BracketFileRole {
|
||||
const base = name.split(/[/\\]/).pop() ?? name;
|
||||
if (base === "" || base.startsWith(".")) return "other";
|
||||
const dot = base.lastIndexOf(".");
|
||||
const ext = dot <= 0 ? "" : base.slice(dot + 1).toLowerCase();
|
||||
if (ext === "xmp") return "sidecar";
|
||||
if (IMAGE_EXTENSIONS.has(ext)) return "image";
|
||||
return "other";
|
||||
}
|
||||
|
||||
export function partitionBracketFiles(files: readonly File[]): { images: File[]; sidecars: File[]; other: number } {
|
||||
const images: File[] = [];
|
||||
const sidecars: File[] = [];
|
||||
let other = 0;
|
||||
for (const file of files) {
|
||||
const name = file.webkitRelativePath || file.name;
|
||||
const role = bracketFileRole(name);
|
||||
if (role === "image") images.push(file);
|
||||
else if (role === "sidecar") sidecars.push(file);
|
||||
else other += 1;
|
||||
}
|
||||
return { images, sidecars, other };
|
||||
}
|
||||
|
||||
/**
|
||||
* Fills only the fields the raw left empty. The camera's own header wins over the sidecar.
|
||||
*/
|
||||
export function fillFromSidecar(frame: BracketFrame, extra: BracketFrame): BracketFrame {
|
||||
const next: BracketFrame = { ...frame };
|
||||
if (next.capturedAt == null && extra.capturedAt != null) next.capturedAt = extra.capturedAt;
|
||||
if (next.cameraSerial == null && extra.cameraSerial != null) next.cameraSerial = extra.cameraSerial;
|
||||
if (next.cameraMake == null && extra.cameraMake != null) next.cameraMake = extra.cameraMake;
|
||||
if (next.cameraModel == null && extra.cameraModel != null) next.cameraModel = extra.cameraModel;
|
||||
if (next.focalLength == null && extra.focalLength != null) next.focalLength = extra.focalLength;
|
||||
if (next.aperture == null && extra.aperture != null) next.aperture = extra.aperture;
|
||||
if (next.iso == null && extra.iso != null) next.iso = extra.iso;
|
||||
if (next.width == null && extra.width != null) next.width = extra.width;
|
||||
if (next.height == null && extra.height != null) next.height = extra.height;
|
||||
if (next.exposureBias == null && extra.exposureBias != null) next.exposureBias = extra.exposureBias;
|
||||
if (next.exposureTime == null && extra.exposureTime != null) next.exposureTime = extra.exposureTime;
|
||||
return next;
|
||||
}
|
||||
|
||||
export function frameFromCapture(id: string, fileName: string, tags: Record<string, unknown> | undefined): BracketFrame {
|
||||
const frame: BracketFrame = { id, fileName };
|
||||
if (!tags) return frame;
|
||||
const captured = text(tags.capturedAt);
|
||||
if (captured && Number.isFinite(Date.parse(captured))) frame.capturedAt = captured;
|
||||
const serial = text(tags.cameraSerial);
|
||||
if (serial) frame.cameraSerial = serial;
|
||||
const make = text(tags.cameraMake);
|
||||
if (make) frame.cameraMake = make;
|
||||
const model = text(tags.cameraModel);
|
||||
if (model) frame.cameraModel = model;
|
||||
const focal = num(tags.focalLength);
|
||||
if (focal !== null && focal > 0) frame.focalLength = focal;
|
||||
const aperture = num(tags.aperture);
|
||||
if (aperture !== null && aperture > 0) frame.aperture = aperture;
|
||||
const iso = num(tags.iso);
|
||||
if (iso !== null && iso > 0) frame.iso = Math.round(iso);
|
||||
const width = num(tags.width);
|
||||
if (width !== null && width > 0) frame.width = Math.round(width);
|
||||
const height = num(tags.height);
|
||||
if (height !== null && height > 0) frame.height = Math.round(height);
|
||||
const bias = num(tags.exposureBias);
|
||||
if (bias !== null) frame.exposureBias = bias;
|
||||
const time = num(tags.exposureTime);
|
||||
if (time !== null && time > 0) frame.exposureTime = time;
|
||||
return frame;
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads capture metadata with the develop engine (LightCraft). The bytes stay in this browser.
|
||||
* A file the engine cannot read still comes back, with nothing but its name, so the grouper sets it aside.
|
||||
* `readMeta` is the engine's `readCaptureMeta`; tests pass their own.
|
||||
*/
|
||||
export async function readBracketFile(file: File, readMeta?: (bytes: Uint8Array) => string | Promise<string>): Promise<BracketFrame> {
|
||||
const name = file.webkitRelativePath || file.name;
|
||||
const id = `${name}\u0000${file.size}\u0000${file.lastModified}`;
|
||||
try {
|
||||
const bytes = new Uint8Array(await file.arrayBuffer());
|
||||
const json = readMeta ? await readMeta(bytes) : (await loadEngine()).readCaptureMeta(bytes);
|
||||
const tags = JSON.parse(json) as Record<string, unknown>;
|
||||
return frameFromCapture(id, file.name, tags);
|
||||
} catch {
|
||||
return { id, fileName: file.name };
|
||||
}
|
||||
}
|
||||
|
||||
function num(value: unknown): number | null {
|
||||
if (typeof value === "number" && Number.isFinite(value)) return value;
|
||||
return null;
|
||||
}
|
||||
|
||||
function text(value: unknown): string | null {
|
||||
if (typeof value !== "string") return null;
|
||||
const trimmed = value.trim();
|
||||
return trimmed === "" ? null : trimmed;
|
||||
}
|
||||
@@ -31,6 +31,8 @@ sha2 = "0.10"
|
||||
libc = "0.2"
|
||||
image = { version = "0.25", default-features = false, features = ["jpeg"] }
|
||||
photoreport-faces = { path = "../../../workers/faces" }
|
||||
# Capture time (EXIF / IPTC / XMP, including CR3) comes from the engine's LightCraft reader.
|
||||
photoreport-engine = { path = "../../../engine/core" }
|
||||
tauri-plugin-dialog = "2"
|
||||
tauri-plugin-updater = "2"
|
||||
# New versions of the interface (see src/ui.rs). Already built for the updater: same versions, no new crates.
|
||||
|
||||
@@ -164,14 +164,29 @@ fn sibling_jpeg(path: &Path) -> Option<PathBuf> {
|
||||
None
|
||||
}
|
||||
|
||||
/// The capture day of a photo: EXIF DateTimeOriginal when it can be read (a JPEG, or a RAW's paired JPEG), else
|
||||
/// the file's modification time — on a card straight from the camera that is when the frame was shot. RAW-only
|
||||
/// formats with no EXIF reader yet (e.g. CR3) fall back to the modification time.
|
||||
/// Year, month, day from the engine's capture clock (`YYYY-MM-DD...`), when the file recorded one.
|
||||
fn ymd_from_capture(bytes: &[u8]) -> Option<(i32, u32, u32)> {
|
||||
let value = photoreport_engine::capture::read_capture(bytes);
|
||||
let text = value.get("capturedAt")?.as_str()?;
|
||||
let year: i32 = text.get(0..4)?.parse().ok()?;
|
||||
let month: u32 = text.get(5..7)?.parse().ok()?;
|
||||
let day: u32 = text.get(8..10)?.parse().ok()?;
|
||||
if (1..=12).contains(&month) && (1..=31).contains(&day) && year > 1900 {
|
||||
Some((year, month, day))
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
/// The capture day of a photo. LightCraft reads EXIF, then IPTC, then XMP, including a CR3 with no JPEG
|
||||
/// beside it. A JPEG whose header the engine cannot read still tries the short EXIF scan. Otherwise the
|
||||
/// file's modification time — on a card straight from the camera that is when the frame was shot.
|
||||
fn capture_day(path: &Path, ext: &str) -> chrono::DateTime<Local> {
|
||||
let from_engine = || std::fs::read(path).ok().and_then(|bytes| ymd_from_capture(&bytes));
|
||||
let ymd = if is_jpeg(ext) {
|
||||
crate::preview::exif_date(&read_head(path))
|
||||
} else if is_raw(ext) {
|
||||
sibling_jpeg(path).and_then(|j| crate::preview::exif_date(&read_head(&j)))
|
||||
from_engine().or_else(|| crate::preview::exif_date(&read_head(path)))
|
||||
} else if is_image(ext) {
|
||||
from_engine().or_else(|| sibling_jpeg(path).and_then(|j| crate::preview::exif_date(&read_head(&j))))
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
@@ -380,7 +380,7 @@ export function Gallery({
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
{playing !== null && videos[playing] && <VideoPlayer videos={videos} index={playing} onIndex={setPlaying} />}
|
||||
{playing !== null && videos[playing] && <VideoPlayer videos={videos} index={playing} onIndex={setPlaying} onPerson={onPerson} />}
|
||||
{index !== null && photos[index] && (
|
||||
<Lightbox
|
||||
photos={photos}
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
"use client";
|
||||
|
||||
import { useCallback, useEffect, useMemo, useState } from "react";
|
||||
import { cached, call, day, download, forget, Forbidden, LEVEL, Unauthorised, type Level, type Me, type PersonHistory, type PhotoFace, type PhotosOfResult } from "./api";
|
||||
import { cached, call, day, download, duration, forget, Forbidden, LEVEL, Unauthorised, type ArchiveVideo, type Level, type Me, type PersonHistory, type PhotoFace, type PhotosOfResult } from "./api";
|
||||
import { Lightbox } from "./Lightbox";
|
||||
import { FaceCrop, Icon, Loading, PersonFace } from "./parts";
|
||||
import { VideoPlayer } from "./VideoPlayer";
|
||||
|
||||
/** A person's photos, or the photos of a face clicked in a photo, with how sure each one is. */
|
||||
export function PhotosOf({
|
||||
@@ -32,6 +33,8 @@ export function PhotosOf({
|
||||
const [data, setData] = useState<PhotosOfResult | null>(null);
|
||||
const [only, setOnly] = useState<Level | null>(null);
|
||||
const [index, setIndex] = useState<number | null>(null);
|
||||
/** A video open in the player, at one of the person's moments. */
|
||||
const [playing, setPlaying] = useState<{ index: number; at: number } | null>(null);
|
||||
const [error, setError] = useState(false);
|
||||
const [attempt, setAttempt] = useState(0);
|
||||
|
||||
@@ -52,6 +55,24 @@ export function PhotosOf({
|
||||
}, [sourceId, view.kind, view.id, token, onExpired, attempt]);
|
||||
|
||||
const photos = useMemo(() => (data ? (only ? data.photos.filter((p) => p.level === only) : data.photos) : []), [data, only]);
|
||||
// Their videos, as the player takes them (who else appears is in each gallery; here, when they do).
|
||||
const videos: ArchiveVideo[] = useMemo(
|
||||
() =>
|
||||
(data?.videos ?? []).map((v) => ({
|
||||
id: v.id,
|
||||
name: v.name,
|
||||
durationMs: v.durationMs,
|
||||
width: v.width,
|
||||
height: v.height,
|
||||
capturedAt: null,
|
||||
thumb: v.thumb,
|
||||
poster: v.poster,
|
||||
src: v.src,
|
||||
download: v.download,
|
||||
people: data?.person ? [{ id: data.person.id, name: data.person.name, level: v.level, startMs: v.moments[0]?.startMs ?? 0, moments: v.moments }] : [],
|
||||
})),
|
||||
[data],
|
||||
);
|
||||
const counts = useMemo(() => {
|
||||
const c: Record<Level, number> = { confirmed: 0, probable: 0, similar: 0 };
|
||||
for (const p of data?.photos ?? []) if (p.level) c[p.level]++;
|
||||
@@ -159,7 +180,43 @@ export function PhotosOf({
|
||||
))}
|
||||
</div>
|
||||
{counts.similar > 0 && <p className="arq-muted" style={{ margin: 0 }}>“Parecido” são caras semelhantes que ainda ninguém identificou: confirma antes de publicar.</p>}
|
||||
{photos.length === 0 && <p className="arq-empty">Sem fotos.</p>}
|
||||
{videos.length > 0 && (
|
||||
<section className="arq-videos" aria-label="Vídeos">
|
||||
<h2 className="arq-label">Vídeos</h2>
|
||||
<div className="arq-person-videos">
|
||||
{data!.videos!.map((v, i) => (
|
||||
<article key={v.id} className="arq-person-video">
|
||||
<button type="button" className="arq-video-tile" onClick={() => setPlaying({ index: i, at: v.moments[0]?.startMs ?? 0 })} aria-label={`Ver ${v.name}`}>
|
||||
<img src={v.thumb} alt="" loading="lazy" decoding="async" />
|
||||
<span className="arq-video-play" aria-hidden="true">
|
||||
<Icon name="play" size={22} />
|
||||
</span>
|
||||
{v.durationMs ? <span className="arq-video-time">{duration(v.durationMs)}</span> : null}
|
||||
</button>
|
||||
<div className="arq-person-video-head">
|
||||
<FaceCrop src={v.face.src} box={v.face.box} aspect={v.face.aspect} size={44} />
|
||||
<span>
|
||||
<strong>{v.gallery?.title ?? v.name}</strong>
|
||||
<small>
|
||||
<span className={`arq-badge ${v.level === "confirmed" ? "ok" : "maybe"}`}>{LEVEL[v.level]}</span>{" "}
|
||||
{[v.gallery?.startsAt ? day.format(new Date(v.gallery.startsAt)) : null, v.name].filter(Boolean).join(" · ")}
|
||||
</small>
|
||||
</span>
|
||||
</div>
|
||||
<span className="arq-video-moments" aria-label="Momentos">
|
||||
{v.moments.map((m, j) => (
|
||||
<button key={`${m.startMs}-${j}`} type="button" className="arq-chip" onClick={() => setPlaying({ index: i, at: m.startMs })}>
|
||||
{duration(m.startMs) || "0:00"}
|
||||
</button>
|
||||
))}
|
||||
</span>
|
||||
</article>
|
||||
))}
|
||||
</div>
|
||||
{photos.length > 0 && <h2 className="arq-label">Fotos</h2>}
|
||||
</section>
|
||||
)}
|
||||
{photos.length === 0 && videos.length === 0 && <p className="arq-empty">Sem fotos.</p>}
|
||||
<div className="arq-grid">
|
||||
{photos.map((p, i) => (
|
||||
<button key={p.id} type="button" className="arq-tile" onClick={() => setIndex(i)} aria-label={p.gallery?.title ?? p.name}>
|
||||
@@ -179,6 +236,9 @@ export function PhotosOf({
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
{playing !== null && videos[playing.index] && (
|
||||
<VideoPlayer videos={videos} index={playing.index} startAt={playing.at} onIndex={(i) => setPlaying(i === null ? null : { index: i, at: 0 })} onPerson={onPerson} />
|
||||
)}
|
||||
{index !== null && photos[index] && (
|
||||
<Lightbox
|
||||
photos={photos}
|
||||
|
||||
@@ -376,6 +376,7 @@ function Card({
|
||||
const who = g.person ?? g.suggested;
|
||||
const faces = groups.flatMap((item) => item.faces);
|
||||
const photos = groups.reduce((n, item) => n + item.photos, 0);
|
||||
const videos = groups.reduce((n, item) => n + (item.videos ?? 0), 0);
|
||||
const [open, setOpen] = useState<number | null>(null);
|
||||
const [first, ...rest] = faces;
|
||||
const onKey = (e: React.KeyboardEvent) => {
|
||||
@@ -407,7 +408,7 @@ function Card({
|
||||
<div className="arq-rbody">
|
||||
<strong>{who ? who.name : "Sem nome"}</strong>
|
||||
<small>
|
||||
{[who?.number && `nº ${who.number}`, who?.club, `${photos} ${photos === 1 ? "foto" : "fotos"}`, groups.length > 1 ? `${groups.length} jogos` : null].filter(Boolean).join(" · ")}
|
||||
{[who?.number && `nº ${who.number}`, who?.club, photos || !videos ? `${photos} ${photos === 1 ? "foto" : "fotos"}` : null, videos ? `${videos} ${videos === 1 ? "vídeo" : "vídeos"}` : null, groups.length > 1 ? `${groups.length} jogos` : null].filter(Boolean).join(" · ")}
|
||||
</small>
|
||||
{groups.length === 1 && g.event && <small>{[g.event.title, g.event.startsAt ? shortDay.format(new Date(g.event.startsAt)) : null].filter(Boolean).join(" · ")}</small>}
|
||||
{groups.length > 1 && (
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useRef } from "react";
|
||||
import { duration, shortDay, type ArchiveVideo } from "./api";
|
||||
import { duration, LEVEL, shortDay, type ArchiveVideo } from "./api";
|
||||
import { Icon } from "./parts";
|
||||
import "./video.css";
|
||||
|
||||
@@ -10,9 +10,29 @@ import "./video.css";
|
||||
* arrived, and jumps anywhere), the arrows go to the gallery's other videos. Every viewer saves it at web size;
|
||||
* those who edit the folder on the cloud also get the link to the original there.
|
||||
*/
|
||||
export function VideoPlayer({ videos, index, onIndex }: { videos: ArchiveVideo[]; index: number; onIndex: (i: number | null) => void }) {
|
||||
export function VideoPlayer({
|
||||
videos,
|
||||
index,
|
||||
onIndex,
|
||||
startAt,
|
||||
onPerson,
|
||||
}: {
|
||||
videos: ArchiveVideo[];
|
||||
index: number;
|
||||
onIndex: (i: number | null) => void;
|
||||
/** Where to start the first video (ms): a person's moment in it. */
|
||||
startAt?: number | undefined;
|
||||
onPerson?: ((personId: string) => void) | undefined;
|
||||
}) {
|
||||
const current = videos[index]!;
|
||||
const player = useRef<HTMLVideoElement>(null);
|
||||
const opened = useRef(index);
|
||||
const jump = (ms: number) => {
|
||||
const v = player.current;
|
||||
if (!v) return;
|
||||
v.currentTime = ms / 1000;
|
||||
void v.play().catch(() => undefined);
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
const onKey = (e: KeyboardEvent) => {
|
||||
@@ -61,7 +81,21 @@ export function VideoPlayer({ videos, index, onIndex }: { videos: ArchiveVideo[]
|
||||
<div className="arq-stage">
|
||||
<div className="arq-video-frame" style={{ aspectRatio: String(aspect), width: `min(100%, calc((100dvh - 96px) * ${aspect}))` }}>
|
||||
{/* key: a new element per video, so the next one starts from its beginning with its own poster. */}
|
||||
<video key={current.id} ref={player} src={current.src} poster={current.poster} controls autoPlay playsInline preload="metadata" />
|
||||
<video
|
||||
key={current.id}
|
||||
ref={player}
|
||||
src={current.src}
|
||||
poster={current.poster}
|
||||
controls
|
||||
autoPlay
|
||||
playsInline
|
||||
preload="metadata"
|
||||
onLoadedMetadata={(e) => {
|
||||
// Opened at someone's moment: there, once.
|
||||
if (startAt && opened.current === index) e.currentTarget.currentTime = startAt / 1000;
|
||||
opened.current = -1;
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
{index > 0 && (
|
||||
<button type="button" className="arq-arrow prev" onClick={() => onIndex(index - 1)} aria-label="Vídeo anterior">
|
||||
@@ -75,6 +109,34 @@ export function VideoPlayer({ videos, index, onIndex }: { videos: ArchiveVideo[]
|
||||
)}
|
||||
</div>
|
||||
<aside className="arq-info">
|
||||
{current.people && current.people.length > 0 && (
|
||||
<>
|
||||
<span className="arq-label">Quem aparece</span>
|
||||
<ul className="arq-video-people">
|
||||
{current.people.map((p) => (
|
||||
<li key={p.id}>
|
||||
<span className="arq-video-who">
|
||||
{onPerson ? (
|
||||
<button type="button" className="arq-link" onClick={() => onPerson(p.id)}>
|
||||
{p.name}
|
||||
</button>
|
||||
) : (
|
||||
<strong>{p.name}</strong>
|
||||
)}
|
||||
<small>{p.level === "confirmed" ? LEVEL.confirmed : `${LEVEL.probable}: confirma antes de usar`}</small>
|
||||
</span>
|
||||
<span className="arq-video-moments">
|
||||
{p.moments.map((m, i) => (
|
||||
<button key={`${m.startMs}-${i}`} type="button" className="arq-chip" onClick={() => jump(m.startMs)} aria-label={`Ver ${p.name} aos ${duration(m.startMs) || "0:00"}`}>
|
||||
{duration(m.startMs) || "0:00"}
|
||||
</button>
|
||||
))}
|
||||
</span>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</>
|
||||
)}
|
||||
{current.durationMs ? (
|
||||
<>
|
||||
<span className="arq-label">Duração</span>
|
||||
|
||||
@@ -50,6 +50,38 @@ export interface ArchiveVideo {
|
||||
download: string;
|
||||
/** Only for those who edit this folder on the cloud: the original is there. */
|
||||
cloudUrl?: string;
|
||||
/** Who appears in it (named, or probable) and when: the player jumps to them. */
|
||||
people?: VideoPerson[];
|
||||
}
|
||||
|
||||
export interface VideoMoment {
|
||||
startMs: number;
|
||||
endMs: number;
|
||||
}
|
||||
|
||||
export interface VideoPerson {
|
||||
id: string;
|
||||
name: string;
|
||||
level: "confirmed" | "probable";
|
||||
startMs: number;
|
||||
moments: VideoMoment[];
|
||||
}
|
||||
|
||||
/** A video a person appears in (their page): its clearest frame of them, and every moment. */
|
||||
export interface PersonVideo {
|
||||
id: string;
|
||||
name: string;
|
||||
level: "confirmed" | "probable";
|
||||
durationMs: number | null;
|
||||
width: number | null;
|
||||
height: number | null;
|
||||
face: FaceRef;
|
||||
moments: VideoMoment[];
|
||||
thumb: string;
|
||||
poster: string;
|
||||
src: string;
|
||||
download: string;
|
||||
gallery: { id: string; title: string; startsAt: string | null; competition: string | null } | null;
|
||||
}
|
||||
|
||||
export interface PhotoFace {
|
||||
@@ -163,6 +195,8 @@ export interface PhotosOfResult {
|
||||
suggestion?: { id: string; name: string; club: string | null } | null;
|
||||
counts?: Record<Level, number>;
|
||||
photos: ArchivePhoto[];
|
||||
/** The videos they appear in (a person's page). */
|
||||
videos?: PersonVideo[];
|
||||
}
|
||||
|
||||
/** What this viewer may do, from their rights on the cloud. */
|
||||
@@ -191,13 +225,16 @@ export interface ReviewGroup {
|
||||
id: string;
|
||||
size: number;
|
||||
photos: number;
|
||||
/** Videos the group appears in. */
|
||||
videos?: number;
|
||||
score: number | null;
|
||||
person: ReviewPerson | null;
|
||||
suggested: ReviewPerson | null;
|
||||
ignored: boolean;
|
||||
notThem: { id: string; name: string; by: string }[];
|
||||
event: { title: string; startsAt: string | null } | null;
|
||||
faces: { id: string; photoId: string; src: string; box: Box | null; aspect: number }[];
|
||||
/** A photo's face, or an appearance in a video (its clearest frame, and when). */
|
||||
faces: { id: string; photoId: string | null; video?: { id: string; atMs: number }; src: string; box: Box | null; aspect: number }[];
|
||||
}
|
||||
|
||||
export interface ReviewResult {
|
||||
|
||||
@@ -102,3 +102,104 @@
|
||||
border-radius: 4px;
|
||||
}
|
||||
}
|
||||
|
||||
/* Who appears in a video, with a button per moment to jump there. */
|
||||
.arq-video-people {
|
||||
list-style: none;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 10px;
|
||||
}
|
||||
.arq-video-people li {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 6px;
|
||||
}
|
||||
.arq-video-who {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 2px;
|
||||
}
|
||||
.arq-video-who small {
|
||||
color: #9aa0ac;
|
||||
font-size: 12px;
|
||||
}
|
||||
.arq-video-moments {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 6px;
|
||||
}
|
||||
.arq-chip {
|
||||
min-height: 32px;
|
||||
padding: 4px 10px;
|
||||
border: 0;
|
||||
border-radius: 999px;
|
||||
background: rgba(255, 255, 255, 0.12);
|
||||
color: #ffffff;
|
||||
font-size: 13px;
|
||||
font-weight: 700;
|
||||
font-variant-numeric: tabular-nums;
|
||||
cursor: pointer;
|
||||
}
|
||||
.arq-chip:hover,
|
||||
.arq-chip:focus-visible {
|
||||
background: rgba(255, 255, 255, 0.22);
|
||||
}
|
||||
.arq-lightbox .arq-video-people .arq-link {
|
||||
align-self: flex-start;
|
||||
color: #ffffff;
|
||||
font-weight: 700;
|
||||
text-align: left;
|
||||
}
|
||||
|
||||
/* A person's page: the videos they appear in. */
|
||||
.arq-person-videos {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fill, minmax(260px, 1fr));
|
||||
gap: 12px;
|
||||
margin-bottom: 20px;
|
||||
}
|
||||
.arq-person-video {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 8px;
|
||||
padding: 10px;
|
||||
border-radius: var(--r);
|
||||
background: var(--card);
|
||||
box-shadow: 0 0 0 1px var(--line);
|
||||
}
|
||||
.arq-person-video .arq-video-tile {
|
||||
aspect-ratio: 16 / 9;
|
||||
}
|
||||
.arq-person-video-head {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
min-width: 0;
|
||||
}
|
||||
.arq-person-video-head > span {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
min-width: 0;
|
||||
}
|
||||
.arq-person-video-head strong,
|
||||
.arq-person-video-head small {
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.arq-person-video-head small {
|
||||
color: var(--muted);
|
||||
font-size: 12px;
|
||||
}
|
||||
.arq-person-video .arq-chip {
|
||||
background: var(--chip);
|
||||
color: var(--chip-ink);
|
||||
}
|
||||
.arq-person-video .arq-chip:hover,
|
||||
.arq-person-video .arq-chip:focus-visible {
|
||||
background: var(--chip-on);
|
||||
color: var(--chip-on-ink);
|
||||
}
|
||||
+2
-1
@@ -65,7 +65,8 @@ Gitea -> webhook -> the container pulls and redeploys itself. No manual `scp`/`r
|
||||
set `STORAGE_ROOT`, `INGEST_ROOT` and `DELIVERY_SECRET_KEY` (`openssl rand -base64 32`, the same value
|
||||
wherever the worker or API runs). The worker needs `perl` (ExifTool) and `ffmpeg` for the archive's videos
|
||||
(`apt install ffmpeg`; without it each API deploy puts a static build in `~/.local/ffmpeg`, which the worker finds;
|
||||
with neither, videos wait as FAILED "ffprobe_missing" and "Analisar agora" retries them). On the ingest container, SFTPGo
|
||||
with neither, videos wait as FAILED "ffprobe_missing" and "Analisar agora" retries them). Faces in videos run
|
||||
in the face worker (`FACES_*` set), `ARCHIVE_VIDEO_FACE_FPS` frames a second (default 5). On the ingest container, SFTPGo
|
||||
users get `<INGEST_ROOT>/<login>` as home folder; register each login under the member it belongs to
|
||||
(`POST /v1/orgs/:orgId/ftp-accounts`).
|
||||
8. Faces (worker host): install Rust, `infra/faces/download-models.sh /srv/photoreport-data/models`, and set the
|
||||
|
||||
+13
-2
@@ -170,8 +170,19 @@ Viewers: a gallery's first page carries its videos (`videos`, `videoTotal`), eac
|
||||
`Range` requests, so playback starts at once and can jump anywhere. The grid shows them above the photos with their
|
||||
length; the player opens like the large photo, with "Descarregar" (the web copy) for everyone and the original's link
|
||||
on the cloud only for those who edit that folder. A gallery of videos only takes its first video's frame as cover.
|
||||
Faces in videos are the next step: frames through the same `DetectionEngine` as the photos, joined into one
|
||||
appearance per person (tracking), reviewed like the photos' face groups.
|
||||
**Faces in videos** (organizations with face recognition on, like the photos): once a video's web copy is made its
|
||||
`faces_status` is PENDING, and the face worker (one video at a time, in one of the engine's places beside the photos,
|
||||
so a steady flow of photos never keeps it waiting; with a single place, only when no photo is waiting) takes `ARCHIVE_VIDEO_FACE_FPS`
|
||||
frames a second (default 5) out of the web copy with ffmpeg and analyses each with the same engine and filters as a
|
||||
photo (size, focus, sharpness). The same face in consecutive frames (alike, and about where it was; missed for up to
|
||||
1.5 s) is one appearance (`video_faces`: start, end, its clearest frame kept beside the web copy, the mean of its sharp
|
||||
embeddings). Appearances go into the event's face groups by `groupEvent`, the photos' own step, so suggestions,
|
||||
confirming, "não é", false positives, recognition off and merging are the photos'. "Rever rostos" shows a group's
|
||||
video appearances beside its photos' faces (the frame, signed: `/v1/files/video-faces/:id`); a group with videos can
|
||||
be changed only by a viewer who edits every folder its photos and videos are in. The gallery's videos carry who
|
||||
appears and when (`people`, with each moment), and a person's page lists the videos they are in: the player jumps to
|
||||
each moment. A folder moved to another event has its videos' faces looked for again there. The app's archive counts
|
||||
show how many videos are waiting for their faces (`videoFacesPending`), done and failed.
|
||||
|
||||
### Downloads
|
||||
|
||||
|
||||
@@ -16,6 +16,10 @@ lightcraft-codecs = { workspace = true }
|
||||
lightcraft-pipeline = { workspace = true }
|
||||
lightcraft-raster = { workspace = true }
|
||||
lightcraft-geom = { workspace = true }
|
||||
lightcraft-merge = { workspace = true }
|
||||
lightcraft-raw = { workspace = true }
|
||||
lightcraft-color = { workspace = true }
|
||||
lightcraft-meta = { workspace = true }
|
||||
serde = { workspace = true }
|
||||
serde_json = { workspace = true }
|
||||
thiserror = { workspace = true }
|
||||
@@ -0,0 +1,163 @@
|
||||
//! Capture metadata for one photo, read by LightCraft (`lightcraft-meta`).
|
||||
//!
|
||||
//! EXIF first, then IPTC fills whatever is still empty, then XMP overrides the user fields and fills the
|
||||
//! rest. That covers JPEG, PNG, WebP, TIFF, DNG and the raws LightCraft opens, including Canon CR3.
|
||||
//! A loose XMP sidecar (the XML file next to a raw) is read the same way.
|
||||
|
||||
use lightcraft_meta::Metadata;
|
||||
use serde::Serialize;
|
||||
use serde_json::{Value, json};
|
||||
|
||||
#[derive(Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
struct Capture {
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
camera_make: Option<String>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
camera_model: Option<String>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
camera_serial: Option<String>,
|
||||
/// ISO 8601. The offset is included when the file recorded one.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
captured_at: Option<String>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
focal_length: Option<f64>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
aperture: Option<f64>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
iso: Option<u32>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
width: Option<u32>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
height: Option<u32>,
|
||||
/// EV. Zero is a real compensation and is kept.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
exposure_bias: Option<f64>,
|
||||
/// Seconds.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
exposure_time: Option<f64>,
|
||||
}
|
||||
|
||||
fn positive(value: Option<f64>) -> Option<f64> {
|
||||
value.filter(|n| n.is_finite() && *n > 0.0)
|
||||
}
|
||||
|
||||
fn finite(value: Option<f64>) -> Option<f64> {
|
||||
value.filter(|n| n.is_finite())
|
||||
}
|
||||
|
||||
fn text(value: Option<String>) -> Option<String> {
|
||||
value
|
||||
.map(|s| s.trim().trim_end_matches('\0').to_string())
|
||||
.filter(|s| !s.is_empty())
|
||||
}
|
||||
|
||||
fn from_meta(meta: &Metadata) -> Capture {
|
||||
Capture {
|
||||
camera_make: text(meta.make.clone()),
|
||||
camera_model: text(meta.model.clone()),
|
||||
camera_serial: text(meta.serial_number.clone()),
|
||||
captured_at: meta
|
||||
.capture_time
|
||||
.filter(|t| t.year > 1900)
|
||||
.map(|t| t.to_iso()),
|
||||
focal_length: positive(meta.focal_length),
|
||||
aperture: positive(meta.f_number),
|
||||
iso: meta.iso.filter(|n| *n > 0),
|
||||
width: meta.width.filter(|n| *n > 0),
|
||||
height: meta.height.filter(|n| *n > 0),
|
||||
exposure_bias: finite(meta.exposure_bias),
|
||||
exposure_time: positive(meta.exposure_time),
|
||||
}
|
||||
}
|
||||
|
||||
fn present(capture: &Capture) -> bool {
|
||||
capture.camera_make.is_some()
|
||||
|| capture.camera_model.is_some()
|
||||
|| capture.camera_serial.is_some()
|
||||
|| capture.captured_at.is_some()
|
||||
|| capture.focal_length.is_some()
|
||||
|| capture.aperture.is_some()
|
||||
|| capture.iso.is_some()
|
||||
|| capture.width.is_some()
|
||||
|| capture.height.is_some()
|
||||
|| capture.exposure_bias.is_some()
|
||||
|| capture.exposure_time.is_some()
|
||||
}
|
||||
|
||||
fn value_of(capture: &Capture) -> Value {
|
||||
serde_json::to_value(capture).unwrap_or_else(|_| json!({}))
|
||||
}
|
||||
|
||||
/// Capture fields as a JSON object. A file with none of them yields `{}`.
|
||||
pub fn read_capture(bytes: &[u8]) -> Value {
|
||||
let from_file = from_meta(&lightcraft_meta::extract(bytes));
|
||||
if present(&from_file) {
|
||||
return value_of(&from_file);
|
||||
}
|
||||
// A sidecar is not a container. `extract` finds nothing; the packet itself is the metadata.
|
||||
if let Ok(text) = std::str::from_utf8(bytes) {
|
||||
let trimmed = text.trim_start_matches('\u{feff}').trim_start();
|
||||
if trimmed.starts_with('<')
|
||||
&& let Ok(xmp) = lightcraft_meta::parse_xmp(trimmed)
|
||||
{
|
||||
let from_xmp = from_meta(&xmp.metadata);
|
||||
if present(&from_xmp) {
|
||||
return value_of(&from_xmp);
|
||||
}
|
||||
}
|
||||
}
|
||||
value_of(&from_file)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use lightcraft_meta::{DateTime, Metadata, write_exif, write_xmp};
|
||||
|
||||
fn sample() -> Metadata {
|
||||
Metadata {
|
||||
make: Some("Canon".into()),
|
||||
model: Some("EOS R5".into()),
|
||||
serial_number: Some("123".into()),
|
||||
capture_time: DateTime::parse_iso("2026-10-21T10:00:00"),
|
||||
focal_length: Some(16.0),
|
||||
f_number: Some(8.0),
|
||||
iso: Some(100),
|
||||
exposure_bias: Some(-2.0),
|
||||
exposure_time: Some(0.01),
|
||||
..Metadata::default()
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn exif_block_round_trips_the_bracket_fields() {
|
||||
let meta = sample();
|
||||
let json = read_capture(&write_exif(&meta));
|
||||
assert_eq!(json["cameraMake"], "Canon");
|
||||
assert_eq!(json["cameraModel"], "EOS R5");
|
||||
assert_eq!(json["capturedAt"], meta.capture_time.unwrap().to_iso());
|
||||
assert_eq!(json["focalLength"], 16.0);
|
||||
assert_eq!(json["aperture"], 8.0);
|
||||
assert_eq!(json["iso"], 100);
|
||||
assert_eq!(json["exposureBias"], -2.0);
|
||||
let shutter = json["exposureTime"].as_f64().unwrap();
|
||||
assert!((shutter - 0.01).abs() < 1e-6, "{shutter}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn xmp_sidecar_round_trips_the_bracket_fields() {
|
||||
let meta = sample();
|
||||
let json = read_capture(write_xmp(&meta, None).as_bytes());
|
||||
assert_eq!(json["cameraMake"], "Canon");
|
||||
assert_eq!(json["exposureBias"], -2.0);
|
||||
assert_eq!(json["capturedAt"], meta.capture_time.unwrap().to_iso());
|
||||
let shutter = json["exposureTime"].as_f64().unwrap();
|
||||
assert!((shutter - 0.01).abs() < 1e-6, "{shutter}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unknown_bytes_are_empty() {
|
||||
assert_eq!(read_capture(b"not a photo"), json!({}));
|
||||
}
|
||||
}
|
||||
@@ -4,7 +4,9 @@
|
||||
//! small JSON edit commands addressed by LightCraft control ids (`light.exposure`, `effects.clarity`, ...).
|
||||
//! Updating LightCraft should only ever require changes in this crate.
|
||||
|
||||
pub mod capture;
|
||||
pub mod level;
|
||||
pub mod merge;
|
||||
pub mod render;
|
||||
|
||||
pub use lightcraft_develop::DevelopSettings;
|
||||
|
||||
@@ -0,0 +1,326 @@
|
||||
//! Exposure brackets through LightCraft's HDR merge (`lightcraft-merge`).
|
||||
//!
|
||||
//! This is not the `hdr.*` develop panel. That panel is display headroom for one photo. Here several
|
||||
//! exposures of the same angle become one scene-linear image: the engine aligns them, measures the
|
||||
//! exposure steps, and weights each pixel so a clipped channel contributes nothing. The result is
|
||||
//! developed with the engine's Auto settings (the same finish LightCraft applies to a merge).
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use lightcraft_color::Xy;
|
||||
use lightcraft_develop::DevelopSettings;
|
||||
use lightcraft_merge::frame::Frame;
|
||||
use lightcraft_merge::{Deghost, FrameColor, HdrOptions, HdrResult, merge_hdr, no_progress};
|
||||
use lightcraft_pipeline::{Quality, RenderRequest, SourceInfo, auto};
|
||||
use lightcraft_raster::Rgb32f;
|
||||
use lightcraft_raster::resample::{Filter, fit};
|
||||
use lightcraft_raw::ColorData;
|
||||
|
||||
use crate::EngineError;
|
||||
use crate::render::Pixels;
|
||||
|
||||
/// Longest edge of a preview. A full-sensor demosaic does not belong in this path.
|
||||
const EDGE_CAP: u32 = 4096;
|
||||
|
||||
/// Merge `files` (raw or a standard image the engine reads) into one developed preview.
|
||||
/// `max_edge` is the long side of each frame before the merge, clamped to 64..=4096.
|
||||
pub fn merge_brackets(files: &[&[u8]], max_edge: u32) -> Result<Pixels, EngineError> {
|
||||
let (image, info) = fuse_working(files, max_edge)?;
|
||||
let edge = clamped_edge(max_edge);
|
||||
let mut settings = if info.raw {
|
||||
DevelopSettings::for_raw(info.as_shot_temp, info.as_shot_tint)
|
||||
} else {
|
||||
DevelopSettings::default()
|
||||
};
|
||||
let tone = auto::auto_tone(&image, &info, &settings);
|
||||
settings.light.exposure = tone.exposure;
|
||||
settings.light.contrast = tone.contrast;
|
||||
settings.light.highlights = tone.highlights;
|
||||
settings.light.shadows = tone.shadows;
|
||||
settings.light.whites = tone.whites;
|
||||
settings.light.blacks = tone.blacks;
|
||||
settings.color.vibrance = tone.vibrance;
|
||||
settings.color.saturation = tone.saturation;
|
||||
let req = RenderRequest {
|
||||
quality: Quality::Full,
|
||||
apply_crop: false,
|
||||
..RenderRequest::fit(edge, edge)
|
||||
};
|
||||
let out = lightcraft_pipeline::render(&image, &info, &settings, &req);
|
||||
let (width, height) = (out.image.width as u32, out.image.height as u32);
|
||||
let rgba = out.image.data.iter().flat_map(|p| *p).collect();
|
||||
Ok(Pixels {
|
||||
width,
|
||||
height,
|
||||
rgba,
|
||||
})
|
||||
}
|
||||
|
||||
/// Scene-linear working image of a merge, before the develop finish. Tests check that a clipped
|
||||
/// window and a black interior both survive this step.
|
||||
pub(crate) fn fuse_working(
|
||||
files: &[&[u8]],
|
||||
max_edge: u32,
|
||||
) -> Result<(Rgb32f, SourceInfo), EngineError> {
|
||||
if files.len() < 2 {
|
||||
return Err(EngineError::Decode(
|
||||
"a bracket needs at least two exposures".into(),
|
||||
));
|
||||
}
|
||||
let edge = clamped_edge(max_edge);
|
||||
let mut frames = Vec::with_capacity(files.len());
|
||||
for bytes in files {
|
||||
frames.push(load_bracket_frame(bytes, edge)?);
|
||||
}
|
||||
let merged = merge_hdr(
|
||||
frames,
|
||||
&HdrOptions {
|
||||
align: true,
|
||||
deghost: Deghost::None,
|
||||
},
|
||||
&no_progress,
|
||||
)
|
||||
.map_err(|e| EngineError::Decode(e.to_string()))?;
|
||||
Ok(to_working(&merged))
|
||||
}
|
||||
|
||||
fn clamped_edge(max_edge: u32) -> usize {
|
||||
max_edge.clamp(64, EDGE_CAP) as usize
|
||||
}
|
||||
|
||||
/// A frame no larger than `max_edge`. Raw mosaics are binned instead of demosaiced at full size.
|
||||
fn load_bracket_frame(bytes: &[u8], max_edge: usize) -> Result<Frame, EngineError> {
|
||||
if lightcraft_raw::probe(bytes).is_none() {
|
||||
return lightcraft_merge::load_frame(bytes, Some(max_edge), false)
|
||||
.map_err(|e| EngineError::Decode(e.to_string()));
|
||||
}
|
||||
let mut raw = lightcraft_raw::decode(bytes).map_err(|e| EngineError::Decode(e.to_string()))?;
|
||||
// Merged uncorrected. The reference frame's corrections travel with the frame, as the engine does,
|
||||
// so a later full-size file can apply them once.
|
||||
let (aw, ah) = (raw.active_area.width, raw.active_area.height);
|
||||
let crop = raw.develop_crop(aw, ah);
|
||||
let lens = lightcraft_raw::opcodes::applied_ops(&raw.opcodes.list3)
|
||||
.filter(|op| op.is_lens_correction())
|
||||
.filter_map(|op| op.cropped(aw, ah, crop))
|
||||
.map(|op| match op {
|
||||
lightcraft_raw::Opcode::WarpRectilinear2 {
|
||||
planes,
|
||||
center,
|
||||
reciprocal,
|
||||
..
|
||||
} => lightcraft_raw::Opcode::WarpRectilinear2 {
|
||||
planes,
|
||||
center,
|
||||
reciprocal,
|
||||
optional: false,
|
||||
},
|
||||
op => op,
|
||||
})
|
||||
.collect();
|
||||
raw.opcodes.list3.retain(|op| !op.is_lens_correction());
|
||||
let long = raw.active_area.width.max(raw.active_area.height);
|
||||
let mut image = if let Some(k) = bin_factor(&raw, max_edge) {
|
||||
raw.develop_binned(k, 0.99)
|
||||
.map_err(|e| EngineError::Decode(e.to_string()))?
|
||||
.ok_or_else(|| EngineError::Decode("this raw cannot be reduced for a preview".into()))?
|
||||
} else if long <= max_edge.saturating_mul(2) {
|
||||
raw.develop(lightcraft_raw::Method::Bilinear)
|
||||
.map_err(|e| EngineError::Decode(e.to_string()))?
|
||||
} else {
|
||||
return Err(EngineError::Decode(
|
||||
"this raw cannot be reduced for a preview".into(),
|
||||
));
|
||||
};
|
||||
for p in image.data.iter_mut() {
|
||||
*p = p.map(|v| v.max(0.0));
|
||||
}
|
||||
if image.width.max(image.height) > max_edge {
|
||||
image = fit(&image, max_edge, max_edge, Filter::Box);
|
||||
}
|
||||
let metadata = if raw.metadata == lightcraft_meta::Metadata::default() {
|
||||
lightcraft_meta::extract(bytes)
|
||||
} else {
|
||||
raw.metadata.clone()
|
||||
};
|
||||
let mut exposure = lightcraft_merge::frame::exif_exposure(&metadata);
|
||||
if exposure.is_none() {
|
||||
exposure = lightcraft_merge::frame::exif_exposure(&raw.metadata);
|
||||
}
|
||||
Ok(Frame {
|
||||
clip: lightcraft_merge::frame::detect_clip(&image),
|
||||
image,
|
||||
exposure,
|
||||
raw: true,
|
||||
color: FrameColor::Camera(Box::new(raw.color.clone())),
|
||||
orientation: raw.orientation,
|
||||
metadata,
|
||||
baseline_exposure: raw.color.baseline_exposure,
|
||||
lens,
|
||||
wb_multipliers: raw.wb_multipliers,
|
||||
})
|
||||
}
|
||||
|
||||
fn bin_factor(raw: &lightcraft_raw::RawImage, max_edge: usize) -> Option<usize> {
|
||||
let long = raw.active_area.width.max(raw.active_area.height);
|
||||
let need = max_edge.max(1);
|
||||
[8usize, 6, 4, 3, 2]
|
||||
.into_iter()
|
||||
.find(|&k| raw.can_bin(k) && long / k >= need)
|
||||
}
|
||||
|
||||
fn to_working(merged: &HdrResult) -> (Rgb32f, SourceInfo) {
|
||||
let image = merged.radiance.clone().into_oriented(merged.orientation);
|
||||
let gain = 2f32.powf(merged.baseline_exposure as f32);
|
||||
match &merged.color {
|
||||
FrameColor::Camera(color) => camera_working(image, color, gain),
|
||||
FrameColor::Linear { to_xyz_d50 } => {
|
||||
let to_rec = lightcraft_color::REC2020
|
||||
.from_xyz()
|
||||
.mul(&lightcraft_color::bradford(
|
||||
lightcraft_color::D50,
|
||||
lightcraft_color::D65,
|
||||
))
|
||||
.mul(to_xyz_d50);
|
||||
let m = to_rec.to_f32();
|
||||
let image = image.map(|p| apply_mat(&m, p).map(|v| v.max(0.0) * gain));
|
||||
(image, SourceInfo::default())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn camera_working(image: Rgb32f, color: &ColorData, gain: f32) -> (Rgb32f, SourceInfo) {
|
||||
let white = as_shot_xy(color);
|
||||
let transform = lightcraft_raw::color::camera_transform_of(color, white);
|
||||
let m = transform.matrix.to_f32();
|
||||
let wb = transform.wb;
|
||||
let image = image.map(|p| {
|
||||
let balanced = [p[0] * wb[0], p[1] * wb[1], p[2] * wb[2]];
|
||||
apply_mat(&m, balanced).map(|v| v.max(0.0) * gain)
|
||||
});
|
||||
let (temp, tint) = lightcraft_color::cct::xy_to_temp_tint(white);
|
||||
let info = SourceInfo {
|
||||
raw: true,
|
||||
as_shot_temp: temp,
|
||||
as_shot_tint: tint,
|
||||
camera_color: Some(Arc::new(lightcraft_pipeline::CameraColor {
|
||||
tags: color.clone(),
|
||||
developed_for: white,
|
||||
})),
|
||||
..SourceInfo::default()
|
||||
};
|
||||
(image, info)
|
||||
}
|
||||
|
||||
fn as_shot_xy(color: &ColorData) -> Xy {
|
||||
if let Some(xy) = color.as_shot_white_xy {
|
||||
return xy;
|
||||
}
|
||||
if let Some(neutral) = color.as_shot_neutral {
|
||||
return lightcraft_raw::color::neutral_to_xy(color, neutral);
|
||||
}
|
||||
lightcraft_color::D65
|
||||
}
|
||||
|
||||
fn apply_mat(m: &[[f32; 3]; 3], p: [f32; 3]) -> [f32; 3] {
|
||||
[
|
||||
m[0][0] * p[0] + m[0][1] * p[1] + m[0][2] * p[2],
|
||||
m[1][0] * p[0] + m[1][1] * p[1] + m[1][2] * p[2],
|
||||
m[2][0] * p[0] + m[2][1] * p[1] + m[2][2] * p[2],
|
||||
]
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use lightcraft_geom::Orientation;
|
||||
use lightcraft_merge::{DngSamples, write_linear_dng};
|
||||
use lightcraft_meta::Metadata;
|
||||
|
||||
fn linear_color() -> FrameColor {
|
||||
FrameColor::Linear {
|
||||
to_xyz_d50: lightcraft_color::bradford(lightcraft_color::D65, lightcraft_color::D50)
|
||||
.mul(&lightcraft_color::SRGB.to_xyz()),
|
||||
}
|
||||
}
|
||||
|
||||
/// Left half is a window (bright), right half is the room (dark), with a stable texture so
|
||||
/// alignment has something to lock onto. `ev` is relative to the middle exposure.
|
||||
fn exposure_dng(ev: f64) -> Vec<u8> {
|
||||
let (w, h) = (320usize, 240usize);
|
||||
let k = 2f32.powf(ev as f32);
|
||||
let img = Rgb32f::from_fn(w, h, |x, y| {
|
||||
let window = x < w / 2;
|
||||
let base = if window { 2.0 } else { 0.04 };
|
||||
let grain = ((x * 13 + y * 7) % 5) as f32 / 20.0 + 0.9;
|
||||
[base * grain * k; 3].map(|v| v.clamp(0.0, 1.0))
|
||||
});
|
||||
let meta = Metadata {
|
||||
exposure_time: Some(2f64.powf(ev) / 60.0),
|
||||
f_number: Some(8.0),
|
||||
iso: Some(100),
|
||||
..Metadata::default()
|
||||
};
|
||||
write_linear_dng(
|
||||
&img,
|
||||
&linear_color(),
|
||||
Orientation::Normal,
|
||||
&meta,
|
||||
0.0,
|
||||
DngSamples::U16,
|
||||
&[],
|
||||
)
|
||||
.expect("dng")
|
||||
}
|
||||
|
||||
fn mean_green(img: &Rgb32f, x0: usize, x1: usize) -> f32 {
|
||||
let mut sum = 0f64;
|
||||
let mut n = 0usize;
|
||||
let y0 = 16;
|
||||
let y1 = img.height.saturating_sub(16);
|
||||
for y in y0..y1 {
|
||||
for x in x0..x1 {
|
||||
sum += img.get(x, y)[1] as f64;
|
||||
n += 1;
|
||||
}
|
||||
}
|
||||
(sum / n.max(1) as f64) as f32
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn window_and_interior_both_survive() {
|
||||
let dark = exposure_dng(-2.0);
|
||||
let mid = exposure_dng(0.0);
|
||||
let bright = exposure_dng(2.0);
|
||||
let files = [dark.as_slice(), mid.as_slice(), bright.as_slice()];
|
||||
let (image, _) = fuse_working(&files, 512).expect("merge");
|
||||
let mid_x = image.width / 2;
|
||||
let window = mean_green(&image, 16, mid_x.saturating_sub(16));
|
||||
let room = mean_green(&image, mid_x + 16, image.width.saturating_sub(16));
|
||||
// The bright frame clipped the window at 1. The dark frame still held it, so the merge
|
||||
// comes back above that clip. The room was black in the dark frame and readable in the bright one.
|
||||
assert!(
|
||||
window > 1.2,
|
||||
"window should be recovered past the clip, got {window}"
|
||||
);
|
||||
assert!(
|
||||
room > 0.02 && room < 0.5,
|
||||
"room should be open but not blown, got {room}"
|
||||
);
|
||||
let preview = merge_brackets(&files, 512).expect("preview");
|
||||
assert!(preview.width > 0 && preview.height > 0);
|
||||
assert_eq!(
|
||||
preview.rgba.len(),
|
||||
preview.width as usize * preview.height as usize * 4
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn one_photo_is_not_a_bracket() {
|
||||
let mid = exposure_dng(0.0);
|
||||
match merge_brackets(&[mid.as_slice()], 256) {
|
||||
Err(EngineError::Decode(_)) => {}
|
||||
Err(err) => panic!("unexpected error: {err}"),
|
||||
Ok(_) => panic!("one photo was merged"),
|
||||
}
|
||||
}
|
||||
}
|
||||
+66
-1
@@ -2,7 +2,7 @@
|
||||
//! slider move, and gets RGBA pixels back. Settings and commands cross the boundary as JSON strings, the
|
||||
//! same documents the API stores, so there is one format everywhere.
|
||||
|
||||
use photoreport_engine::render::Source;
|
||||
use photoreport_engine::render::{Source, encode_jpeg};
|
||||
use photoreport_engine::{DevelopSettings, EditCommand};
|
||||
use wasm_bindgen::prelude::*;
|
||||
|
||||
@@ -18,6 +18,13 @@ fn settings_from(json: &str) -> Result<DevelopSettings, JsError> {
|
||||
DevelopSettings::from_json(&v).map_err(js_err)
|
||||
}
|
||||
|
||||
/// Capture metadata (camera, clock, exposure) as JSON. LightCraft reads EXIF, then IPTC, then XMP,
|
||||
/// including Canon CR3 and a loose XMP sidecar. A file with none of those fields yields `{}`.
|
||||
#[wasm_bindgen(js_name = readCaptureMeta)]
|
||||
pub fn read_capture_meta(bytes: &[u8]) -> String {
|
||||
photoreport_engine::capture::read_capture(bytes).to_string()
|
||||
}
|
||||
|
||||
/// Every develop control of the pinned LightCraft version (id, module, label, range, default, step).
|
||||
#[wasm_bindgen]
|
||||
pub fn controls() -> Result<String, JsError> {
|
||||
@@ -163,6 +170,64 @@ impl Photo {
|
||||
}
|
||||
}
|
||||
|
||||
/// Exposures of one angle, held until [`BracketJob::merge`].
|
||||
#[wasm_bindgen]
|
||||
#[derive(Default)]
|
||||
pub struct BracketJob {
|
||||
files: Vec<Vec<u8>>,
|
||||
}
|
||||
|
||||
#[wasm_bindgen]
|
||||
impl BracketJob {
|
||||
#[wasm_bindgen(constructor)]
|
||||
pub fn new() -> BracketJob {
|
||||
BracketJob::default()
|
||||
}
|
||||
|
||||
/// One photo's bytes. The order is the order they are merged.
|
||||
pub fn push(&mut self, bytes: &[u8]) {
|
||||
self.files.push(bytes.to_vec());
|
||||
}
|
||||
|
||||
/// Developed JPEG preview of the merged bracket. `max_edge` is the long side of each frame.
|
||||
pub fn merge(&self, max_edge: u32) -> Result<BracketMerge, JsError> {
|
||||
let refs: Vec<&[u8]> = self.files.iter().map(Vec::as_slice).collect();
|
||||
let pixels = photoreport_engine::merge::merge_brackets(&refs, max_edge).map_err(js_err)?;
|
||||
let jpeg = encode_jpeg(&pixels, 90).map_err(js_err)?;
|
||||
Ok(BracketMerge {
|
||||
width: pixels.width,
|
||||
height: pixels.height,
|
||||
jpeg,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// A merged bracket, as a baseline JPEG.
|
||||
#[wasm_bindgen]
|
||||
pub struct BracketMerge {
|
||||
width: u32,
|
||||
height: u32,
|
||||
jpeg: Vec<u8>,
|
||||
}
|
||||
|
||||
#[wasm_bindgen]
|
||||
impl BracketMerge {
|
||||
#[wasm_bindgen(getter)]
|
||||
pub fn width(&self) -> u32 {
|
||||
self.width
|
||||
}
|
||||
|
||||
#[wasm_bindgen(getter)]
|
||||
pub fn height(&self) -> u32 {
|
||||
self.height
|
||||
}
|
||||
|
||||
/// JPEG bytes (copied out to JS).
|
||||
pub fn jpeg(&self) -> Vec<u8> {
|
||||
self.jpeg.clone()
|
||||
}
|
||||
}
|
||||
|
||||
fn values_json(values: Vec<(&'static str, f64)>) -> Result<String, JsError> {
|
||||
let map: serde_json::Map<String, serde_json::Value> = values
|
||||
.into_iter()
|
||||
|
||||
@@ -0,0 +1,126 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { groupBrackets, type BracketFrame } from "./brackets.js";
|
||||
|
||||
const START = Date.parse("2026-10-21T10:00:00.000Z");
|
||||
|
||||
function frame(id: string, bias: number, atMs: number, extra: Partial<BracketFrame> = {}): BracketFrame {
|
||||
return {
|
||||
id,
|
||||
fileName: `${id}.CR3`,
|
||||
capturedAt: new Date(START + atMs).toISOString(),
|
||||
cameraSerial: "body",
|
||||
focalLength: 16,
|
||||
aperture: 8,
|
||||
iso: 100,
|
||||
width: 6000,
|
||||
height: 4000,
|
||||
exposureBias: bias,
|
||||
exposureTime: 1 / 100,
|
||||
...extra,
|
||||
};
|
||||
}
|
||||
|
||||
function stackIds(frames: BracketFrame[]): string[][] {
|
||||
return groupBrackets(frames).stacks.map((stack) => stack.frameIds);
|
||||
}
|
||||
|
||||
describe("real-estate brackets", () => {
|
||||
it("keeps a three-frame ±2 bracket as one angle", () => {
|
||||
const frames = [frame("dark", -2, 0), frame("mid", 0, 200), frame("bright", 2, 400)];
|
||||
expect(stackIds(frames)).toEqual([["dark", "mid", "bright"]]);
|
||||
expect(groupBrackets(frames).aside).toEqual([]);
|
||||
});
|
||||
|
||||
it("keeps a five-frame bracket together", () => {
|
||||
const frames = [-2, -1, 0, 1, 2].map((bias, index) => frame(`f${index}`, bias, index * 200));
|
||||
expect(stackIds(frames)).toEqual([["f0", "f1", "f2", "f3", "f4"]]);
|
||||
});
|
||||
|
||||
it("splits two angles shot a second apart when the compensation repeats", () => {
|
||||
const first = [frame("a", -2, 0), frame("b", 0, 200), frame("c", 2, 400)];
|
||||
const second = [frame("d", -2, 600), frame("e", 0, 800), frame("f", 2, 1000)];
|
||||
expect(stackIds([...first, ...second])).toEqual([
|
||||
["a", "b", "c"],
|
||||
["d", "e", "f"],
|
||||
]);
|
||||
});
|
||||
|
||||
it("leaves a loose frame between two angles out of both stacks", () => {
|
||||
const frames = [
|
||||
frame("a", -2, 0),
|
||||
frame("b", 0, 200),
|
||||
frame("c", 2, 400),
|
||||
frame("solo", 0, 30_000),
|
||||
frame("d", -2, 60_000),
|
||||
frame("e", 0, 60_200),
|
||||
frame("f", 2, 60_400),
|
||||
];
|
||||
const grouped = groupBrackets(frames);
|
||||
expect(grouped.stacks.map((stack) => stack.frameIds)).toEqual([
|
||||
["a", "b", "c"],
|
||||
["d", "e", "f"],
|
||||
]);
|
||||
expect(grouped.aside).toEqual(["solo"]);
|
||||
});
|
||||
|
||||
it("counts a long exposure from when the shutter closes, not from when it opens", () => {
|
||||
const frames = [
|
||||
frame("dark", -2, 0, { exposureTime: 20 }),
|
||||
frame("mid", 0, 20_000, { exposureTime: 5 }),
|
||||
frame("bright", 2, 25_000, { exposureTime: 1 }),
|
||||
];
|
||||
expect(stackIds(frames)).toEqual([["dark", "mid", "bright"]]);
|
||||
});
|
||||
|
||||
it("groups a manual bracket whose compensation stays at zero and whose shutter changes", () => {
|
||||
const frames = [
|
||||
frame("dark", 0, 0, { exposureTime: 1 / 30 }),
|
||||
frame("mid", 0, 200, { exposureTime: 1 / 8 }),
|
||||
frame("bright", 0, 400, { exposureTime: 1 / 2 }),
|
||||
];
|
||||
expect(stackIds(frames)).toEqual([["dark", "mid", "bright"]]);
|
||||
});
|
||||
|
||||
it("does not stack a same-exposure burst", () => {
|
||||
const frames = Array.from({ length: 8 }, (_, index) => frame(`b${index}`, 0, index * 50, { exposureTime: 1 / 500 }));
|
||||
const grouped = groupBrackets(frames);
|
||||
expect(grouped.stacks).toEqual([]);
|
||||
expect(grouped.aside).toEqual(frames.map((item) => item.id));
|
||||
});
|
||||
|
||||
it("leaves a two-frame pair and a bracket that barely changes exposure aside", () => {
|
||||
const pair = [frame("p0", -2, 0), frame("p1", 2, 200)];
|
||||
const nudge = [frame("n0", 0, 10_000), frame("n1", 0.3, 10_200), frame("n2", 0.7, 10_400)];
|
||||
const grouped = groupBrackets([...pair, ...nudge]);
|
||||
expect(grouped.stacks).toEqual([]);
|
||||
expect(grouped.aside).toEqual(["p0", "p1", "n0", "n1", "n2"]);
|
||||
});
|
||||
|
||||
it("does not mix two focal lengths or two bodies", () => {
|
||||
const wide = [frame("w0", -2, 0), frame("w1", 0, 200), frame("w2", 2, 400, { focalLength: 35 })];
|
||||
expect(stackIds(wide)).toEqual([]);
|
||||
const mixed = [
|
||||
frame("a0", -2, 0, { cameraSerial: "A" }),
|
||||
frame("b0", -2, 100, { cameraSerial: "B" }),
|
||||
frame("a1", 0, 200, { cameraSerial: "A" }),
|
||||
frame("b1", 0, 300, { cameraSerial: "B" }),
|
||||
frame("a2", 2, 400, { cameraSerial: "A" }),
|
||||
frame("b2", 2, 500, { cameraSerial: "B" }),
|
||||
];
|
||||
expect(stackIds(mixed)).toEqual([]);
|
||||
expect(groupBrackets(mixed).aside).toHaveLength(6);
|
||||
});
|
||||
|
||||
it("orders a bracket by the file name when the clock is missing", () => {
|
||||
const frames = [
|
||||
frame("IMG_10", 2, 0, { capturedAt: null, fileName: "IMG_10.CR3" }),
|
||||
frame("IMG_2", 0, 0, { capturedAt: null, fileName: "IMG_2.CR3" }),
|
||||
frame("IMG_1", -2, 0, { capturedAt: null, fileName: "IMG_1.CR3" }),
|
||||
];
|
||||
expect(stackIds(frames)).toEqual([["IMG_1", "IMG_2", "IMG_10"]]);
|
||||
});
|
||||
|
||||
it("returns nothing for an empty folder", () => {
|
||||
expect(groupBrackets([])).toEqual({ stacks: [], aside: [] });
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,194 @@
|
||||
/**
|
||||
* Groups a real-estate shoot into one stack per camera angle.
|
||||
*
|
||||
* Cameras do not agree on a "this is a bracket" tag. The portable signal is the exposure
|
||||
* compensation (EXIF ExposureBiasValue), together with the same body, lens, aperture, ISO
|
||||
* and frame size. A repeated compensation starts the next angle, so two brackets fired a
|
||||
* second apart stay apart. Time is only the gap after the shutter closes: a long exposure
|
||||
* is still one angle, and a frame shot after the photographer has moved is not.
|
||||
*/
|
||||
|
||||
/** Quiet time after one exposure ends before the next frame is another angle. */
|
||||
const GAP_AFTER_EXPOSURE_SECONDS = 4;
|
||||
/** Two frames are not the bracket this area merges. */
|
||||
const MIN_STACK_FRAMES = 3;
|
||||
/** Darkest to brightest. ±1 EV around the middle is 2; a nudge of a third of a stop is not. */
|
||||
const MIN_SPAN_STOPS = 1.5;
|
||||
|
||||
export interface BracketFrame {
|
||||
id: string;
|
||||
fileName?: string | null;
|
||||
/** ISO-8601. Only differences matter, so a shared wall clock is enough. */
|
||||
capturedAt?: string | null;
|
||||
cameraSerial?: string | null;
|
||||
cameraMake?: string | null;
|
||||
cameraModel?: string | null;
|
||||
focalLength?: number | null;
|
||||
aperture?: number | null;
|
||||
iso?: number | null;
|
||||
width?: number | null;
|
||||
height?: number | null;
|
||||
/** EV. Null when the body left it out and only the shutter changed. */
|
||||
exposureBias?: number | null;
|
||||
/** Seconds. */
|
||||
exposureTime?: number | null;
|
||||
}
|
||||
|
||||
export interface BracketGrouping {
|
||||
/** Capture order inside each stack. */
|
||||
stacks: { frameIds: string[] }[];
|
||||
/** Frames that are not part of a stack, in capture order. */
|
||||
aside: string[];
|
||||
}
|
||||
|
||||
export function groupBrackets(frames: readonly BracketFrame[]): BracketGrouping {
|
||||
const sorted = [...frames].sort(byCapture);
|
||||
const stacked = new Set<BracketFrame>();
|
||||
const stacks: { frameIds: string[] }[] = [];
|
||||
for (const run of runsOf(sorted)) {
|
||||
for (const group of splitByExposure(run)) {
|
||||
if (!isStack(group)) continue;
|
||||
stacks.push({ frameIds: group.map((frame) => frame.id) });
|
||||
for (const frame of group) stacked.add(frame);
|
||||
}
|
||||
}
|
||||
return { stacks, aside: sorted.filter((frame) => !stacked.has(frame)).map((frame) => frame.id) };
|
||||
}
|
||||
|
||||
function runsOf(sorted: readonly BracketFrame[]): BracketFrame[][] {
|
||||
const runs: BracketFrame[][] = [];
|
||||
let current: BracketFrame[] = [];
|
||||
for (const frame of sorted) {
|
||||
const first = current[0];
|
||||
const prev = current[current.length - 1];
|
||||
if (!first || !prev || !sameAngle(first, frame) || gapTooWide(prev, frame)) {
|
||||
if (current.length > 0) runs.push(current);
|
||||
current = [];
|
||||
}
|
||||
current.push(frame);
|
||||
}
|
||||
if (current.length > 0) runs.push(current);
|
||||
return runs;
|
||||
}
|
||||
|
||||
/**
|
||||
* Inside one burst, the exposure identity is the compensation when it actually changes,
|
||||
* and the shutter when the body wrote the same compensation on every frame (manual brackets).
|
||||
* The next angle starts where that identity repeats.
|
||||
*/
|
||||
function splitByExposure(run: readonly BracketFrame[]): BracketFrame[][] {
|
||||
const useBias = distinct(run.map((frame) => biasKey(frame.exposureBias))) >= 2;
|
||||
const groups: BracketFrame[][] = [];
|
||||
let current: BracketFrame[] = [];
|
||||
const seen = new Set<number>();
|
||||
const close = () => {
|
||||
if (current.length === 0) return;
|
||||
groups.push(current);
|
||||
current = [];
|
||||
seen.clear();
|
||||
};
|
||||
for (const frame of run) {
|
||||
const key = useBias ? biasKey(frame.exposureBias) : shutterKey(frame.exposureTime);
|
||||
if (key !== null && seen.has(key)) close();
|
||||
current.push(frame);
|
||||
if (key !== null) seen.add(key);
|
||||
}
|
||||
close();
|
||||
return groups;
|
||||
}
|
||||
|
||||
function isStack(group: readonly BracketFrame[]): boolean {
|
||||
return group.length >= MIN_STACK_FRAMES && spanStops(group) >= MIN_SPAN_STOPS;
|
||||
}
|
||||
|
||||
function spanStops(group: readonly BracketFrame[]): number {
|
||||
const biases = group.map((frame) => frame.exposureBias).filter((value): value is number => value != null && Number.isFinite(value));
|
||||
if (distinct(biases.map((value) => biasKey(value))) >= 2) return Math.max(...biases) - Math.min(...biases);
|
||||
const times = group.map((frame) => frame.exposureTime).filter((value): value is number => value != null && value > 0);
|
||||
if (times.length < 2) return 0;
|
||||
return Math.log2(Math.max(...times) / Math.min(...times));
|
||||
}
|
||||
|
||||
function sameAngle(first: BracketFrame, frame: BracketFrame): boolean {
|
||||
if (!sameBody(first, frame)) return false;
|
||||
if (!closeNumber(first.focalLength, frame.focalLength, 0.02, 0)) return false;
|
||||
if (!closeNumber(first.aperture, frame.aperture, 0, 0.15)) return false;
|
||||
if (first.iso != null && frame.iso != null && first.iso !== frame.iso) return false;
|
||||
if (first.width != null && frame.width != null && first.width !== frame.width) return false;
|
||||
if (first.height != null && frame.height != null && first.height !== frame.height) return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
function sameBody(a: BracketFrame, b: BracketFrame): boolean {
|
||||
const aSerial = text(a.cameraSerial);
|
||||
const bSerial = text(b.cameraSerial);
|
||||
if (aSerial && bSerial) return aSerial === bSerial;
|
||||
const aName = cameraName(a);
|
||||
const bName = cameraName(b);
|
||||
if (aName && bName) return aName === bName;
|
||||
return true;
|
||||
}
|
||||
|
||||
function cameraName(frame: BracketFrame): string {
|
||||
return [text(frame.cameraMake), text(frame.cameraModel)].filter((part) => part !== "").join(" ").toLowerCase();
|
||||
}
|
||||
|
||||
function gapTooWide(prev: BracketFrame, next: BracketFrame): boolean {
|
||||
const gap = gapSeconds(prev, next);
|
||||
return gap !== null && gap > GAP_AFTER_EXPOSURE_SECONDS;
|
||||
}
|
||||
|
||||
/** Seconds from the end of `prev` to the start of `next`. Null when either clock is missing. */
|
||||
function gapSeconds(prev: BracketFrame, next: BracketFrame): number | null {
|
||||
const from = instant(prev);
|
||||
const to = instant(next);
|
||||
if (from === null || to === null) return null;
|
||||
const duration = prev.exposureTime != null && prev.exposureTime > 0 ? prev.exposureTime : 0;
|
||||
return (to - from) / 1000 - duration;
|
||||
}
|
||||
|
||||
function byCapture(a: BracketFrame, b: BracketFrame): number {
|
||||
const aAt = instant(a);
|
||||
const bAt = instant(b);
|
||||
if (aAt !== null && bAt !== null && aAt !== bAt) return aAt - bAt;
|
||||
const name = natural(a.fileName ?? "", b.fileName ?? "");
|
||||
if (name !== 0) return name;
|
||||
if (a.id < b.id) return -1;
|
||||
if (a.id > b.id) return 1;
|
||||
return 0;
|
||||
}
|
||||
|
||||
function instant(frame: BracketFrame): number | null {
|
||||
if (!frame.capturedAt) return null;
|
||||
const value = Date.parse(frame.capturedAt);
|
||||
return Number.isFinite(value) ? value : null;
|
||||
}
|
||||
|
||||
function biasKey(value: number | null | undefined): number | null {
|
||||
if (value == null || !Number.isFinite(value)) return null;
|
||||
return Math.round(value * 10) / 10;
|
||||
}
|
||||
|
||||
/** Two significant figures, so 1/100 and 1/400 differ and 1/100.1 does not. */
|
||||
function shutterKey(value: number | null | undefined): number | null {
|
||||
if (value == null || !Number.isFinite(value) || value <= 0) return null;
|
||||
const magnitude = 10 ** (Math.floor(Math.log10(value)) - 1);
|
||||
return Math.round(value / magnitude) * magnitude;
|
||||
}
|
||||
|
||||
function distinct(keys: readonly (number | null)[]): number {
|
||||
return new Set(keys.filter((key): key is number => key !== null)).size;
|
||||
}
|
||||
|
||||
function closeNumber(a: number | null | undefined, b: number | null | undefined, rel: number, abs: number): boolean {
|
||||
if (a == null || b == null || !Number.isFinite(a) || !Number.isFinite(b)) return true;
|
||||
return Math.abs(a - b) <= Math.max(abs, rel * Math.max(Math.abs(a), Math.abs(b)));
|
||||
}
|
||||
|
||||
function text(value: string | null | undefined): string {
|
||||
return value?.trim() ?? "";
|
||||
}
|
||||
|
||||
function natural(a: string, b: string): number {
|
||||
return a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" });
|
||||
}
|
||||
@@ -1,3 +1,4 @@
|
||||
export * from "./brackets.js";
|
||||
export * from "./codes.js";
|
||||
export * from "./iptc.js";
|
||||
export * from "./paths.js";
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import type { BundleInput, BundleSummary, PressAccountInput, PressAccountSummary, PressStatement, NotificationView, AffiliateInput, AffiliateSummary, EarningsOverview, EarningsSettings, MemberPayoutInput, MyEarnings, PayeeAccount, PayoutInput, PayoutView, CodeGeneratorSettings, CodeLine, ConfirmFaceGroup, DeliveryItemSummary, DevelopState, EditLogEntry, FaceGroupSummary, GalleryInput, GalleryPhotosChange, GallerySummary, Module, OrderView, PhotoPatch, PhotoSummary, PostEdits, PrinterSummary, PrintEventInput, PrintEventSummary, PrintJobSummary, ProductInput, ProofingReport, ProductSummary, SiteInfo, SiteInput, StationSummary } from "@photoreport/contracts";
|
||||
import type { AgendaEntry, ArchiveStorage, CardScan, FaceIdentify, FaceRoster, CloudFolderSummary, CloudSource, CloudTreeFolder, InvoiceSummary, AutopilotStyle, DeliveryTarget, DeliveryTargetInput, JerseySample, JerseyStats, PersonSummary, PhotoFace, PhotoLookup, ShopSettings, SquadPerson, DeviceGrant, FtpAccount, FtpPlan, EventInput, EventSquads, EventSummary, FtpTargetAccount, IptcIssue, SportsCompetition, SportsFixture, SportsPlayer, SportsTeam, Me, Member, PhotoQuery, Role, ZerozeroGame } from "./types.js";
|
||||
import type { AgendaEntry, ArchiveStorage, CardScan, FaceIdentify, FaceRoster, CloudFolderSummary, CloudSource, CloudTreeFolder, InvoiceSummary, AutopilotStyle, DeliveryTarget, DeliveryTargetInput, JerseySample, JerseyStats, PersonSummary, PhotoFace, PhotoLookup, ShopSettings, SquadPerson, DeviceGrant, FtpAccount, FtpPlan, EventInput, EventSquads, EventSummary, FtpTargetAccount, IptcIssue, SportsCompetition, SportsFixture, SportsPlayer, SportsTeam, Me, Member, PhotoQuery, RealEstateFrame, RealEstateGrouping, Role, ZerozeroGame } from "./types.js";
|
||||
|
||||
/**
|
||||
* Where the refresh token lives. The web app leaves it in an httpOnly cookie (no store); the desktop app keeps it
|
||||
@@ -772,6 +772,20 @@ export class ApiClient {
|
||||
return this.request<{ enabled: boolean; legalBasis: string | null }>("PUT", `/v1/orgs/${orgId}/biometrics`, { enabled, ...(legalBasis ? { legalBasis } : {}) });
|
||||
}
|
||||
|
||||
getRealEstate(orgId: string) {
|
||||
return this.request<{ enabled: boolean }>("GET", `/v1/orgs/${orgId}/real-estate`);
|
||||
}
|
||||
|
||||
/** Owners show or hide the interior-bracket area. */
|
||||
setRealEstate(orgId: string, enabled: boolean) {
|
||||
return this.request<{ enabled: boolean }>("PUT", `/v1/orgs/${orgId}/real-estate`, { enabled });
|
||||
}
|
||||
|
||||
/** Groups exposure metadata into one stack per angle. The image files are not uploaded. */
|
||||
groupRealEstate(orgId: string, frames: RealEstateFrame[]) {
|
||||
return this.request<RealEstateGrouping>("POST", `/v1/orgs/${orgId}/real-estate/groups`, { frames });
|
||||
}
|
||||
|
||||
analyseEventFaces(eventId: string) {
|
||||
return this.request<{ queued: number }>("POST", `/v1/events/${eventId}/faces/analyse`);
|
||||
}
|
||||
|
||||
@@ -8,6 +8,30 @@ export interface Organization {
|
||||
slug: string;
|
||||
name: string;
|
||||
mode: OrganizationMode;
|
||||
/** Interior brackets. Missing on a session saved before the area existed: treated as off. */
|
||||
realEstateEnabled?: boolean;
|
||||
}
|
||||
|
||||
/** One frame's exposure metadata. The file itself stays on the photographer's computer. */
|
||||
export interface RealEstateFrame {
|
||||
id: string;
|
||||
fileName?: string | null;
|
||||
capturedAt?: string | null;
|
||||
cameraSerial?: string | null;
|
||||
cameraMake?: string | null;
|
||||
cameraModel?: string | null;
|
||||
focalLength?: number | null;
|
||||
aperture?: number | null;
|
||||
iso?: number | null;
|
||||
width?: number | null;
|
||||
height?: number | null;
|
||||
exposureBias?: number | null;
|
||||
exposureTime?: number | null;
|
||||
}
|
||||
|
||||
export interface RealEstateGrouping {
|
||||
stacks: { frameIds: string[] }[];
|
||||
aside: string[];
|
||||
}
|
||||
|
||||
export interface Me {
|
||||
|
||||
@@ -9,6 +9,9 @@
|
||||
//! Settings from an op log:
|
||||
//! in: {"id": "...", "base": {..settings..} | null, "commands": [{"command": "develop.set", "params": {..}}, ..]}
|
||||
//! out: {"id": "...", "settings": {..}, "skipped": [indexes of commands that were refused], "unedited": bool}
|
||||
//! Capture metadata (LightCraft: EXIF, then IPTC, then XMP, including CR3 and a loose XMP sidecar):
|
||||
//! in: {"id": "...", "meta": {"input": "/abs/photo.cr3"}}
|
||||
//! out: {"id": "...", "capture": { "cameraMake": "..", "exposureTime": 0.01, "exposureBias": -2, .. }}
|
||||
|
||||
use std::io::{BufRead, Write};
|
||||
|
||||
@@ -149,6 +152,23 @@ fn run(job: &Job) -> Result<(u32, u32), String> {
|
||||
Ok((px.width, px.height))
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct MetaRequest {
|
||||
id: String,
|
||||
meta: MetaJob,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct MetaJob {
|
||||
input: String,
|
||||
}
|
||||
|
||||
/// Capture metadata of one file. The same JSON the browser engine returns.
|
||||
fn capture_file(path: &str) -> Result<serde_json::Value, String> {
|
||||
let bytes = std::fs::read(path).map_err(|e| format!("{path}: {e}"))?;
|
||||
Ok(photoreport_engine::capture::read_capture(&bytes))
|
||||
}
|
||||
|
||||
fn main() {
|
||||
let stdout = std::io::stdout();
|
||||
let mut out = stdout.lock();
|
||||
@@ -171,6 +191,20 @@ fn main() {
|
||||
continue;
|
||||
}
|
||||
};
|
||||
if value.get("meta").is_some() {
|
||||
let reply = match serde_json::from_value::<MetaRequest>(value) {
|
||||
Ok(req) => match capture_file(&req.meta.input) {
|
||||
Ok(capture) => serde_json::json!({ "id": req.id, "capture": capture }),
|
||||
Err(error) => serde_json::json!({ "id": req.id, "error": error }),
|
||||
},
|
||||
Err(e) => {
|
||||
serde_json::json!({ "id": serde_json::Value::Null, "error": format!("bad request: {e}") })
|
||||
}
|
||||
};
|
||||
let _ = writeln!(out, "{reply}");
|
||||
let _ = out.flush();
|
||||
continue;
|
||||
}
|
||||
if value.get("auto").is_some() {
|
||||
let reply = match serde_json::from_value::<AutoRequest>(value) {
|
||||
Ok(req) => match auto(&req.auto) {
|
||||
@@ -219,7 +253,13 @@ fn main() {
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::{DevelopSettings, decode_edge};
|
||||
use super::{DevelopSettings, capture_file, decode_edge};
|
||||
|
||||
#[test]
|
||||
fn a_missing_file_is_an_error() {
|
||||
let err = capture_file("/no/such/photo.cr3").unwrap_err();
|
||||
assert!(err.contains("photo.cr3"), "{err}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_tight_crop_decodes_enough_for_the_output() {
|
||||
|
||||
Reference in new issue
Block a user