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