Graph-Native Infrastructure for Context and Accountable AI Systems
Python agent-memoryaiai-governanceai-infrastructureartificial-intelligencecontext-engineeringcontext-graphsdata-engineeringdecision-intelligencedeveloper-toolsexplainable-aigenerative-aigraph-ragknowledge-graphllmontologyprovenancepythonreasoningsemantic-search
fix(deps): address review feedback on slim core dependencies (#1513)
Zohaib Hassnaina0de5c2cdd50
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 917afbfe..9070ec51 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -97,6 +97,29 @@ jobs:- name: Build Explorer frontendworking-directory: explorerrun: npm run build+ - name: Install core package and base dependencies+ run: |+ # Verify that core semantica installs cleanly with only its base dependencies+ # (no optional extras) and that core imports and lazy missing-dependency hints work.+ #+ # --no-deps only skips *runtime* dependency resolution - `-e .`+ # still does a PEP 517 build, which by default creates an isolated+ # build env and fetches [build-system] requires (setuptools,+ # wheel) completely outside any hash checking. Install+ # pep517-build.txt (pins that exact build-system.requires) first+ # and pass --no-build-isolation so pip reuses those hash-verified+ # copies instead of fetching its own.+ pip install -r .github/requirements/pep517-build.txt --require-hashes+ pip install --no-deps --no-build-isolation -e .+ pip install -r .github/requirements/base-deps.txt --require-hashes+ pip install -r .github/requirements/pytest-tool.txt --require-hashes+ - name: Verify core-only package importability and slim behavior+ run: |+ python -c "+ import semantica+ print('semantica', semantica.__version__, 'core installed and importable')+ "+ pytest -q tests/test_issue_1513_slim_core.py- name: Install Explorer backend test dependenciesrun: |# Run the deterministic backend path before the all-extras CI@@ -104,10 +127,6 @@ jobs:# production API dependencies without importing optional vector# providers such as Pinecone during test collection.#- # --no-deps + a separate hash-pinned install (rather than the old- # `pip install -e ".[explorer]" pytest==9.1.1`) so every fetched- # package is hash-verified (Scorecard Pinned-Dependencies); the- # local editable install itself has nothing to hash.# .github/requirements/explorer-extra-py311.txt is# `uv pip compile pyproject.toml --extra explorer --python-version 3.11 --constraint requirements-ci.txt --generate-hashes`# - regenerate it the same way if pyproject.toml's base/explorer@@ -115,18 +134,7 @@ jobs:# (see the Dockerfile's explorer-extra-py313.txt for why this# can't be shared with python 3.13: audioread needs extra# standard-aifc/standard-sunau hashes only on 3.13+).- #- # --no-deps only skips *runtime* dependency resolution - `-e .`- # still does a PEP 517 build, which by default creates an isolated- # build env and fetches [build-system] requires (setuptools,- # wheel) completely outside any hash checking. Install- # pep517-build.txt (pins that exact build-system.requires) first- # and pass --no-build-isolation so pip reuses those hash-verified- # copies instead of fetching its own.- pip install -r .github/requirements/pep517-build.txt --require-hashes- pip install --no-deps --no-build-isolation -e .pip install -r .github/requirements/explorer-extra-py311.txt --require-hashes- pip install -r .github/requirements/pytest-tool.txt --require-hashes- name: Test deterministic Explorer backend pathrun: |pytest -q tests/explorer/test_explorer_deterministic_rendering_e2e.pydiff --git a/CHANGELOG.md b/CHANGELOG.mdindex 354fdc0c..ac219efa 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -18,7 +18,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0- Heavy ML/NLP, visualization, document parsing, and ingestion packages moved into granular optional extras:- `models-huggingface`: `torch`, `transformers`- `embeddings-local`: `sentence-transformers`, `fastembed`, `onnxruntime`, `tokenizers`- - `nlp-spacy`: `spacy`, `thinc`+ - `nlp-spacy`: `spacy`- `viz`: expanded to include `matplotlib`, `seaborn`, `plotly`, `ipywidgets`, `umap-learn`, alongside `pyvis`, `graphviz`, and `d3blocks`- `media`: `librosa`, `opencv-python`- `vectorstore-faiss`: `faiss-cpu` (also included in `vectorstore-all`)diff --git a/README.md b/README.mdindex beee7b95..59c36a70 100644--- a/README.md+++ b/README.md@@ -1537,7 +1537,7 @@ pip install "semantica[all]" # full bundled behavior with all extraspip install "semantica[documents]" # Document parsing (docx, openpyxl, lxml, beautifulsoup4)pip install "semantica[embeddings-local]" # Local embeddings (sentence-transformers, fastembed, onnxruntime)pip install "semantica[models-huggingface]" # HuggingFace models (transformers, torch)-pip install "semantica[nlp-spacy]" # spaCy NLP pipelines (spacy, thinc)+pip install "semantica[nlp-spacy]" # spaCy NLP pipelines (spacy)pip install "semantica[viz]" # Visualization (matplotlib, seaborn, plotly, pyvis, graphviz)pip install "semantica[media]" # Audio & computer vision (librosa, opencv-python)pip install "semantica[graph-embeddings]" # Knowledge graph embeddings (gensim / Node2Vec)diff --git a/pyproject.toml b/pyproject.tomlindex 3646838d..c853f605 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -158,8 +158,7 @@ embeddings-local = []nlp-spacy = ["spacy>=3.4.0,<3.8.8; python_version < '3.10'",- "spacy>=3.4.0; python_version >= '3.10'",- "thinc<8.3.5; python_version < '3.10'"+ "spacy>=3.4.0; python_version >= '3.10'"]# ---- Graph Backends ----diff --git a/semantica/ingest/repo_ingestor.py b/semantica/ingest/repo_ingestor.pyindex da045a0b..5996a9d7 100644--- a/semantica/ingest/repo_ingestor.py+++ b/semantica/ingest/repo_ingestor.py@@ -28,6 +28,7 @@ Example Usage:Author: Semantica ContributorsLicense: MIT"""+from __future__ import annotationsimport ipaddressimport os@@ -1070,14 +1071,14 @@ class RepoIngestor:return code_filesdef get_repository_info(- self, repo_url: str, repo: Optional[git.Repo] = None+ self, repo_url: str, repo: Optional[Any] = None) -> Dict[str, Any]:"""Get repository metadata and information.Args:repo_url: Repository URL- repo: Git repository object (optional)+ repo: Git repository object (git.Repo, optional)Returns:dict: Repository informationdiff --git a/semantica/ingest/xml_ingestor.py b/semantica/ingest/xml_ingestor.pyindex c7689f90..9f3be0ed 100644--- a/semantica/ingest/xml_ingestor.py+++ b/semantica/ingest/xml_ingestor.py@@ -792,8 +792,8 @@ class XMLIngestor:first_error = errors[0] if errors else "No detailed validation error available."return f"{prefix} for {source}: {first_error}"- def _format_xml_error(self, exc: etree.XMLSyntaxError) -> str:- if exc.error_log:+ def _format_xml_error(self, exc: Any) -> str:+ if hasattr(exc, "error_log") and exc.error_log:return str(exc.error_log.last_error)return str(exc)diff --git a/semantica/visualization/embedding_visualizer.py b/semantica/visualization/embedding_visualizer.pyindex b6ba2d88..648c9515 100644--- a/semantica/visualization/embedding_visualizer.py+++ b/semantica/visualization/embedding_visualizer.py@@ -33,10 +33,6 @@ License: MITfrom pathlib import Pathfrom typing import Any, Dict, List, Optional, Tuple, Union-try:- import matplotlib.pyplot as plt-except (ImportError, OSError):- plt = Noneimport numpy as nptry:@@ -64,7 +60,7 @@ from ..utils.exceptions import ProcessingErrorfrom ..utils.logging import get_loggerfrom ..utils.progress_tracker import get_progress_trackerfrom .utils.color_schemes import ColorPalette, ColorScheme-from .utils.export_formats import export_matplotlib_figure, export_plotly_figure+from .utils.export_formats import export_plotly_figureclass EmbeddingVisualizer:@@ -101,13 +97,18 @@ class EmbeddingVisualizer:self.color_scheme = ColorScheme.DEFAULTself.point_size = config.get("point_size", 5)- def _check_dependencies(self):+ def _check_dependencies(self, require_sklearn: bool = False):"""Check if dependencies are available."""if px is None or go is None:raise ProcessingError("Plotly is required for embedding visualization. ""Install with: pip install 'semantica[viz]'")+ if require_sklearn and (PCA is None or TSNE is None):+ raise ProcessingError(+ "scikit-learn is required for dimensionality reduction. "+ "Reinstall scikit-learn or install dependencies."+ )def visualize_2d_projection(self,@@ -172,8 +173,10 @@ class EmbeddingVisualizer:self.progress_tracker.update_tracking(tracking_id, message=f"Reducing dimensions using {method}...")+ dim_options = dict(options)+ n_comp = dim_options.pop("n_components", 2)projected = self._reduce_dimensions(- embeddings, method=method, n_components=2, **options+ embeddings, method=method, n_components=n_comp, **dim_options)self.progress_tracker.update_tracking(@@ -244,8 +247,10 @@ class EmbeddingVisualizer:self.progress_tracker.update_tracking(tracking_id, message=f"Reducing dimensions using {method}...")+ dim_options = dict(options)+ n_comp = dim_options.pop("n_components", 3)projected = self._reduce_dimensions(- embeddings, method=method, n_components=3, **options+ embeddings, method=method, n_components=n_comp, **dim_options)self.progress_tracker.update_tracking(@@ -411,8 +416,10 @@ class EmbeddingVisualizer:self.progress_tracker.update_tracking(tracking_id, message=f"Reducing dimensions using {method}...")+ dim_options = dict(options)+ n_comp = dim_options.pop("n_components", 2)projected = self._reduce_dimensions(- embeddings, method=method, n_components=2, **options+ embeddings, method=method, n_components=n_comp, **dim_options)num_clusters = len(set(cluster_labels))@@ -548,8 +555,10 @@ class EmbeddingVisualizer:self.progress_tracker.update_tracking(tracking_id, message=f"Reducing dimensions using {method}...")+ dim_options = dict(options)+ n_comp = dim_options.pop("n_components", 2)projected = self._reduce_dimensions(- combined_embeddings, method=method, n_components=2, **options+ combined_embeddings, method=method, n_components=n_comp, **dim_options)# Color by type@@ -615,39 +624,56 @@ class EmbeddingVisualizer:**options,) -> np.ndarray:"""Reduce embedding dimensions using specified method."""+ opts = dict(options)+ opts.pop("n_components", None)+if method == "pca":- pca = PCA(n_components=n_components, **options)+ if PCA is None:+ raise ProcessingError(+ "scikit-learn is required for dimensionality reduction. "+ "Reinstall scikit-learn or install dependencies."+ )+ pca = PCA(n_components=n_components, **opts)return pca.fit_transform(embeddings)elif method == "tsne":- perplexity = options.get("perplexity", min(30, len(embeddings) - 1))+ if TSNE is None:+ raise ProcessingError(+ "scikit-learn is required for dimensionality reduction. "+ "Reinstall scikit-learn or install dependencies."+ )+ perplexity = opts.pop("perplexity", min(30, len(embeddings) - 1))+ random_state = opts.pop("random_state", 42)tsne = TSNE(n_components=n_components,perplexity=perplexity,- random_state=42,- **options,+ random_state=random_state,+ **opts,)return tsne.fit_transform(embeddings)elif method == "umap":if umap is not None:- n_neighbors = options.get("n_neighbors", min(15, len(embeddings) - 1))+ n_neighbors = opts.pop("n_neighbors", min(15, len(embeddings) - 1))reducer = umap.UMAP(- n_components=n_components, n_neighbors=n_neighbors, **options+ n_components=n_components, n_neighbors=n_neighbors, **opts)return reducer.fit_transform(embeddings)else:- # Fallback to PCA if UMAP not available- self.logger.warning(- "UMAP not available, using PCA. Install with: pip install 'semantica[viz]'"+ raise ProcessingError(+ "UMAP is required for UMAP dimensionality reduction. "+ "Install with: pip install 'semantica[viz]'")- pca = PCA(n_components=n_components)- return pca.fit_transform(embeddings)else:+ if PCA is None:+ raise ProcessingError(+ "scikit-learn is required for dimensionality reduction. "+ "Reinstall scikit-learn or install dependencies."+ )# Fallback to PCAself.logger.warning(f"Method {method} not available, using PCA")- pca = PCA(n_components=n_components)+ pca = PCA(n_components=n_components, **opts)return pca.fit_transform(embeddings)def _visualize_2d_plotly(diff --git a/tests/test_issue_1513_slim_core.py b/tests/test_issue_1513_slim_core.pyindex 683e9720..039bccd9 100644--- a/tests/test_issue_1513_slim_core.py+++ b/tests/test_issue_1513_slim_core.py@@ -1,10 +1,6 @@from pathlib import Pathfrom unittest.mock import patchimport pytest-try:- import tomllib-except ImportError:- import toml as tomllibfrom semantica.parse.docx_parser import DOCXParserfrom semantica.parse.excel_parser import ExcelParser@@ -13,11 +9,25 @@ from semantica.parse.xml_parser import XMLParserfrom semantica.utils.exceptions import ProcessingError+def _load_toml(file_path: Path) -> dict:+ """Load and parse a TOML file across Python 3.8-3.14+ without mode mismatches."""+ content = file_path.read_text(encoding="utf-8")+ try:+ import tomllib # Python 3.11+ standard library+ return tomllib.loads(content)+ except ImportError:+ try:+ import tomli # Fast PEP 680 compatible parser for Python < 3.11+ return tomli.loads(content)+ except ImportError:+ import toml # Fallback toml parser+ return toml.loads(content)++def test_core_dependencies_count():"""pyproject.toml must contain exactly 22 unique core dependencies."""repo_root = Path(__file__).resolve().parents[1]- with open(repo_root / "pyproject.toml", "rb") as f:- data = tomllib.load(f)+ data = _load_toml(repo_root / "pyproject.toml")deps = data["project"]["dependencies"]normalized_names = {d.split(";")[0].split(">=")[0].split("<")[0].split("==")[0].strip()@@ -36,8 +46,7 @@ def test_core_dependencies_count():def test_optional_extras_defined():"""All required optional extras must be declared in pyproject.toml."""repo_root = Path(__file__).resolve().parents[1]- with open(repo_root / "pyproject.toml", "rb") as f:- data = tomllib.load(f)+ data = _load_toml(repo_root / "pyproject.toml")extras = data["project"]["optional-dependencies"]for extra in ["documents", "ingest-git", "embeddings-local", "nlp-spacy",@@ -53,6 +62,27 @@ def test_optional_extras_defined():# And vectorstore-faiss is in vectorstore-allassert "vectorstore-faiss" in str(extras["vectorstore-all"])+ # Verify nlp-spacy does not declare thinc directly (Qodo bot issue 1)+ nlp_spacy_deps = str(extras.get("nlp-spacy", []))+ assert "thinc" not in nlp_spacy_deps, "nlp-spacy should not directly declare thinc"+ assert "spacy" in nlp_spacy_deps, "nlp-spacy must declare spacy"+++def test_core_modules_importable():+ """Core modules must be importable without requiring optional extras."""+ import semantica+ import semantica.cli+ import semantica.parse+ import semantica.ingest+ import semantica.embeddings+ import semantica.export+ import semantica.kg+ import semantica.vector_store+ import semantica.visualization+ import semantica.semantic_extract+ import semantica.pipeline+ assert semantica.__version__ is not None+def test_docx_parser_lazy_construction_and_parse_hint():with patch("semantica.parse.docx_parser.Document", None):@@ -96,6 +126,20 @@ def test_xml_parser_lxml_explicit_requires_documents_extra():parser.parse("<root/>")+def test_xml_ingestor_missing_hint():+ with patch("semantica.ingest.xml_ingestor.etree", None):+ from semantica.ingest.xml_ingestor import XMLIngestor+ with pytest.raises(ProcessingError, match=r"semantica\[documents\]"):+ XMLIngestor()+++def test_repo_ingestor_missing_hint():+ with patch("semantica.ingest.repo_ingestor.git", None):+ from semantica.ingest.repo_ingestor import RepoIngestor+ with pytest.raises(ImportError, match=r"semantica\[ingest-git\]"):+ RepoIngestor()++def test_node_embedder_gensim_missing_hint():with patch("semantica.kg.node_embeddings.GENSIM_AVAILABLE", False):from semantica.kg.node_embeddings import NodeEmbedder@@ -117,10 +161,93 @@ def test_faiss_store_missing_hint():def test_visualization_missing_hint():import numpy as npfrom semantica.visualization.embedding_visualizer import EmbeddingVisualizer- with patch("semantica.visualization.embedding_visualizer.plt", None):++ # Plotly is checked via px and go in _check_dependencies+ with patch("semantica.visualization.embedding_visualizer.px", None):+ visualizer = EmbeddingVisualizer()+ with pytest.raises(ProcessingError, match=r"Plotly is required.*semantica\[viz\]"):+ visualizer.visualize_2d_projection(np.array([[0.1, 0.2], [0.3, 0.4]]))++ with patch("semantica.visualization.embedding_visualizer.go", None):+ visualizer = EmbeddingVisualizer()+ with pytest.raises(ProcessingError, match=r"Plotly is required.*semantica\[viz\]"):+ visualizer.visualize_2d_projection(np.array([[0.1, 0.2], [0.3, 0.4]]))+++def test_visualization_umap_missing_hint():+ import numpy as np+ from unittest.mock import MagicMock+ from semantica.visualization.embedding_visualizer import EmbeddingVisualizer++ # Stand in for Plotly so we reach dimensionality reduction+ with patch("semantica.visualization.embedding_visualizer.px", MagicMock()), \+ patch("semantica.visualization.embedding_visualizer.go", MagicMock()), \+ patch("semantica.visualization.embedding_visualizer.umap", None):visualizer = EmbeddingVisualizer()- with pytest.raises(ProcessingError, match=r"semantica\[viz\]"):- visualizer.visualize_2d_projection(np.array([[0.1, 0.2], [0.3, 0.4]]), output="png")+ # High-dimensional embeddings (>2D) trigger dimensionality reduction with method="umap"+ embeddings = np.array([[0.1, 0.2, 0.3], [0.4, 0.5, 0.6], [0.7, 0.8, 0.9]])+ with pytest.raises(ProcessingError, match=r"UMAP is required.*semantica\[viz\]"):+ visualizer.visualize_2d_projection(embeddings, method="umap")++ # Also verify 3D projection triggers the same actionable error on >3D embeddings+ embeddings_4d = np.array([[0.1, 0.2, 0.3, 0.4], [0.5, 0.6, 0.7, 0.8], [0.9, 1.0, 1.1, 1.2]])+ with pytest.raises(ProcessingError, match=r"UMAP is required.*semantica\[viz\]"):+ visualizer.visualize_3d_projection(embeddings_4d, method="umap")+++def test_visualization_sklearn_missing_hint():+ import numpy as np+ from unittest.mock import MagicMock+ from semantica.visualization.embedding_visualizer import EmbeddingVisualizer++ # Stand in for Plotly so we reach dimensionality reduction+ with patch("semantica.visualization.embedding_visualizer.px", MagicMock()), \+ patch("semantica.visualization.embedding_visualizer.go", MagicMock()):+ visualizer = EmbeddingVisualizer()+ embeddings = np.array([[0.1, 0.2, 0.3], [0.4, 0.5, 0.6], [0.7, 0.8, 0.9]])++ # Test direct dependency check+ with patch("semantica.visualization.embedding_visualizer.PCA", None):+ with pytest.raises(ProcessingError, match=r"scikit-learn is required"):+ visualizer._check_dependencies(require_sklearn=True)++ with patch("semantica.visualization.embedding_visualizer.PCA", None):+ with pytest.raises(ProcessingError, match=r"scikit-learn is required"):+ visualizer.visualize_2d_projection(embeddings, method="pca")++ with patch("semantica.visualization.embedding_visualizer.TSNE", None):+ with pytest.raises(ProcessingError, match=r"scikit-learn is required"):+ visualizer.visualize_2d_projection(embeddings, method="tsne")+++def test_visualization_options_collision_free():+ """Options such as n_components, perplexity, n_neighbors must not cause keyword collisions."""+ import numpy as np+ from unittest.mock import MagicMock+ from semantica.visualization.embedding_visualizer import EmbeddingVisualizer++ mock_pca = MagicMock()+ mock_tsne = MagicMock()+ mock_umap_cls = MagicMock()+ mock_umap_module = MagicMock()+ mock_umap_module.UMAP = mock_umap_cls++ with patch("semantica.visualization.embedding_visualizer.PCA", mock_pca), \+ patch("semantica.visualization.embedding_visualizer.TSNE", mock_tsne), \+ patch("semantica.visualization.embedding_visualizer.umap", mock_umap_module), \+ patch("semantica.visualization.embedding_visualizer.px", MagicMock()), \+ patch("semantica.visualization.embedding_visualizer.go", MagicMock()):+ visualizer = EmbeddingVisualizer()+ embeddings = np.array([[0.1, 0.2, 0.3], [0.4, 0.5, 0.6], [0.7, 0.8, 0.9]])++ # PCA with n_components+ visualizer.visualize_2d_projection(embeddings, method="pca", n_components=2)+ # TSNE with perplexity and random_state+ visualizer.visualize_2d_projection(embeddings, method="tsne", perplexity=1, random_state=42)+ # UMAP with n_neighbors and min_dist+ visualizer.visualize_2d_projection(embeddings, method="umap", n_neighbors=2, min_dist=0.1)+ # 3D with n_components+ visualizer.visualize_3d_projection(embeddings, method="pca", n_components=3)def test_spacy_load_missing_hint():diff --git a/tests/visualization/test_optional_dependencies.py b/tests/visualization/test_optional_dependencies.pyindex af41e5ca..0e7f7fb2 100644--- a/tests/visualization/test_optional_dependencies.py+++ b/tests/visualization/test_optional_dependencies.py@@ -38,14 +38,13 @@ class TestOptionalDependencies(unittest.TestCase):with import_without("semantica.visualization.embedding_visualizer", "umap") as module:- with plotly_doubles(module), patch.object(module, "PCA") as mock_pca_class:- mock_pca_class.return_value.fit_transform.return_value = np.zeros((4, 2))-+ with plotly_doubles(module):viz = module.EmbeddingVisualizer()embeddings = np.array([[0, 1, 2], [1, 0, 3], [0, 0, 0], [1, 1, 1]])- viz.visualize_2d_projection(embeddings, method="umap")-- mock_pca_class.assert_called()+ with self.assertRaises(module.ProcessingError) as cm:+ viz.visualize_2d_projection(embeddings, method="umap")+ self.assertIn("UMAP is required", str(cm.exception))+ self.assertIn("semantica[viz]", str(cm.exception))def test_ontology_visualizer_without_graphviz(self):"""Test OntologyVisualizer behavior when graphviz is missing."""