// Copyright (c) 2026 LlamaIndex, Inc. All rights reserved. // Licensed under the OCRia-1 Model and Code License (LICENSE at the root of this repository). // This is not open-source software: see the license for permitted uses. use std::slice; // Caller supplies contiguous float32 attention and same-shape float64 density. // Seed is a positive maximum; bounds are exclusive cell edges in x/y order. #[no_mangle] pub unsafe extern "C" fn add_component_centroid( h: usize, w: usize, map: *const f32, seed: usize, density: *mut f64, bounds: *mut i64, center: *mut f64, ) -> usize { let m = slice::from_raw_parts(map, h * w); let d = slice::from_raw_parts_mut(density, h * w); let threshold = 0.3f32 * m[seed]; let mut total = 0.0f64; let mut visited = vec![false; m.len()]; let mut queue = vec![seed]; visited[seed] = true; let mut k = 0; let mut x0 = seed % w; let mut y0 = seed / w; let mut x1 = x0 + 1; let mut y1 = y0 + 1; while k < queue.len() { let j = queue[k]; k += 1; total += m[j] as f64; let x = j % w; let y = j / w; x0 = x0.min(x); y0 = y0.min(y); x1 = x1.max(x + 1); y1 = y1.max(y + 1); for yy in y.saturating_sub(1)..(y + 2).min(h) { for xx in x.saturating_sub(1)..(x + 2).min(w) { let p = yy * w + xx; if !visited[p] && m[p] >= threshold { visited[p] = true; queue.push(p); } } } } for j in queue { d[j] += m[j] as f64 / total; } for (k, v) in [x0, y0, x1, y1].iter().enumerate() { *bounds.add(k) = *v as i64; } let y = seed / w; let x = seed % w; let mut mass = 0.0; let mut weighted_x = 0.0; let mut weighted_y = 0.0; for yy in y.saturating_sub(1)..(y + 2).min(h) { for xx in x.saturating_sub(1)..(x + 2).min(w) { let value = m[yy * w + xx] as f64; mass += value; weighted_x += value * (xx as f64 + 0.5); weighted_y += value * (yy as f64 + 0.5); } } *center = weighted_x / mass; *center.add(1) = weighted_y / mass; seed } // Sparse rows share one scratch grid; accumulation follows transcript order. // Python validates offsets, cell indices, seeds, and output capacities. #[no_mangle] pub unsafe extern "C" fn add_components( h: usize, w: usize, words: usize, offsets: *const i64, indices: *const i64, values: *const f32, seeds: *const i64, density: *mut f64, bounds: *mut i64, centers: *mut f64, ) -> bool { let offsets = slice::from_raw_parts(offsets, words + 1); let indices = slice::from_raw_parts(indices, offsets[words] as usize); let values = slice::from_raw_parts(values, indices.len()); let mut grid = vec![0.0f32; h * w]; for u in 0..words { let start = offsets[u] as usize; let end = offsets[u + 1] as usize; for j in start..end { grid[indices[j] as usize] = values[j]; } let seed = *seeds.add(u) as usize; if !grid[seed].is_finite() || grid[seed] <= 0.0 { return false; } add_component_centroid( h, w, grid.as_ptr(), seed, density, bounds.add(u * 4), centers.add(u * 2), ); for j in start..end { grid[indices[j] as usize] = 0.0; } } true }