Spaces:
Runtime error
Runtime error
Update app.py
Browse files
app.py
CHANGED
@@ -1,5 +1,8 @@
|
|
|
|
|
|
1 |
import os
|
2 |
import json
|
|
|
3 |
from datetime import datetime
|
4 |
import streamlit as st
|
5 |
from langchain_huggingface import HuggingFaceEmbeddings
|
@@ -15,6 +18,9 @@ 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 |
# Vectorstore setup
|
19 |
def setup_vectorstore():
|
20 |
embeddings = HuggingFaceEmbeddings()
|
@@ -41,6 +47,28 @@ def chat_chain(vectorstore):
|
|
41 |
)
|
42 |
return chain
|
43 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
44 |
# Updated Streamlit setup with language selection dropdown
|
45 |
st.set_page_config(page_title="Soil.Ai", page_icon="🌱", layout="centered")
|
46 |
st.title("🌱 Soil.Ai - Smart Farming Recommendations")
|
@@ -109,14 +137,17 @@ if "username" in st.session_state:
|
|
109 |
|
110 |
# Option 2: Input sensor data for recommendations
|
111 |
elif option == "Input sensor data for recommendations":
|
112 |
-
st.markdown("###
|
113 |
-
|
114 |
-
|
115 |
-
|
116 |
-
|
117 |
-
|
118 |
-
|
119 |
-
|
|
|
|
|
|
|
120 |
with st.spinner("Analyzing data..."):
|
121 |
# Prepare input query
|
122 |
user_input = f"Recommendations for:\n- pH: {ph}\n- Moisture: {moisture}%\n- Temperature: {temperature}°C\n- Air Quality: {air_quality}"
|
@@ -136,8 +167,6 @@ if "username" in st.session_state:
|
|
136 |
|
137 |
# Display response in selected language
|
138 |
st.markdown(f"**{st.session_state.selected_language}:** {translated_response}")
|
139 |
-
else:
|
140 |
-
st.error("Please fill in all the fields!")
|
141 |
|
142 |
# Option 3: Satellite Data
|
143 |
elif option == "Satellite Data":
|
@@ -145,40 +174,201 @@ if "username" in st.session_state:
|
|
145 |
|
146 |
# Option 4: FAQ Section
|
147 |
elif option == "FAQ Section":
|
148 |
-
|
149 |
-
|
150 |
-
|
151 |
-
|
152 |
-
|
153 |
-
|
154 |
-
|
155 |
-
|
156 |
-
|
157 |
-
|
158 |
-
|
159 |
-
|
160 |
-
|
161 |
-
|
162 |
-
|
163 |
-
|
164 |
-
|
165 |
-
|
166 |
-
|
167 |
-
|
168 |
-
|
169 |
-
|
170 |
-
|
171 |
-
|
172 |
-
|
173 |
-
|
174 |
-
|
175 |
-
|
176 |
-
|
177 |
-
|
178 |
-
|
179 |
-
|
180 |
-
|
181 |
-
|
182 |
-
|
183 |
-
|
184 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# New code in which sensor data is taken directly from thinkspace.
|
2 |
+
|
3 |
import os
|
4 |
import json
|
5 |
+
import requests
|
6 |
from datetime import datetime
|
7 |
import streamlit as st
|
8 |
from langchain_huggingface import HuggingFaceEmbeddings
|
|
|
18 |
GROQ_API_KEY = config_data["GROQ_API_KEY"]
|
19 |
os.environ["GROQ_API_KEY"] = GROQ_API_KEY
|
20 |
|
21 |
+
# ThinkSpace API details
|
22 |
+
THINGSPEAK_API_URL = "https://api.thingspeak.com/channels/2485113/feeds.json?results=2"
|
23 |
+
|
24 |
# Vectorstore setup
|
25 |
def setup_vectorstore():
|
26 |
embeddings = HuggingFaceEmbeddings()
|
|
|
47 |
)
|
48 |
return chain
|
49 |
|
50 |
+
# Fetch sensor data from ThinkSpace API
|
51 |
+
def fetch_sensor_data():
|
52 |
+
try:
|
53 |
+
response = requests.get(THINGSPEAK_API_URL)
|
54 |
+
if response.status_code == 200:
|
55 |
+
data = response.json()
|
56 |
+
feeds = data.get("feeds", [])
|
57 |
+
if feeds:
|
58 |
+
latest_feed = feeds[-1] # Get the latest feed
|
59 |
+
return {
|
60 |
+
"pH": float(latest_feed.get("field1", 0)),
|
61 |
+
"moisture": float(latest_feed.get("field2", 0)),
|
62 |
+
"temperature": float(latest_feed.get("field3", 0)),
|
63 |
+
"air_quality": float(latest_feed.get("field4", 0)),
|
64 |
+
}
|
65 |
+
else:
|
66 |
+
st.error("Failed to fetch data from ThinkSpace API. Please check the API URL or connectivity.")
|
67 |
+
return None
|
68 |
+
except Exception as e:
|
69 |
+
st.error(f"An error occurred while fetching sensor data: {e}")
|
70 |
+
return None
|
71 |
+
|
72 |
# Updated Streamlit setup with language selection dropdown
|
73 |
st.set_page_config(page_title="Soil.Ai", page_icon="🌱", layout="centered")
|
74 |
st.title("🌱 Soil.Ai - Smart Farming Recommendations")
|
|
|
137 |
|
138 |
# Option 2: Input sensor data for recommendations
|
139 |
elif option == "Input sensor data for recommendations":
|
140 |
+
st.markdown("### Fetching data from sensors...")
|
141 |
+
sensor_data = fetch_sensor_data()
|
142 |
+
if sensor_data:
|
143 |
+
ph = sensor_data["pH"]
|
144 |
+
moisture = sensor_data["moisture"]
|
145 |
+
temperature = sensor_data["temperature"]
|
146 |
+
air_quality = sensor_data["air_quality"]
|
147 |
+
|
148 |
+
st.markdown(f"**Sensor Data:**\n- pH: {ph}\n- Moisture: {moisture}%\n- Temperature: {temperature}°C\n- Air Quality: {air_quality}")
|
149 |
+
|
150 |
+
if st.button("Get Recommendations"):
|
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}"
|
|
|
167 |
|
168 |
# Display response in selected language
|
169 |
st.markdown(f"**{st.session_state.selected_language}:** {translated_response}")
|
|
|
|
|
170 |
|
171 |
# Option 3: Satellite Data
|
172 |
elif option == "Satellite Data":
|
|
|
174 |
|
175 |
# Option 4: FAQ Section
|
176 |
elif option == "FAQ Section":
|
177 |
+
st.markdown("### FAQs Coming Soon!")
|
178 |
+
|
179 |
+
|
180 |
+
|
181 |
+
|
182 |
+
|
183 |
+
|
184 |
+
|
185 |
+
|
186 |
+
|
187 |
+
|
188 |
+
|
189 |
+
# OLD code
|
190 |
+
|
191 |
+
# import os
|
192 |
+
# import json
|
193 |
+
# from datetime import datetime
|
194 |
+
# import streamlit as st
|
195 |
+
# from langchain_huggingface import HuggingFaceEmbeddings
|
196 |
+
# from langchain_chroma import Chroma
|
197 |
+
# from langchain_groq import ChatGroq
|
198 |
+
# from langchain.memory import ConversationBufferMemory
|
199 |
+
# from langchain.chains import ConversationalRetrievalChain
|
200 |
+
# from deep_translator import GoogleTranslator
|
201 |
+
|
202 |
+
# # Directory paths and configurations
|
203 |
+
# working_dir = os.path.dirname(os.path.abspath(__file__))
|
204 |
+
# config_data = json.load(open(f"{working_dir}/config.json"))
|
205 |
+
# GROQ_API_KEY = config_data["GROQ_API_KEY"]
|
206 |
+
# os.environ["GROQ_API_KEY"] = GROQ_API_KEY
|
207 |
+
|
208 |
+
# # Vectorstore setup
|
209 |
+
# def setup_vectorstore():
|
210 |
+
# embeddings = HuggingFaceEmbeddings()
|
211 |
+
# vectorstore = Chroma(persist_directory="soil_vectordb", embedding_function=embeddings)
|
212 |
+
# return vectorstore
|
213 |
+
|
214 |
+
# # Chatbot chain setup
|
215 |
+
# def chat_chain(vectorstore):
|
216 |
+
# llm = ChatGroq(model="llama-3.1-70b-versatile", temperature=0)
|
217 |
+
# retriever = vectorstore.as_retriever()
|
218 |
+
# memory = ConversationBufferMemory(
|
219 |
+
# llm=llm,
|
220 |
+
# output_key="answer",
|
221 |
+
# memory_key="chat_history",
|
222 |
+
# return_messages=True
|
223 |
+
# )
|
224 |
+
# chain = ConversationalRetrievalChain.from_llm(
|
225 |
+
# llm=llm,
|
226 |
+
# retriever=retriever,
|
227 |
+
# chain_type="stuff",
|
228 |
+
# memory=memory,
|
229 |
+
# verbose=True,
|
230 |
+
# return_source_documents=True
|
231 |
+
# )
|
232 |
+
# return chain
|
233 |
+
|
234 |
+
# # Updated Streamlit setup with language selection dropdown
|
235 |
+
# st.set_page_config(page_title="Soil.Ai", page_icon="🌱", layout="centered")
|
236 |
+
# st.title("🌱 Soil.Ai - Smart Farming Recommendations")
|
237 |
+
# st.subheader("AI-driven solutions for modern farming!")
|
238 |
+
|
239 |
+
# # Initialize session state
|
240 |
+
# if "username" not in st.session_state:
|
241 |
+
# username = st.text_input("Enter your name to proceed:")
|
242 |
+
# if username:
|
243 |
+
# with st.spinner("Loading AI interface..."):
|
244 |
+
# st.session_state.username = username
|
245 |
+
# st.session_state.vectorstore = setup_vectorstore()
|
246 |
+
# st.session_state.conversational_chain = chat_chain(st.session_state.vectorstore)
|
247 |
+
# st.session_state.selected_language = "English" # Default language
|
248 |
+
# st.success(f"Welcome, {username}! Start by choosing an option.")
|
249 |
+
# else:
|
250 |
+
# username = st.session_state.username
|
251 |
+
|
252 |
+
# # Language options
|
253 |
+
# languages = [
|
254 |
+
# "English", "Marathi", "Hindi", "Bengali", "Gujarati", "Kannada", "Malayalam",
|
255 |
+
# "Odia", "Punjabi", "Tamil", "Telugu", "Urdu", "Spanish", "French", "German"
|
256 |
+
# ]
|
257 |
+
|
258 |
+
# # Main interface
|
259 |
+
# if "conversational_chain" not in st.session_state:
|
260 |
+
# st.session_state.vectorstore = setup_vectorstore()
|
261 |
+
# st.session_state.conversational_chain = chat_chain(st.session_state.vectorstore)
|
262 |
+
|
263 |
+
# if "username" in st.session_state:
|
264 |
+
# st.subheader(f"Hello {username}, choose your option below:")
|
265 |
+
|
266 |
+
# # Dropdown for selecting output language
|
267 |
+
# st.session_state.selected_language = st.selectbox(
|
268 |
+
# "Select output language:",
|
269 |
+
# languages,
|
270 |
+
# index=languages.index(st.session_state.get("selected_language", "English"))
|
271 |
+
# )
|
272 |
+
|
273 |
+
# # Option selection
|
274 |
+
# option = st.radio(
|
275 |
+
# "Choose an action:",
|
276 |
+
# ("Ask a general agriculture-related question", "Input sensor data for recommendations", "Satellite Data", "FAQ Section")
|
277 |
+
# )
|
278 |
+
|
279 |
+
# # Option 1: Ask AI any agriculture-related question
|
280 |
+
# if option == "Ask a general agriculture-related question":
|
281 |
+
# user_query = st.chat_input("Ask AI anything about agriculture...")
|
282 |
+
# if user_query:
|
283 |
+
# with st.spinner("Processing your query..."):
|
284 |
+
# # Display user's query
|
285 |
+
# with st.chat_message("user"):
|
286 |
+
# st.markdown(user_query)
|
287 |
+
|
288 |
+
# # Get assistant's response
|
289 |
+
# with st.chat_message("assistant"):
|
290 |
+
# response = st.session_state.conversational_chain({"question": user_query})
|
291 |
+
# assistant_response = response["answer"]
|
292 |
+
|
293 |
+
# # Translate response based on selected language
|
294 |
+
# translator = GoogleTranslator(source="en", target=st.session_state.selected_language.lower())
|
295 |
+
# translated_response = translator.translate(assistant_response)
|
296 |
+
|
297 |
+
# # Display response in selected language
|
298 |
+
# st.markdown(f"**{st.session_state.selected_language}:** {translated_response}")
|
299 |
+
|
300 |
+
# # Option 2: Input sensor data for recommendations
|
301 |
+
# elif option == "Input sensor data for recommendations":
|
302 |
+
# st.markdown("### Enter soil and environmental parameters:")
|
303 |
+
# ph = st.number_input("Enter Soil pH", min_value=0.0, max_value=14.0, step=0.1)
|
304 |
+
# moisture = st.number_input("Enter Soil Moisture (%)", min_value=0.0, max_value=100.0, step=0.1)
|
305 |
+
# temperature = st.number_input("Enter Temperature (°C)", min_value=-50.0, max_value=60.0, step=0.1)
|
306 |
+
# air_quality = st.number_input("Enter Air Quality Index (AQI)", min_value=0, max_value=500, step=1)
|
307 |
+
|
308 |
+
# if st.button("Get Recommendations"):
|
309 |
+
# if ph and moisture and temperature and air_quality:
|
310 |
+
# with st.spinner("Analyzing data..."):
|
311 |
+
# # Prepare input query
|
312 |
+
# user_input = f"Recommendations for:\n- pH: {ph}\n- Moisture: {moisture}%\n- Temperature: {temperature}°C\n- Air Quality: {air_quality}"
|
313 |
+
|
314 |
+
# # Display user's input
|
315 |
+
# with st.chat_message("user"):
|
316 |
+
# st.markdown(user_input)
|
317 |
+
|
318 |
+
# # Get assistant's response
|
319 |
+
# with st.chat_message("assistant"):
|
320 |
+
# response = st.session_state.conversational_chain({"question": user_input})
|
321 |
+
# assistant_response = response["answer"]
|
322 |
+
|
323 |
+
# # Translate response based on selected language
|
324 |
+
# translator = GoogleTranslator(source="en", target=st.session_state.selected_language.lower())
|
325 |
+
# translated_response = translator.translate(assistant_response)
|
326 |
+
|
327 |
+
# # Display response in selected language
|
328 |
+
# st.markdown(f"**{st.session_state.selected_language}:** {translated_response}")
|
329 |
+
# else:
|
330 |
+
# st.error("Please fill in all the fields!")
|
331 |
+
|
332 |
+
# # Option 3: Satellite Data
|
333 |
+
# elif option == "Satellite Data":
|
334 |
+
# st.markdown("### Satellite Data Functionality Coming Soon!")
|
335 |
+
|
336 |
+
# # Option 4: FAQ Section
|
337 |
+
# elif option == "FAQ Section":
|
338 |
+
# crop = st.radio("Select a crop for FAQs:", ("Cotton", "Tur"))
|
339 |
+
# if crop == "Tur":
|
340 |
+
# st.markdown("### *Q&A on Arhar Crop*")
|
341 |
+
# tur_questions = [
|
342 |
+
# "Q1: What are the suitable climate and soil requirements for Arhar cultivation?",
|
343 |
+
# "Q2: What is the best time for sowing Arhar, and how much seed is needed per hectare?",
|
344 |
+
# "Q3: What are the improved varieties of Arhar and their characteristics?",
|
345 |
+
# "Q4: What fertilizers and irrigation are required for Arhar cultivation?",
|
346 |
+
# "Q5: What are the main pests and diseases affecting Arhar, and how can they be managed?"
|
347 |
+
# ]
|
348 |
+
# tur_answers = [
|
349 |
+
# "A: Arhar requires a warm and dry climate with a temperature range of 25-30°C. It thrives in well-drained loamy soil with a pH value of 6.0 to 7.5.",
|
350 |
+
# "A: The best time for sowing Arhar is from June to July (monsoon season). The seed requirement is 15-20 kg per hectare. The seeds should be treated with Trichoderma or Carbendazim before sowing.",
|
351 |
+
# "A: Some improved varieties of Arhar include ICPL-87 (early maturing), Sharad (high-yielding), and Pant Arhar-3 (short-duration).",
|
352 |
+
# "A: Fertilizers: Nitrogen: 20 kg/hectare, Phosphorus: 50 kg/hectare. Irrigation: Two to three irrigations during flowering and pod formation stages.",
|
353 |
+
# "A: Pests like pod borers and diseases like wilt (root rot) affect Arhar. Control measures include spraying neem oil and using disease-resistant varieties."
|
354 |
+
# ]
|
355 |
+
# elif crop == "Cotton":
|
356 |
+
# st.markdown("### *Q&A on Cotton Crop*")
|
357 |
+
# tur_questions = [
|
358 |
+
# "Q1: What is the suitable climate for cotton cultivation?",
|
359 |
+
# "Q2: How much water does cotton require during its growth?",
|
360 |
+
# "Q3: What are the common pests and diseases in cotton?",
|
361 |
+
# "Q4: Which fertilizers are best for cotton farming?",
|
362 |
+
# "Q5: What is the average yield of cotton per hectare?"
|
363 |
+
# ]
|
364 |
+
# tur_answers = [
|
365 |
+
# "A: Cotton grows well in warm climates with temperatures between 21-30°C.",
|
366 |
+
# "A: Cotton requires about 700-1300 mm of water depending on the variety and climate.",
|
367 |
+
# "A: Common pests include bollworms; diseases include leaf curl virus.",
|
368 |
+
# "A: Use nitrogen (60 kg/ha), phosphorus (30 kg/ha), and potassium (30 kg/ha).",
|
369 |
+
# "A: Average yield ranges between 500-800 kg/ha depending on the variety and conditions."
|
370 |
+
# ]
|
371 |
+
|
372 |
+
# for q, a in zip(tur_questions, tur_answers):
|
373 |
+
# translator = GoogleTranslator(source="en", target=st.session_state.selected_language.lower())
|
374 |
+
# st.markdown(f"**{translator.translate(q)}**\n\n{translator.translate(a)}")
|