Capstone Project: Build Inbox Guardian
You have arrived at the flagship capstone milestone of Workshop 1. Rather than writing disconnected toy scripts, you will now synthesize all 7 chapters—variables, types, string methods, branching conditions, loops, structured collections, and modular functions—into an end-to-end command-line application: INBOX GUARDIAN. You will architect, implement, test, and debug a rule-based email threat scanner capable of parsing raw messages, extracting structural heuristics, computing weighted risk scores, and generating security quarantine verdicts.
- 01Synthesize all Workshop 1 competencies into a complete, modular, command-line Python application
- 02Implement an end-to-end heuristic pipeline: text normalization, keyword matching, structural anomaly detection, and classification
- 03Calculate structural threat heuristics including uppercase character density and exclamation mark frequency with zero-division safeguards
- 04Manage in-memory datasets using lists of dictionaries to log scan histories and generate executive summary statistics
- 05Differentiate deterministic rule-based heuristic engineering from future statistical machine learning classification models
- 06Handle critical production edge cases: zero-alphabetic strings, empty inboxes, and case-obfuscation attacks
8.1 System Architecture: The Heuristic Rule-Based Pipeline
8.2 Module 1 & 2: Text Normalization & Keyword Matching
Scanning normalized text against weighted threat categories.
def scan_keywords(text, keyword_weights):
"""Scans text for keywords and returns accumulated weight and matched terms."""
cleaned = text.strip().lower()
score = 0
matched = []
for keyword, weight in keyword_weights.items():
if keyword in cleaned:
matched.append(keyword)
score += weight
return score, matched
# Threat dictionary with weighted risks
RULES = {
"urgent": 25,
"verify account": 30,
"free prize": 35,
"wire transfer": 40,
"password expired": 25
}
sample = " URGENT: Please verify account access to claim prize! "
pts, terms = scan_keywords(sample, RULES)
print("Detected Terms :", terms)
print("Keyword Points :", pts)- 1.Line 3: Strips and converts sample to lowercase.
- 2.Lines 7-10: Checks each keyword; finds 'urgent' (+25) and 'verify account' (+30).
- 3.Line 12: Returns accumulated score 55 and list of matched terms.
Detected Terms : ['urgent', 'verify account'] Keyword Points : 55
• Substring collision: 'free' would match 'freeze'. In production regex or token matching, word boundaries are checked. For our foundations workshop, phrase matching handles multi-word triggers like 'verify account'.
Why it happens: The 'in' operator tests substring presence in O(n) time.
8.3 Module 3 & 4: Structural Anomaly Detection & Risk Classification
Calculating uppercase ratio and exclamation density safely.
def calculate_structural_risk(text):
"""Calculates structural risk points based on caps ratio and exclamation marks."""
points = 0
letters = [c for c in text if c.isalpha()]
total_letters = len(letters)
# Zero-division defensive guard!
if total_letters > 0:
upper_count = len([c for c in letters if c.isupper()])
caps_ratio = upper_count / total_letters
if caps_ratio > 0.30: # Over 30% uppercase
points += 20
else:
caps_ratio = 0.0
exclamation_count = text.count("!")
if exclamation_count >= 2:
points += 15
return points, caps_ratio, exclamation_count
# Test on shouting email
sample_shouting = "URGENT ACTION NEEDED IMMEDIATELY!!!"
pts, ratio, ex_count = calculate_structural_risk(sample_shouting)
print(f"Caps Ratio : {ratio:.1%} (+{pts} pts, {ex_count} exclamations)")- 1.Line 4: Extracts all alphabetic characters.
- 2.Line 8: Verifies total_letters > 0 before dividing.
- 3.Line 10: Caps ratio is 100% (> 30%) -> adds 20 points.
- 4.Line 17: Exclamation count is 3 (>= 2) -> adds 15 points.
- 5.Line 24: Outputs 100.0% ratio and 35 risk points.
Caps Ratio : 100.0% (+35 pts, 3 exclamations)
• Non-alphabetic input: If text is '123456789', total_letters is 0. Without the guard, upper_count / total_letters causes ZeroDivisionError: division by zero.
Why it happens: Heuristic rules combine text statistics with keyword scores to create resilient multi-factor classifiers.
8.4 Module 5: Batch Scanning & Summary Statistics
Batch scanning email records and accumulating departmental statistics.
inbox_batch = [
{"id": "MSG-01", "sender": "support@datacorp.com", "body": "Meeting agenda for today at 3pm."},
{"id": "MSG-02", "sender": "billing@external.xyz", "body": "URGENT: Verify account or access suspended immediately!!!"},
{"id": "MSG-03", "sender": "colleague@datacorp.com", "body": "Please review the attached project slide draft."}
]
def classify_risk(total_score):
if total_score >= 60:
return "QUARANTINE"
elif total_score >= 30:
return "SUSPICIOUS"
return "CLEAN"
# Batch audit
history = []
for msg in inbox_batch:
# Simulated score for demonstration
score = 85 if "urgent" in msg["body"].lower() else 5
verdict = classify_risk(score)
# Log record
history.append({
"id": msg["id"],
"sender": msg["sender"],
"score": score,
"verdict": verdict
})
print("=== BATCH AUDIT REPORT ===")
for rec in history:
print(f"[{rec['id']}] {rec['verdict']:<12} | Score: {rec['score']:>2} | Sender: {rec['sender']}")- 1.Lines 1-5: Defines batch dataset of simulated incoming messages.
- 2.Lines 15-26: Loops over batch, computes scores, and logs to history list of dictionaries.
- 3.Lines 28-30: Emits formatted tabular report.
=== BATCH AUDIT REPORT === [MSG-01] CLEAN | Score: 5 | Sender: support@datacorp.com [MSG-02] QUARANTINE | Score: 85 | Sender: billing@external.xyz [MSG-03] CLEAN | Score: 5 | Sender: colleague@datacorp.com
• Empty batch stream: If inbox_batch is empty `[]`, calculating average score by dividing by `len(inbox_batch)` raises ZeroDivisionError! Always verify `if len(inbox_batch) > 0:` before computing averages.
Why it happens: Lists of dictionaries provide a clean in-memory database representation.
8.5 Module 6: The Interactive Terminal Menu Loop
Practice exercise
Work through the exercise before starting the chapter assignment
Exercise 8: Classification Decision Boundary
basicModify the starter code to implement classify_message(score) which returns 'QUARANTINE' if score >= 60, 'SUSPICIOUS' if score >= 30, and 'CLEAN' otherwise. Test with score = 75 and print the returned status.
Inbox Guardian Enterprise: Heuristic Threat Auditor
You are the lead security software engineer at the Center of Excellence. You have been commissioned to build the production engine for INBOX GUARDIAN. The tool must parse raw incoming messages, compute multi-factor threat scores (combining weighted keywords, uppercase density, and exclamation marks), assign quarantine verdicts, log scan histories in memory, and generate an executive risk report.
- Define multi-tier keyword dictionary: {'urgent': 25, 'verify account': 30, 'free prize': 35, 'wire transfer': 40, 'suspended': 25}.
- Implement scan_message(text: str, keyword_rules: dict) -> dict:
- - Normalize text with .strip() and .lower().
- - Accumulate keyword score and store matched terms in a list.
- - Calculate uppercase ratio safely (guarding against zero-division): +20 pts if caps ratio > 0.30.
- - Calculate exclamation density: +15 pts if text.count('!') >= 2.
- - Compute total_risk = keyword_score + structural_score (capped at 100).
- - Determine verdict: 'QUARANTINE' if total_risk >= 60, 'SUSPICIOUS' if total_risk >= 30, else 'CLEAN'.
- - Return result dictionary: {'text': text[:45], 'score': total_risk, 'matched': matched, 'verdict': verdict}.
- Batch process a sample list of 4 simulated emails:
- 1. 'Reminder: Data Science workshop begins at 10 AM in Lab 3.'
- 2. 'URGENT: Your account has been suspended! Please verify credentials immediately!'
- 3. 'Congratulations! You won a free prize. Claim your wire transfer now.'
- 4. 'Please review the attached project draft when you have a moment.'
- Store all result dictionaries into an in-memory scan_history list.
- Generate an Executive Security Summary: Total Scanned, Quarantine Count, Suspicious Count, Clean Count, and Threat Ratio percentage.
- 1.Zero alphabetic characters: Message '123456789 !!!' must not crash with ZeroDivisionError when computing uppercase ratio.
- 2.Empty text: Blank input '' must return score = 0, verdict = 'CLEAN'.
- 3.Capping risk score: Ensure total_risk does not exceed 100.
# Chapter 8 Capstone Assignment: INBOX GUARDIAN ENTERPRISE
# Center of Excellence: Data Science & AI
KEYWORDS = {
"urgent": 25,
"verify account": 30,
"free prize": 35,
"wire transfer": 40,
"suspended": 25
}
SAMPLE_EMAILS = [
"Reminder: Data Science workshop begins at 10 AM in Lab 3.",
"URGENT: Your account has been suspended! Please verify credentials immediately!",
"Congratulations! You won a free prize. Claim your wire transfer now.",
"Please review the attached project draft when you have a moment."
]
# TODO: Step 1 - Define scan_message(text, keyword_rules)
# TODO: Step 2 - Implement keyword matching and structural heuristics with zero-division guard
# TODO: Step 3 - Assign verdict (QUARANTINE, SUSPICIOUS, CLEAN)
# TODO: Step 4 - Batch scan SAMPLE_EMAILS and append results to scan_history list
# TODO: Step 5 - Print formatted audit roster and executive summary metrics
Chapter summary
Key concepts and syntax cards for review
- 01Rule-based systems use deterministic heuristic logic (keywords + structural thresholds) to make automated decisions.
- 02Always guard against zero-division when calculating ratios like uppercase density: verify denominator > 0.
- 03The modular architecture separates sanitization, keyword scoring, structural features, and classification.
- 04In-memory datasets (lists of dictionaries) enable high-throughput batch inspection and statistical summaries.
- 05Heuristic rule engineering provides the foundation for feature engineering in modern machine learning.
result = scan_message(text, rules)Encapsulating multi-factor security heuristics into pure modular functions.ratio = upper_count / len(letters) if len(letters) > 0 else 0.0Zero-division guarded density formula.history.append({'score': total, 'verdict': verdict})Appending structured audit dictionaries to historical logs.Knowledge check
Verify your grasp of the chapter concepts
What mathematical protection is essential when calculating text character ratios?
What is the primary architectural difference between heuristics and machine learning?
How is an email audit history best represented in native Python memory?
Programiz Python programming guide
Visit Programiz for additional Python syntax examples and language reference