Skip to main content

qualia_core_db/medical/dicom_part10/
discovery.rs

1//! Local private DICOM directory discovery and Part-10 file enumeration helpers.
2
3use std::fs;
4use std::path::{Path, PathBuf};
5
6use super::parser::split_dicom_payload;
7
8/// Default relative path for gitignored private DICOM slices (local dev only).
9pub const DEFAULT_LOCAL_DICOM_DIR: &str = "app-development/DICOM-20250126T150544Z-001";
10
11/// Resolve private local DICOM root: `QUALIA_DICOM_FIXTURE_DIR` env, then workspace-relative default.
12pub fn resolve_local_dicom_dir() -> Option<PathBuf> {
13    if let Ok(dir) = std::env::var("QUALIA_DICOM_FIXTURE_DIR") {
14        let path = PathBuf::from(dir);
15        if path.is_dir() {
16            return path.canonicalize().ok().or(Some(path));
17        }
18    }
19
20    let mut candidates: Vec<PathBuf> = Vec::new();
21    candidates.push(PathBuf::from(DEFAULT_LOCAL_DICOM_DIR));
22    if let Ok(manifest) = std::env::var("CARGO_MANIFEST_DIR") {
23        candidates.push(
24            PathBuf::from(manifest)
25                .join("..")
26                .join("..")
27                .join(DEFAULT_LOCAL_DICOM_DIR),
28        );
29    }
30    if let Ok(cwd) = std::env::current_dir() {
31        candidates.push(cwd.join(DEFAULT_LOCAL_DICOM_DIR));
32        candidates.push(cwd.join("..").join("..").join(DEFAULT_LOCAL_DICOM_DIR));
33    }
34
35    for path in candidates {
36        if path.is_dir() {
37            return path.canonicalize().ok().or(Some(path));
38        }
39    }
40    None
41}
42
43/// Returns true when the byte slice looks like DICOM Part 10 (preamble + `DICM`).
44pub fn is_dicom_part10(bytes: &[u8]) -> bool {
45    bytes.len() >= 132 && &bytes[128..132] == b"DICM"
46}
47
48/// True when the buffer contains extractable Pixel Data for split-ingest.
49pub fn dicom_has_pixel_data(data: &[u8]) -> bool {
50    split_dicom_payload(data).is_ok()
51}
52
53/// Collect up to `max_files` DICOM Part-10 paths under `root` (cold-path helper; may allocate).
54pub fn collect_dicom_paths_under(root: &Path, max_files: usize) -> Vec<PathBuf> {
55    let mut out = Vec::new();
56    collect_dicom_paths_recursive(root, max_files, &mut out);
57    out
58}
59
60/// Image slices only (Pixel Data present), preferring `IM*` filenames typical of PACS export.
61pub fn collect_dicom_image_paths_under(root: &Path, max_files: usize) -> Vec<PathBuf> {
62    let mut all = Vec::new();
63    collect_dicom_paths_recursive(root, max_files.saturating_mul(8).max(32), &mut all);
64    let mut images: Vec<PathBuf> = all
65        .into_iter()
66        .filter(|path| {
67            fs::read(path)
68                .ok()
69                .map(|bytes| dicom_has_pixel_data(&bytes))
70                .unwrap_or(false)
71        })
72        .collect();
73    images.sort_by_key(|p| {
74        let name = p.file_name().and_then(|s| s.to_str()).unwrap_or("");
75        (
76            !(name.starts_with("IM") || name.starts_with("im")),
77            name.to_string(),
78        )
79    });
80    images.truncate(max_files);
81    images
82}
83
84/// Bounded depth-first walk collecting paths whose bytes pass the
85/// `DICM` magic check into `out` (stops at `max_files`).
86fn collect_dicom_paths_recursive(dir: &Path, max_files: usize, out: &mut Vec<PathBuf>) {
87    if out.len() >= max_files {
88        return;
89    }
90    let entries = match fs::read_dir(dir) {
91        Ok(e) => e,
92        Err(_) => return,
93    };
94    for entry in entries.flatten() {
95        if out.len() >= max_files {
96            break;
97        }
98        let path = entry.path();
99        if path.is_dir() {
100            collect_dicom_paths_recursive(&path, max_files, out);
101        } else if path.is_file() {
102            if let Ok(bytes) = fs::read(&path) {
103                if is_dicom_part10(&bytes) {
104                    out.push(path);
105                }
106            }
107        }
108    }
109}