Update app.py
Browse files
app.py
CHANGED
|
@@ -4,23 +4,23 @@ import gradio as gr
|
|
| 4 |
import time
|
| 5 |
import re
|
| 6 |
import io
|
| 7 |
-
from PIL import Image, ImageDraw, ImageOps, ImageFont
|
| 8 |
-
import base64
|
| 9 |
import tempfile
|
| 10 |
|
| 11 |
from PyPDF2 import PdfReader, PdfWriter
|
| 12 |
|
| 13 |
|
| 14 |
-
from langchain.chains import LLMChain, RetrievalQA
|
| 15 |
from langchain_community.document_loaders import PyPDFLoader, UnstructuredWordDocumentLoader, DirectoryLoader
|
| 16 |
from langchain_community.document_loaders.blob_loaders.youtube_audio import YoutubeAudioLoader
|
| 17 |
#from langchain.document_loaders import GenericLoader
|
| 18 |
-
from langchain.schema import AIMessage, HumanMessage
|
| 19 |
-
from langchain_community.llms import HuggingFaceHub
|
| 20 |
from langchain_huggingface import HuggingFaceEndpoint
|
| 21 |
#from langchain_community.llms import HuggingFaceEndPoints
|
| 22 |
from langchain_huggingface import HuggingFaceEmbeddings
|
| 23 |
-
from langchain_community.llms import HuggingFaceTextGenInference
|
| 24 |
#from langchain_community.embeddings import HuggingFaceInstructEmbeddings, HuggingFaceEmbeddings, HuggingFaceBgeEmbeddings, HuggingFaceInferenceAPIEmbeddings
|
| 25 |
from langchain.prompts import PromptTemplate
|
| 26 |
from langchain.text_splitter import RecursiveCharacterTextSplitter
|
|
@@ -108,23 +108,23 @@ def clear_all(history, uploaded_file_paths, chats):
|
|
| 108 |
|
| 109 |
#Eine Überschrift zu dem jeweiligen Chatverlauf finden - abhängig vom Inhalt
|
| 110 |
#file_path_download = save_and_download(summary)
|
| 111 |
-
headers, payload = process_chatverlauf(summary, MODEL_NAME, OAI_API_KEY)
|
| 112 |
-
response = requests.post("https://api.openai.com/v1/chat/completions", headers=headers, json=payload)
|
| 113 |
#als json ausgeben
|
| 114 |
-
data = response.json()
|
| 115 |
# Den "content" auswählen, da dort die Antwort der Ki enthalten ist
|
| 116 |
-
result = data['choices'][0]['message']['content']
|
| 117 |
-
worte = result.split()
|
| 118 |
-
if len(worte) > 2:
|
| 119 |
-
file_path_download = "data/" + str(len(chats)) + "_Chatverlauf.pdf"
|
| 120 |
-
else:
|
| 121 |
-
file_path_download = "data/" + str(len(chats)) + "_" + result + ".pdf"
|
| 122 |
|
| 123 |
-
erstellePdf(file_path_download, result, dic_history)
|
| 124 |
|
| 125 |
|
| 126 |
#die session variable in gradio erweitern und alle fliepath neu in das gr.File hochladen
|
| 127 |
-
uploaded_file_paths= uploaded_file_paths + [file_path_download]
|
| 128 |
|
| 129 |
return None, gr.Image(visible=False), uploaded_file_paths, [], gr.File(uploaded_file_paths, label="Download-Chatverläufe", visible=True, file_count="multiple", interactive = False), chats
|
| 130 |
|
|
@@ -184,79 +184,6 @@ def cancel_outputing():
|
|
| 184 |
def reset_textbox():
|
| 185 |
return gr.update(value=""),""
|
| 186 |
|
| 187 |
-
|
| 188 |
-
##########################################
|
| 189 |
-
#Hilfsfunktion, um ein von Stable Diffusion erzeugtes Bild für die Ausgabe in der History vorzubereiten
|
| 190 |
-
def umwandeln_fuer_anzeige(image):
|
| 191 |
-
buffer = io.BytesIO()
|
| 192 |
-
image.save(buffer, format='PNG')
|
| 193 |
-
return buffer.getvalue()
|
| 194 |
-
|
| 195 |
-
|
| 196 |
-
|
| 197 |
-
|
| 198 |
-
####################################################
|
| 199 |
-
#aus einem Text-Prompt die Antwort von KI bekommen
|
| 200 |
-
#mit oder ohne RAG möglich
|
| 201 |
-
def generate_text (prompt, chatbot, history, vektordatenbank, retriever, top_p=0.6, temperature=0.2, max_new_tokens=4048, max_context_length_tokens=2048, repetition_penalty=1.3, top_k=35):
|
| 202 |
-
print("Text pur..............................")
|
| 203 |
-
if (prompt == ""):
|
| 204 |
-
raise gr.Error("Prompt ist erforderlich.")
|
| 205 |
-
|
| 206 |
-
try:
|
| 207 |
-
#oder an Hugging Face --------------------------
|
| 208 |
-
print("HF Anfrage.......................")
|
| 209 |
-
model_kwargs={"temperature": 0.5, "max_length": 512, "num_return_sequences": 1, "top_k": top_k, "top_p": top_p, "repetition_penalty": repetition_penalty}
|
| 210 |
-
#llm = HuggingFaceHub(repo_id=repo_id, model_kwargs=model_kwargs)
|
| 211 |
-
|
| 212 |
-
# Erstelle eine Pipeline mit den gewünschten Parametern
|
| 213 |
-
#pipe = pipeline("text-generation", model=MODEL_NAME_HF, config={"temperature": 0.5, "max_length": 512, "num_return_sequences": 1, "top_k": top_k, "top_p": top_p, "repetition_penalty": repetition_penalty})
|
| 214 |
-
|
| 215 |
-
# Erstelle eine HuggingFaceEndPoints-Instanz mit den entsprechenden Endpunkt-Parametern
|
| 216 |
-
llm = HuggingFaceEndpoint(
|
| 217 |
-
endpoint_url=f"https://api-inference.huggingface.co/models/{MODEL_NAME_HF}",
|
| 218 |
-
api_key=hf_token,
|
| 219 |
-
model_kwargs=model_kwargs
|
| 220 |
-
)
|
| 221 |
-
|
| 222 |
-
#Prompt an history anhängen und einen Text daraus machen
|
| 223 |
-
history_text_und_prompt = generate_prompt_with_history(prompt, history)
|
| 224 |
-
|
| 225 |
-
#zusätzliche Dokumenten Splits aus DB zum Prompt hinzufügen (aus VektorDB - Chroma oder Mongo DB)
|
| 226 |
-
print("LLM aufrufen mit RAG: ...........")
|
| 227 |
-
#result = rag_chain(history_text_und_prompt, vektordatenbank, ANZAHL_DOCS)
|
| 228 |
-
result = rag_chain(llm, history_text_und_prompt, retriever)
|
| 229 |
-
print("result regchain.....................")
|
| 230 |
-
print(result)
|
| 231 |
-
print("Ene result............................")
|
| 232 |
-
|
| 233 |
-
except Exception as e:
|
| 234 |
-
raise gr.Error(e)
|
| 235 |
-
|
| 236 |
-
return result, False
|
| 237 |
-
|
| 238 |
-
|
| 239 |
-
########################################
|
| 240 |
-
# Bot- test gegen schädliche Bots die die Anwendung testen...
|
| 241 |
-
# Funktion zur Überprüfung der Benutzereingabe
|
| 242 |
-
# Funktion zur Überprüfung der Eingabe und Aktivierung der Hauptanwendung
|
| 243 |
-
def validate_input(user_input_validate, validate=False):
|
| 244 |
-
user_input_hashed = hash_input(user_input_validate)
|
| 245 |
-
if user_input_hashed == hash_input(ANTI_BOT_PW):
|
| 246 |
-
return "Richtig! Weiter gehts... ", True, gr.Textbox(visible=False), gr.Button(visible=False)
|
| 247 |
-
else:
|
| 248 |
-
return "Falsche Antwort!!!!!!!!!", False, gr.Textbox(label = "", placeholder="Bitte tippen Sie das oben im Moodle Kurs angegebene Wort ein, um zu beweisen, dass Sie kein Bot sind.", visible=True, scale= 5), gr.Button("Validieren", visible = True)
|
| 249 |
-
|
| 250 |
-
|
| 251 |
-
|
| 252 |
-
def custom_css():
|
| 253 |
-
return """
|
| 254 |
-
body, html {
|
| 255 |
-
background-color: #303030; /* Dunkler Hintergrund */
|
| 256 |
-
color:#353535;
|
| 257 |
-
}
|
| 258 |
-
"""
|
| 259 |
-
|
| 260 |
|
| 261 |
#####################################################################
|
| 262 |
# Antwort des Vektorstores in ein Dictionary packen
|
|
@@ -298,8 +225,8 @@ def parse_vectorstore_response(response_text):
|
|
| 298 |
})
|
| 299 |
|
| 300 |
return parsed_entries
|
| 301 |
-
|
| 302 |
|
|
|
|
| 303 |
def create_history_entry(page_content, metadata):
|
| 304 |
source = metadata.get('source', 'No source available')
|
| 305 |
page = metadata.get('page', 'No page information available')
|
|
@@ -310,9 +237,52 @@ def create_history_entry(page_content, metadata):
|
|
| 310 |
"page": page,
|
| 311 |
"download_link": download_link
|
| 312 |
}
|
|
|
|
| 313 |
|
| 314 |
|
| 315 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 316 |
#Eingaben der GUI verarbeiten
|
| 317 |
def generate_auswahl(prompt_in, file, file_history, chatbot, history, anzahl_docs=4, top_p=0.6, temperature=0.5, max_new_tokens=4048, max_context_length_tokens=2048, repetition_penalty=1.3,top_k=5, validate=False):
|
| 318 |
global vektordatenbank, retriever
|
|
@@ -362,7 +332,29 @@ def generate_auswahl(prompt_in, file, file_history, chatbot, history, anzahl_doc
|
|
| 362 |
else: #noch nicht validiert, oder kein Prompt
|
| 363 |
return chatbot, history, None, file_history, "Erst validieren oder einen Prompt eingeben!"
|
| 364 |
|
| 365 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 366 |
|
| 367 |
#############################################################################################
|
| 368 |
# Start Gui Vorabfrage
|
|
|
|
| 4 |
import time
|
| 5 |
import re
|
| 6 |
import io
|
| 7 |
+
#from PIL import Image, ImageDraw, ImageOps, ImageFont
|
| 8 |
+
#import base64
|
| 9 |
import tempfile
|
| 10 |
|
| 11 |
from PyPDF2 import PdfReader, PdfWriter
|
| 12 |
|
| 13 |
|
| 14 |
+
#from langchain.chains import LLMChain, RetrievalQA
|
| 15 |
from langchain_community.document_loaders import PyPDFLoader, UnstructuredWordDocumentLoader, DirectoryLoader
|
| 16 |
from langchain_community.document_loaders.blob_loaders.youtube_audio import YoutubeAudioLoader
|
| 17 |
#from langchain.document_loaders import GenericLoader
|
| 18 |
+
#from langchain.schema import AIMessage, HumanMessage
|
| 19 |
+
#from langchain_community.llms import HuggingFaceHub
|
| 20 |
from langchain_huggingface import HuggingFaceEndpoint
|
| 21 |
#from langchain_community.llms import HuggingFaceEndPoints
|
| 22 |
from langchain_huggingface import HuggingFaceEmbeddings
|
| 23 |
+
#from langchain_community.llms import HuggingFaceTextGenInference
|
| 24 |
#from langchain_community.embeddings import HuggingFaceInstructEmbeddings, HuggingFaceEmbeddings, HuggingFaceBgeEmbeddings, HuggingFaceInferenceAPIEmbeddings
|
| 25 |
from langchain.prompts import PromptTemplate
|
| 26 |
from langchain.text_splitter import RecursiveCharacterTextSplitter
|
|
|
|
| 108 |
|
| 109 |
#Eine Überschrift zu dem jeweiligen Chatverlauf finden - abhängig vom Inhalt
|
| 110 |
#file_path_download = save_and_download(summary)
|
| 111 |
+
#headers, payload = process_chatverlauf(summary, MODEL_NAME, OAI_API_KEY)
|
| 112 |
+
#response = requests.post("https://api.openai.com/v1/chat/completions", headers=headers, json=payload)
|
| 113 |
#als json ausgeben
|
| 114 |
+
#data = response.json()
|
| 115 |
# Den "content" auswählen, da dort die Antwort der Ki enthalten ist
|
| 116 |
+
#result = data['choices'][0]['message']['content']
|
| 117 |
+
#worte = result.split()
|
| 118 |
+
#if len(worte) > 2:
|
| 119 |
+
#file_path_download = "data/" + str(len(chats)) + "_Chatverlauf.pdf"
|
| 120 |
+
#else:
|
| 121 |
+
#file_path_download = "data/" + str(len(chats)) + "_" + result + ".pdf"
|
| 122 |
|
| 123 |
+
#erstellePdf(file_path_download, result, dic_history)
|
| 124 |
|
| 125 |
|
| 126 |
#die session variable in gradio erweitern und alle fliepath neu in das gr.File hochladen
|
| 127 |
+
#uploaded_file_paths= uploaded_file_paths + [file_path_download]
|
| 128 |
|
| 129 |
return None, gr.Image(visible=False), uploaded_file_paths, [], gr.File(uploaded_file_paths, label="Download-Chatverläufe", visible=True, file_count="multiple", interactive = False), chats
|
| 130 |
|
|
|
|
| 184 |
def reset_textbox():
|
| 185 |
return gr.update(value=""),""
|
| 186 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 187 |
|
| 188 |
#####################################################################
|
| 189 |
# Antwort des Vektorstores in ein Dictionary packen
|
|
|
|
| 225 |
})
|
| 226 |
|
| 227 |
return parsed_entries
|
|
|
|
| 228 |
|
| 229 |
+
#History Eintrag vorbereiten
|
| 230 |
def create_history_entry(page_content, metadata):
|
| 231 |
source = metadata.get('source', 'No source available')
|
| 232 |
page = metadata.get('page', 'No page information available')
|
|
|
|
| 237 |
"page": page,
|
| 238 |
"download_link": download_link
|
| 239 |
}
|
| 240 |
+
|
| 241 |
|
| 242 |
|
| 243 |
+
|
| 244 |
+
####################################################
|
| 245 |
+
#aus einem Text-Prompt die Antwort von KI bekommen
|
| 246 |
+
def generate_text (prompt, chatbot, history, vektordatenbank, retriever, top_p=0.6, temperature=0.2, max_new_tokens=4048, max_context_length_tokens=2048, repetition_penalty=1.3, top_k=35):
|
| 247 |
+
print("Text pur..............................")
|
| 248 |
+
if (prompt == ""):
|
| 249 |
+
raise gr.Error("Prompt ist erforderlich.")
|
| 250 |
+
|
| 251 |
+
try:
|
| 252 |
+
#oder an Hugging Face --------------------------
|
| 253 |
+
print("HF Anfrage.......................")
|
| 254 |
+
model_kwargs={"temperature": 0.5, "max_length": 512, "num_return_sequences": 1, "top_k": top_k, "top_p": top_p, "repetition_penalty": repetition_penalty}
|
| 255 |
+
#llm = HuggingFaceHub(repo_id=repo_id, model_kwargs=model_kwargs)
|
| 256 |
+
|
| 257 |
+
# Erstelle eine Pipeline mit den gewünschten Parametern
|
| 258 |
+
#pipe = pipeline("text-generation", model=MODEL_NAME_HF, config={"temperature": 0.5, "max_length": 512, "num_return_sequences": 1, "top_k": top_k, "top_p": top_p, "repetition_penalty": repetition_penalty})
|
| 259 |
+
|
| 260 |
+
# Erstelle eine HuggingFaceEndPoints-Instanz mit den entsprechenden Endpunkt-Parametern
|
| 261 |
+
llm = HuggingFaceEndpoint(
|
| 262 |
+
endpoint_url=f"https://api-inference.huggingface.co/models/{MODEL_NAME_HF}",
|
| 263 |
+
api_key=hf_token,
|
| 264 |
+
model_kwargs=model_kwargs
|
| 265 |
+
)
|
| 266 |
+
|
| 267 |
+
#Prompt an history anhängen und einen Text daraus machen
|
| 268 |
+
history_text_und_prompt = generate_prompt_with_history(prompt, history)
|
| 269 |
+
|
| 270 |
+
#zusätzliche Dokumenten Splits aus DB zum Prompt hinzufügen (aus VektorDB - Chroma oder Mongo DB)
|
| 271 |
+
print("LLM aufrufen mit RAG: ...........")
|
| 272 |
+
#result = rag_chain(history_text_und_prompt, vektordatenbank, ANZAHL_DOCS)
|
| 273 |
+
result = rag_chain(llm, history_text_und_prompt, retriever)
|
| 274 |
+
print("result regchain.....................")
|
| 275 |
+
print(result)
|
| 276 |
+
print("Ende result............................")
|
| 277 |
+
|
| 278 |
+
except Exception as e:
|
| 279 |
+
raise gr.Error(e)
|
| 280 |
+
|
| 281 |
+
return result, False
|
| 282 |
+
|
| 283 |
+
|
| 284 |
+
|
| 285 |
+
##############################################################
|
| 286 |
#Eingaben der GUI verarbeiten
|
| 287 |
def generate_auswahl(prompt_in, file, file_history, chatbot, history, anzahl_docs=4, top_p=0.6, temperature=0.5, max_new_tokens=4048, max_context_length_tokens=2048, repetition_penalty=1.3,top_k=5, validate=False):
|
| 288 |
global vektordatenbank, retriever
|
|
|
|
| 332 |
else: #noch nicht validiert, oder kein Prompt
|
| 333 |
return chatbot, history, None, file_history, "Erst validieren oder einen Prompt eingeben!"
|
| 334 |
|
| 335 |
+
|
| 336 |
+
|
| 337 |
+
########################################
|
| 338 |
+
# Bot- test gegen schädliche Bots die die Anwendung testen...
|
| 339 |
+
# Funktion zur Überprüfung der Benutzereingabe
|
| 340 |
+
# Funktion zur Überprüfung der Eingabe und Aktivierung der Hauptanwendung
|
| 341 |
+
def validate_input(user_input_validate, validate=False):
|
| 342 |
+
user_input_hashed = hash_input(user_input_validate)
|
| 343 |
+
if user_input_hashed == hash_input(ANTI_BOT_PW):
|
| 344 |
+
return "Richtig! Weiter gehts... ", True, gr.Textbox(visible=False), gr.Button(visible=False)
|
| 345 |
+
else:
|
| 346 |
+
return "Falsche Antwort!!!!!!!!!", False, gr.Textbox(label = "", placeholder="Bitte tippen Sie das oben im Moodle Kurs angegebene Wort ein, um zu beweisen, dass Sie kein Bot sind.", visible=True, scale= 5), gr.Button("Validieren", visible = True)
|
| 347 |
+
|
| 348 |
+
|
| 349 |
+
|
| 350 |
+
def custom_css():
|
| 351 |
+
return """
|
| 352 |
+
body, html {
|
| 353 |
+
background-color: #303030; /* Dunkler Hintergrund */
|
| 354 |
+
color:#353535;
|
| 355 |
+
}
|
| 356 |
+
"""
|
| 357 |
+
|
| 358 |
|
| 359 |
#############################################################################################
|
| 360 |
# Start Gui Vorabfrage
|