├── tests ├── __init__.py ├── beep.m4a ├── beep-nochap.m4a ├── 01_chapters_to_workitems_test.py ├── 00_ffprobe_parse_test.py ├── 02_workitem_to_ffmpeg_cmd_test.py └── testdata.py ├── requirements.txt ├── requirements-dev.txt ├── pyproject.toml ├── Makefile ├── .github └── workflows │ └── python.yml ├── src └── audiobook_split_ffmpeg │ ├── __init__.py │ ├── util.py │ ├── workers.py │ ├── cli.py │ └── ffmpeg.py ├── .gitignore ├── README.md └── LICENSE /tests/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /tests/beep.m4a: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/MawKKe/audiobook-split-ffmpeg/HEAD/tests/beep.m4a -------------------------------------------------------------------------------- /tests/beep-nochap.m4a: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/MawKKe/audiobook-split-ffmpeg/HEAD/tests/beep-nochap.m4a -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | # 2 | # This file is autogenerated by pip-compile with Python 3.12 3 | # by the following command: 4 | # 5 | # pip-compile --generate-hashes --output-file=requirements.txt --strip-extras pyproject.toml 6 | # 7 | -------------------------------------------------------------------------------- /tests/01_chapters_to_workitems_test.py: -------------------------------------------------------------------------------- 1 | from audiobook_split_ffmpeg import ( 2 | compute_workitems, 3 | ) 4 | 5 | from .testdata import beep 6 | 7 | 8 | def test_compute_workitems(): 9 | work_items = list(compute_workitems(beep['file'], 'foo')) 10 | assert len(work_items) == 3 11 | assert work_items == beep['expected_workitems'] 12 | -------------------------------------------------------------------------------- /tests/00_ffprobe_parse_test.py: -------------------------------------------------------------------------------- 1 | from audiobook_split_ffmpeg import ( 2 | ffprobe_read_chapters, 3 | ) 4 | 5 | from .testdata import beep, beep_nochap 6 | 7 | 8 | def test_file_with_chapters(): 9 | chapters = ffprobe_read_chapters(beep['file']) 10 | assert chapters == beep['expected_chapters'] 11 | 12 | 13 | def test_file_without_chapters(): 14 | chapters = ffprobe_read_chapters(beep_nochap['file']) 15 | assert chapters == beep_nochap['expected_chapters'] 16 | -------------------------------------------------------------------------------- /requirements-dev.txt: -------------------------------------------------------------------------------- 1 | # 2 | # This file is autogenerated by pip-compile with Python 3.12 3 | # by the following command: 4 | # 5 | # pip-compile --constraint=requirements.txt --extra=dev --output-file=requirements-dev.txt --strip-extras pyproject.toml 6 | # 7 | coverage==7.4.3 8 | # via pytest-cov 9 | iniconfig==2.0.0 10 | # via pytest 11 | mypy==1.10.1 12 | # via audiobook-split-ffmpeg (pyproject.toml) 13 | mypy-extensions==1.0.0 14 | # via mypy 15 | packaging==23.2 16 | # via pytest 17 | pluggy==1.4.0 18 | # via pytest 19 | pytest==8.1.1 20 | # via 21 | # audiobook-split-ffmpeg (pyproject.toml) 22 | # pytest-cov 23 | pytest-cov==4.1.0 24 | # via audiobook-split-ffmpeg (pyproject.toml) 25 | ruff==0.3.2 26 | # via audiobook-split-ffmpeg (pyproject.toml) 27 | typing-extensions==4.12.2 28 | # via mypy 29 | -------------------------------------------------------------------------------- /tests/02_workitem_to_ffmpeg_cmd_test.py: -------------------------------------------------------------------------------- 1 | from audiobook_split_ffmpeg import ( 2 | workitem_to_ffmpeg_cmd, 3 | ) 4 | from audiobook_split_ffmpeg.util import ( 5 | WorkItem, 6 | ) 7 | 8 | 9 | def test_workitem_to_ffmpeg_cmd(): 10 | wi = WorkItem( 11 | infile='koe.m4a', 12 | outfile='out/Output File.m4a', 13 | start='13.1230', 14 | end='42.5363', 15 | ch_num=2, 16 | ch_max=3, 17 | ch_title='Output title', 18 | ) 19 | 20 | cmd = workitem_to_ffmpeg_cmd(wi) 21 | 22 | expected = [ 23 | 'ffmpeg', 24 | '-nostdin', 25 | '-i', 26 | 'koe.m4a', 27 | '-v', 28 | 'error', 29 | '-map_chapters', 30 | '-1', 31 | '-vn', 32 | '-c', 33 | 'copy', 34 | '-ss', 35 | '13.1230', 36 | '-to', 37 | '42.5363', 38 | '-n', 39 | '-metadata', 40 | 'track=2/3', 41 | '-metadata', 42 | 'title=Output title', 43 | 'out/Output File.m4a', 44 | ] 45 | 46 | assert len(cmd) > 1 47 | assert len(cmd) == len(expected) 48 | assert cmd == expected 49 | -------------------------------------------------------------------------------- /pyproject.toml: -------------------------------------------------------------------------------- 1 | [build-system] 2 | requires = ['setuptools>=61'] 3 | build-backend = 'setuptools.build_meta' 4 | 5 | [project] 6 | name = 'audiobook-split-ffmpeg' 7 | authors = [ 8 | {name='Markus H (MawKKe)', email='markus@mawkke.fi'} 9 | ] 10 | description = 'Split audiobook file into per-chapter files using chapter metadata and ffmpeg' 11 | dynamic = ["version"] 12 | license = {text = 'Apache License 2.0'} 13 | readme = 'README.md' 14 | requires-python = '>=3.8' 15 | dependencies = [] 16 | 17 | [tool.setuptools.dynamic] 18 | version = {attr = "audiobook_split_ffmpeg.__version__"} 19 | 20 | [project.optional-dependencies] 21 | dev = [ 22 | 'ruff>=0.3', 23 | 'pytest>=7', 24 | 'pytest-cov>=4.1', 25 | 'mypy>=1.10', 26 | ] 27 | 28 | [project.urls] 29 | homepage = 'https://github.com/MawKKe/audiobook-split-ffmpeg' 30 | Issues = 'https://github.com/MawKKe/audiobook-split-ffmpeg/issues' 31 | 32 | [project.scripts] 33 | audiobook-split-ffmpeg = 'audiobook_split_ffmpeg.cli:main' 34 | 35 | [tool.pytest.ini_options] 36 | pythonpath = [ 37 | ".", "src", 38 | ] 39 | 40 | [tool.ruff] 41 | line-length = 100 42 | 43 | [tool.ruff.format] 44 | # Use single quotes rather than double quotes. 45 | quote-style = 'single' 46 | skip-magic-trailing-comma = false 47 | 48 | [tool.ruff.lint] 49 | select = ['E4', 'E7', 'E9', 'F', 'C901'] 50 | 51 | [tool.ruff.lint.mccabe] 52 | max-complexity = 10 53 | 54 | [tool.mypy] 55 | #warn_return_any = true 56 | warn_unreachable = true 57 | disallow_untyped_defs = true 58 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | VENV_DIR := .venv 2 | 3 | sync-venv: requirements-dev.txt 4 | python3 -m venv ${VENV_DIR} 5 | ./${VENV_DIR}/bin/pip install --upgrade pip 6 | ./${VENV_DIR}/bin/pip install -r requirements-dev.txt 7 | @echo "---" 8 | @echo "NOTE: Please run 'source ./${VENV_DIR}/bin/activate' to use the env" 9 | @echo " or run 'Python: Select Interpreter' from VSCode command palette" 10 | 11 | pin-requirements: requirements.txt requirements-dev.txt 12 | @echo "---------------------------------------------" 13 | @echo "Done.\n" 14 | @echo "Remember to commit changes to pyproject.toml," 15 | @echo " requirements.txt, and requirements-dev.txt" 16 | @echo "---------------------------------------------" 17 | 18 | requirements.txt: pyproject.toml 19 | pip-compile \ 20 | --generate-hashes \ 21 | --strip-extras \ 22 | --output-file=requirements.txt \ 23 | pyproject.toml 24 | 25 | requirements-dev.txt: requirements.txt 26 | pip-compile \ 27 | --strip-extras \ 28 | --constraint requirements.txt \ 29 | --output-file=requirements-dev.txt \ 30 | --extra dev \ 31 | pyproject.toml 32 | 33 | # This is basically 'python3 -m build' 34 | build: 35 | pyproject-build 36 | 37 | fmt format: 38 | ruff format 39 | 40 | lint: 41 | ruff check --output-format=full 42 | 43 | test: test-pytest test-mypy 44 | 45 | test-pytest: 46 | pytest --cov=audiobook_split_ffmpeg tests/ 47 | 48 | test-mypy: 49 | mypy src 50 | 51 | .PHONY: sync-venv pin-requirements build lint test 52 | -------------------------------------------------------------------------------- /.github/workflows/python.yml: -------------------------------------------------------------------------------- 1 | # This workflow will install Python dependencies, run tests and lint with a variety of Python versions 2 | # For more information see: https://docs.github.com/en/actions/automating-builds-and-tests/building-and-testing-python 3 | 4 | name: Python app 5 | 6 | on: 7 | push: 8 | branches: [ "main" ] 9 | pull_request: 10 | branches: [ "main" ] 11 | 12 | jobs: 13 | build: 14 | 15 | runs-on: ubuntu-latest 16 | strategy: 17 | fail-fast: false 18 | matrix: 19 | python-version: ["3.9", "3.10", "3.11"] 20 | 21 | steps: 22 | - uses: actions/checkout@v3 23 | - uses: FedericoCarboni/setup-ffmpeg@v3 24 | - name: Set up Python ${{ matrix.python-version }} 25 | uses: actions/setup-python@v3 26 | with: 27 | python-version: ${{ matrix.python-version }} 28 | - name: Install environment 29 | run: | 30 | python -m pip install --upgrade pip 31 | python -m pip install -r requirements-dev.txt 32 | - name: Run linter 33 | run: | 34 | make lint 35 | - name: Run tests with pytest 36 | run: | 37 | make test-pytest 38 | - name: Run tests with mypy 39 | run: | 40 | make test-mypy 41 | - name: Verify main entrypoint script works 42 | run: | 43 | python -m venv app-venv && ./app-venv/bin/pip install . 44 | ./app-venv/bin/audiobook-split-ffmpeg --help 45 | ./app-venv/bin/audiobook-split-ffmpeg --infile tests/beep.m4a --outdir _out --verbose 46 | -------------------------------------------------------------------------------- /src/audiobook_split_ffmpeg/__init__.py: -------------------------------------------------------------------------------- 1 | # Copyright 2018 Markus Holmström (MawKKe) 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | """ 16 | Split audiobook file into per-chapter files using chapter metadata and ffmpeg 17 | 18 | 19 | This package provides the functionality to split a single audiobook file into 20 | several smaller chapter files, assuming the file has embedded chapter metadata 21 | available. 22 | 23 | This package can be used either as a standalone CLI application or as library. 24 | The CLI application should be available as: 25 | 26 | $ audiobook-split-ffmpeg 27 | 28 | ...assuming this package installed with 'pip install' or similar. Run the 29 | script with --help to get started. 30 | 31 | The package can be used as a library by importing the 'audiobook_split_ffmpeg' module 32 | and using the provided functions. The functions are rudimentary, meaning some additional 33 | housekeeping code may be needed. See the file 'audiobook_split_ffmpeg/cli.py' for an 34 | example how to combine the functions to produce a useful application. 35 | 36 | More information in Github: https://github.com/MawKKe/audiobook-split-ffmpeg 37 | """ 38 | 39 | from .ffmpeg import ( 40 | ffprobe_read_chapters, 41 | workitem_to_ffmpeg_cmd, 42 | ffmpeg_split_chapter, 43 | compute_workitems, 44 | ) 45 | from .workers import process_workitems 46 | 47 | __all__ = [ 48 | 'ffprobe_read_chapters', 49 | 'workitem_to_ffmpeg_cmd', 50 | 'ffmpeg_split_chapter', 51 | 'process_workitems', 52 | 'compute_workitems', 53 | ] 54 | __author__ = 'Markus Holmström (MawKKe) ' 55 | __version__ = '0.2.0' 56 | -------------------------------------------------------------------------------- /src/audiobook_split_ffmpeg/util.py: -------------------------------------------------------------------------------- 1 | # Copyright 2018 Markus Holmström (MawKKe) 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | """ 16 | Various utilities for audiobook_split_ffmpeg 17 | """ 18 | 19 | from collections import namedtuple 20 | import typing as t 21 | 22 | 23 | # Helper type for collecting necessary information about chapter for processing 24 | WorkItem = namedtuple( 25 | 'WorkItem', 26 | [ 27 | 'infile', 28 | 'outfile', 29 | 'start', 30 | 'end', 31 | 'ch_num', 32 | 'ch_max', 33 | 'ch_title', 34 | ], 35 | ) 36 | 37 | 38 | # Special characters interpreted specially by most crappy software 39 | 40 | _CHR_BLACKLIST = [ 41 | '\\', 42 | '/', 43 | ':', 44 | '*', 45 | '?', 46 | '"', 47 | '<', 48 | '>', 49 | '|', 50 | '\0', 51 | ] 52 | 53 | 54 | def _sanitize_string(original: t.Optional[str]) -> t.Optional[str]: 55 | """ 56 | Filter typical special letters from string 57 | """ 58 | if original is None: 59 | return None 60 | return ''.join(c for c in original if c not in _CHR_BLACKLIST) 61 | 62 | 63 | Chapter = t.Dict[str, t.Any] 64 | 65 | 66 | def _validate_chapter(chap: Chapter) -> t.Optional[Chapter]: 67 | """ 68 | Checks that chapter is valid (i.e has valid length) 69 | """ 70 | start = chap['start'] 71 | end = chap['end'] 72 | if (end - start) <= 0: 73 | msg = 'WARNING: chapter {0} duration <= 0 (start: {1}, end: {2}), skipping...' 74 | print(msg.format(chap['id'], start, end)) 75 | return None 76 | return chap 77 | 78 | 79 | def _get_title_maybe(chap: Chapter) -> t.Optional[str]: 80 | """ 81 | Chapter to title (string) or None 82 | """ 83 | if 'tags' not in chap: 84 | return None 85 | return chap['tags'].get('title', None) 86 | -------------------------------------------------------------------------------- /tests/testdata.py: -------------------------------------------------------------------------------- 1 | import pathlib 2 | 3 | from audiobook_split_ffmpeg.util import WorkItem 4 | 5 | here = pathlib.Path(__file__).parent.resolve() 6 | 7 | 8 | beep = { 9 | 'file': (here / 'beep.m4a'), 10 | 'expected_chapters': { 11 | 'chapters': [ 12 | { 13 | 'end': 20000, 14 | 'end_time': '20.000000', 15 | 'id': 0, 16 | 'start': 0, 17 | 'start_time': '0.000000', 18 | 'tags': {'title': 'It All Started With a Simple BEEP'}, 19 | 'time_base': '1/1000', 20 | }, 21 | { 22 | 'end': 40000, 23 | 'end_time': '40.000000', 24 | 'id': 1, 25 | 'start': 20000, 26 | 'start_time': '20.000000', 27 | 'tags': {'title': 'All You Can BEEP Buffee'}, 28 | 'time_base': '1/1000', 29 | }, 30 | { 31 | 'end': 60000, 32 | 'end_time': '60.000000', 33 | 'id': 2, 34 | 'start': 40000, 35 | 'start_time': '40.000000', 36 | 'tags': {'title': 'The Final Beep'}, 37 | 'time_base': '1/1000', 38 | }, 39 | ] 40 | }, 41 | 'expected_workitems': [ 42 | WorkItem( 43 | infile=(here / 'beep.m4a'), 44 | outfile='foo/1 - It All Started With a Simple BEEP.m4a', 45 | start='0.000000', 46 | end='20.000000', 47 | ch_num=1, 48 | ch_max=3, 49 | ch_title='It All Started With a Simple BEEP', 50 | ), 51 | WorkItem( 52 | infile=(here / 'beep.m4a'), 53 | outfile='foo/2 - All You Can BEEP Buffee.m4a', 54 | start='20.000000', 55 | end='40.000000', 56 | ch_num=2, 57 | ch_max=3, 58 | ch_title='All You Can BEEP Buffee', 59 | ), 60 | WorkItem( 61 | infile=(here / 'beep.m4a'), 62 | outfile='foo/3 - The Final Beep.m4a', 63 | start='40.000000', 64 | end='60.000000', 65 | ch_num=3, 66 | ch_max=3, 67 | ch_title='The Final Beep', 68 | ), 69 | ], 70 | } 71 | 72 | beep_nochap = { 73 | 'file': (here / 'beep-nochap.m4a'), 74 | 'expected_chapters': {'chapters': []}, 75 | } 76 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | wheels/ 23 | pip-wheel-metadata/ 24 | share/python-wheels/ 25 | *.egg-info/ 26 | .installed.cfg 27 | *.egg 28 | MANIFEST 29 | 30 | # PyInstaller 31 | # Usually these files are written by a python script from a template 32 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 33 | *.manifest 34 | *.spec 35 | 36 | # Installer logs 37 | pip-log.txt 38 | pip-delete-this-directory.txt 39 | 40 | # Unit test / coverage reports 41 | htmlcov/ 42 | .tox/ 43 | .nox/ 44 | .coverage 45 | .coverage.* 46 | .cache 47 | nosetests.xml 48 | coverage.xml 49 | *.cover 50 | *.py,cover 51 | .hypothesis/ 52 | .pytest_cache/ 53 | .ruff_cache/ 54 | 55 | # Translations 56 | *.mo 57 | *.pot 58 | 59 | # Django stuff: 60 | *.log 61 | local_settings.py 62 | db.sqlite3 63 | db.sqlite3-journal 64 | 65 | # Flask stuff: 66 | instance/ 67 | .webassets-cache 68 | 69 | # Scrapy stuff: 70 | .scrapy 71 | 72 | # Sphinx documentation 73 | docs/_build/ 74 | 75 | # PyBuilder 76 | target/ 77 | 78 | # Jupyter Notebook 79 | .ipynb_checkpoints 80 | 81 | # IPython 82 | profile_default/ 83 | ipython_config.py 84 | 85 | # pyenv 86 | .python-version 87 | 88 | # pipenv 89 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 90 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 91 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 92 | # install all needed dependencies. 93 | #Pipfile.lock 94 | 95 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow 96 | __pypackages__/ 97 | 98 | # Celery stuff 99 | celerybeat-schedule 100 | celerybeat.pid 101 | 102 | # SageMath parsed files 103 | *.sage.py 104 | 105 | # Environments 106 | .env 107 | .venv 108 | env/ 109 | venv/ 110 | ENV/ 111 | env.bak/ 112 | venv.bak/ 113 | 114 | # Spyder project settings 115 | .spyderproject 116 | .spyproject 117 | 118 | # Rope project settings 119 | .ropeproject 120 | 121 | # mkdocs documentation 122 | /site 123 | 124 | # mypy 125 | .mypy_cache/ 126 | .dmypy.json 127 | dmypy.json 128 | 129 | # Pyre type checker 130 | .pyre/ 131 | 132 | # vim crap 133 | .*.sw[mnop] -------------------------------------------------------------------------------- /src/audiobook_split_ffmpeg/workers.py: -------------------------------------------------------------------------------- 1 | # Copyright 2018 Markus Holmström (MawKKe) 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | """ 16 | Functioality for consuming WorkItems and producing final chapter files 17 | with parallel worker threads/processes. 18 | """ 19 | 20 | import os 21 | import sys 22 | from concurrent.futures import ( 23 | Future, 24 | ThreadPoolExecutor, 25 | as_completed, 26 | ) 27 | import typing as t 28 | from pathlib import Path 29 | 30 | from .ffmpeg import ffmpeg_split_chapter 31 | from .util import WorkItem 32 | 33 | 34 | def process_workitems( 35 | work_items: t.Sequence[WorkItem], outdir: Path, concurrency: int = 1, verbose: bool = False 36 | ) -> int: 37 | """ 38 | Runs ffmpeg worker process for each WorkItem, parallellized with ThreadPoolExecutor 39 | """ 40 | 41 | os.makedirs(outdir, exist_ok=True) 42 | 43 | if verbose: 44 | print('Output directory: {}'.format(outdir)) 45 | print('Starting ThreadPoolExecutor with concurrency={0}'.format(concurrency)) 46 | 47 | n_jobs = 0 48 | with ThreadPoolExecutor(max_workers=concurrency) as pool: 49 | 50 | def start_all() -> t.Iterator[t.Tuple[Future, WorkItem]]: 51 | for w_item in work_items: 52 | if verbose: 53 | print('Submitting job: {}'.format(w_item)) 54 | yield ( 55 | pool.submit( 56 | ffmpeg_split_chapter, 57 | w_item, 58 | ), 59 | w_item, 60 | ) 61 | 62 | futs = dict(start_all()) 63 | n_jobs = len(futs) 64 | stats = _wait_for_results(futs, verbose) 65 | 66 | print('Total jobs: {n}, Success: {success}, Errors: {error}'.format(n=n_jobs, **stats)) 67 | 68 | if stats['error'] > 0: 69 | print( 70 | 'WARNING: Due to errors, some chapters may not have been processed!', 71 | file=sys.stderr, 72 | ) 73 | return -1 74 | 75 | return 0 76 | 77 | 78 | def _wait_for_results(futs: t.Dict[Future, WorkItem], verbose: bool = False) -> t.Dict[str, int]: 79 | """ 80 | Collect ffmpeg processing results and display whether chapter was processed correctly 81 | """ 82 | stats = {'success': 0, 'error': 0} 83 | for fut in as_completed(futs): 84 | w_item = futs[fut] 85 | try: 86 | result = fut.result() 87 | # this looks nasty as hell, but hey, this is what they do in python docs.. 88 | except Exception as exn_wtf: # pylint: disable=broad-except 89 | stats['error'] += 1 90 | print("ERROR: job '{}' generated an exeption: {}".format(w_item.outfile, exn_wtf)) 91 | else: 92 | if result['ok']: 93 | stats['success'] += 1 94 | if verbose: 95 | print('SUCCESS: {0}'.format(w_item.outfile)) 96 | else: 97 | stats['error'] += 1 98 | exn_proc = result['exn'] 99 | print('FAILURE: {0}'.format(exn_proc.stderr.decode('utf8').strip())) 100 | if verbose: 101 | print('Command that failed: {0}'.format(result['cmd'])) 102 | print('-' * 5) 103 | return stats 104 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # audiobook-split-ffmpeg 2 | 3 | Split audiobook file into per-chapter files using chapter metadata and ffmpeg. 4 | 5 | Useful in situations where your preferred audio player does not support chapter metadata. 6 | 7 | **NOTE**: Works only if the input file actually has chapter metadata (see example below) 8 | 9 | # Example 10 | 11 | Let's say, you have an audio file `mybook.m4b`, for which `ffprobe -i mybook.m4b` 12 | shows the following: 13 | 14 | Chapter #0:0: start 0.000000, end 1079.000000 15 | Metadata: 16 | title : Chapter Zero 17 | Chapter #0:1: start 1079.000000, end 2040.000000 18 | Metadata: 19 | title : Chapter One 20 | Chapter #0:2: start 2040.000000, end 2878.000000 21 | Metadata: 22 | title : Chapter Two 23 | Chapter #0:3: start 2878.000000, end 3506.000000 24 | 25 | Then, running: 26 | 27 | $ audiobook-split-ffmpeg --infile mybook.m4b --outdir /tmp/foo 28 | 29 | ..produces the following files: 30 | - `/tmp/foo/001 - Chapter Zero.m4b` 31 | - `/tmp/foo/002 - Chapter One.m4b` 32 | - `/tmp/foo/003 - Chapter Two.m4b` 33 | 34 | You may then play these files with your preferred application. 35 | 36 | # Install 37 | 38 | This package is not published in the PYPI, but you can install it directly from Github with 39 | 40 | $ pip install --user git+https://github.com/MawKKe/audiobook-split-ffmpeg 41 | 42 | **However**, I personally recommend using [pipx](https://github.com/pypa/pipx) 43 | which simplifies installing python applications into isolated virtualenvs: 44 | 45 | $ pipx install git+https://github.com/MawKKe/audiobook-split-ffmpeg 46 | 47 | afterwards, the `audiobook-split-ffmpeg` command should be available via your `PATH`. 48 | 49 | Next, see Usage below. 50 | 51 | # Usage 52 | 53 | See the help: 54 | 55 | $ audiobook-split-ffmpeg -h 56 | 57 | In the simplest case you can just call 58 | 59 | $ audiobook-split-ffmpeg --infile /path/to/audio.m4b --outdir foo 60 | 61 | Note that this script will never overwrite files in `foo/`, so you must delete conflicting 62 | files manually (or specify some other empty/nonexistent directory) 63 | 64 | The chapter titles will be included in the filenames if they are available in 65 | the chapter metadata. You may prevent this behaviour with flag `--no-use-title-as-filename`, 66 | in which case the filenames will include the input file basename instead (this 67 | is useful is your metadata is crappy or malformed, for example). 68 | 69 | You may specify how many parallel `ffmpeg` jobs you want with command line param `--concurrency`. 70 | The default concurrency is equal to the number of cores available. Note that at some point increasing 71 | the concurrency might not increase the throughput. (We specifically instruct `ffmpeg` to NOT perform 72 | re-encoding, so most of the processing work consists of copying the existing encoded audio data from the 73 | input file to the output file(s) - this kind of processing is more I/O bounded than CPU-bounded). 74 | 75 | # Dependencies 76 | 77 | This application has no 3rd party library dependencies, as everything is 78 | implemented using the Python standard library. However, the script assumes 79 | the that the following system-executables are available somewhere in your `$PATH`: 80 | 81 | - `ffmpeg` 82 | - `ffprobe` 83 | 84 | For Ubuntu, these can be installed with `apt install ffmpeg`. 85 | 86 | # Development and Testing 87 | 88 | Clone the repo, and install the package in development mode: 89 | 90 | $ git clone audiobook-split-ffmpeg && cd audiobook-split-ffmpeg 91 | $ pip install -e '.[dev]' 92 | 93 | then run tests with: 94 | 95 | $ pytest -vv 96 | 97 | # Features 98 | 99 | - The script does not transcode/re-encode the audio data. This speeds up the processing, but has 100 | the possibility of creating mangled audio in some rare cases (let me know if this happens). 101 | 102 | - This script will instruct ffmpeg to write metadata in the resulting chapter files, including: 103 | - `track`: the chapter number; in the format X/Y, where X = chapter number, Y = total num of chapters. 104 | - `title`: the chapter title, as-is (if available) 105 | 106 | - The chapter numbers are included in the output file names, padded with zeroes so that all 107 | numbers are of equal length. This makes the files much easier to sort by name. 108 | 109 | - The work is parallelized to speed up the processing. 110 | 111 | 112 | # License 113 | 114 | Copyright 2018 Markus Holmström (MawKKe) 115 | 116 | The works under this repository are licenced under Apache License 2.0. 117 | See file `LICENSE` for more information. 118 | 119 | # Contributing 120 | 121 | This project is hosted at https://github.com/MawKKe/audiobook-split-ffmpeg 122 | 123 | You are welcome to leave bug reports, fixes and feature requests. Thanks! 124 | 125 | -------------------------------------------------------------------------------- /src/audiobook_split_ffmpeg/cli.py: -------------------------------------------------------------------------------- 1 | # Copyright 2018 Markus Holmström (MawKKe) 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | """ 16 | CLI application implementation for audiobook-split-ffmpeg 17 | """ 18 | 19 | import sys 20 | import shlex 21 | import argparse 22 | import typing as t 23 | 24 | from multiprocessing import cpu_count 25 | 26 | from . import __version__ 27 | from .ffmpeg import workitem_to_ffmpeg_cmd, compute_workitems 28 | from .workers import process_workitems 29 | 30 | 31 | def parse_args(argv: t.List[str]) -> argparse.Namespace: 32 | """ 33 | Parse argv into argparse.Namespace 34 | 35 | Arguments: 36 | 37 | argv 38 | a list of strings, usually the value of sys.argv 39 | 40 | WARNING: 41 | If argv is malformed, the process will exit. Avoid using this function in tests. 42 | """ 43 | parser = argparse.ArgumentParser( 44 | description='Split audiobook chapters using ffmpeg', epilog=f'version {__version__}' 45 | ) 46 | parser.add_argument( 47 | '--infile', 48 | required=True, 49 | help='Input file. Chapter information must be present in file metadata', 50 | ) 51 | parser.add_argument( 52 | '--outdir', 53 | required=True, 54 | help='Output directory. Created if does not exist yet.', 55 | ) 56 | parser.add_argument( 57 | '--concurrency', 58 | required=False, 59 | type=int, 60 | default=cpu_count(), 61 | help='Number of concurrent ffmpeg worker processes', 62 | ) 63 | 64 | # NOTE: without this mutual exclusion, the output 65 | # filenames would be identical between chapters! 66 | # In essence, you can give either (or neither), but not both. 67 | excl = parser.add_mutually_exclusive_group(required=False) 68 | excl.add_argument( 69 | '--no-enumerate-filenames', 70 | required=False, 71 | dest='enumerate_files', 72 | action='store_false', 73 | help='Do not include chapter numbers in the output filenames', 74 | ) 75 | excl.add_argument( 76 | '--no-use-title', 77 | '--no-use-title-as-filename', 78 | required=False, 79 | dest='use_title', 80 | action='store_false', 81 | help='Do not include chapter titles in the output filenames', 82 | ) 83 | 84 | parser.add_argument( 85 | '--dry-run', 86 | required=False, 87 | action='store_true', 88 | help='Show what actions would be taken without taking them', 89 | ) 90 | parser.add_argument( 91 | '--verbose', 92 | required=False, 93 | action='store_true', 94 | help='Show more output', 95 | ) 96 | 97 | args = parser.parse_args(argv[1:]) 98 | 99 | return args 100 | 101 | 102 | def _main(args: argparse.Namespace) -> int: 103 | """ 104 | CLI main function for audiobook-split-ffmpeg 105 | 106 | Arguments: 107 | 108 | args 109 | an argparse.Namespace() object containing the required command line arguments 110 | See parse_args() for more details. 111 | """ 112 | 113 | if args.verbose: 114 | print('args:', args) 115 | 116 | work_items = list( 117 | compute_workitems( 118 | args.infile, 119 | args.outdir, 120 | enumerate_files=args.enumerate_files, 121 | use_title_in_filenames=args.use_title, 122 | ) 123 | ) 124 | if args.verbose: 125 | print('Found: {0} chapters to be processed'.format(len(work_items))) 126 | 127 | if args.dry_run: 128 | print('# NOTE: dry-run requested') 129 | print(shlex.join(['mkdir', '-p', args.outdir])) 130 | commands = (workitem_to_ffmpeg_cmd(wi) for wi in work_items) 131 | escaped_cmds = (shlex.join(cmd) for cmd in commands) 132 | for cmd in escaped_cmds: 133 | print(cmd) 134 | return 0 135 | 136 | return process_workitems( 137 | work_items, 138 | args.outdir, 139 | args.concurrency, 140 | args.verbose, 141 | ) 142 | 143 | 144 | def main() -> t.NoReturn: 145 | """ 146 | CLI main function for audiobook-split-ffmpeg 147 | """ 148 | sys.exit(_main(parse_args(sys.argv))) 149 | 150 | 151 | if __name__ == '__main__': 152 | main() 153 | -------------------------------------------------------------------------------- /src/audiobook_split_ffmpeg/ffmpeg.py: -------------------------------------------------------------------------------- 1 | # Copyright 2018 Markus Holmström (MawKKe) 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | """ 16 | Utility functionality for interacting with system ffmpeg executables 17 | """ 18 | 19 | import json 20 | import os 21 | import subprocess as sub 22 | import typing as t 23 | from pathlib import Path 24 | 25 | from .util import WorkItem, _validate_chapter, _sanitize_string, _get_title_maybe 26 | 27 | 28 | def ffprobe_read_chapters(filename: Path) -> t.Dict[t.Any, t.Any]: 29 | """ 30 | Read chapter metadata from 'filename' using ffprobe and return it as dict 31 | """ 32 | 33 | command = [ 34 | 'ffprobe', 35 | '-i', 36 | str(filename), 37 | '-v', 38 | 'error', 39 | '-print_format', 40 | 'json', 41 | '-show_chapters', 42 | ] 43 | 44 | # ffmpeg & ffprobe write output into stderr, except when 45 | # using -show_XXXX and -print_format. Strange. 46 | # Had we ran ffmpeg instead of ffprobe, this would throw since ffmpeg without 47 | # an output file will exit with exitcode != 0 48 | proc = sub.run( 49 | command, 50 | check=True, 51 | stdout=sub.PIPE, 52 | stderr=sub.PIPE, 53 | ) 54 | 55 | # .decode() will most likely explode if the ffprobe json output (chapter metadata) 56 | # was written with some weird encoding, and even more so if the data contains text in 57 | # multiple different text encodings... 58 | 59 | # TODO how does this handle non-ascii/utf8 metadata? # pylint: disable=fixme 60 | # https://stackoverflow.com/questions/10009753/python-dealing-with-mixed-encoding-files 61 | output = proc.stdout.decode('utf8') 62 | 63 | data = json.loads(output) 64 | 65 | return data 66 | 67 | 68 | def workitem_to_ffmpeg_cmd(w_item: WorkItem) -> t.List[str]: 69 | """ 70 | Build command list from WorkItem. 71 | The command list can be directly passed to subprocess.run() or similar. 72 | """ 73 | 74 | # NOTE: 75 | # '-nostdin' param should prevent your terminal becoming all messed up 76 | # during the pool processing. But if it does, you can fix it with 'reset' 77 | # and/or 'stty sane'. If corruption still occurs, let me know (email is at 78 | # the top of the file). 79 | 80 | base_cmd = [ 81 | 'ffmpeg', 82 | '-nostdin', 83 | '-i', 84 | w_item.infile, 85 | '-v', 86 | 'error', 87 | '-map_chapters', 88 | '-1', 89 | '-vn', 90 | '-c', 91 | 'copy', 92 | '-ss', 93 | w_item.start, 94 | '-to', 95 | w_item.end, 96 | '-n', 97 | ] 98 | 99 | metadata_track = [ 100 | '-metadata', 101 | 'track={}/{}'.format(w_item.ch_num, w_item.ch_max), 102 | ] 103 | 104 | # TODO how does this handle mangled title values? # pylint: disable=fixme 105 | metadata_title = ( 106 | [ 107 | '-metadata', 108 | 'title={}'.format(w_item.ch_title), 109 | ] 110 | if w_item.ch_title 111 | else [] 112 | ) 113 | 114 | # Build the final command 115 | cmd = base_cmd + metadata_track + metadata_title + [w_item.outfile] 116 | 117 | return cmd 118 | 119 | 120 | def ffmpeg_split_chapter(w_item: WorkItem) -> t.Dict: 121 | """ 122 | Split a single chapter using ffmpeg subprocess. Blocks until completion. 123 | 124 | w_item: 125 | a WorkItem that fully describes the task to be performed 126 | """ 127 | 128 | # cmd is a a flat list of strings 129 | cmd = workitem_to_ffmpeg_cmd(w_item) 130 | 131 | try: 132 | proc = sub.run( 133 | cmd, 134 | check=True, 135 | stdout=sub.PIPE, 136 | stderr=sub.PIPE, 137 | ) 138 | return { 139 | 'ok': True, 140 | 'w_item': w_item, 141 | 'proc': proc, 142 | 'exn': None, 143 | 'cmd': cmd, 144 | } 145 | except sub.CalledProcessError as exn: 146 | return { 147 | 'ok': False, 148 | 'w_item': w_item, 149 | 'proc': None, 150 | 'exn': exn, 151 | 'cmd': cmd, 152 | } 153 | 154 | 155 | def compute_workitems( 156 | infile: Path, outdir: Path, enumerate_files: bool = True, use_title_in_filenames: bool = True 157 | ) -> t.Iterator[WorkItem]: 158 | """ 159 | Compute WorkItem's for each chapter to be processed. These WorkItems can be then used 160 | for launching ffmpeg processes (see ffmpeg_split_chapter) 161 | 162 | Arguments: 163 | 164 | infile 165 | Path to an audio(book) file. Must contain chapter information in its metadata. 166 | outdir 167 | Path to a directory where chapter files will be written. Must exist already. 168 | enumerate_files 169 | Include chapter numbers in output filenames? 170 | use_title_in_filenames 171 | Include chapter titles in output filenames? 172 | """ 173 | 174 | in_root, in_ext = os.path.splitext(os.path.basename(infile)) 175 | 176 | if 0 in [len(in_root), len(in_ext)]: 177 | raise RuntimeError('Unexpected input filename format - root part or extension is empty') 178 | 179 | # Make sure extension has no leading dots. 180 | in_ext = in_ext[1:] if in_ext.startswith('.') else in_ext 181 | 182 | # Get chapter metadata 183 | info = ffprobe_read_chapters(infile) 184 | 185 | if (info is None) or ('chapters' not in info) or (len(info['chapters']) == 0): 186 | raise RuntimeError('Could not parse chapters') 187 | 188 | # Collect all valid chapters into a list 189 | chapters = list( 190 | filter( 191 | None, 192 | (_validate_chapter(ch) for ch in info['chapters']), 193 | ) 194 | ) 195 | 196 | # Find maximum chapter number. Remember + 1 since enumeration starts at zero! 197 | ch_max = max(chap['id'] + 1 for chap in chapters) 198 | 199 | # Produces equal-width zero-padded chapter numbers for use in filenames. 200 | def chnum_fmt(n: int) -> str: 201 | return '{n:{fill}{width}}'.format(n=n, fill='0', width=len(str(ch_max))) 202 | 203 | for chapter in chapters: 204 | # Get cleaned title or None 205 | title_maybe = _sanitize_string(_get_title_maybe(chapter)) 206 | 207 | ch_num = chapter['id'] + 1 208 | 209 | # Use chapter title in output filename base unless disabled or not available. 210 | # Otherwise, use the root part of input filename 211 | title = title_maybe if (use_title_in_filenames and title_maybe) else in_root 212 | 213 | out_base = '{title}.{ext}'.format(title=title, ext=in_ext) 214 | 215 | # Prepend chapter number if requested 216 | if enumerate_files: 217 | out_base = '{0} - {1}'.format(chnum_fmt(ch_num), out_base) 218 | 219 | yield WorkItem( 220 | infile=infile, 221 | outfile=os.path.join(outdir, out_base), 222 | start=chapter['start_time'], 223 | end=chapter['end_time'], 224 | ch_num=ch_num, 225 | ch_max=ch_max, 226 | ch_title=_get_title_maybe(chapter), 227 | ) 228 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | --------------------------------------------------------------------------------