File size: 7,750 Bytes
8055a93
321fadd
8055a93
 
 
5052352
e4eb7c7
 
 
 
f6a19a0
df508cf
8055a93
 
 
e4eb7c7
 
d9264f3
 
8055a93
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
49cc5e0
8055a93
d9264f3
2d13d0a
321fadd
7ab7abe
 
ed960ea
 
 
 
 
 
 
 
 
 
c755b00
7ab7abe
 
c933b27
0d7f12f
2747fb3
 
 
 
 
39785e9
 
 
 
 
 
1eb61ab
ed960ea
6a541cb
d9264f3
5f99ca5
5e112a6
d9264f3
8055a93
eefaf9d
ed960ea
af05c4c
c933b27
8055a93
eefaf9d
0d7f12f
ed960ea
a16969c
39ed458
 
a16969c
ed960ea
272bf11
 
 
 
2fbc455
272bf11
ed960ea
2fbc455
5052352
8055a93
7ab7abe
5f99ca5
d9264f3
5f99ca5
d9264f3
cea5a83
3af0fb2
789d020
cea5a83
789d020
bf0ed7c
 
 
7ab7abe
 
a16969c
 
2fbc455
39ed458
a16969c
 
2fbc455
cea5a83
 
 
 
f179843
8055a93
f179843
1668d01
93fc339
 
fe9c860
456f78e
671f7b0
0647997
456f78e
8055a93
 
cea5a83
 
f179843
cea5a83
f179843
 
 
 
cea5a83
 
 
0647997
cea5a83
 
f179843
cea5a83
 
5b3b5e2
cea5a83
a190ff7
731c251
5b3b5e2
 
731c251
cea5a83
 
5b3b5e2
 
 
 
cea5a83
 
0647997
cea5a83
2fbc455
ebc7be4
 
cea5a83
ebc7be4
 
 
 
 
 
 
cea5a83
ebc7be4
 
456f78e
ebc7be4
 
 
 
 
cea5a83
8055a93
71a5775
cea5a83
1
2
3
4
5
6
7
8
9
10
11
12
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
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
196
197
198
199
200
201
202
203
204

import initialize
from langchain_openai import ChatOpenAI
from langchain.memory import ConversationBufferMemory
from langchain.chains import ConversationalRetrievalChain
from langchain.chains import VectorDBQA
from langchain_community.llms import OpenAI
from langchain_core.prompts import PromptTemplate
from langchain_community.llms.huggingface_pipeline import HuggingFacePipeline
from langchain.chains import LLMChain
from langchain_google_genai import GoogleGenerativeAI
from langchain_google_genai import ChatGoogleGenerativeAI

import gradio as gr
import requests
import os

from langchain_ollama import OllamaLLM


import sys
sys.path.append('../..')

# For Google Colab
'''
from google.colab import userdata
OPENAI_API_KEY = userdata.get('OPENAI_API_KEY')
hf_token = userdata.get('hf_token')
GEMINI_API_KEY = userdata.get('GEMINI_API_KEY')
# For Desktop
from dotenv import load_dotenv, find_dotenv
_ = load_dotenv(find_dotenv()) # Read local .env file
OPENAI_API_KEY = os.environ['OPENAI_API_KEY']
hf_token = os.environ['hf_token']
GEMINI_API_KEY = os.environ['GEMINI_API_KEY']
'''

# For Hugging Face
OPENAI_API_KEY = os.environ.get('OPENAI_API_KEY')
hf_token = os.environ.get('hf_token')
GEMINI_API_KEY = os.environ.get('GEMINI_API_KEY')
fs_token = os.environ.get('fs_token')

llm_name = "gpt-3.5-turbo-0125"


vectordb = initialize.initialize()

chat_history_doc = []
chat_history_IS = []

# For getting source documents
def get_file(source_documents):
  files = set()
  for doc in source_documents:
    file = os.path.basename(doc.metadata['source'])
    files.add(file)
    # Print unique filenames
  return list(set(files))


