Statistics
| Revision:

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

History | View | Annotate | Download (15.1 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
import org.txm.scripts.importer.*
9
import org.txm.stat.utils.ConsoleProgressBar
10
import org.txm.utils.BundleUtils;
11
import org.txm.utils.io.FileCopy;
12
import org.txm.utils.i18n.*
13
import org.txm.importer.xtz.*
14
import javax.xml.stream.*
15
import org.txm.objects.*
16

    
17
class XTZPager extends Pager {
18

    
19
        Project project;
20

    
21
        Element corpusElem;
22
        String lang;
23
        String page_element;
24
        String wordTag;
25
        int wordsPerPage;
26

    
27
        File cssDirectory, jsDirectory, imagesDirectory;
28

    
29
        public XTZPager(ImportModule module) {
30
                super(module, "default");
31

    
32
                project = module.getProject()
33

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

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

    
44
        public void process(ArrayList<File> files) {
45
                super.process(files);
46

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

    
52
                if (!doDefaultEditionStep()) return;
53
                if (!doFacsEditionStep()) return;
54
                if (!doPostEditionXSLStep()) return;
55

    
56
                isSuccessFul = true;
57
                println ""
58
        }
59

    
60
        public boolean doDefaultEditionStep() {
61

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

    
67
                def second = 0
68

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

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

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

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

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

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

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

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

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

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

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

    
145
                // save changes
146
                println ""
147
                return true;
148
        }
149

    
150
        public boolean doFacsEditionStep() {
151

    
152
                boolean mustBuildFacsEdition = project.getEditionDefinition("facs").getBuildEdition()
153
                if (!mustBuildFacsEdition) return true;
154

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

    
161
                def second = 0
162

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

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

    
174
                        File firstHTMLPageFile = new File(newEditionDirectory, txtname+"_1.html");
175
                        if (firstHTMLPageFile.exists() && firstHTMLPageFile.lastModified() >= txmFile.lastModified()) continue;
176

    
177
                        List<String> NoSpaceBefore = LangFormater.getNoSpaceBefore(lang);
178
                        List<String> NoSpaceAfter = LangFormater.getNoSpaceAfter(lang);
179

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

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

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

    
202

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

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

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

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

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

    
248
                project.setDefaultEditionName("default,facs");
249

    
250
                println ""
251
                return true;
252
        }
253

    
254
        /**
255
         * read from $bindir/txm and write the result in $bindir/txm
256
         *
257
         */
258
        public boolean doPostEditionXSLStep() {
259

    
260
                File xslDirectory = new File(module.getSourceDirectory(), "xsl/4-edition")
261
                if (xslDirectory.exists()) {
262

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

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

    
274
                        def xslFiles = xslDirectory.listFiles()
275
                        xslFiles.sort()
276
                        def editionsCreated = [:]
277
                        for (File xslFile : xslFiles) {
278
                                if (xslFile.isDirectory() || xslFile.isHidden() || !xslFile.getName().endsWith(".xsl")) continue;
279
                                if (!xslFile.getName().matches("[1-9]-.+")) continue;
280

    
281
                                String xslName = xslFile.getName().substring(2); // remove the "1-", "2-", etc.
282
                                int idx2 = xslName.indexOf(".")
283
                                if (idx2 > 0) xslName = xslName.substring(0, idx2)
284
                                else {
285
                                        println "$xslFile is not a '.xsl' file"
286
                                        continue;
287
                                }
288
                                int idx3 = xslName.indexOf("-")
289
                                if (idx3 < 0) {
290
                                        println "$xslFile file does not follow the '{Number}-{editionName}-{step}.xsl' name pattern"
291
                                        continue;
292
                                }
293
                                String pagerStep = xslName.substring(idx3 + 1);
294
                                String editionName = xslName.substring(0, idx3);
295

    
296
                                int idx = editionName.indexOf(".")
297
                                if (idx > 0) editionName = editionName.substring(0, idx);
298
                                println "-- Building '$editionName' XSL edition with step '$pagerStep'..."
299

    
300
                                File newEditionDirectory = new File(htmlDirectory, editionName);
301
                                xslParams["output-directory"] = newEditionDirectory.toURI().toString()
302

    
303
                                if (editionsCreated[editionName] == null) { // first XSL, replace an edition
304
                                        editionsCreated[editionName] = xslFile
305
                                        //if (!importModule.isUpdatingCorpus()) {
306
                                        //TODO: optimisation if update is enable,
307
                                        newEditionDirectory.deleteDir(); // delete previous edition if any
308
                                        //}
309
                                        newEditionDirectory.mkdir()
310

    
311
                                        boolean deleteOutputFiles = "pager" == pagerStep;
312
                                        if (ApplyXsl2.processImportSources(xslFile, inputDirectory, newEditionDirectory, xslParams, deleteOutputFiles)) {
313
                                                println ""
314
                                        } else {
315
                                                reason = "Fail to apply edition XSL: $xslFile"
316
                                                return false;
317
                                        }
318

    
319
                                        // copy CSS files in the newEditionDirector edition directory
320
                                        if (cssDirectory.exists()) {
321
                                                File csshtmlDirectory = new File(newEditionDirectory, "css")
322
                                                FileCopy.copyFiles(cssDirectory, csshtmlDirectory)
323
                                        }
324
                                        if (jsDirectory.exists()) {
325
                                                File jshtmlDirectory = new File(newEditionDirectory, "js")
326
                                                FileCopy.copyFiles(jsDirectory, jshtmlDirectory)
327
                                        }
328
                                        if (imagesDirectory.exists()) {
329
                                                File imageshtmlDirectory = new File(newEditionDirectory, "images")
330
                                                FileCopy.copyFiles(imagesDirectory, imageshtmlDirectory)
331
                                        }
332
                                } else { // N+1 XSL working with HTML files
333
                                        def htmlFiles = newEditionDirectory.listFiles()
334
                                        htmlFiles.sort()
335

    
336
                                        if (ApplyXsl2.processImportSources(xslFile, htmlFiles, xslParams)) {
337
                                                if ("pager".equals(pagerStep)) {
338
                                                        // delete the one page HTML files only if the XSL step is "pager"
339
                                                        for (File f : htmlFiles) f.delete();
340
                                                }
341
                                                //        println ""
342
                                        } else {
343
                                                reason = "Fail to apply edition XSL: $xslFile"
344
                                                return false;
345
                                        }
346
                                }
347
                        }
348

    
349
                        // UPDATE import.xml: for each XML-TXM file, we must retrieve the first word ID from the XSL output files
350
                        //println "retrieve word ids from $inputDirectory"
351
                        println "-- Fetching page word IDs..."
352
                        ConsoleProgressBar cpb = new ConsoleProgressBar(editionsCreated.keySet().size())
353
                        for (String editionName : editionsCreated.keySet()) {
354
                                cpb.tick()
355

    
356
                                File newEditionDirectory = new File(htmlDirectory, editionName);
357
                                File xslFile = editionsCreated[editionName]
358
                                for (File txmFile : inputDirectory.listFiles()) {
359
                                        if (txmFile.isDirectory()) continue;
360
                                        String textName = txmFile.getName()
361
                                        int idx4 = textName.indexOf(".")
362
                                        if (idx4 > 0) textName = textName.substring(0, idx4);
363

    
364
                                        getFirstWordIDs(textName, editionName, newEditionDirectory, xslFile, txmFile);
365
                                }
366
                        }
367
                        println ""
368
                }
369
                return true;
370
        }
371

    
372
        private void getFirstWordIDs(String textName, String editionName, File newEditionDirectory, File xslFile, File txmFile) {
373
                //                println "call getFirstWordIDs textName=$textName editionName=$editionName dir=$newEditionDirectory xsl=$xslFile"
374
                Text t = project.getText(textName);
375
                if (t == null) {
376
                        t = new Text(project);
377
                }
378
                t.setName(textName);
379
                t.setSourceFile(txmFile)
380
                t.setTXMFile(txmFile)
381

    
382
                Edition edition = t.getEdition(editionName)
383
                if (edition == null) {
384
                        edition = new Edition(t);
385
                }
386
                edition.setName(editionName);
387
                edition.setIndex(outputDirectory.getAbsolutePath());
388

    
389
                LinkedHashMap<File, String> words = new LinkedHashMap<File, String>()
390
                def files = []
391
                newEditionDirectory.eachFile() {it -> if (it.isFile()) files << it}
392

    
393
                files.sort() { f1, f2 ->
394
                        String s1 = f1.getName()
395
                        String s2 = f2.getName()
396
                        int n1 = Integer.parseInt(s1.substring(s1.lastIndexOf("_")+1, s1.lastIndexOf(".")))
397
                        int n2 = Integer.parseInt(s2.substring(s2.lastIndexOf("_")+1, s2.lastIndexOf(".")))
398
                        return n1 - n2;
399
                }
400

    
401
                for (File f : files) {
402
                        String pagename = f.getName();
403
                        if (pagename.startsWith(textName+"_")) { // this is a page
404
                                String firstWordID = getMetaContent(f);
405
                                pagename = pagename.substring((textName+"_").length(), pagename.indexOf(".html")) // !!!!
406
                                edition.addPage(pagename, firstWordID)
407
                        }
408
                }
409
        }
410

    
411
        public static String getMetaContent(File f) {
412
                def inputData = f.toURI().toURL().openStream();
413
                def factory = XMLInputFactory.newInstance();
414
                factory.setProperty("javax.xml.stream.supportDTD", false); // ignore the DTD declared in doctype
415

    
416
                def parser = factory.createXMLStreamReader(inputData);
417
                String META = "meta"
418
                String BODY = "body"
419
                String NAME = "name"
420
                String DESCRIPTION = "txm:first-word-id"
421
                String CONTENT = "content"
422

    
423
                String content = "";
424
                String desc = "";
425

    
426
                for (int event = parser.next(); event != XMLStreamConstants.END_DOCUMENT; event = parser.next()) {
427
                        if (event == XMLStreamConstants.START_ELEMENT) { // start elem
428

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

    
450
                return content;
451
        }
452

    
453
        public static void main(def args) {
454
                println "RESULT: "+getMetaContent(new File("/home/mdecorde/TXM/corpora/QGRAALXTZ/HTML/QGRAALXTZ/default", "qgraal_cm_test201510_page_160_2.html"))
455
        }
456
}