cnmoro commited on
Commit
73891ee
1 Parent(s): e7cd08a

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +217 -0
app.py ADDED
@@ -0,0 +1,217 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from functools import lru_cache
2
+ import time, aiohttp, asyncio, json, os, multiprocessing, torch, \
3
+ requests, xmltodict, fitz, io
4
+ from minivectordb.embedding_model import EmbeddingModel
5
+ from minivectordb.vector_database import VectorDatabase
6
+ from text_util_en_pt.cleaner import structurize_text, detect_language, Language
7
+ import gradio as gr
8
+
9
+ torch.set_num_threads(2)
10
+
11
+ openrouter_key = os.environ.get("OPENROUTER_KEY")
12
+ model = EmbeddingModel(use_quantized_onnx_model=True)
13
+
14
+ def convert_xml_to_json(xml):
15
+ return xmltodict.parse(xml)
16
+
17
+ def clean_title(title):
18
+ title = title.replace('\n', ' ')
19
+ while ' ' in title:
20
+ title = title.replace(' ', ' ')
21
+ return title
22
+
23
+ @lru_cache(maxsize=500)
24
+ def fetch_arxiv_links(query, max_results=5):
25
+ url = f'http://export.arxiv.org/api/query?search_query=all:{query}&start=0&max_results={max_results}'
26
+ response = requests.get(url)
27
+ json_response = convert_xml_to_json(response.text)
28
+
29
+ # Return a list of titles and links, and pdf links
30
+ entries = []
31
+ for entry in json_response['feed']['entry']:
32
+
33
+ title = entry['title']
34
+ id = entry['id'].split('/abs/')[-1]
35
+
36
+ link = f'http://arxiv.org/abs/{id}'
37
+ pdf_link = f'http://arxiv.org/pdf/{id}.pdf'
38
+
39
+ entries.append({
40
+ 'title': clean_title(title),
41
+ 'link': link,
42
+ 'pdf_link': pdf_link
43
+ })
44
+ return entries
45
+
46
+ def download_pdf_from_link(link):
47
+ # Download the file and hold it in memory
48
+ response = requests.get(link)
49
+ return io.BytesIO(response.content)
50
+
51
+ @lru_cache(maxsize=100)
52
+ def read_remote_pdf(pdf_metadata):
53
+ pdf_metadata = json.loads(pdf_metadata)
54
+
55
+ link = pdf_metadata['pdf_link']
56
+ title = pdf_metadata['title']
57
+
58
+ pdf_content = download_pdf_from_link(link)
59
+ pdf_file = fitz.open("pdf", pdf_content.read())
60
+ text_content = [page.get_text() for page in pdf_file]
61
+ pdf_file.close()
62
+ del pdf_file
63
+ return {'title': title, 'text': '\n'.join(text_content)}
64
+
65
+ def fetch_data_from_pdfs(links):
66
+ links = [ json.dumps(link) for link in links ]
67
+ with multiprocessing.Pool(10) as pool:
68
+ pdf_metadata = pool.map(read_remote_pdf, links)
69
+ return pdf_metadata
70
+
71
+ def index_and_search(query, pdf_metadata):
72
+ start = time.time()
73
+ query_embedding = model.extract_embeddings(query)
74
+
75
+ # Indexing
76
+ vector_db = VectorDatabase()
77
+
78
+ sentence_counter = 1
79
+
80
+ for pdf_data in pdf_metadata:
81
+ text = pdf_data['text']
82
+ title = pdf_data['title']
83
+
84
+ sentences = [ s['sentence'] for s in structurize_text(text)]
85
+
86
+ for sentence in sentences:
87
+ sentence_embedding = model.extract_embeddings(sentence)
88
+ vector_db.store_embedding(
89
+ sentence_counter,
90
+ sentence_embedding,
91
+ {
92
+ 'sentence': sentence,
93
+ 'title': title
94
+ }
95
+ )
96
+ sentence_counter += 1
97
+
98
+ embedding_time = time.time() - start
99
+
100
+ # Retrieval
101
+ start = time.time()
102
+ search_results = vector_db.find_most_similar(query_embedding, k = 15)
103
+ search_metadata = search_results[2]
104
+ retrieval_time = time.time() - start
105
+
106
+ retrieved_contents = {}
107
+ for ret_cont in search_metadata:
108
+ title = ret_cont['title']
109
+ if title not in retrieved_contents:
110
+ retrieved_contents[title] = []
111
+ retrieved_contents[title].append(ret_cont['sentence'])
112
+
113
+ retrieved_contents = {k: '\n'.join(v) for k, v in retrieved_contents.items()}
114
+
115
+ return retrieved_contents, embedding_time, retrieval_time
116
+
117
+ def retrieval_pipeline(query, question):
118
+ start = time.time()
119
+ links = fetch_arxiv_links(query)
120
+ websearch_time = time.time() - start
121
+
122
+ start = time.time()
123
+ pdf_metadata = fetch_data_from_pdfs(links)
124
+ webcrawl_time = time.time() - start
125
+
126
+ retrieved_contents, embedding_time, retrieval_time = index_and_search(question, pdf_metadata)
127
+
128
+ return retrieved_contents, websearch_time, webcrawl_time, embedding_time, retrieval_time, links
129
+
130
+ async def predict(message, history):
131
+ # message is in format: "Search: <query>; Question: <question>"
132
+ # we need to parse both parts into variables
133
+ message = message.split(';')
134
+
135
+ query = message[0].split(':')[-1].strip()
136
+ question = message[1].split(':')[-1].strip()
137
+
138
+ retrieved_contents, websearch_time, webcrawl_time, embedding_time, retrieval_time, links = retrieval_pipeline(query, question)
139
+
140
+ if detect_language(message) == Language.ptbr:
141
+ context = ""
142
+ for title, content in retrieved_contents.items():
143
+ context += f'Artigo "{title}"\nConteúdo:\n{content}\n\n'
144
+ prompt = f'{context.strip()}\n\nBaseado nos conteúdos dos artigos, responda: "{message}"\n\nPor favor, mencione a fonte da sua resposta.'
145
+ else:
146
+ context = ""
147
+ for title, content in retrieved_contents.items():
148
+ context += f'Article "{title}"\nContent:\n{content}\n\n'
149
+ prompt = f'{context.strip()}\n\nBased on the article\'s contents, answer: "{message}"\n\nPlease, mention the source of your answer.'
150
+
151
+ print(prompt)
152
+
153
+ url = "https://openrouter.ai/api/v1/chat/completions"
154
+ headers = { "Content-Type": "application/json",
155
+ "Authorization": f"Bearer {openrouter_key}" }
156
+ body = { "stream": True,
157
+ "models": [
158
+ "mistralai/mistral-7b-instruct:free",
159
+ "openchat/openchat-7b:free"
160
+ ],
161
+ "route": "fallback",
162
+ "max_tokens": 1024,
163
+ "messages": [
164
+ {"role": "user", "content": prompt}
165
+ ] }
166
+
167
+ full_response = ""
168
+ async with aiohttp.ClientSession() as session:
169
+ async with session.post(url, headers=headers, json=body) as response:
170
+ buffer = "" # A buffer to hold incomplete lines of data
171
+ async for chunk in response.content.iter_any():
172
+ buffer += chunk.decode()
173
+ while "\n" in buffer: # Process as long as there are complete lines in the buffer
174
+ line, buffer = buffer.split("\n", 1)
175
+
176
+ if line.startswith("data: "):
177
+ event_data = line[len("data: "):]
178
+ if event_data != '[DONE]':
179
+ try:
180
+ current_text = json.loads(event_data)['choices'][0]['delta']['content']
181
+ full_response += current_text
182
+ yield full_response
183
+ await asyncio.sleep(0.01)
184
+ except Exception:
185
+ try:
186
+ current_text = json.loads(event_data)['choices'][0]['text']
187
+ full_response += current_text
188
+ yield full_response
189
+ await asyncio.sleep(0.01)
190
+ except Exception:
191
+ pass
192
+
193
+ final_metadata_block = ""
194
+
195
+ final_metadata_block += f"Links visited:\n"
196
+ for link in links:
197
+ final_metadata_block += f"{link['title']} ({link['link']})\n"
198
+ final_metadata_block += f"\nWeb search time: {websearch_time:.4f} seconds\n"
199
+ final_metadata_block += f"\nText extraction: {webcrawl_time:.4f} seconds\n"
200
+ final_metadata_block += f"\nEmbedding time: {embedding_time:.4f} seconds\n"
201
+ final_metadata_block += f"\nRetrieval from VectorDB time: {retrieval_time:.4f} seconds"
202
+
203
+ yield f"{full_response}\n\n{final_metadata_block}"
204
+
205
+ gr.ChatInterface(
206
+ predict,
207
+ title="Automated Arxiv Paper Search and Question Answering",
208
+ description="Provide a search term and a question to find relevant papers and answer questions about them.",
209
+ retry_btn=None,
210
+ undo_btn=None,
211
+ examples=[
212
+ 'Search: RAG LLMS; Question: What are some challenges of implementing a system of RAG with LLMS ?',
213
+ 'Search: LLM Self-Play; Question: What are the benefits of using self-play with LLMS?',
214
+ 'Search: Brazil Tax Rate; Question: Why does Brazil has a high tax rate?',
215
+ 'Search: Stomach medicine; Question: Can stomach medicine cause genetic mutations?'
216
+ ]
217
+ ).launch()