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.EmptyParser;
50 import org.apache.tika.parser.ParseContext;
51 import org.apache.tika.parser.Parser;
52 import org.apache.tika.parser.ParsingReader;
53 import org.apache.tika.parser.microsoft.OfficeParserConfig;
54 import org.apache.tika.parser.ocr.TesseractOCRConfig;
55 import org.apache.tika.parser.pdf.PDFParserConfig;
56 import org.openide.util.NbBundle;
57 import org.openide.modules.InstalledFileLocator;
58 import org.openide.util.Lookup;
71 import org.xml.sax.ContentHandler;
72 import org.xml.sax.SAXException;
73 import org.xml.sax.helpers.DefaultHandler;
74 import com.google.common.collect.ImmutableMap;
80 final class TikaTextExtractor
implements TextExtractor {
84 private static final List<String> BINARY_MIME_TYPES
87 "application/octet-stream",
88 "application/x-msdownload");
94 private static final List<String> ARCHIVE_MIME_TYPES
97 "application/x-7z-compressed",
98 "application/x-ace-compressed",
99 "application/x-alz-compressed",
101 "application/vnd.ms-cab-compressed",
102 "application/x-cfs-compressed",
103 "application/x-dgc-compressed",
104 "application/x-apple-diskimage",
105 "application/x-gca-compressed",
109 "application/x-rar-compressed",
110 "application/x-stuffit",
111 "application/x-stuffitx",
112 "application/x-gtar",
113 "application/x-archive",
114 "application/x-executable",
115 "application/x-gzip",
118 "application/x-cpio",
119 "application/x-shar",
121 "application/x-bzip",
122 "application/x-bzip2",
123 "application/x-lzip",
124 "application/x-lzma",
125 "application/x-lzop",
127 "application/x-compress");
130 private static final List<String> EMBEDDED_FILE_MIME_TYPES
131 = ImmutableList.of(
"application/msword",
132 "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
133 "application/vnd.ms-powerpoint",
134 "application/vnd.openxmlformats-officedocument.presentationml.presentation",
135 "application/vnd.ms-excel",
136 "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
140 private static final java.util.logging.Logger TIKA_LOGGER = java.util.logging.Logger.getLogger(
"Tika");
141 private static final Logger AUTOPSY_LOGGER = Logger.getLogger(TikaTextExtractor.class.getName());
143 private final ThreadFactory tikaThreadFactory
144 =
new ThreadFactoryBuilder().setNameFormat(
"tika-reader-%d").build();
145 private final ExecutorService executorService = Executors.newSingleThreadExecutor(tikaThreadFactory);
146 private static final String SQLITE_MIMETYPE =
"application/x-sqlite3";
148 private final AutoDetectParser parser =
new AutoDetectParser();
149 private final Content content;
151 private boolean tesseractOCREnabled;
152 private static final String TESSERACT_DIR_NAME =
"Tesseract-OCR";
153 private static final String TESSERACT_EXECUTABLE =
"tesseract.exe";
154 private static final File TESSERACT_PATH = locateTesseractExecutable();
155 private String languagePacks = formatLanguagePacks(PlatformUtil.getOcrLanguagePacks());
156 private static final String TESSERACT_OUTPUT_FILE_NAME =
"tess_output";
157 private Map<String, String> metadataMap;
159 private ProcessTerminator processTerminator;
161 private static final List<String> TIKA_SUPPORTED_TYPES
162 =
new Tika().getParser().getSupportedTypes(
new ParseContext())
164 .map(mt -> mt.getType() +
"/" + mt.getSubtype())
165 .collect(Collectors.toList());
167 public TikaTextExtractor(Content content) {
168 this.content = content;
178 private boolean ocrEnabled() {
179 return TESSERACT_PATH != null && tesseractOCREnabled
180 && PlatformUtil.isWindowsOS() ==
true && PlatformUtil.is64BitOS();
195 public Reader getReader() throws InitReaderException {
196 InputStream stream = null;
198 ParseContext parseContext =
new ParseContext();
202 if(content instanceof AbstractFile && EMBEDDED_FILE_MIME_TYPES.contains(((AbstractFile)content).getMIMEType())) {
203 parseContext.set(Parser.class,
new EmptyParser());
205 parseContext.set(Parser.class, parser);
208 if (ocrEnabled() && content instanceof AbstractFile) {
209 AbstractFile file = ((AbstractFile) content);
211 if (file.getMIMEType().toLowerCase().startsWith(
"image/")) {
212 stream = performOCR(file);
216 PDFParserConfig pdfConfig =
new PDFParserConfig();
221 pdfConfig.setExtractInlineImages(
true);
223 pdfConfig.setExtractUniqueInlineImagesOnly(
true);
224 parseContext.set(PDFParserConfig.class, pdfConfig);
227 TesseractOCRConfig ocrConfig =
new TesseractOCRConfig();
228 String tesseractFolder = TESSERACT_PATH.getParent();
229 ocrConfig.setTesseractPath(tesseractFolder);
231 ocrConfig.setLanguage(languagePacks);
232 ocrConfig.setTessdataPath(PlatformUtil.getOcrLanguagePacksPath());
233 parseContext.set(TesseractOCRConfig.class, ocrConfig);
235 stream =
new ReadContentInputStream(content);
238 stream =
new ReadContentInputStream(content);
241 Metadata metadata =
new Metadata();
244 OfficeParserConfig officeParserConfig =
new OfficeParserConfig();
245 officeParserConfig.setUseSAXPptxExtractor(
true);
246 officeParserConfig.setUseSAXDocxExtractor(
true);
247 parseContext.set(OfficeParserConfig.class, officeParserConfig);
250 Future<Reader> future = executorService.submit(
251 new GetTikaReader(parser, stream, metadata, parseContext));
253 final Reader tikaReader = future.get(getTimeout(content.getSize()), TimeUnit.SECONDS);
255 PushbackReader pushbackReader =
new PushbackReader(tikaReader);
256 int read = pushbackReader.read();
258 throw new InitReaderException(
"Unable to extract text: "
259 +
"Tika returned empty reader for " + content);
261 pushbackReader.unread(read);
264 if (metadataMap == null) {
265 metadataMap =
new HashMap<>();
266 for (String mtdtKey : metadata.names()) {
267 metadataMap.put(mtdtKey, metadata.get(mtdtKey));
271 return new ReaderCharSource(pushbackReader).openStream();
272 }
catch (TimeoutException te) {
273 final String msg = NbBundle.getMessage(this.getClass(),
274 "AbstractFileTikaTextExtract.index.tikaParseTimeout.text",
275 content.getId(), content.getName());
276 throw new InitReaderException(msg, te);
277 }
catch (InitReaderException ex) {
279 }
catch (Exception ex) {
280 AUTOPSY_LOGGER.log(Level.WARNING, String.format(
"Error with file [id=%d] %s, see Tika log for details...",
281 content.getId(), content.getName()));
282 TIKA_LOGGER.log(Level.WARNING,
"Exception: Unable to Tika parse the "
283 +
"content" + content.getId() +
": " + content.getName(),
285 final String msg = NbBundle.getMessage(this.getClass(),
286 "AbstractFileTikaTextExtract.index.exception.tikaParse.msg",
287 content.getId(), content.getName());
288 throw new InitReaderException(msg, ex);
304 private InputStream performOCR(AbstractFile file)
throws InitReaderException {
305 File inputFile = null;
306 File outputFile = null;
308 String tempDirectory = Case.getCurrentCaseThrows().getTempDirectory();
311 String tempFileName = FileUtil.escapeFileName(file.getId() + file.getName());
312 inputFile = Paths.get(tempDirectory, tempFileName).toFile();
313 ContentUtils.writeToFile(content, inputFile);
315 String tempOutputName = FileUtil.escapeFileName(file.getId() + TESSERACT_OUTPUT_FILE_NAME);
316 String outputFilePath = Paths.get(tempDirectory, tempOutputName).toString();
317 String executeablePath = TESSERACT_PATH.toString();
320 ProcessBuilder process =
new ProcessBuilder();
321 process.command(executeablePath,
322 String.format(
"\"%s\"", inputFile.getAbsolutePath()),
323 String.format(
"\"%s\"", outputFilePath),
324 "--tessdata-dir", PlatformUtil.getOcrLanguagePacksPath(),
326 "-l", languagePacks);
330 if (processTerminator != null) {
331 ExecUtil.execute(process, 1, TimeUnit.SECONDS, processTerminator);
333 ExecUtil.execute(process);
336 outputFile =
new File(outputFilePath +
".txt");
338 return new CleanUpStream(outputFile);
339 }
catch (NoCurrentCaseException | IOException ex) {
340 if (outputFile != null) {
343 throw new InitReaderException(
"Could not successfully run Tesseract", ex);
345 if (inputFile != null) {
363 Metadata metadata, ParseContext parseContext) {
371 public Reader
call() throws Exception {
372 return new ParsingReader(parser, stream, metadata, parseContext);
403 public void close() throws IOException {
420 private static File locateTesseractExecutable() {
425 String executableToFindName = Paths.get(TESSERACT_DIR_NAME, TESSERACT_EXECUTABLE).toString();
426 File exeFile = InstalledFileLocator.getDefault().locate(executableToFindName, TikaTextExtractor.class.getPackage().getName(),
false);
427 if (null == exeFile) {
431 if (!exeFile.canExecute()) {
444 public Map<String, String> getMetadata() {
445 if (metadataMap != null) {
446 return ImmutableMap.copyOf(metadataMap);
450 metadataMap =
new HashMap<>();
451 InputStream stream =
new ReadContentInputStream(content);
452 ContentHandler doNothingContentHandler =
new DefaultHandler();
453 Metadata mtdt =
new Metadata();
454 parser.parse(stream, doNothingContentHandler, mtdt);
455 for (String mtdtKey : mtdt.names()) {
456 metadataMap.put(mtdtKey, mtdt.get(mtdtKey));
458 }
catch (IOException | SAXException | TikaException ex) {
459 AUTOPSY_LOGGER.log(Level.WARNING, String.format(
"Error getting metadata for file [id=%d] %s, see Tika log for details...",
460 content.getId(), content.getName()));
461 TIKA_LOGGER.log(Level.WARNING,
"Exception: Unable to get metadata for "
462 +
"content" + content.getId() +
": " + content.getName(), ex);
474 public boolean isSupported() {
475 if (!(content instanceof AbstractFile)) {
479 String detectedType = ((AbstractFile) content).getMIMEType();
480 if (detectedType == null
481 || BINARY_MIME_TYPES.contains(detectedType)
482 || ARCHIVE_MIME_TYPES.contains(detectedType)
483 || (detectedType.startsWith(
"video/") && !detectedType.equals(
"video/x-flv"))
484 || detectedType.equals(SQLITE_MIMETYPE)
489 return TIKA_SUPPORTED_TYPES.contains(detectedType);
497 private static String formatLanguagePacks(List<String> languagePacks) {
498 return String.join(
"+", languagePacks);
508 private static int getTimeout(
long size) {
509 if (size < 1024 * 1024L)
512 }
else if (size < 10 * 1024 * 1024L)
515 }
else if (size < 100 * 1024 * 1024L)
534 public void setExtractionSettings(Lookup context) {
535 if (context != null) {
536 ImageConfig configInstance = context.lookup(ImageConfig.class);
537 if (configInstance != null) {
538 if (Objects.nonNull(configInstance.getOCREnabled())) {
539 this.tesseractOCREnabled = configInstance.getOCREnabled();
542 if (Objects.nonNull(configInstance.getOCRLanguages())) {
543 this.languagePacks = formatLanguagePacks(configInstance.getOCRLanguages());
547 ProcessTerminator terminatorInstance = context.lookup(ProcessTerminator.class);
548 if (terminatorInstance != null) {
549 this.processTerminator = terminatorInstance;