Creating a Python application that facilitates voice-based interaction with local Ollama models involves integrating several components seamlessly. Below is a comprehensive guide that includes the complete Python code, explanations of key components, and suggestions for further improvements.
Overview
This Python application enables voice-based communication with local Ollama models (e.g., llama3.2:3b). It captures voice input, converts it to text, sends the text to the Ollama model, retrieves the response, and then converts the response back to speech. The application also manages conversation memory both within and across sessions, handles commands like stopping and exiting, and incorporates robust error handling to ensure a smooth user experience.
Dependencies
Before diving into the code, ensure that you have the following dependencies installed:
-
Python 3.7 or higher
-
Python Libraries:
speech_recognition: For converting speech to text.
pyttsx3 or comtypes with Microsoft's Speech API: For text-to-speech (TTS).
requests: For making HTTP requests to the Ollama API.
pygame: For handling audio playback and stopping speech.
nest_asyncio and asyncio: For handling asynchronous tasks if needed.
logging: For logging purposes.
-
Local Ollama Server:
- Ensure that the Ollama model is running locally on your machine and is accessible via
localhost.
-
Additional Dependencies for TTS:
- Depending on the TTS engine you choose (e.g.,
pyttsx3 uses different drivers), you might need to install additional system libraries or configure specific settings.
Installation
You can install the required Python libraries using pip:
pip install SpeechRecognition pyttsx3 requests pygame
Note: If you choose to use Microsoft's Speech API for TTS, additional setup may be required, such as installing specific drivers or configuring APIs.
Complete Python Code
Below is the complete Python code that fulfills the requirements outlined:
import speech_recognition as sr
import pyttsx3
import requests
import json
import threading
import time
import os
import sys
import logging
from pygame import mixer
# Suppress unnecessary logs
logging.basicConfig(level=logging.ERROR)
# Initialize Pygame Mixer for TTS playback control
mixer.init()
# Initialize Text-to-Speech engine
tts_engine = pyttsx3.init()
voices = tts_engine.getProperty('voices')
tts_engine.setProperty('voice', voices[0].id) # Select the first available voice
tts_engine.setProperty('rate', 150) # Set speech rate
# Global flag to control playback
playback_flag = threading.Event()
playback_flag.set()
# Paths for persistent memory and summaries
MEMORY_FILE = 'conversation_memory.json'
SUMMARY_FILE = 'conversation_summary.txt'
# Load persistent memory
def load_memory():
if os.path.exists(MEMORY_FILE):
with open(MEMORY_FILE, 'r') as f:
try:
return json.load(f)
except json.JSONDecodeError:
return []
return []
# Save persistent memory
def save_memory(memory):
with open(MEMORY_FILE, 'w') as f:
json.dump(memory, f, indent=4)
# Summarize conversation (placeholder for actual summarization logic)
def summarize_conversation(memory):
summary = "Conversation Summary:\n"
for interaction in memory[-10:]: # Summarize last 10 interactions
summary += f"User: {interaction['user']}\nAI: {interaction['ai']}\n"
with open(SUMMARY_FILE, 'w') as f:
f.write(summary)
# Initialize conversation memory
conversation_memory = load_memory()
# Function to handle text-to-speech
def speak(text):
if not playback_flag.is_set():
return
def run_tts():
tts_engine.say(text)
tts_engine.runAndWait()
tts_thread = threading.Thread(target=run_tts)
tts_thread.start()
# Function to stop speech playback
def stop_speech():
tts_engine.stop()
mixer.music.stop()
playback_flag.clear()
# Function to recognize speech
def recognize_speech(recognizer, microphone):
with microphone as source:
recognizer.adjust_for_ambient_noise(source, duration=1)
try:
audio = recognizer.listen(source, timeout=5, phrase_time_limit=10)
except sr.WaitTimeoutError:
return None
try:
return recognizer.recognize_google(audio)
except sr.UnknownValueError:
return None
except sr.RequestError:
return None
# Function to interact with Ollama model
def query_ollama(prompt):
try:
response = requests.post(
'http://localhost:11434/v1/models/llama3.2:3b/completions',
headers={'Content-Type': 'application/json'},
data=json.dumps({
'prompt': prompt,
'max_tokens': 500
}),
timeout=30
)
if response.status_code == 200:
data = response.json()
return data.get('choices', [{}])[0].get('text', '').strip()
else:
return f"Error: Received status code {response.status_code}"
except requests.RequestException as e:
return f"Error: {str(e)}"
# Function to handle user commands
def handle_command(command):
command = command.lower()
if 'stop' in command:
stop_speech()
return True
if 'exit' in command:
summarize_conversation(conversation_memory)
save_memory(conversation_memory)
print("Exiting the application. Goodbye!")
sys.exit(0)
return False
# Main application loop
def main():
recognizer = sr.Recognizer()
microphone = sr.Microphone()
print("Initializing... Please wait.")
speak("Hello! How can I assist you today?")
while True:
print("Listening for your command...")
speech = recognize_speech(recognizer, microphone)
if speech:
print(f"You said: {speech}")
if handle_command(speech):
continue
# Send to Ollama model
ai_response = query_ollama(speech)
print(f"AI: {ai_response}")
# Update conversation memory
conversation_memory.append({'user': speech, 'ai': ai_response})
# Speak the AI response
speak(ai_response)
else:
print("Didn't catch that. Please try again.")
speak("I didn't catch that. Could you please repeat?")
# Run the application
if __name__ == "__main__":
try:
main()
except KeyboardInterrupt:
summarize_conversation(conversation_memory)
save_memory(conversation_memory)
print("\nSession ended. Goodbye!")
sys.exit(0)
except Exception as e:
logging.error(f"An unexpected error occurred: {str(e)}")
print("An unexpected error occurred. Please check the logs for more details.")
sys.exit(1)
Key Components Explanation
1. Speech Recognition
The application uses the speech_recognition library to capture and convert voice input to text.
import speech_recognition as sr
def recognize_speech(recognizer, microphone):
with microphone as source:
recognizer.adjust_for_ambient_noise(source, duration=1)
try:
audio = recognizer.listen(source, timeout=5, phrase_time_limit=10)
except sr.WaitTimeoutError:
return None
try:
return recognizer.recognize_google(audio)
except sr.UnknownValueError:
return None
except sr.RequestError:
return None
- Ambient Noise Adjustment:
adjust_for_ambient_noise calibrates the recognizer to account for background noise.
- Timeouts:
timeout=5 and phrase_time_limit=10 ensure the application doesn't wait indefinitely and avoids premature cutoffs.
- Error Handling: The function gracefully handles scenarios where speech isn't recognized or the API request fails.
2. Text-to-Speech (TTS)
The application employs pyttsx3 for converting text responses from the AI into audible speech.
import pyttsx3
tts_engine = pyttsx3.init()
voices = tts_engine.getProperty('voices')
tts_engine.setProperty('voice', voices[0].id) # Select the first available voice
tts_engine.setProperty('rate', 150) # Set speech rate
def speak(text):
if not playback_flag.is_set():
return
def run_tts():
tts_engine.say(text)
tts_engine.runAndWait()
tts_thread = threading.Thread(target=run_tts)
tts_thread.start()
def stop_speech():
tts_engine.stop()
- Voice Selection: Selects the first available voice. You can customize this based on your system's available voices.
- Speech Rate: Adjusted to 150 words per minute for clarity.
- Asynchronous Playback: Uses threading to ensure the main application loop isn't blocked during speech playback.
- Stop Playback:
stop_speech function allows interrupting ongoing speech.
3. Ollama Model Integration
Communicates with the local Ollama model hosted on localhost using HTTP requests.
import requests
import json
def query_ollama(prompt):
try:
response = requests.post(
'http://localhost:11434/v1/models/llama3.2:3b/completions',
headers={'Content-Type': 'application/json'},
data=json.dumps({
'prompt': prompt,
'max_tokens': 500
}),
timeout=30
)
if response.status_code == 200:
data = response.json()
return data.get('choices', [{}])[0].get('text', '').strip()
else:
return f"Error: Received status code {response.status_code}"
except requests.RequestException as e:
return f"Error: {str(e)}"
- Endpoint Configuration: Adjust the URL to match your Ollama server's configuration.
- Timeout Handling: A 30-second timeout ensures the application doesn't hang indefinitely waiting for a response.
- Error Feedback: Provides clear error messages if the server is unreachable or returns an unexpected status code.
4. Memory Management
Handles both in-session and persistent memory to maintain conversation context.
import os
import json
MEMORY_FILE = 'conversation_memory.json'
SUMMARY_FILE = 'conversation_summary.txt'
def load_memory():
if os.path.exists(MEMORY_FILE):
with open(MEMORY_FILE, 'r') as f:
try:
return json.load(f)
except json.JSONDecodeError:
return []
return []
def save_memory(memory):
with open(MEMORY_FILE, 'w') as f:
json.dump(memory, f, indent=4)
def summarize_conversation(memory):
summary = "Conversation Summary:\n"
for interaction in memory[-10:]: # Summarize last 10 interactions
summary += f"User: {interaction['user']}\nAI: {interaction['ai']}\n"
with open(SUMMARY_FILE, 'w') as f:
f.write(summary)
conversation_memory = load_memory()
- Persistent Memory: Stores conversation history in a JSON file, allowing the model to recall previous interactions across sessions.
- Memory Pruning: The
summarize_conversation function creates a summary of the last 10 interactions to prevent token limit issues.
- Error Handling: Ensures the application doesn't crash if the memory file is missing or corrupted.
5. Command Handling
Implements commands like stop and exit to control the application's behavior.
import sys
def handle_command(command):
command = command.lower()
if 'stop' in command:
stop_speech()
return True
if 'exit' in command:
summarize_conversation(conversation_memory)
save_memory(conversation_memory)
print("Exiting the application. Goodbye!")
sys.exit(0)
return False
- Stop Command: Halts ongoing speech playback.
- Exit Command: Ends the session, saves the conversation, and exits gracefully.
- Graceful Handling: Ensures that the application doesn't crash and provides user feedback during these operations.
6. Error Handling
Incorporates robust error handling mechanisms to manage various failure scenarios gracefully.
import logging
# Suppress unnecessary logs
logging.basicConfig(level=logging.ERROR)
# Throughout the code, try-except blocks handle specific exceptions
# For example, in the main loop:
try:
main()
except KeyboardInterrupt:
summarize_conversation(conversation_memory)
save_memory(conversation_memory)
print("\nSession ended. Goodbye!")
sys.exit(0)
except Exception as e:
logging.error(f"An unexpected error occurred: {str(e)}")
print("An unexpected error occurred. Please check the logs for more details.")
sys.exit(1)
- Logging Configuration: Sets the logging level to
ERROR to suppress less critical logs.
- Specific Exception Handling: Differentiates between
KeyboardInterrupt and other unexpected exceptions.
- User Feedback: Provides clear messages to the user in case of errors without exposing unnecessary technical details.
7. Suppress Unnecessary Logs
Ensures that only relevant information is displayed to the user by configuring the logging module.
import logging
logging.basicConfig(level=logging.ERROR)
- Logging Level: By setting the level to
ERROR, only critical issues are logged, while informational and debugging messages are suppressed.
Running the Application
-
Ensure Ollama Server is Running:
- Start your Ollama server locally, ensuring it listens on the appropriate port (e.g.,
11434).
-
Execute the Python Script:
-
Interact via Voice:
- Speak your commands or queries when prompted.
- Use commands like "stop" to halt speech or "exit" to terminate the application.
Further Refinements and Suggestions
While the current application meets the core requirements, here are some suggestions to enhance its functionality and user experience:
-
Enhanced Summarization:
- Integrate a more sophisticated summarization model or algorithm to generate concise and meaningful summaries of the conversation.
-
Dynamic Voice Selection:
- Allow users to choose from multiple available TTS voices and adjust speech rate and volume based on preferences.
-
Graphical User Interface (GUI):
- Develop a GUI using frameworks like
Tkinter or PyQt to provide a more user-friendly interface, visual indicators for listening and speaking states, and controls for settings.
-
Asynchronous Processing:
- Utilize asynchronous programming (
asyncio) to handle multiple tasks concurrently, improving responsiveness, especially during long-running operations.
-
Advanced Memory Management:
- Implement token counting mechanisms to ensure conversation history stays within the model's token limits.
- Introduce mechanisms to prioritize recent interactions or important context over older, less relevant parts.
-
Security Enhancements:
- If deploying in a multi-user environment, incorporate authentication and authorization mechanisms to secure access to the Ollama API.
-
Logging and Monitoring:
- Expand logging to include debug information during development while maintaining minimal logs in production.
- Implement monitoring tools to track the application's performance and identify potential bottlenecks.
-
Error Recovery:
- Develop strategies to recover from common errors without terminating the application, such as retry mechanisms for failed API requests.
-
Multi-language Support:
- Extend speech recognition and TTS capabilities to support multiple languages, catering to a broader user base.
-
Customization of Commands:
- Allow users to customize command phrases or add new commands for additional functionalities.
Conclusion
This Python application provides a robust and efficient way to interact with local Ollama models using voice commands. By integrating speech recognition, text-to-speech, and model querying functionalities, it offers a seamless conversational experience. With the outlined suggestions for further enhancements, you can tailor the application to better suit specific needs and improve its overall performance and usability.