File: __init__.py

package info (click to toggle)
imdbpy 2.7-2
  • links: PTS
  • area: main
  • in suites: etch, etch-m68k
  • size: 780 kB
  • ctags: 1,295
  • sloc: python: 8,867; ansic: 440; makefile: 44
file content (421 lines) | stat: -rw-r--r-- 17,599 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
"""
imdb package.

This package can be used to retrieve information about a movie or
a person from the IMDb database.
It can fetch data through different media (e.g.: the IMDb web pages,
a local installation, a SQL database, etc.)

Copyright 2004-2006 Davide Alberani <da@erlug.linux.it>

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 2 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, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
"""

__all__ = ['IMDb', 'IMDbError', 'Movie', 'Person']

import sys
from types import UnicodeType, TupleType, ListType, MethodType

from imdb import Movie, Person
from imdb._exceptions import IMDbError, IMDbDataAccessError
from imdb.utils import build_title, build_name


# URLs of the main pages for movies and persons.
imdbURL_movie_main = 'http://akas.imdb.com/title/tt%s/'
imdbURL_person_main = 'http://akas.imdb.com/name/nm%s/'


def IMDb(accessSystem='http', *arguments, **keywords):
    """Return an instance of the appropriate class.
    The accessSystem parameter is used to specify the kind of
    the preferred access system."""
    if accessSystem in ('http', 'web', 'html'):
        from parser.http import IMDbHTTPAccessSystem
        return IMDbHTTPAccessSystem(*arguments, **keywords)
    elif accessSystem in ('httpThin', 'webThin', 'htmlThin'):
        from parser.http import IMDbHTTPAccessSystem
        return IMDbHTTPAccessSystem(isThin=1, *arguments, **keywords)
    elif accessSystem in ('mobile',):
        from parser.mobile import IMDbMobileAccessSystem
        return IMDbMobileAccessSystem(*arguments, **keywords)
    elif accessSystem in ('local', 'files'):
        try:
            from parser.local import IMDbLocalAccessSystem
        except ImportError:
            raise IMDbError, 'the local access system is not installed'
        return IMDbLocalAccessSystem(*arguments, **keywords)
    elif accessSystem in ('sql', 'db', 'database'):
        try:
            from parser.sql import IMDbSqlAccessSystem
        except ImportError:
            raise IMDbError, 'the sql access system is not installed'
        return IMDbSqlAccessSystem(*arguments, **keywords)
    else:
        raise IMDbError, 'unknown kind of data access system: "%s"' \
                            % accessSystem


# XXX: I'm not sure this is a good guess.
#      I suppose that an argument of the IMDb function can be used to
#      set a default encoding for the output, and then Movie and Person
#      objects can use this default encoding, returning strings.
#      Anyway, passing unicode strings to search_movie() and search_person()
#      methods is always safer.
encoding = sys.stdin.encoding or sys.getdefaultencoding()

