Statistics
| Revision:

root / tmp / org.txm.groovy.core / src / groovy / org / txm / scripts / importer / xtz / XTZCompiler.groovy @ 2246

History | View | Annotate | Download (8.5 kB)

1
package org.txm.scripts.importer.xtz
2

    
3
import java.io.File;
4

    
5
import org.txm.*
6
import org.txm.scripts.importer.SAttributesListener
7
import org.txm.importer.cwb.*
8
import org.txm.utils.ConsoleProgressBar
9
import org.txm.utils.logger.Log
10
import org.txm.core.preferences.TXMPreferences
11
import org.txm.core.preferences.TBXPreferences
12
import org.txm.libs.cqp.CQPLibPreferences
13

    
14
import javax.xml.stream.*
15
import org.txm.importer.xtz.*
16
import org.txm.objects.*
17
import org.txm.searchengine.cqp.corpus.*
18

    
19
class XTZCompiler extends Compiler {
20

    
21
        SAttributesListener sattrsListener; // store scanned structures
22
        private def anatypes = new HashSet<String>() // store scanned word attributes
23

    
24
        String regPath;
25
        String corpusname;
26
        String wtag;
27

    
28
        boolean doNormalizeAttributeValues = false;
29
        boolean doNormalizeAnaValues = true;
30

    
31
        public XTZCompiler(ImportModule module) {
32
                super(module);
33

    
34
                corpusname = module.getProject().getName();
35
                regPath = module.getBinaryDirectory().getAbsolutePath() + "/registry/"+corpusname.toLowerCase()
36

    
37
                wtag = module.getProject().getTokenizerWordElement();
38

    
39
                doNormalizeAttributeValues = "true".equals(module.getProject().getPreferencesScope().getNode("import").get(TBXPreferences.NORMALISEATTRIBUTEVALUES, "false"))
40
                doNormalizeAnaValues = "true".equals(module.getProject().getPreferencesScope().getNode("import").get(TBXPreferences.NORMALISEANAVALUES, "false"))
41
        }
42

    
43
        @Override
44
        public void process(List<String> orderedTextIDs) {
45
                super.process(orderedTextIDs); // set member
46

    
47
                if (orderedTextIDs == null) orderedTextIDs = module.getProject().getTextsID() ;
48

    
49
                Project project = module.getProject();
50
                CorpusBuild corpus = project.getCorpusBuild(project.getName(), MainCorpus.class);
51
                if (corpus != null) {
52
                        if (project.getDoUpdate()) {
53
                                corpus.clean(); // remove old files
54
                        } else {
55
                                corpus.delete(); // remove old files and TXMResult children
56
                        }
57
                } else {
58
                        corpus = new MainCorpus(project);
59
                        corpus.setID(project.getName());
60
                        corpus.setName(project.getName());
61
                }
62
                corpus.setDescription("Built with the XTZ import module");
63

    
64
                if (!doScanStep()) return;
65
                if (!doCQPStep()) return;
66
                if (!doCWBEncodeStep()) return;
67
                if (!doCWBMakeAllStep()) return;
68

    
69
                if (module.getProject().getCleanAfterBuild() && !module.getProject().getDoUpdate()) {
70
                        new File(module.getBinaryDirectory(), "cqp").deleteDir()
71
                }
72

    
73
                isSuccessFul = true;
74
        }
75

    
76
        /**
77
         * Scan all XML-TXM files to find out structures and word properties
78
         */
79
        public boolean doScanStep() {
80
                // get all anatypes
81
                sattrsListener = SAttributesListener.scanFiles(inputDirectory, wtag)
82
                def texts = module.getProject().getTexts()
83
                println "-- Listing structures&properties to create for "+texts.size()+" texts..."
84
                ConsoleProgressBar cpb = new ConsoleProgressBar(texts.size())
85
                for (Text t : texts) {
86
                        try {
87
                                cpb.tick();
88
                                getAnaTypes(t.getXMLTXMFile())
89
                        } catch (Exception e) {
90
                                println "Error while processing $t text XML-TXM file : "+t.getSource()+". Error: "+e
91
                                e.printStackTrace();
92
                                return false;
93
                        }
94
                }
95
                println ""
96
                return true;
97
        }
98

    
99
        private void getAnaTypes(File xmlFile) {
100
                def inputData = xmlFile.toURI().toURL().openStream();
101
                def factory = XMLInputFactory.newInstance();
102
                def parser = factory.createXMLStreamReader(inputData);
103
                boolean start = false;
104
                String ANA = "ana"
105
                String TYPE = "type"
106
                for (int event = parser.next(); event != XMLStreamConstants.END_DOCUMENT; event = parser.next()) {
107
                        if (event == XMLStreamConstants.START_ELEMENT) { // start elem
108
                                if (wtag.equals(parser.getLocalName())) {
109
                                        start = true;
110
                                } else if (start && ANA.equals(parser.getLocalName())) { // ana elem
111
                                        for (int i = 0 ; i < parser.getAttributeCount(); i++) { // find @type
112
                                                if (TYPE.equals(parser.getAttributeLocalName(i))) { // @type
113
                                                        anatypes.add(parser.getAttributeValue(i).substring(1)); //remove the #
114
                                                        break;
115
                                                }
116
                                        }
117
                                }
118
                        } else if (event == XMLStreamConstants.END_ELEMENT) { // start elem
119
                                if (wtag.equals(parser.getLocalName())) {
120
                                        start = false;
121
                                }
122
                        }
123
                }
124

    
125
                if (parser != null) parser.close();
126
                if (inputData != null) inputData.close();
127

    
128
                //                for (String type : types)
129
                //                        if (!anatypes.contains(type))
130
                //                                anatypes << type
131
        }
132

    
133
        def cqpFiles = []
134
        int cqpFilesUpdated = 0;
135
        public boolean doCQPStep() {
136
                println "-- Building CQP files $inputDirectory..."
137
                cqpDirectory.mkdir(); // if not created
138

    
139
                def texts = module.getProject().getTexts()
140
                ConsoleProgressBar cpb = new ConsoleProgressBar(texts.size())
141
                cqpFilesUpdated = 0;
142
                for (Text text : texts) {
143
                        cpb.tick();
144

    
145
                        File xmlFile = text.getXMLTXMFile()
146
                        String textname = text.getName()
147

    
148
                        File cqpFile = new File(cqpDirectory, textname + ".cqp")
149
                        cqpFiles << cqpFile
150

    
151
                        // skip step if cqpFile exists AND is more recent than the XML-TXM File
152
                        boolean mustBuild = false;
153
                        if (!cqpFile.exists() || xmlFile.lastModified() >= cqpFile.lastModified()) {
154
                                mustBuild = true
155
                        }
156

    
157
                        if (!text.isDirty() && !mustBuild) {
158
                                Log.finer("skipping .cqp step of $text");
159
                                continue
160
                        }
161
                        
162
                        cqpFilesUpdated++
163

    
164
                        XTZCompilerStep step = new XTZCompilerStep(xmlFile, cqpFile, textname, corpusname, "default", anatypes, wtag)
165
                        step.setNormalizeAnaValues(doNormalizeAnaValues)
166
                        step.setNormalizeAttributeValues(doNormalizeAttributeValues)
167
                        if (!step.process()) {
168
                                reason = "Fail to process $xmlFile."
169
                                return false;
170
                        }
171
                }
172
                println ""
173
                return true;
174
        }
175

    
176
        public boolean doCWBEncodeStep() {
177
                println "-- Running cwb-encode..."
178
                CwbEncode cwbEn = new CwbEncode()
179
                cwbEn.setDebug(debug)
180

    
181
                List<String> pargs = []
182
                pargs.add("id")
183
                for (String ana : anatypes)
184
                        pargs.add(ana)
185

    
186
                String[] pAttrs = pargs
187

    
188
                def structs = sattrsListener.getStructs()
189
                def structsProf = sattrsListener.getProfs()
190

    
191
                if (debug) {
192
                        println structs
193
                        println structsProf
194
                }
195

    
196
                List<String> sargs = new ArrayList<String>()
197
                def tmpTextAttrs = []
198
                for (String name : structs.keySet()) {
199
                        if (name == "text") {
200
                                for (String value : structs.get(name)) // append the attributes
201
                                        tmpTextAttrs << value // added after
202
                                continue;
203
                        }
204

    
205
                        String concat = name+":"+structsProf.get(name); // append the depth
206
                        for (String attributeName : structs.get(name)) // append the attributes
207
                                concat += "+"+attributeName.toLowerCase();
208

    
209
                        if (structs.get(name).size() == 0) {
210
                                concat += "+n";
211
                        } else {
212
                                if (!structs.get(name).contains("n"))
213
                                        concat += "+n"
214
                        }
215

    
216
                        if ((name == "p" || name == "body" || name == "back" || name == "front")
217
                        && !concat.contains("+n+") && !concat.endsWith("+n"))
218
                                concat += "+n"
219

    
220
                        sargs.add(concat)
221
                }
222

    
223
                String textSAttributes = "text:0+id+base+project";
224
                for (String name : tmpTextAttrs) {
225
                        if (!("id".equals(name) || "base".equals(name) || "project".equals(name)))
226
                                textSAttributes += "+"+name.toLowerCase()
227
                }
228

    
229
                sargs.add(textSAttributes)
230
                sargs.add("txmcorpus:0+lang")
231

    
232
                sargs.sort()
233

    
234
                String[] sAttributes = sargs
235
                String[] pAttributes = pAttrs
236
                println " Word properties: "+pAttributes
237
                println " Structures: "+sargs
238
                File allcqpFile = new File(cqpDirectory, "all.cqp");
239
                allcqpFile.delete()
240
                try {
241
                        if (!CwbEncode.concat(cqpFiles, allcqpFile)) {
242
                                println "Fail to write the master cqp file: "+allcqpFile
243
                                return false;
244
                        }
245

    
246
                        if (!cwbEn.run(outputDirectory.getAbsolutePath() + "/$corpusname",
247
                        allcqpFile.getAbsolutePath(),
248
                        regPath, pAttributes, sAttributes, false)) {
249
                                println "** cwb-encode did not ends well. Activate finer logs to see details."
250
                                return false;
251
                        }
252

    
253
                        allcqpFile.delete(); // clean
254
                } catch (Exception e) {
255
                        println "Error while running cwb-encode: "+e
256
                        e.printStackTrace()
257
                        allcqpFile.delete(); // clean
258
                        return false;
259
                }
260
                println ""
261
                return true;
262
        }
263

    
264
        public boolean doCWBMakeAllStep() {
265
                println "-- Running cwb-makeall..."
266
                try {
267
                        CwbMakeAll cwbMa = new CwbMakeAll();
268
                        cwbMa.setDebug(debug);
269

    
270
                        if (!new File(regPath).exists()) {
271
                                println "Error: The registry file was not created: $regPath. See https://groupes.renater.fr/wiki/txm-users/public/faq"
272
                                return false;
273
                        }
274
                        if (!cwbMa.run(corpusname, new File(regPath).getParent())) {
275
                                println "** cwb-makeall did not ends well. Activate finer logs to see details."
276
                                return false;
277
                        }
278

    
279
                        // remove milestones from CWB registry and data files
280
                        FixMilestoneDeclarations fm = new FixMilestoneDeclarations(
281
                                        new File(regPath), new File(outputDirectory.getAbsolutePath(), corpusname));
282
                        if (!fm.process()) {
283
                                println "Fail to verify&fix milestone declarations"
284
                                return false
285
                        }
286
                } catch (Exception e) {
287
                        println "Error while running cwb-makeall: "+e
288
                        return false;
289
                }
290
                return true;
291
        }
292
}