Creating Video.ffprobe_json column which stores ffprobe information about the video file. Creating find_corrupt_videos.py script which automatically re-downloads videos which do not have both video and audio streams.

This commit is contained in:
Roland 2023-07-27 15:53:47 -06:00
parent 097c3143e1
commit 36083200e6
No known key found for this signature in database
GPG key ID: 9D6DBD3ACF11AB93
39 changed files with 598 additions and 172 deletions

View file

@ -11,11 +11,11 @@ from wrolpi.common import logger, register_modeler, register_refresh_cleanup, li
from wrolpi.db import optional_session, get_db_session
from wrolpi.downloader import Downloader, Download, DownloadResult
from wrolpi.errors import UnrecoverableDownloadError
from .errors import InvalidArchive
from wrolpi.files.models import FileGroup
from wrolpi.vars import PYTEST
from . import lib
from .api import bp # noqa
from .errors import InvalidArchive
from .lib import is_singlefile_file, get_title_from_html
from .models import Archive, Domain
@ -193,34 +193,6 @@ async def archive_modeler():
@register_refresh_cleanup
@limit_concurrent(1)
def archive_cleanup():
# Process all Archives that have not been validated. Delete any that no longer exist, or are not real Archives.
# Validate all other Archives.
logger.info('Searching for invalid Archives')
offset = 0
limit = 100
while True:
with get_db_session(commit=True) as session:
archives: List[Archive] = session.query(Archive).order_by(Archive.id).limit(limit).offset(offset)
processed = 0
deleted = 0
for archive in archives:
processed += 1
singlefile_path = archive.singlefile_path
if not singlefile_path:
archive.file_group.model = None
session.delete(archive)
deleted += 1
continue
if not lib.is_singlefile_file(singlefile_path):
# Archive is not a real archive.
archive.singlefile_file.model = None
session.delete(archive)
deleted += 1
if processed < limit:
# Validated all archives.
break
offset += (limit - deleted)
with get_db_session(commit=True) as session:
# Remove any Domains without any Archives.
domain_ids = [i[0] for i in session.execute('SELECT DISTINCT domain_id FROM archive') if i[0]]

View file

@ -4,6 +4,7 @@ from http import HTTPStatus
from sanic import response, Request
from sanic_ext import validate
from sanic_ext.extensions.openapi import openapi
from sanic_ext.extensions.openapi.definitions import Response
from wrolpi.common import logger, wrol_mode_check, api_param_limiter
from wrolpi.errors import ValidationError
@ -43,7 +44,9 @@ async def delete_archive(_: Request, archive_ids: str):
@bp.get('/domains')
async def fetch_domains(_: Request):
@openapi.summary('Get a list of all Domains and their Archive statistics')
@openapi.response(200, schema.GetDomainsResponse, "The list of domains")
async def get_domains(_: Request):
domains = lib.get_domains()
return json_response({'domains': domains, 'totals': {'domains': len(domains)}})

View file

@ -1,6 +1,7 @@
import datetime
import json
import pathlib
from typing import List
from uuid import uuid4
import pytest
@ -28,10 +29,12 @@ def archive_factory(test_session, archive_directory, make_files_structure):
now = time_generator()
def _(domain: str = None, url: str = None, title: str = 'NA', contents: str = None,
singlefile_contents: str = None) -> Archive:
singlefile_contents: str = None, tag_names: List[str] = None) -> Archive:
if domain:
assert '/' not in domain
tag_names = tag_names or list()
title = title or str(uuid4())
domain_dir = domain or title
domain_dir = archive_directory / domain_dir
@ -77,6 +80,9 @@ def archive_factory(test_session, archive_directory, make_files_structure):
archive.domain = domain
archive.validate()
for tag_name in tag_names:
archive.add_tag(tag_name)
return archive
return _

View file

