Spaces:
Sleeping
Sleeping
Update chunking
Browse files
run.py
CHANGED
|
@@ -2,7 +2,7 @@
|
|
| 2 |
# Title: Gradio Interface to LLM-chatbot with dynamic RAG-funcionality and ChromaDB
|
| 3 |
# Author: Andreas Fischer
|
| 4 |
# Date: October 10th, 2024
|
| 5 |
-
# Last update: October
|
| 6 |
##########################################################################################
|
| 7 |
|
| 8 |
import os
|
|
@@ -82,8 +82,8 @@ def format_prompt0(message, history):
|
|
| 82 |
|
| 83 |
def format_prompt(message, history, system=None, RAGAddon=None, system2=None, zeichenlimit=None,historylimit=4, removeHTML=False):
|
| 84 |
if zeichenlimit is None: zeichenlimit=1000000000 # :-)
|
| 85 |
-
startOfString="<s>"
|
| 86 |
-
template0=" [INST] {system} [/INST]</s>"
|
| 87 |
template1=" [INST] {message} [/INST]"
|
| 88 |
template2=" {response}</s>"
|
| 89 |
prompt = ""
|
|
@@ -155,13 +155,58 @@ def convertPDF(pdf_file, allow_ocr=False):
|
|
| 155 |
# Function for splitting text with overlap
|
| 156 |
#------------------------------------------
|
| 157 |
|
| 158 |
-
def
|
| 159 |
-
chunks
|
| 160 |
-
|
| 161 |
-
|
| 162 |
-
|
| 163 |
-
|
| 164 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 165 |
|
| 166 |
|
| 167 |
#---------------------------------------------------------------
|
|
@@ -169,16 +214,22 @@ def split_with_overlap(text,chunk_size=3500, overlap=700):
|
|
| 169 |
#---------------------------------------------------------------
|
| 170 |
|
| 171 |
def add_doc(path, session):
|
|
|
|
| 172 |
print("def add_doc!")
|
| 173 |
print(path)
|
| 174 |
anhang=False
|
| 175 |
if(str.lower(path).endswith(".pdf") and os.path.exists(path)):
|
| 176 |
doc=convertPDF(path)
|
| 177 |
-
if(len(doc[0])>5):
|
| 178 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 179 |
else:
|
| 180 |
-
|
| 181 |
-
|
| 182 |
anhang=True
|
| 183 |
else:
|
| 184 |
gr.Info("No PDF attached - answer based on DB_"+str(session)+".")
|
|
@@ -196,29 +247,28 @@ def add_doc(path, session):
|
|
| 196 |
collection = client.get_collection(
|
| 197 |
name=dbName, embedding_function=embeddingModel)
|
| 198 |
if(anhang==True):
|
| 199 |
-
corpus=split_with_overlap(doc,3500,700)
|
| 200 |
-
print(len(corpus))
|
|
|
|
| 201 |
then = datetime.now()
|
| 202 |
x=collection.get(include=[])["ids"]
|
| 203 |
print(len(x))
|
| 204 |
if(len(x)==0):
|
| 205 |
chunkSize=40000
|
| 206 |
-
for i in range(round(len(corpus)/chunkSize+0.5)):
|
| 207 |
print("embed batch "+str(i)+" of "+str(round(len(corpus)/chunkSize+0.5)))
|
| 208 |
ids=list(range(i*chunkSize,(i*chunkSize+chunkSize)))
|
| 209 |
batch=corpus[i*chunkSize:(i*chunkSize+chunkSize)]
|
| 210 |
textIDs=[str(id) for id in ids[0:len(batch)]]
|
| 211 |
ids=[str(id+len(x)+1) for id in ids[0:len(batch)]] # id refers to chromadb-unique ID
|
| 212 |
collection.add(documents=batch, ids=ids,
|
| 213 |
-
metadatas=[{"date": str("2024-10-10")} for b in batch])
|
| 214 |
print("finished batch "+str(i)+" of "+str(round(len(corpus)/40000+0.5)))
|
| 215 |
now = datetime.now()
|
| 216 |
gr.Info(f"Indexing complete!")
|
| 217 |
-
print(now-then)
|
| 218 |
return(collection)
|
| 219 |
|
| 220 |
-
#split_with_overlap("test me if you can",2,1)
|
| 221 |
-
|
| 222 |
|
| 223 |
#--------------------------------------------------------
|
| 224 |
# Function for response to user queries and pot. addenda
|
|
@@ -249,7 +299,7 @@ def multimodal_response(message, history, dropdown, hfToken, request: gr.Request
|
|
| 249 |
print(str(client.list_collections()))
|
| 250 |
x=collection.get(include=[])["ids"]
|
| 251 |
context=collection.query(query_texts=[query], n_results=1)
|
| 252 |
-
context=["<
|
| 253 |
gr.Info("Kontext:\n"+str(context))
|
| 254 |
generate_kwargs = dict(
|
| 255 |
temperature=float(0.9),
|
|
@@ -305,3 +355,4 @@ i=gr.ChatInterface(multimodal_response,
|
|
| 305 |
])
|
| 306 |
i.launch() #allowed_paths=["."])
|
| 307 |
|
|
|
|
|
|
| 2 |
# Title: Gradio Interface to LLM-chatbot with dynamic RAG-funcionality and ChromaDB
|
| 3 |
# Author: Andreas Fischer
|
| 4 |
# Date: October 10th, 2024
|
| 5 |
+
# Last update: October 22th, 2024
|
| 6 |
##########################################################################################
|
| 7 |
|
| 8 |
import os
|
|
|
|
| 82 |
|
| 83 |
def format_prompt(message, history, system=None, RAGAddon=None, system2=None, zeichenlimit=None,historylimit=4, removeHTML=False):
|
| 84 |
if zeichenlimit is None: zeichenlimit=1000000000 # :-)
|
| 85 |
+
startOfString="<s>"
|
| 86 |
+
template0=" [INST] {system} [/INST] </s>" #" [INST] {system} [/INST] </s>" vs " [INST]{system}\n [/INST] </s>"
|
| 87 |
template1=" [INST] {message} [/INST]"
|
| 88 |
template2=" {response}</s>"
|
| 89 |
prompt = ""
|
|
|
|
| 155 |
# Function for splitting text with overlap
|
| 156 |
#------------------------------------------
|
| 157 |
|
| 158 |
+
def split_with_overlap0(text,chunk_size=3500, overlap=700):
|
| 159 |
+
""" Split text in chunks based on number of characters (chunk_size) with chunks overlapping (overlap)"""
|
| 160 |
+
chunks=[]
|
| 161 |
+
step=max(1,chunk_size-overlap)
|
| 162 |
+
for i in range(0,len(text),step):
|
| 163 |
+
end=min(i+chunk_size,len(text))
|
| 164 |
+
chunks.append(text[i:end])
|
| 165 |
+
return chunks
|
| 166 |
+
|
| 167 |
+
import re
|
| 168 |
+
def split_with_overlap(text, chunk_size=3500, overlap=700, pattern=r'([.!;?][ \n\r]|[\n\r]{2,})', variant=1, verbose=False):
|
| 169 |
+
""" Split text in chunks based on regex (pattern) matches. By default the pattern is '([.!;?][ \\n\\r]|[\\n\\r]{2,})' Chunks are no longer than a certain number of characters (chunk_size) with chunks overlapping (overlap).
|
| 170 |
+
By default (variant=1) chunking is based on complete sentences, but it's also possible to split only within the left overlap region and within the rest of the chunk-size (variant==2) or strictly within both overlap-regions (variant=3).
|
| 171 |
+
"""
|
| 172 |
+
chunks = []
|
| 173 |
+
overlap=min(overlap,chunk_size) # Overlap kann nicht größer sein als chunk_size
|
| 174 |
+
step = max(1, chunk_size - overlap) # step richtet sich nach chunk_size und overlap
|
| 175 |
+
def find_pattern(text): # Funktion zur Suche nach dem Muster
|
| 176 |
+
return re.search(pattern, text)
|
| 177 |
+
i, lastEnd = 0,0
|
| 178 |
+
while i<len(text):
|
| 179 |
+
print("i="+str(i))
|
| 180 |
+
end = min(i + chunk_size, len(text))
|
| 181 |
+
pattern_match = find_pattern(text[i:end]) # erstes Vorkommnis (if any)
|
| 182 |
+
matchesStart = [x.start() for x in re.finditer(pattern, text[i:end])] # start aller matches
|
| 183 |
+
matchesEnd = [x.start() for x in re.finditer(pattern, text[i:end])] # end aller matches
|
| 184 |
+
step = max(1, chunk_size - overlap) # Normalerweise beträgt ein Step chunk_size - overlap
|
| 185 |
+
if pattern_match: # Wenn (mindestens) ein Satzzeichen gefunden wurde
|
| 186 |
+
for s in matchesStart: # gehe jedes Satzzeichen durch
|
| 187 |
+
if ((variant<=2 and s>=overlap) or (variant==3 and s>=overlap and s>(chunk_size-overlap))): # wenn das Satzzeichen nicht im Overlap links liegt (1) oder zusätzlich im reechten Overlap liegt (2) - wobei letzteres unvollständige Sätze bedeuten kann
|
| 188 |
+
end=s+i+1 # Setze end auf den Start des Patterns/Satzzeichens im gesamten Text
|
| 189 |
+
if(verbose==True): print("***move end:"+str(end)+"; step="+str(step))
|
| 190 |
+
if(s<(chunk_size-overlap)):step=min(step,max(1,s-overlap)) # Springe mit step höchstens zum Ende des Satzzeichens (nur erforderlich, wenn end nicht im Overlap)
|
| 191 |
+
if ((variant==1 and i>0) or (variant>=2 and pattern_match.start()<overlap and i>0)): # wenn das erste Satzzeichen im Overlap liegt
|
| 192 |
+
i=i+pattern_match.start()+1 # Verzichte auf Textteile vor dem ersten Satzzeichen
|
| 193 |
+
if(verbose==True): print("i="+str(i)+"; end="+str(end)+"; step="+str(step)+"; len="+str(len(text))+"; match="+str(pattern_match)+"; text="+text[i:end]+"; rest="+text[end:])
|
| 194 |
+
if(end>lastEnd): # wenn das Ende sich verschoben hat (und nicht nur den Satzbeginn zu einem bereits bekannten Satz abschneidet)
|
| 195 |
+
chunks.append(text[i:end])
|
| 196 |
+
lastEnd=end
|
| 197 |
+
if(verbose==True): print("Text at position "+str(i)+": "+text[i:end])
|
| 198 |
+
i += step
|
| 199 |
+
if(len(text[end:])>0): chunks.append(text[end:]) # Ergänze am ende etwaigen Rest
|
| 200 |
+
return chunks
|
| 201 |
+
|
| 202 |
+
fiveChars= "(?<![ \n\(]bspw|[ \n]inkl)"
|
| 203 |
+
fourChars= "(?<![ \n\(]sog|[ \n]Mio|[ \n]Mrd|[ \n]Tsd|[ \n]Tel)"
|
| 204 |
+
threeChars= "(?<!www|bzw|etc|ggf|[ \n\(]al|[ \n\(]St|[ \n\(]dh|[ \n\(]va|[ \n\(]ca|[ \n\(]Dr|[ \n\(]Hr|[ \n\(]Fr|[0-9]ff)"
|
| 205 |
+
twoChars= "(?<![ \n\(][A-Za-zΆ-Ωά-ωäöüß])"
|
| 206 |
+
oneChars= "(?<![0-9.])"
|
| 207 |
+
sentenceRegex="(?<=[^.]{4})"+fiveChars+fourChars+threeChars+twoChars+oneChars+"[.?!](?![A-Za-zΆ-Ωά-ωäöüß0-9.!?'\"])"
|
| 208 |
+
sectionRegex="\n[ ]*\n[\n ]*"
|
| 209 |
+
splitRegex="("+sentenceRegex+"|"+sectionRegex+")"
|
| 210 |
|
| 211 |
|
| 212 |
#---------------------------------------------------------------
|
|
|
|
| 214 |
#---------------------------------------------------------------
|
| 215 |
|
| 216 |
def add_doc(path, session):
|
| 217 |
+
global device
|
| 218 |
print("def add_doc!")
|
| 219 |
print(path)
|
| 220 |
anhang=False
|
| 221 |
if(str.lower(path).endswith(".pdf") and os.path.exists(path)):
|
| 222 |
doc=convertPDF(path)
|
| 223 |
+
if(len(doc[0])>5):
|
| 224 |
+
if(not "cuda" in device):
|
| 225 |
+
doc="\n\n".join(doc[0][0:5])
|
| 226 |
+
gr.Info("PDF uploaded to DB_"+str(session)+", start Indexing excerpt (first 5 pages on CPU setups)!")
|
| 227 |
+
else:
|
| 228 |
+
doc="\n\n".join(doc[0])
|
| 229 |
+
gr.Info("PDF uploaded to DB_"+str(session)+", start Indexing!")
|
| 230 |
else:
|
| 231 |
+
doc="\n\n".join(doc[0])
|
| 232 |
+
gr.Info("PDF uploaded to DB_"+str(session)+", start Indexing!")
|
| 233 |
anhang=True
|
| 234 |
else:
|
| 235 |
gr.Info("No PDF attached - answer based on DB_"+str(session)+".")
|
|
|
|
| 247 |
collection = client.get_collection(
|
| 248 |
name=dbName, embedding_function=embeddingModel)
|
| 249 |
if(anhang==True):
|
| 250 |
+
corpus=split_with_overlap(doc,3500,700,pattern=splitRegex)
|
| 251 |
+
print("Length of corpus: "+str(len(corpus)))
|
| 252 |
+
print("Corpus:"+str(corpus))
|
| 253 |
then = datetime.now()
|
| 254 |
x=collection.get(include=[])["ids"]
|
| 255 |
print(len(x))
|
| 256 |
if(len(x)==0):
|
| 257 |
chunkSize=40000
|
| 258 |
+
for i in range(round(len(corpus)/chunkSize+0.5)): #0 is first batch, 3 is last (incomplete) batch given 133497 texts
|
| 259 |
print("embed batch "+str(i)+" of "+str(round(len(corpus)/chunkSize+0.5)))
|
| 260 |
ids=list(range(i*chunkSize,(i*chunkSize+chunkSize)))
|
| 261 |
batch=corpus[i*chunkSize:(i*chunkSize+chunkSize)]
|
| 262 |
textIDs=[str(id) for id in ids[0:len(batch)]]
|
| 263 |
ids=[str(id+len(x)+1) for id in ids[0:len(batch)]] # id refers to chromadb-unique ID
|
| 264 |
collection.add(documents=batch, ids=ids,
|
| 265 |
+
metadatas=[{"date": str("2024-10-10")} for b in batch]) #"textID":textIDs, "id":ids,
|
| 266 |
print("finished batch "+str(i)+" of "+str(round(len(corpus)/40000+0.5)))
|
| 267 |
now = datetime.now()
|
| 268 |
gr.Info(f"Indexing complete!")
|
| 269 |
+
print(now-then) #zu viel GB für sentences (GPU), bzw. 0:00:10.375087 für chunks
|
| 270 |
return(collection)
|
| 271 |
|
|
|
|
|
|
|
| 272 |
|
| 273 |
#--------------------------------------------------------
|
| 274 |
# Function for response to user queries and pot. addenda
|
|
|
|
| 299 |
print(str(client.list_collections()))
|
| 300 |
x=collection.get(include=[])["ids"]
|
| 301 |
context=collection.query(query_texts=[query], n_results=1)
|
| 302 |
+
context=["<Kontext "+str(i)+"> "+str(c)+"</Kontext "+str(i)+">" for i,c in enumerate(context["documents"][0])]
|
| 303 |
gr.Info("Kontext:\n"+str(context))
|
| 304 |
generate_kwargs = dict(
|
| 305 |
temperature=float(0.9),
|
|
|
|
| 355 |
])
|
| 356 |
i.launch() #allowed_paths=["."])
|
| 357 |
|
| 358 |
+
|