Update app.py
Browse files
app.py
CHANGED
|
@@ -1,260 +1,193 @@
|
|
| 1 |
-
import PyPDF2
|
| 2 |
-
import re
|
| 3 |
-
from sentence_transformers import SentenceTransformer
|
| 4 |
-
import faiss
|
| 5 |
-
from langchain.agents import initialize_agent, AgentType,Tool
|
| 6 |
-
from langchain.schema import HumanMessage
|
| 7 |
-
from langchain_google_genai import ChatGoogleGenerativeAI
|
| 8 |
-
import gradio as gr
|
| 9 |
-
import os
|
| 10 |
-
import pytesseract
|
| 11 |
-
from PIL import Image
|
| 12 |
-
pytesseract.pytesseract.tesseract_cmd = r"tesseract.exe"
|
| 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 |
-
for
|
| 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 |
-
|
| 152 |
-
|
| 153 |
-
|
| 154 |
-
|
| 155 |
-
|
| 156 |
-
|
| 157 |
-
|
| 158 |
-
|
| 159 |
-
|
| 160 |
-
|
| 161 |
-
|
| 162 |
-
|
| 163 |
-
|
| 164 |
-
|
| 165 |
-
|
| 166 |
-
|
| 167 |
-
)
|
| 168 |
-
|
| 169 |
-
|
| 170 |
-
|
| 171 |
-
|
| 172 |
-
|
| 173 |
-
|
| 174 |
-
|
| 175 |
-
|
| 176 |
-
|
| 177 |
-
|
| 178 |
-
)
|
| 179 |
-
|
| 180 |
-
|
| 181 |
-
|
| 182 |
-
|
| 183 |
-
|
| 184 |
-
|
| 185 |
-
|
| 186 |
-
|
| 187 |
-
|
| 188 |
-
|
| 189 |
-
|
| 190 |
-
|
| 191 |
-
|
| 192 |
-
|
| 193 |
-
]
|
| 194 |
-
)
|
| 195 |
-
else:
|
| 196 |
-
# If no image, only pass the text
|
| 197 |
-
message = HumanMessage(content=[{"type": "text", "text": query}])
|
| 198 |
-
|
| 199 |
-
# Invoke the model with the multimodal message
|
| 200 |
-
result = agent.invoke([message])
|
| 201 |
-
response = result['output']
|
| 202 |
-
intermediate_steps = result.get('intermediate_steps', [])
|
| 203 |
-
|
| 204 |
-
thought_process = ""
|
| 205 |
-
for action, observation in intermediate_steps:
|
| 206 |
-
thought_process += f"**Thought:** {action.log}\n"
|
| 207 |
-
thought_process += f"**Action:** {action.tool}\n"
|
| 208 |
-
thought_process += f"**Observation:** {observation}\n\n"
|
| 209 |
-
|
| 210 |
-
return response, thought_process.strip()
|
| 211 |
-
# Step 5: Gradio Interface
|
| 212 |
-
from gradio import ChatMessage
|
| 213 |
-
def chatbot_interface(messages,prompt):
|
| 214 |
-
response, thought_process = chatbot_response(prompt)
|
| 215 |
-
#messages.append(ChatMessage(role="user", content=prompt))
|
| 216 |
-
|
| 217 |
-
for x in prompt["files"]:
|
| 218 |
-
messages.append(ChatMessage(role="user", content={"path": x, "mime_type": "image/png"}))
|
| 219 |
-
if prompt["text"] is not None:
|
| 220 |
-
messages.append(ChatMessage(role="user", content=prompt['text']))
|
| 221 |
-
if thought_process:
|
| 222 |
-
messages.append(ChatMessage(role="assistant", content=thought_process,metadata={"title": "🧠 Thought Process"}))
|
| 223 |
-
messages.append(ChatMessage(role="assistant", content=response))
|
| 224 |
-
|
| 225 |
-
return messages, gr.MultimodalTextbox(value=None, interactive=True)
|
| 226 |
-
|
| 227 |
-
|
| 228 |
-
def vote(data: gr.LikeData):
|
| 229 |
-
if data.liked:
|
| 230 |
-
print("You upvoted this response: " + data.value)
|
| 231 |
-
else:
|
| 232 |
-
print("You downvoted this response: " + data.value)
|
| 233 |
-
|
| 234 |
-
with gr.Blocks(theme=gr.themes.Soft()) as iface:
|
| 235 |
-
|
| 236 |
-
gr.Markdown(
|
| 237 |
-
"""
|
| 238 |
-
<div style="font-size: 24px; font-weight: bold; color: #333;">
|
| 239 |
-
DoJ Chatbot
|
| 240 |
-
</div>
|
| 241 |
-
<div style="font-size: 16px; color: #555;">
|
| 242 |
-
Ask questions related to the Department of Justice.
|
| 243 |
-
</div>
|
| 244 |
-
"""
|
| 245 |
-
)
|
| 246 |
-
chatbot = gr.Chatbot(type="messages",avatar_images=("user.jpeg", "logo.jpeg"), bubble_full_width=True) # Chatbot component to display conversation history
|
| 247 |
-
query_input = gr.MultimodalTextbox(interactive=True,
|
| 248 |
-
placeholder="Enter message or upload file...", show_label=False)
|
| 249 |
-
submit_button = gr.Button("Send")
|
| 250 |
-
|
| 251 |
-
submit_button.click(chatbot_interface, [chatbot, query_input], [chatbot, query_input])
|
| 252 |
-
query_input.submit(chatbot_interface, [chatbot, query_input], [chatbot,query_input])
|
| 253 |
-
|
| 254 |
-
chatbot.like(vote, None, None) # Adding like/dislike functionality to the chatbot
|
| 255 |
-
|
| 256 |
-
|
| 257 |
-
iface.launch(
|
| 258 |
-
show_error=True,
|
| 259 |
-
prevent_thread_lock=True
|
| 260 |
)
|
|
|
|
| 1 |
+
import PyPDF2
|
| 2 |
+
import re
|
| 3 |
+
from sentence_transformers import SentenceTransformer
|
| 4 |
+
import faiss
|
| 5 |
+
from langchain.agents import initialize_agent, AgentType,Tool
|
| 6 |
+
from langchain.schema import HumanMessage
|
| 7 |
+
from langchain_google_genai import ChatGoogleGenerativeAI
|
| 8 |
+
import gradio as gr
|
| 9 |
+
import os
|
| 10 |
+
import pytesseract
|
| 11 |
+
from PIL import Image
|
| 12 |
+
pytesseract.pytesseract.tesseract_cmd = r"tesseract.exe"
|
| 13 |
+
|
| 14 |
+
model = SentenceTransformer('sentence-transformers/all-MiniLM-L6-v2')
|
| 15 |
+
|
| 16 |
+
embeddings = model.encode(flattened_data)
|
| 17 |
+
index = faiss.read_index('IPC_index.faiss')
|
| 18 |
+
index2 = faiss.read_index('CrPC_index.faiss')
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
# Step 3: Retrieval with Citations using PDF filename
|
| 22 |
+
def retrieve_info_with_citation(query, top_k=5):
|
| 23 |
+
query_embedding = model.encode([query])
|
| 24 |
+
D, I = index.search(query_embedding, k=top_k)
|
| 25 |
+
|
| 26 |
+
results = []
|
| 27 |
+
for i in range(min(top_k, len(I[0]))):
|
| 28 |
+
if D[0][i] < 1.0: # Relevance threshold
|
| 29 |
+
chunk_index = I[0][i]
|
| 30 |
+
citation = f"Source: IPC"
|
| 31 |
+
results.append((match, citation))
|
| 32 |
+
else:
|
| 33 |
+
break
|
| 34 |
+
|
| 35 |
+
if results:
|
| 36 |
+
return results
|
| 37 |
+
else:
|
| 38 |
+
return [("I'm sorry, I couldn't find relevant information.", "Source: N/A")]
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def retrieve_info_with_citation2(query, top_k=5):
|
| 42 |
+
query_embedding = model.encode([query])
|
| 43 |
+
D, I = index2.search(query_embedding, k=top_k)
|
| 44 |
+
|
| 45 |
+
results = []
|
| 46 |
+
for i in range(min(top_k, len(I[0]))):
|
| 47 |
+
if D[0][i] < 1.0: # Relevance threshold
|
| 48 |
+
chunk_index = I[0][i]
|
| 49 |
+
citation = f"Source: CrPC"
|
| 50 |
+
results.append((match, citation))
|
| 51 |
+
else:
|
| 52 |
+
break
|
| 53 |
+
|
| 54 |
+
if results:
|
| 55 |
+
return results
|
| 56 |
+
else:
|
| 57 |
+
return [("I'm sorry, I couldn't find relevant information.", "Source: N/A")]
|
| 58 |
+
|
| 59 |
+
def retrieve_info(query):
|
| 60 |
+
results = retrieve_info_with_citation(query)
|
| 61 |
+
formatted_results = "\n\n".join([f"{i+1}. {match}\n{citation}" for i, (match, citation) in enumerate(results)])
|
| 62 |
+
return formatted_results
|
| 63 |
+
|
| 64 |
+
def retrieve_info2(query):
|
| 65 |
+
results = retrieve_info_with_citation2(query)
|
| 66 |
+
formatted_results = "\n\n".join([f"{i+1}. {match}\n{citation}" for i, (match, citation) in enumerate(results)])
|
| 67 |
+
return formatted_results
|
| 68 |
+
|
| 69 |
+
ipc_tool = Tool(
|
| 70 |
+
name="IPC Information Retrieval",
|
| 71 |
+
func=retrieve_info,
|
| 72 |
+
description="Retrieve information from the Indian Penal Code Related to query keyword(s)."
|
| 73 |
+
)
|
| 74 |
+
|
| 75 |
+
crpc_tool=Tool(
|
| 76 |
+
name="CrPC Information Retrieval",
|
| 77 |
+
func=retrieve_info2,
|
| 78 |
+
description="Retrieve information from the Code of Criminal Procedure(CrPC) Related to query keyword(s)."
|
| 79 |
+
)
|
| 80 |
+
llm = ChatGoogleGenerativeAI(
|
| 81 |
+
model="gemini-1.5-pro",
|
| 82 |
+
temperature=0.25,
|
| 83 |
+
max_tokens=None,
|
| 84 |
+
timeout=None,
|
| 85 |
+
max_retries=2,
|
| 86 |
+
prompt_template="""
|
| 87 |
+
You are a highly specialized legal assistant with deep knowledge of the Indian Penal Code (IPC).
|
| 88 |
+
Your primary task is to retrieve and summarize legal information accurately from the IPC.pdf document provided to you.
|
| 89 |
+
Your responses should be highly specific, fact-based, and free from any speculation or hallucinations.
|
| 90 |
+
Always cite the exact section from the IPC when providing an answer.
|
| 91 |
+
If the information is not available in the document, clearly state that and do not make any assumptions.
|
| 92 |
+
|
| 93 |
+
Example task: "What is the punishment for theft according to the IPC?"
|
| 94 |
+
Example response: "According to Section 379 of the IPC, the punishment for theft is imprisonment of either description for a term which may extend to three years, or with fine, or with both."
|
| 95 |
+
|
| 96 |
+
Task: {{query}}
|
| 97 |
+
|
| 98 |
+
Response:
|
| 99 |
+
""",
|
| 100 |
+
)
|
| 101 |
+
|
| 102 |
+
agent_tools = [ipc_tool,crpc_tool]
|
| 103 |
+
|
| 104 |
+
agent = initialize_agent(
|
| 105 |
+
tools=agent_tools,
|
| 106 |
+
llm=llm,
|
| 107 |
+
agent=AgentType.STRUCTURED_CHAT_ZERO_SHOT_REACT_DESCRIPTION,
|
| 108 |
+
verbose=True,
|
| 109 |
+
return_intermediate_steps=True,
|
| 110 |
+
handle_parsing_errors=True,
|
| 111 |
+
)
|
| 112 |
+
def encode_image_to_base64(image_path):
|
| 113 |
+
return pytesseract.image_to_string(Image.open(image_path))
|
| 114 |
+
def chatbot_response(query):
|
| 115 |
+
if query.get('files'):
|
| 116 |
+
# Encode image to base64
|
| 117 |
+
image_data=""
|
| 118 |
+
for x in range(len(query["files"])):
|
| 119 |
+
image_data += f"{x}. "+encode_image_to_base64(query["files"][x]) +"\n"
|
| 120 |
+
|
| 121 |
+
# Create a multimodal message with both text and image data
|
| 122 |
+
message = HumanMessage(
|
| 123 |
+
content=[
|
| 124 |
+
{"type": "text", "text": query['text'] +" System :Image(s) was added to this prompt by this user. Text Extracted from this image (Some words may be misspelled ,Use your understanding ):"+image_data}, # Add text input
|
| 125 |
+
|
| 126 |
+
]
|
| 127 |
+
)
|
| 128 |
+
else:
|
| 129 |
+
# If no image, only pass the text
|
| 130 |
+
message = HumanMessage(content=[{"type": "text", "text": query}])
|
| 131 |
+
|
| 132 |
+
# Invoke the model with the multimodal message
|
| 133 |
+
result = agent.invoke([message])
|
| 134 |
+
response = result['output']
|
| 135 |
+
intermediate_steps = result.get('intermediate_steps', [])
|
| 136 |
+
|
| 137 |
+
thought_process = ""
|
| 138 |
+
for action, observation in intermediate_steps:
|
| 139 |
+
thought_process += f"**Thought:** {action.log}\n"
|
| 140 |
+
thought_process += f"**Action:** {action.tool}\n"
|
| 141 |
+
thought_process += f"**Observation:** {observation}\n\n"
|
| 142 |
+
|
| 143 |
+
return response, thought_process.strip()
|
| 144 |
+
# Step 5: Gradio Interface
|
| 145 |
+
from gradio import ChatMessage
|
| 146 |
+
def chatbot_interface(messages,prompt):
|
| 147 |
+
response, thought_process = chatbot_response(prompt)
|
| 148 |
+
#messages.append(ChatMessage(role="user", content=prompt))
|
| 149 |
+
|
| 150 |
+
for x in prompt["files"]:
|
| 151 |
+
messages.append(ChatMessage(role="user", content={"path": x, "mime_type": "image/png"}))
|
| 152 |
+
if prompt["text"] is not None:
|
| 153 |
+
messages.append(ChatMessage(role="user", content=prompt['text']))
|
| 154 |
+
if thought_process:
|
| 155 |
+
messages.append(ChatMessage(role="assistant", content=thought_process,metadata={"title": "🧠 Thought Process"}))
|
| 156 |
+
messages.append(ChatMessage(role="assistant", content=response))
|
| 157 |
+
|
| 158 |
+
return messages, gr.MultimodalTextbox(value=None, interactive=True)
|
| 159 |
+
|
| 160 |
+
|
| 161 |
+
def vote(data: gr.LikeData):
|
| 162 |
+
if data.liked:
|
| 163 |
+
print("You upvoted this response: " + data.value)
|
| 164 |
+
else:
|
| 165 |
+
print("You downvoted this response: " + data.value)
|
| 166 |
+
|
| 167 |
+
with gr.Blocks(theme=gr.themes.Soft()) as iface:
|
| 168 |
+
|
| 169 |
+
gr.Markdown(
|
| 170 |
+
"""
|
| 171 |
+
<div style="font-size: 24px; font-weight: bold; color: #333;">
|
| 172 |
+
DoJ Chatbot
|
| 173 |
+
</div>
|
| 174 |
+
<div style="font-size: 16px; color: #555;">
|
| 175 |
+
Ask questions related to the Department of Justice.
|
| 176 |
+
</div>
|
| 177 |
+
"""
|
| 178 |
+
)
|
| 179 |
+
chatbot = gr.Chatbot(type="messages",avatar_images=("user.jpeg", "logo.jpeg"), bubble_full_width=True) # Chatbot component to display conversation history
|
| 180 |
+
query_input = gr.MultimodalTextbox(interactive=True,
|
| 181 |
+
placeholder="Enter message or upload file...", show_label=False)
|
| 182 |
+
submit_button = gr.Button("Send")
|
| 183 |
+
|
| 184 |
+
submit_button.click(chatbot_interface, [chatbot, query_input], [chatbot, query_input])
|
| 185 |
+
query_input.submit(chatbot_interface, [chatbot, query_input], [chatbot,query_input])
|
| 186 |
+
|
| 187 |
+
chatbot.like(vote, None, None) # Adding like/dislike functionality to the chatbot
|
| 188 |
+
|
| 189 |
+
|
| 190 |
+
iface.launch(
|
| 191 |
+
show_error=True,
|
| 192 |
+
prevent_thread_lock=True
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 193 |
)
|