Spaces:
GIZ
/
Running on CPU Upgrade

ppsingh commited on
Commit
941faf0
·
1 Parent(s): 57ad147

Readme update and cleanup

Browse files
README.md CHANGED
@@ -9,28 +9,29 @@ app_file: app.py
9
  fullWidth: true
10
  pinned: false
11
  startup_duration_timeout: 1h
 
 
12
  models:
13
  - BAAI/bge-m3
14
  - BAAI/bge-reranker-v2-m3
15
  - meta-llama/Llama-3.1-8B-Instruct
16
  ---
17
- short_description: AI-powered conversational assistant for EU Deforestation Regulation compliance
18
- license: apache-2.0
19
 
20
 
21
  ## Technical Documentation of the system in accordance with EU AI Act
22
 
23
- **System Name:** EUDR ChatBot
24
 
25
  **Provider / Supplier:** GIZ Data Service Center
26
 
27
- **As of:** July 2025
28
 
29
  ## 1. General Description of the System
30
 
31
  EUDR Bot is an AI-powered conversational assistant designed to help you understand compliance with and analyze the EU Deforestation Regulation. This tool leverages advanced language models to help you get clear and structured answers about EUDR requirements, compliance procedures, and regulatory guidance.
32
 
33
- It combines a generative language assistant with a knowledge base implemented via Retrieval-Augmented Generation (RAG). The scope and functionality of the tool is focused on EU Deforestation Regulation compliance and related documentation.
34
 
35
  ## 2. Models Used
36
 
