Deleting temporary video files after video has been downloaded.

This commit is contained in:
Roland 2025-01-13 19:14:45 -07:00
parent 2bf28897ed
commit b34f5dd594
No known key found for this signature in database
GPG key ID: 1BA620CE6C9A4680
4 changed files with 51 additions and 11 deletions

View file

@ -4,6 +4,7 @@ import json
import logging
import os.path
import pathlib
import re
import traceback
from abc import ABC
from datetime import timedelta
@ -464,12 +465,8 @@ class VideoDownloader(Downloader, ABC):
with get_db_session(commit=True) as session:
# Find any files downloaded with the video (poster, caption, etc.).
video_paths = glob_shared_stem(video_path)
# Delete any leftover .part files because the video has been verified complete
# by `ffmpeg_video_complete`.
for part_file in [i for i in video_paths if i.name.endswith(f'{video_path.suffix}.part')]:
logger.warning(f'Deleting leftover .part file: {part_file}')
part_file.unlink()
video_paths.remove(part_file)
# Delete any leftover part files now that we have verified the video is complete.
video_paths = self._delete_part_files(video_path, video_paths)
# Create the Video record.
video = Video.from_paths(session, *video_paths)
video.source_id = entry['id']
@ -705,6 +702,33 @@ class VideoDownloader(Downloader, ABC):
return DownloadResult(success=True, location=location)
@staticmethod
def _delete_part_files(video_file: pathlib.Path, files: list[pathlib.Path]) -> list[pathlib.Path]:
"""Delete temporary "part" files that are used by yt-dlp when downloading video (and related) files."""
files = list(files)
video_suffix = video_file.suffix.lstrip('.')
# Delete any files in this group that end with .part.
for part_file in [i for i in files if i.name.endswith('.part')]:
logger.warning(f'Deleting leftover .part file: {part_file}')
part_file.unlink()
files.remove(part_file)
# Delete any video files that are a temporary file that contain the "format" number.
# Example: The Video Title.f616.mp4
video_files = [i for i in files if i != video_file and i.name.endswith(video_suffix)]
for part_video in video_files:
if VIDEO_FORMAT_PARSER.match(part_video.stem):
# Extra yt-dlp format video file that is not the video file, delete it.
logger.warning(f'Deleting leftover incomplete video file: {part_video}')
part_video.unlink()
files.remove(part_video)
return files
VIDEO_FORMAT_PARSER = re.compile(r'^.+?\.f\d{2,4}')
channel_downloader = ChannelDownloader()
# Videos may match the ChannelDownloader, give it a higher priority.

View file

@ -285,6 +285,8 @@ for six_ in ISO_639_CODES.keys():
EXTRA_SUFFIXES |= {f'.{six_}-{i}.srt' for i in ISO_3166_CODES}
EXTRA_SUFFIXES |= {f'.{six_}-{i}.vtt' for i in ISO_3166_CODES}
PART_PARSER = re.compile(r'(.+?)(\.f[\d]{2,3})?(\.info)?(\.\w{3,4})(\.part)', re.IGNORECASE)
@functools.lru_cache(maxsize=10_000)
def split_path_stem_and_suffix(path: Union[pathlib.Path, str], full: bool = False) -> Tuple[str, str]:
@ -301,6 +303,14 @@ def split_path_stem_and_suffix(path: Union[pathlib.Path, str], full: bool = Fals
"""
path = pathlib.Path(path) if isinstance(path, str) else path
if path.suffix == '.part':
# yt-dlp uses part files while downloading, include those in a FileGroup.
stem, info, format_num, suffix, part = PART_PARSER.match(path.name).groups()
info = info or ''
format_num = format_num or ''
stem = f'{path.parent}/{stem}' if full else stem
return stem, f'{info}{format_num}{suffix}{part}'
# May or may not be absolute. Convert to lowercase so any suffix case can be matched.
full_ = str(path).lower()
# Get the special matching suffix, if any. Match against `.en.srt` but could return `.EN.SRT`
@ -928,7 +938,7 @@ def get_matching_directories(path: Union[str, Path]) -> List[str]:
return paths
WHITESPACE = re.compile(r'[\s_]')
WHITESPACE = re.compile(r'[\s_\[\]()]')
def split_file_name_words(name: str) -> str:
@ -954,7 +964,7 @@ def split_file_name_words(name: str) -> str:
if suffix:
words.append(suffix.lstrip('.'))
words = ' '.join(words)
words = ' '.join(i for i in words if i)
return words
except Exception as e:
logger.error(f'Failed to split filename into words: {name}', exc_info=e)

View file

@ -305,7 +305,7 @@ class FileGroup(ModelHelper, Base):
unique_stems = get_unique_files_by_stem(paths)
if len(unique_stems) > 1:
raise RuntimeError(f'Refusing to create FileGroup with paths that do not share a stem.')
raise RuntimeError(f'Refusing to create FileGroup with paths that do not share a stem: {paths[0]}')
existing_groups = session.query(FileGroup).filter(FileGroup.primary_path.in_(list(map(str, paths)))).all()
logger.debug(f'FileGroup.from_paths: {len(existing_groups)}')

View file

@ -156,8 +156,12 @@ 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')),
]
)
# Part files from yt-dlp.
('foo.webm.part', False, ('foo', '.webm.part')),
('foo.f248.webm.part', False, ('foo', '.f248.webm.part')),
('foo.info.json.part', False, ('foo', '.info.json.part')),
('/absolute/foo.webm.part', True, ('/absolute/foo', '.webm.part')),
])
def test_split_path_stem_and_suffix(path, full, expected):
assert lib.split_path_stem_and_suffix(Path(path), full) == expected
@ -531,6 +535,8 @@ async def test_files_indexer(async_client, test_session, make_files_structure, t
('this self-reliance_split.txt', 'this self reliance self-reliance split txt'),
('-be_split!.txt', '-be split! txt'),
('WROLPi-v0.10-aarch64-desktop.img.xz', 'WROLPi v0.10 aarch64 desktop.img WROLPi-v0.10-aarch64-desktop.img xz'),
('some words [but words in braces].txt', 'some words but words in braces txt'),
('some words (but words in parentheses).txt', 'some words but words in parentheses txt'),
])
def test_split_file_name_words(name, expected):
assert lib.split_file_name_words(name) == expected