File size: 30,737 Bytes
e455e2a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a38197e
e455e2a
 
 
 
 
 
 
 
 
e50df4b
 
 
 
 
 
 
 
 
 
 
e1d41b5
 
e50df4b
 
 
 
 
 
5a9ae3f
 
 
9787837
e50df4b
f1715d8
 
 
 
 
 
fc94519
 
 
 
e455e2a
 
 
 
 
 
fc94519
 
 
 
f0fac31
a38881b
 
 
 
 
 
5fc8f2d
a38881b
7f19cee
f0fac31
 
 
785d30a
a38881b
 
 
 
 
f0fac31
285c233
f0fac31
 
a38881b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fc94519
 
 
98c4fd4
 
c16f545
 
 
 
 
 
 
 
 
 
 
 
 
 
fc94519
 
f1715d8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8b0f09e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f0fac31
 
 
 
 
 
8b0f09e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7b13b82
 
 
 
 
 
cf21012
7b13b82
 
 
 
 
 
 
cf21012
7b13b82
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cf21012
02ee690
 
 
7b13b82
 
 
cf21012
7b13b82
 
 
 
 
 
 
 
 
9516191
7b13b82
 
 
 
 
 
 
8b0f09e
643a931
 
f0fac31
dcffd8b
 
1e8fcfa
 
 
 
 
 
 
 
 
 
 
 
 
8b0f09e
 
 
 
e455e2a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b92c57d
 
 
 
 
 
e455e2a
faad25e
 
 
 
 
 
 
78c1f86
faad25e
 
00a616b
 
 
5969f71
0179ea7
 
 
 
 
 
 
 
 
00a616b
 
0179ea7
00a616b
5969f71
00a616b
 
 
 
 
 
 
 
 
9c5aff5
00a616b
 
 
 
 
 
 
 
6728a12
 
e1d41b5
6728a12
 
 
f5edc18
9a3bcdf
0d5659a
f5edc18
e051898
f5edc18
 
 
 
 
 
 
 
 
9280e71
f5edc18
 
 
 
 
 
9edb4f8
00a616b
 
bce755b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d447d84
bce755b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e455e2a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
from __future__ import annotations
from typing import TYPE_CHECKING, Any, Callable, Dict, List, Tuple, Type
import logging
import json
import os
import datetime
import hashlib
import csv
import requests
import re
import html
import markdown2
import torch 
import sys
import gc
from pygments.lexers import guess_lexer, ClassNotFound
import time

import gradio as gr
from pypinyin import lazy_pinyin
import tiktoken
import mdtex2html
from markdown import markdown
from pygments import highlight
from pygments.lexers import guess_lexer,get_lexer_by_name
from pygments.formatters import HtmlFormatter

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.tools import DuckDuckGoSearchRun
from langchain.retrievers.tavily_search_api import TavilySearchAPIRetriever

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
import io
from PIL import Image, ImageDraw, ImageOps, ImageFont
import base64
from tempfile import NamedTemporaryFile

import nltk
from nltk.corpus import stopwords
from nltk.tokenize import word_tokenize
from nltk.stem import WordNetLemmatizer
nltk.download('punkt')

from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics.pairwise import cosine_similarity
import numpy as np


logging.basicConfig(
    level=logging.INFO,
    format="%(asctime)s [%(levelname)s] [%(filename)s:%(lineno)d] %(message)s",
)

################################################
#Beispiel-Antworten, wenn die KI etwas nicht beantworten kann - dann im Netz suchen
################################################
# Your predefined sentences
ANTWORT_WEISS_NICHT = ["ich weiß nicht.", "ich weiß das nicht", "Ich habe dazu keine Antwort", "Ich bin nicht sicher", "Ich kann das nicht beantworten", "Es tut mir leid, aber ich kenne keinen", "Es tut mir leid, aber ich kann die Frage nicht beantworten.", "Es tut mir leid, aber ich kann die Frage nicht beantworten, da ich zu der Frage keine spezifischen Informatioen habe"]

