Files changed (5) hide show
  1. app.py +63 -267
  2. requirements.txt +123 -8
  3. utils/__init__.py +3 -0
  4. utils/bot.py +203 -0
  5. utils/functions.py +72 -0
app.py CHANGED
@@ -1,287 +1,83 @@
1
  import gradio as gr
2
- import os
3
  import time
 
 
4
 
5
- from langchain.document_loaders import OnlinePDFLoader
6
- from langchain.text_splitter import CharacterTextSplitter
7
- from langchain.llms import OpenAI
8
- from langchain.embeddings import OpenAIEmbeddings
9
- from langchain.vectorstores import Chroma
10
- from langchain.chains import ConversationalRetrievalChain
11
- from langchain import PromptTemplate
12
- from transformers import Pix2StructForConditionalGeneration, Pix2StructProcessor
13
- import requests
14
- from PIL import Image
15
- import torch
16
-
17
-
18
-
19
- # _template = """Given the following conversation and a follow up question, rephrase the follow up question to be a standalone question.
20
- # Chat History:
21
- # {chat_history}
22
- # Follow Up Input: {question}
23
- # Standalone question:"""
24
-
25
- # CONDENSE_QUESTION_PROMPT = PromptTemplate.from_template(_template)
26
-
27
- # template = """
28
- # You are given the following extracted parts of a long document and a question. Provide a short structured answer.
29
- # If you don't know the answer, look on the web. Don't try to make up an answer.
30
- # Question: {question}
31
- # =========
32
- # {context}
33
- # =========
34
- # Answer in Markdown:"""
35
-
36
- torch.hub.download_url_to_file('https://raw.githubusercontent.com/vis-nlp/ChartQA/main/ChartQA%20Dataset/val/png/20294671002019.png', 'chart_example.png')
37
- torch.hub.download_url_to_file('https://raw.githubusercontent.com/vis-nlp/ChartQA/main/ChartQA%20Dataset/test/png/multi_col_1081.png', 'chart_example_2.png')
38
- torch.hub.download_url_to_file('https://raw.githubusercontent.com/vis-nlp/ChartQA/main/ChartQA%20Dataset/test/png/18143564004789.png', 'chart_example_3.png')
39
- torch.hub.download_url_to_file('https://sharkcoder.com/files/article/matplotlib-bar-plot.png', 'chart_example_4.png')
40
-
41
-
42
- model_name = "google/matcha-chartqa"
43
- model = Pix2StructForConditionalGeneration.from_pretrained(model_name)
44
- processor = Pix2StructProcessor.from_pretrained(model_name)
45
- device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
46
- model.to(device)
47
-
48
- def filter_output(output):
49
- return output.replace("<0x0A>", "")
50
-
51
- def chart_qa(image, question):
52
- inputs = processor(images=image, text=question, return_tensors="pt").to(device)
53
- predictions = model.generate(**inputs, max_new_tokens=512)
54
- return filter_output(processor.decode(predictions[0], skip_special_tokens=True))
55
-
56
- def loading_pdf():
57
- return "Loading..."
58
-
59
-
60
- def pdf_changes(pdf_doc, open_ai_key):
61
- if open_ai_key is not None:
62
- os.environ['OPENAI_API_KEY'] = open_ai_key
63
- loader = OnlinePDFLoader(pdf_doc.name)
64
- documents = loader.load()
65
- text_splitter = CharacterTextSplitter(chunk_size=1000, chunk_overlap=0)
66
- texts = text_splitter.split_documents(documents)
67
- embeddings = OpenAIEmbeddings()
68
- db = Chroma.from_documents(texts, embeddings)
69
- retriever = db.as_retriever()
70
- global qa
71
- qa = ConversationalRetrievalChain.from_llm(
72
- llm=OpenAI(temperature=0.5),
73
- retriever=retriever,
74
- return_source_documents=True)
75
- return "Ready"
76
- else:
77
- return "You forgot OpenAI API key"
78
-
79
- def add_text(history, text):
80
- history = history + [(text, None)]
81
- return history, ""
82
-
83
- def bot(history):
84
- response = infer(history[-1][0], history)
85
- history[-1][1] = ""
86
-
87
- for character in response:
88
- history[-1][1] += character
89
- time.sleep(0.05)
90
- yield history
91
 
