YAMITEK commited on
Commit
53312be
·
verified ·
1 Parent(s): ea7629f

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +92 -92
app.py CHANGED
@@ -1,92 +1,92 @@
1
- import streamlit as st
2
- import pickle
3
- import numpy as np
4
- import pandas as pd
5
- from sklearn.preprocessing import LabelEncoder
6
- import re
7
-
8
- # Load Data
9
- df = pd.read_csv('Crop_Yield.csv')
10
- cropOptions = list(df['Crop'].unique())
11
- model_path = 'model.pkl'
12
-
13
- css = """
14
- <style>
15
- .stApp {
16
- background-image: url("https://images.pexels.com/photos/265216/pexels-photo-265216.jpeg?auto=compress&cs=tinysrgb&w=1260&h=750&dpr=2");
17
- background-position: center;
18
- background-repeat: no-repeat;
19
- background-attachment: fixed;
20
- margin: 0;
21
- padding: 0;
22
- }
23
- .stForm{
24
- background-color: black;
25
- }
26
- .stButton > button {
27
- background-color: white;
28
- color: black;
29
- }
30
- </style>
31
- """
32
-
33
- # Inject custom CSS
34
- st.markdown(css, unsafe_allow_html=True)
35
-
36
- # Load Model
37
- with open(model_path, 'rb') as file:
38
- model = pickle.load(file)
39
-
40
- # Initialize Label Encoder and encode columns
41
- label_encoder_crop = LabelEncoder()
42
-
43
- df['Crop_encoded'] = label_encoder_crop.fit_transform(df['Crop'])
44
-
45
- # Create mappings for Area and Item
46
- crop_mapping = dict(zip(label_encoder_crop.classes_, range(len(label_encoder_crop.classes_))))
47
-
48
- # Create Form
49
- with st.form(key="my_form"):
50
- st.markdown("<h1 style='text-align: center; background-color: #f4edcd;color:black'>Crop Yield Prediction</h1>", unsafe_allow_html=True)
51
-
52
- crop = st.selectbox("Choose a Crop:", options=cropOptions)
53
- area = st.text_input("Area (in hectares):")
54
- area_error = "" if re.match(r"^\d+(\.\d+)?$", area) or not area else "Invalid input for area. Enter a numeric value without commas or special characters."
55
- if area_error:
56
- st.markdown(f"<span style='color:red;'>{area_error}</span>", unsafe_allow_html=True)
57
-
58
- production = st.text_input("Production (in metric tons):")
59
- production_error = "" if re.match(r"^\d+(\.\d+)?$", production) or not production else "Invalid input for production. Enter a numeric value without commas or special characters."
60
- if production_error:
61
- st.markdown(f"<span style='color:red;'>{production_error}</span>", unsafe_allow_html=True)
62
-
63
- rainfall = st.slider("Annual Rainfall (in mm)", min(df['Annual_Rainfall']), max(df['Annual_Rainfall']), value=min(df['Annual_Rainfall']))
64
- fertilizer = st.slider("Fertilizer (in kilograms).", min(df['Fertilizer']), max(df['Fertilizer']), value=min(df['Fertilizer']))
65
- pesticide = st.slider("Pesticide (in kilograms).", min(df['Pesticide']), max(df['Pesticide']), value=min(df['Pesticide']))
66
-
67
- submit_button = st.form_submit_button(label="Predict")
68
-
69
- # Handle Form Submission
70
- if submit_button:
71
- # Validate Inputs
72
- if area_error or production_error:
73
- st.error("Please fix the errors above before proceeding.")
74
- else:
75
- # Prepare Input Data
76
- encoded_crop = crop_mapping[crop]
77
-
78
- input_data = np.array([[pesticide, fertilizer, rainfall,float(production), float(area), encoded_crop]])
79
-
80
- # Predict
81
- try:
82
- prediction = model.predict(input_data)
83
- st.markdown(
84
- f"""
85
- <div style="color: black; font-size: 18px; border: 1px solid darkgreen; border-radius: 5px; padding: 10px; background-color: #e6ffe6;">
86
- <strong>Expected Yield is (production per unit area):</strong> {prediction[0]}
87
- </div>
88
- """,
89
- unsafe_allow_html=True
90
- )
91
- except Exception as e:
92
- st.error(f"Error in prediction: {e}")
 
