File size: 4,601 Bytes
aee08b4 |
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 |
# Semantic Search API
A production-ready semantic search service built with FastAPI. Upload your data (sequences + metadata), create embeddings automatically, and search using natural language queries.
## Features
- **Semantic/Latent Search**: Find similar sequences based on meaning, not just keywords
- **FastAPI Backend**: Modern, fast, async Python web framework
- **FAISS Index**: Efficient similarity search at scale
- **Sentence Transformers**: State-of-the-art embedding models
- **Beautiful UI**: Dark-themed, responsive search interface
- **CSV Upload**: Easy data import via web interface or API
- **Persistent Storage**: Index persists across restarts
## Quick Start
### 1. Install Dependencies
```bash
pip install -r requirements.txt
```
### 2. Run the Server
```bash
python app.py
# or
uvicorn app:app --reload --host 0.0.0.0 --port 8000
```
### 3. Open the UI
Navigate to `http://localhost:8000` in your browser.
### 4. Upload Your Data
- Drag & drop a CSV file or click to browse
- Select the column containing your sequences
- Click "Create Index"
- Start searching!
## Data Format
Your CSV should have at least one column containing the text sequences you want to search. All other columns become searchable metadata.
Example:
```csv
sequence,category,source,date
"Machine learning is transforming industries",tech,blog,2024-01-15
"The quick brown fox jumps over the lazy dog",example,pangram,2024-01-10
"Embeddings capture semantic meaning",ml,paper,2024-01-20
```
## API Endpoints
### Search
```bash
POST /api/search
Content-Type: application/json
{
"query": "artificial intelligence",
"top_k": 10
}
```
### Upload CSV
```bash
POST /api/upload-csv?sequence_column=text
Content-Type: multipart/form-data
file: your_data.csv
```
### Create Index (JSON)
```bash
POST /api/index
Content-Type: application/json
{
"sequence_column": "text",
"data": [
{"text": "Hello world", "category": "greeting"},
{"text": "Machine learning", "category": "tech"}
]
}
```
### Get Stats
```bash
GET /api/stats
```
### Get Sample
```bash
GET /api/sample?n=5
```
### Delete Index
```bash
DELETE /api/index
```
## Programmatic Usage
You can also create indexes directly from Python:
```python
from create_index import create_index_from_dataframe, search_index
import pandas as pd
# Create your dataframe
df = pd.DataFrame({
'sequence': [
'The mitochondria is the powerhouse of the cell',
'DNA stores genetic information',
'Proteins are made of amino acids'
],
'category': ['biology', 'genetics', 'biochemistry'],
'difficulty': ['easy', 'medium', 'medium']
})
# Create the index
create_index_from_dataframe(df, sequence_column='sequence')
# Search
results = search_index("cellular energy production", top_k=3)
for r in results:
print(f"Score: {r['score']:.3f} | {r['sequence'][:50]}...")
```
## Configuration
Edit these values in `app.py` to customize:
```python
# Embedding model (from sentence-transformers)
EMBEDDING_MODEL = "all-MiniLM-L6-v2" # Fast, 384 dimensions
# Alternatives:
# "all-mpnet-base-v2" # Higher quality, 768 dimensions
# "paraphrase-multilingual-MiniLM-L12-v2" # Multilingual support
# "all-MiniLM-L12-v2" # Balanced quality/speed
```
## Project Structure
```
semantic_search/
├── app.py # FastAPI application
├── create_index.py # Programmatic index creation
├── requirements.txt # Python dependencies
├── static/
│ └── index.html # Search UI
├── data/ # Created at runtime
│ ├── faiss.index # FAISS index file
│ ├── metadata.pkl # DataFrame with metadata
│ └── embeddings.npy # Raw embeddings (optional)
└── README.md
```
## How It Works
1. **Embedding Creation**: When you upload data, each sequence is converted to a dense vector (embedding) using a sentence transformer model
2. **FAISS Indexing**: Embeddings are stored in a FAISS index optimized for similarity search
3. **Search**: Your query is embedded using the same model, then FAISS finds the most similar vectors using cosine similarity
4. **Results**: The original sequences and metadata are returned, ranked by similarity
## Performance Tips
- **Model Choice**: `all-MiniLM-L6-v2` is fast and good for most use cases. Use `all-mpnet-base-v2` for higher quality at the cost of speed.
- **Batch Size**: For large datasets, the model processes in batches automatically
- **GPU**: If you have a CUDA-capable GPU, install `faiss-gpu` instead of `faiss-cpu` for faster indexing
## License
MIT
|