...
[iramuteq] / iramuteq.py
index d180525..f1dabc0 100644 (file)
@@ -5,40 +5,37 @@
 #License: GNU GPL
 
 from optparse import OptionParser
 #License: GNU GPL
 
 from optparse import OptionParser
+from wx import BusyCursor
 
 parser = OptionParser()
 parser.add_option("-f", "--file", dest="filename",
                   help="open FILE", metavar="FILE", default=False)
 (options, args) = parser.parse_args()
 
 
 parser = OptionParser()
 parser.add_option("-f", "--file", dest="filename",
                   help="open FILE", metavar="FILE", default=False)
 (options, args) = parser.parse_args()
 
-#print args
-#print options
 import sys
 reload(sys)
 import locale
 import tempfile
 import codecs
 import os
 import sys
 reload(sys)
 import locale
 import tempfile
 import codecs
 import os
-import shutil
 from random import randint
 from random import randint
-from ConfigParser import *
+from ConfigParser import ConfigParser, RawConfigParser
 import webbrowser
 import gettext
 import logging
 #------------------------------------
 import wx
 import webbrowser
 import gettext
 import logging
 #------------------------------------
 import wx
-#import wx.aui
 import wx.lib.agw.aui as aui
 import wx.html
 import wx.grid
 import wx.lib.hyperlink as hl
 #------------------------------------
 import wx.lib.agw.aui as aui
 import wx.html
 import wx.grid
 import wx.lib.hyperlink as hl
 #------------------------------------
-from functions import BugReport, PlaySound, ReadLexique, History, DoConf, ReadDicoAsDico, progressbar
+from functions import BugReport, PlaySound, History
 from checkversion import NewVersion
 from guifunct import *
 from tableau import Tableau
 from checkversion import NewVersion
 from guifunct import *
 from tableau import Tableau
-from dialog import PrefDialog, CorpusPref
-from tabfrequence import Frequences
+from dialog import PrefDialog
+from tabfrequence import Frequences, FreqMultiple
 from tabchi2 import ChiSquare
 #from tabstudent import MakeStudent
 from tabchddist import ChdCluster
 from tabchi2 import ChiSquare
 #from tabstudent import MakeStudent
 from tabchddist import ChdCluster
@@ -48,18 +45,15 @@ from tabsimi import DoSimi
 from tabrsimple import InputText
 from tabverges import Prototypical
 from tabsplitvar import SplitMatrixFromVar
 from tabrsimple import InputText
 from tabverges import Prototypical
 from tabsplitvar import SplitMatrixFromVar
-#from textafcuci import AfcUci
 from textdist import AnalysePam
 from textstat import Stat
 from textaslexico import Lexico
 from textsimi import SimiTxt, SimiFromCluster
 from textwordcloud import WordCloud, ClusterCloud
 from textreinert import Reinert
 from textdist import AnalysePam
 from textstat import Stat
 from textaslexico import Lexico
 from textsimi import SimiTxt, SimiFromCluster
 from textwordcloud import WordCloud, ClusterCloud
 from textreinert import Reinert
-#from profile_segment import ProfileSegment
 #from textcheckcorpus import checkcorpus
 from openanalyse import OpenAnalyse
 from corpus import Builder, SubBuilder
 #from textcheckcorpus import checkcorpus
 from openanalyse import OpenAnalyse
 from corpus import Builder, SubBuilder
-#from sheet import MySheet
 from checkinstall import CreateIraDirectory, CheckRPath, FindRPAthWin32, FindRPathNix, CheckRPackages, IsNew, UpgradeConf, CopyConf, RLibsAreInstalled
 from chemins import RscriptsPath, ConstructConfigPath, ConstructDicoPath, ConstructGlobalPath, PathOut
 from parse_factiva_xml import ImportFactiva
 from checkinstall import CreateIraDirectory, CheckRPath, FindRPAthWin32, FindRPathNix, CheckRPackages, IsNew, UpgradeConf, CopyConf, RLibsAreInstalled
 from chemins import RscriptsPath, ConstructConfigPath, ConstructDicoPath, ConstructGlobalPath, PathOut
 from parse_factiva_xml import ImportFactiva
