Statistics
| Revision:

root / tmp / org.txm.core / src / groovy / org / txm / importer / factiva / factivaLoader.groovy @ 187

History | View | Annotate | Download (10.1 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: 2012-02-13 11:42:24 +0100 (lun., 13 févr. 2012) $
25
// $LastChangedRevision: 2126 $
26
// $LastChangedBy: mdecorde $
27
//
28
package org.txm.importer.factiva;
29

    
30
import javax.xml.stream.XMLStreamReader;
31

    
32
import org.txm.importer.ApplyXsl2;
33
import org.txm.importer.Factiva2XmlTxm;
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;
38
import org.txm.objects.*;
39
import org.txm.utils.*;
40
import org.txm.*;
41
import org.txm.scripts.teitxm.*;
42
import org.txm.utils.i18n.*;
43
import org.txm.metadatas.*;
44

    
45
import javax.xml.stream.*;
46

    
47
import org.w3c.dom.Element
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/TESTS/factiva/import.xml"))
58
        params.load()
59
        if (!org.txm.Toolbox.isInitialized()) {
60

    
61
                Toolbox.setParam(Toolbox.INSTALL_DIR,new File("/usr/lib/TXM"));
62
                Toolbox.setParam(Toolbox.TREETAGGER_INSTALL_PATH,new File(userDir,"treetagger"));
63
                Toolbox.setParam(Toolbox.TREETAGGER_MODELS_PATH,new File(userDir,"treetagger/models"));
64
                Toolbox.setParam(Toolbox.METADATA_ENCODING, "UTF-8");
65
                Toolbox.setParam(Toolbox.METADATA_COLSEPARATOR, ",");
66
                Toolbox.setParam(Toolbox.METADATA_TXTSEPARATOR, "\"");
67
                Toolbox.setParam(Toolbox.USER_TXM_HOME, new File(System.getProperty("user.home"), "TXM"));
68
        }
69
}
70
if (params == null) { println "no parameters. Aborting"; return; }
71

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

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

    
95
File txmDir = new File(binDir,"txm/$corpusname");
96
txmDir.deleteDir();
97
txmDir.mkdirs();
98

    
99
File propertyFile = new File(rootDir, "import.properties")//default
100
Properties props = new Properties();
101
String[] metadatasToKeep;
102

    
103
String textSortAttribute = null;
104
String paginationElement = null;
105
boolean normalizeMetadata = false;
106
String ignoredElements = null;
107
boolean stopIfMalformed = false;
108

    
109
println "Trying to read import properties file: "+propertyFile
110
if (propertyFile.exists() && propertyFile.canRead()) {
111
        InputStreamReader input = new InputStreamReader(new FileInputStream(propertyFile) , "UTF-8");
112
        props.load(input);
113
        input.close();
114
        if(props.getProperty("sortmetadata") != null)
115
                textSortAttribute = props.get("sortmetadata").toString();
116
        if(props.getProperty("editionpage") != null)
117
                paginationElement = props.get("editionpage").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 " edition page tag: "+paginationElement
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 Factiva2XMLTXM
136
println "Factiva -> xml/w"
137
File factivaOutDir = new File(binDir, "src")
138
new Factiva2XmlTxm().run(srcDir, factivaOutDir.getAbsolutePath());
139
if (factivaOutDir.listFiles() == null) {
140
        println "Error: no file to process"
141
        return;
142
}
143
srcDir = factivaOutDir;
144

    
145
// Apply XSL
146
if (MONITOR != null && MONITOR.isCanceled()) { return MONITOR.done(); }
147
if (MONITOR != null) MONITOR.worked(1, "APPLYING XSL")
148
if (xsl != null && xslParams != null && xsl.trim().length() > 0) {
149
        if (ApplyXsl2.processImportSources(new File(xsl), srcDir, new File(binDir, "src"), xslParams))
150
        // return; // error during process
151
        srcDir = new File(binDir, "src");
152
        println ""
153
}
154

    
155
// copy txm files
156
List<File> srcfiles = srcDir.listFiles();
157
for (int i = 0 ; i < srcfiles.size() ; i++) {// check XML format, and copy file into binDir
158
        File f = srcfiles.get(i)
159
        if (f.getName().equals("import.xml") || f.getName().equals("metadata.csv") || f.getName().endsWith(".properties")) {
160
                srcfiles.remove(i);
161
                i--;
162
                continue;
163
        }
164
        if (ValidateXml.test(f)) {
165
                FileCopy.copy(f, new File(txmDir, f.getName()));
166
        } else {
167
                println "Won't process file "+f;
168
        }
169
}
170

    
171
if (txmDir.listFiles() == null) {
172
        println "No txm file to process"
173
        return;
174
}
175

    
176
//get metadata values from CSV
177
Metadatas metadatas; // text metadata
178
println "Trying to read metadata from: "+allmetadatasfile
179
if (allmetadatasfile.exists()) {
180
        File copy = new File(binDir, "metadata.csv")
181
        if (!FileCopy.copy(allmetadatasfile, copy)) {
182
                println "Error: could not create a copy of metadata file "+allmetadatasfile.getAbsoluteFile();
183
                return;
184
        }
185
        metadatas = new Metadatas(copy, Toolbox.getParam(Toolbox.METADATA_ENCODING), Toolbox.getParam(Toolbox.METADATA_COLSEPARATOR), Toolbox.getParam(Toolbox.METADATA_TXTSEPARATOR), 1)
186
} else
187
        println "no metadata file: "+allmetadatasfile
188

    
189
if (MONITOR != null) MONITOR.worked(1, "IMPORTER")
190
if (MONITOR != null && MONITOR.isCanceled()) { return MONITOR.done(); }
191
println "-- IMPORTER - Reading source files"
192
def imp = new importer();
193
imp.doValidation(true) // change this to not validate xml
194
imp.doTokenize(true) // change this, to not tokenize xml
195
imp.setStopIfMalformed(stopIfMalformed);
196
if (!imp.run( srcDir, binDir, txmDir, basename, null, lang)) {
197
        println "import process stopped";
198
        return;
199
}
200

    
201
if (MONITOR != null) MONITOR.worked(20, "INJECTING METADATA")
202
if (MONITOR != null && MONITOR.isCanceled()) { return MONITOR.done(); }
203
println "-- INJECTING METADATA - from csv file: "+allmetadatasfile
204
if (metadatas != null) {
205
        println("Injecting metadata: "+metadatas.getHeadersList()+" in texts of directory "+new File(binDir,"txm"))
206
        for (File infile : txmDir.listFiles()) {
207
                print "."
208
                File outfile = File.createTempFile("temp", ".xml", infile.getParentFile());
209
                if (!metadatas.injectMetadatasInXml(infile, outfile, "text", null)) {
210
                        outfile.delete();
211
                } else {
212
                        if (!(infile.delete() && outfile.renameTo(infile))) println "Warning can't rename file "+outfile+" to "+infile
213
                        if (!infile.exists()) {
214
                                println "Error: could not replace $infile by $outfile"
215
                                return false;
216
                        }
217
                }
218
        }
219
        println ""
220
}
221

    
222
List<File> files = txmDir.listFiles()
223
if (files == null || files.size() == 0) {
224
        return;
225
}
226

    
227
if (MONITOR != null && MONITOR.isCanceled()) { return MONITOR.done(); }
228
if (MONITOR != null) MONITOR.worked(10, "ANNOTATE")
229
println "-- ANNOTATE - Running NLP tools"
230
boolean annotationSuccess = false;
231
if (annotate && new Annotate().run(binDir, txmDir, model+".par")) {
232
        annotationSuccess = true;
233
}
234

    
235
if (MONITOR != null && MONITOR.isCanceled()) { return MONITOR.done(); }
236
if (MONITOR != null) MONITOR.worked(25, "COMPILING")
237
println "-- COMPILING - Building Search Engine indexes"
238
def c = new compiler();
239
if(debug) c.setDebug();
240
//c.setCwbPath("~/TXM/cwb/bin");
241
c.setOptions(textSortAttribute, normalizeMetadata);
242
c.setAnnotationSuccess(annotationSuccess)
243
c.setLang(lang);
244
if (!c.run(binDir, txmDir, corpusname, null, srcfiles, metadatas)) {
245
        println "import process stopped";
246
        return;
247
}
248

    
249
if (MONITOR != null && MONITOR.isCanceled()) { return MONITOR.done(); }
250

    
251
new File(binDir,"HTML/$corpusname").deleteDir();
252
new File(binDir,"HTML/$corpusname").mkdirs();
253
if (build_edition) {
254

    
255
        println "-- EDITION - Building edition"
256
        if (MONITOR != null) MONITOR.worked(20, "EDITION")
257
        
258
        File outdir = new File(binDir,"/HTML/$corpusname/default/");
259
        outdir.mkdirs();
260
        List<File> filelist = txmDir.listFiles();
261
        Collections.sort(filelist);
262
        def second = 0
263

    
264
        println "Paginating texts: "
265

    
266
        for (File txmFile : filelist) {
267
                print "."
268
                String txtname = txmFile.getName();
269
                int i = txtname.lastIndexOf(".");
270
                if(i > 0) txtname = txtname.substring(0, i);
271

    
272
                List<String> NoSpaceBefore = LangFormater.getNoSpaceBefore(lang);
273
                List<String> NoSpaceAfter = LangFormater.getNoSpaceAfter(lang);
274

    
275
                Element text = params.addText(corpusElem, txtname, txmFile);
276

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

    
280
                for (i = 0 ; i < ed.getPageFiles().size();) {
281
                        File f = ed.getPageFiles().get(i);
282
                        String wordid = ed.getIdx().get(i);
283
                        params.addPage(edition, ""+(++i), wordid);
284
                }
285
        }
286
}
287

    
288
if (MONITOR != null) MONITOR.worked(20, "FINALIZING")
289
File paramFile = new File(binDir, "import.xml");
290
DomUtils.save(params.root.getOwnerDocument(), paramFile);readyToLoad = true;