|
from typing import TYPE_CHECKING, Any, Callable, Dict, List, Tuple, Type |
|
import logging |
|
import json |
|
import os |
|
import pickle |
|
from datetime import datetime |
|
import hashlib |
|
import csv |
|
import requests |
|
import re |
|
import html |
|
import markdown2 |
|
import torch |
|
import sys |
|
import gc |
|
from pygments.lexers import guess_lexer, ClassNotFound |
|
import time |
|
import json |
|
import base64 |
|
from io import BytesIO |
|
import urllib.parse |
|
import tempfile |
|
import uuid |
|
|
|
from transformers import pipeline, AutoModelForSeq2SeqLM, AutoTokenizer, AutoModelForCausalLM, GPTNeoForCausalLM, GPT2Tokenizer, DistilBertTokenizer, DistilBertForQuestionAnswering |
|
from sentence_transformers import SentenceTransformer, util |
|
from huggingface_hub import HfApi, hf_hub_download |
|
from typing import List, Dict |
|
|
|
import gradio as gr |
|
from pypinyin import lazy_pinyin |
|
import tiktoken |
|
import mdtex2html |
|
from markdown import markdown |
|
|
|
|
|
|
|
|
|
from langchain.chains import LLMChain, RetrievalQA |
|
from langchain.prompts import PromptTemplate |
|
from langchain_community.document_loaders import PyPDFLoader, UnstructuredWordDocumentLoader, DirectoryLoader |
|
|
|
|
|
from langchain.schema import AIMessage, HumanMessage, Document |
|
|
|
|
|
|
|
from langchain_huggingface import HuggingFaceEmbeddings |
|
|
|
from typing import Dict, TypedDict |
|
from langchain_core.messages import BaseMessage |
|
from langchain.prompts import PromptTemplate |
|
|
|
from langchain_community.vectorstores import Chroma |
|
from langchain_core.messages import BaseMessage, FunctionMessage |
|
from langchain_core.output_parsers import StrOutputParser |
|
from langchain_core.pydantic_v1 import BaseModel, Field |
|
from langchain_core.runnables import RunnablePassthrough, RunnableSequence |
|
from langchain.text_splitter import RecursiveCharacterTextSplitter |
|
from chromadb.errors import InvalidDimensionException |
|
import fitz |
|
import docx |
|
from huggingface_hub import hf_hub_download, list_repo_files |
|
|
|
|
|
|
|
|
|
|
|
import nltk |
|
from nltk.corpus import stopwords |
|
from nltk.tokenize import word_tokenize |
|
from nltk.stem import WordNetLemmatizer, PorterStemmer |
|
from nltk.tokenize import RegexpTokenizer |
|
from transformers import BertModel, BertTokenizer, pipeline |
|
from nltk.stem.snowball import SnowballStemmer |
|
|
|
from sklearn.feature_extraction.text import TfidfVectorizer |
|
from sklearn.metrics.pairwise import cosine_similarity |
|
import numpy as np |
|
|
|
|
|
nltk.download('punkt') |
|
nltk.download('stopwords') |
|
german_stopwords = set(stopwords.words('german')) |
|
|
|
|
|
ANZAHL_DOCS = 5 |
|
|
|
REPO_ID = "alexkueck/kkg_suche" |
|
STORAGE_REPO_ID = "alexkueck/kkg_files" |
|
REPO_TYPE = "space" |
|
|
|
|
|
|
|
HUGGINGFACEHUB_API_TOKEN = os.getenv("HF_READ") |
|
os.environ["HUGGINGFACEHUB_API_TOKEN"] = HUGGINGFACEHUB_API_TOKEN |
|
HEADERS = {"Authorization": f"Bearer {HUGGINGFACEHUB_API_TOKEN}"} |
|
|
|
hf_token = os.getenv("HF_READ") |
|
HF_WRITE = os.getenv("HF_WRITE") |
|
|
|
api = HfApi() |
|
|
|
|
|
try: |
|
repo_info = api.list_repo_files(repo_id=STORAGE_REPO_ID, repo_type=REPO_TYPE, token=hf_token) |
|
print(f"Repository '{STORAGE_REPO_ID}' enthält folgende Dateien: {repo_info}") |
|
except Exception as e: |
|
print(f"Fehler beim Zugriff auf das Repository: {e}") |
|
|
|
|
|
|
|
|
|
|
|
|
|
split_to_original_mapping = [] |
|
|
|
|
|
|
|
|
|
|
|
|
|
template = """\Antworte in deutsch, wenn es nicht explizit anders gefordert wird. Wenn du die Antwort nicht kennst, antworte direkt, dass du es nicht weißt. |
|
Antworte nur zu dem mitgelieferten Text. Fasse die einzelnen Text-Ausschnitte zusammen zu einem Text, gehe dabei auf jeden Textausschnitt ein.""" |
|
|
|
llm_template = "Beantworte die Frage am Ende. " + template + "Frage: {question} " |
|
|
|
llm_template2 = "Fasse folgenden Text als Überschrift mit maximal 3 Worten zusammen. Text: {question} " |
|
|
|
rag_template = "Nutze ausschließlich die folgenden Kontexte (Beginnend mit dem Wort 'Kontext:') aus Teilen aus den angehängten Dokumenten, um die Frage (Beginnend mit dem Wort 'Frage: ') am Ende zu beantworten. Wenn du die Frage aus dem folgenden Kontext nicht beantworten kannst, sage, dass du keine passende Antwort gefunden hast. Wenn du dich auf den angegebenen Kontext beziehst, gib unbedingt den Namen des Dokumentes an, auf den du dich beziehst. Antworte nur zu dem mitgelieferten Text. Fasse die einzelnen Text-Ausschnitte zusammen zu einem Text, gehe dabei auf jeden Textausschnitt ein. Formuliere wichtige Punkte ausführlich aus." + template + "Kontext: {context} Frage: {question}" |
|
|
|
|
|
|
|
LLM_CHAIN_PROMPT = PromptTemplate(input_variables = ["question"], |
|
template = llm_template) |
|
|
|
LLM_CHAIN_PROMPT2 = PromptTemplate(input_variables = ["question"], |
|
template = llm_template2) |
|
|
|
RAG_CHAIN_PROMPT = PromptTemplate(input_variables = ["context", "question"], |
|
template = rag_template) |
|
|
|
|
|
|
|
PATH_WORK = "." |
|
CHROMA_DIR = "/chroma/kkg" |
|
CHROMA_PDF = './chroma/kkg/pdf' |
|
CHROMA_WORD = './chroma/kkg/word' |
|
CHROMA_EXCEL = './chroma/kkg/excel' |
|
YOUTUBE_DIR = "/youtube" |
|
HISTORY_PFAD = "/data/history" |
|
DOCS_DIR_PDF = "chroma/kkg/pdf" |
|
DOCS_DIR_WORD = "chroma/kkg/word" |
|
VECTORSTORE_DIR="chroma/kkg" |
|
|
|
|
|
|
|
PDF_URL = "https://arxiv.org/pdf/2303.08774.pdf" |
|
WEB_URL = "https://openai.com/research/gpt-4" |
|
YOUTUBE_URL_1 = "https://www.youtube.com/watch?v=--khbXchTeE" |
|
YOUTUBE_URL_2 = "https://www.youtube.com/watch?v=hdhZwyf24mE" |
|
|
|
|
|
urls = [ |
|
"https://kkg.hamburg.de/unser-leitbild/" |
|
"https://kkg.hamburg.de/unsere-schulcharta/", |
|
"https://kkg.hamburg.de/koordination-unterrichtsentwicklung/", |
|
"https://kkg.hamburg.de/konzept-medien-und-it-am-kkg/", |
|
] |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
embedder_modell = SentenceTransformer("sentence-transformers/all-mpnet-base-v2") |
|
EMBEDDING_MODELL = "sentence-transformers/all-mpnet-base-v2" |
|
|
|
|
|
|
|
""" |
|
HF_MODELL = "distilbert-base-uncased-distilled-squad" |
|
modell_rag = DistilBertForQuestionAnswering.from_pretrained(HF_MODELL) |
|
tokenizer_rag = DistilBertTokenizer.from_pretrained(HF_MODELL) |
|
qa_pipeline = pipeline("question-answering", model=modell_rag, tokenizer=tokenizer_rag) |
|
|
|
HF_MODELL ="EleutherAI/gpt-neo-2.7B" |
|
modell_rag = GPTNeoForCausalLM.from_pretrained(HF_MODELL) |
|
tokenizer_rag = GPT2Tokenizer.from_pretrained(HF_MODELL) |
|
tokenizer_rag.pad_token = tokenizer_rag.eos_token |
|
|
|
HF_MODELL = "microsoft/Phi-3-mini-4k-instruct" |
|
# Laden des Modells und Tokenizers |
|
modell_rag = AutoModelForCausalLM.from_pretrained(HF_MODELL) |
|
tokenizer_rag = AutoTokenizer.from_pretrained(HF_MODELL) |
|
|
|
HF_MODELL = "t5-small" |
|
modell_rag = AutoModelForSeq2SeqLM.from_pretrained(HF_MODELL) |
|
tokenizer_rag = AutoTokenizer.from_pretrained(HF_MODELL) |
|
""" |
|
|
|
|
|
|
|
|
|
|
|
|
|
def normalise_prompt (prompt): |
|
|
|
prompt_klein =prompt.lower() |
|
|
|
tokens = word_tokenize(prompt_klein) |
|
|
|
tokens = [word for word in tokens if word.isalnum()] |
|
|
|
|
|
tokens = [word for word in tokens if not word in german_stopwords] |
|
|
|
nltk.download('wordnet') |
|
lemmatizer = WordNetLemmatizer() |
|
tokens = [lemmatizer.lemmatize(word) for word in tokens] |
|
|
|
tokens = [re.sub(r'\W+', '', word) for word in tokens] |
|
|
|
from spellchecker import SpellChecker |
|
spell = SpellChecker() |
|
tokens = [spell.correction(word) for word in tokens] |
|
|
|
normalized_prompt = ' '.join(tokens) |
|
print("normaiserd prompt..................................") |
|
print(normalized_prompt) |
|
return normalized_prompt |
|
|
|
|
|
|
|
|
|
def preprocess_text(text): |
|
if not text: |
|
return "" |
|
|
|
text = text.lower() |
|
tokenizer = RegexpTokenizer(r'\w+') |
|
word_tokens = tokenizer.tokenize(text) |
|
filtered_words = [word for word in word_tokens if word not in german_stopwords] |
|
stemmer = SnowballStemmer("german") |
|
stemmed_words = [stemmer.stem(word) for word in filtered_words] |
|
return " ".join(stemmed_words) |
|
|
|
|
|
def clean_text(text): |
|
|
|
text = re.sub(r'[^\x00-\x7F]+', ' ', text) |
|
|
|
text = re.sub(r'\s+', ' ', text) |
|
return text.strip() |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def access_pdf(self, filename): |
|
|
|
with tempfile.NamedTemporaryFile(delete=False, suffix=self.file_type) as temp_file: |
|
temp_path = temp_file.name |
|
|
|
|
|
hf_hub_download( |
|
repo_id=STORAGE_REPO_ID, |
|
filename=file_path, |
|
repo_type=DATA_REPO_TYPE, |
|
local_dir=os.path.dirname(temp_path), |
|
token=hf_token |
|
) |
|
|
|
return temp_path |
|
|
|
""" |
|
#besseren directory Loader als CustomLoader definieren, der den inhalt des dokuemnts, die seitenzahlen, die überschriften und die pfadezu den dokumenten extrahieren |
|
def create_custom_loader(file_type, file_list): #create_directory_loader(file_type, directory_path): |
|
loaders = { |
|
'.pdf': load_pdf_with_metadata, |
|
'.word': load_word_with_metadata, |
|
} |
|
|
|
|
|
class CustomLoader: |
|
|
|
def __init__(self, directory_path, file_type, loader_func): |
|
self.directory_path = directory_path |
|
self.file_type = file_type |
|
self.loader_func = loader_func |
|
|
|
def load(self): |
|
documents = [] |
|
for root, _, files in os.walk(self.directory_path): |
|
for file in files: |
|
if file.endswith(self.file_type): |
|
file_path = os.path.join(root, file) |
|
documents.extend(self.loader_func(file_path)) |
|
return documents |
|
|
|
return CustomLoader(directory_path, file_type, loaders[file_type]) |
|
""" |
|
|
|
|
|
def create_custom_loader(file_type, file_list): |
|
loaders = { |
|
'.pdf': load_pdf_with_metadata, |
|
'.docx': load_word_with_metadata, |
|
} |
|
return CustomLoader(file_type, file_list, loaders[file_type]) |
|
|
|
|
|
|
|
|
|
def load_pdf_with_metadata(file_path): |
|
document = fitz.open(file_path) |
|
documents = [] |
|
for page_num in range(len(document)): |
|
page = document.load_page(page_num) |
|
content = page.get_text("text") |
|
title = document.metadata.get("title", "Unbekannt") |
|
page_number = page_num + 1 |
|
documents.append(Document(content=content, title=title, page=page_number, path=file_path, split_id=None)) |
|
return documents |
|
|
|
|
|
def load_word_with_metadata(file_path): |
|
document = docx.Document(file_path) |
|
title = "Dokument" |
|
path = file_path |
|
documents = [] |
|
for para in document.paragraphs: |
|
content = para.text |
|
page_number = 1 |
|
documents.append(Document(content=content, title=title, page=page_number, path=path, split_id= None)) |
|
return documents |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
""" |
|
def list_files_in_hf_repo(repo_id, directory=""): |
|
try: |
|
repo_info = api.list_repo_files(repo_id=repo_id, repo_type=REPO_TYPE) |
|
if directory: |
|
repo_info = [file for file in repo_info if file.startswith(directory)] |
|
return repo_info |
|
except Exception as e: |
|
print(f"Fehler beim Zugriff auf das Repository.........................:{repo_id} {e}") |
|
return [] |
|
""" |
|
|
|
|
|
|
|
|
|
|
|
def split_documents_with_id(docs, text_splitter): |
|
splits = [] |
|
for doc in docs: |
|
if not doc.metadata['title']: |
|
doc.metadata['title'] = "Dokument" |
|
if not doc.page_content: |
|
doc.page_content = "leer" |
|
|
|
doc_splits = text_splitter.split_text(f"{doc.metadata['title']} {doc.page_content}") |
|
for split_content in doc_splits: |
|
split_id = str(uuid.uuid4()) |
|
split_doc = Document(content=split_content, title=doc.metadata["title"], page=doc.metadata["page"], path=doc.metadata["path"], split_id=split_id) |
|
splits.append(split_doc) |
|
return splits |
|
|
|
|
|
|
|
|
|
|
|
def document_loading_splitting(): |
|
docs = [] |
|
print("Directory Loader neu............................") |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
""" |
|
files_in_repo = list_files_in_hf_repo(STORAGE_REPO_ID, "chroma/kkg/pdf/") |
|
print("hier.....................................") |
|
# Dateien aus dem Hugging Face Space mit der STORAGE_REPO_ID herunterladen |
|
for file_name in files_in_repo: |
|
if file_name.endswith('.pdf'): |
|
local_file_path = os.path.join(CHROMA_PDF, os.path.basename(file_name)) |
|
download_file_from_hf(file_name, local_file_path) |
|
if file_name.endswith('.docx'): |
|
local_file_path = os.path.join(CHROMA_WORD, os.path.basename(file_name)) |
|
download_file_from_hf(file_name, local_file_path) |
|
print("file_name..................."+str(file_name)) |
|
print("local_file_path..................."+str(local_file_path)) |
|
""" |
|
|
|
|
|
|
|
files_in_repo = list_repo_files(repo_id=STORAGE_REPO_ID, repo_type="space", token=hf_token) |
|
pdf_files = [f for f in files_in_repo if f.endswith('.pdf') and f.startswith("chroma/kkg/pdf/")] |
|
word_files = [f for f in files_in_repo if f.endswith('.docx') and f.startswith("chroma/kkg/word/")] |
|
|
|
|
|
|
|
|
|
|
|
|
|
pdf_loader = create_custom_loader('.pdf', pdf_files) |
|
word_loader = create_custom_loader('.docx', word_files) |
|
|
|
|
|
|
|
""" |
|
# kreiere einen DirectoryLoader für jeden file type |
|
pdf_loader = create_directory_loader('.pdf', CHROMA_PDF) |
|
word_loader = create_directory_loader('.word', CHROMA_WORD) |
|
""" |
|
|
|
pdf_documents = pdf_loader.load() |
|
word_documents = word_loader.load() |
|
|
|
|
|
docs.extend(pdf_documents) |
|
docs.extend(word_documents) |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
text_splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=200) |
|
|
|
|
|
|
|
|
|
original_splits = split_documents_with_id(docs, text_splitter) |
|
|
|
|
|
preprocessed_splits = [] |
|
for split in original_splits: |
|
preprocessed_content = preprocess_text(split.page_content) |
|
preprocessed_split = Document(content=preprocessed_content, title=split.metadata["title"], page=split.metadata["page"], path=split.metadata["path"], split_id=split.metadata["split_id"]) |
|
preprocessed_splits.append(preprocessed_split) |
|
|
|
|
|
|
|
split_to_original_mapping = {p_split.metadata["split_id"]: o_split for p_split, o_split in zip(preprocessed_splits, original_splits)} |
|
|
|
|
|
assert split_to_original_mapping, "Das Mapping von Splits wurde nicht korrekt erstellt" |
|
|
|
return preprocessed_splits, split_to_original_mapping, original_splits |
|
|
|
|
|
|
|
|
|
def document_storage_chroma(splits): |
|
|
|
embedding_fn = HuggingFaceEmbeddings(model_name=EMBEDDING_MODELL, model_kwargs={"device": "cpu"}, encode_kwargs={'normalize_embeddings': False}) |
|
|
|
|
|
vectorstore = Chroma.from_documents(documents=splits, embedding=embedding_fn) |
|
|
|
return vectorstore |
|
|
|
|
|
|
|
def save_splits(preprocessed_splits, original_splits, directory="chroma/kkg", preprocessed_filename="preprocessed_splits.pkl", original_filename="original_splits.pkl"): |
|
|
|
if not os.path.exists(directory): |
|
os.makedirs(directory) |
|
|
|
|
|
preprocessed_filepath = os.path.join(directory, preprocessed_filename) |
|
with open(preprocessed_filepath, "wb") as f: |
|
pickle.dump(preprocessed_splits, f) |
|
|
|
|
|
original_filepath = os.path.join(directory, original_filename) |
|
with open(original_filepath, "wb") as f: |
|
pickle.dump(original_splits, f) |
|
|
|
|
|
upload_file_to_huggingface(preprocessed_filepath, f"{directory}/{preprocessed_filename}") |
|
upload_file_to_huggingface(original_filepath, f"{directory}/{original_filename}") |
|
""" |
|
def load_splits(directory="chroma/kkg", preprocessed_filename="preprocessed_splits.pkl", original_filename="original_splits.pkl"): |
|
# Vollständigen Pfad zur Datei erstellen |
|
preprocessed_filepath = os.path.join(directory, preprocessed_filename) |
|
original_filepath = os.path.join(directory, original_filename) |
|
|
|
# Laden der vorverarbeiteten Splits aus der Datei |
|
if os.path.exists(preprocessed_filepath) and os.path.exists(original_filepath): |
|
with open(preprocessed_filepath, "rb") as f: |
|
preprocessed_splits = pickle.load(f) |
|
|
|
with open(original_filepath, "rb") as f: |
|
original_splits = pickle.load(f) |
|
|
|
return preprocessed_splits, original_splits |
|
return None, None |
|
""" |
|
def load_splits(directory="chroma/kkg", preprocessed_filename="preprocessed_splits.pkl", original_filename="original_splits.pkl"): |
|
preprocessed_splits = None |
|
original_splits = None |
|
|
|
try: |
|
|
|
preprocessed_file = hf_hub_download( |
|
repo_id=STORAGE_REPO_ID, |
|
filename=f"{directory}/{preprocessed_filename}", |
|
repo_type="space", |
|
token=hf_token |
|
) |
|
with open(preprocessed_file, "rb") as f: |
|
preprocessed_splits = pickle.load(f) |
|
|
|
|
|
original_file = hf_hub_download( |
|
repo_id=STORAGE_REPO_ID, |
|
filename=f"{directory}/{original_filename}", |
|
repo_type="space", |
|
token=hf_token |
|
) |
|
with open(original_file, "rb") as f: |
|
original_splits = pickle.load(f) |
|
|
|
except Exception as e: |
|
print(f"Fehler beim Laden der Splits: {str(e)}") |
|
|
|
return preprocessed_splits, original_splits |
|
|
|
|
|
|
|
|
|
""" |
|
def load_vectorstore(): |
|
splits_and_metadata = load_splits_and_metadata() |
|
if splits_and_metadata is not None: |
|
PREPROCESSED_SPLITS, SPLIT_TO_ORIGINAL_MAPPING = splits_and_metadata |
|
return document_storage_chroma(PREPROCESSED_SPLITS) |
|
return None |
|
""" |
|
|
|
|
|
|
|
def save_split_to_original_mapping(mapping, directory="chroma/kkg", filename="mapping.pkl"): |
|
|
|
if not os.path.exists(directory): |
|
os.makedirs(directory) |
|
|
|
|
|
filepath = os.path.join(directory, filename) |
|
with open(filepath, "wb") as f: |
|
pickle.dump(mapping, f) |
|
|
|
|
|
upload_file_to_huggingface(filepath, f"{directory}/{filename}") |
|
""" |
|
def load_split_to_original_mapping(directory="chroma/kkg", filename="mapping.pkl"): |
|
# Vollständigen Pfad zur Datei erstellen |
|
filepath = os.path.join(directory, filename) |
|
|
|
# Laden des Mappings aus der Datei |
|
if os.path.exists(filepath): |
|
with open(filepath, "rb") as f: |
|
return pickle.load(f) |
|
return None |
|
""" |
|
|
|
def load_split_to_original_mapping(directory="chroma/kkg", filename="mapping.pkl"): |
|
try: |
|
|
|
file_path = hf_hub_download( |
|
repo_id=STORAGE_REPO_ID, |
|
filename=f"{directory}/{filename}", |
|
repo_type="space", |
|
token=hf_token |
|
) |
|
|
|
with open(file_path, "rb") as f: |
|
return pickle.load(f) |
|
|
|
except Exception as e: |
|
print(f"Fehler beim Laden des Mappings: {str(e)}") |
|
return None |
|
|
|
|
|
|
|
|
|
|
|
|
|
def upload_file_to_huggingface(file_path, upload_path): |
|
api.upload_file( |
|
path_or_fileobj=file_path, |
|
path_in_repo=upload_path, |
|
repo_id=STORAGE_REPO_ID, |
|
repo_type=REPO_TYPE, |
|
token=HF_WRITE |
|
) |
|
|
|
|
|
|
|
def download_file_from_hf(file_name, save_path): |
|
url = f"https://huggingface.co/{STORAGE_REPO_ID}/resolve/main/{file_name}" |
|
response = requests.get(url, headers=HEADERS) |
|
response.raise_for_status() |
|
with open(save_path, 'wb') as file: |
|
file.write(response.content) |
|
return save_path |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
""" |
|
#langchain nutzen, um prompt an LLM zu leiten - llm und prompt sind austauschbar |
|
def llm_chain(llm, prompt, context): |
|
# Generiere den vollständigen Prompt mit der Eingabe |
|
# Generiere den vollständigen Prompt mit den Eingabevariablen |
|
full_prompt = RAG_CHAIN_PROMPT.format(context=context, question=prompt) |
|
# Erstellen der RunnableSequence |
|
params={ |
|
"input": full_prompt, |
|
"llm": llm |
|
} |
|
sequence = RunnableSequence(params) |
|
result = sequence.invoke() |
|
return result |
|
|
|
def query(api_llm, payload): |
|
response = requests.post(api_llm, headers=HEADERS, json=payload) |
|
return response.json() |
|
|
|
def llm_chain2(prompt, context): |
|
full_prompt = RAG_CHAIN_PROMPT.format(context=context, question=prompt) |
|
inputs = tokenizer_rag(full_prompt, return_tensors="pt", max_length=1024, truncation=True) |
|
#Generiere die Antwort |
|
outputs = modell_rag.generate( |
|
inputs.input_ids, |
|
attention_mask=inputs.attention_mask, |
|
max_new_tokens=1024, |
|
do_sample=True, |
|
temperature=0.9, |
|
pad_token_id=tokenizer_rag.eos_token_id |
|
) |
|
#outputs = modell_rag.generate(inputs['input_ids'], max_new_tokens=1024, num_beams=2, early_stopping=True) |
|
answer = tokenizer_rag.decode(outputs[0], skip_special_tokens=True) |
|
|
|
return answer |
|
|
|
|
|
############################################# |
|
#langchain nutzen, um prompt an llm zu leiten, aber vorher in der VektorDB suchen, um passende splits zum Prompt hinzuzufügen |
|
def rag_chain(llm, prompt, retriever): |
|
#Langgraph nutzen für ein wenig mehr Intelligenz beim Dokumente suchen |
|
relevant_docs=[] |
|
most_relevant_docs=[] |
|
|
|
#passend zum Prompt relevante Dokuemnte raussuchen |
|
relevant_docs = retriever.invoke(prompt) |
|
#zu jedem relevanten Dokument die wichtigen Informationen zusammenstellen (im Dict) |
|
extracted_docs = extract_document_info(relevant_docs) |
|
|
|
if (len(extracted_docs)>0): |
|
# Inahlte Abrufen der relevanten Dokumente |
|
doc_contents = [doc["content"] for doc in extracted_docs] |
|
|
|
#Berechne die Ähnlichkeiten und finde das relevanteste Dokument |
|
question_embedding = embedder_modell.encode(prompt, convert_to_tensor=True) |
|
doc_embeddings = embedder_modell.encode(doc_contents, convert_to_tensor=True) |
|
similarity_scores = util.pytorch_cos_sim(question_embedding, doc_embeddings) |
|
most_relevant_doc_indices = similarity_scores.argsort(descending=True).squeeze().tolist() |
|
|
|
#Erstelle eine Liste der relevantesten Dokumente |
|
most_relevant_docs = [extracted_docs[i] for i in most_relevant_doc_indices] |
|
|
|
#Kombiniere die Inhalte aller relevanten Dokumente |
|
combined_content = " ".join([doc["content"] for doc in most_relevant_docs]) |
|
|
|
|
|
############################################# |
|
#Verschiedene LLMs ausprobieren als Generierungsmodell |
|
#für die Zusammenfassung |
|
############################################# |
|
#1. Alternative, wenn llm direkt übergeben.................................... |
|
#answer = llm_chain2(prompt, combined_content) |
|
|
|
#Formuliere die Eingabe für das Generierungsmodell |
|
#input_text = f"frage: {prompt} kontext: {combined_content}" |
|
#2. Alternative, wenn mit API_URL ........................................... |
|
#answer = query(llm, {"inputs": input_text,}) |
|
|
|
#3. Alternative: mit pipeline |
|
#für summarizatiuon |
|
#answer = llm(input_text,max_length=1024, min_length=150, do_sample=False) |
|
#result = qa_pipeline(question=prompt, context=combined_content) |
|
#answer=result['answer'] |
|
|
|
# Erstelle das Ergebnis-Dictionary |
|
result = { |
|
"answer": "Folgende relevante Dokumente wurden gefunden:", |
|
"relevant_docs": most_relevant_docs |
|
} |
|
else: |
|
# keine relevanten Dokumente gefunden |
|
result = { |
|
"answer": "Keine relevanten Dokumente gefunden", |
|
"relevant_docs": None |
|
} |
|
|
|
return result |
|
""" |
|
|
|
|
|
|
|
def rag_chain_simpel( prompt, retriever): |
|
|
|
relevant_docs=[] |
|
most_relevant_docs=[] |
|
|
|
|
|
relevant_docs = retriever.invoke(prompt) |
|
|
|
print("relevant docs............."+str(relevant_docs)) |
|
|
|
|
|
extracted_docs = extract_document_info(relevant_docs) |
|
|
|
if (len(extracted_docs)>0): |
|
|
|
doc_contents = [doc["content"] for doc in extracted_docs] |
|
|
|
|
|
question_embedding = embedder_modell.encode(prompt, convert_to_tensor=True) |
|
doc_embeddings = embedder_modell.encode(doc_contents, convert_to_tensor=True) |
|
similarity_scores = util.pytorch_cos_sim(question_embedding, doc_embeddings) |
|
most_relevant_doc_indices = similarity_scores.argsort(descending=True).squeeze().tolist() |
|
|
|
|
|
most_relevant_docs = [extracted_docs[i] for i in most_relevant_doc_indices] |
|
|
|
|
|
combined_content = " ".join([doc["content"] for doc in most_relevant_docs]) |
|
|
|
|
|
result = { |
|
"answer": "Folgende relevante Dokumente wurden gefunden:", |
|
"relevant_docs": most_relevant_docs |
|
} |
|
else: |
|
|
|
result = { |
|
"answer": "Keine relevanten Dokumente gefunden", |
|
"relevant_docs": most_relevant_docs |
|
} |
|
|
|
return result |
|
|
|
|
|
|
|
|
|
|
|
def extract_document_info(documents): |
|
extracted_info = [] |
|
for doc in documents: |
|
|
|
filename = os.path.basename(doc.metadata.get("path", "")) |
|
title = filename if filename else "Keine Überschrift" |
|
|
|
|
|
doc_path = doc.metadata.get("path", "") |
|
if doc_path.endswith('.pdf'): |
|
download_link = f"https://huggingface.co/spaces/alexkueck/SucheRAG/resolve/main/chroma/kkg/pdf/{title}" |
|
elif doc_path.endswith('.docx'): |
|
download_link = f"https://huggingface.co/spaces/alexkueck/SucheRAG/resolve/main/chroma/kkg/word/{title}" |
|
else: |
|
download_link = doc_path |
|
|
|
|
|
info = { |
|
'content': doc.page_content, |
|
'metadata': doc.metadata, |
|
'titel': title, |
|
'seite': doc.metadata.get("page", "Unbekannte Seite"), |
|
'pfad': doc_path, |
|
'download_link': download_link, |
|
} |
|
extracted_info.append(info) |
|
return extracted_info |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def generate_prompt_with_history(text, history, max_length=4048): |
|
|
|
|
|
prompt="" |
|
history = ["\n{}\n{}".format(x[0],x[1]) for x in history] |
|
history.append("\n{}\n".format(text)) |
|
history_text = "" |
|
flag = False |
|
for x in history[::-1]: |
|
history_text = x + history_text |
|
flag = True |
|
if flag: |
|
return prompt+history_text |
|
else: |
|
return None |
|
|
|
|
|
|
|
|
|
def generate_prompt_with_history_hf(prompt, history): |
|
history_transformer_format = history + [[prompt, ""]] |
|
|
|
|
|
messages = "".join(["".join(["\n<human>:"+item[0], "\n<bot>:"+item[1]]) |
|
for item in history_transformer_format]) |
|
|
|
|
|
|
|
|
|
|
|
|
|
def hash_input(input_string): |
|
return hashlib.sha256(input_string.encode()).hexdigest() |
|
|
|
|
|
|
|
|
|
|
|
def transfer_input(inputs): |
|
textbox = reset_textbox() |
|
return ( |
|
inputs, |
|
gr.update(value=""), |
|
gr.Button.update(visible=True), |
|
) |
|
|
|
|
|
|
|
|
|
def download_link(doc): |
|
|
|
|
|
if isinstance(doc, dict) and 'pfad' in doc: |
|
file_url = f"https://huggingface.co/spaces/alexkueck/SucheRAG/resolve/main/chroma/kkg/{doc['pfad']}?token=hf_token" |
|
return f'<b><a href="{file_url}" target="_blank" style="color: #BB70FC; font-weight: bold;">{doc["titel"]}</a></b>' |
|
else: |
|
file_url = f"https://huggingface.co/spaces/alexkueck/SucheRAG/resolve/main/{doc}?token=hf_token" |
|
return f'<b><a href="{file_url}" target="_blank" style="color: #BB70FC; font-weight: bold;">{doc}</a></b>' |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
""" |
|
def display_files(): |
|
files = os.listdir(DOCS_DIR_PDF) |
|
files_table = "<table style='width:100%; border-collapse: collapse;'>" |
|
files_table += "<tr style='background-color: #930BBA; color: white; font-weight: bold; font-size: larger;'><th>Dateiname - PDF-Ordner</th></tr>" |
|
for i, file in enumerate(files): |
|
file_path = os.path.join(DOCS_DIR_PDF, file) |
|
file_size = os.path.getsize(file_path) / 1024 # Größe in KB |
|
row_color = "#4f4f4f" if i % 2 == 0 else "#3a3a3a" # Wechselnde Zeilenfarben |
|
files_table += f"<tr style='background-color: {row_color}; border-bottom: 1px solid #ddd;'>" |
|
files_table += f"<td><b>{download_link(file)}</b></td></tr>" |
|
files_table += "</table>" |
|
|
|
files = os.listdir(DOCS_DIR_WORD) |
|
files_table += "<table style='width:100%; border-collapse: collapse;'>" |
|
files_table += "<tr style='background-color: #930BBA; color: white; font-weight: bold; font-size: larger;'><th>Dateiname - Word-Ordner</th></tr>" |
|
for i, file in enumerate(files): |
|
file_path = os.path.join(DOCS_DIR_WORD, file) |
|
file_size = os.path.getsize(file_path) / 1024 # Größe in KB |
|
row_color = "#4f4f4f" if i % 2 == 0 else "#3a3a3a" # Wechselnde Zeilenfarben |
|
files_table += f"<tr style='background-color: {row_color}; border-bottom: 1px solid #ddd;'>" |
|
files_table += f"<td><b>{download_link(file)}</b></td></tr>" |
|
files_table += "</table>" |
|
return files_table |
|
""" |
|
|
|
def display_files(): |
|
files_table = "<table style='width:100%; border-collapse: collapse;'>" |
|
|
|
|
|
files_table += "<tr style='background-color: #930BBA; color: white; font-weight: bold; font-size: larger;'><th>Dateiname - PDF-Ordner</th></tr>" |
|
pdf_files = [f for f in list_repo_files(repo_id=STORAGE_REPO_ID, repo_type="space", token=hf_token) if f.endswith('.pdf') and f.startswith("chroma/kkg/pdf/")] |
|
for i, file in enumerate(pdf_files): |
|
row_color = "#4f4f4f" if i % 2 == 0 else "#3a3a3a" |
|
files_table += f"<tr style='background-color: {row_color}; border-bottom: 1px solid #ddd;'>" |
|
files_table += f"<td><b>{file.split('/')[-1]}</b></td></tr>" |
|
|
|
|
|
files_table += "<tr style='background-color: #930BBA; color: white; font-weight: bold; font-size: larger;'><th>Dateiname - Word-Ordner</th></tr>" |
|
word_files = [f for f in list_repo_files(repo_id=STORAGE_REPO_ID, repo_type="space", token=hf_token) if f.endswith('.docx') and f.startswith("chroma/kkg/word/")] |
|
for i, file in enumerate(word_files): |
|
row_color = "#4f4f4f" if i % 2 == 0 else "#3a3a3a" |
|
files_table += f"<tr style='background-color: {row_color}; border-bottom: 1px solid #ddd;'>" |
|
files_table += f"<td><b>{file.split('/')[-1]}</b></td></tr>" |
|
|
|
files_table += "</table>" |
|
return files_table |
|
|
|
|
|
|
|
""" |
|
def list_pdfs(): |
|
if not os.path.exists(DOCS_DIR): |
|
return [] |
|
return [f for f in os.listdir(SAVE_DIR) if f.endswith('.pdf')] |
|
""" |
|
|
|
|
|
def analyze_file(file): |
|
file_extension = file.name.split('.')[-1] |
|
return file_extension |
|
|
|
|
|
|
|
def get_filename(file_pfad): |
|
parts = file_pfad.rsplit('/', 1) |
|
if len(parts) == 2: |
|
result = parts[1] |
|
else: |
|
result = "Ein Fehler im Filenamen ist aufgetreten..." |
|
return result |
|
|
|
|
|
def is_stop_word_or_prefix(s: str, stop_words: list) -> bool: |
|
for stop_word in stop_words: |
|
if s.endswith(stop_word): |
|
return True |
|
for i in range(1, len(stop_word)): |
|
if s.endswith(stop_word[:i]): |
|
return True |
|
return False |
|
|
|
|
|
|
|
|
|
class State: |
|
interrupted = False |
|
|
|
def interrupt(self): |
|
self.interrupted = True |
|
|
|
def recover(self): |
|
self.interrupted = False |
|
shared_state = State() |
|
|
|
|
|
|
|
class Document: |
|
def __init__(self, content, title, page, path, split_id=None): |
|
self.page_content = content |
|
self.metadata = { |
|
"title": title, |
|
"page": page, |
|
"path": path, |
|
"split_id": split_id |
|
} |
|
|
|
|
|
|
|
|
|
|
|
class CustomLoader: |
|
def __init__(self, file_type, file_list, loader_func): |
|
self.file_type = file_type |
|
self.file_list = file_list |
|
self.loader_func = loader_func |
|
|
|
def load(self): |
|
documents = [] |
|
for file_path in self.file_list: |
|
with tempfile.NamedTemporaryFile(delete=False, suffix=self.file_type) as temp_file: |
|
temp_path = temp_file.name |
|
|
|
try: |
|
|
|
downloaded_path = hf_hub_download( |
|
repo_id=STORAGE_REPO_ID, |
|
filename=file_path, |
|
repo_type="space", |
|
local_dir=os.path.dirname(temp_path), |
|
token=hf_token |
|
) |
|
|
|
|
|
if os.path.getsize(downloaded_path) == 0: |
|
print(f"Warnung: Die Datei {file_path} ist leer und wird übersprungen.") |
|
continue |
|
|
|
documents.extend(self.loader_func(downloaded_path)) |
|
except Exception as e: |
|
print(f"Fehler beim Verarbeiten der Datei {file_path}: {str(e)}") |
|
finally: |
|
|
|
if os.path.exists(temp_path): |
|
os.unlink(temp_path) |
|
|
|
return documents |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|