def fetchDetails(self, show, id): if show not in self.tvShows: return False # Fetch show information details = TV().details(id) self.tvShows[show] = details show.firstAirYear = int(details.first_air_date[:4]) show.databaseId = id show.databaseTitle = details['name'] # Fetch episode information for sNbr, season in show.seasons.items(): if not self.__seasonAvailable__(sNbr, details): continue seasonDetails = Season().details(id, sNbr) for episode in season.episodes: episodeDetails = None # Check if episode exist for e in seasonDetails.episodes: if e['episode_number'] == episode.episodeNumber: episodeDetails = e break if episodeDetails == None: continue episode.databaseTitle = episodeDetails['name'] return True
def queryTVShowsFromTmdb(tv_shows_id): """ Collect current tv show data from tmdb api Args: tv_shows_id (int list): list of tv shows id Returns: tv_shows_data (str list): list of each TV show raw data in JSON format """ # Create a TV object tv = TV() # Iterate over each TV show and get their details tv_shows_data = [] for id in tv_shows_id: try: tv_show = tv.details(id) tv_show_dict = tv_show.__dict__ query_datetime = datetime.utcnow().strftime("%Y-%m-%d %H:%M:%S") tv_show_dict['query_datetime'] = query_datetime except Exception as e: logging.error(str(e)) logging.error( 'TV show id={} could not be queried properly'.format(id)) else: tv_shows_data.append(json.dumps(tv_show_dict)) # Check how many TV shows are successfully queried if len(tv_shows_data) == len(tv_shows_id): logging.info('All {} tv shows are queried successfully'.format( len(tv_shows_data))) else: logging.warning('{}/{} tv shows are queried successfully'.format( len(tv_shows_data), len(tv_shows_id))) return tv_shows_data
def __init__(self): self.tmdb = TMDb() self.tmdb.api_key = "e00b72174e4ae097af808f34a8f220fc" self.tv = TV() self.season = Season() self.movie = Movie() self.discover = Discover()
def __init__(self, api_key: str, language: str = 'en'): self.tmbd = TMDb() self.tmbd.api_key = api_key self.tmbd.language = language self.__tv = QueryTV(TV()) self.__movie = QueryMovie(Movie())
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 tv_show(request): tv = TV() populars = tv.popular() print(populars) context = { 'tv': populars, } return render(request, 'tv/index.html', context)
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.tmdb.cache = False self.tv = TV()
def getDatabaseMatches(self): tv = TV() result = [] for show in self.tvShows.keys(): search = tv.search(show.estimatedTitle) result.append([show, search]) return result
def setUp(self): self.tmdb = TMDb() self.tmdb.api_key = os.environ['api_key'] self.movie = Movie() self.discover = Discover() self.tv = TV() self.person = Person() self.collection = Collection() self.company = Company() self.season = Season()
def recommend(): web = str(request.args.get('web')) rcmd = recommendation(web) tmdb_webseries = TV() result = tmdb_webseries.search(web) web_id = result[0].id response = requests.get('http://api.themoviedb.org/3/tv/{}?api_key={}&append_to_response=external_ids'.format(web_id,tmdb.api_key)) data_json = response.json() imdb_id = data_json['external_ids']['imdb_id'] poster = result[0].poster_path img_path = 'https://image.tmdb.org/t/p/original{}'.format(poster) genre = ListOfGenres(data_json['genres']) cast_response = requests.get('https://api.themoviedb.org/3/tv/{}?api_key={}&append_to_response=credits'.format(web_id,tmdb.api_key)) cast_data = cast_response.json() casts = {i:[cast_data['credits']['cast'][i]['name'], cast_data['credits']['cast'][i]['character'], 'https://image.tmdb.org/t/p/original/'+cast_data['credits']['cast'][i]['profile_path']] for i in range(len(cast_data['credits']['cast']))} sauce = urllib.request.urlopen('https://www.imdb.com/title/{}/reviews?ref_=tt_ql_3'.format(imdb_id)).read() soup = bs.BeautifulSoup(sauce,'lxml') soup_result = soup.find_all("div",{"class":"text show-more__control"}) reviews_list = [] reviews_status = [] for reviews in soup_result: if reviews.string: reviews_list.append(reviews.string) web_review_list = np.array([reviews.string]) web_vector = vectorizer.transform(web_review_list) pred = clf.predict(web_vector) reviews_status.append('Good' if pred else 'Bad') web_reviews = {reviews_list[i]: reviews_status[i] for i in range(len(reviews_list))} vote_count = "{:,}".format(result[0].vote_count) rd = date_convert(result[0].first_air_date) df = pd.read_csv('data.csv') seasons = df[df['Series Title']== web.lower()]['No of Seasons'] seasons = seasons.iloc[0] overview = result[0].overview poster = [] for web_title in rcmd: list_result = tmdb_webseries.search(web_title) web_id = list_result[0].id posterr = list_result[0].poster_path poster.append('https://image.tmdb.org/t/p/original{}'.format(posterr)) web_cards = {poster[i]: rcmd[i] for i in range(len(rcmd))} suggestions = get_suggestions() return render_template('recommend.html', web=web, webtitle=rcmd, cards=web_cards,casts=casts, result=result[0], reviews = web_reviews, img_path=img_path, genre=genre, vote_count=vote_count, release_date=rd, seasons=seasons, overview=overview, t='l', suggestions=suggestions)
def get_dim_tmdb(tv_shows_id): """ Queries TV show details from TMDB and extracts genres, networks and tv show data Args: tv_shows_id (int list): list of tv shows id Returns: df_genre (dataframe) : genre id and name df_network (dataframe) : network id, name and origin country df_tvshow (dataframe) : TV show id, name, original name, genre ids and network ids """ # Create the TV object tv = TV() # Retrieve raw TV show data tv_shows_raw = [] for tv_show_id in tv_shows_id: tv_show_detail = tv.details(tv_show_id) tv_shows_raw.append(tv_show_detail.__dict__) # Define the columns genre_columns = ['id', 'name'] network_columns = ['id', 'name', 'origin_country'] tv_show_columns = ['id', 'name', 'original_name', 'original_language', 'genres_id', 'networks_id'] # Initialize the dataframes df_genre = pd.DataFrame(columns=genre_columns) df_network = pd.DataFrame(columns=network_columns) df_tvshow = pd.DataFrame(columns=tv_show_columns) # Extract from the raw data for tv_show_data in tv_shows_raw: # Genres for genre in tv_show_data.get('genres', []): genre_id, genre_name = int(genre['id']), genre['name'] if not ((df_genre['id'] == genre_id) & (df_genre['name'] == genre_name)).any(): df_genre.loc[len(df_genre),:] = genre_id, genre_name # Networks for network in tv_show_data.get('networks', []): network_id, network_name, network_country = int(network['id']), network['name'], network['origin_country'] if not ((df_network['id'] == network_id) & (df_network['name'] == network_name)).any(): df_network.loc[len(df_network),:] = network_id, network_name, network_country # TV shows genres_id = [] for genre in tv_show_data.get('genres', []): genres_id.append(int(genre['id'])) networks_id = [] for network in tv_show_data.get('networks', []): networks_id.append(int(network['id'])) df_tvshow.loc[len(df_tvshow),:] = [int(tv_show_data['id']), tv_show_data['name'], tv_show_data['original_name'], tv_show_data['original_language'], genres_id,networks_id] return df_genre, df_network, df_tvshow
def query_api(self, name): tmdb = TMDb() tmdb.api_key = tmdb_key tmdb.language = 'en' #search movies movie = Movie() search_movie = movie.search(name) for res in search_movie: try: Media.objects.get(external_id=res.id) continue except Media.DoesNotExist as ex: if res.release_date == '': res.release_date = None if res.poster_path == None: poster = "https://lascrucesfilmfest.com/wp-content/uploads/2018/01/no-poster-available-737x1024.jpg" else: poster = "https://www.themoviedb.org/t/p/w600_and_h900_bestv2" + res.poster_path Media.objects.create( title = res.title, description = res.overview, poster_url = poster, release_date = res.release_date, media_type= "Movie", external_id= res.id ) #search TV tv = TV() search_tv = tv.search(name) for res in search_tv: if res.first_air_date == '': res.first_air_date = None if res.poster_path == None: poster = "https://lascrucesfilmfest.com/wp-content/uploads/2018/01/no-poster-available-737x1024.jpg" else: poster = "https://www.themoviedb.org/t/p/w600_and_h900_bestv2" + res.poster_path try: Media.objects.get(external_id=res.id) continue except Media.DoesNotExist as ex: Media.objects.create( title = res.name, description = res.overview, poster_url = poster, release_date = res.first_air_date, media_type= "TV", external_id= res.id )
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 tv_details(request, tv_name): comment_form = CommentForm() tv = TV() found_tv = tv.search(tv_name)[0] poster_path = found_tv.poster_path[1:] similar = tv.similar(found_tv.id) print(found_tv.id) comments = Comment.objects.filter(film=tv_name) print(found_tv) context = {'tv': found_tv, 'comment_form': comment_form, 'comments': comments, 'poster_path': poster_path, 'similar': similar} return render(request, 'tv/details.html', context)
def IMDBtoTMDB(args): if args.tmdb != "AUTO-DETECT": return format = "" movie = Movie() tv = TV() tmdb = TMDb() tmdb.api_key = args.tmdbapi if (args.type == "TV"): format = 'tv_results' if (args.type == "Movie"): format = 'movie_results' tmdb = movie.external(f"{args.imdb}", f'imdb_id') if len(tmdb.get(format)) != 0: args.tmdb = tmdb.get(format)[0].get("id", "")
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.network = Network() self.search = Search() self.season = Season() self.list = List()
def scrape_images(filepath, save_to='media/images/'): """ Takes path to a csv file as argument and uses TMDB API to download images by searching for title """ BASE_IMG_URL = 'https://image.tmdb.org/t/p/w500' tmdb = TMDb() tmdb.api_key = TMDB_API_KEY tmdb.language = 'en' tmdb.debug = True with open(filepath, 'r') as f: reader = csv.DictReader(f) movie = Movie() tv = TV() for i, row in enumerate(reader): title = row['title'] print(f'{i} Title: {title}') if row['type'] == 'TV Show': res = tv.search(title) else: res = movie.search(title) if len(res) == 0: print('No results found') continue elif len(res) > 1: print('Length of results: ', len(res)) print(res) # Check to see if image is available try: image_url = BASE_IMG_URL + res[0].poster_path except TypeError as e: print('No image available') continue image_response = requests.get(image_url) if image_response.status_code == 200: with open(save_to + row['show_id'] + '.jpg', 'wb') as f: f.write(image_response.content) else: print(f'Error retreiving image for: {title}') print(f'Status code: {image_response.status_code}') time.sleep(0.1)
def clean_votes(award, vote_list): actor_contain = 'performance' in award or 'director' in award or 'screenplay' in award or 'score' in award or 'actor' in award or 'actress' in award if(not actor_contain): actor_contain = award in PEOPLE_AWARDS mov_contain = 'motion picture' in award or 'feature' in award or 'film' in award if(not mov_contain): mov_contain = award in ENTITY_AWARDS tv_contain = 'television' in award cleaned_votes = [] if(actor_contain): for vote in vote_list: text = vote[0] person = Person() result = person.search(text) if(len(result) > 0): res = str(result[0]) ind = get_curr_index(res, cleaned_votes) if(ind != -1): cleaned_votes[ind][1] = cleaned_votes[ind][1] + vote[1] else: cleaned_votes.append([res, vote[1]]) elif(mov_contain): for vote in vote_list: text = vote[0] movie = Movie() result = movie.search(text) if(len(result) > 0): res = str(result[0]) ind = get_curr_index(res, cleaned_votes) if(ind != -1): cleaned_votes[ind][1] = cleaned_votes[ind][1] + vote[1] else: cleaned_votes.append([res, vote[1]]) if(tv_contain and not actor_contain): for vote in vote_list: text = vote[0] tv = TV() result = tv.search(text) if(len(result) > 0): res = str(result[0]) ind = get_curr_index(res, cleaned_votes) if(ind != -1): cleaned_votes[ind][1] = cleaned_votes[ind][1] + vote[1] else: cleaned_votes.append([res, vote[1]]) return cleaned_votes
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
def buscar(): try: if request.method == 'POST': titulo = request.form['titulo'] tipo = request.form['tipo'] if not titulo: raise Exception('El Titulo es requerido.') if tipo == "peliculas": entidad = Movie() elif tipo == "series": entidad = Season() elif tipo == "tv": entidad = TV() show = entidad.search(titulo) except Exception as e: flash(str(e)) return redirect(url_for('pagina.index')) return render_template('pagina/buscar.html', resultados=show)
def getAdditionalData(self, movieId): if "Url" not in self.movieID_to_info[movieId]: tmdb = TMDb() tmdb.api_key = '66a11b9611008995220d8300279b6011' tmdb.language = 'en' tmdb.debug = True base = "https://image.tmdb.org/t/p/w200" url = "" title = self.movieID_to_info[movieId]["Title"][:-6] search = Movie().search(title) if search != []: url = search[0].poster_path else: search = TV().search(title) if search != []: url = search[0].poster_path self.movieID_to_info[movieId]["Url"] = base + url return self.getChartData(movieId)
from tmdbv3api import TMDb from tmdbv3api import Movie from tmdbv3api import TV # For loading JSON file import json # Open the JSON file with open('./everything.json', encoding='utf-8') as fh: file = json.load(fh) tmdb = TMDb() tmdb.api_key = 'a9545ec1bd745e79c447cdadf22cb82c' tmdb.language = 'en' tmdb.debug = True tv = TV() movie = Movie() data = [] for i in range(1): print(obj['title']) if (obj['type'] == "TV Show"): show = tv.search(obj['title']) try: print(show[0].name) print(show[0].poster_path) obj |= {'img': show[0].poster_path}
def __init__(self): self.movie = Movie() self.tv = TV()
def getSeriesNamePoster(series_id): id = int(series_id) series = TV() s = series.details(id) return s.name, s.poster_path
def singleSeries(request, series_id): data = {} id = int(series_id) # Fetching all the reviews of that series reviews = ReviewSeries.objects.filter(seriesid=id) userReviews = [] if reviews.exists(): 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 = ReviewSeries.objects.filter(seriesid=id).filter(userid=request.user.username) if check.exists(): data['check'] = True else: data['check'] = False # If user send review this part is executed. if request.method == "POST": username = request.user.username series_id = int(series_id) text = request.POST['review'] # Calling getSentiment function to get probability and sentiment of review. prob, sen = getSentiment(text) x = ReviewSeries( userid = username, seriesid = series_id, review = text, sentiment = sen, probability = prob ) # Saving the review and sending a conformation message. x.save() messages.success(request, 'Your review has been saved successfully.') return redirect(singleSeries, id) # setting series details series = TV() s = series.details(id) # Arranging series data cast = [] temp = s.credits.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.credits.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.name data['homepage'] = s.homepage data['networks'] = [{'name': x.name, 'logo': x.logo_path} for x in s.networks] data['description'] = s.overview data['tagline'] = s.tagline data['languages'] = s.languages data['seasons'] = s.seasons data['created_by'] = [{'name': x.name, 'photo': x.profile_path} for x in s.created_by] data['status'] = s.status data['country'] = s.origin_country data['trailer'] = s.videos.results[0].key data['type'] = s.type data['cast'] = cast data['crew'] = crew data['runtime'] = s.episode_run_time data['release_date'] = s.first_air_date data['votes'] = getRatingSeries(seriesid=id) data['negative'] = 100 - data['votes'] data['poster'] = s.poster_path context = {} context['data'] = data return render(request, 'rhub/seriesInfo.html', context)
def series(request): tv = TV() context = {} data = {} data['page'] = 1 data['query'] = "" if request.method == 'POST': if 'submit-btn' in request.POST: query = request.POST['search'] search = tv.search(query) count = 0 for p in search: c = {'id':p.id, 'title':p.name, 'poster':p.poster_path, 'overview':p.overview, 'vote':getRatingSeries(int(p.id))} context["m_id" + str(count)] = c count += 1 page_count = int(tv.total_pages) data['data_series'] = context data['page'] = 1 data['query'] = query data['total_pages'] = page_count if 'next' in request.POST: page = int(request.POST['page']) if request.POST['search'] == "": popular = tv.popular(page = page + 1 ) count = 0 for p in popular: c = {'id':p.id, 'title':p.name, 'poster':p.poster_path, 'overview':p.overview, 'vote':getRatingSeries(int(p.id))} context["m_id" + str(count)] = c count += 1 page_count = int(tv.total_pages) else: query = request.POST['search'] search = tv.search(query, page+1) if len(search) > 0: count = 0 for p in search: c = {'id':p.id, 'title':p.name, 'poster':p.poster_path, 'overview':p.overview, 'vote':getRatingSeries(int(p.id))} context["m_id" + str(count)] = c count += 1 page_count = int(tv.total_pages) data['data_series'] = context data['page'] = page+1 data['total_pages'] = page_count data['query'] = request.POST['search'] if 'prev' in request.POST: page = int(request.POST['page']) if request.POST['search'] == "": popular = tv.popular(page=page-1) count = 0 for p in popular: c = {'id':p.id, 'title':p.name, 'poster':p.poster_path, 'overview':p.overview, 'vote':getRatingSeries(int(p.id))} context["m_id" + str(count)] = c count += 1 page_count = int(tv.total_pages) else: query = request.POST['search'] search = tv.search(query, page-1) if len(search) > 0: count = 0 for p in search: c = {'id':p.id, 'title':p.name, 'poster':p.poster_path, 'overview':p.overview, 'vote':getRatingSeries(int(p.id))} context["m_id" + str(count)] = c count += 1 page_count = int(tv.total_pages) data['data_series'] = context data['page'] = page -1 data['total_pages'] = page_count data['query'] = request.POST['search'] return render(request, 'rhub/series.html', data) else: popular = tv.popular() count = 0 for p in popular: c = {'id':p.id, 'title':p.name, 'poster':p.poster_path, 'overview':p.overview, 'vote':getRatingSeries(int(p.id))} context["m_id" + str(count)] = c count += 1 page_count = int(tv.total_pages) data['data_series'] = context data['total_pages'] = page_count data['page'] = 1 return render(request, 'rhub/series.html', data)
def home(request): # This method runs when post request is done. if request.method == 'POST': form = FeedbackForm(request.POST) # If form is valid then it saves it. if form.is_valid(): form.save() data = {} #setting up movies movie = Movie() latest = movie.popular() upcoming = movie.upcoming() context = {} count = 0 for l in latest: c = {'id':l.id, 'poster':l.poster_path} context["m_id" + str(count)] = c count += 1 data['latest_movies'] = context context = {} count = 0 for up in upcoming: c = {'id':up.id, 'poster':up.poster_path} context["m_id" + str(count)] = c count += 1 data['upcoming_movies'] = context #setting up series tv = TV() popular = tv.popular() top_rated = tv.top_rated() count = 0 context = {} for p in popular: c = {'id':p.id, 'poster':p.poster_path} context["m_id" + str(count)] = c count += 1 data['latest_series'] = context count = 0 context = {} for tr in top_rated: c = {'id':tr.id, 'poster':tr.poster_path} context["tr_id" + str(count)] = c count += 1 data['top_series'] = context #setting up feedback form form = FeedbackForm() data['form'] = form return render(request, 'rhub/home.html', data)
def search_tmdb_shows(q): tv = TV() sr = tv.search(q) return sr
def tmdb_get_shows(config_path, plex, data, is_list=False): config_tools.TraktClient(config_path) tmdb_id = int(data) t_tvs = [] t_tv = TV() t_tv.api_key = config_tools.TMDB( config_path).apikey # Set TMDb api key for Movie if t_tv.api_key == "None": raise KeyError("Invalid TMDb API Key") if is_list: tmdb = List() tmdb.api_key = t_tv.api_key try: t_col = tmdb.details(tmdb_id) for ttv in t_col: if ttv.media_type == "tv": t_tvs.append(ttv.id) except: raise ValueError( "| Config Error: TMDb List: {} not found".format(tmdb_id)) else: try: t_tv.details(tmdb_id).number_of_seasons t_tvs.append(tmdb_id) except: raise ValueError( "| Config Error: TMDb ID: {} not found".format(tmdb_id)) p_tv_map = {} for item in plex.Library.all(): guid = urlparse(item.guid) item_type = guid.scheme.split('.')[-1] if item_type == 'thetvdb': tvdb_id = guid.netloc elif item_type == 'themoviedb': tvdb_id = get_tvdb_id_from_tmdb_id(guid.netloc) else: tvdb_id = None p_tv_map[item] = tvdb_id matched = [] missing = [] for mid in t_tvs: match = False tvdb_id = get_tvdb_id_from_tmdb_id(mid) if tvdb_id is None: print( "| Trakt Error: tmbd_id: {} could not converted to tvdb_id try just using tvdb_id instead" .format(mid)) else: for t in p_tv_map: if p_tv_map[t] and "tt" not in p_tv_map[t] != "None": if p_tv_map[t] is not None and int( p_tv_map[t]) == int(tvdb_id): match = True break if match: matched.append(t) else: missing.append(tvdb_id) return matched, missing
def get_external_id(show_id): tv = TV() details = tv.external_ids(show_id) return details["imdb_id"] if "imdb_id" in details else None