Spaces:
Sleeping

Chatbot / app.py
shaikhmaria151's picture
Update app.py
da6f206 verified
Raw History Blame Contribute Delete
3.15 kB
import spaces
import gradio as gr
import traceback
from rag_inference import answer_query
from encryption_utils import (
encrypt_message,
decrypt_message,
)
# ============================================================
# CORE CHAT
# ============================================================
def generate_answer(question: str) -> str:
question = str(question).strip()
if not question:
return "ERROR: Question cannot be empty."
# Try to decrypt incoming question
try:
question = decrypt_message(question)
print("Input decrypted successfully.")
except Exception as e:
print(
f"Input is plain text or decryption failed: {e}"
)
question = str(question).strip()
print(
f"Question received: {question[:100]}"
)
# RAG + Mistral
answer = answer_query(
question
)
if not answer:
answer = "Unable to generate an answer."
print(
"Answer generated successfully."
)
return str(answer)
# ============================================================
# GPU API FUNCTION
# ============================================================
@spaces.GPU(duration=120)
def run_chat(question: str):
try:
answer = generate_answer(
question
)
# Encrypt response for frontend
encrypted_answer = encrypt_message(
answer
)
return encrypted_answer
except Exception as e:
traceback.print_exc()
try:
return encrypt_message(
f"ERROR: {str(e)}"
)
except Exception:
return f"ERROR: {str(e)}"
# ============================================================
# GRADIO TEST FUNCTION
# ============================================================
@spaces.GPU(duration=120)
def test_chat(question: str):
try:
# For Space UI, return readable answer
return generate_answer(
question
)
except Exception as e:
traceback.print_exc()
return f"ERROR: {str(e)}"
# ============================================================
# GRADIO UI
# ============================================================
with gr.Blocks(
title="Court Companion Chatbot"
) as demo:
gr.Markdown(
"""
# ⚖️ Court Companion Chatbot
Pakistani Criminal Law RAG Assistant
"""
)
question = gr.Textbox(
label="Question",
placeholder=(
"Ask a question about Pakistani criminal law..."
),
lines=5,
)
ask_button = gr.Button(
"Ask",
variant="primary",
)
answer = gr.Textbox(
label="Answer",
lines=12,
)
ask_button.click(
fn=test_chat,
inputs=question,
outputs=answer,
api_name="test",
)
# ============================================================
# LAUNCH
# ============================================================
if __name__ == "__main__":
demo.launch(
server_name="0.0.0.0",
server_port=7860,
)