web_reader_tool.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421
  1. import hashlib
  2. import json
  3. import os
  4. import re
  5. import site
  6. import subprocess
  7. import tempfile
  8. import unicodedata
  9. from contextlib import contextmanager
  10. from typing import Type
  11. import requests
  12. from bs4 import BeautifulSoup, NavigableString, Comment, CData
  13. from langchain.base_language import BaseLanguageModel
  14. from langchain.chains.summarize import load_summarize_chain
  15. from langchain.schema import Document
  16. from langchain.text_splitter import RecursiveCharacterTextSplitter
  17. from langchain.tools.base import BaseTool
  18. from newspaper import Article
  19. from pydantic import BaseModel, Field
  20. from regex import regex
  21. from core.data_loader import file_extractor
  22. from core.data_loader.file_extractor import FileExtractor
  23. FULL_TEMPLATE = """
  24. TITLE: {title}
  25. AUTHORS: {authors}
  26. PUBLISH DATE: {publish_date}
  27. TOP_IMAGE_URL: {top_image}
  28. TEXT:
  29. {text}
  30. """
  31. class WebReaderToolInput(BaseModel):
  32. url: str = Field(..., description="URL of the website to read")
  33. summary: bool = Field(
  34. default=False,
  35. description="When the user's question requires extracting the summarizing content of the webpage, "
  36. "set it to true."
  37. )
  38. cursor: int = Field(
  39. default=0,
  40. description="Start reading from this character."
  41. "Use when the first response was truncated"
  42. "and you want to continue reading the page."
  43. "The value cannot exceed 24000.",
  44. )
  45. class WebReaderTool(BaseTool):
  46. """Reader tool for getting website title and contents. Gives more control than SimpleReaderTool."""
  47. name: str = "web_reader"
  48. args_schema: Type[BaseModel] = WebReaderToolInput
  49. description: str = "use this to read a website. " \
  50. "If you can answer the question based on the information provided, " \
  51. "there is no need to use."
  52. page_contents: str = None
  53. url: str = None
  54. max_chunk_length: int = 4000
  55. summary_chunk_tokens: int = 4000
  56. summary_chunk_overlap: int = 0
  57. summary_separators: list[str] = ["\n\n", "。", ".", " ", ""]
  58. continue_reading: bool = True
  59. llm: BaseLanguageModel = None
  60. def _run(self, url: str, summary: bool = False, cursor: int = 0) -> str:
  61. try:
  62. if not self.page_contents or self.url != url:
  63. page_contents = get_url(url)
  64. self.page_contents = page_contents
  65. self.url = url
  66. else:
  67. page_contents = self.page_contents
  68. except Exception as e:
  69. return f'Read this website failed, caused by: {str(e)}.'
  70. if summary and self.llm:
  71. character_splitter = RecursiveCharacterTextSplitter.from_tiktoken_encoder(
  72. chunk_size=self.summary_chunk_tokens,
  73. chunk_overlap=self.summary_chunk_overlap,
  74. separators=self.summary_separators
  75. )
  76. texts = character_splitter.split_text(page_contents)
  77. docs = [Document(page_content=t) for t in texts]
  78. docs = docs[1:]
  79. # only use first 5 docs
  80. if len(docs) > 5:
  81. docs = docs[:5]
  82. chain = load_summarize_chain(self.llm, chain_type="refine", callbacks=self.callbacks)
  83. try:
  84. page_contents = chain.run(docs)
  85. # todo use cache
  86. except Exception as e:
  87. return f'Read this website failed, caused by: {str(e)}.'
  88. else:
  89. page_contents = page_result(page_contents, cursor, self.max_chunk_length)
  90. if self.continue_reading and len(page_contents) >= self.max_chunk_length:
  91. page_contents += f"\nPAGE WAS TRUNCATED. IF YOU FIND INFORMATION THAT CAN ANSWER QUESTION " \
  92. f"THEN DIRECT ANSWER AND STOP INVOKING web_reader TOOL, OTHERWISE USE " \
  93. f"CURSOR={cursor+len(page_contents)} TO CONTINUE READING."
  94. return page_contents
  95. async def _arun(self, url: str) -> str:
  96. raise NotImplementedError
  97. def page_result(text: str, cursor: int, max_length: int) -> str:
  98. """Page through `text` and return a substring of `max_length` characters starting from `cursor`."""
  99. return text[cursor: cursor + max_length]
  100. def get_url(url: str) -> str:
  101. """Fetch URL and return the contents as a string."""
  102. headers = {
  103. "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"
  104. }
  105. supported_content_types = file_extractor.SUPPORT_URL_CONTENT_TYPES + ["text/html"]
  106. head_response = requests.head(url, headers=headers, allow_redirects=True, timeout=(5, 10))
  107. if head_response.status_code != 200:
  108. return "URL returned status code {}.".format(head_response.status_code)
  109. # check content-type
  110. main_content_type = head_response.headers.get('Content-Type').split(';')[0].strip()
  111. if main_content_type not in supported_content_types:
  112. return "Unsupported content-type [{}] of URL.".format(main_content_type)
  113. if main_content_type in file_extractor.SUPPORT_URL_CONTENT_TYPES:
  114. return FileExtractor.load_from_url(url, return_text=True)
  115. response = requests.get(url, headers=headers, allow_redirects=True, timeout=(5, 30))
  116. a = extract_using_readabilipy(response.text)
  117. if not a['plain_text'] or not a['plain_text'].strip():
  118. return get_url_from_newspaper3k(url)
  119. res = FULL_TEMPLATE.format(
  120. title=a['title'],
  121. authors=a['byline'],
  122. publish_date=a['date'],
  123. top_image="",
  124. text=a['plain_text'] if a['plain_text'] else "",
  125. )
  126. return res
  127. def get_url_from_newspaper3k(url: str) -> str:
  128. a = Article(url)
  129. a.download()
  130. a.parse()
  131. res = FULL_TEMPLATE.format(
  132. title=a.title,
  133. authors=a.authors,
  134. publish_date=a.publish_date,
  135. top_image=a.top_image,
  136. text=a.text,
  137. )
  138. return res
  139. def extract_using_readabilipy(html):
  140. with tempfile.NamedTemporaryFile(delete=False, mode='w+') as f_html:
  141. f_html.write(html)
  142. f_html.close()
  143. html_path = f_html.name
  144. # Call Mozilla's Readability.js Readability.parse() function via node, writing output to a temporary file
  145. article_json_path = html_path + ".json"
  146. jsdir = os.path.join(find_module_path('readabilipy'), 'javascript')
  147. with chdir(jsdir):
  148. subprocess.check_call(["node", "ExtractArticle.js", "-i", html_path, "-o", article_json_path])
  149. # Read output of call to Readability.parse() from JSON file and return as Python dictionary
  150. with open(article_json_path, "r", encoding="utf-8") as json_file:
  151. input_json = json.loads(json_file.read())
  152. # Deleting files after processing
  153. os.unlink(article_json_path)
  154. os.unlink(html_path)
  155. article_json = {
  156. "title": None,
  157. "byline": None,
  158. "date": None,
  159. "content": None,
  160. "plain_content": None,
  161. "plain_text": None
  162. }
  163. # Populate article fields from readability fields where present
  164. if input_json:
  165. if "title" in input_json and input_json["title"]:
  166. article_json["title"] = input_json["title"]
  167. if "byline" in input_json and input_json["byline"]:
  168. article_json["byline"] = input_json["byline"]
  169. if "date" in input_json and input_json["date"]:
  170. article_json["date"] = input_json["date"]
  171. if "content" in input_json and input_json["content"]:
  172. article_json["content"] = input_json["content"]
  173. article_json["plain_content"] = plain_content(article_json["content"], False, False)
  174. article_json["plain_text"] = extract_text_blocks_as_plain_text(article_json["plain_content"])
  175. if "textContent" in input_json and input_json["textContent"]:
  176. article_json["plain_text"] = input_json["textContent"]
  177. article_json["plain_text"] = re.sub(r'\n\s*\n', '\n', article_json["plain_text"])
  178. return article_json
  179. def find_module_path(module_name):
  180. for package_path in site.getsitepackages():
  181. potential_path = os.path.join(package_path, module_name)
  182. if os.path.exists(potential_path):
  183. return potential_path
  184. return None
  185. @contextmanager
  186. def chdir(path):
  187. """Change directory in context and return to original on exit"""
  188. # From https://stackoverflow.com/a/37996581, couldn't find a built-in
  189. original_path = os.getcwd()
  190. os.chdir(path)
  191. try:
  192. yield
  193. finally:
  194. os.chdir(original_path)
  195. def extract_text_blocks_as_plain_text(paragraph_html):
  196. # Load article as DOM
  197. soup = BeautifulSoup(paragraph_html, 'html.parser')
  198. # Select all lists
  199. list_elements = soup.find_all(['ul', 'ol'])
  200. # Prefix text in all list items with "* " and make lists paragraphs
  201. for list_element in list_elements:
  202. plain_items = "".join(list(filter(None, [plain_text_leaf_node(li)["text"] for li in list_element.find_all('li')])))
  203. list_element.string = plain_items
  204. list_element.name = "p"
  205. # Select all text blocks
  206. text_blocks = [s.parent for s in soup.find_all(string=True)]
  207. text_blocks = [plain_text_leaf_node(block) for block in text_blocks]
  208. # Drop empty paragraphs
  209. text_blocks = list(filter(lambda p: p["text"] is not None, text_blocks))
  210. return text_blocks
  211. def plain_text_leaf_node(element):
  212. # Extract all text, stripped of any child HTML elements and normalise it
  213. plain_text = normalise_text(element.get_text())
  214. if plain_text != "" and element.name == "li":
  215. plain_text = "* {}, ".format(plain_text)
  216. if plain_text == "":
  217. plain_text = None
  218. if "data-node-index" in element.attrs:
  219. plain = {"node_index": element["data-node-index"], "text": plain_text}
  220. else:
  221. plain = {"text": plain_text}
  222. return plain
  223. def plain_content(readability_content, content_digests, node_indexes):
  224. # Load article as DOM
  225. soup = BeautifulSoup(readability_content, 'html.parser')
  226. # Make all elements plain
  227. elements = plain_elements(soup.contents, content_digests, node_indexes)
  228. if node_indexes:
  229. # Add node index attributes to nodes
  230. elements = [add_node_indexes(element) for element in elements]
  231. # Replace article contents with plain elements
  232. soup.contents = elements
  233. return str(soup)
  234. def plain_elements(elements, content_digests, node_indexes):
  235. # Get plain content versions of all elements
  236. elements = [plain_element(element, content_digests, node_indexes)
  237. for element in elements]
  238. if content_digests:
  239. # Add content digest attribute to nodes
  240. elements = [add_content_digest(element) for element in elements]
  241. return elements
  242. def plain_element(element, content_digests, node_indexes):
  243. # For lists, we make each item plain text
  244. if is_leaf(element):
  245. # For leaf node elements, extract the text content, discarding any HTML tags
  246. # 1. Get element contents as text
  247. plain_text = element.get_text()
  248. # 2. Normalise the extracted text string to a canonical representation
  249. plain_text = normalise_text(plain_text)
  250. # 3. Update element content to be plain text
  251. element.string = plain_text
  252. elif is_text(element):
  253. if is_non_printing(element):
  254. # The simplified HTML may have come from Readability.js so might
  255. # have non-printing text (e.g. Comment or CData). In this case, we
  256. # keep the structure, but ensure that the string is empty.
  257. element = type(element)("")
  258. else:
  259. plain_text = element.string
  260. plain_text = normalise_text(plain_text)
  261. element = type(element)(plain_text)
  262. else:
  263. # If not a leaf node or leaf type call recursively on child nodes, replacing
  264. element.contents = plain_elements(element.contents, content_digests, node_indexes)
  265. return element
  266. def add_node_indexes(element, node_index="0"):
  267. # Can't add attributes to string types
  268. if is_text(element):
  269. return element
  270. # Add index to current element
  271. element["data-node-index"] = node_index
  272. # Add index to child elements
  273. for local_idx, child in enumerate(
  274. [c for c in element.contents if not is_text(c)], start=1):
  275. # Can't add attributes to leaf string types
  276. child_index = "{stem}.{local}".format(
  277. stem=node_index, local=local_idx)
  278. add_node_indexes(child, node_index=child_index)
  279. return element
  280. def normalise_text(text):
  281. """Normalise unicode and whitespace."""
  282. # Normalise unicode first to try and standardise whitespace characters as much as possible before normalising them
  283. text = strip_control_characters(text)
  284. text = normalise_unicode(text)
  285. text = normalise_whitespace(text)
  286. return text
  287. def strip_control_characters(text):
  288. """Strip out unicode control characters which might break the parsing."""
  289. # Unicode control characters
  290. # [Cc]: Other, Control [includes new lines]
  291. # [Cf]: Other, Format
  292. # [Cn]: Other, Not Assigned
  293. # [Co]: Other, Private Use
  294. # [Cs]: Other, Surrogate
  295. control_chars = set(['Cc', 'Cf', 'Cn', 'Co', 'Cs'])
  296. retained_chars = ['\t', '\n', '\r', '\f']
  297. # Remove non-printing control characters
  298. return "".join(["" if (unicodedata.category(char) in control_chars) and (char not in retained_chars) else char for char in text])
  299. def normalise_unicode(text):
  300. """Normalise unicode such that things that are visually equivalent map to the same unicode string where possible."""
  301. normal_form = "NFKC"
  302. text = unicodedata.normalize(normal_form, text)
  303. return text
  304. def normalise_whitespace(text):
  305. """Replace runs of whitespace characters with a single space as this is what happens when HTML text is displayed."""
  306. text = regex.sub(r"\s+", " ", text)
  307. # Remove leading and trailing whitespace
  308. text = text.strip()
  309. return text
  310. def is_leaf(element):
  311. return (element.name in ['p', 'li'])
  312. def is_text(element):
  313. return isinstance(element, NavigableString)
  314. def is_non_printing(element):
  315. return any(isinstance(element, _e) for _e in [Comment, CData])
  316. def add_content_digest(element):
  317. if not is_text(element):
  318. element["data-content-digest"] = content_digest(element)
  319. return element
  320. def content_digest(element):
  321. if is_text(element):
  322. # Hash
  323. trimmed_string = element.string.strip()
  324. if trimmed_string == "":
  325. digest = ""
  326. else:
  327. digest = hashlib.sha256(trimmed_string.encode('utf-8')).hexdigest()
  328. else:
  329. contents = element.contents
  330. num_contents = len(contents)
  331. if num_contents == 0:
  332. # No hash when no child elements exist
  333. digest = ""
  334. elif num_contents == 1:
  335. # If single child, use digest of child
  336. digest = content_digest(contents[0])
  337. else:
  338. # Build content digest from the "non-empty" digests of child nodes
  339. digest = hashlib.sha256()
  340. child_digests = list(
  341. filter(lambda x: x != "", [content_digest(content) for content in contents]))
  342. for child in child_digests:
  343. digest.update(child.encode('utf-8'))
  344. digest = digest.hexdigest()
  345. return digest