-
Notifications
You must be signed in to change notification settings - Fork 0
/
DiplomaticConversion.java
198 lines (169 loc) · 7.04 KB
/
DiplomaticConversion.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
package net.faustedition.gen;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.StringWriter;
import java.net.URI;
import java.net.URL;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Optional;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.stream.Stream;
import java.util.stream.Stream.Builder;
import javax.xml.stream.XMLStreamException;
import javax.xml.transform.TransformerException;
import com.google.common.base.Joiner;
import com.google.common.collect.Lists;
import com.mycila.xmltool.XMLDoc;
import com.mycila.xmltool.XMLDocumentException;
import com.mycila.xmltool.XMLTag;
import de.faustedition.transcript.simple.SimpleTransform;
import fi.iki.elonen.SimpleWebServer;
public class DiplomaticConversion {
private static Logger logger = Logger.getLogger(DiplomaticConversion.class.getName());
public static Path root = Paths.get("data/xml/");
public static Path target = Paths.get("target");
private static String serverURL;
public static class TranscriptPage {
public final Document document;
private final String page;
private final int pageNo;
public TranscriptPage(final Document document, final String page, final int pageNo) {
this.document = document;
this.page = page;
this.pageNo = pageNo;
}
public Path source() {
return resolveFaustUri(document.base.resolve(page));
}
private Path getPagePath(final String extension) {
final Path relPath = document.relPath;
return Paths.get(relPath.subpath(1, relPath.getNameCount()).toString(),
MessageFormat.format("page_{0}.{1}", pageNo, extension));
}
public TranscriptPage writeTranscriptJson() {
final Path targetPath = getJsonPath();
targetPath.getParent().toFile().mkdirs();
try (FileInputStream input = new FileInputStream(source().toFile())) {
final StringWriter output = new StringWriter();
SimpleTransform.simpleTransform(input, output);
com.google.common.io.Files.write(output.toString(), targetPath.toFile(), Charset.forName("UTF-8"));
} catch (IOException | TransformerException | XMLStreamException e) {
logger.log(Level.SEVERE, "Failed to generate JSON for " + document.base.resolve(page), e);
}
return this;
}
public Optional<Path> getImageLinkPath() {
try {
final XMLTag transcript = XMLDoc.from(source().toFile()).deletePrefixes();
final XMLTag graphic = transcript.gotoTag("//graphic[@mimeType = 'image/svg+xml']");
return Optional.of(resolveFaustUri(URI.create(graphic.getAttribute("url"))));
} catch (final XMLDocumentException e) {
return Optional.empty();
}
}
@Override
public String toString() {
return MessageFormat.format("{0} page {1}: {2}", document.faustURI, pageNo, document.base.resolve(page));
}
public boolean buildSVGs() {
logger.fine("Converting " + this);
final ArrayList<String> arguments = Lists.newArrayList(
System.getProperty("phantomjs.binary", "/usr/local/bin/phantomjs"), "rendersvgs.js",
serverURL, getJsonPath().toString(),
target.resolve("www").resolve("transcript").resolve("diplomatic").resolve(getPagePath("svg")).toString());
final Optional<Path> imageLinkPath = getImageLinkPath();
if (imageLinkPath.isPresent()) {
arguments.add(imageLinkPath.get().toString());
arguments.add(target.resolve("www").resolve("transcript").resolve("overlay").resolve(getPagePath("svg")).toString());
} else {
logger.fine(this + " has no text-image-links");
}
try {
final Process renderProcess = new ProcessBuilder(arguments).redirectErrorStream(true).start();
final BufferedReader bufferedReader = new BufferedReader(
new InputStreamReader(new BufferedInputStream(renderProcess.getInputStream())));
bufferedReader.lines().forEach(line -> logger.warning(line + " (while converting " + this + ")"));
return renderProcess.waitFor() != 0;
} catch (IOException | InterruptedException e) {
logger.log(Level.SEVERE, "Failed to convert SVG for " + document.base.resolve(page), e);
}
return true;
}
private Path getJsonPath() {
return target.resolve("pages/").resolve(getPagePath("json"));
}
}
public static class Document {
private final Path path;
/** The base faust:// uri for the transcripts of this document */
public URI base;
/** The relative path to this document */
public final Path relPath;
/** The faust:// uri for this document */
public URI faustURI;
public Document(final Path path) {
this.path = path;
relPath = root.relativize(path);
faustURI = URI.create("faust://xml/" + relPath.toString());
}
public Stream<TranscriptPage> transcripts() {
try {
final XMLTag doc = XMLDoc.from(path.toFile()).deletePrefixes();
base = URI.create(doc.gotoTag("//*[@base]").getAttribute("base"));
final Builder<TranscriptPage> builder = Stream.builder();
doc.forEach(tag -> builder.accept(new TranscriptPage(this, tag.getAttribute("uri"), tag.rawXpathNumber("count(preceding::page)").intValue()+1)),
"//docTranscript[@uri]");
return builder.build();
} catch (final XMLDocumentException e) {
logger.log(Level.WARNING, path + ": XML extraction error", e);
return Stream.empty();
}
}
}
public static void main(final String[] args) throws IOException {
final SimpleWebServer webServer = new SimpleWebServer("localhost", 0, new File("svg_rendering/page"), true);
webServer.start(60, true);
try {
serverURL = new URL("http", "localhost", webServer.getListeningPort(), "/transcript-generation.html").toString();
logger.info(MessageFormat.format("Web server runs on {0}", serverURL));
final Object[] failedConversions = getDocuments()
.flatMap(document -> document.transcripts())
.parallel()
.map(page -> page.writeTranscriptJson())
.filter(page -> page.buildSVGs())
.filter(page -> page.buildSVGs())
.filter(page -> page.buildSVGs())
.toArray();
if (failedConversions.length > 0) {
logger.log(Level.SEVERE, MessageFormat.format("Conversion of the following {0} pages failed:\n {1}",
failedConversions.length, Joiner.on("\n ").join(failedConversions)));
int allowedFailures = Integer.parseUnsignedInt(System.getProperty("faust.diplo.allowedFailures", "0"));
if (failedConversions.length > allowedFailures) {
logger.log(Level.SEVERE, MessageFormat.format("These are more than the {0} tolerated failures.", allowedFailures));
System.exit(1);
} else {
logger.log(Level.INFO, MessageFormat.format("Up to {0} failures are tolerated.", allowedFailures));
}
}
} finally {
webServer.stop();
}
}
public static Path resolveFaustUri(final URI uri) {
return root.resolve(uri.getPath().substring(1));
}
private static Stream<Document> getDocuments() throws IOException {
return Files.walk(root.resolve("document")).filter(path -> path.toString().endsWith(".xml")).map(
path -> new Document(path));
}
}