File size: 2,864 Bytes
d65f7e4
 
 
 
8bcde54
 
 
d65f7e4
8bcde54
d65f7e4
 
e93a982
d65f7e4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8bcde54
 
 
 
 
 
 
 
 
 
 
 
d65f7e4
 
 
 
 
 
 
 
 
 
 
8bcde54
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
import os
from groq import Groq
import gradio as gr
from dotenv import load_dotenv
from gtts import gTTS
import tempfile

load_dotenv()

API_KEY = os.getenv("GROQ_API_KEY")
if not API_KEY:
    raise ValueError("Missing GROQ_API_KEY environment variable.")

client = Groq(api_key=API_KEY)

VALIDATION_PROMPT = "You are an intelligent assistant. Analyze the input question carefully. Respond with 'Yes' if the input is agriculture-related, and 'No' otherwise."
RESPONSE_PROMPT = "You are an agriculture expert. Provide a concise and accurate answer to the following agriculture-related question:"

def validate_input(input_text):
    try:
        validation_response = client.chat.completions.create(
            model="llama-3.1-8b-instant",
            messages=[
                {"role": "system", "content": "You are a helpful assistant."},
                {"role": "user", "content": VALIDATION_PROMPT},
                {"role": "user", "content": input_text},
            ],
            temperature=0,
            max_completion_tokens=1,
        )
        return validation_response.choices[0].message.content.strip()
    except Exception as e:
        return f"Error: {e}"

def get_agriculture_response(input_text):
    try:
        detailed_response = client.chat.completions.create(
            model="llama-3.1-8b-instant",
            messages=[
                {"role": "system", "content": "You are a helpful assistant."},
                {"role": "user", "content": RESPONSE_PROMPT},
                {"role": "user", "content": input_text},
            ],
            temperature=0.5,
            max_completion_tokens=700,
        )
        return detailed_response.choices[0].message.content.strip()
    except Exception as e:
        return f"Error: {e}"

def text_to_speech(text):
    if not text.strip():
        return None
    try:
        tts = gTTS(text=text, lang='en')
        temp_file = tempfile.NamedTemporaryFile(delete=False, suffix=".mp3")
        tts.save(temp_file.name)
        return temp_file.name
    except Exception as e:
        print(f"TTS error: {e}")
        return None

def groq_chatbot(input_text, chat_history):
    validation_result = validate_input(input_text)
    
    if validation_result.lower() == "yes":
        response = get_agriculture_response(input_text)
    elif validation_result.lower() == "no":
        response = "❌ This is not an agriculture-related question."
    else:
        response = f"⚠️ Unexpected response: {validation_result}"

    chat_history.append((input_text, response))
    # Return chat history, clear input, reset audio output
    return chat_history, "", None

def on_tts_click(chat_history):
    if chat_history and chat_history[-1][1]:
        last_response = chat_history[-1][1]
        audio_path = text_to_speech(last_response)
        return audio_path
    return None