extract

package
v2.5.4 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 20, 2026 License: MIT Imports: 18 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package extract converts raw HTML and PDF payloads into clean GitHub-Flavored Markdown, plain text, resolved links, images, CSS branding signals, BM25 query-reranked passages, and `llms.txt` structured discovery metadata using only the Go standard library.

Extraction Pipeline

  1. Head metadata & branding signals (`<title>`, OpenGraph, canonical URL, favicon, CSS hex palette, fonts).
  2. Boilerplate & chrome removal (`<nav>`, `<footer>`, `<aside>`, `<script>`, `<style>`) with `<main>` / `<article>` focus when `OnlyMainContent` is enabled.
  3. Sentinel-protected `<pre><code>` and multi-backtick inline `<code>` conversion so generic type signatures (`Promise<void>`, `#include <stdio.h>`) survive HTML tag stripping intact.
  4. GFM table reconstruction, optional BM25 passage reranking (RerankPassages), and optional PII redaction (RedactPII).
  5. Streaming Poppler `pdftotext -layout` extraction with a pure-Go FlateDecode fallback (ExtractPDFText) for distroless Lite deployments.

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func CandidateCompanionMarkdownURL

func CandidateCompanionMarkdownURL(pageURL string) string

CandidateCompanionMarkdownURL returns `<url>.md` when `pageURL` looks like a clean documentation/article path (e.g. `https://developers.cloudflare.com/workers/wrangler` -> `https://developers.cloudflare.com/workers/wrangler.md`).

func DetectRenderedChallenge

func DetectRenderedChallenge(rawHTML string) string

DetectRenderedChallenge checks whether an HTML payload (HTTP or headless browser) is gated by a bot/CAPTCHA challenge. Delegates to `classify.ClassifyWAF` (`R2` & `R3`) so all 4 anti-false-positive guardrails (visible word-count veto, Schema.org JSON-LD veto, `<pre>`/`<code>` immunity, and `<nav>` landmark veto) protect rendered pages too.

func ExtractPDFFileText

func ExtractPDFFileText(ctx context.Context, pdfPath string, maxPages int) (text string, usedPoppler bool, err error)

ExtractPDFFileText extracts UTF-8 text from an on-disk PDF file up to `maxPages` (default 60) using `pdftotext` (`poppler-utils`), falling back to a bounded pure-Go FlateDecode stream reader when `pdftotext` is absent. Reading from a seekable file path allows Poppler to seek directly to the PDF `xref` trailer at EOF without buffering large manuals in RAM.

func ExtractPDFText

func ExtractPDFText(ctx context.Context, pdfBytes []byte, maxPages int) (text string, usedPoppler bool, err error)

ExtractPDFText extracts UTF-8 text from `pdfBytes` up to `maxPages` (default 60). On Fat nodes (`edgefetch_fat`), it streams `pdfBytes` directly over stdin into `pdftotext -layout` (`poppler-utils`, zero temporary files on disk). On distroless Lite nodes without `pdftotext`, it falls back to a pure-Go FlateDecode content-stream text reader so PDF fetches remain functional everywhere.

func HasPDFToText

func HasPDFToText() bool

HasPDFToText reports whether `pdftotext` (`poppler-utils`, bundled in `edgefetch_fat`) is available in $PATH.

func IsPDFBytes

func IsPDFBytes(data []byte) bool

IsPDFBytes checks whether `data` starts with `%PDF-` within the first 1024 bytes (per PDF spec §7.5.2).

func NeedsBrowserRender

func NeedsBrowserRender(rawHTML string) bool

NeedsBrowserRender heuristics detect empty client-side SPA shells (`<div id="root"></div>` + script bundles with almost zero SSR body text) so `renderMode: "auto"` only launches Chromium when static HTTP/2 lacks content.

func PlainText

func PlainText(rawHTML string) string

PlainText strips scripts/styles/tags from HTML and collapses whitespace.

func RedactPII

func RedactPII(s string) string

RedactPII replaces email addresses, SSNs, phone numbers, and Luhn-valid payment card numbers with `[REDACTED_*]`.

func RerankPassages

func RerankPassages(doc, query string, maxChars int) string

RerankPassages splits long Markdown or PDF text into semantic paragraphs/sections and selects the top chunks matching `query` via BM25-style term scoring + exact-phrase boost while preserving original document reading order.

Types

type BrandingProfile

type BrandingProfile struct {
	Title        string   `json:"title,omitempty"`
	Description  string   `json:"description,omitempty"`
	CanonicalURL string   `json:"canonicalUrl,omitempty"`
	Favicon      string   `json:"favicon,omitempty"`
	OGImage      string   `json:"ogImage,omitempty"`
	ThemeColor   string   `json:"themeColor,omitempty"`
	Colors       []string `json:"colors,omitempty"`
	Fonts        []string `json:"fonts,omitempty"`
}

BrandingProfile summarizes visual brand identity signals extracted from HTML/CSS (`formats: ["branding"]`).

