forked from Prompt-Hash-Stellar/prompt-hash
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsimilarityDetection.ts
More file actions
185 lines (156 loc) · 5.41 KB
/
Copy pathsimilarityDetection.ts
File metadata and controls
185 lines (156 loc) · 5.41 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
/**
* Anti-Plagiarism / Similarity Detection Service (Issue #133)
*
* Detects when a newly indexed prompt is too similar to existing ones.
* Uses TF-IDF cosine similarity for general content and Levenshtein ratio
* for very short texts (< 50 chars).
*
* Thresholds:
* score >= 0.90 → "highly_similar" (flag for moderation)
* score >= 0.70 → "suspicious"
* score < 0.70 → "clean"
*/
import Prompt from "../models/Prompt";
// ---------------------------------------------------------------------------
// Text preprocessing
// ---------------------------------------------------------------------------
function tokenize(text: string): string[] {
return text
.toLowerCase()
.replace(/[^a-z0-9\s]/g, " ")
.split(/\s+/)
.filter(Boolean);
}
function buildTermFrequency(tokens: string[]): Map<string, number> {
const tf = new Map<string, number>();
for (const token of tokens) {
tf.set(token, (tf.get(token) ?? 0) + 1);
}
// Normalize by document length
for (const [term, count] of tf) {
tf.set(term, count / tokens.length);
}
return tf;
}
// ---------------------------------------------------------------------------
// Cosine similarity on TF vectors
// ---------------------------------------------------------------------------
export function cosineSimilarity(a: Map<string, number>, b: Map<string, number>): number {
let dot = 0;
let normA = 0;
let normB = 0;
for (const [term, tfA] of a) {
normA += tfA * tfA;
const tfB = b.get(term) ?? 0;
dot += tfA * tfB;
}
for (const [, tfB] of b) {
normB += tfB * tfB;
}
const denom = Math.sqrt(normA) * Math.sqrt(normB);
return denom === 0 ? 0 : dot / denom;
}
// ---------------------------------------------------------------------------
// Levenshtein distance (for short texts)
// ---------------------------------------------------------------------------
export function levenshteinRatio(a: string, b: string): number {
const m = a.length;
const n = b.length;
const dp: number[][] = Array.from({ length: m + 1 }, (_, i) =>
Array.from({ length: n + 1 }, (_, j) => (i === 0 ? j : j === 0 ? i : 0)),
);
for (let i = 1; i <= m; i++) {
for (let j = 1; j <= n; j++) {
if (a[i - 1] === b[j - 1]) {
dp[i][j] = dp[i - 1][j - 1];
} else {
dp[i][j] = 1 + Math.min(dp[i - 1][j], dp[i][j - 1], dp[i - 1][j - 1]);
}
}
}
const distance = dp[m][n];
const maxLen = Math.max(m, n);
return maxLen === 0 ? 1 : 1 - distance / maxLen;
}
// ---------------------------------------------------------------------------
// Score computation
// ---------------------------------------------------------------------------
export function computeSimilarityScore(textA: string, textB: string): number {
const norm = (s: string) => s.toLowerCase().trim();
const a = norm(textA);
const b = norm(textB);
if (a.length < 50 || b.length < 50) {
return levenshteinRatio(a, b);
}
const tokensA = tokenize(a);
const tokensB = tokenize(b);
const tfA = buildTermFrequency(tokensA);
const tfB = buildTermFrequency(tokensB);
return cosineSimilarity(tfA, tfB);
}
// ---------------------------------------------------------------------------
// Thresholds
// ---------------------------------------------------------------------------
export const SIMILARITY_THRESHOLDS = {
HIGHLY_SIMILAR: 0.9,
SUSPICIOUS: 0.7,
} as const;
export type SimilarityFlag = "clean" | "suspicious" | "highly_similar";
export function classifyScore(score: number): SimilarityFlag {
if (score >= SIMILARITY_THRESHOLDS.HIGHLY_SIMILAR) return "highly_similar";
if (score >= SIMILARITY_THRESHOLDS.SUSPICIOUS) return "suspicious";
return "clean";
}
// ---------------------------------------------------------------------------
// Main scan function: called after a new prompt is indexed
// ---------------------------------------------------------------------------
export interface SimilarityResult {
flag: SimilarityFlag;
score: number;
similarTo: string | null;
}
/**
* Scan a newly indexed prompt against all existing active prompts.
* Updates the Prompt document with the result and returns the result.
*
* @param onChainId The on-chain ID of the newly created prompt.
* @param content The prompt text to compare (title + body combined).
*/
export async function scanForSimilarity(
onChainId: string,
content: string,
): Promise<SimilarityResult> {
const existing = await Prompt.find(
{ onChainId: { $ne: onChainId } },
{ onChainId: 1, content: 1, title: 1 },
).lean();
let maxScore = 0;
let mostSimilarId: string | null = null;
for (const prompt of existing) {
const candidateText = `${prompt.title ?? ""} ${prompt.content ?? ""}`;
const score = computeSimilarityScore(content, candidateText);
if (score > maxScore) {
maxScore = score;
mostSimilarId = prompt.onChainId ?? null;
}
}
const flag = classifyScore(maxScore);
await Prompt.findOneAndUpdate(
{ onChainId },
{
$set: {
similarityFlag: flag,
similarityScore: maxScore,
similarTo: flag !== "clean" ? mostSimilarId : null,
similarityCheckedAt: new Date(),
},
},
);
if (flag !== "clean") {
console.warn(
`[similarity] Prompt ${onChainId} flagged as "${flag}" ` +
`(score=${maxScore.toFixed(3)}, similar to ${mostSimilarId})`,
);
}
return { flag, score: maxScore, similarTo: flag !== "clean" ? mostSimilarId : null };
}