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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import streamlit as st
|
| 2 |
+
import tensorflow as tf
|
| 3 |
+
import numpy as np
|
| 4 |
+
from PIL import Image
|
| 5 |
+
import pandas as pd
|
| 6 |
+
import matplotlib.pyplot as plt
|
| 7 |
+
import plotly.express as px
|
| 8 |
+
|
| 9 |
+
# Configure page
|
| 10 |
+
st.set_page_config(
|
| 11 |
+
page_title="ML Model Demo",
|
| 12 |
+
page_icon="π€",
|
| 13 |
+
layout="wide"
|
| 14 |
+
)
|
| 15 |
+
|
| 16 |
+
@st.cache_resource
|
| 17 |
+
def load_model():
|
| 18 |
+
"""Load your model (cached to avoid reloading)"""
|
| 19 |
+
try:
|
| 20 |
+
# Replace this with your actual model loading
|
| 21 |
+
# Example: model = tf.keras.models.load_model('path/to/your/model.h5')
|
| 22 |
+
|
| 23 |
+
# For demonstration, we'll create a simple model
|
| 24 |
+
model = tf.keras.Sequential([
|
| 25 |
+
tf.keras.layers.Dense(64, activation='relu', input_shape=(4,)),
|
| 26 |
+
tf.keras.layers.Dense(32, activation='relu'),
|
| 27 |
+
tf.keras.layers.Dense(3, activation='softmax')
|
| 28 |
+
])
|
| 29 |
+
|
| 30 |
+
st.success("β
Model loaded successfully!")
|
| 31 |
+
return model
|
| 32 |
+
|
| 33 |
+
except Exception as e:
|
| 34 |
+
st.error(f"β Error loading model: {str(e)}")
|
| 35 |
+
return None
|
| 36 |
+
|
| 37 |
+
def preprocess_image(image):
|
| 38 |
+
"""Preprocess image for model input"""
|
| 39 |
+
# Resize image to expected dimensions
|
| 40 |
+
image = image.resize((224, 224))
|
| 41 |
+
# Convert to array and normalize
|
| 42 |
+
image_array = np.array(image) / 255.0
|
| 43 |
+
# Add batch dimension
|
| 44 |
+
return np.expand_dims(image_array, axis=0)
|
| 45 |
+
|
| 46 |
+
def make_prediction(model, input_data, input_type):
|
| 47 |
+
"""Make prediction with the model"""
|
| 48 |
+
if model is None:
|
| 49 |
+
return "β Model not available"
|
| 50 |
+
|
| 51 |
+
try:
|
| 52 |
+
if input_type == "image":
|
| 53 |
+
# Process image prediction
|
| 54 |
+
processed_input = preprocess_image(input_data)
|
| 55 |
+
# Mock prediction for demo
|
| 56 |
+
prediction = np.random.rand(1, 3)
|
| 57 |
+
classes = ['Class A', 'Class B', 'Class C']
|
| 58 |
+
predicted_class = classes[np.argmax(prediction)]
|
| 59 |
+
confidence = np.max(prediction) * 100
|
| 60 |
+
|
| 61 |
+
return {
|
| 62 |
+
'predicted_class': predicted_class,
|
| 63 |
+
'confidence': confidence,
|
| 64 |
+
'all_predictions': dict(zip(classes, prediction[0]))
|
| 65 |
+
}
|
| 66 |
+
|
| 67 |
+
elif input_type == "numeric":
|
| 68 |
+
# Process numeric prediction
|
| 69 |
+
prediction = model.predict(input_data.reshape(1, -1))
|
| 70 |
+
predicted_class = f"Class {np.argmax(prediction[0])}"
|
| 71 |
+
confidence = np.max(prediction[0]) * 100
|
| 72 |
+
|
| 73 |
+
return {
|
| 74 |
+
'predicted_class': predicted_class,
|
| 75 |
+
'confidence': confidence,
|
| 76 |
+
'raw_output': prediction[0].tolist()
|
| 77 |
+
}
|
| 78 |
+
|
| 79 |
+
elif input_type == "text":
|
| 80 |
+
# Mock text processing
|
| 81 |
+
return {
|
| 82 |
+
'sentiment': 'Positive',
|
| 83 |
+
'confidence': 85.6,
|
| 84 |
+
'keywords': ['example', 'text', 'analysis']
|
| 85 |
+
}
|
| 86 |
+
|
| 87 |
+
except Exception as e:
|
| 88 |
+
return f"β Prediction error: {str(e)}"
|
| 89 |
+
|
| 90 |
+
def main():
|
| 91 |
+
# Header
|
| 92 |
+
st.title("π€ Machine Learning Model Demo")
|
| 93 |
+
st.markdown("---")
|
| 94 |
+
|
| 95 |
+
# Sidebar
|
| 96 |
+
st.sidebar.header("ποΈ Model Controls")
|
| 97 |
+
|
| 98 |
+
# Load model
|
| 99 |
+
with st.spinner("Loading model..."):
|
| 100 |
+
model = load_model()
|
| 101 |
+
|
| 102 |
+
# Model selection
|
| 103 |
+
model_type = st.sidebar.selectbox(
|
| 104 |
+
"Select Model Type:",
|
| 105 |
+
["Image Classification", "Numeric Prediction", "Text Analysis"]
|
| 106 |
+
)
|
| 107 |
+
|
| 108 |
+
# Main content area
|
| 109 |
+
col1, col2 = st.columns([2, 1])
|
| 110 |
+
|
| 111 |
+
with col1:
|
| 112 |
+
if model_type == "Image Classification":
|
| 113 |
+
st.subheader("πΈ Image Classification")
|
| 114 |
+
|
| 115 |
+
uploaded_file = st.file_uploader(
|
| 116 |
+
"Upload an image:",
|
| 117 |
+
type=['jpg', 'jpeg', 'png', 'bmp'],
|
| 118 |
+
help="Supported formats: JPG, JPEG, PNG, BMP"
|
| 119 |
+
)
|
| 120 |
+
|
| 121 |
+
if uploaded_file is not None:
|
| 122 |
+
# Display uploaded image
|
| 123 |
+
image = Image.open(uploaded_file)
|
| 124 |
+
st.image(image, caption="Uploaded Image", use_column_width=True)
|
| 125 |
+
|
| 126 |
+
# Prediction button
|
| 127 |
+
if st.button("π Classify Image", type="primary"):
|
| 128 |
+
with st.spinner("Analyzing image..."):
|
| 129 |
+
result = make_prediction(model, image, "image")
|
| 130 |
+
|
| 131 |
+
if isinstance(result, dict):
|
| 132 |
+
st.success(f"**Prediction:** {result['predicted_class']}")
|
| 133 |
+
st.info(f"**Confidence:** {result['confidence']:.1f}%")
|
| 134 |
+
|
| 135 |
+
# Show all predictions
|
| 136 |
+
st.subheader("All Predictions:")
|
| 137 |
+
for class_name, prob in result['all_predictions'].items():
|
| 138 |
+
st.write(f"β’ {class_name}: {prob*100:.1f}%")
|
| 139 |
+
else:
|
| 140 |
+
st.error(result)
|
| 141 |
+
|
| 142 |
+
elif model_type == "Numeric Prediction":
|
| 143 |
+
st.subheader("π’ Numeric Prediction")
|
| 144 |
+
|
| 145 |
+
# Input parameters
|
| 146 |
+
col_a, col_b = st.columns(2)
|
| 147 |
+
|
| 148 |
+
with col_a:
|
| 149 |
+
param1 = st.number_input("Parameter 1:", value=5.0, step=0.1)
|
| 150 |
+
param2 = st.number_input("Parameter 2:", value=3.2, step=0.1)
|
| 151 |
+
|
| 152 |
+
with col_b:
|
| 153 |
+
param3 = st.number_input("Parameter 3:", value=1.4, step=0.1)
|
| 154 |
+
param4 = st.number_input("Parameter 4:", value=0.2, step=0.1)
|
| 155 |
+
|
| 156 |
+
# Create input array
|
| 157 |
+
input_array = np.array([param1, param2, param3, param4])
|
| 158 |
+
|
| 159 |
+
if st.button("π Make Prediction", type="primary"):
|
| 160 |
+
with st.spinner("Computing prediction..."):
|
| 161 |
+
result = make_prediction(model, input_array, "numeric")
|
| 162 |
+
|
| 163 |
+
if isinstance(result, dict):
|
| 164 |
+
st.success(f"**Prediction:** {result['predicted_class']}")
|
| 165 |
+
st.info(f"**Confidence:** {result['confidence']:.1f}%")
|
| 166 |
+
|
| 167 |
+
# Visualization
|
| 168 |
+
fig, ax = plt.subplots()
|
| 169 |
+
ax.bar(range(len(result['raw_output'])), result['raw_output'])
|
| 170 |
+
ax.set_xlabel('Class')
|
| 171 |
+
ax.set_ylabel('Probability')
|
| 172 |
+
ax.set_title('Prediction Probabilities')
|
| 173 |
+
st.pyplot(fig)
|
| 174 |
+
else:
|
| 175 |
+
st.error(result)
|
| 176 |
+
|
| 177 |
+
elif model_type == "Text Analysis":
|
| 178 |
+
st.subheader("π Text Analysis")
|
| 179 |
+
|
| 180 |
+
text_input = st.text_area(
|
| 181 |
+
"Enter your text:",
|
| 182 |
+
placeholder="Type your text here for analysis...",
|
| 183 |
+
height=150
|
| 184 |
+
)
|
| 185 |
+
|
| 186 |
+
if st.button("π Analyze Text", type="primary") and text_input.strip():
|
| 187 |
+
with st.spinner("Analyzing text..."):
|
| 188 |
+
result = make_prediction(model, text_input, "text")
|
| 189 |
+
|
| 190 |
+
if isinstance(result, dict):
|
| 191 |
+
st.success(f"**Sentiment:** {result['sentiment']}")
|
| 192 |
+
st.info(f"**Confidence:** {result['confidence']:.1f}%")
|
| 193 |
+
|
| 194 |
+
st.subheader("Keywords:")
|
| 195 |
+
for keyword in result['keywords']:
|
| 196 |
+
st.write(f"β’ {keyword}")
|
| 197 |
+
else:
|
| 198 |
+
st.error(result)
|
| 199 |
+
|
| 200 |
+
with col2:
|
| 201 |
+
st.subheader("π Model Info")
|
| 202 |
+
|
| 203 |
+
# Model statistics (mock data)
|
| 204 |
+
metrics = {
|
| 205 |
+
'Accuracy': 94.2,
|
| 206 |
+
'Precision': 91.8,
|
| 207 |
+
'Recall': 93.5,
|
| 208 |
+
'F1-Score': 92.6
|
| 209 |
+
}
|
| 210 |
+
|
| 211 |
+
for metric, value in metrics.items():
|
| 212 |
+
st.metric(metric, f"{value}%")
|
| 213 |
+
|
| 214 |
+
# Additional info
|
| 215 |
+
st.markdown("---")
|
| 216 |
+
st.subheader("βΉοΈ About")
|
| 217 |
+
st.info("""
|
| 218 |
+
**Model Details:**
|
| 219 |
+
- Framework: TensorFlow 2.13
|
| 220 |
+
- Architecture: Deep Neural Network
|
| 221 |
+
- Training Data: Custom dataset
|
| 222 |
+
- Last Updated: July 2025
|
| 223 |
+
""")
|
| 224 |
+
|
| 225 |
+
# Usage stats (mock)
|
| 226 |
+
st.markdown("---")
|
| 227 |
+
st.subheader("π Usage Stats")
|
| 228 |
+
usage_data = pd.DataFrame({
|
| 229 |
+
'Day': ['Mon', 'Tue', 'Wed', 'Thu', 'Fri'],
|
| 230 |
+
'Predictions': [45, 52, 38, 61, 49]
|
| 231 |
+
})
|
| 232 |
+
|
| 233 |
+
fig = px.bar(usage_data, x='Day', y='Predictions', title='Daily Predictions')
|
| 234 |
+
st.plotly_chart(fig, use_container_width=True)
|
| 235 |
+
|
| 236 |
+
# Footer
|
| 237 |
+
st.markdown("---")
|
| 238 |
+
st.markdown("Built with β€οΈ using Streamlit and TensorFlow")
|
| 239 |
+
|
| 240 |
+
if __name__ == "__main__":
|
| 241 |
+
main()
|