Example #1
0
File: api.py Project: wolf1996/cp
def filmload(movie_id, rdf):
    """
        Load film
    """
    snode = None
    #movie_id = search.movie(query='Doctor Who')['results'][0]['id']
    movie_buf = tmdb.Movies(movie_id)
    movie = movie_buf.info()
    mnode = MovieNode()
    mnode.set_name(movie['original_title'])
    mnode.set_country([i['name'] for i in movie['production_countries']])
    mnode.set_genre([i['name'] for i in movie['genres']])
    mnode.set_release_year(movie['release_date'].split('-')[0])
    mnode.set_id(movie['id'])
    # print(movie.credits()['cast'][:4])
    # print(movie)
    print(mnode)
    actors = movie_buf.credits()['cast'][:4]
    actors_node = {}
    for i in actors:
        node = PersonNode()
        act = tmdb.People(i['id']).info()
        # print(act)
        node.set_name(act['name'])
        node.set_id(act['id'])
        node.set_acted(1)
        if act['place_of_birth']:
            node.set_country(FIL.findall(act['place_of_birth'])[-1])
        if act['birthday']:
            node.set_birth_year(act['birthday'].split('-')[0])
        # print(node)
        actors_node.update({node.get_id(): node})
        snode = node

    for i in movie_buf.credits()['crew']:
        if i['job'] == 'Director':
            if i['id'] in actors_node.keys():
                actors_node[i['id']].set_directed(1)
            else:
                node = PersonNode()
                act = tmdb.People(i['id']).info()
                node.set_name(act['name'])
                node.set_id(act['id'])
                node.set_directed(1)
                if act['place_of_birth']:
                    node.set_country(FIL.findall(act['place_of_birth'])[-1])
                if act['birthday']:
                    node.set_birth_year(act['birthday'].split('-')[0])
                # print(act)
                # print(node)
                actors_node.update({node.get_id(): node})
    # print(actors_node)
    mnode.add_to_rdf(rdf)
    for i in actors_node.keys():
        actors_node[i].add_to_rdf(rdf, mnode)
Example #2
0
def peoples_retrieve(uid, rdb):
    cache_manager = CacheManager(rdb, f'people-{uid}', ONE_WEEK)

    return cache_manager.get_or_set(
        tmdbsimple.People(uid).info,
        language=LANGUAGE,
        append_to_response='combined_credits,images')
Example #3
0
    def run(self, dispatcher, tracker, domain):

        #actor from user text
        actor_name = tracker.get_slot('actor')
        if actor_name == '':
            response = "Sorry, found no actor name in that sentence. Try with different wording."
            dispatcher.utter_message(response)
            return [SlotSet('actor', actor_name)]

        search = tmdb.Search()
        response = search.person(query=actor_name)

        if len(search.results) > 0:
            actor_id = search.results[0]['id']
            person = tmdb.People(actor_id)
            response = person.info()
            biography = re.split(r'(?<=\.) ', person.biography)

            response = "Birthday - " + person.birthday + "\n" \
            + "Place of birth - " + person.place_of_birth + "\n" \
            + "Biography - " + biography[0] + " " + biography[1] + " " + biography[2]
        else:
            response = "Searched for actor " + actor_name + " but found no information. Check spelling and try again."

        dispatcher.utter_message(response)
        return [SlotSet('actor', actor_name)]
Example #4
0
def get_actor_list(search_term):
    response_obj = {'status': 'success'}
    if request.method == 'GET':
        search = tmdb.Search()
        results = search.person(query=search_term)
        actor_list = []
        if results['total_results'] > 0:
            with ActorGraph(db_user, db_pass) as graph:
                for res in results['results']:
                    person_res = tmdb.People(res['id']).info()
                    if 'imdb_id' in person_res and graph.actor_id_in_db(
                            person_res['imdb_id']):
                        # if graph.actor_name_in_db(res['name']):
                        profile_path = ''
                        if 'profile_path' in person_res and person_res[
                                'profile_path'] != '' and person_res[
                                    'profile_path'] is not None:
                            profile_path = 'https://image.tmdb.org/t/p/w45' + person_res[
                                'profile_path']
                        actor_list.append({
                            'name': res['name'],
                            'tmdb_id': res['id'],
                            'imdb_id': person_res['imdb_id'],
                            'profile_path': profile_path
                        })
        response_obj['actor_list'] = actor_list

    return jsonify(response_obj)
Example #5
0
def get_actor_movies(entities):
    try:
        actor = entities['actor']
    except KeyError:
        return "Sorry, what actor is that?"

    search = tmdb.Search()
    search.person(query=actor)

    try:
        actor = tmdb.People(search.results[0]['id'])
    except (IndexError, KeyError):
        return "That's weird ... I never heard of him/her."

    movies = actor.movie_credits()['cast']

    if not movies:
        return "I don't know of any movies featuring him/her."

    random.shuffle(movies)

    return "Ok, here are some movies %s played in: %s" % (
        "he" if actor.info()['gender'] == 2 else "she",
        ", ".join('"%s" in the role of %s' % (m['title'], m['character']) for m in movies[:5])
    )
Example #6
0
def actor_in_movie(entities):
    try:
        actor, movie = entities['actor'], entities['movie']
    except KeyError:
        return "Did who play in what?"

    search = tmdb.Search()
    search.movie(query=movie)

    try:
        movie = tmdb.Movies(search.results[0]['id'])
    except (IndexError, KeyError):
        return "That's weird ... I never heard of this movie."

    search = tmdb.Search()
    search.person(query=actor)

    try:
        actor = tmdb.People(search.results[0]['id'])
    except (IndexError, KeyError):
        return "That's weird ... I never heard of this actor."

    cast = movie.credits()['cast']
    role = [a for a in cast if a['id'] == actor.info()['id']]

    if not role:
        return 'Nope, I believe "%s" didn\'t play in %s' % (actor.info()['name'], movie.info()['original_title'])

    return 'Yep, "%s" played the role of "%s" in "%s"' % (
        actor.info()['name'], role[0]['character'], movie.info()['original_title']
    )
Example #7
0
def get_profile_pic(actor_name, imdb_id):
    path_prefix = 'https://image.tmdb.org/t/p/w185'
    search = tmdb.Search()
    results = search.person(query=actor_name)
    if results['total_results'] == 0:
        return None
    elif results['total_results'] == 1:
        single_res = results['results'][0]
        if 'profile_path' not in single_res or single_res[
                'profile_path'] is None or single_res['profile_path'] == '':
            return None
        return 'https://image.tmdb.org/t/p/w185' + single_res['profile_path']
    else:
        for r in results['results']:
            actor = tmdb.People(r['id']).info()
            if 'imdb_id' in actor and actor['imdb_id'] == imdb_id:
                if 'profile_path' not in actor or actor[
                        'profile_path'] is None or actor['profile_path'] == '':
                    return None
                return path_prefix + actor['profile_path']
        # if imdb_ids don't match we just return the first profile pic we find from the name, it is usually correct
        for r in results['results']:
            if 'profile_path' in r and r['profile_path'] != '' and r[
                    'profile_path'] is not None:
                return path_prefix + r['profile_path']
    return None
Example #8
0
def get_movie_list(top):
    #movies_id = []
    if len(top_actor) <= 1:
        get_acteur_e_liste()
    indice = randint(0, top - 1)
    #print indice
    #print len(top_actor)
    global actor_nom
    actor_nom = top_actor[indice]
    search = tmdb.Search()
    actor1 = search.person(query=actor_nom)
    #print len(actor1)
    while not actor1:
        actor1 = search.person(query=actor_nom)
    #print "search results: "
    #print len(actor1)
    actor_id = search.results[0]['id']
    actor = tmdb.People(actor_id)
    if not actor:
        return get_movie_list(top)
    movies_list = actor.movie_credits()
    if movies_list == None:
        return get_movie_list(top)
    if (len(movies_list['cast']) < 2):
        return get_movie_list(top)
    # list1 = get_acteur_list(movies_list[0])
    #for i in movies_list['cast']:
    #	movies_id.append(i.movieID)
    (film1, film2) = random.sample(movies_list['cast'], 2)
    #film1 = ia.get_movie(film1id)
    #film2 = ia.get_movie(film2id)
    # print film1['title']
    # print film2['title']
    return (actor, film1, film2)
