python-lucide 0.5.14__tar.gz → 0.5.15__tar.gz

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.
Files changed (41) hide show
  1. {python_lucide-0.5.14 → python_lucide-0.5.15}/Makefile +2 -6
  2. {python_lucide-0.5.14 → python_lucide-0.5.15}/PKG-INFO +5 -26
  3. {python_lucide-0.5.14 → python_lucide-0.5.15}/README.md +2 -24
  4. {python_lucide-0.5.14 → python_lucide-0.5.15}/pyproject.toml +7 -17
  5. {python_lucide-0.5.14 → python_lucide-0.5.15}/src/lucide/__init__.py +6 -1
  6. {python_lucide-0.5.14 → python_lucide-0.5.15}/src/lucide/build_clusters.py +7 -7
  7. {python_lucide-0.5.14 → python_lucide-0.5.15}/src/lucide/build_search.py +9 -5
  8. {python_lucide-0.5.14 → python_lucide-0.5.15}/src/lucide/cli.py +8 -20
  9. {python_lucide-0.5.14 → python_lucide-0.5.15}/src/lucide/config.py +2 -1
  10. {python_lucide-0.5.14 → python_lucide-0.5.15}/src/lucide/core.py +24 -7
  11. {python_lucide-0.5.14 → python_lucide-0.5.15}/src/lucide/db.py +8 -4
  12. {python_lucide-0.5.14 → python_lucide-0.5.15}/src/lucide/dev_utils.py +3 -3
  13. python_lucide-0.5.15/src/lucide/py.typed +0 -0
  14. {python_lucide-0.5.14 → python_lucide-0.5.15}/src/lucide/search.py +55 -39
  15. {python_lucide-0.5.14 → python_lucide-0.5.15}/tests/build_clusters_test.py +46 -1
  16. {python_lucide-0.5.14 → python_lucide-0.5.15}/tests/build_search_test.py +3 -3
  17. {python_lucide-0.5.14 → python_lucide-0.5.15}/tests/cli_test.py +11 -2
  18. {python_lucide-0.5.14 → python_lucide-0.5.15}/tests/conftest.py +1 -0
  19. {python_lucide-0.5.14 → python_lucide-0.5.15}/tests/core_test.py +57 -0
  20. {python_lucide-0.5.14 → python_lucide-0.5.15}/tests/search_test.py +52 -16
  21. {python_lucide-0.5.14 → python_lucide-0.5.15}/.gitignore +0 -0
  22. {python_lucide-0.5.14 → python_lucide-0.5.15}/LICENSE +0 -0
  23. {python_lucide-0.5.14 → python_lucide-0.5.15}/build_support.py +0 -0
  24. {python_lucide-0.5.14 → python_lucide-0.5.15}/hatch_build.py +0 -0
  25. {python_lucide-0.5.14 → python_lucide-0.5.15}/src/lucide/data/__init__.py +0 -0
  26. {python_lucide-0.5.14 → python_lucide-0.5.15}/src/lucide/data/gemini-icon-descriptions.jsonl +0 -0
  27. {python_lucide-0.5.14 → python_lucide-0.5.15}/src/lucide/data/lucide-icon-clusters.json +0 -0
  28. {python_lucide-0.5.14 → python_lucide-0.5.15}/src/lucide/data/lucide-icons.sql +0 -0
  29. {python_lucide-0.5.14 → python_lucide-0.5.15}/tests/__init__.py +0 -0
  30. {python_lucide-0.5.14 → python_lucide-0.5.15}/tests/db_source_test.py +0 -0
  31. {python_lucide-0.5.14 → python_lucide-0.5.15}/web/src/App.svelte +0 -0
  32. {python_lucide-0.5.14 → python_lucide-0.5.15}/web/src/app.css +0 -0
  33. {python_lucide-0.5.14 → python_lucide-0.5.15}/web/src/components/DetailPanel.svelte +0 -0
  34. {python_lucide-0.5.14 → python_lucide-0.5.15}/web/src/lib/clusters.ts +0 -0
  35. {python_lucide-0.5.14 → python_lucide-0.5.15}/web/src/lib/embeddings.ts +0 -0
  36. {python_lucide-0.5.14 → python_lucide-0.5.15}/web/src/lib/model-loader.ts +0 -0
  37. {python_lucide-0.5.14 → python_lucide-0.5.15}/web/src/lib/types.ts +0 -0
  38. {python_lucide-0.5.14 → python_lucide-0.5.15}/web/src/main.ts +0 -0
  39. {python_lucide-0.5.14 → python_lucide-0.5.15}/web/src/pages/ExplorePage.svelte +0 -0
  40. {python_lucide-0.5.14 → python_lucide-0.5.15}/web/src/pages/SearchPage.svelte +0 -0
  41. {python_lucide-0.5.14 → python_lucide-0.5.15}/web/src/vite-env.d.ts +0 -0
@@ -48,15 +48,11 @@ help:
48
48
  @echo " nuke A more thorough clean: runs 'clean', 'uv cache clean', and removes $(VENV_DIR)."
49
49
  @echo ""
50
50
 
51
- env: $(VENV_DIR)/pyvenv.cfg
51
+ env:
52
52
  @echo "Installing/updating development dependencies into $(VENV_DIR)..."
53
- $(UV_CMD) pip install -e ".[dev]"
53
+ $(UV_CMD) sync --dev
54
54
  @echo "Development environment ready in $(VENV_DIR)/."
55
55
 
56
- $(VENV_DIR)/pyvenv.cfg:
57
- @echo "Creating virtual environment in $(VENV_DIR)/ using $(UV_CMD)..."
58
- $(UV_CMD) venv $(VENV_DIR)
59
-
60
56
  lucide-db:
61
57
  @echo "Building Lucide icon database with tag $(TAG) into $(DB_OUTPUT_PATH)..."
62
58
  @mkdir -p src/lucide/data # Ensure data directory exists
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: python-lucide
3
- Version: 0.5.14
3
+ Version: 0.5.15
4
4
  Summary: A Python package for working with Lucide icons
5
5
  Project-URL: Bug Tracker, https://github.com/mmacpherson/python-lucide/issues
6
6
  Project-URL: Homepage, https://github.com/mmacpherson/python-lucide
@@ -17,11 +17,12 @@ Classifier: Programming Language :: Python :: 3.11
17
17
  Classifier: Programming Language :: Python :: 3.12
18
18
  Classifier: Programming Language :: Python :: 3.13
19
19
  Classifier: Programming Language :: Python :: 3.14
20
+ Classifier: Programming Language :: Python :: 3.15
20
21
  Classifier: Topic :: Software Development :: Libraries :: Python Modules
21
22
  Requires-Python: >=3.11
22
23
  Provides-Extra: search
23
24
  Requires-Dist: cairosvg>=2.7.0; extra == 'search'
24
- Requires-Dist: fastembed>=0.4.0; extra == 'search'
25
+ Requires-Dist: candle-embed>=0.1.0; extra == 'search'
25
26
  Description-Content-Type: text/markdown
26
27
 
27
28
  # python-lucide
@@ -56,20 +57,8 @@ pip install python-lucide
56
57
  ```
57
58
  This installs the package with a pre-built database of all Lucide icons, ready to use immediately.
58
59
 
59
- Python 3.11–3.14 are supported. **Python 3.15 support is experimental:** core
60
- rendering, aliases, and SQL-backed package builds pass tests on 3.15 RC2 and have
61
- a dedicated CI job, but semantic search is currently unsupported because ONNX
62
- Runtime does not yet provide compatible wheels. Core installation remains
63
- available on 3.15; full support will be advertised once search is validated too.
64
- Use Python 3.11–3.14 for search and full development tooling. HDBSCAN and UMAP's
65
- dependencies affect cluster generation during development, not ordinary searches.
66
-
67
- To run the core tests on Python 3.15 from a source checkout:
68
-
69
- ```bash
70
- uv sync --python 3.15 --no-dev --group test-core
71
- uv run --no-sync python -m pytest tests/core_test.py tests/db_source_test.py
72
- ```
60
+ Python 3.11–3.15 are supported, including semantic search (`python-lucide[search]`)
61
+ and full development/clustering tooling.
73
62
 
74
63
  ## Quick Start
75
64
  ```python
@@ -165,16 +154,6 @@ pip install "python-lucide[search]"
165
154
  lucide search "celebrate a big achievement"
166
155
  ```
167
156
 
168
- If your application uses Python 3.15, run the search CLI separately under Python
169
- 3.14, or use the [browser search](https://mmacpherson.github.io/python-lucide/):
170
-
171
- ```bash
172
- uvx --python 3.14 --from "python-lucide[search]" lucide search "payment"
173
- ```
174
-
175
- This runs the CLI in a separate environment; calling `search_icons()` from your
176
- application still requires a supported Python version with the search extra.
177
-
178
157
  <img src="https://raw.githubusercontent.com/mmacpherson/python-lucide/main/.github/images/search-cli.png" width="360" alt="Terminal output of lucide search: each result icon renders inline next to its name and match score">
179
158
 
180
159
  In terminals supporting the Kitty graphics protocol (kitty, Ghostty,
@@ -30,20 +30,8 @@ pip install python-lucide
30
30
  ```
31
31
  This installs the package with a pre-built database of all Lucide icons, ready to use immediately.
32
32
 
33
- Python 3.11–3.14 are supported. **Python 3.15 support is experimental:** core
34
- rendering, aliases, and SQL-backed package builds pass tests on 3.15 RC2 and have
35
- a dedicated CI job, but semantic search is currently unsupported because ONNX
36
- Runtime does not yet provide compatible wheels. Core installation remains
37
- available on 3.15; full support will be advertised once search is validated too.
38
- Use Python 3.11–3.14 for search and full development tooling. HDBSCAN and UMAP's
39
- dependencies affect cluster generation during development, not ordinary searches.
40
-
41
- To run the core tests on Python 3.15 from a source checkout:
42
-
43
- ```bash
44
- uv sync --python 3.15 --no-dev --group test-core
45
- uv run --no-sync python -m pytest tests/core_test.py tests/db_source_test.py
46
- ```
33
+ Python 3.11–3.15 are supported, including semantic search (`python-lucide[search]`)
34
+ and full development/clustering tooling.
47
35
 
48
36
  ## Quick Start
49
37
  ```python
@@ -139,16 +127,6 @@ pip install "python-lucide[search]"
139
127
  lucide search "celebrate a big achievement"
140
128
  ```
141
129
 
142
- If your application uses Python 3.15, run the search CLI separately under Python
143
- 3.14, or use the [browser search](https://mmacpherson.github.io/python-lucide/):
144
-
145
- ```bash
146
- uvx --python 3.14 --from "python-lucide[search]" lucide search "payment"
147
- ```
148
-
149
- This runs the CLI in a separate environment; calling `search_icons()` from your
150
- application still requires a supported Python version with the search extra.
151
-
152
130
  <img src="https://raw.githubusercontent.com/mmacpherson/python-lucide/main/.github/images/search-cli.png" width="360" alt="Terminal output of lucide search: each result icon renders inline next to its name and match score">
153
131
 
154
132
  In terminals supporting the Kitty graphics protocol (kitty, Ghostty,
@@ -6,22 +6,16 @@ requires = ["hatchling>=1.27,<2"]
6
6
  dev = [
7
7
  { include-group = "test-core" },
8
8
  "cairosvg>=2.7.0",
9
- "fastembed>=0.4.0",
10
- "hdbscan>=0.8.0",
9
+ "candle-embed>=0.1.0",
11
10
  "mypy-extensions>=1.0.0",
12
11
  "mypy>=1.0.0",
13
- # Floor keeps the resolver off ancient numba/llvmlite, which fail to build
14
- # from source when numpy resolves above modern numba's cap.
15
- "numba>=0.60",
16
12
  "plotly>=5.0.0",
17
13
  "pre-commit>=3.0.0",
18
- # Cap below 2: pydantic-ai v2 removed Agent(output_retries=...), which
19
- # build_clusters.py relies on. Lift the cap when migrating to the v2 API.
20
- "pydantic-ai-slim[google]>=1.0.0,<2",
14
+ "pydantic-ai-slim[google]>=1.0.0",
15
+ "raso>=0.2.0",
21
16
  "ruff>=0.1.0",
22
17
  "types-setuptools>=80.9.0.20250529",
23
- "typing-extensions>=4.1.0",
24
- "umap-learn>=0.5.0"
18
+ "typing-extensions>=4.1.0"
25
19
  ]
26
20
  test-core = ["pytest-cov>=4.0.0", "pytest>=7.0.0"]
27
21
 
@@ -36,6 +30,7 @@ classifiers = [
36
30
  "Programming Language :: Python :: 3.12",
37
31
  "Programming Language :: Python :: 3.13",
38
32
  "Programming Language :: Python :: 3.14",
33
+ "Programming Language :: Python :: 3.15",
39
34
  "Topic :: Software Development :: Libraries :: Python Modules"
40
35
  ]
41
36
  dependencies = []
@@ -45,10 +40,10 @@ license = { text = "MIT" }
45
40
  name = "python-lucide"
46
41
  readme = "README.md"
47
42
  requires-python = ">=3.11"
48
- version = "0.5.14"
43
+ version = "0.5.15"
49
44
 
50
45
  [project.optional-dependencies]
51
- search = ["cairosvg>=2.7.0", "fastembed>=0.4.0"]
46
+ search = ["cairosvg>=2.7.0", "candle-embed>=0.1.0"]
52
47
 
53
48
  [project.scripts]
54
49
  check-lucide-version = "lucide.dev_utils:print_version_status"
@@ -160,8 +155,3 @@ convention = "google"
160
155
  [tool.uv]
161
156
  # SQL edits must invalidate uv's cached editable build too.
162
157
  cache-keys = [{ file = "pyproject.toml" }, { file = "hatch_build.py" }, { file = "build_support.py" }, { file = "src/lucide/data/lucide-icons.sql" }]
163
- # fastembed (search extra) caps pillow below 13, but every pillow before 13.0.0
164
- # has critical advisories (GHSA-8g5g-8vmr-9782, GHSA-332p-7hrc-92wf,
165
- # GHSA-w889-685w-c8fh). Override it for development and CI; this doesn't change
166
- # what users install. Remove once fastembed allows pillow 13.
167
- override-dependencies = ["pillow>=13"]
@@ -4,7 +4,12 @@ This package provides utilities for creating, accessing, and using Lucide
4
4
  icons from a SQLite database.
5
5
  """
6
6
 
7
- __version__ = "0.1.0"
7
+ from importlib.metadata import PackageNotFoundError, version
8
+
9
+ try:
10
+ __version__ = version("python-lucide")
11
+ except PackageNotFoundError: # pragma: no cover -- uninstalled source checkout
12
+ __version__ = "0.0.0+unknown"
8
13
 
9
14
  from .core import create_placeholder_svg, get_icon_list, lucide_icon
10
15
  from .db import get_db_connection, get_default_db_path
@@ -4,8 +4,8 @@ Uses UMAP for dimensionality reduction, HDBSCAN for density-based
4
4
  clustering, and Gemini Flash to generate evocative theme names from
5
5
  the icon names in each cluster.
6
6
 
7
- Build-time only — requires ``umap-learn``, ``hdbscan``, and ``plotly``
8
- (all in the dev dependency group).
7
+ Build-time only — requires ``raso`` and ``plotly`` (both in the dev
8
+ dependency group).
9
9
  """
10
10
 
11
11
  import json
@@ -20,6 +20,7 @@ from pydantic_ai import Agent
20
20
  from pydantic_ai.models import Model
21
21
 
22
22
  from .config import DEFAULT_SEARCH_MODEL_ID
23
+ from .db import sqlite_ro_uri
23
24
 
24
25
  logger = logging.getLogger(__name__)
25
26
 
@@ -92,10 +93,9 @@ def discover_clusters(
92
93
  Dict with keys: clusters, coords, descriptions.
93
94
  """
94
95
  import numpy as np # noqa: PLC0415
95
- import umap # noqa: PLC0415
96
- from hdbscan import HDBSCAN # noqa: PLC0415
96
+ from raso import HDBSCAN, UMAP # noqa: PLC0415
97
97
 
98
- conn = sqlite3.connect(f"file:{search_db_path}?mode=ro", uri=True)
98
+ conn = sqlite3.connect(sqlite_ro_uri(search_db_path), uri=True)
99
99
  rows = conn.execute(
100
100
  "SELECT e.name, e.embedding, d.description "
101
101
  "FROM icon_embeddings e "
@@ -112,7 +112,7 @@ def discover_clusters(
112
112
  logger.info("Loaded %d embeddings (%dd)", len(names), matrix.shape[1])
113
113
 
114
114
  logger.info("Running UMAP (2D projection)...")
115
- reducer = umap.UMAP(
115
+ reducer = UMAP(
116
116
  n_components=2,
117
117
  n_neighbors=15,
118
118
  min_dist=0.1,
@@ -191,7 +191,7 @@ def name_clusters(
191
191
  model,
192
192
  output_type=ClusterTheme,
193
193
  instructions=NAMING_INSTRUCTIONS,
194
- output_retries=3,
194
+ retries=3,
195
195
  )
196
196
 
197
197
  clusters = data["clusters"]
@@ -34,6 +34,7 @@ from .config import (
34
34
  EMBEDDING_MODELS,
35
35
  SEARCH_DB_SCHEMA_VERSION,
36
36
  )
37
+ from .db import sqlite_ro_uri
37
38
 
38
39
  logger = logging.getLogger(__name__)
39
40
 
@@ -359,7 +360,7 @@ def generate_descriptions( # noqa: PLR0913, PLR0915
359
360
  )
360
361
 
361
362
  # Read version and icon names from the main DB
362
- main_conn = sqlite3.connect(f"file:{main_db_path}?mode=ro", uri=True)
363
+ main_conn = sqlite3.connect(sqlite_ro_uri(main_db_path), uri=True)
363
364
  try:
364
365
  all_names = [
365
366
  row[0]
@@ -404,7 +405,7 @@ def generate_descriptions( # noqa: PLR0913, PLR0915
404
405
  logger.info("Generating descriptions for %d icons", len(names))
405
406
 
406
407
  # Read SVG content from the main DB
407
- main_conn = sqlite3.connect(f"file:{main_db_path}?mode=ro", uri=True)
408
+ main_conn = sqlite3.connect(sqlite_ro_uri(main_db_path), uri=True)
408
409
  svgs: dict[str, str] = {}
409
410
  try:
410
411
  for name in names:
@@ -663,10 +664,10 @@ def build_search_db(
663
664
  verbose: Verbose logging.
664
665
  """
665
666
  try:
666
- from fastembed import TextEmbedding # noqa: PLC0415
667
+ from candle_embed import TextEmbedding # noqa: PLC0415
667
668
  except ImportError:
668
669
  raise ImportError(
669
- "fastembed is required to build the search database. "
670
+ "candle-embed is required to build the search database. "
670
671
  "Install with: pip install 'python-lucide[search]'"
671
672
  ) from None
672
673
 
@@ -710,7 +711,10 @@ def build_search_db(
710
711
  embeddings: dict[str, dict[str, object]] = {}
711
712
  for model_id, model_cfg in EMBEDDING_MODELS.items():
712
713
  texts = [f"{model_cfg.document_prefix}{t}" for t in base_texts]
713
- embedder = TextEmbedding(model_name=model_cfg.fastembed_model)
714
+ embedder = TextEmbedding(
715
+ model_name=model_cfg.fastembed_model,
716
+ pooling=model_cfg.pooling,
717
+ )
714
718
  vecs = list(embedder.embed(texts))
715
719
  embeddings[model_id] = dict(zip(ordered_names, vecs, strict=True))
716
720
  logger.info(
@@ -541,30 +541,19 @@ def _cmd_build_search(args: argparse.Namespace) -> int:
541
541
  def _first_run_downloads(model: str) -> list[str]:
542
542
  """Human-readable one-time downloads the next search will trigger.
543
543
 
544
- Best-effort: peeks at fastembed's model cache and the search-DB cache;
544
+ Best-effort: peeks at candle-embed's model cache and the search-DB cache;
545
545
  any surprise in their layout just means the notice is skipped.
546
546
  """
547
547
  from .search import search_available # noqa: PLC0415
548
548
 
549
549
  pending = []
550
550
  try:
551
- from fastembed import TextEmbedding # noqa: PLC0415
552
- from fastembed.common.utils import define_cache_dir # noqa: PLC0415
553
-
554
- fastembed_name = EMBEDDING_MODELS[model].fastembed_model
555
- meta = next(
556
- m
557
- for m in TextEmbedding.list_supported_models()
558
- if m["model"] == fastembed_name
559
- )
560
- hf_repo = (meta.get("sources") or {}).get("hf") or ""
561
- size_mb = round(meta["size_in_GB"] * 1000)
562
- model_dir = (
563
- pathlib.Path(define_cache_dir(None))
564
- / f"models--{hf_repo.replace('/', '--')}"
565
- )
566
- if hf_repo and not model_dir.exists():
567
- pending.append(f"embedding model (~{size_mb} MB)")
551
+ from candle_embed import _cache_root, _safe_cache_dir # noqa: PLC0415
552
+
553
+ model_repo = EMBEDDING_MODELS[model].fastembed_model
554
+ model_dir = _safe_cache_dir(_cache_root(), model_repo, "main")
555
+ if not (model_dir / "model.safetensors").exists():
556
+ pending.append("embedding model")
568
557
  except Exception:
569
558
  pass
570
559
  if not search_available():
@@ -809,8 +798,7 @@ def _cmd_version(_args: argparse.Namespace) -> int:
809
798
  """Handle ``lucide version``."""
810
799
  from .dev_utils import print_version_status # noqa: PLC0415
811
800
 
812
- print_version_status()
813
- return 0
801
+ return print_version_status()
814
802
 
815
803
 
816
804
  def _resolve_icons_db(
@@ -4,6 +4,7 @@ This module contains default configuration values used throughout the package.
4
4
  """
5
5
 
6
6
  from dataclasses import dataclass
7
+ from typing import Literal
7
8
 
8
9
  # Default Lucide tag to use when building the icon database
9
10
  DEFAULT_LUCIDE_TAG = "1.84.0"
@@ -48,7 +49,7 @@ class EmbeddingModelConfig:
48
49
  dim: int
49
50
  fastembed_model: str = ""
50
51
  web_model: str = ""
51
- pooling: str = "mean"
52
+ pooling: Literal["mean", "cls"] = "mean"
52
53
  web_dtype: str = "fp32"
53
54
  query_prefix: str = ""
54
55
  document_prefix: str = ""
@@ -10,6 +10,7 @@ import logging
10
10
  import sqlite3
11
11
  import warnings
12
12
  import xml.etree.ElementTree as ET
13
+ from xml.sax.saxutils import escape as xml_escape
13
14
 
14
15
  from .config import DEFAULT_ICON_CACHE_SIZE
15
16
  from .db import get_db_connection, get_default_db_path
@@ -258,6 +259,22 @@ def lucide_icon( # noqa: PLR0917 -- public API; positional arguments are suppor
258
259
  return create_placeholder_svg(icon_name, fallback_text, f"Error: {e}")
259
260
 
260
261
 
262
+ def _escape_xml_attr(value: str) -> str:
263
+ """Escape a string for safe inclusion inside a double-quoted XML attribute."""
264
+ return xml_escape(value, {'"': "&quot;", "'": "&apos;"})
265
+
266
+
267
+ def _escape_xml_comment(text: str) -> str:
268
+ """Sanitize text for safe inclusion inside an XML ``<!-- ... -->`` comment."""
269
+ # XML 1.0 forbids '--' anywhere inside a comment and a trailing '-' before '-->'.
270
+ sanitized = text
271
+ while "--" in sanitized:
272
+ sanitized = sanitized.replace("--", "- -")
273
+ if sanitized.endswith("-"):
274
+ sanitized += " "
275
+ return sanitized
276
+
277
+
261
278
  def create_placeholder_svg(
262
279
  icon_name: str,
263
280
  fallback_text: str | None = None,
@@ -273,20 +290,20 @@ def create_placeholder_svg(
273
290
  Returns:
274
291
  A string containing an SVG placeholder.
275
292
  """
276
- display_text = fallback_text if fallback_text is not None else icon_name
277
- comment = (
278
- f"<!-- {error_text} -->"
279
- if error_text
280
- else f"<!-- Icon '{icon_name}' not found -->"
293
+ display_text = xml_escape(fallback_text if fallback_text is not None else icon_name)
294
+ safe_icon_attr = _escape_xml_attr(icon_name)
295
+ comment_body = _escape_xml_comment(
296
+ error_text if error_text else f"Icon '{icon_name}' not found"
281
297
  )
298
+ comment = f"<!-- {comment_body} -->"
282
299
 
283
300
  # Using a more robust SVG structure for the placeholder
284
301
  # Ensures it's also parsable by ElementTree for consistency in testing if needed
285
302
  return f"""{comment}
286
303
  <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24"
287
304
  fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"
288
- stroke-linejoin="round" class="lucide lucide-{icon_name} lucide-placeholder"
289
- data-missing-icon="{icon_name}">
305
+ stroke-linejoin="round" class="lucide lucide-{safe_icon_attr} lucide-placeholder"
306
+ data-missing-icon="{safe_icon_attr}">
290
307
  <rect x="3" y="3" width="18" height="18" rx="2" ry="2"></rect>
291
308
  <text x="12" y="14" text-anchor="middle" font-size="8"
292
309
  font-family="sans-serif" fill="currentColor">{display_text}</text>
@@ -31,8 +31,8 @@ def get_default_db_path() -> pathlib.Path | None:
31
31
  """Determines the default path for the Lucide icons database.
32
32
 
33
33
  The function looks for the database in the following locations (in order):
34
- 1. The path specified in the LUCIDE_PY_DB_PATH environment variable
35
- 2. In the package data directory (if installed with the 'db' extra)
34
+ 1. The path specified in the LUCIDE_DB_PATH environment variable
35
+ 2. In the package data directory
36
36
  3. In the current working directory
37
37
 
38
38
  Returns:
@@ -57,6 +57,11 @@ def get_default_db_path() -> pathlib.Path | None:
57
57
  return pathlib.Path.cwd() / "lucide-icons.db"
58
58
 
59
59
 
60
+ def sqlite_ro_uri(db_path: pathlib.Path | str) -> str:
61
+ """Build a read-only SQLite file URI that safely encodes path characters."""
62
+ return f"{pathlib.Path(db_path).resolve().as_uri()}?mode=ro"
63
+
64
+
60
65
  @contextlib.contextmanager
61
66
  def get_db_connection(
62
67
  db_path: pathlib.Path | str | None = None,
@@ -92,8 +97,7 @@ def get_db_connection(
92
97
  return
93
98
 
94
99
  # Read-only connection
95
- uri = f"file:{db_path}?mode=ro"
96
- conn = sqlite3.connect(uri, uri=True)
100
+ conn = sqlite3.connect(sqlite_ro_uri(db_path), uri=True)
97
101
  yield conn
98
102
  except sqlite3.Error as e:
99
103
  logger.error(f"Database connection error: {e}")
@@ -10,7 +10,7 @@ from datetime import datetime
10
10
  from typing import NamedTuple
11
11
 
12
12
  from .config import DEFAULT_LUCIDE_TAG
13
- from .db import get_default_db_path
13
+ from .db import get_default_db_path, sqlite_ro_uri
14
14
 
15
15
 
16
16
  class VersionStatus(NamedTuple):
@@ -53,7 +53,7 @@ def get_database_metadata() -> tuple[str | None, datetime | None]:
53
53
  return None, None
54
54
 
55
55
  try:
56
- with sqlite3.connect(f"file:{db_path}?mode=ro", uri=True) as conn:
56
+ with sqlite3.connect(sqlite_ro_uri(db_path), uri=True) as conn:
57
57
  cursor = conn.cursor()
58
58
 
59
59
  # Check if metadata table exists
@@ -251,7 +251,7 @@ def get_icon_count_from_db(db_path: pathlib.Path | str | None = None) -> int:
251
251
  return 0
252
252
 
253
253
  try:
254
- with sqlite3.connect(f"file:{db_path}?mode=ro", uri=True) as conn:
254
+ with sqlite3.connect(sqlite_ro_uri(db_path), uri=True) as conn:
255
255
  cursor = conn.cursor()
256
256
  cursor.execute("SELECT COUNT(*) FROM icons")
257
257
  result = cursor.fetchone()
File without changes
@@ -10,7 +10,9 @@ Requires the ``search`` extra: ``pip install 'python-lucide[search]'``
10
10
  import logging
11
11
  import os
12
12
  import pathlib
13
+ import shutil
13
14
  import sqlite3
15
+ import tempfile
14
16
  import urllib.request
15
17
  from typing import Any, NamedTuple
16
18
 
@@ -21,7 +23,9 @@ from .config import (
21
23
  SEARCH_DB_SCHEMA_VERSION,
22
24
  SEARCH_DB_URL_TEMPLATE,
23
25
  )
24
- from .db import get_db_connection
26
+ from .db import get_db_connection, sqlite_ro_uri
27
+
28
+ SEARCH_DB_DOWNLOAD_TIMEOUT = 60.0
25
29
 
26
30
  logger = logging.getLogger(__name__)
27
31
 
@@ -46,7 +50,7 @@ class SearchResult(NamedTuple):
46
50
  def _check_search_deps() -> None:
47
51
  """Raise a clear error if the search extra is not installed."""
48
52
  try:
49
- import fastembed # noqa: F401, PLC0415
53
+ import candle_embed # noqa: F401, PLC0415
50
54
  except ImportError:
51
55
  raise ImportError(
52
56
  "Semantic search requires the 'search' extra. "
@@ -87,8 +91,7 @@ def _read_schema_version(path: pathlib.Path) -> int:
87
91
  schema 2) and 0 for files that cannot be read as a search DB at all.
88
92
  """
89
93
  try:
90
- uri = f"file:{path}?mode=ro"
91
- conn = sqlite3.connect(uri, uri=True)
94
+ conn = sqlite3.connect(sqlite_ro_uri(path), uri=True)
92
95
  try:
93
96
  cursor = conn.cursor()
94
97
  cursor.execute("SELECT value FROM metadata WHERE key = 'schema_version'")
@@ -100,6 +103,43 @@ def _read_schema_version(path: pathlib.Path) -> int:
100
103
  return 0
101
104
 
102
105
 
106
+ def _download_search_db(url: str, dest: pathlib.Path) -> None:
107
+ """Download, validate, and atomically move a search database into place."""
108
+ with tempfile.NamedTemporaryFile(
109
+ dir=dest.parent,
110
+ prefix=f".{dest.name}.",
111
+ suffix=".tmp",
112
+ delete=False,
113
+ ) as tmp:
114
+ tmp_path = pathlib.Path(tmp.name)
115
+ try:
116
+ try:
117
+ with (
118
+ urllib.request.urlopen(url, timeout=SEARCH_DB_DOWNLOAD_TIMEOUT) as resp,
119
+ open(tmp_path, "wb") as out,
120
+ ):
121
+ shutil.copyfileobj(resp, out)
122
+ except Exception as e:
123
+ raise SearchNotAvailableError(
124
+ f"Failed to download search database: {e}\n"
125
+ f"URL: {url}\n"
126
+ "Build search data locally with: lucide build-search"
127
+ ) from e
128
+
129
+ downloaded_schema = _read_schema_version(tmp_path)
130
+ if downloaded_schema != SEARCH_DB_SCHEMA_VERSION:
131
+ raise SearchNotAvailableError(
132
+ f"Downloaded search database has schema {downloaded_schema}, "
133
+ f"but this version of python-lucide requires "
134
+ f"{SEARCH_DB_SCHEMA_VERSION}. The published search data may "
135
+ "not match this package version yet.\n"
136
+ "Build search data locally with: lucide build-search"
137
+ )
138
+ tmp_path.replace(dest)
139
+ finally:
140
+ tmp_path.unlink(missing_ok=True)
141
+
142
+
103
143
  def _resolve_search_db(*, allow_download: bool = False) -> pathlib.Path | None:
104
144
  """Locate the search database file.
105
145
 
@@ -139,26 +179,7 @@ def _resolve_search_db(*, allow_download: bool = False) -> pathlib.Path | None:
139
179
  if allow_download:
140
180
  url = SEARCH_DB_URL_TEMPLATE.format(version=version)
141
181
  logger.info("Downloading search database from %s", url)
142
- try:
143
- urllib.request.urlretrieve(url, cached)
144
- except Exception as e:
145
- if cached.exists():
146
- cached.unlink()
147
- raise SearchNotAvailableError(
148
- f"Failed to download search database: {e}\n"
149
- f"URL: {url}\n"
150
- "Build search data locally with: lucide build-search"
151
- ) from e
152
- downloaded_schema = _read_schema_version(cached)
153
- if downloaded_schema != SEARCH_DB_SCHEMA_VERSION:
154
- cached.unlink()
155
- raise SearchNotAvailableError(
156
- f"Downloaded search database has schema {downloaded_schema}, "
157
- f"but this version of python-lucide requires "
158
- f"{SEARCH_DB_SCHEMA_VERSION}. The published search data may "
159
- "not match this package version yet.\n"
160
- "Build search data locally with: lucide build-search"
161
- )
182
+ _download_search_db(url, cached)
162
183
  return cached
163
184
 
164
185
  return None
@@ -183,18 +204,16 @@ def _resolve_model(model: str) -> str:
183
204
 
184
205
 
185
206
  def _get_embedder(model: str) -> Any:
186
- """Return a cached fastembed TextEmbedding instance for *model*."""
207
+ """Return a cached candle-embed TextEmbedding instance for *model*."""
187
208
  if model not in _embedder_instances:
188
209
  _check_search_deps()
189
- import warnings # noqa: PLC0415
190
-
191
- from fastembed import TextEmbedding # noqa: PLC0415
210
+ from candle_embed import TextEmbedding # noqa: PLC0415
192
211
 
193
- with warnings.catch_warnings():
194
- warnings.simplefilter("ignore", UserWarning)
195
- _embedder_instances[model] = TextEmbedding(
196
- model_name=EMBEDDING_MODELS[model].fastembed_model
197
- )
212
+ cfg = EMBEDDING_MODELS[model]
213
+ _embedder_instances[model] = TextEmbedding(
214
+ model_name=cfg.fastembed_model,
215
+ pooling=cfg.pooling,
216
+ )
198
217
  return _embedder_instances[model]
199
218
 
200
219
 
@@ -227,8 +246,7 @@ def _load_search_index(model: str) -> dict[str, Any]:
227
246
  "Build search data locally with: lucide build-search"
228
247
  )
229
248
 
230
- uri = f"file:{db_path}?mode=ro"
231
- conn = sqlite3.connect(uri, uri=True)
249
+ conn = sqlite3.connect(sqlite_ro_uri(db_path), uri=True)
232
250
  try:
233
251
  cursor = conn.cursor()
234
252
  cursor.execute(
@@ -340,8 +358,7 @@ def get_icon_description(icon_name: str) -> str | None:
340
358
  return None
341
359
 
342
360
  try:
343
- uri = f"file:{db_path}?mode=ro"
344
- conn = sqlite3.connect(uri, uri=True)
361
+ conn = sqlite3.connect(sqlite_ro_uri(db_path), uri=True)
345
362
  try:
346
363
  cursor = conn.cursor()
347
364
  cursor.execute(
@@ -367,8 +384,7 @@ def search_available() -> bool:
367
384
  return False
368
385
 
369
386
  try:
370
- uri = f"file:{db_path}?mode=ro"
371
- conn = sqlite3.connect(uri, uri=True)
387
+ conn = sqlite3.connect(sqlite_ro_uri(db_path), uri=True)
372
388
  try:
373
389
  cursor = conn.cursor()
374
390
  cursor.execute("SELECT COUNT(*) FROM icon_embeddings")
@@ -2,12 +2,20 @@
2
2
 
3
3
  import json
4
4
  import pathlib
5
+ import sqlite3
5
6
 
7
+ import numpy as np
6
8
  from pydantic_ai.messages import ModelMessage, ModelResponse, TextPart, ToolCallPart
7
9
  from pydantic_ai.models.function import AgentInfo, FunctionModel
8
10
  from pydantic_ai.models.test import TestModel
9
11
 
10
- from lucide.build_clusters import MAX_THEME_LENGTH, _sanitize_theme, name_clusters
12
+ from lucide.build_clusters import (
13
+ MAX_THEME_LENGTH,
14
+ _sanitize_theme,
15
+ discover_clusters,
16
+ name_clusters,
17
+ )
18
+ from lucide.config import DEFAULT_SEARCH_MODEL_ID
11
19
 
12
20
  CLUSTERS_JSON = (
13
21
  pathlib.Path(__file__).parent.parent
@@ -105,3 +113,40 @@ class TestShippedClusterData:
105
113
  if "\n" in cluster["theme"] or len(cluster["theme"]) > MAX_THEME_LENGTH
106
114
  }
107
115
  assert not offenders, f"Clusters with leaked/invalid themes: {offenders}"
116
+
117
+
118
+ class TestDiscoverClusters:
119
+ def test_discovers_clusters_with_raso(self, tmp_path):
120
+ db_path = tmp_path / "search.db"
121
+ rng = np.random.default_rng(0)
122
+ centers = [
123
+ np.array([1.0, 0.0, 0.0, 0.0], dtype=np.float32),
124
+ np.array([0.0, 1.0, 0.0, 0.0], dtype=np.float32),
125
+ ]
126
+ conn = sqlite3.connect(db_path)
127
+ conn.execute(
128
+ "CREATE TABLE icon_embeddings (name TEXT, model TEXT, embedding BLOB)"
129
+ )
130
+ conn.execute("CREATE TABLE icon_descriptions (name TEXT, description TEXT)")
131
+ for group_idx, center in enumerate(centers):
132
+ for i in range(12):
133
+ name = f"icon-{group_idx}-{i:02d}"
134
+ vec = (center + rng.normal(0.0, 0.02, size=4)).astype(np.float32)
135
+ conn.execute(
136
+ "INSERT INTO icon_embeddings VALUES (?, ?, ?)",
137
+ (name, DEFAULT_SEARCH_MODEL_ID, vec.tobytes()),
138
+ )
139
+ conn.execute(
140
+ "INSERT INTO icon_descriptions VALUES (?, ?)",
141
+ (name, f"Description for {name}"),
142
+ )
143
+ conn.commit()
144
+ conn.close()
145
+
146
+ result = discover_clusters(db_path, min_cluster_size=5)
147
+
148
+ assert len(result["coords"]) == 24
149
+ assert len(result["descriptions"]) == 24
150
+ real_clusters = {k: v for k, v in result["clusters"].items() if k != "-1"}
151
+ assert len(real_clusters) >= 1
152
+ assert sum(len(v["icons"]) for v in result["clusters"].values()) == 24
@@ -3,7 +3,7 @@
3
3
  import json
4
4
  import sqlite3
5
5
 
6
- import fastembed
6
+ import candle_embed
7
7
  import numpy as np
8
8
  import pytest
9
9
 
@@ -281,8 +281,8 @@ class _FakeTextEmbedding:
281
281
 
282
282
  @pytest.fixture
283
283
  def fake_fastembed(monkeypatch):
284
- """Replace fastembed's TextEmbedding with the offline fake."""
285
- monkeypatch.setattr(fastembed, "TextEmbedding", _FakeTextEmbedding)
284
+ """Replace candle_embed's TextEmbedding with the offline fake."""
285
+ monkeypatch.setattr(candle_embed, "TextEmbedding", _FakeTextEmbedding)
286
286
  return _FakeTextEmbedding
287
287
 
288
288
 
@@ -200,7 +200,9 @@ class TestMainSubcommands:
200
200
  assert result == 0
201
201
 
202
202
  def test_version_subcommand(self):
203
- with mock.patch("lucide.dev_utils.print_version_status") as mock_version:
203
+ with mock.patch(
204
+ "lucide.dev_utils.print_version_status", return_value=0
205
+ ) as mock_version:
204
206
  with mock.patch("sys.argv", ["lucide", "version"]):
205
207
  result = cli.main()
206
208
  mock_version.assert_called_once()
@@ -254,7 +256,7 @@ class TestMainSubcommands:
254
256
  search._embedder_instances[DEFAULT_SEARCH_MODEL_ID] = FakeEmbedder()
255
257
  try:
256
258
  with (
257
- mock.patch.dict("sys.modules", {"fastembed": mock.MagicMock()}),
259
+ mock.patch.dict("sys.modules", {"candle_embed": mock.MagicMock()}),
258
260
  mock.patch(
259
261
  "sys.argv",
260
262
  ["lucide", "search", "love", "--search-db", str(search_db)],
@@ -388,3 +390,10 @@ class TestInlineIcons:
388
390
  show, tip = cli._graphics_support()
389
391
  assert show is False
390
392
  assert "cairo system library" in tip
393
+
394
+
395
+ @pytest.mark.parametrize("exit_code", [0, 1])
396
+ def test_cmd_version_propagates_exit_code(exit_code):
397
+ """`lucide version` should return the exit code from print_version_status()."""
398
+ with mock.patch("lucide.dev_utils.print_version_status", return_value=exit_code):
399
+ assert cli._cmd_version(mock.MagicMock()) == exit_code
@@ -21,4 +21,5 @@ def isolated_search_cache(tmp_path, monkeypatch):
21
21
  def _no_network(url, *_args, **_kwargs):
22
22
  raise AssertionError(f"unexpected download attempt: {url}")
23
23
 
24
+ monkeypatch.setattr(search.urllib.request, "urlopen", _no_network)
24
25
  monkeypatch.setattr(search.urllib.request, "urlretrieve", _no_network)
@@ -1,5 +1,7 @@
1
1
  # ruff: noqa: ARG001
2
2
  import contextlib
3
+ import importlib.metadata
4
+ import importlib.resources
3
5
  import re
4
6
  import sqlite3
5
7
  import warnings
@@ -9,6 +11,7 @@ from unittest import mock
9
11
 
10
12
  import pytest
11
13
 
14
+ import lucide
12
15
  from lucide import core, db # Import db to patch its members
13
16
  from lucide.config import DEFAULT_ICON_CACHE_SIZE
14
17
 
@@ -676,3 +679,57 @@ def test_lucide_icon_invalid_svg_from_db_fallback(mock_db_path_fixture):
676
679
  assert icon_str_with_class == malformed_svg, (
677
680
  "Should return original SVG on parse error with cls"
678
681
  )
682
+
683
+
684
+ def test_placeholder_svg_escapes_untrusted_inputs():
685
+ """Placeholder SVG must escape XML metacharacters in name, fallback, and error."""
686
+ malicious_name = 'x"><script>alert(1)</script><!-- --'
687
+ malicious_fallback = '<b>&"hi"</b>'
688
+ malicious_error = "bad -- error -"
689
+
690
+ svg = core.create_placeholder_svg(
691
+ malicious_name,
692
+ fallback_text=malicious_fallback,
693
+ error_text=malicious_error,
694
+ )
695
+
696
+ root = get_svg_root(svg)
697
+ assert root.get("data-missing-icon") == malicious_name
698
+ assert root.find(SVG_NAMESPACE + "script") is None
699
+ assert "<script>" not in svg
700
+ text_el = root.find(SVG_NAMESPACE + "text")
701
+ assert text_el is not None
702
+ assert text_el.text == malicious_fallback
703
+ # Verify XML comment syntax is valid (no '--' inside comment body)
704
+ comment_end = svg.index("-->")
705
+ comment_body = svg[4:comment_end]
706
+ assert "--" not in comment_body
707
+ assert not comment_body.endswith("-")
708
+
709
+
710
+ def test_get_db_connection_handles_special_uri_characters(tmp_path):
711
+ """Read-only SQLite URI encoding should handle paths containing ? and #."""
712
+ special_dir = tmp_path / "dir?with#chars"
713
+ special_dir.mkdir()
714
+ db_file = special_dir / "icons.db"
715
+ with contextlib.closing(sqlite3.connect(db_file)) as conn, conn:
716
+ conn.execute("CREATE TABLE icons (name TEXT PRIMARY KEY, svg TEXT NOT NULL)")
717
+ conn.execute(
718
+ "INSERT INTO icons VALUES (?, ?)",
719
+ ("dot", '<svg xmlns="http://www.w3.org/2000/svg"><circle r="1"/></svg>'),
720
+ )
721
+
722
+ with db.get_db_connection(db_file) as conn:
723
+ assert conn is not None
724
+ row = conn.execute("SELECT name FROM icons").fetchone()
725
+ assert row == ("dot",)
726
+
727
+
728
+ def test_package_version_matches_metadata():
729
+ """__version__ should stay in sync with installed package metadata."""
730
+ assert lucide.__version__ == importlib.metadata.version("python-lucide")
731
+
732
+
733
+ def test_py_typed_marker_present():
734
+ """PEP 561 py.typed marker should be packaged with lucide."""
735
+ assert importlib.resources.files("lucide").joinpath("py.typed").is_file()
@@ -1,5 +1,6 @@
1
1
  """Tests for the semantic search module."""
2
2
 
3
+ import io
3
4
  import sqlite3
4
5
  from unittest import mock
5
6
 
@@ -121,7 +122,7 @@ class TestSearchIcons:
121
122
  monkeypatch.setenv("LUCIDE_SEARCH_DB_PATH", str(db_path))
122
123
  monkeypatch.setattr(search, "_get_icons_version", lambda: "0.577.0")
123
124
 
124
- with mock.patch.dict("sys.modules", {"fastembed": mock.MagicMock()}):
125
+ with mock.patch.dict("sys.modules", {"candle_embed": mock.MagicMock()}):
125
126
  search._embedder_instances[DEFAULT_SEARCH_MODEL_ID] = FakeEmbedder()
126
127
 
127
128
  results = search.search_icons("love", limit=3)
@@ -138,7 +139,7 @@ class TestSearchIcons:
138
139
  monkeypatch.setenv("LUCIDE_SEARCH_DB_PATH", str(db_path))
139
140
  monkeypatch.setattr(search, "_get_icons_version", lambda: "0.577.0")
140
141
 
141
- with mock.patch.dict("sys.modules", {"fastembed": mock.MagicMock()}):
142
+ with mock.patch.dict("sys.modules", {"candle_embed": mock.MagicMock()}):
142
143
  search._embedder_instances[DEFAULT_SEARCH_MODEL_ID] = FakeEmbedder()
143
144
 
144
145
  results = search.search_icons("test", limit=1)
@@ -151,7 +152,7 @@ class TestSearchIcons:
151
152
  monkeypatch.setenv("LUCIDE_SEARCH_DB_PATH", str(db_path))
152
153
  monkeypatch.setattr(search, "_get_icons_version", lambda: "0.577.0")
153
154
 
154
- with mock.patch.dict("sys.modules", {"fastembed": mock.MagicMock()}):
155
+ with mock.patch.dict("sys.modules", {"candle_embed": mock.MagicMock()}):
155
156
  search._embedder_instances[DEFAULT_SEARCH_MODEL_ID] = FakeEmbedder()
156
157
 
157
158
  # Very high threshold should exclude most results
@@ -165,7 +166,7 @@ class TestSearchIcons:
165
166
  monkeypatch.setenv("LUCIDE_SEARCH_DB_PATH", str(db_path))
166
167
  monkeypatch.setattr(search, "_get_icons_version", lambda: "0.577.0")
167
168
 
168
- with mock.patch.dict("sys.modules", {"fastembed": mock.MagicMock()}):
169
+ with mock.patch.dict("sys.modules", {"candle_embed": mock.MagicMock()}):
169
170
  search._embedder_instances[DEFAULT_SEARCH_MODEL_ID] = FakeEmbedder()
170
171
 
171
172
  results = search.search_icons("heart", limit=3)
@@ -234,20 +235,22 @@ class TestSearchNotAvailableError:
234
235
  with (
235
236
  mock.patch.object(
236
237
  search.urllib.request,
237
- "urlretrieve",
238
+ "urlopen",
238
239
  side_effect=Exception("404"),
239
240
  ),
240
- mock.patch.dict("sys.modules", {"fastembed": mock.MagicMock()}),
241
+ mock.patch.dict("sys.modules", {"candle_embed": mock.MagicMock()}),
241
242
  ):
242
243
  search._embedder_instances[DEFAULT_SEARCH_MODEL_ID] = FakeEmbedder()
243
244
  with pytest.raises(search.SearchNotAvailableError):
244
245
  search.search_icons("test")
246
+ # No partial or temp files left in cache dir
247
+ assert list((tmp_path / "cache").iterdir()) == []
245
248
 
246
249
 
247
250
  class TestCheckSearchDeps:
248
251
  def test_import_error_message(self):
249
252
  with (
250
- mock.patch.dict("sys.modules", {"fastembed": None}),
253
+ mock.patch.dict("sys.modules", {"candle_embed": None}),
251
254
  pytest.raises(ImportError, match="python-lucide\\[search\\]"),
252
255
  ):
253
256
  search._check_search_deps()
@@ -336,21 +339,54 @@ class TestResolveSearchDb:
336
339
  monkeypatch.setattr(search, "_get_cache_dir", lambda: cache_dir)
337
340
  monkeypatch.setattr(search, "_get_icons_version", lambda: "0.577.0")
338
341
 
339
- def fake_urlretrieve(_url, dest):
340
- conn = sqlite3.connect(dest)
341
- conn.execute("CREATE TABLE metadata (key TEXT PRIMARY KEY, value TEXT)")
342
- conn.execute("INSERT INTO metadata VALUES ('version', '0.577.0')")
343
- conn.commit()
344
- conn.close()
342
+ v1_db = tmp_path / "v1.db"
343
+ conn = sqlite3.connect(v1_db)
344
+ conn.execute("CREATE TABLE metadata (key TEXT PRIMARY KEY, value TEXT)")
345
+ conn.execute("INSERT INTO metadata VALUES ('version', '0.577.0')")
346
+ conn.commit()
347
+ conn.close()
348
+ v1_bytes = v1_db.read_bytes()
349
+
350
+ def fake_urlopen(_url, *, timeout=None):
351
+ assert timeout == search.SEARCH_DB_DOWNLOAD_TIMEOUT
352
+ return io.BytesIO(v1_bytes)
345
353
 
346
354
  with (
347
355
  mock.patch.object(
348
- search.urllib.request, "urlretrieve", side_effect=fake_urlretrieve
356
+ search.urllib.request, "urlopen", side_effect=fake_urlopen
349
357
  ),
350
358
  pytest.raises(search.SearchNotAvailableError, match="schema"),
351
359
  ):
352
360
  search._resolve_search_db(allow_download=True)
353
361
  assert not (cache_dir / "lucide-search-0.577.0.db").exists()
362
+ assert list(cache_dir.iterdir()) == []
363
+
364
+ def test_valid_download_atomically_populates_cache(
365
+ self, search_db, tmp_path, monkeypatch
366
+ ):
367
+ db_path, _ = search_db
368
+ monkeypatch.delenv("LUCIDE_SEARCH_DB_PATH", raising=False)
369
+
370
+ cache_dir = tmp_path / "cache"
371
+ cache_dir.mkdir()
372
+ monkeypatch.setattr(search, "_get_cache_dir", lambda: cache_dir)
373
+ monkeypatch.setattr(search, "_get_icons_version", lambda: "0.577.0")
374
+
375
+ db_bytes = db_path.read_bytes()
376
+
377
+ def fake_urlopen(_url, *, timeout=None):
378
+ assert timeout == search.SEARCH_DB_DOWNLOAD_TIMEOUT
379
+ return io.BytesIO(db_bytes)
380
+
381
+ with mock.patch.object(
382
+ search.urllib.request, "urlopen", side_effect=fake_urlopen
383
+ ):
384
+ result = search._resolve_search_db(allow_download=True)
385
+
386
+ expected = cache_dir / "lucide-search-0.577.0.db"
387
+ assert result == expected
388
+ assert expected.exists()
389
+ assert list(cache_dir.iterdir()) == [expected]
354
390
 
355
391
 
356
392
  class TestModelSelection:
@@ -359,7 +395,7 @@ class TestModelSelection:
359
395
  monkeypatch.setenv("LUCIDE_SEARCH_DB_PATH", str(db_path))
360
396
 
361
397
  with (
362
- mock.patch.dict("sys.modules", {"fastembed": mock.MagicMock()}),
398
+ mock.patch.dict("sys.modules", {"candle_embed": mock.MagicMock()}),
363
399
  pytest.raises(ValueError, match="Unknown embedding model"),
364
400
  ):
365
401
  search.search_icons("test", model="not-a-model")
@@ -371,7 +407,7 @@ class TestModelSelection:
371
407
  monkeypatch.setenv("LUCIDE_SEARCH_DB_PATH", str(db_path))
372
408
  monkeypatch.setattr(search, "_get_icons_version", lambda: "0.577.0")
373
409
 
374
- with mock.patch.dict("sys.modules", {"fastembed": mock.MagicMock()}):
410
+ with mock.patch.dict("sys.modules", {"candle_embed": mock.MagicMock()}):
375
411
  search._embedder_instances[other] = FakeEmbedder()
376
412
  with pytest.raises(search.SearchNotAvailableError, match="no embeddings"):
377
413
  search.search_icons("test", model=other)
File without changes