hm.py 3.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127
  1. import pygame
  2. import speech_recognition as sr
  3. from openai import OpenAI
  4. from pathlib import Path
  5. import time
  6. import os
  7. import io
  8. import soundfile as sf
  9. import sounddevice as sd
  10. # Initialize OpenAI API key
  11. api_key = 'sk-proj-wwWaxim1Qt13uqzSS0xjT3BlbkFJK0rZvx78AJiWG3Ot7d3S'
  12. client = OpenAI(api_key=api_key)
  13. def create_messages(question, file_content):
  14. return [
  15. {"role": "system", "content": "You are a helpful assistant who explains and answers about IoT use cases in Vodafone."},
  16. {"role": "user", "content": f"{file_content}\n\nQ: {question}\nA:"}
  17. ]
  18. def play_audio(num):
  19. audio_files = {
  20. 1: "speech1.mp3",
  21. 2: "hydrosense.mp3",
  22. 3: "Pushtotalk.mp3",
  23. }
  24. audio_file = audio_files.get(num)
  25. if audio_file:
  26. pygame.mixer.init()
  27. pygame.mixer.music.load(audio_file)
  28. pygame.mixer.music.play()
  29. while pygame.mixer.music.get_busy():
  30. time.sleep(1)
  31. def recognize_speech():
  32. recognizer = sr.Recognizer()
  33. with sr.Microphone() as source:
  34. print("Listening...")
  35. audio = recognizer.listen(source)
  36. try:
  37. print("Recognizing...")
  38. text = recognizer.recognize_google(audio, language='en-US')
  39. print(f"You said: {text}")
  40. return text
  41. except sr.UnknownValueError:
  42. print("Sorry, I did not understand that.")
  43. return None
  44. except sr.RequestError:
  45. print("Sorry, there was an error with the speech recognition service.")
  46. return None
  47. def get_response_from_openai(messages):
  48. response = client.chat.completions.create(
  49. model="gpt-3.5-turbo",
  50. messages=messages,
  51. max_tokens=150,
  52. temperature=0.5,
  53. )
  54. return (response.choices[0].message.content)
  55. def read_text_file(file_path):
  56. with open(file_path, 'r') as file:
  57. return file.read()
  58. def generate_speech(text):
  59. spoken_response = client.audio.speech.create(
  60. model="tts-1",
  61. voice="alloy",
  62. response_format="opus",
  63. input=text
  64. )
  65. buffer = io.BytesIO()
  66. for chunk in spoken_response.iter_bytes(chunk_size=4096):
  67. buffer.write(chunk)
  68. buffer.seek(0)
  69. with sf.SoundFile(buffer, 'r') as sound_file:
  70. data = sound_file.read(dtype='int16')
  71. sd.play(data, sound_file.samplerate)
  72. sd.wait()
  73. def start_qa_mode(file_content):
  74. while True:
  75. print("Please ask your question:")
  76. question = recognize_speech()
  77. if question and question.lower() in ["no", "go to next showcase", "exit"]:
  78. break
  79. if question:
  80. messages = create_messages(question, file_content)
  81. answer = get_response_from_openai(messages)
  82. print(f"Answer: {answer}")
  83. generate_speech(answer)
  84. else:
  85. print("Sorry, I didn't get that. Please ask again.")
  86. def user_input():
  87. while True:
  88. try:
  89. num = int(input("Enter a number from 1 to 3: "))
  90. if 1 <= num <= 3:
  91. return num
  92. else:
  93. print("Invalid input. Please enter a number between 1 and 3.")
  94. except ValueError:
  95. print("Invalid input. Please enter a valid integer.")
  96. def main():
  97. text_files = {
  98. 1: "Gigabeeprotect.txt",
  99. 2: "Hydrosense.txt",
  100. 3: "Pushtotalk.txt",
  101. }
  102. while True:
  103. num = user_input()
  104. play_audio(num)
  105. file_content = read_text_file(text_files[num])
  106. start_qa_mode(file_content)
  107. if __name__ == "__main__":
  108. main()