Ejemplo n.º 1
0
def search_movie(query):
    tmdb = TMDb()
    tmdb.api_key = 'PLEASE GENERATE UR OWN API KEY, ALL INFO IN README FILE'
    movie = Movie()

    result = movie.search(query)
    number_of_movies = len(result)

    if number_of_movies == 0:
        print("SORRY, I CAN'T FIND ANYTHING, PLEASE TRY ANOTHER PHRASE")
    else:
        random_movie_title = choice(result).title
        print(
            f'I have found {number_of_movies} movies, here is a random choice for you:'
        )
        print(f'Title: {random_movie_title}')
        for res in result:
            if res.title == random_movie_title:
                if res.overview == "":
                    print('Sorry, no plot available :c')
                else:
                    print(f'Movie id: {res.id}')
                    print(f'Plot: {res.overview}')
                    print(f'Released in {res.release_date}')

                    similar = movie.similar(res.id)
                    for sim in similar:
                        print(
                            f'Similar movie: {sim} (movie id: {sim.id}), released in {sim.release_date}'
                        )
                        break
                break
Ejemplo n.º 2
0
def findMovies(request):
    baseURL = "https://image.tmdb.org/t/p/w300/"
    movieName = request.GET['search field']
    recommended_movies = main_code(movieName)
    movie = Movie()
    movie_poster = []
    new_movie_list = []
    for title in recommended_movies:
        m = re.match(r'^(.*) \((19\d\d|20\d\d)\)$', title)
        name, year = m.groups()
        new_movie_list.append(name)

    for i in new_movie_list:
        print(i)
    count = 0
    flag = True
    for i in new_movie_list:
        if count < 6:
            try:
                search = movie.search(i)
                item = search[0].poster_path
            except IndexError:
                return render(request, "error.html")

            movie_poster_path = str(item)
            final = baseURL + movie_poster_path
            movie_poster.append(final)
            print(final)
            count += 1
        else:
            break

    return render(request, "output.html", {'movie_poster': movie_poster})
Ejemplo n.º 3
0
    def add_poster(self, movie_title):
        import requests
        from PyQt5.QtGui import QIcon, QPixmap
        from tmdbv3api import TMDb
        from tmdbv3api import Movie
        tmdb = TMDb()
        tmdb.api_key = '1437062848d1dda19bd3907cf120e9f4'
        tmdb.language = 'en'
        #tmdb.debug = True
        movie = Movie()
        m = movie.search(movie_title)
        for i in m:
            continue_path = i.poster_path
            if continue_path != "None":
                continue_path = i.poster_path
                #print(continue_path)
                break

        url = 'http://image.tmdb.org/t/p/w185'
        combine = url + continue_path
        #readlink
        href = combine
        r = requests.get(href, stream=True)

        pixmap = QPixmap()
        pixmap.loadFromData(r.content)

        self.poster.setPixmap(pixmap)
        self.poster.setScaledContents(True)  #fullsizepic
        self.poster.show()
Ejemplo n.º 4
0
def search_movie(request):
    if request.method == 'GET':
        form = FilmSearchForm()
        return render(request, 'save_search.html', {'form': form})
    elif request.method == 'POST':
        form = FilmSearchForm(request.POST)
        if form.is_valid():
            tmdb = TMDb()
            tmdb.api_key = os.environ['KEY-MDB']
            movie = Movie()
            query = request.POST.get('query', 'Marlina')
            search = movie.search(query)

            db, token, uid = initializationDb()
            for p in search:
                data = {
                    "id": p.id,
                    "title": p.title,
                    "overview": p.overview,
                    "poster_path": p.poster_path,
                    "release_date": p.release_date,
                    "popularity": p.popularity,
                    "original_title": p.original_title,
                    "vote_count": p.vote_count,
                    "vote_average": p.vote_average
                }
                db.child(uid).child("movie_list").child(p.id).set(data, token)
            response = {"status": 200, "message": "Success Save"}
            return JsonResponse(response)
        else:
            response = {"status": 401, "message": "Invalid Input"}
            return JsonResponse(response)
