mtyrrell commited on
Commit
ca49a1b
1 Parent(s): a32f2dc

Upload app.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. app.py +110 -0
app.py ADDED
@@ -0,0 +1,110 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # inspiration from Ekimetrics climate qa
2
+
3
+ import streamlit as st
4
+ import os
5
+ import json
6
+ from dotenv import load_dotenv
7
+ from haystack.nodes.prompt import PromptNode, PromptTemplate
8
+ from haystack.nodes import EmbeddingRetriever
9
+ from haystack import Pipeline
10
+ import numpy as np
11
+ import pandas as pd
12
+ from haystack.document_stores import FAISSDocumentStore
13
+ from haystack.nodes import EmbeddingRetriever
14
+ from haystack.schema import Document
15
+
16
+
17
+ # Enter openai API key
18
+ openai_key = os.environ["OPENAI_API_KEY"]
19
+
20
+ # Select model
21
+ model_name = "gpt-3.5-turbo"
22
+
23
+ # Define the template
24
+ template = PromptTemplate(
25
+ prompt="""
26
+ Answer the given question using the provided documents. The answer should be in the style of an academic report and should provide example quotes and references. Always start the response by stating the name of the country relevant to the documents. When relevant, use bullet points and lists to structure your answers. When relevant, use facts and numbers from the following documents in your answer. Whenever you use information from a document, reference it at the end of the sentence (ex: [doc 2]). You don't have to use all documents, only if it makes sense in the conversation. If no relevant information to answer the question is present in the documents, just say you don't have enough information to answer.
27
+
28
+ Context: {join(documents)}\n\nQuestion: {query}\n\nAnswer:""",
29
+ )
30
+
31
+ # Create a list of options for the dropdown
32
+ country_options = ['Angola','Botswana','Lesotho','Malawi','Mozambique','Namibia','South Africa','Zambia','Zimbabwe']
33
+
34
+ # List of examples
35
+ examples = [
36
+ "-",
37
+ "What specific initiatives are presented in the context to address the needs of groups such women and children to the effects climate change?",
38
+ "In addition to gender, children, and youth, is there any mention of other groups facing disproportional impacts from climate change due to their geographic location, socio-economic status, age, gender, health, and occupation?"
39
+ ]
40
+
41
+ def get_docs(input_query, country = None):
42
+ # Construct a hacky query to focus the retriever on the target country (see notes below)
43
+ if country:
44
+ query = "For the country of "+country+", "+input_query
45
+ else:
46
+ query = input_query
47
+ # Get top 150 because we want to make sure we have 10 pertaining to the selected country
48
+ # TEMP SOLUTION: not ideal, but FAISS document store doesnt allow metadata filtering. Needs to be tested with the full dataset
49
+ docs = retriever.retrieve(query=query,top_k = 150)
50
+ # Break out the key fields and convert to pandas for filtering
51
+ docs = [{**x.meta,"score":x.score,"content":x.content} for x in docs]
52
+ df_docs = pd.DataFrame(docs)
53
+ if country:
54
+ df_docs = df_docs.query('country in @country')
55
+ # Take the top 10
56
+ df_docs = df_docs.head(10)
57
+ # Convert back to Document format
58
+ ls_dict = []
59
+ for doc, _ in df_docs.iterrows():
60
+ x = Document(df_docs['content'][doc])
61
+ ls_dict.append(x)
62
+ return(ls_dict)
63
+
64
+ def run_query(input_text):
65
+ docs = get_docs(input_text)
66
+ res = pipe.run(query=input_text, documents=docs)
67
+ output = res["results"][0]
68
+ st.write('Response')
69
+ st.success(output)
70
+
71
+
72
+ # Setup retriever, pulling from local faiss datastore
73
+ retriever = EmbeddingRetriever(
74
+ document_store=FAISSDocumentStore.load(
75
+ index_path="./cpv_test_2.faiss",
76
+ config_path="./cpv_test_2.json",
77
+ ),
78
+ embedding_model="sentence-transformers/multi-qa-mpnet-base-dot-v1",
79
+ model_format="sentence_transformers",
80
+ progress_bar=False,
81
+ )
82
+
83
+ # Initialize the PromptNode
84
+ pn = PromptNode(model_name_or_path=model_name, default_prompt_template=template, api_key=openai_key, max_length=700)
85
+
86
+ # Initialize the pipeline
87
+ pipe = Pipeline()
88
+ pipe.add_node(component=pn, name="prompt_node", inputs=["Query"])
89
+
90
+
91
+ # Guiding text
92
+ st.title('Climate Policy Documents: Vulnerabilities Analysis Q&A (test)')
93
+ st.markdown('This tool seeks to provide an interface for quering national climate policy documents (NDCs, LTS etc.). The current version is powered by chatGPT (3.5) and limited to 9 Southern African countries (Angola, Botswana, Eswatini, Lesotho, Malawi, Mozambique, Namibia, South Africa, Zambia, Zimbabwe). The intended use case is to allow users to interact with the documents and obtain valuable insights on various vulnerable groups affected by climate change.')
94
+
95
+
96
+
97
+ # Dropdown selectbox
98
+ country = st.selectbox('Select a country:', country_options)
99
+
100
+ # Display the text passages as radio buttons
101
+ selected_example = st.radio("Example questions", examples)
102
+
103
+ if selected_example == "-":
104
+ text = st.text_area('Enter your question in the text box below using natural language or select an example from above:')
105
+ else:
106
+ text = st.text_area('Enter your question in the text box below using natural language or select an example from above:', value=selected_example)
107
+
108
+
109
+ if st.button('Submit'):
110
+ run_query(text)