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