fast-sentence-segment 1.4.3__py3-none-any.whl → 1.4.5__py3-none-any.whl

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.
@@ -1,3 +1,5 @@
1
+ from typing import List, Optional, Union
2
+
1
3
  from .bp import *
2
4
  from .svc import *
3
5
  from .dmo import *
@@ -5,6 +7,7 @@ from .dmo import *
5
7
  from .bp.segmenter import Segmenter
6
8
  from .dmo.unwrap_hard_wrapped_text import unwrap_hard_wrapped_text
7
9
  from .dmo.normalize_quotes import normalize_quotes
10
+ from .dmo.dialog_formatter import format_dialog
8
11
 
9
12
  segment = Segmenter().input_text
10
13
 
@@ -14,7 +17,8 @@ def segment_text(
14
17
  flatten: bool = False,
15
18
  unwrap: bool = False,
16
19
  normalize: bool = True,
17
- ) -> list:
20
+ format: Optional[str] = None,
21
+ ) -> Union[List, str]:
18
22
  """Segment text into sentences.
19
23
 
20
24
  Args:
@@ -26,14 +30,23 @@ def segment_text(
26
30
  normalize: If True (default), normalize unicode quote variants
27
31
  to ASCII equivalents before segmenting. Ensures consistent
28
32
  quote characters for downstream processing.
33
+ format: Optional output format. Supported values:
34
+ - None (default): Return list of sentences/paragraphs
35
+ - "dialog": Return formatted string with dialog-aware
36
+ paragraph grouping (keeps multi-sentence quotes together,
37
+ adds paragraph breaks between speakers)
29
38
 
30
39
  Returns:
31
- List of sentences (if flatten=True) or list of paragraph
32
- groups, each containing a list of sentences.
40
+ If format is None: List of sentences (if flatten=True) or list
41
+ of paragraph groups, each containing a list of sentences.
42
+ If format="dialog": Formatted string with paragraph breaks.
33
43
 
34
- Related GitHub Issue:
44
+ Related GitHub Issues:
35
45
  #6 - Review findings from Issue #5
36
46
  https://github.com/craigtrim/fast-sentence-segment/issues/6
47
+
48
+ #10 - feat: Add --format flag for dialog-aware paragraph formatting
49
+ https://github.com/craigtrim/fast-sentence-segment/issues/10
37
50
  """
38
51
  if unwrap:
39
52
  input_text = unwrap_hard_wrapped_text(input_text)
@@ -43,9 +56,15 @@ def segment_text(
43
56
 
44
57
  results = segment(input_text)
45
58
 
59
+ # Flatten to list of sentences
60
+ flat = []
61
+ [[flat.append(y) for y in x] for x in results]
62
+
63
+ # Apply formatting if requested
64
+ if format == "dialog":
65
+ return format_dialog(flat)
66
+
46
67
  if flatten:
47
- flat = []
48
- [[flat.append(y) for y in x] for x in results]
49
68
  return flat
50
69
 
51
70
  return results
@@ -97,6 +97,11 @@ def main():
97
97
  action="store_true",
98
98
  help="Unwrap hard-wrapped lines and dehyphenate split words",
99
99
  )
100
+ parser.add_argument(
101
+ "--format",
102
+ action="store_true",
103
+ help="Format output with dialog-aware paragraph grouping",
104
+ )
100
105
  args = parser.parse_args()
101
106
 
102
107
  # Get input text
@@ -112,12 +117,80 @@ def main():
112
117
  sys.exit(1)
113
118
 
114
119
  # Segment and output
115
- sentences = segment_text(text.strip(), flatten=True, unwrap=args.unwrap)
116
- for i, sentence in enumerate(sentences, 1):
117
- if args.numbered:
118
- print(f"{i}. {sentence}")
119
- else:
120
- print(sentence)
120
+ result = segment_text(
121
+ text.strip(), flatten=True, unwrap=args.unwrap,
122
+ format="dialog" if args.format else None
123
+ )
124
+
125
+ # If format is used, result is a string
126
+ if args.format:
127
+ print(result)
128
+ else:
129
+ # Result is a list of sentences
130
+ for i, sentence in enumerate(result, 1):
131
+ if args.numbered:
132
+ print(f"{i}. {sentence}")
133
+ else:
134
+ print(sentence)
135
+
136
+
137
+ def _generate_output_path(input_path: str) -> str:
138
+ """Generate output path by inserting -clean before extension."""
139
+ base, ext = os.path.splitext(input_path)
140
+ return f"{base}-clean{ext}"
141
+
142
+
143
+ def _process_single_file(
144
+ input_file: str, output_file: str, unwrap: bool, normalize: bool, format: str = None
145
+ ):
146
+ """Process a single file and write output."""
147
+ # Show configuration
148
+ _param("Input", input_file)
149
+ _param("Output", output_file)
150
+ _param("Size", _file_size(input_file))
151
+ _param("Unwrap", "enabled" if unwrap else "disabled")
152
+ _param("Normalize quotes", "disabled" if not normalize else "enabled")
153
+ _param("Format", format if format else "default (one sentence per line)")
154
+ print()
155
+
156
+ # Step 1: Read file
157
+ print(f" {YELLOW}→{RESET} Reading input file...")
158
+ with open(input_file, "r", encoding="utf-8") as f:
159
+ text = f.read()
160
+ print(f" {GREEN}✓{RESET} Read {len(text):,} characters")
161
+
162
+ # Step 2: Segment text
163
+ print(f" {YELLOW}→{RESET} Segmenting text...", end="", flush=True)
164
+ start = time.perf_counter()
165
+ result = segment_text(
166
+ text.strip(), flatten=True, unwrap=unwrap, normalize=normalize, format=format,
167
+ )
168
+ elapsed = time.perf_counter() - start
169
+
170
+ # Step 3: Write output
171
+ if format:
172
+ # Format mode returns a string
173
+ sentence_count = result.count("\n") + 1 if result else 0
174
+ print(f"\r {GREEN}✓{RESET} Segmented text ({elapsed:.2f}s)")
175
+ with open(output_file, "w", encoding="utf-8") as f:
176
+ f.write(result + "\n")
177
+ print(f" {GREEN}✓{RESET} Written formatted output to {output_file}")
178
+ else:
179
+ # Default mode returns a list
180
+ sentences = result
181
+ print(f"\r {GREEN}✓{RESET} Segmented into {len(sentences):,} sentences ({elapsed:.2f}s)")
182
+ total = len(sentences)
183
+ with open(output_file, "w", encoding="utf-8") as f:
184
+ if unwrap:
185
+ f.write(format_grouped_sentences(sentences) + "\n")
186
+ print(f" {GREEN}✓{RESET} Written {total:,} sentences to {output_file}")
187
+ else:
188
+ for i, sentence in enumerate(sentences, 1):
189
+ f.write(sentence + "\n")
190
+ if i % 500 == 0 or i == total:
191
+ pct = (i / total) * 100
192
+ print(f"\r {YELLOW}→{RESET} Writing... {pct:.0f}% ({i:,}/{total:,})", end="", flush=True)
193
+ print(f"\r {GREEN}✓{RESET} Written {total:,} sentences to {output_file} ")
121
194
 
122
195
 
123
196
  def file_main():
@@ -126,12 +199,16 @@ def file_main():
126
199
  description="Segment a text file into sentences and write to an output file",
127
200
  )
128
201
  parser.add_argument(
129
- "--input-file", required=True,
202
+ "--input-file",
130
203
  help="Path to input text file",
131
204
  )
132
205
  parser.add_argument(
133
- "--output-file", required=True,
134
- help="Path to output file",
206
+ "--input-dir",
207
+ help="Path to directory containing text files to process",
208
+ )
209
+ parser.add_argument(
210
+ "--output-file",
211
+ help="Path to output file (optional, defaults to input-file with -clean suffix)",
135
212
  )
136
213
  parser.add_argument(
137
214
  "--unwrap", action="store_true",
@@ -141,50 +218,77 @@ def file_main():
141
218
  "--no-normalize-quotes", action="store_true",
142
219
  help="Disable unicode quote normalization to ASCII equivalents",
143
220
  )
221
+ parser.add_argument(
222
+ "--format",
223
+ action="store_true",
224
+ help="Format output with dialog-aware paragraph grouping",
225
+ )
144
226
  args = parser.parse_args()
145
227
 
146
- # Echo command immediately
147
- _header("segment-file")
148
- print(f" {DIM}Segmenting text file into sentences{RESET}")
149
- print()
228
+ # Validate arguments
229
+ if not args.input_file and not args.input_dir:
230
+ print(f" {YELLOW}Error:{RESET} Either --input-file or --input-dir is required")
231
+ sys.exit(1)
232
+ if args.input_file and args.input_dir:
233
+ print(f" {YELLOW}Error:{RESET} Cannot specify both --input-file and --input-dir")
234
+ sys.exit(1)
235
+ if args.input_dir and args.output_file:
236
+ print(f" {YELLOW}Error:{RESET} --output-file cannot be used with --input-dir")
237
+ sys.exit(1)
150
238
 
151
- # Show configuration
152
- _param("Input", args.input_file)
153
- _param("Output", args.output_file)
154
- _param("Size", _file_size(args.input_file))
155
- _param("Unwrap", "enabled" if args.unwrap else "disabled")
156
- _param("Normalize quotes", "disabled" if args.no_normalize_quotes else "enabled")
157
- print()
239
+ normalize = not args.no_normalize_quotes
158
240
 
