Statistics
| Revision:

root / tmp / org.txm.groovy.core / src / groovy / org / txm / importer / xml / xmlLoader.groovy @ 966

History | View | Annotate | Download (10.6 kB)

1
// Copyright © 2010-2013 ENS de Lyon.
2
// Copyright © 2007-2010 ENS de Lyon, CNRS, INRP, University of
3
// Lyon 2, University of Franche-Comté, University of Nice
4
// Sophia Antipolis, University of Paris 3.
5
//
6
// The TXM platform is free software: you can redistribute it
7
// and/or modify it under the terms of the GNU General Public
8
// License as published by the Free Software Foundation,
9
// either version 2 of the License, or (at your option) any
10
// later version.
11
//
12
// The TXM platform is distributed in the hope that it will be
13
// useful, but WITHOUT ANY WARRANTY; without even the implied
14
// warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
15
// PURPOSE. See the GNU General Public License for more
16
// details.
17
//
18
// You should have received a copy of the GNU General
19
// Public License along with the TXM platform. If not, see
20
// http://www.gnu.org/licenses.
21
//
22
//
23
//
24
// $LastChangedDate: 2016-11-29 16:47:07 +0100 (mar. 29 nov. 2016) $
25
// $LastChangedRevision: 3349 $
26
// $LastChangedBy: mdecorde $
27
//
28
package org.txm.importer.xml;
29

    
30
import javax.xml.stream.XMLStreamReader;
31

    
32
import org.txm.sw.RemoveTag;
33
import org.txm.importer.ApplyXsl2;
34
import org.txm.importer.ValidateXml;
35
import org.txm.importer.xml.importer;
36
import org.txm.importer.xml.compiler;
37
import org.txm.importer.xml.pager_old;
38
import org.txm.objects.*;
39
import org.txm.tokenizer.TokenizerClasses;
40
import org.txm.utils.*
41
import org.txm.utils.io.*;
42
import org.txm.*;
43
import org.txm.core.engines.*;
44
import org.txm.importer.xmltxm.*;
45
import org.txm.utils.i18n.*;
46
import org.txm.metadatas.*;
47
import javax.xml.stream.*;
48
import org.w3c.dom.Element
49
import org.txm.utils.xml.DomUtils;
50

    
51
String userDir = System.getProperty("user.home");
52

    
53
def MONITOR;
54
boolean debug = org.txm.utils.logger.Log.isPrintingErrors();
55
BaseParameters params;
56
try {params = paramsBinding;MONITOR=monitor} catch (Exception)
57
{        println "DEV MODE";//exception means we debug
58
        debug = true
59
        params = new BaseParameters(new File(userDir, "xml/bvh/bugnames/import.xml"))
60
        params.load()
61
        if (!org.txm.Toolbox.isInitialized()) {
62

    
63
                TokenizerClasses.loadFromNode(params.getTokenizerElement(params.getCorpusElement()));
64
                Toolbox.setParam(Toolbox.INSTALL_DIR,new File("/usr/lib/TXM"));
65
                //Toolbox.setParam(Toolbox.INSTALL_DIR,new File("C:\\Program Files\\TXM"));//For Windows
66
                Toolbox.setParam(Toolbox.METADATA_ENCODING, "UTF-8");
67
                Toolbox.setParam(Toolbox.METADATA_COLSEPARATOR, ",");
68
                Toolbox.setParam(Toolbox.METADATA_TXTSEPARATOR, "\"");
69
                //Toolbox.setParam(Toolbox.TREETAGGER_MODELS_PATH,new File("C:\\Program Files\\treetagger\\models"));//for Windows
70
                Toolbox.setParam(Toolbox.USER_TXM_HOME, new File(System.getProperty("user.home"), "TXM"));
71
        }
72
}
73
if (params == null) { println "no parameters. Aborting"; return; }
74

    
75
String corpusname = params.getCorpusName();
76
Element corpusElem = params.corpora.get(corpusname);
77
String basename = params.name;
78
String rootDir = params.rootDir;
79
String lang = corpusElem.getAttribute("lang");
80
String model = lang
81
String encoding = corpusElem.getAttribute("encoding");
82
boolean annotate = "true" == corpusElem.getAttribute("annotate");
83
String xsl = params.getXsltElement(corpusElem).getAttribute("xsl")
84
def xslParams = params.getXsltParams(corpusElem);
85
int wordsPerPage = params.getWordsPerPage("default")
86
String page_element = params.getPageElement("default")
87
boolean build_edition = params.getDoEdition("default")
88

    
89
File srcDir = new File(rootDir);
90
File binDir = new File(Toolbox.getTxmHomePath(), "corpora/"+basename);
91
binDir.deleteDir();
92
binDir.mkdirs();
93
if (!binDir.exists()) {
94
        println "Could not create binDir "+binDir
95
        return;
96
}
97

    
98
File txmDir = new File(binDir, "txm/$corpusname");
99
txmDir.deleteDir();
100
txmDir.mkdirs();
101

    
102
File propertyFile = new File(rootDir, "import.properties")//default
103
Properties props = new Properties();
104
String[] metadatasToKeep;
105

    
106
String textSortAttribute = null;
107
boolean normalizeMetadata = false;
108
String ignoredElements = null;
109
boolean stopIfMalformed = false;
110

    
111
println "Trying to read import properties file: "+propertyFile
112
if (propertyFile.exists() && propertyFile.canRead()) {
113
        InputStreamReader input = new InputStreamReader(new FileInputStream(propertyFile) , "UTF-8");
114
        props.load(input);
115
        input.close();
116
        if(props.getProperty("sortmetadata") != null)
117
                textSortAttribute = props.get("sortmetadata").toString();
118
        if (props.getProperty("normalizemetadata") != null)
119
                normalizeMetadata = Boolean.parseBoolean(props.get("normalizemetadata").toString());
120
        if (props.getProperty("ignoredelements") != null)
121
                ignoredElements = props.get("ignoredelements").toString();
122
        if (props.getProperty("stopifmalformed") != null)
123
                stopIfMalformed = Boolean.parseBoolean(props.get("stopifmalformed").toString());
124

    
125
        println "import properties: "
126
        println " sort metadata: "+textSortAttribute
127
        println " normalize attributes: "+normalizeMetadata
128
        println " ignored elements: "+ignoredElements
129
        println " stop if a XML source is malformed: "+stopIfMalformed
130
}
131

    
132
File allmetadatasfile = Metadatas.findMetadataFile(srcDir);
133

    
134
// Apply XSL
135
if (MONITOR != null && MONITOR.isCanceled()) { return MONITOR.done(); }
136
if (MONITOR != null) MONITOR.worked(1, "APPLYING XSL")
137
if (xsl != null && xslParams != null && xsl.trim().length() > 0) {
138
        if (ApplyXsl2.processImportSources(new File(xsl), srcDir, new File(binDir, "src"), xslParams))
139
        // return; // error during process
140
        srcDir = new File(binDir, "src");
141
        println ""
142
}
143

    
144
// copy xml+dtd files
145
if (MONITOR != null && MONITOR.isCanceled()) { return MONITOR.done(); }
146
List<File> srcfiles = srcDir.listFiles();
147
if (srcfiles != null)
148
        for (int i = 0 ; i < srcfiles.size() ; i++) {// check XML format, and copy file into binDir
149
                File f = srcfiles.get(i)
150
                if (f.getName().equals("import.xml") || f.getName().matches("metadata\.....?") || f.getName().endsWith(".properties")) {
151
                        srcfiles.remove(i);
152
                        i--;
153
                        continue;
154
                }
155
                if (ValidateXml.test(f)) {
156
                        FileCopy.copy(f, new File(txmDir, f.getName()));
157
                } else {
158
                        println "Won't process file "+f;
159
                }
160
        }
