newcache.py 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187
  1. import pygame
  2. import speech_recognition as sr
  3. from openai import OpenAI
  4. from pathlib import Path
  5. import os
  6. import io
  7. import soundfile as sf
  8. import sounddevice as sd
  9. import random
  10. import csv
  11. # Initialize Pygame mixer for audio playback
  12. pygame.mixer.init()
  13. # Set your OpenAI API key here
  14. api_key = 'sk-proj-wwWaxim1Qt13uqzSS6660xjT3BlbkFJK0rZvx78AJiWG3Ot7d3S' # Replace with your actual OpenAI API key
  15. client = OpenAI(api_key=api_key)
  16. # Cache for content and previous responses
  17. content_cache = {}
  18. response_cache = {}
  19. # Function to read text file
  20. def read_text_file(file_path):
  21. try:
  22. with open(file_path, 'r', encoding='utf-8') as file:
  23. return file.read()
  24. except Exception as e:
  25. print(f"Error reading text file: {e}")
  26. return ""
  27. # Function to read CSV file
  28. def read_csv_file(file_path):
  29. content = ""
  30. try:
  31. with open(file_path, mode='r', encoding='utf-8') as file:
  32. reader = csv.reader(file)
  33. for row in reader:
  34. content += ' '.join(row) + ' '
  35. except Exception as e:
  36. print(f"Error reading CSV file: {e}")
  37. return content
  38. # Function to recognize speech from the microphone
  39. def recognize_speech():
  40. recognizer = sr.Recognizer()
  41. with sr.Microphone() as source:
  42. print("Listening...")
  43. audio = recognizer.listen(source)
  44. try:
  45. print("Recognizing...")
  46. text = recognizer.recognize_google(audio, language='en-US')
  47. # Play a random audio response
  48. random_audio = random.choice(["ty.mp3", "th.mp3", "sure.mp3", "sure1.mp3"])
  49. pygame.mixer.music.load(random_audio)
  50. pygame.mixer.music.play()
  51. print(f"You said: {text}")
  52. return text
  53. except sr.UnknownValueError:
  54. print("Sorry, I did not understand that.")
  55. return None
  56. except sr.RequestError:
  57. print("Sorry, there was an error with the speech recognition service.")
  58. return None
  59. # Function to create messages for OpenAI API
  60. def create_messages(question, file_content):
  61. return [
  62. {"role": "system", "content": "Your name is Futurebot..."},
  63. {"role": "user", "content": f"{file_content}\n\nQ: {question}\nA:"}
  64. ]
  65. # Function to get a response from OpenAI
  66. def get_response_from_openai(messages):
  67. stream = client.chat.completions.create(
  68. model="gpt-3.5-turbo",
  69. max_tokens=150,
  70. temperature=0.5,
  71. messages=messages,
  72. stream=True,
  73. )
  74. for chunk in stream:
  75. yield chunk
  76. # Function to generate and play speech in chunks
  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. # Function to load files once at startup
  93. def load_files_once(text_file_path, csv_file_path):
  94. text_content = read_text_file(text_file_path)
  95. csv_content = read_csv_file(csv_file_path)
  96. return text_content + ' ' + csv_content
  97. # Function to reload files if they have been modified since the last load
  98. def load_files_if_updated(text_file_path, csv_file_path, last_mod_time):
  99. text_mod_time = os.path.getmtime(text_file_path)
  100. csv_mod_time = os.path.getmtime(csv_file_path)
  101. if text_mod_time > last_mod_time['text'] or csv_mod_time > last_mod_time['csv']:
  102. print("Files updated, reloading...")
  103. last_mod_time['text'] = text_mod_time
  104. last_mod_time['csv'] = csv_mod_time
  105. return read_text_file(text_file_path) + ' ' + read_csv_file(csv_file_path)
  106. return None # No update
  107. # Function to cache and retrieve responses
  108. def get_cached_response(question, combined_content):
  109. # Generate a unique key based on question and content
  110. cache_key = (question, combined_content)
  111. # Check if the response is already cached
  112. if cache_key in response_cache:
  113. print("Using cached response")
  114. return response_cache[cache_key]
  115. # Otherwise, generate a new response
  116. messages = create_messages(question, combined_content)
  117. response_generator = get_response_from_openai(messages)
  118. accumulated_response = ""
  119. # Process the response chunk by chunk
  120. for response_chunk in response_generator:
  121. chunk_content = response_chunk.choices[0].delta.content if response_chunk.choices else None
  122. # Check if chunk_content is not None
  123. if chunk_content:
  124. accumulated_response += chunk_content
  125. # Check for sentence end or length
  126. if '.' in chunk_content or len(accumulated_response) > 600:
  127. print(accumulated_response, end="", flush=True)
  128. generate_speech(accumulated_response)
  129. accumulated_response = "" # Reset accumulated response for the next chunk
  130. if accumulated_response: # Generate speech for any remaining text
  131. print(accumulated_response, end="", flush=True)
  132. generate_speech(accumulated_response)
  133. # Cache the response for future use
  134. response_cache[cache_key] = accumulated_response
  135. return accumulated_response
  136. # Main function to handle user query
  137. def chatbot(question, combined_content):
  138. response = get_cached_response(question, combined_content)
  139. print("Answer: ", response)
  140. generate_speech(response)
  141. if __name__ == "__main__":
  142. text_file_path = 'Allinone.txt' # Path to your text file
  143. csv_file_path = 'device_data.csv' # Path to your CSV file
  144. # Load the files once at startup
  145. last_mod_time = {'text': 0, 'csv': 0}
  146. combined_content = load_files_once(text_file_path, csv_file_path)
  147. last_mod_time['text'] = os.path.getmtime(text_file_path)
  148. last_mod_time['csv'] = os.path.getmtime(csv_file_path)
  149. # Main loop
  150. while True:
  151. question = recognize_speech()
  152. if question:
  153. # Check if files have been updated, and reload if necessary
  154. updated_content = load_files_if_updated(text_file_path, csv_file_path, last_mod_time)
  155. if updated_content:
  156. combined_content = updated_content
  157. # Call the chatbot with the current content
  158. chatbot(question, combined_content)
  159. else:
  160. print("Sorry, I didn't get that. Please ask again.")