File size: 25,052 Bytes
e4932aa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import re
import json
import os
from typing import List, Set, Dict, Tuple
from pathlib import Path
import pandas as pd
from dotenv import load_dotenv

# Import your CTI tools
from langchain.chat_models import init_chat_model
from langchain_tavily import TavilySearch
import sys

sys.path.append("src/agents/cti_agent")
from cti_tools import CTITools
from config import MODEL_NAME, CTI_SEARCH_CONFIG


class CTIToolsEvaluator:
    """Evaluator for CTI tools on CTIBench benchmarks."""

    def __init__(self):
        """Initialize the evaluator with CTI tools."""
        load_dotenv()

        # Initialize LLM
        self.llm = init_chat_model(MODEL_NAME, temperature=0.1)

        # Initialize search (needed for CTITools init, even if not used in evaluation)
        search_config = {**CTI_SEARCH_CONFIG, "api_key": os.getenv("TAVILY_API_KEY")}
        self.cti_search = TavilySearch(**search_config)

        # Initialize CTI Tools
        self.cti_tools = CTITools(self.llm, self.cti_search)

        # Storage for results
        self.ate_results = []
        self.taa_results = []

    # ==================== CTI-ATE: MITRE Technique Extraction Tool ====================

    def extract_technique_ids(self, text: str) -> Set[str]:
        """

        Extract MITRE technique IDs from text.

        Looks for patterns like T1234 (main techniques only, no subtechniques).



        Args:

            text: Text containing technique IDs



        Returns:

            Set of technique IDs (e.g., {'T1071', 'T1059'})

        """
        # Pattern for main techniques only (T#### not T####.###)
        pattern = r"\bT\d{4}\b"
        matches = re.findall(pattern, text)
        return set(matches)

    def calculate_ate_metrics(

        self, predicted: Set[str], ground_truth: Set[str]

    ) -> Dict[str, float]:
        """

        Calculate precision, recall, and F1 score for technique extraction.



        Args:

            predicted: Set of predicted technique IDs

            ground_truth: Set of ground truth technique IDs



        Returns:

            Dictionary with precision, recall, f1, tp, fp, fn

        """
        tp = len(predicted & ground_truth)  # True positives
        fp = len(predicted - ground_truth)  # False positives
        fn = len(ground_truth - predicted)  # False negatives

        precision = tp / len(predicted) if len(predicted) > 0 else 0.0
        recall = tp / len(ground_truth) if len(ground_truth) > 0 else 0.0
        f1 = (
            2 * (precision * recall) / (precision + recall)
            if (precision + recall) > 0
            else 0.0
        )

        return {
            "precision": precision,
            "recall": recall,
            "f1": f1,
            "tp": tp,
            "fp": fp,
            "fn": fn,
            "predicted_count": len(predicted),
            "ground_truth_count": len(ground_truth),
        }

    def evaluate_mitre_extraction_tool(

        self,

        sample_id: str,

        description: str,

        ground_truth: str,

        platform: str = "Enterprise",

    ) -> Dict:
        """

        Evaluate extract_mitre_techniques tool on a single sample.



        Args:

            sample_id: Sample identifier (e.g., URL)

            description: Malware/report description to analyze

            ground_truth: Ground truth technique IDs (comma-separated)

            platform: MITRE platform (Enterprise, Mobile, ICS)



        Returns:

            Dictionary with evaluation metrics

        """
        print(f"Evaluating {sample_id[:60]}...")

        # Call the extract_mitre_techniques tool
        tool_output = self.cti_tools.extract_mitre_techniques(description, platform)

        # Extract technique IDs from tool output
        predicted_ids = self.extract_technique_ids(tool_output)
        gt_ids = set([t.strip() for t in ground_truth.split(",") if t.strip()])

        # Calculate metrics
        metrics = self.calculate_ate_metrics(predicted_ids, gt_ids)

        result = {
            "sample_id": sample_id,
            "platform": platform,
            "description": description[:100] + "...",
            "tool_output": tool_output[:500] + "...",  # Truncate for storage
            "predicted": sorted(predicted_ids),
            "ground_truth": sorted(gt_ids),
            "missing": sorted(gt_ids - predicted_ids),  # False negatives
            "extra": sorted(predicted_ids - gt_ids),  # False positives
            **metrics,
        }

        self.ate_results.append(result)
        return result

    def evaluate_ate_from_tsv(

        self, filepath: str = "cti-bench/data/cti-ate.tsv", limit: int = None

    ) -> pd.DataFrame:
        """

        Evaluate extract_mitre_techniques tool on CTI-ATE benchmark.



        Args:

            filepath: Path to CTI-ATE TSV file

            limit: Optional limit on number of samples to evaluate



        Returns:

            DataFrame with results for each sample

        """
        print(f"\n{'='*80}")
        print(f"Evaluating extract_mitre_techniques tool on CTI-ATE benchmark")
        print(f"{'='*80}\n")

        # Load benchmark
        df = pd.read_csv(filepath, sep="\t")

        if limit:
            df = df.head(limit)

        print(f"Loaded {len(df)} samples from {filepath}")
        print(f"Starting evaluation...\n")

        # Evaluate each sample
        for idx, row in df.iterrows():
            try:
                self.evaluate_mitre_extraction_tool(
                    sample_id=row["URL"],
                    description=row["Description"],
                    ground_truth=row["GT"],
                    platform=row["Platform"],
                )
            except Exception as e:
                print(f"Error on sample {idx}: {e}")
                continue

        results_df = pd.DataFrame(self.ate_results)

        print(f"\nCompleted evaluation of {len(self.ate_results)} samples")
        return results_df

    def get_ate_summary(self) -> Dict:
        """

        Get summary statistics for CTI-ATE evaluation.



        Returns:

            Dictionary with macro and micro averaged metrics

        """
        if not self.ate_results:
            return {}

        df = pd.DataFrame(self.ate_results)

        # Macro averages (average of per-sample metrics)
        macro_metrics = {
            "macro_precision": df["precision"].mean(),
            "macro_recall": df["recall"].mean(),
            "macro_f1": df["f1"].mean(),
        }

        # Micro averages (calculated from total TP, FP, FN)
        total_tp = df["tp"].sum()
        total_fp = df["fp"].sum()
        total_fn = df["fn"].sum()
        total_predicted = df["predicted_count"].sum()
        total_gt = df["ground_truth_count"].sum()

        micro_precision = total_tp / total_predicted if total_predicted > 0 else 0.0
        micro_recall = total_tp / total_gt if total_gt > 0 else 0.0
        micro_f1 = (
            2 * (micro_precision * micro_recall) / (micro_precision + micro_recall)
            if (micro_precision + micro_recall) > 0
            else 0.0
        )

        micro_metrics = {
            "micro_precision": micro_precision,
            "micro_recall": micro_recall,
            "micro_f1": micro_f1,
            "total_samples": len(self.ate_results),
            "total_tp": int(total_tp),
            "total_fp": int(total_fp),
            "total_fn": int(total_fn),
        }

        return {**macro_metrics, **micro_metrics}

    # ==================== CTI-TAA: Threat Actor Attribution Tool ====================

    def normalize_actor_name(self, name: str) -> str:
        """

        Normalize threat actor names for comparison.



        Args:

            name: Threat actor name



        Returns:

            Normalized name (lowercase, trimmed)

        """
        if not name:
            return ""

        # Convert to lowercase and strip
        normalized = name.lower().strip()

        # Remove common prefixes
        prefixes = ["apt", "apt-", "group", "the "]
        for prefix in prefixes:
            if normalized.startswith(prefix):
                normalized = normalized[len(prefix) :].strip()

        return normalized

    def extract_actor_from_output(self, text: str) -> str:
        """

        Extract threat actor name from tool output.



        Args:

            text: Tool output text



        Returns:

            Extracted actor name or empty string

        """
        # Look for Q&A format from our updated prompt
        qa_patterns = [
            r"Q:\s*What threat actor.*?\n\s*A:\s*([^\n]+)",
            r"threat actor.*?is[:\s]+([A-Z][A-Za-z0-9\s\-]+?)(?:\s*\(|,|\.|$)",
            r"attributed to[:\s]+([A-Z][A-Za-z0-9\s\-]+?)(?:\s*\(|,|\.|$)",
        ]

        for pattern in qa_patterns:
            match = re.search(pattern, text, re.IGNORECASE | re.MULTILINE)
            if match:
                actor = match.group(1).strip()
                # Clean up common artifacts
                actor = actor.split("(")[0].strip()  # Remove parenthetical aliases
                if actor and actor.lower() not in [
                    "none",
                    "none identified",
                    "unknown",
                    "not specified",
                ]:
                    return actor

        return ""

    def check_actor_match(

        self, predicted: str, ground_truth: str, aliases: Dict[str, List[str]] = None

    ) -> bool:
        """

        Check if predicted actor matches ground truth, considering aliases.



        Args:

            predicted: Predicted threat actor name

            ground_truth: Ground truth threat actor name

            aliases: Optional dictionary mapping canonical names to aliases



        Returns:

            True if match, False otherwise

        """
        pred_norm = self.normalize_actor_name(predicted)
        gt_norm = self.normalize_actor_name(ground_truth)

        if not pred_norm or not gt_norm:
            return False

        # Direct match
        if pred_norm == gt_norm:
            return True

        # Check aliases if provided
        if aliases:
            # Check if prediction is in ground truth's aliases
            if gt_norm in aliases:
                for alias in aliases[gt_norm]:
                    if pred_norm == self.normalize_actor_name(alias):
                        return True

            # Check if ground truth is in prediction's aliases
            if pred_norm in aliases:
                for alias in aliases[pred_norm]:
                    if gt_norm == self.normalize_actor_name(alias):
                        return True

        return False

    def evaluate_threat_actor_tool(

        self,

        sample_id: str,

        report_text: str,

        ground_truth: str,

        aliases: Dict[str, List[str]] = None,

    ) -> Dict:
        """

        Evaluate identify_threat_actors tool on a single sample.



        Args:

            sample_id: Sample identifier (e.g., URL)

            report_text: Threat report text to analyze

            ground_truth: Ground truth threat actor name

            aliases: Optional alias dictionary for matching



        Returns:

            Dictionary with evaluation result

        """
        print(f"Evaluating {sample_id[:60]}...")

        # Call the identify_threat_actors tool
        tool_output = self.cti_tools.identify_threat_actors(report_text)

        # Extract predicted actor
        predicted_actor = self.extract_actor_from_output(tool_output)

        # Check if match
        is_correct = self.check_actor_match(predicted_actor, ground_truth, aliases)

        result = {
            "sample_id": sample_id,
            "report_snippet": report_text[:100] + "...",
            "tool_output": tool_output[:500] + "...",  # Truncate for storage
            "predicted_actor": predicted_actor,
            "ground_truth": ground_truth,
            "correct": is_correct,
        }

        self.taa_results.append(result)
        return result

    def evaluate_taa_from_tsv(

        self,

        filepath: str = "cti-bench/data/cti-taa.tsv",

        limit: int = None,

        interactive: bool = True,

    ) -> pd.DataFrame:
        """

        Evaluate identify_threat_actors tool on CTI-TAA benchmark.



        Since CTI-TAA has no ground truth labels, this generates predictions

        that need manual validation.



        Args:

            filepath: Path to CTI-TAA TSV file

            limit: Optional limit on number of samples to evaluate

            interactive: If True, prompts for manual validation after each prediction



        Returns:

            DataFrame with results for each sample

        """
        print(f"\n{'='*80}")
        print(f"Evaluating identify_threat_actors tool on CTI-TAA benchmark")
        print(f"{'='*80}\n")

        if not interactive:
            print("NOTE: Running in non-interactive mode.")
            print("Predictions will be saved for manual review later.")
        else:
            print("NOTE: Running in interactive mode.")
            print("You will be asked to validate each prediction (y/n/s to skip).")

        # Load benchmark
        df = pd.read_csv(filepath, sep="\t")

        if limit:
            df = df.head(limit)

        print(f"\nLoaded {len(df)} samples from {filepath}")
        print(f"Starting evaluation...\n")

        # Evaluate each sample
        for idx, row in df.iterrows():
            try:
                print(f"\n{'-'*80}")
                print(f"Sample {idx + 1}/{len(df)}")
                print(f"URL: {row['URL']}")
                print(f"Report snippet: {row['Text'][:200]}...")
                print(f"{'-'*80}")

                # Call the identify_threat_actors tool
                tool_output = self.cti_tools.identify_threat_actors(row["Text"])

                # Extract predicted actor
                predicted_actor = self.extract_actor_from_output(tool_output)

                print(f"\nTOOL OUTPUT:")
                print(tool_output[:600])
                if len(tool_output) > 600:
                    print("... (truncated)")

                print(
                    f"\nEXTRACTED ACTOR: {predicted_actor if predicted_actor else '(none detected)'}"
                )

                # Manual validation
                is_correct = None
                validator_notes = ""

                if interactive:
                    print(f"\nIs this attribution correct?")
                    print(f"  y = Yes, correct")
                    print(f"  n = No, incorrect")
                    print(
                        f"  p = Partially correct (e.g., right family but wrong specific group)"
                    )
                    print(f"  s = Skip this sample")
                    print(f"  q = Quit evaluation")

                    while True:
                        response = input("\nYour answer [y/n/p/s/q]: ").strip().lower()

                        if response == "y":
                            is_correct = True
                            break
                        elif response == "n":
                            is_correct = False
                            correct_actor = input(
                                "What is the correct actor? (optional): "
                            ).strip()
                            if correct_actor:
                                validator_notes = f"Correct actor: {correct_actor}"
                            break
                        elif response == "p":
                            is_correct = 0.5  # Partial credit
                            note = input("Explanation (optional): ").strip()
                            if note:
                                validator_notes = f"Partially correct: {note}"
                            break
                        elif response == "s":
                            print("Skipping this sample...")
                            break
                        elif response == "q":
                            print("Quitting evaluation...")
                            return pd.DataFrame(self.taa_results)
                        else:
                            print("Invalid response. Please enter y, n, p, s, or q.")

                # Store result
                result = {
                    "sample_id": row["URL"],
                    "report_snippet": row["Text"][:100] + "...",
                    "tool_output": tool_output[:500] + "...",
                    "predicted_actor": predicted_actor,
                    "is_correct": is_correct,
                    "validator_notes": validator_notes,
                    "needs_review": is_correct is None,
                }

                self.taa_results.append(result)

            except Exception as e:
                print(f"Error on sample {idx}: {e}")
                continue

        results_df = pd.DataFrame(self.taa_results)

        print(f"\n{'='*80}")
        print(f"Completed evaluation of {len(self.taa_results)} samples")

        if interactive:
            validated = sum(1 for r in self.taa_results if r["is_correct"] is not None)
            print(f"Validated: {validated}/{len(self.taa_results)}")

        return results_df

    def _extract_ground_truths_from_urls(self, urls: List[str]) -> Dict[str, str]:
        """

        Extract ground truth actor names from URLs.



        Args:

            urls: List of URLs from the benchmark



        Returns:

            Dictionary mapping URL to actor name

        """
        # Known threat actors and their URL patterns
        actor_patterns = {
            "sidecopy": "SideCopy",
            "apt29": "APT29",
            "apt36": "APT36",
            "transparent-tribe": "Transparent Tribe",
            "emotet": "Emotet",
            "bandook": "Bandook",
            "stately-taurus": "Stately Taurus",
            "mustang-panda": "Mustang Panda",
            "bronze-president": "Bronze President",
            "cozy-bear": "APT29",
            "nobelium": "APT29",
        }

        ground_truths = {}
        for url in urls:
            url_lower = url.lower()
            for pattern, actor in actor_patterns.items():
                if pattern in url_lower:
                    ground_truths[url] = actor
                    break

        return ground_truths

    def get_taa_summary(self) -> Dict:
        """

        Get summary statistics for CTI-TAA evaluation.



        Returns:

            Dictionary with accuracy and validation status

        """
        if not self.taa_results:
            return {}

        df = pd.DataFrame(self.taa_results)

        # Only calculate metrics for validated samples
        validated_df = df[df["is_correct"].notna()]

        if len(validated_df) == 0:
            return {
                "total_samples": len(df),
                "validated_samples": 0,
                "needs_review": len(df),
                "message": "No samples have been validated yet",
            }

        # Calculate accuracy (treating partial credit as 0.5)
        total_score = validated_df["is_correct"].sum()
        accuracy = total_score / len(validated_df) if len(validated_df) > 0 else 0.0

        # Count correct, incorrect, partial
        correct = sum(1 for x in validated_df["is_correct"] if x == True)
        incorrect = sum(1 for x in validated_df["is_correct"] if x == False)
        partial = sum(1 for x in validated_df["is_correct"] if x == 0.5)

        return {
            "accuracy": accuracy,
            "total_samples": len(df),
            "validated_samples": len(validated_df),
            "needs_review": len(df) - len(validated_df),
            "correct": correct,
            "incorrect": incorrect,
            "partial": partial,
        }

    # ==================== Utility Functions ====================

    def export_results(self, output_dir: str = "./tool_evaluation_results"):
        """

        Export evaluation results to CSV and JSON files.



        Args:

            output_dir: Directory to save results

        """
        output_path = Path(output_dir)
        output_path.mkdir(exist_ok=True)

        if self.ate_results:
            ate_df = pd.DataFrame(self.ate_results)
            ate_df.to_csv(
                output_path / "extract_mitre_techniques_results.csv", index=False
            )

            ate_summary = self.get_ate_summary()
            with open(output_path / "extract_mitre_techniques_summary.json", "w") as f:
                json.dump(ate_summary, f, indent=2)

            print(f"ATE results saved to {output_path}")

        if self.taa_results:
            taa_df = pd.DataFrame(self.taa_results)
            taa_df.to_csv(
                output_path / "identify_threat_actors_results.csv", index=False
            )

            taa_summary = self.get_taa_summary()
            with open(output_path / "identify_threat_actors_summary.json", "w") as f:
                json.dump(taa_summary, f, indent=2)

            print(f"TAA results saved to {output_path}")

    def print_summary(self):
        """Print summary of both tool evaluations."""
        print("\n" + "=" * 80)
        print("extract_mitre_techniques Tool Evaluation (CTI-ATE)")
        print("=" * 80)

        ate_summary = self.get_ate_summary()
        if ate_summary:
            print(f"Total Samples: {ate_summary['total_samples']}")
            print(f"\nMacro Averages (per-sample average):")
            print(f"  Precision: {ate_summary['macro_precision']:.4f}")
            print(f"  Recall:    {ate_summary['macro_recall']:.4f}")
            print(f"  F1 Score:  {ate_summary['macro_f1']:.4f}")
            print(f"\nMicro Averages (overall corpus):")
            print(f"  Precision: {ate_summary['micro_precision']:.4f}")
            print(f"  Recall:    {ate_summary['micro_recall']:.4f}")
            print(f"  F1 Score:  {ate_summary['micro_f1']:.4f}")
            print(f"\nConfusion Matrix:")
            print(f"  True Positives:  {ate_summary['total_tp']}")
            print(f"  False Positives: {ate_summary['total_fp']}")
            print(f"  False Negatives: {ate_summary['total_fn']}")
        else:
            print("No results available.")

        print("\n" + "=" * 80)
        print("identify_threat_actors Tool Evaluation (CTI-TAA)")
        print("=" * 80)

        taa_summary = self.get_taa_summary()
        if taa_summary:
            print(f"Total Samples: {taa_summary['total_samples']}")
            print(
                f"Accuracy: {taa_summary['accuracy']:.4f} ({taa_summary['accuracy']*100:.2f}%)"
            )
            print(f"Correct: {taa_summary['correct']}")
            print(f"Incorrect: {taa_summary['incorrect']}")
        else:
            print("No results available.")

        print("=" * 80 + "\n")


