use of eu.transkribus.core.model.beans.JAXBPageTranscript in project TranskribusCore by Transkribus.
the class DocExporter method exportDoc.
/**
* Export current document with the provided parameters.
* @param doc current document
* @param pars export settings
* @return directory to which the export files were written
* @throws IOException
* @throws IllegalArgumentException
* @throws URISyntaxException
* @throws JAXBException
* @throws TransformerException
*/
public File exportDoc(TrpDoc doc, CommonExportPars pars) throws IOException, IllegalArgumentException, URISyntaxException, JAXBException, TransformerException {
FimgStoreGetClient getter = null;
FimgStoreUriBuilder uriBuilder = null;
ImgType imgType = pars.getRemoteImgQuality() == null ? ImgType.orig : pars.getRemoteImgQuality();
if (doc.isRemoteDoc()) {
// FIXME fimagestore path should be read from docMd!
getter = new FimgStoreGetClient("dbis-thure.uibk.ac.at", "f");
final String scheme = pars.isUseHttps() ? "https" : "http";
final int port = pars.isUseHttps() ? 443 : 80;
uriBuilder = new FimgStoreUriBuilder(scheme, getter.getHost(), port, getter.getServerContext());
}
// create copy of object, as we alter it here while exporting
TrpDoc doc2;
doc2 = new TrpDoc(doc);
// check and create output directory
File outputDir = new File(pars.getDir());
if (!pars.isDoOverwrite() && outputDir.exists()) {
throw new IOException("File path already exists.");
}
outputDir.mkdir();
// decide where to put the images
final File imgOutputDir;
if (pars.isUseOcrMasterDir()) {
imgOutputDir = new File(outputDir.getAbsolutePath() + File.separatorChar + LocalDocConst.OCR_MASTER_DIR);
imgOutputDir.mkdir();
} else {
imgOutputDir = outputDir;
}
File pageOutputDir = null, altoOutputDir = null;
// check PAGE export settings and create output directory
String pageDirName = pars.getPageDirName();
if (pars.isDoExportPageXml() && !StringUtils.isEmpty(pageDirName)) {
pageOutputDir = new File(outputDir.getAbsolutePath() + File.separatorChar + pageDirName);
if (pageOutputDir.mkdir()) {
logger.debug("pageOutputDir created successfully ");
} else {
logger.debug("pageOutputDir could not be created!");
}
} else {
// if pageDirName is not set, export the PAGE XMLs to imgOutputDir
pageOutputDir = imgOutputDir;
}
// check Alto export settings and create output directory
AltoExporter altoEx = new AltoExporter();
if (pars.isDoExportAltoXml()) {
altoOutputDir = altoEx.createAltoOuputDir(doc2, outputDir.getAbsolutePath());
}
// check and write metadata
if (doc2.getMd() != null) {
File fileOut = new File(outputDir.getAbsolutePath() + File.separatorChar + LocalDocConst.METADATA_FILENAME);
try {
JaxbUtils.marshalToFile(doc2.getMd(), fileOut);
} catch (JAXBException e) {
throw new IOException("Could not marshal metadata to file.", e);
}
}
List<TrpPage> pages = doc2.getPages();
Set<Integer> pageIndices = pars.getPageIndices(doc.getNPages());
// do export for all defined pages
for (int i = 0; i < pages.size(); ++i) {
if (pageIndices != null && !pageIndices.contains(i)) {
continue;
}
TrpPage p = pages.get(i);
File imgFile = null, xmlFile = null, altoFile = null;
URL imgUrl = p.getUrl();
final String baseFileName = ExportFilePatternUtils.buildBaseFileName(pars.getFileNamePattern(), p);
final String imgExt = "." + FilenameUtils.getExtension(p.getImgFileName());
final String xmlExt = ".xml";
// gather remote files and export document
if (doc2.isRemoteDoc()) {
if (pars.isDoWriteImages()) {
final String msg = "Downloading " + imgType.toString() + " image for page nr. " + p.getPageNr();
logger.debug(msg);
updateStatus(msg);
final URI imgUri = uriBuilder.getImgUri(p.getKey(), imgType);
imgFile = getter.saveFile(imgUri, imgOutputDir.getAbsolutePath(), baseFileName + imgExt);
p.setUrl(imgFile.toURI().toURL());
p.setKey(null);
}
if (pars.isDoExportPageXml()) {
// old
// TrpTranscriptMetadata t = p.getCurrentTranscript();
/*
* new: to get the previously stored chosen version
*/
TrpTranscriptMetadata transcriptMd;
JAXBPageTranscript transcript = cache.getPageTranscriptAtIndex(i);
// set up transcript metadata
if (transcript == null) {
transcriptMd = p.getCurrentTranscript();
logger.warn("Have to unmarshall transcript in DocExporter for transcript " + transcriptMd + " - should have been built before using ExportUtils::storePageTranscripts4Export!");
transcript = new JAXBPageTranscript(transcriptMd);
transcript.build();
} else {
transcriptMd = transcript.getMd();
}
URL xmlUrl = transcriptMd.getUrl();
if (pars.isExportTranscriptMetadata()) {
MetadataType md = transcript.getPage().getPcGtsType().getMetadata();
if (md == null) {
throw new JAXBException("Transcript does not contain a metadata element: " + transcriptMd);
}
String imgUrlStr = CoreUtils.urlToString(imgUrl);
String xmlUrlStr = CoreUtils.urlToString(xmlUrl);
String status = transcriptMd.getStatus() == null ? null : transcriptMd.getStatus().toString();
TranskribusMetadataType tmd = new TranskribusMetadataType();
tmd.setDocId(doc.getId());
tmd.setPageId(p.getPageId());
tmd.setPageNr(p.getPageNr());
tmd.setTsid(transcriptMd.getTsId());
tmd.setStatus(status);
tmd.setUserId(transcriptMd.getUserId());
tmd.setImgUrl(imgUrlStr);
tmd.setXmlUrl(xmlUrlStr);
tmd.setImageId(p.getImageId());
md.setTranskribusMetadata(tmd);
}
// write transcript to file
xmlFile = new File(FilenameUtils.normalizeNoEndSeparator(pageOutputDir.getAbsolutePath()) + File.separator + baseFileName + xmlExt);
logger.debug("PAGE XMl output file: " + xmlFile.getAbsolutePath());
transcript.write(xmlFile);
// old code: save file by just downloading to disk
// xmlFile = getter.saveFile(transcriptMd.getUrl().toURI(), pageOutputDir.getAbsolutePath(), baseFileName + xmlExt);
// make sure (for other exports) that the transcript that is exported is the only one set in the transcripts list of TrpPage
p.getTranscripts().clear();
TrpTranscriptMetadata tCopy = new TrpTranscriptMetadata(transcriptMd, p);
tCopy.setUrl(xmlFile.toURI().toURL());
p.getTranscripts().add(tCopy);
}
} else {
updateStatus("Copying local files for page nr. " + p.getPageNr());
// copy local files during export
if (pars.isDoWriteImages()) {
imgFile = LocalDocWriter.copyImgFile(p, p.getUrl(), imgOutputDir.getAbsolutePath(), baseFileName + imgExt);
}
if (pars.isDoExportPageXml()) {
xmlFile = LocalDocWriter.copyTranscriptFile(p, pageOutputDir.getAbsolutePath(), baseFileName + xmlExt, cache);
}
}
// export alto:
if (pars.isDoExportAltoXml()) {
altoFile = altoEx.exportAltoFile(p, baseFileName + xmlExt, altoOutputDir, pars.isSplitIntoWordsInAltoXml());
}
if (imgFile != null)
logger.debug("Written image file " + imgFile.getAbsolutePath());
if (xmlFile != null) {
logger.debug("Written transcript xml file " + xmlFile.getAbsolutePath());
} else {
logger.warn("No transcript was exported for page ");
}
if (altoFile != null) {
logger.debug("Written ALTO xml file " + altoFile.getAbsolutePath());
} else {
logger.warn("No alto was exported for page ");
}
setChanged();
notifyObservers(Integer.valueOf(p.getPageNr()));
}
if (pars.isDoWriteMets()) {
// load the exported doc from its new location
// FIXME this does not work for export of PAGE XMLs only!
// final TrpDoc localDoc = LocalDocReader.load(outputDir.getAbsolutePath(), false);
// set local folder or else TrpMetsBuilder will treat this as remote doc!
doc2.getMd().setLocalFolder(outputDir);
// write mets with file pointers to local files
Mets mets = TrpMetsBuilder.buildMets(doc2, pars.isDoExportPageXml(), pars.isDoExportAltoXml(), pars.isDoWriteImages(), pageIndices);
File metsFile = new File(outputDir.getAbsolutePath() + File.separator + TrpMetsBuilder.METS_FILE_NAME);
try {
JaxbUtils.marshalToFile(mets, metsFile, TrpDocMetadata.class);
} catch (JAXBException e) {
throw new IOException("Could not marshal METS to file!", e);
}
}
return outputDir;
}
use of eu.transkribus.core.model.beans.JAXBPageTranscript in project TranskribusCore by Transkribus.
the class ATeiBuilder method getPcGtsTypeForPage.
// protected abstract void setTextRegion(TextRegionType r, int pageNr);
protected PcGtsType getPcGtsTypeForPage(TrpPage p) throws JAXBException {
PcGtsType pc;
if (transcrBuffer.containsKey(p.getPageNr())) {
pc = transcrBuffer.get(p.getPageNr());
} else {
TrpTranscriptMetadata tMd = p.getCurrentTranscript();
try {
JAXBPageTranscript tr = new JAXBPageTranscript(tMd);
tr.build();
pc = tr.getPageData();
} catch (IOException je) {
throw new JAXBException("Could not unmarshal page " + p.getPageNr(), je);
}
transcrBuffer.put(p.getPageNr(), pc);
}
return pc;
}
use of eu.transkribus.core.model.beans.JAXBPageTranscript in project TranskribusCore by Transkribus.
the class PdfExporter method export.
public File export(final TrpDoc doc, final String path, Set<Integer> pageIndices, final boolean useWordLevel, final boolean addTextPages, final boolean imagesOnly, final boolean highlightTags, final boolean doBlackening, boolean createTitle, ExportCache cache) throws DocumentException, MalformedURLException, IOException, JAXBException, URISyntaxException, InterruptedException {
if (doc == null) {
throw new IllegalArgumentException("TrpDoc is null!");
}
if (path == null) {
throw new IllegalArgumentException("path is null!");
}
if (cache == null) {
cache = new ExportCache();
}
// if(startPage == null || startPage < 1) startPage = 1;
// final int nrOfPages = doc.getPages().size();
// if(endPage == null || endPage > nrOfPages+1) endPage = nrOfPages;
//
// if(startPage > endPage){
// throw new IllegalArgumentException("Start page must be smaller than end page!");
// }
File pdfFile = new File(path);
TrpPdfDocument pdf = new TrpPdfDocument(pdfFile, useWordLevel, highlightTags, doBlackening, createTitle);
setChanged();
notifyObservers("Creating PDF document...");
boolean onePagePrinted = false;
// for(int i = startPage-1; i <= endPage-1; i++){
for (int i = 0; i < doc.getPages().size(); ++i) {
if (pageIndices != null && !pageIndices.contains(i))
continue;
logger.info("Processing page " + (i + 1));
TrpPage p = doc.getPages().get(i);
URL imgUrl = p.getUrl();
/*
* md is only needed for getting resolution because in the image it may be missing
* But if it is a local doc we have to try to get from img because md is null
*/
FimgStoreImgMd md = null;
if (doc.isRemoteDoc()) {
FimgStoreGetClient getter = new FimgStoreGetClient(p.getUrl());
md = (FimgStoreImgMd) getter.getFileMd(p.getKey());
}
URL xmlUrl = p.getCurrentTranscript().getUrl();
logger.debug("output with tags " + highlightTags);
// PcGtsType pc = PageXmlUtils.unmarshal(xmlUrl);
// should be the same as above
JAXBPageTranscript pt = null;
if (cache != null) {
pt = cache.getPageTranscriptAtIndex(i);
}
PcGtsType pc;
if (pt != null) {
pc = pt.getPageData();
} else {
pc = PageXmlUtils.unmarshal(xmlUrl);
}
if (!onePagePrinted) {
// add first page and previously add a title page with doc metadata and editorial declarations (if this option is set)
pdf.addPage(imgUrl, doc, pc, addTextPages, imagesOnly, md, doBlackening, cache);
onePagePrinted = true;
} else {
pdf.addPage(imgUrl, null, pc, addTextPages, imagesOnly, md, doBlackening, cache);
}
setChanged();
notifyObservers(Integer.valueOf(i + 1));
if (cancel) {
pdf.close();
File file = new File(path);
if (!file.delete()) {
throw new IOException("Could not delete the incomplete PDF file during export cancel");
}
throw new InterruptedException("Export canceled by the user");
// break;
}
}
if (highlightTags) {
pdf.addTags(doc, pageIndices, useWordLevel, cache);
}
pdf.close();
setChanged();
notifyObservers("PDF written at: " + path);
logger.info("PDF written at: " + path);
return pdfFile;
}
use of eu.transkribus.core.model.beans.JAXBPageTranscript in project TranskribusCore by Transkribus.
the class TrpRtfBuilder method writeRtfForDoc.
public static void writeRtfForDoc(TrpDoc doc, boolean wordBased, boolean writeTags, boolean doBlackening, File file, Set<Integer> pageIndices, IProgressMonitor monitor, ExportCache cache) throws JAXBException, IOException {
exportTags = writeTags;
tagnames = cache.getSelectedTags();
TrpRtfBuilder.doBlackening = doBlackening;
/*
* get all names of tags
*/
// tagnames = CustomTagFactory.getRegisteredTagNames();
Rtf rtf = Rtf.rtf();
List<TrpPage> pages = doc.getPages();
int totalPages = pageIndices == null ? pages.size() : pageIndices.size();
if (monitor != null) {
monitor.beginTask("Exporting to RTF", totalPages);
}
int c = 0;
for (int i = 0; i < pages.size(); ++i) {
if (pageIndices != null && !pageIndices.contains(i))
continue;
if (monitor != null) {
if (monitor.isCanceled()) {
logger.debug("RTF export cancelled!");
return;
}
monitor.subTask("Processing page " + (c + 1));
}
TrpPage page = pages.get(i);
TrpTranscriptMetadata md = page.getCurrentTranscript();
JAXBPageTranscript tr = new JAXBPageTranscript(md);
tr.build();
TrpPageType trpPage = tr.getPage();
logger.debug("writing rtf for page " + (i + 1) + "/" + doc.getNPages());
// rtf().header(color( 204, 0, 0 ).at( 0 ),
// color( 0, 0xff, 0 ).at( 1 ),
// color( 0, 0, 0xff ).at( 2 ),
// font( "Calibri" ).at( 0 ) );
// RtfHeaderColor color = RtfHeaderColor.color(0xff, 0, 0);
rtf.header(color(204, 0, 0).at(0), color(0, 0xff, 0).at(1)).section(getRtfParagraphsForTranscript(trpPage, wordBased));
++c;
if (monitor != null) {
monitor.worked(c);
}
}
// write tags at end of last page
if (exportTags) {
// RtfText headline = RtfText.text("Person names in this document (amount of found persons: " + persons.size() + ")", "\n");
/*
* for all different tagnames:
* find all custom tags in doc
* create list and
*/
ArrayList<RtfPara> tagParas = new ArrayList<RtfPara>();
// tagnames = all user choosen tags via export dialog
for (String currTagname : tagnames) {
// logger.debug("curr tagname " + currTagname);
// get all custom tags with currTagname and text
HashMap<CustomTag, String> allTagsOfThisTagname = cache.getTags(currTagname);
if (allTagsOfThisTagname.size() > 0) {
tagParas.add(RtfPara.p(RtfText.text(RtfText.underline(currTagname + " tags in this document: " + allTagsOfThisTagname.size()))));
// ArrayList<RtfText> tagTexts = new ArrayList<RtfText>();
Collection<String> valueSet = allTagsOfThisTagname.values();
RtfText[] tagTexts = new RtfText[valueSet.size()];
int l = 0;
for (String currEntry : valueSet) {
tagTexts[l++] = RtfText.text(currEntry.concat("\n"));
// logger.debug("tag value is " + currEntry);
}
tagParas.add(RtfPara.p(tagTexts));
}
}
// int parSize = getParsNumber();
// int k = 0;
//
// if (persons.size() > 0){
// logger.debug("k is " + k);
// List<String> newPersonList = new ArrayList<String>(new HashSet<String>(persons));
// tagParas[k++]=RtfPara.p(RtfText.text("Person names in this document (amount of found persons: " + newPersonList.size() + ")", "\n"));
// logger.debug("k is " + k);
// //rtf.p("Person names in this document (amount of found persons: " + persons.size() + ")", "\n");
// //to make the list contain only unique values
//
// RtfText[] personTexts = new RtfText[newPersonList.size()];
// for (int j=0; j<newPersonList.size(); ++j) {
// personTexts[j] = RtfText.text(newPersonList.get(j), "\n");
// logger.debug("person is " + newPersonList.get(j));
// }
// tagParas[k++] = RtfPara.p(personTexts);
// }
//
// if (places.size() > 0){
// List<String> newPlaceList = new ArrayList<String>(new HashSet<String>(places));
// tagParas[k++]=RtfPara.p(RtfText.text("Places in this document (amount of found places " + newPlaceList.size() + ")", "\n"));
//
// RtfText[] placeTexts = new RtfText[newPlaceList.size()];
// for (int j=0; j<newPlaceList.size(); ++j) {
// //RtfText.color(0, "red");
// placeTexts[j] = RtfText.color(0, newPlaceList.get(j).concat("\n"));
// logger.debug("place is " + newPlaceList.get(j));
// }
// RtfPara par2 = RtfPara.p(placeTexts);
// tagParas[k++] = par2;
// }
//
// if(addresses.size() > 0){
// List<String> newAddressList = new ArrayList<String>(new HashSet<String>(addresses));
// tagParas[k++]=RtfPara.p(RtfText.text("Addresses in this document (amount of found addresses " + newAddressList.size() + ")", "\n"));
//
// RtfText[] addresseTexts = new RtfText[newAddressList.size()];
// for (int j=0; j<newAddressList.size(); ++j) {
// addresseTexts[j] = RtfText.text(newAddressList.get(j), "\n");
// logger.debug("addresse is " + newAddressList.get(j));
// }
// RtfPara par3 = RtfPara.p(addresseTexts);
// tagParas[k++] = par3;
// }
// rtf.section(par3);
rtf.header(color(204, 0, 0).at(0)).section(tagParas);
}
rtf.out(new FileWriter(file));
logger.info("wrote rtf to: " + file.getAbsolutePath());
}
use of eu.transkribus.core.model.beans.JAXBPageTranscript in project TranskribusCore by Transkribus.
the class TrpRtfBuilder method writeRtfForDoc.
public static void writeRtfForDoc(TrpDoc doc, boolean wordBased, File file, Set<Integer> pageIndices, IProgressMonitor monitor) throws JAXBException, IOException {
Rtf rtf = Rtf.rtf();
List<TrpPage> pages = doc.getPages();
int totalPages = pageIndices == null ? pages.size() : pageIndices.size();
if (monitor != null) {
monitor.beginTask("Exporting to RTF", totalPages);
}
int c = 0;
for (int i = 0; i < pages.size(); ++i) {
if (pageIndices != null && !pageIndices.contains(i))
continue;
if (monitor != null) {
if (monitor.isCanceled()) {
logger.debug("RTF export cancelled!");
return;
}
monitor.subTask("Processing page " + (c + 1));
}
TrpPage page = pages.get(i);
TrpTranscriptMetadata md = page.getCurrentTranscript();
JAXBPageTranscript tr = new JAXBPageTranscript(md);
tr.build();
TrpPageType trpPage = tr.getPage();
logger.debug("writing rtf for page " + (i + 1) + "/" + doc.getNPages());
rtf.section(getRtfParagraphsForTranscript(trpPage, wordBased));
++c;
if (monitor != null) {
monitor.worked(c);
}
}
rtf.out(new FileWriter(file));
logger.info("wrote rtf to: " + file.getAbsolutePath());
}
Aggregations