Spaces:
Runtime error
Runtime error
Update app.py
Browse files
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 |
-
|
13 |
-
|
14 |
-
|
15 |
-
|
16 |
-
|
17 |
-
|
18 |
-
|
19 |
-
|
20 |
-
|
21 |
-
|
22 |
-
cursor.
|
23 |
-
|
24 |
-
|
25 |
-
|
26 |
-
|
27 |
-
|
28 |
-
|
29 |
-
|
30 |
-
|
31 |
-
|
32 |
-
|
33 |
-
|
34 |
-
|
35 |
-
|
36 |
-
|
37 |
-
|
38 |
-
cursor.
|
39 |
-
|
40 |
-
|
41 |
-
|
42 |
-
|
43 |
-
|
44 |
-
|
45 |
-
|
46 |
-
|
47 |
-
|
48 |
-
|
49 |
-
|
50 |
-
|
51 |
-
|
52 |
-
|
53 |
-
|
54 |
-
|
55 |
-
|
56 |
-
|
57 |
-
|
58 |
-
|
59 |
-
|
60 |
-
|
61 |
-
|
62 |
-
|
63 |
-
|
64 |
-
|
65 |
-
|
66 |
-
|
67 |
-
|
68 |
-
|
69 |
-
|
70 |
-
|
71 |
-
|
72 |
-
st.
|
73 |
-
st.
|
74 |
-
|
75 |
-
|
76 |
-
|
77 |
-
|
78 |
-
|
79 |
-
|
80 |
-
|
81 |
-
|
82 |
-
|
83 |
-
|
84 |
-
st.session_state.
|
85 |
-
st.session_state.
|
86 |
-
st.session_state.
|
87 |
-
st.
|
88 |
-
|
89 |
-
|
90 |
-
|
91 |
-
|
92 |
-
|
93 |
-
|
94 |
-
st.session_state.
|
95 |
-
|
96 |
-
|
97 |
-
|
98 |
-
|
99 |
-
|
100 |
-
|
101 |
-
|
102 |
-
|
103 |
-
|
104 |
-
|
105 |
-
|
106 |
-
|
107 |
-
|
108 |
-
|
109 |
-
|
110 |
-
|
111 |
-
|
112 |
-
|
113 |
-
|
114 |
-
|
115 |
-
|
116 |
-
|
117 |
-
|
118 |
-
|
119 |
-
|
120 |
-
#
|
121 |
-
|
122 |
-
|
123 |
-
|
124 |
-
|
125 |
-
|
126 |
-
|
127 |
-
|
128 |
-
|
129 |
-
|
130 |
-
|
131 |
-
|
132 |
-
|
133 |
-
|
134 |
-
|
135 |
-
|
136 |
-
|
137 |
-
|
138 |
-
|
139 |
-
|
140 |
-
|
141 |
-
|
142 |
-
|
143 |
-
|
144 |
-
|
145 |
-
|
146 |
-
|
147 |
-
|
148 |
-
|
149 |
-
|
150 |
-
|
151 |
-
|
152 |
-
|
153 |
-
|
154 |
-
|
155 |
-
|
156 |
-
|
157 |
-
|
158 |
-
|
159 |
-
|
160 |
-
|
161 |
-
|
162 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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!")
|