readability.go 8.2 KB

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