textPhonographer.py 17.1 KB
Newer Older
Sylvain Coulange's avatar
Sylvain Coulange committed
1
# -*- encoding:utf8 -*- 
Sylvain Coulange's avatar
Sylvain Coulange committed
2
3
import re, sys, os, datetime, json, tempfile, csv, locale, pinyin, pymongo
from bson import json_util
4
from colorapp.models import Entree, DicEntry, LogStat
Sylvain Coulange's avatar
Sylvain Coulange committed
5
from collections import OrderedDict
Sylvain Coulange's avatar
Sylvain Coulange committed
6

7
locale.setlocale(locale.LC_ALL, "")
8

9
from sys import path as pylib #im naming it as pylib so that we won't get confused between os.path and sys.path 
10

11
pylib += [os.path.relpath(r'../phon2graph')]
Sylvain Coulange's avatar
Sylvain Coulange committed
12
from phon2graph_french import decoupage
Sylvain Coulange's avatar
Sylvain Coulange committed
13
from phon2graph_english import decoupageEn # ENGLISH
Sylvain Coulange's avatar
Sylvain Coulange committed
14
from phon2graph_mandarin import pinyin2phon # MANDARIN CHINESE
15
from .liaisons import *
Sylvain Coulange's avatar
Sylvain Coulange committed
16
17

# FICHIERS
Sylvain Coulange's avatar
Sylvain Coulange committed
18
19
phonColFile = "../phon2graph/data/api2class.json"

20
phonGraphFile = "../phon2graph/data/fidel_wikicolor.scsv" # "../phon2graph/data/phoneme-graphies_fr.scsv"
21
phonGraphFileEn = "../phon2graph/data/fidel_wikicolor_en_global.scsv" # ENGLISH
Sylvain Coulange's avatar
Sylvain Coulange committed
22
23
pinyin2apiFile = "../phon2graph/data/pinyin2api.json" # MANDARIN
api2classFile = "../phon2graph/data/api2class.json" # MANDARIN
Sylvain Coulange's avatar
Sylvain Coulange committed
24

Sylvain Coulange's avatar
Sylvain Coulange committed
25

Sylvain Coulange's avatar
Sylvain Coulange committed
26
27

########################################
28
########## CONNEXION MONGODB ###########
Sylvain Coulange's avatar
Sylvain Coulange committed
29
########################################
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
def connexion():
    mdp = ""
    with open('../private/dbmdp','r') as infile:
        mdp = infile.read()
    print('Connexion à AlemDic...')
    mongodb_client = pymongo.MongoClient("mongodb+srv://alemadmin:"+mdp+"@cluster0.6nopd.mongodb.net/myFirstDatabase?retryWrites=true&w=majority")
    print(mongodb_client.list_database_names())
    return mongodb_client['alemdic']

alemdic = connexion()
dicoFr = alemdic['dicoFr']
dicoEn = alemdic['dicoEn']
dicoZh = alemdic['dicoZh']
dicoFrLogs = alemdic['dicoFrLogs']
dicoEnLogs = alemdic['dicoEnLogs']
dicoZhLogs = alemdic['dicoZhLogs']


##### STATS DICTIONNAIRES
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
def getLenDic(lang):
    # if lang == "fr":
    #     alemDic = dicoFr
    # elif lang == "en":
    #     alemDic = dicoEn
    # elif lang == "zh":
    #     alemDic = dicoZh

    # query = alemDic.find()
    # lenDic = 0
    # for q in query:
    #     lenDic+=1
    # return lenDic

    # VARIANTE ÉCONOMIQUE (calculée à partir des logs)
    if lang == "fr":
        dicoLogs = dicoFrLogs
        base = 1457835 # nb d'entrées au 28 août 2021
    elif lang == "en":
        dicoLogs = dicoEnLogs
        base = 155019 # nb d'entrées au 28 août 2021
    elif lang == "zh":
        dicoLogs = dicoZhLogs
        base = 188996 # nb d'entrées au 28 août 2021

    query = dicoLogs.find()
    nbDel=0
    nbAdd=0
    for q in query:
        if q['type'] == 'ADD': nbAdd+=1
        if q['type'] == 'DEL': nbDel+=1
    return base+nbAdd-nbDel
Sylvain Coulange's avatar
Sylvain Coulange committed
81

82
83
##### MISE EN MÉMOIRE DES DICTIONNAIRES (seulement les transcriptions+regions)
def makeWord2trans(alemDic):
Sylvain Coulange's avatar
Sylvain Coulange committed
84
    query = alemDic.find()#.limit(1000)
85
    word2trans = {}
86
    cpt = 0
87
    for q in query:
88
89
90
        if len(q['w'].split(' '))==1:
            # on met que les mots simples en mémoire (pas les expressions (=avec une espace))
            if q['w'] not in word2trans.keys():
91
                cpt+=1
92
                word2trans[q['w']] = { "t" : q['t'] } # pas besoin de mettre en mémoire le reste pour l'instant (catégories, traductions, fantizi...)
93
                print("Mise en mémoire...",cpt,end='\r',flush=True)
94
95
            else:
                print('DOUBLON DÉTECTÉ :', q['w'])
96
    return word2trans
Sylvain Coulange's avatar
Sylvain Coulange committed
97

98
99
100
101
102

word2transFr = {}
word2transEn = {}
word2transZh = {}

103
104
print("Mise en mémoire de dicoFr...")
word2transFr = makeWord2trans(dicoFr)
105
print("Nombre d'entrées dans AlemDic-dicoFr :", getLenDic('fr'))
106
107
108

print("Mise en mémoire de dicoEn...")
word2transEn = makeWord2trans(dicoEn)
109
print("Nombre d'entrées dans AlemDic-dicoEn :", getLenDic(('en')))
Sylvain Coulange's avatar
Sylvain Coulange committed
110

Sylvain Coulange's avatar
Sylvain Coulange committed
111
112
113
print("Mise en mémoire de dicoZh...")
word2transZh = makeWord2trans(dicoZh)
print("Nombre d'entrées dans AlemDic-dicoZh :", getLenDic('zh'))
114
115
116
117
118
119
120
121

########################################
######### LECTURE DES FICHIERS #########
########################################

##### LECTURE DU CODE PHONEME-COULEUR #####
with open(phonColFile,"r") as phonFile:
    phon2class = json.load(phonFile)
Sylvain Coulange's avatar
Sylvain Coulange committed
122
123


Sylvain Coulange's avatar
Sylvain Coulange committed
124
##### LECTURE DES LISTES PHONEME-GRAPHIES (FIDEL) #####
Sylvain Coulange's avatar
Sylvain Coulange committed
125

Sylvain Coulange's avatar
Sylvain Coulange committed
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
## FR
with open(phonGraphFile,mode="r") as phonFile:
    phon2graphFr = {}
    phonCpt = 0
    graphCpt = 0

    for line in phonFile:
        phonCpt+=1
        line = line.strip()
        l= line.split(':')

        phon2graphFr[l[0]] = []

        listegraphies = l[1].split(',')
        for graph in listegraphies:
            phon2graphFr[l[0]].append(graph.replace("'","’"))
            graphCpt+=1

## EN
with open(phonGraphFileEn,mode="r") as phonFileEn:
    phon2graphEn = {}
    phonCptEn = 0
    graphCptEn = 0

    for line in phonFileEn:
        phonCptEn+=1
        line = line.strip()
        l= line.split(':')

        phon2graphEn[l[0]] = []
Sylvain Coulange's avatar
Sylvain Coulange committed
156

Sylvain Coulange's avatar
Sylvain Coulange committed
157
158
159
160
161
162
163
164
        listegraphies = l[1].split(',')
        for graph in listegraphies:
            phon2graphEn[l[0]].append(graph.replace("'","’"))
            graphCptEn+=1


##### LECTURE DES LOGS #####

165
166
167
168
def getLogStat(lang):
    if lang=="fr": alemDicLogs = dicoFrLogs
    if lang=="en": alemDicLogs = dicoEnLogs
    if lang=="zh": alemDicLogs = dicoZhLogs
169
170
171
172
173
    logStat = LogStat()
    logStat.cptEdit = 0
    logStat.cptModif = 0
    logStat.cptAdd = 0
    logStat.cptDel = 0
174
175
176
177
178
    for log in alemDicLogs.find():
        logStat.cptEdit+=1
        if log['type'] == "MODIF" : logStat.cptModif += 1
        if log['type'] == "ADD" : logStat.cptAdd += 1
        if log['type'] == "DEL" : logStat.cptDel += 1
179
    return logStat
180

181
182
183
print("Nombre de modifications du dictionnaire de français :", getLogStat('fr').cptEdit)
print("Nombre de modifications du dictionnaire d'anglais :", getLogStat('en').cptEdit)
print("Nombre de modifications du dictionnaire de mandarin :", getLogStat('zh').cptEdit)
Sylvain Coulange's avatar
Sylvain Coulange committed
184

Sylvain Coulange's avatar
Sylvain Coulange committed
185
186
187
188
189
190
191
192
193
194
195
196
##### SUPPLEMENTS POUR MANDARIN #####
with open(pinyin2apiFile) as inFile:
    pinyin2api = json.load(inFile)

with open(api2classFile) as inFile:
    api2class = json.load(inFile)


########################################
######### LISTE DES FONCTIONS ##########
########################################

197
def traitement(mot, lang, liaison): # LIAISON : avec le caractere liaison en argument ('O', 'F', 'N' ou None)
Sylvain Coulange's avatar
Sylvain Coulange committed
198
199
200
201
202
203
204
    if lang == "fr":
        word2trans = word2transFr
        phon2graph = phon2graphFr
    elif lang == "en":
        word2trans = word2transEn
        phon2graph = phon2graphEn

Sylvain Coulange's avatar
Sylvain Coulange committed
205
206
207
208
209
    # Enregistrement de la casse
    caseMemory = []
    for i,lettre in enumerate(mot):
        if lettre.isupper():
            caseMemory.append(i)
Sylvain Coulange's avatar
Sylvain Coulange committed
210
            print('caseMemory +=',i,'(',lettre,')')
Sylvain Coulange's avatar
Sylvain Coulange committed
211
212
    mot = mot.lower()

213
    # Traitement de l'apostrophe
Sylvain Coulange's avatar
Sylvain Coulange committed
214
215
    if lang == "fr":
        mot = mot.replace("'",'’')
216
217
    if lang == "en":
        mot = mot.replace("’","'")
Sylvain Coulange's avatar
Sylvain Coulange committed
218
    
219
    # Si mot dans dictionnaire... decoupage(mot,transcription)
Sylvain Coulange's avatar
Sylvain Coulange committed
220
    if re.match(r'^\W+$|^\d+$',mot):
221
        print("'", mot, "' n'est pas un mot.")
222
223
224
225
226
227
228
229
230
231
232
233
234
235
        
        #verifier la liaison
        if '‿' in mot or "-͜" in mot :
            phon = phon_liaison(liaison[-2])
            if liaison[-1] == "O" :
                result = [([(phon, mot)], "", mot, "Liaison obligatoire")]
            elif liaison[-1] == "F" :
                result = [([(phon, mot)], "", mot, "Liaison facultative")]
            elif liaison[-1] == "N" :
                phon = "v"
                result = [([(phon, mot)], "", mot, "Liaison obligatoire")]
        else :
            result = [([('phon_neutre',mot)],"",mot,"")]

236
    elif mot in word2trans.keys():
237
        print("'", mot, "' trouvé dans le dico !",word2trans[mot])
238
        if lang in ["fr","en"]:
Sylvain Coulange's avatar
Sylvain Coulange committed
239
            transList = []
Sylvain Coulange's avatar
Sylvain Coulange committed
240
241
242
243
244
245
246
247
248
249
250
251
252
            shortmem = [] # pour pas afficher plusieurs fois un même alignement (avec et sans syllabation typiquement; le visuel est identique)
            for trans in word2trans[mot]['t']:
                newT = trans['tt'].replace('.','')
                if newT not in shortmem:
                    transList.append((newT,trans['tr']))
                    shortmem.append(newT)
                else:
                    for r in trans['tr']:
                        # pour chaque région du trans courrant: si elle n'est pas dans les régions de la trans identique déjà présente dans transList: on l'ajoute
                        # ci-dessous : alreadyPushedTuple correspond au tuple (newT,trans['r']) déjà présent dans transList, auquel on veut ajouter r
                        if r not in [alreadyPushedTuple for alreadyPushedTuple in transList if alreadyPushedTuple[0]==newT][0][1]:
                            [alreadyPushedTuple for alreadyPushedTuple in transList if alreadyPushedTuple[0]==newT][0][1].append(r)
                print("TRANS",trans)
253
        result = []
254
255
256
257
258
259
260
261
262
263

        ############ partie d'appel de la fonction denasalisation
        if liaison != None :
            liste = ["aucun", "bien", "en", "on", "rien", "un", "non", "mon", "ton", "son","commun"]
            if mot[-1] == 'n' and mot not in liste :
                for i , trans in enumerate(transList):
                    trans = denasal(trans)
                    transList[i] = trans
        ############################################################

264
        for trans in transList:
Sylvain Coulange's avatar
Sylvain Coulange committed
265
            if lang == "fr":
266
                res = decoupage(mot,trans[0],phon2graph,phon2class) # add ,True to get live log
267
268
                ll = trans[1]
                tt = trans[0]
Sylvain Coulange's avatar
Sylvain Coulange committed
269
270
271
                msg = ""
            elif lang == "en":
                mot = mot.replace("'",'’')
272
                res, msg = decoupageEn(mot,trans[0],phon2graph,phon2class) # add ,True to get live log
Sylvain Coulange's avatar
Sylvain Coulange committed
273
274
275
                ll = trans[1]
                tt = trans[0]
            result.append((res,ll,tt,msg))
276
            
Sylvain Coulange's avatar
Sylvain Coulange committed
277
278
    else:
        print("'", mot, "' non trouvé !")
Sylvain Coulange's avatar
Sylvain Coulange committed
279
        result = [([('phon_inconnu',mot)],"","","Mot non trouvé dans le dictionnaire")]
280

Sylvain Coulange's avatar
Sylvain Coulange committed
281
    # Rétablissement de la casse
282
    for r in result:
283
284
285
286
287
288
289
290
291
292
293
        if len(r[0])>0:
            for m in caseMemory:
                cptlettre = 0
                while cptlettre < len(mot):
                    for k,tupl in enumerate(r[0]):
                        #print("\t",tupl)
                        cased = ''
                        for l in tupl[1]:
                            cased += l.upper() if cptlettre == m else l
                            cptlettre += 1
                        r[0][k] = (tupl[0],cased)
Sylvain Coulange's avatar
Sylvain Coulange committed
294
    return result
295

Sylvain Coulange's avatar
Sylvain Coulange committed
296
297
298
299
300

def traitementzh(mot):
    result = [] # liste type : [[car, api, phonlist, ton], [car, api, phonlist, ton]...]

    if mot in word2transZh.keys():
Sylvain Coulange's avatar
Sylvain Coulange committed
301
        pinyinOutput = word2transZh[mot]["t"][0]["tt"].lower()
