2 # -*- coding: utf-8 -*-
3 #Author: Pierre Ratinaud
4 #Copyright (c) 2008-2012 Pierre Ratinaud
9 from ConfigParser import ConfigParser
10 from subprocess import Popen, call, PIPE
22 from shutil import copyfile
24 #from dialog import BugDialog
27 log = logging.getLogger('iramuteq')
30 indices_simi = [u'cooccurrence' ,'pourcentage de cooccurrence',u'Russel',u'Jaccard', 'Kulczynski1', 'Kulczynski2', 'Mountford', 'Fager', 'simple matching', 'Hamman', 'Faith', 'Tanimoto', 'Dice', 'Phi', 'Stiles', 'Michael', 'Mozley', 'Yule', 'Yule2', 'Ochiai', 'Simpson', 'Braun-Blanquet','Chi-squared', 'Phi-squared', 'Tschuprow', 'Cramer', 'Pearson', 'binomial']
34 def __init__(self, path = None, encoding = 'utf8'):
37 self.encoding = encoding
39 def __getitem__(self, key):
43 with codecs.open(path, 'r', self.encoding) as f :
45 tgen = [line.split('\t') for line in tgen.splitlines()]
46 tgen = dict([[line[0], line[1:]] for line in tgen])
50 def write(self, path = None):
53 with open(path, 'w') as f :
54 f.write('\n'.join(['\t'.join([val] + self.tgen[val]) for val in self.tgen]))
56 def writetable(self, pathout, tgens, totocc):
57 etoiles = totocc.keys()
58 with open(pathout, 'w') as f :
59 line = '\t'.join([u'tgens'] + etoiles) + '\n'
60 f.write(line.encode(self.encoding))
62 line = '\t'.join([t] + [`tgens[t][et]` for et in etoiles]) + '\n'
63 f.write(line.encode(self.encoding))
66 while totname + `i` in tgens :
68 totname = totname + `i`
69 line = '\t'.join([totname] + [`totocc[et]` for et in etoiles])
70 f.write(line.encode(self.encoding))
73 def __init__(self, filein, syscoding = 'utf8') :
75 self.syscoding = syscoding
77 self.openedcorpus = {}
78 self.openedmatrix = {}
86 d = shelve.open(self.filein)
87 self.history = d.get('history', [])
88 self.matrix = d.get('matrix', [])
89 self.ordercorpus = dict([[corpus['uuid'], i] for i, corpus in enumerate(self.history)])
90 self.corpus = dict([[corpus['uuid'], corpus] for corpus in self.history])
91 self.analyses = dict([[analyse['uuid'], analyse] for corpus in self.history for analyse in corpus.get('analyses', [])])
92 self.matrixanalyse = dict([[mat['uuid'], mat] for mat in self.matrix])
93 self.ordermatrix = dict([[matrix['uuid'], i] for i, matrix in enumerate(self.matrix)])
97 d = shelve.open(self.filein)
98 d['history'] = self.history
99 d['matrix'] = self.matrix
102 def add(self, analyse) :
103 log.info('add to history %s' % analyse.get('corpus_name', 'pas un corpus'))
104 tosave = {'uuid' : analyse['uuid'], 'ira': analyse['ira'], 'type' : analyse['type']}
105 if analyse.get('corpus', False) :
106 if analyse['uuid'] in self.analyses :
108 tosave['corpus'] = analyse['corpus']
109 tosave['name'] = analyse['name']
110 acorpus_uuid = analyse['corpus']
111 if acorpus_uuid in self.corpus :
112 if 'analyses' in self.history[self.ordercorpus[acorpus_uuid]] :
113 self.history[self.ordercorpus[acorpus_uuid]]['analyses'].append(tosave)
115 self.history[self.ordercorpus[acorpus_uuid]]['analyses'] = [tosave]
117 self.orph.append(tosave)
119 tosave['corpus_name'] = analyse['corpus_name']
120 self.history.append(tosave)
124 def addMatrix(self, analyse) :
126 #tosave['matrix_name'] = analyse['matrix_name']
127 tosave['analyses'] = []
128 self.matrix.append(tosave)
132 def addMatrixAnalyse(self, analyse) :
133 tosave = {'uuid' : analyse['uuid'], 'ira': analyse['ira'], 'type' : analyse['type'], 'matrix' : analyse['matrix']}
134 tosave['name'] = analyse['name']
135 if tosave['matrix'] in self.ordermatrix :
136 self.matrix[self.ordermatrix[tosave['matrix']]]['analyses'].append(tosave)
140 def addmultiple(self, analyses) :
141 log.info('add multiple')
142 for analyse in analyses :
143 tosave = {'uuid' : analyse['uuid'], 'ira': analyse['ira'], 'type' : analyse['type']}
144 corpus = analyse['corpus']
145 tosave['corpus'] = corpus
146 tosave['name'] = analyse['name']
147 if corpus in self.corpus :
148 if 'analyses' in self.history[self.ordercorpus[corpus]] :
149 self.history[self.ordercorpus[corpus]]['analyses'].append(tosave)
151 self.history[self.ordercorpus[corpus]]['analyses'] = [tosave]
155 def delete(self, analyse, corpus = False) :
156 log.info('delete %s' % analyse.get('name', 'noname'))
158 self.history.pop(self.ordercorpus[analyse['uuid']])
159 if analyse['uuid'] in self.openedcorpus :
160 del self.openedcorpus[analyse['uuid']]
161 elif analyse['uuid'] in self.analyses :
162 todel = [i for i, ana in enumerate(self.corpus[analyse['corpus']]['analyses']) if ana['uuid'] == analyse['uuid']][0]
163 self.history[self.ordercorpus[analyse['corpus']]]['analyses'].pop(todel)
164 elif analyse['uuid'] in self.matrixanalyse :
165 self.matrix = [mat for mat in self.matrix if mat['uuid'] != analyse['uuid']]
169 def addtab(self, analyse) :
170 self.opened[analyse['uuid']] = analyse
172 def rmtab(self, analyse) :
173 del self.opened[analyse['uuid']]
176 corpustodel = [corpus for corpus in self.history if not os.path.exists(corpus['ira'])]
178 for corpus in corpustodel :
179 print 'cleaning :', corpus['corpus_name']
180 self.delete(corpus, corpus = True)
181 anatodel = [analyse for corpus in self.history for analyse in corpus.get('analyses', []) if not os.path.exists(analyse.get('ira', '/'))]
182 for analyse in anatodel :
183 print 'cleaning :', analyse['name']
187 return str(self.history)
190 def __init__(self, configfile=None, diff = None, parametres = None) :
191 self.configfile = configfile
192 self.conf = ConfigParser()
193 if configfile is not None :
194 self.conf.readfp(codecs.open(configfile, 'r', 'utf8'))
196 if parametres is not None :
197 self.doparametres(parametres)
199 def doparametres(self, parametres) :
202 def getsections(self) :
203 return self.conf.sections()
205 def getoptions(self, section = None, diff = None):
208 section = self.conf.sections()[0]
209 for option in self.conf.options(section) :
210 if self.conf.get(section, option).isdigit() :
211 parametres[option] = int(self.conf.get(section, option))
212 elif self.conf.get(section, option) == 'False' :
213 parametres[option] = False
214 elif self.conf.get(section, option) == 'True' :
215 parametres[option] = True
216 elif self.conf.get(section, option).startswith('(') and self.conf.get(section, option).endswith(')') :
217 parametres[option] = ast.literal_eval(self.conf.get(section, option))
218 elif self.conf.get(section, option).startswith('[') and self.conf.get(section, option).endswith(']') :
219 parametres[option] = ast.literal_eval(self.conf.get(section, option))
221 parametres[option] = self.conf.get(section, option)
222 if 'type' not in parametres :
223 parametres['type'] = section
226 def makeoptions(self, sections, parametres, outfile = None) :
228 for i, section in enumerate(sections) :
229 txt += '[%s]\n' % section
230 if not self.conf.has_section(section) :
231 self.conf.add_section(section)
232 for option in parametres[i] :
233 if isinstance(parametres[i][option], int) :
234 self.conf.set(section, option, `parametres[i][option]`)
235 txt += '%s = %i\n' % (option, parametres[i][option])
236 elif isinstance(parametres[i][option], basestring) :
237 self.conf.set(section, option, parametres[i][option].encode('utf8'))
238 txt += '%s = %s\n' % (option, parametres[i][option])
239 elif isinstance(parametres[i][option], wx.Colour) :
240 self.conf.set(section, option, str(parametres[i][option]))
241 txt += '%s = %s\n' % (option, str(parametres[i][option]))
242 elif option == 'analyses' :
245 self.conf.set(section, option, `parametres[i][option]`)
246 txt += '%s = %s\n' % (option, `parametres[i][option]`)
248 outfile = self.configfile
249 with codecs.open(outfile, 'w', 'utf8') as f :
253 def totext(self, parametres) :
256 for val in parametres :
257 if isinstance(parametres[val], int) :
258 txt.append(' \t\t: '.join([val, `parametres[val]`]))
259 elif isinstance(parametres[val], basestring) :
260 txt.append(' \t\t: '.join([val, parametres[val]]))
261 elif val in ['listet', 'stars'] :
264 txt.append(' \t\t: '.join([val, `parametres[val]`]))
265 return '\n'.join(txt)
268 def write_tab(tab, fileout) :
269 writer = csv.writer(open(fileout, 'wb'), delimiter=';', quoting = csv.QUOTE_NONNUMERIC)
270 writer.writerows(tab)
272 class BugDialog(wx.Dialog):
273 def __init__(self, *args, **kwds):
274 # begin wxGlade: MyDialog.__init__
275 kwds["style"] = wx.DEFAULT_DIALOG_STYLE
276 kwds["size"] = wx.Size(500, 200)
277 wx.Dialog.__init__(self, *args, **kwds)
278 self.SetTitle(kwds['title'])
279 self.text_ctrl_1 = wx.TextCtrl(self, -1, "", style=wx.TE_MULTILINE)
280 self.text_ctrl_1.SetBackgroundColour('#DDE8EB')
281 self.button_1 = wx.Button(self, wx.ID_OK, "")
283 self.__set_properties()
287 def __set_properties(self):
288 # begin wxGlade: MyDialog.__set_properties
289 self.SetMinSize(wx.Size(500, 200))
290 self.text_ctrl_1.SetMinSize(wx.Size(500, 200))
294 def __do_layout(self):
295 # begin wxGlade: MyDialog.__do_layout
296 sizer_1 = wx.BoxSizer(wx.VERTICAL)
297 sizer_1.Add(self.text_ctrl_1, 1, wx.EXPAND, 0)
298 sizer_1.Add(self.button_1, 0, wx.ALIGN_CENTER_HORIZONTAL, 0)
299 self.SetSizer(sizer_1)
304 def CreateIraFile(DictPathOut, clusternb, corpname='corpus_name', section = 'analyse'):
305 AnalyseConf = ConfigParser()
306 AnalyseConf.read(DictPathOut['ira'])
307 AnalyseConf.add_section(section)
308 date = datetime.datetime.now().ctime()
309 AnalyseConf.set(section, 'date', str(date))
310 AnalyseConf.set(section, 'clusternb', clusternb)
311 AnalyseConf.set(section, 'corpus_name', corpname)
313 fileout = open(DictPathOut['ira'], 'w')
314 AnalyseConf.write(fileout)
317 def sortedby(list, direct, *indices):
320 sortedby: sort a list of lists (e.g. a table) by one or more indices
321 (columns of the table) and return the sorted list
324 for list = [[2,3],[1,2],[3,1]]:
325 sortedby(list,1) will return [[3, 1], [1, 2], [2, 3]],
326 sortedby(list,0) will return [[1, 2], [2, 3], [3, 1]]
329 nlist = map(lambda x, indices=indices:
330 map(lambda i, x=x: x[i], indices) + [x],
335 nlist.sort(reverse=True)
336 return map(lambda l: l[-1], nlist)
338 def add_type(line, dictlem):
339 if line[4] in dictlem:
340 line.append(dictlem[line[4]])
345 def treat_line_alceste(i, line) :
346 if line[0] == '*' or line[0] == '*****' :
351 elif float(line[5].replace(',', '.')) < 0.0001:
353 elif float(line[5].replace(',', '.')) > 0.05:
354 line[5] = 'NS (%s)' % str(float(line[5].replace(',', '.')))[0:7]
356 line[5] = str(float(line[5].replace(',', '.')))[0:7]
357 return [i, int(line[0]), int(line[1]), float(line[2]), float(line[3]), line[6], line[4], line[5]]
359 def ReadProfileAsDico(File, Alceste=False, encoding = sys.getdefaultencoding()):
360 #print 'lecture des profils : ReadProfileAsDico'
362 # print 'lecture du dictionnaire de type'
364 # for line in parent.corpus.lem_type_list :
365 # dictlem[line[0]] = line[1]
367 print 'lecture des profiles'
368 #encoding = sys.getdefaultencoding()
369 FileReader = codecs.open(File, 'r', encoding)
370 Filecontent = FileReader.readlines()
374 #rows = [row.replace('\n', '').replace("'", '').replace('\"', '').replace(',', '.').replace('\r','').split(';') for row in Filecontent]
375 rows = [row.replace('\n', '').replace("'", '').replace('\"', '').replace('\r','').split(';') for row in Filecontent]
377 ClusterNb = rows[0][2]
379 clusters = [row[2] for row in rows if row[0] == u'**']
380 valclusters = [row[1:4] for row in rows if row[0] == u'****']
381 lp = [i for i, line in enumerate(rows) if line[0] == u'****']
382 prof = [rows[lp[i] + 1:lp[i+1] - 1] for i in range(0, len(lp)-1)] + [rows[lp[-1] + 1:len(rows)]]
384 prof = [[add_type(row, dictlem) for row in pr] for pr in prof]
385 prof = [[treat_line_alceste(i,line) for i, line in enumerate(pr)] for pr in prof]
387 prof = [[line + [''] for line in pr] for pr in prof]
388 prof = [[treat_line_alceste(i,line) for i, line in enumerate(pr)] for pr in prof]
389 for i, cluster in enumerate(clusters):
390 DictProfile[cluster] = [valclusters[i]] + prof[i]
393 def GetTxtProfile(dictprofile, cluster_size) :
395 for classe in range(0, len(dictprofile)) :
396 prof = dictprofile[str(classe + 1)]
397 clinfo = cluster_size[classe]
398 proflist.append('\n'.join([' '.join(['classe %i' % (classe + 1), '-', '%s uce sur %s - %s%%' % (clinfo[0], clinfo[1], clinfo[2])]), '\n'.join(['%5s|%5s|%6s|%6s|%8s|%8s|%20s\t%10s' % tuple([str(val) for val in line]) for line in prof if len(line)==8])]))
399 return '\n\n'.join(proflist)
401 def formatExceptionInfo(maxTBlevel=5):
402 cla, exc, trbk = sys.exc_info()
404 excName = cla.__name__
408 excArgs = exc.args[0]
410 excArgs = "<no args>"
411 excTb = traceback.format_tb(trbk, maxTBlevel)
412 return (excName, excArgs, excTb)
415 #fonction des etudiants de l'iut
416 def decoupercharact(chaine, longueur, longueurOptimale, separateurs = None) :
418 on part du dernier caractère, et on recule jusqu'au début de la chaîne.
419 Si on trouve un '$', c'est fini.
420 Sinon, on cherche le meilleur candidat. C'est-Ã -dire le rapport poids/distance le plus important.
422 separateurs = [[u'.', 60.0], [u'?', 60.0], [u'!', 60.0], [u'£$£', 60], [u':', 50.0], [u';', 40.0], [u',', 10.0], [u' ', 0.1]]
423 trouve = False # si on a trouvé un bon séparateur
424 iDecoupe = 0 # indice du caractere ou il faut decouper
426 # on découpe la chaine pour avoir au maximum 240 caractères
427 longueur = min(longueur, len(chaine) - 1)
428 chaineTravail = chaine[:longueur + 1]
430 meilleur = ['', 0, 0] # type, poids et position du meilleur separateur
432 # on vérifie si on ne trouve pas un '$'
433 indice = chaineTravail.find(u'$')
438 # si on ne trouve rien, on cherche le meilleur séparateur
441 caractere = chaineTravail[nbCar]
442 distance = abs(longueurOptimale - nbCar) + 1
443 meilleureDistance = abs(longueurOptimale - meilleur[2]) + 1
445 # on vérifie si le caractére courant est une marque de ponctuation
446 for s in separateurs:
447 if caractere == s[0]:
448 # si c'est une ponctuation
450 if s[1] / distance > float(meilleur[1]) / meilleureDistance:
458 # et on termine la recherche
461 # on passe au caractère précédant
466 fin = chaine[iDecoupe + 1:]
467 retour = chaineTravail[:iDecoupe]
468 return len(retour) > 0, retour.split(), fin
469 # si on a rien trouvé
470 return False, chaine.split(), ''
473 exceptions = {'paragrapheOT' : u"Un problème de formatage (présence d'un marqueur de paragraphe (-*) en dehors d'un texte) est survenu à la ligne ",
474 'EmptyText' : u"Texte vide (probablement un problème de formatage du corpus). Le problème est apparu à la ligne ",
475 'CorpusEncoding' : u"Problème d'encodage.",
476 'TextBeforeTextMark' : u"Problème de formatage : du texte avant le premier marqueur de texte (****). Le problème est survenu à la ligne ",
479 def BugReport(parent, error = None):
480 for ch in parent.GetChildren():
481 if "<class 'wx._windows.ProgressDialog'>" == str(type(ch)):
483 excName, exc, excTb = formatExceptionInfo()
484 if excName == 'Exception' :
486 if len(exc.split()) == 2 :
487 mss, linenb = exc.split()
488 if mss in exceptions :
489 txt = exceptions[mss] + linenb
493 if exc in exceptions :
494 txt = exceptions[exc]
497 title = "Information"
499 txt = u' !== BUG ==! \n'
500 txt += u'*************************************\n'
501 txt += '\n'.join(excTb).replace(' ', ' ')
502 txt += excName + '\n'
506 dial = BugDialog(parent, **{'title' : title})
507 if 'Rerror' in dir(parent) :
511 dial.text_ctrl_1.write(txt)
512 dial.CenterOnParent()
516 def PlaySound(parent):
517 if parent.pref.getboolean('iramuteq', 'sound') :
519 if "gtk2" in wx.PlatformInfo:
520 error = Popen(['aplay','-q',os.path.join(parent.AppliPath,'son_fin.wav')])
522 sound = wx.Sound(os.path.join(parent.AppliPath, 'son_fin.wav'))
523 sound.Play(wx.SOUND_SYNC)
527 def ReadDicoAsDico(dicopath):
528 with codecs.open(dicopath, 'r', 'UTF8') as f:
529 content = f.readlines()
530 lines = [line.rstrip('\n\r').replace(u'\n', '').replace('"', '').split('\t') for line in content if line != u'']
531 return dict([[line[0], line[1:]] for line in lines])
533 def ReadLexique(parent, lang = 'french', filein = None):
536 parent.lexique = ReadDicoAsDico(parent.DictPath.get(lang, 'french'))
538 parent.lexique = ReadDicoAsDico(filein)
542 def ReadList(filein, encoding = sys.getdefaultencoding(), sep = ';'):
544 with codecs.open(filein, 'r', encoding) as f :
546 content = [line.replace('\n', '').replace('\r','').replace('\"', '').replace(',', '.').split(sep) for line in content.splitlines()]
547 #file = codecs.open(filein, 'r', encoding)
548 #content = file.readlines()
550 first = content.pop(0)
551 #first = first.replace('\n', '').replace('\r','').replace('\"', '').split(sep)
555 #line = line.replace('\n', '').replace('\r','').replace('\"', '').replace(',', '.')
556 #line = line.split(';')
565 don = float('%.5f' % float(val))
571 def exec_RCMD(rpath, command) :
572 log.info('R CMD INSTALL %s' % command)
573 rpath = rpath.replace('\\','\\\\')
574 error = call(["%s" % rpath, 'CMD', 'INSTALL', "%s" % command])
577 def exec_rcode(rpath, rcode, wait = True, graph = False):
578 log.info("R Script : %s" % rcode)
580 if sys.platform == 'darwin' :
582 macversion = platform.mac_ver()[0].split('.')
583 if int(macversion[1]) < 5 :
590 rpath = rpath.replace('\\','\\\\')
591 env = os.environ.copy()
592 if sys.platform == 'darwin' and 'LC_ALL' not in env:
593 env['LC_ALL'] = 'en_US.UTF-8'
596 if sys.platform == 'win32':
597 error = call(["%s" % rpath, "--vanilla","--slave","-f", "%s" % rcode])
599 error = call([rpath, '--slave', "--vanilla", "-f %s" % rcode, "--encoding=UTF-8"], env = env)
602 if sys.platform == 'win32':
603 pid = Popen(["%s" % rpath, '--vanilla','--slave','-f', "%s" % rcode])
605 pid = Popen([rpath, '--slave', "--vanilla", "-f %s" % rcode, "--encoding=UTF-8"], stderr = PIPE, env = env)
609 if sys.platform == 'win32':
610 error = call(["%s" % rpath, '--vanilla','--slave','-f', "%s" % rcode])
611 elif sys.platform == 'darwin' and needX11:
612 os.environ['DISPLAY'] = ':0.0'
613 error = call([rpath, '--vanilla','--slave',"-f %s" % rcode, "--encoding=UTF-8"], env = env)
615 error = call([rpath, '--vanilla','--slave',"-f %s" % rcode, "--encoding=UTF-8"], env = env)
618 if sys.platform == 'win32':
619 pid = Popen(["%s" % rpath, '--vanilla','--slave','-f', "%s" % rcode])
620 elif sys.platform == 'darwin' and needX11:
621 os.environ['DISPLAY'] = ':0.0'
622 pid = Popen([rpath, '--vanilla','--slave',"-f %s" % rcode, "--encoding=UTF-8"], stderr = PIPE, env = env)
624 pid = Popen([rpath, '--vanilla','--slave',"-f %s" % rcode, "--encoding=UTF-8"], stderr = PIPE, env = env)
627 def check_Rresult(parent, pid) :
628 if isinstance(pid, Popen) :
629 if pid.returncode != 0 :
630 error = pid.communicate()
631 error = [str(error[0]), error[1]]
632 if error[1] is None :
634 parent.Rerror = '\n'.join([str(pid.returncode), '\n'.join(error)])
636 raise Exception('\n'.join([u'Erreur R', '\n'.join(error[1:])]))
645 raise Exception(u'Erreur R')
652 def print_liste(filename,liste):
653 with open(filename,'w') as f :
655 f.write(';'.join(graph)+'\n')
657 def read_list_file(filename, encoding = sys.getdefaultencoding()):
658 with codecs.open(filename,'rU', encoding) as f :
659 content=f.readlines()
660 ncontent=[line.replace('\n','').split(';') for line in content if line.strip() != '']
663 class MessageImage(wx.Frame):
664 def __init__(self, parent,title, size):
665 wx.Frame.__init__ ( self, parent, id = wx.ID_ANY, title = title, pos = wx.DefaultPosition, size = size, style = wx.DEFAULT_FRAME_STYLE )
666 self.SetSizeHintsSz( wx.DefaultSize, wx.DefaultSize )
667 self.imageFile = False
668 self.imagename = u"chi_classe.png"
669 self.HtmlPage = wx.html.HtmlWindow(self, -1)
670 self.HtmlPage.SetMinSize(size)
671 if "gtk2" in wx.PlatformInfo:
672 self.HtmlPage.SetStandardFonts()
673 self.HtmlPage.SetFonts('Courier', 'Courier')
675 self.button_1 = wx.Button(self, wx.ID_CANCEL)
676 self.button_2 = wx.Button(self, wx.ID_SAVE)
677 self.Bind(wx.EVT_BUTTON, self.OnCloseMe, self.button_1)
678 self.Bind(wx.EVT_BUTTON, self.OnSaveImage, self.button_2)
682 self.sizer_1 = wx.BoxSizer(wx.VERTICAL)
683 self.sizer_2 = wx.BoxSizer(wx.HORIZONTAL)
684 self.sizer_1.Add(self.HtmlPage, 2, wx.EXPAND, 0)
686 self.m_sdbSizer1 = wx.StdDialogButtonSizer()
687 self.m_sdbSizer1.AddButton( self.button_2 )
688 self.m_sdbSizer1.AddButton( self.button_1 )
689 self.m_sdbSizer1.Realize()
690 self.sizer_1.Add(self.m_sdbSizer1, 0, wx.EXPAND, 5)
691 self.SetSizer(self.sizer_1)
693 self.sizer_1.Fit( self )
695 def addsaveimage(self, imageFile) :
696 self.imageFile = imageFile
698 def OnCloseMe(self, event):
701 def OnSaveImage(self, event) :
703 self, message="Enregistrer sous...", defaultDir=os.getcwd(),
704 defaultFile= self.imagename, wildcard="png|*.png", style=wx.SAVE | wx.OVERWRITE_PROMPT
706 dlg.SetFilterIndex(2)
708 if dlg.ShowModal() == wx.ID_OK:
710 copyfile(self.imageFile, path)
713 def progressbar(self, maxi) :
714 if 'parent' in dir(self) :
718 return wx.ProgressDialog("Traitements",
719 "Veuillez patienter...",
722 style=wx.PD_APP_MODAL | wx.PD_AUTO_HIDE | wx.PD_ELAPSED_TIME | wx.PD_CAN_ABORT
726 def treat_var_mod(variables) :
728 variables = list(set(variables))
729 varmod = [variable.split('_') for variable in variables]
730 vars = list(set([var[0] for var in varmod if len(var) >=2]))
732 mods = ['_'.join(v) for v in varmod if v[0] == var]
735 # for variable in variables :
736 # if u'_' in variable :
737 # forme = variable.split(u'_')
740 # if not var in var_mod :
741 # var_mod[var] = [variable]
743 # if not mod in var_mod[var] :
744 # var_mod[var].append(variable)
747 def doconcorde(corpus, uces, mots, uci = False) :
749 ucestxt1 = [row for row in corpus.getconcorde(uces)]
751 ucestxt1 = [row for row in corpus.getuciconcorde(uces)]
752 ucestxt1 = dict(ucestxt1)
755 listmot = [corpus.getlems()[lem].formes for lem in mots]
756 listmot = [corpus.getforme(fid).forme for lem in listmot for fid in lem]
757 mothtml = ['<font color=red><b>%s</b></font>' % mot for mot in listmot]
758 dmots = dict(zip(listmot, mothtml))
760 ucetxt = ucestxt1[uce].split()
761 ucetxt = ' '.join([dmots.get(mot, mot) for mot in ucetxt])
763 ucis_txt.append('<p><b>' + ' '.join(corpus.ucis[corpus.getucefromid(uce).uci].etoiles) + '</b></p>')
765 ucis_txt.append('<p><b>' + ' '.join(corpus.ucis[uce].etoiles) + '</b></p>')
766 ucestxt.append(ucetxt)
767 return ucis_txt, ucestxt
770 def getallstcarac(corpus, analyse) :
771 pathout = PathOut(analyse['ira'])
772 profils = ReadProfileAsDico(pathout['PROFILE_OUT'], Alceste, self.encoding)