finetype-model 0.1.0

Candle-based transformer model for FineType
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
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
//! Inference utilities for text classification.

use crate::char_cnn::{CharCnn, CharCnnConfig, CharVocab};
use crate::model::{TextClassifier, TextClassifierConfig};
use candle_core::{DType, Device, Tensor};
use candle_nn::VarBuilder;
use finetype_core::{Taxonomy, Tokenizer};
use std::collections::HashMap;
use std::path::Path;
use thiserror::Error;

#[derive(Error, Debug)]
pub enum InferenceError {
    #[error("Model error: {0}")]
    ModelError(#[from] candle_core::Error),
    #[error("Tokenizer error: {0}")]
    TokenizerError(#[from] finetype_core::tokenizer::TokenizerError),
    #[error("Taxonomy error: {0}")]
    TaxonomyError(#[from] finetype_core::taxonomy::TaxonomyError),
    #[error("IO error: {0}")]
    IoError(#[from] std::io::Error),
    #[error("Invalid model path: {0}")]
    InvalidPath(String),
}

/// Classification result.
#[derive(Debug, Clone)]
pub struct ClassificationResult {
    pub label: String,
    pub confidence: f32,
    pub all_scores: Vec<(String, f32)>,
}

/// Classifier for text classification inference.
pub struct Classifier {
    model: TextClassifier,
    tokenizer: Tokenizer,
    index_to_label: HashMap<usize, String>,
    device: Device,
    max_seq_length: usize,
}

impl Classifier {
    /// Load a classifier from a directory containing model weights and taxonomy.
    pub fn load<P: AsRef<Path>>(model_dir: P) -> Result<Self, InferenceError> {
        let model_dir = model_dir.as_ref();

        // Determine device
        let device = Self::get_device();

        // Load taxonomy
        let taxonomy_path = model_dir.join("taxonomy.yaml");
        let taxonomy = if taxonomy_path.exists() {
            Taxonomy::from_file(&taxonomy_path)?
        } else {
            // Try default labels path
            Taxonomy::from_file(model_dir.join("labels.yaml"))?
        };

        let n_classes = taxonomy.len();
        let index_to_label = taxonomy.index_to_label();

        // Load config
        // TODO: Load from config file if available
        let config = TextClassifierConfig {
            n_classes,
            max_seq_length: 128, // Must match training config
            ..Default::default()
        };

        // Load model weights
        let weights_path = model_dir.join("model.safetensors");
        let vb = if weights_path.exists() {
            unsafe { VarBuilder::from_mmaped_safetensors(&[weights_path], DType::F32, &device)? }
        } else {
            // Initialize with random weights for testing
            VarBuilder::zeros(DType::F32, &device)
        };

        let model = TextClassifier::new(config.clone(), vb)?;
        let tokenizer = Tokenizer::bert_cased()?;

        Ok(Self {
            model,
            tokenizer,
            index_to_label,
            device,
            max_seq_length: config.max_seq_length,
        })
    }

    /// Classify a single text input.
    pub fn classify(&self, text: &str) -> Result<ClassificationResult, InferenceError> {
        let results = self.classify_batch(&[text.to_string()])?;
        Ok(results.into_iter().next().unwrap())
    }

    /// Classify multiple text inputs.
    pub fn classify_batch(
        &self,
        texts: &[String],
    ) -> Result<Vec<ClassificationResult>, InferenceError> {
        let batch_size = texts.len();

        // Tokenize all inputs
        let mut all_ids = Vec::with_capacity(batch_size);
        let mut all_masks = Vec::with_capacity(batch_size);

        for text in texts {
            let (ids, mask) = self.tokenizer.encode_padded(text, self.max_seq_length)?;
            all_ids.push(ids);
            all_masks.push(mask);
        }

        // Create tensors
        let input_ids = Tensor::new(
            all_ids.into_iter().flatten().collect::<Vec<u32>>(),
            &self.device,
        )?
        .reshape((batch_size, self.max_seq_length))?;

        let attention_mask = Tensor::new(
            all_masks.into_iter().flatten().collect::<Vec<u32>>(),
            &self.device,
        )?
        .reshape((batch_size, self.max_seq_length))?
        .to_dtype(DType::F32)?;

        // Run inference
        let probs = self.model.infer(&input_ids, Some(&attention_mask))?;
        let probs = probs.to_vec2::<f32>()?;

        // Convert to results
        let mut results = Vec::with_capacity(batch_size);
        for prob_row in probs {
            let (max_idx, max_prob) = prob_row
                .iter()
                .enumerate()
                .max_by(|(_, a), (_, b)| a.partial_cmp(b).unwrap())
                .unwrap();

            let label = self
                .index_to_label
                .get(&max_idx)
                .cloned()
                .unwrap_or_else(|| "unknown".to_string());

            let all_scores: Vec<(String, f32)> = prob_row
                .iter()
                .enumerate()
                .map(|(i, &p)| {
                    let lbl = self
                        .index_to_label
                        .get(&i)
                        .cloned()
                        .unwrap_or_else(|| format!("class_{}", i));
                    (lbl, p)
                })
                .collect();

            results.push(ClassificationResult {
                label,
                confidence: *max_prob,
                all_scores,
            });
        }

        Ok(results)
    }

    /// Get the best device available.
    fn get_device() -> Device {
        #[cfg(feature = "cuda")]
        {
            if let Ok(device) = Device::new_cuda(0) {
                return device;
            }
        }

        #[cfg(feature = "metal")]
        {
            if let Ok(device) = Device::new_metal(0) {
                return device;
            }
        }

        Device::Cpu
    }

    /// Get the tokenizer.
    pub fn tokenizer(&self) -> &Tokenizer {
        &self.tokenizer
    }

    /// Get the device being used.
    pub fn device(&self) -> &Device {
        &self.device
    }
}

/// CharCNN-based classifier for text classification inference.
pub struct CharClassifier {
    model: CharCnn,
    vocab: CharVocab,
    index_to_label: HashMap<usize, String>,
    device: Device,
    max_seq_length: usize,
}

impl CharClassifier {
    /// Load a CharCNN classifier from embedded byte slices.
    ///
    /// Used by the DuckDB extension where model files are compiled into the binary.
    pub fn from_bytes(
        weights: &[u8],
        labels_json: &[u8],
        config_yaml: &[u8],
    ) -> Result<Self, InferenceError> {
        let device = Self::get_device();

        // Parse labels
        let labels_str = std::str::from_utf8(labels_json).map_err(|e| {
            InferenceError::InvalidPath(format!("Invalid UTF-8 in labels.json: {}", e))
        })?;
        let labels: Vec<String> = serde_json::from_str(labels_str).map_err(|e| {
            InferenceError::InvalidPath(format!("Failed to parse labels.json: {}", e))
        })?;
        let n_classes = labels.len();
        let index_to_label: HashMap<usize, String> = labels.into_iter().enumerate().collect();

        // Parse config
        let config_str = std::str::from_utf8(config_yaml).unwrap_or("");
        let mut vocab_size = 97usize;
        let mut max_seq_length = 128usize;
        let mut embed_dim = 32usize;
        let mut num_filters = 64usize;
        let mut hidden_dim = 128usize;

        for line in config_str.lines() {
            if let Some((key, val)) = line.split_once(':') {
                let key = key.trim();
                let val = val.trim();
                match key {
                    "vocab_size" => vocab_size = val.parse().unwrap_or(97),
                    "max_seq_length" => max_seq_length = val.parse().unwrap_or(128),
                    "embed_dim" => embed_dim = val.parse().unwrap_or(32),
                    "num_filters" => num_filters = val.parse().unwrap_or(64),
                    "hidden_dim" => hidden_dim = val.parse().unwrap_or(128),
                    _ => {}
                }
            }
        }

        let vocab = CharVocab::new();
        let config = CharCnnConfig {
            vocab_size,
            max_seq_length,
            embed_dim,
            num_filters,
            kernel_sizes: vec![2, 3, 4, 5],
            hidden_dim,
            n_classes,
            dropout: 0.0,
        };

        let vb = VarBuilder::from_buffered_safetensors(weights.to_vec(), DType::F32, &device)?;
        let model = CharCnn::new(config, vb)?;

        Ok(Self {
            model,
            vocab,
            index_to_label,
            device,
            max_seq_length,
        })
    }

    /// Load a CharCNN classifier from a directory.
    pub fn load<P: AsRef<Path>>(model_dir: P) -> Result<Self, InferenceError> {
        let model_dir = model_dir.as_ref();
        let device = Self::get_device();

        // Load label mapping — try labels.json first (saved by trainer), then taxonomy.yaml
        let labels_json_path = model_dir.join("labels.json");
        let taxonomy_path = model_dir.join("taxonomy.yaml");
        let (n_classes, index_to_label) = if labels_json_path.exists() {
            let content = std::fs::read_to_string(&labels_json_path)?;
            let labels: Vec<String> = serde_json::from_str(&content).map_err(|e| {
                InferenceError::InvalidPath(format!("Failed to parse labels.json: {}", e))
            })?;
            let n = labels.len();
            let mapping: HashMap<usize, String> = labels.into_iter().enumerate().collect();
            (n, mapping)
        } else if taxonomy_path.exists() {
            let taxonomy = Taxonomy::from_file(&taxonomy_path)?;
            let n = taxonomy.len();
            (n, taxonomy.index_to_label())
        } else {
            let labels_yaml_path = model_dir.join("labels.yaml");
            let taxonomy = Taxonomy::from_file(&labels_yaml_path)?;
            let n = taxonomy.len();
            (n, taxonomy.index_to_label())
        };

        // Load config from config.yaml if available
        let config_path = model_dir.join("config.yaml");
        let (vocab_size, max_seq_length, embed_dim, num_filters, hidden_dim) =
            if config_path.exists() {
                let config_str = std::fs::read_to_string(&config_path)?;
                let mut vocab_size = 97usize;
                let mut max_seq_length = 128usize;
                let mut embed_dim = 32usize;
                let mut num_filters = 64usize;
                let mut hidden_dim = 128usize;

                for line in config_str.lines() {
                    if let Some((key, val)) = line.split_once(':') {
                        let key = key.trim();
                        let val = val.trim();
                        match key {
                            "vocab_size" => vocab_size = val.parse().unwrap_or(97),
                            "max_seq_length" => max_seq_length = val.parse().unwrap_or(128),
                            "embed_dim" => embed_dim = val.parse().unwrap_or(32),
                            "num_filters" => num_filters = val.parse().unwrap_or(64),
                            "hidden_dim" => hidden_dim = val.parse().unwrap_or(128),
                            _ => {}
                        }
                    }
                }
                (
                    vocab_size,
                    max_seq_length,
                    embed_dim,
                    num_filters,
                    hidden_dim,
                )
            } else {
                (97, 128, 32, 64, 128)
            };

        let vocab = CharVocab::new();

        let config = CharCnnConfig {
            vocab_size,
            max_seq_length,
            embed_dim,
            num_filters,
            kernel_sizes: vec![2, 3, 4, 5],
            hidden_dim,
            n_classes,
            dropout: 0.0, // No dropout during inference
        };

        // Load model weights
        let weights_path = model_dir.join("model.safetensors");
        let vb =
            unsafe { VarBuilder::from_mmaped_safetensors(&[weights_path], DType::F32, &device)? };

        let model = CharCnn::new(config, vb)?;

        Ok(Self {
            model,
            vocab,
            index_to_label,
            device,
            max_seq_length,
        })
    }

    /// Classify a single text input.
    pub fn classify(&self, text: &str) -> Result<ClassificationResult, InferenceError> {
        let results = self.classify_batch(&[text.to_string()])?;
        Ok(results.into_iter().next().unwrap())
    }

    /// Classify multiple text inputs.
    pub fn classify_batch(
        &self,
        texts: &[String],
    ) -> Result<Vec<ClassificationResult>, InferenceError> {
        let batch_size = texts.len();

        // Encode all inputs
        let mut all_ids = Vec::with_capacity(batch_size * self.max_seq_length);
        for text in texts {
            let ids = self.vocab.encode(text, self.max_seq_length);
            all_ids.extend(ids);
        }

        // Create tensor
        let input_ids =
            Tensor::new(all_ids, &self.device)?.reshape((batch_size, self.max_seq_length))?;

        // Run inference
        let probs = self.model.infer(&input_ids)?;
        let probs = probs.to_vec2::<f32>()?;

        // Convert to results
        let mut results = Vec::with_capacity(batch_size);
        for prob_row in probs {
            let (max_idx, max_prob) = prob_row
                .iter()
                .enumerate()
                .max_by(|(_, a), (_, b)| a.partial_cmp(b).unwrap())
                .unwrap();

            let label = self
                .index_to_label
                .get(&max_idx)
                .cloned()
                .unwrap_or_else(|| "unknown".to_string());

            let all_scores: Vec<(String, f32)> = prob_row
                .iter()
                .enumerate()
                .map(|(i, &p)| {
                    let lbl = self
                        .index_to_label
                        .get(&i)
                        .cloned()
                        .unwrap_or_else(|| format!("class_{}", i));
                    (lbl, p)
                })
                .collect();

            results.push(ClassificationResult {
                label,
                confidence: *max_prob,
                all_scores,
            });
        }

        // Post-process: apply format-based corrections for known model confusions
        for (result, text) in results.iter_mut().zip(texts.iter()) {
            post_process(result, text);
        }

        Ok(results)
    }

    /// Get the best device available.
    fn get_device() -> Device {
        #[cfg(feature = "cuda")]
        {
            if let Ok(device) = Device::new_cuda(0) {
                return device;
            }
        }

        #[cfg(feature = "metal")]
        {
            if let Ok(device) = Device::new_metal(0) {
                return device;
            }
        }

        Device::Cpu
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// POST-PROCESSING RULES
// ═══════════════════════════════════════════════════════════════════════════════

/// Apply format-based corrections for known model confusion pairs.
///
/// These rules check the actual input text to resolve confusions where the model
/// struggles but the format provides a definitive signal. Each rule is a simple
/// character/pattern check with no ambiguity.
fn post_process(result: &mut ClassificationResult, text: &str) {
    // Rule 1: rfc_3339 vs iso_8601_offset
    //
    // The only difference is T (ISO 8601) vs space (RFC 3339) between date and time.
    // The model confuses these 100% of the time. A simple character check resolves it.
    //
    // iso_8601_offset: "2024-01-15T10:30:00+05:00" (T separator)
    // rfc_3339:        "2024-01-15 10:30:00+05:00" (space separator)
    if result.label == "datetime.timestamp.iso_8601_offset"
        || result.label == "datetime.timestamp.rfc_3339"
    {
        let trimmed = text.trim();
        // Look for the separator at position 10 (after YYYY-MM-DD)
        if trimmed.len() >= 11 {
            let sep = trimmed.as_bytes()[10];
            if sep == b'T' {
                result.label = "datetime.timestamp.iso_8601_offset".to_string();
            } else if sep == b' ' {
                result.label = "datetime.timestamp.rfc_3339".to_string();
            }
        }
    }

    // Rule 2: hash vs token_hex
    //
    // Cryptographic hashes have fixed lengths: 32 (MD5), 40 (SHA-1), 64 (SHA-256), 128 (SHA-512).
    // Hex tokens have variable non-standard lengths. The model confuses these (58x token_hex→hash).
    // A simple length check on the trimmed hex string resolves this definitively.
    if result.label == "technology.cryptographic.hash"
        || result.label == "technology.cryptographic.token_hex"
    {
        let trimmed = text.trim();
        let is_hex = !trimmed.is_empty()
            && trimmed
                .bytes()
                .all(|b| b.is_ascii_hexdigit() && !b.is_ascii_uppercase());
        if is_hex {
            let len = trimmed.len();
            if len == 32 || len == 40 || len == 64 || len == 128 {
                result.label = "technology.cryptographic.hash".to_string();
            } else {
                result.label = "technology.cryptographic.token_hex".to_string();
            }
        }
    }

    // Rule 3: emoji vs gender_symbol
    //
    // Gender symbols are a specific set: ♂ (U+2642), ♀ (U+2640), ⚧ (U+26A7), ⚪ (U+26AA).
    // The model confuses emojis as gender symbols (96x). A character identity check resolves this.
    if result.label == "identity.person.gender_symbol"
        || result.label == "representation.text.emoji"
    {
        let trimmed = text.trim();
        let is_gender_symbol = trimmed.chars().count() == 1
            && matches!(trimmed.chars().next(), Some('♂' | '♀' | '⚧' | '⚪'));
        if is_gender_symbol {
            result.label = "identity.person.gender_symbol".to_string();
        } else if !trimmed.is_empty() {
            result.label = "representation.text.emoji".to_string();
        }
    }

    // Rule 4: ISSN vs postal_code
    //
    // ISSN has a distinctive format: XXXX-XXX[0-9X] (4 digits, hyphen, 3 digits, check char).
    // Postal codes are typically 5 digits (ZIP), 5-4 (ZIP+4), or other country formats.
    // The model confuses these bidirectionally (24x issn→postal, 23x postal→issn).
    // A regex-free pattern check on the hyphenated format resolves this.
    if result.label == "technology.code.issn"
        || result.label == "geography.address.postal_code"
    {
        let trimmed = text.trim();
        let bytes = trimmed.as_bytes();
        // ISSN pattern: exactly 9 chars, format DDDD-DDD[DX]
        let is_issn = bytes.len() == 9
            && bytes[4] == b'-'
            && bytes[..4].iter().all(|b| b.is_ascii_digit())
            && bytes[5..8].iter().all(|b| b.is_ascii_digit())
            && (bytes[8].is_ascii_digit() || bytes[8] == b'X');
        if is_issn {
            result.label = "technology.code.issn".to_string();
        } else {
            result.label = "geography.address.postal_code".to_string();
        }
    }

    // Rule 5: longitude vs latitude (partial)
    //
    // Latitude is bounded to -90..+90, longitude to -180..+180.
    // If a value's absolute magnitude exceeds 90, it's definitively longitude.
    // Values within ±90 remain as the model predicted (ambiguous at single-value level).
    // The model confuses these (30x lon→lat, 21x lat→lon).
    if result.label == "geography.coordinate.latitude"
        || result.label == "geography.coordinate.longitude"
    {
        let trimmed = text.trim();
        if let Ok(val) = trimmed.parse::<f64>() {
            if val.abs() > 90.0 {
                result.label = "geography.coordinate.longitude".to_string();
            }
        }
    }

    // Rule 6: email rescue
    //
    // The `@` sign is a definitive format signal for email addresses. The model sometimes
    // misclassifies emails with short/uncommon domains as hostname, username, or slug.
    // Only applies to specific confusion labels (not container types, CSV, JSON, etc.).
    // The text must look like a standalone email, not a substring within structured data.
    if result.label == "technology.internet.hostname"
        || result.label == "identity.person.username"
        || result.label == "technology.internet.slug"
    {
        let trimmed = text.trim();
        if let Some(at_pos) = trimmed.find('@') {
            let local = &trimmed[..at_pos];
            let domain = &trimmed[at_pos + 1..];
            // Strict email check: standalone email, not embedded in structured data
            let looks_like_email = !local.is_empty()
                && !domain.is_empty()
                && domain.contains('.')
                && trimmed.find('@') == trimmed.rfind('@') // exactly one @
                && !trimmed.contains(' ')
                && !trimmed.contains("://")
                && !trimmed.contains(',')
                && !trimmed.contains('=')
                && !trimmed.contains('&')
                && !trimmed.contains('{')
                && !trimmed.contains('|')
                && !trimmed.contains(';');
            if looks_like_email {
                result.label = "identity.person.email".to_string();
            }
        }
    }
}

#[cfg(test)]
mod post_process_tests {
    use super::*;

    fn make_result(label: &str) -> ClassificationResult {
        ClassificationResult {
            label: label.to_string(),
            confidence: 0.9,
            all_scores: vec![],
        }
    }

    #[test]
    fn test_iso_8601_offset_with_t_separator() {
        let mut result = make_result("datetime.timestamp.rfc_3339");
        post_process(&mut result, "2024-01-15T10:30:00+05:00");
        assert_eq!(result.label, "datetime.timestamp.iso_8601_offset");
    }

    #[test]
    fn test_rfc_3339_with_space_separator() {
        let mut result = make_result("datetime.timestamp.iso_8601_offset");
        post_process(&mut result, "2024-01-15 10:30:00+05:00");
        assert_eq!(result.label, "datetime.timestamp.rfc_3339");
    }

    #[test]
    fn test_correct_iso_8601_offset_unchanged() {
        let mut result = make_result("datetime.timestamp.iso_8601_offset");
        post_process(&mut result, "2024-01-15T10:30:00+05:00");
        assert_eq!(result.label, "datetime.timestamp.iso_8601_offset");
    }

    #[test]
    fn test_correct_rfc_3339_unchanged() {
        let mut result = make_result("datetime.timestamp.rfc_3339");
        post_process(&mut result, "2024-01-15 10:30:00+05:00");
        assert_eq!(result.label, "datetime.timestamp.rfc_3339");
    }

    #[test]
    fn test_unrelated_label_unchanged() {
        let mut result = make_result("technology.internet.ip_v4");
        post_process(&mut result, "192.168.1.1");
        assert_eq!(result.label, "technology.internet.ip_v4");
    }

    #[test]
    fn test_short_text_no_crash() {
        let mut result = make_result("datetime.timestamp.rfc_3339");
        post_process(&mut result, "short");
        // No crash, label unchanged (too short to check)
        assert_eq!(result.label, "datetime.timestamp.rfc_3339");
    }

    // ── Rule 2: hash vs token_hex ────────────────────────────────────────────

    #[test]
    fn test_hash_md5_length_32() {
        let mut result = make_result("technology.cryptographic.token_hex");
        post_process(&mut result, "5d41402abc4b2a76b9719d911017c592");
        assert_eq!(result.label, "technology.cryptographic.hash");
    }

    #[test]
    fn test_hash_sha1_length_40() {
        let mut result = make_result("technology.cryptographic.token_hex");
        post_process(&mut result, "aaf4c61ddcc5e8a2dabede0f3b482cd9aea9434d");
        assert_eq!(result.label, "technology.cryptographic.hash");
    }

    #[test]
    fn test_hash_sha256_length_64() {
        let mut result = make_result("technology.cryptographic.token_hex");
        post_process(
            &mut result,
            "2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824",
        );
        assert_eq!(result.label, "technology.cryptographic.hash");
    }

    #[test]
    fn test_token_hex_non_standard_length() {
        let mut result = make_result("technology.cryptographic.hash");
        post_process(&mut result, "a417b553b18d13027c23e8016c3466b81e70832254");
        // 42 chars — not a standard hash length, should become token_hex
        assert_eq!(result.label, "technology.cryptographic.token_hex");
    }

    #[test]
    fn test_correct_hash_unchanged() {
        let mut result = make_result("technology.cryptographic.hash");
        post_process(&mut result, "5d41402abc4b2a76b9719d911017c592");
        assert_eq!(result.label, "technology.cryptographic.hash");
    }

    #[test]
    fn test_correct_token_hex_unchanged() {
        let mut result = make_result("technology.cryptographic.token_hex");
        post_process(&mut result, "deadbeefcafebabe00ff11");
        // 22 chars — non-standard, stays as token_hex
        assert_eq!(result.label, "technology.cryptographic.token_hex");
    }

    #[test]
    fn test_hash_with_uppercase_not_reclassified() {
        // Uppercase hex isn't lowercase-only, so rule doesn't fire
        let mut result = make_result("technology.cryptographic.hash");
        post_process(&mut result, "5D41402ABC4B2A76B9719D911017C592");
        // Label unchanged — uppercase hex doesn't match our hex check
        assert_eq!(result.label, "technology.cryptographic.hash");
    }

    // ── Rule 3: emoji vs gender_symbol ───────────────────────────────────────

    #[test]
    fn test_gender_symbol_male() {
        let mut result = make_result("representation.text.emoji");
        post_process(&mut result, "♂");
        assert_eq!(result.label, "identity.person.gender_symbol");
    }

    #[test]
    fn test_gender_symbol_female() {
        let mut result = make_result("representation.text.emoji");
        post_process(&mut result, "♀");
        assert_eq!(result.label, "identity.person.gender_symbol");
    }

    #[test]
    fn test_gender_symbol_transgender() {
        let mut result = make_result("representation.text.emoji");
        post_process(&mut result, "⚧");
        assert_eq!(result.label, "identity.person.gender_symbol");
    }

    #[test]
    fn test_emoji_not_gender_symbol() {
        let mut result = make_result("identity.person.gender_symbol");
        post_process(&mut result, "🎉");
        assert_eq!(result.label, "representation.text.emoji");
    }

    #[test]
    fn test_emoji_rocket_not_gender_symbol() {
        let mut result = make_result("identity.person.gender_symbol");
        post_process(&mut result, "🚀");
        assert_eq!(result.label, "representation.text.emoji");
    }

    #[test]
    fn test_correct_emoji_unchanged() {
        let mut result = make_result("representation.text.emoji");
        post_process(&mut result, "😀");
        assert_eq!(result.label, "representation.text.emoji");
    }

    #[test]
    fn test_correct_gender_symbol_unchanged() {
        let mut result = make_result("identity.person.gender_symbol");
        post_process(&mut result, "♂");
        assert_eq!(result.label, "identity.person.gender_symbol");
    }

    // ── Rule 4: ISSN vs postal_code ──────────────────────────────────────────

    #[test]
    fn test_issn_format_corrects_postal_code() {
        let mut result = make_result("geography.address.postal_code");
        post_process(&mut result, "0028-0836");
        assert_eq!(result.label, "technology.code.issn");
    }

    #[test]
    fn test_issn_with_x_check_digit() {
        let mut result = make_result("geography.address.postal_code");
        post_process(&mut result, "1234-567X");
        assert_eq!(result.label, "technology.code.issn");
    }

    #[test]
    fn test_postal_code_zip5_corrects_issn() {
        let mut result = make_result("technology.code.issn");
        post_process(&mut result, "58763");
        assert_eq!(result.label, "geography.address.postal_code");
    }

    #[test]
    fn test_postal_code_zip_plus_4() {
        let mut result = make_result("technology.code.issn");
        post_process(&mut result, "79262-7606");
        // 10 chars (5-4), not ISSN format (4-3+check = 9 chars)
        assert_eq!(result.label, "geography.address.postal_code");
    }

    #[test]
    fn test_correct_issn_unchanged() {
        let mut result = make_result("technology.code.issn");
        post_process(&mut result, "5019-8538");
        assert_eq!(result.label, "technology.code.issn");
    }

    #[test]
    fn test_correct_postal_code_unchanged() {
        let mut result = make_result("geography.address.postal_code");
        post_process(&mut result, "55502");
        assert_eq!(result.label, "geography.address.postal_code");
    }

    // ── Rule 5: longitude vs latitude ────────────────────────────────────────

    #[test]
    fn test_longitude_outside_latitude_range() {
        let mut result = make_result("geography.coordinate.latitude");
        post_process(&mut result, "170.0522");
        // >90 → definitively longitude
        assert_eq!(result.label, "geography.coordinate.longitude");
    }

    #[test]
    fn test_negative_longitude_outside_latitude_range() {
        let mut result = make_result("geography.coordinate.latitude");
        post_process(&mut result, "-138.9274");
        // abs > 90 → definitively longitude
        assert_eq!(result.label, "geography.coordinate.longitude");
    }

    #[test]
    fn test_value_within_latitude_range_unchanged() {
        // 40.7128 is within ±90, so prediction stays as-is
        let mut result = make_result("geography.coordinate.latitude");
        post_process(&mut result, "40.7128");
        assert_eq!(result.label, "geography.coordinate.latitude");
    }

    #[test]
    fn test_longitude_within_range_stays_longitude() {
        // -58.0804 is within ±90, but predicted as longitude — stays
        let mut result = make_result("geography.coordinate.longitude");
        post_process(&mut result, "-58.0804");
        assert_eq!(result.label, "geography.coordinate.longitude");
    }

    #[test]
    fn test_exactly_90_stays_as_predicted() {
        // Exactly 90.0 is valid latitude, should not change
        let mut result = make_result("geography.coordinate.latitude");
        post_process(&mut result, "90.0");
        assert_eq!(result.label, "geography.coordinate.latitude");
    }

    #[test]
    fn test_just_over_90_becomes_longitude() {
        let mut result = make_result("geography.coordinate.latitude");
        post_process(&mut result, "90.001");
        assert_eq!(result.label, "geography.coordinate.longitude");
    }

    // ── Rule 6: email rescue ─────────────────────────────────────────────────

    #[test]
    fn test_email_rescues_from_hostname() {
        let mut result = make_result("technology.internet.hostname");
        post_process(&mut result, "bob@demo.net");
        assert_eq!(result.label, "identity.person.email");
    }

    #[test]
    fn test_email_rescues_from_username() {
        let mut result = make_result("identity.person.username");
        post_process(&mut result, "info@startup.co");
        assert_eq!(result.label, "identity.person.email");
    }

    #[test]
    fn test_email_rescues_from_slug() {
        let mut result = make_result("technology.internet.slug");
        post_process(&mut result, "hello@world.org");
        assert_eq!(result.label, "identity.person.email");
    }

    #[test]
    fn test_correct_email_unchanged() {
        let mut result = make_result("identity.person.email");
        post_process(&mut result, "alice@gmail.com");
        assert_eq!(result.label, "identity.person.email");
    }

    #[test]
    fn test_paypal_email_not_overridden() {
        let mut result = make_result("identity.payment.paypal_email");
        post_process(&mut result, "user@paypal.com");
        assert_eq!(result.label, "identity.payment.paypal_email");
    }

    #[test]
    fn test_non_email_hostname_unchanged() {
        // A plain hostname without @ should not become email
        let mut result = make_result("technology.internet.hostname");
        post_process(&mut result, "www.example.com");
        assert_eq!(result.label, "technology.internet.hostname");
    }

    #[test]
    fn test_url_with_at_not_email() {
        // URL with @ (e.g., basic auth) has :// so should not become email
        let mut result = make_result("technology.internet.url");
        post_process(&mut result, "https://user@host.com/path");
        assert_eq!(result.label, "technology.internet.url");
    }

    #[test]
    fn test_at_without_dot_not_email() {
        // @ without a dot in domain is not a valid email
        let mut result = make_result("identity.person.username");
        post_process(&mut result, "user@localhost");
        assert_eq!(result.label, "identity.person.username");
    }
}