-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathlambda_function.py
2180 lines (1825 loc) · 78.2 KB
/
lambda_function.py
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
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import json
import boto3
import os
import traceback
import time
import docx
import base64
import fitz
import re
from io import BytesIO
from urllib import parse
from botocore.config import Config
from PIL import Image
from urllib.parse import unquote_plus
from langchain_aws import BedrockEmbeddings
from langchain_community.vectorstores.opensearch_vector_search import OpenSearchVectorSearch
from langchain_community.docstore.document import Document
from langchain.text_splitter import RecursiveCharacterTextSplitter
from opensearchpy import OpenSearch
from pptx import Presentation
from multiprocessing import Process, Pipe
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.messages import HumanMessage, SystemMessage
from langchain_aws import ChatBedrock
from pptx.enum.shapes import MSO_SHAPE_TYPE
from docx.enum.shape import WD_INLINE_SHAPE_TYPE
from pypdf import PdfReader
sqs = boto3.client('sqs')
s3_client = boto3.client('s3')
s3_bucket = os.environ.get('s3_bucket') # bucket name
s3_prefix = os.environ.get('s3_prefix')
meta_prefix = "metadata/"
enableParentDocumentRetrival = os.environ.get('enableParentDocumentRetrival')
opensearch_account = os.environ.get('opensearch_account')
opensearch_passwd = os.environ.get('opensearch_passwd')
opensearch_url = os.environ.get('opensearch_url')
sqsUrl = os.environ.get('sqsUrl')
doc_prefix = s3_prefix+'/'
LLM_embedding = json.loads(os.environ.get('LLM_embedding'))
selected_model = 0
selected_embedding = 0
maxOutputTokens = 4096
contextual_embedding = 'Disable'
ocr = "Disable"
model_name = "default"
multi_region = 'Disable'
def get_model_info(model):
global model_name, selected_model
if model != model_name:
selected_model = 0
model_name = model
nova_pro_models = [ # Nova Pro
{
"bedrock_region": "us-west-2", # Oregon
"model_type": "nova",
"model_id": "us.amazon.nova-pro-v1:0"
},
{
"bedrock_region": "us-east-1", # N.Virginia
"model_type": "nova",
"model_id": "us.amazon.nova-pro-v1:0"
},
{
"bedrock_region": "us-east-2", # Ohio
"model_type": "nova",
"model_id": "us.amazon.nova-pro-v1:0"
}
]
nova_lite_models = [ # Nova Lite
{
"bedrock_region": "us-west-2", # Oregon
"model_type": "nova",
"model_id": "us.amazon.nova-pro-v1:0"
},
{
"bedrock_region": "us-east-1", # N.Virginia
"model_type": "nova",
"model_id": "us.amazon.nova-pro-v1:0"
},
{
"bedrock_region": "us-east-2", # Ohio
"model_type": "nova",
"model_id": "us.amazon.nova-pro-v1:0"
}
]
claude_sonnet_3_5_v1_models = [ # Sonnet 3.5 V1
{
"bedrock_region": "us-west-2", # Oregon
"model_type": "claude",
"model_id": "anthropic.claude-3-5-sonnet-20240620-v1:0"
},
{
"bedrock_region": "us-east-1", # N.Virginia
"model_type": "claude",
"model_id": "anthropic.claude-3-5-sonnet-20240620-v1:0"
},
{
"bedrock_region": "us-east-2", # Ohio
"model_type": "claude",
"model_id": "us.anthropic.claude-3-5-sonnet-20240620-v1:0"
}
]
claude_sonnet_3_5_v2_models = [ # Sonnet 3.5 V2
{
"bedrock_region": "us-west-2", # Oregon
"model_type": "claude",
"model_id": "anthropic.claude-3-5-sonnet-20241022-v2:0"
},
{
"bedrock_region": "us-east-1", # N.Virginia
"model_type": "claude",
"model_id": "us.anthropic.claude-3-5-sonnet-20241022-v2:0"
},
{
"bedrock_region": "us-east-2", # Ohio
"model_type": "claude",
"model_id": "us.anthropic.claude-3-5-sonnet-20241022-v2:0"
}
]
claude_sonnet_3_0_models = [ # Sonnet 3.0
{
"bedrock_region": "us-west-2", # Oregon
"model_type": "claude",
"model_id": "anthropic.claude-3-sonnet-20240229-v1:0"
},
{
"bedrock_region": "us-east-1", # N.Virginia
"model_type": "claude",
"model_id": "anthropic.claude-3-sonnet-20240229-v1:0"
}
]
claude_haiku_3_5_models = [ # Haiku 3.5
{
"bedrock_region": "us-west-2", # Oregon
"model_type": "claude",
"model_id": "anthropic.claude-3-5-haiku-20241022-v1:0"
},
{
"bedrock_region": "us-east-1", # N.Virginia
"model_type": "claude",
"model_id": "us.anthropic.claude-3-5-haiku-20241022-v1:0"
},
{
"bedrock_region": "us-east-2", # Ohio
"model_type": "claude",
"model_id": "us.anthropic.claude-3-5-haiku-20241022-v1:0"
}
]
claude_3_7_sonnet_models = [ # Sonnet 3.7
{
"bedrock_region": "us-west-2", # Oregon
"model_type": "claude",
"model_id": "us.anthropic.claude-3-7-sonnet-20250219-v1:0"
},
{
"bedrock_region": "us-east-1", # N.Virginia
"model_type": "claude",
"model_id": "us.anthropic.claude-3-7-sonnet-20250219-v1:0"
},
{
"bedrock_region": "us-east-2", # N.Ohio
"model_type": "claude",
"model_id": "us.anthropic.claude-3-7-sonnet-20250219-v1:0"
}
]
claude_models = [
{ # Claude 3.7 Sonnet
"bedrock_region": "us-west-2", # Oregon
"model_type": "claude",
"model_id": "us.anthropic.claude-3-7-sonnet-20250219-v1:0"
},
{
"bedrock_region": "us-east-1", # N.Virginia
"model_type": "claude",
"model_id": "us.anthropic.claude-3-7-sonnet-20250219-v1:0"
},
{ # Claude 3.5 Sonnet v1
"bedrock_region": "us-west-2", # Oregon
"model_type": "claude",
"model_id": "anthropic.claude-3-5-sonnet-20240620-v1:0"
},
{
"bedrock_region": "us-east-1", # N.Virginia
"model_type": "claude",
"model_id": "anthropic.claude-3-5-sonnet-20240620-v1:0"
},
{
"bedrock_region": "us-east-2", # Ohio
"model_type": "claude",
"model_id": "us.anthropic.claude-3-5-sonnet-20240620-v1:0"
},
{ # Claude 3.5 Sonnet v2
"bedrock_region": "us-west-2", # Oregon
"model_type": "claude",
"model_id": "anthropic.claude-3-5-sonnet-20241022-v2:0"
},
{
"bedrock_region": "us-east-1", # N.Virginia
"model_type": "claude",
"model_id": "us.anthropic.claude-3-5-sonnet-20241022-v2:0"
},
{
"bedrock_region": "us-east-2", # Ohio
"model_type": "claude",
"model_id": "us.anthropic.claude-3-5-sonnet-20241022-v2:0"
}
]
if model == 'Nova Pro':
return nova_pro_models
elif model == 'Nova Lite':
return nova_lite_models
elif model == 'Claude 3.7 Sonnet':
return claude_3_7_sonnet_models
elif model == 'Claude 3.5 Sonnet':
return claude_sonnet_3_5_v2_models # claude_sonnet_3_5_v1_models
elif model == 'Claude 3.0 Sonnet':
return claude_sonnet_3_0_models
elif model == 'Claude 3.5 Haiku':
return claude_models
else:
return claude_models
roleArn = os.environ.get('roleArn')
path = os.environ.get('path')
max_object_size = int(os.environ.get('max_object_size'))
supportedFormat = json.loads(os.environ.get('supportedFormat'))
print('supportedFormat: ', supportedFormat)
enableHybridSearch = os.environ.get('enableHybridSearch')
vectorIndexName = os.environ.get('vectorIndexName')
enableTableExtraction = 'Enable'
enableImageExtraction = 'Enable'
enablePageImageExraction = 'Enable'
os_client = OpenSearch(
hosts = [{
'host': opensearch_url.replace("https://", ""),
'port': 443
}],
http_compress = True,
http_auth=(opensearch_account, opensearch_passwd),
use_ssl = True,
verify_certs = True,
ssl_assert_hostname = False,
ssl_show_warn = False,
)
def delete_document_if_exist(metadata_key):
try:
s3r = boto3.resource("s3")
bucket = s3r.Bucket(s3_bucket)
objs = list(bucket.objects.filter(Prefix=metadata_key))
print('objs: ', objs)
if(len(objs)>0):
doc = s3r.Object(s3_bucket, metadata_key)
meta = doc.get()['Body'].read().decode('utf-8')
print('meta: ', meta)
ids = json.loads(meta)['ids']
print('ids: ', ids)
# delete ids
result = vectorstore.delete(ids)
print('delete ids in vectorstore: ', result)
# delete files
files = json.loads(meta)['files']
print('files: ', files)
for file in files:
s3r.Object(s3_bucket, file).delete()
print('delete file: ', file)
else:
print('no meta file: ', metadata_key)
except Exception:
err_msg = traceback.format_exc()
print('error message: ', err_msg)
raise Exception ("Not able to create meta file")
def get_model():
global selected_model
LLM_for_chat = get_model_info(model_name)
print(f'selected_model: {selected_model}, model_name: {model_name}')
if selected_model >= len(LLM_for_chat): # exceptional case
print(f"# of models: {len(LLM_for_chat)}, selected_model: {selected_model}")
print('------> selected_model is initiated')
selected_model = 0
profile = LLM_for_chat[selected_model]
bedrock_region = profile['bedrock_region']
modelId = profile['model_id']
print(f'selected_model: {selected_model}, bedrock_region: {bedrock_region}, modelId: {modelId}')
# bedrock
boto3_bedrock = boto3.client(
service_name='bedrock-runtime',
region_name=bedrock_region,
config=Config(
retries = {
'max_attempts': 30
}
)
)
parameters = {
"max_tokens":maxOutputTokens,
"temperature":0.1,
"top_k":250,
"top_p":0.9,
"stop_sequences": [HUMAN_PROMPT]
}
# print('parameters: ', parameters)
llm = ChatBedrock( # new chat model
model_id=modelId,
client=boto3_bedrock,
model_kwargs=parameters,
)
if multi_region == "Enable":
selected_model = selected_model + 1
if selected_model >= len(LLM_for_chat):
selected_model = 0
else:
selected_model = 0
return llm
def get_selected_model(selected_model):
LLM_for_chat = get_model_info(model_name)
print(f'selected_model: {selected_model}, model_name: {model_name}')
profile = LLM_for_chat[selected_model]
bedrock_region = profile['bedrock_region']
modelId = profile['model_id']
print(f'selected_model: {selected_model}, bedrock_region: {bedrock_region}, modelId: {modelId}')
# bedrock
boto3_bedrock = boto3.client(
service_name='bedrock-runtime',
region_name=bedrock_region,
config=Config(
retries = {
'max_attempts': 30
}
)
)
parameters = {
"max_tokens":maxOutputTokens,
"temperature":0.1,
"top_k":250,
"top_p":0.9,
"stop_sequences": [HUMAN_PROMPT]
}
# print('parameters: ', parameters)
llm = ChatBedrock( # new chat model
model_id=modelId,
client=boto3_bedrock,
model_kwargs=parameters,
)
return llm
def get_embedding():
global selected_embedding
profile = LLM_embedding[selected_embedding]
bedrock_region = profile['bedrock_region']
model_id = profile['model_id']
print(f'selected_embedding: {selected_embedding}, bedrock_region: {bedrock_region}')
# bedrock
boto3_bedrock = boto3.client(
service_name='bedrock-runtime',
region_name=bedrock_region,
config=Config(
retries = {
'max_attempts': 30
}
)
)
bedrock_embedding = BedrockEmbeddings(
client=boto3_bedrock,
region_name = bedrock_region,
model_id = model_id
)
if multi_region == "Enable":
selected_embedding = selected_embedding + 1
if selected_embedding == len(LLM_embedding):
selected_embedding = 0
else:
selected_embedding = 0
return bedrock_embedding
bedrock_embeddings = get_embedding()
index_name = vectorIndexName
vectorstore = OpenSearchVectorSearch(
index_name=index_name,
is_aoss = False,
#engine="faiss", # default: nmslib
embedding_function = bedrock_embeddings,
opensearch_url = opensearch_url,
http_auth=(opensearch_account, opensearch_passwd),
)
def store_document_for_opensearch(file_type, key):
print('upload to opensearch: ', key)
contents, files, tables = load_document(file_type, key)
if len(contents) == 0:
print('no contents: ', key)
return [], files
# contents = str(contents).replace("\n"," ")
print('length: ', len(contents))
# text
docs = []
docs.append(Document(
page_content=contents,
metadata={
'name': key,
'url': path+parse.quote(key)
}
))
# table
for table in tables:
docs.append(Document(
page_content=table['body'],
metadata={
'name': table['name'],
'url': path+parse.quote(table['name']),
}
))
print('docs: ', docs)
ids = add_to_opensearch(docs, key)
return ids, files
def store_code_for_opensearch(file_type, key):
codes = load_code(file_type, key) # number of functions in the code
if multi_region=='Enable':
docs = summarize_relevant_codes_using_parallel_processing(codes, key)
else:
docs = []
for code in codes:
start = code.find('\ndef ')
end = code.find(':')
# print(f'start: {start}, end: {end}')
if start != -1:
function_name = code[start+1:end]
# print('function_name: ', function_name)
llm = get_model()
summary = summary_of_code(llm, code, file_type)
if summary[:len(function_name)]==function_name:
summary = summary[summary.find('\n')+1:len(summary)]
docs.append(
Document(
page_content=summary,
metadata={
'name': key,
# 'page':i+1,
#'url': path+doc_prefix+parse.quote(key),
'url': path+key,
'code': code,
'function_name': function_name
}
)
)
print('docs size: ', len(docs))
return add_to_opensearch(docs, key)
def store_image_for_opensearch(key):
print('extract text from an image: ', key)
image_obj = s3_client.get_object(Bucket=s3_bucket, Key=key)
image_content = image_obj['Body'].read()
img = Image.open(BytesIO(image_content))
width, height = img.size
print(f"width: {width}, height: {height}, size: {width*height}")
if width < 100 or height < 100: # skip small size image
return []
isResized = False
while(width*height > 5242880):
width = int(width/2)
height = int(height/2)
isResized = True
print(f"width: {width}, height: {height}, size: {width*height}")
try:
if isResized:
img = img.resize((width, height))
buffer = BytesIO()
img.save(buffer, format="PNG")
img_base64 = base64.b64encode(buffer.getvalue()).decode("utf-8")
# extract text from the image
llm = get_model()
text = extract_text(llm, img_base64)
extracted_text = text[text.find('<result>')+8:text.find('</result>')] # remove <result> tag
#print('extracted_text: ', extracted_text)
contextual_text = ""
if "contextual_text" in object_meta:
contextual_text = object_meta["contextual_text"]
print('contextual_text: ', contextual_text)
summary = summary_image(llm, img_base64, contextual_text)
image_summary = summary[summary.find('<result>')+8:summary.find('</result>')] # remove <result> tag
#print('image summary: ', image_summary)
if len(extracted_text) > 30:
contents = f"[이미지 요약]\n{image_summary}\n\n[추출된 텍스트]\n{extracted_text}"
else:
contents = f"[이미지 요약]\n{image_summary}"
print('image contents: ', contents)
page = object_meta["page"]
print("page: ", page)
docs = []
if len(contents) > 30:
docs.append(
Document(
page_content=contents,
metadata={
'name': key,
'page': page,
'url': path+parse.quote(key)
}
)
)
print('docs size: ', len(docs))
return add_to_opensearch(docs, key)
except Exception:
err_msg = traceback.format_exc()
print('error message: ', err_msg)
#raise Exception ("Not able to summary")
return []
def is_not_exist(index_name):
if os_client.indices.exists(index_name):
print('use exist index: ', index_name)
return False
else:
print('no index: ', index_name)
return True
def create_nori_index():
index_body = {
'settings': {
'analysis': {
'analyzer': {
'my_analyzer': {
'char_filter': ['html_strip'],
'tokenizer': 'nori',
'filter': ['nori_number','lowercase','trim','my_nori_part_of_speech'],
'type': 'custom'
}
},
'tokenizer': {
'nori': {
'decompound_mode': 'mixed',
'discard_punctuation': 'true',
'type': 'nori_tokenizer'
}
},
"filter": {
"my_nori_part_of_speech": {
"type": "nori_part_of_speech",
"stoptags": [
"E", "IC", "J", "MAG", "MAJ",
"MM", "SP", "SSC", "SSO", "SC",
"SE", "XPN", "XSA", "XSN", "XSV",
"UNA", "NA", "VSV"
]
}
}
},
'index': {
'knn': True,
'knn.space_type': 'cosinesimil' # Example space type
}
},
'mappings': {
'properties': {
'metadata': {
'properties': {
'source' : {'type': 'keyword'},
'last_updated': {'type': 'date'},
'project': {'type': 'keyword'},
'seq_num': {'type': 'long'},
'title': {'type': 'text'}, # For full-text search
'url': {'type': 'text'}, # For full-text search
}
},
'text': {
'analyzer': 'my_analyzer',
'search_analyzer': 'my_analyzer',
'type': 'text'
},
'vector_field': {
'type': 'knn_vector',
'dimension': 1024
}
}
}
}
if(is_not_exist(index_name)):
try: # create index
response = os_client.indices.create(
index_name,
body=index_body
)
print('index was created with nori plugin:', response)
except Exception:
err_msg = traceback.format_exc()
print('error message: ', err_msg)
#raise Exception ("Not able to create the index")
if enableHybridSearch == 'true':
create_nori_index()
def get_contextual_text(whole_text, splitted_text, llm): # per page
contextual_template = (
"<document>"
"{WHOLE_DOCUMENT}"
"</document>"
"Here is the chunk we want to situate within the whole document."
"<chunk>"
"{CHUNK_CONTENT}"
"</chunk>"
"Please give a short succinct context to situate this chunk within the overall document for the purposes of improving search retrieval of the chunk."
"Answer only with the succinct context and nothing else in English."
"Put it in <result> tags."
)
contextual_prompt = ChatPromptTemplate([
('human', contextual_template)
])
contextual_text = ""
contexual_chain = contextual_prompt | llm
response = contexual_chain.invoke(
{
"WHOLE_DOCUMENT": whole_text,
"CHUNK_CONTENT": splitted_text
}
)
# print('--> contexual rext: ', response)
output = response.content
contextual_text = output[output.find('<result>')+8:output.find('</result>')]
# print(f"--> whole_text: {whole_text}")
print(f"--> original_chunk: {splitted_text}")
print(f"--> contextual_text: {contextual_text}")
return contextual_text
def get_contextual_docs_from_chunks(whole_doc, splitted_docs): # per chunk
contextual_template = (
"<document>"
"{WHOLE_DOCUMENT}"
"</document>"
"Here is the chunk we want to situate within the whole document."
"<chunk>"
"{CHUNK_CONTENT}"
"</chunk>"
"Please give a short succinct context to situate this chunk within the overall document for the purposes of improving search retrieval of the chunk."
"Answer only with the succinct context and nothing else."
"Put it in <result> tags."
)
contextual_prompt = ChatPromptTemplate([
('human', contextual_template)
])
contexualized_docs = []
contexualized_chunks = []
for i, doc in enumerate(splitted_docs):
# chat = get_contexual_retrieval_chat()
llm = get_model()
contexual_chain = contextual_prompt | llm
response = contexual_chain.invoke(
{
"WHOLE_DOCUMENT": whole_doc.page_content,
"CHUNK_CONTENT": doc.page_content
}
)
# print('--> contexual chunk: ', response)
output = response.content
contextualized_chunk = output[output.find('<result>')+8:output.find('</result>')]
contexualized_chunks.replace('\n', '')
contexualized_chunks.append(contextualized_chunk)
print(f"--> {i}: original_chunk: {doc.page_content}")
print(f"--> {i}: contexualized_chunk: {contextualized_chunk}")
contexualized_docs.append(
Document(
page_content="\n"+contextualized_chunk+"\n\n"+doc.page_content,
metadata=doc.metadata
)
)
return contexualized_docs, contexualized_chunks
def get_contextual_doc(conn, whole_doc, splitted_doc, selected_model): # per chunk
contextual_template = (
"<document>"
"{WHOLE_DOCUMENT}"
"</document>"
"Here is the chunk we want to situate within the whole document."
"<chunk>"
"{CHUNK_CONTENT}"
"</chunk>"
"Please give a short succinct context to situate this chunk within the overall document for the purposes of improving search retrieval of the chunk."
"Answer only with the succinct context and nothing else."
"Put it in <result> tags."
)
contextual_prompt = ChatPromptTemplate([
('human', contextual_template)
])
# chat = get_contexual_retrieval_chat()
llm = get_selected_model(selected_model)
contexual_chain = contextual_prompt | llm
response = contexual_chain.invoke(
{
"WHOLE_DOCUMENT": whole_doc.page_content,
"CHUNK_CONTENT": splitted_doc.page_content
}
)
# print('--> contexual chunk: ', response)
output = response.content
contextualized_chunk = output[output.find('<result>')+8:output.find('</result>')]
contextualized_chunk.replace('\n', '')
print(f"--> original_chunk: {splitted_doc.page_content}")
print(f"--> contexualized_chunk: {contextualized_chunk}")
contexualized_doc = Document(
page_content="\n"+contextualized_chunk+"\n\n"+splitted_doc.page_content,
metadata=splitted_doc.metadata
)
result = {
"contexualized_doc": contexualized_doc,
"contextualized_chunk": contextualized_chunk
}
conn.send(result)
conn.close()
def get_contextual_docs_using_parallel_processing(whole_doc, splitted_docs):
global selected_model
contexualized_docs = []
contexualized_chunks = []
LLM_for_chat = get_model_info(model_name)
# for i in range(len(splitted_docs)):
index = 0
while index < len(splitted_docs):
print(f"index: {index}")
processes = []
parent_connections = []
for i in range(len(LLM_for_chat)):
print(f"{i}: extract contextual doc[{index}]")
parent_conn, child_conn = Pipe()
parent_connections.append(parent_conn)
process = Process(target=get_contextual_doc, args=(child_conn, whole_doc, splitted_docs[index], selected_model))
processes.append(process)
selected_model = selected_model + 1
if selected_model >= len(LLM_for_chat):
selected_model = 0
index = index + 1
if index >= len(splitted_docs):
break
for process in processes:
process.start()
for parent_conn in parent_connections:
result = parent_conn.recv()
if result is not None:
contexualized_docs.append(result["contexualized_doc"])
contexualized_chunks.append(result["contextualized_chunk"])
for process in processes:
process.join()
return contexualized_docs, contexualized_chunks
def add_to_opensearch(docs, key):
if len(docs) == 0:
return []
#print('docs[0]: ', docs[0])
# objectName = (key[key.find(s3_prefix)+len(s3_prefix)+1:len(key)])
# print('objectName: ', objectName)
# metadata_key = meta_prefix+objectName+'.metadata.json'
# print('meta file name: ', metadata_key)
# delete_document_if_exist(metadata_key)
ids = []
if enableParentDocumentRetrival == 'true':
parent_splitter = RecursiveCharacterTextSplitter(
chunk_size=2000,
chunk_overlap=100,
separators=["\n\n", "\n", ".", " ", ""],
length_function = len,
)
child_splitter = RecursiveCharacterTextSplitter(
chunk_size=400,
chunk_overlap=50,
# separators=["\n\n", "\n", ".", " ", ""],
length_function = len,
)
splitted_docs = parent_splitter.split_documents(docs)
print('len(splitted_docs): ', len(splitted_docs))
print('splitted_docs[0]: ', splitted_docs[0].page_content)
parent_docs = []
if contextual_embedding == 'Enable':
if multi_region=="Enable":
parent_docs, contexualized_chunks = get_contextual_docs_using_parallel_processing(docs[-1], splitted_docs)
else:
parent_docs, contexualized_chunks = get_contextual_docs_from_chunks(docs[-1], splitted_docs)
print('parent contextual chunk[0]: ', parent_docs[0].page_content)
else:
parent_docs = splitted_docs
if len(parent_docs):
for i, doc in enumerate(parent_docs):
doc.metadata["doc_level"] = "parent"
# print(f"parent_docs[{i}]: {doc}")
print('parent_docs[0]: ', parent_docs[0].page_content)
try:
parent_doc_ids = vectorstore.add_documents(parent_docs, bulk_size = 10000)
print('parent_doc_ids: ', parent_doc_ids)
ids = parent_doc_ids
for i, doc in enumerate(splitted_docs):
_id = parent_doc_ids[i]
child_docs = child_splitter.split_documents([doc])
for _doc in child_docs:
_doc.metadata["parent_doc_id"] = _id
_doc.metadata["doc_level"] = "child"
if contextual_embedding == 'Enable':
contexualized_child_docs = [] # contexualized child doc
for _doc in child_docs:
contexualized_child_docs.append(
Document(
page_content=contexualized_chunks[i]+"\n\n"+_doc.page_content,
metadata=_doc.metadata
)
)
child_docs = contexualized_child_docs
print('child_docs[0]: ', child_docs[0].page_content)
child_doc_ids = vectorstore.add_documents(child_docs, bulk_size = 10000)
print('child_doc_ids: ', child_doc_ids)
print('len(child_doc_ids): ', len(child_doc_ids))
ids += child_doc_ids
except Exception:
err_msg = traceback.format_exc()
print('error message: ', err_msg)
#raise Exception ("Not able to add docs in opensearch")
else:
text_splitter = RecursiveCharacterTextSplitter(
chunk_size=1000,
chunk_overlap=100,
separators=["\n\n", "\n", ".", " ", ""],
length_function = len,
)
splitted_docs = text_splitter.split_documents(docs)
print('len(splitted_docs): ', len(splitted_docs))
if len(splitted_docs):
if contextual_embedding == 'Enable':
if multi_region=="Enable":
documents, contexualized_chunks = get_contextual_docs_using_parallel_processing(docs[-1], splitted_docs)
else:
documents, contexualized_chunks = get_contextual_docs_from_chunks(docs[-1], splitted_docs)
print('contextual chunks[0]: ', contexualized_chunks[0])
else:
print('documents[0]: ', documents[0])
try:
ids = vectorstore.add_documents(documents, bulk_size = 10000)
print('response of adding documents: ', ids)
except Exception:
err_msg = traceback.format_exc()
print('error message: ', err_msg)
#raise Exception ("Not able to add docs in opensearch")
return ids
def extract_images_from_pdf(reader, key):
picture_count = 1
extracted_image_files = []
print('pages: ', len(reader.pages))
for i, page in enumerate(reader.pages):
print('page: ', page)
if '/ProcSet' in page['/Resources']:
print('Resources/ProcSet: ', page['/Resources']['/ProcSet'])
if '/XObject' in page['/Resources']:
print(f"Resources/XObject[{i}]: {page['/Resources']['/XObject']}")
for image_file_object in page.images:
print('image_file_object: ', image_file_object)
img_name = image_file_object.name
print('img_name: ', img_name)
if img_name in extracted_image_files:
print('skip....')
continue
extracted_image_files.append(img_name)
# print('list: ', extracted_image_files)
ext = img_name.split('.')[-1]
contentType = ""
if ext == 'png':
contentType = 'image/png'
elif ext == 'jpg' or ext == 'jpeg':
contentType = 'image/jpeg'
elif ext == 'gif':
contentType = 'image/gif'
elif ext == 'bmp':
contentType = 'image/bmp'
elif ext == 'tiff' or ext == 'tif':
contentType = 'image/tiff'
elif ext == 'svg':