Spaces:
Sleeping
Sleeping
Create services/kb_creation.py
Browse files- services/kb_creation.py +129 -0
services/kb_creation.py
ADDED
|
@@ -0,0 +1,129 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
from docx import Document
|
| 3 |
+
from sentence_transformers import SentenceTransformer
|
| 4 |
+
import chromadb
|
| 5 |
+
|
| 6 |
+
# Initialize ChromaDB client
|
| 7 |
+
client = chromadb.PersistentClient(path="chroma_db")
|
| 8 |
+
collection = client.get_or_create_collection(name="knowledge_base")
|
| 9 |
+
|
| 10 |
+
# Load embedding model
|
| 11 |
+
model = SentenceTransformer('./models/all-MiniLM-L6-v2')
|
| 12 |
+
"""
|
| 13 |
+
def extract_text_from_docx(file_path):
|
| 14 |
+
doc = Document(file_path)
|
| 15 |
+
return '\n'.join([para.text for para in doc.paragraphs if para.text.strip()])
|
| 16 |
+
|
| 17 |
+
def chunk_text(text, max_words=300):
|
| 18 |
+
words = text.split()
|
| 19 |
+
return [' '.join(words[i:i + max_words]) for i in range(0, len(words), max_words)]
|
| 20 |
+
|
| 21 |
+
def ingest_documents(file_path):
|
| 22 |
+
if not os.path.exists(file_path):
|
| 23 |
+
return {"status": "error", "message": f"File not found: {file_path}"}
|
| 24 |
+
|
| 25 |
+
text = extract_text_from_docx(file_path)
|
| 26 |
+
if not text.strip():
|
| 27 |
+
return {"status": "error", "message": "Document is empty"}
|
| 28 |
+
|
| 29 |
+
chunks = chunk_text(text)
|
| 30 |
+
print(f"π Ingesting {os.path.basename(file_path)} with {len(chunks)} chunks")
|
| 31 |
+
|
| 32 |
+
for i, chunk in enumerate(chunks):
|
| 33 |
+
embedding = model.encode(chunk).tolist()
|
| 34 |
+
doc_id = f"{os.path.basename(file_path)}_{i}"
|
| 35 |
+
collection.add(
|
| 36 |
+
ids=[doc_id],
|
| 37 |
+
embeddings=[embedding],
|
| 38 |
+
documents=[chunk],
|
| 39 |
+
metadatas=[{"filename": os.path.basename(file_path)}]
|
| 40 |
+
)
|
| 41 |
+
|
| 42 |
+
return {"status": "success", "chunks": len(chunks), "message": "Ingestion completed"}
|
| 43 |
+
|
| 44 |
+
def ingest_all_documents(folder_path):
|
| 45 |
+
files = [f for f in os.listdir(folder_path) if f.endswith('.docx')]
|
| 46 |
+
if not files:
|
| 47 |
+
return {"status": "error", "message": "No .docx files found"}
|
| 48 |
+
|
| 49 |
+
for file in files:
|
| 50 |
+
file_path = os.path.join(folder_path, file)
|
| 51 |
+
ingest_documents(file_path)
|
| 52 |
+
|
| 53 |
+
return {"status": "success", "message": f"Ingested {len(files)} files"}
|
| 54 |
+
|
| 55 |
+
def search_knowledge_base(query, top_k=3):
|
| 56 |
+
query_embedding = model.encode(query).tolist()
|
| 57 |
+
print("query_embedding",query_embedding)
|
| 58 |
+
results = collection.query(
|
| 59 |
+
query_embeddings=[query_embedding],
|
| 60 |
+
n_results=top_k,
|
| 61 |
+
include=['documents', 'metadatas', 'distances']
|
| 62 |
+
)
|
| 63 |
+
print("results",results)
|
| 64 |
+
return results
|
| 65 |
+
"""
|
| 66 |
+
def extract_text_from_docx(file_path):
|
| 67 |
+
"""Extract text from a .docx file."""
|
| 68 |
+
#print("file_path",file_path)
|
| 69 |
+
doc = Document(file_path)
|
| 70 |
+
return '\n'.join([para.text for para in doc.paragraphs])
|
| 71 |
+
|
| 72 |
+
def chunk_text(text, max_words=300):
|
| 73 |
+
"""Split text into smaller chunks for better embedding quality."""
|
| 74 |
+
words = text.split()
|
| 75 |
+
return [' '.join(words[i:i + max_words]) for i in range(0, len(words), max_words)]
|
| 76 |
+
|
| 77 |
+
def ingest_documents(folder_path):
|
| 78 |
+
"""Read .docx files, chunk text, generate embeddings, and store in ChromaDB."""
|
| 79 |
+
print(f"π Checking folder: {folder_path}")
|
| 80 |
+
files = [f for f in os.listdir(folder_path) if f.endswith('.docx')]
|
| 81 |
+
print(f"Found {len(files)} Word files: {files}")
|
| 82 |
+
|
| 83 |
+
if not files:
|
| 84 |
+
print("β οΈ No .docx files found. Please check the folder path.")
|
| 85 |
+
return
|
| 86 |
+
|
| 87 |
+
for file in files:
|
| 88 |
+
file_path = os.path.join(folder_path, file)
|
| 89 |
+
text = extract_text_from_docx(file_path)
|
| 90 |
+
chunks = chunk_text(text)
|
| 91 |
+
|
| 92 |
+
print(f"π Ingesting {file} with {len(chunks)} chunks")
|
| 93 |
+
|
| 94 |
+
for i, chunk in enumerate(chunks):
|
| 95 |
+
embedding = model.encode(chunk).tolist()
|
| 96 |
+
doc_id = f"{file}_{i}"
|
| 97 |
+
collection.add(
|
| 98 |
+
ids=[doc_id],
|
| 99 |
+
embeddings=[embedding],
|
| 100 |
+
documents=[chunk],
|
| 101 |
+
metadatas=[{"filename": file}]
|
| 102 |
+
)
|
| 103 |
+
|
| 104 |
+
print(f"β
Documents ingested. Total entries: {collection.count()}")
|
| 105 |
+
|
| 106 |
+
def search_knowledge_base(query, top_k=3):
|
| 107 |
+
"""Search ChromaDB using semantic similarity."""
|
| 108 |
+
query_embedding = model.encode(query).tolist()
|
| 109 |
+
results = collection.query(query_embeddings=[query_embedding], n_results=top_k,include=['embeddings','documents', 'metadatas', 'distances'])
|
| 110 |
+
print("results",results)
|
| 111 |
+
return results
|
| 112 |
+
|
| 113 |
+
# Example usage:
|
| 114 |
+
# ingest_documents("path/to/docs")
|
| 115 |
+
# results = search_knowledge_base("inventory mismatch in warehouse")
|
| 116 |
+
# print(results)
|
| 117 |
+
|
| 118 |
+
#def main():
|
| 119 |
+
# folder_path = r"C:/Users/UD724VY/Downloads/Chatbot_V1/Chatbot_V1/Chatbot_FastAPI/GenericSOPsForTesting"
|
| 120 |
+
# print(os.path.exists(r"C:/Users/UD724VY/Downloads/Chatbot_V1/Chatbot_FastAPI/GenericSOPsForTesting"))
|
| 121 |
+
# if os.path.exists(folder_path):
|
| 122 |
+
# print(folder_path)
|
| 123 |
+
# ingest_documents(folder_path)
|
| 124 |
+
# else:
|
| 125 |
+
# print("β Invalid folder path. Please check and try again.")
|
| 126 |
+
#
|
| 127 |
+
#if __name__ == "__main__":
|
| 128 |
+
# print("Running main()", flush=True)
|
| 129 |
+
# main()
|