-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.py
170 lines (131 loc) · 4.93 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
import json
import logging
from crawler import Frontier, Crawler, WebPage
from evaluation import Evaluator
from parser import SaverParser, ArxivParser, SpringerParser
from urllib.parse import urlparse
from text_processing import TextProcessor
from data import Document, Article
from pony.orm import db_session, commit, select
from index import InvertedIndex, IndexBuilder
from ranker import TfIdf, AbstractAndArticle
from doc2vec import Doc2VecModel
import argparse
import os
INDEX_FOLDER = "index"
CRAWLER_CONFIG = "config/crawler.json"
HOSTS_CONFIG = "config/hosts.json"
DUMP_FOLDER = "dumps"
MODEL_PATH = "doc2vec/model.dump"
VECTORS_PER_FILE = 512
VECTORS_SAVE_FOLDER = "ranker"
logger = logging.getLogger(__name__)
def start_crawlers():
with open(CRAWLER_CONFIG) as file:
# read configuration file
config = json.load(file)
with open(HOSTS_CONFIG) as file:
hosts = json.load(file)["hosts"]
parser = SaverParser("webdata")
for host in hosts:
if not os.path.exists(DUMP_FOLDER):
os.mkdir(DUMP_FOLDER)
dump_prefix = DUMP_FOLDER + "/" + urlparse(host)[1]
frontier = Frontier.restore_from_dump(dump_prefix)
if not frontier:
frontier = Frontier(urls={host}, allowed={host}, dump_prefix=dump_prefix)
crawler = Crawler(user_agent=config["user_agent"],
frontier=frontier,
parser=parser,
max_pages_count=int(config["max_pages_count"]),
max_depth=int(config["max_depth"]),
delay_ms=int(config["delay_ms"]),
frontier_dump_delay_s=config["frontier_dump_delay_s"])
crawler.start()
@db_session
def parse_documents():
arxiv_parser = ArxivParser(TextProcessor())
springer_parser = SpringerParser(TextProcessor())
for document in Document.select(lambda doc: not doc.is_processed):
if "arxiv.org" in urlparse(document.url)[1]:
cur_parser = arxiv_parser
elif "springer.com" in urlparse(document.url)[1]:
cur_parser = springer_parser
else:
continue
page = WebPage.from_disk(document.url, document.file_path)
if document.document_hash != page.page_hash:
Document[document.id].delete()
continue
parsed = cur_parser.parse(page)
document.is_processed = True
commit()
logging.debug(("Article: {}" if parsed else "{}").format(document.url))
@db_session
def build_index():
if not os.path.exists(INDEX_FOLDER):
os.mkdir(INDEX_FOLDER)
index = InvertedIndex.load(INDEX_FOLDER, InvertedIndex.NAME)
if index:
logging.debug("Index is successfully loaded")
return
logging.debug("Building index...")
articles = select(article.id for article in Article)[:]
index = InvertedIndex()
IndexBuilder(processes=1).build(index, articles)
logging.debug("Saving index...")
index.save(INDEX_FOLDER)
def run_web():
from web import app
app.run(host="127.0.0.1")
@db_session
def train_doc2vec():
articles = select(article for article in Article)[:]
model = Doc2VecModel(10)
model.fit(articles, 50)
model.save_model(MODEL_PATH)
@db_session
def run_rank():
text_processor = TextProcessor()
docs = []
index = InvertedIndex.load(INDEX_FOLDER, "inverted_index")
articles = select(article.id for article in Article)
for article_id in articles:
article = Article[article_id]
docs.append(AbstractAndArticle(article, _read_file(article.processed_abstract_path)))
ranker = TfIdf(index,
text_processor,
docs,
vectors_per_file=VECTORS_PER_FILE,
vectors_save_folder=VECTORS_SAVE_FOLDER)
while True:
query = input("Enter query: ")
top_ids = ranker.rank(query, 5)
for article_id in top_ids:
article = Article[article_id]
print(article.title, article.document.url)
def run_evaluation():
with open("queries.txt", "r") as queries_file:
queries = list(map(str.strip, queries_file.readlines()))
print(Evaluator().evaluate_to_latex(queries, "query.csv", "like.csv", relevance_cutoff=2))
def _read_file(path):
with open(path, "r") as file:
return " ".join(file.readlines())
parser = argparse.ArgumentParser(description="Information Retrieval")
parser.add_argument("mode", choices=["crawler", "parser", "index", "rank", "web", "doc2vec", "evaluate"])
if __name__ == "__main__":
args = parser.parse_args()
if args.mode == "crawler":
start_crawlers()
elif args.mode == "parser":
parse_documents()
elif args.mode == "index":
build_index()
elif args.mode == "web":
run_web()
elif args.mode == "rank":
run_rank()
elif args.mode == "doc2vec":
train_doc2vec()
elif args.mode == "evaluate":
run_evaluation()