alexkueck commited on
Commit
8bdd5f5
1 Parent(s): 7e89036

Create appBackup.py

Browse files
Files changed (1) hide show
  1. appBackup.py +816 -0
appBackup.py ADDED
@@ -0,0 +1,816 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
12
+ from langchain.chains import LLMChain, RetrievalQA
13
+ from langchain.chat_models import ChatOpenAI
14
+ from langchain.document_loaders import PyPDFLoader, WebBaseLoader, UnstructuredWordDocumentLoader, DirectoryLoader
15
+ from langchain.document_loaders.blob_loaders.youtube_audio import YoutubeAudioLoader
16
+ from langchain.document_loaders.generic import GenericLoader
17
+ from langchain.document_loaders.parsers import OpenAIWhisperParser
18
+ from langchain.schema import AIMessage, HumanMessage
19
+ from langchain.llms import HuggingFaceHub
20
+ from langchain.llms import HuggingFaceTextGenInference
21
+ from langchain.embeddings import HuggingFaceInstructEmbeddings, HuggingFaceEmbeddings, HuggingFaceBgeEmbeddings, HuggingFaceInferenceAPIEmbeddings
22
+
23
+ from langchain.embeddings.openai import OpenAIEmbeddings
24
+ from langchain.prompts import PromptTemplate
25
+ from langchain.text_splitter import RecursiveCharacterTextSplitter
26
+ from langchain.vectorstores import Chroma
27
+ from chromadb.errors import InvalidDimensionException
28
+ from utils import *
29
+ from beschreibungen import *
30
+
31
+
32
+ #from langchain.vectorstores import MongoDBAtlasVectorSearch
33
+ #from pymongo import MongoClient
34
+
35
+ from dotenv import load_dotenv, find_dotenv
36
+ _ = load_dotenv(find_dotenv())
37
+
38
+
39
+
40
+ ###############################################
41
+ #globale Variablen
42
+ ##############################################
43
+ #nur bei ersten Anfrage splitten der Dokumente - um die Vektordatenbank entsprechend zu füllen
44
+ splittet = False
45
+
46
+ ##################################################
47
+ #Für MongoDB statt Chroma als Vektorstore
48
+ #MONGODB_URI = os.environ["MONGODB_ATLAS_CLUSTER_URI"]
49
+ #client = MongoClient(MONGODB_URI)
50
+ #MONGODB_DB_NAME = "langchain_db"
51
+ #MONGODB_COLLECTION_NAME = "gpt-4"
52
+ #MONGODB_COLLECTION = client[MONGODB_DB_NAME][MONGODB_COLLECTION_NAME]
53
+ #MONGODB_INDEX_NAME = "default"
54
+
55
+ #################################################
56
+ #Prompt Zusätze
57
+ template = """Antworte in deutsch, wenn es nicht explizit anders gefordert wird. Wenn du die Antwort nicht kennst, antworte einfach, dass du es nicht weißt. Versuche nicht, die Antwort zu erfinden oder aufzumocken. Halte die Antwort kurz aber ausführlich genug und exakt."""
58
+
59
+ llm_template = "Beantworte die Frage am Ende. " + template + "Frage: {question} Hilfreiche Antwort: "
60
+ rag_template = "Nutze die folgenden Kontext Teile, um die Frage zu beantworten am Ende. " + template + "{context} Frage: {question} Hilfreiche Antwort: "
61
+
62
+ #################################################
63
+ #Konstanten
64
+ LLM_CHAIN_PROMPT = PromptTemplate(input_variables = ["question"],
65
+ template = llm_template)
66
+ RAG_CHAIN_PROMPT = PromptTemplate(input_variables = ["context", "question"],
67
+ template = rag_template)
68
+
69
+ #Plattform Keys aus den Secrets holen zu diesem Space
70
+ HUGGINGFACEHUB_API_TOKEN = os.getenv("HF_ACCESS_READ")
71
+ OAI_API_KEY=os.getenv("OPENAI_API_KEY")
72
+ HEADERS = {"Authorization": f"Bearer {HUGGINGFACEHUB_API_TOKEN}"}
73
+
74
+
75
+ #Pfad, wo Docs/Bilder/Filme abgelegt werden können - lokal, also hier im HF Space (sonst auf eigenem Rechner)
76
+ PATH_WORK = "."
77
+ CHROMA_DIR = "/chroma"
78
+ YOUTUBE_DIR = "/youtube"
79
+ HISTORY_PFAD = "/data/history"
80
+
81
+ ###############################################
82
+ #URLs zu Dokumenten oder andere Inhalte, die einbezogen werden sollen
83
+ PDF_URL = "https://arxiv.org/pdf/2303.08774.pdf"
84
+ WEB_URL = "https://openai.com/research/gpt-4"
85
+ YOUTUBE_URL_1 = "https://www.youtube.com/watch?v=--khbXchTeE"
86
+ YOUTUBE_URL_2 = "https://www.youtube.com/watch?v=hdhZwyf24mE"
87
+ #YOUTUBE_URL_3 = "https://www.youtube.com/watch?v=vw-KWfKwvTQ"
88
+
89
+ ################################################
90
+ #LLM Model mit dem gearbeitet wird
91
+ #openai-------------------------------------
92
+ MODEL_NAME = "gpt-3.5-turbo-16k"
93
+ #MODEL_NAME = "gpt-3.5-turbo-1106"
94
+ #MODEL_NAME= "gpt-4-1106-preview"
95
+ MODEL_NAME_IMAGE = "gpt-4-vision-preview"
96
+
97
+
98
+ #verfügbare Modelle anzeigen lassen
99
+
100
+
101
+ #HuggingFace Reop ID--------------------------------
102
+ #repo_id = "meta-llama/Llama-2-13b-chat-hf"
103
+ repo_id = "HuggingFaceH4/zephyr-7b-alpha" #das Modell ist echt gut!!! Vom MIT
104
+ #repo_id = "TheBloke/Yi-34B-Chat-GGUF"
105
+ #repo_id = "meta-llama/Llama-2-70b-chat-hf"
106
+ #repo_id = "tiiuae/falcon-40b"
107
+ #repo_id = "Vicuna-33b"
108
+ #repo_id = "alexkueck/ChatBotLI2Klein"
109
+ #repo_id = "mistralai/Mistral-7B-v0.1"
110
+ #repo_id = "internlm/internlm-chat-7b"
111
+ #repo_id = "Qwen/Qwen-7B"
112
+ #repo_id = "Salesforce/xgen-7b-8k-base"
113
+ #repo_id = "Writer/camel-5b-hf"
114
+ #repo_id = "databricks/dolly-v2-3b"
115
+ #repo_id = "google/flan-t5-xxl"
116
+
117
+ #HuggingFace Model name--------------------------------
118
+ MODEL_NAME_HF = "mistralai/Mixtral-8x7B-Instruct-v0.1"
119
+ MODEL_NAME_OAI_ZEICHNEN = "dall-e-3"
120
+ #Alternativ zeichnen: Stabe Diffusion from HF:
121
+ API_URL = "https://api-inference.huggingface.co/models/stabilityai/stable-diffusion-2-1"
122
+
123
+ ################################################
124
+ #HF Hub Zugriff ermöglichen
125
+ ###############################################
126
+ os.environ["HUGGINGFACEHUB_API_TOKEN"] = HUGGINGFACEHUB_API_TOKEN
127
+
128
+
129
+ #################################################
130
+ #################################################
131
+ #################################################
132
+ #Funktionen zur Verarbeitung
133
+ ################################################
134
+
135
+ ##############################################
136
+ #wenn löschen Button geklickt
137
+ def clear_all():
138
+ return None, gr.Image(visible=False), []
139
+
140
+ ##############################################
141
+ #History - die Frage oder das File eintragen...
142
+ def add_text(chatbot, history, prompt, file):
143
+ if (file == None):
144
+ chatbot = chatbot +[(prompt, None)]
145
+ else:
146
+ if (prompt == ""):
147
+ chatbot=chatbot + [((file.name,), "Prompt fehlt!")]
148
+ else:
149
+ chatbot = chatbot +[((file.name,), None), (prompt, None)]
150
+ print("chatbot nach add_text............")
151
+ print(chatbot)
152
+ return chatbot, history, prompt, file, gr.Image(visible = False), "" #gr.Image( label=None, size=(30,30), visible=False, scale=1) #gr.Textbox(value="", interactive=False)
153
+
154
+ def add_text2(chatbot, prompt):
155
+ if (prompt == ""):
156
+ chatbot = chatbot + [("", "Prompt fehlt!")]
157
+ else:
158
+ chatbot = chatbot + [(prompt, None)]
159
+ print("chatbot nach add_text............")
160
+ print(chatbot)
161
+ return chatbot, prompt, ""
162
+
163
+ ############################################
164
+ #nach dem Upload soll das zusätzliche Fenster mit dem image drinnen angezeigt werden
165
+ def file_anzeigen(file):
166
+ return gr.Image( width=47, visible=True, interactive = False, height=47, min_width=47, show_download_button=False, show_share_button=False, show_label=False, scale = 0.5), file, file
167
+
168
+ def file_loeschen():
169
+ return None, gr.Image(visible = False)
170
+
171
+ ############################################
172
+ #wenn 'Stop' Button geklickt, dann Message dazu und das Eingabe-Fenster leeren
173
+ def cancel_outputing():
174
+ reset_textbox()
175
+ return "Stop Done"
176
+
177
+ def reset_textbox():
178
+ return gr.update(value=""),""
179
+
180
+
181
+ ##########################################
182
+ #Hilfsfunktion, um ein von Stable Diffusion erzeugtes Bild für die Ausgabe in der History vorzubereiten
183
+ def umwandeln_fuer_anzeige(image):
184
+ buffer = io.BytesIO()
185
+ image.save(buffer, format='PNG')
186
+ return buffer.getvalue()
187
+
188
+ #########################################
189
+ #nicht im Einsatz, da Stable Diffusion die Bilder erzeugt
190
+ def create_picture(history, prompt):
191
+ client = OpenAI()
192
+ response = client.images.generate(model="dall-e-3", prompt=prompt,size="1024x1024",quality="standard",n=1,)
193
+ image_url = response.data[0].url
194
+ # using requests library to get the image in bytes
195
+ response2 = requests.get(image_url)
196
+ # using the Image module from PIL library to view the image
197
+ image = Image.open(response2.raw)
198
+ return image
199
+
200
+ ##########################################
201
+ #ein hochgeladenes Bild so vorbereiten, dass OpenAI API es annehmen kann und bearbeiten
202
+ #muss ein base64 Bils sein und header und payload entsprechend konfigurieren
203
+ def process_image(image_path, prompt):
204
+ # Convert image to base64
205
+ with open(image_path, "rb") as image_file:
206
+ encoded_string = base64.b64encode(image_file.read()).decode('utf-8')
207
+
208
+
209
+ # Prepare the data for the API request (specific to the API you're using)
210
+ headers = {
211
+ "Content-Type": "application/json",
212
+ "Authorization": f"Bearer {OAI_API_KEY}"
213
+ }
214
+
215
+ payload = {
216
+ "model": MODEL_NAME_IMAGE,
217
+ "messages": [
218
+ {
219
+ "role": "user",
220
+ "content": [
221
+ {
222
+ "type": "text",
223
+ "text": prompt
224
+ },
225
+ {
226
+ "type": "image_url",
227
+ "image_url": {
228
+ "url": f"data:image/jpeg;base64,{encoded_string}"
229
+ }
230
+ }
231
+ ]
232
+ }
233
+ ],
234
+ "max_tokens": 300
235
+ }
236
+ return headers, payload
237
+
238
+ ###################################################
239
+ #zur Zeit nicht im Gebrauch
240
+ def transfer_input(inputs):
241
+ textbox = reset_textbox()
242
+ return (
243
+ inputs,
244
+ gr.update(value=""),
245
+ gr.Button.update(visible=True),
246
+ )
247
+ ##################################################
248
+ #RAG Hilfsfunktionen - Dokumenten bearbeiten für Vektorstore
249
+ ##################################################
250
+ ##################################################
251
+ # Funktion, um für einen best. File-typ ein directory-loader zu definieren
252
+ def create_directory_loader(file_type, directory_path):
253
+ #verscheidene Dokument loaders:
254
+ loaders = {
255
+ '.pdf': PyPDFLoader,
256
+ '.word': UnstructuredWordDocumentLoader,
257
+ }
258
+ return DirectoryLoader(
259
+ path=directory_path,
260
+ glob=f"**/*{file_type}",
261
+ loader_cls=loaders[file_type],
262
+ )
263
+ ################################################
264
+ #die Inhalte splitten, um in Vektordatenbank entsprechend zu laden als Splits
265
+ def document_loading_splitting():
266
+ global splittet
267
+ ##############################
268
+ # Document loading
269
+ docs = []
270
+
271
+ # kreiere einen DirectoryLoader für jeden file type
272
+ pdf_loader = create_directory_loader('.pdf', './chroma/pdf')
273
+ word_loader = create_directory_loader('.word', './chroma/word')
274
+
275
+
276
+ # Load the files
277
+ pdf_documents = pdf_loader.load()
278
+ word_documents = word_loader.load()
279
+
280
+ #alle zusammen in docs...
281
+ docs.extend(pdf_documents)
282
+ docs.extend(word_documents)
283
+
284
+ #andere loader...
285
+ # Load PDF
286
+ loader = PyPDFLoader(PDF_URL)
287
+ docs.extend(loader.load())
288
+ # Load Web
289
+ loader = WebBaseLoader(WEB_URL)
290
+ docs.extend(loader.load())
291
+ # Load YouTube
292
+ loader = GenericLoader(YoutubeAudioLoader([YOUTUBE_URL_1,YOUTUBE_URL_2], PATH_WORK + YOUTUBE_DIR), OpenAIWhisperParser())
293
+ docs.extend(loader.load())
294
+ ################################
295
+ # Document splitting
296
+ text_splitter = RecursiveCharacterTextSplitter(chunk_overlap = 150, chunk_size = 1500)
297
+ splits = text_splitter.split_documents(docs)
298
+
299
+ #nur bei erster Anfrage mit "choma" wird gesplittet...
300
+ splittet = True
301
+ return splits
302
+
303
+ ###########################################
304
+ #Chroma DB die splits ablegen - vektorisiert...
305
+ def document_storage_chroma(splits):
306
+ #OpenAi embeddings----------------------------------
307
+ Chroma.from_documents(documents = splits, embedding = OpenAIEmbeddings(disallowed_special = ()), persist_directory = PATH_WORK + CHROMA_DIR)
308
+
309
+ #HF embeddings--------------------------------------
310
+ #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)
311
+
312
+ #Mongo DB die splits ablegen - vektorisiert...
313
+ def document_storage_mongodb(splits):
314
+ MongoDBAtlasVectorSearch.from_documents(documents = splits,
315
+ embedding = OpenAIEmbeddings(disallowed_special = ()),
316
+ collection = MONGODB_COLLECTION,
317
+ index_name = MONGODB_INDEX_NAME)
318
+ ############################################
319
+ #dokumente in chroma db vektorisiert ablegen können - die Db vorbereiten daüfur
320
+ def document_retrieval_chroma(llm, prompt):
321
+ #OpenAI embeddings -------------------------------
322
+ embeddings = OpenAIEmbeddings()
323
+
324
+ #HF embeddings -----------------------------------
325
+ #Alternative Embedding - für Vektorstore, um Ähnlichkeitsvektoren zu erzeugen - die ...InstructEmbedding ist sehr rechenaufwendig
326
+ #embeddings = HuggingFaceInstructEmbeddings(model_name="sentence-transformers/all-MiniLM-L6-v2", model_kwargs={"device": "cpu"})
327
+ #etwas weniger rechenaufwendig:
328
+ #embeddings = HuggingFaceEmbeddings(model_name="sentence-transformers/all-mpnet-base-v2", model_kwargs={"device": "cpu"}, encode_kwargs={'normalize_embeddings': False})
329
+
330
+ #ChromaDb um die embedings zu speichern
331
+ db = Chroma(embedding_function = embeddings, persist_directory = PATH_WORK + CHROMA_DIR)
332
+ return db
333
+
334
+ ############################################
335
+ #dokumente in chroma db vektorisiert ablegen können - die Db vorbereiten daüfur
336
+ #zweite Variante, passend zu rag_chain2 für generate_text_mit_bild- ohne llm vorher festlegen zu müssen
337
+ def document_retrieval_chroma2():
338
+ #OpenAI embeddings -------------------------------
339
+ embeddings = OpenAIEmbeddings()
340
+
341
+ #HF embeddings -----------------------------------
342
+ #Alternative Embedding - für Vektorstore, um Ähnlichkeitsvektoren zu erzeugen - die ...InstructEmbedding ist sehr rechenaufwendig
343
+ #embeddings = HuggingFaceInstructEmbeddings(model_name="sentence-transformers/all-MiniLM-L6-v2", model_kwargs={"device": "cpu"})
344
+ #etwas weniger rechenaufwendig:
345
+ #embeddings = HuggingFaceEmbeddings(model_name="sentence-transformers/all-mpnet-base-v2", model_kwargs={"device": "cpu"}, encode_kwargs={'normalize_embeddings': False})
346
+ #oder einfach ohne Langchain:
347
+ #embeddings = SentenceTransformerEmbeddings(model_name="all-MiniLM-L6-v2")
348
+
349
+ #ChromaDb um die embedings zu speichern
350
+ db = Chroma(embedding_function = embeddings, persist_directory = PATH_WORK + CHROMA_DIR)
351
+ print ("Chroma DB bereit ...................")
352
+
353
+ return db
354
+
355
+ ###########################################
356
+ #dokumente in mongo db vektorisiert ablegen können - die Db vorbereiten daüfür
357
+ def document_retrieval_mongodb(llm, prompt):
358
+ db = MongoDBAtlasVectorSearch.from_connection_string(MONGODB_URI,
359
+ MONGODB_DB_NAME + "." + MONGODB_COLLECTION_NAME,
360
+ OpenAIEmbeddings(disallowed_special = ()),
361
+ index_name = MONGODB_INDEX_NAME)
362
+ return db
363
+
364
+ ###############################################
365
+ #Langchain anlegen
366
+ ###############################################
367
+ #langchain nutzen, um prompt an LLM zu leiten - llm und prompt sind austauschbar
368
+ def llm_chain(llm, prompt):
369
+ llm_chain = LLMChain(llm = llm, prompt = LLM_CHAIN_PROMPT)
370
+ result = llm_chain.run({"question": prompt})
371
+ return result
372
+
373
+ #############################################
374
+ #langchain nutzen, um prompt an llm zu leiten, aber vorher in der VektorDB suchen, um passende splits zum Prompt hinzuzufügen
375
+ def rag_chain(llm, prompt, db):
376
+ rag_chain = RetrievalQA.from_chain_type(llm,
377
+ chain_type_kwargs = {"prompt": RAG_CHAIN_PROMPT},
378
+ retriever = db.as_retriever(search_kwargs = {"k": 3}),
379
+ return_source_documents = True)
380
+ result = rag_chain({"query": prompt})
381
+ return result["result"]
382
+
383
+ ############################################
384
+ # rag_chain Alternative für RAg mit Bild-Upload, da hier das llm so nicht genutzt werden kann und der prompt mit den RAG Erweiterungen anders übergeben wird
385
+ #langchain nutzen, um prompt an llm zu leiten, aber vorher in der VektorDB suchen, um passende splits zum Prompt hinzuzufügen
386
+ #prompt mit RAG!!!
387
+ def rag_chain2(prompt, db, k=3):
388
+ rag_template = "Nutze die folgenden Kontext Teile am Ende, um die Frage zu beantworten . " + template + "Frage: " + prompt + "Kontext Teile: "
389
+ retrieved_chunks = db.similarity_search(prompt, k)
390
+
391
+ neu_prompt = rag_template
392
+ for i, chunk in enumerate(retrieved_chunks):
393
+ neu_prompt += f"{i+1}. {chunk}\n"
394
+
395
+ return neu_prompt
396
+
397
+ ###################################################
398
+ #Prompts mit History erzeugen für verschiednee Modelle
399
+ ###################################################
400
+ #Funktion, die einen Prompt mit der history zusammen erzeugt - allgemein
401
+ def generate_prompt_with_history(text, history, max_length=4048):
402
+ #prompt = "The following is a conversation between a human and an AI assistant named Baize (named after a mythical creature in Chinese folklore). Baize is an open-source AI assistant developed by UCSD and Sun Yat-Sen University. The human and the AI assistant take turns chatting. Human statements start with [|Human|] and AI assistant statements start with [|AI|]. The AI assistant always provides responses in as much detail as possible, and in Markdown format. The AI assistant always declines to engage with topics, questions and instructions related to unethical, controversial, or sensitive issues. Complete the transcript in exactly that format.\n[|Human|]Hello!\n[|AI|]Hi!"
403
+ #prompt = "Das folgende ist eine Unterhaltung in deutsch zwischen einem Menschen und einem KI-Assistenten, der Baize genannt wird. Baize ist ein open-source KI-Assistent, der von UCSD entwickelt wurde. Der Mensch und der KI-Assistent chatten abwechselnd miteinander in deutsch. Die Antworten des KI Assistenten sind immer so ausführlich wie möglich und in Markdown Schreibweise und in deutscher Sprache. Wenn nötig übersetzt er sie ins Deutsche. Die Antworten des KI-Assistenten vermeiden Themen und Antworten zu unethischen, kontroversen oder sensiblen Themen. Die Antworten sind immer sehr höflich formuliert..\n[|Human|]Hallo!\n[|AI|]Hi!"
404
+ prompt=""
405
+ history = ["\n{}\n{}".format(x[0],x[1]) for x in history]
406
+ history.append("\n{}\n".format(text))
407
+ history_text = ""
408
+ flag = False
409
+ for x in history[::-1]:
410
+ history_text = x + history_text
411
+ flag = True
412
+ print ("Prompt: ..........................")
413
+ print(prompt+history_text)
414
+ if flag:
415
+ return prompt+history_text
416
+ else:
417
+ return None
418
+
419
+ ##############################################
420
+ #Prompt und History für OPenAi Schnittstelle
421
+ def generate_prompt_with_history_openai(prompt, history):
422
+ history_openai_format = []
423
+ for human, assistant in history:
424
+ history_openai_format.append({"role": "user", "content": human })
425
+ history_openai_format.append({"role": "assistant", "content":assistant})
426
+
427
+ history_openai_format.append({"role": "user", "content": prompt})
428
+ print("openai history und prompt................")
429
+ print(history_openai_format)
430
+ return history_openai_format
431
+
432
+ #############################################
433
+ #Prompt und History für Hugging Face Schnittstelle
434
+ def generate_prompt_with_history_hf(prompt, history):
435
+ history_transformer_format = history + [[prompt, ""]]
436
+ #stop = StopOnTokens()
437
+
438
+ messages = "".join(["".join(["\n<human>:"+item[0], "\n<bot>:"+item[1]]) #curr_system_message +
439
+ for item in history_transformer_format])
440
+
441
+ ##############################################
442
+ #Prompt und History für Langchain Schnittstelle
443
+ def generate_prompt_with_history_langchain(prompt, history):
444
+ history_langchain_format = []
445
+ for human, ai in history:
446
+ history_langchain_format.append(HumanMessage(content=human))
447
+ history_langchain_format.append(AIMessage(content=ai))
448
+ history_langchain_format.append(HumanMessage(content=prompt))
449
+
450
+ return history_langchain_format
451
+
452
+
453
+ ###################################################
454
+ #Funktion von Gradio aus, die den dort eingegebenen Prompt annimmt und weiterverarbeitet
455
+ ###################################################
456
+
457
+
458
+ #########################################################
459
+ #Funktion wird direkt aufgerufen aus der GUI - von hier muss auch die Rückmeldung kommen....
460
+ #man kann einen Text-Prompt eingeben (mit oder ohne RAG), dazu ein Image hochladen, ein Bild zu einem reinen textprompt erzeugen lassen
461
+ def generate_auswahl(prompt, file, 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,):
462
+ #kein Bild hochgeladen -> auf Text antworten...
463
+ if (file == None):
464
+ result = generate_text(prompt, 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,)
465
+ history = history + [(prompt, result)]
466
+ else:
467
+ #Es wurde ein Bild angehängt -> wenn prompt dazu, das Bild analysieren
468
+ #geht nur über spezielle OpenAI-Schnittstelle...
469
+ result= generate_text_zu_bild(file, prompt, k, rag_option, chatbot)
470
+ history = history + [((file,), None),(prompt, result)]
471
+
472
+ print("result..................")
473
+ print(result)
474
+ print("history.......................")
475
+ print(chatbot)
476
+ chatbot[-1][1] = ""
477
+ for character in result:
478
+ chatbot[-1][1] += character
479
+ time.sleep(0.03)
480
+ yield chatbot, history, None, "Generating"
481
+ if shared_state.interrupted:
482
+ shared_state.recover()
483
+ try:
484
+ yield chatbot, history, None, "Stop: Success"
485
+ except:
486
+ pass
487
+
488
+ ##################################################
489
+ #zu einem Text-Prompt ein Bild via Stable Diffusion generieren
490
+ def generate_bild(prompt, chatbot, temperature=0.5, max_new_tokens=4048,top_p=0.6, repetition_penalty=1.3):
491
+ #Bild nach Anweisung zeichnen und in History darstellen...
492
+ data = {"inputs": prompt}
493
+ response = requests.post(API_URL, headers=HEADERS, json=data)
494
+ print("fertig Bild")
495
+ result = response.content
496
+ #Bild ausgeben
497
+ image = Image.open(io.BytesIO(result))
498
+ image_64 = umwandeln_fuer_anzeige(image)
499
+ chatbot[-1][1]= "<img src='data:image/png;base64,{0}'/>".format(base64.b64encode(image_64).decode('utf-8'))
500
+ return chatbot, "Success"
501
+
502
+
503
+
504
+ ##################################################
505
+ #zu einem Bild und Text-Prompt eine Analyse generieren
506
+ def generate_text_zu_bild(file, prompt, k, rag_option, chatbot):
507
+ global splittet
508
+
509
+ prompt_neu = prompt
510
+ if (rag_option == "An"):
511
+ #muss nur einmal ausgeführt werden...
512
+ if not splittet:
513
+ splits = document_loading_splitting()
514
+ document_storage_chroma(splits)
515
+ db = document_retrieval_chroma2()
516
+ #mit RAG:
517
+ neu_text_mit_chunks = rag_chain2(prompt, db, k)
518
+ #für Chat LLM:
519
+ #prompt = generate_prompt_with_history_openai(neu_text_mit_chunks, history)
520
+ #als reiner prompt:
521
+ prompt_neu = generate_prompt_with_history(neu_text_mit_chunks, chatbot)
522
+
523
+ headers, payload = process_image(file, prompt_neu)
524
+ response = requests.post("https://api.openai.com/v1/chat/completions", headers=headers, json=payload)
525
+ #als json ausgeben
526
+ data = response.json()
527
+ # Den "content" auswählen, da dort die Antwort der Ki enthalten ist
528
+ result = data['choices'][0]['message']['content']
529
+ return result
530
+
531
+ ####################################################
532
+ #aus einem Text-Prompt die Antwort von KI bekommen
533
+ #mit oder ohne RAG möglich
534
+ def generate_text (prompt, 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,):
535
+ global splittet
536
+
537
+ if (openai_api_key == "" or openai_api_key == "sk-"):
538
+ #raise gr.Error("OpenAI API Key is required.")
539
+ #eigenen OpenAI key nutzen
540
+ openai_api_key= OAI_API_KEY
541
+ if (rag_option is None):
542
+ raise gr.Error("Retrieval Augmented Generation ist erforderlich.")
543
+ if (prompt == ""):
544
+ raise gr.Error("Prompt ist erforderlich.")
545
+
546
+ #history für HuggingFace Models formatieren
547
+ #history_text_und_prompt = generate_prompt_with_history_hf(prompt, history)
548
+ #history für openAi formatieren
549
+ #history_text_und_prompt = generate_prompt_with_history_openai(prompt, history)
550
+ #history für Langchain formatieren
551
+ #history_text_und_prompt = generate_prompt_with_history_langchain(prompt, history)
552
+
553
+
554
+ try:
555
+ ###########################
556
+ #LLM auswählen (OpenAI oder HF)
557
+ ###########################
558
+ if (model_option == "OpenAI"):
559
+ #Anfrage an OpenAI ----------------------------
560
+ print("OpenAI Anfrage.......................")
561
+ llm = ChatOpenAI(model_name = MODEL_NAME, openai_api_key = openai_api_key, temperature=temperature)#, top_p = top_p)
562
+ #Prompt an history anhängen und einen Text daraus machen
563
+ if (rag_option == "An"):
564
+ history_text_und_prompt = generate_prompt_with_history(prompt, chatbot)
565
+ else:
566
+ history_text_und_prompt = generate_prompt_with_history_openai(prompt, chatbot)
567
+ else:
568
+ #oder an Hugging Face --------------------------
569
+ print("HF Anfrage.......................")
570
+ llm = HuggingFaceHub(repo_id=repo_id, model_kwargs={"temperature": 0.5, "max_length": 128})
571
+ #llm = HuggingFaceChain(model=MODEL_NAME_HF, model_kwargs={"temperature": 0.5, "max_length": 128})
572
+ #llm = HuggingFaceHub(url_??? = "https://wdgsjd6zf201mufn.us-east-1.aws.endpoints.huggingface.cloud", model_kwargs={"temperature": 0.5, "max_length": 64})
573
+ #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,)
574
+ print("HF")
575
+ #Prompt an history anhängen und einen Text daraus machen
576
+ history_text_und_prompt = generate_prompt_with_history(prompt, chatbot)
577
+
578
+ #zusätzliche Dokumenten Splits aus DB zum Prompt hinzufügen (aus VektorDB - Chroma oder Mongo DB)
579
+ if (rag_option == "An"):
580
+ print("RAG aktiviert.......................")
581
+ #muss nur einmal ausgeführt werden...
582
+ if not splittet:
583
+ splits = document_loading_splitting()
584
+ document_storage_chroma(splits)
585
+ db = document_retrieval_chroma(llm, history_text_und_prompt)
586
+ print("LLM aufrufen mit RAG: ...........")
587
+ result = rag_chain(llm, history_text_und_prompt, db)
588
+ #elif (rag_option == "MongoDB"):
589
+ #splits = document_loading_splitting()
590
+ #document_storage_mongodb(splits)
591
+ #db = document_retrieval_mongodb(llm, history_text_und_prompt)
592
+ #result = rag_chain(llm, history_text_und_prompt, db)
593
+ else:
594
+ print("LLM aufrufen ohne RAG: ...........")
595
+ result = llm_chain(llm, history_text_und_prompt)
596
+
597
+ except Exception as e:
598
+ raise gr.Error(e)
599
+
600
+ return result
601
+
602
+
603
+
604
+ ################################################
605
+ #GUI
606
+ ###############################################
607
+ #Beschreibung oben in GUI
608
+ ################################################
609
+ #title = "LLM mit RAG"
610
+ #description = """<strong>Information:</strong> Hier wird ein <strong>Large Language Model (LLM)</strong> mit
611
+ #<strong>Retrieval Augmented Generation (RAG)</strong> auf <strong>externen Daten</strong> verwendet.\n\n"""
612
+
613
+ description2 = "<strong>Information:</strong> Hier wird ein <strong>Large Language Model (LLM)</strong> zum Zeichnen verwendet. Zur Zeit wird hier Stable Diffusion verwendet.\n\n"
614
+
615
+ #css = """.toast-wrap { display: none !important } """
616
+ #examples=[['Was ist ChtGPT-4?'],['schreibe ein Python Programm, dass die GPT-4 API aufruft.']]
617
+
618
+ def vote(data: gr.LikeData):
619
+ if data.liked: print("You upvoted this response: " + data.value)
620
+ else: print("You downvoted this response: " + data.value)
621
+
622
+
623
+ print ("Start GUIneu")
624
+ with open("custom.css", "r", encoding="utf-8") as f:
625
+ customCSS = f.read()
626
+
627
+ #Add Inputs für Tab 2
628
+ additional_inputs = [
629
+ 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),
630
+ gr.Slider(label="Max new tokens", value=1024, minimum=0, maximum=4096, step=64, interactive=True, info="Maximale Anzahl neuer Tokens", visible=True),
631
+ 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),
632
+ 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)
633
+ ]
634
+ with gr.Blocks(css=customCSS, theme=small_and_beautiful_theme) as demo:
635
+ #Session Variablen, um Weete zu speichern, auch wenn die Felder in der GUI bereits wieder leer sind
636
+ #history parallel zu chatbot speichern - momentan nicht im Gebrauch, ist aber in allen relevanten Methoden mit verlinkt
637
+ history = gr.State([])
638
+ #damit der Prompt auch nach dem upload in die History noch für predicts_args verfügbar ist
639
+ user_question = gr.State("")
640
+ #damit der Prompt auch nach dem upload in die History noch für predicts_args verfügbar ist
641
+ user_question2 = gr.State("")
642
+ attached_file = gr.State(None)
643
+ ################################################
644
+ # Tab zum Chatbot mit Text oder Bildeingabe
645
+ ################################################
646
+ gr.Markdown(description_top)
647
+ with gr.Tab("Chatbot"):
648
+ with gr.Row():
649
+ gr.HTML("LI Chatot")
650
+ status_display = gr.Markdown("Success", elem_id="status_display")
651
+ with gr.Row():
652
+ with gr.Column(scale=5):
653
+ with gr.Row():
654
+ chatbot = gr.Chatbot(elem_id="li-chat",show_copy_button=True)
655
+ with gr.Row():
656
+ with gr.Column(scale=12):
657
+ user_input = gr.Textbox(
658
+ show_label=False, placeholder="Gib hier deinen Prompt ein...",
659
+ container=False
660
+ )
661
+ with gr.Column(min_width=70, scale=1):
662
+ submitBtn = gr.Button("Senden")
663
+ with gr.Column(min_width=70, scale=1):
664
+ cancelBtn = gr.Button("Stop")
665
+ with gr.Row():
666
+ #file_display = gr.File(visible=False)
667
+ image_display = gr.Image( visible=False)
668
+ upload = gr.UploadButton("📁", file_types=["image"], scale = 10)
669
+ emptyBtn = gr.ClearButton([user_input, chatbot, history, attached_file, image_display], value="🧹 Neue Session", scale=10)
670
+
671
+ with gr.Column():
672
+ with gr.Column(min_width=50, scale=1):
673
+ with gr.Tab(label="Parameter Einstellung"):
674
+ #gr.Markdown("# Parameters")
675
+ rag_option = gr.Radio(["Aus", "An"], label="LI Erweiterungen (RAG)", value = "Aus")
676
+ model_option = gr.Radio(["OpenAI", "HuggingFace"], label="Modellauswahl", value = "OpenAI")
677
+
678
+
679
+ top_p = gr.Slider(
680
+ minimum=-0,
681
+ maximum=1.0,
682
+ value=0.95,
683
+ step=0.05,
684
+ interactive=True,
685
+ label="Top-p",
686
+ visible=False,
687
+ )
688
+ temperature = gr.Slider(
689
+ minimum=0.1,
690
+ maximum=2.0,
691
+ value=0.5,
692
+ step=0.1,
693
+ interactive=True,
694
+ label="Temperature",
695
+ visible=False
696
+ )
697
+ max_length_tokens = gr.Slider(
698
+ minimum=0,
699
+ maximum=512,
700
+ value=512,
701
+ step=8,
702
+ interactive=True,
703
+ label="Max Generation Tokens",
704
+ visible=False,
705
+ )
706
+ max_context_length_tokens = gr.Slider(
707
+ minimum=0,
708
+ maximum=4096,
709
+ value=2048,
710
+ step=128,
711
+ interactive=True,
712
+ label="Max History Tokens",
713
+ visible=False,
714
+ )
715
+ 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)
716
+ 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)
717
+ openai_key = gr.Textbox(label = "OpenAI API Key", value = "sk-", lines = 1, visible = False)
718
+ ################################################
719
+ # Tab zum Zeichnen mit Stable Diffusion
720
+ ################################################
721
+ with gr.Tab("KI zum Zeichnen"):
722
+ with gr.Row():
723
+ gr.HTML("LI Zeichnen mit KI")
724
+ status_display2 = gr.Markdown("Success", elem_id="status_display")
725
+ gr.Markdown(description2)
726
+ with gr.Row():
727
+ with gr.Column(scale=5):
728
+ with gr.Row():
729
+ chatbot_bild = gr.Chatbot(elem_id="li-zeichnen")
730
+ with gr.Row():
731
+ with gr.Column(scale=12):
732
+ user_input2 = gr.Textbox(
733
+ show_label=False, placeholder="Gib hier deinen Prompt ein...",
734
+ container=False
735
+ )
736
+ with gr.Column(min_width=70, scale=1):
737
+ submitBtn2 = gr.Button("Senden")
738
+ #with gr.Column(min_width=70, scale=1):
739
+ #cancelBtn2 = gr.Button("Stop")
740
+ with gr.Row():
741
+ emptyBtn2 = gr.ClearButton([user_input, chatbot_bild], value="🧹 Neue Session", scale=10)
742
+ #additional_inputs_accordion = gr.Accordion(label="Weitere Eingaben...", open=False)
743
+
744
+ gr.Markdown(description)
745
+
746
+ ######################################
747
+ # Events und Übergabe Werte an Funktionen
748
+ #######################################
749
+ ######################################
750
+ # Für Tab 1: Chatbot
751
+ #Argumente für generate Funktion als Input
752
+ predict_args = dict(
753
+ fn=generate_auswahl,
754
+ inputs=[
755
+ user_question,
756
+ attached_file,
757
+ chatbot,
758
+ history,
759
+ rag_option,
760
+ model_option,
761
+ openai_key,
762
+ anzahl_docs,
763
+ top_p,
764
+ temperature,
765
+ max_length_tokens,
766
+ max_context_length_tokens,
767
+ repetition_penalty
768
+ ],
769
+ outputs=[chatbot, history, attached_file, status_display], #[chatbot, history, status_display]
770
+ show_progress=True,
771
+ )
772
+
773
+ reset_args = dict(
774
+ fn=reset_textbox, inputs=[], outputs=[user_input, status_display]
775
+ )
776
+
777
+ # Chatbot
778
+ transfer_input_args = dict(
779
+ fn=add_text, inputs=[chatbot, history, user_input, attached_file], outputs=[chatbot, history, user_question, attached_file, image_display , user_input], show_progress=True
780
+ )
781
+
782
+ predict_event1 = user_input.submit(**transfer_input_args, queue=False,).then(**predict_args)
783
+ predict_event2 = submitBtn.click(**transfer_input_args, queue=False,).then(**predict_args)
784
+ predict_event3 = upload.upload(file_anzeigen, [upload], [image_display, image_display, attached_file] ) #.then(**predict_args)
785
+ emptyBtn.click(clear_all, [], [attached_file, image_display, history])
786
+ image_display.select(file_loeschen, [], [attached_file, image_display])
787
+
788
+ #Berechnung oder Ausgabe anhalten (kann danach fortgesetzt werden)
789
+ cancelBtn.click(cancel_outputing, [], [status_display], cancels=[predict_event1,predict_event2, predict_event3])
790
+
791
+ ######################################
792
+ # Für Tab 2: Zeichnen
793
+ predict_args2 = dict(
794
+ fn=generate_bild,
795
+ inputs=[
796
+ user_question2,
797
+ chatbot_bild,
798
+ #additional_inputs,
799
+ ],
800
+ outputs=[chatbot_bild, status_display2], #[chatbot, history, status_display]
801
+ show_progress=True,
802
+ )
803
+ transfer_input_args2 = dict(
804
+ fn=add_text2, inputs=[chatbot_bild, user_input2], outputs=[chatbot_bild, user_question2, user_input2], show_progress=True
805
+ )
806
+ predict_event2_1 = user_input2.submit(**transfer_input_args2, queue=False,).then(**predict_args2)
807
+ predict_event2_2 = submitBtn2.click(**transfer_input_args2, queue=False,).then(**predict_args2)
808
+ #emptyBtn2.click(clear_all, [], [file_display, image_display])
809
+
810
+ #cancelBtn2.click(
811
+ #cancels=[predict_event2_1,predict_event2_2 ]
812
+ #)
813
+
814
+
815
+ demo.title = "LI-ChatBot"
816
+ demo.queue().launch(debug=True)