fast-sentence-segment 0.1.9__tar.gz → 1.2.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (33) hide show
  1. fast_sentence_segment-1.2.0/LICENSE +21 -0
  2. fast_sentence_segment-1.2.0/PKG-INFO +189 -0
  3. fast_sentence_segment-1.2.0/README.md +161 -0
  4. {fast-sentence-segment-0.1.9 → fast_sentence_segment-1.2.0}/fast_sentence_segment/__init__.py +18 -18
  5. {fast-sentence-segment-0.1.9 → fast_sentence_segment-1.2.0}/fast_sentence_segment/bp/__init__.py +1 -1
  6. {fast-sentence-segment-0.1.9 → fast_sentence_segment-1.2.0}/fast_sentence_segment/bp/segmenter.py +65 -68
  7. fast_sentence_segment-1.2.0/fast_sentence_segment/cli.py +56 -0
  8. fast_sentence_segment-1.2.0/fast_sentence_segment/core/__init__.py +4 -0
  9. fast_sentence_segment-1.2.0/fast_sentence_segment/core/base_object.py +18 -0
  10. fast_sentence_segment-1.2.0/fast_sentence_segment/core/stopwatch.py +38 -0
  11. fast_sentence_segment-1.2.0/fast_sentence_segment/dmo/__init__.py +10 -0
  12. fast_sentence_segment-1.2.0/fast_sentence_segment/dmo/abbreviation_merger.py +146 -0
  13. fast_sentence_segment-1.2.0/fast_sentence_segment/dmo/abbreviation_splitter.py +95 -0
  14. fast_sentence_segment-1.2.0/fast_sentence_segment/dmo/abbreviations.py +96 -0
  15. {fast-sentence-segment-0.1.9 → fast_sentence_segment-1.2.0}/fast_sentence_segment/dmo/bullet_point_cleaner.py +55 -55
  16. fast_sentence_segment-1.2.0/fast_sentence_segment/dmo/ellipsis_normalizer.py +45 -0
  17. {fast-sentence-segment-0.1.9 → fast_sentence_segment-1.2.0}/fast_sentence_segment/dmo/newlines_to_periods.py +57 -57
  18. fast_sentence_segment-1.2.0/fast_sentence_segment/dmo/numbered_list_normalizer.py +47 -0
  19. {fast-sentence-segment-0.1.9 → fast_sentence_segment-1.2.0}/fast_sentence_segment/dmo/post_process_sentences.py +48 -48
  20. fast_sentence_segment-1.2.0/fast_sentence_segment/dmo/question_exclamation_splitter.py +59 -0
  21. {fast-sentence-segment-0.1.9 → fast_sentence_segment-1.2.0}/fast_sentence_segment/dmo/spacy_doc_segmenter.py +101 -101
  22. fast_sentence_segment-1.2.0/fast_sentence_segment/dmo/title_name_merger.py +152 -0
  23. {fast-sentence-segment-0.1.9 → fast_sentence_segment-1.2.0}/fast_sentence_segment/svc/__init__.py +2 -2
  24. {fast-sentence-segment-0.1.9 → fast_sentence_segment-1.2.0}/fast_sentence_segment/svc/perform_paragraph_segmentation.py +50 -50
  25. {fast-sentence-segment-0.1.9 → fast_sentence_segment-1.2.0}/fast_sentence_segment/svc/perform_sentence_segmentation.py +165 -129
  26. {fast-sentence-segment-0.1.9 → fast_sentence_segment-1.2.0}/pyproject.toml +52 -61
  27. fast_sentence_segment-1.2.0/setup.py +38 -0
  28. fast-sentence-segment-0.1.9/PKG-INFO +0 -54
  29. fast-sentence-segment-0.1.9/README.md +0 -29
  30. fast-sentence-segment-0.1.9/fast_sentence_segment/dmo/__init__.py +0 -6
  31. fast-sentence-segment-0.1.9/fast_sentence_segment/dmo/delimiters_to_periods.py +0 -37
  32. fast-sentence-segment-0.1.9/fast_sentence_segment/dmo/numbered_list_normalizer.py +0 -53
  33. fast-sentence-segment-0.1.9/setup.py +0 -33
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Craig Trim
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,189 @@
1
+ Metadata-Version: 2.4
2
+ Name: fast-sentence-segment
3
+ Version: 1.2.0
4
+ Summary: Fast and Efficient Sentence Segmentation
5
+ License: MIT
6
+ License-File: LICENSE
7
+ Keywords: nlp,text,preprocess,segment
8
+ Author: Craig Trim
9
+ Author-email: craigtrim@gmail.com
10
+ Maintainer: Craig Trim
11
+ Maintainer-email: craigtrim@gmail.com
12
+ Requires-Python: >=3.9,<4.0
13
+ Classifier: Development Status :: 4 - Beta
14
+ Classifier: License :: OSI Approved :: MIT License
15
+ Classifier: Programming Language :: Python :: 3
16
+ Classifier: Programming Language :: Python :: 3.9
17
+ Classifier: Programming Language :: Python :: 3.10
18
+ Classifier: Programming Language :: Python :: 3.11
19
+ Classifier: Programming Language :: Python :: 3.12
20
+ Classifier: Programming Language :: Python :: 3.13
21
+ Classifier: Programming Language :: Python :: 3.14
22
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
23
+ Requires-Dist: spacy (>=3.8.0,<4.0.0)
24
+ Project-URL: Bug Tracker, https://github.com/craigtrim/fast-sentence-segment/issues
25
+ Project-URL: Repository, https://github.com/craigtrim/fast-sentence-segment
26
+ Description-Content-Type: text/markdown
27
+
28
+ # Fast Sentence Segmentation
29
+
30
+ [![PyPI version](https://img.shields.io/pypi/v/fast-sentence-segment.svg)](https://pypi.org/project/fast-sentence-segment/)
31
+ [![Python versions](https://img.shields.io/pypi/pyversions/fast-sentence-segment.svg)](https://pypi.org/project/fast-sentence-segment/)
32
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
33
+ [![spaCy](https://img.shields.io/badge/spaCy-3.8-blue.svg)](https://spacy.io/)
34
+
35
+ Fast and efficient sentence segmentation using spaCy with surgical post-processing fixes. Handles complex edge cases like abbreviations (Dr., Mr., etc.), ellipses, quoted text, and multi-paragraph documents.
36
+
37
+ ## Why This Library?
38
+
39
+ 1. **Keep it local**: LLM API calls cost money and send your data to third parties. Run sentence segmentation entirely on your machine.
40
+ 2. **spaCy perfected**: spaCy is a great local model, but it makes mistakes. This library fixes most of spaCy's shortcomings.
41
+
42
+ ## Features
43
+
44
+ - **Paragraph-aware segmentation**: Returns sentences grouped by paragraph
45
+ - **Abbreviation handling**: Correctly handles "Dr.", "Mr.", "etc.", "p.m.", "a.m." without false splits
46
+ - **Ellipsis preservation**: Keeps `...` intact while detecting sentence boundaries
47
+ - **Question/exclamation splitting**: Properly splits on `?` and `!` followed by capital letters
48
+ - **Cached processing**: LRU cache for repeated text processing
49
+ - **Flexible output**: Nested lists (by paragraph) or flattened list of sentences
50
+ - **Bullet point & numbered list normalization**: Cleans common list formats
51
+ - **CLI tool**: Command-line interface for quick segmentation
52
+
53
+ ## Installation
54
+
55
+ ```bash
56
+ pip install fast-sentence-segment
57
+ ```
58
+
59
+ After installation, download the spaCy model:
60
+
61
+ ```bash
62
+ python -m spacy download en_core_web_sm
63
+ ```
64
+
65
+ ## Quick Start
66
+
67
+ ```python
68
+ from fast_sentence_segment import segment_text
69
+
70
+ text = "Here is a Dr. who says something. And then again, what else? I don't know. Do you?"
71
+
72
+ results = segment_text(text)
73
+ # Returns: [['Here is a Dr. who says something.', 'And then again, what else?', "I don't know.", 'Do you?']]
74
+ ```
75
+
76
+ ## Usage
77
+
78
+ ### Basic Segmentation
79
+
80
+ The `segment_text` function returns a list of lists, where each inner list represents a paragraph containing its sentences:
81
+
82
+ ```python
83
+ from fast_sentence_segment import segment_text
84
+
85
+ text = """First paragraph here. It has two sentences.
86
+
87
+ Second paragraph starts here. This one also has multiple sentences. And a third."""
88
+
89
+ results = segment_text(text)
90
+ # Returns:
91
+ # [
92
+ # ['First paragraph here.', 'It has two sentences.'],
93
+ # ['Second paragraph starts here.', 'This one also has multiple sentences.', 'And a third.']
94
+ # ]
95
+ ```
96
+
97
+ ### Flattened Output
98
+
99
+ If you don't need paragraph boundaries, use the `flatten` parameter:
100
+
101
+ ```python
102
+ results = segment_text(text, flatten=True)
103
+ # Returns: ['First paragraph here.', 'It has two sentences.', 'Second paragraph starts here.', ...]
104
+ ```
105
+
106
+ ### Direct Segmenter Access
107
+
108
+ For more control, use the `Segmenter` class directly:
109
+
110
+ ```python
111
+ from fast_sentence_segment import Segmenter
112
+
113
+ segmenter = Segmenter()
114
+ results = segmenter.input_text("Your text here.")
115
+ ```
116
+
117
+ ### Command Line Interface
118
+
119
+ Segment text directly from the terminal:
120
+
121
+ ```bash
122
+ # Direct text input
123
+ segment "Hello world. How are you? I am fine."
124
+
125
+ # Numbered output
126
+ segment -n "First sentence. Second sentence."
127
+
128
+ # From stdin
129
+ echo "Some text here. Another sentence." | segment
130
+
131
+ # From file
132
+ segment -f document.txt
133
+ ```
134
+
135
+ ## API Reference
136
+
137
+ | Function | Parameters | Returns | Description |
138
+ |----------|------------|---------|-------------|
139
+ | `segment_text()` | `input_text: str`, `flatten: bool = False` | `list` | Main entry point for segmentation |
140
+ | `Segmenter.input_text()` | `input_text: str` | `list[list[str]]` | Cached paragraph-aware segmentation |
141
+
142
+ ### CLI Options
143
+
144
+ | Option | Description |
145
+ |--------|-------------|
146
+ | `text` | Text to segment (positional argument) |
147
+ | `-f, --file` | Read text from file |
148
+ | `-n, --numbered` | Number output lines |
149
+
150
+ ## Why Nested Lists?
151
+
152
+ The segmentation process preserves document structure by segmenting into both paragraphs and sentences. Each outer list represents a paragraph, and each inner list contains that paragraph's sentences. This is useful for:
153
+
154
+ - Document structure analysis
155
+ - Paragraph-level processing
156
+ - Maintaining original text organization
157
+
158
+ Use `flatten=True` when you only need sentences without paragraph context.
159
+
160
+ ## Requirements
161
+
162
+ - Python 3.9+
163
+ - spaCy 3.8+
164
+ - en_core_web_sm spaCy model
165
+
166
+ ## How It Works
167
+
168
+ This library uses spaCy for initial sentence segmentation, then applies surgical post-processing fixes for cases where spaCy's default behavior is incorrect:
169
+
170
+ 1. **Pre-processing**: Normalize numbered lists, preserve ellipses with placeholders
171
+ 2. **spaCy segmentation**: Use spaCy's sentence boundary detection
172
+ 3. **Post-processing**: Split on abbreviation boundaries, handle `?`/`!` + capital patterns
173
+ 4. **Denormalization**: Restore placeholders to original text
174
+
175
+ ## License
176
+
177
+ MIT License - see [LICENSE](LICENSE) for details.
178
+
179
+ ## Contributing
180
+
181
+ Contributions are welcome! Please feel free to submit a Pull Request.
182
+
183
+ 1. Fork the repository
184
+ 2. Create your feature branch (`git checkout -b feature/amazing-feature`)
185
+ 3. Run tests (`make test`)
186
+ 4. Commit your changes
187
+ 5. Push to the branch
188
+ 6. Open a Pull Request
189
+
@@ -0,0 +1,161 @@
1
+ # Fast Sentence Segmentation
2
+
3
+ [![PyPI version](https://img.shields.io/pypi/v/fast-sentence-segment.svg)](https://pypi.org/project/fast-sentence-segment/)
4
+ [![Python versions](https://img.shields.io/pypi/pyversions/fast-sentence-segment.svg)](https://pypi.org/project/fast-sentence-segment/)
5
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
6
+ [![spaCy](https://img.shields.io/badge/spaCy-3.8-blue.svg)](https://spacy.io/)
7
+
8
+ Fast and efficient sentence segmentation using spaCy with surgical post-processing fixes. Handles complex edge cases like abbreviations (Dr., Mr., etc.), ellipses, quoted text, and multi-paragraph documents.
9
+
10
+ ## Why This Library?
11
+
12
+ 1. **Keep it local**: LLM API calls cost money and send your data to third parties. Run sentence segmentation entirely on your machine.
13
+ 2. **spaCy perfected**: spaCy is a great local model, but it makes mistakes. This library fixes most of spaCy's shortcomings.
14
+
15
+ ## Features
16
+
17
+ - **Paragraph-aware segmentation**: Returns sentences grouped by paragraph
18
+ - **Abbreviation handling**: Correctly handles "Dr.", "Mr.", "etc.", "p.m.", "a.m." without false splits
19
+ - **Ellipsis preservation**: Keeps `...` intact while detecting sentence boundaries
20
+ - **Question/exclamation splitting**: Properly splits on `?` and `!` followed by capital letters
21
+ - **Cached processing**: LRU cache for repeated text processing
22
+ - **Flexible output**: Nested lists (by paragraph) or flattened list of sentences
23
+ - **Bullet point & numbered list normalization**: Cleans common list formats
24
+ - **CLI tool**: Command-line interface for quick segmentation
25
+
26
+ ## Installation
27
+
28
+ ```bash
29
+ pip install fast-sentence-segment
30
+ ```
31
+
32
+ After installation, download the spaCy model:
33
+
34
+ ```bash
35
+ python -m spacy download en_core_web_sm
36
+ ```
37
+
38
+ ## Quick Start
39
+
40
+ ```python
41
+ from fast_sentence_segment import segment_text
42
+
43
+ text = "Here is a Dr. who says something. And then again, what else? I don't know. Do you?"
44
+
45
+ results = segment_text(text)
46
+ # Returns: [['Here is a Dr. who says something.', 'And then again, what else?', "I don't know.", 'Do you?']]
47
+ ```
48
+
49
+ ## Usage
50
+
51
+ ### Basic Segmentation
52
+
53
+ The `segment_text` function returns a list of lists, where each inner list represents a paragraph containing its sentences:
54
+
55
+ ```python
56
+ from fast_sentence_segment import segment_text
57
+
58
+ text = """First paragraph here. It has two sentences.
59
+
60
+ Second paragraph starts here. This one also has multiple sentences. And a third."""
61
+
62
+ results = segment_text(text)
63
+ # Returns:
64
+ # [
65
+ # ['First paragraph here.', 'It has two sentences.'],
66
+ # ['Second paragraph starts here.', 'This one also has multiple sentences.', 'And a third.']
67
+ # ]
68
+ ```
69
+
70
+ ### Flattened Output
71
+
72
+ If you don't need paragraph boundaries, use the `flatten` parameter:
73
+
74
+ ```python
75
+ results = segment_text(text, flatten=True)
76
+ # Returns: ['First paragraph here.', 'It has two sentences.', 'Second paragraph starts here.', ...]
77
+ ```
78
+
79
+ ### Direct Segmenter Access
80
+
81
+ For more control, use the `Segmenter` class directly:
82
+
83
+ ```python
84
+ from fast_sentence_segment import Segmenter
85
+
86
+ segmenter = Segmenter()
87
+ results = segmenter.input_text("Your text here.")
88
+ ```
89
+
90
+ ### Command Line Interface
91
+
92
+ Segment text directly from the terminal:
93
+
94
+ ```bash
95
+ # Direct text input
96
+ segment "Hello world. How are you? I am fine."
97
+
98
+ # Numbered output
99
+ segment -n "First sentence. Second sentence."
100
+
101
+ # From stdin
102
+ echo "Some text here. Another sentence." | segment
103
+
104
+ # From file
105
+ segment -f document.txt
106
+ ```
107
+
108
+ ## API Reference
109
+
110
+ | Function | Parameters | Returns | Description |
111
+ |----------|------------|---------|-------------|
112
+ | `segment_text()` | `input_text: str`, `flatten: bool = False` | `list` | Main entry point for segmentation |
113
+ | `Segmenter.input_text()` | `input_text: str` | `list[list[str]]` | Cached paragraph-aware segmentation |
114
+
115
+ ### CLI Options
116
+
117
+ | Option | Description |
118
+ |--------|-------------|
119
+ | `text` | Text to segment (positional argument) |
120
+ | `-f, --file` | Read text from file |
121
+ | `-n, --numbered` | Number output lines |
122
+
123
+ ## Why Nested Lists?
124
+
125
+ The segmentation process preserves document structure by segmenting into both paragraphs and sentences. Each outer list represents a paragraph, and each inner list contains that paragraph's sentences. This is useful for:
126
+
127
+ - Document structure analysis
128
+ - Paragraph-level processing
129
+ - Maintaining original text organization
130
+
131
+ Use `flatten=True` when you only need sentences without paragraph context.
132
+
133
+ ## Requirements
134
+
135
+ - Python 3.9+
136
+ - spaCy 3.8+
137
+ - en_core_web_sm spaCy model
138
+
139
+ ## How It Works
140
+
141
+ This library uses spaCy for initial sentence segmentation, then applies surgical post-processing fixes for cases where spaCy's default behavior is incorrect:
142
+
143
+ 1. **Pre-processing**: Normalize numbered lists, preserve ellipses with placeholders
144
+ 2. **spaCy segmentation**: Use spaCy's sentence boundary detection
145
+ 3. **Post-processing**: Split on abbreviation boundaries, handle `?`/`!` + capital patterns
146
+ 4. **Denormalization**: Restore placeholders to original text
147
+
148
+ ## License
149
+
150
+ MIT License - see [LICENSE](LICENSE) for details.
151
+
152
+ ## Contributing
153
+
154
+ Contributions are welcome! Please feel free to submit a Pull Request.
155
+
156
+ 1. Fork the repository
157
+ 2. Create your feature branch (`git checkout -b feature/amazing-feature`)
158
+ 3. Run tests (`make test`)
159
+ 4. Commit your changes
160
+ 5. Push to the branch
161
+ 6. Open a Pull Request
@@ -1,18 +1,18 @@
1
- from .bp import *
2
- from .svc import *
3
- from .dmo import *
4
-
5
- from .bp.segmenter import Segmenter
6
-
7
- segment = Segmenter().input_text
8
-
9
-
10
- def segment_text(input_text: str, flatten: bool = False) -> list:
11
- results = segment(input_text)
12
-
13
- if flatten:
14
- flat = []
15
- [[flat.append(y) for y in x] for x in results]
16
- return flat
17
-
18
- return results
1
+ from .bp import *
2
+ from .svc import *
3
+ from .dmo import *
4
+
5
+ from .bp.segmenter import Segmenter
6
+
7
+ segment = Segmenter().input_text
8
+
9
+
10
+ def segment_text(input_text: str, flatten: bool = False) -> list:
11
+ results = segment(input_text)
12
+
13
+ if flatten:
14
+ flat = []
15
+ [[flat.append(y) for y in x] for x in results]
16
+ return flat
17
+
18
+ return results
@@ -1 +1 @@
1
- from .segmenter import Segmenter
1
+ from .segmenter import Segmenter
@@ -1,68 +1,65 @@
1
- #!/usr/bin/env python
2
- # -*- coding: UTF-8 -*-
3
- """ Orchestrate Sentence Segmentation """
4
-
5
-
6
- from functools import lru_cache
7
-
8
- from baseblock import Enforcer
9
- from baseblock import Stopwatch
10
- from baseblock import BaseObject
11
-
12
- from fast_sentence_segment.svc import PerformParagraphSegmentation
13
- from fast_sentence_segment.svc import PerformSentenceSegmentation
14
-
15
-
16
- class Segmenter(BaseObject):
17
- """ Orchestrate Sentence Segmentation """
18
-
19
- def __init__(self):
20
- """ Change Log
21
-
22
- Created:
23
- 30-Sept-2021
24
- """
25
- BaseObject.__init__(self, __name__)
26
- self._segment_paragraphs = PerformParagraphSegmentation().process
27
- self._segment_sentences = PerformSentenceSegmentation().process
28
-
29
- def _input_text(self,
30
- input_text: str) -> list:
31
- paragraphs = []
32
-
33
- for paragraph in self._segment_paragraphs(input_text):
34
- paragraphs.append(self._segment_sentences(paragraph))
35
-
36
- return paragraphs
37
-
38
- @lru_cache(maxsize=1024, typed=True)
39
- def input_text(self,
40
- input_text: str) -> list:
41
- """Segment Input Text into Paragraphs and Sentences
42
-
43
- Args:
44
- input_text (str): An input string of any length or type
45
-
46
- Raises:
47
- ValueError: input must be a string
48
-
49
- Returns:
50
- list: returns a list of lists.
51
- Each outer list is a paragraph.
52
- Each inner list contains 1..* sentences
53
- """
54
-
55
- if self.isEnabledForDebug:
56
- Enforcer.is_str(input_text)
57
-
58
- sw = Stopwatch()
59
-
60
- paragraphs = self._input_text(input_text)
61
-
62
- if self.isEnabledForInfo:
63
- self.logger.info('\n'.join([
64
- "Segmentation of Input Text Complete",
65
- f"\tTotal Paragraphs: {len(paragraphs)}",
66
- f"\tTotal Time: {str(sw)}"]))
67
-
68
- return paragraphs
1
+ #!/usr/bin/env python
2
+ # -*- coding: UTF-8 -*-
3
+ """ Orchestrate Sentence Segmentation """
4
+
5
+
6
+ from functools import lru_cache
7
+
8
+ from fast_sentence_segment.core import BaseObject, Stopwatch
9
+ from fast_sentence_segment.svc import PerformParagraphSegmentation
10
+ from fast_sentence_segment.svc import PerformSentenceSegmentation
11
+
12
+
13
+ class Segmenter(BaseObject):
14
+ """ Orchestrate Sentence Segmentation """
15
+
16
+ def __init__(self):
17
+ """ Change Log
18
+
19
+ Created:
20
+ 30-Sept-2021
21
+ """
22
+ BaseObject.__init__(self, __name__)
23
+ self._segment_paragraphs = PerformParagraphSegmentation().process
24
+ self._segment_sentences = PerformSentenceSegmentation().process
25
+
26
+ def _input_text(self,
27
+ input_text: str) -> list:
28
+ paragraphs = []
29
+
30
+ for paragraph in self._segment_paragraphs(input_text):
31
+ paragraphs.append(self._segment_sentences(paragraph))
32
+
33
+ return paragraphs
34
+
35
+ @lru_cache(maxsize=1024, typed=True)
36
+ def input_text(self,
37
+ input_text: str) -> list:
38
+ """Segment Input Text into Paragraphs and Sentences
39
+
40
+ Args:
41
+ input_text (str): An input string of any length or type
42
+
43
+ Raises:
44
+ ValueError: input must be a string
45
+
46
+ Returns:
47
+ list: returns a list of lists.
48
+ Each outer list is a paragraph.
49
+ Each inner list contains 1..* sentences
50
+ """
51
+
52
+ if self.isEnabledForDebug and not isinstance(input_text, str):
53
+ raise ValueError(f"Expected str, got {type(input_text)}")
54
+
55
+ sw = Stopwatch()
56
+
57
+ paragraphs = self._input_text(input_text)
58
+
59
+ if self.isEnabledForInfo:
60
+ self.logger.info('\n'.join([
61
+ "Segmentation of Input Text Complete",
62
+ f"\tTotal Paragraphs: {len(paragraphs)}",
63
+ f"\tTotal Time: {str(sw)}"]))
64
+
65
+ return paragraphs
@@ -0,0 +1,56 @@
1
+ # -*- coding: UTF-8 -*-
2
+ """CLI for fast-sentence-segment."""
3
+
4
+ import argparse
5
+ import logging
6
+ import sys
7
+
8
+ from fast_sentence_segment import segment_text
9
+
10
+ logging.disable(logging.CRITICAL)
11
+
12
+
13
+ def main():
14
+ parser = argparse.ArgumentParser(
15
+ prog="segment",
16
+ description="Segment text into sentences",
17
+ )
18
+ parser.add_argument(
19
+ "text",
20
+ nargs="?",
21
+ help="Text to segment (or use stdin)",
22
+ )
23
+ parser.add_argument(
24
+ "-f", "--file",
25
+ help="Read text from file",
26
+ )
27
+ parser.add_argument(
28
+ "-n", "--numbered",
29
+ action="store_true",
30
+ help="Number output lines",
31
+ )
32
+ args = parser.parse_args()
33
+
34
+ # Get input text
35
+ if args.file:
36
+ with open(args.file, "r", encoding="utf-8") as f:
37
+ text = f.read()
38
+ elif args.text:
39
+ text = args.text
40
+ elif not sys.stdin.isatty():
41
+ text = sys.stdin.read()
42
+ else:
43
+ parser.print_help()
44
+ sys.exit(1)
45
+
46
+ # Segment and output
47
+ sentences = segment_text(text.strip(), flatten=True)
48
+ for i, sentence in enumerate(sentences, 1):
49
+ if args.numbered:
50
+ print(f"{i}. {sentence}")
51
+ else:
52
+ print(sentence)
53
+
54
+
55
+ if __name__ == "__main__":
56
+ main()
@@ -0,0 +1,4 @@
1
+ from .base_object import BaseObject
2
+ from .stopwatch import Stopwatch
3
+
4
+ __all__ = ["BaseObject", "Stopwatch"]
@@ -0,0 +1,18 @@
1
+ # -*- coding: utf-8 -*-
2
+ """Base object providing logging functionality."""
3
+
4
+ import logging
5
+
6
+ logging.basicConfig(
7
+ format='%(asctime)s : %(levelname)s : %(filename)s : %(funcName)s() : %(lineno)d : %(message)s',
8
+ level=logging.DEBUG)
9
+
10
+
11
+ class BaseObject:
12
+ """Base class providing logging capabilities."""
13
+
14
+ def __init__(self, component_name: str):
15
+ self.logger = logging.getLogger(component_name)
16
+ self.isEnabledForDebug = self.logger.isEnabledFor(logging.DEBUG)
17
+ self.isEnabledForInfo = self.logger.isEnabledFor(logging.INFO)
18
+ self.isEnabledForWarning = self.logger.isEnabledFor(logging.WARNING)
@@ -0,0 +1,38 @@
1
+ # -*- coding: utf-8 -*-
2
+ """Simple stopwatch for timing operations."""
3
+
4
+ import time
5
+
6
+
7
+ class Stopwatch:
8
+ """A simple stopwatch for measuring elapsed time."""
9
+
10
+ def __init__(self):
11
+ self._start = time.perf_counter()
12
+ self._end = None
13
+
14
+ @property
15
+ def duration(self):
16
+ return self._end - self._start if self._end else time.perf_counter() - self._start
17
+
18
+ @property
19
+ def running(self):
20
+ return not self._end
21
+
22
+ def restart(self):
23
+ self._start = time.perf_counter()
24
+ self._end = None
25
+ return self
26
+
27
+ def stop(self):
28
+ if self.running:
29
+ self._end = time.perf_counter()
30
+ return self
31
+
32
+ def __str__(self):
33
+ ms = self.duration * 1000
34
+ if ms >= 1000:
35
+ return f'{ms / 1000:.2f}s'
36
+ if ms >= 1:
37
+ return f'{ms:.2f}ms'
38
+ return f'{ms * 1000:.2f}μs'
@@ -0,0 +1,10 @@
1
+ from .abbreviation_merger import AbbreviationMerger
2
+ from .abbreviation_splitter import AbbreviationSplitter
3
+ from .title_name_merger import TitleNameMerger
4
+ from .bullet_point_cleaner import BulletPointCleaner
5
+ from .ellipsis_normalizer import EllipsisNormalizer
6
+ from .newlines_to_periods import NewlinesToPeriods
7
+ from .post_process_sentences import PostProcessStructure
8
+ from .question_exclamation_splitter import QuestionExclamationSplitter
9
+ from .spacy_doc_segmenter import SpacyDocSegmenter
10
+ from .numbered_list_normalizer import NumberedListNormalizer