Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Binary file not shown.
147 changes: 147 additions & 0 deletions Domains/AI-ML/MiniProjects/email_spam_filter/main.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,147 @@
# Simple Spam Classifier based on Word Frequency (Easy ML/Statistics)
import numpy as np
import csv

# --- 1. DATA LOADING FUNCTION ---

def load_data_from_csv(filename="sample.csv"):
"""
Reads text and label data from a specified CSV file.
Expects two columns: Text (str) and Label (int 0 or 1).
"""
data = []
try:
with open(filename, mode='r', encoding='utf-8') as file:
reader = csv.reader(file)
next(reader) # Skip the header row (e.g., "Text,Label")
for row in reader:
if len(row) == 2:
text = row[0].strip()
# Convert label to integer
try:
label = int(row[1].strip())
data.append((text, label))
except ValueError:
print(f"[Warning] Skipping row with non-integer label: {row}")
except FileNotFoundError:
print(f"[CRITICAL ERROR] The file '{filename}' was not found.")
print("Please ensure the CSV file is in the same directory as the script.")
return []
except Exception as e:
print(f"[ERROR] An error occurred while reading the CSV: {e}")
return []

return data

# --- 2. TRAIN THE CLASSIFIER (Counting) ---

def train_classifier(data):
"""
Counts the frequency of words in spam and ham messages.
"""
spam_word_counts = {}
ham_word_counts = {}
total_spam_messages = 0
total_ham_messages = 0

print("--- Training Model (Counting Words) ---")

for text, label in data:
# Convert text to lowercase and split into words
words = text.lower().split()

if label == 1:
total_spam_messages += 1
counts = spam_word_counts
else:
total_ham_messages += 1
counts = ham_word_counts

for word in words:
# Use a basic dictionary to store word frequency
counts[word] = counts.get(word, 0) + 1

print(f"Total Spam Messages: {total_spam_messages}")
print(f"Total Ham Messages: {total_ham_messages}")
print("[Training Complete]")

return spam_word_counts, ham_word_counts, total_spam_messages, total_ham_messages

# --- 3. PREDICTION LOGIC ---

def predict_spam_score(text, spam_counts, ham_counts, total_spam, total_ham):
"""
Scores a new message based on how many "spam words" it contains.
The score is the ratio of spam-words found.
"""
words = text.lower().split()
spam_score = 0

print(f"\nAnalyzing Text: '{text}'")

for word in words:
# Calculate the simple probability of this word being in spam vs ham

# Count how many times this word appeared in spam and ham training data
spam_hits = spam_counts.get(word, 0)
ham_hits = ham_counts.get(word, 0)

# Simple probability: P(word|Spam)
# Add '1' (Laplace smoothing) to avoid dividing by zero if a word wasn't seen
p_word_given_spam = (spam_hits + 1) / (total_spam + 2)
p_word_given_ham = (ham_hits + 1) / (total_ham + 2)

# Calculate the ratio: How much more likely is this word to be spam?
if p_word_given_spam > p_word_given_ham:
ratio = p_word_given_spam / p_word_given_ham
# Log the ratio to prevent numbers from exploding, and add to the score
spam_score += np.log(ratio)
print(f" - '{word}': Spam Likely (Score added: {np.log(ratio):.2f})")
else:
print(f" - '{word}': Ham Likely")

return spam_score

# --- MAIN EXECUTION ---
if __name__ == "__main__":
try:
# NumPy is needed for the log function, which keeps numbers manageable
import numpy as np

# 1. Load Data from CSV
DATA = load_data_from_csv()

if not DATA:
print("\n[Execution Halted] Cannot proceed without training data.")
else:
# 2. Train the Classifier
s_counts, h_counts, t_spam, t_ham = train_classifier(DATA)

# 3. Set the threshold (a score above this is classified as SPAM)
SPAM_THRESHOLD = 1.0

# 4. Interactive Testing
print("\n--- Interactive Spam Tester ---")
print(f"Prediction Threshold: Score > {SPAM_THRESHOLD} is SPAM")
print("Enter 'quit' to exit.")

while True:
test_text = input("\nEnter email subject/body: ")
if test_text.lower() == 'quit':
break

final_score = predict_spam_score(test_text, s_counts, h_counts, t_spam, t_ham)

print(f"\nFINAL SPAM SCORE: {final_score:.3f}")

if final_score > SPAM_THRESHOLD:
print("CLASSIFICATION: 🚨 SPAM")
else:
print("CLASSIFICATION: ✅ HAM")
print("-" * 30)

except ImportError:
print("\n[CRITICAL ERROR] NumPy is required for this script (for log function).")
print("Please ensure your Python environment has NumPy installed.")
except Exception as e:
print(f"[ERROR] An unexpected error occurred: {e}")
16 changes: 16 additions & 0 deletions Domains/AI-ML/MiniProjects/email_spam_filter/sample.csv
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
Text,Label
Win a free gift card now,1
Meeting scheduled for 2 PM,0
URGENT: Your account verification,1
Please review the project report,0
Claim your guaranteed prize money,1
Lunch plans confirmed tomorrow,0
Special offer, click now,1
Remember to submit your hours,0
Click to renew your subscription immediately,1
Congratulations you've won a $1000 voucher,1
Here is the link to the quarterly budget,0
Earn millions working from home today,1
Your package delivery failed, update address,1
Quick question about your vacation dates,0
Did you send the attachment I asked for,0
42 changes: 42 additions & 0 deletions Domains/Frontend/MiniProjects/expense_tracker/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
**Contributor:** alisha1510

# Expense Tracker

A dynamic web application to help users track their income, expenses, and balance in real-time. Features interactive charts, a clean interface, and a user-friendly way to manage personal finances.

