PlotDirector/PlotLine/Services/NameTextMatcher.cs

41 lines
3.2 KiB
C#

using System.Security.Cryptography;
using System.Text;
using System.Text.Json;
using System.Text.RegularExpressions;
using PlotLine.Models;
namespace PlotLine.Services;
public static class NameTextMatcher
{
public const int MaximumParagraphs=1000,MaximumReferences=2000;
public static string NormaliseText(string text)=>text.Normalize(NormalizationForm.FormKC).Replace('\u2019','\'').Replace('\u2018','\'').Replace('\u2010','-').Replace('\u2011','-');
public static string Prefilter(string name)=>Regex.Matches(NormaliseText(name),@"[\p{L}\p{N}]+",RegexOptions.CultureInvariant,TimeSpan.FromMilliseconds(100)).Select(x=>x.Value).OrderByDescending(x=>x.Length).FirstOrDefault()??name;
public static Regex Pattern(string name)
{
var literal=string.Join(@"\s+",Regex.Split(NormaliseText(name).Trim(),@"\s+").Select(Regex.Escape));
return new(@"(?<![\p{L}\p{M}\p{N}_])"+literal+@"(?![\p{L}\p{M}\p{N}_])",RegexOptions.IgnoreCase|RegexOptions.CultureInvariant,TimeSpan.FromMilliseconds(250));
}
public static NameTextSearch Match(string name,NameManuscriptScope scope,IReadOnlyList<NameCandidateParagraph> paragraphs)
{
var pattern=Pattern(name);var contexts=new Dictionary<string,NameCandidateContext>(StringComparer.Ordinal);var total=0;var references=0;var limit=new List<string>();
foreach(var paragraph in paragraphs)
{
var text=NormaliseText(paragraph.Text);var matches=pattern.Matches(text);total=checked(total+matches.Count);
foreach(Match match in matches)
{
if(references>=MaximumReferences)break;
var before=(paragraph.PreviousText is {} previous?previous+"\n":"")+text[Math.Max(0,match.Index-350)..match.Index];
var after=text[(match.Index+match.Length)..Math.Min(text.Length,match.Index+match.Length+350)]+(paragraph.NextText is {} next?"\n"+next:"");
var key=Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(JsonSerializer.Serialize(new{before,match=match.Value,after}))));
if(!contexts.TryGetValue(key,out var context)){context=new(){Key=key,Before=before,Match=match.Value,After=after};contexts.Add(key,context);}
context.References.Add(new(paragraph.BookID,paragraph.BookTitle,paragraph.ChapterID,paragraph.ChapterTitle,paragraph.SceneID,paragraph.SceneTitle,paragraph.ParagraphID,paragraph.ParagraphOrdinal,paragraph.ManuscriptID,paragraph.Revision,paragraph.SourceKind,match.Index));references++;
}
}
var candidates=paragraphs.FirstOrDefault()?.TotalCandidateParagraphs??0;var exact=candidates<=paragraphs.Count&&!paragraphs.Any(x=>x.Truncated);
if(candidates>paragraphs.Count)limit.Add($"The local lookup examined {paragraphs.Count:N0} of {candidates:N0} candidate paragraphs; textual match counts are a lower bound.");
if(paragraphs.Any(x=>x.Truncated))limit.Add("Some unusually long paragraphs were searched in bounded excerpts; textual match counts are a lower bound.");
if(references<total)limit.Add($"At most {MaximumReferences:N0} manuscript references are retained for a verification.");
if(scope.MissingBooks>0)limit.Add($"{scope.MissingBooks} book(s) have missing saved manuscript sources. Verification cannot cover unavailable text.");
return new(scope,total,exact,paragraphs.Count,candidates,exact&&references==total&&scope.MissingBooks==0,contexts.Values.ToList(),limit);
}
}