Ejemplo n.º 1
0
 def __init__(self):
     self.tmdb = TMDb()
     self.tmdb.api_key = "e00b72174e4ae097af808f34a8f220fc"
     self.tv = TV()
     self.season = Season()
     self.movie = Movie()
     self.discover = Discover()
Ejemplo n.º 2
0
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
Ejemplo n.º 3
0
def tv_show(request):
    tv = TV()
    populars = tv.popular()
    print(populars)
    context = {
        'tv': populars,
    }
    return render(request, 'tv/index.html', context)
Ejemplo n.º 4
0
 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()
Ejemplo n.º 5
0
    def getDatabaseMatches(self):
        tv = TV()
        result = []

        for show in self.tvShows.keys():
            search = tv.search(show.estimatedTitle)
            result.append([show, search])

        return result
Ejemplo n.º 6
0
 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()
Ejemplo n.º 7
0
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)
Ejemplo n.º 8
0
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
Ejemplo n.º 9
0
    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
                )
Ejemplo n.º 10
0
 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()
Ejemplo n.º 11
0
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 __init__(self, option_config_json):
     self.API_KEY = option_config_json['API']['themoviedb']
     self.tmdbv3 = TMDb()
     self.tmdbv3.api_key = self.API_KEY
     tmdb.API_KEY = self.API_KEY
     self.movie = Movie()
     self.tv = TV()
Ejemplo n.º 13
0
    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
Ejemplo n.º 14
0
    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())
Ejemplo n.º 15
0
 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()
Ejemplo n.º 16
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
Ejemplo n.º 17
0
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)
Ejemplo n.º 18
0
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
Ejemplo n.º 19
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
Ejemplo n.º 20
0
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", "")
Ejemplo n.º 21
0
    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)
