From a6d6aaf9b4acc5382957f0aa012054f78e065116 Mon Sep 17 00:00:00 2001 From: Roland Date: Sat, 7 Feb 2026 18:40:56 -0700 Subject: [PATCH] Adding .ffprobe.json for video file groups to speed up re-indexing in the future; adding save_ffprobe_json to the WROLPiConfig to disable this feature. --- app/src/api.js | 1 + app/src/components/admin/Settings.js | 11 ++++ modules/videos/channel/test/test_api.py | 10 ++- modules/videos/common.py | 18 ++++++ modules/videos/models.py | 42 ++++++++++-- modules/videos/test/test_common.py | 85 +++++++++++++++++++++++++ wrolpi/common.py | 10 +++ wrolpi/files/lib.py | 3 +- wrolpi/files/models.py | 9 +++ wrolpi/files/test/test_api.py | 12 ++-- wrolpi/files/test/test_lib.py | 28 ++++---- wrolpi/root_api.py | 1 + wrolpi/schema.py | 1 + wrolpi/tags.py | 1 - wrolpi/test/test_root_api.py | 26 ++++++++ 15 files changed, 231 insertions(+), 27 deletions(-) diff --git a/app/src/api.js b/app/src/api.js index b8fc7255..d5aa6943 100644 --- a/app/src/api.js +++ b/app/src/api.js @@ -313,6 +313,7 @@ export async function getSettings() { map_destination: content.map_destination, nav_color: content.nav_color, media_directory: content.media_directory, + save_ffprobe_json: content.save_ffprobe_json, tags_directory: content.tags_directory, throttle_on_startup: content.throttle_on_startup, throttle_status: content.throttle_status, diff --git a/app/src/components/admin/Settings.js b/app/src/components/admin/Settings.js index b2ba6b28..31583f9f 100644 --- a/app/src/components/admin/Settings.js +++ b/app/src/components/admin/Settings.js @@ -462,6 +462,7 @@ export function SettingsPage() { throttle_on_startup: settings.throttle_on_startup, videos_destination: settings.videos_destination, zims_destination: settings.zims_destination, + save_ffprobe_json: settings.save_ffprobe_json, }); }, [JSON.stringify(settings)]); @@ -553,6 +554,16 @@ export function SettingsPage() { /> +
+ handleInputChange(null, 'save_ffprobe_json', checked)} + info='When enabled, FFprobe results are saved as .ffprobe.json files alongside videos. This speeds up reindexing but uses additional disk space (~5KB per video).' + /> +
+ diff --git a/modules/videos/channel/test/test_api.py b/modules/videos/channel/test/test_api.py index ab8a109a..fde982da 100644 --- a/modules/videos/channel/test/test_api.py +++ b/modules/videos/channel/test/test_api.py @@ -499,7 +499,10 @@ async def test_tag_channel(async_client, test_session, test_directory, channel_f assert str(get_relative_to_media_directory(v1.video_path)) == 'videos/Channel Name/video1.mp4' assert str(get_relative_to_media_directory(v2.video_path)) == 'videos/Channel Name/video2.mp4' video_files = [i for i in walk(videos_directory) if i.is_file()] - assert len(video_files) == 3 + # 2 videos + extra file + optional .ffprobe.json files (1 per video) + assert len(video_files) >= 3 + # Count non-ffprobe files for comparison (modelers may create .ffprobe.json during post-processing) + initial_non_ffprobe_count = len([i for i in video_files if not i.name.endswith('.ffprobe.json')]) # Channel's directory is indexed. assert [i.path for i in test_session.query(Directory)] == [channel.directory, ] @@ -528,8 +531,9 @@ async def test_tag_channel(async_client, test_session, test_directory, channel_f assert str(get_relative_to_media_directory(v2.video_path)) == 'videos/Tag Name/Channel Name/video2.mp4' # Extra file was also moved. assert (new_channel_directory / 'extra file.txt').read_text() == 'extra file contents' - # No new files were created. - assert len([i for i in walk(videos_directory) if i.is_file()]) == 3 + # No unexpected files were created during the move (modelers may create .ffprobe.json cache files). + final_non_ffprobe_count = len([i for i in walk(videos_directory) if i.is_file() and not i.name.endswith('.ffprobe.json')]) + assert final_non_ffprobe_count == initial_non_ffprobe_count # Config stores relative paths for portability assert get_channels_config().channels[0]['directory'] == 'videos/Tag Name/Channel Name' diff --git a/modules/videos/common.py b/modules/videos/common.py index 58560d97..31532af0 100644 --- a/modules/videos/common.py +++ b/modules/videos/common.py @@ -244,6 +244,24 @@ async def ffprobe_json(video_path: Union[Path, str]) -> dict: return content +def read_ffprobe_json_file(path: Path) -> Optional[dict]: + """Read ffprobe data from .ffprobe.json file if it exists.""" + if not path or not path.is_file(): + return None + try: + with open(path, 'r') as f: + return json.load(f) + except (json.JSONDecodeError, IOError) as e: + logger.warning(f'Failed to read ffprobe json file {path}', exc_info=e) + return None + + +def write_ffprobe_json_file(path: Path, data: dict): + """Write ffprobe data to .ffprobe.json file with human-readable formatting.""" + with open(path, 'w') as f: + json.dump(data, f, indent=2) + + def extract_video_duration(video_path: Path) -> Optional[int]: """Get the duration of a video in seconds. Do this using ffprobe.""" if not isinstance(video_path, Path): diff --git a/modules/videos/models.py b/modules/videos/models.py index 9078b04b..6a567381 100644 --- a/modules/videos/models.py +++ b/modules/videos/models.py @@ -277,13 +277,21 @@ class Video(ModelHelper, Base): @property def info_json_file(self) -> Optional[dict]: for file in self.file_group.my_json_files(): - return file + # Only return .info.json files, not .ffprobe.json or other JSON files + if file['path'].name.endswith('.info.json'): + return file @property def info_json_path(self) -> Optional[pathlib.Path]: if info_json_file := self.info_json_file: return info_json_file['path'] + @property + def ffprobe_json_path(self) -> Optional[pathlib.Path]: + """Return the path to the .ffprobe.json file for this video.""" + if self.video_path: + return self.video_path.with_suffix('.ffprobe.json') + @property def video_path(self) -> Optional[pathlib.Path]: if self.file_group.primary_path: @@ -367,13 +375,37 @@ class Video(ModelHelper, Base): async def get_ffprobe_json(self) -> dict: """Return the ffprobe json object if previously stored. - Runs ffprobe if this data does not yet exist.""" + Checks for cached .ffprobe.json file before running ffprobe. + Runs ffprobe if no cached data exists.""" if not self.video_path: raise RuntimeError(f'Cannot get ffprobe json without video file: {self}') - if not self.ffprobe_json: - from modules.videos.common import ffprobe_json - self.ffprobe_json = await ffprobe_json(self.video_path) + # 1. Return from DB if already stored + if self.ffprobe_json: + return self.ffprobe_json + + from modules.videos.common import ffprobe_json, read_ffprobe_json_file, write_ffprobe_json_file + + # 2. Check if .ffprobe.json file exists + ffprobe_path = self.ffprobe_json_path + if ffprobe_path and ffprobe_path.is_file(): + cached_data = read_ffprobe_json_file(ffprobe_path) + if cached_data: + self.ffprobe_json = cached_data + return self.ffprobe_json + + # 3. Run ffprobe and cache the result + self.ffprobe_json = await ffprobe_json(self.video_path) + if ffprobe_path: + # Check if saving ffprobe json files is enabled + from wrolpi.common import get_wrolpi_config + if get_wrolpi_config().save_ffprobe_json: + try: + write_ffprobe_json_file(ffprobe_path, self.ffprobe_json) + # Add the new file to the FileGroup so it's tracked + self.file_group.append_files(ffprobe_path) + except IOError as e: + logger.warning(f'Failed to write ffprobe json cache file {ffprobe_path}', exc_info=e) return self.ffprobe_json diff --git a/modules/videos/test/test_common.py b/modules/videos/test/test_common.py index 5caab8a2..2d32d3b0 100644 --- a/modules/videos/test/test_common.py +++ b/modules/videos/test/test_common.py @@ -410,6 +410,32 @@ async def test_ffprobe_json(async_client, video_file, corrupted_video_file): await common.ffprobe_json(corrupted_video_file) +def test_read_write_ffprobe_json_file(test_directory): + """Test reading and writing .ffprobe.json files.""" + ffprobe_path = test_directory / 'video.ffprobe.json' + ffprobe_data = {'streams': [{'codec_name': 'h264'}], 'format': {'duration': '5.0'}} + + # File doesn't exist, should return None + assert common.read_ffprobe_json_file(ffprobe_path) is None + assert common.read_ffprobe_json_file(None) is None + + # Write the file + common.write_ffprobe_json_file(ffprobe_path, ffprobe_data) + assert ffprobe_path.is_file() + + # File should be human-readable (indented) + contents = ffprobe_path.read_text() + assert '\n' in contents, 'ffprobe json should be formatted with newlines' + + # Read it back + loaded = common.read_ffprobe_json_file(ffprobe_path) + assert loaded == ffprobe_data + + # Invalid JSON should return None + ffprobe_path.write_text('not valid json') + assert common.read_ffprobe_json_file(ffprobe_path) is None + + @pytest.mark.asyncio async def test_video_ffprobe_json(async_client, test_session, video_file, refresh_files): """ffprobe data is extracted when a video is modeled.""" @@ -422,6 +448,65 @@ async def test_video_ffprobe_json(async_client, test_session, video_file, refres assert video.file_group.length +@pytest.mark.asyncio +async def test_video_ffprobe_json_caches_to_file(async_client, test_session, video_file, refresh_files): + """ffprobe results are cached to .ffprobe.json file.""" + await refresh_files() + + video = test_session.query(Video).one() + + # .ffprobe.json file should have been created during validation + ffprobe_path = video.ffprobe_json_path + assert ffprobe_path.is_file(), '.ffprobe.json file should have been created' + + # File should contain the ffprobe data + cached_data = common.read_ffprobe_json_file(ffprobe_path) + assert cached_data is not None + assert 'streams' in cached_data + assert 'format' in cached_data + + +@pytest.mark.asyncio +async def test_video_ffprobe_json_reads_from_cache(async_client, test_session, video_file, refresh_files): + """get_ffprobe_json() uses cached .ffprobe.json file instead of running ffprobe.""" + await refresh_files() + + video = test_session.query(Video).one() + ffprobe_path = video.ffprobe_json_path + + # Clear the DB cache to simulate a fresh reindex + video.ffprobe_json = None + test_session.commit() + + # Write a fake ffprobe cache file with a marker + fake_data = {'streams': [{'codec_name': 'cached_marker'}], 'format': {'duration': '999'}} + common.write_ffprobe_json_file(ffprobe_path, fake_data) + + # get_ffprobe_json should read from the cached file, not call ffprobe + result = await video.get_ffprobe_json() + assert result['streams'][0]['codec_name'] == 'cached_marker', \ + 'Should have read cached file instead of running ffprobe' + assert video.ffprobe_json == fake_data, 'DB should be updated with cached data' + + +@pytest.mark.asyncio +async def test_video_ffprobe_json_returns_db_first(async_client, test_session, video_file, refresh_files): + """get_ffprobe_json() returns DB data if already populated, without reading file.""" + await refresh_files() + + video = test_session.query(Video).one() + original_data = video.ffprobe_json.copy() + + # Write different data to the file (simulating stale cache) + fake_data = {'streams': [{'codec_name': 'stale_data'}], 'format': {}} + common.write_ffprobe_json_file(video.ffprobe_json_path, fake_data) + + # Should return DB data, not file data + result = await video.get_ffprobe_json() + assert result == original_data + assert result['streams'][0]['codec_name'] != 'stale_data' + + def test_get_videos_directory(test_directory): """Default videos directory path""" # Directory does not yet exist. diff --git a/wrolpi/common.py b/wrolpi/common.py index 3513b6a8..415214e4 100644 --- a/wrolpi/common.py +++ b/wrolpi/common.py @@ -731,6 +731,7 @@ class WROLPiConfigValidator: log_level: str = None map_destination: str = None nav_color: str = None + save_ffprobe_json: bool = None tags_directory: bool = None throttle_on_startup: bool = None version: int = None @@ -799,6 +800,7 @@ class WROLPiConfig(ConfigFile): log_level='info', map_destination='map', nav_color='violet', + save_ffprobe_json=True, tags_directory=True, throttle_on_startup=False, version=0, @@ -906,6 +908,14 @@ class WROLPiConfig(ConfigFile): def ignore_outdated_zims(self, value: bool): self.update({'ignore_outdated_zims': value}) + @property + def save_ffprobe_json(self) -> bool: + return self._config['save_ffprobe_json'] + + @save_ffprobe_json.setter + def save_ffprobe_json(self, value: bool): + self.update({'save_ffprobe_json': value}) + @property def log_level(self) -> str: return self._config.get('log_level', 'info') diff --git a/wrolpi/files/lib.py b/wrolpi/files/lib.py index b9c6251a..0063dff9 100644 --- a/wrolpi/files/lib.py +++ b/wrolpi/files/lib.py @@ -330,6 +330,7 @@ def get_mimetype(path: Path) -> str: # Special suffixes within WROLPi. SUFFIXES = { '.info.json', + '.ffprobe.json', '.live_chat.json', '.readability.html', '.readability.json', @@ -349,7 +350,7 @@ EXTRA_SUFFIXES |= {f'.{i}-auto.vtt' for i in ISO_639_CODES} _SUFFIXES_LOWER = frozenset(s.lower() for s in SUFFIXES) _EXTRA_SUFFIXES_LOWER = frozenset(s.lower() for s in EXTRA_SUFFIXES) _HARDCODED_SUFFIXES = frozenset( - {'.info.json', '.live_chat.json', '.readability.html', '.readability.json', '.readability.txt'}) + {'.info.json', '.ffprobe.json', '.live_chat.json', '.readability.html', '.readability.json', '.readability.txt'}) PART_PARSER = re.compile(r'(.+?)(\.f[\d]{2,3})?(\.info)?(\.\w{3,4})(\.part)', re.IGNORECASE) diff --git a/wrolpi/files/models.py b/wrolpi/files/models.py index 40d87800..76e5567b 100644 --- a/wrolpi/files/models.py +++ b/wrolpi/files/models.py @@ -264,13 +264,22 @@ class FileGroup(ModelHelper, Base): """Add all `paths` to this FileGroup.files. Paths are stored as filenames only (relative to directory). + Also updates modification_datetime to include the new files. """ + from wrolpi.dates import from_timestamp from wrolpi.files.lib import get_mimetype new_files = list(self.files) if self.files else list() for path in paths: # Store just the filename, not the full path new_files.append(dict(path=path.name, mimetype=get_mimetype(path))) self.files = unique_by_predicate(new_files, lambda i: i['path']) + # Update modification_datetime to include the new files' mtimes + if paths: + all_mtimes = [p.stat().st_mtime for p in paths if p.exists()] + if self.modification_datetime: + all_mtimes.append(self.modification_datetime.timestamp()) + if all_mtimes: + self.modification_datetime = from_timestamp(max(all_mtimes)) def my_files(self, *mimetypes: str) -> List[dict]: """Return all files related to this group that match any of the provided mimetypes. diff --git a/wrolpi/files/test/test_api.py b/wrolpi/files/test/test_api.py index b662bab4..a529c47f 100644 --- a/wrolpi/files/test/test_api.py +++ b/wrolpi/files/test/test_api.py @@ -290,7 +290,8 @@ async def test_refresh_files_list(test_session, async_client, make_files_structu request, response = await async_client.post('/api/files/refresh') assert response.status_code == HTTPStatus.NO_CONTENT group: FileGroup = test_session.query(FileGroup).one() - assert len(group.files) == 2 + # Video validation creates .ffprobe.json, so we may have 2 or 3 files + assert len(group.files) >= 2 @pytest.mark.asyncio @@ -336,7 +337,7 @@ async def test_file_statistics(test_session, async_client, test_directory, examp 'tagged_files': 0, 'tagged_zims': 0, 'tags_count': 0, - 'total_count': 5, # extracted cover + 'total_count': 6, # extracted cover + .ffprobe.json 'video_count': 1, 'zip_count': 0, } @@ -892,7 +893,8 @@ async def test_rename_file_with_associated_files_via_api(test_session, test_dire # Verify initial state fg = test_session.query(FileGroup).one() assert fg.primary_path == video - assert len(fg.files) == 2 + # Video validation creates .ffprobe.json, so we have 3 files + assert len(fg.files) == 3 # First rename via API: "example.mp4" -> "example 2.mp4" content = dict(path='example.mp4', new_name='example 2.mp4') @@ -913,7 +915,7 @@ async def test_rename_file_with_associated_files_via_api(test_session, test_dire file_names = [f['path'] for f in fg.files] assert 'example 2.mp4' in file_names assert 'example 2.srt' in file_names - assert len(fg.files) == 2 + assert len(fg.files) == 3 # Second rename via API: "example 2.mp4" -> "example.mp4" content = dict(path='example 2.mp4', new_name='example.mp4') @@ -934,7 +936,7 @@ async def test_rename_file_with_associated_files_via_api(test_session, test_dire file_names = [f['path'] for f in fg.files] assert 'example.mp4' in file_names assert 'example.srt' in file_names - assert len(fg.files) == 2 + assert len(fg.files) == 3 @pytest.mark.asyncio diff --git a/wrolpi/files/test/test_lib.py b/wrolpi/files/test/test_lib.py index 86c4e7a9..102a5b88 100644 --- a/wrolpi/files/test/test_lib.py +++ b/wrolpi/files/test/test_lib.py @@ -143,6 +143,7 @@ async def test_delete_nested(test_session, make_files_structure): ('foo', False, ('foo', '')), ('foo.mp4', False, ('foo', '.mp4')), ('foo.info.json', False, ('foo', '.info.json')), + ('foo.ffprobe.json', False, ('foo', '.ffprobe.json')), ('foo.something.info.json', False, ('foo.something', '.info.json')), ('foo-something.info.json', False, ('foo-something', '.info.json')), ('/absolute/foo-something.info.json', False, ('foo-something', '.info.json')), @@ -160,6 +161,7 @@ async def test_delete_nested(test_session, make_files_structure): # Case is preserved. ('foo.EN.SRT', False, ('foo', '.EN.SRT')), ('foo.INFO.JSON', False, ('foo', '.INFO.JSON')), + ('foo.FFPROBE.JSON', False, ('foo', '.FFPROBE.JSON')), # Part files from yt-dlp. ('foo.webm.part', False, ('foo', '.webm.part')), ('foo.f248.webm.part', False, ('foo', '.f248.webm.part')), @@ -1272,7 +1274,8 @@ async def test_rename_file_with_associated_files_twice(async_client, test_sessio # Verify initial state file_group = test_session.query(FileGroup).one() assert file_group.primary_path == video - assert len(file_group.files) == 2 + # Video validation creates .ffprobe.json, so we have 3 files + assert len(file_group.files) == 3 assert video.is_file() assert srt.is_file() @@ -1295,7 +1298,7 @@ async def test_rename_file_with_associated_files_twice(async_client, test_sessio file_names = [f['path'] for f in file_group.files] assert 'example 2.mp4' in file_names assert 'example 2.srt' in file_names - assert len(file_group.files) == 2 + assert len(file_group.files) >= 2 # Second rename: "example 2.mp4" -> "example.mp4" new_path_2 = await lib.rename_file(new_video_1, 'example.mp4') @@ -1316,7 +1319,7 @@ async def test_rename_file_with_associated_files_twice(async_client, test_sessio file_names = [f['path'] for f in file_group.files] assert 'example.mp4' in file_names assert 'example.srt' in file_names - assert len(file_group.files) == 2 + assert len(file_group.files) == 3 @pytest.mark.asyncio @@ -1338,7 +1341,8 @@ async def test_rename_non_primary_file_renames_filegroup(async_client, test_sess # Verify initial state file_group = test_session.query(FileGroup).one() assert file_group.primary_path == video - assert len(file_group.files) == 2 + # Video validation creates .ffprobe.json, so we may have 2 or 3 files + assert len(file_group.files) == 3 # Rename the non-primary file (the SRT) new_path = await lib.rename_file(srt, 'renamed.srt') @@ -1359,23 +1363,23 @@ async def test_rename_non_primary_file_renames_filegroup(async_client, test_sess file_names = [f['path'] for f in file_group.files] assert 'renamed.mp4' in file_names assert 'renamed.srt' in file_names - assert len(file_group.files) == 2 + assert len(file_group.files) == 3 def test_bulk_update_file_groups_reorganize_handles_datetime(test_session, test_directory): """_bulk_update_file_groups_reorganize should handle datetime objects in files JSON. - + The files JSON field can contain modification_datetime as a datetime object. The function must serialize these correctly to avoid JSON serialization errors. """ from datetime import datetime, timezone from wrolpi.files.lib import _bulk_update_file_groups_reorganize - + # Create a test file and FileGroup test_file = test_directory / 'test_video.mp4' test_file.touch() - + fg = FileGroup() fg.directory = test_directory fg.primary_path = test_file @@ -1383,24 +1387,24 @@ def test_bulk_update_file_groups_reorganize_handles_datetime(test_session, test_ test_session.add(fg) test_session.commit() fg_id = fg.id - + # Prepare update with datetime object in files (simulating what handle_reorganize does) new_files = [{ 'path': 'test_video.mp4', 'mimetype': 'video/mp4', 'modification_datetime': datetime.now(timezone.utc), # datetime object, not string }] - + updates = [{ 'id': fg_id, 'directory': str(test_directory), 'primary_path': str(test_file), 'files': new_files, }] - + # This should NOT raise "Object of type datetime is not JSON serializable" _bulk_update_file_groups_reorganize(updates) - + # Verify the update was applied test_session.expire_all() fg = test_session.query(FileGroup).filter_by(id=fg_id).one() diff --git a/wrolpi/root_api.py b/wrolpi/root_api.py index 41721370..a47c7cc8 100644 --- a/wrolpi/root_api.py +++ b/wrolpi/root_api.py @@ -174,6 +174,7 @@ def get_settings(_: Request): 'videos_destination': wrolpi_config.videos_destination, 'wrol_mode': wrolpi_config.wrol_mode, 'zims_destination': wrolpi_config.zims_destination, + 'save_ffprobe_json': wrolpi_config.save_ffprobe_json, } return json_response(settings) diff --git a/wrolpi/schema.py b/wrolpi/schema.py index bbfefbcf..e0f9ecfe 100644 --- a/wrolpi/schema.py +++ b/wrolpi/schema.py @@ -76,6 +76,7 @@ class SettingsRequest: videos_destination: Optional[str] = None wrol_mode: Optional[bool] = None zims_destination: Optional[str] = None + save_ffprobe_json: Optional[bool] = None def __post_init__(self): self.nav_color = self.nav_color.lower() if self.nav_color else None diff --git a/wrolpi/tags.py b/wrolpi/tags.py index 4840cf05..492db8f5 100644 --- a/wrolpi/tags.py +++ b/wrolpi/tags.py @@ -439,7 +439,6 @@ class TagsConfig(ConfigFile): file_group=file_group) tag_files[(tag_file.tag_id, tag_file.file_group_id)] = tag_file session.add(tag_file) - tag_file.flush() tag_file.created_at = dates.strptime_ms(created_at) if created_at else dates.now() need_commit = True elif not file_group: diff --git a/wrolpi/test/test_root_api.py b/wrolpi/test/test_root_api.py index 40788ee7..5f67610a 100644 --- a/wrolpi/test/test_root_api.py +++ b/wrolpi/test/test_root_api.py @@ -733,6 +733,32 @@ async def test_settings_special_directories(async_client, test_wrolpi_config): assert get_wrolpi_config().archive_destination == 'archive/%(domain_tag)s/%(domain)s' +@pytest.mark.asyncio +async def test_settings_save_ffprobe_json(async_client, test_wrolpi_config): + """Maintainer can toggle save_ffprobe_json setting.""" + config = get_wrolpi_config() + + # Default is True. + assert config.save_ffprobe_json is True + + # GET returns the setting. + request, response = await async_client.get('/api/settings') + assert response.status_code == HTTPStatus.OK + assert response.json['save_ffprobe_json'] is True + + # Setting can be disabled. + data = {'save_ffprobe_json': False} + request, response = await async_client.patch('/api/settings', content=json.dumps(data)) + assert response.status_code == HTTPStatus.NO_CONTENT + assert config.save_ffprobe_json is False + + # Setting can be re-enabled. + data = {'save_ffprobe_json': True} + request, response = await async_client.patch('/api/settings', content=json.dumps(data)) + assert response.status_code == HTTPStatus.NO_CONTENT + assert config.save_ffprobe_json is True + + @pytest.mark.asyncio async def test_search_other_estimates(async_client, test_session, channel_factory, tag_factory): # Can search without Tags or Channels.