Calculate a cover's "signature" using its thumbnail url.
197231
async def updateSignature(self):
    
    assert(self.thumbnail_sig is None)

    if self.thumbnail_url is None:
      logging.getLogger("Cover").warning("No thumbnail available for %s" % (self))
      return

    # download
    logging.getLogger("Cover").debug("Downloading cover thumbnail '%s'..." % (self.thumbnail_url))
    headers = {}
    self.source.updateHttpHeaders(headers)

    async def pre_cache_callback(img_data):
      return await __class__.crunch(img_data, CoverImageFormat.JPEG, silent=True)

    try:
      store_in_cache_callback, image_data = await self.source.http.query(self.thumbnail_url,
                                                                         cache=__class__.image_cache,
                                                                         headers=headers,
                                                                         pre_cache_callback=pre_cache_callback)
    except Exception as e:
      logging.getLogger("Cover").warning("Download of '%s' failed: %s %s" % (self.thumbnail_url,
                                                                             e.__class__.__qualname__,
                                                                             e))
      return

    # compute sig
    logging.getLogger("Cover").debug("Computing signature of %s..." % (self))
    try:
      self.thumbnail_sig = __class__.computeImgSignature(image_data)
    except Exception as e:
      logging.getLogger("Cover").warning("Failed to compute signature of '%s': %s %s" % (self,
                                                                                         e.__class__.__qualname__,
                                                                                         e))
    else:
      await store_in_cache_callback()
276042
function getFingerprintForURL(url) {
	var domain = getDomain(url);
	var found = global.requestSSLFingerprints[domain];
	debug('getFingerprintForURL %s -> %s=%s',url,domain,found);
	if (!found) {
		// try a wildcard search
		var u = urlib.parse(domain),
			tokens = (u && u.host || domain).split('.');
		domain = '*.'+tokens.splice(tokens.length > 1 ? 0 : 1).join('.');
		found = global.requestSSLFingerprints[domain];
		debug('getFingerprintForURL (wildcard) %s -> %s=%s',url,domain,found);
	}
	return found;
}
182202
def have_thumbnail(self, fitsimage, image):
        
        chname = self.fv.get_channel_name(fitsimage)

        # Look up our version of the thumb
        idx = image.get('idx', None)
        path = image.get('path', None)
        if path is not None:
            path = os.path.abspath(path)
            name = iohelper.name_image_from_path(path, idx=idx)
        else:
            name = 'NoName'

        # get image name
        name = image.get('name', name)

        thumbkey = self.get_thumb_key(chname, name, path)
        with self.thmblock:
            return thumbkey in self.thumb_dict
1325164
def renderThumbnail(self, relpath=""):
        """"""
        # no thumbnail -- return empty string
        if self.thumbnail is None:
            return ""
        # else thumbnail is same as full image (because image was small enough), insert directly
        elif self.thumbnail is self.fullimage:
            fname = relpath + self.fullimage
            return """<IMG SRC="%s" ALT="%s"></IMG>""" % (quote_url(fname), quote_url(os.path.basename(self.filename)))
        # else return thumbnail linking to full image
        else:
            tname = relpath + self.thumbnail
            fname = relpath + self.fullimage
            return """<A HREF="%s"><IMG SRC="%s" ALT="%s"></A>""" % (
            quote_url(fname), quote_url(tname), quote_url(os.path.basename(self.filename)))
93921
def saveThumbnail(self,fileName,filePath):
        
        if self._thumbnail is None:
            self.__init()
        param_dict = {}
        if  self._thumbnail is not None:
            imgUrl = self.root + "/info/" + self._thumbnail
            onlineFileName, file_ext = splitext(self._thumbnail)
            fileNameSafe = "".join(x for x in fileName if x.isalnum()) + file_ext
            result = self._get(url=imgUrl,
                               param_dict=param_dict,
                               securityHandler=self._securityHandler,
                               proxy_url=self._proxy_url,
                               proxy_port=self._proxy_port,
                               out_folder=filePath,
                               file_name=fileNameSafe)
            return result
        else:
            return None
524744
def repr_part(self):
        """"""
        optargs = [('weighting', array_str(self.array, nprint=10), ''),
                   ('exponent', self.exponent, 2.0)]
        return signature_string([], optargs, sep=',\n',
                                mod=[[], ['!s', ':.4']])
484419
def thumbnail(self, path, height, width, quality=100, **kwargs):
        
        params = {'ec': 1,
                  'path': path,
                  'quality': quality,
                  'width': width,
                  'height': height}

        url = 'http://{0}/rest/2.0/pcs/thumbnail'.format(BAIDUPCS_SERVER)
        return self._request('thumbnail', 'generate', url=url, extra_params=params, **kwargs)
1145578
def documentCover(self):
        
        rels_pth = os.path.join(self._cache_dir, "_rels", ".rels")
        rels_xml = lxml.etree.parse(xmlFile(rels_pth, 'rb'))
        thumb_ns = ns_map["thumbnails"]
        thumb_elm_xpr = "relationships:Relationship[@Type='%s']" % thumb_ns
        rels_xpath = lxml.etree.XPath(thumb_elm_xpr, namespaces=ns_map)
        try:
            cover_path = rels_xpath(rels_xml)[0].attrib["Target"]
        except IndexError:
            return None
        cover_fp = open(self._cache_dir + os.sep + cover_path, "rb")
        cover_type = imghdr.what(None, h=cover_fp.read(32))
        cover_fp.seek(0)
        # some MS docs say the type can be JPEG which is ok,
        # or WMF, which imghdr does not recognize...
        if not cover_type:
            cover_type = cover_path.split('.')[-1]
        else:
            cover_type = cover_type.replace("jpeg", "jpg")
        return (cover_type, cover_fp)
