Statistics
| Revision:

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

History | View | Annotate | Download (10.7 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.*;
42
import org.txm.scripts.teitxm.*;
43
import org.txm.utils.i18n.*;
44
import org.txm.metadatas.*;
45
import javax.xml.stream.*;
46
import org.w3c.dom.Element
47
import org.txm.utils.xml.DomUtils;
48

    
49
String userDir = System.getProperty("user.home");
50

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

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

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

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

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

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

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

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

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

    
133
File allmetadatasfile = new File(srcDir, "metadata.csv");
134

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

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

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

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

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

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

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

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

    
236
if (MONITOR != null && MONITOR.isCanceled()) { return MONITOR.done(); }
237
if (MONITOR != null) MONITOR.worked(20, "ANNOTATE")
238
println "-- ANNOTATE - Running NLP tools"
239
boolean annotationSuccess = false;
240
if (annotate && new Annotate().run(binDir, txmDir, model+".par")) {
241
        annotationSuccess = true;
242
}
243

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

    
258
if (MONITOR != null && MONITOR.isCanceled()) { return MONITOR.done(); }
259

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

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

    
273
        println "Paginating texts: "+filelist
274

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

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

    
284
                Element text = params.addText(corpusElem, txtname, txmFile);
285

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

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

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