Thoughts, stories and ideas.

Drawing anti-aliased unicode text with python

For an app I was hacking during the weekend, I needed to generate images for all characters of Berber alphabet and had to figure out several things

converting hexcode to python unicode

Since there were a lot of characters and they were contiguous, I could loop through them - for this, I had to figure out how to convert hex code into python unicode character

hexCode = '0x2d62'                # U+2d62
intValue = int( hexCode, 16 )     # hex is base 16

# using unicode(intValue) won't work
pyUnicodeChar = unichr( intValue ) 

drawing on the image

Next came the part of drawing it on a ImageDraw surface -

# Load the True Type font for anti-aliasing
font = ImageFont.truetype( 'T_I_UNICODE.ttf', 400 )

# Init the drawing surface
image = Image.new( 'RGBA', (500,500) )
drawPad = ImageDraw.Draw(image)

# Draw pyUnicodeChar string at origin in black with opacity=1
drawPad.text( (0,0), pyUnicodeChar, fill=(0,0,0,225) )

computing font size for centring

Note: ImageFont or ImageDraw, do not provide functionality to centre the text and has to be done manually by computing its size, which can be done this way

# using ImageDraw instance
textSize = drawPad.textsize(pyUnicodeChar, font=font)

# Or, using ImageFont instance
textSize = font.getsize( pyUnicodeChar )

python implementation

Here is the full code to generate the image shown above

# -*- coding: utf-8 -*-
# Above comment is needed if we use unicode chars directly in code

from PIL import Image, ImageDraw, ImageFont
import sys, os

# Constants
fontFile = 'T_I_UNICODE.ttf'

# Unicode characters from the Berber alphabet system
hexcodeChars = ['0x2d62', '0x2d65', '0x2d4b', '0x2d3e']

# Load the font
font = ImageFont.truetype(fontFile, 400)

# Convert the hexCodes to python unicode strings
unicodeChars = map( lambda c: unichr( int(c, 16) ), hexcodeChars )

# Compute the font sizes, to derive an optimal image size
unicodeCharSizes = map( lambda c: font.getsize(c), unicodeChars )
maxCharDimension = max( map( lambda s: max(s), unicodeCharSizes ) )

layoutPadding = 10
gridSize = maxCharDimension*2 + layoutPadding*3

# Initalize the image
theImage = Image.new( 'RGB', (gridSize,gridSize), color='white' )
theDrawPad = ImageDraw.Draw(theImage)

i = 0
for char, size in zip(unicodeChars, unicodeCharSizes):
	x, y = ( i % 2, i / 2 )
	xSize, ySize = size

	# get the grid cell position, and then center the font in that cell
	# as only way to do it is to compute size of char & position it manually
	xPos = (maxCharDimension * x) + (maxCharDimension-xSize)/2.0
	yPos = (maxCharDimension * y) + (maxCharDimension-ySize)/2.0

	theDrawPad.text( (xPos, yPos), char, font=font, fill='black' )
	i += 1


note: PIL & Pillow

  • For using the Image/ImageDraw/ImageFont library, install PIL using
    pip install Pillow
  • the original PIL is quite buggy and is not maintained to by knowledge
    • for example font size returned for true-type fonts is wrong and inconsistent.
  • Pillow is the drop-in replacement/fork for it, which addresses all the issues and is actively maintained.
  • If you have older PIL installed, remove it using pip uninstall PIL

Flask custom template loaders

Flask is amazing. The templating system called jinja2 packed with it is equally amazing.

The default behaviour of flask app is to look for template files specified in app.template_folder directory. Although this will work in most use-cases, sometimes you need additional control over this - for example if you have user specific templates or if you want to load templates from a database, dynamically.

This can be accomplished, by initialising app.jinja_loader with a custom Loader.

Jinja2 ships with serveral different loaders by default. The easiest one is DictLoader, which simply loads tempalte sfrom a dictionary.

from flask import Flask
import jinja2

app = Flask(__name__)
app.jinja_loader = jinja2.DictLoader({
		'index.html' : """
			{% extends 'base.html' %}
			{% block text %}
			Super cool!
			{% endblock %}

		'base.html' : """
			<b>{{ self.text() }}</b>

def doHome():
	return render_template('index.html')

The above example was fairly simple - it still pre-loads all templates. If there is a non-trivial requirement where you want to load them from database, then you can use FunctionLoader

def load_template(template_name):
	is_uptodate = True
	if template_name == 'index.html':
		return ("""
			{% extends 'base.html' %}
			{% block text %}
			Super cool!
			{% endblock %}
		""", None, is_uptodate)

	if template_name == 'base.html':
		return ("""
			<b>{{ self.text() }}</b>
		""", None, is_uptodate)

app.jinja_loader = jinja2.FunctionLoader(load_template)

Jinja2 ships with the following loaders, all of which can be used with flask

  • FileSystemLoader
  • PackageLoader
  • DictLoader
  • FunctionLoader
  • PrefixLoader
  • ChoiceLoader
  • ModuleLoader

Open home webserver to internet

There are several ways to open up your home webserver to the internet, the most popular one involves port forwarding. But it is not something that one can assume to be available in all situations.

If you do have a server already, we can use it to create a tunnel. This essentially involes 2 steps

1. create tunnel from home server to remote server

This creates a tunnel between home_port and remote_port_x.

ssh -R <remote-port-x>:<home_localhost>:<home_port> <remote.server.com>


[8080] = remote port
[5000] = local port

ssh -R 8080:localhost:5000 [email protected]

2. make remote server port internet aware

By default, opening a reverse tunnel, will only bind it to the loopback interface. Which means, home computer will be accessible from localhost:<remote-port-x>, but not from <remote.server.com>:<remote-port-x>.

There are multiple ways to solve this

a. enable GatewayPorts

  1. Open /etc/ssh/sshd_conf on the remote server
  2. Set GatewayPorts to either yes or clientspecified
  3. Restart ssh daemon
    ubuntu - sudo service ssh restart

Ensure that you add -g option to step 1, for step a to work.

b. create local tunnel

Since initial tunnel binds to loopback interface, this local-only tunnel, binds it to all interfaces on a different port, thereby exposing it to the internet.

ssh -L<internet_port>:localhost:<remote-port-x> <remote.server.com>

<remote-port-x> is the same port specified in step 1

c. socat or netcat

Either of these tools can be used to relay traffic between the tunnelled port (I haven't tried this yet)

Propogating iOS Gestures to parent views

If a custom UIView adds UITapGestureRecognizer to one of its elements for example say tracking, the default behaviour would prevent it from the gesture being propogated it to its parent views which may be listening for the same gesture.

Gesture propogation can be ensured simply by implementing a UIGestureRecognizerDelegate method.

- (void)setup {
	UITapGestureRecognizer *gestuer = [[UITapGestureRecognizer alloc] init];
	gesture.delegate = self;

#pragma mark - UIGestureRecognizerDelegate
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer
    return YES;

Unlike other solutions, this does not reqire the UIView subclass to be aware of the existence any other gesture recognizers.

Comparing NSDates from different timezones

Comparing 2 NSDate's is trivial, unless they are from different timezone, in which case one of them should be converted to the other timezone and then compared.

Here is a simple code snippet that I came up with. It gets the offset from GMT in seconds for both timezones and uses the delta to convert a date relative to the other timezone.

// Get time and time zone offset from GMT
NSDate *currentTime = [NSDate date];
NSInteger currentTZSec = [[NSTimeZone defaultTimeZone] secondsFromGMT];

NSDate *otherTime = info.otherTime;
NSInteger otherTZSec = [info.otherTimeZone secondsFromGMT];

// Get timezone delta difference in seconds
NSInteger deltaTZSec = currentTZSec - otherTZSec;

// Convert other time into current timezone
NSDate *otherTimeInUserTZ = [otherTime dateByAddingTimeInterval:deltaTZSec];

// Check if cancellation until time is past current user time
if ( [otherTimeInUserTZ compare:currentTime] == NSOrderedDescending ) {
	NSLog(@"currentTIme < otherTime");
} else {
	NSLog(@"currentTIme > otherTime");