Spaces:
Runtime error
Runtime error
Delete Version_3
Browse files- Version_3/app.py +0 -119
- Version_3/config.py +0 -22
- Version_3/models/model_quantized.onnx +0 -3
- Version_3/pipeline/__pycache__/tier1_fast_filter.cpython-313.pyc +0 -0
- Version_3/pipeline/__pycache__/tier2_extraction.cpython-313.pyc +0 -0
- Version_3/pipeline/__pycache__/tier3_inference.cpython-313.pyc +0 -0
- Version_3/pipeline/__pycache__/tier4_scoring.cpython-313.pyc +0 -0
- Version_3/pipeline/tier1_fast_filter.py +0 -18
- Version_3/pipeline/tier2_extraction.py +0 -36
- Version_3/pipeline/tier3_inference.py +0 -59
- Version_3/pipeline/tier4_scoring.py +0 -30
Version_3/app.py
DELETED
|
@@ -1,119 +0,0 @@
|
|
| 1 |
-
import os
|
| 2 |
-
import sys
|
| 3 |
-
import time
|
| 4 |
-
from fastapi import FastAPI, HTTPException
|
| 5 |
-
from pydantic import BaseModel
|
| 6 |
-
|
| 7 |
-
# =====================================================================
|
| 8 |
-
# SAFE PIPELINE IMPORT MATRIX
|
| 9 |
-
# =====================================================================
|
| 10 |
-
try:
|
| 11 |
-
from pipeline.tier1_fast_filter import check_fast_filter
|
| 12 |
-
from pipeline.tier2_extraction import sanitize_text, extract_metadata_flags
|
| 13 |
-
from pipeline.tier3_inference import neural_engine
|
| 14 |
-
from pipeline.tier4_scoring import calculate_final_verdict
|
| 15 |
-
except ModuleNotFoundError:
|
| 16 |
-
from Version_3.pipeline.tier1_fast_filter import check_fast_filter
|
| 17 |
-
from Version_3.pipeline.tier2_extraction import sanitize_text, extract_metadata_flags
|
| 18 |
-
from Version_3.pipeline.tier3_inference import neural_engine
|
| 19 |
-
from Version_3.pipeline.tier4_scoring import calculate_final_verdict
|
| 20 |
-
|
| 21 |
-
# =====================================================================
|
| 22 |
-
# INITIALIZE APP INSTANCE
|
| 23 |
-
# =====================================================================
|
| 24 |
-
app = FastAPI(title="Real-Time NLP Phishing Defender")
|
| 25 |
-
|
| 26 |
-
class MessagePayload(BaseModel):
|
| 27 |
-
message_id: str
|
| 28 |
-
sender_domain: str
|
| 29 |
-
display_name: str
|
| 30 |
-
raw_text: str
|
| 31 |
-
|
| 32 |
-
# =====================================================================
|
| 33 |
-
# UNIFIED ROUTE ENDPOINT
|
| 34 |
-
# =====================================================================
|
| 35 |
-
@app.post("/analyze")
|
| 36 |
-
async def analyze_message(payload: MessagePayload):
|
| 37 |
-
start_time = time.perf_counter()
|
| 38 |
-
|
| 39 |
-
# --- TIER 1: Fast Filter ---
|
| 40 |
-
t1_result = check_fast_filter(payload.sender_domain, payload.raw_text)
|
| 41 |
-
if t1_result["bypassed"]:
|
| 42 |
-
latency_ms = (time.perf_counter() - start_time) * 1000
|
| 43 |
-
return {
|
| 44 |
-
"message_id": payload.message_id,
|
| 45 |
-
"verdict": t1_result["verdict"],
|
| 46 |
-
"latency_ms": round(latency_ms, 2),
|
| 47 |
-
"bypassed_at_tier": 1
|
| 48 |
-
}
|
| 49 |
-
|
| 50 |
-
# --- TIER 2: Extraction & Sanitization ---
|
| 51 |
-
clean_text = sanitize_text(payload.raw_text)
|
| 52 |
-
flags = extract_metadata_flags(payload.sender_domain, payload.display_name, clean_text)
|
| 53 |
-
|
| 54 |
-
# --- TIER 3: Neural Inference ---
|
| 55 |
-
nlp_prob = neural_engine.predict_phishing_prob(clean_text)
|
| 56 |
-
|
| 57 |
-
# --- TIER 4: Scoring Matrix ---
|
| 58 |
-
final_result = calculate_final_verdict(nlp_prob, flags)
|
| 59 |
-
|
| 60 |
-
latency_ms = (time.perf_counter() - start_time) * 1000
|
| 61 |
-
|
| 62 |
-
return {
|
| 63 |
-
"message_id": payload.message_id,
|
| 64 |
-
"verdict": final_result["verdict"],
|
| 65 |
-
"risk_score": final_result["risk_score"],
|
| 66 |
-
"details": final_result["breakdown"],
|
| 67 |
-
"latency_ms": round(latency_ms, 2)
|
| 68 |
-
}
|
| 69 |
-
|
| 70 |
-
# =====================================================================
|
| 71 |
-
# STANDALONE LOCAL EXECUTION GATEWAY
|
| 72 |
-
# =====================================================================
|
| 73 |
-
if __name__ == "__main__":
|
| 74 |
-
# Check if we explicitly want to run in local interactive mode
|
| 75 |
-
if len(sys.argv) > 1 and sys.argv[1] == "--cli":
|
| 76 |
-
print("\n" + "="*50)
|
| 77 |
-
print(" CHIMERA 2.0 LOCAL TERMINAL ENGINE LOADED ")
|
| 78 |
-
print(" (Press Ctrl+C at any time to exit) ")
|
| 79 |
-
print("="*50 + "\n")
|
| 80 |
-
|
| 81 |
-
while True:
|
| 82 |
-
try:
|
| 83 |
-
domain = input("1. Enter Sender Domain: ").strip()
|
| 84 |
-
name = input("2. Enter Display Name: ").strip()
|
| 85 |
-
text = input("3. Enter Email Content Text: ").strip()
|
| 86 |
-
|
| 87 |
-
if not text:
|
| 88 |
-
print("\nError: Text cannot be empty.\n")
|
| 89 |
-
continue
|
| 90 |
-
|
| 91 |
-
start = time.perf_counter()
|
| 92 |
-
|
| 93 |
-
# Run the exact pipeline logic defined in your endpoint
|
| 94 |
-
t1 = check_fast_filter(domain, text)
|
| 95 |
-
if t1["bypassed"]:
|
| 96 |
-
latency = (time.perf_counter() - start) * 1000
|
| 97 |
-
print(f"\n[🛑 TIER 1 HIT] Verdict: {t1['verdict']} | Latency: {round(latency, 2)} ms\n" + "-"*50)
|
| 98 |
-
continue
|
| 99 |
-
|
| 100 |
-
clean = sanitize_text(text)
|
| 101 |
-
flags = extract_metadata_flags(domain, name, clean)
|
| 102 |
-
nlp_prob = neural_engine.predict_phishing_prob(clean)
|
| 103 |
-
final = calculate_final_verdict(nlp_prob, flags)
|
| 104 |
-
|
| 105 |
-
latency = (time.perf_counter() - start) * 1000
|
| 106 |
-
print(f"\n" + "═"*15 + " ANALYSIS RESULT " + "═"*15)
|
| 107 |
-
print(f"VERDICT: {final['verdict']}")
|
| 108 |
-
print(f"RISK SCORE: {final['risk_score']}")
|
| 109 |
-
print(f"LATENCY: {round(latency, 2)} ms")
|
| 110 |
-
print(f"DETAILS: {final['breakdown']}")
|
| 111 |
-
print("═"*47 + "\n")
|
| 112 |
-
|
| 113 |
-
except KeyboardInterrupt:
|
| 114 |
-
print("\nExiting interactive mode.")
|
| 115 |
-
break
|
| 116 |
-
else:
|
| 117 |
-
# Fallback default behavior to run the web server if no flag is provided
|
| 118 |
-
import uvicorn
|
| 119 |
-
uvicorn.run(app, host="0.0.0.0", port=8000)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Version_3/config.py
DELETED
|
@@ -1,22 +0,0 @@
|
|
| 1 |
-
import os
|
| 2 |
-
|
| 3 |
-
class Config:
|
| 4 |
-
# --- Dynamic Path Resolution for Hugging Face ---
|
| 5 |
-
# This automatically finds the absolute path to the Version_4 folder
|
| 6 |
-
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
|
| 7 |
-
|
| 8 |
-
# Model Paths
|
| 9 |
-
MODEL_PATH = os.getenv(
|
| 10 |
-
"ONNX_MODEL_PATH",
|
| 11 |
-
os.path.join(BASE_DIR, "models", "model_quantized.onnx")
|
| 12 |
-
)
|
| 13 |
-
TOKENIZER_PATH = os.getenv("TOKENIZER_PATH", "microsoft/deberta-v3-base")
|
| 14 |
-
|
| 15 |
-
# Tier 4 Decision Matrix Weights
|
| 16 |
-
W_NLP = 0.70
|
| 17 |
-
W_META = 0.30
|
| 18 |
-
THRESHOLD = 0.40
|
| 19 |
-
|
| 20 |
-
# Tier 1 Cache (Simulated with local sets for this pipeline)
|
| 21 |
-
KNOWN_SAFE_DOMAINS = {"google.com", "microsoft.com", "apple.com", "internal-corp.com"}
|
| 22 |
-
KNOWN_MALICIOUS_HASHES = {"e99a18c428cb38d5f260853678922e03"} # Example MD5s
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Version_3/models/model_quantized.onnx
DELETED
|
@@ -1,3 +0,0 @@
|
|
| 1 |
-
version https://git-lfs.github.com/spec/v1
|
| 2 |
-
oid sha256:07eb49da681035631002cf959d0fb34e9c9efd5016d884ff1170228d841d47fb
|
| 3 |
-
size 244570129
|
|
|
|
|
|
|
|
|
|
|
|
Version_3/pipeline/__pycache__/tier1_fast_filter.cpython-313.pyc
DELETED
|
Binary file (1.21 kB)
|
|
|
Version_3/pipeline/__pycache__/tier2_extraction.cpython-313.pyc
DELETED
|
Binary file (1.74 kB)
|
|
|
Version_3/pipeline/__pycache__/tier3_inference.cpython-313.pyc
DELETED
|
Binary file (2.93 kB)
|
|
|
Version_3/pipeline/__pycache__/tier4_scoring.cpython-313.pyc
DELETED
|
Binary file (1.08 kB)
|
|
|
Version_3/pipeline/tier1_fast_filter.py
DELETED
|
@@ -1,18 +0,0 @@
|
|
| 1 |
-
import hashlib
|
| 2 |
-
from config import Config
|
| 3 |
-
|
| 4 |
-
def compute_hash(text: str) -> str:
|
| 5 |
-
return hashlib.md5(text.encode('utf-8')).hexdigest()
|
| 6 |
-
|
| 7 |
-
def check_fast_filter(sender_domain: str, raw_text: str):
|
| 8 |
-
"""
|
| 9 |
-
Tier 1: Deterministic $O(1)$ lookup. Returns a definitive verdict instantly if matched.
|
| 10 |
-
"""
|
| 11 |
-
if sender_domain.lower() in Config.KNOWN_SAFE_DOMAINS:
|
| 12 |
-
return {"bypassed": True, "verdict": "SAFE", "reason": "Trusted Domain"}
|
| 13 |
-
|
| 14 |
-
msg_hash = compute_hash(raw_text)
|
| 15 |
-
if msg_hash in Config.KNOWN_MALICIOUS_HASHES:
|
| 16 |
-
return {"bypassed": True, "verdict": "PHISHING", "reason": "Known Threat Signature"}
|
| 17 |
-
|
| 18 |
-
return {"bypassed": False}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Version_3/pipeline/tier2_extraction.py
DELETED
|
@@ -1,36 +0,0 @@
|
|
| 1 |
-
import re
|
| 2 |
-
import unicodedata
|
| 3 |
-
|
| 4 |
-
# Common obfuscation characters (e.g., zero-width spaces)
|
| 5 |
-
OBFUSCATION_CHARS = r'[\u200B\u200C\u200D\uFEFF]'
|
| 6 |
-
URL_SHORTENERS = r'(bit\.ly|tinyurl\.com|t\.co|ow\.ly|is\.gd)'
|
| 7 |
-
URGENCY_KEYWORDS = r'(immediate action|account suspended|verify now|unauthorized login|final warning)'
|
| 8 |
-
|
| 9 |
-
def sanitize_text(text: str) -> str:
|
| 10 |
-
"""Strips zero-width characters and normalizes lookalike Unicode."""
|
| 11 |
-
clean_text = re.sub(OBFUSCATION_CHARS, '', text)
|
| 12 |
-
clean_text = unicodedata.normalize('NFKC', clean_text)
|
| 13 |
-
return clean_text
|
| 14 |
-
|
| 15 |
-
def extract_metadata_flags(sender_domain: str, display_name: str, clean_text: str) -> int:
|
| 16 |
-
"""
|
| 17 |
-
Tier 2: Extracts behavioral flags. Each triggered rule adds to the flag count.
|
| 18 |
-
"""
|
| 19 |
-
flags = 0
|
| 20 |
-
text_lower = clean_text.lower()
|
| 21 |
-
|
| 22 |
-
# Flag 1: Domain / Display Name mismatch (e.g., "PayPal" sending from "support@cheap-shoes.xyz")
|
| 23 |
-
if display_name and display_name.lower() != sender_domain.lower():
|
| 24 |
-
# A naive check; in production, use Levenshtein distance against known brands
|
| 25 |
-
if "paypal" in display_name.lower() and "paypal.com" not in sender_domain.lower():
|
| 26 |
-
flags += 1
|
| 27 |
-
|
| 28 |
-
# Flag 2: Presence of URL shorteners
|
| 29 |
-
if re.search(URL_SHORTENERS, text_lower):
|
| 30 |
-
flags += 1
|
| 31 |
-
|
| 32 |
-
# Flag 3: Urgency / Threat-to-Action density
|
| 33 |
-
if re.search(URGENCY_KEYWORDS, text_lower):
|
| 34 |
-
flags += 1
|
| 35 |
-
|
| 36 |
-
return flags
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Version_3/pipeline/tier3_inference.py
DELETED
|
@@ -1,59 +0,0 @@
|
|
| 1 |
-
import onnxruntime as ort
|
| 2 |
-
import numpy as np
|
| 3 |
-
from transformers import AutoTokenizer
|
| 4 |
-
from config import Config
|
| 5 |
-
|
| 6 |
-
class NeuralEngine:
|
| 7 |
-
def __init__(self):
|
| 8 |
-
# Load HuggingFace tokenizer (Fast tokenizer written in Rust for low latency)
|
| 9 |
-
self.tokenizer = AutoTokenizer.from_pretrained(Config.TOKENIZER_PATH)
|
| 10 |
-
|
| 11 |
-
# Initialize ONNX CPU runtime for INT8 quantized model
|
| 12 |
-
# intra_op_num_threads limits thread spinning to hit the 15ms target consistently
|
| 13 |
-
sess_options = ort.SessionOptions()
|
| 14 |
-
sess_options.intra_op_num_threads = 2
|
| 15 |
-
sess_options.graph_optimization_level = ort.GraphOptimizationLevel.ORT_ENABLE_ALL
|
| 16 |
-
|
| 17 |
-
try:
|
| 18 |
-
self.session = ort.InferenceSession(Config.MODEL_PATH, sess_options, providers=['CPUExecutionProvider'])
|
| 19 |
-
self.model_loaded = True
|
| 20 |
-
except Exception as e:
|
| 21 |
-
print(f"Warning: ONNX model not found at {Config.MODEL_PATH}. Running in mock mode.")
|
| 22 |
-
self.model_loaded = False
|
| 23 |
-
|
| 24 |
-
def predict_phishing_prob(self, text: str) -> float:
|
| 25 |
-
"""
|
| 26 |
-
Tier 3: Transformer execution. Uses dynamic padding to minimize matrix sizes.
|
| 27 |
-
"""
|
| 28 |
-
# Dynamic Padding: only pad up to the longest sequence in this specific batch (1 in this case)
|
| 29 |
-
inputs = self.tokenizer(
|
| 30 |
-
text,
|
| 31 |
-
return_tensors="np",
|
| 32 |
-
truncation=True,
|
| 33 |
-
max_length=512,
|
| 34 |
-
padding=False
|
| 35 |
-
)
|
| 36 |
-
|
| 37 |
-
if not self.model_loaded:
|
| 38 |
-
# Mock output for testing without the actual heavy model file
|
| 39 |
-
return 0.85 if "password" in text.lower() else 0.05
|
| 40 |
-
|
| 41 |
-
ort_inputs = {
|
| 42 |
-
"input_ids": inputs["input_ids"].astype(np.int64),
|
| 43 |
-
"attention_mask": inputs["attention_mask"].astype(np.int64)
|
| 44 |
-
}
|
| 45 |
-
|
| 46 |
-
# Run forward pass
|
| 47 |
-
ort_outs = self.session.run(None, ort_inputs)
|
| 48 |
-
|
| 49 |
-
# Assuming binary classification where index 1 is 'Phishing'
|
| 50 |
-
logits = ort_outs[0][0]
|
| 51 |
-
|
| 52 |
-
# Softmax to get probability
|
| 53 |
-
exp_logits = np.exp(logits - np.max(logits))
|
| 54 |
-
probabilities = exp_logits / exp_logits.sum()
|
| 55 |
-
|
| 56 |
-
return float(probabilities[1])
|
| 57 |
-
|
| 58 |
-
# Singleton instantiation to keep model loaded in memory
|
| 59 |
-
neural_engine = NeuralEngine()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Version_3/pipeline/tier4_scoring.py
DELETED
|
@@ -1,30 +0,0 @@
|
|
| 1 |
-
from config import Config
|
| 2 |
-
|
| 3 |
-
def calculate_final_verdict(nlp_prob, flags):
|
| 4 |
-
# 'flags' is an integer representing the total count of suspicious flags
|
| 5 |
-
base_score = nlp_prob * 100
|
| 6 |
-
|
| 7 |
-
# Add a risk penalty for every flag found (e.g., 10 points per flag)
|
| 8 |
-
penalty = flags * 10
|
| 9 |
-
|
| 10 |
-
actual_calculated_score = min(100, base_score + penalty)
|
| 11 |
-
|
| 12 |
-
if actual_calculated_score >= 40:
|
| 13 |
-
actual_verdict_string = "Phishing"
|
| 14 |
-
else:
|
| 15 |
-
actual_verdict_string = "Safe"
|
| 16 |
-
|
| 17 |
-
# THE NEW BREAKDOWN DICTIONARY
|
| 18 |
-
detailed_breakdown = {
|
| 19 |
-
"language_analysis": f"NLP matched phishing patterns with {round(nlp_prob * 100, 2)}% confidence." if nlp_prob >= 0.4 else "Text appears conversational and safe.",
|
| 20 |
-
|
| 21 |
-
"link_analysis": f"Detected {flags} suspicious metadata/link flags." if flags > 0 else "Metadata and links appear clean.",
|
| 22 |
-
|
| 23 |
-
"sender_verification": "Suspicious metadata detected." if flags > 0 else "Sender identity verified and clean."
|
| 24 |
-
}
|
| 25 |
-
|
| 26 |
-
return {
|
| 27 |
-
"verdict": actual_verdict_string,
|
| 28 |
-
"risk_score": actual_calculated_score,
|
| 29 |
-
"breakdown": detailed_breakdown
|
| 30 |
-
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|