1093637
def get_thumbnail_name(self, thumbnail_options, transparent=False,
                           high_resolution=False):
        
        path, filename = os.path.split(self.name)

        basedir = self.thumbnail_basedir
        subdir = self.thumbnail_subdir

        return os.path.join(basedir, path, subdir, filename)
1093008
async def get(self, target_format, target_size, size_tolerance_prct, out_filepath):
    
    if self.source_quality.value <= CoverSourceQuality.LOW.value:
      logging.getLogger("Cover").warning("Cover is from a potentially unreliable source and may be unrelated to the search")

    images_data = []
    for i, url in enumerate(self.urls):
      # download
      logging.getLogger("Cover").info("Downloading cover '%s' (part %u/%u)..." % (url, i + 1, len(self.urls)))
      headers = {}
      self.source.updateHttpHeaders(headers)

      async def pre_cache_callback(img_data):
        return await __class__.crunch(img_data, self.format)

      store_in_cache_callback, image_data = await self.source.http.query(url,
                                                                         headers=headers,
                                                                         verify=False,
                                                                         cache=__class__.image_cache,
                                                                         pre_cache_callback=pre_cache_callback)

      # store immediately in cache
      await store_in_cache_callback()

      # append for multi images
      images_data.append(image_data)

    need_format_change = (self.format != target_format)
    need_size_change = ((max(self.size) > target_size) and
                        (abs(max(self.size) - target_size) >
                         target_size * size_tolerance_prct / 100))
    need_join = len(images_data) > 1
    if need_join or need_format_change or need_size_change:
      # post process
      image_data = self.postProcess(images_data,
                                    target_format if need_format_change else None,
                                    target_size if need_size_change else None)

      # crunch image again
      image_data = await __class__.crunch(image_data, target_format)

    # write it
    with open(out_filepath, "wb") as file:
      file.write(image_data)
1172706
def get_cover_image(self, size=SIZE_EXTRA_LARGE):
        
        if "image" not in self.info:
            self.info["image"] = _extract_all(
                self._request(self.ws_prefix + ".getInfo", cacheable=True), "image"
            )
        return self.info["image"][size]
1229863
def render(parameters = {})

      has_thumbnail = parameters.fetch(:has_thumbnail, true)
      effect_number = parameters.fetch(:effect_number, false)
      thumbnail_template = self.get_template(effect_number)


      if has_thumbnail
        @attributes.map { |key, value| thumbnail_template["###{key}##"] &&= value }
        thumbnail_template.gsub!('##url##', @url).html_safe
      else
        self.to_s.html_safe
      end
    end
737875
def thumbnail(parser, token):
    '''
    
    '''

    thumb = None

    if SORL:
        try:
            thumb = sorl_thumb(parser, token)
        except Exception:
            thumb = False

    if EASY and not thumb:
        thumb = easy_thumb(parser, token)

    return thumb
1310076
def get_cover(song, size=250):
    """"""
    try:
        data = mus.search_releases(artist=song["artist"],
                                   release=song["album"],
                                   limit=1)
        release_id = data["release-list"][0]["release-group"]["id"]
        print(f"album: Using release-id: {data['release-list'][0]['id']}")

        return mus.get_release_group_image_front(release_id, size=size)

    except mus.NetworkError:
        get_cover(song, size)

    except mus.ResponseError:
        print("error: Couldn't find album art for",
              f"{song['artist']} - {song['album']}")
1300070
def computeImgSignature(image_data):
    
    parser = PIL.ImageFile.Parser()
    parser.feed(image_data)
    img = parser.close()
    target_size = (__class__.IMG_SIG_SIZE, __class__.IMG_SIG_SIZE)
    img.thumbnail(target_size, PIL.Image.BICUBIC)
    if img.size != target_size:
      logging.getLogger("Cover").debug("Non square thumbnail after resize to %ux%u, unable to compute signature" % target_size)
      return None
    img = img.convert(mode="RGB")
    pixels = img.getdata()
    pixel_count = target_size[0] * target_size[1]
    color_count = 3
    r = bitarray.bitarray(pixel_count * color_count)
    r.setall(False)
    for ic in range(color_count):
      mean = sum(p[ic] for p in pixels) // pixel_count
      for ip, p in enumerate(pixels):
        if p[ic] > mean:
          r[pixel_count * ic + ip] = True
    return r
1228578
def _save_owner_cover_photo(session, hash, photo):
        
        response = session.fetch('photos.saveOwnerCoverPhoto', hash=hash, photo=photo)
        return response
98667
def verify_signature(key, qs):
    """"""
    unsigned_qs = re.sub(r'&?sig=[^&]*', '', qs)
    sig = derive_signature(key, unsigned_qs)
    return urlparse.parse_qs(qs).get("sig", [None])[0] == sig