File size: 28,739 Bytes
89457ed
af937f5
 
063f2a2
204683a
27b2a14
b6b95fd
6868a66
b6b95fd
c5752ed
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
 
 
18d9524
47a5e53
41b540b
0fc5c2f
18d9524
ab6c181
5c4777a
 
d049b0a
4167057
df562c0
f08bb4c
4167057
9519de3
2b00953
ab6c181
701644a
ec9687d
764dc40
 
97ad75d
ddcfdbf
97ad75d
038542f
ab6c181
ddcfdbf
 
 
 
 
ada41ab
2ff2fc8
701644a
 
40f9ca5
0fc5c2f
 
18d9524
 
 
 
 
 
2b9c89c
 
 
5c4777a
 
 
27b2a14
bd804ad
 
371a1c2
f5360cb
bd804ad
a3847a3
 
5473db2
6d807e8
d699d10
6d807e8
 
d699d10
6d807e8
d699d10
4fa3e86
 
37e795b
e1c664b
72784ec
aa47a34
 
 
 
 
 
72784ec
a3847a3
7d84973
 
a5559e0
2cb3e6c
 
 
 
a5559e0
39baa47
 
 
 
 
 
 
 
c793a2a
39baa47
7d84973
 
67a7465
 
 
 
 
9764b41
 
 
 
 
 
 
37126bf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
10847b7
37126bf
 
 
 
 
 
 
 
 
 
 
 
 
aa96542
 
 
 
 
 
 
 
 
 
 
 
 
5b0f25f
5c4777a
 
7d84973
 
 
 
5ba7b43
4167057
9569fab
3d1f254
dc99fa5
9569fab
4167057
 
9764b41
 
 
 
 
 
4167057
10847b7
f43dcfb
191b138
e1c664b
191b138
61d5bf5
3e27c33
 
 
61d5bf5
3e27c33
 
e1c664b
7d84973
 
65be560
77898f3
9b40322
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b4127d8
8b2e190
2bf8d5a
5648df4
7d84973
 
4e50dab
857f4df
10847b7
7b0d0ec
 
10847b7
7b0d0ec
 
 
 
880d19b
7b0d0ec
84a5d26
7b0d0ec
 
 
4e50dab
bb49215
7b0d0ec
a149802
7d84973
a149802
7d84973
a149802
 
7d84973
aa96542
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7d84973
 
 
3d1f254
1c79a7c
10847b7
d40a063
 
 
 
 
 
 
 
624fd5c
f96ce19
e776b9f
f96ce19
555c5b0
 
428c948
5b0f25f
063f2a2
2ff2fc8
 
 
d8dd36b
 
42e7ede
191b138
d2db8f4
857f4df
f5360cb
857f4df
f5360cb
d8dd36b
 
42e7ede
f677869
 
d8dd36b
 
d58126c
d2db8f4
f5360cb
d2db8f4
5c4777a
da09491
42e7ede
4e21196
1c79a7c
 
 
5b0f25f
a471be0
7d84973
5b0f25f
42e7ede
063f2a2
 
42e7ede
 
063f2a2
a471be0
6d807e8
a149802
0fc5c2f
063f2a2
 
27b2a14
191b138
6d807e8
bc6921d
2440d28
f4e05be
 
 
 
5b0f25f
eb31b4b
a6e143b
 
 
3e901f3
 
a3847a3
 
5bf144f
 
 
 
 
0268abc
f70118e
a3847a3
 
a0dc16a
 
 
 
 
 
 
 
a3847a3
cce393e
 
a3847a3
cce393e
a3847a3
3caaad5
 
26a5193
2bf8d5a
 
 
5cb312a
f520e98
2bf8d5a
 
 
 
 
 
0ab1740
2bf8d5a
 
 
 
 
 
 
 
 
 
 
26a5193
2bf8d5a
9764b41
26a5193
2bf8d5a
 
 
 
 
8f58f98
2bf8d5a
0ab1740
2bf8d5a
 
 
 
 
 
 
 
0ab1740
2bf8d5a
 
 
 
 
 
 
 
93c2fe4
2bf8d5a
 
 
 
 
 
 
 
0ab1740
2bf8d5a
 
 
 
 
 
 
 
