World's first open-source enterprise world model.
Rust agent-memorybitemporalgraphragknowledge-baseknowledge-graphllmontologypgvectorpostgresqlragrustself-hostedsemantic-searchtemporal-knowledge-graphworld-model
feat(upload): date detection reads filename first, body falls back (#610) (#979)
Roycec30a12ab18ac
diff --git a/crates/utopia-server/src/api/documents_routes.rs b/crates/utopia-server/src/api/documents_routes.rsindex 4a2fcdc9..2eb689f8 100644--- a/crates/utopia-server/src/api/documents_routes.rs+++ b/crates/utopia-server/src/api/documents_routes.rs@@ -593,14 +593,19 @@ fn hex(bytes: &[u8]) -> String {}/// 只认开头独立的完整日期行,不把正文里提到的事件日期当作文档日期(#610)。+///+/// 顺序:**文件名 → 正文首行**。文件名是 multipart 解析时一定有的;+/// 公告、备案一类的语料通常按日期命名,是正文里写「2024年2月29日 公告」还是+/// 文件名叫「2024-02-29_gaoshu.txt」,对读的人来说是一个东西,但只有文件名+/// 这条路在 multipart 落库之前就拍得到。日期格式与正文保持一致(ISO 或中文全形)。fn content_time(filename: &str, bytes: &[u8]) -> Option<chrono::DateTime<chrono::Utc>> {- let extension = std::path::Path::new(filename).extension()?.to_str()?;- if !["txt", "md", "markdown"]- .iter()- .any(|ext| extension.eq_ignore_ascii_case(ext))- {+ if !is_text_extension(filename) {return None;}+ let stem = std::path::Path::new(filename).file_stem()?.to_str()?;+ if let Some(day) = parse_filename_date(stem) {+ return Some(day.and_hms_opt(0, 0, 0)?.and_utc());+ }// 只解码头部 4 KiB:日期行只认开头。PDF、Word 这类格式要读日期时,在各自的解析器里// 读它们自己的元数据,不在这里猜const HEADER_BYTES: usize = 4096;@@ -631,6 +636,93 @@ fn content_time(filename: &str, bytes: &[u8]) -> Option<chrono::DateTime<chrono:Some(day.and_hms_opt(0, 0, 0)?.and_utc())}+/// 文本类的扩展名:只对 `txt` / `md` / `markdown` 试日期解析。+/// PDF / Word 等格式要读日期时,在各自的解析器里读它们自己的元数据(#610 决定 2)。+fn is_text_extension(filename: &str) -> bool {+ let Some(ext) = std::path::Path::new(filename)+ .extension()+ .and_then(|e| e.to_str())+ else {+ return false;+ };+ ["txt", "md", "markdown"]+ .iter()+ .any(|known| ext.eq_ignore_ascii_case(known))+}++/// 解析主名前缀里的 ISO `YYYY-MM-DD` 或中文 `YYYY年M月D日`。+///+/// 不依赖 `regex` 库:手工走一遍就够,错误形态也清楚。+/// 严格匹配:`%Y` 是 4 位数字,`%m` / `%d` 是 1-2 位(与正文解析一致,`chrono`+/// 会拒掉像 `2023-02-29` 这种不可能的日期,但接受 `2024-2-9` 与 `2024-02-09`)。+fn parse_filename_date(stem: &str) -> Option<chrono::NaiveDate> {+ let bytes = stem.as_bytes();+ // 头 4 位必须是数字;这一关漏过去 `chrono` 也会拒,但提前失败省一次分配+ if bytes.len() < 4 || !bytes[..4].iter().all(u8::is_ascii_digit) {+ return None;+ }+ // ISO:`YYYY-MM-DD` 或 `YYYY-M-D`,至少 8 个字符位+ if bytes.len() >= 8 && bytes[4] == b'-' {+ // 找到下一处分隔(位置 5+),可以是 `-` 或别的字符(停止位)+ let after_year = 5;+ let month_end = find_ascii_digit_end(bytes, after_year);+ // 月份 1-2 位数字+ let month_str = std::str::from_utf8(&bytes[after_year..month_end]).ok()?;+ // 月份后必须是 `-`+ if month_end >= bytes.len() || bytes[month_end] != b'-' {+ return None;+ }+ let day_start = month_end + 1;+ let day_end = find_ascii_digit_end(bytes, day_start);+ let day_str = std::str::from_utf8(&bytes[day_start..day_end]).ok()?;+ return chrono::NaiveDate::parse_from_str(+ &format!("{}-{}-{}", &stem[..4], month_str, day_str),+ "%Y-%m-%d",+ )+ .ok();+ }+ // 中文:`YYYY年M月D日`,年号后必须是 `年`+ let year_str = std::str::from_utf8(&bytes[..4]).ok()?;+ let after_year = 4;+ let rest = stem.get(after_year..)?;+ let zh_tail = rest.strip_prefix('年')?;+ let (month_str, zh_tail) = read_ascii_digits(zh_tail)?;+ let zh_tail = zh_tail.strip_prefix('月')?;+ let (day_str, zh_tail) = read_ascii_digits(zh_tail)?;+ if !zh_tail.starts_with('日') {+ return None;+ }+ chrono::NaiveDate::parse_from_str(+ &format!("{year_str}年{month_str}月{day_str}日"),+ "%Y年%m月%d日",+ )+ .ok()+}++/// 从 `start` 起往后读 1-2 位 ASCII 数字,返回 (数字字符串, 剩余的字符串)。+fn read_ascii_digits(s: &str) -> Option<(&str, &str)> {+ let end = s+ .as_bytes()+ .iter()+ .take(2)+ .take_while(|b| b.is_ascii_digit())+ .count();+ if end == 0 {+ return None;+ }+ Some((&s[..end], &s[end..]))+}++/// 从 `start` 起往后走 ASCII 数字,返回第一个非数字字符的位置(闭区间右开)。+/// 全部到尾部也允许:返回 `bytes.len()`。+fn find_ascii_digit_end(bytes: &[u8], start: usize) -> usize {+ let mut i = start;+ while i < bytes.len() && bytes[i].is_ascii_digit() {+ i += 1;+ }+ i+}+#[cfg(test)]#[path = "documents_routes_tests.rs"]mod tests;diff --git a/crates/utopia-server/src/api/documents_routes_tests.rs b/crates/utopia-server/src/api/documents_routes_tests.rsindex fa3c847e..5bcb74d3 100644--- a/crates/utopia-server/src/api/documents_routes_tests.rs+++ b/crates/utopia-server/src/api/documents_routes_tests.rs@@ -50,6 +50,111 @@ fn only_a_complete_opening_dateline_sets_the_date() {}}+/// #610:文件名里的日期和正文一样,但要排在前面——公告语料通常按日期命名,+/// multipart 解析时这条信息已经在那儿了;正文里写「2024年2月29日 公告」还是+/// 文件名叫「2024-02-29_gaoshu.txt」,对读的人来说是一个东西。+///+/// 日期格式与正文一致:ISO `YYYY-MM-DD` 或中文 `YYYY年M月D日`(月/日 1-2 位都行,+/// 输出一律是规范化的两位数)。文件名后跟任意内容(包括完全没有后跟),+/// 只要日期在主名开头就算。+#[test]+fn a_filename_with_a_leading_date_sets_the_date_even_when_body_has_none() {+ let expected = "2024-02-29T00:00:00Z".parse::<DateTime<Utc>>().unwrap();+ // ISO+ for filename in [+ "2024-02-29.txt",+ "2024-02-29_filing.txt",+ "2024-02-29.md",+ "2024-02-29.markdown",+ "2024-02-29 some filing.txt", // 后跟空格分隔+ ] {+ assert_eq!(+ content_time(filename, b""),+ Some(expected),+ "filename {filename:?}"+ );+ }+ // ISO 月/日 1 位 → 标准化为 2 位+ let expected_0209 = "2024-02-09T00:00:00Z".parse::<DateTime<Utc>>().unwrap();+ assert_eq!(content_time("2024-2-9 filing.md", b""), Some(expected_0209));+ // 中文+ for filename in ["2024年2月29日.txt", "2024年02月29日_公告.md"] {+ assert_eq!(+ content_time(filename, b""),+ Some(expected),+ "filename {filename:?}"+ );+ }+ // 中文月/日 1 位 → 标准化为 2 位+ let expected_0209 = "2024-02-09T00:00:00Z".parse::<DateTime<Utc>>().unwrap();+ assert_eq!(+ content_time("2024年2月9日 公告.markdown", b""),+ Some(expected_0209)+ );+}++/// 文件名没日期时,回到正文找:与正文解析路径完全一致(`#610` 的「文件名优先,+/// 正文兜底」)+#[test]+fn a_filename_without_a_date_falls_back_to_body() {+ let expected = "2024-02-29T00:00:00Z".parse::<DateTime<Utc>>().unwrap();+ // ISO in body+ assert_eq!(+ content_time("filing.txt", b"2024-02-29\nAnnouncement"),+ Some(expected)+ );+ // 中文 in body+ assert_eq!(+ content_time("filing.md", "(2024年2月29日)\n公告".as_bytes()),+ Some(expected)+ );+ // Filename 无日期,正文也无日期 → 全部 None+ assert_eq!(content_time("filing.txt", b""), None);+ assert_eq!(content_time("filing.txt", b"Announcement"), None);+}++/// 模糊/部分/无日期:全走 None(与正文那条路径同一套规矩)+#[test]+fn a_partial_or_ambiguous_filename_does_not_match() {+ // 不是 4 位数年份开头+ for filename in [+ "24-02-29.txt", // 年份只有 2 位+ "abcd-02-29.txt", // 年份是字母+ " 2024-02-29.txt", // 开头有空格+ ] {+ assert_eq!(content_time(filename, b""), None, "filename {filename:?}");+ }+ // 日期格式对但数字超出范围(chrono 拒)+ for filename in [+ "2023-02-29.txt", // 2023 不是闰年+ "2024-13-01.txt", // 月份 13+ "2024-02-30.txt", // 2 月 30 日+ "2024年13月01日.txt",+ ] {+ assert_eq!(content_time(filename, b""), None, "filename {filename:?}");+ }+ // 中文格式部分缺+ for filename in [+ "2024年.txt", // 缺月日+ "2024年2月.txt", // 缺日+ "2024年2月29.txt", // 缺日字+ ] {+ assert_eq!(content_time(filename, b""), None, "filename {filename:?}");+ }+}++/// 文件名 vs 正文优先级:文件名日期早于正文日期时,**用文件名的**+/// (announcement corpus 多半以日期命名)。+#[test]+fn filename_date_wins_over_body_date() {+ let filename_date = "2024-02-29T00:00:00Z".parse::<DateTime<Utc>>().unwrap();+ // 正文是另一个日期;文件名日期优先+ assert_eq!(+ content_time("2024-02-29_filing.txt", b"2025-12-31\nOld announcement"),+ Some(filename_date)+ );+}+impl Fixture {async fn get_raw(&self,@@ -538,6 +643,48 @@ async fn each_upload_keeps_its_own_date_before_processing_and_extraction() -> anf.cleanup().await}+/// `#610`:文件名里有日期时,日期来自文件名而不是正文——这一档要把+/// `content_time` 走文件名优先的路径整条接到数据库层(不只是单测)。+///+/// 这里只挂纯文本的三种情形:ISO 文件名、中文文件名、ISO 文件名 + 中文正文。+/// 它们都对得上 `content_time` 单测,但落库之后 `doc_time` 与 `doc_time_source`+/// 必须一起被设成对应值,不能再回到「正文解析失败 → 全 None」。+#[tokio::test]+async fn a_filename_with_a_date_drives_doc_time_when_body_has_none() -> anyhow::Result<()> {+ let Some(f) = Fixture::new().await? else {+ return Ok(());+ };+ let files = [+ // ISO 文件名 + 正文无日期+ ("2024-02-29_filing.txt", "First announcement"),+ // 中文文件名 + 正文无日期+ ("2025年3月1日_公告.md", "第二次公告"),+ // ISO 文件名 + 中文正文+ (+ "2026-06-15_meeting.markdown",+ "(2027年1月1日)\nthis header date must not win over the filename",+ ),+ ];+ let (status, response) = f.upload(f.kb, "", &files).await?;+ assert_eq!(status, StatusCode::OK, "{response}");+ let created = f.created_docs(&response).await?;+ assert_eq!(created.len(), 3);+ let expected = [+ "2024-02-29T00:00:00Z",+ "2025-03-01T00:00:00Z",+ "2026-06-15T00:00:00Z",+ ];+ for (doc, expected) in created.iter().zip(expected) {+ assert_eq!(+ (doc.doc_time, doc.doc_time_source.as_str()),+ (Some(expected.parse::<DateTime<Utc>>()?), "content"),+ "filename doc {}",+ doc.filename,+ );+ }+ f.cleanup().await+}+#[tokio::test]async fn fallback_restore_and_other_ingest_dates_do_not_change() -> anyhow::Result<()> {let Some(f) = Fixture::new().await? else {diff --git a/web/src/api.ts b/web/src/api.tsindex 11ab2d39..07451958 100644--- a/web/src/api.ts+++ b/web/src/api.ts@@ -197,6 +197,12 @@ export interface Doc {/** 这份文件的字要靠哪一种模型读、而那种模型没配(0040):ocr / transcribe;文档此时是 failed */reader_needed: "ocr" | "transcribe" | null;created_at: string;+ /** 文档日期——`#610`:从文件名或正文首行解析出来的「文件上写的日期」,+ * 与 `created_at`(上传时刻)必须分开展示。`null` 表示没认出来(`#610` 决定 3) */+ doc_time: string | null;+ /** `doc_time` 是怎么来的:`"content"` = 文件名或正文,`"none"` = 没认出来。+ * 上传时刻不在这里—— `created_at` 才是 */+ doc_time_source: "content" | "none";}/** 一类抽取丢弃在一篇文档里的聚合:事实抽出来了,却没能落地。 */diff --git a/web/src/i18n/en.ts b/web/src/i18n/en.tsindex 37a51ea2..943c15fa 100644--- a/web/src/i18n/en.ts+++ b/web/src/i18n/en.ts@@ -1136,6 +1136,10 @@ export const en = {loading: "Loading…",extracted: "Extracted",ongoing: "now",+ /** `#610`:`doc_time` 是从文件里读出来的日期;与上传时刻是两件事 */+ docDate: "Document date",+ docDateFromContent: "Detected from the filename or first line",+ uploadedAt: "Uploaded",},settings: {title: "Administration",diff --git a/web/src/i18n/zh.ts b/web/src/i18n/zh.tsindex c8e55729..d067ee77 100644--- a/web/src/i18n/zh.ts+++ b/web/src/i18n/zh.ts@@ -1005,6 +1005,10 @@ export const zh: Strings = {loading: "加载中…",extracted: "已抽取",ongoing: "至今",+ /** `#610`:`doc_time` 是从文件里读出来的日期;与上传时刻是两件事 */+ docDate: "文档日期",+ docDateFromContent: "从文件名或正文首行认出来的",+ uploadedAt: "上传于",},settings: {title: "管理",diff --git a/web/src/pages/DocViewer.tsx b/web/src/pages/DocViewer.tsxindex 87841896..41b5530d 100644--- a/web/src/pages/DocViewer.tsx+++ b/web/src/pages/DocViewer.tsx@@ -1,10 +1,11 @@import { useEffect, useMemo, useRef, useState } from "react";import { useQuery } from "@tanstack/react-query";import { Link, useNavigate, useParams, useSearch } from "@tanstack/react-router";-import { api, type ChunkFact } from "../api";+import { api, type ChunkFact, type Doc } from "../api";import { S } from "../i18n";import { useKbId } from "../kb";import { originHint, originLabel } from "../origin";+import { fmtTime } from "../time";import { GroupLabel, PageHeader, Pager, pageSlice } from "../ui";import { SourcesRail } from "./SourcesRail";@@ -86,12 +87,7 @@ export function DocViewer() {<div className="px-8 py-6"><PageHeadertitle={doc.filename}- sub={- <>- {chunks.length} {S.doc.sections} · {(doc.size_bytes / 1024).toFixed(0)} KB ·{" "}- {new Date(doc.created_at).toLocaleDateString()}- </>- }+ sub={<DocMeta doc={doc} chunks={chunks.length} />}actions={<Link to="/kb/$kbId/library" params={{ kbId }} className="u-link shrink-0 text-body">{S.doc.backToLibrary}@@ -208,3 +204,27 @@ export function DocViewer() {</div>);}++/** 文档头部的元数据条:段数 · 大小 · 文档日期 · 上传时刻。+ *+ * 文档日期(`doc_time`)与上传时刻(`created_at`)分开显示(#610):合成一格,读的人会把+ * 上传时间当成文档上写的日期。两者的读法也不同:文档日期是**日历日期**,存的是那一天的+ * UTC 午夜,按 UTC 读(`fmtTime`)——按本地读,UTC-5 的人看到的是前一天;上传时刻是一个+ * 真实的时刻,按看的人所在的时区读。 */+function DocMeta({ doc, chunks }: { doc: Doc; chunks: number }) {+ const docDate = fmtTime(doc.doc_time, "day");+ return (+ <>+ {chunks} {S.doc.sections} · {(doc.size_bytes / 1024).toFixed(0)} KB ·{" "}+ {docDate && (+ <>+ <span title={S.doc.docDateFromContent}>+ {S.doc.docDate}: {docDate}+ </span>+ {" · "}+ </>+ )}+ {S.doc.uploadedAt} {new Date(doc.created_at).toLocaleDateString()}+ </>+ );+}