Spaces:
Running
Running
talexm
commited on
Commit
•
fdc732d
1
Parent(s):
aeb8626
adding LLM for RAg
Browse files- falocon_api/README.md +146 -0
- falocon_api/__init__.py +0 -0
- falocon_api/embeddingGenerator.py +101 -0
- falocon_api/embededGeneratorRAG.py +116 -0
falocon_api/README.md
ADDED
@@ -0,0 +1,146 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
### RAG Demo: AI-Powered Document Search with Generative Response
|
2 |
+
This project showcases a Retrieval-Augmented Generation (RAG) implementation using
|
3 |
+
SentenceTransformer for semantic search and GPT-2 (or a similar generative model)
|
4 |
+
for response generation. The system combines the power of semantic search with AI-driven text generation,
|
5 |
+
providing relevant answers based on a collection of text documents.
|
6 |
+
|
7 |
+
## Project Overview
|
8 |
+
The Chagu RAG Demo aims to solve the problem of efficient document retrieval and provide contextual
|
9 |
+
responses using Generative AI. It supports secure document search and offers additional protection
|
10 |
+
against malicious queries using semantic analysis. The project is built with the following goals:
|
11 |
+
|
12 |
+
# Semantic Search: Retrieve the most relevant documents based on user queries using embeddings.
|
13 |
+
# Generative AI Response: Generate a coherent and context-aware answer using a pre-trained text generation model.
|
14 |
+
# Anomaly Detection: Detect potentially harmful queries (e.g., SQL injections) and block them.
|
15 |
+
|
16 |
+
### Features
|
17 |
+
# Embedding-based Document Ingestion: Efficiently process and store text document embeddings in a local SQLite database.
|
18 |
+
# Semantic Search: Uses cosine similarity with SentenceTransformer embeddings for accurate information retrieval.
|
19 |
+
# Text Generation: Leverages GPT-2 or distilgpt2 for generating responses based on the retrieved context.
|
20 |
+
# Security: Includes basic query validation to prevent malicious input (e.g., SQL injection detection).
|
21 |
+
|
22 |
+
Technologies Used
|
23 |
+
SentenceTransformer: For generating semantic embeddings of text documents.
|
24 |
+
Transformers: Provides the generative model (e.g., we have a wide range of models here: https://huggingface.co/models?sort=trending&search=distilgpt2).
|
25 |
+
SQLite: A lightweight database for storing embeddings and document content.
|
26 |
+
Scikit-learn: Used for calculating cosine similarity.
|
27 |
+
NumPy: Efficient numerical operations.
|
28 |
+
|
29 |
+
Installation
|
30 |
+
|
31 |
+
Clone the Repository:
|
32 |
+
|
33 |
+
bash
|
34 |
+
```
|
35 |
+
git clone https://github.com/yourusername/chagu-rag-demo.git
|
36 |
+
cd chagu-rag-demo
|
37 |
+
```
|
38 |
+
Create a Virtual Environment:
|
39 |
+
|
40 |
+
bash
|
41 |
+
```
|
42 |
+
python3 -m venv .venv
|
43 |
+
source .venv/bin/activate
|
44 |
+
```
|
45 |
+
Install Dependencies:
|
46 |
+
|
47 |
+
bash
|
48 |
+
```
|
49 |
+
pip install -r requirements.txt
|
50 |
+
```
|
51 |
+
Authenticate with Hugging Face (if needed):
|
52 |
+
|
53 |
+
bash
|
54 |
+
```
|
55 |
+
huggingface-cli login
|
56 |
+
```
|
57 |
+
|
58 |
+
Setup and Dataset
|
59 |
+
Download and Prepare the Dataset:
|
60 |
+
|
61 |
+
You can use the IMDB Movie Reviews dataset or any other text files.
|
62 |
+
Place your .txt files in the documents/ directory or specify a custom path.
|
63 |
+
Ingest Files:
|
64 |
+
|
65 |
+
The script will process all .txt files in the specified directory and store embeddings in a local SQLite database.
|
66 |
+
bash
|
67 |
+
```
|
68 |
+
python embededGeneratorRAG.py
|
69 |
+
```
|
70 |
+
|
71 |
+
Usage
|
72 |
+
Ingest Documents
|
73 |
+
Ingest .txt files from the documents/ directory:
|
74 |
+
|
75 |
+
python
|
76 |
+
```
|
77 |
+
embedding_generator = EmbeddingGenerator()
|
78 |
+
embedding_generator.ingest_files("documents")
|
79 |
+
```
|
80 |
+
|
81 |
+
Perform a Search Query
|
82 |
+
Run a semantic search query and generate a response:
|
83 |
+
|
84 |
+
python
|
85 |
+
```
|
86 |
+
query = "How can I secure my database against SQL injection?"
|
87 |
+
response = embedding_generator.find_most_similar_and_generate(query)
|
88 |
+
print("Generated Response:")
|
89 |
+
print(response)
|
90 |
+
```
|
91 |
+
Example Output
|
92 |
+
sql
|
93 |
+
```
|
94 |
+
Generated Response:
|
95 |
+
To prevent SQL injection, you should use prepared statements and parameterized queries.
|
96 |
+
Avoid constructing SQL queries directly using user input.
|
97 |
+
```
|
98 |
+
File Structure
|
99 |
+
bash
|
100 |
+
```
|
101 |
+
chagu-rag-demo/
|
102 |
+
├── embeddings.db # SQLite database for storing embeddings
|
103 |
+
├── documents/ # Directory containing .txt files for ingestion
|
104 |
+
├── rag_chagu_demo.py # Main script with RAG implementation
|
105 |
+
├── embededGeneratorRAG.py # Core Embedding Generator class
|
106 |
+
├── requirements.txt # Python dependencies
|
107 |
+
├── README.md # Project documentation
|
108 |
+
Configuration
|
109 |
+
```
|
110 |
+
You can update the following configurations in the EmbeddingGenerator class:
|
111 |
+
|
112 |
+
Model Names: Change model_name or gen_model to use different embedding or generative models.
|
113 |
+
Database Path: Specify a custom path for the SQLite database.
|
114 |
+
|
115 |
+
python
|
116 |
+
```
|
117 |
+
embedding_generator = EmbeddingGenerator(model_name="all-MiniLM-L6-v2", gen_model="distilgpt2", db_path="custom_embeddings.db")
|
118 |
+
```
|
119 |
+
### Potential Improvements
|
120 |
+
FAISS Integration for Scalability:
|
121 |
+
|
122 |
+
Replace the current SQLite-based retrieval with FAISS for efficient and scalable vector search.
|
123 |
+
Enhanced Security:
|
124 |
+
|
125 |
+
Implement more robust query validation using a fine-tuned BERT model to detect harmful or suspicious inputs.
|
126 |
+
Deployment on Hugging Face Spaces:
|
127 |
+
|
128 |
+
Create an interactive demo using Streamlit or Gradio for showcasing the project on Hugging Face Spaces.
|
129 |
+
Known Issues
|
130 |
+
Input Truncation Warning: If the input text is too long, you may see a warning about truncation. This is handled using truncation=True, but it may affect very long queries.
|
131 |
+
|
132 |
+
Model Availability: Ensure you are using a publicly available model from Hugging Face. If you encounter a 404 Not Found error, check the model identifier.
|
133 |
+
|
134 |
+
## Contributing
|
135 |
+
Contributions are welcome! Please open an issue or submit a pull request if you would like to improve the project.
|
136 |
+
|
137 |
+
## Fork the repository.
|
138 |
+
Create a new feature branch.
|
139 |
+
Submit your changes via a pull request.
|
140 |
+
License
|
141 |
+
This project is licensed under the MIT License - see the LICENSE file for details.
|
142 |
+
|
143 |
+
## Acknowledgments
|
144 |
+
Hugging Face for the amazing models and NLP tools.
|
145 |
+
Scikit-learn for efficient similarity computation.
|
146 |
+
SQLite for providing a lightweight database solution.
|
falocon_api/__init__.py
ADDED
File without changes
|
falocon_api/embeddingGenerator.py
ADDED
@@ -0,0 +1,101 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
import sqlite3
|
3 |
+
import numpy as np
|
4 |
+
from sentence_transformers import SentenceTransformer
|
5 |
+
from sklearn.metrics.pairwise import cosine_similarity
|
6 |
+
from typing import List, Dict
|
7 |
+
|
8 |
+
class EmbeddingGenerator:
|
9 |
+
def __init__(self, model_name: str = "all-MiniLM-L6-v2", db_path: str = "embeddings.db"):
|
10 |
+
self.model = SentenceTransformer(model_name)
|
11 |
+
self.db_path = db_path
|
12 |
+
self._initialize_db()
|
13 |
+
print(f"Loaded embedding model: {model_name}")
|
14 |
+
|
15 |
+
def _initialize_db(self):
|
16 |
+
# Connect to SQLite database and create table
|
17 |
+
self.conn = sqlite3.connect(self.db_path)
|
18 |
+
self.cursor = self.conn.cursor()
|
19 |
+
self.cursor.execute("""
|
20 |
+
CREATE TABLE IF NOT EXISTS embeddings (
|
21 |
+
filename TEXT PRIMARY KEY,
|
22 |
+
content TEXT,
|
23 |
+
embedding BLOB
|
24 |
+
)
|
25 |
+
""")
|
26 |
+
self.conn.commit()
|
27 |
+
|
28 |
+
def generate_embedding(self, text: str) -> np.ndarray:
|
29 |
+
try:
|
30 |
+
embedding = self.model.encode(text, convert_to_numpy=True)
|
31 |
+
return embedding
|
32 |
+
except Exception as e:
|
33 |
+
print(f"Error generating embedding: {str(e)}")
|
34 |
+
return np.array([])
|
35 |
+
|
36 |
+
def ingest_files(self, directory: str):
|
37 |
+
for filename in os.listdir(directory):
|
38 |
+
if filename.endswith(".txt"):
|
39 |
+
file_path = os.path.join(directory, filename)
|
40 |
+
with open(file_path, 'r') as f:
|
41 |
+
content = f.read()
|
42 |
+
embedding = self.generate_embedding(content)
|
43 |
+
self._store_embedding(filename, content, embedding)
|
44 |
+
|
45 |
+
def _store_embedding(self, filename: str, content: str, embedding: np.ndarray):
|
46 |
+
try:
|
47 |
+
self.cursor.execute("INSERT OR REPLACE INTO embeddings (filename, content, embedding) VALUES (?, ?, ?)",
|
48 |
+
(filename, content, embedding.tobytes()))
|
49 |
+
self.conn.commit()
|
50 |
+
except Exception as e:
|
51 |
+
print(f"Error storing embedding: {str(e)}")
|
52 |
+
|
53 |
+
def load_embeddings(self) -> List[Dict]:
|
54 |
+
self.cursor.execute("SELECT filename, content, embedding FROM embeddings")
|
55 |
+
rows = self.cursor.fetchall()
|
56 |
+
documents = []
|
57 |
+
for filename, content, embedding_blob in rows:
|
58 |
+
embedding = np.frombuffer(embedding_blob, dtype=np.float32)
|
59 |
+
documents.append({"filename": filename, "content": content, "embedding": embedding})
|
60 |
+
return documents
|
61 |
+
|
62 |
+
def compute_similarity(self, query_embedding: np.ndarray, document_embeddings: List[np.ndarray]) -> List[float]:
|
63 |
+
try:
|
64 |
+
similarities = cosine_similarity([query_embedding], document_embeddings)[0]
|
65 |
+
return similarities.tolist()
|
66 |
+
except Exception as e:
|
67 |
+
print(f"Error computing similarity: {str(e)}")
|
68 |
+
return []
|
69 |
+
|
70 |
+
def find_most_similar(self, query: str, top_k: int = 5) -> List[Dict]:
|
71 |
+
query_embedding = self.generate_embedding(query)
|
72 |
+
documents = self.load_embeddings()
|
73 |
+
|
74 |
+
if query_embedding.size == 0 or len(documents) == 0:
|
75 |
+
print("Error: Invalid embeddings or no documents found.")
|
76 |
+
return []
|
77 |
+
|
78 |
+
document_embeddings = [doc["embedding"] for doc in documents]
|
79 |
+
similarities = self.compute_similarity(query_embedding, document_embeddings)
|
80 |
+
ranked_results = sorted(
|
81 |
+
[{"filename": doc["filename"], "content": doc["content"][:100], "similarity": sim}
|
82 |
+
for doc, sim in zip(documents, similarities)],
|
83 |
+
key=lambda x: x["similarity"],
|
84 |
+
reverse=True
|
85 |
+
)
|
86 |
+
return ranked_results[:top_k]
|
87 |
+
|
88 |
+
# Example Usage
|
89 |
+
if __name__ == "__main__":
|
90 |
+
# Initialize the embedding generator and ingest .txt files from the 'documents' directory
|
91 |
+
embedding_generator = EmbeddingGenerator()
|
92 |
+
embedding_generator.ingest_files(os.path.expanduser("~/data-sets/aclImdb/train/"))
|
93 |
+
|
94 |
+
# Perform a search query
|
95 |
+
query = "What can be used for document search?"
|
96 |
+
results = embedding_generator.find_most_similar(query, top_k=3)
|
97 |
+
|
98 |
+
print("Search Results:")
|
99 |
+
for result in results:
|
100 |
+
print(f"Filename: {result['filename']}, Similarity: {result['similarity']:.4f}")
|
101 |
+
print(f"Snippet: {result['content']}\n")
|
falocon_api/embededGeneratorRAG.py
ADDED
@@ -0,0 +1,116 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
import sqlite3
|
3 |
+
import numpy as np
|
4 |
+
from sentence_transformers import SentenceTransformer
|
5 |
+
from sklearn.metrics.pairwise import cosine_similarity
|
6 |
+
from transformers import pipeline
|
7 |
+
from typing import List, Dict
|
8 |
+
|
9 |
+
class EmbeddingGenerator:
|
10 |
+
def __init__(self, model_name: str = "all-MiniLM-L6-v2", gen_model: str = "distilgpt2", db_path: str = "embeddings.db"):
|
11 |
+
self.model = SentenceTransformer(model_name)
|
12 |
+
self.generator = pipeline("text-generation", model=gen_model)
|
13 |
+
self.db_path = db_path
|
14 |
+
self._initialize_db()
|
15 |
+
print(f"Loaded embedding model: {model_name}")
|
16 |
+
print(f"Loaded generative model: {gen_model}")
|
17 |
+
|
18 |
+
def _initialize_db(self):
|
19 |
+
# Connect to SQLite database and create table
|
20 |
+
self.conn = sqlite3.connect(self.db_path)
|
21 |
+
self.cursor = self.conn.cursor()
|
22 |
+
self.cursor.execute("""
|
23 |
+
CREATE TABLE IF NOT EXISTS embeddings (
|
24 |
+
filename TEXT PRIMARY KEY,
|
25 |
+
content TEXT,
|
26 |
+
embedding BLOB
|
27 |
+
)
|
28 |
+
""")
|
29 |
+
self.conn.commit()
|
30 |
+
|
31 |
+
def generate_embedding(self, text: str) -> np.ndarray:
|
32 |
+
try:
|
33 |
+
embedding = self.model.encode(text, convert_to_numpy=True)
|
34 |
+
return embedding
|
35 |
+
except Exception as e:
|
36 |
+
print(f"Error generating embedding: {str(e)}")
|
37 |
+
return np.array([])
|
38 |
+
|
39 |
+
def ingest_files(self, directory: str):
|
40 |
+
for filename in os.listdir(directory):
|
41 |
+
if filename.endswith(".txt"):
|
42 |
+
file_path = os.path.join(directory, filename)
|
43 |
+
with open(file_path, 'r') as f:
|
44 |
+
content = f.read()
|
45 |
+
embedding = self.generate_embedding(content)
|
46 |
+
self._store_embedding(filename, content, embedding)
|
47 |
+
|
48 |
+
def _store_embedding(self, filename: str, content: str, embedding: np.ndarray):
|
49 |
+
try:
|
50 |
+
self.cursor.execute("INSERT OR REPLACE INTO embeddings (filename, content, embedding) VALUES (?, ?, ?)",
|
51 |
+
(filename, content, embedding.tobytes()))
|
52 |
+
self.conn.commit()
|
53 |
+
except Exception as e:
|
54 |
+
print(f"Error storing embedding: {str(e)}")
|
55 |
+
|
56 |
+
def load_embeddings(self) -> List[Dict]:
|
57 |
+
self.cursor.execute("SELECT filename, content, embedding FROM embeddings")
|
58 |
+
rows = self.cursor.fetchall()
|
59 |
+
documents = []
|
60 |
+
for filename, content, embedding_blob in rows:
|
61 |
+
embedding = np.frombuffer(embedding_blob, dtype=np.float32)
|
62 |
+
documents.append({"filename": filename, "content": content, "embedding": embedding})
|
63 |
+
return documents
|
64 |
+
|
65 |
+
def compute_similarity(self, query_embedding: np.ndarray, document_embeddings: List[np.ndarray]) -> List[float]:
|
66 |
+
try:
|
67 |
+
similarities = cosine_similarity([query_embedding], document_embeddings)[0]
|
68 |
+
return similarities.tolist()
|
69 |
+
except Exception as e:
|
70 |
+
print(f"Error computing similarity: {str(e)}")
|
71 |
+
return []
|
72 |
+
|
73 |
+
def find_most_similar(self, query: str, top_k: int = 5) -> List[Dict]:
|
74 |
+
query_embedding = self.generate_embedding(query)
|
75 |
+
documents = self.load_embeddings()
|
76 |
+
|
77 |
+
if query_embedding.size == 0 or len(documents) == 0:
|
78 |
+
print("Error: Invalid embeddings or no documents found.")
|
79 |
+
return []
|
80 |
+
|
81 |
+
document_embeddings = [doc["embedding"] for doc in documents]
|
82 |
+
similarities = self.compute_similarity(query_embedding, document_embeddings)
|
83 |
+
ranked_results = sorted(
|
84 |
+
[{"filename": doc["filename"], "content": doc["content"][:100], "similarity": sim}
|
85 |
+
for doc, sim in zip(documents, similarities)],
|
86 |
+
key=lambda x: x["similarity"],
|
87 |
+
reverse=True
|
88 |
+
)
|
89 |
+
return ranked_results[:top_k]
|
90 |
+
|
91 |
+
def generate_response(self, query: str, top_k_docs: List[str]) -> str:
|
92 |
+
# Combine the query with the retrieved documents for context
|
93 |
+
context = " ".join(top_k_docs)
|
94 |
+
input_text = f"Query: {query}\nContext: {context}\nAnswer:"
|
95 |
+
# Generate a response using the generative model
|
96 |
+
response = self.generator(input_text, max_length=1000, num_return_sequences=1)
|
97 |
+
return response[0]["generated_text"]
|
98 |
+
|
99 |
+
def find_most_similar_and_generate(self, query: str, top_k: int = 5) -> str:
|
100 |
+
top_k_results = self.find_most_similar(query, top_k)
|
101 |
+
top_k_docs = [result["content"] for result in top_k_results]
|
102 |
+
response = self.generate_response(query, top_k_docs)
|
103 |
+
return response
|
104 |
+
|
105 |
+
# Example Usage
|
106 |
+
if __name__ == "__main__":
|
107 |
+
# Initialize the embedding generator with RAG capabilities and ingest .txt files from the 'documents' directory
|
108 |
+
embedding_generator = EmbeddingGenerator()
|
109 |
+
embedding_generator.ingest_files(os.path.expanduser("~/data-sets/aclImdb/train/"))
|
110 |
+
|
111 |
+
# Perform a search query with RAG response generation
|
112 |
+
query = "find user comments tt0118866"
|
113 |
+
response = embedding_generator.find_most_similar_and_generate(query)
|
114 |
+
|
115 |
+
print("Generated Response:")
|
116 |
+
print(response)
|