diff --git a/modules/archive/__init__.py b/modules/archive/__init__.py index 67993644..57c44bbd 100644 --- a/modules/archive/__init__.py +++ b/modules/archive/__init__.py @@ -11,7 +11,7 @@ from sqlalchemy.orm import Session from wrolpi.cmd import SINGLE_FILE_BIN, CHROMIUM, READABILITY_BIN from wrolpi.common import logger, register_modeler, register_refresh_cleanup, limit_concurrent, split_lines_by_length, \ - slow_logger, html_screenshot + slow_logger, html_screenshot, get_title_from_html from wrolpi.db import optional_session, get_db_session from wrolpi.downloader import Downloader, Download, DownloadResult from wrolpi.errors import UnrecoverableDownloadError @@ -20,7 +20,7 @@ from wrolpi.vars import PYTEST, DOCKERIZED from . import lib from .api import bp # noqa from .errors import InvalidArchive -from .lib import is_singlefile_file, get_title_from_html, request_archive, SINGLEFILE_HEADER +from .lib import is_singlefile_file, request_archive, SINGLEFILE_HEADER from .models import Archive, Domain PRETTY_NAME = 'Archive' @@ -263,6 +263,9 @@ async def archive_modeler(): for file_group, archive in results: processed += 1 + # Even if indexing fails, we mark it as indexed. We won't retry indexing this. + file_group.indexed = True + with slow_logger(1, f'Modeling archive took %(elapsed)s seconds: {file_group}', logger__=logger): if archive: @@ -279,10 +282,7 @@ async def archive_modeler(): model_archive(file_group, session=session) except InvalidArchive: # It was not a real Archive. Many HTML files will not be an Archive. - pass - - # Even if indexing fails, we mark it as indexed. We won't retry indexing this. - file_group.indexed = True + file_group.indexed = False session.commit() diff --git a/modules/archive/lib.py b/modules/archive/lib.py index 2c381f3b..a0290eff 100644 --- a/modules/archive/lib.py +++ b/modules/archive/lib.py @@ -15,7 +15,7 @@ from sqlalchemy.orm import Session from modules.archive.models import Domain, Archive from wrolpi import dates from wrolpi.common import get_media_directory, logger, extract_domain, escape_file_name, aiohttp_post, \ - format_html_string, split_lines_by_length, get_html_soup + format_html_string, split_lines_by_length, get_html_soup, get_title_from_html from wrolpi.dates import now, Seconds from wrolpi.db import get_db_session, get_db_curs, optional_session from wrolpi.errors import UnknownArchive, InvalidOrderBy, InvalidDatetime @@ -219,17 +219,6 @@ def get_or_create_domain(session: Session, url) -> Domain: return domain -def get_title_from_html(html: str, url: str = None) -> str: - """ - Try and get the title from the - """ - soup = get_html_soup(html) - try: - return soup.title.string - except Exception: # noqa - logger.debug(f'Unable to extract title {url}') - - SINGLEFILE_URL_EXTRACTOR = re.compile(r'Page saved with SingleFile \s+url: (http.+?)\n') diff --git a/modules/archive/models.py b/modules/archive/models.py index bd159b42..b5043450 100644 --- a/modules/archive/models.py +++ b/modules/archive/models.py @@ -9,7 +9,7 @@ from sqlalchemy.orm import relationship, Session, validates from sqlalchemy.orm.collections import InstrumentedList from wrolpi import dates -from wrolpi.common import ModelHelper, Base, logger +from wrolpi.common import ModelHelper, Base, logger, get_title_from_html from wrolpi.db import optional_session from wrolpi.errors import UnknownArchive from wrolpi.files.models import FileGroup @@ -242,7 +242,6 @@ class Archive(Base, ModelHelper): def apply_singlefile_title(self): """Get the title from the Singlefile, if it's missing.""" - from modules.archive.lib import get_title_from_html if self.singlefile_path and not self.file_group.title: self.file_group.title = get_title_from_html(self.singlefile_path.read_text()) diff --git a/wrolpi/common.py b/wrolpi/common.py index d48505a8..7aed499a 100644 --- a/wrolpi/common.py +++ b/wrolpi/common.py @@ -1592,3 +1592,14 @@ def chain(iterable: Union[List, Tuple], length: int) -> List: if not yielded: # Not enough items to iterate. Yield the original iterable. yield iterable + + +def get_title_from_html(html: str, url: str = None) -> str: + """ + Try and get the title from the + """ + soup = get_html_soup(html) + try: + return soup.title.string + except Exception: # noqa + logger.debug(f'Unable to extract title {url}') diff --git a/wrolpi/conftest.py b/wrolpi/conftest.py index a6d869d7..99ababdf 100644 --- a/wrolpi/conftest.py +++ b/wrolpi/conftest.py @@ -424,6 +424,7 @@ def make_files_structure(test_directory) -> Callable[[Union[List[Union[pathlib.P if file_groups: for idx, path in enumerate(files): fg = FileGroup.from_paths(session, path) + fg.do_index() files[idx] = fg return sorted(files) if isinstance(paths, dict) else files diff --git a/wrolpi/files/indexers.py b/wrolpi/files/indexers.py index 967b1b4b..782f12c1 100644 --- a/wrolpi/files/indexers.py +++ b/wrolpi/files/indexers.py @@ -11,7 +11,7 @@ try: except ImportError: PdfReader = None -from wrolpi.common import logger, split_lines_by_length, truncate_object_bytes +from wrolpi.common import logger, split_lines_by_length, truncate_object_bytes, extract_html_text, get_title_from_html logger = logger.getChild(__name__) @@ -115,3 +115,23 @@ class TextIndexer(Indexer, ABC): contents = truncate_object_bytes(contents, FILE_MAX_TEXT_SIZE) words = split_lines_by_length(contents) return words + + +@register_indexer('text/html') +class HTMLIndexer(Indexer, ABC): + """Extracts words from an HTML document. Ignores code (HTML/Javascript/etc).""" + + @classmethod + def create_index(cls, path: pathlib.Path): + from modules.archive.lib import parse_article_html_metadata + + a = cls.get_title(path) + + contents = path.read_text() + metadata = parse_article_html_metadata(contents) + text = extract_html_text(contents) + words = split_lines_by_length(text) + + title = metadata.title or get_title_from_html(contents) + + return title, a, metadata.description, words diff --git a/wrolpi/files/test/test_lib.py b/wrolpi/files/test/test_lib.py index feb0ee96..94f381e9 100644 --- a/wrolpi/files/test/test_lib.py +++ b/wrolpi/files/test/test_lib.py @@ -899,3 +899,49 @@ async def test_move_tagged(test_session, test_directory, make_files_structure, t await lib.rename(new_bar, 'baz.txt') baz = new_bar.with_name('baz.txt') assert baz.read_text() == 'bar' + + +@pytest.mark.asyncio +async def test_html_index(test_session, test_directory, make_files_structure): + make_files_structure({ + 'archive.html': ''' + The Title + + + + + + +

Some Header

+

Some Text

+ + Span Text + + Outside element. + + + + ''' + }) + + await lib.refresh_files() + + assert test_session.query(FileGroup).count() == 1, 'Too many files were refreshed.' + archive_file: FileGroup = test_session.query(FileGroup).one() + assert archive_file.a_text == 'The Title' + assert archive_file.b_text == 'archive html' + assert archive_file.c_text == 'The article description' + assert archive_file.d_text == '''Some Header +Some Text +Span Text +Outside element.'''