File size: 10,597 Bytes
bfff176
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
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
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
# EmbeddingGemma 2 — Multimodal API

Text, image, audio, and video embeddings from Google's `google/embeddinggemma-2`, served with FastAPI. Includes a built-in browser playground and copyable Markdown documentation.

**Public Space:** `https://misukisu-embeddinggemma-2-api.hf.space`  
**Model:** `google/embeddinggemma-2`  
**Output:** 128-, 256-, 512-, or 768-dimensional, unit-normalized float vectors  
**Version:** 2.0

> This describes the upgraded `app.py` provided with this project. Deploy these files before using the new batch API or UI. Your currently deployed Space may still run the older code.

## Quick start

```bash
curl -sS https://misukisu-embeddinggemma-2-api.hf.space/embed \
  -X POST -H 'Content-Type: application/json' \
  -d '{"text":"Finland","task_prefix":"SearchQuery","dimensions":256}'
```

Illustrative response (vector shortened here):

```json
{"embedding": [0.0123, -0.0456, 0.0789], "dimensions": 256}
```

Real responses have exactly the requested number of floats.

## Endpoints

| Method | Route | Description |
| --- | --- | --- |
| GET | `/` | Built-in web UI: playground and copyable docs |
| GET | `/health` | Model readiness, device, and configuration |
| GET | `/docs.MD` | Raw Markdown documentation (copy/download) |
| GET | `/swagger` | Interactive FastAPI/Swagger OpenAPI reference |
| GET | `/redoc` | ReDoc API reference |
| GET | `/openapi.json` | Machine-readable API schema |
| POST | `/embed` | One text/multimodal input, or batch of text strings |
| POST | `/embed/file` | Image, audio, or video upload (optionally with text) |

## GET /health

```bash
curl https://misukisu-embeddinggemma-2-api.hf.space/health
```

Example:

```json
{
  "status": "ready",
  "engine": "multimodal-embeddinggemma-2",
  "model": "google/embeddinggemma-2",
  "device": "cpu",
  "dtype": "float32",
  "dimensions": [128, 256, 512, 768],
  "max_batch": 32,
  "max_tokens": 2048
}
```

The values of `device`, `dtype`, and `max_batch` depend on deployment configuration. `/` is the frontend, not a health JSON endpoint.

## POST /embed — JSON embeddings

Send an `application/json` body.

| Field | Type | Default | Description |
| --- | --- | --- | --- |
| `text` | string | `null` | One text input. |
| `texts` | string array | `null` | Batch text input; cannot mix with single input/media. |
| `image_b64` | string | `null` | Base64 image, optionally a `data:image/...;base64,` URI. |
| `audio_b64` | string | `null` | Base64 WAV, FLAC or OGG audio. |
| `task_prefix` | string or null | `"SearchQuery"` | Task-specific instruction for **text-only** input. |
| `title` | string | `null` | Optional title for `Document` task; otherwise `none`. |
| `dimensions` | integer | `256` | **Exactly** 128, 256, 512, or 768. Invalid values return 422. |

At least one input is required. `image_b64` and `audio_b64` can be combined with `text` for a single multimodal input. If media is included, supplied text is used literally (without an automatic task prefix).

### One text input

```python
import requests

base = 'https://misukisu-embeddinggemma-2-api.hf.space'
r = requests.post(f'{base}/embed', json={
    'text': 'Northern lights in Finland',
    'task_prefix': 'SearchQuery',
    'dimensions': 256
}, timeout=120)
r.raise_for_status()
vector = r.json()['embedding']
print(len(vector))  # 256
```

### Text batch (NEW)

`texts` embeds multiple strings in one request, using a shared task type and dimensions. This is ideal for your **Finland → Elon Musk Wikipedia speedrunner** because it avoids making one API call per link.

```python
import requests

base = 'https://misukisu-embeddinggemma-2-api.hf.space'
r = requests.post(f'{base}/embed', json={
    'texts': ['Finland', 'SpaceX', 'Elon Musk', 'Tesla, Inc.'],
    'task_prefix': 'SentenceSimilarity',
    'dimensions': 256
}, timeout=120)
r.raise_for_status()
data = r.json()
print(data['count'])          # 4
print(len(data['embeddings'][0]))  # 256
```

Response shape:

```json
{"embeddings": [[0.1, 0.2], [0.2, 0.1]], "dimensions": 256, "count": 2}
```

Example vectors above are shortened and illustrative. Default maximum is 32 strings per batch, configurable with `MAX_BATCH`.

### Text task prefixes

The upgraded backend applies Google's **actual task instruction strings**, not the old `SearchQuery: text` format.

| `task_prefix` | Text passed to processor |
| --- | --- |
| `SearchQuery` | `task: search result \| query: {text}` |
| `Document` | `title: {title or none} \| text: {text}` |
| `QuestionAnswering` | `task: question answering \| query: {text}` |
| `FactChecking` | `task: fact checking \| query: {text}` |
| `CodeRetrieval` | `task: code retrieval \| query: {text}` |
| `Classification` | `task: classification \| query: {text}` |
| `Clustering` | `task: clustering \| query: {text}` |
| `SentenceSimilarity` | `task: sentence similarity \| query: {text}` |
| `null`, `"None"`, or `"Raw"` | Raw text, no instruction |

For same-type Wikipedia article title comparisons, use `SentenceSimilarity` for **both** the goal and the candidates. For document retrieval, use `SearchQuery` for your query and `Document` for articles.

