forked from kaisugi/hyperdoc2vec
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathReferences.py
273 lines (265 loc) · 8.99 KB
/
References.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
# Author: Pierce Brooks
import re
import os
import sys
import json
import inspect
import logging
import traceback
from bs4 import BeautifulSoup
def replace(tag, replacement, tail):
tag.insert(0, replacement)
if (tail):
tag.append(replacement)
tag.unwrap()
def leaf(node, keys):
result = []
if ("dict" in str(type(node)).lower()):
for key in node:
if (keys):
result.append(key)
value = node[key]
result += leaf(value, keys)
elif ("list" in str(type(node)).lower()):
for i in range(len(node)):
result += leaf(node[i], keys)
else:
result.append(str(node))
return result
def fix(name):
if not (name.endswith(".html")):
return ""
name = name.replace(".html", "")
if not ("_" in name):
return name.replace("-", "/")
parts = name.split("_")
return parts[len(parts)-1].replace("-", "/")
def run(script, target, media, tropes, subpages):
names = [""]
paths = [""]
summaries = {}
references = {}
map = {}
if not (os.path.exists(target)):
return -1
locations = []
locations.append(media+".d")
locations.append(tropes+".d")
locations.append(subpages)
count = len(locations)
error = -count-2
limit = 50
for i in range(count):
location = locations[i]
if not (os.path.exists(location)):
return -i-2
for root, folders, files in os.walk(location):
length = len(files)
for j in range(length):
name = files[j]
path = os.path.join(root, name).replace("\\", "/")
name = fix(name)
if (name in names):
continue
paths.append(path)
names.append(name)
"""
if (j > limit):
break
"""
break
#break
length = len(names)
if not (length == len(paths)):
return error
descriptor = open(media, "r")
media = descriptor.read()
descriptor.close()
media = leaf(json.loads(media), False)
descriptor = open(tropes, "r")
tropes = descriptor.read()
descriptor.close()
tropes = json.loads(tropes)
descriptor = open(target, "r")
content = descriptor.read()
descriptor.close()
data = json.loads(content)
extra = {}
for key in data:
values = data[key]
for value in values:
if not (len(values[value]) == 0):
if not (value in data):
print(value)
extra[value] = []
data[key] = leaf(values, True)
for trope in tropes:
if not (trope in data):
data[trope] = []
for key in extra:
data[key] = extra[key]
"""
patterns = []
patterns.append(r"</?\w+>")
programs = []
for pattern in patterns:
programs.append(re.compile(pattern))
"""
for i in range(length):
name = names[i]
path = paths[i]
if (len(name) == 0):
continue
if not (name in data):
continue
try:
descriptor = open(path, encoding="raw_unicode_escape")
content = descriptor.read()
descriptor.close()
if (len(content) == 0):
continue
if not (name in map):
map[name] = path
references[name] = {}
else:
continue
print(name+" ("+str(i)+" / "+str(length)+")")
content = content.replace("<br>", "☺")
soup = BeautifulSoup(content)
body = soup.find("div", {"id": "main-article"})
"""
breaks = body.find_all("br", recursive=True)
for j in range(len(breaks)):
replace(breaks[j], "\n", False)
soup.prettify()
body = soup.find("div", {"id": "main-article"})
"""
paragraphs = body.find_all("p")
summary = ""
for paragraph in paragraphs:
summary += " ".join(list(paragraph.stripped_strings)).replace("\u263a", "\n").strip()+"\n"
links = paragraph.find_all("a", href=True)
urls = []
for link in links:
url = link["href"]
if not ("/pmwiki/pmwiki.php/" in url):
continue
url = url.replace("/pmwiki/pmwiki.php/", "")
if (url == name):
continue
if (url in urls):
continue
if not (len(data[name]) == 0):
if not (url in data[name]):
continue
if not ((url in tropes) or (url in media)):
continue
#print(url)
urls.append(url)
if (len(urls) == 0):
continue
content = " ".join(list(paragraph.stripped_strings)).replace("\u263a", "\n")
for link in links:
matcher = re.escape(" ".join(list(link.stripped_strings)).strip())+"\\s*:\\s*"
try:
match = re.search(matcher, content)
if (match == None):
continue
content = content.replace(match.group(0), "")
except:
print(matcher+"\n"+content)
content = content.strip()
references[name][content] = urls
summaries[name] = summary.strip()
items = body.find_all("li", recursive=True)
for item in items:
links = item.find_all("a", href=True)
urls = []
for link in links:
url = link["href"]
if not ("/pmwiki/pmwiki.php/" in url):
continue
url = url.replace("/pmwiki/pmwiki.php/", "")
if (url == name):
continue
if (url in urls):
continue
if not (len(data[name]) == 0):
if not (url in data[name]):
continue
if not ((url in tropes) or (url in media)):
continue
#print(url)
urls.append(url)
if (len(urls) == 0):
continue
content = " ".join(list(item.stripped_strings)).replace("\u263a", "\n")
for link in links:
matcher = re.escape(" ".join(list(link.stripped_strings)).strip())+"\\s*:\\s*"
try:
match = re.search(matcher, content)
if (match == None):
continue
content = content.replace(match.group(0), "")
except:
print(matcher+"\n"+content)
content = content.strip()
"""
for program in programs:
matches = []
match = None
while (True):
if (match == None):
match = program.search(content)
else:
match = program.search(content, pos=match.start())
if (match == None):
break
else:
print(content)
return error-1
matches.append(match)
if not (len(matches) == 0):
print(str(len(matches))+" "+content)
return error-1
"""
references[name][content] = urls
"""
if (i > limit):
break
"""
except Exception as exception:
logging.error(traceback.format_exc())
#"""
descriptor = open(script+".json", "w")
descriptor.write(json.dumps(references))
descriptor.close()
descriptor = open(script+".map.json", "w")
descriptor.write(json.dumps(map))
descriptor.close()
descriptor = open("Summaries.py.json", "w")
descriptor.write(json.dumps(summaries))
descriptor.close()
#"""
return 0
def launch(arguments):
if (len(arguments) < 4):
return False
script = arguments[0]
target = arguments[1]
media = arguments[2]
tropes = arguments[3]
subpages = arguments[4]
if not (os.path.exists(media)):
return False
if not (os.path.exists(tropes)):
return False
if not (os.path.exists(subpages)):
return False
result = run(script, target, media, tropes, subpages)
print(str(result))
if not (result == 0):
return False
return True
if (__name__ == "__main__"):
print(str(launch(sys.argv)))