Spaces:
Running
Running
mehradans92
commited on
Commit
·
df44d29
1
Parent(s):
fd60d1d
developed api
Browse files- app.py +224 -6
- requirements.txt +5 -1
app.py
CHANGED
@@ -2,14 +2,232 @@ import easyocr as ocr #OCR
|
|
2 |
import streamlit as st #Web App
|
3 |
from PIL import Image #Image Processing
|
4 |
import numpy as np #Image Processing
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
5 |
|
6 |
#title
|
7 |
-
st.title("
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
8 |
|
9 |
-
#
|
10 |
-
st.markdown(
|
|
|
11 |
|
12 |
-
st.markdown("Link to the app - [image-to-text-app on 🤗 Spaces](https://huggingface.co/spaces/Amrrs/image-to-text-app)")
|
13 |
|
14 |
-
#
|
15 |
-
|
|
|
2 |
import streamlit as st #Web App
|
3 |
from PIL import Image #Image Processing
|
4 |
import numpy as np #Image Processing
|
5 |
+
import urllib
|
6 |
+
from lxml import html
|
7 |
+
import requests
|
8 |
+
import re
|
9 |
+
import os
|
10 |
+
from stqdm import stqdm
|
11 |
+
import pandoc
|
12 |
+
import time
|
13 |
+
import shutil
|
14 |
+
|
15 |
+
import pickle
|
16 |
+
|
17 |
|
18 |
#title
|
19 |
+
st.title("Encode knowledge from papers with cited references")
|
20 |
+
st.markdown("##### Current version searches on ArXiv only.")
|
21 |
+
|
22 |
+
api_key_url = 'https://help.openai.com/en/articles/4936850-where-do-i-find-my-secret-api-key'
|
23 |
+
|
24 |
+
api_key = st.text_input('OpenAI API Key',
|
25 |
+
placeholder='sk-...',
|
26 |
+
help=f"['What is that?']({api_key_url})",
|
27 |
+
type="password")
|
28 |
+
|
29 |
+
# st.write('The current movie title is', title)
|
30 |
+
os.environ["OPENAI_API_KEY"] = f"{api_key}" #
|
31 |
+
import paperqa
|
32 |
+
|
33 |
+
|
34 |
+
def call_arXiv_API(search_query, search_by='all', sort_by='relevance', max_results='10', folder_name='arxiv-dl'):
|
35 |
+
'''
|
36 |
+
Scraps the arXiv's html to get data from each entry in a search. Entries has the following formatting:
|
37 |
+
<entry>\n
|
38 |
+
<id>http://arxiv.org/abs/2008.04584v2</id>\n
|
39 |
+
<updated>2021-05-11T12:00:24Z</updated>\n
|
40 |
+
<published>2020-08-11T08:47:06Z</published>\n
|
41 |
+
<title>Bayesian Selective Inference: Non-informative Priors</title>\n
|
42 |
+
<summary> We discuss Bayesian inference for parameters selected using the data. First,\nwe provide a critical analysis of the existing positions in the literature\nregarding the correct Bayesian approach under selection. Second, we propose two\ntypes of non-informative priors for selection models. These priors may be\nemployed to produce a posterior distribution in the absence of prior\ninformation as well as to provide well-calibrated frequentist inference for the\nselected parameter. We test the proposed priors empirically in several\nscenarios.\n</summary>\n
|
43 |
+
<author>\n <name>Daniel G. Rasines</name>\n </author>\n <author>\n <name>G. Alastair Young</name>\n </author>\n
|
44 |
+
<arxiv:comment xmlns:arxiv="http://arxiv.org/schemas/atom">24 pages, 7 figures</arxiv:comment>\n
|
45 |
+
<link href="http://arxiv.org/abs/2008.04584v2" rel="alternate" type="text/html"/>\n
|
46 |
+
<link title="pdf" href="http://arxiv.org/pdf/2008.04584v2" rel="related" type="application/pdf"/>\n
|
47 |
+
<arxiv:primary_category xmlns:arxiv="http://arxiv.org/schemas/atom" term="math.ST" scheme="http://arxiv.org/schemas/atom"/>\n
|
48 |
+
<category term="math.ST" scheme="http://arxiv.org/schemas/atom"/>\n
|
49 |
+
<category term="stat.TH" scheme="http://arxiv.org/schemas/atom"/>\n
|
50 |
+
</entry>\n
|
51 |
+
'''
|
52 |
+
|
53 |
+
# Remove space in seach query
|
54 |
+
search_query=search_query.strip().replace(" ", "+")
|
55 |
+
# Call arXiv API
|
56 |
+
arXiv_url=f'http://export.arxiv.org/api/query?search_query={search_by}:{search_query}&sortBy={sort_by}&start=0&max_results={max_results}'
|
57 |
+
with urllib.request.urlopen(arXiv_url) as url:
|
58 |
+
s = url.read()
|
59 |
+
|
60 |
+
# Parse the xml data
|
61 |
+
root = html.fromstring(s)
|
62 |
+
# Fetch relevant pdf information
|
63 |
+
pdf_entries = root.xpath("entry")
|
64 |
+
|
65 |
+
pdf_titles = []
|
66 |
+
pdf_authors = []
|
67 |
+
pdf_urls = []
|
68 |
+
pdf_categories = []
|
69 |
+
folder_names = []
|
70 |
+
pdf_citation = []
|
71 |
+
pdf_years = []
|
72 |
+
|
73 |
+
for i, pdf in enumerate(pdf_entries):
|
74 |
+
# print(pdf.xpath('updated/text()')[0][:4])
|
75 |
+
# xpath return a list with every ocurrence of the html path. Since we're getting each entry individually, we'll take the first element to avoid an unecessary list
|
76 |
+
pdf_titles.append(re.sub('[^a-zA-Z0-9]', ' ', pdf.xpath("title/text()")[0]))
|
77 |
+
pdf_authors.append(pdf.xpath("author/name/text()"))
|
78 |
+
pdf_urls.append(pdf.xpath("link[@title='pdf']/@href")[0])
|
79 |
+
pdf_categories.append(pdf.xpath("category/@term"))
|
80 |
+
folder_names.append(folder_name)
|
81 |
+
pdf_years.append(pdf.xpath('updated/text()')[0][:4])
|
82 |
+
pdf_citation.append(f"{', '.join(pdf_authors[i])}, {pdf_titles[i]}. arXiv [{pdf_categories[i][0]}] ({pdf_years[i]}), (available at {pdf_urls[i]}).")
|
83 |
+
|
84 |
+
|
85 |
+
|
86 |
+
pdf_info=list(zip(pdf_titles, pdf_urls, pdf_authors, pdf_categories, folder_names, pdf_citation))
|
87 |
+
|
88 |
+
# Check number of available files
|
89 |
+
print('Requesting {max_results} files'.format(max_results=max_results))
|
90 |
+
if len(pdf_urls)<int(max_results):
|
91 |
+
matching_pdf_num=len(pdf_urls)
|
92 |
+
print('Only {matching_pdf_num} files available'.format(matching_pdf_num=matching_pdf_num))
|
93 |
+
return pdf_info, pdf_citation
|
94 |
+
|
95 |
+
|
96 |
+
def download_pdf(pdf_info):
|
97 |
+
|
98 |
+
# if len(os.listdir(f'./{folder_name}') ) != 0:
|
99 |
+
# check folder is empty to avoid using papers from old runs:
|
100 |
+
# os.remove(f'./{folder_name}/*')
|
101 |
+
|
102 |
+
for i,p in enumerate(stqdm(pdf_info, desc='Searching and downloading papers')):
|
103 |
+
|
104 |
+
pdf_title=p[0]
|
105 |
+
pdf_url=p[1]
|
106 |
+
pdf_author=p[2]
|
107 |
+
pdf_category=p[3]
|
108 |
+
folder_name=p[4]
|
109 |
+
pdf_citation=p[5]
|
110 |
+
r = requests.get(pdf_url, allow_redirects=True)
|
111 |
+
if i == 0:
|
112 |
+
if not os.path.exists(f'{folder_name}'):
|
113 |
+
os.makedirs(f"{folder_name}")
|
114 |
+
else:
|
115 |
+
shutil.rmtree(f'{folder_name}')
|
116 |
+
os.makedirs(f"{folder_name}")
|
117 |
+
with open(f'{folder_name}/{pdf_title}.pdf', 'wb') as currP:
|
118 |
+
currP.write(r.content)
|
119 |
+
if i == 0:
|
120 |
+
st.markdown("###### Papers found:")
|
121 |
+
st.markdown(f'{i+1}. {pdf_citation}')
|
122 |
+
|
123 |
+
|
124 |
+
|
125 |
+
|
126 |
+
# #subtitle
|
127 |
+
# st.markdown("## Optical Character Recognition - Using `easyocr`, `streamlit` - hosted on 🤗 Spaces")
|
128 |
+
|
129 |
+
# st.markdown("Link to the app - [image-to-text-app on 🤗 Spaces](https://huggingface.co/spaces/Amrrs/image-to-text-app)")
|
130 |
+
|
131 |
+
# #image uploader
|
132 |
+
# image = st.file_uploader(label = "Upload your image here",type=['png','jpg','jpeg'])
|
133 |
+
|
134 |
+
max_results_current = 1
|
135 |
+
max_results = max_results_current
|
136 |
+
pdf_info = ''
|
137 |
+
pdf_citation = ''
|
138 |
+
def search_click_callback(search_query, max_results):
|
139 |
+
global pdf_info, pdf_citation
|
140 |
+
pdf_info, pdf_citation = call_arXiv_API(f'{search_query}', max_results=max_results)
|
141 |
+
download_pdf(pdf_info)
|
142 |
+
|
143 |
+
|
144 |
+
|
145 |
+
|
146 |
+
with st.form(key='columns_in_form', clear_on_submit = False):
|
147 |
+
c1, c2 = st.columns([8,1])
|
148 |
+
with c1:
|
149 |
+
search_query = st.text_input("Input search query here:", placeholder='Keywords for most relevant search...', value=''
|
150 |
+
)#search_query, max_results_current))
|
151 |
+
|
152 |
+
with c2:
|
153 |
+
max_results = st.text_input("Max papers", value=max_results_current)
|
154 |
+
max_results_current = max_results_current
|
155 |
+
searchButton = st.form_submit_button(label = 'Search')
|
156 |
+
# search_click(search_query, max_results_default)
|
157 |
+
|
158 |
+
if searchButton:
|
159 |
+
text = st.write(search_click_callback(search_query, max_results))
|
160 |
+
|
161 |
+
def tokenize_callback():
|
162 |
+
global docs
|
163 |
+
docs = paperqa.Docs()
|
164 |
+
pdf_paths = [f"{p[4]}/{p[0]}.pdf" for p in pdf_info]
|
165 |
+
pdf_citations = [p[5] for p in pdf_info]
|
166 |
+
|
167 |
+
for d, c in stqdm(zip(pdf_paths, pdf_citations)):
|
168 |
+
docs.add(d, c)
|
169 |
+
# return docs
|
170 |
+
|
171 |
+
tokenization_form = st.form(key='tokenization-form')
|
172 |
+
tokenization_form.markdown(f"Happy with your paper search results? ")
|
173 |
+
toknizeButton = tokenization_form.form_submit_button(label = "Yes! Let's tokenize.", on_click=tokenize_callback())
|
174 |
+
tokenization_form.markdown("If not, change keywords and search again. [This step costs!](https://openai.com/api/pricing/)")
|
175 |
+
|
176 |
+
# submitButton = form.form_submit_button('Submit')
|
177 |
+
# with st.form(key='tokenization_form', clear_on_submit = False):
|
178 |
+
# st.markdown(f"Happy with your paper search results? If not, change keywords and search again. [This step costs!](https://openai.com/api/pricing/)")
|
179 |
+
# # st.text_input("Input search query here:", placeholder='Keywords for most relevant search...'
|
180 |
+
# # )#search_query, max_results_current))
|
181 |
+
# toknizeButton = st.form_submit_button(label = "Yes! Let's tokenize.")
|
182 |
+
|
183 |
+
# if toknizeButton:
|
184 |
+
# tokenize_callback()
|
185 |
+
|
186 |
+
def answer_callback(question_query):
|
187 |
+
answer = docs.query(question_query)
|
188 |
+
print(answer.formatted_answer)
|
189 |
+
return answer.formatted_answer
|
190 |
+
|
191 |
+
form = st.form(key='question_form')
|
192 |
+
question_query = form.text_input("What do you wanna know from these papers?", placeholder='Input questions here...',
|
193 |
+
value='')
|
194 |
+
submitButton = form.form_submit_button('Submit')
|
195 |
+
|
196 |
+
if submitButton:
|
197 |
+
text = st.text_area("Answer:", answer_callback(question_query), height=300)
|
198 |
+
|
199 |
+
# with st.form(key='question_form', clear_on_submit = False):
|
200 |
+
# question_query = st.text_input("What do you wanna know from these papers?", placeholder='Input questions here')
|
201 |
+
# # st.text_input("Input search query here:", placeholder='Keywords for most relevant search...'
|
202 |
+
# # )#search_query, max_results_current))
|
203 |
+
# submitButton = form.form_submit_button(label = "Submit", on_click=answer_callback(question_query))
|
204 |
+
|
205 |
+
|
206 |
+
# Simulation-based inference bayesian model selection
|
207 |
+
|
208 |
+
|
209 |
+
|
210 |
+
|
211 |
+
|
212 |
+
# test = "<ul> \
|
213 |
+
# <li>List item here</li> \
|
214 |
+
# <li>List item here</li> \
|
215 |
+
# <li>List item here</li> \
|
216 |
+
# <li>List item here</li> \
|
217 |
+
# </ul>"
|
218 |
+
# test = "'''It was the best of times, it was the worst of times, it was \
|
219 |
+
# the age of wisdom, it was the age of foolishness, it was \
|
220 |
+
# the epoch of belief, it was the epoch of incredulity, it \
|
221 |
+
# was the season of Light, it was the season of Darkness, it\
|
222 |
+
# was the spring of hope, it was the winter of despair, (...)'''"
|
223 |
+
|
224 |
+
# citation_text = st.text_area('Papers found:',test, height=300) # f'{pdf_citation}'
|
225 |
+
|
226 |
|
227 |
+
# for i, cite in enumerate(pdf_citation):
|
228 |
+
# st.markdown(f'{i+1}. {cite}')
|
229 |
+
# time.sleep(1)
|
230 |
|
|
|
231 |
|
232 |
+
# def make_clickable('link',text):
|
233 |
+
# return f'<a target="_blank" href="{link}">{text}'
|
requirements.txt
CHANGED
@@ -2,4 +2,8 @@ streamlit
|
|
2 |
opencv-python-headless
|
3 |
numpy
|
4 |
easyocr
|
5 |
-
Pillow
|
|
|
|
|
|
|
|
|
|
2 |
opencv-python-headless
|
3 |
numpy
|
4 |
easyocr
|
5 |
+
Pillow
|
6 |
+
urllib
|
7 |
+
lxml
|
8 |
+
stqdm
|
9 |
+
paper-qa
|