alexkueck commited on
Commit
d00993a
·
verified ·
1 Parent(s): c582708

Delete appBackupNeu.py

Browse files
Files changed (1) hide show
  1. appBackupNeu.py +0 -608
appBackupNeu.py DELETED
@@ -1,608 +0,0 @@
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
-
249
-
250
- #########################################################
251
- #Funktion wird direkt aufgerufen aus der GUI - von hier muss auch die Rückmeldung kommen....
252
- #man kann einen Text-Prompt eingeben (mit oder ohne RAG), dazu ein Image hochladen, ein Bild zu einem reinen textprompt erzeugen lassen
253
- 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,):
254
- #kein Bild hochgeladen -> auf Text antworten...
255
- if (file == None):
256
- 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,)
257
- history = history + [(prompt, result)]
258
- else:
259
- #Es wurde ein Bild angehängt -> wenn prompt dazu, das Bild analysieren
260
- #geht nur über spezielle OpenAI-Schnittstelle...
261
- result= generate_text_zu_bild(file, prompt, k, rag_option, chatbot)
262
- history = history + [((file,), None),(prompt, result)]
263
-
264
- print("result..................")
265
- print(result)
266
- print("history.......................")
267
- print(chatbot)
268
- chatbot[-1][1] = ""
269
- for character in result:
270
- chatbot[-1][1] += character
271
- time.sleep(0.03)
272
- yield chatbot, history, None, "Generating"
273
- if shared_state.interrupted:
274
- shared_state.recover()
275
- try:
276
- yield chatbot, history, None, "Stop: Success"
277
- except:
278
- pass
279
-
280
- ##################################################
281
- #zu einem Text-Prompt ein Bild via Stable Diffusion generieren
282
- def generate_bild(prompt, chatbot, temperature=0.5, max_new_tokens=4048,top_p=0.6, repetition_penalty=1.3):
283
- #Bild nach Anweisung zeichnen und in History darstellen...
284
- data = {"inputs": prompt}
285
- response = requests.post(API_URL, headers=HEADERS, json=data)
286
- print("fertig Bild")
287
- result = response.content
288
- #Bild ausgeben
289
- image = Image.open(io.BytesIO(result))
290
- image_64 = umwandeln_fuer_anzeige(image)
291
- chatbot[-1][1]= "<img src='data:image/png;base64,{0}'/>".format(base64.b64encode(image_64).decode('utf-8'))
292
- return chatbot, "Success"
293
-
294
-
295
-
296
- ##################################################
297
- #zu einem Bild und Text-Prompt eine Analyse generieren
298
- def generate_text_zu_bild(file, prompt, k, rag_option, chatbot):
299
- global splittet
300
-
301
- prompt_neu = prompt
302
- if (rag_option == "An"):
303
- #muss nur einmal ausgeführt werden...
304
- if not splittet:
305
- splits = document_loading_splitting()
306
- document_storage_chroma(splits)
307
- db = document_retrieval_chroma2()
308
- #mit RAG:
309
- neu_text_mit_chunks = rag_chain2(prompt, db, k)
310
- #für Chat LLM:
311
- #prompt = generate_prompt_with_history_openai(neu_text_mit_chunks, history)
312
- #als reiner prompt:
313
- prompt_neu = generate_prompt_with_history(neu_text_mit_chunks, chatbot)
314
-
315
- headers, payload = process_image(file, prompt_neu)
316
- response = requests.post("https://api.openai.com/v1/chat/completions", headers=headers, json=payload)
317
- #als json ausgeben
318
- data = response.json()
319
- # Den "content" auswählen, da dort die Antwort der Ki enthalten ist
320
- result = data['choices'][0]['message']['content']
321
- return result
322
-
323
- ####################################################
324
- #aus einem Text-Prompt die Antwort von KI bekommen
325
- #mit oder ohne RAG möglich
326
- 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,):
327
- global splittet
328
-
329
- if (openai_api_key == "" or openai_api_key == "sk-"):
330
- #raise gr.Error("OpenAI API Key is required.")
331
- #eigenen OpenAI key nutzen
332
- openai_api_key= OAI_API_KEY
333
- if (rag_option is None):
334
- raise gr.Error("Retrieval Augmented Generation ist erforderlich.")
335
- if (prompt == ""):
336
- raise gr.Error("Prompt ist erforderlich.")
337
-
338
- #history für HuggingFace Models formatieren
339
- #history_text_und_prompt = generate_prompt_with_history_hf(prompt, history)
340
- #history für openAi formatieren
341
- #history_text_und_prompt = generate_prompt_with_history_openai(prompt, history)
342
- #history für Langchain formatieren
343
- #history_text_und_prompt = generate_prompt_with_history_langchain(prompt, history)
344
-
345
-
346
- try:
347
- ###########################
348
- #LLM auswählen (OpenAI oder HF)
349
- ###########################
350
- if (model_option == "OpenAI"):
351
- #Anfrage an OpenAI ----------------------------
352
- print("OpenAI Anfrage.......................")
353
- llm = ChatOpenAI(model_name = MODEL_NAME, openai_api_key = openai_api_key, temperature=temperature)#, top_p = top_p)
354
- #Prompt an history anhängen und einen Text daraus machen
355
- if (rag_option == "An"):
356
- history_text_und_prompt = generate_prompt_with_history(prompt, chatbot)
357
- else:
358
- history_text_und_prompt = generate_prompt_with_history_openai(prompt, chatbot)
359
- else:
360
- #oder an Hugging Face --------------------------
361
- print("HF Anfrage.......................")
362
- llm = HuggingFaceHub(repo_id=repo_id, model_kwargs={"temperature": 0.5, "max_length": 128})
363
- #llm = HuggingFaceChain(model=MODEL_NAME_HF, model_kwargs={"temperature": 0.5, "max_length": 128})
364
- #llm = HuggingFaceHub(url_??? = "https://wdgsjd6zf201mufn.us-east-1.aws.endpoints.huggingface.cloud", model_kwargs={"temperature": 0.5, "max_length": 64})
365
- #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,)
366
- print("HF")
367
- #Prompt an history anhängen und einen Text daraus machen
368
- history_text_und_prompt = generate_prompt_with_history(prompt, chatbot)
369
-
370
- #zusätzliche Dokumenten Splits aus DB zum Prompt hinzufügen (aus VektorDB - Chroma oder Mongo DB)
371
- if (rag_option == "An"):
372
- print("RAG aktiviert.......................")
373
- #muss nur einmal ausgeführt werden...
374
- if not splittet:
375
- splits = document_loading_splitting()
376
- document_storage_chroma(splits)
377
- db = document_retrieval_chroma(llm, history_text_und_prompt)
378
- print("LLM aufrufen mit RAG: ...........")
379
- result = rag_chain(llm, history_text_und_prompt, db)
380
- #elif (rag_option == "MongoDB"):
381
- #splits = document_loading_splitting()
382
- #document_storage_mongodb(splits)
383
- #db = document_retrieval_mongodb(llm, history_text_und_prompt)
384
- #result = rag_chain(llm, history_text_und_prompt, db)
385
- else:
386
- print("LLM aufrufen ohne RAG: ...........")
387
- result = llm_chain(llm, history_text_und_prompt)
388
-
389
- except Exception as e:
390
- raise gr.Error(e)
391
-
392
- return result
393
-
394
-
395
-
396
- ################################################
397
- #GUI
398
- ###############################################
399
- #Beschreibung oben in GUI
400
- ################################################
401
- #title = "LLM mit RAG"
402
- #description = """<strong>Information:</strong> Hier wird ein <strong>Large Language Model (LLM)</strong> mit
403
- #<strong>Retrieval Augmented Generation (RAG)</strong> auf <strong>externen Daten</strong> verwendet.\n\n"""
404
-
405
- 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"
406
-
407
- #css = """.toast-wrap { display: none !important } """
408
- #examples=[['Was ist ChtGPT-4?'],['schreibe ein Python Programm, dass die GPT-4 API aufruft.']]
409
-
410
- def vote(data: gr.LikeData):
411
- if data.liked: print("You upvoted this response: " + data.value)
412
- else: print("You downvoted this response: " + data.value)
413
-
414
-
415
- print ("Start GUIneu")
416
- with open("custom.css", "r", encoding="utf-8") as f:
417
- customCSS = f.read()
418
-
419
- #Add Inputs für Tab 2
420
- additional_inputs = [
421
- 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),
422
- gr.Slider(label="Max new tokens", value=1024, minimum=0, maximum=4096, step=64, interactive=True, info="Maximale Anzahl neuer Tokens", visible=True),
423
- 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),
424
- 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)
425
- ]
426
- with gr.Blocks(css=customCSS, theme=small_and_beautiful_theme) as demo:
427
- #Session Variablen, um Weete zu speichern, auch wenn die Felder in der GUI bereits wieder leer sind
428
- #history parallel zu chatbot speichern - momentan nicht im Gebrauch, ist aber in allen relevanten Methoden mit verlinkt
429
- history = gr.State([])
430
- #damit der Prompt auch nach dem upload in die History noch für predicts_args verfügbar ist
431
- user_question = gr.State("")
432
- #damit der Prompt auch nach dem upload in die History noch für predicts_args verfügbar ist
433
- user_question2 = gr.State("")
434
- attached_file = gr.State(None)
435
- ################################################
436
- # Tab zum Chatbot mit Text oder Bildeingabe
437
- ################################################
438
- gr.Markdown(description_top)
439
- with gr.Tab("Chatbot"):
440
- with gr.Row():
441
- gr.HTML("LI Chatot")
442
- status_display = gr.Markdown("Success", elem_id="status_display")
443
- with gr.Row():
444
- with gr.Column(scale=5):
445
- with gr.Row():
446
- chatbot = gr.Chatbot(elem_id="li-chat",show_copy_button=True)
447
- with gr.Row():
448
- with gr.Column(scale=12):
449
- user_input = gr.Textbox(
450
- show_label=False, placeholder="Gib hier deinen Prompt ein...",
451
- container=False
452
- )
453
- with gr.Column(min_width=70, scale=1):
454
- submitBtn = gr.Button("Senden")
455
- with gr.Column(min_width=70, scale=1):
456
- cancelBtn = gr.Button("Stop")
457
- with gr.Row():
458
- #file_display = gr.File(visible=False)
459
- image_display = gr.Image( visible=False)
460
- upload = gr.UploadButton("📁", file_types=["image"], scale = 10)
461
- emptyBtn = gr.ClearButton([user_input, chatbot, history, attached_file, image_display], value="🧹 Neue Session", scale=10)
462
-
463
- with gr.Column():
464
- with gr.Column(min_width=50, scale=1):
465
- with gr.Tab(label="Parameter Einstellung"):
466
- #gr.Markdown("# Parameters")
467
- rag_option = gr.Radio(["Aus", "An"], label="LI Erweiterungen (RAG)", value = "Aus")
468
- model_option = gr.Radio(["OpenAI", "HuggingFace"], label="Modellauswahl", value = "OpenAI")
469
-
470
-
471
- top_p = gr.Slider(
472
- minimum=-0,
473
- maximum=1.0,
474
- value=0.95,
475
- step=0.05,
476
- interactive=True,
477
- label="Top-p",
478
- visible=False,
479
- )
480
- temperature = gr.Slider(
481
- minimum=0.1,
482
- maximum=2.0,
483
- value=0.5,
484
- step=0.1,
485
- interactive=True,
486
- label="Temperature",
487
- visible=False
488
- )
489
- max_length_tokens = gr.Slider(
490
- minimum=0,
491
- maximum=512,
492
- value=512,
493
- step=8,
494
- interactive=True,
495
- label="Max Generation Tokens",
496
- visible=False,
497
- )
498
- max_context_length_tokens = gr.Slider(
499
- minimum=0,
500
- maximum=4096,
501
- value=2048,
502
- step=128,
503
- interactive=True,
504
- label="Max History Tokens",
505
- visible=False,
506
- )
507
- 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)
508
- 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)
509
- openai_key = gr.Textbox(label = "OpenAI API Key", value = "sk-", lines = 1, visible = False)
510
- ################################################
511
- # Tab zum Zeichnen mit Stable Diffusion
512
- ################################################
513
- with gr.Tab("KI zum Zeichnen"):
514
- with gr.Row():
515
- gr.HTML("LI Zeichnen mit KI")
516
- status_display2 = gr.Markdown("Success", elem_id="status_display")
517
- gr.Markdown(description2)
518
- with gr.Row():
519
- with gr.Column(scale=5):
520
- with gr.Row():
521
- chatbot_bild = gr.Chatbot(elem_id="li-zeichnen")
522
- with gr.Row():
523
- with gr.Column(scale=12):
524
- user_input2 = gr.Textbox(
525
- show_label=False, placeholder="Gib hier deinen Prompt ein...",
526
- container=False
527
- )
528
- with gr.Column(min_width=70, scale=1):
529
- submitBtn2 = gr.Button("Senden")
530
- #with gr.Column(min_width=70, scale=1):
531
- #cancelBtn2 = gr.Button("Stop")
532
- with gr.Row():
533
- emptyBtn2 = gr.ClearButton([user_input, chatbot_bild], value="🧹 Neue Session", scale=10)
534
- #additional_inputs_accordion = gr.Accordion(label="Weitere Eingaben...", open=False)
535
-
536
- gr.Markdown(description)
537
-
538
- ######################################
539
- # Events und Übergabe Werte an Funktionen
540
- #######################################
541
- ######################################
542
- # Für Tab 1: Chatbot
543
- #Argumente für generate Funktion als Input
544
- predict_args = dict(
545
- fn=generate_auswahl,
546
- inputs=[
547
- user_question,
548
- attached_file,
549
- chatbot,
550
- history,
551
- rag_option,
552
- model_option,
553
- openai_key,
554
- anzahl_docs,
555
- top_p,
556
- temperature,
557
- max_length_tokens,
558
- max_context_length_tokens,
559
- repetition_penalty
560
- ],
561
- outputs=[chatbot, history, attached_file, status_display], #[chatbot, history, status_display]
562
- show_progress=True,
563
- )
564
-
565
- reset_args = dict(
566
- fn=reset_textbox, inputs=[], outputs=[user_input, status_display]
567
- )
568
-
569
- # Chatbot
570
- transfer_input_args = dict(
571
- fn=add_text, inputs=[chatbot, history, user_input, attached_file], outputs=[chatbot, history, user_question, attached_file, image_display , user_input], show_progress=True
572
- )
573
-
574
- predict_event1 = user_input.submit(**transfer_input_args, queue=False,).then(**predict_args)
575
- predict_event2 = submitBtn.click(**transfer_input_args, queue=False,).then(**predict_args)
576
- predict_event3 = upload.upload(file_anzeigen, [upload], [image_display, image_display, attached_file] ) #.then(**predict_args)
577
- emptyBtn.click(clear_all, [], [attached_file, image_display, history])
578
- image_display.select(file_loeschen, [], [attached_file, image_display])
579
-
580
- #Berechnung oder Ausgabe anhalten (kann danach fortgesetzt werden)
581
- cancelBtn.click(cancel_outputing, [], [status_display], cancels=[predict_event1,predict_event2, predict_event3])
582
-
583
- ######################################
584
- # Für Tab 2: Zeichnen
585
- predict_args2 = dict(
586
- fn=generate_bild,
587
- inputs=[
588
- user_question2,
589
- chatbot_bild,
590
- #additional_inputs,
591
- ],
592
- outputs=[chatbot_bild, status_display2], #[chatbot, history, status_display]
593
- show_progress=True,
594
- )
595
- transfer_input_args2 = dict(
596
- fn=add_text2, inputs=[chatbot_bild, user_input2], outputs=[chatbot_bild, user_question2, user_input2], show_progress=True
597
- )
598
- predict_event2_1 = user_input2.submit(**transfer_input_args2, queue=False,).then(**predict_args2)
599
- predict_event2_2 = submitBtn2.click(**transfer_input_args2, queue=False,).then(**predict_args2)
600
- #emptyBtn2.click(clear_all, [], [file_display, image_display])
601
-
602
- #cancelBtn2.click(
603
- #cancels=[predict_event2_1,predict_event2_2 ]
604
- #)
605
-
606
-
607
- demo.title = "LI-ChatBot"
608
- demo.queue().launch(debug=True)