diffbot 3.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,430 @@
1
+ import json
2
+ import re
3
+ import sys
4
+ import textwrap
5
+ from email.utils import parsedate_to_datetime
6
+
7
+ import click
8
+ from rich.console import Console
9
+ from rich.live import Live
10
+ from rich.markdown import Markdown
11
+ from rich.progress import Progress, SpinnerColumn, TextColumn
12
+ from datetime import datetime
13
+
14
+ from diffbot import (
15
+ __version__,
16
+ CrawlEventType,
17
+ AuthError,
18
+ ExtractionError,
19
+ APIError,
20
+ ValidationError,
21
+ json_schema_format,
22
+ )
23
+
24
+ from ._common import get_client
25
+
26
+ console = Console()
27
+ is_interactive = sys.stdout.isatty()
28
+
29
+
30
+ def print_markdown(text):
31
+ if is_interactive:
32
+ console.print(Markdown(text))
33
+ else:
34
+ sys.stdout.write(text)
35
+ sys.stdout.write("\n")
36
+
37
+
38
+ @click.group()
39
+ @click.version_option(__version__, "-V", "--version", prog_name="db")
40
+ def main():
41
+ """
42
+ Diffbot 🤖 Structure the world's knowledge.
43
+ """
44
+ pass
45
+
46
+
47
+ @main.command(name="extract")
48
+ @click.argument("url")
49
+ @click.option("-o", "--output", type=click.Path(), help="Write output to file instead of stdout")
50
+ @click.option("-f", "--format", "fmt", type=click.Choice(["markdown", "json"]), default="markdown", help="Output format")
51
+ @click.option("-a", "--api", type=str, default="analyze", help="Diffbot API to use")
52
+ def extract(url, output, fmt, api):
53
+ """Get structured content from a URL."""
54
+ db = get_client()
55
+ try:
56
+ if is_interactive and not output:
57
+ with Progress(SpinnerColumn(), TextColumn("[progress.description]{task.description}"), transient=True) as progress:
58
+ progress.add_task(description="Extracting content...", total=None)
59
+ data = db.extract(url, api=api, fmt=fmt)
60
+ else:
61
+ data = db.extract(url, api=api, fmt=fmt)
62
+
63
+ if fmt == "json":
64
+ output_str = json.dumps(data, indent=2)
65
+ else:
66
+ objects = data.get("objects", [])
67
+ if not objects:
68
+ output_str = json.dumps(data, indent=2)
69
+ else:
70
+ obj = objects[0]
71
+ title = obj.get("title", "")
72
+ url = obj.get("pageUrl", "")
73
+ content = obj.get("content", "")
74
+ output_str = f"Title: {title}\n\nURL: {url}\n\nContent: {content}"
75
+
76
+ if output:
77
+ with open(output, "w") as f:
78
+ f.write(output_str)
79
+ click.echo(f"Output written to {output}")
80
+ else:
81
+ print_markdown(output_str)
82
+ except ExtractionError as e:
83
+ click.echo(f"Extraction error {e.error_code}: {e.error}", err=True)
84
+ raise click.Abort()
85
+ except AuthError:
86
+ click.echo("Error: Invalid or unauthorized API token.", err=True)
87
+ raise click.Abort()
88
+ except APIError as e:
89
+ click.echo(f"API error {e.status_code}: {e.message or e.body}", err=True)
90
+ raise click.Abort()
91
+
92
+
93
+ @main.command()
94
+ @click.argument("prompt")
95
+ @click.option("-o", "--output", type=click.Path(), help="Write output to file instead of stdout")
96
+ @click.option("--json", "as_json", is_flag=True, help="Output from LLM as JSON")
97
+ @click.option(
98
+ "--schema",
99
+ "schema_path",
100
+ type=click.Path(exists=True, dir_okay=False),
101
+ help="JSON Schema file constraining the output (implies --json)",
102
+ )
103
+ def ask(prompt: str, output: str = None, as_json: bool = False, schema_path: str = None):
104
+ """Ask a question to the Diffbot LLM"""
105
+ db = get_client()
106
+ stdin_content = sys.stdin.read() if not sys.stdin.isatty() else None
107
+
108
+ response_format = None
109
+ if schema_path:
110
+ as_json = True
111
+ try:
112
+ with open(schema_path) as f:
113
+ response_format = json_schema_format(json.load(f))
114
+ except json.JSONDecodeError as e:
115
+ click.echo(f"Error: {schema_path} is not valid JSON: {e}", err=True)
116
+ raise click.Abort()
117
+
118
+ # Without --schema, response_format stays None and ask_json picks its own
119
+ # permissive default; --json alone must not become {"type": "json_object"}.
120
+ interactive_mode = is_interactive and not output and not as_json
121
+
122
+ messages = [
123
+ {
124
+ "role": "system",
125
+ "content": f"Current local time: {datetime.now().strftime('%A, %B %d, %Y, %I:%M:%S %p %Z')}",
126
+ },
127
+ {"role": "user", "content": prompt},
128
+ ]
129
+
130
+ if stdin_content:
131
+ messages[1]["content"] = f"<input>{stdin_content}</input>\n" + messages[1]["content"]
132
+
133
+ try:
134
+ if interactive_mode:
135
+ response_text = ""
136
+ with Live("", auto_refresh=False, console=console) as live:
137
+ for chunk in db.ask(messages):
138
+ response_text += chunk
139
+ live.update(Markdown(response_text))
140
+ live.refresh()
141
+
142
+ messages.append({"role": "assistant", "content": response_text})
143
+
144
+ while True:
145
+ try:
146
+ sys.stdout.write("\n> ")
147
+ sys.stdout.flush()
148
+ user_input = input()
149
+ messages.append({"role": "user", "content": user_input})
150
+ except (KeyboardInterrupt, EOFError):
151
+ console.print("\nExiting chat...")
152
+ return
153
+
154
+ response_text = ""
155
+ with Live("", auto_refresh=False, console=console) as live:
156
+ for chunk in db.ask(messages):
157
+ response_text += chunk
158
+ live.update(Markdown(response_text))
159
+ live.refresh()
160
+ messages.append({"role": "assistant", "content": response_text})
161
+ else:
162
+ response = ""
163
+ if output:
164
+ if as_json:
165
+ response = json.dumps(
166
+ db.ask_json(messages, response_format=response_format), indent=2
167
+ )
168
+ else:
169
+ for chunk in db.ask(messages):
170
+ response += chunk
171
+ with open(output, "w") as f:
172
+ f.write(response)
173
+ click.echo(f"Output written to {output}")
174
+ elif as_json:
175
+ sys.stdout.write(
176
+ json.dumps(db.ask_json(messages, response_format=response_format), indent=2)
177
+ )
178
+ else:
179
+ for chunk in db.ask(messages):
180
+ sys.stdout.write(chunk)
181
+ except (KeyboardInterrupt, EOFError):
182
+ console.print("\nExiting chat...")
183
+ except AuthError:
184
+ click.echo("Error: Invalid or unauthorized API token.", err=True)
185
+ raise click.Abort()
186
+ except ValidationError as e:
187
+ click.echo(f"Error: {e}", err=True)
188
+ raise click.Abort()
189
+ except APIError as e:
190
+ click.echo(f"API error {e.status_code}: {e.message or e.body}", err=True)
191
+ raise click.Abort()
192
+
193
+
194
+ @main.command()
195
+ @click.argument("site")
196
+ @click.option("--hops", type=int, default=2, help="Maximum link depth from seed URLs")
197
+ @click.option("--job-name", type=str, help="Name for the crawler job (generated if not provided)")
198
+ @click.option("--max-to-crawl", type=int, default=100, help="Maximum number of pages to crawl")
199
+ @click.option("--max-to-process", type=int, default=100, help="Maximum number of pages to process")
200
+ @click.option("--restrict-domain", is_flag=True, default=True, help="Restrict crawling to the same domain as seeds")
201
+ @click.option("--api-url", type=str, default="", help="Diffbot API endpoint to use for processing")
202
+ @click.option("--crawl-delay", type=float, default=-1, help="Delay between requests to the same domain in seconds")
203
+ @click.option("--url-crawl-pattern", type=str, help="Only crawl URLs matching this pattern")
204
+ @click.option("--url-process-pattern", type=str, help="Only process URLs matching this pattern")
205
+ @click.option("--obey-robots", is_flag=True, help="Obey robots.txt rules")
206
+ @click.option("--use-proxies", is_flag=True, help="Use proxies for crawling")
207
+ @click.option("--custom-headers", type=str, help="Custom HTTP headers to send with requests (newline separated)")
208
+ @click.option("-o", "--output", type=click.Path(), help="Write output to file instead of stdout")
209
+ @click.option("-f", "--format", "fmt", type=click.Choice(["markdown", "json"]), default="markdown", help="Output format")
210
+ def crawl(site, hops, job_name, max_to_crawl, max_to_process, restrict_domain,
211
+ api_url, crawl_delay, url_crawl_pattern, url_process_pattern, obey_robots,
212
+ use_proxies, custom_headers, output, fmt):
213
+ """Crawl a website using the Diffbot Crawler API."""
214
+ db = get_client()
215
+ events = []
216
+ try:
217
+ with Progress(SpinnerColumn(), TextColumn("[progress.description]{task.description}"), transient=True) as progress:
218
+ progress.add_task(description=f"Crawling {site}...", total=None)
219
+
220
+ for event in db.crawl(
221
+ site,
222
+ hops=hops,
223
+ job_name=job_name,
224
+ max_to_crawl=max_to_crawl,
225
+ max_to_process=max_to_process,
226
+ restrict_domain=restrict_domain,
227
+ api_url=api_url,
228
+ crawl_delay=crawl_delay,
229
+ url_crawl_pattern=url_crawl_pattern,
230
+ url_process_pattern=url_process_pattern,
231
+ obey_robots=obey_robots,
232
+ use_proxies=use_proxies,
233
+ custom_headers=custom_headers,
234
+ watch=True,
235
+ ):
236
+ events.append(event)
237
+ if event.event_type == CrawlEventType.JOB_CREATED:
238
+ progress.console.print(f"Job created: {event.details['job_name']}")
239
+ elif event.event_type == CrawlEventType.URL_PROCESSED:
240
+ status = event.details.get("status", "")
241
+ icon = "✓" if status == "Success" else "!"
242
+ progress.console.print(f" [{icon}] {event.details['url']}")
243
+
244
+ if fmt == "json":
245
+ output_str = json.dumps(
246
+ [{"event_type": e.event_type.value, "timestamp": e.timestamp, "details": e.details} for e in events],
247
+ indent=2,
248
+ )
249
+ else:
250
+ lines = []
251
+ for event in events:
252
+ if event.event_type == CrawlEventType.JOB_CREATED:
253
+ lines.append(f"# Job: {event.details['job_name']}\n")
254
+ elif event.event_type == CrawlEventType.URL_PROCESSED:
255
+ lines.append(f"- [{event.details.get('status', 'unknown')}] {event.details['url']}")
256
+ output_str = "\n".join(lines)
257
+
258
+ if output:
259
+ with open(output, "w") as f:
260
+ f.write(output_str)
261
+ click.echo(f"Output written to {output}")
262
+ else:
263
+ print_markdown(output_str)
264
+ except AuthError:
265
+ click.echo("Error: Invalid or unauthorized API token.", err=True)
266
+ raise click.Abort()
267
+ except APIError as e:
268
+ click.echo(f"API error {e.status_code}: {e.message or e.body}", err=True)
269
+ raise click.Abort()
270
+
271
+
272
+ @main.command()
273
+ @click.argument("job_name", required=False)
274
+ def crawl_list_jobs(job_name):
275
+ """List Diffbot crawler jobs or get details for a specific job."""
276
+ db = get_client()
277
+ try:
278
+ if job_name:
279
+ job = db.crawl_get_job(job_name)
280
+ print_markdown(f"# Job: {job_name}\n\n```json\n{json.dumps(job, indent=2)}\n```")
281
+ else:
282
+ jobs = db.crawl_list_jobs()
283
+ if not jobs:
284
+ print_markdown("No crawler jobs found.")
285
+ return
286
+ lines = ["# Diffbot Crawler Jobs\n"]
287
+ for job in jobs:
288
+ name = job.get("name", "Unknown")
289
+ job_type = job.get("type", "Unknown")
290
+ status = job.get("jobStatus", {}).get("message", "Unknown")
291
+ lines.append(f"## {name}")
292
+ lines.append(f"Type: {job_type}")
293
+ lines.append(f"Status: {status}")
294
+ if "pageCrawlSuccesses" in job:
295
+ lines.append(f"Pages Crawled: {job['pageCrawlSuccesses']}")
296
+ if "pageProcessSuccesses" in job:
297
+ lines.append(f"Pages Processed: {job['pageProcessSuccesses']}")
298
+ lines.append("\n---\n")
299
+ print_markdown("\n".join(lines))
300
+ except AuthError:
301
+ click.echo("Error: Invalid or unauthorized API token.", err=True)
302
+ raise click.Abort()
303
+ except APIError as e:
304
+ click.echo(f"API error {e.status_code}: {e.message or e.body}", err=True)
305
+ raise click.Abort()
306
+
307
+
308
+ @main.command()
309
+ @click.argument("job_name")
310
+ def crawl_delete_job(job_name):
311
+ """Delete a Diffbot crawler job."""
312
+ db = get_client()
313
+ try:
314
+ with Progress(SpinnerColumn(), TextColumn("[progress.description]{task.description}"), transient=True) as progress:
315
+ progress.add_task(description=f"Deleting job {job_name}...", total=None)
316
+ db.crawl_delete_job(job_name)
317
+ progress.console.print(f"Job {job_name} deleted.")
318
+ except AuthError:
319
+ click.echo("Error: Invalid or unauthorized API token.", err=True)
320
+ raise click.Abort()
321
+ except APIError as e:
322
+ click.echo(f"API error {e.status_code}: {e.message or e.body}", err=True)
323
+ raise click.Abort()
324
+
325
+
326
+ def _format_date(date_str: str) -> str:
327
+ if not date_str:
328
+ return ""
329
+ try:
330
+ dt = parsedate_to_datetime(date_str)
331
+ return f"{dt.strftime('%b')} {dt.day}, {dt.year}"
332
+ except Exception:
333
+ return date_str[:12].strip()
334
+
335
+
336
+ def _score_color(score: float) -> str:
337
+ if score > 0.85:
338
+ return "bright_green"
339
+ elif score >= 0.7:
340
+ return "green"
341
+ elif score >= 0.5:
342
+ return "yellow"
343
+ return "red"
344
+
345
+
346
+ def _strip_markdown(text: str) -> str:
347
+ text = re.sub(r'!\[.*?\]\(.*?\)', '', text) # images
348
+ text = re.sub(r'\[([^\]]*)\]\([^)]*\)', r'\1', text) # links → label
349
+ text = re.sub(r'^#{1,6}\s+', '', text, flags=re.MULTILINE) # headings
350
+ text = re.sub(r'^\s*[-*+]\s+', '', text, flags=re.MULTILINE) # bullets
351
+ text = re.sub(r'^\s*\d+\.\s+', '', text, flags=re.MULTILINE) # numbered lists
352
+ text = re.sub(r'[`*_~]{1,3}', '', text) # inline code/bold/italic
353
+ text = re.sub(r'\s+', ' ', text)
354
+ return text.strip()
355
+
356
+
357
+ @main.command(name="web-search")
358
+ @click.argument("query")
359
+ @click.option("-n", "--num-results", type=int, default=None, help="Number of results to return")
360
+ @click.option("-m", "--max-tokens", type=int, default=None, help="Limit total response tokens (for agentic use cases)")
361
+ @click.option("-f", "--format", "fmt", type=click.Choice(["list", "json", "text"]), default="list", help="Output format (text is plain/agent-friendly)")
362
+ def web_search(query: str, num_results, max_tokens, fmt: str):
363
+ """Search the web using the Diffbot LLM web search API."""
364
+ db = get_client()
365
+ try:
366
+ if is_interactive:
367
+ with Progress(SpinnerColumn(), TextColumn("[progress.description]{task.description}"), transient=True) as progress:
368
+ progress.add_task(description="Searching...", total=None)
369
+ data = db.web_search(query, num_results=num_results, max_tokens=max_tokens)
370
+ else:
371
+ data = db.web_search(query, num_results=num_results, max_tokens=max_tokens)
372
+
373
+ if fmt == "json":
374
+ sys.stdout.write(json.dumps(data, indent=2))
375
+ sys.stdout.write("\n")
376
+ return
377
+
378
+ results = data.get("search_results", [])
379
+
380
+ if fmt == "text":
381
+ for i, r in enumerate(results, 1):
382
+ date_fmt = _format_date(r.get("date", ""))
383
+ content = " ".join(r.get("content", "").split())
384
+ lines = [
385
+ f"[{i}] {r.get('title', '')} (score: {r.get('score', 0):.3f})",
386
+ f"URL: {r.get('pageUrl', '')}",
387
+ ]
388
+ if date_fmt:
389
+ lines.append(f"Date: {date_fmt}")
390
+ lines += [f"Content: {content}", "---"]
391
+ sys.stdout.write("\n".join(lines) + "\n")
392
+ return
393
+
394
+ time_ms = data.get("timeMs", 0)
395
+
396
+ for i, r in enumerate(results, 1):
397
+ score = r.get("score", 0)
398
+ title = r.get("title", "")
399
+ url = r.get("pageUrl", "")
400
+ date = r.get("date", "")
401
+ content = _strip_markdown(r.get("content", ""))
402
+
403
+ date_fmt = _format_date(date)
404
+ color = _score_color(score)
405
+ prefix_len = len(date_fmt) + 3 if date_fmt else 0 # " — "
406
+ snippet_width = max(80, console.width * 2 - prefix_len)
407
+ snippet = textwrap.shorten(content, width=snippet_width, placeholder="...")
408
+
409
+ console.print(f"[bold]#{i}: {title}[/bold] [[{color}]{score:.3f}[/{color}]]")
410
+ console.print(f"[dim blue]{url}[/dim blue]")
411
+ if date_fmt:
412
+ console.print(f"[dim]{date_fmt}[/dim] — {snippet}")
413
+ else:
414
+ console.print(snippet)
415
+ console.print()
416
+
417
+ console.print(f"[dim]{len(results)} result(s) in {time_ms}ms[/dim]")
418
+ except AuthError:
419
+ click.echo("Error: Invalid or unauthorized API token.", err=True)
420
+ raise click.Abort()
421
+ except APIError as e:
422
+ click.echo(f"API error {e.status_code}: {e.message or e.body}", err=True)
423
+ raise click.Abort()
424
+
425
+
426
+ from .dql import dql as _dql_group # noqa: E402
427
+ from .entities import entities as _entities_cmd # noqa: E402
428
+
429
+ main.add_command(_dql_group)
430
+ main.add_command(_entities_cmd)
@@ -0,0 +1,4 @@
1
+ from . import main
2
+
3
+ if __name__ == "__main__":
4
+ main()
diffbot/cli/_common.py ADDED
@@ -0,0 +1,21 @@
1
+ import click
2
+
3
+ from diffbot import Diffbot, resolve_token
4
+ from diffbot._auth import CREDENTIALS_PATH, TOKEN_ENV_VAR
5
+
6
+
7
+ def get_client() -> Diffbot:
8
+ """Build a Diffbot client using the shared credential resolution chain.
9
+
10
+ Looks at the DIFFBOT_API_TOKEN env var, then ~/.diffbot/credentials.
11
+ """
12
+ token = resolve_token()
13
+ if not token:
14
+ click.echo(
15
+ "Error: no Diffbot API token found.\n"
16
+ f" Set a {TOKEN_ENV_VAR} environment variable, or\n"
17
+ f" write '{TOKEN_ENV_VAR}=YOUR_TOKEN' to {CREDENTIALS_PATH}",
18
+ err=True,
19
+ )
20
+ raise click.Abort()
21
+ return Diffbot(token=token)