159
- # Step 1: Read file
160
- print(f" {YELLOW}→{RESET} Reading input file...")
161
- with open(args.input_file, "r", encoding="utf-8") as f:
162
- text = f.read()
163
- print(f" {GREEN}✓{RESET} Read {len(text):,} characters")
241
+ # Process directory
242
+ if args.input_dir:
243
+ if not os.path.isdir(args.input_dir):
244
+ print(f" {YELLOW}Error:{RESET} Directory not found: {args.input_dir}")
245
+ sys.exit(1)
246
+
247
+ # Find all .txt files
248
+ txt_files = sorted([
249
+ f for f in os.listdir(args.input_dir)
250
+ if f.endswith(".txt") and not f.endswith("-clean.txt")
251
+ ])
252
+
253
+ if not txt_files:
254
+ print(f" {YELLOW}Error:{RESET} No .txt files found in {args.input_dir}")
255
+ sys.exit(1)
256
+
257
+ _header("segment-file (batch)")
258
+ print(f" {DIM}Processing {len(txt_files)} files in directory{RESET}")
259
+ print()
260
+ _param("Directory", args.input_dir)
261
+ _param("Files", str(len(txt_files)))
262
+ _param("Unwrap", "enabled" if args.unwrap else "disabled")
263
+ _param("Normalize quotes", "disabled" if not normalize else "enabled")
264
+ _param("Format", "dialog" if args.format else "default (one sentence per line)")
265
+ print()
266
+
267
+ format_value = "dialog" if args.format else None
268
+ for i, filename in enumerate(txt_files, 1):
269
+ input_path = os.path.join(args.input_dir, filename)
270
+ output_path = _generate_output_path(input_path)
271
+ print(f" {BOLD}[{i}/{len(txt_files)}]{RESET} {filename}")
272
+ _process_single_file(input_path, output_path, args.unwrap, normalize, format_value)
273
+ print()
274
+
275
+ print(f" {GREEN}Done! Processed {len(txt_files)} files.{RESET}")
276
+ print()
277
+ return
278
+
279
+ # Process single file
280
+ if not os.path.isfile(args.input_file):
281
+ print(f" {YELLOW}Error:{RESET} File not found: {args.input_file}")
282
+ sys.exit(1)
164
283
 
165
- # Step 2: Segment text
166
- print(f" {YELLOW}→{RESET} Segmenting text...", end="", flush=True)
167
- start = time.perf_counter()
168
- normalize = not args.no_normalize_quotes
169
- sentences = segment_text(
170
- text.strip(), flatten=True, unwrap=args.unwrap, normalize=normalize,
171
- )
172
- elapsed = time.perf_counter() - start
173
- print(f"\r {GREEN}✓{RESET} Segmented into {len(sentences):,} sentences ({elapsed:.2f}s)")
284
+ output_file = args.output_file or _generate_output_path(args.input_file)
174
285
 
175
- # Step 3: Write output
176
- total = len(sentences)
177
- with open(args.output_file, "w", encoding="utf-8") as f:
178
- if args.unwrap:
179
- f.write(format_grouped_sentences(sentences) + "\n")
180
- print(f" {GREEN}✓{RESET} Written {total:,} sentences to {args.output_file}")
181
- else:
182
- for i, sentence in enumerate(sentences, 1):
183
- f.write(sentence + "\n")
184
- if i % 500 == 0 or i == total:
185
- pct = (i / total) * 100
186
- print(f"\r {YELLOW}→{RESET} Writing... {pct:.0f}% ({i:,}/{total:,})", end="", flush=True)
187
- print(f"\r {GREEN}✓{RESET} Written {total:,} sentences to {args.output_file} ")
286
+ _header("segment-file")
287
+ print(f" {DIM}Segmenting text file into sentences{RESET}")
288
+ print()
289
+
290
+ format_value = "dialog" if args.format else None
291
+ _process_single_file(args.input_file, output_file, args.unwrap, normalize, format_value)
188
292
 
189
293
  print(f"\n {GREEN}Done!{RESET}")
190
294
  print()
@@ -13,3 +13,5 @@ from .unwrap_hard_wrapped_text import unwrap_hard_wrapped_text
13
13
  from .normalize_quotes import normalize_quotes
14
14
  from .group_quoted_sentences import group_quoted_sentences, format_grouped_sentences
15
15
  from .strip_trailing_period_after_quote import StripTrailingPeriodAfterQuote
16
+ from .ocr_artifact_fixer import OcrArtifactFixer
17
+ from .dialog_formatter import DialogFormatter, format_dialog
@@ -0,0 +1,255 @@
1
+ # -*- coding: UTF-8 -*-
2
+ """Dialog-aware paragraph formatter for segmented text.
3
+
4
+ Formats segmented sentences into readable paragraphs with intelligent
5
+ grouping of dialog and narrative text. Keeps multi-sentence quoted speech
6
+ together and adds paragraph breaks between different speakers.
7
+
8
+ Related GitHub Issue:
9
+ #10 - feat: Add --format flag for dialog-aware paragraph formatting
10
+ https://github.com/craigtrim/fast-sentence-segment/issues/10
11
+
12
+ Example:
13
+ >>> from fast_sentence_segment.dmo.dialog_formatter import format_dialog
14
+ >>> sentences = [
15
+ ... '"Hello," said Jack.',
16
+ ... '"How are you today?',
17
+ ... 'I hope you are well."',
18
+ ... '"I am fine," replied Mary.',
19
+ ... ]
20
+ >>> print(format_dialog(sentences))
21
+ "Hello," said Jack.
22
+
23
+ "How are you today?
24
+ I hope you are well."
25
+
26
+ "I am fine," replied Mary.
27
+ """
28
+
29
+ import re
30
+ from typing import List
31
+
32
+ from fast_sentence_segment.core import BaseObject
33
+
34
+
35
+ # Quote characters to track for dialog detection
36
+ DOUBLE_QUOTES = '""\""'
37
+ SINGLE_QUOTES = "'''"
38
+ ALL_QUOTES = DOUBLE_QUOTES + SINGLE_QUOTES
39
+
40
+
41
+ def _count_quotes(text: str) -> int:
42
+ """Count quote characters in text (both single and double)."""
43
+ return sum(1 for c in text if c in ALL_QUOTES)
44
+
45
+
46
+ def _starts_with_quote(text: str) -> bool:
47
+ """Check if text starts with a quote character."""
48
+ text = text.lstrip()
49
+ return text and text[0] in ALL_QUOTES
50
+
51
+
52
+ def _ends_with_closing_quote(text: str) -> bool:
53
+ """Check if text ends with a closing quote (possibly followed by punctuation)."""
54
+ text = text.rstrip()
55
+ if not text:
56
+ return False
57
+ # Check last few characters for closing quote pattern
58
+ # e.g., '" or "' or .' or ."
59
+ for i in range(min(3, len(text)), 0, -1):
60
+ if text[-i] in ALL_QUOTES:
61
+ return True
62
+ return False
63
+
64
+
65
+ def _is_complete_quote(text: str) -> bool:
66
+ """Check if text contains a complete (balanced) quote.
67
+
68
+ A complete quote has an even number of quote characters,
69
+ meaning all opened quotes are closed.
70
+ """
71
+ quote_count = _count_quotes(text)
72
+ return quote_count > 0 and quote_count % 2 == 0
73
+
74
+
75
+ def _sentence_is_dialog_continuation(sentence: str, in_quote: bool) -> bool:
76
+ """Determine if sentence continues an open quote.
77
+
78
+ Args:
79
+ sentence: The sentence to check.
80
+ in_quote: Whether we're currently inside an unclosed quote.
81
+
82
+ Returns:
83
+ True if this sentence is a continuation of open dialog.
84
+ """
85
+ if in_quote:
86
+ return True
87
+ return False
88
+
89
+
90
+ def _get_quote_delta(sentence: str) -> int:
91
+ """Get the net change in quote depth for a sentence.
92
+
93
+ Returns:
94
+ Positive if more quotes opened than closed,
95
+ negative if more closed than opened,
96
+ zero if balanced.
97
+ """
98
+ return _count_quotes(sentence) % 2
99
+
100
+
101
+ class DialogFormatter(BaseObject):
102
+ """Formats segmented sentences with dialog-aware paragraph grouping.
103
+
104
+ This formatter analyzes sentence structure to intelligently group
105
+ text into paragraphs:
106
+
107
+ - Multi-sentence quoted speech stays together (same speaker)
108
+ - Paragraph breaks added between different speakers
109
+ - Narrative text grouped appropriately
110
+ - Handles both single and double quote styles
111
+
112
+ Example:
113
+ >>> formatter = DialogFormatter()
114
+ >>> sentences = ['"Hello," he said.', 'The door opened.']
115
+ >>> print(formatter.process(sentences))
116
+ "Hello," he said.
117
+
118
+ The door opened.
119
+ """
120
+
121
+ def __init__(self):
122
+ """Initialize the DialogFormatter."""
123
+ BaseObject.__init__(self, __name__)
124
+
125
+ def process(self, sentences: List[str]) -> str:
126
+ """Format sentences into dialog-aware paragraphs.
127
+
128
+ Args:
129
+ sentences: List of segmented sentences.
130
+
131
+ Returns:
132
+ Formatted string with appropriate paragraph breaks.
133
+ """
134
+ return format_dialog(sentences)
135
+
136
+
137
+ def _is_narrative(sentence: str) -> bool:
138
+ """Check if a sentence is narrative (no quotes at start)."""
139
+ return not _starts_with_quote(sentence)
140
+
141
+
142
+ def _ends_dialog_turn(sentence: str) -> bool:
143
+ """Check if a sentence ends a dialog turn.
144
+
145
+ A dialog turn ends when the sentence ends with a closing quote
146
+ followed by optional punctuation or dialog tag ending.
147
+ """
148
+ sentence = sentence.rstrip()
149
+ if not sentence:
150
+ return False
151
+
152
+ # Pattern: ends with quote + optional punctuation
153
+ # e.g., ." or .' or "' or '" or ," he said. etc.
154
+ # Check if there's a closing quote near the end
155
+ last_chars = sentence[-10:] if len(sentence) >= 10 else sentence
156
+
157
+ # Count quotes in last part - if odd from end, likely closes
158
+ for i, c in enumerate(reversed(last_chars)):
159
+ if c in ALL_QUOTES:
160
+ # Found a quote - check if it's likely a closer
161
+ # A closer is typically followed by punctuation or end
162
+ remaining = last_chars[len(last_chars) - i:]
163
+ if not remaining or all(ch in '.,!?;: ' for ch in remaining):
164
+ return True
165
+ # Also handle dialog tags: ,' he said.
166
+ if remaining and remaining[0] in '.,!?' and 'said' not in sentence.lower()[-20:]:
167
+ return True
168
+ break
169
+
170
+ return False
171
+
172
+
173
+ def format_dialog(sentences: List[str]) -> str:
174
+ """Format sentences into dialog-aware paragraphs.
175
+
176
+ Groups sentences intelligently based on dialog structure:
177
+ - Sentences within an unclosed quote stay grouped
178
+ - Complete quoted sentences become their own paragraphs
179
+ - Narrative text is grouped together
180
+ - Paragraph breaks separate different speakers/turns
181
+
182
+ Args:
183
+ sentences: List of segmented sentences.
184
+
185
+ Returns:
186
+ Formatted string with paragraph breaks (double newlines)
187
+ between logical groups and single newlines within groups.
188
+
189
+ Example:
190
+ >>> sentences = [
191
+ ... '"My dear sir," cried the man.',
192
+ ... '"You had every reason to be carried away."',
193
+ ... ]
194
+ >>> print(format_dialog(sentences))
195
+ "My dear sir," cried the man.
196
+
197
+ "You had every reason to be carried away."
198
+ """
199
+ if not sentences:
200
+ return ""
201
+
202
+ paragraphs: List[List[str]] = []
203
+ current_para: List[str] = []
204
+ in_quote = False # Track if we're inside an unclosed quote
205
+
206
+ for i, sentence in enumerate(sentences):
207
+ sentence = sentence.strip()
208
+ if not sentence:
209
+ continue
210
+
211
+ quote_count = _count_quotes(sentence)
212
+ starts_quote = _starts_with_quote(sentence)
213
+ is_narrative = _is_narrative(sentence)
214
+ is_complete = _is_complete_quote(sentence)
215
+
216
+ # Get info about previous sentence
217
+ prev_sentence = current_para[-1] if current_para else ""
218
+ prev_was_narrative = _is_narrative(prev_sentence) if prev_sentence else False
219
+ prev_was_complete = _is_complete_quote(prev_sentence) if prev_sentence else False
220
+
221
+ # Determine if this sentence starts a new paragraph
222
+ should_start_new_para = False
223
+
224
+ if not current_para:
225
+ # First sentence always starts a new paragraph
226
+ should_start_new_para = True
227
+ elif in_quote:
228
+ # Inside an open quote - continue current paragraph
229
+ should_start_new_para = False
230
+ elif starts_quote:
231
+ # New quote starting - always new paragraph
232
+ should_start_new_para = True
233
+ elif is_narrative and prev_was_complete and not prev_was_narrative:
234
+ # Narrative after complete dialog - new paragraph
235
+ should_start_new_para = True
236
+ elif is_narrative and not prev_was_narrative and _ends_dialog_turn(prev_sentence):
237
+ # Narrative after dialog that ends a turn - new paragraph
238
+ should_start_new_para = True
239
+
240
+ if should_start_new_para and current_para:
241
+ paragraphs.append(current_para)
242
+ current_para = []
243
+
244
+ current_para.append(sentence)
245
+
246
+ # Update quote tracking
247
+ if quote_count % 2 == 1:
248
+ in_quote = not in_quote
249
+
250
+ # Don't forget the last paragraph
251
+ if current_para:
252
+ paragraphs.append(current_para)
253
+
254
+ # Format: join sentences in paragraph with newline, paragraphs with double newline
255
+ return "\n\n".join("\n".join(para) for para in paragraphs)
@@ -0,0 +1,70 @@
1
+ # -*- coding: UTF-8 -*-
2
+ """Fix common OCR/text extraction artifacts.
3
+
4
+ Ebook text files often contain artifacts where common word pairs
5
+ are incorrectly joined. This module fixes known patterns.
6
+
7
+ Related GitHub Issue:
8
+ #9 - Fix common OCR/cleaning artifacts (Iam, witha)
9
+ https://github.com/craigtrim/fast-sentence-segment/issues/9
10
+ """
11
+
12
+ from fast_sentence_segment.core import BaseObject
13
+
14
+ # Known OCR artifact patterns: (pattern, replacement)
15
+ # All patterns include surrounding spaces to ensure exact word boundaries
16
+ _OCR_ARTIFACTS = [
17
+ (" Iam ", " I am "),
18
+ (" Ihave ", " I have "),
19
+ (" ihave ", " I have "),
20
+ (" Ithink ", " I think "),
21
+ (" ithink ", " I think "),
22
+ (" anda ", " and a "),
23
+ (" witha ", " with a "),
24
+ (" sucha ", " such a "),
25
+ (" aliquid ", " a liquid "),
26
+ ]
27
+
28
+
29
+ class OcrArtifactFixer(BaseObject):
30
+ """Fix common OCR/text extraction artifacts.
31
+
32
+ Detects and corrects known patterns where words are incorrectly
33
+ joined during OCR or text extraction processes.
34
+
35
+ Related GitHub Issue:
36
+ #9 - Fix common OCR/cleaning artifacts (Iam, witha)
37
+ https://github.com/craigtrim/fast-sentence-segment/issues/9
38
+ """
39
+
40
+ def __init__(self):
41
+ """Change Log
42
+
43
+ Created:
44
+ 3-Feb-2026
45
+ craigtrim@gmail.com
46
+ * fix common OCR/cleaning artifacts
47
+ https://github.com/craigtrim/fast-sentence-segment/issues/9
48
+ """
49
+ BaseObject.__init__(self, __name__)
50
+
51
+ @staticmethod
52
+ def process(input_text: str) -> str:
53
+ """Fix known OCR artifact patterns.
54
+
55
+ Args:
56
+ input_text: Text that may contain OCR artifacts.
57
+
58
+ Returns:
59
+ Text with known OCR artifacts corrected.
60
+
61
+ Examples:
62
+ >>> OcrArtifactFixer.process("Jack, Iam so happy")
63
+ 'Jack, I am so happy'
64
+ >>> OcrArtifactFixer.process("horizon witha hint")
65
+ 'horizon with a hint'
66
+ """
67
+ for pattern, replacement in _OCR_ARTIFACTS:
68
+ if pattern in input_text:
69
+ input_text = input_text.replace(pattern, replacement)
70
+ return input_text
@@ -65,6 +65,54 @@ class SpacyDocSegmenter(BaseObject):
65
65
  return False
