# -*- coding: utf-8 -*-
import sys
# Read various files 
phoneme_file = open('hi_phonet.dat')
unigram_file = open('corpus.txt').read().decode('utf-8').strip().split('\n')
alphabets_file = open('alphabets.txt').read().translate(None,'\n').decode('utf-8')

#    Replace alphabet by Phonemes   
def r_phoneme(phone, a, b, word):
	index = 0;
	index2 = 0;
	for i in word:
		for j in range(len(a)):
			if(i.encode('utf-8') == a[j]):
				if(b[j]  != "_"):
					w = word[0:index]+b[j].decode('utf-8')+word[index+1:]
					phone.append(w)
				else:
					w = word[0:index]+word[index+1:]
					phone.append(w)
		index = index + 1;
	for i in word:
		for j in range(len(b)):
			if(i.encode('utf-8') == b[j]):
				if(b[j]  != "_"):
					w = word[0:index2]+a[j].decode('utf-8')+word[index2+1:]
					phone.append(w)
		index2 = index2 + 1;

#  Construct UniGram Dictionary 
unigram_dict = {}
for line in unigram_file:					
	element=line.split()
	element[1] = element[1].strip();
	unigram_dict[element[1]] = int(element[0].decode('utf-8'))



##    Find unigrams in dictionary 
def check(words, x):
	for w in words:
		try:
			fr = unigram_dict[w];
			x.append([fr, w]);
		except:
			continue;

#  Check existence of unigram 
def check2(word):
	x=0
	try:
		x = unigram_dict[word.decode('utf-8')]
	except:
		x=0
	if(x!=0):
		return 1
	else:
		return 0
	
#  Find Edit1-Distance  
def editsR(word):
   splits     = [(word[:i], word[i:]) for i in range(len(word) + 1)]
   deletes    = [a + b[1:] for a, b in splits if b]
   transposes = [a + b[1] + b[0] + b[2:] for a, b in splits if len(b)>1]
   replaces   = [a + c + b[1:] for a, b in splits for c in alphabets_file if b]
   inserts    = [a + c + b for a, b in splits for c in alphabets_file]
   return set(deletes + transposes + replaces + inserts)


a = []
b = []
for line in phoneme_file:
	ele = line.split(" ")
	ele[0] = ele[0].strip()
	ele[1] = ele[1].strip()
	a.append(ele[0])
	b.append(ele[1])

# Suggestions(Phonetics+Unigram) 
spell = open("hi-spell2.txt")
for line in spell:
	print "                               \n --- \n                         "
	print line
	el=line.split(" ")
	for word in el:
		word=word.strip();	
		if(check2(word) == 1):
			word=word.decode('utf-8').strip()
			prev_word = word
			continue;
		else:
			word=word.decode('utf-8').strip()
			edits = editsR(word)
			uni=[]	
			check(edits, uni)
			uni.sort(key = lambda t:t[0], reverse=True)
			print "\nUnigram suggestions: ", word.encode('utf-8')
			for j in range(3):
				if (uni and j<len(uni)):
					print uni[j][1].encode('utf-8')
					
				 
			phone = []					
			index=0;
			r_phoneme(phone, a, b, word)	
			z = []
			check(phone, z)
			z.sort(key = lambda t:t[0], reverse=True)	
			print "\nPhonetic Suggestions: "
			if(z):
				for w in z:
					print w[1].encode('utf-8')
	
			else:
				print "None"
			prev_word = word
			
