* spam-stat.el (spam-stat-reduce-size): Set spam-stat-dirty.
[gnus] / lisp / spam-stat.el
1 ;;; spam-stat.el --- detecting spam based on statistics
2
3 ;; Copyright (C) 2002, 2003 Free Software Foundation, Inc.
4
5 ;; Author: Alex Schroeder <alex@gnu.org>
6 ;; Keywords: network
7 ;; URL: http://www.emacswiki.org/cgi-bin/wiki.pl?SpamStat
8
9 ;; This file is part of GNU Emacs.
10
11 ;; This is free software; you can redistribute it and/or modify it
12 ;; under the terms of the GNU General Public License as published by
13 ;; the Free Software Foundation; either version 2, or (at your option)
14 ;; any later version.
15
16 ;; This is distributed in the hope that it will be useful, but WITHOUT
17 ;; ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
18 ;; or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public
19 ;; License for more details.
20
21 ;; You should have received a copy of the GNU General Public License
22 ;; along with GNU Emacs; see the file COPYING.  If not, write to the
23 ;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
24 ;; Boston, MA 02111-1307, USA.
25
26 ;;; Commentary:
27
28 ;; This implements spam analysis according to Paul Graham in "A Plan
29 ;; for Spam".  The basis for all this is a statistical distribution of
30 ;; words for your spam and non-spam mails.  We need this information
31 ;; in a hash-table so that the analysis can use the information when
32 ;; looking at your mails.  Therefore, before you begin, you need tons
33 ;; of mails (Graham uses 4000 non-spam and 4000 spam mails for his
34 ;; experiments).
35 ;;
36 ;; The main interface to using spam-stat, are the following functions:
37 ;;
38 ;; `spam-stat-buffer-is-spam' -- called in a buffer, that buffer is
39 ;; considered to be a new spam mail; use this for new mail that has
40 ;; not been processed before
41 ;;
42 ;; `spam-stat-buffer-is-non-spam' -- called in a buffer, that buffer
43 ;; is considered to be a new non-spam mail; use this for new mail that
44 ;; has not been processed before
45 ;;
46 ;; `spam-stat-buffer-change-to-spam' -- called in a buffer, that
47 ;; buffer is no longer considered to be normal mail but spam; use this
48 ;; to change the status of a mail that has already been processed as
49 ;; non-spam
50 ;;
51 ;; `spam-stat-buffer-change-to-non-spam' -- called in a buffer, that
52 ;; buffer is no longer considered to be spam but normal mail; use this
53 ;; to change the status of a mail that has already been processed as
54 ;; spam
55 ;;
56 ;; `spam-stat-save' -- save the hash table to the file; the filename
57 ;; used is stored in the variable `spam-stat-file'
58 ;;
59 ;; `spam-stat-load' -- load the hash table from a file; the filename
60 ;; used is stored in the variable `spam-stat-file'
61 ;;
62 ;; `spam-stat-score-word' -- return the spam score for a word
63 ;;
64 ;; `spam-stat-score-buffer' -- return the spam score for a buffer
65 ;;
66 ;; `spam-stat-split-fancy' -- for fancy mail splitting; add
67 ;; the rule (: spam-stat-split-fancy) to `nnmail-split-fancy'
68 ;;
69 ;; This requires the following in your ~/.gnus file:
70 ;;
71 ;; (require 'spam-stat)
72 ;; (spam-stat-load)
73
74 ;;; Testing:
75
76 ;; Typical test will involve calls to the following functions:
77 ;;
78 ;; Reset: (spam-stat-reset)
79 ;; Learn spam: (spam-stat-process-spam-directory "~/Mail/mail/spam")
80 ;; Learn non-spam: (spam-stat-process-non-spam-directory "~/Mail/mail/misc")
81 ;; Save table: (spam-stat-save)
82 ;; File size: (nth 7 (file-attributes spam-stat-file))
83 ;; Number of words: (hash-table-count spam-stat)
84 ;; Test spam: (spam-stat-test-directory "~/Mail/mail/spam")
85 ;; Test non-spam: (spam-stat-test-directory "~/Mail/mail/misc")
86 ;; Reduce table size: (spam-stat-reduce-size)
87 ;; Save table: (spam-stat-save)
88 ;; File size: (nth 7 (file-attributes spam-stat-file))
89 ;; Number of words: (hash-table-count spam-stat)
90 ;; Test spam: (spam-stat-test-directory "~/Mail/mail/spam")
91 ;; Test non-spam: (spam-stat-test-directory "~/Mail/mail/misc")
92
93 ;;; Dictionary Creation:
94
95 ;; Typically, you will filter away mailing lists etc. using specific
96 ;; rules in `nnmail-split-fancy'.  Somewhere among these rules, you
97 ;; will filter spam.  Here is how you would create your dictionary:
98
99 ;; Reset: (spam-stat-reset)
100 ;; Learn spam: (spam-stat-process-spam-directory "~/Mail/mail/spam")
101 ;; Learn non-spam: (spam-stat-process-non-spam-directory "~/Mail/mail/misc")
102 ;; Repeat for any other non-spam group you need...
103 ;; Reduce table size: (spam-stat-reduce-size)
104 ;; Save table: (spam-stat-save)
105
106 ;;; Todo:
107
108 ;; Speed it up.  Integrate with Gnus such that it uses spam and expiry
109 ;; marks to call the appropriate functions when leaving the summary
110 ;; buffer and saves the hash table when leaving Gnus.  More testing:
111 ;; More mails, disabling SpamAssassin, double checking algorithm, find
112 ;; improved algorithm.
113
114 ;;; Thanks:
115
116 ;; Ted Zlatanov <tzz@lifelogs.com>
117 ;; Jesper Harder <harder@myrealbox.com>
118 ;; Dan Schmidt <dfan@dfan.org>
119 ;; Lasse Rasinen <lrasinen@iki.fi>
120 ;; Milan Zamazal <pdm@zamazal.org>
121
122 \f
123
124 ;;; Code:
125 (require 'mail-parse)
126
127 (defgroup spam-stat nil
128   "Statistical spam detection for Emacs.
129 Use the functions to build a dictionary of words and their statistical
130 distribution in spam and non-spam mails.  Then use a function to determine
131 whether a buffer contains spam or not."
132   :group 'gnus)
133
134 (defcustom spam-stat-file "~/.spam-stat.el"
135   "File used to save and load the dictionary.
136 See `spam-stat-to-hash-table' for the format of the file."
137   :type 'file
138   :group 'spam-stat)
139
140 (defcustom spam-stat-install-hooks t
141   "Whether spam-stat should install its hooks in Gnus.
142 This is set to nil if you use spam-stat through spam.el."
143   :type 'boolean
144   :group 'spam-stat)
145
146 (defcustom spam-stat-unknown-word-score 0.2
147   "The score to use for unknown words.
148 Also used for words that don't appear often enough."
149   :type 'number
150   :group 'spam-stat)
151
152 (defcustom spam-stat-max-word-length 15
153   "Only words shorter than this will be considered."
154   :type 'integer
155   :group 'spam-stat)
156
157 (defcustom spam-stat-max-buffer-length 10240
158   "Only the beginning of buffers will be analyzed.
159 This variable says how many characters this will be."
160   :type 'integer
161   :group 'spam-stat)
162
163 (defcustom spam-stat-split-fancy-spam-group "mail.spam"
164   "Name of the group where spam should be stored, if
165 `spam-stat-split-fancy' is used in fancy splitting rules.  Has no
166 effect when spam-stat is invoked through spam.el."
167   :type 'string
168   :group 'spam-stat)
169
170 (defcustom spam-stat-split-fancy-spam-threshhold 0.9
171   "Spam score threshhold in spam-stat-split-fancy."
172   :type 'number
173   :group 'spam-stat)
174
175 (defvar spam-stat-syntax-table
176   (let ((table (copy-syntax-table text-mode-syntax-table)))
177     (modify-syntax-entry ?- "w" table)
178     (modify-syntax-entry ?_ "w" table)
179     (modify-syntax-entry ?. "w" table)
180     (modify-syntax-entry ?! "w" table)
181     (modify-syntax-entry ?? "w" table)
182     (modify-syntax-entry ?+ "w" table)
183     table)
184   "Syntax table used when processing mails for statistical analysis.
185 The important part is which characters are word constituents.")
186
187 (defvar spam-stat-dirty nil
188   "Whether the spam-stat database needs saving.")
189
190 (defvar spam-stat-buffer nil
191   "Buffer to use for scoring while splitting.
192 This is set by hooking into Gnus.")
193
194 (defvar spam-stat-buffer-name " *spam stat buffer*"
195   "Name of the `spam-stat-buffer'.")
196
197 ;; Hooking into Gnus
198
199 (defun spam-stat-store-current-buffer ()
200   "Store a copy of the current buffer in `spam-stat-buffer'."
201   (let ((buf (current-buffer)))
202     (with-current-buffer (get-buffer-create spam-stat-buffer-name)
203       (erase-buffer)
204       (insert-buffer-substring buf)
205       (setq spam-stat-buffer (current-buffer)))))
206
207 (defun spam-stat-store-gnus-article-buffer ()
208   "Store a copy of the current article in `spam-stat-buffer'.
209 This uses `gnus-article-buffer'."
210   (with-current-buffer gnus-original-article-buffer
211     (spam-stat-store-current-buffer)))
212
213 ;; Data -- not using defstruct in order to save space and time
214
215 (defvar spam-stat (make-hash-table :test 'equal)
216   "Hash table used to store the statistics.
217 Use `spam-stat-load' to load the file.
218 Every word is used as a key in this table.  The value is a vector.
219 Use `spam-stat-ngood', `spam-stat-nbad', `spam-stat-good',
220 `spam-stat-bad', and `spam-stat-score' to access this vector.")
221
222 (defvar spam-stat-ngood 0
223   "The number of good mails in the dictionary.")
224
225 (defvar spam-stat-nbad 0
226   "The number of bad mails in the dictionary.")
227
228 (defsubst spam-stat-good (entry)
229   "Return the number of times this word belongs to good mails."
230   (aref entry 0))
231
232 (defsubst spam-stat-bad (entry)
233   "Return the number of times this word belongs to bad mails."
234   (aref entry 1))
235
236 (defsubst spam-stat-score (entry)
237   "Set the score of this word."
238   (if entry
239       (aref entry 2)
240     spam-stat-unknown-word-score))
241
242 (defsubst spam-stat-set-good (entry value)
243   "Set the number of times this word belongs to good mails."
244   (aset entry 0 value))
245
246 (defsubst spam-stat-set-bad (entry value)
247   "Set the number of times this word belongs to bad mails."
248   (aset entry 1 value))
249
250 (defsubst spam-stat-set-score (entry value)
251   "Set the score of this word."
252   (aset entry 2 value))
253
254 (defsubst spam-stat-make-entry (good bad)
255   "Return a vector with the given properties."
256   (let ((entry (vector good bad nil)))
257     (spam-stat-set-score entry (spam-stat-compute-score entry))
258     entry))
259
260 ;; Computing
261
262 (defun spam-stat-compute-score (entry)
263   "Compute the score of this word.  1.0 means spam."
264    ;; promote all numbers to floats for the divisions
265    (let* ((g (* 2.0 (spam-stat-good entry)))
266           (b (float (spam-stat-bad entry))))
267      (cond ((< (+ g b) 5)
268             .2)
269            ((= 0 spam-stat-ngood)
270             .99)
271            ((= 0 spam-stat-nbad)
272             .01)
273            (t
274             (max .01
275                  (min .99 (/ (/ b spam-stat-nbad)
276                              (+ (/ g spam-stat-ngood)
277                                 (/ b spam-stat-nbad)))))))))
278
279 ;; Parsing
280
281 (defmacro with-spam-stat-max-buffer-size (&rest body)
282   "Narrows the buffer down to the first 4k characters, then evaluates BODY."
283   `(save-restriction
284      (when (> (- (point-max)
285                  (point-min))
286               spam-stat-max-buffer-length)
287        (narrow-to-region (point-min)
288                          (+ (point-min) spam-stat-max-buffer-length)))
289      ,@body))
290
291 (defun spam-stat-buffer-words ()
292   "Return a hash table of words and number of occurences in the buffer."
293   (with-spam-stat-max-buffer-size
294    (with-syntax-table spam-stat-syntax-table
295      (goto-char (point-min))
296      (let ((result (make-hash-table :test 'equal))
297            word count)
298        (while (re-search-forward "\\w+" nil t)
299          (setq word (match-string-no-properties 0)
300                count (1+ (gethash word result 0)))
301          (when (< (length word) spam-stat-max-word-length)
302            (puthash word count result)))
303        result))))
304
305 (defun spam-stat-buffer-is-spam ()
306   "Consider current buffer to be a new spam mail."
307   (setq spam-stat-nbad (1+ spam-stat-nbad))
308   (maphash
309    (lambda (word count)
310      (let ((entry (gethash word spam-stat)))
311        (if entry
312            (spam-stat-set-bad entry (+ count (spam-stat-bad entry)))
313          (setq entry (spam-stat-make-entry 0 count)))
314        (spam-stat-set-score entry (spam-stat-compute-score entry))
315        (puthash word entry spam-stat)))
316    (spam-stat-buffer-words))
317   (setq spam-stat-dirty t))
318
319 (defun spam-stat-buffer-is-non-spam ()
320   "Consider current buffer to be a new non-spam mail."
321   (setq spam-stat-ngood (1+ spam-stat-ngood))
322   (maphash
323    (lambda (word count)
324      (let ((entry (gethash word spam-stat)))
325        (if entry
326            (spam-stat-set-good entry (+ count (spam-stat-good entry)))
327          (setq entry (spam-stat-make-entry count 0)))
328        (spam-stat-set-score entry (spam-stat-compute-score entry))
329        (puthash word entry spam-stat)))
330    (spam-stat-buffer-words))
331   (setq spam-stat-dirty t))
332
333 (defun spam-stat-buffer-change-to-spam ()
334   "Consider current buffer no longer normal mail but spam."
335   (setq spam-stat-nbad (1+ spam-stat-nbad)
336         spam-stat-ngood (1- spam-stat-ngood))
337   (maphash
338    (lambda (word count)
339      (let ((entry (gethash word spam-stat)))
340        (if (not entry)
341            (error "This buffer has unknown words in it.")
342          (spam-stat-set-good entry (- (spam-stat-good entry) count))
343          (spam-stat-set-bad entry (+ (spam-stat-bad entry) count))
344          (spam-stat-set-score entry (spam-stat-compute-score entry))
345          (puthash word entry spam-stat))))
346    (spam-stat-buffer-words))
347   (setq spam-stat-dirty t))
348
349 (defun spam-stat-buffer-change-to-non-spam ()
350   "Consider current buffer no longer spam but normal mail."
351   (setq spam-stat-nbad (1- spam-stat-nbad)
352         spam-stat-ngood (1+ spam-stat-ngood))
353   (maphash
354    (lambda (word count)
355      (let ((entry (gethash word spam-stat)))
356        (if (not entry)
357            (error "This buffer has unknown words in it.")
358          (spam-stat-set-good entry (+ (spam-stat-good entry) count))
359          (spam-stat-set-bad entry (- (spam-stat-bad entry) count))
360          (spam-stat-set-score entry (spam-stat-compute-score entry))
361          (puthash word entry spam-stat))))
362    (spam-stat-buffer-words))
363   (setq spam-stat-dirty t))
364
365 ;; Saving and Loading
366
367 (defun spam-stat-save (&optional force)
368   "Save the `spam-stat' hash table as lisp file.
369 With a prefix argument save unconditionally."
370   (interactive "P")
371   (when (or force spam-stat-dirty)
372     (with-temp-buffer
373       (let ((standard-output (current-buffer))
374             (font-lock-maximum-size 0))
375         (insert "(setq spam-stat-ngood "
376                 (number-to-string spam-stat-ngood)
377                 " spam-stat-nbad "
378                 (number-to-string spam-stat-nbad)
379                 " spam-stat (spam-stat-to-hash-table '(")
380         (maphash (lambda (word entry)
381                    (prin1 (list word
382                                 (spam-stat-good entry)
383                                 (spam-stat-bad entry))))
384                  spam-stat)
385         (insert ")))")
386         (write-file spam-stat-file)))
387     (setq spam-stat-dirty nil)))
388
389 (defun spam-stat-load ()
390   "Read the `spam-stat' hash table from disk."
391   ;; TODO: maybe we should warn the user if spam-stat-dirty is t?
392   (load-file spam-stat-file)
393   (setq spam-stat-dirty nil))
394
395 (defun spam-stat-to-hash-table (entries)
396   "Turn list ENTRIES into a hash table and store as `spam-stat'.
397 Every element in ENTRIES has the form \(WORD GOOD BAD) where WORD is
398 the word string, NGOOD is the number of good mails it has appeared in,
399 NBAD is the number of bad mails it has appeared in, GOOD is the number
400 of times it appeared in good mails, and BAD is the number of times it
401 has appeared in bad mails."
402   (let ((table (make-hash-table :size (length entries)
403                                 :test 'equal)))
404     (mapc (lambda (l)
405             (puthash (car l)
406                      (spam-stat-make-entry (nth 1 l) (nth 2 l))
407                      table))
408           entries)
409     table))
410
411 (defun spam-stat-reset ()
412   "Reset `spam-stat' to an empty hash-table.
413 This deletes all the statistics."
414   (interactive)
415   (setq spam-stat (make-hash-table :test 'equal)
416         spam-stat-ngood 0
417         spam-stat-nbad 0)
418   (setq spam-stat-dirty t))
419
420 ;; Scoring buffers
421
422 (defvar spam-stat-score-data nil
423   "Raw data used in the last run of `spam-stat-score-buffer'.")
424
425 (defsubst spam-stat-score-word (word)
426   "Return score for WORD.
427 The default score for unknown words is stored in
428 `spam-stat-unknown-word-score'."
429   (spam-stat-score (gethash word spam-stat)))
430
431 (defun spam-stat-buffer-words-with-scores ()
432   "Process current buffer, return the 15 most conspicuous words.
433 These are the words whose spam-stat differs the most from 0.5.
434 The list returned contains elements of the form \(WORD SCORE DIFF),
435 where DIFF is the difference between SCORE and 0.5."
436   (let (result word score)
437     (maphash (lambda (word ignore)
438                (setq score (spam-stat-score-word word)
439                      result (cons (list word score (abs (- score 0.5)))
440                                   result)))
441              (spam-stat-buffer-words))
442     (setq result (sort result (lambda (a b) (< (nth 2 b) (nth 2 a)))))
443     (setcdr (nthcdr 14 result) nil)
444     result))
445
446 (defun spam-stat-score-buffer ()
447   "Return a score describing the spam-probability for this buffer."
448   (setq spam-stat-score-data (spam-stat-buffer-words-with-scores))
449   (let* ((probs (mapcar (lambda (e) (cadr e)) spam-stat-score-data))
450          (prod (apply #'* probs)))
451     (/ prod (+ prod (apply #'* (mapcar #'(lambda (x) (- 1 x))
452                                        probs))))))
453
454 (defun spam-stat-split-fancy ()
455   "Return the name of the spam group if the current mail is spam.
456 Use this function on `nnmail-split-fancy'.  If you are interested in
457 the raw data used for the last run of `spam-stat-score-buffer',
458 check the variable `spam-stat-score-data'."
459   (condition-case var
460       (progn
461         (set-buffer spam-stat-buffer)
462         (goto-char (point-min))
463         (when (> (spam-stat-score-buffer) spam-stat-split-fancy-spam-threshhold)
464           (when (boundp 'nnmail-split-trace)
465             (mapc (lambda (entry)
466                     (push entry nnmail-split-trace))
467                   spam-stat-score-data))
468           spam-stat-split-fancy-spam-group))
469     (error (message "Error in spam-stat-split-fancy: %S" var)
470            nil)))
471
472 ;; Testing
473
474 (defun spam-stat-strip-xref ()
475   "Strip the the Xref header."
476   (save-restriction
477     (mail-narrow-to-head)
478     (when (re-search-forward "^Xref:.*\n" nil t)
479       (delete-region (match-beginning 0) (match-end 0)))))
480
481 (defun spam-stat-process-directory (dir func)
482   "Process all the regular files in directory DIR using function FUNC."
483   (let* ((files (directory-files dir t "^[^.]"))
484          (max (/ (length files) 100.0))
485          (count 0))
486     (with-temp-buffer
487       (dolist (f files)
488         (when (and (file-readable-p f)
489                    (file-regular-p f)
490                    (> (nth 7 (file-attributes f)) 0))
491           (setq count (1+ count))
492           (message "Reading %s: %.2f%%" dir (/ count max))
493           (insert-file-contents f)
494           (spam-stat-strip-xref)
495           (funcall func)
496           (erase-buffer))))))
497
498 (defun spam-stat-process-spam-directory (dir)
499   "Process all the regular files in directory DIR as spam."
500   (interactive "D")
501   (spam-stat-process-directory dir 'spam-stat-buffer-is-spam))
502
503 (defun spam-stat-process-non-spam-directory (dir)
504   "Process all the regular files in directory DIR as non-spam."
505   (interactive "D")
506   (spam-stat-process-directory dir 'spam-stat-buffer-is-non-spam))
507
508 (defun spam-stat-count ()
509   "Return size of `spam-stat'."
510   (interactive)
511   (hash-table-count spam-stat))
512
513 (defun spam-stat-test-directory (dir &optional verbose)
514   "Test all the regular files in directory DIR for spam.
515 If the result is 1.0, then all files are considered spam.
516 If the result is 0.0, non of the files is considered spam.
517 You can use this to determine error rates.
518
519 If VERBOSE is non-nil display names of files detected as spam or
520 non-spam in a temporary buffer.  If it is the symbol `ham',
521 display non-spam files; otherwise display spam files."
522   (interactive "DDirectory: ")
523   (let* ((files (directory-files dir t "^[^.]"))
524          display-files
525          buffer-score
526          (total (length files))
527          (score 0.0); float
528          (max (/ total 100.0)); float
529          (count 0))
530     (with-temp-buffer
531       (dolist (f files)
532         (when (and (file-readable-p f)
533                    (file-regular-p f)
534                    (> (nth 7 (file-attributes f)) 0))
535           (setq count (1+ count))
536           (message "Reading %.2f%%, score %.2f"
537                    (/ count max) (/ score count))
538           (insert-file-contents f)
539           (setq buffer-score (spam-stat-score-buffer))
540           (when (> buffer-score 0.9)
541             (setq score (1+ score)))
542           (when verbose
543             (if (> buffer-score 0.9)
544                 (unless (eq verbose 'ham) (push f display-files))
545               (when (eq verbose 'ham) (push f display-files))))
546           (erase-buffer))))
547     (when display-files
548       (with-output-to-temp-buffer "*spam-stat results*"
549         (dolist (file display-files)
550           (princ file)
551           (terpri))))
552     (message "Final score: %d / %d = %f" score total (/ score total))))
553
554 ;; Shrinking the dictionary
555
556 (defun spam-stat-reduce-size (&optional count)
557   "Reduce the size of `spam-stat'.
558 This removes all words that occur less than COUNT from the dictionary.
559 COUNT defaults to 5"
560   (interactive)
561   (setq count (or count 5))
562   (maphash (lambda (key entry)
563              (when (< (+ (spam-stat-good entry)
564                          (spam-stat-bad entry))
565                       count)
566                (remhash key spam-stat)))
567            spam-stat)
568   (setq spam-stat-dirty t))
569
570 (defun spam-stat-install-hooks-function ()
571   "Install the spam-stat function hooks"
572   (interactive)
573   (add-hook 'nnmail-prepare-incoming-message-hook
574             'spam-stat-store-current-buffer)
575   (add-hook 'gnus-select-article-hook
576             'spam-stat-store-gnus-article-buffer))
577
578 (when spam-stat-install-hooks
579   (spam-stat-install-hooks-function))
580
581 (defun spam-stat-unload-hook ()
582   "Uninstall the spam-stat function hooks"
583   (interactive)
584   (remove-hook 'nnmail-prepare-incoming-message-hook
585                'spam-stat-store-current-buffer)
586   (remove-hook 'gnus-select-article-hook
587                'spam-stat-store-gnus-article-buffer))
588
589 (provide 'spam-stat)
590
591 ;;; spam-stat.el ends here