Compare commits
254 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| e8dec6c143 | |||
| 8b2b19de4b | |||
| af162578c0 | |||
| c6ccfa4417 | |||
| 132001a1be | |||
| 830c09dde7 | |||
| 57bcde2511 | |||
| c1db5b43e5 | |||
| 7b7f29720c | |||
| 13320db360 | |||
| dd9d63d74e | |||
| 739ed2be6d | |||
| 95d9ed685f | |||
| 1064d60873 | |||
| a93f74c3ec | |||
| a5b9d2dbd6 | |||
| 2e6e27991a | |||
| b0ae70a88f | |||
| af2e8ba7bd | |||
| 15ca8dac1d | |||
| b6f6d17daa | |||
| 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 |
+34
-3
@@ -1,4 +1,35 @@
|
||||
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
|
||||
|
||||
#Sphinx
|
||||
docs/_build
|
||||
|
||||
@@ -0,0 +1,3 @@
|
||||
[submodule "docs/_themes"]
|
||||
path = docs/_themes
|
||||
url = git://github.com/Diaoul/diaoul-sphinx-themes.git
|
||||
@@ -0,0 +1,674 @@
|
||||
GNU GENERAL PUBLIC LICENSE
|
||||
Version 3, 29 June 2007
|
||||
|
||||
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
|
||||
Everyone is permitted to copy and distribute verbatim copies
|
||||
of this license document, but changing it is not allowed.
|
||||
|
||||
Preamble
|
||||
|
||||
The GNU General Public License is a free, copyleft license for
|
||||
software and other kinds of works.
|
||||
|
||||
The licenses for most software and other practical works are designed
|
||||
to take away your freedom to share and change the works. By contrast,
|
||||
the GNU General Public License is intended to guarantee your freedom to
|
||||
share and change all versions of a program--to make sure it remains free
|
||||
software for all its users. We, the Free Software Foundation, use the
|
||||
GNU General Public License for most of our software; it applies also to
|
||||
any other work released this way by its authors. You can apply it to
|
||||
your programs, too.
|
||||
|
||||
When we speak of free software, we are referring to freedom, not
|
||||
price. Our General Public Licenses are designed to make sure that you
|
||||
have the freedom to distribute copies of free software (and charge for
|
||||
them if you wish), that you receive source code or can get it if you
|
||||
want it, that you can change the software or use pieces of it in new
|
||||
free programs, and that you know you can do these things.
|
||||
|
||||
To protect your rights, we need to prevent others from denying you
|
||||
these rights or asking you to surrender the rights. Therefore, you have
|
||||
certain responsibilities if you distribute copies of the software, or if
|
||||
you modify it: responsibilities to respect the freedom of others.
|
||||
|
||||
For example, if you distribute copies of such a program, whether
|
||||
gratis or for a fee, you must pass on to the recipients the same
|
||||
freedoms that you received. You must make sure that they, too, receive
|
||||
or can get the source code. And you must show them these terms so they
|
||||
know their rights.
|
||||
|
||||
Developers that use the GNU GPL protect your rights with two steps:
|
||||
(1) assert copyright on the software, and (2) offer you this License
|
||||
giving you legal permission to copy, distribute and/or modify it.
|
||||
|
||||
For the developers' and authors' protection, the GPL clearly explains
|
||||
that there is no warranty for this free software. For both users' and
|
||||
authors' sake, the GPL requires that modified versions be marked as
|
||||
changed, so that their problems will not be attributed erroneously to
|
||||
authors of previous versions.
|
||||
|
||||
Some devices are designed to deny users access to install or run
|
||||
modified versions of the software inside them, although the manufacturer
|
||||
can do so. This is fundamentally incompatible with the aim of
|
||||
protecting users' freedom to change the software. The systematic
|
||||
pattern of such abuse occurs in the area of products for individuals to
|
||||
use, which is precisely where it is most unacceptable. Therefore, we
|
||||
have designed this version of the GPL to prohibit the practice for those
|
||||
products. If such problems arise substantially in other domains, we
|
||||
stand ready to extend this provision to those domains in future versions
|
||||
of the GPL, as needed to protect the freedom of users.
|
||||
|
||||
Finally, every program is threatened constantly by software patents.
|
||||
States should not allow patents to restrict development and use of
|
||||
software on general-purpose computers, but in those that do, we wish to
|
||||
avoid the special danger that patents applied to a free program could
|
||||
make it effectively proprietary. To prevent this, the GPL assures that
|
||||
patents cannot be used to render the program non-free.
|
||||
|
||||
The precise terms and conditions for copying, distribution and
|
||||
modification follow.
|
||||
|
||||
TERMS AND CONDITIONS
|
||||
|
||||
0. Definitions.
|
||||
|
||||
"This License" refers to version 3 of the GNU General Public License.
|
||||
|
||||
"Copyright" also means copyright-like laws that apply to other kinds of
|
||||
works, such as semiconductor masks.
|
||||
|
||||
"The Program" refers to any copyrightable work licensed under this
|
||||
License. Each licensee is addressed as "you". "Licensees" and
|
||||
"recipients" may be individuals or organizations.
|
||||
|
||||
To "modify" a work means to copy from or adapt all or part of the work
|
||||
in a fashion requiring copyright permission, other than the making of an
|
||||
exact copy. The resulting work is called a "modified version" of the
|
||||
earlier work or a work "based on" the earlier work.
|
||||
|
||||
A "covered work" means either the unmodified Program or a work based
|
||||
on the Program.
|
||||
|
||||
To "propagate" a work means to do anything with it that, without
|
||||
permission, would make you directly or secondarily liable for
|
||||
infringement under applicable copyright law, except executing it on a
|
||||
computer or modifying a private copy. Propagation includes copying,
|
||||
distribution (with or without modification), making available to the
|
||||
public, and in some countries other activities as well.
|
||||
|
||||
To "convey" a work means any kind of propagation that enables other
|
||||
parties to make or receive copies. Mere interaction with a user through
|
||||
a computer network, with no transfer of a copy, is not conveying.
|
||||
|
||||
An interactive user interface displays "Appropriate Legal Notices"
|
||||
to the extent that it includes a convenient and prominently visible
|
||||
feature that (1) displays an appropriate copyright notice, and (2)
|
||||
tells the user that there is no warranty for the work (except to the
|
||||
extent that warranties are provided), that licensees may convey the
|
||||
work under this License, and how to view a copy of this License. If
|
||||
the interface presents a list of user commands or options, such as a
|
||||
menu, a prominent item in the list meets this criterion.
|
||||
|
||||
1. Source Code.
|
||||
|
||||
The "source code" for a work means the preferred form of the work
|
||||
for making modifications to it. "Object code" means any non-source
|
||||
form of a work.
|
||||
|
||||
A "Standard Interface" means an interface that either is an official
|
||||
standard defined by a recognized standards body, or, in the case of
|
||||
interfaces specified for a particular programming language, one that
|
||||
is widely used among developers working in that language.
|
||||
|
||||
The "System Libraries" of an executable work include anything, other
|
||||
than the work as a whole, that (a) is included in the normal form of
|
||||
packaging a Major Component, but which is not part of that Major
|
||||
Component, and (b) serves only to enable use of the work with that
|
||||
Major Component, or to implement a Standard Interface for which an
|
||||
implementation is available to the public in source code form. A
|
||||
"Major Component", in this context, means a major essential component
|
||||
(kernel, window system, and so on) of the specific operating system
|
||||
(if any) on which the executable work runs, or a compiler used to
|
||||
produce the work, or an object code interpreter used to run it.
|
||||
|
||||
The "Corresponding Source" for a work in object code form means all
|
||||
the source code needed to generate, install, and (for an executable
|
||||
work) run the object code and to modify the work, including scripts to
|
||||
control those activities. However, it does not include the work's
|
||||
System Libraries, or general-purpose tools or generally available free
|
||||
programs which are used unmodified in performing those activities but
|
||||
which are not part of the work. For example, Corresponding Source
|
||||
includes interface definition files associated with source files for
|
||||
the work, and the source code for shared libraries and dynamically
|
||||
linked subprograms that the work is specifically designed to require,
|
||||
such as by intimate data communication or control flow between those
|
||||
subprograms and other parts of the work.
|
||||
|
||||
The Corresponding Source need not include anything that users
|
||||
can regenerate automatically from other parts of the Corresponding
|
||||
Source.
|
||||
|
||||
The Corresponding Source for a work in source code form is that
|
||||
same work.
|
||||
|
||||
2. Basic Permissions.
|
||||
|
||||
All rights granted under this License are granted for the term of
|
||||
copyright on the Program, and are irrevocable provided the stated
|
||||
conditions are met. This License explicitly affirms your unlimited
|
||||
permission to run the unmodified Program. The output from running a
|
||||
covered work is covered by this License only if the output, given its
|
||||
content, constitutes a covered work. This License acknowledges your
|
||||
rights of fair use or other equivalent, as provided by copyright law.
|
||||
|
||||
You may make, run and propagate covered works that you do not
|
||||
convey, without conditions so long as your license otherwise remains
|
||||
in force. You may convey covered works to others for the sole purpose
|
||||
of having them make modifications exclusively for you, or provide you
|
||||
with facilities for running those works, provided that you comply with
|
||||
the terms of this License in conveying all material for which you do
|
||||
not control copyright. Those thus making or running the covered works
|
||||
for you must do so exclusively on your behalf, under your direction
|
||||
and control, on terms that prohibit them from making any copies of
|
||||
your copyrighted material outside their relationship with you.
|
||||
|
||||
Conveying under any other circumstances is permitted solely under
|
||||
the conditions stated below. Sublicensing is not allowed; section 10
|
||||
makes it unnecessary.
|
||||
|
||||
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
||||
|
||||
No covered work shall be deemed part of an effective technological
|
||||
measure under any applicable law fulfilling obligations under article
|
||||
11 of the WIPO copyright treaty adopted on 20 December 1996, or
|
||||
similar laws prohibiting or restricting circumvention of such
|
||||
measures.
|
||||
|
||||
When you convey a covered work, you waive any legal power to forbid
|
||||
circumvention of technological measures to the extent such circumvention
|
||||
is effected by exercising rights under this License with respect to
|
||||
the covered work, and you disclaim any intention to limit operation or
|
||||
modification of the work as a means of enforcing, against the work's
|
||||
users, your or third parties' legal rights to forbid circumvention of
|
||||
technological measures.
|
||||
|
||||
4. Conveying Verbatim Copies.
|
||||
|
||||
You may convey verbatim copies of the Program's source code as you
|
||||
receive it, in any medium, provided that you conspicuously and
|
||||
appropriately publish on each copy an appropriate copyright notice;
|
||||
keep intact all notices stating that this License and any
|
||||
non-permissive terms added in accord with section 7 apply to the code;
|
||||
keep intact all notices of the absence of any warranty; and give all
|
||||
recipients a copy of this License along with the Program.
|
||||
|
||||
You may charge any price or no price for each copy that you convey,
|
||||
and you may offer support or warranty protection for a fee.
|
||||
|
||||
5. Conveying Modified Source Versions.
|
||||
|
||||
You may convey a work based on the Program, or the modifications to
|
||||
produce it from the Program, in the form of source code under the
|
||||
terms of section 4, provided that you also meet all of these conditions:
|
||||
|
||||
a) The work must carry prominent notices stating that you modified
|
||||
it, and giving a relevant date.
|
||||
|
||||
b) The work must carry prominent notices stating that it is
|
||||
released under this License and any conditions added under section
|
||||
7. This requirement modifies the requirement in section 4 to
|
||||
"keep intact all notices".
|
||||
|
||||
c) You must license the entire work, as a whole, under this
|
||||
License to anyone who comes into possession of a copy. This
|
||||
License will therefore apply, along with any applicable section 7
|
||||
additional terms, to the whole of the work, and all its parts,
|
||||
regardless of how they are packaged. This License gives no
|
||||
permission to license the work in any other way, but it does not
|
||||
invalidate such permission if you have separately received it.
|
||||
|
||||
d) If the work has interactive user interfaces, each must display
|
||||
Appropriate Legal Notices; however, if the Program has interactive
|
||||
interfaces that do not display Appropriate Legal Notices, your
|
||||
work need not make them do so.
|
||||
|
||||
A compilation of a covered work with other separate and independent
|
||||
works, which are not by their nature extensions of the covered work,
|
||||
and which are not combined with it such as to form a larger program,
|
||||
in or on a volume of a storage or distribution medium, is called an
|
||||
"aggregate" if the compilation and its resulting copyright are not
|
||||
used to limit the access or legal rights of the compilation's users
|
||||
beyond what the individual works permit. Inclusion of a covered work
|
||||
in an aggregate does not cause this License to apply to the other
|
||||
parts of the aggregate.
|
||||
|
||||
6. Conveying Non-Source Forms.
|
||||
|
||||
You may convey a covered work in object code form under the terms
|
||||
of sections 4 and 5, provided that you also convey the
|
||||
machine-readable Corresponding Source under the terms of this License,
|
||||
in one of these ways:
|
||||
|
||||
a) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by the
|
||||
Corresponding Source fixed on a durable physical medium
|
||||
customarily used for software interchange.
|
||||
|
||||
b) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by a
|
||||
written offer, valid for at least three years and valid for as
|
||||
long as you offer spare parts or customer support for that product
|
||||
model, to give anyone who possesses the object code either (1) a
|
||||
copy of the Corresponding Source for all the software in the
|
||||
product that is covered by this License, on a durable physical
|
||||
medium customarily used for software interchange, for a price no
|
||||
more than your reasonable cost of physically performing this
|
||||
conveying of source, or (2) access to copy the
|
||||
Corresponding Source from a network server at no charge.
|
||||
|
||||
c) Convey individual copies of the object code with a copy of the
|
||||
written offer to provide the Corresponding Source. This
|
||||
alternative is allowed only occasionally and noncommercially, and
|
||||
only if you received the object code with such an offer, in accord
|
||||
with subsection 6b.
|
||||
|
||||
d) Convey the object code by offering access from a designated
|
||||
place (gratis or for a charge), and offer equivalent access to the
|
||||
Corresponding Source in the same way through the same place at no
|
||||
further charge. You need not require recipients to copy the
|
||||
Corresponding Source along with the object code. If the place to
|
||||
copy the object code is a network server, the Corresponding Source
|
||||
may be on a different server (operated by you or a third party)
|
||||
that supports equivalent copying facilities, provided you maintain
|
||||
clear directions next to the object code saying where to find the
|
||||
Corresponding Source. Regardless of what server hosts the
|
||||
Corresponding Source, you remain obligated to ensure that it is
|
||||
available for as long as needed to satisfy these requirements.
|
||||
|
||||
e) Convey the object code using peer-to-peer transmission, provided
|
||||
you inform other peers where the object code and Corresponding
|
||||
Source of the work are being offered to the general public at no
|
||||
charge under subsection 6d.
|
||||
|
||||
A separable portion of the object code, whose source code is excluded
|
||||
from the Corresponding Source as a System Library, need not be
|
||||
included in conveying the object code work.
|
||||
|
||||
A "User Product" is either (1) a "consumer product", which means any
|
||||
tangible personal property which is normally used for personal, family,
|
||||
or household purposes, or (2) anything designed or sold for incorporation
|
||||
into a dwelling. In determining whether a product is a consumer product,
|
||||
doubtful cases shall be resolved in favor of coverage. For a particular
|
||||
product received by a particular user, "normally used" refers to a
|
||||
typical or common use of that class of product, regardless of the status
|
||||
of the particular user or of the way in which the particular user
|
||||
actually uses, or expects or is expected to use, the product. A product
|
||||
is a consumer product regardless of whether the product has substantial
|
||||
commercial, industrial or non-consumer uses, unless such uses represent
|
||||
the only significant mode of use of the product.
|
||||
|
||||
"Installation Information" for a User Product means any methods,
|
||||
procedures, authorization keys, or other information required to install
|
||||
and execute modified versions of a covered work in that User Product from
|
||||
a modified version of its Corresponding Source. The information must
|
||||
suffice to ensure that the continued functioning of the modified object
|
||||
code is in no case prevented or interfered with solely because
|
||||
modification has been made.
|
||||
|
||||
If you convey an object code work under this section in, or with, or
|
||||
specifically for use in, a User Product, and the conveying occurs as
|
||||
part of a transaction in which the right of possession and use of the
|
||||
User Product is transferred to the recipient in perpetuity or for a
|
||||
fixed term (regardless of how the transaction is characterized), the
|
||||
Corresponding Source conveyed under this section must be accompanied
|
||||
by the Installation Information. But this requirement does not apply
|
||||
if neither you nor any third party retains the ability to install
|
||||
modified object code on the User Product (for example, the work has
|
||||
been installed in ROM).
|
||||
|
||||
The requirement to provide Installation Information does not include a
|
||||
requirement to continue to provide support service, warranty, or updates
|
||||
for a work that has been modified or installed by the recipient, or for
|
||||
the User Product in which it has been modified or installed. Access to a
|
||||
network may be denied when the modification itself materially and
|
||||
adversely affects the operation of the network or violates the rules and
|
||||
protocols for communication across the network.
|
||||
|
||||
Corresponding Source conveyed, and Installation Information provided,
|
||||
in accord with this section must be in a format that is publicly
|
||||
documented (and with an implementation available to the public in
|
||||
source code form), and must require no special password or key for
|
||||
unpacking, reading or copying.
|
||||
|
||||
7. Additional Terms.
|
||||
|
||||
"Additional permissions" are terms that supplement the terms of this
|
||||
License by making exceptions from one or more of its conditions.
|
||||
Additional permissions that are applicable to the entire Program shall
|
||||
be treated as though they were included in this License, to the extent
|
||||
that they are valid under applicable law. If additional permissions
|
||||
apply only to part of the Program, that part may be used separately
|
||||
under those permissions, but the entire Program remains governed by
|
||||
this License without regard to the additional permissions.
|
||||
|
||||
When you convey a copy of a covered work, you may at your option
|
||||
remove any additional permissions from that copy, or from any part of
|
||||
it. (Additional permissions may be written to require their own
|
||||
removal in certain cases when you modify the work.) You may place
|
||||
additional permissions on material, added by you to a covered work,
|
||||
for which you have or can give appropriate copyright permission.
|
||||
|
||||
Notwithstanding any other provision of this License, for material you
|
||||
add to a covered work, you may (if authorized by the copyright holders of
|
||||
that material) supplement the terms of this License with terms:
|
||||
|
||||
a) Disclaiming warranty or limiting liability differently from the
|
||||
terms of sections 15 and 16 of this License; or
|
||||
|
||||
b) Requiring preservation of specified reasonable legal notices or
|
||||
author attributions in that material or in the Appropriate Legal
|
||||
Notices displayed by works containing it; or
|
||||
|
||||
c) Prohibiting misrepresentation of the origin of that material, or
|
||||
requiring that modified versions of such material be marked in
|
||||
reasonable ways as different from the original version; or
|
||||
|
||||
d) Limiting the use for publicity purposes of names of licensors or
|
||||
authors of the material; or
|
||||
|
||||
e) Declining to grant rights under trademark law for use of some
|
||||
trade names, trademarks, or service marks; or
|
||||
|
||||
f) Requiring indemnification of licensors and authors of that
|
||||
material by anyone who conveys the material (or modified versions of
|
||||
it) with contractual assumptions of liability to the recipient, for
|
||||
any liability that these contractual assumptions directly impose on
|
||||
those licensors and authors.
|
||||
|
||||
All other non-permissive additional terms are considered "further
|
||||
restrictions" within the meaning of section 10. If the Program as you
|
||||
received it, or any part of it, contains a notice stating that it is
|
||||
governed by this License along with a term that is a further
|
||||
restriction, you may remove that term. If a license document contains
|
||||
a further restriction but permits relicensing or conveying under this
|
||||
License, you may add to a covered work material governed by the terms
|
||||
of that license document, provided that the further restriction does
|
||||
not survive such relicensing or conveying.
|
||||
|
||||
If you add terms to a covered work in accord with this section, you
|
||||
must place, in the relevant source files, a statement of the
|
||||
additional terms that apply to those files, or a notice indicating
|
||||
where to find the applicable terms.
|
||||
|
||||
Additional terms, permissive or non-permissive, may be stated in the
|
||||
form of a separately written license, or stated as exceptions;
|
||||
the above requirements apply either way.
|
||||
|
||||
8. Termination.
|
||||
|
||||
You may not propagate or modify a covered work except as expressly
|
||||
provided under this License. Any attempt otherwise to propagate or
|
||||
modify it is void, and will automatically terminate your rights under
|
||||
this License (including any patent licenses granted under the third
|
||||
paragraph of section 11).
|
||||
|
||||
However, if you cease all violation of this License, then your
|
||||
license from a particular copyright holder is reinstated (a)
|
||||
provisionally, unless and until the copyright holder explicitly and
|
||||
finally terminates your license, and (b) permanently, if the copyright
|
||||
holder fails to notify you of the violation by some reasonable means
|
||||
prior to 60 days after the cessation.
|
||||
|
||||
Moreover, your license from a particular copyright holder is
|
||||
reinstated permanently if the copyright holder notifies you of the
|
||||
violation by some reasonable means, this is the first time you have
|
||||
received notice of violation of this License (for any work) from that
|
||||
copyright holder, and you cure the violation prior to 30 days after
|
||||
your receipt of the notice.
|
||||
|
||||
Termination of your rights under this section does not terminate the
|
||||
licenses of parties who have received copies or rights from you under
|
||||
this License. If your rights have been terminated and not permanently
|
||||
reinstated, you do not qualify to receive new licenses for the same
|
||||
material under section 10.
|
||||
|
||||
9. Acceptance Not Required for Having Copies.
|
||||
|
||||
You are not required to accept this License in order to receive or
|
||||
run a copy of the Program. Ancillary propagation of a covered work
|
||||
occurring solely as a consequence of using peer-to-peer transmission
|
||||
to receive a copy likewise does not require acceptance. However,
|
||||
nothing other than this License grants you permission to propagate or
|
||||
modify any covered work. These actions infringe copyright if you do
|
||||
not accept this License. Therefore, by modifying or propagating a
|
||||
covered work, you indicate your acceptance of this License to do so.
|
||||
|
||||
10. Automatic Licensing of Downstream Recipients.
|
||||
|
||||
Each time you convey a covered work, the recipient automatically
|
||||
receives a license from the original licensors, to run, modify and
|
||||
propagate that work, subject to this License. You are not responsible
|
||||
for enforcing compliance by third parties with this License.
|
||||
|
||||
An "entity transaction" is a transaction transferring control of an
|
||||
organization, or substantially all assets of one, or subdividing an
|
||||
organization, or merging organizations. If propagation of a covered
|
||||
work results from an entity transaction, each party to that
|
||||
transaction who receives a copy of the work also receives whatever
|
||||
licenses to the work the party's predecessor in interest had or could
|
||||
give under the previous paragraph, plus a right to possession of the
|
||||
Corresponding Source of the work from the predecessor in interest, if
|
||||
the predecessor has it or can get it with reasonable efforts.
|
||||
|
||||
You may not impose any further restrictions on the exercise of the
|
||||
rights granted or affirmed under this License. For example, you may
|
||||
not impose a license fee, royalty, or other charge for exercise of
|
||||
rights granted under this License, and you may not initiate litigation
|
||||
(including a cross-claim or counterclaim in a lawsuit) alleging that
|
||||
any patent claim is infringed by making, using, selling, offering for
|
||||
sale, or importing the Program or any portion of it.
|
||||
|
||||
11. Patents.
|
||||
|
||||
A "contributor" is a copyright holder who authorizes use under this
|
||||
License of the Program or a work on which the Program is based. The
|
||||
work thus licensed is called the contributor's "contributor version".
|
||||
|
||||
A contributor's "essential patent claims" are all patent claims
|
||||
owned or controlled by the contributor, whether already acquired or
|
||||
hereafter acquired, that would be infringed by some manner, permitted
|
||||
by this License, of making, using, or selling its contributor version,
|
||||
but do not include claims that would be infringed only as a
|
||||
consequence of further modification of the contributor version. For
|
||||
purposes of this definition, "control" includes the right to grant
|
||||
patent sublicenses in a manner consistent with the requirements of
|
||||
this License.
|
||||
|
||||
Each contributor grants you a non-exclusive, worldwide, royalty-free
|
||||
patent license under the contributor's essential patent claims, to
|
||||
make, use, sell, offer for sale, import and otherwise run, modify and
|
||||
propagate the contents of its contributor version.
|
||||
|
||||
In the following three paragraphs, a "patent license" is any express
|
||||
agreement or commitment, however denominated, not to enforce a patent
|
||||
(such as an express permission to practice a patent or covenant not to
|
||||
sue for patent infringement). To "grant" such a patent license to a
|
||||
party means to make such an agreement or commitment not to enforce a
|
||||
patent against the party.
|
||||
|
||||
If you convey a covered work, knowingly relying on a patent license,
|
||||
and the Corresponding Source of the work is not available for anyone
|
||||
to copy, free of charge and under the terms of this License, through a
|
||||
publicly available network server or other readily accessible means,
|
||||
then you must either (1) cause the Corresponding Source to be so
|
||||
available, or (2) arrange to deprive yourself of the benefit of the
|
||||
patent license for this particular work, or (3) arrange, in a manner
|
||||
consistent with the requirements of this License, to extend the patent
|
||||
license to downstream recipients. "Knowingly relying" means you have
|
||||
actual knowledge that, but for the patent license, your conveying the
|
||||
covered work in a country, or your recipient's use of the covered work
|
||||
in a country, would infringe one or more identifiable patents in that
|
||||
country that you have reason to believe are valid.
|
||||
|
||||
If, pursuant to or in connection with a single transaction or
|
||||
arrangement, you convey, or propagate by procuring conveyance of, a
|
||||
covered work, and grant a patent license to some of the parties
|
||||
receiving the covered work authorizing them to use, propagate, modify
|
||||
or convey a specific copy of the covered work, then the patent license
|
||||
you grant is automatically extended to all recipients of the covered
|
||||
work and works based on it.
|
||||
|
||||
A patent license is "discriminatory" if it does not include within
|
||||
the scope of its coverage, prohibits the exercise of, or is
|
||||
conditioned on the non-exercise of one or more of the rights that are
|
||||
specifically granted under this License. You may not convey a covered
|
||||
work if you are a party to an arrangement with a third party that is
|
||||
in the business of distributing software, under which you make payment
|
||||
to the third party based on the extent of your activity of conveying
|
||||
the work, and under which the third party grants, to any of the
|
||||
parties who would receive the covered work from you, a discriminatory
|
||||
patent license (a) in connection with copies of the covered work
|
||||
conveyed by you (or copies made from those copies), or (b) primarily
|
||||
for and in connection with specific products or compilations that
|
||||
contain the covered work, unless you entered into that arrangement,
|
||||
or that patent license was granted, prior to 28 March 2007.
|
||||
|
||||
Nothing in this License shall be construed as excluding or limiting
|
||||
any implied license or other defenses to infringement that may
|
||||
otherwise be available to you under applicable patent law.
|
||||
|
||||
12. No Surrender of Others' Freedom.
|
||||
|
||||
If conditions are imposed on you (whether by court order, agreement or
|
||||
otherwise) that contradict the conditions of this License, they do not
|
||||
excuse you from the conditions of this License. If you cannot convey a
|
||||
covered work so as to satisfy simultaneously your obligations under this
|
||||
License and any other pertinent obligations, then as a consequence you may
|
||||
not convey it at all. For example, if you agree to terms that obligate you
|
||||
to collect a royalty for further conveying from those to whom you convey
|
||||
the Program, the only way you could satisfy both those terms and this
|
||||
License would be to refrain entirely from conveying the Program.
|
||||
|
||||
13. Use with the GNU Affero General Public License.
|
||||
|
||||
Notwithstanding any other provision of this License, you have
|
||||
permission to link or combine any covered work with a work licensed
|
||||
under version 3 of the GNU Affero General Public License into a single
|
||||
combined work, and to convey the resulting work. The terms of this
|
||||
License will continue to apply to the part which is the covered work,
|
||||
but the special requirements of the GNU Affero General Public License,
|
||||
section 13, concerning interaction through a network will apply to the
|
||||
combination as such.
|
||||
|
||||
14. Revised Versions of this License.
|
||||
|
||||
The Free Software Foundation may publish revised and/or new versions of
|
||||
the GNU General Public License from time to time. Such new versions will
|
||||
be similar in spirit to the present version, but may differ in detail to
|
||||
address new problems or concerns.
|
||||
|
||||
Each version is given a distinguishing version number. If the
|
||||
Program specifies that a certain numbered version of the GNU General
|
||||
Public License "or any later version" applies to it, you have the
|
||||
option of following the terms and conditions either of that numbered
|
||||
version or of any later version published by the Free Software
|
||||
Foundation. If the Program does not specify a version number of the
|
||||
GNU General Public License, you may choose any version ever published
|
||||
by the Free Software Foundation.
|
||||
|
||||
If the Program specifies that a proxy can decide which future
|
||||
versions of the GNU General Public License can be used, that proxy's
|
||||
public statement of acceptance of a version permanently authorizes you
|
||||
to choose that version for the Program.
|
||||
|
||||
Later license versions may give you additional or different
|
||||
permissions. However, no additional obligations are imposed on any
|
||||
author or copyright holder as a result of your choosing to follow a
|
||||
later version.
|
||||
|
||||
15. Disclaimer of Warranty.
|
||||
|
||||
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
|
||||
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
|
||||
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
|
||||
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
|
||||
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
|
||||
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
|
||||
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
||||
|
||||
16. Limitation of Liability.
|
||||
|
||||
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
||||
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
|
||||
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
|
||||
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
|
||||
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
|
||||
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
|
||||
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
|
||||
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
|
||||
SUCH DAMAGES.
|
||||
|
||||
17. Interpretation of Sections 15 and 16.
|
||||
|
||||
If the disclaimer of warranty and limitation of liability provided
|
||||
above cannot be given local legal effect according to their terms,
|
||||
reviewing courts shall apply local law that most closely approximates
|
||||
an absolute waiver of all civil liability in connection with the
|
||||
Program, unless a warranty or assumption of liability accompanies a
|
||||
copy of the Program in return for a fee.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
How to Apply These Terms to Your New Programs
|
||||
|
||||
If you develop a new program, and you want it to be of the greatest
|
||||
possible use to the public, the best way to achieve this is to make it
|
||||
free software which everyone can redistribute and change under these terms.
|
||||
|
||||
To do so, attach the following notices to the program. It is safest
|
||||
to attach them to the start of each source file to most effectively
|
||||
state the exclusion of warranty; and each file should have at least
|
||||
the "copyright" line and a pointer to where the full notice is found.
|
||||
|
||||
<one line to give the program's name and a brief idea of what it does.>
|
||||
Copyright (C) <year> <name of author>
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
the Free Software Foundation, either version 3 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
This program 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
|
||||
GNU General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU General Public License
|
||||
along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
Also add information on how to contact you by electronic and paper mail.
|
||||
|
||||
If the program does terminal interaction, make it output a short
|
||||
notice like this when it starts in an interactive mode:
|
||||
|
||||
<program> Copyright (C) <year> <name of author>
|
||||
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
|
||||
This is free software, and you are welcome to redistribute it
|
||||
under certain conditions; type `show c' for details.
|
||||
|
||||
The hypothetical commands `show w' and `show c' should show the appropriate
|
||||
parts of the General Public License. Of course, your program's commands
|
||||
might be different; for a GUI interface, you would use an "about box".
|
||||
|
||||
You should also get your employer (if you work as a programmer) or school,
|
||||
if any, to sign a "copyright disclaimer" for the program, if necessary.
|
||||
For more information on this, and how to apply and follow the GNU GPL, see
|
||||
<http://www.gnu.org/licenses/>.
|
||||
|
||||
The GNU General Public License does not permit incorporating your program
|
||||
into proprietary programs. If your program is a subroutine library, you
|
||||
may consider it more useful to permit linking proprietary applications with
|
||||
the library. If this is what you want to do, use the GNU Lesser General
|
||||
Public License instead of this License. But first, please read
|
||||
<http://www.gnu.org/philosophy/why-not-lgpl.html>.
|
||||
+165
@@ -0,0 +1,165 @@
|
||||
GNU LESSER GENERAL PUBLIC LICENSE
|
||||
Version 3, 29 June 2007
|
||||
|
||||
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
|
||||
Everyone is permitted to copy and distribute verbatim copies
|
||||
of this license document, but changing it is not allowed.
|
||||
|
||||
|
||||
This version of the GNU Lesser General Public License incorporates
|
||||
the terms and conditions of version 3 of the GNU General Public
|
||||
License, supplemented by the additional permissions listed below.
|
||||
|
||||
0. Additional Definitions.
|
||||
|
||||
As used herein, "this License" refers to version 3 of the GNU Lesser
|
||||
General Public License, and the "GNU GPL" refers to version 3 of the GNU
|
||||
General Public License.
|
||||
|
||||
"The Library" refers to a covered work governed by this License,
|
||||
other than an Application or a Combined Work as defined below.
|
||||
|
||||
An "Application" is any work that makes use of an interface provided
|
||||
by the Library, but which is not otherwise based on the Library.
|
||||
Defining a subclass of a class defined by the Library is deemed a mode
|
||||
of using an interface provided by the Library.
|
||||
|
||||
A "Combined Work" is a work produced by combining or linking an
|
||||
Application with the Library. The particular version of the Library
|
||||
with which the Combined Work was made is also called the "Linked
|
||||
Version".
|
||||
|
||||
The "Minimal Corresponding Source" for a Combined Work means the
|
||||
Corresponding Source for the Combined Work, excluding any source code
|
||||
for portions of the Combined Work that, considered in isolation, are
|
||||
based on the Application, and not on the Linked Version.
|
||||
|
||||
The "Corresponding Application Code" for a Combined Work means the
|
||||
object code and/or source code for the Application, including any data
|
||||
and utility programs needed for reproducing the Combined Work from the
|
||||
Application, but excluding the System Libraries of the Combined Work.
|
||||
|
||||
1. Exception to Section 3 of the GNU GPL.
|
||||
|
||||
You may convey a covered work under sections 3 and 4 of this License
|
||||
without being bound by section 3 of the GNU GPL.
|
||||
|
||||
2. Conveying Modified Versions.
|
||||
|
||||
If you modify a copy of the Library, and, in your modifications, a
|
||||
facility refers to a function or data to be supplied by an Application
|
||||
that uses the facility (other than as an argument passed when the
|
||||
facility is invoked), then you may convey a copy of the modified
|
||||
version:
|
||||
|
||||
a) under this License, provided that you make a good faith effort to
|
||||
ensure that, in the event an Application does not supply the
|
||||
function or data, the facility still operates, and performs
|
||||
whatever part of its purpose remains meaningful, or
|
||||
|
||||
b) under the GNU GPL, with none of the additional permissions of
|
||||
this License applicable to that copy.
|
||||
|
||||
3. Object Code Incorporating Material from Library Header Files.
|
||||
|
||||
The object code form of an Application may incorporate material from
|
||||
a header file that is part of the Library. You may convey such object
|
||||
code under terms of your choice, provided that, if the incorporated
|
||||
material is not limited to numerical parameters, data structure
|
||||
layouts and accessors, or small macros, inline functions and templates
|
||||
(ten or fewer lines in length), you do both of the following:
|
||||
|
||||
a) Give prominent notice with each copy of the object code that the
|
||||
Library is used in it and that the Library and its use are
|
||||
covered by this License.
|
||||
|
||||
b) Accompany the object code with a copy of the GNU GPL and this license
|
||||
document.
|
||||
|
||||
4. Combined Works.
|
||||
|
||||
You may convey a Combined Work under terms of your choice that,
|
||||
taken together, effectively do not restrict modification of the
|
||||
portions of the Library contained in the Combined Work and reverse
|
||||
engineering for debugging such modifications, if you also do each of
|
||||
the following:
|
||||
|
||||
a) Give prominent notice with each copy of the Combined Work that
|
||||
the Library is used in it and that the Library and its use are
|
||||
covered by this License.
|
||||
|
||||
b) Accompany the Combined Work with a copy of the GNU GPL and this license
|
||||
document.
|
||||
|
||||
c) For a Combined Work that displays copyright notices during
|
||||
execution, include the copyright notice for the Library among
|
||||
these notices, as well as a reference directing the user to the
|
||||
copies of the GNU GPL and this license document.
|
||||
|
||||
d) Do one of the following:
|
||||
|
||||
0) Convey the Minimal Corresponding Source under the terms of this
|
||||
License, and the Corresponding Application Code in a form
|
||||
suitable for, and under terms that permit, the user to
|
||||
recombine or relink the Application with a modified version of
|
||||
the Linked Version to produce a modified Combined Work, in the
|
||||
manner specified by section 6 of the GNU GPL for conveying
|
||||
Corresponding Source.
|
||||
|
||||
1) Use a suitable shared library mechanism for linking with the
|
||||
Library. A suitable mechanism is one that (a) uses at run time
|
||||
a copy of the Library already present on the user's computer
|
||||
system, and (b) will operate properly with a modified version
|
||||
of the Library that is interface-compatible with the Linked
|
||||
Version.
|
||||
|
||||
e) Provide Installation Information, but only if you would otherwise
|
||||
be required to provide such information under section 6 of the
|
||||
GNU GPL, and only to the extent that such information is
|
||||
necessary to install and execute a modified version of the
|
||||
Combined Work produced by recombining or relinking the
|
||||
Application with a modified version of the Linked Version. (If
|
||||
you use option 4d0, the Installation Information must accompany
|
||||
the Minimal Corresponding Source and Corresponding Application
|
||||
Code. If you use option 4d1, you must provide the Installation
|
||||
Information in the manner specified by section 6 of the GNU GPL
|
||||
for conveying Corresponding Source.)
|
||||
|
||||
5. Combined Libraries.
|
||||
|
||||
You may place library facilities that are a work based on the
|
||||
Library side by side in a single library together with other library
|
||||
facilities that are not Applications and are not covered by this
|
||||
License, and convey such a combined library under terms of your
|
||||
choice, if you do both of the following:
|
||||
|
||||
a) Accompany the combined library with a copy of the same work based
|
||||
on the Library, uncombined with any other library facilities,
|
||||
conveyed under the terms of this License.
|
||||
|
||||
b) Give prominent notice with the combined library that part of it
|
||||
is a work based on the Library, and explaining where to find the
|
||||
accompanying uncombined form of the same work.
|
||||
|
||||
6. Revised Versions of the GNU Lesser General Public License.
|
||||
|
||||
The Free Software Foundation may publish revised and/or new versions
|
||||
of the GNU Lesser General Public License from time to time. Such new
|
||||
versions will be similar in spirit to the present version, but may
|
||||
differ in detail to address new problems or concerns.
|
||||
|
||||
Each version is given a distinguishing version number. If the
|
||||
Library as you received it specifies that a certain numbered version
|
||||
of the GNU Lesser General Public License "or any later version"
|
||||
applies to it, you have the option of following the terms and
|
||||
conditions either of that published version or of any later version
|
||||
published by the Free Software Foundation. If the Library as you
|
||||
received it does not specify a version number of the GNU Lesser
|
||||
General Public License, you may choose any version of the GNU Lesser
|
||||
General Public License ever published by the Free Software Foundation.
|
||||
|
||||
If the Library as you received it specifies that a proxy can decide
|
||||
whether future versions of the GNU Lesser General Public License shall
|
||||
apply, that proxy's public statement of acceptance of any version is
|
||||
permanent authorization for you to choose that version for the
|
||||
Library.
|
||||
@@ -0,0 +1 @@
|
||||
include COPYING COPYING.LESSER NEWS.rst README.rst
|
||||
@@ -0,0 +1,54 @@
|
||||
News
|
||||
====
|
||||
|
||||
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
|
||||
@@ -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/)
|
||||
+43
@@ -0,0 +1,43 @@
|
||||
Subliminal
|
||||
==========
|
||||
Subliminal is a python library to search and download subtitles.
|
||||
|
||||
It uses video hashes and the powerful `guessit <http://guessit.readthedocs.org/>`_ library
|
||||
that extracts informations from filenames or filepaths to ensure you have the best subtitles.
|
||||
It also relies on `enzyme <https://github.com/Diaoul/enzyme>`_ to detect embedded subtitles
|
||||
and avoid duplicates.
|
||||
|
||||
Features
|
||||
--------
|
||||
Multiple subtitles services are available:
|
||||
|
||||
* OpenSubtitles
|
||||
* TheSubDB
|
||||
* BierDopje
|
||||
* SubsWiki
|
||||
* Subtitulos
|
||||
|
||||
You can use main subliminal's functions with a **file path**, a **file name** or a **folder path**.
|
||||
|
||||
CLI
|
||||
^^^
|
||||
Download english subtitles::
|
||||
|
||||
$ subliminal -l en The.Big.Bang.Theory.S05E18.HDTV.x264-LOL.mp4
|
||||
**************************************************
|
||||
Downloaded 1 subtitles
|
||||
(Episode(u'The.Big.Bang.Theory.S05E18.HDTV.x264-LOL.mp4'), ResultSubtitle(en, opensubtitles, 0.33, The.Big.Bang.Theory.S05E18.HDTV-LOL.srt))
|
||||
**************************************************
|
||||
|
||||
Module
|
||||
^^^^^^
|
||||
List english subtitles::
|
||||
|
||||
>>> subliminal.list_subtitles('The.Big.Bang.Theory.S05E18.HDTV.x264-LOL.mp4', ['en'])
|
||||
|
||||
Multi-threaded use
|
||||
^^^^^^^^^^^^^^^^^^
|
||||
Use 4 workers to achieve the same result::
|
||||
|
||||
>>> with subliminal.Pool(4) as p:
|
||||
... p.list_subtitles('The.Big.Bang.Theory.S05E18.HDTV.x264-LOL.mp4', ['en'])
|
||||
+153
@@ -0,0 +1,153 @@
|
||||
# Makefile for Sphinx documentation
|
||||
#
|
||||
|
||||
# You can set these variables from the command line.
|
||||
SPHINXOPTS =
|
||||
SPHINXBUILD = sphinx-build
|
||||
PAPER =
|
||||
BUILDDIR = _build
|
||||
|
||||
# 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 " 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 " 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."
|
||||
|
||||
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."
|
||||
Vendored
BIN
Binary file not shown.
|
After Width: | Height: | Size: 32 KiB |
Vendored
+4
@@ -0,0 +1,4 @@
|
||||
<h3>About</h3>
|
||||
<p>
|
||||
Subliminal is a python library to search and download subtitles.
|
||||
</p>
|
||||
Vendored
+6
@@ -0,0 +1,6 @@
|
||||
<h3>Useful Links</h3>
|
||||
<ul>
|
||||
<li><a href="http://pypi.python.org/pypi/subliminal">subliminal @ PyPI</a></li>
|
||||
<li><a href="http://github.com/Diaoul/subliminal">subliminal @ GitHub</a></li>
|
||||
<li><a href="http://github.com/Diaoul/subliminal/issues">Issue Tracker</a></li>
|
||||
</ul>
|
||||
Vendored
+4
@@ -0,0 +1,4 @@
|
||||
<p>
|
||||
<iframe src="http://markdotto.github.com/github-buttons/github-btn.html?user=Diaoul&repo=subliminal&type=watch&count=true&size=large"
|
||||
allowtransparency="true" frameborder="0" scrolling="0" width="200px" height="35px"></iframe>
|
||||
</p>
|
||||
Submodule
+1
Submodule docs/_themes added at 643e653f25
+247
@@ -0,0 +1,247 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
#
|
||||
# subliminal documentation build configuration file, created by
|
||||
# sphinx-quickstart on Tue Feb 28 16:33:06 2012.
|
||||
#
|
||||
# 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.infos
|
||||
|
||||
# -- 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']
|
||||
|
||||
# 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 = u'subliminal'
|
||||
copyright = u'2012, Antoine Bertin'
|
||||
|
||||
# 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.infos.__version__
|
||||
# The full version, including alpha/beta/rc tags.
|
||||
release = 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 = []
|
||||
|
||||
|
||||
# -- 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 = 'flask'
|
||||
|
||||
# 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 = {}
|
||||
|
||||
# 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 = '_static/subliminal-logo.png'
|
||||
|
||||
# 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-watch.html', 'localtoc.html', 'sidebar-links.html', 'searchbox.html'],
|
||||
'**': ['localtoc.html', 'relations.html', 'sourcelink.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'
|
||||
@@ -0,0 +1,87 @@
|
||||
This guide is going to explain the main logic of subliminal and detail
|
||||
every class or function.
|
||||
|
||||
Services
|
||||
--------
|
||||
Subliminal aims at downloading subtitles. Over the web, one can find subtitles
|
||||
combining different websites but there is no guarantee of a perfect match.
|
||||
Even if OpenSubtitles has a gigantic subtitles database, you may not be able to
|
||||
find a subtitle on it but you will find it elsewhere, say BierDopje. Sometimes,
|
||||
it just takes some time before it shows up on a website even if already available
|
||||
on another, but you don't wanna wait to watch the latest Big Bang Theory, right?
|
||||
|
||||
Given this, to be reliable, subliminal has to use different :mod:`~subliminal.services`
|
||||
and use a unified method to gather them all. The :class:`~subliminal.services.ServiceBase`
|
||||
class will achieve this.
|
||||
|
||||
.. automodule:: subliminal.services
|
||||
:members:
|
||||
|
||||
Languages
|
||||
---------
|
||||
To be able to support many languages, subliminal has a :mod:`~subliminal.languages`
|
||||
module that contains utility functions and ISO languages code (639-1 and 639-2)
|
||||
|
||||
.. automodule:: subliminal.languages
|
||||
:members:
|
||||
|
||||
Tasks
|
||||
-----
|
||||
Subliminal is IO bound: it mostly waits for IO operations (web requests) to complete.
|
||||
Thus, subliminal is a good place for multi-threading. It works with atomic operations
|
||||
represented by a :class:`~subliminal.tasks.Task` class which can be consumed with
|
||||
:func:`~subliminal.core.consume_task` but we'll see that later.
|
||||
|
||||
.. automodule:: subliminal.tasks
|
||||
:members:
|
||||
|
||||
Asynchronous
|
||||
------------
|
||||
To consume those tasks in an asynchronous way without flooding services with requests,
|
||||
subliminal uses multiple instances of the :class:`~subliminal.async.Worker` class that
|
||||
will consume the same task queue. Each worker will only create a single instance of each
|
||||
:mod:`service <subliminal.services>` and this save some initialization time.
|
||||
The :class:`~subliminal.async.Pool` is here to instantiate and manage multiple workers
|
||||
at a time.
|
||||
|
||||
.. automodule:: subliminal.async
|
||||
:members:
|
||||
|
||||
Core
|
||||
----
|
||||
The goal of subliminal's :mod:`~subliminal.core` module is to merge results from
|
||||
consumed tasks. Merging has to be intelligent and take user preferences into account.
|
||||
Core module is thus responsible for the computation of a :func:`matching confidence
|
||||
<subliminal.core.matching_confidence>` so the user knows the chances that the
|
||||
:class:`~subliminal.subtitles.ResultSubtitle` matches the :class:`~subliminal.videos.Video`
|
||||
|
||||
.. automodule:: subliminal.core
|
||||
:members:
|
||||
|
||||
Other objects
|
||||
-------------
|
||||
Subliminal uses some other self-explanatory functions and classes listed below.
|
||||
|
||||
Video
|
||||
^^^^^
|
||||
|
||||
.. automodule:: subliminal.videos
|
||||
:members:
|
||||
|
||||
Subtitle
|
||||
^^^^^^^^
|
||||
|
||||
.. automodule:: subliminal.subtitles
|
||||
:members:
|
||||
|
||||
Utilities
|
||||
^^^^^^^^^
|
||||
|
||||
.. automodule:: subliminal.utils
|
||||
:members:
|
||||
|
||||
Exceptions
|
||||
^^^^^^^^^^
|
||||
|
||||
.. automodule:: subliminal.exceptions
|
||||
:members:
|
||||
@@ -0,0 +1,77 @@
|
||||
.. subliminal documentation master file, created by
|
||||
sphinx-quickstart on Tue Feb 28 16:33:06 2012.
|
||||
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 uses video hashes and the powerful `guessit <http://guessit.readthedocs.org/>`_ library
|
||||
that extracts informations from filenames or filepaths to ensure you have the best subtitles.
|
||||
It also relies on `enzyme <https://github.com/Diaoul/enzyme>`_ to detect embedded subtitles
|
||||
and avoid duplicates.
|
||||
|
||||
Features
|
||||
--------
|
||||
Multiple subtitles services are available:
|
||||
|
||||
* OpenSubtitles
|
||||
* TheSubDB
|
||||
* BierDopje
|
||||
* SubsWiki
|
||||
* Subtitulos
|
||||
|
||||
You can use main subliminal's functions with a **file path**, a **file name** or a **folder path**.
|
||||
|
||||
CLI
|
||||
^^^
|
||||
Download english subtitles::
|
||||
|
||||
$ subliminal -l en The.Big.Bang.Theory.S05E18.HDTV.x264-LOL.mp4
|
||||
**************************************************
|
||||
Downloaded 1 subtitles
|
||||
(Episode(u'The.Big.Bang.Theory.S05E18.HDTV.x264-LOL.mp4'), ResultSubtitle(en, opensubtitles, 0.33, The.Big.Bang.Theory.S05E18.HDTV-LOL.srt))
|
||||
**************************************************
|
||||
|
||||
Module
|
||||
^^^^^^
|
||||
List english subtitles::
|
||||
|
||||
>>> subliminal.list_subtitles('The.Big.Bang.Theory.S05E18.HDTV.x264-LOL.mp4', ['en'])
|
||||
|
||||
Multi-threaded use
|
||||
^^^^^^^^^^^^^^^^^^
|
||||
Use 4 workers to achieve the same result::
|
||||
|
||||
>>> with subliminal.Pool(4) as p:
|
||||
... p.list_subtitles('The.Big.Bang.Theory.S05E18.HDTV.x264-LOL.mp4', ['en'])
|
||||
|
||||
User Guide
|
||||
----------
|
||||
This part of the documentation details how to use subliminal for most common tasks
|
||||
|
||||
.. toctree::
|
||||
:maxdepth: 2
|
||||
|
||||
user
|
||||
|
||||
Developer Guide
|
||||
---------------
|
||||
This part of the documentation explains internal behavior of subliminal and its algorithms
|
||||
|
||||
.. toctree::
|
||||
:maxdepth: 2
|
||||
|
||||
dev
|
||||
|
||||
|
||||
API Documentation
|
||||
-----------------
|
||||
Most common subliminal features are listed here
|
||||
|
||||
.. automodule:: subliminal
|
||||
:members:
|
||||
:noindex:
|
||||
+113
@@ -0,0 +1,113 @@
|
||||
There are 4 different ways of using subliminal and each one
|
||||
is described in a dedicated section below.
|
||||
|
||||
First, here are some basics
|
||||
|
||||
Basics
|
||||
------
|
||||
Services
|
||||
^^^^^^^^
|
||||
You can use subliminal with multiple services to get the best result.
|
||||
Current available services are available in the :data:`subliminal.SERVICES` variable.
|
||||
|
||||
.. autodata:: subliminal.SERVICES
|
||||
|
||||
Languages
|
||||
^^^^^^^^^
|
||||
Subliminal supports multiple languages that are represented with their extended ISO 639-1 code.
|
||||
The current extensions to the ISO 639-1 are:
|
||||
|
||||
* *po* for Brazilian Portuguese
|
||||
|
||||
Paths
|
||||
^^^^^
|
||||
All paths parameters in subliminal most commont functions can be either *a file path*,
|
||||
*a file name* or a *folder path*
|
||||
|
||||
* File path (existing): hashes of the file will be computed and used during the search for services that supports
|
||||
this functionnality.
|
||||
* File name (or non-existing file path): the guessit python library will be used to guess informations and a text-based search will
|
||||
be done with services.
|
||||
* Folder path (containing video files): the given folder will be searched for video files using their :data:`~subliminal.videos.MIMETYPES`
|
||||
and/or :data:`~subliminal.videos.EXTENSIONS`. The default maximum depth to scan is 3
|
||||
|
||||
CLI
|
||||
---
|
||||
Subliminal is shipped with a basic Command Line Interface that allows you to
|
||||
download subtitles for one or more videos in a multi-threaded way.
|
||||
|
||||
You can have the documentation of the CLI using ``subliminal --help``::
|
||||
|
||||
usage: subliminal [-h] [-l LG] [-s NAME] [-m] [-f] [-w N] [-c] [-q | -v]
|
||||
[--cache-dir DIR | --no-cache-dir] [--version]
|
||||
PATH [PATH ...]
|
||||
|
||||
Subtitles, faster than your thoughts
|
||||
|
||||
positional arguments:
|
||||
PATH path to video file or folder
|
||||
|
||||
optional arguments:
|
||||
-h, --help show this help message and exit
|
||||
-l LG, --language LG wanted language (ISO 639-1)
|
||||
-s NAME, --service NAME
|
||||
service to use
|
||||
-m, --multi download multiple subtitle languages
|
||||
-f, --force replace existing subtitle file
|
||||
-w N, --workers N use N threads (default: 4)
|
||||
-c, --compatibility try not to use unicode (use this if you have encoding
|
||||
errors)
|
||||
-q, --quiet disable output
|
||||
-v, --verbose verbose output
|
||||
--cache-dir DIR cache directory to use
|
||||
--no-cache-dir do not use cache directory (some services may not
|
||||
work)
|
||||
--version show program's version number and exit
|
||||
|
||||
.. note::
|
||||
|
||||
The cache directory defaults to *~/.config/subliminal*. Even on Windows
|
||||
|
||||
Simple module use
|
||||
-----------------
|
||||
Subliminal comes with two basic functions to search and download subtitles. For example, you
|
||||
can do::
|
||||
|
||||
>>> subliminal.list_subtitles('The.Big.Bang.Theory.S05E18.HDTV.x264-LOL.mp4', ['en'])
|
||||
|
||||
.. autofunction:: subliminal.list_subtitles
|
||||
|
||||
Or even download missing subtitles for each episodes under the given folders in two different languages::
|
||||
|
||||
>>> subliminal.download_subtitles(['/mnt/videos/BBT/Season 05', '/mnt/videos/HIMYM/Season 07'],
|
||||
... ['en', 'fr'], force=False, multi=True)
|
||||
|
||||
.. autofunction:: subliminal.download_subtitles
|
||||
|
||||
Multi-threaded module use
|
||||
-------------------------
|
||||
You can call the same functions on a :class:`subliminal.Pool` object previously
|
||||
created with the appropriate number of workers.
|
||||
|
||||
.. autoclass:: subliminal.Pool
|
||||
:members:
|
||||
|
||||
You have to call the :meth:`~subliminal.Pool.start` method before any actions and
|
||||
:meth:`~subliminal.Pool.stop` before exiting your program::
|
||||
|
||||
>>> p = subliminal.Pool(4)
|
||||
... p.start()
|
||||
... p.list_subtitles('The.Big.Bang.Theory.S05E18.HDTV.x264-LOL.mp4', ['en'])
|
||||
... p.stop()
|
||||
|
||||
To make the use of :class:`~subliminal.Pool` easier, you can use the ``with`` statement
|
||||
that takes care of that for you::
|
||||
|
||||
>>> with subliminal.Pool(4) as p:
|
||||
... p.list_subtitles('The.Big.Bang.Theory.S05E18.HDTV.x264-LOL.mp4', ['en'])
|
||||
|
||||
|
||||
* from the command line
|
||||
* basic functions :func:`~subliminal.list_subtitles` and :func:`~subliminal.download_subtitles`
|
||||
* multi-threaded :class:`~subliminal.async.Pool` which implements the abovementioned functions
|
||||
* using your own algorithm that produces and gather results of elementary :class:`~subliminal.tasks.Task`
|
||||
@@ -0,0 +1,4 @@
|
||||
BeautifulSoup>=3.2.0
|
||||
guessit>=0.2
|
||||
requests
|
||||
enzyme>=0.1
|
||||
@@ -0,0 +1,79 @@
|
||||
#!/usr/bin/env python
|
||||
# -*- coding: utf-8 -*-
|
||||
# Copyright 2011-2012 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 GNU Lesser 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
|
||||
# GNU Lesser General Public License for more details.
|
||||
#
|
||||
# You should have received a copy of the GNU Lesser General Public License
|
||||
# along with subliminal. If not, see <http://www.gnu.org/licenses/>.
|
||||
import argparse
|
||||
import subliminal
|
||||
import logging
|
||||
import os
|
||||
import sys
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description='Subtitles, faster than your thoughts')
|
||||
parser.add_argument('-l', '--language', action='append', dest='languages', help='wanted language (ISO 639-1)', metavar='LG')
|
||||
parser.add_argument('-s', '--service', action='append', dest='services', help='service to use', metavar='NAME')
|
||||
parser.add_argument('-m', '--multi', action='store_true', help='download multiple subtitle languages')
|
||||
parser.add_argument('-f', '--force', action='store_true', help='replace existing subtitle file')
|
||||
parser.add_argument('-w', '--workers', action='store', help='use N threads (default: %(default)s)', metavar='N', default=4)
|
||||
parser.add_argument('-c', '--compatibility', action='store_true', help='try not to use unicode (use this if you have encoding errors)')
|
||||
group_verbosity = parser.add_mutually_exclusive_group()
|
||||
group_verbosity.add_argument('-q', '--quiet', action='store_true', help='disable output')
|
||||
group_verbosity.add_argument('-v', '--verbose', action='store_true', help='verbose output')
|
||||
group_cache = parser.add_mutually_exclusive_group()
|
||||
group_cache.add_argument('--cache-dir', action='store', dest='cache_dir', help='cache directory to use', metavar='DIR', default=os.path.expanduser('~/.config/subliminal'))
|
||||
group_cache.add_argument('--no-cache-dir', action='store_false', dest='cache_dir', help='do not use cache directory (some services may not work)')
|
||||
parser.add_argument('--version', action='version', version=subliminal.__version__)
|
||||
parser.add_argument('paths', nargs='+', help='path to video file or folder', metavar='PATH')
|
||||
args = parser.parse_args()
|
||||
|
||||
# Set log verbosity
|
||||
if args.verbose:
|
||||
logging.basicConfig(level=logging.DEBUG, format='%(levelname)-8s %(asctime)s %(name)-24s %(message)s', datefmt='%Y-%m-%d %H:%M:%S')
|
||||
elif not args.quiet:
|
||||
logging.basicConfig(level=logging.WARN, format='%(levelname)s: %(name)s %(message)s')
|
||||
|
||||
# Create cache directory
|
||||
if not os.path.exists(args.cache_dir):
|
||||
os.mkdir(args.cache_dir)
|
||||
|
||||
# Compatibility mode
|
||||
if args.compatibility:
|
||||
paths = args.paths
|
||||
else:
|
||||
paths = [unicode(x) for x in args.paths]
|
||||
|
||||
# Download subtitles
|
||||
with subliminal.Pool(args.workers) as p:
|
||||
subtitles = p.download_subtitles(paths, languages=args.languages,
|
||||
services=args.services, cache_dir=args.cache_dir,
|
||||
force=args.force, multi=args.multi)
|
||||
|
||||
if not subtitles:
|
||||
if not args.quiet:
|
||||
sys.stderr.write('No subtitles found\n')
|
||||
exit(1)
|
||||
if not args.quiet:
|
||||
print '*' * 50
|
||||
print 'Downloaded %d subtitles' % len(subtitles)
|
||||
for subtitle in subtitles:
|
||||
print subtitle
|
||||
print '*' * 50
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,7 @@
|
||||
[build_sphinx]
|
||||
source-dir = docs/
|
||||
build-dir = docs/_build
|
||||
all_files = 1
|
||||
|
||||
[upload_sphinx]
|
||||
upload-dir = docs/_build/html
|
||||
@@ -1,44 +1,46 @@
|
||||
#!/usr/bin/env python
|
||||
# -*- coding: utf-8 -*-
|
||||
# Copyright 2011-2012 Antoine Bertin <diaoulael@gmail.com>
|
||||
#
|
||||
# Subliminal - Subtitles, faster than your thoughts
|
||||
# Copyright (c) 2011 Antoine Bertin <diaoulael@gmail.com>
|
||||
# This file is part of subliminal.
|
||||
#
|
||||
# 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
|
||||
# subliminal is free software; you can redistribute it and/or modify it under
|
||||
# the terms of the GNU Lesser 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,
|
||||
# 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.
|
||||
# GNU Lesser 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__
|
||||
# You should have received a copy of the GNU Lesser General Public License
|
||||
# along with subliminal. If not, see <http://www.gnu.org/licenses/>.
|
||||
import os.path
|
||||
from setuptools import setup, find_packages
|
||||
|
||||
|
||||
def read(fname):
|
||||
return open(os.path.join(os.path.dirname(__file__), fname)).read()
|
||||
|
||||
execfile(os.path.join(os.path.dirname(__file__), 'subliminal', 'infos.py'))
|
||||
setup(name='subliminal',
|
||||
version=__version__,
|
||||
license="LGPLv3",
|
||||
description="Subliminal - Subtitles, faster than your thoughts",
|
||||
license='LGPLv3',
|
||||
description='Subtitles, faster than your thoughts',
|
||||
long_description=read('README.rst') + '\n\n' + read('NEWS.rst'),
|
||||
classifiers=['Development Status :: 4 - Beta',
|
||||
'License :: OSI Approved :: GNU Library or Lesser General Public License (LGPL)',
|
||||
'Intended Audience :: Developers',
|
||||
'Operating System :: OS Independent',
|
||||
'Programming Language :: Python :: 2.6',
|
||||
'Programming Language :: Python :: 2.7',
|
||||
'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"])
|
||||
keywords='subtitle subtitles video movie episode tv show',
|
||||
author='Antoine Bertin',
|
||||
author_email='diaoulael@gmail.com',
|
||||
url='https://github.com/Diaoul/subliminal',
|
||||
packages=find_packages(),
|
||||
scripts=['scripts/subliminal'],
|
||||
install_requires=['BeautifulSoup >= 3.2.0', 'guessit >= 0.2', 'requests', 'enzyme >= 0.1'])
|
||||
|
||||
@@ -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)
|
||||
+23
-14
@@ -1,25 +1,34 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
# Copyright 2011-2012 Antoine Bertin <diaoulael@gmail.com>
|
||||
#
|
||||
# Subliminal - Subtitles, faster than your thoughts
|
||||
# Copyright (c) 2011 Antoine Bertin <diaoulael@gmail.com>
|
||||
# This file is part of subliminal.
|
||||
#
|
||||
# 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
|
||||
# subliminal is free software; you can redistribute it and/or modify it under
|
||||
# the terms of the GNU Lesser 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,
|
||||
# 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.
|
||||
# GNU Lesser General Public License for more details.
|
||||
#
|
||||
# You should have received a copy of the Lesser GNU General Public License
|
||||
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
#
|
||||
|
||||
__version__ = '0.2'
|
||||
# You should have received a copy of the GNU Lesser General Public License
|
||||
# along with subliminal. If not, see <http://www.gnu.org/licenses/>.
|
||||
from .api import list_subtitles, download_subtitles
|
||||
from .async import Pool
|
||||
from .core import (SERVICES, LANGUAGE_INDEX, SERVICE_INDEX, SERVICE_CONFIDENCE,
|
||||
MATCHING_CONFIDENCE)
|
||||
from .infos import __version__
|
||||
import logging
|
||||
try:
|
||||
from logging import NullHandler
|
||||
except ImportError:
|
||||
class NullHandler(logging.Handler):
|
||||
def emit(self, record):
|
||||
pass
|
||||
|
||||
|
||||
from subliminal import *
|
||||
__all__ = ['SERVICES', 'LANGUAGE_INDEX', 'SERVICE_INDEX', 'SERVICE_CONFIDENCE',
|
||||
'MATCHING_CONFIDENCE', 'list_subtitles', 'download_subtitles', 'Pool']
|
||||
logging.getLogger(__name__).addHandler(NullHandler())
|
||||
|
||||
@@ -0,0 +1,100 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
# Copyright 2011-2012 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 GNU Lesser 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
|
||||
# GNU Lesser General Public License for more details.
|
||||
#
|
||||
# You should have received a copy of the GNU Lesser General Public License
|
||||
# along with subliminal. If not, see <http://www.gnu.org/licenses/>.
|
||||
from .core import (SERVICES, LANGUAGE_INDEX, SERVICE_INDEX, SERVICE_CONFIDENCE,
|
||||
MATCHING_CONFIDENCE, create_list_tasks, consume_task, create_download_tasks,
|
||||
group_by_video, key_subtitles)
|
||||
from .languages import list_languages
|
||||
import logging
|
||||
|
||||
|
||||
__all__ = ['list_subtitles', 'download_subtitles']
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def list_subtitles(paths, languages=None, services=None, force=True, multi=False, cache_dir=None, max_depth=3):
|
||||
"""List subtitles in given paths according to the criteria
|
||||
|
||||
:param paths: path(s) to video file or folder
|
||||
:type paths: string or list
|
||||
:param list languages: languages to search for, in preferred order
|
||||
:param list services: services to use for the search, in preferred order
|
||||
:param bool force: force searching for subtitles even if some are detected
|
||||
:param bool multi: search multiple languages for the same video
|
||||
:param string cache_dir: path to the cache directory to use
|
||||
:param int max_depth: maximum depth for scanning entries
|
||||
:return: found subtitles
|
||||
:rtype: dict of :class:`~subliminal.videos.Video` => [:class:`~subliminal.subtitles.ResultSubtitle`]
|
||||
|
||||
"""
|
||||
services = services or SERVICES
|
||||
languages = set(languages or list_languages(1))
|
||||
if isinstance(paths, basestring):
|
||||
paths = [paths]
|
||||
if any([not isinstance(p, unicode) for p in paths]):
|
||||
logger.warning(u'Not all entries are unicode')
|
||||
results = []
|
||||
service_instances = {}
|
||||
tasks = create_list_tasks(paths, languages, services, force, multi, cache_dir, max_depth)
|
||||
for task in tasks:
|
||||
try:
|
||||
result = consume_task(task, service_instances)
|
||||
results.append((task.video, result))
|
||||
except:
|
||||
logger.error(u'Error consuming task %r' % task, exc_info=True)
|
||||
for service_instance in service_instances.itervalues():
|
||||
service_instance.terminate()
|
||||
return group_by_video(results)
|
||||
|
||||
|
||||
def download_subtitles(paths, languages=None, services=None, force=True, multi=False, cache_dir=None, max_depth=3, order=None):
|
||||
"""Download subtitles in given paths according to the criteria
|
||||
|
||||
:param paths: path(s) to video file or folder
|
||||
:type paths: string or list
|
||||
:param list languages: languages to search for, in preferred order
|
||||
:param list services: services to use for the search, in preferred order
|
||||
:param bool force: force searching for subtitles even if some are detected
|
||||
:param bool multi: search multiple languages for the same video
|
||||
:param string cache_dir: path to the cache directory to use
|
||||
:param int max_depth: maximum depth for scanning entries
|
||||
:param order: preferred order for subtitles sorting
|
||||
:type list: list of :data:`~subliminal.core.LANGUAGE_INDEX`, :data:`~subliminal.core.SERVICE_INDEX`, :data:`~subliminal.core.SERVICE_CONFIDENCE`, :data:`~subliminal.core.MATCHING_CONFIDENCE`
|
||||
:return: found subtitles
|
||||
:rtype: list of (:class:`~subliminal.videos.Video`, [:class:`~subliminal.subtitles.ResultSubtitle`])
|
||||
|
||||
"""
|
||||
services = services or SERVICES
|
||||
languages = languages or list_languages(1)
|
||||
if isinstance(paths, basestring):
|
||||
paths = [paths]
|
||||
order = order or [LANGUAGE_INDEX, SERVICE_INDEX, SERVICE_CONFIDENCE, MATCHING_CONFIDENCE]
|
||||
subtitles_by_video = list_subtitles(paths, set(languages), services, force, multi, cache_dir, max_depth)
|
||||
for video, subtitles in subtitles_by_video.iteritems():
|
||||
subtitles.sort(key=lambda s: key_subtitles(s, video, languages, services, order), reverse=True)
|
||||
results = []
|
||||
service_instances = {}
|
||||
tasks = create_download_tasks(subtitles_by_video, multi)
|
||||
for task in tasks:
|
||||
try:
|
||||
result = consume_task(task, service_instances)
|
||||
results.append(result)
|
||||
except:
|
||||
logger.error(u'Error consuming task %r' % task, exc_info=True)
|
||||
for service_instance in service_instances.itervalues():
|
||||
service_instance.terminate()
|
||||
return results
|
||||
@@ -0,0 +1,141 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
# Copyright 2011-2012 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 GNU Lesser 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
|
||||
# GNU Lesser General Public License for more details.
|
||||
#
|
||||
# You should have received a copy of the GNU Lesser General Public License
|
||||
# along with subliminal. If not, see <http://www.gnu.org/licenses/>.
|
||||
from .core import (consume_task, LANGUAGE_INDEX, SERVICE_INDEX,
|
||||
SERVICE_CONFIDENCE, MATCHING_CONFIDENCE, SERVICES, create_list_tasks,
|
||||
create_download_tasks, group_by_video, key_subtitles)
|
||||
from .languages import list_languages
|
||||
from .tasks import StopTask
|
||||
import Queue
|
||||
import logging
|
||||
import threading
|
||||
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class Worker(threading.Thread):
|
||||
"""Consume tasks and put the result in the queue"""
|
||||
def __init__(self, tasks, results):
|
||||
super(Worker, self).__init__()
|
||||
self.tasks = tasks
|
||||
self.results = results
|
||||
self.services = {}
|
||||
|
||||
def run(self):
|
||||
while 1:
|
||||
result = []
|
||||
try:
|
||||
task = self.tasks.get(block=True)
|
||||
if isinstance(task, StopTask):
|
||||
break
|
||||
result = consume_task(task, self.services)
|
||||
self.results.put((task.video, result))
|
||||
except:
|
||||
logger.error(u'Exception raised in worker %s' % self.name, exc_info=True)
|
||||
finally:
|
||||
self.tasks.task_done()
|
||||
self.terminate()
|
||||
logger.debug(u'Thread %s terminated' % self.name)
|
||||
|
||||
def terminate(self):
|
||||
"""Terminate instantiated services"""
|
||||
for service_name, service in self.services.iteritems():
|
||||
try:
|
||||
service.terminate()
|
||||
except:
|
||||
logger.error(u'Exception raised when terminating service %s' % service_name, exc_info=True)
|
||||
|
||||
|
||||
class Pool(object):
|
||||
"""Pool of workers"""
|
||||
def __init__(self, size):
|
||||
self.tasks = Queue.Queue()
|
||||
self.results = Queue.Queue()
|
||||
self.workers = []
|
||||
for _ in range(size):
|
||||
self.workers.append(Worker(self.tasks, self.results))
|
||||
|
||||
def __enter__(self):
|
||||
self.start()
|
||||
return self
|
||||
|
||||
def __exit__(self, *args):
|
||||
self.stop()
|
||||
self.join()
|
||||
|
||||
def start(self):
|
||||
"""Start workers"""
|
||||
for worker in self.workers:
|
||||
worker.start()
|
||||
|
||||
def stop(self):
|
||||
"""Stop workers"""
|
||||
for _ in self.workers:
|
||||
self.tasks.put(StopTask())
|
||||
|
||||
def join(self):
|
||||
"""Join the task queue"""
|
||||
self.tasks.join()
|
||||
|
||||
def collect(self):
|
||||
"""Collect available results
|
||||
|
||||
:return: results of tasks
|
||||
:rtype: list of :class:`~subliminal.tasks.Task`
|
||||
|
||||
"""
|
||||
results = []
|
||||
while 1:
|
||||
try:
|
||||
result = self.results.get(block=False)
|
||||
results.append(result)
|
||||
except Queue.Empty:
|
||||
break
|
||||
return results
|
||||
|
||||
def list_subtitles(self, paths, languages=None, services=None, force=True, multi=False, cache_dir=None, max_depth=3):
|
||||
"""See :meth:`subliminal.list_subtitles`"""
|
||||
services = services or SERVICES
|
||||
languages = set(languages or list_languages(1))
|
||||
if isinstance(paths, basestring):
|
||||
paths = [paths]
|
||||
if any([not isinstance(p, unicode) for p in paths]):
|
||||
logger.warning(u'Not all entries are unicode')
|
||||
tasks = create_list_tasks(paths, languages, services, force, multi, cache_dir, max_depth)
|
||||
for task in tasks:
|
||||
self.tasks.put(task)
|
||||
self.join()
|
||||
results = self.collect()
|
||||
return group_by_video(results)
|
||||
|
||||
def download_subtitles(self, paths, languages=None, services=None, cache_dir=None, max_depth=3, force=True, multi=False, order=None):
|
||||
"""See :meth:`subliminal.download_subtitles`"""
|
||||
services = services or SERVICES
|
||||
languages = languages or list_languages(1)
|
||||
if isinstance(paths, basestring):
|
||||
paths = [paths]
|
||||
order = order or [LANGUAGE_INDEX, SERVICE_INDEX, SERVICE_CONFIDENCE, MATCHING_CONFIDENCE]
|
||||
subtitles_by_video = self.list_subtitles(paths, set(languages), services, force, multi, cache_dir, max_depth)
|
||||
for video, subtitles in subtitles_by_video.iteritems():
|
||||
subtitles.sort(key=lambda s: key_subtitles(s, video, languages, services, order), reverse=True)
|
||||
tasks = create_download_tasks(subtitles_by_video, multi)
|
||||
for task in tasks:
|
||||
self.tasks.put(task)
|
||||
self.join()
|
||||
results = self.collect()
|
||||
return results
|
||||
@@ -0,0 +1,240 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
# Copyright 2011-2012 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 GNU Lesser 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
|
||||
# GNU Lesser General Public License for more details.
|
||||
#
|
||||
# You should have received a copy of the GNU Lesser General Public License
|
||||
# along with subliminal. If not, see <http://www.gnu.org/licenses/>.
|
||||
from .exceptions import DownloadFailedError
|
||||
from .services import ServiceConfig
|
||||
from .tasks import DownloadTask, ListTask
|
||||
from .utils import get_keywords
|
||||
from .videos import Episode, Movie, scan
|
||||
from collections import defaultdict
|
||||
from itertools import groupby
|
||||
import guessit
|
||||
import logging
|
||||
|
||||
|
||||
__all__ = ['SERVICES', 'LANGUAGE_INDEX', 'SERVICE_INDEX', 'SERVICE_CONFIDENCE', 'MATCHING_CONFIDENCE',
|
||||
'create_list_tasks', 'create_download_tasks', 'consume_task', 'matching_confidence',
|
||||
'key_subtitles', 'group_by_video']
|
||||
logger = logging.getLogger(__name__)
|
||||
SERVICES = ['opensubtitles', 'bierdopje', 'subswiki', 'subtitulos', 'thesubdb']
|
||||
LANGUAGE_INDEX, SERVICE_INDEX, SERVICE_CONFIDENCE, MATCHING_CONFIDENCE = range(4)
|
||||
|
||||
|
||||
def create_list_tasks(paths, languages, services, force, multi, cache_dir, max_depth):
|
||||
"""Create a list of :class:`~subliminal.tasks.ListTask` from one or more paths using the given criteria
|
||||
|
||||
:param paths: path(s) to video file or folder
|
||||
:type paths: string or list
|
||||
:param set languages: languages to search for
|
||||
:param list services: services to use for the search
|
||||
:param bool force: force searching for subtitles even if some are detected
|
||||
:param bool multi: search multiple languages for the same video
|
||||
:param string cache_dir: path to the cache directory to use
|
||||
:param int max_depth: maximum depth for scanning entries
|
||||
:return: the created tasks
|
||||
:rtype: list of :class:`~subliminal.tasks.ListTask`
|
||||
|
||||
"""
|
||||
scan_result = []
|
||||
for p in paths:
|
||||
scan_result.extend(scan(p, max_depth))
|
||||
logger.debug(u'Found %d videos in %r with maximum depth %d' % (len(scan_result), paths, max_depth))
|
||||
tasks = []
|
||||
config = ServiceConfig(multi, cache_dir)
|
||||
for video, detected_subtitles in scan_result:
|
||||
detected_languages = set([s.language for s in detected_subtitles])
|
||||
wanted_languages = languages.copy()
|
||||
if not force and multi:
|
||||
wanted_languages -= detected_languages
|
||||
if not wanted_languages:
|
||||
logger.debug(u'No need to list multi subtitles %r for %r because %r detected' % (languages, video, detected_languages))
|
||||
continue
|
||||
if not force and not multi and None in detected_languages:
|
||||
logger.debug(u'No need to list single subtitles %r for %r because one detected' % (languages, video))
|
||||
continue
|
||||
logger.debug(u'Listing subtitles %r for %r with services %r' % (wanted_languages, video, services))
|
||||
for service_name in services:
|
||||
mod = __import__('services.' + service_name, globals=globals(), locals=locals(), fromlist=['Service'], level=-1)
|
||||
service = mod.Service
|
||||
service_languages = wanted_languages & service.available_languages()
|
||||
if not service_languages:
|
||||
logger.debug(u'Skipping %r: none of wanted languages %r available for service %s' % (video, wanted_languages, service_name))
|
||||
continue
|
||||
if not service.is_valid_video(video):
|
||||
logger.debug(u'Skipping %r: not part of supported videos %r for service %s' % (video, service.videos, service_name))
|
||||
continue
|
||||
task = ListTask(video, service_languages, service_name, config)
|
||||
logger.debug(u'Created task %r' % task)
|
||||
tasks.append(task)
|
||||
return tasks
|
||||
|
||||
|
||||
def create_download_tasks(subtitles_by_video, multi):
|
||||
"""Create a list of :class:`~subliminal.tasks.DownloadTask` from a list results grouped by video
|
||||
|
||||
:param subtitles_by_video: :class:`~subliminal.tasks.ListTask` results grouped by video and sorted
|
||||
:type subtitles_by_video: dict of :class:`~subliminal.videos.Video` => [:class:`~subliminal.subtitles.Subtitle`]
|
||||
:param order: preferred order for subtitles sorting
|
||||
:type list: list of :data:`LANGUAGE_INDEX`, :data:`SERVICE_INDEX`, :data:`SERVICE_CONFIDENCE`, :data:`MATCHING_CONFIDENCE`
|
||||
:param bool multi: download multiple languages for the same video
|
||||
:return: the created tasks
|
||||
:rtype: list of :class:`~subliminal.tasks.DownloadTask`
|
||||
|
||||
"""
|
||||
tasks = []
|
||||
for video, subtitles in subtitles_by_video.iteritems():
|
||||
if not subtitles:
|
||||
continue
|
||||
if not multi:
|
||||
task = DownloadTask(video, list(subtitles))
|
||||
logger.debug(u'Created task %r' % task)
|
||||
tasks.append(task)
|
||||
continue
|
||||
for _, by_language in groupby(subtitles, lambda s: s.language):
|
||||
task = DownloadTask(video, list(by_language))
|
||||
logger.debug(u'Created task %r' % task)
|
||||
tasks.append(task)
|
||||
return tasks
|
||||
|
||||
|
||||
def consume_task(task, services=None):
|
||||
"""Consume a task. If the ``services`` parameter is given, the function will attempt
|
||||
to get the service from it. In case the service is not in ``services``, it will be initialized
|
||||
and put in ``services``
|
||||
|
||||
:param task: task to consume
|
||||
:type task: :class:`~subliminal.tasks.ListTask` or :class:`~subliminal.tasks.DownloadTask`
|
||||
:param dict services: mapping between the service name and an instance of this service
|
||||
:return: the result of the task
|
||||
:rtype: list of :class:`~subliminal.subtitles.ResultSubtitle` or :class:`~subliminal.subtitles.Subtitle`
|
||||
|
||||
"""
|
||||
if services is None:
|
||||
services = {}
|
||||
logger.info(u'Consuming %r' % task)
|
||||
result = None
|
||||
if isinstance(task, ListTask):
|
||||
if task.service not in services:
|
||||
mod = __import__('services.' + task.service, globals=globals(), locals=locals(), fromlist=['Service'], level=-1)
|
||||
services[task.service] = mod.Service(task.config)
|
||||
services[task.service].init()
|
||||
subtitles = services[task.service].list(task.video, task.languages)
|
||||
result = subtitles
|
||||
elif isinstance(task, DownloadTask):
|
||||
for subtitle in task.subtitles:
|
||||
if subtitle.service not in services:
|
||||
mod = __import__('services.' + subtitle.service, globals=globals(), locals=locals(), fromlist=['Service'], level=-1)
|
||||
services[subtitle.service] = mod.Service()
|
||||
services[subtitle.service].init()
|
||||
try:
|
||||
services[subtitle.service].download(subtitle)
|
||||
result = subtitle
|
||||
break
|
||||
except DownloadFailedError:
|
||||
logger.warning(u'Could not download subtitle %r, trying next' % subtitle)
|
||||
continue
|
||||
if result is None:
|
||||
logger.error(u'No subtitles could be downloaded for video %r' % task.video)
|
||||
return result
|
||||
|
||||
|
||||
def matching_confidence(video, subtitle):
|
||||
"""Compute the probability (confidence) that the subtitle matches the video
|
||||
|
||||
:param video: video to match
|
||||
:type video: :class:`~subliminal.videos.Video`
|
||||
:param subtitle: subtitle to match
|
||||
:type subtitle: :class:`~subliminal.subtitles.Subtitle`
|
||||
:return: the matching probability
|
||||
:rtype: float
|
||||
|
||||
"""
|
||||
guess = guessit.guess_file_info(subtitle.release, 'autodetect')
|
||||
video_keywords = get_keywords(video.guess)
|
||||
subtitle_keywords = get_keywords(guess) | subtitle.keywords
|
||||
replacement = {'keywords': len(video_keywords & subtitle_keywords)}
|
||||
if isinstance(video, Episode):
|
||||
replacement.update({'series': 0, 'season': 0, 'episode': 0})
|
||||
matching_format = '{series:b}{season:b}{episode:b}{keywords:03b}'
|
||||
best = matching_format.format(series=1, season=1, episode=1, keywords=len(video_keywords))
|
||||
if guess['type'] in ['episode', 'episodesubtitle']:
|
||||
if 'series' in guess and guess['series'].lower() == video.series.lower():
|
||||
replacement['series'] = 1
|
||||
if 'season' in guess and guess['season'] == video.season:
|
||||
replacement['season'] = 1
|
||||
if 'episodeNumber' in guess and guess['episodeNumber'] == video.episode:
|
||||
replacement['episode'] = 1
|
||||
elif isinstance(video, Movie):
|
||||
replacement.update({'title': 0, 'year': 0})
|
||||
matching_format = '{title:b}{year:b}{keywords:03b}'
|
||||
best = matching_format.format(title=1, year=1, keywords=len(video_keywords))
|
||||
if guess['type'] in ['movie', 'moviesubtitle']:
|
||||
if 'title' in guess and guess['title'].lower() == video.title.lower():
|
||||
replacement['title'] = 1
|
||||
if 'year' in guess and guess['year'] == video.year:
|
||||
replacement['year'] = 1
|
||||
else:
|
||||
return 0
|
||||
confidence = float(int(matching_format.format(**replacement), 2)) / float(int(best, 2))
|
||||
return confidence
|
||||
|
||||
|
||||
def key_subtitles(subtitle, video, languages, services, order):
|
||||
"""Create a key to sort subtitle using the given order
|
||||
|
||||
:param subtitle: subtitle to sort
|
||||
:type subtitle: :class:`~subliminal.subtitles.ResultSubtitle`
|
||||
:param video: video to match
|
||||
:type video: :class:`~subliminal.videos.Video`
|
||||
:param list languages: languages in preferred order
|
||||
:param list services: services in preferred order
|
||||
:param order: preferred order for subtitles sorting
|
||||
:type list: list of :data:`LANGUAGE_INDEX`, :data:`SERVICE_INDEX`, :data:`SERVICE_CONFIDENCE`, :data:`MATCHING_CONFIDENCE`
|
||||
:return: a key ready to use for subtitles sorting
|
||||
:rtype: int
|
||||
|
||||
"""
|
||||
key = ''
|
||||
for sort_item in order:
|
||||
if sort_item == LANGUAGE_INDEX:
|
||||
key += '{0:03d}'.format(len(languages) - languages.index(subtitle.language) - 1)
|
||||
elif sort_item == SERVICE_INDEX:
|
||||
key += '{0:02d}'.format(len(services) - services.index(subtitle.service) - 1)
|
||||
elif sort_item == SERVICE_CONFIDENCE:
|
||||
key += '{0:04d}'.format(int(subtitle.confidence * 1000))
|
||||
elif sort_item == MATCHING_CONFIDENCE:
|
||||
confidence = 0
|
||||
if subtitle.release:
|
||||
confidence = matching_confidence(video, subtitle)
|
||||
key += '{0:04d}'.format(int(confidence * 1000))
|
||||
return int(key)
|
||||
|
||||
|
||||
def group_by_video(list_results):
|
||||
"""Group the results of :class:`ListTasks <subliminal.tasks.ListTask>` into a
|
||||
dictionary of :class:`~subliminal.videos.Video` => :class:`~subliminal.subtitles.Subtitle`
|
||||
|
||||
:param list_results:
|
||||
:type list_results: list of result of :class:`~subliminal.tasks.ListTask`
|
||||
:return: subtitles grouped by videos
|
||||
:rtype: dict of :class:`~subliminal.videos.Video` => [:class:`~subliminal.subtitles.Subtitle`]
|
||||
|
||||
"""
|
||||
result = defaultdict(list)
|
||||
for video, subtitles in list_results:
|
||||
result[video] += subtitles
|
||||
return result
|
||||
@@ -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,81 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
# Copyright 2011-2012 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 GNU Lesser 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
|
||||
# GNU Lesser General Public License for more details.
|
||||
#
|
||||
# You should have received a copy of the GNU Lesser General Public License
|
||||
# along with subliminal. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
|
||||
class Error(Exception):
|
||||
"""Base class for exceptions in subliminal"""
|
||||
pass
|
||||
|
||||
|
||||
class InvalidLanguageError(Error):
|
||||
"""Exception raised when invalid language is submitted
|
||||
|
||||
Attributes:
|
||||
language -- language that cause the error
|
||||
"""
|
||||
def __init__(self, language):
|
||||
self.language = language
|
||||
|
||||
def __str__(self):
|
||||
return self.language
|
||||
|
||||
|
||||
class MissingLanguageError(Error):
|
||||
"""Exception raised when a missing language is found
|
||||
|
||||
Attributes:
|
||||
language -- the missing language
|
||||
"""
|
||||
def __init__(self, language):
|
||||
self.language = language
|
||||
|
||||
def __str__(self):
|
||||
return self.language
|
||||
|
||||
|
||||
class InvalidServiceError(Error):
|
||||
"""Exception raised when invalid service is submitted
|
||||
|
||||
:param string service: service that causes the error
|
||||
|
||||
"""
|
||||
def __init__(self, service):
|
||||
self.service = service
|
||||
|
||||
def __str__(self):
|
||||
return self.service
|
||||
|
||||
|
||||
class ServiceError(Error):
|
||||
""""Exception raised by services"""
|
||||
pass
|
||||
|
||||
|
||||
class WrongTaskError(Error):
|
||||
""""Exception raised when invalid task is submitted"""
|
||||
pass
|
||||
|
||||
|
||||
class DownloadFailedError(Error):
|
||||
""""Exception raised when a download task has failed in service"""
|
||||
pass
|
||||
|
||||
|
||||
class UnknownVideoError(Error):
|
||||
""""Exception raised when a video could not be identified"""
|
||||
pass
|
||||
@@ -0,0 +1,18 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
# Copyright 2011-2012 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 GNU Lesser 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
|
||||
# GNU Lesser General Public License for more details.
|
||||
#
|
||||
# You should have received a copy of the GNU Lesser General Public License
|
||||
# along with subliminal. If not, see <http://www.gnu.org/licenses/>.
|
||||
__version__ = '0.5.1'
|
||||
@@ -0,0 +1,547 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
# Copyright 2011-2012 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 GNU Lesser 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
|
||||
# GNU Lesser General Public License for more details.
|
||||
#
|
||||
# You should have received a copy of the GNU Lesser General Public License
|
||||
# along with subliminal. If not, see <http://www.gnu.org/licenses/>.
|
||||
__all__ = ['convert_language', 'list_languages', 'LANGUAGES']
|
||||
|
||||
|
||||
def convert_language(language, to_iso, from_iso=None):
|
||||
"""Convert a language into another format
|
||||
|
||||
:param string language: language
|
||||
:param int to_iso: convert language to ISO-639-x
|
||||
:param int from_iso: convert language from ISO-639-x
|
||||
:return: converted language
|
||||
:rtype: string
|
||||
|
||||
"""
|
||||
if from_iso == None: # if no from_iso is given, try to guess it
|
||||
if language.startswith(language[:1].upper()):
|
||||
from_iso = 0
|
||||
elif len(language) == 2:
|
||||
from_iso = 1
|
||||
elif len(language) == 3:
|
||||
from_iso = 2
|
||||
else:
|
||||
raise ValueError('Invalid input language format')
|
||||
if isinstance(language, unicode):
|
||||
language = language.encode('utf-8')
|
||||
converted_language = None
|
||||
for language_tuple in LANGUAGES:
|
||||
if language_tuple[from_iso] == language and language_tuple[to_iso]:
|
||||
converted_language = language_tuple[to_iso]
|
||||
break
|
||||
return converted_language
|
||||
|
||||
|
||||
def list_languages(iso):
|
||||
"""List languages in the given ISO-639-x format
|
||||
|
||||
:param int iso: ISO-639-x format to list
|
||||
:return: languages in the requested format
|
||||
:rtype: list
|
||||
|
||||
"""
|
||||
return [l[iso] for l in LANGUAGES if l[iso]]
|
||||
|
||||
#: ISO-639-2 languages list from http://www.loc.gov/standards/iso639-2/ISO-639-2_utf-8.txt
|
||||
#: + ('Brazilian', 'po', 'pob')
|
||||
LANGUAGES = [('Afar', 'aa', 'aar'),
|
||||
('Abkhazian', 'ab', 'abk'),
|
||||
('Achinese', '', 'ace'),
|
||||
('Acoli', '', 'ach'),
|
||||
('Adangme', '', 'ada'),
|
||||
('Adyghe; Adygei', '', 'ady'),
|
||||
('Afro-Asiatic languages', '', 'afa'),
|
||||
('Afrihili', '', 'afh'),
|
||||
('Afrikaans', 'af', 'afr'),
|
||||
('Ainu', '', 'ain'),
|
||||
('Akan', 'ak', 'aka'),
|
||||
('Akkadian', '', 'akk'),
|
||||
('Albanian', 'sq', 'alb'),
|
||||
('Aleut', '', 'ale'),
|
||||
('Algonquian languages', '', 'alg'),
|
||||
('Southern Altai', '', 'alt'),
|
||||
('Amharic', 'am', 'amh'),
|
||||
('English, Old (ca.450-1100)', '', 'ang'),
|
||||
('Angika', '', 'anp'),
|
||||
('Apache languages', '', 'apa'),
|
||||
('Arabic', 'ar', 'ara'),
|
||||
('Official Aramaic (700-300 BCE); Imperial Aramaic (700-300 BCE)', '', 'arc'),
|
||||
('Aragonese', 'an', 'arg'),
|
||||
('Armenian', 'hy', 'arm'),
|
||||
('Mapudungun; Mapuche', '', 'arn'),
|
||||
('Arapaho', '', 'arp'),
|
||||
('Artificial languages', '', 'art'),
|
||||
('Arawak', '', 'arw'),
|
||||
('Assamese', 'as', 'asm'),
|
||||
('Asturian; Bable; Leonese; Asturleonese', '', 'ast'),
|
||||
('Athapascan languages', '', 'ath'),
|
||||
('Australian languages', '', 'aus'),
|
||||
('Avaric', 'av', 'ava'),
|
||||
('Avestan', 'ae', 'ave'),
|
||||
('Awadhi', '', 'awa'),
|
||||
('Aymara', 'ay', 'aym'),
|
||||
('Azerbaijani', 'az', 'aze'),
|
||||
('Banda languages', '', 'bad'),
|
||||
('Bamileke languages', '', 'bai'),
|
||||
('Bashkir', 'ba', 'bak'),
|
||||
('Baluchi', '', 'bal'),
|
||||
('Bambara', 'bm', 'bam'),
|
||||
('Balinese', '', 'ban'),
|
||||
('Basque', 'eu', 'baq'),
|
||||
('Basa', '', 'bas'),
|
||||
('Baltic languages', '', 'bat'),
|
||||
('Beja; Bedawiyet', '', 'bej'),
|
||||
('Belarusian', 'be', 'bel'),
|
||||
('Bemba', '', 'bem'),
|
||||
('Bengali', 'bn', 'ben'),
|
||||
('Berber languages', '', 'ber'),
|
||||
('Bhojpuri', '', 'bho'),
|
||||
('Bihari languages', 'bh', 'bih'),
|
||||
('Bikol', '', 'bik'),
|
||||
('Bini; Edo', '', 'bin'),
|
||||
('Bislama', 'bi', 'bis'),
|
||||
('Siksika', '', 'bla'),
|
||||
('Bantu (Other)', '', 'bnt'),
|
||||
('Bosnian', 'bs', 'bos'),
|
||||
('Braj', '', 'bra'),
|
||||
('Breton', 'br', 'bre'),
|
||||
('Batak languages', '', 'btk'),
|
||||
('Buriat', '', 'bua'),
|
||||
('Buginese', '', 'bug'),
|
||||
('Bulgarian', 'bg', 'bul'),
|
||||
('Burmese', 'my', 'bur'),
|
||||
('Blin; Bilin', '', 'byn'),
|
||||
('Caddo', '', 'cad'),
|
||||
('Central American Indian languages', '', 'cai'),
|
||||
('Galibi Carib', '', 'car'),
|
||||
('Catalan; Valencian', 'ca', 'cat'),
|
||||
('Caucasian languages', '', 'cau'),
|
||||
('Cebuano', '', 'ceb'),
|
||||
('Celtic languages', '', 'cel'),
|
||||
('Chamorro', 'ch', 'cha'),
|
||||
('Chibcha', '', 'chb'),
|
||||
('Chechen', 'ce', 'che'),
|
||||
('Chagatai', '', 'chg'),
|
||||
('Chinese', 'zh', 'chi'),
|
||||
('Chuukese', '', 'chk'),
|
||||
('Mari', '', 'chm'),
|
||||
('Chinook jargon', '', 'chn'),
|
||||
('Choctaw', '', 'cho'),
|
||||
('Chipewyan; Dene Suline', '', 'chp'),
|
||||
('Cherokee', '', 'chr'),
|
||||
('Church Slavic; Old Slavonic; Church Slavonic; Old Bulgarian; Old Church Slavonic', 'cu', 'chu'),
|
||||
('Chuvash', 'cv', 'chv'),
|
||||
('Cheyenne', '', 'chy'),
|
||||
('Chamic languages', '', 'cmc'),
|
||||
('Coptic', '', 'cop'),
|
||||
('Cornish', 'kw', 'cor'),
|
||||
('Corsican', 'co', 'cos'),
|
||||
('Creoles and pidgins, English based', '', 'cpe'),
|
||||
('Creoles and pidgins, French-based ', '', 'cpf'),
|
||||
('Creoles and pidgins, Portuguese-based ', '', 'cpp'),
|
||||
('Cree', 'cr', 'cre'),
|
||||
('Crimean Tatar; Crimean Turkish', '', 'crh'),
|
||||
('Creoles and pidgins ', '', 'crp'),
|
||||
('Kashubian', '', 'csb'),
|
||||
('Cushitic languages', '', 'cus'),
|
||||
('Czech', 'cs', 'cze'),
|
||||
('Dakota', '', 'dak'),
|
||||
('Danish', 'da', 'dan'),
|
||||
('Dargwa', '', 'dar'),
|
||||
('Land Dayak languages', '', 'day'),
|
||||
('Delaware', '', 'del'),
|
||||
('Slave (Athapascan)', '', 'den'),
|
||||
('Dogrib', '', 'dgr'),
|
||||
('Dinka', '', 'din'),
|
||||
('Divehi; Dhivehi; Maldivian', 'dv', 'div'),
|
||||
('Dogri', '', 'doi'),
|
||||
('Dravidian languages', '', 'dra'),
|
||||
('Lower Sorbian', '', 'dsb'),
|
||||
('Duala', '', 'dua'),
|
||||
('Dutch, Middle (ca.1050-1350)', '', 'dum'),
|
||||
('Dutch; Flemish', 'nl', 'dut'),
|
||||
('Dyula', '', 'dyu'),
|
||||
('Dzongkha', 'dz', 'dzo'),
|
||||
('Efik', '', 'efi'),
|
||||
('Egyptian (Ancient)', '', 'egy'),
|
||||
('Ekajuk', '', 'eka'),
|
||||
('Elamite', '', 'elx'),
|
||||
('English', 'en', 'eng'),
|
||||
('English, Middle (1100-1500)', '', 'enm'),
|
||||
('Esperanto', 'eo', 'epo'),
|
||||
('Estonian', 'et', 'est'),
|
||||
('Ewe', 'ee', 'ewe'),
|
||||
('Ewondo', '', 'ewo'),
|
||||
('Fang', '', 'fan'),
|
||||
('Faroese', 'fo', 'fao'),
|
||||
('Fanti', '', 'fat'),
|
||||
('Fijian', 'fj', 'fij'),
|
||||
('Filipino; Pilipino', '', 'fil'),
|
||||
('Finnish', 'fi', 'fin'),
|
||||
('Finno-Ugrian languages', '', 'fiu'),
|
||||
('Fon', '', 'fon'),
|
||||
('French', 'fr', 'fre'),
|
||||
('French, Middle (ca.1400-1600)', '', 'frm'),
|
||||
('French, Old (842-ca.1400)', '', 'fro'),
|
||||
('Northern Frisian', '', 'frr'),
|
||||
('Eastern Frisian', '', 'frs'),
|
||||
('Western Frisian', 'fy', 'fry'),
|
||||
('Fulah', 'ff', 'ful'),
|
||||
('Friulian', '', 'fur'),
|
||||
('Ga', '', 'gaa'),
|
||||
('Gayo', '', 'gay'),
|
||||
('Gbaya', '', 'gba'),
|
||||
('Germanic languages', '', 'gem'),
|
||||
('Georgian', 'ka', 'geo'),
|
||||
('German', 'de', 'ger'),
|
||||
('Geez', '', 'gez'),
|
||||
('Gilbertese', '', 'gil'),
|
||||
('Gaelic; Scottish Gaelic', 'gd', 'gla'),
|
||||
('Irish', 'ga', 'gle'),
|
||||
('Galician', 'gl', 'glg'),
|
||||
('Manx', 'gv', 'glv'),
|
||||
('German, Middle High (ca.1050-1500)', '', 'gmh'),
|
||||
('German, Old High (ca.750-1050)', '', 'goh'),
|
||||
('Gondi', '', 'gon'),
|
||||
('Gorontalo', '', 'gor'),
|
||||
('Gothic', '', 'got'),
|
||||
('Grebo', '', 'grb'),
|
||||
('Greek, Ancient (to 1453)', '', 'grc'),
|
||||
('Greek, Modern (1453-)', 'el', 'gre'),
|
||||
('Guarani', 'gn', 'grn'),
|
||||
('Swiss German; Alemannic; Alsatian', '', 'gsw'),
|
||||
('Gujarati', 'gu', 'guj'),
|
||||
('Gwich\'in', '', 'gwi'),
|
||||
('Haida', '', 'hai'),
|
||||
('Haitian; Haitian Creole', 'ht', 'hat'),
|
||||
('Hausa', 'ha', 'hau'),
|
||||
('Hawaiian', '', 'haw'),
|
||||
('Hebrew', 'he', 'heb'),
|
||||
('Herero', 'hz', 'her'),
|
||||
('Hiligaynon', '', 'hil'),
|
||||
('Himachali languages; Western Pahari languages', '', 'him'),
|
||||
('Hindi', 'hi', 'hin'),
|
||||
('Hittite', '', 'hit'),
|
||||
('Hmong; Mong', '', 'hmn'),
|
||||
('Hiri Motu', 'ho', 'hmo'),
|
||||
('Croatian', 'hr', 'hrv'),
|
||||
('Upper Sorbian', '', 'hsb'),
|
||||
('Hungarian', 'hu', 'hun'),
|
||||
('Hupa', '', 'hup'),
|
||||
('Iban', '', 'iba'),
|
||||
('Igbo', 'ig', 'ibo'),
|
||||
('Icelandic', 'is', 'ice'),
|
||||
('Ido', 'io', 'ido'),
|
||||
('Sichuan Yi; Nuosu', 'ii', 'iii'),
|
||||
('Ijo languages', '', 'ijo'),
|
||||
('Inuktitut', 'iu', 'iku'),
|
||||
('Interlingue; Occidental', 'ie', 'ile'),
|
||||
('Iloko', '', 'ilo'),
|
||||
('Interlingua (International Auxiliary Language Association)', 'ia', 'ina'),
|
||||
('Indic languages', '', 'inc'),
|
||||
('Indonesian', 'id', 'ind'),
|
||||
('Indo-European languages', '', 'ine'),
|
||||
('Ingush', '', 'inh'),
|
||||
('Inupiaq', 'ik', 'ipk'),
|
||||
('Iranian languages', '', 'ira'),
|
||||
('Iroquoian languages', '', 'iro'),
|
||||
('Italian', 'it', 'ita'),
|
||||
('Javanese', 'jv', 'jav'),
|
||||
('Lojban', '', 'jbo'),
|
||||
('Japanese', 'ja', 'jpn'),
|
||||
('Judeo-Persian', '', 'jpr'),
|
||||
('Judeo-Arabic', '', 'jrb'),
|
||||
('Kara-Kalpak', '', 'kaa'),
|
||||
('Kabyle', '', 'kab'),
|
||||
('Kachin; Jingpho', '', 'kac'),
|
||||
('Kalaallisut; Greenlandic', 'kl', 'kal'),
|
||||
('Kamba', '', 'kam'),
|
||||
('Kannada', 'kn', 'kan'),
|
||||
('Karen languages', '', 'kar'),
|
||||
('Kashmiri', 'ks', 'kas'),
|
||||
('Kanuri', 'kr', 'kau'),
|
||||
('Kawi', '', 'kaw'),
|
||||
('Kazakh', 'kk', 'kaz'),
|
||||
('Kabardian', '', 'kbd'),
|
||||
('Khasi', '', 'kha'),
|
||||
('Khoisan languages', '', 'khi'),
|
||||
('Central Khmer', 'km', 'khm'),
|
||||
('Khotanese; Sakan', '', 'kho'),
|
||||
('Kikuyu; Gikuyu', 'ki', 'kik'),
|
||||
('Kinyarwanda', 'rw', 'kin'),
|
||||
('Kirghiz; Kyrgyz', 'ky', 'kir'),
|
||||
('Kimbundu', '', 'kmb'),
|
||||
('Konkani', '', 'kok'),
|
||||
('Komi', 'kv', 'kom'),
|
||||
('Kongo', 'kg', 'kon'),
|
||||
('Korean', 'ko', 'kor'),
|
||||
('Kosraean', '', 'kos'),
|
||||
('Kpelle', '', 'kpe'),
|
||||
('Karachay-Balkar', '', 'krc'),
|
||||
('Karelian', '', 'krl'),
|
||||
('Kru languages', '', 'kro'),
|
||||
('Kurukh', '', 'kru'),
|
||||
('Kuanyama; Kwanyama', 'kj', 'kua'),
|
||||
('Kumyk', '', 'kum'),
|
||||
('Kurdish', 'ku', 'kur'),
|
||||
('Kutenai', '', 'kut'),
|
||||
('Ladino', '', 'lad'),
|
||||
('Lahnda', '', 'lah'),
|
||||
('Lamba', '', 'lam'),
|
||||
('Lao', 'lo', 'lao'),
|
||||
('Latin', 'la', 'lat'),
|
||||
('Latvian', 'lv', 'lav'),
|
||||
('Lezghian', '', 'lez'),
|
||||
('Limburgan; Limburger; Limburgish', 'li', 'lim'),
|
||||
('Lingala', 'ln', 'lin'),
|
||||
('Lithuanian', 'lt', 'lit'),
|
||||
('Mongo', '', 'lol'),
|
||||
('Lozi', '', 'loz'),
|
||||
('Luxembourgish; Letzeburgesch', 'lb', 'ltz'),
|
||||
('Luba-Lulua', '', 'lua'),
|
||||
('Luba-Katanga', 'lu', 'lub'),
|
||||
('Ganda', 'lg', 'lug'),
|
||||
('Luiseno', '', 'lui'),
|
||||
('Lunda', '', 'lun'),
|
||||
('Luo (Kenya and Tanzania)', '', 'luo'),
|
||||
('Lushai', '', 'lus'),
|
||||
('Macedonian', 'mk', 'mac'),
|
||||
('Madurese', '', 'mad'),
|
||||
('Magahi', '', 'mag'),
|
||||
('Marshallese', 'mh', 'mah'),
|
||||
('Maithili', '', 'mai'),
|
||||
('Makasar', '', 'mak'),
|
||||
('Malayalam', 'ml', 'mal'),
|
||||
('Mandingo', '', 'man'),
|
||||
('Maori', 'mi', 'mao'),
|
||||
('Austronesian languages', '', 'map'),
|
||||
('Marathi', 'mr', 'mar'),
|
||||
('Masai', '', 'mas'),
|
||||
('Malay', 'ms', 'may'),
|
||||
('Moksha', '', 'mdf'),
|
||||
('Mandar', '', 'mdr'),
|
||||
('Mende', '', 'men'),
|
||||
('Irish, Middle (900-1200)', '', 'mga'),
|
||||
('Mi\'kmaq; Micmac', '', 'mic'),
|
||||
('Minangkabau', '', 'min'),
|
||||
('Uncoded languages', '', 'mis'),
|
||||
('Mon-Khmer languages', '', 'mkh'),
|
||||
('Malagasy', 'mg', 'mlg'),
|
||||
('Maltese', 'mt', 'mlt'),
|
||||
('Manchu', '', 'mnc'),
|
||||
('Manipuri', '', 'mni'),
|
||||
('Manobo languages', '', 'mno'),
|
||||
('Mohawk', '', 'moh'),
|
||||
('Mongolian', 'mn', 'mon'),
|
||||
('Mossi', '', 'mos'),
|
||||
('Multiple languages', '', 'mul'),
|
||||
('Munda languages', '', 'mun'),
|
||||
('Creek', '', 'mus'),
|
||||
('Mirandese', '', 'mwl'),
|
||||
('Marwari', '', 'mwr'),
|
||||
('Mayan languages', '', 'myn'),
|
||||
('Erzya', '', 'myv'),
|
||||
('Nahuatl languages', '', 'nah'),
|
||||
('North American Indian languages', '', 'nai'),
|
||||
('Neapolitan', '', 'nap'),
|
||||
('Nauru', 'na', 'nau'),
|
||||
('Navajo; Navaho', 'nv', 'nav'),
|
||||
('Ndebele, South; South Ndebele', 'nr', 'nbl'),
|
||||
('Ndebele, North; North Ndebele', 'nd', 'nde'),
|
||||
('Ndonga', 'ng', 'ndo'),
|
||||
('Low German; Low Saxon; German, Low; Saxon, Low', '', 'nds'),
|
||||
('Nepali', 'ne', 'nep'),
|
||||
('Nepal Bhasa; Newari', '', 'new'),
|
||||
('Nias', '', 'nia'),
|
||||
('Niger-Kordofanian languages', '', 'nic'),
|
||||
('Niuean', '', 'niu'),
|
||||
('Norwegian Nynorsk; Nynorsk, Norwegian', 'nn', 'nno'),
|
||||
('Bokmål, Norwegian; Norwegian Bokmål', 'nb', 'nob'),
|
||||
('Nogai', '', 'nog'),
|
||||
('Norse, Old', '', 'non'),
|
||||
('Norwegian', 'no', 'nor'),
|
||||
('N\'Ko', '', 'nqo'),
|
||||
('Pedi; Sepedi; Northern Sotho', '', 'nso'),
|
||||
('Nubian languages', '', 'nub'),
|
||||
('Classical Newari; Old Newari; Classical Nepal Bhasa', '', 'nwc'),
|
||||
('Chichewa; Chewa; Nyanja', 'ny', 'nya'),
|
||||
('Nyamwezi', '', 'nym'),
|
||||
('Nyankole', '', 'nyn'),
|
||||
('Nyoro', '', 'nyo'),
|
||||
('Nzima', '', 'nzi'),
|
||||
('Occitan (post 1500); Provençal', 'oc', 'oci'),
|
||||
('Ojibwa', 'oj', 'oji'),
|
||||
('Oriya', 'or', 'ori'),
|
||||
('Oromo', 'om', 'orm'),
|
||||
('Osage', '', 'osa'),
|
||||
('Ossetian; Ossetic', 'os', 'oss'),
|
||||
('Turkish, Ottoman (1500-1928)', '', 'ota'),
|
||||
('Otomian languages', '', 'oto'),
|
||||
('Papuan languages', '', 'paa'),
|
||||
('Pangasinan', '', 'pag'),
|
||||
('Pahlavi', '', 'pal'),
|
||||
('Pampanga; Kapampangan', '', 'pam'),
|
||||
('Panjabi; Punjabi', 'pa', 'pan'),
|
||||
('Papiamento', '', 'pap'),
|
||||
('Palauan', '', 'pau'),
|
||||
('Persian, Old (ca.600-400 B.C.)', '', 'peo'),
|
||||
('Persian', 'fa', 'per'),
|
||||
('Philippine languages', '', 'phi'),
|
||||
('Phoenician', '', 'phn'),
|
||||
('Pali', 'pi', 'pli'),
|
||||
('Polish', 'pl', 'pol'),
|
||||
('Pohnpeian', '', 'pon'),
|
||||
('Portuguese', 'pt', 'por'),
|
||||
('Prakrit languages', '', 'pra'),
|
||||
('Provençal, Old (to 1500)', '', 'pro'),
|
||||
('Pushto; Pashto', 'ps', 'pus'),
|
||||
('Reserved for local use', '', 'qaa-qtz'),
|
||||
('Quechua', 'qu', 'que'),
|
||||
('Rajasthani', '', 'raj'),
|
||||
('Rapanui', '', 'rap'),
|
||||
('Rarotongan; Cook Islands Maori', '', 'rar'),
|
||||
('Romance languages', '', 'roa'),
|
||||
('Romansh', 'rm', 'roh'),
|
||||
('Romany', '', 'rom'),
|
||||
('Romanian; Moldavian; Moldovan', 'ro', 'rum'),
|
||||
('Rundi', 'rn', 'run'),
|
||||
('Aromanian; Arumanian; Macedo-Romanian', '', 'rup'),
|
||||
('Russian', 'ru', 'rus'),
|
||||
('Sandawe', '', 'sad'),
|
||||
('Sango', 'sg', 'sag'),
|
||||
('Yakut', '', 'sah'),
|
||||
('South American Indian (Other)', '', 'sai'),
|
||||
('Salishan languages', '', 'sal'),
|
||||
('Samaritan Aramaic', '', 'sam'),
|
||||
('Sanskrit', 'sa', 'san'),
|
||||
('Sasak', '', 'sas'),
|
||||
('Santali', '', 'sat'),
|
||||
('Sicilian', '', 'scn'),
|
||||
('Scots', '', 'sco'),
|
||||
('Selkup', '', 'sel'),
|
||||
('Semitic languages', '', 'sem'),
|
||||
('Irish, Old (to 900)', '', 'sga'),
|
||||
('Sign Languages', '', 'sgn'),
|
||||
('Shan', '', 'shn'),
|
||||
('Sidamo', '', 'sid'),
|
||||
('Sinhala; Sinhalese', 'si', 'sin'),
|
||||
('Siouan languages', '', 'sio'),
|
||||
('Sino-Tibetan languages', '', 'sit'),
|
||||
('Slavic languages', '', 'sla'),
|
||||
('Slovak', 'sk', 'slo'),
|
||||
('Slovenian', 'sl', 'slv'),
|
||||
('Southern Sami', '', 'sma'),
|
||||
('Northern Sami', 'se', 'sme'),
|
||||
('Sami languages', '', 'smi'),
|
||||
('Lule Sami', '', 'smj'),
|
||||
('Inari Sami', '', 'smn'),
|
||||
('Samoan', 'sm', 'smo'),
|
||||
('Skolt Sami', '', 'sms'),
|
||||
('Shona', 'sn', 'sna'),
|
||||
('Sindhi', 'sd', 'snd'),
|
||||
('Soninke', '', 'snk'),
|
||||
('Sogdian', '', 'sog'),
|
||||
('Somali', 'so', 'som'),
|
||||
('Songhai languages', '', 'son'),
|
||||
('Sotho, Southern', 'st', 'sot'),
|
||||
('Spanish; Castilian', 'es', 'spa'),
|
||||
('Sardinian', 'sc', 'srd'),
|
||||
('Sranan Tongo', '', 'srn'),
|
||||
('Serbian', 'sr', 'srp'),
|
||||
('Serer', '', 'srr'),
|
||||
('Nilo-Saharan languages', '', 'ssa'),
|
||||
('Swati', 'ss', 'ssw'),
|
||||
('Sukuma', '', 'suk'),
|
||||
('Sundanese', 'su', 'sun'),
|
||||
('Susu', '', 'sus'),
|
||||
('Sumerian', '', 'sux'),
|
||||
('Swahili', 'sw', 'swa'),
|
||||
('Swedish', 'sv', 'swe'),
|
||||
('Classical Syriac', '', 'syc'),
|
||||
('Syriac', '', 'syr'),
|
||||
('Tahitian', 'ty', 'tah'),
|
||||
('Tai languages', '', 'tai'),
|
||||
('Tamil', 'ta', 'tam'),
|
||||
('Tatar', 'tt', 'tat'),
|
||||
('Telugu', 'te', 'tel'),
|
||||
('Timne', '', 'tem'),
|
||||
('Tereno', '', 'ter'),
|
||||
('Tetum', '', 'tet'),
|
||||
('Tajik', 'tg', 'tgk'),
|
||||
('Tagalog', 'tl', 'tgl'),
|
||||
('Thai', 'th', 'tha'),
|
||||
('Tibetan', 'bo', 'tib'),
|
||||
('Tigre', '', 'tig'),
|
||||
('Tigrinya', 'ti', 'tir'),
|
||||
('Tiv', '', 'tiv'),
|
||||
('Tokelau', '', 'tkl'),
|
||||
('Klingon; tlhIngan-Hol', '', 'tlh'),
|
||||
('Tlingit', '', 'tli'),
|
||||
('Tamashek', '', 'tmh'),
|
||||
('Tonga (Nyasa)', '', 'tog'),
|
||||
('Tonga (Tonga Islands)', 'to', 'ton'),
|
||||
('Tok Pisin', '', 'tpi'),
|
||||
('Tsimshian', '', 'tsi'),
|
||||
('Tswana', 'tn', 'tsn'),
|
||||
('Tsonga', 'ts', 'tso'),
|
||||
('Turkmen', 'tk', 'tuk'),
|
||||
('Tumbuka', '', 'tum'),
|
||||
('Tupi languages', '', 'tup'),
|
||||
('Turkish', 'tr', 'tur'),
|
||||
('Altaic languages', '', 'tut'),
|
||||
('Tuvalu', '', 'tvl'),
|
||||
('Twi', 'tw', 'twi'),
|
||||
('Tuvinian', '', 'tyv'),
|
||||
('Udmurt', '', 'udm'),
|
||||
('Ugaritic', '', 'uga'),
|
||||
('Uighur; Uyghur', 'ug', 'uig'),
|
||||
('Ukrainian', 'uk', 'ukr'),
|
||||
('Umbundu', '', 'umb'),
|
||||
('Undetermined', '', 'und'),
|
||||
('Urdu', 'ur', 'urd'),
|
||||
('Uzbek', 'uz', 'uzb'),
|
||||
('Vai', '', 'vai'),
|
||||
('Venda', 've', 'ven'),
|
||||
('Vietnamese', 'vi', 'vie'),
|
||||
('Volapük', 'vo', 'vol'),
|
||||
('Votic', '', 'vot'),
|
||||
('Wakashan languages', '', 'wak'),
|
||||
('Walamo', '', 'wal'),
|
||||
('Waray', '', 'war'),
|
||||
('Washo', '', 'was'),
|
||||
('Welsh', 'cy', 'wel'),
|
||||
('Sorbian languages', '', 'wen'),
|
||||
('Walloon', 'wa', 'wln'),
|
||||
('Wolof', 'wo', 'wol'),
|
||||
('Kalmyk; Oirat', '', 'xal'),
|
||||
('Xhosa', 'xh', 'xho'),
|
||||
('Yao', '', 'yao'),
|
||||
('Yapese', '', 'yap'),
|
||||
('Yiddish', 'yi', 'yid'),
|
||||
('Yoruba', 'yo', 'yor'),
|
||||
('Yupik languages', '', 'ypk'),
|
||||
('Zapotec', '', 'zap'),
|
||||
('Blissymbols; Blissymbolics; Bliss', '', 'zbl'),
|
||||
('Zenaga', '', 'zen'),
|
||||
('Zhuang; Chuang', 'za', 'zha'),
|
||||
('Zande languages', '', 'znd'),
|
||||
('Zulu', 'zu', 'zul'),
|
||||
('Zuni', '', 'zun'),
|
||||
('No linguistic content; Not applicable', '', 'zxx'),
|
||||
('Zaza; Dimili; Dimli; Kirdki; Kirmanjki; Zazaki', '', 'zza'),
|
||||
('Brazilian', 'po', 'pob')]
|
||||
@@ -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,214 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
# Copyright 2011-2012 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 GNU Lesser 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
|
||||
# GNU Lesser General Public License for more details.
|
||||
#
|
||||
# You should have received a copy of the GNU Lesser General Public License
|
||||
# along with subliminal. If not, see <http://www.gnu.org/licenses/>.
|
||||
from ..exceptions import MissingLanguageError, DownloadFailedError
|
||||
import logging
|
||||
import os
|
||||
import requests
|
||||
import threading
|
||||
|
||||
|
||||
__all__ = ['ServiceBase', 'ServiceConfig']
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class ServiceBase(object):
|
||||
"""Service base class
|
||||
|
||||
:param config: service configuration
|
||||
:type config: :class:`ServiceConfig`
|
||||
|
||||
"""
|
||||
#: URL to the service server
|
||||
server_url = ''
|
||||
|
||||
#: User Agent for any HTTP-based requests
|
||||
user_agent = 'subliminal v0.5'
|
||||
|
||||
#: Whether based on an API or not
|
||||
api_based = False
|
||||
|
||||
#: Timeout for web requests
|
||||
timeout = 5
|
||||
|
||||
#: Lock for cache interactions
|
||||
lock = threading.Lock()
|
||||
|
||||
#: Mapping to Service's language codes and subliminal's
|
||||
languages = {}
|
||||
|
||||
#: Whether the mapping is reverted or not
|
||||
reverted_languages = False
|
||||
|
||||
#: Accepted video classes (:class:`~subliminal.videos.Episode`, :class:`~subliminal.videos.Movie`, :class:`~subliminal.videos.UnknownVideo`)
|
||||
videos = []
|
||||
|
||||
#: Whether the video has to exist or not
|
||||
require_video = False
|
||||
|
||||
def __init__(self, config=None):
|
||||
self.config = config or ServiceConfig()
|
||||
|
||||
def __enter__(self):
|
||||
self.init()
|
||||
return self
|
||||
|
||||
def __exit__(self, *args):
|
||||
self.terminate()
|
||||
|
||||
def init(self):
|
||||
"""Initialize connection"""
|
||||
logger.debug(u'Initializing %s' % self.__class__.__name__)
|
||||
self.session = requests.session(timeout=10, headers={'User-Agent': self.user_agent})
|
||||
|
||||
def terminate(self):
|
||||
"""Terminate connection"""
|
||||
logger.debug(u'Terminating %s' % self.__class__.__name__)
|
||||
|
||||
def query(self, *args):
|
||||
"""Make the actual query"""
|
||||
pass
|
||||
|
||||
def list(self, video, languages):
|
||||
"""List subtitles"""
|
||||
pass
|
||||
|
||||
def download(self, subtitle):
|
||||
"""Download a subtitle"""
|
||||
self.download_file(subtitle.link, subtitle.path)
|
||||
|
||||
@classmethod
|
||||
def available_languages(cls):
|
||||
"""Available languages in the Service
|
||||
|
||||
:return: available languages
|
||||
:rtype: set
|
||||
|
||||
"""
|
||||
if not cls.reverted_languages:
|
||||
return set(cls.languages.keys())
|
||||
return set(cls.languages.values())
|
||||
|
||||
@classmethod
|
||||
def check_validity(cls, video, languages):
|
||||
"""Check for video and languages validity in the Service
|
||||
|
||||
:param video: the video to check
|
||||
:type video: :class:`~subliminal.videos.video`
|
||||
:param set languages: languages to check
|
||||
:rtype: bool
|
||||
|
||||
"""
|
||||
languages &= cls.available_languages()
|
||||
if not languages:
|
||||
logger.debug(u'No language available for service %s' % cls.__class__.__name__.lower())
|
||||
return False
|
||||
if not cls.is_valid_video(video):
|
||||
logger.debug(u'%r is not valid for service %s' % (video, cls.__class__.__name__.lower()))
|
||||
return False
|
||||
return True
|
||||
|
||||
@classmethod
|
||||
def is_valid_video(cls, video):
|
||||
"""Check if video is valid in the Service
|
||||
|
||||
:param video: the video to check
|
||||
:type video: :class:`~subliminal.videos.Video`
|
||||
:rtype: bool
|
||||
|
||||
"""
|
||||
if cls.require_video and not video.exists:
|
||||
return False
|
||||
if not isinstance(video, tuple(cls.videos)):
|
||||
return False
|
||||
return True
|
||||
|
||||
@classmethod
|
||||
def is_valid_language(cls, language):
|
||||
"""Check if language is valid in the Service
|
||||
|
||||
:param string language: the language to check
|
||||
:rtype: bool
|
||||
|
||||
"""
|
||||
if language in cls.available_languages():
|
||||
return True
|
||||
return False
|
||||
|
||||
@classmethod
|
||||
def get_revert_language(cls, language):
|
||||
"""ISO-639-1 language code from service language code
|
||||
|
||||
:param string language: service language code
|
||||
:return: ISO-639-1 language code
|
||||
:rtype: string
|
||||
|
||||
"""
|
||||
if not cls.reverted_languages and language in cls.languages.values():
|
||||
return [k for k, v in cls.languages.iteritems() if v == language][0]
|
||||
if cls.reverted_languages and language in cls.languages.keys():
|
||||
return cls.languages[language]
|
||||
raise MissingLanguageError(language)
|
||||
|
||||
@classmethod
|
||||
def get_language(cls, language):
|
||||
"""Service language code from ISO-639-1 language code
|
||||
|
||||
:param string language: ISO-639-1 language code
|
||||
:return: service language code
|
||||
:rtype: string
|
||||
|
||||
"""
|
||||
if not cls.reverted_languages and language in cls.languages.keys():
|
||||
return cls.languages[language]
|
||||
if cls.reverted_languages and language in cls.languages.values():
|
||||
return [k for k, v in cls.languages.iteritems() if v == language][0]
|
||||
raise MissingLanguageError(language)
|
||||
|
||||
def download_file(self, url, filepath):
|
||||
"""Attempt to download a file and remove it in case of failure
|
||||
|
||||
:param string url: URL to download
|
||||
:param string filepath: destination path
|
||||
|
||||
"""
|
||||
logger.info(u'Downloading %s' % url)
|
||||
try:
|
||||
r = self.session.get(url, headers={'Referer': url, 'User-Agent': self.user_agent})
|
||||
with open(filepath, 'wb') as f:
|
||||
f.write(r.content)
|
||||
except Exception as e:
|
||||
logger.error(u'Download %s failed: %s' % (url, e))
|
||||
if os.path.exists(filepath):
|
||||
os.remove(filepath)
|
||||
raise DownloadFailedError(str(e))
|
||||
logger.debug(u'Download finished for file %s. Size: %s' % (filepath, os.path.getsize(filepath)))
|
||||
|
||||
|
||||
class ServiceConfig(object):
|
||||
"""Configuration for any :class:`Service`
|
||||
|
||||
:param bool multi: whether to download one subtitle per language or not
|
||||
:param string cache_dir: cache directory
|
||||
|
||||
"""
|
||||
def __init__(self, multi=False, cache_dir=None):
|
||||
self.multi = multi
|
||||
self.cache_dir = cache_dir
|
||||
|
||||
def __repr__(self):
|
||||
return 'ServiceConfig(%r, %s)' % (self.multi, self.cache_dir)
|
||||
@@ -0,0 +1,122 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
# Copyright 2011-2012 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 GNU Lesser 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
|
||||
# GNU Lesser General Public License for more details.
|
||||
#
|
||||
# You should have received a copy of the GNU Lesser General Public License
|
||||
# along with subliminal. If not, see <http://www.gnu.org/licenses/>.
|
||||
from . import ServiceBase
|
||||
from ..exceptions import ServiceError
|
||||
from ..subtitles import get_subtitle_path, ResultSubtitle
|
||||
from ..videos import Episode
|
||||
from ..utils import to_unicode
|
||||
import BeautifulSoup
|
||||
import logging
|
||||
import os.path
|
||||
import urllib
|
||||
try:
|
||||
import cPickle as pickle
|
||||
except ImportError:
|
||||
import pickle
|
||||
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class BierDopje(ServiceBase):
|
||||
server_url = 'http://api.bierdopje.com/A2B638AC5D804C2E/'
|
||||
api_based = True
|
||||
languages = {'en': 'en', 'nl': 'nl'}
|
||||
reverted_languages = False
|
||||
videos = [Episode]
|
||||
require_video = False
|
||||
|
||||
def __init__(self, config=None):
|
||||
super(BierDopje, self).__init__(config)
|
||||
self.showids = {}
|
||||
if self.config and self.config.cache_dir:
|
||||
self.init_cache()
|
||||
|
||||
def init_cache(self):
|
||||
logger.debug(u'Initializing cache...')
|
||||
if not self.config or not self.config.cache_dir:
|
||||
raise ServiceError('Cache directory is required')
|
||||
self.showids_cache = os.path.join(self.config.cache_dir, 'bierdopje_showids.cache')
|
||||
if not os.path.exists(self.showids_cache):
|
||||
self.save_cache()
|
||||
|
||||
def save_cache(self):
|
||||
logger.debug(u'Saving showids to cache...')
|
||||
with self.lock:
|
||||
with open(self.showids_cache, 'w') as f:
|
||||
pickle.dump(self.showids, f)
|
||||
|
||||
def load_cache(self):
|
||||
logger.debug(u'Loading showids from cache...')
|
||||
with self.lock:
|
||||
with open(self.showids_cache, 'r') as f:
|
||||
self.showids = pickle.load(f)
|
||||
|
||||
def query(self, season, episode, languages, filepath, tvdbid=None, series=None):
|
||||
self.load_cache()
|
||||
if series:
|
||||
if series.lower() in self.showids: # from cache
|
||||
request_id = self.showids[series.lower()]
|
||||
logger.debug(u'Retreived showid %d for %s from cache' % (request_id, series))
|
||||
else: # query to get showid
|
||||
logger.debug(u'Getting showid from show name %s...' % series)
|
||||
r = self.session.get('%sGetShowByName/%s' % (self.server_url, urllib.quote(series.lower())))
|
||||
if r.status_code != 200:
|
||||
logger.error(u'Request %s returned status code %d' % (r.url, r.status_code))
|
||||
return []
|
||||
soup = BeautifulSoup.BeautifulStoneSoup(r.content)
|
||||
if soup.status.contents[0] == 'false':
|
||||
logger.debug(u'Could not find show %s' % series)
|
||||
return []
|
||||
request_id = int(soup.showid.contents[0])
|
||||
self.showids[series.lower()] = request_id
|
||||
self.save_cache()
|
||||
request_source = 'showid'
|
||||
request_is_tvdbid = 'false'
|
||||
elif tvdbid:
|
||||
request_id = tvdbid
|
||||
request_source = 'tvdbid'
|
||||
request_is_tvdbid = 'true'
|
||||
else:
|
||||
raise ServiceError('One or more parameter missing')
|
||||
subtitles = []
|
||||
for language in languages:
|
||||
logger.debug(u'Getting subtitles for %s %d season %d episode %d with language %s' % (request_source, request_id, season, episode, language))
|
||||
r = self.session.get('%sGetAllSubsFor/%s/%s/%s/%s/%s' % (self.server_url, request_id, season, episode, language, request_is_tvdbid))
|
||||
if r.status_code != 200:
|
||||
logger.error(u'Request %s returned status code %d' % (r.url, r.status_code))
|
||||
return []
|
||||
soup = BeautifulSoup.BeautifulStoneSoup(r.content)
|
||||
if soup.status.contents[0] == 'false':
|
||||
logger.debug(u'Could not find subtitles for %s %d season %d episode %d with language %s' % (request_source, request_id, season, episode, language))
|
||||
continue
|
||||
path = get_subtitle_path(filepath, language, self.config.multi)
|
||||
for result in soup.results('result'):
|
||||
subtitle = ResultSubtitle(path, language, service=self.__class__.__name__.lower(), link=result.downloadlink.contents[0],
|
||||
release=to_unicode(result.filename.contents[0]))
|
||||
subtitles.append(subtitle)
|
||||
return subtitles
|
||||
|
||||
def list(self, video, languages):
|
||||
if not self.check_validity(video, languages):
|
||||
return []
|
||||
results = self.query(video.season, video.episode, languages, video.path or video.release, video.tvdbid, video.series)
|
||||
return results
|
||||
|
||||
|
||||
Service = BierDopje
|
||||
@@ -0,0 +1,143 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
# Copyright 2011-2012 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 GNU Lesser 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
|
||||
# GNU Lesser General Public License for more details.
|
||||
#
|
||||
# You should have received a copy of the GNU Lesser General Public License
|
||||
# along with subliminal. If not, see <http://www.gnu.org/licenses/>.
|
||||
from . import ServiceBase
|
||||
from ..exceptions import ServiceError, DownloadFailedError
|
||||
from ..subtitles import get_subtitle_path, ResultSubtitle
|
||||
from ..videos import Episode, Movie
|
||||
from ..utils import to_unicode
|
||||
import gzip
|
||||
import logging
|
||||
import os.path
|
||||
import xmlrpclib
|
||||
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class OpenSubtitles(ServiceBase):
|
||||
server_url = 'http://api.opensubtitles.org/xml-rpc'
|
||||
api_based = True
|
||||
languages = {'aa': 'aar', 'ab': 'abk', 'af': 'afr', 'ak': 'aka', 'sq': 'alb', 'am': 'amh', 'ar': 'ara',
|
||||
'an': 'arg', 'hy': 'arm', 'as': 'asm', 'av': 'ava', 'ae': 'ave', 'ay': 'aym', 'az': 'aze',
|
||||
'ba': 'bak', 'bm': 'bam', 'eu': 'baq', 'be': 'bel', 'bn': 'ben', 'bh': 'bih', 'bi': 'bis',
|
||||
'bs': 'bos', 'br': 'bre', 'bg': 'bul', 'my': 'bur', 'ca': 'cat', 'ch': 'cha', 'ce': 'che',
|
||||
'zh': 'chi', 'cu': 'chu', 'cv': 'chv', 'kw': 'cor', 'co': 'cos', 'cr': 'cre', 'cs': 'cze',
|
||||
'da': 'dan', 'dv': 'div', 'nl': 'dut', 'dz': 'dzo', 'en': 'eng', 'eo': 'epo', 'et': 'est',
|
||||
'ee': 'ewe', 'fo': 'fao', 'fj': 'fij', 'fi': 'fin', 'fr': 'fre', 'fy': 'fry', 'ff': 'ful',
|
||||
'ka': 'geo', 'de': 'ger', 'gd': 'gla', 'ga': 'gle', 'gl': 'glg', 'gv': 'glv', 'el': 'ell',
|
||||
'gn': 'grn', 'gu': 'guj', 'ht': 'hat', 'ha': 'hau', 'he': 'heb', 'hz': 'her', 'hi': 'hin',
|
||||
'ho': 'hmo', 'hr': 'hrv', 'hu': 'hun', 'ig': 'ibo', 'is': 'ice', 'io': 'ido', 'ii': 'iii',
|
||||
'iu': 'iku', 'ie': 'ile', 'ia': 'ina', 'id': 'ind', 'ik': 'ipk', 'it': 'ita', 'jv': 'jav',
|
||||
'ja': 'jpn', 'kl': 'kal', 'kn': 'kan', 'ks': 'kas', 'kr': 'kau', 'kk': 'kaz', 'km': 'khm',
|
||||
'ki': 'kik', 'rw': 'kin', 'ky': 'kir', 'kv': 'kom', 'kg': 'kon', 'ko': 'kor', 'kj': 'kua',
|
||||
'ku': 'kur', 'lo': 'lao', 'la': 'lat', 'lv': 'lav', 'li': 'lim', 'ln': 'lin', 'lt': 'lit',
|
||||
'lb': 'ltz', 'lu': 'lub', 'lg': 'lug', 'mk': 'mac', 'mh': 'mah', 'ml': 'mal', 'mi': 'mao',
|
||||
'mr': 'mar', 'ms': 'may', 'mg': 'mlg', 'mt': 'mlt', 'mo': 'mol', 'mn': 'mon', 'na': 'nau',
|
||||
'nv': 'nav', 'nr': 'nbl', 'nd': 'nde', 'ng': 'ndo', 'ne': 'nep', 'nn': 'nno', 'nb': 'nob',
|
||||
'no': 'nor', 'ny': 'nya', 'oc': 'oci', 'oj': 'oji', 'or': 'ori', 'om': 'orm', 'os': 'oss',
|
||||
'pa': 'pan', 'fa': 'per', 'pi': 'pli', 'pl': 'pol', 'pt': 'por', 'ps': 'pus', 'qu': 'que',
|
||||
'rm': 'roh', 'rn': 'run', 'ru': 'rus', 'sg': 'sag', 'sa': 'san', 'sr': 'scc', 'si': 'sin',
|
||||
'sk': 'slo', 'sl': 'slv', 'se': 'sme', 'sm': 'smo', 'sn': 'sna', 'sd': 'snd', 'so': 'som',
|
||||
'st': 'sot', 'es': 'spa', 'sc': 'srd', 'ss': 'ssw', 'su': 'sun', 'sw': 'swa', 'sv': 'swe',
|
||||
'ty': 'tah', 'ta': 'tam', 'tt': 'tat', 'te': 'tel', 'tg': 'tgk', 'tl': 'tgl', 'th': 'tha',
|
||||
'bo': 'tib', 'ti': 'tir', 'to': 'ton', 'tn': 'tsn', 'ts': 'tso', 'tk': 'tuk', 'tr': 'tur',
|
||||
'tw': 'twi', 'ug': 'uig', 'uk': 'ukr', 'ur': 'urd', 'uz': 'uzb', 've': 'ven', 'vi': 'vie',
|
||||
'vo': 'vol', 'cy': 'wel', 'wa': 'wln', 'wo': 'wol', 'xh': 'xho', 'yi': 'yid', 'yo': 'yor',
|
||||
'za': 'zha', 'zu': 'zul', 'ro': 'rum', 'po': 'pob', 'un': 'unk', 'ay': 'ass'}
|
||||
reverted_languages = False
|
||||
videos = [Episode, Movie]
|
||||
require_video = False
|
||||
confidence_order = ['moviehash', 'imdbid', 'fulltext']
|
||||
|
||||
def __init__(self, config=None):
|
||||
super(OpenSubtitles, self).__init__(config)
|
||||
self.server = xmlrpclib.ServerProxy(self.server_url)
|
||||
self.token = None
|
||||
|
||||
def init(self):
|
||||
super(OpenSubtitles, self).init()
|
||||
result = self.server.LogIn('', '', 'eng', self.user_agent)
|
||||
if result['status'] != '200 OK':
|
||||
raise ServiceError('Login failed')
|
||||
self.token = result['token']
|
||||
|
||||
def terminate(self):
|
||||
super(OpenSubtitles, self).terminate()
|
||||
if self.token:
|
||||
self.server.LogOut(self.token)
|
||||
|
||||
def query(self, filepath, languages, moviehash=None, size=None, imdbid=None, query=None):
|
||||
searches = []
|
||||
if moviehash and size:
|
||||
searches.append({'moviehash': moviehash, 'moviebytesize': size})
|
||||
if imdbid:
|
||||
searches.append({'imdbid': imdbid})
|
||||
if query:
|
||||
searches.append({'query': query})
|
||||
if not searches:
|
||||
raise ServiceError('One or more parameter missing')
|
||||
for search in searches:
|
||||
search['sublanguageid'] = ','.join([self.get_language(l) for l in languages])
|
||||
logger.debug(u'Getting subtitles %r with token %s' % (searches, self.token))
|
||||
results = self.server.SearchSubtitles(self.token, searches)
|
||||
if not results['data']:
|
||||
logger.debug(u'Could not find subtitles for %r with token %s' % (searches, self.token))
|
||||
return []
|
||||
subtitles = []
|
||||
for result in results['data']:
|
||||
language = self.get_revert_language(result['SubLanguageID'])
|
||||
path = get_subtitle_path(filepath, language, self.config.multi)
|
||||
confidence = 1 - float(self.confidence_order.index(result['MatchedBy'])) / float(len(self.confidence_order))
|
||||
subtitle = ResultSubtitle(path, language, service=self.__class__.__name__.lower(), link=result['SubDownloadLink'],
|
||||
release=to_unicode(result['SubFileName']), confidence=confidence)
|
||||
subtitles.append(subtitle)
|
||||
return subtitles
|
||||
|
||||
def list(self, video, languages):
|
||||
if not self.check_validity(video, languages):
|
||||
return []
|
||||
results = []
|
||||
if video.exists:
|
||||
results = self.query(video.path or video.release, languages, moviehash=video.hashes['OpenSubtitles'], size=str(video.size))
|
||||
elif video.imdbid:
|
||||
results = self.query(video.path or video.release, languages, imdbid=video.imdbid)
|
||||
elif isinstance(video, Episode):
|
||||
results = self.query(video.path or video.release, languages, query=video.series)
|
||||
elif isinstance(video, Movie):
|
||||
results = self.query(video.path or video.release, languages, query=video.title)
|
||||
return results
|
||||
|
||||
def download(self, subtitle):
|
||||
#TODO: Use OpenSubtitles DownloadSubtitles method
|
||||
try:
|
||||
self.download_file(subtitle.link, subtitle.path + '.gz')
|
||||
with open(subtitle.path, 'wb') as dump:
|
||||
gz = gzip.open(subtitle.path + '.gz')
|
||||
dump.write(gz.read())
|
||||
gz.close()
|
||||
except Exception as e:
|
||||
if os.path.exists(subtitle.path):
|
||||
os.remove(subtitle.path)
|
||||
raise DownloadFailedError(str(e))
|
||||
finally:
|
||||
if os.path.exists(subtitle.path + '.gz'):
|
||||
os.remove(subtitle.path + '.gz')
|
||||
return subtitle
|
||||
|
||||
|
||||
Service = OpenSubtitles
|
||||
@@ -0,0 +1,99 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
# Copyright 2011-2012 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 GNU Lesser 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
|
||||
# GNU Lesser General Public License for more details.
|
||||
#
|
||||
# You should have received a copy of the GNU Lesser General Public License
|
||||
# along with subliminal. If not, see <http://www.gnu.org/licenses/>.
|
||||
from . import ServiceBase
|
||||
from ..exceptions import ServiceError
|
||||
from ..subtitles import get_subtitle_path, ResultSubtitle
|
||||
from ..videos import Episode, Movie
|
||||
from subliminal.utils import get_keywords, split_keyword
|
||||
import BeautifulSoup
|
||||
import logging
|
||||
import re
|
||||
import urllib
|
||||
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class SubsWiki(ServiceBase):
|
||||
server_url = 'http://www.subswiki.com'
|
||||
api_based = False
|
||||
languages = {u'English (US)': 'en', u'English (UK)': 'en', u'English': 'en', u'French': 'fr', u'Brazilian': 'po',
|
||||
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'}
|
||||
reverted_languages = True
|
||||
videos = [Episode, Movie]
|
||||
require_video = False
|
||||
release_pattern = re.compile('\nVersion (.+), ([0-9]+).([0-9])+ MBs')
|
||||
|
||||
def list(self, video, languages):
|
||||
if not self.check_validity(video, languages):
|
||||
return []
|
||||
results = []
|
||||
if isinstance(video, Episode):
|
||||
results = self.query(video.path or video.release, languages, get_keywords(video.guess), series=video.series, season=video.season, episode=video.episode)
|
||||
elif isinstance(video, Movie) and video.year:
|
||||
results = self.query(video.path or video.release, languages, get_keywords(video.guess), movie=video.title, year=video.year)
|
||||
return results
|
||||
|
||||
def query(self, filepath, languages, keywords=None, series=None, season=None, episode=None, movie=None, year=None):
|
||||
if series and season and episode:
|
||||
request_series = series.lower().replace(' ', '_')
|
||||
if isinstance(request_series, unicode):
|
||||
request_series = request_series.encode('utf-8')
|
||||
logger.debug(u'Getting subtitles for %s season %d episode %d with languages %r' % (series, season, episode, languages))
|
||||
r = self.session.get('%s/serie/%s/%s/%s/' % (self.server_url, urllib.quote(request_series), season, episode))
|
||||
if r.status_code == 404:
|
||||
logger.debug(u'Could not find subtitles for %s season %d episode %d with languages %r' % (series, season, episode, languages))
|
||||
return []
|
||||
elif movie and year:
|
||||
request_movie = movie.title().replace(' ', '_')
|
||||
if isinstance(request_movie, unicode):
|
||||
request_movie = request_movie.encode('utf-8')
|
||||
logger.debug(u'Getting subtitles for %s (%d) with languages %r' % (movie, year, languages))
|
||||
r = self.session.get('%s/film/%s_(%d)' % (self.server_url, urllib.quote(request_movie), year))
|
||||
if r.status_code == 404:
|
||||
logger.debug(u'Could not find subtitles for %s (%d) with languages %r' % (movie, year, languages))
|
||||
return []
|
||||
else:
|
||||
raise ServiceError('One or more parameter missing')
|
||||
if r.status_code != 200:
|
||||
logger.error(u'Request %s returned status code %d' % (r.url, r.status_code))
|
||||
return []
|
||||
soup = BeautifulSoup.BeautifulSoup(r.content)
|
||||
subtitles = []
|
||||
for sub in soup('td', {'class': 'NewsTitle'}):
|
||||
sub_keywords = split_keyword(self.release_pattern.search(sub.contents[1]).group(1).lower())
|
||||
if not keywords & sub_keywords:
|
||||
logger.debug(u'None of subtitle keywords %r in %r' % (sub_keywords, keywords))
|
||||
continue
|
||||
for html_language in sub.parent.parent.findAll('td', {'class': 'language'}):
|
||||
language = self.get_revert_language(html_language.string.strip())
|
||||
if not language in languages:
|
||||
logger.debug(u'Language %r not in wanted languages %r' % (language, languages))
|
||||
continue
|
||||
html_status = html_language.findNextSibling('td')
|
||||
status = html_status.find('strong').string.strip()
|
||||
if status != 'Completed':
|
||||
logger.debug(u'Wrong subtitle status %s' % status)
|
||||
continue
|
||||
path = get_subtitle_path(filepath, language, self.config.multi)
|
||||
subtitle = ResultSubtitle(path, language, service=self.__class__.__name__.lower(), link='%s%s' % (self.server_url, html_status.findNext('td').find('a')['href']))
|
||||
subtitles.append(subtitle)
|
||||
return subtitles
|
||||
|
||||
Service = SubsWiki
|
||||
@@ -0,0 +1,83 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
# Copyright 2011-2012 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 GNU Lesser 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
|
||||
# GNU Lesser General Public License for more details.
|
||||
#
|
||||
# You should have received a copy of the GNU Lesser General Public License
|
||||
# along with subliminal. If not, see <http://www.gnu.org/licenses/>.
|
||||
from . import ServiceBase
|
||||
from ..subtitles import get_subtitle_path, ResultSubtitle
|
||||
from ..videos import Episode
|
||||
from subliminal.utils import get_keywords, split_keyword
|
||||
import BeautifulSoup
|
||||
import logging
|
||||
import re
|
||||
import unicodedata
|
||||
import urllib
|
||||
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class Subtitulos(ServiceBase):
|
||||
server_url = 'http://www.subtitulos.es'
|
||||
api_based = False
|
||||
languages = {u'English (US)': 'en', u'English (UK)': 'en', u'English': 'en', u'French': 'fr', u'Brazilian': 'po',
|
||||
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'}
|
||||
reverted_languages = True
|
||||
videos = [Episode]
|
||||
require_video = False
|
||||
release_pattern = re.compile('Versión (.+) ([0-9]+).([0-9])+ megabytes')
|
||||
|
||||
def list(self, video, languages):
|
||||
if not self.check_validity(video, languages):
|
||||
return []
|
||||
results = self.query(video.path or video.release, languages, get_keywords(video.guess), video.series, video.season, video.episode)
|
||||
return results
|
||||
|
||||
def query(self, filepath, languages, keywords, series, season, episode):
|
||||
request_series = series.lower().replace(' ', '_')
|
||||
if isinstance(request_series, unicode):
|
||||
request_series = unicodedata.normalize('NFKD', request_series).encode('ascii', 'ignore')
|
||||
logger.debug(u'Getting subtitles for %s season %d episode %d with languages %r' % (series, season, episode, languages))
|
||||
r = self.session.get('%s/%s/%sx%.2d' % (self.server_url, urllib.quote(request_series), season, episode))
|
||||
if r.status_code == 404:
|
||||
logger.debug(u'Could not find subtitles for %s season %d episode %d with languages %r' % (series, season, episode, languages))
|
||||
return []
|
||||
if r.status_code != 200:
|
||||
logger.error(u'Request %s returned status code %d' % (r.url, r.status_code))
|
||||
return []
|
||||
soup = BeautifulSoup.BeautifulSoup(r.content)
|
||||
subtitles = []
|
||||
for sub in soup('div', {'id': 'version'}):
|
||||
sub_keywords = split_keyword(self.release_pattern.search(sub.find('p', {'class': 'title-sub'}).contents[1]).group(1).lower())
|
||||
if not keywords & sub_keywords:
|
||||
logger.debug(u'None of subtitle keywords %r in %r' % (sub_keywords, keywords))
|
||||
continue
|
||||
for html_language in sub.findAllNext('ul', {'class': 'sslist'}):
|
||||
language = self.get_revert_language(html_language.findNext('li', {'class': 'li-idioma'}).find('strong').contents[0].string.strip())
|
||||
if not language in languages:
|
||||
logger.debug(u'Language %r not in wanted languages %r' % (language, languages))
|
||||
continue
|
||||
html_status = html_language.findNext('li', {'class': 'li-estado green'})
|
||||
status = html_status.contents[0].string.strip()
|
||||
if status != 'Completado':
|
||||
logger.debug(u'Wrong subtitle status %s' % status)
|
||||
continue
|
||||
path = get_subtitle_path(filepath, language, self.config.multi)
|
||||
subtitle = ResultSubtitle(path, language, service=self.__class__.__name__.lower(), link=html_status.findNext('span', {'class': 'descargar green'}).find('a')['href'], keywords=sub_keywords)
|
||||
subtitles.append(subtitle)
|
||||
return subtitles
|
||||
|
||||
Service = Subtitulos
|
||||
@@ -0,0 +1,65 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
# Copyright 2011-2012 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 GNU Lesser 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
|
||||
# GNU Lesser General Public License for more details.
|
||||
#
|
||||
# You should have received a copy of the GNU Lesser General Public License
|
||||
# along with subliminal. If not, see <http://www.gnu.org/licenses/>.
|
||||
from . import ServiceBase
|
||||
from ..subtitles import get_subtitle_path, ResultSubtitle
|
||||
from ..videos import Episode, Movie, UnknownVideo
|
||||
import logging
|
||||
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class TheSubDB(ServiceBase):
|
||||
server_url = 'http://api.thesubdb.com/' # for testing purpose, use http://sandbox.thesubdb.com/ instead
|
||||
user_agent = 'SubDB/1.0 (subliminal/0.5; https://github.com/Diaoul/subliminal)' # defined by the API
|
||||
api_based = True
|
||||
languages = {'af': 'af', 'cs': 'cs', 'da': 'da', 'de': 'de', 'en': 'en', 'es': 'es', 'fi': 'fi',
|
||||
'fr': 'fr', 'hu': 'hu', 'id': 'id', 'it': 'it', 'la': 'la', 'nl': 'nl', 'no': 'no',
|
||||
'oc': 'oc', 'pl': 'pl', 'pt': 'pt', 'ro': 'ro', 'ru': 'ru', 'sl': 'sl', 'sr': 'sr',
|
||||
'sv': 'sv', 'tr': 'tr'} # list available with the API at http://sandbox.thesubdb.com/?action=languages
|
||||
reverted_languages = False
|
||||
videos = [Movie, Episode, UnknownVideo]
|
||||
require_video = True
|
||||
|
||||
def list(self, video, languages):
|
||||
if not self.check_validity(video, languages):
|
||||
return []
|
||||
results = self.query(video.path, video.hashes['TheSubDB'], languages)
|
||||
return results
|
||||
|
||||
def query(self, filepath, moviehash, languages):
|
||||
r = self.session.get(self.server_url, params={'action': 'search', 'hash': moviehash})
|
||||
if r.status_code == 404:
|
||||
logger.debug(u'Could not find subtitles for hash %s' % moviehash)
|
||||
return []
|
||||
if r.status_code != 200:
|
||||
logger.error(u'Request %s returned status code %d' % (r.url, r.status_code))
|
||||
return []
|
||||
available_languages = set([self.get_revert_language(l) for l in r.content.split(',')])
|
||||
languages &= available_languages
|
||||
if not languages:
|
||||
logger.debug(u'Could not find subtitles for hash %s with languages %r (only %r available)' % (moviehash, languages, available_languages))
|
||||
return []
|
||||
subtitles = []
|
||||
for language in languages:
|
||||
path = get_subtitle_path(filepath, language, self.config.multi)
|
||||
subtitle = ResultSubtitle(path, language, service=self.__class__.__name__.lower(), link='%s?action=download&hash=%s&language=%s' % (self.server_url, moviehash, self.get_language(language)))
|
||||
subtitles.append(subtitle)
|
||||
return subtitles
|
||||
|
||||
Service = TheSubDB
|
||||
@@ -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,130 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
# Copyright 2011-2012 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 GNU Lesser 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
|
||||
# GNU Lesser General Public License for more details.
|
||||
#
|
||||
# You should have received a copy of the GNU Lesser General Public License
|
||||
# along with subliminal. If not, see <http://www.gnu.org/licenses/>.
|
||||
from .languages import list_languages, convert_language
|
||||
import os.path
|
||||
|
||||
|
||||
__all__ = ['Subtitle', 'EmbeddedSubtitle', 'ExternalSubtitle', 'ResultSubtitle', 'get_subtitle_path']
|
||||
|
||||
|
||||
#: Subtitles extensions
|
||||
EXTENSIONS = ['.srt', '.sub', '.txt']
|
||||
|
||||
|
||||
class Subtitle(object):
|
||||
"""Base class for subtitles
|
||||
|
||||
:param string path: path to the subtitle
|
||||
:param string language: language of the subtitle (second element of :class:`~subliminal.languages.LANGUAGES`)
|
||||
|
||||
"""
|
||||
def __init__(self, path, language):
|
||||
self.path = path
|
||||
self.language = language
|
||||
|
||||
@property
|
||||
def exists(self):
|
||||
"""Whether the subtitle exists or not"""
|
||||
if self.path:
|
||||
return os.path.exists(self.path)
|
||||
return False
|
||||
|
||||
|
||||
class EmbeddedSubtitle(Subtitle):
|
||||
"""Subtitle embedded in a container
|
||||
|
||||
:param string path: path to the subtitle
|
||||
:param string language: language of the subtitle (second element of :class:`~subliminal.languages.LANGUAGES`)
|
||||
:param int track_id: id of the subtitle track in the container
|
||||
|
||||
"""
|
||||
def __init__(self, path, language, track_id):
|
||||
super(EmbeddedSubtitle, self).__init__(path, language)
|
||||
self.track_id = track_id
|
||||
|
||||
@classmethod
|
||||
def from_enzyme(cls, path, subtitle):
|
||||
language = convert_language(subtitle.language, 1, 2)
|
||||
return cls(path, language, subtitle.trackno)
|
||||
|
||||
|
||||
class ExternalSubtitle(Subtitle):
|
||||
"""Subtitle in a file next to the video file"""
|
||||
@classmethod
|
||||
def from_path(cls, path):
|
||||
"""Create an :class:`ExternalSubtitle` from path"""
|
||||
extension = ''
|
||||
for e in EXTENSIONS:
|
||||
if path.endswith(e):
|
||||
extension = e
|
||||
break
|
||||
if not extension:
|
||||
raise ValueError('Not a supported subtitle extension')
|
||||
language = os.path.splitext(path[:len(path) - len(extension)])[1][1:]
|
||||
if not language in list_languages(1):
|
||||
language = None
|
||||
return cls(path, language)
|
||||
|
||||
|
||||
class ResultSubtitle(ExternalSubtitle):
|
||||
"""Subtitle found using :mod:`~subliminal.services`
|
||||
|
||||
:param string path: path to the subtitle
|
||||
:param string language: language of the subtitle (second element of :class:`~subliminal.languages.LANGUAGES`)
|
||||
:param string service: name of the service
|
||||
:param string link: download link for the subtitle
|
||||
:param string release: release name of the video
|
||||
:param float confidence: confidence that the subtitle matches the video according to the service
|
||||
:param set keywords: keywords that describe the subtitle
|
||||
|
||||
"""
|
||||
def __init__(self, path, language, service, link, release=None, confidence=1, keywords=set()):
|
||||
super(ResultSubtitle, self).__init__(path, language)
|
||||
self.service = service
|
||||
self.link = link
|
||||
self.release = release
|
||||
self.confidence = confidence
|
||||
self.keywords = keywords
|
||||
|
||||
@property
|
||||
def single(self):
|
||||
"""Whether this is a single subtitle or not. A single subtitle does not have
|
||||
a language indicator in its file name
|
||||
|
||||
:rtype: bool
|
||||
|
||||
"""
|
||||
extension = os.path.splitext(self.path)[0]
|
||||
language = os.path.splitext(self.path[:len(self.path) - len(extension)])[1][1:]
|
||||
if not language in list_languages(1):
|
||||
return True
|
||||
return False
|
||||
|
||||
def __repr__(self):
|
||||
return 'ResultSubtitle(%s, %s, %.2f, %s)' % (self.language, self.service, self.confidence, self.release)
|
||||
|
||||
|
||||
def get_subtitle_path(video_path, language, multi):
|
||||
"""Create the subtitle path from the given video path using language if multi"""
|
||||
if not os.path.exists(video_path):
|
||||
path = os.path.splitext(os.path.basename(video_path))[0]
|
||||
else:
|
||||
path = os.path.splitext(video_path)[0]
|
||||
if multi and language:
|
||||
return path + '.%s%s' % (language, EXTENSIONS[0])
|
||||
return path + '%s' % EXTENSIONS[0]
|
||||
@@ -0,0 +1,66 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
# Copyright 2011-2012 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 GNU Lesser 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
|
||||
# GNU Lesser General Public License for more details.
|
||||
#
|
||||
# You should have received a copy of the GNU Lesser General Public License
|
||||
# along with subliminal. If not, see <http://www.gnu.org/licenses/>.
|
||||
__all__ = ['Task', 'ListTask', 'DownloadTask', 'StopTask']
|
||||
|
||||
|
||||
class Task(object):
|
||||
"""Base class for tasks to use in subliminal"""
|
||||
pass
|
||||
|
||||
|
||||
class ListTask(Task):
|
||||
"""List task used by the worker to search for subtitles
|
||||
|
||||
:param video: video to search subtitles for
|
||||
:type video: :class:`~subliminal.videos.Video`
|
||||
:param list languages: languages to search for
|
||||
:param string service: name of the service to use
|
||||
:param config: configuration for the service
|
||||
:type config: :class:`~subliminal.services.ServiceConfig`
|
||||
|
||||
"""
|
||||
def __init__(self, video, languages, service, config):
|
||||
self.video = video
|
||||
self.service = service
|
||||
self.languages = languages
|
||||
self.config = config
|
||||
|
||||
def __repr__(self):
|
||||
return 'ListTask(%r, %r, %s, %r)' % (self.video, self.languages, self.service, self.config)
|
||||
|
||||
|
||||
class DownloadTask(Task):
|
||||
"""Download task used by the worker to download subtitles
|
||||
|
||||
:param video: video to download subtitles for
|
||||
:type video: :class:`~subliminal.videos.Video`
|
||||
:param subtitles: subtitles to download in order of preference
|
||||
:type subtitles: list of :class:`~subliminal.subtitles.Subtitle`
|
||||
|
||||
"""
|
||||
def __init__(self, video, subtitles):
|
||||
self.video = video
|
||||
self.subtitles = subtitles
|
||||
|
||||
def __repr__(self):
|
||||
return 'DownloadTask(%r, %r)' % (self.video, self.subtitles)
|
||||
|
||||
|
||||
class StopTask(Task):
|
||||
"""Stop task that will stop the worker"""
|
||||
pass
|
||||
@@ -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,64 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
# Copyright 2011-2012 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 GNU Lesser 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
|
||||
# GNU Lesser General Public License for more details.
|
||||
#
|
||||
# You should have received a copy of the GNU Lesser General Public License
|
||||
# along with subliminal. If not, see <http://www.gnu.org/licenses/>.
|
||||
import re
|
||||
|
||||
|
||||
__all__ = ['get_keywords', 'split_keyword', 'to_unicode']
|
||||
|
||||
|
||||
def get_keywords(guess):
|
||||
"""Retrieve keywords from guessed informations
|
||||
|
||||
:param guess: guessed informations
|
||||
:type guess: :class:`guessit.guess.Guess`
|
||||
:return: lower case alphanumeric keywords
|
||||
:rtype: set
|
||||
|
||||
"""
|
||||
keywords = set()
|
||||
for k in ['releaseGroup', 'screenSize', 'videoCodec', 'format']:
|
||||
if k in guess:
|
||||
keywords = keywords | split_keyword(guess[k].lower())
|
||||
return keywords
|
||||
|
||||
|
||||
def split_keyword(keyword):
|
||||
"""Split a keyword in multiple ones on any non-alphanumeric character
|
||||
|
||||
:param string keyword: keyword
|
||||
:return: keywords
|
||||
:rtype: set
|
||||
|
||||
"""
|
||||
split = set(re.findall(r'\w+', keyword))
|
||||
return split
|
||||
|
||||
|
||||
def to_unicode(data):
|
||||
"""Convert a basestring to unicode
|
||||
|
||||
:param basestring data: data to decode
|
||||
:return: data as unicode
|
||||
:rtype: unicode
|
||||
|
||||
"""
|
||||
if not isinstance(data, basestring):
|
||||
raise ValueError('Basestring expected')
|
||||
if isinstance(data, unicode):
|
||||
return data
|
||||
return unicode(data, 'utf-8', 'replace')
|
||||
@@ -0,0 +1,269 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
# Copyright 2011-2012 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 GNU Lesser 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
|
||||
# GNU Lesser General Public License for more details.
|
||||
#
|
||||
# You should have received a copy of the GNU Lesser General Public License
|
||||
# along with subliminal. If not, see <http://www.gnu.org/licenses/>.
|
||||
from . import subtitles
|
||||
from .languages import list_languages
|
||||
import enzyme
|
||||
import guessit
|
||||
import hashlib
|
||||
import logging
|
||||
import mimetypes
|
||||
import os
|
||||
import struct
|
||||
|
||||
|
||||
__all__ = ['EXTENSIONS', 'MIMETYPES', 'Video', 'Episode', 'Movie', 'UnknownVideo',
|
||||
'scan', 'hash_opensubtitles', 'hash_thesubdb']
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
#: Video extensions
|
||||
EXTENSIONS = ['.avi', '.mkv', '.mpg', '.mp4', '.m4v', '.mov', '.ogm', '.ogv', '.wmv',
|
||||
'.divx', '.asf']
|
||||
|
||||
#: Video mimetypes
|
||||
MIMETYPES = ['video/mpeg', 'video/mp4', 'video/quicktime', 'video/x-ms-wmv', 'video/x-msvideo',
|
||||
'video/x-flv', 'video/x-matroska', 'video/x-matroska-3d']
|
||||
|
||||
|
||||
class Video(object):
|
||||
"""Base class for videos
|
||||
|
||||
:param string path: path
|
||||
:param guess: guessed informations
|
||||
:type guess: :class:`~guessit.guess.Guess`
|
||||
:param string imdbid: imdbid
|
||||
|
||||
"""
|
||||
def __init__(self, path, guess, imdbid=None):
|
||||
self.release = path
|
||||
self.guess = guess
|
||||
self.imdbid = imdbid
|
||||
self._path = None
|
||||
self.hashes = {}
|
||||
if os.path.exists(path):
|
||||
self._path = path
|
||||
self.size = os.path.getsize(self._path)
|
||||
self._compute_hashes()
|
||||
|
||||
@classmethod
|
||||
def from_path(cls, path):
|
||||
"""Create a :class:`Video` subclass guessing all informations from the given path
|
||||
|
||||
:param string path: path
|
||||
:return: video object
|
||||
:rtype: :class:`Episode` or :class:`Movie` or :class:`UnknownVideo`
|
||||
|
||||
"""
|
||||
guess = guessit.guess_file_info(path, 'autodetect')
|
||||
result = None
|
||||
if guess['type'] == 'episode' and 'series' in guess and 'season' in guess and 'episodeNumber' in guess:
|
||||
title = None
|
||||
if 'title' in guess:
|
||||
title = guess['title']
|
||||
result = Episode(path, guess['series'], guess['season'], guess['episodeNumber'], title, guess)
|
||||
if guess['type'] == 'movie' and 'title' in guess:
|
||||
year = None
|
||||
if 'year' in guess:
|
||||
year = guess['year']
|
||||
result = Movie(path, guess['title'], year, guess)
|
||||
if not result:
|
||||
result = UnknownVideo(path, guess)
|
||||
if not isinstance(result, cls):
|
||||
raise ValueError('Video is not of requested type')
|
||||
return result
|
||||
|
||||
@property
|
||||
def exists(self):
|
||||
"""Whether the video exists or not"""
|
||||
if self._path:
|
||||
return os.path.exists(self._path)
|
||||
return False
|
||||
|
||||
@property
|
||||
def path(self):
|
||||
"""Path to the video"""
|
||||
return self._path
|
||||
|
||||
@path.setter
|
||||
def path(self, value):
|
||||
if not os.path.exists(value):
|
||||
raise ValueError('Path does not exists')
|
||||
self._path = value
|
||||
self.size = os.path.getsize(self._path)
|
||||
self._compute_hashes()
|
||||
|
||||
def _compute_hashes(self):
|
||||
"""Compute different hashes"""
|
||||
self.hashes['OpenSubtitles'] = hash_opensubtitles(self.path)
|
||||
self.hashes['TheSubDB'] = hash_thesubdb(self.path)
|
||||
|
||||
def scan(self):
|
||||
"""Scan and return associated subtitles
|
||||
|
||||
:return: associated subtitles
|
||||
:rtype: list of :class:`~subliminal.subtitles.Subtitle`
|
||||
|
||||
"""
|
||||
if not self.exists:
|
||||
return []
|
||||
basepath = os.path.splitext(self.path)[0]
|
||||
results = []
|
||||
video_infos = None
|
||||
try:
|
||||
video_infos = enzyme.parse(self.path)
|
||||
logger.debug(u'Succeeded parsing %s with enzyme: %r' % (self.path, video_infos))
|
||||
except:
|
||||
logger.debug(u'Failed parsing %s with enzyme' % self.path)
|
||||
if isinstance(video_infos, enzyme.core.AVContainer):
|
||||
results.extend([subtitles.EmbeddedSubtitle.from_enzyme(self.path, s) for s in video_infos.subtitles])
|
||||
for l in list_languages(1):
|
||||
for e in subtitles.EXTENSIONS:
|
||||
single_path = basepath + '%s' % e
|
||||
if os.path.exists(single_path):
|
||||
results.append(subtitles.ExternalSubtitle(single_path, None))
|
||||
multi_path = basepath + '.%s%s' % (l, e)
|
||||
if os.path.exists(multi_path):
|
||||
results.append(subtitles.ExternalSubtitle(multi_path, l))
|
||||
return results
|
||||
|
||||
def __repr__(self):
|
||||
return '%s(%r)' % (self.__class__.__name__, self.release)
|
||||
|
||||
|
||||
class Episode(Video):
|
||||
"""Episode :class:`Video`
|
||||
|
||||
:param string path: path
|
||||
:param string series: series
|
||||
:param int season: season number
|
||||
:param int episode: episode number
|
||||
:param string title: title
|
||||
:param guess: guessed informations
|
||||
:type guess: :class:`~guessit.guess.Guess`
|
||||
:param string tvdbid: tvdbid
|
||||
:param string imdbid: imdbid
|
||||
|
||||
"""
|
||||
def __init__(self, path, series, season, episode, title=None, guess=None, tvdbid=None, imdbid=None):
|
||||
super(Episode, self).__init__(path, guess, imdbid)
|
||||
self.series = series
|
||||
self.title = title
|
||||
self.season = season
|
||||
self.episode = episode
|
||||
self.tvdbid = tvdbid
|
||||
|
||||
|
||||
class Movie(Video):
|
||||
"""Movie :class:`Video`
|
||||
|
||||
:param string path: path
|
||||
:param string title: title
|
||||
:param int year: year
|
||||
:param guess: guessed informations
|
||||
:type guess: :class:`~guessit.guess.Guess`
|
||||
:param string imdbid: imdbid
|
||||
|
||||
"""
|
||||
def __init__(self, path, title, year=None, guess=None, imdbid=None):
|
||||
super(Movie, self).__init__(path, guess, imdbid)
|
||||
self.title = title
|
||||
self.year = year
|
||||
|
||||
|
||||
class UnknownVideo(Video):
|
||||
"""Unknown video"""
|
||||
pass
|
||||
|
||||
|
||||
def scan(entry, max_depth=3, depth=0):
|
||||
"""Scan a path for videos and subtitles
|
||||
|
||||
:param string entry: path
|
||||
:param int max_depth: maximum folder depth
|
||||
:param int depth: starting depth
|
||||
:return: found videos and subtitles
|
||||
:rtype: list of (:class:`Video`, [:class:`~subliminal.subtitles.Subtitle`])
|
||||
|
||||
"""
|
||||
if depth > max_depth and max_depth != 0: # we do not want to search the whole file system except if max_depth = 0
|
||||
return []
|
||||
if depth == 0:
|
||||
entry = os.path.abspath(entry)
|
||||
if os.path.isdir(entry): # a dir? recurse
|
||||
logger.debug(u'Scanning directory %s with depth %d/%d' % (entry, depth, max_depth))
|
||||
result = []
|
||||
for e in os.listdir(entry):
|
||||
result.extend(scan(os.path.join(entry, e), max_depth, depth + 1))
|
||||
return result
|
||||
if os.path.isfile(entry) or depth == 0:
|
||||
logger.debug(u'Scanning file %s with depth %d/%d' % (entry, depth, max_depth))
|
||||
if depth != 0: # trust the user: only check for valid format if recursing
|
||||
if mimetypes.guess_type(entry)[0] not in MIMETYPES and os.path.splitext(entry)[1] not in EXTENSIONS:
|
||||
return []
|
||||
video = Video.from_path(entry)
|
||||
return [(video, video.scan())]
|
||||
logger.warning(u'Scanning entry %s failed with depth %d/%d' % (entry, depth, max_depth))
|
||||
return [] # anything else
|
||||
|
||||
|
||||
def hash_opensubtitles(path):
|
||||
"""Compute a hash using OpenSubtitles' algorithm
|
||||
|
||||
:param string path: path
|
||||
:return: hash
|
||||
:rtype: string
|
||||
|
||||
"""
|
||||
longlongformat = 'q' # long long
|
||||
bytesize = struct.calcsize(longlongformat)
|
||||
with open(path, 'rb') as f:
|
||||
filesize = os.path.getsize(path)
|
||||
filehash = filesize
|
||||
if filesize < 65536 * 2:
|
||||
return None
|
||||
for _ in range(65536 / bytesize):
|
||||
filebuffer = f.read(bytesize)
|
||||
(l_value,) = struct.unpack(longlongformat, 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(longlongformat, filebuffer)
|
||||
filehash += l_value
|
||||
filehash = filehash & 0xFFFFFFFFFFFFFFFF
|
||||
returnedhash = '%016x' % filehash
|
||||
logger.debug(u'Computed OpenSubtitle hash %s for %s' % (returnedhash, path))
|
||||
return returnedhash
|
||||
|
||||
|
||||
def hash_thesubdb(path):
|
||||
"""Compute a hash using TheSubDB's algorithm
|
||||
|
||||
:param string path: path
|
||||
:return: hash
|
||||
:rtype: string
|
||||
|
||||
"""
|
||||
readsize = 64 * 1024
|
||||
with open(path, 'rb') as f:
|
||||
data = f.read(readsize)
|
||||
f.seek(-readsize, os.SEEK_END)
|
||||
data += f.read(readsize)
|
||||
returnedhash = hashlib.md5(data).hexdigest()
|
||||
logger.debug(u'Computed TheSubDB hash %s for %s' % (returnedhash, path))
|
||||
return returnedhash
|
||||
@@ -0,0 +1,58 @@
|
||||
#!/usr/bin/env python
|
||||
# -*- coding: utf-8 -*-
|
||||
# Copyright 2011-2012 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 GNU Lesser 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
|
||||
# GNU Lesser General Public License for more details.
|
||||
#
|
||||
# You should have received a copy of the GNU Lesser General Public License
|
||||
# along with subliminal. If not, see <http://www.gnu.org/licenses/>.
|
||||
from subliminal import Pool
|
||||
import os
|
||||
import time
|
||||
import unittest
|
||||
|
||||
|
||||
cache_dir = u'/tmp/sublicache'
|
||||
if not os.path.exists(cache_dir):
|
||||
os.mkdir(cache_dir)
|
||||
existing_video = u'/something/The.Big.Bang.Theory.S05E18.HDTV.x264-LOL.mp4'
|
||||
|
||||
|
||||
class AsyncTestCase(unittest.TestCase):
|
||||
def test_pool(self):
|
||||
p = Pool(4)
|
||||
self.assertTrue(len(p.workers) == 4)
|
||||
for w in p.workers:
|
||||
self.assertTrue(w.isAlive() == False)
|
||||
p.start()
|
||||
for w in p.workers:
|
||||
self.assertTrue(w.isAlive() == True)
|
||||
p.stop()
|
||||
p.join()
|
||||
time.sleep(0.2) # so terminate is finished on Worker and proper Thread methods finished
|
||||
for w in p.workers:
|
||||
self.assertTrue(w.isAlive() == False)
|
||||
|
||||
def test_list_subtitles(self):
|
||||
with Pool(4) as p:
|
||||
results = p.list_subtitles(existing_video, languages=['en', 'fr'], cache_dir=cache_dir, max_depth=3)
|
||||
self.assertTrue(len(results) > 0)
|
||||
|
||||
def test_download_subtitles(self):
|
||||
with Pool(4) as p:
|
||||
results = p.download_subtitles(existing_video, languages=['en', 'fr'], cache_dir=cache_dir, max_depth=3)
|
||||
self.assertTrue(len(results) > 0)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -0,0 +1,392 @@
|
||||
#!/usr/bin/env python
|
||||
# -*- coding: utf-8 -*-
|
||||
# Copyright 2011-2012 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 GNU Lesser 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
|
||||
# GNU Lesser General Public License for more details.
|
||||
#
|
||||
# You should have received a copy of the GNU Lesser General Public License
|
||||
# along with subliminal. If not, see <http://www.gnu.org/licenses/>.
|
||||
from subliminal import videos
|
||||
from subliminal.exceptions import MissingLanguageError, ServiceError
|
||||
from subliminal.services import ServiceConfig
|
||||
from subliminal.services.bierdopje import BierDopje
|
||||
from subliminal.services.opensubtitles import OpenSubtitles
|
||||
from subliminal.services.subswiki import SubsWiki
|
||||
from subliminal.services.subtitulos import Subtitulos
|
||||
from subliminal.services.thesubdb import TheSubDB
|
||||
from subliminal.subtitles import Subtitle
|
||||
import os
|
||||
import unittest
|
||||
|
||||
|
||||
cache_dir = u'/tmp/sublicache'
|
||||
if not os.path.exists(cache_dir):
|
||||
os.mkdir(cache_dir)
|
||||
existing_video = u'/something/The.Big.Bang.Theory.S05E18.HDTV.x264-LOL.mp4'
|
||||
|
||||
|
||||
class BierDopjeTestCase(unittest.TestCase):
|
||||
query_tests = ['test_query_series', 'test_query_wrong_series', 'test_query_wrong_languages',
|
||||
'test_query_tvdbid', 'test_query_wrong_tvdbid', 'test_query_series_and_tvdbid']
|
||||
list_tests = ['test_list_episode', 'test_list_movie', 'test_list_wrong_languages']
|
||||
download_tests = ['test_download']
|
||||
|
||||
def setUp(self):
|
||||
self.config = ServiceConfig(multi=True, cache_dir=cache_dir)
|
||||
self.episode_path = u'The Big Bang Theory/Season 05/S05E06 - The Rhinitis Revelation - HD TV.mkv'
|
||||
self.movie_path = u'Inception (2010)/Inception - 1080p.mkv'
|
||||
self.languages = set(['en', 'nl'])
|
||||
self.wrong_languages = set(['zz', 'es'])
|
||||
self.fake_file = u'/tmp/fake_file'
|
||||
self.series = 'The Big Bang Theory'
|
||||
self.wrong_series = 'No Existent Show Name'
|
||||
self.season = 5
|
||||
self.episode = 6
|
||||
self.tvdbid = 80379
|
||||
self.wrong_tvdbid = 9999999999
|
||||
|
||||
def test_query_series(self):
|
||||
with BierDopje(self.config) as service:
|
||||
results = service.query(self.season, self.episode, self.languages, self.fake_file, series=self.series)
|
||||
self.assertTrue(len(results) > 0)
|
||||
|
||||
def test_query_wrong_series(self):
|
||||
with BierDopje(self.config) as service:
|
||||
results = service.query(self.season, self.episode, self.languages, self.fake_file, series=self.wrong_series)
|
||||
self.assertTrue(len(results) == 0)
|
||||
|
||||
def test_query_wrong_languages(self):
|
||||
with BierDopje(self.config) as service:
|
||||
results = service.query(self.season, self.episode, self.wrong_languages, self.fake_file, series=self.series)
|
||||
self.assertTrue(len(results) == 0)
|
||||
|
||||
def test_query_tvdbid(self):
|
||||
with BierDopje(self.config) as service:
|
||||
results = service.query(self.season, self.episode, self.languages, self.fake_file, tvdbid=self.tvdbid)
|
||||
self.assertTrue(len(results) > 0)
|
||||
|
||||
def test_query_series_and_tvdbid(self):
|
||||
with BierDopje(self.config) as service:
|
||||
results = service.query(self.season, self.episode, self.languages, self.fake_file, series=self.series, tvdbid=self.tvdbid)
|
||||
self.assertTrue(len(results) > 0)
|
||||
|
||||
def test_query_wrong_tvdbid(self):
|
||||
with BierDopje(self.config) as service:
|
||||
results = service.query(self.season, self.episode, self.languages, self.fake_file, tvdbid=self.wrong_tvdbid)
|
||||
self.assertTrue(len(results) == 0)
|
||||
|
||||
def test_list_episode(self):
|
||||
episode = videos.Video.from_path(self.episode_path)
|
||||
with BierDopje(self.config) as service:
|
||||
results = service.list(episode, self.languages)
|
||||
self.assertTrue(len(results) > 0)
|
||||
|
||||
def test_list_movie(self):
|
||||
movie = videos.Video.from_path(self.movie_path)
|
||||
with BierDopje(self.config) as service:
|
||||
results = service.list(movie, self.languages)
|
||||
self.assertTrue(len(results) == 0)
|
||||
|
||||
def test_list_wrong_languages(self):
|
||||
episode = videos.Video.from_path(self.episode_path)
|
||||
with BierDopje(self.config) as service:
|
||||
results = service.list(episode, self.wrong_languages)
|
||||
self.assertTrue(len(results) == 0)
|
||||
|
||||
def test_download(self):
|
||||
episode = videos.Video.from_path(self.episode_path)
|
||||
with BierDopje(self.config) as service:
|
||||
subtitle = service.list(episode, self.languages)[0]
|
||||
if os.path.exists(subtitle.path):
|
||||
os.remove(subtitle.path)
|
||||
service.download(subtitle)
|
||||
self.assertTrue(os.path.exists(subtitle.path))
|
||||
|
||||
|
||||
class OpenSubtitlesTestCase(unittest.TestCase):
|
||||
query_tests = ['test_query_query', 'test_query_imdbid', 'test_query_hash', 'test_query_wrong_languages']
|
||||
list_tests = ['test_list', 'test_list_wrong_languages']
|
||||
download_tests = ['test_download']
|
||||
|
||||
def setUp(self):
|
||||
self.config = ServiceConfig(multi=True, cache_dir=cache_dir)
|
||||
self.languages = set(['en', 'fr'])
|
||||
self.wrong_languages = set(['zz', 'yy'])
|
||||
self.fake_file = u'/tmp/fake_file'
|
||||
self.path = existing_video
|
||||
self.series = 'The Big Bang Theory'
|
||||
self.movie = 'Inception'
|
||||
self.wrong_series = 'No Existent Show Name'
|
||||
self.imdbid = 'tt1375666'
|
||||
self.wrong_imdbid = 'tt9999999'
|
||||
self.hash = '51e57c4e8fd77990'
|
||||
self.size = 882571264L
|
||||
|
||||
def test_query_query(self):
|
||||
with OpenSubtitles(self.config) as service:
|
||||
results = service.query(self.fake_file, self.languages, query=self.movie)
|
||||
self.assertTrue(len(results) > 0)
|
||||
|
||||
def test_query_imdbid(self):
|
||||
with OpenSubtitles(self.config) as service:
|
||||
results = service.query(self.fake_file, self.languages, imdbid=self.imdbid)
|
||||
self.assertTrue(len(results) > 0)
|
||||
|
||||
def test_query_hash(self):
|
||||
with OpenSubtitles(self.config) as service:
|
||||
results = service.query(self.fake_file, self.languages, moviehash=self.hash, size=self.size)
|
||||
self.assertTrue(len(results) > 0)
|
||||
|
||||
def test_query_wrong_languages(self):
|
||||
with OpenSubtitles(self.config) as service:
|
||||
with self.assertRaises(MissingLanguageError):
|
||||
service.query(self.fake_file, self.wrong_languages, moviehash=self.hash, size=self.size)
|
||||
|
||||
def test_list(self):
|
||||
video = videos.Video.from_path(self.path)
|
||||
with OpenSubtitles(self.config) as service:
|
||||
results = service.list(video, self.languages)
|
||||
self.assertTrue(len(results) > 0)
|
||||
|
||||
def test_list_wrong_languages(self):
|
||||
video = videos.Video.from_path(self.path)
|
||||
with OpenSubtitles(self.config) as service:
|
||||
results = service.list(video, self.wrong_languages)
|
||||
self.assertTrue(len(results) == 0)
|
||||
|
||||
def test_download(self):
|
||||
video = videos.Video.from_path(self.path)
|
||||
with OpenSubtitles(self.config) as service:
|
||||
subtitle = service.list(video, self.languages)[0]
|
||||
if os.path.exists(subtitle.path):
|
||||
os.remove(subtitle.path)
|
||||
result = service.download(subtitle)
|
||||
self.assertTrue(isinstance(result, Subtitle))
|
||||
self.assertTrue(os.path.exists(subtitle.path))
|
||||
|
||||
|
||||
class TheSubDBTestCase(unittest.TestCase):
|
||||
query_tests = ['test_query', 'test_query_wrong_hash', 'test_query_wrong_languages']
|
||||
list_tests = ['test_list', 'test_list_wrong_languages']
|
||||
download_tests = ['test_download']
|
||||
|
||||
def setUp(self):
|
||||
self.config = ServiceConfig(multi=True, cache_dir=cache_dir)
|
||||
self.path = existing_video
|
||||
self.hash = u'edc1981d6459c6111fe36205b4aff6c2'
|
||||
self.wrong_hash = u'ffffffffffffffffffffffffffffffff'
|
||||
self.languages = set(['en', 'nl'])
|
||||
self.wrong_languages = set(['zz', 'cs'])
|
||||
self.fake_file = u'/tmp/fake_file'
|
||||
|
||||
def test_query(self):
|
||||
with TheSubDB(self.config) as service:
|
||||
results = service.query(self.fake_file, self.hash, self.languages)
|
||||
self.assertTrue(len(results) > 0)
|
||||
|
||||
def test_query_wrong_hash(self):
|
||||
with TheSubDB(self.config) as service:
|
||||
results = service.query(self.fake_file, self.wrong_hash, self.languages)
|
||||
self.assertTrue(len(results) == 0)
|
||||
|
||||
def test_query_wrong_languages(self):
|
||||
with TheSubDB(self.config) as service:
|
||||
results = service.query(self.fake_file, self.hash, self.wrong_languages)
|
||||
self.assertTrue(len(results) == 0)
|
||||
|
||||
def test_list(self):
|
||||
video = videos.Video.from_path(self.path)
|
||||
with TheSubDB(self.config) as service:
|
||||
results = service.list(video, self.languages)
|
||||
self.assertTrue(len(results) > 0)
|
||||
|
||||
def test_list_wrong_languages(self):
|
||||
video = videos.Video.from_path(self.path)
|
||||
with TheSubDB(self.config) as service:
|
||||
results = service.list(video, self.wrong_languages)
|
||||
self.assertTrue(len(results) == 0)
|
||||
|
||||
def test_download(self):
|
||||
video = videos.Video.from_path(self.path)
|
||||
with TheSubDB(self.config) as service:
|
||||
subtitle = service.list(video, self.languages)[0]
|
||||
if os.path.exists(subtitle.path):
|
||||
os.remove(subtitle.path)
|
||||
service.download(subtitle)
|
||||
self.assertTrue(os.path.exists(subtitle.path))
|
||||
|
||||
|
||||
class SubsWikiTestCase(unittest.TestCase):
|
||||
query_tests = ['test_query_series', 'test_query_movie', 'test_query_wrong_parameters', 'test_query_wrong_series', 'test_query_wrong_languages']
|
||||
list_tests = ['test_list_series', 'test_list_movie', 'test_list_series_wrong_languages']
|
||||
download_tests = ['test_download']
|
||||
|
||||
def setUp(self):
|
||||
self.config = ServiceConfig(multi=True, cache_dir=cache_dir)
|
||||
self.fake_file = u'/tmp/fake_file'
|
||||
self.languages = set(['en', 'es'])
|
||||
self.wrong_languages = set(['zz', 'ay'])
|
||||
self.movie_path = u'Soul Surfer (2011)/Soul.Surfer.(2011).DVDRip.XviD-TWiZTED.mkv'
|
||||
self.movie_keywords = set(['twizted'])
|
||||
self.movie = u'Soul Surfer'
|
||||
self.movie_year = 2011
|
||||
self.series_path = u'The Big Bang Theory/Season 05/The.Big.Bang.Theory.S05E06.HDTV.XviD-ASAP.mkv'
|
||||
self.series_keywords = set(['asap', 'hdtv'])
|
||||
self.series = 'The Big Bang Theory'
|
||||
self.wrong_series = 'No Existent Show Name'
|
||||
self.series_season = 5
|
||||
self.series_episode = 6
|
||||
|
||||
def test_query_series(self):
|
||||
with SubsWiki(self.config) as service:
|
||||
results = service.query(self.fake_file, self.languages, keywords=self.series_keywords, series=self.series, season=self.series_season, episode=self.series_episode)
|
||||
self.assertTrue(len(results) > 0)
|
||||
|
||||
def test_query_movie(self):
|
||||
with SubsWiki(self.config) as service:
|
||||
results = service.query(self.fake_file, self.languages, keywords=self.movie_keywords, movie=self.movie, year=self.movie_year)
|
||||
self.assertTrue(len(results) > 0)
|
||||
|
||||
def test_query_wrong_parameters(self):
|
||||
with SubsWiki(self.config) as service:
|
||||
with self.assertRaises(ServiceError):
|
||||
service.query(self.fake_file, self.languages, keywords=self.movie_keywords, movie=self.movie, series=self.series)
|
||||
|
||||
def test_query_wrong_series(self):
|
||||
with SubsWiki(self.config) as service:
|
||||
results = service.query(self.fake_file, self.languages, keywords=self.series_keywords, series=self.wrong_series, season=self.series_season, episode=self.series_episode)
|
||||
self.assertTrue(len(results) == 0)
|
||||
|
||||
def test_query_wrong_languages(self):
|
||||
with SubsWiki(self.config) as service:
|
||||
results = service.query(self.fake_file, self.wrong_languages, keywords=self.series_keywords, series=self.series, season=self.series_season, episode=self.series_episode)
|
||||
self.assertTrue(len(results) == 0)
|
||||
|
||||
def test_list_series(self):
|
||||
video = videos.Video.from_path(self.series_path)
|
||||
with SubsWiki(self.config) as service:
|
||||
results = service.list(video, self.languages)
|
||||
self.assertTrue(len(results) > 0)
|
||||
|
||||
def test_list_movie(self):
|
||||
video = videos.Video.from_path(self.movie_path)
|
||||
with SubsWiki(self.config) as service:
|
||||
results = service.list(video, self.languages)
|
||||
self.assertTrue(len(results) > 0)
|
||||
|
||||
def test_list_series_wrong_languages(self):
|
||||
video = videos.Video.from_path(self.series_path)
|
||||
with SubsWiki(self.config) as service:
|
||||
results = service.list(video, self.wrong_languages)
|
||||
self.assertTrue(len(results) == 0)
|
||||
|
||||
def test_download(self):
|
||||
video = videos.Video.from_path(self.series_path)
|
||||
with SubsWiki(self.config) as service:
|
||||
subtitle = service.list(video, self.languages)[0]
|
||||
if os.path.exists(subtitle.path):
|
||||
os.remove(subtitle.path)
|
||||
service.download(subtitle)
|
||||
self.assertTrue(os.path.exists(subtitle.path))
|
||||
|
||||
|
||||
class SubtitulosTestCase(unittest.TestCase):
|
||||
query_tests = ['test_query', 'test_query_wrong_series', 'test_query_wrong_languages']
|
||||
list_tests = ['test_list', 'test_list_wrong_languages']
|
||||
download_tests = ['test_download']
|
||||
|
||||
def setUp(self):
|
||||
self.config = ServiceConfig(multi=True, cache_dir=cache_dir)
|
||||
self.fake_file = u'/tmp/fake_file'
|
||||
self.languages = set(['en', 'es'])
|
||||
self.wrong_languages = set(['zz', 'ay'])
|
||||
self.path = u'The Big Bang Theory/Season 05/The.Big.Bang.Theory.S05E06.HDTV.XviD-ASAP.mkv'
|
||||
self.keywords = set(['asap', 'hdtv'])
|
||||
self.series = 'The Big Bang Theory'
|
||||
self.wrong_series = 'No Existent Show Name'
|
||||
self.season = 5
|
||||
self.episode = 6
|
||||
|
||||
def test_query(self):
|
||||
with Subtitulos(self.config) as service:
|
||||
results = service.query(self.fake_file, self.languages, self.keywords, self.series, self.season, self.episode)
|
||||
self.assertTrue(len(results) > 0)
|
||||
|
||||
def test_query_wrong_series(self):
|
||||
with Subtitulos(self.config) as service:
|
||||
results = service.query(self.fake_file, self.languages, self.keywords, self.wrong_series, self.season, self.episode)
|
||||
self.assertTrue(len(results) == 0)
|
||||
|
||||
def test_query_wrong_languages(self):
|
||||
with Subtitulos(self.config) as service:
|
||||
results = service.query(self.fake_file, self.wrong_languages, self.keywords, self.series, self.season, self.episode)
|
||||
self.assertTrue(len(results) == 0)
|
||||
|
||||
def test_list(self):
|
||||
video = videos.Video.from_path(self.path)
|
||||
with Subtitulos(self.config) as service:
|
||||
results = service.list(video, self.languages)
|
||||
self.assertTrue(len(results) > 0)
|
||||
|
||||
def test_list_wrong_languages(self):
|
||||
video = videos.Video.from_path(self.path)
|
||||
with Subtitulos(self.config) as service:
|
||||
results = service.list(video, self.wrong_languages)
|
||||
self.assertTrue(len(results) == 0)
|
||||
|
||||
def test_download(self):
|
||||
video = videos.Video.from_path(self.path)
|
||||
with Subtitulos(self.config) as service:
|
||||
subtitle = service.list(video, self.languages)[0]
|
||||
if os.path.exists(subtitle.path):
|
||||
os.remove(subtitle.path)
|
||||
result = service.download(subtitle)
|
||||
self.assertTrue(os.path.exists(subtitle.path))
|
||||
|
||||
|
||||
def query_suite():
|
||||
suite = unittest.TestSuite()
|
||||
suite.addTests(map(BierDopjeTestCase, BierDopjeTestCase.query_tests))
|
||||
suite.addTests(map(OpenSubtitlesTestCase, OpenSubtitlesTestCase.query_tests))
|
||||
suite.addTests(map(TheSubDBTestCase, TheSubDBTestCase.query_tests))
|
||||
suite.addTests(map(SubsWikiTestCase, SubsWikiTestCase.query_tests))
|
||||
suite.addTests(map(SubtitulosTestCase, SubtitulosTestCase.query_tests))
|
||||
return suite
|
||||
|
||||
|
||||
def list_suite():
|
||||
suite = unittest.TestSuite()
|
||||
suite.addTests(map(BierDopjeTestCase, BierDopjeTestCase.list_tests))
|
||||
suite.addTests(map(OpenSubtitlesTestCase, OpenSubtitlesTestCase.list_tests))
|
||||
suite.addTests(map(TheSubDBTestCase, TheSubDBTestCase.list_tests))
|
||||
suite.addTests(map(SubsWikiTestCase, SubsWikiTestCase.list_tests))
|
||||
suite.addTests(map(SubtitulosTestCase, SubtitulosTestCase.list_tests))
|
||||
return suite
|
||||
|
||||
|
||||
def download_suite():
|
||||
suite = unittest.TestSuite()
|
||||
suite.addTests(map(BierDopjeTestCase, BierDopjeTestCase.download_tests))
|
||||
suite.addTests(map(OpenSubtitlesTestCase, OpenSubtitlesTestCase.download_tests))
|
||||
suite.addTests(map(TheSubDBTestCase, TheSubDBTestCase.download_tests))
|
||||
suite.addTests(map(SubsWikiTestCase, SubsWikiTestCase.download_tests))
|
||||
suite.addTests(map(SubtitulosTestCase, SubtitulosTestCase.download_tests))
|
||||
return suite
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
suites = []
|
||||
suites.append(query_suite())
|
||||
suites.append(list_suite())
|
||||
suites.append(download_suite())
|
||||
unittest.TextTestRunner(verbosity=2).run(unittest.TestSuite(suites))
|
||||
Reference in New Issue
Block a user