mirror of
https://github.com/lrnselfreliance/wrolpi.git
synced 2026-11-29 11:26:25 -05:00
Creating HTMLIndexer which indexes the text of HTML files.
This commit is contained in:
parent
35d25515fb
commit
61a7fdab10
7 changed files with 87 additions and 21 deletions
|
|
@ -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()
|
||||
|
||||
|
|
|
|||
|
|
@ -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')
|
||||
|
||||
|
||||
|
|
|
|||
|
|
@ -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())
|
||||
|
||||
|
|
|
|||
|
|
@ -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}')
|
||||
|
|
|
|||
|
|
@ -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
|
||||
|
||||
|
|
|
|||
|
|
@ -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
|
||||
|
|
|
|||
|
|
@ -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': '''<html>
|
||||
<title>The Title</title>
|
||||
|
||||
<style>
|
||||
body {
|
||||
color: red;
|
||||
}
|
||||
</style>
|
||||
|
||||
<script class="sf-hidden" type="application/ld+json">
|
||||
{"@context":"http://schema.org", "@type":"NewsArticle",
|
||||
"datePublished":"2022-09-27T00:40:19.000Z", "dateModified":"2022-09-27T13:43:47.971Z",
|
||||
"author":{"@type":"Person", "name":"BOBBY", "jobTitle":""},
|
||||
"creator":{"@type":"Person", "name":"OTHER BOBBY", "jobTitle":""},
|
||||
"description": "The article description"}
|
||||
</script>
|
||||
|
||||
<body>
|
||||
<h1>Some Header</h1>
|
||||
<p>Some Text</p>
|
||||
|
||||
<span>Span Text</span>
|
||||
|
||||
Outside element.
|
||||
</body>
|
||||
|
||||
</html>
|
||||
'''
|
||||
})
|
||||
|
||||
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.'''
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue