Skip to main content

qualia_core_db/medical/dicom_part10/
overlay.rs

1//! DICOM organ inference, torso overlay placement specs, and JSON/chat helpers.
2
3use std::collections::BTreeMap;
4use std::path::Path;
5
6use super::parser::parse_dicom_file;
7use super::types::{
8    DicomError, DicomMetadata, DicomOverlaySpec, DicomPlacement, DicomTagMatcher,
9};
10
11/// Lowercase, alphanumeric-only, whitespace-collapsed form of `value`
12/// — the keyword-matching normal form.
13pub fn normalize_dicom_token(value: &str) -> String {
14    value
15        .to_lowercase()
16        .chars()
17        .map(|c| if c.is_ascii_alphanumeric() { c } else { ' ' })
18        .collect::<String>()
19        .split_whitespace()
20        .collect::<Vec<_>>()
21        .join(" ")
22}
23
24/// Built-in token->organ matcher table (heart, lung, liver, brain,
25/// kidney, ovary, ...) for DICOM text fields.
26pub fn default_organ_matchers() -> Vec<DicomTagMatcher> {
27    vec![
28        DicomTagMatcher {
29            tokens: vec![
30                "heart".into(),
31                "cardiac".into(),
32                "coronary".into(),
33                "aorta".into(),
34            ],
35            organ: Some("Heart".into()),
36        },
37        DicomTagMatcher {
38            tokens: vec![
39                "lung".into(),
40                "pulmonary".into(),
41                "chest ct".into(),
42                "thorax".into(),
43            ],
44            organ: Some("Lung".into()),
45        },
46        DicomTagMatcher {
47            tokens: vec!["liver".into(), "hepatic".into()],
48            organ: Some("Liver".into()),
49        },
50        DicomTagMatcher {
51            tokens: vec![
52                "brain".into(),
53                "cerebral".into(),
54                "cranial".into(),
55                "head".into(),
56            ],
57            organ: Some("Brain (Allen)".into()),
58        },
59        DicomTagMatcher {
60            tokens: vec!["kidney".into(), "renal".into()],
61            organ: Some("Kidney (Left)".into()),
62        },
63        DicomTagMatcher {
64            tokens: vec!["pancrea".into(), "pancreatic".into()],
65            organ: Some("Pancreas".into()),
66        },
67        DicomTagMatcher {
68            tokens: vec!["spleen".into(), "splenic".into()],
69            organ: Some("Spleen".into()),
70        },
71        DicomTagMatcher {
72            tokens: vec!["intestin".into(), "bowel".into(), "abdomen".into()],
73            organ: Some("Small Intestine".into()),
74        },
75        DicomTagMatcher {
76            tokens: vec!["prostate".into()],
77            organ: Some("Prostate".into()),
78        },
79        DicomTagMatcher {
80            tokens: vec!["uterus".into(), "uterine".into()],
81            organ: Some("Uterus".into()),
82        },
83        DicomTagMatcher {
84            tokens: vec!["ovary".into(), "ovarian".into()],
85            organ: Some("Ovary (Left)".into()),
86        },
87    ]
88}
89
90/// Infer the organ from the file's text fields (body part, series/
91/// study descriptions, protocol name) via `matchers`.
92pub fn infer_organ_from_metadata(
93    meta: &DicomMetadata,
94    matchers: &[DicomTagMatcher],
95) -> Option<String> {
96    let haystack = normalize_dicom_token(
97        &[
98            meta.body_part_examined.as_str(),
99            meta.series_description.as_str(),
100            meta.study_description.as_str(),
101            meta.protocol_name.as_str(),
102        ]
103        .iter()
104        .filter(|s| !s.is_empty())
105        .copied()
106        .collect::<Vec<_>>()
107        .join(" "),
108    );
109
110    infer_organ_from_haystack(&haystack, matchers)
111}
112
113/// First-matching-token organ inference over normalized `haystack`.
114pub fn infer_organ_from_haystack(haystack: &str, matchers: &[DicomTagMatcher]) -> Option<String> {
115    let normalized = normalize_dicom_token(haystack);
116    for matcher in matchers {
117        for token in &matcher.tokens {
118            let token_norm = normalize_dicom_token(token);
119            if !token_norm.is_empty() && normalized.contains(&token_norm) {
120                return matcher.organ.clone();
121            }
122        }
123    }
124    None
125}
126
127/// Curated 3D torso-overlay placement per organ label (offset/scale/
128/// rotation), with a generic fallback for unlisted organs.
129pub fn default_placement_for_organ(organ: &str) -> DicomPlacement {
130    let table: BTreeMap<&str, DicomPlacement> = BTreeMap::from([
131        (
132            "Heart",
133            DicomPlacement {
134                offset_x: 0.0,
135                offset_y: 0.05,
136                offset_z: 0.32,
137                scale: 0.9,
138                rotation_y: 0.0,
139            },
140        ),
141        (
142            "Lung",
143            DicomPlacement {
144                offset_x: 0.0,
145                offset_y: 0.08,
146                offset_z: 0.3,
147                scale: 1.05,
148                rotation_y: 0.0,
149            },
150        ),
151        (
152            "Liver",
153            DicomPlacement {
154                offset_x: 0.12,
155                offset_y: -0.02,
156                offset_z: 0.22,
157                scale: 0.95,
158                rotation_y: -0.35,
159            },
160        ),
161        (
162            "Brain (Allen)",
163            DicomPlacement {
164                offset_x: 0.0,
165                offset_y: 0.18,
166                offset_z: 0.12,
167                scale: 1.0,
168                rotation_y: 0.0,
169            },
170        ),
171        (
172            "Kidney (Left)",
173            DicomPlacement {
174                offset_x: -0.14,
175                offset_y: -0.06,
176                offset_z: 0.18,
177                scale: 0.75,
178                rotation_y: 0.2,
179            },
180        ),
181    ]);
182
183    table.get(organ).copied().unwrap_or(DicomPlacement {
184        offset_x: 0.0,
185        offset_y: 0.0,
186        offset_z: 0.28,
187        scale: 0.85,
188        rotation_y: 0.0,
189    })
190}
191
192/// Assemble a `DicomOverlaySpec` from parsed metadata — organ
193/// inferred when not supplied, placement defaulted per organ.
194pub fn build_overlay_spec(
195    meta: &DicomMetadata,
196    organ: Option<String>,
197    source: &str,
198) -> DicomOverlaySpec {
199    let organ_label = organ.or_else(|| infer_organ_from_metadata(meta, &default_organ_matchers()));
200    let placement = organ_label
201        .as_deref()
202        .map(default_placement_for_organ)
203        .unwrap_or_else(|| default_placement_for_organ("Heart"));
204
205    DicomOverlaySpec {
206        version: "1.0.0".to_string(),
207        organ: organ_label,
208        opacity: 0.72,
209        visible: true,
210        placement,
211        series_instance_uid: if meta.series_instance_uid.is_empty() {
212            None
213        } else {
214            Some(meta.series_instance_uid.clone())
215        },
216        modality: if meta.modality.is_empty() {
217            None
218        } else {
219            Some(meta.modality.clone())
220        },
221        body_part_examined: if meta.body_part_examined.is_empty() {
222            None
223        } else {
224            Some(meta.body_part_examined.clone())
225        },
226        source: Some(source.to_string()),
227    }
228}
229
230/// Read `path`, parse its DICOM metadata, and build the overlay spec.
231pub fn overlay_spec_from_file(path: &Path) -> Result<DicomOverlaySpec, DicomError> {
232    let meta = parse_dicom_file(path)?;
233    Ok(build_overlay_spec(
234        &meta,
235        None,
236        &format!("dicom-file:{}", path.display()),
237    ))
238}
239
240/// `overlay_spec_from_file` serialized to a JSON string (WASM/FFI seam).
241pub fn overlay_spec_json_from_file(path: &Path) -> Result<String, String> {
242    let spec = overlay_spec_from_file(path).map_err(|e| e.to_string())?;
243    serde_json::to_string(&spec).map_err(|e| e.to_string())
244}
245
246/// Parsed `DicomMetadata` from `path` serialized to JSON.
247pub fn metadata_json_from_file(path: &Path) -> Result<String, String> {
248    let meta = parse_dicom_file(path).map_err(|e| e.to_string())?;
249    serde_json::to_string(&meta).map_err(|e| e.to_string())
250}
251
252const IMAGING_CHAT_MARKERS: &[&str] = &[
253    "dicom",
254    "ct scan",
255    " ct ",
256    "mri",
257    "x-ray",
258    "xray",
259    "radiograph",
260    "ultrasound",
261    "pet scan",
262    "mammogram",
263    "imaging study",
264    "chest x",
265    "slice thickness",
266    "window level",
267    "hounsfield",
268];
269
270/// `true` when `text` mentions imaging (marker-substring scan over `IMAGING_CHAT_MARKERS`).
271pub fn chat_mentions_imaging(text: &str) -> bool {
272    let haystack = format!(" {} ", text.to_lowercase());
273    IMAGING_CHAT_MARKERS
274        .iter()
275        .any(|marker| haystack.contains(marker))
276}
277
278/// Build a "chat-inferred" overlay spec when `text` mentions imaging
279/// — organ from keyword match, sensible default opacity/placement.
280pub fn infer_overlay_spec_from_text(
281    text: &str,
282    matchers: &[DicomTagMatcher],
283) -> Option<DicomOverlaySpec> {
284    if !chat_mentions_imaging(text) {
285        return None;
286    }
287
288    let organ = infer_organ_from_haystack(text, matchers);
289    let placement = organ
290        .as_deref()
291        .map(default_placement_for_organ)
292        .unwrap_or_else(|| default_placement_for_organ("Heart"));
293
294    Some(DicomOverlaySpec {
295        version: "1.0.0".to_string(),
296        organ,
297        opacity: 0.72,
298        visible: true,
299        placement,
300        series_instance_uid: None,
301        modality: None,
302        body_part_examined: None,
303        source: Some("chat-inferred".to_string()),
304    })
305}