-
Notifications
You must be signed in to change notification settings - Fork 5
/
main.py
241 lines (213 loc) · 9.53 KB
/
main.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
import pandas as pd
import csv
import tkinter as tk
from tkinter import ttk
from tkinter import filedialog as fd
from tkinter import messagebox
from SemanticScholarScrapper import *
import os
class MainGUI(object):
def __init__(self):
self.path, filename = os.path.split(os.path.realpath(__file__))
self.root = tk.Tk()
self.root.title('Zotero2SemanticScholar')
self.root.geometry('350x250')
self.root.protocol("WM_DELETE_WINDOW", self.onClosing)
# Email entry:
self.lblInfo = ttk.Label(self.root, text='Sign in SemanticScholar:')
self.lblEmail = ttk.Label(self.root, text='Email:')
self.entryEmail = ttk.Entry(self.root)
# Password entry:
self.lblPasswd = ttk.Label(self.root, text='Password:')
self.entryPasswd = ttk.Entry(self.root, show='*')
self.buttonSelectFiles = ttk.Button(
self.root,
text='Select a csv file exported by zotero...',
command=self._selectFiles
)
self.separator = ttk.Separator(self.root, orient='horizontal')
self.buttonSendData = ttk.Button(
self.root,
text='Send data to SemanticScholar.com...',
command=self._sendDataToSemanticscholar
)
self.lblLoading = ttk.Label(
self.root, text='Waiting for a file to be selected...')
self.fileName = ""
self.data = pd.DataFrame()
self.email = ""
self.passwd = ""
self.hasFile = False
self._pack()
self.saveFileName = self.path + "//saveDataSC.csv"
self.saveFile = None
self.logFileName = self.path + "//log.txt"
self.saveFileDataFrame = pd.DataFrame()
self._initSaveData()
self.logFile = open(self.logFileName, "a",
encoding="utf-8", errors='ignore')
self.hasAlreadySaveFile = False
self._autoFillID()
self.hasWriteIdInLog = False
if os.path.isfile("bibliography.csv"):
print(
"Has found bibliography.csv, it will be used by default, if no other file will be send")
self.fileName = "bibliography.csv"
self._csvToDataFrame()
def _initSaveData(self):
if (os.path.exists(self.saveFileName) == False):
self.saveFile = open(self.saveFileName, "a",
encoding="utf-8", errors='ignore')
self.saveFile.write("\"Key\",\"Title\"\n")
self.saveFile.close()
self.saveFileDataFrame = pd.read_csv(self.saveFileName)
self.saveFile = open(self.saveFileName, "a",
encoding="utf-8", errors='ignore')
else:
self.saveFile = open(self.saveFileName, "a",
encoding="utf-8", errors='ignore')
self.hasAlreadySaveFile = True
self.saveFileDataFrame = pd.read_csv(self.saveFileName)
def onClosing(self):
# if messagebox.askokcancel("Quit", "Do you want to quit?"):
self.root.destroy()
self.saveFile.close()
self.logFile.close()
def _pack(self):
self.lblInfo.pack(anchor='nw')
self.lblEmail.pack()
self.entryEmail.pack()
self.lblPasswd.pack()
self.entryPasswd.pack()
self.separator.pack(fill='x', pady=10)
self.buttonSelectFiles.pack(expand=True,
fill='both', padx=10, pady=10)
self.separator.pack(fill='x')
self.buttonSendData.pack(expand=True,
fill='both', padx=10, pady=10)
self.lblLoading.pack(expand=True,
fill='both')
def _selectFiles(self):
filetypes = (
('csv files', '*.csv'),
('All files', '*.*')
)
self.fileName = fd.askopenfilename(
title='Open a file',
initialdir='C://Users',
filetypes=filetypes)
self._csvToDataFrame()
def _csvToDataFrame(self):
self.lblLoading.config(text="Reading library...")
self.data = pd.read_csv(self.fileName)
val = []
for i in range(len(self.data.index)):
val.append(True)
self.data.insert(0, 'Ajouter une alarme', val)
self.data.insert(0, 'Ajouter dans la librairie', val)
self.data = self.data[['Ajouter une alarme', 'Ajouter dans la librairie',
'Key', 'Title', 'Author', 'Item Type', 'Publication Year']]
self.data = self.data.loc[self.data['Item Type'].isin([
'journalArticle', 'conferencePaper', 'bookSection', 'preprint', 'thesis', 'book'])]
self.hasFile = True
# for index, row in self.saveFileDataFrame.iterrows():
def _sendDataToSemanticscholar(self):
self.lblLoading.config(text="Connection to semanticScholar.com...")
self.writeInLog("Connection to semanticScholar.com...")
self.email = self.entryEmail.get()
self.passwd = self.entryPasswd.get()
if (self.email == '' or self.passwd == ''):
self.lblLoading.config(text="Please sign-in above")
messagebox.showerror('Error', 'Please fill the login field above')
self.writeInLog("Error - Please fill the login field above")
return
if (self.hasFile == False):
messagebox.showerror(
'Error', 'Please select a csv file containing your zotero librairies')
self.writeInLog(
"Error - Please select a csv file containing your zotero librairies")
return
messagebox.showinfo(
'Info', 'The application may not responding during scrapping.\n Go make yourself a coffee, it may take a few minutes.')
self.writeInLog(
"The application may not responding during scrapping. Go make yourself a coffee, it may take a few minutes.")
scrapper = SemanticScholarScrapper(self.logFile, self.path)
self.lblLoading.config(text="Login in progress...")
self.writeInLog(
"Login in progress...")
isConnected = scrapper.connect_to_account(self.email, self.passwd)
if (scrapper.is_connected):
self.writeInLog("Is connected.")
self.lblLoading.config(text="Sending data to semanticScholar...")
else:
self.lblLoading.config(
text="Unable to connect to SemanticScholar !")
messagebox.showerror(
'Error', 'Unable to connect to SemanticScholar !\nPlease check you login information or you connection and try again.')
self.writeInLog(
"Error - Unable to connect to SemanticScholar !\nPlease check you login information or you connection and try again.")
return
Alert = ""
self.data.reset_index(drop=True, inplace=True)
total_items = len(self.data)
for index, row in self.data.iterrows():
current_item = index + 1
if ((self.saveFileDataFrame['Key'] == row['Key']).any()):
self.writeInLog(
"skip : " + str(row['Title']) + " (Item " + str(current_item) + "/" + str(total_items) + ")\n")
continue
self.writeInLog(
"Searching " + str(row['Title']) + " (Item " + str(current_item) + "/" + str(total_items) + ")\n")
hasAddPaper = scrapper.scrap_paper_by_title(
row['Title'], False)
if (hasAddPaper == False):
msg = "Could not add " + str(row['Title']) + "\n"
self.writeInLog(msg)
Alert += msg
continue
addAlert = scrapper.alert()
saveToLibrary = scrapper.save_to_library()
if (addAlert == False and saveToLibrary == False):
msg = "Could not add alert on " + row['Title']+"\n"
self.writeInLog(
msg)
Alert += msg
continue
if (addAlert == False):
self.writeInLog(
"Could not add alert on " + row['Title'] + ", but add it to library.\n")
if (saveToLibrary == False):
self.writeInLog(
"Could not save " + row['Title'] + "in library, but add it to alert.\n")
title = row['Title'].replace(',', '')
self.saveFile.write("\""+row['Key']+"\", \""+title+"\"\n")
self.writeInLog(
"add " + row['Title'] + " to save file. " + self.saveFileName + " \n")
self.lblLoading.config(text="Finish sending data.")
self.writeInLog("Finish sending data.")
if (Alert != ''):
messagebox.showerror('Scrapping is over', Alert)
def writeInLog(self, msg):
if os.stat(self.logFileName).st_size == 0 and self.hasWriteIdInLog == False:
print("write id")
self.logFile.write("id : " + self.email + "\n")
self.hasWriteIdInLog = True
print("\n")
print(msg)
self.logFile.write(msg)
def _autoFillID(self):
with open(self.logFileName, 'r', encoding="utf-8", errors='ignore') as logFile:
# Read the first line
first_line = logFile.readline().strip()
# Extract the part after "id :"
if (first_line[0:5] != "id : "):
return
else:
id_part = first_line[5:]
if (id_part != ''):
self.entryEmail.insert(0, id_part)
def MainLoop(self):
self.root.mainloop()
if __name__ == "__main__":
gui = MainGUI()
gui.MainLoop()