Repository navigation
Expand file tree
/
Copy pathmain.py
More file actions
832 lines (726 loc) · 29.9 KB
/
Copy pathmain.py
File metadata and controls
832 lines (726 loc) · 29.9 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
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
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
#!/usr/bin/env python3
"""CLI entrypoint for clickbait-parser (auth, catalog, analysis, dataset, pipeline, ml, gui)."""
from __future__ import annotations
import argparse
import logging
import sys
from dataclasses import asdict
from datetime import datetime
from pathlib import Path
from allchats_sdk.credentials import vk_authorized
from analysis.analyzer import RuleBasedClickbaitAnalyzer
from app.analysis.service import AnalysisService
from app.auth.service import AuthService
from app.catalog.service import CatalogService
from app.composition import create_clickbait_pipeline
from app.dataset.service import DatasetService
from app.ml.service import MLTrainingService
from app.ml.storage import ModelStore
from app.ml.trainer import LABEL_CLICKBAIT, LABEL_NORMAL
from app.pipeline.service import ClickbaitPipeline
from domain.dataset import DatasetLabel
from domain.ml import MLTrainingError
from domain.pipeline import PipelineProgress, PipelineRequest, PipelineState
from infrastructure.credentials.store import FileCredentialStore
from infrastructure.db.database import connect, init_schema
from infrastructure.db.repositories.analysis_repository import AnalysisRepository
from infrastructure.db.repositories.label_repository import LabelRepository
from infrastructure.db.repositories.post_repository import PostRepository
from infrastructure.db.repositories.profile_repository import ProfileRepository
from infrastructure.vk.catalog_client import CatalogAuthError, CatalogError, VKCatalogClient
from infrastructure.vk.client import VKClient
from app.runtime_paths import default_dataset_csv
DEFAULT_DATASET_CSV = default_dataset_csv()
def build_parser() -> argparse.ArgumentParser:
parser = argparse.ArgumentParser(
prog="clickbait-parser",
description="VK clickbait analyzer — auth, catalog, analysis, dataset, pipeline, ml, gui",
)
sub = parser.add_subparsers(dest="command", required=True)
auth = sub.add_parser("auth", help="Authorize a messenger profile")
auth.add_argument("provider", choices=["vk"], help="Messenger provider")
auth.add_argument("--method", default="qr", choices=["qr"], help="Auth method")
auth.add_argument(
"--no-browser",
action="store_true",
help="Do not open the local QR HTML page",
)
sub.add_parser("profiles", help="List saved profiles")
logout = sub.add_parser("logout", help="Remove a saved profile and its credentials")
logout.add_argument("profile_id", type=int, help="Profile id from `profiles`")
catalog = sub.add_parser("catalog", help="Global VK catalog operations")
catalog_sub = catalog.add_subparsers(dest="catalog_command", required=True)
collect = catalog_sub.add_parser("collect", help="Fetch catalog statuses into SQLite")
collect.add_argument("--count", type=int, default=100, help="Max posts to fetch")
collect.add_argument("--pages", type=int, default=10, help="Max catalog pages")
collect.add_argument("--page-size", type=int, default=100, help="Posts per VK page")
collect.add_argument(
"-q",
"--query",
default="",
help="Search query for newsfeed.search",
)
collect.add_argument("--profile-id", type=int, default=None)
collect.add_argument("--start-from", default=None)
posts = sub.add_parser("posts", help="Show latest saved catalog posts")
posts.add_argument("--limit", type=int, default=20)
analysis = sub.add_parser("analysis", help="Rule-based clickbait analysis")
analysis_sub = analysis.add_subparsers(dest="analysis_command", required=True)
run = analysis_sub.add_parser("run", help="Analyze latest saved posts")
run.add_argument("--limit", type=int, default=100)
run.add_argument("--threshold", type=float, default=0.5)
run.add_argument("--post-id", type=int, default=None)
alist = analysis_sub.add_parser("list", help="Show latest analysis results")
alist.add_argument("--limit", type=int, default=20)
aclick = analysis_sub.add_parser("clickbait", help="Show posts marked as clickbait")
aclick.add_argument("--limit", type=int, default=20)
dataset = sub.add_parser("dataset", help="Manual labeling & dataset export")
dataset_sub = dataset.add_subparsers(dest="dataset_command", required=True)
label = dataset_sub.add_parser("label", help="Interactive human labeling")
label.add_argument(
"--mode",
choices=["default", "random", "suspicious"],
default="default",
help="Unlabeled post sampling strategy",
)
label.add_argument(
"--max",
type=int,
default=0,
help="Stop after N labels this session (0 = unlimited)",
)
dataset_sub.add_parser("stats", help="Show labeling / disagreement stats")
export = dataset_sub.add_parser("export", help="Export labeled dataset to CSV")
export.add_argument(
"--output",
type=Path,
default=DEFAULT_DATASET_CSV,
help=f"CSV path (default: {DEFAULT_DATASET_CSV})",
)
dataset_sub.add_parser("validate", help="Soft quality checks before ML")
pipeline = sub.add_parser("pipeline", help="Collect + analyze orchestration")
pipeline_sub = pipeline.add_subparsers(dest="pipeline_command", required=True)
prun = pipeline_sub.add_parser("run", help="Run collect → analyze pipeline")
prun.add_argument("--limit", type=int, required=True, help="Max posts to process")
prun.add_argument(
"-q",
"--query",
default=None,
help="Optional catalog search query",
)
prun.add_argument("--profile-id", type=int, default=None)
prun.add_argument("--threshold", type=float, default=0.5)
prun.add_argument("--page-size", type=int, default=100)
ml = sub.add_parser("ml", help="Train / inspect TF-IDF + LogisticRegression model")
ml_sub = ml.add_subparsers(dest="ml_command", required=True)
ml_sub.add_parser("train", help="Train model from human CLICKBAIT/NORMAL labels")
ml_sub.add_parser("info", help="Show current model version and metrics")
gui = sub.add_parser("gui", help="Open PyQt6 desktop MVP")
gui.add_argument("--profile-id", type=int, default=None)
gui.add_argument("--threshold", type=float, default=0.5)
gui.add_argument("--page-size", type=int, default=100)
return parser
def _format_profile(profile) -> str:
name = " ".join(part for part in (profile.first_name, profile.last_name) if part).strip()
name = name or "(no name)"
return (
f"id={profile.id} provider={profile.provider} "
f"user_id={profile.provider_user_id} name={name}"
)
def _truncate(text: str, limit: int = 160) -> str:
text = " ".join((text or "").split())
if len(text) <= limit:
return text
return text[: limit - 1] + "…"
def _format_post(post) -> str:
when = post.date.astimezone().strftime("%Y-%m-%d %H:%M") if isinstance(post.date, datetime) else "?"
label = "VK" if post.source.startswith("vk") else post.source.upper()
body = _truncate(post.text) or "(no text)"
return (
f"[{label}] owner={post.owner_id} post={post.post_id}\n"
f"{when}\n"
f"{body}\n"
f"Links: {len(post.links)}"
)
def _format_analysis(post, analysis) -> str:
label = "CLICKBAIT" if analysis.is_clickbait else "NORMAL"
reasons = ", ".join(analysis.reasons) if analysis.reasons else "(none)"
return (
f"{analysis.score:0.2f} {label:<9} owner={post.owner_id} post={post.post_id}\n"
f"Причины: {reasons}"
)
def _format_pipeline_analysis(post, analysis) -> str:
label = "CLICKBAIT" if analysis.is_clickbait else "NORMAL"
reasons = ", ".join(analysis.reasons) if analysis.reasons else "(none)"
return (
f"{analysis.score:0.2f} {label}\n"
f"owner={post.owner_id} post={post.post_id}\n"
f"Причины: {reasons}"
)
class _PipelineCliProgress:
"""Prints pipeline progress without coupling application layer to CLI."""
def __init__(self) -> None:
self._last_state: PipelineState | None = None
def __call__(self, progress: PipelineProgress) -> None:
if progress.state == PipelineState.COLLECTING:
if self._last_state != PipelineState.COLLECTING:
print(f"State: {progress.state.value}")
if progress.current > 0 or progress.total == 0:
print(f"Collected: {progress.current}", flush=True)
self._last_state = progress.state
return
if progress.state == PipelineState.ANALYZING:
if self._last_state != PipelineState.ANALYZING:
print()
print(f"State: {progress.state.value}")
if progress.total >= 0 and progress.current > 0:
print(f"Analyzed: {progress.current}/{progress.total}", flush=True)
self._last_state = progress.state
return
if progress.state == PipelineState.COMPLETED:
print()
print(f"State: {progress.state.value}")
self._last_state = progress.state
return
if progress.state == PipelineState.FAILED:
print()
print(f"State: {progress.state.value}", file=sys.stderr)
self._last_state = progress.state
def _print_label_card(post, analysis) -> None:
when = post.date.astimezone().strftime("%Y-%m-%d %H:%M:%S") if isinstance(post.date, datetime) else "?"
print("=" * 40)
print(f"POST #{post.id}")
print("=" * 40)
print()
print(f"Owner: {post.owner_id}")
print(f"Date: {when}")
print()
print("Text:")
print("-" * 40)
print(post.text or "(empty)")
print("-" * 40)
print()
print("Rule-based prediction:")
if analysis is None:
print("score: (no analysis yet — run `analysis run`)")
print("is_clickbait: ?")
print()
print("Reasons:")
print("- (none)")
print()
print("Features:")
print("- (none)")
else:
print(f"score: {analysis.score:0.2f}")
print(f"is_clickbait: {'YES' if analysis.is_clickbait else 'NO'}")
print()
print("Reasons:")
if analysis.reasons:
for reason in analysis.reasons:
print(f"- {reason}")
else:
print("- (none)")
print()
print("Features:")
for key, value in asdict(analysis.features).items():
print(f"- {key}: {str(value).lower()}")
print()
print("Label:")
print()
print("[c] clickbait")
print("[n] normal")
print("[b] borderline")
print("[s] skip")
print("[q] quit")
def _open_db():
conn = connect()
init_schema(conn)
return conn
def _build_auth_service(
*,
open_browser: bool = True,
on_status=None,
on_qr=None,
) -> AuthService:
conn = _open_db()
status_cb = on_status if on_status is not None else (lambda msg: print(msg, flush=True))
return AuthService(
vk_client=VKClient(
open_browser=open_browser,
on_status=status_cb,
on_qr=on_qr,
),
profiles=ProfileRepository(conn),
credentials=FileCredentialStore(),
)
def _build_analysis_service(*, threshold: float = 0.5) -> AnalysisService:
conn = _open_db()
return AnalysisService(
posts=PostRepository(conn),
analyses=AnalysisRepository(conn),
analyzer=RuleBasedClickbaitAnalyzer(threshold=threshold),
)
def _build_dataset_service() -> DatasetService:
conn = _open_db()
return DatasetService(
posts=PostRepository(conn),
labels=LabelRepository(conn),
analyses=AnalysisRepository(conn),
)
def _build_ml_service(*, store: ModelStore | None = None) -> MLTrainingService:
conn = _open_db()
return MLTrainingService(
posts=PostRepository(conn),
labels=LabelRepository(conn),
store=store or ModelStore(),
)
def _pct(value: float) -> str:
return f"{value * 100:0.2f}%"
def _print_ml_info(service: MLTrainingService) -> int:
info = service.get_model_info()
if info is None:
print("Model is not trained yet.")
return 0
m = info.metrics
when = info.trained_at.astimezone()
print("Model: Clickbait TF-IDF + Logistic Regression")
print(f"Version: v{info.version}")
print()
print(f"Trained: {when.day} {when.strftime('%b %Y %H:%M')}")
print()
print(f"Training samples: {m.train_samples}")
print(f"Test samples: {m.test_samples}")
print()
print(f"Accuracy: {_pct(m.accuracy)}")
print(f"Precision: {_pct(m.precision)}")
print(f"Recall: {_pct(m.recall)}")
print(f"F1: {_pct(m.f1)}")
return 0
def _run_ml_train(service: MLTrainingService) -> int:
print("Training model...")
print()
try:
texts, y = service.load_training_pairs()
n_clickbait = sum(1 for v in y if v == LABEL_CLICKBAIT)
n_normal = sum(1 for v in y if v == LABEL_NORMAL)
print("Dataset:")
print(f" Clickbait: {n_clickbait}")
print(f" Normal: {n_normal}")
print()
result = service.train()
except MLTrainingError as exc:
print(str(exc), file=sys.stderr)
return 1
except Exception as exc:
print(f"ml train failed: {exc}", file=sys.stderr)
return 1
m = result.info.metrics
print(f"Train: {m.train_samples}")
print(f"Test: {m.test_samples}")
print()
print("Model trained successfully.")
print()
print(f"Version: v{result.info.version}")
print()
print(f"Accuracy: {_pct(m.accuracy)}")
print(f"Precision: {_pct(m.precision)}")
print(f"Recall: {_pct(m.recall)}")
print(f"F1: {_pct(m.f1)}")
return 0
def _resolve_vk_token(*, profile_id: int | None) -> tuple[int, str]:
conn = _open_db()
profiles = ProfileRepository(conn)
creds_store = FileCredentialStore()
if profile_id is not None:
profile = profiles.get(profile_id)
if profile is None:
raise CatalogAuthError(f"profile {profile_id} not found")
if profile.provider != "vk":
raise CatalogAuthError(f"profile {profile_id} is not a vk profile")
else:
vk_profiles = [p for p in profiles.get_all() if p.provider == "vk"]
if not vk_profiles:
raise CatalogAuthError("no vk profiles — run: python main.py auth vk --method qr")
profile = vk_profiles[0]
assert profile.id is not None
credentials = creds_store.load(profile.provider, profile.provider_user_id)
if not credentials or not vk_authorized(credentials):
raise CatalogAuthError(
f"vk credentials missing for profile {profile.id} — re-run auth"
)
token = str(credentials.get("access_token") or "").strip()
if not token:
raise CatalogAuthError("vk access_token is empty — re-run auth")
assert profile.id is not None
return profile.id, token
def _run_labeling_session(*, mode: str, max_labels: int) -> int:
service = _build_dataset_service()
labeled_now = 0
skipped: set[int] = set()
while True:
if max_labels > 0 and labeled_now >= max_labels:
print(f"Reached --max={max_labels}")
return 0
post = None
for attempt in range(80):
sample_mode = mode
if attempt > 0 and mode == "default":
sample_mode = "random"
candidate = service.get_next_unlabeled_post(mode=sample_mode) # type: ignore[arg-type]
if candidate is None or candidate.id is None:
break
if candidate.id in skipped:
continue
post = candidate
break
if post is None or post.id is None:
print("(no unlabeled posts left)")
return 0
_, analysis, _existing = service.get_label_context(post)
_print_label_card(post, analysis)
while True:
choice = input("> ").strip().lower()
if choice in {"q", "quit"}:
return 0
if choice in {"s", "skip"}:
skipped.add(post.id)
print("skipped")
break
mapping = {
"c": DatasetLabel.CLICKBAIT,
"clickbait": DatasetLabel.CLICKBAIT,
"n": DatasetLabel.NORMAL,
"normal": DatasetLabel.NORMAL,
"b": DatasetLabel.BORDERLINE,
"borderline": DatasetLabel.BORDERLINE,
}
if choice in mapping:
saved = service.label_post(post.id, mapping[choice])
print(f"saved label={saved.label.value} post_id={saved.post_id}")
labeled_now += 1
break
print("use: c / n / b / s / q")
return 0
def _run_gui(*, profile_id: int | None, threshold: float, page_size: int) -> int:
from PyQt6.QtWidgets import QApplication, QDialog
from app.gui.controller import PipelineController
from app.gui.ml_controller import MLTrainController
from ui.main_window import MainWindow
from ui.profile_dialog import ProfileSelectDialog, format_profile_label
from ui.theme import apply_theme
app = QApplication(sys.argv)
apply_theme(app)
# AuthService for list/delete on the GUI thread (own SQLite connection).
auth_service = _build_auth_service(open_browser=False)
def auth_factory(*, on_status=None, on_qr=None):
# Fresh AuthService/SQLite on the auth worker thread; QR stays in-app.
return _build_auth_service(
open_browser=False,
on_status=on_status,
on_qr=on_qr,
)
dialog = ProfileSelectDialog(
profiles=auth_service,
auth_factory=auth_factory,
initial_profile_id=profile_id,
)
if dialog.exec() != QDialog.DialogCode.Accepted:
return 0
selected_id = dialog.selected_profile_id
if selected_id is None:
print("no profile selected", file=sys.stderr)
return 1
try:
resolved_id, token = _resolve_vk_token(profile_id=selected_id)
except CatalogAuthError as exc:
print(f"auth error: {exc}", file=sys.stderr)
return 1
profile = auth_service.get_profile(resolved_id)
title_suffix = format_profile_label(profile) if profile is not None else f"#{resolved_id}"
model_store = ModelStore()
def pipeline_factory():
# Must run on the worker thread so SQLite is not shared with the GUI thread.
return create_clickbait_pipeline(
access_token=token,
threshold=threshold,
page_size=page_size,
model_store=model_store,
)
def ml_factory():
# Fresh SQLite on the ML worker thread.
return _build_ml_service(store=model_store)
window = MainWindow()
window.setWindowTitle(f"clickbait-parser — {title_suffix}")
window.set_dataset_service(_build_dataset_service())
window.set_ml_service(_build_ml_service(store=model_store))
window.set_controller(
PipelineController(window=window, pipeline_factory=pipeline_factory)
)
window.set_ml_controller(
MLTrainController(window=window, train_factory=ml_factory)
)
window.show()
from app.gui.update_controller import maybe_start_update_check
from app.release_info import UPDATE_REPO_URL
maybe_start_update_check(window, repo_url=UPDATE_REPO_URL)
return int(app.exec())
def main(argv: list[str] | None = None) -> int:
logging.basicConfig(level=logging.INFO, format="%(levelname)s %(name)s: %(message)s")
logging.getLogger("allchats_sdk").setLevel(logging.WARNING)
parser = build_parser()
args = parser.parse_args(argv)
if args.command == "auth":
service = _build_auth_service(open_browser=not args.no_browser)
try:
profile = service.login_vk(method=args.method)
except Exception as exc:
print(f"auth failed: {exc}", file=sys.stderr)
return 1
print(_format_profile(profile))
return 0
if args.command == "profiles":
service = _build_auth_service()
profiles = service.get_profiles()
if not profiles:
print("(no profiles)")
return 0
for profile in profiles:
print(_format_profile(profile))
return 0
if args.command == "logout":
service = _build_auth_service()
profile = service.get_profile(args.profile_id)
if profile is None:
print(f"profile {args.profile_id} not found", file=sys.stderr)
return 1
service.logout(args.profile_id)
print(f"logged out profile {args.profile_id}")
return 0
if args.command == "catalog":
if args.catalog_command == "collect":
try:
profile_id, token = _resolve_vk_token(profile_id=args.profile_id)
conn = _open_db()
service = CatalogService(
client=VKCatalogClient(access_token=token),
posts=PostRepository(conn),
)
result = service.collect(
count=args.count,
start_from=args.start_from,
pages=args.pages,
page_size=args.page_size,
query=args.query,
)
except CatalogAuthError as exc:
print(f"auth error: {exc}", file=sys.stderr)
return 1
except CatalogError as exc:
print(f"catalog error: {exc}", file=sys.stderr)
return 1
print("VK Global Catalog")
print(f"Profile: {profile_id}")
print(f"Method: newsfeed.search")
if args.query:
print(f"Query: {args.query}")
print(f"Fetched: {result.fetched}")
print(f"Inserted: {result.upsert.inserted}")
print(f"Updated: {result.upsert.updated}")
print(f"Unchanged: {result.upsert.unchanged}")
print(f"Pages: {result.pages}")
if result.next_from:
print(f"next_from: {result.next_from}")
return 0
parser.error(f"unknown catalog command: {args.catalog_command}")
return 2
if args.command == "posts":
conn = _open_db()
latest = PostRepository(conn).get_latest(limit=args.limit)
if not latest:
print("(no posts)")
return 0
for index, post in enumerate(latest):
if index:
print()
print(_format_post(post))
return 0
if args.command == "analysis":
if args.analysis_command == "run":
threshold = float(args.threshold)
if not 0.0 <= threshold <= 1.0:
parser.error("--threshold must be between 0 and 1")
service = _build_analysis_service(threshold=threshold)
try:
if args.post_id is not None:
analysis = service.analyze_post(args.post_id)
conn = _open_db()
post = PostRepository(conn).get_by_id(args.post_id)
if post is None:
print(f"post {args.post_id} not found", file=sys.stderr)
return 1
print(_format_analysis(post, analysis))
return 0
result = service.analyze_posts(limit=args.limit)
except ValueError as exc:
print(f"analysis error: {exc}", file=sys.stderr)
return 1
print("Clickbait Analysis")
print(f"Analyzed: {result.analyzed}")
print(f"Clickbait: {result.clickbait}")
print(f"Normal: {result.normal}")
print(f"Skipped: {result.skipped}")
print(f"Threshold: {threshold}")
return 0
if args.analysis_command == "list":
service = _build_analysis_service()
rows = service.list_latest(limit=args.limit)
if not rows:
print("(no analysis results)")
return 0
for index, (post, analysis) in enumerate(rows):
if index:
print()
print(_format_analysis(post, analysis))
return 0
if args.analysis_command == "clickbait":
service = _build_analysis_service()
rows = service.list_clickbait(limit=args.limit)
if not rows:
print("(no clickbait posts)")
return 0
for index, (post, analysis) in enumerate(rows):
if index:
print()
print(_format_analysis(post, analysis))
return 0
parser.error(f"unknown analysis command: {args.analysis_command}")
return 2
if args.command == "dataset":
if args.dataset_command == "label":
return _run_labeling_session(mode=args.mode, max_labels=args.max)
if args.dataset_command == "stats":
stats = _build_dataset_service().get_dataset_stats()
print("Dataset statistics")
print("------------------")
print()
print(f"Total labeled: {stats.total_labeled}")
print()
print(f"CLICKBAIT: {stats.by_label[DatasetLabel.CLICKBAIT]}")
print(f"NORMAL: {stats.by_label[DatasetLabel.NORMAL]}")
print(f"BORDERLINE: {stats.by_label[DatasetLabel.BORDERLINE]}")
print()
print(f"Unlabeled: {stats.unlabeled}")
print()
print("Rule prediction:")
print(f"CLICKBAIT: {stats.rule_clickbait}")
print(f"NORMAL: {stats.rule_normal}")
print()
print("Human vs Rule disagreement:")
print()
print(
f"Human CLICKBAIT + Rule NORMAL: "
f"{stats.disagreement_human_clickbait_rule_normal}"
)
print(
f"Human NORMAL + Rule CLICKBAIT: "
f"{stats.disagreement_human_normal_rule_clickbait}"
)
return 0
if args.dataset_command == "export":
path = _build_dataset_service().export_csv(args.output)
print(f"exported: {path}")
return 0
if args.dataset_command == "validate":
result = _build_dataset_service().validate()
print("Dataset validation")
print("------------------")
print()
print(f"Total labeled: {result.total_labeled}")
print()
print(f"CLICKBAIT: {result.by_label[DatasetLabel.CLICKBAIT]}")
print(f"NORMAL: {result.by_label[DatasetLabel.NORMAL]}")
print(f"BORDERLINE: {result.by_label[DatasetLabel.BORDERLINE]}")
print()
if result.warnings:
for warning in result.warnings:
print(f"WARNING:\n{warning}")
print()
else:
print("OK: no soft warnings.")
return 0
parser.error(f"unknown dataset command: {args.dataset_command}")
return 2
if args.command == "pipeline":
if args.pipeline_command == "run":
threshold = float(args.threshold)
if not 0.0 <= threshold <= 1.0:
parser.error("--threshold must be between 0 and 1")
if args.limit <= 0:
parser.error("--limit must be > 0")
print("Pipeline")
print("────────")
print()
progress = _PipelineCliProgress()
try:
profile_id, token = _resolve_vk_token(profile_id=args.profile_id)
conn = _open_db()
catalog = CatalogService(
client=VKCatalogClient(access_token=token),
posts=PostRepository(conn),
)
pipeline = ClickbaitPipeline(
catalog_service=catalog,
analyzer=RuleBasedClickbaitAnalyzer(threshold=threshold),
analysis_repository=AnalysisRepository(conn),
on_progress=progress,
page_size=args.page_size,
)
request = PipelineRequest(limit=args.limit, query=args.query)
result = pipeline.run(request)
except CatalogAuthError as exc:
print(f"auth error: {exc}", file=sys.stderr)
return 1
except CatalogError as exc:
print(f"catalog error: {exc}", file=sys.stderr)
return 1
except ValueError as exc:
print(f"pipeline error: {exc}", file=sys.stderr)
return 1
except Exception as exc:
print(f"pipeline failed: {exc}", file=sys.stderr)
return 1
print()
print("Results:")
print("────────────────────────────────────────")
print()
if not result.posts:
print("(no posts)")
else:
for index, item in enumerate(result.posts):
if index:
print()
print(_format_pipeline_analysis(item.post, item.analysis))
return 0
parser.error(f"unknown pipeline command: {args.pipeline_command}")
return 2
if args.command == "ml":
service = _build_ml_service()
if args.ml_command == "train":
return _run_ml_train(service)
if args.ml_command == "info":
return _print_ml_info(service)
parser.error(f"unknown ml command: {args.ml_command}")
return 2
if args.command == "gui":
threshold = float(args.threshold)
if not 0.0 <= threshold <= 1.0:
parser.error("--threshold must be between 0 and 1")
return _run_gui(
profile_id=args.profile_id,
threshold=threshold,
page_size=args.page_size,
)
parser.error(f"unknown command: {args.command}")
return 2
if __name__ == "__main__":
raise SystemExit(main())