-
Notifications
You must be signed in to change notification settings - Fork 17
/
process.py
334 lines (281 loc) · 13.3 KB
/
process.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
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
import json
import os
import requests
from bs4 import BeautifulSoup
from openai import *
class Parser:
def __init__(self):
self.database = {}
pass
def parse_from_bib(self, bibpath):
print(bibpath)
with open(bibpath, 'r') as file:
bib_tex = file.read()
bib_tex = bib_tex.replace("{{", "{").replace("}}", "}").replace("{ ", "{").replace(" }", "}")
venue_database = {}
for entry_text in bib_tex.strip().split("\n@")[0:]:
entry_type, rest = entry_text.split("{", 1)
entry_dict = {}
entry_dict["type"] = entry_type.strip("@").strip()
key, attributes = rest.split(",", 1)
attributes = attributes.replace(", \n", ",\n")
entry_dict["key"] = key.strip()
entry_dict["venue"] = bibpath.split("/")[-1].split(".")[0]
attributes = attributes.rsplit("}", 1)[0]
for attribute in attributes.split(",\n"):
if "=" in attribute:
k, v = attribute.strip("\n").split("=", 1)
k = k.strip().strip("\n").strip().replace("\n", "")
v = v.strip().strip("\n").strip("{}").strip('"').strip(" ").strip(",").strip("}").replace("\n", "")\
.replace(" ", " ")
entry_dict[k] = v
if "title" not in entry_dict or "abstract" not in entry_dict:
continue
abstract = entry_dict["abstract"]
if abstract != "":
venue_database[entry_dict["title"]] = entry_dict
self.database.update(venue_database)
return venue_database
def parse_ndss_html(self, htmlpath):
with open(htmlpath, "r") as file:
lines = file.readlines()
venue_database = {}
for line in lines:
if "<a class=\"paper-link-abs\" href=" in line:
index1 = line.find("<a class=\"paper-link-abs\" href=")
index2 = line.find("><span")
weblink = line[index1+32:index2-2]
print(weblink)
response = requests.get(weblink)
if response.status_code == 200:
soup = BeautifulSoup(response.content, "html.parser")
if soup:
entry_title = soup.find("h1", class_="entry-title").get_text(strip=True)
paper_data = soup.find("div", class_="paper-data")
author_list_str = paper_data.find("p").get_text(strip=True)
abstract = ""
for p in paper_data.find_all("p")[2:]:
abstract += p.get_text(strip=True)
authors = [author.split('(')[0].strip() for author in author_list_str.split(',')]
print(entry_title)
print(authors)
print(abstract)
print("\n")
venue_database[entry_title] = {
"type": "INPROCEEDINGS",
"key": "",
"author": " and ".join(authors),
"booktitle": htmlpath.split("/")[-1].replace(".html", ""),
"title": entry_title,
"year": htmlpath.split("/")[-1].replace(".html", "").replace("NDSS", "").replace("ndss", ""),
"volume": "",
"number": "",
"pages": "",
"abstract": abstract,
"keywords": "",
"url": weblink,
"doi": "",
"ISSN": "",
"month": "",
"venue": htmlpath.split("/")[-1].replace(".html", "")
}
self.database.update(venue_database)
return
def parse_acl_html(self, htmlpath, venue, year):
prefix = str(year) + "." + venue.lower()
with open(htmlpath, "r") as file:
lines = file.readlines()
venue_database = {}
for line in lines:
if "href=/" + prefix in line and ".bib" not in line:
index1 = line.find("href=/")
s1 = line[index1:]
index2 = s1.find(">")
weblink = "https://aclanthology.org/" + s1[6:index2-1]
print(weblink)
response = requests.get(weblink)
title = ""
venue_name = ""
authors = []
year = ""
month = ""
id = ""
abstract = ""
pdf_link = ""
if response.status_code == 200:
for line in str(BeautifulSoup(response.content, "html.parser")).split("\n"):
if line.startswith("%T"):
title = line[3:].strip("\n").strip()
elif line.startswith("%A"):
authors.append(line[3:].strip("\n").strip())
elif line.startswith("%S"):
venue_name = line[3:].strip("\n").strip()
elif line.startswith("%D"):
year = line[3:].strip("\n").strip()
elif line.startswith("%8"):
month = line[3:].strip("\n").strip()
elif line.startswith("%F"):
id = line[3:].strip("\n").strip()
elif line.startswith("%X"):
abstract = line[3:].strip("\n").strip()
elif line.startswith("%U"):
pdf_link = line[3:].strip("\n").strip()
venue_database[title] = {
"type": "INPROCEEDINGS",
"key": id,
"author": " and ".join(authors),
"booktitle": htmlpath.split("/")[-1].replace(".html", ""),
"title": title,
"year": year,
"volume": "",
"number": "",
"pages": "",
"abstract": abstract,
"keywords": "",
"url": pdf_link,
"doi": "",
"ISSN": "",
"month": month,
"venue": htmlpath.split("/")[-1].replace(".html", "")
}
self.database.update(venue_database)
return
class Classifier:
def __init__(self, database):
self.database = database
pass
def keyword_match(self):
matching_dict = {}
for title in self.database:
paper = self.database[title]
if paper.get('type', '') == "software":
continue
abstract = paper.get('abstract', '').lower()
if ('code' in abstract.replace("our code", "") or 'program' in abstract.replace("our code", "")) and \
('llm' in abstract or 'large language model' in abstract or 'pretrain' in abstract or 'transformer' in abstract or 'code model' in abstract):
matching_dict[title] = paper
return matching_dict
@staticmethod
def get_openai_response(prompt):
client = OpenAI(api_key=os.environ.get("OPENAI_API_KEY").split(":")[0])
try:
model_input = [
{
"role": "system",
"content": "You are a senior CS researcher and good at categorizing papers.",
},
{"role": "user", "content": prompt},
]
response = client.chat.completions.create(
model="gpt-4o-mini", messages=model_input, temperature=0.0
)
output = response.choices[0].message.content
return output
except Exception as e:
return f"An error occurred: {e}"
def relevance_check(self, matching_dict):
def get_prompt(title, abstract):
prompt_template = """
Please check whether a given paper is related to large language models for code. You should carefully read the abstract and title of the paper.
If the paper concentrates on coding related tasks and leverage large language models, please answer YES. Otherwise, answer NO.
Here are the title and abstract of the paper:
[Title]: {title}
[Abstract]: {abstract}
Please think step by step and provide a clear explanation before concluding YES or NO.
The output format is as follows:
[Explanation]: Your explanation here.
[Answer]: YES or NO.
"""
return prompt_template.format(title=title, abstract=abstract)
def parse_output(output):
print(output)
answer = output.split("[Answer]: ")[1]
return answer
related_papers = {}
for title in matching_dict:
paper = matching_dict[title]
abstract = paper.get('abstract', '')
prompt = get_prompt(title, abstract)
output = Classifier.get_openai_response(prompt)
answer = parse_output(output)
if answer == "YES":
related_papers[title] = paper
return related_papers
def label_with_llms(self, related_papers):
def get_prompt(title, abstract, category_dict_str):
prompt_template = """
Please generate the labels for a given paper according to its title and abstract.
Here are the hierarchical labels:
{category_dict_str}
Here are the title and abstract of the paper:
[Title]: {title}
[Abstract]: {abstract}
When you choose the labels, you should also select all the labels that are parent of the labels you choose.
Please think step by step and provide a clear explanation before concluding YES or NO.
The output format is as follows:
[Explanation]: Your explanation here.
[Answer]: label1, label2, label3, ...
"""
return prompt_template.format(title=title, abstract=abstract, category_dict_str=category_dict_str)
def parse_output(output):
print(output)
labels = output.split("[Answer]: ")[1].split(", ")
return labels
labeled_related_papers = {}
with open("../data/category.json", "r") as file:
lines = file.readlines()
category_dict_str = "".join(lines)
for title in related_papers:
paper = related_papers[title]
title = paper.get('title', '')
abstract = paper.get('abstract', '')
prompt = get_prompt(title, abstract, category_dict_str)
output = Classifier.get_openai_response(prompt)
answer = parse_output(output)
paper['labels'] = answer
labeled_related_papers[title] = paper
with open("labeled_related_papers.json", "w") as file:
json.dump(labeled_related_papers, file, indent=4)
print("Labeled papers are saved in labeled_related_papers.json")
return related_papers
def classify(self):
matching_dict = classifier.keyword_match()
print(len(matching_dict))
related_papers = classifier.relevance_check(matching_dict)
print(len(related_papers))
classifier.label_with_llms(related_papers)
if __name__ == "__main__":
parser = Parser()
bibs_with_abstract = [
"../data/rawdata/2024/ICSE2024.bib",
"../data/rawdata/2024/FSE2024.bib",
"../data/rawdata/2024/ASE2024.bib",
"../data/rawdata/2024/ISSTA2024.bib",
"../data/rawdata/2024/TOSEM2024.bib",
"../data/rawdata/2024/TSE2024.bib",
"../data/rawdata/2024/PLDI2024.bib",
"../data/rawdata/2024/OOPSLA2024.bib",
"../data/rawdata/2024/S&P2024.bib",
"../data/rawdata/2023/ICSE2023.bib",
"../data/rawdata/2023/FSE2023.bib",
"../data/rawdata/2023/ASE2023.bib",
"../data/rawdata/2023/ISSTA2023.bib",
"../data/rawdata/2023/TOSEM2023.bib",
"../data/rawdata/2023/TSE2023.bib",
"../data/rawdata/2023/PLDI2023.bib",
"../data/rawdata/2023/OOPSLA2023.bib",
"../data/rawdata/2023/S&P2023.bib",
"../data/rawdata/2023/USENIXSec2023.bib",
"../data/rawdata/2023/CCS2023.bib",
]
for bib_with_abstract in bibs_with_abstract:
parser.parse_from_bib(bib_with_abstract)
# parser.parse_ndss_html("../data/rawdata/2024/NDSS2024.html")
# parser.parse_ndss_html("../data/rawdata/2023/NDSS2023.html")
# parser.parse_acl_html("../data/rawdata/2023/ACL2023.html", "ACL", 2023)
# parser.parse_acl_html("../data/rawdata/2023/EMNLP2023.html", "EMNLP", 2023)
# parser.parse_acl_html("../data/rawdata/2024/ACL2024.html", "ACL", 2024)
# parser.parse_acl_html("../data/rawdata/2024/NAACL2024.html", "NAACL", 2024)
print(len(parser.database))
classifier = Classifier(parser.database)
classifier.classify()