readability.go 8.2 KB

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