|
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 operator |
|
from typing import Annotated, Sequence, TypedDict |
|
import pprint |
|
|
|
import gradio as gr |
|
from pypinyin import lazy_pinyin |
|
import tiktoken |
|
import mdtex2html |
|
from markdown import markdown |
|
from pygments import highlight |
|
from pygments.lexers import guess_lexer,get_lexer_by_name |
|
from pygments.formatters import HtmlFormatter |
|
|
|
from langchain.chains import LLMChain, RetrievalQA |
|
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 |
|
from langchain.text_splitter import RecursiveCharacterTextSplitter |
|
from chromadb.errors import InvalidDimensionException |
|
import io |
|
|
|
|
|
|
|
|
|
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 |
|
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 |
|
|
|
|
|
|
|
|
|
|
|
|
|
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. |
|
Versuche nicht es zu umschreiben. Versuche nicht, die Antwort zu erfinden oder aufzumocken. Antworte nur zu dem mitgelieferten Text.""" |
|
|
|
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." + 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" |
|
|
|
|
|
|
|
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/", |
|
] |
|
|
|
|
|
|
|
|
|
|
|
|
|
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': PyPDFLoader, |
|
'.word': UnstructuredWordDocumentLoader, |
|
} |
|
return DirectoryLoader( |
|
path=directory_path, |
|
glob=f"**/*{file_type}", |
|
loader_cls=loaders[file_type], |
|
) |
|
|
|
|
|
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) |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
text_splitter = RecursiveCharacterTextSplitter(chunk_overlap = 150, chunk_size = 1500) |
|
splits = text_splitter.split_documents(docs) |
|
|
|
return splits |
|
|
|
|
|
|
|
def document_storage_chroma(splits): |
|
|
|
vectorstore = Chroma.from_documents(documents = splits, embedding = HuggingFaceEmbeddings(model_name="sentence-transformers/all-mpnet-base-v2", model_kwargs={"device": "cpu"}, encode_kwargs={'normalize_embeddings': False}), persist_directory = PATH_WORK + CHROMA_DIR) |
|
retriever = vectorstore.as_retriever(search_kwargs = {"k": ANZAHL_DOCS}) |
|
return vectorstore, retriever |
|
|
|
|
|
|
|
def document_retrieval_chroma(llm, prompt): |
|
|
|
|
|
|
|
|
|
embeddings = HuggingFaceEmbeddings(model_name="sentence-transformers/all-mpnet-base-v2", model_kwargs={"device": "cpu"}, encode_kwargs={'normalize_embeddings': False}) |
|
|
|
|
|
db = Chroma(embedding_function = embeddings, persist_directory = PATH_WORK + CHROMA_DIR) |
|
return db |
|
|
|
|
|
|
|
|
|
|
|
|
|
def rag_chainback(prompt, db, k=3): |
|
rag_template = "Nutze ausschließlich die folgenden Kontext Teile am Ende, um die Frage zu beantworten . " + template + "Frage: " + prompt + "Kontext Teile: " |
|
retrieved_chunks = db.similarity_search(prompt, k) |
|
|
|
|
|
chunks_dict = [] |
|
for i, chunk in enumerate(retrieved_chunks): |
|
chunk_dict = { |
|
"chunk_index": i + 1, |
|
"page_content": chunk.page_content, |
|
"metadata": chunk.metadata |
|
} |
|
chunks_dict.append(chunk_dict) |
|
|
|
|
|
neu_prompt = rag_template |
|
for chunk in chunks_dict: |
|
neu_prompt += f"{chunk['chunk_index']}. {chunk['page_content']}\n" |
|
|
|
print("dict.............................."+ json.dumps(chunks_dict, indent=4, ensure_ascii=False)) |
|
|
|
return neu_prompt, chunks_dict |
|
|
|
|
|
|
|
|
|
|
|
|
|
def llm_chain(llm, prompt): |
|
llm_chain = LLMChain(llm = llm, prompt = LLM_CHAIN_PROMPT) |
|
result = llm_chain.run({"question": prompt}) |
|
return result |
|
|
|
|
|
def llm_chain2(llm, prompt): |
|
llm_chain = LLMChain(llm = llm, prompt = LLM_CHAIN_PROMPT2) |
|
result = llm_chain.run({"question": prompt}) |
|
return result |
|
|
|
|
|
def rag_chain(llm, prompt, retriever): |
|
|
|
relevant_docs=[] |
|
filtered_docs=[] |
|
relevant_docs = retriever.get_relevant_documents(prompt) |
|
print("releant docs1......................") |
|
if (len(relevant_docs)>0): |
|
print("releant docs2......................") |
|
print(relevant_docs) |
|
llm_chain = LLMChain(llm = llm, prompt = RAG_CHAIN_PROMPT) |
|
result = llm_chain.run({"context": relevant_docs, "question": prompt}) |
|
else: |
|
|
|
result = "Keine relevanten Dokumente gefunden" |
|
|
|
return result |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 |
|
print("hist+prompt: ") |
|
print(history_text) |
|
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), |
|
) |
|
|
|
|
|
|
|
|
|
|
|
class State: |
|
interrupted = False |
|
|
|
def interrupt(self): |
|
self.interrupted = True |
|
|
|
def recover(self): |
|
self.interrupted = False |
|
shared_state = State() |
|
|
|
|
|
|
|
|
|
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 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|