fihris 0.1__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.
- fihris/__init__.py +7 -0
- fihris/__main__.py +3 -0
- fihris/bm25.py +57 -0
- fihris/chunking.py +200 -0
- fihris/chunks.py +102 -0
- fihris/cli.py +255 -0
- fihris/clients.py +143 -0
- fihris/config.py +94 -0
- fihris/db.py +221 -0
- fihris/engine.py +592 -0
- fihris/ids.py +43 -0
- fihris/ingest/__init__.py +2 -0
- fihris/ingest/extract.py +160 -0
- fihris/library.py +220 -0
- fihris/principal.py +37 -0
- fihris/ranking.py +37 -0
- fihris/retrieve.py +95 -0
- fihris/text.py +48 -0
- fihris/units.py +57 -0
- fihris/vectors.py +213 -0
- fihris-0.1.dist-info/METADATA +148 -0
- fihris-0.1.dist-info/RECORD +26 -0
- fihris-0.1.dist-info/WHEEL +5 -0
- fihris-0.1.dist-info/entry_points.txt +2 -0
- fihris-0.1.dist-info/licenses/LICENSE +661 -0
- fihris-0.1.dist-info/top_level.txt +1 -0
fihris/__init__.py
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
"""Fihris (فهرس): a retrieval engine for Arabic and English documents. It ingests documents,
|
|
2
|
+
stores their chunks and vectors, and retrieves numbered, access-filtered sources for a question.
|
|
3
|
+
It stops at retrieval: answering is the caller's job."""
|
|
4
|
+
|
|
5
|
+
__version__ = "0.1"
|
|
6
|
+
|
|
7
|
+
__all__ = ["__version__"]
|
fihris/__main__.py
ADDED
fihris/bm25.py
ADDED
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
"""Okapi BM25 over loose-normalized words, without the Arabic article or proclitic+article."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import math
|
|
6
|
+
import re
|
|
7
|
+
from collections import Counter, defaultdict
|
|
8
|
+
|
|
9
|
+
import numpy as np
|
|
10
|
+
|
|
11
|
+
from fihris.text import normalize
|
|
12
|
+
|
|
13
|
+
K1 = 1.2
|
|
14
|
+
B = 0.75
|
|
15
|
+
PREFIXES = ("وال", "بال", "كال", "فال", "لل", "ال")
|
|
16
|
+
MIN_STEM = 3
|
|
17
|
+
_WORD = re.compile(r"\w+")
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def tokenize(text: str) -> list[str]:
|
|
21
|
+
"""Words of the loose-normalized text, each stripped of one leading article or
|
|
22
|
+
proclitic+article when at least three letters remain."""
|
|
23
|
+
tokens = []
|
|
24
|
+
for word in _WORD.findall(normalize(text, loose=True)):
|
|
25
|
+
prefix = next((p for p in PREFIXES if word.startswith(p)), "")
|
|
26
|
+
tokens.append(word[len(prefix):] if len(word) - len(prefix) >= MIN_STEM else word)
|
|
27
|
+
return tokens
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
class BM25:
|
|
31
|
+
"""Inverted index scored with Lucene's non-negative IDF,
|
|
32
|
+
``ln(1 + (N - df + 0.5) / (df + 0.5))``."""
|
|
33
|
+
|
|
34
|
+
def __init__(self, docs: list[list[str]], k1: float = K1, b: float = B):
|
|
35
|
+
self.k1, self.b, self.n = k1, b, len(docs)
|
|
36
|
+
lengths = np.array([len(doc) for doc in docs], dtype=np.float64)
|
|
37
|
+
self.avgdl = float(lengths.mean()) if lengths.any() else 1.0
|
|
38
|
+
self._norm = k1 * (1 - b + b * lengths / self.avgdl)
|
|
39
|
+
postings: dict[str, dict[int, int]] = defaultdict(dict)
|
|
40
|
+
for i, doc in enumerate(docs):
|
|
41
|
+
for term, tf in Counter(doc).items():
|
|
42
|
+
postings[term][i] = tf
|
|
43
|
+
self.postings = {term: (np.fromiter(found, dtype=np.int64),
|
|
44
|
+
np.fromiter(found.values(), dtype=np.float64))
|
|
45
|
+
for term, found in postings.items()}
|
|
46
|
+
self.idf = {term: math.log(1 + (self.n - len(found) + 0.5) / (len(found) + 0.5))
|
|
47
|
+
for term, found in postings.items()}
|
|
48
|
+
|
|
49
|
+
def scores(self, query: list[str]) -> np.ndarray:
|
|
50
|
+
"""One score per document. Every query word counts, so a repeated word weighs more."""
|
|
51
|
+
out = np.zeros(self.n)
|
|
52
|
+
for term, count in Counter(query).items():
|
|
53
|
+
if term in self.postings:
|
|
54
|
+
docs, tf = self.postings[term]
|
|
55
|
+
out[docs] += (count * self.idf[term] * tf * (self.k1 + 1)
|
|
56
|
+
/ (tf + self._norm[docs]))
|
|
57
|
+
return out
|
fihris/chunking.py
ADDED
|
@@ -0,0 +1,200 @@
|
|
|
1
|
+
"""Structure-aware chunks of a document's pages.
|
|
2
|
+
|
|
3
|
+
Chunks never cross a page, so every chunk belongs to exactly one page and citations stay exact.
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
import json
|
|
9
|
+
import math
|
|
10
|
+
import re
|
|
11
|
+
from collections import Counter, defaultdict
|
|
12
|
+
from collections.abc import Iterator
|
|
13
|
+
from pathlib import Path
|
|
14
|
+
|
|
15
|
+
from fihris.text import normalize
|
|
16
|
+
|
|
17
|
+
MAX_CHARS = 1000
|
|
18
|
+
MIN_CHARS = 200
|
|
19
|
+
|
|
20
|
+
_COLON_HEADING = re.compile(r"^[^|]{1,60}[::]$")
|
|
21
|
+
_NUMBERED_HEADING = re.compile(r"^([0-9٠-٩]+(?:\.[0-9٠-٩]+)+)[.)]?\s+\S")
|
|
22
|
+
_MD_HEADING = re.compile(r"^(#{1,6})\s+(.*)$")
|
|
23
|
+
_TABLE_RULE = re.compile(r"^\|?\s*:?-{3,}")
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def windows(text: str, size: int, overlap: int = 0) -> list[str]:
|
|
27
|
+
"""Fixed-size windows of about ``size`` characters, cut at spaces, overlapping by about
|
|
28
|
+
``overlap`` characters."""
|
|
29
|
+
text = " ".join(text.split())
|
|
30
|
+
if len(text) <= size:
|
|
31
|
+
return [text] if text else []
|
|
32
|
+
out, start = [], 0
|
|
33
|
+
while start < len(text):
|
|
34
|
+
end = min(len(text), start + size)
|
|
35
|
+
if end < len(text):
|
|
36
|
+
cut = text.rfind(" ", start + size // 2, end)
|
|
37
|
+
end = cut if cut > start else end
|
|
38
|
+
out.append(text[start:end].strip())
|
|
39
|
+
if end >= len(text):
|
|
40
|
+
break
|
|
41
|
+
next_start = text.find(" ", max(start + 1, end - overlap))
|
|
42
|
+
start = next_start + 1 if 0 <= next_start < end else end
|
|
43
|
+
return [w for w in out if w]
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def _blocks(md: str) -> list[tuple[str, str]]:
|
|
47
|
+
"""(kind, text) blocks of one page's Markdown: ``table`` rows grouped, ``text`` paragraphs
|
|
48
|
+
split at blank lines."""
|
|
49
|
+
out: list[tuple[str, str]] = []
|
|
50
|
+
paragraph: list[str] = []
|
|
51
|
+
table: list[str] = []
|
|
52
|
+
|
|
53
|
+
def flush_paragraph() -> None:
|
|
54
|
+
if paragraph:
|
|
55
|
+
out.append(("text", " ".join(paragraph)))
|
|
56
|
+
paragraph.clear()
|
|
57
|
+
|
|
58
|
+
def flush_table() -> None:
|
|
59
|
+
if table:
|
|
60
|
+
out.append(("table", "\n".join(table)))
|
|
61
|
+
table.clear()
|
|
62
|
+
|
|
63
|
+
for raw in md.splitlines():
|
|
64
|
+
line = raw.strip()
|
|
65
|
+
if line.startswith("<!--"):
|
|
66
|
+
continue
|
|
67
|
+
if line.startswith("|"):
|
|
68
|
+
flush_paragraph()
|
|
69
|
+
table.append(line)
|
|
70
|
+
elif not line:
|
|
71
|
+
flush_paragraph()
|
|
72
|
+
flush_table()
|
|
73
|
+
else:
|
|
74
|
+
flush_table()
|
|
75
|
+
paragraph.append(line)
|
|
76
|
+
flush_paragraph()
|
|
77
|
+
flush_table()
|
|
78
|
+
return out
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def table_rows(table: str) -> list[str]:
|
|
82
|
+
"""Each row of a Markdown table as its non-empty cells joined by `` | ``."""
|
|
83
|
+
rows = []
|
|
84
|
+
for line in table.splitlines():
|
|
85
|
+
if _TABLE_RULE.match(line.strip("| ")) or set(line) <= set("|-: "):
|
|
86
|
+
continue
|
|
87
|
+
cells = [c.strip() for c in line.strip().strip("|").split("|")]
|
|
88
|
+
cells = [c for c in cells if c]
|
|
89
|
+
if cells:
|
|
90
|
+
rows.append(" | ".join(dict.fromkeys(cells)))
|
|
91
|
+
return rows
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def heading_level(text: str) -> int:
|
|
95
|
+
"""0 if not a heading; else 1 for a label ending in a colon, the number of parts for a
|
|
96
|
+
numbered section such as 2.1, or the number of # for a Markdown heading."""
|
|
97
|
+
text = text.strip()
|
|
98
|
+
if match := _MD_HEADING.match(text):
|
|
99
|
+
return len(match.group(1))
|
|
100
|
+
if len(text) > 80:
|
|
101
|
+
return 0
|
|
102
|
+
words = len(text.split())
|
|
103
|
+
if _COLON_HEADING.match(text) and words <= 8:
|
|
104
|
+
return 1
|
|
105
|
+
if (match := _NUMBERED_HEADING.match(text)) and words <= 10 and not text.endswith("."):
|
|
106
|
+
return match.group(1).count(".") + 1
|
|
107
|
+
return 0
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def _furniture(pages: list[list[str]]) -> set[str]:
|
|
111
|
+
"""Normalized lines that repeat on at least half of a document's pages (and on two or
|
|
112
|
+
more): page headers, footers and document-control tables."""
|
|
113
|
+
if len(pages) < 2:
|
|
114
|
+
return set()
|
|
115
|
+
counts = Counter(key for lines in pages for key in {normalize(x, loose=True) for x in lines})
|
|
116
|
+
need = max(2, math.ceil(len(pages) / 2))
|
|
117
|
+
return {key for key, n in counts.items() if n >= need and key}
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def structured(doc_pages: list[dict], max_chars: int = MAX_CHARS,
|
|
121
|
+
min_chars: int = MIN_CHARS) -> Iterator[dict]:
|
|
122
|
+
"""Structure-aware chunks of one document: repeated page furniture kept only on its first
|
|
123
|
+
page, a new chunk at each heading, table rows kept whole, at most ``max_chars``, and no
|
|
124
|
+
chunk crossing a page. Each chunk carries its heading path."""
|
|
125
|
+
parsed = []
|
|
126
|
+
for page in doc_pages:
|
|
127
|
+
lines: list[tuple[str, str]] = []
|
|
128
|
+
for kind, text in _blocks(page.get("md") or page.get("text", "")):
|
|
129
|
+
if kind == "table":
|
|
130
|
+
lines.extend(("row", row) for row in table_rows(text))
|
|
131
|
+
else:
|
|
132
|
+
lines.append(("text", text))
|
|
133
|
+
parsed.append((page["page"], lines))
|
|
134
|
+
furniture = _furniture([[t for _k, t in lines] for _p, lines in parsed])
|
|
135
|
+
seen: set[str] = set()
|
|
136
|
+
path: list[tuple[int, str]] = []
|
|
137
|
+
for number, lines in parsed:
|
|
138
|
+
yield from _page_chunks(number, lines, path, furniture, seen, max_chars, min_chars)
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
def _page_chunks(number: int, lines: list[tuple[str, str]], path: list[tuple[int, str]],
|
|
142
|
+
furniture: set[str], seen: set[str], max_chars: int,
|
|
143
|
+
min_chars: int) -> Iterator[dict]:
|
|
144
|
+
"""One page's chunks. ``path`` (the heading path) and ``seen`` (furniture already kept)
|
|
145
|
+
carry over from page to page. Text shorter than ``min_chars`` before a heading joins the
|
|
146
|
+
next chunk instead of standing alone."""
|
|
147
|
+
buffer: list[str] = []
|
|
148
|
+
|
|
149
|
+
def flush(force: bool = False) -> Iterator[dict]:
|
|
150
|
+
text = "\n".join(buffer).strip()
|
|
151
|
+
if text and (force or len(text) >= min_chars):
|
|
152
|
+
yield {"page": number, "headings": [h for _lvl, h in path], "text": text}
|
|
153
|
+
buffer.clear()
|
|
154
|
+
|
|
155
|
+
for kind, text in lines:
|
|
156
|
+
key = normalize(text, loose=True)
|
|
157
|
+
if key in furniture:
|
|
158
|
+
if key in seen:
|
|
159
|
+
continue
|
|
160
|
+
seen.add(key)
|
|
161
|
+
level = heading_level(text) if kind == "text" else 0
|
|
162
|
+
if level:
|
|
163
|
+
yield from flush()
|
|
164
|
+
while path and path[-1][0] >= level:
|
|
165
|
+
path.pop()
|
|
166
|
+
path.append((level, _MD_HEADING.sub(r"\2", text).strip()))
|
|
167
|
+
buffer.append(path[-1][1])
|
|
168
|
+
continue
|
|
169
|
+
pieces = [text] if len(text) <= max_chars else windows(text, max_chars, 0)
|
|
170
|
+
for piece in pieces:
|
|
171
|
+
if buffer and sum(len(b) + 1 for b in buffer) + len(piece) > max_chars:
|
|
172
|
+
yield from flush(force=True)
|
|
173
|
+
buffer.append(piece)
|
|
174
|
+
yield from flush(force=True)
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
def contextual(chunk: dict, title: str) -> str:
|
|
178
|
+
"""The chunk text under a header naming its document and section."""
|
|
179
|
+
lines = [f"Document: {title}"]
|
|
180
|
+
if chunk.get("headings"):
|
|
181
|
+
lines.append("Section: " + " > ".join(chunk["headings"]))
|
|
182
|
+
return "\n".join(lines) + "\n" + chunk["text"]
|
|
183
|
+
|
|
184
|
+
|
|
185
|
+
def doc_title(relative_path: str) -> str:
|
|
186
|
+
"""A title from a file name: its stem, with underscores as spaces."""
|
|
187
|
+
return " ".join(Path(relative_path).stem.replace("_", " ").split())
|
|
188
|
+
|
|
189
|
+
|
|
190
|
+
def load_pages(index: Path) -> dict[str, list[dict]]:
|
|
191
|
+
"""A page index (JSON lines with ``doc_id``, ``page``, ``text`` and optional ``md``),
|
|
192
|
+
grouped by document in page order."""
|
|
193
|
+
by_doc: dict[str, list[dict]] = defaultdict(list)
|
|
194
|
+
with index.open(encoding="utf-8") as handle:
|
|
195
|
+
for line in handle:
|
|
196
|
+
row = json.loads(line)
|
|
197
|
+
by_doc[row["doc_id"]].append(row)
|
|
198
|
+
for pages in by_doc.values():
|
|
199
|
+
pages.sort(key=lambda r: r["page"])
|
|
200
|
+
return by_doc
|
fihris/chunks.py
ADDED
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
"""The chunk set of one index build, held in memory: unit texts and languages, the BM25 index,
|
|
2
|
+
and each document's groups and searchability, for the access mask."""
|
|
3
|
+
|
|
4
|
+
from __future__ import annotations
|
|
5
|
+
|
|
6
|
+
import json
|
|
7
|
+
from collections.abc import Iterable, Iterator
|
|
8
|
+
from dataclasses import dataclass, field
|
|
9
|
+
from pathlib import Path
|
|
10
|
+
|
|
11
|
+
import numpy as np
|
|
12
|
+
|
|
13
|
+
from fihris import bm25
|
|
14
|
+
from fihris.chunking import contextual, structured
|
|
15
|
+
from fihris.config import PINNED
|
|
16
|
+
from fihris.principal import Principal
|
|
17
|
+
from fihris.text import body, is_arabic
|
|
18
|
+
from fihris.units import Unit, fingerprint, load_chunks
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def unit_language(text: str) -> str:
|
|
22
|
+
return "ar" if is_arabic(body(text)) else "en"
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def chunk_document(pages: list[dict], title: str, doc_id: str) -> Iterator[dict]:
|
|
26
|
+
"""Structure-aware chunks of one document's pages, each under its document and section
|
|
27
|
+
header."""
|
|
28
|
+
for n, chunk in enumerate(structured(sorted(pages, key=lambda r: r["page"]),
|
|
29
|
+
PINNED.max_chars, PINNED.min_chars)):
|
|
30
|
+
yield {"doc_id": doc_id, "page": chunk["page"], "chunk": n,
|
|
31
|
+
"headings": chunk["headings"], "text": contextual(chunk, title)}
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def chunk_corpus(by_doc: dict[str, list[dict]], titles: dict[str, str]) -> list[dict]:
|
|
35
|
+
"""Every document's chunks, in ``doc_id`` order."""
|
|
36
|
+
out = []
|
|
37
|
+
for doc_id in sorted(by_doc):
|
|
38
|
+
out.extend(chunk_document(by_doc[doc_id], titles.get(doc_id, doc_id), doc_id))
|
|
39
|
+
return out
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def write_chunks(rows: Iterable[dict], path: Path) -> None:
|
|
43
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
44
|
+
with path.open("w", encoding="utf-8", newline="\n") as handle:
|
|
45
|
+
for row in rows:
|
|
46
|
+
handle.write(json.dumps(row, ensure_ascii=False) + "\n")
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
@dataclass
|
|
50
|
+
class Access:
|
|
51
|
+
"""A document's groups (``all`` when visible to everyone) and whether search may return it:
|
|
52
|
+
superseded, duplicate and removed documents may not."""
|
|
53
|
+
|
|
54
|
+
groups: tuple[str, ...]
|
|
55
|
+
searchable: bool = True
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
@dataclass
|
|
59
|
+
class ChunkSet:
|
|
60
|
+
units: list[Unit]
|
|
61
|
+
access: dict[str, Access] = field(default_factory=dict)
|
|
62
|
+
|
|
63
|
+
def __post_init__(self) -> None:
|
|
64
|
+
self.by_key = {u.key: u for u in self.units}
|
|
65
|
+
self.texts = {u.key: u.text for u in self.units}
|
|
66
|
+
self.langs = {u.key: unit_language(u.text) for u in self.units}
|
|
67
|
+
self.doc_ids = [u.doc_id for u in self.units]
|
|
68
|
+
self.bm25 = bm25.BM25([bm25.tokenize(u.text) for u in self.units])
|
|
69
|
+
self._masks: dict[frozenset[str] | None, np.ndarray] = {}
|
|
70
|
+
|
|
71
|
+
@classmethod
|
|
72
|
+
def from_file(cls, path: Path, access: dict[str, Access] | None = None) -> ChunkSet:
|
|
73
|
+
return cls(load_chunks(path), access or {})
|
|
74
|
+
|
|
75
|
+
@property
|
|
76
|
+
def fingerprint(self) -> str:
|
|
77
|
+
return fingerprint(self.units)
|
|
78
|
+
|
|
79
|
+
def set_access(self, access: dict[str, Access]) -> None:
|
|
80
|
+
self.access = access
|
|
81
|
+
self._masks.clear()
|
|
82
|
+
|
|
83
|
+
def mask(self, principal: Principal) -> np.ndarray:
|
|
84
|
+
"""Which units the principal may retrieve."""
|
|
85
|
+
key = principal.allowed
|
|
86
|
+
if key not in self._masks:
|
|
87
|
+
allowed_docs = {doc for doc, a in self.access.items()
|
|
88
|
+
if a.searchable and principal.may_read(a.groups)}
|
|
89
|
+
if not self.access:
|
|
90
|
+
allowed_docs = set(self.doc_ids) if key is None else set()
|
|
91
|
+
self._masks[key] = np.fromiter((d in allowed_docs for d in self.doc_ids), dtype=bool,
|
|
92
|
+
count=len(self.doc_ids))
|
|
93
|
+
return self._masks[key]
|
|
94
|
+
|
|
95
|
+
def keyword(self, text: str, mask: np.ndarray, depth: int = PINNED.bm25_depth) -> list[dict]:
|
|
96
|
+
"""The top BM25 hits over the allowed units only: the stable order of all scores,
|
|
97
|
+
restricted before cutting, so a restricted principal still gets a full top list."""
|
|
98
|
+
scores = self.bm25.scores(bm25.tokenize(text))
|
|
99
|
+
order = np.argsort(-scores, kind="stable")
|
|
100
|
+
if not mask.all():
|
|
101
|
+
order = order[mask[order]]
|
|
102
|
+
return [self.units[i].hit(float(scores[i])) for i in order[:depth]]
|
fihris/cli.py
ADDED
|
@@ -0,0 +1,255 @@
|
|
|
1
|
+
"""The ``fihris`` command line: set up, ingest files, search, manage builds and access. Output is
|
|
2
|
+
content-free unless ``--text`` is asked for.
|
|
3
|
+
|
|
4
|
+
fihris init-db
|
|
5
|
+
fihris ingest documents/ --visible-to-all
|
|
6
|
+
fihris search "How many days of annual leave?" --text
|
|
7
|
+
fihris status
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import argparse
|
|
13
|
+
import json
|
|
14
|
+
import sys
|
|
15
|
+
import time
|
|
16
|
+
from pathlib import Path
|
|
17
|
+
|
|
18
|
+
from sqlalchemy import func, select
|
|
19
|
+
|
|
20
|
+
from fihris.config import PINNED, Endpoints
|
|
21
|
+
from fihris.db import Chunk, Document, Job, Page, create_schema, engine_for, sessions
|
|
22
|
+
from fihris.principal import Principal
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def _engine(args, **clients):
|
|
26
|
+
from fihris.engine import Engine
|
|
27
|
+
|
|
28
|
+
endpoints = Endpoints.from_env()
|
|
29
|
+
db = engine_for(args.database or endpoints.database_url)
|
|
30
|
+
create_schema(db)
|
|
31
|
+
engine = Engine(endpoints, sessions(db), **clients)
|
|
32
|
+
engine.load()
|
|
33
|
+
return engine
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def _print(data: dict) -> None:
|
|
37
|
+
print(json.dumps(data, ensure_ascii=False, indent=1, default=str))
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def cmd_init_db(args) -> int:
|
|
41
|
+
db = engine_for(args.database or Endpoints.from_env().database_url)
|
|
42
|
+
create_schema(db)
|
|
43
|
+
_print({"database": db.url.render_as_string(hide_password=True), "created": True})
|
|
44
|
+
return 0
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def cmd_import_pages(args) -> int:
|
|
48
|
+
"""Documents and their page text extracted elsewhere, chunked and embedded as one new build:
|
|
49
|
+
documents from a JSON-lines catalogue (``Document`` columns per row, at least
|
|
50
|
+
``relative_path`` or ``doc_id``), pages from a page index."""
|
|
51
|
+
from fihris.chunking import load_pages
|
|
52
|
+
from fihris.chunks import chunk_corpus
|
|
53
|
+
|
|
54
|
+
engine = _engine(args)
|
|
55
|
+
with args.catalogue.open(encoding="utf-8") as handle:
|
|
56
|
+
rows = [json.loads(line) for line in handle if line.strip()]
|
|
57
|
+
report: dict = {"documents": engine.upsert_documents(rows),
|
|
58
|
+
"pages": engine.import_pages(args.pages)}
|
|
59
|
+
with engine.make_session() as session:
|
|
60
|
+
titles = {d.doc_id: d.title for d in session.scalars(select(Document)).all()}
|
|
61
|
+
chunks = chunk_corpus(load_pages(args.pages), titles)
|
|
62
|
+
report["chunks"] = len(chunks)
|
|
63
|
+
vectors = engine.embed_chunks([r["text"] for r in chunks])
|
|
64
|
+
report["build"] = engine.create_build(chunks, vectors, None, "embedded", args.activate,
|
|
65
|
+
args.build_id)
|
|
66
|
+
with engine.make_session() as session:
|
|
67
|
+
indexed = {r["doc_id"] for r in chunks}
|
|
68
|
+
for doc in session.scalars(select(Document)).all():
|
|
69
|
+
doc.index_state = "indexed" if doc.doc_id in indexed else "not_indexed"
|
|
70
|
+
session.commit()
|
|
71
|
+
engine.load()
|
|
72
|
+
_print(report)
|
|
73
|
+
return 0
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def cmd_status(args) -> int:
|
|
77
|
+
engine = _engine(args)
|
|
78
|
+
with engine.make_session() as session:
|
|
79
|
+
def count(model, *where):
|
|
80
|
+
return session.scalar(select(func.count()).select_from(model).where(*where))
|
|
81
|
+
|
|
82
|
+
build = engine.active_build(session)
|
|
83
|
+
_print({"active_build": build.build_id if build else None,
|
|
84
|
+
"build_chunks": count(Chunk, Chunk.build_id == build.build_id) if build else 0,
|
|
85
|
+
"documents": count(Document), "removed": count(Document, Document.removed),
|
|
86
|
+
"visible_to_all": count(Document, Document.visible_to_all),
|
|
87
|
+
"pages": count(Page), "jobs_running": count(Job, Job.state == "running"),
|
|
88
|
+
"config_sha256": PINNED.sha256})
|
|
89
|
+
return 0
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def cmd_builds(args) -> int:
|
|
93
|
+
engine = _engine(args)
|
|
94
|
+
_print({"builds": [{"build_id": b.build_id, "state": b.state, "chunks": b.chunk_count,
|
|
95
|
+
"documents": b.document_count, "units_sha256": b.units_sha256,
|
|
96
|
+
"vectors": b.vectors_source, "created_at": b.created_at}
|
|
97
|
+
for b in engine.builds()]})
|
|
98
|
+
return 0
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def cmd_activate(args) -> int:
|
|
102
|
+
engine = _engine(args)
|
|
103
|
+
engine.activate(args.build_id)
|
|
104
|
+
_print({"active_build": args.build_id})
|
|
105
|
+
return 0
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def cmd_search(args) -> int:
|
|
109
|
+
engine = _engine(args)
|
|
110
|
+
principal = (Principal.for_groups(args.groups, args.pilot) if args.groups or args.pilot
|
|
111
|
+
else Principal.unrestricted())
|
|
112
|
+
result = engine.retrieve(args.question, principal)
|
|
113
|
+
_print({"question_language": result.question_language, "timings": result.timings,
|
|
114
|
+
"sources": [{"n": s.n, "doc_id": s.doc_id, "page": s.page, "chunk": s.chunk,
|
|
115
|
+
"score": s.score, "language": s.language,
|
|
116
|
+
**({"text": s.text} if args.text else {})} for s in result.sources]})
|
|
117
|
+
return 0
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def cmd_access(args) -> int:
|
|
121
|
+
"""Set documents' groups or visibility, by id or by access-level label."""
|
|
122
|
+
engine = _engine(args)
|
|
123
|
+
with engine.make_session() as session:
|
|
124
|
+
query = select(Document)
|
|
125
|
+
if args.doc:
|
|
126
|
+
query = query.where(Document.doc_id.in_(args.doc))
|
|
127
|
+
if args.access_level:
|
|
128
|
+
query = query.where(Document.access_level.in_(args.access_level))
|
|
129
|
+
docs = session.scalars(query).all()
|
|
130
|
+
for doc in docs:
|
|
131
|
+
if args.visible_to_all is not None:
|
|
132
|
+
doc.visible_to_all = args.visible_to_all == "yes"
|
|
133
|
+
if args.groups is not None:
|
|
134
|
+
doc.groups = sorted(set(args.groups))
|
|
135
|
+
session.commit()
|
|
136
|
+
ids = [d.doc_id for d in docs]
|
|
137
|
+
engine.refresh_access()
|
|
138
|
+
if engine.build is not None:
|
|
139
|
+
for doc_id in ids:
|
|
140
|
+
engine.refresh_access(doc_id)
|
|
141
|
+
_print({"documents_changed": len(ids)})
|
|
142
|
+
return 0
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
SUFFIXES = (".pdf", ".docx", ".doc", ".xlsx", ".pptx", ".html", ".htm", ".md", ".markdown",
|
|
146
|
+
".csv", ".txt", ".png", ".jpg", ".jpeg", ".tif", ".tiff", ".bmp", ".gif", ".webp")
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
def _files(paths: list[Path]) -> list[Path]:
|
|
150
|
+
out = []
|
|
151
|
+
for path in paths:
|
|
152
|
+
if path.is_dir():
|
|
153
|
+
out.extend(sorted(p for p in path.rglob("*")
|
|
154
|
+
if p.is_file() and p.suffix.lower() in SUFFIXES))
|
|
155
|
+
else:
|
|
156
|
+
out.append(path)
|
|
157
|
+
return out
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
def cmd_ingest(args) -> int:
|
|
161
|
+
"""Add files, or every supported file in folders, one job each, and wait for them."""
|
|
162
|
+
engine = _engine(args)
|
|
163
|
+
files = _files(args.paths)
|
|
164
|
+
if args.title and len(files) != 1:
|
|
165
|
+
print("--title needs exactly one file", file=sys.stderr)
|
|
166
|
+
return 2
|
|
167
|
+
metadata = {"visible_to_all": True} if args.visible_to_all else {}
|
|
168
|
+
if args.groups:
|
|
169
|
+
metadata["group_ids"] = args.groups
|
|
170
|
+
jobs = []
|
|
171
|
+
for file in files:
|
|
172
|
+
with engine.make_session() as session:
|
|
173
|
+
doc_id, path, checksum = engine.store_upload(file.read_bytes(), file.name)
|
|
174
|
+
engine.new_document(session, doc_id, path, checksum, file.name,
|
|
175
|
+
{**metadata, **({"title": args.title} if args.title else {})},
|
|
176
|
+
None)
|
|
177
|
+
session.commit()
|
|
178
|
+
jobs.append((engine.submit("ingest", doc_id, None, path=str(path)), doc_id, file))
|
|
179
|
+
results = []
|
|
180
|
+
for job_id, doc_id, file in jobs:
|
|
181
|
+
while True:
|
|
182
|
+
with engine.make_session() as session:
|
|
183
|
+
job = session.get(Job, job_id)
|
|
184
|
+
if job.state in ("succeeded", "failed", "cancelled"):
|
|
185
|
+
results.append({"file": file.name, "doc_id": doc_id, "state": job.state,
|
|
186
|
+
"pages_sent_to_review": job.pages_sent_to_review,
|
|
187
|
+
"errors": job.errors})
|
|
188
|
+
break
|
|
189
|
+
time.sleep(1)
|
|
190
|
+
_print({"files": len(files), "results": results})
|
|
191
|
+
return 0 if all(r["state"] == "succeeded" for r in results) else 1
|
|
192
|
+
|
|
193
|
+
|
|
194
|
+
def cmd_reindex(args) -> int:
|
|
195
|
+
engine = _engine(args)
|
|
196
|
+
job_id = engine.submit("reindex_corpus", None, None)
|
|
197
|
+
while True:
|
|
198
|
+
with engine.make_session() as session:
|
|
199
|
+
job = session.get(Job, job_id)
|
|
200
|
+
if job.state in ("succeeded", "failed", "cancelled"):
|
|
201
|
+
_print({"job_id": job_id, "state": job.state, "target_build": job.target_build,
|
|
202
|
+
"errors": job.errors})
|
|
203
|
+
return 0 if job.state == "succeeded" else 1
|
|
204
|
+
time.sleep(2)
|
|
205
|
+
|
|
206
|
+
|
|
207
|
+
def parser() -> argparse.ArgumentParser:
|
|
208
|
+
p = argparse.ArgumentParser(prog="fihris", description="Fihris: ingestion, storage and "
|
|
209
|
+
"retrieval of Arabic and English documents.")
|
|
210
|
+
p.add_argument("--database", help="SQLAlchemy URL (default FIHRIS_DATABASE_URL)")
|
|
211
|
+
sub = p.add_subparsers(dest="command", required=True)
|
|
212
|
+
sub.add_parser("init-db").set_defaults(run=cmd_init_db)
|
|
213
|
+
s = sub.add_parser("import-pages", help="documents and page text extracted elsewhere, as a "
|
|
214
|
+
"new build")
|
|
215
|
+
s.add_argument("--catalogue", type=Path, required=True,
|
|
216
|
+
help="JSON lines, one document per line")
|
|
217
|
+
s.add_argument("--pages", type=Path, required=True, help="page index, JSON lines")
|
|
218
|
+
s.add_argument("--build-id")
|
|
219
|
+
s.add_argument("--activate", action="store_true")
|
|
220
|
+
s.set_defaults(run=cmd_import_pages)
|
|
221
|
+
sub.add_parser("status").set_defaults(run=cmd_status)
|
|
222
|
+
sub.add_parser("builds").set_defaults(run=cmd_builds)
|
|
223
|
+
s = sub.add_parser("activate")
|
|
224
|
+
s.add_argument("build_id")
|
|
225
|
+
s.set_defaults(run=cmd_activate)
|
|
226
|
+
s = sub.add_parser("search")
|
|
227
|
+
s.add_argument("question")
|
|
228
|
+
s.add_argument("--groups", nargs="*", default=[])
|
|
229
|
+
s.add_argument("--pilot", action="store_true")
|
|
230
|
+
s.add_argument("--text", action="store_true", help="print the source texts")
|
|
231
|
+
s.set_defaults(run=cmd_search)
|
|
232
|
+
s = sub.add_parser("access", help="set groups or visibility")
|
|
233
|
+
s.add_argument("--doc", nargs="*")
|
|
234
|
+
s.add_argument("--access-level", nargs="*")
|
|
235
|
+
s.add_argument("--visible-to-all", choices=["yes", "no"])
|
|
236
|
+
s.add_argument("--groups", nargs="*")
|
|
237
|
+
s.set_defaults(run=cmd_access)
|
|
238
|
+
s = sub.add_parser("ingest", help="add files or folders and wait for their jobs")
|
|
239
|
+
s.add_argument("paths", type=Path, nargs="+")
|
|
240
|
+
s.add_argument("--title", help="for a single file")
|
|
241
|
+
s.add_argument("--visible-to-all", action="store_true")
|
|
242
|
+
s.add_argument("--groups", nargs="*", help="group ids that may read the documents")
|
|
243
|
+
s.set_defaults(run=cmd_ingest)
|
|
244
|
+
sub.add_parser("reindex", help="re-chunk every document into a new build").set_defaults(
|
|
245
|
+
run=cmd_reindex)
|
|
246
|
+
return p
|
|
247
|
+
|
|
248
|
+
|
|
249
|
+
def main(argv: list[str] | None = None) -> int:
|
|
250
|
+
args = parser().parse_args(argv)
|
|
251
|
+
return args.run(args)
|
|
252
|
+
|
|
253
|
+
|
|
254
|
+
if __name__ == "__main__":
|
|
255
|
+
raise SystemExit(main())
|