Ejemplo n.º 5
0
def search(request):
	if request.method == "POST":
		movie = Movie()
		results = serialize_movie_array(movie.search(request.POST["search"]),5)
		if len(results)>5:
			return JsonResponse({"results":results[:5]})
		else:
			return JsonResponse({"results":results})
def movid(ti):
  movie = Movie()
  search = movie.search(ti)
  for res in search:

    x = (res.id)
    break
  return x
Ejemplo n.º 7
0
def add_movie(request, movie_name):
    movie = Movie()
    found_movie = movie.search(movie_name)[0]
    poster_path = found_movie.poster_path[1:]
    print(poster_path)
    new_film = Film(title=movie_name, poster_path=poster_path)
    new_film.save()
    Profile.objects.get(user=request.user).films_list.add(new_film)
    return redirect('/')
Ejemplo n.º 8
0
def search(query, limit):
    movie = Movie()
    s = movie.search(query)
    first_result = s[0]
    recommendations = movie.recommendations(first_result.id)
    recommendations = recommendations[:int(
        limit)] if recommendations >= limit else recommendations
    for recommendation in recommendations:
        print("%s (%s)" % (recommendation.title, recommendation.release_date))
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 tmdb_api(movie_name):
    try:
        movie = Movie()
        genre = Genre()
        config = Configuration()
        info = config.info()
        secure_base_url = info.images['secure_base_url']
        poster_size = "w500/"
        ret_dict = {}
        genres = {}
        genres_objs = genre.movie_list()
        for g in genres_objs:
            genres[g.id] = g.name
        movie_list = movie.search(movie_name)
        for i, m in enumerate(movie_list):
            external_ids = movie.external_ids(m.id)
            if 'imdb_id' in external_ids and external_ids[
                    'imdb_id'] is not None:
                external_id = external_ids['imdb_id'][2:]
                release_date = ""
                if hasattr(m, 'release_date') and m.release_date != "":
                    rel_date = m.release_date
                    date_obj = datetime.strptime(rel_date, '%Y-%m-%d')
                    release_date = date_obj.strftime('%d %B %Y')
                poster_path = ""
                if hasattr(m, 'poster_path') and m.poster_path != "" and str(
                        m.poster_path) != "None":
                    poster_path = secure_base_url + poster_size + str(
                        m.poster_path)
                ret_dict[i] = {
                    'title':
                    m.title if hasattr(m, 'title') else "",
                    'plot':
                    m.overview if hasattr(m, 'overview') else "",
                    'image':
                    poster_path,
                    'director':
                    "",
                    'release_date':
                    release_date,
                    'genre':
                    ', '.join(map(lambda x: genres[x], m.genre_ids))
                    if hasattr(m, 'genre_ids') else "",
                    'movie_id':
                    external_id
                }
        return ret_dict

    except exceptions.ConnectionError:
        raise TMDBConnectionException()
    except Exception:
        raise TMDBParsingException()
class MovieInfo:
    def __init__(self):
        self.tmdbObj= Movie()
    def getGenres(self,movie):
        genres=[]
        movieId=0
        try:
            movieId = self.tmdbObj.search(movie)[0]['id']
            response = requests.get('https://api.themoviedb.org/3/movie/{}?api_key={}'.format(movieId,tmdb.api_key))
            response =response.json()
            for g in range(len(response['genres'])):
                genres.append(response['genres'][g]['name'])
        except:
            print(movieId)
            return []
        return genres
    def getDirector(self,crew):
        if '(director)' in crew:
            return crew.split('(director)')[0]
        elif '(directors)' in crew:
            return crew.split('(directors)')[0]
        elif '(director/screenplay)' in crew:
            return crew.split('(director/screenplay)')[0]
        else:
            return 'unknown'
    def actor1(self,crew):
        if 'screenplay);' in crew:
            spl='screenplay);'
        else:
            spl='director);'
        actors= crew.split(spl)[-1].split(',')
        if len(actors)>0:
            return actors[0]
        else: return 'unknown'
    def actor2(self,crew):
        if 'screenplay);' in crew:
            spl='screenplay);'
        else:
            spl='director);'
        actors= crew.split(spl)[-1].split(',')
        if len(actors)>1:
            return actors[1]
        else: return 'unknown'
    def actor3(self,crew):
        if 'screenplay);' in crew:
            spl='screenplay);'
        else:
            spl='director);'
        actors= crew.split(spl)[-1].split(',')
        if len(actors)>2:
            return actors[2]
        else: return 'unknown'
Ejemplo n.º 12
0
def movie(name):
    response = "Searching for 2 similar movies for " + name
    movie = Movie()
    search = movie.search(name)
    i = 0
    for result in search:
        if i < 2:
            response += result.title + "\n"
            response += result.overview + "\n"
            response += "https://image.tmdb.org/t/p/w500" + p.poster_path + "\n"
            i = i + 1
        else:
            break
    return response
Ejemplo n.º 13
0
def movie_details(request, movie_name):
    comment_form = CommentForm()
    movie = Movie()
    found_movie = movie.search(movie_name)[0]
    poster_path = found_movie.poster_path[1:]
    similar = movie.similar(found_movie.id)
    print(found_movie.id)
    comments = Comment.objects.filter(film=movie_name)
    print(found_movie)
    context = {'movie': found_movie, 
    'comment_form': comment_form, 
    'comments': comments, 
    'poster_path': poster_path,
    'similar': similar}
    return render(request, 'movie/details.html', context)
Ejemplo n.º 14
0
 def search(self, submission):
     movie = Movie()
     title = submission
     if len(title) > 0:
         try:
             search = movie.search(title)
         except Exception as e:
             return
         if len(search) > 0:
             first = search[0]
             try:
                 movie = movie.details(first.id)
             except Exception as e:
                 return
             self.post(movie)
def get_similar(string):
    movie = Movie()
    movies = movie.search(string)
    if len(movies) == 0:
        return 0
    similar_movies = movie.similar(random.choice(movies).id)
    if len(similar_movies) == 0:
        return 1
    similar_movie = random.choice(similar_movies)
    return {
        "title": similar_movie.title,
        "overview": similar_movie.overview,
        "vote": str(similar_movie.vote_average) + "/10",
        "poster":
        "https://image.tmdb.org/t/p/w1280" + similar_movie.poster_path
    }
Ejemplo n.º 16
0
def search_movie(request):
    '''
    Функция поиска фильма (в названиях) по запросу. На вход получает строку запроса,
    на выходе выдает список, содержащий объекты-фильмы в виде словаря {поле-значение}
    :param request:
    :return search:
    '''

    movie = Movie()
    search = movie.search(request)
    #print(len(search))
    #for res in search:
    #    print(res.id)
    #    print(res.title, '['+res.original_title+']')
    #    print(res.entries.items())
    return search
Ejemplo n.º 17
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.º 18
0
 def getMovieData(self, title):
     #jsonData = urllib.request.urlopen("http://omdbapi.com/?t=%s&y=&tomatoes=true&plot=short&r=json" % title)
     #request = urllib.request.Request("http://omdbapi.com/?t=%s&y=&tomatoes=true&plot=short&r=json" % title)
     #response = urllib.request.urlopen(request)
     title = urllib.quote(title)
     movie = Movie()
     search = movie.search(title)
     self.movieData = {}
     self.movieData['title'] = search[0].title
     self.movieData['year'] = search[0].release_date
     self.movieData['userrating'] = search[0].vote_average
     self.movieData['imdbID'] = search[0].id
     self.movieData['plot'] = search[0].overview
     self.movieData['response'] = 'True'
     self.movieData['posterURL'] = self.generateImageLink(
         search[0].poster_path)
     return self.movieData