# ==================== Main Evaluation Script ====================

if __name__ == "__main__":
    """Run evaluation on both CTI tools."""

    # Initialize evaluator
    print("Initializing CTI Tools Evaluator...")
    evaluator = CTIToolsEvaluator()

    # Define threat actor aliases for TAA evaluation
    aliases = {
        "apt29": ["cozy bear", "the dukes", "nobelium", "yttrium"],
        "apt36": ["transparent tribe", "mythic leopard"],
        "sidecopy": [],
        "emotet": [],
        "stately taurus": ["mustang panda", "bronze president"],
        "bandook": [],
    }

    # Evaluate extract_mitre_techniques tool (CTI-ATE)
    print("\n" + "=" * 80)
    print("PART 1: Evaluating extract_mitre_techniques tool")
    print("=" * 80)
    try:
        ate_results = evaluator.evaluate_ate_from_tsv(
            filepath="cti-bench/data/cti-ate.tsv"
        )
    except Exception as e:
        print(f"Error evaluating ATE: {e}")

    # Evaluate identify_threat_actors tool (CTI-TAA)
    print("\n" + "=" * 80)
    print("PART 2: Evaluating identify_threat_actors tool")
    print("=" * 80)
    try:
        taa_results = evaluator.evaluate_taa_from_tsv(
            filepath="cti-bench/data/cti-taa.tsv", limit=25, interactive=True
        )
    except Exception as e:
        print(f"Error evaluating TAA: {e}")

    # Print summary
    evaluator.print_summary()

    # Export results
    evaluator.export_results("./tool_evaluation_results")

    print("\nEvaluation complete! Results saved to ./tool_evaluation_results/")