ppsingh commited on
Commit
50eb981
1 Parent(s): 0b0c6cd

Delete app1.py

Browse files
Files changed (1) hide show
  1. app1.py +0 -405
app1.py DELETED
@@ -1,405 +0,0 @@
1
- import gradio as gr
2
- import pandas as pd
3
- import numpy as np
4
- import os
5
- import time
6
- import re
7
- import json
8
- from auditqa.sample_questions import QUESTIONS
9
- from auditqa.engine.prompts import audience_prompts
10
- from auditqa.reports import POSSIBLE_REPORTS, files
11
- from auditqa.doc_process import process_pdf
12
- from langchain_core.messages import (
13
- HumanMessage,
14
- SystemMessage,
15
- )
16
- from langchain_huggingface import ChatHuggingFace
17
- from langchain_core.output_parsers import StrOutputParser
18
- from langchain_huggingface import HuggingFaceEndpoint
19
- from dotenv import load_dotenv
20
- load_dotenv()
21
-
22
- HF_token = os.environ["HF_TOKEN"]
23
- vectorstores = process_pdf()
24
-
25
- async def chat(query,history,sources,reports):
26
- """taking a query and a message history, use a pipeline (reformulation, retriever, answering) to yield a tuple of:
27
- (messages in gradio format, messages in langchain format, source documents)"""
28
-
29
- print(f">> NEW QUESTION : {query}")
30
- print(f"history:{history}")
31
- #print(f"audience:{audience}")
32
- print(f"sources:{sources}")
33
- print(f"reports:{reports}")
34
- docs_html = ""
35
- output_query = ""
36
- output_language = "English"
37
- audience = "Experts"
38
-
39
- if audience == "Children":
40
- audience_prompt = audience_prompts["children"]
41
- elif audience == "General public":
42
- audience_prompt = audience_prompts["general"]
43
- elif audience == "Experts":
44
- audience_prompt = audience_prompts["experts"]
45
- else:
46
- audience_prompt = audience_prompts["experts"]
47
-
48
- # Prepare default values
49
- if len(sources) == 0:
50
- sources = ["Consolidated Reports"]
51
-
52
- if len(reports) == 0:
53
- reports = []
54
-
55
- if sources == "Ministry":
56
- vectorstore = vectorstores["MWTS"]
57
- else:
58
- vectorstore = vectorstores["Consolidated"]
59
-
60
- # get context
61
- context_retrieved_lst = []
62
- question_lst= [query]
63
- for question in question_lst:
64
- retriever = vectorstore.as_retriever(
65
- search_type="similarity_score_threshold", search_kwargs={"score_threshold": 0.6, "k": 3})
66
-
67
- context_retrieved = retriever.invoke(question)
68
-
69
- def format_docs(docs):
70
- return "\n\n".join(doc.page_content for doc in docs)
71
-
72
- context_retrieved_formatted = format_docs(context_retrieved)
73
- context_retrieved_lst.append(context_retrieved_formatted)
74
- print(context_retrieved_lst)
75
-
76
-
77
- # get prompt
78
- SYSTEM_PROMPT = """
79
- You are AuditQ&A, an AI Assistant created by Auditors and Data Scientist. You are given a question and extracted passages of the consolidated/departmental/thematic focus audit reports. Provide a clear and structured answer based on the passages provided, the context and the guidelines.
80
- Guidelines:
81
- - If the passages have useful facts or numbers, use them in your answer.
82
- - 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.
83
- - Do not use the sentence 'Doc i says ...' to say where information came from.
84
- - 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]
85
- - Do not just summarize each passage one by one. Group your summaries to highlight the key parts in the explanation.
86
- - If it makes sense, use bullet points and lists to make your answers easier to understand.
87
- - You do not need to use every passage. Only use the ones that help answer the question.
88
- - If the documents do not have the information needed to answer the question, just say you do not have enough information.
89
- """
90
-
91
- USER_PROMPT = """Passages:
92
- {context}
93
- -----------------------
94
- Question: {question} - Explained to audit expert
95
- Answer in english with the passages citations:
96
- """.format(context = context_retrieved_lst, question=query)
97
-
98
- messages = [
99
- SystemMessage(content=SYSTEM_PROMPT),
100
- HumanMessage(
101
- content=USER_PROMPT
102
- ),]
103
-
104
-
105
- # get llm_qa
106
- # llm_qa = HuggingFaceEndpoint(
107
- # endpoint_url= "https://mnczdhmrf7lkfd9d.eu-west-1.aws.endpoints.huggingface.cloud",
108
- # task="text-generation",
109
- # huggingfacehub_api_token=HF_token,
110
- # model_kwargs={})
111
-
112
- # trying llm new-prompt adapted for llama-3
113
- # https://stackoverflow.com/questions/78429932/langchain-ollama-and-llama-3-prompt-and-response
114
- # https://api.python.langchain.com/en/latest/llms/langchain_community.llms.huggingface_endpoint.HuggingFaceEndpoint.html#langchain_community.llms.huggingface_endpoint.HuggingFaceEndpoint.model_kwargs
115
- # https://huggingface.co/blog/llama3#how-to-prompt-llama-3
116
-
117
- llm_qa = HuggingFaceEndpoint(
118
- endpoint_url= "https://nhe9phsr2zhs0e36.eu-west-1.aws.endpoints.huggingface.cloud",
119
- task="text-generation",
120
- huggingfacehub_api_token=HF_token)
121
-
122
-
123
- # create rag chain
124
- chat_model = ChatHuggingFace(llm=llm_qa)
125
- chain = chat_model | StrOutputParser()
126
- # get answers
127
- answer_lst = []
128
- for question, context in zip(question_lst , context_retrieved_lst):
129
- answer = chain.invoke(messages)
130
- answer_lst.append(answer)
131
- docs_html = []
132
- for i, d in enumerate(context_retrieved, 1):
133
- docs_html.append(make_html_source(d, i))
134
- docs_html = "".join(docs_html)
135
-
136
- previous_answer = history[-1][1]
137
- previous_answer = previous_answer if previous_answer is not None else ""
138
- answer_yet = previous_answer + answer_lst[0]
139
- answer_yet = parse_output_llm_with_sources(answer_yet)
140
- history[-1] = (query,answer_yet)
141
-
142
- history = [tuple(x) for x in history]
143
-
144
- yield history,docs_html,output_language
145
-
146
- def make_html_source(source,i):
147
- meta = source.metadata
148
- # content = source.page_content.split(":",1)[1].strip()
149
- content = source.page_content.strip()
150
-
151
- name = meta['source']
152
- card = f"""
153
- <div class="card" id="doc{i}">
154
- <div class="card-content">
155
- <h2>Doc {i} - {meta['file_path']} - Page {int(meta['page'])}</h2>
156
- <p>{content}</p>
157
- </div>
158
- <div class="card-footer">
159
- <span>{name}</span>
160
- <a href="{meta['file_path']}#page={int(meta['page'])}" target="_blank" class="pdf-link">
161
- <span role="img" aria-label="Open PDF">🔗</span>
162
- </a>
163
- </div>
164
- </div>
165
- """
166
-
167
- return card
168
-
169
- def parse_output_llm_with_sources(output):
170
- # Split the content into a list of text and "[Doc X]" references
171
- content_parts = re.split(r'\[(Doc\s?\d+(?:,\s?Doc\s?\d+)*)\]', output)
172
- parts = []
173
- for part in content_parts:
174
- if part.startswith("Doc"):
175
- subparts = part.split(",")
176
- subparts = [subpart.lower().replace("doc","").strip() for subpart in subparts]
177
- subparts = [f"""<a href="#doc{subpart}" class="a-doc-ref" target="_self"><span class='doc-ref'><sup>{subpart}</sup></span></a>""" for subpart in subparts]
178
- parts.append("".join(subparts))
179
- else:
180
- parts.append(part)
181
- content_parts = "".join(parts)
182
- return content_parts
183
- # --------------------------------------------------------------------
184
- # Gradio
185
- # --------------------------------------------------------------------
186
-
187
- # Set up Gradio Theme
188
- theme = gr.themes.Base(
189
- primary_hue="blue",
190
- secondary_hue="red",
191
- font=[gr.themes.GoogleFont("Poppins"), "ui-sans-serif", "system-ui", "sans-serif"],
192
- text_size = gr.themes.utils.sizes.text_sm,
193
- )
194
-
195
- init_prompt = """
196
- Hello, I am Audit Q&A, a conversational assistant designed to help you understand audit Reports. I will answer your questions by using **Audit reports publishsed by Auditor General Office**.
197
- 💡 How to use (tabs on right)
198
- - **Reports**: You can choose to address your question to either specific report or a collection of report like District or Ministry focused reports. \
199
- If you dont select any then the Consolidated report is relied upon to answer your question.
200
- - **Examples**: We have curated some example questions,select a particular question from category of questions.
201
- - **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.
202
- ⚠️ For limitations of the tool please check **Disclaimer** tab.
203
- """
204
-
205
-
206
- # Setting Tabs
207
- with gr.Blocks(title="Audit Q&A", css= "style.css", theme=theme,elem_id = "main-component") as demo:
208
- # user_id_state = gr.State([user_id])
209
-
210
- with gr.Tab("AuditQ&A"):
211
-
212
- with gr.Row(elem_id="chatbot-row"):
213
- with gr.Column(scale=2):
214
- # state = gr.State([system_template])
215
- chatbot = gr.Chatbot(
216
- value=[(None,init_prompt)],
217
- show_copy_button=True,show_label = False,elem_id="chatbot",layout = "panel",
218
- avatar_images = (None,"data-collection.png"),
219
- )#,avatar_images = ("assets/logo4.png",None))
220
-
221
- # bot.like(vote,None,None)
222
-
223
-
224
-
225
- with gr.Row(elem_id = "input-message"):
226
- textbox=gr.Textbox(placeholder="Ask me anything here!",show_label=False,scale=7,lines = 1,interactive = True,elem_id="input-textbox")
227
- # submit = gr.Button("",elem_id = "submit-button",scale = 1,interactive = True,icon = "https://static-00.iconduck.com/assets.00/settings-icon-2048x2046-cw28eevx.png")
228
-
229
-
230
- with gr.Column(scale=1, variant="panel",elem_id = "right-panel"):
231
-
232
-
233
- with gr.Tabs() as tabs:
234
-
235
- with gr.Tab("Reports",elem_id = "tab-config",id = 2):
236
-
237
- gr.Markdown("Reminder: To get better results select the specific report/reports")
238
-
239
- dropdown_sources = gr.Radio(
240
- ["Consolidated", "District","Ministry"],
241
- label="Select Report Source",
242
- value="Consolidated",
243
- interactive=True,
244
- )
245
-
246
- dropdown_category = gr.Dropdown(
247
- list(files["Consolidated"].keys()),
248
- value = list(files["Consolidated"].keys())[0],
249
- label = "Filter for Sub-Type",
250
- interactive=True)
251
-
252
- def rs_change(rs):
253
- return gr.update(choices=files[rs], value=list(files[rs].keys())[0])
254
-
255
- dropdown_sources.change(fn=rs_change, inputs=[dropdown_sources], outputs=[dropdown_category])
256
-
257
- dropdown_year = gr.Dropdown(
258
- [2018,2019,2020,2021,2022,2023],
259
- label="Filter for year",
260
- multiselect=True,
261
- value=[2023],
262
- interactive=True,
263
- )
264
-
265
- dropdown_reports = gr.Dropdown(
266
- POSSIBLE_REPORTS,
267
- label="Or select specific reports",
268
- multiselect=True,
269
- value=None,
270
- interactive=True,
271
- )
272
-
273
- #output_query = gr.Textbox(label="Query used for retrieval",show_label = True,elem_id = "reformulated-query",lines = 2,interactive = False)
274
- #output_language = gr.Textbox(label="Language",show_label = True,elem_id = "language",lines = 1,interactive = False)
275
-
276
-
277
-
278
-
279
- with gr.TabItem("Examples",elem_id = "tab-examples",id = 0):
280
-
281
- examples_hidden = gr.Textbox(visible = False)
282
- first_key = list(QUESTIONS.keys())[0]
283
- dropdown_samples = gr.Dropdown(QUESTIONS.keys(),value = first_key,interactive = True,show_label = True,label = "Select a category of sample questions",elem_id = "dropdown-samples")
284
-
285
- samples = []
286
- for i,key in enumerate(QUESTIONS.keys()):
287
-
288
- examples_visible = True if i == 0 else False
289
-
290
- with gr.Row(visible = examples_visible) as group_examples:
291
-
292
- examples_questions = gr.Examples(
293
- QUESTIONS[key],
294
- [examples_hidden],
295
- examples_per_page=8,
296
- run_on_click=False,
297
- elem_id=f"examples{i}",
298
- api_name=f"examples{i}",
299
- # label = "Click on the example question or enter your own",
300
- # cache_examples=True,
301
- )
302
-
303
- samples.append(group_examples)
304
-
305
-
306
- with gr.Tab("Sources",elem_id = "tab-citations",id = 1):
307
- sources_textbox = gr.HTML(show_label=False, elem_id="sources-textbox")
308
- docs_textbox = gr.State("")
309
-
310
- # with Modal(visible = False) as config_modal:
311
-
312
-
313
- with gr.Tab("About",elem_classes = "max-height other-tabs"):
314
- with gr.Row():
315
- with gr.Column(scale=1):
316
- gr.Markdown("""The <ins>[**Office of the Auditor General (OAG)**](https://www.oag.go.ug/welcome)</ins> in Uganda, \
317
- consistent with the mandate of Supreme Audit Institutions (SAIs),\
318
- remains integral in ensuring transparency and fiscal responsibility.\
319
- Regularly, the OAG submits comprehensive audit reports to Parliament, \
320
- which serve as instrumental references for both policymakers and the public, \
321
- facilitating informed decisions regarding public expenditure.
322
-
323
- However, the prevalent underutilization of these audit reports, \
324
- leading to numerous unimplemented recommendations, has posed significant challenges\
325
- to the effectiveness and impact of the OAG's operations. The audit reports made available \
326
- to the public have not been effectively used by them and other relevant stakeholders. \
327
- The current format of the audit reports is considered a challenge to the \
328
- stakeholders' accessibility and usability. This in one way constrains transparency \
329
- and accountability in the utilization of public funds and effective service delivery.
330
-
331
- In the face of this, modern advancements in Artificial Intelligence (AI),\
332
- particularly Retrieval Augmented Generation (RAG) technology, \
333
- emerge as a promising solution. By harnessing the capabilities of such AI tools, \
334
- there is an opportunity not only to improve the accessibility and understanding \
335
- of these audit reports but also to ensure that their insights are effectively \
336
- translated into actionable outcomes, thereby reinforcing public transparency \
337
- and service delivery in Uganda.
338
-
339
- To address these issues, the OAG has initiated several projects, \
340
- such as the Audit Recommendation Tracking (ART) System and the Citizens Feedback Platform (CFP). \
341
- These systems are designed to increase the transparency and relevance of audit activities. \
342
- However, despite these efforts, engagement and awareness of the audit findings remain low, \
343
- and the complexity of the information often hinders effective public utilization. Recognizing the need for further\
344
- enhancement in how audit reports are processed and understood, \
345
- the **Civil Society and Budget Advocacy Group (CSBAG)** in partnership with the **GIZ**, \
346
- has recognizing the need for further enhancement in how audit reports are processed and understood.
347
-
348
- This prototype tool leveraging AI (Artificial Intelligence) aims at offering critical capabilities such as '
349
- summarizing complex texts, extracting thematic insights, and enabling interactive, \
350
- user-friendly analysis through a chatbot interface. By making the audit reports more accessible,\
351
- this aims to increase readership and utilization among stakeholders, \
352
- which can lead to better accountability and improve service delivery
353
-
354
- """)
355
-
356
-
357
- with gr.Tab("Disclaimer",elem_classes = "max-height other-tabs"):
358
- with gr.Row():
359
- with gr.Column(scale=1):
360
- gr.Markdown("""
361
- - This chatbot is intended for specific use of answering the questions based on audit reports published by OAG, for any use beyond this scope we have no liability to response provided by chatbot.
362
- - We do not guarantee the accuracy, reliability, or completeness of any information provided by the chatbot and disclaim any liability or responsibility for actions taken based on its responses.
363
- - The chatbot may occasionally provide inaccurate or inappropriate responses, and it is important to exercise judgment and critical thinking when interpreting its output.
364
- - 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.
365
- - The chatbot's responses do not reflect the opinions or policies of our organization or its affiliates.
366
- - Any personal or sensitive information shared with the chatbot is at the user's own risk, and we cannot guarantee complete privacy or confidentiality.
367
- - the chatbot is not deterministic, so there might be change in answer to same question when asked by different users or multiple times.
368
- - 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.
369
- - **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.
370
- """)
371
-
372
- def start_chat(query,history):
373
- history = history + [(query,None)]
374
- history = [tuple(x) for x in history]
375
- return (gr.update(interactive = False),gr.update(selected=1),history)
376
-
377
- def finish_chat():
378
- return (gr.update(interactive = True,value = ""))
379
-
380
- (textbox
381
- .submit(start_chat, [textbox,chatbot], [textbox,tabs,chatbot],queue = False,api_name = "start_chat_textbox")
382
- .then(chat, [textbox,chatbot, dropdown_sources,dropdown_reports], [chatbot,sources_textbox],concurrency_limit = 8,api_name = "chat_textbox")
383
- .then(finish_chat, None, [textbox],api_name = "finish_chat_textbox")
384
- )
385
-
386
- (examples_hidden
387
- .change(start_chat, [examples_hidden,chatbot], [textbox,tabs,chatbot],queue = False,api_name = "start_chat_examples")
388
- .then(chat, [examples_hidden,chatbot, dropdown_sources,dropdown_reports], [chatbot,sources_textbox],concurrency_limit = 8,api_name = "chat_examples")
389
- .then(finish_chat, None, [textbox],api_name = "finish_chat_examples")
390
- )
391
-
392
-
393
- def change_sample_questions(key):
394
- index = list(QUESTIONS.keys()).index(key)
395
- visible_bools = [False] * len(samples)
396
- visible_bools[index] = True
397
- return [gr.update(visible=visible_bools[i]) for i in range(len(samples))]
398
-
399
-
400
-
401
- dropdown_samples.change(change_sample_questions,dropdown_samples,samples)
402
-
403
- demo.queue()
404
-
405
- demo.launch()