-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathWordReplacementLoader.cs
More file actions
94 lines (88 loc) · 3.45 KB
/
Copy pathWordReplacementLoader.cs
File metadata and controls
94 lines (88 loc) · 3.45 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
using System;
using System.Collections.Generic;
using System.IO;
using System.Text.Json;
using System.Text.RegularExpressions;
namespace NaturalCommands
{
/// <summary>
/// Loads optional word replacements from a JSON file and provides an Apply method
/// to deterministically replace whole words in input text (case-insensitive).
/// The JSON file should be a simple object mapping strings to strings, e.g.
/// { "closed": "close", "ferries": "fairies" }
/// </summary>
internal static class WordReplacementLoader
{
private static readonly Dictionary<string, string> _replacements = new(StringComparer.OrdinalIgnoreCase);
public static IReadOnlyDictionary<string, string> Replacements => _replacements;
public static void Load()
{
try
{
var candidates = new[] {
Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "word_replacements.json"),
Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "..", "..", "word_replacements.json"),
Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "..", "..", "..", "word_replacements.json")
};
foreach (var cand in candidates)
{
var p = Path.GetFullPath(cand);
if (File.Exists(p))
{
var json = File.ReadAllText(p);
try
{
var dict = JsonSerializer.Deserialize<Dictionary<string, string>>(json);
if (dict != null)
{
_replacements.Clear();
foreach (var kv in dict)
{
if (string.IsNullOrWhiteSpace(kv.Key)) continue;
_replacements[kv.Key.ToLowerInvariant()] = kv.Value ?? string.Empty;
}
Log($"Loaded word replacements from: {p}");
return;
}
}
catch (Exception ex)
{
Log($"Failed to parse word replacements file {p}: {ex.Message}");
}
}
}
}
catch (Exception ex)
{
Log($"LoadWordReplacements exception: {ex.Message}");
}
}
public static string Apply(string text)
{
if (string.IsNullOrEmpty(text) || _replacements.Count == 0)
return text;
string original = text;
foreach (var kv in _replacements)
{
try
{
text = Regex.Replace(text, "\\b" + Regex.Escape(kv.Key) + "\\b", kv.Value, RegexOptions.IgnoreCase);
}
catch { }
}
if (!string.Equals(original, text, StringComparison.Ordinal))
{
Log($"Applied word replacements: '{original}' -> '{text}'");
}
return text;
}
private static void Log(string msg)
{
try
{
NaturalCommands.Helpers.Logger.LogDebug($"[WordReplacementLoader] {msg}");
}
catch { }
}
}
}