Fill in an inventory entry's empty boxes from its website
On the entry form, "Fill in the empty boxes" reads their website. Links, social accounts and feeds come straight from the pages (no guessing); the AI drafts the name if missing, a description, keywords, hashtags, and talking points set against the company profile for the relationship chosen. Typed values stay, nothing is saved until Save, and the form says which boxes were filled. Website reading moves from the profile draft into internal/site, shared by both, and now also collects links and declared RSS/Atom feeds (comment feeds skipped; Fill takes up to three). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
+4
-135
@@ -2,44 +2,31 @@ package profile
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"html"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"regexp"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"supermarket/internal/ai"
|
||||
"supermarket/internal/site"
|
||||
)
|
||||
|
||||
// Draft reads the company's website and asks the AI for a first draft of the
|
||||
// profile, for the user to correct. Nothing is saved.
|
||||
func Draft(ctx context.Context, client ai.Client, siteURL string) (*Profile, error) {
|
||||
pages, err := fetchSite(ctx, siteURL)
|
||||
st, err := site.Read(ctx, siteURL, "Supermarket/1 (profile draft)")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var b strings.Builder
|
||||
for _, pg := range pages {
|
||||
fmt.Fprintf(&b, "<page url=%q>\n%s\n</page>\n\n", pg.url, pg.text)
|
||||
}
|
||||
|
||||
var draft Profile
|
||||
err = ai.GenerateJSON(ctx, client, ai.Request{
|
||||
Task: ai.TaskProfile,
|
||||
System: draftSystem,
|
||||
Prompt: "Here is text from the company's website. Draft the profile.\n\n" + b.String(),
|
||||
Prompt: "Here is text from the company's website. Draft the profile.\n\n" + st.PromptText(),
|
||||
MaxTokens: 8000,
|
||||
Schema: draftSchema(),
|
||||
}, &draft)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
draft.Websites = []Website{{URL: pages[0].url}}
|
||||
draft.Websites = []Website{{URL: st.Pages[0].URL}}
|
||||
draft.Clean()
|
||||
return &draft, nil
|
||||
}
|
||||
@@ -85,121 +72,3 @@ func draftSchema() map[string]any {
|
||||
"accounts": obj(map[string]any{"x": str, "linkedin": str}),
|
||||
})
|
||||
}
|
||||
|
||||
type sitePage struct {
|
||||
url string
|
||||
text string
|
||||
}
|
||||
|
||||
const (
|
||||
maxPageBytes = 2 << 20
|
||||
maxPageText = 12000 // characters of text kept per page
|
||||
maxPages = 4
|
||||
)
|
||||
|
||||
// Pages beyond the home page worth reading, by the words in their links.
|
||||
var usefulLink = regexp.MustCompile(`(?i)about|product|pricing|features|solutions|customers|services|platform`)
|
||||
|
||||
var (
|
||||
hrefRe = regexp.MustCompile(`(?i)<a\s[^>]*href\s*=\s*["']([^"']+)["']`)
|
||||
dropRe = regexp.MustCompile(`(?is)<(script|style|noscript|svg|template)\b.*?</(script|style|noscript|svg|template)>`)
|
||||
tagRe = regexp.MustCompile(`(?s)<[^>]+>`)
|
||||
metaRe = regexp.MustCompile(`(?is)<meta\s[^>]*name\s*=\s*["']description["'][^>]*content\s*=\s*["']([^"']*)["']`)
|
||||
titlRe = regexp.MustCompile(`(?is)<title[^>]*>(.*?)</title>`)
|
||||
blockRe = regexp.MustCompile(`(?i)<(br|/p|/div|/h[1-6]|/li|/tr|/section|/header|/footer)\b[^>]*>`)
|
||||
wsRe = regexp.MustCompile(`[ \t\f\r]+`)
|
||||
nlRe = regexp.MustCompile(`\n\s*\n+`)
|
||||
)
|
||||
|
||||
func fetchSite(ctx context.Context, siteURL string) ([]sitePage, error) {
|
||||
siteURL = strings.TrimSpace(siteURL)
|
||||
if !strings.Contains(siteURL, "://") {
|
||||
siteURL = "https://" + siteURL
|
||||
}
|
||||
base, err := url.Parse(siteURL)
|
||||
if err != nil || (base.Scheme != "http" && base.Scheme != "https") || base.Host == "" {
|
||||
return nil, fmt.Errorf("%q isn't a website address", siteURL)
|
||||
}
|
||||
client := &http.Client{Timeout: 20 * time.Second}
|
||||
|
||||
home, homeHTML, err := fetchPage(ctx, client, base.String())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
pages := []sitePage{home}
|
||||
seen := map[string]bool{home.url: true, base.String(): true}
|
||||
|
||||
finalBase, _ := url.Parse(home.url)
|
||||
for _, m := range hrefRe.FindAllStringSubmatch(homeHTML, -1) {
|
||||
if len(pages) >= maxPages {
|
||||
break
|
||||
}
|
||||
ref, err := url.Parse(html.UnescapeString(m[1]))
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
u := finalBase.ResolveReference(ref)
|
||||
u.Fragment, u.RawQuery = "", ""
|
||||
if u.Host != finalBase.Host || seen[u.String()] || !usefulLink.MatchString(u.Path) {
|
||||
continue
|
||||
}
|
||||
seen[u.String()] = true
|
||||
if pg, _, err := fetchPage(ctx, client, u.String()); err == nil {
|
||||
pages = append(pages, pg)
|
||||
}
|
||||
}
|
||||
return pages, nil
|
||||
}
|
||||
|
||||
func fetchPage(ctx context.Context, client *http.Client, u string) (sitePage, string, error) {
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, u, nil)
|
||||
if err != nil {
|
||||
return sitePage{}, "", err
|
||||
}
|
||||
req.Header.Set("User-Agent", "Supermarket/1 (profile draft)")
|
||||
req.Header.Set("Accept", "text/html")
|
||||
res, err := client.Do(req)
|
||||
if err != nil {
|
||||
return sitePage{}, "", fmt.Errorf("can't read %s: %w", u, err)
|
||||
}
|
||||
defer res.Body.Close()
|
||||
if res.StatusCode != http.StatusOK {
|
||||
return sitePage{}, "", fmt.Errorf("%s answered %s", u, res.Status)
|
||||
}
|
||||
if ct := res.Header.Get("Content-Type"); ct != "" && !strings.Contains(ct, "html") {
|
||||
return sitePage{}, "", errors.New(u + " isn't a web page")
|
||||
}
|
||||
raw, err := io.ReadAll(io.LimitReader(res.Body, maxPageBytes))
|
||||
if err != nil {
|
||||
return sitePage{}, "", err
|
||||
}
|
||||
src := string(raw)
|
||||
return sitePage{url: res.Request.URL.String(), text: pageText(src)}, src, nil
|
||||
}
|
||||
|
||||
// pageText reduces HTML to its title, meta description and visible text.
|
||||
func pageText(src string) string {
|
||||
var parts []string
|
||||
if m := titlRe.FindStringSubmatch(src); m != nil {
|
||||
parts = append(parts, "Title: "+clean(m[1]))
|
||||
}
|
||||
if m := metaRe.FindStringSubmatch(src); m != nil {
|
||||
parts = append(parts, "Description: "+clean(m[1]))
|
||||
}
|
||||
body := dropRe.ReplaceAllString(src, " ")
|
||||
body = blockRe.ReplaceAllString(body, "\n")
|
||||
body = tagRe.ReplaceAllString(body, " ")
|
||||
body = html.UnescapeString(body)
|
||||
body = wsRe.ReplaceAllString(body, " ")
|
||||
body = nlRe.ReplaceAllString(body, "\n")
|
||||
parts = append(parts, strings.TrimSpace(body))
|
||||
text := strings.Join(parts, "\n")
|
||||
if r := []rune(text); len(r) > maxPageText {
|
||||
text = string(r[:maxPageText])
|
||||
}
|
||||
return text
|
||||
}
|
||||
|
||||
func clean(s string) string {
|
||||
return strings.TrimSpace(wsRe.ReplaceAllString(html.UnescapeString(tagRe.ReplaceAllString(s, " ")), " "))
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user