import speech_recognition as sr
import threading
import time
import logging
import requests
import os
from obswebsocket import obsws, requests as obs_requests
from urllib.parse import urlencode
# ---------------------- Configuration ----------------------
# OBS WebSocket Configuration
OBS_HOST = "localhost" # OBS WebSocket host
OBS_PORT = 4455 # OBS WebSocket port
OBS_PASSWORD = "your_obs_password" # OBS WebSocket password
# Unsplash API Configuration
UNSPLASH_ACCESS_KEY = "your_unsplash_access_key" # Replace with your Unsplash Access Key
UNSPLASH_API_URL = "https://api.unsplash.com/search/photos"
# Image Sources in OBS
SEARCH_IMAGE_SOURCE = "SearchImage" # Name of the search image source in OBS
YAY_IMAGE_SOURCE = "YayImage" # Name of the "yay" image source in OBS
# Image Positions (Modify as per your OBS canvas size)
SEARCH_IMAGE_END_POSITION = {"x": 100, "y": 100} # Target position for search image
YAY_IMAGE_END_POSITION = {"x": 400, "y": 100} # Target position for "yay" image
ANIMATION_DURATION = 2.0 # Seconds for the slide-in animation
# Download Configuration
DOWNLOAD_FOLDER = "downloaded_images" # Folder to save downloaded images
NUMBER_OF_IMAGES = 5 # Number of images to download from Unsplash
# Logging Configuration
logging.basicConfig(level=logging.INFO,
format='%(asctime)s - %(levelname)s - %(message)s')
# -----------------------------------------------------------
class OBSController:
def __init__(self, host, port, password):
self.ws = obsws(host, port, password)
try:
self.ws.connect()
logging.info("Connected to OBS WebSocket.")
except Exception as e:
logging.error(f"Failed to connect to OBS WebSocket: {e}")
raise
def slide_image(self, source_name, target_position, duration=2):
"""
Animates the sliding of an image source to the target position.
"""
try:
# Get current position to calculate movement
current_scene_item = self.ws.call(obs_requests.GetSceneItemProperties(source_name)).getSceneItemProperties()
start_position = current_scene_item["position"]
# Move in steps to create animation
steps = 20
delay = duration / steps
delta_x = (target_position["x"] - start_position["x"]) / steps
delta_y = (target_position["y"] - start_position["y"]) / steps
for i in range(1, steps + 1):
new_position = {
"x": start_position["x"] + delta_x * i,
"y": start_position["y"] + delta_y * i
}
self.ws.call(obs_requests.SetSceneItemProperties(source=source_name, position=new_position))
time.sleep(delay)
logging.info(f"Image '{source_name}' slid to position {target_position}.")
except Exception as e:
logging.error(f"Error sliding image '{source_name}': {e}")
def slide_both_images_in(self, search_target, yay_target, duration=ANIMATION_DURATION):
"""
Slides both search and yay images into view.
"""
try:
# Slide both images in parallel using threading
search_thread = threading.Thread(target=self.slide_image, args=(SEARCH_IMAGE_SOURCE, search_target, duration))
yay_thread = threading.Thread(target=self.slide_image, args=(YAY_IMAGE_SOURCE, yay_target, duration))
search_thread.start()
yay_thread.start()
search_thread.join()
yay_thread.join()
logging.info("Both images have been slid in.")
except Exception as e:
logging.error(f"Error sliding images: {e}")
def slide_both_images_out(self, duration=ANIMATION_DURATION):
"""
Slides both images out of view to their initial positions.
Assumes initial positions are off-screen; modify as needed.
"""
try:
# Define off-screen starting positions
off_screen_left = {"x": -500, "y": 100}
off_screen_right = {"x": 1920 + 500, "y": 100} # Assuming a 1920 width canvas
# Slide both images out in parallel
search_thread = threading.Thread(target=self.slide_image, args=(SEARCH_IMAGE_SOURCE, off_screen_left, duration))
yay_thread = threading.Thread(target=self.slide_image, args=(YAY_IMAGE_SOURCE, off_screen_right, duration))
search_thread.start()
yay_thread.start()
search_thread.join()
yay_thread.join()
logging.info("Both images have been slid out.")
except Exception as e:
logging.error(f"Error sliding images out: {e}")
def disconnect(self):
self.ws.disconnect()
logging.info("Disconnected from OBS WebSocket.")
def search_unsplash(query, per_page=5):
"""
Searches Unsplash for images matching the query.
"""
try:
headers = {
"Accept-Version": "v1",
"Authorization": f"Client-ID {UNSPLASH_ACCESS_KEY}"
}
params = {
"query": query,
"per_page": per_page
}
response = requests.get(UNSPLASH_API_URL, headers=headers, params=params)
response.raise_for_status()
data = response.json()
images = [result["urls"]["small"] for result in data["results"]]
logging.info(f"Found {len(images)} images for query '{query}'.")
return images
except requests.RequestException as e:
logging.error(f"Unsplash API request failed: {e}")
return []
def download_images(image_urls, download_folder):
"""
Downloads images from the provided URLs to the specified folder.
"""
if not os.path.exists(download_folder):
os.makedirs(download_folder)
logging.info(f"Created download folder at '{download_folder}'.")
downloaded_files = []
for idx, url in enumerate(image_urls, start=1):
try:
response = requests.get(url, stream=True)
response.raise_for_status()
image_path = os.path.join(download_folder, f"image_{int(time.time())}_{idx}.jpg")
with open(image_path, 'wb') as f:
for chunk in response.iter_content(1024):
f.write(chunk)
downloaded_files.append(image_path)
logging.info(f"Downloaded image to '{image_path}'.")
except requests.RequestException as e:
logging.error(f"Failed to download image from '{url}': {e}")
return downloaded_files
def listen_for_commands(callback):
"""
Continuously listens for voice commands and triggers the callback upon detection.
"""
recognizer = sr.Recognizer()
microphone = sr.Microphone()
logging.info("Adjusting for ambient noise. Please wait...")
with microphone as source:
recognizer.adjust_for_ambient_noise(source)
logging.info("Adjustment complete. Listening for commands...")
while True:
with microphone as source:
try:
audio = recognizer.listen(source, timeout=None)
command = recognizer.recognize_google(audio).lower()
logging.info(f"Detected command: {command}")
callback(command)
except sr.UnknownValueError:
logging.warning("Could not understand the audio.")
except sr.RequestError as e:
logging.error(f"Speech recognition service error: {e}")
except Exception as e:
logging.error(f"Error while listening: {e}")
def main():
obs = None
try:
obs = OBSController(OBS_HOST, OBS_PORT, OBS_PASSWORD)
except Exception as e:
logging.critical("Exiting due to OBS WebSocket connection failure.")
return
def handle_command(command):
if "alfred" in command:
logging.info("Processing 'alfred' command.")
# Slide in images
obs.slide_both_images_in(SEARCH_IMAGE_END_POSITION, YAY_IMAGE_END_POSITION)
# After sliding in, listen for second command
listen_for_second_command()
def listen_for_second_command():
recognizer = sr.Recognizer()
microphone = sr.Microphone()
logging.info("Listening for the second command...")
with microphone as source:
try:
audio = recognizer.listen(source, timeout=10) # Timeout after 10 seconds
second_command = recognizer.recognize_google(audio).lower()
logging.info(f"Detected second command: {second_command}")
if "me a" in second_command:
# Extract keywords after "me a"
keywords = second_command.split("me a", 1)[1].strip()
logging.info(f"Extracted keywords: '{keywords}'")
# Search Unsplash
image_urls = search_unsplash(keywords, per_page=NUMBER_OF_IMAGES)
# Download images
downloaded_files = download_images(image_urls, DOWNLOAD_FOLDER)
# Optionally, you can add code here to display these images in OBS or perform other actions
else:
logging.warning("Second command does not contain 'me a'.")
except sr.UnknownValueError:
logging.warning("Could not understand the second audio command.")
except sr.RequestError as e:
logging.error(f"Speech recognition service error: {e}")
except sr.WaitTimeoutError:
logging.warning("Listening timed out waiting for the second command.")
except Exception as e:
logging.error(f"Error while processing the second command: {e}")
finally:
# Slide images out after handling the second command
obs.slide_both_images_out()
# Start listening for the initial 'alfred' command in a separate thread
listener_thread = threading.Thread(target=listen_for_commands, args=(handle_command,), daemon=True)
listener_thread.start()
try:
while True:
time.sleep(1) # Keep the main thread alive
except KeyboardInterrupt:
logging.info("Interrupted by user.")
finally:
if obs:
obs.disconnect()
if __name__ == "__main__":
main()