Ejemplo n.º 1
0
    def resolveTmdbID(self, mediatype, tmdbid=None, tvdbid=None, imdbid=None):
        find = None

        if tmdbid:
            try:
                return int(tmdbid)
            except:
                self.log.error("Invalid TMDB ID provided.")
                pass

        if mediatype == MediaType.Movie:
            if imdbid:
                imdbid = "tt%s" % imdbid if not imdbid.startswith(
                    "tt") else imdbid
                find = tmdb.Find(imdbid)
                response = find.info(external_source='imdb_id')
            if find and len(find.movie_results) > 0:
                tmdbid = find.movie_results[0].get('id')
        elif mediatype == MediaType.TV:
            if imdbid:
                imdbid = "tt%s" % imdbid if not imdbid.startswith(
                    "tt") else imdbid
                find = tmdb.Find(imdbid)
                response = find.info(external_source='imdb_id')
            elif tvdbid:
                find = tmdb.Find(tvdbid)
                response = find.info(external_source='tvdb_id')
            if find and len(find.tv_results) > 0:
                tmdbid = find.tv_results[0].get('id')
        return tmdbid
Ejemplo n.º 2
0
    def save_model(self, request, obj, form, change):
        ncast = int(request.POST.get('ncast'))
        img_crop_small = int(request.POST.get('img_crop_small'))
        img_crop = int(request.POST.get('img_crop'))
        if not change:
            if 'tt' in obj.imdb: obj.imdb = obj.imdb.strip('tt')
            f = tmdb.Find('tt' + obj.imdb)
            m = f.info(external_source="imdb_id")['movie_results'][0]
            self.tmdb_movie = tmdb.Movies(m['id'])
            obj.title = m['title']
            obj.tmdb = m['id']
            obj.runtime = self.tmdb_movie.info()['runtime']
            obj.release_date = parse_date(m['release_date'])
            obj.link_title = get_short_link(obj)
            self.message_user(
                request, 'Saving imdb id tt%s as %s' % (obj.imdb, obj.title))
        super(ReviewAdmin, self).save_model(request, obj, form, change)
        if not change:
            self.cast, self.director = self.add_people(self.tmdb_movie,
                                                       request, ncast)
            for c in self.cast:
                obj.cast.add(c)
            for d in self.director:
                obj.director.add(d)
        if change and ncast > len(obj.cast.all()):
            if 'tt' in obj.imdb: obj.imdb = obj.imdb.strip('tt')
            f = tmdb.Find('tt' + obj.imdb)
            m = f.info(external_source="imdb_id")['movie_results'][0]
            self.tmdb_movie = tmdb.Movies(m['id'])
            self.cast, self.director = self.add_people(self.tmdb_movie,
                                                       request, ncast)
            for c in self.cast:
                if len(obj.cast.filter(tmdb=c.tmdb)) == 0:
                    obj.cast.add(c)
            for c in self.director:
                if len(obj.director.filter(tmdb=c.tmdb)) == 0:
                    obj.director.add(c)

        if change and ncast < len(obj.cast.all()):
            for i, c in enumerate(obj.cast.all()):
                if i >= ncast:
                    obj.cast.remove(c)

        if not change or 'image_small' in form.changed_data:
            if obj.image_small:
                crop_image(obj.image_small.path, home_page=True)
        if not change or 'image' in form.changed_data:
            if obj.image:
                crop_image(obj.image.path, home_page=False)
Ejemplo n.º 3
0
    def get_fav_movie_info(tconst):
        movie = {}
        mov = ia.get_movie(tconst)

        long_title = mov.get('long imdb title')
        genres = (", ".join(mov.get('genres', []))).title()
        rating = mov.get('rating', None)
        cover = None

        if posters_on_profile_page:
            find = tmdb.Find('tt{:07}'.format(int(tconst)))
            find.info(external_source='imdb_id')
            cover_path = None

            if find.movie_results:
                cover_path = find.movie_results[0].get('poster_path', None)
            elif find.tv_results:
                cover_path = find.tv_results[0].get('poster_path', None)

            if cover_path:
                cover = tmdb_img_url + cover_path

        movie = {
            'id': tconst,
            'long title': long_title,
            'rating': rating if rating else '',
            'genres': genres,
            'cover': cover if cover else ''
        }

        user_data['movies'].append(movie)
Ejemplo n.º 4
0
 def test_find_info(self):
     id = FIND_MOVIE_ID
     external_source = FIND_SOURCE
     title = FIND_TITLE
     find = tmdb.Find(id)
     response = find.info(external_source=external_source)
     self.assertEqual(find.movie_results[0]['title'], title)
Ejemplo n.º 5
0
def imdbid_to_tmdbid(imdbid):
    logger.info("Querying TMDB for IMDB id %s" % imdbid)
    movie = tmdbsimple.Find("tt" + imdbid)
    response = movie.info(external_source="imdb_id")
    movie_results_ = response["movie_results"]
    if len(movie_results_) != 1:
        logger.error("Expected 1 result but got %d" % len(movie_results_))
    tmdbid = movie_results_[0]["id"]
    logger.info("Found IMDB id %s for TMDB id %s" % (imdbid, tmdbid))
    return str(tmdbid)
Ejemplo n.º 6
0
def _find_by_imdbid(imdb_id):
    # Returns tmdb.Movies object
    try:
        tmdb_id = tmdb.Find(imdb_id).info(
            external_source='imdb_id')['movie_results'][0]['id']
        movie = _find_by_tmdbid(tmdb_id)
    except HTTPError as e:
        _handle_error(e)
        return False

    return movie
Ejemplo n.º 7
0
 def __convert_imdb(self, imdbid):
     try:
         tmdb_id = tmdb.Find(imdbid).info(external_source='imdb_id')['movie_results'][0]['id']
     except HTTPError as e:
         self._handle_error(e)
         return False
     except IndexError:
         log.warning('IMDB id not found: {}'.format(imdbid))
         self.data = None
         return False
     
     return tmdb_id
    def get_tmdb_cast(self):
        cast = {}
        external_source = 'imdb_id'
        find = tmdb.Find(f"tt{self.imdb_id}")
        resp = find.info(external_source=external_source)
        m_id = resp['movie_results'][0]['id']
        m = tmdb.Movies(m_id)

        for person in m.credits()['cast']:
            if "uncredited" not in person['character']:
                cast[person['name']] = person['character'].replace(
                    " (voice)", "")
        return cast
Ejemplo n.º 9
0
    def get_movie_data(self, slug):
        instance = Profile.objects.get(user=self.request.user)
        movie_status = self.get_movie_status(instance.watchlist,str(slug))

        imdb_id = str(slug)
        external_source = 'imdb_id'

        find = tmdb.Find('tt0'+imdb_id)
        resp = find.info(external_source=external_source)

        if not resp['movie_results']:
            find = tmdb.Find('tt00'+imdb_id)
            resp = find.info(external_source=external_source)

        if not resp['movie_results']:
            find = tmdb.Find('tt'+imdb_id)
            resp = find.info(external_source=external_source)

        id = find.movie_results[0]['id']
        movie = tmdb.Movies(id)
        movie_info = movie.info()
        
        context = {}
        context['status'] = movie_status
        context['title'] = movie_info['title']
        context['genres'] = movie_info['genres']
        context['overview'] = movie_info['overview']
        context['runtime'] = movie_info['runtime']
        context['score'] = movie_info['vote_average']

        movie_credits = movie.credits()
        context['crew'] = movie_credits['crew']
        context['director'] = [ context['crew'][i]['name'] for i in range(len(context['crew'])) if context['crew'][i]['job'] == 'Director' ]
        context['cast'] = movie_credits['cast'][:12]
        context['poster'] = "https://image.tmdb.org/t/p/w500" + movie.poster_path

        return context
Ejemplo n.º 10
0
def profile():
    if not session.get('user', None):
        return render_template('profile.html')

    user_id = db_get_userid(session['user'])
    fav_query = fav.query.filter_by(user_id=user_id).all()
    fav_tconsts = [a.tconst for a in fav_query]
    user = user_info.query.filter_by(user_id=user_id).first()

    user_data = {}
    user_data['movies'] = []
    user_data['favorite_count'] = len(fav_tconsts)
    user_data['favorite_genre'] = user.fav_genre
    user_data['recent_fav'] = user.recent_fav
    for a in fav_tconsts:
        movie = {}
        mov = ia.get_movie(a)

        long_title = mov.get('long imdb title')
        genres = (", ".join(mov.get('genres', []))).title()
        rating = mov.get('rating', None)
        cover = None

        if posters_on_profile_page:
            find = tmdb.Find('tt{:07}'.format(int(a)))
            find.info(external_source='imdb_id')
            cover_path = None

            if find.movie_results:
                cover_path = find.movie_results[0].get('poster_path', None)
            elif find.tv_results:
                cover_path = find.tv_results[0].get('poster_path', None)

            if cover_path:
                cover = tmdb_img_url + cover_path

        movie = {
            'id': a,
            'long title': long_title,
            'rating': rating if rating else '',
            'genres': genres,
            'cover': cover if cover else ''
        }

        user_data['movies'].append(movie)

    return render_template('profile.html',
                           user_data=user_data,
                           posters_on_profile_page=posters_on_profile_page)
