openclacky 1.5.26 → 1.5.27

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,485 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "json"
4
+ require "time"
5
+ require "fileutils"
6
+ require "date"
7
+ require_relative "store"
8
+
9
+ module Clacky
10
+ module Knowledge
11
+ # Question log behind the statistics page.
12
+ #
13
+ # One JSON line per question, appended to <root>/stats/YYYY-MM.jsonl, so the
14
+ # date filter is a file choice rather than a full scan: "today" opens one
15
+ # file, and a busy month is only a few MB.
16
+ #
17
+ # A row is grouped by its session: whatever the host calls that
18
+ # conversation ("微信 | 黄土标", a titled web session…) is what the panel
19
+ # shows, so the same code works for IM accounts and for web-only setups.
20
+ # Platform / account / sender ids ride along for the source tag only.
21
+ class Stats
22
+ QUESTION_MAX = 500
23
+
24
+ # Column order of a cached row. Arrays instead of hashes: a year of heavy
25
+ # use is ~300k rows, and hashes would hold ~4x the memory for the same data.
26
+ T = 0 # epoch seconds
27
+ Q = 1 # question text
28
+ SID = 2 # session id
29
+ SN = 3 # session name at the time of asking
30
+ SRC = 4 # "web" | "channel"
31
+ PF = 5 # platform (feishu / wecom / weixin / dingtalk / qq)
32
+ CI = 6 # channel instance id
33
+ U = 7 # sender id
34
+ N = 8 # number of hits
35
+ SC = 9 # best score
36
+ F = 10 # folder of the best hit
37
+ COLUMNS = 11
38
+
39
+ NO_THEME = "\u0000"
40
+ NO_SESSION = "-"
41
+
42
+ RANGE_DAYS = { "today" => 1, "week" => 7, "month" => 30, "all" => 0 }.freeze
43
+
44
+ # Above this many distinct questions only the most frequent ones take
45
+ # part in wording normalisation: the long tail can never reach the top-20
46
+ # or the gap list, and a full pairwise comparison would crawl.
47
+ MERGE_CANDIDATES = 300
48
+ MERGE_THRESHOLD = 0.75
49
+
50
+ @cache = {}
51
+ @mutex = Mutex.new
52
+
53
+ class << self
54
+ attr_reader :cache, :mutex
55
+
56
+ def reset_cache!
57
+ mutex.synchronize { cache.clear }
58
+ end
59
+ end
60
+
61
+ attr_reader :store
62
+
63
+ def initialize(store = nil)
64
+ @store = store || Clacky::Knowledge.store
65
+ end
66
+
67
+ # ── Writing ─────────────────────────────────────────────────────────
68
+
69
+ # Never raises: a failed log line must not affect an answer.
70
+ def record(question:, hits: [], session_id: nil, session_name: nil, channel_info: nil, now: Time.now)
71
+ q = question.to_s.strip
72
+ return if q.empty?
73
+
74
+ info = channel_info || {}
75
+ source = info[:platform].to_s.empty? ? "web" : "channel"
76
+ best = best_hit(hits)
77
+ row = [
78
+ now.to_i,
79
+ q[0, QUESTION_MAX],
80
+ session_id.to_s,
81
+ session_name.to_s[0, 80],
82
+ source,
83
+ source == "channel" ? info[:platform].to_s : "",
84
+ source == "channel" ? instance_id_of(info) : "",
85
+ source == "channel" ? info[:user_id].to_s : "",
86
+ Array(hits).size,
87
+ best ? best[:score].to_f.round(3) : 0.0,
88
+ best ? best[:folder].to_s : ""
89
+ ]
90
+ append(row, now)
91
+ row
92
+ end
93
+
94
+ # ── Reading ─────────────────────────────────────────────────────────
95
+
96
+ def report(days: 30, session: nil, theme: nil, now: Time.now)
97
+ window = window_for(days, now)
98
+ all = rows_between(window[:from], now)
99
+ labels = session_labels(all)
100
+
101
+ rows = all
102
+ rows = rows.select { |r| session_key(r) == session.to_s } unless no_filter?(session)
103
+ rows = rows.select { |r| theme_key(r) == theme_filter(theme) } unless no_filter?(theme)
104
+
105
+ {
106
+ range: { days: window[:days], from: iso(Time.at(window[:from].to_i)), to: iso(now) },
107
+ kpi: kpi(rows),
108
+ trend: trend(rows, window, now),
109
+ themes: themes(rows),
110
+ top: top_questions(rows),
111
+ gaps: gaps(rows),
112
+ hours: hours(rows),
113
+ sessions: sessions(rows, labels),
114
+ filters: {
115
+ sessions: session_options(all, labels),
116
+ themes: theme_options(all)
117
+ }
118
+ }
119
+ end
120
+
121
+ # ── Files ───────────────────────────────────────────────────────────
122
+
123
+ private def append(row, now)
124
+ FileUtils.mkdir_p(store.stats_dir)
125
+ File.open(store.stats_path(now), "a:UTF-8") do |f|
126
+ f.write("#{JSON.generate(row)}\n")
127
+ end
128
+ rescue StandardError => e
129
+ Clacky::Logger.warn("knowledge.stats_write_failed", error: e) if defined?(Clacky::Logger)
130
+ nil
131
+ end
132
+
133
+ private def rows_between(from, to)
134
+ months(from, to).flat_map { |path| load_month(path) }.select do |r|
135
+ t = r[T].to_i
136
+ t >= from.to_i && t <= to.to_i
137
+ end
138
+ end
139
+
140
+ # Only the month files covering the range; a single day never reads more
141
+ # than the current month.
142
+ private def months(from, to)
143
+ first = Time.at(from.to_i)
144
+ last = Time.at(to.to_i)
145
+ cursor = Date.new(first.year, first.month, 1)
146
+ stop = Date.new(last.year, last.month, 1)
147
+ out = []
148
+ while cursor <= stop
149
+ path = store.stats_path(Time.new(cursor.year, cursor.month, 1))
150
+ out << path if File.file?(path)
151
+ cursor >>= 1
152
+ end
153
+ out
154
+ end
155
+
156
+ private def load_month(path)
157
+ stat = File.stat(path)
158
+ signature = [stat.mtime.to_f, stat.size]
159
+ cached = self.class.mutex.synchronize { self.class.cache[path] }
160
+ return cached[:rows] if cached && cached[:signature] == signature
161
+
162
+ rows = []
163
+ File.foreach(path, encoding: "UTF-8") do |line|
164
+ row = begin
165
+ JSON.parse(line)
166
+ rescue JSON::ParserError
167
+ nil
168
+ end
169
+ next unless row.is_a?(Array) && row.size == COLUMNS
170
+
171
+ rows << row
172
+ end
173
+ self.class.mutex.synchronize { self.class.cache[path] = { signature: signature, rows: rows } }
174
+ rows
175
+ rescue SystemCallError
176
+ []
177
+ end
178
+
179
+ private def window_for(days, now)
180
+ count = if days.is_a?(String) && days =~ /\A\d+\z/
181
+ days.to_i
182
+ elsif days.is_a?(String)
183
+ RANGE_DAYS[days] || 30
184
+ else
185
+ days.to_i
186
+ end
187
+ if count <= 0
188
+ { days: 0, from: [earliest_record_time(now), now - (365 * 86_400)].max }
189
+ else
190
+ { days: count, from: Time.at(now.to_i - ((count - 1) * 86_400)).to_date.to_time }
191
+ end
192
+ end
193
+
194
+ private def earliest_record_time(now)
195
+ first = Dir.glob(File.join(store.stats_dir, "*.jsonl")).sort.first
196
+ return now - (365 * 86_400) unless first
197
+
198
+ stamp = File.basename(first, ".jsonl")
199
+ Time.strptime("#{stamp}-01", "%Y-%m-%d")
200
+ rescue ArgumentError
201
+ now - (365 * 86_400)
202
+ end
203
+
204
+ # ── Aggregation ─────────────────────────────────────────────────────
205
+
206
+ private def kpi(rows)
207
+ total = rows.size
208
+ hit = rows.count { |r| r[N].to_i.positive? }
209
+ {
210
+ total: total,
211
+ sessions: rows.map { |r| session_key(r) }.uniq.size,
212
+ hit: hit,
213
+ hit_rate: total.zero? ? 0.0 : (hit.to_f / total).round(4),
214
+ gaps: rows.count { |r| r[N].to_i.zero? }
215
+ }
216
+ end
217
+
218
+ private def trend(rows, window, now)
219
+ span = (now.to_i - window[:from].to_i) / 86_400
220
+ bucket = if span <= 31 then :day
221
+ elsif span <= 180 then :week
222
+ else :month
223
+ end
224
+ counts = Hash.new(0)
225
+ rows.each { |r| counts[bucket_key(bucket, Time.at(r[T].to_i))] += 1 }
226
+ # Empty buckets stay in the series: a quiet day has to read as a dip,
227
+ # not as a chart whose whole width is one bar. A filter that matched
228
+ # nothing keeps the empty list so the block can say so in words.
229
+ keys = rows.empty? ? [] : bucket_keys(bucket, Time.at(window[:from].to_i), now)
230
+ { bucket: bucket.to_s, buckets: keys.map { |k| { key: k, count: counts[k] } } }
231
+ end
232
+
233
+ private def bucket_key(bucket, time)
234
+ case bucket
235
+ when :day then time.strftime("%Y-%m-%d")
236
+ when :week then monday(time).strftime("%Y-%m-%d")
237
+ else time.strftime("%Y-%m")
238
+ end
239
+ end
240
+
241
+ private def bucket_keys(bucket, from, now)
242
+ keys = []
243
+ cursor = case bucket
244
+ when :day then from.to_date
245
+ when :week then monday(from)
246
+ else Date.new(from.year, from.month, 1)
247
+ end
248
+ last = case bucket
249
+ when :day then now.to_date
250
+ when :week then monday(now)
251
+ else Date.new(now.year, now.month, 1)
252
+ end
253
+ while cursor <= last
254
+ keys << (bucket == :month ? cursor.strftime("%Y-%m") : cursor.strftime("%Y-%m-%d"))
255
+ cursor = case bucket
256
+ when :day then cursor + 1
257
+ when :week then cursor + 7
258
+ else cursor >> 1
259
+ end
260
+ end
261
+ keys
262
+ end
263
+
264
+ private def themes(rows)
265
+ counts = Hash.new(0)
266
+ rows.each { |r| counts[theme_key(r)] += 1 }
267
+ total = rows.size
268
+ counts.sort_by { |k, v| [-v, k] }.map do |key, count|
269
+ { key: key == NO_THEME ? nil : key, count: count, share: total.zero? ? 0.0 : (count.to_f / total).round(4) }
270
+ end
271
+ end
272
+
273
+ private def top_questions(rows)
274
+ clusters(rows).first(20).map do |c|
275
+ { q: c[:q], count: c[:count], theme: c[:theme] == NO_THEME ? nil : c[:theme], last: iso(Time.at(c[:last])) }
276
+ end
277
+ end
278
+
279
+ private def gaps(rows)
280
+ clusters(rows.select { |r| r[N].to_i.zero? }).first(50).map do |c|
281
+ { q: c[:q], count: c[:count], last: iso(Time.at(c[:last])) }
282
+ end
283
+ end
284
+
285
+ private def hours(rows)
286
+ counts = Array.new(24, 0)
287
+ rows.each { |r| counts[Time.at(r[T].to_i).hour] += 1 }
288
+ peak = counts.each_with_index.max_by { |v, i| [v, -i] }
289
+ { buckets: counts.each_with_index.map { |v, i| { hour: i, count: v } }, peak: peak && peak[0].positive? ? peak[1] : nil }
290
+ end
291
+
292
+ # session id → label, taken from the newest row that still knows the name;
293
+ # a session never renamed falls back to its first question.
294
+ private def session_labels(rows)
295
+ names = {}
296
+ first_q = {}
297
+ first_t = {}
298
+ rows.each do |r|
299
+ sid = session_key(r)
300
+ name = r[SN].to_s.strip
301
+ names[sid] = { t: r[T].to_i, name: name } if !name.empty? && (names[sid].nil? || r[T].to_i >= names[sid][:t])
302
+ if first_t[sid].nil? || r[T].to_i < first_t[sid]
303
+ first_t[sid] = r[T].to_i
304
+ first_q[sid] = r[Q].to_s
305
+ end
306
+ end
307
+ labels = {}
308
+ names.each { |sid, v| labels[sid] = v[:name] }
309
+ first_q.each { |sid, q| labels[sid] ||= q[0, 24] }
310
+ labels
311
+ end
312
+
313
+ private def sessions(rows, labels)
314
+ grouped = Hash.new { |h, k| h[k] = { count: 0, days: {}, last: 0, src: "web", pf: "" } }
315
+ rows.each do |r|
316
+ g = grouped[session_key(r)]
317
+ g[:count] += 1
318
+ g[:days][Time.at(r[T].to_i).strftime("%Y-%m-%d")] = true
319
+ g[:last] = [g[:last], r[T].to_i].max
320
+ g[:src] = r[SRC].to_s
321
+ g[:pf] = r[PF].to_s
322
+ end
323
+ grouped.map do |key, g|
324
+ { key: key, name: labels[key] || default_label(key), src: g[:src], platform: g[:pf],
325
+ count: g[:count], days: g[:days].size, last: iso(Time.at(g[:last])) }
326
+ end.sort_by { |g| [-g[:count], g[:name]] }
327
+ end
328
+
329
+ private def session_options(rows, labels)
330
+ sessions(rows, labels).map { |s| { key: s[:key], name: s[:name], count: s[:count] } }
331
+ end
332
+
333
+ private def theme_options(rows)
334
+ themes(rows).map { |t| { key: t[:key] || NO_THEME, name: t[:key], count: t[:count] } }
335
+ end
336
+
337
+ private def default_label(key)
338
+ key == NO_SESSION ? "—" : key[0, 8]
339
+ end
340
+
341
+ private def session_key(row)
342
+ sid = row[SID].to_s
343
+ sid.empty? ? NO_SESSION : sid
344
+ end
345
+
346
+ private def theme_key(row)
347
+ folder = row[F].to_s
348
+ return NO_THEME if row[N].to_i.zero? || folder.empty?
349
+
350
+ folder.split("/").first
351
+ end
352
+
353
+ private def theme_filter(theme)
354
+ value = theme.to_s
355
+ value == NO_THEME || value == "unmatched" ? NO_THEME : value
356
+ end
357
+
358
+ private def best_hit(hits)
359
+ list = Array(hits)
360
+ return nil if list.empty?
361
+
362
+ list.max_by { |h| h[:score].to_f }
363
+ end
364
+
365
+ private def instance_id_of(info)
366
+ raw = info[:channel_instance_id].to_s
367
+ raw.empty? ? "default" : raw
368
+ end
369
+
370
+ # Not String#strip-based: the "no match" sentinel is a NUL byte, which
371
+ # strip would eat, silently dropping the filter.
372
+ private def no_filter?(value)
373
+ value.nil? || value.to_s.empty?
374
+ end
375
+
376
+ private def iso(time)
377
+ time.getlocal.iso8601
378
+ end
379
+
380
+ private def monday(time)
381
+ date = time.to_date
382
+ date - (date.wday.zero? ? 6 : date.wday - 1)
383
+ end
384
+
385
+ # ── Wording normalisation ───────────────────────────────────────────
386
+ # "门票多少钱" / "门票多少钱?" / "门票多少" are one row: punctuation,
387
+ # polite lead-ins and trailing particles are stripped, then near
388
+ # duplicates are merged by character-bigram Jaccard similarity. Local and
389
+ # deterministic — no model call.
390
+
391
+ PUNCT = /[\s[:punct:]、。,!?;:""''‘’“”()【】《》〈〉…—~·「」『』]/.freeze
392
+ LEAD_IN = /\A(?:请问|想请问|我想问一下|我想问|想问一下|想问下|想问|问一下|问下|你好|您好|打扰一下|麻烦问一下|麻烦问下)[,,。\s]*/.freeze
393
+ TAIL = /(?:吗|呢|呀|啊|吧|哈|嘛|哦|喔|谢谢|多谢)+\z/.freeze
394
+
395
+ def normalize(text)
396
+ s = text.to_s.downcase.gsub(PUNCT, "")
397
+ s = s.sub(LEAD_IN, "")
398
+ s = s.sub(TAIL, "")
399
+ s.strip.empty? ? text.to_s.strip : s
400
+ end
401
+
402
+ # [{q:, count:, last:, theme:}] — most frequent first.
403
+ # The key is the normalised wording; the label shown is the wording people
404
+ # actually typed (most used, shortest on a tie), so "有讲解吗" never turns
405
+ # into "有讲解" in the list.
406
+ private def clusters(rows)
407
+ grouped = Hash.new { |h, k| h[k] = { key: k, raws: Hash.new(0), count: 0, last: 0, themes: Hash.new(0) } }
408
+ rows.each do |r|
409
+ c = grouped[normalize(r[Q])]
410
+ c[:raws][r[Q].to_s] += 1
411
+ c[:count] += 1
412
+ c[:last] = [c[:last], r[T].to_i].max
413
+ c[:themes][theme_key(r)] += 1
414
+ end
415
+ merged = merge_similar(grouped.values)
416
+ merged.each do |c|
417
+ c[:q] = pick_label(c[:raws])
418
+ c[:theme] = c[:themes].max_by { |k, v| [v, k == NO_THEME ? 0 : 1] }&.first || NO_THEME
419
+ c.delete(:themes)
420
+ c.delete(:raws)
421
+ c.delete(:key)
422
+ end
423
+ merged.sort_by { |c| [-c[:count], c[:q]] }
424
+ end
425
+
426
+ private def pick_label(raws)
427
+ best = raws.max_by { |text, count| [count, -text.length] }
428
+ best ? best.first : ""
429
+ end
430
+
431
+ private def merge_similar(items)
432
+ items = items.sort_by { |i| [-i[:count], i[:key]] }
433
+ head = items.first(MERGE_CANDIDATES)
434
+ tail = items.drop(MERGE_CANDIDATES)
435
+ return items if head.size < 2
436
+
437
+ grams = head.map { |i| bigrams(i[:key]) }
438
+ parent = (0...head.size).to_a
439
+ find = lambda do |i|
440
+ i = parent[i] while parent[i] != i
441
+ i
442
+ end
443
+ head.each_with_index do |a, i|
444
+ ((i + 1)...head.size).each do |j|
445
+ next if (a[:key].length - head[j][:key].length).abs > 3
446
+ next unless similar_grams?(grams[i], grams[j])
447
+
448
+ ri = find.call(i)
449
+ rj = find.call(j)
450
+ parent[rj] = ri unless ri == rj
451
+ end
452
+ end
453
+
454
+ buckets = Hash.new { |h, k| h[k] = [] }
455
+ head.each_with_index { |item, i| buckets[find.call(i)] << item }
456
+ tail + buckets.values.map do |members|
457
+ raws = Hash.new(0)
458
+ themes = Hash.new(0)
459
+ members.each do |m|
460
+ m[:raws].each { |text, n| raws[text] += n }
461
+ m[:themes].each { |k, v| themes[k] += v }
462
+ end
463
+ { key: members.first[:key], raws: raws, count: members.reduce(0) { |acc, m| acc + m[:count] },
464
+ last: members.map { |m| m[:last] }.max, themes: themes }
465
+ end
466
+ end
467
+
468
+ private def bigrams(text)
469
+ chars = text.to_s.chars
470
+ return [text.to_s] if chars.size < 2
471
+
472
+ chars.each_cons(2).map { |a, b| "#{a}#{b}" }.uniq
473
+ end
474
+
475
+ private def similar_grams?(a, b)
476
+ return true if a == b
477
+
478
+ inter = (a & b).size
479
+ return false if inter.zero?
480
+
481
+ inter.to_f / (a.size + b.size - inter) >= MERGE_THRESHOLD
482
+ end
483
+ end
484
+ end
485
+ end
@@ -37,6 +37,17 @@ module Clacky
37
37
  File.join(@root, "entries")
