def FILEtoIMDB(
    file_name
):  #Added function by nctiggy. This executes if the nzb does not have the IMDB id appended to the name
    #This does capture all of the movies info not just the IMDB id
    #Future can eliminate the calls to IMDB to use this data instead perhaps

    print "CouchPotatoServer did not append the IMDB id to the nzb, guessing instead"
    api_key = "45e408d2851e968e6e4d0353ce621c66"  # You need to get this key from themoviedb.org

    # Guessing at the name of the movie using the filename
    movie_info = guessit.guess_movie_info(file_name)

    #configuring tmdb to use the supplied api key
    tmdb.configure(api_key)
    print "Guessed movie title as: %s" % (movie_info["title"])

    #Creating a collection of movies from tmdb for the guess movie title
    movies = tmdb.Movies(movie_info["title"])

    #parse through all movies found
    for movie in movies.iter_results():
        #Identify the first movie in the collection that matches exactly the movie title
        if movie["title"].lower() == movie_info["title"].lower():
            print "Matched movie title as: %s %s" % (movie["title"],
                                                     movie["release_date"])
            movie = tmdb.Movie(movie["id"])
            break
    #return the imdb id of the movie identified
    return movie.get_imdb_id()[2:]
def FILEtoIMDB(file_name): #Added function by nctiggy. This executes if the nzb does not have the IMDB id appended to the name
    #This does capture all of the movies info not just the IMDB id
    #Future can eliminate the calls to IMDB to use this data instead perhaps
    
    print "CouchPotatoServer did not append the IMDB id to the nzb, guessing instead"
    api_key = "45e408d2851e968e6e4d0353ce621c66" # You need to get this key from themoviedb.org

    # Guessing at the name of the movie using the filename
    movie_info = guessit.guess_movie_info(file_name)
    
    #configuring tmdb to use the supplied api key
    tmdb.configure(api_key)
    print "Guessed movie title as: %s" % (movie_info["title"])
    
    #Creating a collection of movies from tmdb for the guess movie title
    movies = tmdb.Movies(movie_info["title"])

    #parse through all movies found
    for movie in movies.iter_results():
        #Identify the first movie in the collection that matches exactly the movie title
        if movie["title"].lower() == movie_info["title"].lower():
            print "Matched movie title as: %s %s" % (movie["title"], movie["release_date"])
            movie = tmdb.Movie(movie["id"])
            break
    #return the imdb id of the movie identified
    return movie.get_imdb_id()[2:]
    def configure(self):
        # Configure the TMDB database.
        tmdb.configure(self.args.api_key)

        # Get the v3 API stuff directly through JSON.
        url = "http://api.themoviedb.org/3/configuration?api_key={0}".format(
            self.args.api_key)
        self.configuration = self.get_json(url)
Example #4
0
def search_tmdb(title):
    tmdb.configure(TMDB_KEY)
    movie = tmdb.Movies(title,limit=True)
    
    filmList=[]
    
    try:
        for i in movie.iter_results():
            year = re.sub('-.*', '', i['release_date'])                         
            filmList.append(ricerca_TMDB(i['title'], year, i['id'], i['poster_path']))
        
    except:
        filmList = []
    
    return filmList
