readability.py 3.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113
  1. __package__ = 'archivebox.extractors'
  2. from pathlib import Path
  3. from tempfile import NamedTemporaryFile
  4. from typing import Optional
  5. import json
  6. from ..index.schema import Link, ArchiveResult, ArchiveError
  7. from ..system import run, atomic_write
  8. from ..util import (
  9. enforce_types,
  10. is_static_file,
  11. )
  12. from ..config import (
  13. TIMEOUT,
  14. CURL_BINARY,
  15. SAVE_READABILITY,
  16. DEPENDENCIES,
  17. READABILITY_VERSION,
  18. )
  19. from ..logging_util import TimedProgress
  20. from .title import get_html
  21. @enforce_types
  22. def should_save_readability(link: Link, out_dir: Optional[str]=None, overwrite: Optional[bool]=False) -> bool:
  23. if is_static_file(link.url):
  24. return False
  25. out_dir = out_dir or Path(link.link_dir)
  26. if not overwrite and (out_dir / 'readability').exists():
  27. return False
  28. return SAVE_READABILITY
  29. @enforce_types
  30. def save_readability(link: Link, out_dir: Optional[str]=None, timeout: int=TIMEOUT) -> ArchiveResult:
  31. """download reader friendly version using @mozilla/readability"""
  32. out_dir = Path(out_dir or link.link_dir)
  33. output_folder = out_dir.absolute() / "readability"
  34. output = "readability"
  35. # Readability Docs: https://github.com/mozilla/readability
  36. status = 'succeeded'
  37. # fake command to show the user so they have something to try debugging if get_html fails
  38. cmd = [
  39. CURL_BINARY,
  40. link.url
  41. ]
  42. readability_content = None
  43. timer = TimedProgress(timeout, prefix=' ')
  44. try:
  45. document = get_html(link, out_dir)
  46. temp_doc = NamedTemporaryFile(delete=False)
  47. temp_doc.write(document.encode("utf-8"))
  48. temp_doc.close()
  49. if not document or len(document) < 10:
  50. raise ArchiveError('Readability could not find HTML to parse for article text')
  51. cmd = [
  52. DEPENDENCIES['READABILITY_BINARY']['path'],
  53. temp_doc.name,
  54. link.url,
  55. ]
  56. result = run(cmd, cwd=out_dir, timeout=timeout)
  57. try:
  58. result_json = json.loads(result.stdout)
  59. assert result_json and 'content' in result_json, 'Readability output is not valid JSON'
  60. except json.JSONDecodeError:
  61. raise ArchiveError('Readability was not able to archive the page (invalid JSON)', result.stdout + result.stderr)
  62. output_folder.mkdir(exist_ok=True)
  63. readability_content = result_json.pop("textContent")
  64. atomic_write(str(output_folder / "content.html"), result_json.pop("content"))
  65. atomic_write(str(output_folder / "content.txt"), readability_content)
  66. atomic_write(str(output_folder / "article.json"), result_json)
  67. output_tail = [
  68. line.strip()
  69. for line in (result.stdout + result.stderr).decode().rsplit('\n', 5)[-5:]
  70. if line.strip()
  71. ]
  72. hints = (
  73. 'Got readability response code: {}.'.format(result.returncode),
  74. *output_tail,
  75. )
  76. # Check for common failure cases
  77. if (result.returncode > 0):
  78. raise ArchiveError(f'Readability was not able to archive the page (status={result.returncode})', hints)
  79. except (Exception, OSError) as err:
  80. status = 'failed'
  81. output = err
  82. # prefer Chrome dom output to singlefile because singlefile often contains huge url(data:image/...base64) strings that make the html too long to parse with readability
  83. cmd = [cmd[0], './{dom,singlefile}.html']
  84. finally:
  85. timer.end()
  86. return ArchiveResult(
  87. cmd=cmd,
  88. pwd=str(out_dir),
  89. cmd_version=READABILITY_VERSION,
  90. output=output,
  91. status=status,
  92. index_texts=[readability_content] if readability_content else [],
  93. **timer.stats,
  94. )