92
-
93
- def infer(question, history):
94
- res = []
95
- for human, ai in history[:-1]:
96
- pair = (human, ai)
97
- res.append(pair)
98
 
99
- chat_history = res
100
- #print(chat_history)
101
- query = question
102
- result = qa({"question": query, "chat_history": chat_history})
103
- #print(result)
104
- return result["answer"]
105
-
106
- css="""
107
- #col-container {max-width: 700px; margin-left: auto; margin-right: auto;}
108
- """
109
-
110
- title = """
111
- <div style="text-align: center;">
112
- <h1>YnP LangChain Test </h1>
113
- <p style="text-align: center;">Please specify OpenAI Key before use</p>
114
- </div>
115
- """
116
-
117
-
118
- # with gr.Blocks(css=css) as demo:
119
- # with gr.Column(elem_id="col-container"):
120
- # gr.HTML(title)
121
-
122
- # with gr.Column():
123
- # openai_key = gr.Textbox(label="You OpenAI API key", type="password")
124
- # pdf_doc = gr.File(label="Load a pdf", file_types=['.pdf'], type="file")
125
- # with gr.Row():
126
- # langchain_status = gr.Textbox(label="Status", placeholder="", interactive=False)
127
- # load_pdf = gr.Button("Load pdf to langchain")
128
-
129
- # chatbot = gr.Chatbot([], elem_id="chatbot").style(height=350)
130
- # question = gr.Textbox(label="Question", placeholder="Type your question and hit Enter ")
131
- # submit_btn = gr.Button("Send Message")
132
-
133
- # load_pdf.click(loading_pdf, None, langchain_status, queue=False)
134
- # load_pdf.click(pdf_changes, inputs=[pdf_doc, openai_key], outputs=[langchain_status], queue=False)
135
- # question.submit(add_text, [chatbot, question], [chatbot, question]).then(
136
- # bot, chatbot, chatbot
137
- # )
138
- # submit_btn.click(add_text, [chatbot, question], [chatbot, question]).then(
139
- # bot, chatbot, chatbot)
140
-
141
- # demo.launch()
142
-
143
-
144
- """functions"""
145
-
146
- def load_file():
147
- return "Loading..."
148
-
149
- def load_xlsx(name):
150
- import pandas as pd
151
 
152
- xls_file = rf'{name}'
153
- data = pd.read_excel(xls_file)
154
- return data
155
-
156
- def table_loader(table_file, open_ai_key):
157
- import os
158
- from langchain.llms import OpenAI
159
- from langchain.agents import create_pandas_dataframe_agent
160
- from pandas import read_csv
161
 
162
- global agent
163
- if open_ai_key is not None:
164
- os.environ['OPENAI_API_KEY'] = open_ai_key
165
- else:
166
- return "Enter API"
167
 
168
- if table_file.name.endswith('.xlsx') or table_file.name.endswith('.xls'):
169
- data = load_xlsx(table_file.name)
170
- agent = create_pandas_dataframe_agent(OpenAI(temperature=0), data)
171
- return "Ready!"
172
- elif table_file.name.endswith('.csv'):
173
- data = read_csv(table_file.name)
174
- agent = create_pandas_dataframe_agent(OpenAI(temperature=0), data)
175
- return "Ready!"
176
- else:
177
- return "Wrong file format! Upload excel file or csv!"
178
 
179
- def run(query):
180
- from langchain.callbacks import get_openai_callback
181
 
