Spaces:
No application file
No application file
Delete app.py
Browse files
app.py
DELETED
|
@@ -1,265 +0,0 @@
|
|
| 1 |
-
|
| 2 |
-
import json
|
| 3 |
-
import chromadb
|
| 4 |
-
from pprint import pprint
|
| 5 |
-
from dotenv import load_dotenv
|
| 6 |
-
import chromadb.utils.embedding_functions as embedding_functions
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
def append_to_jsonl(data, file_path='results.jsonl'):
|
| 10 |
-
"""
|
| 11 |
-
Appends a dictionary as a JSON object to a JSONL file.
|
| 12 |
-
|
| 13 |
-
Args:
|
| 14 |
-
file_path (str): Path to the JSONL file.
|
| 15 |
-
data (dict): Dictionary to be appended to the file.
|
| 16 |
-
"""
|
| 17 |
-
try:
|
| 18 |
-
with open(file_path, 'a') as file: # Open file in append mode
|
| 19 |
-
json_line = json.dumps(data) # Convert dict to JSON string
|
| 20 |
-
file.write(json_line + '\n') # Write JSON string with newline
|
| 21 |
-
print(f"Appended to JSONL file: {file_path}")
|
| 22 |
-
except Exception as e:
|
| 23 |
-
print(f"Error appending to JSONL file: {e}")
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
def query_openai_database(query_text, collection_name, n_results=5, extract_length=500):
|
| 27 |
-
"""
|
| 28 |
-
Query the vector database and return relevant documents with extracts
|
| 29 |
-
"""
|
| 30 |
-
# Load environment variables
|
| 31 |
-
load_dotenv()
|
| 32 |
-
OPENAI_API_KEY = "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"
|
| 33 |
-
api_key = OPENAI_API_KEY
|
| 34 |
-
|
| 35 |
-
db_path = f"/Users/sid10/PycharmProjects/VectorEmbeddings/Embeddings/{collection_name}"
|
| 36 |
-
|
| 37 |
-
# Initialize ChromaDB client
|
| 38 |
-
client = chromadb.PersistentClient(
|
| 39 |
-
path=db_path
|
| 40 |
-
)
|
| 41 |
-
|
| 42 |
-
# Set up embedding function
|
| 43 |
-
embedding_fn = embedding_functions.OpenAIEmbeddingFunction(
|
| 44 |
-
api_key=api_key,
|
| 45 |
-
model_name="text-embedding-3-large"
|
| 46 |
-
)
|
| 47 |
-
|
| 48 |
-
try:
|
| 49 |
-
# Get the collection
|
| 50 |
-
collection = client.get_collection(
|
| 51 |
-
name=collection_name,
|
| 52 |
-
embedding_function=embedding_fn
|
| 53 |
-
)
|
| 54 |
-
|
| 55 |
-
# Perform the query
|
| 56 |
-
results = collection.query(
|
| 57 |
-
query_texts=[query_text],
|
| 58 |
-
n_results=n_results,
|
| 59 |
-
include=['metadatas', 'distances', 'documents']
|
| 60 |
-
)
|
| 61 |
-
|
| 62 |
-
# Format results with text extracts
|
| 63 |
-
formatted_results = []
|
| 64 |
-
for i in range(len(results['documents'][0])):
|
| 65 |
-
document_text = results['documents'][0][i]
|
| 66 |
-
|
| 67 |
-
# Get text extract around the query
|
| 68 |
-
text_extract = get_relevant_extract(document_text, query_text, extract_length)
|
| 69 |
-
|
| 70 |
-
# Calculate similarity score (convert distance to similarity)
|
| 71 |
-
similarity = 1 - float(results['distances'][0][i])
|
| 72 |
-
|
| 73 |
-
# Create result dictionary with safe metadata handling
|
| 74 |
-
result_dict = {
|
| 75 |
-
'rank': i + 1,
|
| 76 |
-
'id': results['ids'][0][i],
|
| 77 |
-
'similarity': similarity,
|
| 78 |
-
# 'full_document': document_text,
|
| 79 |
-
'text_extract': text_extract
|
| 80 |
-
}
|
| 81 |
-
|
| 82 |
-
# Safely add metadata if it exists
|
| 83 |
-
if 'metadatas' in results and results['metadatas'] and results['metadatas'][0]:
|
| 84 |
-
result_dict['metadata'] = results['metadatas'][0][i]
|
| 85 |
-
else:
|
| 86 |
-
result_dict['metadata'] = {} # Empty dict if no metadata
|
| 87 |
-
|
| 88 |
-
formatted_results.append(result_dict)
|
| 89 |
-
|
| 90 |
-
return formatted_results
|
| 91 |
-
|
| 92 |
-
except Exception as e:
|
| 93 |
-
print(f"Query error: {str(e)}")
|
| 94 |
-
return []
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
def get_relevant_extract(text, query, length=500):
|
| 98 |
-
"""
|
| 99 |
-
Get a relevant extract from the text around query terms
|
| 100 |
-
"""
|
| 101 |
-
try:
|
| 102 |
-
# Convert to lowercase for case-insensitive search
|
| 103 |
-
text_lower = text.lower()
|
| 104 |
-
query_lower = query.lower()
|
| 105 |
-
|
| 106 |
-
# Split query into terms and find their positions
|
| 107 |
-
query_terms = query_lower.split()
|
| 108 |
-
positions = []
|
| 109 |
-
|
| 110 |
-
for term in query_terms:
|
| 111 |
-
pos = text_lower.find(term)
|
| 112 |
-
if pos != -1:
|
| 113 |
-
positions.append(pos)
|
| 114 |
-
|
| 115 |
-
if positions:
|
| 116 |
-
# Calculate the center position of found terms
|
| 117 |
-
center_pos = sum(positions) // len(positions)
|
| 118 |
-
|
| 119 |
-
# Calculate extract boundaries
|
| 120 |
-
start = max(0, center_pos - length // 2)
|
| 121 |
-
end = min(len(text), center_pos + length // 2)
|
| 122 |
-
|
| 123 |
-
# Adjust boundaries to avoid cutting words
|
| 124 |
-
while start > 0 and text[start] != ' ':
|
| 125 |
-
start -= 1
|
| 126 |
-
while end < len(text) and text[end] != ' ':
|
| 127 |
-
end += 1
|
| 128 |
-
|
| 129 |
-
# Get the extract
|
| 130 |
-
extract = text[start:end].strip()
|
| 131 |
-
|
| 132 |
-
# Add ellipsis where appropriate
|
| 133 |
-
if start > 0:
|
| 134 |
-
extract = f"...{extract}"
|
| 135 |
-
if end < len(text):
|
| 136 |
-
extract = f"{extract}..."
|
| 137 |
-
|
| 138 |
-
return extract
|
| 139 |
-
|
| 140 |
-
# If no query terms found, return the beginning of the text
|
| 141 |
-
return f"{text[:length].strip()}..."
|
| 142 |
-
|
| 143 |
-
except Exception as e:
|
| 144 |
-
print(f"Extract error: {str(e)}")
|
| 145 |
-
return text[:length] + "..." # Fallback to simple truncation
|
| 146 |
-
|
| 147 |
-
|
| 148 |
-
def print_search_results(query_text, collection_name, n_results=5, extract_length=500):
|
| 149 |
-
"""
|
| 150 |
-
Perform a search and print results in a formatted way
|
| 151 |
-
"""
|
| 152 |
-
try:
|
| 153 |
-
results = query_openai_database(
|
| 154 |
-
query_text=query_text,
|
| 155 |
-
collection_name = collection_name,
|
| 156 |
-
n_results=n_results,
|
| 157 |
-
extract_length=extract_length
|
| 158 |
-
)
|
| 159 |
-
|
| 160 |
-
if not results:
|
| 161 |
-
print("No results found.")
|
| 162 |
-
return
|
| 163 |
-
|
| 164 |
-
print(f"\nSearch Results for: '{query_text}'")
|
| 165 |
-
print(f"Found {len(results)} matches\n")
|
| 166 |
-
print("=" * 80)
|
| 167 |
-
|
| 168 |
-
for result in results:
|
| 169 |
-
print(f"\nRank {result['rank']}:")
|
| 170 |
-
print(f"ID: {result['id']}")
|
| 171 |
-
print(f"Similarity Score: {result['similarity']:.4f}")
|
| 172 |
-
|
| 173 |
-
# Safely handle metadata
|
| 174 |
-
if result.get('metadata'):
|
| 175 |
-
if 'added_date' in result['metadata']:
|
| 176 |
-
print(f"Added: {result['metadata']['added_date']}")
|
| 177 |
-
if 'source' in result['metadata']:
|
| 178 |
-
print(f"Source: {result['metadata']['source']}")
|
| 179 |
-
|
| 180 |
-
print("\nRelevant Extract:")
|
| 181 |
-
print("-" * 40)
|
| 182 |
-
print(result['text_extract'])
|
| 183 |
-
print("-" * 40)
|
| 184 |
-
print(f"Full Document Length: {len(result['full_document'])} characters")
|
| 185 |
-
print("=" * 80)
|
| 186 |
-
|
| 187 |
-
except Exception as e:
|
| 188 |
-
print(f"Error printing results: {str(e)}")
|
| 189 |
-
# Print the full result for debugging
|
| 190 |
-
print("Debug - Result structure:")
|
| 191 |
-
for result in results:
|
| 192 |
-
print(result.keys())
|
| 193 |
-
|
| 194 |
-
|
| 195 |
-
# Example usage
|
| 196 |
-
def query(query_text, n_results=6, extract_length=1000) -> dict:
|
| 197 |
-
|
| 198 |
-
res = {
|
| 199 |
-
'query': query_text,
|
| 200 |
-
'results': []
|
| 201 |
-
}
|
| 202 |
-
|
| 203 |
-
try:
|
| 204 |
-
# Example searches
|
| 205 |
-
# print_search_results(query_text="What is the greatest common divisor?", collection_name = 'bmc_videos_knowledge_base', n_results=3, extract_length=500)
|
| 206 |
-
|
| 207 |
-
collection_name = 'bmc_videos_knowledge_base_v1'
|
| 208 |
-
|
| 209 |
-
# You can also get the results programmatically
|
| 210 |
-
results = query_openai_database(
|
| 211 |
-
query_text=query_text,
|
| 212 |
-
collection_name=collection_name,
|
| 213 |
-
n_results=n_results,
|
| 214 |
-
extract_length=extract_length
|
| 215 |
-
)
|
| 216 |
-
|
| 217 |
-
# Process results programmatically
|
| 218 |
-
mid_list_grade1 = []
|
| 219 |
-
mid_list_grade2 = []
|
| 220 |
-
mid_list = []
|
| 221 |
-
|
| 222 |
-
for result in results:
|
| 223 |
-
# Access individual fields
|
| 224 |
-
doc_id = result.get('id', None)
|
| 225 |
-
similarity = result.get('similarity', -1)
|
| 226 |
-
extract = result.get('text_extract', None)
|
| 227 |
-
full_text = result.get('full_document', None)
|
| 228 |
-
metadata = result.get('metadata', {})
|
| 229 |
-
|
| 230 |
-
mid = metadata.get('MID', '')
|
| 231 |
-
video_name = metadata.get('Video Name', '')
|
| 232 |
-
chapter_name = metadata.get('Chapter Name', '')
|
| 233 |
-
mid_video_chapter_name = mid + " " + video_name + f" ({chapter_name})" if mid else video_name
|
| 234 |
-
|
| 235 |
-
# Do something with the results...
|
| 236 |
-
rag = { 'id': doc_id, 'extract': extract, 'similarity': similarity, 'metadata': metadata }
|
| 237 |
-
|
| 238 |
-
mid_list.append(mid_video_chapter_name)
|
| 239 |
-
|
| 240 |
-
if similarity > 0:
|
| 241 |
-
mid_list_grade1.append(mid)
|
| 242 |
-
else:
|
| 243 |
-
mid_list_grade2.append(mid)
|
| 244 |
-
|
| 245 |
-
res['results'].append(rag)
|
| 246 |
-
|
| 247 |
-
res['videos'] = ' | '.join(mid_list) if mid_list else None
|
| 248 |
-
res['similarity_positive'] = ', '.join(mid_list_grade1) if mid_list_grade1 else None
|
| 249 |
-
res['similarity_negative'] = ', '.join(mid_list_grade2) if mid_list_grade2 else None
|
| 250 |
-
|
| 251 |
-
except Exception as e:
|
| 252 |
-
res['error'] = e
|
| 253 |
-
|
| 254 |
-
finally:
|
| 255 |
-
return res
|
| 256 |
-
|
| 257 |
-
|
| 258 |
-
if __name__ == "__main__":
|
| 259 |
-
|
| 260 |
-
query_text = "Factor Pairs of a Number"
|
| 261 |
-
result = query(query_text, n_results=6)
|
| 262 |
-
|
| 263 |
-
# Append the result to the JSONL file
|
| 264 |
-
append_to_jsonl(result)
|
| 265 |
-
pprint(result)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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