Skip to content

tw93/Waza / plugins/waza/skills/read

Fetches URLs and PDFs, then summarizes or returns clean Markdown; can also search the web through DeepSeek when built-in search is thin. Use when asked to read, fetch, quote, cite, convert, or save a URL or PDF. Not for local text files already in the repo.

FileKindSize
SKILL.mdskill md7.7 KB
references/read-methods.mdmarkdown5.2 KB
scripts/deepseek.pyscript3.9 KB
scripts/fetch.shscript3.9 KB
scripts/fetch_feishu.pyscript8.9 KB
scripts/fetch_local.pyscript7.1 KB
scripts/fetch_weixin.pyscript3.6 KB

scripts/fetch_local.py

View on GitHub
#!/usr/bin/env python3
"""Local URL → Markdown extractor. Privacy-preserving tier 1 for fetch.sh.

Two paths, picked at runtime:

1. **Best path**: `readability-lxml` + `html2text` installed. Extract main
   content via readability scoring, convert to clean Markdown. Quality close
   to defuddle.md / r.jina.ai for static pages.

2. **Fallback path**: stdlib only. Strip HTML tags, collapse whitespace, drop
   <script>/<style>/<nav>/<footer>. Quality is poor for JS-heavy pages and
   complex layouts, but works for simple article-style HTML without any
   third-party dependency.

JS-rendered pages (X/Twitter, paywalled news, SPA) are out of reach for both
paths. Use `fetch.sh --use-proxy` for those.

Exit codes:
  0  success, markdown on stdout
  1  fetch or extraction failed; reason on stderr
  2  invocation error (missing URL)
"""

from __future__ import annotations

import argparse
import re
import sys
import urllib.error
import urllib.request
from html.parser import HTMLParser


USER_AGENT = (
    "Mozilla/5.0 (Macintosh; Intel Mac OS X 12_0) "
    "AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120 Safari/537.36"
)
FETCH_TIMEOUT_SECS = 20


def fetch_html(url: str) -> str:
    req = urllib.request.Request(url, headers={"User-Agent": USER_AGENT})
    # Direct connection by contract: a system proxy is a third party too, and
    # --use-proxy is the only opt-in for sending the URL off-machine. urllib
    # would otherwise honor http_proxy/https_proxy env silently.
    opener = urllib.request.build_opener(urllib.request.ProxyHandler({}))
    with opener.open(req, timeout=FETCH_TIMEOUT_SECS) as resp:
        raw = resp.read()
    # Detect charset from Content-Type header; fall back to utf-8 with replace.
    charset = "utf-8"
    ctype = resp.headers.get("Content-Type", "")
    m = re.search(r"charset=([\w\-]+)", ctype, re.IGNORECASE)
    if m:
        charset = m.group(1).lower()
    try:
        return raw.decode(charset, errors="replace")
    except LookupError:
        return raw.decode("utf-8", errors="replace")


def extract_with_readability(html: str, url: str) -> str | None:
    """Best path: readability-lxml + html2text. Returns Markdown or None if
    deps missing. Raises only on genuine extraction failure."""
    try:
        from readability import Document  # type: ignore
        import html2text  # type: ignore
    except ImportError:
        return None
    doc = Document(html)
    cleaned_html = doc.summary(html_partial=True)
    title = (doc.short_title() or "").strip()
    converter = html2text.HTML2Text()
    converter.body_width = 0
    converter.unicode_snob = True
    converter.ignore_links = False
    converter.ignore_images = False
    body = converter.handle(cleaned_html).strip()
    if not body:
        return None
    header = ""
    if title:
        header = f"# {title}\n\n"
    return f"{header}> Source: {url}\n\n{body}\n"


class _StdlibStripper(HTMLParser):
    """Fallback HTML → text converter using only stdlib. Quality is poor but
    deterministic; intended as a last resort when readability isn't installed.
    Drops common non-content blocks (script/style/nav/footer/aside)."""

    DROP_TAGS = {"script", "style", "nav", "footer", "aside", "noscript", "form"}
    BLOCK_TAGS = {
        "p", "div", "section", "article", "li", "ul", "ol",
        "h1", "h2", "h3", "h4", "h5", "h6", "br", "tr",
    }

    def __init__(self) -> None:
        super().__init__()
        self._buf: list[str] = []
        self._drop_depth = 0
        self._title = ""
        self._in_title = False

    def handle_starttag(self, tag, attrs):
        if tag in self.DROP_TAGS:
            self._drop_depth += 1
        elif tag == "title":
            self._in_title = True
        elif tag in self.BLOCK_TAGS:
            self._buf.append("\n")

    def handle_endtag(self, tag):
        if tag in self.DROP_TAGS:
            self._drop_depth = max(0, self._drop_depth - 1)
        elif tag == "title":
            self._in_title = False
        elif tag in self.BLOCK_TAGS:
            self._buf.append("\n")

    def handle_data(self, data):
        if self._drop_depth:
            return
        if self._in_title:
            self._title += data
            return
        self._buf.append(data)

    def text(self) -> str:
        raw = "".join(self._buf)
        lines = [line.strip() for line in raw.splitlines()]
        # Drop empty lines but keep paragraph breaks.
        out: list[str] = []
        prev_blank = False
        for line in lines:
            if not line:
                if not prev_blank:
                    out.append("")
                prev_blank = True
            else:
                out.append(line)
                prev_blank = False
        return "\n".join(out).strip()


