yougandar commited on
Commit
427dba7
·
verified ·
1 Parent(s): ebe0177

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +161 -0
app.py ADDED
@@ -0,0 +1,161 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import pandas as pd
3
+ import random
4
+ import joblib
5
+ from sklearn.ensemble import RandomForestClassifier
6
+ from sklearn.preprocessing import StandardScaler
7
+ from sklearn.model_selection import train_test_split
8
+ from sklearn.metrics import classification_report
9
+ import matplotlib.pyplot as plt
10
+ import seaborn as sns
11
+ import numpy as np
12
+ import os
13
+
14
+ # Load cattle data
15
+ DATA_FILE = 'cattle_data.csv'
16
+
17
+ def load_data():
18
+ # Check if the dataset exists
19
+ if os.path.exists(DATA_FILE):
20
+ return pd.read_csv(DATA_FILE)
21
+ else:
22
+ return pd.DataFrame(columns=['TAG ID', 'BREED', 'AGE', 'SURGERY', 'REPRODUCTION CYCLES', 'OTHER'])
23
+
24
+ # Function to generate random sensor data for a specific cow breed
25
+ def generate_sensor_data(cow_breed):
26
+ cow_data = {
27
+ 'Holstein Friesian': {'body_temp': (38.0, 39.0), 'rumination': (600, 800), 'steps': (8000, 12000), 'behavior_score': (6, 8)},
28
+ 'Girolando': {'body_temp': (38.0, 39.0), 'rumination': (650, 750), 'steps': (7000, 10000), 'behavior_score': (7, 9)},
29
+ 'Jersey': {'body_temp': (38.0, 39.0), 'rumination': (650, 750), 'steps': (7500, 10500), 'behavior_score': (6, 8)},
30
+ 'Sahiwal': {'body_temp': (38.0, 39.0), 'rumination': (550, 700), 'steps': (6500, 9000), 'behavior_score': (7, 9)},
31
+ 'Kankrej': {'body_temp': (38.0, 39.0), 'rumination': (600, 750), 'steps': (7000, 10000), 'behavior_score': (7, 9)}
32
+ }
33
+
34
+ data = cow_data.get(cow_breed)
35
+ if not data:
36
+ return None
37
+
38
+ sensor_data = {
39
+ 'Body Temperature (°C)': round(random.uniform(data['body_temp'][0], data['body_temp'][1]), 2),
40
+ 'Rumination (min/day)': random.randint(data['rumination'][0], data['rumination'][1]),
41
+ 'Step Count (steps/day)': random.randint(data['steps'][0], data['steps'][1]),
42
+ 'Behavior Score (1-10)': random.randint(data['behavior_score'][0], data['behavior_score'][1])
43
+ }
44
+ return sensor_data
45
+
46
+ # Load the data and preprocess
47
+ df = load_data()
48
+
49
+ # Feature Engineering - Create features like daily trends or differences if needed
50
+ df['milk_yield_change'] = df['AGE'].diff().fillna(0) # Just an example to create a derived feature
51
+
52
+ # Merge sensor data with cattle profile
53
+ cow_breeds = ['Holstein Friesian', 'Girolando', 'Jersey', 'Sahiwal', 'Kankrej']
54
+ sensor_data_list = []
55
+ for breed in cow_breeds:
56
+ sensor_data = generate_sensor_data(breed)
57
+ if sensor_data:
58
+ sensor_data['TAG ID'] = random.randint(1, 100) # Random TAG ID for simulation
59
+ sensor_data['BREED'] = breed
60
+ sensor_data_list.append(sensor_data)
61
+
62
+ sensor_df = pd.DataFrame(sensor_data_list)
63
+
64
+ # Merge with the original cattle profile dataset
65
+ df = pd.merge(df, sensor_df, on='TAG ID', how='left')
66
+
67
+ # Model Training (Disease Prediction)
68
+ X = df[['Body Temperature (°C)', 'Rumination (min/day)', 'Step Count (steps/day)', 'Behavior Score (1-10)', 'AGE']]
69
+ y = df['OTHER'].apply(lambda x: 1 if x == 'Healthy' else 0) # Convert health status to binary (0 = not healthy, 1 = healthy)
70
+
71
+ # Data Preprocessing
72
+ scaler = StandardScaler()
73
+ X_scaled = scaler.fit_transform(X)
74
+
75
+ # Train Test Split
76
+ X_train, X_test, y_train, y_test = train_test_split(X_scaled, y, test_size=0.3, random_state=42)
77
+
78
+ # Train a Random Forest Classifier
79
+ model = RandomForestClassifier(n_estimators=100, random_state=42)
80
+ model.fit(X_train, y_train)
81
+
82
+ # Save the trained model
83
+ joblib.dump(model, 'disease_prediction_model.pkl')
84
+ joblib.dump(scaler, 'scaler.pkl')
85
+
86
+ # Evaluate the model
87
+ y_pred = model.predict(X_test)
88
+ st.write("Model Evaluation Results")
89
+ st.text(classification_report(y_test, y_pred))
90
+
91
+ # Streamlit App
92
+ st.title('Cattle Profile & Disease Prediction Dashboard')
93
+
94
+ # Register New Cow form
95
+ st.header("➕ Register New Cow")
96
+ tag_id = st.number_input("TAG ID", min_value=1, step=1)
97
+ breed = st.selectbox("Breed", cow_breeds)
98
+ age = st.number_input("Age (in years)", min_value=0, step=1)
99
+ surgery = st.text_input("Surgery")
100
+ reproduction_cycles = st.number_input("Reproduction Cycles", min_value=0, step=1)
101
+ other = st.text_input("Other Health Details")
102
+
103
+ submit = st.button("Register Cow")
104
+ if submit:
105
+ new_cow = pd.DataFrame([{
106
+ 'TAG ID': tag_id,
107
+ 'BREED': breed,
108
+ 'AGE': age,
109
+ 'SURGERY': surgery,
110
+ 'REPRODUCTION CYCLES': reproduction_cycles,
111
+ 'OTHER': other
112
+ }])
113
+ df = pd.concat([df, new_cow], ignore_index=True)
114
+ st.write("Cow registered successfully!")
115
+
116
+ # Select RFID dropdown to view details
117
+ st.header("🔢 Select RFID Tag ID")
118
+ selected_rfid = st.selectbox("Select RFID Tag ID", df['TAG ID'].unique())
119
+
120
+ if selected_rfid:
121
+ cow_info = df[df['TAG ID'] == selected_rfid].iloc[0]
122
+ st.write(f"**TAG ID:** {cow_info['TAG ID']}")
123
+ st.write(f"**BREED:** {cow_info['BREED']}")
124
+ st.write(f"**AGE:** {cow_info['AGE']} years")
125
+ st.write(f"**SURGERY:** {cow_info['SURGERY']}")
126
+ st.write(f"**REPRODUCTION CYCLES:** {cow_info['REPRODUCTION CYCLES']}")
127
+ st.write(f"**OTHER HEALTH DETAILS:** {cow_info['OTHER']}")
128
+
129
+ # Predict disease status based on the selected cow's data
130
+ selected_data = scaler.transform([[
131
+ cow_info['Body Temperature (°C)'],
132
+ cow_info['Rumination (min/day)'],
133
+ cow_info['Step Count (steps/day)'],
134
+ cow_info['Behavior Score (1-10)'],
135
+ cow_info['AGE']
136
+ ]])
137
+ disease_prediction = model.predict(selected_data)
138
+ disease_status = "Healthy" if disease_prediction[0] == 1 else "Not Healthy"
139
+ st.write(f"Predicted Health Status: {disease_status}")
140
+
141
+ # Display cow milk yield trends
142
+ st.header("🐄 Cow Milk Yield Trends")
143
+ milk_data = {
144
+ 'Tag ID': df['TAG ID'],
145
+ 'Date': pd.date_range(start='2025-04-01', periods=len(df), freq='D'),
146
+ 'Milk Yield (L)': np.random.uniform(10, 22, len(df)),
147
+ }
148
+ milk_df = pd.DataFrame(milk_data)
149
+
150
+ # Plot trends
151
+ st.subheader('Milk Yield Trend for Each Cow')
152
+ plt.figure(figsize=(10, 6))
153
+ sns.lineplot(data=milk_df, x='Date', y='Milk Yield (L)', hue='Tag ID', marker='o')
154
+ plt.title('Milk Yield Trend (Day-wise for Each Cow)')
155
+ plt.xlabel('Date')
156
+ plt.ylabel('Milk Yield (L)')
157
+ plt.xticks(rotation=45)
158
+ st.pyplot()
159
+
160
+ # Save updated data back to CSV
161
+ df.to_csv(DATA_FILE, index=False)