(latexenc-find-file-coding-system): Don't inherit the EOL part of the
[emacs.git] / lisp / gnus / spam-stat.el
blobca1cdc6ce60f6c18953fb22b4b716feb9042d870
1 ;;; spam-stat.el --- detecting spam based on statistics
3 ;; Copyright (C) 2002, 2003, 2004 Free Software Foundation, Inc.
5 ;; Author: Alex Schroeder <alex@gnu.org>
6 ;; Keywords: network
7 ;; URL: http://www.emacswiki.org/cgi-bin/wiki.pl?SpamStat
9 ;; This file is part of GNU Emacs.
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.
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.
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.
26 ;;; Commentary:
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).
36 ;; The main interface to using spam-stat, are the following functions:
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
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
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
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
56 ;; `spam-stat-save' -- save the hash table to the file; the filename
57 ;; used is stored in the variable `spam-stat-file'
59 ;; `spam-stat-load' -- load the hash table from a file; the filename
60 ;; used is stored in the variable `spam-stat-file'
62 ;; `spam-stat-score-word' -- return the spam score for a word
64 ;; `spam-stat-score-buffer' -- return the spam score for a buffer
66 ;; `spam-stat-split-fancy' -- for fancy mail splitting; add
67 ;; the rule (: spam-stat-split-fancy) to `nnmail-split-fancy'
69 ;; This requires the following in your ~/.gnus file:
71 ;; (require 'spam-stat)
72 ;; (spam-stat-load)
74 ;;; Testing:
76 ;; Typical test will involve calls to the following functions:
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")
93 ;;; Dictionary Creation:
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:
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)
106 ;;; Todo:
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.
114 ;;; Thanks:
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>
124 ;;; Code:
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 whether a buffer contains spam or not."
131 :version "22.1"
132 :group 'gnus)
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)
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)
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)
152 (defcustom spam-stat-max-word-length 15
153 "Only words shorter than this will be considered."
154 :type 'integer
155 :group 'spam-stat)
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)
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)
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)
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.")
187 (defvar spam-stat-dirty nil
188 "Whether the spam-stat database needs saving.")
190 (defvar spam-stat-buffer nil
191 "Buffer to use for scoring while splitting.
192 This is set by hooking into Gnus.")
194 (defvar spam-stat-buffer-name " *spam stat buffer*"
195 "Name of the `spam-stat-buffer'.")
197 ;; Functions missing in Emacs 20
199 (when (memq nil (mapcar 'fboundp
200 '(gethash hash-table-count make-hash-table
201 mapc puthash)))
202 (require 'cl)
203 (unless (fboundp 'puthash)
204 ;; alias puthash is missing from Emacs 20 cl-extra.el
205 (defalias 'puthash 'cl-puthash)))
207 (eval-when-compile
208 (unless (fboundp 'with-syntax-table)
209 ;; Imported from Emacs 21.2
210 (defmacro with-syntax-table (table &rest body) "\
211 Evaluate BODY with syntax table of current buffer set to a copy of TABLE.
212 The syntax table of the current buffer is saved, BODY is evaluated, and the
213 saved table is restored, even in case of an abnormal exit.
214 Value is what BODY returns."
215 (let ((old-table (make-symbol "table"))
216 (old-buffer (make-symbol "buffer")))
217 `(let ((,old-table (syntax-table))
218 (,old-buffer (current-buffer)))
219 (unwind-protect
220 (progn
221 (set-syntax-table (copy-syntax-table ,table))
222 ,@body)
223 (save-current-buffer
224 (set-buffer ,old-buffer)
225 (set-syntax-table ,old-table))))))))
227 ;; Hooking into Gnus
229 (defun spam-stat-store-current-buffer ()
230 "Store a copy of the current buffer in `spam-stat-buffer'."
231 (save-excursion
232 (let ((str (buffer-string)))
233 (set-buffer (get-buffer-create spam-stat-buffer-name))
234 (erase-buffer)
235 (insert str)
236 (setq spam-stat-buffer (current-buffer)))))
238 (defun spam-stat-store-gnus-article-buffer ()
239 "Store a copy of the current article in `spam-stat-buffer'.
240 This uses `gnus-article-buffer'."
241 (save-excursion
242 (set-buffer gnus-original-article-buffer)
243 (spam-stat-store-current-buffer)))
245 ;; Data -- not using defstruct in order to save space and time
247 (defvar spam-stat (make-hash-table :test 'equal)
248 "Hash table used to store the statistics.
249 Use `spam-stat-load' to load the file.
250 Every word is used as a key in this table. The value is a vector.
251 Use `spam-stat-ngood', `spam-stat-nbad', `spam-stat-good',
252 `spam-stat-bad', and `spam-stat-score' to access this vector.")
254 (defvar spam-stat-ngood 0
255 "The number of good mails in the dictionary.")
257 (defvar spam-stat-nbad 0
258 "The number of bad mails in the dictionary.")
260 (defsubst spam-stat-good (entry)
261 "Return the number of times this word belongs to good mails."
262 (aref entry 0))
264 (defsubst spam-stat-bad (entry)
265 "Return the number of times this word belongs to bad mails."
266 (aref entry 1))
268 (defsubst spam-stat-score (entry)
269 "Set the score of this word."
270 (if entry
271 (aref entry 2)
272 spam-stat-unknown-word-score))
274 (defsubst spam-stat-set-good (entry value)
275 "Set the number of times this word belongs to good mails."
276 (aset entry 0 value))
278 (defsubst spam-stat-set-bad (entry value)
279 "Set the number of times this word belongs to bad mails."
280 (aset entry 1 value))
282 (defsubst spam-stat-set-score (entry value)
283 "Set the score of this word."
284 (aset entry 2 value))
286 (defsubst spam-stat-make-entry (good bad)
287 "Return a vector with the given properties."
288 (let ((entry (vector good bad nil)))
289 (spam-stat-set-score entry (spam-stat-compute-score entry))
290 entry))
292 ;; Computing
294 (defun spam-stat-compute-score (entry)
295 "Compute the score of this word. 1.0 means spam."
296 ;; promote all numbers to floats for the divisions
297 (let* ((g (* 2.0 (spam-stat-good entry)))
298 (b (float (spam-stat-bad entry))))
299 (cond ((< (+ g b) 5)
301 ((= 0 spam-stat-ngood)
302 .99)
303 ((= 0 spam-stat-nbad)
304 .01)
306 (max .01
307 (min .99 (/ (/ b spam-stat-nbad)
308 (+ (/ g spam-stat-ngood)
309 (/ b spam-stat-nbad)))))))))
311 ;; Parsing
313 (defmacro with-spam-stat-max-buffer-size (&rest body)
314 "Narrows the buffer down to the first 4k characters, then evaluates BODY."
315 `(save-restriction
316 (when (> (- (point-max)
317 (point-min))
318 spam-stat-max-buffer-length)
319 (narrow-to-region (point-min)
320 (+ (point-min) spam-stat-max-buffer-length)))
321 ,@body))
323 (defun spam-stat-buffer-words ()
324 "Return a hash table of words and number of occurences in the buffer."
325 (with-spam-stat-max-buffer-size
326 (with-syntax-table spam-stat-syntax-table
327 (goto-char (point-min))
328 (let ((result (make-hash-table :test 'equal))
329 word count)
330 (while (re-search-forward "\\w+" nil t)
331 (setq word (match-string-no-properties 0)
332 count (1+ (gethash word result 0)))
333 (when (< (length word) spam-stat-max-word-length)
334 (puthash word count result)))
335 result))))
337 (defun spam-stat-buffer-is-spam ()
338 "Consider current buffer to be a new spam mail."
339 (setq spam-stat-nbad (1+ spam-stat-nbad))
340 (maphash
341 (lambda (word count)
342 (let ((entry (gethash word spam-stat)))
343 (if entry
344 (spam-stat-set-bad entry (+ count (spam-stat-bad entry)))
345 (setq entry (spam-stat-make-entry 0 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))
351 (defun spam-stat-buffer-is-non-spam ()
352 "Consider current buffer to be a new non-spam mail."
353 (setq spam-stat-ngood (1+ spam-stat-ngood))
354 (maphash
355 (lambda (word count)
356 (let ((entry (gethash word spam-stat)))
357 (if entry
358 (spam-stat-set-good entry (+ count (spam-stat-good entry)))
359 (setq entry (spam-stat-make-entry count 0)))
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))
365 (defun spam-stat-buffer-change-to-spam ()
366 "Consider current buffer no longer normal mail but spam."
367 (setq spam-stat-nbad (1+ spam-stat-nbad)
368 spam-stat-ngood (1- spam-stat-ngood))
369 (maphash
370 (lambda (word count)
371 (let ((entry (gethash word spam-stat)))
372 (if (not entry)
373 (error "This buffer has unknown words in it.")
374 (spam-stat-set-good entry (- (spam-stat-good entry) count))
375 (spam-stat-set-bad entry (+ (spam-stat-bad entry) count))
376 (spam-stat-set-score entry (spam-stat-compute-score entry))
377 (puthash word entry spam-stat))))
378 (spam-stat-buffer-words))
379 (setq spam-stat-dirty t))
381 (defun spam-stat-buffer-change-to-non-spam ()
382 "Consider current buffer no longer spam but normal mail."
383 (setq spam-stat-nbad (1- spam-stat-nbad)
384 spam-stat-ngood (1+ spam-stat-ngood))
385 (maphash
386 (lambda (word count)
387 (let ((entry (gethash word spam-stat)))
388 (if (not entry)
389 (error "This buffer has unknown words in it.")
390 (spam-stat-set-good entry (+ (spam-stat-good entry) count))
391 (spam-stat-set-bad entry (- (spam-stat-bad entry) count))
392 (spam-stat-set-score entry (spam-stat-compute-score entry))
393 (puthash word entry spam-stat))))
394 (spam-stat-buffer-words))
395 (setq spam-stat-dirty t))
397 ;; Saving and Loading
399 (defun spam-stat-save (&optional force)
400 "Save the `spam-stat' hash table as lisp file.
401 With a prefix argument save unconditionally."
402 (interactive "P")
403 (when (or force spam-stat-dirty)
404 (with-temp-buffer
405 (let ((standard-output (current-buffer))
406 (font-lock-maximum-size 0))
407 (insert "(setq spam-stat-ngood "
408 (number-to-string spam-stat-ngood)
409 " spam-stat-nbad "
410 (number-to-string spam-stat-nbad)
411 " spam-stat (spam-stat-to-hash-table '(")
412 (maphash (lambda (word entry)
413 (prin1 (list word
414 (spam-stat-good entry)
415 (spam-stat-bad entry))))
416 spam-stat)
417 (insert ")))")
418 (write-file spam-stat-file)))
419 (setq spam-stat-dirty nil)))
421 (defun spam-stat-load ()
422 "Read the `spam-stat' hash table from disk."
423 ;; TODO: maybe we should warn the user if spam-stat-dirty is t?
424 (load-file spam-stat-file)
425 (setq spam-stat-dirty nil))
427 (defun spam-stat-to-hash-table (entries)
428 "Turn list ENTRIES into a hash table and store as `spam-stat'.
429 Every element in ENTRIES has the form \(WORD GOOD BAD) where WORD is
430 the word string, NGOOD is the number of good mails it has appeared in,
431 NBAD is the number of bad mails it has appeared in, GOOD is the number
432 of times it appeared in good mails, and BAD is the number of times it
433 has appeared in bad mails."
434 (let ((table (make-hash-table :test 'equal)))
435 (mapc (lambda (l)
436 (puthash (car l)
437 (spam-stat-make-entry (nth 1 l) (nth 2 l))
438 table))
439 entries)
440 table))
442 (defun spam-stat-reset ()
443 "Reset `spam-stat' to an empty hash-table.
444 This deletes all the statistics."
445 (interactive)
446 (setq spam-stat (make-hash-table :test 'equal)
447 spam-stat-ngood 0
448 spam-stat-nbad 0)
449 (setq spam-stat-dirty t))
451 ;; Scoring buffers
453 (defvar spam-stat-score-data nil
454 "Raw data used in the last run of `spam-stat-score-buffer'.")
456 (defsubst spam-stat-score-word (word)
457 "Return score for WORD.
458 The default score for unknown words is stored in
459 `spam-stat-unknown-word-score'."
460 (spam-stat-score (gethash word spam-stat)))
462 (defun spam-stat-buffer-words-with-scores ()
463 "Process current buffer, return the 15 most conspicuous words.
464 These are the words whose spam-stat differs the most from 0.5.
465 The list returned contains elements of the form \(WORD SCORE DIFF),
466 where DIFF is the difference between SCORE and 0.5."
467 (with-spam-stat-max-buffer-size
468 (with-syntax-table spam-stat-syntax-table
469 (let (result word score)
470 (maphash (lambda (word ignore)
471 (setq score (spam-stat-score-word word)
472 result (cons (list word score (abs (- score 0.5)))
473 result)))
474 (spam-stat-buffer-words))
475 (setq result (sort result (lambda (a b) (< (nth 2 b) (nth 2 a)))))
476 (setcdr (nthcdr 14 result) nil)
477 result))))
479 (defun spam-stat-score-buffer ()
480 "Return a score describing the spam-probability for this buffer."
481 (setq spam-stat-score-data (spam-stat-buffer-words-with-scores))
482 (let* ((probs (mapcar (lambda (e) (cadr e)) spam-stat-score-data))
483 (prod (apply #'* probs)))
484 (/ prod (+ prod (apply #'* (mapcar #'(lambda (x) (- 1 x))
485 probs))))))
487 (defun spam-stat-split-fancy ()
488 "Return the name of the spam group if the current mail is spam.
489 Use this function on `nnmail-split-fancy'. If you are interested in
490 the raw data used for the last run of `spam-stat-score-buffer',
491 check the variable `spam-stat-score-data'."
492 (condition-case var
493 (progn
494 (set-buffer spam-stat-buffer)
495 (goto-char (point-min))
496 (when (> (spam-stat-score-buffer) spam-stat-split-fancy-spam-threshhold)
497 (when (boundp 'nnmail-split-trace)
498 (mapc (lambda (entry)
499 (push entry nnmail-split-trace))
500 spam-stat-score-data))
501 spam-stat-split-fancy-spam-group))
502 (error (message "Error in spam-stat-split-fancy: %S" var)
503 nil)))
505 ;; Testing
507 (defun spam-stat-process-directory (dir func)
508 "Process all the regular files in directory DIR using function FUNC."
509 (let* ((files (directory-files dir t "^[^.]"))
510 (max (/ (length files) 100.0))
511 (count 0))
512 (with-temp-buffer
513 (dolist (f files)
514 (when (and (file-readable-p f)
515 (file-regular-p f)
516 (> (nth 7 (file-attributes f)) 0))
517 (setq count (1+ count))
518 (message "Reading %s: %.2f%%" dir (/ count max))
519 (insert-file-contents f)
520 (funcall func)
521 (erase-buffer))))))
523 (defun spam-stat-process-spam-directory (dir)
524 "Process all the regular files in directory DIR as spam."
525 (interactive "D")
526 (spam-stat-process-directory dir 'spam-stat-buffer-is-spam))
528 (defun spam-stat-process-non-spam-directory (dir)
529 "Process all the regular files in directory DIR as non-spam."
530 (interactive "D")
531 (spam-stat-process-directory dir 'spam-stat-buffer-is-non-spam))
533 (defun spam-stat-count ()
534 "Return size of `spam-stat'."
535 (interactive)
536 (hash-table-count spam-stat))
538 (defun spam-stat-test-directory (dir)
539 "Test all the regular files in directory DIR for spam.
540 If the result is 1.0, then all files are considered spam.
541 If the result is 0.0, non of the files is considered spam.
542 You can use this to determine error rates."
543 (interactive "D")
544 (let* ((files (directory-files dir t "^[^.]"))
545 (total (length files))
546 (score 0.0); float
547 (max (/ total 100.0)); float
548 (count 0))
549 (with-temp-buffer
550 (dolist (f files)
551 (when (and (file-readable-p f)
552 (file-regular-p f)
553 (> (nth 7 (file-attributes f)) 0))
554 (setq count (1+ count))
555 (message "Reading %.2f%%, score %.2f%%"
556 (/ count max) (/ score count))
557 (insert-file-contents f)
558 (when (> (spam-stat-score-buffer) 0.9)
559 (setq score (1+ score)))
560 (erase-buffer))))
561 (message "Final score: %d / %d = %f" score total (/ score total))))
563 ;; Shrinking the dictionary
565 (defun spam-stat-reduce-size (&optional count)
566 "Reduce the size of `spam-stat'.
567 This removes all words that occur less than COUNT from the dictionary.
568 COUNT defaults to 5"
569 (interactive)
570 (setq count (or count 5))
571 (maphash (lambda (key entry)
572 (when (< (+ (spam-stat-good entry)
573 (spam-stat-bad entry))
574 count)
575 (remhash key spam-stat)))
576 spam-stat)
577 (setq spam-stat-dirty t))
579 (defun spam-stat-install-hooks-function ()
580 "Install the spam-stat function hooks"
581 (interactive)
582 (add-hook 'nnmail-prepare-incoming-message-hook
583 'spam-stat-store-current-buffer)
584 (add-hook 'gnus-select-article-hook
585 'spam-stat-store-gnus-article-buffer))
587 (when spam-stat-install-hooks
588 (spam-stat-install-hooks-function))
590 (defun spam-stat-unload-hook ()
591 "Uninstall the spam-stat function hooks"
592 (interactive)
593 (remove-hook 'nnmail-prepare-incoming-message-hook
594 'spam-stat-store-current-buffer)
595 (remove-hook 'gnus-select-article-hook
596 'spam-stat-store-gnus-article-buffer))
598 (add-hook 'spam-stat-unload-hook 'spam-stat-unload-hook)
600 (provide 'spam-stat)
602 ;;; arch-tag: ff1d2200-8ddb-42fb-bb7b-1b5e20448554
603 ;;; spam-stat.el ends here