Ejemplo n.º 11
0
def findTMDB(title, imdb_id = None):
    page = 1
    sel = 'n'
    tmdb_id = None
    year = None
    overview = None
    runtime = None
    tagline = None
    gs = []
    tmdb_title = None
    if imdb_id is not None:
        res = tmdb.Find(imdb_id).info(external_source = 'imdb_id')['movie_results']
        if len(res) > 0:
            tmdb_id, year, overview, tagline, runtime, gs, imdb_id = parseTMDB(res[0])
            tmdb_title = None
            sel = 'y'
    while sel != 'y' and page <= 5:
        res = tmdb.Search().movie(query = title, page = page)
        page += 1
        if len(res['results']) == 0: break
        for r in res['results']:
            tmdb_title = unidecode(r['title']).replace(',', '')
            if tmdb_title.lower() == title.lower():
                sel = 'y'
            elif title.lower() in tmdb_title.lower() or tmdb_title.lower() in title.lower():
                sel = input(
                    "Matching '{}' with TMDB '{}' ({})... OK? [y or n] ".format(title, tmdb_title, r['id'])
                ).lower()
            if sel == 'y':
                tmdb_id, year, overview, tagline, runtime, gs, imdb_id = parseTMDB(r)
                break
            else:
                print("Trying again...")

    if sel != 'y':
        print("Unable to find match in TMDB for '{}'".format(title))
        tmdb_title = None
        tmdb_id = tryFloat(input("What is the TMDB ID?  "), get = True)
        year = tryFloat(input("What is the year?  "), get = True)
        overview = input("What is the overview?  ")
        tagline = input("What is the tagline?  ")
        runtime = tryFloat(input("What is the runtime?  "), get = True)
        genres = input("What are the genres? (separated by commas)  ")
        gs = [x.strip() for x in genres.split(',')]
        imdb_id = input("What is the IMDB ID?  ")
    else:
        print("* MATCHED TMDB")
    return tmdb_id, year, overview, tagline, runtime, gs, imdb_id, tmdb_title
Ejemplo n.º 12
0
 def get_by_imdbid_id(imdbid) -> MovieMatchCandidate:
     try:
         results = tmdb.Find("tt" + str(imdbid)).info(
             external_source="imdb_id")['movie_results']
         logger.debug(
             "Getting TMDB movie candidates by IMDB: {}. Resuls: {}".format(
                 imdbid, results))
         if len(results) == 0:
             return None
         # Assume we don't have duplicated entries in TMDB and only one movie per imdb
         return TMDBApi._tmdb_to_movie_match_candidate(
             results[0], prefetch_genres=False)
     except BaseException as e:
         logger.warning(
             "Exception caught while searching TMDB by IMDB: {}. {}".format(
                 imdbid, e))
         return None
Ejemplo n.º 13
0
def getInfoIMDB(imdb_id):
    imdb = tmdb.Find(imdb_id)
    results = imdb.info(external_source='imdb_id')
    isTv = len(results['movie_results']) == 0
    if all(len(v) == 0 for v in results.values()):
        # print(f'ERROR: The IMDB id: {imdb_id} return nothing')
        return None
    elif not isTv:
        all_info = parseFindBasic(results, imdb_id)
        movie = tmdb.Movies(all_info['tmdb_id'])
        details = parseMovies(movie)
        all_info.update(details)
        more_info = parseMoreInfo(movie)
        all_info.update(more_info)
        mreview = getReviews(movie,all_info['tmdb_id'],imdb_id)
        return (json.dumps(all_info),mreview)
    return None
Ejemplo n.º 14
0
    def get_by_tvdb_id(self, tvdb_id):
        """Converts TVDB ID to TMDB ID.

        Args:
            id: An Integer or String containing the TMDB ID.
        """
        # TODO: Add caching
        try:
            return tmdb.Find(tvdb_id).info(external_source="tvdb_id")

        except:
            log.handler(
                "Failed to obtain content with TVDB ID " + str(tvdb_id) + "!",
                log.ERROR,
                self.__logger,
            )
            return None
