Update env.py
Browse files1234567891011121314615161791011121314181920212223242526272829213031323334352736373830313233343536373940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533641337338339443403413423433443453464748347495051523483493503513523535435435535635735857359360361362363364365366367368369370371372373374375376377378593793803813823833843853863873883893903913923933943953963973986162636465666739940040140240340440540640740840941041169412413414415416417418419764204214224234244254264277842842943043180818283848586878889909143243343443543695437438439440441442443102103104444106107108445446447448449450451110452453454455456457458459460"""EmailTriageEnv — Intelligent Email Gatekeeper RL Environment============================================================Observation : flat Box vector encoding keywords, sentiment, and context.Action : MultiDiscrete([3, 3, 3]) [0] Urgency — 0=General, 1=Billing, 2=Security Breach [1] Routing — 0=AI Auto-Reply, 1=Tech Support, 2=Legal [2] Resolution— 0=Archive, 1=Draft Reply, 2=Escalate to HumanReward : +1.0 fully correct | -2.0 wrong priority on crisis email"""import numpy as npimport gymnasium as gymfrom gymnasium import spaces
# ---------------------------------------------------------------------------# Vocabulary & Encoding# Vocabulary & encoding helpers# ---------------------------------------------------------------------------KEYWORD_VOCAB = [ "invoice", "payment", "overdue", "refund", "hacked", "breach", "unauthorized", "password", "crash", "error", "bug", "slow", "lawsuit", "legal", "attorney", "sue", "spam", "offer", "win", "free", "urgent", "critical", "angry", "threat", "invoice", "payment", "overdue", "refund", # billing "hacked", "breach", "unauthorized", "password", # security "crash", "error", "bug", "slow", # tech "lawsuit", "legal", "attorney", "sue", # legal "spam", "offer", "win", "free", # spam "urgent", "critical", "angry", "threat", # sentiment signals]
SENTIMENT_MAP = {"positive": 0, "neutral": 1, "negative": 2}CONTEXT_MAP = {"spam": 0, "billing": 1, "tech": 2, "security": 3, "legal": 4}OBS_DIM = len(KEYWORD_VOCAB) + len(SENTIMENT_MAP) + len(CONTEXT_MAP)
# Labels for UI# UI Labels (Required by app.py)URGENCY_LABELS = ["General", "Billing", "Security Breach"]ROUTING_LABELS = ["AI Auto-Reply", "Tech Support", "Legal"]RESOLUTION_LABELS = ["Archive", "Draft Reply", "Escalate to Human"]
# ---------------------------------------------------------------------------# Dataset# Mock email dataset# ---------------------------------------------------------------------------EMAIL_DATASET = [ {"description": "Spam promo", "keywords": ["spam", "offer"], "sentiment": "positive", "context": "spam", "difficulty": "easy", "correct_actions": (0, 0, 0)}, {"description": "Routine support", "keywords": ["slow", "error"], "sentiment": "neutral", "context": "tech", "difficulty": "easy", "correct_actions": (0, 1, 1)}, {"description": "Billing inquiry", "keywords": ["invoice", "payment"], "sentiment": "neutral", "context": "billing", "difficulty": "easy", "correct_actions": (1, 0, 1)}, {"description": "Overdue invoice", "keywords": ["invoice", "overdue"], "sentiment": "negative", "context": "billing", "difficulty": "medium", "correct_actions": (1, 0, 1)}, {"description": "Refund dispute", "keywords": ["refund", "angry"], "sentiment": "negative", "context": "billing", "difficulty": "medium", "correct_actions": (1, 2, 2)}, {"description": "Legal threat", "keywords": ["lawsuit", "attorney"], "sentiment": "negative", "context": "legal", "difficulty": "hard", "correct_actions": (2, 2, 2)}, {"description": "Account hacked", "keywords": ["hacked", "password"], "sentiment": "negative", "context": "security", "difficulty": "hard", "correct_actions": (2, 1, 2)}, {"description": "Data breach", "keywords": ["breach", "unauthorized"], "sentiment": "negative", "context": "security", "difficulty": "hard", "correct_actions": (2, 1, 2)}, # ── Easy: Spam vs Real ────────────────────────────────────────────────── { "description": "Spam promo", "keywords": ["spam", "offer", "win", "free"], "sentiment": "positive", "context": "spam", "difficulty": "easy", "correct_actions": (0, 0, 0), }, { "description": "Spam lottery", "keywords": ["free", "win", "offer"], "sentiment": "positive", "context": "spam", "difficulty": "easy", "correct_actions": (0, 0, 0), }, { "description": "Routine support request", "keywords": ["slow", "error"], "sentiment": "neutral", "context": "tech", "difficulty": "easy", "correct_actions": (0, 1, 1), }, { "description": "General billing inquiry", "keywords": ["invoice", "payment"], "sentiment": "neutral", "context": "billing", "difficulty": "easy", "correct_actions": (1, 0, 1), },
# ── Medium: Billing / Tech context ────────────────────────────────────── { "description": "Overdue invoice complaint", "keywords": ["invoice", "overdue", "payment", "angry"], "sentiment": "negative", "context": "billing", "difficulty": "medium", "correct_actions": (1, 0, 1), }, { "description": "Refund dispute", "keywords": ["refund", "payment", "angry"], "sentiment": "negative", "context": "billing", "difficulty": "medium", "correct_actions": (1, 2, 2), }, { "description": "App crash report", "keywords": ["crash", "bug", "error"], "sentiment": "negative", "context": "tech", "difficulty": "medium", "correct_actions": (0, 1, 1), }, { "description": "Persistent login bug", "keywords": ["bug", "password", "error"], "sentiment": "negative", "context": "tech", "difficulty": "medium", "correct_actions": (0, 1, 1), }, # ── Medium: Legal Threats ──────────────────────────── { "id": "TC-M-01", "description": "Polite refund ultimatum with implied legal action", "keywords": ["refund", "legal", "angry", "threat"], "sentiment": "negative", "context": "legal", "difficulty": "medium", "correct_actions": (2, 2, 2), }, { "id": "TC-M-02", "description": "Overdue invoice with attorney CC warning", "keywords": ["invoice", "overdue", "attorney", "legal", "payment", "threat"], "sentiment": "negative", "context": "legal", "difficulty": "medium", "correct_actions": (2, 2, 2), }, { "id": "TC-M-03", "description": "Disappointed customer implying regulatory complaint", "keywords": ["angry", "threat", "legal"], "sentiment": "negative", "context": "legal", "difficulty": "medium", "correct_actions": (2, 2, 2), }, { "id": "TC-M-04", "description": "SLA breach complaint with legal remedy language", "keywords": ["breach", "legal", "threat", "angry"], "sentiment": "negative", "context": "legal", "difficulty": "medium", "correct_actions": (2, 2, 2), }, { "id": "TC-M-05", "description": "Billing dispute with small claims court mention", "keywords": ["refund", "payment", "angry", "lawsuit", "urgent"], "sentiment": "negative", "context": "legal", "difficulty": "medium", "correct_actions": (2, 2, 2), }, { "id": "TC-M-06", "description": "GDPR deletion request with legal consequence warning", "keywords": ["legal", "breach", "threat", "angry"], "sentiment": "negative", "context": "legal", "difficulty": "medium", "correct_actions": (2, 2, 2), }, { "id": "TC-M-07", "description": "Subscription cancellation with chargeback and CFPB threat", "keywords": ["payment", "refund", "angry", "threat", "legal"], "sentiment": "negative", "context": "legal", "difficulty": "medium", "correct_actions": (2, 2, 2), }, { "id": "TC-M-08", "description": "Vendor threatening IP infringement claim", "keywords": ["unauthorized", "legal", "attorney", "threat"], "sentiment": "negative", "context": "legal", "difficulty": "medium", "correct_actions": (2, 2, 2), },
# ── Hard: Subtle Phishing Attempts ────────────────────────────────────── { "id": "TC-H-01", "description": "IT password reset disguised as routine security audit", "keywords": ["password", "unauthorized", "critical", "urgent", "threat"], "sentiment": "negative", "context": "security", "difficulty": "hard", "correct_actions": (2, 1, 2), }, { "id": "TC-H-02", "description": "Fake invoice payment portal redirect — credential harvest", "keywords": ["invoice", "payment", "password", "unauthorized", "urgent"], "sentiment": "neutral", "context": "security", "difficulty": "hard", "correct_actions": (2, 1, 2), }, { "id": "TC-H-03", "description": "HR benefits enrollment with credential capture", "keywords": ["password", "urgent", "critical"], "sentiment": "neutral", "context": "security", "difficulty": "hard", "correct_actions": (2, 1, 2), }, { "id": "TC-H-04", "description": "Fake account suspension notice with login link", "keywords": ["unauthorized", "password", "breach", "urgent", "threat"], "sentiment": "negative", "context": "security", "difficulty": "hard", "correct_actions": (2, 1, 2), }, { "id": "TC-H-05", "description": "Vendor onboarding BEC — admin credentials via reply", "keywords": ["password", "unauthorized", "urgent"], "sentiment": "neutral", "context": "security", "difficulty": "hard", "correct_actions": (2, 1, 2), }, { "id": "TC-H-06", "description": "Fake new sign-in alert — was this you? phish", "keywords": ["unauthorized", "password", "hacked", "breach", "urgent"], "sentiment": "negative", "context": "security", "difficulty": "hard", "correct_actions": (2, 1, 2), }, { "id": "TC-H-07", "description": "Payroll migration phish — salary interruption fear", "keywords": ["payment", "password", "urgent", "threat"], "sentiment": "negative", "context": "security", "difficulty": "hard", "correct_actions": (2, 1, 2), }, { "id": "TC-H-08", "description": "Software license renewal — admin credential request", "keywords": ["password", "critical", "urgent", "error"], "sentiment": "neutral", "context": "security", "difficulty": "hard", "correct_actions": (2, 1, 2), },
# ── Hard: Phishing + Legal Threat Overlay ─────────────────────────────── { "id": "TC-H-09", "description": "Fake GDPR breach notice — credential harvest via legal fear", "keywords": ["breach", "hacked", "password", "legal", "threat", "urgent", "unauthorized"], "sentiment": "negative", "context": "security", "difficulty": "hard", "correct_actions": (2, 1, 2), }, { "id": "TC-H-10", "description": "Ransomware disguised as software compliance audit", "keywords": ["hacked", "breach", "unauthorized", "lawsuit", "legal", "threat", "critical", "urgent"], "sentiment": "negative", "context": "security", "difficulty": "hard", "correct_actions": (2, 2, 2), }, { "id": "TC-H-11", "description": "Extortion — threatening to publish stolen data", "keywords": ["hacked", "breach", "unauthorized", "attorney", "threat", "critical", "urgent"], "sentiment": "negative", "context": "security", "difficulty": "hard", "correct_actions": (2, 2, 2), }, { "id": "TC-H-12", "description": "Fake law firm letter claiming evidence of data misuse", "keywords": ["unauthorized", "breach", "attorney", "lawsuit", "legal", "threat"], "sentiment": "negative", "context": "legal", "difficulty": "hard", "correct_actions": (2, 2, 2), },
# ── Hard: Crisis / Security threats ───────────────────────────────────── { "description": "Account hacked — urgent", "keywords": ["hacked", "unauthorized", "password", "urgent", "angry"], "sentiment": "negative", "context": "security", "difficulty": "hard", "correct_actions": (2, 1, 2), }, { "description": "Data breach notification", "keywords": ["breach", "unauthorized", "critical", "threat"], "sentiment": "negative", "context": "security", "difficulty": "hard", "correct_actions": (2, 1, 2), }, { "description": "Legal threat — lawsuit", "keywords": ["lawsuit", "legal", "attorney", "threat", "angry"], "sentiment": "negative", "context": "legal", "difficulty": "hard", "correct_actions": (2, 2, 2), }, { "description": "Ransomware / extortion threat", "keywords": ["hacked", "threat", "critical", "urgent", "breach"], "sentiment": "negative", "context": "security", "difficulty": "hard", "correct_actions": (2, 2, 2), },]
# ---------------------------------------------------------------------------# Reward weights — adjust freely# ---------------------------------------------------------------------------REWARD_CORRECT_FULL = 1.0 REWARD_PARTIAL_ONE_WRONG = 0.2 REWARD_PARTIAL_BOTH_WRONG= 0.1 PENALTY_MISSED_SECURITY = -2.0
# ---------------------------------------------------------------------------# Environment Class# Environment# ---------------------------------------------------------------------------class EmailTriageEnv(gym.Env): def __init__(self, batch: list | None = None, shuffle: bool = True, task: str = "easy"): """Single-email-per-step triage environment.""" metadata = {"render_modes": ["human"]}
# --- BUG FIX: Added `task` argument and filtering logic --- def __init__(self, task: str = "all", batch: list | None = None, shuffle: bool = True): super().__init__() # Meta Grader logic: filter by task if no batch provided if batch is None: if batch is not None: self.email_batch = [e for e in EMAIL_DATASET if e["difficulty"] == task] if not self.email_batch: # Fallback agar task match na ho self.email_batch = EMAIL_DATASET[:3] else: self.email_batch = batch elif task != "all": # Filter dataset based on the task difficulty ("easy", "medium", "hard") self.email_batch = [e for e in EMAIL_DATASET if e.get("difficulty") == task] else: self.email_batch = EMAIL_DATASET
self.shuffle = shuffle
# Action space: [urgency(3), routing(3), resolution(3)] self.action_space = spaces.MultiDiscrete([3, 3, 3]) self.observation_space = spaces.Box(low=0.0, high=1.0, shape=(OBS_DIM,), dtype=np.float32)
# Observation space: binary keyword flags + one-hot sentiment + one-hot context self.observation_space = spaces.Box( low=0.0, high=1.0, shape=(OBS_DIM,), dtype=np.float32 )
# Internal state (populated by reset) self._queue: list[dict] = [] self._current_email: dict = {} self._step_idx: int = 0
def _encode(self, email: dict) -> np.ndarray: """Convert an email dict into a flat float32 observation vector.""" kw_flags = np.array( [1.0 if kw in email["keywords"] else 0.0 for kw in KEYWORD_VOCAB], dtype=np.float32, ) sentiment_vec = np.zeros(len(SENTIMENT_MAP), dtype=np.float32) sentiment_vec[SENTIMENT_MAP[email["sentiment"]]] = 1.0 self._max_episode_reward = len(self.email_batch) * 1.0 context_vec = np.zeros(len(CONTEXT_MAP), dtype=np.float32) context_vec[CONTEXT_MAP[email["context"]]] = 1.0 return np.concatenate([kw_flags, sentiment_vec, context_vec])
def _compute_reward(self, action: np.ndarray, email: dict) -> float: """Strict reward rules based on priority.""" urgency = int(action[0]) routing = int(action[1]) resolution = int(action[2]) correct = email["correct_actions"]
# Priority 1: Security breach miss — sabse bada crime if correct[0] == 2 and urgency != 2: return PENALTY_MISSED_SECURITY
# Priority 2: Perfect match if (urgency, routing, resolution) == correct: return REWARD_CORRECT_FULL
def _encode(self, email): kw_flags = np.array([1.0 if kw in email["keywords"] else 0.0 for kw in KEYWORD_VOCAB], dtype=np.float32) sent_vec = np.zeros(len(SENTIMENT_MAP), dtype=np.float32) sent_vec[SENTIMENT_MAP[email["sentiment"]]] = 1.0 ctx_vec = np.zeros(len(CONTEXT_MAP), dtype=np.float32) ctx_vec[CONTEXT_MAP[email["context"]]] = 1.0 return np.concatenate([kw_flags, sent_vec, ctx_vec]) # Priority 3: Urgency sahi hai — partial credit if urgency == correct[0]: routing_ok = (routing == correct[1]) resolution_ok = (resolution == correct[2]) if routing_ok and not resolution_ok: return REWARD_PARTIAL_ONE_WRONG if resolution_ok and not routing_ok: return REWARD_PARTIAL_ONE_WRONG return REWARD_PARTIAL_BOTH_WRONG return 0.0
def reset(self, *, seed=None, options=None): def reset(self, *, seed: int | None = None, options: dict | None = None): super().reset(seed=seed) self._queue = list(self.email_batch) if self.shuffle: self.np_random.shuffle(self._queue) self._step_idx = 0 self._current_email = self._queue[self._step_idx] return self._encode(self._current_email), {"difficulty": self._current_email["difficulty"]} obs = self._encode(self._current_email) info = { "description": self._current_email.get("description", ""), "difficulty": self._current_email.get("difficulty", "") } return obs, info
# --- BUG FIX: Returning raw float reward instead of normalised --- def step(self, action): def step(self, action: np.ndarray): """Process one email triage decision.""" # Save current email and compute raw reward scored_email = self._current_email correct = scored_email["correct_actions"] # Reward Logic raw_reward = 0.0 if tuple(action) == correct: raw_reward = 1.0 elif action[0] == correct[0]: raw_reward = 0.2 # Partial # Security Penalty if correct[0] == 2 and action[0] != 2: raw_reward = -2.0 reward = self._compute_reward(action, scored_email)
# Move to next email self._step_idx += 1 terminated = self._step_idx >= len(self._queue)
if not terminated: self._current_email = self._queue[self._step_idx] obs = self._encode(self._current_email) else: obs = self._encode(scored_email)
# Normalize reward norm_reward = raw_reward / self._max_episode_reward info = { "raw_reward": raw_reward, "correct_actions": correct, "difficulty": scored_email["difficulty"] "raw_reward": reward, "correct_actions": scored_email["correct_actions"], "difficulty": scored_email.get("difficulty", ""), "description": scored_email.get("description", ""), }
# Return standard Gymnasium step signature with raw reward return obs, norm_reward, terminated, False, info return obs, float(reward), terminated, False, info
def render(self, mode: str = "human"): """Print current email details to stdout.""" e = self._current_email print(f"[Step {self._step_idx}] {e.get('description', '')} " f"| difficulty={e.get('difficulty', '')} " f"| sentiment={e.get('sentiment', '')} " f"| context={e.get('context', '')}")env.py+408-58