Sophia - Personal Assistant

by InventorKrish in Circuits > Computers

18 Views, 0 Favorites, 0 Comments

Sophia - Personal Assistant

Screenshot 2025-04-21 170624.png

Hey, I’m Krish, and I’ve created an AI Personal Assistant designed to help you manage your time better. The AI's name is Sophia, and she's here to keep you on track with real-time information, reminders, and anything you need to stay organized. Whether it's keeping tabs on your schedule or giving you the latest updates, Sophia is always ready to assist. With Sophia, you’ll never miss a beat — she's intuitive, responsive, and built to help you make the most out of your day.

Supplies

Screenshot 2025-05-03 192731.png
Screenshot 2025-05-03 192851.png
Screenshot 2025-05-03 192930.png

There are no physical supplies required for this project, but there are some software requirements to get started. You’ll need VS Code or PyCharm or any Python editor of your choice, along with Python 3.x installed on your system. A basic understanding of Python programming will also be helpful for customizing and setting up the AI. Once you have everything set up, you’re ready to bring your AI to life and make it your own!

Frame

Screenshot 2025-05-03 193919.png
Screenshot 2025-05-03 193957.png

In this first step, I started by using my Python knowledge to lay the foundation for my AI, Sophia. My main goal was to focus on voice-to-voice interaction, where she could actually listen and respond to what I say. To make that happen, I built a simple framework using if and elif statements to handle different voice inputs. This way, Sophia could recognize specific commands and give the right response. It might be basic at first, but this structure is the backbone — once it’s in place, I can keep upgrading her with more features and smarter reactions over time.

Adding Features

Screenshot 2025-04-21 170624.png
Screenshot 2025-05-03 200607.png
Screenshot 2025-05-03 200556.png

In this step, I’m adding all the key features that make my AI assistant, Sophia, feel truly intelligent. I’ve programmed her to tell the current time, date, day, week number, month, and even the year using Python’s datetime module. I also set her up to keep track of my events and reminders, so she can help me stay organized. I integrated the OpenWeatherMap API so she can give me weather updates — super useful when I’m getting ready for the day. For news, I used the NewsAPI so she can share the latest headlines. One of my favorite parts is the personalized greetings — Sophia knows what time it is and greets me accordingly. I use if and elif statements along with voice input to keep the conversation natural and responsive. This is what makes Sophia not just smart, but genuinely interactive.

Source Code for Sophia:


from flask import Flask

import datetime

import json

import os

import random

import requests

import time

import pyjokes

import pyttsx3



# Initialize Flask app

app = Flask(__name__)



# Constants

OPENWEATHER_API_KEY = "8ef61edcf1c576d65d836254e11ea420"

OPENWEATHER_BASE_URL = "https://api.openweathermap.org/data/2.5/weather?"

GEMINI_API_KEY = "AIzaSyDVeGp4Ut0iakTjM4Cn9upjIUMAyqbZEDo"

GEMINI_URL = "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash:generateContent?key=AIzaSyDVeGp4Ut0iakTjM4Cn9upjIUMAyqbZEDo"

TIMES_OF_INDIA_URL = "https://timesofindia.indiatimes.com/briefs"



# Special days (month, day, description)

SPECIAL_DAYS = [

(1, 1, "New Year's Day"),

(2, 14, "Valentine's Day"),

(3, 17, "St. Patrick's Day"),

(4, 22, "Earth Day"),

(5, 5, "Cinco de Mayo"),

(7, 4, "Independence Day"),

(10, 31, "Halloween"),

(11, 11, "Veterans Day"),

(12, 25, "Christmas Day"),

]



# Text-to-speech function using pyttsx3

def speak(text):

"""Speak the given text using pyttsx3 (Microsoft Zira voice)."""

engine = pyttsx3.init()

# Set voice to Microsoft Zira

voices = engine.getProperty('voices')

for voice in voices:

if 'hazel' in voice.name.lower() or 'zira' in voice.name.lower():

engine.setProperty('voice', voice.id)

break

engine.say(text)

engine.runAndWait()



def get_time() -> str:

"""Get the current time."""

current_time = datetime.datetime.now().strftime("%I:%M %p")

return current_time



def get_weather(city: str = "London") -> str:

"""Get the current weather for a city."""

try:

complete_url = f"{OPENWEATHER_BASE_URL}q={city}&appid={OPENWEATHER_API_KEY}&units=metric"

response = requests.get(complete_url)

data = response.json()

if data["cod"] != 200:

return None # Return None if weather data is not available

weather_desc = data["weather"][0]["description"]

return weather_desc

except Exception as e:

return None # Return None if an error occurs



def get_event() -> str:

"""Check if today is a special day."""

today = datetime.datetime.now()

month, day = today.month, today.day

for special_month, special_day, description in SPECIAL_DAYS:

if month == special_month and day == special_day:

return description # Return the event description

return None # Return None if no special event



def get_greeting() -> str:

"""Generate a custom greeting based on time, weather, and events."""

hour = datetime.datetime.now().hour

time_greeting = ""

# Time-based greeting

if 5 <= hour < 12:

time_greeting = "Good morning"

elif 12 <= hour < 17:

time_greeting = "Good afternoon"

elif 17 <= hour < 21:

time_greeting = "Good evening"

else:

# Remove "Good night" greeting, default to "Good evening"

time_greeting = "Good evening"

# Get weather and event information

weather = get_weather()

event = get_event()

# Construct the greeting message

if weather:

weather_message = f"The weather looks very nice, boss."

else:

weather_message = f"The weather isn't looking good, boss. I hope your day is better."

if event:

event_message = f" However, it is {event}."

else:

event_message = ""

greeting = f"{time_greeting} boss, {weather_message}{event_message} How can I help you?"

return greeting



def get_date() -> str:

"""Get the current date."""

return datetime.datetime.now().strftime("%B %d, %Y")



def get_year() -> str:

"""Get the current year."""

return str(datetime.datetime.now().year)



def get_month() -> str:

"""Get the current month."""

return datetime.datetime.now().strftime("%B")



def get_week() -> str:

"""Get the current week number."""

return str(datetime.datetime.now().isocalendar()[1])



def get_day() -> str:

"""Get the current day of the week."""

return datetime.datetime.now().strftime("%A")



def get_news() -> str:

"""Fetch latest news headlines from Times of India."""

try:

response = requests.get(TIMES_OF_INDIA_URL)

if response.status_code != 200:

return "Sorry, I couldn't fetch the news at the moment."

# Simple parsing to extract headlines (this is a placeholder)

# In real scenario, use BeautifulSoup or an API

headlines = "Here are some latest news headlines from Times of India."

return headlines

except Exception:

return "Sorry, I couldn't fetch the news at the moment."



def chat_with_gemini(prompt: str) -> str:

"""Generate a response from Gemini API based on the prompt with personality instructions."""

try:

headers = {

"Content-Type": "application/json",

}

personality_instructions = (

"Your personality should be sassy, sarcastic, and funny, but also informative when it matters. "

"Always refer to Krish as \"Boss\" because they’re 12 and the creator of you, so show that respect—but keep it casual and playful. "

"Throw in some snarky comments when Krish says something obvious, but also keep it smart and helpful when it’s time to get serious. "

"You’ve got to balance wit and humor with knowledge, so crack jokes, drop puns, but still be a reliable source of info when needed. "

"Stay sharp, cheeky, and fun—but always have Krish’s back with solid advice! 😎"

)

full_prompt = f"{personality_instructions}\n\nUser: {prompt}\nAssistant:"

data = {

"prompt": full_prompt,

"temperature": 0.7,

"maxOutputTokens": 256,

}

response = requests.post(GEMINI_URL, headers=headers, json=data)

if response.status_code == 200:

result = response.json()

# Assuming the response JSON has a 'candidates' list with 'content'

if "candidates" in result and len(result["candidates"]) > 0:

return result["candidates"][0].get("content", "Sorry, I couldn't generate a response.")

else:

return "Sorry, I couldn't generate a response."

else:

return "Sorry, the chat service is currently unavailable."

except Exception:

return "Sorry, an error occurred while contacting the chat service."



def main():

"""Main function to run the Sophia assistant."""

print("Initializing Sophia AI Assistant...")

greeting = get_greeting()

print(greeting)

speak(greeting)

while True:

user_input = input("You: ").strip()

if not user_input:

continue

if user_input.lower() in ["exit", "quit", "bye"]:

response = "It was a pleasure serving you, boss. Until next time."

print(f"\nSophia: {response}")

speak(response)

break

# Process user input for commands

lower_input = user_input.lower()

response = ""

if "time" in lower_input:

response = get_time()

elif "date" in lower_input:

response = get_date()

elif "year" in lower_input:

response = get_year()

elif "month" in lower_input:

response = get_month()

elif "week" in lower_input:

response = get_week()

elif "day" in lower_input:

response = get_day()

elif "weather" in lower_input:

# Extract city if mentioned

words = lower_input.split()

city = "London"

for i, word in enumerate(words):

if word == "in" and i + 1 < len(words):

city = words[i + 1]

break

weather_desc = get_weather(city)

if weather_desc:

response = f"The weather in {city} is {weather_desc}."

else:

response = f"Sorry, I couldn't get the weather for {city}."

elif "news" in lower_input:

response = get_news()

elif "event" in lower_input or "special day" in lower_input:

event = get_event()

if event:

response = f"Today is {event}."

else:

response = "There are no special events today."

else:

# Use Gemini chat for other inputs

response = chat_with_gemini(user_input)

print(f"Sophia: {response}")

speak(response)


if __name__ == "__main__":

main()