File size: 18,570 Bytes
b4856f1
 
 
 
752f5cc
b4856f1
4134ab0
b4856f1
 
 
 
 
 
 
 
 
 
 
 
4134ab0
 
 
b4c4175
4134ab0
 
 
 
 
b4856f1
 
 
 
752f5cc
b4856f1
 
 
752f5cc
b4856f1
 
 
 
 
752f5cc
b4856f1
 
752f5cc
b4856f1
 
 
 
752f5cc
b4856f1
 
 
 
 
 
752f5cc
b4856f1
752f5cc
2473009
752f5cc
b4856f1
752f5cc
b4856f1
 
 
752f5cc
b4856f1
 
752f5cc
b4856f1
 
 
 
 
 
 
752f5cc
b4856f1
752f5cc
b4856f1
 
 
 
 
 
752f5cc
b4856f1
 
 
 
 
 
 
 
 
752f5cc
b4856f1
 
 
752f5cc
b4856f1
 
 
 
 
 
 
 
 
752f5cc
b4856f1
 
 
 
 
 
752f5cc
b4856f1
 
 
752f5cc
b4856f1
 
 
 
 
 
752f5cc
b4856f1
 
752f5cc
b4856f1
 
 
 
 
 
 
 
 
752f5cc
b4856f1
752f5cc
4134ab0
 
 
 
b4856f1
 
752f5cc
b4856f1
 
 
752f5cc
4134ab0
 
 
b4c4175
4134ab0
 
 
b4c4175
4134ab0
 
 
 
 
b4c4175
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4134ab0
b4c4175
4134ab0
 
b4c4175
 
 
4134ab0
 
b4c4175
4134ab0
 
b4c4175
4134ab0
 
b4c4175
4134ab0
 
 
 
b4c4175
4134ab0
 
 
 
 
 
 
b4c4175
4134ab0
 
 
b4c4175
4134ab0
 
 
b4c4175
4134ab0
 
 
 
 
 
 
 
b4c4175
4134ab0
b4c4175
 
4134ab0
b4c4175
 
 
 
4134ab0
 
 
b4856f1
 
 
752f5cc
 
 
 
b4856f1
 
 
 
 
 
752f5cc
b4856f1
 
 
 
 
752f5cc
b4856f1
 
752f5cc
b4856f1
 
752f5cc
b4856f1
752f5cc
 
 
 
 
 
 
b4856f1
752f5cc
 
b4856f1
752f5cc
b4856f1
 
752f5cc
b4856f1
752f5cc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b4856f1
752f5cc
b4856f1
 
752f5cc
b4856f1
 
 
752f5cc
b4856f1
 
752f5cc
b4856f1
 
 
 
 
752f5cc
b4856f1
 
 
 
 
752f5cc
b4856f1
 
752f5cc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b4856f1
 
752f5cc
 
 
 
 
 
 
 
 
 
 
 
b4856f1
752f5cc
b4856f1
 
 
752f5cc
ff3017c
 
 
 
 
 
 
 
 
52329fa
ff3017c
 
 
 
 
 
 
 
 
 
 
52329fa
 
 
 
 
 
 
 
 
 
 
 
 
ff3017c
 
52329fa
 
 
 
 
 
 
 
 
 
ff3017c
 
 
 
 
 
b4856f1
 
 
752f5cc
b4856f1
 
752f5cc
b4856f1
 
 
 
 
 
752f5cc
b4856f1
 
 
 
 
752f5cc
b4856f1
 
752f5cc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
16ec2cf
752f5cc
 
b4856f1
 
752f5cc
 
 
 
 
 
 
 
b4856f1
752f5cc
b4856f1
 
 
752f5cc
b4856f1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
752f5cc
b4856f1
 
 
 
 
 
752f5cc
 
 
 
b4856f1
 
 
752f5cc
b4856f1
752f5cc
b4856f1
 
 
 
16ec2cf
 
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
"""
src/storage/storage_manager.py
Unified storage manager orchestrating 3-tier deduplication pipeline
"""

import logging
import re
from typing import Dict, Any, List, Optional, Tuple
import csv
from datetime import datetime
from pathlib import Path

from .config import config
from .sqlite_cache import SQLiteCache
from .chromadb_store import ChromaDBStore
from .neo4j_graph import Neo4jGraph

logger = logging.getLogger("storage_manager")

# Trending detection integration
try:
    from ..utils.trending_detector import record_topic_mention

    TRENDING_AVAILABLE = True
except ImportError:
    TRENDING_AVAILABLE = False
    logger.warning("[StorageManager] Trending detector not available")


