rem
stringlengths
0
322k
add
stringlengths
0
2.05M
context
stringlengths
8
228k
self._check(lgn, 'login') def TrainFolder(self, folder_name, isSpam): folder = IMAPFolder(folder_name) for msg in folder: if msg.isTrndAs(not isSpam): self.classifier.unlearn(msg.asTokens(), not isSpam) msg.notTrained() if not msg.isTrained(): self.classifier.learn(msg.asTokens(), isSpam) msg.trndAs(isSpam)
def Login(self): lgn = imap.login(options.imap_username, options.imap_password) self._check(lgn, 'login')
self.TrainFolder(fol, False)
folder = IMAPFolder(fol) folder.Train(self.classifier, False)
def Train(self): if options.verbose: t = time.time() if options.imap_ham_train_folders != "": ham_training_folders = options.imap_ham_train_folders.split() for fol in ham_training_folders: self.TrainFolder(fol, False) if options.imap_spam_train_folders != "": spam_training_folders = options.imap_spam_train_folders.spli...
self.TrainFolder(fol, True)
folder = IMAPFolder(fol) folder.Train(self.classifier, True)
def Train(self): if options.verbose: t = time.time() if options.imap_ham_train_folders != "": ham_training_folders = options.imap_ham_train_folders.split() for fol in ham_training_folders: self.TrainFolder(fol, False) if options.imap_spam_train_folders != "": spam_training_folders = options.imap_spam_train_folders.spli...
for msg in folder: (prob, clues) = self.classifier.spamprob(msg.asTokens(), evidence=True) msg.addSBHeaders(prob, clues) self._filterMessage(msg)
folder.Filter(self.classifier)
def Filter(self): if options.verbose: t = time.time() for filter_folder in options.imap_filter_folders.split(): folder = IMAPFolder(filter_folder, False) for msg in folder: (prob, clues) = self.classifier.spamprob(msg.asTokens(), evidence=True) # add headers and remember classification msg.addSBHeaders(prob, clues) # X...
def _moveMessage(self, old_msg, dest): msg = IMAPMessage(dest.uid, dest.folder_name, None) msg.setId(msg.extractTime()) msg.copy(old_msg) msg.Append() old_msg.Delete() def _filterMessage(self, msg): if msg.isClsfdHam(): print "untouched" pass elif msg.isClsfdSpam(): self._moveMessage(...
def Logout(self): # sign off if options.imap_expunge: imap.expunge() imap.logout()
imap_filter.Train()
def _filterMessage(self, msg): if msg.isClsfdHam(): # we leave ham alone print "untouched" pass elif msg.isClsfdSpam(): #XXX I actually think move should be a method on IMAPMessage #but I'm running out of time. self._moveMessage(msg, self.spam_folder) else: self._moveMessage(msg, self.unsure_folder)
fcntl.lockf(f, fcntl.LOCK_UN)
fcntl.flock(f, fcntl.LOCK_UN)
def mbox_train(h, path, is_spam, force): """Train bayes with a Unix mbox""" if loud: print " Reading as Unix mbox" import mailbox import fcntl # Open and lock the mailbox. Some systems require it be opened for # writes in order to assert an exclusive lock. f = file(path, "r+b") fcntl.flock(f, fcntl.LOCK_EX) mbox =...
(probability, clues) = state.bayes.spamprob(tokenizer.tokenize(message), evidence=True)
(probability, clues) = state.bayes.spamprob(tokenizer.tokenize(message),\ evidence=True)
def onClassify(self, file, text, which): """Classify an uploaded or pasted message.""" message = file or text message = message.replace('\r\n', '\n').replace('\r', '\n') # For Macs
ret = self.wordinfo.get(word) if not ret:
try: return self.wordinfo[word] except KeyError: ret = None
def _wordinfoget(self, word): ret = self.wordinfo.get(word) if not ret: r = self.db.get(word) if r: ret = self.WordInfoClass() ret.__setstate__(r) self.wordinfo[word] = ret return ret
self[options['pop3proxy','prob_header_name']] = prob
self[options['pop3proxy','prob_header_name']] = str(prob)
def addSBHeaders(self, prob, clues): '''Add hammie header, and remember message's classification. Also, add optional headers if needed.''' if prob < options['Categorization','ham_cutoff']: disposition = options['Hammie','header_ham_string'] elif prob > options['Categorization','spam_cutoff']: disposition = options['H...
Eg, python\\python-dev' will locate a python-dev subfolder in a python
Eg, 'python\\python-dev' will locate a python-dev subfolder in a python
def usage(): msg = """\
for msg in msginfoDB.db:
for msg in msginfoDB.db.keys():
def CalculateStats(self): self.Reset() for msg in msginfoDB.db: self.total += 1 m = self.__empty_msg() m.id = msg msginfoDB._getState(m) if m.c == 's': self.cls_spam += 1 if m.t == 0: self.fp += 1 elif m.c == 'h': self.cls_ham += 1 if m.t == 1: self.fn += 1 elif m.c == 'u': self.cls_unsure += 1 if m.t == 0: self.trn_un...
return val in header_strings or not val
self._options[sect, opt.lower()].set(val) return
def set(self, sect, opt, val=None): '''Set an option.''' if self.conversion_table.has_key((sect, opt.lower())): sect, opt = self.conversion_table[sect, opt.lower()] # Annoyingly, we have a special case. The notate_to and # notate_subject allowed values have to be set to the same # values as the header_x_ options, but...
global url_dict
def spamprob(self, wordstream, evidence=False, time_limit=None): global url_dict start_time = time.time() prob, clues = Classifier.spamprob(self, wordstream, True) if len(clues) < options["Classifier", "max_discriminators"] and \ prob > options["Categorization", "ham_cutoff"] and \ prob < options["Categorization", "spa...
print "Slurping:", url, "..."
print >> sys.stderr, "Slurping:", url, "..."
def spamprob(self, wordstream, evidence=False, time_limit=None): global url_dict start_time = time.time() prob, clues = Classifier.spamprob(self, wordstream, True) if len(clues) < options["Classifier", "max_discriminators"] and \ prob > options["Categorization", "ham_cutoff"] and \ prob < options["Categorization", "spa...
print "Slurped." except IOError:
print >> sys.stderr, "Slurped." except (IOError, socket.error):
def spamprob(self, wordstream, evidence=False, time_limit=None): global url_dict start_time = time.time() prob, clues = Classifier.spamprob(self, wordstream, True) if len(clues) < options["Classifier", "max_discriminators"] and \ prob > options["Categorization", "ham_cutoff"] and \ prob < options["Categorization", "spa...
print "Couldn't get", url
print >> sys.stderr, "Couldn't get", url
def spamprob(self, wordstream, evidence=False, time_limit=None): global url_dict start_time = time.time() prob, clues = Classifier.spamprob(self, wordstream, True) if len(clues) < options["Classifier", "max_discriminators"] and \ prob > options["Categorization", "ham_cutoff"] and \ prob < options["Categorization", "spa...
if __name__ == "__main__":
def main():
def setup(proxy={}, filename=None): if len(proxy) > 0: # build a new opener that uses a proxy requiring authorization proxy_support = urllib2.ProxyHandler({"http" : "http://%(user)s:%(pass)s@%(host)s:%(port)d" % proxy}) opener = urllib2.build_opener(proxy_support, urllib2.HTTPHandler) else: # Build a new opener without...
global proxy_info
def setup(proxy={}, filename=None): if len(proxy) > 0: # build a new opener that uses a proxy requiring authorization proxy_support = urllib2.ProxyHandler({"http" : "http://%(user)s:%(pass)s@%(host)s:%(port)d" % proxy}) opener = urllib2.build_opener(proxy_support, urllib2.HTTPHandler) else: # Build a new opener without...
self.imap_server.close()
self.close()
def SelectFolder(self, folder): """A method to point ensuing IMAP operations at a target folder.
except BadIMAPResponse:
except BadIMAPResponseError:
def folder_list(self): """Return a alphabetical list of all folders available on the server.""" response = self.list() try: all_folders = self.check_response("list", response) except BadIMAPResponse: # We want to keep going, so just print out a warning, and # return an empty list. print "Could not retrieve folder list....
response = imap.uid("STORE", id_to_remove, "+FLAGS.SILENT", "(\\Deleted \\Seen)")
response = self.imap_server.uid("STORE", id_to_remove, "+FLAGS.SILENT", "(\\Deleted \\Seen)")
def Save(self): """Save message to IMAP server.
response = imap.uid("SEARCH", "ALL")
response = self.imap_server.uid("SEARCH", "ALL")
def Save(self): """Save message to IMAP server.
num = DeleteField_Folder(folder, field_name)
num = DeleteField_Folder(driver, folder, field_name)
def main(): driver = mapi_driver.MAPIDriver() import getopt try: opts, args = getopt.getopt(sys.argv[1:], "dnsf:", ["no-mapi", "no-outlook", "no-folder"]) except getopt.error, e: print e print usage(driver) sys.exit(1) delete = show = False do_mapi = do_outlook = do_folder = True folder_names = [] for opt, opt_val in ...
Persistent except NameError:
from persistent import Persistent except ImportError:
def close(self): # We keep no resources open - nothing to do. pass
self.statekey = STATE_KEY
def __init__(self, db_name): self.statekey = STATE_KEY self.db_name = db_name self.load()
if hasattr(self.classifier, att):
if hasattr(self, "classifier") and hasattr(self.classifier, att):
def __getattr__(self, att): # We pretend that we are a classifier subclass. if hasattr(self.classifier, att): return getattr(self.classifier, att) raise AttributeError("ZODBClassifier object has no attribute '%s'" % (att,))
root = self.db.open().root()
self.conn = self.db.open() root = self.conn.root()
def load(self): import ZODB self.create_storage() self.db = ZODB.DB(self.storage) root = self.db.open().root() self.classifier = root.get(self.db_name) if self.classifier is None: # There is no classifier, so create one. if options["globals", "verbose"]: print >> sys.stderr, self.db_name, 'is a new ZODB' self.classifie...
get_transaction().commit() else: self.nham, self.nspam = self.classifier.wordinfo[self.statekey]
else:
def load(self): import ZODB self.create_storage() self.db = ZODB.DB(self.storage) root = self.db.open().root() self.classifier = root.get(self.db_name) if self.classifier is None: # There is no classifier, so create one. if options["globals", "verbose"]: print >> sys.stderr, self.db_name, 'is a new ZODB' self.classifie...
self.classifier.wordinfo[self.statekey] = (self.nham, self.nspam) get_transaction().commit()
import ZODB import transaction assert self.closed == False, "Can't store a closed database" if options["globals", "verbose"]: print >> sys.stderr, 'Persisting', self.db_name, 'state in database' transaction.commit()
def store(self): # It seems to me that the persistent classifier should store # the nham and nspam values, but that doesn't appear to be the # case, so work around that. This can be removed once I figure # out the problem. self.classifier.wordinfo[self.statekey] = (self.nham, self.nspam) get_transaction().commit()
assert word not in self.wordinfo, \
assert key not in self.wordinfo, \
def store(self): '''Place state into persistent store'''
os.path.join("~", ".hammiedb"))
os.path.join("~", ".hammiedb")
def bool(val): return not not val
pop3proxy.main(state.servers, state.proxyPorts, state.uiPort, state.launchUI)
try: try: pop3proxy.main(state.servers, state.proxyPorts, state.uiPort, state.launchUI) except SystemExit: print "pop3proxy service shutting down due to user request" except: ob = cStringIO.StringIO() traceback.print_exc(file=ob) message = "The pop3proxy service failed with an " \ "unexpected error\r\n\r\n" + ob.get...
def ServerThread(self): state = pop3proxy.state state.buildServerStrings() pop3proxy.main(state.servers, state.proxyPorts, state.uiPort, state.launchUI)
def __init__(self, db_name):
def __init__(self, db_name=None):
def __init__(self, db_name): self.db_name = db_name
attributes = self.db[msg.getDBKey()]
attributes = self.db[key]
def load_msg(self, msg): if self.db is not None: try: try: attributes = self.db[msg.getDBKey()] except pickle.UnpicklingError: # The old-style Outlook message info db didn't use # shelve, so get it straight from the dbm. if hasattr(self, "dbm"): attributes = self.dbm[msg.getDBKey()] else: raise except KeyError: # Set t...
attributes = self.dbm[msg.getDBKey()]
attributes = self.dbm[key]
def load_msg(self, msg): if self.db is not None: try: try: attributes = self.db[msg.getDBKey()] except pickle.UnpicklingError: # The old-style Outlook message info db didn't use # shelve, so get it straight from the dbm. if hasattr(self, "dbm"): attributes = self.dbm[msg.getDBKey()] else: raise except KeyError: # Set t...
self.db[msg.getDBKey()] = attributes
key = msg.getDBKey() assert key is not None, "None is not a valid key." self.db[key] = attributes
def store_msg(self, msg): if self.db is not None: msg.date_modified = time.time() attributes = [] for att in msg.stored_attributes: attributes.append((att, getattr(msg, att))) self.db[msg.getDBKey()] = attributes self.store()
"zodb" : (MessageInfoZODB, False, True),
def store(self): if self.db is not None: self.db.sync()
class Message(email.Message.Message):
class Message(object, email.Message.Message):
def database_type(): dn = ("Storage", "messageinfo_storage_file") # The storage options here may lag behind those in storage.py, # so we try and be more robust. If we can't use the same storage # method, then we fall back to pickle. nm, typ = storage.database_type((), default_name=dn) if typ not in _storage_types.keys...
def __init__(self, id=None, message_info_db=None):
def __init__(self, id=None):
def __init__(self, id=None, message_info_db=None): email.Message.Message.__init__(self)
if message_info_db is not None: self.message_info_db = message_info_db else: nm, typ = database_type() self.message_info_db = open_storage(nm, typ)
def __init__(self, id=None, message_info_db=None): email.Message.Message.__init__(self)
raise ValueError, "MsgId has already been set, cannot be changed"
raise ValueError, "MsgId has already been set, cannot be changed" + `self.id` + `id`
def setId(self, id): if self.id and self.id != id: raise ValueError, "MsgId has already been set, cannot be changed"
def addSBHeaders(self, prob, clues): """Add hammie header, and remember message's classification. Also, add optional headers if needed."""
def setDisposition(self, prob):
def addSBHeaders(self, prob, clues): """Add hammie header, and remember message's classification. Also, add optional headers if needed."""
evd.append("%r: %.2f" % (word, score))
try: evd.append("%r: %.2f" % (word, score)) except TypeError: evd.append("%r: %s" % (word, score))
def addSBHeaders(self, prob, clues): """Add hammie header, and remember message's classification. Also, add optional headers if needed."""
DEFAULTDB = os.path.expanduser(options.hammiefilter_persistent_storage_file)
DEFAULTDB = os.path.expanduser(options["Storage", "persistent_storage_file"])
def bool(val): return not not val
def classifyInbox(v, vmoveto, bayes, ldbname):
def classifyInbox(v, vmoveto, bayes, ldbname, notesindex):
def classifyInbox(v, vmoveto, bayes, ldbname): # the notesindex hash ensures that a message is looked at only once try: fp = open("%s.sbindex" % (ldbname), 'rb') except IOError, e: if e.errno != errno.ENOENT: raise notesindex = {} print "notesindex file not found, this is a first time run" print "No classification wi...
try: fp = open("%s.sbindex" % (ldbname), 'rb') except IOError, e: if e.errno != errno.ENOENT: raise notesindex = {} print "notesindex file not found, this is a first time run" print "No classification will be performed"
if len(notesindex.keys()) == 0:
def classifyInbox(v, vmoveto, bayes, ldbname): # the notesindex hash ensures that a message is looked at only once try: fp = open("%s.sbindex" % (ldbname), 'rb') except IOError, e: if e.errno != errno.ENOENT: raise notesindex = {} print "notesindex file not found, this is a first time run" print "No classification wi...
notesindex = pickle.load(fp) fp.close()
def classifyInbox(v, vmoveto, bayes, ldbname): # the notesindex hash ensures that a message is looked at only once try: fp = open("%s.sbindex" % (ldbname), 'rb') except IOError, e: if e.errno != errno.ENOENT: raise notesindex = {} print "notesindex file not found, this is a first time run" print "No classification wi...
message = "Subject: %s\r\n%s" % (subj, body)
message = "Subject: %s\r\n\r\n%s" % (subj, body)
def classifyInbox(v, vmoveto, bayes, ldbname): # the notesindex hash ensures that a message is looked at only once try: fp = open("%s.sbindex" % (ldbname), 'rb') except IOError, e: if e.errno != errno.ENOENT: raise notesindex = {} print "notesindex file not found, this is a first time run" print "No classification wi...
notesindex[nid] = disposition
notesindex[nid] = 'classified' try: print "%s spamprob is %s" % (subj[:30], prob) except UnicodeError: print "<subject not printed> spamprob is %s" % (prob)
def classifyInbox(v, vmoveto, bayes, ldbname): # the notesindex hash ensures that a message is looked at only once try: fp = open("%s.sbindex" % (ldbname), 'rb') except IOError, e: if e.errno != errno.ENOENT: raise notesindex = {} print "notesindex file not found, this is a first time run" print "No classification wi...
fp = open("timstone.nsf.sbindex", 'wb') pickle.dump(notesindex, fp) fp.close() def processAndTrain(v, vmoveto, bayes, is_spam):
def processAndTrain(v, vmoveto, bayes, is_spam, notesindex):
def classifyInbox(v, vmoveto, bayes, ldbname): # the notesindex hash ensures that a message is looked at only once try: fp = open("%s.sbindex" % (ldbname), 'rb') except IOError, e: if e.errno != errno.ENOENT: raise notesindex = {} print "notesindex file not found, this is a first time run" print "No classification wi...
str = "spam" else: str = "ham"
str = options.header_spam_string else: str = options.header_ham_string
def processAndTrain(v, vmoveto, bayes, is_spam): if is_spam: str = "spam" else: str = "ham" print "Training %s" % (str) docstomove = [] doc = v.GetFirstDocument() while doc: try: subj = doc.GetItemValue('Subject')[0] except: subj = 'No Subject' try: body = doc.GetItemValue('Body')[0] except: body = 'No Body' mess...
try: fp = open("%s.sbindex" % (ldbname), 'rb') except IOError, e: if e.errno != errno.ENOENT: raise notesindex = {} print "%s.sbindex file not found, this is a first time run" \ % (ldbname) print "No classification will be performed" else: notesindex = pickle.load(fp) fp.close()
def run(bdbname, useDBM, ldbname, rdbname, foldname, doTrain, doClassify): if useDBM: bayes = storage.DBDictClassifier(bdbname) else: bayes = storage.PickledClassifier(bdbname) sess = win32com.client.Dispatch("Lotus.NotesSession") sess.initialize() db = sess.GetDatabase("",ldbname) vinbox = db.getView('($Inbox)') vs...
sess.initialize()
try: sess.initialize() except pywintypes.com_error: print "Session aborted" sys.exit()
def run(bdbname, useDBM, ldbname, rdbname, foldname, doTrain, doClassify): if useDBM: bayes = storage.DBDictClassifier(bdbname) else: bayes = storage.PickledClassifier(bdbname) sess = win32com.client.Dispatch("Lotus.NotesSession") sess.initialize() db = sess.GetDatabase("",ldbname) vinbox = db.getView('($Inbox)') vs...
if doTrain: processAndTrain(vtrainspam, vspam, bayes, True) processAndTrain(vtrainham, vham, bayes, False)
def run(bdbname, useDBM, ldbname, rdbname, foldname, doTrain, doClassify): if useDBM: bayes = storage.DBDictClassifier(bdbname) else: bayes = storage.PickledClassifier(bdbname) sess = win32com.client.Dispatch("Lotus.NotesSession") sess.initialize() db = sess.GetDatabase("",ldbname) vinbox = db.getView('($Inbox)') vs...
classifyInbox(vinbox, vspam, bayes, ldbname)
classifyInbox(vinbox, vtrainspam, bayes, ldbname, notesindex) print "The Spambayes database currently has %s Spam and %s Ham" \ % (bayes.nspam, bayes.nham)
def run(bdbname, useDBM, ldbname, rdbname, foldname, doTrain, doClassify): if useDBM: bayes = storage.DBDictClassifier(bdbname) else: bayes = storage.PickledClassifier(bdbname) sess = win32com.client.Dispatch("Lotus.NotesSession") sess.initialize() db = sess.GetDatabase("",ldbname) vinbox = db.getView('($Inbox)') vs...
opts, args = getopt.getopt(sys.argv[1:], 'htcd:D:l:r:f:')
opts, args = getopt.getopt(sys.argv[1:], 'htcpd:D:l:r:f:')
def run(bdbname, useDBM, ldbname, rdbname, foldname, doTrain, doClassify): if useDBM: bayes = storage.DBDictClassifier(bdbname) else: bayes = storage.PickledClassifier(bdbname) sess = win32com.client.Dispatch("Lotus.NotesSession") sess.initialize() db = sess.GetDatabase("",ldbname) vinbox = db.getView('($Inbox)') vs...
if options["pop3proxy", "listen_ports"].find(portStr) != -1 or \ options["smtpproxy", "listen_ports"].find(portStr) != -1:
if portStr in options["pop3proxy", "listen_ports"] or \ portStr in options["smtpproxy", "listen_ports"]:
def move_to_next_free_port(port): # Increment port until we get to one that isn't taken. # I doubt this will work if there is a firewall that prevents # localhost connecting to particular ports, but I'm not sure # how else we can do this - Richie says that bind() doesn't # necessarily fail if the port is already bound....
def configure_outlook_express(key):
def configure_outlook_express():
def configure_outlook_express(key): """Configure OE to use the SpamBayes POP3 and SMTP proxies, and configure SpamBayes to proxy the servers that OE was connecting to.""" # OE stores its configuration in the registry, not a file. key = key + "\\Software\\Microsoft\\Internet Account Manager\\Accounts" import win32api ...
key = key + "\\Software\\Microsoft\\Internet Account Manager\\Accounts"
key = "Software\\Microsoft\\Internet Account Manager\\Accounts"
def configure_outlook_express(key): """Configure OE to use the SpamBayes POP3 and SMTP proxies, and configure SpamBayes to proxy the servers that OE was connecting to.""" # OE stores its configuration in the registry, not a file. key = key + "\\Software\\Microsoft\\Internet Account Manager\\Accounts" import win32api ...
reg = win32api.RegOpenKeyEx(win32con.HKEY_USERS, key)
reg = win32api.RegOpenKeyEx(win32con.HKEY_CURRENT_USER, key)
def configure_outlook_express(key): """Configure OE to use the SpamBayes POP3 and SMTP proxies, and configure SpamBayes to proxy the servers that OE was connecting to.""" # OE stores its configuration in the registry, not a file. key = key + "\\Software\\Microsoft\\Internet Account Manager\\Accounts" import win32api ...
subkey_name = "%s\\%s" % \ (key, win32api.RegEnumKey(reg, account_index))
subkey_name = "%s\\%s" % (key, win32api.RegEnumKey(reg, account_index))
def configure_outlook_express(key): """Configure OE to use the SpamBayes POP3 and SMTP proxies, and configure SpamBayes to proxy the servers that OE was connecting to.""" # OE stores its configuration in the registry, not a file. key = key + "\\Software\\Microsoft\\Internet Account Manager\\Accounts" import win32api ...
subkey = win32api.RegOpenKeyEx(win32con.HKEY_USERS, subkey_name, 0, win32con.KEY_READ | win32con.KEY_SET_VALUE)
subkey = win32api.RegOpenKeyEx(win32con.HKEY_CURRENT_USER, subkey_name, 0, win32con.KEY_READ | win32con.KEY_SET_VALUE)
def configure_outlook_express(key): """Configure OE to use the SpamBayes POP3 and SMTP proxies, and configure SpamBayes to proxy the servers that OE was connecting to.""" # OE stores its configuration in the registry, not a file. key = key + "\\Software\\Microsoft\\Internet Account Manager\\Accounts" import win32api ...
configure_pegasus_mail(pmail_ini_dir)
def configure_pocomail(): import win32api import win32con key = "Software\\Poco Systems Inc" pop_proxy = pop_proxy_port smtp_proxy = smtp_proxy_port reg = win32api.RegOpenKeyEx(win32con.HKEY_CURRENT_USER, key) subkey_name = "%s\\%s" % (key, win32api.RegEnumKey(reg, 0)) reg = win32api.RegOpenKe...
new_id = multiple_ids[-1] if new_id == "":
if multiple_ids: new_id = multiple_ids[-1] else:
def Save(self): '''Save message to imap server.''' # we can't actually update the message with IMAP # so what we do is create a new message and delete the old one if self.folder is None: raise RuntimeError, """Can't save a message that doesn't have a folder.""" if not self.id: raise RuntimeError, """Can't save a messag...
self.nspam += 1 else: self.nham += 1
self.nspam = int(self.nspam) + 1 else: self.nham = int(self.nham) + 1
def _add_msg(self, wordstream, is_spam): self.probcache = {} # nuke the prob cache if is_spam: self.nspam += 1 else: self.nham += 1
server = options["imap", "server"][0] username = options["imap", "username"][0]
server = options["imap", "server"] if len(server) > 0: server = server[0] username = options["imap", "username"] if len(username) > 0: username = username[0]
def run(): global imap try: opts, args = getopt.getopt(sys.argv[1:], 'hbtcvpl:e:i:d:D:') except getopt.error, msg: print >>sys.stderr, str(msg) + '\n\n' + __doc__ sys.exit() bdbname = options["pop3proxy", "persistent_storage_file"] useDBM = options["pop3proxy", "persistent_use_database"] doTrain = False doClassify = F...
pwd = options["imap", "password"][0]
pwd = options["imap", "password"] if len(pwd) > 0: pwd = pwd[0]
def run(): global imap try: opts, args = getopt.getopt(sys.argv[1:], 'hbtcvpl:e:i:d:D:') except getopt.error, msg: print >>sys.stderr, str(msg) + '\n\n' + __doc__ sys.exit() bdbname = options["pop3proxy", "persistent_storage_file"] useDBM = options["pop3proxy", "persistent_use_database"] doTrain = False doClassify = F...
import spambayes.message
def reversed(seq): seq = list(seq[:]) seq.reverse() return iter(seq)
_class=spambayes.message.SBHeaderMessage)
_class=message.SBHeaderMessage)
def onRetr(self, command, args, response): """Adds the judgement header based on the raw headers and body of the message.""" # Previous, we used '\n\r?\n' to detect the end of the headers in # case of broken emails that don't use the proper line separators, # and if we couldn't find it, then we assumed that the respons...
messageText, details = spambayes.message.\
messageText, details = message.\
def onRetr(self, command, args, response): """Adds the judgement header based on the raw headers and body of the message.""" # Previous, we used '\n\r?\n' to detect the end of the headers in # case of broken emails that don't use the proper line separators, # and if we couldn't find it, then we assumed that the respons...
self.names[i] = n
if self.names.has_key(i): print "Duplicate id",i,"for",n,"is", self.names[i] else: self.names[i] = n
def parseH(self, file): lex = shlex.shlex(file) lex.commenters = "//" token = " " while token is not None: token = lex.get_token() if token == "" or token is None: token = None else: if token=='define': n = lex.get_token() i = int(lex.get_token()) self.ids[n] = i self.names[i] = n if self.next_id<=i: self.next_id = i+1
if m.t == 0:
if m.t == False:
def CalculateStats(self): self.Reset() for msg in msginfoDB.db.keys(): self.total += 1 m = self.__empty_msg() m.id = msg msginfoDB._getState(m) if m.c == 's': self.cls_spam += 1 if m.t == 0: self.fp += 1 elif m.c == 'h': self.cls_ham += 1 if m.t == 1: self.fn += 1 elif m.c == 'u': self.cls_unsure += 1 if m.t == 0: self...
if m.t == 1:
if m.t == True:
def CalculateStats(self): self.Reset() for msg in msginfoDB.db.keys(): self.total += 1 m = self.__empty_msg() m.id = msg msginfoDB._getState(m) if m.c == 's': self.cls_spam += 1 if m.t == 0: self.fp += 1 elif m.c == 'h': self.cls_ham += 1 if m.t == 1: self.fn += 1 elif m.c == 'u': self.cls_unsure += 1 if m.t == 0: self...
elif m.t == 1:
elif m.t == True:
def CalculateStats(self): self.Reset() for msg in msginfoDB.db.keys(): self.total += 1 m = self.__empty_msg() m.id = msg msginfoDB._getState(m) if m.c == 's': self.cls_spam += 1 if m.t == 0: self.fp += 1 elif m.c == 'h': self.cls_ham += 1 if m.t == 1: self.fn += 1 elif m.c == 'u': self.cls_unsure += 1 if m.t == 0: self...
elif m.t == 0:
elif m.t == False:
def CalculateStats(self): self.Reset() for msg in msginfoDB.db.keys(): self.total += 1 m = self.__empty_msg() m.id = msg msginfoDB._getState(m) if m.c == 's': self.cls_spam += 1 if m.t == 0: self.fp += 1 elif m.c == 'h': self.cls_ham += 1 if m.t == 1: self.fn += 1 elif m.c == 'u': self.cls_unsure += 1 if m.t == 0: self...
perc_ham = 100.0 * self.cls_ham / self.total perc_spam = 100.0 * self.cls_spam / self.total perc_unsure = 100.0 * self.cls_unsure / self.total
not_trn_unsure = self.cls_unsure - self.trn_unsure_ham - \ self.trn_unsure_spam if self.cls_unsure: unsure_ham_perc = 100.0 * self.trn_unsure_ham / self.cls_unsure unsure_spam_perc = 100.0 * self.trn_unsure_spam / self.cls_unsure unsure_not_perc = 100.0 * not_trn_unsure / self.cls_unsure else: unsure_ham_perc = 0.0 uns...
def GetStats(self): if self.total == 0: return ["SpamBayes has processed zero messages"] chunks = [] push = chunks.append perc_ham = 100.0 * self.cls_ham / self.total perc_spam = 100.0 * self.cls_spam / self.total perc_unsure = 100.0 * self.cls_unsure / self.total format_dict = { 'perc_spam': perc_spam, 'perc_ham': per...
'perc_spam': perc_spam, 'perc_ham': perc_ham, 'perc_unsure': perc_unsure, 'num_seen': self.total
'num_seen' : self.total, 'correct' : self.total - (self.cls_unsure + self.fp + self.fn), 'incorrect' : self.cls_unsure + self.fp + self.fn, 'unsure_ham_perc' : unsure_ham_perc, 'unsure_spam_perc' : unsure_spam_perc, 'unsure_not_perc' : unsure_not_perc, 'not_trn_unsure' : not_trn_unsure, 'trn_total' : (self.trn_ham + se...
def GetStats(self): if self.total == 0: return ["SpamBayes has processed zero messages"] chunks = [] push = chunks.append perc_ham = 100.0 * self.cls_ham / self.total perc_spam = 100.0 * self.cls_spam / self.total perc_unsure = 100.0 * self.cls_unsure / self.total format_dict = { 'perc_spam': perc_spam, 'perc_ham': per...
for num, key in [(self.total, "sp1"), (self.trn_ham, "sp2"), (self.trn_spam, "sp3"), (self.trn_unsure_ham, "sp4"), (self.fp, "sp5"), (self.fn, "sp6")]: if num == 1:
for num, key in [("num_seen", "sp1"), ("correct", "sp2"), ("incorrect", "sp3"), ("fp", "sp4"), ("fn", "sp5"), ("trn_unsure_ham", "sp6"), ("trn_unsure_spam", "sp7"), ("not_trn_unsure", "sp8"), ("trn_total", "sp9"), ]: if format_dict[num] == 1:
def GetStats(self): if self.total == 0: return ["SpamBayes has processed zero messages"] chunks = [] push = chunks.append perc_ham = 100.0 * self.cls_ham / self.total perc_spam = 100.0 * self.cls_spam / self.total perc_unsure = 100.0 * self.cls_unsure / self.total format_dict = { 'perc_spam': perc_spam, 'perc_ham': per...
for num, key in [(self.fp, "wp1"), (self.fn, "wp2")]: if num == 1: format_dict[key] = 'was a'
for num, key in [("correct", "wp1"), ("incorrect", "wp2"), ("not_trn_unsure", "wp3"), ]: if format_dict[num] == 1: format_dict[key] = 'was'
def GetStats(self): if self.total == 0: return ["SpamBayes has processed zero messages"] chunks = [] push = chunks.append perc_ham = 100.0 * self.cls_ham / self.total perc_spam = 100.0 * self.cls_spam / self.total perc_unsure = 100.0 * self.cls_unsure / self.total format_dict = { 'perc_spam': perc_spam, 'perc_ham': per...
push("SpamBayes has processed %(num_seen)d message%(sp1)s - " \ "%(cls_ham)d (%(perc_ham).0f%%) good, " \ "%(cls_spam)d (%(perc_spam).0f%%) spam " \ "and %(cls_unsure)d (%(perc_unsure)d%%) unsure." % format_dict) push("%(trn_ham)d message%(sp2)s were manually " \ "classified as good (%(fp)d %(wp1)s false positive%(sp5)...
push("SpamBayes has classified a total of " \ "%(num_seen)d message%(sp1)s:" \ "<br/>&nbsp;&nbsp;&nbsp;&nbsp;%(cls_ham)d " \ "(%(perc_cls_ham).0f%% of total) good" \ "<br/>&nbsp;&nbsp;&nbsp;&nbsp;%(cls_spam)d " \ "(%(perc_cls_spam).0f%% of total) spam" \ "<br/>&nbsp;&nbsp;&nbsp;&nbsp;%(cls_unsure)d " \ "(%(perc_cls_uns...
def GetStats(self): if self.total == 0: return ["SpamBayes has processed zero messages"] chunks = [] push = chunks.append perc_ham = 100.0 * self.cls_ham / self.total perc_spam = 100.0 * self.cls_spam / self.total perc_unsure = 100.0 * self.cls_unsure / self.total format_dict = { 'perc_spam': perc_spam, 'perc_ham': per...
cmdclass = {'build_py': install_scripts},
cmdclass = {'install_scripts': install_scripts},
def run(self): err = False for s in self.old_scripts: s = os.path.join(self.install_dir, s) if os.path.exists(s): print >> sys.stderr, "Error: old script", s, "still exists." err = True if err: print >>sys.stderr, "Do you want to delete these scripts? (y/n)" answer = raw_input("") if answer == "y": for s in self.old_sc...
def filter(self, msg, header=DISPHEADER, cutoff=SPAM_THRESHOLD):
def filter(self, msg, header=DISPHEADER, spam_cutoff=SPAM_THRESHOLD, ham_cutoff=HAM_THRESHOLD):
def filter(self, msg, header=DISPHEADER, cutoff=SPAM_THRESHOLD): """Score (judge) a message and add a disposition header.
if prob < cutoff:
if prob < ham_cutoff:
def filter(self, msg, header=DISPHEADER, cutoff=SPAM_THRESHOLD): """Score (judge) a message and add a disposition header.
else:
elif prob > spam_cutoff:
def filter(self, msg, header=DISPHEADER, cutoff=SPAM_THRESHOLD): """Score (judge) a message and add a disposition header.
if type(self.allowed_values) in types.StringTypes:
if isinstance(self.allowed_values, types.StringTypes):
def convert(self, value): '''Convert value from a string to the appropriate type.''' svt = type(self.value) if svt == type(value): # already the correct type return value if type(self.allowed_values) == types.TupleType and \ value in self.allowed_values: # already correct type return value if self.is_boolean(): if str(...
vals = value.split()
if isinstance(value, types.TupleType): vals = list(value) else: vals = value.split()
def convert(self, value): '''Convert value from a string to the appropriate type.''' svt = type(self.value) if svt == type(value): # already the correct type return value if type(self.allowed_values) == types.TupleType and \ value in self.allowed_values: # already correct type return value if self.is_boolean(): if str(...
s, h = score(h, u, reverse)
s, g = score(h, u, reverse)
def main(): """Main program; parse options and go.""" try: opts, args = getopt.getopt(sys.argv[1:], 'hdfg:s:p:u:r') except getopt.error, msg: usage(2, msg) if not opts: usage(2, "No options given") pck = DEFAULTDB good = [] spam = [] unknown = [] reverse = 0 do_filter = usedb = False for opt, arg in opts: if opt == '...
hams += h
hams += g
def main(): """Main program; parse options and go.""" try: opts, args = getopt.getopt(sys.argv[1:], 'hdfg:s:p:u:r') except getopt.error, msg: usage(2, msg) if not opts: usage(2, "No options given") pck = DEFAULTDB good = [] spam = [] unknown = [] reverse = 0 do_filter = usedb = False for opt, arg in opts: if opt == '...
("TestDriver", "best_cutoff_fn_weight",
("best_cutoff_fn_weight",
def bool(val): return not not val
("TestDriver", "best_cutoff_unsure_weight",
("best_cutoff_unsure_weight",
def bool(val): return not not val
setattr(options, old_name, opt[2])
setattr(options, old_name, value)
def load_defaults(self): '''Load default values (stored in the module itself).''' for section, opts in defaults.items(): for opt in opts: o = Option(opt[0], opt[1], opt[2], opt[3], opt[4], opt[5], opt[6]) # start with default value o.set(opt[2]) self._options[section, opt[0]] = o # A (really ugly) bit of backwards comp...
value = c.get(section, option)
fetcher, converter = goodopts[new_name] value = getattr(c, fetcher)(section, option) if converter is not None: value = converter(value)
def _update(self): nerrors = 0 c = self._config for section in c.sections(): if section not in all_options: _warn("config file has unknown section %r" % section) nerrors += 1 continue goodopts = all_options[section] for option in c.options(section): if option not in goodopts: _warn("config file has unknown option %r in...
state = INDEXTOSTATEIMAGEMASK(IIL_UNCHECKED) mask = commctrl.TVIS_STATEIMAGEMASK buf, extra = PackTVITEM(info[0], state, mask, None, None, None, None, None) win32gui.SendMessage(self.list, commctrl.TVM_SETITEM, 0, buf)
self.UnselectItem(info)
def OnCommand(self, hwnd, msg, wparam, lparam): FolderSelector_Parent.OnCommand(self, hwnd, msg, wparam, lparam) id = win32api.LOWORD(wparam) id_name = self._GetIDName(id) code = win32api.HIWORD(wparam)
try: names = [] num_checked = 0 for info, spec in self._YieldCheckedChildren(): num_checked += 1 if len(names) < 20: names.append(info[3]) status_string = "%s%s %d folder" % (self.select_desc_noun, self.select_desc_noun_suffix, num_checked) if num_checked != 1: status_string += "s" self.SetDlgItemText("IDC_STATUS1", s...
import timer self.timer_id = None timer.kill_timer(id) self._CheckSelectionsValid() names = [] num_checked = 0 for info, spec in self._YieldCheckedChildren(): num_checked += 1 if len(names) < 20: names.append(info[3]) status_string = "%s%s %d folder" % (self.select_desc_noun, self.select_desc_noun_suffix, num_checked...
def _DoUpdateStatus(self, id, timeval): try: names = [] num_checked = 0 for info, spec in self._YieldCheckedChildren(): num_checked += 1 if len(names) < 20: names.append(info[3])
if self.single_select: self.OnOK()
pass
def OnNotify(self, msg, hwnd, wparam, lparam): FolderSelector_Parent.OnNotify(self, hwnd, msg, wparam, lparam) format = "iii" buf = win32gui.PyMakeBuffer(struct.calcsize(format), lparam) hwndFrom, id, code = struct.unpack(format, buf) code += 0x4f0000 # hrm - wtf - commctrl uses this, and it works with mfc. *sigh* id_...
d=FolderSelector(0, mgr, ids, single_select = False)
d=FolderSelector(0, mgr, ids, single_select = single_select)
def Test(): import sys, os sys.path.append(os.path.abspath(os.path.join(os.path.dirname(sys.argv[0]), ".."))) import manager mgr = manager.GetManager() if mgr.dialog_parser is None: import dialogs mgr.dialog_parser = dialogs.LoadDialogs() ids = [("0000","0000"),] # invalid ID for testing. d=FolderSelector(0, mgr, ids,...
d=FolderSelector(0, mgr, ids, single_select = False, checkbox_state = include_sub)
d=FolderSelector(0, mgr, ids, single_select = single_select, checkbox_state = include_sub)
def Test(): import sys, os sys.path.append(os.path.abspath(os.path.join(os.path.dirname(sys.argv[0]), ".."))) import manager mgr = manager.GetManager() if mgr.dialog_parser is None: import dialogs mgr.dialog_parser = dialogs.LoadDialogs() ids = [("0000","0000"),] # invalid ID for testing. d=FolderSelector(0, mgr, ids,...
header_strings = (options["Headers", "header_ham_string"], options["Headers", "header_spam_string"], options["Headers", "header_unsure_string"]) notate_to = options.get_option("Headers", "notate_to") notate_subject = options.get_option("Headers", "notate_subject") notate_to.allowed_values = header_strings notate_subjec...
def load_options(): global optionsPathname, options options = OptionsClass() options.load_defaults(defaults) # Maybe we are reloading. if optionsPathname: options.merge_file(optionsPathname) alternate = None if hasattr(os, 'getenv'): alternate = os.getenv('BAYESCUSTOMIZE') if alternate: filenames = alternate.split(os...
types.StringsTypes):
types.StringTypes):
def takeMessage(self, key, fromcorpus, fromCache=False): '''Move a Message from another corpus to this corpus''' msg = fromcorpus[key] msg.load() # ensure that the substance has been loaded