File size: 4,771 Bytes
4e39757
497d665
 
 
77937b9
1c04ce8
77937b9
 
54df976
06f7f93
8d8eb38
77937b9
1c04ce8
77937b9
 
 
8d8eb38
77937b9
1c04ce8
 
 
 
 
 
 
 
 
 
77937b9
1c04ce8
 
77937b9
1c04ce8
 
 
 
 
 
 
 
 
8d8eb38
 
77937b9
1c04ce8
 
77937b9
 
 
 
1c04ce8
 
 
 
 
 
 
77937b9
 
 
1c04ce8
77937b9
 
 
 
 
 
18161d7
c5dc4cd
77937b9
 
1c04ce8
77937b9
 
 
8d8eb38
 
77937b9
 
8d8eb38
77937b9
1c04ce8
77937b9
 
1c04ce8
77937b9
 
1c04ce8
8d8eb38
 
18161d7
 
 
 
 
 
 
 
1c04ce8
 
 
 
 
9461617
1c04ce8
 
 
9461617
1c04ce8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8d8eb38
1c04ce8
77937b9
1c04ce8
 
 
77937b9
1c04ce8
8d8eb38
 
1c04ce8
8d8eb38
77937b9
8d8eb38
 
c783ee3
 
 
 
 
 
77937b9
 
62d3060
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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
import gradio as gr
import requests
from gtts import gTTS
import os
from transformers import pipeline
import random

# --- Configuration ---
API_URL = "https://api.together.xyz/v1/chat/completions"
API_KEY = "ccf72cc06e74d9814ab60ca112c40492b4a9b9b552a88c4203ccfb6a95cebd8b"  # Replace with your actual API key
MODEL_NAME = "mistralai/Mistral-7B-Instruct-v0.1"

# Initialize Whisper ASR (for speech recognition)
asr = pipeline("automatic-speech-recognition", model="openai/whisper-tiny")

# Global chat history
chat_history = []

# --- Bible Facts (for Surprise Mode) ---
BIBLE_FACTS = [
    "The Bible has around 611,000 words, depending on the translation.",
    "Psalm 119 is the longest chapter in the Bible, with 176 verses!",
    "The shortest verse in the Bible is John 11:35: ‘Jesus wept.’",
    "The word ‘Christian’ is used only three times in the whole Bible.",
    "The oldest book in the Bible is believed to be Job, not Genesis."
]

# --- AI Chat Function ---
def get_ai_response(user_text):
    global chat_history

    headers = {"Authorization": f"Bearer {API_KEY}"}
    
    # Handle Bible Fact Mode
    if "tell me something cool" in user_text.lower() or "bible fact" in user_text.lower():
        return random.choice(BIBLE_FACTS)

    # Keep chat history short to improve context accuracy
    if len(chat_history) > 5:
        chat_history = chat_history[-5:]

    messages = [{"role": "system", "content": "You are ZEAL AI, a Bible-based spiritual assistant."}]
    messages += chat_history
    messages.append({"role": "user", "content": user_text})

    data = {"model": MODEL_NAME, "messages": messages, "temperature": 0.9, "max_tokens": 500}
    
    response = requests.post(API_URL, json=data, headers=headers)
    try:
        response_json = response.json()
        reply = response_json.get("choices", [{}])[0].get("message", {}).get("content", "No response")

        # Save chat history
        chat_history.append({"role": "user", "content": user_text})
        chat_history.append({"role": "assistant", "content": reply})

        return reply
    except Exception as e:
        return f"Error: {str(e)}"

# --- Text-to-Speech (TTS) Function ---
def text_to_speech(text):
    tts = gTTS(text=text, lang="en")
    audio_path = "response.mp3"
    tts.save(audio_path)
    return audio_path

 # --- Chat Handling Function ---
def chat_with_zeal(text_input, audio_input):
    global chat_history
    
    # Convert Audio to Text (if provided)
    if audio_input is not None:
        asr_result = asr(audio_input)
        user_text = asr_result.get("text", "")
    else:
        user_text = text_input

    if not user_text:
        return gr.update(value=""), None, chat_history

    # Get AI response
    ai_response = get_ai_response(user_text)
    
    # Convert AI response to speech
    audio_file = text_to_speech(ai_response)

    # Format chat display
    display_history = []
    for msg in chat_history:
        if msg["role"] == "user":
            display_history.append(("You", msg["content"]))
        else:
            display_history.append(("ZEAL AI", msg["content"]))

    return display_history, audio_file, gr.update(value="")  # ✅ Clears text input
 
                                                                                   
# --- Custom Styling (Moves Input to Bottom + UI Improvements) ---
custom_css = """
#chatbot-container { 
    display: flex;
    flex-direction: column;
    height: 30vh; 
}
#chatbot {
    flex-grow: 1;
    max-height: 30vh;  /* Limits chat area height */
    overflow-y: auto;
    border-radius: 10px;
    padding: 10px;
}
#input-area {
    display: flex;
    align-items: center;
    padding: 10px;
    background-color: #f0f0f0;
    border-radius: 10px;
}
#input-area textarea {
    flex-grow: 1;
    font-size: 16px;
    padding: 10px;
}
"""

# --- Gradio UI ---
with gr.Blocks(css=custom_css) as demo:
    gr.Markdown("## 🤖 ZEAL AI - Bible-Based Spiritual Assistant")

    with gr.Row(elem_id="chatbot-container"):
        chatbot = gr.Chatbot(label="ZEAL AI Chat")  # Chat Display Area
    
    with gr.Row(elem_id="input-area"):  # Moves input area to bottom
        text_input = gr.Textbox(label="Type your message:")
        audio_input = gr.Audio(label="Or record your message:", type="filepath")  # ✅ FIXED
        send_btn = gr.Button("Send")

    audio_output = gr.Audio(label="ZEAL AI Says (Audio)", autoplay=True)
    chat_history_state = gr.State([])

  # ✅ Make sure .click() is inside the `with gr.Blocks()`
    send_btn.click(
        chat_with_zeal, 
        inputs=[text_input, audio_input],
        outputs=[chatbot, audio_output, text_input]  # ✅ Clears text input
    )

# Launch the app
demo.launch(server_name="0.0.0.0", server_port=7860)