Friday, April 16, 2021

Google Assistant program sent by Blessen Eby & Aaron Mohan Varghese

import pyttsx3

import speech_recognition as sr

import datetime

import wikipedia

import webbrowser

import os

import smtplib

import pywhatkit

import pyjokes


engine = pyttsx3.init('sapi5')

voices = engine.getProperty('voices')

engine.setProperty('voice', voices[0].id)


def speak(audio):

  engine.say(audio)

  engine.runAndWait()


def wishMe():

  hour = int(datetime.datetime.now().hour)

  if hour>=0 and hour<12:

    speak("Good Morning!")

  elif hour>=12 and hour<18:

    speak("Good Afternoon!")

  elif hour==12:

    speak('Sir,its mid day. Would you like me to help you with something')

  else:

    speak("Good Evening!")

  speak("I am Dracore. Please tell me how may I help you, Sir")


def takeCommand():

  r = sr.Recognizer()

  with sr.Microphone() as source:

    print("Listening...")

    r.pause_threshold = 1

    audio = r.listen(source)

  try:

    print("Recognizing...")

    query = r.recognize_google(audio, language='en-uk')

    print(f"User said: {query}\n")

  except Exception as e:

    # print(e)

    print("Say that again please...")

    return "None"

  return query


def sendEmail(to, content):

  server = smtplib.SMTP('smtp.gmail.com', 587)

  server.ehlo()

  server.starttls()

  gmail, pword = "", ""

  server.login(gmail, pword)

  server.sendmail('binoythomas1108@gmail.com', to, content)

  server.close()


if __name__ == "__main__":

  wishMe()

  while True:

    query = takeCommand().lower()

    if 'wikipedia' in query:

      try:

        speak('Searching Wikipedia...')

        query = query.replace("wikipedia", "")

        results = wikipedia.summary(query, sentences=2)

        speak("According to Wikipedia")

        print(results)

        speak(results)

      except:

        speak('Sorry, this result does not exist')

    elif 'who is' in query:

      try:

        speak('Searching in Wikipedia ...')

        query = query.replace("who is", "")

        results = wikipedia.summary(query, sentences=3)

        speak("According to Wikipedia")

        print(results)

        speak(results)

      except:

        speak('sorry, this person does not exist')

    elif 'open youtube' in query:

      webbrowser.open("youtube.com")

    elif 'open google' in query:

      webbrowser.open("google.com")

    elif 'open stackoverflow' in query:

      webbrowser.open("stackoverflow.com")

    elif 'music please' in query:

      music_dir = 'G:/Music'

      songs = os.listdir(music_dir)

      print(songs)

      os.startfile(os.path.join(music_dir, songs[0]))

    elif 'the time' in query:

      strTime = datetime.datetime.now().strftime("%H:%M:%S %p")

      speak(f"Sir, the time is {strTime}")

    elif 'open code' in query:

      codePath = "C:/Users/user/Desktop"

      os.startfile(codePath)

    elif 'joke'in query:

      speak(pyjokes.get_joke())

      print(pyjokes.get_joke())

    elif 'send an email' in query:

      try:

        speak("What should I say?")

        content = takeCommand()

        to = 'binoythomas1108@gmail.com'

        sendEmail(to, content)

        speak("Email has been sent!")

      except Exception as e:

        print(e)

        speak("Sorry . I am not able to send this email")

    elif 'play' in query:

      video = query.replace('play','')

      speak('playing....'+video)

      pywhatkit.playonyt(video)

    elif 'hello' in query:

      speak('hi Sir ,Is there anything you need')

    elif 'exit listening' in query:

      speak('see you later sir')

      exit()

    elif 'what is your name' in query:

      speak('my name is dracore')

    elif 'search' in query:

      query = query.replace('search','')

      pywhatkit.search(query)


Tuesday, April 13, 2021

Creating & Using Virtual Environments

Creating & Using Virtual Environments

1) To create a virtual environment, open an Anaconda prompt.

2) Type "conda create --name Your_vir_env libraries_to_install", e.g., 

conda create --name py_vir jupyter nb_conda ipykernel keras

3) To load the virtual environment, type: "conda activate Your_vir_env", e.g.,

conda activate py_vir

4) The left column of the prompt should change from "base" to "Your_vir_env".

5) To install other libraries later, load the virtual environment using step 3 and type "conda install libraries_to_install", e.g., to install pandas, type:

"conda install pandas"

6) To launch jupyter notebook, load in the virtual environment using step 3 & type “jupyter notebook”. It will open a new tab in the browser.

Wednesday, April 7, 2021

Sliding frame in tkinter


(Right-click the images, choose "Save image as ..." and save them to the same folder as the script. Save images by the default names.)


from tkinter import *

from time import sleep


win = Tk()

win.geometry("300x200")

win.title("Sliding Frame")


frm = Frame(win, width=80, height=150)

frm.place(x=-100, y=38)


frmShowing = False

def slide():

  global frmShowing

  if frmShowing == False:

    for i in range(-80, -1, 1):

      frm.place(x=i, y=38)

      sleep(.01)

      win.update()

    frmShowing = True

  else:

    pic = PhotoImage(file="Blank.png")

    lblImage.config(image=pic)

    lblImage.image = pic

    for i in range(0, -81, -1):

      frm.place(x=i, y=38)

      sleep(.01)

      win.update()

    frmShowing = False

    

pic = PhotoImage(file="Menu.png")

btnMenu = Button(win, image=pic, command=slide)

btnMenu.place(x=0, y=0)


lblImage = Label(win);  lblImage.place(x=150, y=40)


def Show(mood):

  pic = PhotoImage(file=mood + ".png")

  lblImage.config(image=pic)

  lblImage.image = pic


btnHappy = Button(frm, text="Happy", font="Arial 12 bold",\

                  activeforeground="red", bd=0, command=lambda:Show("Happy"))

btnHappy.place(x=5, y=20)


btnGoofy = Button(frm, text="Goofy", font="Arial 12 bold",\

                  activeforeground="red", bd=0, command=lambda:Show("Goofy"))

btnGoofy.place(x=5, y=50)


btnCreepy = Button(frm, text="Creepy", font="Arial 12 bold",\

                   activeforeground="red", bd=0, command=lambda:Show("Creepy"))

btnCreepy.place(x=5, y=80)


win.mainloop()


Monday, April 5, 2021

Sending WhatsApp message through Python (contributed by Aaron Mohan Varghese)

import pywhatkit


pywhatkit.sendwhatmsg("+919400724727", "Hi Aaron, this is fantastic! Thanks for sharing!! I am glad to have students who point me in new directions ...", 14, 57)


# Syntax: pywhatkit.sendwhatmsg(number, msg, hour, minute)

Saturday, April 3, 2021

Storing to & Retrieving images from MySQL

# https://www.youtube.com/watch?v=NwvTh-gkdfs

''' Should have a table "images" under test as:

CREATE TABLE images

( id    INT(45) NOT NULL AUTO_INCREMENT PRIMARY KEY,

  photo LONGBLOB NOT NULL

);

'''


import mysql.connector as mc


conn = mc.connect(host="localhost", user="root", password="bont", database="test")

cur = conn.cursor()


def InsertBlob(Path):

  with open(Path, "rb") as inn:

    s = inn.read()

  sql = "INSERT INTO images (Photo) VALUES (%s)"

  cur.execute(sql, (s, ))

  conn.commit()


def RetrieveBlob(ID):

  sql = "SELECT * FROM images WHERE id = '{0}'"

  cur.execute(sql.format(str(ID)))

  result = cur.fetchone()[1]

  storeFilePath = "img{0}.jpg".format(str(ID))

  print(result)

  with open(storeFilePath, "wb") as out:

    out.write(result)

    out.close()


print("1. Insert Image")

print("2. Read Image")

choice = input("Enter your choice: ")

if choice == '1':

  path = input("Enter file path: ")

  InsertBlob(path)

elif choice == '2':

  userId = input("Enter ID: ")

  RetrieveBlob(userId)