1 ;;; spam-stat.el --- detecting spam based on statistics
3 ;; Copyright (C) 2002 Alex Schroeder
5 ;; Author: Alex Schroeder <alex@gnu.org>
6 ;; Maintainer: Alex Schroeder <alex@gnu.org>
8 ;; Keywords: spam filtering gnus
9 ;; URL: http://www.emacswiki.org/cgi-bin/wiki.pl?SpamStat
11 ;; This file is NOT part of GNU Emacs.
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)
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.
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.
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
38 ;; The main interface to using spam-stat, are the following functions:
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
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
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
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
58 ;; `spam-stat-save' -- save the hash table to the file; the filename
59 ;; used is stored in the variable `spam-stat-file'
61 ;; `spam-stat-load' -- load the hash table from a file; the filename
62 ;; used is stored in the variable `spam-stat-file'
64 ;; `spam-stat-score-word' -- return the spam score for a word
66 ;; `spam-stat-score-buffer' -- return the spam score for a buffer
68 ;; `spam-stat-split-fancy' -- for fancy mail splitting; add
69 ;; the rule (: spam-stat-split-fancy) to `nnmail-split-fancy'
71 ;; This requires the following in your ~/.gnus file:
73 ;; (require 'spam-stat)
78 ;; Typical test will involve calls to the following functions:
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")
95 ;;; Dictionary Creation:
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:
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)
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.
118 ;; Ted Zlatanov <tzz@lifelogs.com>
119 ;; Jesper Harder <harder@myrealbox.com>
120 ;; Dan Schmidt <dfan@dfan.org>
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."
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."
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."
145 (defcustom spam-stat-max-word-length 15
146 "Only words shorter than this will be considered."
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."
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."
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)
171 "Syntax table used when processing mails for statistical analysis.
172 The important part is which characters are word constituents.")
174 (defvar spam-stat-buffer nil
175 "Buffer to use for scoring while splitting.
176 This is set by hooking into Gnus.")
178 (defvar spam-stat-buffer-name " *spam stat buffer*"
179 "Name of the `spam-stat-buffer'.")
183 (defun spam-stat-store-current-buffer ()
184 "Store a copy of the current buffer in `spam-stat-buffer'."
186 (let ((str (buffer-string)))
187 (set-buffer (get-buffer-create spam-stat-buffer-name))
190 (setq spam-stat-buffer (current-buffer)))))
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'."
196 (set-buffer gnus-original-article-buffer)
197 (spam-stat-store-current-buffer)))
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)
204 ;; Data -- not using defstruct in order to save space and time
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.")
213 (defvar spam-stat-ngood 0
214 "The number of good mails in the dictionary.")
216 (defvar spam-stat-nbad 0
217 "The number of bad mails in the dictionary.")
219 (defsubst spam-stat-good (entry)
220 "Return the number of times this word belongs to good mails."
223 (defsubst spam-stat-bad (entry)
224 "Return the number of times this word belongs to bad mails."
227 (defsubst spam-stat-score (entry)
228 "Set the score of this word."
231 spam-stat-unknown-word-score))
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))
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))
241 (defsubst spam-stat-set-score (entry value)
242 "Set the score of this word."
243 (aset entry 2 value))
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))
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))))
260 ((= 0 spam-stat-ngood)
262 ((= 0 spam-stat-nbad)
266 (min .99 (/ (/ b spam-stat-nbad)
267 (+ (/ g spam-stat-ngood)
268 (/ b spam-stat-nbad)))))))))
272 (defmacro with-spam-stat-max-buffer-size (&rest body)
273 "Narrows the buffer down to the first 4k characters, then evaluates BODY."
275 (when (> (- (point-max)
277 spam-stat-max-buffer-length)
278 (narrow-to-region (point-min)
279 (+ (point-min) spam-stat-max-buffer-length)))
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))
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)))
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))
301 (let ((entry (gethash word spam-stat)))
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)))
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))
314 (let ((entry (gethash word spam-stat)))
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)))
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))
328 (let ((entry (gethash word spam-stat)))
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)))
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))
343 (let ((entry (gethash word spam-stat)))
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)))
352 ;; Saving and Loading
354 (defun spam-stat-save ()
355 "Save the `spam-stat' hash table as lisp file."
358 (let ((standard-output (current-buffer)))
359 (insert "(setq spam-stat (spam-stat-to-hash-table '(")
360 (maphash (lambda (word entry)
362 (spam-stat-good entry)
363 (spam-stat-bad entry))))
365 (insert ")) spam-stat-ngood "
366 (number-to-string spam-stat-ngood)
368 (number-to-string spam-stat-nbad)
370 (write-file spam-stat-file)))
372 (defun spam-stat-load ()
373 "Read the `spam-stat' hash table from disk."
374 (load-file spam-stat-file))
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)))
386 (spam-stat-make-entry (nth 1 l) (nth 2 l))
391 (defun spam-stat-reset ()
392 "Reset `spam-stat' to an empty hash-table.
393 This deletes all the statistics."
395 (setq spam-stat (make-hash-table :test 'equal)))
399 (defvar spam-stat-score-data nil
400 "Raw data used in the last run of `spam-stat-score-buffer'.")
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)))
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)))
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)
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))
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'."
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)
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))
461 (when (and (file-readable-p f)
463 (setq count (1+ count))
464 (message "Reading %.2f%%" (/ count max))
465 (insert-file-contents f)
469 (defun spam-stat-process-spam-directory (dir)
470 "Process all the regular files in directory DIR as spam."
472 (spam-stat-process-directory dir 'spam-stat-buffer-is-spam))
474 (defun spam-stat-process-non-spam-directory (dir)
475 "Process all the regular files in directory DIR as non-spam."
477 (spam-stat-process-directory dir 'spam-stat-buffer-is-non-spam))
479 (defun spam-stat-count ()
480 "Return size of `spam-stat'."
482 (hash-table-count spam-stat))
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."
490 (let* ((files (directory-files dir t "^[^.]"))
491 (total (length files))
493 (max (/ total 100.0)); float
497 (when (and (file-readable-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)))
506 (message "Final score: %d / %d = %f" score total (/ score total))))
508 ;; Shrinking the dictionary
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."
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))
523 (< (abs (- (spam-stat-score entry) 0.5))
525 (remhash key spam-stat)))
530 ;;; spam-stat.el ends here