1
+ import streamlit as st
2
+ import pickle
3
+ import numpy as np
4
+ import pandas as pd
5
+ from sklearn.preprocessing import LabelEncoder
6
+ import re
7
+
8
+ # Load Data
9
+ df = pd.read_csv('Crop_Yield.csv')
10
+ cropOptions = list(df['Crop'].unique())
11
+ model_path = 'model.pkl'
12
+
13
+ css = """
14
+ <style>
15
+ .stApp {
16
+ background-image: url("https://images.pexels.com/photos/265216/pexels-photo-265216.jpeg?auto=compress&cs=tinysrgb&w=1260&h=750&dpr=2");
17
+ background-position: center;
18
+ background-repeat: no-repeat;
19
+ background-attachment: fixed;
20
+ margin: 0;
21
+ padding: 0;
22
+ }
23
+ .stForm{
24
+ background-color: black;
25
+ }
26
+ .stButton > button {
27
+ background-color: white;
28
+ color: black;
29
+ }
30
+ </style>
31
+ """
32
+
33
+ # Inject custom CSS
34
+ st.markdown(css, unsafe_allow_html=True)
35
+
36
+ # Load Model
37
+ with open(model_path, 'rb') as file:
38
+ model = pickle.load(file)
39
+
40
+ # Initialize Label Encoder and encode columns
41
+ label_encoder_crop = LabelEncoder()
42
+
43
+ df['Crop_encoded'] = label_encoder_crop.fit_transform(df['Crop'])
44
+
45
+ # Create mappings for Area and Item
46
+ crop_mapping = dict(zip(label_encoder_crop.classes_, range(len(label_encoder_crop.classes_))))
47
+
48
+ # Create Form
49
+ with st.form(key="my_form"):
50
+ st.markdown("<h1 style='text-align: center; background-color: #f4edcd;color:black'>Crop Yield Prediction</h1>", unsafe_allow_html=True)
51
+
52
+ crop = st.selectbox("Choose a Crop:", options=cropOptions)
53
+ area = st.text_input("Area (in hectares):")
54
+ area_error = "" if re.match(r"^\d+(\.\d+)?$", area) or not area else "Invalid input for area. Enter a numeric value without commas or special characters."
55
+ if area_error:
56
+ st.markdown(f"<span style='color:red;'>{area_error}</span>", unsafe_allow_html=True)
57
+
58
+ production = st.text_input("Production (in metric tons):")
59
+ production_error = "" if re.match(r"^\d+(\.\d+)?$", production) or not production else "Invalid input for production. Enter a numeric value without commas or special characters."
60
+ if production_error:
61
+ st.markdown(f"<span style='color:red;'>{production_error}</span>", unsafe_allow_html=True)
62
+
63
+ rainfall = st.slider("Annual Rainfall (in mm)", min(df['Annual_Rainfall']), max(df['Annual_Rainfall']), value=min(df['Annual_Rainfall']))
64
+ fertilizer = st.slider("Fertilizer (in kilograms).", min(df['Fertilizer']), max(df['Fertilizer']), value=min(df['Fertilizer']))
65
+ pesticide = st.slider("Pesticide (in kilograms).", min(df['Pesticide']), max(df['Pesticide']), value=min(df['Pesticide']))
66
+
67
+ submit_button = st.form_submit_button(label="Predict")
68
+
69
+ # Handle Form Submission
70
+ if submit_button:
71
+ # Validate Inputs
72
+ if area_error or production_error:
73
+ st.error("Please fix the errors above before proceeding.")
74
+ else:
75
+ # Prepare Input Data
76
+ encoded_crop = crop_mapping[crop]
77
+
78
+ input_data = np.array([[pesticide, fertilizer, rainfall,float(production), float(area), encoded_crop]])
79
+
80
+ # Predict
81
+ try:
82
+ prediction = model.predict(input_data)
83
+ st.markdown(
84
+ f"""
85
+ <div style="color: black; font-size: 18px; border: 1px solid darkgreen; border-radius: 5px; padding: 10px; background-color: #e6ffe6;">
86
+ <strong>Expected Yield is (production per unit area):</strong> {prediction[0]}
87
+ </div>
88
+ """,
89
+ unsafe_allow_html=True
90
+ )
91
+ except Exception as e:
92
+ st.error(f"Error in prediction: {e}")