mocra 0.3.0

A distributed, event-driven crawling and data collection framework
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
#![allow(unused)]

/// Convert a textual numeric representation (including extended Chinese numerals) into f64.
///
/// Newly supported (enhanced version):
/// - Full Chinese digits: 零 〇 一 二 三 四 五 六 七 八 九 两
/// - Chinese units with hierarchical grouping: 十 百 千 万 亿 (supports combinations like "一亿二千三百四十五万六千七百八十九")
/// - Implicit leading '一' for '十' (e.g., "十五" => 15, "十" => 10)
/// - Decimal part after 点 / . with Chinese digits: "三点一四" => 3.14
/// - Trailing unit directly after an Arabic number or mixed decimal: "1.2万" => 12000
/// - Mixed Chinese + Arabic inside the integer part: "一万2千三百" => 12300
/// - Percent handling remains (suffix %) applied at the end
/// - Currency symbols (¥ ¥ $ € £) stripped anywhere
/// - Optional plus sign '+'
/// - Commas as thousands separators ignored
/// - NaN forms removed (nan / NaN / NAN / Nan) -> treated as zero if nothing else remains
///
/// Fallback plain float parsing still attempted; returns None if unrecognized characters remain.
/// This aims to be permissive but deterministic.
pub fn to_numeric(input: &str) -> Option<f64> {
    let mut s = input.trim().to_string();
    if s.is_empty() || s == "-" {
        return Some(0.0);
    }

    // Normalise & remove known noise tokens
    for pat in ["nan", "NaN", "Nan", "NAN"] {
        s = s.replace(pat, "");
    }
    // Remove spaces
    s = s.replace(' ', "");
    // Remove currency symbols
    for sym in ['¥', '', '$', '', '£'] {
        s = s.replace(sym, "");
    }
    if s.is_empty() {
        return Some(0.0);
    }

    // Fast path: plain float parse (no Chinese chars / percent / units)
    if !s.chars().any(|c| {
        matches!(
            c,
            '%' | ''
                | ''
                | ''
                | ''
                | ''
                | ''
                | '亿'
                | ''
                | ''
                | ''
                | ''
                | ''
                | ''
                | ''
                | ''
                | ''
                | ''
        )
    }) && let Ok(v) = s.parse::<f64>()
    {
        return Some(v);
    }

    // If contains full Chinese numerals, attempt Chinese parsing path.

    // Allowed digit mapping (Arabic + Chinese)
    enum Kind {
        Point,
        Percent,
        Comma,
        Minus,
        Plus,
        Digit(u32),
        Other(char),
    }
    fn classify(c: char) -> Option<Kind> {
        match c {
            '.' | '' => Some(Kind::Point),
            '%' => Some(Kind::Percent),
            ',' => Some(Kind::Comma),
            '-' => Some(Kind::Minus),
            '+' => Some(Kind::Plus),
            '' | '' => Some(Kind::Digit(0)),
            '' => Some(Kind::Digit(1)),
            '' => Some(Kind::Digit(2)),
            '' => Some(Kind::Digit(3)),
            '' => Some(Kind::Digit(4)),
            '' => Some(Kind::Digit(5)),
            '' => Some(Kind::Digit(6)),
            '' => Some(Kind::Digit(7)),
            '' => Some(Kind::Digit(8)),
            '' => Some(Kind::Digit(9)),
            '' => Some(Kind::Digit(2)),
            '0'..='9' => Some(Kind::Digit(c.to_digit(10).unwrap())),
            _ => None,
        }
    }
    // Large unit boundaries (section units) and small units
    fn big_unit(c: char) -> Option<f64> {
        match c {
            '亿' => Some(100_000_000.0),
            '' => Some(10_000.0),
            _ => None,
        }
    }
    fn small_unit(c: char) -> Option<f64> {
        match c {
            '' => Some(1000.0),
            '' => Some(100.0),
            '' => Some(10.0),
            _ => None,
        }
    }

    // If there's any Chinese unit/digit, use Chinese-aware algorithm separate from previous simplistic reverse parsing.
    if s.chars().any(|c| {
        matches!(
            c,
            '亿' | ''
                | ''
                | ''
                | ''
                | ''
                | ''
                | ''
                | ''
                | ''
                | ''
                | ''
                | ''
                | ''
                | ''
                | ''
                | ''
        )
    }) {
        let percent = s.ends_with('%');
        if percent {
            s.pop();
        }

        // Split decimal part
        let mut parts = if let Some(pos) = s.find(['.', '']) {
            vec![s[..pos].to_string(), s[pos + 1..].to_string()]
        } else {
            vec![s.clone()]
        };
        let decimal_part = if parts.len() == 2 {
            Some(parts.pop().unwrap())
        } else {
            None
        };
        let int_part = parts.pop().unwrap();

        // Handle trailing big/small unit after pure Arabic/decimal number like "1.2万"
        let trailing_multiplier;
        if let Some(last) = int_part.chars().last()
            && let Some(m) = big_unit(last).or_else(|| small_unit(last))
        {
            // ensure preceding chars contain a digit
            let core = &int_part[..int_part.len() - last.len_utf8()];
            if core.chars().all(|c| c.is_ascii_digit()) && !core.is_empty() {
                trailing_multiplier = m;
                // rebuild s to parse the core as plain number later
                if let Ok(base) = core.parse::<f64>() {
                    let mut value = base * trailing_multiplier;
                    if let Some(dec) = decimal_part.as_ref() {
                        // decimal after unit ambiguous: treat as fractional appended to base before multiplier? Keep simple: base.dec * multiplier
                        let dec_digits: String =
                            dec.chars().filter(|c| c.is_ascii_digit()).collect();
                        if !dec_digits.is_empty()
                            && let Ok(frac_int) = dec_digits.parse::<f64>()
                        {
                            value += frac_int / 10_f64.powi(dec_digits.len() as i32)
                                * trailing_multiplier;
                        }
                    }
                    if percent {
                        value /= 100.0;
                    }
                    return Some(value);
                }
            }
        }

        // Parse Chinese integer part into number
        let mut section_total = 0_f64; // accumulates within current 10^8 or 10^4 section
        let mut current = 0_f64; // current digit value awaiting a small unit
        let mut total = 0_f64; // grand total
        let mut last_was_digit = false;
        for ch in int_part.chars() {
            if ch == '' || ch == '' {
                last_was_digit = false;
                continue;
            }
            if let Some(su) = small_unit(ch) {
                // Small units: ten, hundred, thousand.
                if last_was_digit {
                    section_total += current * su;
                } else {
                    // implicit one, e.g. 十 => 10
                    section_total += su;
                }
                current = 0.0;
                last_was_digit = false;
                continue;
            }
            if let Some(bu) = big_unit(ch) {
                // Large section boundaries: ten-thousand and hundred-million.
                section_total += current;
                total += section_total * bu;
                section_total = 0.0;
                current = 0.0;
                last_was_digit = false;
                continue;
            }
            if let Some(Kind::Digit(d)) = classify(ch) {
                if last_was_digit {
                    section_total = section_total * 10.0 + d as f64;
                    current = 0.0;
                } else {
                    current = d as f64;
                }
                last_was_digit = true;
                continue;
            }
            // Arabic digit fallback
            if ch.is_ascii_digit() {
                current = (ch as u8 - b'0') as f64;
                last_was_digit = true;
                continue;
            }
            if matches!(
                classify(ch),
                Some(Kind::Comma) | Some(Kind::Plus) | Some(Kind::Minus) | Some(Kind::Point)
            ) {
                continue;
            }
            // Unknown char => fail
            return None;
        }
        section_total += current;
        total += section_total;

        // Decimal part (Chinese digits or Arabic) if present
        let mut decimal_value = 0_f64;
        if let Some(dec) = decimal_part {
            let mut scale = 0_f64;
            for ch in dec.chars() {
                if let Some(Kind::Digit(d)) = classify(ch) {
                    scale += 1.0;
                    decimal_value += (d as f64) / 10_f64.powi(scale as i32);
                } else if ch.is_ascii_digit() {
                    scale += 1.0;
                    decimal_value += ((ch as u8 - b'0') as f64) / 10_f64.powi(scale as i32);
                } else if ch == '%' { /* ignore already handled earlier */
                } else if ch == ' ' {
                    continue;
                } else {
                    return None;
                }
            }
        }

        let mut value = total + decimal_value;

        // Percent
        if percent {
            value /= 100.0;
        }

        // Sign handling
        let negative = input.contains('-');
        if negative {
            value = -value;
        }
        return Some(value);
    }

    let mut n: f64 = 1.0; // overall multiplier (units & percent)
    let mut r: f64 = 0.0; // accumulating integer/decimal digits in reverse
    let mut p: u32 = 0; // power index for digits before hitting decimal point
    let mut negative = false;
    let mut saw_valid = false;

    for c in s.chars().rev() {
        // reverse iteration like Python version
        match c {
            '' => {
                n *= 10_000.0;
                saw_valid = true;
                continue;
            }
            '' => {
                n *= 1_000.0;
                saw_valid = true;
                continue;
            }
            '' => {
                n *= 100.0;
                saw_valid = true;
                continue;
            }
            _ => {}
        }
        match classify(c) {
            Some(Kind::Percent) => {
                n /= 100.0;
                saw_valid = true;
            }
            Some(Kind::Minus) => {
                negative = true;
                saw_valid = true;
            }
            Some(Kind::Plus) => {
                saw_valid = true;
            }
            Some(Kind::Comma) => { /* ignore */ }
            Some(Kind::Point) => {
                if p > 0 {
                    r /= 10_f64.powi(p as i32);
                    p = 0;
                }
                saw_valid = true;
            }
            Some(Kind::Digit(d)) => {
                r += (10_f64).powi(p as i32) * (d as f64);
                p += 1;
                saw_valid = true;
            }
            Some(Kind::Other(_)) => {
                return None;
            }
            None => {
                return None;
            } // unknown character
        }
    }

    if !saw_valid {
        return None;
    }
    let mut value = r * n;
    if negative {
        value = -value;
    }
    Some(value)
}

