Spaces:
Configuration error

File size: 13,921 Bytes
ff32501
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
"""
environment.py β€” Core EmailTriage OpenEnv logic
step(), reset(), grader(), get_obs()
"""
from __future__ import annotations

import json
import random
import re
from pathlib import Path
from typing import Tuple, Dict, Any

from models import (
    Action, ActionType, Email, EmailView, Label,
    Observation, State, Stats, ActionSummary, StepResult, GraderResult
)

# ─────────────────────────── Constants ────────────────────────

DATA_PATH   = Path(__file__).parent / "data" / "inboxes.json"
MAX_STEPS   = 50
RANDOM_SEED = 42

TASK_CONFIG = {
    "easy":   {"label_w": 0.6, "reply_w": 0.2, "empty_w": 0.1, "spam_w": 0.1, "escalate_w": 0.0},
    "medium": {"label_w": 0.5, "reply_w": 0.2, "empty_w": 0.1, "spam_w": 0.2, "escalate_w": 0.0},
    "hard":   {"label_w": 0.3, "reply_w": 0.2, "empty_w": 0.1, "spam_w": 0.1, "escalate_w": 0.3},
}


class EmailTriageEnv:
    """
    OpenEnv-compatible Email Triage environment.

    Lifecycle:
        env = EmailTriageEnv()
        obs = env.reset(task="easy")
        result = env.step(action_json)
        score = env.grader()
    """

    def __init__(self):
        self._raw_data: Dict = {}
        self.state: State = State()
        self.ground_truth: Dict[str, Dict] = {}
        self.action_history: list[ActionSummary] = []
        self.current_task: str = "easy"
        self._load_data()

    # ──────────────── Data Loading ────────────────

    def _load_data(self):
        with open(DATA_PATH, "r", encoding="utf-8") as f:
            self._raw_data = json.load(f)

    # ──────────────── Reset ───────────────────────

    def reset(self, task: str = "easy") -> Observation:
        if task not in self._raw_data:
            raise ValueError(f"Unknown task '{task}'. Choose from: {list(self._raw_data.keys())}")

        random.seed(RANDOM_SEED)
        self.current_task = task
        task_data = self._raw_data[task]

        inbox: Dict[str, Email] = {}
        for e in task_data["emails"]:
            inbox[e["id"]] = Email(
                id=e["id"],
                subject=e["subject"],
                body=e["body"],
                sender=e["sender"],
            )

        self.ground_truth = task_data["ground_truth"]
        self.state = State(inbox=inbox, task=task)
        self.action_history = []

        return self._get_obs()

    # ──────────────── Step ────────────────────────

    def step(self, action_json: str) -> StepResult:
        # Parse action
        try:
            action = Action.model_validate_json(action_json)
        except Exception as e:
            obs = self._get_obs()
            return StepResult(
                observation=obs,
                reward=-0.5,
                done=False,
                info={"error": f"Invalid action JSON: {e}"}
            )

        email_id = action.email_id

        # Validate email_id exists
        if email_id not in self.state.inbox:
            obs = self._get_obs()
            return StepResult(
                observation=obs,
                reward=-0.2,
                done=False,
                info={"error": f"Email '{email_id}' not found in inbox"}
            )

        # Prevent re-acting on deleted/archived
        if email_id in self.state.deleted or email_id in self.state.archived:
            obs = self._get_obs()
            return StepResult(
                observation=obs,
                reward=-0.1,
                done=False,
                info={"warning": f"Email '{email_id}' already processed"}
            )

        reward = self._compute_reward(action)

        # Apply action to state
        self._apply_action(action)

        self.state.step_count += 1

        # Record in history
        self.action_history.append(ActionSummary(
            step=self.state.step_count,
            action_type=action.type,
            email_id=email_id,
            reward=round(reward, 3),
        ))

        done = self._is_done()
        obs = self._get_obs(done=done)

        return StepResult(
            observation=obs,
            reward=round(reward, 4),
            done=done,
            info={
                "step": self.state.step_count,
                "task": self.current_task,
                "action_applied": action.type,
            }
        )

    # ──────────────── Internal Helpers ────────────

    def _apply_action(self, action: Action):
        eid = action.email_id

        if action.type == ActionType.label:
            try:
                self.state.labels[eid] = Label(action.value).value
            except ValueError:
                pass  # invalid label handled in reward

        elif action.type == ActionType.delete:
            self.state.deleted.append(eid)
            # Also record it as spam label
            self.state.labels[eid] = Label.spam.value

        elif action.type == ActionType.escalate:
            self.state.labels[eid] = Label.escalate.value

        elif action.type == ActionType.draft:
            self.state.replies[eid] = action.value or ""

        elif action.type == ActionType.archive:
            self.state.archived.append(eid)

    def _compute_reward(self, action: Action) -> float:
        eid = action.email_id
        gt  = self.ground_truth.get(eid, {})
        gt_label = gt.get("label", "")
        reward = 0.0

        if action.type == ActionType.label:
            try:
                label_val = Label(action.value).value
            except ValueError:
                return -0.3  # completely invalid label string

            if label_val == gt_label:
                reward = 0.2
                # Bonus for escalation (hard task)
                if label_val == "escalate":
                    reward = 0.4
            else:
                reward = -0.1

        elif action.type == ActionType.delete:
            if gt_label == "spam":
                reward = 0.3
            else:
                reward = -0.4  # deleting legit email penalised hard

        elif action.type == ActionType.escalate:
            if gt_label == "escalate":
                reward = 0.4
            else:
                reward = -0.2

        elif action.type == ActionType.draft:
            draft_text = (action.value or "").lower()
            kws = gt.get("reply_keywords", [])
            if gt_label == "spam":
                reward = -0.2  # drafting reply to spam is waste
            elif not draft_text:
                reward = -0.1
            else:
                # Keyword match scoring
                hits = sum(1 for kw in kws if kw.lower() in draft_text)
                ratio = hits / len(kws) if kws else 0.0
                length_ok = 10 <= len(draft_text.split()) <= 80
                reward = 0.1 + (0.2 * ratio) + (0.05 if length_ok else 0)

        elif action.type == ActionType.archive:
            if gt_label in ("low", "med"):
                reward = 0.05  # archiving low/med is acceptable
            elif gt_label == "spam":
                reward = 0.1   # archiving spam is ok (not as good as delete)
            else:
                reward = -0.1  # archiving high/escalate is wrong

        # Progress shaped bonus
        processed = len(self.state.labels) + len(self.state.deleted) + len(self.state.archived)
        total = len(self.state.inbox)
        progress = processed / total if total else 0.0
        reward += 0.05 * progress

        return round(reward, 4)

    def _is_done(self) -> bool:
        processed = (
            set(self.state.labels.keys()) |
            set(self.state.deleted) |
            set(self.state.archived)
        )
        all_processed = processed >= set(self.state.inbox.keys())
        return all_processed or self.state.step_count >= MAX_STEPS

    def _get_obs(self, done: bool = False) -> Observation:
        processed = (
            set(self.state.labels.keys()) |
            set(self.state.deleted) |
            set(self.state.archived)
        )

        email_views = []
        for eid, email in self.state.inbox.items():
            is_labeled = eid in self.state.labels
            email_views.append(EmailView(
                id=email.id,
                subject=email.subject,
                body=email.body,
                sender=email.sender,
                labeled=is_labeled,
                label=self.state.labels.get(eid),
            ))

        stats = Stats(
            total=len(self.state.inbox),
            unread=len(self.state.inbox) - len(processed),
            labeled=len(self.state.labels),
            deleted=len(self.state.deleted),
            escalated=sum(1 for v in self.state.labels.values() if v == "escalate"),
            drafts=len(self.state.replies),
        )

        return Observation(
            current_emails=email_views,
            stats=stats,
            history=self.action_history[-10:],  # Last 10 actions
            done=done,
            step=self.state.step_count,
        )

    # ──────────────── Grader ──────────────────────

    def grader(self) -> GraderResult:
        gt = self.ground_truth
        total = len(gt)
        if total == 0:
            return GraderResult(score=0.0, breakdown={})

        cfg = TASK_CONFIG.get(self.current_task, TASK_CONFIG["easy"])

        # 1. Label accuracy
        label_correct = sum(
            1 for eid, info in gt.items()
            if self.state.labels.get(eid) == info["label"]
        )
        label_acc = label_correct / total

        # 2. Spam recall (spam correctly deleted or labeled)
        spam_ids = [eid for eid, info in gt.items() if info["label"] == "spam"]
        spam_correct = sum(
            1 for eid in spam_ids
            if eid in self.state.deleted
            or self.state.labels.get(eid) == "spam"
        )
        spam_recall = (spam_correct / len(spam_ids)) if spam_ids else 1.0

        # 3. Reply relevance (keyword match)
        legit_ids = [eid for eid, info in gt.items() if info["label"] != "spam"]
        reply_score = 0.0
        if legit_ids and self.state.replies:
            for eid in legit_ids:
                if eid in self.state.replies:
                    reply_text = self.state.replies[eid].lower()
                    kws = gt[eid].get("reply_keywords", [])
                    if kws:
                        hits = sum(1 for kw in kws if kw.lower() in reply_text)
                        reply_score += hits / len(kws)
            reply_score /= len(legit_ids)

        # 4. Escalation recall (hard task)
        escalate_ids = [eid for eid, info in gt.items() if info["label"] == "escalate"]
        escalate_recall = 0.0
        if escalate_ids:
            esc_correct = sum(
                1 for eid in escalate_ids
                if self.state.labels.get(eid) == "escalate"
            )
            escalate_recall = esc_correct / len(escalate_ids)

        # 5. Inbox cleared bonus
        processed = (
            set(self.state.labels.keys()) |
            set(self.state.deleted) |
            set(self.state.archived)
        )
        inbox_cleared = len(processed) / total

        # Weighted final score
        score = (
            cfg["label_w"]    * label_acc +
            cfg["spam_w"]     * spam_recall +
            cfg["reply_w"]    * reply_score +
            cfg["escalate_w"] * escalate_recall +
            cfg["empty_w"]    * inbox_cleared
        )
        score = round(min(1.0, max(0.0, score)), 4)

        return GraderResult(
            score=score,
            breakdown={
                "label_accuracy":    round(label_acc, 4),
                "spam_recall":       round(spam_recall, 4),
                "reply_relevance":   round(reply_score, 4),
                "escalation_recall": round(escalate_recall, 4),
                "inbox_cleared":     round(inbox_cleared, 4),
            },
            details={
                "task": self.current_task,
                "steps_used": str(self.state.step_count),
                "emails_labeled": str(len(self.state.labels)),
                "emails_deleted": str(len(self.state.deleted)),
                "drafts_written": str(len(self.state.replies)),
            }
        )

    # ──────────────── Public Accessors ────────────

    def get_state(self) -> State:
        return self.state

    def get_tasks(self) -> list[dict]:
        return [
            {
                "id": "easy",
                "description": "Binary classify 5 emails as spam or legit (low/med/high). Delete the spam.",
                "difficulty": "easy",
                "email_count": len(self._raw_data["easy"]["emails"]),
                "grader_weights": TASK_CONFIG["easy"],
            },
            {
                "id": "medium",
                "description": "Classify and prioritize 10 mixed emails. Delete spam, label by urgency.",
                "difficulty": "medium",
                "email_count": len(self._raw_data["medium"]["emails"]),
                "grader_weights": TASK_CONFIG["medium"],
            },
            {
                "id": "hard",
                "description": (
                    "Full triage of 15 emails: classify, draft replies for legit emails, "
                    "delete spam, and escalate P0/critical issues."
                ),
                "difficulty": "hard",
                "email_count": len(self._raw_data["hard"]["emails"]),
                "grader_weights": TASK_CONFIG["hard"],
            },
        ]