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