19 package org.sleuthkit.autopsy.textextractors;
21 import com.google.common.collect.ImmutableList;
22 import com.google.common.io.CharSource;
23 import com.google.common.util.concurrent.ThreadFactoryBuilder;
25 import java.io.FileInputStream;
26 import java.io.FileNotFoundException;
27 import java.io.IOException;
28 import java.io.InputStream;
29 import java.io.PushbackReader;
30 import java.io.Reader;
31 import java.nio.file.Paths;
32 import java.util.HashMap;
33 import java.util.List;
34 import java.util.Objects;
36 import java.util.concurrent.Callable;
37 import java.util.concurrent.ExecutorService;
38 import java.util.concurrent.Executors;
39 import java.util.concurrent.Future;
40 import java.util.concurrent.ThreadFactory;
41 import java.util.concurrent.TimeUnit;
42 import java.util.concurrent.TimeoutException;
43 import java.util.logging.Level;
44 import java.util.stream.Collectors;
45 import org.apache.tika.Tika;
46 import org.apache.tika.exception.TikaException;
47 import org.apache.tika.metadata.Metadata;
48 import org.apache.tika.parser.AutoDetectParser;
49 import org.apache.tika.parser.ParseContext;
50 import org.apache.tika.parser.Parser;
51 import org.apache.tika.parser.ParsingReader;
52 import org.apache.tika.parser.microsoft.OfficeParserConfig;
53 import org.apache.tika.parser.ocr.TesseractOCRConfig;
54 import org.apache.tika.parser.pdf.PDFParserConfig;
55 import org.openide.util.NbBundle;
56 import org.openide.modules.InstalledFileLocator;
57 import org.openide.util.Lookup;
70 import org.xml.sax.ContentHandler;
71 import org.xml.sax.SAXException;
72 import org.xml.sax.helpers.DefaultHandler;
73 import com.google.common.collect.ImmutableMap;
74 import java.io.InputStreamReader;
75 import java.nio.charset.Charset;
76 import java.util.ArrayList;
77 import org.apache.tika.parser.pdf.PDFParserConfig.OCR_STRATEGY;
84 final class TikaTextExtractor
implements TextExtractor {
88 private static final List<String> BINARY_MIME_TYPES
91 "application/octet-stream",
92 "application/x-msdownload");
98 private static final List<String> ARCHIVE_MIME_TYPES
101 "application/x-7z-compressed",
102 "application/x-ace-compressed",
103 "application/x-alz-compressed",
105 "application/vnd.ms-cab-compressed",
106 "application/x-cfs-compressed",
107 "application/x-dgc-compressed",
108 "application/x-apple-diskimage",
109 "application/x-gca-compressed",
113 "application/x-rar-compressed",
114 "application/x-stuffit",
115 "application/x-stuffitx",
116 "application/x-gtar",
117 "application/x-archive",
118 "application/x-executable",
119 "application/x-gzip",
122 "application/x-cpio",
123 "application/x-shar",
125 "application/x-bzip",
126 "application/x-bzip2",
127 "application/x-lzip",
128 "application/x-lzma",
129 "application/x-lzop",
131 "application/x-compress");
134 private static final java.util.logging.Logger TIKA_LOGGER = java.util.logging.Logger.getLogger(
"Tika");
135 private static final Logger AUTOPSY_LOGGER = Logger.getLogger(TikaTextExtractor.class.getName());
137 private final ThreadFactory tikaThreadFactory
138 =
new ThreadFactoryBuilder().setNameFormat(
"tika-reader-%d").build();
139 private final ExecutorService executorService = Executors.newSingleThreadExecutor(tikaThreadFactory);
140 private static final String SQLITE_MIMETYPE =
"application/x-sqlite3";
142 private final AutoDetectParser parser =
new AutoDetectParser();
143 private final Content content;
145 private boolean tesseractOCREnabled;
146 private static final String TESSERACT_DIR_NAME =
"Tesseract-OCR";
147 private static final String TESSERACT_EXECUTABLE =
"tesseract.exe";
148 private static final File TESSERACT_PATH = locateTesseractExecutable();
149 private String languagePacks = formatLanguagePacks(PlatformUtil.getOcrLanguagePacks());
150 private static final String TESSERACT_OUTPUT_FILE_NAME =
"tess_output";
151 private Map<String, String> metadataMap;
153 private ProcessTerminator processTerminator;
155 private static final List<String> TIKA_SUPPORTED_TYPES
156 =
new Tika().getParser().getSupportedTypes(
new ParseContext())
158 .map(mt -> mt.getType() +
"/" + mt.getSubtype())
159 .collect(Collectors.toList());
161 public TikaTextExtractor(Content content) {
162 this.content = content;
172 private boolean ocrEnabled() {
173 return TESSERACT_PATH != null && tesseractOCREnabled
174 && PlatformUtil.isWindowsOS() ==
true && PlatformUtil.is64BitOS();
189 public Reader getReader() throws InitReaderException {
190 if (!this.isSupported()) {
191 throw new InitReaderException(
"Content is not supported");
195 final AbstractFile file = ((AbstractFile) content);
197 final String mimeType = file.getMIMEType();
201 if (ocrEnabled() && mimeType.toLowerCase().startsWith(
"image/")) {
202 InputStream imageOcrStream = performOCR(file);
203 return new InputStreamReader(imageOcrStream, Charset.forName(
"UTF-8"));
207 final InputStream stream =
new ReadContentInputStream(content);
208 final ParseContext parseContext =
new ParseContext();
213 parseContext.set(Parser.class, parser);
217 OfficeParserConfig officeParserConfig =
new OfficeParserConfig();
218 officeParserConfig.setUseSAXPptxExtractor(
true);
219 officeParserConfig.setUseSAXDocxExtractor(
true);
220 parseContext.set(OfficeParserConfig.class, officeParserConfig);
225 TesseractOCRConfig ocrConfig =
new TesseractOCRConfig();
226 String tesseractFolder = TESSERACT_PATH.getParent();
227 ocrConfig.setTesseractPath(tesseractFolder);
228 ocrConfig.setLanguage(languagePacks);
229 ocrConfig.setTessdataPath(PlatformUtil.getOcrLanguagePacksPath());
230 parseContext.set(TesseractOCRConfig.class, ocrConfig);
233 PDFParserConfig pdfConfig =
new PDFParserConfig();
241 pdfConfig.setOcrStrategy(OCR_STRATEGY.AUTO);
242 parseContext.set(PDFParserConfig.class, pdfConfig);
245 Metadata metadata =
new Metadata();
247 Future<Reader> future = executorService.submit(
248 new GetTikaReader(parser, stream, metadata, parseContext));
250 final Reader tikaReader = future.get(getTimeout(content.getSize()), TimeUnit.SECONDS);
252 PushbackReader pushbackReader =
new PushbackReader(tikaReader);
253 int read = pushbackReader.read();
255 throw new InitReaderException(
"Unable to extract text: "
256 +
"Tika returned empty reader for " + content);
258 pushbackReader.unread(read);
261 if (metadataMap == null) {
262 metadataMap =
new HashMap<>();
263 for (String mtdtKey : metadata.names()) {
264 metadataMap.put(mtdtKey, metadata.get(mtdtKey));
268 return new ReaderCharSource(pushbackReader).openStream();
269 }
catch (TimeoutException te) {
270 final String msg = NbBundle.getMessage(this.getClass(),
271 "AbstractFileTikaTextExtract.index.tikaParseTimeout.text",
272 content.getId(), content.getName());
273 throw new InitReaderException(msg, te);
274 }
catch (InitReaderException ex) {
276 }
catch (Exception ex) {
277 AUTOPSY_LOGGER.log(Level.WARNING, String.format(
"Error with file [id=%d] %s, see Tika log for details...",
278 content.getId(), content.getName()));
279 TIKA_LOGGER.log(Level.WARNING,
"Exception: Unable to Tika parse the "
280 +
"content" + content.getId() +
": " + content.getName(),
282 final String msg = NbBundle.getMessage(this.getClass(),
283 "AbstractFileTikaTextExtract.index.exception.tikaParse.msg",
284 content.getId(), content.getName());
285 throw new InitReaderException(msg, ex);
301 private InputStream performOCR(AbstractFile file)
throws InitReaderException {
302 File inputFile = null;
303 File outputFile = null;
305 String tempDirectory = Case.getCurrentCaseThrows().getTempDirectory();
308 String tempFileName = FileUtil.escapeFileName(file.getId() + file.getName());
309 inputFile = Paths.get(tempDirectory, tempFileName).toFile();
310 ContentUtils.writeToFile(content, inputFile);
312 String tempOutputName = FileUtil.escapeFileName(file.getId() + TESSERACT_OUTPUT_FILE_NAME);
313 String outputFilePath = Paths.get(tempDirectory, tempOutputName).toString();
314 String executeablePath = TESSERACT_PATH.toString();
317 ProcessBuilder process =
new ProcessBuilder();
318 process.command(executeablePath,
319 String.format(
"\"%s\"", inputFile.getAbsolutePath()),
320 String.format(
"\"%s\"", outputFilePath),
321 "--tessdata-dir", PlatformUtil.getOcrLanguagePacksPath(),
323 "-l", languagePacks);
327 if (processTerminator != null) {
328 ExecUtil.execute(process, 1, TimeUnit.SECONDS, processTerminator);
330 ExecUtil.execute(process);
333 outputFile =
new File(outputFilePath +
".txt");
335 return new CleanUpStream(outputFile);
336 }
catch (NoCurrentCaseException | IOException ex) {
337 if (outputFile != null) {
340 throw new InitReaderException(
"Could not successfully run Tesseract", ex);
342 if (inputFile != null) {
360 Metadata metadata, ParseContext parseContext) {
368 public Reader
call() throws Exception {
369 return new ParsingReader(parser, stream, metadata, parseContext);
400 public void close() throws IOException {
417 private static File locateTesseractExecutable() {
422 String executableToFindName = Paths.get(TESSERACT_DIR_NAME, TESSERACT_EXECUTABLE).toString();
423 File exeFile = InstalledFileLocator.getDefault().locate(executableToFindName, TikaTextExtractor.class.getPackage().getName(),
false);
424 if (null == exeFile) {
428 if (!exeFile.canExecute()) {
441 public Map<String, String> getMetadata() {
442 if (metadataMap != null) {
443 return ImmutableMap.copyOf(metadataMap);
447 metadataMap =
new HashMap<>();
448 InputStream stream =
new ReadContentInputStream(content);
449 ContentHandler doNothingContentHandler =
new DefaultHandler();
450 Metadata mtdt =
new Metadata();
451 parser.parse(stream, doNothingContentHandler, mtdt);
452 for (String mtdtKey : mtdt.names()) {
453 metadataMap.put(mtdtKey, mtdt.get(mtdtKey));
455 }
catch (IOException | SAXException | TikaException ex) {
456 AUTOPSY_LOGGER.log(Level.WARNING, String.format(
"Error getting metadata for file [id=%d] %s, see Tika log for details...",
457 content.getId(), content.getName()));
458 TIKA_LOGGER.log(Level.WARNING,
"Exception: Unable to get metadata for "
459 +
"content" + content.getId() +
": " + content.getName(), ex);
471 public boolean isSupported() {
472 if (!(content instanceof AbstractFile)) {
476 String detectedType = ((AbstractFile) content).getMIMEType();
477 if (detectedType == null
478 || BINARY_MIME_TYPES.contains(detectedType)
479 || ARCHIVE_MIME_TYPES.contains(detectedType)
480 || (detectedType.startsWith(
"video/") && !detectedType.equals(
"video/x-flv"))
481 || detectedType.equals(SQLITE_MIMETYPE)
486 return TIKA_SUPPORTED_TYPES.contains(detectedType);
494 private static String formatLanguagePacks(List<String> languagePacks) {
495 return String.join(
"+", languagePacks);
505 private static int getTimeout(
long size) {
506 if (size < 1024 * 1024L)
509 }
else if (size < 10 * 1024 * 1024L)
512 }
else if (size < 100 * 1024 * 1024L)
531 public void setExtractionSettings(Lookup context) {
532 if (context != null) {
533 List<ProcessTerminator> terminators =
new ArrayList<>();
534 ImageConfig configInstance = context.lookup(ImageConfig.class);
535 if (configInstance != null) {
536 if (Objects.nonNull(configInstance.getOCREnabled())) {
537 this.tesseractOCREnabled = configInstance.getOCREnabled();
540 if (Objects.nonNull(configInstance.getOCRLanguages())) {
541 this.languagePacks = formatLanguagePacks(configInstance.getOCRLanguages());
544 terminators.add(configInstance.getOCRTimeoutTerminator());
547 ProcessTerminator terminatorInstance = context.lookup(ProcessTerminator.class);
548 if (terminatorInstance != null) {
549 terminators.add(terminatorInstance);
552 if(!terminators.isEmpty()) {
553 this.processTerminator =
new HybridTerminator(terminators);