import clip import faiss from PIL import Image from pypdf import PdfReader import pandas as pd import re import os import fitz import torch import numpy as np from tqdm import tqdm import base64 import json class RAG: def __init__( self, fais_index_path, clip_model="ViT-B/32", reranker=None, device="cpu", image_invoice_index_path=None, path_to_invoices=None, path_to_images=None, path_to_invoice_json=None ): self.index = faiss.read_index(fais_index_path) self.model, self.preprocess = clip.load(clip_model, device=device) self.device = device if image_invoice_index_path: self.image_invoice_index = pd.read_csv(image_invoice_index_path) self.path_to_invoices = path_to_invoices self.path_to_images = path_to_images self.reranker = reranker if path_to_invoice_json: with open(path_to_invoice_json, "r") as f: self.invoice_json = json.load(f) @staticmethod def image_to_base64(image_path): with open(image_path, "rb") as image_file: return base64.b64encode(image_file.read()) def search_text(self, text, k=1): text_features = self.model.encode_text(clip.tokenize([text]).to(self.device)) text_features /= text_features.norm(dim=-1, keepdim=True) text_features = text_features.detach().numpy() distances, indices = self.index.search(text_features, k) return distances, indices def search_image(self, image=None, image_path=None, k=1): if image is None and image_path is None: raise ValueError("Either image or image_path must be provided.") if image is None: image = Image.open(image_path) image_input = self.preprocess(image).unsqueeze(0).to(self.device) image_features = self.model.encode_image(image_input) image_features /= image_features.norm(dim=-1, keepdim=True) image_features = image_features.detach().numpy() distances, indices = self.index.search(image_features, k) return distances, indices def return_invoice_table(self, path=None, invoice_is_table=True): if path is None and not invoice_is_table: raise ValueError("Path to invoice must be provided.") if self.invoice_json is None and invoice_is_table: raise ValueError("Path to invoice json must be provided.") if invoice_is_table: return self.invoice_json[path] pdf_path = f"{self.path_to_invoices}/{path}" reader = PdfReader(pdf_path) page = reader.pages[0] text = page.extract_text() table_text = re.search(r"Beschädigtes Teil.*?Gesamtsumme:.*?EUR", text, re.DOTALL).group() lines = table_text.splitlines() header = lines[0] other_text = "\n".join(lines[1:]) cleaned_text = re.sub(r"(?