nao.py 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126
  1. import speech_recognition as sr
  2. from openai import OpenAI
  3. import csv
  4. import requests
  5. # Set your OpenAI API key here
  6. api_key = 'sk-proj-wwWaxim176667Qt13uqzSS0xjT7773BlbkFJK0rZvx78AJiWG3Ot7d3S'
  7. client = OpenAI(api_key=api_key)
  8. # NAO's IP address and port where the server is running
  9. nao_ip = "10.2.100.246"
  10. nao_port = 8080
  11. # Function to read text file
  12. def read_text_file(file_path):
  13. try:
  14. with open(file_path, 'r', encoding='utf-8') as file:
  15. return file.read()
  16. except IOError as e:
  17. print(f"Error reading text file: {e}")
  18. return ""
  19. # Function to read CSV file
  20. def read_csv_file(file_path):
  21. content = ""
  22. try:
  23. with open(file_path, mode='r', encoding='utf-8') as file:
  24. reader = csv.reader(file)
  25. for row in reader:
  26. content += ' '.join(row) + ' '
  27. except Exception as e:
  28. print(f"Error reading CSV file: {e}")
  29. return content
  30. # Function to recognize speech from the Raspberry Pi microphone
  31. def recognize_speech():
  32. recognizer = sr.Recognizer()
  33. with sr.Microphone() as source:
  34. # Adjust for ambient noise to improve recognition accuracy
  35. recognizer.adjust_for_ambient_noise(source)
  36. print("Listening...")
  37. try:
  38. audio = recognizer.listen(source, timeout=5) # Timeout set to 5 seconds
  39. print("Recognizing...")
  40. text = recognizer.recognize_google(audio, language='en-EN')
  41. print(f"You said: {text}")
  42. return text
  43. except sr.UnknownValueError:
  44. print("Sorry, I did not understand that.")
  45. return None
  46. except sr.RequestError:
  47. print("Sorry, there was an error with the speech recognition service.")
  48. return None
  49. except sr.WaitTimeoutError:
  50. print("Listening timed out.")
  51. return None
  52. # Function to create messages for OpenAI API
  53. def create_messages(question, file_content):
  54. return [
  55. {"role": "system", "content": "Your name is Nao. 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 battery level in percentage without decimal values."},
  56. {"role": "user", "content": f"{file_content}\n\nQ: {question}\nA:"}
  57. ]
  58. # Function to get a response from OpenAI
  59. def get_response_from_openai(messages):
  60. try:
  61. stream = client.chat.completions.create(
  62. model="gpt-3.5-turbo",
  63. max_tokens=150,
  64. temperature=0.5,
  65. messages=messages,
  66. stream=True,
  67. )
  68. for chunk in stream:
  69. if chunk.choices[0].delta.content is not None:
  70. yield chunk.choices[0].delta.content
  71. except Exception as e:
  72. print(f"Error getting response from OpenAI: {e}")
  73. # Function to send the generated response to NAO for speaking via HTTP
  74. def send_to_nao(text):
  75. if text.strip(): # Only send non-empty text
  76. url = f"http://{nao_ip}:{nao_port}" # NAO's IP and port
  77. try:
  78. response = requests.post(url, data=text.encode('utf-8'))
  79. if response.status_code == 200:
  80. print("NAO successfully received the message and spoke it.")
  81. else:
  82. print(f"Error: Received status code {response.status_code} from NAO.")
  83. except requests.ConnectionError:
  84. print("Failed to connect to NAO.")
  85. except requests.RequestException as e:
  86. print(f"Request error: {e}")
  87. # Main function to handle user query
  88. def chatbot(question, text_file_path, csv_file_path):
  89. text_content = read_text_file(text_file_path)
  90. csv_content = read_csv_file(csv_file_path)
  91. combined_content = text_content + ' ' + csv_content
  92. messages = create_messages(question, combined_content)
  93. response_generator = get_response_from_openai(messages)
  94. print("Answer: ", end="")
  95. accumulated_response = ""
  96. for response_chunk in response_generator:
  97. accumulated_response += response_chunk
  98. if '.' in response_chunk or len(accumulated_response) > 300: # Check for sentence end or length
  99. print(accumulated_response, end="", flush=True)
  100. send_to_nao(accumulated_response)
  101. accumulated_response = "" # Reset accumulated response for the next chunk
  102. if accumulated_response: # Send remaining text to NAO
  103. print(accumulated_response, end="", flush=True)
  104. send_to_nao(accumulated_response)
  105. if __name__ == "__main__":
  106. text_file_path = 'Allinone.txt' # Path to your text file
  107. csv_file_path = 'device_data.csv' # Path to your CSV file
  108. while True:
  109. question = recognize_speech()
  110. if question:
  111. chatbot(question, text_file_path, csv_file_path)
  112. else:
  113. print("Sorry, I didn't get that. Please ask again.")