def chat_query_doc(question, chat_history_doc):
    
    query_old = f"""Provide an elaborate, precise and pointwise reply to the question: {question}.
                    Also, Please consider the provided chat history: {chat_history_doc}.
                    Ensure that your current response is detailed, accurate, and addresses each aspect of the question thoroughly.
                    If the context of the question doesn't align with your last reply, please provide your response in a fresh manner.
                    If don't get the answer, feel free to reply from your own knowledge."""
    
    
    # query = f"""You'll be asked with a User Query. If the Query is related to Electrical Domain, Provide a precise and point-wise reply to the query: {question} \
    #            based on provided context only. Ensure that your reply addresses each aspect of the query thoroughly. """

    query = f""" Provide a precise and point-wise reply to the query: {question} \
                based on provided context only. Ensure that your reply addresses each aspect of the query thoroughly, and highlight the important points using text formatting 
                in your reply."""



    #llm = ChatOpenAI(model = llm_name, temperature = 0.1, api_key = OPENAI_API_KEY)
    #llm = GoogleGenerativeAI(model = "gemini-pro", google_api_key = GEMINI_API_KEY)                                   ###
    #llm = ChatGoogleGenerativeAI(model = "gemini-1.0-pro", google_api_key = GEMINI_API_KEY, temperature = 0)
    llm = OllamaLLM(model="unsloth/Llama-3.2-3B")

    # Conversation Retrival Chain with Memory
    #memory = ConversationBufferMemory(memory_key="chat_history", return_messages=True)
    retriever = vectordb.as_retriever()
    qa = ConversationalRetrievalChain.from_llm(llm, retriever = retriever, return_source_documents = True)

    # Replace input() with question variable for Gradio
    result = qa({"question": query, "chat_history" : chat_history_doc})

    # Update the history with the latest question and response
    # history.append({"user": question, "bot": result["answer"]})
    # chat_history_doc.append((query, result["answer"]))

    source_docs = result["source_documents"]
    file_names = get_file(source_docs)
    #file_name = os.path.basename(source_docs[0].metadata['source'])
    file_name = ', '.join([f"{x}" for x in file_names[:3]])

    # print("History : ", history)
    # print("\n Chat_his : ", chat_history)

    return result["answer"] + "\n\nSources : " + file_name


def chat_query_IS(question, chat_history_IS):
    
    #llm = ChatOpenAI(model = llm_name, temperature = 0.1, api_key = OPENAI_API_KEY)
    #llm = ChatGoogleGenerativeAI(model="gemini-pro", google_api_key=GEMINI_API_KEY)                                   ###
    llm = OllamaLLM(model="unsloth/Llama-3.2-3B")

    system_old = f""" Provide an elaborate, detailed and pointwise reply about the Topic, as per relevant IS/IEEE/BIS Standard.
              Also, at the end of your reply, quote the Relevant Standard Referred. Topic : {question}
              """
    system = f""" Provide a reply poetically precise as william shakespeare for the Topic : {question}
              """

    
    result = llm.invoke(system_old)
    

    # Update the history with the latest question and response
    # history.append({"user": question, "bot": result.content})
    # chat_history_IS.append((system_old, result.content))

    
    return result.content    


iface_doc = gr.ChatInterface(
    fn=chat_query_doc,
    title="""Standard TS of POWERGRID""",
    concurrency_limit = None,
    examples = ["What should be the GIB height outside the GIS hall ?" ,
                 "STATCOM Station Ratings" , 
                 "Specifications of XLPE POWER Cables."], 
             #    "Specification for Ethernet Switches in SAS."] ,
    theme=gr.themes.Base(),
    fill_height = True,
    delete_cache = (300,360),
    css = "CSS/chat_style.css",

)

iface_IS = gr.ChatInterface(
    fn = chat_query_IS,
    title = """Indian / International Standards""",
    concurrency_limit = None,
    examples = ["Type Tests for HV Switchgears." ,
                "Measurement of acoustic noise level of Transformers & Reactors" , 
                "Technical Requirement for 765kV class Transformer", 
                "Specification of Distance Relays"] ,
    theme=gr.themes.Base(),
    fill_height = True,
    delete_cache = (300,360),
    css = "CSS/chat_style.css",
)

Title= "# Conversational BOT for Model-TS & Indian / International Standards"

Description = """
### Welcome to the Language Model (SS-Engg-Dept.)! ๐Ÿ‘‹

This model is trained on **Model Technical Specifications** of the SS-Engg. Dept. and leverages the power of **ChatGPT** to answer your queries based on:

*   Relevant TS, GTR & Specific Requirements ๐Ÿ“‘
*   International/Indian Standards ๐ŸŒŽ๐Ÿ‡ฎ๐Ÿ‡ณ

**Tips for Effective Use:**

*   Use elaborate questions for more accurate responses. ๐Ÿค”
*   Clear the chat if you don't receive a reply. ๐Ÿ”„
*   Include **Specific Keywords** in your query for precise results. ๐ŸŽฏ 
"""              
 

with gr.Blocks(css="CSS/style.css", fill_height=True) as demo:
  
    # history = gr.State([])  # Initialize the state component
   
    with gr.Column():
    
        with gr.Row():
          with gr.Column(scale=1):
            gr.Image("Images/Chatbot.png", width = 110, show_download_button = False, show_label = False, show_share_button = False, elem_id = "Logo")
          with gr.Column(scale=3):
            gr.Markdown(Title)
          with gr.Column(scale=1):
            gr.Image("Images/PG Logo.png", width = 200, show_download_button = False, show_label = False, show_share_button = False, elem_id = "PG_Logo")  
    
        with gr.Row():
          gr.Markdown(Description)
    
        with gr.Row(equal_height=True):
          with gr.Column(elem_classes = ["chat_container"]):
            iface_doc.render()
          with gr.Column(elem_classes = ["chat_container"]):
            iface_IS.render()  
       

if __name__ == "__main__":
    demo.launch(debug=True, share=True)