#################################################
#Gesetzte Werte für Pfade, Prompts und Keys..
#################################################
#################################################
#Prompt Zusätze
template = """Antworte in deutsch, wenn es nicht explizit anders gefordert wird. Wenn du die Antwort nicht kennst, antworte direkt, dass du es nicht weißt. Versuche nicht es zu umschreiben. Versuche nicht, die Antwort zu erfinden oder aufzumocken. Halte die Antwort kurz aber ausführlich genug und exakt."""

llm_template = "Beantworte die Frage am Ende. " + template + "Frage: {question} "
#nur für HF für Stichwotre bei chatverlauf
llm_template2 = "Fasse folgenden Text als Überschrift mit maximal 3 Worten zusammen. Text: {question}  "

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

#################################################
#Konstanten
LLM_CHAIN_PROMPT = PromptTemplate(input_variables = ["question"], 
                                  template = llm_template)
#nur für HF bei chatverlauf
LLM_CHAIN_PROMPT2 = PromptTemplate(input_variables = ["question"], 
                                  template = llm_template2)

RAG_CHAIN_PROMPT = PromptTemplate(input_variables = ["context", "question"], 
                                  template = rag_template)


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


#################################################
# Retrieval Funktion, um KI-Antwort mit vorgegebenen zu vergleichen
# Function to determine if the response is similar to predefined responses
def is_response_similar(response, threshold=0.7):
    if (len(response) < 160): #nur bei sehr kurzen Antworten prüfen, ob eine Art 2ich weiß nicht dabei ist
        # Combine the standard responses with the user's response
        combined_responses = ANTWORT_WEISS_NICHT + [response]
    
        # Convert text to TF-IDF feature vectors
        vectorizer = TfidfVectorizer()
        tfidf_matrix = vectorizer.fit_transform(combined_responses)
    
        # Compute cosine similarity between user's response and standard responses
        cosine_similarities = cosine_similarity(tfidf_matrix[-1], tfidf_matrix[:-1])
    
        # Check if any of the standard responses are similar to the user's response
        if np.max(cosine_similarities) > threshold:
            return True
        return False
    return False


##################################################
#Normalisierung eines Prompts
##################################################
def normalise_prompt (prompt):
    #alles Kleinbuchstaben
    prompt_klein =prompt.lower()
    #Word Tokenisation
    tokens = word_tokenize(prompt_klein)
    #Punktuierung entfernen
    tokens = [word for word in tokens if word.isalnum()]
    # Stop Word Entfernung
    #nltk.download('stopwords')
    #stop_words = set(stopwords.words('english'))
    #tokens = [word for word in tokens if not word in stop_words]
    # 5. Lemmatisierung: Worte in Grundform bringen, um Text besser vergleichen zu können
    #nltk.download('wordnet')
    #lemmatizer = WordNetLemmatizer()
    #tokens = [lemmatizer.lemmatize(word) for word in tokens]
    # 6. Handling Special Characters (Remove non-alphanumeric characters)
    tokens = [re.sub(r'\W+', '', word) for word in tokens]    
    # 7. Spell Check (optional, using a library like pyspellchecker)
    # from spellchecker import SpellChecker
    # spell = SpellChecker()
    # tokens = [spell.correction(word) for word in tokens]
    # Join tokens back to sentence
    normalized_prompt = ' '.join(tokens)
    print("normaiserd prompt..................................")
    print(normalized_prompt)
    return normalized_prompt
    

##################################################
#RAG Hilfsfunktionen - Dokumenten bearbeiten für Vektorstore
##################################################
##################################################
# 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():
    ##############################
    # 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)
    
    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 chroma db vektorisiert ablegen können - die Db vorbereiten daüfur