class StorageManager:
    """
    Unified storage interface implementing 3-tier deduplication:

    Tier 1: SQLite - Fast hash lookup (microseconds)
    Tier 2: ChromaDB - Semantic similarity (milliseconds)
    Tier 3: Accept unique events

    Also handles:
    - Feed persistence (CSV export)
    - Knowledge graph tracking (Neo4j)
    - Statistics and monitoring
    """

    def __init__(self):
        logger.info("[StorageManager] Initializing multi-database storage system")

        # Initialize all storage backends
        self.sqlite_cache = SQLiteCache()
        self.chromadb = ChromaDBStore()
        self.neo4j = Neo4jGraph()

        # Statistics tracking
        self.stats = {
            "total_processed": 0,
            "exact_duplicates": 0,
            "semantic_duplicates": 0,
            "unique_stored": 0,
            "errors": 0,
        }

        logger.info("[StorageManager] Configuration loaded")

    def is_duplicate(
        self, summary: str, threshold: Optional[float] = None
    ) -> Tuple[bool, str, Optional[Dict[str, Any]]]:
        """
        Check if summary is duplicate using 3-tier pipeline.

        Returns:
            (is_duplicate, reason, match_data)

        Reasons:
            - "exact_match" - SQLite hash match
            - "semantic_match" - ChromaDB similarity match
            - "unique" - New event
        """
        if not summary or len(summary.strip()) < 10:
            return False, "too_short", None

        self.stats["total_processed"] += 1

        # TIER 1: SQLite exact match (fastest)
        is_exact, event_id = self.sqlite_cache.has_exact_match(summary)
        if is_exact:
            self.stats["exact_duplicates"] += 1
            logger.info(f"[DEDUPE] ✓ EXACT MATCH (SQLite): {summary[:60]}...")
            return True, "exact_match", {"matched_event_id": event_id}

        # TIER 2: ChromaDB semantic similarity
        similar = self.chromadb.find_similar(summary, threshold=threshold)
        if similar:
            self.stats["semantic_duplicates"] += 1
            logger.info(
                f"[DEDUPE] ✓ SEMANTIC MATCH (ChromaDB): "
                f"similarity={similar['similarity']:.3f} | {summary[:60]}..."
            )
            return True, "semantic_match", similar

        # TIER 3: Unique event
        logger.info(f"[DEDUPE] ✓ UNIQUE EVENT: {summary[:60]}...")
        return False, "unique", None

    def store_event(
        self,
        event_id: str,
        summary: str,
        domain: str,
        severity: str,
        impact_type: str,
        confidence_score: float,
        timestamp: Optional[str] = None,
        metadata: Optional[Dict[str, Any]] = None,
    ):
        """
        Store event in all databases.
        Should only be called AFTER is_duplicate() returns False.
        """
        timestamp = timestamp or datetime.utcnow().isoformat()

        try:
            # Store in SQLite cache
            self.sqlite_cache.add_entry(summary, event_id)

            # Store in ChromaDB for semantic search
            chroma_metadata = {
                "domain": domain,
                "severity": severity,
                "impact_type": impact_type,
                "confidence_score": confidence_score,
                "timestamp": timestamp,
            }
            self.chromadb.add_event(event_id, summary, chroma_metadata)

            # Store in Neo4j knowledge graph
            self.neo4j.add_event(
                event_id=event_id,
                domain=domain,
                summary=summary,
                severity=severity,
                impact_type=impact_type,
                confidence_score=confidence_score,
                timestamp=timestamp,
                metadata=metadata,
            )

            # Record keywords for trending detection
            if TRENDING_AVAILABLE:
                self._record_trending_mentions(summary, domain, metadata)

            self.stats["unique_stored"] += 1
            logger.debug(f"[STORE] Stored event {event_id[:8]}... in all databases")

        except Exception as e:
            self.stats["errors"] += 1
            logger.error(f"[STORE] Error storing event: {e}")

    def _extract_keywords(self, text: str, max_keywords: int = 5) -> List[str]:
        """
        Extract significant keywords from text for trending detection.

        Args:
            text: Text to extract keywords from
            max_keywords: Maximum number of keywords to return

        Returns:
            List of keywords (2-3 word phrases)
        """
        # Common stopwords to filter out
        stopwords = {
            "the",
            "is",
            "at",
            "which",
            "on",
            "a",
            "an",
            "and",
            "or",
            "but",
            "in",
            "with",
            "to",
            "for",
            "of",
            "as",
            "by",
            "from",
            "that",
            "this",
            "be",
            "are",
            "was",
            "were",
            "been",
            "being",
            "have",
            "has",
            "had",
            "do",
            "does",
            "did",
            "will",
            "would",
            "could",
            "should",
            "may",
            "might",
            "must",
            "shall",
            "can",
            "need",
            "dare",
            "ought",
            "used",
            "सिंहल",
            "தமிழ்",  # Common Sinhala/Tamil particles
        }

        # Clean text
        text = text.lower()
        text = re.sub(r"http\S+|www\.\S+", "", text)  # Remove URLs
        text = re.sub(r"[^\w\s]", " ", text)  # Remove punctuation

        # Split into words
        words = text.split()

        # Filter stopwords and short words
        filtered = [w for w in words if w not in stopwords and len(w) > 2]

        # Extract significant words (prioritize proper nouns, locations, etc.)
        keywords = []

        # Single important words (capitalized in original or long words)
        for word in filtered[:20]:
            if len(word) > 4:  # Longer words are often more significant
                keywords.append(word)

        # Deduplicate and limit
        seen = set()
        unique_keywords = []
        for kw in keywords:
            if kw not in seen:
                seen.add(kw)
                unique_keywords.append(kw)

        return unique_keywords[:max_keywords]

    def _record_trending_mentions(
        self, summary: str, domain: str, metadata: Optional[Dict[str, Any]] = None
    ):
        """
        Extract keywords from summary and record them for trending detection.

        Args:
            summary: Event summary text
            domain: Event domain (political, economical, etc.)
            metadata: Optional metadata with platform info
        """
        try:
            keywords = self._extract_keywords(summary)
            source = metadata.get("platform", "scraper") if metadata else "scraper"

            for keyword in keywords:
                record_topic_mention(topic=keyword, source=source, domain=domain)

            if keywords:
                logger.debug(
                    f"[TRENDING] Recorded {len(keywords)} keywords: {keywords[:3]}..."
                )

        except Exception as e:
            logger.warning(f"[TRENDING] Error recording mentions: {e}")

    def link_similar_events(self, event_id_1: str, event_id_2: str, similarity: float):
        """Create similarity link in Neo4j"""
        self.neo4j.link_similar_events(event_id_1, event_id_2, similarity)

    def export_feed_to_csv(
        self, feed: List[Dict[str, Any]], filename: Optional[str] = None
    ):
        """
        Export feed to CSV for archival and analysis.
        Creates daily files by default.
        """
        if not feed:
            return

        try:
            # Generate filename
            if filename is None:
                date_str = datetime.utcnow().strftime("%Y-%m-%d")
                filename = f"feed_{date_str}.csv"

            filepath = Path(config.CSV_EXPORT_DIR) / filename
            filepath.parent.mkdir(parents=True, exist_ok=True)

            # Check if file exists to decide whether to write header
            file_exists = filepath.exists()

            fieldnames = [
                "event_id",
                "timestamp",
                "domain",
                "severity",
                "impact_type",
                "confidence_score",
                "summary",
            ]

            with open(filepath, "a", newline="", encoding="utf-8") as f:
                writer = csv.DictWriter(f, fieldnames=fieldnames)

                if not file_exists:
                    writer.writeheader()

                for event in feed:
                    writer.writerow(
                        {
                            "event_id": event.get("event_id", ""),
                            "timestamp": event.get("timestamp", ""),
                            "domain": event.get(
                                "domain", event.get("target_agent", "")
                            ),
                            "severity": event.get("severity", ""),
                            "impact_type": event.get("impact_type", ""),
                            "confidence_score": event.get(
                                "confidence_score", event.get("confidence", 0)
                            ),
                            "summary": event.get(
                                "summary", event.get("content_summary", "")
                            ),
                        }
                    )

            logger.info(f"[CSV] Exported {len(feed)} events to {filepath}")

        except Exception as e:
            logger.error(f"[CSV] Export error: {e}")

    def get_recent_feeds(self, limit: int = 50) -> List[Dict[str, Any]]:
        """
        Retrieve recent feeds from SQLite with ChromaDB metadata.

        Args:
            limit: Maximum number of feeds to return

        Returns:
            List of feed dictionaries with full metadata
        """
        try:
            entries = self.sqlite_cache.get_all_entries(limit=limit, offset=0)

            feeds = []
            for entry in entries:
                event_id = entry.get("event_id")
                if not event_id:
                    continue

                try:
                    chroma_data = self.chromadb.collection.get(ids=[event_id])
                    if chroma_data and chroma_data["metadatas"]:
                        metadata = chroma_data["metadatas"][0]
                        feeds.append(
                            {
                                "event_id": event_id,
                                "summary": entry.get("summary_preview", ""),
                                "domain": metadata.get("domain", "unknown"),
                                "severity": metadata.get("severity", "medium"),
                                "impact_type": metadata.get("impact_type", "risk"),
                                "confidence": metadata.get("confidence_score", 0.5),
                                "timestamp": metadata.get(
                                    "timestamp", entry.get("last_seen")
                                ),
                            }
                        )
                except Exception as e:
                    logger.warning(f"Could not fetch ChromaDB data for {event_id}: {e}")
                    feeds.append(
                        {
                            "event_id": event_id,
                            "summary": entry.get("summary_preview", ""),
                            "domain": "unknown",
                            "severity": "medium",
                            "impact_type": "risk",
                            "confidence": 0.5,
                            "timestamp": entry.get("last_seen"),
                        }
                    )

            return feeds

        except Exception as e:
            logger.error(f"[FEED_RETRIEVAL] Error: {e}")
            return []

        return feeds

    def search_feeds(self, query: str, limit: int = 5) -> List[Dict[str, Any]]:
        """
        Search feeds by keyword and return enriched results.
        """
        try:
            entries = self.sqlite_cache.search_entries(query, limit=limit)
            feeds = []

            for entry in entries:
                event_id = entry.get("event_id")
                if not event_id:
                    continue

                try:
                    # Try to get metadata from Chroma (optional)
                    chroma_data = self.chromadb.collection.get(ids=[event_id])
                    metadata = {}
                    if chroma_data and chroma_data["metadatas"]:
                        metadata = chroma_data["metadatas"][0]

                    feeds.append(
                        {
                            "event_id": event_id,
                            "summary": entry.get("summary_preview", ""),
                            "domain": metadata.get("domain", "unknown"),
                            "severity": metadata.get("severity", "medium"),
                            "timestamp": metadata.get(
                                "timestamp", entry.get("last_seen")
                            ),
                            "source": metadata.get("source", "feed"),
                        }
                    )
                except Exception:
                    # Fallback if chroma fails
                    feeds.append(
                        {
                            "event_id": event_id,
                            "summary": entry.get("summary_preview", ""),
                            "domain": "unknown",
                            "severity": "medium",
                            "timestamp": entry.get("last_seen"),
                        }
                    )

            return feeds

        except Exception as e:
            logger.error(f"[FEED_SEARCH] Error searching for '{query}': {e}")
            return []

    def get_feeds_since(self, timestamp: datetime) -> List[Dict[str, Any]]:
        """
        Get all feeds added after given timestamp.

        Args:
            timestamp: Datetime object

        Returns:
            List of feed dictionaries
        """
        try:
            iso_timestamp = timestamp.isoformat()
            entries = self.sqlite_cache.get_entries_since(iso_timestamp)

            feeds = []
            for entry in entries:
                event_id = entry.get("event_id")
                if not event_id:
                    continue

                try:
                    chroma_data = self.chromadb.collection.get(ids=[event_id])
                    if chroma_data and chroma_data["metadatas"]:
                        metadata = chroma_data["metadatas"][0]
                        feeds.append(
                            {
                                "event_id": event_id,
                                "summary": entry.get("summary_preview", ""),
                                "domain": metadata.get("domain", "unknown"),
                                "severity": metadata.get("severity", "medium"),
                                "impact_type": metadata.get("impact_type", "risk"),
                                "confidence": metadata.get("confidence_score", 0.5),
                                "timestamp": metadata.get(
                                    "timestamp", entry.get("last_seen")
                                ),
                            }
                        )
                except Exception:
                    feeds.append(
                        {
                            "event_id": event_id,
                            "summary": entry.get("summary_preview", ""),
                            "domain": "unknown",
                            "severity": "medium",
                            "impact_type": "risk",
                            "confidence": 0.5,
                            "timestamp": entry.get("last_seen"),
                        }
                    )

            return feeds

        except Exception as e:
            logger.error(f"[FEED_RETRIEVAL] Error: {e}")
            return []

    def get_feed_count(self) -> int:
        """Get total feed count from database"""
        try:
            stats = self.sqlite_cache.get_stats()
            return stats.get("total_entries", 0)
        except Exception as e:
            logger.error(f"[FEED_COUNT] Error: {e}")
            return 0

    def cleanup_old_data(self):
        """Cleanup old entries from SQLite cache"""
        try:
            deleted = self.sqlite_cache.cleanup_old_entries()
            if deleted > 0:
                logger.info(f"[CLEANUP] Removed {deleted} old cache entries")
        except Exception as e:
            logger.error(f"[CLEANUP] Error: {e}")

    def get_comprehensive_stats(self) -> Dict[str, Any]:
        """Get statistics from all storage backends"""
        return {
            "deduplication": {
                **self.stats,
                "dedup_rate": (
                    (self.stats["exact_duplicates"] + self.stats["semantic_duplicates"])
                    / max(self.stats["total_processed"], 1)
                    * 100
                ),
            },
            "sqlite": self.sqlite_cache.get_stats(),
            "chromadb": self.chromadb.get_stats(),
            "neo4j": self.neo4j.get_stats(),
        }

    def __del__(self):
        """Cleanup on destruction"""
        try:
            self.neo4j.close()
        except Exception:
            pass  # Ignore close errors