add utils and the main script
Browse files
app.py
ADDED
@@ -0,0 +1,94 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import logging
|
2 |
+
import os
|
3 |
+
import gradio as gr
|
4 |
+
import pandas as pd
|
5 |
+
from utils import get_zotero_ids, get_arxiv_papers, get_hf_embeddings, upload_to_pinecone, get_new_papers, recommend_papers
|
6 |
+
|
7 |
+
HF_API_KEY = os.getenv('HF_API_KEY')
|
8 |
+
PINECONE_API_KEY = os.getenv('PINECONE_API_KEY')
|
9 |
+
INDEX_NAME = os.getenv('INDEX_NAME')
|
10 |
+
NAMESPACE_NAME = os.getenv('NAMESPACE_NAME')
|
11 |
+
|
12 |
+
def category_radio(cat):
|
13 |
+
if cat == 'Computer Vision and Pattern Recognition':
|
14 |
+
return 'cs.CV'
|
15 |
+
elif cat == 'Computation and Language':
|
16 |
+
return 'cs.CL'
|
17 |
+
elif cat == 'Artificial Intelligence':
|
18 |
+
return 'cs.AI'
|
19 |
+
elif cat == 'Robotics':
|
20 |
+
return 'cs.RO'
|
21 |
+
|
22 |
+
def comment_radio(com):
|
23 |
+
if com == 'CVPR':
|
24 |
+
return 'CVPR'
|
25 |
+
else:
|
26 |
+
return None
|
27 |
+
|
28 |
+
def recommend_link(recs):
|
29 |
+
return recs
|
30 |
+
|
31 |
+
with gr.Blocks() as demo:
|
32 |
+
|
33 |
+
zotero_api_key = gr.Textbox(label="Zotero API Key")
|
34 |
+
|
35 |
+
zotero_library_id = gr.Textbox(label="Zotero Library ID")
|
36 |
+
|
37 |
+
zotero_tag = gr.Textbox(label="Zotero Tag")
|
38 |
+
|
39 |
+
arxiv_category_name = gr.State([])
|
40 |
+
radio_arxiv_category_name = gr.Radio(['Computer Vision and Pattern Recognition', 'Computation and Language', 'Artificial Intelligence', 'Robotics'], label="ArXiv Category Query")
|
41 |
+
radio_arxiv_category_name.change(fn = category_radio, inputs= radio_arxiv_category_name, outputs= arxiv_category_name)
|
42 |
+
|
43 |
+
arxiv_comment_query = gr.State([])
|
44 |
+
radio_arxiv_comment_query = gr.Radio(['CVPR', 'None'], label="ArXiv Comment Query")
|
45 |
+
radio_arxiv_comment_query.change(fn = comment_radio, inputs= radio_arxiv_comment_query, outputs= arxiv_comment_query)
|
46 |
+
|
47 |
+
threshold = gr.Slider(minimum= 0.70, maximum= 0.99, label="Similarity Score Threshold")
|
48 |
+
|
49 |
+
init_output = gr.Textbox(label="Project Initialization Result")
|
50 |
+
|
51 |
+
rec_output = gr.Markdown(label = "Recommended Papers")
|
52 |
+
|
53 |
+
init_btn = gr.Button("Initialize")
|
54 |
+
|
55 |
+
rec_btn = gr.Button("Recommend")
|
56 |
+
|
57 |
+
@init_btn.click(inputs= [zotero_api_key, zotero_library_id, zotero_tag], outputs= [init_output])
|
58 |
+
def init(zotero_api_key, zotero_library_id, zotero_tag, hf_api_key = HF_API_KEY, pinecone_api_key = PINECONE_API_KEY, index_name = INDEX_NAME, namespace_name = NAMESPACE_NAME):
|
59 |
+
|
60 |
+
logging.basicConfig(filename= '/mnt/c/Users/ankit/Desktop/Portfolio/Paper-Recommendation-System/logs/logfile.log', level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
|
61 |
+
logging.info("Project Initialization Script Started (Serverless)")
|
62 |
+
|
63 |
+
ids = get_zotero_ids(zotero_api_key, zotero_library_id, zotero_tag)
|
64 |
+
|
65 |
+
df = get_arxiv_papers(ids)
|
66 |
+
|
67 |
+
embeddings, dim = get_hf_embeddings(hf_api_key, df)
|
68 |
+
|
69 |
+
feedback = upload_to_pinecone(pinecone_api_key, index_name, namespace_name, embeddings, dim, df)
|
70 |
+
|
71 |
+
logging.info(feedback)
|
72 |
+
if feedback is dict:
|
73 |
+
return f"Retrieved {len(ids)} papers from Zotero. Successfully upserted {feedback['upserted_count']} embeddings in {namespace_name} namespace."
|
74 |
+
else :
|
75 |
+
return feedback
|
76 |
+
|
77 |
+
@rec_btn.click(inputs= [arxiv_category_name, arxiv_comment_query, threshold], outputs= [rec_output])
|
78 |
+
def recs(arxiv_category_name, arxiv_comment_query, threshold, hf_api_key = HF_API_KEY, pinecone_api_key = PINECONE_API_KEY, index_name = INDEX_NAME, namespace_name = NAMESPACE_NAME):
|
79 |
+
logging.info("Weekly Script Started (Serverless)")
|
80 |
+
|
81 |
+
df = get_arxiv_papers(category= arxiv_category_name, comment= arxiv_comment_query)
|
82 |
+
|
83 |
+
df = get_new_papers(df)
|
84 |
+
|
85 |
+
if not isinstance(df, pd.DataFrame):
|
86 |
+
return df
|
87 |
+
|
88 |
+
embeddings, _ = get_hf_embeddings(hf_api_key, df)
|
89 |
+
|
90 |
+
results = recommend_papers(pinecone_api_key, index_name, namespace_name, embeddings, df, threshold)
|
91 |
+
|
92 |
+
return results
|
93 |
+
|
94 |
+
demo.launch(share = True)
|
utils.py
ADDED
@@ -0,0 +1,132 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import pandas as pd
|
2 |
+
import arxiv
|
3 |
+
import requests
|
4 |
+
from pinecone import Pinecone, ServerlessSpec
|
5 |
+
import logging
|
6 |
+
import os
|
7 |
+
|
8 |
+
script_dir = os.path.dirname(os.path.abspath(__file__))
|
9 |
+
os.chdir(script_dir)
|
10 |
+
|
11 |
+
def get_zotero_ids(api_key, library_id, tag):
|
12 |
+
|
13 |
+
base_url = 'https://api.zotero.org'
|
14 |
+
suffix = '/users/'+ library_id +'/items?tag='+ tag
|
15 |
+
|
16 |
+
header = {'Authorization': 'Bearer '+ api_key}
|
17 |
+
request = requests.get(base_url + suffix, headers= header)
|
18 |
+
|
19 |
+
return [data['data']['archiveID'].replace('arXiv:', '') for data in request.json()]
|
20 |
+
|
21 |
+
def get_arxiv_papers(ids = None, category = None, comment = None):
|
22 |
+
|
23 |
+
logging.getLogger('arxiv').setLevel(logging.WARNING)
|
24 |
+
|
25 |
+
client = arxiv.Client()
|
26 |
+
|
27 |
+
if category is None:
|
28 |
+
search = arxiv.Search(
|
29 |
+
id_list= ids,
|
30 |
+
max_results= len(ids),
|
31 |
+
)
|
32 |
+
else :
|
33 |
+
if comment is None:
|
34 |
+
custom_query = f'cat:{category}'
|
35 |
+
else:
|
36 |
+
custom_query = f'cat:{category} AND co:{comment}'
|
37 |
+
|
38 |
+
search = arxiv.Search(
|
39 |
+
query = custom_query,
|
40 |
+
max_results= 15,
|
41 |
+
sort_by= arxiv.SortCriterion.SubmittedDate
|
42 |
+
)
|
43 |
+
if ids is None and category is None:
|
44 |
+
raise ValueError('not a valid query')
|
45 |
+
|
46 |
+
df = pd.DataFrame({'Title': [result.title for result in client.results(search)],
|
47 |
+
'Abstract': [result.summary.replace('\n', ' ') for result in client.results(search)],
|
48 |
+
'Date': [result.published.date().strftime('%Y-%m-%d') for result in client.results(search)],
|
49 |
+
'id': [result.entry_id for result in client.results(search)]})
|
50 |
+
|
51 |
+
if ids:
|
52 |
+
df.to_csv('arxiv-scrape.csv', index = False)
|
53 |
+
return df
|
54 |
+
|
55 |
+
def get_hf_embeddings(api_key, df):
|
56 |
+
|
57 |
+
title_abs = [title + '[SEP]' + abstract for title,abstract in zip(df['Title'], df['Abstract'])]
|
58 |
+
|
59 |
+
API_URL = "https://api-inference.huggingface.co/models/malteos/scincl"
|
60 |
+
headers = {"Authorization": f"Bearer {api_key}"}
|
61 |
+
|
62 |
+
response = requests.post(API_URL, headers=headers, json={"inputs": title_abs, "wait_for_model": False})
|
63 |
+
print(str(response.status_code) + 'This part needs an update, causing KeyError 0')
|
64 |
+
if response.status_code == 503:
|
65 |
+
response = requests.post(API_URL, headers=headers, json={"inputs": title_abs, "wait_for_model": True})
|
66 |
+
|
67 |
+
embeddings = response.json()
|
68 |
+
|
69 |
+
return embeddings, len(embeddings[0])
|
70 |
+
|
71 |
+
|
72 |
+
def upload_to_pinecone(api_key, index, namespace, embeddings, dim, df):
|
73 |
+
input = [{'id': df['id'][i], 'values': embeddings[i]} for i in range(len(embeddings))]
|
74 |
+
|
75 |
+
pc = Pinecone(api_key = api_key)
|
76 |
+
if index in pc.list_indexes().names():
|
77 |
+
while True:
|
78 |
+
logging.warning(f'Index name : {index} already exists.')
|
79 |
+
return f'Index name : {index} already exists'
|
80 |
+
|
81 |
+
pc.create_index(
|
82 |
+
name=index,
|
83 |
+
dimension=dim,
|
84 |
+
metric="cosine",
|
85 |
+
spec=ServerlessSpec(
|
86 |
+
cloud='aws',
|
87 |
+
region='us-east-1'
|
88 |
+
)
|
89 |
+
)
|
90 |
+
|
91 |
+
index = pc.Index(index)
|
92 |
+
return index.upsert(vectors=input, namespace=namespace)
|
93 |
+
|
94 |
+
|
95 |
+
def get_new_papers(df):
|
96 |
+
df_main = pd.read_csv('arxiv-scrape.csv')
|
97 |
+
df.reset_index(inplace=True)
|
98 |
+
df.drop(columns=['index'], inplace=True)
|
99 |
+
union_df = df.merge(df_main, how='left', indicator=True)
|
100 |
+
df = union_df[union_df['_merge'] == 'left_only'].drop(columns=['_merge'])
|
101 |
+
if df.empty:
|
102 |
+
return 'No New Papers Found'
|
103 |
+
else:
|
104 |
+
df_main = pd.concat([df_main, df], ignore_index= True)
|
105 |
+
df_main.drop_duplicates(inplace= True)
|
106 |
+
df_main.to_csv('arxiv-scrape.csv', index = False)
|
107 |
+
return df
|
108 |
+
|
109 |
+
def recommend_papers(api_key, index, namespace, embeddings, df, threshold):
|
110 |
+
|
111 |
+
pc = Pinecone(api_key = api_key)
|
112 |
+
if index in pc.list_indexes().names():
|
113 |
+
index = pc.Index(index)
|
114 |
+
else:
|
115 |
+
raise ValueError(f"{index} doesnt exist. Project isnt initialized properly")
|
116 |
+
|
117 |
+
results = []
|
118 |
+
score_threshold = threshold
|
119 |
+
for i,embedding in enumerate(embeddings):
|
120 |
+
query = embedding
|
121 |
+
result = index.query(namespace=namespace,vector=query,top_k=3,include_values=False)
|
122 |
+
sum_score = sum(match['score'] for match in result['matches'])
|
123 |
+
if sum_score > score_threshold:
|
124 |
+
results.append(f"Paper-URL : [{df['id'][i]}]({df['id'][i]}) with score: {sum_score / 3} <br />")
|
125 |
+
|
126 |
+
if results:
|
127 |
+
return '\n'.join(results)
|
128 |
+
else:
|
129 |
+
return 'No Interesting Paper'
|
130 |
+
|
131 |
+
|
132 |
+
|