def shelf(apps, **kw): carrier = kw.get('carrier', random.choice(CARRIER_CHOICE_DICT.values())) region = REGIONS_DICT[kw.get('region', 'restofworld')].id sh = FeedShelf.objects.create( carrier=carrier.id, description=kw.get('description', 'shelf for ' + carrier.name), name=kw.get('name', '%s Op Shelf' % carrier.name), region=region) gen = pydenticon.Generator(8, 8, foreground=foreground) img = gen.generate(unicode(sh.name).encode('utf8'), 128, 128, output_format='png') with public_storage.open(sh.image_path(''), 'wb') as f: f.write(img) with public_storage.open(sh.image_path('_landing'), 'wb') as f: f.write(img) image_hash = hashlib.md5(img).hexdigest()[:8] sh.update(slug=kw.get('slug', 'shelf-%d' % sh.pk), image_hash=image_hash, image_landing_hash=image_hash) for a in apps: FeedShelfMembership.objects.create(obj=sh, app=a) FeedItem.objects.create(item_type='shelf', shelf=sh, region=region) return sh
def collection(apps, slug, background_image=True, **kw): region = REGIONS_DICT[kw.get('region', 'restofworld')].id colorname = kw.get('color', random.choice(COLLECTION_COLORS.keys())) co = FeedCollection.objects.create( type=kw.get('type', 'listing'), color=colorname, background_color=COLLECTION_COLORS[colorname], slug=slug, description=kw.get('description', '')) name = kw.get('name', 'Collection %s' % co.pk) if background_image: gen = pydenticon.Generator(8, 8, foreground=foreground) img = gen.generate(name, 128, 128, output_format='png') with public_storage.open(co.image_path(''), 'wb') as f: f.write(img) image_hash = hashlib.md5(img).hexdigest()[:8] else: image_hash = None co.name = name co.image_hash = image_hash co.save() for a in apps: FeedCollectionMembership.objects.create(obj=co, app=a) FeedItem.objects.create(item_type='collection', collection=co, region=region) return co
def return_icon(height=100, width=100): response.content_type = 'image/png' address = IP(get_ipaddress()) values = [] if address.version() == 6: address = str(address).split(":") for ochet in address: if ochet == '': values.append("0") elif int(ochet) >= 255: values.append("255") else: values.append(ochet) else: address = str(address).split(".") for ochet in address: values.append(ochet) colors = [] colors.append("rgb(" + values[0] \ + "," + values[1] \ + "," + values[2] + ")") generator = pydenticon.Generator(8, 8, foreground=colors) identicon = generator.generate(get_ipaddress(), height, width) return identicon
async def identicon( self, ctx: commands.Context, user: Union[discord.Member, discord.User, int] = None, ): """ Generate an unique pydenticon with an user's Discord ID Parameters ---------- `[user]` - any valid user that shares a server with this bot (ID|tag#1234|tag) """ msg = "" DEFAULT_SCALE = 9 DEFAULT_SIZE = 120 scale = DEFAULT_SCALE size = DEFAULT_SIZE - DEFAULT_SIZE % scale if isinstance(user, int): try: user = await ctx.bot.fetch_user(user) except discord.NotFound: await ctx.send( chat.error("Discord user with ID `{}` not found").format( user)) return except discord.HTTPException: await ctx.send( chat.warning( "I was unable to get data about user with ID `{}`. Try again later" ).format(user)) return if user is None: user = ctx.author random.seed(user.id) color_white = "#000000" color_black = "#ffffff" fg: [str] bg: str fg = ["#{:06x}".format(random.randint(0x0, 0xFFFFFF))] bg = "#{:06x}".format(random.randint(0x0, 0xFFFFFF)) if fg[0] == bg: # squashing an edge case for some users... bg = color_black if fg != color_black else color_white f = BytesIO() generator = pydenticon.Generator(scale, scale, foreground=fg, background=bg) icon = generator.generate(str(user.id), size, size) f.write(icon) f.seek(0) f.name = "identicon.png" await ctx.send(msg + f"{user.name}'s identicon:", file=discord.File(f))
def produce_identicon(string, bins_count=(10, 10), size=(600, 600), save_path=None, image_format="png", background="rgb(230, 230, 230)", foreground=None): """ Generate identicon picture from hashtag corresponding to the given string. :param string: string to be transformed into identicon. :param bins_count: tuple with numbers of bins in one row and one column. :param size: tuple with width and height of the resulting picture in px. :param save_path: path that the resulting picture will be located at, if None the resulting picture will not be saved on disc. :param foreground: colors to be used as the foregrounds. :param background: colors to be used as the backgrounds. :param image_format: format of the output image file. :return: freshly generated identicon, as bytes buffer. """ if not foreground: foreground = [ "rgb(45,79,255)", "rgb(254,180,44)", "rgb(226,121,234)", "rgb(30,179,253)", "rgb(232,77,65)", "rgb(49,203,115)", "rgb(141,69,170)" ] try: gen = pydenticon.Generator(bins_count[0], bins_count[1], foreground=foreground, background=background) except ValueError: gen = pydenticon.Generator(4, 4, foreground=foreground, background=background) identicon = gen.generate(string, size[0], size[1], output_format=image_format) if save_path: with open(save_path, "wb") as file: file.write(identicon) return identicon
def identicon(self): if not self._identicon: rbw = self._make_rainbow() generator = pydenticon.Generator( 5, 5, digest=hashlib.sha512, foreground=rbw, background="rgba(0,0,0,0)" ) png = generator.generate(str(self.uuid), 64, 64) b64_png = base64.b64encode(png) self._identicon = f"data:image/png;base64,{b64_png.decode()}" self.save() return self._identicon
def __init__(self): foreground = [ "rgb(45,79,255)", "rgb(254,180,44)", "rgb(226,121,234)", "rgb(30,179,253)", "rgb(232,77,65)", "rgb(49,203,115)", "rgb(141,69,170)" ] background = "rgb(224,224,224)" self.generator = pydenticon.Generator(5, 5, foreground=foreground, background=background)
def generate_identicon(user): p = settings.IDENTICON_SETTINGS generator = pydenticon.Generator(p['col'], p['row'], p['digest'], foreground=p['foreground'], background=p['background']) identicon = generator.generate(user.username, 300, 300, padding=p['padding'], output_format=p['output_format']) return io.BytesIO(identicon)
def generate_previews(app, n=1): gen = pydenticon.Generator(8, 12, foreground=foreground, digest=hashlib.sha512) for i in range(n): img = gen.generate(unicode(app.name) + unichr(i), 320, 480, output_format="png") p = Preview.objects.create(addon=app, filetype="image/png", thumbtype="image/png", caption="screenshot " + str(i), position=i) f = tempfile.NamedTemporaryFile(suffix='.png') f.write(img) f.flush() resize_preview(f.name, p.pk)
def generate_avatar(email: str) -> bytes: foreground = [ "#e05923", "#d9534f", "#337ab7", "#006400", "#5bc0de", "#333", ] blocks = (10, 10) size = (250, 250) background = "rgb(255, 255, 255)" generator = pydenticon.Generator(*blocks, digest=hashlib.sha1, foreground=foreground, background=background) return generator.generate(email, *size, output_format="png")
def generate_previews(app, n=1): gen = pydenticon.Generator(8, 12, foreground=foreground, digest=hashlib.sha512) for i in range(n): img = gen.generate(unicode(app.name) + unichr(i), 320, 480, output_format="png") p = Preview.objects.create(addon=app, filetype="image/png", caption="screenshot " + str(i), position=i) fn = tempfile.mktemp() try: f = private_storage.open(fn, 'w') f.write(img) f.close() resize_preview(fn, p.pk) finally: private_storage.delete(fn)
def sequenticon(sequence, output_format='png', size=60, output_path=None): """Return sequenticon image data for the provided sequence. Note: to change the number of rows and columns, or the colors of the sequenticon, change the values in ``sequenticons.SETTINGS`` Parameters ---------- sequence A string, for instance "ATTGTGCGTGTGC". Sequenticon is case-insensitive and will upper-case the full sequence. output_format One of "png", "base64", "html_image". If "png", raw PNG image data is returned (as bytes). If base64, the png data is base64-encoded (string), and if html_image, the returned string is ``<img src='data:X'/>`` where X is base64 image data (this string is ready to be used in a webpage). size The sequenticon image will be of dimensions (size x size), in pixels. output_path Optional path to a PNG file to which to write the sequenticon """ if hasattr(sequence, 'seq'): sequence = str(sequence.seq) sequence = sequence.upper() generator = pydenticon.Generator(SETTINGS["rows"], SETTINGS["columns"], foreground=SETTINGS["color_palette"]) img = generator.generate(sequence, size, size) base_64 = base64.b64encode(img).decode() html_image = "<img src='data:image/png;base64,%s'/>" % base_64 data = { 'png': img, 'base64': base_64, 'html_image': html_image }[output_format] if output_path is not None: with open(output_path, "wb") as f: f.write(data) return data
def __init__(self, templates, output, title, publisher, dump, cores, cursor, conn, deflate, site_url,redirect_file, mathjax, nopic, nouserprofile): self.identicon_path = os.path.join(output, 'static', 'identicon') self.templates=templates self.output=output self.title=title self.publisher=publisher self.dump=dump self.cores=cores self.cursor=cursor self.conn=conn self.deflate=deflate self.site_url=site_url self.mathjax=mathjax self.nopic=nopic self.nouserprofile=nouserprofile self.id=0 if not os.path.exists(self.identicon_path): os.makedirs(self.identicon_path) os.makedirs(os.path.join(output, 'user')) # Set-up a list of foreground colours (taken from Sigil). self.foreground = [ "rgb(45,79,255)", "rgb(254,180,44)", "rgb(226,121,234)", "rgb(30,179,253)", "rgb(232,77,65)", "rgb(49,203,115)", "rgb(141,69,170)" ] # Set-up a background colour (taken from Sigil). self.background = "rgb(224,224,224)" # Instantiate a generator that will create 5x5 block identicons # using SHA256 digest. self.generator = pydenticon.Generator(5, 5, foreground=self.foreground, background=self.background) # noqa self.request_queue = Queue(cores*2) self.workers = [] self.user={} for i in range(self.cores): self.workers.append(Worker(self.request_queue)) for i in self.workers: i.start() self.f_redirect = open(redirect_file, "a")
def generate_pydenticon(identifier, size): ''' Use pydenticon to generate an identicon image. All parameters are extracted from configuration. ''' blocks_size = get_internal_config('size') foreground = get_internal_config('foreground') background = get_internal_config('background') generator = pydenticon.Generator(blocks_size, blocks_size, digest=hashlib.sha1, foreground=foreground, background=background) # Pydenticon adds padding to the size and as a consequence # we need to compute the size without the padding padding = int(round(get_internal_config('padding') * size / 100.)) size = size - 2 * padding padding = (padding, ) * 4 return generator.generate(identifier, size, size, padding=padding, output_format='png')
def app_item(a, type, **kw): region = REGIONS_DICT[kw.get('region', 'restofworld')].id colorname = kw.get('color', random.choice(COLLECTION_COLORS.keys())) gen = pydenticon.Generator(8, 8, foreground=foreground) img = gen.generate(a.app_slug, 128, 128, output_format='png') ap = FeedApp.objects.create( app=a, description=kw.get('description', rand_text(12)), type=type, color=colorname, preview=kw.get('preview', None), pullquote_attribution=kw.get('pullquote_attribution', None), pullquote_rating=kw.get('pullquote_rating', None), pullquote_text=kw.get('pullquote_text', None), background_color=COLLECTION_COLORS[colorname], slug=kw.get('slug', 'feed-app-%d' % a.pk)) with public_storage.open(ap.image_path(''), 'wb') as f: f.write(img) image_hash = hashlib.md5(img).hexdigest()[:8] ap.update(image_hash=image_hash) FeedItem.objects.create(item_type='app', app=ap, region=region) return ap
def register(request): if request.method == 'POST': form = MemberRegModelForm(request.POST) if form.is_valid(): username = form.cleaned_data['username'] password = form.cleaned_data['password'] password2 = form.cleaned_data['password2'] email = form.cleaned_data['email'] member = form.save(commit=False) user = User.objects.create_user(username=username, email=email, password=password) member.user = user human = True foreground = [ "rgb(45,79,255)", "rgb(254,180,44)", "rgb(226,121,234)", "rgb(30,179,253)", "rgb(232,77,65)", "rgb(49,203,115)", "rgb(141,69,170)" ] background = "rgb(231,231,231)" identicon_generator = pydenticon.Generator(5, 5, foreground=foreground, background=background) identicon = identicon_generator.generate(username, 240, 240) f = open("media/media/" + username + ".png", "wb") f.write(identicon) f.close() member.prof_image = "media/" + username + ".png" member.save() return HttpResponseRedirect('/login/') return render(request, 'register.html', {'form': form}) else: form = MemberRegModelForm() return render(request, 'register.html', {'form': form})
def view_identicon(request, board_id, width=40, height=40): board = get_user_board_or_404(request.user, board_id, is_archived=None) # List of colors taken from example http://pydenticon.readthedocs.io/en/0.3/usage.html#instantiating-a-generator foreground = [ "#{0}".format(board.title_color), "rgb(45,79,255)", "rgb(254,180,44)", "rgb(226,121,234)", "rgb(30,179,253)", "rgb(232,77,65)", "rgb(49,203,115)", "rgb(141,69,170)" ] # Background color taken from example http://pydenticon.readthedocs.io/en/0.3/usage.html#instantiating-a-generator background = u"#{0}".format(board.background_color) identicon_hash = hashlib.sha1(board.name.encode('utf-8')).hexdigest() # If the identicon is already stored, return it if identicon_hash == board.identicon_hash: return HttpResponseRedirect(board.identicon.url) # Otherwise, its generation is needed board.identicon_hash = identicon_hash generator = pydenticon.Generator(5, 5, digest=hashlib.sha1, foreground=foreground, background=background) identicon_png = generator.generate(board.name, int(width), int(height), output_format="png") board.identicon.save(u"{0}".format(identicon_hash), ContentFile(identicon_png)) board.save() return HttpResponseRedirect(board.identicon.url)
import pydenticon # Set-up a list of foreground colours (taken from Sigil). foreground = [ "rgb(45,79,255)", "rgb(254,180,44)", "rgb(226,121,234)", "rgb(30,179,253)", "rgb(232,77,65)", "rgb(49,203,115)", "rgb(141,69,170)" ] # Set-up a background colour (taken from Sigil). background = "rgba(224,224,224,0)" # Set-up the padding (top, bottom, left, right) in pixels. padding = (20, 20, 20, 20) # Instantiate a generator that will create 5x5 block identicons using SHA1 # digest. generator = pydenticon.Generator(10, 10, foreground=foreground, background=background) identicon = generator.generate(USER, 200, 200, padding=padding, output_format="png") filename = "js_pydenticon.png" with open(filename, mode="wb") as f: f.write(identicon)
import pydenticon from app import * generator=pydenticon.Generator(10,10) def generate_identicon(string,filename,location): identicon_png=generator.generate(string, 200, 200, output_format="png") f=open(location+".png", "wb") f.write(identicon_png) f.close()
"rgb(0,250,154)", "rgb(102,205,170)", "rgb(47,79,79)", "rgb(60,179,113)", "rgb(175,238,238)", "rgb(95,158,160)", "rgb(255,192,203)", "rgb(221,160,221)", "rgb(255,228,181)", "rgb(119,136,153)", "rgb(188,143,143)",] # background colour background = "rgb(224,224,224)" # generator creating 5x5 block avatar generator = pydenticon.Generator(AVATAR_BLOCK_NUM, AVATAR_BLOCK_NUM, digest=hashlib.sha1, foreground=foreground, background=background) # generate avatar def generateAvatar(name): # set up padding size pad = int (AVATAR_SIZE/10) padding = (pad, pad, pad, pad) # create a printable version in terminal icon_ascii = generator.generate(name, AVATAR_SIZE, AVATAR_SIZE, padding=padding, output_format="ascii") icon_png = generator.generate(name, AVATAR_SIZE, AVATAR_SIZE, padding=padding, output_format="png") # write image to file filePath = "./images/temp.png"
def generate_identicon(sample_id): identicon_generator = pydenticon.Generator( 6, 6, foreground=["red", "blue", "green", "purple"]) img = identicon_generator.generate(sample_id, 60, 60) return "data:image/png;base64,%s" % (base64.b64encode(img).decode())
def generate_identicon(sample_id): identicon_generator = pydenticon.Generator( 6, 6, foreground=['red', 'blue', 'green', 'purple']) img = identicon_generator.generate(sample_id, 60, 60) return 'data:image/png;base64,%s' % (base64.b64encode(img).decode())
def generate_icon(app): gen = pydenticon.Generator(8, 8, foreground=foreground) img = gen.generate(unicode(app.name), 128, 128, output_format="png") save_icon(app, img)
class FakeDigest: """ Return hash passed to constructor, imitating parts of hashlib digest which are used by pydenticon """ def __init__(self, val): self.val = val def hexdigest(self): # pydenticon checks if >23 bits are produced for 'test' input if len(self.val) < 6: return (self.val + b''.join([b'0' for i in range(6)]))[:6] else: return self.val pydenticon_generator = pydenticon.Generator(5, 5, digest=FakeDigest) class StoreTreeView(QTreeView): def __init__(self, *args, **kwargs): self.status_bar = kwargs.pop('status_bar') super(StoreTreeView, self).__init__(*args, **kwargs) model = QStandardItemModel() self.setModel(model) self.setHeaderHidden(True) self.setSelectionMode(QTreeView.ExtendedSelection) self.setMouseTracking(True) self.expanded.connect(self.expanded__handler) self.entered.connect(lambda index: self.status_bar.showMessage( self.model().itemFromIndex(index).data())) self.selectionModel().currentChanged.connect(