MLDeveloper commited on
Commit
308314b
·
verified ·
1 Parent(s): 1b85d2c

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +42 -65
app.py CHANGED
@@ -1,71 +1,48 @@
1
  import streamlit as st
2
  import pandas as pd
3
- from sklearn.linear_model import LinearRegression
4
- import matplotlib.pyplot as plt
 
5
 
6
  # Page configuration
7
- st.set_page_config(page_title="Crime Rate Predictor", layout="centered")
8
- st.title("🔮 Crime Rate Prediction for Indian States/UTs")
9
-
10
- # CSV path (Hosted online)
11
- csv_path = "https://huggingface.co/spaces/MLDeveloper/crime_rate_predicition/resolve/main/RS_Session_255_AS_116.1%20(2).csv"
12
-
13
- try:
14
- # Load and preprocess data
15
- df = pd.read_csv(csv_path)
16
- data = df[[
17
- 'State/UT',
18
- 'Number of Cases Registered - 2018-19',
19
- 'Number of Cases Registered - 2019-20',
20
- 'Number of Cases Registered - 2020-21',
21
- 'Number of Cases Registered - 2021-22 (up to 31.10.2021)'
22
- ]].copy()
23
- data.columns = ['State/UT', '2018', '2019', '2020', '2021']
24
- for col in ['2018', '2019', '2020', '2021']:
25
- data[col] = pd.to_numeric(data[col], errors='coerce').fillna(0).astype(int)
26
-
27
- # --- User Inputs ---
28
- st.subheader("📝 Enter Details to Predict Future Crime Rates")
29
-
30
- # Dropdown for State selection
31
- state_input = st.selectbox("Select State/UT", sorted(data['State/UT'].unique()))
32
-
33
- # Slider for year selection
34
- year_input = st.slider("Select Starting Year", 2022, 2026, 2022)
35
-
36
- if state_input:
37
- if state_input in data['State/UT'].values:
38
- selected_row = data[data['State/UT'] == state_input].iloc[0]
39
- X_train = pd.DataFrame({'Year': [2018, 2019, 2020, 2021]})
40
- y_train = selected_row[['2018', '2019', '2020', '2021']].values
41
-
42
- # Train model and predict
43
- model = LinearRegression()
44
- model.fit(X_train, y_train)
45
-
46
- future_years = list(range(year_input, 2028))
47
- predictions = model.predict(pd.DataFrame({'Year': future_years}))
48
-
49
- result_df = pd.DataFrame({
50
- 'Year': future_years,
51
- 'Predicted Crime Cases': [max(0, int(pred)) for pred in predictions]
52
- })
53
-
54
- # Show predictions
55
- st.subheader(f"📈 Predicted Crime Rate for {state_input} ({year_input} to 2027)")
56
- st.dataframe(result_df, use_container_width=True)
57
-
58
- # Plot
59
- fig, ax = plt.subplots()
60
- ax.plot(result_df['Year'], result_df['Predicted Crime Cases'], marker='o', linestyle='--', color='orangered')
61
- ax.set_xlabel("Year")
62
- ax.set_ylabel("Predicted Crime Cases")
63
- ax.set_title(f"{state_input} Crime Rate Prediction")
64
- st.pyplot(fig)
65
- else:
66
- st.warning("⚠️ Please enter a valid State/UT name from the dataset.")
67
  else:
68
- st.info("👈 Please enter a State/UT name to begin prediction.")
 
 
 
 
69
 
70
- except FileNotFoundError:
71
- st.error(f"❌ File not found at path: {csv_path}. Please check the path.")
 
 
1
  import streamlit as st
2
  import pandas as pd
3
+ import joblib
4
+ import re
5
+ import string
6
 
7
  # Page configuration
8
+ st.set_page_config(page_title="SMS Spam Detector", layout="centered")
9
+ st.title("📩 SMS Spam Detection App")
10
+ st.markdown("🔍 Enter a message below to check if it's **Spam** or **Not Spam (Ham)**")
11
+
12
+ # --- Load Model and Vectorizer ---
13
+ model = joblib.load("model/spam_model.pkl") # Make sure path is correct
14
+ vectorizer = joblib.load("model/tfidf_vectorizer.pkl") # Adjust as per your folder
15
+
16
+ # --- Text Cleaning Function ---
17
+ def clean_text(text):
18
+ text = text.lower()
19
+ text = re.sub(r"http\S+|www\S+|https\S+", '', text, flags=re.MULTILINE)
20
+ text = re.sub(r'\@w+|\#','', text)
21
+ text = re.sub(r'[^\w\s]', '', text)
22
+ text = re.sub(r'\d+', '', text)
23
+ text = text.translate(str.maketrans('', '', string.punctuation))
24
+ return text.strip()
25
+
26
+ # --- Prediction Function ---
27
+ def predict_spam(message):
28
+ cleaned = clean_text(message)
29
+ vector = vectorizer.transform([cleaned])
30
+ prediction = model.predict(vector)
31
+ return "Spam" if prediction[0] == 1 else "Not Spam"
32
+
33
+ # --- Input Section ---
34
+ user_input = st.text_area("✉️ Enter your SMS message here:")
35
+
36
+ if st.button("Check Message"):
37
+ if user_input.strip() == "":
38
+ st.warning("⚠️ Please enter a valid message.")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
39
  else:
40
+ result = predict_spam(user_input)
41
+ if result == "Spam":
42
+ st.error("🚫 This message is classified as **SPAM**.")
43
+ else:
44
+ st.success("✅ This message is classified as **NOT SPAM (HAM)**.")
45
 
46
+ # Footer
47
+ st.markdown("---")
48
+ st.markdown("🔒 **Note**: This is a demo model and not intended for production use without proper testing.")