Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
14 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion crates/utopia-cli/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ struct ManifestDataDir {
/// not a side effect of a code change.
// 是迁移文件的**个数**,不是最大的编号(守卫 `schema_version_policy_compares_against_current`
// 按个数比):编号有空缺时两者不同——0071 由一个开放 PR 占着,0072 先落,个数是 71
const CURRENT_SCHEMA_VERSION: u32 = 122;
const CURRENT_SCHEMA_VERSION: u32 = 123;

#[tokio::main]
async fn main() -> anyhow::Result<()> {
Expand Down
123 changes: 118 additions & 5 deletions crates/utopia-extract/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -437,7 +437,8 @@ pub(crate) fn currency_unit(tok: &str) -> Option<&'static str> {
"$" | "USD" | "usd" | "US$" | "dollar" | "dollars" | "美元" => "$",
"€" | "EUR" | "eur" | "euro" | "euros" | "欧元" => "€",
"£" | "GBP" | "gbp" | "pound" | "pounds" | "英镑" => "£",
"¥" | "JPY" | "jpy" | "yen" | "日元" => "¥",
// 中文排版的「¥」是全角的同一个符号
"¥" | "¥" | "JPY" | "jpy" | "yen" | "日元" => "¥",
"CNY" | "cny" | "RMB" | "rmb" | "yuan" | "人民币" | "元" | "元人民币" | "人民币元" => {
"¥"
}
Expand Down Expand Up @@ -471,6 +472,8 @@ fn scan_quantity(s: &str, strict: bool) -> Option<Quantity> {
if s.is_empty() {
return None;
}
let negated = if strict { None } else { accounting_negative(s) };
let s = negated.as_deref().unwrap_or(s);
let (body, percent) = match s.strip_suffix('%') {
Some(b) => (b.trim_end(), true),
None => (s, false),
Expand Down Expand Up @@ -559,6 +562,35 @@ fn scan_quantity(s: &str, strict: bool) -> Option<Quantity> {
})
}

/// 财报的写法:括号里的数是负数。`(1,234)` → `-1,234`,`$(1.2) billion` → `$-1.2 billion`,
/// `(12.5%)` → `-12.5%`。括号前只许有一个货币,括号里只许是数,括号后只许是量级词、
/// 货币或 `%`:「(1) 1,200 employees」「(2024) 500」里的括号是编号和年份,不是负号
fn accounting_negative(s: &str) -> Option<String> {
let (head, rest) = s.split_once('(')?;
let (inner, after) = rest.split_once(')')?;
if !head.trim().is_empty() && currency_unit(head.trim()).is_none() {
return None;
}
let mut tail = after.trim();
tail = tail.strip_suffix('%').unwrap_or(tail).trim_end();
while !tail.is_empty() {
let (tok, next) = next_token(tail);
if magnitude(&tok.to_ascii_lowercase()).is_none() && currency_unit(tok).is_none() {
return None;
}
tail = next.trim_start();
}
let digits = inner.trim().strip_suffix('%').unwrap_or(inner.trim());
if !digits.starts_with(|c: char| c.is_ascii_digit())
|| !digits
.chars()
.all(|c| c.is_ascii_digit() || matches!(c, ',' | '.'))
{
return None;
}
Some(format!("{head}-{}{after}", inner.trim()))
}

/// 读出来的一个量。`n` 已经乘上了量级词;`scaled` 记下原文写没写量级词——换算到属性
/// 声明的单位时要知道 `5000` 是原文就这么写的数,还是 `5000万` 展开出来的
struct Quantity {
Expand Down Expand Up @@ -776,10 +808,15 @@ pub fn attribute_value(
if written.is_some() && wanted.is_some() && written != wanted {
return None;
}
// 原文写了量级词,或写了和声明一样的单位(「50000000元」对「万元」),n 才是绝对量,
// 要除下来;光秃秃的数就是声明单位下的数。除法走一次十进制解析,同 `scan_quantity`
// 乘量级词的道理:先算成 f64 再除会留下 23000.000000000004
let n = if q.scaled || (written.is_some() && written == wanted) {
// 原文写了量级词,或写了和声明一样的单位(「50000000元」对「万元」、「12,000人」对
// 「万人」),或写了计数量词,n 才是绝对量,要除下来;光秃秃的数就是声明单位下的数。
// 除法走一次十进制解析,同 `scan_quantity` 乘量级词的道理:先算成 f64 再除会留下
// 23000.000000000004
let counted = q
.unit
.as_deref()
.is_some_and(|u| u == base || COUNTERS.iter().any(|c| c.trim() == u));
let n = if q.scaled || counted || (written.is_some() && written == wanted) {
format!("{}e-{exponent}", q.n).parse().ok()?
} else {
q.n
Expand Down Expand Up @@ -906,6 +943,12 @@ pub fn written_date(s: &str) -> Option<(NaiveDate, &'static str)> {
if year.len() != 4 || day.is_some_and(|d| d.len() > 2) {
return None;
}
// 美联社写法把九月缩成四个字母的「Sept.」,chrono 的 `%b` 只认三个字母
let month = if month.eq_ignore_ascii_case("sept") {
"Sep"
} else {
month
};
let month = ["%B", "%b"].iter().find_map(|f| {
NaiveDate::parse_from_str(&format!("1 {month} 2000"), &format!("%d {f} %Y"))
.ok()
Expand Down Expand Up @@ -1348,6 +1391,25 @@ mod tests {
);
}

#[test]
fn september_abbreviated_as_sept_is_read() {
use serde_json::json;
let day = |s: &str| normalize_attr_value("date", &json!(s));
for written in [
"Sept. 17, 2020",
"Sept 17, 2020",
"17 Sept. 2020",
"SEPT. 17, 2020",
] {
assert_eq!(day(written), Some(json!("2020-09-17")), "{written}");
}
assert_eq!(day("Sept. 2020"), Some(json!("2020-09")));
assert_eq!(
read_time("Sept. 30, 2025").map(|(t, p)| (t.date_naive().to_string(), p)),
Some(("2025-09-30".to_string(), "day"))
);
}

#[test]
fn a_similarity_proposed_pair_says_so_in_the_prompt() {
let side = |name: &str| AdjudicationSide {
Expand Down Expand Up @@ -1476,6 +1538,28 @@ mod tests {
);
assert_eq!(normalize_attr_value("text", &json!([1])), None);
}

/// 财报表里括号里的数是负数:从前整格读不出来,这个值就丢了
#[test]
fn an_accounting_negative_is_read_as_negative() {
use serde_json::json;
let n = |s: &str| normalize_attr_value("number", &json!(s));
assert_eq!(n("(1,234)"), Some(json!(-1234.0)));
assert_eq!(n("$(1.2) billion"), Some(json!(-1200000000.0)));
assert_eq!(n("(12.5%)"), Some(json!(-12.5)));
assert_eq!(
attribute_value("number", Some("万元"), &json!("(350)万元")),
Some(json!(-350.0))
);
// 括号里不是数、括号前不是货币的,照旧读不出
assert_eq!(n("(see note 4)"), None);
assert_eq!(n("Q3 (12)"), None);
// 括号后面跟着别的数:括号是编号或年份,不是负号
assert_eq!(n("(1) 1,200 employees"), None);
assert_eq!(n("(2024) 500"), None);
// 宾语判定不跟着变:点了名的「(1984)」仍是一个东西
assert!(!literal_object("(1984)", true));
}
}

#[cfg(test)]
Expand Down Expand Up @@ -1553,6 +1637,22 @@ mod an_attribute_value_is_read_in_its_declared_unit {
);
}

/// 数后面写了人数的词,那就是一个个数出来的人,落到「万人」上要除下来
#[test]
fn a_counted_figure_is_read_into_a_larger_unit() {
assert_eq!(value("number", Some("万人"), "12,000人"), Some(json!(1.2)));
assert_eq!(value("number", Some("万人"), "约3500名"), Some(json!(0.35)));
assert_eq!(
value("number", Some("thousand people"), "1,250 employees"),
Some(json!(1.25))
);
assert_eq!(
value("number", Some("万人"), "1400万人"),
Some(json!(1400.0))
);
assert_eq!(value("number", Some("万人"), "1.2"), Some(json!(1.2)));
}

/// 换不了的不换:货币对不上、读不出数的,宁缺勿脏
#[test]
fn what_cannot_be_read_is_not_written() {
Expand All @@ -1562,6 +1662,19 @@ mod an_attribute_value_is_read_in_its_declared_unit {
assert_eq!(value("bool", None, "尚未上市"), None);
}

/// 中文财务文本的金额多用全角的「¥」,与「¥」是同一个符号
#[test]
fn a_full_width_yen_sign_is_read_as_the_currency() {
assert_eq!(value("number", None, "¥5,000万"), Some(json!(5e7)));
assert_eq!(
value("number", Some("万元"), "¥5,000万"),
Some(json!(5000.0))
);
assert_eq!(value("number", Some("元"), "¥1,280"), Some(json!(1280.0)));
assert_eq!(value("number", Some("万美元"), "¥5,000万"), None);
assert!(literal_object("¥5000万", true));
}

#[test]
fn a_figure_or_a_date_is_not_a_thing() {
for v in [
Expand Down
36 changes: 36 additions & 0 deletions crates/utopia-ingest/src/parsers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1098,10 +1098,46 @@ fn spreadsheet_cell_text(cell: Option<&calamine::Data>) -> String {
None | Some(calamine::Data::Empty) => String::new(),
Some(calamine::Data::DateTime(d)) => excel_date(d),
Some(calamine::Data::Float(f)) => excel_number(*f),
Some(calamine::Data::DurationIso(d)) => ods_time(d).unwrap_or_else(|| d.clone()),
Some(other) => other.to_string(),
}
}

/// ODS 的时刻格存的是 ISO 时长(`office:time-value="PT09H30M00S"`),不分一天里的钟点和
/// 累计时长。照 xlsx 那两种格子的写法:不到一天的写钟点(`09:30`),满一天的写累计的
/// 时分秒(`36:15:00`)。LibreOffice 常把秒写成 `59.999999998S`,按最近的整秒算
fn ods_time(iso: &str) -> Option<String> {
let iso = iso.trim();
let (sign, body) = match iso.strip_prefix('-') {
Some(rest) => ("-", rest.strip_prefix('P')?),
None => ("", iso.strip_prefix('P')?),
};
let (days, mut clock) = body.split_once('T').unwrap_or((body, ""));
let mut seconds = match days.strip_suffix('D') {
Some(n) => n.parse::<f64>().ok()? * 86_400.0,
None if days.is_empty() => 0.0,
None => return None,
};
for (unit, scale) in [('H', 3_600.0), ('M', 60.0), ('S', 1.0)] {
if let Some((n, tail)) = clock.split_once(unit) {
seconds += n.parse::<f64>().ok()? * scale;
clock = tail;
}
}
if !clock.is_empty() || !seconds.is_finite() {
return None;
}
let seconds = seconds.round() as u64;
let (h, m, s) = (seconds / 3600, seconds / 60 % 60, seconds % 60);
Some(if h >= 24 || !sign.is_empty() {
format!("{sign}{h}:{m:02}:{s:02}")
} else if s == 0 {
format!("{h:02}:{m:02}")
} else {
format!("{h:02}:{m:02}:{s:02}")
})
}

/// 表头从第一排至少两格有字的行开始;这一块里纵向 merge 伸到的行也是表头。
fn spreadsheet_headers(regions: &[GridMerge], rows: &[GridRow]) -> Option<std::ops::Range<usize>> {
let start = rows
Expand Down
56 changes: 56 additions & 0 deletions crates/utopia-ingest/tests/spreadsheet_ods_times.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
//! ODS 的时刻格读成它显示的钟点,和 xlsx 里同一格写法一样。
//!
//! LibreOffice 把时刻存成 ISO 时长:`office:value-type="time"
//! office:time-value="PT09H30M00S"`,格子里显示的是 `09:30:00`。

use std::io::{Cursor, Write};

fn ods(rows: &[(&str, &str)]) -> Vec<u8> {
let cells: String = rows
.iter()
.map(|(label, time)| {
format!(
r#"<table:table-row><table:table-cell office:value-type="string"><text:p>{label}</text:p></table:table-cell><table:table-cell office:value-type="time" office:time-value="{time}"><text:p>{time}</text:p></table:table-cell></table:table-row>"#
)
})
.collect();
let content = format!(
r#"<?xml version="1.0" encoding="UTF-8"?><office:document-content xmlns:office="urn:oasis:names:tc:opendocument:xmlns:office:1.0" xmlns:table="urn:oasis:names:tc:opendocument:xmlns:table:1.0" xmlns:text="urn:oasis:names:tc:opendocument:xmlns:text:1.0" office:version="1.3"><office:body><office:spreadsheet><table:table table:name="Shifts"><table:table-row><table:table-cell office:value-type="string"><text:p>Item</text:p></table:table-cell><table:table-cell office:value-type="string"><text:p>When</text:p></table:table-cell></table:table-row>{cells}</table:table></office:spreadsheet></office:body></office:document-content>"#
);
let mut zip = zip::ZipWriter::new(Cursor::new(Vec::new()));
let stored =
zip::write::SimpleFileOptions::default().compression_method(zip::CompressionMethod::Stored);
zip.start_file("mimetype", stored).unwrap();
zip.write_all(b"application/vnd.oasis.opendocument.spreadsheet")
.unwrap();
zip.start_file(
"META-INF/manifest.xml",
zip::write::SimpleFileOptions::default(),
)
.unwrap();
zip.write_all(br#"<?xml version="1.0" encoding="UTF-8"?><manifest:manifest xmlns:manifest="urn:oasis:names:tc:opendocument:xmlns:manifest:1.0" manifest:version="1.3"><manifest:file-entry manifest:full-path="/" manifest:media-type="application/vnd.oasis.opendocument.spreadsheet"/><manifest:file-entry manifest:full-path="content.xml" manifest:media-type="text/xml"/></manifest:manifest>"#)
.unwrap();
zip.start_file("content.xml", zip::write::SimpleFileOptions::default())
.unwrap();
zip.write_all(content.as_bytes()).unwrap();
zip.finish().unwrap().into_inner()
}

#[test]
fn an_ods_time_cell_reads_as_clock_time() {
let text = utopia_ingest::parse(
"shifts.ods",
&ods(&[
("Daily call", "PT09H30M00S"),
("Cutoff", "PT17H45M30S"),
("Close", "PT14H29M59.999999998S"),
("Downtime", "PT36H15M00S"),
]),
)
.unwrap()
.text;
assert!(text.contains("| Daily call | 09:30 |"), "{text}");
assert!(text.contains("| Cutoff | 17:45:30 |"), "{text}");
assert!(text.contains("| Close | 14:30 |"), "{text}");
assert!(text.contains("| Downtime | 36:15:00 |"), "{text}");
}
54 changes: 48 additions & 6 deletions crates/utopia-reason/src/expressions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -77,15 +77,43 @@ impl DatePart {
let Scalar::Text(text) = value else {
return None;
};
let date = if text.len() == 10 {
NaiveDate::parse_from_str(&text, "%Y-%m-%d").ok()?
// 年精度存的是 "2024",月精度是 "2024-03"(规则 3)。截到比字更细的一档
// 是在补一个原文没有的日或月,所以没有。
let (date, finest) = if text.len() == 10 {
(
NaiveDate::parse_from_str(&text, "%Y-%m-%d").ok()?,
Self::Day,
)
} else if text.len() == 7 {
(
NaiveDate::parse_from_str(&format!("{text}-01"), "%Y-%m-%d").ok()?,
Self::Month,
)
} else if text.len() == 4 {
// 四位数字才是年:`parse` 也收 "+202"、"-123",它们不是存下来的年精度
if !text.bytes().all(|b| b.is_ascii_digit()) {
return None;
}
let year: i32 = text.parse().ok()?;
(NaiveDate::from_ymd_opt(year, 1, 1)?, Self::Year)
} else {
// An offset is required: the host timezone must not change a fact.
chrono::DateTime::parse_from_rfc3339(&text)
.ok()?
.with_timezone(&chrono::Utc)
.date_naive()
(
chrono::DateTime::parse_from_rfc3339(&text)
.ok()?
.with_timezone(&chrono::Utc)
.date_naive(),
Self::Day,
)
};
let rank = |part: Self| match part {
Self::Year => 0,
Self::Month => 1,
Self::Day => 2,
};
if rank(self) > rank(finest) {
return None;
}
let date = match self {
Self::Year => NaiveDate::from_ymd_opt(date.year(), 1, 1)?,
Self::Month => NaiveDate::from_ymd_opt(date.year(), date.month(), 1)?,
Expand Down Expand Up @@ -424,6 +452,9 @@ mod tests {
("year", "2024-01-01T00:30:00+01:00", "2023-01-01"),
("day", "2024-02-29", "2024-02-29"),
("month", "2024-02-29", "2024-02-01"),
("month", "2024-03", "2024-03-01"),
("year", "2024-03", "2024-01-01"),
("year", "2024", "2024-01-01"),
] {
let expr = Expr::from_json(&json!({"date_trunc":part,"expr":{"attr":id(1)}})).unwrap();
assert_eq!(
Expand All @@ -432,6 +463,17 @@ mod tests {
);
}
let expr = Expr::from_json(&json!({"date_trunc":"month","expr":{"attr":id(1)}})).unwrap();
let day = Expr::from_json(&json!({"date_trunc":"day","expr":{"attr":id(1)}})).unwrap();
// 月精度没有日,年精度没有月:截得更细就没有值
assert_eq!(
day.evaluate(&|_| Some(Scalar::Text("2024-03".into()))),
None
);
assert_eq!(expr.evaluate(&|_| Some(Scalar::Text("2024".into()))), None);
let year = Expr::from_json(&json!({"date_trunc":"year","expr":{"attr":id(1)}})).unwrap();
for input in ["+202", "-123"] {
assert_eq!(year.evaluate(&|_| Some(Scalar::Text(input.into()))), None);
}
for input in [
"2023-02-29",
"2024-02-30",
Expand Down
Loading
Loading