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.

This commit is contained in:
Roland 2026-02-07 18:40:56 -07:00
parent fa5c116b62
commit a6d6aaf9b4
No known key found for this signature in database
GPG key ID: 1BA620CE6C9A4680
15 changed files with 231 additions and 27 deletions

View file

@ -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,

View file

@ -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() {
/>
</div>
<div style={{margin: '0.5em'}}>
<Toggle
label='Save FFprobe Cache Files'
disabled={disabled || state.save_ffprobe_json === null}
checked={state.save_ffprobe_json === true}
onChange={checked => 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).'
/>
</div>
<Form.Group inline>
<Form.Input
label={<>

View file

@ -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'

View file

@ -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):

View file

@ -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

View file

@ -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.

View file

@ -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')

View file

@ -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)

View file

@ -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.

View file

@ -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

View file

@ -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()

View file

@ -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)

View file

@ -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

View file

@ -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:

View file

@ -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.