shukdevdatta123 commited on
Commit
0283ec5
·
verified ·
1 Parent(s): 49e589b

Upload app.py

Browse files
Files changed (1) hide show
  1. app.py +141 -0
app.py ADDED
@@ -0,0 +1,141 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import pandas as pd
3
+ import streamlit as st
4
+ from llama_index.experimental.query_engine import PandasQueryEngine
5
+ from prompts import new_prompt, instruction_str, context
6
+ from note_engine import note_engine
7
+ from llama_index.core.tools import QueryEngineTool, ToolMetadata
8
+ from llama_index.core.agent import ReActAgent
9
+ from llama_index.llms.openai import OpenAI
10
+ from data_summary import data_summary_tool
11
+ from pdf import bangladesh_engine
12
+ from dotenv import load_dotenv
13
+
14
+ # Load environment variables
15
+ load_dotenv()
16
+
17
+ # File paths
18
+ conversation_file = os.path.join("data", "conversation.txt")
19
+ summary_file = os.path.join("data", "data_summary.txt")
20
+ population_path = os.path.join("data", "Population.csv")
21
+ population_df = pd.read_csv(population_path)
22
+
23
+ # Set up the Streamlit app
24
+ st.title("🌎 Population and Bangladesh Data Assistant")
25
+
26
+ # Sidebar for OpenAI API key
27
+ api_key = st.sidebar.text_input("Enter your OpenAI API Key", type="password")
28
+ if api_key:
29
+ os.environ["OPENAI_API_KEY"] = api_key
30
+
31
+ # Initialize query engines
32
+ population_query_engine = PandasQueryEngine(
33
+ df=population_df, verbose=True, instruction_str=instruction_str
34
+ )
35
+
36
+ population_query_engine.update_prompts({"pandas_prompt": new_prompt})
37
+
38
+ tools = [
39
+ QueryEngineTool(
40
+ query_engine=population_query_engine,
41
+ metadata=ToolMetadata(
42
+ name="population_data",
43
+ description="Provides information about world population and demographics",
44
+ ),
45
+ ),
46
+ QueryEngineTool(
47
+ query_engine=bangladesh_engine,
48
+ metadata=ToolMetadata(
49
+ name="bangladesh_data",
50
+ description="Provides detailed information about Bangladesh",
51
+ ),
52
+ ),
53
+ ]
54
+
55
+ llm = OpenAI(model="gpt-3.5-turbo")
56
+ agent = ReActAgent.from_tools(tools, llm=llm, verbose=True, context=context)
57
+
58
+ # Sidebar options
59
+ st.sidebar.header("Options")
60
+ option = st.sidebar.selectbox("Choose an action:", [
61
+ "Ask a Question",
62
+ "View Previous Conversations",
63
+ "View Data Summary",
64
+ "Save a Note"
65
+ ])
66
+
67
+ # Conversation management
68
+ conversation_active = st.session_state.get('conversation_active', False)
69
+
70
+ if option == "Ask a Question":
71
+ if not conversation_active:
72
+ st.session_state.conversation_active = True
73
+ st.session_state.conversation_history = []
74
+
75
+ prompt = st.text_area("Enter your query:", key="user_input")
76
+
77
+ if st.button("Submit"):
78
+ if prompt:
79
+ result = agent.query(prompt)
80
+ response_text = result.response # Extract just the response text
81
+ st.write("Response:", response_text) # Show only the response text
82
+
83
+ # Save the conversation with a timestamp
84
+ timestamp = pd.Timestamp.now().strftime("%Y-%m-%d %H:%M:%S")
85
+ st.session_state.conversation_history.append((timestamp, prompt, response_text))
86
+ else:
87
+ st.error("Please enter a query.")
88
+
89
+ if st.button("Save this Conversation"):
90
+ # Save entire conversation history to the file
91
+ with open(conversation_file, "a") as file:
92
+ for timestamp, user_prompt, bot_response in st.session_state.conversation_history:
93
+ file.write(f"Timestamp: {timestamp}\n")
94
+ file.write(f"Prompt: {user_prompt}\n")
95
+ file.write(f"Response: {bot_response}\n")
96
+ file.write("=" * 40 + "\n")
97
+ st.success("Conversation saved.")
98
+
99
+ if st.button("End Conversation"):
100
+ st.session_state.conversation_active = False
101
+ st.success("Conversation ended.")
102
+
103
+ # View previous conversations
104
+ elif option == "View Previous Conversations":
105
+ if os.path.exists(conversation_file):
106
+ with open(conversation_file, "r") as file:
107
+ st.text_area("Previous Conversations", file.read(), height=300)
108
+ else:
109
+ st.warning("No previous conversations found.")
110
+
111
+ # View data summary
112
+ elif option == "View Data Summary":
113
+ if os.path.exists(summary_file):
114
+ with open(summary_file, "r") as file:
115
+ st.text_area("Data Summary", file.read(), height=300)
116
+ else:
117
+ st.warning("No data summary found.")
118
+
119
+ # Save a note
120
+ elif option == "Save a Note":
121
+ note = st.text_input("Enter a note to save:")
122
+ if st.button("Save Note"):
123
+ if note:
124
+ # Append note to the conversation file with a timestamp
125
+ timestamp = pd.Timestamp.now().strftime("%Y-%m-%d %H:%M:%S")
126
+ with open(conversation_file, "a") as file:
127
+ file.write(f"Timestamp: {timestamp} (Note)\n")
128
+ file.write(f"Note: {note}\n")
129
+ file.write("=" * 40 + "\n") # Separator for readability
130
+ st.success("Note saved.")
131
+ else:
132
+ st.error("Please enter a note.")
133
+
134
+ # Instructions
135
+ st.sidebar.subheader("Instructions")
136
+ st.sidebar.write(
137
+ "1. Enter your OpenAI API Key in the sidebar.\n"
138
+ "2. Use the sidebar to choose an action: ask a question, view previous conversations, view the data summary, or save a note.\n"
139
+ "3. If you ask a question and click save, the conversation will be saved. If you ask multiple questions and then press save, it will save the whole conversation.\n"
140
+ "4. The End Conversation button will simply end the conversation without saving anything.\n"
141
+ )