Elffuss BraidHub

kikocis/utopia public

dev · 7.3 KiBRawPermalink
1//! 各格式解析器。全部输出纯文本(结构用 markdown 风格标题保留)。
2
3use anyhow::Context;
4use quick_xml::events::Event;
5use quick_xml::Reader;
6use std::io::{Cursor, Read};
7
8/// 文本解码:chardetng 探测编码(覆盖 GBK/GB18030/BIG5 等中文常见编码)。
9pub fn plain_text(bytes: &[u8]) -> String {
10 use chardetng::{EncodingDetector, Iso2022JpDetection, Utf8Detection};
11 let mut detector = EncodingDetector::new(Iso2022JpDetection::Deny);
12 detector.feed(bytes, true);
13 let encoding = detector.guess(None, Utf8Detection::Allow);
14 let (text, _, _) = encoding.decode(bytes);
15 text.into_owned()
16}
17
18pub fn pdf(bytes: &[u8]) -> anyhow::Result<String> {
19 pdf_extract::extract_text_from_mem(bytes).context("PDF text-layer extraction failed")
20}
21
22/// docx: 解压 word/document.xml,取 w:t 文本、w:p 分段。
23pub fn docx(bytes: &[u8]) -> anyhow::Result<String> {
24 let xml = read_zip_entry(bytes, "word/document.xml").context("Malformed docx structure")?;
25 extract_xml_text(&xml, "w:t", "w:p")
26}
27
28/// pptx: 按页码顺序解析 ppt/slides/slideN.xml,取 a:t 文本。
29pub fn pptx(bytes: &[u8]) -> anyhow::Result<String> {
30 let mut archive =
31 zip::ZipArchive::new(Cursor::new(bytes.to_vec())).context("Failed to unzip pptx")?;
32 let mut slides: Vec<(u32, String)> = Vec::new();
33 for i in 0..archive.len() {
34 let name = archive.by_index(i)?.name().to_string();
35 if let Some(num) = name
36 .strip_prefix("ppt/slides/slide")
37 .and_then(|s| s.strip_suffix(".xml"))
38 .and_then(|s| s.parse::<u32>().ok())
39 {
40 slides.push((num, name));
41 }
42 }
43 slides.sort();
44
45 let mut out = String::new();
46 for (num, name) in slides {
47 let mut entry = archive.by_name(&name)?;
48 let mut xml = String::new();
49 entry.read_to_string(&mut xml)?;
50 let text = extract_xml_text(&xml, "a:t", "a:p")?;
51 if !text.trim().is_empty() {
52 out.push_str(&format!("\n## 第 {num} 页\n{text}\n"));
53 }
54 }
55 Ok(out)
56}
57
58/// xlsx / xls / ods: calamine 全格式读取,每 sheet 输出制表符表格(限前 2000 行)。
59pub fn spreadsheet(bytes: &[u8]) -> anyhow::Result<String> {
60 use calamine::{Data, Reader as _};
61 let mut workbook = calamine::open_workbook_auto_from_rs(Cursor::new(bytes.to_vec()))
62 .context("Failed to open spreadsheet")?;
63 let mut out = String::new();
64 for sheet_name in workbook.sheet_names() {
65 let Ok(range) = workbook.worksheet_range(&sheet_name) else {
66 continue;
67 };
68 if range.is_empty() {
69 continue;
70 }
71 out.push_str(&format!("\n# 工作表: {sheet_name}\n"));
72 for row in range.rows().take(2000) {
73 let line: Vec<String> = row
74 .iter()
75 .map(|c| match c {
76 Data::Empty => String::new(),
77 other => other.to_string(),
78 })
79 .collect();
80 if line.iter().any(|s| !s.is_empty()) {
81 out.push_str(&line.join("\t"));
82 out.push('\n');
83 }
84 }
85 }
86 Ok(out)
87}
88
89/// HTML: 取正文文本。
90///
91/// 真实网页的 chrome 往往比正文还多——整站导航、语言列表、页脚法务、编辑工具。
92/// 全量遍历会把它们一并喂给抽取器:既浪费每个分块一次 LLM 调用,又会把
93/// "Main page""Privacy policy"之类抽成实体污染图谱(实测一篇维基条目 647KB
94/// 产出 60 个分块,首块整块是侧栏菜单、末块整块是版权声明)。
95///
96/// 因此先认正文容器(main / role=main / article),只有都找不到才退回整篇;
97/// 容器内仍可能嵌着导航与表单,交给 walk_html 的 SKIP 名单。
98pub fn html(bytes: &[u8]) -> String {
99 let raw = plain_text(bytes);
100 let doc = scraper::Html::parse_document(&raw);
101 let mut out = String::new();
102 if let Some(title) = doc
103 .select(&scraper::Selector::parse("title").unwrap())
104 .next()
105 {
106 out.push_str(&format!(
107 "# {}\n\n",
108 title.text().collect::<String>().trim()
109 ));
110 }
111 let root = ["main", "[role=main]", "article"]
112 .iter()
113 .find_map(|sel| {
114 scraper::Selector::parse(sel)
115 .ok()
116 .and_then(|s| doc.select(&s).next())
117 })
118 .unwrap_or_else(|| doc.root_element());
119 walk_html(root, &mut out);
120 out
121}
122
123fn walk_html(el: scraper::ElementRef, out: &mut String) {
124 // 导航/页眉页脚/边栏/表单控件即便落在正文容器内也是 chrome,一律跳过
125 const SKIP: &[&str] = &[
126 "script", "style", "noscript", "head", "svg", "template", "nav", "header", "footer",
127 "aside", "form", "button", "select", "iframe", "dialog",
128 ];
129 const BLOCK: &[&str] = &[
130 "p", "div", "li", "tr", "h1", "h2", "h3", "h4", "h5", "h6", "br", "section", "article",
131 ];
132 for node in el.children() {
133 if let Some(child) = scraper::ElementRef::wrap(node) {
134 let tag = child.value().name();
135 if SKIP.contains(&tag) {
136 continue;
137 }
138 walk_html(child, out);
139 if BLOCK.contains(&tag) && !out.ends_with('\n') {
140 out.push('\n');
141 }
142 } else if let Some(text) = node.value().as_text() {
143 let t: &str = text;
144 if !t.trim().is_empty() {
145 out.push_str(t);
146 }
147 }
148 }
149}
150
151pub fn csv_text(bytes: &[u8], tsv: bool) -> anyhow::Result<String> {
152 let decoded = plain_text(bytes);
153 let mut reader = csv::ReaderBuilder::new()
154 .delimiter(if tsv { b'\t' } else { b',' })
155 .flexible(true)
156 .has_headers(false)
157 .from_reader(decoded.as_bytes());
158 let mut out = String::new();
159 for (i, record) in reader.records().enumerate() {
160 if i >= 10_000 {
161 break;
162 }
163 let record = record?;
164 out.push_str(&record.iter().collect::<Vec<_>>().join(" | "));
165 out.push('\n');
166 }
167 Ok(out)
168}
169
170// ---- 工具 ----
171
172fn read_zip_entry(bytes: &[u8], name: &str) -> anyhow::Result<String> {
173 let mut archive = zip::ZipArchive::new(Cursor::new(bytes.to_vec()))?;
174 let mut entry = archive.by_name(name)?;
175 let mut content = String::new();
176 entry.read_to_string(&mut content)?;
177 Ok(content)
178}
179
180/// 从 OOXML 里抽取 `text_tag`(如 w:t)内的文本,遇 `para_tag`(如 w:p)结束换行。
181fn extract_xml_text(xml: &str, text_tag: &str, para_tag: &str) -> anyhow::Result<String> {
182 let mut reader = Reader::from_str(xml);
183 let mut out = String::new();
184 let mut in_text = false;
185 loop {
186 match reader.read_event() {
187 Ok(Event::Start(e)) if e.name().as_ref() == text_tag => in_text = true,
188 Ok(Event::End(e)) => {
189 let name = e.name();
190 if name.as_ref() == text_tag {
191 in_text = false;
192 } else if name.as_ref() == para_tag {
193 out.push('\n');
194 }
195 }
196 Ok(Event::Text(t)) if in_text => {
197 out.push_str(&t.xml_content(quick_xml::XmlVersion::Implicit1_0));
198 }
199 Ok(Event::Eof) => break,
200 Err(e) => anyhow::bail!("XML parse error: {e}"),
201 _ => {}
202 }
203 }
204 Ok(out)
205}