Example #9
0
def get_person_credits(person_id, cast=True, crew=False):
    data = tmdbsimple.People(person_id).combined_credits(
        language=get_language())
    credits_list = []
    if cast:
        credits_list += list(_get_credits(data.get("cast", [])))
    if crew:
        credits_list += list(_get_credits(data.get("crew", [])))
    credits_list.sort(key=lambda v: v[2], reverse=True)
    return credits_list
Example #10
0
def person(request, id=None):

    per = tmdb.People(id)
    frontend = {
        "info": per.info(),
        "movie": per.movie_credits()['cast'][:15],
        "tv": per.tv_credits()['cast'][:15],
        "photos": per.images()['profiles'],
    }
    return render(request, "movies/person.html", frontend)
Example #11
0
def get_person(person_id='', query='', page=1):
    tmdb.API_KEY = TMDB_KEY

    if person_id:
        person = tmdb.People(person_id)
        crew_data = person.movie_credits()['crew']
        cast_data = person.movie_credits()['cast']
        jobs = {}

        for movie in crew_data:
            if movie['job'] not in jobs:
                jobs[movie['job']] = []

            year = ''
            try:
                if movie['release_date']:
                    year = f'({movie["release_date"][:4]})'
            except Exception:
                pass

            jobs[movie['job']].append({
                'title': movie['title'],
                'year': year,
                'id': movie['id']
            })

        if cast_data:
            jobs['Actor'] = []

            for movie in cast_data:
                year = ''
                try:
                    if movie['release_date']:
                        year = f'({movie["release_date"][:4]})'
                except Exception:
                    pass

                jobs['Actor'].append({
                    'title': movie['title'],
                    'year': year,
                    'id': movie['id']
                })

        return person.info(), jobs

    search = tmdb.Search()
    result = search.person(query=query, page=page)

    # Remove tv shows from 'known_for' list
    for person in result['results']:
        person['known_for'][:] = [
            x for x in person['known_for'] if x['media_type'] == 'movie'
        ]

    return result
Example #12
0
def person_info(id):
    person = tmdb.People(id)
    response = person.info()
    if (response["profile_path"] == "None"
            or response["profile_path"] is None):
        response[
            "profile_path"] = "https://www.theprintworks.com/wp-content/themes/psBella/assets/img/film-poster-placeholder.png"
    else:
        response[
            "profile_path"] = "https://image.tmdb.org/t/p/w220_and_h330_face" + response[
                "profile_path"]
    return response
def update_actors():
    actors = execute_select(
        "SELECT id FROM actors WHERE popularity ISNULL ORDER BY id")
    for i, actor in enumerate(actors):
        progress_bar(i, len(actors), prefix='Updating actors:')
        try:
            actor_data = tmdb.People(
                actor['id']).info(append_to_response="images")
        except requests.HTTPError:
            print(
                f"Error while updating actor with id: {actor['id']} Skipping this actor..."
            )
        else:
            insert_actor(actor_data)
Example #14
0
def api_search_by_actor(actor_id):
    people = tmdb.People(actor_id)
    response = people.movie_credits()
    result = []
    if ("cast" in response):
        for d in response["cast"]:
            print(d)
            if (d["poster_path"] == "None" or d["poster_path"] is None):
                d["poster_path"] = "https://www.theprintworks.com/wp-content/themes/psBella/assets/img/film-poster-placeholder.png"
            else:
                d["poster_path"] = "https://image.tmdb.org/t/p/w220_and_h330_face" + d[
                    "poster_path"]
            result.append(d)
    return result