@@ -95,6 +89,7 @@ ID_HTMLcontent = wx.NewId()
 ID_SimiTxt = wx.NewId()
 ID_proto = wx.NewId()
 ID_ImportTXM = wx.NewId()
 ID_SimiTxt = wx.NewId()
 ID_proto = wx.NewId()
 ID_ImportTXM = wx.NewId()
+ID_FreqMulti = wx.NewId()
 ##########################################################
 #elements de configuration
 ##########################################################
 ##########################################################
 #elements de configuration
 ##########################################################
@@ -113,6 +108,8 @@ ImagePath = os.path.join(AppliPath, 'images')
 DictConfigPath = ConstructGlobalPath(AppliPath)
 ConfigGlob = ConfigParser()
 ConfigGlob.read(DictConfigPath['global'])
 DictConfigPath = ConstructGlobalPath(AppliPath)
 ConfigGlob = ConfigParser()
 ConfigGlob.read(DictConfigPath['global'])
+DefaultConf = ConfigParser()
+DefaultConf.read(DictConfigPath['preferences'])
 #repertoire de l'utilisateur
 if os.getenv('HOME') != None:
     user_home = os.getenv('HOME')
 #repertoire de l'utilisateur
 if os.getenv('HOME') != None:
     user_home = os.getenv('HOME')
@@ -149,17 +146,18 @@ sys.stdout = printer()
 ConfigPath = ConstructConfigPath(UserConfigPath)
 
 langues = {'french' : wx.LANGUAGE_FRENCH,
 ConfigPath = ConstructConfigPath(UserConfigPath)
 
 langues = {'french' : wx.LANGUAGE_FRENCH,
-            'english' : wx.LANGUAGE_ENGLISH,
-            'portuguese' : wx.LANGUAGE_PORTUGUESE,
-            'italian' : wx.LANGUAGE_ITALIAN,
-            'spanish' : wx.LANGUAGE_SPANISH}
+           'english' : wx.LANGUAGE_ENGLISH,
+           'portuguese' : wx.LANGUAGE_PORTUGUESE,
+           'italian' : wx.LANGUAGE_ITALIAN,
+           'spanish' : wx.LANGUAGE_SPANISH
+           }
 
 code_langues = {'french' : 'fr_FR',
 
 code_langues = {'french' : 'fr_FR',
-             'english' : 'en',
-            'portuguese' : 'pt_PT',
-            'italian' : 'it_IT',
-            'spanish' : 'es_ES'
-            }
+                'english' : 'en',
+                'portuguese' : 'pt_PT',
+                'italian' : 'it_IT',
+                'spanish' : 'es_ES'
+               }
 #####################################################################
 
 class IraFrame(wx.Frame):
 #####################################################################
 
 class IraFrame(wx.Frame):
@@ -191,10 +189,9 @@ class IraFrame(wx.Frame):
         self.preslangue = {}
         for langue in code_langues :
             self.preslangue[langue] = gettext.translation("iramuteq", os.path.join(AppliPath,'locale'), languages=[code_langues[langue]])
         self.preslangue = {}
         for langue in code_langues :
             self.preslangue[langue] = gettext.translation("iramuteq", os.path.join(AppliPath,'locale'), languages=[code_langues[langue]])
-        
+        self.setlangue()
         #self.presLan_fr = gettext.translation("iramuteq", os.path.join(AppliPath,'locale'), languages=['fr_FR'])
         #self.presLan_en = gettext.translation("iramuteq", os.path.join(AppliPath,'locale'), languages=['en'])
         #self.presLan_fr = gettext.translation("iramuteq", os.path.join(AppliPath,'locale'), languages=['fr_FR'])
         #self.presLan_en = gettext.translation("iramuteq", os.path.join(AppliPath,'locale'), languages=['en'])
-        self.setlangue()
         # tell FrameManager to manage this frame        
         #self._mgr = wx.aui.AuiManager()
         self._mgr = aui.AuiManager()
         # tell FrameManager to manage this frame        
         #self._mgr = wx.aui.AuiManager()
         self._mgr = aui.AuiManager()
@@ -260,6 +257,7 @@ class IraFrame(wx.Frame):
         #view_menu.AppendSeparator()
         matrix_menu = wx.Menu()
         matrix_menu.Append(ID_Freq, _(u"Frequencies").decode('utf8'))
         #view_menu.AppendSeparator()
         matrix_menu = wx.Menu()
         matrix_menu.Append(ID_Freq, _(u"Frequencies").decode('utf8'))
+        matrix_menu.Append(ID_FreqMulti, _(u'Multiple frequencies').decode('utf8'))
         matrix_menu.Append(ID_Chi2, _(u"Chi2").decode('utf8'))
         #matrix_menu.Append(ID_Student, u"t de Student")
         menu_classif = wx.Menu()
         matrix_menu.Append(ID_Chi2, _(u"Chi2").decode('utf8'))
         #matrix_menu.Append(ID_Student, u"t de Student")
         menu_classif = wx.Menu()
@@ -307,8 +305,8 @@ class IraFrame(wx.Frame):
 #--------------------------------------------------------------------
         self.statusbar = self.CreateStatusBar(2, wx.ST_SIZEGRIP)
         self.statusbar.SetStatusWidths([-2, -3])
 #--------------------------------------------------------------------
         self.statusbar = self.CreateStatusBar(2, wx.ST_SIZEGRIP)
         self.statusbar.SetStatusWidths([-2, -3])
-        self.statusbar.SetStatusText(u"Prêt", 0)
-        self.statusbar.SetStatusText(u"Bienvenue", 1)
+        self.statusbar.SetStatusText(_(u"Ready"), 0)
+        self.statusbar.SetStatusText(_(u"Wellcome"), 1)
 
         # min size for the frame itself isn't completely done.
         # see the end up FrameManager::Update() for the test
 
         # min size for the frame itself isn't completely done.
         # see the end up FrameManager::Update() for the test
@@ -397,6 +395,7 @@ class IraFrame(wx.Frame):
         self.Bind(wx.EVT_MENU, self.ExtractTools, extractmod)
         self.Bind(wx.EVT_MENU, self.ExtractTools, extractthem)
         self.Bind(wx.EVT_MENU, self.OnFreq, id=ID_Freq)
         self.Bind(wx.EVT_MENU, self.ExtractTools, extractmod)
         self.Bind(wx.EVT_MENU, self.ExtractTools, extractthem)
         self.Bind(wx.EVT_MENU, self.OnFreq, id=ID_Freq)
+        self.Bind(wx.EVT_MENU, self.OnFreqMulti, id=ID_FreqMulti)
         self.Bind(wx.EVT_MENU, self.OnChi2, id=ID_Chi2)
         self.Bind(wx.EVT_MENU, self.OnStudent, id=ID_Student)
         self.Bind(wx.EVT_MENU, self.OnCHDSIM, id=ID_CHDSIM)
         self.Bind(wx.EVT_MENU, self.OnChi2, id=ID_Chi2)
         self.Bind(wx.EVT_MENU, self.OnStudent, id=ID_Student)
         self.Bind(wx.EVT_MENU, self.OnCHDSIM, id=ID_CHDSIM)
@@ -459,9 +458,9 @@ class IraFrame(wx.Frame):
 
 ##############################################################@
         self.DisEnSaveTabAs(False)
 
 ##############################################################@
         self.DisEnSaveTabAs(False)
-        self.ShowMenu(_("View").decode('utf8'), False)
-        self.ShowMenu(_("Matrix analysis").decode('utf8'), False)
-        self.ShowMenu(_("Text analysis").decode('utf8'), False)
+        self.ShowMenu('view', False)
+        self.ShowMenu('matrix', False)
+        self.ShowMenu('text', False)
    
         self._mgr.Update()
 
    
         self._mgr.Update()
 
@@ -523,10 +522,12 @@ vous devez signaler le chemin de l'éxecutable de R dans les préférences."""
                 pass
             dlg.Destroy()
 
                 pass
             dlg.Destroy()
 