#zweite Variante, passend zu rag_chain2 für generate_text_mit_bild- ohne llm vorher festlegen zu müssen
def document_retrieval_chroma2(): 
    #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})
    #oder einfach ohne Langchain:
    #embeddings = SentenceTransformerEmbeddings(model_name="all-MiniLM-L6-v2")

    #ChromaDb um die embedings zu speichern
    db = Chroma(embedding_function = embeddings, persist_directory = PATH_WORK + CHROMA_DIR)
    print ("Chroma DB bereit ...................")
    
    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

#nur für HF-um bei chatverlauf kurzbeschreibung zu erzeugen
def llm_chain2(llm, prompt):
    llm_chain = LLMChain(llm = llm, prompt = LLM_CHAIN_PROMPT2)
    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"]

############################################
# rag_chain Alternative für RAg mit Bild-Upload, da hier das llm so nicht genutzt werden kann und der prompt mit den RAG Erweiterungen anders übergeben wird
#langchain nutzen, um prompt an llm zu leiten, aber vorher in der VektorDB suchen, um passende splits zum Prompt hinzuzufügen
#prompt mit RAG!!!
def rag_chain2(prompt, db, k=3):
    rag_template = "Nutze die folgenden Kontext Teile am Ende, um die Frage zu beantworten . " + template + "Frage: " + prompt + "Kontext Teile: "
    retrieved_chunks  = db.similarity_search(prompt, k)

    neu_prompt = rag_template 
    for i, chunk in enumerate(retrieved_chunks):
        neu_prompt += f"{i+1}. {chunk}\n"

    return neu_prompt

###################################################
#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
    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
        
