Qrcode.py 4.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150
  1. import pygame
  2. import speech_recognition as sr
  3. import openai
  4. from pathlib import Path
  5. import time
  6. import os
  7. import cv2
  8. from pyzbar import pyzbar
  9. # Initialize OpenAI API key
  10. api_key = 'sk-proj-wwWfffaxim1Qt13uqzS6755567S0xjT3BlbkFJK0rZvx78AJiWG3Ot7d3S'
  11. client = openai.OpenAI(api_key=api_key)
  12. def create_messages(question, file_content):
  13. return [
  14. {"role": "system", "content": "You are a helpful assistant who explains and answers about IoT use cases in Vodafone."},
  15. {"role": "user", "content": f"{file_content}\n\nQ: {question}\nA:"}
  16. ]
  17. def play_audio(num):
  18. audio_files = {
  19. 1: "Gigabee.mp3",
  20. 2: "hydrosense.mp3",
  21. 3: "Pushtotalk.mp3",
  22. }
  23. audio_file = audio_files.get(num)
  24. if audio_file:
  25. pygame.mixer.init()
  26. pygame.mixer.music.load(audio_file)
  27. pygame.mixer.music.play()
  28. while pygame.mixer.music.get_busy():
  29. time.sleep(1)
  30. def recognize_speech():
  31. recognizer = sr.Recognizer()
  32. with sr.Microphone() as source:
  33. print("Listening...")
  34. audio = recognizer.listen(source)
  35. try:
  36. print("Recognizing...")
  37. text = recognizer.recognize_google(audio, language='en-US')
  38. print(f"You said: {text}")
  39. return text
  40. except sr.UnknownValueError:
  41. print("Sorry, I did not understand that.")
  42. return None
  43. except sr.RequestError:
  44. print("Sorry, there was an error with the speech recognition service.")
  45. return None
  46. def get_response_from_openai(messages):
  47. response = client.Completion.create(
  48. model="gpt-3.5-turbo",
  49. messages=messages,
  50. max_tokens=150,
  51. temperature=0.5,
  52. )
  53. return response.choices[0].message['content']
  54. def read_text_file(file_path):
  55. with open(file_path, 'r') as file:
  56. return file.read()
  57. def generate_speech(text, file_path):
  58. speech_file_path = Path(file_path).parent / "speech.mp3"
  59. if speech_file_path.exists():
  60. os.remove(speech_file_path)
  61. with client.Audio.create(
  62. model="tts-1",
  63. input=text,
  64. voice="alloy"
  65. ) as response:
  66. response.stream_to_file(str(speech_file_path))
  67. return str(speech_file_path)
  68. def start_qa_mode(file_content):
  69. while True:
  70. print("Please ask your question:")
  71. question = recognize_speech()
  72. if question and question.lower() in ["no", "next showcase", "exit"]:
  73. break
  74. if question:
  75. messages = create_messages(question, file_content)
  76. answer = get_response_from_openai(messages)
  77. print(f"Answer: {answer}")
  78. speech_file_path = generate_speech(answer, "speech.mp3")
  79. pygame.mixer.init()
  80. pygame.mixer.music.load(speech_file_path)
  81. pygame.mixer.music.play()
  82. while pygame.mixer.music.get_busy():
  83. pygame.time.Clock().tick(10) # Adjust as needed
  84. pygame.mixer.music.stop() # Ensure music playback stops
  85. pygame.mixer.quit() # Release resources
  86. os.remove(speech_file_path)
  87. else:
  88. print("Sorry, I didn't get that. Please ask again.")
  89. def scan_qr_code():
  90. cap = cv2.VideoCapture(0)
  91. while True:
  92. ret, frame = cap.read()
  93. if not ret:
  94. continue
  95. decoded_objects = pyzbar.decode(frame)
  96. for obj in decoded_objects:
  97. qr_data = obj.data.decode('utf-8')
  98. cap.release()
  99. cv2.destroyAllWindows()
  100. return qr_data
  101. cv2.imshow('QR Code Scanner', frame)
  102. if cv2.waitKey(1) & 0xFF == ord('q'):
  103. break
  104. cap.release()
  105. cv2.destroyAllWindows()
  106. return None
  107. def main():
  108. text_files = {
  109. "1": "Gigabeeprotect.txt",
  110. "2": "Hydrosense.txt",
  111. "3": "Pushtotalk.txt",
  112. }
  113. audio_files = {
  114. "1": "Gigabee.mp3",
  115. "2": "hydrosense.mp3",
  116. "3": "Pushtotalk.mp3",
  117. }
  118. while True:
  119. print("Scan a QR code...")
  120. qr_data = scan_qr_code()
  121. if qr_data in text_files:
  122. play_audio(int(qr_data))
  123. file_content = read_text_file(text_files[qr_data])
  124. start_qa_mode(file_content)
  125. else:
  126. print("Invalid QR code. Please try again.")
  127. if __name__ == "__main__":
  128. main()