get-evidence-summary 1.0.0__tar.gz

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.
@@ -0,0 +1,12 @@
1
+ Metadata-Version: 2.3
2
+ Name: get-evidence-summary
3
+ Version: 1.0.0
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
+
File without changes
@@ -0,0 +1,22 @@
1
+ [project]
2
+ name = "get-evidence-summary"
3
+ version = "1.0.0"
4
+ description = "Add your description here"
5
+ readme = "README.md"
6
+ requires-python = ">=3.13"
7
+ dependencies = [
8
+ "click>=8.5.1",
9
+ "openpyxl>=3.1.5",
10
+ "pandas>=3.1.2",
11
+ ]
12
+
13
+ [[project.authors]]
14
+ name = "6vi7ms"
15
+ email = "6vi7ms@gmail.com"
16
+
17
+ [project.scripts]
18
+ get-evidence-summary = "get_evidence_summary.main:main"
19
+
20
+ [build-system]
21
+ requires = ["uv_build>=0.12.18,<0.13.0"]
22
+ build-backend = "uv_build"
@@ -0,0 +1,15 @@
1
+ [project]
2
+ name = "get-evidence-summary"
3
+ version = "1.0.0"
4
+ description = "Add your description here"
5
+ readme = "README.md"
6
+ authors = [{ name = "6vi7ms", email = "6vi7ms@gmail.com" }]
7
+ requires-python = ">=3.13"
8
+ dependencies = ["click>=8.5.1", "openpyxl>=3.1.5", "pandas>=3.1.2"]
9
+
10
+ [project.scripts]
11
+ get-evidence-summary = "get_evidence_summary.main:main"
12
+
13
+ [build-system]
14
+ requires = ["uv_build>=0.12.18,<0.13.0"]
15
+ build-backend = "uv_build"
@@ -0,0 +1,692 @@
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 re
11
+ import warnings
12
+ from collections import Counter, defaultdict
13
+ from datetime import date, datetime, time
14
+ from pathlib import Path
15
+ from urllib.parse import urlparse
16
+
17
+ import click
18
+ import openpyxl
19
+ import pandas as pd
20
+
21
+ EXCEL_EXTENSIONS = {".xlsx", ".xls", ".xlsm", ".xlsb"}
22
+ DEFAULT_STYLE_WARNING = "Workbook contains no default style, apply openpyxl's default"
23
+ HEADER_ROW = 1
24
+ URL_COLUMN_HINTS = ("url", "link", "website", "web", "domain", "uri", "href", "host")
25
+ URL_PATTERN = re.compile(
26
+ r"(?:https?://[^\s,;|]+|www\.[^\s,;|]+|\b[a-z0-9-]+(?:\.[a-z0-9-]+)+(?:/[^\s,;|]*)?)",
27
+ re.IGNORECASE,
28
+ )
29
+ THAI_SHORT_MONTHS = (
30
+ "ม.ค.",
31
+ "ก.พ.",
32
+ "มี.ค.",
33
+ "เม.ย.",
34
+ "พ.ค.",
35
+ "มิ.ย.",
36
+ "ก.ค.",
37
+ "ส.ค.",
38
+ "ก.ย.",
39
+ "ต.ค.",
40
+ "พ.ย.",
41
+ "ธ.ค.",
42
+ )
43
+
44
+
45
+ def open_xlsx_readonly(file_path: Path, data_only: bool = True) -> openpyxl.Workbook:
46
+ with warnings.catch_warnings():
47
+ warnings.filterwarnings(
48
+ "ignore",
49
+ message=DEFAULT_STYLE_WARNING,
50
+ category=UserWarning,
51
+ )
52
+ return openpyxl.load_workbook(file_path, read_only=True, data_only=data_only)
53
+
54
+
55
+ def normalize_single_keyword(raw_item: str) -> str:
56
+ """จัดรูปแบบคำค้นหาเบื้องต้นให้พร้อมใช้ค้นหาแบบ case-insensitive"""
57
+ cleaned = raw_item.strip()
58
+ if cleaned.startswith(("http://", "https://")):
59
+ cleaned = cleaned.split("://", 1)[1]
60
+ if "/" in cleaned and not cleaned.startswith(("/", ".")):
61
+ host_part = cleaned.split("/", 1)[0].strip()
62
+ if host_part and " " not in host_part:
63
+ return host_part
64
+ return cleaned
65
+
66
+
67
+ def parse_keywords(keyword_inputs: tuple[str, ...]) -> list[str]:
68
+ """แยกและจัดระเบียบหลาย keywords จากการคั่นด้วย , ; หรือการส่ง -k ซ้ำหลายครั้ง"""
69
+ keywords: list[str] = []
70
+ seen_lower: set[str] = set()
71
+
72
+ for raw_entry in keyword_inputs:
73
+ for token in re.split(r"[,;\r\n]+", raw_entry):
74
+ normalized = normalize_single_keyword(token)
75
+ if not normalized:
76
+ continue
77
+ lowered = normalized.lower()
78
+ if lowered not in seen_lower:
79
+ seen_lower.add(lowered)
80
+ keywords.append(normalized)
81
+
82
+ return keywords
83
+
84
+
85
+ def extract_domain_from_url_like(raw_value: str) -> str | None:
86
+ """ดึงเฉพาะชื่อ domain กรณีข้อความมีรูปแบบ URL หรือ domain"""
87
+ candidate = raw_value.strip().strip("\"'`<>[](){},;")
88
+ if not candidate:
89
+ return None
90
+
91
+ matched = URL_PATTERN.search(candidate)
92
+ if not matched:
93
+ return None
94
+
95
+ matched_str = matched.group(0).strip().rstrip(".,)")
96
+ target = matched_str if "://" in matched_str else f"http://{matched_str}"
97
+ try:
98
+ parsed = urlparse(target)
99
+ except ValueError:
100
+ return None
101
+
102
+ host = (parsed.hostname or "").strip().lower()
103
+ if not host or "." not in host:
104
+ return None
105
+
106
+ host = host.removeprefix("www.")
107
+ return host or None
108
+
109
+
110
+ def normalize_target_item(raw_value: str, is_url_column: bool) -> str | None:
111
+ """แปลงค่าที่พบให้อยู่ในรูปแบบที่เหมาะกับบริบทของคอลัมน์ (domain หากเป็น URL/domain หรือข้อความเดิม)"""
112
+ text = raw_value.strip()
113
+ if not text:
114
+ return None
115
+
116
+ domain_name = extract_domain_from_url_like(text)
117
+ if domain_name:
118
+ return domain_name
119
+
120
+ if is_url_column:
121
+ cleaned_host = text.lower().removeprefix("http://").removeprefix("https://").removeprefix("www.")
122
+ cleaned_host = cleaned_host.split("/", 1)[0].split("?", 1)[0].strip()
123
+ return cleaned_host or None
124
+
125
+ return text
126
+
127
+
128
+ def is_item_matched_by_keywords(item_value: str, keywords: list[str]) -> bool:
129
+ """ตรวจสอบว่ารายการที่พบตรงหรือสอดคล้องกับคำค้นหาใดคำค้นหาหนึ่งหรือไม่"""
130
+ item_lower = item_value.lower()
131
+ for kw in keywords:
132
+ kw_lower = kw.lower().strip()
133
+ if not kw_lower:
134
+ continue
135
+ if kw_lower in item_lower or item_lower == kw_lower:
136
+ return True
137
+ return False
138
+
139
+
140
+ def parse_datetime_value(val: object) -> datetime | None:
141
+ """แปลงค่าจากเซลล์ Excel เป็น datetime หากสามารถตีความได้"""
142
+ if val is None:
143
+ return None
144
+ if isinstance(val, datetime):
145
+ return val
146
+ if isinstance(val, date):
147
+ return datetime.combine(val, time.min)
148
+ if isinstance(val, pd.Timestamp):
149
+ if pd.isna(val):
150
+ return None
151
+ return val.to_pydatetime()
152
+
153
+ text = str(val).strip()
154
+ if not text or text.lower() in {"nan", "nat", "none", "null", "-"}:
155
+ return None
156
+
157
+ parsed = pd.to_datetime(text, errors="coerce")
158
+ if pd.isna(parsed):
159
+ return None
160
+ return parsed.to_pydatetime()
161
+
162
+
163
+ def format_thai_be_datetime(dt: datetime) -> str:
164
+ """แปลง datetime เป็นรูปแบบ 01 ม.ค.69 เวลา 01:00:01 น."""
165
+ day_str = f"{dt.day:02d}"
166
+ month_str = THAI_SHORT_MONTHS[dt.month - 1]
167
+ be_two_digit = (dt.year + 543) % 100
168
+ be_str = f"{be_two_digit:02d}"
169
+ time_str = dt.strftime("%H:%M:%S")
170
+ return f"{day_str} {month_str}{be_str} เวลา {time_str} น."
171
+
172
+
173
+ def format_thai_datetime_range(min_dt: datetime | None, max_dt: datetime | None) -> str:
174
+ """จัดรูปแบบช่วงวันที่และเวลาในรายงาน"""
175
+ if min_dt is None or max_dt is None:
176
+ return "ข้อมูลเป็นข้อมูลระหว่างวันที่ - เวลา - น. ถึง - เวลา - น."
177
+
178
+ if max_dt < min_dt:
179
+ min_dt, max_dt = max_dt, min_dt
180
+
181
+ start_str = format_thai_be_datetime(min_dt)
182
+ end_str = format_thai_be_datetime(max_dt)
183
+
184
+ return f"ข้อมูลเป็นข้อมูลระหว่างวันที่ {start_str} ถึง {end_str}"
185
+
186
+
187
+ def select_local_excel_file(directory: Path = Path(".")) -> Path | None:
188
+ excel_files = sorted(
189
+ (f for f in directory.iterdir() if f.is_file() and not f.name.startswith("~$") and f.suffix.lower() in EXCEL_EXTENSIONS),
190
+ key=lambda f: f.name.lower(),
191
+ )
192
+
193
+ if not excel_files:
194
+ click.secho("ไม่พบไฟล์ Excel ในโฟลเดอร์ปัจจุบัน", fg="red", bold=True)
195
+ return None
196
+
197
+ click.secho("\nกรุณาเลือกไฟล์ Excel ในโฟลเดอร์ปัจจุบัน:", fg="bright_blue", bold=True)
198
+ for idx, file_path in enumerate(excel_files, start=1):
199
+ click.secho(f" {idx}. ", fg="yellow", nl=False)
200
+ click.secho(file_path.name, fg="white")
201
+
202
+ while True:
203
+ choice = click.prompt(
204
+ click.style(f"ใส่หมายเลข (1-{len(excel_files)}) หรือ q เพื่อออก", fg="cyan"),
205
+ type=str,
206
+ ).strip()
207
+
208
+ if choice.lower() == "q":
209
+ return None
210
+
211
+ if choice.isdigit():
212
+ index = int(choice) - 1
213
+ if 0 <= index < len(excel_files):
214
+ click.secho(f"เลือกไฟล์: {excel_files[index].name}", fg="green")
215
+ return excel_files[index]
216
+
217
+ click.secho("ตัวเลือกไม่ถูกต้อง กรุณาลองใหม่อีกครั้ง", fg="red")
218
+
219
+
220
+ def get_first_sheet(file_path: Path) -> str | int:
221
+ if file_path.suffix.lower() in {".xlsx", ".xlsm"}:
222
+ wb = open_xlsx_readonly(file_path, data_only=True)
223
+ try:
224
+ return wb.sheetnames[0] if wb.sheetnames else 0
225
+ finally:
226
+ wb.close()
227
+
228
+ excel_file = pd.ExcelFile(file_path)
229
+ try:
230
+ return excel_file.sheet_names[0] if excel_file.sheet_names else 0
231
+ finally:
232
+ excel_file.close()
233
+
234
+
235
+ def read_excel_headers(file_path: Path, sheet_name: str | int = 0, header_row: int = HEADER_ROW) -> list[str]:
236
+ if file_path.suffix.lower() in {".xlsx", ".xlsm"}:
237
+ wb = open_xlsx_readonly(file_path, data_only=True)
238
+ try:
239
+ ws = wb[sheet_name] if isinstance(sheet_name, str) else wb.worksheets[sheet_name]
240
+ rows = ws.iter_rows(min_row=header_row, max_row=header_row, values_only=True)
241
+ first_row = next(rows, ())
242
+ return ["" if cell is None else str(cell).strip() for cell in first_row]
243
+ finally:
244
+ wb.close()
245
+
246
+ df = pd.read_excel(file_path, sheet_name=sheet_name, header=header_row - 1, nrows=0)
247
+ return [str(col).strip() for col in df.columns]
248
+
249
+
250
+ def parse_columns_spec(spec: str, headers: list[str]) -> list[tuple[int, str]] | None:
251
+ cleaned = spec.strip().lower()
252
+ if not cleaned:
253
+ return None
254
+
255
+ if cleaned == "all":
256
+ return [(i, name) for i, name in enumerate(headers, start=1)]
257
+
258
+ selected_indices: list[int] = []
259
+ for part in cleaned.split(","):
260
+ token = part.strip()
261
+ if "-" in token:
262
+ bounds = token.split("-")
263
+ if len(bounds) != 2 or not (bounds[0].isdigit() and bounds[1].isdigit()):
264
+ return None
265
+ start, end = int(bounds[0]), int(bounds[1])
266
+ if not (1 <= start <= end <= len(headers)):
267
+ return None
268
+ selected_indices.extend(range(start, end + 1))
269
+ elif token.isdigit():
270
+ num = int(token)
271
+ if not (1 <= num <= len(headers)):
272
+ return None
273
+ selected_indices.append(num)
274
+ else:
275
+ return None
276
+
277
+ if not selected_indices:
278
+ return None
279
+
280
+ unique_indices = list(dict.fromkeys(selected_indices))
281
+ return [(i, headers[i - 1]) for i in unique_indices]
282
+
283
+
284
+ def select_columns_interactive(headers: list[str]) -> list[tuple[int, str]] | None:
285
+ if not headers:
286
+ raise click.ClickException("ไม่พบหัวคอลัมน์ในชีตนี้")
287
+
288
+ click.secho("\nHeader columns ที่มี:", fg="bright_blue", bold=True)
289
+ for idx, col in enumerate(headers, start=1):
290
+ click.secho(f" {idx}. ", fg="yellow", nl=False)
291
+ if col:
292
+ click.secho(col, fg="white")
293
+ else:
294
+ click.secho("(คอลัมน์ว่าง)", fg="bright_black")
295
+
296
+ click.secho(
297
+ "\nวิธีเลือก: พิมพ์หมายเลข เช่น 1 หรือ 1,3,5 หรือช่วง 1-3 | พิมพ์ all เพื่อเลือกทั้งหมด | พิมพ์ q เพื่อออก",
298
+ fg="magenta",
299
+ )
300
+
301
+ while True:
302
+ raw = click.prompt(
303
+ click.style("เลือกคอลัมน์สำหรับค้นหา (คอลัมน์แรกจะใช้สรุปผลในไฟล์ text)", fg="cyan"),
304
+ type=str,
305
+ ).strip()
306
+ if raw.lower() == "q":
307
+ return None
308
+
309
+ parsed = parse_columns_spec(raw, headers)
310
+ if parsed is not None:
311
+ selected_labels = ", ".join(name or f"Col {i}" for i, name in parsed)
312
+ click.secho(f"คอลัมน์ที่เลือก: {selected_labels}", fg="green")
313
+ return parsed
314
+
315
+ click.secho(f"รูปแบบไม่ถูกต้อง กรุณาใส่หมายเลขระหว่าง 1-{len(headers)}", fg="red")
316
+
317
+
318
+ def select_date_column_interactive(headers: list[str]) -> tuple[int, str] | None:
319
+ """Prompt ให้ผู้ใช้เลือกคอลัมน์ที่เกี่ยวกับวันที่"""
320
+ if not headers:
321
+ return None
322
+
323
+ click.secho("\nเลือกคอลัมน์ที่เกี่ยวกับวันที่:", fg="bright_blue", bold=True)
324
+ for idx, col in enumerate(headers, start=1):
325
+ click.secho(f" {idx}. ", fg="yellow", nl=False)
326
+ if col:
327
+ click.secho(col, fg="white")
328
+ else:
329
+ click.secho("(คอลัมน์ว่าง)", fg="bright_black")
330
+
331
+ click.secho(
332
+ "\nวิธีเลือก: พิมพ์หมายเลขคอลัมน์วันที่ เช่น 2 | พิมพ์ s เพื่อข้าม | พิมพ์ q เพื่อออก",
333
+ fg="magenta",
334
+ )
335
+
336
+ while True:
337
+ raw = click.prompt(
338
+ click.style("เลือกคอลัมน์วันที่", fg="cyan"),
339
+ type=str,
340
+ ).strip()
341
+
342
+ lowered = raw.lower()
343
+ if lowered in {"s", "skip", ""}:
344
+ click.secho("ข้ามการระบุคอลัมน์วันที่", fg="yellow")
345
+ return None
346
+
347
+ if lowered == "q":
348
+ raise click.Abort()
349
+
350
+ if raw.isdigit():
351
+ col_num = int(raw)
352
+ if 1 <= col_num <= len(headers):
353
+ col_label = headers[col_num - 1] or f"คอลัมน์ที่ {col_num}"
354
+ click.secho(f"คอลัมน์วันที่ที่เลือก: {col_label}", fg="green")
355
+ return (col_num, col_label)
356
+
357
+ click.secho(f"ตัวเลือกไม่ถูกต้อง กรุณาใส่หมายเลขระหว่าง 1-{len(headers)} หรือ s", fg="red")
358
+
359
+
360
+ def build_output_path(source_file: Path, output_dir: Path = Path(".")) -> Path:
361
+ output_dir.mkdir(parents=True, exist_ok=True)
362
+ timestamp = datetime.now().strftime("%Y-%m-%d_%H-%M")
363
+ return output_dir / f"{source_file.stem}_filtered_{timestamp}.xlsx"
364
+
365
+
366
+ def detect_url_column_indices(headers: list[str]) -> set[int]:
367
+ return {idx for idx, col in enumerate(headers) if any(hint in col.lower() for hint in URL_COLUMN_HINTS)}
368
+
369
+
370
+ def format_column_label(headers: list[str], col_idx: int) -> str:
371
+ if 0 <= col_idx < len(headers) and headers[col_idx].strip():
372
+ return headers[col_idx].strip()
373
+ return f"คอลัมน์ที่ {col_idx + 1}"
374
+
375
+
376
+ def join_thai_items(items: list[str]) -> str:
377
+ if not items:
378
+ return ""
379
+ if len(items) == 1:
380
+ return items[0]
381
+ return f"{', '.join(items[:-1])} และ {items[-1]}"
382
+
383
+
384
+ def extract_mentions_from_first_column(
385
+ row_values: list[object],
386
+ headers: list[str],
387
+ url_col_indices: set[int],
388
+ primary_col_idx: int,
389
+ ) -> list[tuple[str, str]]:
390
+ """ดึงและนับรายการเฉพาะจากคอลัมน์แรกที่ผู้ใช้เลือก"""
391
+ if primary_col_idx < 0 or primary_col_idx >= len(row_values):
392
+ return []
393
+
394
+ val = row_values[primary_col_idx]
395
+ if val is None:
396
+ return []
397
+
398
+ text = str(val).strip()
399
+ if not text:
400
+ return []
401
+
402
+ col_label = format_column_label(headers, primary_col_idx)
403
+ is_url_col = primary_col_idx in url_col_indices
404
+ mentions: list[tuple[str, str]] = []
405
+
406
+ url_matches = URL_PATTERN.findall(text)
407
+ if url_matches:
408
+ for raw_url in url_matches:
409
+ domain_name = extract_domain_from_url_like(raw_url)
410
+ if domain_name:
411
+ mentions.append((domain_name, col_label))
412
+ if mentions:
413
+ return mentions
414
+
415
+ normalized_item = normalize_target_item(text, is_url_column=is_url_col)
416
+ if normalized_item:
417
+ mentions.append((normalized_item, col_label))
418
+
419
+ return mentions
420
+
421
+
422
+ def format_keywords_display(keywords: list[str]) -> str:
423
+ quoted = [f"'{kw}'" for kw in keywords]
424
+ return join_thai_items(quoted)
425
+
426
+
427
+ def write_summary_text_file(
428
+ excel_output_path: Path,
429
+ keywords: list[str],
430
+ matched_row_count: int,
431
+ item_mentions: list[tuple[str, str]],
432
+ primary_column_name: str,
433
+ date_range_text: str | None = None,
434
+ ) -> Path:
435
+ summary_path = excel_output_path.with_name(f"{excel_output_path.stem}_summary.txt")
436
+
437
+ item_counts: Counter[str] = Counter()
438
+ item_sources: dict[str, list[str]] = defaultdict(list)
439
+ seen_sources: dict[str, set[str]] = defaultdict(set)
440
+
441
+ for item_str, col_label in item_mentions:
442
+ item_counts[item_str] += 1
443
+ if col_label not in seen_sources[item_str]:
444
+ seen_sources[item_str].add(col_label)
445
+ item_sources[item_str].append(col_label)
446
+
447
+ unique_item_total = len(item_counts)
448
+ total_hits = sum(item_counts.values())
449
+ keywords_display = format_keywords_display(keywords)
450
+
451
+ intro_line = f"การตรวจสอบข้อมูลตามวัตถุประสงค์การตรวจพิสูจน์ดำเนินการโดยการค้นหาด้วยชุดคำค้นหา (Keywords) ได้แก่ คำว่า {keywords_display} จากการตรวจสอบ พบข้อมูลที่เกี่ยวข้องจำนวน {unique_item_total:,} รายการ ({total_hits:,} รายการที่พบ)"
452
+ if date_range_text:
453
+ intro_line = f"{intro_line} โดย{date_range_text}"
454
+
455
+ lines = [
456
+ intro_line,
457
+ "รายละเอียดดังนี้:",
458
+ ]
459
+
460
+ if item_counts:
461
+ for idx, (item_name, cnt) in enumerate(item_counts.most_common(), start=1):
462
+ note = ""
463
+ if not is_item_matched_by_keywords(item_name, keywords):
464
+ sources = item_sources.get(item_name, [])
465
+ if sources:
466
+ note = f" (ปรากฏใน {join_thai_items(sources)})"
467
+ lines.append(f"\t{idx}\t{item_name}\tจำนวน {cnt:,} รายการ{note}")
468
+ else:
469
+ lines.append(f"ไม่พบรายการจากคอลัมน์ '{primary_column_name}' ในแถวที่เข้าเงื่อนไข (จำนวนแถวที่พบ {matched_row_count:,} แถว)")
470
+
471
+ summary_path.write_text("\n".join(lines) + "\n", encoding="utf-8")
472
+ return summary_path
473
+
474
+
475
+ def filter_and_export_excel(
476
+ file_path: Path,
477
+ headers: list[str],
478
+ chosen_columns: list[tuple[int, str]],
479
+ keywords: list[str],
480
+ sheet_name: str | int = 0,
481
+ header_row: int = HEADER_ROW,
482
+ chunk_size: int = 50_000,
483
+ output_dir: Path = Path("."),
484
+ collect_summary: bool = False,
485
+ date_col_zero_based: int | None = None,
486
+ ) -> tuple[Path, int, list[tuple[str, str]], datetime | None, datetime | None]:
487
+ needles = [kw.lower() for kw in keywords]
488
+ output_path = build_output_path(file_path, output_dir=output_dir)
489
+
490
+ out_wb = openpyxl.Workbook(write_only=True)
491
+ out_ws = out_wb.create_sheet(title="Filtered")
492
+
493
+ search_zero_based = [col_num - 1 for col_num, _ in chosen_columns]
494
+ primary_col_idx = search_zero_based[0] if search_zero_based else 0
495
+ url_col_indices = detect_url_column_indices(headers) if collect_summary else set()
496
+ export_headers = [col_name if col_name else f"Column_{idx}" for idx, col_name in enumerate(headers, start=1)]
497
+ total_cols = len(export_headers)
498
+ out_ws.append(export_headers)
499
+
500
+ matched_count = 0
501
+ collected_mentions: list[tuple[str, str]] = []
502
+ min_dt: datetime | None = None
503
+ max_dt: datetime | None = None
504
+
505
+ def track_dt(dt_val: datetime | None) -> None:
506
+ nonlocal min_dt, max_dt
507
+ if dt_val is None:
508
+ return
509
+ if min_dt is None or dt_val < min_dt:
510
+ min_dt = dt_val
511
+ if max_dt is None or dt_val > max_dt:
512
+ max_dt = dt_val
513
+
514
+ try:
515
+ if file_path.suffix.lower() in {".xlsx", ".xlsm"}:
516
+ in_wb = open_xlsx_readonly(file_path, data_only=True)
517
+ try:
518
+ in_ws = in_wb[sheet_name] if isinstance(sheet_name, str) else in_wb.worksheets[sheet_name]
519
+ data_rows = in_ws.iter_rows(min_row=header_row + 1, values_only=True)
520
+
521
+ for row in data_rows:
522
+ if not row:
523
+ continue
524
+
525
+ row_len = len(row)
526
+ if date_col_zero_based is not None and date_col_zero_based < row_len:
527
+ track_dt(parse_datetime_value(row[date_col_zero_based]))
528
+
529
+ is_match = False
530
+ for idx in search_zero_based:
531
+ if idx >= row_len:
532
+ continue
533
+ val = row[idx]
534
+ if val is None:
535
+ continue
536
+ text_lower = str(val).lower()
537
+ if any(needle in text_lower for needle in needles):
538
+ is_match = True
539
+ break
540
+
541
+ if is_match:
542
+ full_row = [row[i] if i < row_len else None for i in range(total_cols)]
543
+ out_ws.append(full_row)
544
+ matched_count += 1
545
+
546
+ if collect_summary:
547
+ collected_mentions.extend(
548
+ extract_mentions_from_first_column(
549
+ full_row,
550
+ headers=headers,
551
+ url_col_indices=url_col_indices,
552
+ primary_col_idx=primary_col_idx,
553
+ )
554
+ )
555
+
556
+ if matched_count % chunk_size == 0:
557
+ click.secho(
558
+ f" พบข้อมูลตรงเงื่อนไขแล้ว {matched_count:,} แถว...",
559
+ fg="yellow",
560
+ )
561
+ finally:
562
+ in_wb.close()
563
+ else:
564
+ excel_file = pd.ExcelFile(file_path)
565
+ try:
566
+ df = pd.read_excel(
567
+ excel_file,
568
+ sheet_name=sheet_name,
569
+ header=header_row - 1,
570
+ )
571
+ total_rows = len(df)
572
+ if date_col_zero_based is not None and date_col_zero_based < len(df.columns):
573
+ date_series = pd.to_datetime(df.iloc[:, date_col_zero_based], errors="coerce").dropna()
574
+ if not date_series.empty:
575
+ track_dt(date_series.min().to_pydatetime())
576
+ track_dt(date_series.max().to_pydatetime())
577
+
578
+ search_col_names = [df.columns[idx] for idx in search_zero_based if idx < len(df.columns)]
579
+
580
+ for start in range(0, total_rows, chunk_size):
581
+ chunk = df.iloc[start : start + chunk_size]
582
+ mask = pd.Series(False, index=chunk.index)
583
+
584
+ for col in search_col_names:
585
+ series_str = chunk[col].dropna().astype(str).str.lower()
586
+ for needle in needles:
587
+ matched_idx = series_str[series_str.str.contains(needle, regex=False, na=False)].index
588
+ mask.loc[matched_idx] = True
589
+
590
+ filtered_chunk = chunk[mask]
591
+ for row_vals in filtered_chunk.itertuples(index=False, name=None):
592
+ row_list = list(row_vals)
593
+ out_ws.append(row_list)
594
+ matched_count += 1
595
+
596
+ if collect_summary:
597
+ collected_mentions.extend(
598
+ extract_mentions_from_first_column(
599
+ row_list,
600
+ headers=headers,
601
+ url_col_indices=url_col_indices,
602
+ primary_col_idx=primary_col_idx,
603
+ )
604
+ )
605
+ finally:
606
+ excel_file.close()
607
+
608
+ out_wb.save(output_path)
609
+ finally:
610
+ out_wb.close()
611
+
612
+ return output_path, matched_count, collected_mentions, min_dt, max_dt
613
+
614
+
615
+ @click.command()
616
+ @click.option(
617
+ "-k",
618
+ "--keyword",
619
+ "keywords_raw",
620
+ multiple=True,
621
+ required=True,
622
+ help="คำค้นหา (ระบุหลายคำได้โดยคั่นด้วย , หรือส่ง -k ซ้ำ)",
623
+ )
624
+ @click.option(
625
+ "-s",
626
+ "--summary",
627
+ is_flag=True,
628
+ default=False,
629
+ help="สร้างไฟล์ text สรุปรายการที่พบจากคอลัมน์แรกที่เลือก",
630
+ )
631
+ def main(keywords_raw: tuple[str, ...], summary: bool) -> None:
632
+ output_dir = Path(".")
633
+ keywords = parse_keywords(keywords_raw)
634
+ if not keywords:
635
+ raise click.ClickException(click.style("กรุณาระบุคำค้นหาอย่างน้อย 1 คำ", fg="red"))
636
+
637
+ click.secho("Keywords: ", fg="cyan", nl=False)
638
+ click.secho(", ".join(f"'{kw}'" for kw in keywords), fg="bright_green", bold=True)
639
+
640
+ source_file = select_local_excel_file(output_dir)
641
+ if source_file is None:
642
+ click.secho("ยกเลิกการทำงาน", fg="yellow", bold=True)
643
+ return
644
+
645
+ target_sheet = get_first_sheet(source_file)
646
+ headers = read_excel_headers(source_file, sheet_name=target_sheet, header_row=HEADER_ROW)
647
+
648
+ chosen_columns = select_columns_interactive(headers)
649
+ if chosen_columns is None:
650
+ click.secho("ยกเลิกการทำงาน", fg="yellow", bold=True)
651
+ return
652
+
653
+ chosen_date_col = select_date_column_interactive(headers)
654
+ date_col_zero_based = (chosen_date_col[0] - 1) if chosen_date_col else None
655
+
656
+ click.secho("\nกำลังค้นหาและส่งออกข้อมูลทั้งแถว...", fg="cyan", bold=True)
657
+ output_file, total_matched, collected_mentions, min_dt, max_dt = filter_and_export_excel(
658
+ file_path=source_file,
659
+ headers=headers,
660
+ chosen_columns=chosen_columns,
661
+ keywords=keywords,
662
+ sheet_name=target_sheet,
663
+ header_row=HEADER_ROW,
664
+ output_dir=output_dir,
665
+ collect_summary=summary,
666
+ date_col_zero_based=date_col_zero_based,
667
+ )
668
+
669
+ click.secho("\nเสร็จสิ้น!", fg="green", bold=True)
670
+ click.secho("จำนวนแถวที่พบ: ", fg="white", nl=False)
671
+ click.secho(f"{total_matched:,} แถว", fg="bright_yellow", bold=True)
672
+ click.secho("บันทึกไฟล์ไปที่: ", fg="white", nl=False)
673
+ click.secho(str(output_file.resolve()), fg="bright_cyan")
674
+
675
+ if summary:
676
+ first_col_num, first_col_name = chosen_columns[0]
677
+ primary_col_label = first_col_name or f"คอลัมน์ที่ {first_col_num}"
678
+ date_range_text = format_thai_datetime_range(min_dt, max_dt) if chosen_date_col is not None else None
679
+ summary_file = write_summary_text_file(
680
+ excel_output_path=output_file,
681
+ keywords=keywords,
682
+ matched_row_count=total_matched,
683
+ item_mentions=collected_mentions,
684
+ primary_column_name=primary_col_label,
685
+ date_range_text=date_range_text,
686
+ )
687
+ click.secho("บันทึกไฟล์สรุปไปที่: ", fg="white", nl=False)
688
+ click.secho(str(summary_file.resolve()), fg="bright_magenta")
689
+
690
+
691
+ if __name__ == "__main__":
692
+ main()