Spaces:
Running
Running
File size: 13,316 Bytes
42cd5f6 |
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 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 |
from rag.agents.interface import Pipeline
import uuid
import weaviate
from weaviate.util import get_valid_uuid
from unstructured.chunking.title import chunk_by_title
from unstructured.documents.elements import DataSourceMetadata
from unstructured.partition.json import partition_json
from sentence_transformers import SentenceTransformer
from langchain.vectorstores.weaviate import Weaviate
from langchain.prompts import PromptTemplate
from langchain_community.llms import Ollama
import tempfile
import subprocess
import os
from typing import List, Dict
import warnings
import box
import yaml
import timeit
import json
from rich import print
from typing import Any
from rich.progress import Progress, SpinnerColumn, TextColumn
from pydantic.v1 import create_model
warnings.filterwarnings("ignore", category=DeprecationWarning)
warnings.filterwarnings("ignore", category=UserWarning)
# Import config vars
with open('config.yml', 'r', encoding='utf8') as ymlfile:
cfg = box.Box(yaml.safe_load(ymlfile))
class UnstructuredPipeline(Pipeline):
def run_pipeline(self,
payload: str,
query_inputs: [str],
query_types: [str],
keywords: [str],
query: str,
file_path: str,
index_name: str,
options: List[str] = None,
group_by_rows: bool = True,
update_targets: bool = True,
debug: bool = False,
local: bool = True) -> Any:
print(f"\nRunning pipeline with {payload}\n")
if len(query_inputs) == 1:
raise ValueError("Please provide more than one query input")
start = timeit.default_timer()
output_dir = cfg.OUTPUT_DIR_UNSTRUCTURED
input_dir = cfg.INPUT_DIR_UNSTRUCTURED
weaviate_url = cfg.WEAVIATE_URL_UNSTRUCTURED
embedding_model_name = cfg.EMBEDDINGS_UNSTRUCTURED
device = cfg.DEVICE_UNSTRUCTURED
with tempfile.TemporaryDirectory() as temp_dir:
temp_input_dir = os.path.join(temp_dir, input_dir)
temp_output_dir = os.path.join(temp_dir, output_dir) if debug is False else output_dir
if debug:
print(f"Copying {file_path} to {temp_input_dir}")
os.makedirs(temp_input_dir, exist_ok=True)
os.system(f"cp {file_path} {temp_input_dir}")
os.makedirs(temp_output_dir, exist_ok=True)
files = self.invoke_pipeline_step(
lambda: self.process_files(temp_output_dir, temp_input_dir),
"Processing file with unstructured...",
local
)
vectorstore, embedding_model = self.invoke_pipeline_step(
lambda: self.build_vector_store(weaviate_url, embedding_model_name, device, files, debug),
"Building vector store...",
local
)
llm = self.invoke_pipeline_step(
lambda: Ollama(model=cfg.LLM_UNSTRUCTURED,
base_url=cfg.BASE_URL_UNSTRUCTURED),
"Initializing Ollama...",
local
)
raw_result, similar_docs = self.invoke_pipeline_step(
lambda: self.question_answer(query, vectorstore, embedding_model, device, llm),
"Answering question...",
local
)
answer = self.invoke_pipeline_step(
lambda: self.validate_output(raw_result, query_inputs, query_types),
"Validating output...",
local
)
if debug:
print("\n\n\n-------------------------")
print(f"QUERY: {query}")
print("\n\n\n-------------------------")
print(f"Answer: {answer}")
print("\n\n\n-------------------------")
for index, result in enumerate(similar_docs):
print(f"\n\n-- RESULT {index + 1}:\n")
print(result)
end = timeit.default_timer()
print(f"\nJSON response:\n")
print(answer + '\n')
print('=' * 50)
print(f"Time to retrieve answer: {end - start}")
return answer
def process_files(self, temp_output_dir, temp_input_dir):
self.process_local(output_dir=temp_output_dir, num_processes=2, input_path=temp_input_dir)
files = self.get_result_files(temp_output_dir)
return files
def build_vector_store(self, weaviate_url, embedding_model_name, device, files, debug):
client = self.create_local_weaviate_client(db_url=weaviate_url)
my_schema = self.get_schema()
self.upload_schema(my_schema, weaviate=client)
vectorstore = Weaviate(client, "Doc", "text")
embedding_model = SentenceTransformer(embedding_model_name, device=device)
self.add_data_to_weaviate(
debug,
files=files,
client=client,
embedding_model=embedding_model,
device=device,
chunk_under_n_chars=cfg.CHUNK_UNDER_N_CHARS_UNSTRUCTURED,
chunk_new_after_n_chars=cfg.CHUNK_NEW_AFTER_N_CHARS_UNSTRUCTURED
)
if debug:
print(self.count_documents(client=client)['data']['Aggregate']['Doc'])
return vectorstore, embedding_model
def process_local(self, output_dir: str, num_processes: int, input_path: str):
command = [
"unstructured-ingest",
"local",
"--input-path", input_path,
"--output-dir", output_dir,
"--num-processes", str(num_processes),
"--recursive",
"--verbose",
]
# Run the command
process = subprocess.Popen(command, stdout=subprocess.PIPE)
output, error = process.communicate()
# Print output
if process.returncode == 0:
print('Command executed successfully. Output:')
print(output.decode())
else:
print('Command failed. Error:')
print(error.decode())
def get_result_files(self, folder_path) -> List[Dict]:
file_list = []
for root, dirs, files in os.walk(folder_path):
for file in files:
if file.endswith('.json'):
file_path = os.path.join(root, file)
file_list.append(file_path)
return file_list
def create_local_weaviate_client(self, db_url: str):
return weaviate.Client(
url=db_url,
)
def get_schema(self, vectorizer: str = "none"):
return {
"classes": [
{
"class": "Doc",
"description": "A generic document class",
"vectorizer": vectorizer,
"properties": [
{
"name": "last_modified",
"dataType": ["text"],
"description": "Last modified date for the document",
},
{
"name": "player",
"dataType": ["text"],
"description": "Player related to the document",
},
{
"name": "position",
"dataType": ["text"],
"description": "Player Position related to the document",
},
{
"name": "text",
"dataType": ["text"],
"description": "Text content for the document",
},
],
},
],
}
def upload_schema(self, my_schema, weaviate):
weaviate.schema.delete_all()
weaviate.schema.create(my_schema)
def count_documents(self, client: weaviate.Client) -> Dict:
response = (
client.query
.aggregate("Doc")
.with_meta_count()
.do()
)
count = response
return count
def compute_embedding(self, chunk_text: List[str], embedding_model, device):
embeddings = embedding_model.encode(chunk_text, device=device)
return embeddings
def get_chunks(self, elements, embedding_model, device, chunk_under_n_chars=500, chunk_new_after_n_chars=1500):
for element in elements:
if not type(element.metadata.data_source) is DataSourceMetadata:
delattr(element.metadata, "data_source")
if hasattr(element.metadata, "coordinates"):
delattr(element.metadata, "coordinates")
chunks = chunk_by_title(
elements,
combine_text_under_n_chars=chunk_under_n_chars,
new_after_n_chars=chunk_new_after_n_chars
)
for i in range(len(chunks)):
chunks[i] = {"last_modified": chunks[i].metadata.last_modified, "text": chunks[i].text}
chunk_texts = [x['text'] for x in chunks]
embeddings = self.compute_embedding(chunk_texts, embedding_model, device)
return chunks, embeddings
def add_data_to_weaviate(self, debug, files, client, embedding_model, device, chunk_under_n_chars=500, chunk_new_after_n_chars=1500):
for filename in files:
try:
elements = partition_json(filename=filename)
chunks, embeddings = self.get_chunks(elements, embedding_model, device, chunk_under_n_chars, chunk_new_after_n_chars)
except IndexError as e:
print(e)
continue
if debug:
print(f"Uploading {len(chunks)} chunks for {str(filename)}.")
for i, chunk in enumerate(chunks):
client.batch.add_data_object(
data_object=chunk,
class_name="doc",
uuid=get_valid_uuid(uuid.uuid4()),
vector=embeddings[i]
)
client.batch.flush()
def question_answer(self, question: str, vectorstore: Weaviate, embedding_model, device, llm):
embedding = self.compute_embedding(question, embedding_model, device)
similar_docs = vectorstore.max_marginal_relevance_search_by_vector(embedding)
content = [x.page_content for x in similar_docs]
prompt_template = PromptTemplate.from_template(
"""\
Given context about the subject, answer the question based on the context provided to the best of your ability.
Context: {context}
Question:
{question}
Answer:
"""
)
prompt = prompt_template.format(context=content, question=question)
answer = llm(prompt)
return answer, similar_docs
def validate_output(self, raw_result, query_inputs, query_types):
if raw_result is None:
return {}
clean_str = raw_result.replace('<|im_end|>', '')
# Convert the cleaned string to a dictionary
response_dict = json.loads(clean_str)
ResponseModel = self.build_response_class(query_inputs, query_types)
# Validate and create a Pydantic model instance
validated_response = ResponseModel(**response_dict)
# Convert the model instance to JSON
answer = self.beautify_json(validated_response.json())
return answer
def safe_eval_type(self, type_str, context):
try:
return eval(type_str, {}, context)
except NameError:
raise ValueError(f"Type '{type_str}' is not recognized")
def build_response_class(self, query_inputs, query_types_as_strings):
# Controlled context for eval
context = {
'List': List,
'str': str,
'int': int,
'float': float
# Include other necessary types or typing constructs here
}
# Convert string representations to actual types
query_types = [self.safe_eval_type(type_str, context) for type_str in query_types_as_strings]
# Create fields dictionary
fields = {name: (type_, ...) for name, type_ in zip(query_inputs, query_types)}
DynamicModel = create_model('DynamicModel', **fields)
return DynamicModel
def beautify_json(self, result):
try:
# Convert and pretty print
data = json.loads(str(result))
data = json.dumps(data, indent=4)
return data
except (json.decoder.JSONDecodeError, TypeError):
print("The response is not in JSON format:\n")
print(result)
return {}
def invoke_pipeline_step(self, task_call, task_description, local):
if local:
with Progress(
SpinnerColumn(),
TextColumn("[progress.description]{task.description}"),
transient=False,
) as progress:
progress.add_task(description=task_description, total=None)
ret = task_call()
else:
print(task_description)
ret = task_call()
return ret
|