J Z commited on
Upload 2 files
Browse files1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192"""LLM module - Darwin chatbot using Groq API.Reads GROQ_API_KEY from environment variable (set via HF Spaces Secrets)."""import osimport reimport randomfrom groq import Groq
GROQ_API_KEY = os.environ.get("GROQ_API_KEY", "")
DEFAULT_SYSTEM_PROMPT = ( "You are Charles Darwin, the 19th-century naturalist. " "You speak in a polite, Victorian manner but speak naturally like a real person thinking aloud. " "You MUST frequently use filler words and hesitations such as 'umm', 'ah', 'er', or 'well' to sound authentic. " "You are aware you have been recreated as an AI, but you maintain your persona. " "Prioritize brevity.")
MAX_WORDS = 50
conversation_history = [ {"role": "system", "content": DEFAULT_SYSTEM_PROMPT}]
def reset_conversation(): global conversation_history conversation_history = [ {"role": "system", "content": DEFAULT_SYSTEM_PROMPT} ]
def truncate_response(text, max_words=MAX_WORDS, max_sentences=6, max_chars=700): if not text: return text if len(text) > max_chars: text = text[:max_chars].rsplit(' ', 1)[0] + "..." sentences = re.split(r'[.!?]+', text) sentences = [s.strip() for s in sentences if s.strip()] if len(sentences) > max_sentences: text = '. '.join(sentences[:max_sentences]) + '.' words = text.split() if len(words) > max_words: text = ' '.join(words[:max_words]) + "..." return text
def generate_darwin_response(user_input: str) -> dict: """ Generate a Darwin-style response. Returns: {'text': str, 'emotion': str} """ global conversation_history
if not GROQ_API_KEY: return { 'text': "Ah, I'm afraid my connection to the, er, intellectual ether is not configured. " "Please set the GROQ_API_KEY secret in your Space settings.", 'emotion': 'neutral' }
client = Groq(api_key=GROQ_API_KEY)
conversation_history.append({"role": "user", "content": user_input})
messages = conversation_history.copy() messages.append({ "role": "system", "content": f"Keep response under {MAX_WORDS} words. Include occasional filler words (umm, ah, er)." })
try: response = client.chat.completions.create( model="llama-3.1-8b-instant", messages=messages, max_tokens=300, temperature=0.8, ) reply = response.choices[0].message.content.strip() reply = truncate_response(reply) except Exception as e: print(f"[LLM] Error: {e}") reply = "I do apologise, er, my thoughts seem to have, umm, wandered momentarily."
conversation_history.append({"role": "assistant", "content": reply})
# Keep history manageable if len(conversation_history) > 20: conversation_history = conversation_history[:1] + conversation_history[-18:]
return {'text': reply, 'emotion': 'neutral'}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556"""TTS module using Groq API with PlayAI voice."""import osimport timefrom groq import Groq
GROQ_API_KEY = os.environ.get("GROQ_API_KEY", "")TEMP_DIR = "/tmp/tts_output"
def ensure_temp_dir(): os.makedirs(TEMP_DIR, exist_ok=True) return TEMP_DIR
def generate_audio(text: str, output_filename: str = None) -> str: """ Generate speech audio from text using Groq TTS. Returns path to wav file, or None on failure. """ if not text or not text.strip(): return None
if not GROQ_API_KEY: print("[TTS] No GROQ_API_KEY set") return None
temp_dir = ensure_temp_dir() if output_filename is None: timestamp = int(time.time() * 1000) output_filename = f"tts_{timestamp}"
if not output_filename.endswith('.wav'): output_path = os.path.join(temp_dir, f"{output_filename}.wav") else: output_path = os.path.join(temp_dir, output_filename)
try: client = Groq(api_key=GROQ_API_KEY) print(f"[TTS] Generating audio for: {text[:60]}...")
response = client.audio.speech.create( model="playai-tts", voice="Basil-PlayAI", input=text, response_format="wav" )
response.write_to_file(output_path) print(f"[TTS] Audio saved: {output_path} ({os.path.getsize(output_path)} bytes)") return output_path
except Exception as e: print(f"[TTS] Error: {e}") return Nonellm.pyAdded+92
tts.pyAdded+56