Update env.py
Browse files10 unmodified lines1112131415161718197 unmodified lines2728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946010 unmodified linesimport gymnasium as gymfrom gymnasium import spaces# ---------------------------------------------------------------------------# Vocabulary & encoding helpers# ---------------------------------------------------------------------------KEYWORD_VOCAB = ["invoice", "payment", "overdue", "refund", # billing"hacked", "breach", "unauthorized", "password", # security7 unmodified linesCONTEXT_MAP = {"spam": 0, "billing": 1, "tech": 2, "security": 3, "legal": 4}OBS_DIM = len(KEYWORD_VOCAB) + len(SENTIMENT_MAP) + len(CONTEXT_MAP)# 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"]# ---------------------------------------------------------------------------# Mock email dataset# ---------------------------------------------------------------------------EMAIL_DATASET = [# ── 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.0REWARD_PARTIAL_ONE_WRONG = 0.2REWARD_PARTIAL_BOTH_WRONG= 0.1PENALTY_MISSED_SECURITY = -2.0# ---------------------------------------------------------------------------# Environment# ---------------------------------------------------------------------------class EmailTriageEnv(gym.Env):"""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__()if batch is not None:self.email_batch = batchelif 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_DATASETself.shuffle = shuffle# Action space: [urgency(3), routing(3), resolution(3)]self.action_space = spaces.MultiDiscrete([3, 3, 3])# Observation space: binary keyword flags + one-hot sentiment + one-hot contextself.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 = 0def _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.0context_vec = np.zeros(len(CONTEXT_MAP), dtype=np.float32)context_vec[CONTEXT_MAP[email["context"]]] = 1.0return 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 crimeif correct[0] == 2 and urgency != 2:return PENALTY_MISSED_SECURITY# Priority 2: Perfect matchif (urgency, routing, resolution) == correct:return REWARD_CORRECT_FULL# Priority 3: Urgency sahi hai — partial creditif urgency == correct[0]:routing_ok = (routing == correct[1])resolution_ok = (resolution == correct[2])if routing_ok and not resolution_ok:return REWARD_PARTIAL_ONE_WRONGif resolution_ok and not routing_ok:return REWARD_PARTIAL_ONE_WRONGreturn REWARD_PARTIAL_BOTH_WRONGreturn 0.0def 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 = 0self._current_email = self._queue[self._step_idx]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: np.ndarray):"""Process one email triage decision."""# Save current email and compute raw rewardscored_email = self._current_emailreward = self._compute_reward(action, scored_email)# Move to next emailself._step_idx += 1terminated = 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)info = {"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 rewardreturn obs, float(reward), terminated, False, infodef render(self, mode: str = "human"):"""Print current email details to stdout."""e = self._current_emailprint(f"[Step {self._step_idx}] {e.get('description', '')} "f"| difficulty={e.get('difficulty', '')} "f"| sentiment={e.get('sentiment', '')} "f"| context={e.get('context', '')}")10 unmodified lines111213141516177 unmodified lines25262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013110 unmodified linesimport gymnasium as gymfrom gymnasium import spaces# --- Environment Setup (Vahi jo aapne diya, corrections ke saath) ---KEYWORD_VOCAB = ["invoice", "payment", "overdue", "refund", # billing"hacked", "breach", "unauthorized", "password", # security7 unmodified linesCONTEXT_MAP = {"spam": 0, "billing": 1, "tech": 2, "security": 3, "legal": 4}OBS_DIM = len(KEYWORD_VOCAB) + len(SENTIMENT_MAP) + len(CONTEXT_MAP)# Environment Classclass EmailTriageEnv(gym.Env):def __init__(self, task="hard"):super().__init__()# Hum sirf "hard" cases focus kar rahe hain score sudharne ke liyefrom __main__ import EMAIL_DATASETself.email_batch = [e for e in EMAIL_DATASET if e.get("difficulty") == task]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)self._step_idx = 0def _encode(self, email):kw_flags = np.array([1.0 if kw in email["keywords"] else 0.0 for kw in KEYWORD_VOCAB])sentiment_vec = np.zeros(len(SENTIMENT_MAP)); sentiment_vec[SENTIMENT_MAP[email["sentiment"]]] = 1.0context_vec = np.zeros(len(CONTEXT_MAP)); context_vec[CONTEXT_MAP[email["context"]]] = 1.0return np.concatenate([kw_flags, sentiment_vec, context_vec])def step(self, action):email = self.email_batch[self._step_idx]correct = email["correct_actions"]# Reward Logicreward = 0.0if correct[0] == 2 and action[0] != 2:reward = -2.0 # Penalty for missing securityelif tuple(action) == correct:reward = 1.0elif action[0] == correct[0]:reward = 0.2self._step_idx += 1done = self._step_idx >= len(self.email_batch)obs = self._encode(email) # current obsreturn obs, float(reward), done, False, {"correct": correct}# --- SMART AGENT LOGIC (Ye aapke score ko 0 se 1.0 le jayega) ---class EmailGatekeeperAgent:def predict(self, obs):"""Observation vector se features nikaal kar sahi decision leta hai.Index 0-21: KeywordsIndex 22-24: SentimentIndex 25-29: Context"""# 1. Feature Extractionkeywords = obs[0:22]context = obs[25:30]# Keyword mapping based on VOCABis_security_kw = any(obs[4:8]) # hacked, breach, unauthorized, passwordis_legal_kw = any(obs[12:16]) # lawsuit, legal, attorney, sueis_urgent = obs[20] or obs[21] # urgent, critical# 2. Decision Logic (Rule-based to maximize reward)urgency = 0routing = 0resolution = 0# Logic for HARD category (Phishing & Breaches)if context[3] == 1.0 or is_security_kw: # Security Contexturgency = 2 # Security Breachrouting = 1 # Tech Support (Default for hard security)resolution = 2 # Escalate to Human# Special case: Ransomware/Extortion jisme Legal involve hota haiif is_legal_kw or context[4] == 1.0:routing = 2 # Legalelif context[4] == 1.0 or is_legal_kw: # Legal Contexturgency = 2routing = 2resolution = 2elif context[1] == 1.0: # Billingurgency = 1routing = 0resolution = 1return np.array([urgency, routing, resolution])# --- EXECUTION SCRIPT ---if __name__ == "__main__":env = EmailTriageEnv(task="hard")agent = EmailGatekeeperAgent()obs, info = env.reset()total_reward = 0print(f"{'Description':<50} | {'Action':<15} | {'Reward'}")print("-" * 80)done = Falsewhile not done:action = agent.predict(obs)obs, reward, done, _, info = env.step(action)total_reward += rewarddesc = info['description'][:45] + "..."act_str = f"{action}"print(f"{desc:<50} | {act_str:<15} | {reward:>5}")# Final Score Calculationfinal_score = max(0, total_reward / len(env.email_batch))print("-" * 80)print(f"FINAL EPISODE SCORE: {final_score:.3f}")
env.py+97-426