clip
def clip(
s:str, n:int=120
)->str:Collapse the whitespace in a scraped title and cut it to n characters.
Most methods here fetch content with fossick and file the result with Vault.add. The meta of each document records its source URL and the fetch time. A document found by web also records the query that found it.
Collapse the whitespace in a scraped title and cut it to n characters.
url reads one page and converts it to markdown. Many sites answer a script with a challenge page, called a bot wall, instead of the article. With auto=True, the default, fossick then tries a heavier fetcher, then a stealthy browser, then your logged-in Chrome.
crawl follows links from a start page and files each page it reaches. It skips a page whose markdown is empty.
web runs a web search, reads the top n results and files them. It stores the query in the meta of each document. The dropped key of the result lists the results it could not read.
def web(
query:str, # what to search for
n:int=5, # top results to read
google:bool=False, # real Google ranking via a stealth browser (slower)
chars:int=60000, # max markdown chars kept per source
stop:NoneType=None, # asked between sources filed; `unread` holds the URLs not filed
progress:NoneType=None, # told `progress(done, total, [source])` after each source filed
**kw
)->fastcore.basics.AttrDict: # forwarded to fossick.researchSearch the web, read the top n results, and file each result that has a URL and non-empty markdown.
def crawl(
start_url:str, max_pages:int=10, sel:str=None,
stop:NoneType=None, # asked before the crawl and between pages filed; `unread` holds the URLs not filed
progress:NoneType=None, # told `progress(done, total, [url])` after each page filed
scope:NoneType=None, # True -> only the folder of the start page after its redirects; a URL -> only its folder; None -> the whole site
**kw
)->fastcore.foundation.L:Crawl a site from start_url, up to max_pages pages, and file each page with non-empty markdown. The result carries cancelled and unread.
Whether url, without its query and fragment, is in the folder of scope. A path with .., also in percent codes, never is.
The scheme, host and folder of url: all of it up to the last / of its path.
def url(
url:str, # page to read
title:str=None, # defaults to the page's first heading, else its path
sel:str=None, # CSS selector to narrow the page before conversion
kind:str='web', # kind the document is filed as
auto:bool=True, # past a bot wall, escalate plain -> heavy -> stealthy -> logged-in Chrome
meta:dict=None, # extra meta; the reader's own keys replace any that match
force:bool=False, # re-ingest a source already present
stop:NoneType=None, # asked before the fetch; True files nothing and reports the URL in `unread`
progress:NoneType=None, # told `progress(1, 1, [url])` once the page is filed
**kw
)->dict: # forwarded to fossick.fetch (verify=, headers=, heavy=…)Fetch one URL, convert it to markdown and file it in the vault.
[2026-08-14 11:34:27] INFO: Fetched (200) <GET https://www.google.com/search?q=what+is+consciousness%3F&hl=en&num=17&sei=nXB-atSOMMOmwPAPiOThmAw> (referer: https://www.google.com/)
[2026-08-14 11:34:28] INFO: Fetched (200) <GET https://en.wikipedia.org/wiki/Consciousness> (referer: https://www.google.com/)
[2026-08-14 11:34:28] INFO: Fetched (200) <GET https://pmc.ncbi.nlm.nih.gov/articles/PMC5924785/> (referer: https://www.google.com/)
[2026-08-14 11:34:28] INFO: Fetched (200) <GET https://mcgovern.mit.edu/2024/04/29/what-is-consciousness/> (referer: https://www.google.com/)
[2026-08-14 11:34:29] INFO: Fetched (200) <GET https://www.reddit.com/r/askphilosophy/comments/kar7as/what_is_consciousness_exactly_and_why_do_so_many/?rdt=37685> (referer: https://www.google.com/)
[2026-08-14 11:34:29] INFO: Fetched (200) <GET https://www.scientificamerican.com/article/what-is-consciousness/> (referer: https://www.google.com/)
{ 'added': [{'doc_id': '97aaa07e0c0a3b44', 'title': 'Consciousness', 'kind': 'web', 'nodes': 9, 'chunks': 139, 'url': 'https://en.wikipedia.org/wiki/Consciousness'}, {'doc_id': '0d51d0f4dd5d84f6', 'title': 'What is consciousness exactly and why do so many people ...', 'kind': 'web', 'nodes': 2, 'chunks': 3, 'url': 'https://www.reddit.com/r/askphilosophy/comments/kar7as/what_is_consciousness_exactly_and_why_do_so_many/'}, {'doc_id': 'f631a6fe6c50788e', 'title': 'What Is Consciousness?', 'kind': 'web', 'nodes': 5, 'chunks': 46, 'url': 'https://www.scientificamerican.com/article/what-is-consciousness/'}, {'doc_id': '9b5b9514d7b82195', 'title': 'Human Consciousness: Where Is It From and What Is It for', 'kind': 'web', 'nodes': 18, 'chunks': 135, 'url': 'https://pmc.ncbi.nlm.nih.gov/articles/PMC5924785/'}, {'doc_id': 'b144d645fbbc3baa', 'title': 'What is consciousness?', 'kind': 'web', 'nodes': 7, 'chunks': 19, 'url': 'https://mcgovern.mit.edu/2024/04/29/what-is-consciousness/'}],
'dropped': [],
'n_found': 5,
'query': 'what is consciousness?'}"Some philosophers believe that Block's two types of consciousness are not the end of the story. William Lycan, for example, argued in his book _Consciousness and Experience_ that at least eight clearly distinct types of consciousness can be identified (organism consciousness; control consciousness; consciousness _of_ ; state/event consciousness; reportability; introspective consciousness; subjective consciousness; self-consciousness)—and that even this list omits several more obscure forms.[73]\n\n"
grab(target) identifies the target and calls the method that reads it.
| Target | Method |
|---|---|
| arXiv id or link | arxiv |
| YouTube link | youtube (transcript and metadata) |
| GitHub repository | github |
| One file on GitHub | gh_file |
pdf |
|
| Local file, including a Sanskrit file | add_file |
| Directory | add_tree |
| Any other web address | url |
grab does not file a source file on GitHub as a document. It clones the repository and indexes it with kosha as code.
With crawl=True, grab calls crawl on the target whatever its kind. With shelf=, grab files the result on that named shelf. Without it, grab uses the shelf that KIND_SHELF names for the kind of the target.
crawl(scope=True) keeps a crawl in the folder of its start page, after the redirects of that page. scope=url names another folder. A link with .., also as %2e%2e, is never in scope. With fossick 0.1.24 the crawl does not queue a link out of scope; with an older fossick, it visits such a page and does not file it.
def grab(
target:str, # a URL, an arXiv id, a YouTube link, a GitHub repo or file, a PDF, a local file or a directory
title:str=None, # document title; ignored for a directory, repository, arXiv id and YouTube link
sel:str=None, # CSS selector, for the web cases
shelf:str=None, # shelf to file it on; None uses the shelf `KIND_SHELF` names for its kind
crawl:bool=False, # follow links from a web target instead of reading the one page
max_pages:int=10, # pages to visit when crawling
kw_by_kind:dict=None, # more keyword arguments for one kind only, such as `{'github': dict(code=False)}`; keys are the kinds of `what_is`, `sanskrit` and `crawl`
**kw
):Identify target and file it with the method that reads that kind of target.
File one file from GitHub. A prose file becomes a document. A source file causes its repository to be cloned and indexed with kosha.
Clone a GitHub repository and file it with add_tree. Prose goes to the vault and source code to kosha.
File a YouTube video’s transcript and metadata.
File a PDF from a local path or a URL, one section per heading.
File an arXiv paper, with its metadata and full text, as kind arxiv on the papers shelf.
kw_by_kind sends keyword arguments to one reader only. grab(t, kw_by_kind={'github': dict(code=False)}) leaves the code of a repository out, and a web page or a folder does not get code=False.
A directory usually holds two kinds of file. add_dir files prose, such as Markdown, notebooks and PDFs, in the vault. index_code sends source code to kosha, a separate index built for code. add_tree does both, and grab calls it for a directory.
If kosha fails, add_tree issues a warning and leaves the source files out. It does not file them as prose. connect=True runs connect once at the end. It does not run if stop cancelled the ingest or if nothing was filed.
You can stop a long ingest. add_tree, add_dir and add_files take two callbacks.
| Argument | When it is called |
|---|---|
stop |
Before each batch of batch files (50), before each file in a batch, and before kosha. |
progress |
As progress(done, total, batch) after each batch. |
When stop() returns True, the files already filed stay in the vault. The result has cancelled set and unread lists the files not reached. No exception is raised. A fetch already under way finishes.
The other methods take stop and progress too. grab accepts both for any target.
| Method | When it asks stop |
|---|---|
github |
Before the clone. It then passes both arguments to add_tree. |
url, arxiv, youtube, pdf, gh_file, add_file |
Before the fetch or read. |
crawl, web |
Before the first fetch and between the pages they file. |
Without stop, the results of add_tree and web have no cancelled or unread key.
def add_tree(
dir:str, # tree to ingest
types:str='.pdf,.md,.markdown,.txt,.rst,.ipynb,.xml,.tei,.htm,.html,.conllu', # extensions filed into the vault as prose
code:bool=True, # index source files with kosha, when the tree has any
kind:str=None, # override the kind for the prose half
connect:bool=False, # rebuild the topic nodes at the end, unless `stop` cancelled the ingest
verbose:bool=False, queue:bool=False, # enqueue the work instead of doing it; `poll` or `drain` runs it
batch:int=50, # files per job when queueing, and per batch filed when `stop` or `progress` is given
stop:NoneType=None, # asked between batches and before kosha; True stops, and `unread` holds the files not reached
progress:NoneType=None, # told `progress(done, total, batch)` after each batch of documents
max_files:int=None, # the most prose files filed; `cut` says when it stopped
max_bytes:int=None, # the most bytes of prose filed, all files together
rank:NoneType=None, # `rank(rel_path) -> int|None`: the filing order, lowest first; None skips the file
meta:NoneType=None, # `meta(path) -> dict`, merged into the meta of each document filed
links:bool=True, # False -> no symlink, no hard link, and nothing that resolves outside `dir`
**kw
)->fastcore.basics.AttrDict: # forwarded to add_fileAdd the documents in a directory to the vault and its source code to kosha. With queue=True, queue the work instead.
def tree_files(
dir, # tree to walk
types:str='.pdf,.md,.markdown,.txt,.rst,.ipynb,.xml,.tei,.htm,.html,.conllu', # extensions to keep
max_files:int=None, # the most files kept
max_bytes:int=None, # the most bytes kept, all files together
rank:NoneType=None, # `rank(rel_path) -> int|None`: the filing order, lowest first; None skips the file
links:bool=True, # False -> no symlink, no hard link, and nothing that resolves outside `dir`
)->fastcore.foundation.L:The files that add_tree files from dir, in filing order. cut says why the list stopped early, or is ’’.
A large tree can take hours. add_tree(..., queue=True) puts the work on the vault’s job queue (see jobs) instead of doing it. A crash then costs only the batch in flight.
| Job | Count |
|---|---|
Ingest of batch files (50) |
One per batch |
| Code indexing with kosha | One, when the tree has source files |
connect |
One, with connect=True. It waits until every ingest job has run. |
Nothing runs until something runs the queue, such as poll or vault.q.drain(). jobs(kind='ingest') shows the jobs that remain.
The vault skips a file it already holds, so running a batch twice does no harm. A retried batch files only the files it missed. Queueing a batch that is still waiting adds no second job.
Queue a whole directory: one job per batch of documents, one for the source code, and one for connect when asked.
def enqueue_files(
files, # paths to ingest
kind:str=None, # override the kind inferred from the extension
batch:int=50, # files per job; one job is one `add_files` call
route:bool=True, # send Sanskrit sources to the Sanskrit shelf
priority:int=0, **kw
)->fastcore.foundation.L: # forwarded to add_filesQueue an ingest of files as one job per batch files, so a crash resumes at the batch it was on.
Many sites, shops in particular, fill a page with data from a JSON API that the page calls in the background. Reading that API gives clean records instead of scraped HTML.
apis(url) loads the page and captures the JSON calls it makes. It lists them with the number of records in each.
harvest(url) replays one captured call. It runs apis first, unless you pass capture= and the Vault object holds an earlier apis result. capture= is the n of a call in that result. Without capture=, it picks the call with the most records. It follows the pagination of the call when pages is more than 1. It files the records as one document of kind data, with one section per record.
add_records files a list of dicts you already have, from any API or export, in the same way.
Format records as markdown with one ## section per record.
File a list of dicts you already have (any API, any export) as one document, one section each.
def harvest(
url:str, # the page whose API you want
pattern:str='*', # which captured request URLs to keep
title:str=None, # document title; defaults to the page host + path
capture:int=None, # `n` of the call to replay, from the last `apis` result; None picks the call with the most records
pages:int=1, # pages to pull; >1 paginates the endpoint
page_field:str='page', # query/body key incremented per page
session:bool=False, # capture through the logged-in Chrome
force:bool=False, # re-ingest a source already present
**kw
)->dict: # forwarded to `replay_xhr` and `paginate_api`Capture the JSON API a page calls, pull its records, following pagination when asked, and file them as kind data.
List the JSON calls a page makes, with the record count of each. The Vault object keeps the captures for harvest.
A watch repeats an acquisition on a schedule. watch(target, action=..., every='6h') registers one. ACTIONS lists the actions, and kind= is another name for action.
| Action | What each run does |
|---|---|
url |
Re-reads a page. |
web |
Re-runs a web search. |
harvest |
Re-harvests an API. |
arxiv, youtube |
Re-reads a paper or a video. |
crawl |
Re-crawls a site. |
path |
Calls grab on a path. |
folder |
Reports changes in a folder. |
remind |
Writes a reminder note. |
every takes an interval such as '30m', '1d' or '1w'. cron= takes a five-field cron expression instead. Other keyword arguments go to the action, such as n=5 for a web search.
The clock is pobblebonk, which keeps its schedules in the vault file. poll() is the tick to call from cron, a scheduler or an app’s timer. Each call does these steps in order:
connect if any job succeeded and connect=True.housekeep if 600 seconds have passed since the last run on this connection.A failed fetch, or one that hit a bot wall, is retried after a growing delay. After 5 attempts the job is dead. jobs(state='dead') lists dead jobs, and retry_job puts one back on the queue. A worker killed in the middle of a fetch loses its claim on the job, called its lease. The job itself goes back on the queue.
The next run is counted from when the last run was due. A slow fetch does not push later runs back. After a gap, such as a laptop asleep for ten hours under an hourly watch, catchup (1 by default) sets how many missed runs to make up. missed counts the rest. run_watch fires one watch now, outside the queue. pause disables a watch and keeps it. unwatch deletes it. The documents a watch filed stay in both cases.
A folder watch takes a snapshot of the files under a folder, or of those matching pattern. The snapshot holds at most 5000 files. A run reports the files added, changed or removed since the last snapshot. A folder watch needs instructions, the standing brief for whoever reviews the change. Every report includes the instructions. A remind watch writes or updates one note and fetches nothing.
housekeep marks a document stale in these cases:
| Source | Stale when |
|---|---|
| Local file | The file was deleted, or changed after it was filed. |
| Web page | 30 days have passed and no watch refreshes it. |
| Video | 90 days have passed and no watch refreshes it. |
| Data harvest | 7 days have passed and no watch refreshes it. |
Where a watch has filed several copies of one source, housekeep marks the older copies superseded. With prune=True, the default, it deletes the documents that are both stale and superseded.
Mark a document stale when its source changed or vanished, or when it expired with no watch. Mark older copies superseded. With prune, delete documents that are both stale and superseded.
Put a dead or pending job back on the queue now, with its attempt count reset.
List jobs in the vault’s queue; state='dead' lists those that used up their attempts.
The periodic tick. Return expired jobs to the queue, queue due watches, run the queue, then run connect and housekeep when they apply.
Queue a job for every watch that has come due, and count the runs a gap skipped as missed.
Fire one watch now, off the queue, and record the outcome. Failures come back, they do not raise.
List the files added, changed or removed under a folder watch since its last look, and take a new snapshot.
Disable a watch and keep it. enabled=True re-enables it.
Delete a watch. The documents it already filed stay in the vault.
Every registered watch, soonest first. due_only keeps the enabled watches whose next run has arrived.
def watch(
target:str, # URL, query, arXiv id, path, folder, or the text of a reminder
action:str='url', # one of ACTIONS: what to do when it fires
every:str='1d', # interval: '30m', '6h', '1d', '1w', '1M', or seconds
cron:str=None, # or a five-field cron expression, instead of an interval
note:str=None, # why you are watching
start:float=None, # first run time (epoch); an interval watch defaults to now, a cron watch to its next match
catchup:int=1, # missed intervals to make up after a gap; the rest count as `missed`
kind:str=None, # alias for action; what the target set calls it
instructions:str='', # the standing brief a folder watch's reviewer gets, verbatim
pattern:str='', # globs limiting a folder watch
**params
)->dict: # forwarded to the action (n=, pages=, sel=, ...)Register a recurring job: re-read a page, re-run a search, re-harvest an API, watch a folder, or remind you.
The vault’s clock: pobblebonk’s schedules, one per watch, kept in the vault file.
The vault’s job queue, on its database, with the acquisition handlers registered.
The vault’s job ledger, on its database: rows for jobs that run outside the queue.
v.ledger is the Ledger of the vault file, for jobs that run outside the queue. Its shelves share it.
A photo has no text to search. The vault files what the image file says about itself: its size, the camera, and when and where it was taken (from its EXIF data). It also files any caption or labels you add. labels= holds what an image classifier saw. A search for “galah” then finds a picture of a galah. The pixels stay on disk, and the path key in the meta of the document points at them.
| Method | What it does |
|---|---|
add_image |
Files one picture as kind image. |
add_images |
Files every picture in a folder. |
images |
Lists the pictures in the vault. |
tag_image |
Adds labels or a caption to a filed picture and rebuilds its searchable text. |
Dimensions, camera, capture time and GPS for one image file.
The searchable text for a picture: its own metadata, plus whatever a model or a person added.
Add labels or a caption to a picture already in the vault, and rebuild its searchable text.
Every picture in the vault, with the metadata it was filed with.
File every picture under a directory, one document each.
def add_image(
path:str, # the picture
title:str=None, # defaults to the filename
caption:str=None, # a description, if you have one
labels:NoneType=None, # what a classifier saw
meta:dict=None, # your keys replace any the file gives
force:bool=False, # re-ingest a source already present
**kw
)->dict: # forwarded to `add`File one picture as kind="image". Its metadata is the searchable text. The pixels stay on disk.
label_images runs anya, an image classifier, over a folder. It files every picture with the labels it found, with force=True, and you can then search the pictures by what is in them. It raises ImportError when anya is not installed.
def label_images(
dir:str, # folder of pictures
model:str, # an anya model: a path, a hub repo id, or an alias
topk:int=3, # labels to keep per picture
min_score:float=0.0, # ignore anything less confident
add:bool=True, # file them in the vault as well as returning them
**kw
)->fastcore.foundation.L: # forwarded to anya.classifyClassify a folder with anya and file every picture in the vault with what the model saw.
_v = Vault(':memory:')
_r = _v.add_image(wren_path, labels=['Superb Fairywren', 'Malurus cyaneus'])
test_eq(_v.stats()['by_kind']['image'], 1)
test_eq(_v.doc(str(wren_path.resolve()))['meta']['labels'][0], 'Superb Fairywren')
assert first(_v.search('Superb Fairywren', kind='image')), 'labels have to be searchable'
test_eq(len(_v.add_images(Path.cwd(), force=True)), 2)
test_eq(len(_v.images()), 2)
# what a later model run adds is merged in, and the text is rebuilt so it is searchable too
_ = _v.tag_image(str(galah_path.resolve()), labels=['Galah'], caption='pink and grey')
test_eq(_v.doc(str(galah_path.resolve()))['meta']['labels'], ['Galah'])
assert first(_v.search('pink and grey', kind='image'))# fossick's json_records walk; harvest pagination uses the same
_pay = {'data': {'items': [{'a': 1}, {'a': 2}, {'a': 3}]}}
test_eq(len(json_records(_pay)), 3)
test_eq(json_records(_pay, with_key=True)[1], 'items')
test_eq(secs('6h'), 21600); test_eq(secs('1w'), 604800); test_eq(secs(90), 90)
test_eq(secs('30m'), 1800); test_eq(secs('2 days'), 172800); test_eq(secs('45s'), 45)
test_eq(secs('1h30m'), 5400); test_eq(secs('90'), 90)
test_fail(lambda: secs('whenever'), contains='not a duration')
w = v.watch('late chunking', action='web', every='1d', n=3)
test_eq(w['params'], dict(n=3))
test_eq(len(v.watches(due_only=True)), 1)
v.unwatch(w['id'])
test_eq(len(v.watches()), 0)
# a folder watch snapshots what is there and fires only on what moved; `kind` is `action` by another name
with TemporaryDirectory() as d:
v = Vault(':memory:', offline=True)
(Path(d)/'a.py').write_text('a = 1')
test_fail(lambda: v.watch(d, kind='folder', every='5m'), contains='instructions')
w = v.watch(Path(d), kind='folder', every='5m', instructions='flag any print()', pattern='*.py') # a Path target is filed as text
test_eq((w['kind'], w['action'], w['instructions'], w['pattern']), ('folder', 'folder', 'flag any print()', '*.py'))
test_eq(list(w['params']['snap']), [str(Path(d)/'a.py')])
test_eq(v.watches()[0]['kind'], 'folder'); test_eq(v.watches()[0]['pattern'], '*.py')
test_eq(v.run_watch(v.watches()[0])['status'], 'skipped') # nothing moved
(Path(d)/'b.py').write_text('print(2)'); (Path(d)/'a.py').write_text('a = 2'); os.utime(Path(d)/'a.py', (time.time()+1,)*2)
(Path(d)/'c.txt').write_text('ignored')
r = v.run_watch(v.watches()[0])
test_eq((r['status'], sorted(Path(p).name for p in r['result']['added']), [Path(p).name for p in r['result']['changed']]), ('ok', ['b.py'], ['a.py']))
test_eq(r['result']['instructions'], 'flag any print()')
test_eq(v.run_watch(v.watches()[0])['status'], 'skipped') # snapshot advanced
os.utime(Path(d)/'a.py', (time.time()-100,)*2) # an older file checked out is a change too
test_eq([Path(p).name for p in v.run_watch(v.watches()[0])['result']['changed']], ['a.py'])
u = v.watch('https://x.test', action='url', every='1d') # old spelling still works
test_eq((u['kind'], u['instructions'], u['pattern']), ('url', '', ''))
# a row written before the columns existed reads back with defaults
v.db.q("update watches set instructions=NULL, pattern=NULL where id=?", [u['id']])
test_eq((v._watch_row(u['id'])['instructions'], v._watch_row(u['id'])['pattern']), ('', ''))
# `pattern` is a column now, and a harvest still receives it
_got = {}
v.harvest = lambda t, **kw: (_got.update(kw), dict(pages=1))[1]
h = v.watch('https://x.test/shop', action='harvest', every='1d', pattern='*/api/*', pages=2)
test_eq((h['pattern'], h['params']), ('*/api/*', dict(pages=2)))
test_eq(v.run_watch(v._watch_row(h['id']))['status'], 'ok')
test_eq((_got['pattern'], _got['pages']), ('*/api/*', 2))A tree from someone else can be large or hostile. add_tree takes caps and a rank: max_files and max_bytes stop the walk and set cut, and rank(rel) sets the order or skips a file. links=False skips a symlink, a hard link, and any path that resolves outside the tree, so a link to a key file is never read. meta(path) gives the meta of each document. The defaults walk the tree as before. tree_files returns the same list without filing anything.