Repository navigation
Expand file tree
/
Copy pathshared.py
More file actions
219 lines (188 loc) · 5.35 KB
/
Copy pathshared.py
File metadata and controls
219 lines (188 loc) · 5.35 KB
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
from datetime import datetime, timezone
import json
import re
from queue import Queue
import token
from urllib.parse import urlparse, urlunparse
from sklearn.feature_extraction.text import ENGLISH_STOP_WORDS
META_RAW = "./Data/meta_raw.jsonl"
CHUNKS = "./Data/chunked.jsonl"
QUERIES = "./Data/queries.jsonl"
QUERY_RESULTS = "./Data/queries/"
document_queue = Queue()
# Format: {docno: {"url": url, "ext": ext, "time": timestamp, "title": title}}
meta_raw = {}
chunks = []
corpus = []
def import_meta_raw():
global meta_raw
meta_raw = {}
try:
with open(META_RAW, "r", encoding="utf-8") as file:
for line in file:
if not line.strip():
continue
try:
temp = json.loads(line)
docno = temp["docno"]
meta_raw[docno] = {
"url": temp["url"],
"ext": temp["ext"],
"time": temp["time"],
"title": temp["title"]
}
except Exception as e:
print(f"Error parsing line: {line}. Error: {e}")
continue
except FileNotFoundError:
print(f"{META_RAW} file not found. Starting with an empty meta_raw.")
return meta_raw
def add_meta(docno, title, url, ext):
meta_raw[docno] = {
"url": url,
"ext": ext,
"time": datetime.now(timezone.utc).isoformat(),
"title": title
}
if (len(meta_raw) % 100) == 0: # Save every 100 entries
save_meta_raw() # Save the metadata after adding a new entry
def save_meta_raw():
with open(META_RAW, "w", encoding="utf-8") as file:
file.write("") # Clear the file before writing new data
for docno, meta in meta_raw.items():
temp = {
"docno": docno,
"url": meta["url"],
"ext": meta["ext"],
"time": meta["time"],
"title": meta["title"]
}
with open(META_RAW, "a", encoding="utf-8") as file:
file.write(json.dumps(temp) + "\n")
def normalize_url(url):
parsed_url = urlparse(url)
normalized_path = parsed_url.path.rstrip("/")
normalized_url = urlunparse(
(parsed_url.scheme, parsed_url.netloc, normalized_path, "", "", "")
)
return normalized_url
def import_chunks():
global chunks
if not chunks:
try:
with open(CHUNKS, "r", encoding="utf-8") as f:
chunks = [json.loads(line) for line in f]
except FileNotFoundError:
print(f"{CHUNKS} file not found. Starting with an empty chunks list.")
chunks = []
return chunks
def load_corpus():
global corpus
import_chunks()
if not corpus:
corpus = [
normalize_text_tokens(
chunk.get("chunk_text", "") + " " + chunk.get("chunk_title", "")
)
for chunk in chunks
]
return corpus
def filter_url(normalized_url):
parsed = urlparse(normalized_url)
# Only HTTP/HTTPS
if parsed.scheme not in ["http", "https"]:
return False
# Remove authentication/user pages
forbidden_keywords = {
"login",
"signin",
"signup",
"register",
"logout",
"account",
"profile",
"dashboard",
"settings",
"subscribe",
}
# Parse URL path into individual segments
path_segments = {
segment.lower()
for segment in parsed.path.split("/")
if segment
}
# Reject URLs containing an exact forbidden path segment
if path_segments & forbidden_keywords:
return False
# Remove shopping/non-document pages
forbidden_paths = {
"cart",
"checkout",
"payment",
"pricing",
"store",
"shop",
}
# Check exact path segments instead of arbitrary substrings
if path_segments & forbidden_paths:
return False
# Remove files that are not documents
forbidden_extensions = [
".png",
".jpg",
".jpeg",
".gif",
".svg",
".ico",
".webp",
".css",
".js",
".json",
".xml",
".zip",
".tar",
".gz",
".exe",
".dmg",
".pdf",
".tar.gz",
]
path_lower = parsed.path.lower()
for ext in forbidden_extensions:
if path_lower.endswith(ext):
return False
# Remove social media links
forbidden_domains = [
"facebook.com",
"twitter.com",
"x.com",
"linkedin.com",
"youtube.com",
"github.com"
]
for domain in forbidden_domains:
if domain in parsed.netloc:
return False
return True
def _light_stem(word):
suffixes = [
"ingly",
"edly",
"ing",
"ed",
"ly",
"ies",
"es",
"s"
]
for suffix in suffixes:
if word.endswith(suffix) and len(word) > len(suffix) + 2:
return word[:-len(suffix)]
# Only remove plural s in safer cases
if word.endswith("s") and not word.endswith(("ss", "us", "is")):
if len(word) > 3:
return word[:-1]
return word
def normalize_text_tokens(text):
tokens = re.findall(r"[a-zA-Z]+", text.lower())
return [_light_stem(token) for token in tokens]