Compare commits
545 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 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 | |||
| 3cf265f6c9 | |||
| 1b8dd8cc83 | |||
| 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 | |||
| f3292c2916 | |||
| 048d6adfa3 | |||
| f004271e8b | |||
| 63ef2f1273 | |||
| 4d3b050a81 | |||
| f7f2b80028 | |||
| ec21d564b2 | |||
| 6d2b772f21 | |||
| d506dd2095 | |||
| c66028793d | |||
| 0e3467d3aa | |||
| d9dc6832e3 | |||
| a57d49abf1 | |||
| 614388e28f | |||
| 7e1a09fb64 | |||
| 6efbbd9cad | |||
| e0b5894e3f | |||
| 5ed153425b | |||
| c961c9be93 | |||
| 0bafc9d31f | |||
| a48cd6c824 | |||
| cb899b81e4 | |||
| 918151013e | |||
| 4cb9ebb5e3 | |||
| e14a5f1776 | |||
| 2437dc602c | |||
| 8962d84ed3 | |||
| 4172d2a8b1 | |||
| 78a2166efe | |||
| 20a2519d92 | |||
| a7da526885 | |||
| d2010c3510 | |||
| 14c0c6fe6b | |||
| 5d8be66167 | |||
| 9ac838a257 | |||
| 0cd1016cae | |||
| 49b8486f44 | |||
| 0a363ba5d5 | |||
| 5fbfaef31d | |||
| 9324fc4c07 | |||
| 171147dfcd | |||
| dee0b33cec | |||
| f9c7654b7c | |||
| b1e0371bb5 | |||
| f94957c68d | |||
| 03dd15f718 | |||
| 938b30604b | |||
| acff303897 | |||
| 978f4fb376 | |||
| 50e0a6704b | |||
| b4e9c0e655 | |||
| 97ab555e2d | |||
| 9bc12ec619 | |||
| e4c12dfe5c | |||
| ca0d8e4ab1 | |||
| 570dc7ef9a | |||
| 3e7cac972d | |||
| 9c7ac431b5 | |||
| 8f50b317cc | |||
| c5e2e8c4b0 | |||
| 7aec1f7653 | |||
| 65a677e6d4 | |||
| 8e9781c081 | |||
| d76d81eda3 | |||
| 7b439bbf6f | |||
| aea078d65f | |||
| 5834c3edcf | |||
| 1d40c026f4 | |||
| 00fb74c5b1 | |||
| 066dc77bd9 | |||
| f264092e74 | |||
| 052481c0a1 | |||
| 4e3f622de0 | |||
| 143c46fff0 | |||
| bc8b0c762d | |||
| 9ec92d1be4 | |||
| 29ee43a67d | |||
| 0f15f8f52d |
@@ -0,0 +1,5 @@
|
||||
[report]
|
||||
exclude_lines =
|
||||
def __repr__
|
||||
raise NotImplementedError
|
||||
if __name__ == .__main__.:
|
||||
+42
-3
@@ -1,4 +1,43 @@
|
||||
build
|
||||
*.py[co]
|
||||
|
||||
# Packages
|
||||
*.egg
|
||||
*.egg-info
|
||||
dist
|
||||
subliminal.egg-info
|
||||
*.pyc
|
||||
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
|
||||
|
||||
# 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
|
||||
+24
@@ -0,0 +1,24 @@
|
||||
language: python
|
||||
|
||||
python:
|
||||
- "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
|
||||
+140
@@ -0,0 +1,140 @@
|
||||
Changelog
|
||||
=========
|
||||
|
||||
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
|
||||
* BierDopje
|
||||
* OpenSubtitles
|
||||
* 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 = scan_videos(['/path/to/video/folder'], subtitles=True, embedded_subtitles=True)
|
||||
|
||||
# download
|
||||
subliminal.download_best_subtitles(videos, {Language('eng'), Language('fra')}, age=timedelta(week=1))
|
||||
|
||||
|
||||
License
|
||||
-------
|
||||
MIT
|
||||
@@ -0,0 +1,4 @@
|
||||
sympy>=0.7.3
|
||||
sphinx>=1.1.3
|
||||
sphinxcontrib-programoutput>=0.8
|
||||
Sphinx-PyPI-upload>=0.2.1
|
||||
+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
|
||||
* BierDopje
|
||||
* OpenSubtitles
|
||||
* 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 = scan_videos(['/path/to/video/folder'], subtitles=True, embedded_subtitles=True)
|
||||
|
||||
# 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.6.2
|
||||
requests>=2.0.1
|
||||
enzyme>=0.4.0
|
||||
html5lib>=0.99
|
||||
dogpile.cache>=0.5.1
|
||||
babelfish>=0.3.0
|
||||
charade>=1.0.3
|
||||
pysrt>=0.5.0
|
||||
@@ -0,0 +1,7 @@
|
||||
[build_sphinx]
|
||||
source-dir = docs/
|
||||
build-dir = docs/_build
|
||||
all_files = 1
|
||||
|
||||
[upload_sphinx]
|
||||
upload-dir = docs/_build/html
|
||||
@@ -1,44 +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 subliminal import __version__
|
||||
from setuptools import setup, find_packages
|
||||
|
||||
|
||||
setup(name='subliminal',
|
||||
version=__version__,
|
||||
license="LGPLv3",
|
||||
description="Subliminal - Subtitles, faster than your thoughts",
|
||||
version='0.7.2',
|
||||
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',
|
||||
packages=find_packages(),
|
||||
classifiers=['Development Status :: 4 - Beta',
|
||||
'License :: OSI Approved :: GNU Library or Lesser General Public License (LGPL)',
|
||||
'Intended Audience :: Developers',
|
||||
'License :: OSI Approved :: MIT License',
|
||||
'Operating System :: OS Independent',
|
||||
'Programming Language :: Python :: 2.6',
|
||||
'Programming Language :: Python',
|
||||
'Programming Language :: Python :: 2',
|
||||
'Programming Language :: Python :: 2.7',
|
||||
'Programming Language :: Python :: 3',
|
||||
'Programming Language :: Python :: 3.3',
|
||||
'Topic :: Software Development :: Libraries :: Python Modules',
|
||||
'Topic :: Multimedia :: Video'],
|
||||
keywords='subliminal video movie subtitle python library',
|
||||
author="Antoine Bertin",
|
||||
author_email="diaoulael@gmail.com",
|
||||
url="https://github.com/Diaoul/subliminal",
|
||||
packages=["subliminal", "subliminal/plugins"],
|
||||
py_modules=["subliminal"],
|
||||
install_requires=["BeautifulSoup>=3.2.0", "guessit>=0.2"])
|
||||
entry_points={
|
||||
'console_scripts': ['subliminal = subliminal.cli:subliminal'],
|
||||
'subliminal.providers': ['addic7ed = subliminal.providers.addic7ed:Addic7edProvider',
|
||||
'bierdopje = subliminal.providers.bierdopje:BierDopjeProvider',
|
||||
'opensubtitles = subliminal.providers.opensubtitles:OpenSubtitlesProvider',
|
||||
'podnapisi = subliminal.providers.podnapisi:PodnapisiProvider',
|
||||
'thesubdb = subliminal.providers.thesubdb:TheSubDBProvider',
|
||||
'tvsubtitles = subliminal.providers.tvsubtitles:TVsubtitlesProvider'],
|
||||
'babelfish.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')
|
||||
|
||||
@@ -1,71 +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
|
||||
import plugins
|
||||
import logging
|
||||
import traceback
|
||||
|
||||
|
||||
class PluginWorker(threading.Thread):
|
||||
"""Threaded plugin worker"""
|
||||
def __init__(self, taskQueue, resultQueue):
|
||||
threading.Thread.__init__(self)
|
||||
self.taskQueue = taskQueue
|
||||
self.resultQueue = resultQueue
|
||||
self.logger = logging.getLogger('subliminal.worker')
|
||||
|
||||
def run(self):
|
||||
while True:
|
||||
task = self.taskQueue.get()
|
||||
result = None
|
||||
try:
|
||||
if not task: # this is a poison pill
|
||||
break
|
||||
elif task['task'] == 'list': # the task is a listing
|
||||
# get the corresponding plugin
|
||||
plugin = getattr(plugins, task['plugin'])(task['config'])
|
||||
# split tasks if the plugin can't handle multi queries
|
||||
splitedTasks = plugin.splitTask(task)
|
||||
myTask = splitedTasks.pop()
|
||||
for st in splitedTasks:
|
||||
self.taskQueue.put(st)
|
||||
result = plugin.list(myTask['filenames'], myTask['languages'])
|
||||
elif task['task'] == 'download': # the task is to download
|
||||
result = None
|
||||
while task['subtitle']:
|
||||
subtitle = task['subtitle'].pop(0)
|
||||
# get the corresponding plugin
|
||||
plugin = getattr(plugins, subtitle["plugin"])(task['config'])
|
||||
path = plugin.download(subtitle)
|
||||
if path:
|
||||
subtitle["subtitlepath"] = path
|
||||
result = subtitle
|
||||
break
|
||||
else:
|
||||
self.logger.error(u'Unknown task %s submited to worker %s' % (task['task'], self.name))
|
||||
except:
|
||||
self.logger.debug(traceback.print_exc())
|
||||
self.logger.error(u"Worker couldn't do the job %s, continue anyway" % task['task'])
|
||||
finally:
|
||||
self.resultQueue.put(result)
|
||||
self.taskQueue.task_done()
|
||||
self.logger.debug(u"Thread %s terminated" % self.name)
|
||||
+12
-21
@@ -1,25 +1,16 @@
|
||||
# -*- 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.2'
|
||||
__author__ = 'Antoine Bertin'
|
||||
__license__ = 'MIT'
|
||||
__copyright__ = 'Copyright 2013 Antoine Bertin'
|
||||
|
||||
__version__ = '0.2'
|
||||
import logging
|
||||
from .api import PROVIDERS_ENTRY_POINT, list_subtitles, download_subtitles, download_best_subtitles
|
||||
from .cache import 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
|
||||
|
||||
|
||||
from subliminal import *
|
||||
logging.getLogger(__name__).addHandler(logging.NullHandler())
|
||||
|
||||
@@ -0,0 +1,276 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
from __future__ import unicode_literals
|
||||
import collections
|
||||
import io
|
||||
import logging
|
||||
import operator
|
||||
import babelfish
|
||||
import pkg_resources
|
||||
from .exceptions import ProviderNotAvailable, InvalidSubtitle
|
||||
from .subtitle import get_subtitle_path
|
||||
|
||||
|
||||
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:
|
||||
logger.warning('Provider %r is not available, discarding it', provider_entry_point.name)
|
||||
break
|
||||
except:
|
||||
logger.exception('Unexpected error in provider %r', provider_entry_point.name)
|
||||
continue
|
||||
logger.info('Found %d subtitles', len(provider_subtitles))
|
||||
subtitles[provider_video].extend(provider_subtitles)
|
||||
except ProviderNotAvailable:
|
||||
logger.warning('Provider %r is not available, discarding it', provider_entry_point.name)
|
||||
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 = {ep.name: ep.load() for ep in pkg_resources.iter_entry_points(PROVIDERS_ENTRY_POINT)}
|
||||
initialized_providers = {}
|
||||
try:
|
||||
for video, video_subtitles in subtitles.items():
|
||||
languages = {subtitle.language for subtitle in video_subtitles}
|
||||
downloaded_languages = set()
|
||||
for subtitle in video_subtitles:
|
||||
# filter
|
||||
if subtitle.language in downloaded_languages:
|
||||
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:
|
||||
logger.warning('Provider %r is not available, discarding it', 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)
|
||||
logger.info('Downloading subtitle %r into %r', subtitle, subtitle_path)
|
||||
try:
|
||||
subtitle_text = provider.download_subtitle(subtitle)
|
||||
except ProviderNotAvailable:
|
||||
logger.warning('Provider %r is not available, discarding it', subtitle.provider_name)
|
||||
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)
|
||||
if single or downloaded_languages == 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)
|
||||
|
||||
|
||||
def download_best_subtitles(videos, languages, providers=None, provider_configs=None, single=False, min_score=0,
|
||||
hearing_impaired=False):
|
||||
"""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
|
||||
|
||||
"""
|
||||
provider_configs = provider_configs or {}
|
||||
discarded_providers = set()
|
||||
downloaded_subtitles = collections.defaultdict(list)
|
||||
# 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.info('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.info('Skipping provider %r: no video to search for', provider_entry_point.name)
|
||||
continue
|
||||
provider = Provider(**provider_configs.get(provider_entry_point.name, {}))
|
||||
try:
|
||||
provider.initialize()
|
||||
except ProviderNotAvailable:
|
||||
logger.warning('Provider %r is not available, discarding it', provider_entry_point.name)
|
||||
continue
|
||||
initialized_providers[provider_entry_point.name] = provider
|
||||
try:
|
||||
for video in videos:
|
||||
# search for subtitles
|
||||
subtitles = []
|
||||
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:
|
||||
logger.warning('Provider %r is not available, discarding it', provider_name)
|
||||
discarded_providers.add(provider_name)
|
||||
continue
|
||||
except:
|
||||
logger.exception('Unexpected error in provider %r', provider_name)
|
||||
continue
|
||||
logger.info('Found %d subtitles', len(provider_subtitles))
|
||||
subtitles.extend(provider_subtitles)
|
||||
|
||||
# find the best subtitles and download them
|
||||
downloaded_languages = video.subtitle_languages.copy()
|
||||
for subtitle, score in sorted([(s, s.compute_score(video)) 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 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)
|
||||
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:
|
||||
logger.warning('Provider %r is not available, discarding it', subtitle.provider_name)
|
||||
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)
|
||||
if single or downloaded_languages >= languages:
|
||||
logger.debug('All languages downloaded')
|
||||
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
|
||||
@@ -0,0 +1,30 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
import inspect
|
||||
import dogpile.cache
|
||||
|
||||
|
||||
#: Subliminal's cache version
|
||||
CACHE_VERSION = 1
|
||||
|
||||
|
||||
def subliminal_key_generator(namespace, fn, to_str=dogpile.cache.compat.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
|
||||
|
||||
|
||||
#: The dogpile.cache region
|
||||
region = dogpile.cache.make_region(function_key_generator=subliminal_key_generator)
|
||||
@@ -0,0 +1,167 @@
|
||||
# -*- 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, 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')
|
||||
|
||||
# addic7ed
|
||||
addic7ed_group = parser.add_argument_group('addic7ed')
|
||||
addic7ed_group.add_argument('--addic7ed-username', metavar='USERNAME', help='username for addic7ed provider')
|
||||
addic7ed_group.add_argument('--addic7ed-password', metavar='PASSWORD', help='password for addic7ed provider')
|
||||
|
||||
# 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 = {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(**{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 = {}
|
||||
if (args.addic7ed_username is not None and args.addic7ed_password is None
|
||||
or args.addic7ed_username is None and args.addic7ed_password is not None):
|
||||
parser.error('argument --addic7ed-username/--addic7ed-password: both arguments are required or none')
|
||||
if args.addic7ed_username is not None and args.addic7ed_password is not None:
|
||||
provider_configs['addic7ed'] = {'username': args.addic7ed_username, 'password': args.addic7ed_password}
|
||||
|
||||
# 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),
|
||||
arguments={'filename': args.cache_file})
|
||||
|
||||
# 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, 'autodetect')) 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.converters.name import NameConverter
|
||||
|
||||
|
||||
class Addic7edConverter(NameConverter):
|
||||
def __init__(self):
|
||||
super(Addic7edConverter, self).__init__()
|
||||
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 |= 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 super(Addic7edConverter, self).convert(alpha3, country, script)
|
||||
|
||||
def reverse(self, addic7ed):
|
||||
if addic7ed in self.from_addic7ed:
|
||||
return self.from_addic7ed[addic7ed]
|
||||
return super(Addic7edConverter, self).reverse(addic7ed)
|
||||
@@ -0,0 +1,33 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
from __future__ import unicode_literals
|
||||
from babelfish import ReverseConverter, ConvertError, ReverseError
|
||||
|
||||
|
||||
class PodnapisiConverter(ReverseConverter):
|
||||
def __init__(self):
|
||||
super(PodnapisiConverter, self).__init__()
|
||||
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 = {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 ConvertError(alpha3, country, script)
|
||||
|
||||
def reverse(self, podnapisi):
|
||||
if podnapisi not in self.from_podnapisi:
|
||||
raise ReverseError(podnapisi)
|
||||
return self.from_podnapisi[podnapisi]
|
||||
@@ -0,0 +1,24 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
from __future__ import unicode_literals
|
||||
from babelfish.converters.alpha2 import Alpha2Converter
|
||||
|
||||
|
||||
class TVsubtitlesConverter(Alpha2Converter):
|
||||
def __init__(self):
|
||||
super(TVsubtitlesConverter, self).__init__()
|
||||
self.from_tvsubtitles = {'br': ('por', 'BR'), 'ua': ('ukr',), 'gr': ('ell',), 'cn': ('zho',), 'jp': ('jpn',),
|
||||
'cz': ('ces',)}
|
||||
self.to_tvsubtitles = {v: k for k, v in self.from_tvsubtitles}
|
||||
self.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 super(TVsubtitlesConverter, self).convert(alpha3, country, script)
|
||||
|
||||
def reverse(self, tvsubtitles):
|
||||
if tvsubtitles in self.from_tvsubtitles:
|
||||
return self.from_tvsubtitles[tvsubtitles]
|
||||
return super(TVsubtitlesConverter, self).reverse(tvsubtitles)
|
||||
@@ -1,66 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
#
|
||||
# Subliminal - Subtitles, faster than your thoughts
|
||||
# Copyright (c) 2011 Nic Wolfe <nic@wolfeden.ca>
|
||||
# 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 os
|
||||
import subliminal
|
||||
|
||||
|
||||
# This module tries to deal with the apparently random behavior of python when dealing with unicode <-> utf-8
|
||||
# encodings. It tries to just use unicode, but if that fails then it tries forcing it to utf-8. Any functions
|
||||
# which return something should always return unicode.
|
||||
|
||||
def fixStupidEncodings(x, silent=False):
|
||||
if type(x) == str:
|
||||
try:
|
||||
return x.decode(subliminal.SYS_ENCODING)
|
||||
except UnicodeDecodeError:
|
||||
subliminal.logger.error(u"Unable to decode value: " + repr(x))
|
||||
return None
|
||||
elif type(x) == unicode:
|
||||
return x
|
||||
else:
|
||||
subliminal.logger.log(u"Unknown value passed in, ignoring it: " + str(type(x)) + " (" + repr(x) + ":" + repr(type(x)) + ")", logging.DEBUG if silent else logging.ERROR)
|
||||
return None
|
||||
|
||||
return None
|
||||
|
||||
|
||||
def fixListEncodings(x):
|
||||
if type(x) != list:
|
||||
return x
|
||||
else:
|
||||
return filter(lambda x: x != None, map(fixStupidEncodings, x))
|
||||
|
||||
|
||||
def ek(func, *args):
|
||||
result = None
|
||||
if os.name == 'nt':
|
||||
result = func(*args)
|
||||
else:
|
||||
result = func(*[x.encode(subliminal.SYS_ENCODING) if type(x) in (str, unicode) else x for x in args])
|
||||
|
||||
if type(result) == list:
|
||||
return fixListEncodings(result)
|
||||
elif type(result) == str:
|
||||
return fixStupidEncodings(result)
|
||||
else:
|
||||
return result
|
||||
@@ -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,158 +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 PluginBase
|
||||
import zipfile
|
||||
import os
|
||||
import urllib2
|
||||
import urllib
|
||||
import traceback
|
||||
import httplib
|
||||
import re
|
||||
import socket
|
||||
|
||||
|
||||
class Addic7ed(PluginBase.PluginBase):
|
||||
site_url = 'http://www.addic7ed.com'
|
||||
site_name = 'Addic7ed'
|
||||
server_url = 'http://www.addic7ed.com'
|
||||
multi_languages_queries = True
|
||||
multi_filename_queries = False
|
||||
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, filenames, languages):
|
||||
''' Main method to call when you want to list subtitles '''
|
||||
# as self.multi_filename_queries is false, we won't have multiple filenames in the list so pick the only one
|
||||
# once multi-filename queries are implemented, set multi_filename_queries to true and manage a list of multiple filenames here
|
||||
if not self.checkLanguages(languages):
|
||||
return []
|
||||
filepath = filenames[0]
|
||||
guess = guessit.guess_file_info(filepath, 'autodetect')
|
||||
if guess['type'] != 'episode':
|
||||
return []
|
||||
# add multiple things to the release group set
|
||||
release_group = set()
|
||||
if 'releaseGroup' in guess:
|
||||
release_group.add(guess['releaseGroup'])
|
||||
else:
|
||||
if 'title' in guess:
|
||||
release_group.add(guess['title'])
|
||||
if 'screenSize' in guess:
|
||||
release_group.add(guess['screenSize'])
|
||||
if len(release_group) == 0:
|
||||
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):
|
||||
''' Make a query and returns info about found subtitles '''
|
||||
searchname = name.lower().replace(" ", "_")
|
||||
searchurl = "%s/serie/%s/%s/%s/%s" % (self.server_url, searchname, season, episode, 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]], [".", "_", " "])
|
||||
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 = {}
|
||||
result["release"] = "%s.S%.2dE%.2d.%s" % (name.replace(" ", "."), int(season), int(episode), '.'.join(sub_teams))
|
||||
result["lang"] = sub_language
|
||||
result["link"] = sub_link
|
||||
result["page"] = searchurl
|
||||
result["filename"] = filepath
|
||||
result["plugin"] = self.getClassName()
|
||||
result["teams"] = sub_teams # used to sort
|
||||
sublinks.append(result)
|
||||
sublinks.sort(self._cmpTeams)
|
||||
return sublinks
|
||||
|
||||
def download(self, subtitle):
|
||||
'''pass the URL of the sub and the file it matches, will unzip it
|
||||
and return the path to the created file'''
|
||||
suburl = subtitle["link"]
|
||||
videofilename = subtitle["filename"]
|
||||
srtbasefilename = videofilename.rsplit(".", 1)[0]
|
||||
srtfilename = srtbasefilename + self.getExtension(subtitle)
|
||||
self.downloadFile(suburl, srtfilename)
|
||||
return srtfilename
|
||||
|
||||
def _cmpTeams(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,170 +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
|
||||
import pickle
|
||||
import traceback
|
||||
import urllib
|
||||
import urllib2
|
||||
from subliminal import encodingKludge as ek
|
||||
|
||||
|
||||
class BierDopje(PluginBase.PluginBase):
|
||||
site_url = 'http://bierdopje.com'
|
||||
site_name = 'BierDopje'
|
||||
server_url = 'http://api.bierdopje.com/A2B638AC5D804C2E/'
|
||||
multi_languages_queries = True
|
||||
multi_filename_queries = False
|
||||
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):
|
||||
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 not config_dict or not config_dict['cache_dir']:
|
||||
raise Exception('Cache directory is mandatory for this plugin')
|
||||
self.showid_cache = ek.ek(os.path.join, config_dict['cache_dir'], "bierdopje_showid.cache")
|
||||
with self.lock:
|
||||
if not ek.ek(os.path.exists, self.showid_cache):
|
||||
if not ek.ek(os.path.exists, ek.ek(os.path.dirname, self.showid_cache)):
|
||||
raise Exception("Cache directory doesn't exists")
|
||||
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, filenames, languages):
|
||||
"""Main method to call when you want to list subtitles"""
|
||||
# as self.multi_filename_queries is false, we won't have multiple filenames in the list so pick the only one
|
||||
# once multi-filename queries are implemented, set multi_filename_queries to true and manage a list of multiple filenames here
|
||||
if not self.checkLanguages(languages):
|
||||
return []
|
||||
filepath = filenames[0]
|
||||
guess = guessit.guess_file_info(filepath, 'autodetect')
|
||||
if guess['type'] != '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 len(release_group) == 0:
|
||||
return []
|
||||
self.release_group = release_group # used to sort results
|
||||
return self.query(guess['series'], guess['season'], guess['episodeNumber'], release_group, filepath, languages)
|
||||
|
||||
def download(self, subtitle):
|
||||
"""Main method to call when you want to download a subtitle"""
|
||||
subpath = subtitle["filename"].rsplit(".", 1)[0] + self.getExtension(subtitle)
|
||||
self.downloadFile(subtitle["link"], subpath)
|
||||
return subpath
|
||||
|
||||
def query(self, name, season, episode, release_group, filepath, languages=None):
|
||||
"""Makes a query and returns info (link, lang) about found subtitles"""
|
||||
if languages:
|
||||
available_languages = list(set(languages).intersection((self._plugin_languages.values())))
|
||||
else:
|
||||
available_languages = self._plugin_languages.values()
|
||||
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_id_url = "%sGetShowByName/%s" % (self.server_url, urllib.quote(show_name))
|
||||
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 available_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 = {}
|
||||
result["release"] = sub_release
|
||||
result["link"] = sub_link
|
||||
result["page"] = sub_link
|
||||
result["lang"] = language
|
||||
result["filename"] = filepath
|
||||
result["plugin"] = self.getClassName()
|
||||
result["releaseGroup"] = sub_release_group
|
||||
sublinks.append(result)
|
||||
sublinks.sort(self._cmpReleaseGroup)
|
||||
return sublinks
|
||||
|
||||
def _cmpReleaseGroup(self, x, y):
|
||||
"""Sort based on teams matching"""
|
||||
return -cmp(len(x['releaseGroup'].intersection(self.release_group)), len(y['releaseGroup'].intersection(self.release_group)))
|
||||
@@ -1,205 +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
|
||||
from subliminal import encodingKludge as ek
|
||||
|
||||
|
||||
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.2'
|
||||
multi_languages_queries = True
|
||||
multi_filename_queries = False
|
||||
api_based = True
|
||||
_plugin_languages = {"en": "eng",
|
||||
"fr": "fre",
|
||||
"hu": "hun",
|
||||
"cs": "cze",
|
||||
"pl": "pol",
|
||||
"sk": "slo",
|
||||
"pt": "por",
|
||||
"pt-br": "pob",
|
||||
"es": "spa",
|
||||
"el": "ell",
|
||||
"ar": "ara",
|
||||
"sq": "alb",
|
||||
"hy": "arm",
|
||||
"ay": "ass",
|
||||
"bs": "bos",
|
||||
"bg": "bul",
|
||||
"ca": "cat",
|
||||
"zh": "chi",
|
||||
"hr": "hrv",
|
||||
"da": "dan",
|
||||
"nl": "dut",
|
||||
"eo": "epo",
|
||||
"et": "est",
|
||||
"fi": "fin",
|
||||
"gl": "glg",
|
||||
"ka": "geo",
|
||||
"de": "ger",
|
||||
"he": "heb",
|
||||
"hi": "hin",
|
||||
"is": "ice",
|
||||
"id": "ind",
|
||||
"it": "ita",
|
||||
"ja": "jpn",
|
||||
"kk": "kaz",
|
||||
"ko": "kor",
|
||||
"lv": "lav",
|
||||
"lt": "lit",
|
||||
"lb": "ltz",
|
||||
"mk": "mac",
|
||||
"ms": "may",
|
||||
"no": "nor",
|
||||
"oc": "oci",
|
||||
"fa": "per",
|
||||
"ro": "rum",
|
||||
"ru": "rus",
|
||||
"sr": "scc",
|
||||
"sl": "slv",
|
||||
"sv": "swe",
|
||||
"th": "tha",
|
||||
"tr": "tur",
|
||||
"uk": "ukr",
|
||||
"vi": "vie"}
|
||||
|
||||
def __init__(self, config_dict=None):
|
||||
super(OpenSubtitles, self).__init__(self._plugin_languages, config_dict)
|
||||
|
||||
def list(self, filenames, languages):
|
||||
"""Main method to call when you want to list subtitles """
|
||||
# as self.multi_filename_queries is false, we won't have multiple filenames in the list so pick the only one
|
||||
# once multi-filename queries are implemented, set multi_filename_queries to true and manage a list of multiple filenames here
|
||||
filepath = filenames[0]
|
||||
if ek.ek(os.path.isfile, filepath):
|
||||
filehash = self.hashFile(filepath)
|
||||
size = ek.ek(os.path.getsize, filepath)
|
||||
return self.query(moviehash=filehash, languages=languages, bytesize=size, filepath=filepath)
|
||||
else:
|
||||
return self.query(languages=languages, filepath=filepath)
|
||||
|
||||
def download(self, subtitle):
|
||||
"""Main method to call when you want to download a subtitle """
|
||||
subtitleFilename = subtitle["filename"].rsplit(".", 1)[0] + self.getExtension(subtitle)
|
||||
self.downloadFile(subtitle["link"], subtitleFilename + ".gz")
|
||||
f = ek.ek(gzip.open, subtitleFilename + ".gz")
|
||||
dump = ek.ek(open, subtitleFilename, "wb")
|
||||
dump.write(f.read())
|
||||
dump.close()
|
||||
f.close()
|
||||
ek.ek(os.remove, subtitleFilename + ".gz")
|
||||
return subtitleFilename
|
||||
|
||||
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, we'll use the filename")
|
||||
guess = guessit.guess_file_info(filepath, 'autodetect')
|
||||
if guess['type'] == 'episode':
|
||||
search['query'] = guess['series']
|
||||
elif guess['type'] == 'movie':
|
||||
search['query'] = guess['title']
|
||||
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, e:
|
||||
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 = {}
|
||||
result["release"] = r['SubFileName']
|
||||
result["link"] = r['SubDownloadLink']
|
||||
result["page"] = r['SubDownloadLink']
|
||||
result["lang"] = self.getRevertLanguage(r['SubLanguageID'])
|
||||
result["filename"] = filepath
|
||||
result["plugin"] = self.getClassName()
|
||||
if 'query' in search and not r["MovieReleaseName"].replace('.', ' ').startswith(search['query']): # query mode search, filter results
|
||||
self.logger.debug(u"Skipping %s it does not start with %s" % (r["MovieReleaseName"].replace('.', ' '), search['query']))
|
||||
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,183 +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 re
|
||||
import sys
|
||||
import urllib2
|
||||
import struct
|
||||
import threading
|
||||
from subliminal import encodingKludge as ek
|
||||
|
||||
|
||||
class PluginBase(object):
|
||||
__metaclass__ = abc.ABCMeta
|
||||
multi_languages_queries = False
|
||||
multi_filename_queries = False
|
||||
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.getClassName())
|
||||
|
||||
@staticmethod
|
||||
def getFileName(filepath):
|
||||
filename = filepath
|
||||
if ek.ek(os.path.isfile, filename):
|
||||
filename = ek.ek(os.path.basename, filename)
|
||||
if filename.endswith(('.avi', '.wmv', '.mov', '.mp4', '.mpeg', '.mpg', '.mkv')):
|
||||
filename = filename.rsplit('.', 1)[0]
|
||||
return filename
|
||||
|
||||
def hashFile(self, filename):
|
||||
"""Hash a file like OpenSubtitles"""
|
||||
longlongformat = 'q' # long long
|
||||
bytesize = struct.calcsize(longlongformat)
|
||||
f = ek.ek(open, filename, "rb")
|
||||
filesize = ek.ek(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 x 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 x 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, filename, data=None):
|
||||
"""Downloads the given url to the given filename"""
|
||||
try:
|
||||
self.logger.info(u"Downloading %s" % url)
|
||||
req = urllib2.Request(url, headers={'Referer': url, 'User-Agent': self.user_agent})
|
||||
f = urllib2.urlopen(req, data=data)
|
||||
dump = ek.ek(open, filename, "wb")
|
||||
dump.write(f.read())
|
||||
dump.close()
|
||||
f.close()
|
||||
self.logger.debug(u"Download finished for file %s. Size: %s" % (filename, ek.ek(os.path.getsize, filename)))
|
||||
except urllib2.HTTPError, e:
|
||||
self.logger.error(u"HTTP Error:", e.code, url)
|
||||
except urllib2.URLError, e:
|
||||
self.logger.error(u"URL Error:", e.reason, url)
|
||||
|
||||
@abc.abstractmethod
|
||||
def list(self, filenames, languages):
|
||||
"""Main method to call when you want to list subtitles"""
|
||||
|
||||
@abc.abstractmethod
|
||||
def download(self, subtitle):
|
||||
"""Main method to call when you want to download a subtitle"""
|
||||
|
||||
def getRevertLanguage(self, language):
|
||||
"""Returns the short (two-character) representation from the long language name"""
|
||||
try:
|
||||
return self.revertPluginLanguages[language]
|
||||
except KeyError, e:
|
||||
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.getClassName(), language))
|
||||
|
||||
def checkLanguages(self, languages):
|
||||
if languages and not set(languages).intersection((self._plugin_languages.values())):
|
||||
self.logger.debug(u'None of requested languages %s are available' % languages)
|
||||
return False
|
||||
return True
|
||||
|
||||
def getLanguage(self, language):
|
||||
"""Returns the long naming of the language from a two character code"""
|
||||
try:
|
||||
return self.pluginLanguages[language]
|
||||
except KeyError, e:
|
||||
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.getClassName(), language))
|
||||
|
||||
def getExtension(self, subtitle):
|
||||
if self.config_dict and self.config_dict['multi']:
|
||||
return ".%s.srt" % subtitle['lang']
|
||||
return ".srt"
|
||||
|
||||
def getClassName(self):
|
||||
return self.__class__.__name__
|
||||
|
||||
def splitTask(self, task):
|
||||
"""Determines if the plugin can handle multi-thing queries and output splited tasks for list task only"""
|
||||
if task['task'] != 'list':
|
||||
return [task]
|
||||
tasks = [task]
|
||||
if not self.multi_filename_queries:
|
||||
tasks = self._splitOnField(tasks, 'filenames')
|
||||
if not self.multi_languages_queries:
|
||||
tasks = self._splitOnField(tasks, 'languages')
|
||||
return tasks
|
||||
|
||||
@staticmethod
|
||||
def _splitOnField(elements, field):
|
||||
"""
|
||||
Split a list of dict in a bigger one if the element field in the dict has multiple elements too
|
||||
i.e. [{'a': 1, 'b': [2,3]}, {'a': 7, 'b': [4]}] => [{'a': 1, 'b': [2]}, {'a': 1, 'b': [3]}, {'a': 7, 'b': [4]}]
|
||||
with field = 'b'
|
||||
"""
|
||||
results = []
|
||||
for e in elements:
|
||||
for v in e[field]:
|
||||
newElement = {}
|
||||
for (key, value) in e.items():
|
||||
if key != field:
|
||||
newElement[key] = value
|
||||
else:
|
||||
newElement[key] = [v]
|
||||
results.append(newElement)
|
||||
return results
|
||||
|
||||
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
|
||||
@@ -1,146 +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 struct
|
||||
import socket
|
||||
import zipfile
|
||||
import os
|
||||
import urllib2
|
||||
import urllib
|
||||
import traceback
|
||||
from subliminal import encodingKludge as ek
|
||||
|
||||
|
||||
class Podnapisi(PluginBase.PluginBase):
|
||||
site_url = "http://www.podnapisi.net"
|
||||
site_name = "Podnapisi"
|
||||
server_url = 'http://ssp.podnapisi.net:8000'
|
||||
multi_languages_queries = True
|
||||
multi_filename_queries = False
|
||||
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"""
|
||||
# as self.multi_filename_queries is false, we won't have multiple filenames in the list so pick the only one
|
||||
# once multi-filename queries are implemented, set multi_filename_queries to true and manage a list of multiple filenames here
|
||||
filepath = filenames[0]
|
||||
if not ek.ek(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, e:
|
||||
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)
|
||||
d = self.server.download(token, [173793])
|
||||
self.server.terminate(token)
|
||||
return subs
|
||||
@@ -1,176 +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
|
||||
import urllib
|
||||
import traceback
|
||||
import httplib
|
||||
from subliminal import encodingKludge as ek
|
||||
|
||||
|
||||
class SubScene(PluginBase.PluginBase):
|
||||
site_url = 'http://subscene.com'
|
||||
site_name = 'SubScene'
|
||||
server_url = 'http://subscene.com/s.aspx?subtitle='
|
||||
multi_languages_queries = True
|
||||
multi_filename_queries = False
|
||||
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"""
|
||||
# as self.multi_filename_queries is false, we won't have multiple filenames in the list so pick the only one
|
||||
# once multi-filename queries are implemented, set multi_filename_queries to true and manage a list of multiple filenames here
|
||||
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 = ek.ek(open, subtitlefilename, "wb")
|
||||
outfile.write(zf.read(el.orig_filename))
|
||||
outfile.flush()
|
||||
outfile.close()
|
||||
else:
|
||||
self.logger.info(u"File %s does not seem to be valid " % el.orig_filename)
|
||||
# Deleting the zip file
|
||||
zf.close()
|
||||
ek.ek(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, ek.ek(os.path.dirname, archivefilename)]
|
||||
subprocess.Popen(args)
|
||||
tmpsubtitlefilename = ek.ek(os.path.join, ek.ek(os.path.dirname, archivefilename), el)
|
||||
subtitlefilename = ek.ek(os.path.join, ek.ek(os.path.dirname, archivefilename), srtbasefilename + "." + extension)
|
||||
if ek.ek(os.path.exists, tmpsubtitlefilename):
|
||||
# rename it to match the file
|
||||
ek.ek(os.rename, tmpsubtitlefilename, subtitlefilename)
|
||||
# exit
|
||||
return subtitlefilename
|
||||
except OSError, 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
|
||||
super(SubScene, self).downloadFile(url, filename, urllib.urlencode({'__EVENTTARGET': 's$lc$bcr$downloadLink', '__EVENTARGUMENT': '', '__VIEWSTATE': '/wEPDwUHNzUxOTkwNWRk4wau5efPqhlBJJlOkKKHN8FIS04='}))
|
||||
|
||||
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, urllib.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.getClassName()
|
||||
sublinks.append(result)
|
||||
return sublinks
|
||||
@@ -1,156 +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 urllib2
|
||||
import urllib
|
||||
import logging
|
||||
import traceback
|
||||
import httplib
|
||||
import re
|
||||
import guessit
|
||||
from subliminal import encodingKludge as ek
|
||||
|
||||
|
||||
class SubsWiki(PluginBase.PluginBase):
|
||||
site_url = 'http://www.subswiki.com'
|
||||
site_name = 'SubsWiki'
|
||||
server_url = 'http://www.subswiki.com'
|
||||
multi_languages_queries = True
|
||||
multi_filename_queries = False
|
||||
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, filenames, languages):
|
||||
"""Main method to call when you want to list subtitles"""
|
||||
# as self.multi_filename_queries is false, we won't have multiple filenames in the list so pick the only one
|
||||
# once multi-filename queries are implemented, set multi_filename_queries to true and manage a list of multiple filenames here
|
||||
filepath = filenames[0]
|
||||
if not self.checkLanguages(languages):
|
||||
return []
|
||||
guess = guessit.guess_file_info(filepath, 'autodetect')
|
||||
if guess['type'] != 'episode':
|
||||
return []
|
||||
# add multiple things to the release group set
|
||||
release_group = set()
|
||||
if 'releaseGroup' in guess:
|
||||
release_group.add(guess['releaseGroup'])
|
||||
else:
|
||||
if 'title' in guess:
|
||||
release_group.add(guess['title'])
|
||||
if 'screenSize' in guess:
|
||||
release_group.add(guess['screenSize'])
|
||||
if len(release_group) == 0:
|
||||
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):
|
||||
"""Make a query and returns info about found subtitles"""
|
||||
sublinks = []
|
||||
searchname = name.lower().replace(" ", "_")
|
||||
searchurl = "%s/serie/%s/%s/%s/" % (self.server_url, 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)], [".", "_", " ", "/", "-"])
|
||||
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 languages and 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 = {}
|
||||
result["release"] = "%s.S%.2dE%.2d.%s" % (name.replace(" ", "."), int(season), int(episode), '.'.join(sub_teams))
|
||||
result["lang"] = sub_language
|
||||
result["link"] = self.server_url + sub_link
|
||||
result["page"] = searchurl
|
||||
result["filename"] = filepath
|
||||
result["plugin"] = self.getClassName()
|
||||
result["teams"] = sub_teams # used to sort
|
||||
sublinks.append(result)
|
||||
sublinks.sort(self._cmpTeams)
|
||||
return sublinks
|
||||
|
||||
def download(self, subtitle):
|
||||
"""Main method to call when you want to download a subtitle"""
|
||||
subtitleFilename = subtitle["filename"].rsplit(".", 1)[0] + self.getExtension(subtitle)
|
||||
self.downloadFile(subtitle["link"], subtitleFilename)
|
||||
return subtitleFilename
|
||||
|
||||
def listTeams(self, subteams, separators):
|
||||
teams = []
|
||||
for sep in separators:
|
||||
subteams = self.splitTeam(subteams, sep)
|
||||
return set(subteams)
|
||||
|
||||
def splitTeam(self, subteams, sep):
|
||||
teams = []
|
||||
for t in subteams:
|
||||
teams += t.split(sep)
|
||||
return teams
|
||||
|
||||
def downloadFile(self, url, filename):
|
||||
"""Downloads the given url to the given filename"""
|
||||
req = urllib2.Request(url, headers={'Referer': url, 'User-Agent': 'Mozilla/5.0 (X11; U; Linux x86_64; en-US; rv:1.9.1.3)'})
|
||||
f = urllib2.urlopen(req)
|
||||
dump = ek.ek(open, filename, "wb")
|
||||
dump.write(f.read())
|
||||
dump.close()
|
||||
f.close()
|
||||
|
||||
def _cmpTeams(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,122 +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 ConfigParser
|
||||
import PluginBase
|
||||
import traceback
|
||||
import urllib
|
||||
import urllib2
|
||||
import xml.dom.minidom
|
||||
|
||||
|
||||
class SubtitleSource(PluginBase.PluginBase):
|
||||
site_url = 'http://www.subtitlesource.org'
|
||||
site_name = 'SubtitleSource'
|
||||
server_url = 'http://www.subtitlesource.org/api/%s/3.0/xmlsearch'
|
||||
multi_languages_queries = True
|
||||
multi_filename_queries = False
|
||||
api_based = True
|
||||
_plugin_languages = {"en": "English",
|
||||
"sv": "Swedish",
|
||||
"da": "Danish",
|
||||
"fi": "Finnish",
|
||||
"no": "Norwegian",
|
||||
"fr": "French",
|
||||
"es": "Spanish",
|
||||
"is": "Icelandic"}
|
||||
|
||||
def __init__(self, config_dict=None):
|
||||
super(SubtitleSource, self).__init__(self._plugin_languages, config_dict)
|
||||
if config_dict and "subtitlesource_key" in config_dict:
|
||||
self.server_url = self.server_url % config_dict["subtitlesource_key"]
|
||||
else:
|
||||
self.logger.error(u'SubtitleSource API Key is mandatory for this plugin')
|
||||
raise Exception('SubtitleSource API Key is mandatory for this plugin')
|
||||
|
||||
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, 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, languages)
|
||||
return subs
|
||||
else:
|
||||
return subs
|
||||
|
||||
def query(self, token, languages=None):
|
||||
"""Makes a query on SubtitlesSource and returns info (link, lang) about found subtitles"""
|
||||
self.logger.debug(u"Local file is: %s " % token)
|
||||
sublinks = []
|
||||
if not languages: # langs is empty of None
|
||||
languages = ["all"]
|
||||
else: # parse each lang to generate the equivalent lang
|
||||
languages = [self._plugin_languages[l] for l in languages if l in self._plugin_languages.keys()]
|
||||
# Get the CD part of this
|
||||
metaData = self.guessFileData(token)
|
||||
multipart = metaData.get('part', None)
|
||||
part = metaData.get('part')
|
||||
if not part: # part will return None if not found using the regex
|
||||
part = 1
|
||||
for lang in languages:
|
||||
searchurl = "%s/%s/%s/0" % (self.server_url, urllib.quote(token), lang)
|
||||
self.logger.debug(u"dl'ing %s" % searchurl)
|
||||
page = urllib2.urlopen(searchurl, timeout=self.timeout)
|
||||
xmltree = xml.dom.minidom.parse(page)
|
||||
subs = xmltree.getElementsByTagName("sub")
|
||||
for sub in subs:
|
||||
sublang = self.getRevertLanguage(self.getValue(sub, "language"))
|
||||
if languages and not sublang in languages:
|
||||
continue # The language of this sub is not wanted => Skip
|
||||
if multipart and not int(self.getValue(sub, 'cd')) > 1:
|
||||
continue # The subtitle is not a multipart
|
||||
dllink = "http://www.subtitlesource.org/download/text/%s/%s" % (self.getValue(sub, "id"), part)
|
||||
self.logger.debug(u"Link added: %s (%s)" % (dllink, sublang))
|
||||
result = {}
|
||||
result["release"] = self.getValue(sub, "releasename")
|
||||
result["link"] = dllink
|
||||
result["page"] = dllink
|
||||
result["lang"] = sublang
|
||||
releaseMetaData = self.guessFileData(result['release'])
|
||||
teams = set(metaData['teams'])
|
||||
srtTeams = set(releaseMetaData['teams'])
|
||||
self.logger.debug(u"Analyzing: %s " % result['release'])
|
||||
self.logger.debug(u"Local file has: %s " % metaData['teams'])
|
||||
self.logger.debug(u"Remote sub has: %s " % releaseMetaData['teams'])
|
||||
if result['release'].startswith(token) or (releaseMetaData['name'] == metaData['name'] and releaseMetaData['type'] == metaData['type'] and (teams.issubset(srtTeams) or srtTeams.issubset(teams))):
|
||||
sublinks.append(result)
|
||||
return sublinks
|
||||
|
||||
def download(self, subtitle):
|
||||
"""Main method to call when you want to download a subtitle"""
|
||||
suburl = subtitle["link"]
|
||||
videofilename = subtitle["filename"]
|
||||
srtfilename = videofilename.rsplit(".", 1)[0] + self.getExtension(subtitle)
|
||||
self.downloadFile(suburl, srtfilename)
|
||||
return srtfilename
|
||||
|
||||
def getValue(self, sub, tagName):
|
||||
for node in sub.childNodes:
|
||||
if node.nodeType == node.ELEMENT_NODE and node.tagName == tagName:
|
||||
return node.childNodes[0].nodeValue
|
||||
@@ -1,150 +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 zipfile
|
||||
import urllib2
|
||||
import urllib
|
||||
import logging
|
||||
import traceback
|
||||
import httplib
|
||||
import re
|
||||
import PluginBase
|
||||
from subliminal import encodingKludge as ek
|
||||
|
||||
|
||||
class Subtitulos(PluginBase.PluginBase):
|
||||
site_url = 'http://www.subtitulos.es'
|
||||
site_name = 'Subtitulos'
|
||||
server_url = 'http://www.subtitulos.es'
|
||||
multi_languages_queries = True
|
||||
multi_filename_queries = False
|
||||
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, filenames, languages):
|
||||
"""Main method to call when you want to list subtitles"""
|
||||
# as self.multi_filename_queries is false, we won't have multiple filenames in the list so pick the only one
|
||||
# once multi-filename queries are implemented, set multi_filename_queries to true and manage a list of multiple filenames here
|
||||
if not self.checkLanguages(languages):
|
||||
return []
|
||||
filepath = filenames[0]
|
||||
guess = guessit.guess_file_info(filepath, 'autodetect')
|
||||
if guess['type'] != '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 len(release_group) == 0:
|
||||
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):
|
||||
"""Make a query and returns info about found subtitles"""
|
||||
sublinks = []
|
||||
searchname = name.lower().replace(" ", "-")
|
||||
searchurl = "%s/%s/%sx%.2d" % (self.server_url, 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()], [".", "_", " ", "/"])
|
||||
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.findAllNext("ul", {"class": "sslist"}):
|
||||
sub_language = self.getRevertLanguage(html_language.findNext("li", {"class": "li-idioma"}).find("strong").contents[0].string.strip())
|
||||
if languages and 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 = {}
|
||||
result["release"] = "%s.S%.2dE%.2d.%s" % (name.replace(" ", "."), int(season), int(episode), '.'.join(sub_teams))
|
||||
result["lang"] = sub_language
|
||||
result["link"] = sub_link
|
||||
result["page"] = searchurl
|
||||
result["filename"] = filepath
|
||||
result["plugin"] = self.getClassName()
|
||||
result["teams"] = sub_teams # used to sort
|
||||
sublinks.append(result)
|
||||
sublinks.sort(self._cmpTeams)
|
||||
return sublinks
|
||||
|
||||
def download(self, subtitle):
|
||||
"""
|
||||
Pass the URL of the sub and the file it matches, will unzip it
|
||||
and return the path to the created file
|
||||
"""
|
||||
suburl = subtitle["link"]
|
||||
videofilename = subtitle["filename"]
|
||||
srtbasefilename = videofilename.rsplit(".", 1)[0]
|
||||
srtfilename = srtbasefilename + ".srt"
|
||||
self.downloadFile(suburl, srtfilename)
|
||||
return srtfilename
|
||||
|
||||
def downloadFile(self, url, filename):
|
||||
"""Downloads the given url to the given filename"""
|
||||
req = urllib2.Request(url, headers={'Referer': url, 'User-Agent': 'Mozilla/5.0 (X11; U; Linux x86_64; en-US; rv:1.9.1.3)'})
|
||||
f = urllib2.urlopen(req)
|
||||
dump = ek.ek(open, filename, "wb")
|
||||
dump.write(f.read())
|
||||
dump.close()
|
||||
f.close()
|
||||
|
||||
def _cmpTeams(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,125 +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 import encodingKludge as ek
|
||||
|
||||
|
||||
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
|
||||
multi_languages_queries = True
|
||||
multi_filename_queries = False
|
||||
api_based = True
|
||||
user_agent = 'SubDB/1.0 (Subliminal/0.1; https://github.com/Diaoul/subliminal)' # defined by the API
|
||||
_plugin_languages = {'cs': 'cs', # the whole list is available with the API: http://sandbox.thesubdb.com/?action=languages
|
||||
'da': 'da',
|
||||
'de': 'de',
|
||||
'en': 'en',
|
||||
'fi': 'fi',
|
||||
'fr': 'fr',
|
||||
'hu': 'hu',
|
||||
'id': 'id',
|
||||
'it': 'it',
|
||||
'nl': 'nl',
|
||||
'no': 'no',
|
||||
'pl': 'pl',
|
||||
'pt': 'pt',
|
||||
'ro': 'ro',
|
||||
'ru': 'ru',
|
||||
'sl': 'sl',
|
||||
'sr': 'sr',
|
||||
'sv': 'sv',
|
||||
'tr': 'tr'}
|
||||
|
||||
def __init__(self, config_dict=None):
|
||||
super(TheSubDB, self).__init__(self._plugin_languages, config_dict)
|
||||
|
||||
def list(self, filenames, languages):
|
||||
"""Main method to call when you want to list subtitles"""
|
||||
# as self.multi_filename_queries is false, we won't have multiple filenames in the list so pick the only one
|
||||
# once multi-filename queries are implemented, set multi_filename_queries to true and manage a list of multiple filenames here
|
||||
filepath = filenames[0]
|
||||
if not ek.ek(os.path.isfile, filepath):
|
||||
return []
|
||||
return self.query(filepath, self.hashFile(filepath), languages)
|
||||
|
||||
def query(self, filepath, moviehash, languages=None):
|
||||
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 not languages or l in languages:
|
||||
result = {}
|
||||
result['release'] = filepath
|
||||
result['lang'] = l
|
||||
result['link'] = "%s/?action=download&hash=%s&language=%s" % (self.server_url, moviehash, l)
|
||||
result['page'] = result['link']
|
||||
result['filename'] = filepath
|
||||
result['plugin'] = self.getClassName()
|
||||
subs.append(result)
|
||||
return subs
|
||||
|
||||
def hashFile(self, name):
|
||||
"""This hash function receives the filename and returns the hash code"""
|
||||
readsize = 64 * 1024
|
||||
with ek.ek(open, name, 'rb') as f:
|
||||
size = ek.ek(os.path.getsize, name)
|
||||
data = f.read(readsize)
|
||||
f.seek(-readsize, os.SEEK_END)
|
||||
data += f.read(readsize)
|
||||
return hashlib.md5(data).hexdigest()
|
||||
|
||||
def download(self, subtitle):
|
||||
"""Main method to call when you want to download a subtitle"""
|
||||
suburl = subtitle["link"]
|
||||
videofilename = subtitle["filename"]
|
||||
srtfilename = videofilename.rsplit(".", 1)[0] + self.getExtension(subtitle)
|
||||
self.downloadFile(suburl, srtfilename)
|
||||
return srtfilename
|
||||
|
||||
def downloadFile(self, url, srtfilename):
|
||||
"""Downloads the given url to the given filename"""
|
||||
req = urllib2.Request(url)
|
||||
req.add_header('User-Agent', self.user_agent)
|
||||
f = urllib2.urlopen(req)
|
||||
dump = open(srtfilename, "wb")
|
||||
dump.write(f.read())
|
||||
dump.close()
|
||||
f.close()
|
||||
@@ -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 SubtitleSource import SubtitleSource
|
||||
from Subtitulos import Subtitulos
|
||||
from TheSubDB import TheSubDB
|
||||
@@ -0,0 +1,131 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
from __future__ import unicode_literals
|
||||
import babelfish
|
||||
from ..video import Episode, Movie
|
||||
|
||||
|
||||
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
|
||||
|
||||
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,191 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
from __future__ import unicode_literals
|
||||
import logging
|
||||
import babelfish
|
||||
import bs4
|
||||
import charade
|
||||
import requests
|
||||
from . import Provider
|
||||
from .. import __version__
|
||||
from ..cache import region
|
||||
from ..exceptions import ProviderConfigurationError, ProviderNotAvailable, InvalidSubtitle
|
||||
from ..subtitle import Subtitle, is_valid_subtitle
|
||||
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 = {babelfish.Language('por', 'BR')} | {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 __init__(self, username=None, password=None):
|
||||
if username is not None and password is None or username is None and password is not None:
|
||||
raise ProviderConfigurationError('Username and password must be specified')
|
||||
self.username = username
|
||||
self.password = password
|
||||
self.logged_in = False
|
||||
|
||||
def initialize(self):
|
||||
self.session = requests.Session()
|
||||
self.session.headers = {'User-Agent': 'Subliminal/%s' % __version__}
|
||||
# login
|
||||
if self.username is not None and self.password is not None:
|
||||
logger.debug('Logging in')
|
||||
data = {'username': self.username, 'password': self.password, 'Submit': 'Log in'}
|
||||
try:
|
||||
r = self.session.post(self.server + '/dologin.php', data, timeout=10, allow_redirects=False)
|
||||
except requests.Timeout:
|
||||
raise ProviderNotAvailable('Timeout after 10 seconds')
|
||||
if r.status_code == 302:
|
||||
logger.info('Logged in')
|
||||
self.logged_in = True
|
||||
else:
|
||||
logger.error('Failed to login')
|
||||
|
||||
def terminate(self):
|
||||
# logout
|
||||
if self.logged_in:
|
||||
try:
|
||||
r = self.session.get(self.server + '/logout.php', timeout=10)
|
||||
logger.info('Logged out')
|
||||
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)
|
||||
self.session.close()
|
||||
|
||||
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[html_show.string.lower()] = 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()
|
||||
if series.lower() in show_ids:
|
||||
show_id = show_ids[series.lower()]
|
||||
else:
|
||||
show_id = self.find_show_id(series.lower())
|
||||
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
|
||||
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,135 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
from __future__ import unicode_literals
|
||||
import logging
|
||||
import urllib
|
||||
import babelfish
|
||||
import charade
|
||||
import guessit
|
||||
import requests
|
||||
import xml.etree.ElementTree
|
||||
from . import Provider
|
||||
from .. import __version__
|
||||
from ..cache import region
|
||||
from ..exceptions import InvalidSubtitle, ProviderNotAvailable, ProviderError
|
||||
from ..subtitle import Subtitle, is_valid_subtitle, compute_guess_matches
|
||||
from ..video import Episode
|
||||
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class BierDopjeSubtitle(Subtitle):
|
||||
provider_name = 'bierdopje'
|
||||
|
||||
def __init__(self, language, season, episode, tvdb_id, series, filename, download_link):
|
||||
super(BierDopjeSubtitle, self).__init__(language)
|
||||
self.season = season
|
||||
self.episode = episode
|
||||
self.tvdb_id = tvdb_id
|
||||
self.series = series
|
||||
self.filename = filename
|
||||
self.download_link = download_link
|
||||
|
||||
def compute_matches(self, video):
|
||||
matches = set()
|
||||
# tvdb_id
|
||||
if video.tvdb_id and self.tvdb_id == video.tvdb_id:
|
||||
matches.add('tvdb_id')
|
||||
# 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')
|
||||
matches |= compute_guess_matches(video, guessit.guess_episode_info(self.filename + '.mkv'))
|
||||
return matches
|
||||
|
||||
|
||||
class BierDopjeProvider(Provider):
|
||||
languages = {babelfish.Language(l) for l in ['eng', 'nld']}
|
||||
video_types = (Episode,)
|
||||
|
||||
def initialize(self):
|
||||
self.session = requests.Session()
|
||||
self.session.headers = {'User-Agent': 'Subliminal/%s' % __version__}
|
||||
|
||||
def terminate(self):
|
||||
self.session.close()
|
||||
|
||||
def get(self, url, **params):
|
||||
"""Make a GET request on the `url` formatted with `**params`
|
||||
|
||||
:param string url: API part of the URL to reach without the leading slash
|
||||
:param \*\*params: format specs for the `url`
|
||||
:return: the response
|
||||
:rtype: :class:`xml.etree.ElementTree.Element`
|
||||
:raise: :class:`~subliminal.exceptions.ProviderNotAvailable`
|
||||
|
||||
"""
|
||||
try:
|
||||
r = self.session.get('http://api.bierdopje.com/A2B638AC5D804C2E/' + url.format(**params), timeout=10)
|
||||
except requests.Timeout:
|
||||
raise ProviderNotAvailable('Timeout after 10 seconds')
|
||||
if r.status_code == 429:
|
||||
raise ProviderNotAvailable('Too Many Requests')
|
||||
elif r.status_code != 200:
|
||||
raise ProviderError('Request failed with status code %d' % r.status_code)
|
||||
return xml.etree.ElementTree.fromstring(r.content)
|
||||
|
||||
@region.cache_on_arguments()
|
||||
def find_show_id(self, series):
|
||||
"""Find the show id from series name
|
||||
|
||||
:param string series: series of the episode
|
||||
:return: show id
|
||||
:rtype: int
|
||||
|
||||
"""
|
||||
logger.debug('Searching for series %r', series)
|
||||
root = self.get('FindShowByName/{series}', series=urllib.quote(series))
|
||||
if root.find('response/status').text == 'false':
|
||||
logger.info('Series %r not found', series)
|
||||
return None
|
||||
return int(root.find('response/results/result[1]/showid').text)
|
||||
|
||||
def query(self, language, season, episode, tvdb_id=None, series=None):
|
||||
params = {'language': language.alpha2, 'season': season, 'episode': episode}
|
||||
if tvdb_id is not None:
|
||||
params['showid'] = tvdb_id
|
||||
params['istvdbid'] = 'true'
|
||||
elif series is not None:
|
||||
show_id = self.find_show_id(series)
|
||||
if show_id is None:
|
||||
return []
|
||||
params['showid'] = show_id
|
||||
params['istvdbid'] = 'false'
|
||||
else:
|
||||
raise ValueError('Missing parameter tvdb_id or series')
|
||||
logger.debug('Searching subtitles %r', params)
|
||||
root = self.get('GetAllSubsFor/{showid}/{season}/{episode}/{language}/{istvdbid}', **params)
|
||||
if root.find('response/status').text == 'false':
|
||||
logger.debug('No subtitle found')
|
||||
return []
|
||||
logger.debug('Found subtitles %r', root.find('response/results'))
|
||||
return [BierDopjeSubtitle(language, season, episode, tvdb_id, series, result.find('filename').text,
|
||||
result.find('downloadlink').text) for result in root.find('response/results')]
|
||||
|
||||
def list_subtitles(self, video, languages):
|
||||
return [s for l in languages for s in self.query(l, video.season, video.episode, video.tvdb_id, video.series)]
|
||||
|
||||
def download_subtitle(self, subtitle):
|
||||
try:
|
||||
r = self.session.get(subtitle.download_link, timeout=10)
|
||||
except requests.Timeout:
|
||||
raise ProviderNotAvailable('Timeout after 10 seconds')
|
||||
if r.status_code == 429:
|
||||
raise ProviderNotAvailable('Too Many Requests')
|
||||
elif 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,159 @@
|
||||
# -*- 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 ..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, 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 self.series_name.lower() == video.series.lower():
|
||||
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 self.movie_name.lower() == video.title.lower():
|
||||
matches.add('title')
|
||||
return matches
|
||||
|
||||
|
||||
class OpenSubtitlesProvider(Provider):
|
||||
languages = {babelfish.Language.fromopensubtitles(l) for l in babelfish.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):
|
||||
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,163 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
from __future__ import unicode_literals
|
||||
import io
|
||||
import logging
|
||||
import re
|
||||
import xml.etree.ElementTree
|
||||
import zipfile
|
||||
import babelfish
|
||||
import bs4
|
||||
import charade
|
||||
import guessit
|
||||
import requests
|
||||
from . import Provider
|
||||
from .. import __version__
|
||||
from ..exceptions import InvalidSubtitle, ProviderNotAvailable, ProviderError
|
||||
from ..subtitle import Subtitle, is_valid_subtitle, compute_guess_matches
|
||||
from ..video import Episode, Movie
|
||||
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class PodnapisiSubtitle(Subtitle):
|
||||
provider_name = 'podnapisi'
|
||||
|
||||
def __init__(self, language, id, releases, hearing_impaired, link, series=None, season=None, episode=None,
|
||||
title=None, year=None):
|
||||
super(PodnapisiSubtitle, self).__init__(language, hearing_impaired)
|
||||
self.id = id
|
||||
self.releases = releases
|
||||
self.hearing_impaired = hearing_impaired
|
||||
self.link = 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 self.series.lower() == video.series.lower():
|
||||
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 self.title.lower() == video.title.lower():
|
||||
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 = {babelfish.Language.frompodnapisi(l) for l in babelfish.CONVERTERS['podnapisi'].codes}
|
||||
video_types = (Episode, Movie)
|
||||
server = 'http://simple.podnapisi.net'
|
||||
link_re = re.compile('^.*(?P<link>/ppodnapisi/download/i/\d+/k/.*$)')
|
||||
|
||||
def initialize(self):
|
||||
self.session = requests.Session()
|
||||
self.session.headers = {'User-Agent': 'Subliminal/%s' % __version__}
|
||||
|
||||
def terminate(self):
|
||||
self.session.close()
|
||||
|
||||
def get(self, url, params=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 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`
|
||||
|
||||
"""
|
||||
try:
|
||||
r = self.session.get(self.server + '/ppodnapisi' + 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)
|
||||
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('/search', params)
|
||||
if not int(root.find('pagination/results').text):
|
||||
logger.debug('No subtitle found')
|
||||
break
|
||||
if series and season and episode:
|
||||
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')])
|
||||
elif title:
|
||||
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')])
|
||||
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)
|
||||
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 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):
|
||||
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 = {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):
|
||||
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
|
||||
{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,175 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
from __future__ import unicode_literals
|
||||
import io
|
||||
import logging
|
||||
import re
|
||||
import zipfile
|
||||
import babelfish
|
||||
import bs4
|
||||
import charade
|
||||
import requests
|
||||
from . import Provider
|
||||
from .. import __version__
|
||||
from ..cache import region
|
||||
from ..exceptions import InvalidSubtitle, ProviderNotAvailable, ProviderError
|
||||
from ..subtitle import Subtitle, is_valid_subtitle
|
||||
from ..video import Episode
|
||||
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class TVsubtitlesSubtitle(Subtitle):
|
||||
provider_name = 'tvsubtitles'
|
||||
|
||||
def __init__(self, language, series, season, episode, id, rip, release):
|
||||
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 = {babelfish.Language('por', 'BR')} | {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': 'Subliminal/%s' % __version__}
|
||||
|
||||
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-"]')
|
||||
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
|
||||
if match.group('series').lower().replace('.', ' ').strip() == series.lower():
|
||||
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.lower())
|
||||
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 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')
|
||||
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,425 +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/>.
|
||||
#
|
||||
|
||||
from itertools import groupby
|
||||
import ConfigParser
|
||||
import PluginWorker
|
||||
import Queue
|
||||
import locale
|
||||
import logging
|
||||
import mimetypes
|
||||
import os
|
||||
import plugins
|
||||
import sys
|
||||
import traceback
|
||||
import locale
|
||||
import encodingKludge as ek
|
||||
|
||||
|
||||
SUPPORTED_FORMATS = 'video/x-msvideo', 'video/quicktime', 'video/x-matroska', 'video/mp4'
|
||||
logger = logging.getLogger('subliminal')
|
||||
SYS_ENCODING = None
|
||||
try:
|
||||
locale.setlocale(locale.LC_ALL, "")
|
||||
SYS_ENCODING = locale.getpreferredencoding()
|
||||
except (locale.Error, IOError):
|
||||
pass
|
||||
# for OSes that are poorly configured I'll just force UTF-8
|
||||
if not SYS_ENCODING or SYS_ENCODING in ('ANSI_X3.4-1968', 'US-ASCII', 'ASCII'):
|
||||
SYS_ENCODING = 'UTF-8'
|
||||
|
||||
|
||||
class Subliminal(object):
|
||||
"""Main Subliminal class"""
|
||||
|
||||
def __init__(self, config=True, cache_dir=True, workers=4, multi=False, force=False, max_depth=3, autostart=False, plugins_config=None):
|
||||
# set default values
|
||||
self.multi = multi
|
||||
self.force = force
|
||||
self.max_depth = max_depth
|
||||
self.config = None
|
||||
self.config_file = None
|
||||
self.cache_dir = None
|
||||
self.taskQueue = Queue.Queue()
|
||||
self.resultQueue = Queue.Queue()
|
||||
self._languages = None
|
||||
self._plugins = self.listAPIPlugins()
|
||||
self.workers = workers
|
||||
self.plugins_config = plugins_config
|
||||
if autostart:
|
||||
self.startWorkers()
|
||||
# handle configuration file preferences
|
||||
try:
|
||||
if config == True: # default configuration file
|
||||
import xdg.BaseDirectory as bd
|
||||
self.config = ConfigParser.SafeConfigParser({"languages": "", "plugins": ""})
|
||||
self.config_file = ek.ek(os.path.join, bd.xdg_config_home, "subliminal", "config.ini")
|
||||
if not ek.ek(os.path.exists, self.config_file): # configuration file doesn't exist, create it
|
||||
self._createConfigFile()
|
||||
else: # configuration file exists, load it
|
||||
self._loadConfigFile()
|
||||
elif config: # custom configuration file
|
||||
self.config = ConfigParser.SafeConfigParser({"languages": "", "plugins": ""})
|
||||
self.config_file = config
|
||||
if not ek.ek(os.path.isfile, self.config_file): # custom configuration file doesn't exist, create it
|
||||
self._createConfigFile()
|
||||
else:
|
||||
self._loadConfigFile()
|
||||
except:
|
||||
self.config = None
|
||||
self.config_file = None
|
||||
logger.error(u"Failed to use the configuration file, continue without it")
|
||||
raise
|
||||
# handle cache directory preferences
|
||||
try:
|
||||
if cache_dir == True: # default cache directory
|
||||
import xdg.BaseDirectory as bd
|
||||
self.cache_dir = ek.ek(os.path.join, bd.xdg_config_home, "subliminal", "cache")
|
||||
if not ek.ek(os.path.exists, self.cache_dir): # cache directory doesn't exist, create it
|
||||
ek.ek(os.mkdir, self.cache_dir)
|
||||
logger.debug(u'Creating cache directory: %s' % self.cache_dir)
|
||||
elif cache_dir: # custom configuration file
|
||||
self.cache_dir = cache_dir
|
||||
if not ek.ek(os.path.isdir, self.cache_dir): # custom v file doesn't exist, create it
|
||||
ek.ek(os.mkdir, self.cache_dir)
|
||||
logger.debug(u'Creating cache directory: %s' % self.cache_dir)
|
||||
except:
|
||||
self.cache_dir = None
|
||||
logger.error(u"Failed to use the cache directory, continue without it")
|
||||
|
||||
def _loadConfigFile(self):
|
||||
"""Load a configuration file specified in self.config_file"""
|
||||
self.config.read(self.config_file)
|
||||
self._loadLanguagesFromConfig()
|
||||
self._loadPluginsFromConfig()
|
||||
|
||||
def _createConfigFile(self):
|
||||
"""Create a configuration file specified in self.config_file"""
|
||||
folder = ek.ek(os.path.dirname, self.config_file)
|
||||
if not ek.ek(os.path.exists, folder):
|
||||
logger.info(u"Creating folder: %s" % folder)
|
||||
ek.ek(os.mkdir, folder)
|
||||
# try to load a language from system
|
||||
self._loadLanguageFromSystem()
|
||||
self.config.set("DEFAULT", "languages", ",".join(self._languages))
|
||||
self.config.set("DEFAULT", "plugins", ",".join(self._plugins))
|
||||
self.config.add_section("SubtitleSource")
|
||||
self.config.set("SubtitleSource", "key", "")
|
||||
self._writeConfigFile()
|
||||
logger.info(u"Creating configuration file: %s" % self.config_file)
|
||||
logger.debug(u"Languages in created configuration file: %s" % self._languages)
|
||||
logger.debug(u"Plugins in created configuration file: %s" % self._plugins)
|
||||
|
||||
@staticmethod
|
||||
def listExistingPlugins():
|
||||
"""List all possible plugins"""
|
||||
return map(lambda x: x.__name__, plugins.PluginBase.PluginBase.__subclasses__())
|
||||
|
||||
@staticmethod
|
||||
def listAPIPlugins():
|
||||
"""List plugins that use API"""
|
||||
return filter(Subliminal.isAPIBasedPlugin, Subliminal.listExistingPlugins())
|
||||
|
||||
def _writeConfigFile(self):
|
||||
"""Write the configuration file"""
|
||||
configfile = open(self.config_file, "w")
|
||||
self.config.write(configfile)
|
||||
configfile.close()
|
||||
|
||||
def get_languages(self):
|
||||
"""Get current languages"""
|
||||
return self._languages
|
||||
|
||||
def set_languages(self, value):
|
||||
"""Set languages and save to configuration file if specified by the constructor"""
|
||||
logger.debug(u"Setting languages to %s" % value)
|
||||
self._languages = value
|
||||
if self.config:
|
||||
self._saveLanguagesToConfig()
|
||||
|
||||
@staticmethod
|
||||
def isValidLanguage(language):
|
||||
"""Check if a language is valid"""
|
||||
if len(language) != 2:
|
||||
logger.error(u"Language %s is not valid" % language)
|
||||
return False
|
||||
return True
|
||||
|
||||
def _saveLanguagesToConfig(self):
|
||||
"""Save languages to configuration file"""
|
||||
logger.debug(u"Saving languages %s to configuration file" % self._languages)
|
||||
self.config.set("DEFAULT", "languages", ",".join(self._languages))
|
||||
self._writeConfigFile()
|
||||
|
||||
def _loadLanguagesFromConfig(self):
|
||||
"""Load languages from configuration file"""
|
||||
configLanguages = self.config.get("DEFAULT", "languages")
|
||||
logger.debug(u"Loading languages %s from configuration file" % configLanguages)
|
||||
if not configLanguages:
|
||||
self._languages = None
|
||||
return
|
||||
self._languages = filter(self.isValidLanguage, map(str.strip, configLanguages.split(",")))
|
||||
|
||||
def _loadLanguageFromSystem(self):
|
||||
"""Load language from system"""
|
||||
logger.debug(u"Loading language from system")
|
||||
try:
|
||||
self._languages = [locale.getdefaultlocale()[0][:2]]
|
||||
logger.debug(u"Language %s loaded from system" % self._languages)
|
||||
except:
|
||||
logger.warning(u"Could not read language from system")
|
||||
|
||||
def get_plugins(self):
|
||||
"""Get current plugins"""
|
||||
return self._plugins
|
||||
|
||||
def set_plugins(self, value):
|
||||
"""Set plugins and save to configuration file if specified by the constructor"""
|
||||
logger.debug(u"Setting plugins to %s" % value)
|
||||
self._plugins = filter(self.isValidPlugin, value)
|
||||
if self.config:
|
||||
self._savePluginsToConfig()
|
||||
|
||||
@staticmethod
|
||||
def isValidPlugin(pluginName):
|
||||
"""Check if a plugin is valid (exists)"""
|
||||
if pluginName not in Subliminal.listExistingPlugins():
|
||||
logger.error(u"Plugin %s does not exist" % pluginName)
|
||||
return False
|
||||
return True
|
||||
|
||||
@staticmethod
|
||||
def isAPIBasedPlugin(pluginName):
|
||||
"""Check if a plugin is API-based"""
|
||||
if not getattr(plugins, pluginName).api_based:
|
||||
return False
|
||||
return True
|
||||
|
||||
def _savePluginsToConfig(self):
|
||||
"""Save plugins to configuration file"""
|
||||
logger.debug(u"Saving plugins %s to configuration file" % self._plugins)
|
||||
self.config.set("DEFAULT", "plugins", ",".join(self._plugins))
|
||||
self._writeConfigFile()
|
||||
|
||||
def _loadPluginsFromConfig(self):
|
||||
"""Load plugins from configuration file"""
|
||||
configPlugins = self.config.get("DEFAULT", "plugins")
|
||||
logger.debug(u"Loading plugins %s from configuration file" % configPlugins)
|
||||
self._plugins = filter(self.isValidPlugin, map(str.strip, configPlugins.split(",")))
|
||||
|
||||
# getters/setters for the property _languages and _plugins
|
||||
languages = property(get_languages, set_languages)
|
||||
plugins = property(get_plugins, set_plugins)
|
||||
|
||||
def deactivatePlugin(self, plugin):
|
||||
"""Deactivate a plugin"""
|
||||
self._plugins.remove(plugin)
|
||||
if self.config:
|
||||
self._savePluginsToConfig()
|
||||
|
||||
def activatePlugin(self, plugin):
|
||||
"""Activate a plugin"""
|
||||
if self.isValidPlugin(plugin):
|
||||
self._plugins.append(plugin)
|
||||
if self.config:
|
||||
self._savePluginsToConfig()
|
||||
|
||||
def listSubtitles(self, entries):
|
||||
"""
|
||||
Searches subtitles within the active plugins and returns all found matching subtitles.
|
||||
entries can be:
|
||||
- filepaths
|
||||
- folderpaths (N.B. internal recursive search function will be used)
|
||||
- filenames
|
||||
"""
|
||||
search_results = []
|
||||
if isinstance(entries, basestring):
|
||||
entries = [ek.fixStupidEncodings(entries)]
|
||||
elif not isinstance(entries, list):
|
||||
raise TypeError('Entries should be a list or a string')
|
||||
for e in entries:
|
||||
search_results.extend(self._recursiveSearch(e))
|
||||
taskCount = 0
|
||||
for (l, f) in search_results:
|
||||
taskCount += self.searchSubtitlesThreaded(f, l)
|
||||
subtitles = []
|
||||
for i in range(taskCount):
|
||||
subtitles.extend(self.resultQueue.get(timeout=10))
|
||||
return subtitles
|
||||
|
||||
@staticmethod
|
||||
def arrangeSubtitles(subtitles):
|
||||
"""Arrange subtitles in a handy dict by filename, language and plugin"""
|
||||
arrangedSubtitles = {}
|
||||
for (filename, subsByFilename) in groupby(sorted(subtitles, key=lambda x: x["filename"]), lambda x: x["filename"]):
|
||||
arrangedSubtitles[filename] = {}
|
||||
for (language, subsByFilenameByLanguage) in groupby(sorted(subsByFilename, key=lambda x: x["lang"]), lambda x: x["lang"]):
|
||||
arrangedSubtitles[filename][language] = {}
|
||||
for (plugin, subsByFilenameByLanguageByPlugin) in groupby(sorted(subsByFilenameByLanguage, key=lambda x: x["plugin"]), lambda x: x["plugin"]):
|
||||
arrangedSubtitles[filename][language][plugin] = sorted(list(subsByFilenameByLanguageByPlugin))
|
||||
return arrangedSubtitles
|
||||
|
||||
def sortSubtitlesRaw(self, subtitles):
|
||||
"""Sort subtitles using user defined languages and plugins"""
|
||||
return sorted(subtitles, cmp=self._cmpSubtitles)
|
||||
|
||||
def _cmpSubtitles(self, x, y):
|
||||
"""
|
||||
Compares 2 subtitles elements x and y. Returns -1 if x < y, 0 if =, 1 if >
|
||||
Use filename, languages and plugin comparison
|
||||
"""
|
||||
filenames = sorted([x['filename'], y['filename']])
|
||||
if x['filename'] != y['filename'] and filenames.index(x['filename']) < filenames(y['filename']):
|
||||
return - 1
|
||||
if x['filename'] != y['filename'] and filenames.index(x['filename']) > filenames(y['filename']):
|
||||
return 1
|
||||
if self._languages and self._languages.index(x['lang']) < self._languages.index(y['lang']):
|
||||
return - 1
|
||||
if self._languages and self._languages.index(x['lang']) > self._languages.index(y['lang']):
|
||||
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 searchSubtitlesThreaded(self, filenames, languages):
|
||||
"""
|
||||
Makes workers search for subtitles in different languages for multiple filenames and puts the result in the result queue.
|
||||
Aslo split the work in multiple tasks
|
||||
When the function returns, all the results may not be available yet!
|
||||
"""
|
||||
logger.info(u"Searching subtitles for %s with languages %s" % (filenames, languages))
|
||||
tasks = []
|
||||
for pluginName in self._plugins:
|
||||
try:
|
||||
plugin = getattr(plugins, pluginName)(self.getConfigDict())
|
||||
except:
|
||||
logger.debug(traceback.print_exc())
|
||||
continue
|
||||
# split tasks if the plugin can't handle multi-thing queries
|
||||
tasks.extend(plugin.splitTask({'task': 'list', 'plugin': pluginName, 'languages': languages, 'filenames': filenames, 'config': self.getConfigDict()}))
|
||||
for t in tasks:
|
||||
self.taskQueue.put(t)
|
||||
return len(tasks)
|
||||
|
||||
def downloadSubtitlesThreaded(self, subtitles):
|
||||
"""
|
||||
Makes workers download subtitles and puts the result in the result queue.
|
||||
When the function returns, all the results may not be available yet!
|
||||
"""
|
||||
# 1 task per file if not multi, 1 task per file and per language if multi
|
||||
taskCount = 0
|
||||
for (filename, subsByFilename) in groupby(sorted(subtitles, key=lambda x: x["filename"]), lambda x: x["filename"]):
|
||||
if not self.multi:
|
||||
self.taskQueue.put({'task': 'download', 'subtitle': sorted(list(subsByFilename), cmp=self._cmpSubtitles), 'config': self.getConfigDict()})
|
||||
taskCount += 1
|
||||
continue
|
||||
for (language, subsByFilenameByLanguage) in groupby(sorted(subsByFilename, key=lambda x: x["lang"]), lambda x: x["lang"]):
|
||||
self.taskQueue.put({'task': 'download', 'subtitle': sorted(list(subsByFilenameByLanguage), cmp=self._cmpSubtitles), 'config': self.getConfigDict()})
|
||||
taskCount += 1
|
||||
return taskCount
|
||||
|
||||
def downloadSubtitles(self, entries):
|
||||
"""Download subtitles recursivly in entries"""
|
||||
subtitles = self.listSubtitles(entries)
|
||||
taskCount = self.downloadSubtitlesThreaded(subtitles)
|
||||
paths = []
|
||||
for i in range(taskCount):
|
||||
paths.append(self.resultQueue.get(timeout=10))
|
||||
return paths
|
||||
|
||||
def _recursiveSearch(self, entry, depth=0):
|
||||
"""
|
||||
Searches files in the entry
|
||||
This will output a list of tuples (filename, languages)
|
||||
"""
|
||||
if depth > self.max_depth and self.max_depth != 0: # we do not want to search the whole file system except if max_depth = 0
|
||||
return []
|
||||
if ek.ek(os.path.isfile, entry): # a file? scan it
|
||||
if depth != 0: # only check for valid format if recursing, trust the user
|
||||
mimetypes.add_type("video/x-matroska", ".mkv")
|
||||
mimetype = mimetypes.guess_type(entry)[0]
|
||||
if mimetype not in SUPPORTED_FORMATS:
|
||||
return []
|
||||
basepath = ek.fixStupidEncodings(ek.ek(os.path.splitext, entry)[0])
|
||||
# check for .xx.srt if needed
|
||||
if self.multi and self.languages:
|
||||
if self.force:
|
||||
return [(self.languages, [ek.ek(os.path.normpath, entry)])]
|
||||
needed_languages = self.languages[:]
|
||||
for l in self.languages:
|
||||
if ek.ek(os.path.exists, basepath + '.%s.srt' % l):
|
||||
logger.info(u"Skipping language %s for file %s as it already exists. Use the --force option to force the download" % (l, entry))
|
||||
needed_languages.remove(l)
|
||||
if needed_languages:
|
||||
return [(needed_languages, [ek.ek(os.path.normpath, entry)])]
|
||||
return []
|
||||
# single subtitle download: .srt
|
||||
if self.force or not ek.ek(os.path.exists, basepath + '.srt'):
|
||||
return [(self.languages, [ek.ek(os.path.normpath, entry)])]
|
||||
if ek.ek(os.path.isdir, entry): # a dir? recurse
|
||||
#TODO if hidden folder, don't keep going (how to handle windows/mac/linux ?)
|
||||
files = []
|
||||
for e in ek.ek(os.listdir, entry):
|
||||
files.extend(self._recursiveSearch(ek.ek(os.path.join, entry, e), depth + 1))
|
||||
files.sort()
|
||||
grouped_files = []
|
||||
for languages, group in groupby(files, lambda t: t[0]):
|
||||
filenames = []
|
||||
for t in group:
|
||||
filenames.extend(t[1])
|
||||
grouped_files.append((languages, filenames))
|
||||
return grouped_files
|
||||
return [] # anything else, nothing.
|
||||
|
||||
def startWorkers(self):
|
||||
"""Create a pool of workers and start them"""
|
||||
self.pool = []
|
||||
for i in range(self.workers):
|
||||
worker = PluginWorker.PluginWorker(self.taskQueue, self.resultQueue)
|
||||
worker.start()
|
||||
self.pool.append(worker)
|
||||
logger.debug(u"Worker %s added to the pool" % worker.name)
|
||||
|
||||
def sendStopSignal(self):
|
||||
"""Send a stop signal the pool of workers (poison pill)"""
|
||||
logger.debug(u"Sending %d poison pills into the task queue" % self.workers)
|
||||
for i in range(self.workers):
|
||||
self.taskQueue.put(None)
|
||||
|
||||
def stopWorkers(self):
|
||||
"""Stop workers using a stop signal and wait for them to terminate properly"""
|
||||
self.sendStopSignal()
|
||||
for worker in self.pool:
|
||||
worker.join()
|
||||
|
||||
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
|
||||
if self.config:
|
||||
config['subtitlesource_key'] = self.config.get('SubtitleSource', 'key')
|
||||
if self.plugins_config and 'subtitlesource_key' in self.plugins_config:
|
||||
config['subtitlesource_key'] = self.plugins_config['subtitlesource_key']
|
||||
config['force'] = self.force
|
||||
return config
|
||||
@@ -0,0 +1,156 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
from __future__ import unicode_literals
|
||||
import logging
|
||||
import os.path
|
||||
import babelfish
|
||||
import pysrt
|
||||
from .video import Episode, Movie
|
||||
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
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):
|
||||
"""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`
|
||||
: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 -= {'series', 'tvdb_id', 'season', 'episode', 'title'}
|
||||
if 'tvdb_id' in matches:
|
||||
matches -= {'series'}
|
||||
if 'title' in matches:
|
||||
matches -= {'season', 'episode'}
|
||||
# add other scores
|
||||
score += sum((video.scores[match] for match in matches))
|
||||
logger.info('Computed score %d with matches %r', score, initial_matches)
|
||||
return score
|
||||
|
||||
def __repr__(self):
|
||||
return '<%s [%s]>' % (self.__class__.__name__, self.language)
|
||||
|
||||
|
||||
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.ConvertError:
|
||||
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:
|
||||
pass
|
||||
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
|
||||
@@ -1,206 +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 unittest
|
||||
import logging
|
||||
import os
|
||||
|
||||
|
||||
logging.basicConfig(level=logging.DEBUG, format='%(name)-24s %(levelname)-8s %(message)s')
|
||||
if not os.path.exists('/tmp/subliminal/cache'):
|
||||
os.mkdir('/tmp/subliminal/cache')
|
||||
config = {'multi': True, 'cache_dir': '/tmp/subliminal/cache', 'subtitlesource_key': '', 'force': False}
|
||||
|
||||
|
||||
class Addic7edListTestCase1(unittest.TestCase):
|
||||
def runTest(self):
|
||||
from subliminal.plugins import Addic7ed
|
||||
plugin = Addic7ed(config)
|
||||
results = plugin.list(["The.Big.Bang.Theory.S03E13.HDTV.XviD-2HD.mkv"], ["en", "fr"])
|
||||
print results
|
||||
assert len(results) > 0
|
||||
|
||||
|
||||
class Addic7edListTestCase2(unittest.TestCase):
|
||||
def runTest(self):
|
||||
from subliminal.plugins import Addic7ed
|
||||
plugin = Addic7ed(config)
|
||||
results = plugin.list(["Dexter.S05E02.720p.HDTV.x264-IMMERSE.mkv"], ["en", "fr"])
|
||||
print results
|
||||
assert len(results) > 0
|
||||
|
||||
|
||||
class Addic7edDownloadTestCase(unittest.TestCase):
|
||||
def runTest(self):
|
||||
from subliminal.plugins import Addic7ed
|
||||
plugin = Addic7ed(config)
|
||||
results = plugin.download(plugin.list(["/tmp/The.Big.Bang.Theory.S03E13.HDTV.XviD-2HD.mkv"], ["en", "fr"])[0])
|
||||
print results
|
||||
assert len(results) > 0
|
||||
|
||||
|
||||
class BierDopjeListTestCase(unittest.TestCase):
|
||||
def runTest(self):
|
||||
from subliminal.plugins import BierDopje
|
||||
plugin = BierDopje(config)
|
||||
results = plugin.list(["The.Big.Bang.Theory.S03E13.HDTV.XviD-2HD.mkv"], ["en", "fr"])
|
||||
print results
|
||||
assert len(results) > 0
|
||||
|
||||
|
||||
class BierDopjeListExceptionTestCase(unittest.TestCase):
|
||||
def runTest(self):
|
||||
from subliminal.plugins import BierDopje
|
||||
plugin = BierDopje(config)
|
||||
results = plugin.list(["The.Office.US.S07E08.Viewing.Party.HDTV.XviD-FQM.[VTV].avi"], ["en", "fr"])
|
||||
print results
|
||||
assert len(results) > 0
|
||||
|
||||
|
||||
class BierDopjeListTestCase(unittest.TestCase):
|
||||
def runTest(self):
|
||||
from subliminal.plugins import BierDopje
|
||||
plugin = BierDopje(config)
|
||||
results = plugin.list(["The.Big.Bang.Theory.S03E13.HDTV.XviD-2HD.mkv"], ["en", "fr"])
|
||||
print results
|
||||
assert len(results) > 0
|
||||
|
||||
|
||||
class OpenSubtitlesQueryTestCase(unittest.TestCase):
|
||||
def runTest(self):
|
||||
from subliminal.plugins import OpenSubtitles
|
||||
plugin = OpenSubtitles()
|
||||
results = plugin.query('Night.Watch.2004.CD1.DVDRiP.XViD-FiCO.avi', moviehash="09a2c497663259cb", bytesize="733589504") # http://trac.opensubtitles.org/projects/opensubtitles/wiki/XMLRPC
|
||||
print results
|
||||
assert len(results) > 0
|
||||
|
||||
|
||||
class OpenSubtitlesQueryNoHashTestCase(unittest.TestCase):
|
||||
def runTest(self):
|
||||
from subliminal.plugins import OpenSubtitles
|
||||
plugin = OpenSubtitles()
|
||||
results = plugin.query('Night.Watch.2004.CD1.DVDRiP.XViD-FiCO.avi', languages=['en', 'fr']) # http://trac.opensubtitles.org/projects/opensubtitles/wiki/XMLRPC
|
||||
print results
|
||||
assert len(results) > 0
|
||||
|
||||
|
||||
class OpenSubtitlesListTestCase(unittest.TestCase):
|
||||
def runTest(self):
|
||||
from subliminal.plugins import OpenSubtitles
|
||||
plugin = OpenSubtitles()
|
||||
results = plugin.download(plugin.query('/tmp/Night.Watch.2004.CD1.DVDRiP.XViD-FiCO.avi', moviehash="09a2c497663259cb", bytesize="733589504")[0]) # http://trac.opensubtitles.org/projects/opensubtitles/wiki/XMLRPC
|
||||
assert len(results) > 0
|
||||
|
||||
|
||||
class SubtitulosListTestCase(unittest.TestCase):
|
||||
def runTest(self):
|
||||
from subliminal.plugins import Subtitulos
|
||||
plugin = Subtitulos()
|
||||
results = plugin.list(["The.Big.Bang.Theory.S03E13.HDTV.XviD-2HD.mkv"], ['en', 'fr'])
|
||||
print results
|
||||
assert len(results) > 0
|
||||
|
||||
|
||||
class SubtitulosDownloadTestCase(unittest.TestCase):
|
||||
def runTest(self):
|
||||
from subliminal.plugins import Subtitulos
|
||||
plugin = Subtitulos()
|
||||
results = plugin.download(plugin.list(["/tmp/The.Big.Bang.Theory.S03E13.HDTV.XviD-2HD.mkv"], ['en', 'fr'])[0])
|
||||
print results
|
||||
assert len(results) > 0
|
||||
|
||||
|
||||
class TheSubDBQueryTestCase(unittest.TestCase):
|
||||
def runTest(self):
|
||||
from subliminal.plugins import TheSubDB
|
||||
plugin = TheSubDB()
|
||||
results = plugin.query("test.mkv", "edc1981d6459c6111fe36205b4aff6c2")
|
||||
print results
|
||||
assert len(results) > 0
|
||||
|
||||
|
||||
class TheSubDBDownloadTestCase(unittest.TestCase):
|
||||
def runTest(self):
|
||||
from subliminal.plugins import TheSubDB
|
||||
plugin = TheSubDB()
|
||||
results = plugin.download(plugin.query("/tmp/test.mkv", "edc1981d6459c6111fe36205b4aff6c2")[0])
|
||||
print results
|
||||
assert len(results) > 0
|
||||
|
||||
|
||||
class SubsWikiListTestCase(unittest.TestCase):
|
||||
def runTest(self):
|
||||
from subliminal.plugins import SubsWiki
|
||||
plugin = SubsWiki()
|
||||
results = plugin.list(["The.Big.Bang.Theory.S03E13.HDTV.XviD-2HD.mkv"], ['en', 'es'])
|
||||
print results
|
||||
assert len(results) > 0
|
||||
|
||||
|
||||
class SubsWikiDownloadTestCase(unittest.TestCase):
|
||||
def runTest(self):
|
||||
from subliminal.plugins import SubsWiki
|
||||
plugin = SubsWiki()
|
||||
results = plugin.download(plugin.list(["/tmp/The.Big.Bang.Theory.S03E13.HDTV.XviD-2HD.mkv"], ['en', 'es'])[0])
|
||||
print results
|
||||
assert len(results) > 0
|
||||
'''
|
||||
class PodnapisiQueryTestCase(unittest.TestCase):
|
||||
def runTest(self):
|
||||
from subliminal.plugins import Podnapisi
|
||||
plugin = Podnapisi()
|
||||
results = plugin.query('09a2c497663259cb', ["en", "fr"])
|
||||
print results
|
||||
assert len(results) > 5
|
||||
|
||||
|
||||
class SubSceneListTestCase(unittest.TestCase):
|
||||
def runTest(self):
|
||||
from subliminal.plugins import SubScene
|
||||
plugin = SubScene()
|
||||
results = plugin.list(["Dexter.S04E01.HDTV.XviD-NoTV.avi"], ['en', 'fr'])
|
||||
print results
|
||||
assert len(results) > 0, "No result could be found for Dexter.S04E01.HDTV.XviD-NoTV.avi and no languages"
|
||||
|
||||
|
||||
class SubSceneDownloadTestCase(unittest.TestCase):
|
||||
def runTest(self):
|
||||
from subliminal.plugins import SubScene
|
||||
plugin = SubScene()
|
||||
results = plugin.download(plugin.list(["Dexter.S04E01.HDTV.XviD-NoTV.avi"], ['en', 'fr'])[0])
|
||||
print results
|
||||
assert len(results) > 0, "No result could be found for Dexter.S04E01.HDTV.XviD-NoTV.avi and no languages"
|
||||
|
||||
|
||||
class SubtitleSourceListTestCase(unittest.TestCase):
|
||||
def runTest(self):
|
||||
from subliminal.plugins import SubtitleSource
|
||||
plugin = SubtitleSource()
|
||||
results = plugin.list(["PrisM-Inception.2010"], ['en', 'fr'])
|
||||
print results
|
||||
assert len(results) > 0, "No result could be found for PrisM-Inception.2010"
|
||||
'''
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -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)
|
||||
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,448 @@
|
||||
#!/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.assertTrue(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.assertTrue(show_id is 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 and show_ids['the big bang theory'] == 126)
|
||||
|
||||
def test_query_episode_0(self):
|
||||
video = EPISODES[0]
|
||||
languages = {Language('tur'), Language('rus'), Language('heb'), Language('ita'), Language('fra'),
|
||||
Language('ron'), Language('nld'), Language('eng'), Language('deu'), Language('ell'),
|
||||
Language('por', 'BR'), Language('bul')}
|
||||
matches = {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({frozenset(subtitle.compute_matches(video)) for subtitle in subtitles} == matches)
|
||||
self.assertTrue({subtitle.language for subtitle in subtitles} == languages)
|
||||
|
||||
def test_query_episode_1(self):
|
||||
video = EPISODES[1]
|
||||
languages = {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 = {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({frozenset(subtitle.compute_matches(video)) for subtitle in subtitles} == matches)
|
||||
self.assertTrue({subtitle.language for subtitle in subtitles} == languages)
|
||||
|
||||
def test_list_subtitles(self):
|
||||
video = EPISODES[0]
|
||||
languages = {Language('eng'), Language('fra')}
|
||||
matches = {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({frozenset(subtitle.compute_matches(video)) for subtitle in subtitles} == matches)
|
||||
self.assertTrue({subtitle.language for subtitle in subtitles} == languages)
|
||||
|
||||
def test_download_subtitle(self):
|
||||
video = EPISODES[0]
|
||||
languages = {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 BierDopjeProviderTestCase(ProviderTestCase):
|
||||
provider_name = 'bierdopje'
|
||||
|
||||
def test_find_show_id(self):
|
||||
with self.Provider() as provider:
|
||||
show_id = provider.find_show_id('The Big Bang')
|
||||
self.assertTrue(show_id == 9203)
|
||||
|
||||
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.assertTrue(show_id is None)
|
||||
|
||||
def test_query_episode_0(self):
|
||||
video = EPISODES[0]
|
||||
language = Language('eng')
|
||||
matches = {frozenset(['series', 'video_codec', 'resolution', 'episode', 'season']),
|
||||
frozenset(['season', 'video_codec', 'episode', 'series']),
|
||||
frozenset(['episode', 'video_codec', 'season', 'series', 'resolution', 'release_group'])}
|
||||
with self.Provider() as provider:
|
||||
subtitles = provider.query(language, video.season, video.episode, series=video.series)
|
||||
self.assertTrue({frozenset(subtitle.compute_matches(video)) for subtitle in subtitles} == matches)
|
||||
self.assertTrue({subtitle.language for subtitle in subtitles} == {language})
|
||||
|
||||
def test_query_episode_1(self):
|
||||
video = EPISODES[1]
|
||||
language = Language('nld')
|
||||
matches = {frozenset(['series', 'video_codec', 'resolution', 'episode', 'season']),
|
||||
frozenset(['season', 'video_codec', 'episode', 'series']),
|
||||
frozenset(['series', 'episode', 'season']),
|
||||
frozenset(['season', 'video_codec', 'episode', 'release_group', 'series']),
|
||||
frozenset(['episode', 'video_codec', 'season', 'series', 'resolution', 'release_group'])}
|
||||
with self.Provider() as provider:
|
||||
subtitles = provider.query(language, video.season, video.episode, series=video.series)
|
||||
self.assertTrue({frozenset(subtitle.compute_matches(video)) for subtitle in subtitles} == matches)
|
||||
self.assertTrue({subtitle.language for subtitle in subtitles} == {language})
|
||||
|
||||
def test_query_episode_0_tvdb_id(self):
|
||||
video = EPISODES[0]
|
||||
language = Language('eng')
|
||||
matches = {frozenset(['video_codec', 'tvdb_id', 'episode', 'season', 'series']),
|
||||
frozenset(['episode', 'video_codec', 'series', 'season', 'tvdb_id', 'resolution', 'release_group']),
|
||||
frozenset(['episode', 'series', 'video_codec', 'tvdb_id', 'resolution', 'season'])}
|
||||
with self.Provider() as provider:
|
||||
subtitles = provider.query(language, video.season, video.episode, tvdb_id=video.tvdb_id)
|
||||
self.assertTrue({frozenset(subtitle.compute_matches(video)) for subtitle in subtitles} == matches)
|
||||
self.assertTrue({subtitle.language for subtitle in subtitles} == {language})
|
||||
|
||||
def test_list_subtitles(self):
|
||||
video = EPISODES[1]
|
||||
languages = {Language('eng'), Language('nld')}
|
||||
matches = {frozenset(['series', 'video_codec', 'tvdb_id', 'episode', 'season']),
|
||||
frozenset(['episode', 'video_codec', 'season', 'series', 'tvdb_id', 'resolution', 'release_group']),
|
||||
frozenset(['season', 'tvdb_id', 'episode', 'series']),
|
||||
frozenset(['episode', 'video_codec', 'season', 'series', 'tvdb_id', 'resolution']),
|
||||
frozenset(['episode', 'video_codec', 'season', 'series', 'tvdb_id', 'release_group'])}
|
||||
with self.Provider() as provider:
|
||||
subtitles = provider.list_subtitles(video, languages)
|
||||
self.assertTrue({frozenset(subtitle.compute_matches(video)) for subtitle in subtitles} == matches)
|
||||
self.assertTrue({subtitle.language for subtitle in subtitles} == languages)
|
||||
|
||||
def test_download_subtitle(self):
|
||||
video = EPISODES[0]
|
||||
languages = {Language('eng'), Language('nld')}
|
||||
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 = {Language('eng')}
|
||||
matches = {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({frozenset(subtitle.compute_matches(video)) for subtitle in subtitles} == matches)
|
||||
self.assertTrue({subtitle.language for subtitle in subtitles} == languages)
|
||||
|
||||
def test_query_episode_0_query(self):
|
||||
video = EPISODES[0]
|
||||
languages = {Language('eng')}
|
||||
matches = {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({frozenset(subtitle.compute_matches(video)) for subtitle in subtitles} == matches)
|
||||
self.assertTrue({subtitle.language for subtitle in subtitles} == languages)
|
||||
|
||||
def test_query_episode_1_query(self):
|
||||
video = EPISODES[1]
|
||||
languages = {Language('eng'), Language('fra')}
|
||||
matches = {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({frozenset(subtitle.compute_matches(video)) for subtitle in subtitles} == matches)
|
||||
self.assertTrue({subtitle.language for subtitle in subtitles} == languages)
|
||||
|
||||
def test_query_movie_0_imdb_id(self):
|
||||
video = MOVIES[0]
|
||||
languages = {Language('eng'), Language('fra')}
|
||||
matches = {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({frozenset(subtitle.compute_matches(video)) for subtitle in subtitles} == matches)
|
||||
self.assertTrue({subtitle.language for subtitle in subtitles} == languages)
|
||||
|
||||
def test_query_episode_0_imdb_id(self):
|
||||
video = EPISODES[0]
|
||||
languages = {Language('eng'), Language('fra')}
|
||||
matches = {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({frozenset(subtitle.compute_matches(video)) for subtitle in subtitles} == matches)
|
||||
self.assertTrue({subtitle.language for subtitle in subtitles} == languages)
|
||||
|
||||
def test_query_movie_0_hash(self):
|
||||
video = MOVIES[0]
|
||||
languages = {Language('eng')}
|
||||
matches = {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(['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({frozenset(subtitle.compute_matches(video)) for subtitle in subtitles} == matches)
|
||||
self.assertTrue({subtitle.language for subtitle in subtitles} == languages)
|
||||
|
||||
def test_query_episode_0_hash(self):
|
||||
video = EPISODES[0]
|
||||
languages = {Language('eng')}
|
||||
matches = {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({frozenset(subtitle.compute_matches(video)) for subtitle in subtitles} == matches)
|
||||
self.assertTrue({subtitle.language for subtitle in subtitles} == languages)
|
||||
|
||||
def test_list_subtitles(self):
|
||||
video = MOVIES[0]
|
||||
languages = {Language('eng'), Language('fra')}
|
||||
matches = {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(['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({frozenset(subtitle.compute_matches(video)) for subtitle in subtitles} == matches)
|
||||
self.assertTrue({subtitle.language for subtitle in subtitles} == languages)
|
||||
|
||||
def test_download_subtitle(self):
|
||||
video = MOVIES[0]
|
||||
languages = {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 = {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'])}
|
||||
with self.Provider() as provider:
|
||||
subtitles = provider.query(language, title=video.title, year=video.year)
|
||||
self.assertTrue({frozenset(subtitle.compute_matches(video)) for subtitle in subtitles} == matches)
|
||||
self.assertTrue({subtitle.language for subtitle in subtitles} == {language})
|
||||
|
||||
def test_query_episode_0(self):
|
||||
video = EPISODES[0]
|
||||
language = Language('eng')
|
||||
matches = {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({frozenset(subtitle.compute_matches(video)) for subtitle in subtitles} == matches)
|
||||
self.assertTrue({subtitle.language for subtitle in subtitles} == {language})
|
||||
|
||||
def test_list_subtitles(self):
|
||||
video = MOVIES[0]
|
||||
languages = {Language('eng'), Language('fra')}
|
||||
matches = {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'])}
|
||||
with self.Provider() as provider:
|
||||
subtitles = provider.list_subtitles(video, languages)
|
||||
self.assertTrue({frozenset(subtitle.compute_matches(video)) for subtitle in subtitles} == matches)
|
||||
self.assertTrue({subtitle.language for subtitle in subtitles} == languages)
|
||||
|
||||
def test_download_subtitle(self):
|
||||
video = MOVIES[0]
|
||||
languages = {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 = {Language('eng'), Language('spa'), Language('por')}
|
||||
matches = {frozenset(['hash'])}
|
||||
with self.Provider() as provider:
|
||||
subtitles = provider.query(video.hashes['thesubdb'])
|
||||
self.assertTrue({frozenset(subtitle.compute_matches(video)) for subtitle in subtitles} == matches)
|
||||
self.assertTrue({subtitle.language for subtitle in subtitles} == languages)
|
||||
|
||||
def test_query_episode_1(self):
|
||||
video = EPISODES[1]
|
||||
languages = {Language('eng'), Language('por')}
|
||||
matches = {frozenset(['hash'])}
|
||||
with self.Provider() as provider:
|
||||
subtitles = provider.query(video.hashes['thesubdb'])
|
||||
self.assertTrue({frozenset(subtitle.compute_matches(video)) for subtitle in subtitles} == matches)
|
||||
self.assertTrue({subtitle.language for subtitle in subtitles} == languages)
|
||||
|
||||
def test_list_subtitles(self):
|
||||
video = MOVIES[0]
|
||||
languages = {Language('eng'), Language('por')}
|
||||
matches = {frozenset(['hash'])}
|
||||
with self.Provider() as provider:
|
||||
subtitles = provider.list_subtitles(video, languages)
|
||||
self.assertTrue({frozenset(subtitle.compute_matches(video)) for subtitle in subtitles} == matches)
|
||||
self.assertTrue({subtitle.language for subtitle in subtitles} == languages)
|
||||
|
||||
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.assertTrue(show_id == 154)
|
||||
|
||||
def test_find_show_id_ambiguous(self):
|
||||
with self.Provider() as provider:
|
||||
show_id = provider.find_show_id('New Girl')
|
||||
self.assertTrue(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.assertTrue(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.assertTrue(show_id is None)
|
||||
|
||||
def test_find_episode_ids(self):
|
||||
with self.Provider() as provider:
|
||||
episode_ids = provider.find_episode_ids(154, 5)
|
||||
self.assertTrue(set(episode_ids.keys()) == set(range(1, 25)))
|
||||
|
||||
def test_query_episode_0(self):
|
||||
video = EPISODES[0]
|
||||
languages = {Language('fra'), Language('por'), Language('hun'), Language('ron'), Language('eng')}
|
||||
matches = {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({frozenset(subtitle.compute_matches(video)) for subtitle in subtitles} == matches)
|
||||
self.assertTrue({subtitle.language for subtitle in subtitles} == languages)
|
||||
|
||||
def test_query_episode_1(self):
|
||||
video = EPISODES[1]
|
||||
languages = {Language('fra'), Language('ell'), Language('ron'), Language('eng'), Language('hun'),
|
||||
Language('por'), Language('por', 'BR')}
|
||||
matches = {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({frozenset(subtitle.compute_matches(video)) for subtitle in subtitles} == matches)
|
||||
self.assertTrue({subtitle.language for subtitle in subtitles} == languages)
|
||||
|
||||
def test_list_subtitles(self):
|
||||
video = EPISODES[0]
|
||||
languages = {Language('eng'), Language('fra')}
|
||||
matches = {frozenset(['series', 'episode', 'season'])}
|
||||
with self.Provider() as provider:
|
||||
subtitles = provider.list_subtitles(video, languages)
|
||||
self.assertTrue({frozenset(subtitle.compute_matches(video)) for subtitle in subtitles} == matches)
|
||||
self.assertTrue({subtitle.language for subtitle in subtitles} == languages)
|
||||
|
||||
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(BierDopjeProviderTestCase))
|
||||
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,172 @@
|
||||
#!/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 = {Language('eng')}
|
||||
subtitles = list_subtitles(videos, languages)
|
||||
self.assertTrue(len(subtitles) == len(videos))
|
||||
self.assertTrue(len(subtitles[videos[0]]) > 0)
|
||||
|
||||
def test_list_subtitles_movie_0_por_br(self):
|
||||
videos = [MOVIES[0]]
|
||||
languages = {Language('por', 'BR')}
|
||||
subtitles = list_subtitles(videos, languages)
|
||||
self.assertTrue(len(subtitles) == len(videos))
|
||||
self.assertTrue(len(subtitles[videos[0]]) > 0)
|
||||
|
||||
def test_list_subtitles_episodes(self):
|
||||
videos = [EPISODES[0], EPISODES[1]]
|
||||
languages = {Language('eng'), Language('fra')}
|
||||
subtitles = list_subtitles(videos, languages)
|
||||
self.assertTrue(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 = {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 = {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 = {Language('eng'), Language('fra')}
|
||||
subtitles = download_best_subtitles(videos, languages)
|
||||
for video in videos:
|
||||
self.assertTrue(video in subtitles and 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 = {Language('eng'), Language('fra')}
|
||||
subtitles = download_best_subtitles(videos, languages, single=True)
|
||||
for video in videos:
|
||||
self.assertTrue(video in subtitles and 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 = {Language('eng'), Language('fra')}
|
||||
subtitles = download_best_subtitles(videos, languages, min_score=1000)
|
||||
self.assertTrue(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 = {Language('eng')}
|
||||
subtitles = download_best_subtitles(videos, languages, hearing_impaired=True)
|
||||
self.assertTrue(subtitles[videos[0]][0].hearing_impaired == True)
|
||||
|
||||
|
||||
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.assertTrue(scanned_video.name == os.path.join(TEST_DIR, os.path.split(video.name)[1]))
|
||||
self.assertTrue(scanned_video.title.lower() == video.title.lower())
|
||||
self.assertTrue(scanned_video.year == video.year)
|
||||
self.assertTrue(scanned_video.video_codec == video.video_codec)
|
||||
self.assertTrue(scanned_video.resolution == video.resolution)
|
||||
self.assertTrue(scanned_video.release_group == video.release_group)
|
||||
self.assertTrue(scanned_video.subtitle_languages == set())
|
||||
self.assertTrue(scanned_video.hashes == {})
|
||||
self.assertTrue(scanned_video.audio_codec is None)
|
||||
self.assertTrue(scanned_video.imdb_id is None)
|
||||
self.assertTrue(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.assertTrue(scanned_video.name == os.path.join(TEST_DIR, os.path.split(video.name)[1]))
|
||||
self.assertTrue(scanned_video.series == video.series)
|
||||
self.assertTrue(scanned_video.season == video.season)
|
||||
self.assertTrue(scanned_video.episode == video.episode)
|
||||
self.assertTrue(scanned_video.video_codec == video.video_codec)
|
||||
self.assertTrue(scanned_video.resolution == video.resolution)
|
||||
self.assertTrue(scanned_video.release_group == video.release_group)
|
||||
self.assertTrue(scanned_video.subtitle_languages == set())
|
||||
self.assertTrue(scanned_video.hashes == {})
|
||||
self.assertTrue(scanned_video.title is None)
|
||||
self.assertTrue(scanned_video.tvdb_id is None)
|
||||
self.assertTrue(scanned_video.imdb_id is None)
|
||||
self.assertTrue(scanned_video.audio_codec is None)
|
||||
self.assertTrue(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.assertTrue(scanned_video.subtitle_languages == {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.assertTrue(scanned_video.subtitle_languages == {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.assertTrue(scanned_video.subtitle_languages == {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())
|
||||
@@ -0,0 +1,371 @@
|
||||
# -*- 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)
|
||||
|
||||
|
||||
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)
|
||||
|
||||
|
||||
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 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.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):
|
||||
"""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
|
||||
: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)
|
||||
video = Video.fromguess(path, guessit.guess_file_info(path, 'autodetect'))
|
||||
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:
|
||||
try:
|
||||
embedded_subtitle_languages.add(babelfish.Language.fromalpha3b(st.language or 'und'))
|
||||
except babelfish.Error:
|
||||
logger.error('Embedded subtitle language %r is not a valid language', st.language)
|
||||
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', errors='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', errors='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', errors='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')
|
||||
Reference in New Issue
Block a user