Skip to main content

dehyphen PyPI PyPI - Python Version PyPI - Downloads

Experimental, use with care.

Python package for dehyphenation of broken text, i.e., extracted from a PDF. Mainly for German but works for other languages as well.

dehyphen tries to reconstruct the original continuous text by choosing the most probable way to join lines or paragraphs (and remove hyphens). Several options get scored by calculating the perplexity of the text, using the character-based language models of Flair. The option with the lowest perplexity wins.

Check out the PDF text extraction pipeline pd3f that uses dehyphen internally.

An Example

For this input

die Bedeutung der finan-

ziellen Interessen der Union

dehyphen joins the lines and removes the '-'.

die Bedeutung der finanziellen Interessen der Union

But in this example

Auch andere EU-

Staaten, wie bspw. Polen,

the lines are also joined but the hyphen is kept (because it's part of the word).

Auch andere EU-Staaten, wie bspw. Polen,

Installation

pip install dehyphen

dehyphen requires Python 3.10 or newer and PyTorch. On x86-64 Linux, pip installs PyTorch with CUDA support by default, which is a large download. If you don't have a GPU, install the CPU build first:

pip install torch --index-url https://download.pytorch.org/whl/cpu

Usage

from dehyphen import FlairScorer, format_to_text, text_to_format

scorer = FlairScorer(lang="de")

Set lang to de for German, en for English, es for Spanish etc. Without lang, a multilingual model is used. All available models are listed in dehyphen/flair_lm.py; omit the -forward / -backward suffix. Some languages only have a forward model, set backward=False for them.

To speed up computations, set fast=True to get a smaller model (the ones ending in -fast). Only a few languages have one. FlairScorer(lang="multi-v0", fast=True) is a small model that covers English, German, French, Italian, Dutch and Polish.

The models get downloaded on first use to $FLAIR_CACHE_ROOT or ~/.flair, the directory Flair uses, so most models Flair already downloaded get reused. Set cache to choose another directory. The models are loaded with a restricted unpickler that only accepts the objects contained in Flair's language models.

A GPU dramatically improves performance. CUDA is used if available, set device (e.g. device="cpu" or device="mps") to choose explicitly.

Input format

All functions work on paragraphs, lines and words: a paragraph is a list of lines, a line is a list of words. Within a paragraph, the last word of every line but the last ends with a single whitespace character (a space or \n) that joins it to the next line; all other words have none. text_to_format converts text into a list of paragraphs: paragraphs are separated by empty lines (or lines of only whitespace), lines by a newline, which becomes a space. format_to_text joins the paragraphs back into text, separated by an empty line.

text_to_format(
    "die Bedeutung der finan-\nziellen Interessen\n\nAuch andere EU-\nStaaten"
)
# [[['die', 'Bedeutung', 'der', 'finan- '], ['ziellen', 'Interessen']],
#  [['Auch', 'andere', 'EU- '], ['Staaten']]]

Passing a plain string instead raises a TypeError.

1. Remove hyphens from the end of a line (within paragraphs)

# returns the cleaned paragraphs
paragraphs = scorer.dehyphen(text_to_format(text))

# or a single paragraph
paragraph = scorer.dehyphen_paragraph(lines)

2. Join paragraphs, e.g., to reverse a page break

# returns the joined paragraph if the language model thinks it was split, otherwise `None`
joined = scorer.is_split_paragraph(paragraph_1, paragraph_2)

3. Score your own options

score returns the perplexity for each text, summed over the forward and backward model; lower means more likely. Give the model some context, single word fragments score poorly.

scorer.score(["finanziellen Interessen", "finan-ziellen Interessen"])
# [4.15, 11.05]: the first option is more likely

Example

from dehyphen import FlairScorer, format_to_text, text_to_format

scorer = FlairScorer(lang="de")

text = """Zwar wird durch die Einführung eines eigenen Strafgesetzes die Bedeutung der finan-
ziellen Interessen der Union gewiss unterstrichen, dennoch erscheint die Aufspaltung
des strafrechtlichen Vermögensschutzes zweifelhaft. Zum anderen ergeben sich potentielle Auslegungsdif-

ferenzen durch die Verwendung teilweise abweichender Terminologie (finanzielle In-
teressen vs. Vermögen).

Auch andere EU-
Staaten, wie bspw. Polen, liegen im Hinblick auf den Erfolg näher bei der Richtlinie."""

paragraphs = scorer.dehyphen(text_to_format(text))

# join the first two paragraphs if they were split, e.g. by a page break
joined = scorer.is_split_paragraph(paragraphs[0], paragraphs[1])
if joined is not None:
    paragraphs = [joined] + paragraphs[2:]

print(format_to_text(paragraphs))

Output text:

Zwar wird durch die Einführung eines eigenen Strafgesetzes die Bedeutung der finanziellen Interessen der Union gewiss unterstrichen, dennoch erscheint die Aufspaltung des strafrechtlichen Vermögensschutzes zweifelhaft. Zum anderen ergeben sich potentielle Auslegungsdifferenzen durch die Verwendung teilweise abweichender Terminologie (finanzielle Interessen vs. Vermögen).

Auch andere EU-Staaten, wie bspw. Polen, liegen im Hinblick auf den Erfolg näher bei der Richtlinie.

Hyphens are removed, the paragraphs split by the page break are joined along Auslegungsdifferenzen, and EU-Staaten keeps its hyphen.

Changes in 0.4.0

  • Flair is no longer a dependency: dehyphen loads Flair's language models itself and works with current PyTorch. FlairScorer.lms holds these models, their calculate_perplexity is now perplexity.
  • cache sets the model directory of this scorer instead of Flair's global cache.
  • Malformed input raises a TypeError or ValueError instead of an AssertionError.
  • text_to_format always returns a list of paragraphs, also for text without an empty line, and drops empty paragraphs.

Development

poetry install
poetry run pytest

License

GPLv3

Metadata

Release files for dehyphen 0.4.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for dehyphen 0.4.0
File Size Uploaded Provenance Actions
dehyphen-0.4.0.tar.gz 20.8 kB Without provenance Details for dehyphen-0.4.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for dehyphen 0.4.0
File Interpreter ABI Platform Actions
dehyphen-0.4.0-py3-none-any.whl Python 3 none any Details for dehyphen-0.4.0-py3-none-any.whl

Total release size: 43.5 kB

Release files / dehyphen-0.4.0.tar.gz

Download URL dehyphen-0.4.0.tar.gz
Size 20.8 kB
Tags Source
SHA-256 checksum
How to use checksums
82253df85751111b4809c9634dd9696e051516a5192410b3ee3148e500989b03
BLAKE2b-256 checksum
How to use checksums
933fddd62fc3fef5099434fcca38a9303d70b7362817cc326821051055c09d83
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via poetry/2.5.1 CPython/3.14.8 Darwin/24.6.0

Release files / dehyphen-0.4.0-py3-none-any.whl

Download URL dehyphen-0.4.0-py3-none-any.whl
Size 22.7 kB
Tags Python 3
SHA-256 checksum
How to use checksums
d9a5f265bd7d4cdb7052dca38e01b26eb36526003f430814b9737ef45790eab1
BLAKE2b-256 checksum
How to use checksums
ee512adb12ba7cb230fce926aebc69f002ec866d7a83c3ddf404bdae737f9a54
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via poetry/2.5.1 CPython/3.14.8 Darwin/24.6.0

Security for dehyphen 0.4.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page