qualia_core_db/medical/dicom_part10/
discovery.rs1use std::fs;
4use std::path::{Path, PathBuf};
5
6use super::parser::split_dicom_payload;
7
8pub const DEFAULT_LOCAL_DICOM_DIR: &str = "app-development/DICOM-20250126T150544Z-001";
10
11pub 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
43pub fn is_dicom_part10(bytes: &[u8]) -> bool {
45 bytes.len() >= 132 && &bytes[128..132] == b"DICM"
46}
47
48pub fn dicom_has_pixel_data(data: &[u8]) -> bool {
50 split_dicom_payload(data).is_ok()
51}
52
53pub 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
60pub 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
84fn 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}