get-web-access 0.1.1__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
|
File without changes
|
get_web_access/main.py
ADDED
|
@@ -0,0 +1,311 @@
|
|
|
1
|
+
# /// script
|
|
2
|
+
# requires-python = ">=3.10"
|
|
3
|
+
# dependencies = [
|
|
4
|
+
# "click>=8.1",
|
|
5
|
+
# "openpyxl>=3.1",
|
|
6
|
+
# "pandas>=2.0",
|
|
7
|
+
# ]
|
|
8
|
+
# ///
|
|
9
|
+
|
|
10
|
+
import warnings
|
|
11
|
+
from datetime import datetime
|
|
12
|
+
from pathlib import Path
|
|
13
|
+
|
|
14
|
+
import click
|
|
15
|
+
import openpyxl
|
|
16
|
+
import pandas as pd
|
|
17
|
+
|
|
18
|
+
EXCEL_EXTENSIONS = {".xlsx", ".xls", ".xlsm", ".xlsb"}
|
|
19
|
+
DEFAULT_STYLE_WARNING = "Workbook contains no default style, apply openpyxl's default"
|
|
20
|
+
HEADER_ROW = 1
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def open_xlsx_readonly(file_path: Path, data_only: bool = True) -> openpyxl.Workbook:
|
|
24
|
+
with warnings.catch_warnings():
|
|
25
|
+
warnings.filterwarnings(
|
|
26
|
+
"ignore",
|
|
27
|
+
message=DEFAULT_STYLE_WARNING,
|
|
28
|
+
category=UserWarning,
|
|
29
|
+
)
|
|
30
|
+
return openpyxl.load_workbook(file_path, read_only=True, data_only=data_only)
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def normalize_domain_keyword(domain: str) -> str:
|
|
34
|
+
"""แปลง input domain ให้พร้อมใช้เป็น keyword ค้นหาแบบ case-insensitive"""
|
|
35
|
+
cleaned = domain.strip()
|
|
36
|
+
if cleaned.startswith(("http://", "https://")):
|
|
37
|
+
cleaned = cleaned.split("://", 1)[1]
|
|
38
|
+
cleaned = cleaned.split("/", 1)[0].strip()
|
|
39
|
+
return cleaned
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def select_local_excel_file(directory: Path = Path(".")) -> Path | None:
|
|
43
|
+
excel_files = sorted(
|
|
44
|
+
(f for f in directory.iterdir() if f.is_file() and not f.name.startswith("~$") and f.suffix.lower() in EXCEL_EXTENSIONS),
|
|
45
|
+
key=lambda f: f.name.lower(),
|
|
46
|
+
)
|
|
47
|
+
|
|
48
|
+
if not excel_files:
|
|
49
|
+
click.secho("ไม่พบไฟล์ Excel ในโฟลเดอร์ปัจจุบัน", fg="red", bold=True)
|
|
50
|
+
return None
|
|
51
|
+
|
|
52
|
+
click.secho("\nกรุณาเลือกไฟล์ Excel ในโฟลเดอร์ปัจจุบัน:", fg="bright_blue", bold=True)
|
|
53
|
+
for idx, file_path in enumerate(excel_files, start=1):
|
|
54
|
+
click.secho(f" {idx}. ", fg="yellow", nl=False)
|
|
55
|
+
click.secho(file_path.name, fg="white")
|
|
56
|
+
|
|
57
|
+
while True:
|
|
58
|
+
choice = click.prompt(
|
|
59
|
+
click.style(f"ใส่หมายเลข (1-{len(excel_files)}) หรือ q เพื่อออก", fg="cyan"),
|
|
60
|
+
type=str,
|
|
61
|
+
).strip()
|
|
62
|
+
|
|
63
|
+
if choice.lower() == "q":
|
|
64
|
+
return None
|
|
65
|
+
|
|
66
|
+
if choice.isdigit():
|
|
67
|
+
index = int(choice) - 1
|
|
68
|
+
if 0 <= index < len(excel_files):
|
|
69
|
+
click.secho(f"เลือกไฟล์: {excel_files[index].name}", fg="green")
|
|
70
|
+
return excel_files[index]
|
|
71
|
+
|
|
72
|
+
click.secho("ตัวเลือกไม่ถูกต้อง กรุณาลองใหม่อีกครั้ง", fg="red")
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def get_first_sheet(file_path: Path) -> str | int:
|
|
76
|
+
if file_path.suffix.lower() in {".xlsx", ".xlsm"}:
|
|
77
|
+
wb = open_xlsx_readonly(file_path, data_only=True)
|
|
78
|
+
try:
|
|
79
|
+
return wb.sheetnames[0] if wb.sheetnames else 0
|
|
80
|
+
finally:
|
|
81
|
+
wb.close()
|
|
82
|
+
|
|
83
|
+
excel_file = pd.ExcelFile(file_path)
|
|
84
|
+
try:
|
|
85
|
+
return excel_file.sheet_names[0] if excel_file.sheet_names else 0
|
|
86
|
+
finally:
|
|
87
|
+
excel_file.close()
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def read_excel_headers(file_path: Path, sheet_name: str | int = 0, header_row: int = HEADER_ROW) -> list[str]:
|
|
91
|
+
if file_path.suffix.lower() in {".xlsx", ".xlsm"}:
|
|
92
|
+
wb = open_xlsx_readonly(file_path, data_only=True)
|
|
93
|
+
try:
|
|
94
|
+
ws = wb[sheet_name] if isinstance(sheet_name, str) else wb.worksheets[sheet_name]
|
|
95
|
+
rows = ws.iter_rows(min_row=header_row, max_row=header_row, values_only=True)
|
|
96
|
+
first_row = next(rows, ())
|
|
97
|
+
return ["" if cell is None else str(cell).strip() for cell in first_row]
|
|
98
|
+
finally:
|
|
99
|
+
wb.close()
|
|
100
|
+
|
|
101
|
+
df = pd.read_excel(file_path, sheet_name=sheet_name, header=header_row - 1, nrows=0)
|
|
102
|
+
return [str(col).strip() for col in df.columns]
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def parse_columns_spec(spec: str, headers: list[str]) -> list[tuple[int, str]] | None:
|
|
106
|
+
cleaned = spec.strip().lower()
|
|
107
|
+
if not cleaned:
|
|
108
|
+
return None
|
|
109
|
+
|
|
110
|
+
if cleaned == "all":
|
|
111
|
+
return [(i, name) for i, name in enumerate(headers, start=1)]
|
|
112
|
+
|
|
113
|
+
selected_indices: list[int] = []
|
|
114
|
+
for part in cleaned.split(","):
|
|
115
|
+
token = part.strip()
|
|
116
|
+
if "-" in token:
|
|
117
|
+
bounds = token.split("-")
|
|
118
|
+
if len(bounds) != 2 or not (bounds[0].isdigit() and bounds[1].isdigit()):
|
|
119
|
+
return None
|
|
120
|
+
start, end = int(bounds[0]), int(bounds[1])
|
|
121
|
+
if not (1 <= start <= end <= len(headers)):
|
|
122
|
+
return None
|
|
123
|
+
selected_indices.extend(range(start, end + 1))
|
|
124
|
+
elif token.isdigit():
|
|
125
|
+
num = int(token)
|
|
126
|
+
if not (1 <= num <= len(headers)):
|
|
127
|
+
return None
|
|
128
|
+
selected_indices.append(num)
|
|
129
|
+
else:
|
|
130
|
+
return None
|
|
131
|
+
|
|
132
|
+
if not selected_indices:
|
|
133
|
+
return None
|
|
134
|
+
|
|
135
|
+
unique_indices = list(dict.fromkeys(selected_indices))
|
|
136
|
+
return [(i, headers[i - 1]) for i in unique_indices]
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
def select_columns_interactive(headers: list[str]) -> list[tuple[int, str]] | None:
|
|
140
|
+
if not headers:
|
|
141
|
+
raise click.ClickException("ไม่พบหัวคอลัมน์ในชีตนี้")
|
|
142
|
+
|
|
143
|
+
click.secho("\nHeader columns ที่มี:", fg="bright_blue", bold=True)
|
|
144
|
+
for idx, col in enumerate(headers, start=1):
|
|
145
|
+
click.secho(f" {idx}. ", fg="yellow", nl=False)
|
|
146
|
+
if col:
|
|
147
|
+
click.secho(col, fg="white")
|
|
148
|
+
else:
|
|
149
|
+
click.secho("(คอลัมน์ว่าง)", fg="bright_black")
|
|
150
|
+
|
|
151
|
+
click.secho(
|
|
152
|
+
"\nวิธีเลือก: พิมพ์หมายเลข เช่น 1 หรือ 1,3,5 หรือช่วง 1-3 | พิมพ์ all เพื่อเลือกทั้งหมด | พิมพ์ q เพื่อออก",
|
|
153
|
+
fg="magenta",
|
|
154
|
+
)
|
|
155
|
+
|
|
156
|
+
while True:
|
|
157
|
+
raw = click.prompt(
|
|
158
|
+
click.style("เลือกคอลัมน์สำหรับค้นหา", fg="cyan"),
|
|
159
|
+
type=str,
|
|
160
|
+
).strip()
|
|
161
|
+
if raw.lower() == "q":
|
|
162
|
+
return None
|
|
163
|
+
|
|
164
|
+
parsed = parse_columns_spec(raw, headers)
|
|
165
|
+
if parsed is not None:
|
|
166
|
+
selected_labels = ", ".join(name or f"Col {i}" for i, name in parsed)
|
|
167
|
+
click.secho(f"คอลัมน์ที่เลือก: {selected_labels}", fg="green")
|
|
168
|
+
return parsed
|
|
169
|
+
|
|
170
|
+
click.secho(f"รูปแบบไม่ถูกต้อง กรุณาใส่หมายเลขระหว่าง 1-{len(headers)}", fg="red")
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
def build_output_path(source_file: Path, output_dir: Path = Path(".")) -> Path:
|
|
174
|
+
output_dir.mkdir(parents=True, exist_ok=True)
|
|
175
|
+
timestamp = datetime.now().strftime("%Y-%m-%d_%H-%M")
|
|
176
|
+
return output_dir / f"{source_file.stem}_filtered_{timestamp}.xlsx"
|
|
177
|
+
|
|
178
|
+
|
|
179
|
+
def filter_and_export_excel(
|
|
180
|
+
file_path: Path,
|
|
181
|
+
headers: list[str],
|
|
182
|
+
chosen_columns: list[tuple[int, str]],
|
|
183
|
+
keyword: str,
|
|
184
|
+
sheet_name: str | int = 0,
|
|
185
|
+
header_row: int = HEADER_ROW,
|
|
186
|
+
chunk_size: int = 50_000,
|
|
187
|
+
output_dir: Path = Path("."),
|
|
188
|
+
) -> tuple[Path, int]:
|
|
189
|
+
needle = keyword.lower()
|
|
190
|
+
output_path = build_output_path(file_path, output_dir=output_dir)
|
|
191
|
+
|
|
192
|
+
out_wb = openpyxl.Workbook(write_only=True)
|
|
193
|
+
out_ws = out_wb.create_sheet(title="Filtered")
|
|
194
|
+
|
|
195
|
+
search_zero_based = [col_num - 1 for col_num, _ in chosen_columns]
|
|
196
|
+
export_headers = [col_name if col_name else f"Column_{idx}" for idx, col_name in enumerate(headers, start=1)]
|
|
197
|
+
total_cols = len(export_headers)
|
|
198
|
+
out_ws.append(export_headers)
|
|
199
|
+
|
|
200
|
+
matched_count = 0
|
|
201
|
+
|
|
202
|
+
try:
|
|
203
|
+
if file_path.suffix.lower() in {".xlsx", ".xlsm"}:
|
|
204
|
+
in_wb = open_xlsx_readonly(file_path, data_only=True)
|
|
205
|
+
try:
|
|
206
|
+
in_ws = in_wb[sheet_name] if isinstance(sheet_name, str) else in_wb.worksheets[sheet_name]
|
|
207
|
+
data_rows = in_ws.iter_rows(min_row=header_row + 1, values_only=True)
|
|
208
|
+
|
|
209
|
+
for row in data_rows:
|
|
210
|
+
if not row:
|
|
211
|
+
continue
|
|
212
|
+
|
|
213
|
+
row_len = len(row)
|
|
214
|
+
is_match = False
|
|
215
|
+
for idx in search_zero_based:
|
|
216
|
+
if idx >= row_len:
|
|
217
|
+
continue
|
|
218
|
+
val = row[idx]
|
|
219
|
+
if val is not None and needle in str(val).lower():
|
|
220
|
+
is_match = True
|
|
221
|
+
break
|
|
222
|
+
|
|
223
|
+
if is_match:
|
|
224
|
+
full_row = [row[i] if i < row_len else None for i in range(total_cols)]
|
|
225
|
+
out_ws.append(full_row)
|
|
226
|
+
matched_count += 1
|
|
227
|
+
if matched_count % chunk_size == 0:
|
|
228
|
+
click.secho(
|
|
229
|
+
f" พบข้อมูลตรงเงื่อนไขแล้ว {matched_count:,} แถว...",
|
|
230
|
+
fg="yellow",
|
|
231
|
+
)
|
|
232
|
+
finally:
|
|
233
|
+
in_wb.close()
|
|
234
|
+
else:
|
|
235
|
+
excel_file = pd.ExcelFile(file_path)
|
|
236
|
+
try:
|
|
237
|
+
df = pd.read_excel(
|
|
238
|
+
excel_file,
|
|
239
|
+
sheet_name=sheet_name,
|
|
240
|
+
header=header_row - 1,
|
|
241
|
+
)
|
|
242
|
+
total_rows = len(df)
|
|
243
|
+
search_col_names = [df.columns[idx] for idx in search_zero_based if idx < len(df.columns)]
|
|
244
|
+
|
|
245
|
+
for start in range(0, total_rows, chunk_size):
|
|
246
|
+
chunk = df.iloc[start : start + chunk_size]
|
|
247
|
+
mask = pd.Series(False, index=chunk.index)
|
|
248
|
+
|
|
249
|
+
for col in search_col_names:
|
|
250
|
+
series_str = chunk[col].dropna().astype(str).str.lower()
|
|
251
|
+
matched_idx = series_str[series_str.str.contains(needle, regex=False, na=False)].index
|
|
252
|
+
mask.loc[matched_idx] = True
|
|
253
|
+
|
|
254
|
+
filtered_chunk = chunk[mask]
|
|
255
|
+
for row_vals in filtered_chunk.itertuples(index=False, name=None):
|
|
256
|
+
out_ws.append(list(row_vals))
|
|
257
|
+
matched_count += 1
|
|
258
|
+
finally:
|
|
259
|
+
excel_file.close()
|
|
260
|
+
|
|
261
|
+
out_wb.save(output_path)
|
|
262
|
+
finally:
|
|
263
|
+
out_wb.close()
|
|
264
|
+
|
|
265
|
+
return output_path, matched_count
|
|
266
|
+
|
|
267
|
+
|
|
268
|
+
@click.command()
|
|
269
|
+
@click.option("-d", "--domain", required=True, help="ชื่อ domain ที่ใช้เป็น keyword ค้นหา")
|
|
270
|
+
def main(domain: str) -> None:
|
|
271
|
+
output_dir = Path(".")
|
|
272
|
+
keyword = normalize_domain_keyword(domain)
|
|
273
|
+
if not keyword:
|
|
274
|
+
raise click.ClickException(click.style("กรุณาระบุชื่อ domain ที่ถูกต้อง", fg="red"))
|
|
275
|
+
|
|
276
|
+
click.secho("Domain keyword: ", fg="cyan", nl=False)
|
|
277
|
+
click.secho(f"'{keyword}'", fg="bright_green", bold=True)
|
|
278
|
+
|
|
279
|
+
source_file = select_local_excel_file(output_dir)
|
|
280
|
+
if source_file is None:
|
|
281
|
+
click.secho("ยกเลิกการทำงาน", fg="yellow", bold=True)
|
|
282
|
+
return
|
|
283
|
+
|
|
284
|
+
target_sheet = get_first_sheet(source_file)
|
|
285
|
+
headers = read_excel_headers(source_file, sheet_name=target_sheet, header_row=HEADER_ROW)
|
|
286
|
+
|
|
287
|
+
chosen_columns = select_columns_interactive(headers)
|
|
288
|
+
if chosen_columns is None:
|
|
289
|
+
click.secho("ยกเลิกการทำงาน", fg="yellow", bold=True)
|
|
290
|
+
return
|
|
291
|
+
|
|
292
|
+
click.secho("\nกำลังค้นหาและส่งออกข้อมูลทั้งแถว...", fg="cyan", bold=True)
|
|
293
|
+
output_file, total_matched = filter_and_export_excel(
|
|
294
|
+
file_path=source_file,
|
|
295
|
+
headers=headers,
|
|
296
|
+
chosen_columns=chosen_columns,
|
|
297
|
+
keyword=keyword,
|
|
298
|
+
sheet_name=target_sheet,
|
|
299
|
+
header_row=HEADER_ROW,
|
|
300
|
+
output_dir=output_dir,
|
|
301
|
+
)
|
|
302
|
+
|
|
303
|
+
click.secho("\nเสร็จสิ้น!", fg="green", bold=True)
|
|
304
|
+
click.secho("จำนวนแถวที่พบ: ", fg="white", nl=False)
|
|
305
|
+
click.secho(f"{total_matched:,} แถว", fg="bright_yellow", bold=True)
|
|
306
|
+
click.secho("บันทึกไฟล์ไปที่: ", fg="white", nl=False)
|
|
307
|
+
click.secho(str(output_file.resolve()), fg="bright_cyan")
|
|
308
|
+
|
|
309
|
+
|
|
310
|
+
if __name__ == "__main__":
|
|
311
|
+
main()
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
Metadata-Version: 2.3
|
|
2
|
+
Name: get-web-access
|
|
3
|
+
Version: 0.1.1
|
|
4
|
+
Summary: Add your description here
|
|
5
|
+
Author: 6vi7ms
|
|
6
|
+
Author-email: 6vi7ms <6vi7ms@gmail.com>
|
|
7
|
+
Requires-Dist: click>=8.5.1
|
|
8
|
+
Requires-Dist: openpyxl>=3.1.5
|
|
9
|
+
Requires-Dist: pandas>=3.1.2
|
|
10
|
+
Requires-Python: >=3.13
|
|
11
|
+
Description-Content-Type: text/markdown
|
|
12
|
+
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
get_web_access/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
2
|
+
get_web_access/main.py,sha256=udd7yIVVA5OGd1dBpcxFZPTniGoO_MmnDx-0CSHoAeI,12434
|
|
3
|
+
get_web_access-0.1.1.dist-info/WHEEL,sha256=7hzKWg-J8I3Buqyw5tBii5z_MmAVsDYXXijd_QAtNZ8,81
|
|
4
|
+
get_web_access-0.1.1.dist-info/entry_points.txt,sha256=97cdaPO5JsS5CqHO0VwkN6hJSPo_FSDJTyJHbDQ4iSM,61
|
|
5
|
+
get_web_access-0.1.1.dist-info/METADATA,sha256=h8iUvQBUs48fMCH4DB2rqg9wRzX4f06ulirGW_L0ecU,301
|
|
6
|
+
get_web_access-0.1.1.dist-info/RECORD,,
|