コード例 #1
0
def index():
    # discover = 'https://api.themoviedb.org/3/discover/movie'
    # '''
    #     Allowed Values: , popularity.asc, popularity.desc, release_date.asc, release_date.desc, revenue.asc, revenue.desc, primary_release_date.asc, primary_release_date.desc, original_title.asc, original_title.desc, vote_average.asc, vote_average.desc, vote_count.asc, vote_count.desc
    #     default: popularity.desc
    # '''
    # parameters = dict(
    #     api_key=apikey,
    #     language='es-ES'
    #     # sort_by='release_date.desc'
    # )
    # resp = requests.get(url=discover, params=parameters)
    # data = json.loads(resp.text)

    # print(data['page'])
    # print(data['total_results'])
    # print(data['total_pages'])

    discover = Discover()
    movie = discover.discover_movies({
        'sort_by': 'popularity.desc',
        'language': 'es-ES'
    })

    # return render_template('pagina/index.html', posts=data['results'])
    return render_template('pagina/index.html', peliculas=movie)
コード例 #2
0
def main(request):
	movie = Movie()
	d = Discover()
	popular_movies = serialize_movie_array(movie.popular(),10)
	playing_now = serialize_movie_array(movie.now_playing(),10)
	hindi_movies = serialize_hindi_movie(d.discover_movies({"with_original_language":"hi",'vote_count.gte': 100, 'sort_by': 'vote_average.desc'})[:10])
	return render(request, 'index.html', {'popular_movies':popular_movies, 'playing_now':playing_now, 'hindi_movies':hindi_movies})
コード例 #3
0
class DiscoverTests(unittest.TestCase):
    def setUp(self):
        self.tmdb = TMDb()
        self.tmdb.api_key = os.environ["TMDB_API_KEY"]
        self.tmdb.language = "en-US"
        self.tmdb.debug = True
        self.tmdb.wait_on_rate_limit = True
        self.tmdb.cache = False
        self.discover = Discover()

    def test_get_discover_movies(self):
        discover = self.discover.discover_movies({
            "primary_release_year": "2015",
            "with_genres": "28",
            "vote_average.gte": "8",
            "page": "1"
        })
        self.assertGreater(len(discover), 0)
        self.assertTrue(hasattr(discover[0], "id"))
        self.assertGreaterEqual(discover[0].vote_average, 8)
        self.assertIn(28, discover[0].genre_ids)

    def test_get_discover_tv_shows(self):
        discover = self.discover.discover_tv_shows({
            "with_genres": "16",
            "vote_average.gte": "8",
            "page": "1"
        })
        self.assertGreater(len(discover), 0)
        self.assertTrue(hasattr(discover[0], "id"))
        self.assertGreaterEqual(discover[0].vote_average, 8)
        self.assertIn(16, discover[0].genre_ids)
コード例 #4
0
def TMDB_rec(genre='action'):
    genre_map = genre_builder()

    # Sanity check
    if genre not in genre_map:
        genre = 'action'

    discovery = Discover()
    movie = discovery.discover_movies({
        'sort_by': 'popularity.desc',
        'with_genres': genre_map[genre]
    })
    movie_rec = movie[0]

    movie_json = {
        "movie": {
            "title": movie[0]['original_title'],
            "rating": int(float(movie[0]['vote_average']) / 2),
            "summary": movie[0]['overview'],
            "genre": genre
        }
    }

    if API_DEBUG:
        print(movie_json)

    return movie_json
コード例 #5
0
ファイル: db.py プロジェクト: andresryes/love-my-movies
    def getMovies(self):
        tmdb = TMDb()
        tmdb.api_key = '1dc5bcb73c0781470cb348d5e02a05a5'
        tmdb.language = 'en'
        tmdb.debug = False

        movie = Movie()
        self.movie = movie
        self.popular = movie.popular()
        self.now = movie.now_playing()
        self.top = movie.top_rated()

        discover = Discover()
        self.movie_discovered = discover.discover_movies(
            {'sort_by': 'vote_average.desc'})

        lists = [self.top, self.now, self.popular, self.movie_discovered]
        self.all_movies = []

        for li in lists:
            for m in li:
                exist = False
                for r in self.all_movies:
                    if r.id == m.id:
                        exist = True
                if (not exist):
                    self.all_movies.append(m)
コード例 #6
0
ファイル: prune.py プロジェクト: saubhagyashrestha/NLP-CS-337
def movie_list_gen(year):
    year_int = int(year)
    last_year = str(year_int - 1)
    start_date = str(last_year) + '-01-01'
    end_date = str(last_year) + '-12-31'
    discover = Discover()
    count = 1
    mov_list = []
    while (count < 12):
        curr_list = discover.discover_movies({
            'primary_release_year': last_year,
            'page': count
        })
        mov_list.append(curr_list)
        count += 1
    count = 0
    while (count < 10):
        curr_list = discover.discover_tv_shows({
            'air_date.gte': start_date,
            'air_date.lte': end_date
        })
        mov_list.append(curr_list)
        count += 1

    flat_list = []
    for sublist in mov_list:
        for item in sublist:
            flat_list.append(item)
    mov_list = flat_list
    return mov_list
コード例 #7
0
 def scrap_movie_by_rating(self, start, stop):
     discover = Discover()
     movie = discover.discover_movies({
         'vote_average.gte': start,
         'vote_average.lte': stop
     })
     for m in movie:
         self.set_data(m)
コード例 #8
0
    def discoverMedia(self, start_date, end_date):
        sd_str = datetime.strftime(start_date, '%Y-%m-%d')
        ed_str = datetime.strftime(end_date, '%Y-%m-%d')
        tmdb = TMDb()
        tmdb.api_key = tmdb_key
        tmdb.language = 'en'

        discover = Discover()
        movies = discover.discover_movies({
            'primary_release_date.gte': sd_str,
            'primary_release_date.lte': ed_str
        })

        for res in movies:
            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
                )

        
        series = discover.discover_tv_shows({
            'first_air_date.gte': sd_str,
            'first_air_date.lte': ed_str
        })

        for res in series:
            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
                )
コード例 #9
0
 def scrap_movie_by_year(self, start, stop):
     discover = Discover()
     discover_params = dict()
     if start:
         gte_year = datetime.strptime(str(start), "%Y")
         discover_params['primary_release_date.gte'] = gte_year
     if stop:
         lte_year = datetime.strptime(str(stop), "%Y")
         discover_params['primary_release_date.lte'] = lte_year
     try:
         movie = discover.discover_movies(discover_params)
         for m in movie:
             self.set_data(m)
     except Exception as e:
         raise TMDbException("Connection error to imdb api server")
コード例 #10
0
ファイル: tmdb.py プロジェクト: LowerDeez/movies_finder
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()
コード例 #11
0
def movie_list(request):
    if request.method == 'GET':
        form = ReleaseForm()
        return render(request, 'movie_list.html', {'form': form})
    elif request.method == 'POST':
        form = ReleaseForm(request.POST)
        if form.is_valid():
            release_date_gte = request.POST.get('start', '2017-11-01')
            release_date_lte = request.POST.get('end', '2017-12-01')
            tmdb = TMDb()
            tmdb.api_key = os.environ['KEY-MDB']
            discover = Discover()
            movies = discover.discover_movies({
                'primary_release_date.gte':
                release_date_gte,
                'primary_release_date.lte':
                release_date_lte,
            })

            db, token, uid = initializationDb()
            for movie in movies:
                data = {
                    "id": movie.id,
                    "title": movie.title,
                    "overview": movie.overview,
                    "poster_path": movie.poster_path,
                    "release_date": movie.release_date,
                    "popularity": movie.popularity,
                    "original_title": movie.original_title,
                    "vote_count": movie.vote_count,
                    "vote_average": movie.vote_average
                }
                db.child(uid).child("movie_list").child(movie.id).set(
                    data, token)
            response = {"status": 200, "message": "Success Save"}
            return JsonResponse(response)
        else:
            response = {"status": 401, "message": "Invalid Input"}
            return JsonResponse(response)
コード例 #12
0
def post_movie(api, cgi='27'):
    # Choose Genre
    cgi = random.choice(list(dict.keys()))

    # Create recommendation
    discover = Discover()
    movie = discover.discover_movies({'with_genres': cgi, 'with_original_language': 'en', 'release_date.lte': '2020-02-02', \
        'vote_average.gte': '7', 'vote_count.gte': '100', 'page': str(random.randint(1, 5))})
    rec = random.choice(movie)

    # Get IMDB ID
    movieimd = Movie()
    imd = movieimd.details(rec.id)

    # Create hashtags
    namehash = '#' + re.sub(r'\W+', '', rec.title)
    genhash = '#' + re.sub(r'\W+', '', dict[str(rec.genre_ids[0])])

    # Create post string
    tweet = '𝗧𝗶𝘁𝗹𝗲: ' + rec.title + '\n𝗚𝗲𝗻𝗿𝗲: ' + dict[str(rec.genre_ids[0])] + '\n𝗬𝗲𝗮𝗿: ' + rec.release_date[0:4] + \
        '\n𝗦𝗰𝗼𝗿𝗲: ' + str(int(rec.vote_average*10)) + "%" + '\n\nWas it worth the watch? ' + namehash + ' ' + genhash + \
        '\nhttps://www.imdb.com/title/' + imd.imdb_id

    return tweet
コード例 #13
0
def top_war_list():
    ids = []
    mov = discover.discover_movies({
        'sort_by': 'popularity.desc',
        'genre_ids': [10752]
    })
    for i in mov:
        id = omdb_parse.title_search(mov.title)[0]
        ids.append(id)
    return ids


""""""
discover = Discover()
mov_ = discover.discover_movies({
    'sort_by': 'popularity.desc',
    'genre_ids': [1, 2, 4]
})

print(mov_)
"""
genres' id's
action 28
animated 16
documentary 99
drama 18
family 10751
fantasy 14
history 36
comedy 35
war 10752
crime 80
コード例 #14
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()
        self.list = List()

    def test_get_tv_keywords(self):
        keywords = self.tv.keywords(1396)
        self.assertGreater(len(keywords), 0)

    def test_get_tv_reviews(self):
        reviews = self.tv.reviews(1396)
        self.assertGreater(len(reviews), 0)

    def test_get_movie_repr(self):
        search = self.movie.search("Mad Max")
        for results in search:
            print(results)

    def test_get_tv_show_repr(self):
        search_tv = self.tv.search("Breaking Bad")
        for results in search_tv:
            print(results)

    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_credits(self):
        credits = self.movie.credits(111)
        print(credits)
        self.assertIsNotNone(credits)

    def test_get_movie_images(self):
        images = self.movie.images(111)
        print(images)
        self.assertIsNotNone(images)

    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_on_the_air(self):
        show = self.tv.on_the_air()
        self.assertTrue(len(show) > 0)

    def test_airing_today(self):
        show = self.tv.on_the_air()
        self.assertTrue(len(show) > 0)

    def test_tv_videos(self):
        show = self.tv.videos(1396)
        self.assertTrue(len(show) > 0)

    def test_tv_recommendations(self):
        show = self.tv.recommendations(1396)
        self.assertTrue(len(show) > 0)

    def test_external_ids(self):
        show = self.tv.external_ids(1776)
        self.assertEqual(show["imdb_id"], "tt0488262")

    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 Ltd.")

    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)
        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")

    def test_get_list(self):
        list = self.list.details(list_id="112870")
        self.assertTrue(len(list) > 10)
        self.assertTrue(hasattr(list[0], "id"))
        self.assertTrue(hasattr(list[0], "title"))

    def test_get_certifications(self):
        certifications = Certification()
        movie_certifications = certifications.movie_list()
        self.assertIsNotNone(movie_certifications)
        tv_certifications = certifications.tv_list()
        self.assertIsNotNone(tv_certifications)
コード例 #15
0
def process_text(input, intent, request=None):
    try:
        if intent == 'word':
            open_application('word')
        if intent == 'firefox':
            open_application('firefox')
        if intent == 'youtube':
            assistant_speaks('Sure. Tell me what do you want to search for')
            ans = get_audio()
            result = parse_stopwords(ans)
            search_web('youtube ' + result)
        if intent == 'knowledge':
            if 'about' in input:
                parse_text(input, 'about')
            if 'what is' in input:
                parse_text(input, 'is')
            if 'who was' in input:
                parse_text(input, 'was')
        if intent == 'web_search':
            if 'about' in input:
                ans = input
                indx = ans.split().index('about')
                query = ans.split()[indx + 1:]
                string_query = ' '.join(query)
                result = parse_stopwords(string_query)
                search_web('google ' + result)
            if 'for' in input:
                ans = input
                indx = ans.split().index('for')
                query = ans.split()[indx + 1:]
                string_query = ' '.join(query)
                result = parse_stopwords(string_query)
                search_web('google ' + result)
            assistant_speaks('Going back to the main interface')
        movie_list_intents = ['movie', 'horror', 'action', 'comedy', 'popular', 'thriller']
        if intent in movie_list_intents:
            from tmdbv3api import Movie

            movie = Movie()
            discover = Discover()
            if intent == 'popular':
                pop_movie = discover.discover_movies({
                    'sort_by': 'popularity.desc'
                })
                assistant_speaks("The most popular 5 movies are the following")
                pop_movies = ", ".join(str(x) for x in pop_movie[0:5])
                assistant_speaks(pop_movies)
            if intent == 'horror':
                parse_movies(27, discover, movie, 'horror')
            if intent == 'action':
                parse_movies(28, discover, movie, 'action')
            if intent == 'comedy':
                parse_movies(35, discover, movie, 'comedy')
            if intent == 'thriller':
                parse_movies(53, discover, movie, 'thriller')
            if intent == 'movie':
                assistant_speaks('Do you want a movie recommendation based on your favorite movie?')
                ans = get_audio()
                if 'yes' in ans:
                    try:
                        pacient = Pacient.objects.get(user=request.user)
                    except:
                        assistant_speaks('it looks like you have not discussed that with me. '
                                         'please enter discussion module first')
                    pac_details = PacientDetails.objects.get(pacient=pacient)
                    fav_movie = pac_details.fav_movie
                    search_movie = movie.search(fav_movie)
                    assistant_speaks('I will read top three recommended movies based on your favorite movie')
                    res = search_movie[0]
                    recommendations = movie.recommendations(movie_id=res.id)
                    cnt = 0
                    for recommendation in recommendations:
                        if cnt >= 3:
                            break
                        else:
                            assistant_speaks(recommendation.title)
                            assistant_speaks(recommendation.overview)
                        cnt += 1

                    assistant_speaks('Exiting movie module')
                else:
                    assistant_speaks(
                        'I can give you the top movies based on a genre. Just tell me what are you looking for')
                    ans = get_audio()
                    res, ints = chatbot_response(ans)
                    process_text(ans, ints)

        pacient = Pacient.objects.get(user=request.user)
        pac_pars = PacientParsing.objects.get(pacient=pacient)
        if intent == 'event':
            from googleapiclient.discovery import build
            from google_auth_oauthlib.flow import InstalledAppFlow
            scopes = ['https://www.googleapis.com/auth/calendar']
            flow = InstalledAppFlow.from_client_secrets_file("client_secret.json", scopes=scopes)
            credentials = flow.run_console()
            pickle.dump(credentials, open("token.pkl", "wb"))
            credentials = pickle.load(open("token.pkl", "rb"))
            service = build("calendar", "v3", credentials=credentials)

            calendarlist = service.calendarList().list().execute()
            calendar_id = calendarlist['items'][0]['id']
            result = service.events().list(calendarId=calendar_id, timeZone="Europe/Bucharest").execute()

            timp_event = get_audio()

            assistant_speaks("What about the name of the event?")
            name = get_audio()

            assistant_speaks("would you like to add a description?")
            ans = get_audio()
            sub_resp, sub_intent = chatbot_response(ans)
            if sub_intent == 'yes':
                assistant_speaks("please tell me the description")
                desc = get_audio()
                assistant_speaks("should i add a location too?")
                ans = get_audio()
                sub_resp, sub_intent = chatbot_response(ans)
                if sub_intent == 'yes':
                    assistant_speaks("Go ahead, tell me the location")
                    location = get_audio()
                    create_event(service, timp_event, name, 1, desc, location)
                elif sub_intent == 'no':
                    create_event(service, timp_event, name, 1, desc)
            elif sub_intent == 'no':
                create_event(service, timp_event, name)
            assistant_speaks('Event ' + name + ' created.')
            assistant_speaks('Exiting event module')
        if intent == 'web':
            ans = get_audio()
            result = parse_stopwords(ans)
            search_web('google ' + result)
            assistant_speaks('Exiting web module')
        if intent == 'discussion':
            assistant_speaks('Is there a certain topic you would like to discuss?')
            ans = get_audio()
            # print(ans)
            sub_resp, sub_intent = chatbot_response(ans)
            # print(sub_intent)
            if sub_intent == 'no':
                assistant_speaks('Then how about you tell me more about yourself?')
                try:
                    pac_details = PacientDetails.objects.get(pacient=pacient)
                except PacientDetails.DoesNotExist:
                    pac_details = PacientDetails.objects.create(pacient=pacient)
                if pac_details.fav_activity == '':
                    assistant_speaks('Tell me your favorite activity')
                    ans = get_audio()
                    if "don't" not in ans or 'no' not in ans:
                        ans = parse_details(ans)
                        # print(ans)
                        pac_details.fav_activity = ans
                        pac_details.save()
                if pac_details.fav_movie == '':
                    assistant_speaks('what about your favorite movie?')
                    ans = get_audio()
                    if "don't" not in ans or 'no' not in ans:
                        ans = parse_details(ans)
                        pac_details.fav_movie = ans
                        pac_details.save()
                if pac_details.fav_game == '':
                    assistant_speaks('Tell me your favorite game')
                    ans = get_audio()
                    if "don't" not in ans or 'no' not in ans:
                        ans = parse_details(ans)
                        pac_details.fav_game = ans
                        pac_details.save()
                if pac_details.fav_passion == '':
                    assistant_speaks('Do you have a favorite passion?')
                    ans = get_audio()
                    if "don't" not in ans or 'no' not in ans:
                        ans = parse_details(ans)
                        pac_details.fav_passion = ans
                        pac_details.save()
                if pac_details.fav_song == '':
                    assistant_speaks('What is your favorite song?')
                    ans = get_audio()
                    if "don't" not in ans or 'no' not in ans:
                        ans = parse_details(ans)
                        pac_details.fav_song = ans
                        pac_details.save()
                if pac_details.fav_book == '':
                    assistant_speaks('And your favorite book is?')
                    ans = get_audio()
                    if "don't" not in ans or 'no' not in ans:
                        ans = parse_details(ans)
                        pac_details.fav_book = ans
                        pac_details.save()
                assistant_speaks("How was your day so far? When you have finished talking, please say that's it")
                r = sr.Recognizer()
                list = []
                happy_list = ['That sounds great !', 'Wow, I am glad for you', 'Good job!', 'This sounds awesome']
                neutral_list = ['Okay, continue', 'Understood', 'What next?', 'Is there something more?']
                sad_list = ['What is the specific reason that made you feel this way? Please keep it short',
                            'Can you please tell me what is the root of the problem? Please keep it short',
                            'what disturbed you that much? Please keep it short']
                with sr.Microphone() as source:
                    while (1):
                        try:
                            print('Listening to your day: ')
                            audio = r.listen(source)
                            text = r.recognize_google(audio, language='en-US')
                            blob1 = TextBlob(text)
                            blob1 = blob1.correct()
                            text = text.lower()
                            print(format(blob1.sentiment))
                            if "that's it" in text:
                                break
                            if blob1.polarity < 0:
                                assistant_speaks(random.choice(sad_list))
                                motiv = get_audio_simple()
                                pac_pars._negative_problems += motiv + '\n'
                                pac_pars.contor_mesaje += 1
                                if pac_pars.contor_mesaje % 3 == 0:
                                    pac_pars.contor_mesaje = 0
                                    send_mail(
                                        'Mesaj informare pacient ' + str(pacient),
                                        'Urmatoarele probleme par sa-l afecteze pe pacient: ' + pac_pars._negative_problems,
                                        '*****@*****.**',
                                        ['*****@*****.**'],
                                        fail_silently=False,
                                    )
                                list.append(motiv)
                                pac_pars.save()
                                assistant_speaks('Sorry to hear that, please continue')
                            if blob1.polarity > 0.5:
                                assistant_speaks(random.choice(happy_list))
                            elif blob1.polarity <= 0.5 and blob1.polarity >= 0:
                                assistant_speaks(random.choice(neutral_list))
                        except:
                            continue

                motiv = random.choice(list)
                research_later = "what+to+do+when+" + motiv
                ua = UserAgent()
                google_url = "https://www.google.com/search?q=" + research_later
                response = requests.get(google_url, {"User-Agent": ua.random})
                soup = BeautifulSoup(response.text, "html.parser")
                result_div = soup.find_all('div', attrs={'class': 'ZINbbc'})

                links = []
                titles = []
                descriptions = []
                for r in result_div:
                    # Checks if each element is present, else, raise exception
                    try:
                        link = r.find('a', href=True)
                        title = r.find('div', attrs={'class': 'vvjwJb'}).get_text()
                        description = r.find('div', attrs={'class': 's3v9rd'}).get_text()

                        # Check to make sure everything is present before appending
                        if link != '' and title != '' and description != '':
                            links.append(link['href'])
                            titles.append(title)
                            descriptions.append(description)
                    # Next loop if one element is not present
                    except:
                        continue
                to_remove = []
                clean_links = []
                for i, l in enumerate(links):
                    clean = re.search('\/url\?q\=(.*)\&sa', l)

                    # Anything that doesn't fit the above pattern will be removed
                    if clean is None:
                        to_remove.append(i)
                        continue
                    clean_links.append(clean.group(1))
                # Remove the corresponding titles & descriptions
                # for x in to_remove:
                #     print(titles[x])
                #     print(descriptions[x])
                #     del titles[x]
                #     del descriptions[x]
                random_seed = random.randint(0, 3)
                print('rand_seed: ')
                print(random_seed)
                print('titles: ' + str(len(titles)))
                print('links: ' + str(len(clean_links)))
                assistant_speaks("I have found something regarding the problems you have just told me")
                assistant_speaks("The article title is called")
                assistant_speaks(titles[random_seed])
                assistant_speaks("Do you want me to open the link for you?")
                ans = get_audio()
                sub_resp, sub_intent = chatbot_response(ans)
                if sub_intent == 'yes':
                    driver = webdriver.Firefox()
                    driver.implicitly_wait(1)
                    driver.maximize_window()
                    driver.get(clean_links[random_seed])
                    assistant_speaks('I have opened the browser for you. Exiting discussion module')
                else:
                    assistant_speaks('Exiting discussion module')
                    return
            elif sub_intent == 'yes':
                assistant_speaks('Tell me what do you want to discuss.')
                ans = get_audio()
                res, intent = chatbot_response(ans)
                process_text(ans, intent, request)

        if intent == 'news':
            assistant_speaks("Would you like the news on a specific subject?")
            ans = get_audio()
            newsapi = NewsApiClient(api_key='b71542370a6247d493860e6b01d0d713')
            sub_resp, sub_intent = chatbot_response(ans)
            if sub_intent == 'yes':
                assistant_speaks('What would you like me to search for? Please be as specific as you can.')
                ans = get_audio()
                data = newsapi.get_everything(q=ans, language='en', page_size=5)
                articles = data['articles']
                assistant_speaks(
                    'You could choose one article by saying stop when i finish reading the headline. To continue '
                    'reading the headlines, just say continue. I found the following articles: ')
                for article in articles:
                    title = article['title']
                    url = article['url']
                    content = article['content']
                    assistant_speaks(title)
                    ans = get_audio()
                    if 'continue' in ans:
                        continue
                    elif 'stop' in ans:
                        assistant_speaks('I will read the article content')
                        assistant_speaks(content)
                        assistant_speaks(
                            'I can open the webpage which contains the article source. Do you want me to do that? ')
                        ans = get_audio()
                        sub_resp, sub_intent = chatbot_response(ans)
                        if sub_intent == 'yes':
                            driver = webdriver.Firefox()
                            driver.implicitly_wait(1)
                            driver.maximize_window()
                            driver.get(url)
                            r = sr.Recognizer()
                            assistant_speaks(
                                'I have opened your browser. To resume the articles read, just say resume. '
                                'If you want me to stop, just say stop')
                            with sr.Microphone() as source:
                                while (1):
                                    print('Listening ...')
                                    audio = r.listen(source)
                                    try:
                                        text = r.recognize_google(audio, language='en-US')
                                        if 'resume' in text:
                                            break
                                        elif 'stop' in text:
                                            return
                                    except:
                                        continue
                        elif sub_intent == 'no':
                            assistant_speaks('would you like me to continue reading the next articles?')
                            ans = get_audio()
                            sub_resp, sub_intent = chatbot_response(ans)
                            if sub_intent == 'yes':
                                continue
                            elif sub_intent == 'no':
                                assistant_speaks('If you want to find out more, just let me know. Exiting news module')
                                break
            elif sub_intent == 'no':
                assistant_speaks('Alright, i am going to search for the top headlines')
                url = ('http://newsapi.org/v2/top-headlines?'
                       'country=us&'
                       'apiKey=b71542370a6247d493860e6b01d0d713')
                response = requests.get(url).json()
                articles = response['articles']
                assistant_speaks(
                    'Say stop after I finish reading the headline to tell you its content. To continue reading '
                    'the headlines, just say continue. I found the following articles: ')
                for article in articles:
                    title = article['title']
                    url = article['url']
                    content = article['content']
                    assistant_speaks(title)
                    ans = get_audio()
                    if 'continue' in ans:
                        continue
                    elif 'stop' in ans:
                        assistant_speaks('I will read the article content')
                        assistant_speaks(content)
                        assistant_speaks('I can open the webpage which contains the article source. Do you want me'
                                         ' to do that? ')
                        ans = get_audio()
                        sub_resp, sub_intent = chatbot_response(ans)
                        if sub_intent == 'yes':
                            driver = webdriver.Firefox()
                            driver.implicitly_wait(1)
                            driver.maximize_window()
                            driver.get(url)
                        elif sub_intent == 'no':
                            assistant_speaks('would you like me to continue reading the next articles?')
                            ans = get_audio()
                            sub_resp, sub_intent = chatbot_response(ans)
                            if sub_intent == 'yes':
                                return
                            elif sub_intent == 'no':
                                assistant_speaks('If you want to find out more, just let me know. Exiting news module')
                                break
                    elif 'exit' in ans:
                        break
    except Exception as e:
        print(e)
        assistant_speaks("I don't understand, Can you please repeat?")
        ans = get_audio()
コード例 #16
0
ファイル: tmdb_server.py プロジェクト: Glolf/RottenBanana
class tmdb_base():
    def __init__(self):
        api_key = "e9ee4dd66aa205b259f29ccb98e9a989"
        self.tmdb = TMDb()
        self.tmdb.api_key = api_key
        self.tmdb.language = 'en'
        self.tmdb.debug = True

        self.movie = Movie(self.tmdb)
        self.discover = Discover(self.tmdb)

        # build the genre database
        self.genre = Genre(self.tmdb)
        genres = self.genre.movie_list()  # list
        self.genres_dict = {}  # a dict with keys: genre names and values: id
        for g in genres:
            self.genres_dict[g.name] = g.id

        # build the language database (ISO 639-1)
        self.language_dict = {}
        with open('./csv/language-codes_csv.csv', newline='') as csvfile:
            reader = csv.reader(csvfile, delimiter=',')
            for row in reader:
                self.language_dict[row[1]] = row[0]

        self.person = Person(self.tmdb)
        self.company = Company(self.tmdb)

        # initialize the searching attributes
        self.search_genre = None
        self.search_without_genre = None
        self.search_cast = None
        self.search_crew = None
        self.search_people = None
        self.search_company = None
        self.search_year = None
        self.search_upper_year = None
        self.search_lower_year = None
        self.search_rating = None
        self.search_language = None

    def set_attributes(self, json_):
        """
        given a json from furhat, set the searching attributes
        """
        # conv = json.loads(json_)
        conv = json_
        actor = conv["actors"]["selected"]  # list.
        genre = conv["genres"]["selected"]  # list.
        without_genre = conv["genres"]["deselected"]  # list.
        company = conv["company"]["selected"]  # list.
        language = conv["language"]["selected"]  # list.
        director = conv["director"]["selected"]  # list.
        upper_year = conv["years"]["upper"]  # None or int.
        lower_year = conv["years"]["lower"]  # None or int.
        rating = conv["rating"]  # None or int.

        self.search_upper_year = upper_year
        self.search_lower_year = lower_year
        self.rating = rating

        if len(actor) > 0:
            self.search_cast = actor

        if len(director) > 0:
            self.search_crew = director

        if len(genre) > 0:
            self.search_genre = genre

        if len(without_genre) > 0:
            self.search_without_genre = without_genre

        if len(company) > 0:
            self.search_company = company

        if len(language) > 0:
            self.search_language = language

    def set_language(self, language):
        """
        set the query language, better not change it
        language: sting: English, Spanish, etc
        """

        self.tmdb.language = self.language_dict[str(language).capitalize()]

    def name_to_id(self, names):
        """
        names: List of strings
        return: id: string
        """

        ids = []
        for name in names:
            id_ = self.person.search_id(name)
            if len(id_) > 0:
                ids.append(str(id_[0]))
        return ",".join(ids)

    def genre_to_id(self, genres):
        """
        genres: List of strings
        return: id: string
        """
        ids = []
        for genre in genres:
            id_ = self.genres_dict[str(genre).capitalize()]
            ids.append(str(id_))
        return ",".join(ids)

    def company_to_id(self, companies):
        """
        companies: List of strings
        return: id: string
        """
        ids = []
        for company in companies:
            id_ = self.company.search_id(company)
            if len(id_) > 0:
                id_sorted = sorted([item.id for item in id_])
                ids.append(str(id_sorted[0]))
        return ",".join(ids)

    def language_to_iso_639(self, languages):
        """
        languages: List of strings
        return: languages in ISO 639-1 format: string
        """
        ids = []
        for language in languages:
            id_ = self.language_dict[str(language).capitalize()]
            ids.append(id_)
        return ",".join(ids)

    def search_movies(self, top=10):
        """
        with_genres: string: Comma separated value of genre ids that you want to include in the results.
        without_genres: string: Comma separated value of genre ids that you want to exclude from the results.
        with_cast: string: A comma separated list of person ID's. Only include movies that have one of the ID's added as an actor.
        with_crew: string: A comma separated list of person ID's. Only include movies that have one of the ID's added as a crew member.
        with_people: string: A comma separated list of person ID's. Only include movies that have one of the ID's added as a either a actor or a crew member.
        with_companies: string: A comma separated list of production company ID's. Only include movies that have one of the ID's added as a production company.
        year: integer: A filter to limit the results to a specific year (looking at all release dates).
        release_date.gte: string (year-month-day): Filter and only include movies that have a release date (looking at all release dates) that is greater or equal to the specified value.
        release_date.lte: string (year-month-day): Filter and only include movies that have a release date (looking at all release dates) that is less than or equal to the specified value.
        vote_average.gte: number: Filter and only include movies that have a rating that is greater or equal to the specified value.
        with_original_language: string: Specify an ISO 639-1 string to filter results by their original language value.
        """
        request_dic = {}
        request_dic['sort_by'] = 'vote_average.desc'
        request_dic['vote_count.gte'] = 10

        if self.search_genre is not None:
            request_dic['with_genres'] = self.genre_to_id(self.search_genre)
        if self.search_without_genre is not None:
            request_dic['without_genres'] = self.genre_to_id(
                self.search_without_genre)
        if self.search_year is not None:
            request_dic['year'] = self.search_year
        else:
            if self.search_upper_year is not None:
                request_dic['release_date.lte'] = str(
                    self.search_upper_year) + "-12-31"
            if self.search_lower_year is not None:
                request_dic['release_date.gte'] = str(
                    self.search_lower_year) + "-01-01"

        if self.search_rating is not None:
            request_dic['vote_average.gte'] = self.search_rating
        if self.search_company is not None:
            request_dic['with_companies'] = self.company_to_id(
                self.search_company)

        if self.search_cast is not None:
            request_dic['with_cast'] = self.name_to_id(self.search_cast)
        elif self.search_crew is not None:
            request_dic['with_crew'] = self.name_to_id(self.search_crew)
        elif self.search_people is not None:
            request_dic['with_people'] = self.name_to_id(self.search_people)

        if self.search_language is not None:
            request_dic['with_original_language'] = self.language_to_iso_639(
                self.search_language)

        show = self.discover.discover_movies(request_dic)

        # return the top 10 list by default
        return [str(item) for item in show[:top]]
コード例 #17
0
def tmdb_get_movies(config_path, plex, data, method):
    t_movs = []
    t_movie = Movie()
    t_movie.api_key = config_tools.TMDB(config_path).apikey  # Set TMDb api key for Movie
    if t_movie.api_key == "None":
        raise KeyError("Invalid TMDb API Key")

    count = 0
    if method == "tmdb_discover":
        discover = Discover()
        discover.api_key = t_movie.api_key
        discover.discover_movies(data)
        total_pages = int(os.environ["total_pages"])
        total_results = int(os.environ["total_results"])
        limit = int(data.pop('limit'))
        amount = total_results if total_results < limit else limit
        print("| Processing {}: {} items".format(method, amount))
        for attr, value in data.items():
            print("|            {}: {}".format(attr, value))
        for x in range(total_pages):
            data["page"] = x + 1
            tmdb_movies = discover.discover_movies(data)
            for tmovie in tmdb_movies:
                count += 1
                t_movs.append(tmovie.id)
                if count == amount:
                    break
            if count == amount:
                break
    elif method in ["tmdb_popular", "tmdb_top_rated", "tmdb_now_playing", "tmdb_trending_daily", "tmdb_trending_weekly"]:
        #trending = Trending()                  #TURNON:Trending
        #trending.api_key = t_movie.api_key     #TURNON:Trending
        for x in range(int(data / 20) + 1):
            if method == "tmdb_popular":
                tmdb_movies = t_movie.popular(x + 1)
            elif method == "tmdb_top_rated":
                tmdb_movies = t_movie.top_rated(x + 1)
            elif method == "tmdb_now_playing":
                tmdb_movies = t_movie.now_playing(x + 1)
            #elif method == "tmdb_trending_daily":          #TURNON:Trending
            #    tmdb_movies = trending.movie_day(x + 1)    #TURNON:Trending
            #elif method == "tmdb_trending_weekly":         #TURNON:Trending
            #    tmdb_movies = trending.movie_week(x + 1)   #TURNON:Trending
            for tmovie in tmdb_movies:
                count += 1
                t_movs.append(tmovie.id)
                if count == data:
                    break
            if count == data:
                break
        print("| Processing {}: {} Items".format(method, data))
    else:
        tmdb_id = int(data)
        if method == "tmdb_list":
            tmdb = List()
            tmdb.api_key = t_movie.api_key
            try:
                t_col = tmdb.details(tmdb_id)
                tmdb_name = str(t_col)
                for tmovie in t_col:
                    if tmovie.media_type == "movie":
                        t_movs.append(tmovie.id)
            except:
                raise ValueError("| Config Error: TMDb List: {} not found".format(tmdb_id))
        elif method == "tmdb_company":
            tmdb = Company()
            tmdb.api_key = t_movie.api_key
            tmdb_name = str(tmdb.details(tmdb_id))
            company_movies = tmdb.movies(tmdb_id)
            for tmovie in company_movies:
                t_movs.append(tmovie.id)
        else:
            tmdb = Collection()
            tmdb.api_key = t_movie.api_key
            t_col = tmdb.details(tmdb_id)
            tmdb_name = str(t_col)
            try:
                for tmovie in t_col.parts:
                    t_movs.append(tmovie['id'])
            except AttributeError:
                try:
                    t_movie.details(tmdb_id).imdb_id
                    tmdb_name = str(t_movie.details(tmdb_id))
                    t_movs.append(tmdb_id)
                except:
                    raise ValueError("| Config Error: TMDb ID: {} not found".format(tmdb_id))
        print("| Processing {}: ({}) {}".format(method, tmdb_id, tmdb_name))


    # Create dictionary of movies and their guid
    # GUIDs reference from which source Plex has pulled the metadata
    p_m_map = {}
    p_movies = plex.Library.all()
    for m in p_movies:
        guid = m.guid
        if "themoviedb://" in guid:
            guid = guid.split('themoviedb://')[1].split('?')[0]
        elif "imdb://" in guid:
            guid = guid.split('imdb://')[1].split('?')[0]
        elif "plex://" in guid:
            guid = guid.split('plex://')[1].split('?')[0]
        else:
            guid = "None"
        p_m_map[m] = guid

    matched = []
    missing = []
    plex_tools.create_cache(config_path)
    # We want to search for a match first to limit TMDb API calls
    # Too many rapid calls can cause a momentary block
    # If needed in future maybe add a delay after x calls to let the limit reset
    for mid in t_movs:  # For each TMBd ID in TMBd Collection
        match = False
        for m in p_m_map:  # For each movie in Plex
            item = m
            agent_type = urlparse(m.guid).scheme.split('.')[-1]
            # Plex movie agent
            if agent_type == 'plex':
                # Check cache for tmdb_id
                tmdb_id = plex_tools.query_cache(config_path, item.guid, 'tmdb_id')
                imdb_id = plex_tools.query_cache(config_path, item.guid, 'imdb_id')
                if not tmdb_id:
                    imdb_id, tmdb_id = plex_tools.alt_id_lookup(plex, item)
                    print("| Cache | + | {} | {} | {} | {}".format(item.guid, imdb_id, tmdb_id, item.title))
                    plex_tools.update_cache(config_path, item.guid, imdb_id=imdb_id, tmdb_id=tmdb_id)
                if int(tmdb_id) == int(mid):
                    match = True
                    break
            elif agent_type == 'themoviedb':
                if int(p_m_map[m]) == int(mid):
                    match = True
                    break
            elif agent_type == 'imdb':
                imdb_id = t_movie.details(mid).imdb_id
                for m in p_m_map:
                    if "tt" in p_m_map[m]:
                        if p_m_map[m] == imdb_id:
                            match = True
                            break
        if match:
            matched.append(m)
        else:
            # Duplicate TMDb call?
            missing.append(t_movie.details(mid).imdb_id)

    return matched, missing
コード例 #18
0
ファイル: tests.py プロジェクト: rickyklu/tmdbv3api
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")
コード例 #19
0
def tmdb_get_movies(config_path, plex, plex_map, data, method):
    t_movs = []
    t_movie = Movie()
    t_movie.api_key = config_tools.TMDB(
        config_path).apikey  # Set TMDb api key for Movie
    if t_movie.api_key == "None":
        raise KeyError("Invalid TMDb API Key")

    count = 0
    if method == "tmdb_discover":
        attrs = data.copy()
        discover = Discover()
        discover.api_key = t_movie.api_key
        discover.discover_movies(attrs)
        total_pages = int(os.environ["total_pages"])
        total_results = int(os.environ["total_results"])
        limit = int(attrs.pop('limit'))
        amount = total_results if limit == 0 or total_results < limit else limit
        print("| Processing {}: {} movies".format(method, amount))
        for attr, value in attrs.items():
            print("|            {}: {}".format(attr, value))
        for x in range(total_pages):
            attrs["page"] = x + 1
            tmdb_movies = discover.discover_movies(attrs)
            for tmovie in tmdb_movies:
                count += 1
                t_movs.append(tmovie.id)
                if count == amount:
                    break
            if count == amount:
                break
    elif method in [
            "tmdb_popular", "tmdb_top_rated", "tmdb_now_playing",
            "tmdb_trending_daily", "tmdb_trending_weekly"
    ]:
        trending = Trending()
        trending.api_key = t_movie.api_key
        for x in range(int(int(data) / 20) + 1):
            if method == "tmdb_popular":
                tmdb_movies = t_movie.popular(x + 1)
            elif method == "tmdb_top_rated":
                tmdb_movies = t_movie.top_rated(x + 1)
            elif method == "tmdb_now_playing":
                tmdb_movies = t_movie.now_playing(x + 1)
            elif method == "tmdb_trending_daily":
                tmdb_movies = trending.movie_day(x + 1)
            elif method == "tmdb_trending_weekly":
                tmdb_movies = trending.movie_week(x + 1)
            for tmovie in tmdb_movies:
                count += 1
                t_movs.append(tmovie.id)
                if count == data:
                    break
            if count == data:
                break
        print("| Processing {}: {} Items".format(method, data))
    else:
        tmdb_id = int(data)
        if method == "tmdb_list":
            tmdb = List()
            tmdb.api_key = t_movie.api_key
            try:
                t_col = tmdb.details(tmdb_id)
                tmdb_name = str(t_col)
                for tmovie in t_col:
                    if tmovie.media_type == "movie":
                        t_movs.append(tmovie.id)
            except:
                raise ValueError(
                    "| Config Error: TMDb List: {} not found".format(tmdb_id))
        elif method == "tmdb_company":
            tmdb = Company()
            tmdb.api_key = t_movie.api_key
            tmdb_name = str(tmdb.details(tmdb_id))
            company_movies = tmdb.movies(tmdb_id)
            for tmovie in company_movies:
                t_movs.append(tmovie.id)
        else:
            tmdb = Collection()
            tmdb.api_key = t_movie.api_key
            t_col = tmdb.details(tmdb_id)
            tmdb_name = str(t_col)
            try:
                for tmovie in t_col.parts:
                    t_movs.append(tmovie['id'])
            except AttributeError:
                try:
                    t_movie.details(tmdb_id).imdb_id
                    tmdb_name = str(t_movie.details(tmdb_id))
                    t_movs.append(tmdb_id)
                except:
                    raise ValueError(
                        "| Config Error: TMDb ID: {} not found".format(
                            tmdb_id))
        print("| Processing {}: ({}) {}".format(method, tmdb_id, tmdb_name))

    matched = []
    missing = []
    for mid in t_movs:
        mid = str(mid)
        if mid in plex_map:
            matched.append(plex.Server.fetchItem(plex_map[mid]))
        else:
            missing.append(mid)

    return matched, missing
コード例 #20
0
ファイル: app.py プロジェクト: danielvichinyan/CinemaHub
tmdb = TMDb()
tmdb.api_key = '05cc17ca0628a5f323435aca06f0a782'

tmdb.language = 'en'
tmdb.debug = True

movie = Movie()

discover = Discover()

for i in range(1, 10):

    movie = discover.discover_movies({
        'primary_release_date.gte': '2020-01-20',
        'primary_release_date.lte': '2020-07-18',
        'page': i
    })

    print(movie)
    for p in movie:
        print(p.id)
        print(p.title)
        print(p.overview)
        if p.poster_path:
            poster_path = "https://image.tmdb.org/t/p/w500" + p.poster_path
        else:
            poster_path = "NULL"
        print(p.release_date)
        sql = "INSERT INTO Movies (TITLE, OVERVIEW, POSTER, RELEASE_DATE) VALUES (%s, %s, %s, %s)"
        val = (p.title, p.overview, poster_path, p.release_date)