further compilation fixes for spam.el
[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.3
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   (with-temp-buffer
357     (let ((standard-output (current-buffer)))
358       (insert "(setq spam-stat (spam-stat-to-hash-table '(")
359       (maphash (lambda (word entry)
360                  (prin1 (list word
361                               (spam-stat-good entry)
362                               (spam-stat-bad entry))))
363                spam-stat)
364       (insert ")) spam-stat-ngood "
365               (number-to-string spam-stat-ngood)
366               " spam-stat-nbad "
367               (number-to-string spam-stat-nbad)
368               ")"))
369     (write-file spam-stat-file)))
370
371 (defun spam-stat-load ()
372   "Read the `spam-stat' hash table from disk."
373   (load-file spam-stat-file))
374
375 (defun spam-stat-to-hash-table (entries)
376   "Turn list ENTRIES into a hash table and store as `spam-stat'.
377 Every element in ENTRIES has the form \(WORD GOOD BAD) where WORD is
378 the word string, NGOOD is the number of good mails it has appeared in,
379 NBAD is the number of bad mails it has appeared in, GOOD is the number
380 of times it appeared in good mails, and BAD is the number of times it
381 has appeared in bad mails."
382   (let ((table (make-hash-table :test 'equal)))
383     (mapc (lambda (l)
384             (puthash (car l)
385                      (spam-stat-make-entry (nth 1 l) (nth 2 l))
386                      table))
387           entries)
388     table))
389
390 ;; Scoring buffers
391
392 (defvar spam-stat-score-data nil
393   "Raw data used in the last run of `spam-stat-score-buffer'.")
394
395 (defsubst spam-stat-score-word (word)
396   "Return score for WORD.
397 The default score for unknown words is stored in
398 `spam-stat-unknown-word-score'."
399   (spam-stat-score (gethash word spam-stat)))
400     
401
402 (defun spam-stat-buffer-words-with-scores ()
403   "Process current buffer, return the 15 most conspicuous words.
404 These are the words whose spam-stat differs the most from 0.5.
405 The list returned contains elements of the form \(WORD SCORE DIFF),
406 where DIFF is the difference between SCORE and 0.5."
407   (with-spam-stat-max-buffer-size
408    (with-syntax-table spam-stat-syntax-table
409      (let (result word score)
410        (maphash (lambda (word ignore)
411                   (setq score (spam-stat-score-word word)
412                         result (cons (list word score (abs (- score 0.5)))
413                                      result)))
414                 (spam-stat-buffer-words))
415        (setq result (sort result (lambda (a b) (< (nth 2 b) (nth 2 a)))))
416        (setcdr (nthcdr 14 result) nil)
417        result))))
418
419 (defun spam-stat-score-buffer ()
420   "Return a score describing the spam-probability for this buffer."
421   (setq spam-stat-score-data (spam-stat-buffer-words-with-scores))
422   (let* ((probs (mapcar (lambda (e) (cadr e)) spam-stat-score-data))
423          (prod (apply #'* probs)))
424     (/ prod (+ prod (apply #'* (mapcar #'(lambda (x) (- 1 x))
425                                        probs))))))
426
427 (defun spam-stat-split-fancy ()
428   "Return the name of the spam group if the current mail is spam.
429 Use this function on `nnmail-split-fancy'.  If you are interested in
430 the raw data used for the last run of `spam-stat-score-buffer',
431 check the variable `spam-stat-score-data'."
432   (condition-case var
433       (progn
434         (set-buffer spam-stat-buffer)
435         (goto-char (point-min))
436         (when (> (spam-stat-score-buffer) 0.9)
437           (when (boundp 'nnmail-split-trace)
438             (mapc (lambda (entry)
439                     (push entry nnmail-split-trace))
440                   spam-stat-score-data))
441           spam-stat-split-fancy-spam-group))
442     (error (message "Error in spam-stat-split-fancy: %S" var)
443            nil)))
444
445 ;; Testing
446
447 (defun spam-stat-process-directory (dir func)
448   "Process all the regular files in directory DIR using function FUNC."
449   (let* ((files (directory-files dir t "^[^.]"))
450          (max (/ (length files) 100.0))
451          (count 0))
452     (with-temp-buffer
453       (dolist (f files)
454         (when (and (file-readable-p f)
455                    (file-regular-p f))
456           (setq count (1+ count))
457           (message "Reading %.2f%%" (/ count max))
458           (insert-file-contents f)
459           (funcall func)
460           (erase-buffer))))))
461
462 (defun spam-stat-process-spam-directory (dir)
463   "Process all the regular files in directory DIR as spam."
464   (interactive "D")
465   (spam-stat-process-directory dir 'spam-stat-buffer-is-spam))
466
467 (defun spam-stat-process-non-spam-directory (dir)
468   "Process all the regular files in directory DIR as non-spam."
469   (interactive "D")
470   (spam-stat-process-directory dir 'spam-stat-buffer-is-non-spam))
471
472 (defun spam-stat-count ()
473   "Return size of `spam-stat'."
474   (interactive)
475   (hash-table-count spam-stat))
476
477 (defun spam-stat-test-directory (dir)
478   "Test all the regular files in directory DIR for spam.
479 If the result is 1.0, then all files are considered spam.
480 If the result is 0.0, non of the files is considered spam.
481 You can use this to determine error rates."
482   (interactive "D")
483   (let* ((files (directory-files dir t "^[^.]"))
484          (total (length files))
485          (score 0.0); float
486          (max (/ total 100.0)); float
487          (count 0))
488     (with-temp-buffer
489       (dolist (f files)
490         (when (and (file-readable-p f)
491                    (file-regular-p f))
492           (setq count (1+ count))
493           (message "Reading %.2f%%, score %.2f%%"
494                    (/ count max) (/ score count))
495           (insert-file-contents f)
496           (when (> (spam-stat-score-buffer) 0.9)
497             (setq score (1+ score)))
498           (erase-buffer))))
499     (message "Final score: %d / %d = %f" score total (/ score total))))
500
501 ;; Shrinking the dictionary
502
503 (defun spam-stat-reduce-size (&optional count distance)
504   "Reduce the size of `spam-stat'.
505 This removes all words that occur less than COUNT from the dictionary.
506 COUNT defaults to 5.  It also removes all words whose spam score
507 is less than DISTANCE from 0.5.  DISTANCE defaults to 0.1, meaning that
508 all words with score between 0.4 and 0.6 are removed."
509   (setq count (or count 5)
510         distance (or distance 0.1))
511   (maphash (lambda (key entry)
512              (when (or (< (+ (spam-stat-good entry)
513                              (spam-stat-bad entry))
514                           count)
515                        (< (abs (- (spam-stat-score entry) 0.5))
516                           distance))
517                (remhash key spam-stat)))
518            spam-stat))
519
520 (provide 'spam-stat)
521
522 ;;; spam-stat.el ends here
523