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
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# set path
import glob, os, sys; sys.path.append('../udfPreprocess')

#import helper
import udfPreprocess.docPreprocessing as pre
import udfPreprocess.cleaning as clean

#import needed libraries
import seaborn as sns
from pandas import DataFrame
from sentence_transformers import SentenceTransformer, CrossEncoder, util
# from keybert import KeyBERT
from transformers import pipeline
import matplotlib.pyplot as plt
import numpy as np
import streamlit as st
import pandas as pd 
from rank_bm25 import BM25Okapi
from sklearn.feature_extraction import _stop_words
import string
from tqdm.autonotebook import tqdm
import numpy as np

import tempfile
import sqlite3

def app():

    with st.container():
        st.markdown("<h1 style='text-align: center;  \
                      color: black;'> Keyword Search</h1>", 
                      unsafe_allow_html=True)
        st.write(' ')
        st.write(' ')

    with st.expander("ℹ️ - About this app", expanded=True):

        st.write(
            """     
            The *Keyword Search* app is an easy-to-use interface \ 
            built in Streamlit for doing keyword search in \
            policy document - developed by GIZ Data and the \
            Sustainable Development Solution Network.
            """
        )

        st.markdown("")

    st.markdown("")
    st.markdown("### 📌 Step One: Upload document ### ")

    with st.container():
      def bm25_tokenizer(text):
            tokenized_doc = []
            for token in text.lower().split():
                token = token.strip(string.punctuation)

                if len(token) > 0 and token not in _stop_words.ENGLISH_STOP_WORDS:
                    tokenized_doc.append(token)
            return tokenized_doc
          
      def bm25TokenizeDoc(paraList):
          tokenized_corpus = []
          for passage in tqdm(paraList):
              if len(passage.split()) >256:
                  temp  = " ".join(passage.split()[:256])
                  tokenized_corpus.append(bm25_tokenizer(temp))
                  temp  = " ".join(passage.split()[256:])
                  tokenized_corpus.append(bm25_tokenizer(temp))
              else:
                  tokenized_corpus.append(bm25_tokenizer(passage))
                  
          return tokenized_corpus
      def search(keyword):
                ##### BM25 search (lexical search) #####
                bm25_scores = document_bm25.get_scores(bm25_tokenizer(keyword))
                top_n = np.argpartition(bm25_scores, -10)[-10:]
                bm25_hits = [{'corpus_id': idx, 'score': bm25_scores[idx]} for idx in top_n]
                bm25_hits = sorted(bm25_hits, key=lambda x: x['score'], reverse=True)
                
                ##### Sematic Search #####
                # Encode the query using the bi-encoder and find potentially relevant passages
                #query = "Does document contain {} issues ?".format(keyword)
                question_embedding = bi_encoder.encode(keyword, convert_to_tensor=True)
          
                hits = util.semantic_search(question_embedding, document_embeddings, top_k=top_k)
                hits = hits[0]  # Get the hits for the first query
                
                
                ##### Re-Ranking #####
                # Now, score all retrieved passages with the cross_encoder
                #cross_inp = [[query, paraList[hit['corpus_id']]] for hit in hits]
                #cross_scores = cross_encoder.predict(cross_inp)
                
                # Sort results by the cross-encoder scores
                #for idx in range(len(cross_scores)):
                  #   hits[idx]['cross-score'] = cross_scores[idx]
                  
                
                return bm25_hits, hits

      def show_results(keywordList):
        for keyword in keywordList:
          st.write("Results for Query: {}".format(keyword))
          bm25_hits, hits = search(keyword)     

          st.markdown("""
                      We will provide with 2 kind of results. The 'lexical search' and the semantic search. 
                      """)  
          # In the semantic search part we provide two kind of results one with only Retriever (Bi-Encoder) and other the ReRanker (Cross Encoder)           
          st.markdown("Top few lexical search (BM25) hits")
          for hit in bm25_hits[0:5]:
              if hit['score'] > 0.00:   
                  st.write("\t Score: {:.3f}:  \t{}".format(hit['score'], paraList[hit['corpus_id']].replace("\n", " ")))
          
          
        
        
        
        #   st.table(bm25_hits[0:3])
          
          st.markdown("\n-------------------------\n")
          st.markdown("Top few Bi-Encoder Retrieval hits")
          
          hits = sorted(hits, key=lambda x: x['score'], reverse=True)
          for hit in hits[0:5]:
            #  if hit['score'] > 0.45:
              st.write("\t Score: {:.3f}:  \t{}".format(hit['score'], paraList[hit['corpus_id']].replace("\n", " ")))
          #st.table(hits[0:3]


      @st.cache(allow_output_mutation=True)
      def load_sentenceTransformer(name):
          return SentenceTransformer(name)



      docs = None
      # asking user for either upload or select existing doc
      choice = st.radio(label = 'Select the Document',
                        help = 'You can upload the document \
                        or else you can try a example document', 
                        options = ('Upload Document', 'Try Example'), 
                        horizontal = True)

      if choice == 'Upload Document':
        uploaded_file = st.file_uploader('Upload the File', type=['pdf', 'docx', 'txt'])
        if uploaded_file is not None:
          with tempfile.NamedTemporaryFile(mode="wb") as temp:
              bytes_data = uploaded_file.getvalue()
              temp.write(bytes_data)

              st.write("Uploaded Filename: ", uploaded_file.name)
              file_name =  uploaded_file.name
              file_path = temp.name
              docs = pre.load_document(file_path, file_name)
              haystackDoc, dataframeDoc, textData, paraList = clean.preprocessing(docs)

      else:
        # listing the options
        option = st.selectbox('Select the example document',
                              ('South Africa:Low Emission strategy', 
                              'Ethiopia: 10 Year Development Plan'))
        if option is 'South Africa:Low Emission strategy':
          file_name = file_path  = 'sample/South Africa_s Low Emission Development Strategy.txt'
          st.write("Selected document:", file_name.split('/')[1])
          # with open('sample/South Africa_s Low Emission Development Strategy.txt') as dfile:
          # file = open('sample/South Africa_s Low Emission Development Strategy.txt', 'wb')
        else:
          # with open('sample/Ethiopia_s_2021_10 Year Development Plan.txt') as dfile:
          file_name = file_path =  'sample/Ethiopia_s_2021_10 Year Development Plan.txt'
          st.write("Selected document:", file_name.split('/')[1])
        
        if option is not None:
          docs = pre.load_document(file_path,file_name)
          haystackDoc, dataframeDoc, textData, paraList = clean.preprocessing(docs)

        if docs is not None:
          
          bi_encoder = load_sentenceTransformer('msmarco-distilbert-cos-v5') # multi-qa-MiniLM-L6-cos-v1
          bi_encoder.max_seq_length = 64     #Truncate long passages to 256 tokens
          top_k = 32

          document_embeddings = bi_encoder.encode(paraList, convert_to_tensor=True, show_progress_bar=False)
          tokenized_corpus = bm25TokenizeDoc(paraList)
          document_bm25 = BM25Okapi(tokenized_corpus)
          keywordList = None

          col1, col2 = st.columns(2)
          with col1:
            if st.button('Climate Change Keyword Search'):
              keywordList = ['extreme weather', 'floods', 'droughts']
            
             # show_results(keywordList)
          with col2:
            if st.button('Gender Keywords Search'):
              keywordList =  ['Gender', 'Women empowernment']
            
             # show_results(keywordList)
          
          keyword = st.text_input("Please enter here \
                                    what you want to search, \
                                    we will look for similar context \
                                    in the document.",
                                    value="",)
          if st.button("Find them."):
            keywordList = [keyword]
          if keywordList is not None:
              show_results(keywordList)
          



        # @st.cache(allow_output_mutation=True)
        # def load_sentenceTransformer(name):
        #     return SentenceTransformer(name)

        # bi_encoder = load_sentenceTransformer('msmarco-distilbert-cos-v5') # multi-qa-MiniLM-L6-cos-v1
        # bi_encoder.max_seq_length = 64     #Truncate long passages to 256 tokens
        # top_k = 32
        
        # #@st.cache(allow_output_mutation=True)
        # #def load_crossEncoder(name):
        #   #   return CrossEncoder(name)
        
        # # cross_encoder = load_crossEncoder('cross-encoder/ms-marco-MiniLM-L-6-v2')
        # document_embeddings = bi_encoder.encode(paraList, convert_to_tensor=True, show_progress_bar=False)

        # def bm25_tokenizer(text):
        #     tokenized_doc = []
        #     for token in text.lower().split():
        #         token = token.strip(string.punctuation)

        #         if len(token) > 0 and token not in _stop_words.ENGLISH_STOP_WORDS:
        #             tokenized_doc.append(token)
        #     return tokenized_doc
            
        # def bm25TokenizeDoc(paraList):
        #     tokenized_corpus = []
        #     for passage in tqdm(paraList):
        #         if len(passage.split()) >256:
        #             temp  = " ".join(passage.split()[:256])
        #             tokenized_corpus.append(bm25_tokenizer(temp))
        #             temp  = " ".join(passage.split()[256:])
        #             tokenized_corpus.append(bm25_tokenizer(temp))
        #         else:
        #             tokenized_corpus.append(bm25_tokenizer(passage))
                    
        #     return tokenized_corpus
        
        # tokenized_corpus = bm25TokenizeDoc(paraList)
        

        # document_bm25 = BM25Okapi(tokenized_corpus)
        
        # # def search(keyword):
        # #         ##### BM25 search (lexical search) #####
        # #         bm25_scores = document_bm25.get_scores(bm25_tokenizer(keyword))
        #         top_n = np.argpartition(bm25_scores, -10)[-10:]
        #         bm25_hits = [{'corpus_id': idx, 'score': bm25_scores[idx]} for idx in top_n]
        #         bm25_hits = sorted(bm25_hits, key=lambda x: x['score'], reverse=True)
                
        #         ##### Sematic Search #####
        #         # Encode the query using the bi-encoder and find potentially relevant passages
        #         #query = "Does document contain {} issues ?".format(keyword)
        #         question_embedding = bi_encoder.encode(keyword, convert_to_tensor=True)
          
        #         hits = util.semantic_search(question_embedding, document_embeddings, top_k=top_k)
        #         hits = hits[0]  # Get the hits for the first query
                
                
        #         ##### Re-Ranking #####
        #         # Now, score all retrieved passages with the cross_encoder
        #         #cross_inp = [[query, paraList[hit['corpus_id']]] for hit in hits]
        #         #cross_scores = cross_encoder.predict(cross_inp)
                
        #         # Sort results by the cross-encoder scores
        #         #for idx in range(len(cross_scores)):
        #           #   hits[idx]['cross-score'] = cross_scores[idx]
                  
                
        #         return bm25_hits, hits

        # def show_results(keywordList):
        #   for keyword in keywordList:
        #     bm25_hits, hits = search(keyword)     

        #     st.markdown("""
        #                 We will provide with 2 kind of results. The 'lexical search' and the semantic search. 
        #                 """)  
        #     # In the semantic search part we provide two kind of results one with only Retriever (Bi-Encoder) and other the ReRanker (Cross Encoder)           
        #     st.markdown("Top few lexical search (BM25) hits")
        #     for hit in bm25_hits[0:5]:
        #         if hit['score'] > 0.00:   
        #             st.write("\t Score: {:.3f}:  \t{}".format(hit['score'], paraList[hit['corpus_id']].replace("\n", " ")))
            
            
          
          
          
        #   #   st.table(bm25_hits[0:3])
            
        #     st.markdown("\n-------------------------\n")
        #     st.markdown("Top few Bi-Encoder Retrieval hits")
            
        #     hits = sorted(hits, key=lambda x: x['score'], reverse=True)
        #     for hit in hits[0:5]:
        #       #  if hit['score'] > 0.45:
        #         st.write("\t Score: {:.3f}:  \t{}".format(hit['score'], paraList[hit['corpus_id']].replace("\n", " ")))
        #     #st.table(hits[0:3]


        # # if docs is not None:
        # #     col1, col2 = st.columns(2)
        # #     with col1:
        # #       if st.button('Gender Keywords Search'):
        # #         keywordList =  ['Gender Equality', 'Women empowernment']
        # #         show_results(keywordList)
        # #     with col2:
        # #       if st.button('Climate Change Keyword Search'):
        # #         keywordList = ['extreme weather', 'floods', 'droughts']
        # #         show_results(keywordList)
            
        # #     keyword = st.text_input("Please enter here \
        # #                              what you want to search, \
        # #                              we will look for similar context \
        # #                              in the document.",
        # #                              value="",)
        # #     if st.button("Find them."):
        # #       show_results([keyword])

  
            # choice1 = st.radio(label = 'Keyword Search',
            #               help = 'Search  \
            #               or else you can try a example document', 
            #               options = ('Enter your own Query', 'Try Example'), 
            #               horizontal = True)
            
            # if choice1 == 'Enter your own Query':
            #   keyword = st.text_input("Please enter here \
            #                         what you want to search, \
            #                         we will look for similar context \
            #                         in the document.",
            #                         value="",)
            # else:
            #   option1 = st.selectbox('Select the Predefined word cluster',
            #                     ('Gender:[Gender Equality, Women empowernment]', 
            #                     'Climate change:[extreme weather, floods, droughts]',
            #                     ))
            #   if option1 == 'Gender:[Gender Equality, Women empowernment]':
            #     keywordList = ['Gender Equality', 'Women empowernment']
            #   else:
            #     keywordList = ['extreme weather', 'floods', 'droughts']

            # option1 = st.selectbox('Select the Predefined word cluster',
            #                     ('Gender:[Gender Equality, Women empowernment]', 
            #                     'Climate change:[extreme weather, floods, droughts]',
            # #                     'Enter your Own Keyword Query'))
            # if option1 == 'Enter your Own Keyword Query':
            #   keyword = st.text_input("Please enter here \
            #                         what you want to search, \
            #                         we will look for similar context \
            #                         in the document.",
            #                         value="",)
            # elif option1 == 'Gender:[Gender Equality, Women empowernment]':
            #   keywordList = ['Gender Equality', 'Women empowernment']
            # elif option1 == 'Climate change:[extreme weather, floods, droughts]':
            #   keywordList = ['extreme weather', 'floods', 'droughts']


            # st.markdown("### 📌 Step Two: Search Keyword in Document ### ")             
            
                                      
            # @st.cache(allow_output_mutation=True)
            # def load_sentenceTransformer(name):
            #     return SentenceTransformer(name)

            # bi_encoder = load_sentenceTransformer('msmarco-distilbert-cos-v5') # multi-qa-MiniLM-L6-cos-v1
            # bi_encoder.max_seq_length = 64     #Truncate long passages to 256 tokens
            # top_k = 32
            
            # #@st.cache(allow_output_mutation=True)
            # #def load_crossEncoder(name):
            #   #   return CrossEncoder(name)
            
            # # cross_encoder = load_crossEncoder('cross-encoder/ms-marco-MiniLM-L-6-v2')
            # document_embeddings = bi_encoder.encode(paraList, convert_to_tensor=True, show_progress_bar=False)

            # def bm25_tokenizer(text):
            #     tokenized_doc = []
            #     for token in text.lower().split():
            #         token = token.strip(string.punctuation)

            #         if len(token) > 0 and token not in _stop_words.ENGLISH_STOP_WORDS:
            #             tokenized_doc.append(token)
            #     return tokenized_doc
                
            # def bm25TokenizeDoc(paraList):
            #     tokenized_corpus = []
            #     for passage in tqdm(paraList):
            #         if len(passage.split()) >256:
            #             temp  = " ".join(passage.split()[:256])
            #             tokenized_corpus.append(bm25_tokenizer(temp))
            #             temp  = " ".join(passage.split()[256:])
            #             tokenized_corpus.append(bm25_tokenizer(temp))
            #         else:
            #             tokenized_corpus.append(bm25_tokenizer(passage))
                        
            #     return tokenized_corpus
            
            # tokenized_corpus = bm25TokenizeDoc(paraList)
            

            # document_bm25 = BM25Okapi(tokenized_corpus)
            
            
            # def search(keyword):
            #     ##### BM25 search (lexical search) #####
            #     bm25_scores = document_bm25.get_scores(bm25_tokenizer(keyword))
            #     top_n = np.argpartition(bm25_scores, -10)[-10:]
            #     bm25_hits = [{'corpus_id': idx, 'score': bm25_scores[idx]} for idx in top_n]
            #     bm25_hits = sorted(bm25_hits, key=lambda x: x['score'], reverse=True)
                
            #     ##### Sematic Search #####
            #     # Encode the query using the bi-encoder and find potentially relevant passages
            #     #query = "Does document contain {} issues ?".format(keyword)
            #     question_embedding = bi_encoder.encode(keyword, convert_to_tensor=True)
          
            #     hits = util.semantic_search(question_embedding, document_embeddings, top_k=top_k)
            #     hits = hits[0]  # Get the hits for the first query
                
                
            #     ##### Re-Ranking #####
            #     # Now, score all retrieved passages with the cross_encoder
            #     #cross_inp = [[query, paraList[hit['corpus_id']]] for hit in hits]
            #     #cross_scores = cross_encoder.predict(cross_inp)
                
            #     # Sort results by the cross-encoder scores
            #     #for idx in range(len(cross_scores)):
            #       #   hits[idx]['cross-score'] = cross_scores[idx]
                  
                
            #     return bm25_hits, hits

            # def show_results(keywordList):
            #   for keyword in keywordList:
            #     bm25_hits, hits = search(keyword)     

            #     st.markdown("""
            #                 We will provide with 2 kind of results. The 'lexical search' and the semantic search. 
            #                 """)  
            #     # In the semantic search part we provide two kind of results one with only Retriever (Bi-Encoder) and other the ReRanker (Cross Encoder)           
            #     st.markdown("Top few lexical search (BM25) hits")
            #     for hit in bm25_hits[0:5]:
            #         if hit['score'] > 0.00:   
            #             st.write("\t Score: {:.3f}:  \t{}".format(hit['score'], paraList[hit['corpus_id']].replace("\n", " ")))
                
                
              
              
              
            #   #   st.table(bm25_hits[0:3])
                
            #     st.markdown("\n-------------------------\n")
            #     st.markdown("Top few Bi-Encoder Retrieval hits")
                
            #     hits = sorted(hits, key=lambda x: x['score'], reverse=True)
            #     for hit in hits[0:5]:
            #       #  if hit['score'] > 0.45:
            #         st.write("\t Score: {:.3f}:  \t{}".format(hit['score'], paraList[hit['corpus_id']].replace("\n", " ")))
            #     #st.table(hits[0:3]
        

          

            # # if st.button("Find them."):
            # #     bm25_hits, hits = search(keyword)     

            # #     st.markdown("""
            # #                 We will provide with 2 kind of results. The 'lexical search' and the semantic search. 
            # #                 """)  
            # #     # In the semantic search part we provide two kind of results one with only Retriever (Bi-Encoder) and other the ReRanker (Cross Encoder)           
            # #     st.markdown("Top few lexical search (BM25) hits")
            # #     for hit in bm25_hits[0:5]:
            # #         if hit['score'] > 0.00:   
            # #             st.write("\t Score: {:.3f}:  \t{}".format(hit['score'], paraList[hit['corpus_id']].replace("\n", " ")))
                
                
              
              
              
            # #   #   st.table(bm25_hits[0:3])
                
            # #     st.markdown("\n-------------------------\n")
            # #     st.markdown("Top few Bi-Encoder Retrieval hits")
                
            # #     hits = sorted(hits, key=lambda x: x['score'], reverse=True)
            # #     for hit in hits[0:5]:
            # #       #  if hit['score'] > 0.45:
            # #         st.write("\t Score: {:.3f}:  \t{}".format(hit['score'], paraList[hit['corpus_id']].replace("\n", " ")))
            # #     #st.table(hits[0:3]