-
     def setlangue(self) :
         self.pref.read(self.ConfigPath['preferences'])
     def setlangue(self) :
         self.pref.read(self.ConfigPath['preferences'])
-        guilangue = self.pref.get('iramuteq', 'guilanguage')
+        try :
+            guilangue = self.pref.get('iramuteq', 'guilanguage')
+        except :
+            guilangue = DefaultConf.get('iramuteq', 'guilanguage')
         self.preslangue.get(guilangue, 'english').install()
 
     def OnVerif(self, evt) :
         self.preslangue.get(guilangue, 'english').install()
 
     def OnVerif(self, evt) :
@@ -546,9 +547,19 @@ vous devez signaler le chemin de l'éxecutable de R dans les préférences."""
                 item.Enable(DISEN)
     
     def ShowMenu(self, menu, Show=True):
                 item.Enable(DISEN)
     
     def ShowMenu(self, menu, Show=True):
-        menu_pos = self.mb.FindMenu(menu)
-        self.mb.EnableTop(menu_pos, Show)
-        self.mb.UpdateMenus()
+        if menu == 'text' :
+            menu_pos = 4
+        elif menu == 'matrix' :
+            menu_pos = 3
+        elif menu == 'view' :
+            menu_pos = 2
+        else :
+            menu_pos = None
+            
+        #menu_pos = self.mb.FindMenu(menu)
+        if not menu_pos is None :
+            self.mb.EnableTop(menu_pos, Show)
+            self.mb.UpdateMenus()
 
 
 #--------------------------------------------------------------------
 
 
 #--------------------------------------------------------------------
@@ -567,15 +578,22 @@ vous devez signaler le chemin de l'éxecutable de R dans les préférences."""
             self.tableau = Tableau(self,os.path.abspath(self.input_path[0]))
             val = get_table_param(self, self.input_path[0])
             if val == wx.ID_OK :
             self.tableau = Tableau(self,os.path.abspath(self.input_path[0]))
             val = get_table_param(self, self.input_path[0])
             if val == wx.ID_OK :
-                self.tableau.make_content()
-                OpenAnalyse(self, self.tableau.parametres)
-                self.tree.OnItemAppend(self.tableau.parametres)
+                busy = wx.BusyInfo(_("Please wait...").decode('utf8'), self)
+                wx.SafeYield()
+                try :
+                    self.tableau.make_content()
+                    OpenAnalyse(self, self.tableau.parametres)
+                    self.tree.OnItemAppend(self.tableau.parametres)
+                    del busy 
+                except :
+                    del busy
+                    BugReport(self)
                 #self.tableau.show_tab()
 
     def OnOpenAnalyse(self, event):
         self.AnalysePath = OnOpen(self, "Analyse")
         OpenAnalyse(self, self.AnalysePath[1][0], True)
                 #self.tableau.show_tab()
 
     def OnOpenAnalyse(self, event):
         self.AnalysePath = OnOpen(self, "Analyse")
         OpenAnalyse(self, self.AnalysePath[1][0], True)
-        self.ShowMenu(_("View"))
+        self.ShowMenu('view')
 
     def OnOpenText(self, event):
         inputname, self.input_path = OnOpen(self, "Texte")
 
     def OnOpenText(self, event):
         inputname, self.input_path = OnOpen(self, "Texte")
@@ -584,8 +602,6 @@ vous devez signaler le chemin de l'éxecutable de R dans les préférences."""
             self.OpenText()
    
     def OnViewData(self, event):
             self.OpenText()
    
     def OnViewData(self, event):
-        print self.type
-        print self.DataTxt
         if self.type == "Data":
             if not self.DataPop :
                 self.Sheet.Populate(self.content)
         if self.type == "Data":
             if not self.DataPop :
                 self.Sheet.Populate(self.content)
@@ -631,13 +647,14 @@ vous devez signaler le chemin de l'éxecutable de R dans les préférences."""
                 self.tree.OnItemAppend(corpus.parametres)
                 OpenAnalyse(self, corpus.parametres)
             except :
                 self.tree.OnItemAppend(corpus.parametres)
                 OpenAnalyse(self, corpus.parametres)
             except :
+                dlg.Destroy()
                 BugReport(self)
             else :
                 count = 1
                 keepGoing = dlg.Update(count, u"Lecture du fichier")
                 BugReport(self)
             else :
                 count = 1
                 keepGoing = dlg.Update(count, u"Lecture du fichier")
-                self.ShowMenu(_(u"View").decode('utf8'))
-                self.ShowMenu(_(u"Text analysis").decode('utf8'))
-                self.ShowMenu(_(u"Matrix analysis").decode('utf8'), False)
+                self.ShowMenu('view')
+                self.ShowMenu('text')
+                self.ShowMenu('matrix', False)
                 self.type = "Texte"
                 self.DataTxt = False
                 self.Text = ''
                 self.type = "Texte"
                 self.DataTxt = False
                 self.Text = ''
@@ -698,11 +715,11 @@ Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, États-Unis."""
             if 'parametres' in dir(npage) :
                 self.tree.GiveFocus(uuid=npage.parametres['uuid'])
                 if npage.parametres.get('matrix', False) :
             if 'parametres' in dir(npage) :
                 self.tree.GiveFocus(uuid=npage.parametres['uuid'])
                 if npage.parametres.get('matrix', False) :
-                    self.ShowMenu(_(u"Text analysis").decode('utf8'), False)
-                    self.ShowMenu(_(u"Matrix analysis").decode('utf8'), True)
+                    self.ShowMenu('text', False)
+                    self.ShowMenu('matrix', True)
                 elif npage.parametres.get('corpus', False) :
                 elif npage.parametres.get('corpus', False) :
-                    self.ShowMenu(_(u"Text analysis").decode('utf8'))
-                    self.ShowMenu(_(u"Matrix analysis").decode('utf8'), False)
+                    self.ShowMenu('text')
+                    self.ShowMenu('matrix', False)
 
     def OnCloseTab(self, evt):
         #log.info('Closing tab %s' % str(evt.GetEventObject()))
 
     def OnCloseTab(self, evt):
         #log.info('Closing tab %s' % str(evt.GetEventObject()))
@@ -716,34 +733,7 @@ Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, États-Unis."""
             self.history.rmtab(page.parametres)
             self.tree.CloseItem(uuid = page.parametres['uuid'])
         TabTitle = self.nb.GetPageText(self.nb.GetSelection())
             self.history.rmtab(page.parametres)
             self.tree.CloseItem(uuid = page.parametres['uuid'])
         TabTitle = self.nb.GetPageText(self.nb.GetSelection())
-#         if self.DictTab != {} :
-#             if TabTitle in self.DictTab :
-#                 ListFile=self.DictTab[TabTitle]
-#                 if False in ListFile:
-#                     msg = u"""
-# Certains résultats ne sont pas enregistrer.
-# Voulez-vous fermer quand même ?"""
-#                     dlg = wx.MessageDialog(self, msg, "Sauvegarde",wx.YES_NO | wx.NO_DEFAULT | wx.ICON_QUESTION)
-# 
-#                     dlg.CenterOnParent()
-#                     if dlg.ShowModal() in [wx.ID_NO, wx.ID_CANCEL]:
-#                         remove = False
-#                         evt.Veto()
-#                         dlg.Destroy()
-#                     else :
-#                         for f in ListFile[1:] :
-#                             print 'remove', f
-#                             os.remove(f)
-#                             remove = True
-#                         dlg.Destroy()
-#                 elif True in ListFile :
-#                     remove = True
-#                 if remove:
-#                     del self.DictTab[TabTitle]
-#             else : 
-#                 self.LastTabClose()
-#        else :
-#            remove = True
+
         if self.nb.GetPageCount() == 1 and not notebook :
             self.LastTabClose()
     
         if self.nb.GetPageCount() == 1 and not notebook :
             self.LastTabClose()
     
