...
[iramuteq] / textwordcloud.py
1 #!/bin/env python
2 # -*- coding: utf-8 -*-
3 #Author: Pierre Ratinaud
4 #Copyright (c) 2008-2009 Pierre Ratinaud
5 #Lisense: GNU/GPL
6
7 from analysetxt import AnalyseText
8 from guifunct import getPage, getCorpus, SelectColumn
9 from ConfigParser import RawConfigParser
10 from functions import sortedby, progressbar, CreateIraFile, exec_rcode, check_Rresult, MessageImage
11 from dialog import StatDialog, PrefWordCloud
12 from PrintRScript import WordCloudRScript
13 #from openanalyse import OpenAnalyse
14 #from ttparser import * 
15 import tempfile
16 from time import sleep
17 import wx
18 import os
19 #from corpusNG import Corpus
20 import logging
21
22 logger = logging.getLogger('iramuteq.textwordcloud')
23
24
25 class WordCloud(AnalyseText):
26     def doanalyse(self) :
27         self.parametres['type'] = 'wordcloud'
28         #FIXME
29         limit = 3
30         self.make_option()
31         if self.parametres['mode'] == 2 :
32             self.actives = self.corpus.make_actives_limit(limit, 1)
33             self.actives += self.corpus.make_actives_limit(limit, 2)
34         elif self.parametres['mode'] == 0 :
35             self.actives = self.corpus.make_actives_limit(limit, 1)
36         elif self.parametres['mode'] == 1 :
37             self.actives = self.corpus.make_actives_limit(limit, 2)
38         dictcol = dict([[i, [act, self.corpus.getlemeff(act)]] for i, act in enumerate(self.actives)]) 
39         SelectColumn(self.ira, dictcol, self.actives, self.pathout['selected.csv'], dlg = True)
40         self.make_wordcloud()
41         script = WordCloudRScript(self)
42         script.make_script()
43         self.doR(script.scriptout)
44     
45     def make_option(self) :
46         dial = PrefWordCloud(self.ira)
47         dial.CenterOnParent()
48         res = dial.ShowModal()
49         if res == wx.ID_OK :
50             self.parametres['width'] = dial.spin_L.GetValue()
51             self.parametres['height'] = dial.spin_H.GetValue()
52             self.parametres['maxword'] = dial.spin_maxword.GetValue()
53             self.parametres['mincex'] = float(dial.spin_mincex.GetValue())/float(10)
54             self.parametres['maxcex'] = float(dial.spin_maxcex.GetValue())/float(10)
55             self.parametres['col_text'] = dial.color_text.GetColour()
56             self.parametres['col_bg'] = dial.color_bg.GetColour()
57             self.parametres['mode'] = dial.typeformeschoice.GetSelection()
58             outgraph = os.path.join(os.path.dirname(self.pathout['zipf.png']), 'nuage_')
59             nb = 1
60             while os.path.exists(outgraph + str(nb) + '.png') :
61                 nb += 1
62             self.parametres['graphout'] = outgraph + str(nb) + '.png'
63
64
65     def make_wordcloud(self) :
66         act = ['\t'.join([act, `self.corpus.getlemeff(act)`]) for act in self.actives]
67         with open(self.pathout['actives_eff.csv'], 'w') as f :
68             f.write('\n'.join(act).encode(self.ira.syscoding))
69        ####################################################################        
70 #        self.conf = None
71 #        self.parent = parent
72 #        self.type = 'alceste'
73 #        self.cmd = cmd
74 #        self.ConfigPath = parent.ConfigPath
75 #        self.DictPath = parent.DictPath
76 #        self.KeyConf = RawConfigParser()
77 #        self.KeyConf.read(self.ConfigPath['key'])
78 #        page = getPage(self.parent)
79 #        if page is not None :
80 #            self.corpus = getCorpus(page)
81 #            if self.corpus is not None :
82 #                self.pathout = ConstructPathOut(self.corpus.parametre['openpath'], 'WordCloud')
83 #                self.dictpathout = StatTxtPathOut(self.pathout)
84 #                self.val = wx.ID_OK
85 #        else :
86 #            self.corpus = Corpus(parent)
87 #            self.corpus.parametre['encodage'] = parent.corpus_encodage
88 #            self.corpus.parametre['lang'] = parent.corpus_lang
89 #            self.corpus.parametre['filename'] = parent.filename
90 #            self.pathout = ConstructPathOut(self.corpus.parametre['filename'], 'WordCloud')
91 #            self.dictpathout = StatTxtPathOut(self.pathout)
92 #            self.corpus.dictpathout = self.dictpathout
93 #            if not self.cmd :
94 #                dial = StatDialog(self,parent)
95 #                dial.CenterOnParent()
96 #                self.val = dial.ShowModal()
97 #            else :
98 #                self.val = wx.ID_OK
99 #            if self.val == wx.ID_OK :
100 #                if not self.cmd :
101 #                    if dial.radio_lem.GetSelection() == 0 : lem = True
102 #                    else : lem = False
103 #                    if dial.exp.GetSelection() == 0 : exp = True
104 #                    else : exp = False
105 #                    self.make_uce = dial.check_uce.GetValue()
106 #                    self.corpus.parametre['nbforme_uce'] = dial.spin_ctrl_4.GetValue()
107 #                    self.corpus.parametre['max_actives'] = dial.spin_max_actives.GetValue()
108 #                    self.corpus.parametre['eff_min_uce'] = self.corpus.parametre['nbforme_uce']
109 #                else :
110 #                    lem = True
111 #                    exp = True
112 #                    self.make_uce = False
113 #                    self.corpus.parametre['nbforme_uce'] = None
114 #                    self.corpus.parametre['eff_min_uce'] = None
115 #                self.corpus.parametre['lem'] = lem
116 #                self.corpus.parametre['expressions'] = exp
117 #                self.corpus.supplementaires = [option for option in self.KeyConf.options('KEYS') if self.KeyConf.get('KEYS', option) == "2"]
118 #                self.corpus.typeactive = [option for option in self.KeyConf.options('KEYS') if self.KeyConf.get('KEYS', option) == "1"]
119 #                self.make_corpus()
120 #
121 #        if self.val == wx.ID_OK :
122 #            if 'supplementaires' not in dir(self.corpus) :
123 #                self.corpus.supplementaires = [option for option in self.KeyConf.options('KEYS') if self.KeyConf.get('KEYS', option) == "2"]
124 #            if 'typeactive' not in dir(self.corpus) :
125 #                self.corpus.typeactive = [option for option in self.KeyConf.options('KEYS') if self.KeyConf.get('KEYS', option) == "1"]
126 #            self.make_stats()
127 #
128 #    def make_corpus(self) :
129 #        if not self.cmd :
130 #            self.dlg = progressbar(self, 7)
131 #        else :
132 #            self.dlg = None
133 #        self.corpus.content = self.parent.content
134 #        ucis_txt, ucis_paras_txt = self.corpus.start_analyse(self.parent, dlg = self.dlg, cmd = self.cmd, fromtt = False)
135 #        del ucis_txt
136 #        
137 #        if not self.cmd :
138 #            self.dlg.Update(5, '%i UCI...' % len(ucis_paras_txt))
139 #        self.corpus.make_ucis_paras_uces(ucis_paras_txt, make_uce = self.make_uce)
140 #        del ucis_paras_txt
141 #
142 #        if self.corpus.para_coords != [[] for val in self.corpus.para_coords] :
143 #            self.corpus.parametre['para'] = True
144 #        else :
145 #            self.corpus.parametre['para'] = False
146 #        self.corpus.make_etoiles(self.corpus.para_coords)
147 #
148 #        if not self.cmd :
149 #            self.dlg.Update(6, u'Dictionnaires')
150 #        uces, orderuces = self.corpus.make_forms_and_uces()
151 #        self.corpus.make_lems(self.parent.lexique)
152 #
153 #    def make_stats(self):
154 #        if not self.cmd :
155 #            if not 'dlg' in dir(self) :
156 #                self.dlg = progressbar(self, 7)
157 #        if not self.corpus.parametre['lem'] :
158 #            formes = self.corpus.formes
159 #        else :
160 #            formes = self.corpus.make_lem_eff()
161 #        act = [[forme, formes[forme][0], formes[forme][2]] for forme in formes if formes[forme][2] in
162 #                self.corpus.typeactive]
163 #        act = sortedby(act, 2, 1)
164 #        act = [[val[0], `val[1]`, val[2]] for val in act]
165 #        with open(os.path.join(self.pathout, 'actives.csv'), 'w') as f:
166 #            f.write('\n'.join([';'.join(line) for line in act]))
167 #        #act = [[i, val] for i, val in enumerate(act)]
168 #        self.corpus.dictpathout = self.dictpathout
169 #        #self.corpus.make_type_tot()
170 #
171 #        if not self.cmd :
172 #            self.dlg.Destroy()
173 #            pref = PrefWordCloud(self.parent)
174 #            pref.CenterOnParent()
175 #            res = pref.ShowModal()
176 #        else :
177 #            res = wx.ID_OK
178 #        if res == wx.ID_OK :
179 #            self.dlg = progressbar(self, 3)
180 #            width = pref.spin_L.GetValue()
181 #            height = pref.spin_H.GetValue()
182 #            maxword = pref.spin_maxword.GetValue()
183 #            mincex = float(pref.spin_mincex.GetValue())/float(10)
184 #            maxcex = float(pref.spin_maxcex.GetValue())/float(10)
185 #            col_text = pref.color_text.GetColour()
186 #            col_bg = pref.color_bg.GetColour()
187 #            col_text = str(col_text).replace(')', ', max=255)')
188 #            col_bg = str(col_bg).replace(')', ', max=255)')
189 #            outgraph = os.path.join(os.path.dirname(self.dictpathout['zipf']), 'nuage_')
190 #            nb = 1
191 #            while os.path.exists(outgraph + str(nb) + '.png') :
192 #                nb += 1
193 #            outgraph = outgraph + str(nb) + '.png'
194 #
195 #            txt = """
196 #            source("%s")
197 #            library(wordcloud)
198 #            act <- read.csv2("%s", header = FALSE, row.names = 1)
199 #            maxword <- %i
200 #            maxtoprint <- ifelse(nrow(act) > maxword, maxword, nrow(act))
201 #            toprint <- act[1:maxtoprint,]
202 #            open_file_graph("%s", width = %i, height = %i)
203 #            par(bg=rgb%s)
204 #            wordcloud(row.names(toprint), toprint[,1], scale=c(%f,%f), random.order=FALSE, colors=rgb%s) 
205 #            dev.off()
206 #            """ % (self.parent.RscriptsPath['Rgraph'], ffr(os.path.join(self.pathout, 'actives.csv')), maxword, ffr(outgraph), width, height, col_bg, maxcex, mincex, col_text)
207 #            tmpscript = tempfile.mktemp(dir=self.parent.TEMPDIR)
208 #            with open(tmpscript, 'w') as f :
209 #                f.write(txt)
210 #            pid = exec_rcode(self.parent.RPath, tmpscript, wait = False)
211 #            while pid.poll() == None :
212 #                self.dlg.Pulse('R...')
213 #                sleep(0.2)
214 #            check_Rresult(self.parent, pid)
215 #            self.corpus.save_corpus(self.dictpathout['db'])
216 #            CreateIraFile(self.dictpathout, 0, corpname = os.path.basename(self.corpus.parametre['filename']), section =
217 #                    'wordcloud')
218 #            #win = MessageImage(self.parent, -1, u"Graphique", size=(700, 500),style = wx.DEFAULT_FRAME_STYLE)
219 #            #win.imagename = "nuage.png"
220 #            #win.addsaveimage(outgraph)
221 #            #txt = "<img src='%s'>" % FFF(outgraph).replace('//','/')
222 #            #win.HtmlPage.SetPage(txt)
223 #            #win.Show(True)
224 #            if not self.cmd :
225 #                #OpenAnalyse(self.parent, self.dictpathout['ira'])
226 #                #self.DoLayout(self.parent)
227 #                OpenAnalyse(self.parent, self.dictpathout['ira'])
228 #                self.dlg.Update(7, 'fini')
229 #                self.dlg.Destroy()