Example #15
0
    def person(self, person_id):
        """Obtain a person given a TMDB person ID.

        Args:
            id: An Integer or String containing the TMDB ID.
        """
        return self._set_content_attributes(
            None,
            cache.handler(
                "person",
                page_key=person_id,
                function=tmdb.People(person_id).info,
                cache_duration=PERSON_CACHE_TIMEOUT,
                kwargs={"append_to_response": "tv_credits,movie_credits"},
            ),
        )
Example #16
0
    def info_credits(cls, tmdb, entity, crew=True):
        try:
            info = tmdb.credits(language='en')

            for tmdb_item in info['cast']:  #[:20]:
                actor = EntityActor2(site=cls.site_name)
                actor.tmdb_id = tmdb_item['id']
                is_exist = False
                for tmp in entity.actor:
                    if tmp.tmdb_id == actor.tmdb_id:
                        is_exist = True
                if is_exist:
                    continue

                actor.order = tmdb_item['order']
                actor.name_original = tmdb_item['original_name']
                if SiteUtil.is_include_hangul(actor.name_original):
                    actor.name = actor.name_ko = actor.name_original
                else:
                    people_info = tmdbsimple.People(actor.tmdb_id).info()
                    for tmp in people_info['also_known_as']:
                        if SiteUtil.is_include_hangul(tmp):
                            actor.name = actor.name_ko = tmp
                            break
                actor.role = tmdb_item['character']
                if 'profile_path' in tmdb_item and tmdb_item[
                        'profile_path'] is not None:
                    actor.image = cls.get_poster_path(
                        tmdb_item['profile_path'])
                entity.actor.append(actor)

            if crew == False:
                return

            for tmdb_item in info['crew'][:20]:
                if tmdb_item['job'] == 'Director':
                    entity.director.append(tmdb_item['original_name'])
                if tmdb_item['job'] == 'Executive Producer':
                    entity.producer.append(tmdb_item['original_name'])
                if tmdb_item['job'] == 'Producer':
                    entity.producer.append(tmdb_item['original_name'])
                if tmdb_item['job'] in ['Writer', 'Novel', 'Screenplay']:
                    entity.writer.append(tmdb_item['original_name'])
        except Exception as exception:
            logger.error('Exception:%s', exception)
            logger.error(traceback.format_exc())
Example #17
0
    def handle(self, *args, **options):
        tmdb.API_KEY = settings.SECRET_TMDB_API_KEY
        people = tmdb.People()

        curr_page = options['start']
        response = people.popular(page=curr_page)
        total_pages = response['total_pages']

        while curr_page <= total_pages:
            # logger.info('Start processing {} page'.format(curr_page))
            print('Start processing {} page'.format(curr_page))
            response = people.popular(page=curr_page)

            ids = [item['id'] for item in response['results']]
            for id in ids:
                upload_star_by_tmdb_id(id)
            curr_page += 1