66
66
  return True
67
67
 
68
+ @staticmethod
69
+ def _merge_orphaned_quotes(sentences: list) -> list:
70
+ """Merge orphaned opening quotes with the following sentence.
71
+
72
+ spaCy sometimes splits on opening quotes, producing sentences like:
73
+ ["'", "Oh, the funeral..."]
74
+ This merges them into:
75
+ ["'Oh, the funeral..."]
76
+
77
+ Also handles trailing orphaned quotes that should belong to next sentence:
78
+ ["He said. '", "Hello!'"]
79
+ Becomes:
80
+ ["He said.", "'Hello!'"]
81
+ """
82
+ if not sentences:
83
+ return sentences
84
+
85
+ result = []
86
+ i = 0
87
+ while i < len(sentences):
88
+ sent = sentences[i]
89
+ # Check if this sentence is just an opening quote
90
+ if sent.strip() in ("'", '"', "'.", '".'):
91
+ # Merge with the next sentence if available
92
+ if i + 1 < len(sentences):
93
+ quote_char = sent.strip().rstrip('.')
94
+ result.append(quote_char + sentences[i + 1])
95
+ i += 2
96
+ continue
97
+ result.append(sent)
98
+ i += 1
99
+
100
+ # Second pass: handle trailing orphaned quotes
101
+ # Pattern: sentence ends with `. '` or `. "` - move quote to next sentence
102
+ fixed = []
103
+ for i, sent in enumerate(result):
104
+ # Check for trailing orphaned quote (`. '` or `? '` or `! '`)
105
+ if len(sent) >= 3 and sent[-2:] in (" '", ' "') and sent[-3] in '.?!':
106
+ # Strip the trailing quote
107
+ trailing_quote = sent[-1]
108
+ sent = sent[:-2]
109
+ # Prepend to next sentence if available
110
+ if i + 1 < len(result) and not result[i + 1].startswith(('"', "'")):
111
+ result[i + 1] = trailing_quote + result[i + 1]
112
+ fixed.append(sent)
113
+
114
+ return fixed
115
+
68
116
  @staticmethod
