generalnew.py 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136
  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. pygame.mixer.init()
  12. # Set your OpenAI API key here
  13. api_key = 'sk-proj-wwWaxim1Qt765575656913uqz8SS0xjT3BlbkFJK0rZvx78AJiWG3Ot7d3S'
  14. client = OpenAI(api_key=api_key)
  15. # Function to read text file
  16. def read_text_file(file_path):
  17. with open(file_path, 'r', encoding='utf-8') as file:
  18. return file.read()
  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 microphone
  31. import speech_recognition as sr
  32. import pygame
  33. import random
  34. def recognize_speech():
  35. recognizer = sr.Recognizer()
  36. with sr.Microphone() as source:
  37. # Adjust for ambient noise to improve recognition accuracy
  38. recognizer.adjust_for_ambient_noise(source)
  39. print("Listening...")
  40. audio = recognizer.listen(source) # Timeout set to 5 seconds
  41. try:
  42. print("Recognizing...")
  43. text = recognizer.recognize_google(audio, language='en-US')
  44. # Play a random audio file
  45. audio_files = ["ty.mp3", "th.mp3", "sure.mp3", "sure1.mp3"]
  46. random_audio = random.choice(audio_files)
  47. pygame.mixer.music.load(random_audio)
  48. pygame.mixer.music.play()
  49. print(f"You said: {text}")
  50. return text
  51. except sr.UnknownValueError:
  52. print("Sorry, I did not understand that.")
  53. return None
  54. except sr.RequestError:
  55. print("Sorry, there was an error with the speech recognition service.")
  56. return None
  57. # Function to create messages for OpenAI API
  58. def create_messages(question, file_content):
  59. return [
  60. {"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 battery level in percentage without decimal values."},
  61. {"role": "user", "content": f"{file_content}\n\nQ: {question}\nA:"}
  62. ]
  63. # Function to get a response from OpenAI
  64. def get_response_from_openai(messages):
  65. stream = client.chat.completions.create(
  66. model="gpt-3.5-turbo",
  67. max_tokens=150,
  68. temperature=0.5,
  69. messages=messages,
  70. stream=True,
  71. )
  72. for chunk in stream:
  73. if chunk.choices[0].delta.content is not None:
  74. yield chunk.choices[0].delta.content
  75. # Function to generate and play speech in chunks
  76. def generate_speech(text):
  77. if text.strip(): # Only generate speech if the text is not empty
  78. spoken_response = client.audio.speech.create(
  79. model="tts-1",
  80. voice="alloy",
  81. input=text
  82. )
  83. buffer = io.BytesIO()
  84. for chunk in spoken_response.iter_bytes(chunk_size=4096):
  85. buffer.write(chunk)
  86. buffer.seek(0)
  87. with sf.SoundFile(buffer, 'r') as sound_file:
  88. data = sound_file.read(dtype='int16')
  89. sd.play(data, sound_file.samplerate)
  90. sd.wait()
  91. # Main function to handle user query
  92. def chatbot(question, text_file_path, csv_file_path):
  93. text_content = read_text_file(text_file_path)
  94. csv_content = read_csv_file(csv_file_path)
  95. combined_content = text_content + ' ' + csv_content
  96. messages = create_messages(question, combined_content)
  97. response_generator = get_response_from_openai(messages)
  98. print("Answer: ", end="")
  99. accumulated_response = ""
  100. for response_chunk in response_generator:
  101. accumulated_response += response_chunk
  102. if '.' in response_chunk or len(accumulated_response) > 300: # Check for sentence end or length
  103. print(accumulated_response, end="", flush=True)
  104. generate_speech(accumulated_response)
  105. accumulated_response = "" # Reset accumulated response for the next chunk
  106. if accumulated_response: # Generate speech for any remaining text
  107. print(accumulated_response, end="", flush=True)
  108. generate_speech(accumulated_response)
  109. if __name__ == "__main__":
  110. text_file_path = 'Allinone.txt' # Path to your text file
  111. csv_file_path = 'device_data.csv' # Path to your CSV file
  112. while True:
  113. question = recognize_speech()
  114. if question:
  115. chatbot(question, text_file_path, csv_file_path)
  116. else:
  117. print("Sorry, I didn't get that. Please ask again.")