Repository navigation
Expand file tree
/
Copy pathsearch.py
More file actions
66 lines (51 loc) · 1.87 KB
/
Copy pathsearch.py
File metadata and controls
66 lines (51 loc) · 1.87 KB
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
from sentence_transformers import SentenceTransformer
import chromadb
import os
# Configuration
BASE_URL = "localhost"
PORT = 8000
COLLECTION_NAME = "test_collection"
MODEL_NAME = "all-MiniLM-L6-v2"
print(f"Loading embedding model ({MODEL_NAME})...")
model = SentenceTransformer(MODEL_NAME)
def search_chroma(query):
try:
# 1. Initialize ChromaDB Client
# Connect to Embedded ChromaDB
print("Connecting to local ChromaDB...")
client = chromadb.PersistentClient(path="./chroma_db")
# 2. Get the collection
collection = client.get_collection(name=COLLECTION_NAME)
# 3. Convert query to vector
query_vector = model.encode([query])[0].tolist()
# 4. Query Chroma Database
results = collection.query(
query_embeddings=[query_vector],
n_results=1
)
if results['documents'] and len(results['documents'][0]) > 0:
best_match_text = results['documents'][0][0]
# Chroma with cosine space returns distance. Similarity is 1 - distance.
distance = results['distances'][0][0]
score = 1.0 - distance
return best_match_text, score
else:
return "No relevant documents found.", 0.0
except Exception as e:
return f"Error connecting to ChromaDB: {e}", 0.0
def main():
print("\n--- AI Semantic Search (ChromaDB Powered) ---")
print("Type 'exit' or 'quit' to stop.\n")
while True:
query = input("Enter your search query: ")
if query.lower() in ['exit', 'quit']:
break
if not query.strip():
continue
result, score = search_chroma(query)
print("-" * 30)
print(f"Result: {result}")
print(f"Confidence Score: {score:.4f}")
print("-" * 30 + "\n")
if __name__ == "__main__":
main()