Ejemplo n.º 15
0
    def __init__(self, showid, id_type, season=None, episode=None, language='en'):
        # Showinfo is a dict containing the name of the show, episode, season
        super(FetcherTmdb, self).__init__(showid, id_type, season=season, episode=episode, language=language)
        tmdb.API_KEY = FetcherTmdb.api_key
        self.tmdbconfig = tmdb.Configuration().info()
        self.definition = 'original'

        if self.id_type == 'tmdb_id':
            self._fetcherid = self.showid

        if self.id_type in ['imdb_id', 'freebase_mid', 'freebase_id', 'tvdb_id', 'tvrage_id']:
            find = tmdb.Find(self.showid)

            if self.__class__.ftype == 'tv':
                self._fetcherid = find.info(external_source=self.id_type)['tv_results'][0]['id']
            elif self.__class__.ftype == 'movie':
                self._fetcherid = find.info(external_source=self.id_type)['movie_results'][0]['id']
Ejemplo n.º 16
0
    def _retrieve_show_image_urls_from_tmdb(show, img_type, multiple=False):
        types = {
            'poster': 'posters',
            'banner': None,
            'fanart': 'backdrops',
            'poster_thumb': 'posters',
            'banner_thumb': None
        }

        if not types[img_type]:
            return [] if multiple else ""

        # get TMDB configuration info
        tmdbsimple.API_KEY = settings.TMDB_API_KEY
        config = tmdbsimple.Configuration()
        response = config.info()
        base_url = response['images']['base_url']
        sizes = response['images']['poster_sizes']

        def size_str_to_int(x):
            return float("inf") if x == 'original' else int(x[1:])

        max_size = max(sizes, key=size_str_to_int)

        try:
            results = []
            find = tmdbsimple.Find(show.indexerid)
            found = find.info(external_source='tvdb_id')
            if found['tv_results']:
                tmdb_show = tmdbsimple.TV(found['tv_results'][0]['id'])
                images = tmdb_show.images()
                if types[img_type] in images:
                    for result in images[types[img_type]]:
                        results.append("{0}{1}{2}".format(
                            base_url, max_size, result['file_path']))
                        if not multiple:
                            return results[0]
                    return results
        except Exception as error:
            logger.debug(error)

        logger.info("Could not find any " + img_type + " images on TMDB for " +
                    show.name)
Ejemplo n.º 17
0
def findTMDB(title, imdb_id = None):
    page = 1
    sel = 'n'
    tmdb_id = None
    year = None
    overview = None
    runtime = None
    tagline = None
    gs = []
    tmdb_title = None
    if imdb_id is not None:
        res = tmdb.Find(imdb_id).info(external_source = 'imdb_id')['movie_results']
        if len(res) > 0:
            tmdb_id, year, overview, tagline, runtime, gs, imdb_id = parseTMDB(res[0])
            tmdb_title = None
            sel = 'y'
    while sel != 'y' and page <= 5:
        res = tmdb.Search().movie(query = title, page = page)
        page += 1
        if len(res['results']) == 0: break
        for r in res['results']:
            tmdb_title = unidecode(r['title']).replace(',', '')
            if tmdb_title.lower() == title.lower():
                sel = 'y'
            elif title.lower() in tmdb_title.lower() or tmdb_title.lower() in title.lower():
                sel = input(
                    "Matching '{}' with TMDB '{}' ({})... OK? [y or n] ".format(title, tmdb_title, r['id'])
                ).lower()
            if sel == 'y':
                tmdb_id, year, overview, tagline, runtime, gs, imdb_id = parseTMDB(r)
                break
            else:
                print("Trying again...")

    if sel != 'y':
        print("Unable to find match in TMDB for '{}'".format(title))
        print("Genres won't be available.")
        user_genres = input("Enter genres separated by commas if you want to include manually: ")
        gs = [x.strip() for x in user_genres.split(',')]
        tmdb_title = None
    else:
        print("* MATCHED TMDB")
    return tmdb_id, year, overview, tagline, runtime, gs, imdb_id, tmdb_title
Ejemplo n.º 18
0
    def _fetch_poster(self):
        poster_filename = self._build_filepath("jpg")
        if os.path.isfile(poster_filename):
            return

        print("  * Fetching the movie poster")
        tmdb_find = tmdb.Find(self._md["id"])
        tmdb_find.info(external_source="imdb_id")

        if len(tmdb_find.movie_results) == 0:
            print("    * Unable to find movie poster for {}".format(self._md["id"]))
            return

        poster_url = r"https://image.tmdb.org/t/p/w780{}".format(tmdb_find.movie_results[0]["poster_path"])

        uo = urllib.request.urlopen(poster_url)
        with open(poster_filename, "wb") as poster_file:
            poster_file.write(uo.read())
            poster_file.close()
