Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
57 changes: 57 additions & 0 deletions .github/ISSUE_TEMPLATE/colour-pairs.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
name: Share colour pairs for a camera profile
description: Contribute a pairs file from `lightcraft-cli calibrate --pairs` so a built-in camera profile can be fitted on more photographers' photos.
title: "Colour pairs: <camera model>"
body:
- type: markdown
attributes:
value: |
Make the file with `lightcraft-cli calibrate --pairs <model>-pairs.json "<your photo folders>"`. Zip it, then drag the zip into the box below. This issue and its attachment are public.

**What the file shows about your photos.** It has no images, file names, paths, GPS, serial numbers or dates. It does hold, for each photo:
- up to 4,000 colour samples and 4,000 tone samples taken from the photo, sorted by value. Sorting removes where in the frame each sample came from, but the samples still show which colours and brightness levels the photo contains, roughly like a detailed colour histogram. Nobody has shown that a picture can or can't be pieced back together from them.
- a content ID: a 128-bit hash of the raw file's bytes. Anyone who has the same raw file can tell it is in your pairs file, and the same photo shared in two pairs files can be matched up.
- the camera model, and Sony's DRO setting when the file records it.

See `docs/camera-preview-colour.md`, "Sharing colour pairs", for the exact layout and for how accepted files are recorded.
- type: input
id: model
attributes:
label: Camera model
description: As LightCraft shows it, for example ILCE-7CR.
validations:
required: true
- type: input
id: photos
attributes:
label: Number of photos
description: The count `calibrate --pairs` printed.
validations:
required: true
- type: input
id: version
attributes:
label: LightCraft version
description: From `lightcraft-cli --version`.
validations:
required: true
- type: textarea
id: style
attributes:
label: Picture style (optional)
description: The creative style, picture control or film simulation you mostly shot with, and Sony DRO settings if you know them.
- type: textarea
id: file
attributes:
label: Pairs file
description: Drag the zipped pairs file here.
validations:
required: true
- type: checkboxes
id: licence
attributes:
label: Licence
options:
- label: I took these photos and I release this pairs file under CC0 1.0 (public domain dedication).
required: true
- label: I have read what the file shows about my photos (above) and agree to it being public here and used to fit a built-in profile.
required: true
115 changes: 106 additions & 9 deletions apps/lightcraft-cli/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
//! lightcraft-cli denoise-serve [--model ID] [--models DIR] [--listen ADDR] [--token-env VAR] [--run-on auto|gpu|cpu]
//! lightcraft-cli commands [--json]
//! lightcraft-cli controls [--json]
//! lightcraft-cli calibrate [--max N] [--out DIR] FOLDERS/FILES…
//! lightcraft-cli calibrate [--max N] [--out DIR] [--pairs FILE] [--from-pairs FILE]… FOLDERS/FILES…
//! lightcraft-cli bench-cull FOLDER [--files K] [--n N] [--copy M] [--work DIR] [--json FILE]
//! ```
#![forbid(unsafe_code)]
Expand Down Expand Up @@ -106,12 +106,18 @@ USAGE:
--max-connections N concurrent clients (default 8)
lightcraft-cli commands [--json] list every command id with its parameters
lightcraft-cli controls [--json] list every develop control id with its range
lightcraft-cli calibrate [--max N] [--out DIR] FOLDERS/FILES…
lightcraft-cli calibrate [--max N] [--out DIR] [--pairs FILE] [--from-pairs FILE]… [FOLDERS/FILES…]
Fit a colour profile per camera model from raw files and their embedded camera JPEGs
(Sony ARW, Nikon NEF, Fujifilm RAF, Canon CRW): up to N files spread over the folders (default 300; 0 = all), pooled per
model, written as <model>.json to DIR (default: the profiles folder LightCraft reads,
<config>/camera-profiles, or $LIGHTCRAFT_CAMERA_PROFILES). Raws of a profiled model then
take their colour from the profile and only their tone from their own JPEG.
--pairs FILE also write the sampled colour pairs to FILE, to share: per photo its camera model,
an id (a hash of the raw's bytes, not its name), Sony's DRO flag and the colour and tone samples;
no image, file name, GPS, serial number or date. Without --out, only FILE is written
(no profile is fitted or installed).
--from-pairs FILE pool the samples of a file written by --pairs (repeat for several, mix with folders);
the profile is the same as from the same raws. Photos listed twice count once.
lightcraft-cli bench-cull FOLDER [--files K] [--n N] [--copy M] [--work DIR] [--json FILE]
Time what culling a shoot costs on its own files: reading the folder (browse), the first
screen of grid thumbnails, camera previews at loupe sizes and full size, a loupe render,
Expand Down Expand Up @@ -260,18 +266,22 @@ fn calibrate(args: &[String]) -> Result<(), String> {
let mut max = 300usize;
let mut out: Option<std::path::PathBuf> = None;
let mut inputs = Vec::new();
let mut pairs_out: Option<std::path::PathBuf> = None;
let mut pairs_in: Vec<std::path::PathBuf> = Vec::new();
let mut i = 0;
while i < args.len() {
match args[i].as_str() {
"--pairs" => pairs_out = Some(take_value(args, &mut i, "--pairs")?.into()),
"--from-pairs" => pairs_in.push(take_value(args, &mut i, "--from-pairs")?.into()),
"--max" => max = take_value(args, &mut i, "--max")?.parse().map_err(|_| "--max needs a number".to_string())?,
"--out" => out = Some(take_value(args, &mut i, "--out")?.into()),
a if a.starts_with("--") => return Err(format!("unknown option `{a}`")),
f => inputs.push(f.to_string()),
}
i += 1;
}
if inputs.is_empty() {
return Err("calibrate needs folders or raw files".into());
if inputs.is_empty() && pairs_in.is_empty() {
return Err("calibrate needs folders, raw files or --from-pairs FILE".into());
}
let mut files = Vec::new();
for input in &inputs {
Expand All @@ -284,8 +294,23 @@ fn calibrate(args: &[String]) -> Result<(), String> {
// spread over all folders (dates, scenes) rather than the first N
files = (0..max).filter_map(|k| files.get(k * found / max).cloned()).collect();
}
eprintln!("calibrate: {} of {found} raw files", files.len());
let dir = out.or_else(lightcraft_engine::camera_profiles::dir).ok_or("no profiles folder: pass --out DIR")?;
if !inputs.is_empty() {
eprintln!("calibrate: {} of {found} raw files", files.len());
}
// `--pairs` alone only exports: no profile is fitted into the folder LightCraft reads
let fit = pairs_out.is_none() || out.is_some();
let dir = if fit { Some(out.or_else(lightcraft_engine::camera_profiles::dir).ok_or("no profiles folder: pass --out DIR")?) } else { None };
// pairs files first, so a bad one fails before any raw file is decoded (the pool's order doesn't matter)
let mut pool = lightcraft_engine::camera_profiles::Pool::default();
for path in &pairs_in {
let size = std::fs::metadata(path).map_err(|e| format!("{}: {e}", path.display()))?.len();
if size > lightcraft_engine::camera_pairs::MAX_FILE {
return Err(format!("{}: {size} bytes is too large for a pairs file", path.display()));
}
let bytes = std::fs::read(path).map_err(|e| format!("{}: {e}", path.display()))?;
let n = pool.add_pairs_file(&bytes, &path.display().to_string())?;
eprintln!("calibrate: {}: {n} photo(s) from a pairs file", path.display());
}
let workers = std::thread::available_parallelism().map_or(4, |n| n.get()).clamp(1, 6);
let next = std::sync::atomic::AtomicUsize::new(0);
let done = std::sync::atomic::AtomicUsize::new(0);
Expand All @@ -298,9 +323,12 @@ fn calibrate(args: &[String]) -> Result<(), String> {
let result = std::fs::read(path).map_err(|e| e.to_string()).and_then(|bytes| pool.add(&bytes));
let n = done.fetch_add(1, std::sync::atomic::Ordering::Relaxed) + 1;
match result {
Ok(Some(added)) if added.colour => eprintln!("[{n}/{}] {} ({})", files.len(), path.display(), added.model),
Ok(Some(added)) => {
eprintln!("[{n}/{}] {} ({}, tone only: too dark or colourless)", files.len(), path.display(), added.model)
let note = if added.colour { "" } else { ", tone only: too dark or colourless" };
eprintln!("[{n}/{}] {} ({}{note})", files.len(), path.display(), added.model);
if pairs_out.is_some() && !lightcraft_engine::camera_pairs::shareable_model(&added.model) {
eprintln!("{}: left out of --pairs: a pairs file can't hold its camera model", path.display());
}
}
Ok(None) => eprintln!("[{n}/{}] {}: skipped (no usable or a black-and-white camera JPEG)", files.len(), path.display()),
Err(e) => eprintln!("[{n}/{}] {}: {e}", files.len(), path.display()),
Expand All @@ -312,10 +340,34 @@ fn calibrate(args: &[String]) -> Result<(), String> {
.collect();
handles.into_iter().filter_map(|h| h.join().ok()).collect()
});
let mut pool = lightcraft_engine::camera_profiles::Pool::default();
for p in pools {
pool.merge(p);
}
calibrate_outputs(&pool, pairs_out.as_deref(), dir)
}

/// What `calibrate` writes from its pooled photos: the pairs file, if asked for, then the profiles, if a folder is set.
fn calibrate_outputs(
pool: &lightcraft_engine::camera_profiles::Pool,
pairs_out: Option<&Path>,
dir: Option<std::path::PathBuf>,
) -> Result<(), String> {
if let Some(path) = pairs_out {
let bytes = pool.pairs_file()?;
if let Some(parent) = path.parent().filter(|p| !p.as_os_str().is_empty()) {
std::fs::create_dir_all(parent).map_err(|e| format!("{}: {e}", parent.display()))?;
}
let tmp = path.with_extension("tmp");
std::fs::write(&tmp, &bytes).map_err(|e| format!("{}: {e}", tmp.display()))?;
std::fs::rename(&tmp, path).map_err(|e| format!("{}: {e}", path.display()))?;
let photos = pool.shareable_photos().len();
println!("{photos} photos, {} bytes of calibration samples → {}", bytes.len(), path.display());
// photos only a pairs file can't hold still fit, when there is a folder to fit into
if photos == 0 && (dir.is_none() || pool.photos().is_empty()) {
return Err("no photo contributed calibration samples".into());
}
}
let Some(dir) = dir else { return Ok(()) };
let mut written = 0;
for result in pool.fit(5) {
match result {
Expand Down Expand Up @@ -1185,6 +1237,51 @@ mod launch_profile_tests {

#[cfg(test)]
mod tests {
/// Photos no pairs file can hold (a camera model it refuses) leave the export empty but still fit; with nothing to
/// fit, or no folder to fit into, an empty export is the error it was.
#[test]
fn calibrate_fits_photos_a_pairs_file_cannot_hold() {
use lightcraft_engine::camera_profiles::{PhotoPairs, Pool};
let mut state = 12345u32;
let mut next = move || {
state = state.wrapping_mul(1664525).wrapping_add(1013904223);
f64::from(state >> 8) / f64::from(1u32 << 24)
};
let photos: Vec<PhotoPairs> = (0..6)
.map(|k| PhotoPairs {
model: "M".repeat(65),
id: format!("{:032x}", k + 1),
dro: None,
tone: Vec::new(),
pairs: (0..400)
.map(|_| {
let c = [next() * 0.8 + 0.02, next() * 0.8 + 0.02, next() * 0.8 + 0.02];
let y = [c[0] * 1.4 - c[1] * 0.2, c[1] * 1.3 - c[2] * 0.1, c[2] * 1.2 + 0.05 * c[0]].map(|v: f64| v.clamp(0.001, 1.0));
(c, y)
})
.collect(),
})
.collect();
let mut pool = Pool::default();
pool.add_photos(photos);
assert!(pool.shareable_photos().is_empty());
let base = std::env::temp_dir().join(format!("lc-calibrate-outputs-{}", std::process::id()));
std::fs::create_dir_all(&base).unwrap();
let (pairs, profiles) = (base.join("out.pairs"), base.join("profiles"));
let refused = "no photo contributed calibration samples";

let both = super::calibrate_outputs(&pool, Some(&pairs), Some(profiles.clone()));
let written = std::fs::read_dir(&profiles).map_or(0, |d| d.count());
let pairs_only = super::calibrate_outputs(&pool, Some(&pairs), None);
let empty = super::calibrate_outputs(&Pool::default(), Some(&pairs), Some(profiles.clone()));
let _ = std::fs::remove_dir_all(&base);

assert_eq!(both, Ok(()));
assert_eq!(written, 1, "the fit ran");
assert_eq!(pairs_only, Err(refused.to_string()));
assert_eq!(empty, Err(refused.to_string()));
}

/// `render` and `merge` read the lens database the desktop app downloaded, as the desktop does (the same raw
/// gets the same profile everywhere), but never fetch it.
#[test]
Expand Down
96 changes: 96 additions & 0 deletions apps/lightcraft-cli/tests/it/cli.rs
Original file line number Diff line number Diff line change
Expand Up @@ -183,6 +183,102 @@ fn calibrate_reads_raf_inputs_and_reports_bad_files() {
assert!(!out.join("X-T4.json").exists(), "bad input must not produce a profile");
}

#[test]
fn calibrate_pairs_options_check_their_inputs() {
let run = |args: &[&std::ffi::OsStr]| Command::new(binary()).arg("calibrate").args(args).output().unwrap();
let text = |o: &std::process::Output| String::from_utf8_lossy(&o.stderr).into_owned();
// nothing to fit from
let r = run(&[]);
assert!(!r.status.success() && text(&r).contains("--from-pairs"), "{}", text(&r));
// `--pairs` needs a file name
let r = run(&["--pairs".as_ref()]);
assert!(!r.status.success() && text(&r).contains("--pairs"), "{}", text(&r));
// a missing, foreign or damaged pairs file is refused with its name, and writes nothing
let out = tmp("pairs-profiles");
for (name, content) in
[("junk.pairs", Some(&b"{not json"[..])), ("foreign.pairs", Some(&br#"{"format":"x","version":1,"photos":[]}"#[..])), ("missing.pairs", None)]
{
let path = tmp(name);
if let Some(c) = content {
std::fs::write(&path, c).unwrap();
}
let r = run(&["--out".as_ref(), out.as_os_str(), "--from-pairs".as_ref(), path.as_os_str()]);
assert!(!r.status.success() && text(&r).contains(name), "{name}: {}", text(&r));
}
assert!(!out.exists(), "a refused pairs file must not write a profile");
}

#[test]
fn calibrate_pairs_only_exports_and_pools_pairs_files() {
use lightcraft_engine::camera_pairs;
use lightcraft_engine::camera_profiles::PhotoPairs;
// six photos of one made-up model, in two files that overlap in one photo
let mut state = 12345u32;
let mut next = move || {
state = state.wrapping_mul(1664525).wrapping_add(1013904223);
f64::from(state >> 8) / f64::from(1u32 << 24)
};
let photos: Vec<PhotoPairs> = (0..6)
.map(|k| PhotoPairs {
model: "TEST-1".into(),
id: format!("{:032x}", k + 1),
dro: None,
tone: Vec::new(),
pairs: (0..400)
.map(|_| {
let c = [next() * 0.8 + 0.02, next() * 0.8 + 0.02, next() * 0.8 + 0.02];
let y = [c[0] * 1.4 - c[1] * 0.2, c[1] * 1.3 - c[2] * 0.1, c[2] * 1.2 + 0.05 * c[0]].map(|v: f64| v.clamp(0.001, 1.0));
let single = |v: [f64; 3]| v.map(|x| f64::from(x as f32));
(single(c), single(y))
})
.collect(),
})
.collect();
let write = |name: &str, p: &[&PhotoPairs]| {
let path = tmp(name);
std::fs::write(&path, camera_pairs::write(p).unwrap()).unwrap();
path
};
let refs: Vec<&PhotoPairs> = photos.iter().collect();
let (a, b, all) = (write("share-a.pairs", &refs[..4]), write("share-b.pairs", &refs[3..]), write("share-all.pairs", &refs));
let fit = |inputs: &[&std::path::Path], dir: &str| {
let out = tmp(dir);
let mut cmd = Command::new(binary());
cmd.args(["calibrate", "--out"]).arg(&out);
for i in inputs {
cmd.arg("--from-pairs").arg(i);
}
let r = cmd.output().unwrap();
assert!(r.status.success(), "{}", String::from_utf8_lossy(&r.stderr));
std::fs::read_to_string(out.join("TEST-1.json")).unwrap()
};
let pooled = fit(&[&a, &b], "pairs-pooled");
assert_eq!(pooled, fit(&[&all], "pairs-all"), "pooling two files of the same photos gives the same profile");
assert_eq!(pooled, fit(&[&b, &a], "pairs-reversed"));
assert!(pooled.contains("\"files\": 6"), "the shared photo counts once: {pooled}");
// `--pairs` alone re-exports the pooled photos and writes no profile
let merged = tmp("share-merged.pairs");
let default_dir = tmp("pairs-default-profiles");
let r = Command::new(binary())
.env("LIGHTCRAFT_CAMERA_PROFILES", &default_dir)
.args(["calibrate", "--from-pairs"])
.arg(&a)
.arg("--from-pairs")
.arg(&b)
.arg("--pairs")
.arg(&merged)
.output()
.unwrap();
assert!(r.status.success(), "{}", String::from_utf8_lossy(&r.stderr));
assert!(!default_dir.exists(), "--pairs without --out must not install a profile");
// the same photos, each one's pairs in value order
let mut sorted = photos;
for photo in &mut sorted {
lightcraft_engine::camera_profiles::canonical_order(&mut photo.pairs);
}
assert_eq!(camera_pairs::read(&std::fs::read(&merged).unwrap(), "merged").unwrap(), sorted);
}

fn mean(path: &std::path::Path) -> f64 {
let d = lightcraft_codecs::decode(&std::fs::read(path).unwrap(), Default::default()).unwrap();
let img = d.to_srgb8();
Expand Down
Loading
Loading