-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMetaDetect.py
More file actions
2187 lines (1966 loc) · 83.2 KB
/
MetaDetect.py
File metadata and controls
2187 lines (1966 loc) · 83.2 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
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
import re
import json
import os
import sys
import subprocess
import nltk
import warnings
import csv
from datetime import datetime
from collections import defaultdict, Counter
from typing import List, Dict, Any, Tuple, Optional
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.cluster import KMeans, DBSCAN
from sklearn.preprocessing import StandardScaler
from sklearn.decomposition import PCA
import networkx as nx
import torch
import torch.nn as nn
from nltk.sentiment.vader import SentimentIntensityAnalyzer
from nltk.tokenize import word_tokenize
from flask import (
Flask,
request,
render_template_string,
send_from_directory,
url_for,
jsonify,
)
from werkzeug.utils import secure_filename
# Import Plotly for interactive visualizations
import plotly.graph_objects as go
import plotly.express as px
from plotly.subplots import make_subplots
import plotly.io as pio
warnings.filterwarnings("ignore")
# NLTK setup
try:
nltk.data.find("sentiment/vader_lexicon")
except LookupError:
print("First-time setup: Downloading NLTK VADER lexicon...")
nltk.download("vader_lexicon", quiet=True)
try:
nltk.data.find("tokenizers/punkt")
except LookupError:
print("First-time setup: Downloading NLTK punkt tokenizer...")
nltk.download("punkt", quiet=True)
DEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu")
print(f"🔧 Using device: {DEVICE}")
# -------------------------------------------------------------------
# Helper: open file
# -------------------------------------------------------------------
def open_file(path: str):
"""Open a file with the default OS application."""
if not os.path.exists(path):
print(f"⚠️ File not found: {path}")
return
try:
if os.name == "nt": # Windows
os.startfile(path)
elif sys.platform == "darwin": # macOS
subprocess.Popen(["open", path])
else: # Linux
subprocess.Popen(["xdg-open", path])
except Exception as e:
print(f"⚠️ Could not open file {path}: {e}")
# -------------------------------------------------------------------
# BERT Feature Extractor
# -------------------------------------------------------------------
class BERTFeatureExtractor:
def __init__(self):
self.available = False
self.tokenizer = None
self.model = None
self._try_load_bert()
def _try_load_bert(self):
try:
print("🤖 Loading BERT model...", end=" ")
from transformers import BertTokenizer, BertModel
self.tokenizer = BertTokenizer.from_pretrained(
"bert-base-uncased", local_files_only=False
)
self.model = (
BertModel.from_pretrained(
"bert-base-uncased", local_files_only=False
).to(DEVICE)
)
self.model.eval()
self.available = True
print("✓ BERT loaded successfully")
except Exception:
print("⚠️ BERT unavailable (using fallback features)")
self.available = False
def extract_features(self, text: str) -> np.ndarray:
if not self.available:
return np.zeros(768)
try:
inputs = self.tokenizer(
text[:512],
return_tensors="pt",
truncation=True,
max_length=512,
padding=True,
).to(DEVICE)
with torch.no_grad():
outputs = self.model(**inputs)
embeddings = outputs.last_hidden_state[:, 0, :].cpu().numpy()
return embeddings.flatten()
except Exception:
return np.zeros(768)
# -------------------------------------------------------------------
# LSTM model wrapper
# -------------------------------------------------------------------
class LSTMRiskPredictor(nn.Module):
def __init__(self, input_size=10, hidden_size=64, num_layers=2, dropout=0.3):
super(LSTMRiskPredictor, self).__init__()
self.hidden_size = hidden_size
self.num_layers = num_layers
self.lstm = nn.LSTM(
input_size,
hidden_size,
num_layers,
batch_first=True,
dropout=dropout if num_layers > 1 else 0,
)
self.fc = nn.Linear(hidden_size, 1)
self.sigmoid = nn.Sigmoid()
def forward(self, x):
h0 = torch.zeros(self.num_layers, x.size(0), self.hidden_size).to(x.device)
c0 = torch.zeros(self.num_layers, x.size(0), self.hidden_size).to(x.device)
out, _ = self.lstm(x, (h0, c0))
out = self.fc(out[:, -1, :])
return self.sigmoid(out)
# -------------------------------------------------------------------
# Core META DETECT Engine
# -------------------------------------------------------------------
class MetaDetect:
def __init__(self):
print("\n🚀 Initializing META DETECT...")
self.analyzer = SentimentIntensityAnalyzer()
self.bert_extractor = BERTFeatureExtractor()
self.use_bert = self.bert_extractor.available
self.drug_keywords = {
"high_risk": [
"cocaine",
"heroin",
"meth",
"mdma",
"ecstasy",
"lsd",
"fentanyl",
"oxy",
"xanax",
"molly",
"crack",
"crystal",
"smack",
"blow",
"speed",
"amphetamine",
"morphine",
"opium",
"codeine",
"tramadol",
"hydrocodone",
],
"medium_risk": [
"weed",
"hash",
"kush",
"joint",
"blunt",
"stash",
"dealer",
"pickup",
],
"contextual_slang": [
"stuff",
"product",
"package",
"delivery",
"drop",
"meet",
"cash",
"party",
"supply",
"client",
"batch",
"order",
],
}
self.excluded_keywords = {
"pot",
"bud",
"dope",
"ice",
"gram",
"ounce",
"oz",
"eighth",
"quarter",
"half",
"plug",
"connect",
"score",
"deal",
}
self.innocent_patterns = [
r"\b(product|package|delivery|order|client|supply)\s+(development|management|tracking|service|support|team|meeting)\b",
r"\b(amazon|ebay|flipkart|shop|store|business|company|work|office|courier|fedex|ups|dhl)\b",
r"\b(delivery|package)\s+(arrived|coming|expected|received|sent|delayed|tracking)\b",
r"\border\s+(online|number|status|confirmation)\b",
r"\b(birthday|wedding|celebration|dinner|lunch|event|surprise)\s+party\b",
r"\bparty\s+(planning|invitation|tonight|tomorrow|last\s+night|yesterday|hat|dress|theme|venue)\b",
r"\b(house|dinner|lunch|pool|garden|tea)\s+party\b",
r"\b(cash|money)\s+(back|app|payment|transfer|withdraw|deposit|atm|machine)\b",
r"\bpay\s+(cash|money|by\s+cash)\b",
r"\b(have|need|get|give|owe)\s+(cash|money)\s+(for|to\s+pay|from|back)\b",
r"\b(cashback|cashless|petty\s+cash)\b",
r"\bmeet(ing)?\s+(at|for|with|tomorrow|today|later|scheduled|zoom|teams|client)\b",
r"\b(coffee|lunch|dinner|breakfast|video)\s+meet(ing)?\b",
r"\b(team|staff|board|project)\s+meet(ing)?\b",
r"\b(nice|great|pleased)\s+to\s+meet\b",
]
self.suspicious_patterns = [
r"\b(sell|selling|sold)\s+(weed|hash|kush)\b",
r"\b(buy|buying|bought)\s+(weed|hash|kush)\b",
r"\b(good|bad|pure|quality|premium|fresh)\s+(weed|hash|kush)\b",
r"\bhow\s+much\s+(for|per)\s+(it|them|that)\b",
r"\b(need|got|have)\s+(some|the)?\s*(good)?\s*(weed|hash|kush)\b",
r"\bmeet\s+(secretly|privately|quietly|discreetly)\b",
r"\b(dealer|supplier)\b",
r"\bhit\s+me\s+up\b",
r"\blink\s+up\b",
]
self.risk_weights = {
"high_risk": 10,
"medium_risk": 5,
"contextual_slang": 3,
}
self.all_direct_drug_terms = set(
self.drug_keywords["high_risk"] + self.drug_keywords["medium_risk"]
) - self.excluded_keywords
self.interaction_graph = nx.DiGraph()
print("✓ META DETECT initialized successfully\n")
def _is_innocent_context(self, message: str) -> bool:
message_lower = message.lower()
for pattern in self.innocent_patterns:
if re.search(pattern, message_lower):
return True
return False
def _has_suspicious_context(self, message: str) -> bool:
message_lower = message.lower()
for pattern in self.suspicious_patterns:
if re.search(pattern, message_lower):
return True
return False
def _calculate_context_risk(
self,
message: str,
keyword: str,
category: str,
sentiment_compound: float,
) -> Tuple[bool, str]:
message_lower = message.lower()
if category in ["high_risk", "medium_risk"]:
return True, f"Direct drug term: '{keyword}'"
if category == "contextual_slang":
if self._is_innocent_context(message):
return False, "Innocent context detected"
if self._has_suspicious_context(message):
return True, f"Suspicious context with slang: '{keyword}'"
if sentiment_compound <= -0.5:
return True, f"Negative sentiment ({sentiment_compound:.2f}) with slang"
return False, "Contextual slang without suspicious indicators"
def test_detection_accuracy(self) -> float:
print("🧪 Running automated detection accuracy tests...")
test_cases = [
("I'm learning to program in Python", False, "gram"),
("Check out my Instagram profile", False, "gram"),
("Need 500 grams of rice for dinner", False, "gram"),
("My package delivery is coming tomorrow", False, "package"),
("Birthday party tonight!", False, "party"),
("Selling weed, good quality", True, "weed"),
("Got cocaine available", True, "cocaine"),
]
correct = 0
total = len(test_cases)
for message, should_detect, keyword in test_cases:
sentiment = self.analyzer.polarity_scores(message)
if keyword in self.excluded_keywords:
detected = False
else:
word_pattern = r"\b" + re.escape(keyword) + r"\b"
keyword_found = bool(re.search(word_pattern, message.lower()))
if not keyword_found:
detected = False
else:
category = None
for cat, keywords in self.drug_keywords.items():
if keyword in keywords:
category = cat
break
if category:
detected, _ = self._calculate_context_risk(
message, keyword, category, sentiment["compound"]
)
else:
detected = False
if detected == should_detect:
correct += 1
accuracy = (correct / total) * 100
print(f"✓ Detection accuracy: {correct}/{total} ({accuracy:.1f}%)\n")
return accuracy
def parse_whatsapp_chat(self, filepath: str) -> List[Dict[str, str]]:
messages: List[Dict[str, str]] = []
pattern = re.compile(
r"(\d{1,2}/\d{1,2}/\d{2,4}),?\s*(\d{1,2}:\d{2}(?:\s*(?:AM|PM))?)\s*-\s*([^:]+):\s*(.+)",
re.IGNORECASE,
)
try:
with open(filepath, "r", encoding="utf-8", errors="ignore") as f:
for line in f:
match = pattern.match(line.strip())
if match:
messages.append(
{
"date": match.group(1).strip(),
"time": match.group(2).strip(),
"user": match.group(3).strip(),
"message": match.group(4).strip(),
}
)
except Exception as e:
print(f"⚠️ Error reading file: {str(e)[:100]}")
return messages
def parse_telegram_chat(self, filepath: str) -> List[Dict[str, str]]:
messages: List[Dict[str, str]] = []
pattern = re.compile(
r"\[(\d{1,2}\.\d{1,2}\.\d{2,4})\s+(\d{1,2}:\d{2}:\d{2})\]\s+([^:]+):\s*(.+)"
)
try:
with open(filepath, "r", encoding="utf-8", errors="ignore") as f:
for line in f:
match = pattern.match(line.strip())
if match:
messages.append(
{
"date": match.group(1).strip(),
"time": match.group(2).strip(),
"user": match.group(3).strip(),
"message": match.group(4).strip(),
}
)
except Exception as e:
print(f"⚠️ Error reading file: {str(e)[:100]}")
return messages
def build_interaction_network(self, messages: List[Dict[str, str]]):
print("🕸️ Building interaction network...")
self.interaction_graph.clear()
if len(messages) < 2:
print("⚠️ Insufficient messages for network analysis.")
return
for i in range(len(messages) - 1):
try:
user1 = messages[i]["user"].strip()
user2 = messages[i + 1]["user"].strip()
if user1 and user2 and user1 != user2:
if self.interaction_graph.has_edge(user1, user2):
self.interaction_graph[user1][user2]["weight"] += 1
else:
self.interaction_graph.add_edge(user1, user2, weight=1)
except Exception:
continue
print(
f"✓ Network built: {self.interaction_graph.number_of_nodes()} nodes, "
f"{self.interaction_graph.number_of_edges()} edges"
)
def analyze_network_centrality(self) -> Dict[str, Dict[str, float]]:
centrality_metrics: Dict[str, Dict[str, float]] = {}
if self.interaction_graph.number_of_nodes() == 0:
return centrality_metrics
try:
degree_cent = nx.degree_centrality(self.interaction_graph)
betweenness_cent = nx.betweenness_centrality(self.interaction_graph)
try:
pagerank = nx.pagerank(self.interaction_graph)
except Exception:
pagerank = {node: 0 for node in self.interaction_graph.nodes()}
for user in self.interaction_graph.nodes():
centrality_metrics[user] = {
"degree_centrality": float(degree_cent.get(user, 0)),
"betweenness_centrality": float(betweenness_cent.get(user, 0)),
"pagerank": float(pagerank.get(user, 0)),
}
except Exception as e:
print(f"⚠️ Error calculating centrality: {str(e)[:100]}")
return centrality_metrics
def analyze_messages(self, messages: List[Dict[str, str]]) -> Dict[str, Any]:
user_stats: Dict[str, Any] = defaultdict(
lambda: {
"message_count": 0,
"keyword_count": 0,
"high_risk_keywords": 0,
"medium_risk_keywords": 0,
"contextual_slang_keywords": 0,
"false_positives_avoided": 0,
"suspicion_score": 0,
"total_length": 0,
"sentiment_scores": [],
"negative_message_count": 0,
"message_times": [],
"messages_text": [],
"suspicious_words": [],
"suspicious_word_frequency": Counter(),
"innocent_detections": [],
"bert_embeddings": [],
}
)
print("🔍 Analyzing messages with context-aware detection...")
for idx, msg in enumerate(messages):
if idx % max(1, len(messages) // 10) == 0 and idx > 0:
print(f" Processing message {idx}/{len(messages)}...", end="\r")
try:
user = msg.get("user", "Unknown").strip()
message = msg.get("message", "").strip()
if not user or not message:
continue
user_stats[user]["message_count"] += 1
user_stats[user]["total_length"] += len(message)
user_stats[user]["message_times"].append(msg.get("time", ""))
user_stats[user]["messages_text"].append(message)
sentiment = self.analyzer.polarity_scores(message)
user_stats[user]["sentiment_scores"].append(sentiment["compound"])
if sentiment["compound"] <= -0.4:
user_stats[user]["negative_message_count"] += 1
if self.use_bert and idx % 5 == 0:
bert_features = self.bert_extractor.extract_features(message)
user_stats[user]["bert_embeddings"].append(bert_features)
message_lower = message.lower()
for category, keywords in self.drug_keywords.items():
for keyword in keywords:
if keyword in self.excluded_keywords:
continue
word_pattern = r"\b" + re.escape(keyword) + r"\b"
if re.search(word_pattern, message_lower):
is_suspicious, reason = self._calculate_context_risk(
message,
keyword,
category,
sentiment["compound"],
)
if is_suspicious:
user_stats[user]["keyword_count"] += 1
user_stats[user][f"{category}_keywords"] += 1
user_stats[user]["suspicion_score"] += self.risk_weights[
category
]
user_stats[user]["suspicious_words"].append(
{
"word": keyword,
"category": category,
"message_context": message[:150],
"timestamp": msg.get("time", "Unknown"),
"reason": reason,
}
)
user_stats[user]["suspicious_word_frequency"][
keyword
] += 1
else:
user_stats[user]["false_positives_avoided"] += 1
user_stats[user]["innocent_detections"].append(
{
"word": keyword,
"message": message[:150],
"reason": reason,
}
)
except Exception:
continue
print(f"\n✓ Analyzed {len(messages)} messages from {len(user_stats)} users")
for user, stats in user_stats.items():
if stats["message_count"] > 0:
stats["avg_message_length"] = (
stats["total_length"] / stats["message_count"]
)
stats["negative_message_ratio"] = (
stats["negative_message_count"] / stats["message_count"]
)
stats["avg_sentiment"] = (
float(np.mean(stats["sentiment_scores"]))
if stats["sentiment_scores"]
else 0.0
)
if stats["bert_embeddings"]:
stats["avg_bert_embedding"] = np.mean(
stats["bert_embeddings"], axis=0
)
else:
stats["avg_bert_embedding"] = np.zeros(768)
else:
stats["avg_message_length"] = 0
stats["negative_message_ratio"] = 0
stats["avg_sentiment"] = 0.0
stats["avg_bert_embedding"] = np.zeros(768)
stats["suspicion_score"] = min(100, stats["suspicion_score"])
return dict(user_stats)
def apply_dbscan_clustering(
self,
user_stats: Dict[str, Any],
centrality_metrics: Dict[str, Dict[str, float]],
) -> Dict[str, Any]:
print("🔬 Applying DBSCAN clustering...")
if len(user_stats) < 3:
print("⚠️ Not enough users for DBSCAN. Skipping.")
for user in user_stats:
user_stats[user]["dbscan_cluster"] = -1
return user_stats
try:
users = list(user_stats.keys())
features = []
for user in users:
stats = user_stats[user]
centrality = centrality_metrics.get(
user,
{
"degree_centrality": 0,
"betweenness_centrality": 0,
"pagerank": 0,
},
)
feature_vec = [
stats["suspicion_score"],
stats["message_count"],
stats["keyword_count"],
stats.get("avg_message_length", 0),
stats.get("avg_sentiment", 0),
stats.get("negative_message_ratio", 0),
centrality["degree_centrality"] * 100,
centrality["betweenness_centrality"] * 100,
centrality["pagerank"] * 100,
]
features.append(feature_vec)
features = np.array(features, dtype=np.float32)
scaler = StandardScaler()
features_scaled = scaler.fit_transform(features)
dbscan = DBSCAN(eps=0.5, min_samples=max(2, len(users) // 5))
clusters = dbscan.fit_predict(features_scaled)
for i, user in enumerate(users):
user_stats[user]["dbscan_cluster"] = int(clusters[i])
n_clusters = len(set(clusters)) - (1 if -1 in clusters else 0)
n_noise = list(clusters).count(-1)
print(f"✓ DBSCAN found {n_clusters} clusters and {n_noise} outliers")
except Exception as e:
print(f"⚠️ DBSCAN clustering failed: {str(e)[:100]}")
for user in user_stats:
user_stats[user]["dbscan_cluster"] = -1
return user_stats
def apply_kmeans_clustering(self, user_stats: Dict[str, Any]) -> Dict[str, Any]:
print("📊 Applying K-Means clustering...")
if len(user_stats) < 3:
print("⚠️ Not enough users for K-Means. Skipping.")
for user in user_stats:
user_stats[user]["kmeans_cluster"] = "N/A"
return user_stats
try:
users = list(user_stats.keys())
features = np.array(
[
[
stats["suspicion_score"],
stats["message_count"],
stats["keyword_count"],
stats.get("avg_message_length", 0),
stats.get("avg_sentiment", 0),
stats.get("negative_message_ratio", 0),
]
for stats in user_stats.values()
],
dtype=np.float32,
)
scaler = StandardScaler()
features_scaled = scaler.fit_transform(features)
n_clusters = min(3, len(users))
kmeans = KMeans(n_clusters=n_clusters, random_state=42, n_init=10)
clusters = kmeans.fit_predict(features_scaled)
avg_scores: Dict[int, list] = defaultdict(list)
for i, cluster_id in enumerate(clusters):
avg_scores[cluster_id].append(user_stats[users[i]]["suspicion_score"])
sorted_clusters = sorted(
avg_scores.items(), key=lambda item: np.mean(item[1]), reverse=True
)
labels = ["High Risk", "Medium Risk", "Low Risk"]
labels_map = {cid: labels[i] for i, (cid, _) in enumerate(sorted_clusters)}
for i, user in enumerate(users):
user_stats[user]["kmeans_cluster"] = labels_map.get(
clusters[i], "Low Risk"
)
print("✓ K-Means clustering complete")
except Exception as e:
print(f"⚠️ K-Means clustering failed: {str(e)[:100]}")
for user in user_stats:
user_stats[user]["kmeans_cluster"] = "N/A"
return user_stats
def train_lstm_model(self, user_stats: Dict[str, Any]) -> Dict[str, float]:
print("🧠 Training LSTM model for temporal analysis (heuristic)...")
lstm_scores: Dict[str, float] = {}
try:
for user, stats in user_stats.items():
if stats["message_count"] < 10:
lstm_scores[user] = 0.0
continue
temporal_features = []
for i, msg_text in enumerate(stats["messages_text"][:100]):
sentiment_idx = min(i, len(stats["sentiment_scores"]) - 1)
features = [
len(msg_text) / 500.0,
(stats["sentiment_scores"][sentiment_idx] + 1) / 2.0,
1.0
if any(
kw in msg_text.lower() for kw in self.all_direct_drug_terms
)
else 0.0,
i / max(len(stats["messages_text"]), 1),
stats["keyword_count"] / max(stats["message_count"], 1),
stats.get("avg_message_length", 0) / 500.0,
stats["negative_message_ratio"],
stats["suspicion_score"] / 100.0,
1.0 if stats.get("high_risk_keywords", 0) > 0 else 0.0,
1.0 if stats.get("medium_risk_keywords", 0) > 0 else 0.0,
]
temporal_features.append(features[:10])
if len(temporal_features) < 5:
lstm_scores[user] = 0.0
continue
temporal_array = np.array(temporal_features)
variance_score = np.mean(np.std(temporal_array, axis=0))
lstm_scores[user] = min(1.0, float(variance_score))
except Exception as e:
print(f"⚠️ LSTM training encountered error: {str(e)[:100]}")
lstm_scores = {user: 0.0 for user in user_stats.keys()}
print("✓ LSTM temporal analysis complete")
return lstm_scores
def generate_comprehensive_report(
self,
user_stats: Dict[str, Any],
centrality_metrics: Dict[str, Dict[str, float]],
lstm_scores: Dict[str, float],
output_path: str,
) -> Dict[str, Any]:
sorted_users = sorted(
user_stats.items(),
key=lambda x: x[1]["suspicion_score"],
reverse=True,
)
total_false_positives_avoided = sum(
u["false_positives_avoided"] for u in user_stats.values()
)
report: Dict[str, Any] = {
"analysis_timestamp": datetime.now().isoformat(),
"detection_system": "META DETECT v1.0",
"detection_mode": "Context-Aware + BERT + LSTM",
"total_users": len(user_stats),
"total_false_positives_avoided": total_false_positives_avoided,
"kmeans_high_risk": sum(
1 for u in user_stats.values() if u.get("kmeans_cluster") == "High Risk"
),
"kmeans_medium_risk": sum(
1
for u in user_stats.values()
if u.get("kmeans_cluster") == "Medium Risk"
),
"kmeans_low_risk": sum(
1 for u in user_stats.values() if u.get("kmeans_cluster") == "Low Risk"
),
"dbscan_outliers": sum(
1 for u in user_stats.values() if u.get("dbscan_cluster") == -1
),
"total_keywords_detected": sum(
u["keyword_count"] for u in user_stats.values()
),
"network_analysis_enabled": bool(centrality_metrics),
"bert_enabled": self.use_bert,
"users": [],
}
for i, (user, stats) in enumerate(sorted_users):
centrality = centrality_metrics.get(user, {})
top_suspicious_words = stats["suspicious_word_frequency"].most_common(5)
suspicious_words_summary = [
{
"word": word,
"frequency": count,
"category": next(
(cat for cat, kws in self.drug_keywords.items() if word in kws),
"unknown",
),
}
for word, count in top_suspicious_words
]
user_report = {
"rank": i + 1,
"username": user,
"suspicion_score": float(stats["suspicion_score"]),
"false_positives_avoided": int(stats["false_positives_avoided"]),
"kmeans_cluster": stats.get("kmeans_cluster", "N/A"),
"dbscan_cluster": int(stats.get("dbscan_cluster", -1)),
"lstm_risk_score": round(float(lstm_scores.get(user, 0)), 3),
"message_count": int(stats["message_count"]),
"keyword_count": int(stats["keyword_count"]),
"high_risk_keywords": int(stats["high_risk_keywords"]),
"medium_risk_keywords": int(stats["medium_risk_keywords"]),
"contextual_slang_keywords": int(
stats.get("contextual_slang_keywords", 0)
),
"avg_message_length": round(float(stats.get("avg_message_length", 0)), 2),
"avg_sentiment_score": round(float(stats.get("avg_sentiment", 0)), 3),
"negative_message_ratio": round(
float(stats.get("negative_message_ratio", 0)), 2
),
"network_degree_centrality": round(
float(centrality.get("degree_centrality", 0)), 3
),
"network_betweenness": round(
float(centrality.get("betweenness_centrality", 0)), 3
),
"network_pagerank": round(float(centrality.get("pagerank", 0)), 3),
"suspicious_words_used": suspicious_words_summary,
"total_suspicious_words_instances": len(stats["suspicious_words"]),
}
report["users"].append(user_report)
try:
with open(output_path, "w", encoding="utf-8") as f:
json.dump(report, f, indent=4, ensure_ascii=False)
print(f"\n✓ Comprehensive report saved to {output_path}")
except Exception as e:
print(f"⚠️ Error saving report: {str(e)[:100]}")
return report
def export_suspicious_words_csv(
self,
user_stats: Dict[str, Any],
base_filename: str,
output_dir: str = ".",
) -> str:
csv_path = os.path.join(
output_dir, f"{base_filename}_suspicious_words_details.csv"
)
try:
with open(csv_path, "w", newline="", encoding="utf-8") as csvfile:
writer = csv.writer(csvfile)
writer.writerow(
[
"Username",
"Word",
"Category",
"Frequency",
"Detection Reason",
"Message Context",
"Timestamp",
]
)
for user, stats in user_stats.items():
for word_instance in stats["suspicious_words"]:
writer.writerow(
[
user,
word_instance["word"],
word_instance["category"],
stats["suspicious_word_frequency"][
word_instance["word"]
],
word_instance.get("reason", "N/A"),
word_instance["message_context"],
word_instance["timestamp"],
]
)
print(f"✓ Suspicious words details exported to {csv_path}")
except Exception as e:
print(f"⚠️ Error exporting CSV: {str(e)[:100]}")
return csv_path
def export_suspicious_words_summary_csv(
self,
report: Dict[str, Any],
base_filename: str,
output_dir: str = ".",
) -> str:
csv_path = os.path.join(
output_dir, f"{base_filename}_suspicious_words_summary.csv"
)
try:
with open(csv_path, "w", newline="", encoding="utf-8") as csvfile:
writer = csv.writer(csvfile)
writer.writerow(
[
"Rank",
"Username",
"Risk Score",
"False Positives Avoided",
"Total Instances",
"Top Word",
"Top Word Frequency",
"Top Word Category",
]
)
for user_report in report["users"]:
top_word = (
user_report["suspicious_words_used"][0]
if user_report["suspicious_words_used"]
else {}
)
writer.writerow(
[
user_report["rank"],
user_report["username"],
user_report["suspicion_score"],
user_report["false_positives_avoided"],
user_report["total_suspicious_words_instances"],
top_word.get("word", "N/A"),
top_word.get("frequency", 0),
top_word.get("category", "N/A"),
]
)
print(f"✓ Suspicious words summary exported to {csv_path}")
except Exception as e:
print(f"⚠️ Error exporting CSV: {str(e)[:100]}")
return csv_path
def create_static_dashboard_image(
self,
user_stats: Dict[str, Any],
centrality_metrics: Dict[str, Dict[str, float]],
output_path: str,
):
if not user_stats:
print("⚠️ No user statistics to visualize.")
return
print("📸 Generating static dashboard image (PNG)...")
try:
df = pd.DataFrame(
[
{
"User": user[:20],
"Score": stats["suspicion_score"],
"Messages": stats["message_count"],
"Keywords": stats["keyword_count"],
"KMeans": stats.get("kmeans_cluster", "N/A"),
"DBSCAN": stats.get("dbscan_cluster", -1),
"Sentiment": stats.get("avg_sentiment", 0),
"Degree": centrality_metrics.get(user, {}).get(
"degree_centrality", 0
),
"Betweenness": centrality_metrics.get(user, {}).get(
"betweenness_centrality", 0
),
"SuspiciousWords": len(stats["suspicious_words"]),
"FalsePositivesAvoided": stats["false_positives_avoided"],
}
for user, stats in user_stats.items()
]
).sort_values("Score", ascending=False)
if len(df) == 0:
print("⚠️ DataFrame is empty.")
return
fig = plt.figure(figsize=(20, 14))
gs = fig.add_gridspec(4, 3, hspace=0.3, wspace=0.3)
color_map = {
"High Risk": "#2563eb",
"Medium Risk": "#3b82f6",
"Low Risk": "#60a5fa",
"N/A": "#64748b",
}
ax1 = fig.add_subplot(gs[0, :2])
top_10 = df.head(10)
colors_top10 = [color_map.get(c, "#64748b") for c in top_10["KMeans"]]
ax1.barh(top_10["User"], top_10["Score"], color=colors_top10)
ax1.set_xlabel("Suspicion Score", fontsize=10)
ax1.set_title("Top 10 Users by Risk Score", fontsize=12, fontweight="bold")
ax1.invert_yaxis()
ax2 = fig.add_subplot(gs[0, 2])
kmeans_counts = df["KMeans"].value_counts()
colors_pie = [color_map.get(c, "#64748b") for c in kmeans_counts.index]
ax2.pie(
kmeans_counts.values,
labels=kmeans_counts.index,