|
| 1 | +package extractor |
| 2 | + |
| 3 | +import ( |
| 4 | + "cmp" |
| 5 | + "context" |
| 6 | + "encoding/json" |
| 7 | + "errors" |
| 8 | + "fmt" |
| 9 | + "net/url" |
| 10 | + "strings" |
| 11 | + "time" |
| 12 | + |
| 13 | + "github.com/PuerkitoBio/goquery" |
| 14 | + log "github.com/go-pkgz/lgr" |
| 15 | + "github.com/sashabaranov/go-openai" |
| 16 | + |
| 17 | + "github.com/ukeeper/ukeeper-readability/datastore" |
| 18 | +) |
| 19 | + |
| 20 | +// ErrOpenAIDisabled is returned by SuggestRule when no OpenAI client is configured |
| 21 | +var ErrOpenAIDisabled = errors.New("OpenAI is not configured") |
| 22 | + |
| 23 | +// ErrNoSelector is returned by SuggestRule when no attempt produced a selector that passed the checks |
| 24 | +var ErrNoSelector = errors.New("no usable selector was suggested") |
| 25 | + |
| 26 | +// errInvalidAnswer marks a model reply that is not the requested JSON |
| 27 | +var errInvalidAnswer = errors.New("reply is not the requested JSON") |
| 28 | + |
| 29 | +const ( |
| 30 | + suggestAttempts = 3 |
| 31 | + suggestCallTimeout = 60 * time.Second // one model call |
| 32 | + suggestedRuleUser = "openai" |
| 33 | + maxSelectorLen = 200 |
| 34 | + minSuggestedLen = 200 // characters of text a selector has to match |
| 35 | + maxWholePagePercent = 90 // a selector matching more of the page text than this is the page, not the article |
| 36 | + currentTextLen = 500 // characters of the current extraction shown to the model |
| 37 | +) |
| 38 | + |
| 39 | +const suggestPrompt = `You find the main article on a web page. You get an outline of the page body: one line per element ` + |
| 40 | + `with its tag, id, classes, the number of characters of visible text and the number of paragraphs. ` + |
| 41 | + `Reply with JSON only: {"selector": "<CSS selector>"}. ` + |
| 42 | + `The selector must match the element that holds the whole article text and nothing else: ` + |
| 43 | + `no navigation, comments, related links, share buttons or footer. ` + |
| 44 | + `Prefer an id or a stable class over positional selectors.` |
| 45 | + |
| 46 | +// Suggestion is what SuggestRule found for a URL |
| 47 | +type Suggestion struct { |
| 48 | + Selector string `json:"selector"` |
| 49 | + Saved bool `json:"saved"` // true when the selector was stored as a disabled rule for review |
| 50 | + Response *Response `json:"response"` // the page extracted with the selector |
| 51 | +} |
| 52 | + |
| 53 | +// attempt is a rejected selector together with the reason, passed back to the model |
| 54 | +type attempt struct { |
| 55 | + selector string |
| 56 | + reason string |
| 57 | +} |
| 58 | + |
| 59 | +// SuggestRule asks the model for a CSS selector of the article on the page, for a page the general |
| 60 | +// parser got wrong. The selector is applied to the page and has to match a plausible amount of text |
| 61 | +// before it is accepted. When the domain has no rule yet, it is stored as a disabled rule, so |
| 62 | +// nothing changes for readers until someone reviews and enables it. When the domain already has a |
| 63 | +// rule, the existing one is left alone and the suggestion is only returned. |
| 64 | +func (f *UReadability) SuggestRule(ctx context.Context, reqURL string) (*Suggestion, error) { |
| 65 | + if f.OpenAI == nil { |
| 66 | + return nil, ErrOpenAIDisabled |
| 67 | + } |
| 68 | + u, err := url.Parse(reqURL) |
| 69 | + if err != nil { |
| 70 | + return nil, fmt.Errorf("parse url %q: %w", reqURL, err) |
| 71 | + } |
| 72 | + |
| 73 | + var rule *datastore.Rule // the enabled rule, as extraction would use it |
| 74 | + if f.Rules != nil { |
| 75 | + if r, found := f.Rules.Get(ctx, reqURL); found { |
| 76 | + rule = &r |
| 77 | + } |
| 78 | + } |
| 79 | + |
| 80 | + rb, body, err := f.fetch(ctx, reqURL, rule) |
| 81 | + if err != nil { |
| 82 | + return nil, err |
| 83 | + } |
| 84 | + doc, err := goquery.NewDocumentFromReader(strings.NewReader(body)) |
| 85 | + if err != nil { |
| 86 | + return nil, err |
| 87 | + } |
| 88 | + |
| 89 | + current, _, _ := f.getContent(ctx, body, reqURL, rule) |
| 90 | + current = f.getText(current, "") |
| 91 | + outline := pageOutline(doc.Nodes[0]) |
| 92 | + pageLen := visibleTextLen(findBody(doc.Nodes[0])) |
| 93 | + |
| 94 | + var rejected []attempt |
| 95 | + for range suggestAttempts { |
| 96 | + selector, err := f.askSelector(ctx, reqURL, current, outline, rejected) |
| 97 | + if errors.Is(err, errInvalidAnswer) { |
| 98 | + rejected = append(rejected, attempt{reason: "the reply was not the requested JSON"}) |
| 99 | + continue |
| 100 | + } |
| 101 | + if err != nil { |
| 102 | + return nil, err |
| 103 | + } |
| 104 | + if reason := f.checkSelector(body, selector, current, pageLen); reason != "" { |
| 105 | + log.Printf("[INFO] selector %q for %s rejected: %s", selector, reqURL, reason) |
| 106 | + rejected = append(rejected, attempt{selector: selector, reason: reason}) |
| 107 | + continue |
| 108 | + } |
| 109 | + |
| 110 | + resp, err := f.parse(ctx, reqURL, body, rb, &datastore.Rule{Content: selector, Enabled: true}) |
| 111 | + if err != nil { |
| 112 | + return nil, err |
| 113 | + } |
| 114 | + return &Suggestion{Selector: selector, Saved: f.saveSuggested(ctx, u.Host, reqURL, selector), Response: resp}, nil |
| 115 | + } |
| 116 | + return nil, ErrNoSelector |
| 117 | +} |
| 118 | + |
| 119 | +// askSelector makes one model call and returns the selector from the reply |
| 120 | +func (f *UReadability) askSelector(ctx context.Context, reqURL, current, outline string, rejected []attempt) (string, error) { |
| 121 | + var sb strings.Builder |
| 122 | + fmt.Fprintf(&sb, "URL: %s\n\n", reqURL) |
| 123 | + if current != "" { |
| 124 | + if r := []rune(current); len(r) > currentTextLen { |
| 125 | + current = string(r[:currentTextLen]) |
| 126 | + } |
| 127 | + fmt.Fprintf(&sb, "The text extracted now is reported as wrong. It starts with:\n---\n%s\n---\n\n", current) |
| 128 | + } |
| 129 | + fmt.Fprintf(&sb, "Page body outline:\n---\n%s\n---\n", outline) |
| 130 | + for _, a := range rejected { |
| 131 | + if a.selector == "" { |
| 132 | + fmt.Fprintf(&sb, "\nAn earlier attempt failed: %s. Try again.", a.reason) |
| 133 | + continue |
| 134 | + } |
| 135 | + fmt.Fprintf(&sb, "\nThe selector %q was rejected: %s. Suggest a different one.", a.selector, a.reason) |
| 136 | + } |
| 137 | + |
| 138 | + callCtx, cancel := context.WithTimeout(ctx, suggestCallTimeout) |
| 139 | + defer cancel() |
| 140 | + resp, err := f.OpenAI.CreateChatCompletion(callCtx, openai.ChatCompletionRequest{ |
| 141 | + Model: cmp.Or(f.OpenAIModel, DefaultOpenAIModel), |
| 142 | + Messages: []openai.ChatCompletionMessage{ |
| 143 | + {Role: openai.ChatMessageRoleSystem, Content: suggestPrompt}, |
| 144 | + {Role: openai.ChatMessageRoleUser, Content: sb.String()}, |
| 145 | + }, |
| 146 | + ResponseFormat: &openai.ChatCompletionResponseFormat{Type: openai.ChatCompletionResponseFormatTypeJSONObject}, |
| 147 | + }) |
| 148 | + if err != nil { |
| 149 | + return "", fmt.Errorf("openai selector request: %w", err) |
| 150 | + } |
| 151 | + if len(resp.Choices) == 0 { |
| 152 | + return "", fmt.Errorf("openai returned no choices: %w", errInvalidAnswer) |
| 153 | + } |
| 154 | + |
| 155 | + var answer struct { |
| 156 | + Selector string `json:"selector"` |
| 157 | + } |
| 158 | + if err := json.Unmarshal([]byte(resp.Choices[0].Message.Content), &answer); err != nil || strings.TrimSpace(answer.Selector) == "" { |
| 159 | + return "", errInvalidAnswer |
| 160 | + } |
| 161 | + return strings.TrimSpace(answer.Selector), nil |
| 162 | +} |
| 163 | + |
| 164 | +// checkSelector applies the selector to the page and returns why it can't be the article, or "" when it can |
| 165 | +func (f *UReadability) checkSelector(body, selector, current string, pageLen int) string { |
| 166 | + if len(selector) > maxSelectorLen { |
| 167 | + return "it is too long" |
| 168 | + } |
| 169 | + res, err := extractWithSelector(body, selector) |
| 170 | + if err != nil || res == "" { |
| 171 | + return "it matches nothing on the page" |
| 172 | + } |
| 173 | + doc, err := goquery.NewDocumentFromReader(strings.NewReader(res)) |
| 174 | + if err != nil { |
| 175 | + return "what it matches can't be parsed" |
| 176 | + } |
| 177 | + n := visibleTextLen(findBody(doc.Nodes[0])) |
| 178 | + switch { |
| 179 | + case n < minSuggestedLen: |
| 180 | + return fmt.Sprintf("it matches only %d characters of text", n) |
| 181 | + case n*100 > pageLen*maxWholePagePercent: |
| 182 | + return "it matches almost all the text of the page" |
| 183 | + case f.getText(res, "") == current: |
| 184 | + return "it extracts the same text as the current result" |
| 185 | + } |
| 186 | + return "" |
| 187 | +} |
| 188 | + |
| 189 | +// saveSuggested stores the selector as a disabled rule when the domain has none. Both enabled and |
| 190 | +// disabled rules count, and an existing rule is never replaced. |
| 191 | +func (f *UReadability) saveSuggested(ctx context.Context, domain, reqURL, selector string) bool { |
| 192 | + if f.Rules == nil { |
| 193 | + return false |
| 194 | + } |
| 195 | + rule := datastore.Rule{Domain: domain, Content: selector, TestURLs: []string{reqURL}, User: suggestedRuleUser} |
| 196 | + saved, err := f.Rules.SaveIfAbsent(ctx, rule) |
| 197 | + switch { |
| 198 | + case err != nil: |
| 199 | + log.Printf("[WARN] failed to save suggested rule for %s: %v", domain, err) |
| 200 | + case !saved: |
| 201 | + log.Printf("[INFO] %s already has a rule, suggested selector %q is not saved", domain, selector) |
| 202 | + default: |
| 203 | + log.Printf("[INFO] saved disabled rule for %s with selector %q", domain, selector) |
| 204 | + } |
| 205 | + return err == nil && saved |
| 206 | +} |
0 commit comments