mirror of
https://github.com/lrnselfreliance/wrolpi.git
synced 2026-12-01 20:36:21 -05:00
Creating Video.validated which is used by find_corrupt_videos.py to search.
This commit is contained in:
parent
d0d315cd67
commit
e8e5b5727f
17 changed files with 253 additions and 125 deletions
|
|
@ -44,7 +44,8 @@ async def video_modeler():
|
|||
except Exception as e:
|
||||
if PYTEST:
|
||||
raise
|
||||
logger.error(f'Unable to model Video {video_id=}', exc_info=e)
|
||||
i = video.file_group.primary_path if video.file_group else video_id
|
||||
logger.error(f'Unable to model Video {i=}', exc_info=e)
|
||||
|
||||
file_group.indexed = True
|
||||
|
||||
|
|
|
|||
|
|
@ -18,6 +18,7 @@ from sqlalchemy.orm import Session
|
|||
from wrolpi.captions import FFMPEG_BIN
|
||||
from wrolpi.cmd import FFPROBE_BIN
|
||||
from wrolpi.common import logger, get_media_directory
|
||||
from wrolpi.dates import seconds_to_timestamp
|
||||
from wrolpi.db import get_db_session, get_db_curs
|
||||
from wrolpi.vars import DEFAULT_FILE_PERMISSIONS
|
||||
from .errors import ChannelNameConflict, ChannelURLConflict, ChannelDirectoryConflict, ChannelSourceIdConflict
|
||||
|
|
@ -118,24 +119,45 @@ def get_duration_from_ffmpeg(stderr: str) -> int:
|
|||
return duration
|
||||
|
||||
|
||||
def generate_video_poster(video_path: Path) -> Tuple[Path, Optional[int]]:
|
||||
"""Create a poster (aka thumbnail) next to the provided video_path. Also returns the video duration."""
|
||||
poster_path = video_path.with_suffix('.jpg')
|
||||
cmd = (FFMPEG_BIN, '-n', '-i', str(video_path), '-f', 'mjpeg', '-vframes', '1', '-ss', '00:00:05.000',
|
||||
str(poster_path))
|
||||
if poster_path.exists():
|
||||
# Poster already exists.
|
||||
return poster_path, None
|
||||
def ffmpeg_poster(video_path: Path, poster_path: Path, seconds: int):
|
||||
"""Use ffmpeg to create a poster file from a video file at a particular time of the video.
|
||||
|
||||
Returns stderr so data about the command can be extracted."""
|
||||
timestamp = seconds_to_timestamp(seconds)
|
||||
cmd = (FFMPEG_BIN, '-ss', timestamp, '-n', '-i', video_path, '-f', 'mjpeg', '-vframes', '1', poster_path)
|
||||
try:
|
||||
proc = subprocess.run(cmd, check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
|
||||
stderr = proc.stderr.decode()
|
||||
logger.info(f'Generated poster at {poster_path}')
|
||||
except subprocess.CalledProcessError as e:
|
||||
logger.warning(f'FFMPEG poster generation failed with stdout: {e.stdout.decode()}')
|
||||
logger.warning(f'FFMPEG poster generation failed with stdout: {e.stderr.decode()}')
|
||||
logger.error(f'Failed to create video poster', exc_info=e)
|
||||
raise
|
||||
if not poster_path.exists():
|
||||
raise Exception(f'Failed to find generated poster! {poster_path}')
|
||||
|
||||
return stderr
|
||||
|
||||
|
||||
def ffmpeg_video_complete(video_path: Path, seconds: int = None) -> bool:
|
||||
"""Checks if video file is complete by taking screenshot from the end of the video."""
|
||||
seconds = seconds or get_video_duration(video_path) - 5
|
||||
with tempfile.NamedTemporaryFile(suffix='.jpg', delete=False) as fh:
|
||||
path = Path(fh.name)
|
||||
path.unlink()
|
||||
try:
|
||||
ffmpeg_poster(video_path, path, seconds)
|
||||
return True
|
||||
except Exception:
|
||||
return False
|
||||
finally:
|
||||
path.unlink()
|
||||
|
||||
|
||||
def generate_video_poster(video_path: Path, seconds: int = 5) -> Tuple[Path, Optional[int]]:
|
||||
"""Create a poster (aka thumbnail) next to the provided video_path. Also returns the video duration."""
|
||||
poster_path = video_path.with_suffix('.jpg')
|
||||
if poster_path.exists():
|
||||
# Poster already exists.
|
||||
return poster_path, None
|
||||
|
||||
stderr = ffmpeg_poster(video_path, poster_path, seconds)
|
||||
|
||||
duration = get_duration_from_ffmpeg(stderr)
|
||||
return poster_path, duration
|
||||
|
|
|
|||
|
|
@ -22,7 +22,7 @@ from wrolpi.errors import UnrecoverableDownloadError
|
|||
from wrolpi.files.lib import glob_shared_stem
|
||||
from wrolpi.vars import PYTEST
|
||||
from .channel.lib import create_channel, get_channel
|
||||
from .common import get_no_channel_directory, get_videos_directory, update_view_counts
|
||||
from .common import get_no_channel_directory, get_videos_directory, update_view_counts, ffmpeg_video_complete
|
||||
from .errors import UnknownChannel, ChannelURLEmpty
|
||||
from .lib import get_downloader_config
|
||||
from .models import Video, Channel
|
||||
|
|
@ -168,6 +168,9 @@ class VideoDownloader(Downloader, ABC):
|
|||
"""Downloads a single video.
|
||||
|
||||
Store the video in its channel's directory, otherwise store it in `videos/NO CHANNEL`.
|
||||
|
||||
Videos are validated in a few ways. A video file is valid when it has a complete video stream and an audio stream.
|
||||
A complete video stream is validated by taking a screenshot at the end of the video.
|
||||
"""
|
||||
name = 'video'
|
||||
pretty_name = 'Videos'
|
||||
|
|
@ -300,6 +303,12 @@ class VideoDownloader(Downloader, ABC):
|
|||
error=error,
|
||||
)
|
||||
|
||||
if not ffmpeg_video_complete(video_path):
|
||||
return DownloadResult(
|
||||
success=False,
|
||||
error='Video was incomplete',
|
||||
)
|
||||
|
||||
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)
|
||||
|
|
|
|||
|
|
@ -119,8 +119,11 @@ def validate_video(video: Video, channel_generate_poster: bool):
|
|||
|
||||
if video_path and not video.duration:
|
||||
# Duration was not retrieved during poster generation.
|
||||
if video.ffprobe_json and (video_streams := video.get_streams_by_codec_type('video')):
|
||||
video.duration = float(video_streams[0]['duration'])
|
||||
if video.ffprobe_json:
|
||||
if duration := video.ffprobe_json['format'].get('duration'):
|
||||
video.duration = float(duration)
|
||||
elif video_streams := video.get_streams_by_codec_type('video'):
|
||||
video.duration = float(video_streams[0]['duration'])
|
||||
else:
|
||||
# Slowest method.
|
||||
video.duration = get_video_duration(video_path)
|
||||
|
|
|
|||
|
|
@ -33,6 +33,7 @@ class Video(ModelHelper, Base):
|
|||
source_id = Column(String)
|
||||
upload_date: datetime.datetime = Column(TZDateTime)
|
||||
url = Column(String)
|
||||
validated = Column(Boolean, default=False)
|
||||
view_count = Column(Integer)
|
||||
viewed = Column(TZDateTime)
|
||||
ffprobe_json = deferred(Column(JSON))
|
||||
|
|
@ -86,12 +87,13 @@ class Video(ModelHelper, Base):
|
|||
)
|
||||
return d
|
||||
|
||||
def delete(self):
|
||||
def delete(self, add_to_skip_list: bool = True):
|
||||
"""Remove all files and File records related to this video. Delete this Video record.
|
||||
Add it to it's Channel's skip list."""
|
||||
self.file_group.delete()
|
||||
|
||||
self.add_to_skip_list()
|
||||
if add_to_skip_list:
|
||||
self.add_to_skip_list()
|
||||
session = Session.object_session(self)
|
||||
session.delete(self)
|
||||
|
||||
|
|
@ -340,6 +342,10 @@ class Video(ModelHelper, Base):
|
|||
streams = [i for i in self.ffprobe_json['streams'] if i['codec_type'] == codec_type]
|
||||
return streams
|
||||
|
||||
def detect_is_complete(self):
|
||||
from modules.videos.common import ffmpeg_video_complete
|
||||
return ffmpeg_video_complete(self.video_path)
|
||||
|
||||
|
||||
class Channel(ModelHelper, Base):
|
||||
__tablename__ = 'channel'
|
||||
|
|
|
|||
|
|
@ -123,9 +123,10 @@ def test_generate_video_poster(video_file):
|
|||
A poster can be generated from a video file.
|
||||
"""
|
||||
poster_path = video_file.with_suffix('.jpg')
|
||||
generate_video_poster(video_file)
|
||||
_, duration = generate_video_poster(video_file)
|
||||
assert poster_path.is_file(), f'{poster_path} was not created!'
|
||||
assert poster_path.stat().st_size > 0
|
||||
assert duration == 5
|
||||
|
||||
|
||||
def test_import_channel_downloads(test_session, channel_factory, test_channels_config):
|
||||
|
|
|
|||
|
|
@ -319,7 +319,7 @@ def test_channel_download_no_download(test_session, video_download_manager, simp
|
|||
@pytest.mark.asyncio
|
||||
async def test_video_download(test_session, test_directory, simple_channel, video_download_manager,
|
||||
mock_video_process_runner, image_file):
|
||||
"""A video download is performed, files are associated."""
|
||||
"""A video download is performed, files are grouped."""
|
||||
simple_channel.source_id = example_video_json['channel_id']
|
||||
simple_channel.directory = test_directory / 'videos/channel name'
|
||||
simple_channel.directory.mkdir(parents=True)
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue