Statistics
| Revision:

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

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.scripts.importer.transcriber;
45

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
245
        if (MONITOR != null && MONITOR.isCanceled()) { return MONITOR.done(); }
246
        if (MONITOR != null) MONITOR.worked(25, "COMPILING")
247
        println "--COMPILING - Building Search Engine indexes"
248
        trsfiles = txmDir.listFiles();
249

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

    
274
                println "Paginating texts: "
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, htmlDir, txtname, NoSpaceBefore, NoSpaceAfter, wordsPerPage, basename, page_element, metadatas);
287
                        Element edition = params.addEdition(text, "default", htmlDir.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
                        if (ed.getPageFiles().size() > 0) {
296
                                Element editionBD = params.addEdition(text, "onepage", htmlDir.getAbsolutePath(), "html");
297
                                params.addPage(editionBD, "1", ed.getIndexes().get(0));
298
                        }
299
                }
300

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

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