Datasets:
Tasks:
Text Generation
Modalities:
Text
Sub-tasks:
language-modeling
Languages:
English
Size:
100K - 1M
License:
Zhangir Azerbayev
commited on
Commit
•
54efb7e
1
Parent(s):
afd65d6
WIP fetch mathoverflow
Browse files- fetch_mathoverflow.py +185 -0
fetch_mathoverflow.py
ADDED
@@ -0,0 +1,185 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from dataclasses import dataclass, field, fields
|
2 |
+
from functools import lru_cache
|
3 |
+
from xml.etree import ElementTree
|
4 |
+
from datetime import datetime
|
5 |
+
from enum import Enum
|
6 |
+
import typing
|
7 |
+
from typing import List, Optional, Union
|
8 |
+
import os.path
|
9 |
+
from itertools import groupby
|
10 |
+
import dataclasses
|
11 |
+
from tqdm import tqdm
|
12 |
+
from bs4 import BeautifulSoup
|
13 |
+
|
14 |
+
"""
|
15 |
+
Author: E.W.Ayers
|
16 |
+
|
17 |
+
This code takes a dump of math overflow XML and produces
|
18 |
+
a structured set of questions with answers.
|
19 |
+
|
20 |
+
1. Get mathoverflow.net.7z file
|
21 |
+
2. Extract this to `DATA_DIR = 'data/mathoverflow.net'`
|
22 |
+
3. Run `questions()` and run it to get a dictionary of mathoverflow questions.
|
23 |
+
Each question has an `Answers` field that contains a list of answers for the given q.
|
24 |
+
"""
|
25 |
+
|
26 |
+
# source: https://meta.stackexchange.com/questions/2677/database-schema-documentation-for-the-public-data-dump-and-sede
|
27 |
+
class PostType(Enum):
|
28 |
+
Question = 1
|
29 |
+
Answer = 2
|
30 |
+
OrphanedTagWiki = 3
|
31 |
+
TagWikiExcerpt = 4
|
32 |
+
TagWiki = 5
|
33 |
+
ModeratorNomination = 6
|
34 |
+
WikiPlaceholder = 7
|
35 |
+
PrivilegeWiki = 8
|
36 |
+
|
37 |
+
def is_optional(field):
|
38 |
+
return typing.get_origin(field) is Union and type(None) in typing.get_args(field)
|
39 |
+
|
40 |
+
def fromXML(cls, element):
|
41 |
+
out = {}
|
42 |
+
for field in fields(cls):
|
43 |
+
field_key = field.name
|
44 |
+
field_type = field.type
|
45 |
+
f = field.metadata.get('from_xml')
|
46 |
+
if f == 'skip':
|
47 |
+
continue
|
48 |
+
attr_key = f['key'] if (f is not None and f['key'] is not None) else field_key
|
49 |
+
v = element.attrib.get(attr_key)
|
50 |
+
if v is None:
|
51 |
+
if field.default is not dataclasses.MISSING:
|
52 |
+
out[field_key] = field.default
|
53 |
+
elif field.default_factory is not dataclasses.MISSING:
|
54 |
+
out[field_key] = field.default_factory() # type: ignore
|
55 |
+
elif is_optional(field_type):
|
56 |
+
out[field_key] = None
|
57 |
+
else:
|
58 |
+
raise Exception(f"Missing field {attr_key}")
|
59 |
+
continue
|
60 |
+
if is_optional(field_type):
|
61 |
+
field_type = typing.get_args(field_type)[0]
|
62 |
+
if f is not None and f['fn'] is not None:
|
63 |
+
out[field_key] = f['fn'](v)
|
64 |
+
elif field_type is int:
|
65 |
+
out[field_key] = int(v)
|
66 |
+
elif field_type is str:
|
67 |
+
out[field_key] = str(v)
|
68 |
+
elif field_type is datetime:
|
69 |
+
out[field_key] = datetime.fromisoformat(v)
|
70 |
+
else:
|
71 |
+
raise Exception(f"Don't know how to decode {field_type}")
|
72 |
+
return cls(**out)
|
73 |
+
|
74 |
+
def use(fn, key=None):
|
75 |
+
return field(metadata={'from_xml': {'fn': fn, 'key': key}})
|
76 |
+
|
77 |
+
def skip(default):
|
78 |
+
return field(default=default, metadata={'from_xml': 'skip'})
|
79 |
+
|
80 |
+
def iter_rows(path):
|
81 |
+
for [_, element] in ElementTree.iterparse(path, events = ['start']):
|
82 |
+
if (element.tag == 'row'):
|
83 |
+
yield element
|
84 |
+
|
85 |
+
DATA_DIR = 'stack_exchange/mathoverflow.net'
|
86 |
+
|
87 |
+
@dataclass
|
88 |
+
class Comment:
|
89 |
+
Id: int
|
90 |
+
PostId: int
|
91 |
+
Score: int
|
92 |
+
Text: str
|
93 |
+
CreationDate: datetime
|
94 |
+
UserId: Optional[int]
|
95 |
+
|
96 |
+
@lru_cache()
|
97 |
+
def comments():
|
98 |
+
path = os.path.join(DATA_DIR, 'Comments.xml')
|
99 |
+
out = {}
|
100 |
+
for element in iter_rows(path):
|
101 |
+
x : Comment = fromXML(Comment, element)
|
102 |
+
out[x.Id] = x
|
103 |
+
print(f"Processed {len(out)} comments.")
|
104 |
+
return out
|
105 |
+
|
106 |
+
@dataclass
|
107 |
+
class Post:
|
108 |
+
Id: int
|
109 |
+
CreationDate: datetime
|
110 |
+
DeletionDate: Optional[datetime]
|
111 |
+
Score: int
|
112 |
+
Body: str # in html; need to parse out?
|
113 |
+
Title: Optional[str]
|
114 |
+
OwnerUserId: Optional[int]
|
115 |
+
ViewCount: Optional[int]
|
116 |
+
AcceptedAnswerId: Optional[int]
|
117 |
+
ParentId: Optional[int]
|
118 |
+
PostType: "PostType" = use(lambda x: PostType(int(x)), 'PostTypeId')
|
119 |
+
Comments: List[Comment] = skip(None)
|
120 |
+
Answers: Optional[List["Post"]] = skip(None)
|
121 |
+
Tags: str = field(default="")
|
122 |
+
|
123 |
+
@lru_cache()
|
124 |
+
def questions():
|
125 |
+
path = os.path.join(DATA_DIR, 'Posts.xml')
|
126 |
+
cs = {}
|
127 |
+
for k, c in groupby(comments().values(), lambda c: c.PostId):
|
128 |
+
x = list(c)
|
129 |
+
x.sort(key = lambda x: -x.Score)
|
130 |
+
cs[k] = x
|
131 |
+
qs = {}
|
132 |
+
answers = {}
|
133 |
+
for element in iter_rows(path):
|
134 |
+
post = fromXML(Post, element)
|
135 |
+
post.Comments = cs.get(post.Id, [])
|
136 |
+
if (post.PostType is PostType.Question):
|
137 |
+
post.Answers = []
|
138 |
+
qs[post.Id] = post
|
139 |
+
elif (post.PostType is PostType.Answer):
|
140 |
+
answers[post.Id] = post
|
141 |
+
for qk, aa in groupby(answers.values(), lambda a: a.ParentId):
|
142 |
+
x = list(aa)
|
143 |
+
x.sort(key = lambda x: -x.Score)
|
144 |
+
qs[qk].Answers = x
|
145 |
+
print(f"Processed {len(qs)} questions with {len(answers)} answers.")
|
146 |
+
return qs
|
147 |
+
|
148 |
+
def strip_html(string):
|
149 |
+
soup = BeautifulSoup(string, 'html.parser')
|
150 |
+
return soup.get_text()
|
151 |
+
|
152 |
+
def text_of_post(post):
|
153 |
+
text = ""
|
154 |
+
if post.Title:
|
155 |
+
text += "TITLE: " + post.Title
|
156 |
+
|
157 |
+
text += f"\nQUESTION [{post.Score} upvotes]: {strip_html(post.Body).strip()}"
|
158 |
+
|
159 |
+
commented = False
|
160 |
+
|
161 |
+
answered = False
|
162 |
+
for answer in post.Answers:
|
163 |
+
if answer.Score >= 2:
|
164 |
+
answered = True
|
165 |
+
text += f"\n\nREPLY [{answer.Score} votes]: {strip_html(answer.Body).strip()}"
|
166 |
+
|
167 |
+
return text, post.Score, post.Id, answered
|
168 |
+
|
169 |
+
def pull_and_format(url, save_dir)
|
170 |
+
archive_path = os.path.join(save_dir, "archive.7z")
|
171 |
+
os.system(f"wget -O {archive_path} {url}")
|
172 |
+
|
173 |
+
sys.exit()
|
174 |
+
|
175 |
+
qs = questions()
|
176 |
+
|
177 |
+
qs_texts = [text_of_post(qs[key]) for key in tqdm(list(qs.keys())[1:100])]
|
178 |
+
|
179 |
+
for post, score, eyed, answered in tqdm(qs_texts):
|
180 |
+
if score >= 5 and answered:
|
181 |
+
with open(os.path.join("stack_exchange", str(eyed) + ".txt"), "w") as f:
|
182 |
+
f.write(post)
|
183 |
+
if __name__ == '__main__':
|
184 |
+
pull_and_format("https://archive.org/download/stackexchange/mathoverflow.net.7z",
|
185 |
+
"stack_exchange/math_overflow")
|