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