0ab1740
2bf8d5a
0ab1740
 
5175cfc
2bf8d5a
 
 
790cd7f
e1c664b
 
 
 
 
bc21b55
 
65be560
bc21b55
 
 
 
 
 
 
 
adf55cd
 
bc21b55
3caaad5
7f072a0
f64e434
9b40322
 
 
77898f3
9b40322
bc21b55
a6e143b
2bf8d5a
 
 
 
 
 
a3847a3
 
5648df4
a3847a3
 
8a55dff
d699d10
5ba7b43
a3847a3
 
 
 
 
 
 
 
 
 
61d5bf5
a3847a3
 
c793a2a
a3847a3
 
 
 
 
37e795b
173e482
a3847a3
 
61d5bf5
 
26a5193
f5360cb
2cb3e6c
6d807e8
39baa47
 
a3847a3
2bf8d5a
 
e1c664b
 
 
 
 
9b40322
f0ba633
e1c664b
9b40322
e1c664b
 
064c8f9
e1c664b
 
a9c1b77
 
e1c664b
 
adf55cd
 
 
0daec98
2bf8d5a
 
91597b1
a3847a3
e6365e6
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
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
import base64

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"



#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}"}


################################################
#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"
MODEL_NAME_IMAGE = "gpt-4-vision-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
################################################

##############################################
#wenn löschen Button geklickt
def clear_all():
    return None, gr.Image(visible=False), []

##############################################
#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, file, gr.Image(visible = False), "" #gr.Image( label=None, size=(30,30), visible=False, scale=1) #gr.Textbox(value="", interactive=False)

def add_text2(chatbot, prompt):   
    if (prompt == ""):
        chatbot = chatbot + [("", "Prompt fehlt!")]
    else:
        chatbot = chatbot + [(prompt, None)]
    print("chatbot nach add_text............")
    print(chatbot)
    return chatbot, prompt, ""
    
############################################
#nach dem Upload soll das zusätzliche Fenster mit dem image drinnen angezeigt werden
def file_anzeigen(file):
    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

def file_loeschen():
    return None, gr.Image(visible = False)

############################################
#wenn 'Stop' Button geklickt, dann Message dazu und das Eingabe-Fenster leeren
def cancel_outputing():
    reset_textbox()
    return "Stop Done"

def reset_textbox():
    return gr.update(value=""),""

    
##########################################
#Hilfsfunktion, um ein von Stable Diffusion erzeugtes Bild für die Ausgabe in der History vorzubereiten
def umwandeln_fuer_anzeige(image):
        buffer = io.BytesIO()  
        image.save(buffer, format='PNG')
        return buffer.getvalue()

#########################################
#Extension des hochgeladenen Files bestimmen
def analyze_file(file):
    file_extension = file.name.split('.')[-1]  # Holen Sie sich die Dateiendung
    return file_extension


##########################################
#ein hochgeladenes Bild so vorbereiten, dass OpenAI API es annehmen kann und bearbeiten
#muss ein base64 Bils sein und header und payload entsprechend konfigurieren
def process_image(image_path, prompt):
    # Convert image to base64
    with open(image_path, "rb") as image_file:
        encoded_string = base64.b64encode(image_file.read()).decode('utf-8')

    # Prepare the data for the API request (specific to the API you're using)
    headers = {
              "Content-Type": "application/json",
              "Authorization": f"Bearer {OAI_API_KEY}"
            }
    payload = {
      "model": MODEL_NAME_IMAGE,
      "messages": [
        {
          "role": "user",
          "content": [
            {
              "type": "text",
              "text":  llm_template + prompt
            },
            {
              "type": "image_url",
              "image_url": {
                "url": f"data:image/jpeg;base64,{encoded_string}"
              }
            }
          ]
        }
      ],
      "max_tokens": 300
    }   
    return headers, payload

##################################################
#openassistant um uploaded Files zu analysieren
def create_assistant(prompt, file): 
    client = OpenAI()
    assistant = client.beta.assistants.create(name="File Analysator",instructions=template, model="gpt-4-1106-preview",)
    thread = client.beta.threads.create()
    file_neu = client.files.create(file=open(file,"rb",),purpose="assistants",)
    # Update Assistant
    assistant = client.beta.assistants.update(assistant.id,tools=[{"type": "code_interpreter"}, {"type": "retrieval"}],file_ids=[file_neu.id],)
    thread, run = create_thread_and_run(prompt)
    run = wait_on_run(run, thread)
    return get_response(thread))