type ExtractOptions

type ExtractOptions struct {
	BaseURL         string
	OnlyMainContent bool
	IncludeLinks    bool
	IncludeImages   bool
	IncludeBranding bool
	RedactPII       bool
	Query           string
	MaxChars        int
}

ExtractOptions configures HTML extraction.

type ImageInfo

type ImageInfo struct {
	URL string `json:"url"`
	Alt string `json:"alt,omitempty"`
}

ImageInfo describes an image discovered on a page.

type LlmsDiscovery

type LlmsDiscovery struct {
	Found           bool       `json:"found"`
	LlmsTxtURL      string     `json:"llmsTxtUrl,omitempty"`
	LlmsFullTxtURL  string     `json:"llmsFullTxtUrl,omitempty"`
	CompanionMdURL  string     `json:"companionMdUrl,omitempty"`
	UsedCompanionMd bool       `json:"usedCompanionMd,omitempty"`
	SiteTitle       string     `json:"siteTitle,omitempty"`
	SiteSummary     string     `json:"siteSummary,omitempty"`
	MatchedEntry    *LlmsLink  `json:"matchedEntry,omitempty"`
	RelatedLinks    []LlmsLink `json:"relatedLinks,omitempty"`
}

LlmsDiscovery reports `llms.txt` / companion `.md` enrichment attached to a crawled page Result.

type LlmsDocument

type LlmsDocument struct {
	SourceURL  string     `json:"sourceUrl"`
	Title      string     `json:"title,omitempty"`
	Summary    string     `json:"summary,omitempty"`
	FullTxtURL string     `json:"fullTxtUrl,omitempty"`
	Links      []LlmsLink `json:"links,omitempty"`
	RawPreview string     `json:"rawPreview,omitempty"`
}

LlmsDocument represents a parsed `/llms.txt` index per https://llmstxt.org/.

func ParseLlmsTxt

func ParseLlmsTxt(raw, sourceURL string) (*LlmsDocument, bool)

ParseLlmsTxt parses an `llms.txt` Markdown file, rejecting HTML 200 soft-404 pages masquerading as `/llms.txt`.

Example
package main

import (
	"fmt"

	"github.com/bartrumb/edgefetch/v2/internal/extract"
)

func main() {
	raw := `# EdgeFetch Docs
> Distributed edge web crawler for AI agents.

## Guides
- [Quickstart](/docs/quickstart.md): Deploy Hub + Go Worker in 60 seconds
`
	doc, ok := extract.ParseLlmsTxt(raw, "https://docs.example.com/llms.txt")
	fmt.Println("valid:", ok, "| title:", doc.Title, "| firstUrl:", doc.Links[0].URL)
}
Output:
valid: true | title: EdgeFetch Docs | firstUrl: https://docs.example.com/docs/quickstart.md

func (*LlmsDocument) MatchPage

func (doc *LlmsDocument) MatchPage(pageURL string) (matched *LlmsLink, companionMdURL string, related []LlmsLink)

MatchPage finds any exact orcompanion `.md` entry in `doc` corresponding to `pageURL`, plus up to 8 same-section related links.

type LlmsLink struct {
	Section string `json:"section,omitempty"`
	Title   string `json:"title"`
	URL     string `json:"url"`
	Notes   string `json:"notes,omitempty"`
}

LlmsLink represents a single `- [Title](URL): Notes` entry inside `/llms.txt`.

type PageExtraction

type PageExtraction struct {
	Title       string           `json:"title,omitempty"`
	Description string           `json:"description,omitempty"`
	Favicon     string           `json:"favicon,omitempty"`
	Markdown    string           `json:"markdown,omitempty"`
	Text        string           `json:"text,omitempty"`
	Links       []string         `json:"links,omitempty"`
	Images      []ImageInfo      `json:"images,omitempty"`
	Branding    *BrandingProfile `json:"branding,omitempty"`
}

PageExtraction holds the structured outputs extracted from an HTML document.

func ExtractHTML

func ExtractHTML(rawHTML string, opts ExtractOptions) PageExtraction

ExtractHTML parses rawHTML into clean Markdown, plain text, links, images, and optional branding profile.

Example
package main

import (
	"fmt"

	"github.com/bartrumb/edgefetch/v2/internal/extract"
)

func main() {
	rawHTML := `<!doctype html>
<html>
  <head><title>Async Runtime</title></head>
  <body>
    <nav><a href="/home">Home</a></nav>
    <main>
      <h1>Async Runtime</h1>
      <p>Returns <code>Promise&lt;void&gt;</code> when complete.</p>
    </main>
  </body>
</html>`
	page := extract.ExtractHTML(rawHTML, extract.ExtractOptions{
		BaseURL:         "https://docs.example.com/guide",
		OnlyMainContent: true,
	})
	fmt.Println(page.Markdown)
}
Output:
# Async Runtime

Returns `Promise<void>` when complete.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL