|
from typing import TYPE_CHECKING, Any, Callable, Dict, List, Tuple, Type |
|
import logging |
|
import json |
|
import os |
|
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 |
|
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 |
|
|
|
|
|
|
|
|
|
|
|
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/SucheRAG" |
|
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() |
|
|
|
|
|
|
|
|
|
|
|
|
|
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" |
|
|
|
|
|
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 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 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)) |
|
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)) |
|
return documents |
|
|
|
|
|
|
|
|
|
|
|
|
|
def document_loading_splitting(): |
|
|
|
|
|
docs = [] |
|
|
|
|
|
pdf_loader = create_directory_loader('.pdf', CHROMA_PDF) |
|
word_loader = create_directory_loader('.word', CHROMA_WORD) |
|
print("PDF Loader done............................") |
|
|
|
|
|
pdf_documents = pdf_loader.load() |
|
word_documents = word_loader.load() |
|
|
|
|
|
docs.extend(pdf_documents) |
|
docs.extend(word_documents) |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
preprocessed_docs = [] |
|
for doc in docs: |
|
preprocessed_content = preprocess_text(doc.page_content) |
|
preprocessed_title = preprocess_text(doc.metadata["title"]) |
|
preprocessed_metadata = { |
|
"title": preprocessed_title, |
|
"page": doc.metadata["page"], |
|
"path": doc.metadata["path"] |
|
} |
|
preprocessed_doc = Document(content=preprocessed_content, title=preprocessed_metadata["title"], page=preprocessed_metadata["page"], path=preprocessed_metadata["path"]) |
|
original_doc = Document(content=doc.page_content, title=doc.metadata["title"], page=doc.metadata["page"], path=doc.metadata["path"]) |
|
|
|
preprocessed_doc.id = str(uuid.uuid4()) |
|
original_doc.id = preprocessed_doc.id |
|
preprocessed_docs.append(preprocessed_doc) |
|
original_docs.append(original_doc) |
|
|
|
|
|
|
|
text_splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=200) |
|
splits = text_splitter.split_documents(preprocessed_docs) |
|
|
|
original_splits = text_splitter.split_documents(original_docs) |
|
preprocessed_splits = text_splitter.split_documents(preprocessed_docs) |
|
|
|
|
|
split_to_original_mapping = {p_split.id: o_split for p_split, o_split in zip(preprocessed_splits, original_splits)} |
|
|
|
|
|
print("Splits...........................") |
|
for split in preprocessed_splits: |
|
if 'divis' in split.page_content: |
|
print("DIVIS found in chunk:", split) |
|
|
|
return preprocessed_splits, split_to_original_mapping |
|
|
|
|
|
|
|
|
|
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) |
|
retriever = vectorstore.as_retriever(search_kwargs = {"k": ANZAHL_DOCS}) |
|
|
|
|
|
|
|
return vectorstore, retriever |
|
|
|
|
|
|
|
""" |
|
def document_retrieval_chroma(llm, prompt): |
|
#HF embeddings ----------------------------------- |
|
#Alternative Embedding - für Vektorstore, um Ähnlichkeitsvektoren zu erzeugen - die ...InstructEmbedding ist sehr rechenaufwendig |
|
#embeddings = HuggingFaceInstructEmbeddings(model_name="sentence-transformers/all-MiniLM-L6-v2", model_kwargs={"device": "cpu"}) |
|
#etwas weniger rechenaufwendig: |
|
embeddings = HuggingFaceEmbeddings(model_name=EMBEDDING_MODELL, model_kwargs={"device": "cpu"}, encode_kwargs={'normalize_embeddings': False}) |
|
|
|
#ChromaDb um die embedings zu speichern |
|
db = Chroma(embedding_function = embeddings, persist_directory = PATH_WORK + CHROMA_DIR) |
|
return db |
|
""" |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def llm_chain(llm, prompt, context): |
|
|
|
|
|
full_prompt = RAG_CHAIN_PROMPT.format(context=context, question=prompt) |
|
|
|
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) |
|
|
|
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 |
|
) |
|
|
|
answer = tokenizer_rag.decode(outputs[0], skip_special_tokens=True) |
|
|
|
return answer |
|
|
|
|
|
|
|
|
|
def rag_chain(llm, prompt, retriever): |
|
|
|
relevant_docs=[] |
|
most_relevant_docs=[] |
|
|
|
|
|
relevant_docs = retriever.invoke(prompt) |
|
|
|
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 rag_chain_simpel( prompt, retriever): |
|
|
|
relevant_docs=[] |
|
most_relevant_docs=[] |
|
|
|
|
|
relevant_docs = retriever.invoke(prompt) |
|
|
|
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</th><th>Größe (KB)</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 |
|
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>{download_link(file)}</b></td>" |
|
files_table += f"<td>{file_size:.2f}</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</th><th>Größe (KB)</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 |
|
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>{download_link(file)}</b></td>" |
|
files_table += f"<td>{file_size:.2f}</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 |
|
|
|
|
|
|
|
|
|
|
|
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): |
|
self.page_content = content |
|
self.metadata = { |
|
"title": title, |
|
"page": page, |
|
"path": path |
|
} |
|
|
|
|
|
|
|
|
|
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 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|