**Compatibility note:** This upgrade changes vector values compared to your previous API because it fixes pooling and prefixes. Re-embed previously stored data and queries before comparing vectors. Use the same embedding dimensions and compatible task types for both sides.

### Base64 image

```python
import base64
import requests

with open('photo.jpg', 'rb') as f:
    img = base64.b64encode(f.read()).decode('ascii')
r = requests.post('https://misukisu-embeddinggemma-2-api.hf.space/embed',
    json={'image_b64': img, 'dimensions': 256}, timeout=120)
r.raise_for_status()
print(len(r.json()['embedding']))
```

### Base64 audio

```python
import base64
import requests

with open('clip.wav', 'rb') as f:
    audio = base64.b64encode(f.read()).decode('ascii')
r = requests.post('https://misukisu-embeddinggemma-2-api.hf.space/embed',
    json={'audio_b64': audio, 'dimensions': 256}, timeout=120)
r.raise_for_status()
print(len(r.json()['embedding']))
```

Audio is decoded to mono float32 samples at 16kHz. Keep clips to 60 seconds or less by default. For audio formats not handled by `soundfile`, convert them to WAV first.

## POST /embed/file — Upload media

`multipart/form-data` fields:

| Field | Type | Required | Default |
| --- | --- | --- | --- |
| `file` | image/audio/video binary | Yes | — |
| `text` | string | No | empty |
| `task_prefix` | string | No | `SearchQuery` (media content never auto-prefixed) |
| `dimensions` | integer | No | `256` |

Images become RGB, audio becomes 16kHz mono, and video passes through the model's **native video processor**, sampling at 1 FPS with at most 8 frames. Media and optional text are embedded jointly, not as separate outputs.

```bash
curl -sS -X POST 'https://misukisu-embeddinggemma-2-api.hf.space/embed/file' \
  -F 'file=@photo.jpg' \
  -F 'text=A wildlife photo' \
  -F 'dimensions=256'
```

Python:

```python
import requests

url = 'https://misukisu-embeddinggemma-2-api.hf.space/embed/file'
with open('video.mp4', 'rb') as f:
    r = requests.post(url, files={'file': ('video.mp4', f, 'video/mp4')},
                      data={'dimensions': 256}, timeout=180)
r.raise_for_status()
print(r.json()['dimensions'])
```

Response:

```json
{
  "filename": "photo.jpg",
  "type": "image/jpeg",
  "embedding": [0.0123, -0.0456, 0.0789],
  "dimensions": 256
}
```

The vector shown above is shortened and illustrative. Audio support includes WAV/FLAC/OGG through `soundfile`; video decoding requires compatible codecs in your system's PyAV setup.

## Similarity scoring

All embeddings are L2 normalized, so dot product is cosine similarity when you use the same dimension:

```python
import numpy as np

similarity = float(np.dot(query_embedding, document_embedding))
print(similarity)
```

Never directly compare 128-dimensional vectors with 256-dimensional vectors. Text task instruction selection also affects comparisons.

## Errors and limits

| Status | Meaning |
| --- | --- |
| 400 | Unsupported or corrupted media; malformed base64 |
| 413 | Media or audio exceeds configured size/time limits |
| 422 | Invalid JSON/form fields, unsupported dimensions/task, empty inputs |
| 503 | Model is not loaded yet |

Default configuration: 20 MB max media upload, 20 megapixel max image size, 60-second max audio, 32 text inputs per batch, 12,000 characters per text string. Batch text sequences are truncated at 2,048 tokens by default (`MAX_TOKENS`, configurable up to 8,192), and processed in chunks of 8 items (`BATCH_CHUNK`) to control peak memory.

Production considerations: one model instance per process, inference protected by a lock to prevent simultaneous memory spikes, no authentication or rate limiting included. Add reverse-proxy limits and authentication for a public high-traffic API. Model loading can take time and may require Hugging Face model access/authorization.

## Running and deployment

Install dependencies with `pip install -r requirements.txt`, then launch:

```bash
uvicorn app:app --host 0.0.0.0 --port 7860 --workers 1
```

Optional variables: `MODEL_PATH`, `TORCH_THREADS`, `MAX_UPLOAD_MB`, `MAX_AUDIO_SECONDS`, `MAX_BATCH`, `BATCH_CHUNK`, `MAX_TOKENS`, `MAX_TEXT_LENGTH`. Keep `--workers 1`; each additional worker loads another copy of the model.

For a Docker Hugging Face Space, copy the files into your repository and use the provided Dockerfile. For a standard Gradio Space, change it to a Docker Space first or otherwise configure a FastAPI-compatible launch command.

## Why this is better than the original

- Correct **attention-mask-aware mean pooling** instead of taking only token zero.
- Proper task prefixes such as `task: search result | query:`.
- Batch text embeddings for efficient many-link similarity search.
- Input size limits, strict valid dimensions, media decoding checks, and clearer errors.
- Original `/embed` and `/embed/file` routes retained (with improved embedding math).
- Full web playground and documentation with **Copy all Markdown**.
- GPU handling avoids FP16 activations and chooses bfloat16 only when supported; otherwise float32.
- Video uses its native processor instead of treating frames as unrelated images.

## References

- [EmbeddingGemma 2 model card](https://huggingface.co/google/embeddinggemma-2)
- [Transformers EmbeddingGemma 2 documentation](https://huggingface.co/docs/transformers/model_doc/embedding_gemma2)
- [FastAPI OpenAPI guide](https://fastapi.tiangolo.com/tutorial/metadata/)