38
38
  end
39
39
 
40
+ # Question log for the statistics page, one file per month. Kept out of
41
+ # entries/ so it is never indexed as a document, and so a monthly file
42
+ # stays small enough to parse in milliseconds.
43
+ def stats_dir
44
+ File.join(@root, "stats")
45
+ end
46
+
47
+ def stats_path(time = Time.now)
48
+ File.join(stats_dir, "#{time.strftime('%Y-%m')}.jsonl")
49
+ end
50
+
40
51
  def config
41
52
  return {} unless File.file?(config_path)
42
53
  data = YAML.safe_load(File.read(config_path, encoding: "UTF-8"), permitted_classes: [Date, Time])
@@ -75,6 +86,40 @@ module Clacky
75
86
  entry_paths.map { |path| load_entry(path) }
76
87
  end
77
88
 
89
+ # ── Recall test case list ──────────────────────────────────────────
90
+ # Questions the owner re-runs after editing documents. Kept beside
91
+ # kb.yml rather than inside entries/ so it is never indexed as a
92
+ # document, and so it travels with the knowledge folder (backups too).
93
+ MAX_CASES = 100
94
+ MAX_CASE_CHARS = 300
95
+
96
+ def cases_path
97
+ File.join(@root, "recall_cases.json")
98
+ end
99
+
100
+ def recall_cases
101
+ return [] unless File.file?(cases_path)
102
+
103
+ data = JSON.parse(File.read(cases_path, encoding: "UTF-8"))
104
+ data = data["cases"] if data.is_a?(Hash)
105
+ return [] unless data.is_a?(Array)
106
+
107
+ clean_cases(data)
108
+ rescue JSON::ParserError, SystemCallError
109
+ []
110
+ end
111
+
112
+ def save_recall_cases(list)
113
+ cleaned = clean_cases(list)
114
+ FileUtils.mkdir_p(@root)
115
+ File.write(cases_path, JSON.pretty_generate(cleaned))
116
+ cleaned
117
+ end
118
+
119
+ private def clean_cases(list)
120
+ Array(list).map { |q| q.to_s.strip[0, MAX_CASE_CHARS] }.reject(&:empty?).uniq.first(MAX_CASES)
121
+ end
122
+
78
123
  def find(id)
79
124
  entries.find { |e| e.id == id.to_s }
80
125
  end