translation
[iramuteq] / functions.py
index cef90ca..6373176 100644 (file)
@@ -30,6 +30,15 @@ log = logging.getLogger('iramuteq')
 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']
 
 
+def normpath_win32(path) :
+    if not sys.platform == 'win32' :
+        return path
+    while '\\\\' in path :
+        path = path.replace('\\\\', '\\')
+    if path.startswith('\\') and not path.startswith('\\\\') :
+        path = '\\' + path
+    return path
+
 class TGen :
     def __init__(self, path = None, encoding = 'utf8'):
         self.path = path
@@ -39,7 +48,9 @@ class TGen :
     def __getitem__(self, key):
         return self.tgen[key]
     
-    def read(self, path):
+    def read(self, path = None):
+        if path is None :
+            path = self.path
         with codecs.open(path, 'r', self.encoding) as f :
             tgen = f.read()
         tgen = [line.split('\t') for line in tgen.splitlines()]
@@ -51,10 +62,11 @@ class TGen :
         if path is None :
             path = self.path
         with open(path, 'w') as f :
-            f.write('\n'.join(['\t'.join([val] + self.tgen[val]) for val in self.tgen]))
+            f.write('\n'.join(['\t'.join([val] + self.tgen[val]) for val in self.tgen]).encode(self.encoding))
     
     def writetable(self, pathout, tgens, totocc):
         etoiles = totocc.keys()
+        etoiles.sort()
         with open(pathout, 'w') as f :
             line = '\t'.join([u'tgens'] + etoiles) + '\n'
             f.write(line.encode(self.encoding))
@@ -66,14 +78,14 @@ class TGen :
             while totname + `i` in tgens :
                 i += 1
             totname = totname + `i`
-            line = '\t'.join([totname] + [`totocc[et]` for et in etoiles])
+            line = '\t'.join([totname] + [`totocc[et]` for et in etoiles]) + '\n'
             f.write(line.encode(self.encoding))
 
 class History :
     def __init__(self, filein, syscoding = 'utf8') :
         self.filein = filein
         self.syscoding = syscoding
-        self.corpora = {}
+        self.corpus = {}
         self.openedcorpus = {}
         self.openedmatrix = {}
         self.orph = []
@@ -102,6 +114,9 @@ class History :
     def add(self, analyse) :
         log.info('add to history %s' % analyse.get('corpus_name', 'pas un corpus'))
         tosave = {'uuid' : analyse['uuid'], 'ira': analyse['ira'], 'type' : analyse['type']}
+        if tosave['uuid'] in self.corpus :
+            log.info('problem : this uuid is already in history : %s' % tosave['uuid'])
+            return
         if analyse.get('corpus', False) :
             if analyse['uuid'] in self.analyses :
                 return
@@ -117,6 +132,8 @@ class History :
                 self.orph.append(tosave)
         else :
             tosave['corpus_name'] = analyse['corpus_name']
+            #self.ordercorpus[tosave['uuid']] = len(history)
+            #self.corpus[tosave['uuid']] = analyse
             self.history.append(tosave)
         self.write()
         self.read()
@@ -158,6 +175,7 @@ class History :
             self.history.pop(self.ordercorpus[analyse['uuid']])
             if analyse['uuid'] in self.openedcorpus :
                 del self.openedcorpus[analyse['uuid']]
+            log.info('delete corpus : %s' % analyse['uuid'])
         elif analyse['uuid'] in self.analyses :
             todel = [i for i, ana in enumerate(self.corpus[analyse['corpus']]['analyses']) if ana['uuid'] == analyse['uuid']][0]
             self.history[self.ordercorpus[analyse['corpus']]]['analyses'].pop(todel)
@@ -171,6 +189,19 @@ class History :
 
     def rmtab(self, analyse) :
         del self.opened[analyse['uuid']]
