mirror of
https://github.com/lancedb/lancedb.git
synced 2026-08-31 02:18:27 +00:00
Compare commits
1 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 72ac16ba76 |
@@ -3,7 +3,6 @@
|
||||
|
||||
|
||||
from typing import List
|
||||
from urllib.parse import unquote, urlparse
|
||||
|
||||
import numpy as np
|
||||
|
||||
@@ -126,20 +125,9 @@ class InstructorEmbeddingFunction(TextEmbeddingFunction):
|
||||
|
||||
@weak_lru(maxsize=1)
|
||||
def get_model(self):
|
||||
huggingface_hub = attempt_import_or_raise("huggingface_hub", "huggingface-hub")
|
||||
missing = object()
|
||||
original_cached_download = getattr(huggingface_hub, "cached_download", missing)
|
||||
if original_cached_download is missing:
|
||||
huggingface_hub.cached_download = _cached_download(huggingface_hub)
|
||||
|
||||
try:
|
||||
instructor_embedding = attempt_import_or_raise(
|
||||
"InstructorEmbedding", "InstructorEmbedding"
|
||||
)
|
||||
finally:
|
||||
if original_cached_download is missing:
|
||||
del huggingface_hub.cached_download
|
||||
|
||||
instructor_embedding = attempt_import_or_raise(
|
||||
"InstructorEmbedding", "InstructorEmbedding"
|
||||
)
|
||||
torch = attempt_import_or_raise("torch", "torch")
|
||||
|
||||
model = instructor_embedding.INSTRUCTOR(self.name)
|
||||
@@ -152,44 +140,3 @@ class InstructorEmbeddingFunction(TextEmbeddingFunction):
|
||||
model, {torch.nn.Linear}, dtype=torch.qint8
|
||||
)
|
||||
return model
|
||||
|
||||
|
||||
def _cached_download(huggingface_hub):
|
||||
"""Provide the legacy download API used by sentence-transformers 2.2.x."""
|
||||
|
||||
def cached_download(
|
||||
*,
|
||||
url,
|
||||
cache_dir=None,
|
||||
force_filename=None,
|
||||
library_name=None,
|
||||
library_version=None,
|
||||
user_agent=None,
|
||||
use_auth_token=None,
|
||||
**_,
|
||||
):
|
||||
path = urlparse(url).path.lstrip("/")
|
||||
try:
|
||||
repo_id, resolved_path = path.split("/resolve/", maxsplit=1)
|
||||
revision, filename = resolved_path.split("/", maxsplit=1)
|
||||
except ValueError as err:
|
||||
raise ValueError(f"Unsupported Hugging Face Hub URL: {url}") from err
|
||||
|
||||
repo_id = unquote(repo_id)
|
||||
revision = unquote(revision)
|
||||
filename = unquote(filename)
|
||||
# sentence-transformers derives force_filename from this Hub path with
|
||||
# os.path.join. Using the URL path beneath local_dir produces the same
|
||||
# local destination without sending Windows separators to the Hub.
|
||||
return huggingface_hub.hf_hub_download(
|
||||
repo_id=repo_id,
|
||||
filename=filename,
|
||||
revision=revision,
|
||||
local_dir=cache_dir,
|
||||
library_name=library_name,
|
||||
library_version=library_version,
|
||||
user_agent=user_agent,
|
||||
token=use_auth_token,
|
||||
)
|
||||
|
||||
return cached_download
|
||||
|
||||
@@ -1,11 +1,8 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright The LanceDB Authors
|
||||
|
||||
import ntpath
|
||||
import os
|
||||
import pickle
|
||||
import sys
|
||||
from types import ModuleType
|
||||
from typing import List, Optional, Union
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
@@ -525,59 +522,6 @@ def test_embedding_function_safe_model_dump(embedding_type):
|
||||
)
|
||||
|
||||
|
||||
def test_instructor_embedding_supports_huggingface_hub_without_cached_download(
|
||||
tmp_path, monkeypatch
|
||||
):
|
||||
from lancedb.embeddings.instructor import InstructorEmbeddingFunction
|
||||
|
||||
hub_download = MagicMock(return_value="/cache/1_Pooling/config.json")
|
||||
huggingface_hub = ModuleType("huggingface_hub")
|
||||
huggingface_hub.hf_hub_download = hub_download
|
||||
torch = ModuleType("torch")
|
||||
monkeypatch.setitem(sys.modules, "huggingface_hub", huggingface_hub)
|
||||
monkeypatch.setitem(sys.modules, "torch", torch)
|
||||
monkeypatch.delitem(sys.modules, "InstructorEmbedding", raising=False)
|
||||
monkeypatch.syspath_prepend(str(tmp_path))
|
||||
|
||||
(tmp_path / "InstructorEmbedding.py").write_text(
|
||||
"from huggingface_hub import cached_download\n\n"
|
||||
"class INSTRUCTOR:\n"
|
||||
" def __init__(self, name):\n"
|
||||
" self.name = name\n"
|
||||
)
|
||||
|
||||
embedding = InstructorEmbeddingFunction.create(show_progress_bar=False)
|
||||
instructor_model = embedding.get_model()
|
||||
|
||||
assert instructor_model.name == "hkunlp/instructor-base"
|
||||
assert not hasattr(huggingface_hub, "cached_download")
|
||||
|
||||
instructor_embedding = sys.modules["InstructorEmbedding"]
|
||||
path = instructor_embedding.cached_download(
|
||||
url=(
|
||||
"https://huggingface.co/hkunlp/instructor-base/resolve/abc123/"
|
||||
"1_Pooling/config.json"
|
||||
),
|
||||
cache_dir="/cache",
|
||||
force_filename=ntpath.join("1_Pooling", "config.json"),
|
||||
library_name="sentence-transformers",
|
||||
library_version="2.2.2",
|
||||
use_auth_token="token",
|
||||
)
|
||||
|
||||
assert path == "/cache/1_Pooling/config.json"
|
||||
hub_download.assert_called_once_with(
|
||||
repo_id="hkunlp/instructor-base",
|
||||
filename="1_Pooling/config.json",
|
||||
revision="abc123",
|
||||
local_dir="/cache",
|
||||
library_name="sentence-transformers",
|
||||
library_version="2.2.2",
|
||||
user_agent=None,
|
||||
token="token",
|
||||
)
|
||||
|
||||
|
||||
@patch("time.sleep")
|
||||
def test_retry(mock_sleep):
|
||||
test_function = MagicMock(side_effect=[Exception] * 9 + ["result"])
|
||||
|
||||
@@ -656,6 +656,7 @@ pub struct ConnectRequest {
|
||||
/// - `/path/to/database` - local database on file system.
|
||||
/// - `s3://bucket/path/to/database` or `gs://bucket/path/to/database` - database on cloud object store
|
||||
/// - `db://dbname` - LanceDB Cloud
|
||||
/// - `db://` with a host override - remote tables in the storage root
|
||||
pub uri: String,
|
||||
|
||||
#[cfg(feature = "remote")]
|
||||
@@ -768,6 +769,8 @@ impl ConnectBuilder {
|
||||
///
|
||||
/// This option is only used when connecting to LanceDB Cloud (db:// URIs)
|
||||
/// and will be ignored for other URIs.
|
||||
/// Use the URI `db://` together with a host override to connect to remote
|
||||
/// tables stored directly in the storage root.
|
||||
///
|
||||
/// # Arguments
|
||||
///
|
||||
@@ -1354,6 +1357,34 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "remote")]
|
||||
#[tokio::test]
|
||||
async fn test_connect_remote_storage_root() {
|
||||
let conn = ConnectBuilder::new("db://")
|
||||
.region("us-east-1")
|
||||
.api_key("my-api-key")
|
||||
.host_override("https://example.com")
|
||||
.execute()
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
let (impl_name, properties) = conn.namespace_client_config().await.unwrap();
|
||||
assert_eq!(impl_name, "rest");
|
||||
assert_eq!(properties["uri"], "https://example.com");
|
||||
assert_eq!(properties["header.x-lancedb-database"], "");
|
||||
|
||||
let result = ConnectBuilder::new("db://")
|
||||
.region("us-east-1")
|
||||
.api_key("my-api-key")
|
||||
.execute()
|
||||
.await;
|
||||
assert!(matches!(
|
||||
result,
|
||||
Err(Error::InvalidInput { message })
|
||||
if message.contains("A host override is required")
|
||||
));
|
||||
}
|
||||
|
||||
#[cfg(feature = "remote")]
|
||||
#[tokio::test]
|
||||
async fn test_connect_rejects_header_provider_with_oauth_config() {
|
||||
|
||||
@@ -54,6 +54,7 @@
|
||||
//! - `/path/to/database` - local database on file system.
|
||||
//! - `s3://bucket/path/to/database` or `gs://bucket/path/to/database` - database on cloud object store
|
||||
//! - `db://dbname` - Lance Cloud
|
||||
//! - `db://` with a host override - remote tables in the storage root
|
||||
//!
|
||||
//! You can also use [`ConnectBuilder`] to configure the connection to the database.
|
||||
//!
|
||||
|
||||
@@ -349,18 +349,22 @@ pub struct ParsedDbUrl {
|
||||
|
||||
/// Parse a database URL and extract the database name and optional prefix.
|
||||
///
|
||||
/// Expected format: `db://db_name` or `db://db_name/prefix`
|
||||
/// Expected format: `db://db_name`, `db://db_name/prefix`, or `db://` when
|
||||
/// connecting to the storage root through a host override.
|
||||
pub fn parse_db_url(db_url: &str) -> Result<ParsedDbUrl> {
|
||||
let parsed_url = url::Url::parse(db_url).map_err(|err| Error::InvalidInput {
|
||||
message: format!("db_url is not a valid URL. '{db_url}'. Error: {err}"),
|
||||
})?;
|
||||
debug_assert_eq!(parsed_url.scheme(), "db");
|
||||
if !parsed_url.has_host() {
|
||||
return Err(Error::InvalidInput {
|
||||
message: format!("Invalid database URL (missing host) '{}'", db_url),
|
||||
});
|
||||
}
|
||||
let db_name = parsed_url.host_str().unwrap().to_string();
|
||||
let db_name = match parsed_url.host_str() {
|
||||
Some(db_name) => db_name.to_string(),
|
||||
None if matches!(parsed_url.path(), "" | "/") => String::new(),
|
||||
None => {
|
||||
return Err(Error::InvalidInput {
|
||||
message: format!("Invalid database URL (missing host) '{}'", db_url),
|
||||
});
|
||||
}
|
||||
};
|
||||
let db_prefix = {
|
||||
let prefix = parsed_url.path().trim_start_matches('/');
|
||||
if prefix.is_empty() {
|
||||
|
||||
@@ -272,6 +272,13 @@ impl RemoteDatabase {
|
||||
read_consistency_interval: Option<std::time::Duration>,
|
||||
) -> Result<Self> {
|
||||
let parsed = super::client::parse_db_url(uri)?;
|
||||
if parsed.db_name.is_empty() && host_override.is_none() {
|
||||
return Err(Error::InvalidInput {
|
||||
message:
|
||||
"A host override is required when connecting to the storage root with 'db://'"
|
||||
.to_string(),
|
||||
});
|
||||
}
|
||||
let header_map = RestfulLanceDbClient::<Sender>::default_headers(
|
||||
api_key,
|
||||
region,
|
||||
|
||||
Reference in New Issue
Block a user