nokam.py 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153
  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. import random
  11. # Initialize OpenAI API key
  12. api_key = 'sk-proj-435frgerrwwWaxim1Qt13uqzSS0xjT3BlbkFJK0rZvx78AJiWG3Ot7d3S'
  13. client = OpenAI(api_key=api_key)
  14. def create_messages(question, file_content):
  15. return [
  16. {"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 sentences and answer in few lines. Do not say greetings"},
  17. {"role": "user", "content": f"{file_content}\n\nQ: {question}\nA:"}
  18. ]
  19. def play_audio(num):
  20. audio_files = {
  21. 1: "speech1.mp3",
  22. 2: "hydrosense.mp3",
  23. 3: "Pushtotalk.mp3",
  24. }
  25. audio_file = audio_files.get(num)
  26. if audio_file:
  27. pygame.mixer.init()
  28. pygame.mixer.music.load(audio_file)
  29. pygame.mixer.music.play()
  30. while pygame.mixer.music.get_busy():
  31. time.sleep(1)
  32. def recognize_speech():
  33. recognizer = sr.Recognizer()
  34. with sr.Microphone() as source:
  35. print("Listening...")
  36. audio = recognizer.listen(source)
  37. try:
  38. print("Recognizing...")
  39. text = recognizer.recognize_google(audio, language='en-US')
  40. audio_files = ["ty.mp3", "th.mp3", "good.mp3", "hmm.mp3", "haha.mp3"]
  41. # Select a random audio file
  42. random_audio = random.choice(audio_files)
  43. # Load and play the selected random audio
  44. pygame.mixer.music.load(random_audio)
  45. pygame.mixer.music.play()
  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. stream = client.chat.completions.create(
  56. model="gpt-4o",
  57. max_tokens=150,
  58. temperature=0.5,
  59. messages=messages,
  60. stream=True,
  61. )
  62. for chunk in stream:
  63. if chunk.choices[0].delta.content is not None:
  64. yield chunk.choices[0].delta.content
  65. def read_text_file(file_path):
  66. with open(file_path, 'r') as file:
  67. return file.read()
  68. def generate_speech(text):
  69. if text.strip(): # Only generate speech if the text is not empty
  70. spoken_response = client.audio.speech.create(
  71. model="tts-1",
  72. voice="alloy",
  73. input=text
  74. )
  75. buffer = io.BytesIO()
  76. for chunk in spoken_response.iter_bytes(chunk_size=4096):
  77. buffer.write(chunk)
  78. buffer.seek(0)
  79. with sf.SoundFile(buffer, 'r') as sound_file:
  80. data = sound_file.read(dtype='int16')
  81. sd.play(data, sound_file.samplerate)
  82. sd.wait()
  83. def start_qa_mode(file_content):
  84. while True:
  85. question = recognize_speech()
  86. if question and question.lower() in ["no", "go to the next showcase", "exit", "i don't have any questions", "i have no questions", "i don't have any other questions", "I don't have any other questions", "thats it"]:
  87. pygame.mixer.music.load("give.mp3")
  88. pygame.mixer.music.play()
  89. break
  90. if question:
  91. messages = create_messages(question, file_content)
  92. response_generator = get_response_from_openai(messages)
  93. print("Answer: ", end="")
  94. accumulated_response = ""
  95. for response_chunk in response_generator:
  96. accumulated_response += response_chunk
  97. if '.' in response_chunk or len(accumulated_response) > 500: # Check for sentence end or length
  98. print(accumulated_response, end="", flush=True)
  99. generate_speech(accumulated_response)
  100. accumulated_response = "" # Reset accumulated response for the next chunk
  101. if accumulated_response: # Generate speech for any remaining text
  102. print(accumulated_response, end="", flush=True)
  103. generate_speech(accumulated_response)
  104. else:
  105. print("Sorry, I didn't get that. Please ask again.")
  106. def user_input():
  107. while True:
  108. try:
  109. num = int(input("Enter a number from 1 to 3: "))
  110. if 1 <= num <= 3:
  111. return num
  112. else:
  113. print("Invalid input. Please enter a number between 1 and 3.")
  114. except ValueError:
  115. print("Invalid input. Please enter a valid integer.")
  116. def main():
  117. text_files = {
  118. 1: "Gigabeeprotect.txt",
  119. 2: "Hydrosense.txt",
  120. 3: "Pushtotalk.txt",
  121. }
  122. while True:
  123. num = user_input()
  124. play_audio(num)
  125. file_content = read_text_file(text_files[num])
  126. start_qa_mode(file_content)
  127. if __name__ == "__main__":
  128. main()