def get_latest_upcoming_movie():
    """ Returns the list of movies and their information fetched from 
        https://www.themoviedb.org/ API

    Replace YOUR_API_KEY with the actual API KEY
    Uses two third party API for the moviedb API 
    They are 
      - tmdbsimple from [1]
        [1] : https://github.com/celiao/tmdbsimple/tree/master/tmdbsimple
        for fetching the trailer information
      - tmdb from https://github.com/doganaydin/themoviedb for fetching all 
        the information about a specific movie 

    """
    my_movies_list = []
    tmdb.configure('YOUR_API_KEY')
    upcomingmovies.API_KEY = 'YOUR_API_KEY'
    m1 = upcomingmovies.Movies()
    # get the latest upcoming movie
    latest_movies = m1.upcoming()
    logger.debug(latest_movies)
    for c in m1.results:
        movieinfo = tmdb.Movie(c['id'])
        trailers = upcomingmovies.Movies(c['id'])
        trailers.videos()
        if(len(trailers.results) != 0):
            d = trailers.results[0]
            logger.debug(
                "trailer url: "+"https://www.youtube.com/watch?v="+d['key'])
            logger.debug("movie title: "+movieinfo.get_title())
            logger.debug("movie overview: "+movieinfo.get_overview())
            logger.debug("movie release date: "+movieinfo.get_release_date())
            posterurl = movieinfo.get_poster('m')
            if posterurl is None:
                posterurl = "https://upload.wikimedia.org/wikipedia/en" \
                    "/archive/d/d6/20080101230921%21Image_coming_soon.png"
            logger.debug("poster image url: "+posterurl)

            # if there is no poster image in the API put up a default coming
            # soon image from http://tinyurl.com/pofdefk
            youtubeurl = "https://www.youtube.com/watch?v=" + d['key']
            movieresults = media.Movie(movieinfo.get_title(
            ), posterurl, youtubeurl, movieinfo.get_overview(
            ), movieinfo.get_release_date())
            my_movies_list.append(movieresults)
    fresh_tomatoes.open_movies_page(my_movies_list)
Example #6
0
def beginMovieParse(cur):
    updateList = []
    returnList = []

    updateCount = 100
    updated = datetime.datetime.now().strftime("%Y-%m-%d")
    filterWords = r"(.*)proper|sample|repack|extended(\scut)?|dual audio|unrated|rerip|limited|\bdc\b|uncut"

    pass1 = re.compile(r'(?i)(.*?)(?=[0-9]{4}(?!p))\(?([0-9]{4})\)?')
    pass2 = re.compile(r'(?i)(.*?)(?=[0-9]{3,})(?!p)')

    cur.execute('select id, file_name, parent_dir, sub_dir from movie where updated is NULL')
    movie_list = cur.fetchall()

    tmdb.configure('1c6f8a30ad219e30992ea75911f8f9d5')

    for row in movie_list:
        filename = row[1]
        parentdir = row[2]
        id = row[0]

        results = None
        data = {'id': id, 'title': None, 'year': None, 'desc': None, 'year': None, 'aired': None, 'updated': updated
                , "runtime": None, "imdb": None, "tmdb": None}
        searchTitle = None
        searchYear = None

        #first pass
        results = pass1.search(parentdir)
        if results:
            searchTitle = results.group(1)
            searchYear = results.group(2)
        else:
            results = pass2.search(parentdir)
            if results:
                searchTitle = results.group(1)
                searchYear = None

        if searchTitle is not None:
            searchTitle = searchTitle.lower().replace('.', ' ')
            searchTitle = re.sub(filterWords, '', searchTitle, 1, flags=re.IGNORECASE) #reverse removal
            searchTitle = searchTitle.strip()

            movies = tmdb.Movies(searchTitle, limit = True)

            movieResult = None
            if movies:
                for  movie in movies:
                    if movie.get_title().lower() == searchTitle:
                        if searchYear and movie.get_release_date() is not None:
                            movieYear = re.match('[0-9]{4}', movie.get_release_date()).group()
                            if movieYear != searchYear:
                                continue
                        movieResult = movie
                        break

                if not movieResult: #diff search
                    l = [x.get_title() for x in movies]
                    d = difflib.get_close_matches(searchTitle, l, 1, 0)
                    if len(d) > 0:
                        for movie in movies:
                            if movie.get_title() == d[0]:
                                movieResult = movie
                                break

                if not movieResult: #just pick first result if exists
                    if movies.get_total_results() > 0:
                        movieResult = movies.__iter__().next()


                if movieResult:
                    data["title"]= movieResult.get_title()
                    data["year"] = movieResult.get_release_date()
                    data["aired"] = movieResult.get_release_date()
                    data["tmdb"] = movieResult.get_id()
                    data["imdb"]= movieResult.get_imdb_id()
                    data["desc"] = movieResult.get_overview()
                    data["runtime"] = movieResult.get_runtime()

                    if data["desc"] and len(data["desc"]) > 0:
                        data["desc"] = data["desc"].replace('\n', '')

                    updateList.append((
                        data["title"]
                        , data["year"]
                        , data["aired"]
                        , data["tmdb"]
                        , data["imdb"]
                        , data["desc"]
                        , data["runtime"]
                        , data["id"]
                    ))

                    returnList.append(data["title"])

                    logger.info('MEDIA_INFO', 'TMDB scrapped data for \"%s\" @ \"%s\".'
                        , data['title']
                        , parentdir)
                else:
                    logger.warn('MEDIA_INFO', 'TMDB found no matching results for \"%s\".\nTMDB was sent %s and returned a list of %s'
                        , parentdir
                        , searchTitle
                        , ','.join([x.get_title() for x in movies]))
                    #update the database so we dont see this again for the same movie each iteration
                    cur.execute("update movie set updated = date('now') WHERE id = ?", (data['id'],))

                    returnList.append(parentdir)
            else:
                logger.warn('MEDIA_INFO', 'TMDB returned a null object for \"%s\". RAW = %s', searchTitle, parentdir)
                #update the database so we dont see this again for the same movie each iteration
                cur.execute("update movie set updated = date('now') WHERE id = ?", (data['id'],))
                returnList.append(parentdir)
        else:
            logger.error('beginMovieParse', 'update_database.py', 'We were unable to parse a title out of \"%s\"', parentdir)
            #update the database so we dont see this again for the same movie each iteration
            cur.execute("update movie set updated = date('now') WHERE id = ?", (data['id'],))
            returnList.append(parentdir)

        if len(updateList) > 40:
            cur.executemany("update movie set title = ?, year = ?, airdate = ?, tmdbid = ?, imdbid = ?, description = ?, runtime = ?, updated = date('now') WHERE id = ?", updateList)
            updateList = []

    if len(updateList) > 0:
        cur.executemany("update movie set title = ?, year = ?, airdate = ?, tmdbid = ?, imdbid = ?, description = ?, runtime = ?, updated = date('now') WHERE id = ?", updateList)

    return returnList
Example #7
0
#import pdb; pdb.set_trace()
import tmdb
tmdb.configure('49c45d00bdf566880f6014219239531b')
 def __init__(self, language='en'):
     tmdb.configure("57983e31fb435df4df77afb854740ea9", language=language)
     dbname = 'tmdb.%s.db' % language
     self.cache = Cache(dbname, 1.0)
Example #9
0
 def setUp(self):
     tmdb.configure("API_KEY")
     self.movies = tmdb.Movies("The Avengers")
Example #10
0
"""
A the movie db cache layer that stores the values in the configured
mongo db and local image path.
"""
import tmdb
import requests
import pymongo
import os
from sh import rm, mkdir
from PIL import Image
from StringIO import StringIO

# config
try:
    api_key = os.environ['TMDB_API_KEY']
    tmdb.configure(api_key)
except KeyError as e:
    print "You need to set the environment variable TMDB_API_KEY to your the movie db key."
    raise e

try:
    mongo_db_name = os.environ['MONGO_MEDIA_INFO_MONGO_DB']
    mongo_client = pymongo.MongoClient()
    mongo_db = mongo_client[mongo_db_name]

    # mongo collections
    movie_queries = mongo_db.movie_queries
    movies = mongo_db.movies

except KeyError as e:
    print "You need to configure the mongo db to use by setting the environment variable MONGO_MEDIA_INFO_MONGO_DB."
Example #11
0
 def __init__(self, language='en'):
     tmdb.configure("33dd11cb87f2b5fd9ecaff4a81d47edb", language=language)
     dbname = 'tmdb.%s.db' % language
     self.cache = Cache(dbname, 1.0)
Example #12
0
#!/usr/bin/python2
import tmdb
import _mysql
import sys


tmdb.configure("0ed82318c3b01c2800a6fcffdc6d2d34")

titel = sys.argv[1]
url = sys.argv[2]

movie = tmdb.tmdb(titel)

def GetTitle(movie):
	return movie.getName(0)
