transmutation 0.3.2

High-performance document conversion engine for AI/LLM embeddings - 27 formats supported
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
//! Layout postprocessing - merge, deduplicate, and order detected regions
//!
//! Based on docling/utils/layout_postprocessor.py

#![allow(
    missing_docs,
    clippy::unused_self,
    clippy::unnecessary_wraps,
    clippy::comparison_chain
)]

use std::collections::{HashMap, HashSet};

use rstar::{AABB, RTree};

use crate::document::types::DocItemLabel;
use crate::document::types_extended::{BoundingBox, Cluster};
use crate::error::{Result, TransmutationError};

/// Union-Find data structure for grouping overlapping clusters
struct UnionFind {
    parent: HashMap<usize, usize>,
    rank: HashMap<usize, usize>,
}

impl UnionFind {
    fn new(elements: &[usize]) -> Self {
        let mut parent = HashMap::new();
        let mut rank = HashMap::new();

        for &elem in elements {
            parent.insert(elem, elem);
            rank.insert(elem, 0);
        }

        Self { parent, rank }
    }

    fn find(&mut self, x: usize) -> usize {
        if self.parent[&x] != x {
            let root = self.find(self.parent[&x]);
            self.parent.insert(x, root); // Path compression
        }
        self.parent[&x]
    }

    fn union(&mut self, x: usize, y: usize) {
        let root_x = self.find(x);
        let root_y = self.find(y);

        if root_x == root_y {
            return;
        }

        let rank_x = self.rank[&root_x];
        let rank_y = self.rank[&root_y];

        if rank_x > rank_y {
            self.parent.insert(root_y, root_x);
        } else if rank_x < rank_y {
            self.parent.insert(root_x, root_y);
        } else {
            self.parent.insert(root_y, root_x);
            self.rank.insert(root_x, rank_x + 1);
        }
    }

    fn get_groups(&mut self) -> HashMap<usize, Vec<usize>> {
        let mut groups: HashMap<usize, Vec<usize>> = HashMap::new();

        // Clone keys to avoid borrowing issue
        let keys: Vec<usize> = self.parent.keys().copied().collect();

        for elem in keys {
            let root = self.find(elem);
            groups.entry(root).or_default().push(elem);
        }

        groups
    }
}

/// Spatial indexing for efficient overlap detection
struct SpatialIndex {
    rtree: RTree<ClusterRect>,
}

#[derive(Debug, Clone)]
struct ClusterRect {
    id: usize,
    bbox: BoundingBox,
}

impl rstar::RTreeObject for ClusterRect {
    type Envelope = AABB<[f64; 2]>;

    fn envelope(&self) -> Self::Envelope {
        AABB::from_corners([self.bbox.l, self.bbox.t], [self.bbox.r, self.bbox.b])
    }
}

impl SpatialIndex {
    fn new(clusters: &[Cluster]) -> Self {
        let rects: Vec<ClusterRect> = clusters
            .iter()
            .map(|c| ClusterRect {
                id: c.id,
                bbox: c.bbox,
            })
            .collect();

        let rtree = RTree::bulk_load(rects);

        Self { rtree }
    }

    fn find_overlapping(&self, bbox: &BoundingBox, threshold: f64) -> Vec<usize> {
        let envelope = AABB::from_corners([bbox.l, bbox.t], [bbox.r, bbox.b]);

        self.rtree
            .locate_in_envelope_intersecting(&envelope)
            .filter(|rect| {
                let iou = rect.bbox.intersection_over_union(bbox);
                iou >= threshold
            })
            .map(|rect| rect.id)
            .collect()
    }
}

/// Options for layout postprocessing
#[derive(Debug, Clone)]
pub struct LayoutPostprocessorOptions {
    pub merge_overlap_threshold: f64,
    pub merge_containment_threshold: f64,
    pub deduplicate_threshold: f64,
    pub enable_reading_order: bool,
}

impl Default for LayoutPostprocessorOptions {
    fn default() -> Self {
        Self {
            merge_overlap_threshold: 0.5,
            merge_containment_threshold: 0.8,
            deduplicate_threshold: 0.9,
            enable_reading_order: true,
        }
    }
}

/// Layout postprocessor
#[derive(Debug)]
pub struct LayoutPostprocessor {
    options: LayoutPostprocessorOptions,
}

impl LayoutPostprocessor {
    pub fn new(options: LayoutPostprocessorOptions) -> Self {
        Self { options }
    }

    /// Process clusters: merge overlaps, remove duplicates, assign reading order
    pub fn process(&self, mut clusters: Vec<Cluster>) -> Result<Vec<Cluster>> {
        if clusters.is_empty() {
            return Ok(clusters);
        }

        // 1. Merge overlapping clusters
        clusters = self.merge_overlapping_clusters(clusters)?;

        // 2. Remove duplicates
        clusters = self.remove_duplicate_clusters(clusters)?;

        // 3. Assign reading order
        if self.options.enable_reading_order {
            clusters = self.sort_reading_order(clusters)?;
        }

        Ok(clusters)
    }

    /// Merge clusters with high overlap using Union-Find
    fn merge_overlapping_clusters(&self, clusters: Vec<Cluster>) -> Result<Vec<Cluster>> {
        if clusters.len() < 2 {
            return Ok(clusters);
        }

        let ids: Vec<usize> = clusters.iter().map(|c| c.id).collect();
        let mut uf = UnionFind::new(&ids);

        // Find overlapping pairs
        let spatial_index = SpatialIndex::new(&clusters);

        for cluster in &clusters {
            let overlapping =
                spatial_index.find_overlapping(&cluster.bbox, self.options.merge_overlap_threshold);

            for &other_id in &overlapping {
                if other_id != cluster.id {
                    uf.union(cluster.id, other_id);
                }
            }
        }

        // Group clusters by root
        let groups = uf.get_groups();

        // Merge each group
        let mut merged_clusters = Vec::new();
        for (_root_id, group_ids) in groups {
            let group_clusters: Vec<&Cluster> = group_ids
                .iter()
                .filter_map(|&id| clusters.iter().find(|c| c.id == id))
                .collect();

            let merged = self.merge_cluster_group(&group_clusters)?;
            merged_clusters.push(merged);
        }

        Ok(merged_clusters)
    }

    /// Merge a group of clusters into one
    fn merge_cluster_group(&self, group: &[&Cluster]) -> Result<Cluster> {
        if group.is_empty() {
            return Err(TransmutationError::EngineError {
                engine: "layout-postprocessor".to_string(),
                message: "Cannot merge empty group".to_string(),
                source: None,
            });
        }

        if group.len() == 1 {
            return Ok((*group[0]).clone());
        }

        // Compute merged bounding box
        let mut min_l = f64::MAX;
        let mut min_t = f64::MAX;
        let mut max_r = f64::MIN;
        let mut max_b = f64::MIN;

        for cluster in group {
            min_l = min_l.min(cluster.bbox.l);
            min_t = min_t.min(cluster.bbox.t);
            max_r = max_r.max(cluster.bbox.r);
            max_b = max_b.max(cluster.bbox.b);
        }

        // Choose label with highest priority
        let label = self.choose_dominant_label(group);

        // Merge cells
        let mut all_cells = Vec::new();
        for cluster in group {
            all_cells.extend(cluster.cells.clone());
        }

        // Remove duplicate cells (by index)
        let mut seen_indices = HashSet::new();
        all_cells.retain(|cell| seen_indices.insert(cell.index));

        // Average confidence
        let avg_confidence = group.iter().map(|c| c.confidence).sum::<f32>() / group.len() as f32;

        Ok(Cluster {
            id: group[0].id, // Use first ID
            label,
            bbox: BoundingBox::new(min_l, min_t, max_r, max_b, group[0].bbox.origin),
            cells: all_cells,
            confidence: avg_confidence,
        })
    }

    /// Choose dominant label based on priority hierarchy
    fn choose_dominant_label(&self, group: &[&Cluster]) -> DocItemLabel {
        // Priority order (higher = more important)
        let priority = |label: DocItemLabel| -> usize {
            match label {
                DocItemLabel::Title => 100,
                DocItemLabel::SectionHeader => 90,
                DocItemLabel::Table => 85,
                DocItemLabel::Figure | DocItemLabel::Picture => 80,
                DocItemLabel::Formula => 75,
                DocItemLabel::Code => 70,
                DocItemLabel::ListItem => 60,
                DocItemLabel::Caption => 55,
                DocItemLabel::Footnote => 50,
                DocItemLabel::PageHeader | DocItemLabel::PageFooter => 40,
                DocItemLabel::Paragraph | DocItemLabel::Text => 30,
                _ => 10,
            }
        };

        group
            .iter()
            .max_by_key(|c| priority(c.label))
            .map(|c| c.label)
            .unwrap_or(DocItemLabel::Text)
    }

    /// Remove duplicate clusters (one completely contained in another)
    fn remove_duplicate_clusters(&self, mut clusters: Vec<Cluster>) -> Result<Vec<Cluster>> {
        let mut to_remove = HashSet::new();

        for i in 0..clusters.len() {
            for j in 0..clusters.len() {
                if i == j || to_remove.contains(&i) {
                    continue;
                }

                let containment = clusters[i].bbox.intersection_over_self(&clusters[j].bbox);

                if containment >= self.options.deduplicate_threshold {
                    // Cluster i is contained in j, remove i
                    to_remove.insert(i);
                }
            }
        }

        clusters = clusters
            .into_iter()
            .enumerate()
            .filter(|(i, _)| !to_remove.contains(i))
            .map(|(_, c)| c)
            .collect();

        Ok(clusters)
    }

    /// Sort clusters in reading order (top-to-bottom, left-to-right)
    fn sort_reading_order(&self, mut clusters: Vec<Cluster>) -> Result<Vec<Cluster>> {
        // Detect columns (groups with similar X range)
        let columns = self.detect_columns(&clusters);

        if columns.len() <= 1 {
            // Single column - simple sort
            clusters.sort_by(|a, b| {
                let y_cmp = a.bbox.t.partial_cmp(&b.bbox.t).unwrap();
                if y_cmp == std::cmp::Ordering::Equal {
                    a.bbox.l.partial_cmp(&b.bbox.l).unwrap()
                } else {
                    y_cmp
                }
            });
        } else {
            // Multi-column - sort within each column, then by column order
            clusters.sort_by(|a, b| {
                let col_a = self.get_column_index(&columns, &a.bbox);
                let col_b = self.get_column_index(&columns, &b.bbox);

                if col_a != col_b {
                    col_a.cmp(&col_b)
                } else {
                    // Same column - sort by Y then X
                    let y_cmp = a.bbox.t.partial_cmp(&b.bbox.t).unwrap();
                    if y_cmp == std::cmp::Ordering::Equal {
                        a.bbox.l.partial_cmp(&b.bbox.l).unwrap()
                    } else {
                        y_cmp
                    }
                }
            });
        }

        Ok(clusters)
    }

    /// Detect columns based on X-coordinate clustering
    fn detect_columns(&self, clusters: &[Cluster]) -> Vec<(f64, f64)> {
        // Simplified column detection - group by X ranges
        // TODO: Implement more sophisticated algorithm

        if clusters.is_empty() {
            return Vec::new();
        }

        // For now, assume single column
        let min_x = clusters.iter().map(|c| c.bbox.l).fold(f64::MAX, f64::min);
        let max_x = clusters.iter().map(|c| c.bbox.r).fold(f64::MIN, f64::max);

        vec![(min_x, max_x)]
    }

    /// Get column index for a bounding box
    fn get_column_index(&self, columns: &[(f64, f64)], bbox: &BoundingBox) -> usize {
        let center_x = (bbox.l + bbox.r) / 2.0;

        for (i, (col_l, col_r)) in columns.iter().enumerate() {
            if center_x >= *col_l && center_x <= *col_r {
                return i;
            }
        }

        0 // Default to first column
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::document::types_extended::CoordOrigin;

    #[test]
    fn test_union_find() {
        let mut uf = UnionFind::new(&[1, 2, 3, 4]);
        uf.union(1, 2);
        uf.union(3, 4);

        assert_eq!(uf.find(1), uf.find(2));
        assert_eq!(uf.find(3), uf.find(4));
        assert_ne!(uf.find(1), uf.find(3));

        let groups = uf.get_groups();
        assert_eq!(groups.len(), 2);
    }

    #[test]
    fn test_merge_overlapping() {
        let postprocessor = LayoutPostprocessor::new(LayoutPostprocessorOptions::default());

        let clusters = vec![
            Cluster {
                id: 1,
                label: DocItemLabel::Text,
                bbox: BoundingBox::new(0.0, 0.0, 10.0, 10.0, CoordOrigin::TopLeft),
                cells: Vec::new(),
                confidence: 0.9,
            },
            Cluster {
                id: 2,
                label: DocItemLabel::Text,
                bbox: BoundingBox::new(5.0, 5.0, 15.0, 15.0, CoordOrigin::TopLeft),
                cells: Vec::new(),
                confidence: 0.8,
            },
        ];

        let result = postprocessor.merge_overlapping_clusters(clusters).unwrap();

        // Should be merged into one cluster
        assert_eq!(result.len(), 1);
    }
}