Ejemplo n.º 22
0
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)
Ejemplo n.º 23
0
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}
class CommonMetadataTMDB(object):
    """
    Class for interfacing with TMDB
    """

    def __init__(self, option_config_json):
        self.API_KEY = option_config_json['API']['themoviedb']
        self.tmdbv3 = TMDb()
        self.tmdbv3.api_key = self.API_KEY
        tmdb.API_KEY = self.API_KEY
        self.movie = Movie()
        self.tv = TV()

    def com_tmdb_search(self, media_title, media_year=None, id_only=False, media_type='movie'):
        """
        # search for media title and year
        """
        common_global.es_inst.com_elastic_index('info', {"tmdb search": media_title,
                                                         'year': media_year})
        if media_type == 'movie':
            try:
                search = self.movie.search(media_title.replace('\\u25ba', ''))
            except:
                search = self.movie.search(media_title.encode('utf-8'))
        else:  # defaulting to TV search then
            try:
                search = self.tv.search(media_title.replace('\\u25ba', ''))
            except:
                search = self.tv.search(media_title.encode('utf-8'))
        common_global.es_inst.com_elastic_index('info', {'search': str(search)})
        if len(search) > 0:
            for res in search:
                # print(res.id)
                # print(res.title)
                # print(res.overview)
                # print(res.poster_path)
                # print(res.vote_average)
                common_global.es_inst.com_elastic_index('info', {"result": res.title, 'id': res.id,
                                                                 'date':
                                                                     res.release_date.split('-', 1)[
                                                                         0]})
                if media_year is not None and (str(media_year) == res.release_date.split('-', 1)[0]
                                               or str(int(media_year) - 1) ==
                                               res.release_date.split('-', 1)[0]
                                               or str(int(media_year) - 2) ==
                                               res.release_date.split('-', 1)[0]
                                               or str(int(media_year) - 3) ==
                                               res.release_date.split('-', 1)[0]
                                               or str(int(media_year) + 1) ==
                                               res.release_date.split('-', 1)[0]
                                               or str(int(media_year) + 2) ==
                                               res.release_date.split('-', 1)[0]
                                               or str(int(media_year) + 3) ==
                                               res.release_date.split('-', 1)[0]):
                    if not id_only:
                        return 'info', self.com_tmdb_metadata_by_id(res.id)
                    else:
                        return 'idonly', res.id  # , s['title']
            return None, None
            # TODO multimatch......handle better!
            # TODO so, returning None, None for now
            # return 're', search.results
        else:
            return None, None

    def com_tmdb_metadata_by_id(self, tmdb_id):
        """
        Fetch all metadata by id to reduce calls
        """
        if tmdb_id[0:2].lower() == 'tt':
            # imdb id......so, run find and then do the requests
            tmdb_id = metadata_movie.movie_fetch_tmdb_imdb(tmdb_id)
        try:
            return requests.get('https://api.themoviedb.org/3/movie/%s'
                                '?api_key=%s&append_to_response=credits,reviews,release_dates,videos' %
                                (tmdb_id, self.API_KEY))
        except requests.exceptions.ConnectionError:
            time.sleep(20)
            self.com_tmdb_metadata_by_id(tmdb_id)

    def com_tmdb_metadata_tv_by_id(self, tmdb_id):
        """
        Fetch all metadata by id to reduce calls
        """
        try:
            return requests.get('https://api.themoviedb.org/3/tv/%s'
                                '?api_key=%s&append_to_response=credits,reviews,release_dates,videos' %
                                (tmdb_id, self.API_KEY))
        except requests.exceptions.ConnectionError:
            time.sleep(20)
            self.com_tmdb_metadata_tv_by_id(tmdb_id)

    def com_tmdb_metadata_bio_by_id(self, tmdb_id):
        """
        Fetch all metadata bio by id to reduce calls
        """
        try:
            return requests.get('https://api.themoviedb.org/3/person/%s'
                                '?api_key=%s&append_to_response=combined_credits,external_ids,images' %
                                (tmdb_id, self.API_KEY))
        except requests.exceptions.ConnectionError:
            time.sleep(20)
            self.com_tmdb_metadata_bio_by_id(tmdb_id)

    def com_tmdb_meta_bio_image_build(self, thread_db, result_json):
        """
        # download info and set data to be ready for insert into database
        """
        # common_global.es_inst.com_elastic_index('info', {'tmdb bio build': result_json})
        # create file path for poster
        image_file_path = common_metadata.com_meta_image_file_path(result_json['name'],
                                                                   'person')
        # common_global.es_inst.com_elastic_index('info', {'tmdb bio image path': image_file_path})
        if 'profile_path' in result_json and result_json['profile_path'] is not None:
            if not os.path.isfile(image_file_path + result_json['profile_path']):
                if result_json['profile_path'] is not None:
                    if not os.path.isfile(image_file_path):
                        common_network.mk_network_fetch_from_url(
                            'https://image.tmdb.org/t/p/original' + result_json['profile_path'],
                            image_file_path + result_json['profile_path'])
        # set local image json
        return ({'Images': {'themoviedb': image_file_path}})

    def com_tmdb_metadata_id_max(self):
        """
        Grab high metadata id
        """
        return json.loads(common_network.mk_network_fetch_from_url(
            'https://api.themoviedb.org/3/movie/latest'
            '?api_key=%s' % self.API_KEY))['id']

    def com_tmdb_metadata_bio_id_max(self):
        """
        Grab high bios metadata id (person)
        """
        return json.loads(common_network.mk_network_fetch_from_url(
            'https://api.themoviedb.org/3/person/latest'
            '?api_key=%s' % self.API_KEY))['id']

    def com_tmdb_metadata_tv_id_max(self):
        """
        Grab high tv metadata id
        """
        return json.loads(common_network.mk_network_fetch_from_url(
            'https://api.themoviedb.org/3/tv/latest'
            '?api_key=%s' % self.API_KEY))['id']

    def com_tmdb_meta_by_id(self, tmdb_id):
        """
        # movie info by tmdb
        """
        movie = tmdb.Movies(tmdb_id)
        try:
            metadata = movie.info()
        except Exception as err_code:
            common_global.es_inst.com_elastic_index('error', {"TMDB Fetch Error": str(err_code)})
            metadata = None
        return metadata

    def com_tmdb_meta_cast_by_id(self, tmdb_id):
        """
        # cast by tmdb
        """
        movie = tmdb.Movies(tmdb_id)
        try:
            metadata = movie.credits()
        except Exception as err_code:
            common_global.es_inst.com_elastic_index('error', {"TMDB Fetch Credits Error":
                                                                  str(err_code)})
            metadata = None
        return metadata

    def com_tmdb_meta_review_by_id(self, tmdb_id):
        """
        # review by tmdb
        """
        movie = tmdb.Movies(tmdb_id)
        try:
            metadata = movie.reviews()
        except Exception as err_code:
            common_global.es_inst.com_elastic_index('error', {"TMDB Fetch Review Error": str(
                err_code)})
            metadata = None
        return metadata

    def com_tmdb_meta_release_by_id(self, tmdb_id):
        """
        # release by tmdb
        """
        movie = tmdb.Movies(tmdb_id)
        try:
            metadata = movie.releases()
        except Exception as err_code:
            common_global.es_inst.com_elastic_index('error',
                                                    {"TMDB Fetch Releases Error": str(err_code)})
            metadata = None
        return metadata

    # TODO
    # The supported external sources for each object are as follows:
    #    Movies: imdb_id
    #    People: imdb_id, freebase_mid, freebase_id
    #    TV Series: imdb_id, freebase_mid, freebase_id, tvdb_id
    #    TV Seasons: freebase_mid, freebase_id, tvdb_id
    #    TV Episodes: imdb_id, freebase_mid, freebase_id, tvdb_id

    def com_tmdb_meta_by_imdb_id(self, imdb_id):
        """
        # search by imdb
        """
        movie = tmdb.Find(imdb_id)
        try:
            metadata = movie.info(external_source='imdb_id')
        except Exception as err_code:
            common_global.es_inst.com_elastic_index('error',
                                                    {"TMDB Fetch imdb Error": str(err_code)})
            metadata = None
        return metadata

    def com_tmdb_meta_changes_movie(self):
        """
        # movie changes since date within 24 hours
        """
        changes = tmdb.Changes()
        movie_changes = changes.movie()
        return movie_changes

    def com_tmdb_meta_changes_tv(self):
        """
        # tv changes since date within 24 hours
        """
        changes = tmdb.Changes()
        tv_changes = changes.tv()
        return tv_changes

    def com_tmdb_meta_changes_person(self):
        """
        # person changes since date within 24 hours
        """
        changes = tmdb.Changes()
        person_changes = changes.person()
        return person_changes

    def com_tmdb_meta_collection_by_id(self, tmdb_id):
        """
        # collection info
        """
        movie_collection = tmdb.Collections(tmdb_id)
        try:
            metadata = movie_collection.info()
        except Exception as err_code:
            common_global.es_inst.com_elastic_index('error',
                                                    {"TMDB Fetch Collection Error": str(err_code)})
            metadata = None
        return metadata

    def com_tmdb_meta_info_build(self, result_json):
        """
        # download info and set data to be ready for insert into database
        """
        # common_global.es_inst.com_elastic_index('info', {'tmdb info build': result_json})
        # create file path for poster
        image_file_path = common_metadata.com_meta_image_file_path(result_json['title'],
                                                                   'poster')
        # common_global.es_inst.com_elastic_index('info', {'tmdb image path': image_file_path})
        poster_file_path = None
        if result_json['poster_path'] is not None:
            image_file_path += result_json['poster_path']
            if not os.path.isfile(image_file_path):
                common_network.mk_network_fetch_from_url('https://image.tmdb.org/t/p/original'
                                                         + result_json['poster_path'],
                                                         image_file_path)
            poster_file_path = image_file_path
        # create file path for backdrop
        image_file_path = common_metadata.com_meta_image_file_path(result_json['title'],
                                                                   'backdrop')
        backdrop_file_path = None
        if result_json['backdrop_path'] is not None:
            image_file_path += result_json['backdrop_path']
            if not os.path.isfile(image_file_path):
                common_network.mk_network_fetch_from_url('https://image.tmdb.org/t/p/original'
                                                         + result_json['backdrop_path'],
                                                         image_file_path)
            backdrop_file_path = image_file_path
        # its a number so make it a string just in case
        series_id_json = json.dumps({'imdb': result_json['imdb_id'],
                                     'themoviedb': str(result_json['id'])})
        # set local image json
        image_json = ({'Images': {'themoviedb': {'Backdrop': backdrop_file_path,
                                                 'Poster': poster_file_path}}})
        return series_id_json, result_json, image_json
