File size: 19,148 Bytes
0130713
1bfcfd5
c2f0c5c
5c789bc
c258cbb
5a1352d
 
c567921
8fdd4c1
8225c93
cb359de
9d9ace2
53d69f4
 
08da20e
 
 
1bfcfd5
94a0b34
08da20e
 
 
 
 
1bfcfd5
 
 
bc8ecee
d237e1f
 
1bfcfd5
94a0b34
 
035b045
 
 
 
1bfcfd5
 
 
 
f2efbb4
1bfcfd5
 
 
 
 
035b045
 
 
1bfcfd5
 
 
367acc4
7b37585
 
 
 
 
 
367acc4
7b37585
 
 
 
 
 
 
 
 
367acc4
7b37585
540cd3a
 
7b37585
 
 
 
 
 
 
94a0b34
 
 
 
 
 
7b37585
 
 
367acc4
7b37585
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
390ed12
 
 
 
 
367acc4
 
 
 
 
 
 
7b37585
367acc4
7b37585
367acc4
7b37585
 
 
367acc4
f5dac9b
0130713
367acc4
3346614
7b37585
e4b8dd5
367acc4
88e2023
 
 
 
9392032
47177b9
 
7da963b
47177b9
7da963b
47177b9
c567921
7da963b
5170600
b08d54a
5a1352d
 
48484fb
8fdd4c1
 
d845358
8fdd4c1
d845358
 
 
 
 
 
043c4b1
 
d845358
 
043c4b1
8fdd4c1
043c4b1
 
8fdd4c1
 
043c4b1
8fdd4c1
 
d845358
88e2023
8fdd4c1
367acc4
d845358
367acc4
bc8ecee
d845358
7b37585
367acc4
 
 
 
 
d845358
367acc4
77a1d81
 
7b37585
 
 
 
 
d845358
367acc4
d845358
 
367acc4
 
d6bab54
 
 
367acc4
 
d6bab54
5ee7936
d6bab54
7b37585
 
367acc4
 
d6bab54
 
a5158de
 
 
 
 
367acc4
 
7b37585
 
 
 
 
 
 
d6bab54
 
 
7b37585
 
82254d1
d6bab54
 
 
e323495
5fc3c7d
1aa01e9
5fc3c7d
 
 
67f6d38
7b37585
 
1aa01e9
 
 
 
 
a5158de
1aa01e9
bc8ecee
2be935d
1061240
 
 
 
a5158de
 
 
 
5c4bc96
a5158de
e323495
47177b9
 
7b37585
 
 
 
 
 
a5158de
d6bab54
 
 
47177b9
5c789bc
 
 
 
 
 
 
47177b9
7b37585
47177b9
 
 
 
 
 
 
 
 
1aa01e9
5c789bc
 
1aa01e9
 
 
 
 
5c789bc
 
 
bc8ecee
5c789bc
 
 
 
 
1aa01e9
 
 
5c789bc
d6bab54
 
82254d1
7b37585
 
 
d6bab54
 
 
d845358
e323495
1bfcfd5
1aa01e9
1bfcfd5
 
d23e52b
1bfcfd5
77a1d81
7b37585
 
 
1061240
bc8ecee
2be935d
1061240
 
 
 
77a1d81
 
 
 
5c4bc96
77a1d81
e323495
47177b9
 
7b37585
 
 
 
 
 
d6bab54
 
47177b9
5c789bc
 
 
 
 
 
 
47177b9
7b37585
47177b9
 
 
 
 
 
 
 
 
5c789bc
 
 
1aa01e9
 
 
 
 
5c789bc
 
 
bc8ecee
5c789bc
 
 
 
 
1aa01e9
 
 
5c789bc
d6bab54
5c789bc
47177b9
 
 
 
 
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
import streamlit as st
import requests
import pandas as pd
import re
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



#model_config = getconfig("model_params.cfg")
###########
# ToDo move functions to utils and model specifications to config file!
# Configuration for the dedicated model
DEDICATED_MODEL = "meta-llama/Llama-3.1-8B-Instruct"
DEDICATED_ENDPOINT = "https://qu2d8m6dmsollhly.us-east-1.aws.endpoints.huggingface.cloud"
# Write access token from the settings
WRITE_ACCESS_TOKEN = st.secrets["Llama_3_1"]

def get_rag_answer(query, top_results):
    context = "\n\n".join([res.payload["page_content"] for res in top_results])
    max_context_chars = 13500  
    if len(context) > max_context_chars:
        context = context[:max_context_chars]
    prompt = (
        "You are a project portfolio adviser at the development cooperation GIZ. "
        "Using the following context, answer the question precisely. "
        "Only output the final answer below, without repeating the context or question.\n\n"
        f"Context:\n{context}\n\n"
        f"Question: {query}\n\n"
        "Answer:"
    )
    headers = {"Authorization": f"Bearer {WRITE_ACCESS_TOKEN}"}
    payload = {
        "inputs": prompt,
        "parameters": {"max_new_tokens": 220}
    }
    response = requests.post(DEDICATED_ENDPOINT, headers=headers, json=payload)
    if response.status_code == 200:
        result = response.json()
        answer = result[0]["generated_text"]
        if "Answer:" in answer:
            answer = answer.split("Answer:")[-1].strip()
        return answer
    else:
        return f"Error in generating answer: {response.text}"

# Helper: Format project id (e.g., "201940485" -> "2019.4048.5")
def format_project_id(pid):
    s = str(pid)
    if len(s) > 5:
        return s[:4] + "." + s[4:-1] + "." + s[-1]
    return s

# Helper: Compute title from metadata using name.en (or name.de if empty)
def compute_title(metadata):
    name_en = metadata.get("name.en", "").strip()
    name_de = metadata.get("name.de", "").strip()
    base = name_en if name_en else name_de
    pid = metadata.get("id", "")
    if base and pid:
        return f"{base} [{format_project_id(pid)}]"
    return base or "No Title"

# Helper: Get CRS filter options from all documents
@st.cache_data
def get_crs_options(_client, collection_name):
    results = hybrid_search(_client, "", collection_name)
    all_results = results[0] + results[1]
    crs_set = set()
    for res in all_results:
        metadata = res.payload.get('metadata', {})
        crs_key = metadata.get("crs_key", "").strip()
        crs_value = metadata.get("crs_value", "").strip()
        if crs_key or crs_value:
            # Convert crs_value to integer if possible:
            try:
                crs_int = int(float(crs_value))
            except:
                crs_int = crs_value
            crs_combined = f"{crs_key}: {crs_int}"
            crs_set.add(crs_combined)
    return sorted(crs_set)

# Revised filter_results: Allow missing end_year or CRS; enforce CRS only when present.
def filter_results(results, country_filter, region_filter, end_year_range, crs_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

        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 = []

        selected_iso_code = country_name_mapping.get(country_filter, None)
        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

        crs_key = metadata.get("crs_key", "").strip()
        crs_value = metadata.get("crs_value", "").strip()
        try:
            crs_int = int(float(crs_value))
        except:
            crs_int = crs_value
        crs_combined = f"{crs_key}: {crs_int}" if (crs_key or crs_value) else ""
        # Only enforce CRS filter if result has a CRS value.
        if crs_filter != "All/Not allocated" and crs_combined:
            if crs_filter != crs_combined:
                continue

        # Allow projects with no valid end_year to pass (if end_year_val is 0)
        year_ok = True if end_year_val == 0 else (end_year_range[0] <= end_year_val <= end_year_range[1])

        if ((country_filter == "All/Not allocated" or (selected_iso_code and selected_iso_code in c_list))
            and (region_filter == "All/Not allocated" or countries_in_region)
            and year_ok):
            filtered.append(r)
    return filtered

# Get the device to be used (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 Question")


# 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, del_if_exists=True)

################### Hybrid Search #####################################################
client = get_client()
print(client.get_collections())
max_end_year = get_max_end_year(client, collection_name)
_, unique_sub_regions = get_regions(region_df)

@st.cache_data
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("'", '"'))
            two_digit_codes = [code.upper() for code in country_list if len(code) == 2]
            country_set.update(two_digit_codes)
        except json.JSONDecodeError:
            pass
    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

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())

# Layout filters in columns
col1, col2, col3, col4 = st.columns([1, 1, 1, 1])
with col1:
    region_filter = st.selectbox("Region", ["All/Not allocated"] + sorted(unique_sub_regions))
# Compute filtered_country_names based on region_filter:
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]
with col2:
    country_filter = st.selectbox("Country", ["All/Not allocated"] + filtered_country_names)
with col3:
    current_year = datetime.now().year
    default_start_year = current_year - 4
    end_year_range = st.slider("Project End Year", min_value=2010, max_value=max_end_year, value=(default_start_year, max_end_year))
with col4:
    crs_options = ["All/Not allocated"] + get_crs_options(client, collection_name)
    crs_filter = st.selectbox("CRS", crs_options)

# Checkbox for exact matches
show_exact_matches = st.checkbox("Show only exact matches", value=False)

# Run the search
results = hybrid_search(client, var, collection_name, limit=500)
semantic_all = results[0]
lexical_all = results[1]

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]

semantic_thresholded = [r for r in semantic_all if r.score >= 0.0]

filtered_semantic = filter_results(semantic_thresholded, country_filter, region_filter, end_year_range, crs_filter)
filtered_lexical = filter_results(lexical_all, country_filter, region_filter, end_year_range, crs_filter)

filtered_semantic_no_dupe = remove_duplicates(filtered_semantic)
filtered_lexical_no_dupe = remove_duplicates(filtered_lexical)

def format_currency(value):
    try:
        return f"€{int(float(value)):,}"
    except (ValueError, TypeError):
        return value

# Helper to highlight query matches (case-insensitive)
def highlight_query(text, query):
    pattern = re.compile(re.escape(query), re.IGNORECASE)
    return pattern.sub(lambda m: f"**{m.group(0)}**", text)

