c10f90fe
tangwang
cnclip
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
"""
Image encoder using third-party clip-as-service (Jina CLIP server).
Requires clip-as-service server to be running. The client is loaded from
third-party/clip-as-service/client so no separate pip install is needed
if that path is on sys.path or the package is installed in development mode.
"""
import logging
import os
import sys
from typing import List, Optional
import numpy as np
logger = logging.getLogger(__name__)
# Ensure third-party clip client is importable
def _ensure_clip_client_path():
repo_root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
client_path = os.path.join(repo_root, "third-party", "clip-as-service", "client")
if os.path.isdir(client_path) and client_path not in sys.path:
sys.path.insert(0, client_path)
|
cc11ae04
tangwang
cnclip
|
24
25
|
# Skip client version check to avoid importing helper (pkg_resources); no conda/separate env
os.environ.setdefault("NO_VERSION_CHECK", "1")
|
c10f90fe
tangwang
cnclip
|
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
|
def _normalize_image_url(url: str) -> str:
"""Normalize image URL for clip-as-service (e.g. //host/path -> https://host/path)."""
if not url or not isinstance(url, str):
return ""
url = url.strip()
if url.startswith("//"):
return "https:" + url
return url
class ClipAsServiceImageEncoder:
"""
Image embedding encoder using clip-as-service Client.
|
6d71d8e0
tangwang
多模态模型配置
|
41
42
|
Vector length follows the loaded Chinese-CLIP model (e.g. 1024 for ViT-H-14, 768 for ViT-L-14);
must match ``services.embedding.image_backends.*.model_name`` and ES ``image_embedding.vector.dims``.
|
c10f90fe
tangwang
cnclip
|
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
|
"""
def __init__(
self,
server: str = "grpc://127.0.0.1:51000",
batch_size: int = 8,
show_progress: bool = False,
):
"""
Args:
server: clip-as-service server URI (e.g. grpc://127.0.0.1:51000 or http://127.0.0.1:51000).
batch_size: batch size for encode requests.
show_progress: whether to show progress bar when encoding.
"""
_ensure_clip_client_path()
|
3d588bef
tangwang
embeddings
|
58
59
|
from clip_client import Client
|
c10f90fe
tangwang
cnclip
|
60
61
62
63
|
self._server = server
self._batch_size = batch_size
self._show_progress = show_progress
|
ed948666
tangwang
tidy
|
64
65
66
67
68
69
70
71
72
|
try:
self._client = Client(server)
except ModuleNotFoundError as e:
if str(e) == "No module named 'pkg_resources'":
raise RuntimeError(
"clip-as-service requires pkg_resources via jina/hubble. "
"Install compatible setuptools (<82) in current venv."
) from e
raise
|
c10f90fe
tangwang
cnclip
|
73
74
75
76
77
|
def encode_image_urls(
self,
urls: List[str],
batch_size: Optional[int] = None,
|
200fdddf
tangwang
embed norm
|
78
|
normalize_embeddings: bool = True,
|
ed948666
tangwang
tidy
|
79
|
) -> List[np.ndarray]:
|
c10f90fe
tangwang
cnclip
|
80
81
82
83
84
85
86
87
|
"""
Encode a list of image URLs to vectors.
Args:
urls: list of image URLs (http/https or //host/path).
batch_size: override instance batch_size for this call.
Returns:
|
ed948666
tangwang
tidy
|
88
|
List of vectors (float32), same length as urls.
|
c10f90fe
tangwang
cnclip
|
89
90
91
92
93
|
"""
if not urls:
return []
normalized = [_normalize_image_url(u) for u in urls]
|
c10f90fe
tangwang
cnclip
|
94
|
bs = batch_size if batch_size is not None else self._batch_size
|
ed948666
tangwang
tidy
|
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
|
invalid_indices = [i for i, u in enumerate(normalized) if not u]
if invalid_indices:
raise ValueError(f"Invalid empty image URL at indices: {invalid_indices}")
# Client.encode(iterable of str) returns np.ndarray [N, D] for string input
arr = self._client.encode(
normalized,
batch_size=bs,
show_progress=self._show_progress,
)
if arr is None or not hasattr(arr, "shape"):
raise RuntimeError("clip-as-service encode returned empty result")
if len(arr) != len(normalized):
raise RuntimeError(
f"clip-as-service encode length mismatch: expected {len(normalized)}, got {len(arr)}"
|
c10f90fe
tangwang
cnclip
|
110
|
)
|
c10f90fe
tangwang
cnclip
|
111
|
|
ed948666
tangwang
tidy
|
112
113
114
115
116
|
out: List[np.ndarray] = []
for row in arr:
vec = np.asarray(row, dtype=np.float32)
if vec.ndim != 1 or vec.size == 0 or not np.isfinite(vec).all():
raise RuntimeError("clip-as-service returned invalid embedding vector")
|
200fdddf
tangwang
embed norm
|
117
118
119
120
121
|
if normalize_embeddings:
norm = float(np.linalg.norm(vec))
if not np.isfinite(norm) or norm <= 0.0:
raise RuntimeError("clip-as-service returned zero/invalid norm vector")
vec = vec / norm
|
ed948666
tangwang
tidy
|
122
|
out.append(vec)
|
c10f90fe
tangwang
cnclip
|
123
124
|
return out
|
af03fdef
tangwang
embedding模块代码整理
|
125
|
def encode_image_from_url(self, url: str, normalize_embeddings: bool = True) -> np.ndarray:
|
6d71d8e0
tangwang
多模态模型配置
|
126
|
"""Encode a single image URL and return one float32 vector (length = model embedding dim)."""
|
200fdddf
tangwang
embed norm
|
127
|
results = self.encode_image_urls([url], batch_size=1, normalize_embeddings=normalize_embeddings)
|
af03fdef
tangwang
embedding模块代码整理
|
128
129
130
|
if not results:
raise RuntimeError("clip-as-service returned empty result for single image URL")
return results[0]
|
7a013ca7
tangwang
多模态文本向量服务ok
|
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
|
def encode_clip_texts(
self,
texts: List[str],
batch_size: Optional[int] = None,
normalize_embeddings: bool = True,
) -> List[np.ndarray]:
"""
CN-CLIP 文本塔:与 encode_image_urls 输出同一向量空间(图文检索 / image_embedding)。
仅传入自然语言字符串;HTTP 侧见 ``POST /embed/clip_text``。
"""
if not texts:
return []
bs = batch_size if batch_size is not None else self._batch_size
arr = self._client.encode(
texts,
batch_size=bs,
show_progress=self._show_progress,
)
if arr is None or not hasattr(arr, "shape"):
raise RuntimeError("clip-as-service encode (text) returned empty result")
if len(arr) != len(texts):
raise RuntimeError(
f"clip-as-service text encode length mismatch: expected {len(texts)}, got {len(arr)}"
)
out: List[np.ndarray] = []
for row in arr:
vec = np.asarray(row, dtype=np.float32)
if vec.ndim != 1 or vec.size == 0 or not np.isfinite(vec).all():
raise RuntimeError("clip-as-service returned invalid text embedding vector")
if normalize_embeddings:
norm = float(np.linalg.norm(vec))
if not np.isfinite(norm) or norm <= 0.0:
raise RuntimeError("clip-as-service returned zero/invalid norm vector")
vec = vec / norm
out.append(vec)
return out
|