File size: 32,939 Bytes
89457ed
af937f5
 
063f2a2
204683a
27b2a14
b6b95fd
6868a66
b6b95fd
a96e074
62cee3f
af937f5
063f2a2
 
edd880f
063f2a2
 
 
1b7141c
1461b21
0f079ae
73ae7b2
063f2a2
 
 
 
 
16b7808
a3847a3
 
063f2a2
f8ce324
0ddfcd1
2e4f369
063f2a2
 
 
af937f5
 
063f2a2
2b9c89c
5c4777a
2b9c89c
5c4777a
0b4bbfa
063f2a2
5c4777a
2e4f369
 
 
 
 
 
 
063f2a2
5c4777a
 
b335f8c
063f2a2
b335f8c
 
063f2a2
5c4777a
 
063f2a2
 
 
 
 
18d9524
47a5e53
41b540b
0fc5c2f
18d9524
ab6c181
5c4777a
9156bad
41b540b
 
62cee3f
063f2a2
5c4777a
 
8de518d
063f2a2
 
 
196a645
 
5c4777a
 
d049b0a
df562c0
 
68cf40f
9519de3
2b00953
ab6c181
f4b3ea4
063f2a2
701644a
ec9687d
764dc40
 
97ad75d
ddcfdbf
97ad75d
038542f
ab6c181
ddcfdbf
 
 
 
 
ada41ab
2ff2fc8
701644a
 
40f9ca5
0fc5c2f
 
18d9524
 
 
 
 
 
2b9c89c
 
 
5c4777a
 
 
27b2a14
a3847a3
 
5473db2
6d807e8
5473db2
6d807e8
 
5473db2
6d807e8
5473db2
4fa3e86
 
5473db2
a3847a3
 
a5559e0
60114e9
a5559e0
67a7465
 
 
 
 
 
62cee3f
 
 
 
 
 
 
 
 
67a7465
62cee3f
20697e4
93f3fd4
6587416
62cee3f
055ec6f
67a7465
 
055ec6f
67a7465
 
 
 
a447bbc
a3847a3
 
 
 
 
 
 
 
196a645
 
e79aa48
 
edd880f
e79aa48
 
196a645
 
 
 
 
27b2a14
5c4777a
063f2a2
f0634d5
196a645
063f2a2
 
e79aa48
196a645
 
 
 
 
 
 
 
 
 
 
 
 
 
063f2a2
60f8be0
8de518d
063f2a2
8de518d
 
063f2a2
9519de3
 
196a645
063f2a2
196a645
063f2a2
196a645
f0634d5
 
063f2a2
 
5c4777a
063f2a2
611fabf
fd8594f
063f2a2
d049b0a
fd8594f
16b7808
5c4777a
063f2a2
 
 
 
 
 
5c4777a
d049b0a
 
fd8594f
d049b0a
 
73ae7b2
08efd79
73ae7b2
fd8594f
16b7808
9479f46
16b7808
063f2a2
 
5c4777a
063f2a2
 
 
 
 
 
 
5c4777a
 
 
 
063f2a2
 
 
 
 
5c4777a
063f2a2
 
 
 
 
 
 
 
5b0f25f
f96ce19
 
 
76669be
5b0f25f
 
 
 
 
 
 
 
 
 
9479f46
 
5b0f25f
 
 
 
 
3e27c33
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f96ce19
 
 
 
 
 
 
 
5ba7b43
 
f96ce19
 
 
 
 
 
 
 
 
555c5b0
 
 
 
 
 
 
1b7141c
555c5b0
 
5b0f25f
 
5c4777a
 
1b2abae
925ec4a
 
 
1b2abae
 
 
925ec4a
1b2abae
 
 
 
 
6d807e8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
67a7465
5648df4
5ba7b43
5648df4
c6d6ee6
 
c0e5b31
191b138
49ffd3a
5473db2
dc99fa5
62cee3f
5473db2
5648df4
9dd2727
191b138
5473db2
9569fab
dc99fa5
9569fab
fb7f30a
62cee3f
1779326
3e27c33
191b138
 
 
 
3e27c33
 
 
 
 
 
 
5648df4
7407198
5648df4
 
 
c6d6ee6
5648df4
5ba7b43
1c79a7c
ce6fec1
d40a063
 
 
 
 
 
 
 
 
 
5b0f25f
40f9ca5
c237d0f
40f9ca5
67a7465
82621ff
6d807e8
f96ce19
e776b9f
f96ce19
555c5b0
 
428c948
5b0f25f
d40a063
063f2a2
2ff2fc8
 
 
d8dd36b
 
191b138
 
d58126c
d8dd36b
 
f677869
 
d8dd36b
 
d58126c
16b7808
5c4777a
da09491
4e21196
1c79a7c
 
 
5b0f25f
 
063f2a2
 
 
5b0f25f
 
063f2a2
6d807e8
191b138
0fc5c2f
5b0f25f
063f2a2
 
27b2a14
191b138
6d807e8
bc6921d
2440d28
f4e05be
 
 
 
5b0f25f
eb31b4b
61853f8
dab86e5
5bf144f
a3847a3
 
5bf144f
 
 
 
 
0268abc
f70118e
a3847a3
 
e6365e6
a3847a3
 
 
 
 
 
 
 
 
 
17448a6
a3847a3
 
 
 
 
 
 
 
 
 
 
0944ae1
46bfb77
0944ae1
a3847a3
 
 
 
b556df1
a3847a3
01346e3
a3847a3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5648df4
a3847a3
 
12b7a74
a3847a3
5ba7b43
a3847a3
 
 
 
 
 
 
 
 
 
5ba7b43
a3847a3
 
 
 
 
 
 
 
 
6d807e8
5473db2
a3847a3
 
38332fb
6a17bcf
2b4adb2
6d807e8
a3847a3
 
 
 
 
 
 
e6365e6
a3847a3
 
 
 
5bf144f
45f8b93
e776b9f
a734406
ddb0409
552d344
 
74241c4
 
5bf144f
 
0268abc
 
 
 
 
 
e223a8d
0fa95f9
eb31b4b
5b0f25f
57402ef
9a2741c
 
 
dab86e5
96e5ea2
 
0268abc
05ed685
a3847a3
05ed685
 
 
 
 
 
 
 
 
 
a3847a3
0268abc
 
 
 
 
 
 
 
 
 
b882d5a
0268abc
b882d5a
0268abc
b882d5a
0268abc
 
a3847a3
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
import requests
import os, sys, json
import gradio as gr
import openai
from openai import OpenAI
import time
import re
import io
from PIL import Image, ImageDraw, ImageOps, ImageFont
from base64 import b64encode
import shutil

from langchain.chains import LLMChain, RetrievalQA
from langchain.chat_models import ChatOpenAI
from langchain.document_loaders import PyPDFLoader, WebBaseLoader, UnstructuredWordDocumentLoader, DirectoryLoader
from langchain.document_loaders.blob_loaders.youtube_audio import YoutubeAudioLoader
from langchain.document_loaders.generic import GenericLoader
from langchain.document_loaders.parsers import OpenAIWhisperParser
from langchain.schema import AIMessage, HumanMessage
from langchain.llms import HuggingFaceHub
from langchain.llms import HuggingFaceTextGenInference
from langchain.embeddings import HuggingFaceInstructEmbeddings, HuggingFaceEmbeddings, HuggingFaceBgeEmbeddings, HuggingFaceInferenceAPIEmbeddings

from langchain.embeddings.openai import OpenAIEmbeddings
from langchain.prompts import PromptTemplate
from langchain.text_splitter import RecursiveCharacterTextSplitter
from langchain.vectorstores import Chroma
from chromadb.errors import InvalidDimensionException
from utils import *
from beschreibungen import *


#from langchain.vectorstores import MongoDBAtlasVectorSearch
#from pymongo import MongoClient

from dotenv import load_dotenv, find_dotenv
_ = load_dotenv(find_dotenv())



###############################################
#globale Variablen
##############################################
#nur bei ersten Anfrage splitten der Dokumente - um die Vektordatenbank entsprechend zu füllen
splittet = False

##################################################
#Für MongoDB statt Chroma als Vektorstore
#MONGODB_URI = os.environ["MONGODB_ATLAS_CLUSTER_URI"]
#client = MongoClient(MONGODB_URI)
#MONGODB_DB_NAME = "langchain_db"
#MONGODB_COLLECTION_NAME = "gpt-4"
#MONGODB_COLLECTION = client[MONGODB_DB_NAME][MONGODB_COLLECTION_NAME]
#MONGODB_INDEX_NAME = "default"

#################################################
#Prompt Zusätze
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 so kurz aber exakt."""

llm_template = "Beantworte die Frage am Ende. " + template + "Frage: {question} Hilfreiche Antwort: "
rag_template = "Nutze die folgenden Kontext Teile, um die Frage zu beantworten am Ende. " + template + "{context} Frage: {question} Hilfreiche Antwort: "

#################################################
#Konstanten
LLM_CHAIN_PROMPT = PromptTemplate(input_variables = ["question"], 
                                  template = llm_template)
RAG_CHAIN_PROMPT = PromptTemplate(input_variables = ["context", "question"], 
                                  template = rag_template)

#Plattform Keys aus den Secrets holen zu diesem Space
HUGGINGFACEHUB_API_TOKEN = os.getenv("HF_ACCESS_READ")
OAI_API_KEY=os.getenv("OPENAI_API_KEY")
HEADERS = {"Authorization": f"Bearer {HUGGINGFACEHUB_API_TOKEN}"}


#Pfad, wo Docs/Bilder/Filme abgelegt werden können - lokal, also hier im HF Space (sonst auf eigenem Rechner)
PATH_WORK = "."
CHROMA_DIR  = "/chroma"
YOUTUBE_DIR = "/youtube"
HISTORY_PFAD = "/data/history"

###############################################
#URLs zu Dokumenten oder andere Inhalte, die einbezogen werden sollen
PDF_URL       = "https://arxiv.org/pdf/2303.08774.pdf"
WEB_URL       = "https://openai.com/research/gpt-4"
YOUTUBE_URL_1 = "https://www.youtube.com/watch?v=--khbXchTeE"
YOUTUBE_URL_2 = "https://www.youtube.com/watch?v=hdhZwyf24mE"
#YOUTUBE_URL_3 = "https://www.youtube.com/watch?v=vw-KWfKwvTQ"

################################################
#LLM Model mit dem gearbeitet wird
#openai-------------------------------------
MODEL_NAME  = "gpt-3.5-turbo-16k"
#MODEL_NAME = "gpt-3.5-turbo-1106"
#MODEL_NAME= "gpt-4-1106-preview"


#verfügbare Modelle anzeigen lassen


#HuggingFace Reop ID--------------------------------
#repo_id = "meta-llama/Llama-2-13b-chat-hf"   
repo_id = "HuggingFaceH4/zephyr-7b-alpha"   #das Modell ist echt gut!!! Vom MIT
#repo_id = "TheBloke/Yi-34B-Chat-GGUF"
#repo_id = "meta-llama/Llama-2-70b-chat-hf"    
#repo_id = "tiiuae/falcon-40b"  
#repo_id = "Vicuna-33b"
#repo_id = "alexkueck/ChatBotLI2Klein"
#repo_id = "mistralai/Mistral-7B-v0.1"
#repo_id = "internlm/internlm-chat-7b"
#repo_id = "Qwen/Qwen-7B"
#repo_id = "Salesforce/xgen-7b-8k-base"
#repo_id = "Writer/camel-5b-hf" 
#repo_id = "databricks/dolly-v2-3b"
#repo_id = "google/flan-t5-xxl"

#HuggingFace Model name--------------------------------
MODEL_NAME_HF  = "mistralai/Mixtral-8x7B-Instruct-v0.1"
MODEL_NAME_OAI_ZEICHNEN = "dall-e-3"
#Alternativ zeichnen: Stabe Diffusion from HF:
API_URL = "https://api-inference.huggingface.co/models/stabilityai/stable-diffusion-2-1"

################################################
#HF Hub Zugriff ermöglichen
###############################################
os.environ["HUGGINGFACEHUB_API_TOKEN"] = HUGGINGFACEHUB_API_TOKEN


#################################################
#################################################
#################################################
#Funktionen zur Verarbeitung
################################################

##############################################
#History - die Frage oder das File eintragen...
def add_text(chatbot, history, prompt, file):
    if (file == None):
        chatbot = chatbot + [(prompt, None)]
    else:
        if (prompt == ""):
            chatbot = chatbot + [((file.name,), "Prompt fehlt!")]
        else:
            chatbot = chatbot + [((file.name,), None), (prompt, None)]
    print("chatbot nach add_text............")
    print(chatbot)
    return chatbot, history, prompt, "", gr.File( label=None, interactive=False,  height=20, min_width=20, visible=False, scale=2) #gr.Textbox(value="", interactive=False)
    

def file_anzeigen(file):
    return gr.File(visible=True), file

def umwandeln_fuer_anzeige(image):
        buffer = io.BytesIO()  
        image.save(buffer, format='PNG')
        return buffer.getvalue()

def process_image(image_path, prompt):
    #Bild aus tmp in Space ablegen
    #temp_image_path = "/tmp/gradio/01834b95fcf793903d65ab947cc410dc1600d0df/bbb 1.png"
    # Zielverzeichnis für das dauerhafte Bild
    #target_directory = HISTORY_PFAD
    # Ziel-Pfad für das dauerhafte Bild
    #target_image_path = os.path.join(target_directory, "bbb 1.png")
    # Kopieren Sie das temporäre Bild in das Zielverzeichnis
    #shutil.copy(temp_image_path, target_image_path)

    # Convert image to base64
    #with open(image_path, "rb") as image_file:
    with open("/home/user/app/data/history/bbb_1.png", "rb") as image_file:
        encoded_string = b64encode(image_file.read()).decode()
    print ("encoded string.................")
    print(encoded_string)

    # Prepare the data for the API request (specific to the API you're using)
    data = {
        'image': "/home/user/app/data/history/bbb_1.png", #encoded_string,
        'input': prompt,
    }
    return data


def transfer_input(inputs):
    textbox = reset_textbox()
    return (
        inputs,
        gr.update(value=""),
        gr.Button.update(visible=True),
    )
##################################################
# Funktion, um für einen best. File-typ ein directory-loader zu definieren
def create_directory_loader(file_type, directory_path):
    #verscheidene Dokument loaders:
    loaders = {
        '.pdf': PyPDFLoader,
        '.word': UnstructuredWordDocumentLoader,
    }
    return DirectoryLoader(
        path=directory_path,
        glob=f"**/*{file_type}",
        loader_cls=loaders[file_type],
    )
    
#die Inhalte splitten, um in Vektordatenbank entsprechend zu laden als Splits
def document_loading_splitting():
    global splittet
    ##############################
    # Document loading
    docs = []
    
    # kreiere einen DirectoryLoader für jeden file type
    pdf_loader = create_directory_loader('.pdf', './chroma/pdf')
    word_loader = create_directory_loader('.word', './chroma/word')
    
    
    # Load the files
    pdf_documents = pdf_loader.load()
    word_documents = word_loader.load()

    #alle zusammen in docs...
    docs.extend(pdf_documents)
    docs.extend(word_documents)

    #andere loader...
    # Load PDF
    loader = PyPDFLoader(PDF_URL)
    docs.extend(loader.load())
    # Load Web
    loader = WebBaseLoader(WEB_URL)
    docs.extend(loader.load())
    # Load YouTube
    loader = GenericLoader(YoutubeAudioLoader([YOUTUBE_URL_1,YOUTUBE_URL_2], PATH_WORK + YOUTUBE_DIR), OpenAIWhisperParser())
    docs.extend(loader.load())
    ################################
    # Document splitting
    text_splitter = RecursiveCharacterTextSplitter(chunk_overlap = 150, chunk_size = 1500)
    splits = text_splitter.split_documents(docs)
    
    #nur bei erster Anfrage mit "choma" wird gesplittet...
    splittet = True
    return splits

#Chroma DB die splits ablegen - vektorisiert...
def document_storage_chroma(splits):
    #OpenAi embeddings----------------------------------
    Chroma.from_documents(documents = splits, embedding = OpenAIEmbeddings(disallowed_special = ()),  persist_directory = PATH_WORK + CHROMA_DIR)  

    #HF embeddings--------------------------------------
    #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)  
    
#Mongo DB die splits ablegen - vektorisiert...
def document_storage_mongodb(splits):
    MongoDBAtlasVectorSearch.from_documents(documents = splits,
                                            embedding = OpenAIEmbeddings(disallowed_special = ()),
                                            collection = MONGODB_COLLECTION,
                                            index_name = MONGODB_INDEX_NAME)

#dokumente in chroma db vektorisiert ablegen können - die Db vorbereiten daüfur
def document_retrieval_chroma(llm, prompt):  
    #OpenAI embeddings -------------------------------
    embeddings = OpenAIEmbeddings()

    #HF embeddings -----------------------------------
    #Alternative Embedding - für Vektorstore, um Ähnlichkeitsvektoren zu erzeugen - die ...InstructEmbedding ist sehr rechenaufwendig
    #embeddings = HuggingFaceInstructEmbeddings(model_name="sentence-transformers/all-MiniLM-L6-v2", model_kwargs={"device": "cpu"})
    #etwas weniger rechenaufwendig:
    #embeddings = HuggingFaceEmbeddings(model_name="sentence-transformers/all-mpnet-base-v2", model_kwargs={"device": "cpu"}, encode_kwargs={'normalize_embeddings': False})

    #ChromaDb um die embedings zu speichern
    db = Chroma(embedding_function = embeddings, persist_directory = PATH_WORK + CHROMA_DIR)
    return db

#dokumente in mongo db vektorisiert ablegen können - die Db vorbereiten daüfür
def document_retrieval_mongodb(llm, prompt):
    db = MongoDBAtlasVectorSearch.from_connection_string(MONGODB_URI,
                                                         MONGODB_DB_NAME + "." + MONGODB_COLLECTION_NAME,
                                                         OpenAIEmbeddings(disallowed_special = ()),
                                                         index_name = MONGODB_INDEX_NAME)
    return db

###############################################
#Langchain anlegen

#langchain nutzen, um prompt an LLM zu leiten - llm und prompt sind austauschbar
def llm_chain(llm, prompt):
    llm_chain = LLMChain(llm = llm, prompt = LLM_CHAIN_PROMPT)
    result = llm_chain.run({"question": prompt})
    return result

#langchain nutzen, um prompt an llm zu leiten, aber vorher in der VektorDB suchen, um passende splits zum Prompt hinzuzufügen
def rag_chain(llm, prompt, db):
    rag_chain = RetrievalQA.from_chain_type(llm, 
                                            chain_type_kwargs = {"prompt": RAG_CHAIN_PROMPT}, 
                                            retriever = db.as_retriever(search_kwargs = {"k": 3}), 
                                            return_source_documents = True)
    result = rag_chain({"query": prompt})
    return result["result"]

###################################################
#Prompts mit History erzeugen für verschiednee Modelle
###################################################
#Funktion, die einen Prompt mit der history zusammen erzeugt - allgemein
def generate_prompt_with_history(text, history, max_length=4048):
    #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!"   
    #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!"   
    prompt=""
    history = ["\n{}\n{}".format(x[0],x[1]) for x in history]
    history.append("\n{}\n".format(text))
    history_text = ""
    flag = False
    for x in history[::-1]:
            history_text = x + history_text
            flag = True
    print ("Prompt: ..........................")
    print(prompt+history_text)
    if flag:
        return  prompt+history_text
    else:
        return None

def generate_prompt_and_file_with_history(text, history, file):
    #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!"   
    #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!"   
    prompt=""
    history = ["\n{}\n{}".format(x[0],x[1]) for x in history]
    history.append("\n{}\n".format(text))
    history_text = ""
    flag = False
    for x in history[::-1]:
            history_text = x + history_text
            flag = True
    print ("Prompt: ..........................")
    print(prompt+history_text)
    if flag:
        return  prompt+history_text
    else:
        return None

#Prompt und History für OPenAi Schnittstelle
def generate_prompt_with_history_openai(prompt, history):
    history_openai_format = []
    for human, assistant in history:
        history_openai_format.append({"role": "user", "content": human })
        history_openai_format.append({"role": "assistant", "content":assistant})

    history_openai_format.append({"role": "user", "content": prompt})
    print("openai history und prompt................")
    print(history_openai_format)
    return history_openai_format

#Prompt und History für Hugging Face Schnittstelle
def generate_prompt_with_history_hf(prompt, history):
    history_transformer_format = history + [[prompt, ""]]
    #stop = StopOnTokens()

    messages = "".join(["".join(["\n<human>:"+item[0], "\n<bot>:"+item[1]])  #curr_system_message +
                for item in history_transformer_format])

#Prompt und History für Langchain Schnittstelle
def generate_prompt_with_history_langchain(prompt, history):
    history_langchain_format = []
    for human, ai in history:
        history_langchain_format.append(HumanMessage(content=human))
        history_langchain_format.append(AIMessage(content=ai))
    history_langchain_format.append(HumanMessage(content=prompt))
  
    return history_langchain_format
        

###################################################
#Funktion von Gradio aus, die den dort eingegebenen Prompt annimmt und weiterverarbeitet
#erstmal gucken, ob text oder Bild angekommen ist
def chatbot_response(messages):
    print("messages.......................")
    print(messages)
    responses = []
    for message in messages:
        if message['type'] == 'text':
            #invoke(message['data'], history, rag_option, model_option, openai_api_key,  temperature=0.5, max_new_tokens=4048, top_p=0.6, repetition_penalty=1.3,)
            responses.append({'type': 'text', 'data': f"Echo: {message['data']}"})
        else:
            print("Bild.............................")
    return responses

def create_picture(history,  prompt):
    client = OpenAI()
    response = client.images.generate(model="dall-e-3", prompt=prompt,size="1024x1024",quality="standard",n=1,)
    image_url = response.data[0].url
    return image_url

# prompt describing the desired image 
#text = "batman art in red and blue color"
# calling the custom function "generate" 
# saving the output in "url1" 
#url1 = create_picture(text) 
# using requests library to get the image in bytes 
#response = requests.get(url1) 
# using the Image module from PIL library to view the image 
#Image.open(response.raw)



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,):
     if (prompt.find('zeichnen') != -1):
        response = generate_bild(prompt)
        result = response.content 
        #Bild ausgeben
        image = Image.open(io.BytesIO(result)) 
        image_64 = umwandeln_fuer_anzeige(image)
        chatbot[-1][1] =  "<img src='data:image/png;base64,{0}'/>".format(b64encode(image_64).decode('utf-8')) 
        history = history + [(prompt, result)]  

        return chatbot, history, "Success"
     else:
        result = generate_text(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,)
        #Antwort als Stream ausgeben... wenn Textantwort gefordert
        chatbot[-1][1] = result
        if (file == None):
            history = history + [(prompt, result)]
        else:
            history = history + [((file,), None),(prompt, result)]

        return chatbot, history, "Success" 
        """ 
        for character in result:
            history[-1][1] += character
            time.sleep(0.03)
            yield history, "Generating"
            if shared_state.interrupted:
                shared_state.recover()
                try:
                    yield history, "Stop: Success"
                except:
                    pass
        """

def generate_bild(prompt):
    data = {"inputs": prompt}
    response = requests.post(API_URL, headers=HEADERS, json=data)
    print("fertig Bild")
    return response

def generate_text (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,):
    global splittet
    print(splittet)

    if (openai_api_key == "" or openai_api_key == "sk-"):
        #raise gr.Error("OpenAI API Key is required.")
        #eigenen OpenAI key nutzen
        openai_api_key= OAI_API_KEY
    if (rag_option is None):
        raise gr.Error("Retrieval Augmented Generation ist erforderlich.")
    if (prompt == ""):
        raise gr.Error("Prompt ist erforderlich.")
        
    #Prompt an history anhängen und einen Text daraus machen
    if (file == None):
        history_text_und_prompt = generate_prompt_with_history_openai(prompt, history)
    else:
        prompt_neu = process_image(file, prompt)
        history_text_und_prompt = generate_prompt_with_history_openai(prompt_neu, history)
        
    #history für HuggingFace Models formatieren
    #history_text_und_prompt = generate_prompt_with_history_hf(prompt, history)
    #history für openAi formatieren
    #history_text_und_prompt = generate_prompt_with_history_openai(prompt, history)
    #history für Langchain formatieren
    #history_text_und_prompt = generate_prompt_with_history_langchain(prompt, history)
    

    try:
        ###########################
        #LLM auswählen (OpenAI oder HF)
        ###########################
        if (model_option == "OpenAI"):
            #Anfrage an OpenAI ----------------------------
            print("OpenAI normal.......................")
            llm = ChatOpenAI(model_name = MODEL_NAME,  openai_api_key = openai_api_key, temperature=temperature)#, top_p = top_p) 
            print("openAI")
        else:
            #oder an Hugging Face --------------------------
            llm = HuggingFaceHub(repo_id=repo_id, model_kwargs={"temperature": 0.5, "max_length": 128}) 
            #llm = HuggingFaceChain(model=MODEL_NAME_HF, model_kwargs={"temperature": 0.5, "max_length": 128}) 
            #llm = HuggingFaceHub(url_??? = "https://wdgsjd6zf201mufn.us-east-1.aws.endpoints.huggingface.cloud", model_kwargs={"temperature": 0.5, "max_length": 64}) 
            #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,)
            print("HF")

        #zusätzliche Dokumenten Splits aus DB zum Prompt hinzufügen (aus VektorDB - Chroma oder Mongo DB)
        if (rag_option == "An"):
            #muss nur einmal ausgeführt werden... 
            if not splittet:
                splits = document_loading_splitting()
                document_storage_chroma(splits)
            db = document_retrieval_chroma(llm, history_text_und_prompt)
            result = rag_chain(llm, history_text_und_prompt, db)
        elif (rag_option == "MongoDB"):
            #splits = document_loading_splitting()
            #document_storage_mongodb(splits)
            db = document_retrieval_mongodb(llm, history_text_und_prompt)
            result = rag_chain(llm, history_text_und_prompt, db)
        else:
            print("LLM aufrufen ohne RAG: ...........")
            result = llm_chain(llm, history_text_und_prompt)
            

    except Exception as e:
        raise gr.Error(e)

    return result

        
      
################################################
#GUI
###############################################
#Beschreibung oben in GUI
################################################
#title = "LLM mit RAG"
description = """<strong>Information:</strong> Hier wird ein <strong>Large Language Model (LLM)</strong> mit 
                 <strong>Retrieval Augmented Generation (RAG)</strong> auf <strong>externen Daten</strong> verwendet.\n\n
                 """
#css = """.toast-wrap { display: none !important } """
#examples=[['Was ist ChtGPT-4?'],['schreibe ein Python Programm, dass die GPT-4 API aufruft.']]

def vote(data: gr.LikeData):
    if data.liked: print("You upvoted this response: " + data.value)
    else: print("You downvoted this response: " + data.value)


print ("Start GUIneu")
with open("custom.css", "r", encoding="utf-8") as f:
    customCSS = f.read()
    
with gr.Blocks(css=customCSS, theme=small_and_beautiful_theme) as demo:
    history = gr.State([])
    user_question = gr.State("")
    with gr.Row():
        gr.HTML("LI Chatot")
        status_display = gr.Markdown("Success", elem_id="status_display")
    gr.Markdown(description_top)
    with gr.Row():
        with gr.Column(scale=5):
            with gr.Row():
                chatbot = gr.Chatbot(elem_id="chuanhu_chatbot",)
            with gr.Row():
                with gr.Column(scale=12):
                    user_input = gr.Textbox(
                        show_label=False, placeholder="Gib hier deinen Prompt ein...",
                        container=False
                    )
                with gr.Column(min_width=70, scale=1):
                    submitBtn = gr.Button("Senden")
                with gr.Column(min_width=70, scale=1):
                    cancelBtn = gr.Button("Stop")
            with gr.Row():
                emptyBtn = gr.ClearButton( [user_input, chatbot], value="🧹 Neue Session", scale=3)  
                upload = gr.UploadButton("📁", file_types=["image", "video", "audio"], scale=3)
                file_display = gr.File( label=None, interactive=False,  height=30, min_width=30, visible=False, scale=2)

        with gr.Column():
            with gr.Column(min_width=50, scale=1):
                with gr.Tab(label="Parameter Einstellung"):
                    #gr.Markdown("# Parameters")
                    rag_option = gr.Radio(["Aus", "An"], label="RAG - LI Erweiterungen", value = "Aus")
                    model_option = gr.Radio(["OpenAI", "HuggingFace"], label="Modellauswahl", value = "OpenAI")
                    
                    top_p = gr.Slider(
                        minimum=-0,
                        maximum=1.0,
                        value=0.95,
                        step=0.05,
                        interactive=True,
                        label="Top-p",
                    )
                    temperature = gr.Slider(
                        minimum=0.1,
                        maximum=2.0,
                        value=1,
                        step=0.1,
                        interactive=True,
                        label="Temperature",
                    )
                    max_length_tokens = gr.Slider(
                        minimum=0,
                        maximum=512,
                        value=512,
                        step=8,
                        interactive=True,
                        label="Max Generation Tokens",
                    )
                    max_context_length_tokens = gr.Slider(
                        minimum=0,
                        maximum=4096,
                        value=2048,
                        step=128,
                        interactive=True,
                        label="Max History Tokens",
                    )
                    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=True)
                    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=True)
                    openai_key = gr.Textbox(label = "OpenAI API Key", value = "sk-", lines = 1)
    gr.Markdown(description)

    #Argumente für generate Funktion als Input
    predict_args = dict(
        fn=generate_auswahl,
        inputs=[
            user_question,
            upload,
            chatbot,
            history,
            rag_option,
            model_option,
            openai_key,
            anzahl_docs,
            top_p,
            temperature,
            max_length_tokens,
            max_context_length_tokens,
            repetition_penalty
        ],
        outputs=[chatbot, history,  status_display], #[chatbot, history,  status_display]
        show_progress=True,
    )


    reset_args = dict(
        fn=reset_textbox, inputs=[], outputs=[user_input, status_display]
    )

    # Chatbot
    transfer_input_args = dict(
        fn=add_text, inputs=[chatbot, history, user_input, upload], outputs=[chatbot, history, user_question, user_input, file_display], show_progress=True
    )

    predict_event1 = user_input.submit(**transfer_input_args, queue=False,).then(**predict_args)
    predict_event2 = submitBtn.click(**transfer_input_args, queue=False,).then(**predict_args)
    predict_event3 = upload.upload(file_anzeigen, [upload], [file_display, file_display] ) #.then(**predict_args)
    
    cancelBtn.click(
        cancels=[predict_event1,predict_event2, predict_event3 ]
    )
demo.title = "LI-ChatBot"

demo.queue().launch(debug=True)





"""
additional_inputs = [
    #gr.Radio(["Off", "Chroma", "MongoDB"], label="Retrieval Augmented Generation", value = "Off"),
    gr.Radio(["Aus", "An"], label="RAG - LI Erweiterungen", value = "Aus"),
    gr.Radio(["OpenAI", "HuggingFace"], label="Modellauswahl", value = "HuggingFace"),
    gr.Textbox(label = "OpenAI API Key", value = "sk-", lines = 1), 
    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),
    gr.Slider(label="Max new tokens", value=1024, minimum=0, maximum=4096, step=64, interactive=True, info="Maximale Anzahl neuer Tokens", visible=True),
    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),
    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)
]

with gr.Blocks() as demo:
    reference_image  = gr.Image(label="Reference Image")

    chatbot_stream = gr.Chatbot()

    chat_interface_stream = gr.ChatInterface(fn=invoke, 
                additional_inputs = additional_inputs,
                additional_inputs_accordion = gr.Accordion(label="Weitere Eingaben...",  open=False),
                title = "ChatGPT vom LI",
                theme="soft",
                chatbot=chatbot_stream,
                retry_btn="🔄 Wiederholen",
                undo_btn="↩️ Letztes löschen",
                clear_btn="🗑️ Verlauf löschen",
                submit_btn = "Abschicken",
                description = description,
                ) 
    
    gr.HTML(
        
        <div style="display: flex; justify-content: center; align-items: center; text-align: center;">
        <a href="https://github.com/magic-research/magic-animate" style="margin-right: 20px; text-decoration: none; display: flex; align-items: center;">
        </a>
        <div>
            <h1 >Chatbot des LI - hier im Test mit Image Eingabe</h1>
            <div style="display: flex; justify-content: center; align-items: center; text-align: center;>
                <a href="https://arxiv.org/abs/2311.16498"><img src="https://img.shields.io/badge/Arxiv-2311.16498-red"></a>
            </div>
        </div>
        </div>
        )
    
    with gr.Row():
        prompt = gr.Textbox(
            scale=4,
            show_label=False,
            placeholder="Gib einen Text ein oder lade eine Datei (Bild, File, Audio) hoch",
            container=False,
        )
        btn = gr.UploadButton("📁", file_types=["image", "video", "audio"])

    txt_msg = txt.submit(invoke, [chat_interface_stream, prompt], [chat_interface_stream, prompt], queue=False).then(bot, chat_interface_stream, chat_interface_stream, api_name="bot_response")
    txt_msg.then(lambda: gr.Textbox(interactive=True), None, [prompt], queue=False)
    file_msg = btn.upload(add_file, [chat_interface_stream, btn], [chat_interface_stream], queue=False).then(bot, chat_interface_stream, chat_interface_stream)

    #chatbot_stream.like(print_like_dislike, None, None)


demo.queue().launch() 
"""