Statistics
| Revision:

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

History | View | Annotate | Download (15.4 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.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
                                e.printStackTrace()
128
                        }
129
                }
130

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

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

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

    
154
        public boolean doFacsEditionStep() {
155

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

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

    
165
                def second = 0
166

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

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

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

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

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

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

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

    
206

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

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

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

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

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

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

    
254
                println ""
255
                return true;
256
        }
257

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
460
                return content;
461
        }
462

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