Spaces:
Sleeping
Sleeping
File size: 9,010 Bytes
0130713 c2f0c5c e44062d 5a1352d c567921 88e2023 8225c93 cb359de 9d9ace2 53d69f4 50fbfdd f5dac9b 0130713 d845358 e4b8dd5 88e2023 9392032 391fa92 9392032 391fa92 9392032 c567921 5a1352d 5170600 9392032 5a1352d d845358 17d08d8 d845358 17d08d8 d845358 043c4b1 d845358 88e2023 043c4b1 17d08d8 d845358 043c4b1 17d08d8 88e2023 17d08d8 d845358 4ec0c95 d845358 077a149 d845358 53d69f4 d845358 59e8a6b 7471ef6 59e8a6b d845358 59e8a6b d845358 59e8a6b 077a149 59e8a6b d845358 59e8a6b d845358 4ec0c95 59e8a6b 8ad1360 d3da02b 59e8a6b d3da02b 59e8a6b 8225c93 59e8a6b 077a149 59e8a6b 077a149 59e8a6b 077a149 59e8a6b 077a149 59e8a6b 077a149 59e8a6b 077a149 59e8a6b 53d69f4 d845358 59e8a6b d845358 4ec0c95 59e8a6b 8ad1360 d3da02b 59e8a6b d3da02b 59e8a6b 8225c93 59e8a6b 077a149 59e8a6b 077a149 59e8a6b 077a149 59e8a6b 077a149 59e8a6b 077a149 59e8a6b 077a149 59e8a6b 53d69f4 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 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 |
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 appStore.tfidf_extraction import extract_top_keywords
from torch import cuda
import json
from datetime import datetime
# 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 and map to country names
@st.cache_data
def get_country_name_mapping(_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("'", '"'))
# ADD: only add codes of length 2
two_digit_codes = [code.upper() for code in country_list if len(code) == 2]
country_set.update(two_digit_codes)
except json.JSONDecodeError:
pass
# Create a mapping of {CountryName -> ISO2Code}
# so you can display the name in the selectbox but store the 2-digit code
country_name_to_code = {}
for code in country_set:
name = get_country_name(code, region_df)
country_name_to_code[name] = code
return country_name_to_code
# Get country name mapping
client = get_client()
country_name_mapping = get_country_name_mapping(client, collection_name, region_df)
unique_country_names = sorted(country_name_mapping.keys()) # List of country names
# Layout filters in columns
col1, col2, col3 = st.columns([1, 1, 4])
with col1:
country_filter = st.selectbox("Country", ["All/Not allocated"] + unique_country_names) # Display country names
with col2:
current_year = datetime.now().year
default_start_year = current_year - 5 # Default to 5 years ago
end_year_range = st.slider(
"Project End Year",
min_value=2010,
max_value=2030,
value=(default_start_year, current_year)
)
# Checkbox to control whether to show only exact matches
show_exact_matches = st.checkbox("Show only exact matches", value=False)
def filter_results(results, country_filter, end_year_range):
filtered = []
for r in results:
metadata = r.payload.get('metadata', {})
countries = metadata.get('countries', "[]")
end_year_val = float(metadata.get('end_year', 0))
# Convert countries to a list
try:
c_list = json.loads(countries.replace("'", '"'))
c_list = [code.upper() for code in c_list if len(code) == 2]
except json.JSONDecodeError:
c_list = []
# Translate selected country name to iso2
selected_iso_code = country_name_mapping.get(country_filter, None)
# Filtering
if (
(country_filter == "All/Not allocated" or selected_iso_code in c_list)
and (end_year_range[0] <= end_year_val <= end_year_range[1])
):
filtered.append(r)
return filtered
if button:
# 1) Use a bigger limit so we get more than 10 results
# We'll filter them first, then slice the top 10 from the filtered set.
results = hybrid_search(client, var, collection_name, limit=100) # e.g., 100 or 200
# results is a tuple: (semantic_results, lexical_results)
semantic_all = results[0]
lexical_all = results[1]
# 2) Filter the entire sets
filtered_semantic = filter_results(semantic_all, country_filter, end_year_range)
filtered_lexical = filter_results(lexical_all, country_filter, end_year_range)
# 3) Now we take the top 10 *after* filtering
# Check user preference
if show_exact_matches:
st.write(f"Showing **Top 10 Lexical Search results** for query: {var}")
# Show the top 10 from filtered_lexical
for res in filtered_lexical[:10]:
project_name = res.payload['metadata'].get('project_name', 'Project Link')
url = res.payload['metadata'].get('url', '#')
st.markdown(f"#### [{project_name}]({url})")
# Snippet logic (80 words)
full_text = res.payload['page_content']
words = full_text.split()
preview_word_count = 80
preview_text = " ".join(words[:preview_word_count])
remainder_text = " ".join(words[preview_word_count:])
st.write(preview_text + ("..." if remainder_text else ""))
# Keywords
top_keywords = extract_top_keywords(full_text, top_n=5)
if top_keywords:
st.markdown(f"_{' · '.join(top_keywords)}_")
# Metadata
metadata = res.payload.get('metadata', {})
countries = metadata.get('countries', "[]")
client_name = metadata.get('client', 'Unknown Client')
start_year = metadata.get('start_year', None)
end_year_ = metadata.get('end_year', None)
try:
c_list = json.loads(countries.replace("'", '"'))
country_names = [get_country_name(code.upper(), region_df) for code in c_list if len(code) == 2]
except json.JSONDecodeError:
country_names = []
start_year_str = f"{int(round(float(start_year)))}" if start_year else "Unknown"
end_year_str = f"{int(round(float(end_year_)))}" if end_year_ else "Unknown"
additional_text = (
f"**{', '.join(country_names)}**, commissioned by **{client_name}**, **{start_year_str}-{end_year_str}**"
)
st.markdown(additional_text)
st.divider()
else:
st.write(f"Showing **Top 10 Semantic Search results** for query: {var}")
# Show the top 10 from filtered_semantic
for res in filtered_semantic[:10]:
project_name = res.payload['metadata'].get('project_name', 'Project Link')
url = res.payload['metadata'].get('url', '#')
st.markdown(f"#### [{project_name}]({url})")
# Snippet logic
full_text = res.payload['page_content']
words = full_text.split()
preview_word_count = 80
preview_text = " ".join(words[:preview_word_count])
remainder_text = " ".join(words[preview_word_count:])
st.write(preview_text + ("..." if remainder_text else ""))
# Keywords
top_keywords = extract_top_keywords(full_text, top_n=5)
if top_keywords:
st.markdown(f"_{' · '.join(top_keywords)}_")
# Metadata
metadata = res.payload.get('metadata', {})
countries = metadata.get('countries', "[]")
client_name = metadata.get('client', 'Unknown Client')
start_year = metadata.get('start_year', None)
end_year_ = metadata.get('end_year', None)
try:
c_list = json.loads(countries.replace("'", '"'))
country_names = [get_country_name(code.upper(), region_df) for code in c_list if len(code) == 2]
except json.JSONDecodeError:
country_names = []
start_year_str = f"{int(round(float(start_year)))}" if start_year else "Unknown"
end_year_str = f"{int(round(float(end_year_)))}" if end_year_ else "Unknown"
additional_text = (
f"**{', '.join(country_names)}**, commissioned by **{client_name}**, **{start_year_str}-{end_year_str}**"
)
st.markdown(additional_text)
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()
|