-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathWordCounter.py
More file actions
1844 lines (1585 loc) · 72 KB
/
WordCounter.py
File metadata and controls
1844 lines (1585 loc) · 72 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
"""
Batch word counter with GUI for translators (FineCount-inspired).
Counts: .docx, .pptx, .xlsx, optional .pdf
With optional Apache Tika: 50+ additional formats (.doc, .odt, .html, .epub, .rtf, etc.)
Install:
pip install python-docx python-pptx openpyxl
Optional PDF:
pip install pdfminer.six
Optional Tika (50+ extra formats, requires Java):
pip install tika
"""
from __future__ import annotations
import os
import sys
import re
import json
import threading
import queue
import csv
from datetime import datetime
from dataclasses import dataclass
from typing import List, Optional, Tuple, Dict
# --- Bundled JRE + Tika JAR detection (for PyInstaller frozen builds) ---
def _setup_bundled_tika():
"""Configure tika-python to use the JRE and Tika JAR bundled with the EXE."""
if not getattr(sys, 'frozen', False):
return
# _MEIPASS points to _internal/ in onedir mode
bundle_dir = sys._MEIPASS
java_exe = os.path.join(bundle_dir, 'jre', 'bin', 'java.exe')
tika_jar = os.path.join(bundle_dir, 'tika', 'tika-server-standard-3.1.0.jar')
if os.path.isfile(java_exe):
os.environ['TIKA_JAVA'] = java_exe
if os.path.isfile(tika_jar):
os.environ['TIKA_SERVER_JAR'] = 'file:///' + tika_jar.replace('\\', '/')
_setup_bundled_tika()
import tkinter as tk
from tkinter import ttk, filedialog, messagebox
# --- Optional imports ---
DOCX_OK = PPTX_OK = XLSX_OK = PDF_OK = False
try:
from docx import Document
DOCX_OK = True
except Exception:
DOCX_OK = False
try:
from pptx import Presentation
try:
from pptx.enum.shapes import PP_PLACEHOLDER_TYPE
PPTX_PLACEHOLDER_TYPES = PP_PLACEHOLDER_TYPE
except Exception:
PPTX_PLACEHOLDER_TYPES = None
PPTX_OK = True
except Exception:
PPTX_OK = False
try:
import openpyxl
XLSX_OK = True
except Exception:
XLSX_OK = False
try:
from pdfminer.high_level import extract_text as pdf_extract_text
PDF_OK = True
except Exception:
PDF_OK = False
TIKA_OK = False
try:
import logging as _logging
_logging.getLogger("tika").setLevel(_logging.WARNING)
from tika import parser as tika_parser
TIKA_OK = True
except Exception:
TIKA_OK = False
APP_NAME = "WordCounter"
APP_AUTHOR = "Michael Beijer"
APP_VERSION = "0.6.0"
# ---------------- Tokenisation/stat helpers ----------------
WORD_RE = re.compile(r"[A-Za-zÀ-ÖØ-öø-ÿ0-9]+(?:['’][A-Za-zÀ-ÖØ-öø-ÿ0-9]+)?")
NUM_RE = re.compile(r"\b\d+(?:[.,]\d+)?\b")
def safe_join_text(parts: List[str]) -> str:
return "\n".join(p for p in parts if p and p.strip())
def count_words(text: str) -> int:
return len(WORD_RE.findall(text or ""))
def count_chars_with_spaces(text: str) -> int:
return len(text or "")
def count_chars_no_spaces(text: str) -> int:
return len(re.sub(r"\s+", "", text or ""))
def count_numbers(text: str) -> int:
return len(NUM_RE.findall(text or ""))
def count_sentences(text: str) -> int:
# Simple heuristic: count sentence end punctuation.
t = (text or "").strip()
if not t:
return 0
# Split on . ! ? followed by whitespace/end; avoid counting ellipses heavily.
parts = re.split(r"(?<=[.!?])\s+", t)
return sum(1 for p in parts if p.strip())
def count_paragraphs(text: str) -> int:
# paragraphs separated by blank lines
t = (text or "").strip()
if not t:
return 0
blocks = re.split(r"\n\s*\n+", t)
return sum(1 for b in blocks if b.strip())
# ---------------- Segment helpers (for repetition analysis) ----------------
SENTENCE_SPLIT_RE = re.compile(r'(?<=[.!?])\s+')
def normalize_segment(seg: str) -> str:
"""Normalize a segment for repetition comparison: collapse whitespace, strip."""
return re.sub(r'\s+', ' ', seg.strip())
def text_to_sentences(text: str) -> List[str]:
"""Split text into sentence segments for repetition analysis (non-translation formats)."""
if not text or not text.strip():
return []
sentences = SENTENCE_SPLIT_RE.split(text.strip())
return [s.strip() for s in sentences if s.strip()]
# ---------------- Settings ----------------
@dataclass
class Settings:
include_subfolders: bool = True
# DOCX
docx_include_body: bool = True
docx_include_tables: bool = True
docx_include_headers: bool = False
docx_include_footers: bool = False
# PPTX
pptx_include_slide_text: bool = True
pptx_include_footer_placeholders: bool = False
pptx_include_speaker_notes: bool = False
# XLSX
xlsx_include_text: bool = True
xlsx_include_numbers: bool = False
xlsx_include_comments: bool = False
xlsx_include_hidden_sheets: bool = False
# PDF
pdf_include: bool = True
pdf_remove_repeating_headers_footers: bool = True
# Translation files (SDLXLIFF, XLIFF, TMX, PO)
xliff_count_target: bool = False # False = count source, True = count target
# Pages estimate
words_per_page: int = 330 # common translation estimate; adjustable
# ---------------- DOCX ----------------
def _docx_collect(container, include_tables: bool) -> List[str]:
parts: List[str] = []
for p in getattr(container, "paragraphs", []):
t = getattr(p, "text", "")
if t and t.strip():
parts.append(t)
if include_tables:
for table in getattr(container, "tables", []):
for row in table.rows:
for cell in row.cells:
ct = getattr(cell, "text", "")
if ct and ct.strip():
parts.append(ct)
return parts
def docx_text(path: str, s: Settings) -> str:
doc = Document(path)
parts: List[str] = []
if s.docx_include_body:
parts.extend(_docx_collect(doc, include_tables=s.docx_include_tables))
if s.docx_include_headers or s.docx_include_footers:
for sec in doc.sections:
if s.docx_include_headers:
parts.extend(_docx_collect(sec.header, include_tables=s.docx_include_tables))
if s.docx_include_footers:
parts.extend(_docx_collect(sec.footer, include_tables=s.docx_include_tables))
return safe_join_text(parts)
def extract_docx(path: str, s: Settings) -> ExtractionResult:
if not DOCX_OK:
return ExtractionResult("", "python-docx not installed")
try:
return ExtractionResult(docx_text(path, s), None)
except Exception as e:
return ExtractionResult("", f"DOCX error: {e}")
# ---------------- PPTX ----------------
def is_footer_placeholder(shape) -> bool:
try:
if not shape.is_placeholder:
return False
except Exception:
return False
try:
pht = shape.placeholder_format.type
if PPTX_PLACEHOLDER_TYPES is not None:
footer_types = {
PPTX_PLACEHOLDER_TYPES.DATE_AND_TIME,
PPTX_PLACEHOLDER_TYPES.FOOTER,
PPTX_PLACEHOLDER_TYPES.SLIDE_NUMBER,
}
return pht in footer_types
name = str(pht).upper()
return any(k in name for k in ["DATE", "FOOTER", "SLIDE_NUMBER"])
except Exception:
return False
def pptx_text(path: str, s: Settings) -> str:
prs = Presentation(path)
parts: List[str] = []
for slide in prs.slides:
if s.pptx_include_slide_text:
for shape in slide.shapes:
if (not s.pptx_include_footer_placeholders) and is_footer_placeholder(shape):
continue
try:
if getattr(shape, "has_text_frame", False) and shape.has_text_frame:
t = shape.text
if t and t.strip():
parts.append(t)
except Exception:
continue
if s.pptx_include_speaker_notes:
try:
ns = slide.notes_slide
if ns and ns.notes_text_frame:
nt = ns.notes_text_frame.text
if nt and nt.strip():
parts.append(nt)
except Exception:
pass
return safe_join_text(parts)
def extract_pptx(path: str, s: Settings) -> ExtractionResult:
if not PPTX_OK:
return ExtractionResult("", "python-pptx not installed")
try:
return ExtractionResult(pptx_text(path, s), None)
except Exception as e:
return ExtractionResult("", f"PPTX error: {e}")
# ---------------- XLSX ----------------
def xlsx_text(path: str, s: Settings) -> str:
wb = openpyxl.load_workbook(path, data_only=True, read_only=True)
parts: List[str] = []
for ws in wb.worksheets:
if (not s.xlsx_include_hidden_sheets) and getattr(ws, "sheet_state", "visible") != "visible":
continue
for row in ws.iter_rows(values_only=False):
for cell in row:
v = cell.value
if s.xlsx_include_text and isinstance(v, str) and v.strip():
parts.append(v)
if s.xlsx_include_numbers and isinstance(v, (int, float)):
parts.append(str(v))
if s.xlsx_include_comments:
try:
cmt = cell.comment
if cmt and cmt.text and cmt.text.strip():
parts.append(cmt.text)
except Exception:
pass
return safe_join_text(parts)
def extract_xlsx(path: str, s: Settings) -> ExtractionResult:
if not XLSX_OK:
return ExtractionResult("", "openpyxl not installed")
try:
return ExtractionResult(xlsx_text(path, s), None)
except Exception as e:
return ExtractionResult("", f"XLSX error: {e}")
# ---------------- PDF ----------------
def _remove_repeating_lines(text: str) -> str:
pages = text.split("\f")
if len(pages) <= 1:
return text
line_freq: Dict[str, int] = {}
page_norm_lines: List[List[str]] = []
for p in pages:
lines = [ln.strip() for ln in p.splitlines() if ln.strip()]
norm = [re.sub(r"\d+", "#", ln) for ln in lines]
page_norm_lines.append(norm)
for ln in set(norm):
line_freq[ln] = line_freq.get(ln, 0) + 1
threshold = max(2, int(0.6 * len(pages)))
repeating = {ln for ln, n in line_freq.items() if n >= threshold}
cleaned_pages: List[str] = []
for original_page in pages:
cleaned_lines: List[str] = []
for ln in original_page.splitlines():
stripped = ln.strip()
if not stripped:
continue
norm = re.sub(r"\d+", "#", stripped)
if norm in repeating:
continue
cleaned_lines.append(stripped)
cleaned_pages.append("\n".join(cleaned_lines))
return "\n".join(cleaned_pages)
def extract_pdf(path: str, s: Settings) -> ExtractionResult:
if not s.pdf_include:
return ExtractionResult("", "PDF disabled")
if not PDF_OK:
return ExtractionResult("", "pdfminer.six not installed (PDF skipped)")
try:
text = pdf_extract_text(path) or ""
if s.pdf_remove_repeating_headers_footers:
text = _remove_repeating_lines(text)
return ExtractionResult(text, None)
except Exception as e:
return ExtractionResult("", f"PDF error: {e}")
# ---------------- Translation formats (dedicated parsers) ----------------
import xml.etree.ElementTree as ET
# XLIFF inline tag names that are placeholders (no translatable text inside)
_XLIFF_SKIP_TAGS = {"bpt", "ept", "ph", "it", "x"}
def _local_tag(elem) -> str:
"""Return the local tag name (without namespace)."""
tag = elem.tag
if tag.startswith("{"):
return tag[tag.index("}") + 1:]
return tag
def _xml_itertext(elem) -> str:
"""Recursively extract translatable text, skipping XLIFF placeholder tags."""
parts = []
if elem.text:
parts.append(elem.text)
for child in elem:
ltag = _local_tag(child)
if ltag in _XLIFF_SKIP_TAGS:
# Skip the tag content but keep the tail (text after the tag)
if child.tail:
parts.append(child.tail)
else:
# <g>, <mrk>, <sub>, etc. — recurse to get text inside
parts.append(_xml_itertext(child))
if child.tail:
parts.append(child.tail)
return "".join(parts)
def _detect_xliff_ns(root) -> str:
"""Detect the XLIFF namespace from the root element."""
tag = root.tag
if tag.startswith("{"):
return tag[1:tag.index("}")]
return ""
def _xliff_iter(root, ns: str, tag_name: str):
"""Iterate over elements with the given tag name, namespace-aware."""
if ns:
return root.iter(f"{{{ns}}}{tag_name}")
return root.iter(tag_name)
def _xliff_findall(elem, ns: str, tag_name: str):
"""Find all children with the given tag name, namespace-aware."""
if ns:
return elem.findall(f"{{{ns}}}{tag_name}")
return elem.findall(tag_name)
def _extract_mrk_segments(elem, ns: str) -> List[str]:
"""Extract text from <mrk mtype='seg'> children, or fallback to full element text."""
mrks = _xliff_findall(elem, ns, "mrk")
segments = []
if mrks:
for mrk in mrks:
if mrk.get("mtype") == "seg":
text = _xml_itertext(mrk).strip()
if text:
segments.append(text)
else:
text = _xml_itertext(elem).strip()
if text:
segments.append(text)
return segments
def extract_sdlxliff(path: str, count_target: bool = False) -> ExtractionResult:
"""Extract source or target segments from SDL Trados .sdlxliff files."""
try:
tree = ET.parse(path)
root = tree.getroot()
ns = _detect_xliff_ns(root)
# Detect languages from <file> element
file_elem = next(_xliff_iter(root, ns, "file"), None)
src_lang = file_elem.get("source-language", "?") if file_elem is not None else "?"
tgt_lang = file_elem.get("target-language", "?") if file_elem is not None else "?"
counting = "target" if count_target else "source"
lang_label = tgt_lang if count_target else src_lang
segments = []
if count_target:
# Extract from <target> elements within <trans-unit>
for tu in _xliff_iter(root, ns, "trans-unit"):
target = tu.find(f"{{{ns}}}target" if ns else "target")
if target is not None:
segments.extend(_extract_mrk_segments(target, ns))
else:
# Extract from <seg-source> (preferred) or <source>
for seg_src in _xliff_iter(root, ns, "seg-source"):
segments.extend(_extract_mrk_segments(seg_src, ns))
if not segments:
for src in _xliff_iter(root, ns, "source"):
segments.extend(_extract_mrk_segments(src, ns))
if not segments:
return ExtractionResult("", f"No {counting} segments found in SDLXLIFF")
note = f"SDLXLIFF {counting} [{lang_label}]"
return ExtractionResult("\n".join(segments), note, segments)
except Exception as e:
return ExtractionResult("", f"SDLXLIFF error: {e}")
def extract_xliff(path: str, count_target: bool = False) -> ExtractionResult:
"""Extract source or target segments from XLIFF (.xliff, .xlf, .mqxliff) files."""
try:
tree = ET.parse(path)
root = tree.getroot()
ns = _detect_xliff_ns(root)
counting = "target" if count_target else "source"
# Detect languages
file_elem = next(_xliff_iter(root, ns, "file"), None)
src_lang = file_elem.get("source-language", "?") if file_elem is not None else "?"
tgt_lang = file_elem.get("target-language", "?") if file_elem is not None else "?"
lang_label = tgt_lang if count_target else src_lang
segments = []
if count_target:
for tu in _xliff_iter(root, ns, "trans-unit"):
target = tu.find(f"{{{ns}}}target" if ns else "target")
if target is not None:
segments.extend(_extract_mrk_segments(target, ns))
else:
# Try <seg-source> first, fall back to <source>
for seg_src in _xliff_iter(root, ns, "seg-source"):
segments.extend(_extract_mrk_segments(seg_src, ns))
if not segments:
for src in _xliff_iter(root, ns, "source"):
segments.extend(_extract_mrk_segments(src, ns))
if not segments:
return ExtractionResult("", f"No {counting} segments found in XLIFF")
note = f"XLIFF {counting} [{lang_label}]"
return ExtractionResult("\n".join(segments), note, segments)
except Exception as e:
return ExtractionResult("", f"XLIFF error: {e}")
def extract_tmx(path: str) -> ExtractionResult:
"""Extract source segments from TMX files (first language variant per TU)."""
try:
tree = ET.parse(path)
root = tree.getroot()
# Detect source language from header
header = root.find(".//header")
srclang = header.get("srclang", "") if header is not None else ""
segments = []
for tu in root.iter("tu"):
tuvs = tu.findall("tuv")
source_tuv = None
if srclang:
# Find TUV matching source language
for tuv in tuvs:
lang = tuv.get("{http://www.w3.org/XML/1998/namespace}lang", "") or tuv.get("lang", "")
if lang.lower().startswith(srclang.lower()):
source_tuv = tuv
break
if source_tuv is None and tuvs:
source_tuv = tuvs[0] # First TUV = source
if source_tuv is not None:
seg = source_tuv.find("seg")
if seg is not None:
text = _xml_itertext(seg).strip()
if text:
segments.append(text)
if not segments:
return ExtractionResult("", "No source segments found in TMX")
return ExtractionResult("\n".join(segments), None, segments)
except Exception as e:
return ExtractionResult("", f"TMX error: {e}")
def extract_po(path: str) -> ExtractionResult:
"""Extract source strings (msgid) from PO/POT files."""
try:
with open(path, "r", encoding="utf-8", errors="replace") as f:
content = f.read()
segments = []
# Match msgid entries (possibly multi-line)
in_msgid = False
current = []
for line in content.splitlines():
stripped = line.strip()
if stripped.startswith("msgid "):
in_msgid = True
# Extract the string after msgid
val = stripped[6:].strip().strip('"')
if val:
current.append(val)
elif in_msgid and stripped.startswith('"') and stripped.endswith('"'):
current.append(stripped[1:-1])
else:
if in_msgid and current:
text = "".join(current)
if text: # Skip empty msgid ""
segments.append(text)
current = []
in_msgid = False
# Flush last
if in_msgid and current:
text = "".join(current)
if text:
segments.append(text)
if not segments:
return ExtractionResult("", "No source strings found in PO file")
return ExtractionResult("\n".join(segments), None, segments)
except Exception as e:
return ExtractionResult("", f"PO error: {e}")
# Translation format extensions handled by dedicated parsers
TRANSLATION_EXTS = {".sdlxliff", ".xliff", ".xlf", ".mqxliff", ".tmx", ".po", ".pot"}
# ---------------- Tika (universal fallback) ----------------
TIKA_EXTS = {
# Legacy Microsoft Office
".doc", ".xls", ".ppt",
# Rich Text Format
".rtf",
# OpenDocument
".odt", ".odp", ".ods", ".odg",
# Web / markup
".html", ".htm", ".xhtml", ".xml",
# Plain text
".txt", ".csv", ".tsv",
# Markup text
".md", ".rst", ".tex", ".latex",
# E-books
".epub",
# Email
".eml", ".msg",
# Translation / localisation
".xliff", ".xlf", ".tmx", ".sdlxliff", ".mqxliff",
".po", ".pot", ".tbx",
# Subtitles
".srt", ".vtt", ".ass", ".sub",
# Desktop publishing
".idml",
# Visio
".vsdx",
# Images (OCR — requires Tesseract on the system)
".png", ".jpg", ".jpeg", ".tiff", ".tif", ".bmp", ".gif",
# Data formats
".json", ".yaml", ".yml",
# Localisation / config
".properties", ".strings", ".resx",
}
def extract_tika(path: str) -> ExtractionResult:
if not TIKA_OK:
return ExtractionResult("", "Apache Tika not installed")
try:
parsed = tika_parser.from_file(path)
text = parsed.get("content") or ""
return ExtractionResult(text.strip(), None)
except Exception as e:
return ExtractionResult("", f"Tika error: {e}")
# ---------------- Batch + metrics ----------------
CORE_EXTS = {".docx", ".pptx", ".xlsx", ".pdf"} | TRANSLATION_EXTS
def get_supported_exts(include_pdfs: bool = True) -> set:
exts = set(CORE_EXTS)
if not include_pdfs:
exts.discard(".pdf")
if TIKA_OK:
exts |= TIKA_EXTS
return exts
@dataclass
class ExtractionResult:
text: str
note: Optional[str]
segments: Optional[List[str]] = None # individual segments for repetition analysis
@dataclass
class FileMetrics:
filepath: str
words: int
chars: int
chars_nospace: int
numbers: int
sentences: int
paragraphs: int
pages_est: float
note: str = ""
text: str = ""
segments: Optional[List[str]] = None # segments from extraction
@dataclass
class RepetitionInfo:
"""Per-file repetition breakdown."""
total_segments: int
unique_segments: int
repeated_segments: int
unique_words: int
repeated_words: int
unique_chars: int
repeated_chars: int
@dataclass
class BatchRepetitionResult:
"""Corpus-level repetition analysis results."""
per_file: Dict[str, RepetitionInfo]
corpus_unique_segments: int
corpus_total_segments: int
corpus_repeated_segments: int
corpus_unique_words: int
corpus_repeated_words: int
corpus_unique_chars: int
corpus_repeated_chars: int
def compute_metrics(text: str, s: Settings) -> Tuple[int, int, int, int, int, int, float]:
w = count_words(text)
c = count_chars_with_spaces(text)
cns = count_chars_no_spaces(text)
n = count_numbers(text)
sent = count_sentences(text)
para = count_paragraphs(text)
pages = (w / s.words_per_page) if s.words_per_page > 0 else 0.0
return w, c, cns, n, sent, para, pages
def analyze_repetitions(results: List[FileMetrics]) -> BatchRepetitionResult:
"""Analyze cross-document segment repetitions across all files in a batch.
First occurrence of each segment = unique, subsequent = repetition.
File processing order determines which file 'owns' unique segments.
"""
seen: Dict[str, bool] = {} # normalized_segment -> True (just presence)
per_file: Dict[str, RepetitionInfo] = {}
corpus_unique_words = 0
corpus_repeated_words = 0
corpus_unique_chars = 0
corpus_repeated_chars = 0
corpus_total_segments = 0
corpus_repeated_segments = 0
for fm in results:
# Use stored segments for translation formats, sentence-split for others
segments = fm.segments if fm.segments is not None else text_to_sentences(fm.text)
file_unique_segs = 0
file_repeated_segs = 0
file_unique_words = 0
file_repeated_words = 0
file_unique_chars = 0
file_repeated_chars = 0
for seg in segments:
norm = normalize_segment(seg)
if not norm:
continue
seg_words = count_words(seg)
seg_chars = count_chars_with_spaces(seg)
corpus_total_segments += 1
if norm in seen:
file_repeated_segs += 1
file_repeated_words += seg_words
file_repeated_chars += seg_chars
corpus_repeated_segments += 1
corpus_repeated_words += seg_words
corpus_repeated_chars += seg_chars
else:
file_unique_segs += 1
file_unique_words += seg_words
file_unique_chars += seg_chars
corpus_unique_words += seg_words
corpus_unique_chars += seg_chars
seen[norm] = True
per_file[fm.filepath] = RepetitionInfo(
total_segments=file_unique_segs + file_repeated_segs,
unique_segments=file_unique_segs,
repeated_segments=file_repeated_segs,
unique_words=file_unique_words,
repeated_words=file_repeated_words,
unique_chars=file_unique_chars,
repeated_chars=file_repeated_chars,
)
return BatchRepetitionResult(
per_file=per_file,
corpus_unique_segments=len(seen),
corpus_total_segments=corpus_total_segments,
corpus_repeated_segments=corpus_repeated_segments,
corpus_unique_words=corpus_unique_words,
corpus_repeated_words=corpus_repeated_words,
corpus_unique_chars=corpus_unique_chars,
corpus_repeated_chars=corpus_repeated_chars,
)
def extract_text_by_type(path: str, s: Settings) -> ExtractionResult:
ext = os.path.splitext(path)[1].lower()
# Dedicated extractors (with fine-grained settings)
if ext == ".docx":
return extract_docx(path, s)
if ext == ".pptx":
return extract_pptx(path, s)
if ext == ".xlsx":
return extract_xlsx(path, s)
if ext == ".pdf":
return extract_pdf(path, s)
# Translation formats (dedicated XML/text parsers — always preferred over Tika)
if ext == ".sdlxliff":
return extract_sdlxliff(path, count_target=s.xliff_count_target)
if ext in {".xliff", ".xlf", ".mqxliff"}:
return extract_xliff(path, count_target=s.xliff_count_target)
if ext == ".tmx":
return extract_tmx(path)
if ext in {".po", ".pot"}:
return extract_po(path)
# Tika fallback for all other formats
if TIKA_OK:
return extract_tika(path)
return ExtractionResult("", "Unsupported file type")
def iter_files(folder: str, include_subfolders: bool, include_pdfs: bool) -> List[str]:
supported = get_supported_exts(include_pdfs)
def ok_ext(fn: str) -> bool:
return os.path.splitext(fn)[1].lower() in supported
paths: List[str] = []
if include_subfolders:
for root, _, files in os.walk(folder):
for fn in files:
if ok_ext(fn):
paths.append(os.path.join(root, fn))
else:
for fn in os.listdir(folder):
p = os.path.join(folder, fn)
if os.path.isfile(p) and ok_ext(fn):
paths.append(p)
return sorted(paths)
def filter_supported(files: List[str], include_pdfs: bool) -> List[str]:
supported = get_supported_exts(include_pdfs)
out = []
for p in files:
if os.path.splitext(p)[1].lower() in supported:
out.append(p)
return sorted(list(dict.fromkeys(out))) # de-dupe preserve order
# ---------------- GUI ----------------
class App(tk.Tk):
def __init__(self):
super().__init__()
self.title(f"{APP_NAME} v{APP_VERSION}, by {APP_AUTHOR}")
self.geometry("1200x760")
self.folder_var = tk.StringVar(value="")
self._queue = queue.Queue()
self._results: List[FileMetrics] = []
self._file_list: List[str] = []
self._repetition: Optional[BatchRepetitionResult] = None
# --- Settings vars (counting) ---
self.include_subfolders_var = tk.BooleanVar(value=True)
self.docx_body_var = tk.BooleanVar(value=True)
self.docx_tables_var = tk.BooleanVar(value=True)
self.docx_headers_var = tk.BooleanVar(value=False)
self.docx_footers_var = tk.BooleanVar(value=False)
self.pptx_slide_text_var = tk.BooleanVar(value=True)
self.pptx_footer_ph_var = tk.BooleanVar(value=False)
self.pptx_notes_var = tk.BooleanVar(value=False)
self.xlsx_text_var = tk.BooleanVar(value=True)
self.xlsx_numbers_var = tk.BooleanVar(value=False)
self.xlsx_comments_var = tk.BooleanVar(value=False)
self.xlsx_hidden_sheets_var = tk.BooleanVar(value=False)
self.pdf_include_var = tk.BooleanVar(value=True)
self.pdf_strip_repeat_var = tk.BooleanVar(value=True)
self.xliff_count_target_var = tk.BooleanVar(value=False)
self.words_per_page_var = tk.IntVar(value=330)
# --- Billing vars ---
self.bill_by_var = tk.StringVar(value="Words") # Words / Characters / Pages (est.)
self.rate_var = tk.DoubleVar(value=0.0)
self.rep_rate_var = tk.DoubleVar(value=0.0) # rate for repeated segments (0 = excluded)
self.currency_var = tk.StringVar(value="GBP")
self.tax_var = tk.DoubleVar(value=0.0) # percent
self.discount_var = tk.DoubleVar(value=0.0) # percent
self._load_settings()
self._build_ui()
self._poll_queue()
self.protocol("WM_DELETE_WINDOW", self._on_close)
# Auto-save settings when any variable changes
for v in (
self.include_subfolders_var,
self.docx_body_var, self.docx_tables_var, self.docx_headers_var, self.docx_footers_var,
self.pptx_slide_text_var, self.pptx_footer_ph_var, self.pptx_notes_var,
self.xlsx_text_var, self.xlsx_numbers_var, self.xlsx_comments_var, self.xlsx_hidden_sheets_var,
self.pdf_include_var, self.pdf_strip_repeat_var,
self.xliff_count_target_var,
self.words_per_page_var,
self.bill_by_var, self.rate_var, self.rep_rate_var, self.currency_var, self.tax_var, self.discount_var,
):
v.trace_add("write", lambda *_: self._save_settings())
# -------- Settings persistence --------
@staticmethod
def _settings_file() -> str:
return os.path.join(os.path.expanduser("~"), ".wordcounter_settings.json")
def _save_settings(self):
data = {
"include_subfolders": self.include_subfolders_var.get(),
"docx_body": self.docx_body_var.get(),
"docx_tables": self.docx_tables_var.get(),
"docx_headers": self.docx_headers_var.get(),
"docx_footers": self.docx_footers_var.get(),
"pptx_slide_text": self.pptx_slide_text_var.get(),
"pptx_footer_ph": self.pptx_footer_ph_var.get(),
"pptx_notes": self.pptx_notes_var.get(),
"xlsx_text": self.xlsx_text_var.get(),
"xlsx_numbers": self.xlsx_numbers_var.get(),
"xlsx_comments": self.xlsx_comments_var.get(),
"xlsx_hidden_sheets": self.xlsx_hidden_sheets_var.get(),
"pdf_include": self.pdf_include_var.get(),
"pdf_strip_repeat": self.pdf_strip_repeat_var.get(),
"xliff_count_target": self.xliff_count_target_var.get(),
"words_per_page": self.words_per_page_var.get(),
"bill_by": self.bill_by_var.get(),
"rate": self.rate_var.get(),
"rep_rate": self.rep_rate_var.get(),
"currency": self.currency_var.get(),
"tax": self.tax_var.get(),
"discount": self.discount_var.get(),
"last_folder": self.folder_var.get(),
"geometry": self.geometry(),
}
try:
with open(self._settings_file(), "w", encoding="utf-8") as f:
json.dump(data, f, indent=2)
except Exception:
pass # non-critical
def _load_settings(self):
try:
with open(self._settings_file(), "r", encoding="utf-8") as f:
data = json.load(f)
except Exception:
return
def _b(key, var):
if key in data:
var.set(bool(data[key]))
def _s(key, var):
if key in data:
var.set(str(data[key]))
def _n(key, var):
if key in data:
try:
var.set(data[key])
except Exception:
pass
_b("include_subfolders", self.include_subfolders_var)
_b("docx_body", self.docx_body_var)
_b("docx_tables", self.docx_tables_var)
_b("docx_headers", self.docx_headers_var)
_b("docx_footers", self.docx_footers_var)
_b("pptx_slide_text", self.pptx_slide_text_var)
_b("pptx_footer_ph", self.pptx_footer_ph_var)
_b("pptx_notes", self.pptx_notes_var)
_b("xlsx_text", self.xlsx_text_var)
_b("xlsx_numbers", self.xlsx_numbers_var)
_b("xlsx_comments", self.xlsx_comments_var)
_b("xlsx_hidden_sheets", self.xlsx_hidden_sheets_var)
_b("pdf_include", self.pdf_include_var)
_b("pdf_strip_repeat", self.pdf_strip_repeat_var)
_b("xliff_count_target", self.xliff_count_target_var)
_n("words_per_page", self.words_per_page_var)
_s("bill_by", self.bill_by_var)
_n("rate", self.rate_var)
_n("rep_rate", self.rep_rate_var)
_s("currency", self.currency_var)
_n("tax", self.tax_var)
_n("discount", self.discount_var)
_s("last_folder", self.folder_var)
if "geometry" in data:
try:
self.geometry(data["geometry"])
except Exception:
pass
def show_about(self):
dlg = tk.Toplevel(self)
dlg.title(f"About {APP_NAME}")
dlg.resizable(False, False)
dlg.grab_set()
dlg.geometry(f"+{self.winfo_rootx() + 200}+{self.winfo_rooty() + 120}")
frame = ttk.Frame(dlg, padding=24)
frame.pack()
ttk.Label(frame, text=f"{APP_NAME} v{APP_VERSION}",
font=("Segoe UI", 14, "bold")).pack(pady=(0, 8))
ttk.Label(frame, text=f"by {APP_AUTHOR}").pack()
# Clickable website link
website_label = tk.Label(frame, text="michaelbeijer.co.uk",
fg="blue", cursor="hand2", font=("Segoe UI", 9, "underline"))
website_label.pack(pady=(2, 8))
website_label.bind("<Button-1>", lambda e: __import__("webbrowser").open("https://michaelbeijer.co.uk/"))
ttk.Separator(frame).pack(fill="x", pady=8)
ttk.Label(frame, text="A batch word counter for translators.",
wraplength=300).pack(pady=(0, 8))
# Clickable repo link
repo_label = tk.Label(frame, text="GitHub: michaelbeijer/WordCounter",
fg="blue", cursor="hand2", font=("Segoe UI", 9, "underline"))
repo_label.pack(pady=(0, 12))
repo_label.bind("<Button-1>", lambda e: __import__("webbrowser").open("https://github.com/michaelbeijer/WordCounter"))
ttk.Button(frame, text="Close", command=dlg.destroy).pack()
def _on_close(self):
self._save_settings()
self.destroy()