Ejemplo n.º 19
0
def get_tmdb_info(imdb_movie):

    find = tmdb.Find(id=imdb_movie.tconst)
    response = find.info(external_source=c.API_PARAM_EXTERNAL_SOURCES)

    results = []

    if imdb_movie.title_type.name in [TITLE_TYPE_MOVIE, TITLE_TYPE_SHORT]:
        results = response[c.API_RESPONSE_MOVIE_RESULTS]
    elif imdb_movie.title_type.name == TITLE_TYPE_SERIES:
        results = response[c.API_RESPONSE_TV_SERIES_RESULTS]

    if len(results) > 1:
        logger.info('More than one result for imdb id %s (%s)' %
                    (imdb_movie.id, response))
        return None
    elif len(results) == 0:
        return None

    return results[0]
Ejemplo n.º 20
0
    def get_by_tvdb_id(self, tvdb_id):
        """Get a show or list of shows on TMDB through a TVDB ID.

        Args:
            id: An Integer or String containing the TVDB ID.
        """
        try:
            results = cache.handler(
                "get tv by tvdb id",
                page_key=tvdb_id,
                function=tmdb.Find(tvdb_id).info,
                cache_duration=GET_BY_TVDB_ID_CACHE_TIMEOUT,
                kwargs={"external_source": "tvdb_id"},
            )
            self._set_content_attributes("tv", results["tv_results"])
            return results
        except:
            log.handler(
                "Failed to obtain content with TVDB ID " + str(tvdb_id) + "!",
                log.ERROR,
                _logger,
            )
        return None
Ejemplo n.º 21
0
    def __init__(self,
                 show,
                 season,
                 episode,
                 original=None,
                 language='en',
                 logger=None,
                 tmdbid=False):

        tmdb.API_KEY = tmdb_api_key

        if logger:
            self.log = logger
        else:
            self.log = logging.getLogger(__name__)

        if not tmdbid:
            self.log.info(
                "ID supplied is not a TMDB ID, attempting to convert")
            find = tmdb.Find(show)
            response = find.info(external_source='tvdb_id')
            try:
                new = find.tv_results[0]['id']
                self.log.info("Replacing TVDB ID %s with TMDB ID %s" %
                              (show, new))
                show = find.tv_results[0]['id']
            except:
                self.log.exception("Unable to convert TVDB to TMDB")

        for i in range(3):
            try:
                seriesquery = tmdb.TV(show)
                seasonquery = tmdb.TV_Seasons(show, season)
                episodequery = tmdb.TV_Episodes(show, season, episode)
                self.show = show
                self.showid = show
                self.season = season
                self.episode = episode
                self.rating = None
                self.HD = None
                self.original = original

                # Gather information from theTVDB
                self.showdata = seriesquery.info()
                self.seasondata = seasonquery.info()
                self.episodedata = episodequery.info()
                self.credit = episodequery.credits()

                self.show = self.showdata['name']
                self.genre = self.showdata['genres']
                self.network = self.showdata['networks']
                # self.contentrating = self.showdata['rating']

                self.title = self.episodedata['name']
                self.description = self.episodedata['overview']
                self.airdate = self.episodedata['air_date']

                # Generate XML tags for Actors/Writers/Directors
                self.xml = self.xmlTags()
                break
            except Exception as e:
                self.log.exception(
                    "Failed to connect to TVDB, trying again in 20 seconds.")
                time.sleep(20)
Ejemplo n.º 22
0
This test suite checks the methods of the Find class of tmdbsimple.

Created by Celia Oakley on 2013-11-05

