def get_movie_info_tmdb(movie_name, search_tmdb): """ Get movie info from TMDB using movie name Parameters ----------- - movie_name : string Name of the movie - search_tmdb : tmdb.Search object tmdb instantiated Search object Returns ---------- - movie_info : dictionary dictionary containing movie info """ logging.debug('Searching movie %s in TMDB...' % movie_name) # Response from TMDB API search object response = search_tmdb.movie(query=movie_name) # Getting movie id movie_id = response['results'][0]['id'] # Getting movie info from id movie_info = tmdb.Movies(movie_id).info() logging.debug('Movie info retrieved? %s...' % (movie_info is not None)) return movie_info
def insert_movie(conn, i): # i = radarr_item filename = i["movieFile"]["path"] to_srt = Path(filename).with_suffix("") srt = "{}.{}".format(to_srt, "en.srt") movie = tmdb.Movies(i["tmdbId"]) movie.info() country_list = ", ".join([i["name"] for i in movie.production_countries]) movie.credits() dirs = [m["name"] for m in movie.crew if m["job"] == "Director"] values = ( movie.title, str(movie.original_title) if movie.original_title else movie.title, movie.release_date.split("-")[0], ", ".join(dirs), country_list, "Certified Kino", IMAGE_BASE + str(movie.poster_path) if movie.poster_path else "Unknown", IMAGE_BASE + str(movie.backdrop_path) if movie.backdrop_path else "Unknown", filename, srt, i["tmdbId"], i["overview"], movie.popularity, movie.budget, i["movieFile"]["quality"]["quality"]["name"].split("-")[0], i["imdbId"], i["movieFile"]["mediaInfo"]["runTime"], ) insert_into_table(conn, values) print("Added: {}".format(movie.title))
def movie_retrieve(uid, rdb): cache_manager = CacheManager(rdb, f'movie-{uid}', ONE_MONTH) return cache_manager.get_or_set( tmdbsimple.Movies(uid).info, language=LANGUAGE, append_to_response='credits,keywords,videos,reviews,images')
def add_collection(self, search): if search['media_type'] == 'movie': movie = tmdb.Movies(search['id']) response = movie.info() if response['belongs_to_collection'] and response[ 'belongs_to_collection'] not in self.collection: self.collection.append(response['belongs_to_collection']['id'])
def execute_parsed(self, connection, event, extra): tmdb.API_KEY = self.settings["tmdb_api_key"] id = -1 movie = " ".join(self.pargs.movie) res = tmdb.Search().movie(query=movie) if res["total_results"] > 0: id = res["results"][0]["id"] txt = "No such movie." if id != -1: movie = tmdb.Movies(id) movie_info = movie.info() txt = "\x02%s\x02" % movie_info["title"] if movie_info["title"] != movie_info["original_title"]: txt += " (%s)" % movie_info["original_title"] if movie_info["release_date"]: txt += " | \x02Released:\x02 %s" % movie_info["release_date"] if movie_info["vote_count"] > 0: txt += " | \x02Rating:\x02 %.1f/10" % movie_info["vote_average"] if movie_info["homepage"]: txt += " | \x02Homepage:\x02 %s" % movie_info["homepage"] txt += "\n" + Plugin.split(movie_info["overview"]) return txt
def AddMovie(request, id): if Movie.objects.filter(tmdbid=id).exists(): return redirect(Movie.objects.get(tmdbid=id).get_absolute_url()) movie = tmdb.Movies(id) movie.info(language="ru-RU") movie.releases() newmovie = Movie.objects.create( name=movie.title, originalname=movie.original_title, disctiption=movie.overview, release_date=datetime.strptime(movie.release_date, "%Y-%m-%d"), year=datetime.strptime(movie.release_date, "%Y-%m-%d").year, tmdbid=movie.id, imdbid=movie.imdb_id, length=movie.runtime, ) for c in movie.countries: if c['iso_3166_1'] == 'US': newmovie.UScert = c['certification'] if c['iso_3166_1'] == 'RU': newmovie.RUcert = c['certification'] newmovie.release_dateRU = datetime.strptime( c['release_date'], "%Y-%m-%d") for i in movie.genres: newmovie.tags.add(i['name']) AddPoster(newmovie, movie.poster_path) return redirect(newmovie.get_absolute_url())
def details(request, id=None): """This is a function-based view to serve the movie details for a particular list click, using tmdbsimple API calls. Params: request: request from the front-end API call id (int): id of the movie clicked on Returns: render method at the details.html endpoint with the required movie details. """ movie = tmdb.Movies(id) trailers = list( filter(lambda v: v['type'] == 'Trailer', movie.videos()['results'])) teasers = list( filter(lambda v: v['type'] == 'Teaser', movie.videos()['results'])) keywords = movie.keywords()['keywords'] from pprint import pprint pprint(movie.reviews()['results']) frontend = { "info": movie.info(), "year": movie.info()['release_date'][:4], "cast": movie.credits()['cast'][:15], "crew": movie.credits()['crew'][:15], "trailers": trailers, "teasers": teasers, "keywords": keywords, "reviews": movie.reviews()['results'], "alt": movie.alternative_titles()['titles'] } return render(request, "details.html", frontend)
def get_upcoming(**kwargs) -> List: """ Args: language: (optional) ISO 639-1 code. page: (optional) Minimum 1, maximum 1000, default 1. region: (optional) Specify a ISO 3166-1 code to filter release dates. Must be uppercase. Returns upcoming movies. Allows specifying max results to return, returns all matching results by default --> `/upcoming/20` will return first 20 """ movies = tmdb.Movies() results = [] max_results = int(kwargs['max_results']) response = movies.upcoming(language=kwargs['language'], region=kwargs['region']) for page in range(1, response['total_pages']+1): results.extend(movies.upcoming(language=kwargs['language'], region=kwargs['region'], page=page)['results']) if max_results and len(results) > max_results: results = results[:max_results] break return results
def get_popular_movies(**kwargs) -> List: """ Returns popular movies. Allows specifying max results to return, returns 1000 by default as the TMDb API does --> `/popular/20` will return top 20 Optional Args: language: (optional) ISO 639-1 code. page: (optional) Minimum 1, maximum 1000, default 1. region: (optional) Specify a ISO 3166-1 code to filter release dates. Must be uppercase. """ movies = tmdb.Movies() results = [] max_results = int(kwargs['max_results']) response = movies.popular(language=kwargs['language'], region=kwargs['region']) for page in range(1, response['total_pages']+1): results.extend( movies.popular(language=kwargs['language'], region=kwargs['region'], page=page)['results'] ) if max_results and len(results) > max_results: results = results[:max_results] break return results
def _get_movie(mid, language=None, search=False): details = None if search else 'trailers,releases,casts,' if language is not None else 'trailers,images' movie = tmdbsimple.Movies(mid) try: return movie.info(language=language, append_to_response=details) except (Timeout, RequestsConnectionError, RequestException) as ex: return _format_error_message(ex)
def run(self, dispatcher, tracker, domain): genres = "" #movie from user text movie_name = tracker.get_slot('movie') if movie_name == '': response = "Sorry, found no movie name in that sentence. Try with different wording." dispatcher.utter_message(response) return [SlotSet('movie', movie_name)] search = tmdb.Search() response = search.movie(query=movie_name) if len(search.results) > 0: movie_id = search.results[0]['id'] movie = tmdb.Movies(movie_id) response = movie.info() for x in range(0, len(movie.genres)): genres += " " + movie.genres[x]['name'] response = """{} information: title - {}, release date - {}, genres:{}, runtime - {} minutes.""".format(movie.title, movie.title, movie.release_date, genres, movie.runtime) else: response = "Searched for movie " + movie_name + " but found no information. Check spelling and try again." dispatcher.utter_message(response) return [SlotSet('movie', movie_name)]
def loaddata(year): page = totalpages = 1 omdblink = 'http://www.omdbapi.com/?i={}&plot=full&r=json&tomatoes=true' data = [] discover = tmdb.Discover() while page <= totalpages: try: response = discover.movie(year = year, page = page) totalpages = int(response['total_pages']) movies = response['results'] for m in movies: movie = tmdb.Movies(m['id']).info() req = urllib.request.urlopen(omdblink.format(movie['imdb_id'])) resp = req.read().decode('utf-8') addinfo = json.loads(resp) movie.update(addinfo) if movie['budget'] == 0: continue if movie['Response'] == 'False': continue if movie['imdbRating'] == 'N/A': continue data.append(movie) print('progress: {}/{} - {}% ({})'.format(page,totalpages, round(page/totalpages*100,2),len(data))) except Exception as e: print('An error has occurred:\n{}'.format(e)) page += 1 time.sleep(10) # because of the request rate limit print('completed!') return data
def grab_poster_tmdb(movie): response = search.movie(query=movie) id = response['results'][0]['id'] movie = tmdb.Movies(id) title = movie.info()['original_title'] title = '_'.join(title.split(' ')) os.system(strcmd)
def get_movie_genres_tmdb(movie_name, search_tmdb): """ Get movie genres from TMDB using movie name Parameters ----------- - movie_name : string Name of the movie - search_tmdb : tmdb.Search object tmdb instantiated Search object Returns ---------- - movie_genres : list of dictionaries dictionaries list containing movie genres """ logging.debug('Searching movie %s in TMDB...' % movie_name) # Response from TMDB API search object response = search_tmdb.movie(query=movie_name) # Getting movie ID movie_id = response['results'][0]['id'] # Getting movie genres from movie info movie_genres = tmdb.Movies(movie_id).info()['genres'] logging.debug('Movie genres retrieved %s...' % movie_genres) return movie_genres
def six_random_movies(): movies = [] attempt = 0 #safeguard against infinite loops while (len(movies) < 6) and (attempt < 10): num = random.randint(1, 1000) new_movie = [] try: #Trailer has to be called before calling .info() movie = tmdb.Movies(num) trailer = movie.videos()['results'][0] trailer_key = trailer['key'] trailer_site = trailer['site'] #some movies don't have trailer urls if trailer and trailer_site == 'YouTube': processed_url = youtube + trailer_key movie = movie.info() #add title first new_movie += [movie['title']] #next add description new_movie += [movie['overview']] #add poster path new_movie += [img_url + movie['poster_path']] #lastly, add youtube URL new_movie += [processed_url] except: #limited number of attempts to lower burden on TMDB server attempt += 1 #final check to ensure all information is present if len(new_movie) == 4: movies += [new_movie] return movies
def find_movie(self, movie_id): """ Find movie by id type: movie_id: int """ return tmdb.Movies(movie_id)
def get_movie_detail(tmdb_movie_id): movie = tmdb.Movies(tmdb_movie_id) movie_detail = movie.info() translations = movie.translations()['translations'] movie_detail['translations'] = translations translation = is_translation_available(movie_detail) if not translation: return None movie_detail['title'] = translation['data']['title'] videos = movie.videos()['results'] movie_detail['videos'] = videos best_video = get_best_video(movie_detail) if not bool(best_video): return None key = best_video['key'] download(key) key_video_dict = load_key_video_dict() video_input = key_video_dict.get(key, '') if not video_input: return None movie_detail['video_input'] = video_input movie_detail['subtitle'] = get_best_subtitle_or_en(key, 'zh-Hans') return movie_detail
def tmdbMovie(film, types): #Movie check from TMDb if film in types: try: n = int(types[types.index(film)-1]) except:n=0 if n == 3: film = types[types.index(film)+1] elif n == 1: return(tmdbTv(film,types)) elif n == 5: try: return((tmdbTv(types[types.index(film)+1],types))) except: pass response = search.movie(query = film) oneFilm = [] for s in search.results: ide = tm.Movies(s["id"]) try: res = ide.info() except: res = {"title":""} if res["title"].lower() == film.lower(): oneFilm.append([res["id"],res["title"], res["runtime"], res["release_date"],[x["name"] for x in res["genres"]]]) return(oneFilm)
def retrieveData(n, path): fichier = open(path, "w") cpt = 0 for i in range(1000000): if (cpt == n): return try: res = tmdb.Movies(i) movie = res.info() reviews = res.reviews() listComment = [] for elements in reviews['results']: print(elements['content']) listComment.append(elements['content']) movie["review"] = listComment jsonarray = json.dumps(movie) fichier.write(jsonarray) fichier.write("\n") cpt += 1 except Exception as err: print("not found ", err) fichier.close()
def movieDBm(identifier): data = copy.deepcopy(MOV_DATA_TEMP) try: movie = tmdb.Movies(identifier) response = movie.info() title = movie.title summary = response.get('overview') release = response.get('release_date') budget = movie.budget runtime = response.get('runtime') images = movie.images(include_image_language="en,null") poster = response.get('poster_path') backdrop = response.get('backdrop_path') try: posterLink = POSTER_BASE + poster backdropLink = BACKDROP_BASE + backdrop except: posterLink = "NONE" backdropLink = "NONE" data["Title"] = title data["Overview"] = summary data["Release"] = release data["Budget"] = budget data["Runtime"] = runtime data["Poster"] = posterLink data["Backdrop"] = backdropLink except: data["Title"] = "N/A" data["Overview"] = "N/A" data["Release"] = "N/A" data["Budget"] = "N/A" data["Runtime"] = "N/A" data["Poster"] = "/nofilm.png" data["Backdrop"] = "/nofilm.png" return data
def search_tmdb(): query = flask.request.args.get('name') search = tmdb.Search() response = search.movie(query=query) movies = search.results if not search.results: return flask.Response('Nothing found with this name', mimetype='text/html', status=404) s = movies[0] movie = tmdb.Movies(s['id']) r = movie.info() movie_vm = {} movie_vm['name'] = query movie_vm['Title'] = r.get("title") movie_vm['Release Date'] = r.get("release_date") movie_vm['Runtime'] = r.get("runtime") movie_vm['Original Language'] = r.get("original_language") movie_vm['Production Country'] = r.get("production_countries")[0]["name"] if r.get("production_countries") != [] else 'None Listed' movie_vm['Poster'] = r.get("poster_path") movie_vm['TMDB Score'] = r.get("vote_average") return json.dumps(movie_vm)
def get_more_movies(title='', year='', tmdb_id='', page=2): tmdb.API_KEY = TMDB_KEY movie_id = tmdb_id if not movie_id: search = tmdb.Search() res = search.movie(query=title, year=year, page=page) movie_id = res['results'][0]['id'] movie_result = tmdb.Movies(movie_id) if tmdb_id: # Show similar movies when movie ID es provided more_movies = movie_result.similar_movies(page=page) else: # Show more results from user's query more_movies = res results = {'movies': [], 'total_pages': more_movies['total_pages']} for i in more_movies['results']: try: year = f'({i["release_date"][:4]})' if i['release_date'] else '' results['movies'].append({ 'title': i['title'], 'year': year, 'tmdb-id': i['id'] }) except KeyError: results['movies'].append({ 'title': i['title'], 'year': '', 'tmdb-id': i['id'] }) return results
def add_to_watchlist(request): """ Adds a movie to the watchlist (this is not actually a view but it can be used in AJAX requests). """ tmdb_id = int(request.POST.get('tmdb_id')) movie = Movie.objects.filter(tmdb_id=tmdb_id) if movie.exists(): movie = movie.first() else: title = tmdb.Movies(tmdb_id).title movie = Movie(tmdb_id=tmdb_id, title=title) movie.save() watchlist_entry = WatchlistEntry.objects.filter(user=request.user, movie=movie) if watchlist_entry.exists(): return JsonResponse( {'errors': f'Watchlist entry for movie {movie} already exists!'}) WatchlistEntry(user=request.user, movie=movie).save() return JsonResponse( {'status': f'Successfully added movie \'{movie}\' to watchlist.'})
def get_data(n, genres): """ Function for search an information about films of some genre (int), (str) -> (str) """ film_dict = dict() a = tmdb.Movies().top_rated(page=n) b = a.get('results') s = '' for j in b: id = j.get('id') movie = tmdb.Movies(id) info = movie.info() gnr = info.get('genres') c = 0 for l in gnr: if l.get('name') in genres: if info.get('budget') != 0: film_dict['title'] = info.get('title') film_dict['genres'] = info.get('genres') film_dict['release_date'] = info.get('release_date') film_dict['runtime'] = info.get('runtime') film_dict['vote_average'] = info.get('vote_average') film_dict['vote_count'] = info.get('vote_count') film_dict['budget'] = info.get('budget') film_dict['popularity'] = info.get('popularity') if 'genres' in film_dict: visualisation.Visualization.films_list.append(film_dict) gnr_lst = [] gnr = film_dict.get('genres') try: for i in gnr: gnr_lst.append(i.get('name')) except: pass film_dict['genres'] = gnr_lst if film_dict.get('genres') != []: for stat in film_dict: s += str(stat) + ': ' + str(film_dict.get(stat)) + '\n' else: s += '\n' * 12 s += '\n' * 4 s += '[]' + '[]' * int((int((n*100) / visualisation.Visualization.num) / 2)) + \ ' ' * (50 - int((int((n*100) / visualisation.Visualization.num) / 2))) + '\n' s += 'Analyzed data: ' + str( int((n * 100) / visualisation.Visualization.num)) + ' %' return s
def get_img_movie_from_id(self, ID): """"Get img movie url by id """ mov = tmdb.Movies(ID) result = mov.images() if len(result['backdrops']) > 0: dic = result['backdrops'] return dic[0]['file_path']
def tmdbid_to_imdbid(tmdbid): logger.info("Querying TMDB for IMDB id %s" % tmdbid) movie = tmdbsimple.Movies(tmdbid) response = movie.info() imdbid = response["imdb_id"][2:] title = response["title"] logger.info("Found TMDB id %s for IMDB id %s" % (tmdbid, imdbid)) return imdbid, title
def director(self): identity = tmdb.Movies(self.tmdb_id) response = identity.credits() name = '' for i in identity.crew: if i['job'] == "Director": name = str(i['name']) print("Director was" + name)
def get_tmdb_movie_year(tmdb_id): tmdb_movie = tmdb.Movies(tmdb_id) response = tmdb_movie.info(language='pt-BR') year = tmdb_movie.release_date year = year.split('-') year = year[0] return year
def test_movite_title(self): tmdb.API_KEY = settings.TMDB_API_KEY movie = tmdb.Movies(603) response = movie.info() import pdb pdb.set_trace() self.assertEquals(response.title, 'The Matrix')
def filterMovies(self, page, id, gender, name): if (page): response = tmdb.Movies() response = response.now_playing(page=page) return response if (id): movieInfo = tmdb.Movies(id).info() return movieInfo if (gender): genres = tmdb.Genres() response = genres.movie_list() return response if (name): response = tmdb.Search().movie(query=name) return response return None