Ejemplo n.º 1
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)
Ejemplo n.º 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
Ejemplo n.º 3
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
Ejemplo n.º 4
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)
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)
Ejemplo n.º 6
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))
Ejemplo n.º 7
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
Ejemplo n.º 8
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)
 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
Ejemplo n.º 10
0
class FileBeats:
    # # 建立文件索引
    #只有如下扩展名的文件才会被索引文件内容
    export_content_exts = ('.md', '.html', '.htm', '.txt', '.ppt', '.pptx',
                           '.key', '.pdf', ".pages", ".doc", ".docx", '.py',
                           '.java')

    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)

    # 格式化时间,参数是秒和时间格式
    @staticmethod
    def second2date(second, style="%Y-%m-%d %H:%M:%S"):
        time_array = time.localtime(second)
        date_str = time.strftime(style, time_array)
        return date_str

    def export_file_tags(self, abs_path):
        tags = {"path": abs_path}
        (basename, ext) = os.path.splitext(abs_path)
        tags['ext'] = ext.lstrip('.')  # 去掉了后缀的点
        tags['name'] = os.path.basename(abs_path)
        size = os.path.getsize(abs_path)
        tags['size'] = size

        # 过滤调太大或者太小的文件
        # 文件太大,二进制文件类型不导出content

        if self.index_content and ext.lower() in FileBeats.export_content_exts:
            try:
                r = self.tika_app.extract_only_content(
                    path=abs_path, payload="base64_payload")
                if r:
                    tags['content'] = r
            except Exception as e:
                traceback.print_exc()
        return tags

    # 索引文档
    def index_doc(self, tags, _type='_doc'):
        # index 相当于表名, body被索引的文本(分词)
        tags['timestamp'] = datetime.now()
        # 使用文件全路径做为id
        res = self.es.index(index=self.index,
                            doc_type=_type,
                            body=tags,
                            id=tags['path'])

    def index_docs(self, docs):
        for doc in docs:
            self.index_doc(doc)

    # 处理一个文件,先导出tags,然后索引文档
    def process_file(self, f):
        tags = self.export_file_tags(f)
        self.index_doc(tags)

    def beats_more(self, folders, asynchronous=True):
        print("开始索引文件", FileBeats.second2date(time.time()))
        for folder in folders:
            self.start_beats(folder)

        print("索引文件结束", FileBeats.second2date(time.time()))

    def start_beats(self,
                    source_dir='/Volumes/portable/sync/',
                    asynchronous=True):
        print("开始索引文件", source_dir, FileBeats.second2date(time.time()))
        # 遍历文件
        greenlets = list()
        #index_tasks = list()

        for folder, dirs, files in os.walk(source_dir, topdown=False):
            # 过滤掉一些文件夹

            if '@' in folder or '.svn' in folder or folder.endswith(
                    '.app') or "迅雷" in folder:
                print('忽略目录', folder)
                continue
            for f in files:
                if f.startswith("."):
                    continue
                abs_path = os.path.join(folder, f)
                try:
                    # process_file(abs_path)
                    if asynchronous:
                        greenlets.append(
                            gevent.spawn(self.export_file_tags, abs_path))
                    else:
                        tags = self.export_file_tags(abs_path)
                        self.index_doc(tags)
                    # 任务达到500个,执行一次
                    if len(greenlets) >= 5:
                        gevent.joinall(greenlets)
                        self.index_docs([g.value for g in greenlets])
                        # 使用并发es会出现一个read timeout或者是socket的错误
                        # index_tasks.append(gevent.spawn(index_docs,[g.value for g in greenlets]))
                        greenlets.clear()
                    # if len(index_tasks) > 50:
                    #     gevent.joinall(index_tasks)
                    #     index_tasks.clear()
                except Exception as e:
                    traceback.print_exc()
        # 清理不足5个文件的情况
        if asynchronous:
            gevent.joinall(greenlets)
            self.index_docs([g.value for g in greenlets])
        # index_tasks.append(gevent.spawn(index_docs, [g.value for g in greenlets]))
        # gevent.joinall(index_tasks)

        print("索引文件结束", source_dir, FileBeats.second2date(time.time()))
Ejemplo n.º 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)