readability.py 4.1 KB

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