Ejemplo n.º 19
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)
def init():
    movieName = input("\nMovie Name?")
    tmdb = TMDb()
    tmdb.api_key = "10163a322f4558e7cc6411377702d81d"

    movie = Movie()

    try:
        search = movie.search(movieName)

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

        m = movie.details(movieID)

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

        print("-Full name: " + title)

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

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

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

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

    return title, initial_budget, revenue
Ejemplo n.º 21
0
class TMDBWrapper:
    def __init__(self, language: str):
        self.tmdb = TMDb()
        self.tmdb.api_key = config.MOVIE_DB_API_KEY  # '26e13c6a960c2e640f5e1867b9c52a46'
        self.tmdb.language = language or settings.LANGUAGE_CODE
        self.movie = Movie()
        self.discover = Discover()
        self.genre = Genre()

    def set_language(self, language: str):
        self.tmdb.language = language

    @modify_result(return_movies)
    def popular(self, page: int = 1):
        return self.movie.popular(page)

    @modify_result(return_movies)
    def top_rated(self, page: int = 1):
        return self.movie.top_rated(page)

    @modify_result(return_movies)
    def upcoming(self, page: int = 1, region: str = 'UA'):
        return self.movie._get_obj(
            self.movie._call(
                self.movie._urls["upcoming"],
                urlencode({
                    # "region": region,
                    "page": str(page)
                })))

    @modify_result(return_movies)
    def now_playing(self, page: int = 1):
        return self.movie.now_playing(page)

    @modify_result(return_movies)
    def search_movies(self, query: str, page: int = 1, **kwargs):
        return self.movie.search(term=query, page=page)

    @modify_result(return_movies)
    def discover_movies(self, params: Dict, **kwargs):
        return self.discover.discover_movies(params=params)

    def get_movies_genres(self):
        return self.genre.movie_list()
Ejemplo n.º 22
0
def buscar():
    if request.method == 'POST':
        title = request.form['title']
        error = None

        if not title:
            error = 'El Titulo es requerido.'

        if error is not None:
            flash(error)
            return redirect(url_for('blog.index'))
        else:
            from tmdbv3api import TMDb, TV, Movie, Season
            tmdb = TMDb()
            tmdb.api_key = "e00b72174e4ae097af808f34a8f220fc"
            movie = Movie()

            show = movie.search(title)
    return render_template('blog/buscar.html', posts=show)
Ejemplo n.º 23
0
def proc_Douban(df_Douban_raw, df_MovieLens, source=''):
    lists_Douban = df_Douban_raw.values.tolist()
    n = 1
    for a_movie_list in lists_Douban:
        movie_api = Movie()
        movie_api.wait_on_rate_limit = True
        while True:
            try:
                search = movie_api.search(a_movie_list[1])
                break
            except BaseException as error:
                print(error)
                time.sleep(0.25)
        print(n)
        tmdbId = 0
        for res in search:
            if ('release_date' not in res.__dict__) or (
                    res.release_date.split('-')[0] != a_movie_list[2]):
                continue
            else:
                tmdbId = res.id
                name = res.title
                break
        if tmdbId == 0 and len(search):
            tmdbId = search[0].id
            name = search[0].title
        a_movie_list[1] = name
        a_movie_list_extension = get_movie_details(tmdbId, df_MovieLens)
        a_movie_list += a_movie_list_extension
    df_Douban = pd.DataFrame(lists_Douban,
                             columns=[
                                 'rank', 'name', 'year', 'Douban_rating',
                                 'country', 'genres', 'budget', 'revenue',
                                 'keywords', 'MLens_rating', 'tmdb_id'
                             ])
    if source == 'test':
        df_Douban.to_csv('./data/Douban_top_250_test.csv')
        print('Douban testing dataset processed')
    else:
        df_Douban.to_csv('./data/Douban_top_250.csv')
        print('Complete Douban dataset processed')
    return df_Douban
