From 9b048af7fdac8c94837b1ce966f3f8000e2c48c4 Mon Sep 17 00:00:00 2001 From: Roland Date: Wed, 14 Dec 2022 10:33:11 -0700 Subject: [PATCH] Removing unused code. Matching use of style for file name parsing. --- modules/videos/common.py | 44 ------------------------------ modules/videos/test/test_common.py | 17 +----------- wrolpi/common.py | 18 ++++++------ wrolpi/files/ebooks.py | 4 +-- wrolpi/files/indexers.py | 7 +++-- wrolpi/files/lib.py | 4 +-- wrolpi/test/test_common.py | 12 ++++---- 7 files changed, 24 insertions(+), 82 deletions(-) diff --git a/modules/videos/common.py b/modules/videos/common.py index 94c9c650..95ddc922 100644 --- a/modules/videos/common.py +++ b/modules/videos/common.py @@ -58,50 +58,6 @@ def get_no_channel_directory() -> pathlib.Path: return directory -@iterify(set) -def remove_duplicate_video_paths(paths: Iterable[Path]) -> Set[Path]: - """ - Remove any duplicate paths from a given list. - - Duplicate is defined as any file that shares the EXACT same name as another file, but with a different extension. - If a duplicate is found, only yield one of the paths. The path that will be yielded will be whichever is first in - the VIDEO_EXTESIONS tuple. - - i.e. - >>> remove_duplicate_video_paths([Path('one.mp4'), Path('two.mp4'), Path('one.ogg')]) - {'one.mp4, 'two.mp4'} - """ - new_paths = {} - - # Group all paths by their name, but without their extension. - for path in set(paths): - name, _, _ = path.name.rpartition(path.suffix) - try: - new_paths[name].append(path) - except KeyError: - new_paths[name] = [path] - - # Yield back the first occurrence of the preferred format for each video. - for name, paths in new_paths.items(): - if len(paths) == 1: - # This should be the most common case. Most videos will only have one format. - yield paths[0] - else: - path_strings = [i.name for i in paths] - for ext in VIDEO_EXTENSIONS: - try: - index = path_strings.index(f'{name}.{ext}') - yield paths[index] - break - except ValueError: - # That extension is not in the paths. - pass - else: - # Somehow no format was found, yield back the first one. This is probably caused by an unexpected video - # format in the paths. - yield sorted(paths)[0] - - def check_for_channel_conflicts(session: Session, id_=None, url=None, name=None, directory=None, source_id=None): """ diff --git a/modules/videos/test/test_common.py b/modules/videos/test/test_common.py index 6678927c..1684231d 100644 --- a/modules/videos/test/test_common.py +++ b/modules/videos/test/test_common.py @@ -14,8 +14,7 @@ from wrolpi.dates import local_timezone, now from wrolpi.downloader import Download, DownloadFrequency from wrolpi.vars import PROJECT_DIR from .. import common -from ..common import convert_image, remove_duplicate_video_paths, \ - apply_info_json, get_video_duration, generate_video_poster, is_valid_poster +from ..common import convert_image, apply_info_json, get_video_duration, generate_video_poster, is_valid_poster from ..lib import save_channels_config, get_channels_config, import_channels_config @@ -40,20 +39,6 @@ def test_get_video_duration(test_directory): get_video_duration(empty_file) -@pytest.mark.parametrize( - 'paths,expected', - ( - (['1.mp4', ], ['1.mp4', ]), - (['1.mp4', '2.mp4'], ['1.mp4', '2.mp4']), - (['1.mp4', '1.ogg'], ['1.mp4']), - (['1.bad_ext', '1.other_ext'], ['1.bad_ext']), - ) -) -def test_remove_duplicate_video_paths(paths, expected): - result = remove_duplicate_video_paths(map(pathlib.Path, paths)) - assert sorted(result) == sorted(map(pathlib.Path, expected)) - - def test_convert_image(): """ An image's format can be changed. This tests that convert_image() converts from a WEBP format, to a JPEG format. diff --git a/wrolpi/common.py b/wrolpi/common.py index a6bdfe17..8f5dfc85 100644 --- a/wrolpi/common.py +++ b/wrolpi/common.py @@ -85,7 +85,7 @@ __all__ = [ 'apply_after_refresh', 'match_paths_to_suffixes', 'chunks', - 'chunks_by_name', + 'chunks_by_stem', 'timer', 'cum_timer', 'limit_concurrent', @@ -861,15 +861,15 @@ def chunks(it: Iterable, size: int): return iter(lambda: tuple(islice(it, size)), ()) -def chunks_by_name(it: List[Union[pathlib.Path, str]], size: int) -> Generator[List[pathlib.Path], None, None]: +def chunks_by_stem(it: List[Union[pathlib.Path, str]], size: int) -> Generator[List[pathlib.Path], None, None]: """ Attempt to split a list of paths near the defined size. Keep groups of files together when they share matching names. >>> files = ['1.mp4', '1.txt', '2.mp4', '2.txt', '2.png', '3.mp4'] - >>> chunks_by_name(files, 2) + >>> chunks_by_stem(files, 2) [['1.mp4', '1.txt'], ['2.mp4', '2.txt', '2.png'], ['3.mp4']] - >>> chunks_by_name(files, 3) + >>> chunks_by_stem(files, 3) [['1.mp4', '1.txt', '2.mp4', '2.txt', '2.png'], ['3.mp4']] """ if not isinstance(size, int) or size < 1: @@ -885,23 +885,23 @@ def chunks_by_name(it: List[Union[pathlib.Path, str]], size: int) -> Generator[L from wrolpi.files.lib import split_path_stem_and_suffix it = sorted(it.copy()) index = size - last_name = None + last_stem = None while it: if index >= len(it): # Ran out of items, yield what is left. yield it return path = it[index] - name, _ = split_path_stem_and_suffix(path) - if last_name and name != last_name: + stem, _ = split_path_stem_and_suffix(path) + if last_stem and stem != last_stem: # Found a break in the path names, yield and reset. chunk, it = it[:index], it[index:] index = size - last_name = None + last_stem = None yield chunk continue # Didn't find a name change, try again. - last_name = name + last_stem = stem index += 1 diff --git a/wrolpi/files/ebooks.py b/wrolpi/files/ebooks.py index a21fb090..e3873aff 100644 --- a/wrolpi/files/ebooks.py +++ b/wrolpi/files/ebooks.py @@ -229,8 +229,8 @@ def model_ebook(session: Session, ebook_file: File, files: List[File]) -> EBook: if not ebook.title: # Book was not indexed above (probably a MOBI), use the file data. - name, _ = split_path_stem_and_suffix(ebook.ebook_file.path) - ebook.title = ebook.ebook_file.a_text = name + stem, _ = split_path_stem_and_suffix(ebook.ebook_file.path) + ebook.title = ebook.ebook_file.a_text = stem if cover_file: cover_file.associated = True diff --git a/wrolpi/files/indexers.py b/wrolpi/files/indexers.py index c7ab5ae1..5cbe40d5 100644 --- a/wrolpi/files/indexers.py +++ b/wrolpi/files/indexers.py @@ -10,7 +10,7 @@ try: except ImportError: PdfReader = None -from wrolpi.common import logger +from wrolpi.common import logger, timer logger = logger.getChild(__name__) @@ -79,7 +79,7 @@ def register_indexer(*mimetypes: str): @register_indexer('application/zip') class ZipIndexer(Indexer, ABC): - """Handles archive files lik zip.""" + """Handles archive files like zip.""" @classmethod def create_index(cls, file): @@ -146,7 +146,8 @@ class PDFIndexer(Indexer, ABC): words = '' try: # PDFs are complex, don't fail to create title index if text extraction fails. - words = cls.get_words(path) + with timer(f'get words {path=}'): + words = cls.get_words(path) except Exception as e: logger.error(f'Failed to index {path}', exc_info=e) return a, None, None, words diff --git a/wrolpi/files/lib.py b/wrolpi/files/lib.py index e6bb6718..7ce5bd60 100644 --- a/wrolpi/files/lib.py +++ b/wrolpi/files/lib.py @@ -16,7 +16,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_name, \ + get_files_and_directories, apply_modelers, apply_after_refresh, get_model_by_table_name, chunks_by_stem, \ background_task, partition, ordered_unique_list from wrolpi.dates import now from wrolpi.db import get_db_session, get_db_curs, get_ranked_models @@ -160,7 +160,7 @@ async def _refresh_files_list(paths: List[pathlib.Path], idempotency: datetime.d if not paths: return - for idx, chunk in enumerate(map(set, chunks_by_name(paths, FILE_REFRESH_CHUNK_SIZE))): + for idx, chunk in enumerate(map(set, chunks_by_stem(paths, FILE_REFRESH_CHUNK_SIZE))): with get_db_session(commit=True) as session: existing_files = list(session.query(File).filter(File.path.in_(chunk))) existing_paths = {i.path for i in existing_files} diff --git a/wrolpi/test/test_common.py b/wrolpi/test/test_common.py index c5990cbb..a3101b18 100644 --- a/wrolpi/test/test_common.py +++ b/wrolpi/test/test_common.py @@ -361,13 +361,13 @@ def test_bad_check_media_directory(): assert common.check_media_directory() is False -def test_chunks_by_name(test_directory, make_files_structure): - """`chunks_by_name` breaks a list of paths on the name change close to the size.""" +def test_chunks_by_stem(test_directory, make_files_structure): + """`chunks_by_stem` breaks a list of paths on the name change close to the size.""" with pytest.raises(ValueError): - assert list(common.chunks_by_name([], 0)) == [[]] + assert list(common.chunks_by_stem([], 0)) == [[]] - assert list(common.chunks_by_name([], 5)) == [[]] - assert list(common.chunks_by_name([1, 2, 3], 5)) == [[1, 2, 3]] + assert list(common.chunks_by_stem([], 5)) == [[]] + assert list(common.chunks_by_stem([1, 2, 3], 5)) == [[1, 2, 3]] files = make_files_structure([ 'foo.mp4', 'foo.txt', 'foo.png', 'foo.info.json', @@ -377,7 +377,7 @@ def test_chunks_by_name(test_directory, make_files_structure): ]) def assert_chunks(size, files_, expected): - for chunk, expected_chunk in zip_longest(list(common.chunks_by_name(files_, size)), expected): + for chunk, expected_chunk in zip_longest(list(common.chunks_by_stem(files_, size)), expected): assert chunk == [test_directory / i for i in expected_chunk] assert_chunks(8, files, [