feat: support disable progress bar

This commit is contained in:
acgnhik 2023-03-19 15:26:31 +08:00
parent dba4c50437
commit 4761e59871
9 changed files with 42 additions and 15 deletions

View File

@ -21,5 +21,5 @@ ENV BLREC_DEFAULT_OUT_DIR=/rec
ENV TZ="Asia/Shanghai" ENV TZ="Asia/Shanghai"
EXPOSE 2233 EXPOSE 2233
ENTRYPOINT ["blrec", "--host", "0.0.0.0"] ENTRYPOINT ["blrec", "--host", "0.0.0.0", "--no-progress"]
CMD [] CMD []

View File

@ -23,5 +23,5 @@ ENV BLREC_DEFAULT_OUT_DIR=/rec
ENV TZ="Asia/Shanghai" ENV TZ="Asia/Shanghai"
EXPOSE 2233 EXPOSE 2233
ENTRYPOINT ["blrec", "--host", "0.0.0.0"] ENTRYPOINT ["blrec", "--host", "0.0.0.0", "--no-progress"]
CMD [] CMD []

View File

@ -1,5 +1,6 @@
import logging import logging
import os import os
import sys
from copy import deepcopy from copy import deepcopy
from typing import Optional from typing import Optional
@ -44,6 +45,7 @@ def cli_main(
'--log-dir', '--log-dir',
help='path of directory to store log files (overwrite setting)', help='path of directory to store log files (overwrite setting)',
), ),
progress: bool = typer.Option(True, help='display progress'),
host: str = typer.Option('localhost', help='webapp host bind'), host: str = typer.Option('localhost', help='webapp host bind'),
port: int = typer.Option(2233, help='webapp port bind'), port: int = typer.Option(2233, help='webapp port bind'),
open: bool = typer.Option(False, help='open webapp in default browser'), open: bool = typer.Option(False, help='open webapp in default browser'),
@ -62,6 +64,13 @@ def cli_main(
if log_dir is not None: if log_dir is not None:
os.environ['BLREC_LOG_DIR'] = log_dir os.environ['BLREC_LOG_DIR'] = log_dir
if not sys.stderr.isatty():
progress = False
if progress:
os.environ['BLREC_PROGRESS'] = '1'
else:
os.environ['BLREC_PROGRESS'] = ''
if root_path: if root_path:
if not root_path.startswith('/'): if not root_path.startswith('/'):
root_path = '/' + root_path root_path = '/' + root_path
@ -71,9 +80,11 @@ def cli_main(
if open: if open:
typer.launch(f'http://localhost:{port}') typer.launch(f'http://localhost:{port}')
logging_config = deepcopy(LOGGING_CONFIG) if not progress:
logging_config['handlers']['default']['stream'] = TqdmOutputStream logging_config = LOGGING_CONFIG
logging_config['handlers']['access']['stream'] = TqdmOutputStream else:
logging_config = deepcopy(LOGGING_CONFIG)
logging_config['handlers']['default']['stream'] = TqdmOutputStream()
uvicorn.run( uvicorn.run(
'blrec.web:app', 'blrec.web:app',

View File

@ -1,6 +1,7 @@
from __future__ import annotations from __future__ import annotations
import logging import logging
import os
from typing import Optional from typing import Optional
from reactivex import Observable, abc from reactivex import Observable, abc
@ -13,6 +14,8 @@ from blrec.flv.operators.typing import FLVStream, FLVStreamItem
__all__ = ('ProgressBar',) __all__ = ('ProgressBar',)
DISPLAY_PROGRESS = bool(os.environ.get('BLREC_PROGRESS'))
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
@ -41,6 +44,7 @@ class ProgressBar:
unit_scale=True, unit_scale=True,
unit_divisor=1024, unit_divisor=1024,
postfix=self._make_pbar_postfix(), postfix=self._make_pbar_postfix(),
disable=not DISPLAY_PROGRESS,
) )
def on_next(item: FLVStreamItem) -> None: def on_next(item: FLVStreamItem) -> None:

View File

@ -23,7 +23,7 @@ class AnalysingProgress:
def analyse_metadata( def analyse_metadata(
path: str, *, show_progress: bool = False path: str, *, display_progress: bool = False
) -> Observable[AnalysingProgress]: ) -> Observable[AnalysingProgress]:
filesize = os.path.getsize(path) filesize = os.path.getsize(path)
filename = os.path.basename(path) filename = os.path.basename(path)
@ -47,7 +47,7 @@ def analyse_metadata(
desc='Analysing', desc='Analysing',
postfix=filename, postfix=filename,
total=filesize, total=filesize,
disable=not show_progress, disable=not display_progress,
), ),
ops.map(lambda i: len(i)), # type: ignore ops.map(lambda i: len(i)), # type: ignore
ops.scan(lambda acc, x: acc + x, 0), # type: ignore ops.scan(lambda acc, x: acc + x, 0), # type: ignore

View File

@ -26,7 +26,7 @@ class InjectingProgress:
def inject_metadata( def inject_metadata(
path: str, metadata: Dict[str, Any], *, show_progress: bool = False path: str, metadata: Dict[str, Any], *, display_progress: bool = False
) -> Observable[InjectingProgress]: ) -> Observable[InjectingProgress]:
filesize = os.path.getsize(path) filesize = os.path.getsize(path)
@ -51,7 +51,7 @@ def inject_metadata(
desc='Injecting', desc='Injecting',
postfix=filename, postfix=filename,
total=filesize, total=filesize,
disable=not show_progress, disable=not display_progress,
), ),
ops.map(lambda i: len(i)), # type: ignore ops.map(lambda i: len(i)), # type: ignore
ops.scan(lambda acc, x: acc + x, 0), # type: ignore ops.scan(lambda acc, x: acc + x, 0), # type: ignore

