Programmatically get a PNG for a unicode emoji - png

In python I have a combined emoji like this: "👨" + "\u200D" + "🔧" which is normally represented as https://emojipedia.org/male-mechanic/. I want to get a PNG version to use as a plot point (in matplotlib, if that helps). Is there any official or unofficial place where I can convert unicode versions of emojis into PNG equivalents?

For anyone else looking for an answer, at the moment I'm using the PNGs from https://unicode.org/emoji/charts/full-emoji-list.html, with a hack that parses the web page, like this
class EmojiConverter:
def __init__(self):
import requests
import re
self.data = requests.get('https://unicode.org/emoji/charts/full-emoji-list.html').text
def to_base64_png(self, emoji, version=0):
"""For different versions, you can set version = 0 for , """
html_search_string = r"<img alt='{}' class='imga' src='data:image/png;base64,([^']+)'>" #'
matchlist = re.findall(html_search_string.format(emoji), self.data)
return matchlist[version]
e = EmojiConverter()
b64 = e.to_base64_png("👨"+"\u200D" + "🔧")

Related

How do I encoding musescore in Music21?

from music21 import *
us = environment.UserSettings()
us["musicxmlPath"] = r"C:/Program Files/MuseScore 3/bin/MuseScore3.exe"
us["musescoreDirectPNGPath"] = r"C:/Program Files/MuseScore 3/bin/MuseScore3.exe"
.
.
.
xml_file_name = f'output_dance_{str(int(time.time()))}.musicxml'
xml_file_path = f'app/data/output_audio/{xml_file_name}'
midi_stream.write('musicxml', fp=xml_file_path)
When I make musicxml in music21, how can I encode musiccore instead of music21?
music21 did actually encode the output from scratch, so that's why it's listed in <software>, but if you wish to change it:
from music21 import *
beach_score = corpus.parse('beach')
beach_score.metadata.software = ['Musescore']
If .metadata doesn't return anything for your score, you may need to insert a metadata.Metadata object into the beginning of your score and manipulate that.

How to construct a unicode glyph key in C#

I am using FontAwesome to display glyphs in my Xamarin Android application. If I hardcode the glyph like this, where everything works fine:
string iconKey = "\uf0a3";
var drawable = new IconDrawable(this.Context, iconKey, "Font Awesome 5 Pro-Regular-400.otf").Color(Xamarin.Forms.Color.White.ToAndroid()).SizeDp(fontSize);
However, if what I have is the four letter code "f0a3" from FontAwesome's cheatsheet, stored in a string variable, I don't know how to set my iconKey variable to a value that works. Just concatenating a "\u" onto the beginning doesn't work, which makes sense since that's a Unicode escape indicator, not part of a standard string, but I don't know what to do instead. I also tried converting to and from Unicode in various random ways - e.g.
iconKey = unicode.GetChars(unicode.GetBytes("/u" + myFourChar.ToString())).ToString();
but unsurprisingly that didn't work either.
The IconDrawable is from here. The value I send becomes an input there to the Paint.GetTextBounds method and the Canvas.DrawText method.
Thanks for any assistance!
Found the answer here. Here is the code I am using, based on that post but simplified since I have only one hexadecimal character to handle:
string myString = "f0a3";
var chars = new char[] { (char)Convert.ToInt32(myString, 16) };
string iconKey = new string(chars);
var drawable = new IconDrawable(this.Context, iconKey, "Font Awesome 5 Pro-Regular-400.otf").Color(Xamarin.Forms.Color.White.ToAndroid()).SizeDp(fontSize);

How to save edited webview result?

