diff --git a/wrolpi/common.py b/wrolpi/common.py index 8f5dfc85..224a1819 100644 --- a/wrolpi/common.py +++ b/wrolpi/common.py @@ -39,6 +39,8 @@ formatter = logging.Formatter('[%(asctime)s] [%(name)s] [%(levelname)s] %(messag ch.setFormatter(formatter) logger.addHandler(ch) +logger_ = logger.getChild(__name__) + __all__ = [ 'logger', 'Base', @@ -364,7 +366,7 @@ def enable_wrol_mode(download_manager=None): Stop downloads and Download Manager. """ - logger.warning('ENABLING WROL MODE') + logger_.warning('ENABLING WROL MODE') get_config().wrol_mode = True if not download_manager: from wrolpi.downloader import download_manager @@ -380,7 +382,7 @@ def disable_wrol_mode(download_manager=None): Start downloads and Download Manager. """ - logger.warning('DISABLING WROL MODE') + logger_.warning('DISABLING WROL MODE') get_config().wrol_mode = False if not download_manager: from wrolpi.downloader import download_manager @@ -511,16 +513,16 @@ def check_media_directory(): result = True media_directory = get_media_directory() if not media_directory.is_dir(): - logger.error(f'Media directory does not exist: {media_directory}') + logger_.error(f'Media directory does not exist: {media_directory}') result = False permissions = media_directory.stat().st_mode if permissions != MEDIA_DIRECTORY_PERMISSIONS: - logger.error(f'Media directory has the wrong permissions: {oct(permissions)}') + logger_.error(f'Media directory has the wrong permissions: {oct(permissions)}') result = False if not media_directory.is_mount(): - logger.warning('Media directory is not a mount.') + logger_.warning('Media directory is not a mount.') try: # Write a file into the media directory, log an error if this is not possible. This file should be cleaned up @@ -528,7 +530,7 @@ def check_media_directory(): with tempfile.NamedTemporaryFile(dir=media_directory) as tf: tf.write(b'test') except Exception as e: - logger.error(f'Could not write to media directory: {media_directory}', exc_info=e) + logger_.error(f'Could not write to media directory: {media_directory}', exc_info=e) result = False return result @@ -605,12 +607,12 @@ def import_modules(): imported = [] for module_name in modules: module = f'modules.{module_name}.api' - logger.debug(f'Importing {module}') + logger_.debug(f'Importing {module}') try: __import__(module, globals(), locals(), [], 0) imported.append(module_name) except ImportError as e: - logger.fatal(f'Unable to import {module}', exc_info=e) + logger_.fatal(f'Unable to import {module}', exc_info=e) return imported @@ -802,6 +804,7 @@ def register_modeler(modeler: callable): def apply_modelers(files, session: Session): from wrolpi.files.lib import split_path_stem_and_suffix, get_mimetype + from wrolpi.files.models import File if not files: return @@ -821,9 +824,13 @@ def apply_modelers(files, session: Session): modeler(groups, session) for stem, group in groups.items(): - # Index any files that were not claimed by modelers. + # Re-index files that have changed size. for file in group: - file.do_index() + file: File + + if file.size != (size := file.path.stat().st_size): + file.size = size + file.indexed = False after_refresh = [] @@ -836,7 +843,7 @@ def register_after_refresh(func: callable): def apply_after_refresh(): for func in after_refresh: - logger.info(f'Applying after-refresh {func.__name__}') + logger_.info(f'Applying after-refresh {func.__name__}') func() @@ -912,7 +919,7 @@ def timer(name): try: yield finally: - logger.warning(f'{name} elapsed {(datetime.now() - before).total_seconds()} seconds') + logger_.warning(f'{name} elapsed {(datetime.now() - before).total_seconds()} seconds') TIMERS = dict() @@ -1000,6 +1007,18 @@ def truncate_object_bytes(obj: Union[List[str], str, None], maximum_bytes: int) return truncate_object_bytes(obj, maximum_bytes) +def truncate_generator_bytes(gen: Generator, maximum_bytes: int) -> Generator: + """Yield from a generator until the chunk sizes go over the maximum_bytes.""" + total_size = 0 + while total_size < maximum_bytes: + try: + chunk = next(gen) + total_size += sys.getsizeof(chunk) + yield chunk + except StopIteration: + return + + BACKGROUND_TASKS = set() @@ -1014,7 +1033,7 @@ def background_task(coro) -> Task: return task -def get_warn_once(message: str, logger_: logging.Logger, level=logging.ERROR): +def get_warn_once(message: str, logger__: logging.Logger, level=logging.ERROR): """Create a function that will report an error only once. This is used when a function will be called many times, but the error is not important.""" @@ -1022,7 +1041,7 @@ def get_warn_once(message: str, logger_: logging.Logger, level=logging.ERROR): def warn_once(exception: Exception): if not event.is_set(): - logger_.log(level, message, exc_info=exception) + logger__.log(level, message, exc_info=exception) event.set() return warn_once diff --git a/wrolpi/files/indexers.py b/wrolpi/files/indexers.py index 5cbe40d5..56b9fe0e 100644 --- a/wrolpi/files/indexers.py +++ b/wrolpi/files/indexers.py @@ -2,15 +2,17 @@ import pathlib import re from abc import ABC from collections import defaultdict -from typing import List, Type, Tuple +from typing import List, Type, Tuple, Generator from zipfile import ZipFile +from wrolpi.vars import PYTEST + try: from PyPDF2 import PdfReader except ImportError: PdfReader = None -from wrolpi.common import logger, timer +from wrolpi.common import logger, truncate_generator_bytes logger = logger.getChild(__name__) @@ -110,7 +112,7 @@ class TextIndexer(Indexer, ABC): Detects VTT (caption) files and forwards them on.""" - _ignored_suffixes = ('.json', '.vtt', '.srt', '.csv') + _ignored_suffixes = ('.json', '.vtt', '.srt', '.csv', '.hgt') @classmethod def create_index(cls, file): @@ -146,25 +148,30 @@ class PDFIndexer(Indexer, ABC): words = '' try: # PDFs are complex, don't fail to create title index if text extraction fails. - with timer(f'get words {path=}'): - words = cls.get_words(path) + words = '\n'.join(truncate_generator_bytes(cls.get_words(path), MAX_TEXT_FILE_BYTES)) except Exception as e: logger.error(f'Failed to index {path}', exc_info=e) + if PYTEST: + raise return a, None, None, words @classmethod - def get_words(cls, path: pathlib.Path) -> str: + def get_words(cls, path: pathlib.Path) -> Generator[str, None, None]: + """ + Reads all text facing up in a PDF. + + Note, may return more than can be stored in Postgres. See: truncate_generator_bytes + """ if PdfReader is None: logger.error(f'Cannot index {path} PyPDF2 is not installed.') - return '' + yield '' + return reader = PdfReader(path) - words = [] for page in reader.pages: # Get all text facing up. text = page.extract_text(0) - words.append(text) - words = '\n'.join(words) - # Postgres does not allow null characters. - words = words.replace('\x00', '\uFFFD') - return words + # Postgres does not allow null characters. + text = text.replace('\x00', '\uFFFD').strip() + if text: + yield text diff --git a/wrolpi/files/lib.py b/wrolpi/files/lib.py index 7ce5bd60..eb72ef83 100644 --- a/wrolpi/files/lib.py +++ b/wrolpi/files/lib.py @@ -17,7 +17,7 @@ from sqlalchemy.orm import Session from wrolpi.cmd import which from wrolpi.common import get_media_directory, wrol_mode_check, logger, limit_concurrent, \ get_files_and_directories, apply_modelers, apply_after_refresh, get_model_by_table_name, chunks_by_stem, \ - background_task, partition, ordered_unique_list + background_task, partition, ordered_unique_list, chunks from wrolpi.dates import now from wrolpi.db import get_db_session, get_db_curs, get_ranked_models from wrolpi.errors import InvalidFile @@ -217,6 +217,7 @@ async def cancel_refresh_tasks(): def cancelable_wrapper(func: callable): + """Wraps an async function so that it will be canceled by `cancel_refresh_tasks`.""" @wraps(func) async def wrapped(*args, **kwargs): if PYTEST: @@ -228,6 +229,45 @@ def cancelable_wrapper(func: callable): return wrapped +@cancelable_wrapper +async def apply_indexers(): + """Finds all Files that have not been indexed and indexes them.""" + from wrolpi.files.models import File + from wrolpi.db import get_db_session, get_db_curs + + with get_db_curs() as curs: + curs.execute('SELECT path FROM file WHERE indexed = false AND associated = false') + missing_index = [pathlib.Path(i[0]) for i in curs.fetchall()] + + refresh_logger.info(f'Indexing {len(missing_index)} files') + + # Indexing can be slow, commit when its been too long. + last_commit = now() + max_seconds_between_commits = 30 + + for chunk in chunks(missing_index, 100): + with get_db_session(commit=True) as session: + files = session.query(File).filter(File.path.in_(chunk)) + for file in files: + try: + file.do_index() + except Exception as e: + refresh_logger.error(f'Failed to index {file=}', exc_info=e) + if PYTEST: + raise + + if (now() - last_commit).total_seconds() > max_seconds_between_commits: + refresh_logger.debug('Committing because its been too long.') + session.commit() + last_commit = now() + + # Sleep to catch cancel. + await asyncio.sleep(0) + last_commit = now() + + refresh_logger.info(f'Indexed {len(chunk)} chunk of files') + + @wrol_mode_check async def refresh_files_list(paths: List[str], include_files_near: bool = True): """Refresh a list of files. Will not refresh directories or subdirectories. @@ -277,6 +317,7 @@ async def refresh_files_list(paths: List[str], include_files_near: bool = True): curs.execute('DELETE FROM file WHERE path = ANY(%(deleted_paths)s)', dict(deleted_paths=deleted_paths)) apply_after_refresh() + await apply_indexers() refresh_logger.info('Done refreshing files list') @@ -305,6 +346,7 @@ async def refresh_files(): logger.warning(f'Removed {len(deleted)} missing files') apply_after_refresh() + await apply_indexers() refresh_logger.warning('Done refreshing Files') diff --git a/wrolpi/files/models.py b/wrolpi/files/models.py index ea93d2b9..53f89ff7 100644 --- a/wrolpi/files/models.py +++ b/wrolpi/files/models.py @@ -9,6 +9,7 @@ from wrolpi.common import Base, ModelHelper, get_media_directory, tsvector, logg from wrolpi.dates import TZDateTime, from_timestamp, now from wrolpi.files.indexers import MAX_TEXT_FILE_BYTES from wrolpi.media_path import MediaPathType +from wrolpi.vars import PYTEST logger = logger.getChild(__name__) @@ -104,15 +105,20 @@ class File(ModelHelper, Base): # Get the indexer on a separate line for debugging. indexer = self.indexer # Only read the contents of the file once. + start = now() a_text, b_text, c_text, d_text = indexer.create_index(self) self.a_text = truncate_object_bytes(a_text, MAX_TEXT_FILE_BYTES) self.b_text = truncate_object_bytes(b_text, MAX_TEXT_FILE_BYTES) self.c_text = truncate_object_bytes(c_text, MAX_TEXT_FILE_BYTES) self.d_text = truncate_object_bytes(d_text, MAX_TEXT_FILE_BYTES) + if (total_seconds := (now() - start).total_seconds()) > 1: + logger.info(f'Indexing {self.path} took {total_seconds} seconds') self.indexed = True except Exception as e: logger.error(f'Failed to index {self.path}', exc_info=e) + if PYTEST: + raise def do_stats(self) -> bool: """Assign the mimetype, title, size, modification_time of this file. diff --git a/wrolpi/test/test_common.py b/wrolpi/test/test_common.py index a3101b18..5d7d3663 100644 --- a/wrolpi/test/test_common.py +++ b/wrolpi/test/test_common.py @@ -349,6 +349,18 @@ def test_truncate_object_bytes(): assert common.truncate_object_bytes('foo' * 100, 0) == '' +def test_truncate_generator_bytes(): + """A generator can be truncated.""" + + def generator(): + for _ in range(5): + yield 'foo' + raise ValueError('Truncate should not get here') + + assert list(common.truncate_generator_bytes(generator(), 80)) == ['foo', 'foo'] + assert list(common.truncate_generator_bytes(generator(), 200)) == ['foo', 'foo', 'foo', 'foo'] + + def test_check_media_directory(test_directory): """The directory provided by the test_directory fixture is a valid media directory.""" assert common.check_media_directory() is True