def create_actors_dataframe(credits_df, save_path=None, actor_id=None):
    """Create the dataframe of actors present in the tmdb dataset.
    Parameters
    ----------
    credits_df : pandas.DataFrame
        dataframe from the file tmdb_5000_credits.csv
    save_path : str or None
        Save the dataframe to the given path if not None

    Return
    ------
    pandas.DataFrame
        DataFrame which contains information about actors in the tmdb dataset
    """
    columns_to_drop = ['also_known_as']
    actors = flatten(
        [json.loads(item) for index, item in credits_df.cast.iteritems()])

    if actor_id is not None:
        list_of_id = list(set([actor['id'] for actor in actors]))
        recover_index = list_of_id.index(actor_id)
        list_of_id = list_of_id[recover_index:]
    else:
        list_of_id = set([actor['id'] for actor in actors])
    actors.clear()

    for state, id in enumerate(list_of_id):
        try:
            actor = tmdb.People(id).info()
        except HTTPError:
            print(f'id {id} not found')
        else:
            actors.append(actor)
        if save_path is not None and state % 500 == 0:
            actors_df = pd.DataFrame(actors).set_index('id').drop(
                columns_to_drop, axis=1)
            actors_df.to_csv(save_path)

    actors_df = pd.DataFrame(actors).set_index('id').drop(columns_to_drop,
                                                          axis=1)
    if save_path is not None:
        actors_df.to_csv(save_path)
    return list_of_id
    def __init__(self, tmdb_id=None, name=None):
        tmdb.API_KEY = current_app.config["tmdb-api-key"]
        self.tmdb_id = None
        if tmdb_id:
            self.tmbd_id = tmdb_id
        elif name:
            temp = tmdb.Search().person(query=name)
            result = temp['results'][0]
            self.tmdb_id = result['id']
        if not self.tmdb_id:
            print(
                "TMDB search failed. Search type: 'person' Search string: '{}'"
                .format(name))
            raise TMDBSearchException
        person = tmdb.People(self.tmdb_id)

        self.info = person.info()
        self.movies = person.movie_credits()
        self.tv_shows = person.tv_credits()
        self.external_ids = person.external_ids()
Example #20
0
    def run(self, dispatcher, tracker, domain):
        movieResultArray = []
        movieResultFormatted = ""
        i = 0

        #actor from user text
        actor_name = tracker.get_slot('actor')
        if actor_name == '':
            response = "Sorry, found no actor name in that sentence. Try with different wording."
            dispatcher.utter_message(response)
            return [SlotSet('actor', actor_name)]

        search = tmdb.Search()
        response = search.person(query=actor_name)

        if len(search.results) > 0:
            actor_id = search.results[0]['id']

            person = tmdb.People(actor_id)
            response = person.movie_credits()
            cast = person.cast

            cast.sort(key=lambda x: x["popularity"], reverse=True)

            while (i < 5) and (i < len(person.cast)):
                myString = "    " + person.cast[i][
                    'title'] + " as " + person.cast[i]['character']
                movieResultArray.append(myString)
                i += 1

            for x in movieResultArray:
                movieResultFormatted += x + "\n"

                response = search.results[0][
                    'name'] + " acts in movies:\n" + movieResultFormatted
        else:
            response = "Searched for movies with " + actor_name + " but found no information. Check spelling and try again."

        dispatcher.utter_message(response)
        return [SlotSet('actor', actor_name)]
Example #21
0
def get_actor_info(tmdb_id):
    response_obj = {'status': 'success'}
    if request.method == 'GET':
        profile = tmdb.People(tmdb_id).info()
        with ActorGraph(db_user, db_pass) as graph:
            if profile['imdb_id'] is None or profile[
                    'imdb_id'] == '' or not graph.actor_id_in_db(
                        profile['imdb_id']):
                result = graph.guess_actor_imdb_id(profile['name'])
                response_obj['imdb_id'] = result['name_id']
            else:
                response_obj['imdb_id'] = profile['imdb_id']
            image_url = None
            if 'profile_path' in profile and profile[
                    'profile_path'] != '' and profile[
                        'profile_path'] is not None:
                image_url = 'https://image.tmdb.org/t/p/w185' + profile[
                    'profile_path']
            response_obj['img_url'] = image_url
            info = graph.get_actor_info(response_obj['imdb_id'])
            response_obj.update(info)

    return jsonify(response_obj)
Example #22
0
 def check_answer(self, guess, player):
     test = self.round[self.round_index - 1]
     if guess['media_type'] == 'movie':
         movie = tmdb.Movies(guess['id'])
         cast = [
             c['id'] for c in movie.credits()['cast']
             if c['known_for_department'] == "Acting"
         ]
         if test['id'] in cast:
             self.add_to_round(guess)
         else:
             self.scores[player].take_letter()
             self.current_player = next(self.lineup)
             self.round_over = True
     elif guess['media_type'] == 'person':
         actor = tmdb.People(guess['id'])
         credits = [c['id'] for c in actor.movie_credits()['cast']]
         if test['id'] in credits:
             self.add_to_round(guess)
         else:
             self.scores[player].take_letter()
             self.current_player = next(self.lineup)
             self.round_over = True
Example #23
0
def get_random_actor(cache_buster):
    response_obj = {'status': 'success'}
    if request.method == 'GET':
        with ActorGraph(db_user, db_pass) as graph:
            for i in range(10):
                rand = graph.get_random_actor()
                # response_obj['rand'] = rand
                search = tmdb.Search()
                results = search.person(query=rand['name'])
                if results['total_results'] == 0:
                    continue
                for r in results['results']:
                    actor = tmdb.People(r['id']).info()
                    if 'imdb_id' in actor and actor['imdb_id'] == rand[
                            'imdb_id']:
                        response_obj['rand'] = {
                            'name': rand['name'],
                            'imdb_id': rand['imdb_id'],
                            'tmdb_id': r['id']
                        }
                        break

    return jsonify(response_obj)
def getMoviesFromJob(job="Director"):

    # Cria a lista unicas de filmes
    movies_list = []
    person = tmdb.People()
    person_director = []

    # Le a equipe tecnica, separa por diretor e busca seus filmes
    with open('data/f_crew_.csv', 'r') as file:
        reader = csv.reader(file, delimiter=',')
        next(reader, None)
        for crew in reader:
            if crew[2] == job:
                people.id = crew[1]
                try:
                    credits = people.movie_credits()
                except HTTPError:
                    continue

                for cast in credits.get('cast'):
                    if cast.get('id') not in movies_list:
                        movies_list.append(cast.get('id'))
    return movies_list
    def person(self, person_id: int()):
        person = tmdb.People(person_id)
        result = person.info()

        cast = list()
        for actor in person.movie_credits()['cast']:
            cast.append(
                Cast(id=actor['id'],
                     title=actor['title'],
                     poster_path=actor['poster_path'],
                     character=actor['character']))

        crew = list()
        for c in person.movie_credits()['crew']:
            crew.append(
                Crew(id=c['id'],
                     title=c['title'],
                     job=c['job'],
                     department=c['department'],
                     poster_path=c['poster_path']))

        credits = Credits(cast=cast, crew=crew)

        return Person(id=result['id'],
                      name=result['name'],
                      imdb_id=result['imdb_id'],
                      gender=result['gender'],
                      homepage=result['homepage'],
                      profile_path=result['profile_path'],
                      also_known_as=result['also_known_as'],
                      biography=result['biography'],
                      deathday=result['deathday'],
                      birthday=result['birthday'],
                      place_of_birth=result['place_of_birth'],
                      popularity=result['popularity'],
                      credits=credits)
Example #26
0
def main():
    parser = ArgumentParser()
    parser.add_argument("-i", "--movie-id", dest="movie_id", help="Movie ID to link to")
    parser.add_argument(
        "-m", "--movie-name", dest="movie_name", help="Movie name to link to"
    )
    args = parser.parse_args()

    username = os.getenv('MOVIELINKER_USER')
    password = os.getenv('MOVIELINKER_PASSWORD')
    api_key = os.getenv('MOVIELINKER_API')
    
    if username is None: 
      home = os.path.expanduser("~")
      config = configparser.ConfigParser()
      config_file = os.path.join(home, ".movielinker")

      if not os.path.isfile(config_file):
          print("No configuration file found, creating")
          username = input("What is your TMDB Username? ")
          password = input("What is your TMDB Password? ")
          api_key = input("What is your TMDB API Key? ")
          config["movielinker"] = {
              "username": username,
              "password": password,
              "api_key": api_key,
          }
          with open(config_file, "w") as configfile:
              config.write(configfile)

      config.read(os.path.join(config_file))
      username = config["movielinker"]["username"]
      password = config["movielinker"]["password"]
      api_key = config["movielinker"]["api_key"]

    tmdb.API_KEY = api_key

    auth = tmdb.Authentication()
    response = auth.token_new()

    kwargs = {
        "request_token": auth.request_token,
        "username": username,
        "password": password,
    }
    auth = tmdb.Authentication()
    response = auth.token_validate_with_login(**kwargs)

    kwargs = {"request_token": auth.request_token}
    auth = tmdb.Authentication()
    response = auth.session_new(**kwargs)
    session_id = response["session_id"]

    account = tmdb.Account(session_id)
    response = account.info()
    response = account.lists()

    print("\nWhich list contains the movies you have already seen?\n")
    index = 0
    movie_lists = []
    for l in response["results"]:
        print(index, l["name"])
        movie_lists.append({"id": l["id"], "name": l["name"]})
        index += 1
    list_index = int(input())
    list_id = movie_lists[list_index]["id"]
    a = tmdb.Lists(list_id)

    movie_id = args.movie_id

    if args.movie_name != None:
        search = tmdb.Search()
        response = search.movie(query=args.movie_name)
        index = 0
        foundMovies = []
        for s in search.results:
            foundMovies.append({"id": s["id"], "title": s["title"]})
            print(index, s["title"], s["release_date"])
            index += 1
        movie_index = int(input("\nWhich Movie ID did you mean?\n"))
        movie_id = foundMovies[movie_index]["id"]
        print("\nGetting cast list for", foundMovies[movie_index]["title"], "\n")

    movie = tmdb.Movies(movie_id)

    collaboratorList = []
    index = 0
    for c in movie.credits()["cast"]:
        collaboratorList.append({"id": c["id"], "name": c["name"]})
        print(index, c["name"])
        index += 1

    excluded_collaborator_index = int(input("\nExclude a cast member?\n"))
    excluded_collaborator = collaboratorList[excluded_collaborator_index]
    print("Excluding", excluded_collaborator["name"])

    response = movie.info()
    list_response = a.info()
    seen = set()
    [seen.add(movie["id"]) for movie in a.items]

    cache = {}
    for c in movie.credits()["cast"]:
        if c["id"] == excluded_collaborator["id"]:
            continue
        person = tmdb.People(c["id"])
        response = person.info
        for p in person.movie_credits()["cast"]:
            if p["vote_count"] < 40:
                continue
            if p["id"] in seen:
                continue
            if p["id"] in cache:
                cache[p["id"]]["collaborators"].add(c["name"])
            else:
                p["collaborators"] = {c["name"]}
                cache[p["id"]] = p

    filename = "".join(x for x in movie.title if x.isalnum()) + ".csv"
    with open(filename, "w") as csv_file:
        fields = [
            "id",
            "title",
            "collaborators",
            "vote_average",
            "vote_count",
            "release_date",
            "overview",
        ]
        writer = csv.DictWriter(csv_file, fieldnames=fields, extrasaction="ignore")
        writer.writeheader()
        for movie in sorted(
            list(cache.values()), key=lambda x: x["vote_average"], reverse=True
        ):
            writer.writerow(movie)
            # print(str(movie['id']) + ", " + movie['title'] + ", " + str(movie['collaborators']) + ", " + str(movie['vote_average']))

    print("complete")
Example #27
0
 def test_people_latest(self):
     person = tmdb.People()
     response = person.latest()
     self.assertTrue(hasattr(person, 'name'))
Example #28
0
 def test_people_changes(self):
     id = PEOPLE_ID
     person = tmdb.People(id)
     response = person.changes()
     self.assertTrue(hasattr(person, 'changes'))
Example #29
0
 def test_people_popular(self):
     person = tmdb.People()
     response = person.popular()
     self.assertTrue(hasattr(person, 'results'))
Example #30
0
 def test_people_translations(self):
     id = PEOPLE_ID
     person = tmdb.People(id)
     response = person.translations()
     self.assertTrue(hasattr(person, 'translations'))