Spaces:
Sleeping
Sleeping
import streamlit as st | |
import pandas as pd | |
from appStore.prep_data import process_giz_worldwide, remove_duplicates, get_max_end_year, extract_year | |
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, get_regions | |
from appStore.tfidf_extraction import extract_top_keywords | |
from torch import cuda | |
import json | |
from datetime import datetime | |
# get the device to be used either 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 (PROTOTYPE)") | |
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 ###################### | |
# Uncomment these lines to process and embed your data only once. | |
# chunks = process_giz_worldwide() | |
# temp_doc = create_documents(chunks, 'chunks') | |
collection_name = "giz_worldwide" | |
# hybrid_embed_chunks(docs=temp_doc, collection_name=collection_name, del_if_exists=True) | |
################### Hybrid Search ###################################################### | |
client = get_client() | |
print(client.get_collections()) | |
# Get the maximum end_year across the entire collection | |
max_end_year = get_max_end_year(client, collection_name) | |
# Get all unique sub-regions | |
_, unique_sub_regions = get_regions(region_df) | |
# Fetch unique country codes and map to country names | |
def get_country_name_and_region_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("'", '"')) | |
# 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} and {ISO2Code -> SubRegion} | |
country_name_to_code = {} | |
iso_code_to_sub_region = {} | |
for code in country_set: | |
name = get_country_name(code, region_df) | |
sub_region_row = region_df[region_df['alpha-2'] == code] | |
sub_region = sub_region_row['sub-region'].values[0] if not sub_region_row.empty else "Not allocated" | |
country_name_to_code[name] = code | |
iso_code_to_sub_region[code] = sub_region | |
return country_name_to_code, iso_code_to_sub_region | |
# Get country name and region mappings | |
client = get_client() | |
country_name_mapping, iso_code_to_sub_region = get_country_name_and_region_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, col4 = st.columns([1, 1, 1, 4]) | |
# Region filter | |
with col1: | |
region_filter = st.selectbox("Region", ["All/Not allocated"] + sorted(unique_sub_regions)) | |
# Dynamically filter countries based on selected region | |
if region_filter == "All/Not allocated": | |
filtered_country_names = unique_country_names | |
else: | |
filtered_country_names = [ | |
name for name, code in country_name_mapping.items() if iso_code_to_sub_region.get(code) == region_filter | |
] | |
# Country filter | |
with col2: | |
country_filter = st.selectbox("Country", ["All/Not allocated"] + filtered_country_names) | |
# ToDo: Add year filter later if needed (currently commented out) | |
# with col3: | |
# current_year = datetime.now().year | |
# default_start_year = current_year - 5 | |
# end_year_range = st.slider( | |
# "Project End Year", | |
# min_value=2010, | |
# max_value=max_end_year, | |
# value=(default_start_year, max_end_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, region_filter): | |
filtered = [] | |
for r in results: | |
metadata = r.payload.get('metadata', {}) | |
countries = metadata.get('countries', "[]") | |
year_str = metadata.get('end_year') | |
if year_str: | |
extracted = extract_year(year_str) | |
try: | |
end_year_val = int(extracted) if extracted != "Unknown" else 0 | |
except ValueError: | |
end_year_val = 0 | |
else: | |
end_year_val = 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) | |
# Check if any country in the metadata matches the selected region | |
if region_filter != "All/Not allocated": | |
countries_in_region = [code for code in c_list if iso_code_to_sub_region.get(code) == region_filter] | |
else: | |
countries_in_region = c_list | |
if ( | |
(country_filter == "All/Not allocated" or selected_iso_code in c_list) | |
and (region_filter == "All/Not allocated" or countries_in_region) | |
): | |
filtered.append(r) | |
return filtered | |
# Run the search | |
results = hybrid_search(client, var, collection_name, limit=500) | |
semantic_all = results[0] | |
lexical_all = results[1] | |
# Filter out very short content | |
semantic_all = [r for r in semantic_all if len(r.payload["page_content"]) >= 5] | |
lexical_all = [r for r in lexical_all if len(r.payload["page_content"]) >= 5] | |
# Apply a threshold to SEMANTIC results (score >= 0.0) | |
semantic_thresholded = [r for r in semantic_all if r.score >= 0.0] | |
filtered_semantic = filter_results(semantic_thresholded, country_filter, region_filter) | |
filtered_lexical = filter_results(lexical_all, country_filter, region_filter) | |
filtered_semantic_no_dupe = remove_duplicates(filtered_semantic) | |
filtered_lexical_no_dupe = remove_duplicates(filtered_lexical) | |
# Define a helper function to format currency values | |
def format_currency(value): | |
try: | |
# Convert to float then int for formatting (assumes whole numbers) | |
return f"€{int(float(value)):,}" | |
except (ValueError, TypeError): | |
return value | |
# Display Results | |
if show_exact_matches: | |
st.write(f"Showing **Top 15 Lexical Search results** for query: {var}") | |
query_substring = var.strip().lower() | |
lexical_substring_filtered = [] | |
for r in lexical_all: | |
if query_substring in r.payload["page_content"].lower(): | |
lexical_substring_filtered.append(r) | |
filtered_lexical = filter_results(lexical_substring_filtered, country_filter, region_filter) | |
filtered_lexical_no_dupe = remove_duplicates(filtered_lexical) | |
if not filtered_lexical_no_dupe: | |
st.write('No exact matches, consider unchecking "Show only exact matches"') | |
else: | |
for res in filtered_lexical_no_dupe[:15]: | |
metadata = res.payload.get('metadata', {}) | |
# Get title and id; do not format as a link. | |
project_name = metadata.get('project_name', 'Project Link') | |
proj_id = metadata.get('id', 'Unknown') | |
st.markdown(f"#### {project_name} [{proj_id}]") | |
# Build snippet from objectives and descriptions. | |
objectives = metadata.get("objectives", "") | |
desc_de = metadata.get("description.de", "") | |
desc_en = metadata.get("description.en", "") | |
description = desc_de if desc_de else desc_en | |
full_snippet = f"Objective: {objectives} Description: {description}" | |
preview_limit = 400 # preview limit in characters | |
preview_snippet = full_snippet if len(full_snippet) <= preview_limit else full_snippet[:preview_limit] + "..." | |
# Using HTML to add a tooltip with the full snippet text. | |
st.markdown(f'<span title="{full_snippet}">{preview_snippet}</span>', unsafe_allow_html=True) | |
# Keywords remain the same. | |
full_text = res.payload['page_content'] | |
top_keywords = extract_top_keywords(full_text, top_n=5) | |
if top_keywords: | |
st.markdown(f"_{' · '.join(top_keywords)}_") | |
# Metadata: get client, duration and budget details. | |
client_name = metadata.get('client', 'Unknown Client') | |
start_year = metadata.get('start_year', None) | |
end_year = metadata.get('end_year', None) | |
total_volume = metadata.get('total_volume', "Unknown") | |
total_project = metadata.get('total_project', "Unknown") | |
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" | |
formatted_project_budget = format_currency(total_project) | |
formatted_total_volume = format_currency(total_volume) | |
additional_text = ( | |
f"Commissioned by **{client_name}**\n" | |
f"Projekt duration **{start_year_str}-{end_year_str}**\n" | |
f"Budget: Project: **{formatted_project_budget}**, total volume: **{formatted_total_volume}**" | |
) | |
st.markdown(additional_text) | |
st.divider() | |
else: | |
st.write(f"Showing **Top 15 Semantic Search results** for query: {var}") | |
if not filtered_semantic_no_dupe: | |
st.write("No relevant results found.") | |
else: | |
for res in filtered_semantic_no_dupe[:15]: | |
metadata = res.payload.get('metadata', {}) | |
project_name = metadata.get('project_name', 'Project Link') | |
proj_id = metadata.get('id', 'Unknown') | |
st.markdown(f"#### {project_name} [{proj_id}]") | |
# Build snippet from objectives and descriptions. | |
objectives = metadata.get("objectives", "") | |
desc_de = metadata.get("description.de", "") | |
desc_en = metadata.get("description.en", "") | |
description = desc_de if desc_de else desc_en | |
full_snippet = f"Objective: {objectives} Description: {description}" | |
preview_limit = 400 | |
preview_snippet = full_snippet if len(full_snippet) <= preview_limit else full_snippet[:preview_limit] + "..." | |
st.markdown(f'<span title="{full_snippet}">{preview_snippet}</span>', unsafe_allow_html=True) | |
# Keywords | |
full_text = res.payload['page_content'] | |
top_keywords = extract_top_keywords(full_text, top_n=5) | |
if top_keywords: | |
st.markdown(f"_{' · '.join(top_keywords)}_") | |
client_name = metadata.get('client', 'Unknown Client') | |
start_year = metadata.get('start_year', None) | |
end_year = metadata.get('end_year', None) | |
total_volume = metadata.get('total_volume', "Unknown") | |
total_project = metadata.get('total_project', "Unknown") | |
start_year_str = extract_year(start_year) if start_year else "Unknown" | |
end_year_str = extract_year(end_year) if end_year else "Unknown" | |
formatted_project_budget = format_currency(total_project) | |
formatted_total_volume = format_currency(total_volume) | |
additional_text = ( | |
f"Commissioned by **{client_name}**\n" | |
f"Projekt duration **{start_year_str}-{end_year_str}**\n" | |
f"Budget: Project: **{formatted_project_budget}**, total volume: **{formatted_total_volume}**" | |
) | |
st.markdown(additional_text) | |
st.divider() | |
# Uncomment the following lines if you need to debug by listing raw results. | |
# 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() | |