Spaces:
Sleeping
Sleeping
import speech_recognition as sr | |
import webbrowser | |
import pyttsx3 | |
import requests | |
import musiclibrary # your dict of song -> URL | |
API_BASE = "http://127.0.0.1:8000" | |
engine = pyttsx3.init() | |
recognizer = sr.Recognizer() | |
# ---------------- Voice Output ---------------- | |
def speak(text: str): | |
print("Jarvis:", text) | |
engine.say(text) | |
engine.runAndWait() | |
# ---------------- API POST Helper ---------------- | |
def post(endpoint: str, payload: dict) -> dict | None: | |
try: | |
r = requests.post(f"{API_BASE}{endpoint}", json=payload, timeout=15) | |
r.raise_for_status() | |
return r.json() | |
except Exception as e: | |
print("API error:", e) | |
return None | |
# ---------------- AI Features ---------------- | |
def ask_ai(message: str) -> str: | |
data = post("/chat", {"message": message}) | |
return (data or {}).get("reply", "Sorry, I couldn't reach my brain.") | |
def do_summarize(text: str) -> str: | |
data = post("/summarize", {"text": text}) | |
return (data or {}).get("summary", "Couldn't summarize.") | |
def do_translate(text: str, direction: str) -> str: | |
data = post("/translate", {"text": text, "direction": direction}) | |
return (data or {}).get("translation", "Couldn't translate.") | |
def do_sentiment(text: str) -> str: | |
data = post("/sentiment", {"text": text}) | |
if not data: | |
return "Couldn't analyze sentiment." | |
return f"{data['label']} ({round(data['score'], 2)})" | |
# ---------------- Command Handler ---------------- | |
def handle_commands(cmd: str) -> bool: | |
""" | |
Returns True if handled as a built-in command, False if not (so we fall back to AI). | |
""" | |
c = cmd.lower().strip() | |
# quick built-ins | |
if "open google" in c: | |
speak("Opening Google") | |
webbrowser.open("https://www.google.com") | |
return True | |
if "open youtube" in c: | |
speak("Opening YouTube") | |
webbrowser.open("https://www.youtube.com") | |
return True | |
if c.startswith("play "): | |
song = c.replace("play", "", 1).strip() | |
url = musiclibrary.music.get(song) | |
if url: | |
speak(f"Playing {song}") | |
webbrowser.open(url) | |
else: | |
speak("I don't know that song.") | |
return True | |
if any(x in c for x in ["stop", "exit", "goodbye", "sleep"]): | |
speak("Going to sleep. Bye!") | |
raise SystemExit | |
# summarize: "summarize <text>" | |
if c.startswith("summarize "): | |
text = c.replace("summarize", "", 1).strip() | |
summary = do_summarize(text) | |
speak(summary) | |
return True | |
# translate: "translate to hindi <text>" or "translate to english <text>" | |
if c.startswith("translate to hindi"): | |
text = c.replace("translate to hindi", "", 1).strip() | |
out = do_translate(text, "en-hi") | |
speak(out) | |
return True | |
if c.startswith("translate to english"): | |
text = c.replace("translate to english", "", 1).strip() | |
out = do_translate(text, "hi-en") | |
speak(out) | |
return True | |
# sentiment: "sentiment <text>" | |
if c.startswith("sentiment "): | |
text = c.replace("sentiment", "", 1).strip() | |
res = do_sentiment(text) | |
speak(res) | |
return True | |
return False # not handled | |
# ---------------- Main Listening Loop ---------------- | |
def listen_loop(): | |
speak("Initializing Jarvis...") | |
active = False | |
while True: | |
try: | |
with sr.Microphone() as source: | |
recognizer.adjust_for_ambient_noise(source, duration=0.3) | |
if not active: | |
print("Listening for wake word...") | |
audio = recognizer.listen(source, timeout=7, phrase_time_limit=6) | |
text = recognizer.recognize_google(audio).lower() | |
print("Heard:", text) | |
if "jarvis" in text or "jervis" in text: | |
speak("HII KABIR..HOW CAN I HELP YOU...") | |
active = True | |
else: | |
print("Listening for command...") | |
audio = recognizer.listen(source, timeout=8, phrase_time_limit=8) | |
cmd = recognizer.recognize_google(audio) | |
print("Command:", cmd) | |
# 1) try built-ins; 2) else call AI /chat | |
handled = handle_commands(cmd) | |
if not handled: | |
reply = ask_ai(cmd) | |
speak(reply) | |
except sr.WaitTimeoutError: | |
continue | |
except sr.UnknownValueError: | |
print("Didn't catch that.") | |
except SystemExit: | |
break | |
except Exception as e: | |
print("Error:", e) | |
if __name__ == "__main__": | |
listen_loop() | |