class IMDbBase:
    """The base class used to search for a movie/person and to get a
    Movie/Person object.

    This class cannot directly fetch data of any kind and so you
    have to search the "real" code into a subclass."""

    # The name of the preferred access system (MUST be overridden
    # in the subclasses).
    accessSystem = 'UNKNOWN'

    def __init__(self, defaultModFunct=None, *arguments, **keywords):
        """Initialize the access system.
        If specified, defaultModFunct is the function used by
        default by the Person and Movie objects, when accessing
        their text fields.
        """
        # The function used to output the strings that need modification (the
        # ones containing references to movie titles and person names).
        self._defModFunct = defaultModFunct

    def _normalize_movieID(self, movieID):
        """Normalize the given movieID."""
        # By default, do nothing.
        return movieID

    def _normalize_personID(self, personID):
        """Normalize the given personID."""
        # By default, do nothing.
        return personID

    def _get_real_movieID(self, movieID):
        """Handle title aliases."""
        # By default, do nothing.
        return movieID

    def _get_real_personID(self, personID):
        """Handle name aliases."""
        # By default, do nothing.
        return personID

    def _get_infoset(self, prefname):
        """Return methods with the name starting with prefname."""
        infoset = []
        excludes = ('%sinfoset' % prefname,)
        preflen = len(prefname)
        for name in dir(self.__class__):
            if name.startswith(prefname) and name not in excludes:
                member = getattr(self.__class__, name)
                if isinstance(member, MethodType):
                    infoset.append(name[preflen:].replace('_', ' '))
        return infoset

    def get_movie_infoset(self):
        """Return the list of info set available for movies."""
        return self._get_infoset('get_movie_')

    def get_person_infoset(self):
        """Return the list of info set available for persons."""
        return self._get_infoset('get_person_')

    def get_movie(self, movieID, info=Movie.Movie.default_info, modFunct=None):
        """Return a Movie object for the given movieID.

        The movieID is something used to univocally identify a movie;
        it can be the imdbID used by the IMDb web server, a file
        pointer, a line number in a file, an ID in a database, etc.

        info is the list of sets of information to retrieve.

        If specified, modFunct will be the function used by the Movie
        object when accessing its text fields (like 'plot')."""
        movieID = self._normalize_movieID(movieID)
        movieID = self._get_real_movieID(movieID)
        movie = Movie.Movie(movieID=movieID, accessSystem=self.accessSystem)
        modFunct = modFunct or self._defModFunct
        if modFunct is not None:
            movie.set_mod_funct(modFunct)
        self.update(movie, info)
        return movie

    def _search_movie(self, title, results):
        """Return a list of tuples (movieID, {movieData})"""
        # XXX: for the real implementation, see the method of the
        #      subclass, somewhere under the imdb.parser package.
        raise NotImplementedError, 'override this method'

    def search_movie(self, title, results=20):
        """Return a list of Movie objects for a query for the given title.
        The results argument is the maximum number of results to return."""
        try:
            results = int(results)
        except (ValueError, OverflowError):
            results = 20
        # XXX: I suppose it will be much safer if the user provides
        #      an unicode string... this is just a guess.
        if not isinstance(title, UnicodeType):
            title = unicode(title, encoding, 'replace')
        res = self._search_movie(title, results)
        return [Movie.Movie(movieID=self._get_real_movieID(mi),
                data=md, modFunct=self._defModFunct,
                accessSystem=self.accessSystem) for mi, md in res][:results]

    def get_person(self, personID, info=Person.Person.default_info,
                    modFunct=None):
        """Return a Person object for the given personID.

        The personID is something used to univocally identify a person;
        it can be the imdbID used by the IMDb web server, a file
        pointer, a line number in a file, an ID in a database, etc.

        info is the list of sets of information to retrieve.

        If specified, modFunct will be the function used by the Person
        object when accessing its text fields (like 'plot')."""
        personID = self._normalize_personID(personID)
        personID = self._get_real_personID(personID)
        person = Person.Person(personID=personID,
                                accessSystem=self.accessSystem)
        modFunct = modFunct or self._defModFunct
        if modFunct is not None:
            person.set_mod_funct(modFunct)
        self.update(person, info)
        return person

    def _search_person(self, name, results):
        """Return a list of tuples (personID, {personData})"""
        # XXX: for the real implementation, see the method of the
        #      subclass, somewhere under the imdb.parser package.
        raise NotImplementedError, 'override this method'

    def search_person(self, name, results=20):
        """Return a list of Person objects for a query for the given name.

        The results argument is the maximum number of results to return."""
        try:
            results = int(results)
        except (ValueError, OverflowError):
            results = 20
        if not isinstance(name, UnicodeType):
            name = unicode(name, encoding, 'replace')
        res = self._search_person(name, results)
        return [Person.Person(personID=self._get_real_personID(pi),
                data=pd, modFunct=self._defModFunct,
                accessSystem=self.accessSystem) for pi, pd in res][:results]

    def new_movie(self, *arguments, **keywords):
        """Return a Movie object."""
        # XXX: not really useful...
        if keywords.has_key('title'):
            if not isinstance(keywords['title'], UnicodeType):
                keywords['title'] = unicode(keywords['title'],
                                            encoding, 'replace')
        elif len(arguments) > 1:
            if not isinstance(arguments[1], UnicodeType):
                arguments[1] = unicode(arguments[1], encoding, 'replace')
        return Movie.Movie(accessSystem=self.accessSystem,
                            *arguments, **keywords)

    def new_person(self, *arguments, **keywords):
        """Return a Person object."""
        # XXX: not really useful...
        if keywords.has_key('name'):
            if not isinstance(keywords['name'], UnicodeType):
                keywords['name'] = unicode(keywords['name'],
                                            encoding, 'replace')
        elif len(arguments) > 1:
            if not isinstance(arguments[1], UnicodeType):
                arguments[1] = unicode(arguments[1], encoding, 'replace')
        return Person.Person(accessSystem=self.accessSystem,
                                *arguments, **keywords)

    def update(self, mop, info=None, override=0):
        """Given a Movie or Person object with only partial information,
        retrieve the required set of information.

        info is the list of sets of information to retrieve.

        If override is set, the information are retrieved and updated
        even if they're already in the object."""
        # XXX: should this be a method of the Movie and Person classes?
        #      NO!  What for Movie and Person instances created by
        #      external functions?
        mopID = None
        prefix = ''
        if isinstance(mop, Movie.Movie):
            mopID = mop.movieID
            prefix = 'movie'
        elif isinstance(mop, Person.Person):
            mopID = mop.personID
            prefix = 'person'
        else:
            raise IMDbError, 'object ' + repr(mop) + \
                        ' is not a Movie or Person instance'
        if mopID is None:
            raise IMDbDataAccessError, \
                    'the supplied object has null movieID or personID'
        if mop.accessSystem == self.accessSystem:
            as = self
        else:
            as = IMDb(mop.accessSystem)
        if info is None:
            info = mop.default_info
        elif info == 'all':
            if isinstance(mop, Movie.Movie):
                info = self.get_movie_infoset()
            else:
                info = self.get_person_infoset()
        if not isinstance(info, (TupleType, ListType)):
            info = (info,)
        res = {}
        for i in info:
            if i in mop.current_info and not override: continue
            try:
                method = getattr(as, 'get_%s_%s' %
                                    (prefix, i.replace(' ', '_')))
            except AttributeError:
                raise IMDbDataAccessError, 'unknown information set "%s"' % i
            ret = method(mopID)
            if ret.has_key('info sets'):
                for ri in ret['info sets']:
                    mop.add_to_current_info(ri)
            else:
                mop.add_to_current_info(i)
            if ret.has_key('data'):
                res.update(ret['data'])
            if ret.has_key('titlesRefs'):
                mop.update_titlesRefs(ret['titlesRefs'])
            if ret.has_key('namesRefs'):
                mop.update_namesRefs(ret['namesRefs'])
        mop.set_data(res, override=0)

    def get_imdbMovieID(self, movieID):
        """Translate a movieID in an imdbID (the ID used by the IMDb
        web server; must be overridden by the subclass."""
        # XXX: for the real implementation, see the method of the
        #      subclass, somewhere under the imdb.parser package.
        raise NotImplementedError, 'override this method'

    def get_imdbPersonID(self, personID):
        """Translate a personID in a imdbID (the ID used by the IMDb
        web server; must be overridden by the subclass."""
        # XXX: for the real implementation, see the method of the
        #      subclass, somewhere under the imdb.parser package.
        raise NotImplementedError, 'override this method'

    def _searchIMDb(self, params):
        """Fetch the given search page from the IMDb akas server."""
        from imdb.parser.http import IMDbURLopener
        url = 'http://akas.imdb.com/find?%s' % params
        content = u''
        try:
            urlOpener = IMDbURLopener()
            content = urlOpener.retrieve_unicode(url)
        except (IOError, IMDbDataAccessError):
            pass
        return content

    def title2imdbID(self, title):
        """Translate a movie title (in the plain text data files format)
        to an imdbID.
        Try an Exact Primary Title search on IMDb;
        return None if it's unable to get the imdbID."""
        if not title: return None
        import urllib
        params = 'q=%s&s=pt' % str(urllib.quote_plus(title))
        content = self._searchIMDb(params)
        if not content: return None
        from imdb.parser.http.searchMovieParser import BasicMovieParser
        mparser = BasicMovieParser()
        result = mparser.parse(content)
        if not (result and result.get('data')): return None
        return result['data'][0][0]

    def name2imdbID(self, name):
        """Translate a person name in an imdbID.
        Try an Exact Primary Name search on IMDb;
        return None if it's unable to get the imdbID."""
        if not name: return None
        import urllib
        params = 'q=%s&s=pn' % str(urllib.quote_plus(name))
        content = self._searchIMDb(params)
        if not content: return None
        from imdb.parser.http.searchPersonParser import BasicPersonParser
        pparser = BasicPersonParser()
        result = pparser.parse(content)
        if not (result and result.get('data')): return None
        return result['data'][0][0]

    def get_imdbID(self, mop):
        """Return the imdbID for the given Movie or Person object."""
        imdbID = None
        if mop.accessSystem == self.accessSystem:
            as = self
        else:
            as = IMDb(mop.accessSystem)
        if isinstance(mop, Movie.Movie):
            if mop.movieID is not None:
                imdbID = as.get_imdbMovieID(mop.movieID)
            else:
                imdbID = as.title2imdbID(build_title(mop, canonical=1, ptdf=1))
        elif isinstance(mop, Person.Person):
            if mop.personID is not None:
                imdbID = as.get_imdbPersonID(mop.personID)
            else:
                imdbID = as.name2imdbID(build_name(mop, canonical=1))
        else:
            raise IMDbError, 'object ' + repr(mop) + \
                        ' is not a Movie or Person instance'
        return imdbID

    def get_imdbURL(self, mop):
        """Return the main IMDb URL for the given Movie or Person object,
        or None if unable to get it."""
        imdbID = self.get_imdbID(mop)
        if imdbID is None: return None
        if isinstance(mop, Movie.Movie):
            url_firstPart = imdbURL_movie_main
        elif isinstance(mop, Person.Person):
            url_firstPart = imdbURL_person_main
        else:
            raise IMDbError, 'object ' + repr(mop) + \
                        ' is not a Movie or Person instance'
        return url_firstPart % imdbID

    def get_special_methods(self):
        """Return the special methods defined by the subclass."""
        sm_dict = {}
        base_methods = []
        for name in dir(IMDbBase):
            member = getattr(IMDbBase, name)
            if isinstance(member, MethodType):
                base_methods.append(name)
        for name in dir(self.__class__):
            if name.startswith('_') or name in base_methods or \
                    name.startswith('get_movie_') or \
                    name.startswith('get_person_'):
                continue
            member = getattr(self.__class__, name)
            if isinstance(member, MethodType):
                sm_dict.update({name: member.__doc__})
        return sm_dict