161

    
162
if (txmDir.listFiles() == null) {
163
        println "No txm file to process"
164
        return;
165
}
166

    
167
// filtering
168
/*def xpaths = params.getExcludeXpaths()
169
 if (xpaths != null) {
170
 println "Filtering XML files with xpaths: $xpaths"
171
 for (File infile : txmDir.listFiles()) {
172
 print "."
173
 if (!RemoveTag.xpath(infile, xpaths)) {
174
 println "Failed to filter $infile"
175
 return
176
 }
177
 }
178
 println ""
179
 }*/
180

    
181
//get metadata values from CSV
182
Metadatas metadatas; // text metadata
183

    
184
println "Trying to read metadata from: "+allmetadatasfile
185
if (MONITOR != null && MONITOR.isCanceled()) { return MONITOR.done(); }
186
if (allmetadatasfile.exists()) {
187
        println " Metadata file found: "+allmetadatasfile
188
        File copy = new File(binDir, allmetadatasfile.getName())
189
        if (!FileCopy.copy(allmetadatasfile, copy)) {
190
                println "Error: could not create a copy of metadata file "+allmetadatasfile.getAbsoluteFile();
191
                return;
192
        }
193
        metadatas = new Metadatas(copy, Toolbox.getMetadataEncoding(), Toolbox.getMetadataColumnSeparator(), Toolbox.getMetadataTextSeparator(), 1)
194
} else {
195
        println " No metadata file: "+allmetadatasfile
196
}
197

    
198
if (MONITOR != null && MONITOR.isCanceled()) { return MONITOR.done(); }
199
if (MONITOR != null) MONITOR.worked(5, "IMPORTER")
200
println "-- IMPORTER - Reading source files"
201
def imp = new importer();
202
imp.doValidation(true) // change this to not validate xml
203
boolean skipDoTokenizeStep = params.getSkipTokenization()
204
imp.doTokenize(!skipDoTokenizeStep) // change this, to not tokenize xml
205
imp.setStopIfMalformed(stopIfMalformed);
206
if (!imp.run( srcDir, binDir, txmDir, basename, ignoredElements, lang)) {
207
        println "import process stopped";
208
        return;
209
}
210

    
211
if (MONITOR != null && MONITOR.isCanceled()) { return MONITOR.done(); }
212
if (MONITOR != null) MONITOR.worked(20, "INJECTING METADATA")
213
if (metadatas != null) {
214
        println("-- INJECTING METADATA - "+metadatas.getHeadersList()+" in texts of directory "+new File(binDir,"txm"))
215
        for (File infile : txmDir.listFiles()) {
216
                print "."
217
                File outfile = File.createTempFile("temp", ".xml", infile.getParentFile());
218
                if (!metadatas.injectMetadatasInXml(infile, outfile, "text", null)) {
219
                        outfile.delete();
220
                } else {
221
                        if (!(infile.delete() && outfile.renameTo(infile))) println "Warning can't rename file "+outfile+" to "+infile
222
                        if (!infile.exists()) {
223
                                println "Error: could not replace $infile by $outfile"
224
                                return false;
225
                        }
226
                }
227
        }
228
        println ""
229
}
230
List<File> files = txmDir.listFiles()
231
if (files == null || files.size() == 0) {
232
        return;
233
}
234

    
235
if (MONITOR != null && MONITOR.isCanceled()) { return MONITOR.done(); }
236
if (MONITOR != null) MONITOR.worked(20, "ANNOTATE")
237
println "-- ANNOTATE - Running NLP tools"
238
boolean annotationSuccess = false;
239
if (annotate) {
240
        def engine = Toolbox.getEngineManager(EngineType.ANNOTATION).getEngine("TreeTagger")
241
        if (engine.processDirectory(txmDir, binDir, ["lang":model])) {
242
                annotationSuccess = true;
243
        }
244
}
245

    
246
if (MONITOR != null && MONITOR.isCanceled()) { return MONITOR.done(); }
247
if (MONITOR != null) MONITOR.worked(25, "COMPILING")
248
println "-- COMPILING - Building Search Engine indexes"
249
def c = new compiler();
250
if(debug) c.setDebug();
251
//c.setCwbPath("~/TXM/cwb/bin");
252
c.setOptions(textSortAttribute, normalizeMetadata);
253
c.setAnnotationSuccess(annotationSuccess)
254
c.setLang(lang);
255
if (!c.run(binDir, txmDir, corpusname, null, srcfiles, metadatas)) {
256
        println "import process stopped";
257
        return;
258
}
259

    
260
if (MONITOR != null && MONITOR.isCanceled()) { return MONITOR.done(); }
261

    
262
new File(binDir,"HTML/$corpusname").deleteDir();
263
new File(binDir,"HTML/$corpusname").mkdirs();
264
if (build_edition) {
265

    
266
        println "-- EDITION - Building edition"
267
        if (MONITOR != null) MONITOR.worked(25, "EDITION")
268
        
269
        File outdir = new File(binDir,"/HTML/$corpusname/default/");
270
        outdir.mkdirs();
271
        List<File> filelist = txmDir.listFiles();
272
        Collections.sort(filelist);
273
        def second = 0
274

    
275
        println "Paginating texts: "+filelist
276

    
277
        for (File txmFile : filelist) {
278
                print "."
279
                String txtname = txmFile.getName();
280
                int i = txtname.lastIndexOf(".");
281
                if (i > 0) txtname = txtname.substring(0, i);
282

    
283
                List<String> NoSpaceBefore = LangFormater.getNoSpaceBefore(lang);
284
                List<String> NoSpaceAfter = LangFormater.getNoSpaceAfter(lang);
285

    
286
                Element text = params.addText(corpusElem, txtname, txmFile);
287

    
288
                def ed = new pager(txmFile, outdir, txtname, NoSpaceBefore, NoSpaceAfter, wordsPerPage, basename, page_element);
289
                Element edition = params.addEdition(text, "default", outdir.getAbsolutePath(), "html");
290

    
291
                for (i = 0 ; i < ed.getPageFiles().size();) {
292
                        File f = ed.getPageFiles().get(i);
293
                        String wordid = ed.getIdx().get(i);
294
                        params.addPage(edition, ""+(++i), wordid);
295
                }
296
        }
297
}
298

    
299
if (MONITOR != null && MONITOR.isCanceled()) { return MONITOR.done(); }
300
if (MONITOR != null) MONITOR.worked(20, "FINALIZING")
301
File paramFile = new File(binDir, "import.xml");
302
DomUtils.save(params.root.getOwnerDocument(), paramFile);readyToLoad = true;