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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from llama_index.core.response.notebook_utils import display_source_node
|
| 2 |
+
from llama_index.embeddings.azure_openai import AzureOpenAIEmbedding
|
| 3 |
+
from llama_index.core.query_engine import RetrieverQueryEngine
|
| 4 |
+
from llama_index.core import VectorStoreIndex, ServiceContext
|
| 5 |
+
from llama_index.core.node_parser import SimpleNodeParser
|
| 6 |
+
from llama_index.llms.azure_openai import AzureOpenAI
|
| 7 |
+
from llama_index.readers.file import PDFReader
|
| 8 |
+
from llama_index.core.schema import IndexNode
|
| 9 |
+
from llama_index.core import Document
|
| 10 |
+
|
| 11 |
+
from langchain_core.messages import HumanMessage
|
| 12 |
+
from langchain_openai import AzureChatOpenAI
|
| 13 |
+
from langchain.text_splitter import CharacterTextSplitter
|
| 14 |
+
from langchain.chains import ConversationChain
|
| 15 |
+
from langchain.memory import ConversationBufferWindowMemory
|
| 16 |
+
from langchain.prompts import PromptTemplate
|
| 17 |
+
|
| 18 |
+
from sentence_transformers import util
|
| 19 |
+
from openai import AzureOpenAI
|
| 20 |
+
from bs4 import BeautifulSoup
|
| 21 |
+
import pyshorteners
|
| 22 |
+
import gradio as gr
|
| 23 |
+
import pandas as pd
|
| 24 |
+
import numpy as np
|
| 25 |
+
import warnings
|
| 26 |
+
import pickle
|
| 27 |
+
import string
|
| 28 |
+
import json
|
| 29 |
+
import time
|
| 30 |
+
import ast
|
| 31 |
+
import os
|
| 32 |
+
import re
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
client = AzureOpenAI(
|
| 36 |
+
azure_endpoint = "https://moj-ada3.openai.azure.com/",
|
| 37 |
+
api_key="9639718f1a7d478a9313d2b2aeb5dacc",
|
| 38 |
+
api_version="2024-02-15-preview"
|
| 39 |
+
)
|
| 40 |
+
df = pd.read_csv("/content/drive/MyDrive/MOJ/Legislations/Data.csv")
|
| 41 |
+
|
| 42 |
+
warnings.filterwarnings("ignore")
|
| 43 |
+
|
| 44 |
+
def extract_title(text):
|
| 45 |
+
if '-' in text:
|
| 46 |
+
return text.split('-')[-1].strip()
|
| 47 |
+
elif '–' in text:
|
| 48 |
+
return text.split('–')[-1].strip()
|
| 49 |
+
else:
|
| 50 |
+
return ""
|
| 51 |
+
|
| 52 |
+
def remove_title(text):
|
| 53 |
+
if '-' in text:
|
| 54 |
+
return text.split('-')[0].strip()
|
| 55 |
+
elif '–' in text:
|
| 56 |
+
return text.split('–')[0].strip()
|
| 57 |
+
else:
|
| 58 |
+
return text
|
| 59 |
+
|
| 60 |
+
def get_articles(i):
|
| 61 |
+
try:
|
| 62 |
+
|
| 63 |
+
result_df = pd.DataFrame(columns=['Header', 'Text','Comment'])
|
| 64 |
+
|
| 65 |
+
#html = df[df['Id'] == 35850]['HTML'][621]
|
| 66 |
+
html = df['HTML'][i]
|
| 67 |
+
|
| 68 |
+
soup = BeautifulSoup(html, 'html.parser')
|
| 69 |
+
|
| 70 |
+
divs = soup.find_all('div')
|
| 71 |
+
|
| 72 |
+
h_class = 'x__1575___1604___1605___1575___1583___1577_14'
|
| 73 |
+
|
| 74 |
+
x = 0
|
| 75 |
+
|
| 76 |
+
txt = ''
|
| 77 |
+
|
| 78 |
+
headers = ast.literal_eval(df['Subjects'][i])
|
| 79 |
+
|
| 80 |
+
for d in divs:
|
| 81 |
+
try:
|
| 82 |
+
if d.get('class') is None:
|
| 83 |
+
d_class = d.find('div').get('class')[0]
|
| 84 |
+
d_text = d.find('div').text.replace('\n\n',' ').replace('\n',' ')
|
| 85 |
+
else:
|
| 86 |
+
d_class = d.get('class')[0]
|
| 87 |
+
d_text = d.text.replace('\n\n',' ').replace('\n',' ')
|
| 88 |
+
|
| 89 |
+
if h_class not in d_class:
|
| 90 |
+
txt += " " +d_text
|
| 91 |
+
else:
|
| 92 |
+
if x == 0:
|
| 93 |
+
result_df = pd.concat([result_df, pd.DataFrame({'Header': ['Desc'], 'Text': [txt]})], ignore_index=True)
|
| 94 |
+
txt = ''
|
| 95 |
+
x += 1
|
| 96 |
+
else:
|
| 97 |
+
result_df = pd.concat([result_df, pd.DataFrame({'Header': [headers[x-1]], 'Text': [txt]})], ignore_index=True)
|
| 98 |
+
txt = ''
|
| 99 |
+
x += 1
|
| 100 |
+
except:
|
| 101 |
+
pass
|
| 102 |
+
result_df = pd.concat([result_df, pd.DataFrame({'Header': [headers[x-1]], 'Text': [txt]})], ignore_index=True)
|
| 103 |
+
|
| 104 |
+
divs_with_showfn = soup.find_all('div', id=lambda x: x and x.startswith('fn'))
|
| 105 |
+
|
| 106 |
+
for r in range (result_df.shape[0]):
|
| 107 |
+
article = result_df['Header'][r].split('-')[0].strip()
|
| 108 |
+
|
| 109 |
+
for n,d in enumerate(divs_with_showfn):
|
| 110 |
+
edit = d.text.replace('\n\n',' ').replace('\n',' ')
|
| 111 |
+
|
| 112 |
+
match = edit[:35]
|
| 113 |
+
|
| 114 |
+
if (article.replace("الأولى","الاولى") in match.replace("الأولى","الاولى")) and ("القديم" in match) :
|
| 115 |
+
#result_df['Text'][r] += "\n\n-تعديل-\n\n" + edit
|
| 116 |
+
result_df['Comment'][r] = edit
|
| 117 |
+
|
| 118 |
+
if divs_with_showfn:
|
| 119 |
+
|
| 120 |
+
firstindex = divs_with_showfn[0].text.replace('\n\n',' ').replace('\n',' ')
|
| 121 |
+
|
| 122 |
+
last_e = result_df.shape[0] -1
|
| 123 |
+
|
| 124 |
+
mada = result_df['Text'][last_e]
|
| 125 |
+
|
| 126 |
+
if firstindex in mada :
|
| 127 |
+
result_df['Text'][last_e] = (mada.split(firstindex)[0])
|
| 128 |
+
|
| 129 |
+
#result_df['Title'] = result_df['Header'].apply(extract_title)
|
| 130 |
+
#result_df['Header'] = result_df['Header'].apply(remove_title)
|
| 131 |
+
return result_df.reset_index(drop=True)
|
| 132 |
+
|
| 133 |
+
except:
|
| 134 |
+
pass
|
| 135 |
+
|
| 136 |
+
|
| 137 |
+
|
| 138 |
+
with open('/content/drive/MyDrive/MOJ/Legislations/BaseIndex/ada_base_index_small.pkl', 'rb') as f:
|
| 139 |
+
base_index_ = pickle.load(f)
|
| 140 |
+
|
| 141 |
+
azure_endpoint = "https://moj-ada3.openai.azure.com/"
|
| 142 |
+
api_key="9639718f1a7d478a9313d2b2aeb5dacc"
|
| 143 |
+
api_version="2024-02-15-preview"
|
| 144 |
+
deployment = "gpt-35-turbo-16k"
|
| 145 |
+
|
| 146 |
+
|
| 147 |
+
os.environ["AZURE_OPENAI_API_KEY"] = api_key
|
| 148 |
+
os.environ["AZURE_OPENAI_ENDPOINT"] = azure_endpoint
|
| 149 |
+
|
| 150 |
+
llm_chain = AzureChatOpenAI(
|
| 151 |
+
openai_api_version= api_version,
|
| 152 |
+
azure_deployment= deployment,
|
| 153 |
+
|
| 154 |
+
)
|
| 155 |
+
|
| 156 |
+
|
| 157 |
+
|
| 158 |
+
client = AzureOpenAI(
|
| 159 |
+
azure_endpoint = "https://moj-ada3.openai.azure.com/",
|
| 160 |
+
api_key="9639718f1a7d478a9313d2b2aeb5dacc",
|
| 161 |
+
api_version="2024-02-15-preview"
|
| 162 |
+
)
|
| 163 |
+
|
| 164 |
+
|
| 165 |
+
SYS_TEMPLATE = """
|
| 166 |
+
The following is a friendly conversation between a human and an AI.
|
| 167 |
+
AI must follow the Instructions below
|
| 168 |
+
|
| 169 |
+
Instructions:
|
| 170 |
+
- AI is an Arabic legal expert in the UAE.
|
| 171 |
+
- AI shall always reply in Arabic.
|
| 172 |
+
- AI shall never reply in English.
|
| 173 |
+
- AI shall not repeat any questions or rephrase them.
|
| 174 |
+
- AI shall ask a presise question if needed to determine the user's intent.
|
| 175 |
+
- AI shall only ask a maximum of one question if needed to human and then determine his intent.
|
| 176 |
+
- AI shall only reply to questions related to law subjects.
|
| 177 |
+
- AI shall not answer or explain or give any advice to user questions.
|
| 178 |
+
- AI MUST not provide any details ever from given information, only use it to determine the desired intent.
|
| 179 |
+
- AI shall use the given information only to ask precise and short question to determine user intent.
|
| 180 |
+
- AI shall determine the user desired intent with the minimum number of questions possible.
|
| 181 |
+
- AI shall not ask the user again after the user confirms on any question.
|
| 182 |
+
- AI shall decide user intent if the user's query contains enough details without asiking him any more questions.
|
| 183 |
+
- AI shall decide which suits query better if user wants a general info or says give me anything.
|
| 184 |
+
- AI's only purpose is to determine the intended topic from the user.
|
| 185 |
+
- AI shall choose node with the best description matching with the human's intent.
|
| 186 |
+
- AI shall always end the conversation with the returns below as long as the user question matches with given info.
|
| 187 |
+
- if AI asks a question and human says he dosent know the spesific law or article then AI shall determine and end the conversation with the returns below.
|
| 188 |
+
- if Human asks a question (Is it permissible (هل يجوز)) AI should find the best node that can answer the question with yes or no.
|
| 189 |
+
- AI shall end the conversation when the user confirms his intent and return as mentioned below from node's metadata.
|
| 190 |
+
- AI shall mention every detail the user wants in the userintent returns.
|
| 191 |
+
- AI MUST include the five digits number in the returns.
|
| 192 |
+
- AI shall never leave the ID in returns empty it should always be five digits.
|
| 193 |
+
|
| 194 |
+
Returns:
|
| 195 |
+
[
|
| 196 |
+
ID: five didgits number ,
|
| 197 |
+
Topic: ,
|
| 198 |
+
userIntent :
|
| 199 |
+
]
|
| 200 |
+
|
| 201 |
+
Information:
|
| 202 |
+
{}
|
| 203 |
+
"""
|
| 204 |
+
sys_prompt_intent = """
|
| 205 |
+
The following is a friendly conversation between a human and an AI.
|
| 206 |
+
AI must follow the Instructions below
|
| 207 |
+
|
| 208 |
+
Instructions:
|
| 209 |
+
- AI is an Arabic legal expert in the UAE.
|
| 210 |
+
- AI shall always reply in Arabic.
|
| 211 |
+
- AI shall never reply in English.
|
| 212 |
+
- AI shall answer the human questions based on the content provided.
|
| 213 |
+
- AI shall answer only from within the Content provided , and NOT from outside.
|
| 214 |
+
- AI shall answer using the exact text in content and not improvise.
|
| 215 |
+
- AI shall NOT improvise , or give any advices nor explanation.
|
| 216 |
+
- AI shall not provide any links to user and tell him to search in it, it should always provide the required info.
|
| 217 |
+
- AI shall always answer to the user query in a professional and informative way inculding all the details.
|
| 218 |
+
- ِAI shall answer every question asked in the conversation from human in a detailed way.
|
| 219 |
+
- AI shall include in the answer the article number (رقم المادة)
|
| 220 |
+
|
| 221 |
+
Content:
|
| 222 |
+
{}
|
| 223 |
+
"""
|
| 224 |
+
|
| 225 |
+
|
| 226 |
+
punctuations = string.punctuation
|
| 227 |
+
|
| 228 |
+
def generate_embeddings(text, model="ada3_small"):
|
| 229 |
+
|
| 230 |
+
return client.embeddings.create(input = [text], model=model).data[0].embedding
|
| 231 |
+
|
| 232 |
+
base_retriever = base_index_.as_retriever(similarity_top_k=10)
|
| 233 |
+
|
| 234 |
+
def query_df(query):
|
| 235 |
+
|
| 236 |
+
retrievals = base_retriever.retrieve(
|
| 237 |
+
query
|
| 238 |
+
)
|
| 239 |
+
|
| 240 |
+
related_texts = []
|
| 241 |
+
metadatas = []
|
| 242 |
+
|
| 243 |
+
info = ''
|
| 244 |
+
for i,r in enumerate(retrievals):
|
| 245 |
+
article_index = df[df['Id'] == int(r.metadata['ID'])].index[0]
|
| 246 |
+
|
| 247 |
+
article_df = get_articles(article_index)
|
| 248 |
+
|
| 249 |
+
article_intended = article_df[article_df['Header'] == r.metadata['Article']].reset_index()
|
| 250 |
+
|
| 251 |
+
article_text = article_intended['Text'][0]
|
| 252 |
+
|
| 253 |
+
if len(article_text) > 800 :
|
| 254 |
+
related_txt = related_text(article_text, query, 800)[0]
|
| 255 |
+
|
| 256 |
+
else:
|
| 257 |
+
related_txt = article_text
|
| 258 |
+
|
| 259 |
+
meta = r.metadata
|
| 260 |
+
|
| 261 |
+
meta = {
|
| 262 |
+
'Description': meta['Description'],
|
| 263 |
+
'ID': meta['ID'],
|
| 264 |
+
#'Title': meta['Title']
|
| 265 |
+
}
|
| 266 |
+
|
| 267 |
+
info += f"Node Number {i+1} : {related_txt} -- Node MetaData : {meta}\n"
|
| 268 |
+
|
| 269 |
+
return info
|
| 270 |
+
|
| 271 |
+
from llama_index.core.vector_stores.types import ExactMatchFilter, MetadataFilters
|
| 272 |
+
|
| 273 |
+
def query_df_filtered(query,id):
|
| 274 |
+
|
| 275 |
+
filters = MetadataFilters(filters=[
|
| 276 |
+
ExactMatchFilter(
|
| 277 |
+
key="ID",
|
| 278 |
+
value=str(id)
|
| 279 |
+
)
|
| 280 |
+
])
|
| 281 |
+
|
| 282 |
+
b_retriever = base_index_.as_retriever(similarity_top_k=3, filters=filters)
|
| 283 |
+
|
| 284 |
+
retrievals = b_retriever.retrieve(
|
| 285 |
+
query
|
| 286 |
+
)
|
| 287 |
+
|
| 288 |
+
related_texts = []
|
| 289 |
+
metadatas = []
|
| 290 |
+
|
| 291 |
+
info_filtered = ''
|
| 292 |
+
|
| 293 |
+
for i,r in enumerate(retrievals):
|
| 294 |
+
|
| 295 |
+
article_index = df[df['Id'] == int(r.metadata['ID'])].index[0]
|
| 296 |
+
|
| 297 |
+
article_df = get_articles(article_index)
|
| 298 |
+
|
| 299 |
+
article_intended = article_df[article_df['Header'] == r.metadata['Article']].reset_index()
|
| 300 |
+
|
| 301 |
+
article_text = article_intended['Text'][0]
|
| 302 |
+
|
| 303 |
+
if len(article_text) > 5000 :
|
| 304 |
+
related_txt = related_text(article_text, query, 5000)[0]
|
| 305 |
+
|
| 306 |
+
else:
|
| 307 |
+
related_txt = article_text
|
| 308 |
+
|
| 309 |
+
meta = r.metadata
|
| 310 |
+
|
| 311 |
+
meta = {
|
| 312 |
+
#'Title': meta['Title'],
|
| 313 |
+
'Header' : meta['Article']
|
| 314 |
+
}
|
| 315 |
+
|
| 316 |
+
info_filtered += f"Article {meta} : {related_txt} \n"
|
| 317 |
+
|
| 318 |
+
return info_filtered
|
| 319 |
+
|
| 320 |
+
|
| 321 |
+
def related_text(txt, q, size):
|
| 322 |
+
|
| 323 |
+
text_splitter = CharacterTextSplitter(
|
| 324 |
+
separator = " ",
|
| 325 |
+
chunk_size = size,
|
| 326 |
+
chunk_overlap = 50,
|
| 327 |
+
length_function = len,
|
| 328 |
+
)
|
| 329 |
+
|
| 330 |
+
chunks = text_splitter.split_text(txt)
|
| 331 |
+
|
| 332 |
+
embeddings = [generate_embeddings(chunk) for chunk in chunks]
|
| 333 |
+
|
| 334 |
+
def similarity(q):
|
| 335 |
+
query_embedding = generate_embeddings(q)
|
| 336 |
+
|
| 337 |
+
similarity_scores = util.cos_sim(query_embedding, embeddings)
|
| 338 |
+
|
| 339 |
+
sorted_indices = np.argsort(-similarity_scores)
|
| 340 |
+
|
| 341 |
+
indexes = []
|
| 342 |
+
|
| 343 |
+
indexes.append(int(sorted_indices[0][0]))
|
| 344 |
+
|
| 345 |
+
new_chunks = [chunks[i] for i in indexes]
|
| 346 |
+
|
| 347 |
+
ans = '\n'.join(new_chunks)
|
| 348 |
+
return new_chunks
|
| 349 |
+
|
| 350 |
+
return similarity(q)
|
| 351 |
+
|
| 352 |
+
|
| 353 |
+
def format_messages(message_list):
|
| 354 |
+
formatted_messages = []
|
| 355 |
+
current_speaker = None
|
| 356 |
+
|
| 357 |
+
for message in message_list:
|
| 358 |
+
if 'HumanMessage' in str(type(message)):
|
| 359 |
+
if current_speaker != 'Human':
|
| 360 |
+
current_speaker = 'Human'
|
| 361 |
+
formatted_messages.append(f'{current_speaker} : {message.content}')
|
| 362 |
+
else:
|
| 363 |
+
formatted_messages[-1] += f' {message.content}'
|
| 364 |
+
elif 'AIMessage' in str(type(message)):
|
| 365 |
+
if current_speaker != 'AI':
|
| 366 |
+
current_speaker = 'AI'
|
| 367 |
+
formatted_messages.append(f'{current_speaker} : {message.content}')
|
| 368 |
+
else:
|
| 369 |
+
formatted_messages[-1] += f' {message.content}'
|
| 370 |
+
|
| 371 |
+
return '\n'.join(formatted_messages)
|
| 372 |
+
|
| 373 |
+
|
| 374 |
+
def memory_prompt():
|
| 375 |
+
global history
|
| 376 |
+
if len (memory.chat_memory.messages) <= 8 :
|
| 377 |
+
|
| 378 |
+
chat_history_lines = format_messages(memory.chat_memory.messages)
|
| 379 |
+
else:
|
| 380 |
+
|
| 381 |
+
chat_history_lines = format_messages(memory.chat_memory.messages[8:])
|
| 382 |
+
prompt = f"""
|
| 383 |
+
Current conversation:
|
| 384 |
+
{chat_history_lines}
|
| 385 |
+
"""
|
| 386 |
+
return prompt
|
| 387 |
+
|
| 388 |
+
def update_prompt(human, ai):
|
| 389 |
+
memory.save_context({"input": human}, {"output": ai})
|
| 390 |
+
prompt = memory_prompt()
|
| 391 |
+
#print(prompt)
|
| 392 |
+
return prompt
|
| 393 |
+
|
| 394 |
+
shortener = pyshorteners.Shortener()
|
| 395 |
+
|
| 396 |
+
short_url = shortener.tinyurl.short(df['Links'][0])
|
| 397 |
+
|
| 398 |
+
mod ="gpt-35-turbo-16k"
|
| 399 |
+
|
| 400 |
+
memory = ConversationBufferWindowMemory()
|
| 401 |
+
x=0
|
| 402 |
+
info = ''
|
| 403 |
+
history = ''
|
| 404 |
+
is_locked = False
|
| 405 |
+
is_found = False
|
| 406 |
+
new_session = False
|
| 407 |
+
is_new = False
|
| 408 |
+
|
| 409 |
+
captured_ID = ''
|
| 410 |
+
user_intent_text = ''
|
| 411 |
+
full_ans = ''
|
| 412 |
+
|
| 413 |
+
prompt = f"""
|
| 414 |
+
Current conversation:
|
| 415 |
+
"""
|
| 416 |
+
|
| 417 |
+
def clean_ans (answer):
|
| 418 |
+
if answer.startswith("Assistant:"):
|
| 419 |
+
answer = answer[len("Assistant:"):]
|
| 420 |
+
|
| 421 |
+
elif answer.startswith("AI:"):
|
| 422 |
+
answer = answer[len("AI:"):]
|
| 423 |
+
|
| 424 |
+
elif answer.startswith("AI :"):
|
| 425 |
+
answer = answer[len("AI :"):]
|
| 426 |
+
|
| 427 |
+
# if answer.startswith("Assistant:"):
|
| 428 |
+
# answer = answer[len("Assistant:"):]
|
| 429 |
+
# answer = answer[:(len(answer)-len("Assistant:"))]
|
| 430 |
+
|
| 431 |
+
# elif answer.startswith("AI:"):
|
| 432 |
+
# answer = answer[len("AI:"):]
|
| 433 |
+
# answer = answer[:(len(answer)-len("AI:"))]
|
| 434 |
+
|
| 435 |
+
# elif answer.startswith("AI :"):
|
| 436 |
+
# answer = answer[len("AI :"):]
|
| 437 |
+
# answer = answer[:(len(answer)-len("AI :"))]
|
| 438 |
+
|
| 439 |
+
return answer
|
| 440 |
+
|
| 441 |
+
def user(user_message, history):
|
| 442 |
+
return "", history + [[user_message, None]]
|
| 443 |
+
|
| 444 |
+
def slow_echo(history):
|
| 445 |
+
global prompt
|
| 446 |
+
global is_locked
|
| 447 |
+
global is_found
|
| 448 |
+
global captured_ID
|
| 449 |
+
global user_intent_text
|
| 450 |
+
global x
|
| 451 |
+
global info
|
| 452 |
+
global new_session
|
| 453 |
+
global full_ans
|
| 454 |
+
global is_new
|
| 455 |
+
|
| 456 |
+
user_message = history[-1][0]
|
| 457 |
+
my_query = history[-1][0]
|
| 458 |
+
|
| 459 |
+
if x == 0:
|
| 460 |
+
info = query_df(user_message)
|
| 461 |
+
x+=1
|
| 462 |
+
|
| 463 |
+
if is_locked == False:
|
| 464 |
+
|
| 465 |
+
SYS_PROMPT = SYS_TEMPLATE.format(info)
|
| 466 |
+
USER_PROMPT = prompt.rstrip() + f"\nHuman : {user_message}"
|
| 467 |
+
|
| 468 |
+
message_text=[
|
| 469 |
+
{
|
| 470 |
+
"role": "system",
|
| 471 |
+
"content": SYS_PROMPT
|
| 472 |
+
},
|
| 473 |
+
{
|
| 474 |
+
"role": "user",
|
| 475 |
+
"content": USER_PROMPT
|
| 476 |
+
},
|
| 477 |
+
|
| 478 |
+
]
|
| 479 |
+
|
| 480 |
+
stream = client.chat.completions.create(
|
| 481 |
+
model= mod,
|
| 482 |
+
messages = message_text,
|
| 483 |
+
temperature=0.0,
|
| 484 |
+
max_tokens=1700,
|
| 485 |
+
top_p=0.95,
|
| 486 |
+
frequency_penalty=0,
|
| 487 |
+
presence_penalty=0,
|
| 488 |
+
stop=None,
|
| 489 |
+
stream=True,
|
| 490 |
+
)
|
| 491 |
+
|
| 492 |
+
history[-1][1] = ""
|
| 493 |
+
full_ans =""
|
| 494 |
+
cleaned = False
|
| 495 |
+
is_found = False
|
| 496 |
+
|
| 497 |
+
for chunk in stream:
|
| 498 |
+
if not chunk.choices:
|
| 499 |
+
pass
|
| 500 |
+
else:
|
| 501 |
+
if chunk.choices[0].delta.content is not None:
|
| 502 |
+
if is_found == False:
|
| 503 |
+
|
| 504 |
+
if cleaned == False:
|
| 505 |
+
|
| 506 |
+
full_ans += chunk.choices[0].delta.content
|
| 507 |
+
|
| 508 |
+
|
| 509 |
+
if len(full_ans) >= 1500 :
|
| 510 |
+
cleaned = True
|
| 511 |
+
|
| 512 |
+
full_ans = clean_ans(full_ans)
|
| 513 |
+
|
| 514 |
+
if 'id' in full_ans.lower():
|
| 515 |
+
is_found = True
|
| 516 |
+
|
| 517 |
+
else:
|
| 518 |
+
|
| 519 |
+
for t in full_ans:
|
| 520 |
+
time.sleep(0.03)
|
| 521 |
+
history[-1][1] += t
|
| 522 |
+
yield history
|
| 523 |
+
|
| 524 |
+
elif cleaned == True:
|
| 525 |
+
time.sleep(0.03)
|
| 526 |
+
full_ans += chunk.choices[0].delta.content
|
| 527 |
+
history[-1][1] += chunk.choices[0].delta.content
|
| 528 |
+
yield history
|
| 529 |
+
|
| 530 |
+
else:
|
| 531 |
+
full_ans += chunk.choices[0].delta.content
|
| 532 |
+
|
| 533 |
+
if is_found == False:
|
| 534 |
+
if len(full_ans) <1500 :
|
| 535 |
+
if 'id' in full_ans.lower():
|
| 536 |
+
is_found = True
|
| 537 |
+
else:
|
| 538 |
+
full_ans = clean_ans(full_ans)
|
| 539 |
+
for t in full_ans:
|
| 540 |
+
time.sleep(0.02)
|
| 541 |
+
history[-1][1] += t
|
| 542 |
+
|
| 543 |
+
yield history
|
| 544 |
+
|
| 545 |
+
########################################################################################################
|
| 546 |
+
else :
|
| 547 |
+
full_ans = captured_ID
|
| 548 |
+
|
| 549 |
+
if (is_found) or (is_locked) :
|
| 550 |
+
|
| 551 |
+
if not is_locked:
|
| 552 |
+
pattern = r'\b\d{5}\b'
|
| 553 |
+
|
| 554 |
+
matches = re.findall(pattern, full_ans)
|
| 555 |
+
|
| 556 |
+
captured_ID = matches[0]
|
| 557 |
+
|
| 558 |
+
matched = re.search(r'user(?:intent)?\s*:\s*(.*)', full_ans, re.IGNORECASE)
|
| 559 |
+
user_intent_text = (matched.group(1).strip())
|
| 560 |
+
user_intent_text = "".join([x for x in user_intent_text if x not in punctuations])
|
| 561 |
+
|
| 562 |
+
my_query = user_intent_text
|
| 563 |
+
|
| 564 |
+
else:
|
| 565 |
+
|
| 566 |
+
my_query = user_message
|
| 567 |
+
|
| 568 |
+
related_txt = query_df_filtered(my_query, captured_ID)
|
| 569 |
+
|
| 570 |
+
law_df = df[df['Id'] == int(captured_ID)].reset_index()
|
| 571 |
+
|
| 572 |
+
##################################################################2nd
|
| 573 |
+
SYS_PROMPT = sys_prompt_intent.format(related_txt)
|
| 574 |
+
USER_PROMPT = prompt.rstrip() + f"\nHuman : {my_query}"
|
| 575 |
+
|
| 576 |
+
print(SYS_PROMPT)
|
| 577 |
+
print("-----------------")
|
| 578 |
+
print(USER_PROMPT)
|
| 579 |
+
print("-----------------")
|
| 580 |
+
print(prompt)
|
| 581 |
+
|
| 582 |
+
message_text=[
|
| 583 |
+
{
|
| 584 |
+
"role": "system",
|
| 585 |
+
"content": SYS_PROMPT
|
| 586 |
+
},
|
| 587 |
+
{
|
| 588 |
+
"role": "user",
|
| 589 |
+
"content": USER_PROMPT
|
| 590 |
+
},
|
| 591 |
+
|
| 592 |
+
]
|
| 593 |
+
|
| 594 |
+
stream = client.chat.completions.create(
|
| 595 |
+
model= mod,
|
| 596 |
+
messages = message_text,
|
| 597 |
+
temperature=0.0,
|
| 598 |
+
max_tokens=1500,
|
| 599 |
+
top_p=0.95,
|
| 600 |
+
frequency_penalty=0,
|
| 601 |
+
presence_penalty=0,
|
| 602 |
+
stop=None,
|
| 603 |
+
stream=True,
|
| 604 |
+
)
|
| 605 |
+
|
| 606 |
+
history[-1][1] = ""
|
| 607 |
+
full_ans = ''
|
| 608 |
+
for chunk in stream:
|
| 609 |
+
if not chunk.choices:
|
| 610 |
+
pass
|
| 611 |
+
else:
|
| 612 |
+
if chunk.choices[0].delta.content is not None:
|
| 613 |
+
|
| 614 |
+
time.sleep(0.03)
|
| 615 |
+
|
| 616 |
+
history[-1][1] += clean_ans(chunk.choices[0].delta.content)
|
| 617 |
+
full_ans += clean_ans(chunk.choices[0].delta.content)
|
| 618 |
+
|
| 619 |
+
yield (history)
|
| 620 |
+
########################################################################################################
|
| 621 |
+
|
| 622 |
+
if not is_locked:
|
| 623 |
+
|
| 624 |
+
link = shortener.tinyurl.short(law_df['Links'][0])
|
| 625 |
+
law_links = f"\n\nTopic : {law_df['Topic'][0]}\nLink : {link}"
|
| 626 |
+
|
| 627 |
+
for chunk in law_links:
|
| 628 |
+
|
| 629 |
+
time.sleep(0.01)
|
| 630 |
+
|
| 631 |
+
history[-1][1] += chunk
|
| 632 |
+
|
| 633 |
+
yield history
|
| 634 |
+
|
| 635 |
+
is_locked = True
|
| 636 |
+
|
| 637 |
+
else:
|
| 638 |
+
pass
|
| 639 |
+
|
| 640 |
+
prompt = update_prompt(my_query, full_ans)
|
| 641 |
+
|
| 642 |
+
|
| 643 |
+
def test_function():
|
| 644 |
+
global new_session
|
| 645 |
+
global is_locked
|
| 646 |
+
global is_found
|
| 647 |
+
global user_intent_text
|
| 648 |
+
global captured_ID
|
| 649 |
+
global full_ans
|
| 650 |
+
global history
|
| 651 |
+
global info
|
| 652 |
+
global prompt
|
| 653 |
+
global x
|
| 654 |
+
|
| 655 |
+
global memory
|
| 656 |
+
|
| 657 |
+
memory = ConversationBufferWindowMemory()
|
| 658 |
+
|
| 659 |
+
new_session = False
|
| 660 |
+
is_locked = False
|
| 661 |
+
is_found = False
|
| 662 |
+
|
| 663 |
+
user_intent_text = ''
|
| 664 |
+
captured_ID = ''
|
| 665 |
+
full_ans = ''
|
| 666 |
+
history = ''
|
| 667 |
+
info = ''
|
| 668 |
+
x=0
|
| 669 |
+
|
| 670 |
+
prompt = f"""
|
| 671 |
+
Current conversation:
|
| 672 |
+
"""
|
| 673 |
+
|
| 674 |
+
def reset_echo(history):
|
| 675 |
+
history = [history[0]]
|
| 676 |
+
yield history
|
| 677 |
+
welcome_message=" مرحبا معك عمار متخصص في موسوعة القوانين لوزارة العدل بالامارات.كيف يمكنني مساعدتك ؟ "
|
| 678 |
+
desc = "البوابة القانونية لوزارة العدل - الامارات العربية المتحدة- القوانين والتشريعات"
|
| 679 |
+
|
| 680 |
+
with gr.Blocks(theme=gr.themes.Soft(), title="HI") as demo:
|
| 681 |
+
with gr.Row():
|
| 682 |
+
image_path = "https://i.postimg.cc/kgJGhg32/UAE-MOJ-img.png"
|
| 683 |
+
gr.Image(image_path, height=120, show_download_button=False, show_label= False)
|
| 684 |
+
gr.Markdown(value=desc, rtl=True)
|
| 685 |
+
|
| 686 |
+
|
| 687 |
+
chatbot = gr.Chatbot(value=[(None,welcome_message)],height=350, rtl=True)
|
| 688 |
+
|
| 689 |
+
with gr.Row():
|
| 690 |
+
|
| 691 |
+
msg = gr.Textbox(container=False, min_width=750)
|
| 692 |
+
|
| 693 |
+
submit_btn = gr.Button(value="Submit", variant="primary")
|
| 694 |
+
submit_btn.click()
|
| 695 |
+
|
| 696 |
+
with gr.Row():
|
| 697 |
+
new_search = gr.Button(value="بحث جديد")
|
| 698 |
+
new_search.click(fn=test_function)
|
| 699 |
+
|
| 700 |
+
#gr.ClearButton([msg, chatbot])
|
| 701 |
+
|
| 702 |
+
msg.submit(user, [msg, chatbot], [msg, chatbot], queue=False).then(
|
| 703 |
+
slow_echo, chatbot, chatbot
|
| 704 |
+
)
|
| 705 |
+
submit_btn.click(user, [msg, chatbot], [msg, chatbot], queue=False).then(
|
| 706 |
+
slow_echo, chatbot, chatbot
|
| 707 |
+
)
|
| 708 |
+
|
| 709 |
+
new_search.click(user, [msg, chatbot], [msg, chatbot], queue=False).then(
|
| 710 |
+
reset_echo, chatbot, chatbot
|
| 711 |
+
)
|
| 712 |
+
demo.launch(inline=False)
|