def __init__(self): self.tmdb = TMDb() self.tmdb.api_key = "e00b72174e4ae097af808f34a8f220fc" self.tv = TV() self.season = Season() self.movie = Movie() self.discover = Discover()
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)
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 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)
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
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
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})
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 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)
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 )
def setUp(self): self.tmdb = TMDb() self.tmdb.api_key = os.environ['api_key'] self.movie = Movie() self.discover = Discover() self.tv = TV() self.person = Person() self.collection = Collection() self.company = Company() self.season = Season()
def 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 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")
def setUp(self): self.tmdb = TMDb() self.tmdb.api_key = os.environ["TMDB_API_KEY"] self.tmdb.language = "en" self.tmdb.debug = True self.tmdb.wait_on_rate_limit = True self.movie = Movie() self.discover = Discover() self.tv = TV() self.person = Person() self.collection = Collection() self.company = Company() self.network = Network() self.search = Search() self.season = Season() self.list = List()
def 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)
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 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
from tmdbv3api import TMDb, Movie, Discover import omdb_parse tmdb = TMDb() tmdb.api_key = 'b708e47bb2b4e1f533b18723ce7234bf' tmdb.language = 'en' discover = Discover() movie = Movie() def popular_list(): ids_popular = [] popular_titles = movie.popular() for p in popular_titles: id_popular = omdb_parse.title_search(p.title)[0] ids_popular.append(id_popular) return ids_popular """""" def top_family_list(): ids = [] mov = discover.discover_movies({ 'sort_by': 'popularity.desc', 'genre_ids': [10751] }) for i in range(20):
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
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()
def tmdb_get_shows(config_path, plex, plex_map, data, method): config_tools.TraktClient(config_path) t_tvs = [] t_tv = TV() t_tv.api_key = config_tools.TMDB(config_path).apikey if t_tv.api_key == "None": raise KeyError("Invalid TMDb API Key") count = 0 if method in ["tmdb_discover", "tmdb_company", "tmdb_network"]: if method in ["tmdb_company", "tmdb_network"]: tmdb = Company() if method == "tmdb_company" else Network() tmdb.api_key = t_tv.api_key tmdb_id = int(data) tmdb_name = str(tmdb.details(tmdb_id)) discover_method = "with_companies" if method == "tmdb_company" else "with_networks" attrs = {discover_method: tmdb_id} limit = 0 else: attrs = data.copy() limit = int(attrs.pop('limit')) discover = Discover() discover.api_key = t_tv.api_key discover.discover_tv_shows(attrs) total_pages = int(os.environ["total_pages"]) total_results = int(os.environ["total_results"]) amount = total_results if limit == 0 or total_results < limit else limit if method in ["tmdb_company", "tmdb_network"]: print("| Processing {}: {} ({} {} shows)".format( method, tmdb_id, amount, tmdb_name)) else: print("| Processing {}: {} shows".format(method, amount)) for attr, value in attrs.items(): print("| {}: {}".format(attr, value)) for x in range(total_pages): attrs["page"] = x + 1 tmdb_shows = discover.discover_tv_shows(attrs) for tshow in tmdb_shows: count += 1 t_tvs.append(tshow.id) if count == data: break if count == data: break elif method in [ "tmdb_popular", "tmdb_top_rated", "tmdb_trending_daily", "tmdb_trending_weekly" ]: trending = Trending() trending.api_key = t_tv.api_key for x in range(int(int(data) / 20) + 1): if method == "tmdb_popular": tmdb_shows = t_tv.popular(x + 1) elif method == "tmdb_top_rated": tmdb_shows = t_tv.top_rated(x + 1) elif method == "tmdb_trending_daily": tmdb_shows = trending.tv_day(x + 1) elif method == "tmdb_trending_weekly": tmdb_shows = trending.tv_week(x + 1) for tshow in tmdb_shows: count += 1 t_tvs.append(tshow.id) if count == amount: break if count == amount: break print("| Processing {}: {} Items".format(method, data)) else: tmdb_id = int(data) if method == "tmdb_list": tmdb = List() tmdb.api_key = t_tv.api_key try: t_col = tmdb.details(tmdb_id) tmdb_name = str(t_col) for ttv in t_col: if ttv.media_type == "tv": t_tvs.append(ttv.id) except: raise ValueError( "| Config Error: TMDb List: {} not found".format(tmdb_id)) else: try: t_tv.details(tmdb_id).number_of_seasons tmdb_name = str(t_tv.details(tmdb_id)) t_tvs.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_tvs: tvdb_id = tmdb_get_tvdb(config_path, mid) if tvdb_id is None: print( "| TMDb Error: tmdb_id: {} ({}) has no associated tvdb_id. Try just using tvdb_id instead" .format(mid, t_tv.details(mid).name)) elif tvdb_id in plex_map: matched.append(plex.Server.fetchItem(plex_map[tvdb_id])) else: missing.append(tvdb_id) return matched, missing
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
def tmdb_get_shows(config_path, plex, data, method): config_tools.TraktClient(config_path) t_tvs = [] t_tv = TV() t_tv.api_key = config_tools.TMDB(config_path).apikey # Set TMDb api key for Movie if t_tv.api_key == "None": raise KeyError("Invalid TMDb API Key") discover = Discover() discover.api_key = t_tv.api_key count = 0 if method == "tmdb_discover": discover.discover_tv_shows(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_shows = discover.discover_tv_shows(data) for tshow in tmdb_shows: count += 1 t_tvs.append(tshow.id) if count == amount: break if count == amount: break run_discover(data) elif method in ["tmdb_popular", "tmdb_top_rated", "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_shows = t_tv.popular(x + 1) elif method == "tmdb_top_rated": tmdb_shows = t_tv.top_rated(x + 1) #elif method == "tmdb_trending_daily": #TURNON:Trending # tmdb_shows = trending.tv_day(x + 1) #TURNON:Trending #elif method == "tmdb_trending_weekly": #TURNON:Trending # tmdb_shows = trending.tv_week(x + 1) #TURNON:Trending for tshow in tmdb_shows: count += 1 t_tvs.append(tshow.id) if count == amount: break if count == amount: break print("| Processing {}: {} Items".format(method, data)) else: tmdb_id = int(data) if method == "tmdb_list": tmdb = List() tmdb.api_key = t_tv.api_key try: t_col = tmdb.details(tmdb_id) tmdb_name = str(t_col) for ttv in t_col: if ttv.media_type == "tv": t_tvs.append(ttv.id) except: raise ValueError("| Config Error: TMDb List: {} not found".format(tmdb_id)) elif method in ["tmdb_company", "tmdb_network"]: if method == "tmdb_company": tmdb = Company() tmdb.api_key = t_tv.api_key tmdb_name = str(tmdb.details(tmdb_id)) else: #tmdb = Network() #TURNON:Trending #tmdb.api_key = t_tv.api_key #TURNON:Trending tmdb_name = ""#str(tmdb.details(tmdb_id)) #TURNON:Trending discover_method = "with_companies" if method == "tmdb_company" else "with_networks" tmdb_shows = discover.discover_tv_shows({discover_method: tmdb_id}) for tshow in tmdb_shows: t_tvs.append(tshow.id) else: try: t_tv.details(tmdb_id).number_of_seasons tmdb_name = str(t_tv.details(tmdb_id)) t_tvs.append(tmdb_id) except: raise ValueError("| Config Error: TMDb ID: {} not found".format(tmdb_id)) print("| Processing {}: ({}) {}".format(method, tmdb_id, tmdb_name)) p_tv_map = {} for item in plex.Library.all(): guid = urlparse(item.guid) item_type = guid.scheme.split('.')[-1] if item_type == 'thetvdb': tvdb_id = guid.netloc elif item_type == 'themoviedb': tvdb_id = get_tvdb_id_from_tmdb_id(guid.netloc) else: tvdb_id = None p_tv_map[item] = tvdb_id matched = [] missing = [] for mid in t_tvs: match = False tvdb_id = get_tvdb_id_from_tmdb_id(mid) if tvdb_id is None: print("| Trakt Error: tmbd_id: {} could not converted to tvdb_id try just using tvdb_id instead".format(mid)) else: for t in p_tv_map: if p_tv_map[t] and "tt" not in p_tv_map[t] != "None": if p_tv_map[t] is not None and int(p_tv_map[t]) == int(tvdb_id): match = True break if match: matched.append(t) else: missing.append(tvdb_id) return matched, missing