#Python 3.x script
import codecs
import operator

alphabets='कखगघङचछजझञटठडढणतथदधनपफबभमयरऱलळवशषसह'
swar='अआइईउऊऋऌऍऎएऐऑऒऔॠॡ'
matra='ािीुूेैोौॆ्ॉॅॊृ'
symbols='ः़ँंऽ'
all_alphabet=alphabets+swar+matra+symbols

def getkey(dic, value):
	for (key,values) in dic.items():
		if value in values:
			return key
	return False

#getting phoneme classes
def capture_phonemes(filename):
	phoneme_dict={}
	fi=codecs.open(filename, 'r', encoding='utf-8')
	f=fi.read()
	fi.close()
	lines=f.split('\n')
	count=1
	for line in lines[:-2]:
		x=line.split(' ')
		key0=getkey(phoneme_dict,x[0])
		key1=getkey(phoneme_dict,x[1])		
		if not key0 and not key1:
			phoneme_dict[count]=[x[0], x[1]]
			count+=1
		else:
			if not key0:
				phoneme_dict[key1].append(x[0])
			if not key1:
				phoneme_dict[key0].append(x[1])
	return phoneme_dict
	
ph_dict=capture_phonemes('hindi_phoneme.dat')

def makedic(filename):
	fi=codecs.open(filename, 'r', encoding='utf-8')
	f=fi.read()
	fi.close()
	lines=f.split('\n')
	worddict={}
	for line in lines[:-2]:
		x=line.split('\t')
		key=x[-1]
		#print(key)
		value=int(x[0])
		#print(key)
		worddict[key]=value
	#print(worddict['को'])
	return worddict
	
word_dict=makedic('w1g.txt')


def edits1(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   = []
	for a, b in splits:
		if not b=="":
			phoneme_key=getkey(ph_dict,b[0])
			#print(phoneme_key)
			if phoneme_key:
				for c in ph_dict[phoneme_key]:	
					replaces.append(a + c + b[1:])
					#print(replaces)
	inserts    = [a + c + b     for a, b in splits for c in all_alphabet]
	return set(deletes + transposes + replaces + inserts)
	
def find_candidates(word):
	#print(word)
	dict={}
	candidates=edits1(word)
	for candidate in candidates:
		if candidate in word_dict:
			dict[candidate]=word_dict[candidate]+1
	if word not in dict:
		dict[word]=1
	return dict