+    
+    def update(self, analyse) :
+        if 'matrix_name' in analyse :
+            self.matrixanalyse[analyse['uuid']].update(analyse)
+        elif 'corpus_name' in analyse :
+            self.corpus[analyse['uuid']].update(analyse)
+        elif 'corpus' in analyse :
+            self.analyses[analyse['uuid']].update(analyse)
+        else :
+            toupdate = [an for an in self.matrixanalyse[analyse['matrix']]['analyses'] if an['uuid'] == analyse['uuid']]
+            toupdate[0].update(analyse)
+        self.write()
+        self.read()
 
     def clean(self) :
         corpustodel = [corpus for corpus in self.history if not os.path.exists(corpus['ira'])]
@@ -190,7 +221,9 @@ class DoConf :
     def __init__(self, configfile=None, diff = None, parametres = None) :
         self.configfile = configfile
         self.conf = ConfigParser()
+        
         if configfile is not None :
+            configfile = normpath_win32(configfile)
             self.conf.readfp(codecs.open(configfile, 'r', 'utf8'))
         self.parametres = {}
         if parametres is not None :
@@ -246,8 +279,9 @@ class DoConf :
                     txt += '%s = %s\n' % (option, `parametres[i][option]`)
         if outfile is None :
             outfile = self.configfile
-        with codecs.open(outfile, 'w', 'utf8') as f :
-            f.write(txt)
+        outfile = normpath_win32(outfile)
+        with open(outfile, 'w') as f :
+            f.write(txt.encode('utf8'))
             #self.conf.write(f)
 
     def totext(self, parametres) :
@@ -357,15 +391,8 @@ def treat_line_alceste(i, line) :
     return [i, int(line[0]), int(line[1]), float(line[2]), float(line[3]), line[6], line[4], line[5]]
 
 def ReadProfileAsDico(File, Alceste=False, encoding = sys.getdefaultencoding()):
-    #print 'lecture des profils : ReadProfileAsDico'
-    #if Alceste :
-    #    print 'lecture du dictionnaire de type'
-    #    dictlem = {}
-    #    for line in parent.corpus.lem_type_list :
-    #        dictlem[line[0]] = line[1]
     dictlem = {}
     print 'lecture des profiles'
-    #encoding = sys.getdefaultencoding()
     FileReader = codecs.open(File, 'r', encoding)
     Filecontent = FileReader.readlines()
     FileReader.close()
@@ -399,17 +426,17 @@ def GetTxtProfile(dictprofile, cluster_size) :
     return '\n\n'.join(proflist)
 
 def formatExceptionInfo(maxTBlevel=5):
-         cla, exc, trbk = sys.exc_info()
-         try :
-            excName = cla.__name__
-         except :
-            excName = 'None'
-         try:
-             excArgs = exc.args[0]
-         except :
-             excArgs = "<no args>"
-         excTb = traceback.format_tb(trbk, maxTBlevel)
-         return (excName, excArgs, excTb)
+    cla, exc, trbk = sys.exc_info()
+    try :
+        excName = cla.__name__
+    except :
+        excName = 'None'
+    try:
+        excArgs = exc.args[0]
+    except :
+        excArgs = "<no args>"
+    excTb = traceback.format_tb(trbk, maxTBlevel)
+    return (excName, excArgs, excTb)
 
 
 #fonction des etudiants de l'iut
@@ -474,6 +501,7 @@ exceptions = {'paragrapheOT' : u"Un problème de formatage (présence d'un marqu
               'EmptyText' : u"Texte vide (probablement un problème de formatage du corpus). Le problème est apparu à la ligne ",
               'CorpusEncoding' : u"Problème d'encodage.",
               'TextBeforeTextMark' : u"Problème de formatage : du texte avant le premier marqueur de texte (****). Le problème est survenu à la ligne ",
+              'MissingAnalyse' : u'Aucun fichier à cet emplacement :\n', 
 }
 
 def BugReport(parent, error = None):
