Generalwakeup.py 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165
  1. import pygame
  2. import speech_recognition as sr
  3. from openai import OpenAI
  4. from pathlib import Path
  5. import os
  6. import io
  7. import soundfile as sf
  8. import sounddevice as sd
  9. import random
  10. import csv
  11. import threading
  12. import signal
  13. import sys
  14. pygame.mixer.init()
  15. # Set your OpenAI API key here
  16. api_key = 'sk-proj-wwWaxim345ertfgb1Qt13uqzSS0xjT3BlbkFJK0rZvx78AJiWG3Ot7d3S'
  17. client = OpenAI(api_key=api_key)
  18. # Function to read text file
  19. def read_text_file(file_path):
  20. with open(file_path, 'r', encoding='utf-8') as file:
  21. return file.read()
  22. # Function to read CSV file
  23. def read_csv_file(file_path):
  24. content = ""
  25. try:
  26. with open(file_path, mode='r', encoding='utf-8') as file:
  27. reader = csv.reader(file)
  28. for row in reader:
  29. content += ' '.join(row) + ' '
  30. except Exception as e:
  31. print(f"Error reading CSV file: {e}")
  32. return content
  33. # Function to recognize speech from the microphone
  34. def recognize_speech():
  35. recognizer = sr.Recognizer()
  36. with sr.Microphone() as source:
  37. print("Listening...")
  38. audio = recognizer.listen(source)
  39. try:
  40. print("Recognizing...")
  41. text = recognizer.recognize_google(audio, language='en-US')
  42. audio_files = ["ty.mp3", "th.mp3", "sure.mp3", "sure1.mp3"]
  43. # Select a random audio file
  44. random_audio = random.choice(audio_files)
  45. # Load and play the selected random audio
  46. pygame.mixer.music.load(random_audio)
  47. pygame.mixer.music.play()
  48. print(f"You said: {text}")
  49. return text
  50. except sr.UnknownValueError:
  51. print("Sorry, I did not understand that.")
  52. return None
  53. except sr.RequestError:
  54. print("Sorry, there was an error with the speech recognition service.")
  55. return None
  56. # Function to create messages for OpenAI API
  57. def create_messages(question, file_content):
  58. return [
  59. {"role": "system", "content": "Your name is Futurebot. You were created by Sooraj and team who develops innovative projects in IoT future lab at Vodafone. You work with Tim, Sooraj, and Priya along with other team members Laura, Sven, Thomas, and Stephie. You are from T-E-T-I team. Your manager is Teja. You are a lab tour guide who explains and answers about IoT use cases in Vodafone. You have to create and complete explanations and answers in a meaningful way under 150 tokens. Do not say greetings. Do not say any calculations. Directly say the result."},
  60. {"role": "user", "content": f"{file_content}\n\nQ: {question}\nA:"}
  61. ]
  62. # Function to get a response from OpenAI
  63. def get_response_from_openai(messages):
  64. stream = client.chat.completions.create(
  65. model="gpt-4o",
  66. max_tokens=150,
  67. temperature=0.5,
  68. messages=messages,
  69. stream=True,
  70. )
  71. for chunk in stream:
  72. if chunk.choices[0].delta.content is not None:
  73. yield chunk.choices[0].delta.content
  74. # Function to generate and play speech in chunks
  75. def generate_speech(text):
  76. if text.strip(): # Only generate speech if the text is not empty
  77. spoken_response = client.audio.speech.create(
  78. model="tts-1",
  79. voice="alloy",
  80. input=text
  81. )
  82. buffer = io.BytesIO()
  83. for chunk in spoken_response.iter_bytes(chunk_size=4096):
  84. buffer.write(chunk)
  85. buffer.seek(0)
  86. with sf.SoundFile(buffer, 'r') as sound_file:
  87. data = sound_file.read(dtype='int16')
  88. sd.play(data, sound_file.samplerate)
  89. sd.wait()
  90. # Main function to handle user query
  91. def chatbot(question, text_file_path, csv_file_path):
  92. text_content = read_text_file(text_file_path)
  93. csv_content = read_csv_file(csv_file_path)
  94. combined_content = text_content + ' ' + csv_content
  95. messages = create_messages(question, combined_content)
  96. response_generator = get_response_from_openai(messages)
  97. print("Answer: ", end="")
  98. accumulated_response = ""
  99. for response_chunk in response_generator:
  100. accumulated_response += response_chunk
  101. if '.' in response_chunk or len(accumulated_response) > 500: # Check for sentence end or length
  102. print(accumulated_response, end="", flush=True)
  103. generate_speech(accumulated_response)
  104. accumulated_response = "" # Reset accumulated response for the next chunk
  105. if accumulated_response: # Generate speech for any remaining text
  106. print(accumulated_response, end="", flush=True)
  107. generate_speech(accumulated_response)
  108. # Function to detect wake word
  109. def detect_wake_word(stop_event):
  110. recognizer = sr.Recognizer()
  111. wake_word = "hello futurebot"
  112. with sr.Microphone() as source:
  113. while not stop_event.is_set():
  114. print("Waiting for wake word...")
  115. audio = recognizer.listen(source)
  116. try:
  117. text = recognizer.recognize_google(audio, language='en-US').lower()
  118. if wake_word in text:
  119. print("Wake word detected!")
  120. question = recognize_speech()
  121. if question:
  122. chatbot(question, text_file_path, csv_file_path)
  123. else:
  124. print("Sorry, I didn't get that. Please ask again.")
  125. except sr.UnknownValueError:
  126. continue
  127. except sr.RequestError:
  128. print("Sorry, there was an error with the speech recognition service.")
  129. continue
  130. def signal_handler(signal, frame):
  131. print("Exiting program...")
  132. stop_event.set()
  133. sys.exit(0)
  134. if __name__ == "__main__":
  135. text_file_path = 'Allinone.txt' # Path to your text file
  136. csv_file_path = 'device_data.csv' # Path to your CSV file
  137. # Create an event to stop the wake word detection loop
  138. stop_event = threading.Event()
  139. # Set up signal handler for graceful exit
  140. signal.signal(signal.SIGINT, signal_handler)
  141. # Run wake word detection in a separate thread
  142. wake_word_thread = threading.Thread(target=detect_wake_word, args=(stop_event,))
  143. wake_word_thread.daemon = True
  144. wake_word_thread.start()
  145. # Keep the main thread alive
  146. wake_word_thread.join()