├── arutils ├── __init__.py └── arabic_utils.py ├── test.py ├── nawar_bw_plain.phone ├── nawar_bw_tashkeel.phone ├── sortandfilter.py ├── README.md ├── .gitignore ├── dict2cmudict.py ├── corpus2cmudict.py ├── findstress.py ├── diphones.py ├── phonetise.py ├── LICENSE ├── phonetise_Buckwalter.py └── phonetise_Arabic.py /arutils/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /test.py: -------------------------------------------------------------------------------- 1 | import phonetise_Arabic 2 | 3 | # print(phonetise_Arabic.phonetise_word("الصِّينِيَّةِ")) 4 | #print(phonetise_Arabic.phonetise_word("أوضاعها")) 5 | #print(phonetise_Arabic.phonetise_word("أستراليا")) 6 | print(phonetise_Arabic.phonetise_word("أرزو")) 7 | -------------------------------------------------------------------------------- /nawar_bw_plain.phone: -------------------------------------------------------------------------------- 1 | $ 2 | * 3 | < 4 | A 5 | AA 6 | D 7 | E 8 | H 9 | I0 10 | II0 11 | S 12 | SIL 13 | T 14 | UU0 15 | Z 16 | ^ 17 | a 18 | aa 19 | b 20 | d 21 | f 22 | g 23 | h 24 | i0 25 | i1 26 | ii0 27 | j 28 | k 29 | l 30 | m 31 | n 32 | nn 33 | q 34 | r 35 | s 36 | t 37 | u0 38 | u1 39 | uu0 40 | uu1 41 | v 42 | w 43 | x 44 | y 45 | z 46 | -------------------------------------------------------------------------------- /nawar_bw_tashkeel.phone: -------------------------------------------------------------------------------- 1 | $ 2 | $$ 3 | * 4 | ** 5 | < 6 | << 7 | A 8 | AA 9 | D 10 | DD 11 | E 12 | EE 13 | H 14 | HH 15 | I0 16 | I1 17 | II0 18 | S 19 | SIL 20 | SS 21 | T 22 | TT 23 | U0 24 | U1 25 | UU0 26 | Z 27 | ZZ 28 | ^ 29 | ^^ 30 | a 31 | aa 32 | b 33 | bb 34 | d 35 | dd 36 | f 37 | ff 38 | g 39 | gg 40 | h 41 | hh 42 | i0 43 | i1 44 | ii0 45 | j 46 | jj 47 | k 48 | kk 49 | l 50 | ll 51 | m 52 | mm 53 | n 54 | nn 55 | q 56 | qq 57 | r 58 | rr 59 | s 60 | ss 61 | t 62 | tt 63 | u0 64 | u1 65 | uu0 66 | uu1 67 | v 68 | w 69 | ww 70 | x 71 | xx 72 | y 73 | yy 74 | z 75 | zz 76 | -------------------------------------------------------------------------------- /sortandfilter.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- coding: UTF8 -*- 3 | 4 | import sys 5 | 6 | 7 | def distinct(seq): 8 | seen = set() 9 | seen_add = seen.add 10 | return [ x for x in seq if not (x in seen or seen_add(x))] 11 | 12 | inputFileName = sys.argv[1] 13 | inputFile = open(inputFileName, mode='r', encoding='utf-8') 14 | utterances = inputFile.read().splitlines() 15 | inputFile.close() 16 | 17 | utterances = sorted(distinct(utterances)) 18 | 19 | inputFile = open(inputFileName, mode='w', encoding='utf-8') 20 | inputFile.write("\n".join(utterances) + '\r\n') 21 | inputFile.close() 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # ara-pronunciation-tool 2 | 3 | A python tool that converts Arabic diacritised text to a sequence of phonemes and create a pronunciation dictionary. 4 | 5 | This code is based on https://github.com/nawarhalabi/Arabic-Phonetiser 6 | 7 | Modifications mainly make the code in https://github.com/nawarhalabi/Arabic-Phonetiser compatible with python 3, and provide easy to use cmd tool to build the pronunciation dictionary. 8 | 9 | The pronunciation is generated based on Buckwalter transliteration 10 | see https://en.wikipedia.org/wiki/Buckwalter_transliteration and http://www.qamus.org/transliteration.htm for more information 11 | 12 | 13 | 14 | ## test with corpus2cmudict.py on text with diacritics 15 | ``` 16 | python corpus2cmudict.py -i nawar_corpus_tashkeel.txt -p nawar_bw_tashkeel 17 | ``` 18 | 19 | ## test with corpus2cmudict.py on text without diacritics 20 | ``` 21 | python corpus2cmudict.py -i nawar_corpus_plain.txt -p nawar_bw_plain 22 | ``` 23 | 24 | 25 | 26 | ## test on text with diacritics 27 | ``` 28 | python phonetise_Arabic.py -i nawar_corpus_tashkeel.txt 29 | 30 | python dict2cmudict.py -i nawar_corpus_tashkeel.txt.dict -p nawar_bw_tashkeel 31 | 32 | ``` 33 | 34 | ## test on text without diacritics 35 | ``` 36 | python phonetise_Arabic.py nawar_corpus.txt 37 | 38 | python dict2cmudict.py -i dict -p nawar_bw_plain 39 | 40 | ``` 41 | 42 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | env/ 12 | build/ 13 | develop-eggs/ 14 | dist/ 15 | downloads/ 16 | eggs/ 17 | .eggs/ 18 | lib/ 19 | lib64/ 20 | parts/ 21 | sdist/ 22 | var/ 23 | wheels/ 24 | *.egg-info/ 25 | .installed.cfg 26 | *.egg 27 | 28 | # PyInstaller 29 | # Usually these files are written by a python script from a template 30 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 31 | *.manifest 32 | *.spec 33 | 34 | # Installer logs 35 | pip-log.txt 36 | pip-delete-this-directory.txt 37 | 38 | # Unit test / coverage reports 39 | htmlcov/ 40 | .tox/ 41 | .coverage 42 | .coverage.* 43 | .cache 44 | nosetests.xml 45 | coverage.xml 46 | *.cover 47 | .hypothesis/ 48 | 49 | # Translations 50 | *.mo 51 | *.pot 52 | 53 | # Django stuff: 54 | *.log 55 | local_settings.py 56 | 57 | # Flask stuff: 58 | instance/ 59 | .webassets-cache 60 | 61 | # Scrapy stuff: 62 | .scrapy 63 | 64 | # Sphinx documentation 65 | docs/_build/ 66 | 67 | # PyBuilder 68 | target/ 69 | 70 | # Jupyter Notebook 71 | .ipynb_checkpoints 72 | 73 | # pyenv 74 | .python-version 75 | 76 | # celery beat schedule file 77 | celerybeat-schedule 78 | 79 | # SageMath parsed files 80 | *.sage.py 81 | 82 | # dotenv 83 | .env 84 | 85 | # virtualenv 86 | .venv 87 | venv/ 88 | ENV/ 89 | 90 | # Spyder project settings 91 | .spyderproject 92 | .spyproject 93 | 94 | # Rope project settings 95 | .ropeproject 96 | 97 | # mkdocs documentation 98 | /site 99 | 100 | # mypy 101 | .mypy_cache/ 102 | -------------------------------------------------------------------------------- /dict2cmudict.py: -------------------------------------------------------------------------------- 1 | import argparse 2 | 3 | from alphabet_detector import AlphabetDetector 4 | 5 | import phonetise_Arabic 6 | from arutils import arabic_utils 7 | 8 | parser = argparse.ArgumentParser(description='convert dict to cmu dict format') 9 | parser.add_argument('-i', '--input', type=argparse.FileType(mode='r', encoding='utf-8'), 10 | help='input file', required=True) 11 | parser.add_argument('-p', '--project-name', type=str, 12 | help='project name', required=True) 13 | 14 | if __name__ == '__main__': 15 | args = parser.parse_args() 16 | lines = args.input.readlines() 17 | proj_name = args.project_name 18 | cmu_dict = {} 19 | phones_set = set() 20 | ad = AlphabetDetector() 21 | for line in lines: 22 | if not line.strip(): 23 | continue 24 | word = line.split()[0] 25 | phones = ' '.join(line.split()[1:]) 26 | arabic_word = arabic_utils.remove_diacritics(phonetise_Arabic.buckwalterToArabic(word)) 27 | print(word, arabic_word) 28 | if arabic_word in cmu_dict: 29 | cmu_dict[arabic_word].add(phones) 30 | else: 31 | cmu_dict[arabic_word] = {phones} 32 | for ph in phones.split(): 33 | phones_set.add(ph) 34 | 35 | print('writing dic file') 36 | with open(proj_name + '.dic', mode='w', encoding='utf-8') as dict_writer: 37 | for w, ph in sorted(cmu_dict.items()): 38 | if len(ph) == 1: 39 | dict_writer.write('{}\t\t{}\n'.format(w, ph.pop())) 40 | else: 41 | dict_writer.write('{}\t\t{}\n'.format(w, ph.pop())) 42 | for i, p in enumerate(ph): 43 | dict_writer.write('{}({})\t\t{}\n'.format(w, (i + 1), p)) 44 | print('writing phone file') 45 | with open(proj_name + '.phone', mode='w', encoding='utf-8') as phone_writer: 46 | for ph in phones_set: 47 | phone_writer.write(ph) 48 | phone_writer.write('\n') 49 | 50 | print('done!') 51 | 52 | 53 | 54 | 55 | 56 | -------------------------------------------------------------------------------- /corpus2cmudict.py: -------------------------------------------------------------------------------- 1 | import argparse 2 | import operator 3 | import re 4 | 5 | import phonetise_Arabic 6 | from arutils import arabic_utils 7 | 8 | parser = argparse.ArgumentParser(description='extracts dictionary and phones from a corpus') 9 | parser.add_argument('-i', '--input', type=argparse.FileType(mode='r', encoding='utf-8'), 10 | help='input file', required=True) 11 | parser.add_argument('-p', '--project-name', type=str, 12 | help='project name', required=True) 13 | parser.add_argument('-s', '--s-tag', action='store_true', 14 | help='the sentences include tag') 15 | 16 | 17 | def corpus2dictionary(corpus, project_name): 18 | pronunciation_dict = {} 19 | phones_list = set() 20 | phones_list.add('SIL') 21 | for line in corpus: 22 | if args.s_tag: 23 | sentence = re.search('(.*)', line).group(1) 24 | else: 25 | sentence = line 26 | words = sentence.split() 27 | for word in words: 28 | pronunciations = phonetise_Arabic.phonetise_word(word) 29 | for pronunciation in pronunciations: 30 | for phone in pronunciation.split(): 31 | phones_list.add(phone) 32 | clean_word = arabic_utils.remove_diacritics(word) 33 | if clean_word in pronunciation_dict: 34 | for pronunciation in pronunciations: 35 | pronunciation_dict[clean_word].add(pronunciation) 36 | else: 37 | pronunciation_dict[clean_word] = set() 38 | for pronunciation in pronunciations: 39 | pronunciation_dict[clean_word].add(pronunciation) 40 | 41 | print('writing dic file') 42 | with open(proj_name + '.dic', mode='w', encoding='utf-8') as dict_writer: 43 | for w, phones in sorted(pronunciation_dict.items()): 44 | for i, phone in enumerate(phones): 45 | if i == 0: 46 | dict_writer.write('{}\t\t{}\n'.format(w, phone)) 47 | else: 48 | dict_writer.write('{}({})\t\t{}\n'.format(w, (i + 1), phone)) 49 | 50 | print('writing phone file') 51 | with open(proj_name + '.phone', mode='w', encoding='utf-8') as phone_writer: 52 | for ph in sorted(phones_list): 53 | phone_writer.write(ph) 54 | phone_writer.write('\n') 55 | 56 | 57 | if __name__ == '__main__': 58 | args = parser.parse_args() 59 | corpus = args.input.readlines() 60 | proj_name = args.project_name 61 | corpus2dictionary(corpus, project_name=proj_name) 62 | -------------------------------------------------------------------------------- /arutils/arabic_utils.py: -------------------------------------------------------------------------------- 1 | import operator 2 | import re 3 | import string 4 | 5 | from alphabet_detector import AlphabetDetector 6 | 7 | arabic_diacritics = re.compile(""" 8 | ّ | # Tashdid 9 | َ | # Fatha 10 | ً | # Tanwin Fath 11 | ُ | # Damma 12 | ٌ | # Tanwin Damm 13 | ِ | # Kasra 14 | ٍ | # Tanwin Kasr 15 | ْ | # Sukun 16 | ـ # Tatwil/Kashida 17 | """, re.VERBOSE) 18 | 19 | 20 | def remove_diacritics(text): 21 | text = re.sub(arabic_diacritics, '', text) 22 | return text 23 | 24 | 25 | def remove_punctuation(s): 26 | translator = str.maketrans('', '', string.punctuation + "،" + "؛" + "؟" + "«" + "»" + '–') 27 | return s.translate(translator) 28 | 29 | 30 | def get_none_arabic_words(text): 31 | none_arabic = list() 32 | ad = AlphabetDetector() 33 | for word in text.split(): 34 | if not ad.is_arabic(word): 35 | none_arabic.append(word) 36 | return none_arabic 37 | 38 | 39 | def keep_only_arabic(text): 40 | ad = AlphabetDetector() 41 | clean_lines = list() 42 | for line in text.splitlines(): 43 | clean_line = list() 44 | for word in line.split(): 45 | if ad.is_arabic(word): 46 | if word.isalpha(): 47 | clean_line.append(word) 48 | clean_lines.append(' '.join(clean_line)) 49 | return '\n'.join(clean_lines) 50 | 51 | 52 | def remove_links(text): 53 | # return re.sub(r'\s*(?:https?://)?www\.\S*\.[A-Za-z]{2,5}\s*', ' ', text, flags=re.MULTILINE).strip() 54 | # return re.sub(r'^https?:\/\/.*[\r\n]*', '', clean_text, flags=re.MULTILINE) 55 | return re.sub(r'(https|http)?:\/\/(\w|\.|\/|\?|\=|\&|\%)*\b', '', text, flags=re.MULTILINE) 56 | 57 | 58 | def remove_empty_lines(text): 59 | lines = [s.rstrip() for s in text.split("\n") if s.rstrip()] 60 | return '\n'.join(lines) 61 | 62 | 63 | def find_most_freq(words, topn): 64 | word_freq = {} 65 | for word in words: 66 | if word in word_freq: 67 | word_freq[word] += 1 68 | else: 69 | word_freq[word] = 1 70 | 71 | sorted_freq = sorted(word_freq.items(), key=operator.itemgetter(1), reverse=True) 72 | 73 | top = [list(i) for i in sorted_freq[:topn]] # list of lists 74 | return sorted_freq[:topn] 75 | 76 | 77 | def add_s_tag(input_corpus, corpus_outfile): 78 | corpus_writer = open(corpus_outfile, mode='w') 79 | for line in input_corpus: 80 | corpus_writer.write(" " + line + " \n") 81 | 82 | 83 | def remove_repeating_char(text): 84 | # return re.sub(r'(.)\1+', r'\1', text) # keep only 1 repeat 85 | return re.sub(r'(.)\1+', r'\1\1', text) # keep 2 repeat 86 | -------------------------------------------------------------------------------- /findstress.py: -------------------------------------------------------------------------------- 1 | def find_stress_index(sequence): # Find stress syllable in word starting from "start" 2 | if sequence == u'' or len(sequence) == 0: 3 | return -1 4 | print(sequence) 5 | consonants = [ 6 | "r", "g", "y", "G", 7 | "b", "z", "f", "v", 8 | "t", "s", "q", "p", 9 | "$", "k", "<", 10 | "j", "S", "l", 11 | "H", "D", "m", 12 | "x", "T", "n", 13 | "d", "Z", "h", 14 | "*", "E", "w", "^"] 15 | geminatedConsonants = [ 16 | "<<", "rr", "gg", "vv", 17 | "bb", "zz", "ff", "GG", 18 | "tt", "ss", "qq", "pp", 19 | "$$", "kk", "yy", 20 | "jj", "SS", "ll", 21 | "HH", "DD", "mm", 22 | "xx", "TT", "nn", 23 | "dd", "ZZ", "hh", 24 | "**", "EE", "ww", "^^"] 25 | longVowels = ["aa", "AA", 26 | "uu0", "uu1", 27 | "ii0", "ii1", 28 | "UU0", "UU1", 29 | "II0", "II1"] 30 | shortVowels = ["a", "A", 31 | "u0", "u1", 32 | "i0", "i1", 33 | "U0", "U1", 34 | "I0", "I1"] 35 | syllableString = "" 36 | i = 0 37 | while i < len(sequence): 38 | if (sequence[i] in geminatedConsonants): 39 | syllableString += "C" 40 | elif (sequence[i] in consonants): 41 | syllableString += "c" 42 | elif (sequence[i] in longVowels): 43 | syllableString += "V" 44 | elif (sequence[i] in shortVowels): 45 | syllableString += "v" 46 | else: 47 | print('Unacceptable char when finding stress syllable: ' + sequence[i] + ' ' + syllableString + '\n') 48 | file = open("errors", "a") 49 | file.write(sequence[i]) 50 | file.write("\n") 51 | file.close() 52 | return 0 53 | i += 1 54 | if syllableString[0] in ['v', 'V']: 55 | return -1 56 | # Stress falls on the last syllable if it is super heavy 57 | if syllableString.endswith("cVc") and syllableString.endswith("CVc"): 58 | return i - 2 # 3 59 | if (syllableString.endswith("cvvc") or syllableString.endswith("cvcc") or syllableString.endswith( 60 | "cVcc") or syllableString.endswith("Cvvc") or syllableString.endswith("Cvcc") or syllableString.endswith( 61 | "CVcc")): 62 | return i - 3 # 4 63 | if syllableString.endswith("cvvcc") and syllableString.endswith("Cvvcc"): 64 | return i - 4 # 5 65 | # Stress is at the beginning if it is a monosyllabic word 66 | if syllableString == "cvv" or syllableString == "cvc": 67 | return i - 2 # 3 68 | if syllableString == "cV": 69 | return i - 1 # 2 70 | # Remove last syllable if first two rules miss 71 | if syllableString.endswith("cvv") or syllableString.endswith("cvc"): 72 | syllableString = syllableString[0:-3] 73 | i = i - 3 74 | elif syllableString.endswith("Cvv") or syllableString.endswith("Cvc"): 75 | syllableString = syllableString[0:-3] 76 | syllableString += 'c' 77 | i = i - 2 78 | elif syllableString.endswith("cV") or syllableString.endswith("cv"): 79 | syllableString = syllableString[0:-2] 80 | i = i - 2 81 | elif syllableString.endswith("CV") or syllableString.endswith("Cv"): 82 | syllableString = syllableString[0:-2] 83 | syllableString += 'c' 84 | i = i - 1 85 | # Stress is at penultimate syllable if disyllabic word 86 | if syllableString == "cvv" or syllableString == "cvc": 87 | return i - 2 # 3 88 | if syllableString == "cV" or syllableString == "cv": 89 | return i - 1 # 2 90 | # Stress is at penultimate syllable if it is heavy 91 | if (syllableString.endswith("cvv") or syllableString.endswith("cvc") or syllableString.endswith( 92 | "Cvv") or syllableString.endswith("Cvc") or syllableString.endswith("cVc") or syllableString.endswith( 93 | "cVC") or syllableString.endswith("CVc")): 94 | return i - 2 # 3 95 | if syllableString.endswith("cV") or syllableString.endswith("CV"): 96 | return i - 1 # 2 97 | if syllableString.endswith("cv"): 98 | i = i - 2 99 | syllableString = syllableString[0:-2] 100 | elif syllableString.endswith("Cv"): 101 | i = i - 1 102 | syllableString = syllableString[0:-2] 103 | syllableString += 'c' 104 | # Stress is at antepenultimate syllable otherwise 105 | if (syllableString.endswith("cvv") or syllableString.endswith("cvc") or syllableString.endswith( 106 | "Cvv") or syllableString.endswith("Cvc") or syllableString.endswith("cVc") or syllableString.endswith( 107 | "cVC") or syllableString.endswith("CVc")): 108 | return i - 2 # 3 109 | if (syllableString.endswith("cV") or syllableString.endswith("cv") or syllableString.endswith( 110 | "CV") or syllableString.endswith("Cv")): 111 | return i - 1 # 2 112 | return i + 1 -------------------------------------------------------------------------------- /diphones.py: -------------------------------------------------------------------------------- 1 | import sys 2 | import re 3 | 4 | phones = ["<", "b", "t", "^", "j", "H", "x", "d", "*", "r", "z", "s", "$", "S", "D", "T", "Z", "E", "g", "f", "q", "k", 5 | "l", "m", "n", "h", "w", "y", "aa", "uu0", "ii0", "a", "u0", "i0", "AA", "A", "u1", "i1", "<<", "bb", "tt", 6 | "^^", "jj", "HH", "xx", "dd", "**", "rr", "zz", "ss", "$$", "SS", "DD", "TT", "ZZ", "EE", "gg", "ff", "qq", 7 | "kk", "ll", "mm", "nn", "hh", "ww", "yy", "sil"] 8 | 9 | consonants = [ 10 | "r", "g", "y", 11 | "b", "z", "f", 12 | "t", "s", "q", 13 | "$", "k", "<", 14 | "j", "S", "l", 15 | "H", "D", "m", 16 | "x", "T", "n", 17 | "d", "Z", "h", 18 | "*", "E", "w", "^", 19 | "<<", "rr", "gg", 20 | "bb", "zz", "ff", 21 | "tt", "ss", "qq", 22 | "$$", "kk", "yy", 23 | "jj", "SS", "ll", 24 | "HH", "DD", "mm", 25 | "xx", "TT", "nn", 26 | "dd", "ZZ", "hh", 27 | "**", "EE", "ww", "^^" 28 | ] 29 | 30 | emphaticConsonants = ["q", "qq", "x", "xx", "T", "TT", "D", "DD", "S", "SS", "Z", "ZZ", "g", "gg" 31 | ] 32 | nonemphaticVowels = ["aa", "a" 33 | ] 34 | backEmphaticConsonants = ["q", "qq", "T", "TT", "D", "DD", "S", "SS", "Z", "ZZ" 35 | ] 36 | 37 | vowels = ["aa", "A", 38 | "uu0", 39 | "ii0", 40 | "a", "u1", "AA", 41 | "i0", "u0", "i1" 42 | ] 43 | pause = ["sil", "sp" 44 | ] 45 | phones = consonants + vowels # + ["", "-", "DIST", "Dist", "dist"] 46 | allSymbols = phones + pause 47 | stopsVoiced = ["b", "d", "D", "G", "J", 48 | "bb", "dd", "DD", "GG", "JJ" 49 | ] 50 | stopsVoiceless = ["p", "t", "T", "<", "k", "q", "<", 51 | "pp", "tt", "TT", "<<", "kk", "qq", "<<" 52 | ] 53 | stops = stopsVoiced + stopsVoiceless 54 | fricVoiced = ["v", "*", "z", "Z", "j", "g", "E", 55 | "vv", "**", "zz", "ZZ", "jj", "gg", "EE" 56 | ] 57 | fricVoiceless = ["f", "S", "s", "^", "$", "x", "H", "h", 58 | "ff", "SS", "ss", "^^", "$$", "xx", "HH", "hh" 59 | ] 60 | fric = fricVoiced + fricVoiceless 61 | nasals = ["m", "n", 62 | "mm", "nn" 63 | ] 64 | trill = ["r", 65 | "rr" 66 | ] 67 | approx = ["w", "y", "l", 68 | "ww", "yy", "ll" 69 | ] 70 | 71 | types = {"phones": phones, "consonants": consonants, "vowels": vowels, "stops": stops, "stopsVoiced": stopsVoiced, 72 | "stopsVoiceless": stopsVoiceless, "fric": fric, "fricVoiced": fricVoiced, "fricVoiceless": fricVoiceless, 73 | "nasals": nasals, "trill": trill, "approx": approx, "pause": pause} 74 | 75 | 76 | def diphones(target): # Directory of the phonetised transcript 77 | lines = [] 78 | diphoneResults = {} 79 | diphoneTypeResults = {} 80 | 81 | for con in consonants: 82 | for vow in vowels: 83 | vow = re.sub("U", "u", vow) 84 | vow = re.sub("I", "i", vow) 85 | if not (con in emphaticConsonants and vow in nonemphaticVowels): 86 | diphoneResults[con + '-' + vow] = 0 87 | 88 | for con in consonants: 89 | diphoneResults[con + '-sil'] = 0 90 | 91 | for vow in vowels: 92 | for con in consonants: 93 | if len(vow) > 1 and vow[1:] in vowels: 94 | vow = vow[1:] 95 | vow = re.sub("U", "u", vow) 96 | vow = re.sub("I", "i", vow) 97 | if not (con in backEmphaticConsonants and vow in nonemphaticVowels) and not (len(con) > 1): 98 | diphoneResults[vow + '-' + con] = 0 99 | 100 | with open(target, 'r') as file: 101 | lines = file.readlines() 102 | 103 | for line in lines: 104 | line = line.rstrip() 105 | line = line.split(' ') 106 | 107 | if len(line) > 1: 108 | for i in range(1, len(line)): 109 | next_char = 'e' 110 | if i < len(line) - 1: 111 | next_char = line[i + 1].rstrip() 112 | cur = line[i].rstrip() 113 | prev = line[i - 1].rstrip() 114 | 115 | prev = re.sub("U", "u", prev) 116 | prev = re.sub("I", "i", prev) 117 | cur = re.sub("U", "u", cur) 118 | cur = re.sub("I", "i", cur) 119 | next_char = re.sub("U", "u", next_char) 120 | next_char = re.sub("I", "i", next_char) 121 | if len(prev) > 1 and prev[1:] in vowels: 122 | prev = prev[1:] 123 | 124 | if prev + '-' + cur in diphoneResults and not ( 125 | prev in vowels and cur in consonants and next_char in vowels): 126 | diphoneResults[prev + '-' + cur] += 1 127 | 128 | for type1 in types: # For all boundary types, add the delta to the statistics 129 | for type2 in types: 130 | if prev in types[type1] and cur in types[type2]: 131 | if type1 + '-' + type2 in diphoneTypeResults: 132 | diphoneTypeResults[type1 + "-" + type2] += 1 133 | else: 134 | diphoneTypeResults[type1 + "-" + type2] = 1 135 | 136 | return diphoneResults, diphoneTypeResults 137 | 138 | 139 | if __name__ == '__main__': 140 | diphoneResults, diphoneTypeResults = diphones(sys.argv[1]) 141 | res = '' 142 | for key in diphoneResults: 143 | res += key + ', ' + str(diphoneResults[key]) + '\n' 144 | 145 | with open("diphone-results.csv", "w") as file: 146 | file.write(res) 147 | 148 | res = '' 149 | for key in diphoneTypeResults: 150 | res += key + ', ' + str(diphoneTypeResults[key]) + '\n' 151 | 152 | with open("diphone-types-results.csv", "w") as file: 153 | file.write(res) 154 | -------------------------------------------------------------------------------- /phonetise.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- coding: UTF8 -*- 3 | 4 | import sys 5 | import re 6 | 7 | unambiguousConsonantMap = { 8 | u'\u0628': u'b', u'\u0630': u'*', u'\u0637': u'T', u'\u0645': u'm', 9 | u'\u062a': u't', u'\u0631': u'r', u'\u0638': u'Z', u'\u0646': u'n', 10 | u'\u062b': u'^', u'\u0632': u'z', u'\u0639': u'E', u'\u0647': u'h', 11 | u'\u062c': u'j', u'\u0633': u's', u'\u063a': u'g', u'\u062d': u'H', 12 | u'\u0642': u'q', u'\u0641': u'f', u'\u062e': u'x', u'\u0635': u'S', 13 | u'\u0634': u'$', u'\u062f': u'd', u'\u0636': u'D', u'\u0643': u'k', 14 | u'\u0623': u'<', u'\u0621': u'<', u'\u0626': u'<', u'\u0624': u'<', 15 | u'\u0625': u'<' 16 | } 17 | 18 | buckwalter = { 19 | u'\u0628': u'b', u'\u0630': u'*', u'\u0637': u'T', u'\u0645': u'm', 20 | u'\u062a': u't', u'\u0631': u'r', u'\u0638': u'Z', u'\u0646': u'n', 21 | u'\u062b': u'^', u'\u0632': u'z', u'\u0639': u'E', u'\u0647': u'h', 22 | u'\u062c': u'j', u'\u0633': u's', u'\u063a': u'g', u'\u062d': u'H', 23 | u'\u0642': u'q', u'\u0641': u'f', u'\u062e': u'x', u'\u0635': u'S', 24 | u'\u0634': u'$', u'\u062f': u'd', u'\u0636': u'D', u'\u0643': u'k', 25 | u'\u0623': u'>', u'\u0621': u'\'', u'\u0626': u'}', u'\u0624': u'&', 26 | u'\u0625': u'<', u'\u0622': u'|', u'\u0627': u'A', u'\u0649': u'Y', 27 | u'\u0629': u'p', u'\u064a': u'y', u'\u0644': u'l', u'\u0648': u'w', 28 | u'\u064b': u'F', u'\u064c': u'N', u'\u064d': u'K', u'\u064e': u'a', 29 | u'\u064f': u'u', u'\u0650': u'i', u'\u0651': u'~', u'\u0652': u'o' 30 | } 31 | 32 | 33 | def arabicToBuckwalter(word): 34 | res = '' 35 | for letter in word: 36 | if (letter in buckwalter): 37 | res += buckwalter[letter] 38 | else: 39 | res += letter 40 | return res 41 | 42 | 43 | ambiguousConsonantMap = { 44 | u'\u0644': [u'l', u''], u'\u0648': u'w', u'\u064a': u'y', u'\u0629': [u't', u''] 45 | # These consonants are only unambiguous in certain contexts 46 | } 47 | 48 | maddaMap = { 49 | u'\u0622': [[u'<', u'aa'], [u'<', u'AA']] 50 | } 51 | 52 | vowelMap = { 53 | u'\u0627': [[u'aa', u''], [u'AA', u'']], u'\u0649': [[u'aa', u''], [u'AA', u'']], 54 | u'\u0648': [[u'uu0', u'uu1'], [u'UU0', u'UU1']], 55 | u'\u064a': [[u'ii0', u'ii1'], [u'II0', u'II1']], 56 | u'\u064e': [u'a', u'A'], 57 | u'\u064f': [[u'u0', u'u1'], [u'U0', u'U1']], 58 | u'\u0650': [[u'i0', u'i1'], [u'I0', u'I1']], 59 | } 60 | 61 | nunationMap = { 62 | u'\u064b': [[u'a', u'n'], [u'A', u'n']], u'\u064c': [[u'u1', u'n'], [u'U1', u'n']], 63 | u'\u064d': [[u'i1', u'n'], [u'I1', u'n']] 64 | } 65 | 66 | diacritics = [u'\u0652', u'\u064e', u'\u064f', u'\u0650', u'\u064b', u'\u064c', u'\u064d', u'\u0651'] 67 | diacriticsWithoutShadda = [u'\u0652', u'\u064e', u'\u064f', u'\u0650', u'\u064b', u'\u064c', u'\u064d'] 68 | emphatics = [u'\u0636', u'\u0635', u'\u0637', u'\u0638', u'\u063a', u'\u062e', u'\u0642'] 69 | forwardEmphatics = [u'\u063a', u'\u062e'] 70 | consonants = [u'\u0623', u'\u0625', u'\u0626', u'\u0624', u'\u0621', u'\u0628', u'\u062a', u'\u062b', u'\u062c', 71 | u'\u062d', u'\u062e', u'\u062f', u'\u0630', u'\u0631', u'\u0632', u'\u0633', u'\u0634', u'\u0635', 72 | u'\u0636', u'\u0637', u'\u0638', u'\u0639', u'\u063a', u'\u0641', u'\u0642', u'\u0643', u'\u0644', 73 | u'\u0645', u'\u0646', u'\u0647', u'\u0622'] 74 | 75 | fixedWords = { 76 | u'\u0647\u0630\u0627': [u'h aa * aa', u'h aa * a', ], 77 | u'\u0647\u0630\u0647': [u'h aa * i0 h i0', u'h aa * i1 h'], 78 | u'\u0647\u0630\u0627\u0646': [u'h aa * aa n i0', u'h aa * aa n'], 79 | u'\u0647\u0624\u0644\u0627\u0621': [u'h aa < u0 l aa < i0', u'h aa < u0 l aa <'], 80 | u'\u0630\u0644\u0643': [u'* aa l i0 k a', u'* aa l i0 k'], 81 | u'\u0643\u0630\u0644\u0643': [u'k a * aa l i0 k a', u'k a * aa l i1 k'], 82 | u'\u0630\u0644\u0643\u0645': u'* aa l i0 k u1 m', 83 | u'\u0623\u0648\u0644\u0626\u0643': [u'< u0 l aa < i0 k a', u'< u0 l aa < i1 k'], 84 | u'\u0637\u0647': u'T aa h a', 85 | u'\u0644\u0643\u0646': [u'l aa k i0 nn a', u'l aa k i1 n'], 86 | u'\u0644\u0643\u0646\u0647': u'l aa k i0 nn a h u0', 87 | u'\u0644\u0643\u0646\u0647\u0645': u'l aa k i0 nn a h u1 m', 88 | u'\u0644\u0643\u0646\u0643': [u'l aa k i0 nn a k a', u'l aa k i0 nn a k i0'], 89 | u'\u0644\u0643\u0646\u0643\u0645': u'l aa k i0 nn a k u1 m', 90 | u'\u0644\u0643\u0646\u0643\u0645\u0627': u'l aa k i0 nn a k u0 m aa', 91 | u'\u0644\u0643\u0646\u0646\u0627': u'l aa k i0 nn a n aa', 92 | u'\u0627\u0644\u0631\u062D\u0645\u0646': [u'rr a H m aa n i0', u'rr a H m aa n'], 93 | u'\u0627\u0644\u0644\u0647': [u'll aa h i0', u'll aa h', u'll AA h u0', u'll AA h a', u'll AA h', u'll A'], 94 | u'\u0647\u0630\u064a\u0646': [u'h aa * a y n i0', u'h aa * a y n'], 95 | 96 | u'\u0646\u062a': u'n i1 t', 97 | u'\u0641\u064a\u062F\u064a\u0648': u'v i0 d y uu1', 98 | u'\u0644\u0646\u062F\u0646': u'l A n d u1 n' 99 | } 100 | 101 | 102 | def isFixedWord(word, results, orthography): 103 | lastLetter = word[-1] 104 | if (lastLetter == u'\u064e'): 105 | lastLetter = [u'a', u'A'] 106 | elif (lastLetter == u'\u0627'): 107 | lastLetter = [u'aa'] 108 | elif (lastLetter == u'\u064f'): 109 | lastLetter = [u'u0'] 110 | elif (lastLetter == u'\u0650'): 111 | lastLetter = [u'i0'] 112 | elif (lastLetter in unambiguousConsonantMap): 113 | lastLetter = [unambiguousConsonantMap[lastLetter]] 114 | wordConsonants = re.sub( 115 | u'[^\u0647\u0630\u0627\u0647\u0646\u0621\u0623\u0648\u0644\u0626\u0643\u0645\u064A\u0637\u062a\u0641\u062F]', 116 | '', word) # Remove all dacritics from word 117 | if (wordConsonants in fixedWords): # check if word is in the fixed word lookup table 118 | if (isinstance(fixedWords[wordConsonants], list)): 119 | for pronunciation in fixedWords[wordConsonants]: 120 | if (pronunciation.split(' ')[-1] in lastLetter): 121 | results += orthography + ' ' + pronunciation + '\n' # add each pronunciation to the pronunciation dictionary 122 | else: 123 | results += orthography + ' ' + fixedWords[ 124 | wordConsonants] + '\n' # add pronunciation to the pronunciation dictionary 125 | return results 126 | 127 | 128 | inputFileName = sys.argv[1] 129 | inputFile = open(inputFileName, mode='r', encoding='utf-8') 130 | utterances = inputFile.read().splitlines() 131 | inputFile.close() 132 | 133 | result = '' 134 | 135 | for utterance in utterances: 136 | number = utterance.split(',')[0].strip() 137 | utterance = utterance.split(',')[1].strip() 138 | 139 | utteranceText = arabicToBuckwalter(utterance) 140 | 141 | zeros = "" + "0" * (4 - len(number)) 142 | utteranceLabelFile = open("labels/ARA NORM " + zeros + number + ".lab", mode="w", encoding="utf-8") 143 | 144 | utteranceLabelFile.write(utteranceText.replace(' - ', ' sil ')) 145 | utteranceLabelFile.close() 146 | 147 | utteranceText = utteranceText.split(' ') 148 | 149 | utterance = utterance.replace(u'\u0627\u064b', u'\u064b') 150 | utterance = utterance.replace(u'\u0640', u'') 151 | utterance = utterance.replace(u'\u0652', u'') 152 | utterance = utterance.replace(u'\u064e\u0627', u'\u0627') 153 | utterance = utterance.replace(u'\u064e\u0649', u'\u0649') 154 | utterance = utterance.replace(u' \u0627', u' ') 155 | utterance = utterance.replace(u'\u064b', u'\u064e\u0646') 156 | utterance = utterance.replace(u'\u064c', u'\u064f\u0646') 157 | utterance = utterance.replace(u'\u064d', u'\u0650\u0646') 158 | utterance = utterance.replace(u'\u0622', u'\u0623\u0627') 159 | 160 | # Deal with Hamza types that when not followed by a short vowel letter, this short vowel is added automatically 161 | utterance = re.sub(u'\u0627\u0650', u'\u0625\u0650', utterance) 162 | utterance = re.sub(u'\u0627\u064e', u'\u0623\u064e', utterance) 163 | utterance = re.sub(u'\u0627\u064f', u'\u0623\u064f', utterance) 164 | utterance = re.sub(u'^\u0623([^\u064e\u064f\u0627\u0648])', u'\u0623\u064e\\1', utterance) 165 | utterance = re.sub(u' \u0623([^\u064e\u064f\u0627\u0648 ])', u' \u0623\u064e\\1', utterance) 166 | utterance = re.sub(u'\u0625([^\u0650])', u'\u0625\u0650\\1', utterance) 167 | if number < 3: 168 | print(utterance) 169 | 170 | utterance = utterance.split(u' ') 171 | 172 | wordIndex = -1 173 | for word in utterance: 174 | wordIndex += 1 175 | if word != '-': 176 | orthography = utteranceText[wordIndex] 177 | 178 | result = isFixedWord(word, result, orthography) 179 | 180 | emphaticContext = False 181 | word = u'bb' + word + u'ee' # This is the end/beginning of word symbol. just for convenience 182 | 183 | phones = [] 184 | for index in range(2, len(word) - 2): 185 | letter = word[index] 186 | letter1 = word[index + 1] 187 | letter2 = word[index + 2] 188 | letter_1 = word[index - 1] 189 | letter_2 = word[index - 2] 190 | # ---------------------------------------------------------------------------------------------------------------- 191 | if (letter in consonants + [u'\u0648', u'\u064a'] and not letter in emphatics + [ 192 | u'\u0631'""", u'\u0644'"""]): # non-emphatic consonants (except for Lam and Ra) change emphasis to 'no emphasis' 193 | emphaticContext = False 194 | if (letter in emphatics): 195 | emphaticContext = True 196 | if (letter1 in emphatics and not letter1 in forwardEmphatics): 197 | emphaticContext = True 198 | # ---------------------------------------------------------------------------------------------------------------- 199 | # ---------------------------------------------------------------------------------------------------------------- 200 | if (letter in unambiguousConsonantMap): # Unambiguous phones 201 | phones += [unambiguousConsonantMap[letter]] 202 | # ---------------------------------------------------------------------------------------------------------------- 203 | if (letter == u'\u0644'): 204 | if ((not letter1 in diacritics and not letter1 in vowelMap) and letter2 in [ 205 | u'\u0651']): # Lam could be omitted in definite article (sun letters) 206 | phones += [ambiguousConsonantMap[u'\u0644'][1]] 207 | else: 208 | phones += [ambiguousConsonantMap[u'\u0644'][0]] 209 | # ---------------------------------------------------------------------------------------------------------------- 210 | if (letter == u'\u0651' and not letter_1 in [u'\u0648', 211 | u'\u064a']): # shadda just doubles the letter before it 212 | phones[len(phones) - 1] += phones[len(phones) - 1] 213 | # ---------------------------------------------------------------------------------------------------------------- 214 | if (letter == u'\u0622'): # Madda only changes based in emphaticness 215 | if (emphaticContext): 216 | phones += [maddaMap[u'\u0622'][1]] 217 | else: 218 | phones += [maddaMap[u'\u0622'][0]] 219 | # ---------------------------------------------------------------------------------------------------------------- 220 | if (letter == u'\u0629'): # Ta' marboota is determined by the following if it is a diacritic or not 221 | if (letter1 in diacritics): 222 | phones += [ambiguousConsonantMap[u'\u0629'][0]] 223 | else: 224 | phones += [ambiguousConsonantMap[u'\u0629'][1]] 225 | # ---------------------------------------------------------------------------------------------------------------- 226 | if (letter in vowelMap): 227 | if (letter in [u'\u0648', 228 | u'\u064a']): # Waw and Ya are complex they could be consonants or vowels and their gemination is complex as it could be a combination of a vowel and consonants 229 | if (letter1 in diacriticsWithoutShadda + [u'\u0627', u'\u0649'] or ( 230 | letter1 in [u'\u0648', u'\u064a'] and not letter2 in diacritics + [u'\u0627', u'\u0648', 231 | u'\u064a']) or ( 232 | letter_1 in diacriticsWithoutShadda and letter1 in consonants + [u'e'])): 233 | if ((letter in [u'\u0648'] and letter_1 in [u'\u064f'] and not letter1 in [u'\u064e', 234 | u'\u0650', 235 | u'\u0627', 236 | u'\u0649']) or ( 237 | letter in [u'\u064a'] and letter_1 in [u'\u0650'] and not letter1 in [u'\u064e', 238 | u'\u064f', 239 | u'\u0627', 240 | u'\u0649'])): 241 | if (emphaticContext): 242 | phones += [vowelMap[letter][1][0]] 243 | else: 244 | phones += [vowelMap[letter][0][0]] 245 | else: 246 | if (letter1 in [u'\u0627'] and letter in [u'\u0648'] and letter2 in [u'e']): 247 | phones += [[ambiguousConsonantMap[letter], vowelMap[letter][0][0]]] 248 | else: 249 | phones += [ambiguousConsonantMap[letter]] 250 | elif (letter1 in [u'\u0651']): 251 | if (letter_1 in [u'\u064e'] or ( 252 | letter in [u'\u0648'] and letter_1 in [u'\u0650', u'\u064a']) or ( 253 | letter in [u'\u064a'] and letter_1 in [u'\u0648', u'\u064f'])): 254 | phones += [ambiguousConsonantMap[letter], ambiguousConsonantMap[letter]] 255 | else: 256 | phones += [vowelMap[letter][0][0], ambiguousConsonantMap[letter]] 257 | else: # Waws and Ya's at the end of the word could be shortened 258 | if (emphaticContext): 259 | if (letter_1 in consonants + [u'\u064f', u'\u0650'] and letter1 in [u'e']): 260 | phones += [[vowelMap[letter][1][0], vowelMap[letter][1][0][1:]]] 261 | else: 262 | phones += [vowelMap[letter][1][0]] 263 | else: 264 | if (letter_1 in consonants + [u'\u064f', u'\u0650'] and letter1 in [u'e']): 265 | phones += [[vowelMap[letter][0][0], vowelMap[letter][0][0][1:]]] 266 | else: 267 | phones += [vowelMap[letter][0][0]] 268 | if (letter in [u'\u064f', 269 | u'\u0650']): # Kasra and Damma could be mildened if before a final silent consonant 270 | if (emphaticContext): 271 | if (( 272 | letter1 in unambiguousConsonantMap or letter1 == u'\u0644') and letter2 == u'e' and len( 273 | word) > 7): 274 | phones += [vowelMap[letter][1][1]] 275 | else: 276 | phones += [vowelMap[letter][1][0]] 277 | else: 278 | if (( 279 | letter1 in unambiguousConsonantMap or letter1 == u'\u0644') and letter2 == u'e' and len( 280 | word) > 7): 281 | phones += [vowelMap[letter][0][1]] 282 | else: 283 | phones += [vowelMap[letter][0][0]] 284 | if (letter in [u'\u064e', u'\u0627', 285 | u'\u0649']): # Alif could be ommited in definite article and beginning of some words 286 | if (letter in [u'\u0627'] and letter_1 in [u'\u0648', u'\u0643'] and letter_2 == u'b'): 287 | phones += [[vowelMap[letter][0][0], u'a']] 288 | elif (letter in [u'\u0627'] and letter_1 in [u'\u064f', u'\u0650']): 289 | temp = True # do nothing 290 | elif (letter in [u'\u0627'] and letter_1 in [u'\u0648'] and letter1 in [ 291 | u'e']): # Waw al jama3a: The Alif after is optional 292 | phones += [[vowelMap[letter][0][0], vowelMap[letter][0][1]]] 293 | elif (letter in [u'\u0627', u'\u0649'] and letter1 in [u'e']): 294 | if (emphaticContext): 295 | phones += [[vowelMap[letter][1][0], vowelMap[u'\u064e'][1]]] 296 | else: 297 | phones += [[vowelMap[letter][0][0], vowelMap[u'\u064e'][0]]] 298 | else: 299 | if (emphaticContext): 300 | phones += [vowelMap[letter][1][0]] 301 | else: 302 | phones += [vowelMap[letter][0][0]] 303 | possibilities = 1 304 | pronunciations = [] 305 | for letter in phones: 306 | if (isinstance(letter, list)): 307 | possibilities = possibilities * len(letter) 308 | for i in range(0, possibilities): 309 | pronunciations.append([]) 310 | iterations = 1 311 | for index, letter in enumerate(phones): 312 | if (isinstance(letter, list)): 313 | curIndex = (i / iterations) % len(letter) 314 | if (letter[curIndex] != u''): 315 | pronunciations[i].append(letter[curIndex]) 316 | iterations = iterations * len(letter) 317 | else: 318 | if (letter != u''): 319 | pronunciations[i].append(letter) 320 | for pronunciation in pronunciations: 321 | prevLetter = '' 322 | toDelete = [] 323 | for i in range(0, len(pronunciation)): 324 | letter = pronunciation[i] 325 | if (letter in ['aa', 'uu0', 'ii0', 'AA', 'UU0', 'II0'] and prevLetter.lower() == letter[ 326 | 1:].lower()): 327 | toDelete.append(i - 1) 328 | pronunciation[i] = pronunciation[i - 1][0] + pronunciation[i - 1] 329 | if (letter in ['u0', 'i0'] and prevLetter.lower() == letter.lower()): 330 | toDelete.append(i - 1) 331 | pronunciation[i] = pronunciation[i - 1] 332 | if (letter in ['y', 'w'] and prevLetter == letter): 333 | pronunciation[i - 1] += pronunciation[i - 1] 334 | toDelete.append(i); 335 | 336 | prevLetter = letter 337 | for i in reversed(range(0, len(toDelete))): 338 | del (pronunciation[toDelete[i]]) 339 | result += orthography + ' ' + ' '.join(pronunciation) + '\n' 340 | 341 | outFile = open('dict', mode='w', encoding='utf-8') 342 | outFile.write(result.strip()) 343 | outFile.close() 344 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | {one line to give the program's name and a brief idea of what it does.} 635 | Copyright (C) {year} {name of author} 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | {project} Copyright (C) {year} {fullname} 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /phonetise_Buckwalter.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- coding: UTF8 -*- 3 | 4 | import sys 5 | import re 6 | import os 7 | 8 | buckwalter = { # mapping from Arabic script to Buckwalter 9 | u'\u0628': u'b', u'\u0630': u'*', u'\u0637': u'T', u'\u0645': u'm', 10 | u'\u062a': u't', u'\u0631': u'r', u'\u0638': u'Z', u'\u0646': u'n', 11 | u'\u062b': u'^', u'\u0632': u'z', u'\u0639': u'E', u'\u0647': u'h', 12 | u'\u062c': u'j', u'\u0633': u's', u'\u063a': u'g', u'\u062d': u'H', 13 | u'\u0642': u'q', u'\u0641': u'f', u'\u062e': u'x', u'\u0635': u'S', 14 | u'\u0634': u'$', u'\u062f': u'd', u'\u0636': u'D', u'\u0643': u'k', 15 | u'\u0623': u'>', u'\u0621': u'\'', u'\u0626': u'}', u'\u0624': u'&', 16 | u'\u0625': u'<', u'\u0622': u'|', u'\u0627': u'A', u'\u0649': u'Y', 17 | u'\u0629': u'p', u'\u064a': u'y', u'\u0644': u'l', u'\u0648': u'w', 18 | u'\u064b': u'F', u'\u064c': u'N', u'\u064d': u'K', u'\u064e': u'a', 19 | u'\u064f': u'u', u'\u0650': u'i', u'\u0651': u'~', u'\u0652': u'o' 20 | } 21 | 22 | ArabicScript = { # mapping from Buckwalter to Arabic script 23 | u'b': u'\u0628', u'*': u'\u0630', u'T': u'\u0637', u'm': u'\u0645', 24 | u't': u'\u062a', u'r': u'\u0631', u'Z': u'\u0638', u'n': u'\u0646', 25 | u'^': u'\u062b', u'z': u'\u0632', u'E': u'\u0639', u'h': u'\u0647', 26 | u'j': u'\u062c', u's': u'\u0633', u'g': u'\u063a', u'H': u'\u062d', 27 | u'q': u'\u0642', u'f': u'\u0641', u'x': u'\u062e', u'S': u'\u0635', 28 | u'$': u'\u0634', u'd': u'\u062f', u'D': u'\u0636', u'k': u'\u0643', 29 | u'>': u'\u0623', u'\'': u'\u0621', u'}': u'\u0626', u'&': u'\u0624', 30 | u'<': u'\u0625', u'|': u'\u0622', u'A': u'\u0627', u'Y': u'\u0649', 31 | u'p': u'\u0629', u'y': u'\u064a', u'l': u'\u0644', u'w': u'\u0648', 32 | u'F': u'\u064b', u'N': u'\u064c', u'K': u'\u064d', u'a': u'\u064e', 33 | u'u': u'\u064f', u'i': u'\u0650', u'~': u'\u0651', u'o': u'\u0652' 34 | } 35 | 36 | 37 | def arabicToBuckwalter(word): # Convert input string to Buckwalter 38 | res = '' 39 | for letter in word: 40 | if (letter in buckwalter): 41 | res += buckwalter[letter] 42 | else: 43 | res += letter 44 | return res 45 | 46 | 47 | def buckwalterToArabic(word): # Convert input string to Arabic 48 | res = '' 49 | for letter in word: 50 | if (letter in ArabicScript): 51 | res += ArabicScript[letter] 52 | else: 53 | res += letter 54 | return res 55 | 56 | 57 | # ---------------------------------------------------------------------------- 58 | # Grapheme to Phoneme mappings------------------------------------------------ 59 | # ---------------------------------------------------------------------------- 60 | unambiguousConsonantMap = { 61 | u'b': u'b', u'*': u'*', u'T': u'T', u'm': u'm', 62 | u't': u't', u'r': u'r', u'Z': u'Z', u'n': u'n', 63 | u'^': u'^', u'z': u'z', u'E': u'E', u'h': u'h', 64 | u'j': u'j', u's': u's', u'g': u'g', u'H': u'H', 65 | u'q': u'q', u'f': u'f', u'x': u'x', u'S': u'S', 66 | u'$': u'$', u'd': u'd', u'D': u'D', u'k': u'k', 67 | u'>': u'<', u'\'': u'<', u'}': u'<', u'&': u'<', 68 | u'<': u'<' 69 | } 70 | 71 | ambiguousConsonantMap = { 72 | u'l': [u'l', u''], u'w': u'w', u'y': u'y', u'p': [u't', u''] 73 | # These consonants are only unambiguous in certain contexts 74 | } 75 | 76 | maddaMap = { 77 | u'|': [[u'<', u'aa'], [u'<', u'AA']] 78 | } 79 | 80 | vowelMap = { 81 | u'A': [[u'aa', u''], [u'AA', u'']], u'Y': [[u'aa', u''], [u'AA', u'']], 82 | u'w': [[u'uu0', u'uu1'], [u'UU0', u'UU1']], 83 | u'y': [[u'ii0', u'ii1'], [u'II0', u'II1']], 84 | u'a': [u'a', u'A'], 85 | u'u': [[u'u0', u'u1'], [u'U0', u'U1']], 86 | u'i': [[u'i0', u'i1'], [u'I0', u'I1']], 87 | } 88 | 89 | nunationMap = { 90 | u'F': [[u'a', u'n'], [u'A', u'n']], u'N': [[u'u1', u'n'], [u'U1', u'n']], u'K': [[u'i1', u'n'], [u'I1', u'n']] 91 | } 92 | 93 | diacritics = [u'o', u'a', u'u', u'i', u'F', u'N', u'K', u'~'] 94 | diacriticsWithoutShadda = [u'o', u'a', u'u', u'i', u'F', u'N', u'K'] 95 | emphatics = [u'D', u'S', u'T', u'Z', u'g', u'x', u'q'] 96 | forwardEmphatics = [u'g', u'x'] 97 | consonants = [u'>', u'<', u'}', u'&', u'\'', u'b', u't', u'^', u'j', u'H', u'x', u'd', u'*', u'r', u'z', u's', u'$', 98 | u'S', u'D', u'T', u'Z', u'E', u'g', u'f', u'q', u'k', u'l', u'm', u'n', u'h', u'|'] 99 | 100 | # ------------------------------------------------------------------------------------ 101 | # Words with fixed irregular pronunciations------------------------------------------- 102 | # ------------------------------------------------------------------------------------ 103 | fixedWords = { 104 | u'h*A': [u'h aa * aa', u'h aa * a', ], 105 | u'h*h': [u'h aa * i0 h i0', u'h aa * i1 h'], 106 | u'h*An': [u'h aa * aa n i0', u'h aa * aa n'], 107 | u'h&lA\'': [u'h aa < u0 l aa < i0', u'h aa < u0 l aa <'], 108 | u'*lk': [u'* aa l i0 k a', u'* aa l i0 k'], 109 | u'k*lk': [u'k a * aa l i0 k a', u'k a * aa l i1 k'], 110 | u'*lkm': u'* aa l i0 k u1 m', 111 | u'>wl}k': [u'< u0 l aa < i0 k a', u'< u0 l aa < i1 k'], 112 | u'Th': u'T aa h a', 113 | u'lkn': [u'l aa k i0 nn a', u'l aa k i1 n'], 114 | u'lknh': u'l aa k i0 nn a h u0', 115 | u'lknhm': u'l aa k i0 nn a h u1 m', 116 | u'lknk': [u'l aa k i0 nn a k a', u'l aa k i0 nn a k i0'], 117 | u'lknkm': u'l aa k i0 nn a k u1 m', 118 | u'lknkmA': u'l aa k i0 nn a k u0 m aa', 119 | u'lknnA': u'l aa k i0 nn a n aa', 120 | u'AlrHmn': [u'rr a H m aa n i0', u'rr a H m aa n'], 121 | u'Allh': [u'll aa h i0', u'll aa h', u'll AA h u0', u'll AA h a', u'll AA h', u'll A'], 122 | u'h*yn': [u'h aa * a y n i0', u'h aa * a y n'], 123 | 124 | u'nt': u'n i1 t', 125 | u'fydyw': u'v i0 d y uu1', 126 | u'lndn': u'l A n d u1 n' 127 | } 128 | 129 | 130 | def isFixedWord(word, results, orthography, pronunciations): 131 | lastLetter = '' 132 | if len(word) > 0: 133 | lastLetter = word[-1] 134 | if lastLetter == u'a': 135 | lastLetter = [u'a', u'A'] 136 | elif lastLetter == u'A': 137 | lastLetter = [u'aa'] 138 | elif lastLetter == u'u': 139 | lastLetter = [u'u0'] 140 | elif lastLetter == u'i': 141 | lastLetter = [u'i0'] 142 | elif lastLetter in unambiguousConsonantMap: 143 | lastLetter = [unambiguousConsonantMap[lastLetter]] 144 | # Remove all dacritics from word 145 | wordConsonants = re.sub(u'[^h*Ahn\'>wl}kmyTtfd]', '', word) 146 | # check if word is in the fixed word lookup table 147 | if wordConsonants in fixedWords: 148 | if isinstance(fixedWords[wordConsonants], list): 149 | for pronunciation in fixedWords[wordConsonants]: 150 | if pronunciation.split(' ')[-1] in lastLetter: 151 | results += word + ' ' + pronunciation + '\n' # add each pronunciation to the pronunciation dictionary 152 | pronunciations.append(pronunciation.split(' ')) 153 | else: 154 | results += word + ' ' + fixedWords[ 155 | wordConsonants] + '\n' # add pronunciation to the pronunciation dictionary 156 | pronunciations.append(fixedWords[wordConsonants].split(' ')) 157 | return results 158 | 159 | 160 | def work(utterance): 161 | # Do some normalisation work and split utterance to words 162 | utterance = utterance.replace(u'AF', u'F') 163 | utterance = utterance.replace(u'\u0640', u'') 164 | utterance = utterance.replace(u'o', u'') 165 | utterance = utterance.replace(u'aA', u'A') 166 | utterance = utterance.replace(u'aY', u'Y') 167 | utterance = utterance.replace(u' A', u' ') 168 | utterance = utterance.replace(u'F', u'an') 169 | utterance = utterance.replace(u'N', u'un') 170 | utterance = utterance.replace(u'K', u'in') 171 | utterance = utterance.replace(u'|', u'>A') 172 | #utterance = utterance.split(u' ') 173 | 174 | # Deal with Hamza types that when not followed by a short vowel letter, 175 | # this short vowel is added automatically 176 | utterance = re.sub(u'Ai', u'a', utterance) 178 | utterance = re.sub(u'Au', u'>u', utterance) 179 | utterance = re.sub(u'^>([^auAw])', u'>a\\1', utterance) 180 | utterance = re.sub(u' >([^auAw ])', u' >a\\1', utterance) 181 | utterance = re.sub(u'<([^i])', u' 0): # shadda just doubles the letter before it 231 | phones[-1] += phones[-1] 232 | # ----------------------------------------------------------------------------------------------- 233 | if (letter == u'|'): # Madda only changes based in emphaticness 234 | if (emphaticContext): 235 | phones += [maddaMap[u'|'][1]] 236 | else: 237 | phones += [maddaMap[u'|'][0]] 238 | # ---------------------------------------------------------------------------------------------------------------- 239 | if (letter == u'p'): # Ta' marboota is determined by the following if it is a diacritic or not 240 | if (letter1 in diacritics): 241 | phones += [ambiguousConsonantMap[u'p'][0]] 242 | else: 243 | phones += [ambiguousConsonantMap[u'p'][1]] 244 | # ---------------------------------------------------------------------------------------------------------------- 245 | if (letter in vowelMap): 246 | if (letter in [u'w', 247 | u'y']): # Waw and Ya are complex they could be consonants or vowels and their gemination is complex as it could be a combination of a vowel and consonants 248 | if (letter1 in diacriticsWithoutShadda + [u'A', u'Y'] or ( 249 | letter1 in [u'w', u'y'] and not letter2 in diacritics + [u'A', u'w', 250 | u'y']) or ( 251 | letter_1 in diacriticsWithoutShadda and letter1 in consonants + [u'e'])): 252 | if ((letter in [u'w'] and letter_1 in [u'u'] and not letter1 in [u'a', u'i', u'A', 253 | u'Y']) or ( 254 | letter in [u'y'] and letter_1 in [u'i'] and not letter1 in [u'a', 255 | u'u', 256 | u'A', 257 | u'Y'])): 258 | if (emphaticContext): 259 | phones += [vowelMap[letter][1][0]] 260 | else: 261 | phones += [vowelMap[letter][0][0]] 262 | else: 263 | if (letter1 in [u'A'] and letter in [u'w'] and letter2 in [u'e']): 264 | phones += [[ambiguousConsonantMap[letter], vowelMap[letter][0][0]]] 265 | else: 266 | phones += [ambiguousConsonantMap[letter]] 267 | elif letter1 in [u'~']: 268 | if (letter_1 in [u'a'] or (letter in [u'w'] and letter_1 in [u'i', u'y']) or ( 269 | letter in [u'y'] and letter_1 in [u'w', u'u'])): 270 | phones += [ambiguousConsonantMap[letter], ambiguousConsonantMap[letter]] 271 | else: 272 | phones += [vowelMap[letter][0][0], ambiguousConsonantMap[letter]] 273 | else: # Waws and Ya's at the end of the word could be shortened 274 | if emphaticContext: 275 | if (letter_1 in consonants + [u'u', u'i'] and letter1 in [u'e']): 276 | phones += [[vowelMap[letter][1][0], vowelMap[letter][1][0][1:]]] 277 | else: 278 | phones += [vowelMap[letter][1][0]] 279 | else: 280 | if (letter_1 in consonants + [u'u', u'i'] and letter1 in [u'e']): 281 | phones += [[vowelMap[letter][0][0], vowelMap[letter][0][0][1:]]] 282 | else: 283 | phones += [vowelMap[letter][0][0]] 284 | # Kasra and Damma could be mildened if before a final silent consonant 285 | if letter in [u'u', u'i']: 286 | if emphaticContext: 287 | if ((letter1 in unambiguousConsonantMap or letter1 == u'l') and letter2 == u'e' and len( 288 | word) > 7): 289 | phones += [vowelMap[letter][1][1]] 290 | else: 291 | phones += [vowelMap[letter][1][0]] 292 | else: 293 | if ((letter1 in unambiguousConsonantMap or letter1 == u'l') and letter2 == u'e' and len( 294 | word) > 7): 295 | phones += [vowelMap[letter][0][1]] 296 | else: 297 | phones += [vowelMap[letter][0][0]] 298 | # Alif could be ommited in definite article and beginning of some words 299 | if letter in [u'a', u'A', u'Y']: 300 | if (letter in [u'A'] and letter_1 in [u'w', u'k'] and letter_2 == u'b'): 301 | phones += [[u'a', vowelMap[letter][0][0]]] 302 | elif letter in [u'A'] and letter_1 in [u'u', u'i']: 303 | temp = True # do nothing 304 | # Waw al jama3a: The Alif after is optional 305 | elif letter in [u'A'] and letter_1 in [u'w'] and letter1 in [u'e']: 306 | phones += [[vowelMap[letter][0][0], vowelMap[letter][0][1]]] 307 | elif letter in [u'A', u'Y'] and letter1 in [u'e']: 308 | if emphaticContext: 309 | phones += [[vowelMap[letter][1][0], vowelMap[u'a'][1]]] 310 | else: 311 | phones += [[vowelMap[letter][0][0], vowelMap[u'a'][0]]] 312 | else: 313 | if emphaticContext: 314 | phones += [vowelMap[letter][1][0]] 315 | else: 316 | phones += [vowelMap[letter][0][0]] 317 | # ---------------------------------------------------------------------- 318 | # End of main loop------------------------------------------------------ 319 | # ---------------------------------------------------------------------- 320 | possibilities = 1 # Holds the number of possible pronunciations of a word 321 | 322 | # count the number of possible pronunciations 323 | for letter in phones: 324 | if isinstance(letter, list): 325 | possibilities = possibilities * len(letter) 326 | 327 | # Generate all possible pronunciations 328 | for i in range(0, possibilities): 329 | pronunciations.append([]) 330 | iterations = 1 331 | for index, letter in enumerate(phones): 332 | if isinstance(letter, list): 333 | curIndex = (i / iterations) % len(letter) 334 | if letter[curIndex] != u'': 335 | pronunciations[-1].append(letter[curIndex]) 336 | iterations = iterations * len(letter) 337 | else: 338 | if letter != u'': 339 | pronunciations[-1].append(letter) 340 | 341 | # Iterate through each pronunciation to perform some house keeping. 342 | # And append pronunciation to dictionary 343 | # 1- Remove duplicate vowels 344 | # 2- Remove duplicate y and w 345 | for pronunciation in pronunciations: 346 | prevLetter = '' 347 | toDelete = [] 348 | for i in range(0, len(pronunciation)): 349 | letter = pronunciation[i] 350 | if (letter in ['aa', 'uu0', 'ii0', 'AA', 'UU0', 'II0'] and prevLetter.lower() == letter[ 351 | 1:].lower()): # Delete duplicate consecutive vowels 352 | toDelete.append(i - 1) 353 | pronunciation[i] = pronunciation[i - 1][0] + pronunciation[i - 1] 354 | if (letter in ['u0', 'i0'] and prevLetter.lower() == letter.lower()): # Delete duplicates 355 | toDelete.append(i - 1) 356 | pronunciation[i] = pronunciation[i - 1] 357 | # delete duplicate 358 | if letter in ['y', 'w'] and prevLetter == letter: 359 | pronunciation[i - 1] += pronunciation[i - 1] 360 | toDelete.append(i); 361 | 362 | prevLetter = letter 363 | for i in reversed(range(0, len(toDelete))): 364 | del (pronunciation[toDelete[i]]) 365 | result += word[2:-2] + ' ' + ' '.join(pronunciation) + '\n' 366 | 367 | # Append utterance pronunciation to utterancesPronunciations 368 | utterancesPronuncations[-1] += " " + " ".join(pronunciations[0]) 369 | else: 370 | utterancesPronuncations[-1] += " sil" 371 | return utterancesPronuncations 372 | # ----------------------------------------------------------------------------------------------------- 373 | # Read input file-------------------------------------------------------------------------------------- 374 | # ----------------------------------------------------------------------------------------------------- 375 | if __name__ == '__main__': 376 | try: 377 | inputFileName = sys.argv[1] 378 | except: 379 | print("No input file provided") 380 | sys.exit() 381 | 382 | inputFile = open(inputFileName, mode='r', encoding='utf-8') 383 | utterances = inputFile.read().splitlines() 384 | inputFile.close() 385 | 386 | result = '' # Pronunciations Dictionary 387 | utterancesPronuncations = [] # Most likely pronunciation for all utterances 388 | 389 | # ----------------------------------------------------------------------------------------------------- 390 | # Loop through utterances------------------------------------------------------------------------------ 391 | # ----------------------------------------------------------------------------------------------------- 392 | utteranceNumber = 1 393 | for utterance in utterances: 394 | wavFileName = '' 395 | try: 396 | wavFileName = utterance.split(' "')[0].rstrip() # Split line and get file name from first part 397 | utterance = " ".join(utterance.split(' "')[1:]).strip( 398 | '"').rstrip() # Split line and get the orthography from the second part 399 | except: 400 | print("Format Error in utterance number " + str(utteranceNumber)) 401 | sys.exit() 402 | 403 | utteranceNumber += 1 404 | utterancesPronuncations.append('') # Add empty entry that will hold this utterance's pronuncation 405 | 406 | # Do some normalisation work and split utterance to words 407 | utterance = utterance.replace(u'AF', u'F') 408 | utterance = utterance.replace(u'\u0640', u'') 409 | utterance = utterance.replace(u'o', u'') 410 | utterance = utterance.replace(u'aA', u'A') 411 | utterance = utterance.replace(u'aY', u'Y') 412 | utterance = utterance.replace(u' A', u' ') 413 | utterance = utterance.replace(u'F', u'an') 414 | utterance = utterance.replace(u'N', u'un') 415 | utterance = utterance.replace(u'K', u'in') 416 | utterance = utterance.replace(u'|', u'>A') 417 | utterance = utterance.split(u' ') 418 | 419 | # Deal with Hamza types that when not followed by a short vowel letter, 420 | # this short vowel is added automatically 421 | utterance = re.sub(u'Ai', u'a', utterance) 423 | utterance = re.sub(u'Au', u'>u', utterance) 424 | utterance = re.sub(u'^>([^auAw])', u'>a\\1', utterance) 425 | utterance = re.sub(u' >([^auAw ])', u' >a\\1', utterance) 426 | utterance = re.sub(u'<([^i])', u' 0): # shadda just doubles the letter before it 478 | phones[-1] += phones[-1] 479 | # ----------------------------------------------------------------------------------------------- 480 | if (letter == u'|'): # Madda only changes based in emphaticness 481 | if (emphaticContext): 482 | phones += [maddaMap[u'|'][1]] 483 | else: 484 | phones += [maddaMap[u'|'][0]] 485 | # ---------------------------------------------------------------------------------------------------------------- 486 | if (letter == u'p'): # Ta' marboota is determined by the following if it is a diacritic or not 487 | if (letter1 in diacritics): 488 | phones += [ambiguousConsonantMap[u'p'][0]] 489 | else: 490 | phones += [ambiguousConsonantMap[u'p'][1]] 491 | # ---------------------------------------------------------------------------------------------------------------- 492 | if (letter in vowelMap): 493 | if (letter in [u'w', 494 | u'y']): # Waw and Ya are complex they could be consonants or vowels and their gemination is complex as it could be a combination of a vowel and consonants 495 | if (letter1 in diacriticsWithoutShadda + [u'A', u'Y'] or ( 496 | letter1 in [u'w', u'y'] and not letter2 in diacritics + [u'A', u'w', 497 | u'y']) or ( 498 | letter_1 in diacriticsWithoutShadda and letter1 in consonants + [u'e'])): 499 | if ((letter in [u'w'] and letter_1 in [u'u'] and not letter1 in [u'a', u'i', u'A', 500 | u'Y']) or ( 501 | letter in [u'y'] and letter_1 in [u'i'] and not letter1 in [u'a', 502 | u'u', 503 | u'A', 504 | u'Y'])): 505 | if (emphaticContext): 506 | phones += [vowelMap[letter][1][0]] 507 | else: 508 | phones += [vowelMap[letter][0][0]] 509 | else: 510 | if (letter1 in [u'A'] and letter in [u'w'] and letter2 in [u'e']): 511 | phones += [[ambiguousConsonantMap[letter], vowelMap[letter][0][0]]] 512 | else: 513 | phones += [ambiguousConsonantMap[letter]] 514 | elif letter1 in [u'~']: 515 | if (letter_1 in [u'a'] or (letter in [u'w'] and letter_1 in [u'i', u'y']) or ( 516 | letter in [u'y'] and letter_1 in [u'w', u'u'])): 517 | phones += [ambiguousConsonantMap[letter], ambiguousConsonantMap[letter]] 518 | else: 519 | phones += [vowelMap[letter][0][0], ambiguousConsonantMap[letter]] 520 | else: # Waws and Ya's at the end of the word could be shortened 521 | if emphaticContext: 522 | if (letter_1 in consonants + [u'u', u'i'] and letter1 in [u'e']): 523 | phones += [[vowelMap[letter][1][0], vowelMap[letter][1][0][1:]]] 524 | else: 525 | phones += [vowelMap[letter][1][0]] 526 | else: 527 | if (letter_1 in consonants + [u'u', u'i'] and letter1 in [u'e']): 528 | phones += [[vowelMap[letter][0][0], vowelMap[letter][0][0][1:]]] 529 | else: 530 | phones += [vowelMap[letter][0][0]] 531 | # Kasra and Damma could be mildened if before a final silent consonant 532 | if letter in [u'u', u'i']: 533 | if emphaticContext: 534 | if ((letter1 in unambiguousConsonantMap or letter1 == u'l') and letter2 == u'e' and len( 535 | word) > 7): 536 | phones += [vowelMap[letter][1][1]] 537 | else: 538 | phones += [vowelMap[letter][1][0]] 539 | else: 540 | if ((letter1 in unambiguousConsonantMap or letter1 == u'l') and letter2 == u'e' and len( 541 | word) > 7): 542 | phones += [vowelMap[letter][0][1]] 543 | else: 544 | phones += [vowelMap[letter][0][0]] 545 | # Alif could be ommited in definite article and beginning of some words 546 | if letter in [u'a', u'A', u'Y']: 547 | if (letter in [u'A'] and letter_1 in [u'w', u'k'] and letter_2 == u'b'): 548 | phones += [[u'a', vowelMap[letter][0][0]]] 549 | elif letter in [u'A'] and letter_1 in [u'u', u'i']: 550 | temp = True # do nothing 551 | # Waw al jama3a: The Alif after is optional 552 | elif letter in [u'A'] and letter_1 in [u'w'] and letter1 in [u'e']: 553 | phones += [[vowelMap[letter][0][0], vowelMap[letter][0][1]]] 554 | elif letter in [u'A', u'Y'] and letter1 in [u'e']: 555 | if emphaticContext: 556 | phones += [[vowelMap[letter][1][0], vowelMap[u'a'][1]]] 557 | else: 558 | phones += [[vowelMap[letter][0][0], vowelMap[u'a'][0]]] 559 | else: 560 | if emphaticContext: 561 | phones += [vowelMap[letter][1][0]] 562 | else: 563 | phones += [vowelMap[letter][0][0]] 564 | # ---------------------------------------------------------------------- 565 | # End of main loop------------------------------------------------------ 566 | # ---------------------------------------------------------------------- 567 | possibilities = 1 # Holds the number of possible pronunciations of a word 568 | 569 | # count the number of possible pronunciations 570 | for letter in phones: 571 | if isinstance(letter, list): 572 | possibilities = possibilities * len(letter) 573 | 574 | # Generate all possible pronunciations 575 | for i in range(0, possibilities): 576 | pronunciations.append([]) 577 | iterations = 1 578 | for index, letter in enumerate(phones): 579 | if isinstance(letter, list): 580 | curIndex = (i / iterations) % len(letter) 581 | if letter[curIndex] != u'': 582 | pronunciations[-1].append(letter[curIndex]) 583 | iterations = iterations * len(letter) 584 | else: 585 | if letter != u'': 586 | pronunciations[-1].append(letter) 587 | 588 | # Iterate through each pronunciation to perform some house keeping. 589 | # And append pronunciation to dictionary 590 | # 1- Remove duplicate vowels 591 | # 2- Remove duplicate y and w 592 | for pronunciation in pronunciations: 593 | prevLetter = '' 594 | toDelete = [] 595 | for i in range(0, len(pronunciation)): 596 | letter = pronunciation[i] 597 | if (letter in ['aa', 'uu0', 'ii0', 'AA', 'UU0', 'II0'] and prevLetter.lower() == letter[ 598 | 1:].lower()): # Delete duplicate consecutive vowels 599 | toDelete.append(i - 1) 600 | pronunciation[i] = pronunciation[i - 1][0] + pronunciation[i - 1] 601 | if (letter in ['u0', 'i0'] and prevLetter.lower() == letter.lower()): # Delete duplicates 602 | toDelete.append(i - 1) 603 | pronunciation[i] = pronunciation[i - 1] 604 | # delete duplicate 605 | if letter in ['y', 'w'] and prevLetter == letter: 606 | pronunciation[i - 1] += pronunciation[i - 1] 607 | toDelete.append(i); 608 | 609 | prevLetter = letter 610 | for i in reversed(range(0, len(toDelete))): 611 | del (pronunciation[toDelete[i]]) 612 | result += word[2:-2] + ' ' + ' '.join(pronunciation) + '\n' 613 | 614 | # Append utterance pronunciation to utterancesPronunciations 615 | utterancesPronuncations[-1] += " " + " ".join(pronunciations[0]) 616 | else: 617 | utterancesPronuncations[-1] += " sil" 618 | 619 | # Add sound file name back 620 | utterancesPronuncations[-1] = wavFileName + ' "' + utterancesPronuncations[-1].strip() + '"' 621 | 622 | # ---------------------------------------------------------------------------- 623 | # Save output----------------------------------------------------------------- 624 | # ---------------------------------------------------------------------------- 625 | # Save Utterances pronunciations 626 | outFile = open('utterance-pronunciations.txt', mode='w', encoding='utf-8') 627 | outFile.write("\n".join(utterancesPronuncations)) 628 | outFile.close() 629 | 630 | # Save Pronunciation Dictionary 631 | outFile = open('dict', mode='w', encoding='utf-8') 632 | outFile.write(result.rstrip()) 633 | outFile.close() 634 | 635 | # Sort Dictionary 636 | os.system("sortandfilter.py dict") 637 | -------------------------------------------------------------------------------- /phonetise_Arabic.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- coding: UTF8 -*- 3 | 4 | import argparse 5 | import os 6 | import re 7 | 8 | import findstress 9 | from arutils import arabic_utils 10 | 11 | buckwalter = { # mapping from Arabic script to Buckwalter 12 | u'\u0628': u'b', u'\u0630': u'*', u'\u0637': u'T', u'\u0645': u'm', 13 | u'\u062a': u't', u'\u0631': u'r', u'\u0638': u'Z', u'\u0646': u'n', 14 | u'\u062b': u'^', u'\u0632': u'z', u'\u0639': u'E', u'\u0647': u'h', 15 | u'\u062c': u'j', u'\u0633': u's', u'\u063a': u'g', u'\u062d': u'H', 16 | u'\u0642': u'q', u'\u0641': u'f', u'\u062e': u'x', u'\u0635': u'S', 17 | u'\u0634': u'$', u'\u062f': u'd', u'\u0636': u'D', u'\u0643': u'k', 18 | u'\u0623': u'>', u'\u0621': u'\'', u'\u0626': u'}', u'\u0624': u'&', 19 | u'\u0625': u'<', u'\u0622': u'|', u'\u0627': u'A', u'\u0649': u'Y', 20 | u'\u0629': u'p', u'\u064a': u'y', u'\u0644': u'l', u'\u0648': u'w', 21 | u'\u064b': u'F', u'\u064c': u'N', u'\u064d': u'K', u'\u064e': u'a', 22 | u'\u064f': u'u', u'\u0650': u'i', u'\u0651': u'~', u'\u0652': u'o' 23 | } 24 | 25 | ArabicScript = { # mapping from Buckwalter to Arabic script 26 | u'b': u'\u0628', u'*': u'\u0630', u'T': u'\u0637', u'm': u'\u0645', 27 | u't': u'\u062a', u'r': u'\u0631', u'Z': u'\u0638', u'n': u'\u0646', 28 | u'^': u'\u062b', u'z': u'\u0632', u'E': u'\u0639', u'h': u'\u0647', 29 | u'j': u'\u062c', u's': u'\u0633', u'g': u'\u063a', u'H': u'\u062d', 30 | u'q': u'\u0642', u'f': u'\u0641', u'x': u'\u062e', u'S': u'\u0635', 31 | u'$': u'\u0634', u'd': u'\u062f', u'D': u'\u0636', u'k': u'\u0643', 32 | u'>': u'\u0623', u'\'': u'\u0621', u'}': u'\u0626', u'&': u'\u0624', 33 | u'<': u'\u0625', u'|': u'\u0622', u'A': u'\u0627', u'Y': u'\u0649', 34 | u'p': u'\u0629', u'y': u'\u064a', u'l': u'\u0644', u'w': u'\u0648', 35 | u'F': u'\u064b', u'N': u'\u064c', u'K': u'\u064d', u'a': u'\u064e', 36 | u'u': u'\u064f', u'i': u'\u0650', u'~': u'\u0651', u'o': u'\u0652' 37 | } 38 | 39 | 40 | # Convert input string to Buckwalter 41 | def arabicToBuckwalter(word): 42 | result = u'' 43 | for letter in word: 44 | if letter in buckwalter: 45 | result += buckwalter[letter] 46 | else: 47 | result += letter 48 | return result 49 | 50 | 51 | # Convert input string to Arabic 52 | def buckwalterToArabic(word): 53 | result = u'' 54 | for letter in word: 55 | if letter in ArabicScript: 56 | result += ArabicScript[letter] 57 | else: 58 | result += letter 59 | return result 60 | 61 | 62 | # ---------------------------------------------------------------------------- 63 | # Grapheme to Phoneme mappings------------------------------------------------ 64 | # ---------------------------------------------------------------------------- 65 | unambiguousConsonantMap = { 66 | u'b': u'b', u'*': u'*', u'T': u'T', u'm': u'm', 67 | u't': u't', u'r': u'r', u'Z': u'Z', u'n': u'n', 68 | u'^': u'^', u'z': u'z', u'E': u'E', u'h': u'h', 69 | u'j': u'j', u's': u's', u'g': u'g', u'H': u'H', 70 | u'q': u'q', u'f': u'f', u'x': u'x', u'S': u'S', 71 | u'$': u'$', u'd': u'd', u'D': u'D', u'k': u'k', 72 | u'>': u'<', u'\'': u'<', u'}': u'<', u'&': u'<', 73 | u'<': u'<' 74 | } 75 | 76 | ambiguousConsonantMap = { 77 | u'l': [u'l', u''], u'w': u'w', u'y': u'y', u'p': [u't', u''] 78 | # These consonants are only unambiguous in certain contexts 79 | } 80 | 81 | maddaMap = { 82 | u'|': [[u'<', u'aa'], [u'<', u'AA']] 83 | } 84 | 85 | vowelMap = { 86 | u'A': [[u'aa', u''], [u'AA', u'']], u'Y': [[u'aa', u''], [u'AA', u'']], 87 | u'w': [[u'uu0', u'uu1'], [u'UU0', u'UU1']], 88 | u'y': [[u'ii0', u'ii1'], [u'II0', u'II1']], 89 | u'a': [u'a', u'A'], 90 | u'u': [[u'u0', u'u1'], [u'U0', u'U1']], 91 | u'i': [[u'i0', u'i1'], [u'I0', u'I1']], 92 | } 93 | 94 | nunationMap = { 95 | u'F': [[u'a', u'n'], [u'A', u'n']], u'N': [[u'u1', u'n'], [u'U1', u'n']], u'K': [[u'i1', u'n'], [u'I1', u'n']] 96 | } 97 | 98 | diacritics = [u'o', u'a', u'u', u'i', u'F', u'N', u'K', u'~'] 99 | diacriticsWithoutShadda = [u'o', u'a', u'u', u'i', u'F', u'N', u'K'] 100 | emphatics = [u'D', u'S', u'T', u'Z', u'g', u'x', u'q'] 101 | forwardEmphatics = [u'g', u'x'] 102 | consonants = [u'>', u'<', u'}', u'&', u'\'', u'b', u't', u'^', u'j', u'H', u'x', u'd', u'*', u'r', u'z', u's', u'$', 103 | u'S', u'D', u'T', u'Z', u'E', u'g', u'f', u'q', u'k', u'l', u'm', u'n', u'h', u'|'] 104 | 105 | # ------------------------------------------------------------------------------------ 106 | # Words with fixed irregular pronunciations------------------------------------------- 107 | # ------------------------------------------------------------------------------------ 108 | fixedWords = { 109 | u'h*A': [u'h aa * aa', u'h aa * a', ], 110 | u'bh*A': [u'b i0 h aa * aa', u'b i0 h aa * a', ], 111 | u'kh*A': [u'k a h aa * aa', u'k a h aa * a', ], 112 | u'fh*A': [u'f a h aa * aa', u'f a h aa * a', ], 113 | u'h*h': [u'h aa * i0 h i0', u'h aa * i1 h'], 114 | u'bh*h': [u'b i0 h aa * i0 h i0', u'b i0 h aa * i1 h'], 115 | u'kh*h': [u'k a h aa * i0 h i0', u'k a h aa * i1 h'], 116 | u'fh*h': [u'f a h aa * i0 h i0', u'f a h aa * i1 h'], 117 | u'h*An': [u'h aa * aa n i0', u'h aa * aa n'], 118 | u'h&lA\'': [u'h aa < u0 l aa < i0', u'h aa < u0 l aa <'], 119 | u'*lk': [u'* aa l i0 k a', u'* aa l i0 k'], 120 | u'b*lk': [u'b i0 * aa l i0 k a', u'b i0 * aa l i0 k'], 121 | u'k*lk': [u'k a * aa l i0 k a', u'k a * aa l i1 k'], 122 | u'*lkm': u'* aa l i0 k u1 m', 123 | u'>wl}k': [u'< u0 l aa < i0 k a', u'< u0 l aa < i1 k'], 124 | u'Th': u'T aa h a', 125 | u'lkn': [u'l aa k i0 nn a', u'l aa k i1 n'], 126 | u'lknh': u'l aa k i0 nn a h u0', 127 | u'lknhm': u'l aa k i0 nn a h u1 m', 128 | u'lknk': [u'l aa k i0 nn a k a', u'l aa k i0 nn a k i0'], 129 | u'lknkm': u'l aa k i0 nn a k u1 m', 130 | u'lknkmA': u'l aa k i0 nn a k u0 m aa', 131 | u'lknnA': u'l aa k i0 nn a n aa', 132 | u'AlrHmn': [u'rr a H m aa n i0', u'rr a H m aa n'], 133 | u'Allh': [u'll aa h i0', u'll aa h', u'll AA h u0', u'll AA h a', u'll AA h', u'll A'], 134 | u'h*yn': [u'h aa * a y n i0', u'h aa * a y n'], 135 | 136 | u'wh*A': [u'w a h aa * aa', u'w a h aa * a', ], 137 | u'wbh*A': [u'w a b i0 h aa * aa', u'w a b i0 h aa * a', ], 138 | u'wkh*A': [u'w a k a h aa * aa', u'w a k a h aa * a', ], 139 | u'wh*h': [u'w a h aa * i0 h i0', u'w a h aa * i1 h'], 140 | u'wbh*h': [u'w a b i0 h aa * i0 h i0', u'w a b i0 h aa * i1 h'], 141 | u'wkh*h': [u'w a k a h aa * i0 h i0', u'w a k a h aa * i1 h'], 142 | u'wh*An': [u'w a h aa * aa n i0', u'w a h aa * aa n'], 143 | u'wh&lA\'': [u'w a h aa < u0 l aa < i0', u'w a h aa < u0 l aa <'], 144 | u'w*lk': [u'w a * aa l i0 k a', u'w a * aa l i0 k'], 145 | u'wb*lk': [u'w a b i0 * aa l i0 k a', u'w a b i0 * aa l i0 k'], 146 | u'wk*lk': [u'w a k a * aa l i0 k a', u'w a k a * aa l i1 k'], 147 | u'w*lkm': u'w a * aa l i0 k u1 m', 148 | u'w>wl}k': [u'w a < u0 l aa < i0 k a', u'w a < u0 l aa < i1 k'], 149 | u'wTh': u'w a T aa h a', 150 | u'wlkn': [u'w a l aa k i0 nn a', u'w a l aa k i1 n'], 151 | u'wlknh': u'w a l aa k i0 nn a h u0', 152 | u'wlknhm': u'w a l aa k i0 nn a h u1 m', 153 | u'wlknk': [u'w a l aa k i0 nn a k a', u'w a l aa k i0 nn a k i0'], 154 | u'wlknkm': u'w a l aa k i0 nn a k u1 m', 155 | u'wlknkmA': u'w a l aa k i0 nn a k u0 m aa', 156 | u'wlknnA': u'w a l aa k i0 nn a n aa', 157 | u'wAlrHmn': [u'w a rr a H m aa n i0', u'w a rr a H m aa n'], 158 | u'wAllh': [u'w a ll aa h i0', u'w a ll aa h', u'w a ll AA h u0', u'w a ll AA h a', u'w a ll AA h', u'w a ll A'], 159 | u'wh*yn': [u'w a h aa * a y n i0', u'w a h aa * a y n'], 160 | u'w': [u'w a'], 161 | u'Aw': [u'< a w'], 162 | u'>w': [u'< a w'], 163 | 164 | u'Alf': [u'< a l f'], 165 | u'>lf': [u'< a l f'], 166 | u'b>lf': [u'b i0 < a l f'], 167 | u'f>lf': [u'f a < a l f'], 168 | u'wAlf': [u'w a < a l f'], 169 | u'w>lf': [u'w a < a l f'], 170 | u'wb>lf': [u'w a b i0 < a l f'], 171 | 172 | u'nt': u'n i1 t', 173 | u'fydyw': u'v i0 d y uu1', 174 | u'lndn': u'l A n d u1 n' 175 | } 176 | 177 | 178 | def isFixedWord(word, results, orthography, pronunciations): 179 | lastLetter = '' 180 | if len(word) > 0: 181 | lastLetter = word[-1] 182 | if lastLetter == u'a': 183 | lastLetter = [u'a', u'A'] 184 | elif lastLetter == u'A': 185 | lastLetter = [u'aa'] 186 | elif lastLetter == u'u': 187 | lastLetter = [u'u0'] 188 | elif lastLetter == u'i': 189 | lastLetter = [u'i0'] 190 | elif lastLetter in unambiguousConsonantMap: 191 | lastLetter = [unambiguousConsonantMap[lastLetter]] 192 | wordConsonants = re.sub(u'[^h*Ahn\'>wl}kmyTtfdb]', u'', word) # Remove all dacritics from word 193 | if wordConsonants in fixedWords: # check if word is in the fixed word lookup table 194 | if isinstance(fixedWords[wordConsonants], list): 195 | done = False 196 | for pronunciation in fixedWords[wordConsonants]: 197 | if pronunciation.split(u' ')[-1] in lastLetter: 198 | results += word + u' ' + pronunciation + u'\n' # add each pronunciation to the pronunciation dictionary 199 | pronunciations.append(pronunciation.split(u' ')) 200 | done = True 201 | if not done: 202 | # add each pronunciation to the pronunciation dictionary 203 | results += word + u' ' + fixedWords[wordConsonants][0] + u'\n' 204 | pronunciations.append(fixedWords[wordConsonants][0].split(u' ')) 205 | else: 206 | # add pronunciation to the pronunciation dictionary 207 | results += word + u' ' + fixedWords[wordConsonants] + u'\n' 208 | pronunciations.append(fixedWords[wordConsonants].split(u' ')) 209 | return results 210 | 211 | 212 | # modification in isFixedWord2 is just to return the pronunciations without the word 213 | def isFixedWord2(word, results, orthography, pronunciations): 214 | lastLetter = '' 215 | if len(word) > 0: 216 | lastLetter = word[-1] 217 | if lastLetter == u'a': 218 | lastLetter = [u'a', u'A'] 219 | elif lastLetter == u'A': 220 | lastLetter = [u'aa'] 221 | elif lastLetter == u'u': 222 | lastLetter = [u'u0'] 223 | elif lastLetter == u'i': 224 | lastLetter = [u'i0'] 225 | elif lastLetter in unambiguousConsonantMap: 226 | lastLetter = [unambiguousConsonantMap[lastLetter]] 227 | wordConsonants = re.sub(u'[^h*Ahn\'>wl}kmyTtfdb]', u'', word) # Remove all dacritics from word 228 | if wordConsonants in fixedWords: # check if word is in the fixed word lookup table 229 | if isinstance(fixedWords[wordConsonants], list): 230 | done = False 231 | for pronunciation in fixedWords[wordConsonants]: 232 | if pronunciation.split(u' ')[-1] in lastLetter: 233 | # add each pronunciation to the pronunciation dictionary 234 | # results += word + u' ' + pronunciation + u'\n' 235 | results += pronunciation + u'\n' 236 | pronunciations.append(pronunciation.split(u' ')) 237 | done = True 238 | if not done: 239 | # add each pronunciation to the pronunciation dictionary 240 | # results += word + u' ' + fixedWords[wordConsonants][0] + u'\n' 241 | results += fixedWords[wordConsonants][0] + u'\n' 242 | pronunciations.append(fixedWords[wordConsonants][0].split(u' ')) 243 | else: 244 | # add pronunciation to the pronunciation dictionary 245 | # results += word + u' ' + fixedWords[wordConsonants] + u'\n' 246 | results += fixedWords[wordConsonants] + u'\n' 247 | pronunciations.append(fixedWords[wordConsonants].split(u' ')) 248 | return results 249 | 250 | 251 | def phonetise(text): 252 | utterances = text.splitlines() 253 | result = u'' # Pronunciations Dictionary 254 | utterances_pronunciations = [] # Most likely pronunciation for all utterances 255 | utterances_pronunciations_with_boundaries = [] # Most likely pronunciation for all utterances 256 | 257 | # ----------------------------------------------------------------------------------------------------- 258 | # Loop through utterances------------------------------------------------------------------------------ 259 | # ----------------------------------------------------------------------------------------------------- 260 | utterance_number = 1 261 | for utterance in utterances: 262 | utterance_number += 1 263 | utterances_pronunciations.append('') # Add empty entry that will hold this utterance's pronuncation 264 | utterances_pronunciations_with_boundaries.append( 265 | '') # Add empty entry that will hold this utterance's pronuncation 266 | 267 | utterance = arabicToBuckwalter(utterance) 268 | print(u"phoetising utterance") 269 | print(utterance) 270 | # Do some normalisation work and split utterance to words 271 | utterance = utterance.replace(u'AF', u'F') 272 | utterance = utterance.replace(u'\u0640', u'') 273 | utterance = utterance.replace(u'o', u'') 274 | utterance = utterance.replace(u'aA', u'A') 275 | utterance = utterance.replace(u'aY', u'Y') 276 | utterance = re.sub(u'([^\\-]) A', u'\\1 ', utterance) 277 | utterance = utterance.replace(u'F', u'an') 278 | utterance = utterance.replace(u'N', u'un') 279 | utterance = utterance.replace(u'K', u'in') 280 | utterance = utterance.replace(u'|', u'>A') 281 | 282 | # Deal with Hamza types that when not followed by a short vowel letter, 283 | # this short vowel is added automatically 284 | utterance = re.sub(u'^Ai', u'a', utterance) 286 | utterance = re.sub(u'^Au', u'>u', utterance) 287 | utterance = re.sub(u'Ai', u'a', utterance) 289 | utterance = re.sub(u'Au', u'>u', utterance) 290 | utterance = re.sub(u'^Al', u'>al', utterance) 291 | utterance = re.sub(u' - Al', u' - >al', utterance) 292 | utterance = re.sub(u'^- Al', u'- >al', utterance) 293 | utterance = re.sub(u'^>([^auAw])', u'>a\\1', utterance) 294 | utterance = re.sub(u' >([^auAw ])', u' >a\\1', utterance) 295 | utterance = re.sub(u'<([^i])', u' 0: 351 | phones[-1] += phones[-1] 352 | # ---------------------------------------------------------------------------------------------------------------- 353 | if letter == u'|': # Madda only changes based in emphaticness 354 | if (emphaticContext): 355 | phones += [maddaMap[u'|'][1]] 356 | else: 357 | phones += [maddaMap[u'|'][0]] 358 | # ---------------------------------------------------------------------------------------------------------------- 359 | if letter == u'p': # Ta' marboota is determined by the following if it is a diacritic or not 360 | if (letter1 in diacritics): 361 | phones += [ambiguousConsonantMap[u'p'][0]] 362 | else: 363 | phones += [ambiguousConsonantMap[u'p'][1]] 364 | # ---------------------------------------------------------------------------------------------------------------- 365 | if letter in vowelMap: 366 | if (letter in [u'w', 367 | u'y']): # Waw and Ya are complex they could be consonants or vowels and their gemination is complex as it could be a combination of a vowel and consonants 368 | if (letter1 in diacriticsWithoutShadda + [u'A', u'Y'] or ( 369 | letter1 in [u'w', u'y'] and not letter2 in diacritics + [u'A', u'w', 370 | u'y']) or ( 371 | letter_1 in diacriticsWithoutShadda and letter1 in consonants + [u'e'])): 372 | if ((letter in [u'w'] and letter_1 in [u'u'] and not letter1 in [u'a', u'i', u'A', 373 | u'Y']) or ( 374 | letter in [u'y'] and letter_1 in [u'i'] and not letter1 in [u'a', 375 | u'u', 376 | u'A', 377 | u'Y'])): 378 | if emphaticContext: 379 | phones += [vowelMap[letter][1][0]] 380 | else: 381 | phones += [vowelMap[letter][0][0]] 382 | else: 383 | if letter1 in [u'A'] and letter in [u'w'] and letter2 in [u'e']: 384 | phones += [[vowelMap[letter][0][0], ambiguousConsonantMap[letter]]] 385 | else: 386 | phones += [ambiguousConsonantMap[letter]] 387 | elif letter1 in [u'~']: 388 | if (letter_1 in [u'a'] or (letter in [u'w'] and letter_1 in [u'i', u'y']) or ( 389 | letter in [u'y'] and letter_1 in [u'w', u'u'])): 390 | phones += [ambiguousConsonantMap[letter], ambiguousConsonantMap[letter]] 391 | else: 392 | phones += [vowelMap[letter][0][0], ambiguousConsonantMap[letter]] 393 | else: # Waws and Ya's at the end of the word could be shortened 394 | if emphaticContext: 395 | if (letter_1 in consonants + [u'u', u'i'] and letter1 in [u'e']): 396 | phones += [[vowelMap[letter][1][0], vowelMap[letter][1][0][1:]]] 397 | else: 398 | phones += [vowelMap[letter][1][0]] 399 | else: 400 | if letter_1 in consonants + [u'u', u'i'] and letter1 in [u'e']: 401 | phones += [[vowelMap[letter][0][0], vowelMap[letter][0][0][1:]]] 402 | else: 403 | phones += [vowelMap[letter][0][0]] 404 | # Kasra and Damma could be mildened if before a final silent consonant 405 | if letter in [u'u', u'i']: 406 | if emphaticContext: 407 | if ((letter1 in unambiguousConsonantMap or letter1 == u'l') and letter2 == u'e' and len( 408 | word) > 7): 409 | phones += [vowelMap[letter][1][1]] 410 | else: 411 | phones += [vowelMap[letter][1][0]] 412 | else: 413 | if ((letter1 in unambiguousConsonantMap or letter1 == u'l') and letter2 == u'e' and len( 414 | word) > 7): 415 | phones += [vowelMap[letter][0][1]] 416 | else: 417 | phones += [vowelMap[letter][0][0]] 418 | # Alif could be ommited in definite article and beginning of some words 419 | if letter in [u'a', u'A', u'Y']: 420 | if letter in [u'A'] and letter_1 in [u'w', u'k'] and letter_2 == u'b' and letter1 in [u'l']: 421 | phones += [[u'a', vowelMap[letter][0][0]]] 422 | elif letter in [u'A'] and letter_1 in [u'u', u'i']: 423 | temp = True # do nothing 424 | # Waw al jama3a: The Alif after is optional 425 | elif letter in [u'A'] and letter_1 in [u'w'] and letter1 in [u'e']: 426 | phones += [[vowelMap[letter][0][1], vowelMap[letter][0][0]]] 427 | elif letter in [u'A', u'Y'] and letter1 in [u'e']: 428 | if emphaticContext: 429 | phones += [[vowelMap[letter][1][0], vowelMap[u'a'][1]]] 430 | else: 431 | phones += [[vowelMap[letter][0][0], vowelMap[u'a'][0]]] 432 | else: 433 | if emphaticContext: 434 | phones += [vowelMap[letter][1][0]] 435 | else: 436 | phones += [vowelMap[letter][0][0]] 437 | # ------------------------------------------------------------------------------------------------------------------------- 438 | # End of main loop--------------------------------------------------------------------------------------------------------- 439 | # ------------------------------------------------------------------------------------------------------------------------- 440 | possibilities = 1 # Holds the number of possible pronunciations of a word 441 | 442 | # count the number of possible pronunciations 443 | for letter in phones: 444 | if isinstance(letter, list): 445 | possibilities = possibilities * len(letter) 446 | 447 | # Generate all possible pronunciations 448 | for i in range(0, possibilities): 449 | pronunciations.append([]) 450 | iterations = 1 451 | for index, letter in enumerate(phones): 452 | if isinstance(letter, list): 453 | curIndex = int(i / iterations) % len(letter) 454 | if letter[curIndex] != u'': 455 | pronunciations[-1].append(letter[curIndex]) 456 | iterations = iterations * len(letter) 457 | else: 458 | if letter != u'': 459 | pronunciations[-1].append(letter) 460 | 461 | # Iterate through each pronunciation to perform some house keeping. And append pronunciation to dictionary 462 | # 1- Remove duplicate vowels 463 | # 2- Remove duplicate y and w 464 | for pronunciation in pronunciations: 465 | prevLetter = u'' 466 | toDelete = [] 467 | for i in range(0, len(pronunciation)): 468 | letter = pronunciation[i] 469 | # Delete duplicate consecutive vowels 470 | if (letter in [u'aa', u'uu0', u'ii0', u'AA', u'UU0', u'II0'] and prevLetter.lower() == letter[ 471 | 1:].lower()): 472 | toDelete.append(i - 1) 473 | pronunciation[i] = pronunciation[i - 1][0] + pronunciation[i - 1] 474 | if letter in [u'u0', u'i0'] and prevLetter.lower() == letter.lower(): # Delete duplicates 475 | toDelete.append(i - 1) 476 | pronunciation[i] = pronunciation[i - 1] 477 | if letter in [u'y', u'w'] and prevLetter == letter: # delete duplicate 478 | pronunciation[i - 1] += pronunciation[i - 1] 479 | toDelete.append(i); 480 | if letter in [u'a'] and prevLetter == letter: # delete duplicate 481 | toDelete.append(i); 482 | 483 | prevLetter = letter 484 | for i in reversed(range(0, len(toDelete))): 485 | del (pronunciation[toDelete[i]]) 486 | result += word[2:-2] + u' ' + u' '.join(pronunciation) + u'\n' 487 | 488 | # Append utterance pronunciation to utterancesPronunciations 489 | utterances_pronunciations[-1] += u" " + u" ".join(pronunciations[0]) 490 | 491 | # Add Stress to each pronunciation 492 | pIndex = 0 493 | for pronunciation in pronunciations: 494 | stressIndex = findstress.find_stress_index(pronunciation) 495 | if stressIndex < len(pronunciation) and stressIndex != -1: 496 | pronunciation[stressIndex] += u'\'' 497 | else: 498 | if pIndex == 0: 499 | print('skipped') 500 | print(pronunciation) 501 | pIndex += 1 502 | # Append utterance pronunciation to utterancesPronunciations 503 | utterances_pronunciations_with_boundaries[-1] += u" " + u"".join(pronunciations[0]) 504 | else: 505 | utterances_pronunciations[-1] += u" sil" 506 | utterances_pronunciations_with_boundaries[-1] += u" sil" 507 | 508 | # Add sound file name back 509 | utterances_pronunciations[-1] = utterances_pronunciations[-1].strip() + u" sil" 510 | utterances_pronunciations_with_boundaries[-1] = utterances_pronunciations_with_boundaries[-1].strip() + u" sil" 511 | 512 | return utterances_pronunciations_with_boundaries, utterances_pronunciations, result 513 | 514 | 515 | def phonetise_word(arabic_word): 516 | utterances = [arabic_word] 517 | arabic_word = arabic_utils.remove_diacritics(arabic_word) 518 | result = '' # Pronunciations Dictionary 519 | utterances_pronunciations = [] # Most likely pronunciation for all utterances 520 | utterances_pronunciations_with_boundaries = [] # Most likely pronunciation for all utterances 521 | 522 | # ----------------------------------------------------------------------------------------------------- 523 | # Loop through utterances------------------------------------------------------------------------------ 524 | # ----------------------------------------------------------------------------------------------------- 525 | utterance_number = 1 526 | for utterance in utterances: 527 | utterance_number += 1 528 | utterances_pronunciations.append('') # Add empty entry that will hold this utterance's pronuncation 529 | # Add empty entry that will hold this utterance's pronuncation 530 | utterances_pronunciations_with_boundaries.append('') 531 | 532 | utterance = arabicToBuckwalter(utterance) 533 | # print(u"phoetising utterance") 534 | # print(utterance) 535 | # Do some normalisation work and split utterance to words 536 | utterance = utterance.replace(u'AF', u'F') 537 | utterance = utterance.replace(u'\u0640', u'') 538 | utterance = utterance.replace(u'o', u'') 539 | utterance = utterance.replace(u'aA', u'A') 540 | utterance = utterance.replace(u'aY', u'Y') 541 | utterance = re.sub(u'([^\\-]) A', u'\\1 ', utterance) 542 | utterance = utterance.replace(u'F', u'an') 543 | utterance = utterance.replace(u'N', u'un') 544 | utterance = utterance.replace(u'K', u'in') 545 | utterance = utterance.replace(u'|', u'>A') 546 | 547 | # Deal with Hamza types that when not followed by a short vowel letter, 548 | # this short vowel is added automatically 549 | utterance = re.sub(u'^Ai', u'a', utterance) 551 | utterance = re.sub(u'^Au', u'>u', utterance) 552 | utterance = re.sub(u'Ai', u'a', utterance) 554 | utterance = re.sub(u'Au', u'>u', utterance) 555 | utterance = re.sub(u'^Al', u'>al', utterance) 556 | utterance = re.sub(u' - Al', u' - >al', utterance) 557 | utterance = re.sub(u'^- Al', u'- >al', utterance) 558 | utterance = re.sub(u'^>([^auAw])', u'>a\\1', utterance) 559 | utterance = re.sub(u' >([^auAw ])', u' >a\\1', utterance) 560 | utterance = re.sub(u'<([^i])', u' 0: 616 | phones[-1] += phones[-1] 617 | # ---------------------------------------------------------------------------------------------------------------- 618 | if letter == u'|': # Madda only changes based in emphaticness 619 | if (emphaticContext): 620 | phones += [maddaMap[u'|'][1]] 621 | else: 622 | phones += [maddaMap[u'|'][0]] 623 | # ---------------------------------------------------------------------------------------------------------------- 624 | if letter == u'p': # Ta' marboota is determined by the following if it is a diacritic or not 625 | if (letter1 in diacritics): 626 | phones += [ambiguousConsonantMap[u'p'][0]] 627 | else: 628 | phones += [ambiguousConsonantMap[u'p'][1]] 629 | # ---------------------------------------------------------------------------------------------------------------- 630 | if letter in vowelMap: 631 | # Waw and Ya are complex they could be consonants or vowels and their gemination is complex as 632 | # it could be a combination of a vowel and consonants 633 | if (letter in [u'w', u'y']): 634 | if (letter1 in diacriticsWithoutShadda + [u'A', u'Y'] or ( 635 | letter1 in [u'w', u'y'] and not letter2 in diacritics + [u'A', u'w', 636 | u'y']) or ( 637 | letter_1 in diacriticsWithoutShadda and letter1 in consonants + [u'e'])): 638 | if ((letter in [u'w'] and letter_1 in [u'u'] and not letter1 in [u'a', u'i', u'A', 639 | u'Y']) or ( 640 | letter in [u'y'] and letter_1 in [u'i'] and not letter1 in [u'a', 641 | u'u', 642 | u'A', 643 | u'Y'])): 644 | if emphaticContext: 645 | phones += [vowelMap[letter][1][0]] 646 | else: 647 | phones += [vowelMap[letter][0][0]] 648 | else: 649 | if letter1 in [u'A'] and letter in [u'w'] and letter2 in [u'e']: 650 | phones += [[vowelMap[letter][0][0], ambiguousConsonantMap[letter]]] 651 | else: 652 | phones += [ambiguousConsonantMap[letter]] 653 | elif letter1 in [u'~']: 654 | if (letter_1 in [u'a'] or (letter in [u'w'] and letter_1 in [u'i', u'y']) or ( 655 | letter in [u'y'] and letter_1 in [u'w', u'u'])): 656 | phones += [ambiguousConsonantMap[letter], ambiguousConsonantMap[letter]] 657 | else: 658 | phones += [vowelMap[letter][0][0], ambiguousConsonantMap[letter]] 659 | else: # Waws and Ya's at the end of the word could be shortened 660 | if emphaticContext: 661 | if (letter_1 in consonants + [u'u', u'i'] and letter1 in [u'e']): 662 | phones += [[vowelMap[letter][1][0], vowelMap[letter][1][0][1:]]] 663 | else: 664 | phones += [vowelMap[letter][1][0]] 665 | else: 666 | if letter_1 in consonants + [u'u', u'i'] and letter1 in [u'e']: 667 | phones += [[vowelMap[letter][0][0], vowelMap[letter][0][0][1:]]] 668 | else: 669 | phones += [vowelMap[letter][0][0]] 670 | # Kasra and Damma could be mildened if before a final silent consonant 671 | if letter in [u'u', u'i']: 672 | if emphaticContext: 673 | if ((letter1 in unambiguousConsonantMap or letter1 == u'l') and letter2 == u'e' and len( 674 | word) > 7): 675 | phones += [vowelMap[letter][1][1]] 676 | else: 677 | phones += [vowelMap[letter][1][0]] 678 | else: 679 | if ((letter1 in unambiguousConsonantMap or letter1 == u'l') and letter2 == u'e' and len( 680 | word) > 7): 681 | phones += [vowelMap[letter][0][1]] 682 | else: 683 | phones += [vowelMap[letter][0][0]] 684 | # Alif could be ommited in definite article and beginning of some words 685 | if letter in [u'a', u'A', u'Y']: 686 | if letter in [u'A'] and letter_1 in [u'w', u'k'] and letter_2 == u'b' and letter1 in [u'l']: 687 | phones += [[u'a', vowelMap[letter][0][0]]] 688 | elif letter in [u'A'] and letter_1 in [u'u', u'i']: 689 | temp = True # do nothing 690 | # Waw al jama3a: The Alif after is optional 691 | elif letter in [u'A'] and letter_1 in [u'w'] and letter1 in [u'e']: 692 | phones += [[vowelMap[letter][0][1], vowelMap[letter][0][0]]] 693 | elif letter in [u'A', u'Y'] and letter1 in [u'e']: 694 | if emphaticContext: 695 | phones += [[vowelMap[letter][1][0], vowelMap[u'a'][1]]] 696 | else: 697 | phones += [[vowelMap[letter][0][0], vowelMap[u'a'][0]]] 698 | else: 699 | if emphaticContext: 700 | phones += [vowelMap[letter][1][0]] 701 | else: 702 | phones += [vowelMap[letter][0][0]] 703 | # ------------------------------------------------------------------------------------------------------------------------- 704 | # End of main loop--------------------------------------------------------------------------------------------------------- 705 | # ------------------------------------------------------------------------------------------------------------------------- 706 | possibilities = 1 # Holds the number of possible pronunciations of a word 707 | 708 | # count the number of possible pronunciations 709 | for letter in phones: 710 | if isinstance(letter, list): 711 | possibilities = possibilities * len(letter) 712 | 713 | # Generate all possible pronunciations 714 | for i in range(0, possibilities): 715 | pronunciations.append([]) 716 | iterations = 1 717 | for index, letter in enumerate(phones): 718 | if isinstance(letter, list): 719 | curIndex = int(i / iterations) % len(letter) 720 | if letter[curIndex] != u'': 721 | pronunciations[-1].append(letter[curIndex]) 722 | iterations = iterations * len(letter) 723 | else: 724 | if letter != u'': 725 | pronunciations[-1].append(letter) 726 | 727 | # Iterate through each pronunciation to perform some house keeping. 728 | # And append pronunciation to dictionary 729 | # 1- Remove duplicate vowels 730 | # 2- Remove duplicate y and w 731 | for pronunciation in pronunciations: 732 | prevLetter = u'' 733 | toDelete = [] 734 | for i in range(0, len(pronunciation)): 735 | letter = pronunciation[i] 736 | # Delete duplicate consecutive vowels 737 | if (letter in [u'aa', u'uu0', u'ii0', u'AA', u'UU0', u'II0'] and prevLetter.lower() == letter[ 738 | 1:].lower()): 739 | toDelete.append(i - 1) 740 | pronunciation[i] = pronunciation[i - 1][0] + pronunciation[i - 1] 741 | if letter in [u'u0', u'i0'] and prevLetter.lower() == letter.lower(): # Delete duplicates 742 | toDelete.append(i - 1) 743 | pronunciation[i] = pronunciation[i - 1] 744 | if letter in [u'y', u'w'] and prevLetter == letter: # delete duplicate 745 | pronunciation[i - 1] += pronunciation[i - 1] 746 | toDelete.append(i); 747 | if letter in [u'a'] and prevLetter == letter: # delete duplicate 748 | toDelete.append(i); 749 | 750 | prevLetter = letter 751 | for i in reversed(range(0, len(toDelete))): 752 | del (pronunciation[toDelete[i]]) 753 | # result += word[2:-2] + u' ' + u' '.join(pronunciation) + u'\n' 754 | result += u' '.join(pronunciation) + u'\n' 755 | 756 | # Append utterance pronunciation to utterancesPronunciations 757 | utterances_pronunciations[-1] += u" " + u" ".join(pronunciations[0]) 758 | 759 | # Add Stress to each pronunciation 760 | pIndex = 0 761 | for pronunciation in pronunciations: 762 | stressIndex = findstress.find_stress_index(pronunciation) 763 | if stressIndex < len(pronunciation) and stressIndex != -1: 764 | pronunciation[stressIndex] += u'\'' 765 | else: 766 | if pIndex == 0: 767 | # print('skipped') 768 | # print(pronunciation) 769 | pass 770 | pIndex += 1 771 | # Append utterance pronunciation to utterancesPronunciations 772 | utterances_pronunciations_with_boundaries[-1] += u" " + u"".join(pronunciations[0]) 773 | else: 774 | utterances_pronunciations[-1] += u" sil" 775 | utterances_pronunciations_with_boundaries[-1] += u" sil" 776 | 777 | # Add sound file name back 778 | utterances_pronunciations[-1] = utterances_pronunciations[-1].strip() + u" sil" 779 | utterances_pronunciations_with_boundaries[-1] = utterances_pronunciations_with_boundaries[-1].strip() + u" sil" 780 | my_pronunciations = set() 781 | for r in result.split('\n'): 782 | if r.strip() and len(r.split()) >= len(arabic_word): # discard wrong (short) pronunciations 783 | my_pronunciations.add(r) 784 | return list(my_pronunciations) 785 | 786 | 787 | 788 | # ----------------------------------------------------------------------------------------------------- 789 | # Read input file-------------------------------------------------------------------------------------- 790 | # ----------------------------------------------------------------------------------------------------- 791 | 792 | 793 | parser = argparse.ArgumentParser(description='extracts dictionary and phones from a corpus') 794 | parser.add_argument('-i', '--input', type=argparse.FileType(mode='r', encoding='utf-8'), 795 | help='input file', required=True) 796 | 797 | if __name__ == '__main__': 798 | args = parser.parse_args() 799 | inputFile = args.input.read() 800 | (utterancesPronuncationsWithBoundaries, utterancesPronuncations, dict) = phonetise(inputFile) 801 | 802 | # ---------------------------------------------------------------------------- 803 | # Save output----------------------------------------------------------------- 804 | # ---------------------------------------------------------------------------- 805 | file_prefix, ext = args.input.name.split('.') 806 | file_prefix = file_prefix 807 | # Save Utterances pronunciations 808 | print('Save Utterances pronunciations') 809 | outFile = open(file_prefix + '-utterance-pronunciations.txt', mode='w', encoding='utf-8') 810 | outFile.write(u"\n".join(utterancesPronuncations)) 811 | outFile.close() 812 | # Save Utterances pronunciations (with wordboundaries) 813 | print('Save Utterances pronunciations (with wordboundaries)') 814 | outFile = open(file_prefix + '-utterance-pronunciations-with-boundaries.txt', mode='w', encoding='utf-8') 815 | outFile.write(u"\n".join(utterancesPronuncationsWithBoundaries)) 816 | outFile.close() 817 | 818 | # Save Pronunciation Dictionary 819 | print('Save Pronunciation Dictionary') 820 | outFile = open(file_prefix + '.dict', mode='w', encoding='utf-8') 821 | outFile.write(dict.rstrip()) 822 | outFile.close() 823 | 824 | # Sort Dictionary 825 | print('Sort Dictionary') 826 | os.system("python sortandfilter.py {}.dict".format(file_prefix)) 827 | print('done!') 828 | --------------------------------------------------------------------------------