def GetRating(movie):
	return movie.getRating(0)
def GetImage(movie):
	return movie.getPoster(0,"c")
def GetDescription(movie):
	return movie.getOverview(0).replace("'","\\'")

db=_mysql.connect(host="localhost", user="******", passwd=":-)", db="filmer")
query = "INSERT INTO film (titel,bild,beskrivning,rating,url) VALUES('"+ GetTitle(movie) + "', '" + GetImage(movie) + "','" + GetDescription(movie) +"','" + GetRating(movie) + "', '" + url + "')"
db.query(query)

Example #13
0
 def __init__(self, language='en'):
     tmdb.configure("f7f51775877e0bb6703520952b3c7840", language=language)
     dbname = 'tmdb.%s.db' % language
     self.cache = Cache(dbname, 1.0)
Example #14
0
 def __init__(self, instance='Default'):
     tmdb.configure('5c235bb1b487932ebf0a9935c8b39b0a')
     Provider.__init__(self, instance=instance)
 def __init__(self, instance='Default'):
     SearchTermFilter.__init__(self, instance=instance)
     tmdb.configure('5c235bb1b487932ebf0a9935c8b39b0a', 'EN')
Example #16
0
 def __init__(self, language='en'):
     tmdb.configure("57983e31fb435df4df77afb854740ea9", language=language)
     dbname='tmdb.%s.db' % language
     self.cache = Cache(dbname, 1.0)
Example #17
0
 def __init__(self, language='en'):
     tmdb.configure("f7f51775877e0bb6703520952b3c7840", language=language)
     dbname='tmdb.%s.db' % language
     self.cache = Cache(dbname, 1.0)
Example #18
0
 def setUp(self):
     tmdb.configure("API_KEY")
     self.core = tmdb.Core()
Example #19
0
 def setUp(self):
     tmdb.configure("3e7807c4a01f18298f64662b257d7059")
     self.movie = tmdb.Movie(24428)
Example #20
0
def updateFanartMovie(cur, conn): #posters only for now
    cur.execute("select id, tmdbid, title from movie where poster is null and mediaupdated is null and tmdbid is not null")
    movies = cur.fetchall()

    tmdb.configure('1c6f8a30ad219e30992ea75911f8f9d5')

    for movie in movies:
        #check if already exists due to crashing and no DB commits happening during this whole process. Not a good idea.
        #fix later
        if os.path.isfile(globals.local_script_path + 'Views/images/movie/' + movie[1] + '_poster.jpg'):
            cur.execute("UPDATE movie SET poster = ?, mediaupdated = date('now') WHERE id = ?", (movie[1] + '_poster.jpg', movie[0],))
            conn.commit()
            continue
        elif os.path.isfile(globals.local_script_path + 'Views/images/movie/' + movie[1] + '_poster.png'):
            cur.execute("UPDATE movie SET poster = ?, mediaupdated = date('now') WHERE id = ?", (movie[1] + '_poster.png', movie[0],))
            conn.commit()
            continue

        minfo = tmdb.Movie(movie[1])

        if not minfo:
            logger.warn('updateFanartMovie', 'TMDB returned no results for \"%s\" [%s]', movie[2], movie[0])
            cur.execute("UPDATE movie SET mediaupdated = date('now') WHERE id = ?", (movie[0],))
            conn.commit()
            continue

        poster = None
        try:
            poster = minfo.get_poster()
        except:
            logger.error('updateFanartMovie', 'update_database.py', 'TMDB crashed retrieving poster for \"%s\" [%s]', movie[2], movie[0])
            cur.execute("UPDATE movie SET mediaupdated = date('now') WHERE id = ?", (movie[0],))
            conn.commit()
            continue

        if not poster:
            logger.info('updateFanartMovie', 'TMDB has no poster for \"%s\" [%s]', movie[2], movie[0])
            cur.execute("UPDATE movie SET mediaupdated = date('now') WHERE id = ?", (movie[0],))
            conn.commit()
            continue

        url = poster
        ext = os.path.splitext(url)[1]
        poster_file_name = movie[1] + '_poster' + ext

        try:
            urllib.urlretrieve(url, globals.local_script_path + 'Views/images/movie/' + poster_file_name)
        except Exception, e:
            logger.error('updateFanartMovie', 'update_database.py', str(e))
            continue

        # no need to resize any more since not running on PCH but through phone/tablet browser
        #try:
        #    img = Image.open(globals.local_script_path + 'Views/images/movie/' + poster_file_name)
        #    img = img.resize((228, 342), PIL.Image.ANTIALIAS)
        #    img.save(globals.local_script_path + 'Views/images/movie/' + poster_file_name)
        #except Exception, e:
        #    if os.path.isfile(globals.local_script_path + 'VIews/images/movie/' + poster_file_name):
        #        os.remove(globals.local_script_path + 'Views/images/movie' + poster_file_name)
        #        # remove file if partially created.
        #    logger.error('updateFanartMovie', 'update_database.py',
        #                 'PIL crashed on image resize for poster \"%s\" [%s]',
        #                 movie[2], movie[0])
        #    logger.error('updateFanartMovie', 'update_database.py', str(e))

        cur.execute("UPDATE movie SET poster = ?, mediaupdated = date('now') WHERE id = ?",
                    (poster_file_name, movie[0],))
        conn.commit()
        logger.info('FANART', 'TMDB returned poster %s which has been added for \"%s\"', poster_file_name, movie[2])
Example #21
0
    def handle(self, *args, **options):
        user, created = User.objects.get_or_create(name='Stefan')
        tmoviedb_user, created = User.objects.get_or_create(name='The Movie Database')
        tmdb.configure(settings.MOVIE_API_KEY)

        counter = 0
        for dirpath, dirnames, filenames in os.walk('/Users/sspross/UseNeXT/wizard'):
            for filename in filenames:
                try:
                    if filename.endswith(FILE_ENDINGS):
                        path = ('%s/%s' % (dirpath, filename)).replace('//', '/')
                        
                        # handle file only case
                        name = filename

                        # handle 0000n.m2ts case
                        if name[:4] == '0000':
                            dirs = dirpath.split('/')
                            name = dirs[-3]
                        
                        # remove fileendings
                        for ending in FILE_ENDINGS:
                            name = name.replace(ending, '') 
                        
                        # remove (..) stuff
                        desc = re.search(r'\(.*\)', name)
                        if desc:
                            desc = desc.group().replace('(', '').replace(')', '')
                        name = re.sub(r'\(.*\)', '', name)    
                        
                        # get more movie data
                        try:
                            tmovie = tmdb.Movie(name)
                        except (ValueError, requests.exceptions.ConnectionError), e:
                            print 'GIVE UP %s' % name
                            continue

                        # try to get original name
                        try:
                            name = tmovie.get_original_title()
                        except IndexError, e:
                            pass

                        # try to get original name
                        try:
                            movie_id = tmovie.get_id()
                            imdb_id = tmovie.get_imdb_id(movie_id)
                        except IndexError, e:
                            imdb_id = None

                        # create movie, if not exists
                        movie, created = Movie.objects.get_or_create(name=name, imdb_id=imdb_id)
                        print name

                        # create file object
                        fil, created = File.objects.get_or_create(path=path, user=user, movie=movie)
                        fil.desc = desc
                        fil.save()

                        # try to get vote average
                        try:
                            movie_id = tmovie.get_id()
                            vote_average = tmovie.get_vote_average(movie_id)
                            rating, created = Rating.objects.get_or_create(movie=movie, user=tmoviedb_user)
                            rating.rating = "%s" % vote_average
                            rating.save()
                        except IndexError, e:
                            pass

                        # # asdfasdf
                        # i = imdb.IMDb(accessSystem='http')
                        # # movie_list is a list of Movie objects, with only attributes like 'title'
                        # # and 'year' defined.
                        # movie_list = i.search_movie(name)
                        # # the first movie in the list.
                        # first_match = movie_list[0]

                        # print first_match

                        # # only basic information like the title will be printed.
                        # print first_match.summary()
                        # # update the information for this movie.
                        # i.update(first_match)
                        # # a lot of information will be printed!
                        # print first_match.summary()
                        # # retrieve trivia information and print it.
                        # i.update(first_match, 'trivia')
                        # print m['trivia']
                        # # retrieve both 'quotes' and 'goofs' information (with a list or tuple)
                        # i.update(m, ['quotes', 'goofs'])
                        # print m['quotes']
                        # print m['goofs']
                        # # retrieve every available information.
                        # i.update(m, 'all')

                        counter += 1
 def __init__(self, instance="Default"):
     SearchTermFilter.__init__(self, instance=instance)
     tmdb.configure("5c235bb1b487932ebf0a9935c8b39b0a", "EN")
Example #23
0
 def __init__(self, instance='Default'):
     Provider.__init__(self, instance=instance)
     tmdb.configure('5c235bb1b487932ebf0a9935c8b39b0a', self.c.info_language_select)
Example #24
0
def tmdb_init():
    global g_tmdb
    g_tmdb = True
    tmdb.configure(api_key)
Example #25
0
  return [movie['id'] for movie in yearMovies.iter_results()]

def search_movies_for_year(year):
  movieIds = set()
  for keyword in ['a','e','i','o','u']:
    movieIds.update(search_movies(keyword, year))
  movies = []
  for movieId in movieIds:
    try:
      movies.append(tmdb.Movie(movieId).movies)
    except:
      continue
  return movies

api_key = read_file('themoviedb_apikey').strip()
tmdb.configure(api_key)

downloads_directory = args.directory
years = args.years

if not os.path.isdir(downloads_directory):
  print >> sys.stderr, 'Downloads directory %s does not exist'
  sys.exit(1)

year_directory = lambda year : os.path.join(downloads_directory, str(year))

for year in years:
  yearMovies = search_movies_for_year(year)
  print year, len(yearMovies)
  
  movie_filename = lambda year, n : year_directory(year) + '/%06d.json' % (n)
Example #26
0
 def setUp(self):
     tmdb.configure("API_KEY")
     self.movies = tmdb.Movies("The Avengers")
import tmdb
import pprint

tmdb.configure( "c3648d284b99debdb865cf318248b209" )

i = 0
url = "http://api.themoviedb.org/2.1/Movie.search/en/json/c3648d284b99debdb865cf318248b209/%s -O tmdb_files/%s.json"
for line in open('all_titles_from_psql.txt','r'):
	line = line.strip()
	line = line.strip()
	line_plus = line.replace( " " , "+" )
	line_underscore = line.replace( " " , "_" )

	print url % (line_plus, line_underscore)
Example #28
0
        j.append(t[i]['id'])
    except:
        print "ERROR %s" % i

for i in j:
    try:
        print tv.show.summary(i)['title']
    except:
        print i

####
# tmdb
# To install: pip install git+https://github.com/doganaydin/themoviedb.git fuzzywuzzy
####
import tmdb
tmdb.configure(api - key)
movies = tmdb.Movies('Simpson')
movies = tmdb.Movies('fantozzi')
a = movies.get_best_match()
m = tmdb.Movie(a[1]['id'])
for m in movies.iter_results():
    print m['title'].encode('utf-8')

#####
# Mutagen
#####
from mutagen.easyid3 import EasyID3
a = EasyID3(
    '/Volumes/Macintosh HD/andrea/JdownloaderScaricati/Violetta (2012)/08 Are you ready for the ride.mp3'
)
print a
Example #29
0
 def setUp(self):
     tmdb.configure("3e7807c4a01f18298f64662b257d7059")
     self.movie = tmdb.Movie(24428)
Example #30
0
def tmdb_init():
    global g_tmdb
    g_tmdb = True
    tmdb.configure(api_key)
Example #31
0
 def setUp(self):
     tmdb.configure("API_KEY")
     self.core = tmdb.Core()
Example #32
0
 def __init__(self, instance='Default'):
     Provider.__init__(self, instance=instance)
     tmdb.configure('5c235bb1b487932ebf0a9935c8b39b0a',
                    self.c.info_language_select)