Kartheek Akella
Initial Working Commit
9e4c237
#!/usr/bin/env python3
import os
import uuid
import datetime
from typing import Dict, Any, Optional
import gradio as gr
import weave
from pathlib import Path
from bhagavad_gita_bot import BhagavadGitaBot
class BhagavadGitaWebApp:
def __init__(self):
# Check for required API keys with user-friendly messages
if not os.getenv("OPENROUTER_API_KEY"):
raise ValueError(
"❌ OPENROUTER_API_KEY environment variable is required but not set. "
"Please contact the Space owner to configure API keys."
)
self.bot = BhagavadGitaBot()
self.session_storage = {}
# Weave is already initialized in the bot's logger
def process_problem(self, problem_text: str, request: gr.Request) -> tuple:
"""Process user problem and return guidance"""
if not problem_text.strip():
return "Please enter your problem or concern.", None, None, None
# Generate session ID
session_id = str(uuid.uuid4())[:8]
try:
# Get guidance from bot (with Weave logging built-in)
response = self.bot.get_guidance(problem_text, include_verses=True, session_id=session_id)
if 'error' in response:
error_msg = f"I apologize, but I encountered an error: {response['error']}. Please try rephrasing your concern."
return error_msg, None, response.get('session_id', session_id), None
# Format the response
guidance_text = self._format_response(response)
verses_text = self._format_verses(response.get('relevant_verses', []))
# Store session data for feedback correlation
session_data = {
"session_id": response.get('session_id', session_id),
"user_problem": problem_text,
"bot_response": response,
"guidance_text": guidance_text,
"verses_text": verses_text
}
self.session_storage[response.get('session_id', session_id)] = session_data
return guidance_text, verses_text, response.get('session_id', session_id), gr.update(visible=True)
except Exception as e:
error_msg = f"I apologize, but I encountered an unexpected error. Please try again."
print(f"Error processing problem: {e}")
return error_msg, None, session_id, None
def _format_response(self, response: Dict[str, Any]) -> str:
"""Format the main response for display"""
formatted = "πŸ•‰οΈ **Guidance from the Bhagavad Gita**\n\n"
# Problem analysis
analysis = response.get('problem_analysis', {})
if analysis:
formatted += "**Understanding your situation:**\n"
formatted += f"β€’ Key themes: {analysis.get('key_themes', 'N/A')}\n"
formatted += f"β€’ Emotional state: {analysis.get('emotional_state', 'N/A')}\n"
formatted += f"β€’ Core question: {analysis.get('core_question', 'N/A')}\n\n"
# Main guidance
formatted += "**Message for you:**\n"
formatted += response.get('main_response', 'No guidance available') + "\n\n"
# Closing blessing
if response.get('closing_blessing'):
formatted += "**Blessing:**\n"
formatted += response.get('closing_blessing') + "\n"
return formatted
def _format_verses(self, verses: list) -> str:
"""Format verses for display"""
if not verses:
return "No verses found."
formatted = "πŸ“– **Supporting Verses from the Bhagavad Gita**\n\n"
for i, verse in enumerate(verses, 1):
formatted += f"**{i}. {verse.get('verse_reference', 'Unknown')}**\n\n"
formatted += f"*Sanskrit:* {verse.get('sanskrit_text', 'N/A')}\n\n"
formatted += f"*English:* {verse.get('english_translation', 'N/A')}\n\n"
if verse.get('contextual_guidance'):
formatted += f"**Guidance:** {verse.get('contextual_guidance')}\n\n"
if verse.get('practical_application'):
formatted += f"**Application:** {verse.get('practical_application')}\n\n"
if verse.get('reflection_question'):
formatted += f"**Reflection:** {verse.get('reflection_question')}\n\n"
if i < len(verses):
formatted += "---\n\n"
return formatted
def submit_feedback(self, session_id: str, feedback: str, additional_comments: str = ""):
"""Handle feedback submission"""
if not session_id or session_id not in self.session_storage:
return "⚠️ Session not found. Please try your question again."
try:
# Log feedback directly to Weave/WandB (if available)
self.bot.logger.log_user_feedback(
session_id=session_id,
feedback_type=feedback,
comments=additional_comments
)
return f"πŸ™ Thank you for your feedback! Your {feedback} has been recorded."
except Exception as e:
print(f"Warning: Could not log feedback: {e}")
return f"πŸ™ Thank you for your {feedback} feedback!"
def create_interface(self):
"""Create the Gradio interface"""
with gr.Blocks(title="πŸ•‰οΈ Bhagavad Gita Wisdom Bot") as demo:
gr.HTML("""
<div style="text-align: center; padding: 20px; background: linear-gradient(135deg, #fff8e1 0%, #ffecb3 100%); border-radius: 10px; margin-bottom: 20px;">
<h1 style="color: #d84315; margin-bottom: 10px;">πŸ•‰οΈ Bhagavad Gita Wisdom Bot</h1>
<p style="color: #5d4037; font-size: 16px; margin-bottom: 5px;">Share your concerns and receive guidance from the eternal wisdom of the Bhagavad Gita</p>
<p style="color: #8d6e63; font-size: 12px;"><em>Powered by AI and ancient wisdom β€’ All interactions may be logged for service improvement</em></p>
</div>
""")
with gr.Row():
with gr.Column():
# Input section
problem_input = gr.Textbox(
label="What challenges are you facing?",
placeholder="Share your problem, concern, or question here. Be as specific as you'd like - this helps me find the most relevant wisdom for your situation.",
lines=4,
max_lines=10
)
submit_btn = gr.Button("πŸ™ Seek Wisdom", variant="primary", size="lg")
# Examples
gr.Examples(
examples=[
["I'm struggling with a difficult career decision and feel paralyzed by the fear of making the wrong choice."],
["I've been working hard but not seeing the results I want. I'm losing motivation and feeling frustrated."],
["I'm going through a breakup and feeling lost. I don't understand why this happened to me."],
["I feel like I've lost my sense of purpose and don't know what direction my life should take."],
["I'm overwhelmed by anxiety about the future and can't seem to find peace."]
],
inputs=problem_input
)
# Response sections
with gr.Row():
with gr.Column():
guidance_output = gr.Markdown(
label="Guidance",
value="Your personalized guidance will appear here...",
elem_classes=["guidance-text"]
)
with gr.Row():
with gr.Column():
verses_output = gr.Markdown(
label="Supporting Verses",
value="Relevant verses and their applications will appear here...",
elem_classes=["verses-text"]
)
# Hidden session ID storage
session_id_state = gr.State()
# Feedback section (initially hidden)
with gr.Group(visible=False) as feedback_group:
gr.HTML("<h3>πŸ“ How was this guidance?</h3>")
with gr.Row():
thumbs_up_btn = gr.Button("πŸ‘ Helpful", variant="secondary")
thumbs_down_btn = gr.Button("πŸ‘Ž Not Helpful", variant="secondary")
feedback_comments = gr.Textbox(
label="Additional Comments (Optional)",
placeholder="Share any additional thoughts about this guidance...",
lines=2
)
feedback_output = gr.Markdown()
# Event handlers
submit_btn.click(
fn=self.process_problem,
inputs=[problem_input],
outputs=[guidance_output, verses_output, session_id_state, feedback_group],
show_progress=True
)
problem_input.submit(
fn=self.process_problem,
inputs=[problem_input],
outputs=[guidance_output, verses_output, session_id_state, feedback_group],
show_progress=True
)
thumbs_up_btn.click(
fn=lambda sid, comments: self.submit_feedback(sid, "positive", comments),
inputs=[session_id_state, feedback_comments],
outputs=[feedback_output]
)
thumbs_down_btn.click(
fn=lambda sid, comments: self.submit_feedback(sid, "negative", comments),
inputs=[session_id_state, feedback_comments],
outputs=[feedback_output]
)
return demo
def main():
try:
app = BhagavadGitaWebApp()
demo = app.create_interface()
print("πŸ•‰οΈ Starting Bhagavad Gita Wisdom Bot...")
print("🌐 The app will be available shortly...")
if os.getenv("WANDB_API_KEY"):
print("πŸ“Š Logging to Weights & Biases enabled")
else:
print("⚠️ WANDB_API_KEY not set - logging to W&B disabled")
demo.launch(
server_name="0.0.0.0",
server_port=7860,
share=False,
show_error=True
)
except ValueError as e:
print(f"\n{e}")
print("\nπŸ’‘ This is a configuration issue that needs to be resolved by the Space administrator.")
return
except Exception as e:
print(f"❌ Failed to start the application: {e}")
return
if __name__ == "__main__":
main()