Apache Tika Python library
Project description
tika-python
A Python port of the Apache Tika library that makes Tika available using the Tika REST Server.
This makes Apache Tika available as a Python library, installable via Setuptools, Pip and Easy Install.
To use this library, you need to have Java 7+ installed on your system as tika-python starts up the Tika REST server in the background.
Inspired by Aptivate Tika.
Installation (with pip)
pip install tika
Installation (without pip)
python setup.py build
python setup.py install
Environment Variables
These are read once, when tika/tika.py is initially loaded and used throughout after that.
TIKA_VERSION
- set to the version string, e.g., 1.12 or default to current Tika version.TIKA_SERVER_JAR
- set to the full URL to the remote Tika server jar to download and cache.TIKA_SERVER_ENDPOINT
- set to the host (local or remote) for the running Tika server jar.TIKA_CLIENT_ONLY
- if set to True, thenTIKA_SERVER_JAR
is ignored, and relies on the value forTIKA_SERVER_ENDPOINT
and treats Tika like a REST client.TIKA_TRANSLATOR
- set to the fully qualified class name (defaults to Lingo24) for the Tika translator implementation.TIKA_SERVER_CLASSPATH
- set to a string (delimited by ':' for each additional path) to prepend to the Tika server jar path.TIKA_LOG_PATH
- set to a directory with write permissions and thetika.log
andtika-server.log
files will be placed in this directory.TIKA_PATH
- set to a directory with write permissions and thetika_server.jar
file will be placed in this directory.TIKA_JAVA
- set the Java runtime name, e.g.,java
orjava9
TIKA_STARTUP_SLEEP
- number of seconds (float
) to wait per check if Tika server is launched at runtimeTIKA_STARTUP_MAX_RETRY
- number of checks (int
) to attempt for Tika server startup if launched at runtimeTIKA_JAVA_ARGS
- set java runtime arguments, e.g,-Xmx4g
Testing it out ==============
Parser Interface (backwards compat prior to REST)
#!/usr/bin/env python
import tika
tika.initVM()
from tika import parser
parsed = parser.from_file('/path/to/file')
print(parsed["metadata"])
print(parsed["content"])
Parser Interface
The parser interface extracts text and metadata using the /rmeta interface. This is one of the better ways to get the internal XHTML content extracted.
Note:
The parser interface needs the following environment variable set on the console for printing of the extracted content.
export PYTHONIOENCODING=utf8
#!/usr/bin/env python
import tika
from tika import parser
parsed = parser.from_file('/path/to/file')
print(parsed["metadata"])
print(parsed["content"])
# Optionally, you can pass Tika server URL along with the call
# what's useful for multi-instance execution or when Tika is dockerzed/linked
parsed = parser.from_file('/path/to/file', 'http://tika:9998/tika')
string_parsed = parser.from_buffer('Good evening, Dave', 'http://tika:9998/tika')
Specify Output Format To XHTML
The parser interface is optionally able to output the content as XHTML rather than plain text.
Note:
The parser interface needs the following environment variable set on the console for printing of the extracted content.
export PYTHONIOENCODING=utf8
#!/usr/bin/env python
import tika
from tika import parser
parsed = parser.from_file('/path/to/file', xmlContent=True)
print(parsed["metadata"])
print(parsed["content"])
# Note: This is also available when parsing from the buffer.
Unpack Interface
The unpack interface handles both metadata and text extraction in a single call and internally returns back a tarball of metadata and text entries that is internally unpacked, reducing the wire load for extraction.
#!/usr/bin/env python
import tika
from tika import unpack
parsed = unpack.from_file('/path/to/file')
Detect Interface
The detect interface provides a IANA MIME type classification for the provided file.
#!/usr/bin/env python
import tika
from tika import detector
print(detector.from_file('/path/to/file'))
Config Interface
The config interface allows you to inspect the Tika Server environment's configuration including what parsers, mime types, and detectors the server has been configured with.
#!/usr/bin/env python
import tika
from tika import config
print(config.getParsers())
print(config.getMimeTypes())
print(config.getDetectors())
Language Detection Interface
The language detection interface provides a 2 character language code texted based on the text in provided file.
#!/usr/bin/env python
from tika import language
print(language.from_file('/path/to/file'))
Translate Interface
The translate interface translates the text automatically extracted by Tika from the source language to the destination language.
#!/usr/bin/env python
from tika import translate
print(translate.from_file('/path/to/spanish', 'es', 'en'))
Using a Buffer
Note you can also use a Parser and Detector .from_buffer(string) method to dynamically parser a string buffer in Python and/or detect its MIME type. This is useful if you've already loaded the content into memory.
Using Client Only Mode
You can set Tika to use Client only mode by setting
import tika
tika.TikaClientOnly = True
Then you can run any of the methods and it will fully omit the check to see if the service on localhost is running and omit printing the check messages.
Changing the Tika Classpath
You can update the classpath that Tika server uses by setting the classpath as a set of ':' delimited strings. For example if you want to get Tika-Python working with GeoTopicParsing, you can do this, replace paths below with your own paths, as identified here and make sure that you have done this:
kill Tika server (if already running):
ps aux | grep java | grep Tika
kill -9 PID
import tika.tika
import os
from tika import parser
home = os.getenv('HOME')
tika.tika.TikaServerClasspath = home + '/git/geotopicparser-utils/mime:'+home+'/git/geotopicparser-utils/models/polar'
parsed = parser.from_file(home + '/git/geotopicparser-utils/geotopics/polar.geot')
print parsed["metadata"]
Customizing the Tika Server Request
You may customize the outgoing HTTP request to Tika server by setting requestOptions
on the .from_file
and .from_buffer
methods (Parser, Unpack , Detect, Config, Language, Translate). It should be a dictionary of arguments that will be passed to the request method. The request method documentation specifies valid arguments. This will override any defaults except for url
and params
/data
.
from tika import parser
parsed = parser.from_file('/path/to/file', requestOptions={'timeout': 120})
New Command Line Client Tool
When you install Tika-Python you also get a new command
line client tool, tika-python
installed in your /path/to/python/bin
directory.
The options and help for the command line tool can be seen by typing
tika-python
without any arguments. This will also download a copy of
the tika-server jar and start it if you haven't done so already.
tika.py [-v] [-o <outputDir>] [--server <TikaServerEndpoint>] [--install <UrlToTikaServerJar>] [--port <portNumber>] <command> <option> <urlOrPathToFile>
tika.py parse all test.pdf test2.pdf (write output JSON metadata files for test1.pdf_meta.json and test2.pdf_meta.json)
tika.py detect type test.pdf (returns mime-type as text/plain)
tika.py language file french.txt (returns language e.g., fr as text/plain)
tika.py translate fr:en french.txt (translates the file french.txt from french to english)
tika.py config mime-types (see what mime-types the Tika Server can handle)
A simple python and command-line client for Tika using the standalone Tika server (JAR file).
All commands return results in JSON format by default (except text in text/plain).
To parse docs, use:
tika.py parse <meta | text | all> <path>
To check the configuration of the Tika server, use:
tika.py config <mime-types | detectors | parsers>
Commands:
parse = parse the input file and write a JSON doc file.ext_meta.json containing the extracted metadata, text, or both
detect type = parse the stream and 'detect' the MIME/media type, return in text/plain
language file = parse the file stream and identify the language of the text, return its 2 character code in text/plain
translate src:dest = parse and extract text and then translate the text from source language to destination language
config = return a JSON doc describing the configuration of the Tika server (i.e. mime-types it
can handle, or installed detectors or parsers)
Arguments:
urlOrPathToFile = file to be parsed, if URL it will first be retrieved and then passed to Tika
Switches:
--verbose, -v = verbose mode
--encode, -e = encode response in UTF-8
--csv, -c = report detect output in comma-delimited format
--server <TikaServerEndpoint> = use a remote Tika Server at this endpoint, otherwise use local server
--install <UrlToTikaServerJar> = download and exec Tika Server (JAR file), starting server on default port 9998
Example usage as python client:
-- from tika import runCommand, parse1
-- jsonOutput = runCommand('parse', 'all', filename)
or
-- jsonOutput = parse1('all', filename)
Questions, comments?
Send them to Chris A. Mattmann.
Contributors
- Chris A. Mattmann, JPL
- Brian D. Wilson, JPL
- Dongni Zhao, USC
- Kenneth Durri, University of Maryland
- Tyler Palsulich, New York University & Google
- Joe Germuska, Northwestern University
- Vlad Shvedov, Profinda.com
- Diogo Vieira, Globo.com
- Aron Ahmadia, Continuum Analytics
- Karanjeet Singh, USC
- Renat Nasyrov, Yandex
- James Brooking, Blackbeard
- Yash Tanna, USC
- Igor Tokarev, Freelance
- Imraan Parker, Freelance
- Annie K. Didier, JPL
Thanks
Thanks to the DARPA MEMEX program for funding most of the original portions of this work.
License
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
File details
Details for the file tika-1.22.tar.gz
.
File metadata
- Download URL: tika-1.22.tar.gz
- Upload date:
- Size: 27.4 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/1.15.0 pkginfo/1.5.0.1 requests/2.22.0 setuptools/40.8.0 requests-toolbelt/0.9.1 tqdm/4.38.0 CPython/2.7.16
File hashes
Algorithm | Hash digest | |
---|---|---|
SHA256 | a090a0968e7224e12df6d37e2fe4e809397bd87be54778f44621906f3afa1c8a |
|
MD5 | 540e2e86d044a5714df38d96a8d22fa1 |
|
BLAKE2b-256 | 0e0fddb78a3220c07be34e7cf8105daee7080eb0947796498c6f2a01284b0c29 |
File details
Details for the file tika-1.22-py3.7.egg
.
File metadata
- Download URL: tika-1.22-py3.7.egg
- Upload date:
- Size: 47.6 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/1.15.0 pkginfo/1.5.0.1 requests/2.22.0 setuptools/40.8.0 requests-toolbelt/0.9.1 tqdm/4.38.0 CPython/2.7.16
File hashes
Algorithm | Hash digest | |
---|---|---|
SHA256 | 03b6cac5292cce0e88cb063ff63023782cbc6bea6add041b5a0524ba12e0f35c |
|
MD5 | b8df49fc04ca43f8bd4b44742a361f93 |
|
BLAKE2b-256 | e27756d44532616852d0fa089cf396c76767aa0f7f9ca718fcf962b109aeaf29 |