Labtourmode.py 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194
  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. import cv2
  12. from pyzbar.pyzbar import decode
  13. from picamera2 import Picamera2
  14. # Initialize OpenAI API key
  15. api_key = 'sk-proj-wwWaxim1Qt13uqzSS054xjT3BlbkFJK0r78z676Zvx78AJiWG3Ot7d3S'
  16. client = OpenAI(api_key=api_key)
  17. # Global variable to store CSV content
  18. csv_content = ""
  19. def create_messages(question, file_content):
  20. return [
  21. {"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."},
  22. {"role": "user", "content": f"{file_content}\n\nQ: {question}\nA:"}
  23. ]
  24. def play_audio(file_name):
  25. if file_name:
  26. print(f"Playing audio: {file_name}") # Debugging print
  27. pygame.mixer.quit() # Reset the mixer
  28. pygame.mixer.init() # Reinitialize
  29. pygame.mixer.music.load(file_name)
  30. pygame.mixer.music.play()
  31. while pygame.mixer.music.get_busy():
  32. time.sleep(1) # Ensures the program waits until audio finishes
  33. def recognize_speech():
  34. recognizer = sr.Recognizer()
  35. with sr.Microphone() as source:
  36. print("Listening...")
  37. audio = recognizer.listen(source)
  38. try:
  39. print("Recognizing...")
  40. text = recognizer.recognize_google(audio, language='en-US')
  41. audio_files = ["ty.mp3", "th.mp3", "good.mp3", "hmm.mp3"]
  42. random_audio = random.choice(audio_files)
  43. pygame.mixer.music.load(random_audio)
  44. pygame.mixer.music.play()
  45. print(f"You said: {text}")
  46. return text
  47. except sr.UnknownValueError:
  48. print("Sorry, I did not understand that.")
  49. return None
  50. except sr.RequestError:
  51. print("Sorry, there was an error with the speech recognition service.")
  52. return None
  53. def get_response_from_openai(messages):
  54. stream = client.chat.completions.create(
  55. model="gpt-3.5-turbo",
  56. max_tokens=150,
  57. temperature=0.5,
  58. messages=messages,
  59. stream=True,
  60. )
  61. for chunk in stream:
  62. if chunk.choices[0].delta.content is not None:
  63. yield chunk.choices[0].delta.content
  64. def read_file(file_path):
  65. if file_path.endswith('.txt'):
  66. with open(file_path, 'r') as file:
  67. return file.read()
  68. elif file_path.endswith('.csv'):
  69. content = []
  70. with open(file_path, 'r') as file:
  71. reader = csv.reader(file)
  72. for row in reader:
  73. content.append(', '.join(row))
  74. return '\n'.join(content)
  75. else:
  76. raise ValueError("Unsupported file format")
  77. def generate_speech(text):
  78. if text.strip():
  79. spoken_response = client.audio.speech.create(
  80. model="tts-1",
  81. voice="alloy",
  82. input=text
  83. )
  84. buffer = io.BytesIO()
  85. for chunk in spoken_response.iter_bytes(chunk_size=4096):
  86. buffer.write(chunk)
  87. buffer.seek(0)
  88. with sf.SoundFile(buffer, 'r') as sound_file:
  89. data = sound_file.read(dtype='int16')
  90. sd.play(data, sound_file.samplerate)
  91. sd.wait()
  92. def scan_qr_code(image):
  93. """Scans the QR code from the given image and returns the decoded data."""
  94. qr_codes = decode(image)
  95. if qr_codes:
  96. qr_data = qr_codes[0].data.decode('utf-8')
  97. print("QR Code detected:", qr_data)
  98. return qr_data
  99. return None
  100. def start_qa_mode(file_content):
  101. while True:
  102. question = recognize_speech()
  103. 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"]:
  104. pygame.mixer.music.load("give.mp3")
  105. pygame.mixer.music.play()
  106. break
  107. if question:
  108. messages = create_messages(question, file_content)
  109. response_generator = get_response_from_openai(messages)
  110. print("Answer: ", end="")
  111. accumulated_response = ""
  112. for response_chunk in response_generator:
  113. accumulated_response += response_chunk
  114. if '.' in response_chunk or len(accumulated_response) > 300:
  115. print(accumulated_response, end="", flush=True)
  116. generate_speech(accumulated_response)
  117. accumulated_response = ""
  118. if accumulated_response:
  119. print(accumulated_response, end="", flush=True)
  120. generate_speech(accumulated_response)
  121. else:
  122. print("Sorry, I didn't get that. Please ask again.")
  123. def load_csv_content():
  124. global csv_content
  125. csv_file_path = "device_data.csv" # Set your CSV file path here
  126. csv_content = read_file(csv_file_path)
  127. def main():
  128. picam2 = Picamera2()
  129. picam2.start()
  130. text_files = {
  131. "gigabeeprotect": "Gigabeeprotect.txt",
  132. "hydrosense": "Hydrosense.txt",
  133. "pushtotalk": "Pushtotalk.txt",
  134. "rfid": "RFIDautomationenabler.txt",
  135. "smartsanitiser": "smartsanitiserdispenser.txt",
  136. "iotconfigurator": "IoTConfiguratorSolution.txt",
  137. "networkanalyser": "Networkanalyser.txt",
  138. }
  139. audio_files = {
  140. "gigabeeprotect": "Gigabee.mp3",
  141. "hydrosense": "speech1.mp3",
  142. "pushtotalk": "Pushtotalk.mp3",
  143. "rfid": "RFID.mp3",
  144. "smartsanitiser": "smartsanitiser.mp3",
  145. "iotconfigurator": "iotconfig.mp3",
  146. "networkanalyser": "NetworkAnalyser.mp3",
  147. }
  148. load_csv_content()
  149. while True:
  150. # Capture image from camera
  151. image = picam2.capture_array()
  152. # Scan QR code
  153. qr_data = scan_qr_code(image)
  154. if qr_data and qr_data in text_files:
  155. # Play associated audio and load the text file content
  156. play_audio(audio_files[qr_data])
  157. file_content = read_file(text_files[qr_data])
  158. combined_content = file_content + '\n\n' + csv_content # Combine text file content with CSV content
  159. start_qa_mode(combined_content)
  160. cv2.imshow('QR Code Scanner', image)
  161. if cv2.waitKey(1) & 0xFF == ord('q'):
  162. break
  163. picam2.stop()
  164. cv2.destroyAllWindows()
  165. pygame.quit()
  166. if __name__ == "__main__":
  167. main()