Local Multimodal Search Guide: How to Search Images, PDFs, and Audio/Video Offline
As personal and business data keeps growing, local drives fill up with PDFs, images, recordings, and videos. Filename search only finds names, and full-text search only finds text—neither can answer questions like "someone said this in a video, at which second?" Multimodal retrieval places different content types into a shared vector space so you can locate specific content with natural language. This guide covers the core principles, system architecture, parameter selection, code examples, evaluation methods, and security practices. By the end, you'll be able to build a small system that runs fully offline.
As personal and business data keeps growing, local drives fill up with PDFs, images, recordings, and videos. Filename search only finds names, and full-text search only finds text—neither can answer questions like “someone said this in a video, at which second?” Multimodal retrieval places different content types into a shared vector space so you can locate specific content with natural language. This article walks through the principles, architecture, parameter selection, code examples, evaluation, and security practices, so you can build a small system that works fully offline.
1. Core Principles of Multimodal Retrieval
Multimodal retrieval converts text, images, audio, and video into fixed-dimension vectors. Multimodal embedding models are pretrained to understand semantic relationships across modalities, so semantically similar content ends up close together in vector space. The sentence “the meeting discussed the budget” and an audio clip about the budget will have relatively close vectors.
There is one prerequisite that must be satisfied: text vectors and image vectors are directly comparable only when they come from the same multimodal model, or from the same model family that has been verified for alignment. If you compute similarity between vectors generated by two unrelated models, the ranking results are meaningless.
A typical system handles four types of data:
- Text: Extract text from PDFs, split it into appropriately sized chunks, and generate one vector per chunk.
- Images: Use the vision component of the model to extract image features and generate image vectors.
- Audio: Either transcribe speech to text first and then generate text vectors, or use audio embeddings directly. Each approach has trade-offs: transcription is easier to verify manually, while direct audio embeddings preserve tone and ambient sounds.
- Video: Extract keyframes at fixed time intervals and separate the audio track. Every frame or audio segment must be recorded with a timestamp.
Timestamps are the key to “jumping straight to that second.” They must be stored in the database together with the vectors as metadata. Keep timestamp units consistent—use seconds throughout, with two decimal places.
2. Architecture of a Local Retrieval System
Local deployment reduces the chances of data leaving the device and works without a network connection. A complete system can be divided into four modules.
2.1 Data Parsing and Preprocessing
This is the starting point of the pipeline. PDFs require a parsing library to extract the body text and to pull out embedded images separately. Videos require a multimedia tool to extract frames at fixed intervals and split out the audio track. Recordings can be fed in directly as audio input.
Every parsed segment needs a unique identifier plus source information, such as file path, page number, or timestamp. Source information is what makes search results navigable—if it’s lost, retrieved content can no longer be traced back to the original file.
2.2 Local Vector Generation
This module calls a locally deployed embedding model to encode the preprocessed segments into vectors one by one. To keep things running smoothly on ordinary hardware, models are often quantized—for example, to INT8 or INT4. Quantization reduces memory usage but affects vector quality; the parameter section below explains how to verify this.
You can use a lightweight inference engine to speed up inference. It’s recommended to normalize the output vectors (divide each vector by its own length), so that a dot product directly yields cosine similarity later.
2.3 Vector Storage and Indexing
Vectors and metadata are written to a local vector store. For individual or small-team data volumes, an in-memory or local-file-based vector search library is sufficient. As data grows, you can consider a dedicated vector database.
Indexes typically use approximate nearest neighbor algorithms such as HNSW. The trade-off is that results are no longer fully exact, in exchange for query speed. Several HNSW parameters need to be balanced: M determines the number of connections per node in the graph; larger values of efConstruction (at index time) and ef_search (at query time) improve recall but slow down both indexing and querying.
Note that the index’s distance metric must match how the vectors were processed. If vectors are normalized, use cosine or inner product—don’t mix in Euclidean distance.
2.4 Semantic Search and Result Mapping
When a user enters a natural language query, the system encodes it with the same model, computes its similarity against all data vectors in the store, and returns the Top-K results. Results are presented based on metadata—for example, showing the PDF page number or having the player jump to the corresponding second.
3. Selection and Starting Parameters
The values below are starting points, not standard answers. Before production use, calibrate them with your own data and sample queries.
- Embedding model: Prefer models that explicitly support the modalities you need, have good Chinese (or your target language) capability, and carry a license that permits your use case. Also confirm it can run within your VRAM or RAM budget.
- Text chunk length: A common starting point is 200–500 characters per chunk, with 10–20% overlap between adjacent chunks to avoid cutting a sentence in half.
- Video frame extraction interval: For lectures and meetings, start with 5 seconds; for action-heavy video, shorten to 1–2 seconds. Shorter intervals mean more vectors and higher storage and compute costs.
- Vector dimensions: Determined by the model, commonly 512–1024. Higher dimensions mean larger storage.
- Top-K: For results browsed manually, take 5–10; for results used for automatic jumps, usually 1–3.
- Similarity threshold: Score distributions vary widely between models, so don’t copy someone else’s numbers. Prepare a set of queries with known answers, observe the scores of correct and incorrect results, then set the threshold.
- Quantization: INT8 usually has a small impact on recall; INT4’s impact is more noticeable. After quantization, run regression tests with the same labeled queries and compare recall changes. Keep an FP16 or INT8 version as a fallback.
4. Key Code Example
The following code shows the basic flow of video frame indexing and retrieval. It won’t run as-is; you need to: install opencv-python and numpy; replace local_model with the object provided by your model’s inference library, which must implement encode_image and encode_text methods returning one-dimensional vectors. Note that OpenCV reads frames in BGR order, and some models require RGB—convert according to your model’s requirements.
import cv2import numpy as npdef extract_video_frames(video_path: str, interval_sec: float = 2.0):"""Extract frames at fixed time intervals; timestamps in seconds"""cap = cv2.VideoCapture(video_path)if not cap.isOpened():raise FileNotFoundError(f"Cannot open video: {video_path}")fps = cap.get(cv2.CAP_PROP_FPS) or 25.0duration = int(cap.get(cv2.CAP_PROP_FRAME_COUNT)) / fpst = 0.0try:while t < duration:cap.set(cv2.CAP_PROP_POS_MSEC, t * 1000)ok, frame = cap.read()if ok:yield {"frame": frame, "timestamp": round(t, 2)}t += interval_secfinally:cap.release()def build_index(video_path: str, video_id: str, local_model, interval_sec: float = 2.0):"""Encode frames one by one and store normalized vectors with metadata,without keeping all raw frames in memory"""vectors, metas = [], []for item in extract_video_frames(video_path, interval_sec):try:vec = np.asarray(local_model.encode_image(item["frame"]), dtype=np.float32)except Exception as exc:print(f"[skipped] {video_id} @ {item['timestamp']}s: {exc}")continuevectors.append(vec / (np.linalg.norm(vec) + 1e-12))metas.append({"video_id": video_id, "timestamp": item["timestamp"]})if not vectors:return np.empty((0, 0), dtype=np.float32), []return np.vstack(vectors), metasdef search_timestamps(query: str, vectors: np.ndarray, metas: list,local_model, top_k: int = 3, threshold: float = 0.25):"""Return the timestamps with the highest similarity;the threshold must be calibrated with your own samples"""if vectors.size == 0:return []q = np.asarray(local_model.encode_text(query), dtype=np.float32)q = q / (np.linalg.norm(q) + 1e-12)scores = vectors @ qorder = np.argsort(-scores)[:top_k]return [{"timestamp": metas[i]["timestamp"], "score": float(scores[i])}for i in order if scores[i] >= threshold]
A few things to note about this code. The generator yields frames one at a time, so long videos won’t exhaust memory at once. Frames that fail to encode are skipped with a log entry rather than interrupting the whole task. The threshold of 0.25 is just a placeholder—it must be recalibrated using the method described earlier.
5. Evaluation and Common Mistakes
“It can find things” is not enough to judge whether the system is usable. It’s recommended to record the following metrics and compare them under the same hardware and data-scale conditions:
- Recall@K: Prepare a set of queries with ground-truth answers and measure the proportion where the correct result appears in the Top-K.
- Timestamp localization error: The difference in seconds between the correct result and the ground-truth time point.
- Query latency: Record P95 and P99, not just the average. Averages hide the few very slow requests.
- Index build time: Record how long it takes to process all the data—this determines how often you can refresh the index.
- Peak RAM and VRAM: Record maximum usage during runs to judge whether your hardware is sufficient.
- Environment info: Record hardware model, data volume, model version, and quantization method—otherwise results can’t be reproduced.
Common mistakes include:
- Using different models for text and images, making cross-modal results nearly random.
- Mixing timestamp units—some records in seconds, others in milliseconds—so every jump lands in the wrong place.
- Mismatch between the index metric and vector processing, such as using inner product on unnormalized vectors.
- Videos carrying rotation metadata, causing extracted frames to be oriented incorrectly and degrading image vector quality.
- Audio segment boundaries cutting a sentence in half, so relevant words can’t be retrieved.
- Scores shifting overall after quantization, invalidating previously calibrated thresholds.
6. Security Boundaries for Local Data
Local deployment reduces the chance of data leaking externally, but it isn’t risk-free. At minimum, do the following:
- Least privilege: The account running the indexing service should only read the directories it needs; don’t run it as an administrator.
- Disk encryption: Enable full-disk encryption so data can’t be read directly if the device is lost.
- Log redaction: Don’t log document content, full personal paths, or other sensitive fields—log only file identifiers and error types.
- Backups: The vector store and metadata need backups just like the original files. Backup files must also be encrypted.
- Deletion sync: When a source file is deleted, delete the corresponding vectors and metadata as well. Otherwise, results may point to files that no longer exist and may still expose content fragments.
- Regular audits: Periodically check that the index matches the source files and clean up orphaned records.
7. Trade-offs of Hybrid Deployment
When building a full index over large volumes of high-resolution video, local hardware may need to run for a very long time. One approach is to run the initial bulk encoding on cloud GPUs and keep only the query service local. This shortens the initial indexing time, but before uploading you must confirm that the data is allowed to leave the local environment, and verify the provider’s data retention and training-use policies. For confidential documents or personal privacy content, it’s recommended to keep all processing local.
