tortoise-graph 0.2.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.
- tortoise/__init__.py +45 -0
- tortoise/__main__.py +1865 -0
- tortoise/analyze.py +473 -0
- tortoise/api.py +303 -0
- tortoise/archived/search_legacy.py +31 -0
- tortoise/audit.py +236 -0
- tortoise/audit_events.py +284 -0
- tortoise/auth.py +107 -0
- tortoise/backup.py +155 -0
- tortoise/config.py +99 -0
- tortoise/connector_loader.py +74 -0
- tortoise/connectors/__init__.py +5 -0
- tortoise/connectors/github.py +432 -0
- tortoise/connectors/github_docs.py +146 -0
- tortoise/connectors/linear.py +199 -0
- tortoise/connectors/slack.py +222 -0
- tortoise/consistency.py +132 -0
- tortoise/crypto.py +52 -0
- tortoise/deployment.py +62 -0
- tortoise/domain_loader.py +142 -0
- tortoise/dream.py +153 -0
- tortoise/embedded_reaper.py +744 -0
- tortoise/embeddings.py +227 -0
- tortoise/ep.py +534 -0
- tortoise/exceptions.py +16 -0
- tortoise/extractor.py +945 -0
- tortoise/hosted_api.py +1982 -0
- tortoise/hosted_middleware.py +22 -0
- tortoise/idempotency.py +39 -0
- tortoise/ids.py +23 -0
- tortoise/indexer/github_indexer.py +129 -0
- tortoise/ingest.py +614 -0
- tortoise/log.py +29 -0
- tortoise/m0.py +50 -0
- tortoise/mcp_auth.py +337 -0
- tortoise/mcp_client.py +108 -0
- tortoise/mcp_server.py +1356 -0
- tortoise/memory_orchestrator.py +492 -0
- tortoise/memory_scope.py +15 -0
- tortoise/migrate_db.py +244 -0
- tortoise/migrate_kinds.py +141 -0
- tortoise/mining.py +338 -0
- tortoise/models.py +109 -0
- tortoise/monitoring.py +133 -0
- tortoise/navigation.py +216 -0
- tortoise/pack_registry.py +767 -0
- tortoise/pipeline_cli.py +197 -0
- tortoise/projection/__init__.py +913 -0
- tortoise/projection/edges.py +311 -0
- tortoise/projection/entities.py +521 -0
- tortoise/projection/grounding.py +95 -0
- tortoise/projection/propagation.py +114 -0
- tortoise/projection.py +37 -0
- tortoise/quadrature.py +90 -0
- tortoise/query_suggestions.py +194 -0
- tortoise/quota.py +163 -0
- tortoise/ranking.py +280 -0
- tortoise/render.py +108 -0
- tortoise/scripts/manifest.py +67 -0
- tortoise/sdk.py +4713 -0
- tortoise/search_engine.py +887 -0
- tortoise/security.py +268 -0
- tortoise/selfhost.py +157 -0
- tortoise/selfhost_api.py +201 -0
- tortoise/session_continuity.py +82 -0
- tortoise/session_indexer.py +569 -0
- tortoise/shared_state/__init__.py +20 -0
- tortoise/shared_state/concurrency.py +113 -0
- tortoise/shared_state/event_log.py +192 -0
- tortoise/shared_state/events.py +150 -0
- tortoise/shared_state/monitoring.py +87 -0
- tortoise/shared_state/recovery.py +126 -0
- tortoise/shared_state/tests/__init__.py +15 -0
- tortoise/shared_state/tests/test_concurrency.py +123 -0
- tortoise/shared_state/tests/test_events.py +145 -0
- tortoise/shared_state/tests/test_monitoring.py +54 -0
- tortoise/shared_state/tests/test_recovery.py +181 -0
- tortoise/source_credibility.py +306 -0
- tortoise/svbp.py +446 -0
- tortoise/taxonomy.py +71 -0
- tortoise/test_cross_ontology.py +180 -0
- tortoise/test_tortoise_client.py +206 -0
- tortoise/tool_registry.py +805 -0
- tortoise/tortoise_client.py +262 -0
- tortoise/verify_ontology.py +154 -0
- tortoise/version_vector.py +97 -0
- tortoise/weights.py +61 -0
- tortoise_graph-0.2.0.dist-info/METADATA +152 -0
- tortoise_graph-0.2.0.dist-info/RECORD +93 -0
- tortoise_graph-0.2.0.dist-info/WHEEL +5 -0
- tortoise_graph-0.2.0.dist-info/entry_points.txt +4 -0
- tortoise_graph-0.2.0.dist-info/licenses/LICENSE +95 -0
- tortoise_graph-0.2.0.dist-info/top_level.txt +1 -0
tortoise/embeddings.py
ADDED
|
@@ -0,0 +1,227 @@
|
|
|
1
|
+
"""Embedding-based cross-vocabulary concept matching for Tortoise.
|
|
2
|
+
|
|
3
|
+
Different sources use different words for the same concepts. Term-index matching
|
|
4
|
+
finds 0 cross-lens connections; embeddings bridge that gap.
|
|
5
|
+
"""
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
import logging
|
|
9
|
+
import threading
|
|
10
|
+
import numpy as np
|
|
11
|
+
|
|
12
|
+
logger = logging.getLogger(__name__)
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class EmbeddingModel:
|
|
16
|
+
"""Lazy-loaded embedding model singleton.
|
|
17
|
+
|
|
18
|
+
Loads all-MiniLM-L6-v2 (384-dim) via sentence-transformers. Model loading
|
|
19
|
+
runs in a worker thread with a 30s timeout. In the hosted Docker image the
|
|
20
|
+
model is pre-downloaded at build time (Dockerfile.hosted) and pre-warmed at
|
|
21
|
+
container start (entrypoint.sh), so the first API request never hits a cold
|
|
22
|
+
start. Failures are NOT permanent — the next get() call creates a fresh
|
|
23
|
+
instance and retries.
|
|
24
|
+
|
|
25
|
+
Embeddings are OPTIONAL — point creation and search must never depend on them.
|
|
26
|
+
"""
|
|
27
|
+
_instance: "EmbeddingModel | None" = None
|
|
28
|
+
_model = None
|
|
29
|
+
_lock = threading.Lock()
|
|
30
|
+
_LOAD_TIMEOUT_S = 30.0 # generous for cold I/O (model is 90MB on disk; pre-warmed at startup in hosted)
|
|
31
|
+
|
|
32
|
+
@classmethod
|
|
33
|
+
def get(cls, load_timeout: float | None = None) -> "EmbeddingModel | None":
|
|
34
|
+
"""Get or create the singleton. Returns None if model unavailable.
|
|
35
|
+
|
|
36
|
+
Loads the model in a worker thread with a hard timeout. In the hosted
|
|
37
|
+
Docker image the model is pre-downloaded at build time (Dockerfile.hosted)
|
|
38
|
+
and pre-warmed at startup via the FastAPI lifespan background thread
|
|
39
|
+
(hosted_api.py _lifespan), so this path is only hit in dev or if the
|
|
40
|
+
pre-warm was skipped. Unlike the old implementation, we do NOT
|
|
41
|
+
permanently self-disable — a transient failure (OOM from a competing
|
|
42
|
+
process, slow I/O) is retried on the next call.
|
|
43
|
+
|
|
44
|
+
Args:
|
|
45
|
+
load_timeout: Override _LOAD_TIMEOUT_S. The lifespan pre-warm
|
|
46
|
+
passes a longer window (cold-start torch import on a 2GB VM
|
|
47
|
+
can exceed 30s, #545); request paths keep the default so
|
|
48
|
+
latency stays bounded.
|
|
49
|
+
"""
|
|
50
|
+
timeout = load_timeout if load_timeout is not None else cls._LOAD_TIMEOUT_S
|
|
51
|
+
if cls._instance is None:
|
|
52
|
+
with cls._lock:
|
|
53
|
+
if cls._instance is None:
|
|
54
|
+
cls._instance = cls(load_timeout=timeout)
|
|
55
|
+
model = cls._instance._model if (cls._instance and cls._instance._model) else None
|
|
56
|
+
if model is None and cls._instance is not None:
|
|
57
|
+
# Transient load failure (timeout/OOM) — clear the instance so the
|
|
58
|
+
# NEXT get() call retries (code-review P2 fix, #160). Previously
|
|
59
|
+
# the timed-out instance was cached forever, making the failure
|
|
60
|
+
# permanent despite the docstring claiming retry.
|
|
61
|
+
with cls._lock:
|
|
62
|
+
cls._instance = None
|
|
63
|
+
cls._model = None
|
|
64
|
+
return model
|
|
65
|
+
|
|
66
|
+
@classmethod
|
|
67
|
+
def _reset(cls) -> None:
|
|
68
|
+
"""Test hook — clear cached instance."""
|
|
69
|
+
with cls._lock:
|
|
70
|
+
cls._instance = None
|
|
71
|
+
cls._model = None
|
|
72
|
+
|
|
73
|
+
def __init__(self, load_timeout: float | None = None):
|
|
74
|
+
timeout = load_timeout if load_timeout is not None else self._LOAD_TIMEOUT_S
|
|
75
|
+
result: dict = {"model": None}
|
|
76
|
+
|
|
77
|
+
def _load():
|
|
78
|
+
try:
|
|
79
|
+
from sentence_transformers import SentenceTransformer
|
|
80
|
+
result["model"] = SentenceTransformer("all-MiniLM-L6-v2")
|
|
81
|
+
except Exception as e: # noqa: BLE001
|
|
82
|
+
logger.info("sentence-transformers unavailable: %s", e)
|
|
83
|
+
result["model"] = None
|
|
84
|
+
|
|
85
|
+
t = threading.Thread(target=_load, daemon=True)
|
|
86
|
+
t.start()
|
|
87
|
+
t.join(timeout=timeout)
|
|
88
|
+
if t.is_alive():
|
|
89
|
+
# Model load timed out — log and return None. Do NOT permanently
|
|
90
|
+
# self-disable: in the hosted container the model is pre-downloaded
|
|
91
|
+
# and pre-warmed at startup (entrypoint.sh), so this path means
|
|
92
|
+
# transient resource starvation (OOM, competing process). Next call
|
|
93
|
+
# will create a fresh instance and retry.
|
|
94
|
+
logger.warning(
|
|
95
|
+
"Embedding model load exceeded %ss — returning None "
|
|
96
|
+
"(retries on next get() call).",
|
|
97
|
+
self._LOAD_TIMEOUT_S,
|
|
98
|
+
)
|
|
99
|
+
self._model = None
|
|
100
|
+
return
|
|
101
|
+
self._model = result["model"]
|
|
102
|
+
|
|
103
|
+
def encode(self, texts: list[str], batch_size: int = 32):
|
|
104
|
+
"""Encode texts to embeddings. Returns numpy array or None."""
|
|
105
|
+
if self._model is None:
|
|
106
|
+
return None
|
|
107
|
+
return self._model.encode(texts, batch_size=batch_size, show_progress_bar=False)
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def compute_embedding(content: str, max_tokens: int = 512) -> list[float] | None:
|
|
111
|
+
"""Compute embedding for a single text. Returns 384-dim list or None.
|
|
112
|
+
|
|
113
|
+
Truncates to max_tokens before encoding to prevent OOM.
|
|
114
|
+
Returns None if model unavailable or encoding fails.
|
|
115
|
+
"""
|
|
116
|
+
model = EmbeddingModel.get()
|
|
117
|
+
if model is None:
|
|
118
|
+
return None
|
|
119
|
+
try:
|
|
120
|
+
words = content.split()[:max_tokens]
|
|
121
|
+
truncated = " ".join(words)
|
|
122
|
+
vec = model.encode([truncated])
|
|
123
|
+
if vec is None or len(vec) == 0:
|
|
124
|
+
return None
|
|
125
|
+
return vec[0].tolist()
|
|
126
|
+
except Exception:
|
|
127
|
+
return None
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
def find_cross_source_matches(
|
|
131
|
+
points: dict[str, dict],
|
|
132
|
+
threshold: float = 0.75,
|
|
133
|
+
) -> list[dict]:
|
|
134
|
+
"""Find points from different speakers that describe the same concept.
|
|
135
|
+
|
|
136
|
+
Args:
|
|
137
|
+
points: point_id → {content, speaker, ...} from fold()
|
|
138
|
+
threshold: cosine similarity threshold (0.0 to 1.0)
|
|
139
|
+
|
|
140
|
+
Returns:
|
|
141
|
+
List of {"src": id, "dst": id, "similarity": float, "speakers": [sp1, sp2]}
|
|
142
|
+
"""
|
|
143
|
+
ids = list(points)
|
|
144
|
+
texts = [points[i]["content"] for i in ids]
|
|
145
|
+
speakers = [points[i].get("speaker", "unknown") for i in ids]
|
|
146
|
+
|
|
147
|
+
try:
|
|
148
|
+
from sentence_transformers import SentenceTransformer
|
|
149
|
+
model = SentenceTransformer("all-MiniLM-L6-v2")
|
|
150
|
+
vectors = model.encode(texts, show_progress_bar=False)
|
|
151
|
+
except ImportError:
|
|
152
|
+
from sklearn.feature_extraction.text import TfidfVectorizer
|
|
153
|
+
model = TfidfVectorizer()
|
|
154
|
+
vectors = model.fit_transform(texts).toarray()
|
|
155
|
+
|
|
156
|
+
# Normalized dot product = cosine similarity
|
|
157
|
+
norms = np.linalg.norm(vectors, axis=1, keepdims=True)
|
|
158
|
+
norms[norms == 0] = 1
|
|
159
|
+
vectors_n = vectors / norms
|
|
160
|
+
sim = vectors_n @ vectors_n.T
|
|
161
|
+
|
|
162
|
+
matches = []
|
|
163
|
+
n = len(ids)
|
|
164
|
+
for i in range(n):
|
|
165
|
+
for j in range(i + 1, n):
|
|
166
|
+
if speakers[i] == speakers[j]:
|
|
167
|
+
continue
|
|
168
|
+
if sim[i, j] >= threshold:
|
|
169
|
+
matches.append({
|
|
170
|
+
"src": ids[i],
|
|
171
|
+
"dst": ids[j],
|
|
172
|
+
"similarity": float(sim[i, j]),
|
|
173
|
+
"speakers": [speakers[i], speakers[j]],
|
|
174
|
+
})
|
|
175
|
+
|
|
176
|
+
return matches
|
|
177
|
+
|
|
178
|
+
|
|
179
|
+
def search_points(
|
|
180
|
+
query: str,
|
|
181
|
+
points: list[dict],
|
|
182
|
+
*,
|
|
183
|
+
threshold: float = 0.3,
|
|
184
|
+
limit: int = 10,
|
|
185
|
+
) -> list[dict]:
|
|
186
|
+
"""Semantic search over Points. Returns ranked [{id, content, similarity, snippet}, ...]."""
|
|
187
|
+
if not points:
|
|
188
|
+
return []
|
|
189
|
+
|
|
190
|
+
ids = [p["id"] for p in points]
|
|
191
|
+
texts = [p["content"] for p in points]
|
|
192
|
+
|
|
193
|
+
# ponytail: TF-IDF fallback — sentence_transformers is heavy
|
|
194
|
+
try:
|
|
195
|
+
from sentence_transformers import SentenceTransformer
|
|
196
|
+
model = SentenceTransformer("all-MiniLM-L6-v2")
|
|
197
|
+
vectors = model.encode([query] + texts, show_progress_bar=False)
|
|
198
|
+
query_vec, doc_vecs = vectors[0], vectors[1:]
|
|
199
|
+
except ImportError:
|
|
200
|
+
from sklearn.feature_extraction.text import TfidfVectorizer
|
|
201
|
+
model = TfidfVectorizer()
|
|
202
|
+
doc_vecs = model.fit_transform(texts).toarray()
|
|
203
|
+
query_vec = model.transform([query]).toarray()[0]
|
|
204
|
+
|
|
205
|
+
norms = np.linalg.norm(doc_vecs, axis=1, keepdims=True)
|
|
206
|
+
norms[norms == 0] = 1
|
|
207
|
+
doc_vecs_n = doc_vecs / norms
|
|
208
|
+
q_norm = np.linalg.norm(query_vec)
|
|
209
|
+
q_norm = q_norm if q_norm > 0 else 1
|
|
210
|
+
query_vec_n = query_vec / q_norm
|
|
211
|
+
|
|
212
|
+
sims = doc_vecs_n @ query_vec_n.T
|
|
213
|
+
|
|
214
|
+
results = []
|
|
215
|
+
for i, sim in enumerate(sims):
|
|
216
|
+
if sim < threshold:
|
|
217
|
+
continue
|
|
218
|
+
content = texts[i]
|
|
219
|
+
results.append({
|
|
220
|
+
"id": ids[i],
|
|
221
|
+
"content": content,
|
|
222
|
+
"similarity": float(sim),
|
|
223
|
+
"snippet": content[:200] if len(content) > 200 else content,
|
|
224
|
+
})
|
|
225
|
+
|
|
226
|
+
results.sort(key=lambda r: r["similarity"], reverse=True)
|
|
227
|
+
return results[:limit]
|