aKode fase 5: rinomina interna (crate akode-*, akode-rs/, akode-cli/, binario akode, AKODE_*, ~/.akode, snapshot)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
andrea.difonzo
2026-11-11 11:06:46 +01:00
parent df99318392
commit 86e7c72e5f
10383 changed files with 749164 additions and 749170 deletions

View File

@@ -0,0 +1,461 @@
//! Small hand-written HTML-to-text extractor. It is not a conforming HTML
//! parser; it aims to produce readable text for a language model from
//! typical web pages without pulling in a parsing dependency.
/// Text extracted from an HTML document.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ExtractedHtml {
pub title: Option<String>,
pub text: String,
}
/// Elements whose content is raw text that must be skipped entirely.
const RAW_SKIP: &[&str] = &["script", "style"];
/// Container elements whose whole subtree is dropped.
const SKIP_CONTAINERS: &[&str] = &[
"head", "noscript", "template", "svg", "math", "iframe", "object", "canvas",
];
/// Elements separated from their surroundings by a blank line.
const PARAGRAPH_ELEMENTS: &[&str] = &[
"blockquote",
"dl",
"figure",
"h1",
"h2",
"h3",
"h4",
"h5",
"h6",
"ol",
"p",
"table",
"ul",
];
/// Elements that start a new line in the extracted text.
const BLOCK_ELEMENTS: &[&str] = &[
"address",
"article",
"aside",
"blockquote",
"body",
"caption",
"dd",
"details",
"dialog",
"div",
"dl",
"dt",
"fieldset",
"figcaption",
"figure",
"footer",
"form",
"h1",
"h2",
"h3",
"h4",
"h5",
"h6",
"header",
"hr",
"html",
"legend",
"main",
"menu",
"nav",
"ol",
"p",
"pre",
"section",
"summary",
"table",
"tbody",
"tfoot",
"thead",
"tr",
"ul",
];
/// Converts an HTML document into plain text plus its `<title>`.
pub fn html_to_text(html: &str) -> ExtractedHtml {
let mut extractor = Extractor::default();
extractor.run(html);
ExtractedHtml {
title: extractor
.title
.map(|t| collapse_inline_whitespace(&t))
.filter(|t| !t.is_empty()),
text: normalize_whitespace(&extractor.out),
}
}
#[derive(Default)]
struct Extractor {
out: String,
title: Option<String>,
skip_stack: Vec<String>,
pre_depth: usize,
}
impl Extractor {
fn run(&mut self, html: &str) {
let bytes = html.as_bytes();
let len = bytes.len();
let mut i = 0;
while i < len {
if bytes[i] != b'<' {
let next = html[i..].find('<').map_or(len, |p| i + p);
self.push_text(&html[i..next]);
i = next;
continue;
}
let rest = &html[i..];
if let Some(comment) = rest.strip_prefix("<!--") {
match comment.find("-->") {
Some(p) => i += 4 + p + 3,
None => break,
}
continue;
}
if rest.starts_with("<!") || rest.starts_with("<?") {
i = rest.find('>').map_or(len, |p| i + p + 1);
continue;
}
let (is_close, name_start) = if bytes.get(i + 1) == Some(&b'/') {
(true, i + 2)
} else {
(false, i + 1)
};
if name_start >= len || !bytes[name_start].is_ascii_alphabetic() {
// A literal '<' in text.
self.push_text("<");
i += 1;
continue;
}
let mut name_end = name_start;
while name_end < len
&& (bytes[name_end].is_ascii_alphanumeric()
|| bytes[name_end] == b'-'
|| bytes[name_end] == b':')
{
name_end += 1;
}
let name = html[name_start..name_end].to_ascii_lowercase();
let tag_end = find_tag_end(bytes, name_end);
let self_closing =
tag_end >= 2 && bytes[tag_end - 1] == b'>' && bytes[tag_end - 2] == b'/';
i = tag_end;
if !is_close && !self_closing && (RAW_SKIP.contains(&name.as_str()) || name == "title")
{
let (content_end, after) = find_closing_tag(html, i, &name);
if name == "title" && self.title.is_none() {
self.title = Some(decode_entities(&html[i..content_end]));
}
i = after;
continue;
}
self.handle_tag(&name, is_close, self_closing);
}
}
fn handle_tag(&mut self, name: &str, is_close: bool, self_closing: bool) {
if SKIP_CONTAINERS.contains(&name) {
if is_close {
if let Some(pos) = self.skip_stack.iter().rposition(|n| n == name) {
self.skip_stack.truncate(pos);
}
} else if !self_closing {
self.skip_stack.push(name.to_string());
}
return;
}
if name == "body" && !is_close {
// `<body>` implicitly closes an unterminated `<head>`.
if let Some(pos) = self.skip_stack.iter().position(|n| n == "head") {
self.skip_stack.truncate(pos);
}
}
if !self.skip_stack.is_empty() {
return;
}
match name {
"br" => self.out.push('\n'),
"li" if !is_close => {
self.ensure_breaks(1);
self.out.push_str("- ");
}
"td" | "th" if !is_close => self.out.push(' '),
"pre" => {
if is_close {
self.pre_depth = self.pre_depth.saturating_sub(1);
} else if !self_closing {
self.pre_depth += 1;
}
self.ensure_breaks(2);
}
_ if PARAGRAPH_ELEMENTS.contains(&name) => self.ensure_breaks(2),
_ if BLOCK_ELEMENTS.contains(&name) => self.ensure_breaks(1),
_ => {}
}
}
/// Makes sure the output ends with at least `n` line breaks (ignoring
/// trailing spaces). Nothing is added at the very start of the output.
fn ensure_breaks(&mut self, n: usize) {
let trimmed = self.out.trim_end_matches(' ');
if trimmed.is_empty() {
return;
}
let have = trimmed.len() - trimmed.trim_end_matches('\n').len();
for _ in have..n {
self.out.push('\n');
}
}
fn push_text(&mut self, raw: &str) {
if !self.skip_stack.is_empty() {
return;
}
let decoded = decode_entities(raw);
let keep_newlines = self.pre_depth > 0;
for c in decoded.chars() {
if c == '\n' && keep_newlines {
self.out.push('\n');
} else if c.is_whitespace() {
self.out.push(' ');
} else {
self.out.push(c);
}
}
}
}
/// Returns the index just past the `>` ending the tag whose name ends at
/// `from`, honouring quoted attribute values.
fn find_tag_end(bytes: &[u8], from: usize) -> usize {
let mut quote: Option<u8> = None;
let mut i = from;
while i < bytes.len() {
let b = bytes[i];
match quote {
Some(q) if b == q => quote = None,
Some(_) => {}
None if b == b'"' || b == b'\'' => quote = Some(b),
None if b == b'>' => return i + 1,
None => {}
}
i += 1;
}
bytes.len()
}
/// Finds `</name ...>` (case-insensitive) starting at `from`. Returns the
/// end of the content and the index after the closing tag; both are the
/// end of input when the element is never closed.
fn find_closing_tag(html: &str, from: usize, name: &str) -> (usize, usize) {
let bytes = html.as_bytes();
let needle = name.as_bytes();
let mut i = from;
while let Some(p) = html[i..].find("</") {
let start = i + p;
let name_start = start + 2;
let name_end = name_start + needle.len();
if name_end <= bytes.len()
&& bytes[name_start..name_end].eq_ignore_ascii_case(needle)
&& bytes
.get(name_end)
.is_none_or(|b| !b.is_ascii_alphanumeric())
{
return (start, find_tag_end(bytes, name_end));
}
i = name_start;
}
(html.len(), html.len())
}
fn named_entity(name: &str) -> Option<char> {
let c = match name {
"amp" | "AMP" => '&',
"lt" | "LT" => '<',
"gt" | "GT" => '>',
"quot" | "QUOT" => '"',
"apos" => '\'',
"nbsp" => ' ',
"copy" | "COPY" => '©',
"reg" | "REG" => '®',
"trade" => '™',
"hellip" => '…',
"mdash" => '—',
"ndash" => '–',
"lsquo" => '‘',
"rsquo" => '’',
"sbquo" => '‚',
"ldquo" => '“',
"rdquo" => '”',
"bdquo" => '„',
"laquo" => '«',
"raquo" => '»',
"bull" => '•',
"middot" => '·',
"deg" => '°',
"plusmn" => '±',
"times" => '×',
"divide" => '÷',
"sect" => '§',
"para" => '¶',
"euro" => '€',
"pound" => '£',
"yen" => '¥',
"cent" => '¢',
"shy" => '\u{ad}',
"zwj" => '\u{200d}',
"zwnj" => '\u{200c}',
_ => return None,
};
Some(c)
}
/// Parses an entity at the start of `s` (which begins with `&`). Returns the
/// decoded character and the number of bytes consumed.
fn parse_entity(s: &str) -> Option<(char, usize)> {
let semi = s.bytes().take(32).position(|b| b == b';')?;
let body = &s[1..semi];
let c = if let Some(num) = body.strip_prefix('#') {
let code = if let Some(hex) = num.strip_prefix(['x', 'X']) {
if hex.is_empty() || !hex.bytes().all(|b| b.is_ascii_hexdigit()) {
return None;
}
u32::from_str_radix(hex, 16).unwrap_or(u32::MAX)
} else {
if num.is_empty() || !num.bytes().all(|b| b.is_ascii_digit()) {
return None;
}
num.parse::<u32>().unwrap_or(u32::MAX)
};
char::from_u32(code)
.filter(|c| *c != '\0')
.unwrap_or('\u{fffd}')
} else {
named_entity(body)?
};
Some((c, semi + 1))
}
/// Decodes common named entities and numeric character references.
/// Unknown or unterminated entities are left untouched.
pub fn decode_entities(s: &str) -> String {
if !s.contains('&') {
return s.to_string();
}
let mut out = String::with_capacity(s.len());
let mut rest = s;
while let Some(p) = rest.find('&') {
out.push_str(&rest[..p]);
rest = &rest[p..];
match parse_entity(rest) {
Some((c, consumed)) => {
out.push(c);
rest = &rest[consumed..];
}
None => {
out.push('&');
rest = &rest[1..];
}
}
}
out.push_str(rest);
out
}
fn collapse_inline_whitespace(s: &str) -> String {
s.split_whitespace().collect::<Vec<_>>().join(" ")
}
/// Collapses runs of whitespace within lines, trims lines and keeps at most
/// one blank line between paragraphs.
pub(crate) fn normalize_whitespace(s: &str) -> String {
let mut out = String::with_capacity(s.len());
let mut pending_blank = false;
for line in s.split('\n') {
let line = collapse_inline_whitespace(line);
if line.is_empty() {
pending_blank = !out.is_empty();
continue;
}
if !out.is_empty() {
out.push('\n');
if pending_blank {
out.push('\n');
}
}
pending_blank = false;
out.push_str(&line);
}
out
}
#[cfg(test)]
mod tests {
use super::*;
use pretty_assertions::assert_eq;
#[test]
fn extracts_text_and_title() {
let html = r#"<!DOCTYPE html>
<html><head><title> Hello &amp; welcome </title>
<meta charset="utf-8"><style>body { color: red; }</style>
<script>var x = "<p>not text</p>";</script></head>
<body>
<!-- a comment <p>hidden</p> -->
<h1>Heading</h1>
<p>First paragraph with <b>bold</b> and <a href="/x?a=1&amp;b=2">a link</a>.</p>
<noscript>enable js</noscript>
<template><p>tpl</p></template>
<svg viewBox="0 0 1 1"><text>svg text</text></svg>
<ul><li>one</li><li>two</li></ul>
<div>a<br>b</div>
<p>Entities: &lt;tag&gt; &quot;q&quot; &#39;s&#39; &#65;&#x42;&nbsp;end &unknown; & alone</p>
</body></html>"#;
let extracted = html_to_text(html);
assert_eq!(extracted.title.as_deref(), Some("Hello & welcome"));
assert_eq!(
extracted.text,
"Heading\n\nFirst paragraph with bold and a link.\n\n- one\n- two\n\na\nb\n\nEntities: <tag> \"q\" 's' AB end &unknown; & alone"
);
}
#[test]
fn head_without_close_ends_at_body() {
let extracted = html_to_text("<head><meta x='>'>junk<body>visible");
assert_eq!(extracted.text, "visible");
assert_eq!(extracted.title, None);
}
#[test]
fn unclosed_script_drops_rest() {
assert_eq!(html_to_text("<p>a</p><script>if (a < b) {").text, "a");
}
#[test]
fn script_close_is_case_insensitive() {
assert_eq!(html_to_text("x<SCRIPT>y</Script >z").text, "xz");
}
#[test]
fn pre_keeps_newlines() {
assert_eq!(html_to_text("<pre>a\nb</pre>").text, "a\nb");
}
#[test]
fn literal_less_than_and_numeric_entities() {
assert_eq!(
decode_entities("1 &lt; 2 &#0; &#xD800; &#x1F600;"),
"1 < 2 \u{fffd} \u{fffd} 😀"
);
assert_eq!(html_to_text("a < b").text, "a < b");
}
}