77 lines
1.6 KiB
Go
77 lines
1.6 KiB
Go
package articlecontent
|
|
|
|
import (
|
|
"strings"
|
|
"unicode"
|
|
|
|
"golang.org/x/net/html"
|
|
)
|
|
|
|
// candidateBodyLength measures a unique recognized editorial root without
|
|
// constructing or retaining candidate text. It runs before identity rejection,
|
|
// never feeds extraction, and saturates at the largest bucket's lower bound.
|
|
func candidateBodyLength(root *html.Node) int {
|
|
total, chunk, paragraphs := 0, 0, 0
|
|
pendingSpace := false
|
|
flush := func() {
|
|
if chunk > 0 {
|
|
if paragraphs > 0 {
|
|
total += 2
|
|
} // Existing editorial paragraph separator.
|
|
total += chunk
|
|
paragraphs++
|
|
}
|
|
chunk = 0
|
|
pendingSpace = false
|
|
}
|
|
var walk func(*html.Node)
|
|
walk = func(n *html.Node) {
|
|
if total+chunk > 2000 || excluded(n) {
|
|
return
|
|
}
|
|
marker := strings.ToLower(attr(n, "class") + " " + attr(n, "id") + " " + attr(n, "data-component"))
|
|
if strings.Contains(marker, "placeholder") || strings.Contains(marker, "skeleton") {
|
|
return
|
|
}
|
|
if n.Type == html.TextNode {
|
|
for _, r := range n.Data {
|
|
if unicode.IsSpace(r) {
|
|
if chunk > 0 {
|
|
pendingSpace = true
|
|
}
|
|
continue
|
|
}
|
|
if pendingSpace {
|
|
chunk++
|
|
pendingSpace = false
|
|
}
|
|
chunk++
|
|
if total+chunk > 2000 {
|
|
break
|
|
}
|
|
}
|
|
return
|
|
}
|
|
block := false
|
|
switch n.Data {
|
|
case "p", "div", "section", "h1", "h2", "h3", "h4", "h5", "h6", "li", "ul", "ol", "blockquote", "pre", "figcaption", "table", "tr", "td", "th":
|
|
block = true
|
|
}
|
|
if block {
|
|
flush()
|
|
}
|
|
if n.Data == "br" && chunk > 0 {
|
|
pendingSpace = true
|
|
}
|
|
for c := n.FirstChild; c != nil; c = c.NextSibling {
|
|
walk(c)
|
|
}
|
|
if block {
|
|
flush()
|
|
}
|
|
}
|
|
walk(root)
|
|
flush()
|
|
return min(total, 2001)
|
|
}
|