Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,172 +1,278 @@
|
|
| 1 |
#!/usr/bin/env python3
|
| 2 |
"""
|
| 3 |
-
Indian Legal AI Assistant using
|
| 4 |
-
|
| 5 |
-
|
|
|
|
| 6 |
"""
|
| 7 |
|
| 8 |
import os
|
|
|
|
|
|
|
| 9 |
import gradio as gr
|
| 10 |
from huggingface_hub import hf_hub_download
|
| 11 |
from llama_cpp import Llama
|
| 12 |
|
|
|
|
|
|
|
| 13 |
# Model configuration
|
|
|
|
|
|
|
| 14 |
MODEL_REPO = "invincibleambuj/Ambuj-Tripathi-Indian-Legal-Llama-GGUF"
|
| 15 |
MODEL_FILE = "ambuj-tripathi-indian-legal-llama.Q4_K_M.gguf"
|
| 16 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 17 |
# Global model instance
|
| 18 |
llm = None
|
| 19 |
|
| 20 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 21 |
def load_model():
|
| 22 |
-
"""
|
| 23 |
global llm
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 40 |
return llm
|
| 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 |
{conversation}User: {message}
|
| 67 |
Assistant:"""
|
| 68 |
-
|
| 69 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 70 |
response = model(
|
| 71 |
prompt,
|
| 72 |
max_tokens=512,
|
| 73 |
temperature=0.7,
|
| 74 |
top_p=0.95,
|
| 75 |
echo=False,
|
| 76 |
-
stop=["User:", "\n\n\n"]
|
| 77 |
)
|
| 78 |
-
|
| 79 |
-
return response['choices'][0]['text'].strip()
|
| 80 |
-
|
| 81 |
-
except Exception as e:
|
| 82 |
-
return f"Error: {str(e)}\n\nPlease ensure the model is properly downloaded and configured."
|
| 83 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 84 |
|
| 85 |
def create_gradio_interface():
|
| 86 |
-
"""Create and return the Gradio chat interface"""
|
| 87 |
-
|
| 88 |
-
# Custom CSS for better appearance
|
| 89 |
custom_css = """
|
| 90 |
.container {
|
| 91 |
max-width: 900px;
|
| 92 |
margin: auto;
|
| 93 |
padding: 20px;
|
| 94 |
}
|
|
|
|
| 95 |
#title {
|
| 96 |
text-align: center;
|
| 97 |
color: #1e3a8a;
|
| 98 |
}
|
| 99 |
"""
|
| 100 |
-
|
| 101 |
with gr.Blocks(css=custom_css, title="Indian Legal AI Assistant") as demo:
|
| 102 |
gr.Markdown(
|
| 103 |
"""
|
| 104 |
# 🏛️ Indian Legal AI Assistant
|
| 105 |
-
|
| 106 |
-
Ask questions about Indian laws, acts, and legal procedures.
|
| 107 |
-
|
| 108 |
-
|
|
|
|
| 109 |
**Examples:**
|
| 110 |
- What is the Indian Penal Code?
|
| 111 |
-
- Explain Section 377 of IPC
|
| 112 |
-
- What are the grounds for divorce under Hindu Marriage Act?
|
| 113 |
-
- Explain the Right to Information Act
|
| 114 |
""",
|
| 115 |
-
elem_id="title"
|
| 116 |
)
|
| 117 |
-
|
| 118 |
chatbot = gr.Chatbot(
|
| 119 |
height=500,
|
| 120 |
label="Chat History",
|
| 121 |
show_label=True,
|
| 122 |
-
elem_id="chatbot"
|
|
|
|
| 123 |
)
|
| 124 |
-
|
| 125 |
with gr.Row():
|
| 126 |
msg = gr.Textbox(
|
| 127 |
label="Your Question",
|
| 128 |
placeholder="Ask about Indian laws...",
|
| 129 |
lines=2,
|
| 130 |
-
scale=4
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 131 |
)
|
| 132 |
-
|
| 133 |
-
|
| 134 |
with gr.Row():
|
| 135 |
clear = gr.Button("Clear Chat")
|
| 136 |
-
|
| 137 |
gr.Markdown(
|
| 138 |
"""
|
| 139 |
---
|
| 140 |
-
|
| 141 |
-
|
| 142 |
-
|
|
|
|
|
|
|
| 143 |
**Model:** [invincibleambuj/Ambuj-Tripathi-Indian-Legal-Llama-GGUF](https://huggingface.co/invincibleambuj/Ambuj-Tripathi-Indian-Legal-Llama-GGUF)
|
| 144 |
"""
|
| 145 |
)
|
| 146 |
-
|
| 147 |
-
|
| 148 |
-
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
|
| 152 |
-
|
| 153 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 154 |
return demo
|
| 155 |
|
| 156 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 157 |
if __name__ == "__main__":
|
| 158 |
print("Starting Indian Legal AI Assistant...")
|
| 159 |
print(f"Using model: {MODEL_REPO}/{MODEL_FILE}")
|
| 160 |
-
|
| 161 |
-
#
|
| 162 |
-
|
| 163 |
-
|
| 164 |
-
|
| 165 |
-
# Launch the Gradio interface
|
| 166 |
demo = create_gradio_interface()
|
|
|
|
| 167 |
demo.launch(
|
| 168 |
server_name="0.0.0.0",
|
| 169 |
server_port=7860,
|
| 170 |
share=False,
|
| 171 |
-
show_error=True
|
| 172 |
)
|
|
|
|
| 1 |
#!/usr/bin/env python3
|
| 2 |
"""
|
| 3 |
+
Indian Legal AI Assistant using a GGUF model with llama-cpp-python.
|
| 4 |
+
|
| 5 |
+
Model:
|
| 6 |
+
invincibleambuj/Ambuj-Tripathi-Indian-Legal-Llama-GGUF
|
| 7 |
"""
|
| 8 |
|
| 9 |
import os
|
| 10 |
+
import traceback
|
| 11 |
+
|
| 12 |
import gradio as gr
|
| 13 |
from huggingface_hub import hf_hub_download
|
| 14 |
from llama_cpp import Llama
|
| 15 |
|
| 16 |
+
|
| 17 |
+
# -----------------------------
|
| 18 |
# Model configuration
|
| 19 |
+
# -----------------------------
|
| 20 |
+
|
| 21 |
MODEL_REPO = "invincibleambuj/Ambuj-Tripathi-Indian-Legal-Llama-GGUF"
|
| 22 |
MODEL_FILE = "ambuj-tripathi-indian-legal-llama.Q4_K_M.gguf"
|
| 23 |
|
| 24 |
+
# Hugging Face Spaces usually provides limited CPU/RAM on free hardware.
|
| 25 |
+
# These defaults are conservative.
|
| 26 |
+
N_CTX = int(os.getenv("N_CTX", "2048"))
|
| 27 |
+
N_THREADS = int(os.getenv("N_THREADS", "4"))
|
| 28 |
+
N_GPU_LAYERS = int(os.getenv("N_GPU_LAYERS", "0"))
|
| 29 |
+
|
| 30 |
# Global model instance
|
| 31 |
llm = None
|
| 32 |
|
| 33 |
|
| 34 |
+
# -----------------------------
|
| 35 |
+
# Model loading
|
| 36 |
+
# -----------------------------
|
| 37 |
+
|
| 38 |
def load_model():
|
| 39 |
+
"""Download and load the GGUF model once."""
|
| 40 |
global llm
|
| 41 |
+
|
| 42 |
+
if llm is not None:
|
| 43 |
+
return llm
|
| 44 |
+
|
| 45 |
+
print(f"Downloading model from {MODEL_REPO}...")
|
| 46 |
+
model_path = hf_hub_download(
|
| 47 |
+
repo_id=MODEL_REPO,
|
| 48 |
+
filename=MODEL_FILE,
|
| 49 |
+
cache_dir="./models",
|
| 50 |
+
)
|
| 51 |
+
|
| 52 |
+
print(f"Model downloaded to: {model_path}")
|
| 53 |
+
print("Loading model into memory...")
|
| 54 |
+
|
| 55 |
+
llm = Llama(
|
| 56 |
+
model_path=model_path,
|
| 57 |
+
n_ctx=N_CTX,
|
| 58 |
+
n_threads=N_THREADS,
|
| 59 |
+
n_gpu_layers=N_GPU_LAYERS,
|
| 60 |
+
verbose=False,
|
| 61 |
+
)
|
| 62 |
+
|
| 63 |
+
print("Model loaded successfully.")
|
| 64 |
return llm
|
| 65 |
|
| 66 |
|
| 67 |
+
# -----------------------------
|
| 68 |
+
# Prompting / inference
|
| 69 |
+
# -----------------------------
|
| 70 |
+
|
| 71 |
+
def build_prompt(message, history):
|
| 72 |
+
"""Build a simple instruction prompt from chat history."""
|
| 73 |
+
|
| 74 |
+
conversation = ""
|
| 75 |
+
|
| 76 |
+
if history:
|
| 77 |
+
for user_msg, bot_msg in history:
|
| 78 |
+
conversation += f"User: {user_msg}\nAssistant: {bot_msg}\n"
|
| 79 |
+
|
| 80 |
+
prompt = f"""You are an expert Indian legal AI assistant.
|
| 81 |
+
|
| 82 |
+
You have knowledge of Indian laws, acts, legal procedures, and general legal concepts.
|
| 83 |
+
Provide accurate, helpful, and concise information.
|
| 84 |
+
|
| 85 |
+
Important:
|
| 86 |
+
- Do not claim to be a lawyer.
|
| 87 |
+
- Do not present your answer as formal legal advice.
|
| 88 |
+
- Encourage the user to consult a qualified lawyer for specific legal matters.
|
| 89 |
|
| 90 |
{conversation}User: {message}
|
| 91 |
Assistant:"""
|
| 92 |
+
|
| 93 |
+
return prompt
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
def generate_legal_response(message, history):
|
| 97 |
+
"""Generate a response from the local GGUF model."""
|
| 98 |
+
|
| 99 |
+
if not message or not message.strip():
|
| 100 |
+
return "Please enter a legal question."
|
| 101 |
+
|
| 102 |
+
try:
|
| 103 |
+
model = load_model()
|
| 104 |
+
prompt = build_prompt(message.strip(), history)
|
| 105 |
+
|
| 106 |
response = model(
|
| 107 |
prompt,
|
| 108 |
max_tokens=512,
|
| 109 |
temperature=0.7,
|
| 110 |
top_p=0.95,
|
| 111 |
echo=False,
|
| 112 |
+
stop=["User:", "\nUser:", "\n\n\n"],
|
| 113 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 114 |
|
| 115 |
+
text = response["choices"][0]["text"].strip()
|
| 116 |
+
|
| 117 |
+
if not text:
|
| 118 |
+
return "I could not generate a response. Please try rephrasing your question."
|
| 119 |
+
|
| 120 |
+
return text
|
| 121 |
+
|
| 122 |
+
except Exception as error:
|
| 123 |
+
print("Error during generation:")
|
| 124 |
+
traceback.print_exc()
|
| 125 |
+
|
| 126 |
+
return (
|
| 127 |
+
"The app encountered an error while loading or running the model.\n\n"
|
| 128 |
+
f"Error details: {str(error)}"
|
| 129 |
+
)
|
| 130 |
+
|
| 131 |
+
|
| 132 |
+
# -----------------------------
|
| 133 |
+
# Gradio handlers
|
| 134 |
+
# -----------------------------
|
| 135 |
+
|
| 136 |
+
def respond(message, history):
|
| 137 |
+
"""
|
| 138 |
+
Gradio chat handler.
|
| 139 |
+
|
| 140 |
+
Input:
|
| 141 |
+
- message: latest user message
|
| 142 |
+
- history: list of (user_message, assistant_message)
|
| 143 |
+
|
| 144 |
+
Output:
|
| 145 |
+
- empty textbox
|
| 146 |
+
- updated chatbot history
|
| 147 |
+
"""
|
| 148 |
+
|
| 149 |
+
if history is None:
|
| 150 |
+
history = []
|
| 151 |
+
|
| 152 |
+
bot_reply = generate_legal_response(message, history)
|
| 153 |
+
history.append((message, bot_reply))
|
| 154 |
+
|
| 155 |
+
return "", history
|
| 156 |
+
|
| 157 |
+
|
| 158 |
+
def clear_chat():
|
| 159 |
+
"""Clear the chat history."""
|
| 160 |
+
return []
|
| 161 |
+
|
| 162 |
+
|
| 163 |
+
# -----------------------------
|
| 164 |
+
# Gradio UI
|
| 165 |
+
# -----------------------------
|
| 166 |
|
| 167 |
def create_gradio_interface():
|
| 168 |
+
"""Create and return the Gradio chat interface."""
|
| 169 |
+
|
|
|
|
| 170 |
custom_css = """
|
| 171 |
.container {
|
| 172 |
max-width: 900px;
|
| 173 |
margin: auto;
|
| 174 |
padding: 20px;
|
| 175 |
}
|
| 176 |
+
|
| 177 |
#title {
|
| 178 |
text-align: center;
|
| 179 |
color: #1e3a8a;
|
| 180 |
}
|
| 181 |
"""
|
| 182 |
+
|
| 183 |
with gr.Blocks(css=custom_css, title="Indian Legal AI Assistant") as demo:
|
| 184 |
gr.Markdown(
|
| 185 |
"""
|
| 186 |
# 🏛️ Indian Legal AI Assistant
|
| 187 |
+
|
| 188 |
+
Ask questions about Indian laws, acts, and legal procedures.
|
| 189 |
+
|
| 190 |
+
This AI assistant uses the **Ambuj Tripathi Indian Legal Llama GGUF** model.
|
| 191 |
+
|
| 192 |
**Examples:**
|
| 193 |
- What is the Indian Penal Code?
|
| 194 |
+
- Explain Section 377 of IPC.
|
| 195 |
+
- What are the grounds for divorce under the Hindu Marriage Act?
|
| 196 |
+
- Explain the Right to Information Act.
|
| 197 |
""",
|
| 198 |
+
elem_id="title",
|
| 199 |
)
|
| 200 |
+
|
| 201 |
chatbot = gr.Chatbot(
|
| 202 |
height=500,
|
| 203 |
label="Chat History",
|
| 204 |
show_label=True,
|
| 205 |
+
elem_id="chatbot",
|
| 206 |
+
type="tuples",
|
| 207 |
)
|
| 208 |
+
|
| 209 |
with gr.Row():
|
| 210 |
msg = gr.Textbox(
|
| 211 |
label="Your Question",
|
| 212 |
placeholder="Ask about Indian laws...",
|
| 213 |
lines=2,
|
| 214 |
+
scale=4,
|
| 215 |
+
)
|
| 216 |
+
|
| 217 |
+
submit = gr.Button(
|
| 218 |
+
"Send",
|
| 219 |
+
variant="primary",
|
| 220 |
+
scale=1,
|
| 221 |
)
|
| 222 |
+
|
|
|
|
| 223 |
with gr.Row():
|
| 224 |
clear = gr.Button("Clear Chat")
|
| 225 |
+
|
| 226 |
gr.Markdown(
|
| 227 |
"""
|
| 228 |
---
|
| 229 |
+
|
| 230 |
+
**Disclaimer:** This assistant provides general legal information only.
|
| 231 |
+
It is not a substitute for advice from a qualified legal professional.
|
| 232 |
+
For specific legal matters, please consult a lawyer.
|
| 233 |
+
|
| 234 |
**Model:** [invincibleambuj/Ambuj-Tripathi-Indian-Legal-Llama-GGUF](https://huggingface.co/invincibleambuj/Ambuj-Tripathi-Indian-Legal-Llama-GGUF)
|
| 235 |
"""
|
| 236 |
)
|
| 237 |
+
|
| 238 |
+
msg.submit(
|
| 239 |
+
respond,
|
| 240 |
+
inputs=[msg, chatbot],
|
| 241 |
+
outputs=[msg, chatbot],
|
| 242 |
+
)
|
| 243 |
+
|
| 244 |
+
submit.click(
|
| 245 |
+
respond,
|
| 246 |
+
inputs=[msg, chatbot],
|
| 247 |
+
outputs=[msg, chatbot],
|
| 248 |
+
)
|
| 249 |
+
|
| 250 |
+
clear.click(
|
| 251 |
+
clear_chat,
|
| 252 |
+
inputs=None,
|
| 253 |
+
outputs=chatbot,
|
| 254 |
+
)
|
| 255 |
+
|
| 256 |
return demo
|
| 257 |
|
| 258 |
|
| 259 |
+
# -----------------------------
|
| 260 |
+
# App entry point
|
| 261 |
+
# -----------------------------
|
| 262 |
+
|
| 263 |
if __name__ == "__main__":
|
| 264 |
print("Starting Indian Legal AI Assistant...")
|
| 265 |
print(f"Using model: {MODEL_REPO}/{MODEL_FILE}")
|
| 266 |
+
|
| 267 |
+
# Do not preload the model here.
|
| 268 |
+
# On Hugging Face Spaces, preloading can cause startup timeout or memory issues.
|
| 269 |
+
# The model will load on the first user message instead.
|
| 270 |
+
|
|
|
|
| 271 |
demo = create_gradio_interface()
|
| 272 |
+
|
| 273 |
demo.launch(
|
| 274 |
server_name="0.0.0.0",
|
| 275 |
server_port=7860,
|
| 276 |
share=False,
|
| 277 |
+
show_error=True,
|
| 278 |
)
|