General.py 4.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112
  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. pygame.mixer.init()
  11. # Set your OpenAI API key here
  12. api_key = 'sk-proj-wwWrdrtzhuaxim1Qt13uqzSS0xjT3BlbkFJK0rZvx78AJiWG3Ot7d3S'
  13. client = OpenAI(api_key=api_key)
  14. def read_text_file(file_path):
  15. with open(file_path, 'r', encoding='utf-8') as file:
  16. return file.read()
  17. # Function to recognize speech from the microphone
  18. def recognize_speech():
  19. recognizer = sr.Recognizer()
  20. with sr.Microphone() as source:
  21. print("Listening...")
  22. audio = recognizer.listen(source)
  23. try:
  24. print("Recognizing...")
  25. text = recognizer.recognize_google(audio, language='en-US')
  26. audio_files = ["ty.mp3", "th.mp3", "sure.mp3", "sure1.mp3"]
  27. # Select a random audio file
  28. random_audio = random.choice(audio_files)
  29. # Load and play the selected random audio
  30. pygame.mixer.music.load(random_audio)
  31. pygame.mixer.music.play()
  32. print(f"You said: {text}")
  33. return text
  34. except sr.UnknownValueError:
  35. print("Sorry, I did not understand that.")
  36. return None
  37. except sr.RequestError:
  38. print("Sorry, there was an error with the speech recognition service.")
  39. return None
  40. # Function to create messages for OpenAI API
  41. def create_messages(question, file_content):
  42. return [
  43. {"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, 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. "},
  44. {"role": "user", "content": f"{file_content}\n\nQ: {question}\nA:"}
  45. ]
  46. # Function to get a response from OpenAI
  47. def get_response_from_openai(messages):
  48. stream = client.chat.completions.create(
  49. model="gpt-4o",
  50. max_tokens=150,
  51. temperature=0.5,
  52. messages=messages,
  53. stream=True,
  54. )
  55. for chunk in stream:
  56. if chunk.choices[0].delta.content is not None:
  57. yield chunk.choices[0].delta.content
  58. # Function to generate and play speech in chunks
  59. def generate_speech(text):
  60. if text.strip(): # Only generate speech if the text is not empty
  61. spoken_response = client.audio.speech.create(
  62. model="tts-1",
  63. voice="alloy",
  64. input=text
  65. )
  66. buffer = io.BytesIO()
  67. for chunk in spoken_response.iter_bytes(chunk_size=4096):
  68. buffer.write(chunk)
  69. buffer.seek(0)
  70. with sf.SoundFile(buffer, 'r') as sound_file:
  71. data = sound_file.read(dtype='int16')
  72. sd.play(data, sound_file.samplerate)
  73. sd.wait()
  74. # Main function to handle user query
  75. def chatbot(question, file_path):
  76. file_content = read_text_file(file_path)
  77. messages = create_messages(question, file_content)
  78. response_generator = get_response_from_openai(messages)
  79. print("Answer: ", end="")
  80. accumulated_response = ""
  81. for response_chunk in response_generator:
  82. accumulated_response += response_chunk
  83. if '.' in response_chunk or len(accumulated_response) > 500: # Check for sentence end or length
  84. print(accumulated_response, end="", flush=True)
  85. generate_speech(accumulated_response)
  86. accumulated_response = "" # Reset accumulated response for the next chunk
  87. if accumulated_response: # Generate speech for any remaining text
  88. print(accumulated_response, end="", flush=True)
  89. generate_speech(accumulated_response)
  90. if __name__ == "__main__":
  91. file_path = 'Allinone.txt' # Path to your text file
  92. while True:
  93. question = recognize_speech()
  94. if question:
  95. chatbot(question, file_path)
  96. else:
  97. print("Sorry, I didn't get that. Please ask again.")