:copyright: (c) 2013-2014 by Celia Oakley.
:license: GPLv3, see LICENSE for more details.
"""

# limit: 30 requests in 10 seq.

import tmdbsimple as tmdb

tmdb.API_KEY = '12345'

urlForImagePrefix = 'https://image.tmdb.org/t/p/original'
"""
Constants
"""
id = 'tt0266543'  # findet nemo
#id = 'tt123' # falsche id zum testen
external_source = 'imdb_id'

find = tmdb.Find(id)
response = find.info(external_source=external_source)
if len(find.movie_results) == 0:  #nichts gefunden
    pass
else:
    print find.movie_results
    print urlForImagePrefix + find.movie_results[0]['poster_path']
Ejemplo n.º 23
0
def get_identificator(guess, identificator, callback):
    """ returns ids for the guessed videofile """

    # get episode and season from guessed
    if guess['type'] == MediaType.episode or \
       guess['type'] == MediaType.season:
        if not identificator['season']:
            identificator['season'] = guess['season']

    if guess['type'] == MediaType.episode and \
       not identificator['episode']:
        identificator['episode'] = guess['episode']

    # get tmdb id from imdb id
    if guess['type'] == MediaType.movie and identificator['imdb']:
        info = tmdbsimple.Find(
            identificator['imdb']
        ).info(external_source='imdb_id')

        if guess['type'] == MediaType.movie:
            identificator['tmdb'] = info['movie_results'][0]['id']
            identificator['tmdb'] = callback(
                [{'title': info['movie_results'][0]['title'],
                  'description': info['movie_results'][0]['overview'],
                  'id': info['movie_results'][0]['id']}],
                guess['type'].name
            )

        elif guess['type'] == MediaType.episode:
            identificator['tmdb'] = info['tv_results'][0]['id']
            tvshow = tmdbsimple.TV(identificator['tmdb']).external_ids()
            identificator['tvdb'] = tvshow['tvdb_id']
            identificator['tmdb'] = callback(
                [{'title': info['tv_results'][0]['name'],
                  'description': info['tv_results'][0]['overview'],
                  'id': info['tv_results'][0]['id']}],
                guess['type'].name
            )

    # get tmdb id from title
    if not identificator['tmdb']:
        args = {'query': guess['title'], 'language': CONFIG['search_language']}
        if guess['type'] == MediaType.movie and guess['year']:
            args['year'] = guess['year']
        search = tmdbsimple.Search()
        if guess['type'] == MediaType.movie:
            search.movie(**args)
        elif guess['type'] == MediaType.episode:
            search.tv(**args)

        if not search.results:
            raise error.NotEnoughData("TMDb search didn't found anything.")

        if callback is None and len(search.results) == 1:
            identificator['tmdb'] = search.results[0]['id']
        else:
            # call callback function
            callback_list = []
            for result in search.results:
                if guess['type'] == MediaType.movie:
                    movie = tmdbsimple.Movies(result['id']).info(
                        language=CONFIG['search_language'])

                    callback_list.append(
                        {'title': "{0} ({1})".format(movie['title'], movie['release_date']),
                         'descprition': result['overview'],
                         'id': result['id']}
                    )
                elif guess['type'] == MediaType.episode or \
                     guess['type'] == MediaType.tvshow or \
                     guess['type'] == MediaType.season:
                    callback_list.append(
                        {'title': result['name'],
                         'descprition': result['overview'],
                         'id': result['id']}
                    )
            identificator['tmdb'] = callback(callback_list,
                                             guess['type'].name)

    # now we should have a tmdb id. get the rest of ids
    if guess['type'] == MediaType.movie and not identificator['imdb']:
        identificator['imdb'] = tmdbsimple.Movies(identificator['tmdb']).info()['imdb_id']
    elif guess['type'] == MediaType.episode:
        tvshow = tmdbsimple.TV(identificator['tmdb']).external_ids()
        identificator['imdb'] = tvshow['imdb_id']
        identificator['tvdb'] = tvshow['tvdb_id']

    return identificator
Ejemplo n.º 24
0
     original_title VARCHAR(100),
     backdrop_path VARCHAR(100),
     vote_count INT,
     adult BOOLEAN,
     vote_average DECIMAL(4,2),
     popularity DECIMAL(20,10),
     PRIMARY KEY(id)
   );
 """
   cur.execute(query)
   db.commit()
   for i in range(len(items.keys())):
       imdb_id = items.keys()[i]
       print "imdb_id = %s, %s / %s" % (imdb_id, str(i + 1),
                                        str(len(items.keys())))
       find = tmdb.Find(imdb_id)
       response = find.info(external_source='imdb_id')
       if len(find.movie_results) == 0:  #nichts gefunden
           msg = "imdb_id = %s not found at tmdb." % imdb_id
           print msg
           logging.info(msg)
       elif len(find.movie_results) == 1:  # genau ein Treffer gefunden:
           myDict = find.movie_results[0]
           myDict['imdb_id'] = imdb_id
           myDict['adult'] = 0 + (myDict['adult'] == 'True')
           # todo: rausfinden wie man das mit dem scheiss unicode macht! jetzige lsg: wenns nicht klappt nimm leeren string!
           try:
               myDict['original_title'] = db.escape_string(
                   myDict['original_title'])  #.decode('utf-8')
           except UnicodeEncodeError:
               myDict['original_title'] = ''
