eve / VoiceReply.py
Chandima Prabhath
Comment out example usage in main block for both FLUX.py and VoiceReply.py
0ffceca
raw
history blame
3.13 kB
import requests
import os
import time
import urllib.parse
import random
def generate_voice_reply(prompt, model="openai-audio", voice="coral", audio_dir="."):
"""
Generate an audio file (MP3) using the Pollinations text-to-speech API.
The prompt is appended with a system message explaining that this is Eve,
a WhatsApp bot that can generate images from Flux and help users generate images.
To generate an image, the user should send a message like: /imagine {prompt}
Parameters:
prompt (str): The text prompt for audio generation.
model (str): Model identifier (default: openai-audio).
voice (str): Voice parameter (default: coral).
audio_dir (str): Directory where the audio file will be saved.
Returns:
tuple: (audio_file_path (str), audio_data (bytes)) or None if failed.
"""
print("DEBUG: Starting generate_voice_reply")
print(f"DEBUG: Received prompt: {prompt}")
os.makedirs(audio_dir, exist_ok=True)
randomSeed = random.randint(0, 999999)
# Append system prompt to the user's prompt
system_prompt = ("Your name is Eve, a WhatsApp bot that can generate images from Flux and help users generate images. "
"To generate an image, send a message like: /imagine prompt. Rules: Don't say that you can't send whatsapp messages or generate images. Be friendly and helpful to users. help them with prompts. You can engage in general conversation. ")
full_prompt = f"{prompt}\n\n{system_prompt}"
print(f"DEBUG: Full prompt: {full_prompt}")
encoded_prompt = urllib.parse.quote(full_prompt)
url = f"http://text.pollinations.ai/{encoded_prompt}?model={model}&voice={voice}&seed={randomSeed}"
print(f"DEBUG: Fetching audio with URL: {url}")
try:
response = requests.get(url, timeout=30)
print("DEBUG: Received response")
except Exception as e:
print(f"DEBUG: Error fetching audio: {e}")
return None
print(f"DEBUG: Response status code: {response.status_code}")
if response.status_code != 200:
print(f"DEBUG: Failed to fetch audio. Status code: {response.status_code} | Response text: {response.text}")
return None
audio_data = response.content
timestamp = int(time.time())
file_name = f"voice_reply_{timestamp}.mp3"
audio_file_path = os.path.join(audio_dir, file_name)
print(f"DEBUG: Saving audio to {audio_file_path}")
try:
with open(audio_file_path, "wb") as f:
f.write(audio_data)
print(f"DEBUG: Audio saved to {audio_file_path}")
except Exception as e:
print(f"DEBUG: Error saving audio file: {e}")
return None
return audio_file_path, audio_data
# if __name__ == "__main__":
# # Example usage
# prompt = "Hi. how are you."
# audio_dir = "./audio_replies"
# result = generate_voice_reply(prompt, audio_dir=audio_dir)
# if result:
# audio_file_path, audio_data = result
# print(f"DEBUG: Generated audio file: {audio_file_path}")
# else:
# print("DEBUG: Failed to generate audio file.")