-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathalgorithm.go
More file actions
252 lines (233 loc) · 6.76 KB
/
algorithm.go
File metadata and controls
252 lines (233 loc) · 6.76 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
// Package compress implements the prompt-compression algorithm
// ported natively to Go. Source: JuliusBrussee/prompt-compression (MIT).
//
// Algorithm overview:
//
// 1. Split input into segments (sentences, preserving code/URLs).
// 2. Per segment, run the auto-clarity check: segments containing
// security/destructive keywords are passed through verbatim.
// 3. For safe segments, apply the dictionary (eng/v1) first
// (longest-match-first phrase substitutions).
// 4. Then apply the drop-list for the chosen intensity level
// (Lite/Full/Ultra).
// 5. Re-join segments, preserving original whitespace.
package compress
import (
"strings"
)
// CompressResult reports what the compression did to the input.
type CompressResult struct {
// Original is the input verbatim.
Original string
// Compressed is the rewritten text.
Compressed string
// Stats for the operation.
Stats Stats
}
// Stats reports per-stage counts.
type Stats struct {
Intensity Intensity
OriginalBytes int
CompressedBytes int
OriginalWords int
CompressedWords int
BytesSaved int
PercentOff float64
DroppedArticles int
DroppedFiller int
DroppedHedge int
DroppedConjunctions int
DictionaryHits int
PassThroughSegments int
CompressedSegments int
BytesSavedByDict int
BytesSavedByDrops int
RefusedDueToSensitive bool
// Per-segment counts (informational; first N at most).
SensitiveKeywordsHit []string
}
// Compress applies the algorithm to s at the given intensity.
//
// Behavior:
// - Empty input returns (input, empty result) untouched.
// - CJK-heavy text is passed through (compression rules assume Latin grammar).
// - Sensitive segments (security/destructive keywords) are preserved
// verbatim regardless of intensity.
// - Multi-word drop-list entries ("of course", "feel free") are matched
// as whole phrases.
// - Dictionary substitutions are case-insensitive and preserve the
// case of the first character of each match.
func Compress(s string, intensity Intensity) (string, Stats) {
stats := Stats{Intensity: intensity, OriginalBytes: len(s), OriginalWords: wordCount(s)}
if s == "" {
return s, stats
}
if isCJK(s) {
// CJK has no articles/filler; pass through.
stats.CompressedBytes = len(s)
stats.CompressedWords = stats.OriginalWords
stats.PercentOff = 0
return s, stats
}
// Split into segments, classify safe vs. pass-through.
segs := SplitSafeSegments(s)
// Build the output and per-stage counters.
var out strings.Builder
dropSet := dropLists[intensity]
for _, seg := range segs {
if !seg.Safe {
stats.PassThroughSegments++
stats.SensitiveKeywordsHit = append(stats.SensitiveKeywordsHit, detectSensitive(seg.Text))
out.WriteString(seg.Text)
continue
}
stats.CompressedSegments++
// 1. Dictionary substitutions
preDict := seg.Text
postDict := SubstituteDict(seg.Text)
stats.BytesSavedByDict += len(preDict) - len(postDict)
if postDict != preDict {
stats.DictionaryHits++
}
// 2. Drop-list application
postDrops := applyDropList(postDict, dropSet, &stats)
stats.BytesSavedByDrops += len(postDict) - len(postDrops)
out.WriteString(postDrops)
}
compressed := out.String()
stats.CompressedBytes = len(compressed)
stats.CompressedWords = wordCount(compressed)
stats.BytesSaved = stats.OriginalBytes - stats.CompressedBytes
if stats.OriginalBytes > 0 {
stats.PercentOff = float64(stats.BytesSaved) / float64(stats.OriginalBytes) * 100
}
return compressed, stats
}
// applyDropList removes all words/phrases in dropSet from s.
// Counts are tallied per category (article, filler, hedge, conjunction).
// Whitespace is normalized but not destroyed: a doubled space becomes
// a single space, leading/trailing spaces on a segment are preserved.
func applyDropList(s string, dropSet map[string]bool, stats *Stats) string {
if len(dropSet) == 0 {
return s
}
// Sort by length desc so multi-word phrases match first.
phrases := make([]string, 0, len(dropSet))
for k := range dropSet {
phrases = append(phrases, k)
}
sortByLengthDesc(phrases)
out := s
for _, p := range phrases {
before := out
out = removePhraseCI(out, p)
if out != before {
classifyDrop(p, stats)
}
}
return normalizeWhitespace(out)
}
func classifyDrop(phrase string, stats *Stats) {
lower := strings.ToLower(phrase)
switch {
case lower == "a" || lower == "an" || lower == "the":
stats.DroppedArticles++
case isHedge(lower):
stats.DroppedHedge++
case isConjunction(lower):
stats.DroppedConjunctions++
default:
stats.DroppedFiller++
}
}
func isHedge(p string) bool {
switch p {
case "perhaps", "maybe", "i think", "i believe", "in my opinion",
"it seems", "it appears", "somewhat", "kind of", "sort of":
return true
}
return false
}
func isConjunction(p string) bool {
switch p {
case "however", "moreover", "furthermore", "nevertheless", "nonetheless",
"therefore", "thus", "hence", "accordingly", "consequently",
"additionally", "alternatively", "likewise", "similarly",
"subsequently", "previously":
return true
}
return false
}
// removePhraseCI removes all case-insensitive occurrences of needle from s.
// Removes the trailing whitespace if present (to avoid "word word").
// Does NOT remove leading whitespace (to preserve word boundaries).
func removePhraseCI(s, needle string) string {
if needle == "" {
return s
}
lowerS := toLowerASCII(s)
lowerN := toLowerASCII(needle)
if len(lowerN) > len(lowerS) {
return s
}
var out []byte
i := 0
for i < len(s) {
if i+len(lowerN) <= len(lowerS) && lowerS[i:i+len(lowerN)] == lowerN {
// Word boundary checks
if i > 0 && isWordByte(s[i-1]) {
out = append(out, s[i])
i++
continue
}
if i+len(lowerN) < len(s) && isWordByte(s[i+len(lowerN)]) {
out = append(out, s[i])
i++
continue
}
// Skip the phrase
i += len(lowerN)
// Also skip one trailing space if present
if i < len(s) && s[i] == ' ' {
i++
}
} else {
out = append(out, s[i])
i++
}
}
return string(out)
}
// normalizeWhitespace collapses runs of spaces and trims segment
// boundaries, but preserves newlines.
func normalizeWhitespace(s string) string {
var out []byte
prevSpace := false
for i := 0; i < len(s); i++ {
c := s[i]
if c == ' ' || c == '\t' {
if !prevSpace {
out = append(out, ' ')
}
prevSpace = true
continue
}
prevSpace = false
out = append(out, c)
}
return string(out)
}
func wordCount(s string) int {
return len(strings.Fields(s))
}
// detectSensitive returns the first safety keyword found in s (lower-case).
// Returns empty if none.
func detectSensitive(s string) string {
lower := strings.ToLower(s)
for _, kw := range safetyKeywords {
if strings.Contains(lower, kw) {
return kw
}
}
return ""
}