satya11's picture
Create app.py
b0987e9 verified
import streamlit as st
import numpy as np
import pickle
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler, OneHotEncoder
from sklearn.compose import ColumnTransformer
import os
# Set page config first
st.set_page_config(
page_title="Crop Prediction App",
page_icon="🌾",
layout="centered",
initial_sidebar_state="expanded"
)
# Custom CSS
st.markdown("""
<style>
.title {
color: #2c3e50;
text-align: center;
margin-bottom: 30px;
}
.stButton>button {
background-color: #27ae60;
color: white;
border-radius: 8px;
padding: 10px 20px;
width: 100%;
transition: all 0.3s;
}
.stButton>button:hover {
background-color: #2ecc71;
transform: scale(1.02);
}
.input-section {
background-color: #f8f9fa;
padding: 20px;
border-radius: 10px;
margin-bottom: 20px;
}
.prediction-section {
background-color: #e8f5e9;
padding: 20px;
border-radius: 10px;
margin-top: 20px;
}
.step-card {
background-color: #ffffff;
border-radius: 10px;
padding: 15px;
margin-bottom: 10px;
box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}
</style>
""", unsafe_allow_html=True)
# Load model (with error handling)
@st.cache_resource
def load_model():
try:
with open("lor_f.pkl", "rb") as f:
model = pickle.load(f)
return model
except FileNotFoundError:
st.error("Model file not found. Please ensure 'lor_f.pkl' exists.")
return None
except Exception as e:
st.error(f"Error loading model: {str(e)}")
return None
model = load_model()
# App title
st.markdown("<h1 class='title'>🌾 Smart Crop Prediction</h1>", unsafe_allow_html=True)
# Main app sections
tab1, tab2 = st.tabs(["Prediction", "Project Overview"])
with tab1:
st.subheader("Enter Soil and Weather Conditions")
with st.container():
st.markdown("<div class='input-section'>", unsafe_allow_html=True)
col1, col2 = st.columns(2)
with col1:
nitrogen = st.slider("Nitrogen (N) level", 1, 140, 50,
help="Nitrogen content in soil (1-140 kg/ha)")
phosphorus = st.slider("Phosphorus (P) level", 5, 145, 50,
help="Phosphorus content in soil (5-145 kg/ha)")
potassium = st.slider("Potassium (K) level", 5, 205, 50,
help="Potassium content in soil (5-205 kg/ha)")
ph_value = st.slider("Soil pH Value", 3.0, 9.9, 6.5, 0.1,
help="Soil acidity/alkalinity (3.0-9.9 pH)")
with col2:
temperature = st.slider("Temperature (Β°C)", 8.0, 43.0, 25.0, 0.1,
help="Average temperature (8-43Β°C)")
humidity = st.slider("Humidity (%)", 14, 99, 60,
help="Relative humidity (14-99%)")
rainfall = st.slider("Rainfall (mm)", 20, 298, 100,
help="Annual rainfall (20-298 mm)")
st.markdown("</div>", unsafe_allow_html=True)
if st.button("Predict Optimal Crop", key="predict_btn"):
if model is None:
st.error("Model not available. Please check the model file.")
else:
try:
user_data = np.array([[nitrogen, phosphorus, potassium, temperature,
humidity, ph_value, rainfall]])
prediction = model.predict(user_data)
with st.container():
st.markdown("<div class='prediction-section'>", unsafe_allow_html=True)
st.success(f"### Recommended Crop: **{prediction[0]}**")
# Add some visual feedback
st.write("Based on your inputs, the optimal crop for these conditions is:")
st.markdown(f"<h3 style='text-align: center; color: #27ae60;'>{prediction[0]}</h3>",
unsafe_allow_html=True)
# Add some additional information
st.markdown("""
**Tips for better yield:**
- Maintain proper irrigation
- Monitor soil nutrients regularly
- Follow recommended crop rotation practices
""")
st.markdown("</div>", unsafe_allow_html=True)
except Exception as e:
st.error(f"Prediction error: {str(e)}")
with tab2:
st.header("Machine Learning Project Steps")
st.write("""
This crop prediction system was developed following these key machine learning steps:
""")
steps = {
"1. Problem Definition 🧠": {
"description": "Identify the agricultural challenge and define objectives for crop prediction.",
"actions": [
"Determine key factors affecting crop growth",
"Define success metrics for the model"
]
},
"2. Data Collection πŸ“Š": {
"description": "Gather comprehensive agricultural datasets.",
"actions": [
"Collect soil nutrient data (N, P, K, pH)",
"Gather weather and climate data",
"Obtain historical crop yield information"
]
},
"3. Data Cleaning 🧹": {
"description": "Prepare raw data for analysis by addressing quality issues.",
"actions": [
"Handle missing values and outliers",
"Correct measurement inconsistencies",
"Remove duplicate entries"
]
},
"4. Exploratory Analysis πŸ”": {
"description": "Understand data patterns and relationships.",
"actions": [
"Analyze feature distributions",
"Identify correlations between variables",
"Visualize data patterns"
]
},
"5. Feature Engineering βš™οΈ": {
"description": "Select and transform relevant features.",
"actions": [
"Normalize numerical features",
"Create derived features if needed",
"Select most predictive features"
]
},
"6. Model Selection πŸ€–": {
"description": "Choose appropriate machine learning algorithms.",
"actions": [
"Compare classification algorithms",
"Evaluate based on accuracy and performance",
"Select final model (Logistic Regression)"
]
},
"7. Model Training πŸ‹οΈβ€β™‚οΈ": {
"description": "Train the selected model with prepared data.",
"actions": [
"Split data into training and validation sets",
"Train model with optimal parameters",
"Validate model performance"
]
},
"8. Model Evaluation πŸ“ˆ": {
"description": "Assess model performance rigorously.",
"actions": [
"Calculate precision, recall, and F1-score",
"Analyze confusion matrix",
"Test on unseen data"
]
},
"9. Deployment πŸš€": {
"description": "Implement the model in a production environment.",
"actions": [
"Develop user-friendly interface",
"Create API endpoints if needed",
"Ensure scalability"
]
},
"10. Monitoring πŸ”„": {
"description": "Continuously track and improve the system.",
"actions": [
"Monitor prediction accuracy",
"Update model with new data",
"Address concept drift"
]
}
}
for step, content in steps.items():
with st.expander(step):
st.write(content["description"])
st.markdown("**Key Actions:**")
for action in content["actions"]:
st.markdown(f"- {action}")
st.markdown("---")
st.write("This application helps farmers make data-driven decisions for optimal crop selection.")
# Add footer
st.markdown("---")
st.markdown(
"""
<div style="text-align: center; color: #777; font-size: 0.9em;">
Agricultural Decision Support System β€’ Powered by Machine Learning
</div>
""",
unsafe_allow_html=True
)