Handling new issue with youtube caption file names. Adding QR Code calculator.

This commit is contained in:
Roland 2025-02-07 11:44:17 -07:00
parent 506a349276
commit 15f6e7ed5c
No known key found for this signature in database
GPG key ID: 1BA620CE6C9A4680
15 changed files with 191 additions and 20 deletions

View file

@ -7,6 +7,7 @@ import {ElectricalCalculators} from "./calculators/ElectricalCalculators";
import {DipoleAntennaCalculator} from "./calculators/HamCalculators";
import {Link} from "react-router-dom";
import {RatioCalculators} from "./calculators/RatioCalculator";
import {QRCodeCalculator} from "./calculators/QRCodeCalculator";
export const useCalculators = () => {
const [calc, setCalc] = useCalcQuery();
@ -16,6 +17,7 @@ export const useCalculators = () => {
{key: 'electrical', icon: 'lightning', button: 'Electrical', contents: <ElectricalCalculators/>},
{key: 'antenna', icon: 'signal', button: 'Antenna', contents: <DipoleAntennaCalculator/>},
{key: 'temperature', icon: 'thermometer', button: 'Temperature', contents: <TemperatureCalculator/>},
{key: 'qrCode', icon: 'qrcode', button: 'QR Code', contents: <QRCodeCalculator/>},
];
const activeCalculator = calc ? calculators.find(i => i.key === calc) : null;

View file

@ -0,0 +1,50 @@
import Grid from "semantic-ui-react/dist/commonjs/collections/Grid";
import React from "react";
import {Header} from "../Theme";
import QRCode from "react-qr-code";
import {Input} from "semantic-ui-react";
import {Media} from "../../contexts/contexts";
export function QRCodeCalculator() {
const [value, setValue] = React.useState('');
return <Grid>
<Grid.Row>
<Grid.Column>
<Header as='h1'>QR Code Calculator</Header>
</Grid.Column>
</Grid.Row>
<Grid.Row>
<Grid.Column>
<Input fluid value={value} onChange={e => setValue(e.target.value)} placeholder='Enter link, etc.'/>
</Grid.Column>
</Grid.Row>
<Grid.Row>
<Grid.Column>
<Media at='mobile'>
<div style={{
height: "auto",
margin: "0 auto",
width: '332px',
background: 'white',
padding: '16px'
}}>
<QRCode value={value} size={300}/>
</div>
</Media>
<Media greaterThanOrEqual='tablet'>
<div style={{
height: "auto",
margin: "0 auto",
maxWidth: '632px',
width: "100%",
background: 'white',
padding: '16px'
}}>
<QRCode value={value} size={600}/>
</div>
</Media>
</Grid.Column>
</Grid.Row>
</Grid>
}

View file

@ -1185,6 +1185,7 @@ export const useUploadFile = () => {
formData.append('filename', file.path);
formData.append('totalChunks', totalChunks.toString());
formData.append('destination', destination);
formData.append('mkdir', 'true');
if (overwrite) {
formData.append('overwrite', 'true');
}

View file

@ -466,6 +466,8 @@ class VideoDownloader(Downloader, ABC):
video_paths = glob_shared_stem(video_path)
# Delete any leftover part files now that we have verified the video is complete.
video_paths = self._delete_part_files(video_path, video_paths)
# Rename any special files that do not match the stem.
video_paths = self.normalize_video_file_names(video_path, video_paths)
# Create the Video record.
video = Video.from_paths(session, *video_paths)
video.source_id = entry['id']
@ -726,6 +728,28 @@ class VideoDownloader(Downloader, ABC):
return files
@staticmethod
def normalize_video_file_names(video_path: pathlib.Path, files: List[pathlib.Path]) -> List[pathlib.Path]:
"""Video files can have unpredictable names, rename any video files as necessary to make them share the same
stem."""
video_stem, _ = split_path_stem_and_suffix(video_path.name)
new_files = []
for file in files:
suffix = file.name[len(video_stem):]
if suffix.endswith('.vtt'):
_, normal_suffix = split_path_stem_and_suffix(file.name)
if suffix != normal_suffix:
# Video captions file has extra characters in the suffix from yt-dlp.
# Example: .en-uYU-mmqFLq8.vtt -> .en.vtt
lang, _, suffix = VTT_SUFFIX_PARSER.match(suffix.strip()).groups()
suffix = f'.{lang}.{suffix}'
file = file.rename(video_path.with_suffix(suffix))
new_files.append(file)
return new_files
VTT_SUFFIX_PARSER = re.compile(r'^\.([a-z]{2,3})-(.+?)\.(vtt|srt)$', re.IGNORECASE)
VIDEO_FORMAT_PARSER = re.compile(r'^.+?\.f\d{2,4}')

View file

@ -667,8 +667,10 @@ async def get_statistics():
return ret
NAME_PARSER = re.compile(r'(.*?)_((?:\d+?)|(?:NA))_(?:(.{5,25})_)?(.*)\.'
r'(jpg|webp|flv|mp4|part|info\.json|description|webm|..\.srt|..\.vtt)')
NAME_PARSER = re.compile(
r'(?:(.*?)_)?((?:\d+?)|(?:NA))_(?:(.{5,25})_)?(.*)'
r'\.(jpg|webp|flv|mp4|part|info\.json|description|webm|..\.srt|..\.vtt)', # the file suffix
re.IGNORECASE)
def parse_video_file_name(video_path: pathlib.Path) -> \
@ -676,7 +678,14 @@ def parse_video_file_name(video_path: pathlib.Path) -> \
"""
A Video's file name can have data in it, this attempts to extract what may be there.
Example: {channel_name}_{published_datetime}_{source_id}_title{ext}
{published_date} is assumed to always be %Y%m%d
Examples:
NA_{published_date}_{source_id}_{title}{ext}
{channel_name}_NA_{source_id}_{title}{ext}
{channel_name}_{published_date}_{source_id}_{title}{ext} # Typical name format from WROLPi.
{published_date}_{title}{ext}
{title}{ext}
"""
video_str = str(video_path)
if match := NAME_PARSER.match(video_str):
@ -692,8 +701,8 @@ def parse_video_file_name(video_path: pathlib.Path) -> \
return channel, date, source_id, title
# Return the stem as a last resort
title = split_path_stem_and_suffix(video_path)[0].strip()
return None, None, None, title
title, _ = split_path_stem_and_suffix(video_path)
return None, None, None, title.strip()
def find_orphaned_video_files(directory: pathlib.Path) -> Generator[pathlib.Path, None, None]:

View file

@ -516,3 +516,33 @@ def test_preview_filename(test_directory, fake_now):
with pytest.raises(RuntimeError):
preview_filename('%(upload_date)s_%(title)s.asdf')
def test_normalize_video_file_names(test_directory, video_download_manager):
"""VideoDownloader renames caption files that do not share the video file's stem."""
downloader = VideoDownloader()
mp4 = test_directory / 'video.mp4'
info_json = test_directory / 'video.info.json'
# Minimal video files.
vtt = test_directory / 'video.vtt'
assert set(downloader.normalize_video_file_names(mp4, [mp4, vtt, info_json])) == {mp4, vtt, info_json}
# Normal video files.
vtt = test_directory / 'video.en.vtt'
assert set(downloader.normalize_video_file_names(mp4, [mp4, vtt, info_json])) == {mp4, vtt, info_json}
# Rare -auto file.
vtt = test_directory / 'video.en-auto.vtt'
assert set(downloader.normalize_video_file_names(mp4, [mp4, vtt, info_json])) == {mp4, vtt, info_json}
# Extra characters get removed from the vtt file.
vtt = test_directory / 'video.en-uYU-mmqFLq8.vtt'
vtt.touch() # must exist so it can be renamed.
assert set(downloader.normalize_video_file_names(mp4, [mp4, vtt, info_json])) == {
mp4,
(test_directory / 'video.en.vtt'),
info_json,
}
assert not vtt.exists()

View file

@ -18,12 +18,15 @@ from wrolpi.vars import PROJECT_DIR
@pytest.mark.parametrize('file_name,expected', [
('channel_20000101_12345678910_ some title.mp4', ('channel', '20000101', '12345678910', 'some title')),
('channel name_NA_12345678910_ some title.mp4', ('channel name', None, '12345678910', 'some title')),
('channel name_NA_12345678910_ some title.MP4', ('channel name', None, '12345678910', 'some title')),
('20000101 foo.mp4', (None, None, None, '20000101 foo')),
('20000101foo.mp4', (None, None, None, '20000101foo')),
('something 20000101 foo.mp4', (None, None, None, 'something 20000101 foo')),
('something_20000101_foo.mp4', ('something', '20000101', None, 'foo')),
('foo .mp4', (None, None, None, 'foo')), # Has trailing whitespace.
('NA_20000303_vp91w5_Bob&apos;s Pancakes.mp4', (None, '20000303', 'vp91w5', 'Bob&apos;s Pancakes')),
('NA_20000303_Bob&apos;s Pancakes.mp4', (None, '20000303', None, 'Bob&apos;s Pancakes')),
('20000303_Bob&apos;s Pancakes.mp4', (None, '20000303', None, 'Bob&apos;s Pancakes')),
('NA_NA_vp91w5_Bob&apos;s Pancakes.mp4', (None, None, 'vp91w5', 'Bob&apos;s Pancakes')),
('Learning Self-Reliance_20170529_p_MzsCFkUPU_Beekeeping 2017 Part 6 - Merging Hives.mp4',
('Learning Self-Reliance', '20170529', 'p_MzsCFkUPU', 'Beekeeping 2017 Part 6 - Merging Hives')),

View file

@ -1,6 +1,7 @@
import asyncio
import json
import logging
from time import time
from asyncio import CancelledError
from datetime import datetime, timezone, date
from decimal import Decimal
@ -153,7 +154,7 @@ def perpetual_signal(event: str = None, sleep: int | float = 1):
async def worker(*args, **kwargs):
logger.trace(f'perpetual_signal {event_}')
cancelled = False
start = datetime.now()
start = time()
try:
await func(*args, **kwargs)
except CancelledError:
@ -163,7 +164,7 @@ def perpetual_signal(event: str = None, sleep: int | float = 1):
logger.error(f'Perpetual worker {event_} had error', exc_info=e)
finally:
if logger.isEnabledFor(TRACE_LEVEL):
elapsed = (datetime.now() - start).total_seconds()
elapsed = int(time() - start)
logger.trace(f'perpetual_signal {event_} took {elapsed} seconds')
if not cancelled:
await asyncio.sleep(sleep)

View file

@ -101,7 +101,7 @@ def test_session() -> Session:
@pytest.fixture(autouse=True)
def test_debug_logger(request):
"""Tests use debug logging by default. Use pytest's verbosity level if set."""
"""The tests use debug logging by default. Use pytest's verbosity level if set."""
level = logging.INFO
verbose = request.config.option.verbose
if verbose == 2:

View file

@ -345,13 +345,15 @@ class Downloader:
async def get_meta4_contents(url: str) -> bytes | None:
try:
meta4_url = f'{url}.meta4'
async with aiohttp_get(meta4_url, timeout=5) as response:
async with aiohttp_get(meta4_url, timeout=60) as response:
if response.status == HTTPStatus.OK:
contents = await response.content.read()
try:
root = ET.fromstring(contents)
if root.tag == '{urn:ietf:params:xml:ns:metalink4}metalink':
return contents
if root.tag == '{urn:ietf:params:xml:ns:metalink}metalink':
return contents
logger.debug(f'meta4 file was not a metalink file: {meta4_url}')
except Exception as e:
logger.debug(f'Failed to parse XML {meta4_url}', exc_info=e)

View file

@ -7,7 +7,7 @@ from sanic_ext import validate
from sanic_ext.extensions.openapi import openapi
from wrolpi.common import get_media_directory, wrol_mode_check, get_relative_to_media_directory, logger, \
background_task, walk, timer
background_task, walk, timer, TRACE_LEVEL
from wrolpi.errors import InvalidFile, UnknownDirectory, FileUploadFailed, FileConflict
from . import lib, schema
from ..api_utils import json_response, api_app
@ -144,24 +144,32 @@ async def post_search_directories(_, body: schema.DirectoriesSearchRequest):
})
path = get_media_directory() / body.path
if logger.isEnabledFor(TRACE_LEVEL):
logger.trace(f'post_search_directories: {path=}')
try:
matching_directories = lib.get_matching_directories(str(path))
matching_directories = list(map(pathlib.Path, matching_directories))
except FileNotFoundError:
matching_directories = []
if logger.isEnabledFor(TRACE_LEVEL):
logger.trace(f'post_search_directories: {matching_directories=}')
# Search Channels by name.
from modules.videos.channel.lib import search_channels_by_name
channels = await search_channels_by_name(name=body.path)
channel_directories = [dict(path=i.directory, name=i.name) for i in channels]
channel_paths = [i['path'] for i in channel_directories]
if logger.isEnabledFor(TRACE_LEVEL):
logger.trace(f'post_search_directories: {channel_paths=}')
# Search Domains by name.
from modules.archive.lib import search_domains_by_name
domains = await search_domains_by_name(name=body.path)
domain_directories = [dict(path=i.directory, domain=i.domain) for i in domains]
domain_paths = [i['path'] for i in domain_directories]
if logger.isEnabledFor(TRACE_LEVEL):
logger.trace(f'post_search_directories: {domain_paths=}')
# Get all Directory that match but do not contain the above directories.
excluded = [str(i) for i in channel_paths + domain_paths + matching_directories]
@ -172,6 +180,10 @@ async def post_search_directories(_, body: schema.DirectoriesSearchRequest):
directories.extend([{'path': i, 'name': i.name} for i in matching_directories])
directories = list(sorted(directories, key=lambda i: i['path']))[:20]
if logger.isEnabledFor(TRACE_LEVEL):
logger.trace(f'post_search_directories: {excluded=}')
logger.trace(f'post_search_directories: {directories=}')
body = {
'is_dir': path.is_dir(),
'directories': directories,
@ -316,6 +328,13 @@ async def post_upload(request: Request):
Will not overwrite an existing file, unless a previous upload did not complete."""
try:
mkdir = request.form['mkdir'][0]
mkdir = True if mkdir.strip().lower() == 'true' else False
except Exception as e:
logger.error('Failed to parse mkdir form data', exc_info=e)
mkdir = False
try:
destination_str = request.form['destination'][0]
except Exception as e:
@ -323,6 +342,8 @@ async def post_upload(request: Request):
raise UnknownDirectory('Must provide destination') from e
destination = get_media_directory() / destination_str
if mkdir:
destination.mkdir(exist_ok=True)
if destination_str.startswith('/') or destination_str.startswith('.') or not destination.is_dir():
msg = f'Destination must be a relative directory that is already in the media directory: {destination}'
raise UnknownDirectory(msg)
@ -351,7 +372,6 @@ async def post_upload(request: Request):
except Exception:
overwrite = False
print(f'{overwrite=} {type(overwrite)=}')
tag_names = request.form.getlist('tagNames')
if tag_names:
if not isinstance(tag_names, list):

View file

@ -297,6 +297,8 @@ EXTRA_SUFFIXES = set()
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}
EXTRA_SUFFIXES |= {f'.{i}-auto.srt' for i in ISO_639_CODES}
EXTRA_SUFFIXES |= {f'.{i}-auto.vtt' for i in ISO_639_CODES}
PART_PARSER = re.compile(r'(.+?)(\.f[\d]{2,3})?(\.info)?(\.\w{3,4})(\.part)', re.IGNORECASE)

View file

@ -305,11 +305,7 @@ class FileGroup(ModelHelper, Base):
@classmethod
def from_paths(cls, session: Session, *paths: pathlib.Path) -> 'FileGroup':
"""Create a new FileGroup which contains the provided file paths."""
from wrolpi.files.lib import get_primary_file, get_mimetype, get_unique_files_by_stem
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: {paths[0]}')
from wrolpi.files.lib import get_primary_file, get_mimetype
existing_groups = session.query(FileGroup).filter(FileGroup.primary_path.in_(list(map(str, paths)))).all()
if len(existing_groups) == 0:

View file

@ -369,12 +369,13 @@ async def test_file_group_tag_by_primary_path(test_session, async_client, test_d
assert test_session.query(TagFile).count() == 0
def test_file_group_tag(test_client):
request, response = test_client.post('/api/files/tag', content=json.dumps(dict(tag_id=1)))
@pytest.mark.asyncio
async def test_file_group_tag(async_client):
request, response = await async_client.post('/api/files/tag', content=json.dumps(dict(tag_id=1)))
assert response.status_code == HTTPStatus.BAD_REQUEST
assert 'file_group_id' in response.json['error']
request, response = test_client.post('/api/files/tag', content=json.dumps(dict(file_group_id=1)))
request, response = await async_client.post('/api/files/tag', content=json.dumps(dict(file_group_id=1)))
assert response.status_code == HTTPStatus.BAD_REQUEST
assert 'tag_id' in response.json['error']
@ -702,6 +703,34 @@ def test_post_upload_text(test_session, test_client, test_directory, make_files_
assert file_group.d_text == 'hello'
@pytest.mark.asyncio
async def test_post_upload_new_directory(test_session, async_client, test_directory, make_files_structure,
make_multipart_form,
tag_factory, video_bytes):
"""User can create a new directory when uploading."""
tag1, tag2 = await tag_factory(), await tag_factory()
forms = [
dict(name='chunkNumber', value='0'),
dict(name='filename', value='video.mp4'),
dict(name='totalChunks', value='1'),
dict(name='destination', value='some new directory'),
dict(name='mkdir', value=True),
dict(name='chunkSize', value=len(video_bytes)),
dict(name='tagNames', value=tag1.name),
dict(name='tagNames', value=tag2.name),
dict(name='chunk', value=video_bytes, filename='chunk'),
]
body = make_multipart_form(forms)
headers = {'Content-Type': 'multipart/form-data; boundary=-----------------------------sanic'}
request, response = await async_client.post('/api/files/upload', content=body, headers=headers)
assert response.status_code == HTTPStatus.OK, response.content.decode()
assert (test_directory / 'some new directory').is_dir()
assert (test_directory / 'some new directory/video.mp4').is_file()
assert (test_directory / 'some new directory/video.mp4').read_bytes() == video_bytes
@pytest.mark.asyncio
async def test_directory_crud(test_session, async_client, test_directory, assert_directories, assert_files):
"""A directory can be created in a subdirectory. Errors are returned if there are conflicts."""

View file

@ -151,6 +151,8 @@ async def test_delete_nested(test_session, make_files_structure):
('foo.en-US.srt', False, ('foo', '.en-US.srt')),
('foo.en-US.vtt', False, ('foo', '.en-US.vtt')),
('foo.en-us.vtt', False, ('foo', '.en-us.vtt')),
('foo.en-AUTO.srt', False, ('foo', '.en-AUTO.srt')),
('foo.en-auto.vtt', False, ('foo', '.en-auto.vtt')),
# Absolute path can be returned.
('/absolute//foo.bar', True, ('/absolute/foo', '.bar')),
# Case is preserved.
@ -371,7 +373,7 @@ async def test_refresh_discover_paths_groups(test_session, make_files_structure,
@pytest.mark.asyncio
async def test_file_group_tag(test_session, make_files_structure, test_directory, tag_factory):
async def test_file_group_tag(test_session, make_files_structure, test_directory, tag_factory, await_switches):
"""A FileGroup can be tagged."""
make_files_structure(['foo.mp4'])
await lib.refresh_discover_paths([test_directory, ], now())