-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
2509 lines (2234 loc) · 92.8 KB
/
server.js
File metadata and controls
2509 lines (2234 loc) · 92.8 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
// Load environment variables from .env file
require("dotenv").config();
const express = require("express");
const cors = require("cors");
const bodyParser = require("body-parser");
const natural = require("natural");
const stringSimilarity = require("string-similarity");
const { distance } = require("ml-distance");
const { Matrix } = require("ml-matrix");
const axios = require("axios");
const { exec } = require("child_process");
const { promisify } = require("util");
const path = require("path");
const fs = require("fs");
const GreekNameCorrector = require("./greeknames_rules.js");
const AINameDBSearcherMSSQL = require("./ai_name_db_checker_standalone.js");
const AISimilaritySearch = require("./ai_similarity_search.js");
const execAsync = promisify(exec);
const app = express();
const PORT = 3031;
// Middleware
app.use(cors());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
// Request logging middleware
app.use((req, res, next) => {
const timestamp = new Date().toISOString();
console.log(`[${timestamp}] ${req.method} ${req.path} - IP: ${req.ip || req.connection.remoteAddress}`);
if (req.method === "POST" && req.path === "/compare") {
console.log(`📝 Request Body Summary:`, {
inputObject: req.body.inputObject ? "Object provided" : "undefined",
inputElement: req.body.inputElement || "undefined",
inputString:
req.body.inputObject && req.body.inputElement && req.body.inputObject[req.body.inputElement]
? `${req.body.inputObject[req.body.inputElement].substring(0, 50)}${
req.body.inputObject[req.body.inputElement].length > 50 ? "..." : ""
}`
: "undefined",
arrayOfObjects: req.body.arrayOfObjects ? `${req.body.arrayOfObjects.length} objects` : "undefined",
elementToCheck: req.body.elementToCheck || "undefined"
});
// Debug logging for object parsing
console.log(`🔍 Debug - Raw inputObject:`, req.body.inputObject);
console.log(`🔍 Debug - inputObject type:`, typeof req.body.inputObject);
console.log(`🔍 Debug - inputObject constructor:`, req.body.inputObject?.constructor?.name);
console.log(`🔍 Debug - inputObject keys:`, req.body.inputObject ? Object.keys(req.body.inputObject) : "N/A");
console.log(`🔍 Debug - Full request body keys:`, Object.keys(req.body));
console.log(`🔍 Debug - Content-Type:`, req.get("Content-Type"));
}
next();
});
// Initialize TF-IDF for better text similarity
const tfidf = new natural.TfIdf();
// Text preprocessing function
function preprocessText(text) {
return text
.toLowerCase()
.replace(/[^\w\s]/g, "") // Remove punctuation
.replace(/\s+/g, " ") // Normalize whitespace
.trim();
}
// Calculate cosine similarity between two vectors
function cosineSimilarity(vecA, vecB) {
if (vecA.length !== vecB.length) {
throw new Error("Vectors must have the same length");
}
let dotProduct = 0;
let normA = 0;
let normB = 0;
for (let i = 0; i < vecA.length; i++) {
dotProduct += vecA[i] * vecB[i];
normA += vecA[i] * vecA[i];
normB += vecB[i] * vecB[i];
}
normA = Math.sqrt(normA);
normB = Math.sqrt(normB);
if (normA === 0 || normB === 0) {
return 0;
}
return dotProduct / (normA * normB);
}
// Create TF-IDF vectors for text similarity
function createTfIdfVector(text, corpus) {
const tfidf = new natural.TfIdf();
// Add all documents to TF-IDF
corpus.forEach((doc) => tfidf.addDocument(doc));
// Get TF-IDF vector for the input text
const vector = new Array(corpus.length).fill(0);
tfidf.tfidfs(text, (i, measure) => {
vector[i] = measure;
});
return vector;
}
// Calculate multiple similarity scores
function calculateSimilarityScores(inputText, targetText) {
const scores = {};
// 1. String similarity (Dice coefficient)
scores.stringSimilarity = stringSimilarity.compareTwoStrings(inputText, targetText);
// 2. Jaro-Winkler distance
scores.jaroWinkler = natural.JaroWinklerDistance(inputText, targetText);
// 3. Levenshtein distance (normalized)
const levenshtein = natural.LevenshteinDistance(inputText, targetText);
const maxLength = Math.max(inputText.length, targetText.length);
scores.levenshtein = maxLength === 0 ? 1 : 1 - levenshtein / maxLength;
// 4. Jaccard similarity
const inputWords = new Set(inputText.toLowerCase().split(/\s+/));
const targetWords = new Set(targetText.toLowerCase().split(/\s+/));
const intersection = new Set([...inputWords].filter((x) => targetWords.has(x)));
const union = new Set([...inputWords, ...targetWords]);
scores.jaccard = union.size === 0 ? 0 : intersection.size / union.size;
// 5. TF-IDF cosine similarity
const corpus = [inputText, targetText];
const inputVector = createTfIdfVector(inputText, corpus);
const targetVector = createTfIdfVector(targetText, corpus);
scores.tfidfCosine = cosineSimilarity(inputVector, targetVector);
return scores;
}
// Calculate weighted similarity score
function calculateWeightedScore(scores) {
const weights = {
stringSimilarity: 0.3,
jaroWinkler: 0.2,
levenshtein: 0.2,
jaccard: 0.15,
tfidfCosine: 0.15
};
let weightedScore = 0;
for (const [metric, weight] of Object.entries(weights)) {
weightedScore += scores[metric] * weight;
}
return Math.min(1, Math.max(0, weightedScore));
}
// Main similarity comparison function
function compareStrings(inputString, arrayOfObjects, elementToCheck) {
const results = [];
arrayOfObjects.forEach((obj, index) => {
const targetString = obj[elementToCheck];
if (!targetString || typeof targetString !== "string") {
return;
}
const scores = calculateSimilarityScores(inputString, targetString);
const weightedScore = calculateWeightedScore(scores);
results.push({
index: index,
originalObject: obj,
targetString: targetString,
score: weightedScore,
detailedScores: scores
});
});
// Sort by score (descending)
results.sort((a, b) => b.score - a.score);
return results;
}
// POST endpoint for string similarity comparison
app.post("/compare", (req, res) => {
try {
const { inputObject, inputElement, arrayOfObjects, elementToCheck } = req.body;
// Validation with detailed logging
console.log("🔍 Validation Debug:");
console.log(" - inputObject exists:", !!inputObject);
console.log(" - inputObject type:", typeof inputObject);
console.log(" - inputObject value:", inputObject);
console.log(" - inputObject is null:", inputObject === null);
console.log(" - inputObject is array:", Array.isArray(inputObject));
let parsedInputObject = inputObject;
// Try to parse inputObject if it's a string
if (typeof inputObject === "string") {
console.log("🔄 Attempting to parse inputObject string as JSON...");
try {
parsedInputObject = JSON.parse(inputObject);
console.log("✅ Successfully parsed inputObject string to object");
console.log(" - Parsed type:", typeof parsedInputObject);
console.log(" - Parsed keys:", Object.keys(parsedInputObject));
} catch (parseError) {
console.log("❌ Failed to parse inputObject string as JSON:", parseError.message);
console.log("❌ Raw string value:", inputObject.substring(0, 100) + (inputObject.length > 100 ? "..." : ""));
return res.status(400).json({
error: "inputObject string could not be parsed as valid JSON",
debug: {
received: inputObject,
type: typeof inputObject,
parseError: parseError.message
}
});
}
}
if (!parsedInputObject || typeof parsedInputObject !== "object" || Array.isArray(parsedInputObject)) {
console.log("❌ Validation Error: inputObject is required and must be an object");
console.log("❌ Debug - inputObject details:", {
exists: !!parsedInputObject,
type: typeof parsedInputObject,
isArray: Array.isArray(parsedInputObject),
isNull: parsedInputObject === null,
value: parsedInputObject
});
return res.status(400).json({
error: "inputObject is required and must be an object",
debug: {
received: parsedInputObject,
type: typeof parsedInputObject,
isArray: Array.isArray(parsedInputObject)
}
});
}
// Update inputObject to use the parsed version
const finalInputObject = parsedInputObject;
if (!inputElement || typeof inputElement !== "string") {
console.log("❌ Validation Error: inputElement is required and must be a string");
return res.status(400).json({
error: "inputElement is required and must be a string"
});
}
// Helper function to get nested property using dot notation
function getNestedProperty(obj, path) {
return path.split(".").reduce((current, key) => {
return current && current[key] !== undefined ? current[key] : undefined;
}, obj);
}
// Check if inputElement exists (supports dot notation)
const inputString = getNestedProperty(finalInputObject, inputElement);
if (inputString === undefined) {
console.log("❌ Validation Error: inputObject does not have the specified inputElement path");
console.log("❌ Debug - Searched path:", inputElement);
console.log("❌ Debug - Available keys:", Object.keys(finalInputObject));
return res.status(400).json({
error: "inputObject does not have the specified inputElement path",
debug: {
searchedPath: inputElement,
availableKeys: Object.keys(finalInputObject)
}
});
}
if (!inputString || typeof inputString !== "string") {
console.log("❌ Validation Error: inputElement value must be a string");
return res.status(400).json({
error: "inputElement value must be a string"
});
}
if (!Array.isArray(arrayOfObjects)) {
console.log("❌ Validation Error: arrayOfObjects is required and must be an array");
return res.status(400).json({
error: "arrayOfObjects is required and must be an array"
});
}
if (!elementToCheck || typeof elementToCheck !== "string") {
console.log("❌ Validation Error: elementToCheck is required and must be a string");
return res.status(400).json({
error: "elementToCheck is required and must be a string"
});
}
// Filter out objects that don't have the specified element
const validObjects = arrayOfObjects.filter(
(obj) => obj && typeof obj === "object" && obj.hasOwnProperty(elementToCheck)
);
if (validObjects.length === 0) {
console.log("❌ Validation Error: No valid objects found with the specified elementToCheck");
return res.status(400).json({
error: "No valid objects found with the specified elementToCheck"
});
}
// Perform similarity comparison
const comparisonResults = compareStrings(inputString, validObjects, elementToCheck);
// Filter results with score > 0 (optional threshold)
const filteredResults = comparisonResults.filter((result) => result.score > 0);
// Format response
const response = {
inputObject: finalInputObject,
inputString: inputString,
totalCompared: validObjects.length,
resultsReturned: filteredResults.length,
results: filteredResults.map((result) => ({
index: result.index,
score: Math.round(result.score * 10000) / 10000, // Round to 4 decimal places
targetString: result.targetString,
originalObject: result.originalObject
})),
topMatch:
filteredResults.length > 0
? {
index: filteredResults[0].index,
score: Math.round(filteredResults[0].score * 10000) / 10000,
targetString: filteredResults[0].targetString,
originalObject: filteredResults[0].originalObject
}
: null
};
// Log response summary
console.log(`✅ Response: ${response.resultsReturned}/${response.totalCompared} matches found`);
if (response.topMatch) {
console.log(
`🎯 Top match: Score ${response.topMatch.score} - "${response.topMatch.targetString.substring(0, 50)}${
response.topMatch.targetString.length > 50 ? "..." : ""
}"`
);
}
res.json(response);
} catch (error) {
console.error("❌ Error in comparison:", error.message);
console.error("Stack trace:", error.stack);
res.status(500).json({
error: "Internal server error",
message: error.message
});
}
});
// POST endpoint for finding AFKAS numbers in filenames
app.post("/findAfaks", (req, res) => {
try {
const { filename, ignoreStrings } = req.body;
// Validation
if (!filename || typeof filename !== "string") {
console.log("❌ Validation Error: filename is required and must be a string");
return res.status(400).json({
error: "filename is required and must be a string"
});
}
// Validate ignoreStrings if provided
if (ignoreStrings !== undefined) {
if (!Array.isArray(ignoreStrings)) {
console.log("❌ Validation Error: ignoreStrings must be an array");
return res.status(400).json({
error: "ignoreStrings must be an array of strings"
});
}
// Check if all elements in ignoreStrings are strings
const invalidElements = ignoreStrings.filter((item) => typeof item !== "string");
if (invalidElements.length > 0) {
console.log("❌ Validation Error: All elements in ignoreStrings must be strings");
return res.status(400).json({
error: "All elements in ignoreStrings must be strings"
});
}
}
let autoIgnoreNumbers = [];
let afkasNumbers = [];
// Step 1: Detect year patterns and extract AFKs that appear after them
// Pattern 1: number_year_AFKs... (e.g., "11668_2025_40450", "9304_2025_40140_40142")
const pattern1 = /^(\d+)_(\d{4})_(.+)/;
const match1 = filename.match(pattern1);
// Pattern 2: _year_AFKs... (e.g., "_2025_40450", "_2025_40140-40142")
const pattern2 = /^_(\d{4})_(.+)/;
const match2 = filename.match(pattern2);
if (match1) {
const beforeYearNumber = parseInt(match1[1], 10);
const year = parseInt(match1[2], 10);
const afterYearPart = match1[3];
autoIgnoreNumbers.push(beforeYearNumber);
autoIgnoreNumbers.push(year);
console.log(`🔢 Auto-detected number before year: ${beforeYearNumber}`);
console.log(`🗓️ Auto-detected year (pattern 1): ${year}`);
// Extract AFKs from the part after the year
// AFKs can be separated by underscores or hyphens
// Match sequences like: 40450, 40140_40142, 40140-40142, 40220-40221-40222
// Extract all 4-5 digit numbers that appear immediately after the year
// Use pattern that works with underscores and hyphens (not word boundaries)
const afkasPattern = /(?:^|[^0-9])(\d{4,5})(?![0-9])/g;
const afkasMatches = [...afterYearPart.matchAll(afkasPattern)];
if (afkasMatches && afkasMatches.length > 0) {
afkasNumbers = [...new Set(afkasMatches.map((match) => parseInt(match[1], 10)))];
console.log(`🔍 Extracted AFKs from pattern 1: [${afkasNumbers.join(", ")}]`);
}
} else if (match2) {
const year = parseInt(match2[1], 10);
const afterYearPart = match2[2];
autoIgnoreNumbers.push(year);
console.log(`🗓️ Auto-detected year (pattern 2): ${year}`);
// Extract AFKs from the part after the year
// Use pattern that works with underscores and hyphens (not word boundaries)
const afkasPattern = /(?:^|[^0-9])(\d{4,5})(?![0-9])/g;
const afkasMatches = [...afterYearPart.matchAll(afkasPattern)];
if (afkasMatches && afkasMatches.length > 0) {
afkasNumbers = [...new Set(afkasMatches.map((match) => parseInt(match[1], 10)))];
console.log(`🔍 Extracted AFKs from pattern 2: [${afkasNumbers.join(", ")}]`);
}
} else {
// No year pattern found - check if there are any AFKs at all
// Only extract if they appear in sequences (separated by underscores/hyphens)
// This handles cases where there might be AFKs without a year pattern
// But we're more conservative here - if no year pattern, likely no AFKs
// (This handles edge cases, but most examples have year patterns)
// Look for sequences of 4-5 digit numbers separated by underscores or hyphens
// But exclude standalone numbers at the start (like "10713_" which is not an AFK)
const standaloneAfkasPattern = /(?:_|^)(\d{4,5})(?:[-_](\d{4,5}))+/;
const standaloneMatch = filename.match(standaloneAfkasPattern);
if (standaloneMatch) {
// Extract all numbers from the sequence
const sequencePart = standaloneMatch[0];
const numbersPattern = /(?:^|[^0-9])(\d{4,5})(?![0-9])/g;
const numbersMatches = [...sequencePart.matchAll(numbersPattern)];
if (numbersMatches && numbersMatches.length > 0) {
afkasNumbers = [...new Set(numbersMatches.map((match) => parseInt(match[1], 10)))];
// Filter out years
afkasNumbers = afkasNumbers.filter((num) => num < 2000 || num > 2099);
if (afkasNumbers.length > 0) {
console.log(`🔍 Extracted AFKs from standalone pattern: [${afkasNumbers.join(", ")}]`);
}
}
}
}
// Step 2: Combine user-provided ignoreStrings with auto-detected ones
const allIgnoreNumbers = [...autoIgnoreNumbers];
if (ignoreStrings && ignoreStrings.length > 0) {
console.log(`🔍 User-provided ignoreStrings: [${ignoreStrings.join(", ")}]`);
allIgnoreNumbers.push(...ignoreStrings.map((str) => parseInt(str, 10)).filter((num) => !isNaN(num)));
}
// Step 3: Filter out numbers that should be ignored
if (allIgnoreNumbers.length > 0) {
console.log(`🔍 Filtering with all ignore numbers: [${allIgnoreNumbers.join(", ")}]`);
afkasNumbers = afkasNumbers.filter((number) => {
const shouldIgnore = allIgnoreNumbers.includes(number);
if (shouldIgnore) {
console.log(`🚫 Filtering out ${number} (in ignore list)`);
}
return !shouldIgnore;
});
}
// Step 4: Final validation - ensure we only return valid AFKs
// AFKs should be 4-5 digit numbers, exclude years
afkasNumbers = afkasNumbers.filter((num) => {
// Must be 4-5 digits
if (num < 1000 || num > 99999) {
return false;
}
// Exclude years (2000-2099)
if (num >= 2000 && num <= 2099) {
return false;
}
return true;
});
// Sort numbers for consistent output
afkasNumbers.sort((a, b) => a - b);
const response = {
filename: filename,
afkasNumbers: afkasNumbers,
count: afkasNumbers.length,
found: afkasNumbers.length > 0,
ignoreStrings: ignoreStrings || [],
autoIgnoredNumbers: autoIgnoreNumbers,
allIgnoredNumbers: allIgnoreNumbers
};
console.log(`🔍 AFKAS Search: "${filename}" -> [${afkasNumbers.join(", ")}]`);
res.json(response);
} catch (error) {
console.error("❌ Error in findAfaks:", error.message);
console.error("Stack trace:", error.stack);
res.status(500).json({
error: "Internal server error",
message: error.message
});
}
});
// Initialize Greek Name Corrector
const greekNameCorrector = new GreekNameCorrector();
// Initialize AI Name Database Searcher (Standalone)
let aiNameSearcherMSSQL = null;
// Initialize AI searcher with standalone configuration
async function initializeAISearcherMSSQL() {
try {
aiNameSearcherMSSQL = new AINameDBSearcherMSSQL({
batchSize: 1000,
similarityThreshold: 0.7,
maxResults: 50
});
console.log("🤖 AI Name Database Searcher (Standalone) initialized successfully");
} catch (error) {
console.error("❌ Failed to initialize AI Name Database Searcher:", error);
}
}
// Initialize the AI searcher on startup
initializeAISearcherMSSQL();
// Initialize AI Similarity Search
let aiSimilaritySearch = null;
async function initializeAISimilaritySearch() {
try {
aiSimilaritySearch = new AISimilaritySearch({
batchSize: 1000,
similarityThreshold: 0.7,
maxResults: 50
});
// Initialize database connection (will be lazy-loaded when first used)
// Don't initialize connection at startup to avoid loading Azure dependencies
console.log("🤖 AI Similarity Search instance created (connection will be established on first use)");
} catch (error) {
console.error("❌ Failed to create AI Similarity Search instance:", error);
console.error(" The server will continue, but /aiSimilaritySearch endpoints may not work");
}
}
// Initialize on startup (non-blocking)
initializeAISimilaritySearch();
// POST endpoint for Greek name correction
app.post("/correctGreekName", (req, res) => {
try {
const { name, options = {} } = req.body;
// Validation
if (!name || typeof name !== "string") {
return res.status(400).json({
success: false,
error: "Invalid name provided. Name must be a non-empty string.",
received: { name, type: typeof name }
});
}
console.log(`🇬🇷 Greek Name Correction Request:`, {
name: name,
options: options,
timestamp: new Date().toISOString()
});
// Correct the name using the Greek Name Corrector
const result = greekNameCorrector.correctName(name, options);
// Log the result for debugging
console.log(`✅ Greek Name Correction Result:`, {
original: result.original,
corrected: result.corrected,
gender: result.gender,
confidence: result.confidence
});
// Return the result
res.json({
success: true,
data: result,
timestamp: new Date().toISOString()
});
} catch (error) {
console.error("❌ Greek Name Correction Error:", error);
res.status(500).json({
success: false,
error: "Internal server error during Greek name correction",
message: error.message,
timestamp: new Date().toISOString()
});
}
});
// POST endpoint for AI-powered Greek name database search
app.post("/aiNameSearch", async (req, res) => {
try {
const { firstName, lastName, databaseRecords, options = {} } = req.body;
// Validation
if (!firstName && !lastName) {
console.log("❌ Validation Error: At least one name (first or last) must be provided");
return res.status(400).json({
success: false,
error: "At least one name (first or last) must be provided",
received: { firstName, lastName }
});
}
if (!Array.isArray(databaseRecords) || databaseRecords.length === 0) {
console.log("❌ Validation Error: databaseRecords is required and must not be empty");
return res.status(400).json({
success: false,
error: "databaseRecords is required and must not be empty",
received: {
databaseRecords: Array.isArray(databaseRecords) ? databaseRecords.length : "not an array"
}
});
}
// Check if AI searcher is initialized
if (!aiNameSearcher) {
console.log("❌ AI searcher not initialized");
return res.status(500).json({
success: false,
error: "AI Name Database Searcher is not initialized. Please try again in a moment."
});
}
console.log(`🤖 AI Name Search Request:`, {
firstName: firstName || "not provided",
lastName: lastName || "not provided",
databaseRecordsCount: databaseRecords.length,
options: options,
timestamp: new Date().toISOString()
});
// Perform AI-powered semantic search
const searchResults = await aiNameSearcher.searchNames(firstName || "", lastName || "", databaseRecords, options);
// Log the result for debugging
console.log(`✅ AI Name Search Result:`, {
query: searchResults.query,
resultsFound: searchResults.results.length,
totalProcessed: searchResults.totalProcessed,
topMatch:
searchResults.results.length > 0
? {
name: searchResults.results[0].fullName,
similarity: searchResults.results[0].similarity
}
: null
});
// Return the result
res.json({
success: true,
data: searchResults,
timestamp: new Date().toISOString()
});
} catch (error) {
console.error("❌ AI Name Search Error:", error);
res.status(500).json({
success: false,
error: "Internal server error during AI name search",
message: error.message,
timestamp: new Date().toISOString()
});
}
});
// POST endpoint for AI-powered partial name search
app.post("/aiPartialNameSearch", async (req, res) => {
try {
const { partialName, databaseRecords, options = {} } = req.body;
// Validation
if (!partialName || typeof partialName !== "string" || partialName.trim().length < 2) {
console.log("❌ Validation Error: partialName must be at least 2 characters long");
return res.status(400).json({
success: false,
error: "partialName must be at least 2 characters long",
received: { partialName, type: typeof partialName }
});
}
if (!Array.isArray(databaseRecords) || databaseRecords.length === 0) {
console.log("❌ Validation Error: databaseRecords is required and must not be empty");
return res.status(400).json({
success: false,
error: "databaseRecords is required and must not be empty",
received: {
databaseRecords: Array.isArray(databaseRecords) ? databaseRecords.length : "not an array"
}
});
}
// Check if AI searcher is initialized
if (!aiNameSearcher) {
console.log("❌ AI searcher not initialized");
return res.status(500).json({
success: false,
error: "AI Name Database Searcher is not initialized. Please try again in a moment."
});
}
console.log(`🔍 AI Partial Name Search Request:`, {
partialName: partialName,
databaseRecordsCount: databaseRecords.length,
options: options,
timestamp: new Date().toISOString()
});
// Perform AI-powered partial name search
const searchResults = await aiNameSearcher.searchPartialName(partialName, databaseRecords, options);
// Log the result for debugging
console.log(`✅ AI Partial Name Search Result:`, {
query: searchResults.query,
resultsFound: searchResults.results.length,
totalProcessed: searchResults.totalProcessed,
topMatch:
searchResults.results.length > 0
? {
name: searchResults.results[0].fullName,
similarity: searchResults.results[0].similarity
}
: null
});
// Return the result
res.json({
success: true,
data: searchResults,
timestamp: new Date().toISOString()
});
} catch (error) {
console.error("❌ AI Partial Name Search Error:", error);
res.status(500).json({
success: false,
error: "Internal server error during AI partial name search",
message: error.message,
timestamp: new Date().toISOString()
});
}
});
// GET endpoint for AI searcher statistics
app.get("/aiSearchStats", (req, res) => {
try {
if (!aiNameSearcher) {
return res.status(500).json({
success: false,
error: "AI Name Database Searcher is not initialized"
});
}
const stats = aiNameSearcher.getSearchStats();
res.json({
success: true,
data: {
isInitialized: stats.isInitialized,
batchSize: stats.batchSize,
similarityThreshold: stats.similarityThreshold,
embeddingsCacheSize: stats.embeddingsCacheSize,
memoryUsage: {
heapUsed: Math.round(stats.memoryUsage.heapUsed / 1024 / 1024),
heapTotal: Math.round(stats.memoryUsage.heapTotal / 1024 / 1024),
external: Math.round(stats.memoryUsage.external / 1024 / 1024),
rss: Math.round(stats.memoryUsage.rss / 1024 / 1024)
}
},
timestamp: new Date().toISOString()
});
} catch (error) {
console.error("❌ AI Search Stats Error:", error);
res.status(500).json({
success: false,
error: "Internal server error getting AI search statistics",
message: error.message,
timestamp: new Date().toISOString()
});
}
});
// POST endpoint to clear AI searcher cache
app.post("/aiSearchClearCache", (req, res) => {
try {
if (!aiNameSearcher) {
return res.status(500).json({
success: false,
error: "AI Name Database Searcher is not initialized"
});
}
aiNameSearcher.clearCache();
res.json({
success: true,
message: "AI searcher cache cleared successfully",
timestamp: new Date().toISOString()
});
} catch (error) {
console.error("❌ AI Search Clear Cache Error:", error);
res.status(500).json({
success: false,
error: "Internal server error clearing AI search cache",
message: error.message,
timestamp: new Date().toISOString()
});
}
});
// POST endpoint for AI-powered Greek name database search with MSSQL
app.post("/aiNameSearchMSSQL", async (req, res) => {
try {
const { firstName, lastName, options = {} } = req.body;
// Validation
if (!firstName && !lastName) {
console.log("❌ Validation Error: At least one name (first or last) must be provided");
return res.status(400).json({
success: false,
error: "At least one name (first or last) must be provided",
received: { firstName, lastName }
});
}
// Check if AI searcher is initialized
if (!aiNameSearcherMSSQL) {
console.log("❌ AI searcher not initialized");
return res.status(500).json({
success: false,
error: "AI Name Database Searcher with MSSQL is not initialized. Please try again in a moment."
});
}
console.log(`🤖 AI Name Search Request (MSSQL):`, {
firstName: firstName || "not provided",
lastName: lastName || "not provided",
options: options,
timestamp: new Date().toISOString()
});
// Perform AI-powered semantic search in MSSQL database
const searchResults = await aiNameSearcherMSSQL.searchNames(firstName || "", lastName || "", options);
// Log the result for debugging
console.log(`✅ AI Name Search Result (MSSQL):`, {
query: searchResults.query,
resultsFound: searchResults.results.length,
totalProcessed: searchResults.totalProcessed,
topMatch:
searchResults.results.length > 0
? {
name: searchResults.results[0].fullName,
similarity: searchResults.results[0].similarity
}
: null
});
// Return the result
res.json({
success: true,
data: searchResults,
timestamp: new Date().toISOString()
});
} catch (error) {
console.error("❌ AI Name Search Error (MSSQL):", error);
res.status(500).json({
success: false,
error: "Internal server error during AI name search in MSSQL database",
message: error.message,
timestamp: new Date().toISOString()
});
}
});
// POST endpoint for AI-powered partial name search with MSSQL
app.post("/aiPartialNameSearchMSSQL", async (req, res) => {
try {
const { partialName, options = {} } = req.body;
// Validation
if (!partialName || typeof partialName !== "string" || partialName.trim().length < 2) {
console.log("❌ Validation Error: partialName must be at least 2 characters long");
return res.status(400).json({
success: false,
error: "partialName must be at least 2 characters long",
received: { partialName, type: typeof partialName }
});
}
// Check if AI searcher is initialized
if (!aiNameSearcherMSSQL) {
console.log("❌ AI searcher not initialized");
return res.status(500).json({
success: false,
error: "AI Name Database Searcher with MSSQL is not initialized. Please try again in a moment."
});
}
console.log(`🔍 AI Partial Name Search Request (MSSQL):`, {
partialName: partialName,
options: options,
timestamp: new Date().toISOString()
});
// Perform AI-powered partial name search in MSSQL database
const searchResults = await aiNameSearcherMSSQL.searchPartialName(partialName, options);
// Log the result for debugging
console.log(`✅ AI Partial Name Search Result (MSSQL):`, {
query: searchResults.query,
resultsFound: searchResults.results.length,
totalProcessed: searchResults.totalProcessed,
topMatch:
searchResults.results.length > 0
? {
name: searchResults.results[0].fullName,
similarity: searchResults.results[0].similarity
}
: null
});
// Return the result
res.json({
success: true,
data: searchResults,
timestamp: new Date().toISOString()
});
} catch (error) {
console.error("❌ AI Partial Name Search Error (MSSQL):", error);
res.status(500).json({
success: false,
error: "Internal server error during AI partial name search in MSSQL database",
message: error.message,
timestamp: new Date().toISOString()
});
}
});
// GET endpoint for MSSQL database statistics
app.get("/aiSearchStatsMSSQL", async (req, res) => {
try {
if (!aiNameSearcherMSSQL) {
return res.status(500).json({
success: false,
error: "AI Name Database Searcher with MSSQL is not initialized"
});
}
const stats = aiNameSearcherMSSQL.getSearchStats();
const dbStats = await aiNameSearcherMSSQL.getDatabaseStats();
res.json({
success: true,
data: {
isInitialized: stats.isInitialized,
batchSize: stats.batchSize,
similarityThreshold: stats.similarityThreshold,
embeddingsCacheSize: stats.embeddingsCacheSize,
memoryUsage: {
heapUsed: Math.round(stats.memoryUsage.heapUsed / 1024 / 1024),
heapTotal: Math.round(stats.memoryUsage.heapTotal / 1024 / 1024),
external: Math.round(stats.memoryUsage.external / 1024 / 1024),