@@ -757,40 +747,6 @@ Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, États-Unis."""
             else :
                 self.ShowAPane("Intro_Text")
 
             else :
                 self.ShowAPane("Intro_Text")
 
-#     def OnSaveTabAs(self, event):
-#         SelectTab = self.nb.GetSelection()
-#         TabTitle = self.nb.GetPageText(SelectTab)
-#         FileToSave = self.DictTab[TabTitle]
-#         NewListFile = []
-#         dlg = wx.FileDialog(
-#             self, message="Enregistrer sous...", defaultDir=os.getcwd(),
-#             defaultFile="resultat.html", wildcard="Tous les fichiers|*", style=wx.SAVE | wx.OVERWRITE_PROMPT
-#             )
-#         dlg.SetFilterIndex(2)
-#         dlg.CenterOnParent()
-#         
-#         if dlg.ShowModal() == wx.ID_OK:
-#             Path = dlg.GetPath()
-#             Dirname = os.path.dirname(Path)
-#             Filename = dlg.GetFilename()
-#         else :
-#             Path = False
-#         dlg.Destroy()
-#         if Path:
-#             shutil.copyfile(FileToSave[-1], Path)
-#             os.remove(FileToSave[len(FileToSave) - 1])
-#             NewListFile.append(True)
-#             NewListFile.append(Path)
-#             for f in FileToSave[1:-1] :
-#                 Fileout = os.path.join(Dirname, os.path.basename(f))
-#                 shutil.copyfile(f, Fileout)
-#                 NewListFile.append(Fileout)
-#                 os.remove(f)
-#             TabText = Filename
-#             self.DictTab[TabText] = NewListFile
-#             del self.DictTab[TabTitle]
-#             self.nb.SetPageText(SelectTab, TabText)
-
     def GetStartPosition(self):
 
         self.x = self.x + 20
     def GetStartPosition(self):
 
         self.x = self.x + 20
@@ -830,14 +786,17 @@ Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, États-Unis."""
             parametres['type'] = analyse_type
         else :
             parametres = {'type' : analyse_type}
             parametres['type'] = analyse_type
         else :
             parametres = {'type' : analyse_type}
-        #try :
-        print 'plus de bug@@@@@@@@@@@@@@@@@@@@@@'
-        analyse(self, matrix, parametres = parametres, dlg = dlgnb)
-        #except:
-        #    BugReport(self)           
+        try :
+        #print 'plus de bug@@@@@@@@@@@@@@@@@@@@@@'
+            analyse(self, matrix, parametres = parametres, dlg = dlgnb)
+        except:
+            BugReport(self)           
 
     def OnFreq(self, event, matrix = None):
         self.analyse_matrix(Frequences, analyse_type = 'freq', matrix = matrix, dlgnb = 3)
 
     def OnFreq(self, event, matrix = None):
         self.analyse_matrix(Frequences, analyse_type = 'freq', matrix = matrix, dlgnb = 3)
+    
+    def OnFreqMulti(self, event, matrix = None):
+        self.analyse_matrix(FreqMultiple, analyse_type = 'freqmulti', matrix = matrix, dlgnb = 3)
 
     def OnChi2(self, event, matrix = None):
         self.analyse_matrix(ChiSquare, matrix = matrix, analyse_type = 'chi2', dlgnb = 3) 
 
     def OnChi2(self, event, matrix = None):
         self.analyse_matrix(ChiSquare, matrix = matrix, analyse_type = 'chi2', dlgnb = 3) 
@@ -1008,8 +967,8 @@ Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, États-Unis."""
         except:
             BugReport(self)
 
         except:
             BugReport(self)
 
-    def SimiCluster(self, parametres = {}, fromprof = False, pathout = '', listactives = [], actives = [], tableau = None) :
-        DoSimi(self, param = parametres, fromprof =  fromprof, listactives = listactives, actives = actives, tableau = tableau)
+    def SimiCluster(self, parametres = {}, fromprof = False, tableau = None) :
+        self.analyse_matrix(DoSimi, parametres = parametres, analyse_type = 'simiclustermatrix', matrix = tableau)
     
 #    def OnSimi(self,evt):
 #        try :
     
 #    def OnSimi(self,evt):
 #        try :