###############################
# Display Lexical Results Branch
###############################
if show_exact_matches:
    st.write(f"Showing **Top 15 Lexical Search results** for query: {var}")
    query_substring = var.strip().lower()
    lexical_substring_filtered = [r for r in lexical_all if query_substring in r.payload["page_content"].lower()]
    filtered_lexical = filter_results(lexical_substring_filtered, country_filter, region_filter, end_year_range, crs_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:
        top_results = filtered_lexical_no_dupe[:10]
        rag_answer = get_rag_answer(var, top_results)
        st.markdown(f"**{var}**")
        st.write(rag_answer)
        st.divider()
        for res in top_results:
            metadata = res.payload.get('metadata', {})
            if "title" not in metadata:
                metadata["title"] = compute_title(metadata)
            # Highlight query in red and bold (allow HTML)
            display_title = (
                st.markdown(highlight_query(metadata["title"], var), unsafe_allow_html=True)
                if var.strip() else metadata["title"]
            )
            proj_id = metadata.get('id', 'Unknown')
            st.markdown(f"#### {metadata['title']}")
            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)
            total_volume = metadata.get('total_volume', "Unknown")
            total_project = metadata.get('total_project', "Unknown")
            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"{objectives} {description}"
            words = full_snippet.split()
            preview_word_count = 90
            preview_text = " ".join(words[:preview_word_count])
            remainder_text = " ".join(words[preview_word_count:])
            preview_text = highlight_query(preview_text, var) if var.strip() else preview_text
            st.write(preview_text)
            if remainder_text:
                with st.expander("Show more"):
                    st.write(remainder_text)
            
            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)}_")
            
            # Format year range and budget info
            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)
            
            # Compute matched country names (as before)
            try:
                c_list = json.loads(metadata.get('countries', "[]").replace("'", '"'))
            except json.JSONDecodeError:
                c_list = []
            matched_countries = []
            for code in c_list:
                if len(code) == 2:
                    resolved_name = get_country_name(code.upper(), region_df)
                    if resolved_name.upper() != code.upper():
                        matched_countries.append(resolved_name)
            
            # Compute CRS combined value as integer
            crs_key = metadata.get("crs_key", "").strip()
            crs_value = metadata.get("crs_value", "").strip()
            try:
                crs_int = int(float(crs_value))
            except:
                crs_int = crs_value
            crs_combined = f"{crs_key}: {crs_int}" if (crs_key or crs_value) else "Unknown"
            
            # Build the additional text with original details, then add Sector and contact.
            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}**\n"
                f"Country: **{', '.join(matched_countries)}**\n"
                f"Sector: **{crs_combined}**"
            )
            #contact = metadata.get("contact", "").strip()
            #if contact and contact.lower() != "[email protected]":
            #    additional_text += f" | Contact: **{contact}**"
            
            st.markdown(additional_text)
            st.divider()

###############################
# Display Semantic Results Branch
###############################
else:
    if not filtered_semantic_no_dupe:
        st.write("No relevant results found.")
    else:
        top_results = filtered_semantic_no_dupe[:10]
        rag_answer = get_rag_answer(var, top_results)
        st.markdown(f"**{var}**")
        st.write(rag_answer)
        st.divider()
        st.write(f"Showing **Top 15 Semantic Search results** for query: {var}")
        for res in top_results:
            metadata = res.payload.get('metadata', {})
            if "title" not in metadata:
                metadata["title"] = compute_title(metadata)
            display_title = metadata["title"]
            st.markdown(f"#### {display_title}")
            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)
            total_volume = metadata.get('total_volume', "Unknown")
            total_project = metadata.get('total_project', "Unknown")
            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"{objectives} {description}"
            words = full_snippet.split()
            preview_word_count = 90
            preview_text = " ".join(words[:preview_word_count])
            remainder_text = " ".join(words[preview_word_count:])
            st.write(preview_text)
            if remainder_text:
                with st.expander("Show more"):
                    st.write(remainder_text)
            
            top_keywords = extract_top_keywords(res.payload['page_content'], top_n=5)
            if top_keywords:
                st.markdown(f"_{' · '.join(top_keywords)}_")
            
            # Format year range and budget info
            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)
            
            # Compute matched country names (as before)
            try:
                c_list = json.loads(metadata.get('countries', "[]").replace("'", '"'))
            except json.JSONDecodeError:
                c_list = []
            matched_countries = []
            for code in c_list:
                if len(code) == 2:
                    resolved_name = get_country_name(code.upper(), region_df)
                    if resolved_name.upper() != code.upper():
                        matched_countries.append(resolved_name)
            
            # Compute CRS combined value
            crs_key = metadata.get("crs_key", "").strip()
            crs_value = metadata.get("crs_value", "").strip()
            try:
                crs_int = int(float(crs_value))
            except:
                crs_int = crs_value
            crs_combined = f"{crs_key}: {crs_int}" if (crs_key or crs_value) else "Unknown"
            
            # Build the additional text with original details, then add Sector and contact.
            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}**\n"
                f"Country: **{', '.join(matched_countries)}**\n"
                f"Sector: **{crs_combined}**"
            )
            #contact = metadata.get("contact", "").strip()
            #if contact and contact.lower() != "[email protected]":
            #    additional_text += f" | Contact: **{contact}**"
            
            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()