182
- with get_openai_callback() as cb:
183
- response = (agent.run(query))
184
- costs = (f"Total Cost (USD): ${cb.total_cost}")
185
- output = f'{response} \n {costs}'
186
- return output
 
187
 
188
- def respond(message, chat_history):
189
- import time
 
 
190
 
191
- bot_message = run(message)
192
- chat_history.append((message, bot_message))
193
- time.sleep(0.5)
194
- return "", chat_history
 
 
195
 
 
 
196
 
197
  with gr.Blocks() as demo:
198
- with gr.Column(elem_id="col-container"):
199
- gr.HTML(title)
200
- key = gr.Textbox(
201
- show_label=False,
202
- placeholder="Your OpenAI key",
203
- type = 'password',
204
- ).style(container=False)
205
-
206
- # PDF processing tab
207
- with gr.Tab("PDFs"):
208
-
209
- with gr.Row():
210
-
211
- with gr.Column(scale=0.5):
212
- langchain_status = gr.Textbox(label="Status", placeholder="", interactive=False)
213
- load_pdf = gr.Button("Load pdf to langchain")
214
-
215
- with gr.Column(scale=0.5):
216
- pdf_doc = gr.File(label="Load a pdf", file_types=['.pdf'], type="file")
217
-
218
-
219
- with gr.Row():
220
-
221
- with gr.Column(scale=1):
222
- chatbot = gr.Chatbot([], elem_id="chatbot").style(height=350)
223
-
224
- with gr.Row():
225
-
226
- with gr.Column(scale=0.85):
227
- question = gr.Textbox(
228
- show_label=False,
229
- placeholder="Enter text and press enter, or upload an image",
230
- ).style(container=False)
231
-
232
- with gr.Column(scale=0.15, min_width=0):
233
- clr_btn = gr.Button("Clear!")
234
-
235
- load_pdf.click(loading_pdf, None, langchain_status, queue=False)
236
- load_pdf.click(pdf_changes, inputs=[pdf_doc, key], outputs=[langchain_status], queue=True)
237
- question.submit(add_text, [chatbot, question], [chatbot, question]).then(
238
- bot, chatbot, chatbot
239
- )
240
-
241
- # XLSX and CSV processing tab
242
- with gr.Tab("Spreadsheets"):
243
- with gr.Row():
244
-
245
- with gr.Column(scale=0.5):
246
- status_sh = gr.Textbox(label="Status", placeholder="", interactive=False)
247
- load_table = gr.Button("Load csv|xlsx to langchain")
248
-
249
- with gr.Column(scale=0.5):
250
- raw_table = gr.File(label="Load a table file (xls or csv)", file_types=['.csv, xlsx, xls'], type="file")
251
-
252
-
253
- with gr.Row():
254
 
255
- with gr.Column(scale=1):
256
- chatbot_sh = gr.Chatbot([], elem_id="chatbot").style(height=350)
257
-
258
-
259
- with gr.Row():
 
 
 
260
 
261
- with gr.Column(scale=0.85):
262
- question_sh = gr.Textbox(
263
- show_label=False,
264
- placeholder="Enter text and press enter, or upload an image",
265
- ).style(container=False)
266
-
267
- with gr.Column(scale=0.15, min_width=0):
268
- clr_btn = gr.Button("Clear!")
269
 
270
- load_table.click(load_file, None, status_sh, queue=False)
271
- load_table.click(table_loader, inputs=[raw_table, key], outputs=[status_sh], queue=False)
272
-
273
- question_sh.submit(respond, [question_sh, chatbot_sh], [question_sh, chatbot_sh])
274
- clr_btn.click(lambda: None, None, chatbot_sh, queue=False)
275
-
 
 
 
 
 
276
 
277
- with gr.Tab("Charts"):
278
- image = gr.Image(type="pil", label="Chart")
279
- question = gr.Textbox(label="Question")
280
- load_chart = gr.Button("Load chart and question!")
281
- answer = gr.Textbox(label="Model Output")
282
-
283
- load_chart.click(chart_qa, [image, question], answer)
284
 