###################################################
#Funktion von Gradio aus, die den dort eingegebenen Prompt annimmt und weiterverarbeitet
###################################################
#########################################################
#Funktion wird direkt aufgerufen aus der GUI - von hier muss auch die Rückmeldung kommen....
#man kann einen Text-Prompt eingeben (mit oder ohne RAG), dazu ein Image hochladen, ein Bild zu einem reinen textprompt erzeugen lassen
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,):
        #kein Bild hochgeladen -> auf Text antworten...
        if (file == None):
            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,)
            history = history + [(prompt, result)]
        else:
            #Es wurde ein Bild angehängt -> wenn prompt dazu, das Bild analysieren
            #geht nur über spezielle OpenAI-Schnittstelle...
            ext = analyze_file(file)
            if (ext == "png" or ext == "PNG" or ext == "jgp" or ext == "jepg"):
                result= "Ausgabe" #generate_text_zu_bild(file, prompt, k, rag_option, chatbot)
            else:
                result = "Ausgabe File" #generate_text_zu_doc(file, prompt, k, rag_option, chatbot)
                
            history = history + [((file,), None),(prompt, result)]

        chatbot[-1][1] = ""
        for character in result:
            chatbot[-1][1] += character
            time.sleep(0.03)
            yield chatbot, history, None, "Generating"
            if shared_state.interrupted:
                shared_state.recover()
                try:
                    yield chatbot, history, None, "Stop: Success"
                except:
                    pass
        
##################################################
#zu einem Text-Prompt ein Bild via Stable Diffusion generieren
def generate_bild(prompt, chatbot, model_option_zeichnen='HuggingFace', temperature=0.5, max_new_tokens=4048,top_p=0.6, repetition_penalty=1.3):
    if (model_option_zeichnen == "Stable Diffusion"):
        print("Bild Erzeugung HF..............................")
        #Bild nach Anweisung zeichnen und in History darstellen...
        data = {"inputs": prompt}
        response = requests.post(API_URL, headers=HEADERS, json=data)
        print("fertig Bild")
        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(base64.b64encode(image_64).decode('utf-8'))
    else:     
        print("Bild Erzeugung DallE..............................")
        client = OpenAI()
        #als Format ginge auch 'url', n - Anz. der erzeugten Bilder
        response = client.images.generate(model="dall-e-3",prompt=prompt,size="1024x1024",quality="standard",n=1, response_format='b64_json') 
        #chatbot[-1][1]= "<img src='data:image/png;base64,{0}'/>".format(base64.b64encode(image_64).decode('utf-8'))
        chatbot[-1][1] = "<img src='data:image/png;base64,{0}'/>".format(response.data[0].b64_json)
    
    return chatbot, "Success"
    

##################################################
#zu einem Bild und Text-Prompt eine Analyse generieren
def generate_text_zu_bild(file, prompt, k, rag_option, chatbot):
    global splittet
    print("text mit Bild ..............................")
    prompt_neu = prompt
    if (rag_option == "An"):
        print("Bild mit RAG..............................")
        #muss nur einmal ausgeführt werden... 
        if not splittet:
            splits = document_loading_splitting()
            document_storage_chroma(splits)
        db = document_retrieval_chroma2()
        #mit RAG:
        neu_text_mit_chunks = rag_chain2(prompt, db, k)
        #für Chat LLM:
        #prompt = generate_prompt_with_history_openai(neu_text_mit_chunks, history)
        #als reiner prompt:
        prompt_neu = generate_prompt_with_history(neu_text_mit_chunks, chatbot)

    headers, payload = process_image(file, prompt_neu)
    response = requests.post("https://api.openai.com/v1/chat/completions", headers=headers, json=payload)
    #als json ausgeben
    data = response.json()
    # Den "content" auswählen, da dort die Antwort der Ki enthalten ist
    result = data['choices'][0]['message']['content']
    return result


