File size: 8,043 Bytes
065b1c3 cb4f7ee 065b1c3 cb4f7ee 065b1c3 cb4f7ee 065b1c3 cb4f7ee 065b1c3 f2d841b 065b1c3 cb4f7ee 065b1c3 f2d841b cb4f7ee f2d841b 065b1c3 f2d841b cb4f7ee f2d841b cb4f7ee 065b1c3 cb4f7ee f2d841b cb4f7ee f2d841b cb4f7ee 065b1c3 cb4f7ee 065b1c3 cb4f7ee 065b1c3 cb4f7ee 065b1c3 cb4f7ee 065b1c3 cb4f7ee 065b1c3 f2d841b cb4f7ee f2d841b 065b1c3 cb4f7ee 065b1c3 cb4f7ee 065b1c3 cb4f7ee 065b1c3 f2d841b 065b1c3 cb4f7ee 065b1c3 | 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 | import gradio as gr
import requests
import json
from typing import Optional
import base64
API_BASE_URL = "https://api.mixpeek.com/v1"
def encode_file_to_base64(file_path: str) -> str:
"""Encode a file to base64 string."""
with open(file_path, "rb") as f:
return base64.b64encode(f.read()).decode("utf-8")
def get_file_type(file_path: str) -> str:
"""Determine file type from extension."""
ext = file_path.lower().split(".")[-1]
video_exts = {"mp4", "mov", "avi", "mkv", "webm", "flv"}
if ext in video_exts:
return "video"
return "image"
def extract_features(
api_key: str,
namespace_id: str,
file: Optional[str],
text_input: str,
input_type: str,
model_choice: str,
) -> str:
"""Extract features from the input using Mixpeek API."""
if not api_key:
return json.dumps({"error": "Please provide your Mixpeek API key"}, indent=2)
if not namespace_id:
return json.dumps({"error": "Please provide your Namespace ID"}, indent=2)
headers = {
"Authorization": f"Bearer {api_key}",
"Content-Type": "application/json",
"X-Namespace": namespace_id,
}
# Map model choice to model name
model_map = {
"Google Multimodal (1408D)": "multimodalembedding",
"OpenAI text-embedding-3-large": "text-embedding-3-large",
"OpenAI text-embedding-3-small": "text-embedding-3-small",
}
model = model_map.get(model_choice, "multimodalembedding")
try:
# Handle text input
if input_type == "Text":
if not text_input.strip():
return json.dumps({"error": "Please provide text input"}, indent=2)
payload = {
"provider": "google" if "multimodal" in model else "openai",
"model": model,
"inputs": {"text": text_input},
"parameters": {}
}
# Handle file input
else:
if not file:
return json.dumps({"error": "Please upload a file"}, indent=2)
file_type = get_file_type(file)
base64_data = encode_file_to_base64(file)
# Only Google multimodal supports image/video embeddings
if "multimodal" not in model:
return json.dumps({
"error": f"OpenAI embedding models only support text. Use 'Google Multimodal (1408D)' for {file_type} embeddings."
}, indent=2)
payload = {
"provider": "google",
"model": model,
"inputs": {
f"{file_type}_base64": base64_data
},
"parameters": {}
}
response = requests.post(
f"{API_BASE_URL}/inference",
headers=headers,
json=payload,
timeout=180
)
if response.status_code == 200:
result = response.json()
# Format the output nicely
output = {
"status": "success",
"model": model,
"input_type": input_type.lower() if input_type == "Text" else get_file_type(file),
}
if "data" in result:
data = result["data"]
if "embeddings" in data:
embeddings = data["embeddings"]
if embeddings and len(embeddings) > 0:
output["embedding_dimensions"] = len(embeddings[0])
output["embedding_preview"] = embeddings[0][:10] # First 10 dims
output["embedding_full"] = embeddings[0]
else:
output["data"] = data
else:
output["raw_response"] = result
if "latency_ms" in result:
output["latency_ms"] = result["latency_ms"]
return json.dumps(output, indent=2)
else:
return json.dumps({
"error": f"API returned status {response.status_code}",
"details": response.text
}, indent=2)
except requests.exceptions.Timeout:
return json.dumps({"error": "Request timed out. Try a smaller file."}, indent=2)
except Exception as e:
return json.dumps({"error": str(e)}, indent=2)
# Build the Gradio interface
with gr.Blocks(
title="Mixpeek Multimodal Feature Extractor",
theme=gr.themes.Soft(),
) as demo:
gr.Markdown("""
# Mixpeek Multimodal Feature Extractor
Extract **1408-dimensional embeddings** from **videos**, **images**, and **text** using
[Mixpeek's](https://mixpeek.com) inference API powered by Google Vertex AI.
**Supported Inputs:**
- **Image**: JPG, PNG, WebP, BMP, GIF
- **Video**: MP4, MOV, AVI, MKV, WebM
- **Text**: Any text string
---
""")
with gr.Row():
with gr.Column(scale=1):
api_key = gr.Textbox(
label="Mixpeek API Key",
placeholder="Enter your API key from mixpeek.com",
type="password",
)
namespace_id = gr.Textbox(
label="Namespace ID",
placeholder="Enter your namespace ID (e.g., ns_abc123)",
info="Required for API access. Find this in your Mixpeek dashboard."
)
input_type = gr.Radio(
choices=["File Upload", "Text"],
value="File Upload",
label="Input Type",
)
file_input = gr.File(
label="Upload File",
file_types=[".mp4", ".mov", ".avi", ".mkv", ".webm", ".flv",
".jpg", ".jpeg", ".png", ".webp", ".bmp", ".gif"],
visible=True,
)
text_input = gr.Textbox(
label="Text Input",
placeholder="Enter text to embed...",
lines=3,
visible=False,
)
model_choice = gr.Dropdown(
choices=[
"Google Multimodal (1408D)",
"OpenAI text-embedding-3-large",
"OpenAI text-embedding-3-small",
],
value="Google Multimodal (1408D)",
label="Embedding Model",
info="Google Multimodal supports text, image, and video. OpenAI models support text only."
)
extract_btn = gr.Button("Extract Embedding", variant="primary", size="lg")
with gr.Column(scale=1):
output = gr.Code(
label="Results",
language="json",
lines=30,
)
# Toggle visibility based on input type
def toggle_input(choice):
if choice == "Text":
return gr.update(visible=False), gr.update(visible=True)
else:
return gr.update(visible=True), gr.update(visible=False)
input_type.change(
toggle_input,
inputs=[input_type],
outputs=[file_input, text_input]
)
# Extract button click handler
extract_btn.click(
extract_features,
inputs=[
api_key,
namespace_id,
file_input,
text_input,
input_type,
model_choice,
],
outputs=[output],
)
gr.Markdown("""
---
### API Usage
```bash
curl -X POST https://api.mixpeek.com/v1/inference \\
-H "Authorization: Bearer YOUR_API_KEY" \\
-H "X-Namespace: YOUR_NAMESPACE_ID" \\
-H "Content-Type: application/json" \\
-d '{
"provider": "google",
"model": "multimodalembedding",
"inputs": {"text": "your text here"},
"parameters": {}
}'
```
### Resources
- [Mixpeek Documentation](https://docs.mixpeek.com)
- [API Reference](https://docs.mixpeek.com/api-reference)
- [Get API Key](https://mixpeek.com)
""")
if __name__ == "__main__":
demo.launch()
|