Statistics
| Revision:

root / tmp / org.txm.groovy.core / src / groovy / org / txm / scripts / importer / xtz / XTZPager.groovy @ 1217

History | View | Annotate | Download (15.3 kB)

1
package org.txm.scripts.importer.xtz
2

    
3
import java.io.File;
4
import java.util.ArrayList;
5

    
6
import org.txm.objects.BaseParameters
7
import org.w3c.dom.Element
8

    
9
import org.txm.scripts.importer.*
10
import org.txm.stat.utils.ConsoleProgressBar
11
import org.txm.utils.BundleUtils;
12
import org.txm.utils.io.FileCopy;
13
import org.txm.utils.i18n.*
14
import org.txm.importer.xtz.*
15
import javax.xml.stream.*
16
import org.txm.objects.*
17
import org.txm.importer.ApplyXsl2
18

    
19
class XTZPager extends Pager {
20

    
21
        Project project;
22

    
23
        Element corpusElem;
24
        String lang;
25
        String page_element;
26
        String wordTag;
27
        int wordsPerPage;
28

    
29
        File cssDirectory, jsDirectory, imagesDirectory;
30

    
31
        public XTZPager(ImportModule module) {
32
                super(module, "default");
33

    
34
                project = module.getProject()
35

    
36
                lang = project.getLang();
37
                wordsPerPage = project.getEditionDefinition("default").getWordsPerPage()
38
                page_element = project.getEditionDefinition("default").getPageElement()
39
                wordTag = project.getTokenizerWordElement()
40

    
41
                cssDirectory = new File(module.getSourceDirectory(), "css")
42
                jsDirectory = new File(module.getSourceDirectory(), "js")
43
                imagesDirectory = new File(module.getSourceDirectory(), "images")
44
        }
45

    
46
        public void process(ArrayList<File> files) {
47
                super.process(files);
48

    
49
                if (files == null) {
50
                        files = inputDirectory.listFiles();
51
                        if (files != null) Collections.sort(files);
52
                }
53

    
54
                if (!doDefaultEditionStep()) return;
55
                if (!doFacsEditionStep()) return;
56
                if (!doPostEditionXSLStep()) return;
57

    
58
                isSuccessFul = true;
59
                println ""
60
        }
61

    
62
        public boolean doDefaultEditionStep() {
63

    
64
                boolean build_edition = project.getEditionDefinition("default").getBuildEdition()
65
                if (!build_edition) {
66
                        return true;
67
                }
68

    
69
                def second = 0
70

    
71
                println "-- Building 'default' edition of  ${files.size()} texts..."
72

    
73
                def css = ["css/txm.css", "css/${corpusname}.css"] // default CSS inclusion
74

    
75
                // scan existing css files that must be declared in each HTML page
76
                if (cssDirectory.exists()) {
77
                        def cssFiles = cssDirectory.listFiles();
78
                        if (cssFiles != null)
79
                                for (File cssFile : cssFiles) {
80
                                        if (cssFile.isFile() && !cssFile.isHidden() && cssFile.getName().endsWith(".css"))
81
                                                css << "css/"+cssFile.getName();
82
                                }
83
                }
84

    
85
                ConsoleProgressBar cpb = new ConsoleProgressBar(files.size())
86
                for (File txmFile : files) {
87
                        try {
88
                                cpb.tick()
89
                                String textname = txmFile.getName();
90
                                int i = textname.lastIndexOf(".");
91
                                if (i > 0) textname = textname.substring(0, i);
92

    
93
                                File firstHTMLPageFile = new File(outputDirectory, textname+"_1.html");
94
                                if (firstHTMLPageFile.exists() && firstHTMLPageFile.lastModified() >= txmFile.lastModified()) continue;
95

    
96
                                List<String> NoSpaceBefore = LangFormater.getNoSpaceBefore(lang);
97
                                List<String> NoSpaceAfter = LangFormater.getNoSpaceAfter(lang);
98

    
99
                                Text t = project.getText(textname);
100
                                if (t == null) {
101
                                        t = new Text(project);
102
                                }
103
                                t.setName(textname);
104
                                t.setSourceFile(txmFile)
105
                                t.setTXMFile(txmFile)
106

    
107
                                def ed = new XTZDefaultPagerStep(this, txmFile, textname, NoSpaceBefore, NoSpaceAfter, css);
108
                                if (!ed.process()) {
109
                                        println "Fail to build 'default' edition for text: $txmFile"
110
                                        continue;
111
                                }
112
                                Edition edition = t.getEdition("default")
113
                                if (edition == null) {
114
                                        edition = new Edition(t);
115
                                }
116
                                edition.setName("default");
117
                                edition.setIndex(outputDirectory.getAbsolutePath());
118

    
119
                                for (i = 0 ; i < ed.getPageFiles().size();) {
120
                                        File f = ed.getPageFiles().get(i);
121
                                        String wordid = "w_0";
122
                                if (i < ed.getIdx().size()) wordid = ed.getIdx().get(i);
123
                                        edition.addPage(""+(++i), wordid);
124
                                }
125
                        } catch(Exception e) {
126
                                println "Error: could not create $txmFile 'default' edition: "+e
127
                        }
128
                }
129

    
130
                // copy default TXM css file in the "facs" edition directory
131
                File csshtmlDirectory = new File(outputDirectory, "css")
132
                csshtmlDirectory.mkdirs()
133
                BundleUtils.copyFiles("org.txm.core", "res", "org/txm/css", "txm.css", csshtmlDirectory);
134

    
135
                // copy CSS files in the "default" edition directory
136
                if (cssDirectory.exists()) {
137
                        FileCopy.copyFiles(cssDirectory, csshtmlDirectory)
138
                }
139
                if (jsDirectory.exists()) {
140
                        File jshtmlDirectory = new File(outputDirectory, "js")
141
                        FileCopy.copyFiles(jsDirectory, jshtmlDirectory)
142
                }
143
                if (imagesDirectory.exists()) {
144
                        File imageshtmlDirectory = new File(outputDirectory, "images")
145
                        FileCopy.copyFiles(imagesDirectory, imageshtmlDirectory)
146
                }
147

    
148
                // save changes
149
                println ""
150
                return true;
151
        }
152

    
153
        public boolean doFacsEditionStep() {
154

    
155
                boolean mustBuildFacsEdition = project.getEditionDefinition("facs").getBuildEdition()
156
                if (!mustBuildFacsEdition) return true;
157

    
158
                String imageDirectoryPath = project.getEditionDefinition("facs").getImagesDirectory().trim();
159
                File imageDirectory = new File(imageDirectoryPath);
160
                if (!imageDirectoryPath.startsWith("http") && imageDirectoryPath.length()== 0 && !imageDirectory.exists() && !imageDirectory.isDirectory()) {
161
                        imageDirectory = null;
162
                }
163

    
164
                def second = 0
165

    
166
                println "-- Building 'facs' edition of ${files.size()} texts..."
167
                File newEditionDirectory = new File(htmlDirectory, "facs");
168
                newEditionDirectory.mkdir();
169

    
170
                ConsoleProgressBar cpb = new ConsoleProgressBar(files.size())
171
                for (File txmFile : files) {
172
                        cpb.tick()
173
                        String txtname = txmFile.getName();
174
                        int i = txtname.lastIndexOf(".");
175
                        if (i > 0) txtname = txtname.substring(0, i);
176

    
177
                        File firstHTMLPageFile = new File(newEditionDirectory, txtname+"_1.html");
178
                        if (firstHTMLPageFile.exists() && firstHTMLPageFile.lastModified() >= txmFile.lastModified()) continue;
179

    
180
                        List<String> NoSpaceBefore = LangFormater.getNoSpaceBefore(lang);
181
                        List<String> NoSpaceAfter = LangFormater.getNoSpaceAfter(lang);
182

    
183
                        Text t = project.getText(txtname);
184
                        if (t == null) {
185
                                t = new Text(project);
186
                        }
187
                        t.setName(txtname);
188
                        t.setSourceFile(txmFile)
189
                        t.setTXMFile(txmFile)
190

    
191
                        Edition edition = t.getEdition("facs")
192
                        if (edition == null) {
193
                                edition = new Edition(t);
194
                        }
195
                        edition.setName("facs");
196
                        edition.setIndex(outputDirectory.getAbsolutePath());
197

    
198
                        try {
199
                                def ed = new XTZFacsPagerStep(txmFile, newEditionDirectory, imageDirectory, txtname, corpusname, "pb", "facs", wordTag, debug);
200
                                if (!ed.process()) {
201
                                        println "Fail to build 'facs' edition for text: $txmFile"
202
                                        continue;
203
                                }
204

    
205

    
206
                                def pages = ed.getPageFiles()
207
                                for (i = 0 ; i < pages.size();) {
208
                                        File f = pages[i][0];
209
                                        String wordid = pages[i][1]
210
                                        //TODO replace '""+(++i)' with something that fetch/findout the page 'name'
211
                                        // TODO or move the Edition and Page corpus declaration in the XTZDefaultPagerStep
212
                                        edition.addPage(""+(++i), wordid);
213
                                        //println "add facs page: $f $wordid"
214
                                }
215
                        } catch (Exception e) {
216
                                println "Error while processing $txmFile text: "+e
217
                                e.printStackTrace();
218
                                return false;
219
                        }
220
                }
221

    
222
                if (!imageDirectoryPath.startsWith("http") && imageDirectory != null) { // copy files only if local
223
                        File editionImagesDirectory = new File(newEditionDirectory, "res/images/"+corpusname+"/facs");
224
                        editionImagesDirectory.mkdirs();
225
                        FileCopy.copyFiles(imageDirectory, editionImagesDirectory);
226
                }
227

    
228
                // copy SimpleViewer files in the "facs" edition directory
229
                File jshtmlDirectory = new File(newEditionDirectory, "js")
230
                jshtmlDirectory.mkdirs()
231
                BundleUtils.copyFiles("org.txm.core", "res", "org/txm/js", "viewer", jshtmlDirectory);
232
                BundleUtils.copyFiles("org.txm.core", "res", "org/txm/", "images", newEditionDirectory);
233

    
234
                // copy default TXM css file in the "facs" edition directory
235
                File csshtmlDirectory = new File(newEditionDirectory, "css")
236
                csshtmlDirectory.mkdirs()
237
                BundleUtils.copyFiles("org.txm.core", "res", "org/txm/css", "txm.css", csshtmlDirectory);
238

    
239
                // copy CSS/JS/Images sources files in the "facs" edition directory
240
                if (cssDirectory.exists()) {
241
                        FileCopy.copyFiles(cssDirectory, csshtmlDirectory)
242
                }
243
                if (jsDirectory.exists()) {
244
                        FileCopy.copyFiles(jsDirectory, jshtmlDirectory)
245
                }
246
                if (imagesDirectory.exists()) {
247
                        File imageshtmlDirectory = new File(newEditionDirectory, "images")
248
                        FileCopy.copyFiles(imagesDirectory, imageshtmlDirectory)
249
                }
250

    
251
                project.setDefaultEditionName("default,facs");
252

    
253
                println ""
254
                return true;
255
        }
256

    
257
        /**
258
         * read from $bindir/txm and write the result in $bindir/txm
259
         *
260
         */
261
        public boolean doPostEditionXSLStep() {
262

    
263
                File xslDirectory = new File(module.getSourceDirectory(), "xsl/4-edition")
264
                if (xslDirectory.exists()) {
265

    
266
                        // prepare XSL parameters
267
                        def xslParams = module.getProject().getXsltParameters();
268
                        String s = module.getProject().getEditionDefinition("default").getWordsPerPage()
269
                        if (s != null && s.length() > 0)
270

    
271
                        // shared XSL parameters
272
                        xslParams["number-words-per-page"] = Integer.parseInt(s);
273
                        xslParams["pagination-element"] = module.getProject().getEditionDefinition("default").getPageElement()
274
                        xslParams["import-xml-path"] = module.getProject().getProjectDirectory()
275
                        //println "XSL PARAMS: "+xslParams
276

    
277
                        def xslFiles = xslDirectory.listFiles()
278
                        xslFiles = xslFiles.sort() { f -> 
279
                                try {
280
                                return Integer.parseInt(f.getName().substring(0, f.getName().indexOf("-")))
281
                                } catch(Exception e) {}
282
                                return -1;
283
                        }
284
                        def editionsCreated = [:]
285
                        for (File xslFile : xslFiles) {
286
                                if (xslFile.isDirectory() || xslFile.isHidden() || !xslFile.getName().endsWith(".xsl")) continue;
287
                                if (!xslFile.getName().matches("[1-9]{1.3}-.+")) continue;
288

    
289
                                String xslName = xslFile.getName().substring(2); // remove the "1-", "2-", etc.
290
                                int idx2 = xslName.indexOf(".")
291
                                if (idx2 > 0) xslName = xslName.substring(0, idx2)
292
                                else {
293
                                        println "$xslFile is not a '.xsl' file"
294
                                        continue;
295
                                }
296
                                int idx3 = xslName.indexOf("-")
297
                                if (idx3 < 0) {
298
                                        println "$xslFile file does not follow the '{Number}-{editionName}-{step}.xsl' name pattern"
299
                                        continue;
300
                                }
301
                                String pagerStep = xslName.substring(idx3 + 1);
302
                                String editionName = xslName.substring(0, idx3);
303

    
304
                                int idx = editionName.indexOf(".")
305
                                if (idx > 0) editionName = editionName.substring(0, idx);
306
                                println "-- Building '$editionName' XSL edition with step '$pagerStep'..."
307

    
308
                                File newEditionDirectory = new File(htmlDirectory, editionName);
309
                                xslParams["output-directory"] = newEditionDirectory.toURI().toString()
310

    
311
                                if (editionsCreated[editionName] == null) { // first XSL, replace an edition
312
                                        editionsCreated[editionName] = xslFile
313
                                        //if (!importModule.isUpdatingCorpus()) {
314
                                        //TODO: optimisation if update is enable,
315
                                        newEditionDirectory.deleteDir(); // delete previous edition if any
316
                                        //}
317
                                        newEditionDirectory.mkdir()
318

    
319
                                        boolean deleteOutputFiles = "pager" == pagerStep;
320
                                        if (ApplyXsl2.processImportSources(xslFile, inputDirectory, newEditionDirectory, xslParams, deleteOutputFiles)) {
321
                                                println ""
322
                                        } else {
323
                                                reason = "Fail to apply edition XSL: $xslFile"
324
                                                return false;
325
                                        }
326

    
327
                                        // copy CSS files in the newEditionDirector edition directory
328
                                        if (cssDirectory.exists()) {
329
                                                File csshtmlDirectory = new File(newEditionDirectory, "css")
330
                                                FileCopy.copyFiles(cssDirectory, csshtmlDirectory)
331
                                        }
332
                                        if (jsDirectory.exists()) {
333
                                                File jshtmlDirectory = new File(newEditionDirectory, "js")
334
                                                FileCopy.copyFiles(jsDirectory, jshtmlDirectory)
335
                                        }
336
                                        if (imagesDirectory.exists()) {
337
                                                File imageshtmlDirectory = new File(newEditionDirectory, "images")
338
                                                FileCopy.copyFiles(imagesDirectory, imageshtmlDirectory)
339
                                        }
340
                                } else { // N+1 XSL working with HTML files
341
                                        def htmlFiles = newEditionDirectory.listFiles()
342
                                        htmlFiles.sort()
343

    
344
                                        if (ApplyXsl2.processImportSources(xslFile, htmlFiles, xslParams)) {
345
                                                if ("pager".equals(pagerStep)) {
346
                                                        // delete the one page HTML files only if the XSL step is "pager"
347
                                                        for (File f : htmlFiles) f.delete();
348
                                                }
349
                                                //        println ""
350
                                        } else {
351
                                                reason = "Fail to apply edition XSL: $xslFile"
352
                                                return false;
353
                                        }
354
                                }
355
                        }
356

    
357
                        // UPDATE import.xml: for each XML-TXM file, we must retrieve the first word ID from the XSL output files
358
                        //println "retrieve word ids from $inputDirectory"
359
                        println "-- Fetching page word IDs..."
360
                        ConsoleProgressBar cpb = new ConsoleProgressBar(editionsCreated.keySet().size())
361
                        for (String editionName : editionsCreated.keySet()) {
362
                                cpb.tick()
363

    
364
                                File newEditionDirectory = new File(htmlDirectory, editionName);
365
                                File xslFile = editionsCreated[editionName]
366
                                for (File txmFile : inputDirectory.listFiles()) {
367
                                        if (txmFile.isDirectory()) continue;
368
                                        String textName = txmFile.getName()
369
                                        int idx4 = textName.indexOf(".")
370
                                        if (idx4 > 0) textName = textName.substring(0, idx4);
371

    
372
                                        getFirstWordIDs(textName, editionName, newEditionDirectory, xslFile, txmFile);
373
                                }
374
                        }
375
                        println ""
376
                }
377
                return true;
378
        }
379

    
380
        private void getFirstWordIDs(String textName, String editionName, File newEditionDirectory, File xslFile, File txmFile) {
381
                //                println "call getFirstWordIDs textName=$textName editionName=$editionName dir=$newEditionDirectory xsl=$xslFile"
382
                Text t = project.getText(textName);
383
                if (t == null) {
384
                        t = new Text(project);
385
                }
386
                t.setName(textName);
387
                t.setSourceFile(txmFile)
388
                t.setTXMFile(txmFile)
389

    
390
                Edition edition = t.getEdition(editionName)
391
                if (edition == null) {
392
                        edition = new Edition(t);
393
                }
394
                edition.setName(editionName);
395
                edition.setIndex(outputDirectory.getAbsolutePath());
396

    
397
                LinkedHashMap<File, String> words = new LinkedHashMap<File, String>()
398
                def files = []
399
                newEditionDirectory.eachFile() {it -> if (it.isFile()) files << it}
400

    
401
                files.sort() { f1, f2 ->
402
                        String s1 = f1.getName()
403
                        String s2 = f2.getName()
404
                        int n1 = Integer.parseInt(s1.substring(s1.lastIndexOf("_")+1, s1.lastIndexOf(".")))
405
                        int n2 = Integer.parseInt(s2.substring(s2.lastIndexOf("_")+1, s2.lastIndexOf(".")))
406
                        return n1 - n2;
407
                }
408

    
409
                for (File f : files) {
410
                        String pagename = f.getName();
411
                        if (pagename.startsWith(textName+"_")) { // this is a page
412
                                String firstWordID = getMetaContent(f);
413
                                pagename = pagename.substring((textName+"_").length(), pagename.indexOf(".html")) // !!!!
414
                                edition.addPage(pagename, firstWordID)
415
                        }
416
                }
417
        }
418

    
419
        public static String getMetaContent(File f) {
420
                def inputData = f.toURI().toURL().openStream();
421
                def factory = XMLInputFactory.newInstance();
422
                factory.setProperty("javax.xml.stream.supportDTD", false); // ignore the DTD declared in doctype
423

    
424
                def parser = factory.createXMLStreamReader(inputData);
425
                String META = "meta"
426
                String BODY = "body"
427
                String NAME = "name"
428
                String DESCRIPTION = "txm:first-word-id"
429
                String CONTENT = "content"
430

    
431
                String content = "";
432
                String desc = "";
433

    
434
                for (int event = parser.next(); event != XMLStreamConstants.END_DOCUMENT; event = parser.next()) {
435
                        if (event == XMLStreamConstants.START_ELEMENT) { // start elem
436

    
437
                                if (META.equals(parser.getLocalName())) { // ana elem
438
                                        desc = "";
439
                                        // fetch attribute values
440
                                        for (int i = 0 ; i < parser.getAttributeCount(); i++) { // scan attributes
441
                                                if (NAME.equals(parser.getAttributeLocalName(i))) { // found @name
442
                                                        desc = parser.getAttributeValue(i)
443
                                                } else if (CONTENT.equals(parser.getAttributeLocalName(i))) { // found @content
444
                                                        content = parser.getAttributeValue(i)
445
                                                }
446
                                        }
447
                                        if (DESCRIPTION.equals(desc)) { // stop now
448
                                                break;
449
                                        }
450
                                } else if (BODY.equals(parser.getLocalName())) { // no need to go further, meta@name="description" not found :(
451
                                        content = "";
452
                                        break;
453
                                }
454
                        }
455
                }
456
                parser.close()
457

    
458
                return content;
459
        }
460

    
461
        public static void main(def args) {
462
                println "RESULT: "+getMetaContent(new File("/home/mdecorde/TXM/corpora/QGRAALXTZ/HTML/QGRAALXTZ/default", "qgraal_cm_test201510_page_160_2.html"))
463
        }
464
}