Skip to content

Commit

Permalink
first commit
Browse files Browse the repository at this point in the history
  • Loading branch information
mhajiloo committed Oct 27, 2017
0 parents commit a506181
Show file tree
Hide file tree
Showing 10 changed files with 436 additions and 0 deletions.
106 changes: 106 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,106 @@
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class

# C extensions
*.so

# Distribution / packaging
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
*.egg-info/
.installed.cfg
*.egg
MANIFEST

# PyInstaller
# Usually these files are written by a python script from a template
# before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec

# Installer logs
pip-log.txt
pip-delete-this-directory.txt

# Unit test / coverage reports
htmlcov/
.tox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*.cover
.hypothesis/

# Translations
*.mo
*.pot

# Django stuff:
*.log
.static_storage/
.media/
local_settings.py

# Flask stuff:
instance/
.webassets-cache

# Scrapy stuff:
.scrapy

# Sphinx documentation
docs/_build/

# PyBuilder
target/

# Jupyter Notebook
.ipynb_checkpoints

# pyenv
.python-version

# celery beat schedule file
celerybeat-schedule

# SageMath parsed files
*.sage.py

# Environments
.env
.venv
env/
venv/
ENV/
env.bak/
venv.bak/

# Spyder project settings
.spyderproject
.spyproject

# Rope project settings
.ropeproject

# mkdocs documentation
/site

# mypy
.mypy_cache/

.idea/
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
The MIT License (MIT)

Copyright (c) 2017 Majid Hajiloo

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
Empty file added sereh/__init__.py
Empty file.
5 changes: 5 additions & 0 deletions sereh/__version__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
__title__ = 'sereh'
__description__ = 'Subtitle tools especially for Persians'
__author = 'Majid Hajiloo'
__url__ = 'https://github.com/mhajiloo/sereh'
__version__ = '0.0.1'
45 changes: 45 additions & 0 deletions sereh/commandline.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
#!/usr/bin/env python
import argparse
import os
import re

from sereh.subfile import Subtitle

SHIFT_REGEX = r'^(-?\d+h)?(-?\d+m)?(-?\d+s)?(-?\d+ms)?$'


def shift_validator(string):
if string is None:
return string

if not re.match(SHIFT_REGEX, string):
raise argparse.ArgumentTypeError('must be in the form []h[]m[]s[]ms, eg. 1h22m1s100ms, 1400ms, -1h-22m')

return string


class FullAbsPathAction(argparse.Action):
def __call__(self, parser, namespace, values, option_string=None):
setattr(namespace, self.dest, os.path.abspath(os.path.expanduser(values)))


class ShiftAction(argparse.Action):
def __call__(self, parser, namespace, values, option_string=None):
shift = [int(re.sub('[^\d-]', '', x)) if x else 0 for x in re.findall(SHIFT_REGEX, values)[0]]
setattr(namespace, self.dest, tuple(shift))


def main():
parser = argparse.ArgumentParser(prog='sereh', description='Sereh Subtitle tools.')
parser.add_argument('srt', type=str, help='Source subtitle path', action=FullAbsPathAction)
parser.add_argument('-e', '--output-encoding', type=str, dest='encoding', default='utf-8', choices=['utf-8', 'cp1256'],
help='New subtitle encoding')
parser.add_argument('-s', '--shift', type=shift_validator, dest='shift', action=ShiftAction, default=None, help='Shift subtitle')

args = parser.parse_args()

subtitle = Subtitle(args.srt)
if args.shift is not None:
subtitle.shift(*args.shift)

subtitle.save(encoding=args.encoding)
10 changes: 10 additions & 0 deletions sereh/subexception.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
class SerehException(Exception):
pass


class InvalidExtension(SerehException):
pass


class InvalidEncoding(SerehException):
pass
105 changes: 105 additions & 0 deletions sereh/subfile.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
import re

try:
from pathlib import Path
except ImportError:
from pathlib2 import Path

from chardet import UniversalDetector

from sereh.subexception import InvalidExtension
from sereh.subitem import SubtitleItem


class Subtitle(object):
SUFFIX = ('.srt',)
_items = []
TIME_SEPARATOR = ' --> '

def __init__(self, path):
subtitle_path = Path(path)
if not subtitle_path.is_file():
raise FileNotFoundError

if subtitle_path.suffix not in self.SUFFIX:
raise InvalidExtension('Invalid file extension!')

self._path = path
self._name = subtitle_path.name

self._detect_encoding()
self._prepare()

@property
def path(self):
return self._path

@property
def encoding(self):
return self._encoding

def _detect_encoding(self, max_line=200):
detector = UniversalDetector()

with open(self._path, 'rb') as f:
for num, line in enumerate(f, 1):
if num > max_line:
break
detector.feed(line)
if detector.done:
break

detector.close()

if detector.result['confidence'] > 0.9:
self._encoding = detector.result['encoding']
else:
with open(self._path, encoding='cp1256') as f:
for num, line in enumerate(f, 1):
if num > max_line:
break

self._encoding = 'cp1256'

def _prepare(self):
with open(self._path, encoding=self.encoding) as f:
self._subtitle = f.read()

dic = {'ي': 'ی', 'ك': 'ک'}

pattern = re.compile('|'.join(dic.keys()))
self._subtitle = pattern.sub(lambda x: dic[x.group()], self._subtitle)

regex = r"(\d+\s*)\n([\d:,]+)\s+-{2}\>\s+([\d:,]+)\s*\n([\s\S]*?(?=\n{2}|$))"
self._items = [SubtitleItem(*i) for i in re.findall(regex, self._subtitle, re.IGNORECASE)]

def save(self, path=None, encoding=None):
path = path or (self._path + '_new.srt')
encoding = encoding or self._encoding

with open(path, 'w', encoding=encoding) as f:
f.write(self._get_srt())

def _get_srt(self):
srt = ''
linesep = '\r\n'

for i in self._items:
srt += linesep.join([str(i.index), self.TIME_SEPARATOR.join([str(i.start), str(i.end)]), i.text])
srt += linesep * 2

return srt

def shift(self, *args, **kwargs):
for i in self._items:
i.shift(*args, **kwargs)

def __getitem__(self, key):
return self._items[key]

def __iter__(self):
for i in self._items:
yield i

def __str__(self):
return self._name
37 changes: 37 additions & 0 deletions sereh/subitem.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
from sereh.subtime import SubtitleTime


class SubtitleItem(object):
PATTERN = '[{} - {}] {}'

def __init__(self, index=0, start=None, end=None, text=''):
self._index = int(str(index).strip())
self._start = SubtitleTime.prepare_time(start)
self._end = SubtitleTime.prepare_time(end)
self._text = str(text).strip()

@property
def index(self):
return self._index

@property
def start(self):
return self._start

@property
def end(self):
return self._end

@property
def text(self):
return self._text

def duration(self):
return self._end - self._start

def shift(self, *args, **kwargs):
self._start.shift(*args, **kwargs)
self._end.shift(*args, **kwargs)

def __str__(self):
return self.PATTERN.format(self._start, self._end, self._text)
Loading

0 comments on commit a506181

Please sign in to comment.