Situation description:
Python 3.7, GTK 3.0, PyGObjects 3.34.0 Webkit2 4.0
I have a dialog window, with GtkNotebook containing 2 tabs.
1. tab contains editable Webkit webview, the 2. tab contains textview. One of the arguments provided in class consrtructor is valid HTML snippet as string variable
What I would like to get as a result, is that any changes made in any window, are automatically reflected in other.
Current problem:
Using solution provided here, any previous changes that were made in webview are discarded upon switching the notepad tabs. Debugging shows that html obtained with aforementioned call, does not contain changes.
Any ideas what might be missing in the logic or handling itself?
For reference, the code for the dialog is as follows:
# -*- coding: utf-8 -*-
import gi
gi.require_version('Gtk', '3.0')
gi.require_version('WebKit2', '4.0')
from gi.repository import Gtk, WebKit2
class DescriptionDialog:
def __init__(self, *args):
# GTK Builder
self._builder = args[0]
self._builder.add_from_file("UI/GUI/description.glade")
self.dialog = self._builder.get_object("descriptionDialog")
self._textView = self._builder.get_object("textview1")
self.webViewContainer = self._builder.get_object("WebViewContainer")
self.browserHolder = WebKit2.WebView()
self.browserHolder.set_editable(True)
self.webViewContainer.add(self.browserHolder)
self.browserHolder.show()
# valid html snippet, held as string
self.__buffer_orig__ = args[2]
self.buffer = args[2]
self.browserHolder.load_html(self.buffer)
self._builder.connect_signals(
{
"onDialogClose": self.onDialogClose,
"pageChangeNotebook": self.onPageChange
})
self.dialog.set_transient_for(self._builder.get_object("MainWindow"))
self.textBuffer = self._builder.get_object("textbuffer1")
self.textBuffer.set_text(self.buffer)
self.dialog.show()
def onDialogClose(self, handler):
self.dialog.hide()
def onPageChange(self, notebook=None, scrolledWindow=None, pageNumber=0):
if pageNumber == 0:
self.buffer = self.textBuffer.get_text(self.textBuffer.get_start_iter(), self.textBuffer.get_end_iter(), True)
self.browserHolder.load_html(self.buffer)
if pageNumber == 1:
self.browserHolder.get_main_resource().get_data(None, self.getDataFromResource, None)
def getDataFromResource(self, resource, result, userData=None):
# Changed html is not returned here
self.buffer = str(resource.get_data_finish(result).decode("utf-8"))
self.textBuffer.set_text(self.buffer)
For other internet users finding this thread.
Currently, at the given versions, this is the working result that I have come up with.
Main idea with this implementation is following - use the WebView enabled Javascript engine to obtain the contents of a <body> tag. Then, parse the Javascript result to use this value later on.
def onPageChange(self, notebook=None, scrolledWindow=None, pageNumber=0):
if pageNumber == 0:
self.buffer = self.textBuffer.get_text(self.textBuffer.get_start_iter(), self.textBuffer.get_end_iter(), True)
self.browserHolder.load_html(self.buffer)
if pageNumber == 1:
# use JavaScript to get the html contained in rendered body tag
script = "document.body.innerHTML;"
# Execute JavasScript via WebKit2.WebView bindings.
# Result can be obtained asynchronously, via callback method
self.browserHolder.run_javascript(script, None, self.getJSStatus, None)
def getJSStatus(self, resource, result, userData=None):
# Sample adapted and simplified from here:
# https://lazka.github.io/pgi-docs/#WebKit2-4.0/classes/WebView.html#WebKit2.WebView.run_javascript_finish
# Get the JavaScript result
data = self.browserHolder.run_javascript_finish(result)
# Get value from result, and convert it to string
self.buffer = data.get_js_value().to_string()
self.textBuffer.set_text(self.buffer)

UnicodeEncodeError while I try to fetch a Chinese String from Tkinter.Entry, in Python

An UnicodeEncodeError occurred while I tried to fetch a Chinese string from an Entry, an widget from 'tkinter' module. The operation system on which I am working is Windows 7 and the version of Python is Python3.4. The widget works well on English characters. Here is my program.
from tkinter import *
class LabelEntry(Frame):
def __init__(self, parent, title, **config):
Frame.__init__(self, parent, **config)
self.title = title
self.user_input = StringVar(parent)
self.pack()
self.makeWidgets()
def makeWidgets(self):
Label(self, text=self.title).pack(side=LEFT)
ent = Entry(self, textvariable=self.user_input)
ent.pack(side=RIGHT)
ent.bind('<Return>', self.onReturnKey)
def onReturnKey(self, event):
print(self.user_input.get())
if __name__ == '__main__':
tkroot = Tk()
widget = LabelEntry(tkroot, 'corp_title')
widget.mainloop()
Since I do not know how to solve to problem, I try to modify the program. This time, I do not use StringVar to save the string in the Entry, instead, I use Entry.get() to get the value directly. However, same exception occurs after I input a Chinese string. Here is the new program.
from tkinter import *
class LabelEntry(Frame):
def __init__(self, parent, title, **config):
Frame.__init__(self, parent, **config)
self.title = title
self.pack()
self.makeWidgets()
def makeWidgets(self):
Label(self, text=self.title).pack(side=LEFT)
self.ent = Entry(self)
self.ent.pack(side=RIGHT)
self.ent.bind('<Return>', self.onReturnKey)
def onReturnKey(self, event):
print(self.ent.get())
if __name__ == '__main__':
tkroot = Tk()
widget = LabelEntry(tkroot, 'corp_title')
widget.mainloop()
Please help me, thank you!
Your console may not support, or be correctly configured to support, Chinese characters. Change:
print(self.user_input.get())
to:
print(ascii(self.user_input.get()))
You should see the correct Unicode codepoints displayed.
If you are on Windows, changing Control Panel's Region and Language, Administrative, Current language for non-Unicode programs to a Chinese locale will allow Chinese characters to print in the Windows console.
Better yet, display the text in a widget instead of printing to the console.

Resource Not Found Exception in pyglet

I'm using Python 2.6.6 and pyglet 1.1.4. In my "Erosion" folder, I have "Erosion.py" and a folder named "Images." Inside images, there are .png images. One image is named "Guard.png."
In "Erosion.py" there is a segment that goes like so:
pyglet.resource.path = ['Images']
pyglet.resource.reindex()
self.image = pyglet.resource.image('%s%s' % (character, '.png'))
When I run this, I am given
File "C:\Python26\lib\site-packages\pyglet\resource.py", line 394, in file raise ResourceNotFoundException(name)
ResourceNotFoundException: Resource "Guard.png" was not found on the path. Ensure that the filename has the correct captialisation.
I have tried changing the path to ['./Images'] and ['../Images']. I've also tried removing the path and the reindex call and putting Erosion.py and Guard.png in the same folder.
This is what i do to be able to load resources:
pyglet.resource.path = ['C:\\Users\\myname\\Downloads\\temp']
pyglet.resource.reindex()
pic = pyglet.resource.image('1.jpg')
texture = pic.get_texture()
gl.glTexParameteri(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_MAG_FILTER, gl.GL_NEAREST)
texture.width = 960
texture.height = 720
texture.blit(0, 0, 0)
try this
pyglet.image.load('path/to/image.png')
If the relative path is not working you can try with the absolute path using the os module.
import pyglet
import os
working_dir = os.path.dirname(os.path.realpath(__file__))
pyglet.resource.path = [os.path.join(working_dir,'Images')]
pyglet.resource.reindex()
image = pyglet.resource.image('character.png'))
It's better to use the os.path.join method instead of writing it as a string for a better cross-platform support.
I get a problem like this using pyglet and pyscripter.(the text editor) In order for the file to be found I have to restart the editor before running the program.
This might be a problem with pyscripter however.
It is worth looking into: http://pyglet.readthedocs.io/en/pyglet-1.3-maintenance/programming_guide/resources.html
You should include all the directories into:
pyglet.resource.path = [...]
Then pass the ONLY the file name when you call:
pyglet.resource.image("ball_color.jpeg")
Try:
import os
import pyglet
working_dir = os.path.dirname(os.path.realpath(__file__))
image_dir = os.path.join(working_dir, 'images')
sound_dir = os.path.join(working_dir, 'sound')
print working_dir
print "Images are in: " + image_dir
print "Sounds are in: " + sound_dir
pyglet.resource.path = [working_dir, image_dir, sound_dir]
pyglet.resource.reindex()
try:
window = pyglet.window.Window()
image = pyglet.resource.image("ball_color.jpeg")
#window.event
def on_draw():
window.clear()
image.blit(0, 0)
pyglet.app.run()
finally:
window.close()
The use of try and finally are not necessary, but they are recommended. You might end up with a lot of open windows and pyglet back processes if you don't close the window when there are errors.
pyglet 1.4.4 format: HUD_img = pyglet.resource.image('ui\ui_gray_block_filled.png')
pyglet 1.4.8 format: HUD_img = pyglet.resource.image('ui/ui_gray_block_filled.png')
I was using pyglet 1.4.4 and was able to use this the first format.
After upgrading to pyglet 1.4.8 I had the error: pyglet.resource.ResourceNotFoundException: Resource "your_resource_path" was not found on the path.
Switching to the 2nd format with forward slashes solved this issue for me. Not sure why this change was made...I'm sure there was a good reason for it.