rotsl commited on
Commit
20ce560
·
verified ·
1 Parent(s): b8128ca

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +193 -87
app.py CHANGED
@@ -1,172 +1,278 @@
1
  #!/usr/bin/env python3
2
  """
3
- Indian Legal AI Assistant using Hugging Face LLM
4
- This app provides a chat interface for querying Indian laws using the
5
- invincibleambuj/Ambuj-Tripathi-Indian-Legal-Llama-GGUF model.
 
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
- """Load the GGUF model from Hugging Face Hub"""
23
  global llm
24
- if llm is None:
25
- print(f"Downloading model from {MODEL_REPO}...")
26
- model_path = hf_hub_download(
27
- repo_id=MODEL_REPO,
28
- filename=MODEL_FILE,
29
- cache_dir="./models"
30
- )
31
- print(f"Model downloaded to: {model_path}")
32
- print("Loading model into memory...")
33
- llm = Llama(
34
- model_path=model_path,
35
- n_ctx=2048, # Context window
36
- n_threads=4, # CPU threads
37
- n_gpu_layers=0, # Set to 0 for CPU-only, increase if GPU available
38
- )
39
- print("Model loaded successfully!")
 
 
 
 
 
 
 
40
  return llm
41
 
42
 
43
- def chat_with_legal_ai(message, history):
44
- """
45
- Process user message and generate response using the Indian Legal LLM
46
-
47
- Args:
48
- message: User's input message
49
- history: Chat history (list of [user_msg, bot_msg] pairs)
50
-
51
- Returns:
52
- Response from the LLM
53
- """
54
- try:
55
- model = load_model()
56
-
57
- # Build conversation context
58
- conversation = ""
59
- if history:
60
- for user_msg, bot_msg in history:
61
- conversation += f"User: {user_msg}\nAssistant: {bot_msg}\n"
62
-
63
- # Add current message
64
- prompt = f"""You are an expert Indian legal AI assistant. You have deep knowledge of Indian laws, acts, and legal procedures. Provide accurate, helpful, and concise answers to legal queries.
65
 
66
  {conversation}User: {message}
67
  Assistant:"""
68
-
69
- # Generate response
 
 
 
 
 
 
 
 
 
 
 
 
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. This AI assistant is powered by
107
- the **Ambuj Tripathi Indian Legal Llama** model, trained on Indian legal documents.
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
- submit = gr.Button("Send", variant="primary", scale=1)
133
-
134
  with gr.Row():
135
  clear = gr.Button("Clear Chat")
136
-
137
  gr.Markdown(
138
  """
139
  ---
140
- **Disclaimer:** This AI assistant provides general information only and should not be considered
141
- legal advice. For specific legal matters, please consult a qualified legal professional.
142
-
 
 
143
  **Model:** [invincibleambuj/Ambuj-Tripathi-Indian-Legal-Llama-GGUF](https://huggingface.co/invincibleambuj/Ambuj-Tripathi-Indian-Legal-Llama-GGUF)
144
  """
145
  )
146
-
147
- # Set up event handlers
148
- msg.submit(chat_with_legal_ai, [msg, chatbot], [chatbot])
149
- submit.click(chat_with_legal_ai, [msg, chatbot], [chatbot])
150
- msg.submit(lambda: "", None, [msg])
151
- submit.click(lambda: "", None, [msg])
152
- clear.click(lambda: None, None, [chatbot])
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
- # Pre-load the model to avoid delays on first query
162
- print("\nPre-loading model (this may take a few minutes on first run)...")
163
- load_model()
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
  )