def lookup_local_recording(self, title, channel): """lookup actual recordings to get details for grouped recordings also grab a thumb provided by the pvr """ cache = self._mutils.cache.get("recordingdetails.%s%s" % (title, channel)) if cache: return cache details = {} recordings = self._mutils.kodidb.recordings() for item in recordings: if (title == item["title"] or title in item["file"]) and (channel == item["channel"] or not channel): # grab thumb from pvr if item.get("art"): details["thumbnail"] = get_clean_image( item["art"].get("thumb")) # ignore tvheadend thumb as it returns the channellogo elif item.get("icon") and "imagecache" not in item["icon"]: details["thumbnail"] = get_clean_image(item["icon"]) details["channel"] = item["channel"] details["genre"] = " / ".join(item["genre"]) break self._mutils.cache.set("recordingdetails.%s%s" % (title, channel), details) return details
def lookup_local_library(self, title, media_type): """lookup the title in the local video db""" details = {} filters = [{"operator": "is", "field": "title", "value": title}] if not media_type or media_type == "tvshow": kodi_items = self._mutils.kodidb.tvshows(filters=filters, limits=(0, 1)) if kodi_items: details = kodi_items[0] details["media_type"] = "tvshow" if not details and (not media_type or media_type == "movie"): kodi_items = self._mutils.kodidb.movies(filters=filters, limits=(0, 1)) if kodi_items: details = kodi_items[0] details["media_type"] = "movie" if details: if sys.version_info.major == 3: for artkey, artvalue in details["art"].items(): details["art"][artkey] = get_clean_image(artvalue) else: for artkey, artvalue in details["art"].iteritems(): details["art"][artkey] = get_clean_image(artvalue) # todo: check extrafanart ? return details
def apply_mask_to_image(): """ Input: -Image Original -Image mask (from get_model_unet()) Output -Return a bitwise image applied a applied be """ # print("apply_mask_endpoint", file=sys.stderr) image_orig = request.args.get('orig') image_mask = request.args.get('mask') # 1.- convert base64 uri o png image and save to tmp folder image_name_orig = convert_and_save4(image_orig) image_name_mask = convert_and_save4(image_mask) # 2.- Load image to numpy array img_orig = imread(image_name_orig) img_mask = imread(image_name_mask) # debug_np_to_file(img_mask, '/tmp/mask.jpg') # 3.- resize image to model specs 256x256 resized_image_orig = np.uint8(downsample(img_orig, H, W)) resized_image_mask = np.uint8(downsample(img_mask, H, W)) debug_np_to_file(resized_image_mask, '/tmp/resized_mask.jpg') debug_np_to_file(resized_image_orig, '/tmp/resized_orig.jpg') # 4.- perform bitwise operation to extract car appling mask final = get_clean_image(resized_image_orig, resized_image_mask) debug_np_to_file(final, '/tmp/car.jpg') ret = save_np_array_to_image(final) return ret
def backup_skinshortcuts_properties(propertiesfile, dest_path): '''parse skinshortcuts properties file and translate images''' # look for any backgrounds and translate them propfile = xbmcvfs.File(propertiesfile) data = propfile.read() propfile.close() allprops = eval(data) if data else [] for count, prop in enumerate(allprops): if prop[2] == "background": background = prop[3] if prop[3] else "" defaultid = prop[1] if background.endswith(".jpg") or background.endswith( ".png") or background.endswith(".gif"): background = get_clean_image(background) extension = background.split(".")[-1] newthumb = os.path.join( dest_path, "%s-background-%s.%s" % (xbmc.getSkinDir(), normalize_string(defaultid), extension)) newthumb_vfs = "special://profile/addon_data/script.skinshortcuts/%s-background-%s.%s" % ( xbmc.getSkinDir(), normalize_string(defaultid), extension) if xbmcvfs.exists(background): xbmcvfs.copy(background, newthumb) allprops[count] = [ prop[0], prop[1], prop[2], newthumb_vfs ] # write updated properties file propfile = xbmcvfs.File(propertiesfile, "w") propfile.write(repr(allprops)) propfile.close()
def lookup_local_recording(self, title, channel): '''lookup actual recordings to get details for grouped recordings also grab a thumb provided by the pvr ''' cache = self.metadatautils.cache.get("recordingdetails.%s%s" % (title, channel)) if cache: return cache details = {} recordings = self.metadatautils.kodidb.recordings() for item in recordings: if (title == item["title"] or title in item["file"]) and (channel == item["channel"] or not channel): # grab thumb from pvr if item.get("art"): details["thumbnail"] = get_clean_image(item["art"].get("thumb")) # ignore tvheadend thumb as it returns the channellogo elif item.get("icon") and "imagecache" not in item["icon"]: details["thumbnail"] = get_clean_image(item["icon"]) details["channel"] = item["channel"] details["genre"] = " / ".join(item["genre"]) break self.metadatautils.cache.set("recordingdetails.%s%s" % (title, channel), details) return details
def search_kodi(self, searchphrase): """search kodi json api for channel logo""" result = "" if xbmc.getCondVisibility("PVR.HasTVChannels"): results = self.kodidb.get_json('PVR.GetChannels', fields=["thumbnail"], returntype="tvchannels", optparam=("channelgroupid", "alltv")) for item in results: if item["label"] == searchphrase: channelicon = get_clean_image(item['thumbnail']) if channelicon and xbmcvfs.exists(channelicon): result = channelicon break return result
def lookup_local_library(self, title, media_type): '''lookup the title in the local video db''' details = {} filters = [{"operator": "is", "field": "title", "value": title}] if not media_type or media_type == "tvshow": kodi_items = self.metadatautils.kodidb.tvshows(filters=filters, limits=(0, 1)) if kodi_items: details = kodi_items[0] details["media_type"] = "tvshow" if not details and (not media_type or media_type == "movie"): kodi_items = self.metadatautils.kodidb.movies(filters=filters, limits=(0, 1)) if kodi_items: details = kodi_items[0] details["media_type"] = "movie" if details: for artkey, artvalue in details["art"].iteritems(): details["art"][artkey] = get_clean_image(artvalue) # todo: check extrafanart ? return details
def backup_skinshortcuts_images(shortcutfile, dest_path): '''parse skinshortcuts file and copy images to backup location''' shortcutfile = xbmc.translatePath(shortcutfile).decode("utf-8") doc = parse(shortcutfile) listing = doc.documentElement.getElementsByTagName('shortcut') for shortcut in listing: defaultid = shortcut.getElementsByTagName('defaultID') if defaultid: defaultid = defaultid[0].firstChild if defaultid: defaultid = defaultid.data if not defaultid: defaultid = shortcut.getElementsByTagName( 'label')[0].firstChild.data thumb = shortcut.getElementsByTagName('thumb') if thumb: thumb = thumb[0].firstChild if thumb: thumb = thumb.data if thumb and (thumb.endswith(".jpg") or thumb.endswith(".png") or thumb.endswith(".gif")): thumb = get_clean_image(thumb) extension = thumb.split(".")[-1] newthumb = os.path.join( dest_path, "%s-thumb-%s.%s" % (xbmc.getSkinDir(), normalize_string(defaultid), extension)) newthumb_vfs = "special://profile/addon_data/script.skinshortcuts/%s-thumb-%s.%s" % ( xbmc.getSkinDir(), normalize_string(defaultid), extension) if xbmcvfs.exists(thumb): xbmcvfs.copy(thumb, newthumb) shortcut.getElementsByTagName( 'thumb')[0].firstChild.data = newthumb_vfs # write changes to skinshortcuts file shortcuts_file = xbmcvfs.File(shortcutfile, "w") shortcuts_file.write(doc.toxml(encoding='utf-8')) shortcuts_file.close()
def prepare_listitem(item): '''helper to convert kodi output from json api to compatible format for listitems''' try: # fix values returned from json to be used as listitem values properties = item.get("extraproperties", {}) # set type for idvar in [ ('episode', 'DefaultTVShows.png'), ('tvshow', 'DefaultTVShows.png'), ('movie', 'DefaultMovies.png'), ('song', 'DefaultAudio.png'), ('album', 'DefaultAudio.png'), ('artist', 'DefaultArtist.png'), ('musicvideo', 'DefaultMusicVideos.png'), ('recording', 'DefaultTVShows.png'), ('channel', 'DefaultAddonPVRClient.png')]: dbid = item.get(idvar[0] + "id") if dbid: properties["DBID"] = str(dbid) if not item.get("type"): item["type"] = idvar[0] if not item.get("icon"): item["icon"] = idvar[1] break # general properties if "genre" in item and isinstance(item['genre'], list): item["genre"] = " / ".join(item.get('genre')) if "studio" in item and isinstance(item['studio'], list): item["studio"] = " / ".join(item.get('studio')) if "writer" in item and isinstance(item['writer'], list): item["writer"] = " / ".join(item.get('writer')) if 'director' in item and isinstance(item['director'], list): item["director"] = " / ".join(item.get('director')) if 'artist' in item and not isinstance(item['artist'], list): item["artist"] = [item.get('artist')] if not 'artist' in item: item["artist"] = [] if item['type'] == "album" and not item.get('album'): item['album'] = item.get('label') if not item.get("duration") and item.get("runtime"): if (item["runtime"] / 60) > 300: item["duration"] = item.get("runtime") / 60 else: item["duration"] = item.get("runtime") if not item.get("plot") and item.get("comment"): item["plot"] = item.get("comment") if not item.get("tvshowtitle") and item.get("showtitle"): item["tvshowtitle"] = item.get("showtitle") if not item.get("premiered") and item.get("firstaired"): item["premiered"] = item.get("firstaired") if not properties.get("imdbnumber") and item.get("imdbnumber"): properties["imdbnumber"] = item.get("imdbnumber") if not properties.get("imdbnumber") and item.get("uniqueid"): for value in item["uniqueid"].values(): if value.startswith("tt"): properties["imdbnumber"] = value properties["dbtype"] = item["type"] properties["DBTYPE"] = item["type"] properties["type"] = item["type"] properties["path"] = item.get("file") # cast list_cast = [] list_castandrole = [] item["cast_org"] = item.get("cast", []) if item.get("cast") and isinstance(item["cast"], list): for castmember in item["cast"]: if isinstance(castmember, dict): list_cast.append(castmember.get("name", "")) list_castandrole.append((castmember["name"], castmember["role"])) else: list_cast.append(castmember) list_castandrole.append((castmember, "")) item["cast"] = list_cast item["castandrole"] = list_castandrole if item.get("season") and item.get("episode"): properties["episodeno"] = "s%se%s" % (item.get("season"), item.get("episode")) if item.get("resume"): properties["resumetime"] = str(item['resume']['position']) properties["totaltime"] = str(item['resume']['total']) properties['StartOffset'] = str(item['resume']['position']) # streamdetails if item.get("streamdetails"): streamdetails = item["streamdetails"] audiostreams = streamdetails.get('audio', []) videostreams = streamdetails.get('video', []) subtitles = streamdetails.get('subtitle', []) if len(videostreams) > 0: stream = videostreams[0] height = stream.get("height", "") width = stream.get("width", "") if height and width: resolution = "" if width <= 720 and height <= 480: resolution = "480" elif width <= 768 and height <= 576: resolution = "576" elif width <= 960 and height <= 544: resolution = "540" elif width <= 1280 and height <= 720: resolution = "720" elif width <= 1920 and height <= 1080: resolution = "1080" elif width * height >= 6000000: resolution = "4K" properties["VideoResolution"] = resolution if stream.get("codec", ""): properties["VideoCodec"] = str(stream["codec"]) if stream.get("aspect", ""): properties["VideoAspect"] = str(round(stream["aspect"], 2)) item["streamdetails"]["video"] = stream # grab details of first audio stream if len(audiostreams) > 0: stream = audiostreams[0] properties["AudioCodec"] = stream.get('codec', '') properties["AudioChannels"] = str(stream.get('channels', '')) properties["AudioLanguage"] = stream.get('language', '') item["streamdetails"]["audio"] = stream # grab details of first subtitle if len(subtitles) > 0: properties["SubtitleLanguage"] = subtitles[0].get('language', '') item["streamdetails"]["subtitle"] = subtitles[0] else: item["streamdetails"] = {} item["streamdetails"]["video"] = {'duration': item.get('duration', 0)} # additional music properties if item.get('album_description'): properties["Album_Description"] = item.get('album_description') # pvr properties if item.get("starttime"): # convert utc time to local time item["starttime"] = localdate_from_utc_string(item["starttime"]) item["endtime"] = localdate_from_utc_string(item["endtime"]) # set some localized versions of the time and date as additional properties startdate, starttime = localized_date_time(item['starttime']) enddate, endtime = localized_date_time(item['endtime']) properties["StartTime"] = starttime properties["StartDate"] = startdate properties["EndTime"] = endtime properties["EndDate"] = enddate properties["Date"] = "%s %s-%s" % (startdate, starttime, endtime) properties["StartDateTime"] = "%s %s" % (startdate, starttime) properties["EndDateTime"] = "%s %s" % (enddate, endtime) # set date to startdate item["date"] = arrow.get(item["starttime"]).format("DD.MM.YYYY") if item.get("channellogo"): properties["channellogo"] = item["channellogo"] properties["channelicon"] = item["channellogo"] if item.get("episodename"): properties["episodename"] = item["episodename"] if item.get("channel"): properties["channel"] = item["channel"] properties["channelname"] = item["channel"] item["label2"] = item["channel"] # artwork art = item.get("art", {}) if item["type"] in ["episode", "season"]: if not art.get("fanart") and art.get("season.fanart"): art["fanart"] = art["season.fanart"] if not art.get("poster") and art.get("season.poster"): art["poster"] = art["season.poster"] if not art.get("landscape") and art.get("season.landscape"): art["poster"] = art["season.landscape"] if not art.get("fanart") and art.get("tvshow.fanart"): art["fanart"] = art.get("tvshow.fanart") if not art.get("poster") and art.get("tvshow.poster"): art["poster"] = art.get("tvshow.poster") if not art.get("clearlogo") and art.get("tvshow.clearlogo"): art["clearlogo"] = art.get("tvshow.clearlogo") if not art.get("banner") and art.get("tvshow.banner"): art["banner"] = art.get("tvshow.banner") if not art.get("landscape") and art.get("tvshow.landscape"): art["landscape"] = art.get("tvshow.landscape") if not art.get("fanart") and item.get('fanart'): art["fanart"] = item.get('fanart') if not art.get("thumb") and item.get('thumbnail'): art["thumb"] = get_clean_image(item.get('thumbnail')) if not art.get("thumb") and art.get('poster'): art["thumb"] = get_clean_image(art.get('poster')) if not art.get("thumb") and item.get('icon'): art["thumb"] = get_clean_image(item.get('icon')) if not item.get("thumbnail") and art.get('thumb'): item["thumbnail"] = art["thumb"] for key, value in art.iteritems(): if not isinstance(value, (str, unicode)): art[key] = "" item["art"] = art item["extraproperties"] = properties if "file" not in item: log_msg("Item is missing file path ! --> %s" % item["label"], xbmc.LOGWARNING) item["file"] = "" # return the result return item except Exception as exc: log_exception(__name__, exc) log_msg(item) return None
def get_kodidb_setdata(metadatautils, set_id): '''get moviesetdetails from Kodi DB''' details = {} movieset = metadatautils.kodidb.movieset(set_id, FIELDS_MOVIES) count = 0 runtime = 0 unwatchedcount = 0 watchedcount = 0 runtime = 0 writer = [] director = [] genre = [] countries = [] studio = [] years = [] plot = "" title_list = "" total_movies = len(movieset['movies']) title_header = "[B]%s %s[/B][CR]" % (total_movies, xbmc.getLocalizedString(20342)) all_fanarts = [] details["art"] = movieset["art"] movieset_movies = sorted(movieset['movies'], key=itemgetter("year")) for count, item in enumerate(movieset_movies): if item["playcount"] == 0: unwatchedcount += 1 else: watchedcount += 1 # generic labels for label in ["label", "plot", "year", "rating"]: details['%s.%s' % (count, label)] = item[label] details["%s.DBID" % count] = item["movieid"] details["%s.duration" % count] = item['runtime'] / 60 # art labels art = item['art'] for label in ["poster", "fanart", "landscape", "clearlogo", "clearart", "banner", "discart"]: if art.get(label): details['%s.art.%s' % (count, label)] = get_clean_image(art[label]) if not movieset["art"].get(label): movieset["art"][label] = get_clean_image(art[label]) all_fanarts.append(get_clean_image(art.get("fanart"))) # streamdetails if item.get('streamdetails', ''): streamdetails = item["streamdetails"] audiostreams = streamdetails.get('audio', []) videostreams = streamdetails.get('video', []) subtitles = streamdetails.get('subtitle', []) if len(videostreams) > 0: stream = videostreams[0] height = stream.get("height", "") width = stream.get("width", "") if height and width: resolution = "" if width <= 720 and height <= 480: resolution = "480" elif width <= 768 and height <= 576: resolution = "576" elif width <= 960 and height <= 544: resolution = "540" elif width <= 1280 and height <= 720: resolution = "720" elif width <= 1920 and height <= 1080: resolution = "1080" elif width * height >= 6000000: resolution = "4K" details["%s.resolution" % count] = resolution details["%s.Codec" % count] = stream.get("codec", "") if stream.get("aspect", ""): details["%s.aspectratio" % count] = round(stream["aspect"], 2) if len(audiostreams) > 0: # grab details of first audio stream stream = audiostreams[0] details["%s.audiocodec" % count] = stream.get('codec', '') details["%s.audiochannels" % count] = stream.get('channels', '') details["%s.audiolanguage" % count] = stream.get('language', '') if len(subtitles) > 0: # grab details of first subtitle details["%s.SubTitle" % count] = subtitles[0].get('language', '') title_list += "%s (%s)[CR]" % (item['label'], item['year']) if item['plotoutline']: plot += "[B]%s (%s)[/B][CR]%s[CR][CR]" % (item['label'], item['year'], item['plotoutline']) else: plot += "[B]%s (%s)[/B][CR]%s[CR][CR]" % (item['label'], item['year'], item['plot']) runtime += item['runtime'] if item.get("writer"): writer += [w for w in item["writer"] if w and w not in writer] if item.get("director"): director += [d for d in item["director"] if d and d not in director] if item.get("genre"): genre += [g for g in item["genre"] if g and g not in genre] if item.get("country"): countries += [c for c in item["country"] if c and c not in countries] if item.get("studio"): studio += [s for s in item["studio"] if s and s not in studio] years.append(str(item['year'])) details["plots"] = plot if total_movies > 1: details["extendedplots"] = title_header + title_list + "[CR]" + plot else: details["extendedplots"] = plot details["titles"] = title_list details["runtime"] = runtime / 60 details.update(get_duration(runtime / 60)) details["writer"] = writer details["director"] = director details["genre"] = genre details["studio"] = studio details["years"] = years if len(years) > 1: details["year"] = "%s - %s" % (years[0], years[-1]) else: details["year"] = years[0] if years else "" details["country"] = countries details["watchedcount"] = str(watchedcount) details["unwatchedcount"] = str(unwatchedcount) details.update(metadatautils.studiologos.get_studio_logo(studio, metadatautils.studiologos_path)) details["count"] = total_movies details["art"]["fanarts"] = all_fanarts return details
def create_colortheme(self): '''create a colortheme from current skin color settings''' try: current_skinfont = None json_response = kodi_json("Settings.GetSettingValue", {"setting": "lookandfeel.font"}) if json_response: current_skinfont = json_response current_skincolors = None json_response = kodi_json("Settings.GetSettingValue", {"setting": "lookandfeel.skincolors"}) if json_response: current_skincolors = json_response # user has to enter name for the theme themename = xbmcgui.Dialog().input( self.addon.getLocalizedString(32023), type=xbmcgui.INPUT_ALPHANUM).decode("utf-8") if not themename: return xbmc.executebuiltin("ActivateWindow(busydialog)") xbmc.executebuiltin( "Skin.SetString(SkinHelper.LastColorTheme,%s)" % themename.encode("utf-8")) # add screenshot custom_thumbnail = xbmcgui.Dialog().browse( 2, self.addon.getLocalizedString(32024), 'files') if custom_thumbnail: xbmcvfs.copy(custom_thumbnail, self.userthemes_path + themename + ".jpg") # read the guisettings file to get all skin settings from backuprestore import BackupRestore skinsettingslist = BackupRestore().get_skinsettings([ "color", "opacity", "texture", "panel", "colour", "background", "image" ]) newlist = [] if skinsettingslist: newlist.append(("THEMENAME", themename)) newlist.append( ("DESCRIPTION", self.addon.getLocalizedString(32025))) newlist.append( ("SKINTHEME", xbmc.getInfoLabel("Skin.CurrentTheme"))) newlist.append(("SKINFONT", current_skinfont)) newlist.append(("SKINCOLORS", current_skincolors)) # look for any images in the skin settings and translate them so they can # be included in the theme backup for skinsetting in skinsettingslist: setting_type = skinsetting[0] setting_name = skinsetting[1] setting_value = skinsetting[2] if setting_type == "string" and setting_value: if (setting_value and (setting_value.endswith(".png") or setting_value.endswith(".gif") or setting_value.endswith(".jpg")) and "resource://" not in setting_value): image = get_clean_image(setting_value) extension = image.split(".")[-1] newimage = "%s_%s.%s" % ( themename, normalize_string(setting_name), extension) newimage_path = self.userthemes_path + newimage if xbmcvfs.exists(image): xbmcvfs.copy(image, newimage_path) skinsetting = (setting_type, setting_name, newimage_path) newlist.append(skinsetting) # save guisettings text_file_path = self.userthemes_path + themename + ".theme" text_file = xbmcvfs.File(text_file_path, "w") text_file.write(repr(newlist)) text_file.close() xbmc.executebuiltin("Dialog.Close(busydialog)") xbmcgui.Dialog().ok(self.addon.getLocalizedString(32026), self.addon.getLocalizedString(32027)) except Exception as exc: xbmc.executebuiltin("Dialog.Close(busydialog)") log_exception(__name__, exc) xbmcgui.Dialog().ok(self.addon.getLocalizedString(32028), self.addon.getLocalizedString(32030), str(exc))