Browse Source

Initial commit

master
Jakub Valenta 4 years ago
commit
1e322df65b
19 changed files with 1146 additions and 0 deletions
  1. +6
    -0
      .gitignore
  2. +202
    -0
      LICENSE
  3. +13
    -0
      NOTICE
  4. +99
    -0
      README.md
  5. +56
    -0
      setup.py
  6. +5
    -0
      tv-series-check-approved-subs
  7. +5
    -0
      tv-series-download-subs
  8. +5
    -0
      tv-series-find-episode-ids
  9. +5
    -0
      tv-series-print-approved-subs
  10. +5
    -0
      tv-series-search-subs
  11. +5
    -0
      tv-series-text
  12. +5
    -0
      tv-series-video
  13. +0
    -0
      tv_series/__init__.py
  14. +33
    -0
      tv_series/common.py
  15. +135
    -0
      tv_series/download_subs.py
  16. +77
    -0
      tv_series/find_episode_ids.py
  17. +287
    -0
      tv_series/search_subs.py
  18. +32
    -0
      tv_series/text.py
  19. +171
    -0
      tv_series/video.py

+ 6
- 0
.gitignore View File

@@ -0,0 +1,6 @@
*.pyc
__pycache__
build
dist
*.DS_Store
*.egg-info

+ 202
- 0
LICENSE View File

@@ -0,0 +1,202 @@

Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/

TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION

1. Definitions.

"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.

"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.

"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.

"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.

"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.

"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.

"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).

"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.

"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."

"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.

2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.

3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.

4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:

(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and

(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and

(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and

(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.

You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.

5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.

6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.

7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.

8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.

9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.

END OF TERMS AND CONDITIONS

APPENDIX: How to apply the Apache License to your work.

To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.

Copyright [yyyy] [name of copyright owner]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

+ 13
- 0
NOTICE View File

@@ -0,0 +1,13 @@
Copyright 2015 Jakub Valenta

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

+ 99
- 0
README.md View File

@@ -0,0 +1,99 @@
# TV Series Tools

- Download subtitles for all TV series episodes.
- Search subtitles for specific dialogues and create transcript for [videogrep](https://github.com/antiboredom/videogrep).

## Installation

This software requires Python 2.7. See [Pythons's website](https://www.python.org/) for installation instructions.

When you have Python 2.7 installed, install required packages with pip (Python's package management system):

```
pip2 install requests
pip2 install imdbpy
pip2 install "git+https://github.com/agonzalezro/python-opensubtitles#egg=python-opensubtitles"
pip2 install pysrt
pip2 install termcolor
pip2 install moviepy
```

Then you can call the executables:

```
./tv-series-download-subs -h
./tv-series-find-episode-ids -h
```

Or you can install this software as a Python package, which will also install all the dependencies and make the executables available globally:

```
python2 setup.py install

tv-series-download-subs -h
tv-series-find-episode-ids -h
```

## Usage

This software works in two phases:

### 1. Find IMDB IDs for all episodes of passed TV series

Create a file containing the names of the TV series you are interested in. One title per line. Empty lines and lines starting with the hash sign (`#`) are ignored. Example:

my_series.txt:

```
Arrested Development
Six Feet Under
True Detective
# this is a comment
```

Then call:

```
tv-series-find-episode-ids.py -i my_series.txt -o my_episode_ids.txt
```

Episode IDs for all the TV series mentioned in `my_series.txt` will be written to `my_episode_ids.txt` like this:

```
2510426
2580386
2639284
2545702
2639288
```

### 2. Download subtitles for passed IMDB IDs

Sign up at [OpenSubtitles.org](https://www.opensubtitles.org/). Consider buying a VIP account, otherwise you will hit the download limit very soon.

Set environment variables `OPENSUB_USER` and `OPENSUB_PASSWD` to contain your OpenSubtitles.org credentials.

```sh
export OPENSUB_USER='you@example.com'
export OPENSUB_PASSWD='yourpassword'
```

Then call:

```
tv-series-download-subs -i my_episode_ids.txt -o my_subs/
```

All the episodes's subtitles will be downloaded to the directory `my_subs/` as SRT files.

## Help

Call any of the scripts mentioned in [Usage](#usage) with the parameter `-h` or `--help` to see full documentation. Example:

```
tv-series-download-subs -h
```

## Contributing

__Feel free to remix this piece of software.__ See [NOTICE](./NOTICE) and [LICENSE](./LICENSE) for license information.

+ 56
- 0
setup.py View File

@@ -0,0 +1,56 @@
from setuptools import setup, find_packages
from codecs import open
from os import path

here = path.abspath(path.dirname(__file__))

with open(path.join(here, 'README.md'), encoding='utf-8') as f:
long_description = f.read()

setup(
name='tv_series_tools',

version='1.0.0',

description='Tools to work with TV series\'s subtitles.',
long_description=long_description,

url='https://lab.saloun.cz/jakub/tv-series-tools',

author='Jakub Valenta',
author_email='jakub@jakubvalenta.cz',

license='Apache Software License',

classifiers=[
'Development Status :: 3 - Alpha',
'Intended Audience :: Developers',
'Topic :: Artistic Software',
'License :: OSI Approved :: Apache Software License',
'Programming Language :: Python :: 2.7',
],

keywords='',

packages=find_packages(),

install_requires=[
'requests',
'imdbpy',
'python-opensubtitles>=0.2.dev0',
'pysrt',
'termcolor',
'moviepy',
],

entry_points={
'console_scripts': [
'tv-series-download-subs=tv_series.download_subs:download_subs_and_cache_results',
'tv-series-find-episode-ids=tv_series.find_episode_ids:find_and_write_episode_ids',
'tv-series-search-subs=tv_series.search_subs:search_and_approve_subs',
'tv-series-chech-approved-subs=tv_series.search_subs:check_approved_subs',
'tv-series-print-approved-subs=tv_series.search_subs:print_approved_subs',
'tv-series-video=tv_series.video:create_super_cut',
],
},
)

+ 5
- 0
tv-series-check-approved-subs View File

@@ -0,0 +1,5 @@
#!/usr/bin/env python

import tv_series.search_subs
if __name__ == '__main__':
tv_series.search_subs.check_approved_subs()

+ 5
- 0
tv-series-download-subs View File

@@ -0,0 +1,5 @@
#!/usr/bin/env python

import tv_series.download_subs
if __name__ == '__main__':
tv_series.download_subs.download_subs_and_cache_results()

+ 5
- 0
tv-series-find-episode-ids View File

@@ -0,0 +1,5 @@
#!/usr/bin/env python

import tv_series.find_episode_ids
if __name__ == '__main__':
tv_series.find_episode_ids.find_and_write_episode_ids()

+ 5
- 0
tv-series-print-approved-subs View File

@@ -0,0 +1,5 @@
#!/usr/bin/env python

import tv_series.search_subs
if __name__ == '__main__':
tv_series.search_subs.print_approved_subs()

+ 5
- 0
tv-series-search-subs View File

@@ -0,0 +1,5 @@
#!/usr/bin/env python

import tv_series.search_subs
if __name__ == '__main__':
tv_series.search_subs.search_and_approve_subs()

+ 5
- 0
tv-series-text View File

@@ -0,0 +1,5 @@
#!/usr/bin/env python

import tv_series.text
if __name__ == '__main__':
tv_series.text.main()

+ 5
- 0
tv-series-video View File

@@ -0,0 +1,5 @@
#!/usr/bin/env python

import tv_series.video
if __name__ == '__main__':
tv_series.video.create_super_cut()

+ 0
- 0
tv_series/__init__.py View File


+ 33
- 0
tv_series/common.py View File

@@ -0,0 +1,33 @@
SEP = ' :: '


def read_list_from_file(file_path, first_column_only=True):
items = []
try:
with open(file_path, 'r') as f:
for line in f:
line = line.strip()
if not line or line[0] == '#':
continue
if SEP not in line:
items.append(line)
continue
line_columns = line.split(SEP)
if first_column_only:
items.append(line_columns[0])
else:
items.append(line_columns)
except FileNotFoundError:
pass
return items


def write_list_to_file(file_path, items):
with open(file_path, 'a') as f:
for item in items:
if type(item) == tuple or type(item) == list:
f.write(SEP.join([str(i) for i in item]))
else:
f.write(item)
f.write('\n')
f.flush()

+ 135
- 0
tv_series/download_subs.py View File

@@ -0,0 +1,135 @@
import itertools
import os
import random
import sys
import time

try:
from http.client import HTTPException
except ImportError:
from httplib import HTTPException
try:
from xmlrpc.client import ProtocolError
except ImportError:
from xmlrpclib import ProtocolError

import gzip
try:
from StringIO import StringIO
except ImportError:
pass

import requests
from pythonopensubtitles.opensubtitles import OpenSubtitles

from tv_series import common


DEFAULT_TIMEOUT = 15
FILE_NAME_DOWNLOADED = 'episode_ids_downloaded.txt'
FILE_NAME_ERROR = 'episode_ids_failed.txt'


def _gzip_decompress(s):
"""Decompress a gzip compressed string.
Compatible with both Python 2 and 3."""
try:
return gzip.decompress(s)
except AttributeError:
with gzip.GzipFile(fileobj=StringIO(s)) as f:
return f.read()


def download_subs(ids, excl, dir_path, opensub, timeout=0):
for id in ids:
if id in excl:
print('IMDB ID SKIPPED {}'.format(id))
continue
print('IMDB ID {}'.format(id))
try:
if timeout:
time.sleep(timeout)
subs = opensub.search_subtitles([{
'imdbid': id,
'sublanguageid': 'eng'
}])
except HTTPException as e:
print(' ERROR HTTP exception {}'.format(e))
continue
except ProtocolError as e:
print(' ERROR XML-RPC exception {}'.format(e))
continue
if not subs:
print(' ERROR Subtitles not found')
continue
sub = subs[0]
file_path = os.path.join(dir_path, sub['SubFileName'])
if os.path.isfile(file_path):
print(u' ALREADY DOWNLOADED {} {}'
.format(sub['SubFileName'], sub['SubDownloadLink']))
continue
print(u' DOWNLOADING {} {}'
.format(sub['SubFileName'], sub['SubDownloadLink']))
r = requests.get(sub['SubDownloadLink'])
if r.status_code != 200 or not r.content:
print(u' ERROR HTTP request failed, status_code={}, text={}'
.format(r.status_code, r.text))
continue
with open(file_path, 'wb') as f:
print(u' WRITING {}'.format(file_path))
f.write(_gzip_decompress(r.content))
yield (id, sub['SubFileName'])


def download_subs_and_cache_results():
import argparse

parser = argparse.ArgumentParser(
description='TV Series Tools: Download subtitles for movies specified'
' by passed IMDB IDs'
)
parser.add_argument('--input', '-i', dest='inputfile', required=True,
help='IMDB IDs list file -- one IMDB ID per line')
parser.add_argument('--output', '-o', dest='outputdir', required=True,
help='path to a directory in which the subtitle SRT'
' files will be downloaded')
parser.add_argument('--cache', '-c', dest='cachedir', required=True,
help='cache location')
parser.add_argument('--shuffle', '-s', dest='shuffle', action='store_true',
help='shuffle the list of IMDB IDs')
parser.add_argument('--timeout', '-t', dest='timeout', type=int,
default=DEFAULT_TIMEOUT,
help='time in seconds between OpenSubtitles\'s API'
' calls, if not set {} is used'
.format(DEFAULT_TIMEOUT))
args = parser.parse_args()

opensub = OpenSubtitles()
opensub.login(os.environ['OPENSUB_USER'], os.environ['OPENSUB_PASSWD'])

ids = common.read_list_from_file(args.inputfile)
if args.shuffle:
random.shuffle(ids)

# Need to call list to make the list concatenation work in Python 2.
excl = list(itertools.chain.from_iterable(
[common.read_list_from_file(os.path.join(args.cachedir, f))
for f in (FILE_NAME_DOWNLOADED, FILE_NAME_ERROR)]
))

common.write_list_to_file(
os.path.join(args.cachedir, FILE_NAME_DOWNLOADED),
download_subs(
ids,
excl,
args.outputdir,
opensub,
timeout=args.timeout
)
)

sys.exit()


if __name__ == '__main__':
download_subs_and_cache_results()

+ 77
- 0
tv_series/find_episode_ids.py View File

@@ -0,0 +1,77 @@
import sys

from imdb import IMDb
from imdb import IMDbDataAccessError

from tv_series import common


def find_episode_ids(series_titles, ia):
for series_title in series_titles:
print('FIND ' + series_title)
ids = []
ia_result = ia.search_movie(series_title)
if not ia_result:
print(ia_result)
print(' ERROR Movie not found')
continue
ia_movie = [0]
for ia_movie in ia_result:
print(u'MOVIE {0}'.format(ia_movie['long imdb canonical title']))
ia.update(ia_movie)
if ia_movie['kind'] != 'tv series':
print(' ERROR Not a TV series')
continue
try:
ia.update(ia_movie, 'episodes')
try:
if not ia_movie['episodes']:
continue
except KeyError as e:
print(e)
continue
for season_no, episodes in ia_movie['episodes'].items():
for episode_no, episode in episodes.items():
print(u' EPISODE S{0:02d}E{1:02d} [{2}] {3}'.format(
int(season_no),
int(episode_no),
episode.movieID,
episode['title']
))
yield episode.movieID
except IMDbDataAccessError as e:
print(e)
break


def find_and_write_episode_ids():
import argparse

parser = argparse.ArgumentParser(
description='TV Series Tools: Find IMDB IDs for all episodes of ' +
'passed TV series'
)
parser.add_argument('--input', '-i', dest='inputfile', required=True,
help='TV series list file -- one series title per'
' line, empty lines and lines starting with the hash'
' sign are ignored')
parser.add_argument('--output', '-o', dest='outputfile', required=True,
help='output file -- episode IMDB IDs will be written'
' one ID per line, if the file exists it will not be'
' overwritte, but IMDB IDs not already included in the'
' file will be added')
args = parser.parse_args()

common.write_list_to_file(
args.outputfile,
find_episode_ids(
common.read_list_from_file(args.inputfile),
IMDb()
)
)

sys.exit()


if __name__ == '__main__':
find_and_write_episode_ids()

+ 287
- 0
tv_series/search_subs.py View File

@@ -0,0 +1,287 @@
import math
import os
import re
import readline
import sys

import pysrt
from termcolor import colored

from tv_series import common


def parse_sub_text(s):
return s.replace('\n', ' ')


def parse_sub_time(t):
return t.ordinal / 1000


def convert_sub_to_match(file_path, sub):
return {
'file_path': file_path,
'time_start': parse_sub_time(sub.start),
'time_end': parse_sub_time(sub.end),
}


def convert_match_to_answer(match, yes_or_no, start, end):
return (
yes_or_no.upper(),
match['file_path'],
match['time_start'],
match['time_end'],
start,
end,
)


def convert_answer_to_match(answer):
return {
'file_path': answer[1],
'time_start': float(answer[2]),
'time_end': float(answer[3]),
}


def find_subs_context(subs, current, no=1):
context = []
for i in range(current - no, current + no + 1):
if i < 0 or i >= len(subs):
continue
context.append(subs[i])
return context


def compile_regex(pattern):
return re.compile(pattern, flags=re.IGNORECASE)


def search_line(line, regex_list):
for i, regex in enumerate(regex_list):
m = regex.search(line)
if m:
return True
return False


def read_subs(file_path):
try:
return pysrt.open(file_path)
except UnicodeDecodeError:
print('ERROR Subtitle file "{}" could not be read.'.format(file_path))
return None


def iter_subs(dir_path):
d = os.scandir(dir_path)
for entry in sorted(d, key=lambda entry: entry.name):
if entry.name.startswith('.'):
continue
if entry.is_dir():
for ret in iter_subs(entry.path):
yield ret
continue
if not entry.is_file() or not entry.name.endswith('.srt'):
continue
subs = read_subs(entry.path)
if subs is not None:
yield (entry.path, subs)


def search_subs(subs_dir, excl, regex_list):
for file_path, subs in subs_dir:
for i, sub in enumerate(subs):
match = convert_sub_to_match(file_path, sub)
if match in excl:
print('ANSWERED', match)
continue
line = parse_sub_text(sub.text)
if not search_line(line, regex_list):
continue
subs_context = find_subs_context(subs, i, 2)
yield {
'file_path': match['file_path'],
'time_start': match['time_start'],
'time_end': match['time_end'],
'subs_context': subs_context,
}


def format_subs(subs, color=True):
if type(subs) != tuple and type(subs) != list:
subs = [subs]
middle = math.floor(len(subs) / 2)
formatted = []
for i, sub in enumerate(subs):
no = i - middle
if no == 0 and color:
text = colored(sub.text, 'red')
else:
text = sub.text
formatted.append('{no} {text:<80} {start} --> {end}'.format(
no=abs(no),
text=parse_sub_text(text),
start='{:02d}:{:02d}:{:02d}'.format(sub.start.hours, sub.start.minutes, sub.start.seconds),
end='{:02d}:{:02d}:{:02d}'.format(sub.end.hours, sub.end.minutes, sub.end.seconds),
))
return '\n'.join(formatted)


def format_sub_match_with_context(match, color=True):
if color:
file_path_formatted = colored(match['file_path'], attrs=('bold',))
else:
file_path_formatted = match['file_path']
return(
'\n'
'{file_path} {time_start} --> {time_end}\n'
'\n'
'{subs_context}\n'
'\n'
.format(
file_path=file_path_formatted,
time_start=match['time_start'],
time_end=match['time_end'],
subs_context=format_subs(match['subs_context'], color)
)
)


def approve_matches(matches):
for match in matches:
print(format_sub_match_with_context(match))

inp = None
while inp is None or (inp not in ('y', 'n', 'x', '')
and not re.match(r'^\d{1,2}$', inp)):
print('Do you like this match? "y" = yes, "n" = no, "x" = ask'
' again next time, "AB" start at line number A and end at B')
inp = input('--> ')

if inp in ('', 'x'):
continue
if inp in ('y', 'n'):
yes_or_no = inp.upper()
no_start = 0
no_end = no_start
elif len(inp) == 1:
yes_or_no = 'y'
no_start = int(inp)
no_end = no_start
else:
yes_or_no = 'y'
no_start = -1 * int(inp[0])
no_end = int(inp[1])

i_middle = math.floor(len(match['subs_context']) / 2)
i_start = i_middle + no_start
i_end = i_middle + no_end
yield convert_match_to_answer(
match,
yes_or_no,
parse_sub_time(match['subs_context'][i_start].start),
parse_sub_time(match['subs_context'][i_end].end)
)


def filter_approved_answers(answers):
for answer in answers:
if answer[0] == 'Y':
yield answer


def add_subs_context_to_matches(matches, no=1):
for match in matches:
subs = read_subs(match['file_path'])
if subs is None:
continue
for i, sub in enumerate(subs):
sub_match = convert_sub_to_match(match['file_path'], sub)
if sub_match != match:
continue
match['subs_context'] = find_subs_context(subs, i, no)
yield match


def search_and_approve_subs():
import argparse

parser = argparse.ArgumentParser(
description='TV Series Tools: Search subtitles'
)
parser.add_argument('--input', '-i', dest='inputdir', required=True,
help='path to a directory with the subtitle SRT files')
parser.add_argument('--output', '-o', dest='outputfile', required=True,
help='path to a file in which the answers will be'
' stored')
parser.add_argument('--patterns', '-p', dest='patterns', required=True,
help='path to a file with search patterns')
args = parser.parse_args()

excl = [
convert_answer_to_match(answer)
for answer in common.read_list_from_file(args.outputfile, False)
]
regex_list = [
compile_regex(pattern)
for pattern in common.read_list_from_file(args.patterns)
]
subs_dir = iter_subs(args.inputdir)
matches_with_context = search_subs(subs_dir, excl, regex_list)
answers = approve_matches(matches_with_context)

common.write_list_to_file(args.outputfile, answers)

sys.exit()


def check_approved_subs():
import argparse

parser = argparse.ArgumentParser(
description='TV Series Tools: Check approved subtitles'
)
parser.add_argument('--input', '-i', dest='inputfile', required=True,
help='path to a file with the answers')
parser.add_argument('--output', '-o', dest='outputfile', required=True,
help='path to a file in which the new answers will be'
' stored')
args = parser.parse_args()

answers = common.read_list_from_file(args.inputfile, False)
approved = filter_approved_answers(answers)
matches = [convert_answer_to_match(answer) for answer in approved]
matches_with_context = add_subs_context_to_matches(matches, 3)
new_answers = approve_matches(matches_with_context)

common.write_list_to_file(args.outputfile, new_answers)

sys.exit()


def print_approved_subs():
import argparse

parser = argparse.ArgumentParser(
description='TV Series Tools: Print answers with context'
)
parser.add_argument('--input', '-i', dest='inputfile', required=True,
help='path to a file with the answers')
args = parser.parse_args()

answers = common.read_list_from_file(args.inputfile, False)
approved = filter_approved_answers(answers)
matches = [convert_answer_to_match(answer) for answer in approved]
matches_with_context = add_subs_context_to_matches(matches, 3)
[
print(format_sub_match_with_context(match, False))
for match in matches_with_context
]

sys.exit()


if __name__ == '__main__':
seach_and_approve_subs()

+ 32
- 0
tv_series/text.py View File

@@ -0,0 +1,32 @@
#!/usr/bin/env python

from moviepy.editor import *

from tv_series import common

def main():
import argparse

parser = argparse.ArgumentParser(
description='TV Series Tools: Text'
)
parser.add_argument('--input', '-i', dest='inputfile', required=True,
help='input file')
args = parser.parse_args()

inp = common.read_list_from_file(args.inputfile, False)

SIZE = (1280, 720)

for file_path, text in inp:
text_clip = TextClip(text, color='white', font="Arial", fontsize=48)
composite_clip = CompositeVideoClip(
[text_clip.set_pos('center')],
size=SIZE
)
final_clip = composite_clip.subclip(0,3)
final_clip.write_videofile(file_path, fps=24, codec='png')


if __name__ == '__main__':
main()

+ 171
- 0
tv_series/video.py View File

@@ -0,0 +1,171 @@
import math
import os
import sys

from moviepy.editor import *
from moviepy.video.tools.subtitles import SubtitlesClip

from tv_series import common


DEFAULT_LIMIT = -1
DEFAULT_FPS = 24
DEFAULT_EXT = '.avi'
DEFAULT_DIR = 'clips'

VIDEO_FORMAT_SIZE_W = 640
VIDEO_FORMAT_SIZE_H = 360

DEBUG_SKIP = ()


def render(clip, file_path, fps=None, ext=None):
if fps is None:
fps = DEFAULT_FPS
if ext is None:
ext = DEFAULT_EXT
base, _ = os.path.splitext(file_path)
if ext == '.avi':
codec = 'png'
clip.write_videofile(base + ext, fps=fps, codec=codec)


def subtitle_generator(txt):
return TextClip(txt, font='Georgia-Regular', fontsize=24, color='white')


def parse_duration(duration):
return duration.replace(',', '.')


def format_duration(duration):
return duration.replace(':', '_').replace('.', '_')


def format_clip_file_path(file_path, cut_start, cut_end):
file_dir, file_basename = os.path.split(file_path)
file_name, file_ext = os.path.splitext(file_basename)
new_path_without_ext = os.path.join(file_dir, DEFAULT_DIR, file_name)
return '{path}-{start}-{end}{ext}'.format(
path=new_path_without_ext,
start=format_duration(cut_start),
end=format_duration(cut_end),
ext=file_ext
)


def create_super_cut():
import argparse

parser = argparse.ArgumentParser(
description='TV Series Tools: Video'
)
parser.add_argument('--input', '-i', dest='inputfile', required=True,
help='file path to a file containing info on how to'
' cut the clips')
parser.add_argument('--output', '-o', dest='outputfile', required=True,
help='output video file path')
parser.add_argument('--clips', '-c', dest='clipsdir', required=True,
help='clips video files location')
parser.add_argument('--join', '-j', dest='join', action='store_true',
help='concat cut video clips')
parser.add_argument('--change-fps', '-f', dest='change_fps', type=int,
default=DEFAULT_FPS,
help='video fps')
parser.add_argument('--resize-width', '-rw', dest='resize_width',
type=int,
help='resize width; you must set both --resize-width'
' and --resize-height')
parser.add_argument('--resize-height', '-rh', dest='resize_height',
type=int,
help='resize height; you must set both --resize-width'
' and --resize-height')
parser.add_argument('--limit', '-l', dest='limit', type=int,
default=DEFAULT_LIMIT,
help='process only first <limit> clips')
parser.add_argument('--speed', '-s', dest='speed', type=float,
help='speed of the composition; the standard speed'
' will be multiplied by this number, hence'
' 1 = normal speed, 0.5 = half the normal speed,'
' 3 = three times as fast, etc.')
args = parser.parse_args()

inp = common.read_list_from_file(args.inputfile, False)
if not inp:
sys.exit(1)

video_clips = {}
all_clips = []

i = 0
for file_name, start, end in inp:
if i == args.limit:
break
i = i + 1

file_path = os.path.join(args.clipsdir, file_name)
subtitles_path = os.path.splitext(file_path)[0] + '.srt'
cut_start = parse_duration(start)
cut_end = parse_duration(end)
print(
'CLIP {}\n'
' {}\n'
' {}\n'
' {} --> {}'
.format(
i,
file_path,
subtitles_path,
cut_start,
cut_end
)
)
if file_name in DEBUG_SKIP:
print(' SKIP')
continue
if not args.join:
clip_file_path = format_clip_file_path(file_path, cut_start, cut_end)
if os.path.isfile(clip_file_path):
print(' SKIP EXISTS')
continue
if not os.path.isfile(file_path):
print(' SKIP FILE NOT FOUND')
continue

if file_path not in video_clips:
video_clips[file_path] = VideoFileClip(file_path)
video_clip = video_clips[file_path]
video_sub_clip = video_clip.subclip(
cut_start,
cut_end
)
if args.change_fps:
video_sub_clip = video_sub_clip.set_fps(args.change_fps)
if args.resize_width and args.resize_height:
video_sub_clip = video_sub_clip.resize(width=args.resize_width, height=args.resize_height)
#subtitles_clip = SubtitlesClip(
# subtitles_path,
# subtitle_generator
#)
composite_clip = video_sub_clip
#composite_clip = CompositeVideoClip([video_sub_clip, subtitles_clip])
#composite_clips.append(composite_clip)

if args.speed is not None:
# composite_clip = composite_clip.speedx(factor=args.speed)
pass

if args.join:
all_clips.append(composite_clip)
else:
render(composite_clip, clip_file_path, fps=args.change_fps)

if args.join:
joined_clip = concatenate_videoclips(all_clips)
render(joined_clip, args.outputfile, fps=args.change_fps)

sys.exit()


if __name__ == '__main__':
create_super_cut()

Loading…
Cancel
Save