69
117
  def _cleanse(sentences: list) -> str:
70
118
  sentences = [sent for sent in sentences
@@ -103,6 +151,9 @@ class SpacyDocSegmenter(BaseObject):
103
151
  sentences = [sent for sent in sentences if
104
152
  sent and len(sent) and sent != 'None']
105
153
 
154
+ # Merge orphaned opening quotes with following sentence
155
+ sentences = self._merge_orphaned_quotes(sentences)
156
+
106
157
  sentences = [self._append_period(sent)
107
158
  for sent in sentences]
108
159
 
@@ -55,6 +55,7 @@ from fast_sentence_segment.dmo import SpacyDocSegmenter
55
55
  from fast_sentence_segment.dmo import PostProcessStructure
56
56
  from fast_sentence_segment.dmo import StripTrailingPeriodAfterQuote
57
57
  from fast_sentence_segment.dmo import Dehyphenator
58
+ from fast_sentence_segment.dmo import OcrArtifactFixer
58
59
 
59
60
 
60
61
  class PerformSentenceSegmentation(BaseObject):
@@ -84,6 +85,7 @@ class PerformSentenceSegmentation(BaseObject):
84
85
  self.__nlp = _load_spacy_model("en_core_web_sm")
85
86
 
86
87
  self._dehyphenate = Dehyphenator.process
88
+ self._fix_ocr_artifacts = OcrArtifactFixer.process
87
89
  self._newlines_to_periods = NewlinesToPeriods.process
88
90
  self._normalize_numbered_lists = NumberedListNormalizer().process
89
91
  self._normalize_ellipses = EllipsisNormalizer().process
@@ -138,6 +140,9 @@ class PerformSentenceSegmentation(BaseObject):
138
140
  # Must happen before newlines are converted to periods
139
141
  input_text = self._dehyphenate(input_text)
140
142
 
143
+ # Fix common OCR artifacts (issue #9)
144
+ input_text = self._fix_ocr_artifacts(input_text)
145
+
141
146
  input_text = self._normalize_numbered_lists(input_text)
142
147
  input_text = self._normalize_ellipses(input_text)
143
148
 
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: fast-sentence-segment
3
- Version: 1.4.3
3
+ Version: 1.4.5
4
4
  Summary: Fast and Efficient Sentence Segmentation
5
5
  Home-page: https://github.com/craigtrim/fast-sentence-segment
6
6
  License: MIT
@@ -1,32 +1,34 @@
1
- fast_sentence_segment/__init__.py,sha256=jeb4yCy89ivyqbo-4ldJLquPAG_XR_33Q7nrDjqPxvE,1465
1
+ fast_sentence_segment/__init__.py,sha256=DI7cyxtqnWd_5lrtGXqkIm8Aje0h55nGAHGgP6zXRyE,2278
2
2
  fast_sentence_segment/bp/__init__.py,sha256=j2-WfQ9WwVuXeGSjvV6XLVwEdvau8sdAQe4Pa4DrYi8,33
3
3
  fast_sentence_segment/bp/segmenter.py,sha256=UW6DguPgA56h-pPYRsfJhjIzBe40j6NdjkwYxamASyA,1928
4
- fast_sentence_segment/cli.py,sha256=vr1Gh-pq4bIPcnhUF6c7ckGdEfoyrI_r0XcrJrIfjEA,5640
4
+ fast_sentence_segment/cli.py,sha256=8AA_V3hcOVL8ENXboFDuJTimFbHKK5KbjzIeS9Cs-xA,9568
5
5
  fast_sentence_segment/core/__init__.py,sha256=uoBersYyVStJ5a8zJpQz1GDGaloEdAv2jGHw1292hRM,108
6
6
  fast_sentence_segment/core/base_object.py,sha256=AYr7yzusIwawjbKdvcv4yTEnhmx6M583kDZzhzPOmq4,635
7
7
  fast_sentence_segment/core/stopwatch.py,sha256=hE6hMz2q6rduaKi58KZmiAL-lRtyh_wWCANhl4KLkRQ,879
8
- fast_sentence_segment/dmo/__init__.py,sha256=N0lLHVn6zKeg6h1LIfoc4XeXPUY-uSbMT45dP2_vn8M,862
8
+ fast_sentence_segment/dmo/__init__.py,sha256=emn-F46GMpR5dTQXbhMWGexj7sOfWWuTpRWiENjIadQ,972
9
9
  fast_sentence_segment/dmo/abbreviation_merger.py,sha256=tCXM6yCfMryJvMIVWIxP_EocoibZi8vohFzJ5tvMYr0,4432
10
10
  fast_sentence_segment/dmo/abbreviation_splitter.py,sha256=03mSyJcLooNyIjXx6mPlrnjmKgZW-uhUIqG4U-MbIGw,2981
11
11
  fast_sentence_segment/dmo/abbreviations.py,sha256=CGJrJDo6pmYd3pTNEQbdOo8N6tnkCnwyL2X7Si663Os,2530
12
12
  fast_sentence_segment/dmo/bullet_point_cleaner.py,sha256=WOZQRWXiiyRi8rOuEIw36EmkaXmATHL9_Dxb2rderw4,1606
13
13
  fast_sentence_segment/dmo/dehyphenator.py,sha256=6BJTie7tClRAifeiW8V2CdAAbcbknhtqmKylAdRZ7ko,1776
14
+ fast_sentence_segment/dmo/dialog_formatter.py,sha256=C5r3t3vY6ZbU26g0JGIk8BRlXhMn1LGPljw_WPTuCSg,8276
14
15
  fast_sentence_segment/dmo/ellipsis_normalizer.py,sha256=lHs9dLFfKJe-2vFNe17Hik90g3_kXX347OzGP_IOT08,1521
15
16
  fast_sentence_segment/dmo/group_quoted_sentences.py,sha256=Ifh_kUwi7sMbzbZvrTgEKkzWe50AafUDhVKVPR9h7wQ,5092
16
17
  fast_sentence_segment/dmo/newlines_to_periods.py,sha256=PUrXreqZWiITINfoJL5xRRlXJH6noH0cdXtW1EqAh8I,1517
17
18
  fast_sentence_segment/dmo/normalize_quotes.py,sha256=mr53qo_tj_I9XzElOKjUQvCtDQh7mBCGy-iqsHZDX14,2881
18
19
  fast_sentence_segment/dmo/numbered_list_normalizer.py,sha256=q0sOCW8Jkn2vTXlUcVhmDvYES3yvJx1oUVl_8y7eL4E,1672
20
+ fast_sentence_segment/dmo/ocr_artifact_fixer.py,sha256=lhU6Nfp4_g5yChm1zxgwM5R5ixk3pzhrk1qEgNJa8Hc,2139
19
21
  fast_sentence_segment/dmo/post_process_sentences.py,sha256=5jxG3TmFjxIExMPLhnCB5JT1lXQvFU9r4qQGoATGrWk,916
20
22
  fast_sentence_segment/dmo/question_exclamation_splitter.py,sha256=cRsWRu8zb6wOWG-BjMahHfz4YGutKiV9lW7dE-q3tgc,2006
21
- fast_sentence_segment/dmo/spacy_doc_segmenter.py,sha256=_oTsrIL2rjysjt_8bPJVNTn230pUtL-geCC8g174iC4,3163
23
+ fast_sentence_segment/dmo/spacy_doc_segmenter.py,sha256=Kb65TYMhrbpTYEey5vb7TyhCjUHVxmugHYIeKkntCwk,5147
22
24
  fast_sentence_segment/dmo/strip_trailing_period_after_quote.py,sha256=wYkoLy5XJKZIblJXBvDAB8-a81UTQOhOf2u91wjJWUw,2259
23
25
  fast_sentence_segment/dmo/title_name_merger.py,sha256=zbG04_VjwM8TtT8LhavvmZqIZL_2xgT2OTxWkK_Zt1s,5133
24
26
  fast_sentence_segment/dmo/unwrap_hard_wrapped_text.py,sha256=V1T5RsJBaII_iGJMyWvv6rb2mny8pnVd428oVZL0n5I,2457
25
27
  fast_sentence_segment/svc/__init__.py,sha256=9B12mXxBnlalH4OAm1AMLwUMa-RLi2ilv7qhqv26q7g,144
26
28
  fast_sentence_segment/svc/perform_paragraph_segmentation.py,sha256=zLKw9rSzb0NNfx4MyEeoGrHwhxTtH5oDrYcAL2LMVHY,1378
27
- fast_sentence_segment/svc/perform_sentence_segmentation.py,sha256=mAJEPWqNQFbnlj7Rb7yiXIRHCAdlgsN0jAbg7e2qpMU,7421
28
- fast_sentence_segment-1.4.3.dist-info/LICENSE,sha256=vou5JCLAT5nHcsUv-AkjUYAihYfN9mwPDXxV2DHyHBo,1067
29
- fast_sentence_segment-1.4.3.dist-info/METADATA,sha256=5LGK9z9ip2AtOr2FgaIgkrR2mLvIQaeeuh8gVi3GBaA,7785
30
- fast_sentence_segment-1.4.3.dist-info/WHEEL,sha256=sP946D7jFCHeNz5Iq4fL4Lu-PrWrFsgfLXbbkciIZwg,88
31
- fast_sentence_segment-1.4.3.dist-info/entry_points.txt,sha256=Zc8OwFKj3ofnjy5ZIFqHzDkIEWweV1AP1xap1ZFGD8M,107
32
- fast_sentence_segment-1.4.3.dist-info/RECORD,,
29
+ fast_sentence_segment/svc/perform_sentence_segmentation.py,sha256=vpZ7lyOKxIAgHRk-rfgNI4BtAC38vU5UbYokkw8JhK8,7639
30
+ fast_sentence_segment-1.4.5.dist-info/LICENSE,sha256=vou5JCLAT5nHcsUv-AkjUYAihYfN9mwPDXxV2DHyHBo,1067
31
+ fast_sentence_segment-1.4.5.dist-info/METADATA,sha256=1xZQ63f20VnbsLC_leQ40nIXLRbSkfUwnbxZmtBGYo0,7785
32
+ fast_sentence_segment-1.4.5.dist-info/WHEEL,sha256=sP946D7jFCHeNz5Iq4fL4Lu-PrWrFsgfLXbbkciIZwg,88
33
+ fast_sentence_segment-1.4.5.dist-info/entry_points.txt,sha256=Zc8OwFKj3ofnjy5ZIFqHzDkIEWweV1AP1xap1ZFGD8M,107
34
+ fast_sentence_segment-1.4.5.dist-info/RECORD,,