#[cfg(test)]
mod tests {
    use super::to_numeric;

    fn approx(a: f64, b: f64) {
        assert!((a - b).abs() < 1e-9, "{} != {}", a, b);
    }

    #[test]
    fn test_plain_number() {
        approx(to_numeric("123").unwrap(), 123.0);
    }

    #[test]
    fn test_with_commas() {
        approx(to_numeric("1,234.56").unwrap(), 1234.56);
    }

    #[test]
    fn test_currency_symbols() {
        approx(to_numeric("¥1,234").unwrap(), 1234.0);
    }

    #[test]
    fn test_percent() {
        approx(to_numeric("12%").unwrap(), 0.12);
    }

    #[test]
    fn test_negative() {
        approx(to_numeric("-123").unwrap(), -123.0);
    }

    #[test]
    fn test_chinese_unit_qian() {
        approx(to_numeric("45千").unwrap(), 45_000.0);
    }

    #[test]
    fn test_chinese_unit_bai() {
        approx(to_numeric("3百").unwrap(), 300.0);
    }

    #[test]
    fn test_zero_variants() {
        approx(to_numeric("").unwrap(), 0.0);
        approx(to_numeric("0").unwrap(), 0.0);
    }

    #[test]
    fn test_nan_replacement() {
        approx(to_numeric("nan").unwrap(), 0.0);
    }

    #[test]
    fn test_invalid_char() {
        assert!(to_numeric("abc").is_none());
    }

    #[test]
    fn test_mixed_cleaning() {
        approx(to_numeric(" ¥ 1,005.50 % ").unwrap_or(-1.0), 10.055);
    }

    #[test]
    fn test_implicit_ten() {
        approx(to_numeric("十五").unwrap(), 15.0);
        approx(to_numeric("").unwrap(), 10.0);
    }

    #[test]
    fn test_large_mixed() {
        approx(
            to_numeric("一亿二千三百四十五万六千七百八十九").unwrap(),
            123456789.0,
        );
    }

    #[test]
    fn test_with_liang() {
        approx(to_numeric("两千零三十").unwrap(), 2030.0);
    }

    #[test]
    fn test_percent_chinese() {
        approx(to_numeric("十%").unwrap(), 0.10);
    }

    #[test]
    fn test_plus_sign() {
        approx(to_numeric("+123").unwrap(), 123.0);
    }

    #[test]
    fn test_mixed_arabic_chinese() {
        approx(to_numeric("一万2千三百").unwrap(), 12300.0);
    }
}