Skip to content

Commit

Permalink
Merge pull request #529 from Kritika75/new-feature-branch
Browse files Browse the repository at this point in the history
Implement Additional Finance Features in Finance Assistant
  • Loading branch information
suryanshsk authored Nov 3, 2024
2 parents a69c52e + be2c25b commit ed55028
Show file tree
Hide file tree
Showing 4 changed files with 96 additions and 19 deletions.
93 changes: 86 additions & 7 deletions Personal Finance Tracker/finance_tracker.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,9 @@
import speech_recognition as sr
import json
import os
import csv
import matplotlib.pyplot as plt
from datetime import datetime

# Class to encapsulate finance data and operations
class FinanceAssistant:
Expand All @@ -11,6 +14,7 @@ class FinanceAssistant:
def __init__(self):
self.expenses = {}
self.budgets = {}
self.recurring_expenses = {}
self.engine = pyttsx3.init()
self.engine.setProperty('rate', 150)
self.load_data()
Expand All @@ -23,14 +27,15 @@ def load_data(self):
data = json.load(f)
self.expenses = data.get("expenses", {})
self.budgets = data.get("budgets", {})
self.recurring_expenses = data.get("recurring_expenses", {})
except (json.JSONDecodeError, IOError):
print("Warning: Data file is corrupted or unreadable. Starting with fresh data.")

def save_data(self):
"""Saves the current state of expenses and budgets to the JSON file."""
"""Saves the current state of expenses, budgets, and recurring expenses to the JSON file."""
try:
with open(self.DATA_FILE, 'w') as f:
json.dump({"expenses": self.expenses, "budgets": self.budgets}, f)
json.dump({"expenses": self.expenses, "budgets": self.budgets, "recurring_expenses": self.recurring_expenses}, f)
except IOError:
print("Warning: Could not save data to file.")

Expand Down Expand Up @@ -60,9 +65,10 @@ async def recognize_speech(self):
print(f"Error in speech recognition: {e}")
return None

async def log_expense(self, category, amount):
async def log_expense(self, category, amount, date=None):
"""Logs an expense under a specific category."""
self.expenses.setdefault(category, []).append(amount)
date = date or datetime.now().strftime("%Y-%m-%d")
self.expenses.setdefault(category, []).append({"amount": amount, "date": date})
self.save_data()
await self.speak_async(f"Logged {amount} dollars for {category}.")

Expand All @@ -73,18 +79,73 @@ async def set_budget(self, category, amount):
await self.speak_async(f"Set {category} budget to {amount} dollars.")

async def check_budget(self):
"""Checks remaining budgets against expenses."""
"""Checks remaining budgets against expenses and provides alerts if limits are exceeded."""
for category, budget in self.budgets.items():
total_expense = sum(self.expenses.get(category, []))
total_expense = sum(expense["amount"] for expense in self.expenses.get(category, []))
remaining = budget - total_expense
if remaining < 0:
await self.speak_async(f"You have exceeded your budget for {category} by {-remaining} dollars.")
elif remaining < budget * 0.1:
await self.speak_async(f"Warning: You are approaching your budget limit for {category}.")
else:
await self.speak_async(f"You have {remaining} dollars left in your budget for {category}.")

async def manage_recurring_expenses(self, category, amount):
"""Logs and manages recurring expenses for subscriptions."""
self.recurring_expenses[category] = amount
self.save_data()
await self.speak_async(f"Recurring expense of {amount} dollars added for {category}.")

def generate_expense_summary(self):
"""Generates a report summarizing expenses by category."""
summary = {category: sum(expense["amount"] for expense in expenses) for category, expenses in self.expenses.items()}
for category, total in summary.items():
print(f"{category}: ${total:.2f}")
return summary

async def generate_monthly_report(self):
"""Generates a monthly report comparing expenses and budgets."""
monthly_summary = self.generate_expense_summary()
for category, total_expense in monthly_summary.items():
budget = self.budgets.get(category, 0)
await self.speak_async(f"For {category}, you spent {total_expense} out of {budget} dollars.")

def export_data_to_csv(self):
"""Exports the expense summary to a CSV file."""
with open("expense_summary.csv", "w", newline='') as file:
writer = csv.writer(file)
writer.writerow(["Category", "Date", "Amount"])
for category, expenses in self.expenses.items():
for expense in expenses:
writer.writerow([category, expense["date"], expense["amount"]])

