Skip to main content

TextPrepper is a simple text preprocessing tool designed to modify queries and documents for Langchain applications.

Project description

TextPrepper

TextPrepper is a simple text preprocessing tool designed to modify queries and documents for Langchain applications. It offers a collection of common NLP preprocessing/cleaning techniques from removing newlines to more advanced regex-based removals. This module should help you from simple text/document transformations to seamless integration with Langchain's LCEL workflows.

Installation

[!WARNING] This is my first published pypi package, so there might be some issues. And some preprocessors are not tested yet!

pip install textprepper

Introduction

TextPrepper helps you with the preprocessing steps essential for natural language processing tasks. Data understanding and cleaning are important steps in building effective ML applications, but let's be honest, not everyone has the time to analyze every PDF, text file, or other documents in their company and maybe you can't/are not allowed use tools like unstructured. Additionally I struggled to find an effective tool for creating a preprocessing pipeline that could be easily integrated into my LCEL Chains, e.g. to manipulating the query in the same way I manipulated my documents.

That’s why I began building my own collection of text preprocessors, which I can not only reuse across various projects but also adapt seamlessly into LCEL chains. I primarily adapted the content from berknolgoy's package text-preprocessing and some kaggle examples in object-oriented fashion. My approach was inspired by the torchvision's compose/transform behavior.

Quickstart

[!IMPORTANT] If you're using a preprocessor, it will overwrite the document's page_content inplace!

Example 1: Document Preprocessing / Cleaning

from textprepper.modifiers import LowerText
from textprepper.removers import RemoveNewLines
from textprepper import DocumentPreprocessorPipe
from langchain_core.documents import Document

doc_pipe = DocumentPreprocessorPipe([LowerText(), RemoveNewLines(count=2)])

dummy_doc = Document(page_content="I AM\n\nMr.\nCAPSLOCK")

print(doc_pipe(dummy_doc))

# Output
# page_content='i ammr.\ncapslock'

## Or if you have mutiple documents, use the .from_document() method
dummy_docs = [dummy_doc.copy() for i in range(5)]
results = doc_pipe.from_documents(dummy_docs)

A more detailed guide on basic usages is available here.

Example 2: Query Manipulation

from textprepper.modifiers import GoogleTrans
from langchain.schema.runnable import RunnablePassthrough
from langchain.prompts import ChatPromptTemplate

# Setup an instance to translate the input text to german
translator = GoogleTrans(source_lng="auto",
                         target_lng="german")

# Define a simple LCEL Chain
prompt = ChatPromptTemplate.from_template("""Question: {question}""")
simple_chain = RunnablePassthrough() | translator | prompt
print(simple_chain.invoke("This is a test."))

# Output:
# messages=[HumanMessage(content='Question: Das ist ein Test.')]

Explore a more detailed LCEL integration example in this notebook. You find an example with a retriever here.

Create your custom Preprocessor

To extend TextPrepper with your custom functionality, you can create a new preprocessor by inheriting from the base class, which utilizes Pydantic's BaseModel under the hood.

  • The preprocessor class has one abstract method whichyou need to define process_text()
    • this will get the string of the document, performs the string manipulation and needs to return a string back
  • Optional: You can define the add_metadata() if you want to edit the metadata of the document too. The add_metadata will be called before the process_text method
from textprepper import Preprocessor

class RemoveAllNumbers(Preprocessor):
    # Abstractmethod which you need to define
    def process_text(self, text: str, *args, **kwargs) -> str:
        return ''.join([char for char in text if not char.isdigit()])
    
    # Optional
    def add_metadata(self, doc, **kwargs) -> Dict:
        return {"removed_all_numbers": True}

Note

My primary motivation is to learn and gain practical experience in developing my own PyPI package, which I plan to release soon. This project is an opportunity for me to get practical experience with testing frameworks like pytest, as well as familiarize myself with GitHub actions. This is my first attempt at creating my own module.

I welcome any suggestions for improvements or corrections, so please feel free to share your feedback. I'm eager to learn from your insights.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

textprepper-0.0.1.tar.gz (9.8 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

textprepper-0.0.1-py3-none-any.whl (11.1 kB view details)

Uploaded Python 3

File details

Details for the file textprepper-0.0.1.tar.gz.

File metadata

  • Download URL: textprepper-0.0.1.tar.gz
  • Upload date:
  • Size: 9.8 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: poetry/1.8.2 CPython/3.12.2 Darwin/23.4.0

File hashes

Hashes for textprepper-0.0.1.tar.gz
Algorithm Hash digest
SHA256 39e721de31d218b9ce21650bf5f6bb3d515760ce6fd3db79f546b1807e14e236
MD5 f3581660ade3bbdc74a6cfd52096a5cb
BLAKE2b-256 c3e4082e872565fa8b61bb3ce31d4ed4ddf137a05e82c7e36a8a7082e5ce9a65

See more details on using hashes here.

File details

Details for the file textprepper-0.0.1-py3-none-any.whl.

File metadata

  • Download URL: textprepper-0.0.1-py3-none-any.whl
  • Upload date:
  • Size: 11.1 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: poetry/1.8.2 CPython/3.12.2 Darwin/23.4.0

File hashes

Hashes for textprepper-0.0.1-py3-none-any.whl
Algorithm Hash digest
SHA256 155c6b1f999297e625abe9033e242d516300ae82e138e9255ed104318bb6d7ef
MD5 48afb1a9b3fca812f4865ebe9cd21d7f
BLAKE2b-256 45a81c23e1151206aa10039a53d54cba66aa15d515e09468fe7b7c9520f621db

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page