285
-
286
- demo.queue(concurrency_count=3)
287
- demo.launch()
 
1
  import gradio as gr
 
2
  import time
3
+ from utils import Bot
4
+ from utils.functions import make_documents, make_descriptions
5
 
6
+ def init_bot(file=None,title=None,pdf=None,key=None):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7
 
8
+ if key is None:
9
+ return 'You must submit OpenAI key'
 
 
 
 
10
 
11
+ if pdf is None:
12
+ return 'You must submit pdf file'
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
13
 
14
+ if file is None:
15
+ return 'You must submit media file'
 
 
 
 
 
 
 
16
 
17
+ if title is None:
18
+ return 'You must submit the description of the media'
 
 
 
19
 
20
+ file = file.name
21
+ print(file)
22
+ pdf = pdf.name
23
+ file_description = make_descriptions(file, title)
24
+ # print(file_description)
25
+ documents = make_documents(pdf)
 
 
 
 
26
 
27
+ # print(documents[0])
28
+ global bot
29
 
30
+ bot = Bot(
31
+ openai_api_key=key,
32
+ file_descriptions=file_description,
33
+ text_documents=documents,
34
+ verbose=False
35
+ )
36
 
37
+ return 'Chat bot successfully initialized'
38
+
39
+ def msg_bot(history):
40
+ message = history[-1][0]
41
 
42
+ bot_message = bot(message)['output']
43
+ history[-1][1] = ""
44
+ for character in bot_message:
45
+ history[-1][1] += character
46
+ time.sleep(0.05)
47
+ yield history
48
 
49
+ def user(user_message, history):
50
+ return "", history + [[user_message, None]]
51
 
52
  with gr.Blocks() as demo:
53
+
54
+ key = gr.Textbox(label='OpenAI key')
55
+ with gr.Tab("Chat bot initialization"):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
56
 
57
+ with gr.Row(variant='panel'):
58
+ with gr.Column():
59
+ with gr.Row():
60
+ title = gr.Textbox(label='File short description')
61
+ with gr.Row():
62
+ file = gr.File(label='CSV or image', file_types=['.csv', 'image'])
63
+
64
+ pdf = gr.File(label='pdf')
65
 
66
+ with gr.Row(variant='panel'):
67
+ init_button = gr.Button('submit')
68
+ init_output = gr.Textbox(label="Initialization status")
69
+ init_button.click(fn=init_bot,inputs=[file,title,pdf,key],outputs=init_output,api_name='init')
 
 
 
 
70
 
