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