Ejemplo n.º 25
0
def start_process(filenames, mode):
    """
    This is the main funtion of the script
    where it does its main processing.\n
    filenames is the list of files to be processed\n
    mode = 1,2,3 or 4\n
    1 means mp4 to tagged mp4\n
    2 means mp4 with sub to subbed and tagged mp4\n
    3 means mkv to tagged mp4\n
    4 means mkv with sub to subbed and tagged mp4
    """

    for filename in filenames:
        try:
            title = filename[:-4]
            
            stream_md = collect_stream_metadata(filename)
            streams_to_process = []
            dvdsub_exists=False
            for stream in stream_md['streams']:
                if not stream['codec_name'] in sub_codec_blacklist:
                    streams_to_process.append(stream['index'])
                else:
                    dvdsub_exists=True
            
            print('\nSearching IMDb for "{}"'.format(title))
            
            imdb = Imdb()
            movie_results = []
            results = imdb.search_for_title(title)
            for result in results:
                if result['type'] == "feature":
                    movie_results.append(result)
                    
            if not movie_results:
                while not movie_results:
                    title = input('\nNo results for "' + title +
                                  '" Enter alternate/correct movie title >> ')
                    
                    results = imdb.search_for_title(title)
                    for result in results:
                        if result['type'] == "feature":
                            movie_results.append(result)
                
            # The most prominent result is the first one
            # mpr - Most Prominent Result
            mpr = movie_results[0]
            print('\nFetching data for {} ({})'.format(mpr['title'],
                                                       mpr['year']))
                                                     
            # imdb_movie is a dict of info about the movie
            imdb_movie = imdb.get_title(mpr['imdb_id'])
            
            imdb_movie_title = imdb_movie['base']['title']
            imdb_movie_year = imdb_movie['base']['year']
            imdb_movie_id = mpr['imdb_id']
                        
            
            imdb_movie_rating = imdb_movie['ratings']['rating']
            
            if not 'outline' in imdb_movie['plot']:
                imdb_movie_plot_outline = (imdb_movie['plot']['summaries'][0]
                                           ['text'])
                print("\nPlot outline does not exist. Fetching plot summary "
                        "instead.\n\n")
            else:
                imdb_movie_plot_outline = imdb_movie['plot']['outline']['text']
            
            # Composing a string to have the rating and the plot of the
            # movie which will go into the 'comment' metadata of the 
            # mp4 file.
            imdb_rating_and_plot = str('IMDb rating ['
                                       + str(float(imdb_movie_rating))
                                       + '/10] - '
                                       + imdb_movie_plot_outline)
                                       
            
            imdb_movie_genres = imdb.get_title_genres(imdb_movie_id)['genres']
            
            # Composing the 'genre' string of the movie.
            # I use ';' as a delimeter to searate the multiple genre values
            genre = ';'.join(imdb_movie_genres)
            
            
            newfilename = (imdb_movie_title
                           + ' ('
                           + str(imdb_movie_year)
                           + ').mp4')
                           
            # We don't want the characters not allowed in a filename
            newfilename = (newfilename
                           .replace(':', ' -')
                           .replace('/', ' ')
                           .replace('?', ''))

            command = ""
            stream_map = []
            for f in streams_to_process:
                stream_map.append("-map 0:{}".format(f))
            stream_map_str = ' '.join(stream_map)           
            
            

            if mode == 1:
                # it is required to rename it as its already an mp4 file that
                # wasn't proccessed by ffmpeg
                os.rename(filename, newfilename)
            if mode == 2 or mode == 4:

                command = ('ffmpeg -i "'
                           + filename
                           + '" -sub_charenc UTF-8 -i "'
                           + filename[:-4]
                           + '.srt" '
                           + stream_map_str
                           + ' -map 1 -c copy -c:s mov_text '
                             '"' + newfilename + '"')
                subprocess.run(shlex.split(command))
            if mode == 3:
                command = ('ffmpeg -i '
                           + '"' + filename + '" '
                           + stream_map_str
                           + ' -c copy -c:s mov_text '
                             '"' + newfilename + '"')
                subprocess.run(shlex.split(command))
                
            if dvdsub_exists:
                print("\nRemoved DVD Subtitles due to uncompatibility with "
                      "mp4 file format")

            # The poster is fetched from tmdb only if there is no file
            # named " filename + '.jpg' " in the working directory
            # this way user can provide their own poster image to be used
            poster_filename = filename[:-4] + '.jpg'
            if not os.path.isfile(poster_filename):
                print('\nFetching the movie poster...')
                tmdb_find = tmdb.Find(imdb_movie_id)
                tmdb_find.info(external_source = 'imdb_id')
                
                path = tmdb_find.movie_results[0]['poster_path']
                complete_path = r'https://image.tmdb.org/t/p/w780' + path
                
                uo = urllib.request.urlopen(complete_path)
                with open(poster_filename, "wb") as poster_file:
                    poster_file.write(uo.read())
                    poster_file.close()
            
            

            video = MP4(newfilename)
            with open(poster_filename, "rb") as f:
                video["covr"] = [MP4Cover(
                                    f.read(),
                                    imageformat=MP4Cover.FORMAT_JPEG)]
                video['\xa9day'] = str(imdb_movie_year)
                video['\xa9nam'] = imdb_movie_title
                video['\xa9cmt'] = imdb_rating_and_plot
                video['\xa9gen'] = genre
                print('\nAdding poster and tagging file...')

            try:
                video.save()
                #  I have encounterd this error in pevious version
                #  of script, now I handle it by removing the metadata
                #  of the file. That seems to solve the probelem
            except OverflowError:
                remove_meta_command = ('ffmpeg -i "' + newfilename
                                       + '" -codec copy -map_metadata -1 "'
                                       + newfilename[:-4] + 'new.mp4"')
                subprocess.run(shlex.split(remove_meta_command))
                video_new = MP4(newfilename[:-4] + 'new.mp4')
                with open(poster_filename, "rb") as f:
                    video_new["covr"] = [MP4Cover(
                                            f.read(),
                                            imageformat=MP4Cover.FORMAT_JPEG)]
                    video_new['\xa9day'] = str(imdb_movie_year)
                    video_new['\xa9nam'] = imdb_movie_title
                    video_new['\xa9cmt'] = imdb_rating_and_plot
                    video_new['\xa9gen'] = genre
                    print('\nAdding poster and tagging file...')

                try:
                    video_new.save()
                    if not os.path.exists('auto fixed files'):
                        os.makedirs('auto fixed files')
                    os.rename(newfilename[:-4]
                              + 'new.mp4', 'auto fixed files\\'
                              + newfilename[:-4] + '.mp4')
                    os.remove(newfilename)

                except OverflowError:
                    errored_files.append(filename
                                         + (' - Could not save even after'
                                            'striping metadata'))
                    continue

            os.remove(poster_filename)
            print('\n' + filename
                       + (' was proccesed successfuly!\n\n===================='
                          '======================================'))
        except Exception as e:
            print('\nSome error occured while processing '
                  + filename
                  + '\n\n====================================================')
            errored_files.append(filename + ' - ' + str(e))
            PrintException()
Ejemplo n.º 26
0
def info():
    movid = request.args.get('id', None)
    if not movid:
        return ('')
    else:
        mov = ia.get_movie(movid)
        movie = {}

        #collect all the relevent info in a dict 'movie'
        long_title = mov.get('long imdb title')
        title = mov.get('title')
        rating = mov.get('rating', None)
        genres = (", ".join(mov.get('genres', []))).title()
        runmin = 0
        if mov.get('runtime'):
            runmin = int(mov.get('runtime', ['0'])[0])
        runtime = "{}h {}m".format(runmin // 60, runmin % 60)

        director = ''
        writer = ''
        if mov.get('director'):
            director = mov.get('director')[0]['name']
        if mov.get('writer'):
            writer = mov.get('writer')[0]['name']

        cover = mov.get('full-size cover url', None)
        plot = mov.get('plot', [''])[0].split('::')[0]

        if enable_extra:
            find = tmdb.Find('tt{:07}'.format(int(movid)))
            find.info(external_source='imdb_id')
            if (find.movie_results and find.movie_results[0]['poster_path']
                    and find.movie_results[0]['overview']):
                cover = tmdb_img_url + find.movie_results[0]['poster_path']
                plot = find.movie_results[0]['overview']
            elif (find.tv_results and find.tv_results[0]['poster_path']
                  and find.tv_results[0]['overview']):
                cover = tmdb_img_url + find.tv_results[0]['poster_path']
                plot = find.tv_results[0]['overview']

        movie = {
            'id': mov.getID(),
            'long title': long_title,
            'title': title,
            'rating': rating if rating else '',
            'genres': genres,
            'runtime': runtime,
            'director': director,
            'writer': writer,
            'plot': plot if plot else '',
            'cover': cover if cover else ''
        }

        isfavorite = False
        if session.get('user', None):
            isfavorite = db_fav_exists(tconst=movie['id'],
                                       user_id=db_get_userid(session['user']))

        return render_template(
            "info.html", movie=movie, isfavorite=isfavorite).replace(
                '<html lang="en"',
                '<html lang="en" style="background-color:#efefef"', 1)