Full2.py 3.9 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. # Initialize OpenAI API key
  8. api_key = 'sk-proj-wwWaxim1Qt13uq45e45rtfgzSS0xjT3BlbkFJK0rZvx78AJiWG3Ot7d3S'
  9. client = OpenAI(api_key=api_key)
  10. def create_messages(question, file_content):
  11. return [
  12. {"role": "system", "content": "You are a tour guide who explains and answers about IoT use cases in Vodafone."},
  13. {"role": "user", "content": f"{file_content}\n\nQ: {question}\nA:"}
  14. ]
  15. def user_input():
  16. while True:
  17. try:
  18. num = int(input("Enter a number from 1 to 3: "))
  19. if 1 <= num <= 3:
  20. return num
  21. else:
  22. print("Invalid input. Please enter a number between 1 and 3.")
  23. except ValueError:
  24. print("Invalid input. Please enter a valid integer.")
  25. def play_audio(num):
  26. audio_files = {
  27. 1: "speech1.mp3",
  28. 2: "hydrosense.mp3",
  29. 3: "Pushtotalk.mp3",
  30. }
  31. audio_file = audio_files.get(num)
  32. if audio_file:
  33. pygame.mixer.init()
  34. pygame.mixer.music.load(audio_file)
  35. pygame.mixer.music.play()
  36. while pygame.mixer.music.get_busy():
  37. time.sleep(1)
  38. def recognize_speech():
  39. recognizer = sr.Recognizer()
  40. with sr.Microphone() as source:
  41. print("Listening...")
  42. audio = recognizer.listen(source)
  43. try:
  44. print("Recognizing...")
  45. text = recognizer.recognize_google(audio, language='en-US')
  46. print(f"You said: {text}")
  47. return text
  48. except sr.UnknownValueError:
  49. print("Sorry, I did not understand that.")
  50. return None
  51. except sr.RequestError:
  52. print("Sorry, there was an error with the speech recognition service.")
  53. return None
  54. def get_response_from_openai(messages):
  55. response = client.chat.completions.create(
  56. model="gpt-4o",
  57. messages=messages,
  58. max_tokens=75,
  59. temperature=0.5,
  60. )
  61. return (response.choices[0].message.content)
  62. def read_text_file(file_path):
  63. with open(file_path, 'r') as file:
  64. return file.read()
  65. def generate_speech(text, file_path):
  66. speech_file_path = Path(file_path).parent / "speech.mp3"
  67. with client.audio.speech.with_streaming_response.create(
  68. model="tts-1", # Replace with your actual model ID
  69. input=text,
  70. voice="alloy" # Replace with a valid voice for your chosen model
  71. ) as response:
  72. response.stream_to_file(str(speech_file_path))
  73. return str(speech_file_path)
  74. def start_qa_mode(file_content):
  75. while True:
  76. print("Please ask your question:")
  77. question = recognize_speech()
  78. if question and question.lower() in ["no", "go to next showcase", "exit"]:
  79. break
  80. if question:
  81. messages = create_messages(question, file_content)
  82. answer = get_response_from_openai(messages)
  83. print(f"Answer: {answer}")
  84. speech_file_path = generate_speech(answer, "speech.mp3")
  85. pygame.mixer.init()
  86. pygame.mixer.music.load(speech_file_path)
  87. pygame.mixer.music.play()
  88. while pygame.mixer.music.get_busy():
  89. pygame.time.Clock().tick(10) # Adjust as needed
  90. pygame.mixer.music.stop() # Ensure music playback stops
  91. pygame.mixer.quit() # Release resources
  92. os.remove(speech_file_path)
  93. else:
  94. print("Sorry, I didn't get that. Please ask again.")
  95. def main():
  96. while True:
  97. num = user_input()
  98. play_audio(num)
  99. text_files = {
  100. 1: "Gigabeeprotect.txt",
  101. 2: "Hydrosense.txt",
  102. 3: "Pushtotalk.txt",
  103. }
  104. text_file = text_files.get(num)
  105. if text_file:
  106. file_content = read_text_file(text_file)
  107. start_qa_mode(file_content)
  108. if __name__ == "__main__":
  109. main()