alexkueck commited on
Commit
0f199af
1 Parent(s): 24104d7

Create utils.py

Browse files
Files changed (1) hide show
  1. utils.py +29 -724
utils.py CHANGED
@@ -1,118 +1,10 @@
1
- from __future__ import annotations
2
- from typing import TYPE_CHECKING, Any, Callable, Dict, List, Tuple, Type
3
- import logging
4
- import json
5
- import os
6
- from datetime import datetime
7
- import hashlib
8
- import csv
9
- import requests
10
- import re
11
- import html
12
- import markdown2
13
- import torch
14
- import sys
15
- import gc
16
- from pygments.lexers import guess_lexer, ClassNotFound
17
- import time
18
-
19
- import gradio as gr
20
- from pypinyin import lazy_pinyin
21
- import tiktoken
22
- import mdtex2html
23
- from markdown import markdown
24
- from pygments import highlight
25
- from pygments.lexers import guess_lexer,get_lexer_by_name
26
- from pygments.formatters import HtmlFormatter
27
-
28
- from langchain.chains import LLMChain, RetrievalQA
29
- from langchain.chat_models import ChatOpenAI
30
- from langchain.document_loaders import PyPDFLoader, WebBaseLoader, UnstructuredWordDocumentLoader, DirectoryLoader
31
- from langchain.document_loaders.blob_loaders.youtube_audio import YoutubeAudioLoader
32
- from langchain.document_loaders.generic import GenericLoader
33
- from langchain.document_loaders.parsers import OpenAIWhisperParser
34
- from langchain.schema import AIMessage, HumanMessage
35
- from langchain.llms import HuggingFaceHub
36
- from langchain.llms import HuggingFaceTextGenInference
37
- from langchain.embeddings import HuggingFaceInstructEmbeddings, HuggingFaceEmbeddings, HuggingFaceBgeEmbeddings, HuggingFaceInferenceAPIEmbeddings
38
- from langchain.tools import DuckDuckGoSearchRun
39
- from langchain.retrievers.tavily_search_api import TavilySearchAPIRetriever
40
-
41
- from langchain.embeddings.openai import OpenAIEmbeddings
42
- from langchain.prompts import PromptTemplate
43
- from langchain.text_splitter import RecursiveCharacterTextSplitter
44
- from langchain.vectorstores import Chroma
45
- from chromadb.errors import InvalidDimensionException
46
- import io
47
- from PIL import Image, ImageDraw, ImageOps, ImageFont
48
- import base64
49
- from tempfile import NamedTemporaryFile
50
-
51
- import nltk
52
- from nltk.corpus import stopwords
53
- from nltk.tokenize import word_tokenize
54
- from nltk.stem import WordNetLemmatizer
55
- nltk.download('punkt')
56
-
57
- from sklearn.feature_extraction.text import TfidfVectorizer
58
- from sklearn.metrics.pairwise import cosine_similarity
59
- import numpy as np
60
-
61
- from reportlab.lib.pagesizes import inch, A4
62
- from reportlab.platypus import SimpleDocTemplate, Frame, Spacer
63
- from reportlab.lib import colors
64
- from reportlab.lib.units import mm
65
- from reportlab.platypus import Paragraph, SimpleDocTemplate, Frame, Image, Table
66
- from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
67
- from reportlab.lib.units import cm
68
-
69
-
70
- logging.basicConfig(
71
- level=logging.INFO,
72
- format="%(asctime)s [%(levelname)s] [%(filename)s:%(lineno)d] %(message)s",
73
- )
74
-
75
- ################################################
76
- #Beispiel-Antworten, wenn die KI etwas nicht beantworten kann - dann im Netz suchen
77
- ################################################
78
- # Your predefined sentences
79
- 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"]
80
-
81
- #################################################
82
- #Gesetzte Werte für Pfade, Prompts und Keys..
83
- #################################################
84
- #################################################
85
- #Prompt Zusätze
86
- 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.
87
- Versuche nicht es zu umschreiben. Beziehe dich in deinen Antworten ausschließlich auf die hinterkegten Dokumente. Halte die Antwort kurz aber ausführlich genug und exakt."""
88
-
89
- llm_template = "Beantworte die Frage am Ende. " + template + "Frage: {question} "
90
- #nur für HF für Stichwotre bei chatverlauf
91
- llm_template2 = "Fasse folgenden Text als Überschrift mit maximal 3 Worten zusammen. Text: {question} "
92
-
93
- rag_template = "Nutze die folgenden Kontexte (Beginnend mit dem Wort 'Kontext:') aus Teilen aus den angehängten Dokumenten, um die Frage (Beginnend mit dem Wort 'Frage: ') am Ende zu beantworten. Wenn du die Frage aus dem folgenden Kontext nicht beantworten kannst, dann versuche eine Beantwortung aus deinen eigenen trainierten Daten zu finden. Mache das kenntlich, ob du dich auf den hier angehängten Kontext beziehst oder ob du anhand deiner Daten antwortest. Wenn du dich auf den angegebenen Kontext beziehst, gib unbedingt den Namen des Dokumentes an, auf den du dich beziehst." + template + "Kontext: {context} Frage: {question}"
94
-
95
-
96
- #################################################
97
- #Konstanten
98
- LLM_CHAIN_PROMPT = PromptTemplate(input_variables = ["question"],
99
- template = llm_template)
100
- #nur für HF bei chatverlauf
101
- LLM_CHAIN_PROMPT2 = PromptTemplate(input_variables = ["question"],
102
- template = llm_template2)
103
-
104
- RAG_CHAIN_PROMPT = PromptTemplate(input_variables = ["context", "question"],
105
- template = rag_template)
106
-
107
-
108
  ################################################
109
  #Pfad, wo Docs/Bilder/Filme abgelegt werden können - lokal, also hier im HF Space (sonst auf eigenem Rechner)
110
  PATH_WORK = "."
111
- CHROMA_DIR = "/chroma"
112
- #CHROMA_DIR = "/chroma/britta"
113
- CHROMA_PDF = './chroma/pdf'
114
- #CHROMA_PDF = './chroma/britta'
115
- CHROMA_WORD = './chroma/word'
116
  YOUTUBE_DIR = "/youtube"
117
  HISTORY_PFAD = "/data/history"
118
 
@@ -123,28 +15,13 @@ WEB_URL = "https://openai.com/research/gpt-4"
123
  YOUTUBE_URL_1 = "https://www.youtube.com/watch?v=--khbXchTeE"
124
  YOUTUBE_URL_2 = "https://www.youtube.com/watch?v=hdhZwyf24mE"
125
  #YOUTUBE_URL_3 = "https://www.youtube.com/watch?v=vw-KWfKwvTQ"
126
-
127
-
128
- #################################################
129
- # Retrieval Funktion, um KI-Antwort mit vorgegebenen zu vergleichen
130
- # Function to determine if the response is similar to predefined responses
131
- def is_response_similar(response, threshold=0.7):
132
- if (len(response) < 160): #nur bei sehr kurzen Antworten prüfen, ob eine Art 2ich weiß nicht dabei ist
133
- # Combine the standard responses with the user's response
134
- combined_responses = ANTWORT_WEISS_NICHT + [response]
135
-
136
- # Convert text to TF-IDF feature vectors
137
- vectorizer = TfidfVectorizer()
138
- tfidf_matrix = vectorizer.fit_transform(combined_responses)
139
-
140
- # Compute cosine similarity between user's response and standard responses
141
- cosine_similarities = cosine_similarity(tfidf_matrix[-1], tfidf_matrix[:-1])
142
-
143
- # Check if any of the standard responses are similar to the user's response
144
- if np.max(cosine_similarities) > threshold:
145
- return True
146
- return False
147
- return False
148
 
149
 
150
  ##################################################
@@ -157,26 +34,27 @@ def normalise_prompt (prompt):
157
  tokens = word_tokenize(prompt_klein)
158
  #Punktuierung entfernen
159
  tokens = [word for word in tokens if word.isalnum()]
 
160
  # Stop Word Entfernung
161
- #nltk.download('stopwords')
162
- #stop_words = set(stopwords.words('english'))
163
- #tokens = [word for word in tokens if not word in stop_words]
164
  # 5. Lemmatisierung: Worte in Grundform bringen, um Text besser vergleichen zu können
165
- #nltk.download('wordnet')
166
- #lemmatizer = WordNetLemmatizer()
167
- #tokens = [lemmatizer.lemmatize(word) for word in tokens]
168
  # 6. Handling Special Characters (Remove non-alphanumeric characters)
169
  tokens = [re.sub(r'\W+', '', word) for word in tokens]
170
  # 7. Spell Check (optional, using a library like pyspellchecker)
171
- # from spellchecker import SpellChecker
172
- # spell = SpellChecker()
173
- # tokens = [spell.correction(word) for word in tokens]
174
  # Join tokens back to sentence
175
  normalized_prompt = ' '.join(tokens)
176
  print("normaiserd prompt..................................")
177
  print(normalized_prompt)
178
  return normalized_prompt
179
-
180
 
181
  ##################################################
182
  #RAG Hilfsfunktionen - Dokumenten bearbeiten für Vektorstore
@@ -234,15 +112,13 @@ def document_loading_splitting():
234
  ###########################################
235
  #Chroma DB die splits ablegen - vektorisiert...
236
  def document_storage_chroma(splits):
 
 
 
237
  #HF embeddings--------------------------------------
238
- 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)
239
 
240
- #Mongo DB die splits ablegen - vektorisiert...
241
- def document_storage_mongodb(splits):
242
- MongoDBAtlasVectorSearch.from_documents(documents = splits,
243
- embedding = OpenAIEmbeddings(disallowed_special = ()),
244
- collection = MONGODB_COLLECTION,
245
- index_name = MONGODB_INDEX_NAME)
246
  ############################################
247
  #dokumente in chroma db vektorisiert ablegen können - die Db vorbereiten daüfur
248
  def document_retrieval_chroma(llm, prompt):
@@ -256,56 +132,13 @@ def document_retrieval_chroma(llm, prompt):
256
  db = Chroma(embedding_function = embeddings, persist_directory = PATH_WORK + CHROMA_DIR)
257
  return db
258
 
259
- ############################################
260
- #dokumente in chroma db vektorisiert ablegen können - die Db vorbereiten daüfur
261
- #zweite Variante, passend zu rag_chain2 für generate_text_mit_bild- ohne llm vorher festlegen zu müssen
262
- def document_retrieval_chroma2():
263
- #HF embeddings -----------------------------------
264
- #Alternative Embedding - für Vektorstore, um Ähnlichkeitsvektoren zu erzeugen - die ...InstructEmbedding ist sehr rechenaufwendig
265
- embeddings = HuggingFaceInstructEmbeddings(model_name="sentence-transformers/all-MiniLM-L6-v2", model_kwargs={"device": "cpu"})
266
- #etwas weniger rechenaufwendig:
267
- #embeddings = HuggingFaceEmbeddings(model_name="sentence-transformers/all-mpnet-base-v2", model_kwargs={"device": "cpu"}, encode_kwargs={'normalize_embeddings': False})
268
- #oder einfach ohne Langchain:
269
- #embeddings = SentenceTransformerEmbeddings(model_name="all-MiniLM-L6-v2")
270
-
271
- #ChromaDb um die embedings zu speichern
272
- db = Chroma(embedding_function = embeddings, persist_directory = PATH_WORK + CHROMA_DIR)
273
- print ("Chroma DB bereit ...................")
274
-
275
- return db
276
-
277
-
278
- ###############################################
279
- #Langchain anlegen
280
- ###############################################
281
- #langchain nutzen, um prompt an LLM zu leiten - llm und prompt sind austauschbar
282
- def llm_chain(llm, prompt):
283
- llm_chain = LLMChain(llm = llm, prompt = LLM_CHAIN_PROMPT)
284
- result = llm_chain.run({"question": prompt})
285
- return result
286
-
287
- #nur für HF-um bei chatverlauf kurzbeschreibung zu erzeugen
288
- def llm_chain2(llm, prompt):
289
- llm_chain = LLMChain(llm = llm, prompt = LLM_CHAIN_PROMPT2)
290
- result = llm_chain.run({"question": prompt})
291
- return result
292
-
293
- #############################################
294
- #langchain nutzen, um prompt an llm zu leiten, aber vorher in der VektorDB suchen, um passende splits zum Prompt hinzuzufügen
295
- def rag_chain(llm, prompt, db):
296
- rag_chain = RetrievalQA.from_chain_type(llm,
297
- chain_type_kwargs = {"prompt": RAG_CHAIN_PROMPT},
298
- retriever = db.as_retriever(search_kwargs = {"k": 3}),
299
- return_source_documents = True)
300
- result = rag_chain({"query": prompt})
301
- return result["result"]
302
 
303
  ############################################
304
  # 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
305
  #langchain nutzen, um prompt an llm zu leiten, aber vorher in der VektorDB suchen, um passende splits zum Prompt hinzuzufügen
306
  #prompt mit RAG!!!
307
- def rag_chain2(prompt, db, k=3):
308
- rag_template = "Nutze die folgenden Kontext Teile am Ende, um die Frage zu beantworten . " + template + "Frage: " + prompt + "Kontext Teile: "
309
  retrieved_chunks = db.similarity_search(prompt, k)
310
 
311
  neu_prompt = rag_template
@@ -314,544 +147,16 @@ def rag_chain2(prompt, db, k=3):
314
 
315
  return neu_prompt
316
 
317
- ###################################################
318
- #Prompts mit History erzeugen für verschiednee Modelle
319
- ###################################################
320
- #Funktion, die einen Prompt mit der history zusammen erzeugt - allgemein
321
- def generate_prompt_with_history(text, history, max_length=4048):
322
- #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!"
323
- #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!"
324
- prompt=""
325
- history = ["\n{}\n{}".format(x[0],x[1]) for x in history]
326
- history.append("\n{}\n".format(text))
327
- history_text = ""
328
- flag = False
329
- for x in history[::-1]:
330
- history_text = x + history_text
331
- flag = True
332
- if flag:
333
- return prompt+history_text
334
- else:
335
- return None
336
-
337
- ##############################################
338
- #Prompt und History für OPenAi Schnittstelle
339
- def generate_prompt_with_history_openai(prompt, history):
340
- history_openai_format = []
341
- for human, assistant in history:
342
- history_openai_format.append({"role": "user", "content": human })
343
- history_openai_format.append({"role": "assistant", "content":assistant})
344
-
345
- history_openai_format.append({"role": "user", "content": prompt})
346
- print("openai history und prompt................")
347
- print(history_openai_format)
348
- return history_openai_format
349
-
350
- #############################################
351
- #Prompt und History für Hugging Face Schnittstelle
352
- def generate_prompt_with_history_hf(prompt, history):
353
- history_transformer_format = history + [[prompt, ""]]
354
- #stop = StopOnTokens()
355
-
356
- messages = "".join(["".join(["\n<human>:"+item[0], "\n<bot>:"+item[1]]) #curr_system_message +
357
- for item in history_transformer_format])
358
-
359
- ##############################################
360
- #Prompt und History für Langchain Schnittstelle
361
- def generate_prompt_with_history_langchain(prompt, history):
362
- history_langchain_format = []
363
- for human, ai in history:
364
- history_langchain_format.append(HumanMessage(content=human))
365
- history_langchain_format.append(AIMessage(content=ai))
366
- history_langchain_format.append(HumanMessage(content=prompt))
367
-
368
- return history_langchain_format
369
-
370
- ##########################################
371
- #Json für OpenAI Genaeration Chat zusammenstellen
372
- ##########################################
373
- ##########################################
374
- #ein hochgeladenes Bild so vorbereiten, dass OpenAI API es annehmen kann und bearbeiten
375
- #muss ein base64 Bils sein und header und payload entsprechend konfigurieren
376
- def process_image(image_path, prompt, model_image, oai_key):
377
- # Convert image to base64
378
- with open(image_path, "rb") as image_file:
379
- encoded_string = base64.b64encode(image_file.read()).decode('utf-8')
380
-
381
- # Prepare the data for the API request (specific to the API you're using)
382
- headers = {
383
- "Content-Type": "application/json",
384
- "Authorization": f"Bearer {oai_key}"
385
- }
386
- payload = {
387
- "model": model_image,
388
- "messages": [
389
- {
390
- "role": "user",
391
- "content": [
392
- {
393
- "type": "text",
394
- "text": llm_template + prompt
395
- },
396
- {
397
- "type": "image_url",
398
- "image_url": {
399
- "url": f"data:image/jpeg;base64,{encoded_string}"
400
- }
401
- }
402
- ]
403
- }
404
- ],
405
- "max_tokens": 300
406
- }
407
- return headers, payload
408
-
409
-
410
- def process_chatverlauf(prompt, model, oai_key):
411
- #um die Abfrage nur für den Namen des chats nicht zu lang werden zu lassen, den Prompt begrenzen:
412
- if (len(prompt)>50):
413
- prompt = prompt[:50]
414
- # Prepare the data for the API request (specific to the API you're using)
415
- headers = {
416
- "Content-Type": "application/json",
417
- "Authorization": f"Bearer {oai_key}"
418
- }
419
- payload = {
420
- "model": model,
421
- "messages": [
422
- {
423
- "role": "user",
424
- "content": [
425
- {
426
- "type": "text",
427
- "text": 'Gib folgendem Text eine Überschrift mit maximal 2 Worten' + prompt
428
- },
429
- ]
430
- }
431
- ],
432
- "max_tokens": 100
433
- }
434
- return headers, payload
435
-
436
- def process_chatverlauf_hf(history, llm):
437
- input = generate_prompt_with_history("Gib folgendem Text eine Überschrift mit maximal 3 Worten", history)
438
- result = llm_chain2(llm, input)
439
- return result
440
-
441
- #######################################################
442
- #Funktionen, um aus der summary des chatverlaufs eine Datei zu machen, die man downloaden kann
443
- def save_and_download(chat_history):
444
- # Speichere den Chatverlauf in einer temporären Datei
445
- with NamedTemporaryFile(delete=False, mode="w", suffix=".txt", dir="./temp") as tmp:
446
- temp_file_path = tmp.name
447
- tmp.write(chat_history)
448
- return temp_file_path
449
 
450
- def cleanup(file_path):
451
- if os.path.exists(file_path):
452
- os.remove(file_path)
453
 
454
 
455
- ########################################################
456
- #Ausgabe im Chatbot aufhübschen...
457
- ########################################################
458
- def markdown_to_html_with_syntax_highlight(md_str):
459
- def replacer(match):
460
- lang = match.group(1) or "text"
461
- code = match.group(2)
462
- lang = lang.strip()
463
- #print(1,lang)
464
- if lang=="text":
465
- lexer = guess_lexer(code)
466
- lang = lexer.name
467
- #print(2,lang)
468
- try:
469
- lexer = get_lexer_by_name(lang, stripall=True)
470
- except ValueError:
471
- lexer = get_lexer_by_name("python", stripall=True)
472
- formatter = HtmlFormatter()
473
- #print(3,lexer.name)
474
- highlighted_code = highlight(code, lexer, formatter)
475
-
476
- return f'<pre><code class="{lang}">{highlighted_code}</code></pre>'
477
-
478
- code_block_pattern = r"```(\w+)?\n([\s\S]+?)\n```"
479
- md_str = re.sub(code_block_pattern, replacer, md_str, flags=re.MULTILINE)
480
-
481
- html_str = markdown(md_str)
482
- return html_str
483
-
484
-
485
- def normalize_markdown(md_text: str) -> str:
486
- lines = md_text.split("\n")
487
- normalized_lines = []
488
- inside_list = False
489
-
490
- for i, line in enumerate(lines):
491
- if re.match(r"^(\d+\.|-|\*|\+)\s", line.strip()):
492
- if not inside_list and i > 0 and lines[i - 1].strip() != "":
493
- normalized_lines.append("")
494
- inside_list = True
495
- normalized_lines.append(line)
496
- elif inside_list and line.strip() == "":
497
- if i < len(lines) - 1 and not re.match(
498
- r"^(\d+\.|-|\*|\+)\s", lines[i + 1].strip()
499
- ):
500
- normalized_lines.append(line)
501
- continue
502
- else:
503
- inside_list = False
504
- normalized_lines.append(line)
505
-
506
- return "\n".join(normalized_lines)
507
-
508
-
509
- def convert_mdtext(md_text):
510
- code_block_pattern = re.compile(r"```(.*?)(?:```|$)", re.DOTALL)
511
- inline_code_pattern = re.compile(r"`(.*?)`", re.DOTALL)
512
- code_blocks = code_block_pattern.findall(md_text)
513
- non_code_parts = code_block_pattern.split(md_text)[::2]
514
-
515
- result = []
516
- for non_code, code in zip(non_code_parts, code_blocks + [""]):
517
- if non_code.strip():
518
- non_code = normalize_markdown(non_code)
519
- if inline_code_pattern.search(non_code):
520
- result.append(markdown(non_code, extensions=["tables"]))
521
- else:
522
- result.append(mdtex2html.convert(non_code, extensions=["tables"]))
523
- if code.strip():
524
- code = f"\n```{code}\n\n```"
525
- code = markdown_to_html_with_syntax_highlight(code)
526
- result.append(code)
527
- result = "".join(result)
528
- result += ALREADY_CONVERTED_MARK
529
- return result
530
-
531
- def convert_asis(userinput):
532
- return f"<p style=\"white-space:pre-wrap;\">{html.escape(userinput)}</p>"+ALREADY_CONVERTED_MARK
533
-
534
- def detect_converted_mark(userinput):
535
- if userinput.endswith(ALREADY_CONVERTED_MARK):
536
- return True
537
- else:
538
- return False
539
-
540
-
541
-
542
- def detect_language(code):
543
- if code.startswith("\n"):
544
- first_line = ""
545
- else:
546
- first_line = code.strip().split("\n", 1)[0]
547
- language = first_line.lower() if first_line else ""
548
- code_without_language = code[len(first_line) :].lstrip() if first_line else code
549
- return language, code_without_language
550
-
551
- def convert_to_markdown(text):
552
- text = text.replace("$","&#36;")
553
- def replace_leading_tabs_and_spaces(line):
554
- new_line = []
555
-
556
- for char in line:
557
- if char == "\t":
558
- new_line.append("&#9;")
559
- elif char == " ":
560
- new_line.append("&nbsp;")
561
- else:
562
- break
563
- return "".join(new_line) + line[len(new_line):]
564
-
565
- markdown_text = ""
566
- lines = text.split("\n")
567
- in_code_block = False
568
-
569
- for line in lines:
570
- if in_code_block is False and line.startswith("```"):
571
- in_code_block = True
572
- markdown_text += f"{line}\n"
573
- elif in_code_block is True and line.startswith("```"):
574
- in_code_block = False
575
- markdown_text += f"{line}\n"
576
- elif in_code_block:
577
- markdown_text += f"{line}\n"
578
- else:
579
- line = replace_leading_tabs_and_spaces(line)
580
- line = re.sub(r"^(#)", r"\\\1", line)
581
- markdown_text += f"{line} \n"
582
-
583
- return markdown_text
584
-
585
- def add_language_tag(text):
586
- def detect_language(code_block):
587
- try:
588
- lexer = guess_lexer(code_block)
589
- return lexer.name.lower()
590
- except ClassNotFound:
591
- return ""
592
-
593
- code_block_pattern = re.compile(r"(```)(\w*\n[^`]+```)", re.MULTILINE)
594
-
595
- def replacement(match):
596
- code_block = match.group(2)
597
- if match.group(2).startswith("\n"):
598
- language = detect_language(code_block)
599
- if language:
600
- return f"```{language}{code_block}```"
601
- else:
602
- return f"```\n{code_block}```"
603
- else:
604
- return match.group(1) + code_block + "```"
605
-
606
- text2 = code_block_pattern.sub(replacement, text)
607
- return text2
608
-
609
- def delete_last_conversation(chatbot, history):
610
- if len(chatbot) > 0:
611
- chatbot.pop()
612
-
613
- if len(history) > 0:
614
- history.pop()
615
-
616
- return (
617
- chatbot,
618
- history,
619
- "Delete Done",
620
- )
621
-
622
- def reset_state():
623
- return [], [], "Reset Done"
624
-
625
- def reset_textbox():
626
- return gr.update(value=""),""
627
-
628
- def cancel_outputing():
629
- return "Stop Done"
630
-
631
-
632
- ##########################################
633
- #Extension des hochgeladenen Files bestimmen
634
- def analyze_file(file):
635
- file_extension = file.name.split('.')[-1] # Holen Sie sich die Dateiendung
636
- return file_extension
637
-
638
- ########################################
639
- #Aus dem File-Pfad nur den Namen herausholen
640
- def get_filename(file_pfad):
641
- parts = file_pfad.rsplit('/', 1) # Den String nach dem letzten '/' aufteilen
642
- if len(parts) == 2:
643
- result = parts[1] # Der Teil nach dem letzten '/' ist in parts[1]
644
- else:
645
- result = "Ein Fehler im Filenamen ist aufgetreten..."
646
- return result
647
-
648
- ########################################
649
- #Open Assistant Funktionen für File upload
650
- ########################################
651
- def submit_message(assistant_id, thread, client, user_message):
652
- client.beta.threads.messages.create(
653
- thread_id=thread.id, role="user", content=user_message
654
- )
655
- return client.beta.threads.runs.create(
656
- thread_id=thread.id,
657
- assistant_id=assistant_id,
658
- )
659
-
660
- def get_response(thread, client, assi_id):
661
- return client.beta.threads.messages.list(thread_id=thread.id, order="asc")
662
-
663
- def create_thread_and_run(user_input, client, assi_id):
664
- thread = client.beta.threads.create()
665
- run = submit_message(assi_id, thread, client, user_input)
666
- return thread, run
667
-
668
- def pretty_print(messages):
669
- print("# Messages")
670
- for m in messages:
671
- print(f"{m.role}: {m.content[0].text.value}")
672
- print()
673
-
674
- # Waiting in a loop
675
- def wait_on_run(run, thread, client):
676
- while run.status == "queued" or run.status == "in_progress":
677
- run = client.beta.threads.runs.retrieve(
678
- thread_id=thread.id,
679
- run_id=run.id,
680
- )
681
- time.sleep(0.5)
682
- return run
683
-
684
- ########################################
685
- # Tavility Search Machine
686
- def tavily_search(tavily_client, query):
687
- search_result = tavily_client.get_search_context(query, search_depth="advanced", max_tokens=8000)
688
- return search_result
689
-
690
- ########################################
691
- # nicht in Gebrauch: Assistant für Websuche anlgen
692
- def openai_assistant_suche(client):
693
- assistant = client.beta.assistants.create(
694
- instructions=template,
695
- model="gpt-4-1106-preview",
696
- tools=[{
697
- "type": "function",
698
- "function": {
699
- "name": "tavily_search",
700
- "description": "Get information on recent events from the web.",
701
- "parameters": {
702
- "type": "object",
703
- "properties": {
704
- "query": {"type": "string", "description": "Die Suchanfrage, die die KI nicht beantworten konnte, hier hinein"},
705
- },
706
- "required": ["query"]
707
- }
708
- }
709
- }]
710
- )
711
- return assistant
712
-
713
-
714
- #########################################
715
- #Bildbearbeitung
716
- #########################################
717
- #########################################
718
- #nicht im Einsatz, da Stable Diffusion die Bilder erzeugt
719
- def create_picture(history, prompt):
720
- client = OpenAI()
721
- response = client.images.generate(model="dall-e-3", prompt=prompt,size="1024x1024",quality="standard",n=1,)
722
- image_url = response.data[0].url
723
- # using requests library to get the image in bytes
724
- response2 = requests.get(image_url)
725
- # using the Image module from PIL library to view the image
726
- image = Image.open(response2.raw)
727
- return image
728
-
729
-
730
- ########################################
731
- # Ausgabe in PDF des Chathistory
732
- ########################################
733
- #callback Methode, die auf jeder PDF Seite das Datum oben hinschreibt
734
- def on_each_page(canvas, doc):
735
- page_width, page_height = A4 # Oder das von Ihnen verwendete Seitenformat, z.B. A4
736
- canvas.saveState()
737
- canvas.setFont('Times-Roman', 10)
738
- # Formatieren Sie das Datum nach Ihrem Wunsch
739
- current_date = datetime.now().strftime("%Y-%m-%d")
740
- print(current_date)
741
- # Positionieren Sie das Datum oben rechts auf der Seite
742
- canvas.drawRightString(page_width - 72, page_height - 28, current_date)
743
- canvas.restoreState()
744
-
745
- #PDF Inhalte zusammenstellen und PDF unter dem angegebene Pfad file_path_download ablegen
746
- def erstellePdf(file_path_download, ueberschrift, dic_history):
747
- # Initialisiere eine leere Listseinstellung ("flowables"), die später gefüllt wird
748
- elements = []
749
- # Definiere ein neues Papierformat mit A4 Maßen
750
- paper_size = A4
751
-
752
- # Erstellen Sie ein neues StyleSheet-Objekt
753
- styles = getSampleStyleSheet()
754
- # Neuen Style hinzufügen
755
- new_style = ParagraphStyle('NewStyle', fontName='Helvetica', fontSize=12)
756
- styles.add(new_style)
757
- #style für Trennlinie
758
- line_style = ParagraphStyle('LineStyle', fontSize=4, leading=6, borderPadding=0,
759
- spaceBefore=0, spaceAfter=0, textColor='black')
760
- #Feststehende Überschriften erzeugen
761
- # Chat-Überschrift
762
- title = Paragraph(ueberschrift, styles['Title'])
763
- headline_nutzer = Paragraph('Nutzer:', styles['Heading3'])
764
- headline_assi = Paragraph('Assistent:', styles['Heading3'])
765
-
766
- #Pdf Abschnittsweise zusammenstellen
767
- elements.append(title)
768
- for nutzer, assi in dic_history.items():
769
- elements.append(headline_nutzer)
770
- p = Paragraph(nutzer, styles['NewStyle'])
771
- elements.append(p)
772
- # Einen Abstand hinzufügen (optional)
773
- elements.append(Spacer(1, 2*mm))
774
- elements.append(headline_assi)
775
- p = Paragraph(assi, styles['NewStyle'])
776
- elements.append(p)
777
- # Einen Abstand hinzufügen (optional)
778
- elements.append(Spacer(1, 8*mm))
779
- #Trennlinie
780
- elements.append(Paragraph('_' * 100, line_style))
781
- # Einen Abstand hinzufügen (optional)
782
- elements.append(Spacer(1, 8*mm))
783
-
784
- #Für später, um bilder einzufügen
785
- # Fügen Sie andere Flowables wie Bilder oder Tabellen hinzu
786
- #image = Image('path/to/your/image.png', width=10*cm, height=5*cm)
787
- #elements.append(image)
788
- #table = Table([['Cell 1', 'Cell 2'], ['Cell 3', 'Cell 4']])
789
- #elements.append(table)
790
-
791
-
792
- # Generiere das PDF-Dokument
793
- doc = CustomDocTemplate(file_path_download, pagesize=paper_size)
794
- #on_each_page ist eine callback Methode, die auf jeder neuen PDF Seite ausgeführt wird
795
- doc.onPage = on_each_page
796
- doc.build(elements)
797
-
798
- ##########################################
799
- #Hashing....
800
- # Funktion zum Hashen des Eingabewerts
801
- def hash_input(input_string):
802
- return hashlib.sha256(input_string.encode()).hexdigest()
803
-
804
-
805
- ###################################################
806
- #zur Zeit nicht im Gebrauch
807
- def transfer_input(inputs):
808
- textbox = reset_textbox()
809
- return (
810
- inputs,
811
- gr.update(value=""),
812
- gr.Button.update(visible=True),
813
- )
814
-
815
 
816
- #################################################
817
- #Klasse mit zuständen - z.B. für interrupt wenn Stop gedrückt...
818
- #################################################
819
- class State:
820
- interrupted = False
821
 
822
- def interrupt(self):
823
- self.interrupted = True
824
 
825
- def recover(self):
826
- self.interrupted = False
827
- shared_state = State()
828
 
829
 
830
 
831
 
832
- def is_stop_word_or_prefix(s: str, stop_words: list) -> bool:
833
- for stop_word in stop_words:
834
- if s.endswith(stop_word):
835
- return True
836
- for i in range(1, len(stop_word)):
837
- if s.endswith(stop_word[:i]):
838
- return True
839
- return False
840
 
841
- ##########################################
842
- # Klasse, die die SimpleDocTemplate überschreibt (für PDF Generierung)
843
- # war nötig, da SimpleDocTemplate die on_each_page nicht ausgeführt hat - warum auch immer ...
844
- ##########################################
845
- class CustomDocTemplate(SimpleDocTemplate):
846
- def handle_pageBegin(self):
847
- # Sorgt dafür, dass die Standard-Page-Begin-Logik ausgeführt wird
848
- self._handle_pageBegin()
849
- # Jetzt können Sie das Canvas-Objekt über self.canv sicher verwenden
850
- self.canv.saveState()
851
- self.canv.setFont('Helvetica', 10)
852
- current_date = datetime.now().strftime("%Y-%m-%d")
853
- # Passen Sie hier die Positionierung an Ihre Bedürfnisse an
854
- self.canv.drawRightString(550, 800, current_date) # Position anpassen
855
- self.canv.restoreState()
856
 
857
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  ################################################
2
  #Pfad, wo Docs/Bilder/Filme abgelegt werden können - lokal, also hier im HF Space (sonst auf eigenem Rechner)
3
  PATH_WORK = "."
4
+ CHROMA_DIR = "/chroma/kkg"
5
+ CHROMA_PDF = './chroma/kkg/pdf'
6
+ CHROMA_WORD = './chroma/kkg/word'
7
+ CHROMA_EXCEL = './chroma/kkg/excel'
 
8
  YOUTUBE_DIR = "/youtube"
9
  HISTORY_PFAD = "/data/history"
10
 
 
15
  YOUTUBE_URL_1 = "https://www.youtube.com/watch?v=--khbXchTeE"
16
  YOUTUBE_URL_2 = "https://www.youtube.com/watch?v=hdhZwyf24mE"
17
  #YOUTUBE_URL_3 = "https://www.youtube.com/watch?v=vw-KWfKwvTQ"
18
+ #spezielle Webseiten als Datenbasis laden
19
+ urls = [
20
+ "https://kkg.hamburg.de/unser-leitbild/"
21
+ "https://kkg.hamburg.de/unsere-schulcharta/",
22
+ "https://kkg.hamburg.de/koordination-unterrichtsentwicklung/",
23
+ "https://kkg.hamburg.de/konzept-medien-und-it-am-kkg/",
24
+ ]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
25
 
26
 
27
  ##################################################
 
34
  tokens = word_tokenize(prompt_klein)
35
  #Punktuierung entfernen
36
  tokens = [word for word in tokens if word.isalnum()]
37
+
38
  # Stop Word Entfernung
39
+ nltk.download('stopwords')
40
+ stop_words = set(stopwords.words('deutsch'))
41
+ tokens = [word for word in tokens if not word in stop_words]
42
  # 5. Lemmatisierung: Worte in Grundform bringen, um Text besser vergleichen zu können
43
+ nltk.download('wordnet')
44
+ lemmatizer = WordNetLemmatizer()
45
+ tokens = [lemmatizer.lemmatize(word) for word in tokens]
46
  # 6. Handling Special Characters (Remove non-alphanumeric characters)
47
  tokens = [re.sub(r'\W+', '', word) for word in tokens]
48
  # 7. Spell Check (optional, using a library like pyspellchecker)
49
+ from spellchecker import SpellChecker
50
+ spell = SpellChecker()
51
+ tokens = [spell.correction(word) for word in tokens]
52
  # Join tokens back to sentence
53
  normalized_prompt = ' '.join(tokens)
54
  print("normaiserd prompt..................................")
55
  print(normalized_prompt)
56
  return normalized_prompt
57
+
58
 
59
  ##################################################
60
  #RAG Hilfsfunktionen - Dokumenten bearbeiten für Vektorstore
 
112
  ###########################################
113
  #Chroma DB die splits ablegen - vektorisiert...
114
  def document_storage_chroma(splits):
115
+ #OpenAi embeddings----------------------------------
116
+ Chroma.from_documents(documents = splits, embedding = OpenAIEmbeddings(disallowed_special = ()), persist_directory = PATH_WORK + CHROMA_DIR)
117
+
118
  #HF embeddings--------------------------------------
119
+ #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)
120
 
121
+
 
 
 
 
 
122
  ############################################
123
  #dokumente in chroma db vektorisiert ablegen können - die Db vorbereiten daüfur
124
  def document_retrieval_chroma(llm, prompt):
 
132
  db = Chroma(embedding_function = embeddings, persist_directory = PATH_WORK + CHROMA_DIR)
133
  return db
134
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
135
 
136
  ############################################
137
  # 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
138
  #langchain nutzen, um prompt an llm zu leiten, aber vorher in der VektorDB suchen, um passende splits zum Prompt hinzuzufügen
139
  #prompt mit RAG!!!
140
+ def rag_chain(prompt, db, k=3):
141
+ rag_template = "Nutze ausschließlich die folgenden Kontext Teile am Ende, um die Frage zu beantworten . " + template + "Frage: " + prompt + "Kontext Teile: "
142
  retrieved_chunks = db.similarity_search(prompt, k)
143
 
144
  neu_prompt = rag_template
 
147
 
148
  return neu_prompt
149
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
150
 
 
 
 
151
 
152
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
153
 
 
 
 
 
 
154
 
 
 
155
 
 
 
 
156
 
157
 
158
 
159
 
 
 
 
 
 
 
 
 
160
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
161
 
162