readability.go 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342
  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. "regexp"
  9. "strings"
  10. "miniflux.app/v2/internal/urllib"
  11. "github.com/PuerkitoBio/goquery"
  12. "golang.org/x/net/html"
  13. )
  14. const (
  15. defaultTagsToScore = "section,h2,h3,h4,h5,h6,p,td,pre,div"
  16. )
  17. var (
  18. divToPElementsRegexp = regexp.MustCompile(`(?i)<(?:a|blockquote|dl|div|img|ol|p|pre|table|ul)[ />]`)
  19. strongCandidates = [...]string{"popupbody", "-ad", "g-plus"}
  20. maybeCandidate = [...]string{"and", "article", "body", "column", "main", "shadow"}
  21. unlikelyCandidate = [...]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"}
  22. positive = [...]string{"article", "blog", "body", "content", "entry", "h-entry", "hentry", "main", "page", "pagination", "post", "story", "text"}
  23. negative = [...]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"}
  24. )
  25. type candidate struct {
  26. selection *goquery.Selection
  27. score float32
  28. }
  29. func (c *candidate) Node() *html.Node {
  30. return c.selection.Get(0)
  31. }
  32. func (c *candidate) String() string {
  33. id, _ := c.selection.Attr("id")
  34. class, _ := c.selection.Attr("class")
  35. switch {
  36. case id != "" && class != "":
  37. return fmt.Sprintf("%s#%s.%s => %f", c.Node().DataAtom, id, class, c.score)
  38. case id != "":
  39. return fmt.Sprintf("%s#%s => %f", c.Node().DataAtom, id, c.score)
  40. case class != "":
  41. return fmt.Sprintf("%s.%s => %f", c.Node().DataAtom, class, c.score)
  42. }
  43. return fmt.Sprintf("%s => %f", c.Node().DataAtom, c.score)
  44. }
  45. type candidateList map[*html.Node]*candidate
  46. func (c candidateList) String() string {
  47. var output []string
  48. for _, candidate := range c {
  49. output = append(output, candidate.String())
  50. }
  51. return strings.Join(output, ", ")
  52. }
  53. // ExtractContent returns relevant content.
  54. func ExtractContent(page io.Reader) (baseURL string, extractedContent string, err error) {
  55. document, err := goquery.NewDocumentFromReader(page)
  56. if err != nil {
  57. return "", "", err
  58. }
  59. if hrefValue, exists := document.FindMatcher(goquery.Single("head base")).Attr("href"); exists {
  60. hrefValue = strings.TrimSpace(hrefValue)
  61. if urllib.IsAbsoluteURL(hrefValue) {
  62. baseURL = hrefValue
  63. }
  64. }
  65. document.Find("script,style").Remove()
  66. transformMisusedDivsIntoParagraphs(document)
  67. removeUnlikelyCandidates(document)
  68. candidates := getCandidates(document)
  69. topCandidate := getTopCandidate(document, candidates)
  70. slog.Debug("Readability parsing",
  71. slog.String("base_url", baseURL),
  72. slog.Any("candidates", candidates),
  73. slog.Any("topCandidate", topCandidate),
  74. )
  75. extractedContent = getArticle(topCandidate, candidates)
  76. return baseURL, extractedContent, nil
  77. }
  78. // Now that we have the top candidate, look through its siblings for content that might also be related.
  79. // Things like preambles, content split by ads that we removed, etc.
  80. func getArticle(topCandidate *candidate, candidates candidateList) string {
  81. var output strings.Builder
  82. output.WriteString("<div>")
  83. siblingScoreThreshold := max(10, topCandidate.score/5)
  84. topCandidate.selection.Siblings().Union(topCandidate.selection).Each(func(i int, s *goquery.Selection) {
  85. append := false
  86. tag := "div"
  87. node := s.Get(0)
  88. if node == topCandidate.Node() {
  89. append = true
  90. } else if c, ok := candidates[node]; ok && c.score >= siblingScoreThreshold {
  91. append = true
  92. } else if s.Is("p") {
  93. tag = node.Data
  94. linkDensity := getLinkDensity(s)
  95. content := s.Text()
  96. contentLength := len(content)
  97. if contentLength >= 80 {
  98. if linkDensity < .25 {
  99. append = true
  100. }
  101. } else {
  102. if linkDensity == 0 {
  103. if containsSentence(content) {
  104. append = true
  105. }
  106. }
  107. }
  108. }
  109. if append {
  110. html, _ := s.Html()
  111. output.WriteString("<" + tag + ">" + html + "</" + tag + ">")
  112. }
  113. })
  114. output.WriteString("</div>")
  115. return output.String()
  116. }
  117. func shouldRemoveCandidate(str string) bool {
  118. str = strings.ToLower(str)
  119. // Those candidates have no false-positives, no need to check against `maybeCandidate`
  120. for _, strong := range strongCandidates {
  121. if strings.Contains(str, strong) {
  122. return true
  123. }
  124. }
  125. for _, unlikely := range unlikelyCandidate {
  126. if strings.Contains(str, unlikely) {
  127. // Do we have a false positive?
  128. for _, maybe := range maybeCandidate {
  129. if strings.Contains(str, maybe) {
  130. return false
  131. }
  132. }
  133. // Nope, it's a true positive!
  134. return true
  135. }
  136. }
  137. return false
  138. }
  139. func removeUnlikelyCandidates(document *goquery.Document) {
  140. document.Find("*").Each(func(i int, s *goquery.Selection) {
  141. if s.Length() == 0 || s.Get(0).Data == "html" || s.Get(0).Data == "body" {
  142. return
  143. }
  144. // Don't remove elements within code blocks (pre or code tags)
  145. if s.Closest("pre, code").Length() > 0 {
  146. return
  147. }
  148. if class, ok := s.Attr("class"); ok && shouldRemoveCandidate(class) {
  149. s.Remove()
  150. } else if id, ok := s.Attr("id"); ok && shouldRemoveCandidate(id) {
  151. s.Remove()
  152. }
  153. })
  154. }
  155. func getTopCandidate(document *goquery.Document, candidates candidateList) *candidate {
  156. var best *candidate
  157. for _, c := range candidates {
  158. if best == nil {
  159. best = c
  160. } else if best.score < c.score {
  161. best = c
  162. }
  163. }
  164. if best == nil {
  165. best = &candidate{document.Find("body"), 0}
  166. }
  167. return best
  168. }
  169. // Loop through all paragraphs, and assign a score to them based on how content-y they look.
  170. // Then add their score to their parent node.
  171. // A score is determined by things like number of commas, class names, etc.
  172. // Maybe eventually link density.
  173. func getCandidates(document *goquery.Document) candidateList {
  174. candidates := make(candidateList)
  175. document.Find(defaultTagsToScore).Each(func(i int, s *goquery.Selection) {
  176. text := s.Text()
  177. // If this paragraph is less than 25 characters, don't even count it.
  178. if len(text) < 25 {
  179. return
  180. }
  181. parent := s.Parent()
  182. parentNode := parent.Get(0)
  183. grandParent := parent.Parent()
  184. var grandParentNode *html.Node
  185. if grandParent.Length() > 0 {
  186. grandParentNode = grandParent.Get(0)
  187. }
  188. if _, found := candidates[parentNode]; !found {
  189. candidates[parentNode] = scoreNode(parent)
  190. }
  191. if grandParentNode != nil {
  192. if _, found := candidates[grandParentNode]; !found {
  193. candidates[grandParentNode] = scoreNode(grandParent)
  194. }
  195. }
  196. // Add a point for the paragraph itself as a base.
  197. contentScore := float32(1.0)
  198. // Add points for any commas within this paragraph.
  199. contentScore += float32(strings.Count(text, ",") + 1)
  200. // For every 100 characters in this paragraph, add another point. Up to 3 points.
  201. contentScore += float32(min(len(text)/100.0, 3))
  202. candidates[parentNode].score += contentScore
  203. if grandParentNode != nil {
  204. candidates[grandParentNode].score += contentScore / 2.0
  205. }
  206. })
  207. // Scale the final candidates score based on link density. Good content
  208. // should have a relatively small link density (5% or less) and be mostly
  209. // unaffected by this operation
  210. for _, candidate := range candidates {
  211. candidate.score *= (1 - getLinkDensity(candidate.selection))
  212. }
  213. return candidates
  214. }
  215. func scoreNode(s *goquery.Selection) *candidate {
  216. c := &candidate{selection: s, score: 0}
  217. switch s.Get(0).DataAtom.String() {
  218. case "div":
  219. c.score += 5
  220. case "pre", "td", "blockquote", "img":
  221. c.score += 3
  222. case "address", "ol", "ul", "dl", "dd", "dt", "li", "form":
  223. c.score -= 3
  224. case "h1", "h2", "h3", "h4", "h5", "h6", "th":
  225. c.score -= 5
  226. }
  227. c.score += getClassWeight(s)
  228. return c
  229. }
  230. // Get the density of links as a percentage of the content
  231. // This is the amount of text that is inside a link divided by the total text in the node.
  232. func getLinkDensity(s *goquery.Selection) float32 {
  233. textLength := len(s.Text())
  234. if textLength == 0 {
  235. return 0
  236. }
  237. linkLength := len(s.Find("a").Text())
  238. return float32(linkLength) / float32(textLength)
  239. }
  240. // Get an elements class/id weight. Uses regular expressions to tell if this
  241. // element looks good or bad.
  242. func getClassWeight(s *goquery.Selection) float32 {
  243. weight := 0
  244. if class, ok := s.Attr("class"); ok {
  245. weight += getWeight(class)
  246. }
  247. if id, ok := s.Attr("id"); ok {
  248. weight += getWeight(id)
  249. }
  250. return float32(weight)
  251. }
  252. func getWeight(s string) int {
  253. s = strings.ToLower(s)
  254. for _, pos := range negative {
  255. if strings.Contains(s, pos) {
  256. return -25
  257. }
  258. }
  259. for _, pos := range positive {
  260. if strings.Contains(s, pos) {
  261. return +25
  262. }
  263. }
  264. return 0
  265. }
  266. func transformMisusedDivsIntoParagraphs(document *goquery.Document) {
  267. document.Find("div").Each(func(i int, s *goquery.Selection) {
  268. html, _ := s.Html()
  269. if !divToPElementsRegexp.MatchString(html) {
  270. node := s.Get(0)
  271. node.Data = "p"
  272. }
  273. })
  274. }
  275. func containsSentence(content string) bool {
  276. return strings.HasSuffix(content, ".") || strings.Contains(content, ". ")
  277. }