##################################################
#zu einem Bild und Text-Prompt eine Analyse generieren
def generate_text_zu_doc(file, prompt, k, rag_option, chatbot):
    global splittet
    print("text mit doc ..............................")
    prompt_neu = prompt
    if (rag_option == "An"):
        print("Doc mit RAG..............................")
        #muss nur einmal ausgeführt werden... 
        if not splittet:
            splits = document_loading_splitting()
            document_storage_chroma(splits)
        db = document_retrieval_chroma2()
        #mit RAG:
        neu_text_mit_chunks = rag_chain2(prompt, db, k)
        #für Chat LLM:
        #prompt = generate_prompt_with_history_openai(neu_text_mit_chunks, history)
        #als reiner prompt:
        prompt_neu = generate_prompt_with_history(neu_text_mit_chunks, chatbot)


    create_assistant(prompt_neu, file)
        

    
    headers, payload = process_image(file, prompt_neu)
    response = requests.post("https://api.openai.com/v1/chat/completions", headers=headers, json=payload)
    #als json ausgeben
    data = response.json()
    # Den "content" auswählen, da dort die Antwort der Ki enthalten ist
    result = data['choices'][0]['message']['content']
    return result
    

####################################################
#aus einem Text-Prompt die Antwort von KI bekommen
#mit oder ohne RAG möglich
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,):
    global splittet
    print("Text pur..............................")
    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.")

    #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 Anfrage.......................")
            llm = ChatOpenAI(model_name = MODEL_NAME,  openai_api_key = openai_api_key, temperature=temperature)#, top_p = top_p) 
            #Prompt an history anhängen und einen Text daraus machen
            if (rag_option == "An"):
                history_text_und_prompt = generate_prompt_with_history(prompt, chatbot)
            else:
                history_text_und_prompt = generate_prompt_with_history_openai(prompt, chatbot)
        else:
            #oder an Hugging Face --------------------------
            print("HF Anfrage.......................")
            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")
            #Prompt an history anhängen und einen Text daraus machen
            history_text_und_prompt = generate_prompt_with_history(prompt, chatbot)
    
        #zusätzliche Dokumenten Splits aus DB zum Prompt hinzufügen (aus VektorDB - Chroma oder Mongo DB)
        if (rag_option == "An"):
            print("RAG aktiviert.......................")
            #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)
            splittet = True
            print("LLM aufrufen mit RAG: ...........")
            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:
            splittet = False
            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"""
                 
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"

#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()

#Add Inputs für Tab 2
additional_inputs = [
                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(css=customCSS, theme=small_and_beautiful_theme) as demo:
    #Session Variablen, um Weete zu speichern, auch wenn die Felder in der GUI bereits wieder leer sind
    #history parallel zu chatbot speichern - momentan nicht im Gebrauch, ist aber in allen relevanten Methoden mit verlinkt
    history = gr.State([])
    #damit der Prompt auch nach dem upload in die History noch für predicts_args verfügbar ist
    user_question = gr.State("")
    #damit der Prompt auch nach dem upload in die History noch für predicts_args verfügbar ist
    user_question2 = gr.State("")
    attached_file = gr.State(None)
    ################################################
    # Tab zum Chatbot mit Text oder Bildeingabe
    ################################################
    gr.Markdown(description_top)
    with gr.Tab("Chatbot"):
        with gr.Row():
            gr.HTML("LI Chatot")
            status_display = gr.Markdown("Success", elem_id="status_display")
        with gr.Row():
            with gr.Column(scale=5):
                with gr.Row():
                    chatbot = gr.Chatbot(elem_id="li-chat",show_copy_button=True)
                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():
                        #file_display = gr.File(visible=False)
                        image_display = gr.Image( visible=False)
                        upload = gr.UploadButton("📁", file_types=["image", "pdf", "docx", "pptx", "xlsx"], scale = 10)
                        emptyBtn = gr.ClearButton([user_input, chatbot, history, attached_file, image_display], value="🧹 Neue Session", scale=10)  
    
            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="LI Erweiterungen (RAG)", 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",
                            visible=False,
                        )
                        temperature = gr.Slider(
                            minimum=0.1,
                            maximum=2.0,
                            value=0.5,
                            step=0.1,
                            interactive=True,
                            label="Temperature",
                            visible=False
                        )
                        max_length_tokens = gr.Slider(
                            minimum=0,
                            maximum=512,
                            value=512,
                            step=8,
                            interactive=True,
                            label="Max Generation Tokens",
                            visible=False,
                        )
                        max_context_length_tokens = gr.Slider(
                            minimum=0,
                            maximum=4096,
                            value=2048,
                            step=128,
                            interactive=True,
                            label="Max History Tokens",
                            visible=False,
                        )
                        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)
                        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)
                        openai_key = gr.Textbox(label = "OpenAI API Key", value = "sk-", lines = 1, visible = False)
    ################################################
    # Tab zum Zeichnen mit Stable Diffusion
    ################################################
    with gr.Tab("KI zum Zeichnen"):
        with gr.Row():
            gr.HTML("LI Zeichnen mit KI")
            status_display2 = gr.Markdown("Success", elem_id="status_display")
        gr.Markdown(description2)
        with gr.Row():
            with gr.Column(scale=5):
                with gr.Row():
                    chatbot_bild = gr.Chatbot(elem_id="li-zeichnen",show_copy_button=True, show_share_button=True)
                with gr.Row():
                    with gr.Column(scale=12):
                        user_input2 = gr.Textbox(
                            show_label=False, placeholder="Gib hier deinen Prompt ein...",
                            container=False
                        )
                    with gr.Column(min_width=70, scale=1):
                        submitBtn2 = gr.Button("Senden")
                    #with gr.Column(min_width=70, scale=1):
                        #cancelBtn2 = gr.Button("Stop")
                with gr.Row():
                    emptyBtn2 = gr.ClearButton([user_input, chatbot_bild], value="🧹 Neue Session", scale=10)  
                    #additional_inputs_accordion = gr.Accordion(label="Weitere Eingaben...",  open=False)
            with gr.Column():
                with gr.Column(min_width=50, scale=1):
                    with gr.Tab(label="Parameter Einstellung"):
                        #gr.Markdown("# Parameters")
                        model_option_zeichnen = gr.Radio(["Stable Diffusion","DallE"], label="Modellauswahl", value = "Stable Diffusion")


    gr.Markdown(description)        
    
    ######################################
    # Events und Übergabe Werte an Funktionen 
    #######################################
    ######################################
    # Für Tab 1: Chatbot
    #Argumente für generate Funktion als Input
    predict_args = dict(
        fn=generate_auswahl,
        inputs=[
            user_question,
            attached_file,
            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, attached_file, 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, attached_file], outputs=[chatbot, history, user_question, attached_file, image_display , user_input], 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], [image_display, image_display, attached_file] ) #.then(**predict_args)
    emptyBtn.click(clear_all, [], [attached_file, image_display, history])
    image_display.select(file_loeschen, [], [attached_file, image_display])
    
    #Berechnung oder Ausgabe anhalten (kann danach fortgesetzt werden)
    cancelBtn.click(cancel_outputing, [], [status_display], cancels=[predict_event1,predict_event2, predict_event3]) 

    ######################################
    # Für Tab 2: Zeichnen
    predict_args2 = dict(
        fn=generate_bild,
        inputs=[
            user_question2,
            chatbot_bild,
            model_option_zeichnen,
            #additional_inputs,
        ],
        outputs=[chatbot_bild,  status_display2], #[chatbot, history,  status_display]
        show_progress=True,
    )
    transfer_input_args2 = dict(
        fn=add_text2, inputs=[chatbot_bild, user_input2], outputs=[chatbot_bild, user_question2, user_input2], show_progress=True
    )
    predict_event2_1 = user_input2.submit(**transfer_input_args2, queue=False,).then(**predict_args2)
    predict_event2_2 = submitBtn2.click(**transfer_input_args2, queue=False,).then(**predict_args2)
    #emptyBtn2.click(clear_all, [], [file_display, image_display])
    
    #cancelBtn2.click(
        #cancels=[predict_event2_1,predict_event2_2 ]
    #)
    
    
demo.title = "LI-ChatBot"
demo.queue().launch(debug=True)