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
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import requests
|
| 2 |
+
import os, sys, json
|
| 3 |
+
import gradio as gr
|
| 4 |
+
import openai
|
| 5 |
+
from openai import OpenAI
|
| 6 |
+
import time
|
| 7 |
+
import re
|
| 8 |
+
import io
|
| 9 |
+
from PIL import Image, ImageDraw, ImageOps, ImageFont
|
| 10 |
+
import base64
|
| 11 |
+
import tempfile
|
| 12 |
+
|
| 13 |
+
from PyPDF2 import PdfReader, PdfWriter
|
| 14 |
+
|
| 15 |
+
from hugchat import hugchat
|
| 16 |
+
from hugchat.login import Login
|
| 17 |
+
from tavily import TavilyClient
|
| 18 |
+
|
| 19 |
+
from langchain.chains import LLMChain, RetrievalQA
|
| 20 |
+
from langchain.chat_models import ChatOpenAI
|
| 21 |
+
from langchain.document_loaders import PyPDFLoader, WebBaseLoader, UnstructuredWordDocumentLoader, DirectoryLoader
|
| 22 |
+
from langchain.document_loaders.blob_loaders.youtube_audio import YoutubeAudioLoader
|
| 23 |
+
from langchain.document_loaders.generic import GenericLoader
|
| 24 |
+
from langchain.document_loaders.parsers import OpenAIWhisperParser
|
| 25 |
+
from langchain.schema import AIMessage, HumanMessage
|
| 26 |
+
from langchain.llms import HuggingFaceHub
|
| 27 |
+
from langchain.llms import HuggingFaceTextGenInference
|
| 28 |
+
from langchain.embeddings import HuggingFaceInstructEmbeddings, HuggingFaceEmbeddings, HuggingFaceBgeEmbeddings, HuggingFaceInferenceAPIEmbeddings
|
| 29 |
+
from langchain.retrievers.tavily_search_api import TavilySearchAPIRetriever
|
| 30 |
+
|
| 31 |
+
from langchain.embeddings.openai import OpenAIEmbeddings
|
| 32 |
+
from langchain.prompts import PromptTemplate
|
| 33 |
+
from langchain.text_splitter import RecursiveCharacterTextSplitter
|
| 34 |
+
from langchain.vectorstores import Chroma
|
| 35 |
+
from chromadb.errors import InvalidDimensionException
|
| 36 |
+
from utils import *
|
| 37 |
+
from beschreibungen import *
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
#from langchain.vectorstores import MongoDBAtlasVectorSearch
|
| 41 |
+
#from pymongo import MongoClient
|
| 42 |
+
|
| 43 |
+
from dotenv import load_dotenv, find_dotenv
|
| 44 |
+
_ = load_dotenv(find_dotenv())
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
###############################################
|
| 48 |
+
#globale Variablen
|
| 49 |
+
##############################################
|
| 50 |
+
#nur bei ersten Anfrage splitten der Dokumente - um die Vektordatenbank entsprechend zu füllen
|
| 51 |
+
#splittet = False
|
| 52 |
+
#DB für Vektorstore
|
| 53 |
+
db = None
|
| 54 |
+
|
| 55 |
+
#############################################
|
| 56 |
+
# Allgemeine Konstanten
|
| 57 |
+
#Filepath zu temp Folder (temp) mit File von ausgewähltem chatverlauf
|
| 58 |
+
file_path_download = ""
|
| 59 |
+
|
| 60 |
+
##################################################
|
| 61 |
+
#Für MongoDB statt Chroma als Vektorstore
|
| 62 |
+
#MONGODB_URI = os.environ["MONGODB_ATLAS_CLUSTER_URI"]
|
| 63 |
+
#client = MongoClient(MONGODB_URI)
|
| 64 |
+
#MONGODB_DB_NAME = "langchain_db"
|
| 65 |
+
#MONGODB_COLLECTION_NAME = "gpt-4"
|
| 66 |
+
#MONGODB_COLLECTION = client[MONGODB_DB_NAME][MONGODB_COLLECTION_NAME]
|
| 67 |
+
#MONGODB_INDEX_NAME = "default"
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
#Plattform Keys aus den Secrets holen zu diesem Space
|
| 72 |
+
HUGGINGFACEHUB_API_TOKEN = os.getenv("HF_ACCESS_READ")
|
| 73 |
+
OAI_API_KEY=os.getenv("OPENAI_API_KEY")
|
| 74 |
+
HEADERS = {"Authorization": f"Bearer {HUGGINGFACEHUB_API_TOKEN}"}
|
| 75 |
+
TAVILY_KEY = os.getenv("TAVILY_KEY")
|
| 76 |
+
os.environ["TAVILY_API_KEY"] = TAVILY_KEY
|
| 77 |
+
ANTI_BOT_PW = os.getenv("CORRECT_VALIDATE")
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
################################################
|
| 81 |
+
#LLM Model mit dem gearbeitet wird
|
| 82 |
+
#openai-------------------------------------
|
| 83 |
+
#MODEL_NAME = "gpt-3.5-turbo-16k"
|
| 84 |
+
#MODEL_NAME = "gpt-3.5-turbo-1106"
|
| 85 |
+
MODEL_NAME= "gpt-4-1106-preview"
|
| 86 |
+
MODEL_NAME_IMAGE = "gpt-4-vision-preview"
|
| 87 |
+
MODEL_NAME_CODE = "code-davinci-002"
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
#verfügbare Modelle anzeigen lassen
|
| 91 |
+
#HuggingFace Reop ID--------------------------------
|
| 92 |
+
#repo_id = "meta-llama/Llama-2-13b-chat-hf"
|
| 93 |
+
repo_id = "HuggingFaceH4/zephyr-7b-alpha" #das Modell ist echt gut!!! Vom MIT
|
| 94 |
+
#repo_id = "TheBloke/Yi-34B-Chat-GGUF"
|
| 95 |
+
#repo_id = "meta-llama/Llama-2-70b-chat-hf"
|
| 96 |
+
#repo_id = "tiiuae/falcon-40b"
|
| 97 |
+
#repo_id = "Vicuna-33b"
|
| 98 |
+
#repo_id = "alexkueck/ChatBotLI2Klein"
|
| 99 |
+
#repo_id = "mistralai/Mistral-7B-v0.1"
|
| 100 |
+
#repo_id = "internlm/internlm-chat-7b"
|
| 101 |
+
#repo_id = "Qwen/Qwen-7B"
|
| 102 |
+
#repo_id = "Salesforce/xgen-7b-8k-base"
|
| 103 |
+
#repo_id = "Writer/camel-5b-hf"
|
| 104 |
+
#repo_id = "databricks/dolly-v2-3b"
|
| 105 |
+
#repo_id = "google/flan-t5-xxl"
|
| 106 |
+
#repo_id = "mistralai/Mixtral-8x7B-Instruct-v0.1"
|
| 107 |
+
#repo_id = "abacusai/Smaug-72B-v0.1"
|
| 108 |
+
|
| 109 |
+
#HuggingFace Model name--------------------------------
|
| 110 |
+
MODEL_NAME_HF = "mistralai/Mixtral-8x7B-Instruct-v0.1"
|
| 111 |
+
#MODLE_NAME_HF = "abacusai/Smaug-72B-v0.1"
|
| 112 |
+
MODEL_NAME_OAI_ZEICHNEN = "dall-e-3"
|
| 113 |
+
#Alternativ zeichnen: Stabe Diffusion from HF:
|
| 114 |
+
#API Inference allgemien: https://api-inference.huggingface.co/models/{model}
|
| 115 |
+
#Zeichnen
|
| 116 |
+
API_URL = "https://api-inference.huggingface.co/models/stabilityai/stable-diffusion-2-1"
|
| 117 |
+
#Textgenerierung
|
| 118 |
+
API_URL_TEXT = "https://api-inference.huggingface.co/models/argilla/notux-8x7b-v1"
|
| 119 |
+
|
| 120 |
+
###############################################
|
| 121 |
+
# Formatierung im PDF - Konstanten setzen
|
| 122 |
+
# Breite und Höhe für Spalten
|
| 123 |
+
COLUMN_WIDTH = 150
|
| 124 |
+
ROW_HEIGHT = 20
|
| 125 |
+
# Bereiche für Spalten
|
| 126 |
+
TIMESTAMP_X = 50
|
| 127 |
+
USER_X = TIMESTAMP_X + COLUMN_WIDTH
|
| 128 |
+
ASSISTANT_X = USER_X + COLUMN_WIDTH
|
| 129 |
+
# Rand und Abstand zwischen Zeilen
|
| 130 |
+
MARGIN = 50
|
| 131 |
+
LINE_SPACING = 10
|
| 132 |
+
|
| 133 |
+
|
| 134 |
+
|
| 135 |
+
################################################
|
| 136 |
+
#HF Hub Zugriff ermöglichen
|
| 137 |
+
###############################################
|
| 138 |
+
os.environ["HUGGINGFACEHUB_API_TOKEN"] = HUGGINGFACEHUB_API_TOKEN
|
| 139 |
+
|
| 140 |
+
###############################################
|
| 141 |
+
#Alternativ: HuggingChat API nutzen
|
| 142 |
+
pw=os.getenv("HFPW")
|
| 143 |
+
email= os.getenv("HFEMail")
|
| 144 |
+
#sign = Login(email, pw)
|
| 145 |
+
#cookies = sign.login()
|
| 146 |
+
# Save cookies to the local directory
|
| 147 |
+
#cookie_path_dir = "cookies_hf"
|
| 148 |
+
#sign.saveCookiesToDir(cookie_path_dir)
|
| 149 |
+
|
| 150 |
+
|
| 151 |
+
################################################
|
| 152 |
+
#OpenAI Zugang, client und Assistant einmal erzeugen.
|
| 153 |
+
################################################
|
| 154 |
+
#zentral einmal erzeugen!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
|
| 155 |
+
client = OpenAI()
|
| 156 |
+
general_assistant_file = client.beta.assistants.create(name="File Analysator",instructions=template, model="gpt-4-1106-preview",)
|
| 157 |
+
thread_file = client.beta.threads.create()
|
| 158 |
+
general_assistant_suche= openai_assistant_suche(client)
|
| 159 |
+
|
| 160 |
+
|
| 161 |
+
#################################################
|
| 162 |
+
#################################################
|
| 163 |
+
#################################################
|
| 164 |
+
#Funktionen zur Verarbeitung
|
| 165 |
+
################################################
|
| 166 |
+
|
| 167 |
+
##############################################
|
| 168 |
+
#wenn löschen Button geklickt
|
| 169 |
+
def clear_all(history, uploaded_file_paths, chats):
|
| 170 |
+
dic_history = {schluessel: wert for schluessel, wert in history}
|
| 171 |
+
#später wird die summary auf 50 tokens verkürzt, um die Anfrage nicht so teuer werden zu lassen
|
| 172 |
+
#summary wird gebraucht für die Anfrage beim NN, um eine Überschrift des Eintrages zu generieren
|
| 173 |
+
summary = "\n\n".join(f'{schluessel}: \n {wert}' for schluessel, wert in dic_history.items())
|
| 174 |
+
|
| 175 |
+
#falls file mit summay für download existiert hat: das zunächst löschen
|
| 176 |
+
#cleanup(file_path_download)
|
| 177 |
+
#noch nicht im Einsatz, aber hier werden alle Chats einer Sitzung gespeichert
|
| 178 |
+
#den aktuellen Chatverlauf zum Download bereitstellen:
|
| 179 |
+
if chats != {} :
|
| 180 |
+
id_neu = len(chats)+1
|
| 181 |
+
chats[id_neu]= summary
|
| 182 |
+
else:
|
| 183 |
+
chats[0]= summary
|
| 184 |
+
|
| 185 |
+
#Eine Überschrift zu dem jeweiligen Chatverlauf finden - abhängig vom Inhalt
|
| 186 |
+
#file_path_download = save_and_download(summary)
|
| 187 |
+
headers, payload = process_chatverlauf(summary, MODEL_NAME, OAI_API_KEY)
|
| 188 |
+
response = requests.post("https://api.openai.com/v1/chat/completions", headers=headers, json=payload)
|
| 189 |
+
#als json ausgeben
|
| 190 |
+
data = response.json()
|
| 191 |
+
# Den "content" auswählen, da dort die Antwort der Ki enthalten ist
|
| 192 |
+
result = data['choices'][0]['message']['content']
|
| 193 |
+
worte = result.split()
|
| 194 |
+
if len(worte) > 2:
|
| 195 |
+
file_path_download = "data/" + str(len(chats)) + "_Chatverlauf.pdf"
|
| 196 |
+
else:
|
| 197 |
+
file_path_download = "data/" + str(len(chats)) + "_" + result + ".pdf"
|
| 198 |
+
|
| 199 |
+
erstellePdf(file_path_download, result, dic_history)
|
| 200 |
+
|
| 201 |
+
|
| 202 |
+
#die session variable in gradio erweitern und alle fliepath neu in das gr.File hochladen
|
| 203 |
+
uploaded_file_paths= uploaded_file_paths + [file_path_download]
|
| 204 |
+
|
| 205 |
+
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
|
| 206 |
+
|
| 207 |
+
|
| 208 |
+
#wenn löschen Button geklickt
|
| 209 |
+
def clear_all3(history):
|
| 210 |
+
#die session variable in gradio erweitern und alle fliepath neu in das gr.File hochladen
|
| 211 |
+
uploaded_file_paths= ""
|
| 212 |
+
return None, gr.Image(visible=False), [],
|
| 213 |
+
|
| 214 |
+
|
| 215 |
+
|
| 216 |
+
##############################################
|
| 217 |
+
#History - die Frage oder das File eintragen...
|
| 218 |
+
#in history_file ist ein file gespeichert, falls voher im Verlauf schon ein File hochgeladen wurde.
|
| 219 |
+
#wird ein neuer File hochgeladen, so wird history_fiel dadurch ersetzt
|
| 220 |
+
def add_text(chatbot, history, prompt, file, file_history):
|
| 221 |
+
if (file == None):
|
| 222 |
+
chatbot = chatbot +[(prompt, None)]
|
| 223 |
+
else:
|
| 224 |
+
file_history = file
|
| 225 |
+
if (prompt == ""):
|
| 226 |
+
chatbot=chatbot + [((file.name,), "Prompt fehlt!")]
|
| 227 |
+
else:
|
| 228 |
+
ext = analyze_file(file)
|
| 229 |
+
if (ext == "png" or ext == "PNG" or ext == "jpg" or ext == "jpeg" or ext == "JPG" or ext == "JPEG"):
|
| 230 |
+
chatbot = chatbot +[((file.name,), None), (prompt, None)]
|
| 231 |
+
else:
|
| 232 |
+
chatbot = chatbot +[("Hochgeladenes Dokument: "+ get_filename(file) +"\n" + prompt, None)]
|
| 233 |
+
|
| 234 |
+
return chatbot, history, prompt, file, file_history, gr.Image(visible = False), "" #gr.Image( label=None, size=(30,30), visible=False, scale=1) #gr.Textbox(value="", interactive=False)
|
| 235 |
+
|
| 236 |
+
def add_text2(chatbot, prompt):
|
| 237 |
+
if (prompt == ""):
|
| 238 |
+
chatbot = chatbot + [("", "Prompt fehlt!")]
|
| 239 |
+
else:
|
| 240 |
+
chatbot = chatbot + [(prompt, None)]
|
| 241 |
+
print("chatbot nach add_text............")
|
| 242 |
+
print(chatbot)
|
| 243 |
+
return chatbot, prompt, ""
|
| 244 |
+
|
| 245 |
+
|
| 246 |
+
############################################
|
| 247 |
+
#nach dem Upload soll das zusätzliche Fenster mit dem image drinnen angezeigt werden
|
| 248 |
+
def file_anzeigen(file):
|
| 249 |
+
ext = analyze_file(file)
|
| 250 |
+
if (ext == "png" or ext == "PNG" or ext == "jpg" or ext == "jpeg" or ext == "JPG" or ext == "JPEG"):
|
| 251 |
+
return gr.Image(width=47, visible=True, interactive = False, height=47, min_width=47, show_label=False, show_share_button=False, show_download_button=False, scale = 0.5), file, file
|
| 252 |
+
else:
|
| 253 |
+
return gr.Image(width=47, visible=True, interactive = False, height=47, min_width=47, show_label=False, show_share_button=False, show_download_button=False, scale = 0.5), "data/file.png", file
|
| 254 |
+
|
| 255 |
+
def file_loeschen():
|
| 256 |
+
return None, gr.Image(visible = False)
|
| 257 |
+
|
| 258 |
+
############################################
|
| 259 |
+
#wenn 'Stop' Button geklickt, dann Message dazu und das Eingabe-Fenster leeren
|
| 260 |
+
def cancel_outputing():
|
| 261 |
+
reset_textbox()
|
| 262 |
+
return "Stop Done"
|
| 263 |
+
|
| 264 |
+
def reset_textbox():
|
| 265 |
+
return gr.update(value=""),""
|
| 266 |
+
|
| 267 |
+
|
| 268 |
+
##########################################
|
| 269 |
+
#Hilfsfunktion, um ein von Stable Diffusion erzeugtes Bild für die Ausgabe in der History vorzubereiten
|
| 270 |
+
def umwandeln_fuer_anzeige(image):
|
| 271 |
+
buffer = io.BytesIO()
|
| 272 |
+
image.save(buffer, format='PNG')
|
| 273 |
+
return buffer.getvalue()
|
| 274 |
+
|
| 275 |
+
|
| 276 |
+
|
| 277 |
+
##################################################
|
| 278 |
+
#openassistant um uploaded Files zu analysieren
|
| 279 |
+
def create_assistant_file(prompt, file):
|
| 280 |
+
global client, general_assistant_file
|
| 281 |
+
#neues File dem Assistant hinzufügen
|
| 282 |
+
file_neu = client.files.create(file=open(file,"rb",),purpose="assistants",)
|
| 283 |
+
# Update Assistant
|
| 284 |
+
#wenn type: code_interpreter, wird das file mit angehängt an den Prpmt, aber vorher nicht bearbeitet
|
| 285 |
+
#wenn type: retrieval, wird das Dokument vorher embedded in einem vektorstore und nur entsprechende chunks mitgegeben.
|
| 286 |
+
#pro Assistant 20 cent pro Tag als Nutzung - egal wie viele Fragen dazu.
|
| 287 |
+
updated_assistant = client.beta.assistants.update(general_assistant_file.id,tools=[{"type": "code_interpreter"}, {"type": "retrieval"}],file_ids=[file_neu.id],)
|
| 288 |
+
thread_file, run = create_thread_and_run(prompt, client, updated_assistant.id)
|
| 289 |
+
run = wait_on_run(run, thread_file, client)
|
| 290 |
+
response = get_response(thread_file, client, updated_assistant.id)
|
| 291 |
+
result = response.data[1].content[0].text.value
|
| 292 |
+
return result
|
| 293 |
+
|
| 294 |
+
##################################################
|
| 295 |
+
#openassistant um im Netz zu suchen
|
| 296 |
+
def create_assistant_suche(prompt):
|
| 297 |
+
#global client, general_assistant_suche
|
| 298 |
+
|
| 299 |
+
retriever = TavilySearchAPIRetriever(k=4)
|
| 300 |
+
result = retriever.invoke(template + prompt)
|
| 301 |
+
erg = "Aus dem Internet: " + result[0].page_content + ".\n Quelle: "
|
| 302 |
+
src = result[0].metadata['source']
|
| 303 |
+
|
| 304 |
+
"""
|
| 305 |
+
#neues Thread mit akt. prompt dem Assistant hinzufügen
|
| 306 |
+
thread_suche, run = create_thread_and_run(prompt, client, general_assistant_suche.id)
|
| 307 |
+
run = wait_on_run(run, thread_suche, client)
|
| 308 |
+
response = get_response(thread_suche, client, general_assistant_suche.id)
|
| 309 |
+
result = response.data[1].content[0].text.value
|
| 310 |
+
"""
|
| 311 |
+
return erg + src
|
| 312 |
+
|
| 313 |
+
|
| 314 |
+
#huggingchat um im Netz zu suchen
|
| 315 |
+
def create_assistant_suche_hf(chatbot, prompt):
|
| 316 |
+
erg, src = hugchat_search(chatbot, prompt)
|
| 317 |
+
return erg + src
|
| 318 |
+
|
| 319 |
+
###################################################
|
| 320 |
+
#Funktion von Gradio aus, die den dort eingegebenen Prompt annimmt und weiterverarbeitet
|
| 321 |
+
###################################################
|
| 322 |
+
#########################################################
|
| 323 |
+
#Funktion wird direkt aufgerufen aus der GUI - von hier muss auch die Rückmeldung kommen....
|
| 324 |
+
#man kann einen Text-Prompt eingeben (mit oder ohne RAG), dazu ein Image hochladen, ein Bild zu einem reinen textprompt erzeugen lassen
|
| 325 |
+
def generate_auswahl(prompt_in, file, file_history, chatbot, history, rag_option, model_option, openai_api_key, k=3, top_p=0.6, temperature=0.5, max_new_tokens=4048, max_context_length_tokens=2048, repetition_penalty=1.3,top_k=35, websuche="Aus", validate=False):
|
| 326 |
+
global db
|
| 327 |
+
#nur wenn man sich validiert hat, kann die Anwendung los legen
|
| 328 |
+
if (validate and not prompt_in == "" and not prompt_in == None):
|
| 329 |
+
#wenn RAG angeschaltet - Vektorstore initialisieren
|
| 330 |
+
#aber nur, wenn es noch nicht geshehen ist (splittet = False)
|
| 331 |
+
#falls schon ein File hochgeladen wurde, ist es in history_file gespeichert - falls ein neues File hochgeladen wurde, wird es anschließend neu gesetzt
|
| 332 |
+
neu_file = file_history
|
| 333 |
+
|
| 334 |
+
#prompt normalisieren bevor er an die KIs geht
|
| 335 |
+
prompt = normalise_prompt(prompt_in)
|
| 336 |
+
|
| 337 |
+
if (rag_option == "An"):
|
| 338 |
+
#muss nur einmal ausgeführt werden...
|
| 339 |
+
if db == None:
|
| 340 |
+
print("db neu aufbauen!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!1")
|
| 341 |
+
splits = document_loading_splitting()
|
| 342 |
+
document_storage_chroma(splits)
|
| 343 |
+
db = document_retrieval_chroma2()
|
| 344 |
+
print("db aktiv!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!")
|
| 345 |
+
print(db)
|
| 346 |
+
#else: #unnötig, da wenn Vektorstor einmal für alle user eingerichtet, wer weiter besthen bleiben kann - die unterschiedlichen Propmt werden dann später je nach rag_option erzeugt
|
| 347 |
+
#db=None
|
| 348 |
+
#splittet = False #sonst würde es für alle User wieder ausgeschaltet - Alternative: gr.State(False) dazu anlegen
|
| 349 |
+
|
| 350 |
+
#kein Bild hochgeladen -> auf Text antworten...
|
| 351 |
+
status = "Antwort der KI ..."
|
| 352 |
+
if (file == None and file_history == None):
|
| 353 |
+
result, status = generate_text(prompt, chatbot, history, rag_option, model_option, openai_api_key, db, websuche, k=3, top_p=0.6, temperature=0.5, max_new_tokens=4048, max_context_length_tokens=2048, repetition_penalty=1.3, top_k=3)
|
| 354 |
+
history = history + [[prompt, result]]
|
| 355 |
+
else:
|
| 356 |
+
#Es wurde ein File neu angehängt -> wenn prompt dazu, das Bild analysieren
|
| 357 |
+
#das history_fiel muss neu gesetzt werden
|
| 358 |
+
if (file != None):
|
| 359 |
+
# file_history wird neu gesetzt in der Rückgabe dieser Funktion...
|
| 360 |
+
neu_file = file
|
| 361 |
+
|
| 362 |
+
#herausfinden, ob Bild oder Dokument...
|
| 363 |
+
ext = analyze_file(neu_file)
|
| 364 |
+
if (ext == "png" or ext == "PNG" or ext == "jpg" or ext == "jpeg" or ext == "JPG" or ext == "JPEG"):
|
| 365 |
+
result= generate_text_zu_bild(neu_file, prompt, k, rag_option, chatbot, history, db)
|
| 366 |
+
else:
|
| 367 |
+
result = generate_text_zu_doc(neu_file, prompt, k, rag_option, chatbot, history, db)
|
| 368 |
+
|
| 369 |
+
#die history erweitern - abhängig davon, ob gerade ein file hochgeladen wurde oder nicht
|
| 370 |
+
if (file != None):
|
| 371 |
+
history = history + [[(file,), None],[prompt, result]]
|
| 372 |
+
else:
|
| 373 |
+
history = history + [[prompt, result]]
|
| 374 |
+
|
| 375 |
+
chatbot[-1][1] = ""
|
| 376 |
+
for character in result:
|
| 377 |
+
chatbot[-1][1] += character
|
| 378 |
+
time.sleep(0.03)
|
| 379 |
+
yield chatbot, history, None, neu_file, status
|
| 380 |
+
if shared_state.interrupted:
|
| 381 |
+
shared_state.recover()
|
| 382 |
+
try:
|
| 383 |
+
yield chatbot, history, None, neu_file, "Stop: Success"
|
| 384 |
+
except:
|
| 385 |
+
pass
|
| 386 |
+
else: #noch nicht validiert, oder kein Prompt
|
| 387 |
+
return chatbot, history, None, file_history, "Erst validieren oder einen Prompt eingeben!"
|
| 388 |
+
|
| 389 |
+
##################################################
|
| 390 |
+
#zu einem Text-Prompt ein Bild via Stable Diffusion generieren
|
| 391 |
+
def generate_bild(prompt, chatbot, model_option_zeichnen='HuggingFace', temperature=0.5, max_new_tokens=4048,top_p=0.6, repetition_penalty=1.3, validate=False):
|
| 392 |
+
global client
|
| 393 |
+
if (validate):
|
| 394 |
+
if (model_option_zeichnen == "Stable Diffusion"):
|
| 395 |
+
print("Bild Erzeugung HF..............................")
|
| 396 |
+
#Bild nach Anweisung zeichnen und in History darstellen...
|
| 397 |
+
data = {"inputs": prompt}
|
| 398 |
+
response = requests.post(API_URL, headers=HEADERS, json=data)
|
| 399 |
+
print("fertig Bild")
|
| 400 |
+
result = response.content
|
| 401 |
+
#Bild ausgeben
|
| 402 |
+
image = Image.open(io.BytesIO(result))
|
| 403 |
+
image_64 = umwandeln_fuer_anzeige(image)
|
| 404 |
+
chatbot[-1][1]= "<img src='data:image/png;base64,{0}'/>".format(base64.b64encode(image_64).decode('utf-8'))
|
| 405 |
+
else:
|
| 406 |
+
print("Bild Erzeugung DallE..............................")
|
| 407 |
+
#als Format ginge auch 'url', n - Anz. der erzeugten Bilder
|
| 408 |
+
response = client.images.generate(model="dall-e-3",prompt=prompt,size="1024x1024",quality="standard",n=1, response_format='b64_json')
|
| 409 |
+
#chatbot[-1][1]= "<img src='data:image/png;base64,{0}'/>".format(base64.b64encode(image_64).decode('utf-8'))
|
| 410 |
+
chatbot[-1][1] = "<img src='data:image/png;base64,{0}'/>".format(response.data[0].b64_json)
|
| 411 |
+
|
| 412 |
+
return chatbot, "Antwort KI: Success"
|
| 413 |
+
else: #noch nicht validiert ...
|
| 414 |
+
return chatbot, "Bitte erst validieren!"
|
| 415 |
+
|
| 416 |
+
|
| 417 |
+
##################################################
|
| 418 |
+
#zu einem Bild und Text-Prompt eine Analyse generieren
|
| 419 |
+
def generate_text_zu_bild(file, prompt, k, rag_option, chatbot, history, db):
|
| 420 |
+
global splittet
|
| 421 |
+
print("Text mit Bild ..............................")
|
| 422 |
+
prompt_neu = generate_prompt_with_history(prompt, history)
|
| 423 |
+
if (rag_option == "An"):
|
| 424 |
+
print("Bild mit RAG..............................")
|
| 425 |
+
neu_text_mit_chunks = rag_chain2(prompt, db, k)
|
| 426 |
+
#für Chat LLM:
|
| 427 |
+
#prompt = generate_prompt_with_history_openai(neu_text_mit_chunks, history)
|
| 428 |
+
#als reiner prompt:
|
| 429 |
+
prompt_neu = generate_prompt_with_history(neu_text_mit_chunks, history)
|
| 430 |
+
|
| 431 |
+
headers, payload = process_image(file, prompt_neu, MODEL_NAME_IMAGE, OAI_API_KEY)
|
| 432 |
+
response = requests.post("https://api.openai.com/v1/chat/completions", headers=headers, json=payload)
|
| 433 |
+
#als json ausgeben
|
| 434 |
+
data = response.json()
|
| 435 |
+
# Den "content" auswählen, da dort die Antwort der Ki enthalten ist
|
| 436 |
+
result = data['choices'][0]['message']['content']
|
| 437 |
+
return result
|
| 438 |
+
|
| 439 |
+
|
| 440 |
+
##################################################
|
| 441 |
+
#zu einem Bild und Text-Prompt eine Analyse generieren
|
| 442 |
+
def generate_text_zu_doc(file, prompt, k, rag_option, chatbot, history, db):
|
| 443 |
+
global splittet
|
| 444 |
+
print("text mit doc ..............................")
|
| 445 |
+
|
| 446 |
+
prompt_neu = generate_prompt_with_history(prompt, history)
|
| 447 |
+
if (rag_option == "An"):
|
| 448 |
+
print("Doc mit RAG..............................")
|
| 449 |
+
neu_text_mit_chunks = rag_chain2(prompt, db, k)
|
| 450 |
+
#für Chat LLM:
|
| 451 |
+
#prompt_neu = generate_prompt_with_history_openai(neu_text_mit_chunks, history)
|
| 452 |
+
#als reiner prompt:
|
| 453 |
+
prompt_neu = generate_prompt_with_history(neu_text_mit_chunks, history)
|
| 454 |
+
|
| 455 |
+
result = create_assistant_file(prompt_neu, file)
|
| 456 |
+
return result
|
| 457 |
+
|
| 458 |
+
|
| 459 |
+
####################################################
|
| 460 |
+
#aus einem Text-Prompt die Antwort von KI bekommen
|
| 461 |
+
#mit oder ohne RAG möglich
|
| 462 |
+
def generate_text (prompt, chatbot, history, rag_option, model_option, openai_api_key, db, websuche, k=3, top_p=0.6, temperature=0.5, max_new_tokens=4048, max_context_length_tokens=2048, repetition_penalty=1.3, top_k=35):
|
| 463 |
+
#global splittet
|
| 464 |
+
#hugchat=False
|
| 465 |
+
suche_im_Netz="Antwort der KI ..."
|
| 466 |
+
print("Text pur..............................")
|
| 467 |
+
|
| 468 |
+
if (openai_api_key == "" or openai_api_key == "sk-"):
|
| 469 |
+
#raise gr.Error("OpenAI API Key is required.")
|
| 470 |
+
#eigenen OpenAI key nutzen
|
| 471 |
+
openai_api_key= OAI_API_KEY
|
| 472 |
+
if (rag_option is None):
|
| 473 |
+
raise gr.Error("Retrieval Augmented Generation ist erforderlich.")
|
| 474 |
+
if (prompt == ""):
|
| 475 |
+
raise gr.Error("Prompt ist erforderlich.")
|
| 476 |
+
|
| 477 |
+
#history für HuggingFace Models formatieren
|
| 478 |
+
#history_text_und_prompt = generate_prompt_with_history_hf(prompt, history)
|
| 479 |
+
#history für openAi formatieren
|
| 480 |
+
#history_text_und_prompt = generate_prompt_with_history_openai(prompt, history)
|
| 481 |
+
#history für Langchain formatieren
|
| 482 |
+
#history_text_und_prompt = generate_prompt_with_history_langchain(prompt, history)
|
| 483 |
+
|
| 484 |
+
try:
|
| 485 |
+
if (websuche=="Aus"):
|
| 486 |
+
###########################
|
| 487 |
+
#LLM auswählen (OpenAI oder HF)
|
| 488 |
+
###########################
|
| 489 |
+
if (model_option == "OpenAI"):
|
| 490 |
+
#Anfrage an OpenAI ----------------------------
|
| 491 |
+
print("OpenAI Anfrage.......................")
|
| 492 |
+
llm = ChatOpenAI(model_name = MODEL_NAME, openai_api_key = openai_api_key, temperature=temperature)#, top_p = top_p)
|
| 493 |
+
#Prompt an history anhängen und einen Text daraus machen
|
| 494 |
+
#wenn da Dokumenten Teile (RAG dazu kommen, wird das anders zusammengestellt, als ohne...)
|
| 495 |
+
if (rag_option == "An"):
|
| 496 |
+
history_text_und_prompt = generate_prompt_with_history(prompt, history)
|
| 497 |
+
else:
|
| 498 |
+
history_text_und_prompt = generate_prompt_with_history_openai(prompt, history)
|
| 499 |
+
else:
|
| 500 |
+
#oder an Hugging Face --------------------------
|
| 501 |
+
print("HF Anfrage.......................")
|
| 502 |
+
model_kwargs={"temperature": 0.5, "max_length": 512, "num_return_sequences": 1, "top_k": top_k, "top_p": top_p, "repetition_penalty": repetition_penalty}
|
| 503 |
+
llm = HuggingFaceHub(repo_id=repo_id, model_kwargs=model_kwargs)
|
| 504 |
+
#llm = HuggingFaceChain(model=MODEL_NAME_HF, model_kwargs={"temperature": 0.5, "max_length": 128})
|
| 505 |
+
#llm = HuggingFaceHub(url_??? = "https://wdgsjd6zf201mufn.us-east-1.aws.endpoints.huggingface.cloud", model_kwargs={"temperature": 0.5, "max_length": 64})
|
| 506 |
+
#llm = HuggingFaceTextGenInference( inference_server_url="http://localhost:8010/", max_new_tokens=max_new_tokens,top_k=10,top_p=top_p,typical_p=0.95,temperature=temperature,repetition_penalty=repetition_penalty,)
|
| 507 |
+
#llm via HuggingChat
|
| 508 |
+
#llm = hugchat.ChatBot(cookies=cookies.get_dict())
|
| 509 |
+
#hugchat=True #da dieses Model in llm_chain bzw reag_chain anderes verarbeitet wird
|
| 510 |
+
|
| 511 |
+
print("HF")
|
| 512 |
+
#Prompt an history anhängen und einen Text daraus machen
|
| 513 |
+
history_text_und_prompt = generate_prompt_with_history(prompt, history)
|
| 514 |
+
|
| 515 |
+
#zusätzliche Dokumenten Splits aus DB zum Prompt hinzufügen (aus VektorDB - Chroma oder Mongo DB)
|
| 516 |
+
if (rag_option == "An"):
|
| 517 |
+
print("LLM aufrufen mit RAG: ...........")
|
| 518 |
+
print(history_text_und_prompt)
|
| 519 |
+
print("-------------------------------")
|
| 520 |
+
result = rag_chain(llm, history_text_und_prompt, db) #für hugchat noch kein rag möglich...
|
| 521 |
+
#weitere Möglichkeit für Rag-Chain - dann auch für HF Modelle möglich, da kein llm in Langchain übergeben werden muss...
|
| 522 |
+
#result = rag_chain2(history_text_und_prompt, db, 5)
|
| 523 |
+
print("result regchain.....................")
|
| 524 |
+
print(result)
|
| 525 |
+
else:
|
| 526 |
+
#splittet = False
|
| 527 |
+
print("LLM aufrufen ohne RAG: ...........")
|
| 528 |
+
resulti = llm_chain(llm, history_text_und_prompt)
|
| 529 |
+
result = resulti.strip()
|
| 530 |
+
"""
|
| 531 |
+
#Alternativ mit API_URL - aber das model braucht 93 B Space!!!
|
| 532 |
+
data = {"inputs": prompt, "options": {"max_new_tokens": max_new_tokens},}
|
| 533 |
+
response = requests.post(API_URL_TEXT, headers=HEADERS, json=data)
|
| 534 |
+
result = response.json()
|
| 535 |
+
print("responseresult.............................")
|
| 536 |
+
print(result)
|
| 537 |
+
chatbot_response = result[0]['generated_text']
|
| 538 |
+
print("anzahl tokens gesamt antwort:------------------")
|
| 539 |
+
print (len(chatbot_response.split()))
|
| 540 |
+
chatbot_message = chatbot_response[len(prompt):].strip()
|
| 541 |
+
print("history/chatbot_rsponse:--------------------------------")
|
| 542 |
+
print(history)
|
| 543 |
+
print(chatbot_message)
|
| 544 |
+
result = chatbot_message
|
| 545 |
+
"""
|
| 546 |
+
else: #Websuche ist An
|
| 547 |
+
print("Suche im Netz: ...........")
|
| 548 |
+
suche_im_Netz="Antwort aus dem Internet ..."
|
| 549 |
+
#Prompt an history anhängen und einen Text daraus machen
|
| 550 |
+
history_text_und_prompt = generate_prompt_with_history(prompt, history)
|
| 551 |
+
#if (hugchat):
|
| 552 |
+
#mit hugchat
|
| 553 |
+
#result = create_assistant_suche_hf(llm, history_text_und_prompt)
|
| 554 |
+
#else:
|
| 555 |
+
#mit tavily:
|
| 556 |
+
result = create_assistant_suche(history_text_und_prompt)
|
| 557 |
+
|
| 558 |
+
|
| 559 |
+
"""
|
| 560 |
+
#Wenn keine Antwort möglich "Ich weiß es nicht" etc., dann versuchen mit Suche im Internet.
|
| 561 |
+
if (result == None or is_response_similar(result)):
|
| 562 |
+
print("Suche im Netz: ...........")
|
| 563 |
+
suche_im_Netz="Antwort aus dem Internet ..."
|
| 564 |
+
result = create_assistant_suche(prompt)
|
| 565 |
+
"""
|
| 566 |
+
except Exception as e:
|
| 567 |
+
raise gr.Error(e)
|
| 568 |
+
|
| 569 |
+
return result, suche_im_Netz
|
| 570 |
+
|
| 571 |
+
|
| 572 |
+
#Funktion wird direkt aufgerufen aus der GUI - von hier muss auch die Rückmeldung kommen....
|
| 573 |
+
#man kann einen Text-Prompt eingeben , dazu ein Image hochladen, und dann dazu code erzeugen lassen
|
| 574 |
+
def generate_code(prompt_in, file, file_history, chatbot, history, model_option, openai_api_key, k=3, top_p=0.6, temperature=0.5, max_new_tokens=4048, max_context_length_tokens=2048, repetition_penalty=1.3,top_k=35):
|
| 575 |
+
#prompt normalisieren bevor er an die KIs geht
|
| 576 |
+
prompt = normalise_prompt(prompt_in)
|
| 577 |
+
#falls schon ein File hochgeladen wurde, ist es in history_file gespeichert - falls ein neues File hochgeladen wurde, wird es anschließend neu gesetzt
|
| 578 |
+
neu_file = file_history
|
| 579 |
+
|
| 580 |
+
#kein Bild hochgeladen -> auf Text antworten...
|
| 581 |
+
status = "Antwort der KI ..."
|
| 582 |
+
if (file == None and file_history == None):
|
| 583 |
+
result, status = generate_code_antwort(prompt, chatbot, history, model_option, openai_api_key, k=3, top_p=0.6, temperature=0.5, max_new_tokens=4048, max_context_length_tokens=2048, repetition_penalty=1.3, top_k=35)
|
| 584 |
+
history = history + [[prompt, result]]
|
| 585 |
+
else:
|
| 586 |
+
#Es wurde ein File neu angehängt -> wenn prompt dazu, das Bild analysieren
|
| 587 |
+
#das history_fiel muss neu gesetzt werden
|
| 588 |
+
if (file != None):
|
| 589 |
+
# file_history wird neu gesetzt in der Rückgabe dieser Funktion...
|
| 590 |
+
neu_file = file
|
| 591 |
+
|
| 592 |
+
#herausfinden, ob Bild oder Dokument...
|
| 593 |
+
ext = analyze_file(neu_file)
|
| 594 |
+
if (ext == "png" or ext == "PNG" or ext == "jpg" or ext == "jpeg" or ext == "JPG" or ext == "JPEG"):
|
| 595 |
+
result= generate_text_zu_bild(neu_file, prompt, k, rag_option, chatbot, history, db)
|
| 596 |
+
else:
|
| 597 |
+
result = generate_text_zu_doc(neu_file, prompt, k, rag_option, chatbot, history, db)
|
| 598 |
+
|
| 599 |
+
#die history erweitern - abhängig davon, ob gerade ein file hochgeladen wurde oder nicht
|
| 600 |
+
if (file != None):
|
| 601 |
+
history = history + [[(file,), None],[prompt, result]]
|
| 602 |
+
else:
|
| 603 |
+
history = history + [[prompt, result]]
|
| 604 |
+
|
| 605 |
+
chatbot[-1][1] = ""
|
| 606 |
+
for character in result:
|
| 607 |
+
chatbot[-1][1] += character
|
| 608 |
+
time.sleep(0.03)
|
| 609 |
+
yield chatbot, history, None, neu_file, status
|
| 610 |
+
if shared_state.interrupted:
|
| 611 |
+
shared_state.recover()
|
| 612 |
+
try:
|
| 613 |
+
yield chatbot, history, None, neu_file, "Stop: Success"
|
| 614 |
+
except:
|
| 615 |
+
pass
|
| 616 |
+
|
| 617 |
+
|
| 618 |
+
####################################################
|
| 619 |
+
#aus einem Text-Prompt die Antwort von KI bekommen
|
| 620 |
+
#mit oder ohne RAG möglich
|
| 621 |
+
def generate_code_antwort (prompt, chatbot, history, model_option, openai_api_key, k=3, top_p=0.6, temperature=0.5, max_new_tokens=4048, max_context_length_tokens=2048, repetition_penalty=1.3, top_k=35):
|
| 622 |
+
suche_im_Netz="Antwort der KI ..."
|
| 623 |
+
print("Text pur..............................")
|
| 624 |
+
if (openai_api_key == "" or openai_api_key == "sk-"):
|
| 625 |
+
#raise gr.Error("OpenAI API Key is required.")
|
| 626 |
+
#eigenen OpenAI key nutzen
|
| 627 |
+
openai_api_key= OAI_API_KEY
|
| 628 |
+
if (prompt == ""):
|
| 629 |
+
raise gr.Error("Prompt ist erforderlich.")
|
| 630 |
+
|
| 631 |
+
|
| 632 |
+
try:
|
| 633 |
+
###########################
|
| 634 |
+
#LLM auswählen (OpenAI oder HF)
|
| 635 |
+
###########################
|
| 636 |
+
if (model_option == "Davinci"):
|
| 637 |
+
#Anfrage an OpenAI ----------------------------
|
| 638 |
+
print("OpenAI Anfrage.......................")
|
| 639 |
+
llm = ChatOpenAI(model_name = MODEL_NAME_CODE, openai_api_key = openai_api_key, temperature=temperature)#, top_p = top_p)
|
| 640 |
+
#Prompt an history anhängen und einen Text daraus machen
|
| 641 |
+
history_text_und_prompt = generate_prompt_with_history_openai(prompt, history)
|
| 642 |
+
else:
|
| 643 |
+
llm = ChatOpenAI(model_name = MODEL_NAME_IMAGE, openai_api_key = openai_api_key, temperature=temperature)#, top_p = top_p)
|
| 644 |
+
#Prompt an history anhängen und einen Text daraus machen
|
| 645 |
+
history_text_und_prompt = generate_prompt_with_history_openai(prompt, history)
|
| 646 |
+
|
| 647 |
+
print("LLM aufrufen ohne RAG: ...........")
|
| 648 |
+
resulti = llm_chain(llm, history_text_und_prompt)
|
| 649 |
+
result = resulti.strip()
|
| 650 |
+
except Exception as e:
|
| 651 |
+
raise gr.Error(e)
|
| 652 |
+
|
| 653 |
+
return result, suche_im_Netz
|
| 654 |
+
|
| 655 |
+
################################################
|
| 656 |
+
#GUI
|
| 657 |
+
###############################################
|
| 658 |
+
#Beschreibung oben in GUI
|
| 659 |
+
################################################
|
| 660 |
+
|
| 661 |
+
#css = """.toast-wrap { display: none !important } """
|
| 662 |
+
#examples=[['Was ist ChtGPT-4?'],['schreibe ein Python Programm, dass die GPT-4 API aufruft.']]
|
| 663 |
+
|
| 664 |
+
def vote(data: gr.LikeData):
|
| 665 |
+
if data.liked: print("You upvoted this response: " + data.value)
|
| 666 |
+
else: print("You downvoted this response: " + data.value)
|
| 667 |
+
|
| 668 |
+
def custom_css():
|
| 669 |
+
return """
|
| 670 |
+
body, html {
|
| 671 |
+
background-color: #303030; /* Dunkler Hintergrund */
|
| 672 |
+
color:#353535;
|
| 673 |
+
}
|
| 674 |
+
"""
|
| 675 |
+
|
| 676 |
+
|
| 677 |
+
########################################
|
| 678 |
+
# Bot- test gegen schädliche Bots die die Anwendung testen...
|
| 679 |
+
# Funktion zur Überprüfung der Benutzereingabe
|
| 680 |
+
# Funktion zur Überprüfung der Eingabe und Aktivierung der Hauptanwendung
|
| 681 |
+
def validate_input(user_input_validate, validate=False):
|
| 682 |
+
user_input_hashed = hash_input(user_input_validate)
|
| 683 |
+
if user_input_hashed == hash_input(ANTI_BOT_PW):
|
| 684 |
+
return "Richtig! Weiter gehts... ", True, gr.Textbox(visible=False), gr.Button(visible=False)
|
| 685 |
+
else:
|
| 686 |
+
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)
|
| 687 |
+
|
| 688 |
+
|
| 689 |
+
#############################################################################################
|
| 690 |
+
# Start Gui Vorabfrage
|
| 691 |
+
# Validierungs-Interface - Bots weghalten...
|
| 692 |
+
print ("Start GUI Vorabfrage")
|
| 693 |
+
#################################################################################################
|
| 694 |
+
print ("Start GUI Hauptanwendung")
|
| 695 |
+
with open("custom.css", "r", encoding="utf-8") as f:
|
| 696 |
+
customCSS = f.read()
|
| 697 |
+
|
| 698 |
+
#Add Inputs für Tab 2
|
| 699 |
+
additional_inputs = [
|
| 700 |
+
gr.Slider(label="Temperature", value=0.65, minimum=0.0, maximum=1.0, step=0.05, interactive=True, info="Höhere Werte erzeugen diversere Antworten", visible=True),
|
| 701 |
+
gr.Slider(label="Max new tokens", value=1024, minimum=0, maximum=4096, step=64, interactive=True, info="Maximale Anzahl neuer Tokens", visible=True),
|
| 702 |
+
gr.Slider(label="Top-p (nucleus sampling)", value=0.6, minimum=0.0, maximum=1, step=0.05, interactive=True, info="Höhere Werte verwenden auch Tokens mit niedrigerer Wahrscheinlichkeit.", visible=True),
|
| 703 |
+
gr.Slider(label="Repetition penalty", value=1.2, minimum=1.0, maximum=2.0, step=0.05, interactive=True, info="Strafe für wiederholte Tokens", visible=True)
|
| 704 |
+
]
|
| 705 |
+
with gr.Blocks(css=customCSS, theme=themeAlex) as demo:
|
| 706 |
+
#validiert speichern
|
| 707 |
+
validate = gr.State(False)
|
| 708 |
+
#Session Variablen, um Weete zu speichern, auch wenn die Felder in der GUI bereits wieder leer sind
|
| 709 |
+
# history parallel zu chatbot speichern - da in chatbot bei Bildern zum Anzeigen in der GUI die Bilder speziell formatiert werden,
|
| 710 |
+
# für die Übergabe an die ki aber der Pfad zum Bild behalten werden muss - was in der history der Fall ist!
|
| 711 |
+
history = gr.State([])
|
| 712 |
+
uploaded_file_paths= gr.State([])
|
| 713 |
+
history3 = gr.State([])
|
| 714 |
+
uploaded_file_paths3= gr.State([])
|
| 715 |
+
#alle chats einer Session sammeln
|
| 716 |
+
chats = gr.State({})
|
| 717 |
+
#damit der Prompt auch nach dem upload in die History noch für predicts_args verfügbar ist
|
| 718 |
+
user_question = gr.State("")
|
| 719 |
+
#für die anderen Tabs auch...
|
| 720 |
+
#damit der Prompt auch nach dem upload in die History noch für predicts_args verfügbar ist
|
| 721 |
+
user_question2 = gr.State("")
|
| 722 |
+
user_question3 = gr.State("")
|
| 723 |
+
attached_file = gr.State(None)
|
| 724 |
+
attached_file_history = gr.State(None)
|
| 725 |
+
attached_file3 = gr.State(None)
|
| 726 |
+
attached_file_history3 = gr.State(None)
|
| 727 |
+
status_display = gr.State("")
|
| 728 |
+
status_display2 = gr.State("")
|
| 729 |
+
status_display3 = gr.State("")
|
| 730 |
+
################################################
|
| 731 |
+
# Tab zum Chatbot mit Text oder Bildeingabe
|
| 732 |
+
################################################
|
| 733 |
+
gr.Markdown(description_top)
|
| 734 |
+
with gr.Row():
|
| 735 |
+
user_input_validate =gr.Textbox(label= "Bitte das oben im Moodle Kurs angegebene Wort eingeben, um die Anwendung zu starten", visible=True, interactive=True, scale= 7)
|
| 736 |
+
validate_btn = gr.Button("Validieren", visible = True)
|
| 737 |
+
#validation_result = gr.Text(label="Validierungsergebnis")
|
| 738 |
+
|
| 739 |
+
with gr.Tab("KKG Chatbot"):
|
| 740 |
+
with gr.Row():
|
| 741 |
+
#gr.HTML("LI Chatot")
|
| 742 |
+
status_display = gr.Markdown("Antwort der KI ...", visible = True) #, elem_id="status_display")
|
| 743 |
+
with gr.Row():
|
| 744 |
+
with gr.Column(scale=5):
|
| 745 |
+
with gr.Row():
|
| 746 |
+
chatbot = gr.Chatbot(elem_id="li-chat",show_copy_button=True)
|
| 747 |
+
with gr.Row():
|
| 748 |
+
with gr.Column(scale=12):
|
| 749 |
+
user_input = gr.Textbox(
|
| 750 |
+
show_label=False, placeholder="Gib hier deinen Prompt ein...",
|
| 751 |
+
container=False
|
| 752 |
+
)
|
| 753 |
+
with gr.Column(min_width=70, scale=1):
|
| 754 |
+
submitBtn = gr.Button("Senden")
|
| 755 |
+
with gr.Column(min_width=70, scale=1):
|
| 756 |
+
cancelBtn = gr.Button("Stop")
|
| 757 |
+
with gr.Row():
|
| 758 |
+
image_display = gr.Image( visible=False)
|
| 759 |
+
upload = gr.UploadButton("📁", file_types=["image", "pdf", "docx", "pptx", "xlsx"], scale = 10)
|
| 760 |
+
emptyBtn = gr.ClearButton([user_input, chatbot, history, attached_file, attached_file_history, image_display], value="🧹 Neue Session", scale=10)
|
| 761 |
+
|
| 762 |
+
with gr.Column():
|
| 763 |
+
with gr.Column(min_width=50, scale=1):
|
| 764 |
+
with gr.Tab(label="Chats ..."):
|
| 765 |
+
#Geht nicht, da für alle gleichzeitig sichtbar
|
| 766 |
+
#chat_selector = gr.CheckboxGroup(label="", choices=update_chat_options())
|
| 767 |
+
#download_button = gr.Button("Download ausgewählte Chats")
|
| 768 |
+
file_download = gr.File(label="Noch keine Chatsverläufe", visible=True, interactive = False, file_count="multiple",)
|
| 769 |
+
|
| 770 |
+
with gr.Tab(label="Parameter"):
|
| 771 |
+
#gr.Markdown("# Parameters")
|
| 772 |
+
rag_option = gr.Radio(["Aus", "An"], label="KKG Erweiterungen (RAG)", value = "Aus")
|
| 773 |
+
model_option = gr.Radio(["OpenAI", "HuggingFace"], label="Modellauswahl", value = "OpenAI")
|
| 774 |
+
websuche = gr.Radio(["Aus", "An"], label="Web-Suche", value = "Aus")
|
| 775 |
+
|
| 776 |
+
|
| 777 |
+
top_p = gr.Slider(
|
| 778 |
+
minimum=-0,
|
| 779 |
+
maximum=1.0,
|
| 780 |
+
value=0.95,
|
| 781 |
+
step=0.05,
|
| 782 |
+
interactive=True,
|
| 783 |
+
label="Top-p",
|
| 784 |
+
visible=False,
|
| 785 |
+
)
|
| 786 |
+
top_k = gr.Slider(
|
| 787 |
+
minimum=1,
|
| 788 |
+
maximum=100,
|
| 789 |
+
value=35,
|
| 790 |
+
step=1,
|
| 791 |
+
interactive=True,
|
| 792 |
+
label="Top-k",
|
| 793 |
+
visible=False,
|
| 794 |
+
)
|
| 795 |
+
temperature = gr.Slider(
|
| 796 |
+
minimum=0.1,
|
| 797 |
+
maximum=2.0,
|
| 798 |
+
value=0.5,
|
| 799 |
+
step=0.1,
|
| 800 |
+
interactive=True,
|
| 801 |
+
label="Temperature",
|
| 802 |
+
visible=False
|
| 803 |
+
)
|
| 804 |
+
max_length_tokens = gr.Slider(
|
| 805 |
+
minimum=0,
|
| 806 |
+
maximum=512,
|
| 807 |
+
value=512,
|
| 808 |
+
step=8,
|
| 809 |
+
interactive=True,
|
| 810 |
+
label="Max Generation Tokens",
|
| 811 |
+
visible=False,
|
| 812 |
+
)
|
| 813 |
+
max_context_length_tokens = gr.Slider(
|
| 814 |
+
minimum=0,
|
| 815 |
+
maximum=4096,
|
| 816 |
+
value=2048,
|
| 817 |
+
step=128,
|
| 818 |
+
interactive=True,
|
| 819 |
+
label="Max History Tokens",
|
| 820 |
+
visible=False,
|
| 821 |
+
)
|
| 822 |
+
repetition_penalty=gr.Slider(label="Repetition penalty", value=1.2, minimum=1.0, maximum=2.0, step=0.05, interactive=True, info="Strafe für wiederholte Tokens", visible=False)
|
| 823 |
+
anzahl_docs = gr.Slider(label="Anzahl Dokumente", value=3, minimum=1, maximum=10, step=1, interactive=True, info="wie viele Dokumententeile aus dem Vektorstore an den prompt gehängt werden", visible=False)
|
| 824 |
+
openai_key = gr.Textbox(label = "OpenAI API Key", value = "sk-", lines = 1, visible = False)
|
| 825 |
+
|
| 826 |
+
|
| 827 |
+
################################################
|
| 828 |
+
# Tab zum Zeichnen mit Stable Diffusion
|
| 829 |
+
################################################
|
| 830 |
+
with gr.Tab("LI Zeichnen"):
|
| 831 |
+
with gr.Row():
|
| 832 |
+
gr.HTML("Lass den KI-Bot deine Ideen zeichnen...")
|
| 833 |
+
status_display2 = gr.Markdown("Success", visible = False, elem_id="status_display")
|
| 834 |
+
#gr.Markdown(description2)
|
| 835 |
+
with gr.Row():
|
| 836 |
+
with gr.Column(scale=5):
|
| 837 |
+
with gr.Row():
|
| 838 |
+
chatbot_bild = gr.Chatbot(elem_id="li-zeichnen",show_copy_button=True, show_share_button=True)
|
| 839 |
+
with gr.Row():
|
| 840 |
+
with gr.Column(scale=12):
|
| 841 |
+
user_input2 = gr.Textbox(
|
| 842 |
+
show_label=False, placeholder="Gib hier deinen Prompt ein...",
|
| 843 |
+
container=False
|
| 844 |
+
)
|
| 845 |
+
with gr.Column(min_width=70, scale=1):
|
| 846 |
+
submitBtn2 = gr.Button("Senden")
|
| 847 |
+
#with gr.Column(min_width=70, scale=1):
|
| 848 |
+
#cancelBtn2 = gr.Button("Stop")
|
| 849 |
+
with gr.Row():
|
| 850 |
+
emptyBtn2 = gr.ClearButton([user_input, chatbot_bild], value="🧹 Neue Session", scale=10)
|
| 851 |
+
#additional_inputs_accordion = gr.Accordion(label="Weitere Eingaben...", open=False)
|
| 852 |
+
with gr.Column():
|
| 853 |
+
with gr.Column(min_width=50, scale=1):
|
| 854 |
+
with gr.Tab(label="Parameter Einstellung"):
|
| 855 |
+
#gr.Markdown("# Parameters")
|
| 856 |
+
model_option_zeichnen = gr.Radio(["Stable Diffusion","DallE"], label="Modellauswahl", value = "Stable Diffusion")
|
| 857 |
+
|
| 858 |
+
"""
|
| 859 |
+
with gr.Tab("LI Codebot"):
|
| 860 |
+
with gr.Row():
|
| 861 |
+
gr.HTML("Gib als textuelle Beschreibung ein, was in Programmcode übersetzt werden soll und in welcher Sprache...")
|
| 862 |
+
status_display3 = gr.Markdown("Success", visible = False, elem_id="status_display")
|
| 863 |
+
#gr.Markdown(description2)
|
| 864 |
+
with gr.Row():
|
| 865 |
+
with gr.Column(scale=5):
|
| 866 |
+
with gr.Row():
|
| 867 |
+
chatbot_code = gr.Chatbot(elem_id="li-zeichnen",show_copy_button=True, show_share_button=True)
|
| 868 |
+
with gr.Row():
|
| 869 |
+
with gr.Column(scale=12):
|
| 870 |
+
user_input3 = gr.Textbox(
|
| 871 |
+
show_label=False, placeholder="Gib hier deinen Prompt ein...",
|
| 872 |
+
container=False
|
| 873 |
+
)
|
| 874 |
+
with gr.Column(min_width=70, scale=1):
|
| 875 |
+
submitBtn3 = gr.Button("Senden")
|
| 876 |
+
with gr.Column(min_width=70, scale=1):
|
| 877 |
+
cancelBtn3 = gr.Button("Stop")
|
| 878 |
+
with gr.Row():
|
| 879 |
+
#file_display = gr.File(visible=False)
|
| 880 |
+
image_display3 = gr.Image( visible=False)
|
| 881 |
+
upload3 = gr.UploadButton("📁", file_types=["image", "pdf", "docx", "pptx", "xlsx"], scale = 10)
|
| 882 |
+
emptyBtn3 = gr.ClearButton([user_input3, chatbot_code, history3, attached_file3, image_display3], value="🧹 Neue Session", scale=10)
|
| 883 |
+
with gr.Column():
|
| 884 |
+
with gr.Column(min_width=50, scale=1):
|
| 885 |
+
with gr.Tab(label="Parameter Einstellung"):
|
| 886 |
+
#gr.Markdown("# Parameters")
|
| 887 |
+
model_option_code3 = gr.Radio(["Davinci","kommt noch"], label="Modellauswahl", value = "Davinci")
|
| 888 |
+
"""
|
| 889 |
+
|
| 890 |
+
|
| 891 |
+
gr.Markdown(description)
|
| 892 |
+
|
| 893 |
+
######################################
|
| 894 |
+
# Events und Übergabe Werte an Funktionen
|
| 895 |
+
#######################################
|
| 896 |
+
######################################
|
| 897 |
+
# Für Tab 1: Chatbot
|
| 898 |
+
#Argumente für generate Funktion als Input
|
| 899 |
+
predict_args = dict(
|
| 900 |
+
fn=generate_auswahl,
|
| 901 |
+
inputs=[
|
| 902 |
+
user_question,
|
| 903 |
+
attached_file,
|
| 904 |
+
attached_file_history,
|
| 905 |
+
chatbot,
|
| 906 |
+
history,
|
| 907 |
+
rag_option,
|
| 908 |
+
model_option,
|
| 909 |
+
openai_key,
|
| 910 |
+
anzahl_docs,
|
| 911 |
+
top_p,
|
| 912 |
+
temperature,
|
| 913 |
+
max_length_tokens,
|
| 914 |
+
max_context_length_tokens,
|
| 915 |
+
repetition_penalty,
|
| 916 |
+
top_k,
|
| 917 |
+
websuche,
|
| 918 |
+
validate
|
| 919 |
+
],
|
| 920 |
+
outputs=[chatbot, history, attached_file, attached_file_history, status_display],
|
| 921 |
+
show_progress=True,
|
| 922 |
+
)
|
| 923 |
+
|
| 924 |
+
reset_args = dict(
|
| 925 |
+
fn=reset_textbox, inputs=[], outputs=[user_input, status_display]
|
| 926 |
+
)
|
| 927 |
+
|
| 928 |
+
# Chatbot
|
| 929 |
+
transfer_input_args = dict(
|
| 930 |
+
fn=add_text, inputs=[chatbot, history, user_input, attached_file, attached_file_history], outputs=[chatbot, history, user_question, attached_file, attached_file_history, image_display , user_input], show_progress=True
|
| 931 |
+
)
|
| 932 |
+
|
| 933 |
+
##############################################
|
| 934 |
+
# Button Events....
|
| 935 |
+
#Validation Button
|
| 936 |
+
# Event-Handler für die Validierung
|
| 937 |
+
validate_btn.click(validate_input, inputs=[user_input_validate, validate], outputs=[status_display, validate, user_input_validate, validate_btn])
|
| 938 |
+
user_input_validate.submit(validate_input, inputs=[user_input_validate, validate], outputs=[status_display, validate, user_input_validate, validate_btn])
|
| 939 |
+
|
| 940 |
+
predict_event1 = user_input.submit(**transfer_input_args, queue=False,).then(**predict_args)
|
| 941 |
+
predict_event2 = submitBtn.click(**transfer_input_args, queue=False,).then(**predict_args)
|
| 942 |
+
predict_event3 = upload.upload(file_anzeigen, [upload], [image_display, image_display, attached_file] ) #.then(**predict_args)
|
| 943 |
+
emptyBtn.click(clear_all, [history, uploaded_file_paths, chats], [attached_file, image_display, uploaded_file_paths, history, file_download, chats])
|
| 944 |
+
#Bild Anzeige neben dem Button wieder entfernen oder austauschen..
|
| 945 |
+
image_display.select(file_loeschen, [], [attached_file, image_display])
|
| 946 |
+
#download_button.click(fn=download_chats, inputs=chat_selector, outputs=[file_download])
|
| 947 |
+
|
| 948 |
+
|
| 949 |
+
#Berechnung oder Ausgabe anhalten (kann danach fortgesetzt werden)
|
| 950 |
+
cancelBtn.click(cancel_outputing, [], [status_display], cancels=[predict_event1,predict_event2, predict_event3])
|
| 951 |
+
|
| 952 |
+
######################################
|
| 953 |
+
# Für Tab 2: Zeichnen
|
| 954 |
+
predict_args2 = dict(
|
| 955 |
+
fn=generate_bild,
|
| 956 |
+
inputs=[
|
| 957 |
+
user_question2,
|
| 958 |
+
chatbot_bild,
|
| 959 |
+
model_option_zeichnen,
|
| 960 |
+
validate
|
| 961 |
+
#additional_inputs,
|
| 962 |
+
],
|
| 963 |
+
outputs=[chatbot_bild, status_display2], #[chatbot, history, status_display]
|
| 964 |
+
show_progress=True,
|
| 965 |
+
)
|
| 966 |
+
transfer_input_args2 = dict(
|
| 967 |
+
fn=add_text2, inputs=[chatbot_bild, user_input2], outputs=[chatbot_bild, user_question2, user_input2], show_progress=True
|
| 968 |
+
)
|
| 969 |
+
predict_event2_1 = user_input2.submit(**transfer_input_args2, queue=False,).then(**predict_args2)
|
| 970 |
+
predict_event2_2 = submitBtn2.click(**transfer_input_args2, queue=False,).then(**predict_args2)
|
| 971 |
+
#emptyBtn2.click(clear_all, [], [file_display, image_display])
|
| 972 |
+
|
| 973 |
+
#cancelBtn2.click(
|
| 974 |
+
#cancels=[predict_event2_1,predict_event2_2 ]
|
| 975 |
+
#)
|
| 976 |
+
|
| 977 |
+
"""
|
| 978 |
+
######################################
|
| 979 |
+
# Für Tab 3: Codebot
|
| 980 |
+
#Argumente für generate Funktion als Input
|
| 981 |
+
predict_args3 = dict(
|
| 982 |
+
fn=generate_code,
|
| 983 |
+
inputs=[
|
| 984 |
+
user_question3,
|
| 985 |
+
attached_file3,
|
| 986 |
+
attached_file_history3,
|
| 987 |
+
chatbot_code,
|
| 988 |
+
history3,
|
| 989 |
+
model_option,
|
| 990 |
+
openai_key,
|
| 991 |
+
top_p,
|
| 992 |
+
temperature,
|
| 993 |
+
max_length_tokens,
|
| 994 |
+
max_context_length_tokens,
|
| 995 |
+
repetition_penalty,
|
| 996 |
+
top_k
|
| 997 |
+
],
|
| 998 |
+
outputs=[chatbot_code, history3, attached_file3, status_display3],
|
| 999 |
+
show_progress=True,
|
| 1000 |
+
)
|
| 1001 |
+
reset_args3 = dict(
|
| 1002 |
+
fn=reset_textbox, inputs=[], outputs=[user_input3, status_display3]
|
| 1003 |
+
)
|
| 1004 |
+
# Chatbot
|
| 1005 |
+
transfer_input_args3 = dict(
|
| 1006 |
+
fn=add_text, inputs=[chatbot_code, history3, user_input3, attached_file3, attached_file_history3], outputs=[chatbot_code, history3, user_question3, attached_file3, attached_file_history3, image_display3, user_input3], show_progress=True
|
| 1007 |
+
)
|
| 1008 |
+
predict_event3_1 = user_input3.submit(**transfer_input_args3, queue=False,).then(**predict_args3)
|
| 1009 |
+
predict_event3_2 = submitBtn3.click(**transfer_input_args3, queue=False,).then(**predict_args3)
|
| 1010 |
+
predict_event3_3 = upload3.upload(file_anzeigen, [upload3], [image_display3, image_display3, attached_file3] ) #.then(**predict_args)
|
| 1011 |
+
emptyBtn3.click(clear_all3, [history3], [attached_file3, image_display3, history3])
|
| 1012 |
+
#Bild Anzeige neben dem Button wieder entfernen oder austauschen..
|
| 1013 |
+
image_display3.select(file_loeschen, [], [attached_file3, image_display3])
|
| 1014 |
+
#download_button.click(fn=download_chats, inputs=chat_selector, outputs=[file_download])
|
| 1015 |
+
"""
|
| 1016 |
+
|
| 1017 |
+
|
| 1018 |
+
demo.title = "KKG-ChatBot"
|
| 1019 |
+
demo.queue(default_concurrency_limit=15).launch(debug=True)
|
| 1020 |
+
|