Statistics
| Revision:

root / tmp / org.txm.groovy.core / src / groovy / org / txm / importer / transcriber / transcriberLoader.groovy @ 945

History | View | Annotate | Download (11.4 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
// This file is part of the TXM platform.
24
//
25
// The TXM platform is free software: you can redistribute it and/or modif y
26
// it under the terms of the GNU General Public License as published by
27
// the Free Software Foundation, either version 3 of the License, or
28
// (at your option) any later version.
29
//
30
// The TXM platform is distributed in the hope that it will be useful,
31
// but WITHOUT ANY WARRANTY; without even the implied warranty of
32
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
33
// GNU General Public License for more details.
34
//
35
// You should have received a copy of the GNU General Public License
36
// along with the TXM platform.  If not, see <http://www.gnu.org/licenses/>.
37
//
38
//
39
//
40
// $LastChangedDate:$
41
// $LastChangedRevision:$
42
// $LastChangedBy:$
43
//
44
package org.txm.importer.transcriber;
45

    
46
import java.io.File;
47
import org.txm.importer.xmltxm.*;
48
import org.txm.*;
49
import org.txm.core.engines.*;
50
import org.txm.objects.*;
51
import org.txm.utils.i18n.*;
52
import org.txm.utils.*;
53
import org.txm.importer.*;
54
import org.txm.metadatas.*;
55
import org.txm.utils.io.FileCopy;
56
import org.w3c.dom.Element
57
import org.txm.utils.xml.DomUtils;
58

    
59
//PARAMETERS
60
boolean removeInterviewer = false;//if true the transcription of speakers (en1 and enq2) defined in metadatas file will be ignored
61
boolean includeComments = false;
62
boolean ignoreTranscriberMetadata = false;
63
int csvHeaderNumber = 1;
64
int maxlines = 200;
65

    
66
String userDir = System.getProperty("user.home");
67

    
68
def MONITOR;
69
boolean debug = org.txm.utils.logger.Log.isPrintingErrors();
70
BaseParameters params;
71
try {params = paramsBinding;MONITOR=monitor} catch (Exception)
72
{        println "DEV MODE";//exception means we debug
73
        debug = true
74
        params = new BaseParameters(new File(userDir, "xml/anapovoas/import.xml"))
75
        params.load()
76
        if (!org.txm.Toolbox.isInitialized()) {
77

    
78
                Toolbox.setParam(Toolbox.INSTALL_DIR,new File("/usr/lib/TXM"));
79
                Toolbox.setParam(Toolbox.TREETAGGER_MODELS_PATH,new File(userDir,"treetagger/models"));
80
                Toolbox.setParam(Toolbox.METADATA_ENCODING, "UTF-8");
81
                Toolbox.setParam(Toolbox.METADATA_COLSEPARATOR, "\t");
82
                Toolbox.setParam(Toolbox.METADATA_TXTSEPARATOR, "");
83
                Toolbox.setParam(Toolbox.USER_TXM_HOME, new File(System.getProperty("user.home"), "TXM"));
84
        }
85
}
86
if (params == null) { println "no parameters. Aborting"; return; }
87

    
88
String corpusname = params.getCorpusName();
89
Element corpusElem = params.corpora.get(corpusname);
90
String basename = params.name;
91
String rootDir = params.rootDir;
92
String lang = corpusElem.getAttribute("lang");
93
String model = lang
94
String encoding = corpusElem.getAttribute("encoding");
95
boolean annotate = "true" == corpusElem.getAttribute("annotate");
96
String xsl = params.getXsltElement(corpusElem).getAttribute("xsl")
97
def xslParams = params.getXsltParams(corpusElem);
98
int wordsPerPage = params.getWordsPerPage("default")
99
String page_element = params.getPageElement("default")
100
boolean build_edition = params.getDoEdition("default")
101

    
102
File srcDir = new File(rootDir);
103
File binDir = new File(Toolbox.getTxmHomePath(),"corpora/"+basename);
104
binDir.deleteDir();
105
binDir.mkdirs();
106
if (!binDir.exists()) {
107
        println "Could not create binDir "+binDir
108
        return;
109
}
110

    
111
File txmDir = new File(binDir,"txm/$corpusname");
112
txmDir.deleteDir();
113
txmDir.mkdirs();
114

    
115
//get metadata values from CSV
116
Metadatas metadatas; // text metadata
117
File allmetadatasfile = new File(srcDir, "metadata.csv");
118
println "Trying to read metadatas values from: "+allmetadatasfile
119
if (allmetadatasfile.exists()) {
120
        File copy = new File(binDir, "metadata.csv")
121
        if (!FileCopy.copy(allmetadatasfile, copy)) {
122
                println "Error: could not create a copy of metadata file "+allmetadatasfile.getAbsoluteFile();
123
                return;
124
        }
125
        metadatas = new Metadatas(copy, Toolbox.getMetadataEncoding(), 
126
                Toolbox.getMetadataColumnSeparator(), 
127
                Toolbox.getMetadataTextSeparator(), 1)
128
}
129
else
130
        println "no metadata file: "+allmetadatasfile
131

    
132
File propertyFile = new File(srcDir, "import.properties")//default
133
Properties props = new Properties();
134
String[] metadatasToKeep;
135
if (propertyFile.exists() && propertyFile.canRead()) {
136
        FileInputStream input = new FileInputStream(propertyFile);
137
        props.load(input);
138
        input.close();
139

    
140
        if (props.getProperty("removeInterviewer") != null)
141
                removeInterviewer = Boolean.parseBoolean(props.get("removeInterviewer").toString());
142
        if (props.getProperty("ignoreTranscriberMetadata") != null)
143
                ignoreTranscriberMetadata = Boolean.parseBoolean(props.get("ignoreTranscriberMetadata").toString());
144
        if (props.getProperty("metadataList") != null)
145
                metadatasToKeep = props.get("metadataList").toString().split("|");
146
        if (props.getProperty("csvHeaderNumber") != null)
147
                csvHeaderNumber = props.get("csvHeaderNumber").toString().split("|");
148
        //if (props.getProperty("includeComments") != null)
149
        //        includeComments = props.get("includeComments").toString();
150

    
151
        println "import properties: "
152
        println " removeInterviewer: "+removeInterviewer
153
        println " ignoreTranscriberMetadata: "+ignoreTranscriberMetadata
154
        println " metadataToKeep: "+metadatasToKeep
155
        println " ignored csvHeaderSize: "+csvHeaderNumber
156
        //println " includeComments: "+includeComments
157
}
158

    
159
// Apply XSL
160
if (MONITOR != null && MONITOR.isCanceled()) { return MONITOR.done(); }
161
if (MONITOR != null) MONITOR.worked(1, "XSL")
162
if (xsl != null && xsl.trim().length() > 0) {
163
        if (ApplyXsl2.processImportSources(new File(xsl), srcDir, new File(binDir, "src")))
164
                srcDir = new File(binDir, "src");
165
        println ""
166
}
167

    
168
try {
169
        // select only trs files
170
        String ext = "trs";
171
        ArrayList<File> trsfiles = srcDir.listFiles(); //find all trs files
172
        if (trsfiles  == null) {
173
                println ("No files in "+srcDir.getAbsolutePath())
174
                return false;
175
        }
176
        for (int i = 0 ; i < trsfiles.size() ; i++) {
177
                File f = trsfiles.get(i);
178
                if (!f.getName().endsWith(ext) || !f.canRead() || f.isHidden()) {
179
                        trsfiles.remove(i)
180
                        i--;
181
                }
182
        }
183

    
184
        if (trsfiles.size() == 0) {
185
                println ("No transcription file (*.trs) found in "+srcDir.getAbsolutePath()+". Aborting.")
186
                return false;
187
        }
188

    
189
        if (MONITOR != null) MONITOR.worked(1, "IMPORTER")
190
        if (MONITOR != null && MONITOR.isCanceled()) { return MONITOR.done(); }
191
        println "-- IMPORTER"
192
        def imp = new importer(trsfiles, binDir, txmDir, metadatas, lang) //put result in the txm folder of binDir
193
        if (!imp.run()) {
194
                println "Failed to prepare files - Aborting";
195
                return;
196
        }
197
        if (MONITOR != null) MONITOR.worked(20)
198

    
199
        println "-- Xml Validation"
200
        if (MONITOR != null && MONITOR.isCanceled()) { return MONITOR.done(); }
201
        for (File infile : txmDir.listFiles()) {
202
                if (!ValidateXml.test(infile)) {
203
                        println "$infile : Validation failed";
204
                        infile.delete();
205
                }
206
        }
207

    
208
        if (MONITOR != null) MONITOR.worked(5)
209
        if (MONITOR != null && MONITOR.isCanceled()) { return MONITOR.done(); }
210
        println "-- Remove interviewer: "+removeInterviewer
211
        if (removeInterviewer)         {
212
                if (metadatas == null) {
213
                        println "Can't remove interviewer without a metadata.csv file defining who are the interviewers."
214
                } else {
215
                        println "Removing some speakers in "+txmDir.listFiles().length+" file(s)"
216
                        for (File infile : txmDir.listFiles()) {
217
                                String filename = infile.getName();
218
                                int idx = filename.indexOf(".xml");
219
                                if (idx > 0)
220
                                        filename = filename.substring(0, idx);
221

    
222
                                ArrayList<Pair<String, String>> metas = metadatas.get(filename)
223
                                //println "filename=$filename metas= $metas"
224
                                for (Pair p : metas) {
225
                                        if (p.getFirst().startsWith("enq")) {
226
                                                new RemoveSpeaker(infile, infile, p.getFirst())
227
                                        }
228
                                }
229
                        }
230
                }
231
        }
232

    
233
        if (MONITOR != null && MONITOR.isCanceled()) { return MONITOR.done(); }
234
        if (MONITOR != null) MONITOR.worked(20, "ANNOTATE")
235
        println "-- ANNOTATE - Running NLP tools"
236
        boolean annotationSuccess = false;
237
if (annotate) {
238
        def engine = Toolbox.getEngineManager(EngineType.ANNOTATION).getEngine("TreeTagger")
239
        if (engine.processDirectory(txmDir, binDir, ["lang":model])) {
240
                annotationSuccess = true;
241
        }
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
        trsfiles = txmDir.listFiles();
248

    
249
        def comp = new compiler()
250
        if(debug) comp.setDebug();
251
        comp.removeInterviewers(removeInterviewer);
252
        comp.setIgnoreTranscriberMetadata(ignoreTranscriberMetadata);
253
        comp.setAnnotationSucces(annotationSuccess)
254
        if (!comp.run(trsfiles, corpusname, "default", binDir)) {
255
                println "Failed to compile files";
256
                return;
257
        }
258
        
259
        if (MONITOR != null && MONITOR.isCanceled()) { return MONITOR.done(); }
260
        
261
        File htmlDir = new File(binDir,"HTML/$corpusname");
262
        htmlDir.deleteDir()
263
        htmlDir.mkdirs();
264
        if (build_edition) {
265
                
266
                if (MONITOR != null) MONITOR.worked(20, "EDITION")
267
                println "-- EDITION - Building editions"
268
                
269
                List<File> filelist = txmDir.listFiles();
270
                Collections.sort(filelist);
271
                def second = 0
272

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

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

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

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

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

    
294
                        if (ed.getPageFiles().size() > 0) {
295
                                Element editionBD = params.addEdition(text, "onepage", htmlDir.getAbsolutePath(), "html");
296
                                params.addPage(editionBD, "1", ed.getIndexes().get(0));
297
                        }
298
                }
299

    
300
                //copy transcriber.css
301
                File cssfile = new File(Toolbox.getTxmHomePath(), "css/transcriber.css")
302
                if (cssfile.exists() && htmlDir.exists()) {
303
                        FileCopy.copy(cssfile, new File(htmlDir, "transcriber.css"));
304
                        FileCopy.copy(cssfile, new File(htmlDir, "onepage/transcriber.css"));
305
                        FileCopy.copy(cssfile, new File(htmlDir, "default/transcriber.css"));
306
                }
307
        }
308
}
309
catch (Exception e){org.txm.utils.logger.Log.printStackTrace(e);}
310

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