Statistics
| Revision:

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

History | View | Annotate | Download (8 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.core.preferences.TXMPreferences
10
import org.txm.core.preferences.TBXPreferences
11
import org.txm.libs.cqp.CQPLibPreferences
12

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

    
18
class XTZCompiler extends Compiler {
19

    
20
        SAttributesListener sattrsListener; // store scanned structures
21
        private def anatypes = new HashSet<String>() // store scanned word attributes
22
        
23
        String regPath;
24
        String corpusname;
25
        String wtag;
26
        
27
        boolean doNormalizeAttributeValues = false;
28
        boolean doNormalizeAnaValues = true;
29
        
30
        public XTZCompiler(ImportModule module) {
31
                super(module);
32

    
33
                corpusname = module.getProject().getName();
34
                regPath = module.getBinaryDirectory().getAbsolutePath() + "/registry/"+corpusname.toLowerCase()
35
                
36
                wtag = module.getProject().getTokenizerWordElement();
37
                
38
                doNormalizeAttributeValues = "true".equals(module.getProject().getPreferencesScope().getNode("import").get(TBXPreferences.NORMALISEATTRIBUTEVALUES, "false"))
39
                doNormalizeAnaValues = "true".equals(module.getProject().getPreferencesScope().getNode("import").get(TBXPreferences.NORMALISEANAVALUES, "false"))
40
        }
41

    
42
        public void process(ArrayList<File> files) {
43
                super.process(files); // set member
44
                
45
                if (files == null) files = inputDirectory.listFiles();
46
                
47
                if (!doScanStep()) return;
48
                if (!doCQPStep()) return;
49
                if (!doCWBEncodeStep()) return;
50
                if (!doCWBMakeAllStep()) return;
51
                
52
                CorpusBuild corpus = module.getProject().getCorpusBuild(corpusname);
53
                if (corpus != null) {
54
                        //println "CLEAN PREVIOUS CORPUS"
55
                        corpus.delete(); // remove old files
56
                }
57
                
58
                // make new one
59
                corpus = new MainCorpus(module.getProject());
60
                corpus.setID(corpusname);
61
                corpus.setName(corpusname);
62
                corpus.setDescription("Built with the XTZ import module");
63
                
64
                if (module.getProject().getCleanAfterBuild()) {
65
                        new File(module.getBinaryDirectory(), "cqp").deleteDir()
66
                }
67
                
68
                isSuccessFul = true;
69
        }
70

    
71
        /**
72
         * Scan all XML-TXM files to find out structures and word properties
73
         */
74
        public boolean doScanStep() {
75
                // get all anatypes                
76
                sattrsListener = SAttributesListener.scanFiles(inputDirectory, wtag)
77
                println "-- Listing structures&properties to create for "+files.size()+" XML-TXM files..."
78
                ConsoleProgressBar cpb = new ConsoleProgressBar(files.size())
79
                for (File f : files) {
80
                        try {
81
                                cpb.tick();
82
                                getAnaTypes(f)
83
                        } catch (Exception e) {
84
                                println "Error while processing $f text: "+e
85
                                e.printStackTrace();
86
                                return false;
87
                        }
88
                }
89
                println ""
90
                return true;
91
        }
92
        
93
        private void getAnaTypes(File xmlFile) {
94
                def inputData = xmlFile.toURI().toURL().openStream();
95
                def factory = XMLInputFactory.newInstance();
96
                def parser = factory.createXMLStreamReader(inputData);
97
                boolean start = false;
98
                String ANA = "ana"
99
                String TYPE = "type"
100
                for (int event = parser.next(); event != XMLStreamConstants.END_DOCUMENT; event = parser.next()) {
101
                        if (event == XMLStreamConstants.START_ELEMENT) { // start elem
102
                                if (wtag.equals(parser.getLocalName())) {
103
                                        start = true;
104
                                } else if (start && ANA.equals(parser.getLocalName())) { // ana elem
105
                                        for (int i = 0 ; i < parser.getAttributeCount(); i++) { // find @type
106
                                                if (TYPE.equals(parser.getAttributeLocalName(i))) { // @type
107
                                                        anatypes.add(parser.getAttributeValue(i).substring(1)); //remove the #
108
                                                        break;
109
                                                }
110
                                        }
111
                                }
112
                        } else if (event == XMLStreamConstants.END_ELEMENT) { // start elem
113
                                if (wtag.equals(parser.getLocalName())) {
114
                                        start = false;
115
                                }        
116
                        }
117
                }
118
                
119
                if (parser != null) parser.close();
120
                if (inputData != null) inputData.close();
121
                
122
//                for (String type : types)
123
//                        if (!anatypes.contains(type))
124
//                                anatypes << type
125
        }
126

    
127
        def cqpFiles = []
128
        public boolean doCQPStep() {
129
                println "-- Building CQP files $inputDirectory..."
130
                cqpDirectory.mkdir(); // if not created
131
                
132
                ConsoleProgressBar cpb = new ConsoleProgressBar(files.size())
133
                for (File xmlFile : files) {
134
                        cpb.tick();
135
                        String textname = xmlFile.getName();
136
                        int idx = textname.lastIndexOf(".")
137
                        if (idx > 0) textname = textname.substring(0, idx)
138
                        
139
                        File cqpFile = new File(cqpDirectory, textname + ".cqp")
140
                        cqpFiles << cqpFile
141
                        // skip step if cqpFile is more recent than xmlFile
142
                        if (cqpFile.exists() && cqpFile.lastModified() >= xmlFile.lastModified()) continue;
143
                        
144
                        XTZCompilerStep step = new XTZCompilerStep(xmlFile, cqpFile, textname, corpusname, "default", anatypes, wtag)
145
                        step.setNormalizeAnaValues(doNormalizeAnaValues)
146
                        step.setNormalizeAttributeValues(doNormalizeAttributeValues)
147
                        if (!step.process()) {
148
                                reason = "Fail to process $xmlFile."
149
                                return false;
150
                        }
151
                }
152
                println ""
153
                return true;
154
        }
155

    
156
        public boolean doCWBEncodeStep() {
157
                println "-- Running cwb-encode..."
158
                CwbEncode cwbEn = new CwbEncode()
159
                cwbEn.setDebug(debug)
160
                
161
                List<String> pargs = []
162
                pargs.add("id")
163
                for (String ana : anatypes)
164
                        pargs.add(ana)
165

    
166
                String[] pAttrs = pargs
167

    
168
                def structs = sattrsListener.getStructs()
169
                def structsProf = sattrsListener.getProfs()
170

    
171
                if (debug) {
172
                        println structs
173
                        println structsProf
174
                }
175
                
176
                List<String> sargs = new ArrayList<String>()
177
                def tmpTextAttrs = []
178
                for (String name : structs.keySet()) {
179
                        if (name == "text") {
180
                                for (String value : structs.get(name)) // append the attributes
181
                                        tmpTextAttrs << value // added after
182
                                continue;
183
                        }
184

    
185
                        String concat = name+":"+structsProf.get(name); // append the depth
186
                        for (String attributeName : structs.get(name)) // append the attributes
187
                                concat += "+"+attributeName.toLowerCase();
188
                        
189
                        if (structs.get(name).size() == 0) {
190
                                concat += "+n";
191
                        } else {
192
                                if (!structs.get(name).contains("n"))
193
                                        concat += "+n"
194
                        }
195
                                
196
                        if ((name == "p" || name == "body" || name == "back" || name == "front")
197
                                 && !concat.contains("+n+") && !concat.endsWith("+n"))
198
                                concat += "+n"
199
                                
200
                        sargs.add(concat)
201
                }
202

    
203
                String textSAttributes = "text:0+id+base+project";
204
                for (String name : tmpTextAttrs) {
205
                        if (!("id".equals(name) || "base".equals(name) || "project".equals(name)))
206
                                textSAttributes += "+"+name.toLowerCase()
207
                }
208

    
209
                sargs.add(textSAttributes)
210
                sargs.add("txmcorpus:0+lang")
211

    
212
                sargs.sort()
213

    
214
                String[] sAttributes = sargs
215
                String[] pAttributes = pAttrs
216
                println " Word properties: "+pAttributes
217
                println " Structures: "+sargs
218
                File allcqpFile = new File(cqpDirectory, "all.cqp");
219
                allcqpFile.delete()
220
                try {
221
                        if (!CwbEncode.concat(cqpFiles, allcqpFile)) {
222
                                println "Fail to write the master cqp file: "+allcqpFile
223
                                return false;
224
                        }
225
                        
226
                        if (!cwbEn.run(outputDirectory.getAbsolutePath() + "/$corpusname",
227
                                        allcqpFile.getAbsolutePath(),
228
                                        regPath, pAttributes, sAttributes, false)) {
229
                                println "** cwb-encode did not ends well. Activate finer logs to see details."
230
                                return false;
231
                        }
232
                        
233
                        allcqpFile.delete(); // clean
234
                } catch (Exception e) {
235
                        println "Error while running cwb-encode: "+e
236
                        e.printStackTrace()
237
                        allcqpFile.delete(); // clean 
238
                        return false;
239
                }
240
                println ""
241
                return true;
242
        }
243

    
244
        public boolean doCWBMakeAllStep() {
245
                println "-- Running cwb-makeall..."
246
                try {
247
                        CwbMakeAll cwbMa = new CwbMakeAll();
248
                        cwbMa.setDebug(debug);
249

    
250
                        if (!new File(regPath).exists()) {
251
                                println "Error: The registry file was not created: $regPath. See https://groupes.renater.fr/wiki/txm-users/public/faq"
252
                                return false;
253
                        }
254
                        if (!cwbMa.run(corpusname, new File(regPath).getParent())) {
255
                                println "** cwb-makeall did not ends well. Activate finer logs to see details."
256
                                return false;
257
                        }
258
                        
259
                        // remove milestones from CWB registry and data files
260
                        FixMilestoneDeclarations fm = new FixMilestoneDeclarations(
261
                                new File(regPath), new File(outputDirectory.getAbsolutePath(), corpusname));
262
                        if (!fm.process()) {
263
                                println "Fail to verify&fix milestone declarations"
264
                                return false
265
                        }
266
                } catch (Exception e) {
267
                        println "Error while running cwb-makeall: "+e
268
                        return false;
269
                }
270
                return true;
271
        }
272
}