latestfetch.py 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172
  1. import pygame
  2. import speech_recognition as sr
  3. from openai import OpenAI
  4. from pathlib import Path
  5. import time
  6. import io
  7. import soundfile as sf
  8. import sounddevice as sd
  9. import random
  10. import csv
  11. # Initialize OpenAI API key
  12. api_key = 'sk-proj-wwWaxim1Qt13uqzSS3453450xjT3BlbkFJK0rZvx78AJiWG3Ot7d3S'
  13. client = OpenAI(api_key=api_key)
  14. # Global variable to store CSV content
  15. csv_content = ""
  16. def create_messages(question, file_content):
  17. return [
  18. {"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, and 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 battery level in percentage without decimal values. You should only answer about the loaded text and its associated data. If any questions are asked out of context please say that you will only give answers about this showcase and if you want answers and explanations about other show case please go and scan the qr code and ask relevant questions."},
  19. {"role": "user", "content": f"{file_content}\n\nQ: {question}\nA:"}
  20. ]
  21. def play_audio(num):
  22. audio_files = {
  23. 1: "speech1.mp3",
  24. 2: "hydrosense.mp3",
  25. 3: "Pushtotalk.mp3",
  26. }
  27. audio_file = audio_files.get(num)
  28. if audio_file:
  29. pygame.mixer.init()
  30. pygame.mixer.music.load(audio_file)
  31. pygame.mixer.music.play()
  32. while pygame.mixer.music.get_busy():
  33. time.sleep(1)
  34. def recognize_speech():
  35. recognizer = sr.Recognizer()
  36. with sr.Microphone() as source:
  37. print("Listening...")
  38. audio = recognizer.listen(source)
  39. try:
  40. print("Recognizing...")
  41. text = recognizer.recognize_google(audio, language='en-US')
  42. audio_files = ["ty.mp3", "th.mp3", "good.mp3", "hmm.mp3",]
  43. # Select a random audio file
  44. random_audio = random.choice(audio_files)
  45. # Load and play the selected random audio
  46. pygame.mixer.music.load(random_audio)
  47. pygame.mixer.music.play()
  48. print(f"You said: {text}")
  49. return text
  50. except sr.UnknownValueError:
  51. print("Sorry, I did not understand that.")
  52. return None
  53. except sr.RequestError:
  54. print("Sorry, there was an error with the speech recognition service.")
  55. return None
  56. def get_response_from_openai(messages):
  57. stream = client.chat.completions.create(
  58. model="gpt-4o",
  59. max_tokens=150,
  60. temperature=0.5,
  61. messages=messages,
  62. stream=True,
  63. )
  64. for chunk in stream:
  65. if chunk.choices[0].delta.content is not None:
  66. yield chunk.choices[0].delta.content
  67. def read_file(file_path):
  68. if file_path.endswith('.txt'):
  69. with open(file_path, 'r') as file:
  70. return file.read()
  71. elif file_path.endswith('.csv'):
  72. content = []
  73. with open(file_path, 'r') as file:
  74. reader = csv.reader(file)
  75. for row in reader:
  76. content.append(', '.join(row))
  77. return '\n'.join(content)
  78. else:
  79. raise ValueError("Unsupported file format")
  80. def generate_speech(text):
  81. if text.strip(): # Only generate speech if the text is not empty
  82. spoken_response = client.audio.speech.create(
  83. model="tts-1",
  84. voice="alloy",
  85. input=text
  86. )
  87. buffer = io.BytesIO()
  88. for chunk in spoken_response.iter_bytes(chunk_size=4096):
  89. buffer.write(chunk)
  90. buffer.seek(0)
  91. with sf.SoundFile(buffer, 'r') as sound_file:
  92. data = sound_file.read(dtype='int16')
  93. sd.play(data, sound_file.samplerate)
  94. sd.wait()
  95. def start_qa_mode(file_content):
  96. while True:
  97. question = recognize_speech()
  98. 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"]:
  99. pygame.mixer.music.load("give.mp3")
  100. pygame.mixer.music.play()
  101. break
  102. if question:
  103. messages = create_messages(question, file_content)
  104. response_generator = get_response_from_openai(messages)
  105. print("Answer: ", end="")
  106. accumulated_response = ""
  107. for response_chunk in response_generator:
  108. accumulated_response += response_chunk
  109. if '.' in response_chunk or len(accumulated_response) > 300: # Check for sentence end or length
  110. print(accumulated_response, end="", flush=True)
  111. generate_speech(accumulated_response)
  112. accumulated_response = "" # Reset accumulated response for the next chunk
  113. if accumulated_response: # Generate speech for any remaining text
  114. print(accumulated_response, end="", flush=True)
  115. generate_speech(accumulated_response)
  116. else:
  117. print("Sorry, I didn't get that. Please ask again.")
  118. def user_input():
  119. while True:
  120. try:
  121. num = int(input("Enter a number from 1 to 3: "))
  122. if 1 <= num <= 3:
  123. return num
  124. else:
  125. print("Invalid input. Please enter a number between 1 and 3.")
  126. except ValueError:
  127. print("Invalid input. Please enter a valid integer.")
  128. def load_csv_content():
  129. global csv_content
  130. csv_file_path = "device_data.csv" # Set your CSV file path here
  131. csv_content = read_file(csv_file_path)
  132. def main():
  133. text_files = {
  134. 1: "Gigabeeprotect.txt",
  135. 2: "Hydrosense.txt",
  136. 3: "Pushtotalk.txt",
  137. }
  138. load_csv_content() # Load CSV content once at the beginning
  139. while True:
  140. num = user_input()
  141. play_audio(num)
  142. file_content = read_file(text_files[num])
  143. combined_content = file_content + '\n\n' + csv_content # Combine text file content with CSV content
  144. start_qa_mode(combined_content)
  145. if __name__ == "__main__":
  146. main()