File size: 5,179 Bytes
0130713
c2f0c5c
e44062d
5a1352d
 
c567921
88e2023
cb359de
9d9ace2
 
50fbfdd
f5dac9b
0130713
 
 
d845358
 
e4b8dd5
88e2023
 
 
 
9392032
 
 
391fa92
9392032
391fa92
9392032
c567921
5a1352d
5170600
9392032
5a1352d
 
d845358
 
 
88e2023
d845358
 
 
 
 
 
 
 
 
88e2023
 
 
 
d845358
88e2023
 
d845358
 
4ec0c95
d845358
 
4ec0c95
d845358
4ec0c95
d845358
 
 
 
4681487
eb00b52
 
e44062d
7471ef6
3fe1fb4
d845358
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4ec0c95
d845358
4ec0c95
 
 
d845358
 
 
 
 
4ec0c95
d845358
4ec0c95
 
 
d845358
 
7471ef6
c567921
 
 
 
 
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
import streamlit as st
import pandas as pd
from appStore.prep_data import process_giz_worldwide
from appStore.prep_utils import create_documents, get_client
from appStore.embed import hybrid_embed_chunks
from appStore.search import hybrid_search
from appStore.region_utils import load_region_data, get_country_name
from torch import cuda
import json

# get the device to be used eithe gpu or cpu
device = 'cuda' if cuda.is_available() else 'cpu'


st.set_page_config(page_title="SEARCH IATI",layout='wide')
st.title("GIZ Project Database")
var = st.text_input("Enter Search Query")

# Load the region lookup CSV
region_lookup_path = "docStore/regions_lookup.csv"
region_df = load_region_data(region_lookup_path)

####################  Create the embeddings collection and save ######################
# the steps below need to be performed only once and then commented out any unnecssary compute over-run
##### First we process and create the chunks for relvant data source
#chunks = process_giz_worldwide()
##### Convert to langchain documents
#temp_doc = create_documents(chunks,'chunks')
##### Embed and store docs, check if collection exist then you need to update the collection
collection_name = "giz_worldwide"
#hybrid_embed_chunks(docs= temp_doc, collection_name = collection_name)

################### Hybrid Search ######################################################
client = get_client()
print(client.get_collections())

# Fetch unique country codes from the metadata for the dropdown
@st.cache_data
def get_unique_countries_with_names(_client, collection_name, region_df):
    results = hybrid_search(_client, "", collection_name)
    country_set = set()
    for res in results[0] + results[1]:
        countries = res.payload.get('metadata', {}).get('countries', "[]")
        try:
            country_list = json.loads(countries.replace("'", '"'))
            country_set.update(country_list)
        except json.JSONDecodeError:
            pass
    
    # Map ISO codes to country names
    country_names = [get_country_name(code, region_df) for code in country_set]
    return sorted(country_names)

client = get_client()
unique_countries = get_unique_countries_with_names(client, collection_name, region_df)

# Layout filters in columns
col1, col2, col3 = st.columns([1, 1, 4])

with col1:
    country_filter = st.selectbox("Country Code", ["All"] + unique_countries)
with col2:
    end_year_range = st.slider("Project End Year", min_value=2010, max_value=2030, value=(2010, 2030))

# Checkbox to control whether to show only exact matches
show_exact_matches = st.checkbox("Show only exact matches", value=False)

button=st.button("Search")
#found_docs = vectorstore.similarity_search(var)
#print(found_docs)
# results= get_context(vectorstore, f"find the relvant paragraphs for: {var}")
if button:
    results = hybrid_search(client, var, collection_name)

    # Filter results based on the user's input
    def filter_results(results, country_filter, end_year_range):
        filtered = []
        for res in results:
            metadata = res.payload.get('metadata', {})
            countries = metadata.get('countries', "[]")
            end_year = float(metadata.get('end_year', 0))

            # Process countries string to a list
            try:
                country_list = json.loads(countries.replace("'", '"'))
            except json.JSONDecodeError:
                country_list = []

            # Apply country and year filters
            if (country_filter == "All" or country_filter in country_list) and (end_year_range[0] <= end_year <= end_year_range[1]):
                filtered.append(res)
        return filtered

    # Check user preference for exact matches
    if show_exact_matches:
        st.write(f"Showing **Top 10 Lexical Search results** for query: {var}")
        lexical_results = results[1]  # Lexical results are in index 1
        filtered_lexical_results = filter_results(lexical_results, country_filter, end_year_range)
        for res in filtered_lexical_results[:10]:
            project_name = res.payload['metadata'].get('project_name', 'Project Link')
            url = res.payload['metadata'].get('url', '#')
            st.markdown(f"#### [{project_name}]({url})")
            st.write(res.payload['page_content'])
            st.divider()
    else:
        st.write(f"Showing **Top 10 Semantic Search results** for query: {var}")
        semantic_results = results[0]  # Semantic results are in index 0
        filtered_semantic_results = filter_results(semantic_results, country_filter, end_year_range)
        for res in filtered_semantic_results[:10]:
            project_name = res.payload['metadata'].get('project_name', 'Project Link')
            url = res.payload['metadata'].get('url', '#')
            st.markdown(f"#### [{project_name}]({url})")
            st.write(res.payload['page_content'])
            st.divider()


    #  for i in results: 
    #      st.subheader(str(i.metadata['id'])+":"+str(i.metadata['title_main']))
    #      st.caption(f"Status:{str(i.metadata['status'])}, Country:{str(i.metadata['country_name'])}")
    #      st.write(i.page_content)
    #      st.divider()