예제 #1
0
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)
예제 #2
0
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
예제 #3
0
def run(message):
    tika_client = TikaApp(file_jar="./tika-app/tika-app-1.21.jar")
    tika_result = tika_client.extract_only_content(message["path"])

    if (tika_result != None):
        processing_dir = "./data/processing/"
        identifier = str(uuid.uuid4())
        workfile = processing_dir + identifier
        with open(workfile, 'wb') as f:
            f.write(tika_result.encode('UTF-8'))

        new_message = {
            "identifier": identifier,
            "parent": message["identifier"],
            "path": workfile,
            "filename": "pdf.txt",
            "filetype": "unknown",
            "history": [],
            "metadata": {},
            "original_file": False
        }
        sendEvent(new_message)
    extract_images_pymupdf(message)

    sendEvent(message)
예제 #4
0
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"
예제 #5
0
    def __init__(self,
                 index,
                 es_host="localhost:9200",
                 file_jar='/Users/laofeng/es_home/tika-app-1.23.jar',
                 index_content=False,
                 create_index=True,
                 force_renew_index=False,
                 schema_file=None):

        self.tika_app = TikaApp(file_jar)
        self.es = Elasticsearch(es_host)
        self.index = index
        self.index_content = index_content

        #查询索引是否存在
        index_exist = self.es.indices.exists(index)

        #if not index_exist and not create_index:

        if not index_exist and create_index and schema_file:
            with open(schema_file, 'r', encoding='utf-8') as f:
                schema = json.load(f)
                self.es.indices.create(index, schema)

        #如果已经存在,且强制renew,先删除后,再建立
        if index_exist and force_renew_index:
            self.es.indices.delete(index)
            with open(schema_file, 'r', encoding='utf-8') as f:
                schema = json.load(f)
                self.es.indices.create(index, schema)
예제 #6
0
    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
예제 #7
0
def run(message):
    # Text
    tika_client = TikaApp(file_jar="./tika-app/tika-app-1.21.jar")
    tika_result = tika_client.extract_only_content(message["path"])

    if (tika_result != None):
        processing_dir = "./data/processing/"
        identifier = str(uuid.uuid4())
        workfile = processing_dir + identifier
        with open(workfile, 'wb') as f:
            f.write(tika_result.encode('UTF-8'))

        new_message = {
                "identifier": identifier,
                "parent": message["identifier"],
                "path": workfile,
                "filename" : "doc.txt",
                "filetype": "unknown",
                "history": [],
                "metadata": {},
                "original_file": False
            }
        sendEvent(new_message)

    # Images
    with ZipFile(message["path"], 'r') as zipObj:
        processng_dir = "./data/processing"
        tmp_identifier = os.path.join(processng_dir, str(uuid.uuid4()))
        zipObj.extractall(tmp_identifier)
    
        for root, dirs, files in os.walk(tmp_identifier):
            for filename in files:
                if ".png" in filename or ".jpeg" in filename or ".jpg" in filename:
                    new_identifier = str(uuid.uuid4())
                    processing_dest = os.path.join(processng_dir, new_identifier)
                    new_message = {
                        "identifier": new_identifier,
                        "parent": message["identifier"],
                        "path": processing_dest,
                        "filename" : filename,
                        "filetype": "unknown",
                        "history": [],
                        "metadata": {},
                        "original_file": False
                    }
                    shutil.move(os.path.join(root, filename), processing_dest)
                    sendEvent(new_message)
        shutil.rmtree(tmp_identifier)

    sendEvent(message)
예제 #8
0
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"]))
예제 #9
0
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
예제 #10
0
 def __init__(self, tika_jar_path):
     self.tika_client = TikaApp(file_jar=tika_jar_path)