71
+ chatbot = gr.Chatbot()
72
+ msg = gr.Textbox(label='Ask the bot')
73
+ clear = gr.Button('Clear')
74
+ msg.submit(user,[msg,chatbot],[msg,chatbot],queue=False).then(
75
+ msg_bot, chatbot, chatbot
76
+ )
77
+ clear.click(lambda: None, None, chatbot, queue=False)
78
+
79
+ demo.queue()
80
+ demo.launch()
81
+
82
 
 
 
 
 
 
 
 
83
 
 
 
 
requirements.txt CHANGED
@@ -1,8 +1,123 @@
1
- openai
2
- tiktoken
3
- chromadb
4
- langchain
5
- unstructured
6
- unstructured[local-inference]
7
- pandas
8
- tabulate
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ aiofiles==23.1.0
2
+ aiohttp==3.8.4
3
+ aiosignal==1.3.1
4
+ altair==5.0.0
5
+ anyio==3.6.2
6
+ async-timeout==4.0.2
7
+ attrs==23.1.0
8
+ backoff==2.2.1
9
+ certifi==2023.5.7
10
+ charset-normalizer==3.1.0
11
+ chromadb==0.3.22
12
+ click==8.1.3
13
+ clickhouse-connect==0.5.24
14
+ cmake==3.26.3
15
+ contourpy==1.0.7
16
+ cycler==0.11.0
17
+ dataclasses-json==0.5.7
18
+ duckdb==0.7.1
19
+ fastapi==0.95.1
20
+ ffmpy==0.3.0
21
+ filelock==3.12.0
22
+ fonttools==4.39.4
23
+ frozenlist==1.3.3
24
+ fsspec==2023.5.0
25
+ gradio==3.29.0
26
+ gradio_client==0.2.2
27
+ greenlet==2.0.2
28
+ h11==0.14.0
29
+ hnswlib==0.7.0
30
+ httpcore==0.17.0
31
+ httptools==0.5.0
32
+ httpx==0.24.0
33
+ huggingface-hub==0.14.1
34
+ idna==3.4
35
+ importlib-resources==5.12.0
36
+ Jinja2==3.1.2
37
+ joblib==1.2.0
38
+ jsonschema==4.17.3
39
+ kiwisolver==1.4.4
40
+ langchain==0.0.164
41
+ linkify-it-py==2.0.2
42
+ lit==16.0.3
43
+ lz4==4.3.2
44
+ markdown-it-py==2.2.0
45
+ MarkupSafe==2.1.2
46
+ marshmallow==3.19.0
47
+ marshmallow-enum==1.5.1
48
+ matplotlib==3.7.1
49
+ mdit-py-plugins==0.3.3
50
+ mdurl==0.1.2
51
+ monotonic==1.6
52
+ mpmath==1.3.0
53
+ multidict==6.0.4
54
+ mypy-extensions==1.0.0
55
+ networkx==3.1
56
+ nltk==3.8.1
57
+ numexpr==2.8.4
58
+ numpy==1.24.3
59
+ nvidia-cublas-cu11==11.10.3.66
60
+ nvidia-cuda-cupti-cu11==11.7.101
61
+ nvidia-cuda-nvrtc-cu11==11.7.99
62
+ nvidia-cuda-runtime-cu11==11.7.99
63
+ nvidia-cudnn-cu11==8.5.0.96
64
+ nvidia-cufft-cu11==10.9.0.58
65
+ nvidia-curand-cu11==10.2.10.91
66
+ nvidia-cusolver-cu11==11.4.0.1
67
+ nvidia-cusparse-cu11==11.7.4.91
68
+ nvidia-nccl-cu11==2.14.3
69
+ nvidia-nvtx-cu11==11.7.91
70
+ openai==0.27.6
71
+ openapi-schema-pydantic==1.2.4
72
+ orjson==3.8.12
73
+ packaging==23.1
74
+ pandas==2.0.1
75
+ Pillow==9.5.0
76
+ pkgutil_resolve_name==1.3.10
77
+ posthog==3.0.1
78
+ pydantic==1.10.7
79
+ pydub==0.25.1
80
+ Pygments==2.15.1
81
+ pyparsing==3.0.9
82
+ pypdf==3.8.1
83
+ pyrsistent==0.19.3
84
+ python-dateutil==2.8.2
85
+ python-dotenv==1.0.0
86
+ python-multipart==0.0.6
87
+ pytz==2023.3
88
+ PyYAML==6.0
89
+ regex==2023.5.5
90
+ requests==2.30.0
91
+ scikit-learn==1.2.2
92
+ scipy==1.10.1
93
+ semantic-version==2.10.0
94
+ sentence-transformers==2.2.2
95
+ sentencepiece==0.1.99
96
+ six==1.16.0
97
+ sniffio==1.3.0
98
+ SQLAlchemy==2.0.12
99
+ starlette==0.26.1
100
+ sympy==1.12
101
+ tabulate==0.9.0
102
+ tenacity==8.2.2
103
+ threadpoolctl==3.1.0
104
+ tiktoken==0.4.0
105
+ tokenizers==0.13.3
106
+ toolz==0.12.0
107
+ torch==2.0.1
108
+ torchvision==0.15.2
109
+ tqdm==4.65.0
110
+ transformers==4.29.0
111
+ triton==2.0.0
112
+ typing-inspect==0.8.0
113
+ typing_extensions==4.5.0
114
+ tzdata==2023.3
115
+ uc-micro-py==1.0.2
116
+ urllib3==2.0.2
117
+ uvicorn==0.22.0
118
+ uvloop==0.17.0
119
+ watchfiles==0.19.0
120
+ websockets==11.0.3
121
+ yarl==1.9.2
122
+ zipp==3.15.0
123
+ zstandard==0.21.0
utils/__init__.py ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ from .bot import Bot
2
+ from .functions import make_documents, make_descriptions
3
+
utils/bot.py ADDED
@@ -0,0 +1,203 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import langchain
2
+ from langchain.agents import create_csv_agent
3
+ from langchain.schema import HumanMessage
4
+ from langchain.chat_models import ChatOpenAI
5
+ from langchain.embeddings import OpenAIEmbeddings
6
+ from langchain.vectorstores import Chroma
7
+ from typing import List, Dict
8
+ from langchain.agents import AgentType
9
+ from langchain.chains.conversation.memory import ConversationBufferWindowMemory
10
+ from utils.functions import Matcha_model
11
+ from PIL import Image
12
+ from pathlib import Path
13
+ from langchain.tools import StructuredTool
14
+ from langchain.embeddings.sentence_transformer import SentenceTransformerEmbeddings
15
+
16
+ class Bot:
17
+
18
+ def __init__(
19
+ self,
20
+ openai_api_key: str,
21
+ file_descriptions: List[Dict[str, any]],
22
+ text_documents: List[langchain.schema.Document],
23
+ verbose: bool = False
24
+ ):
25
+ self.verbose = verbose
26
+ self.file_descriptions = file_descriptions
27
+
28
+ self.llm = ChatOpenAI(
29
+ openai_api_key=openai_api_key,
30
+ temperature=0,
31
+ model_name="gpt-3.5-turbo"
32
+ )
33
+ embedding_function = SentenceTransformerEmbeddings(model_name="all-MiniLM-L6-v2")
34
+ # embeddings = OpenAIEmbeddings(openai_api_key=openai_api_key)
35
+ vector_store = Chroma.from_documents(text_documents, embedding_function)
36
+ self.text_retriever = langchain.chains.RetrievalQAWithSourcesChain.from_chain_type(
37
+ llm=self.llm,
38
+ chain_type='stuff',
39
+ retriever=vector_store.as_retriever()
40
+ )
41
+ self.text_search_tool = langchain.agents.Tool(
42
+ func=self._text_search,
43
+ description="Use this tool when searching for text information",
44
+ name="search text information"
45
+ )
46
+
47
+ self.chart_model = Matcha_model()
48
+
49
+ def __call__(
50
+ self,
51
+ question: str
52
+ ):
53
+ self.tools = []
54
+ self.tools.append(self.text_search_tool)
55
+ file = self._define_appropriate_file(question)
56
+ if file != "None of the files":
57
+ number = int(file[file.find('№')+1:])
58
+ file_description = [x for x in self.file_descriptions if x['number'] == number][0]
59
+ file_path = file_description['path']
60
+
61
+ if Path(file).suffix == '.csv':
62
+ self.csv_agent = create_csv_agent(
63
+ llm=self.llm,
64
+ path=file_path,
65
+ verbose=self.verbose
66
+ )
67
+
68
+ self._init_tabular_search_tool(file_description)
69
+ self.tools.append(self.tabular_search_tool)
70
+
71
+ else:
72
+ self._init_chart_search_tool(file_description)
73
+ self.tools.append(self.chart_search_tool)
74
+
75
+ self._init_chatbot()
76
+ # print(file)
77
+ response = self.agent(question)
78
+ return response
79
+
80
+ def _init_chatbot(self):
81
+
82
+ conversational_memory = ConversationBufferWindowMemory(
83
+ memory_key='chat_history',
84
+ k=5,
85
+ return_messages=True
86
+ )
87
+
88
+ self.agent = langchain.agents.initialize_agent(
89
+ agent=AgentType.STRUCTURED_CHAT_ZERO_SHOT_REACT_DESCRIPTION,
90
+ tools=self.tools,
91
+ llm=self.llm,
92
+ verbose=self.verbose,
93
+ max_iterations=5,
94
+ early_stopping_method='generate',
95
+ memory=conversational_memory
96
+ )
97
+ sys_msg = (
98
+ "You are an expert summarizer and deliverer of information. "
99
+ "Yet, the reason you are so intelligent is that you make complex "
100
+ "information incredibly simple to understand. It's actually rather incredible."
101
+ "When users ask information you refer to the relevant tools."
102
+ "if one of the tools helped you with only a part of the necessary information, you must "
103
+ "try to find the missing information using another tool"
104
+ "if you can't find the information using the provided tools, you MUST "
105
+ "say 'I don't know'. Don't try to make up an answer."
106
+ )
107
+ prompt = self.agent.agent.create_prompt(
108
+ tools=self.tools,
109
+ prefix = sys_msg
110
+ )
111
+ self.agent.agent.llm_chain.prompt = prompt
112
+
113
+ def _text_search(
114
+ self,
115
+ query: str
116
+ ) -> str:
117
+ query = self.text_retriever.prep_inputs(query)
118
+ res = self.text_retriever(query)['answer']
119
+ return res
120
+
121
+ def _tabular_search(
122
+ self,
123
+ query: str
124
+ ) -> str:
125
+ res = self.csv_agent.run(query)
126
+ return res
127
+
128
+ def _chart_search(
129
+ self,
130
+ image,
131
+ query: str
132
+ ) -> str:
133
+ image = Image.open(image)
134
+ res = self.chart_model.chart_qa(image, query)
135
+ return res
136
+
137
+ def _init_chart_search_tool(
138
+ self,
139
+ title: str
140
+ ) -> None:
141
+ title = title
142
+ description = f"""
143
+ Use this tool when searching for information on charts.
144
+ With this tool you can answer the question about related chart.
145
+ You should ask simple question about a chart, then the tool will give you number.
146
+ This chart is called {title}.
147
+ """
148
+
149
+ self.chart_search_tool = StructuredTool(
150
+ func=self._chart_search,
151
+ description=description,
152
+ name="Ask over charts"
153
+ )
154
+
155
+ def _init_tabular_search_tool(
156
+ self,
157
+ file_: Dict[str, any]
158
+ ) -> None:
159
+
160
+
161
+ description = f"""
162
+ Use this tool when searching for tabular information.
163
+ With this tool you could get access to table.
164
+ This table title is "{title}" and the names of the columns in this table: {columns}
165
+ """
166
+
167
+ self.tabular_search_tool = langchain.agents.Tool(
168
+ func=self._tabular_search,
169
+ description=description,
170
+ name="search tabular information"
171
+ )
172
+
173
+ def _define_appropriate_file(
174
+ self,
175
+ question: str
176
+ ) -> str:
177
+ ''' Определяет по описаниям таблиц в какой из них может содержаться ответ на вопрос.
178
+ Возвращает номер таблицы по шаблону "Table №1" или "None of the tables" '''
179
+
180
+ message = 'I have list of descriptions: \n'
181
+ k = 0
182
+
183
+ for description in self.file_descriptions:
184
+ k += 1
185
+ str_description = f""" {k}) description for File №{description['number']}: """
186
+ for key, value in description.items():
187
+ string_val = str(key) + ' : ' + str(value) + '\n'
188
+ str_description += string_val
189
+ message += str_description
190
+ print(message)
191
+ question = f""" How do you think, which file can help answer the question: "{question}" .
192
+ Your answer MUST be specific,
193
+ for example if you think that File №2 can help answer the question, you MUST just write "File №2!".
194
+ If you think that none of the files can help answer the question just write "None of the files!"
195
+ Don't include to answer information about your thinking.
196
+ """
197
+ message += question
198
+
199
+ res = self.llm([HumanMessage(content=message)])
200
+ print(res.content)
201
+ print(res.content[:-1])
202
+ return res.content[:-1]
203
+
utils/functions.py ADDED
@@ -0,0 +1,72 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ import pandas as pd
3
+ from langchain.document_loaders import PyPDFLoader
4
+ from langchain.text_splitter import CharacterTextSplitter
5
+ import torch
6
+ from transformers import Pix2StructForConditionalGeneration, Pix2StructProcessor
7
+ from pathlib import Path
8
+
9
+ def make_descriptions(file, title):
10
+ if Path(file).suffix == '.csv':
11
+ # print(file)
12
+ df = pd.read_csv(file)
13
+ print(df.head())
14
+ columns = list(df.columns)
15
+ print(columns)
16
+ table_description0 = {
17
+ 'path': 'random',
18
+ 'number': 1,
19
+ 'columns': ["clothes", "animals", "students"],
20
+ 'title': "fashionable student clothes"
21
+ }
22
+
23
+ table_description1 = {
24
+ 'path': file,
25
+ 'number': 2,
26
+ 'columns': columns,
27
+ 'title': title
28
+ }
29
+
30
+ table_descriptions = [table_description0, table_description1]
31
+ return table_descriptions
32
+ else:
33
+ file_description = {
34
+ 'path': file,
35
+ 'number': 1,
36
+ 'title': title
37
+ }
38
+ file_descriptions = [file_description]
39
+ return file_descriptions
40
+
41
+
42
+ def make_documents(pdf):
43
+ loader = PyPDFLoader(pdf)
44
+ documents = loader.load()
45
+
46
+ text_splitter = CharacterTextSplitter(chunk_size=500, chunk_overlap=0, separator='\n')
47
+ documents = text_splitter.split_documents(documents)
48
+ return documents
49
+
50
+ class Matcha_model:
51
+
52
+ def __init__(self) -> None:
53
+ # torch.hub.download_url_to_file('https://raw.githubusercontent.com/vis-nlp/ChartQA/main/ChartQA%20Dataset/val/png/20294671002019.png', 'chart_example.png')
54
+ # torch.hub.download_url_to_file('https://raw.githubusercontent.com/vis-nlp/ChartQA/main/ChartQA%20Dataset/test/png/multi_col_1081.png', 'chart_example_2.png')
55
+ # torch.hub.download_url_to_file('https://raw.githubusercontent.com/vis-nlp/ChartQA/main/ChartQA%20Dataset/test/png/18143564004789.png', 'chart_example_3.png')
56
+ # torch.hub.download_url_to_file('https://sharkcoder.com/files/article/matplotlib-bar-plot.png', 'chart_example_4.png')
57
+
58
+ self.model_name = "google/matcha-chartqa"
59
+ self.model = Pix2StructForConditionalGeneration.from_pretrained(self.model_name)
60
+ self.processor = Pix2StructProcessor.from_pretrained(self.model_name)
61
+ self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
62
+ self.model.to(self.device)
63
+
64
+ def _filter_output(self, output):
65
+ return output.replace("<0x0A>", "")
66
+
67
+ def chart_qa(self, image, question: str) -> str:
68
+ inputs = self.processor(images=image, text=question, return_tensors="pt").to(self.device)
69
+ predictions = self.model.generate(**inputs, max_new_tokens=512)
70
+ return self._filter_output(self.processor.decode(predictions[0], skip_special_tokens=True))
71
+
72
+