readability.py 3.8 KB

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