checking.py 4.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109
  1. import pygame.mixer as mixer
  2. import speech_recognition as sr
  3. import openai
  4. from pathlib import Path
  5. from openai import OpenAI
  6. import os
  7. import pygame
  8. import mixer
  9. # Set your OpenAI API key here
  10. api_key = 'sk-proj-wwWaxim1Qt13243454353uqzSS0xjT3BlbkFJK0rZvx78AJiWG3Ot7d3S'
  11. client = OpenAI(api_key=api_key)
  12. # Initialize pygame mixer
  13. pygame.mixer.init()
  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. print(f"You said: {text}")
  27. return text
  28. except sr.UnknownValueError:
  29. print("Sorry, I did not understand that.")
  30. return None
  31. except sr.RequestError:
  32. print("Sorry, there was an error with the speech recognition service.")
  33. return None
  34. # Function to get a response from OpenAI
  35. def create_messages(question, file_content):
  36. return [
  37. {"role": "system", "content": "You are a helpful assistant who explains and answers about IoT use cases in Vodafone. Do not say any calculations. Directly say the result"},
  38. {"role": "user", "content": f"{file_content}\n\nQ: {question}\nA:"}
  39. ]
  40. def get_response_from_openai(messages):
  41. response = client.chat.completions.create(
  42. model="gpt-3.5-turbo",
  43. messages=messages,
  44. max_tokens=150,
  45. temperature=0.5,
  46. )
  47. return (response.choices[0].message.content)
  48. # Function to generate speech using OpenAI TTS
  49. def generate_speech(text, file_path):
  50. speech_file_path = Path(file_path).parent / "speech.mp3"
  51. with client.audio.speech.with_streaming_response.create(
  52. model="tts-1", # Replace with your actual model ID
  53. input=text,
  54. voice="alloy" # Replace with a valid voice for your chosen model
  55. ) as response:
  56. response.stream_to_file(str(speech_file_path))
  57. return str(speech_file_path)
  58. # Main function to handle user query
  59. def chatbot(question, file_path):
  60. file_content = read_text_file(file_path)
  61. messages = create_messages(question, file_content)
  62. answer = get_response_from_openai(messages)
  63. return answer
  64. if __name__ == "__main__":
  65. file_path = 'device_data.txt' # Path to your text file
  66. while True:
  67. print("Press Enter to ask a question, or type 'exit' or 'quit' to stop.")
  68. user_input = input("Type 'speak' to ask a question using your voice: ").strip().lower()
  69. if user_input in ['exit', 'quit']:
  70. break
  71. if user_input == 'speak':
  72. question = recognize_speech()
  73. if question:
  74. answer = chatbot(question, file_path)
  75. print("Answer:", answer)
  76. speech_file = generate_speech(answer, file_path)
  77. pygame.mixer.init()
  78. pygame.mixer.music.load(speech_file)
  79. pygame.mixer.music.play()
  80. while pygame.mixer.music.get_busy():
  81. pygame.time.Clock().tick(10) # Adjust as needed
  82. pygame.mixer.music.stop() # Ensure music playback stops
  83. pygame.mixer.quit() # Release resources
  84. os.remove(speech_file)
  85. else:
  86. question = user_input
  87. answer = chatbot(question, file_path)
  88. print("Answer:", answer)
  89. speech_file = generate_speech(answer, file_path)
  90. pygame.mixer.init()
  91. pygame.mixer.music.load(speech_file)
  92. pygame.mixer.music.play()
  93. while pygame.mixer.music.get_busy():
  94. pygame.time.Clock().tick(10) # Adjust as needed
  95. pygame.mixer.music.stop() # Ensure music playback stops
  96. pygame.mixer.quit() # Release resources
  97. os.remove(speech_file)