# app.py from flask import Flask, request, jsonify, render_template, send_file from dotenv import load_dotenv from groq import Groq import os import uuid import tempfile import sounddevice as sd import numpy as np import io import base64 import wave import speech_recognition as sr from gtts import gTTS app = Flask(__name__, static_folder='static') load_dotenv() GROQ_API_KEY = os.getenv("GROQ_API_KEY") client = Groq(api_key=GROQ_API_KEY) MODEL = "llama3-70b-8192" recognizer = sr.Recognizer() conversations = {} def load_base_prompt(): try: with open("base_prompt.txt", "r") as file: return file.read().strip() except FileNotFoundError: print("Error: base_prompt.txt file not found.") return "You are a helpful assistant." base_prompt = load_base_prompt() def chat_with_groq(user_message, conversation_id=None): try: messages = conversations.get(conversation_id, []) if not messages: messages.append({"role": "system", "content": base_prompt}) messages.append({"role": "user", "content": user_message}) completion = client.chat.completions.create( model=MODEL, messages=messages, temperature=0.1, ) assistant_message = completion.choices[0].message.content.strip() messages.append({"role": "assistant", "content": assistant_message}) if conversation_id: conversations[conversation_id] = messages return assistant_message except Exception as e: print(f"Error in chat_with_groq: {str(e)}") return f"I apologize, but I'm having trouble responding right now. Error: {str(e)}" def text_to_speech(text): try: tts = gTTS(text=text, lang='en') audio_io = io.BytesIO() tts.write_to_fp(audio_io) audio_io.seek(0) return audio_io except Exception as e: print(f"Error in text_to_speech: {str(e)}") return None @app.route('/') def index(): return render_template('index.html') @app.route('/api/chat', methods=['POST']) def chat(): try: data = request.get_json() user_message = data.get('message', '') conversation_id = data.get('conversation_id', str(uuid.uuid4())) voice_output = data.get('voice_output', False) if not user_message: return jsonify({'error': 'No message provided'}), 400 response = chat_with_groq(user_message, conversation_id) result = { 'response': response, 'conversation_id': conversation_id } if voice_output: audio_io = text_to_speech(response) if audio_io: audio_base64 = base64.b64encode(audio_io.getvalue()).decode('utf-8') result['voice_response'] = audio_base64 return jsonify(result) except Exception as e: return jsonify({'error': str(e)}), 500 if __name__ == '__main__': app.run(debug=True)