@@ -500,7 +528,7 @@ def BugReport(parent, error = None):
         txt += u'*************************************\n'
         txt += '\n'.join(excTb).replace('    ', ' ')
         txt += excName + '\n'
-        txt += exc
+        txt += `exc`
         title = "Bug"
 
     dial = BugDialog(parent, **{'title' : title})
@@ -537,7 +565,10 @@ def ReadLexique(parent, lang = 'french', filein = None):
         else :
             parent.lexique = ReadDicoAsDico(filein)
     else :
-        parent.lexique = {}
+        if filein is None :
+            parent.lexique = {}
+        else :
+            parent.lexique = ReadDicoAsDico(filein)
 
 def ReadList(filein, encoding = sys.getdefaultencoding(), sep = ';'):
     #file = open(filein)
@@ -660,54 +691,7 @@ def read_list_file(filename, encoding = sys.getdefaultencoding()):
         ncontent=[line.replace('\n','').split(';') for line in content if line.strip() != '']
     return ncontent
         
-class MessageImage(wx.Frame):
-    def __init__(self, parent,title, size):
-        wx.Frame.__init__ ( self, parent, id = wx.ID_ANY, title = title, pos = wx.DefaultPosition, size = size, style = wx.DEFAULT_FRAME_STYLE )
-        self.SetSizeHintsSz( wx.DefaultSize, wx.DefaultSize )
-        self.imageFile = False
-        self.imagename = u"chi_classe.png"
-        self.HtmlPage = wx.html.HtmlWindow(self, -1)
-        self.HtmlPage.SetMinSize(size)
-        if "gtk2" in wx.PlatformInfo:
-            self.HtmlPage.SetStandardFonts()
-        self.HtmlPage.SetFonts('Courier', 'Courier')
-        
-        self.button_1 = wx.Button(self, wx.ID_CANCEL)
-        self.button_2 = wx.Button(self, wx.ID_SAVE)
-        self.Bind(wx.EVT_BUTTON, self.OnCloseMe, self.button_1)
-        self.Bind(wx.EVT_BUTTON, self.OnSaveImage, self.button_2)
-        self.do_layout()
-
-    def do_layout(self):
-        self.sizer_1 = wx.BoxSizer(wx.VERTICAL)
-        self.sizer_2 = wx.BoxSizer(wx.HORIZONTAL)
-        self.sizer_1.Add(self.HtmlPage, 2, wx.EXPAND, 0)
-
-        self.m_sdbSizer1 = wx.StdDialogButtonSizer()
-        self.m_sdbSizer1.AddButton(  self.button_2 )
-        self.m_sdbSizer1.AddButton(  self.button_1 )
-        self.m_sdbSizer1.Realize()
-        self.sizer_1.Add(self.m_sdbSizer1, 0, wx.EXPAND, 5)
-        self.SetSizer(self.sizer_1)
-        self.Layout()
-        self.sizer_1.Fit( self )
 
-    def addsaveimage(self, imageFile) :
-        self.imageFile = imageFile
-        
-    def OnCloseMe(self, event):
-        self.Destroy()
-
-    def OnSaveImage(self, event) :
-        dlg = wx.FileDialog(
-            self, message="Enregistrer sous...", defaultDir=os.getcwd(),
-            defaultFile= self.imagename, wildcard="png|*.png", style=wx.SAVE | wx.OVERWRITE_PROMPT
-            )
-        dlg.SetFilterIndex(2)
-        dlg.CenterOnParent()
-        if dlg.ShowModal() == wx.ID_OK:
-            path = dlg.GetPath()
-            copyfile(self.imageFile, path)
             
 
 def progressbar(self, maxi) :
@@ -715,6 +699,10 @@ def progressbar(self, maxi) :
         parent = self.parent
     else :
         parent = self
+    try :
+        maxi = int(maxi)
+    except :
+        maxi = 1
     return wx.ProgressDialog("Traitements",
                              "Veuillez patienter...",
                              maximum=maxi,