-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscrape.py
162 lines (130 loc) · 4.98 KB
/
scrape.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
import os
import arxiv
import numpy as np
import pymysql.cursors
from omegaconf import OmegaConf
from sentence_transformers import SentenceTransformer
class Scraper:
def __init__(self, config: str) -> None:
"""
初期設定を行う
Args:
config (str): 設定ファイルパス
"""
self.config = OmegaConf.load(config)
os.makedirs(self.config.path_data, exist_ok=True)
def run(self) -> None:
"""実行関数"""
self.create_database()
self.scrape_paper()
self.create_embed()
def create_database(self) -> None:
"""論文情報用のデータベースを作成する"""
connection = pymysql.connect(
user="root",
password=self.config.password,
host=self.config.host,
)
with connection:
with connection.cursor() as cursor:
cursor.execute("CREATE DATABASE paper")
for category in self.config.category:
cursor.execute(
f"""
CREATE TABLE paper.{category} (
id INT AUTO_INCREMENT NOT NULL PRIMARY KEY,
title VARCHAR(200),
abstract TEXT,
author VARCHAR(50),
year INT,
month INT,
link VARCHAR(100)
);
"""
)
connection.commit()
cursor.close()
def scrape_paper(self) -> None:
"""論文情報をarxivからスクレイピングする"""
tags = " OR ".join(self.config.paper_tags)
for category in self.config.category:
data = []
search = arxiv.Search(
query=f"({tags}) AND ti:{category}",
max_results=10000,
sort_by=arxiv.SortCriterion.SubmittedDate,
)
for result in search.results():
year, month, _ = str(result.published).split(" ")[0].split("-")
data.append(
(
result.title.replace("'", "").replace('"', ""),
result.summary.replace("'", "").replace('"', ""),
str(result.authors[0]),
int(year),
int(month),
str(result.links[0]),
),
)
connection = pymysql.connect(
host=self.config.host,
user="root",
password=self.config.password,
database="paper",
cursorclass=pymysql.cursors.DictCursor,
)
with connection:
with connection.cursor() as cursor:
sql = (
f"INSERT INTO {category} (title, abstract, author, year, month, link)"
+ " VALUES ('%s', '%s', '%s', '%d', '%d', '%s')"
)
for i in range(len(data)):
try:
cursor.execute(sql % data[i])
except Exception:
pass
connection.commit()
print(f"{category} Paper: Get {len(data)} !!")
def create_embed(self) -> None:
"""論文タイトルとアブストラクトの埋め込みベクトルを作成する"""
model = SentenceTransformer(self.config.bert_model)
for category in self.config.category:
connection = pymysql.connect(
host=self.config.host,
user="root",
password=self.config.password,
database="paper",
cursorclass=pymysql.cursors.DictCursor,
)
with connection:
with connection.cursor() as cursor:
sql = """
SELECT title, abstract FROM Fairness;
"""
cursor.execute(sql)
titles, abstracts = [], []
for row in cursor:
title, abstract = row.values()
titles.append(title)
abstracts.append(abstract)
title_embed = model.encode(titles)
abstract_embed = model.encode(abstracts)
np.save(
f"{self.config.path_data}/{category}_title_embed.npy",
title_embed,
)
np.save(
f"{self.config.path_data}/{category}_abstract_embed.npy",
abstract_embed,
)
def main(config: str) -> None:
"""
論文情報収集スクリプト実行関数
Args:
config (str): 設定ファイルパス
"""
scraper = Scraper(config)
scraper.run()
if __name__ == "__main__":
main("config.yaml")