...
[iramuteq] / iramuteq.py
index df7ff89..479278d 100644 (file)
@@ -13,7 +13,6 @@ parser.add_option("-f", "--file", dest="filename",
 
 #print args
 #print options
-
 import sys
 reload(sys)
 import locale
@@ -34,7 +33,6 @@ import agw.aui as aui
 import wx.html
 import wx.grid
 import wx.lib.hyperlink as hl
-#from wx.lib.wordwrap import wordwrap
 #------------------------------------
 from functions import BugReport, PlaySound, ReadLexique, History, DoConf, ReadDicoAsDico, progressbar
 from checkversion import NewVersion
@@ -56,16 +54,17 @@ from analysetxt import Alceste
 from textdist import PamTxt
 from textstat import Stat
 from textaslexico import Lexico
-from textsimi import SimiTxt
+from textsimi import SimiTxt, SimiFromCluster
 from textwordcloud import WordCloud
 from profile_segment import ProfileSegment
 from textcheckcorpus import checkcorpus
 from openanalyse import OpenAnalyse
 from corpusNG import BuildFromAlceste, Builder
 from sheet import MySheet
-from checkinstall import CreateIraDirectory, CheckRPath, FindRPAthWin32, FindRPathNix, CheckRapp, CheckRPackages, IsNew, UpgradeConf, CopyConf, RLibsAreInstalled
+from checkinstall import CreateIraDirectory, CheckRPath, FindRPAthWin32, FindRPathNix, CheckRPackages, IsNew, UpgradeConf, CopyConf, RLibsAreInstalled
 from chemins import ConstructRscriptsPath, ConstructConfigPath, ConstructDicoPath, ConstructGlobalPath, PathOut
 from parse_factiva_xml import ImportFactiva
+
 from tree import LeftTree
 ##########################################################
 ID_OpenData = wx.NewId()
@@ -104,7 +103,6 @@ if sys.platform == 'darwin' :
 else :
     sys.setdefaultencoding(locale.getpreferredencoding())
 #chemin de l'application
-
 AppliPath = os.path.abspath(os.path.dirname(os.path.realpath(sys.argv[0])))
 #chemin des images
 ImagePath = os.path.join(AppliPath, 'images')
@@ -118,27 +116,25 @@ if os.getenv('HOME') != None:
 else:
     user_home = os.getenv('HOMEPATH')
 UserConfigPath = os.path.abspath(os.path.join(user_home, '.iramuteq'))
-#Si pas de fichiers de config utilisateur, on crée le repertoire
+#Si pas de fichiers de config utilisateur, on cree le repertoire
 CreateIraDirectory(UserConfigPath, AppliPath)
 #fichiers log pour windows (py2exe)
-print 'PLUS DE LOG !!!!!!!!!!'
-print 'LOGGING TEST'
 log = logging.getLogger('iramuteq')
 fh = logging.FileHandler(os.path.join(UserConfigPath,'stdout.log'))
 ch = logging.StreamHandler()
-formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
+formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')
 ch.setFormatter(formatter)
 fh.setFormatter(formatter)
 log.addHandler(ch)
 log.addHandler(fh)
 log.setLevel(logging.INFO)
-#debug = False
-#if not debug :
-#    if sys.platform == 'win32' or sys.platform == 'darwin':
-#        sys.stdout = open(os.path.join(UserConfigPath,'stdout.log'), 'w')
-#        sys.stderr = open(os.path.join(UserConfigPath,'stderr.log'), 'w')
-#chemin des fichiers de configuration utilisateur
-#print sys.argv[0]
+
+
+class writer(object):
+    def write(self, data):
+        if data.strip() != '' :
+            log.info('BUG : %s' % data)
+sys.stderr = writer()
 ConfigPath = ConstructConfigPath(UserConfigPath)
 #####################################################################
 
@@ -154,10 +150,13 @@ class IraFrame(wx.Frame):
         self.images_path = os.path.join(AppliPath,'images')
         self.UserConfigPath = UserConfigPath
         self.RscriptsPath = ConstructRscriptsPath(AppliPath)
-        self.DictPath = ConstructDicoPath(AppliPath)
+        #self.DictPath = ConstructDicoPath(AppliPath)
+        self.DictPath = ConstructDicoPath(UserConfigPath)
         self.ConfigGlob = ConfigGlob
         self.ConfigPath = ConstructConfigPath(UserConfigPath)
         self.pref = RawConfigParser()
+        #workaround for import problem
+        self.SimiFromCluster = SimiFromCluster
         #langues
         mylocale = wx.Locale(wx.LANGUAGE_FRENCH)
         mylocale.AddCatalogLookupPathPrefix(os.path.join(AppliPath,'locale'))
@@ -177,37 +176,44 @@ class IraFrame(wx.Frame):
         self.mb = wx.MenuBar()
 
         file_menu = wx.Menu()
-        item = wx.MenuItem(file_menu, ID_OpenData, _(u"Open a questionnaire"), _(u"Open a questionnaire"))
+        item = wx.MenuItem(file_menu, ID_OpenData, _(u"Open a matrix"), _(u"Open a matrix"))
         item.SetBitmap(wx.ArtProvider_GetBitmap(wx.ART_FILE_OPEN))
         file_menu.AppendItem(item)
         
-        item = wx.MenuItem(file_menu, ID_OpenText, u"Ouvrir texte", u"Ouvrir un corpus texte")
+        item = wx.MenuItem(file_menu, ID_OpenText, _(u"Open a text corpora"), _(u"Open a text corpora"))
         item.SetBitmap(wx.ArtProvider_GetBitmap(wx.ART_FILE_OPEN))
         file_menu.AppendItem(item)
         
-        item = wx.MenuItem(file_menu, ID_OnOpenAnalyse, u"Ouvrir une Analyse", "Ouvrir une Analyse")
+        item = wx.MenuItem(file_menu, ID_OnOpenAnalyse, _(u"Open an analysis"), _("Open an analysis"))
         item.SetBitmap(wx.ArtProvider_GetBitmap(wx.ART_FILE_OPEN))
         file_menu.AppendItem(item)
 
-        item1 = wx.MenuItem(file_menu, ID_Import, u"Importer un corpus factiva...", "Importer un corpus factiva...")
-        item1.SetBitmap(wx.ArtProvider_GetBitmap(wx.ART_TIP))
-        file_menu.AppendItem(item1)
+        
+        menuFactiva = wx.Menu()
+        fact_from_xml = wx.MenuItem(menuFactiva, wx.ID_ANY, _(u"from xml"))
+        fact_from_mail = wx.MenuItem(menuFactiva, wx.ID_ANY, _(u"from mail"))
+        fact_from_txt = wx.MenuItem(menuFactiva, wx.ID_ANY, _(u"from copy/paste"))
+        menuFactiva.AppendItem(fact_from_xml)
+        menuFactiva.AppendItem(fact_from_mail)
+        menuFactiva.AppendItem(fact_from_txt)
+
+        file_menu.AppendMenu(-1, _(u"Import from factiva"), menuFactiva)
         #item1.Enable(True)
        
-        item = wx.MenuItem(file_menu, ID_SaveTab, u"Enregistrer l\'onglet sous...", u"Enregistrer l\'onglet sous ...")
+        item = wx.MenuItem(file_menu, ID_SaveTab, _(u"Save tab as..."), _(u"Save tab as..."))
         item.SetBitmap(wx.ArtProvider_GetBitmap(wx.ART_FILE_SAVE_AS))
         #item.Enable(False)
         file_menu.AppendItem(item)
         
-        file_menu.Append(wx.ID_EXIT, u"Exit")
+        file_menu.Append(wx.ID_EXIT, _(u"Exit"))
         
         edit_menu = wx.Menu()
-        edit_menu.Append(wx.ID_PREFERENCES, '', u'Préférences')
+        edit_menu.Append(wx.ID_PREFERENCES, '', _(u'Preferences'))
         
         view_menu = wx.Menu()
-        view_menu.Append(ID_ACCEUIL, u"Page d'accueil")
-        view_menu.Append(ID_VIEWDATA, u"Afficher les données")
-        view_menu.Append(ID_RESULT, u'Afficher les résultats')
+        view_menu.Append(ID_ACCEUIL, _(u"Home page"))
+        view_menu.Append(ID_VIEWDATA, _(u"Show data"))
+        view_menu.Append(ID_RESULT, _(u'Show results'))
         #view_menu.AppendSeparator()
 
         analyse_menu = wx.Menu()
@@ -281,9 +287,9 @@ class IraFrame(wx.Frame):
         #                  CenterPane())
         self._mgr.AddPane(IntroPanel(self), aui.AuiPaneInfo().Name("Intro_Text").
                           CenterPane())
-        if not os.path.exists(os.path.join(UserConfigPath, 'history.db')) :
-            with open(os.path.join(UserConfigPath, 'history.db'), 'w') as f :
-                f.write('')
+        #if not os.path.exists(os.path.join(UserConfigPath, 'history.db')) :
+        #    with open(os.path.join(UserConfigPath, 'history.db'), 'w') as f :
+        #        f.write('')
         self.history = History(os.path.join(UserConfigPath, 'history.db'))
         self.tree = LeftTree(self)
         self._mgr.AddPane(self.tree, aui.AuiPaneInfo().Name("lefttree").Caption("Navigateur").
@@ -307,7 +313,6 @@ class IraFrame(wx.Frame):
         self.Sheet = MySheet(self)
         #self._mgr.AddPane(self.Sheet, wx.aui.AuiPaneInfo().Name("Data").CenterPane())
         self._mgr.AddPane(self.Sheet, aui.AuiPaneInfo().Name("Data").CenterPane())
-        #self.nb.Bind(wx.aui.EVT_AUINOTEBOOK_PAGE_CLOSE, self.OnCloseTab)
         self.nb.Bind(aui.EVT_AUINOTEBOOK_PAGE_CLOSE, self.OnCloseTab)
         self.nb.Bind(aui.EVT_AUINOTEBOOK_PAGE_CHANGED, self.OnPageChanged)
         # add the toolbars to the manager
@@ -335,7 +340,9 @@ class IraFrame(wx.Frame):
         self.Bind(wx.EVT_MENU, self.OnOpenData, id=ID_OpenData)
         self.Bind(wx.EVT_MENU, self.OnOpenText, id=ID_OpenText)
         self.Bind(wx.EVT_MENU, self.OnOpenAnalyse, id=ID_OnOpenAnalyse)
-        self.Bind(wx.EVT_MENU, self.import_factiva, id= ID_Import)
+        self.Bind(wx.EVT_MENU, self.import_factiva_xml, fact_from_xml)
+        self.Bind(wx.EVT_MENU, self.import_factiva_mail, fact_from_mail)
+        self.Bind(wx.EVT_MENU, self.import_factiva_txt, fact_from_txt)
         self.Bind(wx.EVT_MENU, self.OnFreq, id=ID_Freq)
         self.Bind(wx.EVT_MENU, self.OnChi2, id=ID_Chi2)
         self.Bind(wx.EVT_MENU, self.OnStudent, id=ID_Student)
@@ -432,17 +439,13 @@ class IraFrame(wx.Frame):
 Le chemin de l'executable de R n'a pas été trouvé.
 Si R n'est pas installé, vous devez l'installer (http://www.r-project.org/).
 Si R n'est pas installé dans le répertoire par défaut
-(C:\Program Files\R\R-2.x.x\R.exe sous windows ou /usr/bin/R sous linux ou Mac Os X)
-vous devez signaler le chemin de l'éxecutable de R dans les préférences.""" % self.ConfigPath['path']
+(souvent C:\Program Files\R\R-2.x.x\R.exe sous windows ou /usr/bin/R sous linux ou Mac Os X)
+vous devez signaler le chemin de l'éxecutable de R dans les préférences.""" 
             dlg = wx.MessageDialog(self, msg, u"Problème de configuration", wx.OK | wx.NO_DEFAULT | wx.ICON_WARNING)
             dlg.CenterOnParent()
             if dlg.ShowModal() in [wx.ID_NO, wx.ID_CANCEL]:
                  evt.Veto()
-            else :
-                print 'ok'
-        if sys.platform == 'darwin':
-            self.Rapp = self.PathPath.get('PATHS', 'rapp')
-            RappOk = CheckRapp(self.Rapp)
+            dlg.Destroy()
         self.DataPop = False
         self.DataTxt = False
         self.Text = ''
@@ -515,7 +518,6 @@ vous devez signaler le chemin de l'éxecutable de R dans les préférences.""" %
             self._mgr.UnInit()
             del self._mgr
             self.Destroy()
-            ##FIXME
             #if sys.platform == 'win32' :
             #    os.system("taskkill /im iramuteq.exe /f")
             #    print 'meurtre de process'
@@ -570,10 +572,13 @@ vous devez signaler le chemin de l'éxecutable de R dans les préférences.""" %
         
         builder =  Builder(self, dlg)
         if builder.res == wx.ID_OK :
-            corpus = builder.doanalyse()
-            self.history.add(corpus.parametres)
-            self.tree.OnItemAppend(corpus.parametres)
-            OpenAnalyse(self, corpus.parametres)
+            try :
+                corpus = builder.doanalyse()
+                self.history.add(corpus.parametres)
+                self.tree.OnItemAppend(corpus.parametres)
+                OpenAnalyse(self, corpus.parametres)
+            except :
+                BugReport(self)
         #self.content = DoConf().totext(corpus.parametres)
 #        parametres = DoConf(os.path.join(UserConfigPath,'corpus.cfg')).getoptions('corpus')
 #        parametres['originalpath'] = self.filename
@@ -590,28 +595,24 @@ vous devez signaler le chemin de l'éxecutable de R dans les préférences.""" %
 #        corpus = BuildFromAlceste(self.filename, parametres, self.lexique, self.expressions).corpus
         #self.corpus_encodage =  dial.encodages[dial.list_encodages.GetSelection()][0]
         #self.corpus_lang = dial.langues[dial.choice_dict.GetSelection()]
-            count = 1
-            keepGoing = dlg.Update(count, u"Lecture du fichier")
-#        try :
-#            with codecs.open(self.filename, 'rU', self.corpus_encodage) as f:
-#                self.content = f.read()
-#            #self.content = self.content.replace('\r','\n')
-#        except UnicodeDecodeError :
-#            msg = u"Ce fichier ne semble pas être encodé en %s" % self.corpus_encodage
-#            dial = wx.MessageDialog(self, msg, u"Problème d'encodage", wx.OK | wx.NO_DEFAULT | wx.ICON_WARNING)
-#            dial.CenterOnParent()
-#            res = dial.ShowModal()
-#            dial.Destroy()
-#            self.OpenText()
-            self.ShowMenu(_("View"))
-            self.ShowMenu(_("Text analysis"))
-            self.ShowMenu(_(u"Spreadsheet analysis"), False)
-            self.type = "Texte"
-            self.DataTxt = False
-            self.Text = ''
-            count += 1
-            keepGoing = dlg.Update(count, u"Chargement du dictionnaire")
-        dlg.Destroy()
+            else :
+                count = 1
+                keepGoing = dlg.Update(count, u"Lecture du fichier")
+    #            msg = u"Ce fichier ne semble pas être encodé en %s" % self.corpus_encodage
+    #            dial = wx.MessageDialog(self, msg, u"Problème d'encodage", wx.OK | wx.NO_DEFAULT | wx.ICON_WARNING)
+    #            dial.CenterOnParent()
+    #            res = dial.ShowModal()
+    #            dial.Destroy()
+    #            self.OpenText()
+                self.ShowMenu(_("View"))
+                self.ShowMenu(_("Text analysis"))
+                self.ShowMenu(_(u"Spreadsheet analysis"), False)
+                self.type = "Texte"
+                self.DataTxt = False
+                self.Text = ''
+                count += 1
+                keepGoing = dlg.Update(count, u"Chargement du dictionnaire")
+                dlg.Destroy()
         #self.OnViewData(wx.EVT_BUTTON)
         
     def OnExit(self, event):
@@ -666,14 +667,14 @@ Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, États-Unis."""
             self.tree.GiveFocus(uuid=npage.parametres['uuid'])
 
     def OnCloseTab(self, evt):
-        log.info('Closing tab %s' % str(evt.GetEventObject()))
+        #log.info('Closing tab %s' % str(evt.GetEventObject()))
         ctrl = evt.GetEventObject()
         if isinstance(ctrl.GetParent(), aui.AuiNotebook) or isinstance(ctrl.GetParent(), wx.Panel):
             notebook = True
         else :
             notebook = False
         page = self.nb.GetPage(self.nb.GetSelection())
-        if 'parametres' in dir(page) :
+        if 'parametres' in dir(page) and isinstance(ctrl.GetParent(), IraFrame) :
             self.history.rmtab(page.parametres)
             self.tree.CloseItem(uuid = page.parametres['uuid'])
         TabTitle = self.nb.GetPageText(self.nb.GetSelection())
@@ -707,7 +708,6 @@ Voulez-vous fermer quand même ?"""
             remove = True
         if self.nb.GetPageCount() == 1 and remove and not notebook :
             self.LastTabClose()
-
     
     def LastTabClose(self) :
         if self.nb.GetPageCount() == 1 :
@@ -771,21 +771,6 @@ Voulez-vous fermer quand même ?"""
     def OnAcceuil(self, event):
         self.ShowAPane(u"Intro_Text")
         event.Skip()
-    #???
-#    def OnCreateTab(self, event):
-#        if not self._mgr.GetPane("Tab_content").name == "Tab_content":
-#            self._mgr.AddPane(self.CreateTabCtrl(), aui.AuiPaneInfo().
-#                              Name("Tab_content").
-#                              CenterPane())
-#            self._mgr.GetPane("Intro_Text").Hide()
-#            self._mgr.GetPane("Tab_content").Show()
-#            self.ctrl.Bind(aui.EVT_AUINOTEBOOK_PAGE_CLOSE, self.OnCloseTab)
-#        else :
-#            page = wx.TextCtrl(self, -1, str(text), style=wx.TE_MULTILINE)
-#            self.ctrl.AddPage(page, "qsdqsd")
-#            self.ctrl.SetSelection(self.ctrl.GetPageCount() - 1)
-#        self._mgr.Update()
-    
     
     def CreateHTMLCtrl(self):
         ctrl = wx.html.HtmlWindow(self, -1, wx.DefaultPosition, wx.Size(400, 300))
@@ -844,19 +829,24 @@ Voulez-vous fermer quand même ?"""
         except:
             BugReport(self)
 
-    def OnSimiTxt(self, evt) :
+    def OnSimiTxt(self, evt, corpus = None) :
         #    print 'PLUS DE BUG SUR SIMITXT'
         try :
-            self.Text = SimiTxt(self)
+            #self.Text = SimiTxt(self)
+            if corpus is None :
+                corpus = self.tree.getcorpus()            
+            self.Text = SimiTxt(self, corpus, parametres = {'type': 'simitxt'}, dlg = progressbar(self, 3))
             if self.Text.val == wx.ID_OK :
                 PlaySound(self)
         except :
             BugReport(self)
     
-    def OnWordCloud(self, evt) :
+    def OnWordCloud(self, evt, corpus = None) :
         #    print 'PLUS DE BUG SUR WORDCLOUD'
         try :
-            self.Text = WordCloud(self)
+            if corpus is None :
+                corpus = self.tree.getcorpus()            
+            self.Text = WordCloud(self, corpus, parametres = {'type' : 'wordcloud'}, dlg = progressbar(self, 3))
             if self.Text.val == wx.ID_OK :
                 PlaySound(self)
         except :
@@ -878,6 +868,8 @@ Voulez-vous fermer quand même ?"""
     def OnTextStat(self, event, corpus = None):
             print 'PAS DE BUG SUR TEXT STAT'
         #try:
+            if corpus is None :
+                corpus = self.tree.getcorpus()
             self.Text = Stat(self, corpus, parametres = {'type': 'stat'}, dlg = progressbar(self, 7))
             
             if self.Text.val == wx.ID_OK :
@@ -889,6 +881,8 @@ Voulez-vous fermer quand même ?"""
         #try:
             #self.Text = AsLexico(self)
             print('ATTENTION : PLUS DE BUG SUR LEXICO')
+            if corpus is None :
+                corpus = self.tree.getcorpus()
             self.Text = Lexico(self, corpus, parametres = {'type' : 'spec'}, dlg = progressbar(self, 3))
             if self.Text.val == wx.ID_OK :
                 PlaySound(self)
@@ -902,23 +896,35 @@ Voulez-vous fermer quand même ?"""
         except:
             BugReport(self)
 
-    def import_factiva(self,event):
+    def import_factiva_xml(self,event):
         try :
-            ImportFactiva(self)
+            ImportFactiva(self, 'xml')
+        except :
+            BugReport(self)
+
+    def import_factiva_mail(self, evt) :
+        try :
+            ImportFactiva(self, 'mail')
+        except :
+            BugReport(self)
+
+    def import_factiva_txt(self, evt) :
+        try :
+            ImportFactiva(self, 'txt')
         except :
             BugReport(self)
 
     def OnTextAlceste(self, event, corpus = None):
-        #try:
-            print('ATTENTION : PLUS DE BUG SUR ALCESTE')
+        try:
+            #print('ATTENTION : PLUS DE BUG SUR ALCESTE')
             #RunAnalyse(self, corpus, Alceste, OptAlceste)
+            if corpus is None :
+                corpus = self.tree.getcorpus()            
             self.Text = Alceste(self, corpus, parametres = {'type': 'alceste'}, dlg = progressbar(self,6))
-            #self.history.addtab(self.Text.parametres)
-            #OpenAnalyse(self, self.Text.parametres['ira'])
             if self.Text.val == wx.ID_OK:
                 PlaySound(self)
-        #except:
-        #    BugReport(self)
+        except:
+            BugReport(self)
 
     def OnPamSimple(self, event):
         try:
@@ -990,7 +996,9 @@ Voulez-vous fermer quand même ?"""
 class IntroPanel(wx.Panel):
     def __init__(self, parent):
         wx.Panel.__init__(self, parent)
-        #col = randint(0, 100)
+        #col = randint(0, 255)
+        #col1 = randint(0,255)
+        #col2 = randint(0,255)
         col = 0
         bckgrdcolor = wx.Colour(col, col, col)
         self.SetBackgroundColour(bckgrdcolor)
@@ -1095,9 +1103,9 @@ class MySplashScreen(wx.SplashScreen):
         bmp = wx.Image(os.path.join(ImagePath, 'splash.png')).ConvertToBitmap()
         wx.SplashScreen.__init__(self, bmp,
                                  wx.SPLASH_CENTRE_ON_SCREEN | wx.SPLASH_TIMEOUT,
-                                 3000, None, -1)
+                                 2000, None, -1)
         self.Bind(wx.EVT_CLOSE, self.OnClose)
-        self.fc = wx.FutureCall(1500, self.ShowMain)
+        self.fc = wx.FutureCall(1, self.ShowMain)
 
     def OnClose(self, evt):
         evt.Skip()
@@ -1108,7 +1116,7 @@ class MySplashScreen(wx.SplashScreen):
             self.ShowMain()
 
     def ShowMain(self):
-        frame = IraFrame(None, -1, "IRaMuTeQ " + ConfigGlob.get('DEFAULT', 'version'), size=(950, 650))
+        frame = IraFrame(None, -1, "IRaMuTeQ " + ConfigGlob.get('DEFAULT', 'version'), size=(1100, 800))
         frame.Show()
         frame.Upgrade()
         frame.OnOpenFromCmdl()
@@ -1122,7 +1130,6 @@ class MyApp(wx.App):
         Create and show the splash screen.  It will then create and show
         the main frame when it is time to do so.
         """
-
         wx.SystemOptions.SetOptionInt("mac.window-plain-transition", 1)
         self.SetAppName("Iramuteq")       
         splash = MySplashScreen()