def getDataFromTMDb(opts, movieName, movieYear): """docstring for getDataFromTMDb""" if opts.verbose == 2: print "!!Looking up data for: %s - %s" % (movieName, movieYear) #end if debug movieResults = tmdb.search(movieName.decode("utf-8")) movies = [] if opts.verbose == 2: print "!!Search returned %s hits" % len(movieResults) #end if debug #we got zero hits, try replacing some commonly used replacement-characters due to filename illegality if len(movieResults) < 1: if movieName.count(';'): tempMovieName = movieName.replace(';', ':') return getDataFromTMDb(opts, tempMovieName, movieYear) elif movieName.count('_'): tempMovieName = movieName.replace('_', ' ') return getDataFromTMDb(opts, tempMovieName, movieYear) else: #last ditch attempt, search for movies by longest word in movie name as long as more then one word if len(movieName.split()) < 2: return movies #end if len movieNameLongestWord = max(movieName.split(), key=len) longestWordMovies = getDataFromTMDb(opts, movieNameLongestWord, movieYear) if opts.interactive or len(longestWordMovies) == 1: if opts.verbose == 2: print "!!Using search result(s) based upon longest word search" #end if debug return longestWordMovies #end if interactive return movies #end if count #end if len if movieYear != "": for movieResult in movieResults: #check that the year tag in the file name matches with the release date, otherwise not the movie we are looking for if opts.verbose == 2: print "!!Potential hit: %s" % movieResult['name'] if movieResult['released']: if movieResult['released'].startswith( movieYear) or movieResult['released'].startswith( str(int(movieYear) + 1)): movie = tmdb.getMovieInfo(movieResult['id']) movies.append(movie) #end for movie else: for movieResult in movieResults: #check that the year tag in the file name matches with the release date, otherwise not the movie we are looking for if opts.verbose == 2: print "!!Potential hit: %s" % movieResult['name'] if movieResult['released']: movie = tmdb.getMovieInfo(movieResult['id']) movies.append(movie) #end for movie return movies
def refreshMovieTitle(self, title): global movie_title movie_title = title self["title"].setText(_("Searchtitle: %s") % movie_title) self["info"].setText(_("Filename: %s") % os.path.basename(self.service.getPath())) self.setTitle(_("Search result(s) for %s") % (movie_title)) try: results = tmdb.search(movie_title) except: results = [] if len(results) == 0: self.setTitle(_("Nothing found for: %s") % (movie_title)) self["key_green"].setText(_("OK")) print "No info found for: " + movie_title return False self.l = [] for searchResult in results: try: self["key_green"].setText(_("Save infos/cover")) movie = tmdb.getMovieInfo(searchResult['id']) released = movie['released'][:4] if released: self.l.append((movie['name'].encode("utf-8") + " - " + released, movie)) else: self.l.append((movie['name'].encode("utf-8"), movie)) except: pass self["list"].setList(self.l)
def test_get_director(): """Checks you can get the director of a film """ mid = tmdb.search("Inglourious Basterds")[0]['id'] movie = tmdb.getMovieInfo(mid) assert len(movie['cast']['director']) == 1 assert movie['cast']['director'][0]['name'] == "Quentin Tarantino"
def test_search_wrapper(self): """Tests tmdb.search() wrapper works correctly """ r = tmdb.search("The Matrix") self.assertEquals( type(r), tmdb.SearchResults )
def watchlist_search(): title = request.args.get('title') if title == "" or None: title = "Spider-man" flash("No value entered. Here are some recommended movies!") results = tmdb.search(str(title)) size = len(results) return render_template("watchlist_search.html", results=results, size=size)
def downloadMovieInfo(self, name, filename=None): import tmdb from EventInformationTable import createEIT results = tmdb.search(name) if results and len(results) > 0: searchResult = results[0] movie = tmdb.getMovieInfo(searchResult['id']) createEIT(filename, name, config.AdvancedMovieSelection.coversize.value, movie)
def test_get_director(self): """Checks you can get the director of a film """ mid = tmdb.search("Inglourious Basterds")[0]['id'] movie = tmdb.getMovieInfo(mid) self.assertTrue(len(movie['cast']['director']) == 1) self.assertEquals(movie['cast']['director'][0]['name'], "Quentin Tarantino")
def test_search_to_info(self): """Gets a movie ID via search, then calls getMovieInfo using this """ sr = tmdb.search("fight club")[0] movie = tmdb.getMovieInfo(sr['id']) self.assertEquals( sr['name'], movie['name'] )
def downloadMovieInfo(self, name, filename=None): import tmdb from EventInformationTable import createEIT results = tmdb.search(name) if results and len(results) > 0: searchResult = results[0] movie = tmdb.getMovieInfo(searchResult["id"]) createEIT(filename, name, config.AdvancedMovieSelection.coversize.value, movie)
def getDataFromTMDb(opts, movieName, movieYear): """docstring for getDataFromTMDb""" if opts.verbose == 2: print "!!Looking up data for: %s - %s" % (movieName, movieYear) #end if debug movieResults = tmdb.search(movieName.decode("utf-8")) movies = [] if opts.verbose == 2: print "!!Search returned %s hits" % len(movieResults) #end if debug #we got zero hits, try replacing some commonly used replacement-characters due to filename illegality if len(movieResults) < 1: if movieName.count(';'): tempMovieName = movieName.replace(';', ':') return getDataFromTMDb(opts, tempMovieName, movieYear) elif movieName.count('_'): tempMovieName = movieName.replace('_', ' ') return getDataFromTMDb(opts, tempMovieName, movieYear) else: #last ditch attempt, search for movies by longest word in movie name as long as more then one word if len(movieName.split()) < 2: return movies #end if len movieNameLongestWord = max(movieName.split(), key=len) longestWordMovies = getDataFromTMDb(opts, movieNameLongestWord, movieYear) if opts.interactive or len(longestWordMovies) == 1: if opts.verbose == 2: print "!!Using search result(s) based upon longest word search" #end if debug return longestWordMovies #end if interactive return movies #end if count #end if len if movieYear != "": for movieResult in movieResults: #check that the year tag in the file name matches with the release date, otherwise not the movie we are looking for if opts.verbose == 2: print "!!Potential hit: %s" % movieResult['name'] if movieResult['released']: if movieResult['released'].startswith(movieYear) or movieResult['released'].startswith(str(int(movieYear)+1)): movie = tmdb.getMovieInfo(movieResult['id']) movies.append(movie) #end for movie else: for movieResult in movieResults: #check that the year tag in the file name matches with the release date, otherwise not the movie we are looking for if opts.verbose == 2: print "!!Potential hit: %s" % movieResult['name'] if movieResult['released']: movie = tmdb.getMovieInfo(movieResult['id']) movies.append(movie) #end for movie return movies
def test_get_director(self): """Checks you can get the director of a film """ mid = tmdb.search("Inglourious Basterds")[0]['id'] movie = tmdb.getMovieInfo(mid) self.assertTrue(len(movie['cast']['director']) == 1) self.assertEquals( movie['cast']['director'][0]['name'], "Quentin Tarantino" )
def search(self, movie, year=None): attempts = 3 if year == None: index = movie else: index = movie + year movie = movie.encode('utf-8') for i in range(attempts): try: return tmdb.search(movie, year) except Exception as e: raise e
def get_theather_recommend(): """ return: [ { title, url, schedule_start: date +'%H時%M分' }, ... ] """ return json.dumps([ dict(title="スター・ウォーズ/最後のジェダイ", url='http://starwars.disney.co.jp/movie/lastjedi.html', genre="SF", schedule_start='0', schedule_end='0'), dict(title=" Fate/stay night Heavens Feel Ⅰ", url='http://www.fate-sn.com/', genre="Anime", schedule_start='0', schedule_end='0'), ]) genre = request.query['genre'] print('get_theather_recommend') # TODO schedule movies = [ dict(title=data['name'], schedule_start=data['schedule'][0]['showingStart']) for data in now_playings if len(data['schedule']) != 0 ] ret = [] for movie in movies: results = search(movie['title']) if len(results) == 0: continue movie_id = results[0]['id'] detail = get_detail(movie_id) if genre not in [e['name'] for e in detail['genres']]: continue movie['url'] = detail['homepage'] ret += movie print(ret) return json.dumps(ret)
def __init__(self, filename, options): moviename = get_moviename(filename) if options.tmdbid: dbid = options.tmdbid else: results = tmdb.search(get_moviename(filename)) if len(results) == 0: print "Movie not found in TMDB:", moviename dbid = prompt_mm("tmdb", "") else: search = results[0] dbid = search["id"] if mismatch(moviename, search["name"]): print "Possible mismatch for: %s\n" % moviename print "Search Result" print "=============" print "Title: %s (%s)" % (search["name"], search["released"]) print search["url"] dbid = prompt_mm("tmdb", search["id"]) if dbid == "-1": print "Skipping art fetch" else: self.rawmovie = tmdb.getMovieInfo(dbid) print "Retrieving art:", self.rawmovie["name"] posterurl = self.get_url(self.rawmovie, "poster", options.interactive) if posterurl: posterpath = self.get_artpath(filename, posterurl, "poster") if not options.rescrape and os.path.exists(posterpath): print "Art already exists:", posterpath else: self.save_art(posterurl, posterpath) else: print "No posters found" backdropurl = self.get_url(self.rawmovie, "backdrop", options.interactive) if backdropurl: backdroppath = self.get_artpath(filename, backdropurl, "backdrop") if not options.rescrape and os.path.exists(backdroppath): print "Art already exists:", backdroppath else: self.save_art(backdropurl, backdroppath) else: print "No backdrops found" if options.allart: self.save_all_fanart(filename, self.rawmovie["images"].backdrops)
def movie_search(request): if request.method == "POST": titles = [] movies = [] if "single-movie-search" in request.POST: titles = [request.POST["query"]] else: titles = [line for line in request.POST["movies_list"].splitlines() if line] for movie_title in titles: results = tmdb.search(movie_title)[:3] for result in results: result["thumb"] = get_movie_thumbnail(result) result["in_watchlist"] = Movie.objects.filter(tmdb_id=result["id"]).count() != 0 movies.append((movie_title, results)) return {"movies": movies, "TEMPLATE": "movie_search_results.html"} return {"fun": "fun", "TEMPLATE": "movie_search.html"}
def search(title): year = None match = title_regex.search(title) if match: title, year = match.group(1), int(match.group(2)) tmdb_data = tmdb.search(title, year) if tmdb_data.media_type == 'tv': data = TVData() else: data = MovieData() data._tmdb = tmdb_data # data._ttdb = ttdb.from_imdbid(tmdb_data.basic_info['imdb_id']) return data
def main(): year = datetime.datetime.now().year - 1 moviedb = tmdb.MovieDb() for yr in range(1980, year): try: # Yeah I know, searching for a year is pretty bad idea, especially for 1984, # These API's that just aren't made for giving back lists of movies that # are bigger than 200byte! movies = tmdb.search(str(yr)) for mov in movies: check_lists(mov['name']) except: print("Error: Searching for " + str(yr) + " failed") #exit(0) print_list()
def get_genres(): titles = [ data['name'] for data in now_playings if len(data['schedule']) != 0 ] genres = [] for title in titles: results = search(title) if len(results) == 0: continue movie_id = results[0]['id'] genres += [e['name'] for e in get_detail(movie_id)['genres']] genre_set = {genre for genre in genres} genre_rate = [] # type: Tuple[str, int] for genre in genre_set: genre_rate.append((genre, len([e for e in genres if e == genre]))) # sort by rate genre_rate = sorted(genre_rate, key=itemgetter(1), reverse=True) return json.dumps([e[0] for e in genre_rate])
def search(self, movie, year=None): attempts = 3 backoff = 5 if year == None: index = movie else: index = movie+year if index in self.tmdb_cache: res = self.tmdb_cache[index] print 'Using cached result' return res else: for i in xrange(attempts): try: movie = movie.encode('utf-8') res = tmdb.search(movie,year) self.tmdb_cache[index] = to_unicode(res) self.save_cache() return res except Exception, e: raise
def gen_movie_db(self): regex = re.compile(self.movie_regex) for root, dirs, files in os.walk(self.movie_directory, topdown=True): try: dirs.remove('.AppleDouble') except: pass for name in files: info = None comp = regex.match(name) if comp is not None: info = comp.groupdict() title = re.sub('\.',' ',info['title']).strip() print 'Checking %s' % title try: movie = self.db['movies'][title] except: movie_list = tmdb.search(title) if self.interactive: idx = get_choice(movie_list) else: idx = 0 print 'got %s results' % movie_list # for item in movie_list: # # print item try: movie = Movie.select(Movie.q.name==movie_list[idx]['name']).getOne() print 'found %s' % movie movie.file_path = os.path.join(root,name) except Exception as e: item = tmdb.getMovieInfo(movie_list[idx]['id']) movie = Movie() movie.load(item) movie.file_path = os.path.join(root,name) else: print u'%s does not match' % name
def tmdb(self, irc, msg, args, text): """<film> Get information on <film> from TMDb """ try: t = tmdb.search(text) except: irc.reply("Error: I couldn't get that information") return try: m=t[0] except: irc.reply('Not found.') return for key in m.keys(): if isinstance(m[key],basestring): m[key]=m[key].encode('UTF-8') irc.reply('%s %s (%s) %s: %s' % (m['url'], ircutils.bold(m['name']),m['released'].split('-')[0], m['rating'], m['overview']))
def searchMovie(self, title): log.info("Searching TMDB...") searchResults = tmdb.search(title) log.debug("Found movies '%s'" % str(searchResults)) return self.choose(searchResults, "Select movie by title")
def insertMovie(): try: html = [ """ <html> <body> <form name = "input" action = "insertMovie.py" method = "post"> Insert a movie into the Movie Database. <br /> Note: TMDb's API will handle populating the movie's fields. <br /><br /> Movie Title: <input type = "text" name = "movie"/> <input type = "submit" value = "Submit" /> </input> </form> """ ] http_headers() print "\n".join(html) form = cgi.FieldStorage() if form.has_key("movieID"): movie_ID = form["movieID"].value movie = tmdb.getMovieInfo(movie_ID) print "The movie '%s' has been successfully inserted" % movie["name"] # This is in a try block because the API doesn't always have all the fields filled in. # There are some nested try blocks--this is because certain fields (like the poster image or # summary) are more unlikely to be unavailable. try: try: url = movie["images"].posters[0]["cover"] html = ['<br /><br /><center><img src="'] print "\n".join(html) print url html = ["""" alt="poster" align = "top"/></center><br />"""] print "".join(html) # image copyright of Town Of Warner(tm) except: html = [ """ <br /><br /><center><img src="http://www.townofwarner.com/images/businesses /notavailable.gif" alt="poster" align = "top"/></center><br /> """ ] print "".join(html) print "<strong>Movie Name:</strong> %s <br /><br />" % movie["name"] print "<strong>Date Released:</strong> %s <br /><br />" % movie["released"] # Sometimes the API won't successfully show the overview (usually due to # an ascii codec error). try: print "<strong>Movie Summary:</strong> %s <br /><br />" % movie["overview"] except: print "" print "<strong>Movie Director(s):</strong>" directors = movie["cast"]["director"] for director in directors: print " %s, " % director["name"] print "<br /> <br /><strong>Movie Cast:</strong>" cast = movie["cast"]["actor"] for member in cast: print " %s, " % member["name"] print "<br /> <br /><strong>Movie Genre(s):</strong>" genres = movie["categories"]["genre"] for genre in genres: print " %s, " % genre except: print "" elif form.has_key("movie"): results = tmdb.search(form["movie"].value) try: results[0] # this checks if the list isn't empty html = [ """ <br \><p>Based on the list provided below, submit the proper ID number in order to insert the movie.</p> <form name = "movie_input" action = "insertMovie.py" method = "post"> Movie ID: <input type = "text" name = "movieID" /> <input type = "submit" value = "Submit" /><br \> <br \> """ ] print "\n".join(html) # This prints out all of the possible movies based on the movie title the employee writes. # It prints the movie's ID, title, and year released (if provided in API). for searchResult in results: print tmdb.getMovieInfo(searchResult["id"])["id"] + ": " print tmdb.getMovieInfo(searchResult["id"])["name"] year_released = tmdb.getMovieInfo(searchResult["id"])["released"] if year_released != None: year_released = year_released.split("-", 1) # show only the year, not whole date print "(%s)" % year_released[0] html = ["<br />"] print "\n".join(html) except: print "The movie could not be found in the API." # If not found in API, maybe employee can manually insert the movie? # Sometimes this will show at the end of the list even though # movies have been found. Try typing Transformers; the last # item in the list will show this. except: http_headers() print "<!-- --> <hr><h1>Oops... an error occurred.</h1>" cgi.print_exception()
def test_search_wrapper(): """Tests tmdb.search() wrapper works correctly """ r = tmdb.search("The Matrix") assert isinstance(r, tmdb.SearchResults)
def test_search_to_info(): """Gets a movie ID via search helper, then calls getMovieInfo using this """ sr = tmdb.search("fight club")[0] movie = tmdb.getMovieInfo(sr['id']) assert sr['name'] == movie['name']
def test_search_to_info(self): """Gets a movie ID via search, then calls getMovieInfo using this """ sr = tmdb.search("fight club")[0] movie = tmdb.getMovieInfo(sr['id']) self.assertEquals(sr['name'], movie['name'])
def insertMovie(): try: html = [''' <html> <body> <form> Insert a movie into the Movie Database. <br /> Note: TMDb's API will handle populating the movie's fields. <br /><br /> Movie Title: <input type = "text" name = "movie" id="movietitle"/> <input id="searchmovieTitle" type = "button" value = "Submit" onclick="loadXMLDoc(this)" /> </form> '''] http_headers() print "\n".join(html) form = cgi.FieldStorage() if form.has_key("movieID"): movieAPI = tmdb.getMovieInfo(form["movieID"].value) movie = movieObject.Movie(movieAPI['name']) try: year_released = movieAPI['released'] year_released2 = year_released.split('-', 1 ) #show only the year, not whole date year_released = year_released2[0] movie.setYear(year_released) except: movie.setYear("Unavailable") try: photo_url = movieAPI['images'].posters[0]['cover'] movie.setPhoto(photo_url) except: #Image Unavailable" picture is copyright of Town Of Warner(tm) movie.setPhoto("http://www.townofwarner.com/images/businesses/notavailable.gif") if form.has_key("trailerURL"): movie.setTrailer(form["trailerURL"].value) else: movie.setTrailer("Unavailable") try: genres = movieAPI['categories']['genre'] movie.setGenre(genres.keys()[0]) except: movie.setGenre("Unavailable") try: directors = movieAPI['cast']['director'] directors_first = [] directors_last = [] for director in directors: directors_name = director['name'].partition(' ') directors_first.append(directors_name[0]) directors_last.append(directors_name[2]) movie.setDirectorsFirst(directors_first) movie.setDirectorsLast(directors_last) except: movie.setDirectorsFirst([]) movie.setDirectorsLast([]) try: actors = movieAPI['cast']['actor'] actors_first = [] actors_last = [] for actor in actors: actor_name = actor['name'].partition(' ') actors_first.append(actor_name[0]) actors_last.append(actor_name[2]) movie.setCastFirst(actors_first) movie.setCastLast(actors_last) except: movie.setCastFirst([]) movie.setCastLast([]) try: summary = movieAPI['overview'] movie.setSummary(summary) except: movie.setSummary("Unavailable") displayMovieInfo(movie) elif form.has_key("movie"): results = tmdb.search(form["movie"].value) try: results[0] #this checks if the movie list isn't empty html = [''' <br \><p><strong>Based on the list provided below, submit the proper ID number in order to insert the movie.</strong></p> <p><i>Unfortunately, TMDb API does not supply trailer links. <strong>If applicable</strong>, please also supply a URL for the movie's trailer.</i></p> <form name = "movie_input"> Movie ID: <input type = "text" name = "movieID" id="mid"/> <br /> Trailer URL: <input type = "text" name = "trailerURL" id="turl" /> <br /> <input type = "button" value = "Submit" onclick="loadXMLDoc(this)" id="fulldetail" /><br \> <br \> <strong>LIST OF MOVIES</strong> <br /> '''] print "\n".join(html) #This prints out all of the possible movies based on the movie title the employee writes. #It prints the movie's ID, title, and year released (if provided in API). for searchResult in results: print tmdb.getMovieInfo(searchResult['id'])['id'] + ": " print tmdb.getMovieInfo(searchResult['id'])['name'] year_released = tmdb.getMovieInfo(searchResult['id'])['released'] if year_released != None: year_released = year_released.split('-', 1 ) #show only the year, not whole date print "(%s)" %year_released[0] html = ["<br />"] print "\n".join(html) except: print "The movie could not be found in the API." #Sometimes this will show at the end of the list even though #movies have been found. Try typing Transformers; the last #item in the list will show this. I think it's an ascii error. html = [''' </body> </html> '''] print "\n".join(html) except: http_headers() print "<!-- --> <hr><h1>Oops... an error occurred.</h1>" cgi.print_exception()
def test_search_wrapper(self): """Tests tmdb.search() wrapper works correctly """ r = tmdb.search("The Matrix") self.assertEquals(type(r), tmdb.SearchResults)
import Image import tmdb coll = Connection()["media"]["movies"] movies_assocs = [("poster", ["jpg"]), ("backdrop", ["jpg"]), ("trailer", ["mov", "avi", "ogg", "ogv", "mp4", "mkv"])] for movie in coll.find(): if os.path.exists(movie["path"]): dirname = os.path.dirname(movie["path"]) fn, ext = os.path.splitext(os.path.basename(movie["path"])) res = tmdb.search(movie["name"], movie["year"]) ctx = res[0] if len(res) >= 1 else None info = tmdb.getInfo(ctx["id"]) if ctx else None pt_url = ctx["posters"][0]["image"]["url"] if ctx and len(ctx["posters"]) >= 1 else None bd_url = ctx["backdrops"][0]["image"]["url"] if ctx and len(ctx["backdrops"]) >= 1 else None if ctx: # Update document and context # Grab file information # try: # meta = extractMetadata(createParser(media['path'])) # except KeyboardInterrupt: # raise # # except: