class pdf_parser: def __init__(self, tika_jar_path): self.tika_client = TikaApp(file_jar=tika_jar_path) def parse(self, doc_path, file=False): if file: encoded = base64.b64encode(doc_path) content = json.loads( self.tika_client.extract_all_content(payload=encoded)) else: content = json.loads( self.tika_client.extract_all_content(path=doc_path)) content_string = re.sub(r'\n(?![\n])', r'', content[0]['X-TIKA:content']) content_string = re.sub(r'(\n)(\n+)', r'\1', content_string) date_string = content[0].get('Last-Modified') \ or content[0].get('Last-Save-Date') \ or content[0].get('Creation-Date') \ or datetime.now().strftime('%Y-%m-%dT%H:%M:%SZ') if date_string: date_string = str(dateutil.parser.parse(date_string).date()) df = pd.DataFrame(columns=['date', 'content']) df.loc[0] = [date_string, content_string] return df
def main(): args = get_args() tika = TikaApp(args.jar or os.environ.get("TIKA_APP_JAR", None)) parameters = { "path": args.file, "payload": args.payload, "objectInput": sys.stdin if args.stdin else None } try: if args.detect: print(tika.detect_content_type(**parameters)) if args.text: print(tika.extract_only_content(**parameters)) if args.language: print(tika.detect_language(**parameters)) if args.all: parameters["pretty_print"] = True print(tika.extract_all_content(**parameters)) if args.metadata: parameters["pretty_print"] = True print(tika.extract_only_metadata(**parameters)) except IOError: pass
def tika(conf, attachments): """This method updates the attachments results with the Tika reports. Args: attachments (list): all attachments of email conf (dict): conf of this post processor Returns: This method updates the attachments list given """ if conf["enabled"]: from tikapp import TikaApp tika = TikaApp(file_jar=conf["path_jar"], memory_allocation=conf["memory_allocation"]) for a in attachments: if not a.get("is_filtered", False): if a["Content-Type"] in conf["whitelist_cont_types"]: payload = a["payload"] if a["content_transfer_encoding"] != "base64": payload = payload.encode("base64") # tika-app only gets payload in base64 a["tika"] = tika.extract_all_content(payload=payload, convert_to_obj=True)
def getTextFile(nameOfPDF, jarPath): ''' getTextFile("nameOfPDF", path) will take the PDF and output it as a textfile. Path will be taken and used to specify the .jar file needed for tika. Note: Needs the tika-app-1.22.jar and tika-app-python files and folders in the same working directory ''' # get the Tika Object from current directory tika_client = TikaApp(file_jar=join(jarPath, "tika-app-1.22.jar")) # read the pdf with open(nameOfPDF) as fin: # get rid of the .pdf to change to .txt for later if nameOfPDF[-4:] == ".pdf": foutName = nameOfPDF[:-4] else: # if its not .pdf, then just keep the filename foutName = nameOfPDF content = tika_client.extract_all_content(objectInput=fin) # write the pdf to a text file & add .txt to it with open(foutName + ".txt", "w", encoding='utf-8', errors='replace') as fout: fout.write(content) return foutName + ".txt"
def main(): args = get_args() command_line = dict() if args.jar: command_line = {"TIKA_APP_JAR": args.jar} defaults = {"TIKA_APP_JAR": "/opt/tika/tika-app-1.15.jar"} options = ChainMap(command_line, os.environ, defaults) tika = TikaApp(options['TIKA_APP_JAR']) try: if args.file: f = args.file if args.detect: print(tika.detect_content_type(path=f)) if args.text: print(tika.extract_only_content(path=f)) if args.language: print(tika.detect_language(path=f)) if args.all: print(tika.extract_all_content(path=f, pretty_print=True)) elif args.payload: p = args.payload if args.detect: print(tika.detect_content_type(payload=p)) if args.text: print(tika.extract_only_content(payload=p)) if args.language: print(tika.detect_language(payload=p)) if args.all: print(tika.extract_all_content(payload=p, pretty_print=True)) except IOError: pass
class TikaReader(object): def __init__(self, path): self.tika_client = TikaApp(file_jar=path) def detect_type(self, doc): return self.tika_client.detect_content_type(doc) def detect_language(self, doc): return self.tika_client.detect_language(doc) def content(self, doc): return self.tika_client.extract_all_content(doc)
class TikaAnalysis(object): def __init__(self, jar=None, memory_allocation=None, valid_content_types=set()): # Init Tika self._tika_client = TikaApp(file_jar=jar, memory_allocation=memory_allocation) self._jar = jar self._memory_allocation = memory_allocation self._valid_content_types = valid_content_types @property def jar(self): return self._jar @jar.setter def jar(self, value): self._jar = value @property def memory_allocation(self): return self._memory_allocation @memory_allocation.setter def memory_allocation(self, value): self._memory_allocation = value @property def valid_content_types(self): return self._valid_content_types @valid_content_types.setter def valid_content_types(self, value): if not isinstance(value, set): raise InvalidContentTypes("Content types must be a set") self._valid_content_types = value def add_meta_data(self, attachment): """If content_type in valid_content_types this method extracts meta data and update attachments input results. """ if not isinstance(attachment, dict): raise InvalidAttachment("Attachment result is not a dict") # The Apache Tika output of archive contains the contents and metadata # of all archived files. if attachment['Content-Type'] in self.valid_content_types: attachment['tika'] = self._tika_client.extract_all_content( payload=attachment['payload'], convert_to_obj=True)
def handle_backup_file(self,context, savepkt): DebugMessage(context, 100, "handle_backup_file called with " + str(savepkt) + "\n"); DebugMessage(context, 100, "fname: " + savepkt.fname + " Type: " + str(savepkt.type) + "\n"); if ( savepkt.type == bFileType['FT_REG'] ): DebugMessage(context, 100, "regulaer file, do something now...\n"); # configure your Elasticsearch server here: es = Elasticsearch([{'host': '192.168.17.2', 'port': 9200}]) # configure your TikaApp jar file here: try: tika_client = TikaApp(file_jar="/usr/local/bin/tika-app-1.20.jar") except Exception as ex: JobMessage(context, bJobMessageType['M_ERROR'], 'Error indexing %s. Tika error: %s' % (savepkt.fname, str(ex))) return bRCs['bRC_OK']; # tika_client has several parser options # Next one is for metadata only: #result_payload=tika_client.extract_only_metadata(savepkt.fname) # This one includes file contents as text: try: result_payload=tika_client.extract_all_content(savepkt.fname) except Exception as ex: JobMessage(context, bJobMessageType['M_ERROR'], 'Error extracting contents from %s. Tika error: %s' % (savepkt.fname, str(ex))) return bRCs['bRC_OK']; # result_payload is a list of json-strings. Nested structes like # tar-files or emails with attachments or inline documents are # returned as distinct json string. # The first string [0] contains information for the main file # TODO: care about nested structures, for now we only takte the first/main file try: data = json.loads(result_payload)[0] except Exception as ex: JobMessage(context, bJobMessageType['M_ERROR'], 'Error reading json fields delivered by Tika examining file %s. Json error: %s' % (savepkt.fname, str(ex))) return bRCs['bRC_OK']; # Tika eventually adds "Unkonwn Tags (id)", with id as increasing number, which # could lead to exceed the keyword limit in elasticsearch indices, we # remove those tags for data_keyword in data.keys(): if data_keyword.startswith ("Unknown tag ("): del data[data_keyword] # Tika adds some emptylines at the beginning of content, we strip it here if 'X-TIKA:content' in data: data['X-TIKA:content'] = data['X-TIKA:content'].strip() data['bareos_jobId'] = self.jobId data['bareos_fdname'] = self.fdname data['bareos_joblevel'] = unichr(self.level) data['bareos_directory'] = os.path.dirname(savepkt.fname) try: esRes = es.index (index="bareos-test", doc_type='_doc', body=data) except Exception as ex: JobMessage(context, bJobMessageType['M_ERROR'], 'Error indexing %s. Elastic error: %s' % (savepkt.fname, str(ex))) return bRCs['bRC_OK'];
def tika(conf, attachments): """This method updates the attachments results with the Tika reports. Args: attachments (list): all attachments of email conf (dict): conf of this post processor Returns: This method updates the attachments list given """ if conf["enabled"]: from tikapp import TikaApp tika = TikaApp(file_jar=conf["path_jar"], memory_allocation=conf["memory_allocation"]) wtlist = conf.get("whitelist_content_types", []) if not wtlist: log.warning( "Apache Tika analysis setted, without whitelist content types") return for a in attachments: if not a.get("is_filtered", False): if a["Content-Type"] in wtlist: payload = a["payload"] if a["content_transfer_encoding"] != "base64": try: payload = payload.encode("base64") except UnicodeError: # content_transfer_encoding': u'x-uuencode' # it's not binary with strange encoding continue # tika-app only gets payload in base64 try: results = tika.extract_all_content(payload=payload, convert_to_obj=True) if results: a["tika"] = results except JSONDecodeError: log.warning( "JSONDecodeError for {!r} in Tika analysis".format( a["md5"]))
class TikaReader: # Iniciador de la clase. def __init__(self, file_process): # Cliente Tika que utiliza que carga el fichero jar cliente. self.tika_client = TikaApp(file_jar="tika-app-1.20.jar") self.file_process = file_process # Detector del tipo de contenido MIME. def detect_document_type(self): return self.tika_client.detect_content_type(self.file_process) # Detector de lenguaje utilizado en el documento. def detect_language(self): return self.tika_client.detect_language(self.file_process) # Extractor del contenido completo del documento. def extract_complete_info(self, value=False): return self.tika_client.extract_all_content(self.file_process, convert_to_obj=value) # Extractor de solo el contenido del documento. def extract_content_info(self): return self.tika_client.extract_only_content(self.file_process)
class ProcessJSONTika(object): def __init__(self, path): self.tika_client = TikaApp(file_jar=path) def jsonprocessor(self, doc): return self.tika_client.extract_all_content(doc, convert_to_obj=True)[0] def author(self, doc): return self.jsonprocessor(doc).get('Author', None) def creationdate(self, doc): return self.jsonprocessor(doc).get('Creation-Date', None) def lastmodified(self, doc): return self.jsonprocessor(doc).get('Last-Modified', None) def all_content(self, doc): return self.jsonprocessor(doc)['X-TIKA:content'] def top_10_words(self, doc): content = self.all_content(doc) words = word_tokenize(content) # stopwords stopWords = set(stopwords.words('english')) clean_words = [ word for word in words if word.isalpha() and word not in stopWords ] words_dic = {} for i in clean_words: if i in words_dic.keys(): words_dic[i] += 1 else: words_dic[i] = 1 return sorted(words_dic.items(), key=operator.itemgetter(1), reverse=True)[:10]
def tika_extract_all_content(memory=None): tika_client = TikaApp(file_jar=TIKA_APP_JAR, memory_allocation=memory) output = tika_client.extract_all_content(path=test_zip) return output
def handle_backup_file(self, context, savepkt): DebugMessage(context, 100, "handle_backup_file called with " + str(savepkt) + "\n") DebugMessage( context, 100, "fname: " + savepkt.fname + " Type: " + str(savepkt.type) + "\n") if (savepkt.type == bFileType['FT_REG']): DebugMessage(context, 100, "regulaer file, do something now...\n") # configure your Elasticsearch server here: es = Elasticsearch([{'host': '192.168.17.2', 'port': 9200}]) # configure your TikaApp jar file here: try: tika_client = TikaApp( file_jar="/usr/local/bin/tika-app-1.20.jar") except Exception as ex: JobMessage( context, bJobMessageType['M_ERROR'], 'Error indexing %s. Tika error: %s' % (savepkt.fname, str(ex))) return bRCs['bRC_OK'] # tika_client has several parser options # Next one is for metadata only: #result_payload=tika_client.extract_only_metadata(savepkt.fname) # This one includes file contents as text: try: result_payload = tika_client.extract_all_content(savepkt.fname) except Exception as ex: JobMessage( context, bJobMessageType['M_ERROR'], 'Error extracting contents from %s. Tika error: %s' % (savepkt.fname, str(ex))) return bRCs['bRC_OK'] # result_payload is a list of json-strings. Nested structes like # tar-files or emails with attachments or inline documents are # returned as distinct json string. # The first string [0] contains information for the main file # TODO: care about nested structures, for now we only takte the first/main file try: data = json.loads(result_payload)[0] except Exception as ex: JobMessage( context, bJobMessageType['M_ERROR'], 'Error reading json fields delivered by Tika examining file %s. Json error: %s' % (savepkt.fname, str(ex))) return bRCs['bRC_OK'] # Tika eventually adds "Unkonwn Tags (id)", with id as increasing number, which # could lead to exceed the keyword limit in elasticsearch indices, we # remove those tags for data_keyword in data.keys(): if data_keyword.startswith("Unknown tag ("): del data[data_keyword] # Tika adds some emptylines at the beginning of content, we strip it here if 'X-TIKA:content' in data: data['X-TIKA:content'] = data['X-TIKA:content'].strip() data['bareos_jobId'] = self.jobId data['bareos_fdname'] = self.fdname data['bareos_joblevel'] = unichr(self.level) data['bareos_directory'] = os.path.dirname(savepkt.fname) try: esRes = es.index(index="bareos-test", doc_type='_doc', body=data) except Exception as ex: JobMessage( context, bJobMessageType['M_ERROR'], 'Error indexing %s. Elastic error: %s' % (savepkt.fname, str(ex))) return bRCs['bRC_OK']
class TikaProcessing(AbstractProcessing): """ This class processes the output mail attachments to add Apache Tika analysis. Args: jar (string): path of Apache Tika App jar valid_content_types (list or set): list of contents types to analyze memory_allocation (string): memory to give to Apache Tika App """ def __init__(self, **kwargs): super(TikaProcessing, self).__init__(**kwargs) # Init Tika self._tika_client = TikaApp(file_jar=self.jar, memory_allocation=self.memory_allocation) def __getattr__(self, name): try: return self._kwargs[name] except KeyError: # Default values if name in ("memory_allocation"): return None else: msg = "'{0}' object has no attribute '{1}'" raise AttributeError(msg.format(type(self).__name__, name)) def __setattr__(self, name, value): super(TikaProcessing, self).__setattr__(name, value) if name == "valid_content_types": if not isinstance(value, set) and not isinstance(value, list): raise InvalidContentTypes("Content types must be set or list") self._kwargs[name] = value def _check_arguments(self): """This method checks if all mandatory arguments are given. """ if 'jar' not in self._kwargs: msg = "Argument '{0}' not in object '{1}'" raise MissingArgument(msg.format('jar', type(self).__name__)) if 'valid_content_types' not in self._kwargs: msg = "Argument '{0}' not in object '{1}'" raise MissingArgument( msg.format('valid_content_types', type(self).__name__)) def process(self, attachment): """This method updates the attachment result with the Tika output. Args: attachment (dict): dict with a raw attachment mail Returns: This method updates the attachment dict given """ super(TikaProcessing, self).process(attachment) if attachment['Content-Type'] in self.valid_content_types: attachment['tika'] = self._tika_client.extract_all_content( payload=attachment['payload'], convert_to_obj=True)