Spaces:
Running
Running
File size: 8,419 Bytes
ac5ddf6 |
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 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 |
import weaviate
from sentence_transformers import SentenceTransformer
from langchain_community.document_loaders import BSHTMLLoader
from pathlib import Path
from lxml import html
import logging
from semantic_text_splitter import HuggingFaceTextSplitter
from tokenizers import Tokenizer
import json
import os
import re
import logging
weaviate_logger = logging.getLogger("httpx")
weaviate_logger.setLevel(logging.WARNING)
logger = logging.getLogger(__name__)
logging.basicConfig(level=logging.INFO)
######################################################################
# MAINLINE
#
logger.info("#### MAINLINE ENTERED.")
#pathString = "/Users/660565/KPSAllInOne/ProgramFilesX86/WebCopy/DownloadedWebSites/LLMPOC_HTML"
pathString = "/app/inputDocs"
chunks = []
webpageDocNames = []
page_contentArray = []
webpageChunks = []
webpageTitles = []
webpageChunksDocNames = []
#######################################################
# Read each text input file, parse it into a document,
# chunk it, collect chunks and document name.
logger.info("#### Read and chunk input text files.")
for filename in os.listdir(pathString):
logger.info(filename)
path = Path(pathString + "/" + filename)
filename = filename.rstrip(".html")
webpageDocNames.append(filename)
htmlLoader = BSHTMLLoader(path,"utf-8")
htmlData = htmlLoader.load()
title = htmlData[0].metadata['title']
page_content = htmlData[0].page_content
# Clean data. Remove multiple newlines, etc.
page_content = re.sub(r'\n+', '\n',page_content)
page_contentArray.append(page_content);
webpageTitles.append(title)
max_tokens = 1000
tokenizer = Tokenizer.from_pretrained("bert-base-uncased")
logger.debug(f"### tokenizer: {tokenizer}")
splitter = HuggingFaceTextSplitter(tokenizer, trim_chunks=True)
chunksOnePage = splitter.chunks(page_content, chunk_capacity=50)
chunks = []
for chnk in chunksOnePage:
logger.debug(f"#### chnk in file: {chnk}")
chunks.append(chnk)
logger.debug(f"chunks: {chunks}")
webpageChunks.append(chunks)
webpageChunksDocNames.append(filename + "Chunks")
logger.debug(f"### filename, title: {filename}, {title}")
logger.debug(f"### webpageDocNames: {webpageDocNames}")
######################################################
# Connect to the Weaviate vector database.
logger.info("#### Create Weaviate db client connection.")
client = weaviate.connect_to_custom(
http_host="127.0.0.1",
http_port=8080,
http_secure=False,
grpc_host="127.0.0.1",
grpc_port=50051,
grpc_secure=False
#read_timeout=600,
#write_timeout=90
)
client.connect()
######################################################
# Create database webpage and chunks collections.
#wpCollection = createWebpageCollection()
#wpChunkCollection = createChunksCollection()
logger.info("#### createWebpageCollection() entered.")
if client.collections.exists("Documents"):
client.collections.delete("Documents")
class_obj = {
"class": "Documents",
"description": "For first attempt at loading a Weviate database.",
"vectorizer": "text2vec-transformers",
"moduleConfig": {
"text2vec-transformers": {
"vectorizeClassName": False
}
},
"vectorIndexType": "hnsw",
"vectorIndexConfig": {
"distance": "cosine",
},
"properties": [
{
"name": "title",
"dataType": ["text"],
"description": "HTML doc title.",
"vectorizer": "text2vec-transformers",
"moduleConfig": {
"text2vec-transformers": {
"vectorizePropertyName": True,
"skip": False,
"tokenization": "lowercase"
}
},
"invertedIndexConfig": {
"bm25": {
"b": 0.75,
"k1": 1.2
},
}
},
{
"name": "content",
"dataType": ["text"],
"description": "HTML page content.",
"moduleConfig": {
"text2vec-transformers": {
"vectorizePropertyName": True,
"tokenization": "whitespace"
}
}
}
]
}
wpCollection = client.collections.create_from_dict(class_obj)
logger.info("#### createChunksCollection() entered.")
if client.collections.exists("Chunks"):
client.collections.delete("Chunks")
class_obj = {
"class": "Chunks",
"description": "Collection for document chunks.",
"vectorizer": "text2vec-transformers",
"moduleConfig": {
"text2vec-transformers": {
"vectorizeClassName": True
}
},
"vectorIndexType": "hnsw",
"vectorIndexConfig": {
"distance": "cosine",
},
"properties": [
{
"name": "chunk",
"dataType": ["text"],
"description": "Single webpage chunk.",
"vectorizer": "text2vec-transformers",
"moduleConfig": {
"text2vec-transformers": {
"vectorizePropertyName": False,
"skip": False,
"tokenization": "lowercase"
}
}
},
{
"name": "chunk_index",
"dataType": ["int"]
},
{
"name": "webpage",
"dataType": ["Documents"],
"description": "Webpage content chunks.",
"invertedIndexConfig": {
"bm25": {
"b": 0.75,
"k1": 1.2
}
}
}
]
}
wpChunkCollection = client.collections.create_from_dict(class_obj)
###########################################################
# Create document and chunks objects in the database.
logger.info("#### Create page/doc and chunk db objects.")
for i, className in enumerate(webpageDocNames):
title = webpageTitles[i]
logger.debug(f"## className, title: {className}, {title}")
# Create Webpage Object
page_content = page_contentArray[i]
# Insert the document.
wpCollectionObj_uuid = wpCollection.data.insert(
{
"name": className,
"title": title,
"content": page_content
}
)
# Insert the chunks for the document.
for i2, chunk in enumerate(webpageChunks[i]):
chunk_uuid = wpChunkCollection.data.insert(
{
"title": title,
"chunk": chunk,
"chunk_index": i2,
"references":
{
"webpage": wpCollectionObj_uuid
}
}
)
###############################################################################
# text contains prompt for vector DB.
text = "human-made computer cognitive ability"
###############################################################################
# Initial the the sentence transformer and encode the query prompt.
logger.info(f"#### Encode text query prompt to create vectors. {text}")
model = SentenceTransformer('/app/multi-qa-MiniLM-L6-cos-v1')
vector = model.encode(text)
vectorList = []
logger.debug("#### Print vectors.")
for vec in vector:
vectorList.append(vec)
logger.debug(f"vectorList: {vectorList[2]}")
# Fetch chunks and print chunks.
logger.info("#### Retrieve semchunks from db using vectors from prompt.")
semChunks = wpChunkCollection.query.near_vector(
near_vector=vectorList,
distance=0.7,
limit=3
)
logger.debug(f"### semChunks[0]: {semChunks}")
# Print chunks, corresponding document and document title.
logger.info("#### Print individual retrieved chunks.")
for chunk in enumerate(semChunks.objects):
logger.info(f"#### chunk: {chunk}")
webpage_uuid = chunk[1].properties['references']['webpage']
logger.info(f"webpage_uuid: {webpage_uuid}")
wpFromChunk = wpCollection.query.fetch_object_by_id(webpage_uuid)
logger.info(f"### wpFromChunk title: {wpFromChunk.properties['title']}")
logger.info("#### Closing client db connection.")
client.close()
logger.info("#### Program terminating.")
|