import streamlit as st
import numpy as np
import pickle
from langchain.schema import HumanMessage, SystemMessage, AIMessage
from langchain_groq import ChatGroq
from dotenv import load_dotenv
import os
# Set page configuration
st.set_page_config(
page_title="Agricultural AI Assistant and Crop Recommendation",
layout="wide"
)
# Load environment variables
load_dotenv()
os.environ['GROQ_API_KEY'] = os.getenv("GROQ_API_KEY")
groq_api_key = os.getenv("GROQ_API_KEY")
chat = ChatGroq(groq_api_key=groq_api_key, model_name="llama-3.3-70b-versatile")
# Load the model and scaler
model = pickle.load(open('model.pkl', 'rb'))
ms = pickle.load(open('minmaxscaler.pkl', 'rb'))
# Custom CSS for styling
st.markdown("""
""", unsafe_allow_html=True)
# Initialize session state for chatbot messages
if 'flow_messages' not in st.session_state:
st.session_state['flow_messages'] = [
SystemMessage(content="You are a highly intelligent and friendly agricultural assistant. Provide accurate and relevant answers about crops, farming, and agricultural practices.")
]
# Define the chatbot response function
def get_response(question):
st.session_state['flow_messages'].append(HumanMessage(content=question))
answer = chat(st.session_state['flow_messages'])
st.session_state['flow_messages'].append(AIMessage(content=answer.content))
return answer.content
# App features
st.markdown('
Agricultural AI Assistant 🌾
', unsafe_allow_html=True)
st.sidebar.header("Features")
features = st.sidebar.radio("Choose a feature:", ("Crop Recommendation", "Conversational Q&A"))
if features == "Crop Recommendation":
st.write("""
### Provide the necessary agricultural parameters:
""")
# Input fields for the parameters
N = st.number_input('Nitrogen', min_value=0, max_value=150, step=1)
P = st.number_input('Phosphorus', min_value=0, max_value=100, step=1)
K = st.number_input('Potassium', min_value=0, max_value=100, step=1)
temp = st.number_input('Temperature (°C)', min_value=-10.0, max_value=60.0, step=0.1)
humidity = st.number_input('Humidity (%)', min_value=0.0, max_value=100.0, step=0.1)
ph = st.number_input('pH', min_value=0.0, max_value=14.0, step=0.1)
rainfall = st.number_input('Rainfall (mm)', min_value=0.0, max_value=1000.0, step=1.0)
# Button to trigger prediction
if st.button('Get Recommendation'):
# Feature list and transformation
feature_list = [N, P, K, temp, humidity, ph, rainfall]
single_pred = np.array(feature_list).reshape(1, -1)
# Apply scaling
scaled_features = ms.transform(single_pred)
# Make prediction
prediction = model.predict(scaled_features)
# Dictionary to map predictions to crop names
crop_dict = {
1: "Rice", 2: "Maize", 3: "Jute", 4: "Cotton", 5: "Coconut", 6: "Papaya", 7: "Orange",
8: "Apple", 9: "Muskmelon", 10: "Watermelon", 11: "Grapes", 12: "Mango", 13: "Banana",
14: "Pomegranate", 15: "Lentil", 16: "Blackgram", 17: "Mungbean", 18: "Mothbeans",
19: "Pigeonpeas", 20: "Kidneybeans", 21: "Chickpea", 22: "Coffee"
}
# Display the result
if prediction[0] in crop_dict:
crop = crop_dict[prediction[0]]
result = f"**{crop}** is the best crop to be cultivated with the provided data."
st.success(result)
else:
result = "Sorry, we could not determine the best crop to be cultivated with the provided data."
st.error(result)
elif features == "Conversational Q&A":
st.write("""
### Ask any question about crops, farming, and agriculture:
""")
user_input = st.text_input("Your Question:")
if st.button("Ask Question"):
if user_input.strip():
response = get_response(user_input)
st.subheader("The Response is:")
st.write(response)
else:
st.warning("Please enter a question!")