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
397
//! Model serialization and loading module.
//!
//! This module handles the serialization, deserialization, and loading of
//! the phishing-URL detection model (a LightGBM-trained decision tree forest). The model is
//! stored in two formats:
//!
//! - **JSON** (`model_data.json`): Human-readable format used during
//! development and debugging.
//! - **Bincode** (`model_data.bincode`): Compact binary format embedded
//! into the library via `include_bytes!` for zero-configuration usage
//! in production.
//!
//! The bincode format is approximately 48% smaller than JSON, reducing
//! the embedded model from ~236 KB to ~123 KB.
use ;
use File;
use ;
use Path;
/// Embedded default model in bincode format.
///
/// This constant is compiled into the library binary at build time,
/// allowing users to call [`load_default_model`] without specifying
/// a file path. The model file is located at `resources/model_data.bincode`
/// relative to the project root.
const DEFAULT_MODEL_BYTES: & = include_bytes!;
/// A single decision tree in the Random Forest.
///
/// Each field is a flat array representation of the tree structure, where
/// index `i` corresponds to node `i`. The tree is traversed starting from
/// node 0, following left/right child pointers until a leaf node (marked
/// by `left == -1`) is reached.
///
/// # Fields
///
/// - `left`: Left child indices (-1 indicates a leaf node)
/// - `right`: Right child indices (-1 indicates a leaf node)
/// - `feature`: Feature index used for splitting at each internal node
/// - `threshold`: Threshold value for the split (feature <= threshold → left)
/// - `value`: Prediction value stored at leaf nodes (phishing probability)
///
/// # Examples
///
/// ```
/// use phishnano::model::Tree;
///
/// let tree = Tree {
/// left: vec![-1],
/// right: vec![-1],
/// feature: vec![0],
/// threshold: vec![0.5],
/// value: vec![0.9],
/// };
/// assert_eq!(tree.value[0], 0.9);
/// ```
/// The complete decision tree forest model for phishing URL detection.
///
/// # Fields
///
/// - `n_features`: Number of n-gram hash features (typically 500)
/// - `n_manual_features`: Number of manual engineered features (typically 39:
/// 21 hand-crafted + 18 structural)
/// - `ngram_range`: Character n-gram range `[min, max]` (typically `[2, 3]`)
/// - `init_score`: LightGBM additive bias; the forest score is
/// `sigmoid(init_score + Σ raw_leaf)` (0.0 for legacy sklearn exports)
/// - `trees`: Collection of decision trees in the forest
///
/// # Feature Layout
///
/// The feature vector has `n_features + n_manual_features` dimensions:
/// - Indices `[0, n_features)`: Character n-gram hash counts
/// - Indices `[n_features, n_features + n_manual_features)`: Manual features
///
/// # Examples
///
/// ```
/// use phishnano::model::{Model, Tree};
///
/// let model = Model {
/// n_features: 500,
/// n_manual_features: 21,
/// ngram_range: [2, 3],
/// init_score: 0.0,
/// trees: vec![Tree {
/// left: vec![-1],
/// right: vec![-1],
/// feature: vec![0],
/// threshold: vec![0.5],
/// value: vec![0.8],
/// }],
/// };
/// assert_eq!(model.trees.len(), 1);
/// ```
/// Load the default embedded model (bincode format, zero configuration).
///
/// This function loads the model that was compiled into the library at
/// build time via `include_bytes!`. It requires no file path and is the
/// recommended way for end users to load the model.
///
/// # Returns
///
/// - `Ok(Model)` on successful deserialization
/// - `Err` if the embedded model data is corrupted
///
/// # Errors
///
/// Returns an error if the embedded bincode data is corrupted or cannot
/// be deserialized. This should never happen under normal circumstances,
/// as the embedded model is validated at build time.
///
/// # Examples
///
/// ```no_run
/// use phishnano::load_default_model;
/// use phishnano::predict_url;
///
/// let model = load_default_model().expect("Failed to load model");
/// let score = predict_url("http://suspicious.com", &model);
/// ```
/// Load a model from a file path, auto-detecting bincode or JSON format.
///
/// The function reads the entire file into memory and attempts bincode
/// deserialization first. If that fails, it falls back to JSON. This
/// allows users to load either format without specifying the type.
///
/// # Arguments
///
/// - `path`: Path to the model file (`.json` or `.bincode`)
///
/// # Returns
///
/// - `Ok(Model)` on successful load
/// - `Err` if the file cannot be read or deserialized
///
/// # Errors
///
/// Returns an error if:
/// - The file does not exist or cannot be read (IO error)
/// - The file content is neither valid bincode nor valid JSON
/// (deserialization error)
///
/// # Examples
///
/// ```no_run
/// use phishnano::load_model_from_path;
///
/// // Load a bincode or JSON model from a file
/// let model = load_model_from_path("my_model.bincode")
/// .expect("Failed to load model");
/// ```
/// Load a model from raw bytes, auto-detecting bincode or JSON format.
///
/// Format detection is based on the first and last non-whitespace bytes:
/// - JSON starts with `{` (0x7b) and ends with `}` (0x7d)
/// - Bincode is any other binary format
///
/// This explicit detection avoids the risk of bincode silently accepting
/// JSON or corrupted data as a garbage model (bincode has no magic number
/// or checksum to reject invalid input).
///
/// # Arguments
///
/// - `data`: Raw bytes of the model file
///
/// # Returns
///
/// - `Ok(Model)` if the data is valid JSON or bincode
/// - `Err` if deserialization fails for the detected format
///
/// # Errors
///
/// Returns an error if:
/// - The data is detected as JSON but `serde_json::from_slice` fails
/// - The data is detected as bincode but `bincode::deserialize` fails
///
/// # Examples
///
/// ```
/// use phishnano::load_model_from_bytes;
///
/// // Load a model from a JSON byte slice
/// let json = br#"{"n_features":10,"n_manual_features":5,"ngram_range":[2,3],"trees":[]}"#;
/// let model = load_model_from_bytes(json).expect("Failed to load");
/// assert_eq!(model.n_features, 10);
/// ```
/// Convert a JSON model file to bincode format and write to output path.
///
/// This function is used after training to produce the compact bincode
/// model that gets embedded into the library. The typical workflow is:
///
/// 1. Python `train.py` exports the model as JSON
/// 2. CLI `--convert` calls this function to produce bincode
/// 3. Bincode file is placed in `resources/model_data.bincode`
/// 4. Library is rebuilt to embed the new bincode via the `include_bytes!` macro
///
/// # Arguments
///
/// - `json_path`: Path to the input JSON model file
/// - `bincode_path`: Path for the output bincode model file
///
/// # Returns
///
/// - `Ok(u64)`: Size of the bincode output in bytes
/// - `Err` if reading JSON or writing bincode fails
///
/// # Errors
///
/// Returns an error if:
/// - The input JSON file cannot be read or parsed
/// - The output bincode file cannot be written
///
/// # Examples
///
/// ```no_run
/// use phishnano::convert_json_to_bincode;
///
/// let size = convert_json_to_bincode("model_data.json", "model_data.bincode")
/// .expect("Conversion failed");
/// println!("Bincode size: {} bytes", size);
/// ```