Compare commits
517 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| ea1fe66884 | |||
| 2786f66c2a | |||
| eef70c4ed8 | |||
| 253b8ac69e | |||
| e48bf7de02 | |||
| 8c040f2197 | |||
| 407cbe1679 | |||
| 16ddb8a02e | |||
| c74aa01c09 | |||
| 1b7291e45c | |||
| a86694d8d1 | |||
| e45fe70c95 | |||
| 6c2833612c | |||
| 3acbefb9c2 | |||
| a25640b57f | |||
| d45e3b0941 | |||
| e6bd7040e3 | |||
| 7fef3cfc93 | |||
| bc575ea9b2 | |||
| 3c7634fef2 | |||
| d635269aa0 | |||
| 90d06e2072 | |||
| 87aefa3a4d | |||
| 6cdf18961e | |||
| 827c75f092 | |||
| 1e9588e5b8 | |||
| 4702284e87 | |||
| 88a2cb9681 | |||
| 3b52a9385f | |||
| 73a4e5a3af | |||
| 71d206ad46 | |||
| 14c7443635 | |||
| e6dc714f7a | |||
| 3b832a4564 | |||
| a6abc268a5 | |||
| 2dea4fef44 | |||
| fe76634d02 | |||
| b499540bed | |||
| 7b4a9c2060 | |||
| a84cc80a88 | |||
| 241cea9729 | |||
| 4b83ddc63e | |||
| 0b431fbb8d | |||
| 3736d921a1 | |||
| 380fb28d2e | |||
| 64c0ee4ccf | |||
| 5977bf69fb | |||
| 179ae6a24e | |||
| 16942ec4c7 | |||
| 6f5378ea40 | |||
| 02ee2039f4 | |||
| e7f89c1a19 | |||
| be4f9d92eb | |||
| ca63b97e79 | |||
| c1ed4a0232 | |||
| b826a0bf08 | |||
| fd0d87d719 | |||
| 094373f3c1 | |||
| 5dac623c9f | |||
| 57d1e772ec | |||
| 983efbfd9b | |||
| 1f11e293c1 | |||
| bfd278ae1c | |||
| dbe1b9d2af | |||
| d71bc4bf09 | |||
| faf2e1dfa4 | |||
| 93360aa1bb | |||
| 8df7780ef9 | |||
| c1fda7f44c | |||
| ce42201eee | |||
| f65131e5b0 | |||
| 8d9efa5dc0 | |||
| 1a54bfb732 | |||
| a15c1f05b2 | |||
| ccfd341fe9 | |||
| aab8e0aa4d | |||
| 9b669c8a3d | |||
| 50960fed24 | |||
| ff61bc8d2d | |||
| e5d9c229ed | |||
| b0e38c7e2c | |||
| c12dade5ea | |||
| cb35dabf31 | |||
| a66cf4b501 | |||
| c355d6a24a | |||
| 60c1e93037 | |||
| 708126aca3 | |||
| bf763a3ad7 | |||
| bb0c3b91a2 | |||
| a7c0cd0d19 | |||
| f315ef9bd0 | |||
| b262a5491c | |||
| d7b30336b6 | |||
| c834bac460 | |||
| 36da0a1204 | |||
| 6ece9271eb | |||
| a465058bb3 | |||
| bad7dbb55c | |||
| 501aaf076e | |||
| 49d27cc7e4 | |||
| e3903f77e9 | |||
| b6ee9b5d7e | |||
| e3301cefd7 | |||
| 74ac38329e | |||
| 50c39382e6 | |||
| 9a65708855 | |||
| 4ebcb2cc95 | |||
| 0c3c41fb4a | |||
| f44942f78e | |||
| d7f2211800 | |||
| f11402c452 | |||
| 7878fb2f92 | |||
| f90c4634c2 | |||
| b52fbc8af5 | |||
| cde1175a7b | |||
| 30786743e3 | |||
| c675bad95c | |||
| 288b92d2ce | |||
| f6e656117c | |||
| 896baa6a04 | |||
| b8f820a9af | |||
| eb8b046dbd | |||
| ff9e0f3190 | |||
| e4f10b9e77 | |||
| 5ca2623c13 | |||
| e560823271 | |||
| 3f83b13a29 | |||
| 507bf09466 | |||
| 688a07dbe9 | |||
| e7c4bc9fc3 | |||
| 04c74afad6 | |||
| e8a4521b7e | |||
| 768b9d203c | |||
| ba5e03342f | |||
| cb3ff0334d | |||
| b96bf9b9a5 | |||
| 4bf673dfc6 | |||
| 223fe8025c | |||
| cf47cf1512 | |||
| 1bac0c3e8c | |||
| 4634c353d8 | |||
| 9ac2dde4e1 | |||
| 07a6db43e6 | |||
| c40f1f0cc2 | |||
| c4ddc6d793 | |||
| 8f58974a1a | |||
| b17fbd6fc0 | |||
| 57d5d57c53 | |||
| 5436512b1f | |||
| 40e10ea72c | |||
| ea6aba4e92 | |||
| e4817dd0d3 | |||
| 751a2d822a | |||
| 38cc8422b6 | |||
| 35f2e47195 | |||
| ab3ad0fe70 | |||
| ccf26730a2 | |||
| c23868dfb1 | |||
| b24af17326 | |||
| 45aff11bff | |||
| 1ee700fa9d | |||
| 4f74dc9031 | |||
| b53fd0bd61 | |||
| 80e3514d56 | |||
| 3f1cac3ccc | |||
| 261e4e8f67 | |||
| bec7ec1901 | |||
| 69015293a4 | |||
| ca55e417ee | |||
| ed37415ee2 | |||
| 68dc99f7ab | |||
| 4d9cac8941 | |||
| fbd6fe00d6 | |||
| e491680dff | |||
| ffc8474918 | |||
| dd7f26e51e | |||
| 498460031e | |||
| d977e3569f | |||
| f122e7e4ed | |||
| 3af3db3df6 | |||
| f4246de8a7 | |||
| 43b647ed28 | |||
| 04958f63de | |||
| b15b2c0e7b | |||
| 61909b68cc | |||
| 71c91bed29 | |||
| a8aa57dcd6 | |||
| a7de8c81b4 | |||
| c2688fe81c | |||
| 295474506b | |||
| c4a989dd3d | |||
| 7f6e192149 | |||
| 28b40e9174 | |||
| f2d2da94a1 | |||
| 14d19ff090 | |||
| a547464d1e | |||
| 23b9aba560 | |||
| 347038c528 | |||
| 2fc26d910a | |||
| 4828730ea3 | |||
| 7c4f539a44 | |||
| 598ef91a30 | |||
| 4862f12619 | |||
| c96ac214bb | |||
| 8fb9cf6a0b | |||
| 4a177b6008 | |||
| 58b59a3304 | |||
| 83e84a24b1 | |||
| 322e6c1f1c | |||
| d1ca77d7db | |||
| d885c78b9a | |||
| 6c8a8a53e7 | |||
| 21ec9335fc | |||
| 4c40a463da | |||
| 169e97975d | |||
| e26c65d4f1 | |||
| d1dd86c825 | |||
| e8388a757b | |||
| 51c7d46390 | |||
| 84688acf32 | |||
| f16ecd220a | |||
| a0f89e46a8 | |||
| 6fce503814 | |||
| e873a2fbd2 | |||
| 53e15969c1 | |||
| c11d83a204 | |||
| 35d664d414 | |||
| 11a33e5425 | |||
| 97bd82967e | |||
| ca89339042 | |||
| 07054c3f68 | |||
| 72405f5c0e | |||
| d5232b8a68 | |||
| d44d032e93 | |||
| d7122a9c98 | |||
| eb0b9f29f2 | |||
| a8b7763a13 | |||
| 1e7fe9d216 | |||
| a0dbfe8c4b | |||
| ef2571d626 | |||
| d3cde7bd05 | |||
| 01191d632b | |||
| 5c934766f5 | |||
| decd0e2510 | |||
| cd46dad14b | |||
| 69c5075ced | |||
| 4da9b7080d | |||
| be112bc091 | |||
| 8389c86ce7 | |||
| fa55d32563 | |||
| 185cc9844c | |||
| 705fb0d342 | |||
| 2ce9ac0862 | |||
| a237cd856d | |||
| b1e685ffc2 | |||
| d19dde9843 | |||
| 74693bf747 | |||
| 530bc7f5ff | |||
| 1b660d1e6d | |||
| 34ce0d640c | |||
| ae2c08bfbd | |||
| f517a683e3 | |||
| b512439d41 | |||
| c62a2a7672 | |||
| bcd5c8f610 | |||
| a75aff65d6 | |||
| 9500f882d5 | |||
| 7fc5f2ef97 | |||
| 5d0808a1f9 | |||
| 511fe7410b | |||
| 7ed6819b03 | |||
| 4709e26bd5 | |||
| 6e1fa561f0 | |||
| d7668d3573 | |||
| 410295486a | |||
| 0d63b47560 | |||
| d3cb956061 | |||
| 2e00accfab | |||
| c54a60097c | |||
| 58a54bce06 | |||
| d00e6905e1 | |||
| c7388c9247 | |||
| 5a2ab412b8 | |||
| 584acb0856 | |||
| 122f41507a | |||
| 6a78564460 | |||
| 096cd5e09c | |||
| cc3fa4b11a | |||
| f050687487 | |||
| 4165ed0b9e | |||
| 3032590b8e | |||
| 113b504057 | |||
| 1a49f0b3ab | |||
| a79143644b | |||
| a2559d2d31 | |||
| 057933d737 | |||
| bb16df5770 | |||
| b9c8ac23cc | |||
| bad6f77a01 | |||
| bb28945eba | |||
| 5a6ed82c5f | |||
| 055b2c7139 | |||
| e049eebeb0 | |||
| 0f3c68b7ef | |||
| 607efff342 | |||
| a88c05f7c3 | |||
| 3aabbfde4c | |||
| b447825a42 | |||
| 2a1fb7bcb7 | |||
| fa7211c8b6 | |||
| bfa961a005 | |||
| 4d9855d91c | |||
| b09c069af8 | |||
| 8fdb241a72 | |||
| de781d0eec | |||
| 2959f52099 | |||
| 1e11c02006 | |||
| 12a58b0ca3 | |||
| 27f521d74e | |||
| bbc3472873 | |||
| 680c699dfa | |||
| b7ba6d51e2 | |||
| 1f2128999f | |||
| f03503b7f8 | |||
| ae1b86173e | |||
| e783c255b7 | |||
| 0f86d7321f | |||
| f085b0fc8e | |||
| b4beba284d | |||
| c1e70e9e21 | |||
| fca2c698fc | |||
| 5d5b23f907 | |||
| 2860e58830 | |||
| e8dec6c143 | |||
| 8b2b19de4b | |||
| af162578c0 | |||
| c6ccfa4417 | |||
| 132001a1be | |||
| 830c09dde7 | |||
| 57bcde2511 | |||
| c1db5b43e5 | |||
| 7b7f29720c | |||
| 13320db360 | |||
| dd9d63d74e | |||
| 739ed2be6d | |||
| 95d9ed685f | |||
| 1064d60873 | |||
| 014c3249b5 | |||
| 59920a5537 | |||
| 8e04de4d65 | |||
| 3ff8ebea7d | |||
| 29096d6700 | |||
| 1c59fc829f | |||
| ca5c0427b8 | |||
| f1dd77bdfd | |||
| a93f74c3ec | |||
| a5b9d2dbd6 | |||
| 2e6e27991a | |||
| b0ae70a88f | |||
| af2e8ba7bd | |||
| 15ca8dac1d | |||
| b6f6d17daa | |||
| 4d06316d22 | |||
| 9290d7e96f | |||
| 10f931ab68 | |||
| 75986be154 | |||
| 1b53c9377d | |||
| 7b31c000cd | |||
| d180dd5f6a | |||
| b7d4d67bec | |||
| 8a018ed3a8 | |||
| fe41ab9c6b | |||
| 7cf00b4b58 | |||
| 224b2399bc | |||
| bef04df3b3 | |||
| a956707669 | |||
| d812af8535 | |||
| 0edb45d851 | |||
| e25903f282 | |||
| 591f98957f | |||
| 01eb6a7a5a | |||
| 2e9fc52ba2 | |||
| 25c5b0f695 | |||
| 88b242fe65 | |||
| 28b7414347 | |||
| 71e58336aa | |||
| b3388cfef9 | |||
| ad1cbc8318 | |||
| 6d47022bb5 | |||
| 4e96c77d2b | |||
| b1071e0870 | |||
| e786c456af | |||
| 68fb07ee0d | |||
| 35bf0b803c | |||
| ef1a142c59 | |||
| 14ff363ce6 | |||
| 7872bca40d | |||
| 4b4272ce85 | |||
| 28b99ad374 | |||
| b7fb9a7703 | |||
| 3eb4913863 | |||
| fe46afd571 | |||
| e8ba65ef22 | |||
| 4854b2630e | |||
| e7d3465cdd | |||
| b04975af2e | |||
| 947384aa6f | |||
| 8db65824bb | |||
| ec1c625a1a | |||
| ded2171375 | |||
| fdc388a117 | |||
| 2320cfd8e5 | |||
| 1be88b8454 | |||
| e3ea8ee06b | |||
| d7c10ae1b8 | |||
| 03f209b2b0 | |||
| c0ddac5eed | |||
| 0e06088b3e | |||
| 75de6bbb3d | |||
| 0e0189d518 | |||
| c166bfd334 | |||
| 496cb3bc68 | |||
| d5176b1b48 | |||
| 2560c5f711 | |||
| 062fcae014 | |||
| 90e6a4b94a | |||
| c7bf7dcb45 | |||
| 069ab7405f | |||
| ed2e8aa510 | |||
| 08d7ce7a2b | |||
| 8dabb8cbbd | |||
| d12226eb7e | |||
| 6d9c5c34f2 | |||
| 251b1fb446 | |||
| f39df2ff46 | |||
| 945bcee3f5 | |||
| fef5c09a76 | |||
| 54a9851dee | |||
| b609659f65 | |||
| a352ecc771 | |||
| abbf3bc20f | |||
| 21704696da | |||
| ffa38694df | |||
| 090bdbeccd | |||
| 7f0d9fea54 | |||
| 8f6839dfe8 | |||
| 246d35fdb1 | |||
| 11b0037986 | |||
| ab34a23bb4 | |||
| 288b9f00e8 | |||
| 712842a235 | |||
| 82b6b3faf5 | |||
| 563d0f7566 | |||
| a9c605f7c9 | |||
| 21a1c1243b | |||
| 7c94f1792b | |||
| b0f87f4e37 | |||
| 4bb10cf89a | |||
| da22709623 | |||
| 7c8e0457ce | |||
| f18656738d | |||
| 517cf6205c | |||
| f45f0b492d | |||
| 2271d3d4c5 | |||
| b5293e4455 | |||
| c6614e2faa | |||
| b8ddc72fe8 | |||
| 3e63414b80 | |||
| 58338fc946 | |||
| acba7d1228 | |||
| 956d8ef0d8 | |||
| 7bd6db0c5d | |||
| a291af863c | |||
| 7f828783a7 | |||
| eb57a83bf5 | |||
| 9720679461 | |||
| cc10d69b47 | |||
| e5b8b2fc8e | |||
| b3880b3ec8 | |||
| eaafa7fb25 | |||
| be346af2ba | |||
| a5d53eaeba | |||
| af340eec7b | |||
| 0baac5d829 | |||
| 1631d48490 | |||
| f9874c3c37 | |||
| 2f8e49b8df | |||
| 8455b2c480 | |||
| fa25502803 | |||
| bfaa45252a | |||
| 9af3627b62 | |||
| 8edccedbbd | |||
| 8d020fd39a | |||
| 139314eaba | |||
| 9cbd5ccf05 | |||
| 314cab60aa | |||
| 025b53092e | |||
| 7a0ea2bdff | |||
| 0a79820dd6 | |||
| 7203ad93e4 | |||
| 504dda817a | |||
| 1069cff6cf | |||
| 2662150710 | |||
| ad7c187201 | |||
| d7125413e5 | |||
| 87d2d9e1f2 | |||
| 9d712b86fa | |||
| 69baf1e039 | |||
| 906707f0e0 | |||
| 3762ab1878 | |||
| 12d7fe7ebf | |||
| 5a6c278167 | |||
| bddfa15eb8 | |||
| 899de2ebe3 | |||
| eef578b939 | |||
| a7608171b1 | |||
| 4d3b050a81 |
@@ -0,0 +1,5 @@
|
||||
[report]
|
||||
exclude_lines =
|
||||
def __repr__
|
||||
raise NotImplementedError
|
||||
if __name__ == .__main__.:
|
||||
+43
-5
@@ -1,8 +1,46 @@
|
||||
build
|
||||
*.py[co]
|
||||
|
||||
# Packages
|
||||
*.egg
|
||||
*.egg-info
|
||||
dist
|
||||
subliminal.egg-info
|
||||
*.pyc
|
||||
.settings
|
||||
build
|
||||
eggs
|
||||
parts
|
||||
bin
|
||||
var
|
||||
sdist
|
||||
develop-eggs
|
||||
.installed.cfg
|
||||
|
||||
# Installer logs
|
||||
pip-log.txt
|
||||
|
||||
# Unit test / coverage reports
|
||||
.coverage
|
||||
.tox
|
||||
|
||||
# Translations
|
||||
*.mo
|
||||
|
||||
# Mr Developer
|
||||
.mr.developer.cfg
|
||||
|
||||
# Pydev
|
||||
.project
|
||||
.pydevproject
|
||||
*~
|
||||
.settings
|
||||
|
||||
# Rope
|
||||
.ropeproject
|
||||
|
||||
# PyCharm
|
||||
.idea
|
||||
|
||||
# Sphinx
|
||||
docs/_build
|
||||
|
||||
# Subliminal unittests
|
||||
subliminal/tests/*.srt
|
||||
subliminal/tests/*_files
|
||||
subliminal/tests/*_cache
|
||||
|
||||
@@ -0,0 +1,3 @@
|
||||
[submodule "docs/_themes"]
|
||||
path = docs/_themes
|
||||
url = git://github.com/Diaoul/diaoul-sphinx-themes.git
|
||||
+25
@@ -0,0 +1,25 @@
|
||||
language: python
|
||||
|
||||
python:
|
||||
- "2.6"
|
||||
- "2.7"
|
||||
|
||||
install:
|
||||
- pip install coveralls --use-mirrors
|
||||
- pip install -r requirements.txt --use-mirrors
|
||||
|
||||
script:
|
||||
- coverage run --source=subliminal setup.py test
|
||||
|
||||
after_success:
|
||||
- coveralls
|
||||
|
||||
notifications:
|
||||
email: false
|
||||
irc:
|
||||
channels:
|
||||
- "irc.freenode.org#subliminal"
|
||||
on_success: change
|
||||
on_failure: always
|
||||
use_notice: true
|
||||
skip_join: true
|
||||
+167
@@ -0,0 +1,167 @@
|
||||
Changelog
|
||||
=========
|
||||
|
||||
0.7.5
|
||||
-----
|
||||
**release date:** 2015-03-04
|
||||
|
||||
* Update requirements
|
||||
* Remove BierDopje provider
|
||||
* Add pre-guessed video optional argument in scan_video
|
||||
* Improve hearing impaired support
|
||||
* Fix TVSubtitles and Podnapisi providers
|
||||
|
||||
0.7.4
|
||||
-----
|
||||
**release date:** 2014-01-27
|
||||
|
||||
* Fix requirements for guessit and babelfish
|
||||
|
||||
|
||||
0.7.3
|
||||
-----
|
||||
**release date:** 2013-11-22
|
||||
|
||||
* Fix windows compatibility
|
||||
* Improve subtitle validation
|
||||
* Improve embedded subtitle languages detection
|
||||
* Improve unittests
|
||||
|
||||
|
||||
0.7.2
|
||||
-----
|
||||
**release date:** 2013-11-10
|
||||
|
||||
* Fix TVSubtitles for ambiguous series
|
||||
* Add a CACHE_VERSION to force cache reloading on version change
|
||||
* Set CLI default cache expiration time to 30 days
|
||||
* Add podnapisi provider
|
||||
* Support script for languages e.g. Latn, Cyrl
|
||||
* Improve logging levels
|
||||
* Fix subtitle validation in some rare cases
|
||||
|
||||
|
||||
0.7.1
|
||||
-----
|
||||
**release date:** 2013-11-06
|
||||
|
||||
* Improve CLI
|
||||
* Add login support for Addic7ed
|
||||
* Remove lxml dependency
|
||||
* Many fixes
|
||||
|
||||
|
||||
0.7.0
|
||||
-----
|
||||
**release date:** 2013-10-29
|
||||
|
||||
**WARNING:** Complete rewrite of subliminal with backward incompatible changes
|
||||
|
||||
* Use enzyme to parse metadata of videos
|
||||
* Use babelfish to handle languages
|
||||
* Use dogpile.cache for caching
|
||||
* Use charade to detect subtitle encoding
|
||||
* Use pysrt for subtitle validation
|
||||
* Use entry points for subtitle providers
|
||||
* New subtitle score computation
|
||||
* Hearing impaired subtitles support
|
||||
* Drop async support
|
||||
* Drop a few providers
|
||||
* And much more...
|
||||
|
||||
0.6.2
|
||||
-----
|
||||
**release date:** 2012-09-15
|
||||
|
||||
* Fix BierDopje
|
||||
* Fix Addic7ed
|
||||
* Fix SubsWiki
|
||||
* Fix missing enzyme import
|
||||
* Add Catalan and Galician languages to Addic7ed
|
||||
* Add possible services in help message of the CLI
|
||||
* Allow existing filenames to be passed without the ./ prefix
|
||||
|
||||
0.6.1
|
||||
-----
|
||||
**release date:** 2012-06-24
|
||||
|
||||
* Fix subtitle release name in BierDopje
|
||||
* Fix subtitles being downloaded multiple times
|
||||
* Add Chinese support to TvSubtitles
|
||||
* Fix encoding issues
|
||||
* Fix single download subtitles without the force option
|
||||
* Add Spanish (Latin America) exception to Addic7ed
|
||||
* Fix group_by_video when a list entry has None as subtitles
|
||||
* Add support for Galician language in Subtitulos
|
||||
* Add an integrity check after subtitles download for Addic7ed
|
||||
* Add error handling for if not strict in Language
|
||||
* Fix TheSubDB hash method to return None if the file is too small
|
||||
* Fix guessit.Language in Video.scan
|
||||
* Fix language detection of subtitles
|
||||
|
||||
0.6.0
|
||||
-----
|
||||
**release date:** 2012-06-16
|
||||
**WARNING:** Backward incompatible changes
|
||||
|
||||
* Fix --workers option in CLI
|
||||
* Use a dedicated module for languages
|
||||
* Use beautifulsoup4
|
||||
* Improve return types
|
||||
* Add scan_filter option
|
||||
* Add --age option in CLI
|
||||
* Add TvSubtitles service
|
||||
* Add Addic7ed service
|
||||
|
||||
|
||||
0.5.1
|
||||
-----
|
||||
**release date:** 2012-03-25
|
||||
|
||||
* Improve error handling of enzyme parsing
|
||||
|
||||
0.5
|
||||
---
|
||||
**release date:** 2012-03-25
|
||||
**WARNING:** Backward incompatible changes
|
||||
|
||||
* Use more unicode
|
||||
* New list_subtitles and download_subtitles methods
|
||||
* New Pool object for asynchronous work
|
||||
* Improve sort algorithm
|
||||
* Better error handling
|
||||
* Make sorting customizable
|
||||
* Remove class Subliminal
|
||||
* Remove permissions handling
|
||||
|
||||
0.4
|
||||
---
|
||||
**release date:** 2011-11-11
|
||||
|
||||
* Many fixes
|
||||
* Better error handling
|
||||
|
||||
0.3
|
||||
---
|
||||
**release date:** 2011-08-18
|
||||
|
||||
* Fix a bug when series is not guessed by guessit
|
||||
* Fix dependencies failure when installing package
|
||||
* Fix encoding issues with logging
|
||||
* Add a script to ease subtitles download
|
||||
* Add possibility to choose mode of created files
|
||||
* Add more checks before adjusting permissions
|
||||
|
||||
0.2
|
||||
---
|
||||
**release date:** 2011-07-11
|
||||
|
||||
* Fix plugin configuration
|
||||
* Fix some encoding issues
|
||||
* Remove extra logging
|
||||
|
||||
0.1
|
||||
---
|
||||
**release date:** not released yet
|
||||
|
||||
* Initial release
|
||||
@@ -0,0 +1,20 @@
|
||||
The MIT License (MIT)
|
||||
|
||||
Copyright (c) 2013 Antoine Bertin
|
||||
|
||||
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.
|
||||
@@ -0,0 +1 @@
|
||||
include LICENSE HISTORY.rst requirements.txt
|
||||
@@ -1,6 +0,0 @@
|
||||
subliminal
|
||||
==========
|
||||
Python module to search and download subtitles
|
||||
|
||||
* [Project page](https://github.com/Diaoul/subliminal)
|
||||
* [Initial project by Patrick Dessalle](http://code.google.com/p/periscope/)
|
||||
+56
@@ -0,0 +1,56 @@
|
||||
Subliminal
|
||||
==========
|
||||
|
||||
Subliminal is a python library to search and download subtitles.
|
||||
It comes with an easy to use CLI (command-line interface) suitable for direct use or cron jobs.
|
||||
|
||||
.. image:: https://travis-ci.org/Diaoul/subliminal.png?branch=develop
|
||||
:target: https://travis-ci.org/Diaoul/subliminal
|
||||
|
||||
.. image:: https://coveralls.io/repos/Diaoul/subliminal/badge.png?branch=develop
|
||||
:target: https://coveralls.io/r/Diaoul/subliminal?branch=develop
|
||||
|
||||
|
||||
Providers
|
||||
---------
|
||||
Subliminal uses multiple providers to give users a vast choice and have a better chance to find the
|
||||
best matching subtitles. Providers are extensible through a dedicated entry point.
|
||||
|
||||
* Addic7ed
|
||||
* OpenSubtitles
|
||||
* Podnapisi
|
||||
* TheSubDB
|
||||
* TvSubtitles
|
||||
|
||||
|
||||
Usage
|
||||
-----
|
||||
CLI
|
||||
^^^
|
||||
Download english subtitles::
|
||||
|
||||
$ subliminal -l en -- The.Big.Bang.Theory.S05E18.HDTV.x264-LOL.mp4
|
||||
1 subtitle downloaded
|
||||
|
||||
Library
|
||||
^^^^^^^
|
||||
Download best subtitles in French and English for videos less than one week old in a video folder,
|
||||
skipping videos that already have subtitles whether they are embedded or not::
|
||||
|
||||
from babelfish import Language
|
||||
from datetime import timedelta
|
||||
import subliminal
|
||||
|
||||
# configure the cache
|
||||
subliminal.cache_region.configure('dogpile.cache.dbm', arguments={'filename': '/path/to/cachefile.dbm'})
|
||||
|
||||
# scan for videos in the folder and their subtitles
|
||||
videos = subliminal.scan_videos(['/path/to/video/folder'], subtitles=True, embedded_subtitles=True, age=timedelta(weeks=1))
|
||||
|
||||
# download
|
||||
subliminal.download_best_subtitles(videos, {Language('eng'), Language('fra')}, age=timedelta(week=1))
|
||||
|
||||
|
||||
License
|
||||
-------
|
||||
MIT
|
||||
@@ -0,0 +1,5 @@
|
||||
sympy>=0.7.3
|
||||
sphinx>=1.1.3
|
||||
sphinxcontrib-programoutput>=0.8
|
||||
Sphinx-PyPI-upload>=0.2.1
|
||||
setuptools>=1.4
|
||||
+177
@@ -0,0 +1,177 @@
|
||||
# Makefile for Sphinx documentation
|
||||
#
|
||||
|
||||
# You can set these variables from the command line.
|
||||
SPHINXOPTS =
|
||||
SPHINXBUILD = sphinx-build
|
||||
PAPER =
|
||||
BUILDDIR = _build
|
||||
|
||||
# User-friendly check for sphinx-build
|
||||
ifeq ($(shell which $(SPHINXBUILD) >/dev/null 2>&1; echo $$?), 1)
|
||||
$(error The '$(SPHINXBUILD)' command was not found. Make sure you have Sphinx installed, then set the SPHINXBUILD environment variable to point to the full path of the '$(SPHINXBUILD)' executable. Alternatively you can add the directory with the executable to your PATH. If you don't have Sphinx installed, grab it from http://sphinx-doc.org/)
|
||||
endif
|
||||
|
||||
# Internal variables.
|
||||
PAPEROPT_a4 = -D latex_paper_size=a4
|
||||
PAPEROPT_letter = -D latex_paper_size=letter
|
||||
ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) .
|
||||
# the i18n builder cannot share the environment and doctrees with the others
|
||||
I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) .
|
||||
|
||||
.PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest gettext
|
||||
|
||||
help:
|
||||
@echo "Please use \`make <target>' where <target> is one of"
|
||||
@echo " html to make standalone HTML files"
|
||||
@echo " dirhtml to make HTML files named index.html in directories"
|
||||
@echo " singlehtml to make a single large HTML file"
|
||||
@echo " pickle to make pickle files"
|
||||
@echo " json to make JSON files"
|
||||
@echo " htmlhelp to make HTML files and a HTML help project"
|
||||
@echo " qthelp to make HTML files and a qthelp project"
|
||||
@echo " devhelp to make HTML files and a Devhelp project"
|
||||
@echo " epub to make an epub"
|
||||
@echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter"
|
||||
@echo " latexpdf to make LaTeX files and run them through pdflatex"
|
||||
@echo " latexpdfja to make LaTeX files and run them through platex/dvipdfmx"
|
||||
@echo " text to make text files"
|
||||
@echo " man to make manual pages"
|
||||
@echo " texinfo to make Texinfo files"
|
||||
@echo " info to make Texinfo files and run them through makeinfo"
|
||||
@echo " gettext to make PO message catalogs"
|
||||
@echo " changes to make an overview of all changed/added/deprecated items"
|
||||
@echo " xml to make Docutils-native XML files"
|
||||
@echo " pseudoxml to make pseudoxml-XML files for display purposes"
|
||||
@echo " linkcheck to check all external links for integrity"
|
||||
@echo " doctest to run all doctests embedded in the documentation (if enabled)"
|
||||
|
||||
clean:
|
||||
rm -rf $(BUILDDIR)/*
|
||||
|
||||
html:
|
||||
$(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html
|
||||
@echo
|
||||
@echo "Build finished. The HTML pages are in $(BUILDDIR)/html."
|
||||
|
||||
dirhtml:
|
||||
$(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml
|
||||
@echo
|
||||
@echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml."
|
||||
|
||||
singlehtml:
|
||||
$(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml
|
||||
@echo
|
||||
@echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml."
|
||||
|
||||
pickle:
|
||||
$(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle
|
||||
@echo
|
||||
@echo "Build finished; now you can process the pickle files."
|
||||
|
||||
json:
|
||||
$(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json
|
||||
@echo
|
||||
@echo "Build finished; now you can process the JSON files."
|
||||
|
||||
htmlhelp:
|
||||
$(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp
|
||||
@echo
|
||||
@echo "Build finished; now you can run HTML Help Workshop with the" \
|
||||
".hhp project file in $(BUILDDIR)/htmlhelp."
|
||||
|
||||
qthelp:
|
||||
$(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp
|
||||
@echo
|
||||
@echo "Build finished; now you can run "qcollectiongenerator" with the" \
|
||||
".qhcp project file in $(BUILDDIR)/qthelp, like this:"
|
||||
@echo "# qcollectiongenerator $(BUILDDIR)/qthelp/subliminal.qhcp"
|
||||
@echo "To view the help file:"
|
||||
@echo "# assistant -collectionFile $(BUILDDIR)/qthelp/subliminal.qhc"
|
||||
|
||||
devhelp:
|
||||
$(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp
|
||||
@echo
|
||||
@echo "Build finished."
|
||||
@echo "To view the help file:"
|
||||
@echo "# mkdir -p $$HOME/.local/share/devhelp/subliminal"
|
||||
@echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/subliminal"
|
||||
@echo "# devhelp"
|
||||
|
||||
epub:
|
||||
$(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub
|
||||
@echo
|
||||
@echo "Build finished. The epub file is in $(BUILDDIR)/epub."
|
||||
|
||||
latex:
|
||||
$(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
|
||||
@echo
|
||||
@echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex."
|
||||
@echo "Run \`make' in that directory to run these through (pdf)latex" \
|
||||
"(use \`make latexpdf' here to do that automatically)."
|
||||
|
||||
latexpdf:
|
||||
$(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
|
||||
@echo "Running LaTeX files through pdflatex..."
|
||||
$(MAKE) -C $(BUILDDIR)/latex all-pdf
|
||||
@echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex."
|
||||
|
||||
latexpdfja:
|
||||
$(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
|
||||
@echo "Running LaTeX files through platex and dvipdfmx..."
|
||||
$(MAKE) -C $(BUILDDIR)/latex all-pdf-ja
|
||||
@echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex."
|
||||
|
||||
text:
|
||||
$(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text
|
||||
@echo
|
||||
@echo "Build finished. The text files are in $(BUILDDIR)/text."
|
||||
|
||||
man:
|
||||
$(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man
|
||||
@echo
|
||||
@echo "Build finished. The manual pages are in $(BUILDDIR)/man."
|
||||
|
||||
texinfo:
|
||||
$(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo
|
||||
@echo
|
||||
@echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo."
|
||||
@echo "Run \`make' in that directory to run these through makeinfo" \
|
||||
"(use \`make info' here to do that automatically)."
|
||||
|
||||
info:
|
||||
$(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo
|
||||
@echo "Running Texinfo files through makeinfo..."
|
||||
make -C $(BUILDDIR)/texinfo info
|
||||
@echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo."
|
||||
|
||||
gettext:
|
||||
$(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale
|
||||
@echo
|
||||
@echo "Build finished. The message catalogs are in $(BUILDDIR)/locale."
|
||||
|
||||
changes:
|
||||
$(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes
|
||||
@echo
|
||||
@echo "The overview file is in $(BUILDDIR)/changes."
|
||||
|
||||
linkcheck:
|
||||
$(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck
|
||||
@echo
|
||||
@echo "Link check complete; look for any errors in the above output " \
|
||||
"or in $(BUILDDIR)/linkcheck/output.txt."
|
||||
|
||||
doctest:
|
||||
$(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest
|
||||
@echo "Testing of doctests in the sources finished, look at the " \
|
||||
"results in $(BUILDDIR)/doctest/output.txt."
|
||||
|
||||
xml:
|
||||
$(SPHINXBUILD) -b xml $(ALLSPHINXOPTS) $(BUILDDIR)/xml
|
||||
@echo
|
||||
@echo "Build finished. The XML files are in $(BUILDDIR)/xml."
|
||||
|
||||
pseudoxml:
|
||||
$(SPHINXBUILD) -b pseudoxml $(ALLSPHINXOPTS) $(BUILDDIR)/pseudoxml
|
||||
@echo
|
||||
@echo "Build finished. The pseudo-XML files are in $(BUILDDIR)/pseudoxml."
|
||||
Vendored
+4
@@ -0,0 +1,4 @@
|
||||
<h3>Subliminal</h3>
|
||||
<p>
|
||||
Subliminal is a Python library to search and download subtitles.
|
||||
</p>
|
||||
Submodule
+1
Submodule docs/_themes added at 24aa9748e4
@@ -0,0 +1,8 @@
|
||||
API
|
||||
===
|
||||
.. module:: subliminal.api
|
||||
|
||||
.. autodata:: PROVIDERS_ENTRY_POINT
|
||||
.. autofunction:: list_subtitles
|
||||
.. autofunction:: download_subtitles
|
||||
.. autofunction:: download_best_subtitles
|
||||
@@ -0,0 +1,11 @@
|
||||
Cache
|
||||
=====
|
||||
.. module:: subliminal.cache
|
||||
|
||||
.. autodata:: CACHE_VERSION
|
||||
.. autofunction:: subliminal_key_generator
|
||||
.. data:: region
|
||||
|
||||
The dogpile.cache region
|
||||
|
||||
Refer to `dogpile.cache's documentation <http://dogpilecache.readthedocs.org>`_ to see how to configure the region
|
||||
@@ -0,0 +1,7 @@
|
||||
CLI
|
||||
===
|
||||
.. module:: subliminal.cli
|
||||
|
||||
subliminal
|
||||
----------
|
||||
.. program-output:: subliminal --help
|
||||
@@ -0,0 +1,9 @@
|
||||
Exceptions
|
||||
==========
|
||||
.. module:: subliminal.exceptions
|
||||
|
||||
.. autoclass:: Error
|
||||
.. autoclass:: ProviderError
|
||||
.. autoclass:: ProviderConfigurationError
|
||||
.. autoclass:: ProviderNotAvailable
|
||||
.. autoclass:: InvalidSubtitle
|
||||
@@ -0,0 +1,6 @@
|
||||
Providers
|
||||
=========
|
||||
.. module:: subliminal.providers
|
||||
|
||||
.. autoclass:: Provider
|
||||
:members:
|
||||
@@ -0,0 +1,6 @@
|
||||
Score
|
||||
=====
|
||||
.. module:: subliminal.score
|
||||
|
||||
.. autofunction:: get_episode_equations
|
||||
.. autofunction:: get_movie_equations
|
||||
@@ -0,0 +1,9 @@
|
||||
Subtitle
|
||||
========
|
||||
.. module:: subliminal.subtitle
|
||||
|
||||
.. autoclass:: Subtitle
|
||||
:members:
|
||||
.. autofunction:: get_subtitle_path
|
||||
.. autofunction:: is_valid_subtitle
|
||||
.. autofunction:: compute_guess_matches
|
||||
@@ -0,0 +1,17 @@
|
||||
Video
|
||||
=====
|
||||
.. module:: subliminal.video
|
||||
|
||||
.. autodata:: VIDEO_EXTENSIONS
|
||||
.. autodata:: SUBTITLE_EXTENSIONS
|
||||
.. autoclass:: Video
|
||||
:members:
|
||||
.. autoclass:: Episode
|
||||
:members:
|
||||
.. autoclass:: Movie
|
||||
:members:
|
||||
.. autofunction:: hash_opensubtitles
|
||||
.. autofunction:: hash_thesubdb
|
||||
.. autofunction:: scan_subtitle_languages
|
||||
.. autofunction:: scan_video
|
||||
.. autofunction:: scan_videos
|
||||
+269
@@ -0,0 +1,269 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
#
|
||||
# subliminal documentation build configuration file, created by
|
||||
# sphinx-quickstart on Wed Oct 23 23:24:28 2013.
|
||||
#
|
||||
# This file is execfile()d with the current directory set to its containing dir.
|
||||
#
|
||||
# Note that not all possible configuration values are present in this
|
||||
# autogenerated file.
|
||||
#
|
||||
# All configuration values have a default; values that are commented out
|
||||
# serve to show the default.
|
||||
|
||||
import sys, os
|
||||
|
||||
# If extensions (or modules to document with autodoc) are in another directory,
|
||||
# add these directories to sys.path here. If the directory is relative to the
|
||||
# documentation root, use os.path.abspath to make it absolute, like shown here.
|
||||
sys.path.insert(0, os.path.abspath('..'))
|
||||
sys.path.append(os.path.abspath('_themes'))
|
||||
import subliminal
|
||||
|
||||
# -- General configuration -----------------------------------------------------
|
||||
|
||||
# If your documentation needs a minimal Sphinx version, state it here.
|
||||
#needs_sphinx = '1.0'
|
||||
|
||||
# Add any Sphinx extension module names here, as strings. They can be extensions
|
||||
# coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
|
||||
extensions = ['sphinx.ext.autodoc', 'sphinxcontrib.programoutput']
|
||||
|
||||
# Add any paths that contain templates here, relative to this directory.
|
||||
templates_path = ['_templates']
|
||||
|
||||
# The suffix of source filenames.
|
||||
source_suffix = '.rst'
|
||||
|
||||
# The encoding of source files.
|
||||
#source_encoding = 'utf-8-sig'
|
||||
|
||||
# The master toctree document.
|
||||
master_doc = 'index'
|
||||
|
||||
# General information about the project.
|
||||
project = subliminal.__title__
|
||||
copyright = ' '.join(subliminal.__copyright__.split()[1:])
|
||||
|
||||
# The version info for the project you're documenting, acts as replacement for
|
||||
# |version| and |release|, also used in various other places throughout the
|
||||
# built documents.
|
||||
#
|
||||
# The short X.Y version.
|
||||
version = subliminal.__version__
|
||||
# The full version, including alpha/beta/rc tags.
|
||||
release = subliminal.__version__
|
||||
|
||||
# The language for content autogenerated by Sphinx. Refer to documentation
|
||||
# for a list of supported languages.
|
||||
#language = None
|
||||
|
||||
# There are two options for replacing |today|: either, you set today to some
|
||||
# non-false value, then it is used:
|
||||
#today = ''
|
||||
# Else, today_fmt is used as the format for a strftime call.
|
||||
#today_fmt = '%B %d, %Y'
|
||||
|
||||
# List of patterns, relative to source directory, that match files and
|
||||
# directories to ignore when looking for source files.
|
||||
exclude_patterns = ['_build']
|
||||
|
||||
# The reST default role (used for this markup: `text`) to use for all documents.
|
||||
#default_role = None
|
||||
|
||||
# If true, '()' will be appended to :func: etc. cross-reference text.
|
||||
#add_function_parentheses = True
|
||||
|
||||
# If true, the current module name will be prepended to all description
|
||||
# unit titles (such as .. function::).
|
||||
#add_module_names = True
|
||||
|
||||
# If true, sectionauthor and moduleauthor directives will be shown in the
|
||||
# output. They are ignored by default.
|
||||
#show_authors = False
|
||||
|
||||
# The name of the Pygments (syntax highlighting) style to use.
|
||||
pygments_style = 'sphinx'
|
||||
|
||||
# A list of ignored prefixes for module index sorting.
|
||||
#modindex_common_prefix = []
|
||||
|
||||
# If true, keep warnings as "system message" paragraphs in the built documents.
|
||||
#keep_warnings = False
|
||||
|
||||
|
||||
# -- Options for HTML output ---------------------------------------------------
|
||||
|
||||
# The theme to use for HTML and HTML Help pages. See the documentation for
|
||||
# a list of builtin themes.
|
||||
html_theme = 'diaoul'
|
||||
|
||||
# Theme options are theme-specific and customize the look and feel of a theme
|
||||
# further. For a list of options available for each theme, see the
|
||||
# documentation.
|
||||
html_theme_options = {'github_user': 'Diaoul',
|
||||
'github_repo': 'subliminal',
|
||||
'github_branch': 'master',
|
||||
'fork_me': 1,
|
||||
'flattr': 0,
|
||||
'gittip': 'Diaoul',
|
||||
'pypi_downloads': 1,
|
||||
'pypi_version': 0,
|
||||
'travis': 0,
|
||||
'coveralls': 0}
|
||||
|
||||
# Add any paths that contain custom themes here, relative to this directory.
|
||||
html_theme_path = ['_themes']
|
||||
|
||||
# The name for this set of Sphinx documents. If None, it defaults to
|
||||
# "<project> v<release> documentation".
|
||||
#html_title = None
|
||||
|
||||
# A shorter title for the navigation bar. Default is the same as html_title.
|
||||
#html_short_title = None
|
||||
|
||||
# The name of an image file (relative to this directory) to place at the top
|
||||
# of the sidebar.
|
||||
#html_logo = None
|
||||
|
||||
# The name of an image file (within the static path) to use as favicon of the
|
||||
# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
|
||||
# pixels large.
|
||||
#html_favicon = None
|
||||
|
||||
# Add any paths that contain custom static files (such as style sheets) here,
|
||||
# relative to this directory. They are copied after the builtin static files,
|
||||
# so a file named "default.css" will overwrite the builtin "default.css".
|
||||
html_static_path = ['_static']
|
||||
|
||||
# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
|
||||
# using the given strftime format.
|
||||
#html_last_updated_fmt = '%b %d, %Y'
|
||||
|
||||
# If true, SmartyPants will be used to convert quotes and dashes to
|
||||
# typographically correct entities.
|
||||
#html_use_smartypants = True
|
||||
|
||||
# Custom sidebar templates, maps document names to template names.
|
||||
html_sidebars = {
|
||||
'index': ['sidebar-intro.html', 'sidebar-star.html', 'sidebar-pypi.html', 'sidebar-donate.html',
|
||||
'sourcelink.html', 'searchbox.html'],
|
||||
'**': ['sidebar-intro.html', 'sidebar-star.html', 'sidebar-pypi.html', 'sidebar-donate.html',
|
||||
'localtoc.html', 'relations.html', 'sourcelink.html', 'searchbox.html']
|
||||
}
|
||||
|
||||
# Additional templates that should be rendered to pages, maps page names to
|
||||
# template names.
|
||||
#html_additional_pages = {}
|
||||
|
||||
# If false, no module index is generated.
|
||||
#html_domain_indices = True
|
||||
|
||||
# If false, no index is generated.
|
||||
#html_use_index = True
|
||||
|
||||
# If true, the index is split into individual pages for each letter.
|
||||
#html_split_index = False
|
||||
|
||||
# If true, links to the reST sources are added to the pages.
|
||||
#html_show_sourcelink = True
|
||||
|
||||
# If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
|
||||
#html_show_sphinx = True
|
||||
|
||||
# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
|
||||
#html_show_copyright = True
|
||||
|
||||
# If true, an OpenSearch description file will be output, and all pages will
|
||||
# contain a <link> tag referring to it. The value of this option must be the
|
||||
# base URL from which the finished HTML is served.
|
||||
#html_use_opensearch = ''
|
||||
|
||||
# This is the file name suffix for HTML files (e.g. ".xhtml").
|
||||
#html_file_suffix = None
|
||||
|
||||
# Output file base name for HTML help builder.
|
||||
htmlhelp_basename = 'subliminaldoc'
|
||||
|
||||
|
||||
# -- Options for LaTeX output --------------------------------------------------
|
||||
|
||||
latex_elements = {
|
||||
# The paper size ('letterpaper' or 'a4paper').
|
||||
#'papersize': 'letterpaper',
|
||||
|
||||
# The font size ('10pt', '11pt' or '12pt').
|
||||
#'pointsize': '10pt',
|
||||
|
||||
# Additional stuff for the LaTeX preamble.
|
||||
#'preamble': '',
|
||||
}
|
||||
|
||||
# Grouping the document tree into LaTeX files. List of tuples
|
||||
# (source start file, target name, title, author, documentclass [howto/manual]).
|
||||
latex_documents = [
|
||||
('index', 'subliminal.tex', u'subliminal Documentation',
|
||||
u'Antoine Bertin', 'manual'),
|
||||
]
|
||||
|
||||
# The name of an image file (relative to this directory) to place at the top of
|
||||
# the title page.
|
||||
#latex_logo = None
|
||||
|
||||
# For "manual" documents, if this is true, then toplevel headings are parts,
|
||||
# not chapters.
|
||||
#latex_use_parts = False
|
||||
|
||||
# If true, show page references after internal links.
|
||||
#latex_show_pagerefs = False
|
||||
|
||||
# If true, show URL addresses after external links.
|
||||
#latex_show_urls = False
|
||||
|
||||
# Documents to append as an appendix to all manuals.
|
||||
#latex_appendices = []
|
||||
|
||||
# If false, no module index is generated.
|
||||
#latex_domain_indices = True
|
||||
|
||||
|
||||
# -- Options for manual page output --------------------------------------------
|
||||
|
||||
# One entry per manual page. List of tuples
|
||||
# (source start file, name, description, authors, manual section).
|
||||
man_pages = [
|
||||
('index', 'subliminal', u'subliminal Documentation',
|
||||
[u'Antoine Bertin'], 1)
|
||||
]
|
||||
|
||||
# If true, show URL addresses after external links.
|
||||
#man_show_urls = False
|
||||
|
||||
|
||||
# -- Options for Texinfo output ------------------------------------------------
|
||||
|
||||
# Grouping the document tree into Texinfo files. List of tuples
|
||||
# (source start file, target name, title, author,
|
||||
# dir menu entry, description, category)
|
||||
texinfo_documents = [
|
||||
('index', 'subliminal', u'subliminal Documentation',
|
||||
u'Antoine Bertin', 'subliminal', 'One line description of project.',
|
||||
'Miscellaneous'),
|
||||
]
|
||||
|
||||
# Documents to append as an appendix to all manuals.
|
||||
#texinfo_appendices = []
|
||||
|
||||
# If false, no module index is generated.
|
||||
#texinfo_domain_indices = True
|
||||
|
||||
# How to display URL addresses: 'footnote', 'no', or 'inline'.
|
||||
#texinfo_show_urls = 'footnote'
|
||||
|
||||
# If true, do not generate a @detailmenu in the "Top" node's menu.
|
||||
#texinfo_no_detailmenu = False
|
||||
|
||||
|
||||
# -- Options for autodoc -------------------------------------------------------
|
||||
autodoc_member_order = 'bysource'
|
||||
|
||||
+102
@@ -0,0 +1,102 @@
|
||||
.. subliminal documentation master file, created by
|
||||
sphinx-quickstart on Wed Oct 23 23:24:28 2013.
|
||||
You can adapt this file completely to your liking, but it should at least
|
||||
contain the root `toctree` directive.
|
||||
|
||||
Subliminal
|
||||
==========
|
||||
Release v\ |version|
|
||||
|
||||
Subliminal is a python library to search and download subtitles.
|
||||
It comes with an easy to use :abbr:`CLI (command-line interface)` suitable for direct use or cron jobs.
|
||||
|
||||
|
||||
Providers
|
||||
---------
|
||||
Subliminal uses multiple providers to give users a vast choice and have a better chance to find the
|
||||
best matching subtitles. Providers are extensible through a dedicated entry point.
|
||||
|
||||
* Addic7ed
|
||||
* OpenSubtitles
|
||||
* Podnapisi
|
||||
* TheSubDB
|
||||
* TvSubtitles
|
||||
|
||||
|
||||
Usage
|
||||
-----
|
||||
CLI
|
||||
^^^
|
||||
Download english subtitles::
|
||||
|
||||
$ subliminal -l en -- The.Big.Bang.Theory.S05E18.HDTV.x264-LOL.mp4
|
||||
1 subtitle downloaded
|
||||
|
||||
See :mod:`subliminal.cli`
|
||||
|
||||
Library
|
||||
^^^^^^^
|
||||
Download best subtitles in French and English for videos less than one week old in a video folder,
|
||||
skipping videos that already have subtitles whether they are embedded or not::
|
||||
|
||||
from babelfish import Language
|
||||
from datetime import timedelta
|
||||
import subliminal
|
||||
|
||||
# configure the cache
|
||||
subliminal.cache_region.configure('dogpile.cache.dbm', arguments={'filename': '/path/to/cachefile.dbm'})
|
||||
|
||||
# scan for videos in the folder and their subtitles
|
||||
videos = subliminal.scan_videos(['/path/to/video/folder'], subtitles=True, embedded_subtitles=True, age=timedelta(weeks=1))
|
||||
|
||||
# download
|
||||
subliminal.download_best_subtitles(videos, {Language('eng'), Language('fra')}, age=timedelta(week=1))
|
||||
|
||||
See :mod:`subliminal.api`, :func:`~subliminal.video.scan_videos` and :func:`~subliminal.video.scan_video`
|
||||
|
||||
How it works
|
||||
------------
|
||||
Subliminal makes use of various libraries to achieve its goal:
|
||||
|
||||
* `enzyme <http://enzyme.readthedocs.org>`_ to detect embedded subtitles in videos and retrieve metadata
|
||||
* `guessit <http://guessit.readthedocs.org>`_ to guess informations from filenames
|
||||
* `babelfish <http://babelfish.readthedocs.org>`_ to work with languages
|
||||
* `requests <http://docs.python-requests.org>`_ to make human readable HTTP requests
|
||||
* `BeautifulSoup <http://www.crummy.com/software/BeautifulSoup>`_ to parse HTML and XML
|
||||
* `dogpile.cache <http://dogpilecache.readthedocs.org>`_ to cache intermediate search data
|
||||
* `charade <https://github.com/sigmavirus24/charade>`_ to detect subtitles' encoding
|
||||
* `pysrt <https://github.com/byroot/pysrt>`_ to validate downloaded subtitles
|
||||
|
||||
|
||||
License
|
||||
-------
|
||||
MIT
|
||||
|
||||
|
||||
Documentation
|
||||
-------------
|
||||
.. toctree::
|
||||
:maxdepth: 2
|
||||
|
||||
provider_guide
|
||||
|
||||
|
||||
API Documentation
|
||||
-----------------
|
||||
If you are looking for information on a specific function, class or method,
|
||||
this part of the documentation is for you.
|
||||
|
||||
.. toctree::
|
||||
:maxdepth: 2
|
||||
|
||||
api/api
|
||||
api/cache
|
||||
api/cli
|
||||
api/exceptions
|
||||
api/providers
|
||||
api/score
|
||||
api/subtitle
|
||||
api/video
|
||||
|
||||
|
||||
.. include:: ../HISTORY.rst
|
||||
@@ -0,0 +1,103 @@
|
||||
Provider Guide
|
||||
==============
|
||||
This guide is going to explain how to add a :class:`~subliminal.providers.Provider` to subliminal
|
||||
|
||||
|
||||
Requirements
|
||||
------------
|
||||
When starting a provider you should be able to answer to the following questions:
|
||||
|
||||
* What languages does my provider support?
|
||||
* What are the language codes for the supported languages?
|
||||
* Does my provider deliver subtitles for episodes? for movies?
|
||||
* Does my provider require a video hash?
|
||||
|
||||
Each response of these questions will help you set the correct attributes for your
|
||||
:class:`~subliminal.providers.Provider`.
|
||||
|
||||
|
||||
Video Validation
|
||||
----------------
|
||||
Not all providers deliver subtitles for :class:`~subliminal.video.Episode`. Some may require a hash.
|
||||
The :meth:`~subliminal.providers.Provider.check` method does validation against a :class:`~subliminal.video.Video`
|
||||
object and will return `False` if the given :class:`~subliminal.video.Video` isn't suitable. If you're not happy
|
||||
with the default implementation, you can override it.
|
||||
|
||||
|
||||
Configuration
|
||||
-------------
|
||||
API keys must not be configurable by the user and must remain linked to subliminal. Hence they must be written
|
||||
in the provider module.
|
||||
|
||||
Per-user authentication is allowed and must be configured at instantiation as keyword arguments. Configuration
|
||||
will be done by the user through the `provider_configs` argument of the :func:`~subliminal.api.list_subtitles` and
|
||||
:func:`~subliminal.api.download_best_subtitles` functions. No network operation must be done during instantiation,
|
||||
only configuration. Any error in the configuration must raise a
|
||||
:class:`~subliminal.exceptions.ProviderConfigurationError`.
|
||||
|
||||
|
||||
Beyond this point, if a network error occurs, a :class:`~subliminal.exceptions.ProviderNotAvailable` exception
|
||||
must be raised and an unexpected behavior must raise a :class:`~subliminal.exceptions.ProviderError` exception.
|
||||
|
||||
|
||||
Initialization / Termination
|
||||
----------------------------
|
||||
Actual authentication operations must take place in the :meth:`~subliminal.providers.Provider.initialize` method.
|
||||
If you need anything to be executed when the provider isn't used anymore like logout,
|
||||
use :meth:`~subliminal.providers.Provider.terminate`.
|
||||
|
||||
|
||||
Caching policy
|
||||
--------------
|
||||
To save bandwidth and improve querying time, intermediate data should be cached when possible. Typical use case is
|
||||
when a query to retrieve show ids is required prior to the query to actually search for subtitles. In that case
|
||||
the function that gets the show id from the show name must be cached.
|
||||
|
||||
|
||||
Language
|
||||
--------
|
||||
To be able to handle various language codes, subliminal makes use of `babelfish <http://babelfish.readthedocs.org>`_
|
||||
Language and converters. You must set the attribute :attr:`~subliminal.providers.Provider.languages` with a set of
|
||||
supported :class:`babelfish.Language`.
|
||||
|
||||
If you cannot find a suitable converter for your provider, you can `make one of your own
|
||||
<http://babelfish.readthedocs.org/en/latest/#custom-converters>`_.
|
||||
|
||||
|
||||
Querying
|
||||
--------
|
||||
The :meth:`~subliminal.providers.Provider.query` method parameters must include all aspects of provider's querying with
|
||||
simple types.
|
||||
|
||||
|
||||
Subtitle
|
||||
--------
|
||||
A custom :class:`~subliminal.subtitle.Subtitle` subclass must be created to represent a subtitle from the provider.
|
||||
It must have relevant attributes that can be used to compute the matches of the subtitle against a
|
||||
:class:`~subliminal.video.Video` object.
|
||||
|
||||
|
||||
Score computation
|
||||
-----------------
|
||||
|
||||
To be able to compare subtitles coming from different providers between them, the
|
||||
:meth:`~subliminal.subtitle.Subtitle.compute_matches` method must be implemented.
|
||||
If `guessit <http://guessit.readthedocs.org>`_ is used to extract data from the
|
||||
:class:`~subliminal.subtitle.Subtitle` subclass, you can use :func:`~subliminal.subtitle.compute_guess_matches`
|
||||
as a helper to compute matches between the :class:`~subliminal.video.Video` and the :class:`guessit.Guess`.
|
||||
|
||||
Refer to the `scores` attribute of :class:`~subliminal.video.Episode` and :class:`~subliminal.video.Movie`
|
||||
for a list of possible matches.
|
||||
|
||||
|
||||
Unittesting
|
||||
-----------
|
||||
All possible uses of the :meth:`~subliminal.providers.Provider.query` method must be unittested including the uses
|
||||
that produce exceptions other than :class:`~subliminal.exceptions.ProviderNotAvailable`.
|
||||
The :meth:`~subliminal.subtitle.Subtitle.compute_matches` is used to validate the unittests.
|
||||
|
||||
As it is not possible to unittest all uses of the :meth:`~subliminal.providers.Provider.list_subtitles`
|
||||
and :meth:`~subliminal.providers.Provider.download_subtitle` methods, unitests are only required to cover most common
|
||||
use cases.
|
||||
|
||||
See existing unittests for more details on how to proceed.
|
||||
@@ -0,0 +1,9 @@
|
||||
beautifulsoup4>=4.3.2
|
||||
guessit>=0.7,<0.10
|
||||
requests>=2.0.1
|
||||
enzyme>=0.4.0
|
||||
html5lib>=0.99
|
||||
dogpile.cache>=0.5.2
|
||||
babelfish>=0.5.0
|
||||
charade>=1.0.3
|
||||
pysrt>=0.5.0
|
||||
@@ -1,80 +0,0 @@
|
||||
#!/usr/bin/env python
|
||||
# -*- coding: utf-8 -*-
|
||||
#
|
||||
# Subliminal - Subtitles, faster than your thoughts
|
||||
# Copyright (c) 2008-2011 Patrick Dessalle <patrick@dessalle.be>
|
||||
# Copyright (c) 2011 Antoine Bertin <diaoulael@gmail.com>
|
||||
#
|
||||
# This file is part of Subliminal.
|
||||
#
|
||||
# Subliminal is free software; you can redistribute it and/or modify it under
|
||||
# the terms of the Lesser GNU General Public License as published by
|
||||
# the Free Software Foundation; either version 3 of the License, or
|
||||
# (at your option) any later version.
|
||||
#
|
||||
# Subliminal is distributed in the hope that it will be useful,
|
||||
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
# Lesser GNU General Public License for more details.
|
||||
#
|
||||
# You should have received a copy of the Lesser GNU General Public License
|
||||
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
#
|
||||
|
||||
import argparse
|
||||
import subliminal
|
||||
import logging
|
||||
import mimetypes
|
||||
import os
|
||||
import os.path
|
||||
import sys
|
||||
|
||||
|
||||
def main():
|
||||
'''Download subtitles'''
|
||||
# parse command line options
|
||||
parser = argparse.ArgumentParser(description='Subtitles, faster than your thoughts')
|
||||
parser.add_argument('-l', '--language', action='append', dest='languages', help='wanted language (ISO 639-1)', metavar='LG')
|
||||
parser.add_argument('-p', '--plugin', action='append', dest='plugins', help='plugin to use', metavar='NAME')
|
||||
parser.add_argument('-m', '--multi', action='store_true', help='download multiple subtitle languages')
|
||||
parser.add_argument('-f', '--force', action='store_true', help='replace existing subtitle file')
|
||||
parser.add_argument('-w', '--workers', action='store', help='use N threads (default: %(default)s)', metavar='N', default=4)
|
||||
group_verbosity = parser.add_mutually_exclusive_group()
|
||||
group_verbosity.add_argument('-q', '--quiet', action='store_true', help='disable output')
|
||||
group_verbosity.add_argument('-v', '--verbose', action='store_true', help='verbose output')
|
||||
group_cache = parser.add_mutually_exclusive_group()
|
||||
group_cache.add_argument('--cache-dir', action='store', dest='cache_dir', help='cache directory to use', metavar='DIR', default=os.path.expanduser('~/.config/subliminal'))
|
||||
group_cache.add_argument('--no-cache-dir', action='store_false', dest='cache_dir', help='do not use cache directory (some plugins may not work)')
|
||||
parser.add_argument('--version', action='version', version=subliminal.__version__)
|
||||
parser.add_argument('paths', nargs='+', help='path to video files or folders', metavar='PATH')
|
||||
args = parser.parse_args()
|
||||
|
||||
# Set log verbosity
|
||||
if args.verbose:
|
||||
logging.basicConfig(level=logging.DEBUG, format='%(levelname)-8s %(asctime)s %(name)-24s %(message)s', datefmt='%Y-%m-%d %H:%M:%S')
|
||||
elif not args.quiet:
|
||||
logging.basicConfig(level=logging.WARN, format='%(levelname)s: %(name)s %(message)s')
|
||||
|
||||
# Initialize the instance
|
||||
subli = subliminal.Subliminal(cache_dir=args.cache_dir, workers=args.workers, multi=args.multi, force=args.force, max_depth=3, files_mode=-1)
|
||||
if args.plugins:
|
||||
subli.plugins = args.plugins
|
||||
if args.languages:
|
||||
subli.languages = args.languages
|
||||
try:
|
||||
subtitles = subli.downloadSubtitles([unicode(x) for x in args.paths])
|
||||
finally:
|
||||
subli.stopWorkers()
|
||||
if len(subtitles) == 0:
|
||||
if not args.quiet:
|
||||
sys.stderr.write('No subtitles found\n')
|
||||
exit(1)
|
||||
if not args.quiet:
|
||||
print '*' * 50
|
||||
print 'Downloaded %s subtitles' % len(subtitles)
|
||||
for subtitle in subtitles:
|
||||
print subtitle
|
||||
print '*' * 50
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,7 @@
|
||||
[build_sphinx]
|
||||
source-dir = docs/
|
||||
build-dir = docs/_build
|
||||
all_files = 1
|
||||
|
||||
[upload_sphinx]
|
||||
upload-dir = docs/_build/html
|
||||
@@ -1,45 +1,40 @@
|
||||
#!/usr/bin/env python
|
||||
# -*- coding: utf-8 -*-
|
||||
#
|
||||
# Subliminal - Subtitles, faster than your thoughts
|
||||
# Copyright (c) 2011 Antoine Bertin <diaoulael@gmail.com>
|
||||
#
|
||||
# This file is part of Subliminal.
|
||||
#
|
||||
# Subliminal is free software; you can redistribute it and/or modify it under
|
||||
# the terms of the Lesser GNU General Public License as published by
|
||||
# the Free Software Foundation; either version 3 of the License, or
|
||||
# (at your option) any later version.
|
||||
#
|
||||
# Subliminal is distributed in the hope that it will be useful,
|
||||
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
# Lesser GNU General Public License for more details.
|
||||
#
|
||||
# You should have received a copy of the Lesser GNU General Public License
|
||||
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
#
|
||||
|
||||
from setuptools import setup
|
||||
from setuptools import setup, find_packages
|
||||
|
||||
|
||||
execfile('subliminal/version.py')
|
||||
setup(name='subliminal',
|
||||
version=__version__,
|
||||
license='LGPLv3',
|
||||
description='Subliminal - Subtitles, faster than your thoughts',
|
||||
classifiers=['Development Status :: 4 - Beta',
|
||||
'License :: OSI Approved :: GNU Library or Lesser General Public License (LGPL)',
|
||||
'Intended Audience :: Developers',
|
||||
'Operating System :: OS Independent',
|
||||
'Programming Language :: Python :: 2.6',
|
||||
'Topic :: Software Development :: Libraries :: Python Modules',
|
||||
'Topic :: Multimedia :: Video'],
|
||||
keywords='subliminal video movie subtitle python library',
|
||||
version='0.7.5',
|
||||
license='MIT',
|
||||
description='Subtitles, faster than your thoughts',
|
||||
long_description=open('README.rst').read() + '\n\n' + open('HISTORY.rst').read(),
|
||||
keywords='subtitle subtitles video movie episode tv show',
|
||||
url='https://github.com/Diaoul/subliminal',
|
||||
author='Antoine Bertin',
|
||||
author_email='diaoulael@gmail.com',
|
||||
url='https://github.com/Diaoul/subliminal',
|
||||
packages=['subliminal', 'subliminal/plugins'],
|
||||
scripts=['scripts/subliminal'],
|
||||
py_modules=['subliminal'],
|
||||
install_requires=['BeautifulSoup>=3.2.0', 'guessit>=0.2'])
|
||||
packages=find_packages(),
|
||||
classifiers=['Development Status :: 4 - Beta',
|
||||
'Intended Audience :: Developers',
|
||||
'License :: OSI Approved :: MIT License',
|
||||
'Operating System :: OS Independent',
|
||||
'Programming Language :: Python',
|
||||
'Programming Language :: Python :: 2',
|
||||
'Programming Language :: Python :: 2.6',
|
||||
'Programming Language :: Python :: 2.7',
|
||||
'Programming Language :: Python :: 3',
|
||||
'Programming Language :: Python :: 3.3',
|
||||
'Topic :: Software Development :: Libraries :: Python Modules',
|
||||
'Topic :: Multimedia :: Video'],
|
||||
entry_points={
|
||||
'console_scripts': ['subliminal = subliminal.cli:subliminal'],
|
||||
'subliminal.providers': ['addic7ed = subliminal.providers.addic7ed:Addic7edProvider',
|
||||
'opensubtitles = subliminal.providers.opensubtitles:OpenSubtitlesProvider',
|
||||
'podnapisi = subliminal.providers.podnapisi:PodnapisiProvider',
|
||||
'thesubdb = subliminal.providers.thesubdb:TheSubDBProvider',
|
||||
'tvsubtitles = subliminal.providers.tvsubtitles:TVsubtitlesProvider'],
|
||||
'babelfish.language_converters': ['addic7ed = subliminal.converters.addic7ed:Addic7edConverter',
|
||||
'podnapisi = subliminal.converters.podnapisi:PodnapisiConverter',
|
||||
'tvsubtitles = subliminal.converters.tvsubtitles:TVsubtitlesConverter']
|
||||
},
|
||||
install_requires=open('requirements.txt').readlines(),
|
||||
test_suite='subliminal.tests.suite')
|
||||
|
||||
+17
-23
@@ -1,25 +1,19 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
#
|
||||
# Subliminal - Subtitles, faster than your thoughts
|
||||
# Copyright (c) 2011 Antoine Bertin <diaoulael@gmail.com>
|
||||
#
|
||||
# This file is part of Subliminal.
|
||||
#
|
||||
# Subliminal is free software; you can redistribute it and/or modify it under
|
||||
# the terms of the Lesser GNU General Public License as published by
|
||||
# the Free Software Foundation; either version 3 of the License, or
|
||||
# (at your option) any later version.
|
||||
#
|
||||
# Subliminal is distributed in the hope that it will be useful,
|
||||
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
# Lesser GNU General Public License for more details.
|
||||
#
|
||||
# You should have received a copy of the Lesser GNU General Public License
|
||||
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
#
|
||||
__title__ = 'subliminal'
|
||||
__version__ = '0.7.5'
|
||||
__author__ = 'Antoine Bertin'
|
||||
__license__ = 'MIT'
|
||||
__copyright__ = 'Copyright 2013 Antoine Bertin'
|
||||
|
||||
__all__ = ['FORMATS', 'LANGUAGES', 'PLUGINS', 'API_PLUGINS', 'Subliminal', 'Subtitle']
|
||||
from classes import *
|
||||
from subliminal import *
|
||||
from version import __version__
|
||||
import logging
|
||||
from .api import PROVIDERS_ENTRY_POINT, list_subtitles, download_subtitles, download_best_subtitles
|
||||
from .cache import MutexLock, region as cache_region
|
||||
from .exceptions import Error, ProviderError, ProviderConfigurationError, ProviderNotAvailable, InvalidSubtitle
|
||||
from .subtitle import Subtitle
|
||||
from .video import VIDEO_EXTENSIONS, SUBTITLE_EXTENSIONS, Video, Episode, Movie, scan_videos, scan_video
|
||||
|
||||
class NullHandler(logging.Handler):
|
||||
def emit(self, record):
|
||||
pass
|
||||
|
||||
logging.getLogger(__name__).addHandler(NullHandler())
|
||||
|
||||
@@ -0,0 +1,334 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
from __future__ import unicode_literals
|
||||
import collections
|
||||
import io
|
||||
import logging
|
||||
import operator
|
||||
import babelfish
|
||||
import pkg_resources
|
||||
from os.path import basename
|
||||
from .exceptions import ProviderNotAvailable, InvalidSubtitle
|
||||
from .subtitle import get_subtitle_path
|
||||
from socket import error as socket_error
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
#: Entry point for the providers
|
||||
PROVIDERS_ENTRY_POINT = 'subliminal.providers'
|
||||
|
||||
|
||||
def list_subtitles(videos, languages, providers=None, provider_configs=None):
|
||||
"""List subtitles for `videos` with the given `languages` using the specified `providers`
|
||||
|
||||
:param videos: videos to list subtitles for
|
||||
:type videos: set of :class:`~subliminal.video.Video`
|
||||
:param languages: languages of subtitles to search for
|
||||
:type languages: set of :class:`babelfish.Language`
|
||||
:param providers: providers to use for the search, if not all
|
||||
:type providers: list of string or None
|
||||
:param provider_configs: configuration for providers
|
||||
:type provider_configs: dict of provider name => provider constructor kwargs
|
||||
:return: found subtitles
|
||||
:rtype: dict of :class:`~subliminal.video.Video` => [:class:`~subliminal.subtitle.Subtitle`]
|
||||
|
||||
"""
|
||||
provider_configs = provider_configs or {}
|
||||
subtitles = collections.defaultdict(list)
|
||||
# filter videos
|
||||
videos = [v for v in videos if v.subtitle_languages & languages < languages]
|
||||
if not videos:
|
||||
logger.info('No video to download subtitles for with languages %r', languages)
|
||||
return subtitles
|
||||
subtitle_languages = set.intersection(*[v.subtitle_languages for v in videos])
|
||||
for provider_entry_point in pkg_resources.iter_entry_points(PROVIDERS_ENTRY_POINT):
|
||||
# filter and initialize provider
|
||||
if providers is not None and provider_entry_point.name not in providers:
|
||||
logger.debug('Skipping provider %r: not in the list', provider_entry_point.name)
|
||||
continue
|
||||
Provider = provider_entry_point.load()
|
||||
provider_languages = Provider.languages & languages - subtitle_languages
|
||||
if not provider_languages:
|
||||
logger.info('Skipping provider %r: no language to search for', provider_entry_point.name)
|
||||
continue
|
||||
provider_videos = [v for v in videos if Provider.check(v)]
|
||||
if not provider_videos:
|
||||
logger.info('Skipping provider %r: no video to search for', provider_entry_point.name)
|
||||
continue
|
||||
|
||||
# list subtitles with the provider
|
||||
try:
|
||||
with Provider(**provider_configs.get(provider_entry_point.name, {})) as provider:
|
||||
for provider_video in provider_videos:
|
||||
provider_video_languages = provider_languages - provider_video.subtitle_languages
|
||||
if not provider_video_languages:
|
||||
logger.debug('Skipping provider %r: no language to search for for video %r',
|
||||
provider_entry_point.name, provider_video)
|
||||
continue
|
||||
logger.info('Listing subtitles with provider %r for video %r with languages %r',
|
||||
provider_entry_point.name, provider_video, provider_video_languages)
|
||||
try:
|
||||
provider_subtitles = provider.list_subtitles(provider_video, provider_video_languages)
|
||||
except ProviderNotAvailable as err:
|
||||
logger.warning('Provider %r is not available, discarding it', provider_entry_point.name)
|
||||
logger.debug('ProviderNotAvailable error: %r', str(err))
|
||||
break
|
||||
except:
|
||||
logger.exception('Unexpected error in provider %r', provider_entry_point.name)
|
||||
continue
|
||||
logger.info('Found %d subtitle(s) on %s' % (
|
||||
len(provider_subtitles),
|
||||
provider_entry_point.name,
|
||||
))
|
||||
subtitles[provider_video].extend(provider_subtitles)
|
||||
except ProviderNotAvailable as err:
|
||||
logger.warning('Provider %r is not available, discarding it', provider_entry_point.name)
|
||||
logger.debug('ProviderNotAvailable error: %r', str(err))
|
||||
return subtitles
|
||||
|
||||
|
||||
def download_subtitles(subtitles, provider_configs=None, single=False):
|
||||
"""Download subtitles
|
||||
|
||||
:param subtitles: subtitles to download
|
||||
:type subtitles: dict of :class:`~subliminal.video.Video` => [:class:`~subliminal.subtitle.Subtitle`]
|
||||
:param provider_configs: configuration for providers
|
||||
:type provider_configs: dict of provider name => provider constructor kwargs
|
||||
:param bool single: download with .srt extension if `True`, add language identifier otherwise
|
||||
|
||||
"""
|
||||
provider_configs = provider_configs or {}
|
||||
discarded_providers = set()
|
||||
providers_by_name = dict([(ep.name, ep.load()) for ep in pkg_resources.iter_entry_points(PROVIDERS_ENTRY_POINT)])
|
||||
|
||||
initialized_providers = {}
|
||||
downloaded_subtitles = collections.defaultdict(list)
|
||||
fetched_subtitles = set()
|
||||
try:
|
||||
for video, video_subtitles in subtitles.items():
|
||||
languages = set([subtitle.language for subtitle in video_subtitles])
|
||||
downloaded_languages = set()
|
||||
for subtitle in video_subtitles:
|
||||
# filter
|
||||
if subtitle.language in downloaded_languages:
|
||||
logger.debug('Skipping subtitle: %r already downloaded', subtitle.language)
|
||||
continue
|
||||
if subtitle.provider_name in discarded_providers:
|
||||
logger.debug('Skipping subtitle from discarded provider %r', subtitle.provider_name)
|
||||
continue
|
||||
|
||||
# initialize provider
|
||||
if subtitle.provider_name in initialized_providers:
|
||||
provider = initialized_providers[subtitle.provider_name]
|
||||
else:
|
||||
provider = providers_by_name[subtitle.provider_name](**provider_configs.get(subtitle.provider_name, {}))
|
||||
try:
|
||||
provider.initialize()
|
||||
except ProviderNotAvailable as err:
|
||||
logger.warning('Provider %r is not available, discarding it', subtitle.provider_name)
|
||||
logger.debug('ProviderNotAvailable error: %r', str(err))
|
||||
discarded_providers.add(subtitle.provider_name)
|
||||
continue
|
||||
except socket_error as err:
|
||||
logger.warning('Provider %r is not responding, discarding it', subtitle.provider_name)
|
||||
logger.debug('Provider socket error: %r', str(err))
|
||||
discarded_providers.add(subtitle.provider_name)
|
||||
continue
|
||||
except:
|
||||
logger.exception('Unexpected error in provider %r', subtitle.provider_name)
|
||||
discarded_providers.add(subtitle.provider_name)
|
||||
continue
|
||||
initialized_providers[subtitle.provider_name] = provider
|
||||
|
||||
# download subtitles
|
||||
subtitle_path = get_subtitle_path(video.name, None if single else subtitle.language)
|
||||
if basename(subtitle_path) in fetched_subtitles:
|
||||
logger.debug('Skipping subtitle already retrieved %r', basename(subtitle_path))
|
||||
continue
|
||||
|
||||
logger.info('Downloading subtitle %r into %r', subtitle, subtitle_path)
|
||||
try:
|
||||
subtitle_text = provider.download_subtitle(subtitle)
|
||||
downloaded_subtitles[video].append(subtitle)
|
||||
except ProviderNotAvailable as err:
|
||||
logger.warning('Provider %r is not available, discarding it', subtitle.provider_name)
|
||||
logger.debug('ProviderNotAvailable error: %r', str(err))
|
||||
discarded_providers.add(subtitle.provider_name)
|
||||
continue
|
||||
except InvalidSubtitle:
|
||||
logger.info('Invalid subtitle, skipping it')
|
||||
continue
|
||||
except:
|
||||
logger.exception('Unexpected error in provider %r', subtitle.provider_name)
|
||||
continue
|
||||
with io.open(subtitle_path, 'w', encoding='utf-8') as f:
|
||||
f.write(subtitle_text)
|
||||
downloaded_languages.add(subtitle.language)
|
||||
fetched_subtitles.add(basename(subtitle_path))
|
||||
if single or sorted(downloaded_languages) == sorted(languages):
|
||||
break
|
||||
finally: # terminate providers
|
||||
for (provider_name, provider) in initialized_providers.items():
|
||||
try:
|
||||
provider.terminate()
|
||||
except ProviderNotAvailable:
|
||||
logger.warning('Provider %r is not available, unable to terminate', provider_name)
|
||||
except:
|
||||
logger.exception('Unexpected error in provider %r', provider_name)
|
||||
return downloaded_subtitles
|
||||
|
||||
|
||||
def download_best_subtitles(videos, languages, providers=None, provider_configs=None, single=False, min_score=0,
|
||||
hearing_impaired=False, hi_score_adjust=0):
|
||||
"""Download the best subtitles for `videos` with the given `languages` using the specified `providers`
|
||||
|
||||
:param videos: videos to download subtitles for
|
||||
:type videos: set of :class:`~subliminal.video.Video`
|
||||
:param languages: languages of subtitles to download
|
||||
:type languages: set of :class:`babelfish.Language`
|
||||
:param providers: providers to use for the search, if not all
|
||||
:type providers: list of string or None
|
||||
:param provider_configs: configuration for providers
|
||||
:type provider_configs: dict of provider name => provider constructor kwargs
|
||||
:param bool single: download with .srt extension if `True`, add language identifier otherwise
|
||||
:param int min_score: minimum score for subtitles to download
|
||||
:param bool hearing_impaired: download hearing impaired subtitles
|
||||
:param int hi_score_adjust: Adjust hearing_impaired_scores if matched.
|
||||
|
||||
"""
|
||||
provider_configs = provider_configs or {}
|
||||
discarded_providers = set()
|
||||
downloaded_subtitles = collections.defaultdict(list)
|
||||
fetched_subtitles = set()
|
||||
# filter videos
|
||||
videos = [v for v in videos if v.subtitle_languages & languages < languages
|
||||
and (not single or babelfish.Language('und') not in v.subtitle_languages)]
|
||||
if not videos:
|
||||
logger.info('No video to download subtitles for with languages %r', languages)
|
||||
return downloaded_subtitles
|
||||
# filter and initialize providers
|
||||
subtitle_languages = set.intersection(*[v.subtitle_languages for v in videos])
|
||||
initialized_providers = {}
|
||||
for provider_entry_point in pkg_resources.iter_entry_points(PROVIDERS_ENTRY_POINT):
|
||||
if providers is not None and provider_entry_point.name not in providers:
|
||||
logger.debug('Skipping provider %r: not in the list', provider_entry_point.name)
|
||||
continue
|
||||
Provider = provider_entry_point.load()
|
||||
if not Provider.languages & languages - subtitle_languages:
|
||||
logger.debug('Skipping provider %r: no language to search for', provider_entry_point.name)
|
||||
continue
|
||||
if not [v for v in videos if Provider.check(v)]:
|
||||
logger.debug('Skipping provider %r: video type not hosted here.', provider_entry_point.name)
|
||||
continue
|
||||
provider = Provider(**provider_configs.get(provider_entry_point.name, {}))
|
||||
try:
|
||||
provider.initialize()
|
||||
except ProviderNotAvailable as err:
|
||||
logger.warning('Provider %r is not available, discarding it', provider_entry_point.name)
|
||||
logger.debug('ProviderNotAvailable error: %r', str(err))
|
||||
continue
|
||||
except socket_error as err:
|
||||
logger.warning('Provider %r is not responding, discarding it', provider_entry_point.name)
|
||||
logger.debug('Provider socket error: %r', str(err))
|
||||
continue
|
||||
except:
|
||||
logger.exception('Unexpected error in provider %r', provider_entry_point.name)
|
||||
continue
|
||||
initialized_providers[provider_entry_point.name] = provider
|
||||
try:
|
||||
for video in videos:
|
||||
# search for subtitles
|
||||
subtitles = []
|
||||
downloaded_languages = set()
|
||||
for provider_name, provider in initialized_providers.items():
|
||||
if provider.check(video):
|
||||
if provider_name in discarded_providers:
|
||||
logger.debug('Skipping discarded provider %r', provider_name)
|
||||
continue
|
||||
|
||||
provider_video_languages = provider.languages & languages - video.subtitle_languages
|
||||
if not provider_video_languages:
|
||||
logger.debug('Skipping provider %r: no language to search for for video %r', provider_name,
|
||||
video)
|
||||
continue
|
||||
logger.info('Listing subtitles with provider %r for video %r with languages %r',
|
||||
provider_name, video, provider_video_languages)
|
||||
try:
|
||||
provider_subtitles = provider.list_subtitles(video, provider_video_languages)
|
||||
except ProviderNotAvailable as err:
|
||||
logger.warning('Provider %r is not available, discarding it', provider_name)
|
||||
logger.debug('ProviderNotAvailable error: %r', str(err))
|
||||
discarded_providers.add(provider_name)
|
||||
continue
|
||||
except:
|
||||
logger.exception('Unexpected error in provider %r', provider_name)
|
||||
continue
|
||||
logger.info('Found %d subtitle(s) on %s' % (
|
||||
len(provider_subtitles),
|
||||
provider_name,
|
||||
))
|
||||
subtitles.extend(provider_subtitles)
|
||||
|
||||
# find the best subtitles and download them
|
||||
for subtitle, score in sorted([(s, s.compute_score(video, hi_score_adjust)) \
|
||||
for s in subtitles], key=operator.itemgetter(1), reverse=True):
|
||||
|
||||
# filter
|
||||
if subtitle.provider_name in discarded_providers:
|
||||
logger.debug('Skipping subtitle from discarded provider %r', subtitle.provider_name)
|
||||
continue
|
||||
|
||||
if hearing_impaired is not None:
|
||||
if subtitle.hearing_impaired != hearing_impaired:
|
||||
logger.debug('Skipping subtitle: hearing impaired != %r', hearing_impaired)
|
||||
continue
|
||||
|
||||
if score < min_score:
|
||||
logger.debug('Skipping subtitle: score < %d', min_score)
|
||||
continue
|
||||
|
||||
if subtitle.language in downloaded_languages:
|
||||
logger.debug('Skipping subtitle: %r already downloaded', subtitle.language)
|
||||
continue
|
||||
|
||||
# download
|
||||
provider = initialized_providers[subtitle.provider_name]
|
||||
subtitle_path = get_subtitle_path(video.name, None if single else subtitle.language)
|
||||
if basename(subtitle_path) in fetched_subtitles:
|
||||
logger.debug('Skipping subtitle already retrieved %r', basename(subtitle_path))
|
||||
continue
|
||||
|
||||
logger.info('Downloading subtitle %r with score %d into %r', subtitle, score, subtitle_path)
|
||||
try:
|
||||
subtitle_text = provider.download_subtitle(subtitle)
|
||||
downloaded_subtitles[video].append(subtitle)
|
||||
except ProviderNotAvailable as err:
|
||||
logger.warning('Provider %r is not available, discarding it', subtitle.provider_name)
|
||||
logger.debug('ProviderNotAvailable error: %r', str(err))
|
||||
discarded_providers.add(subtitle.provider_name)
|
||||
continue
|
||||
except InvalidSubtitle:
|
||||
logger.info('Invalid subtitle, skipping it')
|
||||
continue
|
||||
except:
|
||||
logger.exception('Unexpected error in provider %r', subtitle.provider_name)
|
||||
continue
|
||||
with io.open(subtitle_path, 'w', encoding='utf-8') as f:
|
||||
f.write(subtitle_text)
|
||||
downloaded_languages.add(subtitle.language)
|
||||
fetched_subtitles.add(basename(subtitle_path))
|
||||
if single or sorted(downloaded_languages) == sorted(languages):
|
||||
break
|
||||
|
||||
finally: # terminate providers
|
||||
for (provider_name, provider) in initialized_providers.items():
|
||||
try:
|
||||
provider.terminate()
|
||||
except ProviderNotAvailable as err:
|
||||
logger.warning('Provider %r is not available, unable to terminate', provider_name)
|
||||
logger.debug('ProviderNotAvailable error: %r', str(err))
|
||||
except socket_error as err:
|
||||
logger.warning('Provider %r is not available, unable to terminate', provider_name)
|
||||
logger.debug('Provider socket error: %r', str(err))
|
||||
except:
|
||||
logger.exception('Unexpected error in provider %r', provider_name)
|
||||
return downloaded_subtitles
|
||||
@@ -0,0 +1,56 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
import inspect
|
||||
from dogpile.cache import make_region # @UnresolvedImport
|
||||
from dogpile.cache.backends.file import AbstractFileLock # @UnresolvedImport
|
||||
from dogpile.cache.compat import string_type # @UnresolvedImport
|
||||
from dogpile.core.readwrite_lock import ReadWriteMutex # @UnresolvedImport
|
||||
|
||||
|
||||
#: Subliminal's cache version
|
||||
CACHE_VERSION = 2
|
||||
|
||||
|
||||
def subliminal_key_generator(namespace, fn, to_str=string_type):
|
||||
"""Add a :data:`CACHE_VERSION` to dogpile.cache's default function_key_generator"""
|
||||
if namespace is None:
|
||||
namespace = '%d:%s:%s' % (CACHE_VERSION, fn.__module__, fn.__name__)
|
||||
else:
|
||||
namespace = '%d:%s:%s|%s' % (CACHE_VERSION, fn.__module__, fn.__name__, namespace)
|
||||
|
||||
args = inspect.getargspec(fn)
|
||||
has_self = args[0] and args[0][0] in ('self', 'cls')
|
||||
|
||||
def generate_key(*args, **kw):
|
||||
if kw:
|
||||
raise ValueError('Keyword arguments not supported')
|
||||
if has_self:
|
||||
args = args[1:]
|
||||
return namespace + '|' + ' '.join(map(to_str, args))
|
||||
return generate_key
|
||||
|
||||
|
||||
class MutexLock(AbstractFileLock):
|
||||
""":class:`MutexLock` is a thread-based rw lock based on :class:`dogpile.core.ReadWriteMutex`"""
|
||||
def __init__(self, filename):
|
||||
self.mutex = ReadWriteMutex()
|
||||
|
||||
def acquire_read_lock(self, wait):
|
||||
ret = self.mutex.acquire_read_lock(wait)
|
||||
return wait or ret
|
||||
|
||||
def acquire_write_lock(self, wait):
|
||||
ret = self.mutex.acquire_write_lock(wait)
|
||||
return wait or ret
|
||||
|
||||
def release_read_lock(self):
|
||||
return self.mutex.release_read_lock()
|
||||
|
||||
def release_write_lock(self):
|
||||
return self.mutex.release_write_lock()
|
||||
|
||||
|
||||
#: The dogpile.cache region (long-lived)
|
||||
region = make_region(function_key_generator=subliminal_key_generator)
|
||||
|
||||
#: The dogpile.cache region for :meth:`~subliminal.providers.Provider.query` (short-lived)
|
||||
query_region = make_region(function_key_generator=subliminal_key_generator)
|
||||
@@ -1,127 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
#
|
||||
# Subliminal - Subtitles, faster than your thoughts
|
||||
# Copyright (c) 2011 Antoine Bertin <diaoulael@gmail.com>
|
||||
#
|
||||
# This file is part of Subliminal.
|
||||
#
|
||||
# Subliminal is free software; you can redistribute it and/or modify it under
|
||||
# the terms of the Lesser GNU General Public License as published by
|
||||
# the Free Software Foundation; either version 3 of the License, or
|
||||
# (at your option) any later version.
|
||||
#
|
||||
# Subliminal is distributed in the hope that it will be useful,
|
||||
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
# Lesser GNU General Public License for more details.
|
||||
#
|
||||
# You should have received a copy of the Lesser GNU General Public License
|
||||
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
#
|
||||
|
||||
|
||||
class Error(Exception):
|
||||
"""Base class for exceptions in subliminal"""
|
||||
pass
|
||||
|
||||
|
||||
class BadStateError(Error):
|
||||
"""Exception raised when an invalid action is asked
|
||||
|
||||
Attributes:
|
||||
current -- current state of Subliminal instance
|
||||
expected -- expected state of Subliminal instance
|
||||
"""
|
||||
def __init__(self, current, expected):
|
||||
self.current = current
|
||||
self.expected = expected
|
||||
|
||||
def __str__(self):
|
||||
return 'Expected state %d but current state is %d' % (self.expected, self.current)
|
||||
|
||||
|
||||
class LanguageError(Error):
|
||||
"""Exception raised when invalid language is submitted
|
||||
|
||||
Attributes:
|
||||
language -- language that cause the error
|
||||
"""
|
||||
def __init__(self, language):
|
||||
self.language = language
|
||||
|
||||
def __str__(self):
|
||||
return self.language
|
||||
|
||||
|
||||
class PluginError(Error):
|
||||
""""Exception raised when invalid plugin is submitted
|
||||
|
||||
Attributes:
|
||||
plugin -- plugin that cause the error
|
||||
"""
|
||||
def __init__(self, plugin):
|
||||
self.plugin = plugin
|
||||
|
||||
def __str__(self):
|
||||
return self.plugin
|
||||
|
||||
|
||||
class WrongTaskError(Error):
|
||||
""""Exception raised when invalid task is submitted"""
|
||||
pass
|
||||
|
||||
|
||||
class DownloadFailedError(Error):
|
||||
""""Exception raised when a download task has failed in plugin"""
|
||||
pass
|
||||
|
||||
|
||||
class Subtitle(object):
|
||||
"""Subtitle class
|
||||
|
||||
Attributes:
|
||||
video_path -- path to the video file
|
||||
path -- path to the subtitle file
|
||||
plugin -- plugin used
|
||||
language -- language of the subtitle
|
||||
link -- download link
|
||||
release -- release group identified by guessit
|
||||
teams -- identified by subliminal
|
||||
"""
|
||||
def __init__(self, video_path=None, path=None, plugin=None, language=None, link=None, release=None, teams=None):
|
||||
self.video_path = video_path
|
||||
self.path = path
|
||||
self.plugin = plugin
|
||||
self.language = language
|
||||
self.link = link
|
||||
self.release = release
|
||||
self.teams = teams
|
||||
|
||||
def __repr__(self):
|
||||
return repr({'video_path': self.video_path, 'path': self.path, 'plugin': self.plugin,
|
||||
'language': self.language, 'link': self.link, 'release': self.release, 'teams': self.teams})
|
||||
|
||||
|
||||
class Task(object):
|
||||
"""Base class for tasks to use in subliminal"""
|
||||
pass
|
||||
|
||||
|
||||
class ListTask(Task):
|
||||
"""List task to list subtitles"""
|
||||
def __init__(self, filepath, languages, plugin, config):
|
||||
self.filepath = filepath
|
||||
self.plugin = plugin
|
||||
self.languages = languages
|
||||
self.config = config
|
||||
|
||||
|
||||
class DownloadTask(Task):
|
||||
"""Download task to download subtitles"""
|
||||
def __init__(self, subtitles):
|
||||
self.subtitles = subtitles
|
||||
|
||||
|
||||
class StopTask(Task):
|
||||
"""Stop task to stop workers"""
|
||||
pass
|
||||
@@ -0,0 +1,157 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
from __future__ import unicode_literals, print_function
|
||||
import argparse
|
||||
import datetime
|
||||
import logging
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
import babelfish
|
||||
import guessit
|
||||
import pkg_resources
|
||||
from subliminal import (__version__, PROVIDERS_ENTRY_POINT, cache_region, MutexLock, Video, Episode, Movie, scan_videos,
|
||||
download_best_subtitles)
|
||||
try:
|
||||
import colorlog
|
||||
except ImportError:
|
||||
colorlog = None
|
||||
|
||||
|
||||
DEFAULT_CACHE_FILE = os.path.join('~', '.config', 'subliminal.cache.dbm')
|
||||
|
||||
|
||||
def subliminal():
|
||||
parser = argparse.ArgumentParser(prog='subliminal', description='Subtitles, faster than your thoughts',
|
||||
epilog='Suggestions and bug reports are greatly appreciated: '
|
||||
'https://github.com/Diaoul/subliminal/issues', add_help=False)
|
||||
|
||||
# required arguments
|
||||
required_arguments_group = parser.add_argument_group('required arguments')
|
||||
required_arguments_group.add_argument('paths', nargs='+', metavar='PATH', help='path to video file or folder')
|
||||
required_arguments_group.add_argument('-l', '--languages', nargs='+', required=True, metavar='LANGUAGE',
|
||||
help='wanted languages as IETF codes e.g. fr, pt-BR, sr-Cyrl ')
|
||||
|
||||
# configuration
|
||||
configuration_group = parser.add_argument_group('configuration')
|
||||
configuration_group.add_argument('-s', '--single', action='store_true',
|
||||
help='download without language code in subtitle\'s filename i.e. .srt only')
|
||||
configuration_group.add_argument('-c', '--cache-file', default=DEFAULT_CACHE_FILE,
|
||||
help='cache file (default: %(default)s)')
|
||||
|
||||
# filtering
|
||||
filtering_group = parser.add_argument_group('filtering')
|
||||
providers = [ep.name for ep in pkg_resources.iter_entry_points(PROVIDERS_ENTRY_POINT)]
|
||||
filtering_group.add_argument('-p', '--providers', nargs='+', metavar='PROVIDER',
|
||||
help='providers to use (%s)' % ', '.join(providers))
|
||||
filtering_group.add_argument('-m', '--min-score', type=int,
|
||||
help='minimum score for subtitles (0-%d for episodes, 0-%d for movies)'
|
||||
% (Episode.scores['hash'], Movie.scores['hash']))
|
||||
filtering_group.add_argument('-a', '--age', help='download subtitles for videos newer than AGE e.g. 12h, 1w2d')
|
||||
filtering_group.add_argument('-h', '--hearing-impaired', action='store_true',
|
||||
help='download hearing impaired subtitles')
|
||||
filtering_group.add_argument('-f', '--force', action='store_true',
|
||||
help='force subtitle download for videos with existing subtitles')
|
||||
|
||||
# output
|
||||
output_group = parser.add_argument_group('output')
|
||||
output_exclusive_group = output_group.add_mutually_exclusive_group()
|
||||
output_exclusive_group.add_argument('-q', '--quiet', action='store_true', help='disable output')
|
||||
output_exclusive_group.add_argument('-v', '--verbose', action='store_true', help='verbose output')
|
||||
output_group.add_argument('--color', action='store_true', help='add color to console output (requires colorlog)')
|
||||
|
||||
# troubleshooting
|
||||
troubleshooting_group = parser.add_argument_group('troubleshooting')
|
||||
troubleshooting_group.add_argument('--debug', action='store_true', help='debug output')
|
||||
troubleshooting_group.add_argument('--version', action='version', version=__version__)
|
||||
troubleshooting_group.add_argument('--help', action='help', help='show this help message and exit')
|
||||
|
||||
# parse args
|
||||
args = parser.parse_args()
|
||||
|
||||
# parse paths
|
||||
try:
|
||||
args.paths = [os.path.abspath(os.path.expanduser(p.decode('utf-8'))) for p in args.paths]
|
||||
except UnicodeDecodeError:
|
||||
parser.error('argument paths: encodings is not utf-8: %r' % args.paths)
|
||||
|
||||
# parse languages
|
||||
try:
|
||||
args.languages = set( babelfish.Language.fromietf(l) for l in args.languages )
|
||||
except babelfish.Error:
|
||||
parser.error('argument -l/--languages: codes are not IETF: %r' % args.languages)
|
||||
|
||||
# parse age
|
||||
if args.age is not None:
|
||||
match = re.match(r'^(?:(?P<weeks>\d+?)w)?(?:(?P<days>\d+?)d)?(?:(?P<hours>\d+?)h)?$', args.age)
|
||||
if not match:
|
||||
parser.error('argument -a/--age: invalid age: %r' % args.age)
|
||||
args.age = datetime.timedelta(**dict([(k, int(v)) for k, v in match.groupdict(0).items()]))
|
||||
|
||||
# parse cache-file
|
||||
args.cache_file = os.path.abspath(os.path.expanduser(args.cache_file))
|
||||
if not os.path.exists(os.path.split(args.cache_file)[0]):
|
||||
parser.error('argument -c/--cache-file: directory %r for cache file does not exist'
|
||||
% os.path.split(args.cache_file)[0])
|
||||
|
||||
# parse provider configs
|
||||
provider_configs = {}
|
||||
|
||||
# parse color
|
||||
if args.color and colorlog is None:
|
||||
parser.error('argument --color: colorlog required')
|
||||
|
||||
# setup output
|
||||
if args.debug:
|
||||
handler = logging.StreamHandler()
|
||||
if args.color:
|
||||
handler.setFormatter(colorlog.ColoredFormatter('%(log_color)s%(levelname)-8s%(reset)s [%(blue)s%(name)s-%(funcName)s:%(lineno)d%(reset)s] %(message)s',
|
||||
log_colors=dict(colorlog.default_log_colors.items() + [('DEBUG', 'cyan')])))
|
||||
else:
|
||||
handler.setFormatter(logging.Formatter('%(levelname)-8s [%(name)s-%(funcName)s:%(lineno)d] %(message)s'))
|
||||
logging.getLogger().addHandler(handler)
|
||||
logging.getLogger().setLevel(logging.DEBUG)
|
||||
elif args.verbose:
|
||||
handler = logging.StreamHandler()
|
||||
if args.color:
|
||||
handler.setFormatter(colorlog.ColoredFormatter('%(log_color)s%(levelname)-8s%(reset)s [%(blue)s%(name)s%(reset)s] %(message)s'))
|
||||
else:
|
||||
handler.setFormatter(logging.Formatter('%(levelname)-8s [%(name)s] %(message)s'))
|
||||
logging.getLogger('subliminal').addHandler(handler)
|
||||
logging.getLogger('subliminal').setLevel(logging.INFO)
|
||||
elif not args.quiet:
|
||||
handler = logging.StreamHandler()
|
||||
if args.color:
|
||||
handler.setFormatter(colorlog.ColoredFormatter('[%(log_color)s%(levelname)s%(reset)s] %(message)s'))
|
||||
else:
|
||||
handler.setFormatter(logging.Formatter('%(levelname)s: %(message)s'))
|
||||
logging.getLogger('subliminal.api').addHandler(handler)
|
||||
logging.getLogger('subliminal.api').setLevel(logging.INFO)
|
||||
|
||||
# configure cache
|
||||
cache_region.configure('dogpile.cache.dbm', expiration_time=datetime.timedelta(days=30), # @UndefinedVariable
|
||||
arguments={'filename': args.cache_file, 'lock_factory': MutexLock})
|
||||
|
||||
# scan videos
|
||||
videos = scan_videos([p for p in args.paths if os.path.exists(p)], subtitles=not args.force,
|
||||
embedded_subtitles=not args.force, age=args.age)
|
||||
|
||||
# guess videos
|
||||
videos.extend([Video.fromguess(os.path.split(p)[1], guessit.guess_file_info(p, info=['filename'])) for p in args.paths
|
||||
if not os.path.exists(p)])
|
||||
|
||||
# download best subtitles
|
||||
subtitles = download_best_subtitles(videos, args.languages, providers=args.providers,
|
||||
provider_configs=provider_configs, single=args.single,
|
||||
min_score=args.min_score, hearing_impaired=args.hearing_impaired)
|
||||
|
||||
# result output
|
||||
if not subtitles:
|
||||
if not args.quiet:
|
||||
sys.stderr.write('No subtitles downloaded\n')
|
||||
exit(1)
|
||||
if not args.quiet:
|
||||
subtitles_count = sum([len(s) for s in subtitles.values()])
|
||||
if subtitles_count == 1:
|
||||
print('%d subtitle downloaded' % subtitles_count)
|
||||
else:
|
||||
print('%d subtitles downloaded' % subtitles_count)
|
||||
@@ -0,0 +1,31 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
from __future__ import unicode_literals
|
||||
from babelfish import LanguageReverseConverter, language_converters
|
||||
|
||||
|
||||
class Addic7edConverter(LanguageReverseConverter):
|
||||
def __init__(self):
|
||||
self.name_converter = language_converters['name']
|
||||
self.from_addic7ed = {'Català': ('cat',), 'Chinese (Simplified)': ('zho',), 'Chinese (Traditional)': ('zho',),
|
||||
'Euskera': ('eus',), 'Galego': ('glg',), 'Greek': ('ell',), 'Malay': ('msa',),
|
||||
'Portuguese (Brazilian)': ('por', 'BR'), 'Serbian (Cyrillic)': ('srp', None, 'Cyrl'),
|
||||
'Serbian (Latin)': ('srp',), 'Spanish (Latin America)': ('spa',),
|
||||
'Spanish (Spain)': ('spa',)}
|
||||
self.to_addic7ed = {('cat',): 'Català', ('zho',): 'Chinese (Simplified)', ('eus',): 'Euskera',
|
||||
('glg',): 'Galego', ('ell',): 'Greek', ('msa',): 'Malay',
|
||||
('por', 'BR'): 'Portuguese (Brazilian)', ('srp', None, 'Cyrl'): 'Serbian (Cyrillic)'}
|
||||
self.codes = self.name_converter.codes | set(self.from_addic7ed.keys())
|
||||
|
||||
def convert(self, alpha3, country=None, script=None):
|
||||
if (alpha3, country, script) in self.to_addic7ed:
|
||||
return self.to_addic7ed[(alpha3, country, script)]
|
||||
if (alpha3, country) in self.to_addic7ed:
|
||||
return self.to_addic7ed[(alpha3, country)]
|
||||
if (alpha3,) in self.to_addic7ed:
|
||||
return self.to_addic7ed[(alpha3,)]
|
||||
return self.name_converter.convert(alpha3, country, script)
|
||||
|
||||
def reverse(self, addic7ed):
|
||||
if addic7ed in self.from_addic7ed:
|
||||
return self.from_addic7ed[addic7ed]
|
||||
return self.name_converter.reverse(addic7ed)
|
||||
@@ -0,0 +1,32 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
from __future__ import unicode_literals
|
||||
from babelfish import LanguageReverseConverter, LanguageConvertError, LanguageReverseError
|
||||
|
||||
|
||||
class PodnapisiConverter(LanguageReverseConverter):
|
||||
def __init__(self):
|
||||
self.from_podnapisi = {2: ('eng',), 28: ('spa',), 26: ('pol',), 36: ('srp',), 1: ('slv',), 38: ('hrv',),
|
||||
9: ('ita',), 8: ('fra',), 48: ('por', 'BR'), 23: ('nld',), 12: ('ara',), 13: ('ron',),
|
||||
33: ('bul',), 32: ('por',), 16: ('ell',), 15: ('hun',), 31: ('fin',), 30: ('tur',),
|
||||
7: ('ces',), 25: ('swe',), 27: ('rus',), 24: ('dan',), 22: ('heb',), 51: ('vie',),
|
||||
52: ('fas',), 5: ('deu',), 14: ('spa', 'AR'), 54: ('ind',), 47: ('srp', None, 'Cyrl'),
|
||||
3: ('nor',), 20: ('est',), 10: ('bos',), 17: ('zho',), 37: ('slk',), 35: ('mkd',),
|
||||
11: ('jpn',), 4: ('kor',), 29: ('sqi',), 6: ('isl',), 19: ('lit',), 46: ('ukr',),
|
||||
44: ('tha',), 53: ('cat',), 56: ('sin',), 21: ('lav',), 40: ('cmn',), 55: ('msa',),
|
||||
42: ('hin',), 50: ('bel',)}
|
||||
self.to_podnapisi = dict([(v, k) for k, v in self.from_podnapisi.items()])
|
||||
self.codes = set(self.from_podnapisi.keys())
|
||||
|
||||
def convert(self, alpha3, country=None, script=None):
|
||||
if (alpha3,) in self.to_podnapisi:
|
||||
return self.to_podnapisi[(alpha3,)]
|
||||
if (alpha3, country) in self.to_podnapisi:
|
||||
return self.to_podnapisi[(alpha3, country)]
|
||||
if (alpha3, country, script) in self.to_podnapisi:
|
||||
return self.to_podnapisi[(alpha3, country, script)]
|
||||
raise LanguageConvertError(alpha3, country, script)
|
||||
|
||||
def reverse(self, podnapisi):
|
||||
if podnapisi not in self.from_podnapisi:
|
||||
raise LanguageReverseError(podnapisi)
|
||||
return self.from_podnapisi[podnapisi]
|
||||
@@ -0,0 +1,24 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
from __future__ import unicode_literals
|
||||
from babelfish import LanguageReverseConverter, language_converters
|
||||
|
||||
|
||||
class TVsubtitlesConverter(LanguageReverseConverter):
|
||||
def __init__(self):
|
||||
self.alpha2_converter = language_converters['alpha2']
|
||||
self.from_tvsubtitles = {'br': ('por', 'BR'), 'ua': ('ukr',), 'gr': ('ell',), 'cn': ('zho',), 'jp': ('jpn',),
|
||||
'cz': ('ces',)}
|
||||
self.to_tvsubtitles = set([(v, k) for k, v in self.from_tvsubtitles])
|
||||
self.codes = self.alpha2_converter.codes | set(self.from_tvsubtitles.keys())
|
||||
|
||||
def convert(self, alpha3, country=None, script=None):
|
||||
if (alpha3, country) in self.to_tvsubtitles:
|
||||
return self.to_tvsubtitles[(alpha3, country)]
|
||||
if (alpha3,) in self.to_tvsubtitles:
|
||||
return self.to_tvsubtitles[(alpha3,)]
|
||||
return self.alpha2_converter.convert(alpha3, country, script)
|
||||
|
||||
def reverse(self, tvsubtitles):
|
||||
if tvsubtitles in self.from_tvsubtitles:
|
||||
return self.from_tvsubtitles[tvsubtitles]
|
||||
return self.alpha2_converter.reverse(tvsubtitles)
|
||||
@@ -0,0 +1,27 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
from __future__ import unicode_literals
|
||||
|
||||
|
||||
class Error(Exception):
|
||||
"""Base class for exceptions in subliminal"""
|
||||
pass
|
||||
|
||||
|
||||
class ProviderError(Error):
|
||||
"""Exception raised by providers"""
|
||||
pass
|
||||
|
||||
|
||||
class ProviderConfigurationError(ProviderError):
|
||||
"""Exception raised by providers when badly configured"""
|
||||
pass
|
||||
|
||||
|
||||
class ProviderNotAvailable(ProviderError):
|
||||
"""Exception raised by providers when unavailable"""
|
||||
pass
|
||||
|
||||
|
||||
class InvalidSubtitle(ProviderError):
|
||||
"""Exception raised by providers when the downloaded subtitle is invalid"""
|
||||
pass
|
||||
@@ -1,134 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
#
|
||||
# Subliminal - Subtitles, faster than your thoughts
|
||||
# Copyright (c) 2008-2011 Patrick Dessalle <patrick@dessalle.be>
|
||||
# Copyright (c) 2011 Antoine Bertin <diaoulael@gmail.com>
|
||||
#
|
||||
# This file is part of Subliminal.
|
||||
#
|
||||
# Subliminal is free software; you can redistribute it and/or modify it under
|
||||
# the terms of the Lesser GNU General Public License as published by
|
||||
# the Free Software Foundation; either version 3 of the License, or
|
||||
# (at your option) any later version.
|
||||
#
|
||||
# Subliminal is distributed in the hope that it will be useful,
|
||||
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
# Lesser GNU General Public License for more details.
|
||||
#
|
||||
# You should have received a copy of the Lesser GNU General Public License
|
||||
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
#
|
||||
|
||||
from BeautifulSoup import BeautifulSoup
|
||||
from subliminal.classes import Subtitle
|
||||
import guessit
|
||||
import PluginBase
|
||||
import urllib2
|
||||
import re
|
||||
|
||||
|
||||
class Addic7ed(PluginBase.PluginBase):
|
||||
site_url = 'http://www.addic7ed.com'
|
||||
site_name = 'Addic7ed'
|
||||
server_url = 'http://www.addic7ed.com'
|
||||
api_based = False
|
||||
_plugin_languages = {u'English': 'en',
|
||||
u'English (US)': 'en',
|
||||
u'English (UK)': 'en',
|
||||
u'Italian': 'it',
|
||||
u'Portuguese': 'pt',
|
||||
u'Portuguese (Brazilian)': 'pt-br',
|
||||
u'Romanian': 'ro',
|
||||
u'Español (Latinoamérica)': 'es',
|
||||
u'Español (España)': 'es',
|
||||
u'Spanish (Latin America)': 'es',
|
||||
u'Español': 'es',
|
||||
u'Spanish': 'es',
|
||||
u'Spanish (Spain)': 'es',
|
||||
u'French': 'fr',
|
||||
u'Greek': 'el',
|
||||
u'Arabic': 'ar',
|
||||
u'German': 'de',
|
||||
u'Croatian': 'hr',
|
||||
u'Indonesian': 'id',
|
||||
u'Hebrew': 'he',
|
||||
u'Russian': 'ru',
|
||||
u'Turkish': 'tr',
|
||||
u'Swedish': 'se',
|
||||
u'Czech': 'cs',
|
||||
u'Dutch': 'nl',
|
||||
u'Hungarian': 'hu',
|
||||
u'Norwegian': 'no',
|
||||
u'Polish': 'pl',
|
||||
u'Persian': 'fa'}
|
||||
|
||||
def __init__(self, config_dict=None):
|
||||
super(Addic7ed, self).__init__(self._plugin_languages, config_dict, isRevert=True)
|
||||
#http://www.addic7ed.com/serie/Smallville/9/11/Absolute_Justice
|
||||
self.release_pattern = re.compile(' \nVersion (.+), ([0-9]+).([0-9])+ MBs')
|
||||
|
||||
def list(self, filepath, languages):
|
||||
if not self.checkLanguages(languages):
|
||||
return []
|
||||
guess = guessit.guess_file_info(filepath, 'autodetect')
|
||||
if guess['type'] != 'episode':
|
||||
self.logger.debug(u'Not an episode')
|
||||
return []
|
||||
# add multiple things to the release group set
|
||||
release_group = set()
|
||||
if 'releaseGroup' in guess:
|
||||
release_group.add(guess['releaseGroup'].lower())
|
||||
else:
|
||||
if 'title' in guess:
|
||||
release_group.add(guess['title'].lower())
|
||||
if 'screenSize' in guess:
|
||||
release_group.add(guess['screenSize'].lower())
|
||||
if 'series' not in guess or len(release_group) == 0:
|
||||
self.logger.debug(u'Not enough information to proceed')
|
||||
return []
|
||||
self.release_group = release_group # used to sort results
|
||||
return self.query(guess['series'], guess['season'], guess['episodeNumber'], release_group, filepath, languages)
|
||||
|
||||
def query(self, name, season, episode, release_group, filepath, languages=None):
|
||||
searchname = name.lower().replace(' ', '_')
|
||||
if isinstance(searchname, unicode):
|
||||
searchname = searchname.encode('utf-8')
|
||||
searchurl = '%s/serie/%s/%s/%s/%s' % (self.server_url, urllib2.quote(searchname), season, episode, urllib2.quote(searchname))
|
||||
self.logger.debug(u'Searching in %s' % searchurl)
|
||||
try:
|
||||
req = urllib2.Request(searchurl, headers={'User-Agent': self.user_agent})
|
||||
page = urllib2.urlopen(req, timeout=self.timeout)
|
||||
except urllib2.HTTPError as inst:
|
||||
self.logger.info(u'Error: %s - %s' % (searchurl, inst))
|
||||
return []
|
||||
except urllib2.URLError as inst:
|
||||
self.logger.info(u'TimeOut: %s' % inst)
|
||||
return []
|
||||
soup = BeautifulSoup(page.read())
|
||||
sublinks = []
|
||||
for html_sub in soup('td', {'class': 'NewsTitle', 'colspan': '3'}):
|
||||
if not self.release_pattern.match(str(html_sub.contents[1])): # On not needed soup td result
|
||||
continue
|
||||
sub_teams = self.listTeams([self.release_pattern.match(str(html_sub.contents[1])).groups()[0].lower()], ['.', '_', ' ', '/', '-'])
|
||||
if not release_group.intersection(sub_teams): # On wrong team
|
||||
continue
|
||||
html_language = html_sub.findNext('td', {'class': 'language'})
|
||||
sub_language = self.getRevertLanguage(html_language.contents[0].strip().replace(' ', ''))
|
||||
if languages and not sub_language in languages: # On wrong language
|
||||
continue
|
||||
html_status = html_language.findNextSibling('td')
|
||||
sub_status = html_status.find('b').string.strip()
|
||||
if not sub_status == 'Completed': # On not completed subtitles
|
||||
continue
|
||||
sub_link = self.server_url + html_status.findNextSibling('td', {'colspan': '3'}).find('a')['href']
|
||||
self.logger.debug(u'Found a match with teams: %s' % sub_teams)
|
||||
result = Subtitle(filepath, self.getSubtitlePath(filepath, sub_language), self.__class__.__name__, sub_language, sub_link, teams=sub_teams)
|
||||
sublinks.append(result)
|
||||
sublinks.sort(self._cmpReleaseGroup)
|
||||
return sublinks
|
||||
|
||||
def download(self, subtitle):
|
||||
self.downloadFile(subtitle.link, subtitle.path)
|
||||
return subtitle
|
||||
|
||||
@@ -1,154 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
#
|
||||
# Subliminal - Subtitles, faster than your thoughts
|
||||
# Copyright (c) 2008-2011 Patrick Dessalle <patrick@dessalle.be>
|
||||
# Copyright (c) 2011 Antoine Bertin <diaoulael@gmail.com>
|
||||
#
|
||||
# This file is part of Subliminal.
|
||||
#
|
||||
# Subliminal is free software; you can redistribute it and/or modify it under
|
||||
# the terms of the Lesser GNU General Public License as published by
|
||||
# the Free Software Foundation; either version 3 of the License, or
|
||||
# (at your option) any later version.
|
||||
#
|
||||
# Subliminal is distributed in the hope that it will be useful,
|
||||
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
# Lesser GNU General Public License for more details.
|
||||
#
|
||||
# You should have received a copy of the Lesser GNU General Public License
|
||||
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
#
|
||||
|
||||
from xml.dom import minidom
|
||||
import guessit
|
||||
import PluginBase
|
||||
import os
|
||||
try:
|
||||
import cPickle as pickle
|
||||
except ImportError:
|
||||
import pickle
|
||||
import urllib2
|
||||
from subliminal.classes import Subtitle
|
||||
|
||||
|
||||
class BierDopje(PluginBase.PluginBase):
|
||||
site_url = 'http://bierdopje.com'
|
||||
site_name = 'BierDopje'
|
||||
server_url = 'http://api.bierdopje.com/A2B638AC5D804C2E/'
|
||||
api_based = True
|
||||
exceptions = {'the office': 10358,
|
||||
'the office us': 10358,
|
||||
'greys anatomy': 3733,
|
||||
'sanctuary us': 7904,
|
||||
'human target 2010': 12986,
|
||||
'csi miami': 2187,
|
||||
'castle 2009': 12708,
|
||||
'chase 2010': 14228,
|
||||
'the defenders 2010': 14225,
|
||||
'hawaii five-0 2010': 14211}
|
||||
_plugin_languages = {'en': 'en', 'nl': 'nl'}
|
||||
|
||||
def __init__(self, config_dict=None):
|
||||
super(BierDopje, self).__init__(self._plugin_languages, config_dict)
|
||||
#http://api.bierdopje.com/23459DC262C0A742/GetShowByName/30+Rock
|
||||
#http://api.bierdopje.com/23459DC262C0A742/GetAllSubsFor/94/5/1/en (30 rock, season 5, episode 1)
|
||||
if config_dict and config_dict['cache_dir']:
|
||||
self.showid_cache = os.path.join(config_dict['cache_dir'], 'bierdopje_showid.cache')
|
||||
with self.lock:
|
||||
if not os.path.exists(self.showid_cache):
|
||||
if not os.path.exists(os.path.dirname(self.showid_cache)):
|
||||
raise Exception('Cache directory does not exist')
|
||||
f = open(self.showid_cache, 'w')
|
||||
pickle.dump({}, f)
|
||||
f.close()
|
||||
f = open(self.showid_cache, 'r')
|
||||
self.showids = pickle.load(f)
|
||||
self.logger.debug(u'Reading showids from cache: %s' % self.showids)
|
||||
f.close()
|
||||
|
||||
def list(self, filepath, languages):
|
||||
if not self.config_dict['cache_dir']:
|
||||
raise Exception('Cache directory is required for this plugin')
|
||||
possible_languages = self.possible_languages(languages)
|
||||
if not possible_languages:
|
||||
return []
|
||||
guess = guessit.guess_file_info(filepath, 'autodetect')
|
||||
if guess['type'] != 'episode':
|
||||
self.logger.debug(u'Not an episode')
|
||||
return []
|
||||
# add multiple things to the release group set
|
||||
release_group = set()
|
||||
if 'releaseGroup' in guess:
|
||||
release_group.add(guess['releaseGroup'].lower())
|
||||
else:
|
||||
if 'title' in guess:
|
||||
release_group.add(guess['title'].lower())
|
||||
if 'screenSize' in guess:
|
||||
release_group.add(guess['screenSize'].lower())
|
||||
if 'series' not in guess or len(release_group) == 0:
|
||||
self.logger.debug(u'Not enough information to proceed')
|
||||
return []
|
||||
self.release_group = release_group # used to sort results
|
||||
return self.query(guess['series'], guess['season'], guess['episodeNumber'], release_group, filepath, possible_languages)
|
||||
|
||||
def download(self, subtitle):
|
||||
self.downloadFile(subtitle.link, subtitle.path)
|
||||
return subtitle
|
||||
|
||||
def query(self, name, season, episode, release_group, filepath, languages):
|
||||
sublinks = []
|
||||
# get the show id
|
||||
show_name = name.lower()
|
||||
if show_name in self.exceptions: # get it from exceptions
|
||||
show_id = self.exceptions[show_name]
|
||||
elif show_name in self.showids: # get it from cache
|
||||
show_id = self.showids[show_name]
|
||||
else: # retrieve it
|
||||
show_name_encoded = show_name
|
||||
if isinstance(show_name_encoded, unicode):
|
||||
show_name_encoded = show_name_encoded.encode('utf-8')
|
||||
show_id_url = '%sGetShowByName/%s' % (self.server_url, urllib2.quote(show_name_encoded))
|
||||
self.logger.debug(u'Retrieving show id from web at %s' % show_id_url)
|
||||
page = urllib2.urlopen(show_id_url)
|
||||
dom = minidom.parse(page)
|
||||
if not dom or len(dom.getElementsByTagName('showid')) == 0: # no proper result
|
||||
page.close()
|
||||
return []
|
||||
show_id = dom.getElementsByTagName('showid')[0].firstChild.data
|
||||
self.showids[show_name] = show_id
|
||||
with self.lock:
|
||||
f = open(self.showid_cache, 'w')
|
||||
self.logger.debug(u'Writing showid %s to cache file' % show_id)
|
||||
pickle.dump(self.showids, f)
|
||||
f.close()
|
||||
page.close()
|
||||
|
||||
# get the subs for the show id we have
|
||||
for language in languages:
|
||||
subs_url = '%sGetAllSubsFor/%s/%s/%s/%s' % (self.server_url, show_id, season, episode, language)
|
||||
self.logger.debug(u'Getting subtitles at %s' % subs_url)
|
||||
page = urllib2.urlopen(subs_url)
|
||||
dom = minidom.parse(page)
|
||||
page.close()
|
||||
for sub in dom.getElementsByTagName('result'):
|
||||
sub_release = sub.getElementsByTagName('filename')[0].firstChild.data
|
||||
if sub_release.endswith('.srt'):
|
||||
sub_release = sub_release[:-4]
|
||||
sub_release = sub_release + '.avi' # put a random extension for guessit not to fail guessing that file
|
||||
# guess information from subtitle
|
||||
sub_guess = guessit.guess_file_info(sub_release, 'episode')
|
||||
sub_release_group = set()
|
||||
if 'releaseGroup' in sub_guess:
|
||||
sub_release_group.add(sub_guess['releaseGroup'].lower())
|
||||
else:
|
||||
if 'title' in sub_guess:
|
||||
sub_release_group.add(sub_guess['title'].lower())
|
||||
if 'screenSize' in sub_guess:
|
||||
sub_release_group.add(sub_guess['screenSize'].lower())
|
||||
sub_link = sub.getElementsByTagName('downloadlink')[0].firstChild.data
|
||||
result = Subtitle(filepath, self.getSubtitlePath(filepath, language), self.__class__.__name__, language, sub_link, sub_release, sub_release_group)
|
||||
sublinks.append(result)
|
||||
sublinks.sort(self._cmpReleaseGroup)
|
||||
return sublinks
|
||||
|
||||
@@ -1,172 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
#
|
||||
# Subliminal - Subtitles, faster than your thoughts
|
||||
# Copyright (c) 2008-2011 Patrick Dessalle <patrick@dessalle.be>
|
||||
# Copyright (c) 2011 Antoine Bertin <diaoulael@gmail.com>
|
||||
#
|
||||
# This file is part of Subliminal.
|
||||
#
|
||||
# Subliminal is free software; you can redistribute it and/or modify it under
|
||||
# the terms of the Lesser GNU General Public License as published by
|
||||
# the Free Software Foundation; either version 3 of the License, or
|
||||
# (at your option) any later version.
|
||||
#
|
||||
# Subliminal is distributed in the hope that it will be useful,
|
||||
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
# Lesser GNU General Public License for more details.
|
||||
#
|
||||
# You should have received a copy of the Lesser GNU General Public License
|
||||
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
#
|
||||
|
||||
import PluginBase
|
||||
import gzip
|
||||
import os
|
||||
import socket
|
||||
import xmlrpclib
|
||||
import guessit
|
||||
import unicodedata
|
||||
from subliminal.classes import Subtitle, DownloadFailedError
|
||||
|
||||
|
||||
class OpenSubtitles(PluginBase.PluginBase):
|
||||
site_url = 'http://www.opensubtitles.org'
|
||||
site_name = 'OpenSubtitles'
|
||||
server_url = 'http://api.opensubtitles.org/xml-rpc'
|
||||
user_agent = 'Subliminal v0.4'
|
||||
api_based = True
|
||||
_plugin_languages = {'aa': 'aar', 'ab': 'abk', 'af': 'afr', 'ak': 'aka', 'sq': 'alb', 'am': 'amh', 'ar': 'ara', 'an': 'arg', 'hy': 'arm',
|
||||
'as': 'asm', 'av': 'ava', 'ae': 'ave', 'ay': 'aym', 'az': 'aze', 'ba': 'bak', 'bm': 'bam', 'eu': 'baq', 'be': 'bel', 'bn': 'ben',
|
||||
'bh': 'bih', 'bi': 'bis', 'bs': 'bos', 'br': 'bre', 'bg': 'bul', 'my': 'bur', 'ca': 'cat', 'ch': 'cha', 'ce': 'che', 'zh': 'chi',
|
||||
'cu': 'chu', 'cv': 'chv', 'kw': 'cor', 'co': 'cos', 'cr': 'cre', 'cs': 'cze', 'da': 'dan', 'dv': 'div', 'nl': 'dut', 'dz': 'dzo',
|
||||
'en': 'eng', 'eo': 'epo', 'et': 'est', 'ee': 'ewe', 'fo': 'fao', 'fj': 'fij', 'fi': 'fin', 'fr': 'fre', 'fy': 'fry', 'ff': 'ful',
|
||||
'ka': 'geo', 'de': 'ger', 'gd': 'gla', 'ga': 'gle', 'gl': 'glg', 'gv': 'glv', 'el': 'ell', 'gn': 'grn', 'gu': 'guj', 'ht': 'hat',
|
||||
'ha': 'hau', 'he': 'heb', 'hz': 'her', 'hi': 'hin', 'ho': 'hmo', 'hr': 'hrv', 'hu': 'hun', 'ig': 'ibo', 'is': 'ice', 'io': 'ido',
|
||||
'ii': 'iii', 'iu': 'iku', 'ie': 'ile', 'ia': 'ina', 'id': 'ind', 'ik': 'ipk', 'it': 'ita', 'jv': 'jav', 'ja': 'jpn', 'kl': 'kal',
|
||||
'kn': 'kan', 'ks': 'kas', 'kr': 'kau', 'kk': 'kaz', 'km': 'khm', 'ki': 'kik', 'rw': 'kin', 'ky': 'kir', 'kv': 'kom', 'kg': 'kon',
|
||||
'ko': 'kor', 'kj': 'kua', 'ku': 'kur', 'lo': 'lao', 'la': 'lat', 'lv': 'lav', 'li': 'lim', 'ln': 'lin', 'lt': 'lit', 'lb': 'ltz',
|
||||
'lu': 'lub', 'lg': 'lug', 'mk': 'mac', 'mh': 'mah', 'ml': 'mal', 'mi': 'mao', 'mr': 'mar', 'ms': 'may', 'mg': 'mlg', 'mt': 'mlt',
|
||||
'mo': 'mol', 'mn': 'mon', 'na': 'nau', 'nv': 'nav', 'nr': 'nbl', 'nd': 'nde', 'ng': 'ndo', 'ne': 'nep', 'nn': 'nno', 'nb': 'nob',
|
||||
'no': 'nor', 'ny': 'nya', 'oc': 'oci', 'oj': 'oji', 'or': 'ori', 'om': 'orm', 'os': 'oss', 'pa': 'pan', 'fa': 'per', 'pi': 'pli',
|
||||
'pl': 'pol', 'pt': 'por', 'ps': 'pus', 'qu': 'que', 'rm': 'roh', 'rn': 'run', 'ru': 'rus', 'sg': 'sag', 'sa': 'san', 'sr': 'scc',
|
||||
'si': 'sin', 'sk': 'slo', 'sl': 'slv', 'se': 'sme', 'sm': 'smo', 'sn': 'sna', 'sd': 'snd', 'so': 'som', 'st': 'sot', 'es': 'spa',
|
||||
'sc': 'srd', 'ss': 'ssw', 'su': 'sun', 'sw': 'swa', 'sv': 'swe', 'ty': 'tah', 'ta': 'tam', 'tt': 'tat', 'te': 'tel', 'tg': 'tgk',
|
||||
'tl': 'tgl', 'th': 'tha', 'bo': 'tib', 'ti': 'tir', 'to': 'ton', 'tn': 'tsn', 'ts': 'tso', 'tk': 'tuk', 'tr': 'tur', 'tw': 'twi',
|
||||
'ug': 'uig', 'uk': 'ukr', 'ur': 'urd', 'uz': 'uzb', 've': 'ven', 'vi': 'vie', 'vo': 'vol', 'cy': 'wel', 'wa': 'wln', 'wo': 'wol',
|
||||
'xh': 'xho', 'yi': 'yid', 'yo': 'yor', 'za': 'zha', 'zu': 'zul', 'ro': 'rum', 'pb': 'pob', 'un': 'unk', 'ay': 'ass'}
|
||||
|
||||
def __init__(self, config_dict=None):
|
||||
super(OpenSubtitles, self).__init__(self._plugin_languages, config_dict)
|
||||
|
||||
def list(self, filepath, languages):
|
||||
possible_languages = self.possible_languages(languages)
|
||||
if not possible_languages:
|
||||
return []
|
||||
if os.path.isfile(filepath):
|
||||
filehash = self.hashFile(filepath)
|
||||
size = os.path.getsize(filepath)
|
||||
return self.query(moviehash=filehash, languages=possible_languages, bytesize=size, filepath=filepath)
|
||||
else:
|
||||
return self.query(languages=possible_languages, filepath=filepath)
|
||||
|
||||
def download(self, subtitle):
|
||||
try:
|
||||
self.downloadFile(subtitle.link, subtitle.path + '.gz')
|
||||
with open(subtitle.path, 'wb') as dump:
|
||||
gz = gzip.open(subtitle.path + '.gz')
|
||||
dump.write(gz.read())
|
||||
gz.close()
|
||||
self.adjustPermissions(subtitle.path)
|
||||
os.remove(subtitle.path + '.gz')
|
||||
except Exception as e:
|
||||
if os.path.exists(subtitle.path):
|
||||
os.remove(subtitle.path)
|
||||
raise DownloadFailedError(str(e))
|
||||
return subtitle
|
||||
|
||||
def query(self, filepath, imdbID=None, moviehash=None, bytesize=None, languages=None):
|
||||
"""Makes a query on OpenSubtitles and returns info about found subtitles.
|
||||
Note: if using moviehash, bytesize is required. """
|
||||
# prepare the search
|
||||
search = {}
|
||||
if moviehash:
|
||||
search['moviehash'] = moviehash
|
||||
if imdbID:
|
||||
search['imdbid'] = imdbID
|
||||
if bytesize:
|
||||
search['moviebytesize'] = str(bytesize)
|
||||
if languages:
|
||||
search['sublanguageid'] = ','.join([self.getLanguage(l) for l in languages])
|
||||
if not imdbID and not moviehash and not bytesize:
|
||||
self.logger.debug(u'No search term, using the filename')
|
||||
guess = guessit.guess_file_info(filepath, 'autodetect')
|
||||
if guess['type'] == 'episode' and 'series' in guess:
|
||||
search['query'] = guess['series'].lower()
|
||||
elif guess['type'] == 'movie':
|
||||
search['query'] = guess['title'].lower()
|
||||
else: # we don't know what we have
|
||||
return[]
|
||||
# login
|
||||
self.server = xmlrpclib.Server(self.server_url)
|
||||
socket.setdefaulttimeout(self.timeout)
|
||||
try:
|
||||
log_result = self.server.LogIn('', '', 'eng', self.user_agent)
|
||||
if not log_result['status'] or log_result['status'] != '200 OK' or not log_result['token']:
|
||||
raise Exception('OpenSubtitles login failed')
|
||||
token = log_result['token']
|
||||
except Exception:
|
||||
self.logger.error(u'Cannot login')
|
||||
token = None
|
||||
socket.setdefaulttimeout(None)
|
||||
return []
|
||||
# search
|
||||
sublinks = self.get_results(token, search, filepath)
|
||||
# logout
|
||||
try:
|
||||
self.server.LogOut(token)
|
||||
except:
|
||||
self.logger.error(u'Cannot logout')
|
||||
socket.setdefaulttimeout(None)
|
||||
return sublinks
|
||||
|
||||
def get_results(self, token, search, filepath):
|
||||
self.logger.debug(u'Query uses token %s and search parameters %s' % (token, search))
|
||||
try:
|
||||
results = self.server.SearchSubtitles(token, [search])
|
||||
except Exception:
|
||||
self.logger.debug(u'Cannot query the server')
|
||||
return []
|
||||
if not results['data']: # no subtitle found
|
||||
return []
|
||||
sublinks = []
|
||||
self.filename = self.getFileName(filepath)
|
||||
for r in sorted(results['data'], self._cmpSubFileName):
|
||||
result = Subtitle(filepath, self.getSubtitlePath(filepath, self.getRevertLanguage(r['SubLanguageID'])), self.__class__.__name__, self.getRevertLanguage(r['SubLanguageID']), r['SubDownloadLink'], r['SubFileName'])
|
||||
if 'query' in search: # query mode search, filter results
|
||||
query_encoded = search['query']
|
||||
if isinstance(query_encoded, unicode):
|
||||
query_encoded = unicodedata.normalize('NFKD', query_encoded).encode('ascii', 'ignore')
|
||||
if not r['MovieReleaseName'].replace('.', ' ').lower().startswith(query_encoded):
|
||||
self.logger.debug(u'Skipping %s it does not start with %s' % (r['MovieReleaseName'].replace('.', ' ').lower(), query_encoded))
|
||||
continue
|
||||
sublinks.append(result)
|
||||
return sublinks
|
||||
|
||||
def _cmpSubFileName(self, x, y):
|
||||
"""Sort based on the SubFileName name tag """
|
||||
#TODO add also support for subtitles release
|
||||
xmatch = x['SubFileName'] and (x['SubFileName'].find(self.filename) > -1 or self.filename.find(x['SubFileName']) > -1)
|
||||
ymatch = y['SubFileName'] and (y['SubFileName'].find(self.filename) > -1 or self.filename.find(y['SubFileName']) > -1)
|
||||
if xmatch and ymatch:
|
||||
if x['SubFileName'] == self.filename or x['SubFileName'].startswith(self.filename):
|
||||
return - 1
|
||||
return 0
|
||||
if not xmatch and not ymatch:
|
||||
return 0
|
||||
if xmatch and not ymatch:
|
||||
return - 1
|
||||
if not xmatch and ymatch:
|
||||
return 1
|
||||
return 0
|
||||
|
||||
@@ -1,163 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
#
|
||||
# Subliminal - Subtitles, faster than your thoughts
|
||||
# Copyright (c) 2011 Antoine Bertin <diaoulael@gmail.com>
|
||||
#
|
||||
# This file is part of Subliminal.
|
||||
#
|
||||
# Subliminal is free software; you can redistribute it and/or modify it under
|
||||
# the terms of the Lesser GNU General Public License as published by
|
||||
# the Free Software Foundation; either version 3 of the License, or
|
||||
# (at your option) any later version.
|
||||
#
|
||||
# Subliminal is distributed in the hope that it will be useful,
|
||||
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
# Lesser GNU General Public License for more details.
|
||||
#
|
||||
# You should have received a copy of the Lesser GNU General Public License
|
||||
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
#
|
||||
|
||||
import abc
|
||||
import logging
|
||||
import os
|
||||
import urllib2
|
||||
import struct
|
||||
import threading
|
||||
import socket
|
||||
from subliminal.classes import DownloadFailedError
|
||||
|
||||
|
||||
class PluginBase(object):
|
||||
__metaclass__ = abc.ABCMeta
|
||||
api_based = True
|
||||
timeout = 3
|
||||
user_agent = 'Mozilla/5.0 (X11; U; Linux x86_64; en-US; rv:1.9.1.3)'
|
||||
lock = threading.Lock()
|
||||
|
||||
@abc.abstractmethod
|
||||
def __init__(self, pluginLanguages, config_dict=None, isRevert=False):
|
||||
self.config_dict = config_dict
|
||||
if not pluginLanguages:
|
||||
self.pluginLanguages = None
|
||||
self.revertPluginLanguages = None
|
||||
elif not isRevert:
|
||||
self.pluginLanguages = pluginLanguages
|
||||
self.revertPluginLanguages = dict((v, k) for k, v in self.pluginLanguages.iteritems())
|
||||
else:
|
||||
self.revertPluginLanguages = pluginLanguages
|
||||
self.pluginLanguages = dict((v, k) for k, v in self.revertPluginLanguages.iteritems())
|
||||
self.logger = logging.getLogger('subliminal.%s' % self.__class__.__name__)
|
||||
|
||||
@staticmethod
|
||||
def getFileName(filepath):
|
||||
filename = filepath
|
||||
if os.path.isfile(filename):
|
||||
filename = os.path.basename(filename)
|
||||
if filename.endswith(('.avi', '.wmv', '.mov', '.mp4', '.mpeg', '.mpg', '.mkv')):
|
||||
filename = filename.rsplit('.', 1)[0]
|
||||
return filename
|
||||
|
||||
def possible_languages(self, languages):
|
||||
possible_languages = languages & set(self.pluginLanguages.keys())
|
||||
if not possible_languages:
|
||||
self.logger.debug(u'Languages %r are not in supported languages' % languages)
|
||||
return possible_languages
|
||||
|
||||
def hashFile(self, filename):
|
||||
"""Hash a file like OpenSubtitles"""
|
||||
longlongformat = 'q' # long long
|
||||
bytesize = struct.calcsize(longlongformat)
|
||||
f = open(filename, 'rb')
|
||||
filesize = os.path.getsize(filename)
|
||||
hash = filesize
|
||||
if filesize < 65536 * 2:
|
||||
self.logger.error(u'File %s is too small (SizeError < 2**16)' % filename)
|
||||
return []
|
||||
for _ in range(65536 / bytesize):
|
||||
buffer = f.read(bytesize)
|
||||
(l_value,) = struct.unpack(longlongformat, buffer)
|
||||
hash += l_value
|
||||
hash = hash & 0xFFFFFFFFFFFFFFFF # to remain as 64bit number
|
||||
f.seek(max(0, filesize - 65536), 0)
|
||||
for _ in range(65536 / bytesize):
|
||||
buffer = f.read(bytesize)
|
||||
(l_value,) = struct.unpack(longlongformat, buffer)
|
||||
hash += l_value
|
||||
hash = hash & 0xFFFFFFFFFFFFFFFF
|
||||
f.close()
|
||||
returnedhash = '%016x' % hash
|
||||
return returnedhash
|
||||
|
||||
def downloadFile(self, url, filepath, data=None):
|
||||
"""Download a subtitle file"""
|
||||
self.logger.info(u'Downloading %s' % url)
|
||||
socket.setdefaulttimeout(self.timeout)
|
||||
try:
|
||||
req = urllib2.Request(url, headers={'Referer': url, 'User-Agent': self.user_agent})
|
||||
with open(filepath, 'wb') as dump:
|
||||
f = urllib2.urlopen(req, data=data)
|
||||
dump.write(f.read())
|
||||
self.adjustPermissions(filepath)
|
||||
f.close()
|
||||
except Exception as e:
|
||||
self.logger.error(u'Download %s failed: %s' % (url, e))
|
||||
if os.path.exists(filepath):
|
||||
os.remove(filepath)
|
||||
raise DownloadFailedError(str(e))
|
||||
finally:
|
||||
socket.setdefaulttimeout(self.timeout)
|
||||
self.logger.debug(u'Download finished for file %s. Size: %s' % (filepath, os.path.getsize(filepath)))
|
||||
|
||||
def adjustPermissions(self, filepath):
|
||||
if self.config_dict and 'files_mode' in self.config_dict and self.config_dict['files_mode'] != -1:
|
||||
os.chmod(filepath, self.config_dict['files_mode'])
|
||||
|
||||
@abc.abstractmethod
|
||||
def list(self, filepath, languages):
|
||||
"""List subtitles"""
|
||||
|
||||
@abc.abstractmethod
|
||||
def download(self, subtitle):
|
||||
"""Download a subtitle"""
|
||||
|
||||
def getRevertLanguage(self, language):
|
||||
"""ISO-639-1 language code from plugin language code"""
|
||||
try:
|
||||
return self.revertPluginLanguages[language]
|
||||
except KeyError:
|
||||
self.logger.warn(u'Ooops, you found a missing language in the configuration file of %s: %s. Send a bug report to have it added.' % (self.__class__.__name__, language))
|
||||
|
||||
def getLanguage(self, language):
|
||||
"""Plugin language code from ISO-639-1 language code"""
|
||||
try:
|
||||
return self.pluginLanguages[language]
|
||||
except KeyError:
|
||||
self.logger.warn(u'Ooops, you found a missing language in the configuration file of %s: %s. Send a bug report to have it added.' % (self.__class__.__name__, language))
|
||||
|
||||
def getSubtitlePath(self, video_path, language):
|
||||
if not os.path.exists(video_path):
|
||||
video_path = os.path.split(video_path)[1]
|
||||
path = video_path.rsplit('.', 1)[0]
|
||||
if self.config_dict and self.config_dict['multi']:
|
||||
return path + '.%s.srt' % language
|
||||
return path + '.srt'
|
||||
|
||||
def listTeams(self, sub_teams, separators):
|
||||
"""List teams of a given string using separators"""
|
||||
for sep in separators:
|
||||
sub_teams = self.splitTeam(sub_teams, sep)
|
||||
return set(sub_teams)
|
||||
|
||||
def splitTeam(self, sub_teams, sep):
|
||||
"""Split teams of a given string using separators"""
|
||||
teams = []
|
||||
for t in sub_teams:
|
||||
teams += t.split(sep)
|
||||
return teams
|
||||
|
||||
def _cmpReleaseGroup(self, x, y):
|
||||
"""Sort based on teams matching"""
|
||||
return -cmp(len(x.teams.intersection(self.release_group)), len(y.teams.intersection(self.release_group)))
|
||||
|
||||
@@ -1,135 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
#
|
||||
# Subliminal - Subtitles, faster than your thoughts
|
||||
# Copyright (c) 2008-2011 Patrick Dessalle <patrick@dessalle.be>
|
||||
# Copyright (c) 2011 Antoine Bertin <diaoulael@gmail.com>
|
||||
#
|
||||
# This file is part of Subliminal.
|
||||
#
|
||||
# Subliminal is free software; you can redistribute it and/or modify it under
|
||||
# the terms of the Lesser GNU General Public License as published by
|
||||
# the Free Software Foundation; either version 3 of the License, or
|
||||
# (at your option) any later version.
|
||||
#
|
||||
# Subliminal is distributed in the hope that it will be useful,
|
||||
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
# Lesser GNU General Public License for more details.
|
||||
#
|
||||
# You should have received a copy of the Lesser GNU General Public License
|
||||
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
#
|
||||
|
||||
from hashlib import md5, sha256
|
||||
import PluginBase
|
||||
import xmlrpclib
|
||||
import socket
|
||||
import os
|
||||
|
||||
|
||||
class Podnapisi(PluginBase.PluginBase):
|
||||
site_url = "http://www.podnapisi.net"
|
||||
site_name = "Podnapisi"
|
||||
server_url = 'http://ssp.podnapisi.net:8000'
|
||||
api_based = True
|
||||
_plugin_languages = {"sl": "1",
|
||||
"en": "2",
|
||||
"no": "3",
|
||||
"ko": "4",
|
||||
"de": "5",
|
||||
"is": "6",
|
||||
"cs": "7",
|
||||
"fr": "8",
|
||||
"it": "9",
|
||||
"bs": "10",
|
||||
"ja": "11",
|
||||
"ar": "12",
|
||||
"ro": "13",
|
||||
"es-ar": "14",
|
||||
"hu": "15",
|
||||
"el": "16",
|
||||
"zh": "17",
|
||||
"lt": "19",
|
||||
"et": "20",
|
||||
"lv": "21",
|
||||
"he": "22",
|
||||
"nl": "23",
|
||||
"da": "24",
|
||||
"se": "25",
|
||||
"pl": "26",
|
||||
"ru": "27",
|
||||
"es": "28",
|
||||
"sq": "29",
|
||||
"tr": "30",
|
||||
"fi": "31",
|
||||
"pt": "32",
|
||||
"bg": "33",
|
||||
"mk": "35",
|
||||
"sk": "37",
|
||||
"hr": "38",
|
||||
"zh": "40",
|
||||
"hi": "42",
|
||||
"th": "44",
|
||||
"uk": "46",
|
||||
"sr": "47",
|
||||
"pt-br": "48",
|
||||
"ga": "49",
|
||||
"be": "50",
|
||||
"vi": "51",
|
||||
"fa": "52",
|
||||
"ca": "53",
|
||||
"id": "54"}
|
||||
|
||||
def __init__(self, config_dict=None):
|
||||
super(Podnapisi, self).__init__(self._plugin_languages, config_dict)
|
||||
# Podnapisi uses two reference for latin serbian and cyrillic serbian (36 and 47)
|
||||
# add the 36 manually as cyrillic seems to be more used
|
||||
self.revertPluginLanguages["36"] = "sr"
|
||||
|
||||
def list(self, filenames, languages):
|
||||
"""Main method to call when you want to list subtitles"""
|
||||
filepath = filenames[0]
|
||||
if not os.path.isfile(filepath):
|
||||
return []
|
||||
return self.query(self.hashFile(filepath), languages)
|
||||
|
||||
def download(self, subtitle):
|
||||
return []
|
||||
|
||||
def query(self, moviehash, languages=None):
|
||||
"""Makes a query on podnapisi and returns info (link, lang) about found subtitles"""
|
||||
# login
|
||||
self.server = xmlrpclib.Server(self.server_url)
|
||||
socket.setdefaulttimeout(self.timeout)
|
||||
try:
|
||||
log_result = self.server.initiate(self.user_agent)
|
||||
self.logger.debug(u"Result: %s" % log_result)
|
||||
token = log_result["session"]
|
||||
nonce = log_result["nonce"]
|
||||
except Exception:
|
||||
self.logger.error(u"Cannot login" % log_result)
|
||||
socket.setdefaulttimeout(None)
|
||||
return []
|
||||
username = 'getmesubs'
|
||||
password = '99D31$$'
|
||||
hash = md5()
|
||||
hash.update(password)
|
||||
password = hash.hexdigest()
|
||||
hash = sha256()
|
||||
hash.update(password)
|
||||
hash.update(nonce)
|
||||
password = hash.hexdigest()
|
||||
self.server.authenticate(token, username, password)
|
||||
self.logger.debug(u'Authenticated')
|
||||
#if languages:
|
||||
# self.logger.debug([self.getLanguage(l) for l in languages])
|
||||
# self.server.setFilters(token, [self.getLanguage(l) for l in languages])
|
||||
# self.logger.debug('Filers set for languages %s' % languages)
|
||||
self.logger.debug(u"Starting search with token %s and hashs %s" % (token, [moviehash]))
|
||||
results = self.server.search(token, [moviehash])
|
||||
return results
|
||||
subs = []
|
||||
for sub in results['results']:
|
||||
subs.append(sub)
|
||||
self.server.terminate(token)
|
||||
return subs
|
||||
@@ -1,168 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
#
|
||||
# Subliminal - Subtitles, faster than your thoughts
|
||||
# Copyright (c) 2008-2011 Patrick Dessalle <patrick@dessalle.be>
|
||||
# Copyright (c) 2011 Antoine Bertin <diaoulael@gmail.com>
|
||||
#
|
||||
# This file is part of Subliminal.
|
||||
#
|
||||
# Subliminal is free software; you can redistribute it and/or modify it under
|
||||
# the terms of the Lesser GNU General Public License as published by
|
||||
# the Free Software Foundation; either version 3 of the License, or
|
||||
# (at your option) any later version.
|
||||
#
|
||||
# Subliminal is distributed in the hope that it will be useful,
|
||||
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
# Lesser GNU General Public License for more details.
|
||||
#
|
||||
# You should have received a copy of the Lesser GNU General Public License
|
||||
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
#
|
||||
|
||||
from BeautifulSoup import BeautifulSoup
|
||||
import PluginBase
|
||||
import zipfile
|
||||
import os
|
||||
import urllib2
|
||||
|
||||
|
||||
class SubScene(PluginBase.PluginBase):
|
||||
site_url = 'http://subscene.com'
|
||||
site_name = 'SubScene'
|
||||
server_url = 'http://subscene.com/s.aspx?subtitle='
|
||||
api_based = False
|
||||
_plugin_languages = {"en": "English",
|
||||
"se": "Swedish",
|
||||
"da": "Danish",
|
||||
"fi": "Finnish",
|
||||
"no": "Norwegian",
|
||||
"fr": "French",
|
||||
"es": "Spanish",
|
||||
"is": "Icelandic",
|
||||
"cs": "Czech",
|
||||
"bg": "Bulgarian",
|
||||
"de": "German",
|
||||
"ar": "Arabic",
|
||||
"el": "Greek",
|
||||
"fa": "Farsi/Persian",
|
||||
"nl": "Dutch",
|
||||
"he": "Hebrew",
|
||||
"id": "Indonesian",
|
||||
"ja": "Japanese",
|
||||
"vi": "Vietnamese",
|
||||
"pt": "Portuguese",
|
||||
"ro": "Romanian",
|
||||
"tr": "Turkish",
|
||||
"sr": "Serbian",
|
||||
"pt-br": "Brazillian Portuguese",
|
||||
"ru": "Russian",
|
||||
"hr": "Croatian",
|
||||
"sl": "Slovenian",
|
||||
"zh": "Chinese BG code",
|
||||
"it": "Italian",
|
||||
"pl": "Polish",
|
||||
"ko": "Korean",
|
||||
"hu": "Hungarian",
|
||||
"ku": "Kurdish",
|
||||
"et": "Estonian"}
|
||||
|
||||
def __init__(self, config_dict=None):
|
||||
super(SubScene, self).__init__(self._plugin_languages, config_dict)
|
||||
#http://subscene.com/s.aspx?subtitle=Dexter.S04E01.HDTV.XviD-NoTV
|
||||
|
||||
def list(self, filenames, languages):
|
||||
"""Main method to call when you want to list subtitles"""
|
||||
filepath = filenames[0]
|
||||
fname = self.getFileName(filepath)
|
||||
subs = self.query(fname, filepath, languages)
|
||||
if not subs and fname.rfind(".[") > 0:
|
||||
# Try to remove the [VTV] or [EZTV] at the end of the file
|
||||
teamless_filename = fname[0:fname.rfind(".[")]
|
||||
subs = self.query(teamless_filename, filepath, languages)
|
||||
return subs
|
||||
else:
|
||||
return subs
|
||||
|
||||
def download(self, subtitle):
|
||||
"""Main method to call when you want to download a subtitle"""
|
||||
subpage = subtitle["page"]
|
||||
page = urllib2.urlopen(subpage)
|
||||
soup = BeautifulSoup(page)
|
||||
dlhref = soup.find("div", {"class": "download"}).find("a")["href"]
|
||||
subtitle["link"] = self.site_url + dlhref.split('"')[7]
|
||||
format = "zip"
|
||||
archivefilename = subtitle["filename"].rsplit(".", 1)[0] + '.' + format
|
||||
self.downloadFile(subtitle["link"], archivefilename)
|
||||
subtitlefilename = None
|
||||
if zipfile.is_zipfile(archivefilename):
|
||||
self.logger.debug(u"Unzipping file " + archivefilename)
|
||||
zf = zipfile.ZipFile(archivefilename, "r")
|
||||
for el in zf.infolist():
|
||||
extension = el.orig_filename.rsplit(".", 1)[1]
|
||||
if extension in ("srt", "sub", "txt"):
|
||||
subtitlefilename = srtbasefilename + "." + extension
|
||||
outfile = open(subtitlefilename, "wb")
|
||||
outfile.write(zf.read(el.orig_filename))
|
||||
outfile.flush()
|
||||
self.adjustPermissions(subtitlefilename)
|
||||
outfile.close()
|
||||
else:
|
||||
self.logger.info(u"File %s does not seem to be valid " % el.orig_filename)
|
||||
# Deleting the zip file
|
||||
zf.close()
|
||||
os.remove(archivefilename)
|
||||
return subtitlefilename
|
||||
elif archivefilename.endswith('.rar'):
|
||||
self.logger.warn(u'Rar is not really supported yet. Trying to call unrar')
|
||||
import subprocess
|
||||
try:
|
||||
args = ['unrar', 'lb', archivefilename]
|
||||
output = subprocess.Popen(args, stdout=subprocess.PIPE).communicate()[0]
|
||||
for el in output.splitlines():
|
||||
extension = el.rsplit(".", 1)[1]
|
||||
if extension in ("srt", "sub"):
|
||||
args = ['unrar', 'e', archivefilename, el, os.path.dirname(archivefilename)]
|
||||
subprocess.Popen(args)
|
||||
tmpsubtitlefilename = os.path.join(os.path.dirname(archivefilename), el)
|
||||
subtitlefilename = os.path.join(os.path.dirname(archivefilename), srtbasefilename + "." + extension)
|
||||
if os.path.exists(tmpsubtitlefilename):
|
||||
# rename it to match the file
|
||||
os.rename(tmpsubtitlefilename, subtitlefilename)
|
||||
# exit
|
||||
return subtitlefilename
|
||||
except OSError as e:
|
||||
self.logger.error(u"Execution failed: %s" % e)
|
||||
return None
|
||||
else:
|
||||
self.logger.info(u"Unexpected file type (not zip) for %s" % archivefilename)
|
||||
return None
|
||||
|
||||
def downloadFile(self, url, filename):
|
||||
"""Downloads the given url to the given filename"""
|
||||
#FIXME: Not working
|
||||
|
||||
def query(self, token, filepath, langs=None):
|
||||
"""Make a query on SubScene and returns info about found subtitles"""
|
||||
sublinks = []
|
||||
searchurl = "%s%s" % (self.server_url, urllib2.quote(token))
|
||||
self.logger.debug(u"Query: %s" % searchurl)
|
||||
page = urllib2.urlopen(searchurl)
|
||||
soup = BeautifulSoup(page.read())
|
||||
for subs in soup("a", {"class": "a1"}):
|
||||
lang_span = subs.find("span")
|
||||
lang = self.getRevertLanguage(lang_span.contents[0].strip())
|
||||
release_span = lang_span.findNext("span")
|
||||
release = release_span.contents[0].strip().split(" (")[0]
|
||||
sub_page = subs["href"]
|
||||
#http://subscene.com//s-dlpath-260016/78348/rar.zipx
|
||||
if release.lower().startswith(token.lower()) and (not langs or lang in langs):
|
||||
result = {}
|
||||
result["release"] = release
|
||||
result["lang"] = lang
|
||||
result["link"] = None
|
||||
result["page"] = self.site_url + sub_page
|
||||
result["filename"] = filepath
|
||||
result["plugin"] = self.__class__.__name__
|
||||
sublinks.append(result)
|
||||
return sublinks
|
||||
@@ -1,116 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
#
|
||||
# Subliminal - Subtitles, faster than your thoughts
|
||||
# Copyright (c) 2008-2011 Patrick Dessalle <patrick@dessalle.be>
|
||||
# Copyright (c) 2011 Antoine Bertin <diaoulael@gmail.com>
|
||||
#
|
||||
# This file is part of Subliminal.
|
||||
#
|
||||
# Subliminal is free software; you can redistribute it and/or modify it under
|
||||
# the terms of the Lesser GNU General Public License as published by
|
||||
# the Free Software Foundation; either version 3 of the License, or
|
||||
# (at your option) any later version.
|
||||
#
|
||||
# Subliminal is distributed in the hope that it will be useful,
|
||||
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
# Lesser GNU General Public License for more details.
|
||||
#
|
||||
# You should have received a copy of the Lesser GNU General Public License
|
||||
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
#
|
||||
|
||||
from BeautifulSoup import BeautifulSoup
|
||||
import PluginBase
|
||||
import urllib2
|
||||
import re
|
||||
import guessit
|
||||
from subliminal.classes import Subtitle
|
||||
|
||||
|
||||
class SubsWiki(PluginBase.PluginBase):
|
||||
site_url = 'http://www.subswiki.com'
|
||||
site_name = 'SubsWiki'
|
||||
server_url = 'http://www.subswiki.com'
|
||||
api_based = False
|
||||
_plugin_languages = {u'English (US)': 'en',
|
||||
u'English (UK)': 'en',
|
||||
u'English': 'en',
|
||||
u'French': 'fr',
|
||||
u'Brazilian': 'pt-br',
|
||||
u'Portuguese': 'pt',
|
||||
u'Español (Latinoamérica)': 'es',
|
||||
u'Español (España)': 'es',
|
||||
u'Español': 'es',
|
||||
u'Italian': 'it',
|
||||
u'Català': 'ca'}
|
||||
|
||||
def __init__(self, config_dict=None):
|
||||
super(SubsWiki, self).__init__(self._plugin_languages, config_dict, True)
|
||||
self.release_pattern = re.compile('\nVersion (.+), ([0-9]+).([0-9])+ MBs')
|
||||
|
||||
def list(self, filepath, languages):
|
||||
possible_languages = self.possible_languages(languages)
|
||||
if not possible_languages:
|
||||
return []
|
||||
guess = guessit.guess_file_info(filepath, 'autodetect')
|
||||
if guess['type'] != 'episode':
|
||||
self.logger.debug(u'Not an episode')
|
||||
return []
|
||||
# add multiple things to the release group set
|
||||
release_group = set()
|
||||
if 'releaseGroup' in guess:
|
||||
release_group.add(guess['releaseGroup'].lower())
|
||||
else:
|
||||
if 'title' in guess:
|
||||
release_group.add(guess['title'].lower())
|
||||
if 'screenSize' in guess:
|
||||
release_group.add(guess['screenSize'].lower())
|
||||
if 'series' not in guess or len(release_group) == 0:
|
||||
self.logger.debug(u'Not enough information to proceed')
|
||||
return []
|
||||
self.release_group = release_group # used to sort results
|
||||
return self.query(guess['series'], guess['season'], guess['episodeNumber'], release_group, filepath, possible_languages)
|
||||
|
||||
def query(self, name, season, episode, release_group, filepath, languages):
|
||||
sublinks = []
|
||||
searchname = name.lower().replace(' ', '_')
|
||||
if isinstance(searchname, unicode):
|
||||
searchname = searchname.encode('utf-8')
|
||||
searchurl = '%s/serie/%s/%s/%s/' % (self.server_url, urllib2.quote(searchname), season, episode)
|
||||
self.logger.debug(u'Searching in %s' % searchurl)
|
||||
try:
|
||||
req = urllib2.Request(searchurl, headers={'User-Agent': self.user_agent})
|
||||
page = urllib2.urlopen(req, timeout=self.timeout)
|
||||
except urllib2.HTTPError as inst:
|
||||
self.logger.info(u'Error: %s - %s' % (searchurl, inst))
|
||||
return []
|
||||
except urllib2.URLError as inst:
|
||||
self.logger.info(u'TimeOut: %s' % inst)
|
||||
return []
|
||||
soup = BeautifulSoup(page.read())
|
||||
for subs in soup('td', {'class': 'NewsTitle'}):
|
||||
sub_teams = self.listTeams([self.release_pattern.search('%s' % subs.contents[1]).group(1).lower()], ['.', '_', ' ', '/', '-'])
|
||||
if not release_group.intersection(sub_teams): # On wrong team
|
||||
continue
|
||||
self.logger.debug(u'Team from website: %s' % sub_teams)
|
||||
self.logger.debug(u'Team from file: %s' % release_group)
|
||||
for html_language in subs.parent.parent.findAll('td', {'class': 'language'}):
|
||||
sub_language = self.getRevertLanguage(html_language.string.strip())
|
||||
self.logger.debug(u'Subtitle reverted language: %s' % sub_language)
|
||||
if not sub_language in languages: # On wrong language
|
||||
continue
|
||||
html_status = html_language.findNextSibling('td')
|
||||
sub_status = html_status.find('strong').string.strip()
|
||||
if not sub_status == 'Completed': # On not completed subtitles
|
||||
continue
|
||||
sub_link = html_status.findNext('td').find('a')['href']
|
||||
result = Subtitle(filepath, self.getSubtitlePath(filepath, sub_language), self.__class__.__name__, sub_language, self.server_url + sub_link, teams=sub_teams)
|
||||
sublinks.append(result)
|
||||
sublinks.sort(self._cmpReleaseGroup)
|
||||
return sublinks
|
||||
|
||||
def download(self, subtitle):
|
||||
self.downloadFile(subtitle.link, subtitle.path)
|
||||
return subtitle
|
||||
|
||||
@@ -1,109 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
#
|
||||
# Subliminal - Subtitles, faster than your thoughts
|
||||
# Copyright (c) 2008-2011 Patrick Dessalle <patrick@dessalle.be>
|
||||
# Copyright (c) 2011 Antoine Bertin <diaoulael@gmail.com>
|
||||
#
|
||||
# This file is part of Subliminal.
|
||||
#
|
||||
# Subliminal is free software; you can redistribute it and/or modify it under
|
||||
# the terms of the Lesser GNU General Public License as published by
|
||||
# the Free Software Foundation; either version 3 of the License, or
|
||||
# (at your option) any later version.
|
||||
#
|
||||
# Subliminal is distributed in the hope that it will be useful,
|
||||
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
# Lesser GNU General Public License for more details.
|
||||
#
|
||||
# You should have received a copy of the Lesser GNU General Public License
|
||||
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
#
|
||||
|
||||
from BeautifulSoup import BeautifulSoup
|
||||
import guessit
|
||||
import urllib2
|
||||
import unicodedata
|
||||
import re
|
||||
import PluginBase
|
||||
from subliminal.classes import Subtitle
|
||||
|
||||
|
||||
class Subtitulos(PluginBase.PluginBase):
|
||||
site_url = 'http://www.subtitulos.es'
|
||||
site_name = 'Subtitulos'
|
||||
server_url = 'http://www.subtitulos.es'
|
||||
api_based = False
|
||||
_plugin_languages = {u'English (US)': 'en', u'English (UK)': 'en', u'English': 'en', u'French': 'fr', u'Brazilian': 'pt-br',
|
||||
u'Portuguese': 'pt', u'Español (Latinoamérica)': 'es', u'Español (España)': 'es', u'Español': 'es', u'Italian': 'it',
|
||||
u'Català': 'ca'}
|
||||
|
||||
def __init__(self, config_dict=None):
|
||||
super(Subtitulos, self).__init__(self._plugin_languages, config_dict, True)
|
||||
self.release_pattern = re.compile('Versión (.+) ([0-9]+).([0-9])+ megabytes')
|
||||
|
||||
def list(self, filepath, languages):
|
||||
possible_languages = self.possible_languages(languages)
|
||||
if not possible_languages:
|
||||
return []
|
||||
guess = guessit.guess_file_info(filepath, 'autodetect')
|
||||
if guess['type'] != 'episode':
|
||||
self.logger.debug(u'Not an episode')
|
||||
return []
|
||||
# add multiple things to the release group set
|
||||
release_group = set()
|
||||
if 'releaseGroup' in guess:
|
||||
release_group.add(guess['releaseGroup'].lower())
|
||||
else:
|
||||
if 'title' in guess:
|
||||
release_group.add(guess['title'].lower())
|
||||
if 'screenSize' in guess:
|
||||
release_group.add(guess['screenSize'].lower())
|
||||
if 'series' not in guess or len(release_group) == 0:
|
||||
self.logger.debug(u'Not enough information to proceed')
|
||||
return []
|
||||
self.release_group = release_group # used to sort results
|
||||
return self.query(guess['series'], guess['season'], guess['episodeNumber'], release_group, filepath, possible_languages)
|
||||
|
||||
def query(self, name, season, episode, release_group, filepath, languages):
|
||||
sublinks = []
|
||||
searchname = name.lower().replace(' ', '-')
|
||||
if isinstance(searchname, unicode):
|
||||
searchname = unicodedata.normalize('NFKD', searchname).encode('ascii','ignore')
|
||||
searchurl = '%s/%s/%sx%.2d' % (self.server_url, urllib2.quote(searchname), season, episode)
|
||||
self.logger.debug(u'Searching in %s' % searchurl)
|
||||
try:
|
||||
req = urllib2.Request(searchurl, headers={'User-Agent': self.user_agent})
|
||||
page = urllib2.urlopen(req, timeout=self.timeout)
|
||||
except urllib2.HTTPError as inst:
|
||||
self.logger.info(u'Error: %s - %s' % (searchurl, inst))
|
||||
return []
|
||||
except urllib2.URLError as inst:
|
||||
self.logger.info(u'TimeOut: %s' % inst)
|
||||
return []
|
||||
soup = BeautifulSoup(page.read())
|
||||
for subs in soup('div', {'id': 'version'}):
|
||||
version = subs.find('p', {'class': 'title-sub'})
|
||||
sub_teams = self.listTeams([self.release_pattern.search('%s' % version.contents[1]).group(1).lower()], ['.', '_', ' ', '/', '-'])
|
||||
self.logger.debug(u'Team from website: %s' % sub_teams)
|
||||
self.logger.debug(u'Team from file: %s' % release_group)
|
||||
if not release_group.intersection(sub_teams): # On wrong team
|
||||
continue
|
||||
for html_language in subs.findAllNext('ul', {'class': 'sslist'}):
|
||||
sub_language = self.getRevertLanguage(html_language.findNext('li', {'class': 'li-idioma'}).find('strong').contents[0].string.strip())
|
||||
if not sub_language in languages: # On wrong language
|
||||
continue
|
||||
html_status = html_language.findNext('li', {'class': 'li-estado green'})
|
||||
sub_status = html_status.contents[0].string.strip()
|
||||
if not sub_status == 'Completado': # On not completed subtitles
|
||||
continue
|
||||
sub_link = html_status.findNext('span', {'class': 'descargar green'}).find('a')['href']
|
||||
result = Subtitle(filepath, self.getSubtitlePath(filepath, sub_language), self.__class__.__name__, sub_language, sub_link, teams=sub_teams)
|
||||
sublinks.append(result)
|
||||
sublinks.sort(self._cmpReleaseGroup)
|
||||
return sublinks
|
||||
|
||||
def download(self, subtitle):
|
||||
self.downloadFile(subtitle.link, subtitle.path)
|
||||
return subtitle
|
||||
|
||||
@@ -1,87 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
#
|
||||
# Subliminal - Subtitles, faster than your thoughts
|
||||
# Copyright (c) 2008-2011 Patrick Dessalle <patrick@dessalle.be>
|
||||
# Copyright (c) 2011 Antoine Bertin <diaoulael@gmail.com>
|
||||
#
|
||||
# This file is part of Subliminal.
|
||||
#
|
||||
# Subliminal is free software; you can redistribute it and/or modify it under
|
||||
# the terms of the Lesser GNU General Public License as published by
|
||||
# the Free Software Foundation; either version 3 of the License, or
|
||||
# (at your option) any later version.
|
||||
#
|
||||
# Subliminal is distributed in the hope that it will be useful,
|
||||
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
# Lesser GNU General Public License for more details.
|
||||
#
|
||||
# You should have received a copy of the Lesser GNU General Public License
|
||||
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
#
|
||||
|
||||
import PluginBase
|
||||
import hashlib
|
||||
import os
|
||||
import urllib2
|
||||
from subliminal.classes import Subtitle
|
||||
|
||||
|
||||
class TheSubDB(PluginBase.PluginBase):
|
||||
site_url = 'http://thesubdb.com'
|
||||
site_name = 'SubDB'
|
||||
server_url = 'http://api.thesubdb.com' # for testing purpose, use http://sandbox.thesubdb.com instead
|
||||
api_based = True
|
||||
user_agent = 'SubDB/1.0 (Subliminal/0.4; https://github.com/Diaoul/subliminal)' # defined by the API
|
||||
_plugin_languages = {'af': 'af', 'cs': 'cs', 'da': 'da', 'de': 'de', 'en': 'en', 'es': 'es', 'fi': 'fi', 'fr': 'fr', 'hu': 'hu', 'id': 'id',
|
||||
'it': 'it', 'la': 'la', 'nl': 'nl', 'no': 'no', 'oc': 'oc', 'pl': 'pl', 'pt': 'pt', 'ro': 'ro', 'ru': 'ru', 'sl': 'sl', 'sr': 'sr',
|
||||
'sv': 'sv', 'tr': 'tr'} # list available with the API at http://sandbox.thesubdb.com/?action=languages
|
||||
|
||||
|
||||
def __init__(self, config_dict=None):
|
||||
super(TheSubDB, self).__init__(self._plugin_languages, config_dict)
|
||||
|
||||
def list(self, filepath, languages):
|
||||
possible_languages = self.possible_languages(languages)
|
||||
if not possible_languages:
|
||||
return []
|
||||
if not os.path.isfile(filepath):
|
||||
return []
|
||||
return self.query(filepath, self.hashFile(filepath), possible_languages)
|
||||
|
||||
def query(self, filepath, moviehash, languages):
|
||||
searchurl = '%s/?action=%s&hash=%s' % (self.server_url, 'search', moviehash)
|
||||
self.logger.debug(u'Query URL: %s' % searchurl)
|
||||
try:
|
||||
req = urllib2.Request(searchurl, headers={'User-Agent': self.user_agent})
|
||||
page = urllib2.urlopen(req, timeout=self.timeout)
|
||||
except urllib2.HTTPError as inst:
|
||||
if inst.code == 404: # no result found
|
||||
return []
|
||||
self.logger.error(u'Error: %s - %s' % (searchurl, inst))
|
||||
return []
|
||||
except urllib2.URLError as inst:
|
||||
self.logger.error(u'TimeOut: %s' % inst)
|
||||
return []
|
||||
available_languages = page.readlines()[0].split(',')
|
||||
self.logger.debug(u'Available languages: %s' % available_languages)
|
||||
subs = []
|
||||
for l in available_languages:
|
||||
if l in languages:
|
||||
result = Subtitle(filepath, self.getSubtitlePath(filepath, l), self.__class__.__name__, l, '%s/?action=download&hash=%s&language=%s' % (self.server_url, moviehash, l))
|
||||
subs.append(result)
|
||||
return subs
|
||||
|
||||
def hashFile(self, filepath):
|
||||
"""TheSubDB specific hash function"""
|
||||
readsize = 64 * 1024
|
||||
with open(filepath, 'rb') as f:
|
||||
data = f.read(readsize)
|
||||
f.seek(-readsize, os.SEEK_END)
|
||||
data += f.read(readsize)
|
||||
return hashlib.md5(data).hexdigest()
|
||||
|
||||
def download(self, subtitle):
|
||||
self.downloadFile(subtitle.link, subtitle.path)
|
||||
return subtitle
|
||||
|
||||
@@ -1,31 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
#
|
||||
# Subliminal - Subtitles, faster than your thoughts
|
||||
# Copyright (c) 2008-2011 Patrick Dessalle <patrick@dessalle.be>
|
||||
# Copyright (c) 2011 Antoine Bertin <diaoulael@gmail.com>
|
||||
#
|
||||
# This file is part of Subliminal.
|
||||
#
|
||||
# Subliminal is free software; you can redistribute it and/or modify it under
|
||||
# the terms of the Lesser GNU General Public License as published by
|
||||
# the Free Software Foundation; either version 3 of the License, or
|
||||
# (at your option) any later version.
|
||||
#
|
||||
# Subliminal is distributed in the hope that it will be useful,
|
||||
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
# Lesser GNU General Public License for more details.
|
||||
#
|
||||
# You should have received a copy of the Lesser GNU General Public License
|
||||
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
#
|
||||
|
||||
#from Addic7ed import Addic7ed
|
||||
from BierDopje import BierDopje
|
||||
from OpenSubtitles import OpenSubtitles
|
||||
#from Podnapisi import Podnapisi
|
||||
#from SubScene import SubScene
|
||||
from SubsWiki import SubsWiki
|
||||
from Subtitulos import Subtitulos
|
||||
from TheSubDB import TheSubDB
|
||||
|
||||
@@ -0,0 +1,156 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
from __future__ import unicode_literals
|
||||
import babelfish
|
||||
from ..video import Episode, Movie
|
||||
from .. import __version__
|
||||
from random import randint
|
||||
|
||||
# Agent List
|
||||
AGENT_LIST = (
|
||||
'Mozilla/5.0 (Windows NT 6.3; rv:36.0) Gecko/20100101 Firefox/36.0',
|
||||
'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36',
|
||||
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2227.1 Safari/537.36',
|
||||
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10; rv:33.0) Gecko/20100101 Firefox/33.0',
|
||||
'Mozilla/5.0 (X11; Linux i586; rv:31.0) Gecko/20100101 Firefox/31.0',
|
||||
'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:31.0) Gecko/20130401 Firefox/31.0',
|
||||
'Mozilla/5.0 (Windows NT 5.1; rv:31.0) Gecko/20100101 Firefox/31.0',
|
||||
'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2227.0 Safari/537.36',
|
||||
'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2227.0 Safari/537.36',
|
||||
'Mozilla/5.0 (compatible, MSIE 11, Windows NT 6.3; Trident/7.0; rv:11.0) like Gecko',
|
||||
'Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; WOW64; Trident/6.0)',
|
||||
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_3) AppleWebKit/537.75.14 (KHTML, like Gecko) Version/7.0.3 Safari/7046A194A',
|
||||
'Mozilla/5.0 (iPad; CPU OS 6_0 like Mac OS X) AppleWebKit/536.26 (KHTML, like Gecko) Version/6.0 Mobile/10A5355d Safari/8536.25',
|
||||
)
|
||||
|
||||
class Provider(object):
|
||||
"""Base class for providers
|
||||
|
||||
If any configuration is possible for the provider, like credentials, it must take place during instantiation
|
||||
|
||||
:param \*\*kwargs: configuration
|
||||
:raise: :class:`~subliminal.exceptions.ProviderConfigurationError` if there is a configuration error
|
||||
|
||||
"""
|
||||
#: Supported BabelFish languages
|
||||
languages = set()
|
||||
|
||||
#: Supported video types
|
||||
video_types = (Episode, Movie)
|
||||
|
||||
#: Required hash, if any
|
||||
required_hash = None
|
||||
|
||||
# Returns a random agent to use from the list above
|
||||
random_user_agent = AGENT_LIST[randint(0, len(AGENT_LIST)-1)]
|
||||
|
||||
# Defines the ideal user agent to use for all providers otherwise
|
||||
primary_user_agent = 'Subliminal/%s' % __version__
|
||||
|
||||
|
||||
def __init__(self, **kwargs):
|
||||
pass
|
||||
|
||||
def __enter__(self):
|
||||
self.initialize()
|
||||
return self
|
||||
|
||||
def __exit__(self, *args):
|
||||
self.terminate()
|
||||
|
||||
def initialize(self):
|
||||
"""Initialize the provider
|
||||
|
||||
Must be called when starting to work with the provider. This is the place for network initialization
|
||||
or login operations.
|
||||
|
||||
.. note:
|
||||
This is called automatically if you use the :keyword:`with` statement
|
||||
|
||||
|
||||
:raise: :class:`~subliminal.exceptions.ProviderNotAvailable` if the provider is unavailable
|
||||
|
||||
"""
|
||||
pass
|
||||
|
||||
def terminate(self):
|
||||
"""Terminate the provider
|
||||
|
||||
Must be called when done with the provider. This is the place for network shutdown or logout operations.
|
||||
|
||||
.. note:
|
||||
This is called automatically if you use the :keyword:`with` statement
|
||||
|
||||
:raise: :class:`~subliminal.exceptions.ProviderNotAvailable` if the provider is unavailable
|
||||
"""
|
||||
pass
|
||||
|
||||
@classmethod
|
||||
def check(cls, video):
|
||||
"""Check if the `video` can be processed
|
||||
|
||||
The video is considered invalid if not an instance of :attr:`video_types` or if the :attr:`required_hash` is
|
||||
not present in :attr:`~subliminal.video.Video`'s `hashes` attribute.
|
||||
|
||||
:param video: the video to check
|
||||
:type video: :class:`~subliminal.video.Video`
|
||||
:return: `True` if the `video` and `languages` are valid, `False` otherwise
|
||||
:rtype: bool
|
||||
|
||||
"""
|
||||
if not isinstance(video, cls.video_types):
|
||||
return False
|
||||
if cls.required_hash is not None and cls.required_hash not in video.hashes:
|
||||
return False
|
||||
return True
|
||||
|
||||
def query(self, languages, *args, **kwargs):
|
||||
"""Query the provider for subtitles
|
||||
|
||||
This method arguments match as much as possible the actual parameters for querying the provider
|
||||
|
||||
:param languages: languages to search for
|
||||
:type languages: set of :class:`babelfish.Language`
|
||||
:param \*args: other required arguments
|
||||
:param \*\*kwargs: other optional arguments
|
||||
:return: the subtitles
|
||||
:rtype: list of :class:`~subliminal.subtitle.Subtitle`
|
||||
:raise: :class:`~subliminal.exceptions.ProviderNotAvailable` if the provider is unavailable
|
||||
:raise: :class:`~subliminal.exceptions.ProviderError` if something unexpected occured
|
||||
|
||||
"""
|
||||
raise NotImplementedError
|
||||
|
||||
def list_subtitles(self, video, languages):
|
||||
"""List subtitles for the `video` with the given `languages`
|
||||
|
||||
This is a proxy for the :meth:`query` method. The parameters passed to the :meth:`query` method may
|
||||
vary depending on the amount of information available in the `video`
|
||||
|
||||
:param video: video to list subtitles for
|
||||
:type video: :class:`~subliminal.video.Video`
|
||||
:param languages: languages to search for
|
||||
:type languages: set of :class:`babelfish.Language`
|
||||
:return: the subtitles
|
||||
:rtype: list of :class:`~subliminal.subtitle.Subtitle`
|
||||
:raise: :class:`~subliminal.exceptions.ProviderNotAvailable` if the provider is unavailable
|
||||
:raise: :class:`~subliminal.exceptions.ProviderError` if something unexpected occured
|
||||
|
||||
"""
|
||||
raise NotImplementedError
|
||||
|
||||
def download_subtitle(self, subtitle):
|
||||
"""Download the `subtitle`
|
||||
|
||||
:param subtitle: subtitle to download
|
||||
:type subtitle: :class:`~subliminal.subtitle.Subtitle`
|
||||
:return: the subtitle text
|
||||
:rtype: string
|
||||
:raise: :class:`~subliminal.exceptions.ProviderNotAvailable` if the provider is unavailable
|
||||
:raise: :class:`~subliminal.exceptions.InvalidSubtitle` if the downloaded subtitle is invalid
|
||||
:raise: :class:`~subliminal.exceptions.ProviderError` if something unexpected occured
|
||||
|
||||
"""
|
||||
raise NotImplementedError
|
||||
|
||||
def __repr__(self):
|
||||
return '<%s [%r]>' % (self.__class__.__name__, self.video_types)
|
||||
@@ -0,0 +1,166 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
from __future__ import unicode_literals
|
||||
import logging
|
||||
import babelfish
|
||||
import bs4
|
||||
import charade
|
||||
import requests
|
||||
from . import Provider
|
||||
from ..cache import region
|
||||
from ..exceptions import ProviderConfigurationError, ProviderNotAvailable, InvalidSubtitle
|
||||
from ..subtitle import Subtitle, is_valid_subtitle, sanitize_string
|
||||
from ..video import Episode
|
||||
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class Addic7edSubtitle(Subtitle):
|
||||
provider_name = 'addic7ed'
|
||||
|
||||
def __init__(self, language, series, season, episode, title, version, hearing_impaired, download_link, referer):
|
||||
super(Addic7edSubtitle, self).__init__(language, hearing_impaired)
|
||||
self.series = series
|
||||
self.season = season
|
||||
self.episode = episode
|
||||
self.title = title
|
||||
self.version = version
|
||||
self.download_link = download_link
|
||||
self.referer = referer
|
||||
|
||||
def compute_matches(self, video):
|
||||
matches = set()
|
||||
# series
|
||||
if video.series and self.series == video.series:
|
||||
matches.add('series')
|
||||
# season
|
||||
if video.season and self.season == video.season:
|
||||
matches.add('season')
|
||||
# episode
|
||||
if video.episode and self.episode == video.episode:
|
||||
matches.add('episode')
|
||||
# title
|
||||
if video.title and self.title.lower() == video.title.lower():
|
||||
matches.add('title')
|
||||
# release_group
|
||||
if video.release_group and self.version and video.release_group.lower() in self.version.lower():
|
||||
matches.add('release_group')
|
||||
# resolution
|
||||
if video.resolution and self.version and video.resolution in self.version.lower():
|
||||
matches.add('resolution')
|
||||
return matches
|
||||
|
||||
|
||||
class Addic7edProvider(Provider):
|
||||
languages = set([babelfish.Language('por', 'BR')]) | set([babelfish.Language(l)
|
||||
for l in ['ara', 'aze', 'ben', 'bos', 'bul', 'cat', 'ces', 'dan', 'deu', 'ell', 'eng', 'eus', 'fas',
|
||||
'fin', 'fra', 'glg', 'heb', 'hrv', 'hun', 'hye', 'ind', 'ita', 'jpn', 'kor', 'mkd', 'msa',
|
||||
'nld', 'nor', 'pol', 'por', 'ron', 'rus', 'slk', 'slv', 'spa', 'sqi', 'srp', 'swe', 'tha',
|
||||
'tur', 'ukr', 'vie', 'zho']])
|
||||
video_types = (Episode,)
|
||||
server = 'http://www.addic7ed.com'
|
||||
|
||||
def initialize(self):
|
||||
self.session = requests.Session()
|
||||
self.session.headers = {
|
||||
'User-Agent': self.random_user_agent,
|
||||
'Referer': self.server,
|
||||
}
|
||||
|
||||
def get(self, url, params=None):
|
||||
"""Make a GET request on `url` with the given parameters
|
||||
|
||||
:param string url: part of the URL to reach with the leading slash
|
||||
:param params: params of the request
|
||||
:return: the response
|
||||
:rtype: :class:`bs4.BeautifulSoup`
|
||||
:raise: :class:`~subliminal.exceptions.ProviderNotAvailable`
|
||||
|
||||
"""
|
||||
try:
|
||||
r = self.session.get(self.server + url, params=params, timeout=10)
|
||||
except requests.Timeout:
|
||||
raise ProviderNotAvailable('Timeout after 10 seconds')
|
||||
if r.status_code != 200:
|
||||
raise ProviderNotAvailable('Request failed with status code %d' % r.status_code)
|
||||
return bs4.BeautifulSoup(r.content, ['permissive'])
|
||||
|
||||
@region.cache_on_arguments()
|
||||
def get_show_ids(self):
|
||||
"""Load the shows page with default series to show ids mapping
|
||||
|
||||
:return: series to show ids
|
||||
:rtype: dict
|
||||
|
||||
"""
|
||||
soup = self.get('/shows.php')
|
||||
show_ids = {}
|
||||
for html_show in soup.select('td.version > h3 > a[href^="/show/"]'):
|
||||
show_ids[sanitize_string(html_show.string)] = \
|
||||
int(html_show['href'][6:])
|
||||
return show_ids
|
||||
|
||||
@region.cache_on_arguments()
|
||||
def find_show_id(self, series):
|
||||
"""Find a show id from the series
|
||||
|
||||
Use this only if the series is not in the dict returned by :meth:`get_show_ids`
|
||||
|
||||
:param string series: series of the episode
|
||||
:return: the show id, if any
|
||||
:rtype: int or None
|
||||
|
||||
"""
|
||||
params = {'search': series, 'Submit': 'Search'}
|
||||
logger.debug('Searching series %r', params)
|
||||
suggested_shows = self.get('/search.php', params).select('span.titulo > a[href^="/show/"]')
|
||||
if not suggested_shows:
|
||||
logger.info('Series %r not found', series)
|
||||
return None
|
||||
return int(suggested_shows[0]['href'][6:])
|
||||
|
||||
def query(self, series, season):
|
||||
show_ids = self.get_show_ids()
|
||||
sanitized_series = sanitize_string(series)
|
||||
if sanitized_series in show_ids:
|
||||
show_id = show_ids[sanitized_series]
|
||||
else:
|
||||
show_id = self.find_show_id(sanitized_series)
|
||||
if show_id is None:
|
||||
return []
|
||||
params = {'show_id': show_id, 'season': season}
|
||||
logger.debug('Searching subtitles %r', params)
|
||||
link = '/show/{show_id}&season={season}'.format(**params)
|
||||
soup = self.get(link)
|
||||
subtitles = []
|
||||
for row in soup('tr', class_='epeven completed'):
|
||||
cells = row('td')
|
||||
if cells[5].string != 'Completed':
|
||||
logger.debug('Skipping incomplete subtitle')
|
||||
continue
|
||||
if not cells[3].string:
|
||||
logger.debug('Skipping empty language')
|
||||
continue
|
||||
subtitles.append(Addic7edSubtitle(babelfish.Language.fromaddic7ed(cells[3].string), series, season,
|
||||
int(cells[1].string), cells[2].string, cells[4].string,
|
||||
bool(cells[6].string), cells[9].a['href'], link))
|
||||
return subtitles
|
||||
|
||||
def list_subtitles(self, video, languages):
|
||||
return [s for s in self.query(video.series, video.season)
|
||||
if s.language in languages and s.episode == video.episode]
|
||||
|
||||
def download_subtitle(self, subtitle):
|
||||
try:
|
||||
r = self.session.get(self.server + subtitle.download_link, timeout=10,
|
||||
headers={'Referer': self.server + subtitle.referer})
|
||||
except requests.Timeout:
|
||||
raise ProviderNotAvailable('Timeout after 10 seconds')
|
||||
if r.status_code != 200:
|
||||
raise ProviderNotAvailable('Request failed with status code %d' % r.status_code)
|
||||
if r.headers['Content-Type'] == 'text/html':
|
||||
raise ProviderNotAvailable('Download limit exceeded')
|
||||
subtitle_text = r.content.decode(charade.detect(r.content)['encoding'], 'replace')
|
||||
if not is_valid_subtitle(subtitle_text):
|
||||
raise InvalidSubtitle
|
||||
return subtitle_text
|
||||
@@ -0,0 +1,164 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
from __future__ import unicode_literals
|
||||
import base64
|
||||
import logging
|
||||
import os
|
||||
import re
|
||||
import xmlrpclib
|
||||
import zlib
|
||||
import babelfish
|
||||
import charade
|
||||
import guessit
|
||||
from . import Provider
|
||||
from .. import __version__
|
||||
from ..exceptions import ProviderError, ProviderNotAvailable, InvalidSubtitle
|
||||
from ..subtitle import Subtitle, is_valid_subtitle, compute_guess_matches
|
||||
from ..subtitle import sanitize_string
|
||||
from ..video import Episode, Movie
|
||||
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class OpenSubtitlesSubtitle(Subtitle):
|
||||
provider_name = 'opensubtitles'
|
||||
series_re = re.compile('^"(?P<series_name>.*)" (?P<series_title>.*)$')
|
||||
|
||||
def __init__(self, language, hearing_impaired, id, matched_by, movie_kind, hash, movie_name, movie_release_name, # @ReservedAssignment
|
||||
movie_year, movie_imdb_id, series_season, series_episode):
|
||||
super(OpenSubtitlesSubtitle, self).__init__(language, hearing_impaired)
|
||||
self.id = id
|
||||
self.matched_by = matched_by
|
||||
self.movie_kind = movie_kind
|
||||
self.hash = hash
|
||||
self.movie_name = movie_name
|
||||
self.movie_release_name = movie_release_name
|
||||
self.movie_year = movie_year
|
||||
self.movie_imdb_id = movie_imdb_id
|
||||
self.series_season = series_season
|
||||
self.series_episode = series_episode
|
||||
|
||||
@property
|
||||
def series_name(self):
|
||||
return self.series_re.match(self.movie_name).group('series_name')
|
||||
|
||||
@property
|
||||
def series_title(self):
|
||||
return self.series_re.match(self.movie_name).group('series_title')
|
||||
|
||||
def compute_matches(self, video):
|
||||
matches = set()
|
||||
# episode
|
||||
if isinstance(video, Episode) and self.movie_kind == 'episode':
|
||||
# series
|
||||
if video.series and \
|
||||
sanitize_string(self.series_name) == \
|
||||
sanitize_string(video.series):
|
||||
matches.add('series')
|
||||
# season
|
||||
if video.season and self.series_season == video.season:
|
||||
matches.add('season')
|
||||
# episode
|
||||
if video.episode and self.series_episode == video.episode:
|
||||
matches.add('episode')
|
||||
# guess
|
||||
matches |= compute_guess_matches(video, guessit.guess_episode_info(self.movie_release_name + '.mkv'))
|
||||
# movie
|
||||
elif isinstance(video, Movie) and self.movie_kind == 'movie':
|
||||
# year
|
||||
if video.year and self.movie_year == video.year:
|
||||
matches.add('year')
|
||||
# guess
|
||||
matches |= compute_guess_matches(video, guessit.guess_movie_info(self.movie_release_name + '.mkv'))
|
||||
else:
|
||||
logger.info('%r is not a valid movie_kind for %r', self.movie_kind, video)
|
||||
return matches
|
||||
# hash
|
||||
if 'opensubtitles' in video.hashes and self.hash == video.hashes['opensubtitles']:
|
||||
matches.add('hash')
|
||||
# imdb_id
|
||||
if video.imdb_id and self.movie_imdb_id == video.imdb_id:
|
||||
matches.add('imdb_id')
|
||||
# title
|
||||
if video.title and \
|
||||
sanitize_string(self.movie_name) == \
|
||||
sanitize_string(video.title):
|
||||
matches.add('title')
|
||||
return matches
|
||||
|
||||
|
||||
class OpenSubtitlesProvider(Provider):
|
||||
languages = set([babelfish.Language.fromopensubtitles(l) for l in babelfish.language_converters['opensubtitles'].codes])
|
||||
|
||||
def __init__(self):
|
||||
self.server = xmlrpclib.ServerProxy('http://api.opensubtitles.org/xml-rpc')
|
||||
self.token = None
|
||||
|
||||
def initialize(self):
|
||||
try:
|
||||
response = self.server.LogIn('', '', 'eng', 'subliminal v%s' % __version__)
|
||||
except xmlrpclib.ProtocolError:
|
||||
raise ProviderNotAvailable
|
||||
if response['status'] != '200 OK':
|
||||
raise ProviderError('Login failed with status %r' % response['status'])
|
||||
self.token = response['token']
|
||||
|
||||
def terminate(self):
|
||||
try:
|
||||
response = self.server.LogOut(self.token)
|
||||
except xmlrpclib.ProtocolError:
|
||||
raise ProviderNotAvailable
|
||||
if response['status'] != '200 OK':
|
||||
raise ProviderError('Logout failed with status %r' % response['status'])
|
||||
|
||||
def query(self, languages, hash=None, size=None, imdb_id=None, query=None): # @ReservedAssignment
|
||||
searches = []
|
||||
if hash and size:
|
||||
searches.append({'moviehash': hash, 'moviebytesize': str(size)})
|
||||
if imdb_id:
|
||||
searches.append({'imdbid': imdb_id})
|
||||
if query:
|
||||
searches.append({'query': query})
|
||||
if not searches:
|
||||
raise ValueError('One or more parameter missing')
|
||||
for search in searches:
|
||||
search['sublanguageid'] = ','.join(l.opensubtitles for l in languages)
|
||||
logger.debug('Searching subtitles %r', searches)
|
||||
try:
|
||||
response = self.server.SearchSubtitles(self.token, searches)
|
||||
except xmlrpclib.ProtocolError:
|
||||
raise ProviderNotAvailable
|
||||
if response['status'] != '200 OK':
|
||||
raise ProviderError('Search failed with status %r' % response['status'])
|
||||
if not response['data']:
|
||||
logger.debug('No subtitle found')
|
||||
return []
|
||||
return [OpenSubtitlesSubtitle(babelfish.Language.fromopensubtitles(r['SubLanguageID']),
|
||||
bool(int(r['SubHearingImpaired'])), r['IDSubtitleFile'], r['MatchedBy'],
|
||||
r['MovieKind'], r['MovieHash'], r['MovieName'], r['MovieReleaseName'],
|
||||
int(r['MovieYear']) if r['MovieYear'] else None, int(r['IDMovieImdb']),
|
||||
int(r['SeriesSeason']) if r['SeriesSeason'] else None,
|
||||
int(r['SeriesEpisode']) if r['SeriesEpisode'] else None)
|
||||
for r in response['data']]
|
||||
|
||||
def list_subtitles(self, video, languages):
|
||||
query = None
|
||||
if ('opensubtitles' not in video.hashes or not video.size) and not video.imdb_id:
|
||||
query = video.name.split(os.sep)[-1]
|
||||
return self.query(languages, hash=video.hashes.get('opensubtitles'), size=video.size, imdb_id=video.imdb_id,
|
||||
query=query)
|
||||
|
||||
def download_subtitle(self, subtitle):
|
||||
try:
|
||||
response = self.server.DownloadSubtitles(self.token, [subtitle.id])
|
||||
except xmlrpclib.ProtocolError:
|
||||
raise ProviderNotAvailable
|
||||
if response['status'] != '200 OK':
|
||||
raise ProviderError('Download failed with status %r' % response['status'])
|
||||
if not response['data']:
|
||||
raise ProviderError('Nothing to download')
|
||||
subtitle_bytes = zlib.decompress(base64.b64decode(response['data'][0]['data']), 47)
|
||||
subtitle_text = subtitle_bytes.decode(charade.detect(subtitle_bytes)['encoding'], 'replace')
|
||||
if not is_valid_subtitle(subtitle_text):
|
||||
raise InvalidSubtitle
|
||||
return subtitle_text
|
||||
@@ -0,0 +1,208 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
from __future__ import unicode_literals
|
||||
import io
|
||||
import logging
|
||||
import re
|
||||
import contextlib
|
||||
import xml.etree.ElementTree
|
||||
import zipfile
|
||||
import babelfish
|
||||
import bs4
|
||||
import charade
|
||||
import guessit
|
||||
import requests
|
||||
from . import Provider
|
||||
from ..exceptions import InvalidSubtitle, ProviderNotAvailable, ProviderError
|
||||
from ..subtitle import Subtitle, is_valid_subtitle, compute_guess_matches
|
||||
from ..subtitle import sanitize_string
|
||||
from ..video import Episode, Movie
|
||||
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
URL_RE = re.compile(
|
||||
'^((http[s]?|ftp):\/)?\/?([^:\/\s]+)(:([^\/]*))?((\/\w+)*\/)' + \
|
||||
'([\w\-\.]+[^#?\s]+)(\?([^#]*))?(#(.*))?$',
|
||||
)
|
||||
|
||||
class PodnapisiSubtitle(Subtitle):
|
||||
provider_name = 'podnapisi'
|
||||
|
||||
def __init__(self, language, id, releases, hearing_impaired, link, series=None, season=None, episode=None, # @ReservedAssignment
|
||||
title=None, year=None):
|
||||
super(PodnapisiSubtitle, self).__init__(language, hearing_impaired)
|
||||
self.id = id
|
||||
self.releases = releases
|
||||
self.hearing_impaired = hearing_impaired
|
||||
self.link = '/ppodnapisi' + link
|
||||
self.series = series
|
||||
self.season = season
|
||||
self.episode = episode
|
||||
self.title = title
|
||||
self.year = year
|
||||
|
||||
def compute_matches(self, video):
|
||||
matches = set()
|
||||
# episode
|
||||
if isinstance(video, Episode):
|
||||
# series
|
||||
if video.series and \
|
||||
sanitize_string(self.series) == \
|
||||
sanitize_string(video.series):
|
||||
matches.add('series')
|
||||
# season
|
||||
if video.season and self.season == video.season:
|
||||
matches.add('season')
|
||||
# episode
|
||||
if video.episode and self.episode == video.episode:
|
||||
matches.add('episode')
|
||||
# guess
|
||||
for release in self.releases:
|
||||
matches |= compute_guess_matches(video, guessit.guess_episode_info(release + '.mkv'))
|
||||
# movie
|
||||
elif isinstance(video, Movie):
|
||||
# title
|
||||
if video.title and \
|
||||
sanitize_string(self.title) == \
|
||||
sanitize_string(video.title):
|
||||
matches.add('title')
|
||||
# year
|
||||
if video.year and self.year == video.year:
|
||||
matches.add('year')
|
||||
# guess
|
||||
for release in self.releases:
|
||||
matches |= compute_guess_matches(video, guessit.guess_movie_info(release + '.mkv'))
|
||||
return matches
|
||||
|
||||
|
||||
class PodnapisiProvider(Provider):
|
||||
languages = set([babelfish.Language.frompodnapisi(l) for l in babelfish.language_converters['podnapisi'].codes])
|
||||
video_types = (Episode, Movie)
|
||||
server = 'http://simple.podnapisi.net'
|
||||
pre_link_re = re.compile('^.*(?P<link>/ppodnapisi/predownload/i/\d+/k/.*$)')
|
||||
link_re = re.compile('^.*(?P<link>/[a-zA-Z]{2}/ppodnapisi/download/i/\d+/k/.*$)')
|
||||
|
||||
def initialize(self):
|
||||
self.session = requests.Session()
|
||||
self.session.headers = {'User-Agent': self.primary_user_agent }
|
||||
|
||||
def terminate(self):
|
||||
self.session.close()
|
||||
|
||||
def get(self, url, params=None, headers=None, is_xml=True):
|
||||
"""Make a GET request on `url` with the given parameters
|
||||
|
||||
:param string url: part of the URL to reach with the leading slash
|
||||
:param dict params: params of the request
|
||||
:param dict headers: headers of the request
|
||||
:param bool xml: whether the response content is XML or not
|
||||
:return: the response
|
||||
:rtype: :class:`xml.etree.ElementTree.Element` or :class:`bs4.BeautifulSoup`
|
||||
:raise: :class:`~subliminal.exceptions.ProviderNotAvailable`
|
||||
|
||||
"""
|
||||
|
||||
prefix_url = ''
|
||||
url_result = URL_RE.search(url)
|
||||
if url_result and url_result.group(2) is None:
|
||||
prefix_url = self.server
|
||||
|
||||
try:
|
||||
r = self.session.get(
|
||||
prefix_url + url, params=params,
|
||||
headers=headers,
|
||||
timeout=10,
|
||||
)
|
||||
except requests.Timeout:
|
||||
raise ProviderNotAvailable('Timeout after 10 seconds')
|
||||
if r.status_code != 200:
|
||||
raise ProviderNotAvailable('Request failed with status code %d' % r.status_code)
|
||||
if is_xml:
|
||||
return xml.etree.ElementTree.fromstring(r.content)
|
||||
else:
|
||||
return bs4.BeautifulSoup(r.content, ['permissive'])
|
||||
|
||||
def query(self, language, series=None, season=None, episode=None, title=None, year=None):
|
||||
params = {'sXML': 1, 'sJ': language.podnapisi}
|
||||
if series and season and episode:
|
||||
params['sK'] = series
|
||||
params['sTS'] = season
|
||||
params['sTE'] = episode
|
||||
elif title:
|
||||
params['sK'] = title
|
||||
if year:
|
||||
params['sY'] = year
|
||||
else:
|
||||
raise ValueError('Missing parameters series and season and episode or title')
|
||||
logger.debug('Searching episode %r', params)
|
||||
subtitles = []
|
||||
while True:
|
||||
root = self.get('/ppodnapisi/search', params)
|
||||
if not int(root.find('pagination/results').text):
|
||||
logger.debug('No subtitle found')
|
||||
break
|
||||
if series and season and episode:
|
||||
try:
|
||||
subtitles.extend([PodnapisiSubtitle(language, int(s.find('id').text), s.find('release').text.split(),
|
||||
'h' in (s.find('flags').text or ''), s.find('url').text[38:],
|
||||
series=series, season=season, episode=episode)
|
||||
for s in root.findall('subtitle')])
|
||||
except AttributeError:
|
||||
# there simply wasn't enough information in the TV Show
|
||||
# gracefully handle this instead of crashing :)
|
||||
break
|
||||
elif title:
|
||||
try:
|
||||
subtitles.extend([PodnapisiSubtitle(language, int(s.find('id').text), s.find('release').text.split(),
|
||||
'h' in (s.find('flags').text or ''), s.find('url').text[38:],
|
||||
title=title, year=year)
|
||||
for s in root.findall('subtitle')])
|
||||
except AttributeError:
|
||||
# there simply wasn't enough information in the movie
|
||||
# gracefully handle this instead of crashing :)
|
||||
break
|
||||
if int(root.find('pagination/current').text) >= int(root.find('pagination/count').text):
|
||||
break
|
||||
params['page'] = int(root.find('pagination/current').text) + 1
|
||||
return subtitles
|
||||
|
||||
def list_subtitles(self, video, languages):
|
||||
if isinstance(video, Episode):
|
||||
return [s for l in languages for s in self.query(l, series=video.series, season=video.season,
|
||||
episode=video.episode)]
|
||||
elif isinstance(video, Movie):
|
||||
return [s for l in languages for s in self.query(l, title=video.title, year=video.year)]
|
||||
|
||||
def download_subtitle(self, subtitle):
|
||||
soup = self.get(subtitle.link, is_xml=False)
|
||||
pre_link = soup.find('a', href=self.pre_link_re)
|
||||
if not pre_link:
|
||||
raise ProviderError('Cannot find the pre-download link')
|
||||
pre_link = self.server + \
|
||||
self.pre_link_re.match(pre_link['href']).group('link')
|
||||
|
||||
# Continue following the link
|
||||
soup = self.get(
|
||||
pre_link,
|
||||
headers={
|
||||
'Referer': self.server,
|
||||
},
|
||||
is_xml=False,
|
||||
)
|
||||
|
||||
link = soup.find('a', href=self.link_re)
|
||||
if not link:
|
||||
raise ProviderError('Cannot find the download link')
|
||||
try:
|
||||
r = self.session.get(self.server + self.link_re.match(link['href']).group('link'), timeout=10)
|
||||
except requests.Timeout:
|
||||
raise ProviderNotAvailable('Timeout after 10 seconds')
|
||||
if r.status_code != 200:
|
||||
raise ProviderNotAvailable('Request failed with status code %d' % r.status_code)
|
||||
with contextlib.closing(zipfile.ZipFile(io.BytesIO(r.content))) as zf:
|
||||
if len(zf.namelist()) > 1:
|
||||
raise ProviderError('More than one file to unzip')
|
||||
subtitle_bytes = zf.read(zf.namelist()[0])
|
||||
subtitle_text = subtitle_bytes.decode(charade.detect(subtitle_bytes)['encoding'], 'replace')
|
||||
if not is_valid_subtitle(subtitle_text):
|
||||
raise InvalidSubtitle
|
||||
return subtitle_text
|
||||
@@ -0,0 +1,81 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
from __future__ import unicode_literals
|
||||
import logging
|
||||
import babelfish
|
||||
import charade
|
||||
import requests
|
||||
from . import Provider
|
||||
from .. import __version__
|
||||
from ..exceptions import InvalidSubtitle, ProviderNotAvailable, ProviderError
|
||||
from ..subtitle import Subtitle, is_valid_subtitle
|
||||
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class TheSubDBSubtitle(Subtitle):
|
||||
provider_name = 'thesubdb'
|
||||
|
||||
def __init__(self, language, hash): # @ReservedAssignment
|
||||
super(TheSubDBSubtitle, self).__init__(language)
|
||||
self.hash = hash
|
||||
|
||||
def compute_matches(self, video):
|
||||
matches = set()
|
||||
# hash
|
||||
if 'thesubdb' in video.hashes and video.hashes['thesubdb'] == self.hash:
|
||||
matches.add('hash')
|
||||
return matches
|
||||
|
||||
|
||||
class TheSubDBProvider(Provider):
|
||||
languages = set([babelfish.Language.fromalpha2(l) for l in ['en', 'es', 'fr', 'it', 'nl', 'pl', 'pt', 'ro', 'sv', 'tr']])
|
||||
required_hash = 'thesubdb'
|
||||
|
||||
def initialize(self):
|
||||
self.session = requests.Session()
|
||||
self.session.headers = {'User-Agent': 'SubDB/1.0 (subliminal/%s; https://github.com/Diaoul/subliminal)' %
|
||||
__version__}
|
||||
|
||||
def terminate(self):
|
||||
self.session.close()
|
||||
|
||||
def get(self, params):
|
||||
"""Make a GET request on the server with the given parameters
|
||||
|
||||
:param params: params of the request
|
||||
:return: the response
|
||||
:rtype: :class:`requests.Response`
|
||||
:raise: :class:`~subliminal.exceptions.ProviderNotAvailable`
|
||||
|
||||
"""
|
||||
try:
|
||||
r = self.session.get('http://api.thesubdb.com', params=params, timeout=10)
|
||||
except requests.Timeout:
|
||||
raise ProviderNotAvailable('Timeout after 10 seconds')
|
||||
return r
|
||||
|
||||
def query(self, hash): # @ReservedAssignment
|
||||
params = {'action': 'search', 'hash': hash}
|
||||
logger.debug('Searching subtitles %r', params)
|
||||
r = self.get(params)
|
||||
if r.status_code == 404:
|
||||
logger.debug('No subtitle found')
|
||||
return []
|
||||
elif r.status_code != 200:
|
||||
raise ProviderError('Request failed with status code %d' % r.status_code)
|
||||
return [TheSubDBSubtitle(language, hash) for language in
|
||||
set([babelfish.Language.fromalpha2(l) for l in r.content.split(',')])]
|
||||
|
||||
def list_subtitles(self, video, languages):
|
||||
return [s for s in self.query(video.hashes['thesubdb']) if s.language in languages]
|
||||
|
||||
def download_subtitle(self, subtitle):
|
||||
params = {'action': 'download', 'hash': subtitle.hash, 'language': subtitle.language.alpha2}
|
||||
r = self.get(params)
|
||||
if r.status_code != 200:
|
||||
raise ProviderError('Request failed with status code %d' % r.status_code)
|
||||
subtitle_text = r.content.decode(charade.detect(r.content)['encoding'], 'replace')
|
||||
if not is_valid_subtitle(subtitle_text):
|
||||
raise InvalidSubtitle
|
||||
return subtitle_text
|
||||
@@ -0,0 +1,195 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
from __future__ import unicode_literals
|
||||
import io
|
||||
import logging
|
||||
import re
|
||||
import contextlib
|
||||
import zipfile
|
||||
import babelfish
|
||||
import bs4
|
||||
import charade
|
||||
import requests
|
||||
from . import Provider
|
||||
from ..cache import region
|
||||
from ..exceptions import InvalidSubtitle, ProviderNotAvailable, ProviderError
|
||||
from ..subtitle import Subtitle, is_valid_subtitle, sanitize_string
|
||||
from ..video import Episode
|
||||
|
||||
IGNORE_DATEMATCH=re.compile('^(.*)[ \t0-9-._)(]*$')
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class TVsubtitlesSubtitle(Subtitle):
|
||||
provider_name = 'tvsubtitles'
|
||||
|
||||
def __init__(self, language, series, season, episode, id, rip, release): # @ReservedAssignment
|
||||
super(TVsubtitlesSubtitle, self).__init__(language)
|
||||
self.series = series
|
||||
self.season = season
|
||||
self.episode = episode
|
||||
self.id = id
|
||||
self.rip = rip
|
||||
self.release = release
|
||||
|
||||
def compute_matches(self, video):
|
||||
matches = set()
|
||||
# series
|
||||
if video.series and self.series == video.series:
|
||||
matches.add('series')
|
||||
# season
|
||||
if video.season and self.season == video.season:
|
||||
matches.add('season')
|
||||
# episode
|
||||
if video.episode and self.episode == video.episode:
|
||||
matches.add('episode')
|
||||
# release_group
|
||||
if video.release_group and self.release and video.release_group.lower() in self.release.lower():
|
||||
matches.add('release_group')
|
||||
# video_codec
|
||||
if video.video_codec and self.release and (video.video_codec in self.release.lower()
|
||||
or video.video_codec == 'h264' and 'x264' in self.release.lower()):
|
||||
matches.add('video_codec')
|
||||
# resolution
|
||||
if video.resolution and self.rip and video.resolution in self.rip.lower():
|
||||
matches.add('resolution')
|
||||
return matches
|
||||
|
||||
|
||||
class TVsubtitlesProvider(Provider):
|
||||
languages = set([babelfish.Language('por', 'BR')]) | set([babelfish.Language(l)
|
||||
for l in ['ara', 'bul', 'ces', 'dan', 'deu', 'ell', 'eng', 'fin', 'fra', 'hun', 'ita', 'jpn', 'kor',
|
||||
'nld', 'pol', 'por', 'ron', 'rus', 'spa', 'swe', 'tur', 'ukr', 'zho']])
|
||||
video_types = (Episode,)
|
||||
server = 'http://www.tvsubtitles.net'
|
||||
episode_id_re = re.compile('^episode-\d+\.html$')
|
||||
subtitle_re = re.compile('^\/subtitle-\d+\.html$')
|
||||
link_re = re.compile('^(?P<series>.+) \(\d{4}-\d{4}\)$')
|
||||
|
||||
def initialize(self):
|
||||
self.session = requests.Session()
|
||||
self.session.headers = {'User-Agent': self.primary_user_agent }
|
||||
|
||||
def terminate(self):
|
||||
self.session.close()
|
||||
|
||||
def request(self, url, params=None, data=None, method='GET'):
|
||||
"""Make a `method` request on `url` with the given parameters
|
||||
|
||||
:param string url: part of the URL to reach with the leading slash
|
||||
:param dict params: params of the request
|
||||
:param dict data: data of the request
|
||||
:param string method: method of the request
|
||||
:return: the response
|
||||
:rtype: :class:`bs4.BeautifulSoup`
|
||||
:raise: :class:`~subliminal.exceptions.ProviderNotAvailable`
|
||||
|
||||
"""
|
||||
try:
|
||||
r = self.session.request(method, self.server + url, params=params, data=data, timeout=10)
|
||||
except requests.Timeout:
|
||||
raise ProviderNotAvailable('Timeout after 10 seconds')
|
||||
if r.status_code != 200:
|
||||
raise ProviderNotAvailable('Request failed with status code %d' % r.status_code)
|
||||
return bs4.BeautifulSoup(r.content, ['permissive'])
|
||||
|
||||
@region.cache_on_arguments()
|
||||
def find_show_id(self, series):
|
||||
"""Find a show id from the series
|
||||
|
||||
:param string series: series of the episode
|
||||
:return: the show id, if any
|
||||
:rtype: int or None
|
||||
|
||||
"""
|
||||
data = {'q': series}
|
||||
logger.debug('Searching series %r', data)
|
||||
soup = self.request('/search.php', data=data, method='POST')
|
||||
links = soup.select('div.left li div a[href^="/tvshow-"]')
|
||||
sanitized_series = IGNORE_DATEMATCH.match(
|
||||
sanitize_string(series).replace('.', ' ').strip(),
|
||||
)
|
||||
if not sanitized_series:
|
||||
sanitized_series = sanitize_string(series)\
|
||||
.replace('.', ' ').strip()
|
||||
else:
|
||||
sanitized_series = sanitized_series.group(1)
|
||||
|
||||
if not links:
|
||||
logger.info('Series %r not found', series)
|
||||
return None
|
||||
|
||||
for link in links:
|
||||
match = self.link_re.match(link.string)
|
||||
if not match:
|
||||
logger.warning('Could not parse %r', link.string)
|
||||
continue
|
||||
show = IGNORE_DATEMATCH.match(
|
||||
sanitize_string(match.group('series'))\
|
||||
.replace('.', ' ').strip(),
|
||||
)
|
||||
if not show:
|
||||
logger.warning('Could not postparse %r', match.group('series'))
|
||||
continue
|
||||
show = show.group(1)
|
||||
|
||||
if show == sanitized_series:
|
||||
return int(link['href'][8:-5])
|
||||
return int(links[0]['href'][8:-5])
|
||||
|
||||
@region.cache_on_arguments()
|
||||
def find_episode_ids(self, show_id, season):
|
||||
"""Find episode ids from the show id and the season
|
||||
|
||||
:param int show_id: show id
|
||||
:param int season: season of the episode
|
||||
:return: episode ids per episode number
|
||||
:rtype: dict
|
||||
|
||||
"""
|
||||
params = {'show_id': show_id, 'season': season}
|
||||
logger.debug('Searching episodes %r', params)
|
||||
soup = self.request('/tvshow-{show_id}-{season}.html'.format(**params))
|
||||
episode_ids = {}
|
||||
for row in soup.select('table#table5 tr'):
|
||||
if not row('a', href=self.episode_id_re):
|
||||
continue
|
||||
cells = row('td')
|
||||
episode_ids[int(cells[0].string.split('x')[1])] = int(cells[1].a['href'][8:-5])
|
||||
return episode_ids
|
||||
|
||||
def query(self, series, season, episode):
|
||||
show_id = self.find_show_id(series)
|
||||
if show_id is None:
|
||||
return []
|
||||
episode_ids = self.find_episode_ids(show_id, season)
|
||||
if episode not in episode_ids:
|
||||
logger.info('Episode %d not found', episode)
|
||||
return []
|
||||
params = {'episode_id': episode_ids[episode]}
|
||||
logger.debug('Searching episode %r', params)
|
||||
soup = self.request('/episode-{episode_id}.html'.format(**params))
|
||||
return [TVsubtitlesSubtitle(babelfish.Language.fromtvsubtitles(row.h5.img['src'][13:-4]), series, season,
|
||||
episode, row['href'][10:-5], row.find('p', title='rip').text.strip() or None,
|
||||
row.find('p', title='release').text.strip() or None)
|
||||
for row in soup('a', href=self.subtitle_re)]
|
||||
|
||||
def list_subtitles(self, video, languages):
|
||||
return [s for s in self.query(video.series, video.season, video.episode) if s.language in languages]
|
||||
|
||||
def download_subtitle(self, subtitle):
|
||||
try:
|
||||
r = self.session.get(self.server + '/download-{subtitle_id}.html'.format(subtitle_id=subtitle.id),
|
||||
timeout=10)
|
||||
except requests.Timeout:
|
||||
raise ProviderNotAvailable('Timeout after 10 seconds')
|
||||
if r.status_code != 200:
|
||||
raise ProviderNotAvailable('Request failed with status code %d' % r.status_code)
|
||||
with contextlib.closing(zipfile.ZipFile(io.BytesIO(r.content))) as zf:
|
||||
if len(zf.namelist()) > 1:
|
||||
raise ProviderError('More than one file to unzip')
|
||||
subtitle_bytes = zf.read(zf.namelist()[0])
|
||||
subtitle_text = subtitle_bytes.decode(charade.detect(subtitle_bytes)['encoding'], 'replace')
|
||||
if not is_valid_subtitle(subtitle_text):
|
||||
raise InvalidSubtitle
|
||||
return subtitle_text
|
||||
Executable
+84
@@ -0,0 +1,84 @@
|
||||
#!/usr/bin/env python
|
||||
# -*- coding: utf-8 -*-
|
||||
from __future__ import print_function, unicode_literals
|
||||
from sympy import Eq, symbols, solve
|
||||
|
||||
|
||||
# Symbols
|
||||
release_group, resolution, video_codec, audio_codec = symbols('release_group resolution video_codec audio_codec')
|
||||
imdb_id, hash, title, series, tvdb_id, season, episode = symbols('imdb_id hash title series tvdb_id season episode') # @ReservedAssignment
|
||||
year = symbols('year')
|
||||
|
||||
|
||||
def get_episode_equations():
|
||||
"""Get the score equations for a :class:`~subliminal.video.Episode`
|
||||
|
||||
The equations are the following:
|
||||
|
||||
1. hash = resolution + video_codec + audio_codec + series + season + episode + release_group
|
||||
2. series = resolution + video_codec + audio_codec + season + episode + 1
|
||||
3. tvdb_id = series
|
||||
4. season = resolution + video_codec + audio_codec + 1
|
||||
5. imdb_id = series + season + episode
|
||||
6. resolution = video_codec
|
||||
7. video_codec = 2 * audio_codec
|
||||
8. title = season + episode
|
||||
9. season = episode
|
||||
10. release_group = season
|
||||
11. audio_codec = 1
|
||||
|
||||
:return: the score equations for an episode
|
||||
:rtype: list of :class:`sympy.Eq`
|
||||
|
||||
"""
|
||||
equations = []
|
||||
equations.append(Eq(hash, resolution + video_codec + audio_codec + series + season + episode + release_group))
|
||||
equations.append(Eq(series, resolution + video_codec + audio_codec + season + episode + release_group))
|
||||
equations.append(Eq(tvdb_id, series))
|
||||
equations.append(Eq(season, resolution + video_codec + audio_codec + 1))
|
||||
equations.append(Eq(imdb_id, series + season + episode))
|
||||
equations.append(Eq(resolution, video_codec))
|
||||
equations.append(Eq(video_codec, 2 * audio_codec))
|
||||
equations.append(Eq(title, season + episode))
|
||||
equations.append(Eq(season, episode))
|
||||
equations.append(Eq(release_group, season))
|
||||
equations.append(Eq(audio_codec, 1))
|
||||
return equations
|
||||
|
||||
|
||||
def get_movie_equations():
|
||||
"""Get the score equations for a :class:`~subliminal.video.Movie`
|
||||
|
||||
The equations are the following:
|
||||
|
||||
1. hash = resolution + video_codec + audio_codec + title + year + release_group
|
||||
2. imdb_id = hash
|
||||
3. resolution = video_codec
|
||||
4. video_codec = 2 * audio_codec
|
||||
5. title = resolution + video_codec + audio_codec + year + 1
|
||||
6. release_group = resolution + video_codec + audio_codec + 1
|
||||
7. year = release_group + 1
|
||||
8. audio_codec = 1
|
||||
|
||||
:return: the score equations for a movie
|
||||
:rtype: list of :class:`sympy.Eq`
|
||||
|
||||
"""
|
||||
equations = []
|
||||
equations.append(Eq(hash, resolution + video_codec + audio_codec + title + year + release_group))
|
||||
equations.append(Eq(imdb_id, hash))
|
||||
equations.append(Eq(resolution, video_codec))
|
||||
equations.append(Eq(video_codec, 2 * audio_codec))
|
||||
equations.append(Eq(title, resolution + video_codec + audio_codec + year + 1))
|
||||
equations.append(Eq(video_codec, 2 * audio_codec))
|
||||
equations.append(Eq(release_group, resolution + video_codec + audio_codec + 1))
|
||||
equations.append(Eq(year, release_group + 1))
|
||||
equations.append(Eq(audio_codec, 1))
|
||||
return equations
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
print(solve(get_episode_equations(), [release_group, resolution, video_codec, audio_codec, imdb_id,
|
||||
hash, series, tvdb_id, season, episode, title]))
|
||||
print(solve(get_movie_equations(), [release_group, resolution, video_codec, audio_codec, imdb_id,
|
||||
hash, title, year]))
|
||||
@@ -1,325 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
#
|
||||
# Subliminal - Subtitles, faster than your thoughts
|
||||
# Copyright (c) 2011 Antoine Bertin <diaoulael@gmail.com>
|
||||
#
|
||||
# This file is part of Subliminal.
|
||||
#
|
||||
# Subliminal is free software; you can redistribute it and/or modify it under
|
||||
# the terms of the Lesser GNU General Public License as published by
|
||||
# the Free Software Foundation; either version 3 of the License, or
|
||||
# (at your option) any later version.
|
||||
#
|
||||
# Subliminal is distributed in the hope that it will be useful,
|
||||
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
# Lesser GNU General Public License for more details.
|
||||
#
|
||||
# You should have received a copy of the Lesser GNU General Public License
|
||||
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
#
|
||||
|
||||
import threading
|
||||
from itertools import groupby
|
||||
from classes import DownloadTask, ListTask, StopTask, LanguageError, PluginError, BadStateError, WrongTaskError, DownloadFailedError
|
||||
import Queue
|
||||
import logging
|
||||
import mimetypes
|
||||
import os
|
||||
import plugins
|
||||
|
||||
|
||||
# be nice
|
||||
try:
|
||||
from logging import NullHandler
|
||||
except ImportError:
|
||||
|
||||
class NullHandler(logging.Handler):
|
||||
def emit(self, record):
|
||||
pass
|
||||
logger = logging.getLogger('subliminal')
|
||||
logger.addHandler(NullHandler())
|
||||
|
||||
# const
|
||||
FORMATS = ['video/x-msvideo', 'video/quicktime', 'video/x-matroska', 'video/mp4']
|
||||
EXTENSIONS = set(['srt', 'sub'])
|
||||
LANGUAGES = set(['aa', 'ab', 'ae', 'af', 'ak', 'am', 'an', 'ar', 'as', 'av', 'ay', 'az', 'ba', 'be', 'bg', 'bh', 'bi',
|
||||
'bm', 'bn', 'bo', 'br', 'bs', 'ca', 'ce', 'ch', 'co', 'cr', 'cs', 'cu', 'cv', 'cy', 'da', 'de', 'dv',
|
||||
'dz', 'ee', 'el', 'en', 'eo', 'es', 'et', 'eu', 'fa', 'ff', 'fi', 'fj', 'fo', 'fr', 'fy', 'ga', 'gd',
|
||||
'gl', 'gn', 'gu', 'gv', 'ha', 'he', 'hi', 'ho', 'hr', 'ht', 'hu', 'hy', 'hz', 'ia', 'id', 'ie', 'ig',
|
||||
'ii', 'ik', 'io', 'is', 'it', 'iu', 'ja', 'jv', 'ka', 'kg', 'ki', 'kj', 'kk', 'kl', 'km', 'kn', 'ko',
|
||||
'kr', 'ks', 'ku', 'kv', 'kw', 'ky', 'la', 'lb', 'lg', 'li', 'ln', 'lo', 'lt', 'lu', 'lv', 'mg', 'mh',
|
||||
'mi', 'mk', 'ml', 'mn', 'mo', 'mr', 'ms', 'mt', 'my', 'na', 'nb', 'nd', 'ne', 'ng', 'nl', 'nn', 'no',
|
||||
'nr', 'nv', 'ny', 'oc', 'oj', 'om', 'or', 'os', 'pa', 'pi', 'pl', 'ps', 'pt', 'qu', 'rm', 'rn', 'ro',
|
||||
'ru', 'rw', 'sa', 'sc', 'sd', 'se', 'sg', 'si', 'sk', 'sl', 'sm', 'sn', 'so', 'sq', 'sr', 'ss', 'st',
|
||||
'su', 'sv', 'sw', 'ta', 'te', 'tg', 'th', 'ti', 'tk', 'tl', 'tn', 'to', 'tr', 'ts', 'tt', 'tw', 'ty',
|
||||
'ug', 'uk', 'ur', 'uz', 've', 'vi', 'vo', 'wa', 'wo', 'xh', 'yi', 'yo', 'za', 'zh', 'zu']) # ISO 639-1
|
||||
PLUGINS = ['BierDopje', 'OpenSubtitles', 'SubsWiki', 'Subtitulos', 'TheSubDB']
|
||||
API_PLUGINS = filter(lambda p: getattr(plugins, p).api_based, PLUGINS)
|
||||
IDLE = 0
|
||||
RUNNING = 1
|
||||
PAUSED = 2
|
||||
|
||||
|
||||
class Subliminal(object):
|
||||
"""Main Subliminal class"""
|
||||
|
||||
def __init__(self, cache_dir=None, workers=4, multi=False, force=False, max_depth=3, files_mode=-1):
|
||||
self.multi = multi
|
||||
self.force = force
|
||||
self.max_depth = max_depth
|
||||
self.cache_dir = None
|
||||
self.taskQueue = Queue.PriorityQueue()
|
||||
self.listResultQueue = Queue.Queue()
|
||||
self.downloadResultQueue = Queue.Queue()
|
||||
self._languages = []
|
||||
self._plugins = API_PLUGINS
|
||||
self.workers = workers
|
||||
self.files_mode = files_mode
|
||||
self.state = IDLE
|
||||
try:
|
||||
if cache_dir:
|
||||
self.cache_dir = cache_dir
|
||||
if not os.path.isdir(self.cache_dir):
|
||||
os.makedirs(self.cache_dir)
|
||||
logger.debug(u'Creating cache directory: %r' % self.cache_dir)
|
||||
except:
|
||||
self.cache_dir = None
|
||||
logger.error(u'Failed to use the cache directory, continue without it')
|
||||
|
||||
@property
|
||||
def languages(self):
|
||||
"""Getter for languages"""
|
||||
return self._languages
|
||||
|
||||
@languages.setter
|
||||
def languages(self, languages):
|
||||
"""Setter for languages"""
|
||||
logger.debug(u'Setting languages to %r' % languages)
|
||||
self._languages = []
|
||||
for l in languages:
|
||||
if l not in LANGUAGES:
|
||||
raise LanguageError(l)
|
||||
if not l in self._languages:
|
||||
self._languages.append(l)
|
||||
|
||||
@property
|
||||
def plugins(self):
|
||||
"""Getter for plugins"""
|
||||
return self._plugins
|
||||
|
||||
@plugins.setter
|
||||
def plugins(self, plugins):
|
||||
"""Setter for plugins"""
|
||||
logger.debug(u'Setting plugins to %r' % plugins)
|
||||
self._plugins = []
|
||||
for p in plugins:
|
||||
if p not in PLUGINS:
|
||||
raise PluginError(p)
|
||||
if not p in self._plugins:
|
||||
self._plugins.append(p)
|
||||
|
||||
def listSubtitles(self, entries, auto=True):
|
||||
"""
|
||||
Search subtitles within the plugins and return all found subtitles in a list of Subtitle object.
|
||||
|
||||
Attributes:
|
||||
entries -- filepath or folderpath of video file or a list of that
|
||||
auto -- automaticaly manage workers"""
|
||||
if auto:
|
||||
if self.state != IDLE:
|
||||
raise BadStateError(self.state, IDLE)
|
||||
self.startWorkers()
|
||||
if isinstance(entries, basestring):
|
||||
entries = [entries]
|
||||
scan_result = []
|
||||
for e in entries:
|
||||
if not isinstance(e, unicode):
|
||||
logger.warning(u'Entry %r is not unicode' % e)
|
||||
if not os.path.exists(e):
|
||||
scan_result.append((e, set(), False))
|
||||
continue
|
||||
scan_result.extend(scan(e))
|
||||
task_count = 0
|
||||
for filepath, languages, has_single in scan_result:
|
||||
wanted_languages = set(self._languages)
|
||||
if not wanted_languages:
|
||||
wanted_languages = LANGUAGES
|
||||
if not self.force and self.multi:
|
||||
wanted_languages = set(wanted_languages) - languages
|
||||
if not wanted_languages:
|
||||
logger.debug(u'No need to list multi subtitles %r for %r because %r subtitles detected' % (self._languages, filepath, languages))
|
||||
continue
|
||||
if not self.force and not self.multi and has_single:
|
||||
logger.debug(u'No need to list single subtitles %r for %r because one detected' % (self._languages, filepath))
|
||||
continue
|
||||
logger.debug(u'Listing subtitles %r for %r with %r' % (wanted_languages, filepath, self._plugins))
|
||||
for plugin in self._plugins:
|
||||
self.taskQueue.put((5, ListTask(filepath, wanted_languages, plugin, self.getConfigDict())))
|
||||
task_count += 1
|
||||
subtitles = []
|
||||
for _ in range(task_count):
|
||||
subtitles.extend(self.listResultQueue.get())
|
||||
if auto:
|
||||
self.stopWorkers()
|
||||
return subtitles
|
||||
|
||||
def downloadSubtitles(self, entries, auto=True):
|
||||
"""
|
||||
Download subtitles using the plugins preferences and languages. Also use internal algorithm to find
|
||||
the best match inside a plugin.
|
||||
|
||||
Attributes:
|
||||
entries -- filepath or folderpath of video file or a list of that
|
||||
auto -- automaticaly manage workers"""
|
||||
if auto:
|
||||
if self.state != IDLE:
|
||||
raise BadStateError(self.state, IDLE)
|
||||
self.startWorkers()
|
||||
subtitles = self.listSubtitles(entries, False)
|
||||
task_count = 0
|
||||
for _, subsByVideoPath in groupby(sorted(subtitles, key=lambda x: x.video_path), lambda x: x.video_path):
|
||||
if not self.multi:
|
||||
self.taskQueue.put((5, DownloadTask(sorted(list(subsByVideoPath), cmp=self.cmpSubtitles))))
|
||||
task_count += 1
|
||||
continue
|
||||
for __, subsByVideoPathByLanguage in groupby(sorted(subsByVideoPath, key=lambda x: x.language), lambda x: x.language):
|
||||
self.taskQueue.put((5, DownloadTask(sorted(list(subsByVideoPathByLanguage), cmp=self.cmpSubtitles))))
|
||||
task_count += 1
|
||||
downloaded = []
|
||||
for _ in range(task_count):
|
||||
downloaded.extend(self.downloadResultQueue.get())
|
||||
if auto:
|
||||
self.stopWorkers()
|
||||
return downloaded
|
||||
|
||||
def cmpSubtitles(self, x, y):
|
||||
"""Compares 2 subtitles elements x and y using video_path, languages and plugin"""
|
||||
video_paths = sorted([x.video_path, y.video_path])
|
||||
if x.video_path != y.video_path and video_paths.index(x.video_path) < video_paths(y.video_path):
|
||||
return - 1
|
||||
if x.video_path != y.video_path and video_paths.index(x.video_path) > video_paths(y.video_path):
|
||||
return 1
|
||||
if self._languages and self._languages.index(x.language) < self._languages.index(y.language):
|
||||
return - 1
|
||||
if self._languages and self._languages.index(x.language) > self._languages.index(y.language):
|
||||
return 1
|
||||
if self._plugins.index(x.plugin) < self._plugins.index(y.plugin):
|
||||
return - 1
|
||||
if self._plugins.index(x.plugin) > self._plugins.index(y.plugin):
|
||||
return 1
|
||||
return 0
|
||||
|
||||
def startWorkers(self):
|
||||
"""Create a pool of workers and start them"""
|
||||
self.pool = []
|
||||
for _ in range(self.workers):
|
||||
worker = PluginWorker(self.taskQueue, self.listResultQueue, self.downloadResultQueue)
|
||||
worker.start()
|
||||
self.pool.append(worker)
|
||||
logger.debug(u'Worker %s added to the pool' % worker.name)
|
||||
self.state = RUNNING
|
||||
|
||||
def stopWorkers(self):
|
||||
"""Stop workers using a lowest priority stop signal and wait for them to terminate properly"""
|
||||
for _ in range(self.workers):
|
||||
self.taskQueue.put((10, StopTask()))
|
||||
for worker in self.pool:
|
||||
worker.join()
|
||||
self.state = IDLE
|
||||
|
||||
def pauseWorkers(self):
|
||||
"""Pause workers using a highest priority stop signal and wait for them to terminate properly"""
|
||||
for _ in range(self.workers):
|
||||
self.taskQueue.put((0, StopTask()))
|
||||
for worker in self.pool:
|
||||
worker.join()
|
||||
self.state = PAUSED
|
||||
if self.taskQueue.empty():
|
||||
self.state = STOPPED
|
||||
|
||||
def getConfigDict(self):
|
||||
"""Produce a dict with configuration items. Used by plugins to read configuration"""
|
||||
config = {}
|
||||
config['multi'] = self.multi
|
||||
config['cache_dir'] = self.cache_dir
|
||||
config['files_mode'] = self.files_mode
|
||||
return config
|
||||
|
||||
def addTask(self, task):
|
||||
if not isinstance(task, Task) or isinstance(task, StopTask):
|
||||
raise WrongTaskError()
|
||||
self.taskQueue.put((5, task))
|
||||
|
||||
|
||||
class PluginWorker(threading.Thread):
|
||||
"""Threaded plugin worker"""
|
||||
def __init__(self, taskQueue, listResultQueue, downloadResultQueue):
|
||||
threading.Thread.__init__(self)
|
||||
self.taskQueue = taskQueue
|
||||
self.listResultQueue = listResultQueue
|
||||
self.downloadResultQueue = downloadResultQueue
|
||||
self.logger = logging.getLogger('subliminal.worker')
|
||||
|
||||
def run(self):
|
||||
while True:
|
||||
task = self.taskQueue.get()[1]
|
||||
if isinstance(task, StopTask):
|
||||
self.logger.debug(u'Poison pill received, terminating thread %s' % self.name)
|
||||
self.taskQueue.task_done()
|
||||
break
|
||||
result = []
|
||||
try:
|
||||
if isinstance(task, ListTask):
|
||||
plugin = getattr(plugins, task.plugin)(task.config)
|
||||
result = plugin.list(task.filepath, task.languages)
|
||||
elif isinstance(task, DownloadTask):
|
||||
for subtitle in task.subtitles:
|
||||
plugin = getattr(plugins, subtitle.plugin)()
|
||||
try:
|
||||
result = [plugin.download(subtitle)]
|
||||
break
|
||||
except DownloadFailedError as e:
|
||||
self.logger.warning(u'Could not download subtitle %r, trying next' % subtitle)
|
||||
continue
|
||||
if not result:
|
||||
self.logger.error(u'No subtitles could be downloaded for file %r' % subtitle.video_path)
|
||||
except:
|
||||
self.logger.error(u'Exception raised in worker %s' % self.name, exc_info=True)
|
||||
finally:
|
||||
if isinstance(task, ListTask):
|
||||
self.listResultQueue.put(result)
|
||||
elif isinstance(task, DownloadTask):
|
||||
self.downloadResultQueue.put(result)
|
||||
self.taskQueue.task_done()
|
||||
self.logger.debug(u'Thread %s terminated' % self.name)
|
||||
|
||||
|
||||
def scan(entry, depth=0, max_depth=3):
|
||||
"""Scan a path and return a list of tuples (filepath, set(languages), has single)"""
|
||||
if depth > max_depth and max_depth != 0: # we do not want to search the whole file system except if max_depth = 0
|
||||
return []
|
||||
if depth == 0:
|
||||
entry = os.path.abspath(entry)
|
||||
if os.path.isfile(entry): # a file? scan it
|
||||
if depth != 0: # trust the user: only check for valid format if recursing
|
||||
mimetypes.add_type('video/x-matroska', '.mkv')
|
||||
if mimetypes.guess_type(entry)[0] not in FORMATS:
|
||||
return []
|
||||
# check for .lg.ext and .ext
|
||||
available_languages = set()
|
||||
has_single = False
|
||||
basepath = os.path.splitext(entry)[0]
|
||||
for l in LANGUAGES:
|
||||
for e in EXTENSIONS:
|
||||
if os.path.exists(basepath + '.%s.%s' % (l, e)):
|
||||
available_languages.add(l)
|
||||
if os.path.exists(basepath + '.%s' % e):
|
||||
has_single = True
|
||||
return [(os.path.normpath(entry), available_languages, has_single)]
|
||||
if os.path.isdir(entry): # a dir? recurse
|
||||
result = []
|
||||
for e in os.listdir(entry):
|
||||
result.extend(scan(os.path.join(entry, e), depth + 1))
|
||||
return result
|
||||
return [] # anything else
|
||||
@@ -0,0 +1,187 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
from __future__ import unicode_literals
|
||||
import logging
|
||||
import os.path
|
||||
import babelfish
|
||||
import pysrt
|
||||
import re
|
||||
from .video import Episode, Movie
|
||||
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
#: The following characters are always stripped
|
||||
IGNORED_CHARACTERS_RE = re.compile('[!@#$\'"]')
|
||||
|
||||
|
||||
class Subtitle(object):
|
||||
"""Base class for subtitle
|
||||
|
||||
:param language: language of the subtitle
|
||||
:type language: :class:`babelfish.Language`
|
||||
:param bool hearing_impaired: `True` if the subtitle is hearing impaired, `False` otherwise
|
||||
|
||||
"""
|
||||
def __init__(self, language, hearing_impaired=False):
|
||||
self.language = language
|
||||
self.hearing_impaired = hearing_impaired
|
||||
|
||||
def compute_matches(self, video):
|
||||
"""Compute the matches of the subtitle against the `video`
|
||||
|
||||
:param video: the video to compute the matches against
|
||||
:type video: :class:`~subliminal.video.Video`
|
||||
:return: matches of the subtitle
|
||||
:rtype: set
|
||||
|
||||
"""
|
||||
raise NotImplementedError
|
||||
|
||||
def compute_score(self, video, hi_score_adjust=0):
|
||||
"""Compute the score of the subtitle against the `video`
|
||||
|
||||
There are equivalent matches so that a provider can match one element or its equivalent. This is
|
||||
to give all provider a chance to have a score in the same range without hurting quality.
|
||||
|
||||
* Matching :class:`~subliminal.video.Video`'s `hashes` is equivalent to matching everything else
|
||||
* Matching :class:`~subliminal.video.Episode`'s `season` and `episode`
|
||||
is equivalent to matching :class:`~subliminal.video.Episode`'s `title`
|
||||
* Matching :class:`~subliminal.video.Episode`'s `tvdb_id` is equivalent to matching
|
||||
:class:`~subliminal.video.Episode`'s `series`
|
||||
|
||||
:param video: the video to compute the score against
|
||||
:type video: :class:`~subliminal.video.Video`
|
||||
:param hi_score_adjust: adjust hearing impaired matched videos by this value
|
||||
:return: score of the subtitle
|
||||
:rtype: int
|
||||
|
||||
"""
|
||||
score = 0
|
||||
# compute matches
|
||||
initial_matches = self.compute_matches(video)
|
||||
matches = initial_matches.copy()
|
||||
# hash is the perfect match
|
||||
if 'hash' in matches:
|
||||
score = video.scores['hash']
|
||||
else:
|
||||
# remove equivalences
|
||||
if isinstance(video, Episode):
|
||||
if 'imdb_id' in matches:
|
||||
matches -= set(['series', 'tvdb_id', 'season', 'episode', 'title'])
|
||||
if 'tvdb_id' in matches:
|
||||
matches -= set(['series',])
|
||||
if 'title' in matches:
|
||||
matches -= set(['season', 'episode'])
|
||||
# add other scores
|
||||
score += sum([video.scores[match] for match in matches])
|
||||
|
||||
# Adjust scoring if hearing impaired subtitles are detected
|
||||
if self.hearing_impaired and hi_score_adjust != 0:
|
||||
logger.debug('Hearing impaired subtitle score adjusted ' + \
|
||||
'by %d' % hi_score_adjust)
|
||||
# Priortization (adjust score)
|
||||
score += hi_score_adjust
|
||||
|
||||
logger.debug('Computed score %d with matches %r', score, initial_matches)
|
||||
return score
|
||||
|
||||
def __repr__(self):
|
||||
return '<%s [%s]>' % (self.__class__.__name__, self.language)
|
||||
|
||||
|
||||
def sanitize_string(str_in):
|
||||
"""
|
||||
Sanitizes a string passed into it by eliminating characters that might
|
||||
otherwise cause issues when attempting to locate a match on websites by
|
||||
striping out any special characters and forcing a consistent string that
|
||||
can be used for caching too.
|
||||
|
||||
:param string str_in: the string to sanitize
|
||||
:return: sanitized string
|
||||
:rtype: string
|
||||
"""
|
||||
if not isinstance(str_in, basestring):
|
||||
# handle int, float, etc
|
||||
str_in = str(str_in)
|
||||
|
||||
return IGNORED_CHARACTERS_RE.sub('', str_in).lower().strip()
|
||||
|
||||
def get_subtitle_path(video_path, language=None):
|
||||
"""Create the subtitle path from the given `video_path` and `language`
|
||||
|
||||
:param string video_path: path to the video
|
||||
:param language: language of the subtitle to put in the path
|
||||
:type language: :class:`babelfish.Language` or None
|
||||
:return: path of the subtitle
|
||||
:rtype: string
|
||||
|
||||
"""
|
||||
subtitle_path = os.path.splitext(video_path)[0]
|
||||
if language is not None:
|
||||
try:
|
||||
return subtitle_path + '.%s.%s' % (language.alpha2, 'srt')
|
||||
except babelfish.LanguageConvertError:
|
||||
return subtitle_path + '.%s.%s' % (language.alpha3, 'srt')
|
||||
return subtitle_path + '.srt'
|
||||
|
||||
|
||||
def is_valid_subtitle(subtitle_text):
|
||||
"""Check if a subtitle text is a valid SubRip format
|
||||
|
||||
:return: `True` if the subtitle is valid, `False` otherwise
|
||||
:rtype: bool
|
||||
|
||||
"""
|
||||
try:
|
||||
pysrt.from_string(subtitle_text, error_handling=pysrt.ERROR_RAISE)
|
||||
return True
|
||||
except pysrt.Error as e:
|
||||
if e.args[0] > 80:
|
||||
return True
|
||||
except:
|
||||
logger.exception('Unexpected error when validating subtitle')
|
||||
return False
|
||||
|
||||
|
||||
def compute_guess_matches(video, guess):
|
||||
"""Compute matches between a `video` and a `guess`
|
||||
|
||||
:param video: the video to compute the matches on
|
||||
:type video: :class:`~subliminal.video.Video`
|
||||
:param guess: the guess to compute the matches on
|
||||
:type guess: :class:`guessit.Guess`
|
||||
:return: matches of the `guess`
|
||||
:rtype: set
|
||||
|
||||
"""
|
||||
matches = set()
|
||||
if isinstance(video, Episode):
|
||||
# Series
|
||||
if video.series and 'series' in guess and guess['series'].lower() == video.series.lower():
|
||||
matches.add('series')
|
||||
# Season
|
||||
if video.season and 'seasonNumber' in guess and guess['seasonNumber'] == video.season:
|
||||
matches.add('season')
|
||||
# Episode
|
||||
if video.episode and 'episodeNumber' in guess and guess['episodeNumber'] == video.episode:
|
||||
matches.add('episode')
|
||||
elif isinstance(video, Movie):
|
||||
# Year
|
||||
if video.year and 'year' in guess and guess['year'] == video.year:
|
||||
matches.add('year')
|
||||
# Title
|
||||
if video.title and 'title' in guess and guess['title'].lower() == video.title.lower():
|
||||
matches.add('title')
|
||||
# Release group
|
||||
if video.release_group and 'releaseGroup' in guess and guess['releaseGroup'].lower() == video.release_group.lower():
|
||||
matches.add('release_group')
|
||||
# Screen size
|
||||
if video.resolution and 'screenSize' in guess and guess['screenSize'] == video.resolution:
|
||||
matches.add('resolution')
|
||||
# Video codec
|
||||
if video.video_codec and 'videoCodec' in guess and guess['videoCodec'] == video.video_codec:
|
||||
matches.add('video_codec')
|
||||
# Audio codec
|
||||
if video.audio_codec and 'audioCodec' in guess and guess['audioCodec'] == video.audio_codec:
|
||||
matches.add('audio_codec')
|
||||
return matches
|
||||
@@ -0,0 +1,14 @@
|
||||
#!/usr/bin/env python
|
||||
# -*- coding: utf-8 -*-
|
||||
from __future__ import unicode_literals
|
||||
from unittest import TextTestRunner, TestSuite
|
||||
from subliminal import cache_region
|
||||
from . import test_providers, test_subliminal
|
||||
|
||||
|
||||
cache_region.configure('dogpile.cache.memory', expiration_time=60 * 30) # @UndefinedVariable
|
||||
suite = TestSuite([test_providers.suite(), test_subliminal.suite()])
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
TextTestRunner().run(suite)
|
||||
@@ -0,0 +1,19 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
from __future__ import unicode_literals
|
||||
from subliminal import Movie, Episode
|
||||
|
||||
|
||||
MOVIES = [Movie('Man of Steel (2013)/man.of.steel.2013.720p.bluray.x264-felony.mkv', 'Man of Steel',
|
||||
release_group='felony', resolution='720p', video_codec='h264', audio_codec='DTS', imdb_id=770828,
|
||||
size=7033732714, year=2013,
|
||||
hashes={'opensubtitles': '5b8f8f4e41ccb21e', 'thesubdb': 'ad32876133355929d814457537e12dc2'})]
|
||||
|
||||
EPISODES = [Episode('The Big Bang Theory/Season 07/The.Big.Bang.Theory.S07E05.720p.HDTV.X264-DIMENSION.mkv',
|
||||
'The Big Bang Theory', 7, 5, release_group='DIMENSION', resolution='720p', video_codec='h264',
|
||||
audio_codec='AC3', imdb_id=3229392, size=501910737, title='The Workplace Proximity',
|
||||
tvdb_id=80379,
|
||||
hashes={'opensubtitles': '6878b3ef7c1bd19e', 'thesubdb': '9dbbfb7ba81c9a6237237dae8589fccc'}),
|
||||
Episode('Game of Thrones/Season 03/Game.of.Thrones.S03E10.Mhysa.720p.WEB-DL.DD5.1.H.264-NTb.mkv',
|
||||
'Game of Thrones', 3, 10, release_group='NTb', resolution='720p', video_codec='h264',
|
||||
audio_codec='AC3', imdb_id=2178796, size=2142810931, title='Mhysa', tvdb_id=121361,
|
||||
hashes={'opensubtitles': 'b850baa096976c22', 'thesubdb': 'b1f899c77f4c960b84b8dbf840d4e42d'})]
|
||||
@@ -0,0 +1,383 @@
|
||||
#!/usr/bin/env python
|
||||
# -*- coding: utf-8 -*-
|
||||
from __future__ import unicode_literals
|
||||
import os
|
||||
from unittest import TestCase, TestSuite, TestLoader, TextTestRunner
|
||||
from babelfish import Language
|
||||
from pkg_resources import iter_entry_points
|
||||
from subliminal import PROVIDERS_ENTRY_POINT
|
||||
from subliminal.subtitle import is_valid_subtitle
|
||||
from subliminal.tests.common import MOVIES, EPISODES
|
||||
|
||||
|
||||
class ProviderTestCase(TestCase):
|
||||
provider_name = ''
|
||||
|
||||
def setUp(self):
|
||||
for provider_entry_point in iter_entry_points(PROVIDERS_ENTRY_POINT, self.provider_name):
|
||||
self.Provider = provider_entry_point.load()
|
||||
break
|
||||
|
||||
|
||||
class Addic7edProviderTestCase(ProviderTestCase):
|
||||
provider_name = 'addic7ed'
|
||||
|
||||
def test_find_show_id(self):
|
||||
with self.Provider() as provider:
|
||||
show_id = provider.find_show_id('The Big Bang')
|
||||
self.assertEqual(show_id, 126)
|
||||
|
||||
def test_find_show_id_error(self):
|
||||
with self.Provider() as provider:
|
||||
show_id = provider.find_show_id('the big how i met your mother')
|
||||
self.assertEqual(show_id, None)
|
||||
|
||||
def test_get_show_ids(self):
|
||||
with self.Provider() as provider:
|
||||
show_ids = provider.get_show_ids()
|
||||
self.assertTrue('the big bang theory' in show_ids)
|
||||
self.assertEqual(show_ids['the big bang theory'], 126)
|
||||
|
||||
def test_query_episode_0(self):
|
||||
video = EPISODES[0]
|
||||
languages = set([Language('rus'), Language('heb'), Language('ita'), Language('fra'),
|
||||
Language('ron'), Language('nld'), Language('eng'), Language('deu'), Language('ell'),
|
||||
Language('por', 'BR'), Language('bul')])
|
||||
matches = set([frozenset(['episode', 'release_group', 'title', 'series', 'resolution', 'season']),
|
||||
frozenset(['series', 'resolution', 'season']),
|
||||
frozenset(['series', 'episode', 'season', 'title']),
|
||||
frozenset(['series', 'release_group', 'season']),
|
||||
frozenset(['series', 'episode', 'season', 'release_group', 'title']),
|
||||
frozenset(['series', 'season'])])
|
||||
with self.Provider() as provider:
|
||||
subtitles = provider.query(video.series, video.season)
|
||||
self.assertTrue(matches - set([frozenset(subtitle.compute_matches(video)) for subtitle in subtitles]) == set([]))
|
||||
self.assertTrue(languages - set([subtitle.language for subtitle in subtitles]) == set([]))
|
||||
|
||||
def test_query_episode_1(self):
|
||||
video = EPISODES[1]
|
||||
languages = set([Language('ind'), Language('spa'), Language('hrv'), Language('ita'), Language('fra'),
|
||||
Language('cat'), Language('ell'), Language('nld'), Language('eng'), Language('fas'),
|
||||
Language('por'), Language('nor'), Language('deu'), Language('ron'), Language('por', 'BR'),
|
||||
Language('bul')])
|
||||
matches = set([frozenset(['series', 'episode', 'resolution', 'season', 'title']),
|
||||
frozenset(['series', 'resolution', 'season']),
|
||||
frozenset(['series', 'episode', 'season', 'title']),
|
||||
frozenset(['series', 'release_group', 'season']),
|
||||
frozenset(['series', 'resolution', 'release_group', 'season']),
|
||||
frozenset(['series', 'episode', 'season', 'release_group', 'title']),
|
||||
frozenset(['series', 'season'])])
|
||||
with self.Provider() as provider:
|
||||
subtitles = provider.query(video.series, video.season)
|
||||
self.assertTrue(matches - set([frozenset(subtitle.compute_matches(video)) for subtitle in subtitles]) == set([]))
|
||||
self.assertTrue(languages - set([subtitle.language for subtitle in subtitles]) == set([]))
|
||||
|
||||
def test_list_subtitles(self):
|
||||
video = EPISODES[0]
|
||||
languages = set([Language('eng'), Language('fra')])
|
||||
matches = set([frozenset(['series', 'episode', 'season', 'release_group', 'title']),
|
||||
frozenset(['series', 'episode', 'season', 'title'])])
|
||||
with self.Provider() as provider:
|
||||
subtitles = provider.list_subtitles(video, languages)
|
||||
self.assertTrue(matches - set([frozenset(subtitle.compute_matches(video)) for subtitle in subtitles]) == set([]))
|
||||
self.assertTrue(languages - set([subtitle.language for subtitle in subtitles]) == set([]))
|
||||
|
||||
def test_download_subtitle(self):
|
||||
video = EPISODES[0]
|
||||
languages = set([Language('eng'), Language('fra')])
|
||||
with self.Provider() as provider:
|
||||
subtitles = provider.list_subtitles(video, languages)
|
||||
subtitle_text = provider.download_subtitle(subtitles[0])
|
||||
self.assertTrue(is_valid_subtitle(subtitle_text))
|
||||
|
||||
|
||||
class OpenSubtitlesProviderTestCase(ProviderTestCase):
|
||||
provider_name = 'opensubtitles'
|
||||
|
||||
def test_query_movie_0_query(self):
|
||||
video = MOVIES[0]
|
||||
languages = set([Language('eng'), ])
|
||||
matches = set([frozenset([]), frozenset(['imdb_id', 'resolution', 'title', 'year']),
|
||||
frozenset(['imdb_id', 'title', 'year']),
|
||||
frozenset(['imdb_id', 'video_codec', 'title', 'year']),
|
||||
frozenset(['imdb_id', 'resolution', 'title', 'video_codec', 'year']),
|
||||
frozenset(['imdb_id', 'title', 'year', 'video_codec', 'resolution', 'release_group'])])
|
||||
with self.Provider() as provider:
|
||||
subtitles = provider.query(languages, query=video.title)
|
||||
self.assertTrue(matches - set([frozenset(subtitle.compute_matches(video)) for subtitle in subtitles]) == set([]))
|
||||
self.assertTrue(languages - set([subtitle.language for subtitle in subtitles]) == set([]))
|
||||
|
||||
def test_query_episode_0_query(self):
|
||||
video = EPISODES[0]
|
||||
languages = set([Language('eng'), ])
|
||||
matches = set([frozenset(['series', 'episode', 'season', 'imdb_id']),
|
||||
frozenset(['series', 'imdb_id', 'video_codec', 'episode', 'season']),
|
||||
frozenset(['episode', 'title', 'series', 'imdb_id', 'video_codec', 'season'])])
|
||||
with self.Provider() as provider:
|
||||
subtitles = provider.query(languages, query=video.name.split(os.sep)[-1])
|
||||
self.assertTrue(matches - set([frozenset(subtitle.compute_matches(video)) for subtitle in subtitles]) == set([]))
|
||||
self.assertTrue(languages - set([subtitle.language for subtitle in subtitles]) == set([]))
|
||||
|
||||
def test_query_episode_1_query(self):
|
||||
video = EPISODES[1]
|
||||
languages = set([Language('eng'), Language('fra')])
|
||||
matches = set([frozenset(['episode', 'title', 'series', 'imdb_id', 'video_codec', 'season']),
|
||||
frozenset(['series', 'imdb_id', 'title', 'episode', 'season']),
|
||||
frozenset(['series', 'imdb_id', 'video_codec', 'episode', 'season']),
|
||||
frozenset(['episode', 'video_codec', 'series', 'imdb_id', 'resolution', 'season']),
|
||||
frozenset(['series', 'imdb_id', 'resolution', 'episode', 'season']),
|
||||
frozenset(['series', 'episode', 'season', 'imdb_id'])])
|
||||
with self.Provider() as provider:
|
||||
subtitles = provider.query(languages, query=video.name.split(os.sep)[-1])
|
||||
self.assertTrue(matches - set([frozenset(subtitle.compute_matches(video)) for subtitle in subtitles]) == set([]))
|
||||
self.assertTrue(languages - set([subtitle.language for subtitle in subtitles]) == set([]))
|
||||
|
||||
def test_query_movie_0_imdb_id(self):
|
||||
video = MOVIES[0]
|
||||
languages = set([Language('eng'), Language('fra')])
|
||||
matches = set([frozenset(['imdb_id', 'video_codec', 'title', 'year']),
|
||||
frozenset(['imdb_id', 'resolution', 'title', 'video_codec', 'year']),
|
||||
frozenset(['imdb_id', 'title', 'year', 'video_codec', 'resolution', 'release_group']),
|
||||
frozenset(['imdb_id', 'title', 'year']),
|
||||
frozenset(['imdb_id', 'resolution', 'title', 'year'])])
|
||||
with self.Provider() as provider:
|
||||
subtitles = provider.query(languages, imdb_id=video.imdb_id)
|
||||
self.assertTrue(matches - set([frozenset(subtitle.compute_matches(video)) for subtitle in subtitles]) == set([]))
|
||||
self.assertTrue(languages - set([subtitle.language for subtitle in subtitles]) == set([]))
|
||||
|
||||
def test_query_episode_0_imdb_id(self):
|
||||
video = EPISODES[0]
|
||||
languages = set([Language('eng'), Language('fra')])
|
||||
matches = set([frozenset(['series', 'episode', 'season', 'imdb_id']),
|
||||
frozenset(['episode', 'release_group', 'video_codec', 'series', 'imdb_id', 'resolution', 'season']),
|
||||
frozenset(['series', 'imdb_id', 'video_codec', 'episode', 'season']),
|
||||
frozenset(['episode', 'title', 'series', 'imdb_id', 'video_codec', 'season'])])
|
||||
with self.Provider() as provider:
|
||||
subtitles = provider.query(languages, imdb_id=video.imdb_id)
|
||||
self.assertTrue(matches - set([frozenset(subtitle.compute_matches(video)) for subtitle in subtitles]) == set([]))
|
||||
self.assertTrue(languages - set([subtitle.language for subtitle in subtitles]) == set([]))
|
||||
|
||||
def test_query_movie_0_hash(self):
|
||||
video = MOVIES[0]
|
||||
languages = set([Language('eng'), ])
|
||||
matches = set([frozenset(['hash', 'title', 'video_codec', 'year', 'resolution', 'imdb_id']),
|
||||
frozenset(['hash', 'title', 'video_codec', 'year', 'resolution', 'release_group', 'imdb_id']),
|
||||
frozenset(['year', 'video_codec', 'imdb_id', 'hash', 'title']),
|
||||
frozenset([]),
|
||||
frozenset(['year', 'resolution', 'imdb_id', 'hash', 'title']),
|
||||
frozenset(['year', 'imdb_id', 'hash', 'title'])])
|
||||
with self.Provider() as provider:
|
||||
subtitles = provider.query(languages, hash=video.hashes['opensubtitles'], size=video.size)
|
||||
self.assertTrue(matches - set([frozenset(subtitle.compute_matches(video)) for subtitle in subtitles]) == set([]))
|
||||
self.assertTrue(languages - set([subtitle.language for subtitle in subtitles]) == set([]))
|
||||
|
||||
def test_query_episode_0_hash(self):
|
||||
video = EPISODES[0]
|
||||
languages = set([Language('eng'), ])
|
||||
matches = set([frozenset(['series', 'hash']),
|
||||
frozenset(['episode', 'season', 'series', 'imdb_id', 'video_codec', 'hash']),
|
||||
frozenset(['series', 'episode', 'season', 'hash', 'imdb_id']),
|
||||
frozenset(['series', 'resolution', 'hash', 'video_codec'])])
|
||||
with self.Provider() as provider:
|
||||
subtitles = provider.query(languages, hash=video.hashes['opensubtitles'], size=video.size)
|
||||
self.assertTrue(matches - set([frozenset(subtitle.compute_matches(video)) for subtitle in subtitles]) == set([]))
|
||||
self.assertTrue(languages - set([subtitle.language for subtitle in subtitles]) == set([]))
|
||||
|
||||
def test_list_subtitles(self):
|
||||
video = MOVIES[0]
|
||||
languages = set([Language('eng'), Language('fra')])
|
||||
matches = set([frozenset(['title', 'video_codec', 'year', 'resolution', 'release_group', 'imdb_id']),
|
||||
frozenset(['imdb_id', 'year', 'title']),
|
||||
frozenset(['year', 'video_codec', 'imdb_id', 'resolution', 'title']),
|
||||
frozenset(['hash', 'title', 'video_codec', 'year', 'resolution', 'release_group', 'imdb_id']),
|
||||
frozenset(['year', 'video_codec', 'imdb_id', 'hash', 'title']),
|
||||
frozenset([]),
|
||||
frozenset(['year', 'resolution', 'imdb_id', 'hash', 'title']),
|
||||
frozenset(['hash', 'title', 'video_codec', 'year', 'resolution', 'imdb_id']),
|
||||
frozenset(['year', 'imdb_id', 'hash', 'title']),
|
||||
frozenset(['video_codec', 'imdb_id', 'year', 'title']),
|
||||
frozenset(['year', 'imdb_id', 'resolution', 'title'])])
|
||||
with self.Provider() as provider:
|
||||
subtitles = provider.list_subtitles(video, languages)
|
||||
self.assertTrue(matches - set([frozenset(subtitle.compute_matches(video)) for subtitle in subtitles]) == set([]))
|
||||
self.assertTrue(languages - set([subtitle.language for subtitle in subtitles]) == set([]))
|
||||
|
||||
def test_download_subtitle(self):
|
||||
video = MOVIES[0]
|
||||
languages = set([Language('eng'), Language('fra')])
|
||||
with self.Provider() as provider:
|
||||
subtitles = provider.list_subtitles(video, languages)
|
||||
subtitle_text = provider.download_subtitle(subtitles[0])
|
||||
self.assertTrue(is_valid_subtitle(subtitle_text))
|
||||
|
||||
|
||||
class PodnapisiProviderTestCase(ProviderTestCase):
|
||||
provider_name = 'podnapisi'
|
||||
|
||||
def test_query_movie_0(self):
|
||||
video = MOVIES[0]
|
||||
language = Language('eng')
|
||||
matches = set([frozenset(['video_codec', 'title', 'resolution', 'year']),
|
||||
frozenset(['title', 'resolution', 'year']),
|
||||
frozenset(['video_codec', 'title', 'year']),
|
||||
frozenset(['title', 'year']),
|
||||
frozenset(['video_codec', 'title', 'resolution', 'release_group', 'year']),
|
||||
frozenset(['video_codec', 'title', 'resolution', 'audio_codec', 'year'])])
|
||||
with self.Provider() as provider:
|
||||
subtitles = provider.query(language, title=video.title, year=video.year)
|
||||
self.assertTrue(matches - set([frozenset(subtitle.compute_matches(video)) for subtitle in subtitles]) == set([]))
|
||||
self.assertTrue([Language, ], [subtitle.language for subtitle in subtitles])
|
||||
|
||||
def test_query_episode_0(self):
|
||||
video = EPISODES[0]
|
||||
language = Language('eng')
|
||||
matches = set([frozenset(['episode', 'series', 'season', 'video_codec', 'resolution', 'release_group']),
|
||||
frozenset(['season', 'video_codec', 'episode', 'resolution', 'series'])])
|
||||
with self.Provider() as provider:
|
||||
subtitles = provider.query(language, series=video.series, season=video.season, episode=video.episode)
|
||||
self.assertTrue(matches - set([frozenset(subtitle.compute_matches(video)) for subtitle in subtitles]) == set([]))
|
||||
self.assertTrue([Language, ], [subtitle.language for subtitle in subtitles])
|
||||
|
||||
def test_list_subtitles(self):
|
||||
video = MOVIES[0]
|
||||
languages = set([Language('eng'), Language('fra')])
|
||||
matches = set([frozenset(['video_codec', 'title', 'resolution', 'year']),
|
||||
frozenset(['title', 'resolution', 'year']),
|
||||
frozenset(['video_codec', 'title', 'year']),
|
||||
frozenset(['title', 'year']),
|
||||
frozenset(['video_codec', 'title', 'resolution', 'release_group', 'year']),
|
||||
frozenset(['video_codec', 'title', 'resolution', 'audio_codec', 'year'])])
|
||||
with self.Provider() as provider:
|
||||
subtitles = provider.list_subtitles(video, languages)
|
||||
self.assertTrue(matches - set([frozenset(subtitle.compute_matches(video)) for subtitle in subtitles]) == set([]))
|
||||
self.assertTrue(languages - set([subtitle.language for subtitle in subtitles]) == set([]))
|
||||
|
||||
def test_download_subtitle(self):
|
||||
video = MOVIES[0]
|
||||
languages = set([Language('eng'), Language('fra')])
|
||||
with self.Provider() as provider:
|
||||
subtitles = provider.list_subtitles(video, languages)
|
||||
subtitle_text = provider.download_subtitle(subtitles[0])
|
||||
self.assertTrue(is_valid_subtitle(subtitle_text))
|
||||
|
||||
|
||||
class TheSubDBProviderTestCase(ProviderTestCase):
|
||||
provider_name = 'thesubdb'
|
||||
|
||||
def test_query_episode_0(self):
|
||||
video = EPISODES[0]
|
||||
languages = set([Language('eng'), Language('spa'), Language('por')])
|
||||
matches = set([frozenset(['hash']), ])
|
||||
with self.Provider() as provider:
|
||||
subtitles = provider.query(video.hashes['thesubdb'])
|
||||
self.assertTrue(matches - set([frozenset(subtitle.compute_matches(video)) for subtitle in subtitles]) == set([]))
|
||||
self.assertTrue(languages - set([subtitle.language for subtitle in subtitles]) == set([]))
|
||||
|
||||
def test_query_episode_1(self):
|
||||
video = EPISODES[1]
|
||||
languages = set([Language('eng'), Language('por')])
|
||||
matches = set([frozenset(['hash']), ])
|
||||
with self.Provider() as provider:
|
||||
subtitles = provider.query(video.hashes['thesubdb'])
|
||||
self.assertTrue(matches - set([frozenset(subtitle.compute_matches(video)) for subtitle in subtitles]) == set([]))
|
||||
self.assertTrue(languages - set([subtitle.language for subtitle in subtitles]) == set([]))
|
||||
|
||||
def test_list_subtitles(self):
|
||||
video = MOVIES[0]
|
||||
languages = set([Language('eng'), Language('por')])
|
||||
matches = set([frozenset(['hash']), ])
|
||||
with self.Provider() as provider:
|
||||
subtitles = provider.list_subtitles(video, languages)
|
||||
self.assertTrue(matches - set([frozenset(subtitle.compute_matches(video)) for subtitle in subtitles]) == set([]))
|
||||
self.assertTrue(languages - set([subtitle.language for subtitle in subtitles]) == set([]))
|
||||
|
||||
def test_download_subtitle(self):
|
||||
video = MOVIES[0]
|
||||
languages = (Language('eng'), Language('por'), )
|
||||
with self.Provider() as provider:
|
||||
subtitles = provider.list_subtitles(video, languages)
|
||||
subtitle_text = provider.download_subtitle(subtitles[0])
|
||||
self.assertTrue(is_valid_subtitle(subtitle_text))
|
||||
|
||||
|
||||
class TVsubtitlesProviderTestCase(ProviderTestCase):
|
||||
provider_name = 'tvsubtitles'
|
||||
|
||||
def test_find_show_id(self):
|
||||
with self.Provider() as provider:
|
||||
show_id = provider.find_show_id('The Big Bang')
|
||||
self.assertEqual(show_id, 154)
|
||||
|
||||
def test_find_show_id_ambiguous(self):
|
||||
with self.Provider() as provider:
|
||||
show_id = provider.find_show_id('New Girl')
|
||||
self.assertEqual(show_id, 977)
|
||||
|
||||
def test_find_show_id_no_dots(self):
|
||||
with self.Provider() as provider:
|
||||
show_id = provider.find_show_id('Marvel\'s Agents of S H I E L D')
|
||||
self.assertEqual(show_id, 1340)
|
||||
|
||||
def test_find_show_id_error(self):
|
||||
with self.Provider() as provider:
|
||||
show_id = provider.find_show_id('the big gaming')
|
||||
self.assertEqual(show_id, None)
|
||||
|
||||
def test_find_episode_ids(self):
|
||||
with self.Provider() as provider:
|
||||
episode_ids = provider.find_episode_ids(154, 5)
|
||||
self.assertEqual(set(episode_ids.keys()), set(range(1, 25)))
|
||||
|
||||
def test_query_episode_0(self):
|
||||
video = EPISODES[0]
|
||||
languages = set([Language('fra'), Language('por'), Language('hun'), Language('ron'), Language('eng')])
|
||||
matches = set([frozenset(['series', 'episode', 'resolution', 'season']),
|
||||
frozenset(['series', 'episode', 'season'])])
|
||||
with self.Provider() as provider:
|
||||
subtitles = provider.query(video.series, video.season, video.episode)
|
||||
self.assertTrue(matches - set([frozenset(subtitle.compute_matches(video)) for subtitle in subtitles]) == set([]))
|
||||
self.assertTrue(languages - set([subtitle.language for subtitle in subtitles]) == set([]))
|
||||
|
||||
def test_query_episode_1(self):
|
||||
video = EPISODES[1]
|
||||
languages = set([Language('fra'), Language('ell'), Language('ron'), Language('eng'), Language('hun'),
|
||||
Language('por'), Language('por', 'BR')])
|
||||
matches = set([frozenset(['series', 'episode', 'resolution', 'season']),
|
||||
frozenset(['series', 'episode', 'season', 'video_codec']),
|
||||
frozenset(['series', 'episode', 'season'])])
|
||||
with self.Provider() as provider:
|
||||
subtitles = provider.query(video.series, video.season, video.episode)
|
||||
self.assertTrue(matches - set([frozenset(subtitle.compute_matches(video)) for subtitle in subtitles]) == set([]))
|
||||
self.assertTrue(languages - set([subtitle.language for subtitle in subtitles]) == set([]))
|
||||
|
||||
def test_list_subtitles(self):
|
||||
video = EPISODES[0]
|
||||
languages = set([Language('eng'), Language('fra')])
|
||||
matches = set([frozenset(['series', 'episode', 'resolution', 'season']),
|
||||
frozenset([u'series', u'episode', u'season'])])
|
||||
with self.Provider() as provider:
|
||||
subtitles = provider.list_subtitles(video, languages)
|
||||
self.assertTrue(matches - set([frozenset(subtitle.compute_matches(video)) for subtitle in subtitles]) == set([]))
|
||||
self.assertTrue(languages - set([subtitle.language for subtitle in subtitles]) == set([]))
|
||||
|
||||
def test_download_subtitle(self):
|
||||
video = EPISODES[0]
|
||||
languages = (Language('hun'), )
|
||||
with self.Provider() as provider:
|
||||
subtitles = provider.list_subtitles(video, languages)
|
||||
subtitle_text = provider.download_subtitle(subtitles[0])
|
||||
self.assertTrue(is_valid_subtitle(subtitle_text))
|
||||
|
||||
|
||||
def suite():
|
||||
suite = TestSuite()
|
||||
suite.addTest(TestLoader().loadTestsFromTestCase(Addic7edProviderTestCase))
|
||||
suite.addTest(TestLoader().loadTestsFromTestCase(OpenSubtitlesProviderTestCase))
|
||||
suite.addTest(TestLoader().loadTestsFromTestCase(PodnapisiProviderTestCase))
|
||||
suite.addTest(TestLoader().loadTestsFromTestCase(TheSubDBProviderTestCase))
|
||||
suite.addTest(TestLoader().loadTestsFromTestCase(TVsubtitlesProviderTestCase))
|
||||
return suite
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
TextTestRunner().run(suite())
|
||||
@@ -0,0 +1,175 @@
|
||||
#!/usr/bin/env python
|
||||
# -*- coding: utf-8 -*-
|
||||
from __future__ import unicode_literals
|
||||
import os
|
||||
import shutil
|
||||
from unittest import TestCase, TestSuite, TestLoader, TextTestRunner
|
||||
from babelfish import Language
|
||||
from subliminal import list_subtitles, download_subtitles, download_best_subtitles, scan_video
|
||||
from subliminal.tests.common import MOVIES, EPISODES
|
||||
|
||||
|
||||
TEST_DIR = 'test_data'
|
||||
|
||||
|
||||
class ApiTestCase(TestCase):
|
||||
def setUp(self):
|
||||
os.mkdir(TEST_DIR)
|
||||
|
||||
def tearDown(self):
|
||||
shutil.rmtree(TEST_DIR)
|
||||
|
||||
def test_list_subtitles_movie_0(self):
|
||||
videos = [MOVIES[0]]
|
||||
languages = set([ Language('eng'), ])
|
||||
subtitles = list_subtitles(videos, languages)
|
||||
self.assertEqual(len(subtitles), len(videos))
|
||||
self.assertTrue(len(subtitles[videos[0]]) > 0)
|
||||
|
||||
def test_list_subtitles_movie_0_por_br(self):
|
||||
videos = [MOVIES[0]]
|
||||
languages = set([Language('por', 'BR'), ])
|
||||
subtitles = list_subtitles(videos, languages)
|
||||
self.assertEqual(len(subtitles), len(videos))
|
||||
self.assertTrue(len(subtitles[videos[0]]) > 0)
|
||||
|
||||
def test_list_subtitles_episodes(self):
|
||||
videos = [EPISODES[0], EPISODES[1]]
|
||||
languages = set([Language('eng'), Language('fra')])
|
||||
subtitles = list_subtitles(videos, languages)
|
||||
self.assertEqual(len(subtitles), len(videos))
|
||||
self.assertTrue(len(subtitles[videos[0]]) > 0)
|
||||
|
||||
def test_download_subtitles(self):
|
||||
videos = [EPISODES[0], EPISODES[1]]
|
||||
for video in videos:
|
||||
video.name = os.path.join(TEST_DIR, video.name.split(os.sep)[-1])
|
||||
languages = set([Language('eng'), Language('fra')])
|
||||
subtitles = list_subtitles(videos, languages)
|
||||
download_subtitles(subtitles)
|
||||
for video in videos:
|
||||
self.assertTrue(os.path.exists(os.path.splitext(video.name)[0] + '.en.srt'))
|
||||
self.assertTrue(os.path.exists(os.path.splitext(video.name)[0] + '.fr.srt'))
|
||||
|
||||
def test_download_subtitles_single(self):
|
||||
videos = [EPISODES[0], EPISODES[1]]
|
||||
for video in videos:
|
||||
video.name = os.path.join(TEST_DIR, video.name.split(os.sep)[-1])
|
||||
languages = set([Language('eng'), Language('fra')])
|
||||
subtitles = list_subtitles(videos, languages)
|
||||
download_subtitles(subtitles, single=True)
|
||||
for video in videos:
|
||||
self.assertTrue(os.path.exists(os.path.splitext(video.name)[0] + '.srt'))
|
||||
|
||||
def test_download_best_subtitles(self):
|
||||
videos = [EPISODES[0], EPISODES[1]]
|
||||
for video in videos:
|
||||
video.name = os.path.join(TEST_DIR, video.name.split(os.sep)[-1])
|
||||
languages = set([Language('eng'), Language('fra')])
|
||||
subtitles = download_best_subtitles(videos, languages)
|
||||
for video in videos:
|
||||
self.assertTrue(video in subtitles)
|
||||
self.assertTrue(len(subtitles[video]) == 2)
|
||||
self.assertTrue(os.path.exists(os.path.splitext(video.name)[0] + '.en.srt'))
|
||||
self.assertTrue(os.path.exists(os.path.splitext(video.name)[0] + '.fr.srt'))
|
||||
|
||||
def test_download_best_subtitles_single(self):
|
||||
videos = [EPISODES[0], EPISODES[1]]
|
||||
for video in videos:
|
||||
video.name = os.path.join(TEST_DIR, video.name.split(os.sep)[-1])
|
||||
languages = set([Language('eng'), Language('fra')])
|
||||
subtitles = download_best_subtitles(videos, languages, single=True)
|
||||
for video in videos:
|
||||
self.assertTrue(video in subtitles)
|
||||
self.assertEqual(len(subtitles[video]), 1)
|
||||
self.assertTrue(os.path.exists(os.path.splitext(video.name)[0] + '.srt'))
|
||||
|
||||
def test_download_best_subtitles_min_score(self):
|
||||
videos = [MOVIES[0]]
|
||||
for video in videos:
|
||||
video.name = os.path.join(TEST_DIR, video.name.split(os.sep)[-1])
|
||||
languages = set([Language('eng'), Language('fra')])
|
||||
subtitles = download_best_subtitles(videos, languages, min_score=1000)
|
||||
self.assertEqual(len(subtitles), 0)
|
||||
|
||||
def test_download_best_subtitles_hearing_impaired(self):
|
||||
videos = [MOVIES[0]]
|
||||
for video in videos:
|
||||
video.name = os.path.join(TEST_DIR, video.name.split(os.sep)[-1])
|
||||
languages = set([Language('eng'), ])
|
||||
subtitles = download_best_subtitles(videos, languages, hearing_impaired=True)
|
||||
self.assertTrue(subtitles[videos[0]][0].hearing_impaired)
|
||||
|
||||
|
||||
class VideoTestCase(TestCase):
|
||||
def setUp(self):
|
||||
os.mkdir(TEST_DIR)
|
||||
for video in MOVIES + EPISODES:
|
||||
open(os.path.join(TEST_DIR, os.path.split(video.name)[1]), 'w').close()
|
||||
|
||||
def tearDown(self):
|
||||
shutil.rmtree(TEST_DIR)
|
||||
|
||||
def test_scan_video_movie(self):
|
||||
video = MOVIES[0]
|
||||
scanned_video = scan_video(os.path.join(TEST_DIR, os.path.split(video.name)[1]))
|
||||
self.assertEqual(scanned_video.name, os.path.join(TEST_DIR, os.path.split(video.name)[1]))
|
||||
self.assertEqual(scanned_video.title.lower(), video.title.lower())
|
||||
self.assertEqual(scanned_video.year, video.year)
|
||||
self.assertEqual(scanned_video.video_codec, video.video_codec)
|
||||
self.assertEqual(scanned_video.resolution, video.resolution)
|
||||
self.assertEqual(scanned_video.release_group, video.release_group)
|
||||
self.assertEqual(scanned_video.subtitle_languages, set())
|
||||
self.assertEqual(scanned_video.hashes, {})
|
||||
self.assertEqual(scanned_video.audio_codec, None)
|
||||
self.assertEqual(scanned_video.imdb_id, None)
|
||||
self.assertEqual(scanned_video.size, 0)
|
||||
|
||||
def test_scan_video_episode(self):
|
||||
video = EPISODES[0]
|
||||
scanned_video = scan_video(os.path.join(TEST_DIR, os.path.split(video.name)[1]))
|
||||
self.assertEqual(scanned_video.name, os.path.join(TEST_DIR, os.path.split(video.name)[1]))
|
||||
self.assertEqual(scanned_video.series, video.series)
|
||||
self.assertEqual(scanned_video.season, video.season)
|
||||
self.assertEqual(scanned_video.episode, video.episode)
|
||||
self.assertEqual(scanned_video.video_codec, video.video_codec)
|
||||
self.assertEqual(scanned_video.resolution, video.resolution)
|
||||
self.assertEqual(scanned_video.release_group, video.release_group)
|
||||
self.assertEqual(scanned_video.subtitle_languages, set())
|
||||
self.assertEqual(scanned_video.hashes, {})
|
||||
self.assertEqual(scanned_video.title, None)
|
||||
self.assertEqual(scanned_video.tvdb_id, None)
|
||||
self.assertEqual(scanned_video.imdb_id, None)
|
||||
self.assertEqual(scanned_video.audio_codec, None)
|
||||
self.assertEqual(scanned_video.size, 0)
|
||||
|
||||
def test_scan_video_subtitle_language_und(self):
|
||||
video = EPISODES[0]
|
||||
open(os.path.join(TEST_DIR, os.path.splitext(os.path.split(video.name)[1])[0]) + '.srt', 'w').close()
|
||||
scanned_video = scan_video(os.path.join(TEST_DIR, os.path.split(video.name)[1]))
|
||||
self.assertEqual(scanned_video.subtitle_languages, set([Language('und'), ]))
|
||||
|
||||
def test_scan_video_subtitles_language_eng(self):
|
||||
video = EPISODES[0]
|
||||
open(os.path.join(TEST_DIR, os.path.splitext(os.path.split(video.name)[1])[0]) + '.en.srt', 'w').close()
|
||||
scanned_video = scan_video(os.path.join(TEST_DIR, os.path.split(video.name)[1]))
|
||||
self.assertEqual(scanned_video.subtitle_languages, set([Language('eng'), ]))
|
||||
|
||||
def test_scan_video_subtitles_languages(self):
|
||||
video = EPISODES[0]
|
||||
open(os.path.join(TEST_DIR, os.path.splitext(os.path.split(video.name)[1])[0]) + '.en.srt', 'w').close()
|
||||
open(os.path.join(TEST_DIR, os.path.splitext(os.path.split(video.name)[1])[0]) + '.fr.srt', 'w').close()
|
||||
open(os.path.join(TEST_DIR, os.path.splitext(os.path.split(video.name)[1])[0]) + '.srt', 'w').close()
|
||||
scanned_video = scan_video(os.path.join(TEST_DIR, os.path.split(video.name)[1]))
|
||||
self.assertEqual(scanned_video.subtitle_languages, set([Language('eng'), Language('fra'), Language('und')]))
|
||||
|
||||
|
||||
def suite():
|
||||
suite = TestSuite()
|
||||
suite.addTest(TestLoader().loadTestsFromTestCase(ApiTestCase))
|
||||
suite.addTest(TestLoader().loadTestsFromTestCase(VideoTestCase))
|
||||
return suite
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
TextTestRunner().run(suite())
|
||||
@@ -1,22 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
#
|
||||
# Subliminal - Subtitles, faster than your thoughts
|
||||
# Copyright (c) 2011 Antoine Bertin <diaoulael@gmail.com>
|
||||
#
|
||||
# This file is part of Subliminal.
|
||||
#
|
||||
# Subliminal is free software; you can redistribute it and/or modify it under
|
||||
# the terms of the Lesser GNU General Public License as published by
|
||||
# the Free Software Foundation; either version 3 of the License, or
|
||||
# (at your option) any later version.
|
||||
#
|
||||
# Subliminal is distributed in the hope that it will be useful,
|
||||
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
# Lesser GNU General Public License for more details.
|
||||
#
|
||||
# You should have received a copy of the Lesser GNU General Public License
|
||||
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
#
|
||||
|
||||
__version__ = '0.4'
|
||||
@@ -0,0 +1,416 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
from __future__ import unicode_literals
|
||||
import datetime
|
||||
import hashlib
|
||||
import logging
|
||||
import os
|
||||
import struct
|
||||
import babelfish
|
||||
import enzyme
|
||||
import guessit
|
||||
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
#: Video extensions
|
||||
VIDEO_EXTENSIONS = ('.3g2', '.3gp', '.3gp2', '.3gpp', '.60d', '.ajp', '.asf', '.asx', '.avchd', '.avi', '.bik',
|
||||
'.bix', '.box', '.cam', '.dat', '.divx', '.dmf', '.dv', '.dvr-ms', '.evo', '.flc', '.fli',
|
||||
'.flic', '.flv', '.flx', '.gvi', '.gvp', '.h264', '.m1v', '.m2p', '.m2ts', '.m2v', '.m4e',
|
||||
'.m4v', '.mjp', '.mjpeg', '.mjpg', '.mkv', '.moov', '.mov', '.movhd', '.movie', '.movx', '.mp4',
|
||||
'.mpe', '.mpeg', '.mpg', '.mpv', '.mpv2', '.mxf', '.nsv', '.nut', '.ogg', '.ogm', '.omf', '.ps',
|
||||
'.qt', '.ram', '.rm', '.rmvb', '.swf', '.ts', '.vfw', '.vid', '.video', '.viv', '.vivo', '.vob',
|
||||
'.vro', '.wm', '.wmv', '.wmx', '.wrap', '.wvx', '.wx', '.x264', '.xvid')
|
||||
|
||||
#: Subtitle extensions
|
||||
SUBTITLE_EXTENSIONS = ('.srt', '.sub', '.smi', '.txt', '.ssa', '.ass', '.mpl')
|
||||
|
||||
|
||||
class Video(object):
|
||||
"""Base class for videos
|
||||
|
||||
Represent a video, existing or not, with various properties that defines it.
|
||||
Each property has an associated score based on equations that are described in
|
||||
subclasses.
|
||||
|
||||
:param string name: name or path of the video
|
||||
:param string release_group: release group of the video
|
||||
:param string resolution: screen size of the video stream (480p, 720p, 1080p or 1080i)
|
||||
:param string video_codec: codec of the video stream
|
||||
:param string audio_codec: codec of the main audio stream
|
||||
:param int imdb_id: IMDb id of the video
|
||||
:param dict hashes: hashes of the video file by provider names
|
||||
:param int size: byte size of the video file
|
||||
:param set subtitle_languages: existing subtitle languages
|
||||
|
||||
"""
|
||||
scores = {}
|
||||
|
||||
def __init__(self, name, release_group=None, resolution=None, video_codec=None, audio_codec=None, imdb_id=None,
|
||||
hashes=None, size=None, subtitle_languages=None):
|
||||
self.name = name
|
||||
self.release_group = release_group
|
||||
self.resolution = resolution
|
||||
self.video_codec = video_codec
|
||||
self.audio_codec = audio_codec
|
||||
self.imdb_id = imdb_id
|
||||
self.hashes = hashes or {}
|
||||
self.size = size
|
||||
self.subtitle_languages = subtitle_languages or set()
|
||||
|
||||
@classmethod
|
||||
def fromguess(cls, name, guess):
|
||||
if guess['type'] == 'episode':
|
||||
return Episode.fromguess(name, guess)
|
||||
if guess['type'] == 'movie':
|
||||
return Movie.fromguess(name, guess)
|
||||
raise ValueError('The guess must be an episode or a movie guess')
|
||||
|
||||
def __repr__(self):
|
||||
return '<%s [%r]>' % (self.__class__.__name__, self.name)
|
||||
|
||||
def __hash__(self):
|
||||
return hash(self.name)
|
||||
|
||||
def __eq__(self, other):
|
||||
return self.__class__.__name__ == other.__class__.__name__\
|
||||
and self.name == other.name
|
||||
|
||||
|
||||
class Episode(Video):
|
||||
"""Episode :class:`Video`
|
||||
|
||||
Scores are defined by a set of equations, see :func:`~subliminal.score.get_episode_equations`
|
||||
|
||||
:param string series: series of the episode
|
||||
:param int season: season number of the episode
|
||||
:param int episode: episode number of the episode
|
||||
:param string title: title of the episode
|
||||
:param int tvdb_id: TheTVDB id of the episode
|
||||
|
||||
"""
|
||||
scores = {'title': 12, 'video_codec': 2, 'imdb_id': 35, 'audio_codec': 1, 'tvdb_id': 23, 'resolution': 2,
|
||||
'season': 6, 'release_group': 6, 'series': 23, 'episode': 6, 'hash': 46}
|
||||
|
||||
def __init__(self, name, series, season, episode, release_group=None, resolution=None, video_codec=None,
|
||||
audio_codec=None, imdb_id=None, hashes=None, size=None, subtitle_languages=None, title=None,
|
||||
tvdb_id=None):
|
||||
super(Episode, self).__init__(name, release_group, resolution, video_codec, audio_codec, imdb_id, hashes,
|
||||
size, subtitle_languages)
|
||||
self.series = series
|
||||
self.season = season
|
||||
self.episode = episode
|
||||
self.title = title
|
||||
self.tvdb_id = tvdb_id
|
||||
|
||||
@classmethod
|
||||
def fromguess(cls, name, guess):
|
||||
if guess['type'] != 'episode':
|
||||
raise ValueError('The guess must be an episode guess')
|
||||
if 'series' not in guess or 'season' not in guess or 'episodeNumber' not in guess:
|
||||
raise ValueError('Insufficient data to process the guess')
|
||||
return cls(name, guess['series'], guess['season'], guess['episodeNumber'],
|
||||
release_group=guess.get('releaseGroup'), resolution=guess.get('screenSize'),
|
||||
video_codec=guess.get('videoCodec'), audio_codec=guess.get('audioCodec'),
|
||||
title=guess.get('title'))
|
||||
|
||||
def __repr__(self):
|
||||
return '<%s [%r, %rx%r]>' % (self.__class__.__name__, self.series, self.season, self.episode)
|
||||
|
||||
def __hash__(self):
|
||||
return hash((
|
||||
self.series,
|
||||
self.season,
|
||||
self.episode,
|
||||
))
|
||||
|
||||
def __eq__(self, other):
|
||||
return self.__class__.__name__ == other.__class__.__name__\
|
||||
and self.series == other.series\
|
||||
and self.season == other.season\
|
||||
and self.episode == other.episode
|
||||
|
||||
class Movie(Video):
|
||||
"""Movie :class:`Video`
|
||||
|
||||
Scores are defined by a set of equations, see :func:`~subliminal.score.get_movie_equations`
|
||||
|
||||
:param string title: title of the movie
|
||||
:param int year: year of the movie
|
||||
|
||||
"""
|
||||
scores = {'title': 13, 'video_codec': 2, 'resolution': 2, 'audio_codec': 1, 'year': 7, 'imdb_id': 31,
|
||||
'release_group': 6, 'hash': 31}
|
||||
|
||||
def __init__(self, name, title, release_group=None, resolution=None, video_codec=None, audio_codec=None,
|
||||
imdb_id=None, hashes=None, size=None, subtitle_languages=None, year=None):
|
||||
super(Movie, self).__init__(name, release_group, resolution, video_codec, audio_codec, imdb_id, hashes,
|
||||
size, subtitle_languages)
|
||||
self.title = title
|
||||
self.year = year
|
||||
|
||||
@classmethod
|
||||
def fromguess(cls, name, guess):
|
||||
if guess['type'] != 'movie':
|
||||
raise ValueError('The guess must be a movie guess')
|
||||
if 'title' not in guess:
|
||||
raise ValueError('Insufficient data to process the guess')
|
||||
return cls(name, guess['title'], release_group=guess.get('releaseGroup'), resolution=guess.get('screenSize'),
|
||||
video_codec=guess.get('videoCodec'), audio_codec=guess.get('audioCodec'),
|
||||
year=guess.get('year'))
|
||||
|
||||
def __repr__(self):
|
||||
if self.year is None:
|
||||
return '<%s [%r]>' % (self.__class__.__name__, self.title)
|
||||
return '<%s [%r, %r]>' % (self.__class__.__name__, self.title, self.year)
|
||||
|
||||
def __hash__(self):
|
||||
if self.year is None:
|
||||
return hash((
|
||||
self.title,
|
||||
self.year,
|
||||
))
|
||||
return hash(self.title)
|
||||
|
||||
def __eq__(self, other):
|
||||
return self.__class__.__name__ == other.__class__.__name__\
|
||||
and self.title == other.title\
|
||||
and self.year == other.year
|
||||
|
||||
def scan_subtitle_languages(path):
|
||||
"""Search for subtitles with alpha2 extension from a video `path` and return their language
|
||||
|
||||
:param string path: path to the video
|
||||
:return: found subtitle languages
|
||||
:rtype: set
|
||||
|
||||
"""
|
||||
language_extensions = tuple('.' + c for c in babelfish.language_converters['alpha2'].codes)
|
||||
dirpath, filename = os.path.split(path)
|
||||
subtitles = set()
|
||||
for p in os.listdir(dirpath):
|
||||
if not isinstance(p, bytes) and p.startswith(os.path.splitext(filename)[0]) and p.endswith(SUBTITLE_EXTENSIONS):
|
||||
if os.path.splitext(p)[0].endswith(language_extensions):
|
||||
subtitles.add(babelfish.Language.fromalpha2(os.path.splitext(p)[0][-2:]))
|
||||
else:
|
||||
subtitles.add(babelfish.Language('und'))
|
||||
logger.debug('Found subtitles %r', subtitles)
|
||||
return subtitles
|
||||
|
||||
|
||||
def scan_video(path, subtitles=True, embedded_subtitles=True, video=None):
|
||||
"""Scan a video and its subtitle languages from a video `path`
|
||||
|
||||
:param string path: absolute path to the video
|
||||
:param bool subtitles: scan for subtitles with the same name
|
||||
:param bool embedded_subtitles: scan for embedded subtitles
|
||||
:parm :class:`Video`: optionally specify a video if you've already detected on
|
||||
by other means.
|
||||
:return: the scanned video
|
||||
:rtype: :class:`Video`
|
||||
:raise: ValueError if cannot guess enough information from the path
|
||||
|
||||
"""
|
||||
dirpath, filename = os.path.split(path)
|
||||
logger.info('Scanning video %r in %r', filename, dirpath)
|
||||
if not video:
|
||||
video = Video.fromguess(
|
||||
path,
|
||||
guessit.guess_file_info(path, info=['filename']),
|
||||
)
|
||||
|
||||
video.size = os.path.getsize(path)
|
||||
if video.size > 10485760:
|
||||
logger.debug('Size is %d', video.size)
|
||||
video.hashes['opensubtitles'] = hash_opensubtitles(path)
|
||||
video.hashes['thesubdb'] = hash_thesubdb(path)
|
||||
logger.debug('Computed hashes %r', video.hashes)
|
||||
else:
|
||||
logger.warning('Size is lower than 10MB: hashes not computed')
|
||||
if subtitles:
|
||||
video.subtitle_languages |= scan_subtitle_languages(path)
|
||||
# enzyme
|
||||
try:
|
||||
if filename.endswith('.mkv'):
|
||||
with open(path, 'rb') as f:
|
||||
mkv = enzyme.MKV(f)
|
||||
if mkv.video_tracks:
|
||||
video_track = mkv.video_tracks[0]
|
||||
# resolution
|
||||
if video_track.height in (480, 720, 1080):
|
||||
if video_track.interlaced:
|
||||
video.resolution = '%di' % video_track.height
|
||||
logger.debug('Found resolution %s with enzyme', video.resolution)
|
||||
else:
|
||||
video.resolution = '%dp' % video_track.height
|
||||
logger.debug('Found resolution %s with enzyme', video.resolution)
|
||||
# video codec
|
||||
if video_track.codec_id == 'V_MPEG4/ISO/AVC':
|
||||
video.video_codec = 'h264'
|
||||
logger.debug('Found video_codec %s with enzyme', video.video_codec)
|
||||
elif video_track.codec_id == 'V_MPEG4/ISO/SP':
|
||||
video.video_codec = 'DivX'
|
||||
logger.debug('Found video_codec %s with enzyme', video.video_codec)
|
||||
elif video_track.codec_id == 'V_MPEG4/ISO/ASP':
|
||||
video.video_codec = 'XviD'
|
||||
logger.debug('Found video_codec %s with enzyme', video.video_codec)
|
||||
else:
|
||||
logger.warning('MKV has no video track')
|
||||
if mkv.audio_tracks:
|
||||
audio_track = mkv.audio_tracks[0]
|
||||
# audio codec
|
||||
if audio_track.codec_id == 'A_AC3':
|
||||
video.audio_codec = 'AC3'
|
||||
logger.debug('Found audio_codec %s with enzyme', video.audio_codec)
|
||||
elif audio_track.codec_id == 'A_DTS':
|
||||
video.audio_codec = 'DTS'
|
||||
logger.debug('Found audio_codec %s with enzyme', video.audio_codec)
|
||||
elif audio_track.codec_id == 'A_AAC':
|
||||
video.audio_codec = 'AAC'
|
||||
logger.debug('Found audio_codec %s with enzyme', video.audio_codec)
|
||||
else:
|
||||
logger.warning('MKV has no audio track')
|
||||
if mkv.subtitle_tracks:
|
||||
# embedded subtitles
|
||||
if embedded_subtitles:
|
||||
embedded_subtitle_languages = set()
|
||||
for st in mkv.subtitle_tracks:
|
||||
if st.language:
|
||||
try:
|
||||
embedded_subtitle_languages.add(babelfish.Language.fromalpha3b(st.language))
|
||||
except babelfish.Error:
|
||||
logger.error('Embedded subtitle track language %r is not a valid language', st.language)
|
||||
embedded_subtitle_languages.add(babelfish.Language('und'))
|
||||
elif st.name:
|
||||
try:
|
||||
embedded_subtitle_languages.add(babelfish.Language.fromname(st.name))
|
||||
except babelfish.Error:
|
||||
logger.error('Embedded subtitle track name %r is not a valid language', st.name)
|
||||
embedded_subtitle_languages.add(babelfish.Language('und'))
|
||||
else:
|
||||
embedded_subtitle_languages.add(babelfish.Language('und'))
|
||||
logger.debug('Found embedded subtitle %r with enzyme', embedded_subtitle_languages)
|
||||
video.subtitle_languages |= embedded_subtitle_languages
|
||||
else:
|
||||
logger.debug('MKV has no subtitle track')
|
||||
except enzyme.Error:
|
||||
logger.error('Parsing video metadata with enzyme failed')
|
||||
return video
|
||||
|
||||
|
||||
def scan_videos(paths, subtitles=True, embedded_subtitles=True, age=None):
|
||||
"""Scan `paths` for videos and their subtitle languages
|
||||
|
||||
:params paths: absolute paths to scan for videos
|
||||
:type paths: list of string
|
||||
:param bool subtitles: scan for subtitles with the same name
|
||||
:param bool embedded_subtitles: scan for embedded subtitles
|
||||
:param age: age of the video, if any
|
||||
:type age: datetime.timedelta or None
|
||||
:return: the scanned videos
|
||||
:rtype: list of :class:`Video`
|
||||
|
||||
"""
|
||||
videos = []
|
||||
# scan files
|
||||
for filepath in [p for p in paths if os.path.isfile(p)]:
|
||||
if age and datetime.datetime.now() - datetime.datetime.fromtimestamp(os.path.getmtime(filepath)) > age:
|
||||
logger.info('Skipping video %r: older than %r', filepath, age)
|
||||
continue
|
||||
try:
|
||||
videos.append(scan_video(filepath, subtitles, embedded_subtitles))
|
||||
except ValueError as e:
|
||||
logger.error('Skipping video: %s', e)
|
||||
continue
|
||||
# scan directories
|
||||
for path in [p for p in paths if os.path.isdir(p)]:
|
||||
logger.info('Scanning directory %r', path)
|
||||
for dirpath, dirnames, filenames in os.walk(path):
|
||||
# skip badly encoded directories
|
||||
if isinstance(dirpath, bytes):
|
||||
logger.error('Skipping badly encoded directory %r', dirpath.decode('utf-8', 'replace'))
|
||||
continue
|
||||
# skip badly encoded and hidden sub directories
|
||||
for dirname in list(dirnames):
|
||||
if isinstance(dirname, bytes):
|
||||
logger.error('Skipping badly encoded dirname %r in %r', dirname.decode('utf-8', 'replace'),
|
||||
dirpath)
|
||||
dirnames.remove(dirname)
|
||||
elif dirname.startswith('.'):
|
||||
logger.debug('Skipping hidden dirname %r in %r', dirname, dirpath)
|
||||
dirnames.remove(dirname)
|
||||
# scan for videos
|
||||
for filename in filenames:
|
||||
# skip badly encoded files
|
||||
if isinstance(filename, bytes):
|
||||
logger.error('Skipping badly encoded filename %r in %r', filename.decode('utf-8', 'replace'),
|
||||
dirpath)
|
||||
continue
|
||||
# filter videos
|
||||
if not filename.endswith(VIDEO_EXTENSIONS):
|
||||
continue
|
||||
# skip hidden files
|
||||
if filename.startswith('.'):
|
||||
logger.debug('Skipping hidden filename %r in %r', filename, dirpath)
|
||||
continue
|
||||
filepath = os.path.join(dirpath, filename)
|
||||
# skip links
|
||||
if os.path.islink(filepath):
|
||||
logger.debug('Skipping link %r in %r', filename, dirpath)
|
||||
continue
|
||||
if age and datetime.datetime.now() - datetime.datetime.fromtimestamp(os.path.getmtime(filepath)) > age:
|
||||
logger.info('Skipping video %r: older than %r', filepath, age)
|
||||
continue
|
||||
try:
|
||||
video = scan_video(filepath, subtitles, embedded_subtitles)
|
||||
except ValueError as e:
|
||||
logger.error('Skipping video: %s', e)
|
||||
continue
|
||||
videos.append(video)
|
||||
return videos
|
||||
|
||||
|
||||
def hash_opensubtitles(video_path):
|
||||
"""Compute a hash using OpenSubtitles' algorithm
|
||||
|
||||
:param string video_path: path of the video
|
||||
:return: the hash
|
||||
:rtype: string
|
||||
|
||||
"""
|
||||
bytesize = struct.calcsize(b'q')
|
||||
with open(video_path, 'rb') as f:
|
||||
filesize = os.path.getsize(video_path)
|
||||
filehash = filesize
|
||||
if filesize < 65536 * 2:
|
||||
return None
|
||||
for _ in range(65536 / bytesize):
|
||||
filebuffer = f.read(bytesize)
|
||||
(l_value,) = struct.unpack(b'q', filebuffer)
|
||||
filehash += l_value
|
||||
filehash = filehash & 0xFFFFFFFFFFFFFFFF # to remain as 64bit number
|
||||
f.seek(max(0, filesize - 65536), 0)
|
||||
for _ in range(65536 / bytesize):
|
||||
filebuffer = f.read(bytesize)
|
||||
(l_value,) = struct.unpack(b'q', filebuffer)
|
||||
filehash += l_value
|
||||
filehash = filehash & 0xFFFFFFFFFFFFFFFF
|
||||
returnedhash = '%016x' % filehash
|
||||
return returnedhash
|
||||
|
||||
|
||||
def hash_thesubdb(video_path):
|
||||
"""Compute a hash using TheSubDB's algorithm
|
||||
|
||||
:param string video_path: path of the video
|
||||
:return: the hash
|
||||
:rtype: string
|
||||
|
||||
"""
|
||||
readsize = 64 * 1024
|
||||
if os.path.getsize(video_path) < readsize:
|
||||
return None
|
||||
with open(video_path, 'rb') as f:
|
||||
data = f.read(readsize)
|
||||
f.seek(-readsize, os.SEEK_END)
|
||||
data += f.read(readsize)
|
||||
return hashlib.md5(data).hexdigest().decode('ascii')
|
||||
@@ -1,152 +0,0 @@
|
||||
#!/usr/bin/env python
|
||||
# -*- coding: utf-8 -*-
|
||||
#
|
||||
# Subliminal - Subtitles, faster than your thoughts
|
||||
# Copyright (c) 2011 Antoine Bertin <diaoulael@gmail.com>
|
||||
#
|
||||
# This file is part of Subliminal.
|
||||
#
|
||||
# Subliminal is free software; you can redistribute it and/or modify it under
|
||||
# the terms of the Lesser GNU General Public License as published by
|
||||
# the Free Software Foundation; either version 3 of the License, or
|
||||
# (at your option) any later version.
|
||||
#
|
||||
# Subliminal is distributed in the hope that it will be useful,
|
||||
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
# Lesser GNU General Public License for more details.
|
||||
#
|
||||
# You should have received a copy of the Lesser GNU General Public License
|
||||
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
#
|
||||
|
||||
import unittest
|
||||
import logging
|
||||
import os
|
||||
|
||||
|
||||
logging.basicConfig(level=logging.DEBUG, format='%(name)-24s %(levelname)-8s %(message)s')
|
||||
test_folder = u'/your/path/here/videos/'
|
||||
test_file = u'/your/path/here/videos/the.big.bang.theory.s04e01.hdtv.xvid-fqm.avi'
|
||||
cache_dir = u'/tmp/sublicache'
|
||||
if not os.path.exists(cache_dir):
|
||||
os.mkdir(cache_dir)
|
||||
|
||||
|
||||
class Addic7edTestCase(unittest.TestCase):
|
||||
def setUp(self):
|
||||
from subliminal.plugins import Addic7ed
|
||||
self.config = {'multi': True, 'cache_dir': cache_dir, 'files_mode': -1}
|
||||
self.plugin = Addic7ed(self.config)
|
||||
self.languages = set(['en', 'fr'])
|
||||
|
||||
def test_list(self):
|
||||
list = self.plugin.list(test_file, self.languages)
|
||||
assert list
|
||||
|
||||
def test_download(self):
|
||||
subtitle = self.plugin.list(test_file, self.languages)[0]
|
||||
if os.path.exists(subtitle.path):
|
||||
os.remove(subtitle.path)
|
||||
download = self.plugin.download(subtitle)
|
||||
assert download
|
||||
|
||||
|
||||
class BierDopjeTestCase(unittest.TestCase):
|
||||
def setUp(self):
|
||||
from subliminal.plugins import BierDopje
|
||||
self.config = {'multi': True, 'cache_dir': cache_dir, 'files_mode': -1}
|
||||
self.plugin = BierDopje(self.config)
|
||||
self.languages = set(['en', 'fr'])
|
||||
|
||||
def test_list(self):
|
||||
list = self.plugin.list(test_file, self.languages)
|
||||
assert list
|
||||
|
||||
def test_download(self):
|
||||
subtitle = self.plugin.list(test_file, self.languages)[0]
|
||||
if os.path.exists(subtitle.path):
|
||||
os.remove(subtitle.path)
|
||||
download = self.plugin.download(subtitle)
|
||||
assert download
|
||||
|
||||
|
||||
class OpenSubtitlesTestCase(unittest.TestCase):
|
||||
def setUp(self):
|
||||
from subliminal.plugins import OpenSubtitles
|
||||
self.config = {'multi': True, 'cache_dir': cache_dir, 'files_mode': -1}
|
||||
self.plugin = OpenSubtitles(self.config)
|
||||
self.languages = set(['en', 'fr'])
|
||||
|
||||
def test_list(self):
|
||||
list = self.plugin.list(test_file, self.languages)
|
||||
assert list
|
||||
|
||||
def test_download(self):
|
||||
subtitle = self.plugin.list(test_file, self.languages)[0]
|
||||
if os.path.exists(subtitle.path):
|
||||
os.remove(subtitle.path)
|
||||
download = self.plugin.download(subtitle)
|
||||
assert download
|
||||
|
||||
|
||||
class SubsWikiTestCase(unittest.TestCase):
|
||||
def setUp(self):
|
||||
from subliminal.plugins import SubsWiki
|
||||
self.config = {'multi': True, 'cache_dir': cache_dir, 'files_mode': -1}
|
||||
self.plugin = SubsWiki(self.config)
|
||||
self.languages = set(['en', 'fr', 'es', 'pt'])
|
||||
|
||||
def test_list(self):
|
||||
list = self.plugin.list(test_file, self.languages)
|
||||
assert list
|
||||
|
||||
def test_download(self):
|
||||
subtitle = self.plugin.list(test_file, self.languages)[0]
|
||||
if os.path.exists(subtitle.path):
|
||||
os.remove(subtitle.path)
|
||||
download = self.plugin.download(subtitle)
|
||||
assert download
|
||||
|
||||
|
||||
class SubtitulosTestCase(unittest.TestCase):
|
||||
def setUp(self):
|
||||
from subliminal.plugins import Subtitulos
|
||||
self.config = {'multi': True, 'cache_dir': cache_dir, 'files_mode': -1}
|
||||
self.plugin = Subtitulos(self.config)
|
||||
self.languages = set(['en', 'fr', 'es', 'pt'])
|
||||
|
||||
def test_list(self):
|
||||
list = self.plugin.list(test_file, self.languages)
|
||||
assert list
|
||||
|
||||
def test_download(self):
|
||||
subtitle = self.plugin.list(test_file, self.languages)[0]
|
||||
if os.path.exists(subtitle.path):
|
||||
os.remove(subtitle.path)
|
||||
download = self.plugin.download(subtitle)
|
||||
assert download
|
||||
|
||||
|
||||
class TheSubDBTestCase(unittest.TestCase):
|
||||
def setUp(self):
|
||||
from subliminal.plugins import TheSubDB
|
||||
self.config = {'multi': True, 'cache_dir': cache_dir, 'files_mode': -1}
|
||||
self.plugin = TheSubDB(self.config)
|
||||
self.languages = set(['en', 'fr', 'es', 'pt'])
|
||||
|
||||
def test_list(self):
|
||||
list = self.plugin.list(test_file, self.languages)
|
||||
assert list
|
||||
|
||||
def test_download(self):
|
||||
subtitle = self.plugin.list(test_file, self.languages)[0]
|
||||
if os.path.exists(subtitle.path):
|
||||
os.remove(subtitle.path)
|
||||
download = self.plugin.download(subtitle)
|
||||
assert download
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
|
||||
@@ -1,90 +0,0 @@
|
||||
#!/usr/bin/env python
|
||||
# -*- coding: utf-8 -*-
|
||||
#
|
||||
# Subliminal - Subtitles, faster than your thoughts
|
||||
# Copyright (c) 2011 Antoine Bertin <diaoulael@gmail.com>
|
||||
#
|
||||
# This file is part of Subliminal.
|
||||
#
|
||||
# Subliminal is free software; you can redistribute it and/or modify it under
|
||||
# the terms of the Lesser GNU General Public License as published by
|
||||
# the Free Software Foundation; either version 3 of the License, or
|
||||
# (at your option) any later version.
|
||||
#
|
||||
# Subliminal is distributed in the hope that it will be useful,
|
||||
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
# Lesser GNU General Public License for more details.
|
||||
#
|
||||
# You should have received a copy of the Lesser GNU General Public License
|
||||
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
#
|
||||
|
||||
import unittest
|
||||
import logging
|
||||
import os
|
||||
import subliminal
|
||||
|
||||
|
||||
logging.basicConfig(level=logging.DEBUG, format='%(name)-24s %(levelname)-8s %(message)s')
|
||||
test_folder = u'/your/path/here/videos/'
|
||||
test_file = u'/your/path/here/videos/the.big.bang.theory.s04e01.hdtv.xvid-fqm.avi'
|
||||
cache_dir = u'/tmp/sublicache'
|
||||
if not os.path.exists(cache_dir):
|
||||
os.mkdir(cache_dir)
|
||||
|
||||
|
||||
class FileTestCase(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.subli = subliminal.Subliminal(cache_dir=cache_dir, workers=4, multi=False, force=True, max_depth=3, files_mode=-1)
|
||||
self.subli.languages = ['en', 'fr', 'es', 'pt']
|
||||
self.subli.plugins = subliminal.PLUGINS
|
||||
|
||||
def test_list(self):
|
||||
results = self.subli.listSubtitles(test_file)
|
||||
self.assertTrue(len(results) > 0)
|
||||
|
||||
def test_download(self):
|
||||
results = self.subli.downloadSubtitles(test_file)
|
||||
self.assertTrue(len(results) > 0)
|
||||
|
||||
|
||||
class ErrorTestCase(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.subli = subliminal.Subliminal(cache_dir=cache_dir, workers=4, multi=False, force=True, max_depth=3, files_mode=-1)
|
||||
|
||||
def test_language(self):
|
||||
with self.assertRaises(subliminal.classes.LanguageError):
|
||||
self.subli.languages = ['en', 'fr', 'zz', 'pt']
|
||||
|
||||
def test_plugin(self):
|
||||
with self.assertRaises(subliminal.classes.PluginError):
|
||||
self.subli.plugins = ['WrongPlugin']
|
||||
|
||||
|
||||
class PriorityQueueTestCase(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.subli = subliminal.Subliminal(cache_dir=cache_dir, workers=4, multi=False, force=True, max_depth=3, files_mode=-1)
|
||||
self.subli.languages = ['en', 'fr', 'es', 'pt']
|
||||
self.subli.plugins = subliminal.PLUGINS
|
||||
|
||||
def test_bad_state_error(self):
|
||||
with self.assertRaises(subliminal.classes.BadStateError):
|
||||
self.subli.startWorkers()
|
||||
results = self.subli.listSubtitles(test_folder)
|
||||
self.subli.stopWorkers()
|
||||
|
||||
def test_manual_list(self):
|
||||
self.subli.taskQueue.put((5, subliminal.classes.ListTask(test_file, set(self.subli.languages), 'OpenSubtitles', self.subli.getConfigDict())))
|
||||
self.subli.startWorkers()
|
||||
# parallel stuff...
|
||||
self.subli.stopWorkers()
|
||||
result = self.subli.listResultQueue.get()
|
||||
self.assertTrue(len(result) > 0)
|
||||
|
||||
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
|
||||
Reference in New Issue
Block a user