Ejemplo n.º 25
0
"""Powered by deep-translator and TMDB
Design by David Zhou For Raspberry Pi 4B and dCloud XT(X86)
PS: Paddle and Papago is not working with python 3.8, so use fallback mode"""
if __name__ =='__main__':
    from deep_translator import GoogleTranslator
    userinput = userinputfr = str(input("请输入英文进行翻译: "))
    from tmdbv3api import TV
    from tmdbv3api import Movie
    from tmdbv3api import TMDb
    tmdb = TMDb()
    tmdb.api_key = 'your TMDB API here'
    tmdb.language = 'zh'
    tv = TV()
    movie = Movie()
    movies = movie.search(userinput)
    show = tv.search(userinput)
    print('\n')
    for result in movies:
        print(result.title)
        quit()
    for result in show:
        print(result.name)
        quit()
    translated1 = GoogleTranslator(source='en', target='ja').translate(userinput) 
    translated2 = GoogleTranslator(source='ja', target='zh').translate(translated1) 
    print("中文:",translated2)
Ejemplo n.º 26
0
 def __init__(self):
     self.movie = Movie()
     self.tv = TV()
Ejemplo n.º 27
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")
Ejemplo n.º 28
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
Ejemplo n.º 29
0
def getSeriesNamePoster(series_id):
    id = int(series_id)
    series = TV()
    s = series.details(id)
    return s.name, s.poster_path
Ejemplo n.º 30
0
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)
Ejemplo n.º 31
0
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)
Ejemplo n.º 32
0
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)