## 🌟 Features

* **Real-Time Tracking** – Add income and expenses instantly, see updates in your balance.
* **Transaction History** – View, sort, and delete past transactions easily.


## 🎯 How to Use

1.Open the web application in a browser.
2.Add a transaction using the Add Transaction form (income or expense).
3.Enter description, amount, and type.
4.Submit to update your balance and charts instantly.
5.View your transaction history below and delete items if needed.


## ⚠️ Important Disclaimer

**For personal finance tracking only!**

This project is intended to help manage budgets and track expenses. Please do not use this app for financial advice or professional accounting purposes.


## 🤝 Contributing

Contributions, issues, and feature requests are welcome! Feel free to check the issues page.

## 👤 Author

**Alisha Sheikh**
- GitHub: [@alisha1510](https://github.com/alisha1510)


---


Made with 💜 for Hacktoberfest and the Open Source Community
100 changes: 100 additions & 0 deletions Domains/Frontend/MiniProjects/expense_tracker/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Dynamic Expense Tracker</title>
<!-- Load Tailwind CSS -->
<script src="https://cdn.tailwindcss.com"></script>
<!-- Link to external CSS file (must be in the same directory) -->
<link rel="stylesheet" href="style.css">
</head>
<body>

<div id="app" class="p-4 md:p-8 lg:p-12 max-w-4xl mx-auto">
<header class="text-center mb-8">
<!-- Dark mode text color -->
<h1 class="text-4xl md:text-5xl font-extrabold text-blue-300 tracking-tight">
BudgetFlow Tracker
</h1>
<!-- Dark mode text color -->
<p class="text-gray-400 mt-2">Manage your money in real-time.</p>
<p class="text-xs mt-1 text-gray-500" id="user-info">Authenticating...</p>
</header>

<!-- Balance Summary Section -->
<section class="grid grid-cols-3 gap-4 mb-8">
<div class="p-4 rounded-xl main-card text-center transition-transform hover:scale-[1.01] duration-300">
<!-- Dark mode text color -->
<h2 class="text-lg font-semibold text-gray-400">Balance</h2>
<p id="balance" class="text-3xl font-bold text-blue-400 mt-1">--</p>
</div>
<div class="p-4 rounded-xl main-card text-center transition-transform hover:scale-[1.01] duration-300">
<!-- Dark mode text color -->
<h2 class="text-lg font-semibold text-gray-400">Income</h2>
<p id="income" class="text-3xl font-bold text-emerald-400 mt-1">--</p>
</div>
<div class="p-4 rounded-xl main-card text-center transition-transform hover:scale-[1.01] duration-300">
<!-- Dark mode text color -->
<h2 class="text-lg font-semibold text-gray-400">Expenses</h2>
<p id="expense" class="text-3xl font-bold text-rose-400 mt-1">--</p>
</div>
</section>

<!-- Add Transaction Form -->
<section class="main-card p-6 rounded-xl mb-8">
<!-- Dark mode text color -->
<h2 class="text-2xl font-bold mb-4 text-blue-300">Add New Transaction</h2>
<form id="transaction-form" class="space-y-4">
<div>
<!-- Dark mode label text color -->
<label for="description" class="block text-sm font-medium text-gray-400 mb-1">Description</label>
<!-- Dark theme input styling -->
<input type="text" id="description" placeholder="E.g., Salary, Coffee, Rent" required
class="w-full p-3 rounded-lg bg-gray-700 border border-gray-600 focus:ring-2 focus:ring-blue-500 focus:border-blue-500 text-white transition duration-200">
</div>
<div class="grid grid-cols-2 gap-4">
<div>
<!-- Dark mode label text color -->
<label for="amount" class="block text-sm font-medium text-gray-400 mb-1">Amount ($)</label>
<!-- Dark theme input styling -->
<input type="number" id="amount" placeholder="50.00" step="0.01" required
class="w-full p-3 rounded-lg bg-gray-700 border border-gray-600 focus:ring-2 focus:ring-blue-500 focus:border-blue-500 text-white transition duration-200">
</div>
<div>
<!-- Dark mode label text color -->
<label for="type" class="block text-sm font-medium text-gray-400 mb-1">Type</label>
<!-- Dark theme select styling -->
<select id="type" required
class="w-full p-3 rounded-lg bg-gray-700 border border-gray-600 focus:ring-2 focus:ring-blue-500 focus:border-blue-500 text-white transition duration-200 appearance-none cursor-pointer">
<option value="income" class="bg-gray-800">Income</option>
<option value="expense" class="bg-gray-800">Expense</option>
</select>
</div>
</div>
<!-- Button colors remain the same for accent -->
<button type="submit" id="submit-btn"
class="animated-btn w-full py-3 mt-4 rounded-lg font-bold text-lg text-white bg-emerald-600 hover:bg-emerald-500 focus:outline-none focus:ring-4 focus:ring-emerald-300/50 transition duration-200 shadow-lg shadow-emerald-600/30">
Add Transaction
</button>
</form>
<!-- Dark mode error text color -->
<p id="error-message" class="text-rose-400 mt-2 text-center hidden"></p>
</section>

<!-- Transaction History Section -->
<section class="main-card p-6 rounded-xl">
<!-- Dark mode text color -->
<h2 class="text-2xl font-bold mb-4 text-blue-300">Transaction History</h2>
<div id="transactions-list" class="space-y-3">
<!-- Transactions will be inserted here by JavaScript -->
<!-- Dark mode loading text color -->
<p id="loading-message" class="text-gray-400 text-center py-4">Loading transactions...</p>
</div>
</section>
</div>

<!-- Link to external JavaScript file (must be in the same directory) -->
<script src="script.js"></script>
</body>
</html>
Loading