-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathProgram.cs
338 lines (308 loc) · 12.9 KB
/
Program.cs
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
using System.Diagnostics;
using System.IO.Packaging;
using System.Text.RegularExpressions;
using System.Xml.XPath;
using System.Xml;
using DocumentFormat.OpenXml.Office.Word;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Spreadsheet;
using DocumentFormat.OpenXml.Wordprocessing;
using GlossaryCompliance;
using Text = DocumentFormat.OpenXml.Wordprocessing.Text;
Console.WriteLine("Check Word docs for glossary compliance");
Dictionary<string, string> glossary = new();
int totalHits = 0;
int totalMisses = 0;
ReportWriter reportWriter = new("report.txt");
if (args.Length > 1)
{
ReadGlossaryFromExcel(args[1], ref glossary);
reportWriter.WriteLine("Glossary read.");
string rootPath = args[0];
TraverseDirectory(rootPath, ProcessFile);
reportWriter.WriteLine($"Total hits: {totalHits}\tTotal misses: {totalMisses}");
reportWriter.Show();
return 0;
}
else
Console.WriteLine("ERROR: Please provide a folder path as argument.");
return 1;
void ReadGlossaryFromExcel(string excelFileName, ref Dictionary<string, string> glossary)
{
using SpreadsheetDocument document = SpreadsheetDocument.Open(excelFileName, false);
if (document is null)
{
reportWriter.WriteLine($"ERROR: Could not open {excelFileName}.");
throw new FileNotFoundException($"ERROR: Could not open {excelFileName}.");
}
var sheets = document.WorkbookPart.WorksheetParts;
// Loop through each of the sheets in the spreadsheet
foreach (var wp in sheets)
{
Worksheet worksheet = wp.Worksheet;
// Loop through each of the rows in the current sheet
var rows = worksheet.GetFirstChild<SheetData>().Elements<Row>();
foreach (var row in rows)
{
// Loop through each of the cells in the current row.
var cells = row.Elements<Cell>();
string rememberA = null;
foreach (var cell in cells)
{
if (cell.CellValue is null) continue;
string? value = document.WorkbookPart.SharedStringTablePart.SharedStringTable.ElementAt(int.Parse(cell.CellValue.Text)).InnerText;
if (cell.CellReference.InnerText.StartsWith('A') && value is not null)
{
rememberA = value;
continue;
}
if (cell.CellReference.InnerText.StartsWith('B') && value is not null && rememberA is not null)
{
if (!glossary.TryAdd(rememberA.Trim(), value.Trim()))
{
reportWriter.WriteLine($"Duplicate glossary entry: {rememberA} - {value}");
}
break;
}
reportWriter.WriteLine($"Something went wrong with glossary entry {cell.CellValue.Text}: Either source or target are empty.");
}
}
}
reportWriter.WriteLine($"{glossary.Count} glossary entries read.");
document.Close();
}
void ProcessExcel(string excelFileName)
{
using SpreadsheetDocument document = SpreadsheetDocument.Open(excelFileName, false);
var sheets = document.WorkbookPart.WorksheetParts;
// Loop through each of the sheets in the spreadsheet
foreach (var wp in sheets)
{
Worksheet worksheet = wp.Worksheet;
// Loop through each of the rows in the current sheet
var rows = worksheet.GetFirstChild<SheetData>().Elements<Row>();
foreach (var row in rows)
{
// Loop through each of the cells in the current row.
var cells = row.Elements<Cell>();
string rememberA = null;
foreach (var cell in cells)
{
string value = document.WorkbookPart.SharedStringTablePart.SharedStringTable.ElementAt(int.Parse(cell.CellValue.Text)).InnerText;
if (cell.CellReference.InnerText.StartsWith('A') && value is not null)
{
rememberA = value;
continue;
}
if (cell.CellReference.InnerText.StartsWith('B') && value is not null && rememberA is not null)
{
break;
}
reportWriter.WriteLine($"Something went wrong with glossary entry {cell.CellValue.Text}: Either source or target are empty.");
}
}
}
reportWriter.WriteLine($"{glossary.Count} glossary entries read.");
document.Close();
}
void TraverseDirectory(string path, Action<string, FileType> action)
{
foreach (string file in Directory.GetFiles(path))
{
if (file.ToUpperInvariant().Contains("_EN.") && (Path.GetExtension(file).ToLowerInvariant() == ".docx"))
{
action(file, FileType.docx);
continue;
}
if (Path.GetExtension(file).ToLowerInvariant() == ".tmx")
{
ProcessTMX(file);
continue;
}
if (Path.GetExtension(file).ToLowerInvariant() == ".xlsx")
{
ProcessExcel(file);
continue;
}
reportWriter.WriteLine($"File skipped:\t{Path.GetFileName(file)}");
}
foreach (string directory in Directory.GetDirectories(path))
{
TraverseDirectory(directory, action);
}
}
void ProcessTMX(string fileName)
{
Debug.WriteLine(fileName);
XmlDocument xmlDoc = new();
xmlDoc.Load(fileName);
XPathNavigator xPathNavigator = xmlDoc.CreateNavigator();
XmlNamespaceManager xmlNamespaceManager = new(xPathNavigator.NameTable);
// Select all TU elements
XmlNodeList tuNodes = xmlDoc.SelectNodes("//tu");
Dictionary<string, CountPair> glosCountPerDoc = new();
int segmentCounter = 0;
// Loop through each TU element and apply the method
foreach (XmlNode tuNode in tuNodes)
{
segmentCounter++;
if ((segmentCounter % 100) == 0) Console.WriteLine("T");
// Apply your method to the TU element here
// For example, you could extract the source and target segments:
XmlNode segSource = tuNode.SelectSingleNode("./tuv[@xml:lang='EN-US']/seg", xmlNamespaceManager);
string sourceText = RemoveMarkup(segSource.InnerText);
XmlNode segTarget = tuNode.SelectSingleNode("./tuv[@xml:lang='ES-ES']/seg", xmlNamespaceManager);
string targetText = RemoveMarkup(segTarget.InnerText);
foreach (string glosEntry in glossary.Keys)
{
//Debug.Assert(!(text.InnerText.Contains("shelters") && (glosEntry=="shelters")));
//BUGBUG This counting misses a count when the glossary term appears multiple times in the same text segment
if (Regex.Match(sourceText, "\\b" + glosEntry + "\\b").Success)
{
if (glosCountPerDoc.TryGetValue(glosEntry, out CountPair countPair))
{
countPair.SourceCount++;
glosCountPerDoc[glosEntry] = countPair;
}
else
glosCountPerDoc.Add(glosEntry, new CountPair(1, 0));
}
}
foreach (string glosEntry in glosCountPerDoc.Keys)
{
string[] alternatives = glossary[glosEntry].Split('/');
foreach (string alternative in alternatives)
{
MatchCollection matches = Regex.Matches(targetText, "\\b" + alternative.Trim() + "\\b", RegexOptions.IgnoreCase);
if (matches.Count > 0)
{
//Debug.Assert(text.InnerText.Contains("asistencia financiera"));
CountPair countPair = glosCountPerDoc[glosEntry];
countPair.TargetCount += matches.Count;
glosCountPerDoc[glosEntry] = countPair;
}
}
}
}
reportWriter.WriteLine("=================================================");
reportWriter.WriteLine($"{Path.GetFileName(fileName)}{Path.GetExtension(fileName)}");
reportWriter.WriteLine("-------------------------------------------------");
int matchCount = 0;
int missCount = 0;
foreach (string glosEntry in glosCountPerDoc.Keys)
{
if (glosCountPerDoc[glosEntry].IsSatisfied())
{
matchCount++;
}
else
{
reportWriter.WriteLine($"Glossary mismatch:\t{glosEntry}\t{glosCountPerDoc[glosEntry].SourceCount}\t{glossary[glosEntry]}\t{glosCountPerDoc[glosEntry].TargetCount}");
missCount++;
}
}
reportWriter.WriteLine($"{matchCount} entries verified.\t{missCount} entries failed.");
totalHits += matchCount;
totalMisses += missCount;
}
static string RemoveMarkup(string tuv)
{
// regular expression pattern to match XML tags
string pattern = @"<[^>]+>";
// remove all XML tags from the string
string plainText = Regex.Replace(tuv, pattern, "");
//other cleanup
plainText = plainText.Replace("\t", " ");
plainText = plainText.Replace("• ", "");
plainText = plainText.StartsWith("-") ? plainText[1..] : plainText;
plainText = plainText.StartsWith("■") ? plainText[1..] : plainText;
plainText = plainText.StartsWith("\"") ? "\"" + plainText : plainText;
plainText = Regex.Replace(plainText, @"\.+", ".");
// output plain text string
return plainText.Trim();
}
void ProcessFile(string filePath, FileType fileType)
{
Debug.WriteLine(filePath);
Console.Write(".");
List<Text> textsSource = new();
using WordprocessingDocument docSource = WordprocessingDocument.Open(filePath, false);
var bodySource = docSource.MainDocumentPart.Document.Body;
textsSource.AddRange(bodySource.Descendants<DocumentFormat.OpenXml.Wordprocessing.Text>()
.Where(text => !String.IsNullOrEmpty(text.Text) && text.Text.Length > 0));
//count up all glossary entries in the source document
Dictionary<string, CountPair> glosCountPerDoc = new();
foreach (Text text in textsSource)
{
foreach (string glosEntry in glossary.Keys)
{
//Debug.Assert(!(text.InnerText.Contains("shelters") && (glosEntry=="shelters")));
//BUGBUG This counting misses a count when the glossary term appears multiple times in the same text segment
if (Regex.Match(text.InnerText, "\\b" + glosEntry + "\\b").Success)
{
if (glosCountPerDoc.TryGetValue(glosEntry, out CountPair countPair))
{
countPair.SourceCount++;
glosCountPerDoc[glosEntry] = countPair;
}
else
glosCountPerDoc.Add(glosEntry, new CountPair(1, 0));
}
}
}
//Now count the glossary target side in the target document
string targetFileName = filePath.Replace("_EN.", "_ES.");
if (!File.Exists(targetFileName))
{
reportWriter.WriteLine($"ERROR: Target file {targetFileName} not found.");
return;
}
if (filePath == targetFileName)
{
reportWriter.WriteLine($"ERROR: Target file {targetFileName} is the same as the source file.");
return;
}
List<Text> textsTarget = new();
using WordprocessingDocument docTarget = WordprocessingDocument.Open(targetFileName, false);
var bodyTarget = docTarget.MainDocumentPart.Document.Body;
textsTarget.AddRange(bodyTarget.Descendants<DocumentFormat.OpenXml.Wordprocessing.Text>()
.Where(text => !String.IsNullOrEmpty(text.Text) && text.Text.Length > 0));
foreach (Text text in textsTarget)
{
foreach (string glosEntry in glosCountPerDoc.Keys)
{
string[] alternatives = glossary[glosEntry].Split('/');
foreach (string alternative in alternatives)
{
MatchCollection matches = Regex.Matches(text.InnerText, "\\b" + alternative.Trim() + "\\b", RegexOptions.IgnoreCase);
if (matches.Count > 0)
{
//Debug.Assert(text.InnerText.Contains("asistencia financiera"));
CountPair countPair = glosCountPerDoc[glosEntry];
countPair.TargetCount += matches.Count;
glosCountPerDoc[glosEntry] = countPair;
}
}
}
}
reportWriter.WriteLine("=================================================");
reportWriter.WriteLine($"{Path.GetFileName(filePath)}\t{Path.GetFileName(targetFileName)}");
reportWriter.WriteLine("-------------------------------------------------");
int matchCount = 0;
int missCount = 0;
foreach (string glosEntry in glosCountPerDoc.Keys)
{
if (glosCountPerDoc[glosEntry].IsSatisfied())
{
matchCount++;
}
else
{
reportWriter.WriteLine($"Glossary mismatch:\t{glosEntry}\t{glosCountPerDoc[glosEntry].SourceCount}\t{glossary[glosEntry]}\t{glosCountPerDoc[glosEntry].TargetCount}");
missCount++;
}
}
reportWriter.WriteLine($"{matchCount} entries verified.\t{missCount} entries failed.");
totalHits += matchCount;
totalMisses += missCount;
}