예제 #11
0
def analyse_pdf_archive(pdf_csv, keyword_csv, tika_file_jar, outfile_name):
	# PDF for each day saved as welt_mmdd. File names listed in csv file 'welt_pdf'. Create list of PDF names. 
	with open(pdf_csv, 'r', encoding = 'utf-8-sig') as f:
		reader = csv.reader(f)
		pdf_names = list(reader)
	pdf_names = list(itertools.chain(*pdf_names)) # acts as main data frame to contain individual data frames

	pdf_list = []
	for name in pdf_names:
		pdf_list.append(name + '.pdf')

	# Create list of keywords from 'keyword_stems.csv'
	with open(keyword_csv, 'r', encoding = 'utf-8-sig') as f:
		reader = csv.reader(f)
		keywords = list(reader)
	keywords = list(itertools.chain(*keywords))

	tika_client = TikaApp(file_jar=tika_file_jar)

	a = 1 #set counter to 1

	keyword_counter = []
	for pdf in pdf_list:
		rawText = tika_client.extract_only_content(pdf)
		print("pdf {0} extracted".format(a))
		rawList = rawText.split( )
		
		rawList_nopunct = [word.translate(str.maketrans('', '', string.punctuation)) for word in rawList]
		counts = Counter(rawList_nopunct)
		list_words = counts.most_common()

		keyword_hits_list = []
		for x in range(0, len(list_words)):
			temp = list(list_words[x]) # convert from tuple to list
			temp[1] = str(temp[1]) # change number (at index 1) into string
			n_temp = [(unicodedata.normalize('NFKD', word).encode('ASCII', 'ignore')).lower().decode() for word in temp] #normalised umlauts in data
			
			#check word (at index 0) against list of keywords, add new column = 1 if match, = 0 otherwise.
			hits = 0 
			for i in range(0, len(keywords)):
				if keywords[i] in n_temp[0]:
					hits = hits + 1
			if hits != 0:
				n_temp.append(1)
			else:
				n_temp.append(0)

			keyword_hits = int(n_temp[1])*int(n_temp[2])
			keyword_hits_list.append(keyword_hits)
		
		keyword_counts = sum(keyword_hits_list)
		keyword_counter.append(keyword_counts)

		print("day {0} complete".format(a))

		if list_words != []:
			a = a + 1
		else:
			break
	
	df = pd.DataFrame({"id": pdf_names, "keywords": keyword_counter})
	df.to_csv(outfile_name, index=False)
 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
예제 #13
0
from tikapp import TikaApp

tika_client = TikaApp(
    file_jar="/Users/yma2/Documents/_garage/python/cxm/tika/tika-app-1.20.jar")

analyzeFile = "/Users/yma2/Downloads/Azure_Developer_Guide_eBook_ja-JP.pdf"
print(tika_client.detect_content_type(analyzeFile))
print(tika_client.detect_language(analyzeFile))
print(tika_client.extract_only_content(analyzeFile))
print(tika_client.extract_only_metadata(analyzeFile))
예제 #14
0
 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 extract_text(filename):
     jar_path = os.path.abspath(os.path.join("lib", "tika-app-1.28.jar"))
     tika_client = TikaApp(file_jar=jar_path)
     parsed = tika_client.extract_only_content(filename)
     return parsed
예제 #16
0
def tika_extract_only_content(memory=None):
    tika_client = TikaApp(file_jar=TIKA_APP_JAR, memory_allocation=memory)
    output = tika_client.extract_only_content(path=test_zip)
    return output
예제 #17
0
def tika_detect_language():
    tika_client = TikaApp(file_jar=TIKA_APP_JAR)
    output = tika_client.detect_language(path=test_zip)
    return output
예제 #18
0
    def __init__(self, **kwargs):
        super(TikaProcessing, self).__init__(**kwargs)

        # Init Tika
        self._tika_client = TikaApp(file_jar=self.jar,
                                    memory_allocation=self.memory_allocation)
예제 #19
0
# -*- coding: utf-8 -*- 
# @Time : 2020/12/11 10:25 
# @Author : 王西亚 
# @File : c_doc.py

from tikapp import TikaApp

tika_client = TikaApp(file_jar="/usr/local/Cellar/tika/1.24.1_1/libexec/tika-app-1.24.1.jar")
metadata = tika_client.extract_only_metadata("/Users/wangxiya/Downloads/000101020062805119-00.pdf")
print(type(metadata))
print(metadata)

# from tika import parser

# parsed = parser.from_file('/path/to/file')
# print(parsed["metadata"])
# print(parsed["content"])

# parsed = parser.from_file('/Users/wangxiya/Downloads/000101020062805119-00.pdf', 'http://localhost:9998/tika')
# metadata = parsed["metadata"]
# print(type(metadata))
# print(metadata)
예제 #20
0
 def convert_Tika(self,fname):
     tika_client = TikaApp(file_jar=os.getcwd()+'/tika-app-1.20.jar')
     return tika_client.extract_only_content(fname)
from tikapp import TikaApp
from image_mod import convert_image_to_string
import os

tika_client = TikaApp(
    os.path.join(os.path.dirname(os.path.realpath(__file__)), 'src',
                 'tika-app-1.22.jar'))


def receive_text_from_file(path: str, ext=None):
    text = tika_client.extract_only_content(path)
    if text == "" and ext == 'pdf':
        return convert_image_to_string(path, ext=ext)
    return text
예제 #22
0
def tika_content_type():
    tika_client = TikaApp(file_jar=TIKA_APP_JAR)
    output = tika_client.detect_content_type(path=test_zip)
    return output