Grammalecte  Diff

Differences From Artifact [1ffed9614b]:

To Artifact [39bc8d4153]:


8
9
10
11
12
13
14

15
16
17
18
19
20
21
22
23
24
25
26
27
28











29
30
31
32
33
34
35
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47







+














+
+
+
+
+
+
+
+
+
+
+







import json
import os

import grammalecte.ibdawg as ibdawg
from grammalecte.echo import echo
from grammalecte.str_transform import defineSuffixCode
import grammalecte.fr.conj as conj
import grammalecte.tokenizer as tkz


class cd:
    """Context manager for changing the current working directory"""
    def __init__ (self, newPath):
        self.newPath = os.path.expanduser(newPath)

    def __enter__ (self):
        self.savedPath = os.getcwd()
        os.chdir(self.newPath)

    def __exit__ (self, etype, value, traceback):
        os.chdir(self.savedPath)


def readFile (spf):
    if os.path.isfile(spf):
        with open(spf, "r", encoding="utf-8") as hSrc:
            for sLine in hSrc:
                sLine = sLine.strip()
                if sLine and not sLine.startswith("#"):
                    yield sLine
    else:
        raise OSError("# Error. File not found or not loadable: " + spf)


def makeDictionaries (sp, sVersion):
    with cd(sp+"/dictionnaire"):
        os.system("genfrdic.py -s -gl -v "+sVersion)


def makeConj (sp, bJS=False):
45
46
47
48
49
50
51
52
53
54


55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116





























































117
118
119
120
121
122
123
57
58
59
60
61
62
63



64
65






























































66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133







-
-
-
+
+
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+







                "spre": ":Sp", "simp": ":Sq",
                "cond": ":K", "impe": ":E",
                "1sg": ":1s", "2sg": ":2s", "3sg": ":3s", "1pl": ":1p", "2pl": ":2p", "3pl": ":3p", "1isg": ":1ś",
                "mas sg": ":Q1", "mas pl": ":Q2", "mas inv": ":Q1", "fem sg": ":Q3", "fem pl": ":Q4", "epi inv": ":Q1"
            }

    # read lexicon
    with open(sp+"/data/dictConj.txt", 'r', encoding='utf-8') as hSrc:
        nStop = 0
        for n, line in enumerate(hSrc.readlines()):
    nStop = 0
    for n, sLine in enumerate(readFile(sp+"/data/dictConj.txt")):
            line = line.strip()
            nTab = line.count("\t")
            if nTab == 1:
                # new entry
                sLemma, sVtyp = line.split("\t")
                dConj = {   ":PQ": { ":P": "", ":Q1": "", ":Q2": "", ":Q3": "", ":Q4": ""},
                            ":Ip": { ":1s": "", ":2s": "", ":3s": "", ":1p": "", ":2p": "", ":3p": "", ":1ś": "" },
                            ":Iq": { ":1s": "", ":2s": "", ":3s": "", ":1p": "", ":2p": "", ":3p": "" },
                            ":Is": { ":1s": "", ":2s": "", ":3s": "", ":1p": "", ":2p": "", ":3p": "" },
                            ":If": { ":1s": "", ":2s": "", ":3s": "", ":1p": "", ":2p": "", ":3p": "" },
                            ":K": { ":1s": "", ":2s": "", ":3s": "", ":1p": "", ":2p": "", ":3p": "" },
                            ":Sp": { ":1s": "", ":2s": "", ":3s": "", ":1p": "", ":2p": "", ":3p": "", ":1ś": "" },
                            ":Sq": { ":1s": "", ":2s": "", ":3s": "", ":1p": "", ":2p": "", ":3p": "", ":1ś": "" },
                            ":E": { ":2s": "", ":1p": "", ":2p": "" }
                        }
                if sVtyp not in lVtyp:
                    dVtyp[sVtyp] = nVtyp
                    lVtyp.append(sVtyp)
                    nVtyp += 1
            elif nTab == 2:
                # flexion
                _, sTag, sFlex = line.split("\t")
                if sTag.count(" ") == 0:
                    if sTag == "ppre":
                        dConj[":PQ"][":P"] = defineSuffixCode(sLemma, sFlex)
                else:
                    try:
                        mode, g = sTag.split(maxsplit=1)
                        mode = dTrad[mode]
                        g = dTrad[g]
                        if dConj[mode][g] == "":
                            dConj[mode][g] = defineSuffixCode(sLemma, sFlex)
                        else:
                            # comment gérer les autres graphies ?
                            pass
                    except:
                        print(sLemma.encode("utf-8").decode("ascii"), " - ", sTag, " - non géré: ", mode, " / ", g)
            elif line == "$":
                # we store the dictionary of rules for this lemma
                if dConj[":Ip"][":1ś"] == "2è":
                    dConj[":Ip"][":1ś"] = "2é"
                elif sLemma == "pouvoir":
                    dConj[":Ip"][":1ś"] = "6uis"
                lConjTags = []
                for key in [":PQ", ":Ip", ":Iq", ":Is", ":If", ":K", ":Sp", ":Sq", ":E"]:
                    bFound = False
                    for i, d in enumerate(dPatternList[key]):
                        if dConj[key] == d:
                            bFound = True
                            lConjTags.append(i)
                            break
                    if not bFound:
                        lConjTags.append(len(dPatternList[key]))
                        dPatternList[key].append(dConj[key])
                tConjTags = tuple(lConjTags)
                if tConjTags not in lTags:
                    dTags[tConjTags] = nTags
                    lTags.append(tConjTags)
                    nTags += 1
                dVerb[sLemma] = (dVtyp[sVtyp], dTags[tConjTags])
            else:
                print("# Error - unknown line #", n)
        nTab = sLine.count("\t")
        if nTab == 1:
            # new entry
            sLemma, sVtyp = sLine.split("\t")
            dConj = {   ":PQ": { ":P": "", ":Q1": "", ":Q2": "", ":Q3": "", ":Q4": ""},
                        ":Ip": { ":1s": "", ":2s": "", ":3s": "", ":1p": "", ":2p": "", ":3p": "", ":1ś": "" },
                        ":Iq": { ":1s": "", ":2s": "", ":3s": "", ":1p": "", ":2p": "", ":3p": "" },
                        ":Is": { ":1s": "", ":2s": "", ":3s": "", ":1p": "", ":2p": "", ":3p": "" },
                        ":If": { ":1s": "", ":2s": "", ":3s": "", ":1p": "", ":2p": "", ":3p": "" },
                        ":K": { ":1s": "", ":2s": "", ":3s": "", ":1p": "", ":2p": "", ":3p": "" },
                        ":Sp": { ":1s": "", ":2s": "", ":3s": "", ":1p": "", ":2p": "", ":3p": "", ":1ś": "" },
                        ":Sq": { ":1s": "", ":2s": "", ":3s": "", ":1p": "", ":2p": "", ":3p": "", ":1ś": "" },
                        ":E": { ":2s": "", ":1p": "", ":2p": "" }
                    }
            if sVtyp not in lVtyp:
                dVtyp[sVtyp] = nVtyp
                lVtyp.append(sVtyp)
                nVtyp += 1
        elif nTab == 2:
            # flexion
            _, sTag, sFlex = sLine.split("\t")
            if sTag.count(" ") == 0:
                if sTag == "ppre":
                    dConj[":PQ"][":P"] = defineSuffixCode(sLemma, sFlex)
            else:
                try:
                    mode, g = sTag.split(maxsplit=1)
                    mode = dTrad[mode]
                    g = dTrad[g]
                    if dConj[mode][g] == "":
                        dConj[mode][g] = defineSuffixCode(sLemma, sFlex)
                    else:
                        # comment gérer les autres graphies ?
                        pass
                except:
                    print(sLemma.encode("utf-8").decode("ascii"), " - ", sTag, " - non géré: ", mode, " / ", g)
        elif sLine == "$":
            # we store the dictionary of rules for this lemma
            if dConj[":Ip"][":1ś"] == "2è":
                dConj[":Ip"][":1ś"] = "2é"
            elif sLemma == "pouvoir":
                dConj[":Ip"][":1ś"] = "6uis"
            lConjTags = []
            for key in [":PQ", ":Ip", ":Iq", ":Is", ":If", ":K", ":Sp", ":Sq", ":E"]:
                bFound = False
                for i, d in enumerate(dPatternList[key]):
                    if dConj[key] == d:
                        bFound = True
                        lConjTags.append(i)
                        break
                if not bFound:
                    lConjTags.append(len(dPatternList[key]))
                    dPatternList[key].append(dConj[key])
            tConjTags = tuple(lConjTags)
            if tConjTags not in lTags:
                dTags[tConjTags] = nTags
                lTags.append(tConjTags)
                nTags += 1
            dVerb[sLemma] = (dVtyp[sVtyp], dTags[tConjTags])
        else:
            print("# Error - unknown line #", n)

    # convert tuples to bytes string
    # si ça merde, toute la partie conversion peut être supprimée
    # lBytesTags = []
    # for t in lTags:
    #     b = b""
    #     for n in t:
167
168
169
170
171
172
173
174
175
176
177
178



179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
























































236
237
238
239
240
241
242
177
178
179
180
181
182
183





184
185
186

























































187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249







-
-
-
-
-
+
+
+
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+







    print("(Python et JavaScript)"  if bJS  else "(Python seulement)")
    aPlurS = set()
    dTag = {}
    lTagMasForm = []
    lTagMiscPlur = []
    dMiscPlur = {}
    dMasForm = {}
    # read lexicon
    with open(sp+"/data/dictDecl.txt", 'r', encoding='utf-8') as hSrc:
        lTag = []
        lTagMasPl = []
        for n, line in enumerate(hSrc.readlines()):
    lTag = []
    lTagMasPl = []
    for n, sLine in enumerate(readFile(sp+"/data/dictDecl.txt")):
            line = line.strip()
            nTab = line.count("\t")
            if nTab == 1:
                # new entry
                lTag.clear()
                lTagMasPl.clear()
                sLemma, sFlags = line.split("\t")
                if sFlags.startswith("S"):
                    cType = "s"
                elif sFlags.startswith("X"):
                    cType = "p"
                elif sFlags.startswith("A"):
                    cType = "p"
                elif sFlags.startswith("I"):
                    cType = "p"
                elif sFlags.startswith("F"):
                    cType = "m"
                elif sFlags.startswith("W"):
                    cType = "m"
                else:
                    cType = "?"
                    print(" > inconnu : " + sFlags)
            elif nTab == 2:
                if cType == "s":
                    continue
                _, sFlexTags, sFlex = line.split("\t")
                if cType == "p":
                    if sFlexTags.endswith("pl"):
                        lTag.append(defineSuffixCode(sLemma, sFlex))
                elif cType == "m":
                    if sFlexTags.endswith("mas sg") or sFlexTags.endswith("mas inv"):
                        lTag.append(defineSuffixCode(sLemma, sFlex))
                    if sFlexTags.endswith("mas pl"):
                        lTagMasPl.append(defineSuffixCode(sLemma, sFlex))
                else:
                    print("erreur: " + cType)
            elif line == "$":
                if cType == "s":
                    aPlurS.add(sLemma)
                elif cType == "p":
                    sTag = "|".join(lTag)
                    if sTag not in dTag:
                        dTag[sTag] = len(lTagMiscPlur)
                        lTagMiscPlur.append(sTag)
                    dMiscPlur[sLemma] = dTag[sTag]
                elif cType == "m":
                    sTag = "|".join(lTag)
                    if lTagMasPl:
                        sTag += "/" + "|".join(lTagMasPl)
                    if sTag not in dTag:
                        dTag[sTag] = len(lTagMasForm)
                        lTagMasForm.append(sTag)
                    dMasForm[sLemma] = dTag[sTag]
                else:
                    print("unknown tag: " + ctype)
            else:
                print("# Error - unknown line #", n)
        nTab = sLine.count("\t")
        if nTab == 1:
            # new entry
            lTag.clear()
            lTagMasPl.clear()
            sLemma, sFlags = sLine.split("\t")
            if sFlags.startswith("S"):
                cType = "s"
            elif sFlags.startswith("X"):
                cType = "p"
            elif sFlags.startswith("A"):
                cType = "p"
            elif sFlags.startswith("I"):
                cType = "p"
            elif sFlags.startswith("F"):
                cType = "m"
            elif sFlags.startswith("W"):
                cType = "m"
            else:
                cType = "?"
                print(" > inconnu : " + sFlags)
        elif nTab == 2:
            if cType == "s":
                continue
            _, sFlexTags, sFlex = sLine.split("\t")
            if cType == "p":
                if sFlexTags.endswith("pl"):
                    lTag.append(defineSuffixCode(sLemma, sFlex))
            elif cType == "m":
                if sFlexTags.endswith("mas sg") or sFlexTags.endswith("mas inv"):
                    lTag.append(defineSuffixCode(sLemma, sFlex))
                if sFlexTags.endswith("mas pl"):
                    lTagMasPl.append(defineSuffixCode(sLemma, sFlex))
            else:
                print("erreur: " + cType)
        elif sLine == "$":
            if cType == "s":
                aPlurS.add(sLemma)
            elif cType == "p":
                sTag = "|".join(lTag)
                if sTag not in dTag:
                    dTag[sTag] = len(lTagMiscPlur)
                    lTagMiscPlur.append(sTag)
                dMiscPlur[sLemma] = dTag[sTag]
            elif cType == "m":
                sTag = "|".join(lTag)
                if lTagMasPl:
                    sTag += "/" + "|".join(lTagMasPl)
                if sTag not in dTag:
                    dTag[sTag] = len(lTagMasForm)
                    lTagMasForm.append(sTag)
                dMasForm[sLemma] = dTag[sTag]
            else:
                print("unknown tag: " + ctype)
        else:
            print("# Error - unknown line #", n)

    ## write file for Python
    sCode = "# generated data (do not edit)\n\n" + \
            "# list of affix codes\n" + \
            "lTagMiscPlur = " + str(lTagMiscPlur) + "\n" + \
            "lTagMasForm = " + str(lTagMasForm) + "\n\n" + \
            "# dictionary of words with uncommon plurals (-x, -ux, english, latin and italian plurals) and tags to generate them\n" + \
254
255
256
257
258
259
260
261

262
263
264
265
266
267
268
269
270
271



272
273
274
275
276
277
278
279







280
281
282
283
284
285
286
287
288
289
290
291
292












293
294
295
296
297
298
299
261
262
263
264
265
266
267

268
269
270
271
272
273
274




275
276
277








278
279
280
281
282
283
284













285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303







-
+






-
-
-
-
+
+
+
-
-
-
-
-
-
-
-
+
+
+
+
+
+
+
-
-
-
-
-
-
-
-
-
-
-
-
-
+
+
+
+
+
+
+
+
+
+
+
+







                '    "dMasForm": ' +  json.dumps(dMasForm, ensure_ascii=False) + "\n}"
        open(sp+"/modules-js/mfsp_data.json", "w", encoding="utf-8", newline="\n").write(sCode)


def makePhonetTable (sp, bJS=False):
    print("> Correspondances phonétiques ", end="")
    print("(Python et JavaScript)"  if bJS  else "(Python seulement)")
    

    try:
        oDict = ibdawg.IBDAWG("French.bdic")
    except:
        traceback.print_exc()
        return

    with open(sp+"/data/phonet_simil.txt", 'r', encoding='utf-8') as hSrc:
        # set of homophonic words
        lSet = []
        for sLine in hSrc.readlines():
    # set of homophonic words
    lSet = []
    for sLine in readFile(sp+"/data/phonet_simil.txt"):
            if not sLine.startswith("#") and sLine.strip():
                lWord = sLine.strip().split()
                aMore = set()
                for sWord in lWord:
                    if sWord.endswith("er") and conj.isVerb(sWord):
                        aMore = aMore.union(conj.getConjSimilInfiV1(sWord))
                lWord.extend(list(aMore))
                lSet.append(sorted(set(lWord)))
        lWord = sLine.split()
        aMore = set()
        for sWord in lWord:
            if sWord.endswith("er") and conj.isVerb(sWord):
                aMore = aMore.union(conj.getConjSimilInfiV1(sWord))
        lWord.extend(list(aMore))
        lSet.append(sorted(set(lWord)))
                #print(lWord)
        # dictionary of words
        dWord = {}
        for i, aSet in enumerate(lSet):
            for sWord in aSet:
                if oDict.lookup(sWord):
                    dWord[sWord] = i  # warning, what if word in several sets?
                else:
                    echo("Mot inconnu : " + sWord)
        # dictionary of morphologies
        dMorph = {}
        for sWord in dWord:
            dMorph[sWord] = oDict.getMorph(sWord)
    # dictionary of words
    dWord = {}
    for i, aSet in enumerate(lSet):
        for sWord in aSet:
            if oDict.lookup(sWord):
                dWord[sWord] = i  # warning, what if word in several sets?
            else:
                echo("Mot inconnu : " + sWord)
    # dictionary of morphologies
    dMorph = {}
    for sWord in dWord:
        dMorph[sWord] = oDict.getMorph(sWord)

    # write file for Python
    sCode = "# generated data (do not edit)\n\n" + \
            "dWord = " + str(dWord) + "\n\n" + \
            "lSet = " + str(lSet) + "\n\n" + \
            "dMorph = " + str(dMorph) + "\n"
    open(sp+"/modules/phonet_data.py", "w", encoding="utf-8", newline="\n").write(sCode)
307
308
309
310
311
312
313
314
315
316



317
318
319
320
321
322
323








324
325
326

327
328
329

330
331
332
333
334
335
336
337
338
339
340
341
342
311
312
313
314
315
316
317



318
319
320







321
322
323
324
325
326
327
328
329
330

331
332
333

334
335
336
337
338
339
340
341
342
343
344
345
346
347







-
-
-
+
+
+
-
-
-
-
-
-
-
+
+
+
+
+
+
+
+


-
+


-
+













        open(sp+"/modules-js/phonet_data.json", "w", encoding="utf-8", newline="\n").write(sCode)


def makeLocutions (sp, bJS=False):
    "compile list of locutions in JSON"
    print("> Locutions ", end="")
    print("(Python et JavaScript)"  if bJS  else "(Python seulement)")
    with open(sp+"/data/locutions.txt", 'r', encoding='utf-8') as hSrc:
        dLocutions = {}
        for sLine in hSrc.readlines():
    dLocGraph = {}
    oTokenizer = tkz.Tokenizer("fr")
    for sLine in readFile(sp+"/data/locutions.txt"):
            if not sLine.startswith("#") and sLine.strip():
                lElem = sLine.strip().split()
                dCur = dLocutions
                for sWord in lElem:
                    if sWord not in dCur:
                        dCur[sWord] = {}
                    dCur = dCur[sWord]
        dCur = dLocGraph
        sLoc, sTag = sLine.split("\t")
        for oToken in oTokenizer.genTokens(sLoc.strip()):
            sWord = oToken["sValue"]
            if sWord not in dCur:
                dCur[sWord] = {}
            dCur = dCur[sWord]
        dCur[":"] = sTag

    sCode = "# generated data (do not edit)\n\n" + \
            "dLocutions = " + str(dLocutions) + "\n"
            "dLocutions = " + str(dLocGraph) + "\n"
    open(sp+"/modules/locutions_data.py", "w", encoding="utf-8", newline="\n").write(sCode)
    if bJS:
        open(sp+"/modules-js/locutions_data.json", "w", encoding="utf-8", newline="\n").write(json.dumps(dLocutions, ensure_ascii=False))
        open(sp+"/modules-js/locutions_data.json", "w", encoding="utf-8", newline="\n").write(json.dumps(dLocGraph, ensure_ascii=False))


def before (spLaunch, dVars, bJS=False):
    print("========== Build Hunspell dictionaries ==========")
    makeDictionaries(spLaunch, dVars['oxt_version'])


def after (spLaunch, dVars, bJS=False):
    print("========== Build French data ==========")
    makeMfsp(spLaunch, bJS)
    makeConj(spLaunch, bJS)
    makePhonetTable(spLaunch, bJS)
    makeLocutions(spLaunch, bJS)