three-dcf-core 0.2.0

Document-to-dataset encoding library for LLM training data preparation. Converts PDFs, Markdown, HTML into structured formats optimized for machine learning.
Documentation
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
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
use std::collections::HashSet;
use std::convert::TryFrom;
use std::fs::File;
use std::io::{Read, Write};
use std::path::Path;

use indexmap::IndexMap;
use prost::Message;
use serde::{Deserialize, Serialize};

use crate::error::Result;
use crate::proto;

pub type CodeHash = [u8; 32];

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Header {
    pub version: u32,
    pub grid: String,
    pub codeset: String,
}

impl Default for Header {
    fn default() -> Self {
        Self {
            version: 1,
            grid: "coarse".to_string(),
            codeset: "HASH256".to_string(),
        }
    }
}

#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Hash)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum CellType {
    Text,
    Table,
    Figure,
    Footer,
    Header,
}

impl From<CellType> for proto::CellType {
    fn from(value: CellType) -> Self {
        match value {
            CellType::Text => proto::CellType::Text,
            CellType::Table => proto::CellType::Table,
            CellType::Figure => proto::CellType::Figure,
            CellType::Footer => proto::CellType::Footer,
            CellType::Header => proto::CellType::Header,
        }
    }
}

impl From<proto::CellType> for CellType {
    fn from(value: proto::CellType) -> Self {
        match value {
            proto::CellType::Text => CellType::Text,
            proto::CellType::Table => CellType::Table,
            proto::CellType::Figure => CellType::Figure,
            proto::CellType::Footer => CellType::Footer,
            proto::CellType::Header => CellType::Header,
        }
    }
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct PageInfo {
    pub z: u32,
    pub width_px: u32,
    pub height_px: u32,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct CellRecord {
    pub z: u32,
    pub x: i32,
    pub y: i32,
    pub w: u32,
    pub h: u32,
    #[serde(with = "codehash_serde")]
    pub code_id: CodeHash,
    pub rle: u32,
    pub cell_type: CellType,
    pub importance: u8,
}

impl CellRecord {
    pub fn key(&self) -> (u32, i32, i32) {
        (self.z, self.y, self.x)
    }
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct NumGuard {
    pub z: u32,
    pub x: u32,
    pub y: u32,
    pub units: String,
    #[serde(with = "numhash_serde")]
    pub sha1: [u8; 20],
}

#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct Document {
    pub header: Header,
    pub pages: Vec<PageInfo>,
    pub cells: Vec<CellRecord>,
    #[serde(with = "dict_serde")]
    pub dict: IndexMap<CodeHash, String>,
    pub numguards: Vec<NumGuard>,
}

impl Document {
    pub fn new(header: Header) -> Self {
        Self {
            header,
            pages: Vec::new(),
            cells: Vec::new(),
            dict: IndexMap::new(),
            numguards: Vec::new(),
        }
    }

    pub fn add_page(&mut self, info: PageInfo) {
        self.pages.push(info);
    }

    pub fn push_cell(&mut self, cell: CellRecord, payload: String) {
        let code = cell.code_id;
        self.cells.push(cell);
        self.dict.entry(code).or_insert(payload);
    }

    pub fn add_numguard(&mut self, guard: NumGuard) {
        self.numguards.push(guard);
    }

    pub fn payload_for(&self, code_id: &CodeHash) -> Option<&str> {
        self.dict.get(code_id).map(|s| s.as_str())
    }

    pub fn ordered_cells(&self) -> Vec<CellRecord> {
        let mut cells = self.cells.clone();
        cells.sort_by_key(|c| (c.z, c.y, c.x));
        cells
    }

    pub fn to_proto(&self) -> proto::Document {
        let mut prev = (0i64, 0i64, 0i64);
        let cells = self
            .ordered_cells()
            .into_iter()
            .map(|cell| {
                let dz = cell.z as i64 - prev.0;
                let dx = cell.x as i64 - prev.1;
                let dy = cell.y as i64 - prev.2;
                prev = (cell.z as i64, cell.x as i64, cell.y as i64);
                proto::Cell {
                    dz: dz as i32,
                    dx: dx as i32,
                    dy: dy as i32,
                    w: cell.w,
                    h: cell.h,
                    code_id: cell.code_id.to_vec().into(),
                    rle: cell.rle,
                    r#type: proto::CellType::from(cell.cell_type) as i32,
                    importance_q: cell.importance as u32,
                }
            })
            .collect();

        let dict = self
            .dict
            .iter()
            .map(|(code_id, payload)| proto::DictEntry {
                code_id: code_id.to_vec().into(),
                payload_utf8: payload.clone(),
            })
            .collect();

        let numguards = self
            .numguards
            .iter()
            .map(|guard| proto::NumGuard {
                z: guard.z,
                x: guard.x,
                y: guard.y,
                units: guard.units.clone(),
                sha1: guard.sha1.to_vec().into(),
            })
            .collect();

        proto::Document {
            header: Some(proto::Header {
                version: self.header.version,
                grid: self.header.grid.clone(),
                codeset: self.header.codeset.clone(),
            }),
            pages: self
                .pages
                .iter()
                .map(|p| proto::PageInfo {
                    z: p.z,
                    width_px: p.width_px,
                    height_px: p.height_px,
                })
                .collect(),
            cells,
            dict,
            numguards,
        }
    }

    pub fn from_proto(doc: proto::Document) -> Result<Self> {
        let header = doc
            .header
            .map(|h| Header {
                version: h.version,
                grid: h.grid,
                codeset: h.codeset,
            })
            .unwrap_or_default();

        let pages = doc
            .pages
            .into_iter()
            .map(|p| PageInfo {
                z: p.z,
                width_px: p.width_px,
                height_px: p.height_px,
            })
            .collect();

        let mut cells = Vec::new();
        let mut prev = (0i64, 0i64, 0i64);
        for cell in doc.cells {
            prev.0 += cell.dz as i64;
            prev.1 += cell.dx as i64;
            prev.2 += cell.dy as i64;
            let mut code_id = [0u8; 32];
            code_id.copy_from_slice(&cell.code_id);
            cells.push(CellRecord {
                z: prev.0 as u32,
                x: prev.1 as i32,
                y: prev.2 as i32,
                w: cell.w,
                h: cell.h,
                code_id,
                rle: cell.rle,
                cell_type: proto::CellType::try_from(cell.r#type)
                    .map(CellType::from)
                    .unwrap_or(CellType::Text),
                importance: cell.importance_q as u8,
            });
        }

        let mut dict = IndexMap::new();
        for entry in doc.dict {
            let mut code_id = [0u8; 32];
            code_id.copy_from_slice(&entry.code_id);
            dict.insert(code_id, entry.payload_utf8);
        }

        let numguards = doc
            .numguards
            .into_iter()
            .map(|guard| {
                let mut sha = [0u8; 20];
                sha.copy_from_slice(&guard.sha1);
                NumGuard {
                    z: guard.z,
                    x: guard.x,
                    y: guard.y,
                    units: guard.units,
                    sha1: sha,
                }
            })
            .collect();

        Ok(Self {
            header,
            pages,
            cells,
            dict,
            numguards,
        })
    }

    pub fn to_bytes(&self) -> Result<Vec<u8>> {
        let proto = self.to_proto();
        let mut buf = Vec::with_capacity(proto.encoded_len());
        proto.encode(&mut buf)?;
        let mut encoder = zstd::stream::Encoder::new(Vec::new(), 3)?;
        encoder.write_all(&buf)?;
        let data = encoder.finish()?;
        Ok(data)
    }

    pub fn from_bytes(bytes: &[u8]) -> Result<Self> {
        let mut decoder = zstd::stream::Decoder::new(bytes)?;
        let mut buf = Vec::new();
        decoder.read_to_end(&mut buf)?;
        let proto = proto::Document::decode(&*buf)?;
        Self::from_proto(proto)
    }

    pub fn save_bin<P: AsRef<Path>>(&self, path: P) -> Result<()> {
        let bytes = self.to_bytes()?;
        let mut file = File::create(path)?;
        file.write_all(&bytes)?;
        Ok(())
    }

    pub fn load_bin<P: AsRef<Path>>(path: P) -> Result<Self> {
        let mut file = File::open(path)?;
        let mut buf = Vec::new();
        file.read_to_end(&mut buf)?;
        Self::from_bytes(&buf)
    }

    pub fn save_json<P: AsRef<Path>>(&self, path: P) -> Result<()> {
        let mut file = File::create(path)?;
        serde_json::to_writer_pretty(&mut file, self)?;
        Ok(())
    }

    pub fn load_json<P: AsRef<Path>>(path: P) -> Result<Self> {
        let file = File::open(path)?;
        let doc: Document = serde_json::from_reader(file)?;
        Ok(doc)
    }

    pub fn total_cells(&self) -> usize {
        self.cells.len()
    }

    pub fn total_pages(&self) -> usize {
        self.pages.len()
    }

    pub fn ensure_dict_entry(&mut self, payload: &str) -> CodeHash {
        let hash = hash_payload(payload);
        self.dict.entry(hash).or_insert_with(|| payload.to_string());
        hash
    }

    pub fn page_dims(&self, z: u32) -> Option<(u32, u32)> {
        self.pages
            .iter()
            .find(|p| p.z == z)
            .map(|p| (p.width_px, p.height_px))
    }

    pub fn iter_cells(&self) -> impl Iterator<Item = &CellRecord> {
        self.cells.iter()
    }

    pub fn decode_to_text(&self) -> String {
        let ordered = self.ordered_cells();
        self.decode_cells_to_text(&ordered)
    }

    pub fn decode_page_to_text(&self, z: u32) -> String {
        let mut page_cells: Vec<_> = self.cells.iter().filter(|c| c.z == z).cloned().collect();
        page_cells.sort_by_key(|c| (c.y, c.x));
        self.decode_cells_to_text(&page_cells)
    }

    pub fn decode_cells_to_text(&self, cells: &[CellRecord]) -> String {
        let mut lines = Vec::with_capacity(cells.len());
        for cell in cells {
            if let Some(payload) = self.payload_for(&cell.code_id) {
                lines.push(payload.to_string());
            }
        }
        lines.join("\n")
    }

    pub fn cells_in_bbox(&self, z: u32, x0: i32, y0: i32, x1: i32, y1: i32) -> Vec<CellRecord> {
        let (min_x, max_x) = if x0 <= x1 { (x0, x1) } else { (x1, x0) };
        let (min_y, max_y) = if y0 <= y1 { (y0, y1) } else { (y1, y0) };
        let mut matches: Vec<_> = self
            .cells
            .iter()
            .filter(|cell| {
                if cell.z != z {
                    return false;
                }
                let cell_x1 = cell.x + cell.w as i32;
                let cell_y1 = cell.y + cell.h as i32;
                cell.x <= max_x && cell_x1 >= min_x && cell.y <= max_y && cell_y1 >= min_y
            })
            .cloned()
            .collect();
        matches.sort_by_key(|c| (c.y, c.x));
        matches
    }
}

pub fn hash_payload(payload: &str) -> CodeHash {
    let mut hasher = blake3::Hasher::new();
    hasher.update(payload.as_bytes());
    let hash = hasher.finalize();
    let mut bytes = [0u8; 32];
    bytes.copy_from_slice(hash.as_bytes());
    bytes
}

impl Document {
    pub fn retain_dict_for_cells(&mut self) {
        let used: HashSet<_> = self.cells.iter().map(|c| c.code_id).collect();
        self.dict.retain(|code, _| used.contains(code));
    }

    pub fn numguard_mismatches(&self) -> Vec<NumGuardAlert> {
        self.numguard_mismatches_with_units(None)
    }

    pub fn numguard_mismatches_with_units(
        &self,
        whitelist: Option<&HashSet<String>>,
    ) -> Vec<NumGuardAlert> {
        let whitelist =
            whitelist.map(|set| set.iter().map(|s| s.to_lowercase()).collect::<HashSet<_>>());
        let mut alerts = Vec::new();
        for guard in &self.numguards {
            if let Some(ref allowed) = whitelist {
                if !guard.units.is_empty() && !allowed.contains(&guard.units.to_lowercase()) {
                    alerts.push(NumGuardAlert {
                        guard: guard.clone(),
                        observed: None,
                        issue: NumGuardIssue::UnitNotAllowed,
                    });
                    continue;
                }
            }
            let cell = self.cells.iter().find(|c| {
                c.z == guard.z && c.x.max(0) as u32 == guard.x && c.y.max(0) as u32 == guard.y
            });
            if let Some(cell) = cell {
                if let Some(payload) = self.payload_for(&cell.code_id) {
                    if let Some(actual) = crate::numguard::hash_digits_from_payload(payload) {
                        if actual != guard.sha1 {
                            alerts.push(NumGuardAlert {
                                guard: guard.clone(),
                                observed: Some(actual),
                                issue: NumGuardIssue::HashMismatch,
                            });
                        }
                        continue;
                    }
                    alerts.push(NumGuardAlert {
                        guard: guard.clone(),
                        observed: None,
                        issue: NumGuardIssue::MissingPayload,
                    });
                    continue;
                }
            }
            alerts.push(NumGuardAlert {
                guard: guard.clone(),
                observed: None,
                issue: NumGuardIssue::MissingCell,
            });
        }
        alerts
    }
}

#[derive(Debug, Clone)]
pub struct NumGuardAlert {
    pub guard: NumGuard,
    pub observed: Option<[u8; 20]>,
    pub issue: NumGuardIssue,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum NumGuardIssue {
    MissingCell,
    MissingPayload,
    HashMismatch,
    UnitNotAllowed,
}

mod dict_serde {
    use super::CodeHash;
    use indexmap::IndexMap;
    use serde::ser::Serialize;
    use serde::{de::Error, Deserialize, Deserializer, Serializer};

    pub fn serialize<S>(map: &IndexMap<CodeHash, String>, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        let as_vec: Vec<_> = map
            .iter()
            .map(|(code, payload)| (hex::encode(code), payload))
            .collect();
        as_vec.serialize(serializer)
    }

    pub fn deserialize<'de, D>(deserializer: D) -> Result<IndexMap<CodeHash, String>, D::Error>
    where
        D: Deserializer<'de>,
    {
        let raw: Vec<(String, String)> = Vec::deserialize(deserializer)?;
        let mut map = IndexMap::new();
        for (hex_code, payload) in raw {
            let bytes = hex::decode(&hex_code).map_err(D::Error::custom)?;
            if bytes.len() != 32 {
                return Err(D::Error::custom("invalid code hash length"));
            }
            let mut code = [0u8; 32];
            code.copy_from_slice(&bytes);
            map.insert(code, payload);
        }
        Ok(map)
    }
}

mod codehash_serde {
    use serde::{de::Error, Deserialize, Deserializer, Serializer};

    pub fn serialize<S>(hash: &[u8; 32], serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        serializer.serialize_str(&hex::encode(hash))
    }

    pub fn deserialize<'de, D>(deserializer: D) -> Result<[u8; 32], D::Error>
    where
        D: Deserializer<'de>,
    {
        let s = String::deserialize(deserializer)?;
        let bytes = hex::decode(&s).map_err(D::Error::custom)?;
        if bytes.len() != 32 {
            return Err(D::Error::custom("invalid hash length"));
        }
        let mut hash = [0u8; 32];
        hash.copy_from_slice(&bytes);
        Ok(hash)
    }
}

mod numhash_serde {
    use serde::{de::Error, Deserialize, Deserializer, Serializer};

    pub fn serialize<S>(hash: &[u8; 20], serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        serializer.serialize_str(&hex::encode(hash))
    }

    pub fn deserialize<'de, D>(deserializer: D) -> Result<[u8; 20], D::Error>
    where
        D: Deserializer<'de>,
    {
        let s = String::deserialize(deserializer)?;
        let bytes = hex::decode(&s).map_err(D::Error::custom)?;
        if bytes.len() != 20 {
            return Err(D::Error::custom("invalid sha1 length"));
        }
        let mut hash = [0u8; 20];
        hash.copy_from_slice(&bytes);
        Ok(hash)
    }
}