Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # create a a.i. gf that talks
- # updated from https://www.youtube.com/watch?v=5htSGLCroc8
- import time
- import openai
- from langchain_openai import OpenAI # Updated import for OpenAI
- from langchain_core.prompts import PromptTemplate # Updated import for PromptTemplate
- from langchain.memory import ConversationBufferWindowMemory # Correct memory import
- from langchain.chains import LLMChain # Revert to using LLMChain for correct usage
- from flask import Flask, render_template, request
- from dotenv import find_dotenv, load_dotenv
- import requests
- from playsound import playsound
- import os
- import textwrap # Make sure to import this module
- # Load environment variables
- load_dotenv(find_dotenv())
- ELEVENLABS_API_KEY = os.getenv("ELEVENLABS_API_KEY")
- def get_voice_message(message):
- # Ensure ELEVENLABS_API_KEY is loaded and not None
- if not ELEVENLABS_API_KEY:
- print("Error: ELEVENLABS_API_KEY is not set. Please check your environment variables.")
- return None
- # Split the message into smaller chunks, each with a maximum length of 5000 characters
- message_chunks = textwrap.wrap(message, 5000)
- for chunk_index, chunk in enumerate(message_chunks):
- payload = {
- "text": chunk,
- "model_id": "eleven_monolingual_v1",
- "voice_settings": {
- "stability": 0,
- "similarity_boost": 0
- }
- }
- headers = {
- 'accept': 'audio/mpeg',
- 'xi-api-key': ELEVENLABS_API_KEY,
- 'Content-Type': 'application/json'
- }
- # Make the POST request to ElevenLabs API
- # voice id: 21m00Tcm4TlvDq8ikWAM
- # you can get voice id's from here: https://api.elevenlabs.io/v1/voices
- response = requests.post('https://api.elevenlabs.io/v1/text-to-speech/21m00Tcm4TlvDq8ikWAM/stream', json=payload, headers=headers)
- if response.status_code == 200 and response.content:
- # Save each chunk's audio with a unique name
- audio_file = f'audio_chunk_{chunk_index}.mp3'
- with open(audio_file, 'wb') as f:
- f.write(response.content)
- playsound(audio_file)
- os.remove(audio_file) # Clean up after playing
- else:
- print(f"Error with ElevenLabs API: {response.status_code}, {response.text}")
- return None
- def get_response_from_ai(human_input, max_retries=5):
- template = """
- put your descriptions here
- {history}
- boyfriend: {human_input}
- girlfriend:
- """
- prompt = PromptTemplate(
- input_variables=["history", "human_input"],
- template=template
- )
- # Initialize memory with the conversation history
- memory = ConversationBufferWindowMemory(k=2)
- llm = OpenAI(temperature=0.2, max_tokens=100)
- chatgpt_chain = LLMChain(
- llm=llm,
- prompt=prompt,
- memory=memory, # Pass memory directly into LLMChain
- verbose=True
- )
- retries = 0
- while retries < max_retries:
- try:
- output = chatgpt_chain.predict(human_input=human_input)
- response_message = output.split("Brig-id:")[-1].strip() # Only return the response after "Brig-id:"
- # Call the get_voice_message function to play the response as speech
- get_voice_message(response_message)
- return response_message
- except openai.error.RateLimitError:
- retries += 1
- wait_time = 2 ** retries # Exponential backoff
- print(f"Rate limit exceeded. Retrying in {wait_time} seconds...")
- time.sleep(wait_time)
- except Exception as e:
- print(f"An unexpected error occurred: {e}")
- break
- raise Exception("API call failed after maximum retries")
- # Build web GUI using Flask
- app = Flask(__name__)
- @app.route("/")
- def home():
- return render_template("index.html")
- @app.route('/send_message', methods=['POST'])
- def send_message():
- human_input = request.form['human_input']
- # Retrieve max_retries from the form, with a default value of 5 if not provided
- max_retries = request.form.get('max_retries', default=5, type=int)
- # Call the function with the human_input and max_retries
- message = get_response_from_ai(human_input, max_retries=max_retries)
- return message
- if __name__ == "__main__":
- app.run(debug=True)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement