readability.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383
  1. // SPDX-FileCopyrightText: Copyright The Miniflux Authors. All rights reserved.
  2. // SPDX-License-Identifier: Apache-2.0
  3. package readability // import "miniflux.app/v2/internal/reader/readability"
  4. import (
  5. "fmt"
  6. "io"
  7. "log/slog"
  8. "strings"
  9. "miniflux.app/v2/internal/urllib"
  10. "github.com/PuerkitoBio/goquery"
  11. "golang.org/x/net/html"
  12. )
  13. const defaultTagsToScore = "section,h2,h3,h4,h5,h6,p,td,pre,div"
  14. var (
  15. strongCandidatesToRemove = [...]string{"popupbody", "-ad", "g-plus"}
  16. maybeCandidateToRemove = [...]string{"and", "article", "body", "column", "main", "shadow", "content"}
  17. unlikelyCandidateToRemove = [...]string{"banner", "breadcrumbs", "combx", "comment", "community", "cover-wrap", "disqus", "extra", "foot", "header", "legends", "menu", "modal", "related", "remark", "replies", "rss", "shoutbox", "sidebar", "skyscraper", "social", "sponsor", "supplemental", "ad-break", "agegate", "pagination", "pager", "popup", "yom-remote"}
  18. positiveKeywords = [...]string{"article", "blog", "body", "content", "entry", "h-entry", "hentry", "main", "page", "pagination", "post", "story", "text"}
  19. negativeKeywords = [...]string{"author", "banner", "byline", "com-", "combx", "comment", "contact", "dateline", "foot", "hid", "masthead", "media", "meta", "modal", "outbrain", "promo", "related", "scroll", "share", "shopping", "shoutbox", "sidebar", "skyscraper", "sponsor", "tags", "tool", "widget", "writtenby"}
  20. )
  21. type candidate struct {
  22. selection *goquery.Selection
  23. score float32
  24. }
  25. func (c *candidate) Node() *html.Node {
  26. if c.selection.Length() == 0 {
  27. return nil
  28. }
  29. return c.selection.Get(0)
  30. }
  31. func (c *candidate) String() string {
  32. node := c.Node()
  33. if node == nil {
  34. return fmt.Sprintf("empty => %f", c.score)
  35. }
  36. id, _ := c.selection.Attr("id")
  37. class, _ := c.selection.Attr("class")
  38. switch {
  39. case id != "" && class != "":
  40. return fmt.Sprintf("%s#%s.%s => %f", node.DataAtom, id, class, c.score)
  41. case id != "":
  42. return fmt.Sprintf("%s#%s => %f", node.DataAtom, id, c.score)
  43. case class != "":
  44. return fmt.Sprintf("%s.%s => %f", node.DataAtom, class, c.score)
  45. }
  46. return fmt.Sprintf("%s => %f", node.DataAtom, c.score)
  47. }
  48. type candidateList map[*html.Node]*candidate
  49. func (c candidateList) String() string {
  50. var output []string
  51. for _, candidate := range c {
  52. output = append(output, candidate.String())
  53. }
  54. return strings.Join(output, ", ")
  55. }
  56. // ExtractContent returns relevant content.
  57. func ExtractContent(page io.Reader) (baseURL string, extractedContent string, err error) {
  58. document, err := goquery.NewDocumentFromReader(page)
  59. if err != nil {
  60. return "", "", err
  61. }
  62. if hrefValue, exists := document.FindMatcher(goquery.Single("head base")).Attr("href"); exists {
  63. hrefValue = strings.TrimSpace(hrefValue)
  64. if urllib.IsAbsoluteURL(hrefValue) {
  65. baseURL = hrefValue
  66. }
  67. }
  68. document.Find("script,style").Remove()
  69. removeUnlikelyCandidates(document)
  70. transformMisusedDivsIntoParagraphs(document)
  71. candidates := getCandidates(document)
  72. topCandidate := getTopCandidate(document, candidates)
  73. slog.Debug("Readability parsing",
  74. slog.String("base_url", baseURL),
  75. slog.String("candidates", candidates.String()),
  76. slog.String("topCandidate", topCandidate.String()),
  77. )
  78. extractedContent = getArticle(topCandidate, candidates)
  79. return baseURL, extractedContent, nil
  80. }
  81. func getSelectionLength(s *goquery.Selection) int {
  82. return sumMapOnSelection(s, func(s string) int { return len(s) })
  83. }
  84. func getSelectionCommaCount(s *goquery.Selection) int {
  85. return sumMapOnSelection(s, func(s string) int { return strings.Count(s, ",") })
  86. }
  87. // sumMapOnSelection maps `f` on the selection, and return the sum of the result.
  88. // This construct is used instead of goquery.Selection's .Text() method,
  89. // to avoid materializing the text to simply map/sum on it, saving a significant
  90. // amount of memory of large selections, and reducing the pressure on the garbage-collector.
  91. func sumMapOnSelection(s *goquery.Selection, f func(str string) int) int {
  92. var recursiveFunction func(*html.Node) int
  93. recursiveFunction = func(n *html.Node) int {
  94. total := 0
  95. if n.Type == html.TextNode {
  96. total += f(n.Data)
  97. }
  98. if n.FirstChild != nil {
  99. for c := n.FirstChild; c != nil; c = c.NextSibling {
  100. total += recursiveFunction(c)
  101. }
  102. }
  103. return total
  104. }
  105. sum := 0
  106. for _, n := range s.Nodes {
  107. sum += recursiveFunction(n)
  108. }
  109. return sum
  110. }
  111. // Now that we have the top candidate, look through its siblings for content that might also be related.
  112. // Things like preambles, content split by ads that we removed, etc.
  113. func getArticle(topCandidate *candidate, candidates candidateList) string {
  114. var output strings.Builder
  115. output.WriteString("<div>")
  116. siblingScoreThreshold := max(10, topCandidate.score/5)
  117. topCandidate.selection.Siblings().Union(topCandidate.selection).Each(func(i int, s *goquery.Selection) {
  118. append := false
  119. tag := "div"
  120. node := s.Get(0)
  121. topNode := topCandidate.Node()
  122. if topNode != nil && node == topNode {
  123. append = true
  124. } else if c, ok := candidates[node]; ok && c.score >= siblingScoreThreshold {
  125. append = true
  126. } else if s.Is("p") {
  127. tag = node.Data
  128. linkDensity := getLinkDensity(s)
  129. contentLength := getSelectionLength(s)
  130. if contentLength >= 80 {
  131. if linkDensity < .25 {
  132. append = true
  133. }
  134. } else {
  135. if linkDensity == 0 {
  136. // It's a small selection, so .Text doesn't impact performances too much.
  137. if containsSentence(s.Text()) {
  138. append = true
  139. }
  140. }
  141. }
  142. }
  143. if append {
  144. html, _ := s.Html()
  145. output.WriteString("<" + tag + ">" + html + "</" + tag + ">")
  146. }
  147. })
  148. output.WriteString("</div>")
  149. return output.String()
  150. }
  151. func shouldRemoveCandidate(str string) bool {
  152. str = strings.ToLower(str)
  153. // Those candidates have no false-positives, no need to check against `maybeCandidate`
  154. for _, strongCandidateToRemove := range strongCandidatesToRemove {
  155. if strings.Contains(str, strongCandidateToRemove) {
  156. return true
  157. }
  158. }
  159. for _, unlikelyCandidateToRemove := range unlikelyCandidateToRemove {
  160. if strings.Contains(str, unlikelyCandidateToRemove) {
  161. // Do we have a false positive?
  162. for _, maybeCandidateToRemove := range maybeCandidateToRemove {
  163. if strings.Contains(str, maybeCandidateToRemove) {
  164. return false
  165. }
  166. }
  167. // Nope, it's a true positive!
  168. return true
  169. }
  170. }
  171. return false
  172. }
  173. func removeUnlikelyCandidates(document *goquery.Document) {
  174. // Only select tags with either a class or an id attribute,
  175. // and never the html nor body tags, as we don't want to ever remove them.
  176. selector := "[class]:not(body,html)" + "," + "[id]:not(body,html)"
  177. for _, s := range document.Find(selector).EachIter() {
  178. if s.Length() == 0 {
  179. continue
  180. }
  181. // Don't remove elements within code blocks (pre or code tags)
  182. if s.Closest("pre,code").Length() > 0 {
  183. continue
  184. }
  185. if class, ok := s.Attr("class"); ok && shouldRemoveCandidate(class) {
  186. s.Remove()
  187. } else if id, ok := s.Attr("id"); ok && shouldRemoveCandidate(id) {
  188. s.Remove()
  189. }
  190. }
  191. }
  192. func getTopCandidate(document *goquery.Document, candidates candidateList) *candidate {
  193. var best *candidate
  194. for _, c := range candidates {
  195. if best == nil {
  196. best = c
  197. } else if best.score < c.score {
  198. best = c
  199. }
  200. }
  201. if best == nil {
  202. best = &candidate{document.Find("body"), 0}
  203. }
  204. return best
  205. }
  206. // Loop through all paragraphs, and assign a score to them based on how content-y they look.
  207. // Then add their score to their parent node.
  208. // A score is determined by things like number of commas, class names, etc.
  209. func getCandidates(document *goquery.Document) candidateList {
  210. candidates := make(candidateList)
  211. document.Find(defaultTagsToScore).Each(func(i int, s *goquery.Selection) {
  212. textLen := getSelectionLength(s)
  213. // If this paragraph is less than 25 characters, don't even count it.
  214. if textLen < 25 {
  215. return
  216. }
  217. // Add a point for the paragraph itself as a base.
  218. contentScore := 1
  219. // Add points for any commas within this paragraph.
  220. contentScore += getSelectionCommaCount(s) + 1
  221. // For every 100 characters in this paragraph, add another point. Up to 3 points.
  222. contentScore += min(textLen/100, 3)
  223. parent := s.Parent()
  224. parentNode := parent.Get(0)
  225. if _, found := candidates[parentNode]; !found {
  226. candidates[parentNode] = scoreNode(parent)
  227. }
  228. candidates[parentNode].score += float32(contentScore)
  229. // The score of the current node influences its grandparent's one as well, but scaled to 50%.
  230. grandParent := parent.Parent()
  231. if grandParent.Length() > 0 {
  232. grandParentNode := grandParent.Get(0)
  233. if _, found := candidates[grandParentNode]; !found {
  234. candidates[grandParentNode] = scoreNode(grandParent)
  235. }
  236. candidates[grandParentNode].score += float32(contentScore) / 2.0
  237. }
  238. })
  239. // Scale the final candidates score based on link density. Good content
  240. // should have a relatively small link density (5% or less) and be mostly
  241. // unaffected by this operation
  242. for _, candidate := range candidates {
  243. candidate.score *= (1 - getLinkDensity(candidate.selection))
  244. }
  245. return candidates
  246. }
  247. func scoreNode(s *goquery.Selection) *candidate {
  248. c := &candidate{selection: s, score: 0}
  249. // Check if selection is empty to avoid panic
  250. if s.Length() == 0 {
  251. return c
  252. }
  253. switch s.Get(0).Data {
  254. case "div":
  255. c.score += 5
  256. case "pre", "td", "blockquote", "img":
  257. c.score += 3
  258. case "address", "ol", "ul", "dl", "dd", "dt", "li", "form":
  259. c.score -= 3
  260. case "h1", "h2", "h3", "h4", "h5", "h6", "th":
  261. c.score -= 5
  262. }
  263. if class, ok := s.Attr("class"); ok {
  264. c.score += getWeight(class)
  265. }
  266. if id, ok := s.Attr("id"); ok {
  267. c.score += getWeight(id)
  268. }
  269. return c
  270. }
  271. // Get the density of links as a percentage of the content
  272. // This is the amount of text that is inside a link divided by the total text in the node.
  273. func getLinkDensity(s *goquery.Selection) float32 {
  274. sum := getSelectionLength(s)
  275. if sum == 0 {
  276. return 0
  277. }
  278. linkLength := getSelectionLength(s.Find("a"))
  279. return float32(linkLength) / float32(sum)
  280. }
  281. func getWeight(s string) float32 {
  282. s = strings.ToLower(s)
  283. for _, keyword := range negativeKeywords {
  284. if strings.Contains(s, keyword) {
  285. return -25
  286. }
  287. }
  288. for _, keyword := range positiveKeywords {
  289. if strings.Contains(s, keyword) {
  290. return +25
  291. }
  292. }
  293. return 0
  294. }
  295. func transformMisusedDivsIntoParagraphs(document *goquery.Document) {
  296. document.Find("div").Each(func(i int, s *goquery.Selection) {
  297. nodes := s.Children().Nodes
  298. if len(nodes) == 0 {
  299. s.Nodes[0].Data = "p"
  300. return
  301. }
  302. for _, node := range nodes {
  303. switch node.Data {
  304. case "a", "blockquote", "div", "dl",
  305. "img", "ol", "p", "pre",
  306. "table", "ul":
  307. return
  308. default:
  309. s.Nodes[0].Data = "p"
  310. }
  311. }
  312. })
  313. }
  314. func containsSentence(content string) bool {
  315. return strings.HasSuffix(content, ".") || strings.Contains(content, ". ")
  316. }