Files
Liber-public/crates/liber-format/src/txt.rs
T

130 lines
5.0 KiB
Rust

//! Plain text: encoding detection, paragraphs, chapters by heading lines or by size.
use crate::sanitize::Element;
use crate::{Document, Format, FormatError, Limits, Metadata, Result, TocEntry, text};
const CHUNK: usize = 40_000;
fn roman(s: &str) -> bool {
let s = s.trim_end_matches('.');
!s.is_empty() && s.len() <= 8 && s.chars().all(|c| matches!(c, 'I' | 'V' | 'X' | 'L' | 'C'))
}
/// A heading line: `Chapter 3`, `KAPITOLA III.`, `Kapitel 3`, a lone Roman numeral or number.
pub(crate) fn heading(p: &str) -> bool {
let p = p.trim();
if p.is_empty() || p.chars().count() > 80 || p.contains('\n') {
return false;
}
if roman(p)
|| (p.trim_end_matches('.').len() <= 3
&& p.trim_end_matches('.').chars().all(|c| c.is_ascii_digit())
&& !p.is_empty())
{
return true;
}
const NUMBERS: &[&str] = &[
"one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "first",
"second", "third", "last", "první", "druhá", "třetí", "eins", "zwei", "drei",
];
let lower = p.to_lowercase();
for w in ["chapter", "kapitola", "kapitel", "část", "part", "book", "kniha", "buch", "teil"] {
if let Some(rest) = lower.strip_prefix(w)
&& rest.starts_with(' ')
{
let next = rest.split_whitespace().next().unwrap_or("").trim_end_matches(['.', ':']);
return (!next.is_empty() && next.chars().all(|c| c.is_ascii_digit()))
|| roman(&next.to_uppercase())
|| NUMBERS.contains(&next);
}
}
["prologue", "epilogue", "prolog", "epilog"].iter().any(|w| lower == *w || lower.starts_with(&format!("{w}:")))
}
pub(crate) fn open(bytes: &[u8], name: Option<&str>, limits: &Limits) -> Result<Document> {
let (raw, _enc) = text::decode_text(bytes);
if raw.len() > limits.max_text {
return Err(FormatError::TooLarge("the text is larger than the limit".into()));
}
if raw.chars().take(4096).filter(|c| *c == '\u{0}').count() > 16 {
return Err(FormatError::Unsupported("this does not look like a book (binary data)".into()));
}
let s = raw.replace("\r\n", "\n").replace('\r', "\n");
let blank_separated = s.contains("\n\n");
let paras: Vec<String> = if blank_separated {
s.split("\n\n")
.map(|p| p.lines().map(str::trim).filter(|l| !l.is_empty()).collect::<Vec<_>>().join(" "))
.collect()
} else {
s.lines().map(|l| l.trim().to_owned()).collect()
};
let paras: Vec<String> = paras.into_iter().filter(|p| !p.is_empty()).collect();
let mut meta = Metadata::default();
// Project Gutenberg's header.
for line in s.lines().take(100) {
if let Some(t) = line.strip_prefix("Title:") {
meta.title.get_or_insert_with(|| text::collapse(t));
} else if let Some(a) = line.strip_prefix("Author:") {
if meta.authors.is_empty() {
meta.authors.push(text::collapse(a));
}
} else if let Some(l) = line.strip_prefix("Language:") {
meta.language.get_or_insert_with(|| text::collapse(l));
}
}
if meta.title.is_none() {
meta.title = name.map(|n| {
let base = n.rsplit(['/', '\\']).next().unwrap_or(n);
base.rsplit_once('.').map_or(base, |(b, _)| b).replace('_', " ")
});
}
// Chapters: at heading lines; else by size.
let mut groups: Vec<(Option<String>, Vec<String>)> = Vec::new();
let has_headings = paras.iter().filter(|p| heading(p)).count() >= 2;
for p in paras {
if has_headings && heading(&p) {
groups.push((Some(p), Vec::new()));
continue;
}
let size: usize = groups.last().map_or(0, |g| g.1.iter().map(String::len).sum());
if groups.is_empty() || (!has_headings && size > CHUNK) {
groups.push((None, Vec::new()));
}
if let Some(g) = groups.last_mut() {
g.1.push(p);
}
}
if groups.len() > limits.max_chapters {
return Err(FormatError::TooLarge(format!("more than {} chapters", limits.max_chapters)));
}
let mut chapters = Vec::new();
let mut toc = Vec::new();
for (i, (title, ps)) in groups.into_iter().enumerate() {
let mut root = Element::new("div");
if let Some(t) = &title {
let mut h = Element::new("h2");
h.push_text(t);
root.push(h);
toc.push(TocEntry { title: text::collapse(t), chapter: i, fragment: None, children: vec![] });
}
for p in ps {
let mut e = Element::new("p");
e.push_text(&p);
root.push(e);
}
chapters.push(crate::chapter(format!("chapter-{i}"), title, true, root));
}
Ok(Document {
format: Format::Txt,
metadata: meta,
chapters,
toc,
footnotes: Default::default(),
images: vec![],
cover: None,
warnings: vec![],
})
}