def tmdb_get_movies(config_path, plex, data):
    try:
        tmdb_id = re.search('.*?(\\d+)', data)
        tmdb_id = tmdb_id.group(1)
    except AttributeError:  # Bad URL Provided
        return

    t_movie = Movie()
    tmdb = Collection()
    tmdb.api_key = config_tools.TMDB(
        config_path).apikey  # Set TMDb api key for Collection
    if tmdb.api_key == "None":
        raise KeyError("Invalid TMDb API Key")
    t_movie.api_key = tmdb.api_key  # Copy same api key to Movie
    t_col = tmdb.details(tmdb_id)
    t_movs = []
    for tmovie in t_col.parts:
        t_movs.append(tmovie['id'])

    # Create dictionary of movies and their guid
    # GUIDs reference from which source Plex has pulled the metadata
    p_m_map = {}
    p_movies = plex.Library.all()
    for m in p_movies:
        guid = m.guid
        if "themoviedb://" in guid:
            guid = guid.split('themoviedb://')[1].split('?')[0]
        elif "imdb://" in guid:
            guid = guid.split('imdb://')[1].split('?')[0]
        else:
            guid = "None"
        p_m_map[m] = guid

    matched = []
    missing = []
    # We want to search for a match first to limit TMDb API calls
    # Too many rapid calls can cause a momentary block
    # If needed in future maybe add a delay after x calls to let the limit reset
    for mid in t_movs:  # For each TMBd ID in TMBd Collection
        match = False
        for m in p_m_map:  # For each movie in Plex
            if "tt" not in p_m_map[
                    m] != "None":  # If the Plex movie's guid does not start with tt
                if int(p_m_map[m]) == int(mid):
                    match = True
                    break
        if not match:
            imdb_id = t_movie.details(mid).entries['imdb_id']
            for m in p_m_map:
                if "tt" in p_m_map[m]:
                    if p_m_map[m] == imdb_id:
                        match = True
                        break
        if match:
            matched.append(m)
        else:
            missing.append(t_movie.details(mid).entries['imdb_id'])

    return matched, missing
Beispiel #2
0
def tmdb_get_metadata(config_path, data, type):
    # Instantiate TMDB objects
    tmdb_id = int(data)

    api_key = config_tools.TMDB(config_path).apikey
    language = config_tools.TMDB(config_path).language
    is_movie = config_tools.Plex(config_path).library_type == "movie"

    if type in ["overview", "poster", "backdrop"]:
        collection = Collection()
        collection.api_key = api_key
        collection.language = language
        try:
            if type == "overview":
                meta = collection.details(tmdb_id).overview
            elif type == "poster":
                meta = collection.details(tmdb_id).poster_path
            elif type == "backdrop":
                meta = collection.details(tmdb_id).backdrop_path
        except AttributeError:
            media = Movie() if is_movie else TV()
            media.api_key = api_key
            media.language = language
            try:
                if type == "overview":
                    meta = media.details(tmdb_id).overview
                elif type == "poster":
                    meta = media.details(tmdb_id).poster_path
                elif type == "backdrop":
                    meta = media.details(tmdb_id).backdrop_path
            except AttributeError:
                raise ValueError(
                    "| TMDb Error: TMBd {} ID: {} not found".format(
                        "Movie/Collection" if is_movie else "Show", tmdb_id))
    elif type in ["biography", "profile", "name"]:
        person = Person()
        person.api_key = api_key
        person.language = language
        try:
            if type == "biography":
                meta = person.details(tmdb_id).biography
            elif type == "profile":
                meta = person.details(tmdb_id).profile_path
            elif type == "name":
                meta = person.details(tmdb_id).name
        except AttributeError:
            raise ValueError(
                "| TMDb Error: TMBd Actor ID: {} not found".format(tmdb_id))
    else:
        raise RuntimeError(
            "type {} not yet supported in tmdb_get_metadata".format(type))

    if meta is None:
        raise ValueError("| TMDb Error: TMDB ID {} has no {}".format(
            tmdb_id, type))
    elif type in ["profile", "poster", "backdrop"]:
        return "https://image.tmdb.org/t/p/original" + meta
    else:
        return meta
    def __init__(self, movieId):
        self.movie = movies.loc[(movies['movieId'] == movieId)].max()

        self.title, self.year = sep_year_title(self.movie.title)
        self.id = movieId
        self.genres = self.movie.genres.split('|')
        self.tmdb_id = links.loc[(links['movieId'] == self.id)].max().tmdbId

        try:
            movie = Movie()
            details = movie.details(self.tmdb_id)
            self.title = details.title
            self.poster_url = 'http://image.tmdb.org/t/p/w500/' + details.poster_path
            self.overview = details.overview
            self.release_date = details.release_date
            self.runtime = details.runtime
            self.budget = details.budget
            self.revenue = details.revenue
            self.popularity = details.popularity
        except:
            self.poster_url = None
            self.overview = 'Not Found'
            self.release_date = None
            self.runtime = 0
            self.budget = 0
            self.revenue = 0
            self.popularity = 0
def fetch():
    projectpath = request.form['projectFilepath']
    id = request.args.get(projectpath)
    print(id)
    movie = Movie()
    m = movie.details(343611)
    url = "http://image.tmdb.org/t/p/w500/" + m.poster_path
    response = requests.get(url)
    img = Image.open(BytesIO(response.content))
    img.save('static/movie.jpg')
    return render_template("image.html")
def imdb_get_movies(config_path, plex, data):
    title_ids = data[1]
    print("| {} Movies found on IMDb".format(len(title_ids)))
    tmdb = TMDb()
    tmdb.api_key = config_tools.TMDB(config_path).apikey
    movie = Movie()
    imdb_map = {}
    matched_imdb_movies = []
    missing_imdb_movies = []
    current_length = 0
    current_count = 0
    plex_tools.create_cache(config_path)
    plex_movies = plex.Library.all()
    for m in plex_movies:
        current_count += 1
        print_display = "| Processing: {}/{} {}".format(current_count, len(plex_movies), m.title)
        print(adjust_space(current_length, print_display), end="\r")
        current_length = len(print_display)
        if 'plex://' in m.guid:
            item = m
            # Check cache for imdb_id
            imdb_id = plex_tools.query_cache(config_path, item.guid, 'imdb_id')
            if not imdb_id:
                imdb_id, tmdb_id = plex_tools.alt_id_lookup(plex, item)
                print(adjust_space(current_length, "| Cache | + | {} | {} | {} | {}".format(item.guid, imdb_id, tmdb_id, item.title)))
                plex_tools.update_cache(config_path, item.guid, imdb_id=imdb_id, tmdb_id=tmdb_id)
        elif 'themoviedb://' in m.guid:
            if not tmdb.api_key == "None":
                tmdb_id = m.guid.split('themoviedb://')[1].split('?')[0]
                tmdbapi = movie.details(tmdb_id)
                imdb_id = tmdbapi.imdb_id if hasattr(tmdbapi, 'imdb_id') else None
            else:
                imdb_id = None
        elif 'imdb://' in m.guid:
            imdb_id = m.guid.split('imdb://')[1].split('?')[0]
        else:
            imdb_id = None

        if imdb_id and imdb_id in title_ids:
            imdb_map[imdb_id] = m
        else:
            imdb_map[m.ratingKey] = m

    print(adjust_space(current_length, "| Processed {} Movies".format(len(plex_movies))))

    for imdb_id in title_ids:
        movie = imdb_map.pop(imdb_id, None)
        if movie:
            matched_imdb_movies.append(plex.Server.fetchItem(movie.ratingKey))
        else:
            missing_imdb_movies.append(imdb_id)

    return matched_imdb_movies, missing_imdb_movies
    def get_details(self):
        """
        get movie details from TMDB 
        """
        movieId = self.movieId
        movie = Movie()
        print(movie)
        m = movie.details(movieId)
        poster = m.poster_path
        image_base = 'http://image.tmdb.org/t/p/w185'
        image_url = image_base + poster

        return m.overview, image_url, m.title, m.popularity, m.release_date
Beispiel #7
0
 def search(self, submission):
     movie = Movie()
     title = submission
     if len(title) > 0:
         try:
             search = movie.search(title)
         except Exception as e:
             return
         if len(search) > 0:
             first = search[0]
             try:
                 movie = movie.details(first.id)
             except Exception as e:
                 return
             self.post(movie)
def import_movie_genre(start, end):
    mg_list = []
    movie = Movie()
    for i in range(start, end):
        try:
            genre_list = movie.details(i).genres
            for g in genre_list:
                movie_id = i
                genre_id = g['id']
                mg = DbMovieGenre(movie_id=movie_id, genre_id=genre_id)
                mg_list.append(mg)
                print(movie_id, genre_id, g['name'])
        except TMDbException:  # if this id is not exist
            pass
    return mg_list
def imdb_get_movies(config_path, plex, data):
    tmdb = TMDb()
    movie = Movie()
    tmdb.api_key = config_tools.TMDB(config_path).apikey
    imdb_url = data
    if imdb_url[-1:] == " ":
        imdb_url = imdb_url[:-1]
    imdb_map = {}
    library_language = plex.Library.language
    try:
        r = requests.get(imdb_url,
                         headers={'Accept-Language': library_language})
    except requests.exceptions.MissingSchema:
        return
    tree = html.fromstring(r.content)
    title_ids = tree.xpath("//div[contains(@class, 'lister-item-image')]"
                           "//a/img//@data-tconst")
    if title_ids:
        for m in plex.Library.all():
            if 'themoviedb://' in m.guid:
                if not tmdb.api_key == "None":
                    tmdb_id = m.guid.split('themoviedb://')[1].split('?')[0]
                    tmdbapi = movie.details(tmdb_id)
                    imdb_id = tmdbapi.imdb_id
                else:
                    imdb_id = None
            elif 'imdb://' in m.guid:
                imdb_id = m.guid.split('imdb://')[1].split('?')[0]
            else:
                imdb_id = None

            if imdb_id and imdb_id in title_ids:
                imdb_map[imdb_id] = m
            else:
                imdb_map[m.ratingKey] = m

        matched_imbd_movies = []
        missing_imdb_movies = []
        for imdb_id in title_ids:
            movie = imdb_map.pop(imdb_id, None)
            if movie:
                matched_imbd_movies.append(
                    plex.Server.fetchItem(movie.ratingKey))
            else:
                missing_imdb_movies.append(imdb_id)

        return matched_imbd_movies, missing_imdb_movies
def init():
    movieName = input("\nMovie Name?")
    tmdb = TMDb()
    tmdb.api_key = "10163a322f4558e7cc6411377702d81d"

    movie = Movie()

    try:
        search = movie.search(movieName)

        if search is not None:
            for e in search:
                movieID = e.id
                break
            else:
                movieID = None

        m = movie.details(movieID)

        initial_budget = m.budget
        revenue = m.revenue
        title = m.original_title

        print("-Full name: " + title)

        if (initial_budget is not 0):
            print("-Intial Budget: " + (str(int(initial_budget))))

        else:
            print(
                "NO INITIAL BUDGET REPORTED. DO NOT USE THIS ENTRY FOR TRAINING DATA."
            )

        if (revenue is not 0):
            print("-Revenue: " + (str(int(revenue))))

        else:
            print(
                "NO REVENUE REPORTED. DO NOT USE THIS ENTRY FOR TRAINING DATA."
            )
            exit()
    except:
        print("\nBad movie entry?")

    return title, initial_budget, revenue
def import_movie(start, end):
    movies = []
    movie = Movie()
    for i in range(start, end):
        try:
            m = movie.details(i)
            tmdb_id = int(m.id)
            imdb_id = m.imdb_id
            title = m.title
            original_title = m.original_title

            collection = str(m.belongs_to_collection)  # need to re-format
            if collection != "None":
                collection = eval(collection)
                collection = collection['name']
            language = m.original_language
            release_date = m.release_date
            if release_date == '': release_date = None
            overview = m.overview
            vote_average = m.vote_average

            country_list = eval(str(
                m.production_countries))  # need to re-format

            country = ""
            for c in country_list:
                country = country + '[' + c['name'] + ']'

            runtime = m.runtime
            poster_path = m.poster_path
            d = DbMovie(tmdb_id, imdb_id, title, original_title, collection,
                        language, release_date, overview, vote_average,
                        country, runtime, poster_path)
            print(d.tmdb_id, d.imdb_id, d.title, d.original_title,
                  d.collection, d.language, d.release_date, d.vote_average,
                  d.vote_count, d.country, d.runtime, d.poster_path)
            print(d.overview)
            movies.append(d)
        except TMDbException:  # if this id is not exist
            pass
    return movies
Beispiel #12
0
def get_detalles(id, tipo=''):
    try:
        if id == '':
            abort(404, "Post id {0} doesn't exist.".format(id))
        if tipo == '':
            abort(403)
        detalles = ""
        if tipo == "peliculas":
            movie = Movie()
            detalles = movie.details(id)
        elif tipo == "series":
            season = Season()
            detalles = season.details(id)
        elif tipo == "tv":
            tv = TV()
            detalles = tv.details(id)

        return detalles

    except Exception as e:
        raise e
Beispiel #13
0
def imdb_get_movies(data):
    imdb_url = data
    # movieLibrary = plex.library.section("Movies")
    library_language = plex.library.section("Movies").language
    r = requests.get(imdb_url, headers={'Accept-Language': library_language})
    tree = html.fromstring(r.content)
    title_name = tree.xpath(
        "//div[contains(@class, 'lister-item-content')]//h3[contains(@class, "
        "'lister-item-header')]//a/text()")
    title_years = tree.xpath(
        "//div[contains(@class, 'lister-item-content')]//h3[contains(@class, "
        "'lister-item-header')]//span[contains(@class, 'lister-item-year')]/text()"
    )
    title_ids = tree.xpath(
        "//div[contains(@class, 'lister-item-image')]//a/img//@data-tconst")
    tmdb = TMDb()
    tmdb.api_key = config['tmdb']['apikey']
    movie = Movie()
    imdb_map = {}
    matched_movies = []
    for m in plex.library.section("Movies").all():
        if 'themoviedb://' in m.guid:
            if not tmdb.api_key == "None":
                tmdb_id = m.guid.split('themoviedb://')[1].split('?')[0]
                tmdbapi = movie.details(tmdb_id)
                imdb_id = tmdbapi.imdb_id
            else:
                imdb_id = None
        elif 'imdb://' in m.guid:
            imdb_id = m.guid.split('imdb://')[1].split('?')[0]
        else:
            imdb_id = None

        if imdb_id and imdb_id in title_ids:
            imdb_map[imdb_id] = m
        else:
            imdb_map[m.ratingKey] = m
        if imdb_id in title_ids:
            matched_movies.append(m)
    return matched_movies
Beispiel #14
0
def serialize_movie_details(id):
	m = Movie()
	k = m.details(int(id))
	casts = []
	if len(k.casts["cast"])>20:
		k.casts["cast"] = k.casts["cast"][:20]
	for i in k.casts["cast"]:
		try:
			casts.append({'name':i['name'], 'character': i['character'], 'image': 'https://image.tmdb.org/t/p/w500' + i['profile_path']})
		except:
			casts.append({'name':i['name'], 'character': i['character']})
	director = ""
	for i in k.casts["crew"]:
		if i["job"] == "Director":
			director += i['name']
	genres_str = ""
	for j in k.genres:
		genres_str += j['name'] + ", "
	genres_str = genres_str[:-2]
	response = {'title':k.original_title, 'director': director, 'year': str(k.release_date)[:4], 'runtime': k.runtime,
				'genres': genres_str, 'rating' : k.vote_average, 'backdrop' : 'https://image.tmdb.org/t/p/w500' + k.backdrop_path,
				'poster':'https://image.tmdb.org/t/p/w500'+k.poster_path,'summary':k.overview, 'casts':casts}
	similar = m.similar(int(id))
	if len(similar)>10:
		similar = similar[:10]
	similar_movies = []
	for i in similar:
		if len(i['title'])>30:
			i['title'] = i['title'][:30] + "..."
		genres_str = ""
		if len(i["genre_ids"])>3:
			i["genre_ids"] = i["genre_ids"][:3]
		for j in i["genre_ids"]:
			genres_str += genres[str(j)] + ", "
		genres_str = genres_str[:-2]
		similar_movies.append({'title':i['title'], 'poster':'https://image.tmdb.org/t/p/w500'+i['poster_path'],
							   'genres':genres_str, 'id':i["id"], 'year': str(k.release_date)[:4]})
	return [response,similar_movies]
Beispiel #15
0
def get_movie_details(tmdbId, df_MovieLens):
    country, genres, budget, revenue, keywords, MLens_rating = '', '', np.NaN, np.NaN, '', np.NaN
    if tmdbId:
        movie_api = Movie()
        movie_api.wait_on_rate_limit = True
        movie_dict = movie_api.details(tmdbId).__dict__
        country_list = movie_dict['entries']['production_countries']
        if country_list:
            country = movie_dict['entries']['production_countries'][0][
                'iso_3166_1']
        genres_list = movie_dict['entries']['genres']
        genres = '/'.join([i['name'] for i in genres_list])
        budget = movie_dict['entries']['budget']
        revenue = movie_dict['entries']['revenue']
        keywords_list = movie_dict['entries']['keywords']['keywords']
        keywords = '/'.join([i['name'] for i in keywords_list])
        MLens_rating_Series = df_MovieLens[df_MovieLens['tmdbId'] ==
                                           tmdbId]['rating']
        if len(MLens_rating_Series) == 1:
            MLens_rating = float(MLens_rating_Series)
        #time.sleep(0.5) # to ensure not to exceed the rate limit of API

    return [country, genres, budget, revenue, keywords, MLens_rating, tmdbId]
Beispiel #16
0
def post_movie(api, cgi='27'):
    # Choose Genre
    cgi = random.choice(list(dict.keys()))

    # Create recommendation
    discover = Discover()
    movie = discover.discover_movies({'with_genres': cgi, 'with_original_language': 'en', 'release_date.lte': '2020-02-02', \
        'vote_average.gte': '7', 'vote_count.gte': '100', 'page': str(random.randint(1, 5))})
    rec = random.choice(movie)

    # Get IMDB ID
    movieimd = Movie()
    imd = movieimd.details(rec.id)

    # Create hashtags
    namehash = '#' + re.sub(r'\W+', '', rec.title)
    genhash = '#' + re.sub(r'\W+', '', dict[str(rec.genre_ids[0])])

    # Create post string
    tweet = '𝗧𝗶𝘁𝗹𝗲: ' + rec.title + '\n𝗚𝗲𝗻𝗿𝗲: ' + dict[str(rec.genre_ids[0])] + '\n𝗬𝗲𝗮𝗿: ' + rec.release_date[0:4] + \
        '\n𝗦𝗰𝗼𝗿𝗲: ' + str(int(rec.vote_average*10)) + "%" + '\n\nWas it worth the watch? ' + namehash + ' ' + genhash + \
        '\nhttps://www.imdb.com/title/' + imd.imdb_id

    return tweet
Beispiel #17
0
class Tmdbapi:
    tmdb = TMDb()
    tmdb.api_key = API_KEY

    def __init__(self):
        self.movie = Movie()
        self.tv = TV()

    # Movies

    # Search for a movie and find the movie's data, its director and its cast
    # Put all of that in a data holding object
    # The data is NOT LINKED TO EACH OTHER
    # This linking has to be done elsewhere by checking the database
    # For example:
    #           the movie's director property will be None, the director's id will be None, the cast's id's will be None
    # Their names need to be checked in the database first to make sure not to add them twice

    # Convert tmdbv3 API data into our own MovieSearchResult
    def tmdb_to_movie(self, moviedata) -> MovieSearchResult:
        movie = database.Movie()
        movie.tmdbId = moviedata.id
        movie.title = moviedata.title
        movie.description = moviedata.overview

        movie_credits = self.movie.credits(moviedata.id).entries

        movie.director = None

        movie_details = self.movie.details(moviedata.id).entries
        runtime = None
        genre = None

        if movie_details is not None:
            if "runtime" in movie_details.keys():
                runtime = movie_details["runtime"]
            else:
                runtime = 0

            if "genres" in movie_details.keys():
                genres = movie_details["genres"]
            else:
                genres = None

            if genres is not None and len(genres) > 0:
                genre = genres[0]["name"]
            else:
                genre = "Unknown"

        movie.runtime = runtime
        movie.genre = genre

        if hasattr(moviedata,
                   'release_date') and len(moviedata.release_date) != 0:
            movie.releaseYear = int(moviedata.release_date[0:4])
        else:
            movie.releaseYear = 0
        movie.avgRating = moviedata.vote_average

        # Director

        director = None
        director_name = None
        crew = []

        if "crew" in movie_credits.keys():
            crew = movie_credits["crew"]

        for person in crew:
            if person["job"] == "Director":
                director_name = person["name"]
                break

        if director_name is not None:
            director = database.Contributor()
            director.name = director_name

        # Cast

        cast = []
        actors = []
        if "cast" in movie_credits.keys():
            actors = movie_credits["cast"]

        for actor in actors[0:CAST_AMOUNT]:
            cast_member = database.Contributor()
            cast_member.name = actor["name"]
            cast.append(cast_member)

        output = MovieSearchResult()
        output.movie = movie
        output.director = director
        output.cast = cast

        return output

    # Search for a movie by title and duration
    def search_movie(self, query: str, duration: int) -> MovieSearchResult:
        search = self.movie.search(query)

        output = None

        for movie_data in search:
            movie = self.tmdb_to_movie(movie_data)
            if output is None:
                output = movie
            #elif abs(movie.movie.runtime - duration) < abs(output.movie.runtime - duration):
            #output = movie

        return output

    # Search multiple movies by title
    def search_movies(self, query: str,
                      max_movies: int) -> [MovieSearchResult]:
        search = self.movie.search(query)

        output = []

        for movie_data in search:
            if len(output) >= max_movies:
                break

            movie = self.tmdb_to_movie(movie_data)
            output.append(movie)

        return output

    # "Download" a movie thumbnail
    def get_poster_movie(self, tmdb_id: int) -> str:
        movie_result = self.movie.details(tmdb_id)
        poster_path = movie_result.poster_path

        if poster_path is None:
            return None

        return "https://image.tmdb.org/t/p/w500" + poster_path

    # Get similar tmdb movies
    def get_similar_tmdb_movies(self, tmdb_id: int) -> [MovieSearchResult]:
        output = []
        for moviedata in self.movie.similar(tmdb_id):
            output.append(self.tmdb_to_movie(moviedata))
            if len(output) == SIMILAR_AMOUNT:
                break
        return output

    # TV shows

    # Convert tmdbv3 API data into our own TvShowSearchResult
    def tmdb_to_tvshow(self, tvshowdata) -> TvShowSearchResult:
        tvshow = database.TvShow()
        tvshow.title = tvshowdata.name
        tvshow.tmdbId = tvshowdata.id
        tvshow.description = tvshowdata.overview

        tvshow.director = None

        tvshow_details = self.tv.details(tvshowdata.id).entries
        runtime = 0
        genre = None

        if tvshow_details is not None:
            if "episode_run_time" in tvshow_details.keys():
                runtimes = tvshow_details["episode_run_time"]
            else:
                runtimes = None

            if runtimes is not None and len(runtimes) != 0:
                runtime = runtimes[0]

            if "genres" in tvshow_details.keys():
                genres = tvshow_details["genres"]
            else:
                genres = None

            if genres is not None and len(genres) > 0:
                genre = genres[0]["name"]
            else:
                genre = "Unknown"

        tvshow.runtime = runtime
        tvshow.genre = genre

        if hasattr(tvshowdata,
                   'first_air_date') and len(tvshowdata.first_air_date) != 0:
            tvshow.releaseYear = int(tvshowdata.first_air_date[0:4])
        else:
            tvshow.releaseYear = 0

        tvshow.avgRating = tvshowdata.vote_average

        # Director

        director = None

        if "created_by" in tvshow_details.keys():
            created_by = tvshow_details["created_by"]
        else:
            created_by = None

        if created_by is not None and len(created_by) != 0:
            director = database.Contributor()
            director.name = created_by[0]["name"]

        # Cast

        cast = []
        if "credits" in tvshow_details.keys():
            if "cast" in tvshow_details["credits"].keys():
                actors = tvshow_details["credits"]["cast"]
        else:
            actors = []

        for actor in actors[0:CAST_AMOUNT]:
            cast_member = database.Contributor()
            cast_member.name = actor["name"]
            cast.append(cast_member)

        # Episodes

        episodes = []

        if "seasons" in tvshow_details.keys():
            seasons_data = tvshow_details["seasons"]
            for season_data in seasons_data:
                season_nr = season_data["season_number"]
                for episode_nr in range(1, season_data["episode_count"] + 1):
                    episode = database.Episode()
                    episode.tmdbId = None
                    episode.season = season_nr
                    episode.episode = episode_nr
                    episodes.append(episode)

        output = TvShowSearchResult()
        output.tvshow = tvshow
        output.episodes = episodes
        output.director = director
        output.cast = cast

        return output

    # Search for a tv show via the API and turn the found data into a database supported object
    def search_tvshow(self, query: str, duration: int) -> TvShowSearchResult:
        search = self.tv.search(query)

        output = None

        for tvshow_data in search:
            tvshow = self.tmdb_to_tvshow(tvshow_data)
            if output is None:
                output = tvshow
            #elif abs(tvshow.tvshow.runtime - duration) < abs(output.tvshow.runtime - duration):
            #output = tvshow

        return output

    # Search for a tv show via the API and turn the found data into a database supported object
    def search_tvshows(self, query: str,
                       max_tvshows: int) -> [TvShowSearchResult]:
        search = self.tv.search(query)

        output = []

        for tvshowdata in search:
            if len(output) >= max_tvshows:
                break

            tvshow = self.tmdb_to_tvshow(tvshowdata)
            output.append(tvshow)

        return output

    # "Download" a tv show thumbnail
    def get_poster_tv(self, tmdb_id: int) -> str:
        tv_result = self.tv.details(tmdb_id)
        poster_path = tv_result.poster_path

        if poster_path is None:
            return None

        return "https://image.tmdb.org/t/p/w500" + poster_path

    # Get the similar items of a tv show
    def get_similar_tmdb_tvshows(self, tmdb_id: int) -> [TvShowSearchResult]:
        output = []
        for tvshowdata in self.tv.similar(tmdb_id):
            output.append(self.tmdb_to_tvshow(tvshowdata))
            if len(output) == SIMILAR_AMOUNT:
                break
        return output
Beispiel #18
0
def getMovieNamePoster(movie_id):
    id = int(movie_id)
    movie = Movie()
    s = movie.details(id)
    return s.original_title, s.poster_path
Beispiel #19
0
def singleMovie(request, movie_id):

    data = {}
    id = int(movie_id)

    # Fetching all the reviews of that movie.
    reviews = ReviewMovie.objects.filter(movieid=id)

    userReviews = []
    if reviews != None:
        temp = {}
        for review in reviews:
            userReviews.append({'review': review.review, 'date': review.date, 'userid': review.userid})
        data['userReview'] = userReviews
    else:
        data['userReview'] = None

    # Checking if the logged in user has reviewed it or not.
    check = ReviewMovie.objects.filter(movieid=id).filter(userid=request.user.username)

    if check.exists():
        data['check'] = True
    else:
        data['check'] = False

    # If user send review request this part is executed.
    if request.method == 'POST':
        username = request.user.username
        text = request.POST['review']

        # calling getSentiment function to get probability and sentiment of reviews.
        prob, sen = getSentiment(text)


        r = ReviewMovie(
            userid = username,
            movieid = movie_id,
            review = request.POST['review'],
            sentiment = sen,
            probability= prob
        )
        #form.data['sentiment'], form.data['probability'] = sentiment.getsentiment(form.cleaned_data['review'])

        # Saving the review and sending a confirmation message.
        r.save()
        messages.success(request, 'Your review has been saved successfully.')
        return redirect(singleMovie, id)


    # Setting movie details
    movie = Movie()
    s = movie.details(id)

    # Arranging Movie data
    cast = []
    temp = s.casts.cast
    length = min(len(temp),20)
    for i in range(length):
        if temp[i].known_for_department == "Acting":
            cast.append({'original_name': temp[i].original_name, 'character': temp[i].character, 'photo': temp[i].profile_path})

    crew = []
    temp = s.casts.crew
    length = min(len(temp),20)
    for i in range(length):
        crew.append({'department': temp[i].department, 'name': temp[i].original_name, 'photo': temp[i].profile_path})
    del temp

    data['title'] = s.original_title
    data['description'] = s.overview
    data['release_day'] = s.release_date
    data['status'] = s.status
    data['country'] = s.production_countries[0].name
    data['runtime'] = s.runtime
    data['budget'] = s.budget
    data['revenue'] = s.revenue
    if s.trailers.youtube == []:
        data['trailer'] = 'None'
    else:
        data['trailer'] = s.trailers.youtube[0].source
    data['adult'] = s.adult
    data['poster'] = s.poster_path
    data['votes'] = getRatingMovie(movieid=id)
    data['negative'] = 100 - data['votes']
    data['cast'] = cast
    data['crew'] = crew

    context = {}
    context['data'] = data


    return render(request, 'rhub/info.html', context)
Beispiel #20
0
    def handle(self, *args, **options):

        not_added = 0
        added = 0
        mov_id = 1
        user_count = 1
        from tmdbv3api import TMDb

        tmdb = TMDb()

        tmdb.api_key = '' # api_key

        tmdb.language = 'en'
        tmdb.debug = True

        from tmdbv3api import Movie

        mov = Movie()

        #file1 = open('film/management/commands/Attributes_Imdb_test1', 'r')
        #Lines = file1.readlines()
        imdb_id_list = []
        """
        f = open("recommendedfilm")
        recommend = {}
        for i in f:
            l = i.split("\n")[0].split("\t")
            recommend[l[0]] = eval(l[1])
        """
        f = open("film/management/commands/watchedfilms")
        watchedfilms = {}
        for i in f:
            l = i.split("\n")[0].split("\t")
            watchedfilms[l[0]] = eval(l[1])
        """
        for line in Lines:
            k = line.split('\t')[0]
            imdb_id_list.append(k)
        """
        for user_id in watchedfilms.keys():

            films = watchedfilms[user_id]

            user_email = "*****@*****.**" % user_count
            try:
                auth_user = User.objects.create_user(username=user_id, email=user_email, password='******')
            except:
                my_user = User.objects.get(username=user_id)
                user_profile = UserProfile.objects.create(user=my_user, spec_id=user_id)

            printed = 'User ID %d is added' % user_count
            print(printed)
            user_count = user_count + 1

            for film in films:  # film[0] = imdb_id  ve film[1] = user_score

                imdb_id = film[0]
                user_score = Decimal(film[1])



                control_exist = Mov.objects.filter(imdb=imdb_id)

                if control_exist:
                    my_movie = Mov.objects.get(imdb=imdb_id)
                    score = Score(user=my_user, movie=my_movie, score=user_score)
                    score.save()
                    user_profile.scores.add(score)
                    user_profile.save()

                else:

                    k = mov.details(imdb_id)

                    try:
                        m = k.poster_path
                        img_path = "https://image.tmdb.org/t/p/w185%s" % m
                        big_img_path = "https://image.tmdb.org/t/p/w500%s" % m
                    except:
                        error_id = "imdb id = %s can not be added" % imdb_id
                        print(error_id)
                        not_added = not_added+1
                        continue

                    try:
                        p = k.vote_average
                        vote_average = Decimal(p)
                        vote_average = vote_average/2
                        vote_average = round(vote_average, 1)

                    except:
                        vote_average = Decimal(0.0)


                    genre_list = []

                    if k.original_title:
                        title = k.original_title

                    if k.overview:
                        overview = k.overview

                    for genre in k.genres:
                        genre_list.append(genre)

                    vid = mov.videos(imdb_id)
                    key = ""
                    if vid:
                        key = vid[0].key

                    yt_url = "https://www.youtube.com/embed/%s" % key
                    rls_date = k.release_date
                    rls_year = k.release_date.split('-')[0]



                    credits = mov.credits(imdb_id)

                    cast_list = []
                    for c in credits.cast:
                        cast_list.append(c)

                    if cast_list:
                        print(cast_list[0]['name'])

                        for c in cast_list:
                            t = c['profile_path']
                            c['profile_path'] = "https://image.tmdb.org/t/p/w342%s" % t

                    writer_list = []
                    director_list = []
                    for c in credits.crew:
                        if c['department'] == "Writing":
                            writer_list.append(c)
                        if c['department'] == "Directing" and c['job'] == "Director":
                            director_list.append(c)

                    for c in writer_list:
                        t = c['profile_path']
                        c['profile_path'] = "https://image.tmdb.org/t/p/w342%s" % t

                    for c in director_list:
                        t = c['profile_path']
                        c['profile_path'] = "https://image.tmdb.org/t/p/w342%s" % t


                    movie = Mov(year=rls_year, date=rls_date, imdb=imdb_id, title=title,
                                topic=overview,poster_url=img_path,poster_big_url=big_img_path,
                                video_url=yt_url, avg_score=vote_average)
                    try:
                        movie.save()
                    except:
                        print("There is invalid field somewhere in movie fields. So this can not be added")
                        not_added = not_added + 1
                        continue

                    adding_control = "movie_id %d is added" % mov_id
                    print(adding_control)
                    mov_id = mov_id + 1

                    for i in cast_list:
                        person_query = Person.objects.filter(id_unique = i['id'])
                        if not person_query:
                            person = Person(id_unique=i['id'], name=i['name'], portrait_url=i['profile_path'], type='Star')
                            person.save()
                            movie.starring.add(person)
                            movie.save()
                        else:
                            person = Person.objects.get(id_unique = i['id'])
                            movie.starring.add(person)
                            movie.save()

                    for i in writer_list:
                        person_query = Person.objects.filter(id_unique=i['id'])
                        if not person_query:
                            person = Person(id_unique=i['id'], name=i['name'], portrait_url=i['profile_path'], type='Writer')
                            person.save()
                            movie.writer.add(person)
                            movie.save()
                        else:
                            person = Person.objects.get(id_unique=i['id'])
                            movie.writer.add(person)
                            movie.save()

                    for i in director_list:
                        person_query = Person.objects.filter(id_unique=i['id'])
                        if not person_query:
                            person = Person(id_unique=i['id'], name=i['name'], portrait_url=i['profile_path'], type='Director')
                            person.save()
                            movie.director.add(person)
                            movie.save()
                        else:
                            person = Person.objects.get(id_unique=i['id'])
                            movie.director.add(person)
                            movie.save()

                    for i in genre_list:

                        existing_genre = Genre.objects.filter(name__exact=i['name'])
                        if not existing_genre:
                            genre = Genre(name=i['name'])
                            genre.save()
                            movie.genres.add(genre)
                            movie.save()
                        else:
                            genre = Genre.objects.get(name=i['name'])
                            movie.genres.add(genre)
                            movie.save()

                    score = Score(user=my_user, movie=movie, score=user_score)
                    score.save()
                    user_profile.scores.add(score)
                    user_profile.save()
            """
            if user_count == 6:
                break
            """
        not_added_result = 'Eklenmeyen sayisi = %d' % not_added
        print(not_added_result)
        self.stdout.write(self.style.SUCCESS('Successfully added'))
Beispiel #21
0
def main():
    movie = Movie()
    n=idTerakhir()
    
    while n > 353000: #353000 just a limit for iteration, may be changed to 1 for all movie id
        
        m = movie.details(n)
        try:
            if m==[] or m is None or m==() or m=="":
                print("Data film ini tidak ditemukan")
            else:
                id_movie=n
                attr = getattr(m, "original_title", None)
                if attr is not None:
                    judul=m.original_title
                    budget=m.budget
                    overview=m.overview
                    popularity=m.popularity
                    poster=m.poster_path
                    tglrelease=m.release_date
                    pendapatan=m.revenue
                    runtime=m.runtime
                    status = m.status
                    voteavrg = m.vote_average
                    votecount = m.vote_count
                    tagline = m.tagline
                    homepage = m.homepage                           
                    negaraproduksi = m.production_countries
                    bahasa=m.original_language
                    revenue=m.revenue
                    print("Mengambil Data Film "+judul)

                    for x in range(0,len(m.genres)):
                        insert_genre(m.genres[x]["id"],m.genres[x]["name"])
                        insert_film(id_movie,judul,overview,poster,homepage,popularity,revenue,runtime,tagline,voteavrg,votecount,m.genres[x]["id"],bahasa,1000000,1000000,1000000,1000000,"",budget)

                    xtanggal = m.release_date
                    if xtanggal!="":
                        a,b,c = xtanggal.split("-")
                        insert_waktu(a,b,c,xtanggal)
                        insert_film(id_movie,judul,overview,poster,homepage,popularity,revenue,runtime,tagline,voteavrg,votecount,1000000,bahasa,xtanggal,1000000,1000000,1000000,"",budget)
                    else:
                        print("Belum ada release data")

                    for z in range(0,len(m.production_companies)):
                        insert_companies(m.production_companies[z]["id"],m.production_companies[z]["name"],m.production_companies[z]["origin_country"],m.production_companies[z]["logo_path"])
                        insert_film(id_movie,judul,overview,poster,homepage,popularity,revenue,runtime,tagline,voteavrg,votecount,1000000,bahasa,1000000,1000000,1000000,m.production_companies[z]["id"],"",budget)
                    
                    
                    for y in range(0,len(m.production_countries)):
                        sqlprod = "insert ignore into sma_tbl_dimnegara(id_negara,nama_negara) values(%s,%s)"
                        args = (m.production_countries[y]["iso_3166_1"],m.production_countries[y]["name"])
                        cursor.execute(sqlprod, args)
                        mydb.commit()
                        insert_film(id_movie,judul,overview,poster,homepage,popularity,revenue,runtime,tagline,voteavrg,votecount,1000000,bahasa,1000000,m.production_countries[y]["iso_3166_1"],1000000,1000000,"",budget)
        
    
                    r = movie.reviews(n)
                    if r==[]:
                        print("Tidak ada data review")
                    else:
                        for h in range(0,len(r.results)):
                            dtreview = "Author: "+r.results[h]["author"]+"<br>"+r.results[h]["content"]
                            insert_film(id_movie,judul,overview,poster,homepage,popularity,revenue,runtime,tagline,voteavrg,votecount,1000000,bahasa,1000000,1000000,1000000,1000000,dtreview,budget)
    
    

                    c = movie.credits(n)
                    if c==[]:
                        print("Tidak ada data person")
                    else:
       
                        for dd in c.cast:
                            id_person   =dd["id"]
                            nama        =dd["name"]
                            job         ="Cast"
							with urllib.request.urlopen("https://api.themoviedb.org/3/person/"+str(id_person)+"?api_key=ee183266d8fc13c415cad996a43d03b1&language=en-US") as url:
                                c = json.loads(url.read().decode())
                                popularity  =c["popularity"]
                                pob         =c["place_of_birth"]
                                foto        =c["profile_path"]
                                birthday    =c["birthday"]
                                homepage    =c["homepage"]
                                biography   =c["biography"]
            
                            insert_person(id_person,nama,biography,popularity,pob,foto,job,birthday,homepage)
                            insert_film(id_movie,judul,overview,poster,homepage,popularity,revenue,runtime,tagline,voteavrg,votecount,1000000,bahasa,1000000,1000000,id_person,1000000,"",budget)
     
                    c = movie.credits(n)
                    if c==[]:
                        print("Tidak ada data person")
                    else:
                        for cc in c.crew:
                            id_person   =cc["id"]
                            nama        =cc["name"]
                            job         ="Crew"
                            with urllib.request.urlopen("https://api.themoviedb.org/3/person/"+str(id_person)+"?api_key=ee183266d8fc13c415cad996a43d03b1&language=en-US") as url:
                                c = json.loads(url.read().decode())
                                popularity  =c["popularity"]
                                pob         =c["place_of_birth"]
                                foto        =c["profile_path"]
                                birthday    =c["birthday"]
                                homepage    =c["homepage"]
                                biography   =c["biography"]
            
                            insert_person(id_person,nama,biography,popularity,pob,foto,job,birthday,homepage)
                            insert_film(id_movie,judul,overview,poster,homepage,popularity,revenue,runtime,tagline,voteavrg,votecount,1000000,bahasa,1000000,1000000,id_person,1000000,"",budget)
class ShowAPIDB():
    def __init__(self):
        self.tmdb = TMDb()
        self.tmdb.api_key = "e00b72174e4ae097af808f34a8f220fc"
        self.tv = TV()
        self.season = Season()
        self.movie = Movie()
        self.discover = Discover()

    def buscarSerie(self, nombre):
        resultado = self.tv.search(nombre)
        series = []
        for i in resultado:
            serie = Tablas.Show()
            serie.nombre = i.name
            serie.idShow = i.id
            serie.overview = i.overview
            serie.poster = i.poster_path
            serie.puntuacionIMDB = i.vote_average
            serie.tipo = 1
            series.append(serie)
        return series

    def buscarPelicula(self, nombre):
        resultado = self.movie.search(nombre)
        pelis = []
        for i in resultado:
            peli = Tablas.Show()
            peli.tipo = 0
            peli.nombre = i.title
            peli.idShow = i.id
            peli.overview = i.overview
            peli.poster = i.poster_path
            peli.puntuacionIMDB = i.vote_average
            pelis.append(peli)
        return pelis

    def buscarPeliculaPorID(self, id):
        resultado = self.movie.details(id)
        peli = Tablas.Show()
        peli.tipo = 0
        peli.nombre = resultado.title
        peli.idShow = resultado.id
        peli.overview = resultado.overview
        peli.poster = resultado.poster_path
        peli.puntuacionIMDB = resultado.vote_average
        return peli

    def buscarSeriePorID(self, id):
        i = self.tv.details(id)
        serie = Tablas.Show()
        serie.nombre = i.name
        serie.idShow = i.id
        serie.overview = i.overview
        serie.poster = i.poster_path
        serie.puntuacionIMDB = i.vote_average
        serie.tipo = 1
        return serie

    def descubrir(self):
        show = self.discover.discover_tv_shows({'sort_by': 'popularity.desc'})
        series = []
        for i in show:
            serie = Tablas.Show()
            serie.nombre = i.name
            serie.idShow = i.id
            serie.overview = i.overview
            serie.poster = i.poster_path
            serie.puntuacionIMDB = i.vote_average
            serie.tipo = 1
            series.append(serie)
        return series
Beispiel #23
0
def tmdb_get_movies(config_path, plex, plex_map, data, method):
    t_movs = []
    t_movie = Movie()
    t_movie.api_key = config_tools.TMDB(
        config_path).apikey  # Set TMDb api key for Movie
    if t_movie.api_key == "None":
        raise KeyError("Invalid TMDb API Key")

    count = 0
    if method == "tmdb_discover":
        attrs = data.copy()
        discover = Discover()
        discover.api_key = t_movie.api_key
        discover.discover_movies(attrs)
        total_pages = int(os.environ["total_pages"])
        total_results = int(os.environ["total_results"])
        limit = int(attrs.pop('limit'))
        amount = total_results if limit == 0 or total_results < limit else limit
        print("| Processing {}: {} movies".format(method, amount))
        for attr, value in attrs.items():
            print("|            {}: {}".format(attr, value))
        for x in range(total_pages):
            attrs["page"] = x + 1
            tmdb_movies = discover.discover_movies(attrs)
            for tmovie in tmdb_movies:
                count += 1
                t_movs.append(tmovie.id)
                if count == amount:
                    break
            if count == amount:
                break
    elif method in [
            "tmdb_popular", "tmdb_top_rated", "tmdb_now_playing",
            "tmdb_trending_daily", "tmdb_trending_weekly"
    ]:
        trending = Trending()
        trending.api_key = t_movie.api_key
        for x in range(int(int(data) / 20) + 1):
            if method == "tmdb_popular":
                tmdb_movies = t_movie.popular(x + 1)
            elif method == "tmdb_top_rated":
                tmdb_movies = t_movie.top_rated(x + 1)
            elif method == "tmdb_now_playing":
                tmdb_movies = t_movie.now_playing(x + 1)
            elif method == "tmdb_trending_daily":
                tmdb_movies = trending.movie_day(x + 1)
            elif method == "tmdb_trending_weekly":
                tmdb_movies = trending.movie_week(x + 1)
            for tmovie in tmdb_movies:
                count += 1
                t_movs.append(tmovie.id)
                if count == data:
                    break
            if count == data:
                break
        print("| Processing {}: {} Items".format(method, data))
    else:
        tmdb_id = int(data)
        if method == "tmdb_list":
            tmdb = List()
            tmdb.api_key = t_movie.api_key
            try:
                t_col = tmdb.details(tmdb_id)
                tmdb_name = str(t_col)
                for tmovie in t_col:
                    if tmovie.media_type == "movie":
                        t_movs.append(tmovie.id)
            except:
                raise ValueError(
                    "| Config Error: TMDb List: {} not found".format(tmdb_id))
        elif method == "tmdb_company":
            tmdb = Company()
            tmdb.api_key = t_movie.api_key
            tmdb_name = str(tmdb.details(tmdb_id))
            company_movies = tmdb.movies(tmdb_id)
            for tmovie in company_movies:
                t_movs.append(tmovie.id)
        else:
            tmdb = Collection()
            tmdb.api_key = t_movie.api_key
            t_col = tmdb.details(tmdb_id)
            tmdb_name = str(t_col)
            try:
                for tmovie in t_col.parts:
                    t_movs.append(tmovie['id'])
            except AttributeError:
                try:
                    t_movie.details(tmdb_id).imdb_id
                    tmdb_name = str(t_movie.details(tmdb_id))
                    t_movs.append(tmdb_id)
                except:
                    raise ValueError(
                        "| Config Error: TMDb ID: {} not found".format(
                            tmdb_id))
        print("| Processing {}: ({}) {}".format(method, tmdb_id, tmdb_name))

    matched = []
    missing = []
    for mid in t_movs:
        mid = str(mid)
        if mid in plex_map:
            matched.append(plex.Server.fetchItem(plex_map[mid]))
        else:
            missing.append(mid)

    return matched, missing
Beispiel #24
0
class TMDbTests(unittest.TestCase):
    def setUp(self):
        self.tmdb = TMDb()
        self.tmdb.api_key = os.environ['TMDB_API_KEY']
        self.tmdb.language = 'en'
        self.tmdb.debug = True
        self.tmdb.wait_on_rate_limit = True
        self.movie = Movie()
        self.discover = Discover()
        self.tv = TV()
        self.person = Person()
        self.collection = Collection()
        self.company = Company()
        self.season = Season()
        self.list = List()

    def test_get_tv_keywords(self):
        keywords = self.tv.keywords(1396)
        self.assertGreater(len(keywords), 0)

    def test_get_tv_reviews(self):
        reviews = self.tv.reviews(1396)
        self.assertGreater(len(reviews), 0)

    def test_get_movie_repr(self):
        search = self.movie.search("Mad Max")
        for results in search:
            print(results)

    def test_get_tv_show_repr(self):
        search_tv = self.tv.search('Breaking Bad')
        for results in search_tv:
            print(results)

    def test_get_movie(self):
        movie = self.movie.details(111)
        self.assertIsNotNone(movie)
        self.assertEqual(movie['title'], 'Scarface')
        self.assertEqual(movie['id'], 111)
        self.assertTrue('title' in  movie)
        self.assertTrue('overview' in  movie)
        self.assertTrue('id' in  movie)

    def test_get_movie_reviews(self):
        search = self.movie.search("Mad Max")
        self.assertTrue(len(search) > 0)
        first = search[0]
        reviews = self.movie.reviews(first.id)
        self.assertTrue(len(reviews) > 0)
        for review in reviews:
            self.assertTrue('id' in review))
            self.assertTrue('content' in review))

    def test_get_movie_lists(self):
        lists = self.movie.lists(111)
        self.assertTrue(len(lists) > 0)
        self.assertTrue(hasattr(lists[0], 'description'))
        self.assertTrue(hasattr(lists[0], 'name'))

    def test_get_movie_credits(self):
        credits = self.movie.credits(111)
        print(credits)
        self.assertIsNotNone(credits)

    def test_get_movie_images(self):
        images = self.movie.images(111)
        print(images)
        self.assertIsNotNone(images)

    def test_get_movie_videos(self):
        videos = self.movie.videos(111)
        self.assertTrue(len(videos) > 0)
        self.assertTrue(hasattr(videos[0], 'id'))

    def test_get_movie_recommendations(self):
        recs = self.movie.recommendations(111)
        self.assertTrue(len(recs) > 0)
        self.assertTrue(hasattr(recs[0], 'id'))

    def test_discover_movies(self):
        discover = self.discover.discover_movies({
            'primary_release_year': '2015',
            'with_genres': '28',
            'page': '1',
            'vote_average.gte': '8'

        })
Beispiel #25
0
class TMDbTests(unittest.TestCase):
    def setUp(self):
        self.tmdb = TMDb()
        self.tmdb.api_key = os.environ["TMDB_API_KEY"]
        self.tmdb.language = "en"
        self.tmdb.debug = True
        self.tmdb.wait_on_rate_limit = True
        self.movie = Movie()
        self.discover = Discover()
        self.tv = TV()
        self.person = Person()
        self.collection = Collection()
        self.company = Company()
        self.season = Season()
        self.list = List()

    def test_get_tv_keywords(self):
        keywords = self.tv.keywords(1396)
        self.assertGreater(len(keywords), 0)

    def test_get_tv_reviews(self):
        reviews = self.tv.reviews(1396)
        self.assertGreater(len(reviews), 0)

    def test_get_movie_repr(self):
        search = self.movie.search("Mad Max")
        for results in search:
            print(results)

    def test_get_tv_show_repr(self):
        search_tv = self.tv.search("Breaking Bad")
        for results in search_tv:
            print(results)

    def test_get_movie(self):
        movie = self.movie.details(111)
        self.assertIsNotNone(movie)
        self.assertEqual(movie.title, "Scarface")
        self.assertEqual(movie.id, 111)
        self.assertTrue(hasattr(movie, "title"))
        self.assertTrue(hasattr(movie, "overview"))
        self.assertTrue(hasattr(movie, "id"))

    def test_get_movie_reviews(self):
        search = self.movie.search("Mad Max")
        self.assertTrue(len(search) > 0)
        first = search[0]
        reviews = self.movie.reviews(first.id)
        self.assertTrue(len(reviews) > 0)
        for review in reviews:
            self.assertTrue(hasattr(review, "id"))
            self.assertTrue(hasattr(review, "content"))

    def test_get_movie_lists(self):
        lists = self.movie.lists(111)
        self.assertTrue(len(lists) > 0)
        self.assertTrue(hasattr(lists[0], "description"))
        self.assertTrue(hasattr(lists[0], "name"))

    def test_get_movie_credits(self):
        credits = self.movie.credits(111)
        print(credits)
        self.assertIsNotNone(credits)

    def test_get_movie_images(self):
        images = self.movie.images(111)
        print(images)
        self.assertIsNotNone(images)

    def test_get_movie_videos(self):
        videos = self.movie.videos(111)
        self.assertTrue(len(videos) > 0)
        self.assertTrue(hasattr(videos[0], "id"))

    def test_get_movie_recommendations(self):
        recs = self.movie.recommendations(111)
        self.assertTrue(len(recs) > 0)
        self.assertTrue(hasattr(recs[0], "id"))

    def test_discover_movies(self):
        discover = self.discover.discover_movies({
            "primary_release_year": "2015",
            "with_genres": "28",
            "page": "1",
            "vote_average.gte": "8",
        })

        self.assertTrue(len(discover) > 0)
        self.assertTrue(hasattr(discover[0], "id"))
        movie = discover[0]

        has_genre = False
        for genre_id in movie.genre_ids:
            if genre_id == 28:
                has_genre = True
        self.assertTrue(has_genre)

    def test_discover_tv_shows(self):
        discover = self.discover.discover_tv_shows({
            "with_genres": "16",
            "vote_average.gte": "8",
            "page": "1"
        })
        self.assertTrue(len(discover) > 0)
        self.assertTrue(hasattr(discover[0], "id"))
        movie = discover[0]
        has_genre = False
        for genre_id in movie.genre_ids:
            if genre_id == 16:
                has_genre = True
        self.assertTrue(has_genre)

    def test_get_latest_movie(self):
        videos = self.movie.latest()
        self.assertIsNotNone(videos)
        self.assertTrue(hasattr(videos, "id"))

    def test_now_playing(self):
        now_playing = self.movie.now_playing()
        self.assertTrue(len(now_playing) > 0)
        self.assertTrue(hasattr(now_playing[0], "id"))

    def test_top_rated(self):
        top_rated = self.movie.top_rated()
        self.assertTrue(len(top_rated) > 0)
        self.assertTrue(hasattr(top_rated[0], "id"))

    def test_upcoming(self):
        upcoming = self.movie.upcoming()
        self.assertTrue(len(upcoming) > 0)
        self.assertTrue(hasattr(upcoming[0], "id"))

    def test_popular(self):
        popular = self.movie.popular()
        self.assertTrue(len(popular) > 0)
        self.assertTrue(hasattr(popular[0], "id"))

    def test_search(self):
        search = self.movie.search("Mad Max")
        self.assertTrue(len(search) > 0)
        self.assertTrue(hasattr(search[0], "id"))

    def test_similar(self):
        similar = self.movie.similar(111)
        self.assertTrue(len(similar) > 0)
        self.assertTrue(hasattr(similar[0], "id"))

    def test_get_tv_show(self):
        show = self.tv.details(12)
        self.assertIsNotNone(show)
        self.assertTrue(hasattr(show, "id"))

    def test_on_the_air(self):
        show = self.tv.on_the_air()
        self.assertTrue(len(show) > 0)

    def test_airing_today(self):
        show = self.tv.on_the_air()
        self.assertTrue(len(show) > 0)

    def test_tv_videos(self):
        show = self.tv.videos(1396)
        self.assertTrue(len(show) > 0)

    def test_tv_recommendations(self):
        show = self.tv.recommendations(1396)
        self.assertTrue(len(show) > 0)

    def test_external_ids(self):
        show = self.tv.external_ids(1776)
        self.assertEqual(show["imdb_id"], "tt0488262")

    def test_get_latest_tv_show(self):
        latest_tv = self.tv.latest()
        self.assertIsNotNone(latest_tv)
        self.assertTrue(hasattr(latest_tv, "id"))

    def test_search_tv(self):
        search_tv = self.tv.search("Sunny")
        self.assertTrue(len(search_tv) > 0)
        self.assertTrue(hasattr(search_tv[0], "id"))

    def test_popular_shows(self):
        popular = self.tv.popular()
        self.assertTrue(len(popular) > 0)
        self.assertTrue(hasattr(popular[0], "id"))

    def test_top_rated_shows(self):
        top_rated = self.tv.top_rated()
        self.assertTrue(len(top_rated) > 0)
        self.assertTrue(hasattr(top_rated[0], "id"))

    def test_get_person(self):
        person = self.person.details(234)
        self.assertIsNotNone(person)
        self.assertTrue(hasattr(person, "id"))

    def test_search_person(self):
        search_person = self.person.search("Bryan")
        self.assertTrue(len(search_person) > 0)
        self.assertTrue(hasattr(search_person[0], "id"))

    def test_collection_details(self):
        c = Collection()
        details = c.details(10)
        self.assertEqual(details.name, "Star Wars Collection")
        self.assertEqual(details.id, 10)
        self.assertTrue(hasattr(details, "overview"))
        self.assertTrue(hasattr(details, "poster_path"))

    def test_collection_images(self):
        c = Collection()
        images = c.images(10)
        self.assertTrue(hasattr(images, "backdrops"))
        self.assertTrue(hasattr(images, "posters"))

    def test_popular_people(self):
        popular = self.person.popular()
        self.assertTrue(len(popular) > 0)
        first = popular[0]
        self.assertTrue(hasattr(first, "name"))
        self.assertTrue(hasattr(first, "known_for"))

    def test_latest_person(self):
        latest_person = self.person.latest()
        self.assertIsNotNone(latest_person)
        self.assertTrue(hasattr(latest_person, "name"))
        self.assertTrue(hasattr(latest_person, "id"))

    def test_person_images(self):
        images = self.person.images(11)
        self.assertIsNotNone(images)
        self.assertTrue(hasattr(images, "profiles"))
        self.assertTrue(hasattr(images, "id"))

    def test_company_details(self):
        c = self.company.details(1)
        self.assertTrue(hasattr(c, "name"))
        self.assertEqual(c.name, "Lucasfilm Ltd.")

    def test_company_movies(self):
        company = self.company.movies(1)
        self.assertTrue(len(company) > 0)
        first = company[0]
        self.assertTrue(hasattr(first, "title"))
        self.assertTrue(hasattr(first, "overview"))

    def test_config(self):
        config = Configuration()
        info = config.info()
        self.assertIsNotNone(info)
        self.assertTrue(hasattr(info, "images"))

    def test_genres(self):
        genres = Genre()
        movie_genres = genres.movie_list()
        self.assertIsNotNone(movie_genres)
        tv_genres = genres.tv_list()
        self.assertIsNotNone(tv_genres)

    def test_season(self):
        s = self.season.details(1418, 1)
        self.assertIsNotNone(s)
        self.assertEqual(s.name, "Season 1")
        self.assertEqual(s.id, 3738)
        self.assertTrue(hasattr(s, "episodes"))
        self.assertTrue(hasattr(s, "overview"))
        self.assertTrue(hasattr(s, "id"))

    def test_get_season_changes(self):
        s = self.season.changes(1418)
        self.assertIsNotNone(s)

    def test_get_season_external_ids(self):
        s = self.season.external_ids(1418, 1)
        self.assertIsNotNone(s)
        self.assertIsNotNone(s["tvdb_id"])

    def test_get_season_videos(self):
        s = self.season.videos(1418, 1)

    def test_get_season_images(self):
        s = self.season.images(1418, 1)
        for l in s:
            self.assertIsNotNone(l.width)
            self.assertIsNotNone(l.height)

    def test_get_season_credits(self):
        s = self.season.credits(1418, 1)
        for c in s:
            self.assertIsNotNone(c.name)
            self.assertIsNotNone(c.character)

    def test_get_movie_by_external_id(self):
        ex = self.movie.external(external_id="tt8155288",
                                 external_source="imdb_id")
        res = ex["movie_results"][0]
        self.assertTrue(res["title"] == "Happy Death Day 2U")

    def test_get_list(self):
        list = self.list.details(list_id="112870")
        self.assertTrue(len(list) > 10)
        self.assertTrue(hasattr(list[0], "id"))
        self.assertTrue(hasattr(list[0], "title"))

    def test_get_certifications(self):
        certifications = Certification()
        movie_certifications = certifications.movie_list()
        self.assertIsNotNone(movie_certifications)
        tv_certifications = certifications.tv_list()
        self.assertIsNotNone(tv_certifications)
Beispiel #26
0
revenue_list = []
runtime_list = []
spoken_languages_list = []
status_list = []
tagline_list = []
title_list = []
video_list = []
vote_average_list = []
vote_count_list = []

df1 = pandas.read_csv('movies.csv')
#adult = belongs_to_collection = budget = genres = homepage = id = imdb_id = original_language = original_title = overview = popularity = poster_path = production_companies = production_countries = release_date = revenue = runtime = spoken_languages = status = tagline = title = video = vote_average = vote_count = []
#for j in range(0,4):
#    for i in range(j*37,j*37+37):
for i in range(0,20):
  m = movie.details(df1[movieId][i])
  if hasattr(m,'adult'):
    adult_list.append(m.adult)
    belongs_to_collection_list.append(m.belongs_to_collection)
    budget_list.append(m.budget)
    genres_list.append(m.genres)
    homepage_list.append(m.homepage)
    id_list.append(m.id)
    imdb_id_list.append(m.imdb_id)
    original_language_list.append(m.original_language)
    original_title_list.append(m.original_title)
    overview_list.append(m.overview)
    popularity_list.append(m.popularity)
    poster_path_list.append(m.poster_path)
    production_companies_list.append(m.production_companies)
    production_countries_list.append(m.production_countries)
def tmdb_get_movies(config_path, plex, data, is_list=False):
    tmdb_id = int(data)
    t_movs = []
    t_movie = Movie()
    t_movie.api_key = config_tools.TMDB(
        config_path).apikey  # Set TMDb api key for Movie
    if t_movie.api_key == "None":
        raise KeyError("Invalid TMDb API Key")

    tmdb = List() if is_list else Collection()
    tmdb.api_key = t_movie.api_key
    t_col = tmdb.details(tmdb_id)

    if is_list:
        try:
            for tmovie in t_col:
                if tmovie.media_type == "movie":
                    t_movs.append(tmovie.id)
        except:
            raise ValueError(
                "| Config Error: TMDb List: {} not found".format(tmdb_id))
    else:
        try:
            for tmovie in t_col.parts:
                t_movs.append(tmovie['id'])
        except AttributeError:
            try:
                t_movie.details(tmdb_id).imdb_id
                t_movs.append(tmdb_id)
            except:
                raise ValueError(
                    "| Config Error: TMDb ID: {} not found".format(tmdb_id))

    # Create dictionary of movies and their guid
    # GUIDs reference from which source Plex has pulled the metadata
    p_m_map = {}
    p_movies = plex.Library.all()
    for m in p_movies:
        guid = m.guid
        if "themoviedb://" in guid:
            guid = guid.split('themoviedb://')[1].split('?')[0]
        elif "imdb://" in guid:
            guid = guid.split('imdb://')[1].split('?')[0]
        elif "plex://" in guid:
            guid = guid.split('plex://')[1].split('?')[0]
        else:
            guid = "None"
        p_m_map[m] = guid

    matched = []
    missing = []
    plex_tools.create_cache(config_path)
    # We want to search for a match first to limit TMDb API calls
    # Too many rapid calls can cause a momentary block
    # If needed in future maybe add a delay after x calls to let the limit reset
    for mid in t_movs:  # For each TMBd ID in TMBd Collection
        match = False
        for m in p_m_map:  # For each movie in Plex
            item = m
            agent_type = urlparse(m.guid).scheme.split('.')[-1]
            # Plex movie agent
            if agent_type == 'plex':
                # Check cache for tmdb_id
                tmdb_id = plex_tools.query_cache(config_path, item.guid,
                                                 'tmdb_id')
                imdb_id = plex_tools.query_cache(config_path, item.guid,
                                                 'imdb_id')
                if not tmdb_id:
                    imdb_id, tmdb_id = plex_tools.alt_id_lookup(plex, item)
                    print("| Cache | + | {} | {} | {} | {}".format(
                        item.guid, imdb_id, tmdb_id, item.title))
                    plex_tools.update_cache(config_path,
                                            item.guid,
                                            imdb_id=imdb_id,
                                            tmdb_id=tmdb_id)
                if int(tmdb_id) == int(mid):
                    match = True
                    break
            elif agent_type == 'themoviedb':
                if int(p_m_map[m]) == int(mid):
                    match = True
                    break
            elif agent_type == 'imdb':
                imdb_id = t_movie.details(mid).imdb_id
                for m in p_m_map:
                    if "tt" in p_m_map[m]:
                        if p_m_map[m] == imdb_id:
                            match = True
                            break
        if match:
            matched.append(m)
        else:
            # Duplicate TMDb call?
            missing.append(t_movie.details(mid).imdb_id)

    return matched, missing
    def run_imdb_sync():
        try:
            plex = PlexServer(PLEX_URL, PLEX_TOKEN)
        except:
            print("Whoopsie! There's an error connecting to the Plex server at: {base_url}".format(base_url=PLEX_URL))
            print("Please check that config.ini exists, and is correct.")
            print("If the URL displayed is the correct URL for your server, then your token may be incorrect.")
            print("\n")
            input("Press Enter to exit")
            sys.exit()

# Get list of movies from the Plex server
        all_movies = []
        for movie_lib in MOVIE_LIBRARIES:
            try:
                print("Retrieving a list of movies from the '{library}' library in Plex.".format(library=movie_lib))
                print("\n")
                movie_library = plex.library.section(movie_lib)
                library_language = movie_library.language  # IMDB will use language from last library in list
                all_movies.extend(movie_library.all())
            except:
                print("The '{library}' library does not exist in Plex.".format(library=movie_lib))
                print("Please check that config.ini exists, and is correct.")
                print("\n")
                input("Press Enter to exit")
                sys.exit()

# Get the requested imdb list
        print("Retrieving movies from selected IMDB list. Depending on the amount of pages selected this might take a few minutes.")
        print("\n")
        maxpages = int(PAGE_NUMBERS) + 1
        title_name = []
        title_years = []
        title_ids = []
        for i in range(1,maxpages):
            url = IMDB_URL + '?page={}'.format(i)
            r = requests.get(url, headers={'Accept-Language': library_language})
            tree = html.fromstring(r.content)
            title_name.extend(tree.xpath("//div[contains(@class, 'lister-item-content')]//h3[contains(@class, 'lister-item-header')]//a/text()"))
            title_years.extend(tree.xpath("//div[contains(@class, 'lister-item-content')]//h3[contains(@class, 'lister-item-header')]//span[contains(@class, 'lister-item-year')]/text()"))
            title_ids.extend(tree.xpath("//div[contains(@class, 'lister-item-image')]//a/img//@data-tconst"))

# Convert TMDB to IMDB ID and create a dictionary of {imdb_id: movie} 
        print("Matching IMDB IDs to Library. For large Libraries using TMDB agent this step can take a long time.")
        print("\n")
        reqcount = 0
        tmdb = TMDb()
        tmdb.api_key = parser.get('tmdb', 'apikey')
        movie = Movie()
        imdb_map = {}
        for m in all_movies:         
            if 'themoviedb://' in m.guid:
                if reqcount >= 10:
                    time.sleep(2.5)
                    reqcount = 0
                if tmdb.api_key:
                    try:
                        tmdb_id = m.guid.split('themoviedb://')[1].split('?')[0]
                        tmdbapi = movie.details(tmdb_id)
                        imdb_id = tmdbapi.imdb_id
                        reqcount += 1
                    except AttributeError:
                        imdb_id = None
                        reqcount += 1
                else:
                    imdb_id = None
            elif 'imdb://' in m.guid:
                imdb_id = m.guid.split('imdb://')[1].split('?')[0]
            else:
                imdb_id = None
            
            if imdb_id and imdb_id in title_ids:
                imdb_map[imdb_id] = m
            else:
                imdb_map[m.ratingKey] = m

# Add movies to the selected collection
        print("Adding the collection '{}' to matched movies.".format(IMDB_COLLECTION_NAME))
        print("\n")
        in_library_idx = []
        for i, imdb_id in enumerate(title_ids):
            movie = imdb_map.pop(imdb_id, None)
            if movie:
                add_collection(movie.librarySectionID, movie.ratingKey)
                in_library_idx.append(i)

# Get list of missing movies from selected list
        missing_imdb_movies = [(idx, imdb) for idx, imdb in enumerate(zip(title_ids, title_name, title_years))
                            if idx not in in_library_idx]

        return missing_imdb_movies, len(title_ids)
Beispiel #29
0
class TMDbTests(unittest.TestCase):
    def setUp(self):
        self.tmdb = TMDb()
        self.tmdb.api_key = os.environ['TMDB_API_KEY']
        self.tmdb.language = 'en'
        self.tmdb.debug = True
        self.tmdb.wait_on_rate_limit = True
        self.movie = Movie()
        self.discover = Discover()
        self.tv = TV()
        self.person = Person()
        self.collection = Collection()
        self.company = Company()
        self.season = Season()

    def test_get_movie(self):
        movie = self.movie.details(111)
        self.assertIsNotNone(movie)
        self.assertEqual(movie.title, 'Scarface')
        self.assertEqual(movie.id, 111)
        self.assertTrue(hasattr(movie, 'title'))
        self.assertTrue(hasattr(movie, 'overview'))
        self.assertTrue(hasattr(movie, 'id'))

    def test_get_movie_reviews(self):
        search = self.movie.search("Mad Max")
        self.assertTrue(len(search) > 0)
        first = search[0]
        reviews = self.movie.reviews(first.id)
        self.assertTrue(len(reviews) > 0)
        for review in reviews:
            self.assertTrue(hasattr(review, 'id'))
            self.assertTrue(hasattr(review, 'content'))

    def test_get_movie_lists(self):
        lists = self.movie.lists(111)
        self.assertTrue(len(lists) > 0)
        self.assertTrue(hasattr(lists[0], 'description'))
        self.assertTrue(hasattr(lists[0], 'name'))

    def test_get_movie_videos(self):
        videos = self.movie.videos(111)
        self.assertTrue(len(videos) > 0)
        self.assertTrue(hasattr(videos[0], 'id'))

    def test_get_movie_recommendations(self):
        recs = self.movie.recommendations(111)
        self.assertTrue(len(recs) > 0)
        self.assertTrue(hasattr(recs[0], 'id'))

    def test_discover_movies(self):
        discover = self.discover.discover_movies({
            'primary_release_year': '2015',
            'with_genres': '28',
            'page': '1',
            'vote_average.gte': '8'

        })

        self.assertTrue(len(discover) > 0)
        self.assertTrue(hasattr(discover[0], 'id'))
        movie = discover[0]

        has_genre = False
        for genre_id in movie.genre_ids:
            if genre_id == 28:
                has_genre = True
        self.assertTrue(has_genre)

    def test_discover_tv_shows(self):
        discover = self.discover.discover_tv_shows({
            'with_genres': '16',
            'vote_average.gte': '8',
            'page': '1'
        })
        self.assertTrue(len(discover) > 0)
        self.assertTrue(hasattr(discover[0], 'id'))
        movie = discover[0]
        has_genre = False
        for genre_id in movie.genre_ids:
            if genre_id == 16:
                has_genre = True
        self.assertTrue(has_genre)

    def test_get_latest_movie(self):
        videos = self.movie.latest()
        self.assertIsNotNone(videos)
        self.assertTrue(hasattr(videos, 'id'))

    def test_now_playing(self):
        now_playing = self.movie.now_playing()
        self.assertTrue(len(now_playing) > 0)
        self.assertTrue(hasattr(now_playing[0], 'id'))

    def test_top_rated(self):
        top_rated = self.movie.top_rated()
        self.assertTrue(len(top_rated) > 0)
        self.assertTrue(hasattr(top_rated[0], 'id'))

    def test_upcoming(self):
        upcoming = self.movie.upcoming()
        self.assertTrue(len(upcoming) > 0)
        self.assertTrue(hasattr(upcoming[0], 'id'))

    def test_popular(self):
        popular = self.movie.popular()
        self.assertTrue(len(popular) > 0)
        self.assertTrue(hasattr(popular[0], 'id'))

    def test_search(self):
        search = self.movie.search('Mad Max')
        self.assertTrue(len(search) > 0)
        self.assertTrue(hasattr(search[0], 'id'))

    def test_similar(self):
        similar = self.movie.similar(111)
        self.assertTrue(len(similar) > 0)
        self.assertTrue(hasattr(similar[0], 'id'))

    def test_get_tv_show(self):
        show = self.tv.details(12)
        self.assertIsNotNone(show)
        self.assertTrue(hasattr(show, 'id'))

    def test_get_latest_tv_show(self):
        latest_tv = self.tv.latest()
        self.assertIsNotNone(latest_tv)
        self.assertTrue(hasattr(latest_tv, 'id'))

    def test_search_tv(self):
        search_tv = self.tv.search('Sunny')
        self.assertTrue(len(search_tv) > 0)
        self.assertTrue(hasattr(search_tv[0], 'id'))

    def test_popular_shows(self):
        popular = self.tv.popular()
        self.assertTrue(len(popular) > 0)
        self.assertTrue(hasattr(popular[0], 'id'))

    def test_top_rated_shows(self):
        top_rated = self.tv.top_rated()
        self.assertTrue(len(top_rated) > 0)
        self.assertTrue(hasattr(top_rated[0], 'id'))

    def test_get_person(self):
        person = self.person.details(234)
        self.assertIsNotNone(person)
        self.assertTrue(hasattr(person, 'id'))

    def test_search_person(self):
        search_person = self.person.search('Bryan')
        self.assertTrue(len(search_person) > 0)
        self.assertTrue(hasattr(search_person[0], 'id'))

    def test_collection_details(self):
        c = Collection()
        details = c.details(10)
        self.assertEqual(details.name, 'Star Wars Collection')
        self.assertEqual(details.id, 10)
        self.assertTrue(hasattr(details, 'overview'))
        self.assertTrue(hasattr(details, 'poster_path'))

    def test_collection_images(self):
        c = Collection()
        images = c.images(10)
        self.assertTrue(hasattr(images, 'backdrops'))
        self.assertTrue(hasattr(images, 'posters'))

    def test_popular_people(self):
        popular = self.person.popular()
        self.assertTrue(len(popular) > 0)
        first = popular[0]
        self.assertTrue(hasattr(first, 'name'))
        self.assertTrue(hasattr(first, 'known_for'))

    def test_latest_person(self):
        latest_person = self.person.latest()
        self.assertIsNotNone(latest_person)
        self.assertTrue(hasattr(latest_person, 'name'))
        self.assertTrue(hasattr(latest_person, 'id'))

    def test_person_images(self):
        images = self.person.images(11)
        self.assertIsNotNone(images)
        self.assertTrue(hasattr(images, 'profiles'))
        self.assertTrue(hasattr(images, 'id'))

    def test_company_details(self):
        c = self.company.details(1)
        self.assertTrue(hasattr(c, 'name'))
        self.assertEqual(c.name, 'Lucasfilm')

    def test_company_movies(self):
        company = self.company.movies(1)
        self.assertTrue(len(company) > 0)
        first = company[0]
        self.assertTrue(hasattr(first, 'title'))
        self.assertTrue(hasattr(first, 'overview'))

    def test_config(self):
        config = Configuration()
        info = config.info()
        self.assertIsNotNone(info)
        self.assertTrue(hasattr(info, 'images'))

    def test_genres(self):
        genres = Genre()
        movie_genres = genres.movie_list()
        self.assertIsNotNone(movie_genres)
        tv_genres = genres.tv_list()
        self.assertIsNotNone(tv_genres)

    def test_season(self):
        s = self.season.details(1418, 1)
        self.assertIsNotNone(s)
        self.assertEqual(s.name, 'Season 1')
        self.assertEqual(s.id, 3738)
        self.assertTrue(hasattr(s, 'episodes'))
        self.assertTrue(hasattr(s, 'overview'))
        self.assertTrue(hasattr(s, 'id'))

    def test_get_season_changes(self):
        s = self.season.changes(1418, 1)
        self.assertIsNotNone(s)

    def test_get_season_external_ids(self):
        s = self.season.external_ids(1418, 1)
        self.assertIsNotNone(s)
        self.assertIsNotNone(s['tvdb_id'])

    def test_get_season_videos(self):
        s = self.season.videos(1418, 1)

    def test_get_season_images(self):
        s = self.season.images(1418, 1)
        for l in s:
            self.assertIsNotNone(l.width)
            self.assertIsNotNone(l.height)

    def test_get_season_credits(self):
        s = self.season.credits(1418, 1)
        for c in s:
            self.assertIsNotNone(c.name)
            self.assertIsNotNone(c.character)

    def test_get_movie_by_external_id(self):
        ex = self.movie.external(external_id="tt8155288", external_source="imdb_id")
        res = ex['movie_results'][0]
        self.assertTrue(res['title'] == "Happy Death Day 2U")
Beispiel #30
0
    release_date = str(p.release_date)
    popularity = str(p.popularity)
    imagenes = str(p.poster_path)

    lista_populares_titulos.append(titulos)
    lista_populares_release_date.append(release_date)
    lista_populares_popularity.append(popularity)
    lista_populares_imagenes.append(imagenes)

    w = (len(titulos))

#print(w)

#top 5 movies
#joker---------------------------
jok = movie.details(475557)
joker_title = jok.title
#joker_overview = jok.overview
joker_release_date = str(jok.release_date)
#joker_votos = str(jok.vote_count)
joker_popularity = str(jok.popularity)
joker_image = str(jok.poster_path)
#-----------------------------------------

#avengers
avengers = movie.search('Avengers: Endgame')
lista_avengers = []
for av in avengers:
    avengers_titulo = av.title
    avengers_release_date = str(av.release_date)
    avengers_popularity = str(av.popularity)
Beispiel #31
0
from tmdbv3api import TMDb, Movie

tmdb = TMDb()
tmdb.api_key = ""

movie = Movie()

m = movie.details(111)

print(m.title)
print(m.overview)
print(m.popularity)