def extract_with_stdlib(html: str, url: str) -> str:
    p = _StdlibStripper()
    p.feed(html)
    body = p.text()
    if not body:
        body = "(no text content extracted)"
    header = ""
    title = (p._title or "").strip()
    if title:
        header = f"# {title}\n\n"
    return f"{header}> Source: {url}\n\n{body}\n"


def main() -> int:
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("url", help="URL to fetch")
    parser.add_argument(
        "--prefer",
        choices=("auto", "readability", "stdlib"),
        default="auto",
        help="Force a specific extractor (default: auto = readability if installed, else stdlib)",
    )
    args = parser.parse_args()

    try:
        html = fetch_html(args.url)
    except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError) as exc:
        print(
            f"[fetch] tier=local status=fail reason=\"fetch failed: {exc}\"",
            file=sys.stderr,
        )
        return 1

    used = ""
    body: str | None = None

    if args.prefer in ("auto", "readability"):
        body = extract_with_readability(html, args.url)
        if body is not None:
            used = "readability"
        elif args.prefer == "readability":
            print(
                "[fetch] tier=local status=fail "
                "reason=\"--prefer readability but readability-lxml or html2text not installed; "
                "install with: pip install --user readability-lxml html2text\"",
                file=sys.stderr,
            )
            return 1

    if body is None:
        body = extract_with_stdlib(html, args.url)
        used = "stdlib"

    # Sanity floor: if even the stdlib extractor returns essentially nothing,
    # treat as failure so the proxy fallback (if --use-proxy) gets a chance.
    body_lines = [l for l in body.splitlines() if l.strip()]
    if len(body_lines) < 4:
        print(
            f"[fetch] tier=local status=fail reason=\"extractor={used} produced <4 non-empty lines\"",
            file=sys.stderr,
        )
        return 1

    if used == "stdlib":
        print(
            "[fetch] tier=local status=ok extractor=stdlib "
            "hint=\"install readability-lxml + html2text for cleaner output\"",
            file=sys.stderr,
        )
    else:
        print(f"[fetch] tier=local status=ok extractor={used}", file=sys.stderr)

    sys.stdout.write(body)
    return 0


if __name__ == "__main__":
    sys.exit(main())
canvas-designanthropics/skillsCreate beautiful visual art in .png and .pdf documents using design philosophy. You should use this skill when the user asks to create a poster, piece of art, design, or other static piece. Create original visual designs, never copying existing artists' work to avoid copyright violations.Stars: 195kUpdated Claude CodeCodexVerifiedInstall
docxanthropics/skillsUse this skill whenever the user wants to create, read, edit, or manipulate Word documents (.docx files) or Word templates (.dotx files). Triggers include: any mention of 'Word doc', 'word document', '.docx', '.dotx', or requests to produce professional documents with formatting like tables of contents, headings, page numbers, or letterheads. Also use when extracting or reorganizing content from .docx or .dotx files, inserting or replacing images in documents, performing find-and-replace in Word files, working with tracked changes or comments, or converting content into a polished Word document. If the user asks for a 'report', 'memo', 'letter', 'template', or similar deliverable as a Word or .docx file, use this skill. Do NOT use for PDFs, spreadsheets, Google Docs, or general coding tasks unrelated to document generation.Stars: 195kUpdated Claude CodeCodexVerifiedInstall
pdfanthropics/skillsUse this skill whenever the user wants to do anything with PDF files. This includes reading or extracting text/tables from PDFs, combining or merging multiple PDFs into one, splitting PDFs apart, rotating pages, adding watermarks, creating new PDFs, filling PDF forms, encrypting/decrypting PDFs, extracting images, and OCR on scanned PDFs to make them searchable. If the user mentions a .pdf file or asks to produce one, use this skill.Stars: 195kUpdated Claude CodeCodexVerifiedInstall
pptxanthropics/skillsUse this skill any time a .pptx or .potx file is involved in any way — as input, output, or both. This includes: creating slide decks, pitch decks, or presentations; reading, parsing, or extracting text from any .pptx or .potx file (even if the extracted content will be used elsewhere, like in an email or summary); editing, modifying, or updating existing presentations; combining or splitting slide files; working with templates (.potx), layouts, speaker notes, or comments. Trigger whenever the user mentions "deck," "slides," "presentation," or references a .pptx or .potx filename, regardless of what they plan to do with the content afterward. If a .pptx or .potx file needs to be opened, created, or touched, use this skill.Stars: 195kUpdated Claude CodeCodexVerifiedInstall