TVRenamer¶
Automatic TV Episode Renamer
Features¶
- Rename TV episodes
- Naming enrichment using Available Data Services
- Processing changes cached
- Deploy as python library or Docker Container
Contents:
Getting Started¶
Running locally / cron¶
Create virtualenv
virtualenv ~/tvrenamer/
Start virtualenv
cd ~/tvrenamer
source bin/activate
Install tvrenamer in the virtualenv:
mkdir etc
pip install tvrenamer
Running tvrenamer:
tvrename
Running tvrenamer from crontab:
crontab -e
@hourly /home/USER/tvrenamer/bin/tvrename >> /home/USER/tvrenamer/etc/tvrenamer/cron.log 2>&1
Note
As part of installing in virtualenv the sample configuration files will be installed into the ~/tvrenamer/etc/tvrenamer folder.
Running as a Container¶
The following will start a container using the default command tvrename using the configurations provided by exposing a volume to the container to the mount point /usr/etc/tvrenamer. The other volume mount points are used to provide direct access to a directory where downloaded files exist and the base directory to your media library.
The pre-built images are published on DockerHub and Quay
docker pull shad7/tvrenamer
docker run --rm \
-v /path/to/downloads:/videos/downloads \
-v /path/to/library:/videos/library \
-v /path/to/configs/dir:/usr/etc/tvrenamer \
shad7/tvrenamer
docker pull quay.io/shad7/tvrenamer
docker run --rm \
-v /path/to/downloads:/videos/downloads \
-v /path/to/library:/videos/library \
-v /path/to/configs/dir:/usr/etc/tvrenamer \
quay.io/shad7/tvrenamer
Congiguration
Possible configuration file locations (General to specific):
/etc
/etc/tvrenamer
# if virtualenv used
~/tvrenamer/etc
~/tvrenamer/etc/tvrenamer
~
~/.tvrenamer
<current working directory>
Note
configuration filename: tvrenamer.conf
virtualenv approach is the recommended approach. Multiple configuration files are supported such that each supported folder is checked for a configuration file and loaded from most general to more specific. Each successive file will override values from the previous.
The folder of the most specific configuration file found will be considered the resource folder where all log files are stored by default.
Command line interface:
usage: tvrename [-h] [--cache_enabled] [--config-dir DIR] [--config-file PATH]
[--console_output_enabled] [--dryrun] [--logfile LOG_FILE]
[--loglevel LOG_LEVEL] [--nocache_enabled]
[--noconsole_output_enabled] [--nodryrun] [--version]
[locations [locations ...]]
positional arguments:
locations specify the paths to search for files to rename.
optional arguments:
-h, --help show this help message and exit
--cache_enabled Enable caching results
--config-dir DIR Path to a config directory to pull *.conf files from.
This file set is sorted, so as to provide a
predictable parse order if individual options are
over-ridden. The set is parsed after the file(s)
specified via previous --config-file, arguments hence
over-ridden options in the directory take precedence.
--config-file PATH Path to a config file to use. Multiple config files
can be specified, with values in later files taking
precedence. The default files used are: None.
--console_output_enabled
Enable console output
--dryrun Practice run where no changes are applied.
--logfile LOG_FILE specify name of log file default: None
--loglevel LOG_LEVEL specify logging level to log messages: None
--nocache_enabled The inverse of --cache_enabled
--noconsole_output_enabled
The inverse of --console_output_enabled
--nodryrun The inverse of --dryrun
--version show program's version number and exit
- Available Configuration Options
- A generated configuration file that contains each option a designation for required, a help message, default value, and associated type.
Available Configuration Options¶
DEFAULT¶
-
locations
¶ Type: multi-valued Default: specify the paths to search for files to rename.
-
dryrun
¶ Type: boolean Default: false
Practice run where no changes are applied.
-
cache_enabled
¶ Type: boolean Default: true
Enable caching results
-
console_output_enabled
¶ Type: boolean Default: true
Enable console output
-
logfile
¶ Type: string Default: tvrenamer.log
specify name of log file default: the value above
-
loglevel
¶ Type: string Default: info
Valid Values: none, critical, error, warning, info, debug, trace specify logging level to log messages: %(choices)s
-
move_files_enabled
¶ Type: boolean Default: false
Move files to library during rename.
-
overwrite_file_enabled
¶ Type: boolean Default: false
Overwrite existing files during rename.
-
default_library
¶ Type: string Default: Default library path to relocate files to.
-
libraries
¶ Type: list Default: Library paths to relocate files to.
-
language
¶ Type: string Default: en
Lanuage to lookup metadata in.
-
valid_extensions
¶ Type: list Default: File extensions considered valid.
-
filename_blacklist
¶ Type: list Default: File names exclused from processing.
-
input_filename_replacements
¶ Type: list Default: List of mappings of string pattern replacements.
-
input_series_replacements
¶ Type: dict Default: Mapping of parsed series name to replacement values.
-
output_series_replacements
¶ Type: dict Default: Mapping of lookup series name to replacement values.
-
lookup_service
¶ Type: string Default: tvdb
Name of lookup service to use for metadata retrieval.
-
directory_name_format
¶ Type: string Default: .
Format for naming library directories.
-
filename_format_ep
¶ Type: string Default: %(seriesname)s - %(seasonnumber)02dx%(episode)s - %(episodename)s%(ext)s
Format for naming files with episode name.
-
episode_single
¶ Type: string Default: %02d
Format for episode numbers.
-
episode_separator
¶ Type: string Default: -
Separator to join multiple episode numbers.
-
multiep_join_name_with
¶ Type: string Default: ", "
Separator to join multiple episodes.
-
multiep_format
¶ Type: string Default: %(epname)s (%(episodemin)s-%(episodemax)s)
Format for naming multiple episodes.
-
filename_character_blacklist
¶ Type: string Default: Characters to ignore within filename.
-
replacement_character
¶ Type: string Default: _
Character used to replace invalid characters.
-
output_filename_replacements
¶ Type: list Default: List of mappings of string pattern replacements.
cache¶
-
dbfile
¶ Type: string Default: $config_dir/cache.json
The full path of the database storage.
tvdb¶
-
apikey
¶ Type: string Default: <None>
API key from your TVDB account ENV[‘TVDB_API_KEY’]
-
username
¶ Type: string Default: <None>
Username from your TVDB account ENV[‘TVDB_USERNAME’]
-
userpass
¶ Type: string Default: <None>
Password from your TVDB account ENV[‘TVDB_PASSWORD’]
-
service_url
¶ Type: string Default: https://api-dev.thetvdb.com
the url for thetvdb api service
-
verify_ssl_certs
¶ Type: boolean Default: true
flag for validating ssl certs for service url (https)
-
select_first
¶ Type: boolean Default: false
flag for selecting first series from search results
trakt¶
-
client_id
¶ Type: string Default: <None>
client id from your trakt account ENV[‘TRAKT_CLIENT_ID’]
-
client_secret
¶ Type: string Default: <None>
client secret from your trakt account ENV[‘TRAKT_CLIENT_SECRET’]
Available Data Services¶
trakt¶
Provides access trakt data service to lookup TV Series information.
Services used from trakt:
- search series by name
- lookup series by id
- get episode name(s) by season number and episode number(s)
tvdb¶
Provides access thetvdb data service to lookup TV Series information.
Services used from thetvdb:
- search series by name
- lookup series by id
- get episode name(s) by season number and episode number(s)
Available Results Processors¶
cache¶
Result processor that cache output from execution.
noop¶
Result processor that does nothing.
print¶
Result processor that dumps output to screen from execution.
Modules¶
tvrenamer package¶
Subpackages¶
tvrenamer.cache package¶
Private database API implemented for database operations.
-
class
tvrenamer.cache.api.
DatabaseAPI
(conf)¶ Bases:
object
Public APIs to perform on the database.
Initialize new instance.
Parameters: conf (oslo_config.cfg.ConfigOpts) – an instance of configuration file -
clear
()¶ Clear database.
-
create
(instance)¶ Create the instance to the database
Parameters: instance – an instance of modeled data object Returns: record id of created record Return type: int
-
save
(instance)¶ Save (create or update) the instance to the database
Parameters: instance – an instance of modeled data object
-
update
(instance, condition)¶ Update the instance to the database
Parameters: - instance – an instance of modeled data object
- condition – condition evaluated to determine record(s) to update
Returns: record id updated or None
Return type: int
-
Provides access to cache API for saving data.
-
tvrenamer.cache.
dbapi
(conf=<oslo_config.cfg.ConfigOpts object>)¶ Retrieves an instance of the configured database API.
Parameters: conf (oslo_config.cfg.ConfigOpts) – an instance of the configuration file Returns: database API instance Return type: DatabaseAPI
tvrenamer.common package¶
Output formatters using prettytable.
-
tvrenamer.common.table.
write_output
(data)¶
-
tvrenamer.common.tools.
make_opt_list
(opts, group)¶ Generate a list of tuple containing group, options
Parameters: - opts (list) – option lists associated with a group
- group (str) – name of an option group
Returns: a list of (group_name, opts) tuples
Return type: list
tvrenamer.core package¶
Represents the state of a TV Episode based on a filename and additional information from a data service.
Available actions on the Episode:
parse: retrieve information about TV Episode from elements of name
enhance: lookup additional information based on parsed elements
- rename: change the name of file based on most up-to-date info
and optionally change location.
The only input is an absolute path of a filename. Everything is controlled via the provided configuration.
-
class
tvrenamer.core.episode.
Episode
(epfile)¶ Bases:
object
Represents a TV episode.
Parameters: epfile (str) – absolute path and filename of media file -
api
¶
-
as_dict
()¶
-
enhance
(*args, **kwargs)¶ Load metadata from a data service to improve naming.
Raises: - tvrenamer.exceptions.ShowNotFound – when unable to find show/series name based on parsed name
- tvrenamer.exceptions.EpisodeNotFound – when unable to find episode name(s) based on parsed data
-
format_name
(*args, **kwargs)¶ Formats the media file based on enhanced metadata.
The actual name of the file and even the name of the directory structure where the file is to be stored.
-
parse
(*args, **kwargs)¶ Extracts component keys from filename.
Raises: - tvrenamer.exceptions.InvalidFilename – when filename was not parseable
- tvrenamer.exceptions.ConfigValueError – when regex used for parsing was incorrectly configured
-
rename
(*args, **kwargs)¶ Renames media file to formatted name.
After parsing data from initial media filename and searching for additional data to using a data service, a formatted filename will be generated and the media file will be renamed to the generated name and optionally relocated.
-
status
¶ Provides current status of processing episode.
Structure of status:
original_filename => formatted_filename, state, messagesReturns: mapping of current processing state Return type: dict
-
-
tvrenamer.core.episode.
state
(pre, post, attr='state')¶ State decorator
-
tvrenamer.core.formatter.
apply_replacements
(cfile, replacements)¶ Applies custom replacements.
- mapping(dict), where each dict contains:
‘match’ - filename match pattern to check against, the filename replacement is applied.
‘replacement’ - string used to replace the matched part of the filename
‘is_regex’ - if True, the pattern is treated as a regex. If False, simple substring check is used (if ‘match’ in filename). Default is False
‘with_extension’ - if True, the file extension is not included in the pattern matching. Default is False
Example replacements:
{'match': ':', 'replacement': '-', 'is_regex': False, 'with_extension': False, }
Parameters: - cfile (str) – name of a file
- replacements (list) – mapping(dict) filename pattern matching directives
Returns: formatted filename
Return type: str
-
tvrenamer.core.formatter.
clean_series_name
(seriesname)¶ Cleans up series name.
By removing any . and _ characters, along with any trailing hyphens.
Is basically equivalent to replacing all _ and . with a space, but handles decimal numbers in string, for example:
>>> _clean_series_name("an.example.1.0.test") 'an example 1.0 test' >>> _clean_series_name("an_example_1.0_test") 'an example 1.0 test'
-
tvrenamer.core.formatter.
find_library
(series_path)¶ Search for the location of a series within the library.
Parameters: series_path (str) – name of the relative path of the series Returns: library path Return type: str
-
tvrenamer.core.formatter.
format_dirname
(series_name, season_number)¶ Generates a directory name based on metadata using configured format.
Parameters: - series_name (str) – name of TV series
- season_number (int) – the numeric season of series
Returns: formatted directory name using input values and configured format
Return type: str
-
tvrenamer.core.formatter.
format_filename
(series_name, season_number, episode_numbers, episode_names, extension)¶ Generates a filename based on metadata using configured format.
Parameters: - series_name (str) – name of TV series
- season_number (int) – the numeric season of series
- episode_numbers (list(int)) – the numeric episode of the series
- episode_names (list(str)) – episode title of the series
- extension (str) – media file extension
Returns: formatted filename using input values and configured format
Return type: str
-
tvrenamer.core.formatter.
format_location
(series_name, season_number)¶
-
tvrenamer.core.parser.
parse_filename
(filename)¶ Parse media filename for metadata.
Parameters: filename (str) – the name of media file Returns: dict of metadata attributes found in filename or None if no matching expression. Return type: dict
Regular expression patterns for filename formats.
Supported filename formats:
* Sample.Show.S01E01.S01E02.S01E03.S01E04.eps.mp4
* Sample-Show.S02e22e23e24.avi
* Sample.Show.3x12.3x13.3x14.avi
* Sample.Show.4x4x5x6.mp4
* Sample.Show.S02E11-15-stuff.mkv
* Sample-Show.2x11-15.avi
* Sample-Show.[3x11-13].mp4
* Sample.Show-[013].avi
* Sample.S0202.mp4
* Sample_Show-7x17.avi
* Sample-Show S09.E11.mkv
* Sample-Show S09_E11.mkv
* Sample-Show S09 - E11.mkv
* Sample_Show-[09.01].avi
* Sample.Show - S9 E 9.avi
* SampleShow - episode 1219 [S 13 - E 07].mkv
* SampleShow - episode 1219 [S 13 Ep 07].avi
* Sample Show 2 of 7.mp4
* Sample.Show.Part.1.and.Part.2.avi
* Sample.Show.pt.1 & pt 2 & pt.3.avi
* Sample Show part 5.mkv
* Sample.Show season 10 episode 15.mp4
* Sample Show 909.mkv
* Sample Show 1011.avi
* Sample Show e19.mp4
-
tvrenamer.core.patterns.
get_expressions
()¶ Retrieve compiled pattern expressions.
Returns: compiled regular expressions for supported filename formats Return type: list
-
tvrenamer.core.renamer.
execute
(filename, formatted_name)¶ Renames a file based on the name generated using metadata.
Parameters: - filename (str) – absolute path and filename of original file
- formatted_name (str) – absolute path and new filename
-
tvrenamer.core.watcher.
retrieve_files
()¶ Get list of files found in provided locations.
Search through the paths provided to find files for processing.
Returns: absolute path of filename Return type: list
tvrenamer.processors package¶
Provides the base result processor abstract class.
-
class
tvrenamer.processors.base.
EnabledExtensionManager
¶ Bases:
stevedore.enabled.EnabledExtensionManager
Extends stevedore.enabled.EnabledExtensionManaer.
Provides default inputs for the manager.
-
map
(func, *args, **kwds)¶
-
sorted_extensions
()¶
-
-
class
tvrenamer.processors.base.
ResultProcessorBase
¶ Bases:
object
Abstract class that provides the structure of a result processor.
-
enabled
¶ Determines if a processor plugin is enabled for processing data.
-
priority
¶ Processor priority used for sorting to determine execution order.
-
process
(data)¶ Process the results from episode processing.
Parameters: data (list) – result instances
-
-
class
tvrenamer.processors.cache.
CacheResults
¶ Bases:
tvrenamer.processors.base.ResultProcessorBase
Result processor that cache output from execution.
-
enabled
¶ Determines if a processor plugin is enabled for processing data.
-
priority
¶ Processor priority used for sorting to determine execution order.
-
process
(data)¶ Process the results from episode processing.
Parameters: data (list) – result instances
-
-
class
tvrenamer.processors.noop.
NoopResults
¶ Bases:
tvrenamer.processors.base.ResultProcessorBase
Result processor that does nothing.
-
enabled
¶ Determines if a processor plugin is enabled for processing data.
-
priority
¶ Processor priority used for sorting to determine execution order.
-
process
(data)¶ Process the results from episode processing.
Parameters: data (list) – result instances
-
-
class
tvrenamer.processors.printer.
PrintResults
¶ Bases:
tvrenamer.processors.base.ResultProcessorBase
Result processor that dumps output to screen from execution.
-
enabled
¶ Determines if a processor plugin is enabled for processing data.
-
priority
¶ Processor priority used for sorting to determine execution order.
-
process
(data)¶ Process the results from episode processing.
Parameters: data (list) – result instances
-
tvrenamer.services package¶
-
class
tvrenamer.services.base.
Service
¶ Bases:
object
-
get_episode_name
(series, episode_numbers, season_number)¶ Perform lookup for name of episode numbers for a given series.
Parameters: - series (object) – instance of a series
- episode_numbers (list) – the episode sequence number
- season_number (int) – numeric season of series
Returns: list of episode name
Return type: list(str)
-
get_series_by_id
(series_id)¶ Perform lookup for series
Parameters: series_id (int) – series id of series Returns: instance of series Return type: object
-
get_series_by_name
(series_name)¶ Perform lookup for series
Parameters: series_name (str) – series name found within filename Returns: instance of series Return type: object
-
get_series_name
(series)¶ Perform lookup for name of series
Parameters: series (object) – instance of a series Returns: name of series Return type: str
-
-
class
tvrenamer.services.tvdb.
TvdbService
¶ Bases:
tvrenamer.services.base.Service
Provides access thetvdb data service to lookup TV Series information.
Services used from thetvdb:
- search series by name
- lookup series by id
- get episode name(s) by season number and episode number(s)
-
get_episode_name
(series, episode_numbers, season_number)¶ Perform lookup for name of episode numbers for a given series.
Parameters: - series (object) – instance of a series
- episode_numbers (list) – the episode sequence number
- season_number (int) – numeric season of series
Returns: list of episode name
Return type: list(str)
-
get_series_by_id
(series_id)¶ Perform lookup for series
Parameters: series_id (int) – series id of series Returns: instance of series Return type: object
-
get_series_by_name
(series_name)¶ Perform lookup for series
Parameters: series_name (str) – series name found within filename Returns: instance of series Return type: object
-
get_series_name
(series)¶ Perform lookup for name of series
Parameters: series (object) – instance of a series Returns: name of series Return type: str
Submodules¶
tvrenamer.cli module¶
Command-line interface to the TvRenamer APIs
-
tvrenamer.cli.
main
(*args, **kwargs)¶
tvrenamer.constants module¶
Application constants.
tvrenamer.exceptions module¶
Exceptions used through-out tvrenamer.
-
exception
tvrenamer.exceptions.
BaseTvRenamerException
¶ Bases:
exceptions.Exception
Base exception all tvrenamers exceptions inherit from.
-
exception
tvrenamer.exceptions.
ConfigValueError
¶ Bases:
tvrenamer.exceptions.BaseTvRenamerException
Raised if the config file is malformed or unreadable.
-
exception
tvrenamer.exceptions.
DataRetrievalError
¶ Bases:
tvrenamer.exceptions.BaseTvRenamerException
Raised when unable to retrieve data.
An error (such as a network problem) prevents tvrenamer from being able to retrieve data such as episode name
-
exception
tvrenamer.exceptions.
EpisodeNotFound
¶ Bases:
tvrenamer.exceptions.DataRetrievalError
Raised when episode cannot be found.
-
exception
tvrenamer.exceptions.
InvalidFilename
¶ Bases:
tvrenamer.exceptions.BaseTvRenamerException
Raised when a file is parsed, but no episode info can be found.
-
exception
tvrenamer.exceptions.
SeasonNotFound
¶ Bases:
tvrenamer.exceptions.DataRetrievalError
Raised when requested season cannot be found.
-
exception
tvrenamer.exceptions.
ShowNotFound
¶ Bases:
tvrenamer.exceptions.DataRetrievalError
Raised when a show cannot be found.
tvrenamer.manager module¶
Manages the processing of media files.
-
tvrenamer.manager.
run
()¶ Entry point to start the processing.
tvrenamer.options module¶
-
tvrenamer.options.
list_opts
()¶ Returns a list of oslo_config options available in the library.
The returned list includes all oslo_config options which may be registered at runtime by the library. Each element of the list is a tuple. The first element is the name of the group under which the list of elements in the second element will be registered. A group name of None corresponds to the [DEFAULT] group in config files. The purpose of this is to allow tools like the Oslo sample config file generator to discover the options exposed to users by this library.
Returns: a list of (group_name, opts) tuples
-
tvrenamer.options.
register_opts
(conf)¶ Configure options within configuration library.
tvrenamer.service module¶
-
tvrenamer.service.
prepare_service
(args=None)¶ Configures application and setups logging.
Module contents¶
Changelog¶
0.3.0¶
- [RELEASE] Update to version v0.3.0
- [TASK] General cleanup
- [TASK] Updating documentation
- [TASK] Dropping CodeClimate
- [TASK] Adding integration with CodeClimate
- [TASK] Dropped daemon mode
- [TASK] Updated documentation
- [TASK] Switched results cache implementation
- [TASK] Add documentation for trakt service
- [FEATURE] Enable trakt as data service
0.2.0¶
- [RELEASE] Update to version v0.2.0
- [TASK] Add print version to next_release task
- [TASK] Remove unused exceptions
- [FEATURE] Implement result processors
- [FEATURE] Enable daemon mode
- [TASK] Add metadata homepage-url
- [TASK] Documentation updates
- [TASK] Dependent options and improved coverage
0.1.3¶
- [RELEASE] Update to version v0.1.3
- [TASK] Cleanup activities and better output display
- [TASK] Updated the way configurations handled
0.1.2¶
- [RELEASE] Update to version v0.1.2
- [TASK] Sets config_dir value
- [TASK] Add landscape configuration
- [TASK] Add requires.io badge
- [TASK] Optimize container image size
0.1.1¶
- [RELEASE] Update to version v0.1.1
- added badges
- added code documentation
0.1.0¶
- [RELEASE] Update to version v0.1.0
- enable working with new project, no tags
- [TASK] Replace tvdb API library and cleanup
- added dev tools; added titlecase req
- added caching of processing results for each media file
- Completed testing for service tvrage. Switched to nose for testing so that coverage can be printed to stdout for parsing
- updated version of tvrage_api
- update repo url
- update version of tvrage_api
- added tvrage service as an option; add handling for service unavailable during testing
- removed extra functions for renaming within Episode
- updated documentation
- added tests for cli, episode, and manager
- added parallel processing and lockfile functionality
- updated ChangeLog
- added initial AUTHORS and ChangeLog files
- completed test cases for api, made loading data services done via plugin
- finished tests for service, added tests for cli, and minor cleanup
- added test cases for episode, and started test cases for service
- cleaned up renamer and tests, fixed pep8, and added tests for options
- added testing for core modules
- added oslo_config.fixture to base test class
- Fixed name of test class from cut and paste
- minor pep8 fix
- Added test cases and documentation
- added test cases for tools
- added some test cases and minor changes/fixes and pep8 clean up
- centralized dependency on oslotest; removed passing logging instance
- moved the core modules into core package, simplified cli such that it could be used as library, added capture of stack trace of errors, and added some testing code
- initial commit