Advertisement
Acid_Alchamy

TheMovieDb

Apr 16th, 2023
574
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 13.46 KB | None | 0 0
  1. ### TheMovieDb ###  Does movies but also series, for which i call it tsdb in metadata id ##
  2. # TMDB_SEARCH_BY_IMDBID       = "https://api.TheMovieDb.org/3/find/tt0412142?api_key=7f4a0bd0bd3315bb832e17feda70b5cd&external_source=imdb_id"
  3.  
  4. ### Imports ###
  5. # Python Modules #
  6. import os
  7. # HAMA Modules #
  8. import common
  9. from common import Log, DictString, Dict, SaveDict # Direct import of heavily used functions
  10.  
  11. ### Variables ###
  12. TMDB_API_KEY                = '7f4a0bd0bd3315bb832e17feda70b5cd'
  13. TMDB_MOVIE_SEARCH           = 'https://api.tmdb.org/3/search/movie?api_key=%s&query={query}&year=&language=en&include_adult=true' % TMDB_API_KEY
  14. TMDB_MOVIE_SEARCH_BY_TMDBID = 'https://api.tmdb.org/3/movie/{id}?api_key=%s&append_to_response=releases,credits,trailers,external_ids&language=en' % TMDB_API_KEY  # Work with IMDbid
  15. TMDB_SERIE_SEARCH_BY_TVDBID = "https://api.TheMovieDb.org/3/find/{id}?api_key=%s&external_source=tvdb_id&append_to_response=releases,credits,trailers,external_ids&language=en" % TMDB_API_KEY
  16. TMDB_CONFIG_URL             = 'https://api.tmdb.org/3/configuration?api_key=%s' % TMDB_API_KEY
  17. #TMDB_MOVIE_GENRE_LIST       = "https://api.TheMovieDb.org/3/genre/movie/list?api_key=%s&language=en" % TMDB_API_KEY
  18. #TMDB_SERIE_GENRE_LIST       = "https://api.TheMovieDb.org/3/genre/tv/list?api_key=%s&language=en" % TMDB_API_KEY
  19. TMDB_MOVIE_IMAGES_URL       = 'https://api.tmdb.org/3/{mode}/{id}/images?api_key=%s' % TMDB_API_KEY
  20.  
  21. ### ###
  22. def GetMetadata(media, movie, TVDBid, TMDbid, IMDbid):
  23.   Log.Info("=== TheMovieDb.GetMetadata() ===".ljust(157, '='))
  24.   TheMovieDb_dict = {}
  25.   TSDbid          = ""
  26.  
  27.   Log.Info("TVDBid: '{}', TMDbid: '{}', IMDbid: '{}'".format(TVDBid, TMDbid, IMDbid))
  28.   if   TMDbid:            url, filename = TMDB_MOVIE_SEARCH_BY_TMDBID.format(id=TMDbid), "TMDB-"+TMDbid+".json"
  29.   elif IMDbid:            url, filename = TMDB_MOVIE_SEARCH_BY_TMDBID.format(id=IMDbid), "IMDb-"+IMDbid+".json"
  30.   elif TVDBid.isdigit():  url, filename = TMDB_SERIE_SEARCH_BY_TVDBID.format(id=TVDBid), "TVDB-"+TVDBid+".json"
  31.   else:                   return TheMovieDb_dict, TSDbid, TMDbid, IMDbid
  32.  
  33.   mode           = "movie" if movie else "tv"
  34.   Log.Info(("--- %s ---" % mode).ljust(157, '-'))
  35.   json           = common.LoadFile(filename=filename,               relativeDirectory=os.path.join('TheMovieDb', 'json'), url=url)
  36.   config_dict    = common.LoadFile(filename="TMDB_CONFIG_URL.json", relativeDirectory="TheMovieDb",                       url=TMDB_CONFIG_URL, cache=CACHE_1MONTH)
  37.   image_base_url = Dict(config_dict, 'images', 'secure_base_url')
  38.   if not json:  Log.Info("TMDB - url: failed to get json" + TMDB_MOVIE_SEARCH_BY_TMDBID.format(id=TMDbid))
  39.   else:  
  40.     if   Dict(json, 'tv_results'   ):  json, mode = json['tv_results'   ][0], "tv"
  41.     elif Dict(json, 'movie_results'):  json, mode = json['movie_results'][0], "movie"
  42.    
  43.     Log.Info("[ ] title: {}"                  .format(SaveDict( Dict(json, 'title') or Dict(json, 'name'),                  TheMovieDb_dict, 'title'                  )))
  44.     Log.Info("[ ] rating: {}"                 .format(SaveDict( Dict(json, 'vote_average'),                                 TheMovieDb_dict, 'rating'                 )))  #if 'vote_count' in json and json['vote_count'] > 3:  SaveDict( Dict(json, 'vote_average'), TheMovieDb_dict, 'rating')
  45.     Log.Info("[ ] tagline: {}"                .format(SaveDict( Dict(json, 'tagline'),                                      TheMovieDb_dict, 'tagline'                )))
  46.     Log.Info("[ ] summary: {}"                .format(SaveDict( Dict(json, 'overview'),                                     TheMovieDb_dict, 'summary'                )))
  47.     Log.Info("[ ] duration: {}"               .format(SaveDict( Dict(json, 'runtime'),                                      TheMovieDb_dict, 'duration'               )))
  48.     Log.Info("[ ] countries: {}"              .format(SaveDict( Dict(json, 'origin_country'),                               TheMovieDb_dict, 'countries'              )))
  49.     Log.Info("[ ] originally_available_at: {}".format(SaveDict( Dict(json, 'first_air_date') or Dict(json, 'release_date'), TheMovieDb_dict, 'originally_available_at')))
  50.     if Dict(json, 'belongs_to_collection', 'name'):  Log.Info("[ ] collections: {}".format(SaveDict( [ Dict(json, 'belongs_to_collection', 'name')],                                TheMovieDb_dict, 'collections')))
  51.     if Dict(json, 'genres'                       ):  Log.Info("[ ] genres: {}"     .format(SaveDict( sorted([ Dict(genre, 'name') for genre in Dict(json, 'genres', default=[]) ]), TheMovieDb_dict, 'genres'     )))
  52.     if Dict(json, 'poster_path'                  ):  Log.Info("[ ] poster: {}"     .format(image_base_url + 'original' + json['poster_path']  )); SaveDict( (os.path.join('TheMovieDb', 'poster',  json['poster_path'  ].lstrip('/')), common.poster_rank('TheMovieDb', 'posters'), None),                                            TheMovieDb_dict, 'posters', image_base_url + 'original' + json['poster_path']  )
  53.     if Dict(json, 'backdrop_path'                ):  Log.Info("[ ] art: {}"        .format(image_base_url + 'original' + json['backdrop_path'])); SaveDict( (os.path.join('TheMovieDb', 'artwork', json['backdrop_path'].lstrip('/')), common.poster_rank('TheMovieDb', 'art'    ), image_base_url + 'w300' + json['backdrop_path']), TheMovieDb_dict, 'art',     image_base_url + 'original' + json['backdrop_path'])
  54.     try:     Log.Info("[ ] duration: {}".format(SaveDict( int(Dict(json, 'duration')) * 60 * 1000,  TheMovieDb_dict, 'duration')))
  55.     except:  pass
  56.     if mode=='tv':   TSDbid = str(Dict(json, 'id'))
  57.     elif not TMDbid: TMDbid = str(Dict(json, 'id'))
  58.     if not IMDbid:   IMDbid = Dict(json, 'imdb_id')
  59.    
  60.     for studio in Dict(json, 'production_companies', default=[]):
  61.       if studio['id'] <= json['production_companies'][0]['id']:
  62.         Log.Info("[ ] studio: {}".format(SaveDict( studio['name'].strip(), TheMovieDb_dict, 'studio')))
  63.  
  64.   ### More pictures ###
  65.   Log.Info("--- pictures.more ---".ljust(157, '-'))
  66.   Log.Info("TMDbid: '{}', TSDbid: '{}', IMDbid: '{}'".format(TMDbid, TSDbid, IMDbid))
  67.   for id in IMDbid.split(',') if ',' in IMDbid else []:
  68.     json                  = common.LoadFile(filename="TMDB-"+(IMDbid or TMDbid)+".json", relativeDirectory="TMDB", url=TMDB_MOVIE_IMAGES_URL.format(id=id, mode=mode))
  69.     for index, poster in enumerate(Dict(json, 'posters', default=[])):
  70.       if Dict(poster,   'file_path'):  Log.Info("[ ] poster: {}" .format(image_base_url + 'original' + poster['file_path'] )); SaveDict((os.path.join('TheMovieDb', 'poster',  "%s-%s.jpg" % (TMDbid, index)),     common.poster_rank('TheMovieDb', 'posters'), None),                                            TheMovieDb_dict, 'posters', image_base_url + 'original' + poster['file_path']  )
  71.     for index, backdrop in enumerate(Dict(json, 'backdrops', default=[])):
  72.       if Dict(backdrop, 'file_path'):  Log.Info("[ ] artwork: {}".format(image_base_url + 'original'+ backdrop['file_path'])); SaveDict((os.path.join('TheMovieDb', 'artwork', "%s-%s-art.jpg" % (TMDbid, index)), common.poster_rank('TheMovieDb', 'art'),     image_base_url + 'w300' + backdrop['file_path']), TheMovieDb_dict, 'art',     image_base_url + 'original' + backdrop['file_path'])
  73.  
  74.   Log.Info("--- return ---".ljust(157, '-'))
  75.   Log.Info("TheMovieDb_dict: {}".format(DictString(TheMovieDb_dict, 4)))
  76.   return TheMovieDb_dict, TSDbid, TMDbid, IMDbid
  77.  
  78. ### TMDB movie search ###
  79. def Search(results, media, lang, manual, movie):
  80.   Log.Info("=== TheMovieDb.Search() ===".ljust(157, '='))
  81.   #'Uchiage Hanabi, Shita kara Miru ka? Yoko kara Miru ka? 打ち上げ花火、下から見るか?横から見るか?' Failed with: TypeError: not all arguments converted during string formatting
  82.   #Fixed with:tmdb_url = TMDB_MOVIE_SEARCH.format(query=String.Quote(orig_title)) Log.Info("TMDB - url: " + tmdb_url) try: json = JSON.ObjectFromURL(tmdb_url, sleep=2.0, headers={'Accept': 'application/json'}, cacheTime=CACHE_1WEEK * 2) except Exception as e: Log.Error("get_json - Error fetching JSON page '%s', Exception: '%s'" % (tmdb_url, e) )
  83.   orig_title = String.Quote(media.name if manual and movie else media.title if movie else media.show)
  84.   maxi = 0
  85.  
  86.   Log.Info("TMDB  - url: " + TMDB_MOVIE_SEARCH.format(query=orig_title))
  87.   try:                    json = JSON.ObjectFromURL(TMDB_MOVIE_SEARCH.format(query=orig_title), sleep=2.0, headers=common.COMMON_HEADERS, cacheTime=CACHE_1WEEK * 2)
  88.   except Exception as e:  Log.Error("get_json - Error fetching JSON page '%s', Exception: '%s'" %( TMDB_MOVIE_SEARCH.format(query=orig_title), e)) # json   = common.get_json(TMDB_MOVIE_SEARCH % orig_title, cache_time=CACHE_1WEEK * 2)
  89.   else:
  90.     if isinstance(json, dict) and 'results' in json:
  91.       for movie in json['results']:
  92.         a, b  = orig_title, movie['title'].encode('utf-8')
  93.         score = 100 - 100*Util.LevenshteinDistance(a,b) / max(len(a),len(b)) if a!=b else 100
  94.         if maxi<score:  maxi = score
  95.         Log.Info("TMDB  - score: '%3d', id: '%6s', title: '%s'" % (score, movie['id'],  movie['title']) )
  96.         results.Append(MetadataSearchResult(id="tmdb-"+str(movie['id']), name="{} [{}-{}]".format(movie['title'], "tmdb", movie['id']), year=None, lang=lang, score=score) )
  97.         if '' in movie and movie['adult']!="null":  Log.Info("adult: '{}'".format(movie['adult']))
  98.   return maxi
  99. ### Trailers (Movie Library Only) ###
  100. ### For when youtube mp4 url can be gotten again
  101. '''
  102.  YOUTUBE_VIDEO_DETAILS = 'https://m.youtube.com/watch?ajax=1&v=%s'
  103.  TYPE_MAP =  { 'primary_trailer'   : TrailerObject,          'trailer'           : TrailerObject,       'interview'         : InterviewObject,
  104.                'behind_the_scenes' : BehindTheScenesObject,  'scene_or_sample'   : SceneOrSampleObject
  105.              }  #https://github.com/plexinc-agents/PlexMovie.bundle/blob/master/Contents/Code/__init__.py
  106.  #metadata.extras.add(Trailer(title=title, file=os.path.join(folder_path, f)))  #https://github.com/gboudreau/XBMCnfoMoviesImporter.bundle/blob/master/Contents/Code/__init__.py
  107.  extras = []
  108.  if movie:  # https://github.com/sander1/YouTube-Agent.bundle/blob/master/Contents/Code/__init__.py
  109.    if 'trailers' in json and json['trailers']:
  110.      if "quicktime" in json['trailers'] and json['trailers']["quicktime"]:
  111.        for trailer in json['trailers']["quicktime"]:
  112.          Log.Info("Trailer detected: " + str (json['trailers']["quicktime"]))
  113.          #metadata.extras.add( TrailerObject(url = "???"+trailer["source"]), title = trailer["name"], thumb = None) )
  114.      if "youtube" in json['trailers'] and json['trailers']["youtube"]:
  115.        for trailer in json['trailers']["youtube"]:
  116.          Log.Info("Trailer detected: name: '%s', size: '%s', source: '%s', type: '%s', link: '%s'" % (trailer["name"], trailer["size"], trailer["source"], trailer["type"], "https://www.youtube.com/watch?v="+trailer["source"]))
  117.          json_obj = None
  118.          try:     json_obj = JSON.ObjectFromString( HTTP.Request(YOUTUBE_VIDEO_DETAILS % trailer["source"]).content[4:] )['content']
  119.          except:  Log("TheMovieDb.GetMetadata() - Trailers - Could not retrieve data from YouTube for: '%s'" % trailer["source"])
  120.          if json_obj:
  121.            Log.Info("TheMovieDb.GetMetadata() - Trailers - json_obj: '%s'" % str(json_obj))
  122.            #metadata.extras.add( TrailerObject(url = "https://www.youtube.com/watch?v="+trailer["source"]), title = json_obj['video']['title'], thumb = 'https://%s' % (json_obj['video']['thumbnail_for_watch'].split('//')[-1])) )
  123.            #metadata.extras.add( TrailerObject(url = "https://www.youtube.com/watch?v="+trailer["source"]), title = json_obj['video']['title'], thumb = Proxy.Preview(HTTP.Request('https://%s' % (json_obj['video']['thumbnail_for_watch'].split('//')[-1])  ).content, sort_order=1))
  124.            metadata.extras.add(TrailerObject(url                     = "https://www.youtube.com/watch?v="+trailer["source"],
  125.                                              title                   = json_obj['video']['title'],
  126.                                              #year                    = avail.year,
  127.                                              #originally_available_at = avail,
  128.                                              thumb                   = 'https://%s' % (json_obj['video']['thumbnail_for_watch'].split('//')[-1]) if 'thumbnail_for_watch' in json_obj['video'] else None
  129.                                             )
  130.                               )
  131.            #metadata.title                   = json_obj['video']['title']
  132.            #metadata.duration                = json_obj['video']['length_seconds'] * 1000
  133.            #thumb                            = 'https://%s' % (json_obj['video']['thumbnail_for_watch'].split('//')[-1])
  134.            #metadata.posters[thumb]          = Proxy.Preview(HTTP.Request(thumb).content, sort_order=1)
  135.            #metadata.summary                 = json_obj['video_main_content']['contents'][0]['description']['runs'][0]['text']
  136.            #date                             = Datetime.ParseDate(json_obj['video_main_content']['contents'][0]['date_text']['runs'][0]['text'].split('Published on ')[-1])
  137.            #metadata.originally_available_at = date.date()
  138.            #metadata.year                    = date.year
  139.            # Add YouTube user as director
  140.             #metadata.directors.clear()
  141.            #if Prefs['add_user_as_director']:
  142.            #  meta_director = metadata.directors.new()
  143.            #  meta_director.name  = json_obj['video_main_content']['contents'][0]['short_byline_text']['runs'][0]['text']
  144.            #  meta_director.photo = json_obj['video_main_content']['contents'][0]['thumbnail']['url'].replace('/s88-', '/s512-')
  145.             #  
  146.  '''
  147.  
  148.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement