Statistics
| Revision:

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

History | View | Annotate | Download (7.7 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.stat.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().getTokenizerParameter("wordelement", "w");
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
                parser.close()
119

    
120
//                for (String type : types)
121
//                        if (!anatypes.contains(type))
122
//                                anatypes << type
123
        }
124

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

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

    
164
                String[] pAttrs = pargs
165

    
166
                def structs = sattrsListener.getStructs()
167
                def structsProf = sattrsListener.getProfs()
168

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

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

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

    
207
                sargs.add(textSAttributes)
208
                sargs.add("txmcorpus:0+lang")
209

    
210
                sargs.sort()
211

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

    
238
        public boolean doCWBMakeAllStep() {
239
                println "-- Running cwb-makeall..."
240
                try {
241
                        CwbMakeAll cwbMa = new CwbMakeAll();
242
                        cwbMa.setDebug(debug);
243

    
244
                        if (!new File(regPath).exists()) {
245
                                println "Error: The registry file was not created: $regPath. See https://groupes.renater.fr/wiki/txm-users/public/faq"
246
                                return false;
247
                        }
248
                        cwbMa.run(corpusname, regPath);
249
                        
250
                        // remove milestones from CWB registry and data files
251
                        FixMilestoneDeclarations fm = new FixMilestoneDeclarations(
252
                                new File(regPath), new File(outputDirectory.getAbsolutePath(), corpusname));                        
253
                        if (!fm.process()) {
254
                                println "Fail to verify&fix milestone declarations"
255
                                return false
256
                        }
257
                } catch (Exception e) {
258
                        println "Error while running cwb-makeall: "+e
259
                        return false;
260
                }
261
                return true;
262
        }
263
}