Krish30 commited on
Commit
02508bd
·
verified ·
1 Parent(s): 038e2b6

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +185 -162
app.py CHANGED
@@ -1,162 +1,185 @@
1
- import os
2
- import json
3
- import sqlite3
4
- from datetime import datetime
5
- import streamlit as st
6
- from langchain_huggingface import HuggingFaceEmbeddings
7
- from langchain_chroma import Chroma
8
- from langchain_groq import ChatGroq
9
- from langchain.memory import ConversationBufferMemory
10
- from langchain.chains import ConversationalRetrievalChain
11
-
12
- # Directory paths and configurations
13
- working_dir = os.path.dirname(os.path.abspath(__file__))
14
- config_data = json.load(open(f"{working_dir}/config.json"))
15
- GROQ_API_KEY = config_data["GROQ_API_KEY"]
16
- os.environ["GROQ_API_KEY"] = GROQ_API_KEY
17
-
18
- # Database setup
19
- def setup_db():
20
- conn = sqlite3.connect("chat_history.db", check_same_thread=False)
21
- cursor = conn.cursor()
22
- cursor.execute("""
23
- CREATE TABLE IF NOT EXISTS chat_histories (
24
- id INTEGER PRIMARY KEY AUTOINCREMENT,
25
- username TEXT,
26
- timestamp TEXT,
27
- day TEXT,
28
- user_input TEXT,
29
- assistant_response TEXT
30
- )
31
- """)
32
- conn.commit()
33
- return conn
34
-
35
- # Save chat history to SQLite
36
- def save_chat_history(conn, username, timestamp, day, user_input, assistant_response):
37
- cursor = conn.cursor()
38
- cursor.execute("""
39
- INSERT INTO chat_histories (username, timestamp, day, user_input, assistant_response)
40
- VALUES (?, ?, ?, ?, ?)
41
- """, (username, timestamp, day, user_input, assistant_response))
42
- conn.commit()
43
-
44
- # Vectorstore setup
45
- def setup_vectorstore():
46
- embeddings = HuggingFaceEmbeddings()
47
- vectorstore = Chroma(persist_directory="soil_vectordb", embedding_function=embeddings)
48
- return vectorstore
49
-
50
- # Chatbot chain setup
51
- def chat_chain(vectorstore):
52
- llm = ChatGroq(model="llama-3.1-70b-versatile", temperature=0)
53
- retriever = vectorstore.as_retriever()
54
- memory = ConversationBufferMemory(
55
- llm=llm,
56
- output_key="answer",
57
- memory_key="chat_history",
58
- return_messages=True
59
- )
60
- chain = ConversationalRetrievalChain.from_llm(
61
- llm=llm,
62
- retriever=retriever,
63
- chain_type="stuff",
64
- memory=memory,
65
- verbose=True,
66
- return_source_documents=True
67
- )
68
- return chain
69
-
70
- # Streamlit setup
71
- st.set_page_config(page_title="Soil.Ai", page_icon="🌱", layout="centered")
72
- st.title("🌱 Soil.Ai - Smart Farming Recommendations")
73
- st.subheader("AI-driven solutions for modern farming!")
74
-
75
- # Initialize database and session state
76
- if "conn" not in st.session_state:
77
- st.session_state.conn = setup_db()
78
-
79
- if "username" not in st.session_state:
80
- username = st.text_input("Enter your name to proceed:")
81
- if username:
82
- with st.spinner("Loading AI interface..."):
83
- st.session_state.username = username
84
- st.session_state.chat_history = []
85
- st.session_state.vectorstore = setup_vectorstore()
86
- st.session_state.conversational_chain = chat_chain(st.session_state.vectorstore)
87
- st.success(f"Welcome, {username}! Start by choosing an option.")
88
- else:
89
- username = st.session_state.username
90
-
91
- # Main interface
92
- if "conversational_chain" not in st.session_state:
93
- st.session_state.vectorstore = setup_vectorstore()
94
- st.session_state.conversational_chain = chat_chain(st.session_state.vectorstore)
95
-
96
- if "username" in st.session_state:
97
- st.subheader(f"Hello {username}, choose your option below:")
98
-
99
- # Option selection: Ask a general question or input sensor data
100
- option = st.radio(
101
- "Choose an action:",
102
- ("Ask a general agriculture-related question", "Input sensor data for recommendations")
103
- )
104
-
105
- # Option 1: Ask AI any agriculture-related question
106
- if option == "Ask a general agriculture-related question":
107
- user_query = st.chat_input("Ask AI anything about agriculture...")
108
- if user_query:
109
- with st.spinner("Processing your query..."):
110
- # Display user's query
111
- with st.chat_message("user"):
112
- st.markdown(user_query)
113
-
114
- # Get assistant's response
115
- with st.chat_message("assistant"):
116
- response = st.session_state.conversational_chain({"question": user_query})
117
- assistant_response = response["answer"]
118
- st.markdown(assistant_response)
119
-
120
- # Save chat history
121
- st.session_state.chat_history.append({"role": "user", "content": user_query})
122
- st.session_state.chat_history.append({"role": "assistant", "content": assistant_response})
123
-
124
- # Save to database
125
- timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
126
- day = datetime.now().strftime("%A")
127
- save_chat_history(st.session_state.conn, username, timestamp, day, user_query, assistant_response)
128
-
129
- # Option 2: Input sensor data for recommendations
130
- elif option == "Input sensor data for recommendations":
131
- st.markdown("### Enter soil and environmental parameters:")
132
- ph = st.number_input("Enter Soil pH", min_value=0.0, max_value=14.0, step=0.1)
133
- moisture = st.number_input("Enter Soil Moisture (%)", min_value=0.0, max_value=100.0, step=0.1)
134
- temperature = st.number_input("Enter Temperature (°C)", min_value=-50.0, max_value=60.0, step=0.1)
135
- air_quality = st.number_input("Enter Air Quality Index (AQI)", min_value=0, max_value=500, step=1)
136
-
137
- if st.button("Get Recommendations"):
138
- if ph and moisture and temperature and air_quality:
139
- with st.spinner("Analyzing data..."):
140
- # Prepare input query
141
- user_input = f"Recommendations for:\n- pH: {ph}\n- Moisture: {moisture}%\n- Temperature: {temperature}°C\n- Air Quality: {air_quality}"
142
-
143
- # Display user's input
144
- with st.chat_message("user"):
145
- st.markdown(user_input)
146
-
147
- # Get assistant's response
148
- with st.chat_message("assistant"):
149
- response = st.session_state.conversational_chain({"question": user_input})
150
- assistant_response = response["answer"]
151
- st.markdown(assistant_response)
152
-
153
- # Save chat history
154
- st.session_state.chat_history.append({"role": "user", "content": user_input})
155
- st.session_state.chat_history.append({"role": "assistant", "content": assistant_response})
156
-
157
- # Save to database
158
- timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
159
- day = datetime.now().strftime("%A")
160
- save_chat_history(st.session_state.conn, username, timestamp, day, user_input, assistant_response)
161
- else:
162
- st.error("Please fill in all the fields!")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import json
3
+ import sqlite3
4
+ from datetime import datetime
5
+ import streamlit as st
6
+ from langchain_huggingface import HuggingFaceEmbeddings
7
+ from langchain_chroma import Chroma
8
+ from langchain_groq import ChatGroq
9
+ from langchain.memory import ConversationBufferMemory
10
+ from langchain.chains import ConversationalRetrievalChain
11
+ from deep_translator import GoogleTranslator
12
+
13
+ # Directory paths and configurations
14
+ working_dir = os.path.dirname(os.path.abspath(__file__))
15
+ config_data = json.load(open(f"{working_dir}/config.json"))
16
+ GROQ_API_KEY = config_data["GROQ_API_KEY"]
17
+ os.environ["GROQ_API_KEY"] = GROQ_API_KEY
18
+
19
+ # Database setup
20
+ def setup_db():
21
+ conn = sqlite3.connect("chat_history.db", check_same_thread=False)
22
+ cursor = conn.cursor()
23
+ cursor.execute("""
24
+ CREATE TABLE IF NOT EXISTS chat_histories (
25
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
26
+ username TEXT,
27
+ timestamp TEXT,
28
+ day TEXT,
29
+ user_input TEXT,
30
+ assistant_response TEXT
31
+ )
32
+ """)
33
+ conn.commit()
34
+ return conn
35
+
36
+ # Save chat history to SQLite
37
+ def save_chat_history(conn, username, timestamp, day, user_input, assistant_response):
38
+ cursor = conn.cursor()
39
+ cursor.execute("""
40
+ INSERT INTO chat_histories (username, timestamp, day, user_input, assistant_response)
41
+ VALUES (?, ?, ?, ?, ?)
42
+ """, (username, timestamp, day, user_input, assistant_response))
43
+ conn.commit()
44
+
45
+ # Vectorstore setup
46
+ def setup_vectorstore():
47
+ embeddings = HuggingFaceEmbeddings()
48
+ vectorstore = Chroma(persist_directory="soil_vectordb", embedding_function=embeddings)
49
+ return vectorstore
50
+
51
+ # Chatbot chain setup
52
+ def chat_chain(vectorstore):
53
+ llm = ChatGroq(model="llama-3.1-70b-versatile", temperature=0)
54
+ retriever = vectorstore.as_retriever()
55
+ memory = ConversationBufferMemory(
56
+ llm=llm,
57
+ output_key="answer",
58
+ memory_key="chat_history",
59
+ return_messages=True
60
+ )
61
+ chain = ConversationalRetrievalChain.from_llm(
62
+ llm=llm,
63
+ retriever=retriever,
64
+ chain_type="stuff",
65
+ memory=memory,
66
+ verbose=True,
67
+ return_source_documents=True
68
+ )
69
+ return chain
70
+
71
+ # Streamlit setup
72
+ st.set_page_config(page_title="Soil.Ai", page_icon="🌱", layout="centered")
73
+ st.title("🌱 Soil.Ai - Smart Farming Recommendations")
74
+ st.subheader("AI-driven solutions for modern farming!")
75
+
76
+ # Initialize database and session state
77
+ if "conn" not in st.session_state:
78
+ st.session_state.conn = setup_db()
79
+
80
+ if "username" not in st.session_state:
81
+ username = st.text_input("Enter your name to proceed:")
82
+ if username:
83
+ with st.spinner("Loading AI interface..."):
84
+ st.session_state.username = username
85
+ st.session_state.chat_history = []
86
+ st.session_state.vectorstore = setup_vectorstore()
87
+ st.session_state.conversational_chain = chat_chain(st.session_state.vectorstore)
88
+ st.success(f"Welcome, {username}! Start by choosing an option.")
89
+ else:
90
+ username = st.session_state.username
91
+
92
+ # Main interface
93
+ if "conversational_chain" not in st.session_state:
94
+ st.session_state.vectorstore = setup_vectorstore()
95
+ st.session_state.conversational_chain = chat_chain(st.session_state.vectorstore)
96
+
97
+ if "username" in st.session_state:
98
+ st.subheader(f"Hello {username}, choose your option below:")
99
+
100
+ # Option selection: Ask a general question or input sensor data
101
+ option = st.radio(
102
+ "Choose an action:",
103
+ ("Ask a general agriculture-related question", "Input sensor data for recommendations")
104
+ )
105
+
106
+ # Option 1: Ask AI any agriculture-related question
107
+ if option == "Ask a general agriculture-related question":
108
+ user_query = st.chat_input("Ask AI anything about agriculture...")
109
+ if user_query:
110
+ with st.spinner("Processing your query..."):
111
+ # Display user's query
112
+ with st.chat_message("user"):
113
+ st.markdown(user_query)
114
+
115
+ # Get assistant's response
116
+ with st.chat_message("assistant"):
117
+ response = st.session_state.conversational_chain({"question": user_query})
118
+ assistant_response = response["answer"]
119
+
120
+ # Translate the assistant response to Marathi and Hindi
121
+ translator_marathi = GoogleTranslator(source="en", target="mr")
122
+ translator_hindi = GoogleTranslator(source="en", target="hi")
123
+
124
+ translated_response_marathi = translator_marathi.translate(assistant_response)
125
+ translated_response_hindi = translator_hindi.translate(assistant_response)
126
+
127
+ # Display responses in English, Marathi, and Hindi
128
+ st.markdown(f"**English:** {assistant_response}")
129
+ st.markdown(f"**Marathi:** {translated_response_marathi}")
130
+ st.markdown(f"**Hindi:** {translated_response_hindi}")
131
+
132
+ # Save chat history
133
+ st.session_state.chat_history.append({"role": "user", "content": user_query})
134
+ st.session_state.chat_history.append({"role": "assistant", "content": assistant_response})
135
+
136
+ # Save to database
137
+ timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
138
+ day = datetime.now().strftime("%A")
139
+ save_chat_history(st.session_state.conn, username, timestamp, day, user_query, assistant_response)
140
+
141
+ # Option 2: Input sensor data for recommendations
142
+ elif option == "Input sensor data for recommendations":
143
+ st.markdown("### Enter soil and environmental parameters:")
144
+ ph = st.number_input("Enter Soil pH", min_value=0.0, max_value=14.0, step=0.1)
145
+ moisture = st.number_input("Enter Soil Moisture (%)", min_value=0.0, max_value=100.0, step=0.1)
146
+ temperature = st.number_input("Enter Temperature (°C)", min_value=-50.0, max_value=60.0, step=0.1)
147
+ air_quality = st.number_input("Enter Air Quality Index (AQI)", min_value=0, max_value=500, step=1)
148
+
149
+ if st.button("Get Recommendations"):
150
+ if ph and moisture and temperature and air_quality:
151
+ with st.spinner("Analyzing data..."):
152
+ # Prepare input query
153
+ user_input = f"Recommendations for:\n- pH: {ph}\n- Moisture: {moisture}%\n- Temperature: {temperature}°C\n- Air Quality: {air_quality}"
154
+
155
+ # Display user's input
156
+ with st.chat_message("user"):
157
+ st.markdown(user_input)
158
+
159
+ # Get assistant's response
160
+ with st.chat_message("assistant"):
161
+ response = st.session_state.conversational_chain({"question": user_input})
162
+ assistant_response = response["answer"]
163
+
164
+ # Translate the assistant response to Marathi and Hindi
165
+ translator_marathi = GoogleTranslator(source="en", target="mr")
166
+ translator_hindi = GoogleTranslator(source="en", target="hi")
167
+
168
+ translated_response_marathi = translator_marathi.translate(assistant_response)
169
+ translated_response_hindi = translator_hindi.translate(assistant_response)
170
+
171
+ # Display responses in English, Marathi, and Hindi
172
+ st.markdown(f"**English:** {assistant_response}")
173
+ st.markdown(f"**Marathi:** {translated_response_marathi}")
174
+ st.markdown(f"**Hindi:** {translated_response_hindi}")
175
+
176
+ # Save chat history
177
+ st.session_state.chat_history.append({"role": "user", "content": user_input})
178
+ st.session_state.chat_history.append({"role": "assistant", "content": assistant_response})
179
+
180
+ # Save to database
181
+ timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
182
+ day = datetime.now().strftime("%A")
183
+ save_chat_history(st.session_state.conn, username, timestamp, day, user_input, assistant_response)
184
+ else:
185
+ st.error("Please fill in all the fields!")