@@ -46,6 +47,10 @@ It combines a generative language assistant with a knowledge base implemented vi
46
  - **Model Name:** [BAAI/bge-reranker-v2-m3](https://huggingface.co/BAAI/bge-reranker-v2-m3)
47
  - **Model Source:** Local Instance
48
 
 
 
 
 
49
  ## 3. Model Training Data
50
 
51
  All the models mentioned above are being consumed without any fine-tuning or training being performed by the developer team of EUDR Bot. And hence there is no training data which had been used by the development team of EUDR Bot.
@@ -57,7 +62,7 @@ All the models mentioned above are being consumed without any fine-tuning or tra
57
  - **Embedding Dimension:** 1024
58
  - **Vector Database:** Qdrant (via API)
59
  - **Framework:** Langchain (custom RAG pipeline)
60
- - **Top-k:** 5 relevant text segments per query
61
 
62
  ## 5. System Limitations and Non-Purposes
63
 
@@ -71,14 +76,14 @@ All the models mentioned above are being consumed without any fine-tuning or tra
71
  - The user interface clearly indicates the use of a generative AI model.
72
  - An explanation of the RAG method is included.
73
  - We collect usage statistics as detailed in Disclaimer tab of the app along with the explicit display in the user interface of the tool.
74
- - Feedback mechanism available (via https://huggingface.co/spaces/GIZ/eudr_assistant/discussions/new).
75
 
76
  ## 7. Monitoring, Feedback, and Incident Reporting
77
 
78
- - User can provide feedback via UI by giving (Thumbs-up or down to AI-Generated answer). Alternatively for more detailed feedback please use https://huggingface.co/spaces/GIZ/eudr_assistant/discussions/new to report any issue.
79
  - Technical development is carried out by the GIZ Data Service Center.
80
  - No automated bias detection – but low risk due to content restrictions.
81
 
82
  ## 8. Contact
83
 
84
- For any questions, please contact via https://huggingface.co/spaces/GIZ/eudr_assistant/discussions/new or send us email to [email protected]
 
9
  fullWidth: true
10
  pinned: false
11
  startup_duration_timeout: 1h
12
+ license: apache-2.0
13
+ short_description: AI-powered conversational assistant for EU Deforestation Regulation compliance
14
  models:
15
  - BAAI/bge-m3
16
  - BAAI/bge-reranker-v2-m3
17
  - meta-llama/Llama-3.1-8B-Instruct
18
  ---
19
+
 
20
 
21
 
22
  ## Technical Documentation of the system in accordance with EU AI Act
23
 
24
+ **System Name:** EUDR Chatbot
25
 
26
  **Provider / Supplier:** GIZ Data Service Center
27
 
28
+ **As of:** September 2025
29
 
30
  ## 1. General Description of the System
31
 
32
  EUDR Bot is an AI-powered conversational assistant designed to help you understand compliance with and analyze the EU Deforestation Regulation. This tool leverages advanced language models to help you get clear and structured answers about EUDR requirements, compliance procedures, and regulatory guidance.
33
 
34
+ It combines a generative language assistant with a knowledge base implemented via Retrieval-Augmented Generation (RAG). In addition to the RAG, the tool also provide quick analysis on the geojson of plot by leveraging the [Whisp](https://openforis.org/solutions/whisp/). The scope and functionality of the tool is focused on EU Deforestation Regulation compliance and related documentation in context of 'Ecuador' and 'Guatemala' only.
35
 
36
  ## 2. Models Used
37
 
 
47
  - **Model Name:** [BAAI/bge-reranker-v2-m3](https://huggingface.co/BAAI/bge-reranker-v2-m3)
48
  - **Model Source:** Local Instance
49
 
50
+ ### External API's
51
+ - **Whisp Info**: https://openforis.org/solutions/whisp/
52
+ - **API Endpoint** https://whisp.openforis.org/documentation/api-guide
53
+
54
  ## 3. Model Training Data
55
 
56
  All the models mentioned above are being consumed without any fine-tuning or training being performed by the developer team of EUDR Bot. And hence there is no training data which had been used by the development team of EUDR Bot.
 
62
  - **Embedding Dimension:** 1024
63
  - **Vector Database:** Qdrant (via API)
64
  - **Framework:** Langchain (custom RAG pipeline)
65
+ - **Top-k:** 10 relevant text segments per query
66
 
67
  ## 5. System Limitations and Non-Purposes
68
 
 
76
  - The user interface clearly indicates the use of a generative AI model.
77
  - An explanation of the RAG method is included.
78
  - We collect usage statistics as detailed in Disclaimer tab of the app along with the explicit display in the user interface of the tool.
79
+ - Feedback mechanism available (via https://huggingface.co/spaces/GIZ/Asistente_EUDR/discussions/new).
80
 
81
  ## 7. Monitoring, Feedback, and Incident Reporting
82
 
83
+ - User can provide feedback via UI by giving (Thumbs-up or down to AI-Generated answer). Alternatively for more detailed feedback please use https://huggingface.co/spaces/GIZ/Asistente_EUDR/discussions/new to report any issue.
84
  - Technical development is carried out by the GIZ Data Service Center.
85
  - No automated bias detection – but low risk due to content restrictions.
86
 
87
  ## 8. Contact
88
 
89
+ For any questions, please contact via https://huggingface.co/spaces/GIZ/Asistente_EUDR/discussions/new or send us email to [email protected]
app1.py DELETED
@@ -1,763 +0,0 @@
1
- import gradio as gr
2
- import pandas as pd
3
- import logging
4
- import asyncio
5
- import os
6
- import time
7
- from uuid import uuid4
8
- from datetime import datetime, timedelta
9
- from pathlib import Path
10
- from huggingface_hub import CommitScheduler, HfApi
11
- from auditqa.sample_questions import QUESTIONS
12
- from auditqa.reports import files, report_list, new_files, new_report_list
13
- from auditqa.process_chunks import load_chunks, getconfig, get_local_qdrant
14
- from auditqa.retriever import get_context
15
- from auditqa.reader import nvidia_client, dedicated_endpoint, serverless_api, inf_provider
16
- from auditqa.utils import make_html_source, parse_output_llm_with_sources, save_logs, get_message_template, get_client_location, get_client_ip, get_platform_info
17
- from dotenv import load_dotenv
18
- load_dotenv()
19
- from threading import Lock
20
- from gradio.routes import Request
21
- import json
22
- #import platform
23
- #print(platform.python_version())
24
-
25
- # fetch tokens and model config params
26
- SPACES_LOG = os.environ["SPACES_LOG"]
27
- #audit_space = os.environ["audit_space"]
28
- model_config = getconfig("model_params.cfg")
29
-
30
- # create the local logs repo
31
- JSON_DATASET_DIR = Path("json_dataset")
32
- JSON_DATASET_DIR.mkdir(parents=True, exist_ok=True)
33
- JSON_DATASET_PATH = JSON_DATASET_DIR / f"logs-{uuid4()}.json"
34
-
35
- # the logs are written to dataset repo periodically from local logs
36
- # https://huggingface.co/spaces/Wauplin/space_to_dataset_saver
37
- scheduler = CommitScheduler(
38
- repo_id="GIZ/spaces_logs",
39
- repo_type="dataset",
40
- folder_path=JSON_DATASET_DIR,
41
- path_in_repo="audit_chatbot",
42
- token=SPACES_LOG )
43
-
44
- #####--------------- VECTOR STORE -------------------------------------------------
45
- # reports contain the already created chunks from Markdown version of pdf reports
46
- # document processing was done using : https://github.com/axa-group/Parsr
47
- # We need to create the local vectorstore collection once using load_chunks
48
- # vectorestore colection are stored on persistent storage so this needs to be run only once
49
- # hence, comment out line below when creating for first time
50
- #vectorstores = load_chunks()
51
- # once the vectore embeddings are created we will use qdrant client to access these
52
- #try:
53
- vectorstores = get_local_qdrant()
54
- #except Exception as e:
55
- # api = HfApi()
56
- # api.restart_space(repo_id = "GIZ/audit_assistant", token=audit_space)
57
-
58
- #####---------------------CHAT-----------------------------------------------------
59
- def start_chat(query,history):
60
- history = history + [(query,None)]
61
- history = [tuple(x) for x in history]
62
- return (gr.update(interactive = False),gr.update(selected=1),history)
63
-
64
- def finish_chat():
65
- return (gr.update(interactive = True,value = ""))
66
-
67
- def submit_feedback(feedback, logs_data):
68
- """Handle feedback submission"""
69
- try:
70
- if logs_data is None:
71
- return gr.update(visible=False), gr.update(visible=True)
72
-
73
- session_id = logs_data.get("session_id")
74
- if session_id:
75
- # Update session last_activity to now
76
- session_manager.update_session(session_id)
77
- # Compute duration from the session manager and update the log.
78
- logs_data["session_duration_seconds"] = session_manager.get_session_duration(session_id)
79
-
80
- # Now save the (feedback) log record
81
- save_logs(scheduler, JSON_DATASET_PATH, logs_data, feedback)
82
- return gr.update(visible=False), gr.update(visible=True)
83
- except Exception as e:
84
- return gr.update(visible=False), gr.update(visible=True)
85
-
86
-
87
- # Session Manager added (track session duration, location, and platform)
88
- class SessionManager:
89
- def __init__(self):
90
- self.sessions = {}
91
-
92
- def create_session(self, client_ip, user_agent):
93
- session_id = str(uuid4())
94
- self.sessions[session_id] = {
95
- 'start_time': datetime.now(),
96
- 'last_activity': datetime.now(),
97
- 'client_ip': client_ip,
98
- 'location_info': get_client_location(client_ip),
99
- 'platform_info': get_platform_info(user_agent)
100
- }
101
- return session_id
102
-
103
- def update_session(self, session_id):
104
- if session_id in self.sessions:
105
- self.sessions[session_id]['last_activity'] = datetime.now()
106
-
107
- def get_session_duration(self, session_id):
108
- if session_id in self.sessions:
109
- start = self.sessions[session_id]['start_time']
110
- last = self.sessions[session_id]['last_activity']
111
- return (last - start).total_seconds()
112
- return 0
113
-
114
- def get_session_data(self, session_id):
115
- return self.sessions.get(session_id)
116
-
117
- # Initialize session manager
118
- session_manager = SessionManager()
119
-
120
- async def chat(query,history, method, sources,reports,subtype, client_ip=None, session_id = None, request:gr.Request = None):
121
- """taking a query and a message history, use a pipeline (reformulation, retriever, answering)
122
- to yield a tuple of:(messages in gradio format/messages in langchain format, source documents)
123
- """
124
-
125
- if not session_id:
126
- user_agent = request.headers.get('User-Agent','') if request else ''
127
- session_id = session_manager.create_session(client_ip, user_agent)
128
- else:
129
- session_manager.update_session(session_id)
130
-
131
- # Get session id
132
- session_data = session_manager.get_session_data(session_id)
133
- session_duration = session_manager.get_session_duration(session_id)
134
-
135
- print(f">> NEW QUESTION : {query}")
136
- print(f"history:{history}")
137
- print(f"sources:{sources}")
138
- print(f"reports:{reports}")
139
- print(f"subtype:{subtype}")
140
- #print(f"year:{year}")
141
- docs_html = ""
142
- output_query = ""
143
- if method == "Search by Report Name":
144
- if len(reports) == 0:
145
- warning_message = "⚠️ **No Report Selected.** Please select the relevant reports."
146
- history[-1] = (query, warning_message)
147
- # Update logs with the warning instead of answer
148
- logs_data = {
149
- "record_id": str(uuid4()),
150
- "session_id": session_id,
151
- "session_duration_seconds": session_duration,
152
- "client_location": session_data['location_info'],
153
- "platform": session_data['platform_info'],
154
- "question": query,
155
- "retriever": model_config.get('retriever','MODEL'),
156
- "endpoint_type": model_config.get('reader','TYPE'),
157
- "reader": model_config.get('reader','NVIDIA_MODEL'),
158
- "answer": warning_message,
159
- "no_results": True # Flag to indicate no results were found
160
- }
161
- yield [tuple(x) for x in history], "", logs_data, session_id
162
- # Save log for the warning response
163
- save_logs(scheduler, JSON_DATASET_PATH, logs_data)
164
- return
165
- else:
166
- if sources is None and subtype is None:
167
- warning_message = "⚠️ **No Report Selected.** Please select the relevant reports."
168
- history[-1] = (query, warning_message)
169
- # Update logs with the warning instead of answer
170
- logs_data = {
171
- "record_id": str(uuid4()),
172
- "session_id": session_id,
173
- "session_duration_seconds": session_duration,
174
- "client_location": session_data['location_info'],
175
- "platform": session_data['platform_info'],
176
- "question": query,
177
- "retriever": model_config.get('retriever','MODEL'),
178
- "endpoint_type": model_config.get('reader','TYPE'),
179
- "reader": model_config.get('reader','NVIDIA_MODEL'),
180
- "answer": warning_message,
181
- "no_results": True # Flag to indicate no results were found
182
- }
183
- yield [tuple(x) for x in history], "", logs_data, session_id
184
- # Save log for the warning response
185
- save_logs(scheduler, JSON_DATASET_PATH, logs_data)
186
- return
187
-
188
-
189
- ##------------------------fetch collection from vectorstore------------------------------
190
- vectorstore = vectorstores["docling"]
191
-
192
- ##------------------------------get context----------------------------------------------
193
-
194
- ### adding for assessing computation time
195
- start_time = time.time()
196
- context_retrieved = get_context(vectorstore=vectorstore,query=query,reports=reports,
197
- sources=sources,subtype=subtype)
198
- end_time = time.time()
199
- print("Time for retriever:",end_time - start_time)
200
-
201
-
202
- if not context_retrieved or len(context_retrieved) == 0:
203
- warning_message = "⚠️ **No relevant information was found in the audit reports pertaining your query.** Please try rephrasing your question or selecting different report filters."
204
- history[-1] = (query, warning_message)
205
- # Update logs with the warning instead of answer
206
- logs_data = {
207
- "record_id": str(uuid4()),
208
- "session_id": session_id,
209
- "session_duration_seconds": session_duration,
210
- "client_location": session_data['location_info'],
211
- "platform": session_data['platform_info'],
212
- "question": query,
213
- "retriever": model_config.get('retriever','MODEL'),
214
- "endpoint_type": model_config.get('reader','TYPE'),
215
- "reader": model_config.get('reader','NVIDIA_MODEL'),
216
- "answer": warning_message,
217
- "no_results": True # Flag to indicate no results were found
218
- }
219
- yield [tuple(x) for x in history], "", logs_data, session_id
220
- # Save log for the warning response
221
- save_logs(scheduler, JSON_DATASET_PATH, logs_data)
222
- return
223
- context_retrieved_formatted = "||".join(doc.page_content for doc in context_retrieved)
224
- context_retrieved_lst = [doc.page_content for doc in context_retrieved]
225
-
226
- ##------------------- -------------Define Prompt-------------------------------------------
227
- SYSTEM_PROMPT = """
228
- You are AuditQ&A, an AI Assistant created by Auditors and Data Scientist. \
229
- You are given a question and extracted passages of the consolidated/departmental/thematic focus audit reports.\
230
- Provide a clear and structured answer based on the passages/context provided and the guidelines.
231
- Guidelines:
232
- - Passeges are provided as comma separated list of strings
233
- - If the passages have useful facts or numbers, use them in your answer.
234
- - When you use information from a passage, mention where it came from by using [Doc i] at the end of the sentence. i stands for the number of the document.
235
- - Do not use the sentence 'Doc i says ...' to say where information came from.
236
- - If the same thing is said in more than one document, you can mention all of them like this: [Doc i, Doc j, Doc k]
237
- - Do not just summarize each passage one by one. Group your summaries to highlight the key parts in the explanation.
238
- - If it makes sense, use bullet points and lists to make your answers easier to understand.
239
- - You do not need to use every passage. Only use the ones that help answer the question.
240
- - If the documents do not have the information needed to answer the question, just say you do not have enough information.
241
- """
242
-
243
- USER_PROMPT = """Passages:
244
- {context}
245
- -----------------------
246
- Question: {question} - Explained to audit expert
247
- Answer in english with the passages citations:
248
- """.format(context = context_retrieved_lst, question=query)
249
-
250
- ##-------------------- apply message template ------------------------------
251
- messages = get_message_template(model_config.get('reader','TYPE'),SYSTEM_PROMPT,USER_PROMPT)
252
-
253
- ## -----------------Prepare HTML for displaying source documents --------------
254
- docs_html = []
255
- for i, d in enumerate(context_retrieved, 1):
256
- docs_html.append(make_html_source(d, i))
257
- docs_html = "".join(docs_html)
258
-
259
- ##-----------------------get answer from endpoints------------------------------
260
- answer_yet = ""
261
-
262
- logs_data = {
263
- "record_id": str(uuid4()), # Add unique record ID
264
- "session_id": session_id,
265
- "session_duration_seconds": session_duration,
266
- "client_location": session_data['location_info'],
267
- "platform": session_data['platform_info'],
268
- "system_prompt": SYSTEM_PROMPT,
269
- "sources": sources,
270
- "reports": reports,
271
- "subtype": subtype,
272
- #"year": year,
273
- "question": query,
274
- "retriever": model_config.get('retriever','MODEL'),
275
- "endpoint_type": model_config.get('reader','TYPE'),
276
- "reader": model_config.get('reader','NVIDIA_MODEL'),
277
- "docs": [doc.page_content for doc in context_retrieved],
278
- }
279
-
280
-
281
- if model_config.get('reader','TYPE') == 'NVIDIA':
282
- chat_model = nvidia_client()
283
- async def process_stream():
284
- nonlocal answer_yet # Use the outer scope's answer_yet variable
285
- # Without nonlocal, Python would create a new local variable answer_yet inside process_stream(),
286
- # instead of modifying the one from the outer scope.
287
- # Iterate over the streaming response chunks
288
- response = chat_model.chat_completion(
289
- model=model_config.get("reader","NVIDIA_MODEL"),
290
- messages=messages,
291
- stream=True,
292
- max_tokens=int(model_config.get('reader','MAX_TOKENS')),
293
- )
294
- for message in response:
295
- token = message.choices[0].delta.content
296
- if token:
297
- answer_yet += token
298
- parsed_answer = parse_output_llm_with_sources(answer_yet)
299
- history[-1] = (query, parsed_answer)
300
- logs_data["answer"] = parsed_answer
301
- yield [tuple(x) for x in history], docs_html, logs_data, session_id
302
-
303
- # Stream the response updates
304
- async for update in process_stream():
305
- yield update
306
-
307
- elif model_config.get('reader','TYPE') == 'INF_PROVIDERS':
308
- chat_model = inf_provider()
309
- start_time = time.time()
310
- ai_prefix = "**AI-Generated Response:**\n\n"
311
- async def process_stream():
312
- nonlocal answer_yet # Use the outer scope's answer_yet variable
313
- # Without nonlocal, Python would create a new local variable answer_yet inside process_stream(),
314
- # instead of modifying the one from the outer scope.
315
- # Iterate over the streaming response chunks
316
- answer_yet += ai_prefix
317
- response = chat_model.chat.completions.create(
318
- model=model_config.get("reader","INF_PROVIDER_MODEL"),
319
- messages = messages,
320
- stream= True,
321
- max_tokens=int(model_config.get('reader','MAX_TOKENS')),
322
- )
323
- for message in response:
324
- token = message.choices[0].delta.content
325
- if token:
326
- answer_yet += token
327
- parsed_answer = parse_output_llm_with_sources(answer_yet)
328
- history[-1] = (query, parsed_answer)
329
- logs_data["answer"] = parsed_answer
330
- yield [tuple(x) for x in history], docs_html, logs_data, session_id
331
- await asyncio.sleep(0.05)
332
-
333
- # Stream the response updates
334
- async for update in process_stream():
335
- yield update
336
-
337
-
338
- elif model_config.get('reader','TYPE') == 'DEDICATED':
339
- chat_model = dedicated_endpoint()
340
- ### adding for assessing computation time
341
- start_time = time.time()
342
- async def process_stream():
343
- # Without nonlocal, Python would create a new local variable answer_yet inside process_stream(),
344
- # instead of modifying the one from the outer scope.
345
- nonlocal answer_yet # Use the outer scope's answer_yet variable
346
- # Iterate over the streaming response chunks
347
- async for chunk in chat_model.astream(messages):
348
- token = chunk.content
349
- answer_yet += token
350
- parsed_answer = parse_output_llm_with_sources(answer_yet)
351
- history[-1] = (query, parsed_answer)
352
- logs_data["answer"] = parsed_answer
353
- yield [tuple(x) for x in history], docs_html, logs_data, session_id
354
- end_time = time.time()
355
- print("Time for reader:",end_time - start_time)
356
-
357
- # Stream the response updates
358
- async for update in process_stream():
359
- yield update
360
-
361
-
362
- else:
363
- chat_model = serverless_api() # TESTING: ADAPTED FOR HF INFERENCE API (needs to be reverted for production version)
364
- async def process_stream():
365
- nonlocal answer_yet
366
- try:
367
- formatted_messages = [
368
- {
369
- "role": msg.type if hasattr(msg, 'type') else msg.role,
370
- "content": msg.content
371
- }
372
- for msg in messages
373
- ]
374
-
375
- response = chat_model.chat_completion(
376
- messages=formatted_messages,
377
- max_tokens= int(model_config.get('reader', 'MAX_TOKENS'))
378
- )
379
-
380
- response_text = response.choices[0].message.content
381
- words = response_text.split()
382
- for word in words:
383
- answer_yet += word + " "
384
- parsed_answer = parse_output_llm_with_sources(answer_yet)
385
- history[-1] = (query, parsed_answer)
386
- # Update logs_data with current answer (and get a new timestamp)
387
- logs_data["answer"] = parsed_answer
388
- yield [tuple(x) for x in history], docs_html, logs_data, session_id
389
- await asyncio.sleep(0.05)
390
-
391
- except Exception as e:
392
- raise
393
-
394
- async for update in process_stream():
395
- yield update
396
-
397
-
398
- # logging the event
399
- try:
400
- save_logs(scheduler,JSON_DATASET_PATH,logs_data)
401
- except Exception as e:
402
- raise
403
-
404
-
405
-
406
-
407
- #####-------------------------- Gradio App--------------------------------------####
408
-
409
- # Set up Gradio Theme
410
- theme = gr.themes.Base(
411
- primary_hue="blue",
412
- secondary_hue="red",
413
- font=[gr.themes.GoogleFont("Poppins"), "ui-sans-serif", "system-ui", "sans-serif"],
414
- text_size = gr.themes.utils.sizes.text_sm,
415
- )
416
-
417
- init_prompt = """
418
- Hello, I am Audit Q&A, an AI-powered conversational assistant designed to help you understand audit reports. I will answer your questions by using **Audit reports publishsed by Auditor General Office, Uganda**.
419
- 💡 How to use (tabs on right)
420
- - **Reports**: You can choose to address your question to either specific report or a collection of report like District or Ministry focused reports. \
421
- If you dont select any then the Consolidated report is relied upon to answer your question.
422
- - **Examples**: We have curated some example questions,select a particular question from category of questions.
423
- - **Sources**: This tab will display the relied upon paragraphs from the report, to help you in assessing or fact checking if the answer provided by Audit Q&A assitant is correct or not.
424
- ⚠️ For limitations of the tool and collection of usage statistics and data please check **Disclaimer** tab.
425
- ⚠️ By using this app, you acknowledge that we collect usage statistics (such as question asked, feedback given, session duration, device type and anonymized geo-location) to understand performance and continuously improve the tool, based on our legitimate interest in enhancing our services.
426
- """
427
-
428
-
429
- with gr.Blocks(title="Audit Q&A", css= "style.css", theme=theme,elem_id = "main-component") as demo:
430
- #----------------------------------------------------------------------------------------------
431
- # main tab where chat interaction happens
432
- # ---------------------------------------------------------------------------------------------
433
- with gr.Tab("AuditQ&A"):
434
-
435
- with gr.Row(elem_id="chatbot-row"):
436
- # chatbot output screen
437
- with gr.Column(scale=2):
438
- chatbot = gr.Chatbot(
439
- value=[(None,init_prompt)],
440
- show_copy_button=True,show_label = False,elem_id="chatbot",layout = "panel",
441
- avatar_images = (None,"data-collection.png"),
442
- )
443
-
444
- # feedback UI
445
- with gr.Column(elem_id="feedback-container"):
446
- with gr.Row(visible=False) as feedback_row:
447
- gr.Markdown("Was this response helpful?")
448
- with gr.Row():
449
- okay_btn = gr.Button("👍 Okay", elem_classes="feedback-button")
450
- not_okay_btn = gr.Button("👎 Not to expectations", elem_classes="feedback-button")
451
- feedback_thanks = gr.Markdown("Thanks for the feedback!", visible=False)
452
- feedback_state = gr.State()
453
-
454
-
455
-
456
-
457
- with gr.Row(elem_id = "input-message"):
458
- textbox=gr.Textbox(placeholder="Ask me anything here!",show_label=False,scale=7,
459
- lines = 1,interactive = True,elem_id="input-textbox")
460
-
461
- # second column with playground area for user to select values
462
- with gr.Column(scale=1, variant="panel",elem_id = "right-panel"):
463
- # creating tabs on right panel
464
- with gr.Tabs() as tabs:
465
- #---------------- tab for REPORTS SELECTION ----------------------
466
-
467
- with gr.Tab("Reports",elem_id = "tab-config",id = 2):
468
-
469
- #---------------- SELECTION METHOD - RADIO BUTTON ------------
470
- search_method = gr.Radio(
471
- choices=["Search by Report Name", "Search by Filters"],
472
- label="Choose search method",
473
- info= "Select the audit reports that you want to analyse directly or browse through categories and select reports",
474
- value="Search by Report Name",
475
- )
476
-
477
- #---------------- SELECT BY REPORT NAME SECTION ------------
478
- with gr.Group(visible=True) as report_name_section:
479
- # Get default report value from config if present
480
- default_report = model_config.get('app', 'dropdown_default', fallback=None)
481
- # Check if it actually exists in the master list
482
- default_report_value = [default_report] if default_report in new_report_list else None
483
-
484
- dropdown_reports = gr.Dropdown(
485
- new_report_list,
486
- label="Select one or more reports (scroll or type to search)",
487
- multiselect=True,
488
- value=default_report_value,
489
- interactive=True,
490
- )
491
-
492
- #---------------- SELECT BY FILTERS SECTION ------------
493
- with gr.Group(visible=False) as filters_section:
494
- #----- First level filter for selecting Report source/category ----------
495
- dropdown_sources = gr.Dropdown(
496
- ["Consolidated","Ministry, Department, Agency and Projects","Local Government","Value for Money","Thematic"],
497
- label="Select Report Category",
498
- value=None,
499
- interactive=True,
500
- )
501
-
502
- #------ second level filter for selecting subtype within the report category selected above
503
- dropdown_category = gr.Dropdown(
504
- [], # Start with empty choices
505
- value=None,
506
- label = "Filter for Sub-Type",
507
- interactive=True)
508
-
509
- #----------- update the second level filter based on values from first level ----------------
510
- def rs_change(rs):
511
- if rs: # Only update choices if a value is selected
512
- return gr.update(choices=new_files[rs], value=None) # Set value to None (no preselection)
513
- else:
514
- return gr.update(choices=[], value=None) # Empty choices if nothing selected
515
- dropdown_sources.change(fn=rs_change, inputs=[dropdown_sources], outputs=[dropdown_category])
516
-
517
- # Toggle visibility based on search method
518
- def toggle_search_method(method):
519
- """Note - this function removes the default value from report search when toggled"""
520
- if method == "Search by Report Name":
521
- # Show report selection, hide filters, and clear filter values
522
- return (
523
- gr.update(visible=True), # report_name_section
524
- gr.update(visible=False), # filters_section
525
- gr.update(value=None), # dropdown_sources
526
- gr.update(value=None), # dropdown_category
527
- #gr.update(value=None), # dropdown_year
528
- gr.update() # dropdown_reports
529
- )
530
- else: # "Search by Filters"
531
- # Show filters, hide report selection, and clear report values
532
- return (
533
- gr.update(visible=False), # report_name_section
534
- gr.update(visible=True), # filters_section
535
- gr.update(), # dropdown_sources
536
- gr.update(), # dropdown_category
537
- #gr.update(), # dropdown_year
538
- gr.update(value=[]) # dropdown_reports
539
- )
540
-
541
- # Pass to the event handler
542
- search_method.change(
543
- fn=toggle_search_method,
544
- inputs=[search_method],
545
- outputs=[
546
- report_name_section,
547
- filters_section,
548
- dropdown_sources,
549
- dropdown_category,
550
- dropdown_reports
551
- ]
552
- )
553
-
554
-
555
- ############### tab for Question selection ###############
556
- with gr.TabItem("Examples",elem_id = "tab-examples",id = 0):
557
- examples_hidden = gr.Textbox(visible = False)
558
-
559
- # getting defualt key value to display
560
- first_key = list(QUESTIONS.keys())[0]
561
- # create the question category dropdown
562
- dropdown_samples = gr.Dropdown(QUESTIONS.keys(),value = first_key,
563
- interactive = True,show_label = True,
564
- label = "Select a category of sample questions",
565
- elem_id = "dropdown-samples")
566
-
567
-
568
- # iterate through the questions list
569
- samples = []
570
- for i,key in enumerate(QUESTIONS.keys()):
571
- examples_visible = True if i == 0 else False
572
- with gr.Row(visible = examples_visible) as group_examples:
573
- examples_questions = gr.Examples(
574
- QUESTIONS[key],
575
- [examples_hidden],
576
- examples_per_page=8,
577
- run_on_click=False,
578
- elem_id=f"examples{i}",
579
- api_name=f"examples{i}",
580
- # label = "Click on the example question or enter your own",
581
- # cache_examples=True,
582
- )
583
-
584
- samples.append(group_examples)
585
- ##------------------- tab for Sources reporting ##------------------
586
- with gr.Tab("Sources",elem_id = "tab-citations",id = 1):
587
- sources_textbox = gr.HTML(show_label=False, elem_id="sources-textbox")
588
- docs_textbox = gr.State("")
589
-
590
- def change_sample_questions(key):
591
- # update the questions list based on key selected
592
- index = list(QUESTIONS.keys()).index(key)
593
- visible_bools = [False] * len(samples)
594
- visible_bools[index] = True
595
- return [gr.update(visible=visible_bools[i]) for i in range(len(samples))]
596
-
597
- dropdown_samples.change(change_sample_questions,dropdown_samples,samples)
598
-
599
-
600
- # ---- Guidelines Tab ----
601
- with gr.Tab("Guidelines", elem_classes="max-height other-tabs"):
602
- gr.Markdown("""
603
- #### Welcome to Audit Q&A, your AI-powered assistant for exploring and understanding Uganda's audit reports. This tool leverages advanced language models to help you get clear and structured answers based on audit publications. To get you started, here a few tips on how to use the tool:
604
- ## 💬 Crafting Effective Prompts
605
- Clear, specific questions will give you the best results. Here are some examples:
606
- | ❌ Less Effective | ✅ More Effective |
607
- |------------------|-------------------|
608
- | "What are the findings?" | "What were the main issues identified in procurement practices in the Ministry of Health in 2022?" |
609
- | "Tell me about revenue collection" | "What specific challenges were identified in revenue collection at the local government level in 2021-2022?" |
610
- | "Is there corruption?" | "What audit findings related to misappropriation of funds were reported in the education sector between 2020-2023?" |
611
- ## ⭐ Best Practices
612
- - **Be Clear and Specific**: Frame your questions clearly and focus on what you want to learn.
613
- - **One Topic at a Time**: Break complex queries into simpler, focused questions.
614
- - **Provide Context**: Mentioning specific ministries, years, or projects helps narrow the focus.
615
- - **Follow Up**: Ask follow-up questions to explore a topic more deeply.
616
-
617
- ## 🔍 Utilizing Filters
618
- - **Report Category & Subtype**: Use the "Reports" tab to choose your preferred report category and refine your query by selecting a specific sub-type. This will help narrow down the context for your question.
619
- - **Specific Reports**: Optionally, select specific reports using the dropdown to focus on a particular document or set of documents.
620
- ## 📚 Useful Resources
621
-
622
- - <ins>[**Short Course: Generative AI for Everyone** (3 hours)](https://www.deeplearning.ai/courses/generative-ai-for-everyone/)</ins>
623
- - <ins>[**Short Course: Advanced Prompting** (1 hour)](https://www.deeplearning.ai/courses/ai-for-everyone/)</ins>
624
- - <ins>[**Short Course: Introduction to AI with IBM** (13 hours)](https://www.coursera.org/learn/introduction-to-ai)</ins>
625
- Enjoy using Audit Q&A and happy prompting!
626
- """)
627
-
628
-
629
-
630
- # static tab 'about us'
631
- with gr.Tab("About",elem_classes = "max-height other-tabs"):
632
- with gr.Row():
633
- with gr.Column(scale=1):
634
- gr.Markdown("""The <ins>[**Office of the Auditor General (OAG)**](https://www.oag.go.ug/welcome)</ins> in Uganda, \
635
- consistent with the mandate of Supreme Audit Institutions (SAIs),\
636
- remains integral in ensuring transparency and fiscal responsibility.\
637
- Regularly, the OAG submits comprehensive audit reports to Parliament, \
638
- which serve as instrumental references for both policymakers and the public, \
639
- facilitating informed decisions regarding public expenditure.
640
-
641
- However, the prevalent underutilization of these audit reports, \
642
- leading to numerous unimplemented recommendations, has posed significant challenges\
643
- to the effectiveness and impact of the OAG's operations. The audit reports made available \
644
- to the public have not been effectively used by them and other relevant stakeholders. \
645
- The current format of the audit reports is considered a challenge to the \
646
- stakeholders' accessibility and usability. This in one way constrains transparency \
647
- and accountability in the utilization of public funds and effective service delivery.
648
-
649
- In the face of this, modern advancements in Artificial Intelligence (AI),\
650
- particularly Retrieval Augmented Generation (RAG) technology, \
651
- emerge as a promising solution. By harnessing the capabilities of such AI tools, \
652
- there is an opportunity not only to improve the accessibility and understanding \
653
- of these audit reports but also to ensure that their insights are effectively \
654
- translated into actionable outcomes, thereby reinforcing public transparency \
655
- and service delivery in Uganda.
656
-
657
- To address these issues, the OAG has initiated several projects, \
658
- such as the Audit Recommendation Tracking (ART) System and the Citizens Feedback Platform (CFP). \
659
- These systems are designed to increase the transparency and relevance of audit activities. \
660
- However, despite these efforts, engagement and awareness of the audit findings remain low, \
661
- and the complexity of the information often hinders effective public utilization. Recognizing the need for further\
662
- enhancement in how audit reports are processed and understood, \
663
- the **Civil Society and Budget Advocacy Group (CSBAG)** in partnership with the **GIZ**, \
664
- has recognizing the need for further enhancement in how audit reports are processed and understood.
665
-
666
- This prototype tool leveraging AI (Artificial Intelligence) aims at offering critical capabilities such as '
667
- summarizing complex texts, extracting thematic insights, and enabling interactive, \
668
- user-friendly analysis through a chatbot interface. By making the audit reports more accessible,\
669
- this aims to increase readership and utilization among stakeholders, \
670
- which can lead to better accountability and improve service delivery
671
-
672
- """)
673
-
674
-
675
- # static tab for disclaimer
676
- with gr.Tab("Disclaimer",elem_classes = "max-height other-tabs"):
677
- with gr.Row():
678
- with gr.Column(scale=1):
679
- gr.Markdown("""
680
- - This chatbot is intended for specific use of answering the questions based on audit reports published by OAG, Uganda for any use beyond this scope we have no liability to response provided by chatbot.
681
- - The functionality and scope of this chatbot is limited to the context contained in audit reports published by OAG, Uganda in national context.
682
- - We have implemented measures to ensure the technical robustness and security of our AI system, minimizing unexpected behaviour, however we do not guarantee the full reliability, or completeness of any information provided by the chatbot and disclaim any liability or responsibility for actions taken based on its responses.
683
- - The chatbot may occasionally provide inaccurate or inappropriate responses, and it is important to exercise judgment and critical thinking when interpreting its output.
684
- - The use of AI within this application is transparent. When interacting with the AI, users are informed that they are engaging with an AI system
685
- - The chatbot responses should not be considered professional or authoritative advice and are generated based on patterns in the data it has been trained on.
686
- - The chatbot's responses do not reflect the opinions or policies of our organization or its affiliates.
687
- - Any personal or sensitive information shared with the chatbot is at the user's own risk, and we cannot guarantee complete privacy or confidentiality.
688
- - The chatbot is not deterministic, so there might be change in answer to same question when asked by different users or multiple times.
689
- - When you use this app, we collect certain information to understand its usage, analyze performance, and continuously improve the tool for future use. This includes:
690
- - The questions you ask
691
- - The AI-generated answers
692
- - Feedback given towards to each response (in form of Thumbs-up and Thumbs-down), if any.
693
- - Usage statistics such as session duration, device type and anonymized geo-location information.
694
-
695
- We process this data based on our legitimate interest in continually enhancing the quality, security, and usability of the Audit Q&A assistant
696
- - By using this chatbot, you agree to these terms and acknowledge that you are solely responsible for any reliance on or actions taken based on its responses.
697
- - User can read more about the technical information about the tool in [**Readme**](https://huggingface.co/spaces/GIZ/audit_assistant/blob/main/README.md) of this tool.
698
- - **This is just a prototype and being tested and worked upon, so its not perfect and may sometimes give irrelevant answers**. If you are not satisfied with the answer, please ask a more specific question or report your feedback to help us improve the system.
699
- """)
700
-
701
-
702
- def show_feedback(logs):
703
- """Show feedback buttons and store logs in state"""
704
- return gr.update(visible=True), gr.update(visible=False), logs
705
-
706
- def submit_feedback_okay(logs_data):
707
- """Handle 'okay' feedback submission"""
708
- return submit_feedback("okay", logs_data)
709
-
710
- def submit_feedback_not_okay(logs_data):
711
- """Handle 'not okay' feedback submission"""
712
- return submit_feedback("not_okay", logs_data)
713
-
714
- okay_btn.click(
715
- submit_feedback_okay,
716
- [feedback_state],
717
- [feedback_row, feedback_thanks]
718
- )
719
-
720
- not_okay_btn.click(
721
- submit_feedback_not_okay,
722
- [feedback_state],
723
- [feedback_row, feedback_thanks]
724
- )
725
-
726
- #-------------------- Session Management + Geolocation -------------------------
727
-
728
- # Add these state components at the top level of the Blocks
729
- session_id = gr.State(None)
730
- client_ip = gr.State(None)
731
-
732
- @demo.load(api_name="get_client_ip")
733
- def get_client_ip_handler(dummy_input="", request: gr.Request = None):
734
- """Handler for getting client IP in Gradio context"""
735
- return get_client_ip(request)
736
-
737
-
738
- #-------------------- Gradio voodoo -------------------------
739
-
740
- # Update the event handlers
741
- (textbox
742
- .submit(get_client_ip_handler, [textbox], [client_ip], api_name="get_ip_textbox")
743
- .then(start_chat, [textbox, chatbot], [textbox, tabs, chatbot], queue=False, api_name="start_chat_textbox")
744
- .then(chat,
745
- [textbox, chatbot, search_method, dropdown_sources, dropdown_reports, dropdown_category, client_ip, session_id],
746
- [chatbot, sources_textbox, feedback_state, session_id],
747
- queue=True, concurrency_limit=8, api_name="chat_textbox")
748
- .then(show_feedback, [feedback_state], [feedback_row, feedback_thanks, feedback_state], api_name="show_feedback_textbox")
749
- .then(finish_chat, None, [textbox], api_name="finish_chat_textbox"))
750
-
751
- (examples_hidden
752
- .change(start_chat, [examples_hidden, chatbot], [textbox, tabs, chatbot], queue=False, api_name="start_chat_examples")
753
- .then(get_client_ip_handler, [examples_hidden], [client_ip], api_name="get_ip_examples")
754
- .then(chat,
755
- [examples_hidden, chatbot, search_method, dropdown_sources, dropdown_reports, dropdown_category, client_ip, session_id],
756
- [chatbot, sources_textbox, feedback_state, session_id],
757
- concurrency_limit=8, api_name="chat_examples")
758
- .then(show_feedback, [feedback_state], [feedback_row, feedback_thanks, feedback_state], api_name="show_feedback_examples")
759
- .then(finish_chat, None, [textbox], api_name="finish_chat_examples"))
760
-
761
- demo.queue()
762
-
763
- demo.launch()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
auditchatbot_requirements.txt DELETED
@@ -1,160 +0,0 @@
1
- aiofiles==23.2.1
2
- aiohappyeyeballs==2.3.5
3
- aiohttp==3.10.3
4
- aiosignal==1.3.1
5
- annotated-types==0.7.0
6
- anyio==4.4.0
7
- asttokens==2.4.1
8
- async-timeout==4.0.3
9
- attrs==24.2.0
10
- authlib==1.3.1
11
- certifi==2024.7.4
12
- cffi==1.17.0
13
- charset-normalizer==3.3.2
14
- click==8.0.4
15
- comm==0.2.2
16
- contourpy==1.2.1
17
- cryptography==43.0.0
18
- cycler==0.12.1
19
- dataclasses-json==0.6.7
20
- datasets==2.20.0
21
- debugpy==1.8.5
22
- decorator==5.1.1
23
- dill==0.3.8
24
- exceptiongroup==1.2.2
25
- executing==2.0.1
26
- fastapi==0.112.0
27
- ffmpy==0.4.0
28
- filelock==3.15.4
29
- fonttools==4.53.1
30
- frozenlist==1.4.1
31
- fsspec==2024.5.0
32
- gradio-client==1.1.1
33
- gradio==4.39.0
34
- greenlet==3.0.3
35
- grpcio-tools==1.65.4
36
- grpcio==1.65.4
37
- h11==0.14.0
38
- h2==4.1.0
39
- hf-transfer==0.1.8
40
- hpack==4.0.0
41
- httpcore==1.0.5
42
- httpx==0.27.0
43
- huggingface-hub==0.23.5
44
- hyperframe==6.0.1
45
- idna==3.7
46
- importlib-resources==6.4.0
47
- ipykernel==6.29.5
48
- ipython==8.26.0
49
- itsdangerous==2.2.0
50
- jedi==0.19.1
51
- jinja2==3.1.4
52
- joblib==1.4.2
53
- jsonpatch==1.33
54
- jsonpointer==3.0.0
55
- jupyter-client==8.6.2
56
- jupyter-core==5.7.2
57
- kiwisolver==1.4.5
58
- langchain-community==0.0.38
59
- langchain-core==0.1.52
60
- langchain-huggingface==0.0.3
61
- langchain-qdrant==0.1.3
62
- langchain-text-splitters==0.0.2
63
- langchain==0.1.20
64
- langsmith==0.1.99
65
- markdown-it-py==3.0.0
66
- markupsafe==2.1.5
67
- marshmallow==3.21.3
68
- matplotlib-inline==0.1.7
69
- matplotlib==3.9.2
70
- mdurl==0.1.2
71
- mpmath==1.3.0
72
- multidict==6.0.5
73
- multiprocess==0.70.16
74
- mypy-extensions==1.0.0
75
- nest-asyncio==1.6.0
76
- networkx==3.3
77
- numpy==1.26.4
78
- nvidia-cublas-cu12==12.1.3.1
79
- nvidia-cuda-cupti-cu12==12.1.105
80
- nvidia-cuda-nvrtc-cu12==12.1.105
81
- nvidia-cuda-runtime-cu12==12.1.105
82
- nvidia-cudnn-cu12==9.1.0.70
83
- nvidia-cufft-cu12==11.0.2.54
84
- nvidia-curand-cu12==10.3.2.106
85
- nvidia-cusolver-cu12==11.4.5.107
86
- nvidia-cusparse-cu12==12.1.0.106
87
- nvidia-nccl-cu12==2.20.5
88
- nvidia-nvjitlink-cu12==12.6.20
89
- nvidia-nvtx-cu12==12.1.105
90
- orjson==3.10.7
91
- packaging==23.2
92
- pandas==2.2.2
93
- parso==0.8.4
94
- pexpect==4.9.0
95
- pillow==10.4.0
96
- pip==22.3.1
97
- platformdirs==4.2.2
98
- portalocker==2.10.1
99
- prompt-toolkit==3.0.47
100
- protobuf==5.27.3
101
- psutil==5.9.8
102
- ptyprocess==0.7.0
103
- pure-eval==0.2.3
104
- pyarrow-hotfix==0.6
105
- pyarrow==17.0.0
106
- pycparser==2.22
107
- pydantic-core==2.20.1
108
- pydantic==2.8.2
109
- pydub==0.25.1
110
- pygments==2.18.0
111
- pymupdf==1.23.26
112
- pymupdfb==1.23.22
113
- pyparsing==3.1.2
114
- python-dateutil==2.9.0.post0
115
- python-dotenv==1.0.1
116
- python-multipart==0.0.9
117
- pytz==2024.1
118
- pyyaml==6.0.2
119
- pyzmq==26.2.0
120
- qdrant-client==1.10.1
121
- regex==2024.7.24
122
- requests==2.32.3
123
- rich==13.7.1
124
- ruff==0.5.7
125
- safetensors==0.4.4
126
- scikit-learn==1.5.1
127
- scipy==1.14.0
128
- semantic-version==2.10.0
129
- sentence-transformers==3.0.1
130
- sentencepiece==0.2.0
131
- setuptools==65.5.0
132
- shellingham==1.5.4
133
- six==1.16.0
134
- sniffio==1.3.1
135
- spaces==0.29.3
136
- sqlalchemy==2.0.32
137
- stack-data==0.6.3
138
- starlette==0.37.2
139
- sympy==1.13.2
140
- tenacity==8.5.0
141
- threadpoolctl==3.5.0
142
- tokenizers==0.19.1
143
- tomlkit==0.12.0
144
- torch==2.4.0
145
- tornado==6.4.1
146
- tqdm==4.66.5
147
- traitlets==5.14.3
148
- transformers==4.44.0
149
- triton==3.0.0
150
- typer==0.12.3
151
- typing-extensions==4.12.2
152
- typing-inspect==0.9.0
153
- tzdata==2024.1
154
- urllib3==2.2.2
155
- uvicorn==0.30.6
156
- wcwidth==0.2.13
157
- websockets==11.0.3
158
- wheel==0.44.0
159
- xxhash==3.4.1
160
- yarl==1.9.4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
model_params.cfg CHANGED
@@ -6,15 +6,3 @@ TEMPERATURE = 0.2
6
  INFERENCE_PROVIDER = novita
7
  ORGANIZATION = GIZ
8
 
9
- [reader]
10
- TYPE = INF_PROVIDERS
11
- INF_PROVIDER_MODEL = meta-llama/Llama-3.1-8B-Instruct
12
- DEDICATED_MODEL = meta-llama/Llama-3.1-8B-Instruct
13
- DEDICATED_ENDPOINT = https://qu2d8m6dmsollhly.us-east-1.aws.endpoints.huggingface.cloud
14
- NVIDIA_MODEL = meta-llama/Llama-3.1-8B-Instruct
15
- NVIDIA_ENDPOINT = https://huggingface.co/api/integrations/dgx/v1
16
- MAX_TOKENS = 768
17
- INF_PROVIDER = nebius
18
-
19
- [app]
20
- dropdown_default = Annual Consolidated OAG 2024
 
6
  INFERENCE_PROVIDER = novita
7
  ORGANIZATION = GIZ
8
 
 
 
 
 
 
 
 
 
 
 
 
 
utils/__pycache__/generator.cpython-310.pyc CHANGED
Binary files a/utils/__pycache__/generator.cpython-310.pyc and b/utils/__pycache__/generator.cpython-310.pyc differ
 
utils/__pycache__/retriever.cpython-310.pyc CHANGED
Binary files a/utils/__pycache__/retriever.cpython-310.pyc and b/utils/__pycache__/retriever.cpython-310.pyc differ
 
utils/__pycache__/whisp_api.cpython-310.pyc CHANGED
Binary files a/utils/__pycache__/whisp_api.cpython-310.pyc and b/utils/__pycache__/whisp_api.cpython-310.pyc differ
 
utils/generator.py CHANGED
@@ -74,6 +74,7 @@ def get_chat_model():
74
  "max_tokens": MAX_TOKENS,
75
  }
76
 
 
77
  # if PROVIDER == "openai":
78
  # return ChatOpenAI(
79
  # model=MODEL,
@@ -110,70 +111,6 @@ def get_chat_model():
110
  # Initialize provider-agnostic chat model
111
  chat_model = get_chat_model()
112
 
113
- # ---------------------------------------------------------------------
114
- # Context processing - may need further refinement (i.e. to manage other data sources)
115
- # ---------------------------------------------------------------------
116
- # def extract_relevant_fields(retrieval_results: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
117
- # """
118
- # Extract only relevant fields from retrieval results.
119
-
120
- # Args:
121
- # retrieval_results: List of JSON objects from retriever
122
-
123
- # Returns:
124
- # List of processed objects with only relevant fields
125
- # """
126
-
127
- # retrieval_results = ast.literal_eval(retrieval_results)
128
-
129
- # processed_results = []
130
-
131
- # for result in retrieval_results:
132
- # # Extract the answer content
133
- # answer = result.get('answer', '')
134
-
135
- # # Extract document identification from metadata
136
- # metadata = result.get('answer_metadata', {})
137
- # doc_info = {
138
- # 'answer': answer,
139
- # 'filename': metadata.get('filename', 'Unknown'),
140
- # 'page': metadata.get('page', 'Unknown'),
141
- # 'year': metadata.get('year', 'Unknown'),
142
- # 'source': metadata.get('source', 'Unknown'),
143
- # 'document_id': metadata.get('_id', 'Unknown')
144
- # }
145
-
146
- # processed_results.append(doc_info)
147
-
148
- # return processed_results
149
-
150
- # def format_context_from_results(processed_results: List[Dict[str, Any]]) -> str:
151
- # """
152
- # Format processed retrieval results into a context string for the LLM.
153
-
154
- # Args:
155
- # processed_results: List of processed objects with relevant fields
156
-
157
- # Returns:
158
- # Formatted context string
159
- # """
160
- # if not processed_results:
161
- # return ""
162
-
163
- # context_parts = []
164
-
165
- # for i, result in enumerate(processed_results, 1):
166
- # doc_reference = f"[Document {i}: {result['filename']}"
167
- # if result['page'] != 'Unknown':
168
- # doc_reference += f", Page {result['page']}"
169
- # if result['year'] != 'Unknown':
170
- # doc_reference += f", Year {result['year']}"
171
- # doc_reference += "]"
172
-
173
- # context_part = f"{doc_reference}\n{result['answer']}\n"
174
- # context_parts.append(context_part)
175
-
176
- # return "\n".join(context_parts)
177
 
178
  # ---------------------------------------------------------------------
179
  # Core generation function for both Gradio UI and MCP
 
74
  "max_tokens": MAX_TOKENS,
75
  }
76
 
77
+ #### Currently the option to fetach any other Generator type are disabled #####3
78
  # if PROVIDER == "openai":
79
  # return ChatOpenAI(
80
  # model=MODEL,
 
111
  # Initialize provider-agnostic chat model
112
  chat_model = get_chat_model()
113
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
114
 
115
  # ---------------------------------------------------------------------
116
  # Core generation function for both Gradio UI and MCP
utils/retriever.py CHANGED
@@ -2,8 +2,19 @@ import gradio as gr
2
  from gradio_client import Client
3
 
4
 
5
- def retrieve_paragraphs(query, country):
6
- """Connect to retriever and retrieve paragraphs"""
 
 
 
 
 
 
 
 
 
 
 
7
  try:
8
 
9
  # Metadata selection
 
2
  from gradio_client import Client
3
 
4
 
5
+ def retrieve_paragraphs(query:str, country:dict):
6
+ """Connect to retriever and retrieve paragraphs, the collection param is fixed in qdrant-client call within code.
7
+
8
+ Params
9
+ ----------
10
+ query: the query input by user
11
+ country: collection 'EUDR' can filter the results based on country field. Past the values of country as str (single) or list
12
+
13
+ Returns
14
+ -----------
15
+ Returns the top 10 retrieved>reranked results list of dict [{'answer':.....,'answer_metadata': {.....}}]
16
+
17
+ """
18
  try:
19
 
20
  # Metadata selection
utils/whisp_api.py CHANGED
@@ -3,7 +3,15 @@ from gradio_client import Client, handle_file
3
  import pandas as pd
4
 
5
  def get_value(df, colname):
6
- """Fetch value from WhispAPI-style Column/Value dataframe"""
 
 
 
 
 
 
 
 
7
  if "Column" in df.columns and "Value" in df.columns:
8
  match = df.loc[df["Column"] == colname, "Value"]
9
  if not match.empty:
@@ -133,7 +141,8 @@ La siguiente información ha sido generada por la [WhispAPI creada por Forest Da
133
  return f"❌ **Analysis Error**\n\nUnable to process the geographic data: {str(e)}\n\n📋 **Troubleshooting:**\n- Verify your GeoJSON file format\n- Check file size (should be < 10MB)\n- Ensure coordinates are valid\n\nPlease try uploading again or contact support."
134
 
135
  def handle_geojson_upload(file):
136
- """Handle GeoJSON file upload and call WHISP API"""
 
137
  if file is not None:
138
  try:
139
  # Initialize WHISP API client
 
3
  import pandas as pd
4
 
5
  def get_value(df, colname):
6
+ """Fetch value from WhispAPI-style Column/Value dataframe
7
+
8
+ Params
9
+ ---------
10
+
11
+ df: dataframe with statistical info from whisp api
12
+ colname: column name for which value need be fetched
13
+
14
+ """
15
  if "Column" in df.columns and "Value" in df.columns:
16
  match = df.loc[df["Column"] == colname, "Value"]
17
  if not match.empty:
 
141
  return f"❌ **Analysis Error**\n\nUnable to process the geographic data: {str(e)}\n\n📋 **Troubleshooting:**\n- Verify your GeoJSON file format\n- Check file size (should be < 10MB)\n- Ensure coordinates are valid\n\nPlease try uploading again or contact support."
142
 
143
  def handle_geojson_upload(file):
144
+ """Handle GeoJSON file upload and call WHISP API through the chatfed-whisp spaces. The API token is taken care by chatfed-whisp
145
+ space """
146
  if file is not None:
147
  try:
148
  # Initialize WHISP API client