Ejemplo n.º 24
0
def get_poster_link(title_list):
    """
    This Function take movie name list and return their Poster link, Tag line and Title into dictionary.
    """
    # TMDB Movie Api Object
    tmdb_movie = Movie()

    # Storing data in to dictionary
    dic_data = {"Movie_Title": [], "Poster_Links": [], "Tag_Line": []}

    for title in title_list:

        # checking given movie is present in our cache database or not.
        r_df = df_cache[df_cache['Title'] == title]
        try:
            # if given movie is found in our cache database then run this part
            if len(r_df) >= 1:
                dic_data["Movie_Title"].append(r_df['Movie_Title'].values[0])
                dic_data["Poster_Links"].append(r_df['Poster_Links'].values[0])
                dic_data["Tag_Line"].append(r_df['Tag_Line'].values[0])

            # otherwise retrieve the data from tmdbi api
            else:
                result = tmdb_movie.search(title)
                movie_id = result[0].id
                response = requests.get('https://api.themoviedb.org/3/movie/{}?api_key={}'.format(movie_id, tmdb.api_key))
                data_json = response.json()

                # Fetching movie title and poster link
                movie_title = data_json['title']
                movie_poster_link = "https://image.tmdb.org/t/p/original" + data_json['poster_path']
                movie_tag_line = data_json['tagline']

                # Appending movie title and poster link into dictionary
                dic_data['Movie_Title'].append(movie_title)
                dic_data['Poster_Links'].append(movie_poster_link)
                dic_data['Tag_Line'].append(movie_tag_line)
        except:
            pass

    return dic_data
Ejemplo n.º 25
0
def proc_Yahoo(df_Yahoo_raw, df_MovieLens, source=''):
    lists_Yahoo = df_Yahoo_raw.values.tolist()
    for a_movie_list in lists_Yahoo:
        movie_api = Movie()
        movie_api.wait_on_rate_limit = True
        while True:
            try:
                search = movie_api.search(a_movie_list[1])
                break
            except BaseException as error:
                print(error)
                time.sleep(0.25)
        tmdbId = 0
        for res in search:
            if ('release_date' not in res.__dict__) or (
                    res.release_date.split('-')[0] != a_movie_list[2]):
                continue
            else:
                tmdbId = res.id
                break
        if tmdbId == 0 and len(search):
            tmdbId = search[0].id
        a_movie_list_extension = get_movie_details(tmdbId, df_MovieLens)
        a_movie_list += a_movie_list_extension
    df_Yahoo = pd.DataFrame(lists_Yahoo,
                            columns=[
                                'rank', 'name', 'year', 'Yahoo_rating',
                                'country', 'genres', 'budget', 'revenue',
                                'keywords', 'MLens_rating', 'tmdb_id'
                            ])
    for i in range(510):
        df_Yahoo['year'][i] = re.sub('[()]', '', df_Yahoo['year'][i])
    df_Yahoo['year'] = df_Yahoo['year'].astype(int)
    if source == 'test':
        df_Yahoo.to_csv('./data/Yahoo_top_500_test.csv')
        print('Yahoo testing dataset processed')
    else:
        df_Yahoo.to_csv('./data/Yahoo_top_500.csv')
        print('Complete Yahoo dataset processed')
    return df_Yahoo
Ejemplo n.º 26
0
def fetch_reply(msg,session_id):
    response = detect_intent_from_text(msg,session_id)
    #storing user news searching details in th database
    db=client1.get_database('news_db')
    record_news=db.news_search
    
    #Getting news details
    img=' '
    if response.intent.display_name =='get_news':
        news =  get_news(dict(response.parameters))
        news_str = 'Here is your news'

        for row in news:
            news_str += '\n\n{}\n\n{}\n\n'.format(row['title'],row['link'])
        
        #sending news search preferences to database
        record_news.insert_one(dict(response.parameters))
               
        return news_str,img
    
    elif response.intent.display_name == 'movie':
        
        #inserting user searching details 
        db=client1.get_database('movies_db')
        records=db.movies

        #retrieving movies details
        movie = Movie()
        movie_name=response.parameters['movie']
        search =movie.search(movie_name)
        result = '\n\nId: {}\n\nTitle: {}\n\nOverview: {}\n\nRatings: {}\n\n'.format(search[0].id,search[0].title,search[0].overview,search[0].vote_average)
        img=search[0].poster_path

        #inserting records to database
        records.insert_one(dict(response.parameters))
        
        return result,img

    else:
        return response.fulfillment_text,img
Ejemplo n.º 27
0
    def show_addmovie(self, inputdata):
        from tmdbv3api import TMDb, Movie
        tmdb = TMDb()
        tmdb.api_key = '1437062848d1dda19bd3907cf120e9f4'
        tmdb.language = 'en'

        if inputdata == "":
            msg = QtWidgets.QMessageBox()
            msg.setIcon(QtWidgets.QMessageBox.Information)
            msg.setText("{0}".format("กรุณากรอกข้อมูล"))
            msg.setWindowTitle("Messages")
            msg.exec_()
        else:
            movie = Movie()
            search = movie.search(inputdata)
            countrow = len(search)
            self.tableAddmovie.setRowCount(countrow)
            i = 0
            for res in search:
                movie_title = res.title
                self.tableAddmovie.setItem(
                    i, 0, QtWidgets.QTableWidgetItem(movie_title))
                i = i + 1
Ejemplo n.º 28
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)
def movie(name):
    movie = Movie()
    search = movie.search(name)
    for res in search:
        x = res.id
        print(x)
        break

    recommendations = movie.recommendations(movie_id=x)
    oh = []
    num = 0
    for some in recommendations:
        if num >= 6:
            break

        a = (some.title)
        b = (some.poster_path)
        c = (some.vote_average)
        d = (some.release_date)
        e = (some.vote_count)
        final_dict = {'name': a, 'link': b, 'vote': c, 'date': d, 'count': e}
        oh.append(final_dict)
        num = num + 1
    return oh
Ejemplo n.º 30
0
def search_movie_api(request):
    movie_title = request.POST.get("movie_title")

    tmdb = TMDb()
    tmdb.api_key = 'd624f6311529ea50a6238e7d7296610a'
    tmdb.language = 'ja-JA'

    movie = Movie()
    search = movie.search(movie_title)

    movie_genres = MovieGenreM.objects

    movie_list = []
    for res in search:
        genre_names = None
        for genre_id in res.genre_ids:
            movie_genre = movie_genres.get(movie_genre_id=genre_id)
            if genre_names:
                genre_names = genre_names + ',' + movie_genre.movie_genre_name
            else:
                genre_names = movie_genre.movie_genre_name

        d = {
            'id': res.id,
            'title': res.title,
            'release_date': res.release_date,
            'genre_ids': res.genre_ids,
            'genre_names': genre_names,
            'summary': res.overview.replace('"', '').replace("'", "")
        }
        movie_list.append(d)

    movie_list.sort(key=lambda x: x['release_date'])
    movie_list_json = json.dumps(movie_list)

    return HttpResponse(movie_list_json)
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.º 32
0
    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}
        except IndexError:
            print("NULL")

            obj |= {'img': "NULL"}

    elif (obj['type'] == "Movie"):

        m = movie.search(obj['title'])

        try:
            print(m[0].title)
            print(m[0].poster_path)

            obj |= {'img': m[0].poster_path}
        except IndexError:
            print("NULL")

            obj |= {'img': "NULL"}

with open('./everything.json', 'w', encoding='utf-8') as outfile:
    json.dump(file, outfile, indent=2, ensure_ascii=False)