@ -20,7 +20,6 @@ from wrolpi.common import get_media_directory, logger, extract_domain, chdir, es
from wrolpi.dates import now, Seconds
from wrolpi.db import get_db_session, get_db_curs, optional_session
from wrolpi.errors import UnknownArchive, InvalidOrderBy
from wrolpi.files.lib import handle_file_group_search_results
from wrolpi.tags import tag_names_to_file_group_sub_select
from wrolpi.vars import DOCKERIZED, PYTEST
@ -356,14 +355,15 @@ def is_singlefile_file(path: pathlib.Path) -> bool:
def get_domains():
with get_db_curs() as curs:
stmt = '''
SELECT domains.domain AS domain, COUNT(a.id) AS url_count
SELECT domains.domain AS domain, COUNT(a.id) AS url_count, SUM(fg.size)::BIGINT AS size
FROM domains
LEFT JOIN archive a on domains.id = a.domain_id
LEFT JOIN archive a on domains.id = a.domain_id
LEFT JOIN file_group fg on fg.id = a.file_group_id
GROUP BY domains.domain
ORDER BY domains.domain
'''
curs.execute(stmt)
domains = list(map(dict, curs.fetchall()))
domains = [dict(i) for i in curs.fetchall()]
return domains
@ -421,6 +421,7 @@ def search_archives(search_str: str, domain: str, limit: int, offset: int, order
tags_stmt, params_ = tag_names_to_file_group_sub_select(tag_names)
params.update(params_)
wheres.append(f'fg.id = ANY({tags_stmt})')
joins = ['LEFT JOIN file_group fg ON fg.id = a.file_group_id']
if search_str and headline:
headline = ''',
@ -455,6 +456,7 @@ def search_archives(search_str: str, domain: str, limit: int, offset: int, order
'''.strip()
logger.debug(stmt, params)
from wrolpi.files.lib import handle_file_group_search_results
results, total = handle_file_group_search_results(stmt, params)
return results, total

View file

@ -11,11 +11,11 @@ from sqlalchemy.orm.collections import InstrumentedList
from wrolpi.common import ModelHelper, Base, logger
from wrolpi.dates import TZDateTime
from modules.archive import InvalidArchive
from wrolpi.files.models import FileGroup
from wrolpi.media_path import MediaPathType
from wrolpi.tags import Tag, TagFile
from wrolpi.vars import PYTEST
from .errors import InvalidArchive
logger = logger.getChild(__name__)

View file

@ -19,8 +19,14 @@ class ArchiveDict:
@dataclass
class DomainDict:
id: int
domain: str
url_count: int
size: int
@dataclass
class GetDomainsResponse:
domains: List[DomainDict]
@dataclass

View file

@ -1,6 +1,8 @@
import json
from http import HTTPStatus
import pytest
from modules.archive import lib
@ -79,6 +81,26 @@ def test_archives_search(test_session, archive_directory, archive_factory, test_
assert response.status_code == HTTPStatus.BAD_REQUEST
@pytest.mark.asyncio
async def test_search_archive_tags(test_session, test_async_client, archive_factory, tag_factory):
"""Tagged Archives can be searched."""
tag = tag_factory()
archive_factory(domain='example.com', tag_names=[tag.name, ])
test_session.commit()
content = {'search_str': '', 'domain': 'example.com', 'tag_names': [tag.name, ]}
request, response = await test_async_client.post('/api/archive/search', content=json.dumps(content))
assert response.status_code == HTTPStatus.OK
assert response.json['file_groups']
assert response.json['totals']['file_groups'] == 1
content = {'search_str': '', 'domain': 'example.com', 'tag_names': ['does not exist', ]}
request, response = await test_async_client.post('/api/archive/search', content=json.dumps(content))
assert response.status_code == HTTPStatus.OK
assert response.json['file_groups'] == []
assert response.json['totals']['file_groups'] == 0
def test_archives_search_headline(test_session, archive_directory, archive_factory, test_client):
"""Headlines can be requested."""
archive_factory('example.com', 'https://example.com/one', 'my archive', 'foo bar qux')
@ -179,6 +201,7 @@ def test_archive_and_domain_crud(test_session, test_client, archive_factory):
request, response = test_client.get(f'/api/archive/domains')
assert response.status_code == HTTPStatus.OK
assert response.json['domains'][0]['domain'] == 'example.com'
assert response.json['domains'][0]['size'] == 116
# Deleting works.
request, response = test_client.delete(f'/api/archive/{archive1.id}')

View file

@ -12,7 +12,7 @@ from modules.archive import lib
from modules.archive.lib import get_or_create_domain, get_new_archive_files, delete_archives, do_archive, get_domains
from modules.archive.models import Archive, Domain
from wrolpi.db import get_db_session
from wrolpi.files.lib import refresh_files
from wrolpi.files import lib as files_lib
from wrolpi.files.models import FileGroup
from wrolpi.root_api import CustomJSONEncoder
from wrolpi.test.common import skip_circleci
@ -94,7 +94,7 @@ async def test_archive_title(test_session, archive_factory, singlefile_contents_
test_session.query(FileGroup).delete()
test_session.commit()
await refresh_files()
await files_lib.refresh_files()
assert test_session.query(FileGroup).count() == 1
assert test_session.query(Archive).count() == 1
@ -108,7 +108,7 @@ async def test_archive_title(test_session, archive_factory, singlefile_contents_
# Delete JSON file.
archive1.readability_json_path.unlink()
test_session.delete(archive1)
await refresh_files()
await files_lib.refresh_files()
archive1: Archive = test_session.query(Archive).one()
assert archive1.url == 'https://example.com/singlefile-url'
@ -117,7 +117,7 @@ async def test_archive_title(test_session, archive_factory, singlefile_contents_
# Clear out title and URL from Singlefile.
archive1.singlefile_path.write_text(singlefile_contents_factory('', ''))
test_session.delete(archive1)
await refresh_files()
await files_lib.refresh_files()
# No title/URL could be found.
archive1: Archive = test_session.query(Archive).one()
@ -207,7 +207,7 @@ async def test_fills_contents_with_refresh(test_client, test_session, archive_fa
assert not archive4.file_group.d_text
# Fill the contents.
await refresh_files()
await files_lib.refresh_files()
# The archives will be renamed with their title.
archive1, archive2, archive3, archive4 = test_session.query(Archive).order_by(Archive.id)
assert not archive4.file_group.d_text
@ -536,7 +536,7 @@ async def test_refresh_archives_index(test_session, test_directory, test_client,
'archive/example.com/2021-10-05-16-20-10_NA.readability.html': '<html></html>',
})
await refresh_files()
await files_lib.refresh_files()
archive: Archive = test_session.query(Archive).one()
assert archive.singlefile_path == singlefile
@ -545,32 +545,22 @@ async def test_refresh_archives_index(test_session, test_directory, test_client,
assert archive.file_group.indexed is True
def test_refresh_archives_invalid_file(test_session, test_directory, test_client, make_files_structure):
"""
Invalid Archives should be removed during refresh.
"""
*_, bogus_path = make_files_structure({
'2022-09-04-16-20-11_The Title.html': '<html></html>',
@pytest.mark.asyncio
async def test_refresh_archives_deleted_singlefile(test_session, make_files_structure, singlefile_contents_factory):
"""Removing a Singlefile file from a FileGroup makes that group no longer an Archive."""
singlefile, readability = make_files_structure({
'2022-09-04-16-20-11_The Title.html': singlefile_contents_factory(),
'2022-09-04-16-20-11_The Title.readability.json': '{"url": "https://example.com"}',
'bogus file': None,
})
test_client.post('/api/files/refresh')
assert test_session.query(FileGroup).count() == 2 # One bogus file, one archive group.
assert test_session.query(Archive).count() == 1 # Only one real archive.
await files_lib.refresh_files()
assert test_session.query(FileGroup).one().model == 'archive'
assert test_session.query(Archive).count() == 1
# Create an invalid Archive, it should be removed during refresh.
bogus_file: FileGroup = test_session.query(FileGroup).filter_by(primary_path=bogus_path).one()
bogus_file.model = 'archive'
archive = Archive(file_group=bogus_file)
test_session.add(archive)
test_session.commit()
assert test_session.query(FileGroup).count() == 2
assert test_session.query(Archive).count() == 2
test_client.post('/api/files/refresh')
assert test_session.query(FileGroup).count() == 2, 'More files in DB than we created'
assert test_session.query(Archive).count() == 1, 'The bogus Archive was not removed'
assert bogus_file.model is None, 'Model was not removed'
# Remove singlefile, FileGroup is no longer an Archive.
singlefile.unlink()
await files_lib.refresh_files()
assert test_session.query(FileGroup).one().model is None
assert test_session.query(Archive).count() == 0
@pytest.mark.parametrize(

View file

@ -37,6 +37,9 @@ async def video_modeler():
session.add(video)
session.flush([video])
video_id = video.id
# Extract ffprobe data.
await video.get_ffprobe_json()
# Validate and index subtitles.
video.validate()
except Exception as e:
if PYTEST:

View file

@ -1,3 +1,4 @@
import asyncio
import json
import pathlib
import tempfile
@ -275,16 +276,14 @@ async def test_channel_download_requires_refresh(test_session, download_channel,
vid = video_factory(channel_id=download_channel.id, with_video_file=True, with_poster_ext='jpg')
vid.url = 'https://example.com/1'
d = download_channel.get_download()
d.next_download = None
test_session.commit()
assert not d.next_download
def assert_refreshed(expected: bool):
channel: Channel = test_session.query(Channel).one()
assert channel.refreshed == expected
if expected:
assert channel.info_json
else:
assert not channel.info_json
assert bool(channel.info_json) == expected
assert_refreshed(False)
test_session.commit()
@ -307,6 +306,8 @@ async def test_channel_download_requires_refresh(test_session, download_channel,
'channel_id': 'the id', 'id': 'the id'}
await video_download_manager.do_downloads()
await video_download_manager.wait_for_all_downloads()
# Give time for background tasks to finish. :(
await asyncio.sleep(1)
# Channel was refreshed before downloading videos.
assert_refreshed(True)

View file

@ -1,13 +1,15 @@
import asyncio
import json
import os
import pathlib
import re
import shlex
import subprocess
import tempfile
from datetime import timedelta
from decimal import Decimal
from pathlib import Path
from typing import Optional, Tuple
from typing import Optional, Tuple, Union
import PIL
from PIL import Image
@ -165,6 +167,50 @@ def is_valid_poster(poster_path: Path) -> bool:
return False
async def ffprobe_json(video_path: Union[Path, str]) -> dict:
"""Extract video file metadata using ffprobe.
>>> ffprobe_json('video')
{
'chapters': [],
'format': {},
'streams': [
{},
],
}
"""
cmd = f'{FFPROBE_BIN}' \
f' -print_format json' \
f' -loglevel quiet' \
f' -show_streams' \
f' -show_format' \
f' -show_chapters' \
f' {shlex.quote(str(video_path.absolute()))}'
try:
proc = await asyncio.create_subprocess_shell(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdout, stderr = await proc.communicate()
except Exception as e:
logger.error(f'Failed to run ffprobe json', exc_info=e)
raise
if proc.returncode != 0:
raise RuntimeError(f'Got non-zero exit code: {proc.returncode}')
try:
content = json.loads(stdout.decode().strip())
except Exception as e:
logger.debug(stdout.decode())
logger.error(f'Failed to load ffprobe json', exc_info=e)
raise
if content == dict():
# Data is empty, video may be corrupt.
raise RuntimeError('ffprobe data was empty')
return content
def get_video_duration(video_path: Path) -> int:
"""Get the duration of a video in seconds. Do this using ffprobe."""
if not isinstance(video_path, Path):

View file

@ -19,11 +19,11 @@ from wrolpi.db import get_db_session
from wrolpi.db import optional_session
from wrolpi.downloader import Downloader, Download, DownloadResult
from wrolpi.errors import UnrecoverableDownloadError
from .errors import UnknownChannel, ChannelURLEmpty
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 .errors import UnknownChannel, ChannelURLEmpty
from .lib import get_downloader_config
from .models import Video, Channel
from .schema import ChannelPostRequest
@ -311,6 +311,20 @@ class VideoDownloader(Downloader, ABC):
if name not in existing_names:
video.add_tag(name)
# Check that video is valid.
await video.get_ffprobe_json()
if not video.get_streams_by_codec_type('video'):
return DownloadResult(
success=False,
error='Video was downloaded but did not contain video stream',
)
if not video.get_streams_by_codec_type('audio'):
return DownloadResult(
success=False,
error='Video was downloaded but did not contain audio stream',
)
session.commit()
except UnrecoverableDownloadError:
raise
except yt_dlp.utils.UnsupportedError as e:

View file

@ -119,7 +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.
video.duration = get_video_duration(video_path)
if video.ffprobe_json and (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)
if video_path and not video.caption_paths and video.file_group.d_text and not EXTRACT_SUBTITLES:
# Caption file was deleted, clear out old captions.

View file

@ -8,12 +8,12 @@ from sqlalchemy import Column, Integer, String, Boolean, JSON, Date, ARRAY, Fore
from sqlalchemy.orm import relationship, Session, deferred
from sqlalchemy.orm.collections import InstrumentedList
from modules.videos.errors import UnknownVideo
from wrolpi.captions import read_captions
from wrolpi.common import Base, ModelHelper, logger, get_media_directory, background_task
from wrolpi.dates import now, TZDateTime
from wrolpi.db import get_db_curs, get_db_session, optional_session
from wrolpi.downloader import Download, download_manager
from modules.videos.errors import UnknownVideo
from wrolpi.files.lib import refresh_files, split_path_stem_and_suffix
from wrolpi.files.models import FileGroup
from wrolpi.media_path import MediaPathType
@ -35,6 +35,7 @@ class Video(ModelHelper, Base):
url = Column(String)
view_count = Column(Integer)
viewed = Column(TZDateTime)
ffprobe_json = deferred(Column(JSON))
channel_id = Column(Integer, ForeignKey('channel.id'))
channel = relationship('Channel', primaryjoin='Video.channel_id==Channel.id', back_populates='videos')
@ -44,7 +45,7 @@ class Video(ModelHelper, Base):
def __repr__(self):
v = None
if self.video_path:
v = self.video_path.relative_to(get_media_directory())
v = repr(str(self.video_path.relative_to(get_media_directory())))
return f'<Video id={self.id} title={repr(self.file_group.title)} path={v} channel={self.channel_id} ' \
f'source_id={repr(self.source_id)}>'
@ -55,12 +56,20 @@ class Video(ModelHelper, Base):
if self.channel:
channel = dict(id=self.channel.id, name=self.channel.name)
codec_names = []
codec_types = []
if self.ffprobe_json:
codec_names = [i['codec_name'] for i in self.ffprobe_json['streams']]
codec_types = [i['codec_type'] for i in self.ffprobe_json['streams']]
# Put live data in "video" instead of "data" to avoid confusion on the frontend.
d['video'] = dict(
caption=self.file_group.d_text,
caption_files=self.caption_files,
channel=channel,
channel_id=self.channel_id,
codec_names=codec_names,
codec_types=codec_types,
description=self.file_group.c_text or self.get_video_description(),
duration=self.duration,
id=self.id,
@ -198,6 +207,8 @@ class Video(ModelHelper, Base):
validate_video(self, self.channel.generate_posters if self.channel else False)
except Exception as e:
logger.warning(f'Failed to validate video {self}', exc_info=e)
if PYTEST:
raise
self.file_group.model = Video.__tablename__
self.file_group.a_text = self.file_group.title
@ -289,6 +300,46 @@ class Video(ModelHelper, Base):
tag = Tag.find_by_name(tag_or_tag_name) if isinstance(tag_or_tag_name, str) else tag_or_tag_name
return self.file_group.add_tag(tag)
async def get_ffprobe_json(self) -> dict:
"""Return the ffprobe json object if previously stored.
Runs ffprobe if this data does not yet exist."""
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)
self.flush()
return self.ffprobe_json
def get_streams_by_codec_name(self, codec_name: str) -> List[dict]:
"""Return all data about all streams which match the codec_name.
>>> video = Video()
>>> video.get_streams_by_codec_name('h264')
[ {'codec_name': 'h264', ...} ]
"""
if not self.ffprobe_json:
raise RuntimeError(f'ffprobe data has not been extracted, call Video.get_ffprobe_json().')
streams = [i for i in self.ffprobe_json['streams'] if i['codec_name'] == codec_name]
return streams
def get_streams_by_codec_type(self, codec_type: str) -> List[dict]:
"""Return all data about all streams which match the codec_type.
>>> video = Video()
>>> video.get_streams_by_codec_type('video')
[ {'codec_type': 'video', ...} ]
"""
if not self.ffprobe_json:
raise RuntimeError(f'ffprobe data has not been extracted, call Video.get_ffprobe_json().')
streams = [i for i in self.ffprobe_json['streams'] if i['codec_type'] == codec_type]
return streams
class Channel(ModelHelper, Base):
__tablename__ = 'channel'

View file

@ -9,6 +9,7 @@ from PIL import Image
from modules.videos.models import Channel, Video
from wrolpi.common import get_absolute_media_path
from wrolpi.downloader import Download, DownloadFrequency
from wrolpi.files import lib as files_lib
from wrolpi.vars import PROJECT_DIR
from .. import common
from ..common import convert_image, update_view_counts, get_video_duration, generate_video_poster, is_valid_poster
@ -204,3 +205,28 @@ def test_check_for_video_corruption(video_file, test_directory):
assert common.check_for_video_corruption(video_file) is True
mock_subprocess.run().stderr = b'Some stderr is fine'
assert common.check_for_video_corruption(video_file) is False
@pytest.mark.asyncio
async def test_ffprobe_json(video_file, corrupted_video_file):
content = await common.ffprobe_json(video_file)
assert not content['chapters']
assert content['format']['duration'] == '5.312000'
assert content['format']['size'] == '1056318'
assert content['streams']
assert content['streams'][0]['codec_name'] == 'h264'
with pytest.raises(RuntimeError):
await common.ffprobe_json(corrupted_video_file)
@pytest.mark.asyncio
async def test_video_ffprobe_json(test_session, video_file):
"""ffprobe data is extracted when a video is modeled."""
with mock.patch('modules.videos.lib.get_video_duration') as mock_get_video_duration:
mock_get_video_duration.side_effect = Exception('duration should be from ffprobe json')
await files_lib.refresh_files()
video = test_session.query(Video).one()
assert video.ffprobe_json
assert video.duration

View file

@ -366,6 +366,8 @@ async def test_download_result(test_session, test_directory, video_download_mana
mock_prepare_filename.return_value = [video_file, {'id': 'foo'}]
video_download_manager.create_download('https://example.com', video_downloader.name)
await video_download_manager.wait_for_all_downloads()
# Sleep to allow background tasks to finish.
await asyncio.sleep(1)
download: Download = test_session.query(Download).one()
assert download.url == 'https://example.com'

View file

@ -0,0 +1,15 @@
import pytest
@pytest.mark.asyncio()
async def test_ffprobe_stream_methods(simple_video):
"""ffprobe data can be used to get data about specific streams in the video file."""
assert await simple_video.get_ffprobe_json()
assert simple_video.get_streams_by_codec_type('video')
assert simple_video.get_streams_by_codec_type('audio')
assert simple_video.get_streams_by_codec_type('subtitle')
assert simple_video.get_streams_by_codec_name('h264')
assert simple_video.get_streams_by_codec_name('aac')
assert simple_video.get_streams_by_codec_name('mov_text')