#!/usr/bin/env python """ Toki Pona to English Translation CGI Author: Sean B. Palmer, inamidst.com """ import cgitb; cgitb.enable() import sys, os, re, urllib import cgi, random, textwrap r_wordOrTag = re.compile(r'((?:[A-Za-z]+)|(?:<(?!\!)[^>]+>))') r_head = re.compile(r'(?ims)
]*>') form = cgi.FieldStorage() form.__call__ = lambda s: form[s].value nimi = {} if os.path.isfile('./nimi.txt'): nimifn = './nimi.txt' else: nimifn = '../misc/nimi.txt' f = open(nimifn) for line in f: line = line.rstrip('\r\n') word, translations = line.split(': ', 1) translations = translations.split(', ') nimi[word] = translations f.close() def translateWord(word): w = word.lower() if nimi.has_key(w): return random.choice(nimi[w]) return {'li': 'is', 'la': "it's said", 'e': 'such'}.get(w) or word def translate(s): def translateMatch(m): wordOrTag = m.group(1) if wordOrTag.startswith('<'): return wordOrTag return translateWord(wordOrTag) return r_wordOrTag.sub(translateMatch, s) def translateURI(uri): u = urllib.urlopen(uri) translation = translate(u.read()) u.close() return translation def homepage(): print textwrap.dedent((""" Content-Type: text/html; charset=utf-8More information: about this service, Python source.
Sean B. Palmer """).lstrip('\n')) sys.exit() def serve(): if form.has_key('uri'): uri = form('uri') else: uri = False if form.has_key('text'): text = form('text') else: text = False if uri: assert ':' in uri u = urllib.urlopen(uri) info = u.info() text = u.read() u.close() mediatype = info.get('Content-Type') or 'text/html; charset=utf-8' if mediatype.startswith('text/html'): base = '\n