-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathbritfix_core.py
More file actions
1467 lines (1221 loc) · 56.6 KB
/
Copy pathbritfix_core.py
File metadata and controls
1467 lines (1221 loc) · 56.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
Britfix core - spelling correction engine.
"""
import re
import json
import os
import sys
import uuid
from pathlib import Path
from typing import Dict, List, Tuple, Optional, Set
from collections import defaultdict
class ConfigError(Exception):
"""Raised when config.json is missing or invalid."""
pass
def _load_config() -> Dict:
"""Load and validate config.json."""
config_path = os.path.join(os.path.dirname(__file__), 'config.json')
if not os.path.exists(config_path):
raise ConfigError(f"Config file not found: {config_path}")
try:
with open(config_path, 'r') as f:
config = json.load(f)
except json.JSONDecodeError as e:
raise ConfigError(f"Invalid JSON in config file: {e}")
# Validate structure
if 'strategies' not in config:
raise ConfigError("Config missing 'strategies' key")
strategies = config['strategies']
if not isinstance(strategies, dict):
raise ConfigError("Config 'strategies' must be an object")
required_strategies = {'text', 'code'}
missing = required_strategies - set(strategies.keys())
if missing:
raise ConfigError(f"Config missing required strategies: {missing}")
for name, strategy in strategies.items():
if not isinstance(strategy, dict):
raise ConfigError(f"Strategy '{name}' must be an object")
if 'extensions' not in strategy:
raise ConfigError(f"Strategy '{name}' missing 'extensions' key")
if not isinstance(strategy['extensions'], list):
raise ConfigError(f"Strategy '{name}' extensions must be a list")
if not strategy['extensions']:
raise ConfigError(f"Strategy '{name}' has no extensions defined")
return config
# Load config at module import time - fail fast if invalid
try:
_CONFIG = _load_config()
except ConfigError as e:
print(f"Britfix config error: {e}", file=sys.stderr)
sys.exit(1)
# Private-use Unicode codepoint used to delimit phrase placeholders during the
# mask-correct-restore pass in SpellingCorrector. Picked because it is non-word
# (so dictionary regex word boundaries treat it as text junction) and is
# vanishingly unlikely to appear in real source content.
_PHRASE_MASK_DELIM = ''
_PHRASE_PLACEHOLDER_RE = re.compile(
re.escape(_PHRASE_MASK_DELIM) + r'(\d+)' + re.escape(_PHRASE_MASK_DELIM)
)
class SpellingCorrector:
"""Efficient spelling corrector with precompiled regex patterns.
``phrases`` are literal substrings (case-insensitive) that should be
preserved verbatim — any dictionary word that falls inside a phrase match
is left untouched. See ``correct_text`` for the masking pass.
"""
def __init__(self, dictionary: Dict[str, str], phrases: Optional[Set[str]] = None):
self.dictionary = {k.lower(): v for k, v in dictionary.items()}
self.pattern = self._compile_pattern()
# Sort phrases by length descending so longer phrases win when alternatives overlap.
self._phrases = sorted({p for p in (phrases or set()) if p}, key=len, reverse=True)
self._phrase_pattern = self._compile_phrase_pattern()
def _compile_pattern(self) -> Optional[re.Pattern]:
"""Compile regex pattern for all dictionary words."""
if not self.dictionary:
return None
pattern = r'\b(' + '|'.join(re.escape(word) for word in self.dictionary.keys()) + r')\b'
return re.compile(pattern, re.IGNORECASE)
def _compile_phrase_pattern(self) -> Optional[re.Pattern]:
if not self._phrases:
return None
return re.compile('|'.join(re.escape(p) for p in self._phrases), re.IGNORECASE)
def _mask_phrases(self, text: str) -> Tuple[str, List[str]]:
"""Replace phrase matches with placeholders. Returns (masked_text, originals)."""
if not self._phrase_pattern:
return text, []
originals: List[str] = []
def stash(match):
originals.append(match.group())
return f"{_PHRASE_MASK_DELIM}{len(originals) - 1}{_PHRASE_MASK_DELIM}"
masked = self._phrase_pattern.sub(stash, text)
return masked, originals
def _restore_phrases(self, text: str, originals: List[str]) -> str:
if not originals:
return text
def restore(match):
idx = int(match.group(1))
# Guard against the (vanishingly unlikely) case where user content
# already contained the delimiter pattern with a bogus index. Leave
# such matches untouched rather than IndexError-ing or rewriting
# unrelated text.
if 0 <= idx < len(originals):
return originals[idx]
return match.group(0)
return _PHRASE_PLACEHOLDER_RE.sub(restore, text)
def _phrase_spans(self, text: str) -> List[Tuple[int, int]]:
"""Return non-overlapping (start, end) spans of phrase matches in ``text``."""
if not self._phrase_pattern:
return []
return [(m.start(), m.end()) for m in self._phrase_pattern.finditer(text)]
def detect_case(self, word: str) -> str:
"""Detect the case pattern of a word."""
if word.isupper():
return 'upper'
elif word.islower():
return 'lower'
elif word.istitle():
return 'title'
else:
return 'mixed'
def apply_case(self, word: str, case_pattern: str) -> str:
"""Apply the detected case pattern to a word."""
if case_pattern == 'upper':
return word.upper()
elif case_pattern == 'lower':
return word.lower()
elif case_pattern == 'title':
return word.title()
else:
return word
def find_replacements(self, text: str) -> List[Tuple[int, int, str, str]]:
"""Find all potential replacements in text."""
if not self.pattern:
return []
phrase_spans = self._phrase_spans(text)
replacements = []
for match in self.pattern.finditer(text):
ms, me = match.start(), match.end()
# Drop any candidate that overlaps a preserved phrase span.
if any(ps < me and ms < pe for ps, pe in phrase_spans):
continue
original_word = match.group()
case_pattern = self.detect_case(original_word)
key = original_word.lower()
if key in self.dictionary:
british_spelling = self.dictionary[key]
replacement = self.apply_case(british_spelling, case_pattern)
if original_word != replacement:
replacements.append((ms, me, original_word, replacement))
return replacements
def correct_text(self, text: str, track_changes: bool = True) -> Tuple[str, Dict[str, int]]:
"""Apply spelling corrections to text.
If phrase ignores are configured, phrases are masked with placeholder
tokens before dictionary correction runs and restored afterwards.
Words that fall inside a phrase match are therefore preserved verbatim.
"""
if not self.pattern:
return text, {}
masked, originals = self._mask_phrases(text)
change_tracker = defaultdict(int) if track_changes else None
def replacement(match):
original_word = match.group()
case_pattern = self.detect_case(original_word)
key = original_word.lower()
if key in self.dictionary:
british_spelling = self.dictionary[key]
if track_changes:
change_tracker[key] += 1
return self.apply_case(british_spelling, case_pattern)
return original_word
corrected_text = self.pattern.sub(replacement, masked)
corrected_text = self._restore_phrases(corrected_text, originals)
return corrected_text, dict(change_tracker) if track_changes else {}
def load_spelling_mappings(file_path: Optional[str] = None) -> Dict[str, str]:
"""Load spelling mappings from a JSON file."""
if not file_path:
# Default to spelling-mapper.json in the same directory
script_dir = os.path.dirname(os.path.realpath(__file__))
file_path = os.path.join(script_dir, 'spelling-mapper.json')
try:
with open(file_path, 'r', encoding='utf-8') as file:
return json.load(file)
except FileNotFoundError:
return {}
except json.JSONDecodeError:
return {}
# File processing strategies for different file types
class FileProcessingStrategy:
"""Base class for file processing strategies."""
supports_interactive = True
def process(self, content: str, corrector: SpellingCorrector) -> Tuple[str, Dict[str, int]]:
"""Process content and return corrected text with change tracking."""
return corrector.correct_text(content)
def find_safe_replacements(self, content: str, corrector: SpellingCorrector) -> List[Tuple[int, int, str, str]]:
"""Find replacements filtered by this strategy's segmentation rules.
Uses positional comparison between the original and strategy-processed
text to determine which candidates the strategy considers safe.
Note: This requires that process() preserves the structure of
non-corrected regions (no reformatting, normalisation, or reordering).
Strategies that reformat content (e.g. JSONStrategy) must not use
this method.
"""
all_replacements = corrector.find_replacements(content)
if not all_replacements:
return []
corrected, _ = self.process(content, corrector)
safe = []
offset = 0
for start, end, original, replacement in all_replacements:
adj_start = start + offset
adj_end_replaced = adj_start + len(replacement)
# Character after the original span in the source content
char_after_original = content[end:end + 1]
# Check whether the replacement appears here and is followed
# by the same boundary as in the original content.
if corrected[adj_start:adj_end_replaced] == replacement:
char_after_candidate = corrected[adj_end_replaced:adj_end_replaced + 1]
if char_after_candidate == char_after_original:
safe.append((start, end, original, replacement))
offset += len(replacement) - len(original)
continue
# If the above didn't confirm an applied replacement, check if
# the original text is still present unchanged at this position.
adj_end_original = adj_start + len(original)
if corrected[adj_start:adj_end_original] == original:
# Not applied by strategy, no offset change
continue
# Unexpected/misaligned state, skip conservatively
return safe
class PlainTextStrategy(FileProcessingStrategy):
"""Process plain text files - just correct everything."""
pass
class MarkdownStrategy(FileProcessingStrategy):
"""Process markdown files, preserving code spans and code blocks."""
def _is_at_line_start(self, content: str, pos: int) -> bool:
"""Check if position is at the start of a line (after newline or at pos 0)."""
return pos == 0 or content[pos - 1] == '\n'
def _count_fence_chars(self, content: str, pos: int, char: str) -> int:
"""Count consecutive fence characters at position."""
count = 0
while pos + count < len(content) and content[pos + count] == char:
count += 1
return count
def _find_closing_fence(self, content: str, start: int, fence_char: str, fence_len: int) -> int:
"""
Find closing fence that matches the opening fence length.
Allows up to 3 spaces of indentation before the closing fence.
Returns position of the closing fence, or -1 if not found.
"""
pos = start
while pos < len(content):
# Find next newline
newline_pos = content.find('\n', pos)
if newline_pos == -1:
break
# Check the line after the newline
line_start = newline_pos + 1
if line_start >= len(content):
break
# Allow up to 3 spaces of indentation
indent = 0
while indent < 3 and line_start + indent < len(content) and content[line_start + indent] == ' ':
indent += 1
fence_start = line_start + indent
# Check if this line starts with the fence character
if fence_start < len(content) and content[fence_start] == fence_char:
closing_len = self._count_fence_chars(content, fence_start, fence_char)
# Closing fence must be at least as long as opening
if closing_len >= fence_len:
return newline_pos # Return position of newline before fence
pos = newline_pos + 1
return -1
def _line_is_blockquote(self, content: str, line_start: int) -> bool:
"""
Check if the line beginning at line_start is a blockquote line.
A blockquote line starts with > after up to 3 spaces of indentation.
4+ spaces is an indented code block, not a blockquote.
"""
indent = 0
while indent < 3 and line_start + indent < len(content) and content[line_start + indent] == ' ':
indent += 1
return line_start + indent < len(content) and content[line_start + indent] == '>'
def _find_indented_block_end(self, content: str, start: int) -> int:
"""
Find end of indented code block (4 spaces or 1 tab).
Returns position after the last line of the indented block.
"""
pos = start
while pos < len(content):
# Find end of current line
line_end = content.find('\n', pos)
if line_end == -1:
line_end = len(content)
# Check next line
next_line_start = line_end + 1 if line_end < len(content) else len(content)
if next_line_start >= len(content):
return len(content)
# Check if next line is also indented or blank
if content[next_line_start:next_line_start + 4] == ' ' or \
(next_line_start < len(content) and content[next_line_start] == '\t'):
pos = next_line_start
elif next_line_start < len(content) and content[next_line_start] == '\n':
# Blank line - could continue the block, check line after
pos = next_line_start
else:
# Not indented, end of block
return line_end + 1 if line_end < len(content) else len(content)
return len(content)
def process(self, content: str, corrector: SpellingCorrector) -> Tuple[str, Dict[str, int]]:
total_changes = defaultdict(int)
result = []
i = 0
while i < len(content):
# Check for fenced code blocks (``` or ~~~) - must be at start of line
if self._is_at_line_start(content, i) and content[i] in ('`', '~'):
fence_char = content[i]
fence_len = self._count_fence_chars(content, i, fence_char)
# Fenced code blocks require at least 3 fence characters
if fence_len >= 3:
# Find end of opening fence line (may include language specifier)
line_end = content.find('\n', i)
if line_end == -1:
# No newline, rest of content is the fence opener
result.append(content[i:])
break
# Find closing fence
close_pos = self._find_closing_fence(content, line_end + 1, fence_char, fence_len)
if close_pos == -1:
# No closing fence, treat rest as code block
result.append(content[i:])
break
# Find end of closing fence line
close_line_start = close_pos + 1
close_line_end = content.find('\n', close_line_start)
if close_line_end == -1:
close_line_end = len(content)
else:
close_line_end += 1 # Include the newline
# Preserve entire code block unchanged
result.append(content[i:close_line_end])
i = close_line_end
continue
# Check for indented code blocks (4 spaces or tab at start of line)
if self._is_at_line_start(content, i):
if content[i:i + 4] == ' ' or content[i] == '\t':
# Find end of indented block
block_end = self._find_indented_block_end(content, i)
result.append(content[i:block_end])
i = block_end
continue
# Check for blockquote lines (> after up to 3 spaces of indent)
# Preserve the entire line unchanged — quoted text should be verbatim.
if self._is_at_line_start(content, i) and self._line_is_blockquote(content, i):
line_end = content.find('\n', i)
if line_end == -1:
result.append(content[i:])
break
result.append(content[i:line_end + 1])
i = line_end + 1
continue
# Check for inline code spans (backticks)
if content[i] == '`':
# Count consecutive backticks
backtick_count = self._count_fence_chars(content, i, '`')
j = i + backtick_count
# Find matching closing backticks
close_pattern = '`' * backtick_count
close_pos = content.find(close_pattern, j)
if close_pos == -1:
# No closing backticks, just add this char and continue
result.append(content[i])
i += 1
continue
# Preserve inline code unchanged
end = close_pos + backtick_count
result.append(content[i:end])
i = end
continue
# Find next potential code delimiter
next_code = len(content)
# Look for backticks (inline code or potential fence at line start)
backtick_pos = content.find('`', i)
if backtick_pos != -1:
next_code = min(next_code, backtick_pos)
# Look for tilde (potential fence at line start)
tilde_pos = content.find('~', i)
if tilde_pos != -1:
next_code = min(next_code, tilde_pos)
# Look for potential indented code block (newline followed by 4 spaces or tab)
# or blockquote line (newline followed by optional spaces then >).
# Track the last `<` and `>` seen so we can tell whether a `>` at line
# start is actually the closing bracket of a multi-line HTML tag.
# Updating state incrementally keeps the scan O(n) over the segment.
pos = i
last_lt = -1
last_gt = -1
while pos < next_code:
newline_pos = content.find('\n', pos)
if newline_pos == -1 or newline_pos >= next_code:
break
# Fold any `<` / `>` in content[pos:newline_pos] into running state
chunk_lt = content.rfind('<', pos, newline_pos)
if chunk_lt != -1:
last_lt = chunk_lt
chunk_gt = content.rfind('>', pos, newline_pos)
if chunk_gt != -1:
last_gt = chunk_gt
# Check if next line starts with indent or is a blockquote
next_char_pos = newline_pos + 1
if next_char_pos < len(content):
if content[next_char_pos:next_char_pos + 4] == ' ' or content[next_char_pos] == '\t':
next_code = min(next_code, next_char_pos)
break
if self._line_is_blockquote(content, next_char_pos):
# Suppress blockquote detection if we're inside an
# unclosed HTML tag opened earlier in this segment.
inside_open_tag = False
if last_lt > last_gt:
nc = content[last_lt + 1:last_lt + 2]
if nc.isalpha() or nc == '/':
inside_open_tag = True
if not inside_open_tag:
next_code = min(next_code, next_char_pos)
break
pos = newline_pos + 1
# Process text up to next code delimiter, skipping HTML tags
segment = content[i:next_code]
if segment:
# Split on HTML tags so attribute values aren't corrected
# Require tag-like structure: < then letter or / to avoid matching bare < in prose
tag_pattern = r'(</?[a-zA-Z][^>]*>)'
# Split on markdown link targets `](url)` (optional title inside) so
# URLs aren't corrected. Matches `](...)` where `...` has no `)`.
# Preserves the `](url)` / `](url "title")` span; the preceding `[text`
# stays in prose so link text is still corrected.
link_target_pattern = r'(\]\([^)]*\))'
parts = re.split(tag_pattern, segment)
for idx, part in enumerate(parts):
if idx % 2 == 0: # Text outside tags
link_parts = re.split(link_target_pattern, part)
for lidx, lpart in enumerate(link_parts):
if lidx % 2 == 0: # Prose around link targets
corrected, changes = corrector.correct_text(lpart)
result.append(corrected)
for word, count in changes.items():
total_changes[word] += count
else: # Link target `](url)` — preserve unchanged
result.append(lpart)
else: # HTML tag — preserve unchanged
result.append(part)
# If we're at a delimiter that wasn't handled as a code block
# (e.g., tilde not at line start like "~7 days"), just add it and advance
if next_code == i:
result.append(content[i])
i += 1
else:
i = next_code
return ''.join(result), dict(total_changes)
class LaTeXStrategy(FileProcessingStrategy):
"""Process LaTeX files, preserving commands."""
def process(self, content: str, corrector: SpellingCorrector) -> Tuple[str, Dict[str, int]]:
# Patterns to preserve
preserve_patterns = [
r'\\[a-zA-Z]+\{[^}]*\}', # LaTeX commands with arguments
r'\\[a-zA-Z]+', # LaTeX commands without arguments
r'\$[^$]+\$', # Inline math
r'\$\$[^$]+\$\$', # Display math
]
# Split content into segments
combined_pattern = '|'.join(f'({p})' for p in preserve_patterns)
segments = re.split(combined_pattern, content)
# Process only non-LaTeX segments
corrected_segments = []
total_changes = defaultdict(int)
for i, segment in enumerate(segments):
if segment and i % 2 == 0: # Even indices are non-LaTeX text
corrected, changes = corrector.correct_text(segment)
corrected_segments.append(corrected)
for word, count in changes.items():
total_changes[word] += count
else:
corrected_segments.append(segment or '')
return ''.join(corrected_segments), dict(total_changes)
class HTMLStrategy(FileProcessingStrategy):
"""Process HTML/XML files, preserving tags and content of style/script tags."""
def process(self, content: str, corrector: SpellingCorrector) -> Tuple[str, Dict[str, int]]:
# Step 1: Extract and replace <script>...</script> and <style>...</style> blocks
# IMPORTANT: Process <script> FIRST - scripts may contain <style> in string literals
# Use UUID-based placeholders to avoid collisions with existing content
preserved_blocks = {}
def preserve_block(match):
# Generate a unique placeholder using UUID
placeholder = f'\x00{uuid.uuid4().hex}\x00'
preserved_blocks[placeholder] = match.group(0)
return placeholder
# Preserve <script>...</script> blocks FIRST (scripts may contain <style> strings)
script_pattern = r'<script\b[^>]*>.*?</script>'
content = re.sub(script_pattern, preserve_block, content, flags=re.IGNORECASE | re.DOTALL)
# Then preserve <style>...</style> blocks
style_pattern = r'<style\b[^>]*>.*?</style>'
content = re.sub(style_pattern, preserve_block, content, flags=re.IGNORECASE | re.DOTALL)
# Step 2: Process remaining HTML with existing tag-skipping logic
tag_pattern = r'<[^>]+>'
segments = re.split(f'({tag_pattern})', content)
corrected_segments = []
total_changes = defaultdict(int)
for i, segment in enumerate(segments):
if i % 2 == 0: # Even indices are text content
corrected, changes = corrector.correct_text(segment)
corrected_segments.append(corrected)
for word, count in changes.items():
total_changes[word] += count
else: # Odd indices are tags
corrected_segments.append(segment)
result = ''.join(corrected_segments)
# Step 3: Restore preserved blocks
for placeholder, block in preserved_blocks.items():
result = result.replace(placeholder, block)
return result, dict(total_changes)
class CssStrategy(FileProcessingStrategy):
"""
Process CSS files - only convert text in comments.
CSS properties like 'color', 'center', etc. must NOT be converted.
Only text inside /* ... */ block comments and // line comments (SCSS/LESS) is converted.
"""
def _is_line_comment(self, content: str, pos: int) -> bool:
"""
Check if // at position is a SCSS/LESS line comment vs a URL.
Returns True if this is a real comment, False if it's part of a URL.
A // is a comment if preceded by:
- Start of line (with optional whitespace)
- Whitespace, {, }, ;
It's NOT a comment if:
- Preceded by : (URL protocol like http://)
- Inside url(...) function
"""
if pos == 0:
return True
# Look backwards to find context
j = pos - 1
# Skip whitespace
while j >= 0 and content[j] in ' \t':
j -= 1
if j < 0:
return True # Start of content
prev_char = content[j]
# After newline = start of line = comment
if prev_char == '\n':
return True
# After these chars, // is a comment
if prev_char in '{};':
return True
# After : it's likely a URL (http://, https://, etc.)
if prev_char == ':':
return False
# Check if we're inside url(...) - look for 'url(' before this position
# Find the most recent '(' and check if preceded by 'url'
paren_pos = content.rfind('(', 0, pos)
if paren_pos != -1:
# Check if there's a closing ')' between paren and current position
close_paren = content.find(')', paren_pos, pos)
if close_paren == -1:
# We're inside parentheses, check if it's url(
before_paren = content[:paren_pos].rstrip()
if before_paren.lower().endswith('url'):
return False # Inside url() function
# Default: treat as comment (SCSS/LESS style)
return True
def process(self, content: str, corrector: SpellingCorrector) -> Tuple[str, Dict[str, int]]:
total_changes = defaultdict(int)
result = []
i = 0
while i < len(content):
# Check for block comments /* ... */
if content[i:i+2] == '/*':
end = content.find('*/', i + 2)
if end == -1:
end = len(content)
else:
end += 2
comment = content[i:end]
corrected, changes = self._process_comment(comment, corrector)
result.append(corrected)
for word, count in changes.items():
total_changes[word] += count
i = end
continue
# Check for line comments // (SCSS/LESS only - must verify it's not a URL)
if content[i:i+2] == '//' and self._is_line_comment(content, i):
end = content.find('\n', i)
if end == -1:
end = len(content)
comment = content[i:end]
corrected, changes = self._process_comment(comment, corrector)
result.append(corrected)
for word, count in changes.items():
total_changes[word] += count
i = end
continue
# Check for strings - skip them entirely (preserve content properties, etc.)
if content[i] in ('"', "'"):
quote = content[i]
j = i + 1
while j < len(content):
if content[j] == '\\':
j += 2
continue
if content[j] == quote:
j += 1
break
j += 1
result.append(content[i:j])
i = j
continue
# Everything else (properties, values, selectors) - keep unchanged
result.append(content[i])
i += 1
return ''.join(result), dict(total_changes)
def _process_comment(self, comment: str, corrector: SpellingCorrector) -> Tuple[str, Dict[str, int]]:
"""
Process a CSS comment, converting only unquoted prose.
Reuses the pattern from CodeStrategy._convert_unquoted_text.
"""
total_changes = defaultdict(int)
result = []
i = 0
while i < len(comment):
# Check for quoted text - preserve it
if comment[i] in ('"', "'"):
quote = comment[i]
j = i + 1
while j < len(comment) and comment[j] != quote:
if comment[j] == '\\':
j += 2
continue
j += 1
if j < len(comment):
j += 1
result.append(comment[i:j])
i = j
continue
# Check for backtick code spans - preserve them
if comment[i] == '`':
j = i + 1
while j < len(comment) and comment[j] != '`':
j += 1
if j < len(comment):
j += 1
result.append(comment[i:j])
i = j
continue
# Find the next quote or end
next_quote = len(comment)
for q in ('"', "'", '`'):
pos = comment.find(q, i)
if pos != -1 and pos < next_quote:
next_quote = pos
# Process unquoted segment
segment = comment[i:next_quote]
if segment:
corrected, changes = corrector.correct_text(segment)
result.append(corrected)
for word, count in changes.items():
total_changes[word] += count
i = next_quote
return ''.join(result), dict(total_changes)
class JSONStrategy(FileProcessingStrategy):
"""Process JSON files, only correcting string values."""
supports_interactive = False
def process(self, content: str, corrector: SpellingCorrector) -> Tuple[str, Dict[str, int]]:
try:
data = json.loads(content)
total_changes = defaultdict(int)
# Root may itself be a string (valid JSON like `"hello world"`).
# _process_json_value walks dicts/lists and rewrites strings in
# place, so a string root would otherwise be missed.
if isinstance(data, str):
if any(c.isspace() for c in data):
corrected, changes = corrector.correct_text(data)
data = corrected
for word, count in changes.items():
total_changes[word] += count
else:
self._process_json_value(data, corrector, total_changes)
return json.dumps(data, indent=2, ensure_ascii=False), dict(total_changes)
except json.JSONDecodeError as e:
print(
f"britfix: skipping malformed JSON ({e.msg} at line {e.lineno}, column {e.colno})",
file=sys.stderr,
)
return content, {}
def _process_json_value(self, value, corrector: SpellingCorrector, change_tracker: defaultdict):
"""Recursively process JSON values.
Only string values containing whitespace are corrected. Single-token
strings are treated as identifiers (config values, CSS keywords, paths,
camelCase / snake_case names) and skipped. This avoids silently
rewriting programmatic values like "center" or "colorScheme".
"""
if isinstance(value, dict):
for k, v in value.items():
if isinstance(v, str):
if any(c.isspace() for c in v):
corrected, changes = corrector.correct_text(v)
value[k] = corrected
for word, count in changes.items():
change_tracker[word] += count
else:
self._process_json_value(v, corrector, change_tracker)
elif isinstance(value, list):
for i, item in enumerate(value):
if isinstance(item, str):
if any(c.isspace() for c in item):
corrected, changes = corrector.correct_text(item)
value[i] = corrected
for word, count in changes.items():
change_tracker[word] += count
else:
self._process_json_value(item, corrector, change_tracker)
def _is_hash_non_comment_construct(content: str, i: int) -> bool:
"""Returns True for ``#``-prefixed tokens that are NOT line comments:
Rust outer/inner attributes (``#[...]``, ``#![...]``) when they are
the first non-whitespace token on a line, and file-leading shebangs
(``#!...`` at offset 0). Localised here so future per-language comment
handling can replace this with a syntax table.
The line-start restriction matters: an inline Python/Ruby/shell comment
like ``x = 1 #[TODO fix the behavior]`` is still a real comment and
must keep being processed. Indented Rust attributes (e.g. inside a
struct body) start their own line and so are still recognised.
Note: Rust raw strings (``r#"..."#``) are not handled here and remain a
known edge case for a future ``RustStrategy``.
"""
if content[i:i+2] == '#[' or content[i:i+3] == '#![':
# Walk back over any leading whitespace on the current line.
j = i - 1
while j >= 0 and content[j] in (' ', '\t'):
j -= 1
# Line-start = either start of file, or the previous non-space
# char is a newline.
return j < 0 or content[j] == '\n'
if i == 0 and content[i:i+2] == '#!':
return True
return False
class CodeStrategy(FileProcessingStrategy):
"""
Process code files - only convert prose in comments and docstrings.
NEVER converts:
- String literals (API keys, config values, etc.)
- Text inside quotes within comments (API references)
- Variable names, function names, etc.
DOES convert:
- Unquoted prose in comments (# The behavior is good)
- Unquoted prose in docstrings
"""
def process(self, content: str, corrector: SpellingCorrector) -> Tuple[str, Dict[str, int]]:
total_changes = defaultdict(int)
result = []
# Process the content, identifying comments and docstrings
i = 0
while i < len(content):
# Check for triple-quoted strings
if content[i:i+3] in ('"""', "'''"):
quote = content[i:i+3]
end = content.find(quote, i + 3)
if end == -1:
end = len(content)
else:
end += 3
# Check if this is a string literal (preceded by = or prefix like r/f/b)
# vs a docstring (at start of line after def/class or at module level)
preceding = ''.join(result).rstrip()
is_string_literal = (
preceding.endswith('=') or
preceding.endswith('r') or preceding.endswith('f') or
preceding.endswith('b') or preceding.endswith('rf') or
preceding.endswith('fr') or preceding.endswith('br') or
preceding.endswith('rb')
)
if is_string_literal:
# String literal - don't convert
result.append(content[i:end])
else:
# Docstring - convert prose
docstring = content[i:end]
corrected, changes = self._process_docstring(docstring, corrector)
result.append(corrected)
for word, count in changes.items():
total_changes[word] += count
i = end
continue
# Check for block comments /* ... */ or /** ... */
if content[i:i+2] == '/*':
end = content.find('*/', i + 2)
if end == -1:
end = len(content)
else:
end += 2
comment = content[i:end]
corrected, changes = self._process_comment(comment, corrector)
result.append(corrected)
for word, count in changes.items():
total_changes[word] += count
i = end
continue
# Check for line comments (# or //). `#` is excluded for Rust
# attribute syntax and file-leading shebangs (see helper above).
if (content[i] == '#' and not _is_hash_non_comment_construct(content, i)) \
or content[i:i+2] == '//':
# Find end of line
end = content.find('\n', i)
if end == -1:
end = len(content)
comment = content[i:end]
corrected, changes = self._process_comment(comment, corrector)
result.append(corrected)
for word, count in changes.items():
total_changes[word] += count
i = end
continue
# Check for string literals - skip them entirely
if content[i] in ('"', "'"):
quote = content[i]
# Handle escaped quotes
j = i + 1
while j < len(content):
if content[j] == '\\':
j += 2 # Skip escaped char
continue
if content[j] == quote:
j += 1
break
j += 1
result.append(content[i:j]) # Keep string unchanged
i = j
continue
# Regular code - keep unchanged