b7b7cd29a2fc4963f98bbdd7eb5056e73a6f65f7
[elisp/gnus.git-] / 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   (save-excursion
202     (let ((str (buffer-string)))
203       (set-buffer (get-buffer-create spam-stat-buffer-name))
204       (erase-buffer)
205       (insert str)
206       (setq spam-stat-buffer (current-buffer)))))
207
208 (defun spam-stat-store-gnus-article-buffer ()
209   "Store a copy of the current article in `spam-stat-buffer'.
210 This uses `gnus-article-buffer'."
211   (save-excursion
212     (set-buffer gnus-original-article-buffer)
213     (spam-stat-store-current-buffer)))
214
215 ;; Data -- not using defstruct in order to save space and time
216
217 (defvar spam-stat (make-hash-table :test 'equal)
218   "Hash table used to store the statistics.
219 Use `spam-stat-load' to load the file.
220 Every word is used as a key in this table.  The value is a vector.
221 Use `spam-stat-ngood', `spam-stat-nbad', `spam-stat-good',
222 `spam-stat-bad', and `spam-stat-score' to access this vector.")
223
224 (defvar spam-stat-ngood 0
225   "The number of good mails in the dictionary.")
226
227 (defvar spam-stat-nbad 0
228   "The number of bad mails in the dictionary.")
229
230 (defsubst spam-stat-good (entry)
231   "Return the number of times this word belongs to good mails."
232   (aref entry 0))
233
234 (defsubst spam-stat-bad (entry)
235   "Return the number of times this word belongs to bad mails."
236   (aref entry 1))
237
238 (defsubst spam-stat-score (entry)
239   "Set the score of this word."
240   (if entry
241       (aref entry 2)
242     spam-stat-unknown-word-score))
243
244 (defsubst spam-stat-set-good (entry value)
245   "Set the number of times this word belongs to good mails."
246   (aset entry 0 value))
247
248 (defsubst spam-stat-set-bad (entry value)
249   "Set the number of times this word belongs to bad mails."
250   (aset entry 1 value))
251
252 (defsubst spam-stat-set-score (entry value)
253   "Set the score of this word."
254   (aset entry 2 value))
255
256 (defsubst spam-stat-make-entry (good bad)
257   "Return a vector with the given properties."
258   (let ((entry (vector good bad nil)))
259     (spam-stat-set-score entry (spam-stat-compute-score entry))
260     entry))
261
262 ;; Computing
263
264 (defun spam-stat-compute-score (entry)
265   "Compute the score of this word.  1.0 means spam."
266    ;; promote all numbers to floats for the divisions
267    (let* ((g (* 2.0 (spam-stat-good entry)))
268           (b (float (spam-stat-bad entry))))
269      (cond ((< (+ g b) 5)
270             .2)
271            ((= 0 spam-stat-ngood)
272             .99)
273            ((= 0 spam-stat-nbad)
274             .01)
275            (t
276             (max .01
277                  (min .99 (/ (/ b spam-stat-nbad)
278                              (+ (/ g spam-stat-ngood)
279                                 (/ b spam-stat-nbad)))))))))
280
281 ;; Parsing
282
283 (defmacro with-spam-stat-max-buffer-size (&rest body)
284   "Narrows the buffer down to the first 4k characters, then evaluates BODY."
285   `(save-restriction
286      (when (> (- (point-max)
287                  (point-min))
288               spam-stat-max-buffer-length)
289        (narrow-to-region (point-min)
290                          (+ (point-min) spam-stat-max-buffer-length)))
291      ,@body))
292
293 (defun spam-stat-buffer-words ()
294   "Return a hash table of words and number of occurences in the buffer."
295   (with-spam-stat-max-buffer-size
296    (with-syntax-table spam-stat-syntax-table
297      (goto-char (point-min))
298      (let ((result (make-hash-table :test 'equal))
299            word count)
300        (while (re-search-forward "\\w+" nil t)
301          (setq word (match-string-no-properties 0)
302                count (1+ (gethash word result 0)))
303          (when (< (length word) spam-stat-max-word-length)
304            (puthash word count result)))
305        result))))
306
307 (defun spam-stat-buffer-is-spam ()
308   "Consider current buffer to be a new spam mail."
309   (setq spam-stat-nbad (1+ spam-stat-nbad))
310   (maphash
311    (lambda (word count)
312      (let ((entry (gethash word spam-stat)))
313        (if entry
314            (spam-stat-set-bad entry (+ count (spam-stat-bad entry)))
315          (setq entry (spam-stat-make-entry 0 count)))
316        (spam-stat-set-score entry (spam-stat-compute-score entry))
317        (puthash word entry spam-stat)))
318    (spam-stat-buffer-words))
319   (setq spam-stat-dirty t))
320
321 (defun spam-stat-buffer-is-non-spam ()
322   "Consider current buffer to be a new non-spam mail."
323   (setq spam-stat-ngood (1+ spam-stat-ngood))
324   (maphash
325    (lambda (word count)
326      (let ((entry (gethash word spam-stat)))
327        (if entry
328            (spam-stat-set-good entry (+ count (spam-stat-good entry)))
329          (setq entry (spam-stat-make-entry count 0)))
330        (spam-stat-set-score entry (spam-stat-compute-score entry))
331        (puthash word entry spam-stat)))
332    (spam-stat-buffer-words))
333   (setq spam-stat-dirty t))
334
335 (defun spam-stat-buffer-change-to-spam ()
336   "Consider current buffer no longer normal mail but spam."
337   (setq spam-stat-nbad (1+ spam-stat-nbad)
338         spam-stat-ngood (1- spam-stat-ngood))
339   (maphash
340    (lambda (word count)
341      (let ((entry (gethash word spam-stat)))
342        (if (not entry)
343            (error "This buffer has unknown words in it.")
344          (spam-stat-set-good entry (- (spam-stat-good entry) count))
345          (spam-stat-set-bad entry (+ (spam-stat-bad entry) count))
346          (spam-stat-set-score entry (spam-stat-compute-score entry))
347          (puthash word entry spam-stat))))
348    (spam-stat-buffer-words))
349   (setq spam-stat-dirty t))
350
351 (defun spam-stat-buffer-change-to-non-spam ()
352   "Consider current buffer no longer spam but normal mail."
353   (setq spam-stat-nbad (1- spam-stat-nbad)
354         spam-stat-ngood (1+ spam-stat-ngood))
355   (maphash
356    (lambda (word count)
357      (let ((entry (gethash word spam-stat)))
358        (if (not entry)
359            (error "This buffer has unknown words in it.")
360          (spam-stat-set-good entry (+ (spam-stat-good entry) count))
361          (spam-stat-set-bad entry (- (spam-stat-bad entry) count))
362          (spam-stat-set-score entry (spam-stat-compute-score entry))
363          (puthash word entry spam-stat))))
364    (spam-stat-buffer-words))
365   (setq spam-stat-dirty t))
366
367 ;; Saving and Loading
368
369 (defun spam-stat-save (&optional force)
370   "Save the `spam-stat' hash table as lisp file."
371   (interactive)
372   (when (or force spam-stat-dirty)
373     (with-temp-buffer
374       (let ((standard-output (current-buffer))
375             (font-lock-maximum-size 0))
376         (insert "(setq spam-stat-ngood "
377                 (number-to-string spam-stat-ngood)
378                 " spam-stat-nbad "
379                 (number-to-string spam-stat-nbad)
380                 " spam-stat (spam-stat-to-hash-table '(")
381         (maphash (lambda (word entry)
382                    (prin1 (list word
383                                 (spam-stat-good entry)
384                                 (spam-stat-bad entry))))
385                  spam-stat)
386         (insert ")))")
387         (write-file spam-stat-file)))
388     (setq spam-stat-dirty nil)))
389
390 (defun spam-stat-load ()
391   "Read the `spam-stat' hash table from disk."
392   ;; TODO: maybe we should warn the user if spam-stat-dirty is t?
393   (load-file spam-stat-file)
394   (setq spam-stat-dirty nil))
395
396 (defun spam-stat-to-hash-table (entries)
397   "Turn list ENTRIES into a hash table and store as `spam-stat'.
398 Every element in ENTRIES has the form \(WORD GOOD BAD) where WORD is
399 the word string, NGOOD is the number of good mails it has appeared in,
400 NBAD is the number of bad mails it has appeared in, GOOD is the number
401 of times it appeared in good mails, and BAD is the number of times it
402 has appeared in bad mails."
403   (let ((table (make-hash-table :size (length entries)
404                                 :test 'equal)))
405     (mapc (lambda (l)
406             (puthash (car l)
407                      (spam-stat-make-entry (nth 1 l) (nth 2 l))
408                      table))
409           entries)
410     table))
411
412 (defun spam-stat-reset ()
413   "Reset `spam-stat' to an empty hash-table.
414 This deletes all the statistics."
415   (interactive)
416   (setq spam-stat (make-hash-table :test 'equal)
417         spam-stat-ngood 0
418         spam-stat-nbad 0)
419   (setq spam-stat-dirty t))
420
421 ;; Scoring buffers
422
423 (defvar spam-stat-score-data nil
424   "Raw data used in the last run of `spam-stat-score-buffer'.")
425
426 (defsubst spam-stat-score-word (word)
427   "Return score for WORD.
428 The default score for unknown words is stored in
429 `spam-stat-unknown-word-score'."
430   (spam-stat-score (gethash word spam-stat)))
431
432 (defun spam-stat-buffer-words-with-scores ()
433   "Process current buffer, return the 15 most conspicuous words.
434 These are the words whose spam-stat differs the most from 0.5.
435 The list returned contains elements of the form \(WORD SCORE DIFF),
436 where DIFF is the difference between SCORE and 0.5."
437   (let (result word score)
438     (maphash (lambda (word ignore)
439                (setq score (spam-stat-score-word word)
440                      result (cons (list word score (abs (- score 0.5)))
441                                   result)))
442              (spam-stat-buffer-words))
443     (setq result (sort result (lambda (a b) (< (nth 2 b) (nth 2 a)))))
444     (setcdr (nthcdr 14 result) nil)
445     result))
446
447 (defun spam-stat-score-buffer ()
448   "Return a score describing the spam-probability for this buffer."
449   (setq spam-stat-score-data (spam-stat-buffer-words-with-scores))
450   (let* ((probs (mapcar (lambda (e) (cadr e)) spam-stat-score-data))
451          (prod (apply #'* probs)))
452     (/ prod (+ prod (apply #'* (mapcar #'(lambda (x) (- 1 x))
453                                        probs))))))
454
455 (defun spam-stat-split-fancy ()
456   "Return the name of the spam group if the current mail is spam.
457 Use this function on `nnmail-split-fancy'.  If you are interested in
458 the raw data used for the last run of `spam-stat-score-buffer',
459 check the variable `spam-stat-score-data'."
460   (condition-case var
461       (progn
462         (set-buffer spam-stat-buffer)
463         (goto-char (point-min))
464         (when (> (spam-stat-score-buffer) spam-stat-split-fancy-spam-threshhold)
465           (when (boundp 'nnmail-split-trace)
466             (mapc (lambda (entry)
467                     (push entry nnmail-split-trace))
468                   spam-stat-score-data))
469           spam-stat-split-fancy-spam-group))
470     (error (message "Error in spam-stat-split-fancy: %S" var)
471            nil)))
472
473 ;; Testing
474
475 (defun spam-stat-strip-xref ()
476   "Strip the the Xref header."
477   (save-restriction
478     (mail-narrow-to-head)
479     (when (re-search-forward "^Xref:.*\n" nil t)
480       (delete-region (match-beginning 0) (match-end 0)))))
481
482 (defun spam-stat-process-directory (dir func)
483   "Process all the regular files in directory DIR using function FUNC."
484   (let* ((files (directory-files dir t "^[^.]"))
485          (max (/ (length files) 100.0))
486          (count 0))
487     (with-temp-buffer
488       (dolist (f files)
489         (when (and (file-readable-p f)
490                    (file-regular-p f)
491                    (> (nth 7 (file-attributes f)) 0))
492           (setq count (1+ count))
493           (message "Reading %s: %.2f%%" dir (/ count max))
494           (insert-file-contents f)
495           (spam-stat-strip-xref)
496           (funcall func)
497           (erase-buffer))))))
498
499 (defun spam-stat-process-spam-directory (dir)
500   "Process all the regular files in directory DIR as spam."
501   (interactive "D")
502   (spam-stat-process-directory dir 'spam-stat-buffer-is-spam))
503
504 (defun spam-stat-process-non-spam-directory (dir)
505   "Process all the regular files in directory DIR as non-spam."
506   (interactive "D")
507   (spam-stat-process-directory dir 'spam-stat-buffer-is-non-spam))
508
509 (defun spam-stat-count ()
510   "Return size of `spam-stat'."
511   (interactive)
512   (hash-table-count spam-stat))
513
514 (defun spam-stat-test-directory (dir &optional verbose)
515   "Test all the regular files in directory DIR for spam.
516 If the result is 1.0, then all files are considered spam.
517 If the result is 0.0, non of the files is considered spam.
518 You can use this to determine error rates.
519
520 If VERBOSE is non-nil display names of files detected as spam or
521 non-spam in a temporary buffer.  If it is the symbol `ham',
522 display non-spam files; otherwise display spam files."
523   (interactive "DDirectory: ")
524   (let* ((files (directory-files dir t "^[^.]"))
525          display-files
526          buffer-score
527          (total (length files))
528          (score 0.0); float
529          (max (/ total 100.0)); float
530          (count 0))
531     (with-temp-buffer
532       (dolist (f files)
533         (when (and (file-readable-p f)
534                    (file-regular-p f)
535                    (> (nth 7 (file-attributes f)) 0))
536           (setq count (1+ count))
537           (message "Reading %.2f%%, score %.2f"
538                    (/ count max) (/ score count))
539           (insert-file-contents f)
540           (setq buffer-score (spam-stat-score-buffer))
541           (when (> buffer-score 0.9)
542             (setq score (1+ score)))
543           (when verbose
544             (if (> buffer-score 0.9)
545                 (unless (eq verbose 'ham) (push f display-files))
546               (when (eq verbose 'ham) (push f display-files))))
547           (erase-buffer))))
548     (when display-files
549       (with-output-to-temp-buffer "*spam-stat results*"
550         (dolist (file display-files)
551           (princ file)
552           (terpri))))
553     (message "Final score: %d / %d = %f" score total (/ score total))))
554
555 ;; Shrinking the dictionary
556
557 (defun spam-stat-reduce-size (&optional count)
558   "Reduce the size of `spam-stat'.
559 This removes all words that occur less than COUNT from the dictionary.
560 COUNT defaults to 5"
561   (interactive)
562   (setq count (or count 5))
563   (maphash (lambda (key entry)
564              (when (< (+ (spam-stat-good entry)
565                          (spam-stat-bad entry))
566                       count)
567                (remhash key spam-stat)))
568            spam-stat))
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