Sylvain Coulange's avatar
Sylvain Coulange committed
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
        print("Mot trouvé dans le dictionnaire :", mot, pinyinOutput)

    else:
        print("Mot non trouvé dans le dictionnaire!")
        pinyinOutput = pinyin.get(mot, format="numerical", delimiter=" ")
        print("Translittération automatique :", pinyinOutput) # ni3 hao3

    pinparse = pinyinOutput.split(' ') # ['ni3', 'hao3']

    for hanzindex, pintone in enumerate(pinparse):
        if pintone[-1] in ['1', '2', '3', '4', '5'] and len(pintone)>1: # Si il y a un ton et que ce n'est pas qu'un chiffre, c'est que la pinyinisation a fonctionné
            res = [mot[hanzindex]]
            for el in pinyin2phon(pintone, pinyin2api, api2class):
                res.append(el)
            result.append(res)
        else:
            result.append((mot[hanzindex], "", [], 0))

    print(result)
    return result


Sylvain Coulange's avatar
Sylvain Coulange committed
324
def getEntryByWord(m,mc,t,tc,lang):
325
326
327
328
    # m = mot (contenu de la barre de recherche "mot"),
    # mc = motCond (condition de recherche : contient, est égal à, commence par, finit par),
    # t = trans (contenu de la barre de recherche "transcription phonétique"),
    # tc = transCond (condition de recherche : contient, est égal à, commence par, finit par),
329
    # lang = langue cible ('fr', 'en', 'zh'...)
330

Sylvain Coulange's avatar
Sylvain Coulange committed
331
    if lang == "fr":
332
        m = m.replace("'",'’')
Sylvain Coulange's avatar
Sylvain Coulange committed
333
        dico = dicoFr
Sylvain Coulange's avatar
Sylvain Coulange committed
334
    elif lang == "en":
335
        m = m.replace('’',"'")
Sylvain Coulange's avatar
Sylvain Coulange committed
336
337
338
        dico = dicoEn
    elif lang == "zh":
        dico = dicoZh
Sylvain Coulange's avatar
Sylvain Coulange committed
339

340
341
342
343
344
345
    m = m.lower()
    t = t.replace('.','')

    if len(m) == 0: m = r'.*'
    if len(t) == 0: t = r'.*'

Sylvain Coulange's avatar
Sylvain Coulange committed
346
    result = {}
347

Sylvain Coulange's avatar
Sylvain Coulange committed
348
349
    mc1 = r'.*'
    mc2 = r'.*'
350
    if mc == 'startsBy' or mc == 'equalsTo':
Sylvain Coulange's avatar
Sylvain Coulange committed
351
        mc1 = r'^'
352
    if mc == 'endsBy' or mc == 'equalsTo':
Sylvain Coulange's avatar
Sylvain Coulange committed
353
354
355
356
        mc2 = r'$'
    
    tc1 = r'.*'
    tc2 = r'.*'
357
    if tc == 'startsBy' or tc == 'equalsTo':
Sylvain Coulange's avatar
Sylvain Coulange committed
358
        tc1 = r'^'
359
    if tc == 'endsBy' or tc == 'equalsTo':
Sylvain Coulange's avatar
Sylvain Coulange committed
360
361
        tc2 = r'$'

Sylvain Coulange's avatar
Sylvain Coulange committed
362
363
364
365
366
367
368
369
    # for entree, infos in word2trans.items():
    #     if re.match(mc1+m+mc2,entree):
    #         transOK = False
    #         for i,trans in enumerate(infos['t']):
    #             if re.match(tc1+t+tc2,trans['t'].replace('.','')):
    #                 transOK = True
    #         if transOK: result[entree] = infos['t']

370
371
372
    # Requêter directement MongoDB et envoyer l'ensemble des résultats (catégories, traductions... compris)
    limite = 999999 # limite à 999999
    cpt = 0
Sylvain Coulange's avatar
Sylvain Coulange committed
373
374
    for entree in dico.find({'w': {"$regex": mc1+m+mc2}}):
        transOK = False
375
376
377
378
379
380
        if t != r'.*':
            for i,trans in enumerate(entree['t']):
                if re.match(tc1+t+tc2,trans['tt'].replace('.','')):
                    transOK = True
        else:
            transOK = True
Sylvain Coulange's avatar
Sylvain Coulange committed
381
        if transOK:
382
383
384
385
386
387
            cpt+=1
            if cpt<=limite:
                result[entree['w']] = {}
                for i, j in entree.items():
                    if i != "_id":
                        result[entree['w']][i] = j
388
    return sorted(result.items(), key=lambda M: locale.strxfrm(M[0])) # mise dans l'ordre alphabétique français (ex. é après e, et pas après z)
Sylvain Coulange's avatar
Sylvain Coulange committed
389

Sylvain Coulange's avatar
Sylvain Coulange committed
390
391
def modifEntry(user,mot,infos,lang):
    if lang == "fr": 
Sylvain Coulange's avatar
Sylvain Coulange committed
392
        word2trans = word2transFr
Sylvain Coulange's avatar
Sylvain Coulange committed
393
394
395
396
397
398
399
        dico = dicoFr
    if lang == "en": 
        word2trans = word2transEn
        dico = dicoEn
    if lang == "zh": 
        word2trans = word2transZh
        dico = dicoZh
400

Sylvain Coulange's avatar
Sylvain Coulange committed
401
402
403
404
    oldInfos = dico.find_one({'w':mot})
    
    dico.update({"w":mot}, {"$set": infos})
    word2trans[mot]['t'] = infos['t']
405

Sylvain Coulange's avatar
Sylvain Coulange committed
406
407
408
409
    newlog = writeLog(Type="MODIF", user=user, mot=mot, oldMot=oldInfos, newMot=infos, lang=lang)
    print("Modification du dictionnaire par",user,": lang =",lang,"; mot =",mot,"; oldMot =",oldInfos,"; newMot =",infos)
    print("ICIIII newlog:",newlog)
    return {"msg":"Modification effectuée avec succès !", "newlog":newlog}
410

Sylvain Coulange's avatar
Sylvain Coulange committed
411
def addEntry(user,mot,trans,lang):
Sylvain Coulange's avatar
Sylvain Coulange committed
412
    if lang == "fr": 
Sylvain Coulange's avatar
Sylvain Coulange committed
413
        word2trans = word2transFr
Sylvain Coulange's avatar
Sylvain Coulange committed
414
        dico = dicoFr
415
        trans = trans.replace('g','ɡ')
Sylvain Coulange's avatar
Sylvain Coulange committed
416
417
        trans = trans.replace('r','ʁ')
    if lang == "en": 
Sylvain Coulange's avatar
Sylvain Coulange committed
418
        word2trans = word2transEn
Sylvain Coulange's avatar
Sylvain Coulange committed
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
        dico = dicoEn
        trans = trans.replace('g','ɡ')
    if lang == "zh": 
        word2trans = word2transZh
        dico = dicoZh

    mot = mot.lower()
    mot = mot.strip()
    transList = trans.split(',')

    for ind,i in enumerate(transList):
        transList[ind] = i.strip()

    if mot not in word2trans.keys():
        newMot = {'t': []}
        for t in transList:
            if len(t)>0:
                if lang =="fr":
                    newMot['t'].append({ 'tt':t, 'tr':['FR']})
                elif lang =="zh":
                    newMot['t'].append({ 'tt':t, 'tr':['CN']})
                else:
                    newMot['t'].append({ 'tt':t, 'tr':[]})

        if len(newMot['t'])>0:
            word2trans[mot] = newMot
            dico.insert_one({ 'w':mot, 't':newMot['t']})
            newlog = writeLog(Type="ADD", user=user, mot=mot, oldMot="", newMot=transList, lang=lang)
            return {"msg":"Ajout effectué avec succès ! Merci pour votre participation !", "newlog":newlog}
        else:
            return {"msg":"Transcription vide. Veuillez indiquer au moins une transcriptions phonétiques. Ajout annulé."}
    else:
        return {"msg":"Ce mot est déjà dans le dictionnaire !"}
452

Sylvain Coulange's avatar
Sylvain Coulange committed
453
def delEntry(user,mot,lang):
Sylvain Coulange's avatar
Sylvain Coulange committed
454
    if lang == "fr": 
Sylvain Coulange's avatar
Sylvain Coulange committed
455
        word2trans = word2transFr
Sylvain Coulange's avatar
Sylvain Coulange committed
456
457
        dico = dicoFr
    if lang == "en": 
Sylvain Coulange's avatar
Sylvain Coulange committed
458
        word2trans = word2transEn
Sylvain Coulange's avatar
Sylvain Coulange committed
459
460
461
462
463
464
465
466
467
468
469
470
471
        dico = dicoEn
    if lang == "zh": 
        word2trans = word2transZh
        dico = dicoZh
    
    if mot in word2trans.keys():
        oldmot = word2trans[mot]
        word2trans.pop(mot)
        dico.delete_one({'w':mot})
        newlog = writeLog(Type="DEL", user=user, mot=mot, oldMot=oldmot, newMot="",lang=lang)
        print("Modification du dictionnaire par",user,": suppression de mot =",mot)
    
        return {"msg":"Suppression effectuée avec succès.", "newlog":newlog}
472
473


Sylvain Coulange's avatar
Sylvain Coulange committed
474
def sendMeLogPlease(lang):
Sylvain Coulange's avatar
Sylvain Coulange committed
475
    if lang == "fr":
Sylvain Coulange's avatar
Sylvain Coulange committed
476
        logDic = dicoFrLogs
Sylvain Coulange's avatar
Sylvain Coulange committed
477
    elif lang == "en":
Sylvain Coulange's avatar
Sylvain Coulange committed
478
479
480
        logDic = dicoEnLogs
    elif lang == "zh":
        logDic = dicoZhLogs
481
    
Sylvain Coulange's avatar
Sylvain Coulange committed
482
483
484
    rep = []
    for log in logDic.find():
        rep.append(noIdDict(log))
Sylvain Coulange's avatar
Sylvain Coulange committed
485

Sylvain Coulange's avatar
Sylvain Coulange committed
486
    return rep
487

Sylvain Coulange's avatar
Sylvain Coulange committed
488
489
490
491
492
493
494
495
def noIdDict(dic):
    if type(dic) is dict:
        # renvoit un dic sans la clé "_id"
        return { i:j for i,j in dic.items() if i!='_id' }
    else:
        return dic

def writeLog(Type,user,mot,oldMot,newMot,lang):
Sylvain Coulange's avatar
Sylvain Coulange committed
496
    if lang == "fr":
Sylvain Coulange's avatar
Sylvain Coulange committed
497
        logDic = dicoFrLogs
Sylvain Coulange's avatar
Sylvain Coulange committed
498
    elif lang == "en":
Sylvain Coulange's avatar
Sylvain Coulange committed
499
500
501
        logDic = dicoEnLogs
    elif lang == "zh":
        logDic = dicoZhLogs
Sylvain Coulange's avatar
Sylvain Coulange committed
502

Sylvain Coulange's avatar
Sylvain Coulange committed
503
504
    newlog = {
        "date":datetime.datetime.now(),
505
        "user":user,
Sylvain Coulange's avatar
Sylvain Coulange committed
506
507
508
509
510
511
        "word":mot,
        "old":noIdDict(oldMot),
        "new":noIdDict(newMot),
        "type":Type
    }
    logDic.insert_one(newlog)
512
    
Sylvain Coulange's avatar
Sylvain Coulange committed
513
514
    print("New log: lang={} ; user={} ; word={} ; type={}".format(lang,user,mot,Type))
    return noIdDict(newlog)