##########################################
#Json für OpenAI Genaeration Chat zusammenstellen
##########################################
##########################################
#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, model_image, oai_key):
    # 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_key}"
            }
    payload = {
      "model": model_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


def process_chatverlauf(prompt, model, oai_key):
    #um die Abfrage nur für den Namen des chats nicht zu lang werden zu lassen, den Prompt begrenzen:
    if (len(prompt)>50):
        prompt = prompt[:50]
    # Prepare the data for the API request (specific to the API you're using)
    headers = {
              "Content-Type": "application/json",
              "Authorization": f"Bearer {oai_key}"
            }
    payload = {
      "model": model,
      "messages": [
        {
          "role": "user",
          "content": [
            {
              "type": "text",
              "text":  'Gib folgendem Text eine Überschrift mit maximal 2 Worten' + prompt
            },
          ]
        }
      ],
      "max_tokens": 100
    }   
    return headers, payload

def process_chatverlauf_hf(history, llm):
    input = generate_prompt_with_history("Gib folgendem Text eine Überschrift mit maximal 3 Worten", history)
    result = llm_chain2(llm, input)
    return result

#######################################################
#Funktionen, um aus der summary des chatverlaufs eine Datei zu machen, die man downloaden kann
def save_and_download(chat_history):
    # Speichere den Chatverlauf in einer temporären Datei
    with NamedTemporaryFile(delete=False, mode="w", suffix=".txt", dir="./temp") as tmp:
        temp_file_path = tmp.name
        tmp.write(chat_history)
    return temp_file_path

def cleanup(file_path):
    if os.path.exists(file_path):
        os.remove(file_path)


########################################################
#Ausgabe im Chatbot aufhübschen...
########################################################
def markdown_to_html_with_syntax_highlight(md_str):
    def replacer(match):
        lang = match.group(1) or "text"
        code = match.group(2)
        lang = lang.strip()
        #print(1,lang)
        if lang=="text":
            lexer = guess_lexer(code)
            lang = lexer.name
            #print(2,lang)
        try:
            lexer = get_lexer_by_name(lang, stripall=True)
        except ValueError:
            lexer = get_lexer_by_name("python", stripall=True)
        formatter = HtmlFormatter()
        #print(3,lexer.name)
        highlighted_code = highlight(code, lexer, formatter)

        return f'<pre><code class="{lang}">{highlighted_code}</code></pre>'

    code_block_pattern = r"```(\w+)?\n([\s\S]+?)\n```"
    md_str = re.sub(code_block_pattern, replacer, md_str, flags=re.MULTILINE)

    html_str = markdown(md_str)
    return html_str


def normalize_markdown(md_text: str) -> str:
    lines = md_text.split("\n")
    normalized_lines = []
    inside_list = False

    for i, line in enumerate(lines):
        if re.match(r"^(\d+\.|-|\*|\+)\s", line.strip()):
            if not inside_list and i > 0 and lines[i - 1].strip() != "":
                normalized_lines.append("")
            inside_list = True
            normalized_lines.append(line)
        elif inside_list and line.strip() == "":
            if i < len(lines) - 1 and not re.match(
                r"^(\d+\.|-|\*|\+)\s", lines[i + 1].strip()
            ):
                normalized_lines.append(line)
            continue
        else:
            inside_list = False
            normalized_lines.append(line)

    return "\n".join(normalized_lines)


def convert_mdtext(md_text):
    code_block_pattern = re.compile(r"```(.*?)(?:```|$)", re.DOTALL)
    inline_code_pattern = re.compile(r"`(.*?)`", re.DOTALL)
    code_blocks = code_block_pattern.findall(md_text)
    non_code_parts = code_block_pattern.split(md_text)[::2]

    result = []
    for non_code, code in zip(non_code_parts, code_blocks + [""]):
        if non_code.strip():
            non_code = normalize_markdown(non_code)
            if inline_code_pattern.search(non_code):
                result.append(markdown(non_code, extensions=["tables"]))
            else:
                result.append(mdtex2html.convert(non_code, extensions=["tables"]))
        if code.strip():
            code = f"\n```{code}\n\n```"
            code = markdown_to_html_with_syntax_highlight(code)
            result.append(code)
    result = "".join(result)
    result += ALREADY_CONVERTED_MARK
    return result

def convert_asis(userinput):
    return f"<p style=\"white-space:pre-wrap;\">{html.escape(userinput)}</p>"+ALREADY_CONVERTED_MARK

def detect_converted_mark(userinput):
    if userinput.endswith(ALREADY_CONVERTED_MARK):
        return True
    else:
        return False



def detect_language(code):
    if code.startswith("\n"):
        first_line = ""
    else:
        first_line = code.strip().split("\n", 1)[0]
    language = first_line.lower() if first_line else ""
    code_without_language = code[len(first_line) :].lstrip() if first_line else code
    return language, code_without_language

def convert_to_markdown(text):
    text = text.replace("$","&#36;")
    def replace_leading_tabs_and_spaces(line):
        new_line = []
        
        for char in line:
            if char == "\t":
                new_line.append("&#9;")
            elif char == " ":
                new_line.append("&nbsp;")
            else:
                break
        return "".join(new_line) + line[len(new_line):]

    markdown_text = ""
    lines = text.split("\n")
    in_code_block = False

    for line in lines:
        if in_code_block is False and line.startswith("```"):
            in_code_block = True
            markdown_text += f"{line}\n"
        elif in_code_block is True and line.startswith("```"):
            in_code_block = False
            markdown_text += f"{line}\n"
        elif in_code_block:
            markdown_text += f"{line}\n"
        else:
            line = replace_leading_tabs_and_spaces(line)
            line = re.sub(r"^(#)", r"\\\1", line)
            markdown_text += f"{line}  \n"

    return markdown_text

def add_language_tag(text):
    def detect_language(code_block):
        try:
            lexer = guess_lexer(code_block)
            return lexer.name.lower()
        except ClassNotFound:
            return ""

    code_block_pattern = re.compile(r"(```)(\w*\n[^`]+```)", re.MULTILINE)

    def replacement(match):
        code_block = match.group(2)
        if match.group(2).startswith("\n"):
            language = detect_language(code_block)
            if language:
                return f"```{language}{code_block}```"
            else:
                return f"```\n{code_block}```"
        else:
            return match.group(1) + code_block + "```"

    text2 = code_block_pattern.sub(replacement, text)
    return text2

def delete_last_conversation(chatbot, history):
    if len(chatbot) > 0:
        chatbot.pop()

    if len(history) > 0:
        history.pop()
        
    return (
        chatbot,
        history,
        "Delete Done",
    )

def reset_state():
    return [], [], "Reset Done"

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

def cancel_outputing():
    return "Stop Done"

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

########################################
#Aus dem File-Pfad nur den Namen herausholen
def get_filename(file_pfad):
    parts = file_pfad.rsplit('/', 1)  # Den String nach dem letzten '/' aufteilen
    if len(parts) == 2:
        result = parts[1]  # Der Teil nach dem letzten '/' ist in parts[1]
    else:
        result = "Ein Fehler im Filenamen ist aufgetreten..."
    return result

########################################
#Open Assistant Funktionen für File upload
########################################
def submit_message(assistant_id, thread, client, user_message):
    client.beta.threads.messages.create(
        thread_id=thread.id, role="user", content=user_message
    )
    return client.beta.threads.runs.create(
        thread_id=thread.id,
        assistant_id=assistant_id,
    )
    
def get_response(thread, client, assi_id):
    return client.beta.threads.messages.list(thread_id=thread.id, order="asc")

def create_thread_and_run(user_input, client, assi_id):
    thread = client.beta.threads.create()
    run = submit_message(assi_id, thread, client, user_input)
    return thread, run

def pretty_print(messages):
    print("# Messages")
    for m in messages:
        print(f"{m.role}: {m.content[0].text.value}")
    print()

# Waiting in a loop
def wait_on_run(run, thread, client):
    while run.status == "queued" or run.status == "in_progress":
        run = client.beta.threads.runs.retrieve(
            thread_id=thread.id,
            run_id=run.id,
        )
        time.sleep(0.5)
    return run

########################################
# Tavility Search Machine
def tavily_search(tavily_client, query):
    search_result = tavily_client.get_search_context(query, search_depth="advanced", max_tokens=8000)
    return search_result

########################################
# nicht in Gebrauch: Assistant für Websuche anlgen
def openai_assistant_suche(client):
    assistant = client.beta.assistants.create(
        instructions=template,
        model="gpt-4-1106-preview",
        tools=[{
            "type": "function",
            "function": {
                "name": "tavily_search",
                "description": "Get information on recent events from the web.",
                "parameters": {
                    "type": "object",
                    "properties": {
                        "query": {"type": "string", "description": "Die Suchanfrage, die die KI nicht beantworten konnte, hier hinein"},
                    },
                    "required": ["query"]
                }
            }
        }]
    )
    return assistant
    

#########################################
#Bildbearbeitung
#########################################
#########################################
#nicht im Einsatz, da Stable Diffusion die Bilder erzeugt
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
    # using requests library to get the image in bytes 
    response2 = requests.get(image_url) 
    # using the Image module from PIL library to view the image 
    image = Image.open(response2.raw)
    return image



###################################################
#zur Zeit nicht im Gebrauch
def transfer_input(inputs):
    textbox = reset_textbox()
    return (
        inputs,
        gr.update(value=""),
        gr.Button.update(visible=True),
    )


#################################################
#Klasse mit zuständen - z.B. für interrupt wenn Stop gedrückt...
#################################################
class State:
    interrupted = False

    def interrupt(self):
        self.interrupted = True

    def recover(self):
        self.interrupted = False
shared_state = State()




def is_stop_word_or_prefix(s: str, stop_words: list) -> bool:
    for stop_word in stop_words:
        if s.endswith(stop_word):
            return True
        for i in range(1, len(stop_word)):
            if s.endswith(stop_word[:i]):
                return True
    return False