web_reader_tool.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357
  1. import hashlib
  2. import json
  3. import mimetypes
  4. import os
  5. import re
  6. import site
  7. import subprocess
  8. import tempfile
  9. import unicodedata
  10. from contextlib import contextmanager
  11. from urllib.parse import unquote
  12. import cloudscraper
  13. import requests
  14. from bs4 import BeautifulSoup, CData, Comment, NavigableString
  15. from newspaper import Article
  16. from regex import regex
  17. from core.rag.extractor import extract_processor
  18. from core.rag.extractor.extract_processor import ExtractProcessor
  19. FULL_TEMPLATE = """
  20. TITLE: {title}
  21. AUTHORS: {authors}
  22. PUBLISH DATE: {publish_date}
  23. TOP_IMAGE_URL: {top_image}
  24. TEXT:
  25. {text}
  26. """
  27. def page_result(text: str, cursor: int, max_length: int) -> str:
  28. """Page through `text` and return a substring of `max_length` characters starting from `cursor`."""
  29. return text[cursor: cursor + max_length]
  30. def get_url(url: str, user_agent: str = None) -> str:
  31. """Fetch URL and return the contents as a string."""
  32. headers = {
  33. "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36"
  34. }
  35. if user_agent:
  36. headers["User-Agent"] = user_agent
  37. main_content_type = None
  38. supported_content_types = extract_processor.SUPPORT_URL_CONTENT_TYPES + ["text/html"]
  39. response = requests.head(url, headers=headers, allow_redirects=True, timeout=(5, 10))
  40. if response.status_code == 200:
  41. # check content-type
  42. content_type = response.headers.get('Content-Type')
  43. if content_type:
  44. main_content_type = response.headers.get('Content-Type').split(';')[0].strip()
  45. else:
  46. content_disposition = response.headers.get('Content-Disposition', '')
  47. filename_match = re.search(r'filename="([^"]+)"', content_disposition)
  48. if filename_match:
  49. filename = unquote(filename_match.group(1))
  50. extension = re.search(r'\.(\w+)$', filename)
  51. if extension:
  52. main_content_type = mimetypes.guess_type(filename)[0]
  53. if main_content_type not in supported_content_types:
  54. return "Unsupported content-type [{}] of URL.".format(main_content_type)
  55. if main_content_type in extract_processor.SUPPORT_URL_CONTENT_TYPES:
  56. return ExtractProcessor.load_from_url(url, return_text=True)
  57. response = requests.get(url, headers=headers, allow_redirects=True, timeout=(120, 300))
  58. elif response.status_code == 403:
  59. scraper = cloudscraper.create_scraper()
  60. response = scraper.get(url, headers=headers, allow_redirects=True, timeout=(120, 300))
  61. if response.status_code != 200:
  62. return "URL returned status code {}.".format(response.status_code)
  63. a = extract_using_readabilipy(response.text)
  64. if not a['plain_text'] or not a['plain_text'].strip():
  65. return get_url_from_newspaper3k(url)
  66. res = FULL_TEMPLATE.format(
  67. title=a['title'],
  68. authors=a['byline'],
  69. publish_date=a['date'],
  70. top_image="",
  71. text=a['plain_text'] if a['plain_text'] else "",
  72. )
  73. return res
  74. def get_url_from_newspaper3k(url: str) -> str:
  75. a = Article(url)
  76. a.download()
  77. a.parse()
  78. res = FULL_TEMPLATE.format(
  79. title=a.title,
  80. authors=a.authors,
  81. publish_date=a.publish_date,
  82. top_image=a.top_image,
  83. text=a.text,
  84. )
  85. return res
  86. def extract_using_readabilipy(html):
  87. with tempfile.NamedTemporaryFile(delete=False, mode='w+') as f_html:
  88. f_html.write(html)
  89. f_html.close()
  90. html_path = f_html.name
  91. # Call Mozilla's Readability.js Readability.parse() function via node, writing output to a temporary file
  92. article_json_path = html_path + ".json"
  93. jsdir = os.path.join(find_module_path('readabilipy'), 'javascript')
  94. with chdir(jsdir):
  95. subprocess.check_call(["node", "ExtractArticle.js", "-i", html_path, "-o", article_json_path])
  96. # Read output of call to Readability.parse() from JSON file and return as Python dictionary
  97. with open(article_json_path, encoding="utf-8") as json_file:
  98. input_json = json.loads(json_file.read())
  99. # Deleting files after processing
  100. os.unlink(article_json_path)
  101. os.unlink(html_path)
  102. article_json = {
  103. "title": None,
  104. "byline": None,
  105. "date": None,
  106. "content": None,
  107. "plain_content": None,
  108. "plain_text": None
  109. }
  110. # Populate article fields from readability fields where present
  111. if input_json:
  112. if input_json.get("title"):
  113. article_json["title"] = input_json["title"]
  114. if input_json.get("byline"):
  115. article_json["byline"] = input_json["byline"]
  116. if input_json.get("date"):
  117. article_json["date"] = input_json["date"]
  118. if input_json.get("content"):
  119. article_json["content"] = input_json["content"]
  120. article_json["plain_content"] = plain_content(article_json["content"], False, False)
  121. article_json["plain_text"] = extract_text_blocks_as_plain_text(article_json["plain_content"])
  122. if input_json.get("textContent"):
  123. article_json["plain_text"] = input_json["textContent"]
  124. article_json["plain_text"] = re.sub(r'\n\s*\n', '\n', article_json["plain_text"])
  125. return article_json
  126. def find_module_path(module_name):
  127. for package_path in site.getsitepackages():
  128. potential_path = os.path.join(package_path, module_name)
  129. if os.path.exists(potential_path):
  130. return potential_path
  131. return None
  132. @contextmanager
  133. def chdir(path):
  134. """Change directory in context and return to original on exit"""
  135. # From https://stackoverflow.com/a/37996581, couldn't find a built-in
  136. original_path = os.getcwd()
  137. os.chdir(path)
  138. try:
  139. yield
  140. finally:
  141. os.chdir(original_path)
  142. def extract_text_blocks_as_plain_text(paragraph_html):
  143. # Load article as DOM
  144. soup = BeautifulSoup(paragraph_html, 'html.parser')
  145. # Select all lists
  146. list_elements = soup.find_all(['ul', 'ol'])
  147. # Prefix text in all list items with "* " and make lists paragraphs
  148. for list_element in list_elements:
  149. plain_items = "".join(list(filter(None, [plain_text_leaf_node(li)["text"] for li in list_element.find_all('li')])))
  150. list_element.string = plain_items
  151. list_element.name = "p"
  152. # Select all text blocks
  153. text_blocks = [s.parent for s in soup.find_all(string=True)]
  154. text_blocks = [plain_text_leaf_node(block) for block in text_blocks]
  155. # Drop empty paragraphs
  156. text_blocks = list(filter(lambda p: p["text"] is not None, text_blocks))
  157. return text_blocks
  158. def plain_text_leaf_node(element):
  159. # Extract all text, stripped of any child HTML elements and normalise it
  160. plain_text = normalise_text(element.get_text())
  161. if plain_text != "" and element.name == "li":
  162. plain_text = "* {}, ".format(plain_text)
  163. if plain_text == "":
  164. plain_text = None
  165. if "data-node-index" in element.attrs:
  166. plain = {"node_index": element["data-node-index"], "text": plain_text}
  167. else:
  168. plain = {"text": plain_text}
  169. return plain
  170. def plain_content(readability_content, content_digests, node_indexes):
  171. # Load article as DOM
  172. soup = BeautifulSoup(readability_content, 'html.parser')
  173. # Make all elements plain
  174. elements = plain_elements(soup.contents, content_digests, node_indexes)
  175. if node_indexes:
  176. # Add node index attributes to nodes
  177. elements = [add_node_indexes(element) for element in elements]
  178. # Replace article contents with plain elements
  179. soup.contents = elements
  180. return str(soup)
  181. def plain_elements(elements, content_digests, node_indexes):
  182. # Get plain content versions of all elements
  183. elements = [plain_element(element, content_digests, node_indexes)
  184. for element in elements]
  185. if content_digests:
  186. # Add content digest attribute to nodes
  187. elements = [add_content_digest(element) for element in elements]
  188. return elements
  189. def plain_element(element, content_digests, node_indexes):
  190. # For lists, we make each item plain text
  191. if is_leaf(element):
  192. # For leaf node elements, extract the text content, discarding any HTML tags
  193. # 1. Get element contents as text
  194. plain_text = element.get_text()
  195. # 2. Normalise the extracted text string to a canonical representation
  196. plain_text = normalise_text(plain_text)
  197. # 3. Update element content to be plain text
  198. element.string = plain_text
  199. elif is_text(element):
  200. if is_non_printing(element):
  201. # The simplified HTML may have come from Readability.js so might
  202. # have non-printing text (e.g. Comment or CData). In this case, we
  203. # keep the structure, but ensure that the string is empty.
  204. element = type(element)("")
  205. else:
  206. plain_text = element.string
  207. plain_text = normalise_text(plain_text)
  208. element = type(element)(plain_text)
  209. else:
  210. # If not a leaf node or leaf type call recursively on child nodes, replacing
  211. element.contents = plain_elements(element.contents, content_digests, node_indexes)
  212. return element
  213. def add_node_indexes(element, node_index="0"):
  214. # Can't add attributes to string types
  215. if is_text(element):
  216. return element
  217. # Add index to current element
  218. element["data-node-index"] = node_index
  219. # Add index to child elements
  220. for local_idx, child in enumerate(
  221. [c for c in element.contents if not is_text(c)], start=1):
  222. # Can't add attributes to leaf string types
  223. child_index = "{stem}.{local}".format(
  224. stem=node_index, local=local_idx)
  225. add_node_indexes(child, node_index=child_index)
  226. return element
  227. def normalise_text(text):
  228. """Normalise unicode and whitespace."""
  229. # Normalise unicode first to try and standardise whitespace characters as much as possible before normalising them
  230. text = strip_control_characters(text)
  231. text = normalise_unicode(text)
  232. text = normalise_whitespace(text)
  233. return text
  234. def strip_control_characters(text):
  235. """Strip out unicode control characters which might break the parsing."""
  236. # Unicode control characters
  237. # [Cc]: Other, Control [includes new lines]
  238. # [Cf]: Other, Format
  239. # [Cn]: Other, Not Assigned
  240. # [Co]: Other, Private Use
  241. # [Cs]: Other, Surrogate
  242. control_chars = {'Cc', 'Cf', 'Cn', 'Co', 'Cs'}
  243. retained_chars = ['\t', '\n', '\r', '\f']
  244. # Remove non-printing control characters
  245. return "".join(["" if (unicodedata.category(char) in control_chars) and (char not in retained_chars) else char for char in text])
  246. def normalise_unicode(text):
  247. """Normalise unicode such that things that are visually equivalent map to the same unicode string where possible."""
  248. normal_form = "NFKC"
  249. text = unicodedata.normalize(normal_form, text)
  250. return text
  251. def normalise_whitespace(text):
  252. """Replace runs of whitespace characters with a single space as this is what happens when HTML text is displayed."""
  253. text = regex.sub(r"\s+", " ", text)
  254. # Remove leading and trailing whitespace
  255. text = text.strip()
  256. return text
  257. def is_leaf(element):
  258. return (element.name in ['p', 'li'])
  259. def is_text(element):
  260. return isinstance(element, NavigableString)
  261. def is_non_printing(element):
  262. return any(isinstance(element, _e) for _e in [Comment, CData])
  263. def add_content_digest(element):
  264. if not is_text(element):
  265. element["data-content-digest"] = content_digest(element)
  266. return element
  267. def content_digest(element):
  268. if is_text(element):
  269. # Hash
  270. trimmed_string = element.string.strip()
  271. if trimmed_string == "":
  272. digest = ""
  273. else:
  274. digest = hashlib.sha256(trimmed_string.encode('utf-8')).hexdigest()
  275. else:
  276. contents = element.contents
  277. num_contents = len(contents)
  278. if num_contents == 0:
  279. # No hash when no child elements exist
  280. digest = ""
  281. elif num_contents == 1:
  282. # If single child, use digest of child
  283. digest = content_digest(contents[0])
  284. else:
  285. # Build content digest from the "non-empty" digests of child nodes
  286. digest = hashlib.sha256()
  287. child_digests = list(
  288. filter(lambda x: x != "", [content_digest(content) for content in contents]))
  289. for child in child_digests:
  290. digest.update(child.encode('utf-8'))
  291. digest = digest.hexdigest()
  292. return digest