Karthikeyan commited on
Commit
0782294
·
1 Parent(s): 605b8bc

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +326 -0
app.py ADDED
@@ -0,0 +1,326 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import logging
2
+ from typing import List
3
+ from pydantic import NoneStr
4
+ import os
5
+ from langchain.chains.question_answering import load_qa_chain
6
+ from langchain.document_loaders import UnstructuredFileLoader
7
+ from langchain.embeddings.openai import OpenAIEmbeddings
8
+ from langchain.llms import OpenAI
9
+ from langchain.text_splitter import CharacterTextSplitter
10
+ from langchain.vectorstores import FAISS
11
+ import gradio as gr
12
+ import openai
13
+ from langchain import PromptTemplate, OpenAI, LLMChain
14
+ import validators
15
+ import requests
16
+ import mimetypes
17
+ import tempfile
18
+ import pandas as pd
19
+ import re
20
+
21
+ class ChemicalIdentifier:
22
+ def __init__(self):
23
+
24
+ openai.api_key = os.getenv("OPENAI_API_KEY")
25
+ self.logger = logging.getLogger("ChemicalIdentifier")
26
+ self.logger.setLevel(logging.DEBUG)
27
+ formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
28
+ console_handler = logging.StreamHandler()
29
+ console_handler.setLevel(logging.DEBUG)
30
+ console_handler.setFormatter(formatter)
31
+ self.logger.addHandler(console_handler)
32
+
33
+
34
+ def upload_via_url(self,url:str)->List:
35
+ """
36
+ Uploads a file from a given URL and returns the loaded document.
37
+
38
+ Args:
39
+ url (str): The URL of the file to be uploaded.
40
+
41
+ Returns:
42
+ Document: The loaded document.
43
+
44
+ Raises:
45
+ ValueError: If the URL is not valid or the file cannot be fetched.
46
+ """
47
+
48
+ try:
49
+ if validators.url(url):
50
+ headers = {'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36',}
51
+ r = requests.get(url,headers=headers)
52
+ if r.status_code != 200:
53
+ raise ValueError(
54
+ "Check the url of your file; returned status code %s" % r.status_code
55
+ )
56
+
57
+ content_type = r.headers.get("content-type")
58
+ file_extension = mimetypes.guess_extension(content_type)
59
+ temp_file = tempfile.NamedTemporaryFile(suffix=file_extension, delete=False)
60
+ temp_file.write(r.content)
61
+ file_path = temp_file.name
62
+ loader = UnstructuredFileLoader(file_path, strategy="fast")
63
+ docs = loader.load()
64
+ return docs
65
+ else:
66
+ raise ValueError("Please enter a valid URL")
67
+ except Exception as e:
68
+ self.logger.error("Error occurred while uploading the file: %s", str(e))
69
+ raise ValueError("Error occurred while uploading the file") from e
70
+
71
+
72
+ def find_chemicals(self,text:str)->str:
73
+ """
74
+ Extracts chemical names from the given text.
75
+
76
+ Args:
77
+ text (str): The text to extract chemical names from.
78
+
79
+ Returns:
80
+ str: The extracted chemical names in bullet form.
81
+
82
+ Raises:
83
+ ValueError: If an error occurs during the extraction process.
84
+ """
85
+
86
+ try:
87
+ prompt = f"List out only all the Chemicals Names in the give text in bullet form.{text}"
88
+ response = openai.Completion.create(
89
+ model="text-davinci-003",
90
+ prompt=prompt,
91
+ temperature=0,
92
+ max_tokens=500,
93
+ top_p=1,
94
+ frequency_penalty=0,
95
+ presence_penalty=0,
96
+ )
97
+
98
+ message = response.choices[0].text.strip()
99
+ if ":" in message:
100
+ message = re.sub(r'^.*:', '', message)
101
+ return message.strip()
102
+ except Exception as e:
103
+ self.logger.error("Error occurred while finding chemicals: %s", str(e))
104
+ raise ValueError("Error occurred while finding chemicals") from e
105
+
106
+
107
+ def get_chemicals(self,urls:str)->str:
108
+ """
109
+ Retrieves chemicals from the provided URLs.
110
+
111
+ Args:
112
+ urls (str): Comma-separated URLs of the files to be processed.
113
+
114
+ Returns:
115
+ str: The extracted chemical names.
116
+
117
+ Raises:
118
+ ValueError: If an error occurs during the process.
119
+ """
120
+
121
+ try:
122
+ total_chemical=[]
123
+ for url in urls.split(','):
124
+ webpage_text = self.upload_via_url(url)
125
+ chemicals = self.find_chemicals(webpage_text)
126
+ total_chemical.append(chemicals)
127
+ list_of_chemicals = "".join(total_chemical)
128
+ return list_of_chemicals
129
+
130
+ except Exception as e:
131
+ self.logger.error("Error occurred while getting chemicals from URLs: %s", str(e))
132
+ raise ValueError("Error occurred while getting chemicals from URLs") from e
133
+
134
+ def get_empty_state(self):
135
+
136
+ """ Create empty Knowledge base"""
137
+
138
+ return {"knowledge_base": None}
139
+
140
+ def create_knowledge_base(self,docs):
141
+
142
+ """Create a knowledge base from the given documents.
143
+ Args:
144
+ docs (List[str]): List of documents.
145
+ Returns:
146
+ FAISS: Knowledge base built from the documents.
147
+ """
148
+
149
+ # Initialize a CharacterTextSplitter to split the documents into chunks
150
+ # Each chunk has a maximum length of 500 characters
151
+ # There is no overlap between the chunks
152
+ text_splitter = CharacterTextSplitter(
153
+ separator="\n", chunk_size=1000, chunk_overlap=200, length_function=len
154
+ )
155
+
156
+ # Split the documents into chunks using the text_splitter
157
+ chunks = text_splitter.split_documents(docs)
158
+
159
+ # Initialize an OpenAIEmbeddings model to compute embeddings of the chunks
160
+ embeddings = OpenAIEmbeddings()
161
+
162
+ # Build a knowledge base using FAISS from the chunks and their embeddings
163
+ knowledge_base = FAISS.from_documents(chunks, embeddings)
164
+
165
+ # Return the resulting knowledge base
166
+ return knowledge_base
167
+
168
+
169
+ def upload_file(self,file_paths):
170
+ """Upload a file and create a knowledge base from its contents.
171
+ Args:
172
+ file_paths : The files to uploaded.
173
+ Returns:
174
+ tuple: A tuple containing the file name and the knowledge base.
175
+ """
176
+
177
+ file_paths = [single_file_path.name for single_file_path in file_paths]
178
+
179
+ loaders = [UnstructuredFileLoader(file_obj, strategy="fast") for file_obj in file_paths]
180
+
181
+ # Load the contents of the file using the loader
182
+ docs = []
183
+ for loader in loaders:
184
+ docs.extend(loader.load())
185
+
186
+ # Create a knowledge base from the loaded documents using the create_knowledge_base() method
187
+ knowledge_base = self.create_knowledge_base(docs)
188
+
189
+
190
+ # Return a tuple containing the file name and the knowledge base
191
+ return file_paths, {"knowledge_base": knowledge_base}
192
+
193
+
194
+
195
+ def answer_question(self,urls, state):
196
+ """Answer a question based on the current knowledge base.
197
+ Args:
198
+ state (dict): The current state containing the knowledge base.
199
+ Returns:
200
+ str: The answer to the question.
201
+ """
202
+
203
+ result = self.get_chemicals(urls)
204
+ # Retrieve the knowledge base from the state dictionary
205
+ knowledge_base = state["knowledge_base"]
206
+
207
+ # Set the question for which we want to find the answer
208
+ question = "Identify the Chemical Capabilities Only"
209
+
210
+ # Perform a similarity search on the knowledge base to retrieve relevant documents
211
+ docs = knowledge_base.similarity_search(question)
212
+
213
+ # Initialize an OpenAI language model for question answering
214
+ template = """Use the following pieces of context to answer the question at the end. If you don't know the answer, just say that you don't know, don't try to make up an answer.
215
+ Identify the Chemical Capabilities Only.
216
+ {context}
217
+ Question :{question}.
218
+ The result should be in bullet points format.
219
+ """
220
+
221
+ prompt = PromptTemplate(template=template,input_variables=["context","question"])
222
+
223
+ llm = OpenAI(temperature=0.4)
224
+ llm_chain = LLMChain(prompt=prompt, llm=llm)
225
+
226
+ # Load a question-answering chain using the language model
227
+ chain = load_qa_chain(llm, chain_type="stuff",prompt=prompt)
228
+
229
+ # Run the question-answering chain on the input documents and question
230
+ response = chain.run(input_documents=docs, question=question)
231
+
232
+ Answer = response+"\n"+result
233
+
234
+ # Return the response as the answer to the question
235
+ return Answer
236
+
237
+
238
+ def extract_excel_data(self,file_path):
239
+ # Read the Excel file
240
+ df = pd.read_excel(file_path)
241
+
242
+ # Flatten the data to a single list
243
+ data_list = []
244
+ for _, row in df.iterrows():
245
+ data_list.extend(row.tolist())
246
+
247
+ return data_list
248
+
249
+ def comparing_chemicals(self,excel_file_path,chemicals):
250
+ chemistry_capability = self.extract_excel_data(excel_file_path.name)
251
+ response = openai.Completion.create(
252
+ engine="text-davinci-003",
253
+ prompt= f"""Analyse the following text delimited by triple backticks to return the comman chemicals.
254
+ text : ```{chemicals} {chemistry_capability}```.
255
+ result should be in bullet points format.
256
+ """,
257
+ max_tokens=100,
258
+ n=1,
259
+ stop=None,
260
+ temperature=0,
261
+ top_p=1.0,
262
+ frequency_penalty=0.0,
263
+ presence_penalty=0.0
264
+ )
265
+
266
+ result = response.choices[0].text.strip()
267
+
268
+ return result
269
+
270
+ def gradio_interface(self)->None:
271
+ """
272
+ Starts the Gradio interface for chemical identification.
273
+ """
274
+
275
+ try:
276
+ with gr.Blocks(css="style.css",theme='karthikeyan-adople/hudsonhayes-dark') as demo:
277
+ gr.HTML("""<center><img src="https://hudsonandhayes.co.uk/wp-content/uploads/2023/03/Hudson_meta.jpg" height="210px" width="310"></center>""")
278
+ state = gr.State(self.get_empty_state())
279
+ gr.HTML("""<center><h1 style="color:#fff">Chemical Identifier for Syngenta</h1></center>""")
280
+ # btn = gr.Button(value="Submit")
281
+ # chemicals_textbox = gr.Textbox(label="Chemicals",lines=6)
282
+ with gr.Column(elem_id="col-container"):
283
+ with gr.Row(elem_id="row-flex"):
284
+ url = gr.Textbox(label="URL")
285
+ with gr.Row(elem_id="row-flex"):
286
+ with gr.Column(scale=0.90, min_width=160):
287
+ file_output = gr.File(elem_classes="heightfit")
288
+ with gr.Column(scale=0.10, min_width=160):
289
+ upload_button = gr.UploadButton(
290
+ "Browse File", file_types=[".txt", ".pdf", ".doc", ".docx"],
291
+ elem_classes="heightfit",
292
+ file_count = "multiple")
293
+ with gr.Row():
294
+ with gr.Column(scale=1, min_width=0):
295
+ excel_input = gr.File(elem_classes="heightfit1",label = "excel file",file_types = [".xlsx"])
296
+ with gr.Row():
297
+ with gr.Column(scale=1, min_width=0):
298
+ analyse_btn = gr.Button(value="Analyse")
299
+ with gr.Row():
300
+ with gr.Column(scale=1, min_width=0):
301
+ answer = gr.Textbox(value="",label='Chemicals :',show_label=True, placeholder="",lines=5)
302
+ with gr.Row():
303
+ with gr.Column(scale=1, min_width=0):
304
+ compare_btn = gr.Button(value="valid")
305
+ with gr.Row():
306
+ with gr.Column(scale=1, min_width=0):
307
+ compared_result = gr.Textbox(value="",label='valid chemicals :',show_label=True, placeholder="",lines=5)
308
+
309
+
310
+ upload_button.upload(self.upload_file, upload_button, [file_output,state])
311
+
312
+ analyse_btn.click(self.answer_question, [url,state], [answer])
313
+
314
+ compare_btn.click(self.comparing_chemicals,[excel_input,answer],compared_result)
315
+
316
+ # btn.click(fn=self.get_chemicals, inputs=url, outputs=chemicals_textbox)
317
+ demo.launch(share=True)
318
+
319
+ except Exception as e:
320
+ self.logger.error("Error occurred while launching Gradio interface: %s", str(e))
321
+ raise ValueError("Error occurred while launching Gradio interface") from e
322
+
323
+ if __name__ == "__main__":
324
+ logging.basicConfig(level=logging.DEBUG)
325
+ chemical_identifier = ChemicalIdentifier()
326
+ chemical_identifier.gradio_interface()