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.
diffbot/cli/dql.py ADDED
@@ -0,0 +1,310 @@
1
+ import csv
2
+ import io
3
+ import json
4
+ import pathlib
5
+ import re
6
+ import shutil
7
+ import time
8
+
9
+ import click
10
+ import sys
11
+ from rich.console import Console
12
+ from rich.progress import Progress, SpinnerColumn, TextColumn
13
+ from rich.table import Table
14
+
15
+ from diffbot import DiffbotError
16
+
17
+ from . import ontology
18
+ from diffbot import resolve_token
19
+
20
+ from ._common import get_client
21
+
22
+
23
+ class _DqlGroup(click.Group):
24
+ _SECTIONS = [
25
+ (
26
+ "Commands",
27
+ ["export"],
28
+ ),
29
+ (
30
+ "Advanced Commands",
31
+ ["init", "ontology", "probe"],
32
+ ),
33
+ ]
34
+
35
+ def invoke(self, ctx):
36
+ try:
37
+ return super().invoke(ctx)
38
+ except (FileNotFoundError, KeyError, DiffbotError) as e:
39
+ raise click.ClickException(str(e))
40
+
41
+ def format_commands(self, ctx, formatter):
42
+ section_cmds = {label: [] for label, _ in self._SECTIONS}
43
+ uncategorized = []
44
+
45
+ for name in self.list_commands(ctx):
46
+ cmd = self.commands.get(name)
47
+ if cmd is None or cmd.hidden:
48
+ continue
49
+ placed = False
50
+ for label, names in self._SECTIONS:
51
+ if name in names:
52
+ section_cmds[label].append((name, cmd))
53
+ placed = True
54
+ break
55
+ if not placed:
56
+ uncategorized.append((name, cmd))
57
+
58
+ for label, _ in self._SECTIONS:
59
+ cmds = section_cmds[label]
60
+ if not cmds:
61
+ continue
62
+ with formatter.section(f"{label}"):
63
+ formatter.write_dl(
64
+ [(name, cmd.get_short_help_str(formatter.width)) for name, cmd in cmds]
65
+ )
66
+
67
+ if uncategorized:
68
+ with formatter.section("Other"):
69
+ formatter.write_dl(
70
+ [(name, cmd.get_short_help_str(formatter.width)) for name, cmd in uncategorized]
71
+ )
72
+
73
+
74
+ @click.group("dql", cls=_DqlGroup)
75
+ def dql():
76
+ """Construct and run Diffbot Query Language (DQL) queries against the Knowledge Graph."""
77
+
78
+
79
+ @dql.command("init")
80
+ @click.option("--max-age", type=int, default=0, help="Skip the ontology re-download if the local copy is younger than N seconds (default 0 = always refresh).")
81
+ @click.option("--keep-tmp", is_flag=True, help="Don't clear ~/.diffbot/tmp.")
82
+ def init(max_age: int, keep_tmp: bool):
83
+ """Cache the Diffbot ontology and reset the tmp workspace."""
84
+ base = pathlib.Path.home() / ".diffbot"
85
+ base.mkdir(exist_ok=True)
86
+ tmp = base / "tmp"
87
+ if not keep_tmp:
88
+ if tmp.exists():
89
+ shutil.rmtree(tmp)
90
+ tmp.mkdir()
91
+
92
+ ont = ontology.ONTOLOGY_PATH
93
+ fresh = ont.exists() and max_age > 0 and (time.time() - ont.stat().st_mtime) < max_age
94
+ if fresh:
95
+ click.echo(f"ontology: cached ({int(time.time() - ont.stat().st_mtime)}s old)")
96
+ else:
97
+ get_client().dql_refresh_ontology(ont)
98
+ click.echo(f"ontology: refreshed -> {ont}")
99
+ ontology._CACHE.pop("data", None)
100
+
101
+ if resolve_token():
102
+ click.echo("credentials: token found")
103
+ else:
104
+ click.echo(
105
+ "credentials: MISSING -- no Diffbot API token found\n"
106
+ " Set the DIFFBOT_API_TOKEN environment variable, or\n"
107
+ " write 'DIFFBOT_API_TOKEN=YOUR_TOKEN' to ~/.diffbot/credentials",
108
+ err=True,
109
+ )
110
+ raise SystemExit(2)
111
+
112
+
113
+ @dql.group("ontology")
114
+ def ontology_group():
115
+ """Navigate the cached Diffbot ontology (types, fields, taxonomies, enums)."""
116
+
117
+
118
+ @ontology_group.command("types")
119
+ def ontology_types():
120
+ """List all entity type names."""
121
+ for n in ontology.list_types():
122
+ click.echo(n)
123
+
124
+
125
+ @ontology_group.command("composites")
126
+ def ontology_composites():
127
+ """List all composite type names."""
128
+ for n in ontology.list_composites():
129
+ click.echo(n)
130
+
131
+
132
+ @ontology_group.command("enums")
133
+ def ontology_enums():
134
+ """List all enum type names."""
135
+ for n in ontology.list_enums():
136
+ click.echo(n)
137
+
138
+
139
+ @ontology_group.command("taxonomies")
140
+ def ontology_taxonomies():
141
+ """List all taxonomy names."""
142
+ for n in ontology.list_taxonomies():
143
+ click.echo(n)
144
+
145
+
146
+ @ontology_group.command("fields")
147
+ @click.argument("type_name", metavar="TYPE")
148
+ @click.argument("search", required=False, default=None)
149
+ @click.option("--include-deprecated", is_flag=True)
150
+ def ontology_fields(type_name: str, search, include_deprecated: bool):
151
+ """List fields of an entity type or composite (e.g. db dql ontology fields Organization)."""
152
+ fields = ontology.fields_for(type_name)
153
+ for name, meta in ontology.filter_fields(fields, search, include_deprecated=include_deprecated):
154
+ click.echo(ontology.format_field(name, meta))
155
+
156
+
157
+ @ontology_group.command("taxonomy")
158
+ @click.argument("name")
159
+ @click.argument("search", required=False, default=None)
160
+ def ontology_taxonomy(name: str, search):
161
+ """List values of a taxonomy."""
162
+ for v in ontology.taxonomy_values(name, search):
163
+ click.echo(v)
164
+
165
+
166
+ @ontology_group.command("enum")
167
+ @click.argument("name")
168
+ def ontology_enum(name: str):
169
+ """List values of an enum."""
170
+ for v in ontology.enum_values(name):
171
+ click.echo(v)
172
+
173
+
174
+ @ontology_group.command("search")
175
+ @click.argument("term")
176
+ def ontology_search(term: str):
177
+ """Generic fallback: search every 'name' field in the ontology by regex."""
178
+ for n in ontology.find_named(term):
179
+ click.echo(n)
180
+
181
+
182
+ @dql.command("probe")
183
+ @click.argument("queries", nargs=-1, required=True)
184
+ @click.option("--workers", type=int, default=8, help="Maximum concurrent requests (default 8).")
185
+ @click.option("--json", "as_json", is_flag=True, help="Emit results as a JSON array instead of a text table.")
186
+ def probe(queries, workers: int, as_json: bool):
187
+ """Run multiple DQL queries in parallel and print hit counts (size=0) for each."""
188
+ reqs = [{"query": q, "size": 0} for q in queries]
189
+ results = get_client().dql_parallel(reqs, workers=workers)
190
+ rows = [
191
+ {"query": q, "hits": r.get("hits"), "results": r.get("results")}
192
+ for q, r in zip(queries, results)
193
+ ]
194
+ if as_json:
195
+ click.echo(json.dumps(rows, indent=2, ensure_ascii=False))
196
+ return
197
+ width = max(len(str(row["hits"])) for row in rows)
198
+ for row in rows:
199
+ click.echo(f"{str(row['hits']).rjust(width)} {row['query']}")
200
+
201
+
202
+ _DEFAULT_SPECS: dict[str, str] = {
203
+ "Organization": "name,Name;summary,Summary;nbEmployees,Employees;location.city.name,City;location.country.name,Country",
204
+ "Person": "name,Name;$.employments[0].employer.name,Organization;$.employments[0].title,Title;location.city.name,City;location.country.name,Country",
205
+ "Article": "date.str,Date;title,Title;author,Author;siteName,Site;language,Language",
206
+ "Product": "name,Name;brand,Brand;category,Category;offerPrice,Price;summary,Summary",
207
+ "*": "name,Name;description,Description",
208
+ }
209
+
210
+ # Extra fields appended to the stdout default spec for file exports (--out).
211
+ # Exports can carry more columns than the terminal table; fill these in per type.
212
+ # Format matches _DEFAULT_SPECS: "field.path,Display Name;..." (no leading ';').
213
+ _EXPORT_EXTRA_SPECS: dict[str, str] = {
214
+ "Organization": "$.categories[*].name,Industries;revenue.value,Revenue;revenue.currency,Revenue Currency;foundingDate.str,Founding Date",
215
+ "Person": "allNames,All Names;homepageUri,Website;linkedInUri,LinkedIn;$.employments[1:].employer.name,Employment History;",
216
+ "Article": "authorUrl,Author URL;$.categories[*].name,Categories;tags.label,Tags;publisherCountry,Publisher Country;text,Text;html,HTML;",
217
+ "Product": "",
218
+ "*": "",
219
+ }
220
+
221
+ _TYPE_RE = re.compile(r"\btype:([A-Za-z]+)", re.IGNORECASE)
222
+
223
+
224
+ def _type_for_query(query: str) -> str:
225
+ """Return the entity type named in the query, or '*' if none is found/known."""
226
+ m = _TYPE_RE.search(query)
227
+ if m and m.group(1) in _DEFAULT_SPECS:
228
+ return m.group(1)
229
+ return "*"
230
+
231
+
232
+ def _spec_for_query(query: str) -> str:
233
+ """Return the default stdout exportspec for the entity type found in query."""
234
+ return _DEFAULT_SPECS[_type_for_query(query)]
235
+
236
+
237
+ def _export_spec_for_query(query: str) -> str:
238
+ """Return the default file-export spec: the stdout default plus any per-type extras."""
239
+ t = _type_for_query(query)
240
+ base = _DEFAULT_SPECS[t]
241
+ extra = _EXPORT_EXTRA_SPECS.get(t, "").strip().strip(";")
242
+ return f"{base};{extra}" if extra else base
243
+
244
+
245
+ @dql.command("export")
246
+ @click.argument("query")
247
+ @click.option("--out", default=None, help="Output file path. If omitted, results are printed to stdout as a table.")
248
+ @click.option("--format", "fmt", type=click.Choice(["csv", "xls", "xlsx", "json"]), default="csv", help="Response format for --out (default csv).")
249
+ @click.option("--spec", "exportspec", default=None, help="exportspec, e.g. 'name,Name;nbEmployees,Employees;location.city.name,City'")
250
+ @click.option("--size", type=int, default=10, help="Page size (default 10).")
251
+ @click.option("--from", "from_", type=int, default=0, help="Pagination offset.")
252
+ @click.option("--filter", "filter_", default=None, help="Response field filter.")
253
+ def export(query: str, out, fmt: str, exportspec, size: int, from_: int, filter_):
254
+ """Execute a DQL query and print to stdout or save to a file."""
255
+ if out is not None:
256
+ resolved_spec = exportspec or _export_spec_for_query(query)
257
+ body = get_client().dql(
258
+ query,
259
+ size=size,
260
+ from_=from_,
261
+ format=fmt,
262
+ exportspec=resolved_spec or None,
263
+ filter=filter_,
264
+ raw=True,
265
+ )
266
+ dest = pathlib.Path(out).expanduser()
267
+ dest.parent.mkdir(parents=True, exist_ok=True)
268
+ dest.write_bytes(body)
269
+ click.echo(f"saved: {dest} ({len(body)} bytes)")
270
+ return
271
+
272
+ client = get_client()
273
+ resolved_spec = exportspec or _spec_for_query(query)
274
+
275
+ if sys.stdout.isatty():
276
+ with Progress(SpinnerColumn(), TextColumn("[progress.description]{task.description}"), transient=True) as progress:
277
+ progress.add_task(description=f"[Querying...] {query}", total=None)
278
+ hits = client.dql(query, size=0).get("hits", 0)
279
+ csv_bytes = client.dql(query, size=size, from_=from_, format="csv", exportspec=resolved_spec or None, filter=filter_, raw=True)
280
+ else:
281
+ hits = client.dql(query, size=0).get("hits", 0)
282
+ csv_bytes = client.dql(query, size=size, from_=from_, format="csv", exportspec=resolved_spec or None, filter=filter_, raw=True)
283
+
284
+ click.echo("")
285
+ click.echo(f"[Query] {query}")
286
+
287
+ reader = csv.reader(io.StringIO(csv_bytes.decode("utf-8")))
288
+ rows = list(reader)
289
+ if len(rows) < 2:
290
+ click.echo("(no results)")
291
+ return
292
+
293
+ headers, *data_rows = rows
294
+ table = Table(show_header=True, header_style="bold", show_lines=True)
295
+ for i, header in enumerate(headers):
296
+ if i < 3:
297
+ table.add_column(header, overflow="ellipsis", max_width=40, no_wrap=True)
298
+ else:
299
+ table.add_column(header, overflow="ellipsis", max_width=20, no_wrap=True)
300
+ for row in data_rows:
301
+ table.add_row(*row)
302
+
303
+ Console().print(table)
304
+
305
+ click.echo(f"{len(data_rows)} of {hits} records")
306
+ click.echo("")
307
+ click.echo("Options:")
308
+ click.echo(" --size N return N records (default 10; -1 for all)")
309
+ click.echo(" --from N skip the first N records (pagination offset)")
310
+ click.echo("")
@@ -0,0 +1,155 @@
1
+ """CLI command: db entities — identify and resolve entities in text via the Diffbot NLP API."""
2
+
3
+ import json
4
+ import sys
5
+
6
+ import click
7
+ from rich.console import Console
8
+ from rich.markup import escape
9
+ from rich.progress import Progress, SpinnerColumn, TextColumn
10
+ from rich.table import Table
11
+
12
+ from diffbot import AuthError, APIError
13
+
14
+ from ._common import get_client
15
+
16
+ console = Console()
17
+
18
+ _PALETTE = [
19
+ "cyan", "magenta", "yellow", "green", "blue", "red",
20
+ "bright_cyan", "bright_magenta", "bright_yellow", "bright_green",
21
+ ]
22
+
23
+
24
+ def _sentiment_label(score) -> str:
25
+ if score is None:
26
+ return ""
27
+ if score > 0.1:
28
+ return f"[green]+{score:.2f}[/green]"
29
+ if score < -0.1:
30
+ return f"[red]{score:.2f}[/red]"
31
+ return f"[dim]{score:.2f}[/dim]"
32
+
33
+
34
+ def _highlight_mentions(text: str, ents: list, palette: list) -> str:
35
+ spans = []
36
+ for i, e in enumerate(ents):
37
+ color = palette[i % len(palette)]
38
+ for m in e.get("mentions", []):
39
+ begin = m.get("beginOffset")
40
+ end = m.get("endOffset")
41
+ if begin is not None and end is not None:
42
+ spans.append((begin, end, color))
43
+
44
+ if not spans:
45
+ return escape(text)
46
+
47
+ spans.sort(key=lambda s: s[0])
48
+
49
+ parts = []
50
+ pos = 0
51
+ for begin, end, color in spans:
52
+ if begin < pos:
53
+ continue # skip overlapping spans
54
+ parts.append(escape(text[pos:begin]))
55
+ parts.append(f"[bold underline {color}]{escape(text[begin:end])}[/bold underline {color}]")
56
+ pos = end
57
+ parts.append(escape(text[pos:]))
58
+ return "".join(parts)
59
+
60
+
61
+ @click.command(name="entities")
62
+ @click.argument("text", required=False)
63
+ @click.option("-f", "--format", "fmt", type=click.Choice(["table", "json", "dql"]), default="table",
64
+ help="Output format: table (default), json (raw), dql (id:or(...) filter ready for db dql export)")
65
+ @click.option("--lang", default="auto", help="Language code (default: auto)")
66
+ def entities(text, fmt, lang):
67
+ """Identify and resolve entities and sentiment in text using the Diffbot NLP API.
68
+
69
+ TEXT can be passed as an argument or piped via stdin.
70
+
71
+ Entity IDs returned can be used in DQL for fast lookups:
72
+
73
+ db entities "..." -f dql | xargs db dql export
74
+ """
75
+ if text is None:
76
+ if sys.stdin.isatty():
77
+ raise click.UsageError("provide TEXT as an argument or pipe text via stdin")
78
+ text = sys.stdin.read().strip()
79
+ if not text:
80
+ raise click.UsageError("no text provided")
81
+
82
+ db = get_client()
83
+ try:
84
+ is_interactive = sys.stdout.isatty()
85
+ if is_interactive:
86
+ with Progress(SpinnerColumn(), TextColumn("[progress.description]{task.description}"), transient=True) as progress:
87
+ progress.add_task(description="Resolving entities...", total=None)
88
+ result = db.entities(text, lang=lang)
89
+ else:
90
+ result = db.entities(text, lang=lang)
91
+
92
+ if fmt == "json":
93
+ sys.stdout.write(json.dumps(result, indent=2))
94
+ sys.stdout.write("\n")
95
+ return
96
+
97
+ ents = result.get("entities", [])
98
+
99
+ if fmt == "dql":
100
+ ids = []
101
+ for e in ents:
102
+ raw = e.get("id") or e.get("diffbotUri") or ""
103
+ eid = raw.rstrip("/").rsplit("/", 1)[-1] if raw else ""
104
+ if eid:
105
+ ids.append(eid)
106
+ if not ids:
107
+ return
108
+ sys.stdout.write('id:or(' + ",".join(f'"{i}"' for i in ids) + ')\n')
109
+ return
110
+
111
+ doc_sentiment = result.get("sentiment")
112
+ if doc_sentiment is not None:
113
+ console.print(f"Document sentiment: {_sentiment_label(doc_sentiment)}")
114
+ console.print()
115
+
116
+ if not ents:
117
+ console.print("[dim]No entities found.[/dim]")
118
+ return
119
+
120
+ table = Table(show_header=True, header_style="bold", show_lines=False)
121
+ table.add_column("Entity", overflow="fold")
122
+ table.add_column("Type", no_wrap=True)
123
+ table.add_column("Confidence", no_wrap=True, justify="right")
124
+ table.add_column("Salience", no_wrap=True, justify="right")
125
+ table.add_column("Sentiment", no_wrap=True, justify="right")
126
+ table.add_column("Diffbot ID", overflow="fold", style="dim")
127
+
128
+ for i, e in enumerate(ents):
129
+ color = _PALETTE[i % len(_PALETTE)]
130
+ name = e.get("name") or e.get("label") or ""
131
+ all_types = e.get("allTypes") or []
132
+ etype = all_types[0]["name"] if all_types else (e.get("type") or "")
133
+ confidence = e.get("confidence")
134
+ salience = e.get("salience")
135
+ sentiment = e.get("sentiment")
136
+ raw = e.get("id") or e.get("diffbotUri") or ""
137
+ eid = raw.rstrip("/").rsplit("/", 1)[-1] if raw else ""
138
+ conf_str = f"{confidence:.2f}" if confidence is not None else ""
139
+ sal_str = f"{salience:.2f}" if salience is not None else ""
140
+ table.add_row(
141
+ f"[{color}]● {name}[/{color}]",
142
+ etype, conf_str, sal_str, _sentiment_label(sentiment), eid,
143
+ )
144
+
145
+ console.print(_highlight_mentions(text, ents, _PALETTE))
146
+ console.print()
147
+ console.print(table)
148
+ console.print(f"[dim]{len(ents)} entit{'y' if len(ents) == 1 else 'ies'} found[/dim]")
149
+
150
+ except AuthError:
151
+ click.echo("Error: Invalid or unauthorized API token.", err=True)
152
+ raise click.Abort()
153
+ except APIError as e:
154
+ click.echo(f"API error {e.status_code}: {e.message or e.body}", err=True)
155
+ raise click.Abort()
@@ -0,0 +1,74 @@
1
+ """CLI-side ontology access: a disk cache over the storage-agnostic core.
2
+
3
+ The navigation logic lives in :mod:`diffbot.ontology` (the `Ontology` class).
4
+ This module adds the CLI's caching policy on top: the ontology is read once from
5
+ ``~/.diffbot/ontology.json`` (populated by `db dql init`) and held in
6
+ ``_CACHE``. The module-level functions preserve the historical CLI surface and
7
+ simply delegate to an `Ontology` built from the cached document.
8
+ """
9
+
10
+ import json
11
+ import pathlib
12
+ from typing import Any, Dict, List, Optional, Tuple
13
+
14
+ from diffbot.ontology import Ontology
15
+
16
+ ONTOLOGY_PATH = pathlib.Path.home() / ".diffbot" / "ontology.json"
17
+
18
+ _CACHE: Dict[str, Any] = {}
19
+
20
+
21
+ def _data() -> Dict[str, Any]:
22
+ if "data" not in _CACHE:
23
+ if not ONTOLOGY_PATH.exists():
24
+ raise FileNotFoundError(
25
+ f"Ontology not found at {ONTOLOGY_PATH}. Run: db dql init"
26
+ )
27
+ _CACHE["data"] = json.loads(ONTOLOGY_PATH.read_text())
28
+ return _CACHE["data"]
29
+
30
+
31
+ def _ontology() -> Ontology:
32
+ return Ontology(_data())
33
+
34
+
35
+ def list_types() -> List[str]:
36
+ return _ontology().types()
37
+
38
+
39
+ def list_composites() -> List[str]:
40
+ return _ontology().composites()
41
+
42
+
43
+ def list_enums() -> List[str]:
44
+ return _ontology().enums()
45
+
46
+
47
+ def list_taxonomies() -> List[str]:
48
+ return _ontology().taxonomies()
49
+
50
+
51
+ def fields_for(type_name: str) -> Dict[str, Any]:
52
+ return _ontology().fields_for(type_name)
53
+
54
+
55
+ def format_field(name: str, meta: Dict[str, Any]) -> str:
56
+ return Ontology.format_field(name, meta)
57
+
58
+
59
+ def filter_fields(
60
+ fields: Dict[str, Any], search: Optional[str], include_deprecated: bool = False
61
+ ) -> List[Tuple[str, Dict[str, Any]]]:
62
+ return Ontology.filter_fields(fields, search, include_deprecated=include_deprecated)
63
+
64
+
65
+ def taxonomy_values(name: str, search: Optional[str] = None) -> List[str]:
66
+ return _ontology().taxonomy_values(name, search)
67
+
68
+
69
+ def enum_values(name: str) -> List[str]:
70
+ return _ontology().enum_values(name)
71
+
72
+
73
+ def find_named(search: str) -> List[str]:
74
+ return _ontology().find_named(search)