readability.go 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307
  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. "bytes"
  6. "fmt"
  7. "io"
  8. "log/slog"
  9. "math"
  10. "regexp"
  11. "strings"
  12. "github.com/PuerkitoBio/goquery"
  13. "golang.org/x/net/html"
  14. )
  15. const (
  16. defaultTagsToScore = "section,h2,h3,h4,h5,h6,p,td,pre,div"
  17. )
  18. var (
  19. divToPElementsRegexp = regexp.MustCompile(`(?i)<(?:a|blockquote|dl|div|img|ol|p|pre|table|ul)`)
  20. blacklistCandidatesRegexp = regexp.MustCompile(`(?i)popupbody|-ad|g-plus`)
  21. okMaybeItsACandidateRegexp = regexp.MustCompile(`(?i)and|article|body|column|main|shadow`)
  22. unlikelyCandidatesRegexp = regexp.MustCompile(`(?i)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`)
  23. negativeRegexp = regexp.MustCompile(`(?i)hidden|^hid$|hid$|hid|^hid |banner|combx|comment|com-|contact|foot|footer|footnote|masthead|media|meta|modal|outbrain|promo|related|scroll|share|shoutbox|sidebar|skyscraper|sponsor|shopping|tags|tool|widget|byline|author|dateline|writtenby|p-author`)
  24. positiveRegexp = regexp.MustCompile(`(?i)article|body|content|entry|hentry|h-entry|main|page|pagination|post|text|blog|story`)
  25. )
  26. type candidate struct {
  27. selection *goquery.Selection
  28. score float32
  29. }
  30. func (c *candidate) Node() *html.Node {
  31. return c.selection.Get(0)
  32. }
  33. func (c *candidate) String() string {
  34. id, _ := c.selection.Attr("id")
  35. class, _ := c.selection.Attr("class")
  36. if id != "" && class != "" {
  37. return fmt.Sprintf("%s#%s.%s => %f", c.Node().DataAtom, id, class, c.score)
  38. } else if id != "" {
  39. return fmt.Sprintf("%s#%s => %f", c.Node().DataAtom, id, c.score)
  40. } else if 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) (string, error) {
  55. document, err := goquery.NewDocumentFromReader(page)
  56. if err != nil {
  57. return "", err
  58. }
  59. document.Find("script,style").Each(func(i int, s *goquery.Selection) {
  60. removeNodes(s)
  61. })
  62. transformMisusedDivsIntoParagraphs(document)
  63. removeUnlikelyCandidates(document)
  64. candidates := getCandidates(document)
  65. topCandidate := getTopCandidate(document, candidates)
  66. slog.Debug("Readability parsing",
  67. slog.Any("candidates", candidates),
  68. slog.Any("topCandidate", topCandidate),
  69. )
  70. output := getArticle(topCandidate, candidates)
  71. return output, nil
  72. }
  73. // Now that we have the top candidate, look through its siblings for content that might also be related.
  74. // Things like preambles, content split by ads that we removed, etc.
  75. func getArticle(topCandidate *candidate, candidates candidateList) string {
  76. output := bytes.NewBufferString("<div>")
  77. siblingScoreThreshold := float32(math.Max(10, float64(topCandidate.score*.2)))
  78. topCandidate.selection.Siblings().Union(topCandidate.selection).Each(func(i int, s *goquery.Selection) {
  79. append := false
  80. node := s.Get(0)
  81. if node == topCandidate.Node() {
  82. append = true
  83. } else if c, ok := candidates[node]; ok && c.score >= siblingScoreThreshold {
  84. append = true
  85. }
  86. if s.Is("p") {
  87. linkDensity := getLinkDensity(s)
  88. content := s.Text()
  89. contentLength := len(content)
  90. if contentLength >= 80 {
  91. if linkDensity < .25 {
  92. append = true
  93. }
  94. } else if linkDensity == 0 && (content[len(content)-1] == '.' || strings.Contains(content, ". ")) {
  95. append = true
  96. }
  97. }
  98. if append {
  99. tag := "div"
  100. if s.Is("p") {
  101. tag = node.Data
  102. }
  103. html, _ := s.Html()
  104. fmt.Fprintf(output, "<%s>%s</%s>", tag, html, tag)
  105. }
  106. })
  107. output.WriteString("</div>")
  108. return output.String()
  109. }
  110. func removeUnlikelyCandidates(document *goquery.Document) {
  111. document.Find("*").Not("html,body").Each(func(i int, s *goquery.Selection) {
  112. class, _ := s.Attr("class")
  113. id, _ := s.Attr("id")
  114. str := class + id
  115. if blacklistCandidatesRegexp.MatchString(str) || (unlikelyCandidatesRegexp.MatchString(str) && !okMaybeItsACandidateRegexp.MatchString(str)) {
  116. removeNodes(s)
  117. }
  118. })
  119. }
  120. func getTopCandidate(document *goquery.Document, candidates candidateList) *candidate {
  121. var best *candidate
  122. for _, c := range candidates {
  123. if best == nil {
  124. best = c
  125. } else if best.score < c.score {
  126. best = c
  127. }
  128. }
  129. if best == nil {
  130. best = &candidate{document.Find("body"), 0}
  131. }
  132. return best
  133. }
  134. // Loop through all paragraphs, and assign a score to them based on how content-y they look.
  135. // Then add their score to their parent node.
  136. // A score is determined by things like number of commas, class names, etc.
  137. // Maybe eventually link density.
  138. func getCandidates(document *goquery.Document) candidateList {
  139. candidates := make(candidateList)
  140. document.Find(defaultTagsToScore).Each(func(i int, s *goquery.Selection) {
  141. text := s.Text()
  142. // If this paragraph is less than 25 characters, don't even count it.
  143. if len(text) < 25 {
  144. return
  145. }
  146. parent := s.Parent()
  147. parentNode := parent.Get(0)
  148. grandParent := parent.Parent()
  149. var grandParentNode *html.Node
  150. if grandParent.Length() > 0 {
  151. grandParentNode = grandParent.Get(0)
  152. }
  153. if _, found := candidates[parentNode]; !found {
  154. candidates[parentNode] = scoreNode(parent)
  155. }
  156. if grandParentNode != nil {
  157. if _, found := candidates[grandParentNode]; !found {
  158. candidates[grandParentNode] = scoreNode(grandParent)
  159. }
  160. }
  161. // Add a point for the paragraph itself as a base.
  162. contentScore := float32(1.0)
  163. // Add points for any commas within this paragraph.
  164. contentScore += float32(strings.Count(text, ",") + 1)
  165. // For every 100 characters in this paragraph, add another point. Up to 3 points.
  166. contentScore += float32(math.Min(float64(int(len(text)/100.0)), 3))
  167. candidates[parentNode].score += contentScore
  168. if grandParentNode != nil {
  169. candidates[grandParentNode].score += contentScore / 2.0
  170. }
  171. })
  172. // Scale the final candidates score based on link density. Good content
  173. // should have a relatively small link density (5% or less) and be mostly
  174. // unaffected by this operation
  175. for _, candidate := range candidates {
  176. candidate.score = candidate.score * (1 - getLinkDensity(candidate.selection))
  177. }
  178. return candidates
  179. }
  180. func scoreNode(s *goquery.Selection) *candidate {
  181. c := &candidate{selection: s, score: 0}
  182. switch s.Get(0).DataAtom.String() {
  183. case "div":
  184. c.score += 5
  185. case "pre", "td", "blockquote", "img":
  186. c.score += 3
  187. case "address", "ol", "ul", "dl", "dd", "dt", "li", "form":
  188. c.score -= 3
  189. case "h1", "h2", "h3", "h4", "h5", "h6", "th":
  190. c.score -= 5
  191. }
  192. c.score += getClassWeight(s)
  193. return c
  194. }
  195. // Get the density of links as a percentage of the content
  196. // This is the amount of text that is inside a link divided by the total text in the node.
  197. func getLinkDensity(s *goquery.Selection) float32 {
  198. linkLength := len(s.Find("a").Text())
  199. textLength := len(s.Text())
  200. if textLength == 0 {
  201. return 0
  202. }
  203. return float32(linkLength) / float32(textLength)
  204. }
  205. // Get an elements class/id weight. Uses regular expressions to tell if this
  206. // element looks good or bad.
  207. func getClassWeight(s *goquery.Selection) float32 {
  208. weight := 0
  209. class, _ := s.Attr("class")
  210. id, _ := s.Attr("id")
  211. if class != "" {
  212. if negativeRegexp.MatchString(class) {
  213. weight -= 25
  214. }
  215. if positiveRegexp.MatchString(class) {
  216. weight += 25
  217. }
  218. }
  219. if id != "" {
  220. if negativeRegexp.MatchString(id) {
  221. weight -= 25
  222. }
  223. if positiveRegexp.MatchString(id) {
  224. weight += 25
  225. }
  226. }
  227. return float32(weight)
  228. }
  229. func transformMisusedDivsIntoParagraphs(document *goquery.Document) {
  230. document.Find("div").Each(func(i int, s *goquery.Selection) {
  231. html, _ := s.Html()
  232. if !divToPElementsRegexp.MatchString(html) {
  233. node := s.Get(0)
  234. node.Data = "p"
  235. }
  236. })
  237. }
  238. func removeNodes(s *goquery.Selection) {
  239. s.Each(func(i int, s *goquery.Selection) {
  240. parent := s.Parent()
  241. if parent.Length() > 0 {
  242. parent.Get(0).RemoveChild(s.Get(0))
  243. }
  244. })
  245. }