View File

@ -16,6 +16,9 @@ from .typing import LOG_LEVEL
__all__ = 'configure_logger', 'ConsoleHandler', 'TqdmOutputStream' __all__ = 'configure_logger', 'ConsoleHandler', 'TqdmOutputStream'
DISPLAY_PROGRESS = bool(os.environ.get('BLREC_PROGRESS'))
class TqdmOutputStream: class TqdmOutputStream:
def write(self, string: str = '') -> None: def write(self, string: str = '') -> None:
tqdm.write(string, end='') tqdm.write(string, end='')
@ -95,7 +98,10 @@ def configure_logger(
) )
# logging to console # logging to console
console_handler = ConsoleHandler(TqdmOutputStream()) if DISPLAY_PROGRESS:
console_handler = ConsoleHandler(TqdmOutputStream())
else:
console_handler = ConsoleHandler()
console_handler.setLevel(logging.getLevelName(console_log_level)) console_handler.setLevel(logging.getLevelName(console_log_level))
console_handler.setFormatter(formatter) console_handler.setFormatter(formatter)
logger.addHandler(console_handler) logger.addHandler(console_handler)

View File

@ -33,6 +33,8 @@ __all__ = (
) )
DISPLAY_PROGRESS = bool(os.environ.get('BLREC_PROGRESS'))
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
@ -259,7 +261,9 @@ class Postprocessor(
future: asyncio.Future[None] = asyncio.Future() future: asyncio.Future[None] = asyncio.Future()
self._postprocessing_path = path self._postprocessing_path = path
subscription = analyse_metadata(path, show_progress=True).subscribe( subscription = analyse_metadata(
path, display_progress=DISPLAY_PROGRESS
).subscribe(
on_error=lambda e: future.set_exception(e), on_error=lambda e: future.set_exception(e),
on_completed=lambda: future.set_result(None), on_completed=lambda: future.set_result(None),
scheduler=self._scheduler, scheduler=self._scheduler,
@ -275,7 +279,9 @@ class Postprocessor(
def on_next(value: InjectingProgress) -> None: def on_next(value: InjectingProgress) -> None:
self._postprocessing_progress = value self._postprocessing_progress = value
subscription = inject_metadata(path, metadata, show_progress=True).subscribe( subscription = inject_metadata(
path, metadata, display_progress=DISPLAY_PROGRESS
).subscribe(
on_next=on_next, on_next=on_next,
on_error=lambda e: future.set_exception(e), on_error=lambda e: future.set_exception(e),
on_completed=lambda: future.set_result(None), on_completed=lambda: future.set_result(None),
@ -301,7 +307,7 @@ class Postprocessor(
in_path, in_path,
out_path, out_path,
metadata_path, metadata_path,
show_progress=True, display_progress=DISPLAY_PROGRESS,
remove_filler_data=True, remove_filler_data=True,
).subscribe( ).subscribe(
on_next=on_next, on_next=on_next,

View File

@ -58,7 +58,7 @@ def remux_video(
out_path: str, out_path: str,
metadata_path: Optional[str] = None, metadata_path: Optional[str] = None,
*, *,
show_progress: bool = False, display_progress: bool = False,
remove_filler_data: bool = False, remove_filler_data: bool = False,
) -> Observable[Union[RemuxingProgress, RemuxingResult]]: ) -> Observable[Union[RemuxingProgress, RemuxingResult]]:
SIZE_PATTERN: Final = re.compile(r'size=\s*(?P<number>\d+)(?P<unit>[a-zA-Z]?B)') SIZE_PATTERN: Final = re.compile(r'size=\s*(?P<number>\d+)(?P<unit>[a-zA-Z]?B)')
@ -125,7 +125,7 @@ def remux_video(
unit_scale=True, unit_scale=True,
unit_divisor=1024, unit_divisor=1024,
postfix=postfix, postfix=postfix,
disable=not show_progress, disable=not display_progress,
) as pbar: ) as pbar:
cmd = f'ffmpeg -i "{in_path}"' cmd = f'ffmpeg -i "{in_path}"'
if metadata_path is not None: if metadata_path is not None: