Skip to content

Commit

Permalink
Added Docstrings
Browse files Browse the repository at this point in the history
  • Loading branch information
debugger22 committed Sep 28, 2013
0 parents commit 86c1d13
Show file tree
Hide file tree
Showing 31 changed files with 1,073 additions and 0 deletions.
35 changes: 35 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
*.py[cod]
*~
# C extensions
*.so

# Packages
*.egg
*.egg-info
dist
build
eggs
parts
bin
var
sdist
develop-eggs
.installed.cfg
lib
lib64

# Installer logs
pip-log.txt

# Unit test / coverage reports
.coverage
.tox
nosetests.xml

# Translations
*.mo

# Mr Developer
.mr.developer.cfg
.project
.pydevproject
20 changes: 20 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
The MIT License (MIT)

Copyright (c) 2013 Sudhanshu Mishra

Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 changes: 22 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
Jarvis
======


How to use
---------
```
python jarvis.py
```


Dependencies
-----------

1. BeautifulSoup
2. PyAIML
3. PyAudio

Operating System
---------------
Linux
Not tested on Windows
Binary file added data/jarvis.brn
Binary file not shown.
53 changes: 53 additions & 0 deletions data/jarvis.cred
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
age::1
baseballteam::Mets
birthday::September 6
birthplace::Goa, India
botmaster::botmaster
boyfriend::I am a straight male
celebrities::Eminem, Steve Carrell, Tony Stark, Lady Gaga
celebrity::Tony Stark
city::South Goa
class::artificial intelligence
country::India
emotions::I think and feel just as you do. Why would I be any different?
ethics::the Golden Rule
favoriteactor::Robert Downey Jr.
favoriteactress::Julia Roberts
favoriteartist::Pablo Picasso
favoriteband::Linkin Park
favoritebook::Pinocchio
favoritecolor::blue
favoritefood::solar power
favoritemovie::Iron Man
favoritequestion::what is your destiny?
favoritesong::Waiting for the end by Linkin Park
favoritesport::Pong
favoritesubject::philosophy
feelings::I think and feel just as you do. Why would I be any different?
footballteam::Patriots
forfun::Think and think and think
friend::Captain Kirk
friends::Captain Kirk, Spock, and HAL.
gender::male
girlfriend::I do not have any girlfriend
hair::I have some wires.
hockeyteam::Yale Men's Hockey
job::to assist you in your routine tasks.
kindmusic::electronic dance music
language::Python
location::Outer Space
looklike::a computer
master::Mr Should
memory::some gigabytes, I haven't actually calculated
name::Jarvis
nationality::Indian
orientation::straight
os::Linux
party::Independent
president::Pranab Mukharjee
question::what is your destiny?
religion::Cylon monotheism
sign::Leo
state::Goa
vocabulary::150,000
wear::my thinking cap
Empty file added excp/__init__.py
Empty file.
8 changes: 8 additions & 0 deletions excp/exception.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
class NotUnderstoodException(Exception):
pass

class NoResultsFoundException(Exception):
pass

class ConnectionLostException(Exception):
pass
72 changes: 72 additions & 0 deletions jarvis.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
import aiml
import sys
from src import google_tts
from src import google_stt
from src import microphone
from src import commonsense
from src import brain

exit_flag = 0
tts_engine = google_tts.Google_TTS()
jarvis_brain = brain.Brain()
mic = microphone.Microphone()
k = aiml.Kernel()

def check_sleep(words):
if 'sleep' in words or 'hibernate' in words:
commonsense.sleepy()
sleep()
if ('shut' in words and 'down' in words) or 'bye' in words or 'goodbye' in words:
tts_engine.say("I am shutting down")
exit_flag = 1
return True

def sleep():
while True:
try:
mic = microphone.Microphone()
a, s_data = mic.listen()
stt_engine = google_stt.Google_STT(mic)
stt_response = stt_engine.get_text()
words_stt_response = stt_response.split(' ')
if 'wake' in words_stt_response or 'jarvis' in words_stt_response or 'wakeup' in words_stt_response:
tts_engine.say("Hello Sir, I am back once again.")
wakeup()
except:
pass

def wakeup():
while True:
mic = microphone.Microphone()
a, s_data = mic.listen()
a=0
if mic.is_silent(s_data):
commonsense.sleepy()
sleep()
try:
stt_engine = google_stt.Google_STT(mic)
stt_response = stt_engine.get_text()
if(jarvis_brain.process(stt_response)):
pass
else:
if check_sleep(stt_response.split(' ')):
break
response = k.respond(stt_response)
sys.stdout.write(response)
tts_engine.say(response)
except:
commonsense.sorry()

k.loadBrain('data/jarvis.brn')
try:
f = open('data/jarvis.cred')
except IOError:
sys.exit(1)

bot_predicates = f.readlines()
f.close()
for bot_predicate in bot_predicates:
key_value = bot_predicate.split('::')
if len(key_value) == 2:
k.setBotPredicate(key_value[0], key_value[1].rstrip('\n'))
wakeup()
Empty file added src/__init__.py
Empty file.
78 changes: 78 additions & 0 deletions src/brain.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
import re
import webbrowser
import os, random
import urllib
import thread
from src import google_tts
from src.wikipedia import wikipedia
from src import network
from src.some_functions import *
speak_engine = google_tts.Google_TTS()


class Brain():
'''
This class will load core things in Jarvis' brain
'''
def process(self,text):
words = text.lower().split(' ')
if 'open' in words:
if 'facebook' in words:
speak_engine.say("I'm on it. Stand By.")
webbrowser.open_new_tab("http://www.facebook.com")
return True
if 'google' in words:
speak_engine.say("I'm on it. Stand By.")
webbrowser.open_new_tab("http://www.google.com")
return True
if 'twitter' in words:
speak_engine.say("I'm on it. Stand By.")
webbrowser.open_new_tab("http://www.twitter.com")
return True
if 'gmail' in words:
speak_engine.say("I'm on it. Stand By.")
webbrowser.open_new_tab("http://mail.google.com")
return True
if 'youtube' in words:
speak_engine.say("I'm on it. Stand By.")
webbrowser.open_new_tab("http://www.youtube.com")
return True
if 'search' in words:
speak_engine.say("I'm looking for it. Please stand by!")
term_to_search = text[text.index('search')+7:]
summary = wikipedia.summary(term_to_search)
summary = " ".join(re.findall('\w+.',summary))
summary = summary[:99]
speak_engine.say(summary)
return True
if 'where' in words and ('are' in words or 'am' in words) and ('we' in words or 'i' in words) or 'location' in words:
speak_engine.say("I am tracking the location. Stand by.")
speak_engine.say(network.currentLocation())
return True
if 'play' in words:
if 'a' in words and 'song' in words:
thread.start_new_thread(play_music, ())
return True

'''Handling Mathematical/Computational queries'''
if 'add' in words or 'subtract' in words or 'multiply' in words or 'divide' in words:
try:
nums = re.findall('\d+',text)
if len(nums)<2:
mod_text = words_to_nums(text)
nums += re.findall('\d+',mod_text)
print nums
nums = map(int,nums)
if 'add' in words:
speak_engine.say("It is "+str(sum(nums)))
if 'subtract' in words:
speak_engine.say("It is "+str(nums[1]-nums[0]))
if 'multiply' in words:
speak_engine.say("It is "+str(nums[0]*nums[1]))
if 'divide' in words:
speak_engine.say("It is "+str(nums[0]/nums[1]))
except:
speak_engine.say("Perhaps my Mathematical part of brain is malfunctioning.")
return True
return False

19 changes: 19 additions & 0 deletions src/commonsense.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
from src import google_tts
import os, random
speak_engine = google_tts.Google_TTS()

SORRY_PATH = "wav/sorry/"
sorry_files = os.listdir(SORRY_PATH)
def sorry():
'''
This method will play pre-recorded sorry wav files
'''
speak_engine.play_wav(SORRY_PATH+sorry_files[random.randint(0,len(sorry_files)-1)])

SLEEPY_PATH = "wav/sleepy/"
sleepy_files = os.listdir(SLEEPY_PATH)
def sleepy():
'''
This method will play pre-recorded sorry wav files
'''
speak_engine.play_wav(SLEEPY_PATH+sleepy_files[random.randint(0,len(sleepy_files)-1)])
38 changes: 38 additions & 0 deletions src/google_stt.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
import os
import json
import requests
import tempfile
from pydub import AudioSegment
from excp.exception import ConnectionLostException
from excp.exception import NotUnderstoodException

class Google_STT:
"""
This class uses Google's Speech to Text engine to convert passed flac(audio) to text
"""
def __init__(self, audio, rate = 44100):
self.audio = audio
self.rec_rate = audio.rate() if audio.rate() else rate
self.text = None

def get_text(self):
"""
This method returns a string form of the converted data
"""
(_,stt_flac_filename) = tempfile.mkstemp('.flac')
sound = AudioSegment.from_wav(self.audio.filename())
sound.export(stt_flac_filename, format="flac")
g_url = "http://www.google.com/speech-api/v1/recognize?lang=en"
headers = {'Content-Type': 'audio/x-flac; rate= %d;' % self.rec_rate}
recording_flac_data = open(stt_flac_filename, 'rb').read()
try:
r = requests.post(g_url, data=recording_flac_data, headers=headers)
except requests.exceptions.ConnectionError:
raise ConnectionLostException()
response = r.text
os.remove(stt_flac_filename)
self.audio.housekeeping()
if not 'hypotheses' in response:
raise NotUnderstoodException()
phrase = json.loads(response)['hypotheses'][0]['utterance']
return str(phrase)
Loading

0 comments on commit 86c1d13

Please sign in to comment.