File size: 4,881 Bytes
4c57dca
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
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
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("""

<style>

    body {

        background: #BCBBB8;

    }

    .title {

        text-align: center;

        color: mediumseagreen;

    }

    .warning {

        color: red;

        font-weight: bold;

        text-align: center;

    }

    .container {

        background: #edf2f7;

        font-weight: bold;

        padding: 20px;

        border-radius: 15px;

        margin-top: 20px;

    }

    .stButton>button {

        background-color: #007bff;

        color: white;

        font-size: 16px;

        font-weight: bold;

        border: none;

        border-radius: 5px;

        padding: 10px 20px;

    }

    .stTextInput>div>input {

        border-radius: 5px;

        border: 1px solid #007bff;

        padding: 10px;

    }

</style>

""", 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('<h1 class="title">Agricultural AI Assistant 🌾</h1>', 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!")