def generate_charts(self):
"""Generates charts to visualize spending by category."""
summary = self.generate_expense_summary()
categories = list(summary.keys())
expenses = list(summary.values())

plt.figure(figsize=(8, 6))
plt.pie(expenses, labels=categories, autopct='%1.1f%%', startangle=140)
plt.title("Spending by Category")
plt.show()

def currency_conversion(self, amount, from_currency, to_currency, rate):
"""Converts amount from one currency to another given an exchange rate."""
converted_amount = amount * rate
print(f"{amount} {from_currency} is approximately {converted_amount:.2f} {to_currency}.")
return converted_amount

async def detailed_expense_history(self):
"""Provides detailed history of expenses for each category."""
for category, expenses in self.expenses.items():
await self.speak_async(f"Expenses for {category}:")
for expense in expenses:
await self.speak_async(f"On {expense['date']}, spent {expense['amount']} dollars.")

async def provide_help(self):
"""Provides help instructions to the user."""
await self.speak_async("You can log expenses by saying 'Log expense [category] [amount]', set budgets by saying 'Set budget [category] [amount]', check budgets by saying 'Check budget'. To exit, say 'exit'.")
await self.speak_async("You can log expenses, set budgets, manage recurring expenses, check budgets, view expense history, and generate reports. To exit, say 'exit'.")

async def parse_command(self, command):
"""Parses the user's command and calls appropriate methods."""
Expand All @@ -107,6 +168,24 @@ async def parse_command(self, command):
elif "check budget" in command:
await self.check_budget()

elif "recurring expense" in command:
try:
_, _, category, amount_str = command.split(maxsplit=3)
amount = float(amount_str)
await self.manage_recurring_expenses(category, amount)
except (ValueError, IndexError):
await self.speak_async("Please specify a valid category and amount for the recurring expense.")

elif "generate report" in command:
await self.generate_monthly_report()

elif "export data" in command:
self.export_data_to_csv()
await self.speak_async("Data exported to CSV.")

elif "expense history" in command:
await self.detailed_expense_history()

elif "help" in command:
await self.provide_help()

Expand Down
20 changes: 8 additions & 12 deletions Python Snippets/language_translator.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,3 @@

# json , translate and pyttsx3 libraries
#make sure there are no microphone or hardware issues

import speech_recognition as sr
import pyttsx3
from translate import Translator
Expand All @@ -12,22 +8,22 @@
# Initialize the TTS engine
engine = pyttsx3.init()

#Define a file to save the translaton history
# Define a file to save the translation history
HISTORY_FILE = 'translation_history.json'

#load previous history if it exists
# Load previous history if it exists
def load_translation_history():
if os.path.exists(HISTORY_FILE):
with open(HISTORY_FILE, "r") as f:
return json.load(f)
return []

#save translation history
# Save translation history
def save_translation_history(history):
with open(HISTORY_FILE, 'w') as f:
json.dump(history, f)
#Initialize translation history

# Initialize translation history
translation_history = load_translation_history()

# Function to translate using translate-python
Expand All @@ -45,7 +41,7 @@ def translate_text(text, target_language):
def speak(text):
engine.say(text)
engine.runAndWait()

# Function to capture voice commands and convert speech to text
def voice_to_text():
recognizer = sr.Recognizer()
Expand Down Expand Up @@ -106,15 +102,15 @@ def process_translation_command(command):
print(f"Error: {e}")
else:
speak("Please give a translation command that includes 'Translate'.")

def show_history():
if translation_history:
print("Translation History: ")
for entry in translation_history:
print(f"Source: {entry['source']} | Translations: {entry['translations']} | Detected Language: {entry['source_language']}")
else:
print("No translation history available")

# Main function for the voice assistant
if __name__ == "__main__":
speak("Hello! I'm your translation assistant. How can I help you?")
Expand Down
1 change: 1 addition & 0 deletions pomodoro_history.json
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
[{"task": "ee", "type": "work", "cycle": 1}]
1 change: 1 addition & 0 deletions user_data.json
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{"Krits": "testingfile"}

0 comments on commit ed55028

Please sign in to comment.