File size: 8,145 Bytes
dcc24f8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
Inference/Prediction Module
Load fine-tuned model and extract entities from emails.
"""

import json
import re
from pathlib import Path
from typing import Dict, Optional, Union
from dataclasses import dataclass


@dataclass
class PredictionResult:
    """Result of model prediction."""
    entities: Dict
    raw_response: str
    success: bool
    error: Optional[str] = None
    
    def to_dict(self) -> Dict:
        return {
            "entities": self.entities,
            "raw_response": self.raw_response,
            "success": self.success,
            "error": self.error
        }
    
    def to_json(self, indent: int = 2) -> str:
        return json.dumps(self.entities, indent=indent)


class Predictor:
    """
    Load and run inference with fine-tuned model.
    
    Supports both:
    - Base model + LoRA adapter
    - Merged model
    """
    
    EXTRACTION_PROMPT = """Extract financial entities from this email:

Subject: {subject}

Body: {body}"""
    
    def __init__(
        self,
        model_path: Union[str, Path],
        adapter_path: Optional[Union[str, Path]] = None,
        max_tokens: int = 200
    ):
        """
        Initialize predictor.
        
        Args:
            model_path: Path to model (base or merged)
            adapter_path: Optional path to LoRA adapter
            max_tokens: Maximum tokens to generate
        """
        self.model_path = Path(model_path)
        self.adapter_path = Path(adapter_path) if adapter_path else None
        self.max_tokens = max_tokens
        
        self.model = None
        self.tokenizer = None
        self._loaded = False
    
    def load(self):
        """Load the model and tokenizer."""
        if self._loaded:
            return
        
        try:
            from mlx_lm import load
        except ImportError:
            raise ImportError(
                "mlx_lm is required. Install with: pip install mlx-lm"
            )
        
        print(f"๐Ÿ”„ Loading model from {self.model_path}...")
        
        if self.adapter_path:
            print(f"   With adapter: {self.adapter_path}")
            self.model, self.tokenizer = load(
                str(self.model_path),
                adapter_path=str(self.adapter_path)
            )
        else:
            self.model, self.tokenizer = load(str(self.model_path))
        
        self._loaded = True
        print("โœ… Model loaded successfully!")
    
    def predict(
        self,
        subject: str = "",
        body: str = "",
        email_text: Optional[str] = None
    ) -> PredictionResult:
        """
        Extract entities from an email.
        
        Args:
            subject: Email subject
            body: Email body
            email_text: Full email text (alternative to subject+body)
            
        Returns:
            PredictionResult with extracted entities
        """
        if not self._loaded:
            self.load()
        
        try:
            from mlx_lm import generate
        except ImportError:
            raise ImportError("mlx_lm is required")
        
        # Build prompt
        if email_text:
            prompt = f"Extract financial entities from this email:\n\n{email_text}"
        else:
            prompt = self.EXTRACTION_PROMPT.format(
                subject=subject[:200],
                body=body[:1500]
            )
        
        # Generate response
        try:
            response = generate(
                self.model,
                self.tokenizer,
                prompt=prompt,
                max_tokens=self.max_tokens,
                verbose=False
            )
        except Exception as e:
            return PredictionResult(
                entities={},
                raw_response="",
                success=False,
                error=f"Generation failed: {str(e)}"
            )
        
        # Parse JSON from response
        entities = self._extract_json(response)
        
        return PredictionResult(
            entities=entities if entities else {},
            raw_response=response,
            success=entities is not None
        )
    
    def predict_batch(
        self,
        emails: list
    ) -> list:
        """
        Extract entities from multiple emails.
        
        Args:
            emails: List of dicts with 'subject' and 'body' keys
            
        Returns:
            List of PredictionResults
        """
        results = []
        for email in emails:
            result = self.predict(
                subject=email.get('subject', ''),
                body=email.get('body', '')
            )
            results.append(result)
        return results
    
    def _extract_json(self, response: str) -> Optional[Dict]:
        """Extract JSON object from model response."""
        # Find JSON pattern
        match = re.search(r'\{[^{}]*\}', response)
        
        if match:
            try:
                return json.loads(match.group())
            except json.JSONDecodeError:
                pass
        
        return None


def main():
    """CLI for running predictions."""
    import argparse
    
    parser = argparse.ArgumentParser(
        description="Extract financial entities from emails using fine-tuned LLM"
    )
    
    parser.add_argument(
        "--model",
        type=str,
        default=str(Path.home() / "llm-mail-trainer/models/base/phi3-mini"),
        help="Path to model"
    )
    parser.add_argument(
        "--adapter",
        type=str,
        default=None,
        help="Path to LoRA adapter (optional)"
    )
    parser.add_argument(
        "--subject",
        type=str,
        default="",
        help="Email subject"
    )
    parser.add_argument(
        "--body",
        type=str,
        default=None,
        help="Email body text"
    )
    parser.add_argument(
        "--file",
        type=str,
        default=None,
        help="Path to file containing email text"
    )
    parser.add_argument(
        "--interactive",
        action="store_true",
        help="Run in interactive mode"
    )
    
    args = parser.parse_args()
    
    # Initialize predictor
    predictor = Predictor(
        model_path=args.model,
        adapter_path=args.adapter
    )
    
    if args.interactive:
        run_interactive(predictor)
    elif args.file:
        with open(args.file, 'r') as f:
            text = f.read()
        predictor.load()
        result = predictor.predict(email_text=text)
        print(result.to_json())
    elif args.body:
        predictor.load()
        result = predictor.predict(subject=args.subject, body=args.body)
        print(result.to_json())
    else:
        parser.print_help()


def run_interactive(predictor: Predictor):
    """Interactive mode for testing."""
    predictor.load()
    
    print("\n" + "=" * 60)
    print("๐Ÿง  LLM Mail Trainer - Interactive Mode")
    print("=" * 60)
    print("Enter email text to extract entities.")
    print("Type 'quit' or 'exit' to stop.")
    print("=" * 60 + "\n")
    
    while True:
        print("\n๐Ÿ“ง Enter email text (multi-line, end with empty line):")
        lines = []
        while True:
            try:
                line = input()
                if line.lower() in ['quit', 'exit']:
                    print("\n๐Ÿ‘‹ Goodbye!")
                    return
                if line == "" and lines:
                    break
                lines.append(line)
            except EOFError:
                print("\n๐Ÿ‘‹ Goodbye!")
                return
        
        email_text = "\n".join(lines)
        
        if email_text.strip():
            print("\n๐Ÿ”„ Extracting entities...")
            result = predictor.predict(email_text=email_text)
            
            print("\n๐Ÿ“‹ Extracted Entities:")
            print("-" * 40)
            print(result.to_json())
            
            if not result.success:
                print(f"\nโš ๏ธ Warning: {result.error or 'Could not parse JSON from response'}")
                print(f"Raw response: {result.raw_response[:200]}...")


if __name__ == "__main__":
    main()