-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathdit.go
More file actions
278 lines (247 loc) · 7.49 KB
/
dit.go
File metadata and controls
278 lines (247 loc) · 7.49 KB
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
// Package dit classifies HTML form, field, and page types.
//
// It provides a three-stage ML pipeline: logistic regression for form types,
// a CRF model for field types, and logistic regression for page types.
//
// c, _ := dit.New()
// results, _ := c.ExtractForms(htmlString)
// for _, r := range results {
// fmt.Println(r.Type) // "login"
// fmt.Println(r.Fields) // {"username": "username or email", "password": "password"}
// }
//
// page, _ := c.ExtractPageType(htmlString)
// fmt.Println(page.Type) // "login"
package dit
import (
"fmt"
"os"
"path/filepath"
"github.com/happyhackingspace/dit/captcha"
"github.com/happyhackingspace/dit/classifier"
"github.com/happyhackingspace/dit/internal/htmlutil"
)
// Classifier wraps the form and field type classification models.
type Classifier struct {
fc *classifier.FormFieldClassifier
}
// FormResult holds the classification result for a single form.
type FormResult struct {
Type string `json:"type"`
Captcha string `json:"captcha_type,omitempty"`
Fields map[string]string `json:"fields,omitempty"`
}
// FormResultProba holds probability-based classification results for a single form.
type FormResultProba struct {
Type map[string]float64 `json:"type"`
Captcha string `json:"captcha_type,omitempty"`
Fields map[string]map[string]float64 `json:"fields,omitempty"`
}
// PageResult holds the page type classification result.
type PageResult struct {
Type string `json:"type"`
Captcha string `json:"captcha_type,omitempty"`
Forms []FormResult `json:"forms,omitempty"`
}
// PageResultProba holds probability-based page type classification results.
type PageResultProba struct {
Type map[string]float64 `json:"type"`
Captcha string `json:"captcha_type,omitempty"`
Forms []FormResultProba `json:"forms,omitempty"`
}
// New loads the classifier from "model.json", searching the current directory
// and parent directories up to the module root, then ~/.dit/model.json.
func New() (*Classifier, error) {
path, err := FindModel("model.json")
if err != nil {
return nil, fmt.Errorf("dit: %w", err)
}
return Load(path)
}
// ModelDir returns the default model storage directory (~/.dit).
func ModelDir() string {
home, err := os.UserHomeDir()
if err != nil {
return ""
}
return filepath.Join(home, ".dit")
}
// FindModel searches for a model file by name.
// Search order: current dir walk-up to module root, then ~/.dit/.
func FindModel(name string) (string, error) {
dir, err := os.Getwd()
if err != nil {
return "", err
}
for {
path := filepath.Join(dir, name)
if _, err := os.Stat(path); err == nil {
return path, nil
}
if _, err := os.Stat(filepath.Join(dir, "go.mod")); err == nil {
break
}
parent := filepath.Dir(dir)
if parent == dir {
break
}
dir = parent
}
// Check ~/.dit/
if modelDir := ModelDir(); modelDir != "" {
path := filepath.Join(modelDir, name)
if _, err := os.Stat(path); err == nil {
return path, nil
}
}
return "", fmt.Errorf("model.json not found")
}
// Load loads a trained classifier from a model file.
func Load(path string) (*Classifier, error) {
fc, err := classifier.LoadClassifier(path)
if err != nil {
return nil, fmt.Errorf("dit: %w", err)
}
return &Classifier{fc: fc}, nil
}
// Save writes the classifier to a model file.
func (c *Classifier) Save(path string) error {
if c.fc == nil {
return fmt.Errorf("dit: classifier not initialized")
}
if err := c.fc.SaveModel(path); err != nil {
return fmt.Errorf("dit: %w", err)
}
return nil
}
// ExtractForms extracts and classifies all forms in the given HTML string.
// Returns an empty slice (not nil) if no forms are found.
func (c *Classifier) ExtractForms(html string) ([]FormResult, error) {
if c.fc == nil || c.fc.FormModel == nil {
return nil, fmt.Errorf("dit: classifier not initialized")
}
results, err := c.fc.ExtractForms(html, false, 0, true)
if err != nil {
return nil, fmt.Errorf("dit: %w", err)
}
doc, err := htmlutil.LoadHTMLString(html)
if err != nil {
return nil, fmt.Errorf("dit: %w", err)
}
forms := htmlutil.GetForms(doc)
out := make([]FormResult, len(results))
detector := &captcha.CaptchaDetector{}
for i, r := range results {
capStr := ""
if i < len(forms) {
if ct := detector.DetectInForm(forms[i]); ct != captcha.CaptchaTypeNone {
capStr = string(ct)
}
}
out[i] = FormResult{
Type: r.Result.Form,
Captcha: capStr,
Fields: r.Result.Fields,
}
}
return out, nil
}
// ExtractFormsProba extracts forms and returns classification probabilities.
// Probabilities below threshold are omitted.
func (c *Classifier) ExtractFormsProba(html string, threshold float64) ([]FormResultProba, error) {
if c.fc == nil || c.fc.FormModel == nil {
return nil, fmt.Errorf("dit: classifier not initialized")
}
results, err := c.fc.ExtractForms(html, true, threshold, true)
if err != nil {
return nil, fmt.Errorf("dit: %w", err)
}
doc, err := htmlutil.LoadHTMLString(html)
if err != nil {
return nil, fmt.Errorf("dit: %w", err)
}
forms := htmlutil.GetForms(doc)
out := make([]FormResultProba, len(results))
detector := &captcha.CaptchaDetector{}
for i, r := range results {
capStr := ""
if i < len(forms) {
if ct := detector.DetectInForm(forms[i]); ct != captcha.CaptchaTypeNone {
capStr = string(ct)
}
}
out[i] = FormResultProba{
Type: r.Proba.Form,
Captcha: capStr,
Fields: r.Proba.Fields,
}
}
return out, nil
}
// detectPageCaptcha detects page-level CAPTCHA by first checking each form
// and falling back to a full-HTML scan.
func detectPageCaptcha(htmlStr string) string {
doc, err := htmlutil.LoadHTMLString(htmlStr)
if err == nil {
detector := &captcha.CaptchaDetector{}
for _, f := range htmlutil.GetForms(doc) {
if ct := detector.DetectInForm(f); ct != captcha.CaptchaTypeNone {
return string(ct)
}
}
}
if ct := captcha.DetectCaptchaInHTML(htmlStr); ct != captcha.CaptchaTypeNone {
return string(ct)
}
return ""
}
// ExtractPageType classifies the page type and all forms in the HTML.
func (c *Classifier) ExtractPageType(html string) (*PageResult, error) {
if c.fc == nil || c.fc.FormModel == nil {
return nil, fmt.Errorf("dit: classifier not initialized")
}
if c.fc.PageModel == nil {
return nil, fmt.Errorf("dit: page model not available")
}
formResults, pageResult, _, err := c.fc.ExtractPage(html, false, 0, true)
if err != nil {
return nil, fmt.Errorf("dit: %w", err)
}
forms := make([]FormResult, len(formResults))
for i, r := range formResults {
forms[i] = FormResult{
Type: r.Result.Form,
Fields: r.Result.Fields,
}
}
return &PageResult{
Type: pageResult.Form,
Captcha: detectPageCaptcha(html),
Forms: forms,
}, nil
}
// ExtractPageTypeProba classifies the page type with probabilities.
func (c *Classifier) ExtractPageTypeProba(html string, threshold float64) (*PageResultProba, error) {
if c.fc == nil || c.fc.FormModel == nil {
return nil, fmt.Errorf("dit: classifier not initialized")
}
if c.fc.PageModel == nil {
return nil, fmt.Errorf("dit: page model not available")
}
formResults, _, pageProba, err := c.fc.ExtractPage(html, true, threshold, true)
if err != nil {
return nil, fmt.Errorf("dit: %w", err)
}
forms := make([]FormResultProba, len(formResults))
for i, r := range formResults {
forms[i] = FormResultProba{
Type: r.Proba.Form,
Fields: r.Proba.Fields,
}
}
return &PageResultProba{
Type: pageProba.Form,
Captcha: detectPageCaptcha(html),
Forms: forms,
}, nil
}