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