readability.go 8.5 KB

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