Likhith Sai Seemala commited on
Commit
0ca462b
·
0 Parent(s):

Deploy IntentForge v2 to HF Spaces

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .gitattributes +1 -0
  2. Cargo.lock +0 -0
  3. Cargo.toml +121 -0
  4. Dockerfile +71 -0
  5. config.yaml +162 -0
  6. models/all-MiniLM-L6-v2.onnx +3 -0
  7. models/config.json +24 -0
  8. models/rerank-MiniLM-L6-v2.onnx +3 -0
  9. models/special_tokens_map.json +37 -0
  10. models/tokenizer.json +0 -0
  11. models/tokenizer_config.json +65 -0
  12. models/vocab.txt +0 -0
  13. services/query_layer/Dockerfile +41 -0
  14. services/query_layer/__pycache__/app.cpython-314.pyc +0 -0
  15. services/query_layer/app/__init__.py +0 -0
  16. services/query_layer/app/__version__.py +5 -0
  17. services/query_layer/app/config/__init__.py +34 -0
  18. services/query_layer/app/config/arq_pool.py +54 -0
  19. services/query_layer/app/config/health_checks.py +710 -0
  20. services/query_layer/app/config/hybrid_cache.py +370 -0
  21. services/query_layer/app/config/hybrid_query_cache.py +412 -0
  22. services/query_layer/app/config/model_cache.py +46 -0
  23. services/query_layer/app/config/multi_tier_cache.py +291 -0
  24. services/query_layer/app/config/optimized_cache.py +58 -0
  25. services/query_layer/app/config/query_cache.py +96 -0
  26. services/query_layer/app/config/redis_cache.py +342 -0
  27. services/query_layer/app/config/redis_product_cache.py +313 -0
  28. services/query_layer/app/config/search_session_manager.py +529 -0
  29. services/query_layer/app/config/settings.py +513 -0
  30. services/query_layer/app/config/tracing.py +411 -0
  31. services/query_layer/app/core/__init__.py +0 -0
  32. services/query_layer/app/core/embedding_service.py +349 -0
  33. services/query_layer/app/core/exceptions.py +249 -0
  34. services/query_layer/app/core/schema.py +332 -0
  35. services/query_layer/app/core/utils.py +100 -0
  36. services/query_layer/app/core/vector_store.py +560 -0
  37. services/query_layer/app/main.py +430 -0
  38. services/query_layer/app/models.py +735 -0
  39. services/query_layer/app/ranking/__init__.py +0 -0
  40. services/query_layer/app/ranking/enhanced_ranker.py +763 -0
  41. services/query_layer/app/ranking/optimized_ranker.py +388 -0
  42. services/query_layer/app/ranking/optimized_url_ranker.py +621 -0
  43. services/query_layer/app/ranking/ranker.py +1043 -0
  44. services/query_layer/app/ranking/url_ranker.py +888 -0
  45. services/query_layer/requirements.txt +9 -0
  46. sources.yaml +599 -0
  47. src/anti_detection/mod.rs +467 -0
  48. src/anti_detection_client/mod.rs +544 -0
  49. src/api/mod.rs +1659 -0
  50. src/cloudflare_bypass/detector.rs +197 -0
.gitattributes ADDED
@@ -0,0 +1 @@
 
 
1
+ *.onnx filter=lfs diff=lfs merge=lfs -text
Cargo.lock ADDED
The diff for this file is too large to render. See raw diff
 
Cargo.toml ADDED
@@ -0,0 +1,121 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [package]
2
+ name = "intent-forge-v2"
3
+ version = "0.1.0"
4
+ edition = "2021"
5
+
6
+ [features]
7
+ default = []
8
+ tor = ["arti-client", "tor-rtcompat", "rusqlite"]
9
+
10
+ [dependencies]
11
+ # Async runtime
12
+ tokio = { version = "1.35", features = ["full"] }
13
+
14
+ # HTTP client
15
+ reqwest = { version = "0.12", features = ["json", "rustls-tls", "gzip", "brotli", "socks"] }
16
+
17
+ # Async trait for provider pattern
18
+ async-trait = "0.1"
19
+ async-recursion = "1.0"
20
+
21
+ # Serialization
22
+ serde = { version = "1.0", features = ["derive"] }
23
+ serde_json = "1.0"
24
+ serde_yaml = "0.9"
25
+ toml = "0.8"
26
+
27
+ # Meilisearch client
28
+ meilisearch-sdk = "0.28"
29
+
30
+ # Qdrant client
31
+ qdrant-client = "1.9.0"
32
+
33
+ # Redis client
34
+ redis = { version = "1.1", features = ["tokio-comp", "connection-manager"] }
35
+
36
+ # Error handling
37
+ anyhow = "1.0"
38
+ thiserror = "1.0"
39
+
40
+ # Logging
41
+ tracing = "0.1"
42
+ tracing-subscriber = { version = "0.3", features = ["env-filter"] }
43
+
44
+ # Configuration
45
+ config = "0.14"
46
+
47
+ # Time
48
+ chrono = { version = "0.4", features = ["serde"] }
49
+
50
+ # URL parsing
51
+ url = "2.5"
52
+
53
+ # Regex
54
+ regex = "1.10"
55
+
56
+ # RSS Feed parsing
57
+ feed-rs = "1.3"
58
+
59
+ # Robots.txt
60
+ robotstxt = "0.3.0"
61
+
62
+ # Futures
63
+ futures = "0.3"
64
+
65
+ # UUID
66
+ uuid = { version = "1.6", features = ["v4", "v5", "serde"] }
67
+
68
+ # Binary quantization helpers
69
+ ndarray = "0.15"
70
+
71
+ # ONNX runtime for embeddings and scoring
72
+ ort = { version = "2.0.0-rc.10" }
73
+
74
+ # HTML parsing
75
+ scraper = "0.21"
76
+
77
+ # Cancellation and coordination
78
+ tokio-util = "0.7"
79
+
80
+ # Compression
81
+ zstd = "0.13"
82
+
83
+ # HTTP API
84
+ axum = { version = "0.7", features = ["json"] }
85
+ tower = "0.4"
86
+ tower-http = { version = "0.5", features = ["cors", "trace"] }
87
+
88
+ # Prometheus metrics
89
+ prometheus = "0.13"
90
+
91
+ # Gzip decompression (for WET files)
92
+ flate2 = "1.0"
93
+ reqwest-eventsource = "0.6.0"
94
+
95
+ # Image processing (lightweight - no GPU)
96
+ image = "0.25"
97
+ thumbhash = "0.1"
98
+
99
+ # Random number generation (for anti-detection)
100
+ rand = "0.8"
101
+
102
+ # URL encoding for API queries
103
+ urlencoding = "2.1"
104
+
105
+ # Content hashing for deduplication
106
+ sha2 = "0.10"
107
+
108
+ # Concurrent hash map/set
109
+ dashmap = "5.5"
110
+
111
+ # LRU cache for embeddings
112
+ lru = "0.12"
113
+
114
+ # Tor integration (optional, enable with --features tor)
115
+ arti-client = { version = "0.40.0", features = ["tokio"], optional = true }
116
+ tor-rtcompat = { version = "0.40.0", features = ["tokio"], optional = true }
117
+ rusqlite = { version = "0.38.0", features = ["bundled"], optional = true }
118
+
119
+ [dev-dependencies]
120
+ tokio-test = "0.4"
121
+ wiremock = "0.6"
Dockerfile ADDED
@@ -0,0 +1,71 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # --- Build Stage for Rust ---
2
+ FROM rust:latest as builder
3
+
4
+ WORKDIR /app
5
+
6
+ # Install build dependencies
7
+ RUN apt-get update && apt-get install -y \
8
+ pkg-config \
9
+ libssl-dev \
10
+ && rm -rf /var/lib/apt/lists/*
11
+
12
+ # Copy source code
13
+ COPY . .
14
+
15
+ # Build the application
16
+ RUN cargo build --release
17
+
18
+ # --- Runtime Stage ---
19
+ FROM python:3.10-slim-bookworm
20
+
21
+ WORKDIR /app
22
+
23
+ # Install runtime dependencies
24
+ RUN apt-get update && apt-get install -y \
25
+ curl \
26
+ ca-certificates \
27
+ libssl3 \
28
+ && rm -rf /var/lib/apt/lists/*
29
+
30
+ # Create a non-root user for Hugging Face Spaces
31
+ RUN useradd -m -u 1000 user
32
+ USER user
33
+ ENV HOME=/home/user \
34
+ PATH=/home/user/.local/bin:$PATH
35
+
36
+ # Set up directories
37
+ WORKDIR /home/user/app
38
+
39
+ # Copy Rust binary
40
+ COPY --from=builder /app/target/release/intent-forge-v2 /home/user/app/intentforge
41
+
42
+ # Copy Python microservice
43
+ COPY services/query_layer /home/user/app/services/query_layer
44
+
45
+ # Install Python dependencies
46
+ RUN pip install --no-cache-dir -r /home/user/app/services/query_layer/requirements.txt
47
+
48
+ # Copy configuration files
49
+ COPY config.yaml sources.yaml /home/user/app/
50
+
51
+ # Download models (Optional: You can also download these during startup)
52
+ # For now, we assume models are either in the repo or downloaded via script
53
+ # RUN python /home/user/app/scripts/export_model.py
54
+
55
+ # Create entrypoint script
56
+ USER root
57
+ RUN echo '#!/bin/bash\n\
58
+ # Start Python Query Layer in background\n\
59
+ cd /home/user/app/services/query_layer && python -m uvicorn app.main:app --host 0.0.0.0 --port 8000 &\n\
60
+ \n\
61
+ # Start Rust Core (Binding to 7860 for HF Spaces)\n\
62
+ export API_PORT=7860\n\
63
+ cd /home/user/app && ./intentforge\n\
64
+ ' > /entrypoint.sh && chmod +x /entrypoint.sh
65
+
66
+ USER user
67
+
68
+ # Hugging Face Spaces use port 7860 by default
69
+ EXPOSE 7860
70
+
71
+ ENTRYPOINT ["/entrypoint.sh"]
config.yaml ADDED
@@ -0,0 +1,162 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # IntentForge v2 Configuration
2
+
3
+ [meilisearch]
4
+ url = "http://localhost:7700"
5
+ master_key = "masterKey"
6
+ index_name = "intentforge"
7
+ # Binary quantization reduces vector size by 8x with minimal accuracy loss
8
+ binary_quantization = true
9
+ # Task timeout for Meilisearch operations (secs)
10
+ task_timeout_secs = 120
11
+ # Hybrid search: 0.7 semantic, 0.3 keyword
12
+ semantic_ratio = 0.7
13
+ # Cache enabled for production
14
+ redis_cache_enabled = true
15
+
16
+ [qdrant]
17
+ url = "http://localhost:6334"
18
+ # api_key = "SET_VIA_ENV"
19
+ collection_name = "intentforge"
20
+
21
+ [redis]
22
+ url = "redis://localhost:6379"
23
+ # Bloom filter false positive rate
24
+ bloom_fp_rate = 0.01
25
+ # SimHash threshold for deduplication
26
+ simhash_threshold = 3
27
+
28
+ [crawler]
29
+ # Requests per second limit
30
+ rate_limit = 10
31
+ # Maximum concurrent fetches
32
+ max_concurrent = 8
33
+ # Request timeout in seconds
34
+ timeout_secs = 30
35
+ # User agent
36
+ user_agent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36 IntentForge/0.1"
37
+ # Respect robots.txt
38
+ respect_robots = true
39
+ # Static-first: try static HTML before JS rendering
40
+ static_first = true
41
+ # Maximum retries for failed requests
42
+ max_retries = 3
43
+ # Robots.txt cache TTL in seconds
44
+ robots_cache_ttl_secs = 3600
45
+ # Domains that require JS rendering (comma-separated in TOML array)
46
+ js_whitelist = ["producthunt.com", "news.ycombinator.com"]
47
+
48
+ [indexer]
49
+ # Batch size for ONNX inference
50
+ inference_batch_size = 32
51
+ # Minimum content length to index
52
+ min_content_length = 100
53
+ # Snippet length for search results
54
+ snippet_length = 200
55
+
56
+ [trending]
57
+ # Refresh interval in seconds
58
+ refresh_interval = 300
59
+ # Number of top items to track per category
60
+ top_n = 50
61
+
62
+ [discovery]
63
+ # Interval in seconds between discovery cycles (adaptive: 30s-3600s based on queue size)
64
+ interval_secs = 300
65
+ # Maximum size of the crawl queue before pausing discovery
66
+ max_queue_size = 50000
67
+ # Whether to extract and follow outbound links
68
+ follow_links = true
69
+ # Minimum intent score threshold for following links
70
+ link_threshold = 0.6
71
+
72
+ [discovery.common_crawl_delta]
73
+ # Enable monthly Common Crawl delta ingestion
74
+ enabled = true
75
+ # Interval in seconds (default: 30 days)
76
+ interval_secs = 2592000
77
+ # Crawl ID to use (empty = fallback to default)
78
+ crawl_id = "CC-MAIN-2025-08"
79
+ # Domains to discover from Common Crawl
80
+ domains = ["github.com", "arxiv.org", "news.ycombinator.com", "stackoverflow.com", "medium.com", "dev.to"]
81
+ # Max CDX entries to query per domain
82
+ max_entries_per_domain = 100
83
+ # Directory for persistent state (mount as volume in Docker: cc_data:/app/cc_data)
84
+ data_dir = "./cc_data"
85
+ # Minimum quality score to enqueue (0.0-1.0)
86
+ quality_threshold = 0.3
87
+
88
+ [video_discovery]
89
+ ytdlp_path = "/usr/local/bin/yt-dlp"
90
+ ytdlp_update_interval_hours = 24
91
+ enabled_sources = ["youtube_unified", "archive_org"]
92
+ search_limit = 15
93
+ cache_ttl_secs = 3600
94
+ piped_instances = []
95
+ invidious_instances = []
96
+ youtube_api_key = "SET_VIA_ENV"
97
+ rapidapi_key = "SET_VIA_ENV"
98
+
99
+ [logging]
100
+ level = "info"
101
+ format = "json"
102
+
103
+ [extraction]
104
+ # Trafilatura microservice URL
105
+ trafilatura_url = "http://localhost:8080"
106
+ # Batch size for extraction
107
+ batch_size = 16
108
+ # Extraction timeout in seconds
109
+ timeout_secs = 60
110
+
111
+ [inference]
112
+ # Path to ONNX model
113
+ model_path = "models/all-MiniLM-L6-v2.onnx"
114
+ # Batch size for inference
115
+ inference_batch_size = 32
116
+ # Embedding dimension
117
+ embedding_dim = 384
118
+ # Maximum sequence length for tokenizer
119
+ max_seq_length = 128
120
+
121
+ [anti_detection]
122
+ # Enable header rotation with TLS alignment
123
+ enabled = true
124
+ # Rotate user agent every N requests
125
+ rotation_interval = 10
126
+ # Use Sec-CH-UA client hints (Chrome-like headers)
127
+ use_client_hints = true
128
+ # Invidious instances for YouTube (fallback order)
129
+ invidious_instances = ["https://invidious.nerdvpn.de", "https://inv.tux.pizza", "https://yewtu.be"]
130
+ # StackExchange API key (optional, increases quota from 300 to 10k/day)
131
+ # stackoverflow_api_key = "YOUR_KEY_HERE"
132
+ # PubMed API key (optional, increases rate limit)
133
+ # pubmed_api_key = "YOUR_KEY_HERE"
134
+ # Semantic Scholar API key (optional)
135
+ # semantic_scholar_api_key = "YOUR_KEY_HERE"
136
+
137
+ [self_improvement]
138
+ # Enable self-improvement via in-process meta-search
139
+ enabled = true
140
+ # Minimum gap score - queries with avg relevance below this trigger gap filling
141
+ min_gap_score = 0.5
142
+ # Max results to fetch from external API per gap query (increased for faster live-fill)
143
+ max_results_per_query = 20
144
+ # Interval between gap processing cycles (in seconds)
145
+ process_interval_secs = 300
146
+ # Synchronous discovery target
147
+ min_urls_per_gap = 15
148
+ # Maximum rounds to try in synchronous discovery
149
+ max_search_rounds = 5
150
+ # Concurrent tasks for background processing
151
+ max_parallel_gaps = 3
152
+
153
+ [image_search]
154
+ # External image search API keys (set via env vars or here)
155
+ # Pixabay: 100 req/60s free tier
156
+ # pixabay_api_key = "YOUR_PIXABAY_KEY"
157
+ # Pexels: 200 req/hour (20k/month) free tier
158
+ # pexels_api_key = "YOUR_PEXELS_KEY"
159
+ # Max results per provider per query
160
+ search_limit = 20
161
+ # Cache TTL in seconds (Pixabay requires 24h minimum)
162
+ cache_ttl_secs = 86400
models/all-MiniLM-L6-v2.onnx ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:8a8fbfb32594ebf754ec35cc5c60d4b35fd863199c2cafd09edbb7faf6340a80
3
+ size 90362391
models/config.json ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "BertModel"
4
+ ],
5
+ "attention_probs_dropout_prob": 0.1,
6
+ "classifier_dropout": null,
7
+ "gradient_checkpointing": false,
8
+ "hidden_act": "gelu",
9
+ "hidden_dropout_prob": 0.1,
10
+ "hidden_size": 384,
11
+ "initializer_range": 0.02,
12
+ "intermediate_size": 1536,
13
+ "layer_norm_eps": 1e-12,
14
+ "max_position_embeddings": 512,
15
+ "model_type": "bert",
16
+ "num_attention_heads": 12,
17
+ "num_hidden_layers": 6,
18
+ "pad_token_id": 0,
19
+ "position_embedding_type": "absolute",
20
+ "transformers_version": "4.57.6",
21
+ "type_vocab_size": 2,
22
+ "use_cache": true,
23
+ "vocab_size": 30522
24
+ }
models/rerank-MiniLM-L6-v2.onnx ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:68a31e3ebc1c6143761531709c43d145512ad3b3fc2c3d18c6f65f256bde9c4d
3
+ size 90964641
models/special_tokens_map.json ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cls_token": {
3
+ "content": "[CLS]",
4
+ "lstrip": false,
5
+ "normalized": false,
6
+ "rstrip": false,
7
+ "single_word": false
8
+ },
9
+ "mask_token": {
10
+ "content": "[MASK]",
11
+ "lstrip": false,
12
+ "normalized": false,
13
+ "rstrip": false,
14
+ "single_word": false
15
+ },
16
+ "pad_token": {
17
+ "content": "[PAD]",
18
+ "lstrip": false,
19
+ "normalized": false,
20
+ "rstrip": false,
21
+ "single_word": false
22
+ },
23
+ "sep_token": {
24
+ "content": "[SEP]",
25
+ "lstrip": false,
26
+ "normalized": false,
27
+ "rstrip": false,
28
+ "single_word": false
29
+ },
30
+ "unk_token": {
31
+ "content": "[UNK]",
32
+ "lstrip": false,
33
+ "normalized": false,
34
+ "rstrip": false,
35
+ "single_word": false
36
+ }
37
+ }
models/tokenizer.json ADDED
The diff for this file is too large to render. See raw diff
 
models/tokenizer_config.json ADDED
@@ -0,0 +1,65 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "added_tokens_decoder": {
3
+ "0": {
4
+ "content": "[PAD]",
5
+ "lstrip": false,
6
+ "normalized": false,
7
+ "rstrip": false,
8
+ "single_word": false,
9
+ "special": true
10
+ },
11
+ "100": {
12
+ "content": "[UNK]",
13
+ "lstrip": false,
14
+ "normalized": false,
15
+ "rstrip": false,
16
+ "single_word": false,
17
+ "special": true
18
+ },
19
+ "101": {
20
+ "content": "[CLS]",
21
+ "lstrip": false,
22
+ "normalized": false,
23
+ "rstrip": false,
24
+ "single_word": false,
25
+ "special": true
26
+ },
27
+ "102": {
28
+ "content": "[SEP]",
29
+ "lstrip": false,
30
+ "normalized": false,
31
+ "rstrip": false,
32
+ "single_word": false,
33
+ "special": true
34
+ },
35
+ "103": {
36
+ "content": "[MASK]",
37
+ "lstrip": false,
38
+ "normalized": false,
39
+ "rstrip": false,
40
+ "single_word": false,
41
+ "special": true
42
+ }
43
+ },
44
+ "clean_up_tokenization_spaces": false,
45
+ "cls_token": "[CLS]",
46
+ "do_basic_tokenize": true,
47
+ "do_lower_case": true,
48
+ "extra_special_tokens": {},
49
+ "mask_token": "[MASK]",
50
+ "max_length": 128,
51
+ "model_max_length": 512,
52
+ "never_split": null,
53
+ "pad_to_multiple_of": null,
54
+ "pad_token": "[PAD]",
55
+ "pad_token_type_id": 0,
56
+ "padding_side": "right",
57
+ "sep_token": "[SEP]",
58
+ "stride": 0,
59
+ "strip_accents": null,
60
+ "tokenize_chinese_chars": true,
61
+ "tokenizer_class": "BertTokenizer",
62
+ "truncation_side": "right",
63
+ "truncation_strategy": "longest_first",
64
+ "unk_token": "[UNK]"
65
+ }
models/vocab.txt ADDED
The diff for this file is too large to render. See raw diff
 
services/query_layer/Dockerfile ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM python:3.11-slim
2
+
3
+ WORKDIR /app
4
+
5
+ # Install system dependencies
6
+ RUN apt-get update && apt-get install -y \
7
+ build-essential \
8
+ curl \
9
+ && rm -rf /var/lib/apt/lists/*
10
+
11
+ # Install dependencies directly DONT REDOWNLOAD, the packages are heavy as fuck
12
+ RUN pip install \
13
+ fastapi \
14
+ uvicorn[standard] \
15
+ meilisearch \
16
+ pydantic \
17
+ pydantic-settings \
18
+ onnxruntime \
19
+ numpy \
20
+ transformers \
21
+ torch --extra-index-url https://download.pytorch.org/whl/cpu \
22
+ sentence-transformers \
23
+ redis \
24
+ prometheus-client \
25
+ slowapi \
26
+ scikit-learn \
27
+ nltk \
28
+ aiohttp \
29
+ python-multipart
30
+
31
+ # Copy application code
32
+ COPY app/ /app/app/
33
+
34
+ # Set environment variable
35
+ ENV PYTHONPATH=/app
36
+
37
+ # Expose port
38
+ EXPOSE 8000
39
+
40
+ # Run the unified service
41
+ CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8000"]
services/query_layer/__pycache__/app.cpython-314.pyc ADDED
Binary file (11.7 kB). View file
 
services/query_layer/app/__init__.py ADDED
File without changes
services/query_layer/app/__version__.py ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ """Version information for the intent-engine package."""
2
+
3
+ __version__ = "3.4.2"
4
+ __version_info__ = (3, 1, 0)
5
+ __version_description__ = "Product URL Extraction & Performance Optimization"
services/query_layer/app/config/__init__.py ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Configuration and Cache Modules for Intent Engine
3
+
4
+ This package provides caching and configuration utilities.
5
+ """
6
+
7
+ from app.config.health_checks import (
8
+ HealthCheckService,
9
+ ServiceHealth,
10
+ ServiceType,
11
+ SystemHealth,
12
+ health_checker,
13
+ )
14
+ from app.config.optimized_cache import EmbeddingCache, get_embedding_cache
15
+ from app.config.query_cache import RankingCache, get_ranking_cache
16
+ from app.config.settings import Settings, get_settings, settings
17
+
18
+ __all__ = [
19
+ # Settings
20
+ "Settings",
21
+ "get_settings",
22
+ "settings",
23
+ # Health Checks
24
+ "HealthCheckService",
25
+ "ServiceHealth",
26
+ "ServiceType",
27
+ "SystemHealth",
28
+ "health_checker",
29
+ # Caching
30
+ "EmbeddingCache",
31
+ "get_embedding_cache",
32
+ "RankingCache",
33
+ "get_ranking_cache",
34
+ ]
services/query_layer/app/config/arq_pool.py ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Intent Engine - ARQ Pool Module
3
+
4
+ Provides a shared connection pool for enqueuing background tasks with arq.
5
+ """
6
+
7
+ import asyncio
8
+ import logging
9
+ import os
10
+ from typing import Optional
11
+
12
+ from arq import create_pool
13
+ from arq.connections import ArqRedis, RedisSettings
14
+
15
+ logger = logging.getLogger(__name__)
16
+
17
+ # ARQ connection settings
18
+ REDIS_HOST = os.getenv("REDIS_HOST", "redis")
19
+ REDIS_PORT = int(os.getenv("REDIS_PORT", 6379))
20
+
21
+ _arq_pool: Optional[ArqRedis] = None
22
+ _arq_lock = asyncio.Lock()
23
+
24
+
25
+ async def get_arq_pool() -> ArqRedis:
26
+ """
27
+ Get or create a shared ARQ connection pool.
28
+
29
+ Returns:
30
+ ArqRedis connection pool
31
+ """
32
+ global _arq_pool
33
+ if _arq_pool is None:
34
+ async with _arq_lock:
35
+ if _arq_pool is None:
36
+ try:
37
+ logger.info(f"Creating ARQ pool: {REDIS_HOST}:{REDIS_PORT}")
38
+ _arq_pool = await create_pool(RedisSettings(host=REDIS_HOST, port=REDIS_PORT))
39
+ logger.info("ARQ pool created successfully")
40
+ except Exception as e:
41
+ logger.error(f"Failed to create ARQ pool: {e}")
42
+ raise
43
+ return _arq_pool
44
+
45
+
46
+ async def close_arq_pool():
47
+ """Close the shared ARQ connection pool"""
48
+ global _arq_pool
49
+ if _arq_pool is not None:
50
+ async with _arq_lock:
51
+ if _arq_pool is not None:
52
+ await _arq_pool.close()
53
+ _arq_pool = None
54
+ logger.info("ARQ pool closed")
services/query_layer/app/config/health_checks.py ADDED
@@ -0,0 +1,710 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Comprehensive Health Check Service for Intent Engine.
3
+
4
+ This module provides authoritative health checks for all services and dependencies,
5
+ with proper readiness and liveness probes.
6
+
7
+ Usage:
8
+ from app.config.health_checks import HealthCheckService
9
+
10
+ checker = HealthCheckService()
11
+ status = await checker.check_all()
12
+ """
13
+
14
+ import asyncio
15
+ import logging
16
+ import os
17
+ import time
18
+ from dataclasses import dataclass, field
19
+ from datetime import UTC, datetime
20
+ from enum import StrEnum
21
+ from typing import Any
22
+
23
+ import aiohttp
24
+
25
+ logger = logging.getLogger(__name__)
26
+
27
+
28
+ class HealthStatus(StrEnum):
29
+ """Health status levels."""
30
+
31
+ HEALTHY = "healthy"
32
+ DEGRADED = "degraded"
33
+ UNHEALTHY = "unhealthy"
34
+
35
+
36
+ class ServiceType(StrEnum):
37
+ """Service types for health checks."""
38
+
39
+ DATABASE = "database"
40
+ REDIS = "redis"
41
+ SEARXNG = "searxng"
42
+ GO_CRAWLER = "go_crawler"
43
+ GO_INDEXER = "go_indexer"
44
+ GO_SEARCH_API = "go_search_api"
45
+ UNIFIED_SEARCH = "unified_search"
46
+ QDRANT = "qdrant"
47
+ MODELS = "models"
48
+ CACHE = "cache"
49
+
50
+
51
+ @dataclass
52
+ class ServiceHealth:
53
+ """Health status for a single service."""
54
+
55
+ service: ServiceType
56
+ status: HealthStatus
57
+ response_time_ms: float | None = None
58
+ error: str | None = None
59
+ details: dict[str, Any] = field(default_factory=dict)
60
+ timestamp: datetime = field(default_factory=lambda: datetime.now(UTC))
61
+
62
+ def to_dict(self) -> dict[str, Any]:
63
+ """Convert to dictionary for API response."""
64
+ return {
65
+ "service": self.service.value,
66
+ "status": self.status.value,
67
+ "response_time_ms": self.response_time_ms,
68
+ "error": self.error,
69
+ "details": self.details,
70
+ "timestamp": self.timestamp.isoformat(),
71
+ }
72
+
73
+
74
+ @dataclass
75
+ class SystemHealth:
76
+ """Overall system health status."""
77
+
78
+ status: HealthStatus
79
+ timestamp: datetime
80
+ services: dict[ServiceType, ServiceHealth]
81
+ version: str
82
+ environment: str
83
+ uptime_seconds: float
84
+
85
+ def to_dict(self) -> dict[str, Any]:
86
+ """Convert to dictionary for API response."""
87
+ return {
88
+ "status": self.status.value,
89
+ "timestamp": self.timestamp.isoformat(),
90
+ "services": {
91
+ service.value: health.to_dict()
92
+ for service, health in self.services.items()
93
+ },
94
+ "version": self.version,
95
+ "environment": self.environment,
96
+ "uptime_seconds": self.uptime_seconds,
97
+ }
98
+
99
+
100
+ class HealthCheckService:
101
+ """
102
+ Centralized health check service for Intent Engine.
103
+
104
+ Provides authoritative health checks for all services with:
105
+ - Liveness probes (is the service running?)
106
+ - Readiness probes (is the service ready to accept traffic?)
107
+ - Detailed error reporting
108
+ - Response time metrics
109
+ """
110
+
111
+ START_TIME = time.time()
112
+
113
+ def __init__(
114
+ self,
115
+ database_url: str | None = None,
116
+ redis_url: str | None = None,
117
+ searxng_url: str | None = None,
118
+ go_crawler_url: str | None = None,
119
+ go_indexer_url: str | None = None,
120
+ go_search_api_url: str | None = None,
121
+ unified_search_url: str | None = None,
122
+ qdrant_url: str | None = None,
123
+ ):
124
+ """Initialize health check service with service URLs."""
125
+ import os
126
+
127
+ self.database_url = database_url or os.getenv("DATABASE_URL")
128
+ self.redis_url = redis_url or os.getenv("REDIS_URL")
129
+ self.searxng_url = searxng_url or os.getenv(
130
+ "SEARXNG_BASE_URL", "http://searxng:8080"
131
+ )
132
+ self.go_crawler_url = go_crawler_url or os.getenv(
133
+ "GO_CRAWLER_URL", "http://go-crawler:8080"
134
+ )
135
+ self.go_indexer_url = go_indexer_url or os.getenv(
136
+ "GO_INDEXER_URL", "http://go-indexer:8080"
137
+ )
138
+ self.go_search_api_url = go_search_api_url or os.getenv(
139
+ "GO_SEARCH_API_URL", "http://go-search-api:8080"
140
+ )
141
+ self.unified_search_url = unified_search_url or os.getenv(
142
+ "UNIFIED_SEARCH_URL", "http://unified-search-api:8082"
143
+ )
144
+ qdrant_host = os.getenv("QDRANT_HOST", "qdrant")
145
+ qdrant_port = os.getenv("QDRANT_PORT", "6333")
146
+ self.qdrant_url = qdrant_url or f"http://{qdrant_host}:{qdrant_port}"
147
+
148
+ self._models_loaded = False
149
+ self._model_load_start = time.time()
150
+ self._model_load_timeout = 120 # 2 minutes
151
+
152
+ def mark_models_loaded(self) -> None:
153
+ """Mark models as loaded."""
154
+ self._models_loaded = True
155
+ load_time = time.time() - self._model_load_start
156
+ logger.info(f"Models loaded in {load_time:.2f}s")
157
+
158
+ def _get_uptime(self) -> float:
159
+ """Get system uptime in seconds."""
160
+ return time.time() - self.START_TIME
161
+
162
+ async def check_database(self) -> ServiceHealth:
163
+ """Check database connectivity using synchronous driver."""
164
+ start = time.time()
165
+ try:
166
+ if not self.database_url:
167
+ return ServiceHealth(
168
+ service=ServiceType.DATABASE,
169
+ status=HealthStatus.UNHEALTHY,
170
+ error="DATABASE_URL not configured",
171
+ )
172
+
173
+ # Run synchronous database check in a thread to avoid blocking
174
+ def _check():
175
+ from sqlalchemy import create_engine, text
176
+
177
+ # Use a very short timeout for health checks
178
+ # If it's a postgres URL, ensure we don't try to use asyncpg here
179
+ url = self.database_url
180
+ if url.startswith("postgresql+asyncpg://"):
181
+ url = url.replace("postgresql+asyncpg://", "postgresql://")
182
+
183
+ # connect_timeout is supported by psycopg2 but not sqlite3
184
+ connect_args = {}
185
+ if "postgresql" in url:
186
+ connect_args["connect_timeout"] = 5
187
+
188
+ engine = create_engine(url, connect_args=connect_args)
189
+ with engine.connect() as conn:
190
+ conn.execute(text("SELECT 1"))
191
+ engine.dispose()
192
+ return True
193
+
194
+ await asyncio.get_event_loop().run_in_executor(None, _check)
195
+ response_time = (time.time() - start) * 1000
196
+
197
+ return ServiceHealth(
198
+ service=ServiceType.DATABASE,
199
+ status=HealthStatus.HEALTHY,
200
+ response_time_ms=round(response_time, 2),
201
+ details={
202
+ "url": self._sanitize_url(self.database_url),
203
+ "driver": "sync",
204
+ },
205
+ )
206
+ except Exception as e:
207
+ response_time = (time.time() - start) * 1000
208
+ logger.error(f"Database health check failed: {e}")
209
+ return ServiceHealth(
210
+ service=ServiceType.DATABASE,
211
+ status=HealthStatus.UNHEALTHY,
212
+ response_time_ms=round(response_time, 2),
213
+ error=str(e),
214
+ )
215
+
216
+ async def check_redis(self) -> ServiceHealth:
217
+ """Check Redis connectivity."""
218
+ start = time.time()
219
+ try:
220
+ if not self.redis_url:
221
+ return ServiceHealth(
222
+ service=ServiceType.REDIS,
223
+ status=HealthStatus.HEALTHY,
224
+ details={"status": "not configured"},
225
+ )
226
+
227
+ import redis.asyncio as redis
228
+
229
+ client = redis.from_url(self.redis_url, socket_timeout=5)
230
+ await client.ping()
231
+
232
+ # Get Redis info
233
+ info = await client.info("server")
234
+ redis_version = info.get("redis_version", "unknown")
235
+
236
+ response_time = (time.time() - start) * 1000
237
+ await client.close()
238
+
239
+ return ServiceHealth(
240
+ service=ServiceType.REDIS,
241
+ status=HealthStatus.HEALTHY,
242
+ response_time_ms=round(response_time, 2),
243
+ details={
244
+ "version": redis_version,
245
+ "url": self._sanitize_url(self.redis_url),
246
+ },
247
+ )
248
+ except Exception as e:
249
+ response_time = (time.time() - start) * 1000
250
+ logger.warning(f"Redis health check failed: {e}")
251
+ return ServiceHealth(
252
+ service=ServiceType.REDIS,
253
+ status=HealthStatus.UNHEALTHY,
254
+ response_time_ms=round(response_time, 2),
255
+ error=str(e),
256
+ )
257
+
258
+ async def check_searxng(self) -> ServiceHealth:
259
+ """
260
+ Check SearXNG connectivity with authoritative health check.
261
+
262
+ Uses the /healthz endpoint and validates response.
263
+ Handles both JSON and HTML/text responses.
264
+ """
265
+ start = time.time()
266
+ try:
267
+ timeout = aiohttp.ClientTimeout(total=5)
268
+ async with aiohttp.ClientSession(timeout=timeout) as session:
269
+ # Try health endpoint
270
+ url = f"{self.searxng_url.rstrip('/')}/healthz"
271
+ async with session.get(url) as response:
272
+ response_time = (time.time() - start) * 1000
273
+
274
+ if response.status == 200:
275
+ content_type = response.headers.get("Content-Type", "")
276
+ details = {"url": url, "content_type": content_type}
277
+
278
+ # Handle plain text response (like "OK")
279
+ if "text/plain" in content_type:
280
+ text = await response.text()
281
+ details["response"] = text.strip()
282
+ return ServiceHealth(
283
+ service=ServiceType.SEARXNG,
284
+ status=HealthStatus.HEALTHY,
285
+ response_time_ms=round(response_time, 2),
286
+ details=details,
287
+ )
288
+ if "application/json" in content_type:
289
+ try:
290
+ details["response"] = await response.json()
291
+ except Exception:
292
+ details["response_text"] = await response.text()
293
+ else:
294
+ # If it's HTML but status is 200, we consider it healthy
295
+ details["note"] = "Received HTML response, status OK"
296
+ # Limit text to avoid bloating health check
297
+ text = await response.text()
298
+ details["response_preview"] = (
299
+ text[:100] + "..." if len(text) > 100 else text
300
+ )
301
+
302
+ return ServiceHealth(
303
+ service=ServiceType.SEARXNG,
304
+ status=HealthStatus.HEALTHY,
305
+ response_time_ms=round(response_time, 2),
306
+ details=details,
307
+ )
308
+ # Try alternative endpoint
309
+ async with session.get(
310
+ f"{self.searxng_url.rstrip('/')}/stats"
311
+ ) as alt_response:
312
+ if alt_response.status == 200:
313
+ response_time = (time.time() - start) * 1000
314
+ return ServiceHealth(
315
+ service=ServiceType.SEARXNG,
316
+ status=HealthStatus.HEALTHY,
317
+ response_time_ms=round(response_time, 2),
318
+ details={
319
+ "url": f"{self.searxng_url}/stats",
320
+ "fallback": True,
321
+ },
322
+ )
323
+
324
+ raise Exception(f"Status {response.status}")
325
+
326
+ except (TimeoutError, aiohttp.ClientConnectorError) as e:
327
+ response_time = (time.time() - start) * 1000
328
+ logger.warning(f"SearXNG health check failed (Connection Error): {e}")
329
+ return ServiceHealth(
330
+ service=ServiceType.SEARXNG,
331
+ status=HealthStatus.UNHEALTHY,
332
+ response_time_ms=round(response_time, 2),
333
+ error=f"Connection failed: {type(e).__name__}",
334
+ details={"url": self.searxng_url},
335
+ )
336
+ except Exception as e:
337
+ response_time = (time.time() - start) * 1000
338
+ logger.warning(f"SearXNG health check failed: {e}")
339
+ return ServiceHealth(
340
+ service=ServiceType.SEARXNG,
341
+ status=HealthStatus.UNHEALTHY,
342
+ response_time_ms=round(response_time, 2),
343
+ error=str(e),
344
+ details={"url": self.searxng_url},
345
+ )
346
+
347
+ async def check_go_crawler(self) -> ServiceHealth:
348
+ """
349
+ Check Go Crawler service status.
350
+
351
+ The Go crawler is a worker-only process and doesn't have a built-in health endpoint.
352
+ We mark it as HEALTHY if we can't connect but know it's a worker-only service,
353
+ or we can check if it's running via other means if needed.
354
+ """
355
+ # For now, we assume it's running if we're in the same network
356
+ # or we just report it as a background worker.
357
+ return ServiceHealth(
358
+ service=ServiceType.GO_CRAWLER,
359
+ status=HealthStatus.HEALTHY,
360
+ details={
361
+ "type": "background_worker",
362
+ "note": "No HTTP endpoint (worker-only process)",
363
+ "url": self.go_crawler_url,
364
+ },
365
+ )
366
+
367
+ async def check_go_indexer(self) -> ServiceHealth:
368
+ """
369
+ Check Go Indexer service status.
370
+
371
+ The Go indexer is a worker-only process and doesn't have a built-in health endpoint.
372
+ """
373
+ return ServiceHealth(
374
+ service=ServiceType.GO_INDEXER,
375
+ status=HealthStatus.HEALTHY,
376
+ details={
377
+ "type": "background_worker",
378
+ "note": "No HTTP endpoint (worker-only process)",
379
+ "url": self.go_indexer_url,
380
+ },
381
+ )
382
+
383
+ async def check_go_search_api(self) -> ServiceHealth:
384
+ """Check Go Search API health."""
385
+ start = time.time()
386
+
387
+ # Check if Go services are enabled
388
+ if os.getenv("ENABLE_GO_SERVICES", "false").lower() != "true":
389
+ return ServiceHealth(
390
+ service=ServiceType.GO_SEARCH_API,
391
+ status=HealthStatus.HEALTHY,
392
+ details={
393
+ "status": "not_enabled",
394
+ "note": "Set ENABLE_GO_SERVICES=true to enable",
395
+ },
396
+ )
397
+
398
+ try:
399
+ timeout = aiohttp.ClientTimeout(total=5)
400
+ async with aiohttp.ClientSession(timeout=timeout) as session:
401
+ url = f"{self.go_search_api_url.rstrip('/')}/health"
402
+ async with session.get(url) as response:
403
+ response_time = (time.time() - start) * 1000
404
+
405
+ if response.status == 200:
406
+ data = await response.json()
407
+ return ServiceHealth(
408
+ service=ServiceType.GO_SEARCH_API,
409
+ status=HealthStatus.HEALTHY,
410
+ response_time_ms=round(response_time, 2),
411
+ details={"url": url, "response": data},
412
+ )
413
+ raise Exception(f"Status {response.status}")
414
+
415
+ except TimeoutError:
416
+ response_time = (time.time() - start) * 1000
417
+ logger.warning("Go Search API health check timeout")
418
+ return ServiceHealth(
419
+ service=ServiceType.GO_SEARCH_API,
420
+ status=HealthStatus.UNHEALTHY,
421
+ response_time_ms=round(response_time, 2),
422
+ error="Connection timeout",
423
+ )
424
+ except Exception as e:
425
+ response_time = (time.time() - start) * 1000
426
+ logger.warning(f"Go Search API health check failed: {e}")
427
+ return ServiceHealth(
428
+ service=ServiceType.GO_SEARCH_API,
429
+ status=HealthStatus.UNHEALTHY,
430
+ response_time_ms=round(response_time, 2),
431
+ error=str(e),
432
+ details={"url": self.go_search_api_url},
433
+ )
434
+
435
+ async def check_unified_search(self) -> ServiceHealth:
436
+ """Check Unified Search API health."""
437
+ start = time.time()
438
+
439
+ # Check if Go services are enabled
440
+ if os.getenv("ENABLE_GO_SERVICES", "false").lower() != "true":
441
+ return ServiceHealth(
442
+ service=ServiceType.UNIFIED_SEARCH,
443
+ status=HealthStatus.HEALTHY,
444
+ details={
445
+ "status": "not_enabled",
446
+ "note": "Set ENABLE_GO_SERVICES=true to enable",
447
+ },
448
+ )
449
+
450
+ try:
451
+ timeout = aiohttp.ClientTimeout(total=5)
452
+ async with aiohttp.ClientSession(timeout=timeout) as session:
453
+ url = f"{self.unified_search_url.rstrip('/')}/health"
454
+ async with session.get(url) as response:
455
+ response_time = (time.time() - start) * 1000
456
+
457
+ if response.status == 200:
458
+ return ServiceHealth(
459
+ service=ServiceType.UNIFIED_SEARCH,
460
+ status=HealthStatus.HEALTHY,
461
+ response_time_ms=round(response_time, 2),
462
+ details={"url": url},
463
+ )
464
+ raise Exception(f"Status {response.status}")
465
+
466
+ except TimeoutError:
467
+ response_time = (time.time() - start) * 1000
468
+ logger.warning("Unified Search health check timeout")
469
+ return ServiceHealth(
470
+ service=ServiceType.UNIFIED_SEARCH,
471
+ status=HealthStatus.UNHEALTHY,
472
+ response_time_ms=round(response_time, 2),
473
+ error="Connection timeout",
474
+ )
475
+ except Exception as e:
476
+ response_time = (time.time() - start) * 1000
477
+ logger.warning(f"Unified Search health check failed: {e}")
478
+ return ServiceHealth(
479
+ service=ServiceType.UNIFIED_SEARCH,
480
+ status=HealthStatus.UNHEALTHY,
481
+ response_time_ms=round(response_time, 2),
482
+ error=str(e),
483
+ details={"url": self.unified_search_url},
484
+ )
485
+
486
+ async def check_qdrant(self) -> ServiceHealth:
487
+ """Check Qdrant vector database health."""
488
+ start = time.time()
489
+
490
+ # Check if Qdrant is enabled
491
+ if os.getenv("ENABLE_QDRANT", "false").lower() != "true":
492
+ return ServiceHealth(
493
+ service=ServiceType.QDRANT,
494
+ status=HealthStatus.HEALTHY,
495
+ details={
496
+ "status": "not_enabled",
497
+ "note": "Set ENABLE_QDRANT=true to enable",
498
+ },
499
+ )
500
+
501
+ try:
502
+ timeout = aiohttp.ClientTimeout(total=5)
503
+ async with aiohttp.ClientSession(timeout=timeout) as session:
504
+ # Try root endpoint first (most reliable across versions)
505
+ url = f"{self.qdrant_url.rstrip('/')}/"
506
+ async with session.get(url) as response:
507
+ response_time = (time.time() - start) * 1000
508
+
509
+ if response.status == 200:
510
+ data = await response.json()
511
+ return ServiceHealth(
512
+ service=ServiceType.QDRANT,
513
+ status=HealthStatus.HEALTHY,
514
+ response_time_ms=round(response_time, 2),
515
+ details={
516
+ "url": url,
517
+ "version": data.get("version", "unknown"),
518
+ },
519
+ )
520
+ raise Exception(f"Status {response.status}")
521
+
522
+ except TimeoutError:
523
+ response_time = (time.time() - start) * 1000
524
+ logger.warning("Qdrant health check timeout")
525
+ return ServiceHealth(
526
+ service=ServiceType.QDRANT,
527
+ status=HealthStatus.UNHEALTHY,
528
+ response_time_ms=round(response_time, 2),
529
+ error="Connection timeout",
530
+ )
531
+ except Exception as e:
532
+ response_time = (time.time() - start) * 1000
533
+ logger.warning(f"Qdrant health check failed: {e}")
534
+ return ServiceHealth(
535
+ service=ServiceType.QDRANT,
536
+ status=HealthStatus.UNHEALTHY,
537
+ response_time_ms=round(response_time, 2),
538
+ error=str(e),
539
+ details={"url": self.qdrant_url},
540
+ )
541
+
542
+ def check_models(self) -> ServiceHealth:
543
+ """Check if ML models are loaded."""
544
+ try:
545
+ # Check if models directory exists and has files
546
+ import os
547
+ from pathlib import Path
548
+
549
+ model_cache = Path(os.getenv("MODEL_CACHE_DIR", "./model_cache"))
550
+ models_loaded = model_cache.exists() and any(model_cache.iterdir())
551
+
552
+ if models_loaded or self._models_loaded:
553
+ load_time = time.time() - self._model_load_start
554
+ return ServiceHealth(
555
+ service=ServiceType.MODELS,
556
+ status=HealthStatus.HEALTHY,
557
+ response_time_ms=round(load_time * 1000, 2),
558
+ details={
559
+ "loaded": True,
560
+ "cache_dir": str(model_cache),
561
+ "load_time_seconds": round(load_time, 2),
562
+ },
563
+ )
564
+ # Models not loaded yet, but that's OK during startup
565
+ return ServiceHealth(
566
+ service=ServiceType.MODELS,
567
+ status=HealthStatus.HEALTHY,
568
+ details={
569
+ "loaded": False,
570
+ "note": "Models not yet loaded (normal during startup)",
571
+ "cache_dir": str(model_cache),
572
+ },
573
+ )
574
+ except Exception as e:
575
+ logger.warning(f"Model check failed: {e}")
576
+ return ServiceHealth(
577
+ service=ServiceType.MODELS,
578
+ status=HealthStatus.DEGRADED,
579
+ error=str(e),
580
+ )
581
+
582
+ def _sanitize_url(self, url: str) -> str:
583
+ """Sanitize URL for logging (remove passwords)."""
584
+ import re
585
+
586
+ # Remove password from URL
587
+ return re.sub(r"://[^:]+:[^@]+@", "://***:***@", url)
588
+
589
+ async def check_all(self, include_optional: bool = True) -> SystemHealth:
590
+ """
591
+ Run comprehensive health checks on all services.
592
+
593
+ Args:
594
+ include_optional: Include optional services (SearXNG, Go services, Qdrant)
595
+
596
+ Returns:
597
+ SystemHealth object with status of all services
598
+ """
599
+ import os
600
+
601
+ # Use individual awaitable tasks
602
+ tasks = [
603
+ self.check_database(),
604
+ self.check_redis(),
605
+ ]
606
+
607
+ if include_optional:
608
+ tasks.extend(
609
+ [
610
+ self.check_searxng(),
611
+ self.check_go_crawler(),
612
+ self.check_go_indexer(),
613
+ self.check_go_search_api(),
614
+ self.check_unified_search(),
615
+ self.check_qdrant(),
616
+ ]
617
+ )
618
+
619
+ # Execute all async health checks
620
+ results = await asyncio.gather(*tasks, return_exceptions=True)
621
+
622
+ # Process results
623
+ services: dict[ServiceType, ServiceHealth] = {}
624
+ for result in results:
625
+ if isinstance(result, ServiceHealth):
626
+ services[result.service] = result
627
+ elif isinstance(result, Exception):
628
+ logger.error(f"Health check task failed: {result}")
629
+
630
+ # Add models check (synchronous but wrapped in executor for consistency if needed,
631
+ # or just run it directly as it's fast)
632
+ services[ServiceType.MODELS] = self.check_models()
633
+
634
+ # Determine overall status
635
+ # Only certain services mark the entire system as unhealthy
636
+ critical_services = [ServiceType.DATABASE, ServiceType.REDIS]
637
+
638
+ overall_status = HealthStatus.HEALTHY
639
+
640
+ for service_type, health in services.items():
641
+ if health.status == HealthStatus.UNHEALTHY:
642
+ if service_type in critical_services:
643
+ overall_status = HealthStatus.UNHEALTHY
644
+ break
645
+ overall_status = HealthStatus.DEGRADED
646
+ elif (
647
+ health.status == HealthStatus.DEGRADED
648
+ and overall_status == HealthStatus.HEALTHY
649
+ ):
650
+ overall_status = HealthStatus.DEGRADED
651
+
652
+ # Get version
653
+ try:
654
+ from app.__version__ import __version__
655
+
656
+ version = __version__
657
+ except ImportError:
658
+ version = "unknown"
659
+
660
+ return SystemHealth(
661
+ status=overall_status,
662
+ timestamp=datetime.now(UTC),
663
+ services=services,
664
+ version=version,
665
+ environment=os.getenv("ENVIRONMENT", "development"),
666
+ uptime_seconds=round(self._get_uptime(), 2),
667
+ )
668
+
669
+ async def check_readiness(self) -> bool:
670
+ """
671
+ Check if the service is ready to accept traffic.
672
+
673
+ Returns:
674
+ True if ready, False otherwise
675
+ """
676
+ health = await self.check_all(include_optional=False)
677
+
678
+ # Critical services must be healthy
679
+ critical = [ServiceType.DATABASE, ServiceType.REDIS]
680
+ for service in critical:
681
+ if (
682
+ service in health.services
683
+ and health.services[service].status != HealthStatus.HEALTHY
684
+ ):
685
+ return False
686
+
687
+ # Models should be loaded
688
+ if ServiceType.MODELS in health.services:
689
+ details = health.services[ServiceType.MODELS].details
690
+ if not details.get("loaded", False) and not self._models_loaded:
691
+ # Check if we're still within load timeout
692
+ if time.time() - self._model_load_start > self._model_load_timeout:
693
+ logger.warning("Models not loaded within timeout")
694
+ return False
695
+
696
+ return True
697
+
698
+ async def check_liveness(self) -> bool:
699
+ """
700
+ Check if the service is alive (basic process check).
701
+
702
+ Returns:
703
+ True if alive, False otherwise
704
+ """
705
+ # Simple check - if we can execute this method, we're alive
706
+ return True
707
+
708
+
709
+ # Global health check service instance
710
+ health_checker = HealthCheckService()
services/query_layer/app/config/hybrid_cache.py ADDED
@@ -0,0 +1,370 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Intent Engine - Hybrid Embedding Cache (Redis + Local LRU)
3
+
4
+ This module provides a two-tier caching strategy:
5
+ - L1: Local in-memory LRU cache for ultra-fast access
6
+ - L2: Redis distributed cache for multi-instance deployments
7
+
8
+ Features:
9
+ - Automatic fallback to local cache if Redis unavailable
10
+ - Cache coherence across instances via Redis
11
+ - Configurable TTL for embeddings
12
+ - Batch processing for efficiency
13
+ - Thread-safe operations
14
+ """
15
+
16
+ import hashlib
17
+ import logging
18
+ import os
19
+ import threading
20
+ from typing import Any
21
+
22
+ import numpy as np
23
+
24
+ from app.config.optimized_cache import LRUCache
25
+ from app.config.redis_cache import RedisCache, get_redis_cache
26
+
27
+ logger = logging.getLogger(__name__)
28
+
29
+
30
+ class HybridEmbeddingCache:
31
+ """
32
+ Two-tier embedding cache with Redis + local LRU.
33
+
34
+ Cache lookup order:
35
+ 1. Check local L1 cache (fastest)
36
+ 2. Check Redis L2 cache (distributed)
37
+ 3. Compute embedding and store in both caches
38
+
39
+ Cache invalidation:
40
+ - Writes go to both caches
41
+ - Redis TTL ensures automatic expiration
42
+ - Local cache uses LRU eviction
43
+ """
44
+
45
+ def __init__(
46
+ self,
47
+ model_name: str = "sentence-transformers/all-MiniLM-L6-v2",
48
+ local_capacity: int = 5000,
49
+ redis_ttl: int = 3600, # 1 hour
50
+ use_redis: bool = True,
51
+ ):
52
+ """
53
+ Initialize hybrid cache.
54
+
55
+ Args:
56
+ model_name: Sentence transformer model to use
57
+ local_capacity: Local LRU cache capacity
58
+ redis_ttl: Redis cache TTL in seconds
59
+ use_redis: Whether to use Redis (falls back to local only if False)
60
+ """
61
+ self.model_name = model_name
62
+ self.redis_ttl = redis_ttl
63
+ self.use_redis = (
64
+ use_redis and os.getenv("REDIS_ENABLED", "false").lower() == "true"
65
+ )
66
+
67
+ # L1: Local cache
68
+ self.local_cache = LRUCache(capacity=local_capacity)
69
+
70
+ # L2: Redis cache (optional)
71
+ self.redis_cache: RedisCache | None = None
72
+ if self.use_redis:
73
+ self.redis_cache = get_redis_cache()
74
+ if self.redis_cache is None:
75
+ logger.warning("Redis not available, using local cache only")
76
+ self.use_redis = False
77
+
78
+ # Model
79
+ self.model = None
80
+ self.tokenizer = None
81
+ self.batch_size = 32
82
+ self._load_model()
83
+
84
+ # Stats
85
+ self._lock = threading.Lock()
86
+ self.hits_l1 = 0
87
+ self.hits_l2 = 0
88
+ self.misses = 0
89
+
90
+ logger.info(f"HybridEmbeddingCache initialized (Redis: {self.use_redis})")
91
+
92
+ def _load_model(self) -> None:
93
+ """Load the sentence transformer model."""
94
+ try:
95
+ from sentence_transformers import SentenceTransformer
96
+
97
+ logger.info(f"Loading SentenceTransformer model: {self.model_name}...")
98
+
99
+ self.model = SentenceTransformer(
100
+ self.model_name,
101
+ trust_remote_code=True,
102
+ )
103
+ self.model = self.model.to("cpu")
104
+ self.model.eval()
105
+
106
+ logger.info(
107
+ f"Successfully loaded SentenceTransformer model: {self.model_name}"
108
+ )
109
+ except ImportError as e:
110
+ logger.warning(
111
+ f"SentenceTransformers library not available: {e}. Using mock embeddings."
112
+ )
113
+ self.model = None
114
+ except Exception as e:
115
+ logger.error(
116
+ f"Error loading embedding model {self.model_name}: {e}. Using mock embeddings."
117
+ )
118
+ self.model = None
119
+
120
+ def _get_cache_key(self, text: str) -> str:
121
+ """Generate cache key for text."""
122
+ text_hash = hashlib.md5(text.encode()).hexdigest()
123
+ return f"embedding:{self.model_name}:{text_hash}"
124
+
125
+ def encode_text(self, text: str, use_cache: bool = True) -> np.ndarray | None:
126
+ """
127
+ Encode single text to embedding with two-tier caching.
128
+
129
+ Args:
130
+ text: Text to encode
131
+ use_cache: Whether to use caching
132
+
133
+ Returns:
134
+ Embedding vector or None
135
+ """
136
+ if not text or not text.strip():
137
+ return None
138
+
139
+ # Check L1 cache
140
+ if use_cache:
141
+ cached = self.local_cache.get(text)
142
+ if cached is not None:
143
+ with self._lock:
144
+ self.hits_l1 += 1
145
+ return cached
146
+
147
+ # Check L2 (Redis) cache
148
+ if use_cache and self.use_redis and self.redis_cache:
149
+ cache_key = self._get_cache_key(text)
150
+ cached = self.redis_cache.get(cache_key)
151
+ if cached is not None and isinstance(cached, np.ndarray):
152
+ # Store in L1 for faster next access
153
+ self.local_cache.put(text, cached)
154
+ with self._lock:
155
+ self.hits_l2 += 1
156
+ return cached
157
+
158
+ # Cache miss - compute embedding
159
+ with self._lock:
160
+ self.misses += 1
161
+
162
+ embedding = self._compute_embedding(text)
163
+ if embedding is None:
164
+ return None
165
+
166
+ # Store in both caches
167
+ if use_cache:
168
+ self.local_cache.put(text, embedding)
169
+
170
+ if self.use_redis and self.redis_cache:
171
+ cache_key = self._get_cache_key(text)
172
+ self.redis_cache.set(cache_key, embedding, ttl=self.redis_ttl)
173
+
174
+ return embedding
175
+
176
+ def encode_batch(
177
+ self, texts: list[str], use_cache: bool = True
178
+ ) -> list[np.ndarray]:
179
+ """
180
+ Encode multiple texts with two-tier caching.
181
+
182
+ Args:
183
+ texts: List of texts to encode
184
+ use_cache: Whether to use caching
185
+
186
+ Returns:
187
+ List of embedding vectors
188
+ """
189
+ if not texts:
190
+ return []
191
+
192
+ results: list[np.ndarray | None] = [None] * len(texts)
193
+ texts_to_encode: list[str] = []
194
+ indices_to_encode: list[int] = []
195
+
196
+ # Check caches for all texts
197
+ for i, text in enumerate(texts):
198
+ if not text or not text.strip():
199
+ results[i] = np.random.rand(384).astype(np.float32)
200
+ continue
201
+
202
+ # Check L1 cache
203
+ cached = self.local_cache.get(text)
204
+ if cached is not None:
205
+ results[i] = cached
206
+ with self._lock:
207
+ self.hits_l1 += 1
208
+ continue
209
+
210
+ # Check L2 (Redis) cache
211
+ if use_cache and self.use_redis and self.redis_cache:
212
+ cache_key = self._get_cache_key(text)
213
+ cached = self.redis_cache.get(cache_key)
214
+ if cached is not None and isinstance(cached, np.ndarray):
215
+ self.local_cache.put(text, cached) # Promote to L1
216
+ results[i] = cached
217
+ with self._lock:
218
+ self.hits_l2 += 1
219
+ continue
220
+
221
+ # Need to encode
222
+ texts_to_encode.append(text)
223
+ indices_to_encode.append(i)
224
+
225
+ # Encode remaining texts in batches
226
+ if texts_to_encode and self.model is not None:
227
+ try:
228
+ embeddings = self.model.encode(
229
+ texts_to_encode,
230
+ convert_to_numpy=True,
231
+ normalize_embeddings=True,
232
+ show_progress_bar=False,
233
+ batch_size=self.batch_size,
234
+ )
235
+
236
+ # Store results and cache
237
+ for idx, embedding in zip(indices_to_encode, embeddings, strict=False):
238
+ result = embedding.astype(np.float32)
239
+ results[idx] = result
240
+
241
+ if use_cache:
242
+ text = texts_to_encode[idx]
243
+ self.local_cache.put(text, result)
244
+
245
+ if self.use_redis and self.redis_cache:
246
+ cache_key = self._get_cache_key(text)
247
+ self.redis_cache.set(cache_key, result, ttl=self.redis_ttl)
248
+
249
+ except Exception as e:
250
+ logger.error(f"Error encoding batch: {e}")
251
+ # Fallback to individual encoding
252
+ for idx, text in zip(indices_to_encode, texts_to_encode, strict=False):
253
+ results[idx] = self.encode_text(text, use_cache)
254
+
255
+ # Replace any remaining None placeholders
256
+ for i, result in enumerate(results):
257
+ if result is None:
258
+ results[i] = np.random.rand(384).astype(np.float32)
259
+
260
+ return results
261
+
262
+ def _compute_embedding(self, text: str) -> np.ndarray | None:
263
+ """Compute embedding for text."""
264
+ if self.model is None:
265
+ return np.random.rand(384).astype(np.float32)
266
+
267
+ try:
268
+ embedding = self.model.encode(
269
+ text,
270
+ convert_to_numpy=True,
271
+ normalize_embeddings=True,
272
+ show_progress_bar=False,
273
+ )
274
+ return embedding.astype(np.float32)
275
+ except Exception as e:
276
+ logger.error(f"Error computing embedding: {e}")
277
+ return np.random.rand(384).astype(np.float32)
278
+
279
+ def cosine_similarity(self, vec1: np.ndarray, vec2: np.ndarray) -> float:
280
+ """Calculate cosine similarity between two vectors."""
281
+ if vec1 is None or vec2 is None:
282
+ return 0.0
283
+ dot_product = np.dot(vec1, vec2)
284
+ return float(np.clip(dot_product, -1.0, 1.0))
285
+
286
+ def get_stats(self) -> dict[str, Any]:
287
+ """Get cache statistics."""
288
+ total = self.hits_l1 + self.hits_l2 + self.misses
289
+ hit_rate_l1 = self.hits_l1 / total if total > 0 else 0
290
+ hit_rate_l2 = self.hits_l2 / total if total > 0 else 0
291
+
292
+ stats = {
293
+ "model_name": self.model_name,
294
+ "model_loaded": self.model is not None,
295
+ "use_redis": self.use_redis,
296
+ "local_cache": self.local_cache.get_stats(),
297
+ "hits_l1": self.hits_l1,
298
+ "hits_l2": self.hits_l2,
299
+ "misses": self.misses,
300
+ "hit_rate_l1": round(hit_rate_l1, 3),
301
+ "hit_rate_l2": round(hit_rate_l2, 3),
302
+ "total_requests": total,
303
+ }
304
+
305
+ if self.use_redis and self.redis_cache:
306
+ stats["redis_cache"] = self.redis_cache.get_stats()
307
+
308
+ return stats
309
+
310
+ def clear(self) -> None:
311
+ """Clear both caches."""
312
+ self.local_cache.clear()
313
+
314
+ if self.use_redis and self.redis_cache:
315
+ # Clear only embedding keys
316
+ keys = self.redis_cache.keys("embedding:*")
317
+ if keys:
318
+ self.redis_cache.delete_many(keys)
319
+ logger.info(f"Cleared {len(keys)} embedding keys from Redis")
320
+
321
+ with self._lock:
322
+ self.hits_l1 = 0
323
+ self.hits_l2 = 0
324
+ self.misses = 0
325
+
326
+ logger.info("Hybrid embedding cache cleared")
327
+
328
+
329
+ # Global instance
330
+ _embedding_cache_instance: HybridEmbeddingCache | None = None
331
+ _init_lock = threading.Lock()
332
+
333
+
334
+ def get_embedding_cache(
335
+ model_name: str = "sentence-transformers/all-MiniLM-L6-v2",
336
+ local_capacity: int = 5000,
337
+ redis_ttl: int = 3600,
338
+ ) -> HybridEmbeddingCache:
339
+ """
340
+ Get singleton instance of HybridEmbeddingCache.
341
+
342
+ Args:
343
+ model_name: Model name for initialization
344
+ local_capacity: Local cache capacity
345
+ redis_ttl: Redis TTL in seconds
346
+
347
+ Returns:
348
+ HybridEmbeddingCache instance
349
+ """
350
+ global _embedding_cache_instance
351
+
352
+ if _embedding_cache_instance is None:
353
+ with _init_lock:
354
+ if _embedding_cache_instance is None:
355
+ _embedding_cache_instance = HybridEmbeddingCache(
356
+ model_name=model_name,
357
+ local_capacity=local_capacity,
358
+ redis_ttl=redis_ttl,
359
+ )
360
+
361
+ return _embedding_cache_instance
362
+
363
+
364
+ def clear_embedding_cache() -> None:
365
+ """Clear the global cache instance."""
366
+ global _embedding_cache_instance
367
+ with _init_lock:
368
+ if _embedding_cache_instance is not None:
369
+ _embedding_cache_instance.clear()
370
+ _embedding_cache_instance = None
services/query_layer/app/config/hybrid_query_cache.py ADDED
@@ -0,0 +1,412 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Intent Engine - Hybrid Query Result Cache (Redis + Local LRU)
3
+
4
+ This module provides a two-tier caching strategy for query results:
5
+ - L1: Local in-memory LRU cache for ultra-fast access
6
+ - L2: Redis distributed cache for multi-instance deployments
7
+
8
+ Features:
9
+ - TTL-based expiration
10
+ - Automatic fallback to local cache if Redis unavailable
11
+ - Cache coherence across instances via Redis
12
+ - Separate caches for different operations (intent, ranking, URLs, ads)
13
+ """
14
+
15
+ import hashlib
16
+ import json
17
+ import logging
18
+ import os
19
+ import threading
20
+ import time
21
+ from collections.abc import Callable
22
+ from dataclasses import dataclass
23
+ from functools import wraps
24
+ from typing import Any
25
+
26
+ from app.config.redis_cache import RedisCache
27
+ from app.config.redis_cache import cache as redis_cache_instance
28
+
29
+ logger = logging.getLogger(__name__)
30
+
31
+
32
+ @dataclass
33
+ class CacheEntry:
34
+ """Cache entry with metadata"""
35
+
36
+ value: Any
37
+ created_at: float
38
+ ttl_seconds: float
39
+ access_count: int = 0
40
+ last_accessed: float = 0
41
+
42
+ def is_expired(self) -> bool:
43
+ """Check if entry has expired"""
44
+ return time.time() - self.created_at > self.ttl_seconds
45
+
46
+ def touch(self) -> None:
47
+ """Update access metadata"""
48
+ self.access_count += 1
49
+ self.last_accessed = time.time()
50
+
51
+
52
+ class HybridQueryCache:
53
+ """
54
+ Two-tier query result cache with Redis + local LRU.
55
+
56
+ Cache lookup order:
57
+ 1. Check local L1 cache (fastest)
58
+ 2. Check Redis L2 cache (distributed)
59
+ 3. Compute and store in both caches
60
+ """
61
+
62
+ def __init__(
63
+ self,
64
+ max_size: int = 1000,
65
+ default_ttl_seconds: float = 300,
66
+ redis_ttl_seconds: float | None = None,
67
+ use_redis: bool = True,
68
+ name: str = "default",
69
+ ):
70
+ """
71
+ Initialize hybrid cache.
72
+
73
+ Args:
74
+ max_size: Local cache max size
75
+ default_ttl_seconds: Local cache default TTL
76
+ redis_ttl_seconds: Redis TTL (defaults to default_ttl_seconds)
77
+ use_redis: Whether to use Redis
78
+ name: Cache name for logging
79
+ """
80
+ self.max_size = max_size
81
+ self.default_ttl_seconds = default_ttl_seconds
82
+ self.redis_ttl_seconds = redis_ttl_seconds or default_ttl_seconds
83
+ self.name = name
84
+ self.use_redis = (
85
+ use_redis and os.getenv("REDIS_ENABLED", "false").lower() == "true"
86
+ )
87
+
88
+ # L1: Local cache
89
+ self.cache: dict[str, CacheEntry] = {}
90
+ self.lock = threading.RLock()
91
+
92
+ # L2: Redis cache
93
+ self.redis_cache: RedisCache | None = None
94
+ if self.use_redis:
95
+ self.redis_cache = redis_cache_instance
96
+ if self.redis_cache is None:
97
+ logger.warning(
98
+ f"Redis not available for cache '{name}', using local cache only"
99
+ )
100
+ self.use_redis = False
101
+
102
+ # Stats
103
+ self.stats = {
104
+ "hits_l1": 0,
105
+ "hits_l2": 0,
106
+ "misses": 0,
107
+ "evictions": 0,
108
+ "expirations": 0,
109
+ }
110
+
111
+ # Start cleanup thread
112
+ self._start_cleanup_thread()
113
+
114
+ logger.info(f"HybridQueryCache '{name}' initialized (Redis: {self.use_redis})")
115
+
116
+ def _start_cleanup_thread(self) -> None:
117
+ """Start background thread to clean expired entries"""
118
+
119
+ def cleanup_worker():
120
+ while True:
121
+ time.sleep(60)
122
+ self._cleanup_expired()
123
+
124
+ thread = threading.Thread(target=cleanup_worker, daemon=True)
125
+ thread.start()
126
+
127
+ def _cleanup_expired(self) -> int:
128
+ """Remove expired entries from local cache"""
129
+ with self.lock:
130
+ expired_keys = [
131
+ key for key, entry in self.cache.items() if entry.is_expired()
132
+ ]
133
+ for key in expired_keys:
134
+ del self.cache[key]
135
+ self.stats["expirations"] += len(expired_keys)
136
+ return len(expired_keys)
137
+
138
+ def _evict_lru(self) -> None:
139
+ """Evict least recently used entry from local cache"""
140
+ if not self.cache:
141
+ return
142
+
143
+ lru_key = min(self.cache.keys(), key=lambda k: self.cache[k].last_accessed)
144
+ del self.cache[lru_key]
145
+ self.stats["evictions"] += 1
146
+
147
+ def _make_key(self, *args, **kwargs) -> str:
148
+ """Create cache key from arguments"""
149
+ key_data = {"args": args, "kwargs": dict(sorted(kwargs.items()))}
150
+ key_str = json.dumps(key_data, sort_keys=True, default=str)
151
+ return f"cache:{self.name}:{hashlib.md5(key_str.encode()).hexdigest()}"
152
+
153
+ def _redis_key(self, local_key: str) -> str:
154
+ """Convert local key to Redis key"""
155
+ return f"cache:{self.name}:{local_key}"
156
+
157
+ def get(self, key: str) -> Any | None:
158
+ """Get value from cache"""
159
+ # Check L1 first
160
+ with self.lock:
161
+ entry = self.cache.get(key)
162
+
163
+ if entry is not None:
164
+ if entry.is_expired():
165
+ del self.cache[key]
166
+ self.stats["expirations"] += 1
167
+ self.stats["misses"] += 1
168
+ else:
169
+ entry.touch()
170
+ self.stats["hits_l1"] += 1
171
+ return entry.value
172
+
173
+ # Check L2 (Redis) - disabled due to async/sync mismatch
174
+ # RedisCache uses async methods which can't be called from sync context
175
+ # self.stats["hits_l2"] += 1 # Would be here if Redis worked
176
+
177
+ self.stats["misses"] += 1
178
+ return None
179
+
180
+ def set(self, key: str, value: Any, ttl_seconds: float | None = None) -> None:
181
+ """Store value in cache"""
182
+ ttl_local = ttl_seconds if ttl_seconds is not None else self.default_ttl_seconds
183
+ # ttl_redis = self.redis_ttl_seconds # Disabled due to async/sync mismatch
184
+
185
+ # Store in L1
186
+ with self.lock:
187
+ while len(self.cache) >= self.max_size:
188
+ self._evict_lru()
189
+
190
+ entry = CacheEntry(
191
+ value=value,
192
+ created_at=time.time(),
193
+ ttl_seconds=ttl_local,
194
+ last_accessed=time.time(),
195
+ )
196
+ self.cache[key] = entry
197
+
198
+ # Store in L2 (Redis) - disabled due to async/sync mismatch
199
+ # RedisCache uses async methods which can't be called from sync context
200
+ # if self.use_redis and self.redis_cache:
201
+ # redis_key = self._redis_key(key)
202
+ # self.redis_cache.set(redis_key, value, ttl=ttl_redis)
203
+
204
+ def get_or_compute(
205
+ self,
206
+ key: str,
207
+ compute_func: Callable[[], Any],
208
+ ttl_seconds: float | None = None,
209
+ ) -> Any:
210
+ """Get from cache or compute and store"""
211
+ cached = self.get(key)
212
+ if cached is not None:
213
+ return cached
214
+
215
+ value = compute_func()
216
+ self.set(key, value, ttl_seconds)
217
+ return value
218
+
219
+ def invalidate(self, key: str) -> bool:
220
+ """Remove entry from cache"""
221
+ with self.lock:
222
+ if key in self.cache:
223
+ del self.cache[key]
224
+
225
+ if self.use_redis and self.redis_cache:
226
+ redis_key = self._redis_key(key)
227
+ self.redis_cache.delete(redis_key)
228
+
229
+ return True
230
+
231
+ def invalidate_pattern(self, pattern: str) -> int:
232
+ """Remove all entries matching pattern"""
233
+ count = 0
234
+
235
+ with self.lock:
236
+ keys_to_remove = [k for k in self.cache if pattern in k]
237
+ for key in keys_to_remove:
238
+ del self.cache[key]
239
+ count = len(keys_to_remove)
240
+
241
+ if self.use_redis and self.redis_cache:
242
+ keys = self.redis_cache.keys(f"cache:{self.name}:*{pattern}*")
243
+ if keys:
244
+ self.redis_cache.delete_many(keys)
245
+ count += len(keys)
246
+
247
+ return count
248
+
249
+ def clear(self) -> None:
250
+ """Clear all cache entries"""
251
+ with self.lock:
252
+ self.cache.clear()
253
+
254
+ if self.use_redis and self.redis_cache:
255
+ keys = self.redis_cache.keys(f"cache:{self.name}:*")
256
+ if keys:
257
+ self.redis_cache.delete_many(keys)
258
+
259
+ self.stats = {
260
+ "hits_l1": 0,
261
+ "hits_l2": 0,
262
+ "misses": 0,
263
+ "evictions": 0,
264
+ "expirations": 0,
265
+ }
266
+
267
+ logger.info(f"HybridQueryCache '{self.name}' cleared")
268
+
269
+ def get_stats(self) -> dict[str, Any]:
270
+ """Get cache statistics"""
271
+ with self.lock:
272
+ total_requests = (
273
+ self.stats["hits_l1"] + self.stats["hits_l2"] + self.stats["misses"]
274
+ )
275
+ hit_rate_l1 = (
276
+ self.stats["hits_l1"] / total_requests if total_requests > 0 else 0
277
+ )
278
+ hit_rate_l2 = (
279
+ self.stats["hits_l2"] / total_requests if total_requests > 0 else 0
280
+ )
281
+
282
+ stats = {
283
+ "name": self.name,
284
+ "size": len(self.cache),
285
+ "max_size": self.max_size,
286
+ **self.stats,
287
+ "hit_rate_l1": round(hit_rate_l1, 4),
288
+ "hit_rate_l2": round(hit_rate_l2, 4),
289
+ "hit_rate_total": round(hit_rate_l1 + hit_rate_l2, 4),
290
+ "use_redis": self.use_redis,
291
+ "default_ttl_seconds": self.default_ttl_seconds,
292
+ }
293
+
294
+ if self.use_redis and self.redis_cache:
295
+ stats["redis_stats"] = self.redis_cache.get_stats()
296
+
297
+ return stats
298
+
299
+
300
+ # Global cache instances for different operations
301
+ _intent_extraction_cache: HybridQueryCache | None = None
302
+ _ranking_cache: HybridQueryCache | None = None
303
+ _url_analysis_cache: HybridQueryCache | None = None
304
+ _ad_matching_cache: HybridQueryCache | None = None
305
+ _cache_lock = threading.Lock()
306
+
307
+
308
+ def get_intent_extraction_cache() -> HybridQueryCache:
309
+ """Get cache for intent extraction results (10 min TTL)"""
310
+ global _intent_extraction_cache
311
+ if _intent_extraction_cache is None:
312
+ with _cache_lock:
313
+ if _intent_extraction_cache is None:
314
+ _intent_extraction_cache = HybridQueryCache(
315
+ max_size=5000,
316
+ default_ttl_seconds=600,
317
+ name="intent_extraction",
318
+ )
319
+ return _intent_extraction_cache
320
+
321
+
322
+ def get_ranking_cache() -> HybridQueryCache:
323
+ """Get cache for ranking results (5 min TTL)"""
324
+ global _ranking_cache
325
+ if _ranking_cache is None:
326
+ with _cache_lock:
327
+ if _ranking_cache is None:
328
+ _ranking_cache = HybridQueryCache(
329
+ max_size=2000,
330
+ default_ttl_seconds=300,
331
+ name="ranking",
332
+ )
333
+ return _ranking_cache
334
+
335
+
336
+ def get_url_analysis_cache() -> HybridQueryCache:
337
+ """Get cache for URL analysis results (1 hour TTL)"""
338
+ global _url_analysis_cache
339
+ if _url_analysis_cache is None:
340
+ with _cache_lock:
341
+ if _url_analysis_cache is None:
342
+ _url_analysis_cache = HybridQueryCache(
343
+ max_size=10000,
344
+ default_ttl_seconds=3600,
345
+ name="url_analysis",
346
+ )
347
+ return _url_analysis_cache
348
+
349
+
350
+ def get_ad_matching_cache() -> HybridQueryCache:
351
+ """Get cache for ad matching results (2 min TTL)"""
352
+ global _ad_matching_cache
353
+ if _ad_matching_cache is None:
354
+ with _cache_lock:
355
+ if _ad_matching_cache is None:
356
+ _ad_matching_cache = HybridQueryCache(
357
+ max_size=1000,
358
+ default_ttl_seconds=120,
359
+ name="ad_matching",
360
+ )
361
+ return _ad_matching_cache
362
+
363
+
364
+ def get_all_cache_stats() -> dict[str, dict[str, Any]]:
365
+ """Get statistics for all caches"""
366
+ return {
367
+ "intent_extraction": get_intent_extraction_cache().get_stats(),
368
+ "ranking": get_ranking_cache().get_stats(),
369
+ "url_analysis": get_url_analysis_cache().get_stats(),
370
+ "ad_matching": get_ad_matching_cache().get_stats(),
371
+ }
372
+
373
+
374
+ def clear_all_caches() -> None:
375
+ """Clear all caches"""
376
+ get_intent_extraction_cache().clear()
377
+ get_ranking_cache().clear()
378
+ get_url_analysis_cache().clear()
379
+ get_ad_matching_cache().clear()
380
+ logger.info("All caches cleared")
381
+
382
+
383
+ def cached(
384
+ cache_instance: HybridQueryCache,
385
+ ttl_seconds: float | None = None,
386
+ key_func: Callable | None = None,
387
+ ):
388
+ """Decorator to cache function results"""
389
+
390
+ def decorator(func: Callable) -> Callable:
391
+ @wraps(func)
392
+ def wrapper(*args, **kwargs):
393
+ # Generate cache key
394
+ cache_key = (
395
+ key_func(*args, **kwargs)
396
+ if key_func
397
+ else cache_instance._make_key(*args, **kwargs)
398
+ )
399
+
400
+ # Try to get from cache
401
+ cached_value = cache_instance.get(cache_key)
402
+ if cached_value is not None:
403
+ return cached_value
404
+
405
+ # Compute and store
406
+ result = func(*args, **kwargs)
407
+ cache_instance.set(cache_key, result, ttl_seconds)
408
+ return result
409
+
410
+ return wrapper
411
+
412
+ return decorator
services/query_layer/app/config/model_cache.py ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Model Cache - Pre-loads and caches ML models for faster startup.
3
+
4
+ This module provides model initialization and caching to avoid cold starts.
5
+ """
6
+
7
+ import logging
8
+
9
+ logger = logging.getLogger(__name__)
10
+
11
+
12
+ def initialize_models():
13
+ """
14
+ Pre-load and cache all ML models used by the Intent Engine.
15
+
16
+ This should be called once at startup to avoid cold-start latency
17
+ on the first request.
18
+ """
19
+ logger.info("Initializing ML models...")
20
+
21
+ try:
22
+ from app.core.embedding_service import get_embedding_service
23
+
24
+ service = get_embedding_service()
25
+ service.initialize(use_redis=False)
26
+ logger.info("Embedding service initialized")
27
+ except Exception as e:
28
+ logger.warning(f"Could not initialize embedding service: {e}")
29
+
30
+ try:
31
+ from app.extraction.extractor import get_intent_extractor
32
+
33
+ get_intent_extractor()
34
+ logger.info("Intent extractor initialized")
35
+ except Exception as e:
36
+ logger.warning(f"Could not initialize intent extractor: {e}")
37
+
38
+ try:
39
+ from app.ranking.ranker import get_intent_ranker
40
+
41
+ get_intent_ranker()
42
+ logger.info("Intent ranker initialized")
43
+ except Exception as e:
44
+ logger.warning(f"Could not initialize intent ranker: {e}")
45
+
46
+ logger.info("Model initialization complete")
services/query_layer/app/config/multi_tier_cache.py ADDED
@@ -0,0 +1,291 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Intent Engine - Multi-Tier Cache for Search Results
3
+
4
+ Implements 3-tier caching strategy for optimal performance:
5
+ - L1: In-memory LRU cache (10ms access) - Top 1000 queries
6
+ - L2: Redis cache (50ms access) - Recent queries (24h)
7
+ - L3: Qdrant semantic cache (100ms access) - Similar queries
8
+
9
+ Usage:
10
+ cache = MultiTierCache()
11
+ result = await cache.get(query)
12
+ if not result:
13
+ result = await search(query)
14
+ await cache.set(query, result)
15
+ """
16
+
17
+ import hashlib
18
+ import logging
19
+ from collections import OrderedDict
20
+ from datetime import datetime, timedelta
21
+ from typing import Any
22
+
23
+ logger = logging.getLogger(__name__)
24
+
25
+
26
+ class LRUCache:
27
+ """L1: In-memory LRU cache for hot queries"""
28
+
29
+ def __init__(self, capacity: int = 1000, ttl_seconds: int = 300):
30
+ self.capacity = capacity
31
+ self.ttl_seconds = ttl_seconds
32
+ self.cache: OrderedDict[str, tuple[Any, datetime]] = OrderedDict()
33
+ self.hits = 0
34
+ self.misses = 0
35
+
36
+ def get(self, key: str) -> Any | None:
37
+ """Get item from cache"""
38
+ if key not in self.cache:
39
+ self.misses += 1
40
+ return None
41
+
42
+ value, expiry = self.cache[key]
43
+
44
+ # Check if expired
45
+ if datetime.now() > expiry:
46
+ del self.cache[key]
47
+ self.misses += 1
48
+ return None
49
+
50
+ # Move to end (most recently used)
51
+ self.cache.move_to_end(key)
52
+ self.hits += 1
53
+ return value
54
+
55
+ def set(self, key: str, value: Any) -> None:
56
+ """Set item in cache"""
57
+ expiry = datetime.now() + timedelta(seconds=self.ttl_seconds)
58
+
59
+ if key in self.cache:
60
+ self.cache.move_to_end(key)
61
+
62
+ self.cache[key] = (value, expiry)
63
+
64
+ # Evict oldest if over capacity
65
+ while len(self.cache) > self.capacity:
66
+ self.cache.popitem(last=False)
67
+
68
+ def stats(self) -> dict[str, Any]:
69
+ """Get cache statistics"""
70
+ total = self.hits + self.misses
71
+ hit_rate = (self.hits / total * 100) if total > 0 else 0
72
+ return {
73
+ "hits": self.hits,
74
+ "misses": self.misses,
75
+ "hit_rate": f"{hit_rate:.1f}%",
76
+ "size": len(self.cache),
77
+ "capacity": self.capacity,
78
+ }
79
+
80
+
81
+ class MultiTierCache:
82
+ """
83
+ Multi-tier caching for search results.
84
+
85
+ Tiers:
86
+ - L1: In-memory LRU (10ms) - Most popular queries
87
+ - L2: Redis (50ms) - Recent queries
88
+ - L3: Qdrant semantic (100ms) - Similar queries
89
+ """
90
+
91
+ def __init__(self, redis_client=None):
92
+ # L1: In-memory cache (1000 queries, 5 min TTL)
93
+ self.l1_cache = LRUCache(capacity=1000, ttl_seconds=300)
94
+
95
+ # L2: Redis cache (will be set from external)
96
+ self.l2_redis = redis_client
97
+
98
+ # L2 Redis keys
99
+ self.redis_prefix = "search:cache:"
100
+ self.redis_ttl = 3600 # 1 hour
101
+
102
+ # L3: Qdrant semantic cache
103
+ self.l3_qdrant = None
104
+ self.l3_threshold = 0.95 # Similarity threshold
105
+
106
+ logger.info("MultiTierCache initialized (L1: LRU, L2: Redis, L3: Qdrant)")
107
+
108
+ def set_redis_client(self, redis_client) -> None:
109
+ """Set Redis client for L2 cache"""
110
+ self.l2_redis = redis_client
111
+ logger.info("L2 Redis cache connected")
112
+
113
+ def set_qdrant_client(self, qdrant_client) -> None:
114
+ """Set Qdrant client for L3 semantic cache"""
115
+ self.l3_qdrant = qdrant_client
116
+ logger.info("L3 Qdrant semantic cache connected")
117
+
118
+ def _generate_cache_key(self, query: str) -> str:
119
+ """Generate consistent cache key from query"""
120
+ # Normalize query
121
+ normalized = query.lower().strip()
122
+ # Generate hash
123
+ key_hash = hashlib.md5(normalized.encode()).hexdigest()[:16]
124
+ return f"{self.redis_prefix}{key_hash}"
125
+
126
+ async def get(self, query: str) -> Any | None:
127
+ """
128
+ Get search results from cache (multi-tier).
129
+
130
+ Tries L1 → L2 → L3 in order, returns first match.
131
+ Promotes results to higher tiers on hit.
132
+ """
133
+ cache_key = self._generate_cache_key(query)
134
+
135
+ # L1: Check in-memory cache (fastest)
136
+ if (result := self.l1_cache.get(cache_key)) is not None:
137
+ logger.debug(f"L1 cache HIT: {query[:50]}")
138
+ return result
139
+
140
+ # L2: Check Redis cache
141
+ if self.l2_redis:
142
+ try:
143
+ cached = await self.l2_redis.get(cache_key)
144
+ if cached:
145
+ import json
146
+
147
+ result = json.loads(cached)
148
+ # Promote to L1
149
+ self.l1_cache.set(cache_key, result)
150
+ logger.debug(f"L2 cache HIT: {query[:50]}")
151
+ return result
152
+ except Exception as e:
153
+ logger.warning(f"L2 Redis cache error: {e}")
154
+
155
+ # L3: Check Qdrant semantic cache (similar queries)
156
+ if self.l3_qdrant:
157
+ try:
158
+ similar_result = await self._find_similar_query(query)
159
+ if similar_result:
160
+ # Promote to L1 and L2
161
+ self.l1_cache.set(cache_key, similar_result)
162
+ await self._set_l2(cache_key, similar_result)
163
+ logger.debug(f"L3 semantic cache HIT: {query[:50]}")
164
+ return similar_result
165
+ except Exception as e:
166
+ logger.warning(f"L3 Qdrant cache error: {e}")
167
+
168
+ # Cache miss
169
+ logger.debug(f"Cache MISS: {query[:50]}")
170
+ return None
171
+
172
+ async def set(self, query: str, result: Any, ttl: int = 3600) -> None:
173
+ """
174
+ Set search results in all cache tiers.
175
+
176
+ Args:
177
+ query: Search query
178
+ result: Search results to cache
179
+ ttl: Time to live in seconds
180
+ """
181
+ cache_key = self._generate_cache_key(query)
182
+
183
+ # L1: Always cache in memory
184
+ self.l1_cache.set(cache_key, result)
185
+
186
+ # L2: Cache in Redis
187
+ await self._set_l2(cache_key, result, ttl)
188
+
189
+ # L3: Index query in Qdrant for semantic lookup
190
+ await self._index_query_semantic(query, result)
191
+
192
+ logger.debug(f"Cached query: {query[:50]} (L1+L2+L3)")
193
+
194
+ async def _set_l2(self, cache_key: str, result: Any, ttl: int = 3600) -> None:
195
+ """Set result in L2 Redis cache"""
196
+ if not self.l2_redis:
197
+ return
198
+
199
+ try:
200
+ import json
201
+
202
+ # Use RedisCache.set() method instead of raw Redis setex
203
+ await self.l2_redis.set(cache_key, json.dumps(result), ttl=ttl)
204
+ except Exception as e:
205
+ logger.warning(f"Failed to set L2 cache: {e}")
206
+
207
+ async def _find_similar_query(self, query: str) -> Any | None:
208
+ """Find similar cached query in Qdrant (L3 semantic cache)"""
209
+ if not self.l3_qdrant:
210
+ return None
211
+
212
+ try:
213
+ from app.core.embedding_service import get_embedding_service
214
+
215
+ embedding_service = get_embedding_service()
216
+ query_embedding = embedding_service.encode_text(query)
217
+
218
+ if query_embedding is None:
219
+ return None
220
+
221
+ # Search for similar queries
222
+ similar = self.l3_qdrant.search_similar(
223
+ query_embedding=query_embedding.tolist(),
224
+ limit=1,
225
+ score_threshold=self.l3_threshold,
226
+ )
227
+
228
+ if similar and len(similar) > 0:
229
+ result = similar[0]
230
+ if result.get("payload", {}).get("cached_result"):
231
+ return result["payload"]["cached_result"]
232
+ except Exception as e:
233
+ logger.debug(f"L3 semantic search failed: {e}")
234
+
235
+ return None
236
+
237
+ async def _index_query_semantic(self, query: str, result: Any) -> None:
238
+ """Index query in Qdrant for future semantic lookup (L3)"""
239
+ if not self.l3_qdrant:
240
+ return
241
+
242
+ try:
243
+ from app.core.embedding_service import get_embedding_service
244
+
245
+ embedding_service = get_embedding_service()
246
+ query_embedding = embedding_service.encode_text(query)
247
+
248
+ if query_embedding is None:
249
+ return
250
+
251
+ # Store in Qdrant with cached result using internal client
252
+ # Note: QdrantVectorStore doesn't have upsert method, use internal client directly
253
+ client = self.l3_qdrant._get_client()
254
+ if client:
255
+ from qdrant_client.http.models import PointStruct
256
+
257
+ point = PointStruct(
258
+ id=hashlib.md5(query.encode()).hexdigest(),
259
+ vector=query_embedding.tolist(),
260
+ payload={
261
+ "query": query,
262
+ "cached_result": result,
263
+ "timestamp": datetime.now().isoformat(),
264
+ },
265
+ )
266
+ client.upsert(
267
+ collection_name=self.l3_qdrant.collection_name,
268
+ points=[point],
269
+ )
270
+ except Exception as e:
271
+ logger.debug(f"Failed to index query in L3: {e}")
272
+
273
+ def get_stats(self) -> dict[str, Any]:
274
+ """Get cache statistics"""
275
+ return {
276
+ "l1": self.l1_cache.stats(),
277
+ "l2": "connected" if self.l2_redis else "disconnected",
278
+ "l3": "connected" if self.l3_qdrant else "disconnected",
279
+ }
280
+
281
+
282
+ # Singleton instance
283
+ _cache_instance: MultiTierCache | None = None
284
+
285
+
286
+ def get_multi_tier_cache() -> MultiTierCache:
287
+ """Get or create multi-tier cache singleton"""
288
+ global _cache_instance
289
+ if _cache_instance is None:
290
+ _cache_instance = MultiTierCache()
291
+ return _cache_instance
services/query_layer/app/config/optimized_cache.py ADDED
@@ -0,0 +1,58 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Optimized Embedding Cache with Singleton Pattern
3
+
4
+ This module provides a shared embedding cache to prevent duplicate model loading.
5
+ """
6
+
7
+ import threading
8
+ from typing import Optional
9
+
10
+ import numpy as np
11
+
12
+ from app.core.embedding_service import get_embedding_service
13
+
14
+
15
+ class EmbeddingCache:
16
+ """Thread-safe embedding cache using the shared embedding service"""
17
+
18
+ _instance: Optional["EmbeddingCache"] = None
19
+ _lock = threading.Lock()
20
+
21
+ def __new__(cls):
22
+ if cls._instance is None:
23
+ with cls._lock:
24
+ if cls._instance is None:
25
+ cls._instance = super().__new__(cls)
26
+ cls._instance._initialized = False
27
+ return cls._instance
28
+
29
+ def __init__(self):
30
+ if self._initialized:
31
+ return
32
+ self._service = get_embedding_service()
33
+ self._service.initialize()
34
+ self._initialized = True
35
+
36
+ def encode_text(self, text: str) -> np.ndarray | None:
37
+ """Encode text to embedding vector"""
38
+ return self._service.encode_text(text)
39
+
40
+ def encode_batch(self, texts: list[str]) -> list[np.ndarray | None]:
41
+ """Encode batch of texts"""
42
+ return self._service.encode_batch(texts)
43
+
44
+ def cosine_similarity(self, vec1: np.ndarray, vec2: np.ndarray) -> float:
45
+ """Calculate cosine similarity between two vectors"""
46
+ return self._service.cosine_similarity(vec1, vec2)
47
+
48
+
49
+ # Singleton instance
50
+ _embedding_cache_instance: EmbeddingCache | None = None
51
+
52
+
53
+ def get_embedding_cache() -> EmbeddingCache:
54
+ """Get singleton instance of EmbeddingCache"""
55
+ global _embedding_cache_instance
56
+ if _embedding_cache_instance is None:
57
+ _embedding_cache_instance = EmbeddingCache()
58
+ return _embedding_cache_instance
services/query_layer/app/config/query_cache.py ADDED
@@ -0,0 +1,96 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Query Cache for Ranking Results
3
+
4
+ This module provides caching for ranking results to improve performance.
5
+ """
6
+
7
+ import hashlib
8
+ import threading
9
+ from collections import OrderedDict
10
+ from typing import Any, Optional
11
+
12
+
13
+ class RankingCache:
14
+ """Thread-safe LRU cache for ranking results"""
15
+
16
+ _instance: Optional["RankingCache"] = None
17
+ _lock = threading.Lock()
18
+
19
+ def __new__(cls, capacity: int = 1000):
20
+ if cls._instance is None:
21
+ with cls._lock:
22
+ if cls._instance is None:
23
+ cls._instance = super().__new__(cls)
24
+ cls._instance._initialized = False
25
+ cls._instance._capacity = capacity
26
+ return cls._instance
27
+
28
+ def __init__(self, capacity: int = 1000):
29
+ if self._initialized:
30
+ return
31
+ self._capacity = capacity
32
+ self._cache: OrderedDict[str, Any] = OrderedDict()
33
+ self._lock = threading.RLock()
34
+ self._hits = 0
35
+ self._misses = 0
36
+ self._initialized = True
37
+
38
+ def _make_key(self, query: str, **kwargs) -> str:
39
+ """Create cache key from query and kwargs"""
40
+ key_parts = [query]
41
+ for k, v in sorted(kwargs.items()):
42
+ key_parts.append(f"{k}={v}")
43
+ key_string = "|".join(key_parts)
44
+ return hashlib.sha256(key_string.encode()).hexdigest()
45
+
46
+ def get(self, query: str, **kwargs) -> Any | None:
47
+ """Get cached result for query"""
48
+ key = self._make_key(query, **kwargs)
49
+ with self._lock:
50
+ if key in self._cache:
51
+ self._cache.move_to_end(key)
52
+ self._hits += 1
53
+ return self._cache[key]
54
+ self._misses += 1
55
+ return None
56
+
57
+ def set(self, query: str, result: Any, **kwargs) -> None:
58
+ """Cache result for query"""
59
+ key = self._make_key(query, **kwargs)
60
+ with self._lock:
61
+ if key in self._cache:
62
+ self._cache.move_to_end(key)
63
+ elif len(self._cache) >= self._capacity:
64
+ self._cache.popitem(last=False)
65
+ self._cache[key] = result
66
+
67
+ def clear(self) -> None:
68
+ """Clear the cache"""
69
+ with self._lock:
70
+ self._cache.clear()
71
+ self._hits = 0
72
+ self._misses = 0
73
+
74
+ def stats(self) -> dict[str, Any]:
75
+ """Get cache statistics"""
76
+ total = self._hits + self._misses
77
+ hit_rate = self._hits / total if total > 0 else 0.0
78
+ return {
79
+ "hits": self._hits,
80
+ "misses": self._misses,
81
+ "hit_rate": hit_rate,
82
+ "size": len(self._cache),
83
+ "capacity": self._capacity,
84
+ }
85
+
86
+
87
+ # Singleton instance
88
+ _ranking_cache_instance: RankingCache | None = None
89
+
90
+
91
+ def get_ranking_cache(capacity: int = 1000) -> RankingCache:
92
+ """Get singleton instance of RankingCache"""
93
+ global _ranking_cache_instance
94
+ if _ranking_cache_instance is None:
95
+ _ranking_cache_instance = RankingCache(capacity=capacity)
96
+ return _ranking_cache_instance
services/query_layer/app/config/redis_cache.py ADDED
@@ -0,0 +1,342 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Intent Engine - Redis Cache Module
3
+
4
+ High-performance async Redis caching for search results and intent extraction.
5
+
6
+ Features:
7
+ - Async Redis client using redis.asyncio
8
+ - Intelligent cache key generation
9
+ - Configurable TTL for different data types
10
+ - Cache-aside pattern with background refresh
11
+ - Graceful degradation when Redis unavailable
12
+
13
+ Usage:
14
+ from app.config.redis_cache import cache
15
+
16
+ # Initialize on startup
17
+ await cache.initialize(redis_url="redis://redis:6379/0")
18
+
19
+ # Get/set cache
20
+ cached = await cache.get("key")
21
+ await cache.set("key", value, ttl=300)
22
+
23
+ # Cache-aside pattern
24
+ result = await cache.get_or_set(
25
+ "search:query123",
26
+ lambda: expensive_search("query123"),
27
+ ttl=300
28
+ )
29
+ """
30
+
31
+ import asyncio
32
+ import hashlib
33
+ import json
34
+ import logging
35
+ import time
36
+ from collections.abc import Callable
37
+ from typing import Any
38
+
39
+ import redis.asyncio as redis
40
+
41
+ logger = logging.getLogger(__name__)
42
+
43
+
44
+ class RedisCache:
45
+ """
46
+ Async Redis cache with intelligent key generation and serialization.
47
+
48
+ Provides:
49
+ - Automatic connection management
50
+ - JSON serialization with datetime support
51
+ - Configurable TTL per operation
52
+ - Background cache updates
53
+ - Cache statistics tracking
54
+ """
55
+
56
+ def __init__(self):
57
+ self._client: redis.Redis | None = None
58
+ self._initialized = False
59
+ self._enabled = False
60
+
61
+ # Default TTL settings (in seconds)
62
+ self._default_ttl = 300 # 5 minutes for general cache
63
+ self._search_ttl = 300 # 5 minutes for search results
64
+ self._intent_ttl = 3600 # 1 hour for intent extraction
65
+ self._ranking_ttl = 600 # 10 minutes for ranking results
66
+
67
+ # Key prefix for namespacing
68
+ self._key_prefix = "intent-engine"
69
+
70
+ # Statistics
71
+ self._stats = {
72
+ "hits": 0,
73
+ "misses": 0,
74
+ "errors": 0,
75
+ "sets": 0,
76
+ }
77
+
78
+ async def initialize(self, redis_url: str = "redis://redis:6379/0"):
79
+ """
80
+ Initialize Redis connection on application startup.
81
+
82
+ Args:
83
+ redis_url: Redis connection URL (redis://host:port/db)
84
+ """
85
+ if self._initialized:
86
+ return
87
+
88
+ try:
89
+ logger.info(f"Connecting to Redis: {redis_url}")
90
+
91
+ self._client = redis.Redis.from_url(
92
+ redis_url,
93
+ encoding="utf-8",
94
+ decode_responses=True,
95
+ socket_connect_timeout=5.0,
96
+ socket_timeout=5.0,
97
+ retry_on_timeout=True,
98
+ health_check_interval=30,
99
+ )
100
+
101
+ # Test connection
102
+ await self._client.ping()
103
+
104
+ self._initialized = True
105
+ self._enabled = True
106
+ logger.info("Redis cache connected and enabled")
107
+
108
+ except Exception as e:
109
+ logger.warning(f"Redis connection failed, caching disabled: {e}")
110
+ self._initialized = True
111
+ self._enabled = False
112
+
113
+ async def close(self):
114
+ """Close Redis connection on application shutdown"""
115
+ if self._client:
116
+ await self._client.close()
117
+ logger.info("Redis cache connection closed")
118
+ self._enabled = False
119
+
120
+ def _generate_key(self, prefix: str, *args, **kwargs) -> str:
121
+ """
122
+ Generate consistent cache key from arguments.
123
+
124
+ Args:
125
+ prefix: Key prefix (e.g., "search", "intent")
126
+ *args: Positional arguments to include in key
127
+ **kwargs: Keyword arguments to include in key
128
+
129
+ Returns:
130
+ MD5-hashed cache key with prefix
131
+ """
132
+ # Create deterministic key string
133
+ key_data = {
134
+ "prefix": prefix,
135
+ "args": args,
136
+ "kwargs": sorted(kwargs.items()) if kwargs else [],
137
+ }
138
+ key_string = json.dumps(key_data, sort_keys=True, default=str)
139
+ key_hash = hashlib.md5(key_string.encode()).hexdigest()
140
+
141
+ return f"{self._key_prefix}:{prefix}:{key_hash}"
142
+
143
+ async def get(self, key: str) -> Any | None:
144
+ """
145
+ Get value from cache.
146
+
147
+ Args:
148
+ key: Cache key
149
+
150
+ Returns:
151
+ Cached value or None if not found/error
152
+ """
153
+ if not self._enabled or not self._initialized:
154
+ return None
155
+
156
+ try:
157
+ start_time = time.perf_counter()
158
+ value = await self._client.get(key)
159
+ elapsed = (time.perf_counter() - start_time) * 1000
160
+
161
+ if value:
162
+ self._stats["hits"] += 1
163
+ logger.debug(f"Cache HIT: {key[:80]}... ({elapsed:.2f}ms)")
164
+ return json.loads(value)
165
+ self._stats["misses"] += 1
166
+ logger.debug(f"Cache MISS: {key[:80]}... ({elapsed:.2f}ms)")
167
+ return None
168
+
169
+ except Exception as e:
170
+ self._stats["errors"] += 1
171
+ logger.error(f"Redis GET error: {e}")
172
+ return None
173
+
174
+ async def set(self, key: str, value: Any, ttl: int | None = None, background: bool = False):
175
+ """
176
+ Set value in cache with TTL.
177
+
178
+ Args:
179
+ key: Cache key
180
+ value: Value to cache (will be JSON serialized)
181
+ ttl: Time to live in seconds (default: 300)
182
+ background: If True, cache update happens asynchronously
183
+ """
184
+ if not self._enabled or not self._initialized:
185
+ return
186
+
187
+ try:
188
+ serialized = json.dumps(value, default=str)
189
+ effective_ttl = ttl or self._default_ttl
190
+
191
+ if background:
192
+ # Non-blocking cache update
193
+ asyncio.create_task(self._set_async(key, serialized, effective_ttl))
194
+ else:
195
+ await self._set_async(key, serialized, effective_ttl)
196
+
197
+ self._stats["sets"] += 1
198
+ logger.debug(f"Cache SET: {key[:80]}... (TTL: {effective_ttl}s)")
199
+
200
+ except Exception as e:
201
+ self._stats["errors"] += 1
202
+ logger.error(f"Redis SET error: {e}")
203
+
204
+ async def _set_async(self, key: str, value: str, ttl: int):
205
+ """Internal async set operation"""
206
+ await self._client.setex(key, ttl, value)
207
+
208
+ async def delete(self, key: str):
209
+ """Delete key from cache"""
210
+ if not self._enabled or not self._initialized:
211
+ return
212
+
213
+ try:
214
+ await self._client.delete(key)
215
+ logger.debug(f"Cache DELETE: {key[:80]}...")
216
+ except Exception as e:
217
+ self._stats["errors"] += 1
218
+ logger.error(f"Redis DELETE error: {e}")
219
+
220
+ async def get_or_set(
221
+ self,
222
+ key: str,
223
+ factory: Callable,
224
+ ttl: int | None = None,
225
+ ) -> Any:
226
+ """
227
+ Get from cache or compute and cache result (cache-aside pattern).
228
+
229
+ Args:
230
+ key: Cache key
231
+ factory: Async function to compute value if cache miss
232
+ ttl: Time to live in seconds
233
+
234
+ Returns:
235
+ Cached or computed value
236
+ """
237
+ # Try cache first
238
+ cached = await self.get(key)
239
+ if cached is not None:
240
+ return cached
241
+
242
+ # Cache miss: compute value
243
+ logger.info(f"Cache miss, computing: {key[:80]}...")
244
+
245
+ if asyncio.iscoroutinefunction(factory):
246
+ value = await factory()
247
+ else:
248
+ value = factory()
249
+
250
+ # Cache result
251
+ await self.set(key, value, ttl)
252
+
253
+ return value
254
+
255
+ async def get_search(self, query: str, pageno: int = 1, language: str = "en") -> dict | None:
256
+ """Get cached search results"""
257
+ key = self._generate_key("search", query=query, pageno=pageno, language=language)
258
+ return await self.get(key)
259
+
260
+ async def set_search(self, query: str, pageno: int, language: str, results: dict):
261
+ """Cache search results"""
262
+ key = self._generate_key("search", query=query, pageno=pageno, language=language)
263
+ await self.set(key, results, ttl=self._search_ttl, background=True)
264
+
265
+ async def get_intent(self, query: str) -> dict | None:
266
+ """Get cached intent extraction"""
267
+ key = self._generate_key("intent", query=query)
268
+ return await self.get(key)
269
+
270
+ async def set_intent(self, query: str, intent: dict):
271
+ """Cache intent extraction result"""
272
+ key = self._generate_key("intent", query=query)
273
+ await self.set(key, intent, ttl=self._intent_ttl, background=True)
274
+
275
+ async def get_stats(self) -> dict:
276
+ """Get cache statistics"""
277
+ total = self._stats["hits"] + self._stats["misses"]
278
+ hit_rate = (self._stats["hits"] / total * 100) if total > 0 else 0
279
+
280
+ return {
281
+ **self._stats,
282
+ "total_requests": total,
283
+ "hit_rate_percent": round(hit_rate, 2),
284
+ "enabled": self._enabled,
285
+ "initialized": self._initialized,
286
+ }
287
+
288
+ async def get_memory_usage(self) -> int | None:
289
+ """Get Redis memory usage in MB"""
290
+ if not self._enabled:
291
+ return None
292
+
293
+ try:
294
+ info = await self._client.info("memory")
295
+ return round(info.get("used_memory", 0) / 1024 / 1024, 2)
296
+ except Exception:
297
+ return None
298
+
299
+ async def flush(self, pattern: str | None = None):
300
+ """
301
+ Flush cache keys matching pattern.
302
+
303
+ Args:
304
+ pattern: Key pattern to delete (default: all intent-engine keys)
305
+ """
306
+ if not self._enabled:
307
+ return
308
+
309
+ try:
310
+ search_pattern = pattern or f"{self._key_prefix}:*"
311
+ cursor = 0
312
+
313
+ while True:
314
+ cursor, keys = await self._client.scan(cursor, match=search_pattern, count=100)
315
+ if keys:
316
+ await self._client.delete(*keys)
317
+ logger.info(f"Flushed {len(keys)} cache keys")
318
+
319
+ if cursor == 0:
320
+ break
321
+
322
+ except Exception as e:
323
+ logger.error(f"Cache flush error: {e}")
324
+
325
+
326
+ # Global cache instance
327
+ cache = RedisCache()
328
+
329
+
330
+ async def get_cache() -> RedisCache:
331
+ """Get global cache instance"""
332
+ return cache
333
+
334
+
335
+ async def initialize_cache(redis_url: str = "redis://redis:6379/0"):
336
+ """Initialize global cache instance"""
337
+ await cache.initialize(redis_url)
338
+
339
+
340
+ async def close_cache():
341
+ """Close global cache instance"""
342
+ await cache.close()
services/query_layer/app/config/redis_product_cache.py ADDED
@@ -0,0 +1,313 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Intent Engine - Redis Product Cache
3
+
4
+ Redis-backed cache for structured product data to improve extraction performance.
5
+ """
6
+
7
+ import hashlib
8
+ import json
9
+ import logging
10
+ from datetime import timedelta
11
+ from typing import Optional
12
+
13
+ import redis.asyncio as redis
14
+
15
+ logger = logging.getLogger(__name__)
16
+
17
+
18
+ class ProductCache:
19
+ """
20
+ Redis cache for structured product data.
21
+
22
+ Caches extracted product information by URL to avoid re-extraction.
23
+ Cache hits reduce extraction time from 50-100ms to <5ms.
24
+ """
25
+
26
+ def __init__(self, redis_client: redis.Redis | None = None, ttl_hours: int = 24):
27
+ """
28
+ Initialize product cache.
29
+
30
+ Args:
31
+ redis_client: Redis client instance (creates new if None)
32
+ ttl_hours: Time-to-live for cached products in hours
33
+ """
34
+ self.redis = redis_client
35
+ self.ttl = timedelta(hours=ttl_hours)
36
+ self.prefix = "product:"
37
+ self._enabled = redis_client is not None
38
+
39
+ def _get_cache_key(self, url: str) -> str:
40
+ """
41
+ Generate cache key from URL hash.
42
+
43
+ Args:
44
+ url: Product URL to cache
45
+
46
+ Returns:
47
+ Redis cache key string
48
+ """
49
+ url_hash = hashlib.md5(url.encode()).hexdigest()
50
+ return f"{self.prefix}{url_hash}"
51
+
52
+ async def get(self, url: str) -> Optional[dict]:
53
+ """
54
+ Get cached product data by URL.
55
+
56
+ Args:
57
+ url: Product URL to lookup
58
+
59
+ Returns:
60
+ Cached product data dict or None if not found
61
+ """
62
+ if not self._enabled:
63
+ return None
64
+
65
+ try:
66
+ key = self._get_cache_key(url)
67
+ data = await self.redis.get(key)
68
+
69
+ if data:
70
+ logger.debug(f"Cache hit for product: {url}")
71
+ return json.loads(data)
72
+
73
+ logger.debug(f"Cache miss for product: {url}")
74
+ return None
75
+ except Exception as e:
76
+ logger.warning(f"Error getting product from cache: {e}")
77
+ return None
78
+
79
+ async def set(self, url: str, product_data: dict) -> None:
80
+ """
81
+ Cache product data with TTL.
82
+
83
+ Args:
84
+ url: Product URL to cache
85
+ product_data: Product data dict to store
86
+ """
87
+ if not self._enabled:
88
+ return
89
+
90
+ try:
91
+ key = self._get_cache_key(url)
92
+ await self.redis.setex(
93
+ key, int(self.ttl.total_seconds()), json.dumps(product_data)
94
+ )
95
+ logger.debug(f"Cached product: {url} (TTL: {self.ttl})")
96
+ except Exception as e:
97
+ logger.warning(f"Error setting product in cache: {e}")
98
+
99
+ async def delete(self, url: str) -> None:
100
+ """
101
+ Delete cached product data.
102
+
103
+ Args:
104
+ url: Product URL to remove from cache
105
+ """
106
+ if not self._enabled:
107
+ return
108
+
109
+ try:
110
+ key = self._get_cache_key(url)
111
+ await self.redis.delete(key)
112
+ logger.debug(f"Deleted cached product: {url}")
113
+ except Exception as e:
114
+ logger.warning(f"Error deleting product from cache: {e}")
115
+
116
+ async def get_batch(self, urls: list[str]) -> dict[str, dict]:
117
+ """
118
+ Get multiple cached products in a single batch.
119
+
120
+ Args:
121
+ urls: List of product URLs to lookup
122
+
123
+ Returns:
124
+ Dict mapping URLs to their cached data (only cached items)
125
+ """
126
+ if not self._enabled:
127
+ return {}
128
+
129
+ try:
130
+ keys = {url: self._get_cache_key(url) for url in urls}
131
+ values = await self.redis.mget(list(keys.values()))
132
+
133
+ result = {}
134
+ for url, key in keys.items():
135
+ key_index = list(keys.values()).index(key)
136
+ data = values[key_index]
137
+ if data:
138
+ result[url] = json.loads(data)
139
+
140
+ if result:
141
+ logger.debug(f"Batch cache hit: {len(result)}/{len(urls)} products")
142
+
143
+ return result
144
+ except Exception as e:
145
+ logger.warning(f"Error getting batch products from cache: {e}")
146
+ return {}
147
+
148
+ async def set_batch(self, products: list[tuple[str, dict]]) -> None:
149
+ """
150
+ Cache multiple products in a single batch.
151
+
152
+ Args:
153
+ products: List of (url, product_data) tuples to cache
154
+ """
155
+ if not self._enabled:
156
+ return
157
+
158
+ try:
159
+ pipeline = self.redis.pipeline()
160
+ for url, product_data in products:
161
+ key = self._get_cache_key(url)
162
+ pipeline.setex(
163
+ key, int(self.ttl.total_seconds()), json.dumps(product_data)
164
+ )
165
+
166
+ await pipeline.execute()
167
+ logger.debug(f"Batch cached {len(products)} products")
168
+ except Exception as e:
169
+ logger.warning(f"Error setting batch products in cache: {e}")
170
+
171
+ async def clear(self) -> int:
172
+ """
173
+ Clear all cached products.
174
+
175
+ Returns:
176
+ Number of keys deleted
177
+ """
178
+ if not self._enabled:
179
+ return 0
180
+
181
+ try:
182
+ pattern = f"{self.prefix}*"
183
+ keys = []
184
+ async for key in self.redis.scan_iter(match=pattern):
185
+ keys.append(key)
186
+
187
+ if keys:
188
+ await self.redis.delete(*keys)
189
+ logger.info(f"Cleared {len(keys)} cached products")
190
+ return len(keys)
191
+
192
+ return 0
193
+ except Exception as e:
194
+ logger.warning(f"Error clearing product cache: {e}")
195
+ return 0
196
+
197
+ async def get_stats(self) -> dict:
198
+ """
199
+ Get cache statistics.
200
+
201
+ Returns:
202
+ Dict with cache stats (count, memory usage, etc.)
203
+ """
204
+ if not self._enabled:
205
+ return {"enabled": False}
206
+
207
+ try:
208
+ pattern = f"{self.prefix}*"
209
+ count = 0
210
+ async for _ in self.redis.scan_iter(match=pattern):
211
+ count += 1
212
+
213
+ # Get memory info if available
214
+ memory_info = {}
215
+ try:
216
+ info = await self.redis.info("memory")
217
+ memory_info = {
218
+ "used_memory": info.get("used_memory_human", "N/A"),
219
+ "used_memory_peak": info.get("used_memory_peak_human", "N/A"),
220
+ }
221
+ except Exception:
222
+ pass
223
+
224
+ return {
225
+ "enabled": True,
226
+ "product_count": count,
227
+ "ttl_hours": self.ttl.total_seconds() / 3600,
228
+ **memory_info,
229
+ }
230
+ except Exception as e:
231
+ logger.warning(f"Error getting cache stats: {e}")
232
+ return {"enabled": True, "error": str(e)}
233
+
234
+
235
+ # Singleton instance
236
+ _product_cache: Optional[ProductCache] = None
237
+ _redis_client: Optional[redis.Redis] = None
238
+
239
+
240
+ async def _get_redis_client() -> redis.Redis | None:
241
+ """Get or create Redis client for product cache."""
242
+ global _redis_client
243
+
244
+ if _redis_client is None:
245
+ try:
246
+ # Try to connect to Redis using environment variable or default
247
+ import os
248
+
249
+ redis_url = os.getenv("REDIS_URL", "redis://localhost:6379/0")
250
+ _redis_client = redis.from_url(redis_url, decode_responses=True)
251
+ # Test connection
252
+ await _redis_client.ping()
253
+ logger.info(f"Connected to Redis for product cache: {redis_url}")
254
+ except Exception as e:
255
+ logger.warning(f"Redis not available for product cache: {e}")
256
+ _redis_client = None
257
+
258
+ return _redis_client
259
+
260
+
261
+ def get_product_cache(ttl_hours: int = 24) -> ProductCache:
262
+ """
263
+ Get or create ProductCache singleton.
264
+
265
+ Args:
266
+ ttl_hours: TTL for new cache instances (ignored if cache exists)
267
+
268
+ Returns:
269
+ ProductCache singleton instance
270
+ """
271
+ global _product_cache
272
+ if _product_cache is None:
273
+ # Create cache without Redis client initially
274
+ # Client will be created asynchronously when needed
275
+ _product_cache = ProductCache(ttl_hours=ttl_hours)
276
+ return _product_cache
277
+
278
+
279
+ async def initialize_product_cache(redis_url: str | None = None) -> ProductCache:
280
+ """
281
+ Initialize product cache with Redis connection.
282
+
283
+ Call this on application startup.
284
+
285
+ Args:
286
+ redis_url: Optional Redis URL (uses env var or default if None)
287
+
288
+ Returns:
289
+ Initialized ProductCache instance
290
+ """
291
+ global _product_cache, _redis_client
292
+
293
+ import os
294
+
295
+ if redis_url is None:
296
+ redis_url = os.getenv("REDIS_URL", "redis://localhost:6379/0")
297
+
298
+ try:
299
+ _redis_client = redis.from_url(redis_url, decode_responses=True)
300
+ await _redis_client.ping()
301
+ logger.info(f"Product cache connected to Redis: {redis_url}")
302
+ except Exception as e:
303
+ logger.warning(f"Product cache Redis connection failed: {e}")
304
+ _redis_client = None
305
+
306
+ _product_cache = ProductCache(redis_client=_redis_client)
307
+ return _product_cache
308
+
309
+
310
+ def reset_product_cache() -> None:
311
+ """Reset the singleton instance (useful for testing)."""
312
+ global _product_cache
313
+ _product_cache = None
services/query_layer/app/config/search_session_manager.py ADDED
@@ -0,0 +1,529 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Intent Engine - Search Session Manager
3
+
4
+ Redis-backed session storage for search pagination with support for:
5
+ - Distributed session storage across multiple workers/containers
6
+ - Configurable TTL with automatic expiration
7
+ - On-demand result fetching from backends
8
+ - Cursor-based and offset-based pagination
9
+ - Session metadata tracking
10
+
11
+ Usage:
12
+ from app.config.search_session_manager import get_session_manager
13
+
14
+ manager = get_session_manager()
15
+ session_id = await manager.create_session(...)
16
+ session = await manager.get_session(session_id)
17
+ """
18
+
19
+ import json
20
+ import logging
21
+ import uuid
22
+ from datetime import UTC, datetime
23
+
24
+ from app.config.settings import get_settings
25
+
26
+ logger = logging.getLogger(__name__)
27
+
28
+
29
+ class SearchSessionData:
30
+ """Data class for search session information"""
31
+
32
+ def __init__(
33
+ self,
34
+ session_id: str,
35
+ query: str,
36
+ total_results: int,
37
+ intent: dict | None = None,
38
+ page_size: int = 20,
39
+ max_results: int = 100,
40
+ ttl_minutes: int = 10,
41
+ cache_results: bool = True,
42
+ ):
43
+ self.session_id = session_id
44
+ self.query = query
45
+ self.total_results = total_results
46
+ self.intent = intent
47
+ self.page_size = page_size
48
+ self.max_results = max_results
49
+ self.ttl_minutes = ttl_minutes
50
+ self.cache_results = cache_results
51
+ self.created_at = datetime.now(UTC)
52
+ self.accessed_at = datetime.now(UTC)
53
+ self.all_results: list[dict] = [] # Cached results
54
+ self.backend_fetched_pages: list[int] = [] # Track fetched pages
55
+ self.result_count: int = 0 # Total results cached
56
+
57
+ def to_dict(self) -> dict:
58
+ """Serialize session data to dictionary"""
59
+ return {
60
+ "session_id": self.session_id,
61
+ "query": self.query,
62
+ "total_results": self.total_results,
63
+ "intent": self.intent,
64
+ "page_size": self.page_size,
65
+ "max_results": self.max_results,
66
+ "ttl_minutes": self.ttl_minutes,
67
+ "cache_results": self.cache_results,
68
+ "created_at": self.created_at.isoformat(),
69
+ "accessed_at": self.accessed_at.isoformat(),
70
+ "all_results": self.all_results,
71
+ "backend_fetched_pages": self.backend_fetched_pages,
72
+ "result_count": self.result_count,
73
+ }
74
+
75
+ @classmethod
76
+ def from_dict(cls, data: dict) -> "SearchSessionData":
77
+ """Deserialize session data from dictionary"""
78
+ session = cls(
79
+ session_id=data["session_id"],
80
+ query=data["query"],
81
+ total_results=data["total_results"],
82
+ intent=data.get("intent"),
83
+ page_size=data.get("page_size", 20),
84
+ max_results=data.get("max_results", 100),
85
+ ttl_minutes=data.get("ttl_minutes", 10),
86
+ cache_results=data.get("cache_results", True),
87
+ )
88
+ session.created_at = datetime.fromisoformat(data["created_at"])
89
+ session.accessed_at = datetime.fromisoformat(data["accessed_at"])
90
+ session.all_results = data.get("all_results", [])
91
+ session.backend_fetched_pages = data.get("backend_fetched_pages", [])
92
+ session.result_count = data.get("result_count", len(session.all_results))
93
+ return session
94
+
95
+
96
+ class SearchSessionManager:
97
+ """
98
+ Manages search sessions with Redis-backed storage.
99
+
100
+ Features:
101
+ - Create, read, update, delete search sessions
102
+ - Automatic TTL management
103
+ - Result caching and on-demand fetching
104
+ - Pagination support (offset and cursor-based)
105
+ """
106
+
107
+ def __init__(self):
108
+ self._redis = None
109
+ self._enabled = False
110
+ self._key_prefix = "search:session"
111
+ self._settings = get_settings()
112
+
113
+ # In-memory fallback (development only)
114
+ self._memory_store: dict[str, SearchSessionData] = {}
115
+
116
+ async def initialize(self):
117
+ """Initialize Redis connection"""
118
+ if self._redis is not None:
119
+ return
120
+
121
+ try:
122
+ from app.config.redis_cache import cache as redis_cache
123
+
124
+ if redis_cache and redis_cache._client:
125
+ self._redis = redis_cache._client
126
+ self._enabled = True
127
+ logger.info("Search Session Manager using Redis storage")
128
+ else:
129
+ logger.warning("Redis not available, using in-memory storage (development mode)")
130
+ self._enabled = False
131
+
132
+ except Exception as e:
133
+ logger.warning(f"Failed to initialize Redis for sessions: {e}. Using in-memory storage.")
134
+ self._enabled = False
135
+
136
+ async def close(self):
137
+ """Cleanup resources"""
138
+ # Redis connection is managed by redis_cache module
139
+ self._memory_store.clear()
140
+
141
+ def _generate_key(self, session_id: str) -> str:
142
+ """Generate Redis key for session"""
143
+ return f"{self._key_prefix}:{session_id}"
144
+
145
+ async def create_session(
146
+ self,
147
+ query: str,
148
+ results: list[dict],
149
+ total_results: int,
150
+ intent: dict | None = None,
151
+ page_size: int = 20,
152
+ max_results: int = 100,
153
+ ttl_minutes: int = 10,
154
+ cache_results: bool = True,
155
+ ) -> str:
156
+ """
157
+ Create a new search session with initial results.
158
+
159
+ Args:
160
+ query: Search query string
161
+ results: Initial list of results (first page)
162
+ total_results: Total number of results available
163
+ intent: Extracted intent data
164
+ page_size: Number of results per page
165
+ max_results: Maximum results to cache
166
+ ttl_minutes: Session TTL in minutes
167
+ cache_results: Whether to cache results in Redis
168
+
169
+ Returns:
170
+ Session ID
171
+ """
172
+ session_id = str(uuid.uuid4())
173
+
174
+ session_data = SearchSessionData(
175
+ session_id=session_id,
176
+ query=query,
177
+ total_results=total_results,
178
+ intent=intent,
179
+ page_size=page_size,
180
+ max_results=max_results,
181
+ ttl_minutes=ttl_minutes,
182
+ cache_results=cache_results,
183
+ )
184
+
185
+ # Store initial results
186
+ session_data.all_results = results[:max_results]
187
+ session_data.result_count = len(results)
188
+
189
+ # Store in Redis or memory
190
+ if self._enabled and self._redis:
191
+ key = self._generate_key(session_id)
192
+ ttl_seconds = ttl_minutes * 60
193
+ await self._redis.setex(
194
+ key,
195
+ ttl_seconds,
196
+ json.dumps(session_data.to_dict(), default=str),
197
+ )
198
+ logger.debug(f"Created session {session_id} in Redis (TTL: {ttl_seconds}s)")
199
+ else:
200
+ self._memory_store[session_id] = session_data
201
+ logger.debug(f"Created session {session_id} in memory")
202
+
203
+ return session_id
204
+
205
+ async def get_session(self, session_id: str) -> SearchSessionData | None:
206
+ """
207
+ Retrieve session by ID.
208
+
209
+ Args:
210
+ session_id: Session identifier
211
+
212
+ Returns:
213
+ SearchSessionData or None if not found/expired
214
+ """
215
+ if self._enabled and self._redis:
216
+ key = self._generate_key(session_id)
217
+ data = await self._redis.get(key)
218
+
219
+ if data:
220
+ # Update accessed_at timestamp
221
+ session_data = SearchSessionData.from_dict(json.loads(data))
222
+ session_data.accessed_at = datetime.now(UTC)
223
+
224
+ # Refresh TTL on access
225
+ ttl_seconds = session_data.ttl_minutes * 60
226
+ await self._redis.setex(
227
+ key,
228
+ ttl_seconds,
229
+ json.dumps(session_data.to_dict(), default=str),
230
+ )
231
+
232
+ return session_data
233
+ return None
234
+ session_data = self._memory_store.get(session_id)
235
+ if session_data:
236
+ session_data.accessed_at = datetime.now(UTC)
237
+ return session_data
238
+
239
+ async def update_session(self, session_data: SearchSessionData) -> bool:
240
+ """
241
+ Update session data.
242
+
243
+ Args:
244
+ session_data: Updated session data
245
+
246
+ Returns:
247
+ True if successful, False if session not found
248
+ """
249
+ session_data.accessed_at = datetime.now(UTC)
250
+
251
+ if self._enabled and self._redis:
252
+ key = self._generate_key(session_data.session_id)
253
+ exists = await self._redis.exists(key)
254
+
255
+ if not exists:
256
+ return False
257
+
258
+ ttl_seconds = session_data.ttl_minutes * 60
259
+ await self._redis.setex(
260
+ key,
261
+ ttl_seconds,
262
+ json.dumps(session_data.to_dict(), default=str),
263
+ )
264
+ return True
265
+ if session_data.session_id not in self._memory_store:
266
+ return False
267
+ self._memory_store[session_data.session_id] = session_data
268
+ return True
269
+
270
+ async def append_results(
271
+ self,
272
+ session_id: str,
273
+ results: list[dict],
274
+ start_index: int,
275
+ page_number: int | None = None,
276
+ ) -> bool:
277
+ """
278
+ Append new results to session cache.
279
+
280
+ Args:
281
+ session_id: Session identifier
282
+ results: New results to append
283
+ start_index: Index where results should start
284
+ page_number: Optional page number to track
285
+
286
+ Returns:
287
+ True if successful
288
+ """
289
+ session_data = await self.get_session(session_id)
290
+ if not session_data:
291
+ return False
292
+
293
+ # Extend all_results list if needed
294
+ current_len = len(session_data.all_results)
295
+ if start_index >= current_len:
296
+ # Pad with None if there's a gap
297
+ session_data.all_results.extend([None] * (start_index - current_len))
298
+ session_data.all_results.extend(results)
299
+ else:
300
+ # Insert at specific positions
301
+ for i, result in enumerate(results):
302
+ idx = start_index + i
303
+ if idx < len(session_data.all_results):
304
+ session_data.all_results[idx] = result
305
+ else:
306
+ session_data.all_results.append(result)
307
+
308
+ session_data.result_count = len([r for r in session_data.all_results if r is not None])
309
+
310
+ if page_number is not None and page_number not in session_data.backend_fetched_pages:
311
+ session_data.backend_fetched_pages.append(page_number)
312
+
313
+ return await self.update_session(session_data)
314
+
315
+ async def extend_ttl(self, session_id: str, additional_minutes: int) -> bool:
316
+ """
317
+ Extend session TTL.
318
+
319
+ Args:
320
+ session_id: Session identifier
321
+ additional_minutes: Minutes to add to TTL
322
+
323
+ Returns:
324
+ True if successful
325
+ """
326
+ session_data = await self.get_session(session_id)
327
+ if not session_data:
328
+ return False
329
+
330
+ session_data.ttl_minutes += additional_minutes
331
+ return await self.update_session(session_data)
332
+
333
+ async def delete_session(self, session_id: str) -> bool:
334
+ """
335
+ Delete a session.
336
+
337
+ Args:
338
+ session_id: Session identifier
339
+
340
+ Returns:
341
+ True if deleted, False if not found
342
+ """
343
+ if self._enabled and self._redis:
344
+ key = self._generate_key(session_id)
345
+ deleted = await self._redis.delete(key)
346
+ return deleted > 0
347
+ if session_id in self._memory_store:
348
+ del self._memory_store[session_id]
349
+ return True
350
+ return False
351
+
352
+ async def get_cached_results(
353
+ self,
354
+ session_id: str,
355
+ start_index: int,
356
+ page_size: int,
357
+ ) -> tuple[list[dict], bool]:
358
+ """
359
+ Get cached results for a specific range.
360
+
361
+ Args:
362
+ session_id: Session identifier
363
+ start_index: Starting index
364
+ page_size: Number of results to return
365
+
366
+ Returns:
367
+ Tuple of (results, has_more_in_cache)
368
+ """
369
+ session_data = await self.get_session(session_id)
370
+ if not session_data:
371
+ return [], False
372
+
373
+ end_index = start_index + page_size
374
+ cached_results = session_data.all_results[start_index:end_index]
375
+
376
+ # Filter out None values (from padding)
377
+ valid_results = [r for r in cached_results if r is not None]
378
+ has_more = end_index < len(session_data.all_results)
379
+
380
+ return valid_results, has_more
381
+
382
+ def calculate_pagination(
383
+ self,
384
+ page: int,
385
+ page_size: int,
386
+ total_cached: int,
387
+ total_available: int,
388
+ ) -> dict:
389
+ """
390
+ Calculate pagination metadata.
391
+
392
+ Args:
393
+ page: Current page number (1-indexed)
394
+ page_size: Results per page
395
+ total_cached: Total results in cache
396
+ total_available: Total results available from backend
397
+
398
+ Returns:
399
+ Pagination metadata
400
+ """
401
+ start_index = (page - 1) * page_size
402
+ end_index = start_index + page_size
403
+
404
+ return {
405
+ "page": page,
406
+ "page_size": page_size,
407
+ "start_index": start_index,
408
+ "end_index": min(end_index, total_available),
409
+ "has_more": end_index < total_available,
410
+ "total_cached": total_cached,
411
+ "total_available": total_available,
412
+ "cache_coverage": min(100, (total_cached / max(1, total_available)) * 100),
413
+ }
414
+
415
+ async def get_session_stats(self) -> dict:
416
+ """
417
+ Get session manager statistics.
418
+
419
+ Returns:
420
+ Statistics dictionary
421
+ """
422
+ stats = {
423
+ "storage_type": "redis" if self._enabled else "memory",
424
+ "enabled": self._enabled,
425
+ "active_sessions": 0,
426
+ }
427
+
428
+ if self._enabled and self._redis:
429
+ try:
430
+ keys = await self._redis.keys(f"{self._key_prefix}:*")
431
+ stats["active_sessions"] = len(keys)
432
+ except Exception as e:
433
+ logger.error(f"Error getting session stats: {e}")
434
+ else:
435
+ stats["active_sessions"] = len(self._memory_store)
436
+
437
+ return stats
438
+
439
+ async def cleanup_expired(self, grace_period_seconds: int = 60) -> int:
440
+ """
441
+ Clean up expired sessions (for manual cleanup).
442
+
443
+ Args:
444
+ grace_period_seconds: Extra time to wait after TTL expires
445
+
446
+ Returns:
447
+ Number of sessions deleted
448
+ """
449
+ import json
450
+ from datetime import UTC, datetime
451
+
452
+ deleted_count = 0
453
+ now = datetime.now(UTC)
454
+
455
+ if self._enabled and self._redis:
456
+ keys = await self._redis.keys(f"{self._key_prefix}:*")
457
+
458
+ for key in keys:
459
+ try:
460
+ session_data = await self._redis.get(key)
461
+ if not session_data:
462
+ continue
463
+
464
+ session = json.loads(session_data)
465
+ ttl_minutes = session.get("ttl_minutes", 10)
466
+ created_at_str = session.get("created_at")
467
+
468
+ if not created_at_str:
469
+ await self._redis.delete(key)
470
+ deleted_count += 1
471
+ continue
472
+
473
+ created_at = datetime.fromisoformat(created_at_str.replace("Z", "+00:00"))
474
+ age_seconds = (now - created_at).total_seconds()
475
+ ttl_seconds = (ttl_minutes * 60) + grace_period_seconds
476
+
477
+ if age_seconds > ttl_seconds:
478
+ await self._redis.delete(key)
479
+ deleted_count += 1
480
+ logger.debug(f"Deleted expired session: {key}")
481
+
482
+ except Exception as e:
483
+ logger.warning(f"Error cleaning up session {key}: {e}")
484
+ # Delete corrupted sessions
485
+ await self._redis.delete(key)
486
+ deleted_count += 1
487
+ else:
488
+ # Memory mode cleanup
489
+ expired = [
490
+ sid
491
+ for sid, session in self._memory_store.items()
492
+ if (now - session.created_at).total_seconds() > (session.ttl_minutes * 60) + grace_period_seconds
493
+ ]
494
+ for sid in expired:
495
+ del self._memory_store[sid]
496
+ deleted_count = len(expired)
497
+
498
+ if deleted_count > 0:
499
+ logger.info(f"Cleaned up {deleted_count} expired sessions")
500
+
501
+ return deleted_count
502
+
503
+
504
+ # Singleton instance
505
+ _session_manager: SearchSessionData | None = None
506
+
507
+
508
+ def get_session_manager() -> SearchSessionManager:
509
+ """Get or create session manager singleton"""
510
+ global _session_manager
511
+
512
+ if _session_manager is None:
513
+ _session_manager = SearchSessionManager()
514
+
515
+ return _session_manager
516
+
517
+
518
+ async def initialize_session_manager():
519
+ """Initialize session manager on application startup"""
520
+ manager = get_session_manager()
521
+ await manager.initialize()
522
+ logger.info("Search Session Manager initialized")
523
+
524
+
525
+ async def close_session_manager():
526
+ """Cleanup session manager on application shutdown"""
527
+ manager = get_session_manager()
528
+ await manager.close()
529
+ logger.info("Search Session Manager closed")
services/query_layer/app/config/settings.py ADDED
@@ -0,0 +1,513 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Centralized Configuration Management for Intent Engine.
3
+
4
+ This module provides a single source of truth for all configuration settings,
5
+ with validation, type safety, and environment variable management.
6
+
7
+ Usage:
8
+ from app.config.settings import settings
9
+
10
+ # Access settings
11
+ db_url = settings.database.effective_url
12
+ secret_key = settings.security.secret_key
13
+
14
+ # Validate at startup
15
+ settings.validate_production()
16
+ """
17
+
18
+ import os
19
+ from functools import lru_cache
20
+ from typing import Literal
21
+
22
+ from pydantic import Field, field_validator, model_validator
23
+ from pydantic_settings import BaseSettings, SettingsConfigDict
24
+
25
+
26
+ class DatabaseSettings(BaseSettings):
27
+ """Database configuration settings."""
28
+
29
+ model_config = SettingsConfigDict(
30
+ env_prefix="DATABASE_",
31
+ env_file=os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(__file__))), ".env"),
32
+ extra="ignore",
33
+ )
34
+
35
+ # Individual connection parameters
36
+ host: str = Field(default="localhost", description="Database host")
37
+ port: int = Field(default=5432, description="Database port")
38
+ name: str = Field(default="intent_engine", description="Database name")
39
+ user: str = Field(default="intent_user", description="Database user")
40
+ password: str = Field(
41
+ default="change_this_password_in_production",
42
+ description="Database password",
43
+ )
44
+
45
+ # Connection pool settings
46
+ pool_size: int = Field(default=10, ge=1, le=100, description="Connection pool size")
47
+ max_overflow: int = Field(default=20, ge=0, le=100, description="Max overflow connections")
48
+ pool_timeout: int = Field(default=30, ge=1, le=300, description="Pool timeout (seconds)")
49
+ pool_recycle: int = Field(default=1800, ge=60, le=7200, description="Pool recycle time (seconds)")
50
+
51
+ # Full connection URL (overrides individual params if set)
52
+ url: str | None = Field(
53
+ default=None,
54
+ description="Full database URL (overrides individual settings)",
55
+ )
56
+
57
+ # PgBouncer settings
58
+ pgbouncer_enabled: bool = Field(default=False, description="Enable PgBouncer connection pooling")
59
+ pgbouncer_host: str = Field(default="localhost", description="PgBouncer host")
60
+ pgbouncer_port: int = Field(default=6543, description="PgBouncer port")
61
+
62
+ @property
63
+ def effective_url(self) -> str:
64
+ """Get the effective database URL."""
65
+ if self.url:
66
+ return self.url
67
+
68
+ if self.pgbouncer_enabled:
69
+ host = self.pgbouncer_host
70
+ port = self.pgbouncer_port
71
+ else:
72
+ host = self.host
73
+ port = self.port
74
+
75
+ return f"postgresql://{self.user}:{self.password}@{host}:{port}/{self.name}"
76
+
77
+ @field_validator("password")
78
+ @classmethod
79
+ def validate_password(cls, v: str) -> str:
80
+ """Validate password strength in production."""
81
+ env = os.getenv("ENVIRONMENT", "development")
82
+ if env == "production":
83
+ if v in (
84
+ "change_this_password_in_production",
85
+ "password",
86
+ "admin",
87
+ "intent_secure_password_change_in_prod",
88
+ ):
89
+ raise ValueError("Weak database password detected. Please use a strong, unique password in production.")
90
+ if len(v) < 12:
91
+ raise ValueError("Database password must be at least 12 characters in production.")
92
+ return v
93
+
94
+
95
+ class RedisSettings(BaseSettings):
96
+ """Redis configuration settings."""
97
+
98
+ model_config = SettingsConfigDict(
99
+ env_prefix="REDIS_",
100
+ env_file=os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(__file__))), ".env"),
101
+ extra="ignore",
102
+ )
103
+
104
+ enabled: bool = Field(default=True, description="Enable Redis caching")
105
+ host: str = Field(default="localhost", description="Redis host")
106
+ port: int = Field(default=6379, description="Redis port")
107
+ db: int = Field(default=0, ge=0, le=15, description="Redis database number")
108
+ password: str | None = Field(default=None, description="Redis password")
109
+ url: str | None = Field(default=None, description="Full Redis URL (overrides individual settings)")
110
+
111
+ # Connection pool settings
112
+ max_connections: int = Field(default=50, ge=1, le=500, description="Max Redis connections")
113
+ timeout: float = Field(default=5.0, ge=0.1, le=60.0, description="Connection timeout (seconds)")
114
+
115
+ # SSL/TLS settings
116
+ ssl: bool = Field(default=False, description="Enable SSL/TLS for Redis")
117
+ ssl_cert_reqs: Literal["none", "optional", "required"] = Field(
118
+ default="none", description="SSL certificate requirements"
119
+ )
120
+
121
+ @property
122
+ def effective_url(self) -> str:
123
+ """Get the effective Redis URL."""
124
+ if self.url:
125
+ return self.url
126
+
127
+ scheme = "rediss" if self.ssl else "redis"
128
+ auth = f":{self.password}@" if self.password else ""
129
+ return f"{scheme}://{auth}{self.host}:{self.port}/{self.db}"
130
+
131
+ @field_validator("password")
132
+ @classmethod
133
+ def validate_password(cls, v: str | None) -> str | None:
134
+ """Warn about missing password in production."""
135
+ if os.getenv("ENVIRONMENT") == "production" and not v:
136
+ # Log warning but don't fail (Redis might be internal)
137
+ pass
138
+ return v
139
+
140
+
141
+ class SecuritySettings(BaseSettings):
142
+ """Security configuration settings."""
143
+
144
+ model_config = SettingsConfigDict(
145
+ env_file=os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(__file__))), ".env"),
146
+ extra="ignore",
147
+ )
148
+
149
+ secret_key: str = Field(
150
+ default="change-this-to-a-secure-random-string-in-production",
151
+ description="Application secret key for JWT signing",
152
+ )
153
+ algorithm: str = Field(default="HS256", description="JWT algorithm")
154
+ access_token_expire_minutes: int = Field(default=30, ge=1, le=1440, description="Access token expiry (minutes)")
155
+ refresh_token_expire_days: int = Field(default=7, ge=1, le=365, description="Refresh token expiry (days)")
156
+
157
+ # CORS settings
158
+ enable_cors: bool = Field(default=True, description="Enable CORS")
159
+ cors_origins: str = Field(
160
+ default="http://localhost:3000,http://localhost:8080",
161
+ description="Allowed CORS origins (comma-separated)",
162
+ )
163
+ cors_allow_credentials: bool = Field(default=True, description="Allow CORS credentials")
164
+ cors_allow_methods: str = Field(
165
+ default="GET,POST,PUT,DELETE,OPTIONS",
166
+ description="Allowed CORS methods",
167
+ )
168
+ cors_allow_headers: str = Field(
169
+ default="Authorization,Content-Type,X-Requested-With,X-Correlation-ID",
170
+ description="Allowed CORS headers",
171
+ )
172
+
173
+ # Rate limiting
174
+ rate_limit_enabled: bool = Field(default=True, description="Enable rate limiting")
175
+ rate_limit_default: str = Field(default="100/minute", description="Default rate limit")
176
+ rate_limit_strict: str = Field(default="10/minute", description="Strict rate limit")
177
+ rate_limit_storage_url: str = Field(
178
+ default="memory://",
179
+ description="Rate limit storage backend (use redis://... for production)",
180
+ )
181
+
182
+ # Session-specific rate limits
183
+ rate_limit_session_create: str = Field(default="100/hour", description="Session creation rate limit")
184
+ rate_limit_session_more: str = Field(default="300/hour", description="Session 'more results' rate limit")
185
+
186
+ @field_validator("secret_key")
187
+ @classmethod
188
+ def validate_secret_key(cls, v: str) -> str:
189
+ """Validate secret key strength."""
190
+ if os.getenv("ENVIRONMENT") == "production":
191
+ if v in (
192
+ "change-this-to-a-secure-random-string-in-production",
193
+ "secret",
194
+ "changeit",
195
+ ):
196
+ raise ValueError(
197
+ "Default SECRET_KEY detected. "
198
+ "Generate a secure random key for production: "
199
+ "python -c 'import secrets; print(secrets.token_urlsafe(32))'"
200
+ )
201
+ if len(v) < 32:
202
+ raise ValueError("SECRET_KEY must be at least 32 characters in production.")
203
+ return v
204
+
205
+ @property
206
+ def cors_origins_list(self) -> list[str]:
207
+ """Parse CORS origins into list."""
208
+ return [origin.strip() for origin in self.cors_origins.split(",")]
209
+
210
+ @property
211
+ def cors_allow_methods_list(self) -> list[str]:
212
+ """Parse CORS methods into list."""
213
+ return [method.strip() for method in self.cors_allow_methods.split(",")]
214
+
215
+ @property
216
+ def cors_allow_headers_list(self) -> list[str]:
217
+ """Parse CORS headers into list."""
218
+ return [header.strip() for header in self.cors_allow_headers.split(",")]
219
+
220
+
221
+ class SearXNGSettings(BaseSettings):
222
+ """SearXNG search engine settings."""
223
+
224
+ model_config = SettingsConfigDict(
225
+ env_prefix="SEARXNG_",
226
+ env_file=os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(__file__))), ".env"),
227
+ extra="ignore",
228
+ )
229
+
230
+ enabled: bool = Field(default=True, description="Enable SearXNG")
231
+ base_url: str = Field(default="http://localhost:8080", description="SearXNG URL")
232
+ secret_key: str = Field(
233
+ default="generate-with-openssl-rand-hex-32",
234
+ description="SearXNG secret key",
235
+ )
236
+ limiter: bool = Field(default=False, description="Enable SearXNG rate limiting")
237
+ image_proxy: bool = Field(default=True, description="Enable SearXNG image proxy")
238
+ categories: str = Field(
239
+ default="general,images,videos,news,science",
240
+ description="SearXNG search categories",
241
+ )
242
+
243
+ @field_validator("secret_key")
244
+ @classmethod
245
+ def validate_secret_key(cls, v: str) -> str:
246
+ """Warn about default secret key."""
247
+ if os.getenv("ENVIRONMENT") == "production":
248
+ if v in ("generate-with-openssl-rand-hex-32", "ultrasecret"):
249
+ raise ValueError(
250
+ "Default SEARXNG_SECRET_KEY detected. Generate a secure random key: openssl rand -hex 32"
251
+ )
252
+ return v
253
+
254
+
255
+ class MLSettings(BaseSettings):
256
+ """Machine learning model settings."""
257
+
258
+ model_config = SettingsConfigDict(
259
+ env_prefix="",
260
+ env_file=os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(__file__))), ".env"),
261
+ extra="ignore",
262
+ )
263
+
264
+ model_cache_dir: str = Field(default="./model_cache", description="Model cache directory")
265
+ sentence_transformers_model: str = Field(default="all-MiniLM-L6-v2", description="Sentence transformers model")
266
+ device: Literal["cpu", "cuda", "mps"] = Field(default="cpu", description="ML device (cpu, cuda, mps)")
267
+ transformers_cache: str = Field(default="./transformers_cache", description="Transformers cache directory")
268
+ hugging_face_token: str | None = Field(default=None, description="Hugging Face API token")
269
+
270
+
271
+ class PrivacySettings(BaseSettings):
272
+ """Privacy and GDPR compliance settings."""
273
+
274
+ model_config = SettingsConfigDict(
275
+ env_prefix="",
276
+ env_file=os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(__file__))), ".env"),
277
+ extra="ignore",
278
+ )
279
+
280
+ # Data retention (hours)
281
+ session_data_retention_hours: int = Field(default=8, ge=1, le=720, description="Session data retention (hours)")
282
+ analytics_data_retention_days: int = Field(default=90, ge=1, le=730, description="Analytics data retention (days)")
283
+ audit_log_retention_days: int = Field(default=365, ge=30, le=2555, description="Audit log retention (days)")
284
+
285
+ # Consent management
286
+ consent_required: bool = Field(default=True, description="Require user consent")
287
+ consent_expiry_days: int = Field(default=365, ge=1, le=730, description="Consent expiry (days)")
288
+
289
+ # Anonymization
290
+ enable_anonymization: bool = Field(default=True, description="Enable data anonymization")
291
+ anonymization_salt: str = Field(
292
+ default="generate-random-salt-for-anonymization",
293
+ description="Salt for anonymization",
294
+ )
295
+
296
+ @field_validator("anonymization_salt")
297
+ @classmethod
298
+ def validate_salt(cls, v: str) -> str:
299
+ """Validate anonymization salt."""
300
+ if os.getenv("ENVIRONMENT") == "production" and v in ("generate-random-salt-for-anonymization", "salt"):
301
+ raise ValueError("Default ANONYMIZATION_SALT detected. Generate a random salt for production.")
302
+ return v
303
+
304
+
305
+ class MonitoringSettings(BaseSettings):
306
+ """Monitoring and observability settings."""
307
+
308
+ model_config = SettingsConfigDict(
309
+ env_prefix="",
310
+ env_file=os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(__file__))), ".env"),
311
+ extra="ignore",
312
+ )
313
+
314
+ # Prometheus
315
+ enable_metrics: bool = Field(default=True, description="Enable Prometheus metrics")
316
+ metrics_port: int = Field(default=9090, description="Metrics port")
317
+
318
+ # Grafana
319
+ grafana_url: str = Field(default="http://localhost:3000", description="Grafana URL")
320
+ grafana_user: str = Field(default="admin", description="Grafana admin user")
321
+ grafana_password: str = Field(
322
+ default="change_this_grafana_password",
323
+ description="Grafana admin password",
324
+ )
325
+
326
+ # Health checks
327
+ health_check_interval: int = Field(default=30, ge=5, le=300, description="Health check interval (seconds)")
328
+ health_check_timeout: int = Field(default=10, ge=1, le=60, description="Health check timeout (seconds)")
329
+
330
+ # Distributed tracing
331
+ tracing_enabled: bool = Field(default=False, description="Enable distributed tracing")
332
+ tracing_endpoint: str = Field(default="http://localhost:4317", description="Tracing endpoint")
333
+ tracing_service_name: str = Field(default="intent-engine", description="Tracing service name")
334
+
335
+
336
+ class ApplicationSettings(BaseSettings):
337
+ """Main application settings."""
338
+
339
+ model_config = SettingsConfigDict(
340
+ env_prefix="",
341
+ env_file=os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(__file__))), ".env"),
342
+ extra="ignore",
343
+ )
344
+
345
+ # Environment
346
+ environment: Literal["development", "staging", "production"] = Field(
347
+ default="development",
348
+ description="Deployment environment",
349
+ )
350
+ app_name: str = Field(default="intent-engine", description="Application name")
351
+
352
+ # API settings
353
+ api_host: str = Field(default="0.0.0.0", description="API host")
354
+ api_port: int = Field(default=8000, description="API port")
355
+ workers: int | None = Field(default=None, description="Number of workers (auto)")
356
+
357
+ # Logging
358
+ log_level: Literal["DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL"] = Field(
359
+ default="INFO", description="Logging level"
360
+ )
361
+ log_format: Literal["json", "console"] = Field(default="console", description="Log format")
362
+
363
+ # Development
364
+ reload: bool = Field(default=False, description="Enable hot reload (dev only)")
365
+ debug: bool = Field(default=False, description="Enable debug mode")
366
+ ssl_verify: bool = Field(default=True, description="Enable SSL verification")
367
+
368
+ # Feature flags
369
+ feature_new_ranking_algorithm: bool = Field(default=False, description="Enable new ranking algorithm")
370
+ feature_advanced_fraud_detection: bool = Field(default=True, description="Enable advanced fraud detection")
371
+ feature_ab_testing: bool = Field(default=True, description="Enable A/B testing")
372
+ feature_real_time_analytics: bool = Field(default=True, description="Enable real-time analytics")
373
+
374
+ @model_validator(mode="after")
375
+ def validate_environment_config(self) -> "ApplicationSettings":
376
+ """Validate environment-specific configuration."""
377
+ if self.environment == "production":
378
+ if self.debug:
379
+ raise ValueError("DEBUG mode must be disabled in production")
380
+ if self.reload:
381
+ raise ValueError("Hot reload must be disabled in production")
382
+ return self
383
+
384
+
385
+ class Settings(BaseSettings):
386
+ """
387
+ Centralized settings class for Intent Engine.
388
+
389
+ All configuration is accessed through this single class, which aggregates
390
+ settings from environment variables and .env files.
391
+
392
+ Usage:
393
+ settings = Settings()
394
+
395
+ # Access nested settings
396
+ db_url = settings.database.effective_url
397
+ secret_key = settings.security.secret_key
398
+
399
+ # Validate for production
400
+ settings.validate_production()
401
+ """
402
+
403
+ model_config = SettingsConfigDict(
404
+ env_file=os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(__file__))), ".env"),
405
+ env_nested_delimiter="_",
406
+ extra="ignore",
407
+ )
408
+
409
+ # Nested settings objects
410
+ database: DatabaseSettings = Field(default_factory=DatabaseSettings)
411
+ redis: RedisSettings = Field(default_factory=RedisSettings)
412
+ security: SecuritySettings = Field(default_factory=SecuritySettings)
413
+ searxng: SearXNGSettings = Field(default_factory=SearXNGSettings)
414
+ ml: MLSettings = Field(default_factory=MLSettings)
415
+ privacy: PrivacySettings = Field(default_factory=PrivacySettings)
416
+ monitoring: MonitoringSettings = Field(default_factory=MonitoringSettings)
417
+ app: ApplicationSettings = Field(default_factory=ApplicationSettings)
418
+
419
+ def validate_production(self) -> list[str]:
420
+ """
421
+ Validate settings for production deployment.
422
+
423
+ Returns:
424
+ List of validation errors (empty if valid)
425
+ """
426
+ errors = []
427
+
428
+ if self.app.environment != "production":
429
+ return errors
430
+
431
+ # Check critical security settings
432
+ if "change" in self.security.secret_key.lower():
433
+ errors.append("SECRET_KEY must be changed in production")
434
+
435
+ if "change" in self.database.password.lower():
436
+ errors.append("DATABASE password must be changed in production")
437
+
438
+ # Check rate limiting storage
439
+ if self.security.rate_limit_storage_url == "memory://":
440
+ errors.append(
441
+ "RATE_LIMIT_STORAGE_URL should use Redis in production (memory:// doesn't work across multiple workers)"
442
+ )
443
+
444
+ # Check Redis configuration
445
+ if self.redis.enabled and self.app.environment == "production" and "localhost" in self.redis.host:
446
+ errors.append("Redis host should not be localhost in production (use a dedicated Redis instance)")
447
+
448
+ return errors
449
+
450
+ def validate_startup(self) -> None:
451
+ """
452
+ Validate critical settings at application startup.
453
+
454
+ Raises:
455
+ ValueError: If critical validation fails
456
+ """
457
+ errors = []
458
+
459
+ # Always validate secret key
460
+ if self.security.secret_key in (
461
+ "change-this-to-a-secure-random-string-in-production",
462
+ "secret",
463
+ "changeit",
464
+ ):
465
+ if self.app.environment == "production":
466
+ errors.append(
467
+ "CRITICAL: SECRET_KEY must be set in production. "
468
+ "Generate with: python -c 'import secrets; print(secrets.token_urlsafe(32))'"
469
+ )
470
+ else:
471
+ # Log warning for development
472
+ import logging
473
+
474
+ logging.getLogger("settings").warning(
475
+ "Using default SECRET_KEY in development. "
476
+ "This is fine for local development but must be changed for production."
477
+ )
478
+
479
+ # Validate database connection
480
+ if "change_this_password" in self.database.password and self.app.environment == "production":
481
+ errors.append("CRITICAL: DATABASE_PASSWORD must be changed in production")
482
+
483
+ if errors:
484
+ raise ValueError("\n".join(errors))
485
+
486
+ def get_rate_limit_storage_url(self) -> str:
487
+ """
488
+ Get the appropriate rate limit storage URL.
489
+
490
+ In production with Redis enabled, use Redis. Otherwise, use memory.
491
+ """
492
+ if (
493
+ self.app.environment == "production"
494
+ and self.redis.enabled
495
+ and self.security.rate_limit_storage_url == "memory://"
496
+ ):
497
+ # Override with Redis URL
498
+ return self.redis.effective_url
499
+ return self.security.rate_limit_storage_url
500
+
501
+
502
+ @lru_cache
503
+ def get_settings() -> Settings:
504
+ """
505
+ Get cached settings instance.
506
+
507
+ This ensures settings are loaded once and reused throughout the application.
508
+ """
509
+ return Settings()
510
+
511
+
512
+ # Global settings instance
513
+ settings = get_settings()
services/query_layer/app/config/tracing.py ADDED
@@ -0,0 +1,411 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Intent Engine - Distributed Tracing Configuration
3
+
4
+ Uses OpenTelemetry for distributed tracing with Jaeger/Prometheus integration.
5
+
6
+ Features:
7
+ - Automatic span creation
8
+ - Context propagation
9
+ - Performance monitoring
10
+ - Error tracking
11
+ - Integration with FastAPI
12
+
13
+ Usage:
14
+ setup_tracing()
15
+
16
+ @traced("custom_operation")
17
+ async def my_function():
18
+ # Your code here
19
+ pass
20
+ """
21
+
22
+ import logging
23
+ import os
24
+ from collections.abc import Callable
25
+ from contextlib import contextmanager
26
+ from functools import wraps
27
+ from typing import Any
28
+
29
+ logger = logging.getLogger(__name__)
30
+
31
+ # Global tracer reference
32
+ _tracer = None
33
+ _tracer_provider = None
34
+
35
+
36
+ def setup_tracing(service_name: str = "intent-engine") -> Any | None:
37
+ """
38
+ Setup distributed tracing with OpenTelemetry.
39
+
40
+ Supports multiple exporters:
41
+ - Jaeger (for development)
42
+ - OTLP (for production with Prometheus/Grafana)
43
+ - Console (for debugging)
44
+
45
+ Args:
46
+ service_name: Service name for tracing
47
+
48
+ Returns:
49
+ TracerProvider if successful, None otherwise
50
+ """
51
+ global _tracer, _tracer_provider
52
+
53
+ # Check if tracing is enabled
54
+ tracing_enabled = os.getenv("TRACING_ENABLED", "true").lower() == "true"
55
+ if not tracing_enabled:
56
+ logger.info("Distributed tracing disabled")
57
+ return None
58
+
59
+ # Get exporter configuration
60
+ exporter_type = os.getenv("TRACING_EXPORTER", "console").lower() # console, jaeger, otlp
61
+ jaeger_endpoint = os.getenv("JAEGER_ENDPOINT", "http://localhost:14268/api/traces")
62
+ otlp_endpoint = os.getenv("OTLP_ENDPOINT", "http://localhost:4317")
63
+
64
+ try:
65
+ from opentelemetry import trace
66
+ from opentelemetry.sdk.resources import Resource
67
+ from opentelemetry.sdk.trace import TracerProvider
68
+ from opentelemetry.sdk.trace.export import (
69
+ BatchSpanProcessor,
70
+ ConsoleSpanExporter,
71
+ )
72
+
73
+ # Create resource with service metadata
74
+ resource = Resource.create(
75
+ {
76
+ "service.name": service_name,
77
+ "service.version": os.getenv("VERSION", "1.0.0"),
78
+ "deployment.environment": os.getenv("ENVIRONMENT", "development"),
79
+ }
80
+ )
81
+
82
+ # Create tracer provider
83
+ provider = TracerProvider(resource=resource)
84
+
85
+ # Configure exporter
86
+ exporter = None
87
+ if exporter_type == "jaeger":
88
+ try:
89
+ from opentelemetry.exporter.jaeger.thrift import JaegerExporter
90
+
91
+ exporter = JaegerExporter(
92
+ agent_host_name=os.getenv("JAEGER_HOST", "localhost"),
93
+ agent_port=int(os.getenv("JAEGER_PORT", "6831")),
94
+ endpoint=jaeger_endpoint,
95
+ )
96
+ logger.info(f"Jaeger exporter configured: {jaeger_endpoint}")
97
+
98
+ except ImportError:
99
+ logger.warning("Jaeger exporter not installed, falling back to console")
100
+ exporter = ConsoleSpanExporter()
101
+
102
+ elif exporter_type == "otlp":
103
+ try:
104
+ from opentelemetry.exporter.otlp.proto.grpc.trace_exporter import (
105
+ OTLPSpanExporter,
106
+ )
107
+
108
+ exporter = OTLPSpanExporter(endpoint=otlp_endpoint)
109
+ logger.info(f"OTLP exporter configured: {otlp_endpoint}")
110
+
111
+ except ImportError:
112
+ logger.warning("OTLP exporter not installed, falling back to console")
113
+ exporter = ConsoleSpanExporter()
114
+
115
+ else:
116
+ exporter = ConsoleSpanExporter()
117
+ logger.info("Using console exporter for tracing")
118
+
119
+ # Add span processor
120
+ processor = BatchSpanProcessor(
121
+ exporter,
122
+ max_queue_size=2048,
123
+ scheduled_delay_millis=5000,
124
+ max_export_batch_size=512,
125
+ )
126
+ provider.add_span_processor(processor)
127
+
128
+ # Set global tracer provider
129
+ trace.set_tracer_provider(provider)
130
+ _tracer_provider = provider
131
+
132
+ # Get tracer
133
+ _tracer = trace.get_tracer(__name__)
134
+
135
+ logger.info(f"Distributed tracing setup complete: service={service_name}, exporter={exporter_type}")
136
+
137
+ return provider
138
+
139
+ except ImportError:
140
+ logger.warning(
141
+ "OpenTelemetry not installed. Install with: "
142
+ "pip install opentelemetry-api opentelemetry-sdk opentelemetry-exporter-jaeger"
143
+ )
144
+ return None
145
+ except Exception as e:
146
+ logger.error(f"Failed to setup tracing: {e}")
147
+ return None
148
+
149
+
150
+ def get_tracer() -> Any | None:
151
+ """Get the current tracer instance"""
152
+ return _tracer
153
+
154
+
155
+ def traced(span_name: str | None = None):
156
+ """
157
+ Decorator to trace a function or method.
158
+
159
+ Usage:
160
+ @traced()
161
+ async def my_function():
162
+ pass
163
+
164
+ @traced("custom_span_name")
165
+ def sync_function():
166
+ pass
167
+
168
+ Args:
169
+ span_name: Optional custom span name (defaults to function name)
170
+ """
171
+
172
+ def decorator(func: Callable) -> Callable:
173
+ tracer = get_tracer()
174
+
175
+ if not tracer:
176
+ # Tracing not enabled, return original function
177
+ return func
178
+
179
+ span_name_final = span_name or func.__name__
180
+
181
+ @wraps(func)
182
+ async def async_wrapper(*args, **kwargs):
183
+ with tracer.start_as_current_span(span_name_final) as span:
184
+ # Add function attributes to span
185
+ span.set_attribute("function.name", func.__name__)
186
+ span.set_attribute("function.module", func.__module__)
187
+
188
+ try:
189
+ result = await func(*args, **kwargs)
190
+ span.set_attribute("success", True)
191
+ return result
192
+ except Exception as e:
193
+ span.set_attribute("success", False)
194
+ span.record_exception(e)
195
+ raise
196
+
197
+ @wraps(func)
198
+ def sync_wrapper(*args, **kwargs):
199
+ with tracer.start_as_current_span(span_name_final) as span:
200
+ # Add function attributes to span
201
+ span.set_attribute("function.name", func.__name__)
202
+ span.set_attribute("function.module", func.__module__)
203
+
204
+ try:
205
+ result = func(*args, **kwargs)
206
+ span.set_attribute("success", True)
207
+ return result
208
+ except Exception as e:
209
+ span.set_attribute("success", False)
210
+ span.record_exception(e)
211
+ raise
212
+
213
+ # Detect if function is async
214
+ import inspect
215
+
216
+ if inspect.iscoroutinefunction(func):
217
+ return async_wrapper
218
+ return sync_wrapper
219
+
220
+ return decorator
221
+
222
+
223
+ @contextmanager
224
+ def trace_context(span_name: str, attributes: dict[str, Any] | None = None):
225
+ """
226
+ Context manager for tracing a code block.
227
+
228
+ Usage:
229
+ with trace_context("database_query", {"table": "users"}):
230
+ # Your code here
231
+ pass
232
+
233
+ Args:
234
+ span_name: Name of the span
235
+ attributes: Optional attributes to add to span
236
+ """
237
+ tracer = get_tracer()
238
+
239
+ if not tracer:
240
+ # Tracing not enabled, yield without context
241
+ yield
242
+ return
243
+
244
+ with tracer.start_as_current_span(span_name) as span:
245
+ if attributes:
246
+ for key, value in attributes.items():
247
+ span.set_attribute(key, value)
248
+
249
+ try:
250
+ yield span
251
+ except Exception as e:
252
+ span.set_attribute("error", True)
253
+ span.record_exception(e)
254
+ raise
255
+
256
+
257
+ def trace_async_context(span_name: str, attributes: dict[str, Any] | None = None):
258
+ """
259
+ Async context manager for tracing.
260
+
261
+ Usage:
262
+ async with trace_async_context("api_call"):
263
+ # Your async code here
264
+ pass
265
+ """
266
+ from contextlib import asynccontextmanager
267
+
268
+ @asynccontextmanager
269
+ async def async_trace_context():
270
+ tracer = get_tracer()
271
+
272
+ if not tracer:
273
+ yield
274
+ return
275
+
276
+ with tracer.start_as_current_span(span_name) as span:
277
+ if attributes:
278
+ for key, value in attributes.items():
279
+ span.set_attribute(key, value)
280
+
281
+ try:
282
+ yield span
283
+ except Exception as e:
284
+ span.set_attribute("error", True)
285
+ span.record_exception(e)
286
+ raise
287
+
288
+ return async_trace_context()
289
+
290
+
291
+ def add_span_attribute(key: str, value: Any):
292
+ """Add attribute to current active span"""
293
+ tracer = get_tracer()
294
+ if not tracer:
295
+ return
296
+
297
+ span = tracer.get_current_span()
298
+ if span and span.is_recording():
299
+ span.set_attribute(key, value)
300
+
301
+
302
+ def shutdown_tracing():
303
+ """Shutdown tracing and flush pending spans"""
304
+ global _tracer, _tracer_provider
305
+
306
+ if _tracer_provider:
307
+ try:
308
+ # Force flush pending spans
309
+ _tracer_provider.force_flush(timeout_millis=5000)
310
+ logger.info("Tracing spans flushed")
311
+
312
+ # Shutdown provider
313
+ _tracer_provider.shutdown()
314
+ logger.info("Tracing shutdown complete")
315
+
316
+ except Exception as e:
317
+ logger.warning(f"Failed to shutdown tracing: {e}")
318
+
319
+ finally:
320
+ _tracer = None
321
+ _tracer_provider = None
322
+
323
+
324
+ # FastAPI middleware integration
325
+ def setup_fastapi_tracing(app):
326
+ """
327
+ Setup tracing middleware for FastAPI application.
328
+
329
+ Args:
330
+ app: FastAPI application instance
331
+ """
332
+ try:
333
+ from opentelemetry.instrumentation.fastapi import FastAPIInstrumentor
334
+
335
+ FastAPIInstrumentor.instrument_app(app)
336
+ logger.info("FastAPI tracing instrumentation enabled")
337
+
338
+ except ImportError:
339
+ logger.warning(
340
+ "FastAPI instrumentation not available. Install with: pip install opentelemetry-instrumentation-fastapi"
341
+ )
342
+
343
+
344
+ # HTTP client instrumentation
345
+ def setup_httpx_tracing():
346
+ """Setup tracing for httpx HTTP client"""
347
+ try:
348
+ from opentelemetry.instrumentation.httpx import HTTPXClientInstrumentor
349
+
350
+ HTTPXClientInstrumentor().instrument()
351
+ logger.info("HTTPX client tracing enabled")
352
+
353
+ except ImportError:
354
+ logger.warning(
355
+ "HTTPX instrumentation not available. Install with: pip install opentelemetry-instrumentation-httpx"
356
+ )
357
+
358
+
359
+ # SQLAlchemy instrumentation
360
+ def setup_sqlalchemy_tracing():
361
+ """Setup tracing for SQLAlchemy database operations"""
362
+ try:
363
+ from opentelemetry.instrumentation.sqlalchemy import SQLAlchemyInstrumentor
364
+
365
+ SQLAlchemyInstrumentor().instrument()
366
+ logger.info("SQLAlchemy tracing enabled")
367
+
368
+ except ImportError:
369
+ logger.warning(
370
+ "SQLAlchemy instrumentation not available. "
371
+ "Install with: pip install opentelemetry-instrumentation-sqlalchemy"
372
+ )
373
+
374
+
375
+ # Redis instrumentation
376
+ def setup_redis_tracing():
377
+ """Setup tracing for Redis operations"""
378
+ try:
379
+ from opentelemetry.instrumentation.redis import RedisInstrumentor
380
+
381
+ RedisInstrumentor().instrument()
382
+ logger.info("Redis tracing enabled")
383
+
384
+ except ImportError:
385
+ logger.warning(
386
+ "Redis instrumentation not available. Install with: pip install opentelemetry-instrumentation-redis"
387
+ )
388
+
389
+
390
+ def setup_all_instrumentation():
391
+ """Setup all available instrumentation"""
392
+ setup_httpx_tracing()
393
+ setup_sqlalchemy_tracing()
394
+ setup_redis_tracing()
395
+
396
+
397
+ # Lifespan integration for FastAPI
398
+ @contextmanager
399
+ def tracing_lifespan(app):
400
+ """
401
+ Lifespan context manager for tracing setup/cleanup.
402
+
403
+ Usage with FastAPI:
404
+ app = FastAPI(lifespan=tracing_lifespan)
405
+ """
406
+ # Startup
407
+ setup_tracing()
408
+ setup_all_instrumentation()
409
+ yield
410
+ # Shutdown
411
+ shutdown_tracing()
services/query_layer/app/core/__init__.py ADDED
File without changes
services/query_layer/app/core/embedding_service.py ADDED
@@ -0,0 +1,349 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Intent Engine - Shared Embedding Service
3
+
4
+ This module provides a shared embedding service to eliminate duplicate model loading
5
+ across ranker, matcher, and recommender modules.
6
+ """
7
+
8
+ import hashlib
9
+ import logging
10
+ import threading
11
+ from typing import Optional, Any
12
+
13
+ import numpy as np
14
+
15
+ # Configure logging
16
+ logging.basicConfig(level=logging.INFO)
17
+ logger = logging.getLogger(__name__)
18
+
19
+
20
+ class EmbeddingService:
21
+ """
22
+ Shared embedding service for encoding text to vectors.
23
+
24
+ This singleton service loads the ML model once and shares it across
25
+ all components (ranker, matcher, recommender) to reduce memory usage
26
+ and improve initialization time.
27
+ """
28
+
29
+ _instance: Optional["EmbeddingService"] = None
30
+ _lock = threading.Lock()
31
+
32
+ def __init__(self):
33
+ self.cache: dict[str, np.ndarray] = {}
34
+ self.model = None
35
+ self.tokenizer = None
36
+ self.redis = None
37
+ self.cache_ttl = 3600 # 1 hour TTL for Redis cache
38
+ self._device = "cpu"
39
+ self._initialized = False
40
+ self._init_lock = threading.Lock()
41
+
42
+ def initialize(
43
+ self,
44
+ use_redis: bool = True,
45
+ model_name: str = None, # model_name ignored if session provided
46
+ onnx_session: Any = None,
47
+ tokenizer: Any = None,
48
+ ):
49
+ """
50
+ Initialize the embedding service with the ML model.
51
+ """
52
+ if self._initialized:
53
+ return
54
+
55
+ with self._init_lock:
56
+ if self._initialized:
57
+ return
58
+
59
+ if onnx_session and tokenizer:
60
+ self.model = onnx_session
61
+ self.tokenizer = tokenizer
62
+ logger.info("EmbeddingService initialized with shared ONNX session")
63
+ else:
64
+ self._load_model(model_name or "sentence-transformers/all-MiniLM-L6-v2")
65
+
66
+ if use_redis:
67
+ self._init_redis()
68
+
69
+ self._initialized = True
70
+ logger.info("EmbeddingService initialized successfully")
71
+
72
+ def _init_redis(self):
73
+ """Initialize Redis connection for caching"""
74
+ try:
75
+ import redis
76
+ import os
77
+
78
+ redis_url = os.getenv("REDIS_URL", "redis://redis:6379")
79
+ self.redis = redis.from_url(redis_url, decode_responses=False)
80
+ self.redis.ping()
81
+ logger.info("Redis connection established for embedding cache")
82
+ except Exception as e:
83
+ logger.warning(f"Redis not available for embedding cache: {e}")
84
+ self.redis = None
85
+
86
+ def _get_from_redis(self, text: str) -> np.ndarray | None:
87
+ """Get cached embedding from Redis"""
88
+ if self.redis is None:
89
+ return None
90
+ try:
91
+ key = f"emb:{hashlib.md5(text.encode()).hexdigest()}"
92
+ data = self.redis.get(key)
93
+ if data is not None:
94
+ return np.frombuffer(data, dtype=np.float32)
95
+ except Exception:
96
+ pass
97
+ return None
98
+
99
+ def _set_in_redis(self, text: str, embedding: np.ndarray):
100
+ """Store embedding in Redis cache"""
101
+ if self.redis is None:
102
+ return
103
+ try:
104
+ key = f"emb:{hashlib.md5(text.encode()).hexdigest()}"
105
+ self.redis.setex(key, self.cache_ttl, embedding.tobytes())
106
+ except Exception:
107
+ pass
108
+
109
+ def _load_model(self, model_name: str):
110
+ """Fallback to transformers if ONNX not provided"""
111
+ try:
112
+ from transformers import AutoModel, AutoTokenizer
113
+
114
+ self.tokenizer = AutoTokenizer.from_pretrained(model_name)
115
+ self.model = AutoModel.from_pretrained(model_name).to(self._device)
116
+ logger.info(f"Loaded embedding model via transformers: {model_name}")
117
+ except Exception as e:
118
+ logger.warning(
119
+ f"Failed to load transformers model: {e}. Using mock embeddings."
120
+ )
121
+ self.tokenizer = None
122
+ self.model = None
123
+
124
+ def encode_text(self, text: str) -> np.ndarray | None:
125
+ """Encode text using ONNX or transformers"""
126
+ if not self._initialized:
127
+ self.initialize()
128
+
129
+ if text in self.cache:
130
+ return self.cache[text]
131
+
132
+ redis_cached = self._get_from_redis(text)
133
+ if redis_cached is not None:
134
+ self.cache[text] = redis_cached
135
+ return redis_cached
136
+
137
+ if self.model is None or self.tokenizer is None:
138
+ # Mock implementation
139
+ result = np.random.rand(384).astype(np.float32)
140
+ self.cache[text] = result
141
+ return result
142
+
143
+ try:
144
+ # Use ONNX if available
145
+ if hasattr(self.model, "run"):
146
+ inputs = self.tokenizer(
147
+ text,
148
+ padding=True,
149
+ truncation=True,
150
+ max_length=128,
151
+ return_tensors="np",
152
+ )
153
+ model_inputs = {
154
+ "input_ids": inputs["input_ids"].astype(np.int64),
155
+ "attention_mask": inputs["attention_mask"].astype(np.int64),
156
+ "token_type_ids": inputs["token_type_ids"].astype(np.int64),
157
+ }
158
+ outputs = self.model.run(None, model_inputs)
159
+ last_hidden_state = outputs[0]
160
+ attention_mask = model_inputs["attention_mask"]
161
+ mask = np.expand_dims(attention_mask, axis=-1)
162
+ embeddings = np.sum(last_hidden_state * mask, axis=1) / np.sum(
163
+ mask, axis=1
164
+ )
165
+ norm = np.linalg.norm(embeddings, axis=1, keepdims=True)
166
+ result = (embeddings / norm)[0].astype(np.float32)
167
+ else:
168
+ # Use Transformers/Torch fallback
169
+ import torch
170
+
171
+ inputs = self.tokenizer(
172
+ text,
173
+ return_tensors="pt",
174
+ padding=True,
175
+ truncation=True,
176
+ max_length=512,
177
+ )
178
+ with torch.no_grad():
179
+ outputs = self.model(**inputs)
180
+ embeddings = outputs.last_hidden_state.mean(dim=1)
181
+ result = embeddings.cpu().numpy().flatten().astype(np.float32)
182
+
183
+ self.cache[text] = result
184
+ self._set_in_redis(text, result)
185
+ return result
186
+ except Exception as e:
187
+ logger.error(f"Error encoding text: {e}")
188
+ return None
189
+
190
+ def encode_batch(self, texts: list[str]) -> list[np.ndarray | None]:
191
+ """
192
+ Encode a batch of texts to embedding vectors efficiently.
193
+
194
+ Args:
195
+ texts: List of texts to encode
196
+
197
+ Returns:
198
+ List of embedding vectors (or None if encoding failed)
199
+ """
200
+ if not texts:
201
+ return []
202
+
203
+ if not self._initialized:
204
+ self.initialize()
205
+
206
+ if self.model is None or self.tokenizer is None:
207
+ # Return deterministic hash-based vectors for mock implementation
208
+ results = []
209
+ for text in texts:
210
+ hash_input = text.encode("utf-8")
211
+ hash_bytes = hashlib.md5(hash_input).digest()
212
+ # Create a 384-dim vector from hash
213
+ result = np.zeros(384, dtype=np.float32)
214
+ for i in range(384):
215
+ result[i] = (hash_bytes[i % 16] + i * 17) % 100 / 100.0
216
+ # Normalize the vector
217
+ norm = np.linalg.norm(result)
218
+ if norm > 0:
219
+ result = result / norm
220
+ results.append(result)
221
+ return results
222
+
223
+ # Filter out cached texts (check both local and Redis cache)
224
+ uncached_texts = []
225
+ uncached_indices = []
226
+ results: list[np.ndarray | None] = [None] * len(texts)
227
+
228
+ for i, text in enumerate(texts):
229
+ # Check local cache first
230
+ if text in self.cache:
231
+ results[i] = self.cache[text]
232
+ else:
233
+ # Check Redis cache
234
+ redis_cached = self._get_from_redis(text)
235
+ if redis_cached is not None:
236
+ results[i] = redis_cached
237
+ self.cache[text] = redis_cached # Also store in local cache
238
+ else:
239
+ uncached_texts.append(text)
240
+ uncached_indices.append(i)
241
+
242
+ if not uncached_texts:
243
+ # All texts were cached
244
+ return results
245
+
246
+ try:
247
+ import torch
248
+
249
+ # Tokenize all uncached texts in a batch
250
+ inputs = self.tokenizer(
251
+ uncached_texts,
252
+ return_tensors="pt",
253
+ padding=True,
254
+ truncation=True,
255
+ max_length=512,
256
+ )
257
+
258
+ # Move inputs to the same device as the model
259
+ device = next(self.model.parameters()).device
260
+ inputs = {k: v.to(device) for k, v in inputs.items()}
261
+
262
+ with torch.no_grad():
263
+ outputs = self.model(**inputs)
264
+ # Use mean pooling to get sentence embeddings
265
+ embeddings = outputs.last_hidden_state.mean(dim=1)
266
+
267
+ # Convert to numpy and cache results
268
+ numpy_embeddings = embeddings.cpu().numpy().astype(np.float32)
269
+
270
+ for idx, text_idx in enumerate(uncached_indices):
271
+ result = numpy_embeddings[idx].flatten()
272
+ results[text_idx] = result
273
+ text = texts[text_idx]
274
+ # Cache in both local and Redis
275
+ self.cache[text] = result
276
+ self._set_in_redis(text, result)
277
+
278
+ return results
279
+
280
+ except Exception as e:
281
+ logger.error(f"Error encoding batch: {e}")
282
+ # Fallback to individual encoding
283
+ for i, text in enumerate(texts):
284
+ if results[i] is None:
285
+ results[i] = self.encode_text(text)
286
+ return results
287
+
288
+ def cosine_similarity(self, vec1: np.ndarray, vec2: np.ndarray) -> float:
289
+ """
290
+ Calculate cosine similarity between two vectors.
291
+
292
+ Args:
293
+ vec1: First vector
294
+ vec2: Second vector
295
+
296
+ Returns:
297
+ Cosine similarity score between 0 and 1
298
+ """
299
+ dot_product = np.dot(vec1, vec2)
300
+ norm_vec1 = np.linalg.norm(vec1)
301
+ norm_vec2 = np.linalg.norm(vec2)
302
+
303
+ if norm_vec1 == 0 or norm_vec2 == 0:
304
+ return 0.0
305
+
306
+ return float(dot_product / (norm_vec1 * norm_vec2))
307
+
308
+ def clear_cache(self):
309
+ """Clear the local cache"""
310
+ self.cache.clear()
311
+ logger.debug("Embedding cache cleared")
312
+
313
+
314
+ # Global singleton instance
315
+ _embedding_service_instance: EmbeddingService | None = None
316
+ _embedding_service_lock = threading.Lock()
317
+
318
+
319
+ def get_embedding_service() -> EmbeddingService:
320
+ """
321
+ Get thread-safe singleton instance of EmbeddingService.
322
+
323
+ Uses double-checked locking pattern for thread safety.
324
+
325
+ Returns:
326
+ Shared EmbeddingService instance
327
+ """
328
+ global _embedding_service_instance
329
+ if _embedding_service_instance is None:
330
+ with _embedding_service_lock:
331
+ if _embedding_service_instance is None:
332
+ _embedding_service_instance = EmbeddingService()
333
+ return _embedding_service_instance
334
+
335
+
336
+ # Convenience functions for direct use
337
+ def encode_text(text: str) -> np.ndarray | None:
338
+ """Encode text to embedding vector"""
339
+ return get_embedding_service().encode_text(text)
340
+
341
+
342
+ def encode_batch(texts: list[str]) -> list[np.ndarray | None]:
343
+ """Encode batch of texts to embedding vectors"""
344
+ return get_embedding_service().encode_batch(texts)
345
+
346
+
347
+ def cosine_similarity(vec1: np.ndarray, vec2: np.ndarray) -> float:
348
+ """Calculate cosine similarity between two vectors"""
349
+ return get_embedding_service().cosine_similarity(vec1, vec2)
services/query_layer/app/core/exceptions.py ADDED
@@ -0,0 +1,249 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Intent Engine - Custom Exception Classes
3
+
4
+ This module defines custom exception classes for consistent error handling
5
+ across the Intent Engine API.
6
+ """
7
+
8
+ from typing import Any
9
+
10
+
11
+ class IntentEngineException(Exception):
12
+ """Base exception for all Intent Engine errors"""
13
+
14
+ def __init__(
15
+ self,
16
+ message: str,
17
+ status_code: int = 500,
18
+ details: dict[str, Any] | None = None,
19
+ ):
20
+ super().__init__(message)
21
+ self.message = message
22
+ self.status_code = status_code
23
+ self.details = details or {}
24
+
25
+
26
+ # Intent Extraction Exceptions
27
+ class IntentExtractionError(IntentEngineException):
28
+ """Error during intent extraction"""
29
+
30
+ def __init__(self, message: str, details: dict[str, Any] | None = None):
31
+ super().__init__(message, status_code=500, details=details)
32
+
33
+
34
+ class InvalidIntentError(IntentEngineException):
35
+ """Invalid intent data provided"""
36
+
37
+ def __init__(self, message: str, details: dict[str, Any] | None = None):
38
+ super().__init__(message, status_code=400, details=details)
39
+
40
+
41
+ class IntentExpiredError(IntentEngineException):
42
+ """Intent has expired"""
43
+
44
+ def __init__(self, message: str = "Intent has expired", details: dict[str, Any] | None = None):
45
+ super().__init__(message, status_code=400, details=details)
46
+
47
+
48
+ # Ranking Exceptions
49
+ class RankingError(IntentEngineException):
50
+ """Error during ranking process"""
51
+
52
+ def __init__(self, message: str, details: dict[str, Any] | None = None):
53
+ super().__init__(message, status_code=500, details=details)
54
+
55
+
56
+ class InvalidRankingInputError(IntentEngineException):
57
+ """Invalid input for ranking"""
58
+
59
+ def __init__(self, message: str, details: dict[str, Any] | None = None):
60
+ super().__init__(message, status_code=400, details=details)
61
+
62
+
63
+ # Service Recommendation Exceptions
64
+ class ServiceRecommendationError(IntentEngineException):
65
+ """Error during service recommendation"""
66
+
67
+ def __init__(self, message: str, details: dict[str, Any] | None = None):
68
+ super().__init__(message, status_code=500, details=details)
69
+
70
+
71
+ # Ad Matching Exceptions
72
+ class AdMatchingError(IntentEngineException):
73
+ """Error during ad matching"""
74
+
75
+ def __init__(self, message: str, details: dict[str, Any] | None = None):
76
+ super().__init__(message, status_code=500, details=details)
77
+
78
+
79
+ class NoMatchingAdsError(IntentEngineException):
80
+ """No ads matched the criteria"""
81
+
82
+ def __init__(
83
+ self,
84
+ message: str = "No matching ads found",
85
+ details: dict[str, Any] | None = None,
86
+ ):
87
+ super().__init__(message, status_code=404, details=details)
88
+
89
+
90
+ class AdFairnessViolationError(IntentEngineException):
91
+ """Ad violates fairness constraints"""
92
+
93
+ def __init__(self, message: str, details: dict[str, Any] | None = None):
94
+ super().__init__(message, status_code=400, details=details)
95
+
96
+
97
+ # Database Exceptions
98
+ class DatabaseError(IntentEngineException):
99
+ """Database operation failed"""
100
+
101
+ def __init__(self, message: str, details: dict[str, Any] | None = None):
102
+ super().__init__(message, status_code=500, details=details)
103
+
104
+
105
+ class NotFoundError(IntentEngineException):
106
+ """Requested resource not found"""
107
+
108
+ def __init__(self, resource: str, resource_id: Any, details: dict[str, Any] | None = None):
109
+ message = f"{resource} with ID {resource_id} not found"
110
+ super().__init__(
111
+ message,
112
+ status_code=404,
113
+ details=details or {"resource": resource, "id": resource_id},
114
+ )
115
+
116
+
117
+ class ValidationError(IntentEngineException):
118
+ """Data validation failed"""
119
+
120
+ def __init__(
121
+ self,
122
+ message: str,
123
+ field: str | None = None,
124
+ details: dict[str, Any] | None = None,
125
+ ):
126
+ details = details or {}
127
+ if field:
128
+ details["field"] = field
129
+ super().__init__(message, status_code=422, details=details)
130
+
131
+
132
+ # External Service Exceptions
133
+ class ExternalServiceError(IntentEngineException):
134
+ """External service (Redis, SearXNG) failed"""
135
+
136
+ def __init__(self, service: str, message: str, details: dict[str, Any] | None = None):
137
+ details = details or {}
138
+ details["service"] = service
139
+ super().__init__(message, status_code=503, details=details)
140
+
141
+
142
+ class ServiceUnavailableError(IntentEngineException):
143
+ """Required external service is unavailable"""
144
+
145
+ def __init__(self, service: str, message: str | None = None):
146
+ message = message or f"Service {service} is unavailable"
147
+ super().__init__(message, status_code=503, details={"service": service})
148
+
149
+
150
+ # Privacy & Compliance Exceptions
151
+ class PrivacyViolationError(IntentEngineException):
152
+ """Privacy policy violation detected"""
153
+
154
+ def __init__(self, message: str, details: dict[str, Any] | None = None):
155
+ super().__init__(message, status_code=400, details=details)
156
+
157
+
158
+ class ConsentRequiredError(IntentEngineException):
159
+ """User consent required but not obtained"""
160
+
161
+ def __init__(self, consent_type: str, details: dict[str, Any] | None = None):
162
+ message = f"Consent required for: {consent_type}"
163
+ super().__init__(message, status_code=403, details=details or {"consent_type": consent_type})
164
+
165
+
166
+ # Fraud Detection Exceptions
167
+ class FraudDetectedError(IntentEngineException):
168
+ """Fraudulent activity detected"""
169
+
170
+ def __init__(self, reason: str, severity: str = "high", details: dict[str, Any] | None = None):
171
+ details = details or {}
172
+ details["reason"] = reason
173
+ details["severity"] = severity
174
+ super().__init__(f"Fraud detected: {reason}", status_code=403, details=details)
175
+
176
+
177
+ # Campaign Management Exceptions
178
+ class CampaignError(IntentEngineException):
179
+ """Campaign operation failed"""
180
+
181
+ def __init__(self, message: str, details: dict[str, Any] | None = None):
182
+ super().__init__(message, status_code=500, details=details)
183
+
184
+
185
+ class BudgetExceededError(IntentEngineException):
186
+ """Campaign budget exceeded"""
187
+
188
+ def __init__(self, message: str, details: dict[str, Any] | None = None):
189
+ super().__init__(message, status_code=400, details=details)
190
+
191
+
192
+ # A/B Testing Exceptions
193
+ class ABTestError(IntentEngineException):
194
+ """A/B test operation failed"""
195
+
196
+ def __init__(self, message: str, details: dict[str, Any] | None = None):
197
+ super().__init__(message, status_code=500, details=details)
198
+
199
+
200
+ class ABTestNotFoundError(NotFoundError):
201
+ """A/B test not found"""
202
+
203
+ def __init__(self, test_id: Any):
204
+ super().__init__("A/B test", test_id)
205
+
206
+
207
+ # Exception handler for FastAPI
208
+ def register_exception_handlers(app):
209
+ """
210
+ Register exception handlers with FastAPI app.
211
+
212
+ Args:
213
+ app: FastAPI application instance
214
+ """
215
+ from fastapi import Request
216
+ from fastapi.responses import JSONResponse
217
+
218
+ @app.exception_handler(IntentEngineException)
219
+ async def intent_engine_exception_handler(request: Request, exc: IntentEngineException):
220
+ """Handle all Intent Engine exceptions"""
221
+ return JSONResponse(
222
+ status_code=exc.status_code,
223
+ content={
224
+ "error": {
225
+ "type": exc.__class__.__name__,
226
+ "message": exc.message,
227
+ "details": exc.details,
228
+ }
229
+ },
230
+ )
231
+
232
+ @app.exception_handler(Exception)
233
+ async def general_exception_handler(request: Request, exc: Exception):
234
+ """Handle unexpected exceptions"""
235
+ import logging
236
+
237
+ logger = logging.getLogger(__name__)
238
+ logger.error(f"Unexpected error: {exc}", exc_info=True)
239
+
240
+ return JSONResponse(
241
+ status_code=500,
242
+ content={
243
+ "error": {
244
+ "type": "InternalServerError",
245
+ "message": "An unexpected error occurred",
246
+ "details": {},
247
+ }
248
+ },
249
+ )
services/query_layer/app/core/schema.py ADDED
@@ -0,0 +1,332 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Intent Engine - Core Schema Definitions
3
+
4
+ This module defines the universal intent schema and related data structures
5
+ used across all components of the Intent Engine.
6
+ """
7
+
8
+ from dataclasses import dataclass, field
9
+ from enum import Enum
10
+ from typing import Any
11
+
12
+
13
+ # Define enums matching the TypeScript definitions from the docs
14
+ class IntentGoal(Enum):
15
+ # Search-specific
16
+ FIND_INFORMATION = "find_information"
17
+ COMPARISON = "comparison"
18
+ TROUBLESHOOTING = "troubleshooting"
19
+ PURCHASE = "purchase"
20
+ LOCAL_SERVICE = "local_service"
21
+ NAVIGATION = "navigation"
22
+
23
+ # Docs/Mail-specific
24
+ DRAFT_DOCUMENT = "draft_document"
25
+ COLLABORATE = "collaborate"
26
+ ORGANIZE = "organize"
27
+ ANALYZE = "analyze"
28
+ SCHEDULE = "schedule"
29
+
30
+ # Cross-product
31
+ LEARN = "learn"
32
+ CREATE = "create"
33
+ REFLECT = "reflect" # Diary
34
+
35
+ # Programming & Development
36
+ PROGRAMMING_ERROR = "programming_error"
37
+ CODE_DEBUG = "code_debug"
38
+ CODE_REVIEW = "code_review"
39
+ API_INTEGRATION = "api_integration"
40
+
41
+
42
+ class UseCase(Enum):
43
+ COMPARISON = "comparison"
44
+ LEARNING = "learning"
45
+ TROUBLESHOOTING = "troubleshooting"
46
+ VERIFICATION = "verification"
47
+ ENTERTAINMENT = "entertainment"
48
+ COMMUNITY_ENGAGEMENT = "community_engagement"
49
+ PROFESSIONAL_DEVELOPMENT = "professional_development"
50
+ MARKET_RESEARCH = "market_research"
51
+
52
+ # Programming & Development
53
+ DEBUGGING = "debugging"
54
+ CODE_FIX = "code_fix"
55
+ ERROR_RESOLUTION = "error_resolution"
56
+ CODE_OPTIMIZATION = "code_optimization"
57
+ LEARNING_TO_CODE = "learning_to_code"
58
+
59
+ # Product/Service contexts
60
+ GAMING = "gaming"
61
+ BUSINESS = "business"
62
+ CONTENT_CREATION = "content_creation"
63
+ STUDENT = "student"
64
+ CASUAL = "casual"
65
+
66
+
67
+ class ConstraintType(Enum):
68
+ INCLUSION = "inclusion"
69
+ EXCLUSION = "exclusion"
70
+ RANGE = "range"
71
+ DATATYPE = "datatype"
72
+
73
+
74
+ class Urgency(Enum):
75
+ IMMEDIATE = "immediate"
76
+ SOON = "soon"
77
+ FLEXIBLE = "flexible"
78
+ EXPLORATORY = "exploratory"
79
+
80
+
81
+ class SkillLevel(Enum):
82
+ BEGINNER = "beginner"
83
+ INTERMEDIATE = "intermediate"
84
+ ADVANCED = "advanced"
85
+ EXPERT = "expert"
86
+
87
+
88
+ class TemporalHorizon(Enum):
89
+ IMMEDIATE = "immediate"
90
+ TODAY = "today"
91
+ WEEK = "week"
92
+ MONTH = "month"
93
+ LONGTERM = "longterm"
94
+ FLEXIBLE = "flexible"
95
+
96
+
97
+ class Recency(Enum):
98
+ BREAKING = "breaking"
99
+ RECENT = "recent"
100
+ EVERGREEN = "evergreen"
101
+ HISTORICAL = "historical"
102
+
103
+
104
+ class Frequency(Enum):
105
+ ONEOFF = "oneoff"
106
+ RECURRING = "recurring"
107
+ EXPLORATORY = "exploratory"
108
+ FLEXIBLE = "flexible"
109
+
110
+
111
+ class EthicalDimension(Enum):
112
+ PRIVACY = "privacy"
113
+ SUSTAINABILITY = "sustainability"
114
+ ETHICS = "ethics"
115
+ ACCESSIBILITY = "accessibility"
116
+ OPENNESS = "openness"
117
+
118
+
119
+ class ResultType(Enum):
120
+ ANSWER = "answer"
121
+ TUTORIAL = "tutorial"
122
+ TOOL = "tool"
123
+ MARKETPLACE = "marketplace"
124
+ COMMUNITY = "community"
125
+
126
+ # Programming-specific
127
+ CODE_SNIPPET = "code_snippet"
128
+ DOCUMENTATION = "documentation"
129
+ STACK_OVERFLOW = "stack_overflow"
130
+ GITHUB_REPO = "github_repo"
131
+ API_REFERENCE = "api_reference"
132
+
133
+
134
+ class Complexity(Enum):
135
+ SIMPLE = "simple"
136
+ MODERATE = "moderate"
137
+ ADVANCED = "advanced"
138
+
139
+
140
+ class ContentType(Enum):
141
+ TEXT = "text"
142
+ SPREADSHEET = "spreadsheet"
143
+ PRESENTATION = "presentation"
144
+ FORM = "form"
145
+
146
+
147
+ class ProgrammingLanguage(Enum):
148
+ """Common programming languages for intent extraction"""
149
+
150
+ PYTHON = "python"
151
+ JAVASCRIPT = "javascript"
152
+ TYPESCRIPT = "typescript"
153
+ JAVA = "java"
154
+ C_SHARP = "csharp"
155
+ CPP = "cpp"
156
+ C = "c"
157
+ GO = "go"
158
+ RUST = "rust"
159
+ RUBY = "ruby"
160
+ PHP = "php"
161
+ SWIFT = "swift"
162
+ KOTLIN = "kotlin"
163
+ SQL = "sql"
164
+ SHELL = "shell"
165
+ HTML = "html"
166
+ CSS = "css"
167
+ UNKNOWN = "unknown"
168
+
169
+
170
+ class ErrorType(Enum):
171
+ """Types of programming errors"""
172
+
173
+ SYNTAX_ERROR = "syntax_error"
174
+ RUNTIME_ERROR = "runtime_error"
175
+ TYPE_ERROR = "type_error"
176
+ NULL_REFERENCE = "null_reference"
177
+ IMPORT_ERROR = "import_error"
178
+ AUTHENTICATION_ERROR = "authentication_error"
179
+ NETWORK_ERROR = "network_error"
180
+ DATABASE_ERROR = "database_error"
181
+ API_ERROR = "api_error"
182
+ COMPILATION_ERROR = "compilation_error"
183
+ MEMORY_ERROR = "memory_error"
184
+ PERMISSION_ERROR = "permission_error"
185
+ UNKNOWN = "unknown"
186
+
187
+
188
+ @dataclass
189
+ class Constraint:
190
+ """Represents a constraint extracted from user input"""
191
+
192
+ type: ConstraintType
193
+ dimension: str # 'language', 'region', 'price', 'license', 'format', 'recency'
194
+ value: str | int | float | list[str | int | float] | list[int] # Single value, range, or list
195
+ hardFilter: bool # Must exclude results violating this
196
+
197
+
198
+ @dataclass
199
+ class TemporalIntent:
200
+ """Temporal aspects of user intent"""
201
+
202
+ horizon: TemporalHorizon
203
+ recency: Recency
204
+ frequency: Frequency
205
+
206
+
207
+ @dataclass
208
+ class DocumentContext:
209
+ """Context from open documents"""
210
+
211
+ docId: str | None = None
212
+ content: str | None = None # First 1000 chars only, not persisted
213
+ lastEditTime: str | None = None
214
+ collaborators: int | None = None # Count only, not names
215
+ contentType: ContentType | None = None
216
+
217
+
218
+ @dataclass
219
+ class MeetingContext:
220
+ """Context from calendar/meetings"""
221
+
222
+ meetingId: str | None = None
223
+ subject: str | None = None
224
+ participantCount: int | None = None
225
+ isRecurring: bool | None = None
226
+ timeZone: str | None = None
227
+
228
+
229
+ @dataclass
230
+ class ProgrammingContext:
231
+ """Context for programming-related queries"""
232
+
233
+ language: ProgrammingLanguage = ProgrammingLanguage.UNKNOWN
234
+ errorType: ErrorType = ErrorType.UNKNOWN
235
+ errorCode: str | None = None # e.g., "E0301", "TS2304"
236
+ errorMessage: str | None = None # e.g., "NameError: name 'x' is not defined"
237
+ stackTrace: str | None = None # Full or partial stack trace
238
+ codeSnippet: str | None = None # Code snippet from the query
239
+ lineNumber: int | None = None # Line number where error occurred
240
+ fileName: str | None = None # File name from error
241
+ framework: str | None = None # e.g., "Django", "React", "Spring"
242
+ library: str | None = None # e.g., "pandas", "lodash", "requests"
243
+ isCompilationError: bool = False
244
+ isRuntimeError: bool = False
245
+ hasStackTrace: bool = False
246
+ confidence: float = 0.0 # Confidence that this is a programming error
247
+
248
+
249
+ @dataclass
250
+ class EthicalSignal:
251
+ """Ethical preferences extracted from intent"""
252
+
253
+ dimension: EthicalDimension
254
+ preference: str # "privacy-first", "open-source", "carbon-neutral", etc.
255
+
256
+
257
+ @dataclass
258
+ class DeclaredIntent:
259
+ """User-declared intent components"""
260
+
261
+ query: str | None = None # Free-form text
262
+ goal: IntentGoal | None = None # Structured goal
263
+ constraints: list[Constraint] = field(default_factory=list) # Hard filters
264
+ negativePreferences: list[str] = field(default_factory=list) # "not X", "no Y"
265
+ urgency: Urgency = Urgency.FLEXIBLE
266
+ budget: str | None = None # "under 1000", "premium", null
267
+ skillLevel: SkillLevel = SkillLevel.INTERMEDIATE
268
+
269
+
270
+ @dataclass
271
+ class InferredIntent:
272
+ """Inferred intent components"""
273
+
274
+ useCases: list[UseCase] = field(default_factory=list) # [comparison, learning, troubleshooting, ...]
275
+ temporalIntent: TemporalIntent | None = None
276
+ documentContext: DocumentContext | None = None # From open docs/emails
277
+ meetingContext: MeetingContext | None = None # From calendar/Meet
278
+ programmingContext: ProgrammingContext | None = None # From programming queries
279
+ resultType: ResultType | None = None
280
+ complexity: Complexity = Complexity.MODERATE
281
+ ethicalSignals: list[EthicalSignal] = field(default_factory=list) # Privacy, sustainability, etc.
282
+
283
+
284
+ @dataclass
285
+ class SessionFeedback:
286
+ """Feedback captured during the session"""
287
+
288
+ clicked: list[str] | None = None # URLs clicked
289
+ dwell: int | None = None # Seconds on result
290
+ reformulated: bool | None = None # User refined query
291
+ bounced: bool | None = None # Left immediately
292
+
293
+
294
+ @dataclass
295
+ class UniversalIntent:
296
+ """Main intent object matching the schema from the whitepaper"""
297
+
298
+ # Unique session-scoped ID (not persistent)
299
+ intentId: str
300
+
301
+ # Product context (which service generated this)
302
+ context: dict[str, Any]
303
+
304
+ # Declared intent (user-supplied constraints and goals)
305
+ declared: DeclaredIntent
306
+
307
+ # Inferred intent (derived from context without tracking)
308
+ inferred: InferredIntent
309
+
310
+ # Feedback (captured in current session only)
311
+ sessionFeedback: SessionFeedback = field(default_factory=SessionFeedback)
312
+
313
+ # TTL: Auto-delete after session ends
314
+ expiresAt: str = ""
315
+
316
+
317
+ @dataclass
318
+ class IntentExtractionRequest:
319
+ """Request object for intent extraction API"""
320
+
321
+ product: str # 'search' | 'docs' | 'mail' | 'calendar' | 'meet' | 'forms' | 'diary' | 'sites'
322
+ input: dict[str, str] # TextInput | FormInput | DocumentInput | EventInput
323
+ context: dict[str, Any] # ExtractionContext
324
+ options: dict[str, Any] | None = None # ExtractionOptions
325
+
326
+
327
+ @dataclass
328
+ class IntentExtractionResponse:
329
+ """Response object for intent extraction API"""
330
+
331
+ intent: UniversalIntent
332
+ extractionMetrics: dict[str, Any] # confidence, extractedDimensions, warnings
services/query_layer/app/core/utils.py ADDED
@@ -0,0 +1,100 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Intent Engine - Core Utilities
3
+
4
+ This module contains shared utilities used across all components of the Intent Engine.
5
+ """
6
+
7
+ import logging
8
+ import re
9
+ from datetime import UTC, datetime, timedelta
10
+
11
+ # Configure logging
12
+ logging.basicConfig(level=logging.INFO)
13
+ logger = logging.getLogger(__name__)
14
+
15
+
16
+ def extract_price_range(text: str) -> tuple | None:
17
+ """
18
+ Extract price range from text using regex patterns
19
+ Returns (operator, value) tuple or None
20
+ """
21
+ # Pattern to match prices like "under 100", "less than 50", etc.
22
+ patterns = [
23
+ r"\b(under|less than|below)\s*(\d+)\s*(?:rupees|rs|₹|dollars?|usd)?\b",
24
+ r"\b(over|more than|above)\s*(\d+)\s*(?:rupees|rs|₹|dollars?|usd)?\b",
25
+ r"\b(above|greater than)\s*(\d+)\s*(?:rupees|rs|₹|dollars?|usd)?\b",
26
+ ]
27
+
28
+ for pattern in patterns:
29
+ match = re.search(pattern, text.lower())
30
+ if match:
31
+ operator_word = match.group(1)
32
+ value = int(match.group(2))
33
+
34
+ # Map operator words to symbols
35
+ if operator_word in ["under", "less than", "below"]:
36
+ return ("<=", value)
37
+ if operator_word in ["over", "more than", "above", "greater than"]:
38
+ return (">=", value)
39
+
40
+ return None
41
+
42
+
43
+ def normalize_datetime(dt_str: str) -> datetime:
44
+ """
45
+ Normalize datetime string to a consistent format
46
+ """
47
+ try:
48
+ # Handle ISO format with Z suffix
49
+ if dt_str.endswith("Z"):
50
+ dt_str = dt_str[:-1] + "+00:00"
51
+
52
+ # Parse the datetime
53
+ if "+" in dt_str or dt_str.count("-") > 2: # Has timezone info
54
+ return datetime.fromisoformat(dt_str)
55
+ # Naive datetime, treat as UTC
56
+ return datetime.fromisoformat(dt_str).replace(tzinfo=UTC)
57
+ except ValueError:
58
+ # If parsing fails, return current time
59
+ return datetime.now(UTC)
60
+
61
+
62
+ def calculate_expiration_time(hours: int = 8) -> str:
63
+ """
64
+ Calculate expiration time (default 8 hours from now)
65
+ """
66
+ return (datetime.utcnow() + timedelta(hours=hours)).isoformat() + "Z"
67
+
68
+
69
+ def sanitize_input(text: str) -> str:
70
+ """
71
+ Sanitize user input to prevent injection attacks
72
+ """
73
+ # Remove potentially dangerous characters/sequences
74
+ sanitized = re.sub(r'[<>"\';]', "", text)
75
+ return sanitized.strip()
76
+
77
+
78
+ def get_current_timestamp() -> str:
79
+ """
80
+ Get current timestamp in ISO format
81
+ """
82
+ return datetime.utcnow().isoformat() + "Z"
83
+
84
+
85
+ def fuzzy_match(text1: str, text2: str, threshold: float = 0.7) -> bool:
86
+ """
87
+ Perform fuzzy matching between two texts
88
+ """
89
+ # Simple token-based similarity
90
+ tokens1 = set(text1.lower().split())
91
+ tokens2 = set(text2.lower().split())
92
+
93
+ intersection = tokens1.intersection(tokens2)
94
+ union = tokens1.union(tokens2)
95
+
96
+ if not union:
97
+ return False
98
+
99
+ similarity = len(intersection) / len(union)
100
+ return similarity >= threshold
services/query_layer/app/core/vector_store.py ADDED
@@ -0,0 +1,560 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Intent Engine - Vector Storage for Intent Embeddings
3
+
4
+ Uses Qdrant for storing and searching intent vectors.
5
+ Enables semantic search over intent-tagged web pages.
6
+
7
+ Features:
8
+ - Intent vector storage
9
+ - Semantic similarity search
10
+ - Intent-based filtering
11
+ - Batch operations
12
+ """
13
+
14
+ import hashlib
15
+ import logging
16
+ import os
17
+ from dataclasses import dataclass, field
18
+ from typing import Any
19
+
20
+ from app.core.embedding_service import get_embedding_service
21
+
22
+ logger = logging.getLogger(__name__)
23
+
24
+
25
+ @dataclass
26
+ class IntentVector:
27
+ """Intent vector with metadata for storage"""
28
+
29
+ id: str
30
+ url: str
31
+ embedding: list[float] = field(default_factory=list)
32
+ intent_tags: dict[str, Any] = field(default_factory=dict)
33
+ score: float = 0.5
34
+ title: str | None = None
35
+ description: str | None = None
36
+
37
+ def to_dict(self) -> dict[str, Any]:
38
+ """Convert to dictionary for storage"""
39
+ return {
40
+ "id": self.id,
41
+ "url": self.url,
42
+ "intent_tags": self.intent_tags,
43
+ "score": self.score,
44
+ "title": self.title,
45
+ "description": self.description,
46
+ }
47
+
48
+ @classmethod
49
+ def from_dict(cls, data: dict[str, Any]) -> "IntentVector":
50
+ """Create from dictionary"""
51
+ return cls(
52
+ id=data.get("id", ""),
53
+ url=data.get("url", ""),
54
+ intent_tags=data.get("intent_tags", {}),
55
+ score=data.get("score", 0.5),
56
+ title=data.get("title"),
57
+ description=data.get("description"),
58
+ )
59
+
60
+
61
+ class QdrantVectorStore:
62
+ """
63
+ Vector storage and search using Qdrant.
64
+
65
+ Usage:
66
+ store = QdrantVectorStore()
67
+ store.store_intent_vector(intent_vector)
68
+ results = store.search_similar(query_embedding, limit=10)
69
+
70
+ Features:
71
+ - Store intent vectors with metadata
72
+ - Semantic similarity search
73
+ - Filter by intent tags
74
+ - Batch operations
75
+ """
76
+
77
+ def __init__(self, config: dict[str, Any] | None = None):
78
+ self.config = config or {}
79
+ self.collection_name = self.config.get("collection", "intent_index")
80
+ self.qdrant_url = self.config.get(
81
+ "url", os.getenv("QDRANT_URL", "http://localhost:6333")
82
+ )
83
+ self.embedding_dim = self.config.get(
84
+ "embedding_dim", 384
85
+ ) # sentence-transformers
86
+
87
+ self._client = None
88
+ self._embedding_service = None
89
+ self._initialized = False
90
+
91
+ # Suppress aiohttp unclosed session warnings (Qdrant manages these internally)
92
+ logging.getLogger("aiohttp").setLevel(logging.ERROR)
93
+
94
+ logger.info(
95
+ f"QdrantVectorStore initialized: collection={self.collection_name}, url={self.qdrant_url}"
96
+ )
97
+
98
+ def _ensure_initialized(self):
99
+ """Lazy initialization of Qdrant client"""
100
+ if self._initialized:
101
+ return
102
+
103
+ try:
104
+ from qdrant_client import QdrantClient
105
+
106
+ self._client = QdrantClient(url=self.qdrant_url, timeout=10)
107
+
108
+ # Create collection if not exists
109
+ self._ensure_collection()
110
+
111
+ self._initialized = True
112
+ logger.info("Qdrant client initialized successfully")
113
+
114
+ except ImportError:
115
+ logger.warning(
116
+ "qdrant-client not installed. Install with: pip install qdrant-client"
117
+ )
118
+ self._client = None
119
+ except Exception as e:
120
+ logger.warning(f"Failed to initialize Qdrant client: {e}")
121
+ self._client = None
122
+
123
+ def _get_client(self) -> Any | None:
124
+ """Get Qdrant client"""
125
+ self._ensure_initialized()
126
+ return self._client
127
+
128
+ def _get_embedding_service(self):
129
+ """Get embedding service"""
130
+ if self._embedding_service is None:
131
+ self._embedding_service = get_embedding_service()
132
+ return self._embedding_service
133
+
134
+ def _ensure_collection(self):
135
+ """Create Qdrant collection if not exists"""
136
+ from qdrant_client.http.models import Distance, VectorParams
137
+
138
+ client = self._get_client()
139
+ if not client:
140
+ return
141
+
142
+ try:
143
+ collections = client.get_collections().collections
144
+ collection_names = [c.name for c in collections]
145
+
146
+ if self.collection_name not in collection_names:
147
+ # Create collection with specified embedding dimension
148
+ client.create_collection(
149
+ collection_name=self.collection_name,
150
+ vectors_config=VectorParams(
151
+ size=self.embedding_dim,
152
+ distance=Distance.COSINE,
153
+ ),
154
+ )
155
+ logger.info(f"Created Qdrant collection: {self.collection_name}")
156
+
157
+ # Create payload indexes for filtering
158
+ client.create_payload_index(
159
+ collection_name=self.collection_name,
160
+ field_name="intent_tags.primary_goal",
161
+ field_schema="keyword",
162
+ )
163
+ client.create_payload_index(
164
+ collection_name=self.collection_name,
165
+ field_name="intent_tags.skill_level",
166
+ field_schema="keyword",
167
+ )
168
+
169
+ logger.info(f"Created payload indexes for {self.collection_name}")
170
+
171
+ except Exception as e:
172
+ logger.warning(f"Failed to create collection: {e}")
173
+
174
+ def store_intent_vector(self, intent_vector: IntentVector) -> bool:
175
+ """
176
+ Store an intent vector.
177
+
178
+ Args:
179
+ intent_vector: IntentVector to store
180
+
181
+ Returns:
182
+ True if successful, False otherwise
183
+ """
184
+ from qdrant_client.http.models import PointStruct
185
+
186
+ client = self._get_client()
187
+ if not client:
188
+ logger.warning("Qdrant client not available")
189
+ return False
190
+
191
+ try:
192
+ # Generate ID from URL if not provided
193
+ if not intent_vector.id:
194
+ intent_vector.id = self._generate_id(intent_vector.url)
195
+
196
+ # Prepare payload
197
+ payload = {
198
+ "url": intent_vector.url,
199
+ "intent_tags": intent_vector.intent_tags,
200
+ "score": intent_vector.score,
201
+ "title": intent_vector.title,
202
+ "description": intent_vector.description,
203
+ }
204
+
205
+ # Create point
206
+ point = PointStruct(
207
+ id=self._hash_to_int(intent_vector.id),
208
+ vector=intent_vector.embedding,
209
+ payload=payload,
210
+ )
211
+
212
+ # Upsert point
213
+ client.upsert(
214
+ collection_name=self.collection_name,
215
+ points=[point],
216
+ )
217
+
218
+ logger.debug(f"Stored intent vector for {intent_vector.url}")
219
+ return True
220
+
221
+ except Exception as e:
222
+ logger.error(f"Failed to store intent vector: {e}")
223
+ return False
224
+
225
+ def store_intent_vectors(self, intent_vectors: list[IntentVector]) -> int:
226
+ """
227
+ Store multiple intent vectors in batch.
228
+
229
+ Args:
230
+ intent_vectors: List of IntentVector to store
231
+
232
+ Returns:
233
+ Number of successfully stored vectors
234
+ """
235
+ from qdrant_client.http.models import PointStruct
236
+
237
+ client = self._get_client()
238
+ if not client:
239
+ return 0
240
+
241
+ try:
242
+ points = []
243
+ for intent_vector in intent_vectors:
244
+ if not intent_vector.id:
245
+ intent_vector.id = self._generate_id(intent_vector.url)
246
+
247
+ payload = {
248
+ "url": intent_vector.url,
249
+ "intent_tags": intent_vector.intent_tags,
250
+ "score": intent_vector.score,
251
+ "title": intent_vector.title,
252
+ "description": intent_vector.description,
253
+ }
254
+
255
+ points.append(
256
+ PointStruct(
257
+ id=self._hash_to_int(intent_vector.id),
258
+ vector=intent_vector.embedding,
259
+ payload=payload,
260
+ )
261
+ )
262
+
263
+ client.upsert(
264
+ collection_name=self.collection_name,
265
+ points=points,
266
+ )
267
+
268
+ logger.info(f"Stored {len(points)} intent vectors")
269
+ return len(points)
270
+
271
+ except Exception as e:
272
+ logger.error(f"Failed to store batch: {e}")
273
+ return 0
274
+
275
+ def search_similar(
276
+ self,
277
+ query_embedding: list[float],
278
+ limit: int = 10,
279
+ filters: dict[str, Any] | None = None,
280
+ score_threshold: float | None = None,
281
+ ) -> list[IntentVector]:
282
+ """
283
+ Search for similar intent vectors.
284
+
285
+ Args:
286
+ query_embedding: Query embedding vector
287
+ limit: Maximum number of results
288
+ filters: Optional filters (e.g., {"primary_goal": "LEARN"})
289
+ score_threshold: Minimum similarity score threshold (0.0-1.0)
290
+
291
+ Returns:
292
+ List of IntentVector sorted by similarity
293
+ """
294
+ from qdrant_client.http.models import (
295
+ FieldCondition,
296
+ Filter,
297
+ MatchValue,
298
+ )
299
+
300
+ client = self._get_client()
301
+ if not client:
302
+ logger.warning("Qdrant client not available")
303
+ return []
304
+
305
+ try:
306
+ # Build filter
307
+ search_filter = None
308
+ if filters:
309
+ conditions = []
310
+ for key, value in filters.items():
311
+ conditions.append(
312
+ FieldCondition(
313
+ key=f"intent_tags.{key}",
314
+ match=MatchValue(value=value),
315
+ )
316
+ )
317
+
318
+ if conditions:
319
+ search_filter = Filter(must=conditions)
320
+
321
+ # Search with score threshold
322
+ results = client.search(
323
+ collection_name=self.collection_name,
324
+ query_vector=query_embedding,
325
+ limit=limit,
326
+ query_filter=search_filter,
327
+ score_threshold=score_threshold if score_threshold else None,
328
+ )
329
+
330
+ # Convert to IntentVector
331
+ intent_vectors = []
332
+ for r in results:
333
+ payload = r.payload or {}
334
+ intent_vectors.append(
335
+ IntentVector(
336
+ id=str(r.id),
337
+ url=payload.get("url", ""),
338
+ embedding=[], # Don't return embedding
339
+ intent_tags=payload.get("intent_tags", {}),
340
+ score=r.score,
341
+ title=payload.get("title"),
342
+ description=payload.get("description"),
343
+ )
344
+ )
345
+
346
+ logger.debug(f"Search returned {len(intent_vectors)} results")
347
+ return intent_vectors
348
+
349
+ except Exception as e:
350
+ logger.error(f"Search failed: {e}")
351
+ return []
352
+
353
+ def search_by_intent(
354
+ self,
355
+ goal: str | None = None,
356
+ use_case: str | None = None,
357
+ skill_level: str | None = None,
358
+ limit: int = 10,
359
+ ) -> list[IntentVector]:
360
+ """
361
+ Search by intent tags (filtered search).
362
+
363
+ Args:
364
+ goal: Filter by primary goal (e.g., "LEARN")
365
+ use_case: Filter by use case
366
+ skill_level: Filter by skill level
367
+ limit: Maximum results
368
+
369
+ Returns:
370
+ List of IntentVector matching filters
371
+ """
372
+ filters = {}
373
+
374
+ if goal:
375
+ filters["primary_goal"] = goal
376
+ if use_case:
377
+ filters["use_cases"] = use_case
378
+ if skill_level:
379
+ filters["skill_level"] = skill_level
380
+
381
+ # For tag-based search, we need to fetch and filter
382
+ # This is a simplified implementation
383
+ client = self._get_client()
384
+ if not client:
385
+ return []
386
+
387
+ try:
388
+ # Scroll through collection with filter
389
+ results, _ = client.scroll(
390
+ collection_name=self.collection_name,
391
+ limit=limit,
392
+ with_payload=True,
393
+ with_vectors=False,
394
+ )
395
+
396
+ # Filter results
397
+ filtered_vectors = []
398
+ for r in results:
399
+ payload = r.payload or {}
400
+ intent_tags = payload.get("intent_tags", {})
401
+
402
+ # Apply filters
403
+ match = True
404
+ if goal and intent_tags.get("primary_goal") != goal:
405
+ match = False
406
+ if use_case and use_case not in intent_tags.get("use_cases", []):
407
+ match = False
408
+ if skill_level and intent_tags.get("skill_level") != skill_level:
409
+ match = False
410
+
411
+ if match:
412
+ filtered_vectors.append(
413
+ IntentVector(
414
+ id=str(r.id),
415
+ url=payload.get("url", ""),
416
+ intent_tags=intent_tags,
417
+ score=payload.get("score", 0.0),
418
+ title=payload.get("title"),
419
+ description=payload.get("description"),
420
+ )
421
+ )
422
+
423
+ return filtered_vectors[:limit]
424
+
425
+ except Exception as e:
426
+ logger.error(f"Filtered search failed: {e}")
427
+ return []
428
+
429
+ def search_by_query(
430
+ self,
431
+ query: str,
432
+ limit: int = 10,
433
+ filters: dict[str, Any] | None = None,
434
+ ) -> list[IntentVector]:
435
+ """
436
+ Search by text query (generates embedding automatically).
437
+
438
+ Args:
439
+ query: Search query string
440
+ limit: Maximum results
441
+ filters: Optional filters
442
+
443
+ Returns:
444
+ List of IntentVector sorted by similarity
445
+ """
446
+ embedding_service = self._get_embedding_service()
447
+ if not embedding_service:
448
+ logger.warning("Embedding service not available")
449
+ return []
450
+
451
+ # Generate embedding
452
+ embedding = embedding_service.encode_text(query)
453
+ if embedding is None:
454
+ logger.warning("Failed to generate query embedding")
455
+ return []
456
+
457
+ # Search
458
+ return self.search_similar(
459
+ query_embedding=embedding.tolist(),
460
+ limit=limit,
461
+ filters=filters,
462
+ )
463
+
464
+ def delete_by_url(self, url: str) -> bool:
465
+ """
466
+ Delete intent vector by URL.
467
+
468
+ Args:
469
+ url: URL to delete
470
+
471
+ Returns:
472
+ True if successful, False otherwise
473
+ """
474
+ client = self._get_client()
475
+ if not client:
476
+ return False
477
+
478
+ try:
479
+ point_id = self._hash_to_int(self._generate_id(url))
480
+ client.delete(
481
+ collection_name=self.collection_name,
482
+ points_selector=[point_id],
483
+ )
484
+ logger.debug(f"Deleted intent vector for {url}")
485
+ return True
486
+ except Exception as e:
487
+ logger.error(f"Failed to delete: {e}")
488
+ return False
489
+
490
+ def count(self) -> int:
491
+ """Get total count of vectors in collection"""
492
+ client = self._get_client()
493
+ if not client:
494
+ return 0
495
+
496
+ try:
497
+ info = client.get_collection(self.collection_name)
498
+ return info.points_count or 0
499
+ except Exception as e:
500
+ logger.error(f"Failed to count: {e}")
501
+ return 0
502
+
503
+ def _generate_id(self, url: str) -> str:
504
+ """Generate unique ID from URL"""
505
+ return f"intent_{hashlib.md5(url.encode()).hexdigest()}"
506
+
507
+ def _hash_to_int(self, id_str: str) -> int:
508
+ """Convert string ID to integer for Qdrant"""
509
+ # Qdrant requires integer IDs, so we hash and truncate
510
+ return int(hashlib.md5(id_str.encode()).hexdigest()[:15], 16)
511
+
512
+ def close(self):
513
+ """Close Qdrant client and cleanup resources"""
514
+ if self._client:
515
+ try:
516
+ # Qdrant client uses aiohttp internally, close the session
517
+ if hasattr(self._client, "_client") and self._client._client:
518
+ import asyncio
519
+
520
+ try:
521
+ loop = asyncio.get_event_loop()
522
+ if loop.is_running():
523
+ asyncio.create_task(self._client._client.close())
524
+ else:
525
+ loop.run_until_complete(self._client._client.close())
526
+ except RuntimeError:
527
+ # No event loop, skip async cleanup
528
+ pass
529
+ logger.info("QdrantVectorStore closed")
530
+ except Exception as e:
531
+ logger.debug(f"Error closing QdrantVectorStore: {e}")
532
+ finally:
533
+ self._client = None
534
+ self._initialized = False
535
+
536
+
537
+ # Singleton instance
538
+ _vector_store: QdrantVectorStore | None = None
539
+
540
+
541
+ def get_vector_store(config: dict[str, Any] | None = None) -> QdrantVectorStore:
542
+ """
543
+ Get or create vector store singleton.
544
+
545
+ Args:
546
+ config: Optional configuration override
547
+
548
+ Returns:
549
+ QdrantVectorStore instance
550
+ """
551
+ global _vector_store
552
+ if _vector_store is None:
553
+ _vector_store = QdrantVectorStore(config)
554
+ return _vector_store
555
+
556
+
557
+ def reset_vector_store():
558
+ """Reset vector store singleton (useful for testing)"""
559
+ global _vector_store
560
+ _vector_store = None
services/query_layer/app/main.py ADDED
@@ -0,0 +1,430 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ IntentForge Unified Query & Ranking Layer
3
+
4
+ Combines semantic/hybrid search with advanced intent-aligned ranking.
5
+ """
6
+
7
+ import asyncio
8
+ import os
9
+ import time
10
+ import logging
11
+ from typing import List, Optional, Dict, Any
12
+
13
+ from math import exp
14
+
15
+ import numpy as np
16
+ import onnxruntime as ort
17
+ from qdrant_client import QdrantClient
18
+ from qdrant_client.http import models as qmodels
19
+ from fastapi import FastAPI, HTTPException, Query
20
+ from pydantic import BaseModel
21
+ from transformers import AutoTokenizer
22
+ from sentence_transformers import CrossEncoder
23
+
24
+ # Import ranking components
25
+ from app.ranking.optimized_ranker import (
26
+ rank_results,
27
+ RankingRequest as InternalRankingRequest,
28
+ SearchResult as InternalSearchResult,
29
+ )
30
+ from app.core.schema import UniversalIntent
31
+ from app.core.embedding_service import get_embedding_service
32
+
33
+ logging.basicConfig(level=logging.INFO)
34
+ logger = logging.getLogger("unified-layer")
35
+
36
+ # Configuration from environment
37
+ QDRANT_URL = os.getenv("QDRANT_URL", "http://localhost:6334")
38
+ QDRANT_API_KEY = os.getenv("QDRANT_API_KEY", None)
39
+ MODEL_PATH = os.getenv("MODEL_PATH", "/models/all-MiniLM-L6-v2.onnx")
40
+ TOKENIZER_NAME = os.getenv("TOKENIZER_NAME", "sentence-transformers/all-MiniLM-L6-v2")
41
+ INDEX_NAME = os.getenv("INDEX_NAME", "intentforge")
42
+
43
+ app = FastAPI(
44
+ title="IntentForge Unified Layer",
45
+ description="Unified API for Search and Intent Ranking",
46
+ version="0.2.0",
47
+ )
48
+
49
+ # Global state
50
+ model_session = None
51
+ tokenizer = None
52
+ cross_encoder_model = None
53
+
54
+ # Initialize Qdrant client
55
+ qdrant_client = QdrantClient(url=QDRANT_URL, api_key=QDRANT_API_KEY)
56
+
57
+ # --- Search Models ---
58
+
59
+
60
+ class SearchResult(BaseModel):
61
+ id: str
62
+ title: str
63
+ snippet: Optional[str] = None
64
+ url: str
65
+ source: str
66
+ category: str
67
+ intent_score: float
68
+ relevance_score: float
69
+ commercial_score: float = 0.0
70
+ spam_score: float = 0.0
71
+ score: float
72
+
73
+
74
+ class SearchResponse(BaseModel):
75
+ query: str
76
+ total_hits: int
77
+ results: List[SearchResult]
78
+ processing_time_ms: float
79
+
80
+
81
+ # --- Ranking Models ---
82
+
83
+
84
+ class SearchResultModel(BaseModel):
85
+ id: str
86
+ title: str
87
+ description: str
88
+ platform: Optional[str] = None
89
+ provider: Optional[str] = None
90
+ license: Optional[str] = None
91
+ price: Optional[float] = None
92
+ tags: Optional[List[str]] = None
93
+ qualityScore: Optional[float] = 0.5
94
+ recency: Optional[str] = None
95
+ complexity: Optional[str] = None
96
+ compatibility: Optional[List[str]] = None
97
+ privacyRating: Optional[float] = None
98
+ opensource: Optional[bool] = None
99
+
100
+
101
+ class RankingAPIRequest(BaseModel):
102
+ intent: UniversalIntent
103
+ candidates: List[SearchResultModel]
104
+ options: Optional[dict] = None
105
+
106
+
107
+ @app.on_event("startup")
108
+ async def startup_event():
109
+ global model_session, tokenizer
110
+
111
+ # Load tokenizer
112
+ logger.info(f"Loading tokenizer: {TOKENIZER_NAME}")
113
+ try:
114
+ tokenizer = AutoTokenizer.from_pretrained(TOKENIZER_NAME)
115
+ except Exception as e:
116
+ logger.error(f"Failed to load tokenizer: {e}")
117
+ # Fallback to local path
118
+ try:
119
+ tokenizer = AutoTokenizer.from_pretrained("/models/")
120
+ except Exception:
121
+ pass
122
+
123
+ # Load ONNX model for embeddings
124
+ if os.path.exists(MODEL_PATH):
125
+ logger.info(f"Loading ONNX model: {MODEL_PATH}")
126
+ try:
127
+ model_session = ort.InferenceSession(MODEL_PATH)
128
+ except Exception as e:
129
+ logger.error(f"Failed to load ONNX model: {e}")
130
+ else:
131
+ logger.warning(
132
+ f"ONNX model not found at {MODEL_PATH}. Semantic search fallback will be used."
133
+ )
134
+
135
+ # Initialize shared EmbeddingService with ONNX session
136
+ if model_session and tokenizer:
137
+ logger.info("Initializing shared EmbeddingService with ONNX session")
138
+ emb_service = get_embedding_service()
139
+ emb_service.initialize(onnx_session=model_session, tokenizer=tokenizer)
140
+
141
+ # Load cross-encoder model for reranking
142
+ global cross_encoder_model
143
+ try:
144
+ logger.info("Loading cross-encoder model: cross-encoder/ms-marco-MiniLM-L6-v2")
145
+ cross_encoder_model = CrossEncoder("cross-encoder/ms-marco-MiniLM-L6-v2")
146
+ logger.info("Cross-encoder model loaded successfully")
147
+ except Exception as e:
148
+ logger.error(
149
+ f"Failed to load cross-encoder model: {e}. Falling back to bi-encoder cosine similarity for reranking."
150
+ )
151
+ cross_encoder_model = None
152
+
153
+
154
+ # --- Shared Logic ---
155
+
156
+
157
+ def generate_embedding(query: str) -> Optional[List[float]]:
158
+ emb_service = get_embedding_service()
159
+ vector = emb_service.encode_text(query)
160
+ return vector.tolist() if vector is not None else None
161
+
162
+
163
+ def cosine_similarity(a: List[float], b: List[float]) -> float:
164
+ a_arr = np.array(a)
165
+ b_arr = np.array(b)
166
+ dot = np.dot(a_arr, b_arr)
167
+ norm_a = np.linalg.norm(a_arr)
168
+ norm_b = np.linalg.norm(b_arr)
169
+ if norm_a == 0 or norm_b == 0:
170
+ return 0.0
171
+ return float(dot / (norm_a * norm_b))
172
+
173
+
174
+ # --- Endpoints ---
175
+
176
+
177
+ @app.get("/health")
178
+ async def health():
179
+ return {
180
+ "status": "healthy",
181
+ "service": "unified-layer",
182
+ "model_loaded": model_session is not None,
183
+ "tokenizer_loaded": tokenizer is not None,
184
+ "cross_encoder_loaded": cross_encoder_model is not None,
185
+ "meili_connection": True, # Basic check
186
+ }
187
+
188
+
189
+ class RerankResult(BaseModel):
190
+ id: str
191
+ score: float
192
+
193
+
194
+ class RerankRequest(BaseModel):
195
+ query: str
196
+ candidates: List[Dict[str, Any]]
197
+
198
+
199
+ class RerankResponse(BaseModel):
200
+ results: List[RerankResult]
201
+ processing_time_ms: float
202
+
203
+
204
+ @app.post("/rerank", response_model=RerankResponse)
205
+ async def rerank_endpoint(request: RerankRequest):
206
+ """
207
+ Rerank candidates using a true cross-encoder model (ms-marco-MiniLM-L6-v2).
208
+ Falls back to bi-encoder cosine similarity if the cross-encoder is unavailable.
209
+ """
210
+ start_time = time.time()
211
+
212
+ if not request.candidates:
213
+ return RerankResponse(results=[], processing_time_ms=0.0)
214
+
215
+ if cross_encoder_model is not None:
216
+ # --- True cross-encoder reranking ---
217
+ pairs = []
218
+ ids = []
219
+ for cand in request.candidates:
220
+ cand_text = f"{cand.get('title', '')} {cand.get('description', '')}"
221
+ pairs.append((request.query, cand_text))
222
+ ids.append(cand.get("id", ""))
223
+
224
+ try:
225
+ raw_scores = await asyncio.to_thread(cross_encoder_model.predict, pairs)
226
+ # Normalize logits to 0-1 via sigmoid
227
+ results = [
228
+ RerankResult(
229
+ id=ids[i], score=float(1 / (1 + exp(-float(raw_scores[i]))))
230
+ )
231
+ for i in range(len(ids))
232
+ ]
233
+ except Exception as e:
234
+ logger.error(
235
+ f"Cross-encoder prediction failed: {e}. Falling back to cosine similarity."
236
+ )
237
+ results = _cosine_fallback_rerank(request)
238
+ else:
239
+ # --- Fallback: bi-encoder cosine similarity ---
240
+ results = _cosine_fallback_rerank(request)
241
+
242
+ # Sort by score descending
243
+ results.sort(key=lambda x: x.score, reverse=True)
244
+
245
+ return RerankResponse(
246
+ results=results, processing_time_ms=(time.time() - start_time) * 1000
247
+ )
248
+
249
+
250
+ def _cosine_fallback_rerank(request: RerankRequest) -> List[RerankResult]:
251
+ """Fallback reranking using bi-encoder cosine similarity."""
252
+ emb_service = get_embedding_service()
253
+ query_vec = emb_service.encode_text(request.query)
254
+
255
+ if query_vec is None:
256
+ raise HTTPException(status_code=500, detail="Failed to encode query")
257
+
258
+ results = []
259
+ for cand in request.candidates:
260
+ cand_text = f"{cand.get('title', '')} {cand.get('description', '')}"
261
+ cand_vec = emb_service.encode_text(cand_text)
262
+
263
+ if cand_vec is not None:
264
+ score = float(
265
+ np.dot(query_vec, cand_vec)
266
+ / (np.linalg.norm(query_vec) * np.linalg.norm(cand_vec))
267
+ )
268
+ results.append(RerankResult(id=cand.get("id", ""), score=score))
269
+ else:
270
+ results.append(RerankResult(id=cand.get("id", ""), score=0.0))
271
+
272
+ return results
273
+
274
+
275
+ @app.get("/search", response_model=SearchResponse)
276
+ async def search(
277
+ q: str = Query(..., description="The search query"),
278
+ limit: int = Query(10, ge=1, le=100),
279
+ offset: int = Query(0, ge=0),
280
+ category: Optional[str] = None,
281
+ media_type: str = Query(
282
+ "text", description="Filter by media type: text, image, video"
283
+ ),
284
+ semantic_ratio: float = Query(0.0, ge=0.0, le=1.0),
285
+ ):
286
+ start_time = time.time()
287
+ embedding = generate_embedding(q) if semantic_ratio > 0.0 else None
288
+
289
+ # Re-ranking depth
290
+ fetch_limit = 100 if embedding else limit
291
+
292
+ # Build Qdrant filter
293
+ filter_conditions = []
294
+ if category:
295
+ filter_conditions.append(
296
+ qmodels.FieldCondition(
297
+ key="category", match=qmodels.MatchValue(value=category)
298
+ )
299
+ )
300
+ if media_type:
301
+ filter_conditions.append(
302
+ qmodels.FieldCondition(
303
+ key="media_type", match=qmodels.MatchValue(value=media_type)
304
+ )
305
+ )
306
+
307
+ query_filter = qmodels.Filter(must=filter_conditions) if filter_conditions else None
308
+
309
+ try:
310
+ if embedding:
311
+ # Semantic Search
312
+ search_result = qdrant_client.search(
313
+ collection_name=INDEX_NAME,
314
+ query_vector=embedding,
315
+ query_filter=query_filter,
316
+ limit=fetch_limit,
317
+ offset=offset,
318
+ with_payload=True,
319
+ with_vectors=True,
320
+ )
321
+ else:
322
+ # Full-text Fallback (using Qdrant MatchText)
323
+ # Since Qdrant doesn't have a top-level 'search' for text without vector,
324
+ # we use a dummy vector or better, just retrieve with text filter.
325
+ # But Qdrant 1.10+ supports Query API which is better.
326
+ # For simplicity, we'll use a zero vector if no embedding is generated.
327
+ search_result = qdrant_client.search(
328
+ collection_name=INDEX_NAME,
329
+ query_vector=[0.0] * 384,
330
+ query_filter=qmodels.Filter(
331
+ must=[
332
+ qmodels.FieldCondition(
333
+ key="title", match=qmodels.MatchText(text=q)
334
+ )
335
+ ]
336
+ + (filter_conditions or [])
337
+ ),
338
+ limit=fetch_limit,
339
+ offset=offset,
340
+ with_payload=True,
341
+ with_vectors=True,
342
+ )
343
+ except Exception as e:
344
+ logger.error(f"Qdrant search failed: {e}")
345
+ return SearchResponse(
346
+ query=q,
347
+ total_hits=0,
348
+ results=[],
349
+ processing_time_ms=(time.time() - start_time) * 1000,
350
+ )
351
+
352
+ scored_results = []
353
+ for hit in search_result:
354
+ payload = hit.payload
355
+
356
+ # Original scores from crawler
357
+ calc_intent = payload.get("intent_score", 0.5)
358
+ calc_rel = payload.get("relevance_score", 0.5)
359
+
360
+ # If we have an embedding, we can use the Qdrant score (cosine similarity)
361
+ # to refine the intent score
362
+ if embedding:
363
+ # hit.score is the cosine similarity from Qdrant
364
+ intent_sim = hit.score
365
+ calc_intent = intent_sim * 0.5 + calc_intent * 0.5
366
+
367
+ final_score = calc_intent * semantic_ratio + calc_rel * (1.0 - semantic_ratio)
368
+ scored_results.append((final_score, calc_intent, calc_rel, hit))
369
+
370
+ scored_results.sort(key=lambda x: x[0], reverse=True)
371
+
372
+ hits = []
373
+ for _, calc_intent, calc_rel, hit in scored_results[:limit]:
374
+ payload = hit.payload
375
+ # Snippet generation (Qdrant doesn't have auto-crop in basic search)
376
+ content = payload.get("content", "")
377
+ snippet = content[:160] + "..." if len(content) > 160 else content
378
+
379
+ hits.append(
380
+ SearchResult(
381
+ id=payload.get("id", str(hit.id)),
382
+ title=payload.get("title", "Untitled"),
383
+ snippet=snippet,
384
+ url=payload.get("url", ""),
385
+ source=payload.get("source", "unknown"),
386
+ category=payload.get("category", "general"),
387
+ intent_score=float(calc_intent),
388
+ relevance_score=float(calc_rel),
389
+ commercial_score=float(payload.get("commercial_score", 0.0)),
390
+ spam_score=float(payload.get("spam_score", 0.0)),
391
+ score=final_score,
392
+ )
393
+ )
394
+
395
+ return SearchResponse(
396
+ query=q,
397
+ total_hits=len(
398
+ search_result
399
+ ), # Qdrant search() doesn't return total count easily without separate count()
400
+ results=hits,
401
+ processing_time_ms=(time.time() - start_time) * 1000,
402
+ )
403
+
404
+
405
+ @app.post("/rank")
406
+ async def rank_candidates(request: RankingAPIRequest):
407
+ try:
408
+ # Convert Pydantic models to internal dataclasses
409
+ internal_candidates = [
410
+ InternalSearchResult(**c.model_dump()) for c in request.candidates
411
+ ]
412
+
413
+ internal_request = InternalRankingRequest(
414
+ intent=request.intent,
415
+ candidates=internal_candidates,
416
+ options=request.options,
417
+ )
418
+
419
+ # Perform ranking using the OptimizedIntentRanker
420
+ response = rank_results(internal_request)
421
+ return response
422
+ except Exception as e:
423
+ logger.error(f"Ranking failed: {e}")
424
+ raise HTTPException(status_code=500, detail=str(e))
425
+
426
+
427
+ if __name__ == "__main__":
428
+ import uvicorn
429
+
430
+ uvicorn.run(app, host="0.0.0.0", port=8000)
services/query_layer/app/models.py ADDED
@@ -0,0 +1,735 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Intent Engine - Pydantic Models
3
+
4
+ This module defines Pydantic models for all entities and requests used in the API.
5
+ """
6
+
7
+ from datetime import date, datetime
8
+ from typing import Any
9
+
10
+ from pydantic import BaseModel, ConfigDict, Field
11
+
12
+ from app.core.schema import UniversalIntent
13
+
14
+
15
+ # Database entity models
16
+ class AdvertiserBase(BaseModel):
17
+ name: str
18
+ contact_email: str | None = None
19
+
20
+
21
+ class AdvertiserCreate(AdvertiserBase):
22
+ pass
23
+
24
+
25
+ class Advertiser(AdvertiserBase):
26
+ id: int
27
+ created_at: datetime
28
+
29
+ class Config:
30
+ from_attributes = True
31
+
32
+
33
+ class CampaignBase(BaseModel):
34
+ name: str
35
+ start_date: datetime | None = None
36
+ end_date: datetime | None = None
37
+ budget: float = 0.0
38
+ daily_budget: float = 0.0
39
+ status: str = "active"
40
+
41
+
42
+ class CampaignCreate(CampaignBase):
43
+ advertiser_id: int
44
+
45
+
46
+ class CampaignUpdate(BaseModel):
47
+ name: str | None = None
48
+ start_date: datetime | None = None
49
+ end_date: datetime | None = None
50
+ budget: float | None = None
51
+ daily_budget: float | None = None
52
+ status: str | None = None
53
+
54
+
55
+ class Campaign(CampaignBase):
56
+ id: int
57
+ advertiser_id: int
58
+ created_at: datetime
59
+ updated_at: datetime | None = None
60
+
61
+ class Config:
62
+ from_attributes = True
63
+
64
+
65
+ class AdGroupBase(BaseModel):
66
+ name: str
67
+ targeting_settings: dict[str, Any] | None = None
68
+ bid_strategy: str = "manual"
69
+
70
+
71
+ class AdGroupCreate(AdGroupBase):
72
+ campaign_id: int
73
+
74
+
75
+ class AdGroupUpdate(BaseModel):
76
+ name: str | None = None
77
+ targeting_settings: dict[str, Any] | None = None
78
+ bid_strategy: str | None = None
79
+
80
+
81
+ class AdGroup(AdGroupBase):
82
+ id: int
83
+ campaign_id: int
84
+ created_at: datetime
85
+ updated_at: datetime | None = None
86
+
87
+ class Config:
88
+ from_attributes = True
89
+
90
+
91
+ class AdBase(BaseModel):
92
+ advertiser_id: int
93
+ ad_group_id: int | None = None
94
+ title: str
95
+ description: str | None = None
96
+ url: str
97
+ targeting_constraints: dict[str, Any] | None = None # e.g., [{"dimension": "device_type", "value": "mobile"}]
98
+ ethical_tags: list[str] | None = None # e.g., ["privacy", "open_source"]
99
+ quality_score: float = 0.5
100
+ creative_format: str | None = None # Banner, native, video, etc.
101
+ bid_amount: float = 0.0 # Current bid amount
102
+ status: str = "active" # active, paused, disapproved
103
+ approval_status: str = "pending" # pending, approved, rejected
104
+
105
+
106
+ class AdCreate(AdBase):
107
+ pass
108
+
109
+
110
+ class AdUpdate(BaseModel):
111
+ advertiser_id: int | None = None
112
+ ad_group_id: int | None = None
113
+ title: str | None = None
114
+ description: str | None = None
115
+ url: str | None = None
116
+ targeting_constraints: dict[str, Any] | None = None
117
+ ethical_tags: list[str] | None = None
118
+ quality_score: float | None = None
119
+ creative_format: str | None = None
120
+ bid_amount: float | None = None
121
+ status: str | None = None
122
+ approval_status: str | None = None
123
+
124
+
125
+ class Ad(AdBase):
126
+ id: int
127
+ created_at: datetime
128
+
129
+ class Config:
130
+ from_attributes = True
131
+
132
+
133
+ class CreativeAssetBase(BaseModel):
134
+ asset_type: str # image, video, text, html
135
+ asset_url: str
136
+ payload: dict[str, Any] | None = None # {"width": 300, "height": 250}
137
+ checksum: str | None = None
138
+
139
+
140
+ class CreativeAssetCreate(CreativeAssetBase):
141
+ ad_id: int
142
+
143
+
144
+ class CreativeAssetUpdate(BaseModel):
145
+ asset_type: str | None = None
146
+ asset_url: str | None = None
147
+ payload: dict[str, Any] | None = None
148
+ checksum: str | None = None
149
+
150
+
151
+ class CreativeAsset(CreativeAssetBase):
152
+ id: int
153
+ ad_id: int
154
+ created_at: datetime
155
+
156
+ class Config:
157
+ from_attributes = True
158
+
159
+
160
+ class AdMetricBase(BaseModel):
161
+ ad_id: int
162
+ date: date
163
+ intent_goal: str | None = None # e.g., "LEARN"
164
+ intent_use_case: str | None = None # e.g., "learning"
165
+ impression_count: int = 0
166
+ click_count: int = 0
167
+ conversion_count: int = 0
168
+ ctr: float | None = None # NEW: Click-through rate
169
+ cpm: float | None = None # NEW: Cost per thousand impressions
170
+ cpc: float | None = None # NEW: Cost per click
171
+ roas: float | None = None # NEW: Return on ad spend
172
+ engagement_rate: float | None = None # NEW: Interaction rate
173
+ expires_at: datetime # 30 days from creation
174
+
175
+
176
+ class AdMetricCreate(AdMetricBase):
177
+ pass
178
+
179
+
180
+ class AdMetric(AdMetricBase):
181
+ id: int
182
+ created_at: datetime
183
+
184
+ class Config:
185
+ from_attributes = True
186
+
187
+
188
+ class ClickTrackingBase(BaseModel):
189
+ ad_id: int
190
+ session_id: str | None = None # Anonymous session identifier
191
+ ip_hash: str | None = None # Hashed IP for fraud detection
192
+ user_agent_hash: str | None = None # Hashed user agent
193
+ referring_url: str | None = None # Source of click
194
+ payload: dict[str, Any] | None = None
195
+
196
+
197
+ class ClickTrackingCreate(ClickTrackingBase):
198
+ pass
199
+
200
+
201
+ class ClickTracking(ClickTrackingBase):
202
+ id: int
203
+ timestamp: datetime
204
+
205
+ class Config:
206
+ from_attributes = True
207
+
208
+
209
+ class ConversionTrackingBase(BaseModel):
210
+ click_id: int # Foreign key to click tracking
211
+ conversion_type: str | None = None # Purchase, signup, download, etc.
212
+ value: float | None = None # Conversion value (if applicable)
213
+ status: str = "pending" # Verified, pending, rejected
214
+ payload: dict[str, Any] | None = None
215
+
216
+
217
+ class ConversionTrackingCreate(ConversionTrackingBase):
218
+ pass
219
+
220
+
221
+ class ConversionTracking(ConversionTrackingBase):
222
+ id: int
223
+ timestamp: datetime
224
+
225
+ class Config:
226
+ from_attributes = True
227
+
228
+
229
+ class FraudDetectionBase(BaseModel):
230
+ event_id: int | None = None # ID of suspicious event
231
+ event_type: str | None = None # Click, impression, conversion
232
+ reason: str | None = None # Reason for flagging
233
+ severity: str | None = None # Low, medium, high risk
234
+ review_status: str = "pending" # Pending, reviewed, action_taken
235
+ ad_id: int | None = None # Optional link to ad
236
+ payload: dict[str, Any] | None = None
237
+
238
+
239
+ class FraudDetectionCreate(FraudDetectionBase):
240
+ pass
241
+
242
+
243
+ class FraudDetection(FraudDetectionBase):
244
+ id: int
245
+ created_at: datetime
246
+
247
+ class Config:
248
+ from_attributes = True
249
+
250
+
251
+ # Request models for API endpoints
252
+ class IntentExtractionInput(BaseModel):
253
+ """Validated input for intent extraction"""
254
+
255
+ text: str = Field(..., min_length=1, max_length=2000, description="User query text")
256
+ metadata: dict[str, Any] | None = Field(None, description="Optional metadata")
257
+
258
+
259
+ class IntentExtractionContext(BaseModel):
260
+ """Validated context for intent extraction"""
261
+
262
+ session_id: str | None = Field(None, max_length=128, description="Session identifier")
263
+ user_locale: str | None = Field(None, pattern=r"^[a-z]{2}(-[A-Z]{2})?$", description="User locale (e.g., en-US)")
264
+ product_context: str | None = Field(None, max_length=50, description="Product context (search, docs, mail, etc.)")
265
+ additional_context: dict[str, Any] | None = Field(None, description="Additional context data")
266
+
267
+
268
+ class IntentExtractionOptions(BaseModel):
269
+ """Validated options for intent extraction"""
270
+
271
+ extract_constraints: bool = Field(True, description="Whether to extract constraints")
272
+ extract_ethical_signals: bool = Field(True, description="Whether to extract ethical signals")
273
+ extract_temporal: bool = Field(True, description="Whether to extract temporal intent")
274
+ confidence_threshold: float = Field(0.5, ge=0.0, le=1.0, description="Minimum confidence threshold")
275
+
276
+
277
+ class IntentExtractionRequest(BaseModel):
278
+ """
279
+ Validated request model for /extract-intent endpoint.
280
+
281
+ Ensures all input data is properly validated before processing.
282
+ """
283
+
284
+ product: str = Field(
285
+ ...,
286
+ min_length=1,
287
+ max_length=50,
288
+ pattern=r"^(search|docs|mail|calendar|meet|forms|sites|diary)$",
289
+ description="Product type (search, docs, mail, calendar, meet, forms, sites, diary)",
290
+ )
291
+ input: IntentExtractionInput = Field(..., description="User input data")
292
+ context: IntentExtractionContext = Field(default_factory=IntentExtractionContext, description="Extraction context")
293
+ options: IntentExtractionOptions | None = Field(None, description="Extraction options")
294
+
295
+ class Config:
296
+ json_schema_extra = {
297
+ "example": {
298
+ "product": "search",
299
+ "input": {
300
+ "text": "best laptop for programming under 50000 rupees",
301
+ "metadata": {"source": "web"},
302
+ },
303
+ "context": {
304
+ "session_id": "test-123",
305
+ "user_locale": "en-US",
306
+ "product_context": "search",
307
+ },
308
+ "options": {
309
+ "extract_constraints": True,
310
+ "extract_ethical_signals": True,
311
+ "extract_temporal": True,
312
+ "confidence_threshold": 0.5,
313
+ },
314
+ }
315
+ }
316
+
317
+
318
+ class RankingRequest(BaseModel):
319
+ intent: dict[str, Any] | Any # UniversalIntent as dict or UniversalIntent object
320
+ candidates: list[dict[str, Any]] | None = None # SearchResult equivalent as dict
321
+ results: list[dict[str, Any]] | None = None # Alias for candidates (backwards compatibility)
322
+ options: dict[str, Any] | None = None
323
+
324
+ class Config:
325
+ # Allow both 'candidates' and 'results' fields
326
+ extra = "ignore"
327
+
328
+ def get_candidates(self) -> list[dict[str, Any]]:
329
+ """Get candidates, supporting both 'candidates' and 'results' fields."""
330
+ if self.candidates is not None:
331
+ return self.candidates
332
+ if self.results is not None:
333
+ return self.results
334
+ return []
335
+
336
+
337
+ class ServiceRecommendationRequest(BaseModel):
338
+ intent: dict[str, Any] # UniversalIntent as dict (converted from JSON)
339
+ available_services: list[dict[str, Any]] # ServiceMetadata equivalent as dict
340
+ options: dict[str, Any] | None = None
341
+
342
+
343
+ class AdMatchingRequest(BaseModel):
344
+ intent: dict[str, Any] # UniversalIntent as dict (converted from JSON)
345
+ ad_inventory: list[dict[str, Any]] | None = None # AdMetadata equivalent as dict
346
+ config: dict[str, Any] | None = None
347
+
348
+
349
+ class AdMatchingWithCampaignRequest(AdMatchingRequest):
350
+ campaign_context: dict[str, Any] | None = None # Additional campaign-specific context
351
+
352
+
353
+ # Response models for API endpoints
354
+ class RankingResponse(BaseModel):
355
+ ranked_results: list[dict[str, Any]] # RankedResult equivalent as dict
356
+
357
+
358
+ class ServiceRecommendationResponse(BaseModel):
359
+ recommendations: list[dict[str, Any]] # ServiceRecommendation equivalent as dict
360
+
361
+
362
+ class AdMatchingResponse(BaseModel):
363
+ matched_ads: list[dict[str, Any]] # MatchedAd equivalent as dict
364
+ metrics: dict[str, int]
365
+
366
+
367
+ # Reporting models
368
+ class CampaignPerformanceReport(BaseModel):
369
+ campaign_id: int
370
+ campaign_name: str
371
+ impressions: int
372
+ clicks: int
373
+ conversions: int
374
+ ctr: float
375
+ cpc: float
376
+ cost: float
377
+ roas: float
378
+
379
+
380
+ # Additional models for the API
381
+ class HealthCheckResponse(BaseModel):
382
+ status: str = "healthy"
383
+ timestamp: datetime
384
+ checks: dict[str, bool] | None = None
385
+ version: str | None = None
386
+
387
+
388
+ class StatusResponse(BaseModel):
389
+ service: str
390
+ version: str
391
+ uptime: str
392
+ status: str
393
+
394
+
395
+ # Models for Consent Management
396
+ class ConsentRecord(BaseModel):
397
+ id: int
398
+ user_id: str
399
+ consent_type: str
400
+ granted: bool
401
+ consent_details: dict[str, Any] | None = None
402
+ granted_at: datetime
403
+ expires_at: datetime | None = None
404
+ withdrawn_at: datetime | None = None
405
+ created_at: datetime
406
+ updated_at: datetime
407
+
408
+ class Config:
409
+ from_attributes = True
410
+
411
+
412
+ class ConsentRequest(BaseModel):
413
+ user_id: str
414
+ consent_type: str
415
+ granted: bool
416
+ consent_details: dict[str, Any] | None = None
417
+ expires_in_days: int | None = None
418
+
419
+
420
+ class ConsentSummary(BaseModel):
421
+ timestamp: str
422
+ total_consents: int
423
+ granted_consents: int
424
+ denied_consents: int
425
+ by_type: dict[str, int]
426
+ overall_compliance_rate: float
427
+
428
+
429
+ # Models for Audit Trail
430
+ class AuditEvent(BaseModel):
431
+ id: int
432
+ user_id: str | None = None
433
+ event_type: str
434
+ resource_type: str | None = None
435
+ resource_id: int | None = None
436
+ action_description: str | None = None
437
+ ip_address: str | None = None
438
+ user_agent: str | None = None
439
+ payload: dict[str, Any] | None = None
440
+ timestamp: datetime
441
+ created_at: datetime
442
+
443
+ model_config = ConfigDict(from_attributes=True)
444
+
445
+
446
+ class AuditEventRequest(BaseModel):
447
+ user_id: str | None = None
448
+ event_type: str
449
+ resource_type: str | None = None
450
+ resource_id: int | None = None
451
+ action_description: str | None = None
452
+ ip_address: str | None = None
453
+ user_agent: str | None = None
454
+ payload: dict[str, Any] | None = None
455
+
456
+
457
+ class AuditStats(BaseModel):
458
+ timestamp: str
459
+ total_events: int
460
+ events_by_type: dict[str, int]
461
+ daily_counts: list[dict[str, Any]]
462
+ recent_activity: int
463
+
464
+
465
+ # Models for Privacy Controls
466
+ class DataRetentionPolicy(BaseModel):
467
+ data_type: str
468
+ retention_period: str
469
+ deletion_date: str
470
+ affected_records: int
471
+
472
+
473
+ class PrivacyComplianceReport(BaseModel):
474
+ timestamp: str
475
+ data_summary: dict[str, int]
476
+ compliance_status: dict[str, Any]
477
+ recommendations: list[str]
478
+
479
+
480
+ # A/B Testing Models
481
+ class ABTestBase(BaseModel):
482
+ name: str
483
+ description: str | None = None
484
+ campaign_id: int
485
+ traffic_allocation: float = 1.0
486
+ min_sample_size: int = 1000
487
+ confidence_level: float = 0.95
488
+ primary_metric: str = "ctr"
489
+ payload: dict[str, Any] | None = None
490
+
491
+
492
+ class ABTestCreate(ABTestBase):
493
+ pass
494
+
495
+
496
+ class ABTestUpdate(BaseModel):
497
+ name: str | None = None
498
+ description: str | None = None
499
+ traffic_allocation: float | None = None
500
+ min_sample_size: int | None = None
501
+ confidence_level: float | None = None
502
+ primary_metric: str | None = None
503
+ status: str | None = None
504
+ payload: dict[str, Any] | None = None
505
+
506
+
507
+ class ABTestResponse(ABTestBase):
508
+ id: int
509
+ status: str
510
+ start_date: datetime | None = None
511
+ end_date: datetime | None = None
512
+ winner_variant_id: int | None = None
513
+ created_at: datetime
514
+ updated_at: datetime | None = None
515
+
516
+ class Config:
517
+ from_attributes = True
518
+
519
+
520
+ class ABTestVariantBase(BaseModel):
521
+ name: str
522
+ ad_id: int
523
+ traffic_weight: float = 0.5
524
+ is_control: bool = False
525
+ payload: dict[str, Any] | None = None
526
+
527
+
528
+ class ABTestVariantCreate(ABTestVariantBase):
529
+ test_id: int
530
+
531
+
532
+ class ABTestVariantResponse(ABTestVariantBase):
533
+ id: int
534
+ test_id: int
535
+ impressions: int = 0
536
+ clicks: int = 0
537
+ conversions: int = 0
538
+ revenue: float = 0.0
539
+ created_at: datetime
540
+
541
+ class Config:
542
+ from_attributes = True
543
+
544
+
545
+ class ABTestResultsResponse(BaseModel):
546
+ test_id: int
547
+ status: str
548
+ total_impressions: int
549
+ variants: list[dict[str, Any]]
550
+ is_significant: bool
551
+ winner_variant_id: int | None = None
552
+ p_value: float | None = None
553
+ recommended_action: str
554
+
555
+
556
+ # Fraud Detection Response Models
557
+ class FraudAnalysisResponse(BaseModel):
558
+ is_fraudulent: bool
559
+ risk_score: float
560
+ signals: list[dict[str, Any]]
561
+ recommended_action: str
562
+
563
+
564
+ class FraudScanSummary(BaseModel):
565
+ total_analyzed: int
566
+ fraudulent_count: int
567
+ high_risk_count: int
568
+ medium_risk_count: int
569
+ low_risk_count: int
570
+ fraud_types: dict[str, int]
571
+ new_fraud_reports: int
572
+
573
+
574
+ # URL Ranking Models
575
+ class URLRankingAPIRequest(BaseModel):
576
+ query: str
577
+ urls: list[str]
578
+ titles: list[str] | None = None
579
+ contents: list[str] | None = None
580
+ intent: UniversalIntent | None = None
581
+ options: dict[str, Any] | None = None
582
+
583
+
584
+ class URLRankedResult(BaseModel):
585
+ url: str
586
+ title: str | None = None
587
+ description: str | None = None
588
+ domain: str | None = None
589
+ privacy_score: float = 0.5
590
+ tracker_count: int = 0
591
+ encryption_enabled: bool = True
592
+ content_type: str | None = None
593
+ is_open_source: bool = False
594
+ is_non_profit: bool = False
595
+ relevance_score: float = 0.0
596
+ final_score: float = 0.0
597
+
598
+
599
+ class URLRankingAPIResponse(BaseModel):
600
+ query: str
601
+ ranked_urls: list[URLRankedResult]
602
+ processing_time_ms: float
603
+ total_urls: int
604
+ filtered_count: int = 0
605
+
606
+
607
+ # Advanced Analytics Models
608
+ class AttributionResultResponse(BaseModel):
609
+ conversion_id: int
610
+ touchpoints: list[dict[str, Any]]
611
+ attribution_weights: dict[str, float]
612
+ total_value: float
613
+ attributed_values: dict[str, float]
614
+
615
+
616
+ class CampaignROIResponse(BaseModel):
617
+ campaign_id: int
618
+ campaign_name: str
619
+ total_spend: float
620
+ total_revenue: float
621
+ roi: float
622
+ roas: float
623
+ cpa: float
624
+ clv: float
625
+ impressions: int
626
+ clicks: int
627
+ conversions: int
628
+ ctr: float
629
+ cvr: float
630
+
631
+
632
+ class TrendAnalysisResponse(BaseModel):
633
+ metric_name: str
634
+ current_value: float
635
+ previous_value: float
636
+ change_percent: float
637
+ trend_direction: str
638
+ data_points: list[dict[str, Any]]
639
+ forecast_next_period: float | None = None
640
+
641
+
642
+ # Unified Search Models (SearXNG Integration)
643
+ class UnifiedSearchRequest(BaseModel):
644
+ """Request model for unified privacy search with intent ranking."""
645
+
646
+ query: str
647
+ categories: list[str] | None = None
648
+ engines: list[str] | None = None
649
+ language: str = "en"
650
+ safe_search: int = 0
651
+ time_range: str | None = None
652
+ extract_intent: bool = True
653
+ rank_results: bool = True
654
+ max_results: int = 20
655
+ page: int = 1
656
+ page_size: int | None = None # Results per page (for pagination)
657
+ weights: dict[str, float] | None = None
658
+ min_privacy_score: float | None = None
659
+ exclude_big_tech: bool = False
660
+
661
+
662
+ class ProductURLInfo(BaseModel):
663
+ """Product URL extracted from blog/review content"""
664
+
665
+ url: str
666
+ domain: str
667
+ is_affiliate: bool = False
668
+ is_ecommerce: bool = False
669
+ product_name: str | None = None
670
+ price: float | None = None
671
+ currency: str | None = None
672
+ confidence: float = 0.5
673
+ source: str = "content"
674
+ ranked_score: float | None = None # Score after intent-based ranking
675
+
676
+
677
+ class RankedSearchResult(BaseModel):
678
+ """Ranked search result with intent alignment and privacy scoring."""
679
+
680
+ url: str
681
+ title: str
682
+ content: str
683
+ engine: str
684
+ original_score: float
685
+ ranked_score: float
686
+ rank: int
687
+ category: str
688
+ thumbnail: str | None = None
689
+ published_date: str | None = None
690
+ intent_goal: str | None = None
691
+ match_reasons: list[str] = []
692
+ privacy_score: float | None = None
693
+ ethical_alignment: float | None = None
694
+ price: float | None = None
695
+ currency: str | None = None
696
+ is_dynamic: bool = False
697
+ # Product URLs extracted from blog/review content
698
+ is_blog_content: bool = False
699
+ blog_confidence: float = 0.0
700
+ product_urls: list[ProductURLInfo] = []
701
+ prices_found: list[dict[str, Any]] = []
702
+ affiliate_links: list[str] = []
703
+
704
+
705
+ class ExtractedIntent(BaseModel):
706
+ """Extracted intent from search query for API response."""
707
+
708
+ goal: str
709
+ constraints: list[dict[str, Any]]
710
+ use_cases: list[str]
711
+ result_type: str
712
+ complexity: str
713
+ confidence: float
714
+ programming_context: dict[str, Any] | None = None
715
+ research_plan: dict[str, Any] | None = None
716
+
717
+
718
+ class UnifiedSearchResponse(BaseModel):
719
+ """Response model for unified search endpoint."""
720
+
721
+ query: str
722
+ results: list[RankedSearchResult]
723
+ total_results: int
724
+ processing_time_ms: float
725
+ extracted_intent: ExtractedIntent | None = None
726
+ engines_used: list[str] = []
727
+ categories_searched: list[str] = []
728
+ ranking_applied: bool = False
729
+ results_ranked: int = 0
730
+ privacy_enhanced: bool = True
731
+ tracking_blocked: bool = True
732
+ metrics: dict[str, Any] = {}
733
+ # Aggregate product URL statistics
734
+ total_product_urls_found: int = 0
735
+ total_blogs_analyzed: int = 0
services/query_layer/app/ranking/__init__.py ADDED
File without changes
services/query_layer/app/ranking/enhanced_ranker.py ADDED
@@ -0,0 +1,763 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Intent Engine - Enhanced Ranking Module (v2.1)
3
+
4
+ Multi-factor scoring with content filtering, authority boosting, and Redis caching.
5
+
6
+ Improvements over optimized_ranker.py:
7
+ 1. ✅ Multi-factor scoring (semantic + authority + freshness + quality)
8
+ 2. ✅ Content filtering (trusted sources, low-quality filtering)
9
+ 3. ✅ Domain authority scoring
10
+ 4. ✅ Better null safety and error handling
11
+ 5. ✅ Configurable weights
12
+ 6. ✅ Redis caching for ranking results (NEW v2.1)
13
+ 7. ✅ Background refresh for popular queries (NEW v2.1)
14
+
15
+ Usage:
16
+ from app.ranking.enhanced_ranker import EnhancedRanker
17
+
18
+ ranker = EnhancedRanker()
19
+ ranked_results = await ranker.rank_with_filters(candidates, intent, options)
20
+ """
21
+
22
+ import asyncio
23
+ import hashlib
24
+ import logging
25
+ import time
26
+ from dataclasses import dataclass, field
27
+ from datetime import UTC, datetime, timedelta
28
+ from typing import Optional
29
+
30
+ from app.config.optimized_cache import get_embedding_cache
31
+ from app.config.redis_cache import cache as redis_cache
32
+ from app.core.schema import (
33
+ DeclaredIntent,
34
+ EthicalDimension,
35
+ InferredIntent,
36
+ SkillLevel,
37
+ UniversalIntent,
38
+ )
39
+
40
+ logger = logging.getLogger(__name__)
41
+
42
+
43
+ # =============================================================================
44
+ # Trusted Domains & Content Quality Configuration
45
+ # =============================================================================
46
+
47
+ # High-authority domains to boost (trusted sources)
48
+ TRUSTED_DOMAINS = {
49
+ # Official Documentation
50
+ "python.org": 1.0,
51
+ "docs.python.org": 1.0,
52
+ "developer.mozilla.org": 1.0,
53
+ "microsoft.com": 0.9,
54
+ "google.com": 0.85,
55
+ "apple.com": 0.85,
56
+ "aws.amazon.com": 0.9,
57
+ # Educational Institutions
58
+ ".edu": 0.95,
59
+ "mit.edu": 1.0,
60
+ "stanford.edu": 1.0,
61
+ "cmu.edu": 1.0,
62
+ "berkeley.edu": 1.0,
63
+ # Known Tutorial Sites (High Quality)
64
+ "realpython.com": 0.95,
65
+ "geeksforgeeks.org": 0.85,
66
+ "tutorialspoint.com": 0.8,
67
+ "w3schools.com": 0.75,
68
+ "stackoverflow.com": 0.9,
69
+ "github.com": 0.9,
70
+ "medium.com": 0.7,
71
+ "dev.to": 0.8,
72
+ "freeCodeCamp.org": 0.9,
73
+ # Tech News & Reviews
74
+ "arstechnica.com": 0.85,
75
+ "wired.com": 0.85,
76
+ "theverge.com": 0.8,
77
+ # Product Sites (for comparison queries)
78
+ "amazon.com": 0.75,
79
+ "newegg.com": 0.75,
80
+ }
81
+
82
+ # Low-quality domains to filter or down-rank
83
+ LOW_QUALITY_DOMAINS = {
84
+ "content-farm": ["ehow.com", "wikihow.com", "answer.com"],
85
+ "clickbait": ["buzzfeed.com", "viralnova.com"],
86
+ "spam_indicators": ["free-", "download-", "crack-"],
87
+ }
88
+
89
+ # Content quality thresholds
90
+ QUALITY_THRESHOLDS = {
91
+ "min_title_length": 10,
92
+ "max_title_length": 200,
93
+ "min_content_length": 50,
94
+ "min_quality_score": 0.3, # Filter results below this
95
+ }
96
+
97
+
98
+ @dataclass
99
+ class SearchResult:
100
+ """Enhanced search result with quality metadata"""
101
+
102
+ id: str
103
+ title: str
104
+ description: str
105
+ url: str
106
+ platform: Optional[str] = None
107
+ provider: Optional[str] = None
108
+ license: Optional[str] = None
109
+ price: Optional[float] = None
110
+ tags: list[str] = field(default_factory=list)
111
+ qualityScore: float = 0.5
112
+ recency: Optional[str] = None
113
+ complexity: Optional[str] = None
114
+ compatibility: list[str] = field(default_factory=list)
115
+ privacyRating: Optional[float] = None
116
+ opensource: Optional[bool] = None
117
+ published_date: Optional[datetime] = None
118
+ domain: str = ""
119
+ domain_authority: float = 0.5
120
+
121
+ def __post_init__(self):
122
+ # Extract domain from URL
123
+ if self.url and not self.domain:
124
+ try:
125
+ self.domain = (
126
+ self.url.split("/")[2].lower()
127
+ if "/" in self.url
128
+ else self.url.lower()
129
+ )
130
+ except (IndexError, AttributeError):
131
+ self.domain = ""
132
+
133
+
134
+ @dataclass
135
+ class RankedResult:
136
+ """Enhanced ranked result with detailed scoring"""
137
+
138
+ result: SearchResult
139
+ alignmentScore: float
140
+ matchReasons: list[str]
141
+ qualityScore: float = 0.0
142
+ authorityScore: float = 0.0
143
+ freshnessScore: float = 0.0
144
+ semanticScore: float = 0.0
145
+ finalScore: float = 0.0
146
+
147
+
148
+ class EnhancedRanker:
149
+ """
150
+ Enhanced ranking with multi-factor scoring and content filtering.
151
+
152
+ Scoring Components:
153
+ 1. Semantic Similarity (35%) - Query-content match
154
+ 2. Intent Alignment (35%) - Use case, skill level, ethics
155
+ 3. Domain Authority (15%) - Trusted source boosting
156
+ 4. Content Quality (10%) - Title/description quality
157
+ 5. Freshness (5%) - Recency boost
158
+
159
+ Filtering:
160
+ - Remove low-quality domains
161
+ - Filter duplicate/spam content
162
+ - Enforce minimum quality thresholds
163
+ """
164
+
165
+ def __init__(self, config: Optional[dict] = None):
166
+ # Use shared embedding cache (singleton) - don't create new instances
167
+ self.embedding_cache = get_embedding_cache()
168
+
169
+ # Configurable weights - PRIORITIZE: Intent > Relevance > Authority > Quality > Freshness
170
+ weight_config = config.get("weights") if config else None
171
+ self.weights = (
172
+ weight_config
173
+ if weight_config
174
+ else {
175
+ "semantic": 0.35, # Relevance (semantic similarity) - HIGHER
176
+ "intent": 0.35, # Intent alignment - HIGHER (combined 70% for relevance)
177
+ "authority": 0.15, # Domain authority - LOWER
178
+ "quality": 0.10, # Content quality - LOWER
179
+ "freshness": 0.05, # Freshness - LOWEST
180
+ }
181
+ )
182
+
183
+ # Filtering config
184
+ filter_config = config.get("filtering") if config else None
185
+ self.filter_config = (
186
+ filter_config
187
+ if filter_config
188
+ else {
189
+ "enable_domain_filter": True,
190
+ "enable_quality_filter": True,
191
+ "min_quality_threshold": QUALITY_THRESHOLDS["min_quality_score"],
192
+ "remove_duplicates": True,
193
+ }
194
+ )
195
+ logger.info("EnhancedRanker initialized (using shared embedding cache)")
196
+
197
+ def _generate_cache_key(
198
+ self, candidates: list[dict], intent: UniversalIntent
199
+ ) -> str:
200
+ """Generate cache key from query and intent"""
201
+ # Use query hash + intent goal for cache key
202
+ declared = intent.declared or DeclaredIntent()
203
+ query = declared.query or ""
204
+ goal = declared.goal.value if declared.goal else "unknown"
205
+
206
+ # Create deterministic key
207
+ key_data = f"{query}:{goal}:{len(candidates)}"
208
+ return f"ranking:{hashlib.md5(key_data.encode()).hexdigest()}"
209
+
210
+ async def _get_cached_ranking(self, cache_key: str) -> Optional[list[RankedResult]]:
211
+ """Get cached ranking results from Redis"""
212
+ try:
213
+ cached_data = await redis_cache.get(cache_key)
214
+ if cached_data:
215
+ logger.debug(f"Ranking cache HIT: {cache_key[:40]}")
216
+ results = []
217
+ for item in cached_data:
218
+ if "result" in item and isinstance(item["result"], dict):
219
+ item["result"] = SearchResult(**item["result"])
220
+ results.append(RankedResult(**item))
221
+ return results
222
+ except Exception as e:
223
+ logger.debug(f"Cache get failed: {e}")
224
+ return None
225
+
226
+ async def _cache_ranking_results(
227
+ self, cache_key: str, results: list[RankedResult], ttl: int = 300
228
+ ):
229
+ """Cache ranking results in Redis with TTL"""
230
+ try:
231
+ # Convert RankedResult objects to dicts
232
+ results_dict = [
233
+ {
234
+ "result": {
235
+ "id": r.result.id,
236
+ "title": r.result.title,
237
+ "description": r.result.description,
238
+ "url": r.result.url,
239
+ "domain": r.result.domain,
240
+ "qualityScore": r.result.qualityScore,
241
+ },
242
+ "alignmentScore": r.alignmentScore,
243
+ "matchReasons": r.matchReasons,
244
+ "qualityScore": r.qualityScore,
245
+ "authorityScore": r.authorityScore,
246
+ "freshnessScore": r.freshnessScore,
247
+ "semanticScore": r.semanticScore,
248
+ "finalScore": r.finalScore,
249
+ }
250
+ for r in results
251
+ ]
252
+
253
+ # Cache with TTL (5 minutes default)
254
+ await redis_cache.set(cache_key, results_dict, ttl=ttl, background=True)
255
+ logger.debug(f"Ranking cache SET: {cache_key[:40]} (TTL={ttl}s)")
256
+ except Exception as e:
257
+ logger.debug(f"Cache set failed: {e}")
258
+
259
+ async def rank_with_filters(
260
+ self,
261
+ candidates: list[dict],
262
+ intent: UniversalIntent,
263
+ options: Optional[dict] = None,
264
+ ) -> list[RankedResult]:
265
+ """
266
+ Main ranking method with filtering, multi-factor scoring, and caching.
267
+
268
+ Caching Strategy:
269
+ 1. Check Redis cache first (5min TTL)
270
+ 2. If miss, compute ranking
271
+ 3. Cache results in background
272
+ 4. Return cached or computed results
273
+
274
+ Args:
275
+ candidates: List of search result dicts
276
+ intent: User intent object
277
+ options: Ranking options (filters, weights, etc.)
278
+
279
+ Returns:
280
+ List of ranked results with scores
281
+ """
282
+ start_time = time.time()
283
+
284
+ # Generate cache key
285
+ cache_key = self._generate_cache_key(candidates, intent)
286
+
287
+ # Step 0: Try cache first
288
+ cached_results = await self._get_cached_ranking(cache_key)
289
+ if cached_results:
290
+ elapsed = (time.time() - start_time) * 1000
291
+ logger.info(f"✓ Ranking cache HIT: {elapsed:.2f}ms")
292
+ return cached_results
293
+
294
+ # Cache miss: proceed with ranking
295
+ logger.info("Ranking cache MISS, computing...")
296
+
297
+ # Convert dicts to SearchResult objects
298
+ search_results = self._convert_to_search_results(candidates)
299
+ logger.debug(f"Converted {len(candidates)} candidates to SearchResult objects")
300
+
301
+ # Step 1: Apply content filters
302
+ filtered_results = self._apply_content_filters(search_results, intent)
303
+ logger.debug(
304
+ f"Filtered {len(search_results)} → {len(filtered_results)} results"
305
+ )
306
+
307
+ # Step 2: Calculate multi-factor scores
308
+ scored_results = []
309
+ for result in filtered_results:
310
+ scored = self._calculate_multi_factor_score(result, intent)
311
+ scored_results.append(scored)
312
+
313
+ # Step 3: Sort by final score
314
+ scored_results.sort(key=lambda x: x.finalScore, reverse=True)
315
+
316
+ # Step 4: Remove duplicates (if enabled)
317
+ if self.filter_config.get("remove_duplicates", True):
318
+ scored_results = self._remove_duplicates(scored_results)
319
+
320
+ # Cache results in background (non-blocking)
321
+ asyncio.create_task(
322
+ self._cache_ranking_results(cache_key, scored_results, ttl=300)
323
+ )
324
+
325
+ elapsed = (time.time() - start_time) * 1000
326
+ logger.info(
327
+ f"Enhanced ranking complete: {len(scored_results)} results in {elapsed:.2f}ms"
328
+ )
329
+
330
+ return scored_results
331
+
332
+ def _convert_to_search_results(self, candidates: list[dict]) -> list[SearchResult]:
333
+ """Convert raw result dicts to SearchResult objects"""
334
+ results = []
335
+ for candidate in candidates:
336
+ try:
337
+ result = SearchResult(
338
+ id=candidate.get(
339
+ "id", hashlib.md5(candidate.get("url", "").encode()).hexdigest()
340
+ ),
341
+ title=candidate.get("title", "")[:200],
342
+ description=candidate.get("content", candidate.get("snippet", "")),
343
+ url=candidate.get("url", ""),
344
+ platform=candidate.get("platform"),
345
+ provider=candidate.get("provider"),
346
+ qualityScore=candidate.get("qualityScore", 0.5),
347
+ tags=candidate.get("tags", []),
348
+ published_date=self._parse_date(candidate.get("publishedDate")),
349
+ )
350
+ results.append(result)
351
+ except Exception as e:
352
+ logger.warning(f"Failed to convert candidate: {e}")
353
+ continue
354
+ return results
355
+
356
+ def _apply_content_filters(
357
+ self, results: list[SearchResult], intent: UniversalIntent
358
+ ) -> list[SearchResult]:
359
+ """Apply content quality and domain filters"""
360
+ filtered = []
361
+
362
+ for result in results:
363
+ # Skip if content is too short
364
+ if len(result.title) < QUALITY_THRESHOLDS["min_title_length"]:
365
+ logger.debug(f"Filtered (short title): {result.url[:50]}")
366
+ continue
367
+
368
+ if len(result.description) < QUALITY_THRESHOLDS["min_content_length"]:
369
+ logger.debug(f"Filtered (short content): {result.url[:50]}")
370
+ continue
371
+
372
+ # Check for low-quality domains
373
+ if self.filter_config.get("enable_domain_filter", True):
374
+ if self._is_low_quality_domain(result.domain):
375
+ logger.debug(f"Filtered (low-quality domain): {result.domain}")
376
+ continue
377
+
378
+ # Check minimum quality score
379
+ if result.qualityScore and result.qualityScore < self.filter_config.get(
380
+ "min_quality_threshold", 0.3
381
+ ):
382
+ logger.debug(f"Filtered (low quality): {result.url[:50]}")
383
+ continue
384
+
385
+ filtered.append(result)
386
+
387
+ return filtered
388
+
389
+ def _is_low_quality_domain(self, domain: str) -> bool:
390
+ """Check if domain is low-quality or spam"""
391
+ if not domain:
392
+ return True
393
+
394
+ # Check exact matches
395
+ for _category, domains in LOW_QUALITY_DOMAINS.items():
396
+ if domain in domains:
397
+ return True
398
+
399
+ # Check for spam indicators in URL
400
+ return any(
401
+ indicator in domain
402
+ for indicator in LOW_QUALITY_DOMAINS.get("spam_indicators", [])
403
+ )
404
+
405
+ def _calculate_multi_factor_score(
406
+ self, result: SearchResult, intent: UniversalIntent
407
+ ) -> RankedResult:
408
+ """Calculate multi-factor ranking score"""
409
+
410
+ # 1. Semantic Similarity (35%)
411
+ semantic_score = self._compute_semantic_similarity(result, intent)
412
+
413
+ # 2. Intent Alignment (35%)
414
+ intent_score, intent_reasons = self._compute_intent_alignment(result, intent)
415
+
416
+ # 3. Domain Authority (15%) - pass query for GitHub boost
417
+ declared = intent.declared or DeclaredIntent()
418
+ query = declared.query if declared else None
419
+ authority_score = self._compute_domain_authority(result, query)
420
+
421
+ # 4. Content Quality (10%)
422
+ quality_score = self._compute_content_quality(result)
423
+
424
+ # 5. Freshness (5%)
425
+ freshness_score = self._compute_freshness(result)
426
+
427
+ # Calculate weighted final score
428
+ final_score = (
429
+ semantic_score * self.weights["semantic"]
430
+ + intent_score * self.weights["intent"]
431
+ + authority_score * self.weights["authority"]
432
+ + quality_score * self.weights["quality"]
433
+ + freshness_score * self.weights["freshness"]
434
+ )
435
+
436
+ # Build match reasons
437
+ match_reasons = list(intent_reasons)
438
+ if authority_score > 0.8:
439
+ match_reasons.append("high-authority-source")
440
+ if quality_score > 0.8:
441
+ match_reasons.append("high-quality-content")
442
+ if freshness_score > 0.7:
443
+ match_reasons.append("recent-content")
444
+
445
+ return RankedResult(
446
+ result=result,
447
+ alignmentScore=intent_score,
448
+ matchReasons=match_reasons,
449
+ qualityScore=quality_score,
450
+ authorityScore=authority_score,
451
+ freshnessScore=freshness_score,
452
+ semanticScore=semantic_score,
453
+ finalScore=final_score,
454
+ )
455
+
456
+ def _compute_semantic_similarity(
457
+ self, result: SearchResult, intent: UniversalIntent
458
+ ) -> float:
459
+ """Compute semantic similarity between query and content"""
460
+ try:
461
+ # Get query from intent
462
+ declared = intent.declared or DeclaredIntent()
463
+ query = declared.query if declared else None
464
+
465
+ if not query:
466
+ return 0.5 # Neutral score if no query
467
+
468
+ content = f"{result.title} {result.description}".strip()
469
+ if not content:
470
+ return 0.0
471
+
472
+ # Use embedding cache
473
+ query_emb = self.embedding_cache.encode_text(query)
474
+ content_emb = self.embedding_cache.encode_text(content)
475
+
476
+ if query_emb is not None and content_emb is not None:
477
+ similarity = self.embedding_cache.cosine_similarity(
478
+ query_emb, content_emb
479
+ )
480
+ # Normalize from [-1, 1] to [0, 1]
481
+ return (similarity + 1) / 2
482
+
483
+ # Fallback to keyword matching
484
+ return self._keyword_match_score(query, content)
485
+
486
+ except Exception as e:
487
+ logger.warning(f"Semantic similarity calculation failed: {e}")
488
+ return 0.5
489
+
490
+ def _compute_intent_alignment(
491
+ self, result: SearchResult, intent: UniversalIntent
492
+ ) -> tuple[float, list[str]]:
493
+ """Compute intent alignment score with reasons"""
494
+ reasons = []
495
+ scores = []
496
+
497
+ # Null safety
498
+ declared = intent.declared or DeclaredIntent()
499
+ inferred = intent.inferred or InferredIntent()
500
+
501
+ # Get query for keyword matching
502
+ query = declared.query if declared else ""
503
+ query_lower = query.lower()
504
+ query_words = [w for w in query_lower.split() if len(w) > 2]
505
+ content_lower = f"{result.title} {result.description}".lower()
506
+
507
+ # 1. Query Keyword Match (40% of intent score) - MOST IMPORTANT
508
+ # Check how many query words appear in the result
509
+ if query_words:
510
+ matches = sum(1 for word in query_words if word in content_lower)
511
+ keyword_match_score = matches / len(query_words)
512
+
513
+ # Boost for exact phrase match in title
514
+ if query_lower in result.title.lower():
515
+ keyword_match_score = min(1.0, keyword_match_score + 0.3)
516
+ reasons.append("exact-title-match")
517
+
518
+ # Boost for AGI/AI/project keywords when query suggests tech intent
519
+ tech_keywords = [
520
+ "agi",
521
+ "artificial intelligence",
522
+ "ai ",
523
+ "machine learning",
524
+ "project",
525
+ "framework",
526
+ "architecture",
527
+ "cognitive",
528
+ "neural",
529
+ "open-source",
530
+ ]
531
+ has_tech_keywords = any(kw in content_lower for kw in tech_keywords)
532
+
533
+ # If query has tech terms (like "agi") and result also has them, boost
534
+ query_has_tech = any(
535
+ kw in query_lower for kw in ["agi", "ai", "ml", "project", "framework"]
536
+ )
537
+ if query_has_tech and has_tech_keywords:
538
+ keyword_match_score = min(1.0, keyword_match_score + 0.2)
539
+ reasons.append("tech-intent-match")
540
+
541
+ scores.append(keyword_match_score * 0.4) # 40% weight
542
+ if keyword_match_score > 0.5:
543
+ reasons.append("high-keyword-match")
544
+
545
+ # 2. Use case alignment (30% of intent score)
546
+ use_cases = inferred.useCases if inferred else []
547
+ if use_cases and result.tags:
548
+ tag_text = " ".join(result.tags).lower()
549
+ for use_case in use_cases:
550
+ use_case_val = (
551
+ use_case.value if hasattr(use_case, "value") else str(use_case)
552
+ )
553
+ use_case_str = use_case_val.replace("_", " ")
554
+ if use_case_str in tag_text:
555
+ scores.append(0.3)
556
+ reasons.append(f"use-case-{use_case_val}")
557
+
558
+ # 3. Skill level alignment (15% of intent score)
559
+ skill_level = declared.skillLevel if declared else None
560
+ if skill_level:
561
+ complexity_keywords = {
562
+ SkillLevel.BEGINNER: ["beginner", "basic", "introduction", "starter"],
563
+ SkillLevel.INTERMEDIATE: ["intermediate", "moderate", "practical"],
564
+ SkillLevel.ADVANCED: ["advanced", "expert", "mastery", "deep dive"],
565
+ SkillLevel.EXPERT: ["expert", "professional", "enterprise"],
566
+ }
567
+
568
+ keywords = complexity_keywords.get(skill_level, [])
569
+
570
+ if any(kw in content_lower for kw in keywords):
571
+ scores.append(0.15)
572
+ reasons.append(f"skill-{skill_level.value}")
573
+
574
+ # 4. Ethical alignment (15% of intent score)
575
+ ethical_signals = inferred.ethicalSignals if inferred else []
576
+ if ethical_signals:
577
+ for signal in ethical_signals:
578
+ if signal.dimension == EthicalDimension.PRIVACY:
579
+ if result.privacyRating and result.privacyRating > 0.7:
580
+ scores.append(0.15)
581
+ reasons.append("privacy-aligned")
582
+ elif (
583
+ signal.dimension == EthicalDimension.OPENNESS and result.opensource
584
+ ):
585
+ scores.append(0.15)
586
+ reasons.append("open-source")
587
+
588
+ # Calculate final intent score
589
+ intent_score = sum(scores) if scores else 0.3 # Lower default if no signals
590
+
591
+ return min(1.0, intent_score), reasons
592
+
593
+ def _compute_domain_authority(
594
+ self, result: SearchResult, query: str = None
595
+ ) -> float:
596
+ """Compute domain authority score"""
597
+ if not result.domain:
598
+ return 0.5
599
+
600
+ # Check exact domain matches
601
+ if result.domain in TRUSTED_DOMAINS:
602
+ authority = TRUSTED_DOMAINS[result.domain]
603
+
604
+ # Specialized boost for GitHub when searching for projects/code
605
+ if result.domain == "github.com" and query:
606
+ query_lower = query.lower()
607
+ if any(
608
+ kw in query_lower
609
+ for kw in ["project", "repo", "code", "implementation", "agi"]
610
+ ):
611
+ authority = 1.0
612
+
613
+ logger.debug(f"Domain {result.domain} has authority {authority}")
614
+ return authority
615
+
616
+ # Check suffix matches (e.g., .edu)
617
+ for domain_suffix, score in TRUSTED_DOMAINS.items():
618
+ if domain_suffix.startswith(".") and result.domain.endswith(domain_suffix):
619
+ return score
620
+
621
+ # Default authority for unknown domains
622
+ return 0.5
623
+
624
+ def _compute_content_quality(self, result: SearchResult) -> float:
625
+ """Compute content quality score"""
626
+ quality_factors = []
627
+
628
+ # Title quality (length, capitalization)
629
+ title_len = len(result.title)
630
+ if (
631
+ QUALITY_THRESHOLDS["min_title_length"]
632
+ <= title_len
633
+ <= QUALITY_THRESHOLDS["max_title_length"]
634
+ ):
635
+ quality_factors.append(0.8)
636
+ elif title_len > QUALITY_THRESHOLDS["min_title_length"]:
637
+ quality_factors.append(0.6)
638
+ else:
639
+ quality_factors.append(0.3)
640
+
641
+ # Description quality
642
+ desc_len = len(result.description)
643
+ if desc_len >= 150:
644
+ quality_factors.append(0.8)
645
+ elif desc_len >= QUALITY_THRESHOLDS["min_content_length"]:
646
+ quality_factors.append(0.6)
647
+ else:
648
+ quality_factors.append(0.3)
649
+
650
+ # Existing quality score
651
+ if result.qualityScore:
652
+ quality_factors.append(result.qualityScore)
653
+
654
+ # Average quality factors
655
+ return sum(quality_factors) / len(quality_factors) if quality_factors else 0.5
656
+
657
+ def _compute_freshness(self, result: SearchResult) -> float:
658
+ """Compute freshness score based on publication date"""
659
+ if not result.published_date:
660
+ return 0.5 # Neutral if no date
661
+
662
+ try:
663
+ now = datetime.now(UTC)
664
+ age = now - result.published_date
665
+
666
+ # Score based on age
667
+ if age < timedelta(days=7):
668
+ return 1.0 # Very fresh
669
+ if age < timedelta(days=30):
670
+ return 0.9 # Fresh
671
+ if age < timedelta(days=90):
672
+ return 0.7 # Recent
673
+ if age < timedelta(days=365):
674
+ return 0.5 # Neutral
675
+ return 0.3 # Old
676
+ except Exception:
677
+ return 0.5
678
+
679
+ def _keyword_match_score(self, query: str, content: str) -> float:
680
+ """Calculate keyword match score as fallback"""
681
+ if not query or not content:
682
+ return 0.0
683
+
684
+ query_words = set(query.lower().split())
685
+ content_words = set(content.lower().split())
686
+
687
+ if not query_words:
688
+ return 0.5
689
+
690
+ matches = query_words.intersection(content_words)
691
+ return len(matches) / len(query_words)
692
+
693
+ def _parse_date(self, date_str: Optional[str]) -> Optional[datetime]:
694
+ """Parse date string to datetime"""
695
+ if not date_str:
696
+ return None
697
+
698
+ try:
699
+ # Try common date formats
700
+ formats = [
701
+ "%Y-%m-%d",
702
+ "%Y-%m-%dT%H:%M:%S",
703
+ "%Y-%m-%dT%H:%M:%SZ",
704
+ "%d-%m-%Y",
705
+ "%m/%d/%Y",
706
+ ]
707
+
708
+ for fmt in formats:
709
+ try:
710
+ return datetime.strptime(date_str, fmt)
711
+ except ValueError:
712
+ continue
713
+
714
+ return None
715
+ except Exception:
716
+ return None
717
+
718
+ def _remove_duplicates(self, results: list[RankedResult]) -> list[RankedResult]:
719
+ """Remove duplicate results based on URL or content similarity"""
720
+ seen_urls = set()
721
+ unique_results = []
722
+
723
+ for result in results:
724
+ url = result.result.url
725
+ if url and url not in seen_urls:
726
+ seen_urls.add(url)
727
+ unique_results.append(result)
728
+
729
+ return unique_results
730
+
731
+
732
+ # Convenience function
733
+ async def rank_results_enhanced(
734
+ candidates: list[dict], intent: UniversalIntent, options: Optional[dict] = None
735
+ ) -> list[dict]:
736
+ """
737
+ Enhanced ranking with multi-factor scoring.
738
+
739
+ Args:
740
+ candidates: List of search result dicts
741
+ intent: User intent object
742
+ options: Ranking options
743
+
744
+ Returns:
745
+ List of ranked result dicts
746
+ """
747
+ ranker = EnhancedRanker()
748
+ ranked = await ranker.rank_with_filters(candidates, intent, options)
749
+
750
+ # Convert back to dicts for API response
751
+ return [
752
+ {
753
+ "url": r.result.url,
754
+ "title": r.result.title,
755
+ "content": r.result.description,
756
+ "score": r.finalScore,
757
+ "quality_score": r.qualityScore,
758
+ "authority_score": r.authorityScore,
759
+ "semantic_score": r.semanticScore,
760
+ "match_reasons": r.matchReasons,
761
+ }
762
+ for r in ranked
763
+ ]
services/query_layer/app/ranking/optimized_ranker.py ADDED
@@ -0,0 +1,388 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Intent Engine - Optimized Ranking Module (Unified ONNX Version)
3
+
4
+ This module implements improved constraint satisfaction and intent-aligned ranking
5
+ using the shared ONNX embedding service for high performance.
6
+ """
7
+
8
+ import hashlib
9
+ import logging
10
+ from dataclasses import dataclass
11
+ from typing import Any
12
+
13
+ from app.config.query_cache import get_ranking_cache
14
+ from app.core.embedding_service import get_embedding_service
15
+ from app.core.schema import (
16
+ Constraint,
17
+ ConstraintType,
18
+ DeclaredIntent,
19
+ EthicalDimension,
20
+ InferredIntent,
21
+ SkillLevel,
22
+ UniversalIntent,
23
+ )
24
+
25
+ logger = logging.getLogger(__name__)
26
+
27
+
28
+ @dataclass
29
+ class SearchResult:
30
+ """Represents a search result candidate with metadata"""
31
+
32
+ id: str
33
+ title: str
34
+ description: str
35
+ platform: str | None = None
36
+ provider: str | None = None
37
+ license: str | None = None
38
+ price: float | None = None
39
+ tags: list[str] | None = None
40
+ qualityScore: float | None = 0.5
41
+ recency: str | None = None
42
+ complexity: str | None = None
43
+ compatibility: list[str] | None = None
44
+ privacyRating: float | None = None
45
+ opensource: bool | None = None
46
+
47
+
48
+ @dataclass
49
+ class RankedResult:
50
+ """Represents a ranked result with alignment score and reasons"""
51
+
52
+ result: SearchResult
53
+ alignmentScore: float
54
+ matchReasons: list[str]
55
+
56
+
57
+ @dataclass
58
+ class RankingRequest:
59
+ """Request object for ranking API"""
60
+
61
+ intent: UniversalIntent
62
+ candidates: list[SearchResult]
63
+ options: dict[str, Any] | None = None
64
+
65
+
66
+ @dataclass
67
+ class RankingResponse:
68
+ """Response object for ranking API"""
69
+
70
+ rankedResults: list[RankedResult]
71
+ cache_hit: bool = False
72
+ processing_time_ms: float = 0.0
73
+
74
+
75
+ class OptimizedConstraintSatisfactionEngine:
76
+ """Improved constraint satisfaction with better performance"""
77
+
78
+ def __init__(self):
79
+ self.embedding_service = get_embedding_service()
80
+
81
+ def satisfies_constraints(
82
+ self, result: SearchResult, constraints: list[Constraint]
83
+ ) -> bool:
84
+ """Check if a result satisfies all hard constraints"""
85
+ if not constraints:
86
+ return True
87
+
88
+ for constraint in constraints:
89
+ if not constraint.hardFilter:
90
+ continue
91
+
92
+ if not self._satisfies_single_constraint(result, constraint):
93
+ return False
94
+
95
+ return True
96
+
97
+ def _satisfies_single_constraint(
98
+ self, result: SearchResult, constraint: Constraint
99
+ ) -> bool:
100
+ """Check if a result satisfies a single constraint"""
101
+ dimension = constraint.dimension
102
+ value = constraint.value
103
+ constraint_type = constraint.type
104
+
105
+ result_value = getattr(result, dimension, None)
106
+
107
+ if constraint_type == ConstraintType.INCLUSION:
108
+ if isinstance(value, str):
109
+ if result_value is None:
110
+ return False
111
+ return result_value.lower() == value.lower()
112
+ if isinstance(value, list):
113
+ if result_value is None:
114
+ return False
115
+ result_lower = str(result_value).lower()
116
+ return any(result_lower == str(v).lower() for v in value)
117
+
118
+ elif constraint_type == ConstraintType.EXCLUSION:
119
+ if isinstance(value, str):
120
+ if result_value is None:
121
+ return True
122
+ return result_value.lower() != value.lower()
123
+ if isinstance(value, list):
124
+ if result_value is None:
125
+ return True
126
+ result_lower = str(result_value).lower()
127
+ return all(result_lower != str(v).lower() for v in value)
128
+
129
+ elif (
130
+ constraint_type == ConstraintType.RANGE
131
+ and dimension == "price"
132
+ and result_value is not None
133
+ ):
134
+ return self._check_price_range(result_value, value)
135
+
136
+ return True
137
+
138
+ def _check_price_range(self, price: float, range_spec: str) -> bool:
139
+ """Check if price satisfies range specification"""
140
+ range_spec = str(range_spec).lower().strip()
141
+ if range_spec in {"budget", "free", "0"}:
142
+ return price == 0
143
+ return True # Simplified for now
144
+
145
+
146
+ class OptimizedIntentAlignmentEngine:
147
+ """Improved intent alignment with better scoring using ONNX"""
148
+
149
+ def __init__(self):
150
+ self.embedding_service = get_embedding_service()
151
+
152
+ def compute_intent_alignment(
153
+ self, result: SearchResult, intent: UniversalIntent
154
+ ) -> tuple[float, list[str]]:
155
+ """Compute alignment score with improved weighting"""
156
+ scores = []
157
+ reasons = []
158
+
159
+ declared = intent.declared or DeclaredIntent()
160
+ inferred = intent.inferred or InferredIntent()
161
+
162
+ # 1. Query-content alignment (semantic similarity) - 40% (Boosted)
163
+ query_score, query_reasons = self._compute_query_content_alignment(
164
+ result, intent, declared
165
+ )
166
+ scores.append((query_score, 0.40))
167
+ reasons.extend(query_reasons)
168
+
169
+ # 2. Use case alignment - 20%
170
+ use_case_score, use_case_reasons = self._compute_use_case_alignment(
171
+ result, intent, inferred
172
+ )
173
+ scores.append((use_case_score, 0.20))
174
+ reasons.extend(use_case_reasons)
175
+
176
+ # 3. Ethical signal alignment - 15%
177
+ ethical_score, ethical_reasons = self._compute_ethical_alignment(
178
+ result, intent, inferred
179
+ )
180
+ scores.append((ethical_score, 0.15))
181
+ reasons.extend(ethical_reasons)
182
+
183
+ # 4. Skill level alignment - 15%
184
+ skill_score, skill_reasons = self._compute_skill_alignment(
185
+ result, intent, declared
186
+ )
187
+ scores.append((skill_score, 0.15))
188
+ reasons.extend(skill_reasons)
189
+
190
+ # 5. Quality score - 10%
191
+ quality_score = result.qualityScore or 0.5
192
+ scores.append((quality_score, 0.10))
193
+
194
+ # Calculate weighted average
195
+ alignment_score = sum(score * weight for score, weight in scores)
196
+ alignment_score = max(0.0, min(1.0, alignment_score))
197
+
198
+ return alignment_score, list(set(reasons))
199
+
200
+ def _compute_query_content_alignment(
201
+ self, result: SearchResult, intent: UniversalIntent, declared: DeclaredIntent
202
+ ) -> tuple[float, list[str]]:
203
+ """Compute semantic similarity between query and result using shared ONNX"""
204
+ reasons = []
205
+ query = declared.query if declared else None
206
+ if not query:
207
+ return 0.5, reasons
208
+
209
+ content = f"{result.title} {result.description}".strip()
210
+ if not content:
211
+ return 0.0, reasons
212
+
213
+ # Get embeddings via shared ONNX service
214
+ query_emb = self.embedding_service.encode_text(query)
215
+ content_emb = self.embedding_service.encode_text(content)
216
+
217
+ if query_emb is not None and content_emb is not None:
218
+ similarity = self.embedding_service.cosine_similarity(
219
+ query_emb, content_emb
220
+ )
221
+ score = (similarity + 1) / 2 # Normalize to 0-1
222
+
223
+ if score > 0.7:
224
+ reasons.append("high-semantic-match")
225
+ elif score > 0.5:
226
+ reasons.append("semantic-match")
227
+
228
+ return score, reasons
229
+
230
+ return 0.5, ["keyword-fallback"]
231
+
232
+ def _compute_use_case_alignment(
233
+ self, result: SearchResult, intent: UniversalIntent, inferred: InferredIntent
234
+ ) -> tuple[float, list[str]]:
235
+ """Compute use case alignment"""
236
+ reasons = []
237
+ use_cases = inferred.useCases if inferred else []
238
+ if not use_cases or not result.tags:
239
+ return 0.5, reasons
240
+
241
+ score = 0.0
242
+ tag_text = " ".join(result.tags).lower()
243
+
244
+ for use_case in use_cases:
245
+ use_case_str = str(use_case.value).replace("_", " ")
246
+ if use_case_str in tag_text:
247
+ score += 1.0
248
+ reasons.append(f"use-case-{use_case.value}")
249
+
250
+ score = min(1.0, score / len(use_cases)) if use_cases else 0.5
251
+ return score, reasons
252
+
253
+ def _compute_ethical_alignment(
254
+ self, result: SearchResult, intent: UniversalIntent, inferred: InferredIntent
255
+ ) -> tuple[float, list[str]]:
256
+ """Compute ethical signal alignment"""
257
+ reasons = []
258
+ ethical_signals = inferred.ethicalSignals if inferred else []
259
+ if not ethical_signals:
260
+ return 0.5, reasons
261
+
262
+ score = 0.0
263
+ for signal in ethical_signals:
264
+ if signal.dimension == EthicalDimension.PRIVACY:
265
+ if result.privacyRating and result.privacyRating > 0.7:
266
+ score += 1.0
267
+ reasons.append("privacy-aligned")
268
+ elif signal.dimension == EthicalDimension.OPENNESS:
269
+ if result.opensource:
270
+ score += 1.0
271
+ reasons.append("open-source-aligned")
272
+
273
+ score = min(1.0, score / len(ethical_signals)) if ethical_signals else 0.5
274
+ return score, reasons
275
+
276
+ def _compute_skill_alignment(
277
+ self, result: SearchResult, intent: UniversalIntent, declared: DeclaredIntent
278
+ ) -> tuple[float, list[str]]:
279
+ """Compute skill level alignment"""
280
+ reasons = []
281
+ declared_skill = declared.skillLevel if declared else SkillLevel.INTERMEDIATE
282
+ result_complexity = result.complexity
283
+
284
+ if not result_complexity:
285
+ return 0.5, reasons
286
+
287
+ # Simple string match for complexity
288
+ if result_complexity.lower() in str(declared_skill.name).lower():
289
+ return 1.0, ["exact-skill-match"]
290
+
291
+ return 0.5, reasons
292
+
293
+
294
+ class ResultDeduplicator:
295
+ """Deduplicate results based on content similarity"""
296
+
297
+ def __init__(self, similarity_threshold: float = 0.9):
298
+ self.similarity_threshold = similarity_threshold
299
+ self.embedding_service = get_embedding_service()
300
+
301
+ def deduplicate(self, results: list[RankedResult]) -> list[RankedResult]:
302
+ if not results:
303
+ return results
304
+
305
+ unique_results = []
306
+ seen_hashes = set()
307
+
308
+ for result in results:
309
+ # Fast hash-based deduplication
310
+ content_hash = hashlib.md5(
311
+ f"{result.result.title}".lower().encode()
312
+ ).hexdigest()
313
+ if content_hash not in seen_hashes:
314
+ unique_results.append(result)
315
+ seen_hashes.add(content_hash)
316
+
317
+ return unique_results
318
+
319
+
320
+ class OptimizedIntentRanker:
321
+ """Main ranking class with ONNX optimizations"""
322
+
323
+ def __init__(self):
324
+ self.constraint_engine = OptimizedConstraintSatisfactionEngine()
325
+ self.alignment_engine = OptimizedIntentAlignmentEngine()
326
+ self.deduplicator = ResultDeduplicator()
327
+ self.cache = get_ranking_cache()
328
+
329
+ def rank_results(self, request: RankingRequest) -> RankingResponse:
330
+ import time
331
+
332
+ start_time = time.time()
333
+
334
+ # Filter candidates
335
+ filtered_candidates = self._filter_candidates(request)
336
+
337
+ # Compute alignment scores
338
+ ranked_results = []
339
+ for candidate in filtered_candidates:
340
+ score, reasons = self.alignment_engine.compute_intent_alignment(
341
+ candidate, request.intent
342
+ )
343
+ ranked_results.append(
344
+ RankedResult(
345
+ result=candidate, alignmentScore=score, matchReasons=reasons
346
+ )
347
+ )
348
+
349
+ # Deduplicate
350
+ ranked_results = self.deduplicator.deduplicate(ranked_results)
351
+
352
+ # Sort by score
353
+ ranked_results.sort(key=lambda x: x.alignmentScore, reverse=True)
354
+
355
+ processing_time = (time.time() - start_time) * 1000
356
+ return RankingResponse(
357
+ rankedResults=ranked_results,
358
+ cache_hit=False,
359
+ processing_time_ms=processing_time,
360
+ )
361
+
362
+ def _filter_candidates(self, request: RankingRequest) -> list[SearchResult]:
363
+ if not request.intent.declared or not request.intent.declared.constraints:
364
+ return request.candidates
365
+
366
+ filtered = []
367
+ for candidate in request.candidates:
368
+ if self.constraint_engine.satisfies_constraints(
369
+ candidate, request.intent.declared.constraints
370
+ ):
371
+ filtered.append(candidate)
372
+ return filtered
373
+
374
+
375
+ # Global instance
376
+ _ranker_instance = None
377
+
378
+
379
+ def get_intent_ranker() -> OptimizedIntentRanker:
380
+ global _ranker_instance
381
+ if _ranker_instance is None:
382
+ _ranker_instance = OptimizedIntentRanker()
383
+ return _ranker_instance
384
+
385
+
386
+ def rank_results(request: RankingRequest) -> RankingResponse:
387
+ ranker = get_intent_ranker()
388
+ return ranker.rank_results(request)
services/query_layer/app/ranking/optimized_url_ranker.py ADDED
@@ -0,0 +1,621 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Intent Engine - Optimized URL Ranking Module
3
+
4
+ This module provides an efficient URL ranking system with:
5
+ - Parallel processing with asyncio and thread pools
6
+ - Persistent caching for URL metadata
7
+ - Batch embedding computation
8
+ - Better privacy scoring
9
+ - Configurable ranking weights
10
+ """
11
+
12
+ import asyncio
13
+ import logging
14
+ import time
15
+ from concurrent.futures import ThreadPoolExecutor
16
+ from dataclasses import dataclass
17
+ from typing import Any
18
+ from urllib.parse import urlparse
19
+
20
+ from app.config.hybrid_query_cache import get_url_analysis_cache
21
+ from app.config.optimized_cache import get_embedding_cache
22
+ from app.core.schema import EthicalDimension, UniversalIntent
23
+
24
+ logger = logging.getLogger(__name__)
25
+
26
+
27
+ @dataclass
28
+ class URLResult:
29
+ """Represents a URL with its metadata and scores"""
30
+
31
+ url: str
32
+ title: str | None = None
33
+ description: str | None = None
34
+ domain: str | None = None
35
+ favicon: str | None = None
36
+
37
+ # Privacy-focused attributes
38
+ privacy_score: float = 0.5
39
+ tracker_count: int = 0
40
+ cookie_policy: str | None = None
41
+ data_retention_days: int | None = None
42
+ encryption_enabled: bool = True
43
+
44
+ # Content attributes
45
+ content_type: str | None = None
46
+ language: str | None = None
47
+ recency: str | None = None
48
+
49
+ # Ethics and quality
50
+ is_open_source: bool = False
51
+ is_non_profit: bool = False
52
+ has_terms_of_service: bool = True
53
+
54
+ # Scores
55
+ relevance_score: float = 0.0
56
+ final_score: float = 0.0
57
+
58
+ # Processing metadata
59
+ processing_time_ms: float = 0.0
60
+ cache_hit: bool = False
61
+
62
+
63
+ @dataclass
64
+ class URLRankingRequest:
65
+ """Request for URL ranking"""
66
+
67
+ query: str
68
+ urls: list[str]
69
+ intent: UniversalIntent | None = None
70
+ options: dict[str, Any] | None = None
71
+
72
+
73
+ @dataclass
74
+ class URLRankingResponse:
75
+ """Response from URL ranking"""
76
+
77
+ query: str
78
+ ranked_urls: list[URLResult]
79
+ processing_time_ms: float
80
+ total_urls: int
81
+ filtered_count: int = 0
82
+ cache_hit_rate: float = 0.0
83
+
84
+
85
+ class PrivacyDatabase:
86
+ """Database of known privacy-friendly and big-tech domains"""
87
+
88
+ # Privacy-focused domains (high scores)
89
+ PRIVACY_FRIENDLY_DOMAINS = {
90
+ # Email services
91
+ "protonmail.com",
92
+ "tutanota.com",
93
+ "mailbox.org",
94
+ "startmail.com",
95
+ # Search engines
96
+ "duckduckgo.com",
97
+ "startpage.com",
98
+ "searx.space",
99
+ "qwant.com",
100
+ # Browsers
101
+ "firefox.com",
102
+ "mozilla.org",
103
+ "brave.com",
104
+ "torproject.org",
105
+ # VPN/Security
106
+ "mullvad.net",
107
+ "ivpn.net",
108
+ "protonvpn.com",
109
+ "nordvpn.com",
110
+ # Privacy tools
111
+ "privacytools.io",
112
+ "privacyguides.org",
113
+ "ssd.eff.org",
114
+ # Open source platforms
115
+ "github.com",
116
+ "gitlab.com",
117
+ "codeberg.org",
118
+ "sourcehut.org",
119
+ # Knowledge bases
120
+ "wikipedia.org",
121
+ "wikimedia.org",
122
+ # Linux distributions
123
+ "ubuntu.com",
124
+ "debian.org",
125
+ "archlinux.org",
126
+ "fedoraproject.org",
127
+ }
128
+
129
+ # Big Tech domains (lower scores)
130
+ BIG_TECH_DOMAINS = {
131
+ # Google
132
+ "google.com",
133
+ "google.co",
134
+ "youtube.com",
135
+ "gmail.com",
136
+ "android.com",
137
+ "chrome.com",
138
+ "googleapis.com",
139
+ "googleusercontent.com",
140
+ # Microsoft
141
+ "microsoft.com",
142
+ "windows.com",
143
+ "office.com",
144
+ "outlook.com",
145
+ "hotmail.com",
146
+ "live.com",
147
+ "msn.com",
148
+ "bing.com",
149
+ # Apple
150
+ "apple.com",
151
+ "icloud.com",
152
+ "me.com",
153
+ "mac.com",
154
+ # Meta
155
+ "facebook.com",
156
+ "instagram.com",
157
+ "whatsapp.com",
158
+ "messenger.com",
159
+ # Amazon
160
+ "amazon.com",
161
+ "amazon.co",
162
+ "aws.amazon.com",
163
+ "alexa.com",
164
+ # Twitter/X
165
+ "twitter.com",
166
+ "x.com",
167
+ "tweetdeck.com",
168
+ # LinkedIn (Microsoft)
169
+ "linkedin.com",
170
+ "licdn.com",
171
+ # TikTok
172
+ "tiktok.com",
173
+ "tiktokv.com",
174
+ }
175
+
176
+ # Known tracker domains
177
+ TRACKER_DOMAINS = {
178
+ "google-analytics.com",
179
+ "googletagmanager.com",
180
+ "googleadservices.com",
181
+ "doubleclick.net",
182
+ "googlesyndication.com",
183
+ "googleapis.com",
184
+ "facebook.net",
185
+ "facebook.com",
186
+ "fbcdn.net",
187
+ "amazon-adsystem.com",
188
+ "amazon.com",
189
+ "twitter.com",
190
+ "twimg.com",
191
+ "linkedin.com",
192
+ "licdn.com",
193
+ "outbrain.com",
194
+ "taboola.com",
195
+ "criteo.com",
196
+ "criteo.net",
197
+ "adnxs.com",
198
+ "appnexus.com",
199
+ "pubmatic.com",
200
+ "rubiconproject.com",
201
+ "openx.net",
202
+ "openx.com",
203
+ "scorecardresearch.com",
204
+ "comscore.com",
205
+ "quantserve.com",
206
+ "quantcount.com",
207
+ "moatads.com",
208
+ "moatpixel.com",
209
+ }
210
+
211
+ @classmethod
212
+ def get_privacy_score(cls, domain: str) -> float:
213
+ """Get privacy score for a domain (0-1)"""
214
+ domain_lower = domain.lower()
215
+
216
+ # Check exact match
217
+ if domain_lower in cls.PRIVACY_FRIENDLY_DOMAINS:
218
+ return 0.95
219
+
220
+ if domain_lower in cls.BIG_TECH_DOMAINS:
221
+ return 0.3
222
+
223
+ # Check subdomains
224
+ for privacy_domain in cls.PRIVACY_FRIENDLY_DOMAINS:
225
+ if domain_lower.endswith("." + privacy_domain):
226
+ return 0.9
227
+
228
+ for big_tech in cls.BIG_TECH_DOMAINS:
229
+ if domain_lower.endswith("." + big_tech):
230
+ return 0.25
231
+
232
+ # Check for tracker subdomains
233
+ for tracker in cls.TRACKER_DOMAINS:
234
+ if tracker in domain_lower:
235
+ return 0.1
236
+
237
+ # Default score
238
+ return 0.5
239
+
240
+ @classmethod
241
+ def is_big_tech(cls, domain: str) -> bool:
242
+ """Check if domain belongs to Big Tech"""
243
+ domain_lower = domain.lower()
244
+
245
+ if domain_lower in cls.BIG_TECH_DOMAINS:
246
+ return True
247
+
248
+ return any(domain_lower.endswith("." + big_tech) for big_tech in cls.BIG_TECH_DOMAINS)
249
+
250
+ @classmethod
251
+ def count_trackers(cls, domain: str) -> int:
252
+ """Count known trackers in domain"""
253
+ domain_lower = domain.lower()
254
+ count = 0
255
+
256
+ for tracker in cls.TRACKER_DOMAINS:
257
+ if tracker in domain_lower:
258
+ count += 1
259
+
260
+ return count
261
+
262
+
263
+ class URLAnalyzer:
264
+ """Analyzes URLs for privacy and content metadata"""
265
+
266
+ def __init__(self):
267
+ self.cache = get_url_analysis_cache()
268
+ self.embedding_cache = get_embedding_cache()
269
+
270
+ def analyze_url(self, url: str, use_cache: bool = True) -> URLResult:
271
+ """Analyze a URL and return metadata"""
272
+ # Check cache
273
+ if use_cache:
274
+ cached = self.cache.get(url)
275
+ if cached is not None:
276
+ result = cached
277
+ result.cache_hit = True
278
+ return result
279
+
280
+ # Parse URL
281
+ parsed = urlparse(url)
282
+ domain = parsed.netloc.lower()
283
+
284
+ # Remove www prefix
285
+ if domain.startswith("www."):
286
+ domain = domain[4:]
287
+
288
+ # Create result
289
+ result = URLResult(
290
+ url=url,
291
+ domain=domain,
292
+ title=self._extract_title(domain),
293
+ description=f"Web resource from {domain}",
294
+ privacy_score=PrivacyDatabase.get_privacy_score(domain),
295
+ tracker_count=PrivacyDatabase.count_trackers(domain),
296
+ encryption_enabled=url.startswith("https"),
297
+ content_type=self._detect_content_type(url),
298
+ is_open_source=self._is_open_source(domain),
299
+ is_non_profit=self._is_non_profit(domain),
300
+ cache_hit=False,
301
+ )
302
+
303
+ # Cache result
304
+ if use_cache:
305
+ self.cache.set(url, result, ttl_seconds=3600) # 1 hour TTL
306
+
307
+ return result
308
+
309
+ def _extract_title(self, domain: str) -> str:
310
+ """Extract a readable title from domain"""
311
+ # Remove TLD and common prefixes
312
+ parts = domain.split(".")
313
+ if len(parts) >= 2:
314
+ name = parts[-2] # Second-level domain
315
+ # Clean up common patterns
316
+ name = name.replace("-", " ").replace("_", " ")
317
+ return name.title()
318
+ return domain
319
+
320
+ def _detect_content_type(self, url: str) -> str:
321
+ """Detect content type from URL patterns"""
322
+ url_lower = url.lower()
323
+
324
+ patterns = {
325
+ "documentation": [
326
+ "/docs/",
327
+ "/documentation/",
328
+ "/wiki/",
329
+ "/help/",
330
+ "/guide/",
331
+ "/manual/",
332
+ ],
333
+ "article": ["/blog/", "/article/", "/post/", "/news/", "/story/"],
334
+ "forum": ["/forum/", "/community/", "/discuss/", "/thread/", "/topic/"],
335
+ "video": ["/video/", "/watch/", "/v/", "/youtube.com/", "/vimeo.com/"],
336
+ "image": ["/image/", "/photo/", "/gallery/", "/img/", "/pic/"],
337
+ "tool": ["/tool/", "/app/", "/calculator/", "/converter/", "/generator/"],
338
+ "download": ["/download/", "/file/", "/software/", "/install/"],
339
+ }
340
+
341
+ for content_type, patterns_list in patterns.items():
342
+ if any(pattern in url_lower for pattern in patterns_list):
343
+ return content_type
344
+
345
+ return "general"
346
+
347
+ def _is_open_source(self, domain: str) -> bool:
348
+ """Check if domain is likely open source"""
349
+ open_source_indicators = [
350
+ "github.com",
351
+ "gitlab.com",
352
+ "codeberg.org",
353
+ "sourcehut.org",
354
+ "apache.org",
355
+ "mozilla.org",
356
+ "gnu.org",
357
+ "linux.org",
358
+ "debian.org",
359
+ "ubuntu.com",
360
+ "archlinux.org",
361
+ "fedoraproject.org",
362
+ ]
363
+ return any(indicator in domain for indicator in open_source_indicators)
364
+
365
+ def _is_non_profit(self, domain: str) -> bool:
366
+ """Check if domain is likely non-profit"""
367
+ non_profit_indicators = [
368
+ ".org",
369
+ "wikipedia.org",
370
+ "wikimedia.org",
371
+ "eff.org",
372
+ "mozilla.org",
373
+ "apache.org",
374
+ "gnu.org",
375
+ ]
376
+ return any(indicator in domain for indicator in non_profit_indicators)
377
+
378
+
379
+ class URLRanker:
380
+ """Main URL ranking class with parallel processing"""
381
+
382
+ def __init__(self):
383
+ self.analyzer = URLAnalyzer()
384
+ self.embedding_cache = get_embedding_cache()
385
+ self.executor = ThreadPoolExecutor(max_workers=4)
386
+ self.default_weights = {
387
+ "relevance": 0.40,
388
+ "privacy": 0.30,
389
+ "quality": 0.20,
390
+ "ethics": 0.10,
391
+ }
392
+
393
+ async def rank_urls(self, request: URLRankingRequest) -> URLRankingResponse:
394
+ """Rank URLs with parallel processing"""
395
+ start_time = time.time()
396
+
397
+ # Get options
398
+ options = request.options or {}
399
+ weights = options.get("weights", self.default_weights)
400
+ min_privacy_score = options.get("min_privacy_score", 0.0)
401
+ exclude_big_tech = options.get("exclude_big_tech", False)
402
+
403
+ # Extract negative preferences from intent
404
+ negative_preferences = None
405
+ if request.intent and request.intent.declared and request.intent.declared.negativePreferences:
406
+ negative_preferences = request.intent.declared.negativePreferences
407
+
408
+ # Analyze all URLs in parallel
409
+ url_results = await self._analyze_urls_parallel(request.urls)
410
+
411
+ # Calculate cache hit rate
412
+ cache_hits = sum(1 for r in url_results if r.cache_hit)
413
+ cache_hit_rate = cache_hits / len(url_results) if url_results else 0
414
+
415
+ # Filter URLs
416
+ filtered_results = self._filter_urls(url_results, min_privacy_score, exclude_big_tech, negative_preferences)
417
+ filtered_count = len(url_results) - len(filtered_results)
418
+
419
+ # Calculate relevance scores
420
+ await self._calculate_relevance_scores(filtered_results, request.query)
421
+
422
+ # Calculate final scores
423
+ self._calculate_final_scores(filtered_results, weights, request.intent)
424
+
425
+ # Sort by final score
426
+ filtered_results.sort(key=lambda x: x.final_score, reverse=True)
427
+
428
+ # Calculate processing time
429
+ processing_time = (time.time() - start_time) * 1000
430
+
431
+ return URLRankingResponse(
432
+ query=request.query,
433
+ ranked_urls=filtered_results,
434
+ processing_time_ms=processing_time,
435
+ total_urls=len(request.urls),
436
+ filtered_count=filtered_count,
437
+ cache_hit_rate=cache_hit_rate,
438
+ )
439
+
440
+ async def _analyze_urls_parallel(self, urls: list[str]) -> list[URLResult]:
441
+ """Analyze multiple URLs in parallel"""
442
+ # Create tasks for parallel execution
443
+ tasks = [
444
+ asyncio.get_running_loop().run_in_executor(self.executor, self.analyzer.analyze_url, url) for url in urls
445
+ ]
446
+
447
+ # Wait for all tasks
448
+ results = await asyncio.gather(*tasks, return_exceptions=True)
449
+
450
+ # Filter out exceptions
451
+ valid_results = []
452
+ for i, result in enumerate(results):
453
+ if isinstance(result, Exception):
454
+ logger.warning(f"Failed to analyze URL {urls[i]}: {result}")
455
+ # Create fallback result
456
+ valid_results.append(URLResult(url=urls[i]))
457
+ else:
458
+ valid_results.append(result)
459
+
460
+ return valid_results
461
+
462
+ def _filter_urls(
463
+ self,
464
+ results: list[URLResult],
465
+ min_privacy_score: float,
466
+ exclude_big_tech: bool,
467
+ negative_preferences: list[str] | None = None,
468
+ ) -> list[URLResult]:
469
+ """Filter URLs based on criteria"""
470
+ filtered = []
471
+
472
+ for result in results:
473
+ # Check minimum privacy score (handle None case)
474
+ if result.privacy_score is not None and result.privacy_score < min_privacy_score:
475
+ continue
476
+
477
+ # Check Big Tech exclusion
478
+ if exclude_big_tech and PrivacyDatabase.is_big_tech(result.domain):
479
+ continue
480
+
481
+ # Apply negative preferences (e.g., "no google")
482
+ if negative_preferences and not self._satisfies_negative_preferences(result, negative_preferences):
483
+ continue
484
+
485
+ filtered.append(result)
486
+
487
+ return filtered
488
+
489
+ def _satisfies_negative_preferences(self, url_result: URLResult, preferences: list[str]) -> bool:
490
+ """Check if URL satisfies negative preferences like 'no google'"""
491
+ for pref in preferences:
492
+ pref_lower = pref.lower().replace("no ", "").replace("not ", "")
493
+
494
+ # Check against big tech domains
495
+ privacy_db = PrivacyDatabase()
496
+ for big_tech in privacy_db.BIG_TECH_DOMAINS:
497
+ if big_tech.replace(".com", "").replace(".", " ") in pref_lower:
498
+ if big_tech in url_result.domain or url_result.domain.endswith("." + big_tech):
499
+ return False
500
+
501
+ return True
502
+
503
+ async def _calculate_relevance_scores(self, results: list[URLResult], query: str) -> None:
504
+ """Calculate semantic relevance scores for all URLs"""
505
+ if not results or not query:
506
+ return
507
+
508
+ # Get query embedding
509
+ query_emb = self.embedding_cache.encode_text(query)
510
+ if query_emb is None:
511
+ # Fallback to simple keyword matching
512
+ for result in results:
513
+ result.relevance_score = self._keyword_relevance(query, result)
514
+ return
515
+
516
+ # Prepare content texts
517
+ contents = [f"{result.title} {result.description} {result.domain}" for result in results]
518
+
519
+ # Get embeddings in batch
520
+ content_embs = self.embedding_cache.encode_batch(contents)
521
+
522
+ # Calculate similarities
523
+ for _i, (result, content_emb) in enumerate(zip(results, content_embs, strict=False)):
524
+ if content_emb is not None:
525
+ similarity = self.embedding_cache.cosine_similarity(query_emb, content_emb)
526
+ result.relevance_score = (similarity + 1) / 2 # Normalize to 0-1
527
+ else:
528
+ result.relevance_score = self._keyword_relevance(query, result)
529
+
530
+ def _keyword_relevance(self, query: str, result: URLResult) -> float:
531
+ """Calculate keyword-based relevance"""
532
+ query_words = set(query.lower().split())
533
+ content = f"{result.title} {result.description} {result.domain}".lower()
534
+
535
+ if not query_words:
536
+ return 0.5
537
+
538
+ matches = query_words.intersection(set(content.split()))
539
+ return len(matches) / len(query_words)
540
+
541
+ def _calculate_final_scores(
542
+ self,
543
+ results: list[URLResult],
544
+ weights: dict[str, float],
545
+ intent: UniversalIntent | None,
546
+ ) -> None:
547
+ """Calculate final weighted scores"""
548
+ for result in results:
549
+ # Base scores
550
+ scores = {
551
+ "relevance": result.relevance_score,
552
+ "privacy": result.privacy_score,
553
+ "quality": 0.7 if result.encryption_enabled else 0.3,
554
+ "ethics": self._calculate_ethics_score(result),
555
+ }
556
+
557
+ # Apply intent-based boosts
558
+ if intent:
559
+ scores = self._apply_intent_boosts(scores, result, intent)
560
+
561
+ # Calculate weighted average
562
+ total_weight = sum(weights.values())
563
+ result.final_score = (
564
+ sum(scores[key] * weights.get(key, 0) for key in scores) / total_weight if total_weight > 0 else 0
565
+ )
566
+
567
+ def _calculate_ethics_score(self, result: URLResult) -> float:
568
+ """Calculate ethics score"""
569
+ score = 0.5
570
+
571
+ if result.is_open_source:
572
+ score += 0.3
573
+
574
+ if result.is_non_profit:
575
+ score += 0.1
576
+
577
+ if result.privacy_score > 0.7:
578
+ score += 0.1
579
+
580
+ return min(1.0, score)
581
+
582
+ def _apply_intent_boosts(
583
+ self, scores: dict[str, float], result: URLResult, intent: UniversalIntent
584
+ ) -> dict[str, float]:
585
+ """Apply intent-based score boosts"""
586
+ # Check for privacy-focused queries
587
+ if intent.declared.query:
588
+ query_lower = intent.declared.query.lower()
589
+ privacy_keywords = ["privacy", "secure", "encrypted", "anonymous"]
590
+
591
+ if any(kw in query_lower for kw in privacy_keywords):
592
+ # Boost privacy score for privacy queries
593
+ scores["privacy"] = min(1.0, scores["privacy"] * 1.2)
594
+
595
+ # Check ethical signals
596
+ if intent.inferred.ethicalSignals:
597
+ for signal in intent.inferred.ethicalSignals:
598
+ if signal.dimension == EthicalDimension.PRIVACY:
599
+ scores["privacy"] = min(1.0, scores["privacy"] * 1.1)
600
+ elif signal.dimension == EthicalDimension.OPENNESS and result.is_open_source:
601
+ scores["ethics"] = min(1.0, scores["ethics"] * 1.2)
602
+
603
+ return scores
604
+
605
+
606
+ # Global instance
607
+ _url_ranker_instance = None
608
+
609
+
610
+ def get_url_ranker() -> URLRanker:
611
+ """Get singleton instance"""
612
+ global _url_ranker_instance
613
+ if _url_ranker_instance is None:
614
+ _url_ranker_instance = URLRanker()
615
+ return _url_ranker_instance
616
+
617
+
618
+ async def rank_urls(request: URLRankingRequest) -> URLRankingResponse:
619
+ """Main entry point"""
620
+ ranker = get_url_ranker()
621
+ return await ranker.rank_urls(request)
services/query_layer/app/ranking/ranker.py ADDED
@@ -0,0 +1,1043 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Intent Engine - Phase 2: Constraint Satisfaction and Result Ranking
3
+
4
+ This module implements Algorithms 2 and 3 for constraint satisfaction and intent-aligned ranking.
5
+ """
6
+
7
+ import logging
8
+ import re
9
+ import threading
10
+ from dataclasses import dataclass
11
+ from datetime import UTC
12
+ from typing import Any
13
+
14
+ import numpy as np
15
+
16
+ from app.core.embedding_service import get_embedding_service
17
+ from app.core.schema import (
18
+ Constraint,
19
+ ConstraintType,
20
+ EthicalDimension,
21
+ Recency,
22
+ SkillLevel,
23
+ TemporalHorizon,
24
+ UniversalIntent,
25
+ UseCase,
26
+ )
27
+
28
+ # Configure logging
29
+ logging.basicConfig(level=logging.INFO)
30
+ logger = logging.getLogger(__name__)
31
+
32
+
33
+ @dataclass
34
+ class SearchResult:
35
+ """Represents a search result candidate with metadata"""
36
+
37
+ id: str
38
+ title: str
39
+ description: str
40
+ platform: str | None = None
41
+ provider: str | None = None
42
+ license: str | None = None
43
+ price: float | None = None
44
+ tags: list[str] | None = None
45
+ qualityScore: float | None = 0.5 # Default quality score
46
+ recency: str | None = None # Publication date or update date
47
+ complexity: str | None = None # beginner, intermediate, advanced
48
+ compatibility: list[str] | None = None # Compatible platforms
49
+ privacyRating: float | None = None # Privacy rating if available
50
+ opensource: bool | None = None # Whether it's open source
51
+
52
+
53
+ @dataclass
54
+ class RankedResult:
55
+ """Represents a ranked result with alignment score and reasons"""
56
+
57
+ result: SearchResult
58
+ alignmentScore: float
59
+ matchReasons: list[str]
60
+
61
+
62
+ @dataclass
63
+ class RankingRequest:
64
+ """Request object for ranking API"""
65
+
66
+ intent: UniversalIntent
67
+ candidates: list[SearchResult]
68
+ options: dict[str, Any] | None = None # RankingOptions
69
+
70
+
71
+ @dataclass
72
+ class RankingResponse:
73
+ """Response object for ranking API"""
74
+
75
+ rankedResults: list[RankedResult]
76
+
77
+
78
+ class EmbeddingCache:
79
+ """Cache for embeddings to improve performance - uses shared EmbeddingService"""
80
+
81
+ def __init__(self, redis_client=None):
82
+ # Use the shared embedding service instead of loading models independently
83
+ self._service = get_embedding_service()
84
+ # Initialize if needed
85
+ self._service.initialize(use_redis=(redis_client is not None))
86
+
87
+ def encode_text(self, text: str) -> np.ndarray | None:
88
+ """Encode text to embedding vector using the shared service"""
89
+ return self._service.encode_text(text)
90
+
91
+ def encode_batch(self, texts: list[str]) -> list[np.ndarray | None]:
92
+ """Encode batch of texts using the shared service"""
93
+ return self._service.encode_batch(texts)
94
+
95
+ def cosine_similarity(self, vec1: np.ndarray, vec2: np.ndarray) -> float:
96
+ """Calculate cosine similarity between two vectors"""
97
+ return self._service.cosine_similarity(vec1, vec2)
98
+
99
+
100
+ class ConstraintSatisfactionEngine:
101
+ """Implements Algorithm 2: satisfiesConstraints()"""
102
+
103
+ def __init__(self):
104
+ self.embedding_cache = EmbeddingCache()
105
+
106
+ def satisfies_constraints(self, result: SearchResult, constraints: list[Constraint]) -> bool:
107
+ """
108
+ Check if a result satisfies all hard constraints
109
+ Implements Algorithm 2: satisfiesConstraints()
110
+ """
111
+ for constraint in constraints:
112
+ if not constraint.hardFilter:
113
+ continue # Skip soft constraints
114
+
115
+ if not self._satisfies_single_constraint(result, constraint):
116
+ return False
117
+
118
+ return True
119
+
120
+ def _satisfies_single_constraint(self, result: SearchResult, constraint: Constraint) -> bool:
121
+ """Check if a result satisfies a single constraint"""
122
+ dimension = constraint.dimension
123
+ value = constraint.value
124
+ constraint_type = constraint.type
125
+
126
+ if dimension == "platform":
127
+ if constraint_type == ConstraintType.INCLUSION:
128
+ if isinstance(value, str):
129
+ if result.platform != value:
130
+ return False
131
+ elif isinstance(value, list) and result.platform not in value:
132
+ return False
133
+ elif constraint_type == ConstraintType.EXCLUSION:
134
+ if isinstance(value, str):
135
+ if result.platform == value:
136
+ return False
137
+ elif isinstance(value, list) and result.platform in value:
138
+ return False
139
+
140
+ elif dimension == "provider":
141
+ if constraint_type == ConstraintType.INCLUSION:
142
+ if isinstance(value, str):
143
+ if result.provider != value:
144
+ return False
145
+ elif isinstance(value, list) and result.provider not in value:
146
+ return False
147
+ elif constraint_type == ConstraintType.EXCLUSION:
148
+ if isinstance(value, str):
149
+ if result.provider == value:
150
+ return False
151
+ elif isinstance(value, list) and result.provider in value:
152
+ return False
153
+
154
+ elif dimension == "license":
155
+ if constraint_type == ConstraintType.INCLUSION:
156
+ if isinstance(value, str):
157
+ if result.license != value:
158
+ return False
159
+ elif isinstance(value, list) and result.license not in value:
160
+ return False
161
+ elif constraint_type == ConstraintType.EXCLUSION:
162
+ if isinstance(value, str):
163
+ if result.license == value:
164
+ return False
165
+ elif isinstance(value, list) and result.license in value:
166
+ return False
167
+
168
+ elif dimension == "price":
169
+ if isinstance(value, str):
170
+ # Handle price ranges like "<=100" or ">=50"
171
+ match = re.match(r"([<>]=?)(\d+)", value)
172
+ if match:
173
+ operator, price_limit = match.groups()
174
+ price_limit = float(price_limit)
175
+
176
+ if constraint_type == ConstraintType.RANGE:
177
+ # Check price constraints
178
+ violates = False
179
+ if (
180
+ (operator == "<=" and result.price and result.price > price_limit)
181
+ or (operator == ">=" and result.price and result.price < price_limit)
182
+ or (operator == "<" and result.price and result.price >= price_limit)
183
+ or (operator == ">" and result.price and result.price <= price_limit)
184
+ ):
185
+ violates = True
186
+ if violates:
187
+ return False
188
+
189
+ elif dimension == "tags":
190
+ # Handle tags constraints
191
+ if constraint_type == ConstraintType.INCLUSION:
192
+ if isinstance(value, str):
193
+ # Check if the value is in result tags
194
+ if result.tags is None or value not in result.tags:
195
+ return False
196
+ elif isinstance(value, list):
197
+ # Check if any of the values are in result tags
198
+ if result.tags is None or not any(v in result.tags for v in value):
199
+ return False
200
+ elif constraint_type == ConstraintType.EXCLUSION:
201
+ if isinstance(value, str):
202
+ # Check if the value is NOT in result tags
203
+ if result.tags is not None and value in result.tags:
204
+ return False
205
+ elif isinstance(value, list):
206
+ # Check if none of the values are in result tags
207
+ if result.tags is not None and any(v in result.tags for v in value):
208
+ return False
209
+
210
+ elif dimension == "format":
211
+ # Handle format constraints (file format, document type, content format)
212
+ # Assumes result has a 'format' attribute or it can be inferred from tags/description
213
+ result_format = getattr(result, "format", None)
214
+
215
+ # Try to infer format from tags if not explicitly set
216
+ if result_format is None and result.tags:
217
+ format_tags = [
218
+ t for t in result.tags if t.lower() in ["pdf", "doc", "video", "audio", "interactive", "text"]
219
+ ]
220
+ if format_tags:
221
+ result_format = format_tags[0].lower()
222
+
223
+ if result_format is None:
224
+ # If no format info available, inclusion fails, exclusion passes
225
+ if constraint_type == ConstraintType.INCLUSION:
226
+ return False
227
+ # EXCLUSION
228
+ return True
229
+
230
+ result_format = result_format.lower()
231
+
232
+ if constraint_type == ConstraintType.INCLUSION:
233
+ if isinstance(value, str):
234
+ if value.lower() != result_format:
235
+ return False
236
+ elif isinstance(value, list) and not any(v.lower() == result_format for v in value):
237
+ return False
238
+ elif constraint_type == ConstraintType.EXCLUSION:
239
+ if isinstance(value, str):
240
+ if value.lower() == result_format:
241
+ return False
242
+ elif isinstance(value, list) and any(v.lower() == result_format for v in value):
243
+ return False
244
+
245
+ elif dimension == "recency":
246
+ # Handle recency constraints (content freshness)
247
+ # Assumes result.recency is in ISO format or similar
248
+ if not result.recency:
249
+ # If no recency info available, inclusion fails, exclusion passes
250
+ if constraint_type == ConstraintType.INCLUSION:
251
+ return False
252
+ # EXCLUSION
253
+ return True
254
+
255
+ from datetime import datetime
256
+
257
+ try:
258
+ # Parse result recency
259
+ recency_str = result.recency
260
+ if recency_str.endswith("Z"):
261
+ result_date = datetime.fromisoformat(recency_str.replace("Z", "+00:00"))
262
+ elif "+" in recency_str or recency_str.count("-") > 2: # Has timezone info
263
+ result_date = datetime.fromisoformat(recency_str)
264
+ else:
265
+ # Naive datetime, treat as UTC
266
+ result_date = datetime.fromisoformat(recency_str).replace(tzinfo=UTC)
267
+
268
+ now = datetime.now(UTC)
269
+ days_old = (now - result_date).days
270
+
271
+ # Handle recency constraint values
272
+ if isinstance(value, str):
273
+ value_lower = value.lower()
274
+
275
+ # Parse recency constraints like "last_7_days", "last_30_days", "this_year", etc.
276
+ if value_lower.startswith("last_") and value_lower.endswith("_days"):
277
+ try:
278
+ days_limit = int(value_lower.split("_")[1])
279
+ if days_old > days_limit:
280
+ return False
281
+ except (ValueError, IndexError):
282
+ pass
283
+ elif (
284
+ value_lower == "today"
285
+ and days_old > 1
286
+ or value_lower == "this_week"
287
+ and days_old > 7
288
+ or value_lower == "this_month"
289
+ and days_old > 30
290
+ ):
291
+ return False
292
+ elif value_lower == "this_year":
293
+ current_year = now.year
294
+ result_year = result_date.year
295
+ if result_year != current_year:
296
+ return False
297
+ elif value_lower == "evergreen":
298
+ # Evergreen content is old but still relevant - no filtering
299
+ pass
300
+
301
+ elif isinstance(value, dict):
302
+ # Handle structured recency constraints
303
+ if "max_days_old" in value:
304
+ max_days = value["max_days_old"]
305
+ if days_old > max_days:
306
+ return False
307
+ if "min_days_old" in value:
308
+ min_days = value["min_days_old"]
309
+ if days_old < min_days:
310
+ return False
311
+
312
+ except (ValueError, AttributeError):
313
+ # If date parsing fails, skip this check (fail open)
314
+ if constraint_type == ConstraintType.INCLUSION:
315
+ return False
316
+
317
+ # Handle exclusion constraints for recency
318
+ if constraint_type == ConstraintType.EXCLUSION and isinstance(value, str):
319
+ value_lower = value.lower()
320
+ # For exclusion, filter out if matches
321
+ if (
322
+ value_lower == "today"
323
+ and days_old <= 1
324
+ or value_lower == "this_week"
325
+ and days_old <= 7
326
+ or value_lower == "this_month"
327
+ and days_old <= 30
328
+ ):
329
+ return False
330
+
331
+ return True
332
+
333
+
334
+ class IntentAlignmentEngine:
335
+ """Implements Algorithm 3: computeIntentAlignment()"""
336
+
337
+ def __init__(self):
338
+ self.embedding_cache = EmbeddingCache()
339
+
340
+ def compute_intent_alignment(self, result: SearchResult, intent: UniversalIntent) -> tuple[float, list[str]]:
341
+ """
342
+ Compute alignment score between a result and user intent
343
+ Implements Algorithm 3: computeIntentAlignment()
344
+ """
345
+ scores = []
346
+ reasons = []
347
+
348
+ # 1. Query-content alignment (semantic similarity)
349
+ query_content_score, query_reasons = self._compute_query_content_alignment(result, intent)
350
+ scores.append(query_content_score)
351
+ reasons.extend(query_reasons)
352
+
353
+ # 2. Use case alignment (semantic similarity)
354
+ use_case_score, use_case_reasons = self._compute_use_case_alignment(result, intent)
355
+ scores.append(use_case_score)
356
+ reasons.extend(use_case_reasons)
357
+
358
+ # 3. Ethical signal alignment
359
+ ethical_score, ethical_reasons = self._compute_ethical_alignment(result, intent)
360
+ scores.append(ethical_score)
361
+ reasons.extend(ethical_reasons)
362
+
363
+ # 4. Skill level alignment
364
+ skill_score, skill_reasons = self._compute_skill_alignment(result, intent)
365
+ scores.append(skill_score)
366
+ reasons.extend(skill_reasons)
367
+
368
+ # 5. Temporal intent alignment
369
+ temporal_score, temporal_reasons = self._compute_temporal_alignment(result, intent)
370
+ scores.append(temporal_score)
371
+ reasons.extend(temporal_reasons)
372
+
373
+ # 6. Quality score (if available)
374
+ quality_score = result.qualityScore or 0.5
375
+ scores.append(quality_score)
376
+
377
+ # Weighted combination of scores
378
+ weights = [0.30, 0.20, 0.15, 0.15, 0.10, 0.10] # Sum to 1.0
379
+
380
+ # Ensure we have the right number of weights
381
+ if len(scores) != len(weights):
382
+ # Adjust weights if needed
383
+ adjusted_weights = list(weights[: len(scores)])
384
+ remaining_weight = 1.0 - sum(adjusted_weights)
385
+ if remaining_weight > 0 and len(adjusted_weights) > 0:
386
+ adjusted_weights[0] += remaining_weight
387
+ elif remaining_weight > 0:
388
+ adjusted_weights = [remaining_weight]
389
+ weights = adjusted_weights
390
+
391
+ alignment_score = sum(score * weight for score, weight in zip(scores, weights, strict=False))
392
+
393
+ # Clamp the score between 0 and 1
394
+ alignment_score = max(0.0, min(1.0, alignment_score))
395
+
396
+ return alignment_score, reasons
397
+
398
+ def _compute_query_content_alignment(
399
+ self, result: SearchResult, intent: UniversalIntent
400
+ ) -> tuple[float, list[str]]:
401
+ """Compute alignment based on query-content similarity"""
402
+ reasons = []
403
+
404
+ if not intent.declared.query:
405
+ return 0.5, reasons # Neutral score if no query
406
+
407
+ # Combine title and description for content
408
+ content = f"{result.title} {result.description}".strip()
409
+
410
+ if not content:
411
+ return 0.0, reasons
412
+
413
+ # Get embeddings for semantic similarity
414
+ query_embedding = self.embedding_cache.encode_text(intent.declared.query)
415
+ content_embedding = self.embedding_cache.encode_text(content)
416
+
417
+ if query_embedding is not None and content_embedding is not None:
418
+ similarity = self.embedding_cache.cosine_similarity(query_embedding, content_embedding)
419
+ # Normalize to 0-1 range
420
+ score = (similarity + 1) / 2 # Cosine similarity is -1 to 1, convert to 0-1
421
+
422
+ if score > 0.3: # Threshold for relevance
423
+ reasons.append("query-content-match")
424
+
425
+ return score, reasons
426
+ # Fallback to keyword matching if embeddings fail
427
+ query_lower = intent.declared.query.lower()
428
+ content_lower = content.lower()
429
+
430
+ # Count matching keywords
431
+ query_words = set(query_lower.split())
432
+ content_words = set(content_lower.split())
433
+ matching_words = query_words.intersection(content_words)
434
+
435
+ if len(query_words) > 0:
436
+ score = len(matching_words) / len(query_words)
437
+ if score > 0.1: # Threshold for relevance
438
+ reasons.append("keyword-match")
439
+ return score, reasons
440
+ return 0.5, reasons # Neutral if no query words
441
+
442
+ def _compute_use_case_alignment(self, result: SearchResult, intent: UniversalIntent) -> tuple[float, list[str]]:
443
+ """Compute alignment based on use case similarity"""
444
+ reasons = []
445
+
446
+ if not intent.inferred.useCases:
447
+ return 0.5, reasons # Neutral score if no use cases
448
+
449
+ if not result.tags:
450
+ return 0.0, reasons # No tags to match against
451
+
452
+ score = 0.0
453
+ tag_text = " ".join(result.tags).lower()
454
+
455
+ for use_case in intent.inferred.useCases:
456
+ use_case_str = use_case.value.replace("_", " ")
457
+
458
+ # Check if use case is mentioned in tags
459
+ if use_case_str in tag_text:
460
+ score += 0.5 # Significant boost for direct match
461
+ reasons.append(f"use-case-{use_case.value}-match")
462
+ else:
463
+ # Use embedding similarity as fallback
464
+ use_case_embedding = self.embedding_cache.encode_text(use_case_str)
465
+ tag_embedding = self.embedding_cache.encode_text(tag_text)
466
+
467
+ if use_case_embedding is not None and tag_embedding is not None:
468
+ similarity = self.embedding_cache.cosine_similarity(use_case_embedding, tag_embedding)
469
+ # Normalize to 0-1 range and add to score
470
+ similarity_score = (similarity + 1) / 2
471
+ score += similarity_score * 0.3 # Smaller weight for semantic match
472
+
473
+ # Normalize score to 0-1 range
474
+ if intent.inferred.useCases:
475
+ score = min(1.0, score / len(intent.inferred.useCases))
476
+
477
+ return score, reasons
478
+
479
+ def _compute_ethical_alignment(self, result: SearchResult, intent: UniversalIntent) -> tuple[float, list[str]]:
480
+ """Compute alignment based on ethical signals"""
481
+ reasons = []
482
+
483
+ if not intent.inferred.ethicalSignals:
484
+ return 0.5, reasons # Neutral score if no ethical signals
485
+
486
+ score = 0.0
487
+ ethical_matches = 0
488
+
489
+ for signal in intent.inferred.ethicalSignals:
490
+ if signal.dimension == EthicalDimension.PRIVACY:
491
+ if result.privacyRating and result.privacyRating > 0.7:
492
+ score += 0.5
493
+ ethical_matches += 1
494
+ reasons.append("privacy-aligned")
495
+ elif signal.dimension == EthicalDimension.OPENNESS:
496
+ if signal.preference == "open-source_preferred" and result.opensource:
497
+ score += 0.5
498
+ ethical_matches += 1
499
+ reasons.append("open-source-aligned")
500
+ elif signal.dimension == EthicalDimension.SUSTAINABILITY:
501
+ # Placeholder for sustainability checks
502
+ pass
503
+ elif signal.dimension == EthicalDimension.ETHICS:
504
+ # Placeholder for ethics checks
505
+ pass
506
+
507
+ # Normalize score based on number of ethical signals
508
+ if intent.inferred.ethicalSignals:
509
+ score = min(1.0, score / len(intent.inferred.ethicalSignals))
510
+
511
+ return score, reasons
512
+
513
+ def _compute_skill_alignment(self, result: SearchResult, intent: UniversalIntent) -> tuple[float, list[str]]:
514
+ """Compute alignment based on skill level"""
515
+ reasons = []
516
+
517
+ declared_skill = intent.declared.skillLevel
518
+ result_complexity = result.complexity
519
+
520
+ if not result_complexity:
521
+ return 0.5, reasons # Neutral if no complexity info
522
+
523
+ # Map result complexity to skill levels
524
+ complexity_to_skill = {
525
+ "beginner": SkillLevel.BEGINNER,
526
+ "intermediate": SkillLevel.INTERMEDIATE,
527
+ "advanced": SkillLevel.ADVANCED,
528
+ "expert": SkillLevel.EXPERT,
529
+ }
530
+
531
+ if result_complexity in complexity_to_skill:
532
+ result_skill = complexity_to_skill[result_complexity]
533
+
534
+ if declared_skill == result_skill:
535
+ score = 1.0
536
+ reasons.append(f"skill-level-match-{result_complexity}")
537
+ elif (
538
+ (
539
+ declared_skill == SkillLevel.BEGINNER
540
+ and result_skill in [SkillLevel.BEGINNER, SkillLevel.INTERMEDIATE]
541
+ )
542
+ or (
543
+ declared_skill == SkillLevel.INTERMEDIATE
544
+ and result_skill
545
+ in [
546
+ SkillLevel.BEGINNER,
547
+ SkillLevel.INTERMEDIATE,
548
+ SkillLevel.ADVANCED,
549
+ ]
550
+ )
551
+ or (
552
+ declared_skill == SkillLevel.ADVANCED
553
+ and result_skill in [SkillLevel.INTERMEDIATE, SkillLevel.ADVANCED, SkillLevel.EXPERT]
554
+ )
555
+ ):
556
+ # Allow some flexibility in skill matching
557
+ score = 0.8
558
+ reasons.append(f"skill-level-compatible-{result_complexity}")
559
+ else:
560
+ score = 0.2
561
+ reasons.append(f"skill-level-mismatch-{result_complexity}")
562
+ else:
563
+ score = 0.5 # Neutral if complexity not recognized
564
+
565
+ return score, reasons
566
+
567
+ def _compute_temporal_alignment(self, result: SearchResult, intent: UniversalIntent) -> tuple[float, list[str]]:
568
+ """Compute alignment based on temporal intent"""
569
+ reasons = []
570
+
571
+ temporal_intent = intent.inferred.temporalIntent
572
+ if not temporal_intent:
573
+ return 0.5, reasons # Neutral if no temporal intent
574
+
575
+ score = 0.5 # Base score
576
+
577
+ # Check recency alignment
578
+ if temporal_intent.recency == Recency.RECENT and result.recency:
579
+ # If user wants recent content, check if result is recent
580
+ from datetime import datetime
581
+
582
+ try:
583
+ # Assume result.recency is in ISO format or similar
584
+ if result.recency.endswith("Z"):
585
+ result_date = datetime.fromisoformat(result.recency.replace("Z", "+00:00"))
586
+ elif "+" in result.recency or result.recency.count("-") > 2: # Has timezone info
587
+ result_date = datetime.fromisoformat(result.recency)
588
+ else:
589
+ # Naive datetime, treat as UTC
590
+ result_date = datetime.fromisoformat(result.recency).replace(tzinfo=UTC)
591
+
592
+ # Make sure both datetimes have timezone info
593
+ now = datetime.now(UTC)
594
+ days_old = (now - result_date).days
595
+
596
+ if days_old <= 30: # Recent if within 30 days
597
+ score += 0.2
598
+ reasons.append("recent-content")
599
+ elif days_old <= 180: # Somewhat recent
600
+ score += 0.1
601
+ except ValueError:
602
+ # If date parsing fails, skip this check
603
+ pass
604
+
605
+ # Check horizon alignment (today, week, month, etc.)
606
+ if temporal_intent.horizon == TemporalHorizon.TODAY and result.recency:
607
+ # If user wants today's content, check if result is very recent
608
+ from datetime import datetime
609
+
610
+ try:
611
+ # Same date parsing logic as above
612
+ if result.recency.endswith("Z"):
613
+ result_date = datetime.fromisoformat(result.recency.replace("Z", "+00:00"))
614
+ elif "+" in result.recency or result.recency.count("-") > 2: # Has timezone info
615
+ result_date = datetime.fromisoformat(result.recency)
616
+ else:
617
+ # Naive datetime, treat as UTC
618
+ result_date = datetime.fromisoformat(result.recency).replace(tzinfo=UTC)
619
+
620
+ # Make sure both datetimes have timezone info
621
+ now = datetime.now(UTC)
622
+ days_old = (now - result_date).days
623
+
624
+ if days_old <= 1: # Within 1 day
625
+ score += 0.2
626
+ reasons.append("today-relevant")
627
+ except ValueError:
628
+ # If date parsing fails, skip this check
629
+ pass
630
+
631
+ # Clamp score between 0 and 1
632
+ score = max(0.0, min(1.0, score))
633
+
634
+ return score, reasons
635
+
636
+
637
+ class IntentRanker:
638
+ """Main class that orchestrates constraint satisfaction and ranking"""
639
+
640
+ def __init__(self):
641
+ self.constraint_satisfaction_engine = ConstraintSatisfactionEngine()
642
+ self.intent_alignment_engine = IntentAlignmentEngine()
643
+
644
+ def rank_results(self, request: RankingRequest) -> RankingResponse:
645
+ """
646
+ Main function to rank results based on intent alignment
647
+ Implements the complete ranking algorithm
648
+ """
649
+ # Step 1: Apply hard filters (constraint satisfaction)
650
+ filtered_candidates = []
651
+ if request.intent.declared and request.intent.declared.constraints:
652
+ for candidate in request.candidates:
653
+ if self.constraint_satisfaction_engine.satisfies_constraints(
654
+ candidate, request.intent.declared.constraints
655
+ ):
656
+ filtered_candidates.append(candidate)
657
+ else:
658
+ filtered_candidates = request.candidates
659
+
660
+ # Step 2: Batch pre-encode contents for all candidates to improve performance
661
+ self._pre_encode_candidates(filtered_candidates, request.intent)
662
+
663
+ # Step 3: Compute intent alignment for each candidate
664
+ ranked_results = []
665
+ for candidate in filtered_candidates:
666
+ alignment_score, match_reasons = self.intent_alignment_engine.compute_intent_alignment(
667
+ candidate, request.intent
668
+ )
669
+
670
+ ranked_result = RankedResult(
671
+ result=candidate,
672
+ alignmentScore=alignment_score,
673
+ matchReasons=match_reasons,
674
+ )
675
+ ranked_results.append(ranked_result)
676
+
677
+ # Step 4: Sort by alignment score (descending)
678
+ ranked_results.sort(key=lambda x: x.alignmentScore, reverse=True)
679
+
680
+ return RankingResponse(rankedResults=ranked_results)
681
+
682
+ def _pre_encode_candidates(self, candidates: list[SearchResult], intent: UniversalIntent):
683
+ """Pre-encode all candidate contents in a single batch for performance"""
684
+ if not candidates:
685
+ return
686
+
687
+ texts_to_encode = []
688
+
689
+ # 1. Query-content texts
690
+ for c in candidates:
691
+ content = f"{c.title} {c.description}".strip()
692
+ if content:
693
+ texts_to_encode.append(content)
694
+
695
+ # 2. Use case tags text
696
+ for c in candidates:
697
+ if c.tags:
698
+ texts_to_encode.append(" ".join(c.tags).lower())
699
+
700
+ # 3. Intent query and use cases
701
+ if intent.declared.query:
702
+ texts_to_encode.append(intent.declared.query)
703
+
704
+ if intent.inferred.useCases:
705
+ for uc in intent.inferred.useCases:
706
+ texts_to_encode.append(uc.value.replace("_", " "))
707
+
708
+ # Perform batch encoding (this will populate the EmbeddingService cache)
709
+ if texts_to_encode:
710
+ self.intent_alignment_engine.embedding_cache.encode_batch(texts_to_encode)
711
+
712
+
713
+ # Global instance for caching
714
+ _intent_ranker_instance = None
715
+ _ranker_lock = threading.Lock()
716
+
717
+
718
+ def get_intent_ranker() -> IntentRanker:
719
+ """
720
+ Get thread-safe singleton instance of IntentRanker with cached model.
721
+
722
+ Uses double-checked locking pattern for thread safety.
723
+ """
724
+ global _intent_ranker_instance
725
+ if _intent_ranker_instance is None:
726
+ with _ranker_lock:
727
+ if _intent_ranker_instance is None:
728
+ _intent_ranker_instance = IntentRanker()
729
+ return _intent_ranker_instance
730
+
731
+
732
+ def rank_results(request: RankingRequest) -> RankingResponse:
733
+ """
734
+ Main entry point for ranking results based on intent
735
+ """
736
+ ranker = get_intent_ranker()
737
+ return ranker.rank_results(request)
738
+
739
+
740
+ # =============================================================================
741
+ # Product Ranking Functions
742
+ # =============================================================================
743
+
744
+
745
+ def rank_products_by_intent(products: list, intent: UniversalIntent) -> list:
746
+ """
747
+ Rank products based on user intent.
748
+
749
+ Considers:
750
+ - Goal alignment (purchase, comparison, research)
751
+ - Constraint satisfaction (price, brand, features)
752
+ - Use case relevance (programming, gaming, etc.)
753
+ - Product quality signals (ratings, reviews, availability)
754
+
755
+ Args:
756
+ products: List of ProductURL objects
757
+ intent: UniversalIntent with declared and inferred intent
758
+
759
+ Returns:
760
+ List of ProductURL objects sorted by ranked_score
761
+ """
762
+ from app.core.schema import IntentGoal
763
+
764
+ ranked = []
765
+
766
+ for product in products:
767
+ score = 0.5 # Base score
768
+
769
+ # 1. Goal alignment
770
+ if intent.declared.goal == IntentGoal.PURCHASE and product.price:
771
+ score += 0.2 # Boost products with prices
772
+
773
+ # 2. Constraint satisfaction
774
+ for constraint in intent.declared.constraints:
775
+ # Price constraints
776
+ if constraint.dimension == "price":
777
+ score += apply_price_constraint(product, constraint)
778
+ # Brand constraints
779
+ elif constraint.dimension == "brand":
780
+ score += apply_brand_constraint(product, constraint)
781
+
782
+ # 3. Use case relevance
783
+ for use_case in intent.inferred.useCases:
784
+ score += match_use_case(product, use_case)
785
+
786
+ # 4. Product quality score
787
+ score += calculate_product_quality_score(product)
788
+
789
+ # Clamp score between 0 and 1
790
+ product.ranked_score = max(0.0, min(score, 1.0))
791
+ ranked.append(product)
792
+
793
+ # Sort by ranked score (descending)
794
+ ranked.sort(key=lambda x: x.ranked_score, reverse=True)
795
+ return ranked
796
+
797
+
798
+ def apply_price_constraint(product, constraint: Constraint) -> float:
799
+ """
800
+ Apply price constraint to product score.
801
+
802
+ Constraints:
803
+ - "price <= 1000" → Filter/rank by max price
804
+ - "price >= 500" → Filter by min price (quality signal)
805
+ - "500 <= price <= 1000" → Range constraint
806
+
807
+ Args:
808
+ product: ProductURL object
809
+ constraint: Constraint object with price dimension
810
+
811
+ Returns:
812
+ Score adjustment (-1.0 to 0.5)
813
+ """
814
+ if not product.price:
815
+ return 0.0 # Can't evaluate without price
816
+
817
+ try:
818
+ constraint_value = parse_constraint_value(constraint.value)
819
+
820
+ if constraint.type == ConstraintType.RANGE:
821
+ # Handle range constraints (e.g., "500-1000", "<=1000", ">=500")
822
+ if "<=" in constraint.value or "max" in constraint.value.lower():
823
+ if product.price <= constraint_value:
824
+ return 0.3 # Satisfies max price constraint
825
+ # Penalize based on how much over budget
826
+ over_by = (product.price - constraint_value) / constraint_value
827
+ return max(-0.5, -0.3 - (over_by * 0.2))
828
+
829
+ if ">=" in constraint.value or "min" in constraint.value.lower():
830
+ if product.price >= constraint_value:
831
+ return 0.2 # Meets minimum (quality signal)
832
+ return -0.1 # Slight penalty for below minimum
833
+
834
+ # Handle "X-Y" range format
835
+ if "-" in constraint.value:
836
+ parts = constraint.value.split("-")
837
+ if len(parts) == 2:
838
+ try:
839
+ min_price = float(parts[0])
840
+ max_price = float(parts[1])
841
+ if min_price <= product.price <= max_price:
842
+ return 0.4 # Perfect match
843
+ if product.price < min_price:
844
+ return -0.2 # Too cheap (quality concern)
845
+ return -0.3 # Over budget
846
+ except ValueError:
847
+ pass
848
+
849
+ elif constraint.type == ConstraintType.COMPARISON:
850
+ # Handle comparison operators
851
+ if "<=" in constraint.value or "<" in constraint.value:
852
+ if product.price <= constraint_value:
853
+ return 0.3
854
+ return -0.4
855
+ if ">=" in constraint.value or ">" in constraint.value:
856
+ if product.price >= constraint_value:
857
+ return 0.2
858
+ return -0.1
859
+
860
+ except (ValueError, AttributeError):
861
+ pass
862
+
863
+ return 0.0
864
+
865
+
866
+ def apply_brand_constraint(product, constraint: Constraint) -> float:
867
+ """
868
+ Apply brand preference/avoidance constraint.
869
+
870
+ Args:
871
+ product: ProductURL object
872
+ constraint: Constraint object with brand dimension
873
+
874
+ Returns:
875
+ Score adjustment (-1.0 to 0.4)
876
+ """
877
+ product_brand = product.brand or ""
878
+ constraint_value = constraint.value.lower()
879
+
880
+ if constraint.type == ConstraintType.INCLUSION:
881
+ # User wants this brand
882
+ if constraint_value in product_brand.lower():
883
+ return 0.4 # Strong boost for preferred brand
884
+ return -0.2 # Slight penalty for non-preferred
885
+
886
+ if constraint.type == ConstraintType.EXCLUSION:
887
+ # User wants to avoid this brand
888
+ if constraint_value in product_brand.lower():
889
+ return -1.0 # Hard filter for excluded brand
890
+ return 0.1 # Small boost for non-excluded
891
+
892
+ return 0.0
893
+
894
+
895
+ def match_use_case(product, use_case: UseCase) -> float:
896
+ """
897
+ Match product to use case (programming, gaming, business, etc.).
898
+
899
+ Args:
900
+ product: ProductURL object
901
+ use_case: UseCase enum value
902
+
903
+ Returns:
904
+ Score adjustment (0.0 to 0.3)
905
+ """
906
+ # Keyword mapping for use cases
907
+ use_case_keywords = {
908
+ UseCase.DEBUGGING: ["programming", "coding", "development", "developer", "laptop", "keyboard"],
909
+ UseCase.GAMING: ["gaming", "gpu", "rtx", "gtx", "high refresh", "144hz", "240hz", "nvidia", "amd"],
910
+ UseCase.BUSINESS: ["business", "professional", "enterprise", "office", "productivity"],
911
+ UseCase.CONTENT_CREATION: ["video editing", "photo", "creative", "design", "rendering", "4k"],
912
+ UseCase.STUDENT: ["student", "school", "college", "university", "budget", "affordable"],
913
+ UseCase.CASUAL: ["casual", "everyday", "basic", "simple"],
914
+ }
915
+
916
+ keywords = use_case_keywords.get(use_case, [])
917
+
918
+ # Check product name, description, and brand
919
+ product_text = f"{product.product_name or ''} {product.description or ''} {product.brand or ''}".lower()
920
+
921
+ if not keywords or not product_text:
922
+ return 0.0
923
+
924
+ matches = sum(1 for kw in keywords if kw in product_text)
925
+ match_ratio = matches / len(keywords)
926
+
927
+ # Scale score by match ratio (max 0.3)
928
+ return match_ratio * 0.3
929
+
930
+
931
+ def calculate_product_quality_score(product) -> float:
932
+ """
933
+ Calculate product quality score based on signals.
934
+
935
+ Factors:
936
+ - Rating value (30% weight)
937
+ - Review count (20% weight)
938
+ - Availability (20% weight)
939
+ - Brand authority (15% weight)
940
+ - Price completeness (15% weight)
941
+
942
+ Args:
943
+ product: ProductURL object
944
+
945
+ Returns:
946
+ Quality score adjustment (0.0 to 0.3)
947
+ """
948
+ score = 0.0
949
+
950
+ # 1. Rating value (30% weight → max 0.09)
951
+ if product.rating_value:
952
+ rating_score = (product.rating_value / 5.0) * 0.09
953
+ score += rating_score
954
+
955
+ # 2. Review count (20% weight → max 0.06)
956
+ if product.review_count:
957
+ if product.review_count >= 1000:
958
+ score += 0.06
959
+ elif product.review_count >= 500:
960
+ score += 0.05
961
+ elif product.review_count >= 100:
962
+ score += 0.04
963
+ elif product.review_count >= 50:
964
+ score += 0.03
965
+ elif product.review_count >= 10:
966
+ score += 0.02
967
+
968
+ # 3. Availability (20% weight → max 0.06)
969
+ if product.availability:
970
+ avail_lower = product.availability.lower()
971
+ if "instock" in avail_lower or "in stock" in avail_lower:
972
+ score += 0.06
973
+ elif "available" in avail_lower:
974
+ score += 0.04
975
+ elif "out of stock" in avail_lower:
976
+ score -= 0.1 # Penalty for out of stock
977
+
978
+ # 4. Brand authority (15% weight → max 0.045)
979
+ authority_brands = {
980
+ "sony": 0.045,
981
+ "apple": 0.045,
982
+ "samsung": 0.04,
983
+ "lg": 0.035,
984
+ "bose": 0.04,
985
+ "dell": 0.035,
986
+ "hp": 0.03,
987
+ "lenovo": 0.03,
988
+ "asus": 0.03,
989
+ "acer": 0.025,
990
+ "microsoft": 0.04,
991
+ "google": 0.04,
992
+ }
993
+ if product.brand:
994
+ brand_lower = product.brand.lower()
995
+ for auth_brand, auth_score in authority_brands.items():
996
+ if auth_brand in brand_lower:
997
+ score += auth_score
998
+ break
999
+
1000
+ # 5. Price completeness (15% weight → max 0.045)
1001
+ if product.price and product.currency:
1002
+ score += 0.045
1003
+ elif product.price:
1004
+ score += 0.03
1005
+
1006
+ return min(score, 0.3) # Cap at 0.3
1007
+
1008
+
1009
+ def parse_constraint_value(value: str) -> float:
1010
+ """
1011
+ Parse constraint value to numeric value.
1012
+
1013
+ Examples:
1014
+ - "1000" → 1000.0
1015
+ - "$1000" → 1000.0
1016
+ - "under 1000" → 1000.0
1017
+ - "500-1000" → Returns first value (500.0)
1018
+
1019
+ Args:
1020
+ value: Constraint value string
1021
+
1022
+ Returns:
1023
+ Parsed float value
1024
+ """
1025
+ import re
1026
+
1027
+ # Remove currency symbols and common words
1028
+ cleaned = re.sub(r"[$€£₹]", "", value)
1029
+ cleaned = re.sub(r"\b(under|over|below|above|max|min|upto|up to)\b", "", cleaned, flags=re.IGNORECASE)
1030
+
1031
+ # Extract numbers
1032
+ numbers = re.findall(r"[\d,]+\.?\d*", cleaned)
1033
+ if numbers:
1034
+ try:
1035
+ return float(numbers[0].replace(",", ""))
1036
+ except ValueError:
1037
+ pass
1038
+
1039
+ # Fallback: try to parse entire string
1040
+ try:
1041
+ return float(cleaned.strip())
1042
+ except ValueError:
1043
+ return 0.0
services/query_layer/app/ranking/url_ranker.py ADDED
@@ -0,0 +1,888 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Intent Engine - URL Ranking Module
3
+
4
+ This module implements an efficient URL ranking system for a privacy-focused
5
+ search engine. It processes URLs in parallel, scores them based on relevance,
6
+ privacy compliance, and ethical alignment.
7
+ """
8
+
9
+ import asyncio
10
+ import logging
11
+ import re
12
+ import time
13
+ from concurrent.futures import ProcessPoolExecutor
14
+ from dataclasses import dataclass, field
15
+ from typing import Any
16
+ from urllib.parse import urlparse
17
+
18
+ import numpy as np
19
+
20
+ from app.core.schema import (
21
+ Constraint,
22
+ ConstraintType,
23
+ EthicalDimension,
24
+ UniversalIntent,
25
+ )
26
+ from app.ranking.ranker import EmbeddingCache
27
+
28
+ # Configure logging
29
+ logging.basicConfig(level=logging.INFO)
30
+ logger = logging.getLogger(__name__)
31
+
32
+
33
+ @dataclass
34
+ class URLResult:
35
+ """Represents a URL with its metadata and scores"""
36
+
37
+ url: str
38
+ title: str | None = None
39
+ description: str | None = None
40
+ domain: str | None = None
41
+ favicon: str | None = None
42
+
43
+ # Privacy-focused attributes
44
+ privacy_score: float = 0.5 # 0-1: How privacy-friendly
45
+ tracker_count: int = 0 # Number of known trackers
46
+ cookie_policy: str | None = None # "minimal", "strict", "lenient"
47
+ data_retention_days: int | None = None
48
+ encryption_enabled: bool = True # HTTPS support
49
+
50
+ # Content attributes
51
+ content_type: str | None = None # "article", "tool", "forum", "docs", etc.
52
+ language: str | None = None
53
+ recency: str | None = None # ISO date string
54
+
55
+ # Quality attributes
56
+ quality_score: float = 0.5
57
+ authority_score: float = 0.5 # Domain authority
58
+ engagement_score: float = 0.5
59
+
60
+ # Ethical attributes
61
+ is_open_source: bool = False
62
+ is_non_profit: bool = False
63
+ advertising_policy: str | None = None # "no_ads", "minimal_ads", "ad_supported"
64
+ ethical_tags: list[str] = field(default_factory=list)
65
+
66
+ # Computed scores
67
+ relevance_score: float = 0.0
68
+ final_score: float = 0.0
69
+
70
+
71
+ @dataclass
72
+ class URLRankingRequest:
73
+ """Request for ranking URLs"""
74
+
75
+ query: str # The search query
76
+ urls: list[str] # List of URLs to rank
77
+ titles: list[str] | None = None # List of result titles (optional)
78
+ contents: list[str] | None = None # List of result snippets (optional)
79
+ intent: UniversalIntent | None = None # Optional structured intent
80
+ options: dict[str, Any] | None = None # Ranking options
81
+
82
+
83
+ @dataclass
84
+ class URLRankingResponse:
85
+ """Response with ranked URLs"""
86
+
87
+ query: str
88
+ ranked_urls: list[URLResult]
89
+ processing_time_ms: float
90
+ total_urls: int
91
+ filtered_count: int = 0
92
+
93
+
94
+ @dataclass
95
+ class URLAnalysisResult:
96
+ """Result of analyzing a single URL"""
97
+
98
+ url: str
99
+ domain: str
100
+ title: str
101
+ description: str
102
+ privacy_score: float
103
+ content_type: str
104
+ quality_indicators: dict[str, Any]
105
+ error: str | None = None
106
+
107
+
108
+ class PrivacyDatabase:
109
+ """Database of known privacy characteristics for domains"""
110
+
111
+ # Known privacy-friendly domains (open source, privacy-focused, non-profit)
112
+ PRIVACY_FRIENDLY_DOMAINS = {
113
+ # Privacy-focused email/services
114
+ "protonmail.com": {
115
+ "privacy_score": 0.95,
116
+ "tracker_count": 0,
117
+ "encryption": True,
118
+ "type": "service",
119
+ "open_source": True,
120
+ },
121
+ "proton.me": {
122
+ "privacy_score": 0.95,
123
+ "tracker_count": 0,
124
+ "encryption": True,
125
+ "type": "service",
126
+ "open_source": True,
127
+ },
128
+ "tutanota.com": {
129
+ "privacy_score": 0.95,
130
+ "tracker_count": 0,
131
+ "encryption": True,
132
+ "type": "service",
133
+ "open_source": True,
134
+ },
135
+ "tuta.io": {
136
+ "privacy_score": 0.95,
137
+ "tracker_count": 0,
138
+ "encryption": True,
139
+ "type": "service",
140
+ "open_source": True,
141
+ },
142
+ # Privacy-focused search
143
+ "duckduckgo.com": {
144
+ "privacy_score": 0.9,
145
+ "tracker_count": 0,
146
+ "encryption": True,
147
+ "type": "search",
148
+ "open_source": False,
149
+ },
150
+ "startpage.com": {
151
+ "privacy_score": 0.85,
152
+ "tracker_count": 1,
153
+ "encryption": True,
154
+ "type": "search",
155
+ "open_source": False,
156
+ },
157
+ "searx.org": {
158
+ "privacy_score": 0.95,
159
+ "tracker_count": 0,
160
+ "encryption": True,
161
+ "type": "search",
162
+ "open_source": True,
163
+ },
164
+ "searxng.org": {
165
+ "privacy_score": 0.95,
166
+ "tracker_count": 0,
167
+ "encryption": True,
168
+ "type": "search",
169
+ "open_source": True,
170
+ },
171
+ # Open source platforms
172
+ "github.com": {
173
+ "privacy_score": 0.8,
174
+ "tracker_count": 1,
175
+ "encryption": True,
176
+ "type": "code",
177
+ "open_source": True,
178
+ },
179
+ "gitlab.com": {
180
+ "privacy_score": 0.85,
181
+ "tracker_count": 0,
182
+ "encryption": True,
183
+ "type": "code",
184
+ "open_source": True,
185
+ },
186
+ "sourceforge.net": {
187
+ "privacy_score": 0.75,
188
+ "tracker_count": 2,
189
+ "encryption": True,
190
+ "type": "code",
191
+ "open_source": True,
192
+ },
193
+ # Privacy-focused browsers
194
+ "brave.com": {
195
+ "privacy_score": 0.9,
196
+ "tracker_count": 0,
197
+ "encryption": True,
198
+ "type": "software",
199
+ "open_source": True,
200
+ },
201
+ "mozilla.org": {
202
+ "privacy_score": 0.85,
203
+ "tracker_count": 1,
204
+ "encryption": True,
205
+ "type": "software",
206
+ "open_source": True,
207
+ },
208
+ # Wikipedia and educational
209
+ "wikipedia.org": {
210
+ "privacy_score": 0.9,
211
+ "tracker_count": 0,
212
+ "encryption": True,
213
+ "type": "encyclopedia",
214
+ "open_source": True,
215
+ "non_profit": True,
216
+ },
217
+ "wikimedia.org": {
218
+ "privacy_score": 0.9,
219
+ "tracker_count": 0,
220
+ "encryption": True,
221
+ "type": "encyclopedia",
222
+ "open_source": True,
223
+ "non_profit": True,
224
+ },
225
+ # Privacy-focused VPNs and tools
226
+ "mullvad.net": {
227
+ "privacy_score": 0.95,
228
+ "tracker_count": 0,
229
+ "encryption": True,
230
+ "type": "vpn",
231
+ "open_source": True,
232
+ },
233
+ "nordvpn.com": {
234
+ "privacy_score": 0.8,
235
+ "tracker_count": 1,
236
+ "encryption": True,
237
+ "type": "vpn",
238
+ "open_source": False,
239
+ },
240
+ # FOSS alternatives
241
+ "fsf.org": {
242
+ "privacy_score": 0.9,
243
+ "tracker_count": 0,
244
+ "encryption": True,
245
+ "type": "organization",
246
+ "open_source": True,
247
+ "non_profit": True,
248
+ },
249
+ "opensource.org": {
250
+ "privacy_score": 0.9,
251
+ "tracker_count": 0,
252
+ "encryption": True,
253
+ "type": "organization",
254
+ "open_source": True,
255
+ "non_profit": True,
256
+ },
257
+ }
258
+
259
+ # Known tracker domains
260
+ TRACKER_DOMAINS = {
261
+ "google.com",
262
+ "facebook.com",
263
+ "twitter.com",
264
+ "linkedin.com",
265
+ "doubleclick.net",
266
+ "google-analytics.com",
267
+ "googletagmanager.com",
268
+ "facebook.net",
269
+ "hotjar.com",
270
+ "segment.io",
271
+ "mixpanel.com",
272
+ "criteo.com",
273
+ "taboola.com",
274
+ "outbrain.com",
275
+ "amazon-adsystem.com",
276
+ }
277
+
278
+ # Big tech domains (often excluded in privacy-focused searches)
279
+ BIG_TECH_DOMAINS = {
280
+ "google.com",
281
+ "googleusercontent.com",
282
+ "googledrive.com",
283
+ "facebook.com",
284
+ "instagram.com",
285
+ "whatsapp.com",
286
+ "messenger.com",
287
+ "microsoft.com",
288
+ "outlook.com",
289
+ "live.com",
290
+ "onedrive.com",
291
+ "amazon.com",
292
+ "aws.amazon.com",
293
+ "apple.com",
294
+ "icloud.com",
295
+ "twitter.com",
296
+ "x.com",
297
+ "tiktok.com",
298
+ "bytedance.com",
299
+ }
300
+
301
+ # Content type patterns
302
+ CONTENT_TYPE_PATTERNS = {
303
+ "article": ["blog", "news", "article", "post", "story"],
304
+ "documentation": ["docs", "documentation", "wiki", "manual", "guide"],
305
+ "tool": ["tool", "generator", "converter", "calculator", "checker"],
306
+ "forum": ["forum", "discussion", "community", "board"],
307
+ "code": ["github", "gitlab", "sourceforge", "code", "repository"],
308
+ "download": ["download", "release", "file"],
309
+ }
310
+
311
+ def get_domain_info(self, url: str) -> dict[str, Any]:
312
+ """Get privacy and content info for a domain"""
313
+ parsed = urlparse(url)
314
+ domain = parsed.netloc.lower()
315
+
316
+ # Remove www. prefix
317
+ if domain.startswith("www."):
318
+ domain = domain[4:]
319
+
320
+ # Check exact match first
321
+ if domain in self.PRIVACY_FRIENDLY_DOMAINS:
322
+ return self.PRIVACY_FRIENDLY_DOMAINS[domain].copy()
323
+
324
+ # Check for partial matches (subdomains)
325
+ for known_domain, info in self.PRIVACY_FRIENDLY_DOMAINS.items():
326
+ if domain.endswith("." + known_domain):
327
+ result = info.copy()
328
+ result["subdomain"] = True
329
+ return result
330
+
331
+ # Check if it's a tracker domain
332
+ is_tracker = any(domain.endswith("." + td) or domain == td for td in self.TRACKER_DOMAINS)
333
+
334
+ # Check if it's big tech
335
+ is_big_tech = any(domain.endswith("." + bt) or domain == bt for bt in self.BIG_TECH_DOMAINS)
336
+
337
+ # Default values based on domain analysis
338
+ privacy_score = 0.3 if is_big_tech else 0.5
339
+ tracker_count = 3 if is_big_tech else (1 if is_tracker else 0)
340
+
341
+ return {
342
+ "privacy_score": privacy_score,
343
+ "tracker_count": tracker_count,
344
+ "encryption": True, # Assume HTTPS
345
+ "type": "unknown",
346
+ "open_source": False,
347
+ "is_big_tech": is_big_tech,
348
+ "is_tracker": is_tracker,
349
+ }
350
+
351
+
352
+ class URLAnalyzer:
353
+ """Analyzes individual URLs for privacy and content characteristics"""
354
+
355
+ def __init__(self, embedding_cache: EmbeddingCache | None = None):
356
+ self.privacy_db = PrivacyDatabase()
357
+ self.embedding_cache = embedding_cache or EmbeddingCache()
358
+
359
+ def analyze_url(self, url: str) -> URLAnalysisResult:
360
+ """Analyze a single URL and return its characteristics"""
361
+ try:
362
+ parsed = urlparse(url)
363
+ domain = parsed.netloc.lower()
364
+
365
+ # Remove www. prefix
366
+ if domain.startswith("www."):
367
+ domain = domain[4:]
368
+
369
+ # Get domain info from privacy database
370
+ domain_info = self.privacy_db.get_domain_info(url)
371
+
372
+ # Determine content type from URL path
373
+ path = parsed.path.lower()
374
+ content_type = self._determine_content_type(path, domain)
375
+
376
+ # Extract title from path (fallback)
377
+ title = self._extract_title_from_path(path, domain)
378
+
379
+ # Generate description from URL structure
380
+ description = self._generate_description(url, content_type)
381
+
382
+ return URLAnalysisResult(
383
+ url=url,
384
+ domain=domain,
385
+ title=title,
386
+ description=description,
387
+ privacy_score=domain_info.get("privacy_score", 0.5),
388
+ content_type=content_type,
389
+ quality_indicators={
390
+ "encryption": domain_info.get("encryption", True),
391
+ "tracker_count": domain_info.get("tracker_count", 0),
392
+ "is_open_source": domain_info.get("open_source", False),
393
+ "is_non_profit": domain_info.get("non_profit", False),
394
+ "is_big_tech": domain_info.get("is_big_tech", False),
395
+ },
396
+ )
397
+ except Exception as e:
398
+ logger.error(f"Error analyzing URL {url}: {e}")
399
+ return URLAnalysisResult(
400
+ url=url,
401
+ domain="unknown",
402
+ title=url,
403
+ description="Error analyzing URL",
404
+ privacy_score=0.5,
405
+ content_type="unknown",
406
+ quality_indicators={},
407
+ error=str(e),
408
+ )
409
+
410
+ def _determine_content_type(self, path: str, domain: str) -> str:
411
+ """Determine content type from URL path"""
412
+ combined = f"{domain} {path}"
413
+
414
+ for content_type, patterns in PrivacyDatabase.CONTENT_TYPE_PATTERNS.items():
415
+ if any(p in combined for p in patterns):
416
+ return content_type
417
+
418
+ # Default based on domain
419
+ if "blog" in domain or "news" in domain:
420
+ return "article"
421
+ if "docs" in domain or "wiki" in domain:
422
+ return "documentation"
423
+ if "forum" in domain or "community" in domain:
424
+ return "forum"
425
+
426
+ return "general"
427
+
428
+ def _extract_title_from_path(self, path: str, domain: str) -> str:
429
+ """Extract a readable title from URL path"""
430
+ # Remove leading/trailing slashes and split
431
+ parts = [p for p in path.strip("/").split("/") if p]
432
+
433
+ if not parts:
434
+ return domain
435
+
436
+ # Use last meaningful part
437
+ last_part = parts[-1] if parts else domain
438
+
439
+ # Clean up: replace hyphens/underscores with spaces, capitalize
440
+ title = re.sub(r"[-_]", " ", last_part)
441
+ title = re.sub(r"\b\w\b", "", title) # Remove single chars
442
+ title = title.strip()
443
+
444
+ if not title:
445
+ return domain
446
+
447
+ return title.title()
448
+
449
+ def _generate_description(self, url: str, content_type: str) -> str:
450
+ """Generate a description based on URL and content type"""
451
+ parsed = urlparse(url)
452
+ domain = parsed.netloc.lower()
453
+
454
+ type_descriptions = {
455
+ "article": "Article and blog content",
456
+ "documentation": "Documentation and guides",
457
+ "tool": "Online tool and utilities",
458
+ "forum": "Community discussion forum",
459
+ "code": "Source code repository",
460
+ "download": "Software downloads",
461
+ "general": "Web resource",
462
+ }
463
+
464
+ return f"{type_descriptions.get(content_type, 'Web resource')} from {domain}"
465
+
466
+
467
+ # Global process pool for CPU-bound URL analysis
468
+ _ranking_executor = None
469
+ _executor_lock = asyncio.Lock()
470
+
471
+
472
+ async def get_ranking_executor():
473
+ """Get or create the process pool executor for ranking"""
474
+ global _ranking_executor
475
+ if _ranking_executor is None:
476
+ async with _executor_lock:
477
+ if _ranking_executor is None:
478
+ # Use a small number of workers for CPU-bound tasks
479
+ import os
480
+
481
+ num_workers = min(os.cpu_count() or 4, 8)
482
+ _ranking_executor = ProcessPoolExecutor(max_workers=num_workers)
483
+ return _ranking_executor
484
+
485
+
486
+ def analyze_url_task(url: str) -> URLAnalysisResult:
487
+ """
488
+ Top-level task for URL analysis that can be pickled for multiprocessing.
489
+ """
490
+ analyzer = URLAnalyzer()
491
+ return analyzer.analyze_url(url)
492
+
493
+
494
+ class URLRanker:
495
+ """
496
+ Main URL ranking engine for privacy-focused search.
497
+
498
+ Processes URLs efficiently using parallel processing and scores them based on:
499
+ - Query relevance (semantic similarity)
500
+ - Privacy compliance (minimal tracking, encryption)
501
+ - Ethical alignment (open source, non-profit)
502
+ - Content quality (authority, recency)
503
+ """
504
+
505
+ # Default scoring weights
506
+ DEFAULT_WEIGHTS = {
507
+ "relevance": 0.35, # Query-content similarity
508
+ "privacy": 0.25, # Privacy-friendly
509
+ "quality": 0.20, # Content quality
510
+ "ethics": 0.20, # Ethical alignment
511
+ }
512
+
513
+ def __init__(self):
514
+ self.embedding_cache = EmbeddingCache()
515
+ self.url_analyzer = URLAnalyzer(self.embedding_cache)
516
+
517
+ async def rank_urls(self, request: URLRankingRequest) -> URLRankingResponse:
518
+ """
519
+ Rank URLs based on query and optional intent.
520
+
521
+ Processes URLs in parallel for efficiency.
522
+ """
523
+ start_time = time.time()
524
+
525
+ urls = request.urls
526
+ query = request.query
527
+ intent = request.intent
528
+
529
+ # Get ranking options
530
+ options = request.options or {}
531
+ weights = options.get("weights", self.DEFAULT_WEIGHTS)
532
+ min_privacy_score = options.get("min_privacy_score", 0.0)
533
+ exclude_big_tech = options.get("exclude_big_tech", False)
534
+
535
+ # Parse intent if provided
536
+ privacy_preference = None
537
+ ethical_signals = []
538
+ constraints = []
539
+
540
+ if intent:
541
+ if intent.inferred and intent.inferred.ethicalSignals:
542
+ ethical_signals = intent.inferred.ethicalSignals
543
+ if intent.declared:
544
+ constraints = intent.declared.constraints or []
545
+ if intent.declared.negativePreferences:
546
+ privacy_preference = intent.declared.negativePreferences
547
+
548
+ # Step 1: Analyze all URLs in parallel
549
+ analyzed_urls = await self._analyze_urls_parallel(urls)
550
+
551
+ # Step 1.5: Merge provided titles and contents if available
552
+ if request.titles or request.contents:
553
+ for i, result in enumerate(analyzed_urls):
554
+ if request.titles and i < len(request.titles) and request.titles[i]:
555
+ result.title = request.titles[i]
556
+ if request.contents and i < len(request.contents) and request.contents[i]:
557
+ result.description = request.contents[i]
558
+
559
+ # Step 2: Filter URLs based on constraints
560
+ filtered_urls = self._apply_filters(
561
+ analyzed_urls,
562
+ constraints,
563
+ min_privacy_score,
564
+ exclude_big_tech,
565
+ privacy_preference,
566
+ )
567
+
568
+ # Step 3: Score remaining URLs
569
+ scored_urls = await self._score_urls(filtered_urls, query, weights, ethical_signals)
570
+
571
+ # Step 4: Sort by final score (handle None values)
572
+ scored_urls.sort(
573
+ key=lambda x: x.final_score if x.final_score is not None else 0.0,
574
+ reverse=True,
575
+ )
576
+
577
+ processing_time = (time.time() - start_time) * 1000 # Convert to ms
578
+
579
+ return URLRankingResponse(
580
+ query=query,
581
+ ranked_urls=scored_urls,
582
+ processing_time_ms=processing_time,
583
+ total_urls=len(urls),
584
+ filtered_count=len(urls) - len(scored_urls),
585
+ )
586
+
587
+ async def _analyze_urls_parallel(self, urls: list[str]) -> list[URLResult]:
588
+ """Analyze URLs in parallel using asyncio for concurrency with minimal overhead"""
589
+ # Optimization: Use asyncio.to_thread for each URL to avoid blocking the event loop
590
+ # and to keep execution concurrent without the heavy overhead of ProcessPoolExecutor.
591
+ # Pickling/unpickling data for ProcessPool is expensive for these light tasks.
592
+ tasks = [asyncio.to_thread(analyze_url_task, url) for url in urls]
593
+ analysis_results = await asyncio.gather(*tasks)
594
+
595
+ results = []
596
+ for analysis in analysis_results:
597
+ results.append(
598
+ URLResult(
599
+ url=analysis.url,
600
+ title=analysis.title,
601
+ description=analysis.description,
602
+ domain=analysis.domain,
603
+ privacy_score=analysis.privacy_score,
604
+ tracker_count=analysis.quality_indicators.get("tracker_count", 0),
605
+ encryption_enabled=analysis.quality_indicators.get("encryption", True),
606
+ content_type=analysis.content_type,
607
+ is_open_source=analysis.quality_indicators.get("is_open_source", False),
608
+ is_non_profit=analysis.quality_indicators.get("is_non_profit", False),
609
+ quality_score=0.5,
610
+ authority_score=self._calculate_authority(analysis.domain),
611
+ )
612
+ )
613
+
614
+ return results
615
+
616
+ def _apply_filters(
617
+ self,
618
+ urls: list[URLResult],
619
+ constraints: list[Constraint],
620
+ min_privacy_score: float,
621
+ exclude_big_tech: bool,
622
+ negative_preferences: list[str] | None,
623
+ ) -> list[URLResult]:
624
+ """Apply filtering constraints to URLs"""
625
+ filtered = []
626
+
627
+ for url_result in urls:
628
+ # Apply hard constraints
629
+ if not self._satisfies_constraints(url_result, constraints):
630
+ continue
631
+
632
+ # Apply minimum privacy score
633
+ if min_privacy_score is not None and url_result.privacy_score < min_privacy_score:
634
+ continue
635
+
636
+ # Exclude big tech if requested
637
+ if exclude_big_tech:
638
+ domain_info = PrivacyDatabase().get_domain_info(url_result.url)
639
+ if domain_info.get("is_big_tech", False):
640
+ continue
641
+
642
+ # Apply negative preferences (e.g., "no google")
643
+ if negative_preferences and not self._satisfies_negative_preferences(url_result, negative_preferences):
644
+ continue
645
+
646
+ filtered.append(url_result)
647
+
648
+ return filtered
649
+
650
+ def _satisfies_constraints(self, url_result: URLResult, constraints: list[Constraint]) -> bool:
651
+ """Check if URL satisfies hard constraints"""
652
+ for constraint in constraints:
653
+ if not constraint.hardFilter:
654
+ continue
655
+
656
+ dimension = constraint.dimension
657
+ value = constraint.value
658
+
659
+ if dimension in {"domain", "provider"}:
660
+ if constraint.type == ConstraintType.INCLUSION:
661
+ if isinstance(value, list):
662
+ if not any(v.lower() in url_result.domain.lower() for v in value):
663
+ return False
664
+ elif isinstance(value, str) and value.lower() not in url_result.domain.lower():
665
+ return False
666
+ elif constraint.type == ConstraintType.EXCLUSION:
667
+ if isinstance(value, list):
668
+ if any(v.lower() in url_result.domain.lower() for v in value):
669
+ return False
670
+ elif isinstance(value, str) and value.lower() in url_result.domain.lower():
671
+ return False
672
+
673
+ elif dimension == "privacy" and constraint.type == ConstraintType.INCLUSION:
674
+ if isinstance(value, str) and url_result.privacy_score is not None:
675
+ violates = False
676
+ if (
677
+ "high" in value.lower()
678
+ and url_result.privacy_score < 0.7
679
+ or ("medium" in value.lower() and url_result.privacy_score < 0.5)
680
+ ):
681
+ violates = True
682
+ if violates:
683
+ return False
684
+
685
+ return True
686
+
687
+ def _satisfies_negative_preferences(self, url_result: URLResult, preferences: list[str]) -> bool:
688
+ """Check if URL satisfies negative preferences like 'no google'"""
689
+ for pref in preferences:
690
+ pref_lower = pref.lower().replace("no ", "").replace("not ", "")
691
+
692
+ # Check against big tech domains
693
+ privacy_db = PrivacyDatabase()
694
+ for big_tech in privacy_db.BIG_TECH_DOMAINS:
695
+ if big_tech.replace(".com", "").replace(".", " ") in pref_lower:
696
+ if big_tech in url_result.domain or url_result.domain.endswith("." + big_tech):
697
+ return False
698
+
699
+ return True
700
+
701
+ async def _score_urls(
702
+ self,
703
+ urls: list[URLResult],
704
+ query: str,
705
+ weights: dict[str, float],
706
+ ethical_signals: list[Any],
707
+ ) -> list[URLResult]:
708
+ """Score URLs based on multiple factors using batch processing for efficiency"""
709
+ import asyncio
710
+
711
+ # Get query embedding for relevance calculation
712
+ query_embedding = self.embedding_cache.encode_text(query)
713
+
714
+ # Prepare all content texts for batch embedding
715
+ if query_embedding is not None:
716
+ contents = []
717
+ url_indices = []
718
+ for i, url in enumerate(urls):
719
+ content = f"{url.title or ''} {url.description or ''} {url.content_type or ''}"
720
+ if content.strip():
721
+ contents.append(content)
722
+ url_indices.append(i)
723
+
724
+ # Batch encode all contents at once (much faster than individual encoding)
725
+ if contents:
726
+ content_embeddings = await asyncio.to_thread(self.embedding_cache.encode_batch, contents)
727
+
728
+ # Calculate similarities for all URLs
729
+ for idx, url_idx in enumerate(url_indices):
730
+ embedding = content_embeddings[idx]
731
+ if embedding is not None:
732
+ similarity = self.embedding_cache.cosine_similarity(query_embedding, embedding)
733
+ urls[url_idx].relevance_score = (similarity + 1) / 2
734
+ else:
735
+ # Fallback to keyword matching
736
+ urls[url_idx].relevance_score = self._calculate_keyword_relevance(urls[url_idx], query)
737
+
738
+ # Ensure weights is not None
739
+ if weights is None:
740
+ weights = self.DEFAULT_WEIGHTS
741
+
742
+ # Process remaining URLs that weren't batch encoded
743
+ for url in urls:
744
+ if url.relevance_score == 0.0: # Not yet scored
745
+ url.relevance_score = self._calculate_relevance(url, query, query_embedding)
746
+
747
+ # 2. Privacy score (already computed during analysis)
748
+ privacy = url.privacy_score if url.privacy_score is not None else 0.5
749
+
750
+ # 3. Quality score
751
+ quality = self._calculate_quality(url)
752
+
753
+ # 4. Ethical score
754
+ ethics = self._calculate_ethics(url, ethical_signals)
755
+
756
+ # Calculate final weighted score
757
+ url.final_score = (
758
+ url.relevance_score * weights.get("relevance", 0.35)
759
+ + privacy * weights.get("privacy", 0.25)
760
+ + quality * weights.get("quality", 0.20)
761
+ + ethics * weights.get("ethics", 0.20)
762
+ )
763
+
764
+ return urls
765
+
766
+ def _calculate_keyword_relevance(self, url: URLResult, query: str) -> float:
767
+ """Calculate relevance using keyword matching only"""
768
+ content = f"{url.title or ''} {url.description or ''} {url.content_type or ''}"
769
+
770
+ if not content.strip():
771
+ return 0.3
772
+
773
+ query_words = set(query.lower().split())
774
+ content_words = set(content.lower().split())
775
+
776
+ if not query_words:
777
+ return 0.5
778
+
779
+ matches = query_words.intersection(content_words)
780
+ return min(1.0, len(matches) / len(query_words)) * 0.5 + 0.3
781
+
782
+ def _calculate_relevance(self, url: URLResult, query: str, query_embedding: np.ndarray | None) -> float:
783
+ """Calculate relevance score between query and URL"""
784
+ # Combine title and description for content
785
+ content = f"{url.title or ''} {url.description or ''} {url.content_type or ''}"
786
+
787
+ if not content.strip():
788
+ return 0.3
789
+
790
+ # Use embeddings if available
791
+ if query_embedding is not None:
792
+ content_embedding = self.embedding_cache.encode_text(content)
793
+ if content_embedding is not None:
794
+ similarity = self.embedding_cache.cosine_similarity(query_embedding, content_embedding)
795
+ # Normalize from [-1, 1] to [0, 1]
796
+ return (similarity + 1) / 2
797
+
798
+ # Fallback to keyword matching
799
+ return self._calculate_keyword_relevance(url, query)
800
+
801
+ def _calculate_quality(self, url: URLResult) -> float:
802
+ """Calculate content quality score"""
803
+ score = 0.5 # Base score
804
+
805
+ # Boost for encryption
806
+ if url.encryption_enabled:
807
+ score += 0.1
808
+
809
+ # Boost for good privacy score
810
+ if url.privacy_score is not None and url.privacy_score > 0.7:
811
+ score += 0.15
812
+ elif url.privacy_score is not None and url.privacy_score > 0.5:
813
+ score += 0.05
814
+
815
+ # Boost for low tracker count
816
+ if url.tracker_count == 0:
817
+ score += 0.15
818
+ elif url.tracker_count <= 2:
819
+ score += 0.05
820
+
821
+ # Penalize high tracker count
822
+ if url.tracker_count > 5:
823
+ score -= 0.15
824
+
825
+ return max(0.0, min(1.0, score))
826
+
827
+ def _calculate_ethics(self, url: URLResult, ethical_signals: list[Any]) -> float:
828
+ """Calculate ethical alignment score"""
829
+ score = 0.5 # Base score
830
+
831
+ # Check ethical signals from intent
832
+ if ethical_signals:
833
+ for signal in ethical_signals:
834
+ if signal.dimension == EthicalDimension.PRIVACY:
835
+ if url.privacy_score is not None and url.privacy_score > 0.7:
836
+ score += 0.2
837
+ elif signal.dimension == EthicalDimension.OPENNESS and url.is_open_source:
838
+ score += 0.2
839
+
840
+ # Boost for open source
841
+ if url.is_open_source:
842
+ score += 0.15
843
+
844
+ # Boost for non-profit
845
+ if url.is_non_profit:
846
+ score += 0.1
847
+
848
+ # Penalize ad-heavy domains
849
+ if url.advertising_policy == "ad_supported":
850
+ score -= 0.1
851
+
852
+ return max(0.0, min(1.0, score))
853
+
854
+ def _calculate_authority(self, domain: str) -> float:
855
+ """Calculate domain authority score"""
856
+ # Known high-authority domains
857
+ authority_domains = {
858
+ "wikipedia.org": 0.95,
859
+ "github.com": 0.9,
860
+ "mozilla.org": 0.85,
861
+ "stackoverflow.com": 0.85,
862
+ "medium.com": 0.75,
863
+ "dev.to": 0.7,
864
+ }
865
+
866
+ for auth_domain, score in authority_domains.items():
867
+ if domain == auth_domain or domain.endswith("." + auth_domain):
868
+ return score
869
+
870
+ return 0.5 # Default
871
+
872
+
873
+ # Global instance for caching
874
+ _url_ranker_instance = None
875
+
876
+
877
+ def get_url_ranker() -> URLRanker:
878
+ """Get singleton instance of URLRanker"""
879
+ global _url_ranker_instance
880
+ if _url_ranker_instance is None:
881
+ _url_ranker_instance = URLRanker()
882
+ return _url_ranker_instance
883
+
884
+
885
+ async def rank_urls(request: URLRankingRequest) -> URLRankingResponse:
886
+ """Main entry point for URL ranking"""
887
+ ranker = get_url_ranker()
888
+ return await ranker.rank_urls(request)
services/query_layer/requirements.txt ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ fastapi
2
+ uvicorn
3
+ qdrant-client>=1.10.0
4
+ onnxruntime
5
+ transformers
6
+ sentence-transformers
7
+ numpy
8
+ pydantic
9
+ torch --index-url https://download.pytorch.org/whl/cpu
sources.yaml ADDED
@@ -0,0 +1,599 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # IntentForge v2 - Fully Verified Working Sources Configuration
2
+ # 100% Reliable sources with anti-detection measures
3
+
4
+ sources:
5
+ # ========== AI & Machine Learning (100% VERIFIED) ==========
6
+ - name: "ArXiv AI"
7
+ url: "http://arxiv.org/rss/cs.AI"
8
+ category: "ai"
9
+ priority: 10
10
+ - name: "ArXiv ML"
11
+ url: "http://arxiv.org/rss/cs.LG"
12
+ category: "ai"
13
+ priority: 10
14
+ - name: "ArXiv CL"
15
+ url: "http://arxiv.org/rss/cs.CL"
16
+ category: "ai"
17
+ priority: 9
18
+ - name: "ArXiv CV"
19
+ url: "http://arxiv.org/rss/cs.CV"
20
+ category: "ai"
21
+ priority: 9
22
+ - name: "Hugging Face Blog"
23
+ url: "https://huggingface.co/blog/feed.xml"
24
+ category: "ai"
25
+ priority: 9
26
+ - name: "OpenAI Blog"
27
+ url: "https://openai.com/news/rss.xml"
28
+ category: "ai"
29
+ priority: 9
30
+ - name: "Google Research"
31
+ url: "https://research.google/blog/rss/"
32
+ category: "ai"
33
+ priority: 9
34
+ - name: "DeepMind Blog"
35
+ url: "https://deepmind.google/blog/rss.xml"
36
+ category: "ai"
37
+ priority: 9
38
+
39
+ # ========== Technology & Programming (100% VERIFIED) ==========
40
+ - name: "Hacker News"
41
+ url: "https://hnrss.org/frontpage"
42
+ category: "tech"
43
+ priority: 10
44
+ - name: "TechCrunch"
45
+ url: "https://techcrunch.com/feed/"
46
+ category: "tech"
47
+ priority: 8
48
+ - name: "Ars Technica"
49
+ url: "https://feeds.arstechnica.com/arstechnica/index"
50
+ category: "tech"
51
+ priority: 8
52
+ - name: "The Verge"
53
+ url: "https://www.theverge.com/rss/index.xml"
54
+ category: "tech"
55
+ priority: 7
56
+ - name: "GitHub Blog"
57
+ url: "https://github.blog/feed/"
58
+ category: "devtools"
59
+ priority: 9
60
+ - name: "Stack Overflow Blog"
61
+ url: "https://stackoverflow.blog/feed/"
62
+ category: "devtools"
63
+ priority: 8
64
+ - name: "DEV Community"
65
+ url: "https://dev.to/feed"
66
+ category: "devtools"
67
+ priority: 8
68
+ - name: "CSS-Tricks"
69
+ url: "https://css-tricks.com/feed/"
70
+ category: "devtools"
71
+ priority: 7
72
+ - name: "Mozilla Hacks"
73
+ url: "https://hacks.mozilla.org/feed/"
74
+ category: "devtools"
75
+ priority: 8
76
+ - name: "Smashing Magazine"
77
+ url: "https://www.smashingmagazine.com/feed/"
78
+ category: "devtools"
79
+ priority: 7
80
+ - name: "ByteByteGo"
81
+ url: "https://blog.bytebytego.com/feed"
82
+ category: "devtools"
83
+ priority: 8
84
+
85
+ # ========== DevOps & Cloud (100% VERIFIED) ==========
86
+ - name: "Kubernetes Blog"
87
+ url: "https://kubernetes.io/feed.xml"
88
+ category: "devops"
89
+ priority: 9
90
+ - name: "Docker Blog"
91
+ url: "https://www.docker.com/blog/feed/"
92
+ category: "devops"
93
+ priority: 8
94
+ - name: "AWS Blog"
95
+ url: "https://aws.amazon.com/blogs/aws/feed/"
96
+ category: "devops"
97
+ priority: 8
98
+ - name: "HashiCorp Blog"
99
+ url: "https://www.hashicorp.com/blog/feed.xml"
100
+ category: "devops"
101
+ priority: 8
102
+ - name: "Cloudflare Blog"
103
+ url: "https://blog.cloudflare.com/rss/"
104
+ category: "devops"
105
+ priority: 8
106
+
107
+ # ========== Cooking & Recipes (100% VERIFIED) ==========
108
+ - name: "Bon Appetit"
109
+ url: "https://www.bonappetit.com/feed/rss"
110
+ category: "cooking"
111
+ priority: 9
112
+ - name: "Minimalist Baker"
113
+ url: "https://minimalistbaker.com/feed/"
114
+ category: "cooking"
115
+ priority: 8
116
+ - name: "BBC Good Food"
117
+ url: "https://www.bbcgoodfood.com/rss"
118
+ category: "cooking"
119
+ priority: 8
120
+ - name: "The Kitchn"
121
+ url: "https://www.thekitchn.com/main.rss"
122
+ category: "cooking"
123
+ priority: 8
124
+ - name: "Love and Lemons"
125
+ url: "https://www.loveandlemons.com/feed/"
126
+ category: "cooking"
127
+ priority: 7
128
+ - name: "Cookie and Kate"
129
+ url: "https://cookieandkate.com/feed/"
130
+ category: "cooking"
131
+ priority: 7
132
+ - name: "Damn Delicious"
133
+ url: "https://damndelicious.net/feed/"
134
+ category: "cooking"
135
+ priority: 7
136
+ - name: "Budget Bytes"
137
+ url: "https://www.budgetbytes.com/feed/"
138
+ category: "cooking"
139
+ priority: 7
140
+ - name: "Half Baked Harvest"
141
+ url: "https://www.halfbakedharvest.com/feed/"
142
+ category: "cooking"
143
+ priority: 8
144
+
145
+ # ========== Travel (100% VERIFIED) ==========
146
+ - name: "Nomadic Matt"
147
+ url: "https://www.nomadicmatt.com/feed/"
148
+ category: "travel"
149
+ priority: 9
150
+ - name: "Condé Nast Traveler"
151
+ url: "https://www.cntraveler.com/feed/rss"
152
+ category: "travel"
153
+ priority: 8
154
+ - name: "Atlas Obscura"
155
+ url: "https://www.atlasobscura.com/feed"
156
+ category: "travel"
157
+ priority: 7
158
+ - name: "Travel Weekly"
159
+ url: "https://www.travelweekly.com/rss"
160
+ category: "travel"
161
+ priority: 7
162
+ - name: "Skift"
163
+ url: "https://skift.com/feed/"
164
+ category: "travel"
165
+ priority: 7
166
+
167
+ # ========== Fitness & Health (100% VERIFIED) ==========
168
+ - name: "Men's Health"
169
+ url: "https://www.menshealth.com/rss/all.xml/"
170
+ category: "fitness"
171
+ priority: 8
172
+ - name: "Women's Health"
173
+ url: "https://www.womenshealthmag.com/rss/all.xml/"
174
+ category: "fitness"
175
+ priority: 8
176
+ - name: "Runner's World"
177
+ url: "https://www.runnersworld.com/rss/all.xml/"
178
+ category: "fitness"
179
+ priority: 7
180
+ - name: "Self Magazine"
181
+ url: "https://www.self.com/feed/rss"
182
+ category: "fitness"
183
+ priority: 7
184
+ - name: "Well+Good"
185
+ url: "https://www.wellandgood.com/feed/"
186
+ category: "fitness"
187
+ priority: 7
188
+ - name: "Health.com"
189
+ url: "https://www.health.com/feed"
190
+ category: "health"
191
+ priority: 8
192
+ - name: "Everyday Health"
193
+ url: "https://www.everydayhealth.com/rss/all.aspx"
194
+ category: "health"
195
+ priority: 7
196
+
197
+ # ========== Gaming (100% VERIFIED) ==========
198
+ - name: "IGN"
199
+ url: "https://feeds.feedburner.com/ign/all"
200
+ category: "gaming"
201
+ priority: 9
202
+ - name: "Kotaku"
203
+ url: "https://kotaku.com/rss"
204
+ category: "gaming"
205
+ priority: 8
206
+ - name: "Polygon"
207
+ url: "https://www.polygon.com/rss/index.xml"
208
+ category: "gaming"
209
+ priority: 8
210
+ - name: "PC Gamer"
211
+ url: "https://www.pcgamer.com/rss/"
212
+ category: "gaming"
213
+ priority: 8
214
+ - name: "GameSpot"
215
+ url: "https://www.gamespot.com/feeds/mashup/"
216
+ category: "gaming"
217
+ priority: 7
218
+ - name: "Eurogamer"
219
+ url: "https://www.eurogamer.net/feed"
220
+ category: "gaming"
221
+ priority: 7
222
+
223
+ # ========== Photography (100% VERIFIED) ==========
224
+ - name: "PetaPixel"
225
+ url: "https://petapixel.com/feed/"
226
+ category: "photography"
227
+ priority: 9
228
+ - name: "Fstoppers"
229
+ url: "https://fstoppers.com/feed"
230
+ category: "photography"
231
+ priority: 7
232
+ - name: "Light Stalking"
233
+ url: "https://www.lightstalking.com/feed/"
234
+ category: "photography"
235
+ priority: 7
236
+
237
+ # ========== Music (100% VERIFIED) ==========
238
+ - name: "Pitchfork"
239
+ url: "https://pitchfork.com/rss/news/"
240
+ category: "music"
241
+ priority: 9
242
+ - name: "Rolling Stone"
243
+ url: "https://www.rollingstone.com/feed/"
244
+ category: "music"
245
+ priority: 8
246
+ - name: "Billboard"
247
+ url: "https://www.billboard.com/feed/"
248
+ category: "music"
249
+ priority: 8
250
+ - name: "NME"
251
+ url: "https://www.nme.com/feed"
252
+ category: "music"
253
+ priority: 7
254
+ - name: "Stereogum"
255
+ url: "https://www.stereogum.com/feed/"
256
+ category: "music"
257
+ priority: 7
258
+
259
+ # ========== Finance & Business (100% VERIFIED) ==========
260
+ - name: "CNBC"
261
+ url: "https://www.cnbc.com/id/100003114/device/rss/rss.html"
262
+ category: "finance"
263
+ priority: 8
264
+ - name: "Yahoo Finance"
265
+ url: "https://finance.yahoo.com/news/rssindex"
266
+ category: "finance"
267
+ priority: 8
268
+ - name: "Seeking Alpha"
269
+ url: "https://seekingalpha.com/market_currents.xml"
270
+ category: "finance"
271
+ priority: 7
272
+ - name: "Investopedia"
273
+ url: "https://www.investopedia.com/feedbuilder/feed"
274
+ category: "finance"
275
+ priority: 7
276
+ - name: "Forbes"
277
+ url: "https://www.forbes.com/business/feed/"
278
+ category: "business"
279
+ priority: 9
280
+ - name: "Inc Magazine"
281
+ url: "https://www.inc.com/rss"
282
+ category: "business"
283
+ priority: 8
284
+ - name: "Entrepreneur"
285
+ url: "https://www.entrepreneur.com/latest.rss"
286
+ category: "business"
287
+ priority: 8
288
+
289
+ # ========== Science (100% VERIFIED) ==========
290
+ - name: "Nature"
291
+ url: "https://www.nature.com/nature.rss"
292
+ category: "science"
293
+ priority: 10
294
+ - name: "Science Magazine"
295
+ url: "https://www.science.org/rss/news_current.xml"
296
+ category: "science"
297
+ priority: 9
298
+ - name: "New Scientist"
299
+ url: "https://www.newscientist.com/section/news/feed/"
300
+ category: "science"
301
+ priority: 8
302
+ - name: "Quanta Magazine"
303
+ url: "https://www.quantamagazine.org/feed/"
304
+ category: "science"
305
+ priority: 9
306
+ - name: "Phys.org"
307
+ url: "https://phys.org/rss-feed/"
308
+ category: "science"
309
+ priority: 7
310
+ - name: "Space.com"
311
+ url: "https://www.space.com/feeds/all"
312
+ category: "science"
313
+ priority: 7
314
+
315
+ # ========== Home & Garden (100% VERIFIED) ==========
316
+ - name: "Architectural Digest"
317
+ url: "https://www.architecturaldigest.com/feed/rss"
318
+ category: "home"
319
+ priority: 8
320
+ - name: "House Beautiful"
321
+ url: "https://www.housebeautiful.com/rss/all.xml/"
322
+ category: "home"
323
+ priority: 7
324
+ - name: "Apartment Therapy"
325
+ url: "https://www.apartmenttherapy.com/main.rss"
326
+ category: "home"
327
+ priority: 8
328
+ - name: "Dwell"
329
+ url: "https://www.dwell.com/feed"
330
+ category: "home"
331
+ priority: 7
332
+ - name: "Gardenista"
333
+ url: "https://www.gardenista.com/feed/"
334
+ category: "gardening"
335
+ priority: 7
336
+
337
+ # ========== Automotive (100% VERIFIED) ==========
338
+ - name: "Car and Driver"
339
+ url: "https://www.caranddriver.com/rss/all.xml/"
340
+ category: "automotive"
341
+ priority: 9
342
+ - name: "Road & Track"
343
+ url: "https://www.roadandtrack.com/rss/all.xml/"
344
+ category: "automotive"
345
+ priority: 8
346
+ - name: "Jalopnik"
347
+ url: "https://jalopnik.com/rss"
348
+ category: "automotive"
349
+ priority: 7
350
+ - name: "The Drive"
351
+ url: "https://www.thedrive.com/feed"
352
+ category: "automotive"
353
+ priority: 7
354
+
355
+ # ========== Real Estate (100% VERIFIED) ==========
356
+ - name: "Realtor.com"
357
+ url: "https://www.realtor.com/news/feed/"
358
+ category: "real_estate"
359
+ priority: 8
360
+ - name: "Redfin Blog"
361
+ url: "https://www.redfin.com/blog/feed/"
362
+ category: "real_estate"
363
+ priority: 7
364
+ - name: "Houzz"
365
+ url: "https://www.houzz.com/feed/news"
366
+ category: "real_estate"
367
+ priority: 7
368
+
369
+ # ========== Legal (100% VERIFIED) ==========
370
+ - name: "Above the Law"
371
+ url: "https://abovethelaw.com/feed/"
372
+ category: "legal"
373
+ priority: 8
374
+ - name: "Legal Cheek"
375
+ url: "https://www.legalcheek.com/feed/"
376
+ category: "legal"
377
+ priority: 7
378
+
379
+ # ========== Education (100% VERIFIED) ==========
380
+ - name: "Khan Academy Blog"
381
+ url: "https://blog.khanacademy.org/feed/"
382
+ category: "education"
383
+ priority: 8
384
+ - name: "Edutopia"
385
+ url: "https://www.edutopia.org/rss.xml"
386
+ category: "education"
387
+ priority: 8
388
+ - name: "MIT News"
389
+ url: "https://news.mit.edu/rss/feed"
390
+ category: "education"
391
+ priority: 8
392
+
393
+ # ========== Startups & VC (100% VERIFIED) ==========
394
+ - name: "Y Combinator"
395
+ url: "https://www.ycombinator.com/blog/rss.xml"
396
+ category: "startups"
397
+ priority: 9
398
+ - name: "TechCrunch Startups"
399
+ url: "https://techcrunch.com/category/startups/feed/"
400
+ category: "startups"
401
+ priority: 8
402
+ - name: "First Round Review"
403
+ url: "https://firstround.substack.com/feed"
404
+ category: "startups"
405
+ priority: 8
406
+ - name: "SaaStr"
407
+ url: "https://www.saastr.com/feed/"
408
+ category: "startups"
409
+ priority: 7
410
+
411
+ # ========== Products (100% VERIFIED) ==========
412
+ - name: "Product Hunt"
413
+ url: "https://www.producthunt.com/feed"
414
+ category: "products"
415
+ priority: 9
416
+ - name: "The Verge Reviews"
417
+ url: "https://www.theverge.com/rss/reviews/index.xml"
418
+ category: "products"
419
+ priority: 8
420
+ - name: "Wirecutter"
421
+ url: "https://www.nytimes.com/wirecutter/feed/"
422
+ category: "products"
423
+ priority: 9
424
+ - name: "Engadget"
425
+ url: "https://www.engadget.com/rss.xml"
426
+ category: "products"
427
+ priority: 7
428
+
429
+ # ========== Domains to Monitor ==========
430
+ domains:
431
+ # Technology
432
+ - name: "GitHub"
433
+ base_url: "https://github.com"
434
+ category: "devtools"
435
+ priority: 10
436
+ - name: "Dev.to"
437
+ base_url: "https://dev.to"
438
+ category: "devtools"
439
+ priority: 8
440
+ sitemap: "https://dev.to/sitemap.xml"
441
+ - name: "Hacker News"
442
+ base_url: "https://news.ycombinator.com"
443
+ category: "tech"
444
+ priority: 10
445
+
446
+ # AI
447
+ - name: "ArXiv"
448
+ base_url: "https://arxiv.org"
449
+ category: "ai"
450
+ priority: 10
451
+ - name: "Hugging Face"
452
+ base_url: "https://huggingface.co"
453
+ category: "ai"
454
+ priority: 9
455
+ - name: "Anthropic"
456
+ base_url: "https://www.anthropic.com"
457
+ category: "ai"
458
+ priority: 9
459
+
460
+ # Cooking
461
+ - name: "Bon Appetit"
462
+ base_url: "https://www.bonappetit.com"
463
+ category: "cooking"
464
+ priority: 9
465
+ - name: "BBC Good Food"
466
+ base_url: "https://www.bbcgoodfood.com"
467
+ category: "cooking"
468
+ priority: 8
469
+
470
+ # Travel
471
+ - name: "Nomadic Matt"
472
+ base_url: "https://www.nomadicmatt.com"
473
+ category: "travel"
474
+ priority: 9
475
+ - name: "Condé Nast Traveler"
476
+ base_url: "https://www.cntraveler.com"
477
+ category: "travel"
478
+ priority: 8
479
+
480
+ # Gaming
481
+ - name: "IGN"
482
+ base_url: "https://www.ign.com"
483
+ category: "gaming"
484
+ priority: 9
485
+ - name: "Kotaku"
486
+ base_url: "https://kotaku.com"
487
+ category: "gaming"
488
+ priority: 8
489
+ - name: "Polygon"
490
+ base_url: "https://www.polygon.com"
491
+ category: "gaming"
492
+ priority: 8
493
+
494
+ # Fitness
495
+ - name: "Men's Health"
496
+ base_url: "https://www.menshealth.com"
497
+ category: "fitness"
498
+ priority: 8
499
+ - name: "Runner's World"
500
+ base_url: "https://www.runnersworld.com"
501
+ category: "fitness"
502
+ priority: 7
503
+
504
+ # Health
505
+ - name: "Health.com"
506
+ base_url: "https://www.health.com"
507
+ category: "health"
508
+ priority: 9
509
+ - name: "Mayo Clinic"
510
+ base_url: "https://www.mayoclinic.org"
511
+ category: "health"
512
+ priority: 9
513
+
514
+ # Finance
515
+ - name: "CNBC"
516
+ base_url: "https://www.cnbc.com"
517
+ category: "finance"
518
+ priority: 8
519
+ - name: "Yahoo Finance"
520
+ base_url: "https://finance.yahoo.com"
521
+ category: "finance"
522
+ priority: 8
523
+
524
+ # Science
525
+ - name: "Nature"
526
+ base_url: "https://www.nature.com"
527
+ category: "science"
528
+ priority: 10
529
+ - name: "Science"
530
+ base_url: "https://www.science.org"
531
+ category: "science"
532
+ priority: 9
533
+
534
+ # Home & Garden
535
+ - name: "Architectural Digest"
536
+ base_url: "https://www.architecturaldigest.com"
537
+ category: "home"
538
+ priority: 8
539
+
540
+ # Automotive
541
+ - name: "Car and Driver"
542
+ base_url: "https://www.caranddriver.com"
543
+ category: "automotive"
544
+ priority: 9
545
+
546
+ # Real Estate
547
+ - name: "Realtor.com"
548
+ base_url: "https://www.realtor.com"
549
+ category: "real_estate"
550
+ priority: 8
551
+
552
+ # Legal
553
+ - name: "Above the Law"
554
+ base_url: "https://abovethelaw.com"
555
+ category: "legal"
556
+ priority: 8
557
+
558
+ # Education
559
+ - name: "Edutopia"
560
+ base_url: "https://www.edutopia.org"
561
+ category: "education"
562
+ priority: 8
563
+ - name: "Khan Academy"
564
+ base_url: "https://www.khanacademy.org"
565
+ category: "education"
566
+ priority: 9
567
+
568
+ # Products
569
+ - name: "Product Hunt"
570
+ base_url: "https://www.producthunt.com"
571
+ category: "products"
572
+ priority: 9
573
+ - name: "Wirecutter"
574
+ base_url: "https://www.nytimes.com/wirecutter"
575
+ category: "products"
576
+ priority: 9
577
+
578
+ # Seed URLs for special crawlers
579
+ seed_urls:
580
+ - name: "GitHub Trending"
581
+ url: "https://github.com/trending"
582
+ category: "devtools"
583
+ priority: 9
584
+ - name: "Hacker News"
585
+ url: "https://news.ycombinator.com"
586
+ category: "tech"
587
+ priority: 10
588
+ - name: "Product Hunt"
589
+ url: "https://www.producthunt.com"
590
+ category: "products"
591
+ priority: 9
592
+ - name: "Reddit Programming"
593
+ url: "https://www.reddit.com/r/programming/"
594
+ category: "devtools"
595
+ priority: 8
596
+ - name: "Reddit MachineLearning"
597
+ url: "https://www.reddit.com/r/MachineLearning/"
598
+ category: "ai"
599
+ priority: 8
src/anti_detection/mod.rs ADDED
@@ -0,0 +1,467 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #![allow(dead_code)]
2
+ //! Anti-detection module for IntentForge v2
3
+ //!
4
+ //! Implements bot detection resilience strategies including:
5
+ //! - Header-TLS alignment (Sec-CH-UA hints match User-Agent)
6
+ //! - Grease strings ("Not;A Brand" format)
7
+ //! - Realistic browser header profiles
8
+ //! - Rotating user agents with proper header combinations
9
+
10
+ use rand::Rng;
11
+ use reqwest::header::{
12
+ HeaderMap, HeaderValue, ACCEPT, ACCEPT_LANGUAGE, UPGRADE_INSECURE_REQUESTS, USER_AGENT,
13
+ };
14
+
15
+ /// Browser profile with aligned headers and Sec-CH-UA hints
16
+ #[derive(Debug, Clone)]
17
+ pub struct BrowserProfile {
18
+ pub user_agent: String,
19
+ pub sec_ch_ua: String,
20
+ pub sec_ch_ua_mobile: String,
21
+ pub sec_ch_ua_platform: String,
22
+ pub accept_language: String,
23
+ pub accept_encoding: String,
24
+ pub sec_fetch_site: String,
25
+ pub sec_fetch_mode: String,
26
+ pub sec_fetch_dest: String,
27
+ pub sec_fetch_user: Option<String>,
28
+ }
29
+
30
+ /// Chrome browser version profiles
31
+ #[derive(Debug, Clone)]
32
+ struct ChromeVersion {
33
+ major: u16,
34
+ full: &'static str,
35
+ brand_version: &'static str,
36
+ chromium_version: &'static str,
37
+ }
38
+
39
+ /// Known Chrome versions for realistic UA generation
40
+ const CHROME_VERSIONS: &[ChromeVersion] = &[
41
+ ChromeVersion {
42
+ major: 124,
43
+ full: "124.0.6367.207",
44
+ brand_version: "\"Chromium\";v=\"124\"",
45
+ chromium_version: "\"Google Chrome\";v=\"124\"",
46
+ },
47
+ ChromeVersion {
48
+ major: 123,
49
+ full: "123.0.6312.122",
50
+ brand_version: "\"Chromium\";v=\"123\"",
51
+ chromium_version: "\"Google Chrome\";v=\"123\"",
52
+ },
53
+ ChromeVersion {
54
+ major: 122,
55
+ full: "122.0.6261.128",
56
+ brand_version: "\"Chromium\";v=\"122\"",
57
+ chromium_version: "\"Google Chrome\";v=\"122\"",
58
+ },
59
+ ChromeVersion {
60
+ major: 121,
61
+ full: "121.0.6167.184",
62
+ brand_version: "\"Chromium\";v=\"121\"",
63
+ chromium_version: "\"Google Chrome\";v=\"121\"",
64
+ },
65
+ ];
66
+
67
+ /// Platform configurations
68
+ #[derive(Debug, Clone)]
69
+ struct PlatformConfig {
70
+ platform: &'static str,
71
+ platform_version: &'static str,
72
+ mobile: bool,
73
+ }
74
+
75
+ const PLATFORMS: &[PlatformConfig] = &[
76
+ PlatformConfig {
77
+ platform: "\"Windows\"",
78
+ platform_version: "\"15.0.0\"",
79
+ mobile: false,
80
+ },
81
+ PlatformConfig {
82
+ platform: "\"macOS\"",
83
+ platform_version: "\"14.4.0\"",
84
+ mobile: false,
85
+ },
86
+ PlatformConfig {
87
+ platform: "\"Linux\"",
88
+ platform_version: "\"\"",
89
+ mobile: false,
90
+ },
91
+ PlatformConfig {
92
+ platform: "\"Android\"",
93
+ platform_version: "\"14.0.0\"",
94
+ mobile: true,
95
+ },
96
+ ];
97
+
98
+ /// Generate a "Not;A Brand" grease string
99
+ ///
100
+ /// Grease strings are randomized brand identifiers used in Sec-CH-UA headers
101
+ /// to prevent fingerprinting based on exact brand list.
102
+ /// Format: "Not_A Brand" or "Not;A Brand" with varying separators.
103
+ fn generate_grease_string(rng: &mut impl Rng) -> String {
104
+ let separators = ['_', ';', ' '];
105
+ let prefix_words = ["Not", "Not_A", "Not;A"];
106
+ let suffix_words = ["Brand", "Browser", "Chromium"];
107
+
108
+ let sep = separators[rng.gen_range(0..separators.len())];
109
+ let prefix = prefix_words[rng.gen_range(0..prefix_words.len())];
110
+ let suffix = suffix_words[rng.gen_range(0..suffix_words.len())];
111
+
112
+ format!("{}{}{}", prefix, sep, suffix)
113
+ }
114
+
115
+ /// Generate realistic Sec-CH-UA header value
116
+ ///
117
+ /// Format: "Not_A Brand";v="8", "Chromium";v="124", "Google Chrome";v="124"
118
+ /// The grease string varies in position (usually first or last).
119
+ fn generate_sec_ch_ua(version: &ChromeVersion, rng: &mut impl Rng) -> String {
120
+ let grease = generate_grease_string(rng);
121
+
122
+ // Randomly decide if grease goes first or last
123
+ let grease_first = rng.gen_bool(0.7);
124
+
125
+ if grease_first {
126
+ format!(
127
+ "\"{}\";v=\"{}\", {}, {}",
128
+ grease, version.major, version.brand_version, version.chromium_version
129
+ )
130
+ } else {
131
+ format!(
132
+ "{}, {}, \"{}\";v=\"{}\"",
133
+ version.brand_version, version.chromium_version, grease, version.major
134
+ )
135
+ }
136
+ }
137
+
138
+ /// Header generator with TLS alignment
139
+ ///
140
+ /// Ensures Sec-CH-UA hints are perfectly aligned with the User-Agent string.
141
+ /// This prevents detection through header inconsistencies.
142
+ pub struct HeaderGenerator {
143
+ profiles: Vec<BrowserProfile>,
144
+ }
145
+
146
+ impl HeaderGenerator {
147
+ /// Create a new header generator with pre-computed browser profiles
148
+ pub fn new() -> Self {
149
+ let mut profiles = Vec::new();
150
+ let mut rng = rand::thread_rng();
151
+
152
+ for version in CHROME_VERSIONS {
153
+ for platform in PLATFORMS {
154
+ let ua = generate_user_agent(version, platform);
155
+ let sec_ch_ua = generate_sec_ch_ua(version, &mut rng);
156
+ let sec_ch_ua_mobile = if platform.mobile { "?1" } else { "?0" };
157
+ let sec_ch_ua_platform = platform.platform.to_string();
158
+
159
+ profiles.push(BrowserProfile {
160
+ user_agent: ua,
161
+ sec_ch_ua,
162
+ sec_ch_ua_mobile: sec_ch_ua_mobile.to_string(),
163
+ sec_ch_ua_platform,
164
+ accept_language: generate_accept_language(&mut rng),
165
+ accept_encoding: "gzip, deflate, br".to_string(),
166
+ sec_fetch_site: "none".to_string(),
167
+ sec_fetch_mode: "navigate".to_string(),
168
+ sec_fetch_dest: "document".to_string(),
169
+ sec_fetch_user: Some("?1".to_string()),
170
+ });
171
+ }
172
+ }
173
+
174
+ Self { profiles }
175
+ }
176
+
177
+ /// Get a random browser profile
178
+ pub fn random_profile(&self) -> &BrowserProfile {
179
+ let mut rng = rand::thread_rng();
180
+ let idx = rng.gen_range(0..self.profiles.len());
181
+ &self.profiles[idx]
182
+ }
183
+
184
+ /// Get a profile that matches a specific User-Agent
185
+ pub fn matching_profile(&self, user_agent: &str) -> Option<&BrowserProfile> {
186
+ self.profiles.iter().find(|p| p.user_agent == user_agent)
187
+ }
188
+
189
+ /// Generate headers for a reqwest request
190
+ pub fn generate_headers(&self) -> HeaderMap {
191
+ let profile = self.random_profile();
192
+ self.profile_to_headers(profile)
193
+ }
194
+
195
+ /// Convert a browser profile to reqwest HeaderMap
196
+ fn profile_to_headers(&self, profile: &BrowserProfile) -> HeaderMap {
197
+ let mut headers = HeaderMap::new();
198
+
199
+ headers.insert(
200
+ USER_AGENT,
201
+ HeaderValue::from_str(&profile.user_agent).unwrap(),
202
+ );
203
+ headers.insert(
204
+ ACCEPT,
205
+ HeaderValue::from_static(
206
+ "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8",
207
+ ),
208
+ );
209
+ headers.insert(
210
+ ACCEPT_LANGUAGE,
211
+ HeaderValue::from_str(&profile.accept_language).unwrap(),
212
+ );
213
+ headers.insert(
214
+ "sec-ch-ua",
215
+ HeaderValue::from_str(&profile.sec_ch_ua).unwrap(),
216
+ );
217
+ headers.insert(
218
+ "sec-ch-ua-mobile",
219
+ HeaderValue::from_str(&profile.sec_ch_ua_mobile).unwrap(),
220
+ );
221
+ headers.insert(
222
+ "sec-ch-ua-platform",
223
+ HeaderValue::from_str(&profile.sec_ch_ua_platform).unwrap(),
224
+ );
225
+ headers.insert(
226
+ "sec-fetch-site",
227
+ HeaderValue::from_str(&profile.sec_fetch_site).unwrap(),
228
+ );
229
+ headers.insert(
230
+ "sec-fetch-mode",
231
+ HeaderValue::from_str(&profile.sec_fetch_mode).unwrap(),
232
+ );
233
+ headers.insert(
234
+ "sec-fetch-dest",
235
+ HeaderValue::from_str(&profile.sec_fetch_dest).unwrap(),
236
+ );
237
+ if let Some(ref sec_fetch_user) = profile.sec_fetch_user {
238
+ headers.insert(
239
+ "sec-fetch-user",
240
+ HeaderValue::from_str(sec_fetch_user).unwrap(),
241
+ );
242
+ }
243
+ headers.insert(UPGRADE_INSECURE_REQUESTS, HeaderValue::from_static("1"));
244
+
245
+ headers
246
+ }
247
+
248
+ /// Build a reqwest::Client with realistic headers
249
+ pub fn build_client(&self) -> reqwest::Client {
250
+ let profile = self.random_profile();
251
+ let headers = self.profile_to_headers(profile);
252
+
253
+ reqwest::Client::builder()
254
+ .user_agent(&profile.user_agent)
255
+ .default_headers(headers)
256
+ .timeout(std::time::Duration::from_secs(30))
257
+ .pool_max_idle_per_host(8)
258
+ .build()
259
+ .expect("Failed to build HTTP client with anti-detection headers")
260
+ }
261
+ }
262
+
263
+ impl Default for HeaderGenerator {
264
+ fn default() -> Self {
265
+ Self::new()
266
+ }
267
+ }
268
+
269
+ /// Generate a realistic User-Agent string for Chrome
270
+ fn generate_user_agent(version: &ChromeVersion, platform: &PlatformConfig) -> String {
271
+ if platform.mobile {
272
+ format!(
273
+ "Mozilla/5.0 (Linux; Android {}; Mobile) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/{} Mobile Safari/537.36",
274
+ "14", version.full
275
+ )
276
+ } else {
277
+ let os = match platform.platform {
278
+ "\"Windows\"" => format!("Windows NT {}", platform.platform_version.trim_matches('"')),
279
+ "\"macOS\"" => "Macintosh; Intel Mac OS X 10_15_7".to_string(),
280
+ "\"Linux\"" => "X11; Linux x86_64".to_string(),
281
+ _ => "Windows NT 10.0; Win64; x64".to_string(),
282
+ };
283
+ format!(
284
+ "Mozilla/5.0 ({}) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/{} Safari/537.36",
285
+ os, version.full
286
+ )
287
+ }
288
+ }
289
+
290
+ /// Generate a realistic Accept-Language header
291
+ fn generate_accept_language(rng: &mut impl Rng) -> String {
292
+ let languages = [
293
+ "en-US,en;q=0.9",
294
+ "en-GB,en;q=0.9",
295
+ "en-US,en;q=0.9,es;q=0.8",
296
+ "en-US,en;q=0.9,fr;q=0.8,de;q=0.7",
297
+ "en-US,en;q=0.9,zh-CN;q=0.8,zh;q=0.7",
298
+ "en-US,en;q=0.9,ja;q=0.8",
299
+ ];
300
+
301
+ languages[rng.gen_range(0..languages.len())].to_string()
302
+ }
303
+
304
+ /// Rotating user agent pool for high-volume scraping
305
+ ///
306
+ /// Maintains a pool of user agents and rotates through them
307
+ /// to avoid pattern-based detection.
308
+ pub struct UserAgentRotator {
309
+ profiles: Vec<BrowserProfile>,
310
+ current: std::sync::atomic::AtomicUsize,
311
+ }
312
+
313
+ impl UserAgentRotator {
314
+ pub fn new() -> Self {
315
+ let generator = HeaderGenerator::new();
316
+ Self {
317
+ profiles: generator.profiles,
318
+ current: std::sync::atomic::AtomicUsize::new(0),
319
+ }
320
+ }
321
+
322
+ /// Get the next user agent in the rotation
323
+ pub fn next(&self) -> &BrowserProfile {
324
+ use std::sync::atomic::Ordering;
325
+ let idx = self.current.fetch_add(1, Ordering::Relaxed) % self.profiles.len();
326
+ &self.profiles[idx]
327
+ }
328
+
329
+ /// Get a random user agent
330
+ pub fn random(&self) -> &BrowserProfile {
331
+ let mut rng = rand::thread_rng();
332
+ let idx = rand::Rng::gen_range(&mut rng, 0..self.profiles.len());
333
+ &self.profiles[idx]
334
+ }
335
+
336
+ /// Get all available user agents
337
+ pub fn all(&self) -> &[BrowserProfile] {
338
+ &self.profiles
339
+ }
340
+ }
341
+
342
+ impl Default for UserAgentRotator {
343
+ fn default() -> Self {
344
+ Self::new()
345
+ }
346
+ }
347
+
348
+ #[cfg(test)]
349
+ mod tests {
350
+ use super::*;
351
+
352
+ #[test]
353
+ fn test_grease_string_generation() {
354
+ let mut rng = rand::thread_rng();
355
+ for _ in 0..100 {
356
+ let grease = generate_grease_string(&mut rng);
357
+ assert!(!grease.is_empty());
358
+ assert!(
359
+ grease.contains("Not") || grease.contains("Brand") || grease.contains("Browser")
360
+ );
361
+ }
362
+ }
363
+
364
+ #[test]
365
+ fn test_sec_ch_ua_format() {
366
+ let mut rng = rand::thread_rng();
367
+ let version = &CHROME_VERSIONS[0];
368
+ let sec_ch_ua = generate_sec_ch_ua(version, &mut rng);
369
+ // Should contain the Chrome version
370
+ assert!(sec_ch_ua.contains(&format!("\"{}\"", version.major)));
371
+ // Should contain Chromium
372
+ assert!(sec_ch_ua.contains("Chromium"));
373
+ // Should contain Google Chrome
374
+ assert!(sec_ch_ua.contains("Google Chrome"));
375
+ }
376
+
377
+ #[test]
378
+ fn test_header_generator_profiles() {
379
+ let gen = HeaderGenerator::new();
380
+ assert!(!gen.profiles.is_empty());
381
+ // Should have profiles for each version × platform combination
382
+ assert_eq!(gen.profiles.len(), CHROME_VERSIONS.len() * PLATFORMS.len());
383
+ }
384
+
385
+ #[test]
386
+ fn test_header_generator_random_profile() {
387
+ let gen = HeaderGenerator::new();
388
+ let profile = gen.random_profile();
389
+ assert!(!profile.user_agent.is_empty());
390
+ assert!(!profile.sec_ch_ua.is_empty());
391
+ assert!(!profile.accept_language.is_empty());
392
+ }
393
+
394
+ #[test]
395
+ fn test_profile_alignment() {
396
+ let gen = HeaderGenerator::new();
397
+ for profile in gen.profiles.iter().take(5) {
398
+ // If UA contains "Mobile", sec-ch-ua-mobile should be "?1"
399
+ if profile.user_agent.contains("Mobile") {
400
+ assert_eq!(profile.sec_ch_ua_mobile, "?1");
401
+ }
402
+ // If UA contains "Windows", platform should be "Windows"
403
+ if profile.user_agent.contains("Windows") {
404
+ assert!(profile.sec_ch_ua_platform.contains("Windows"));
405
+ }
406
+ // If UA contains "Mac", platform should be "macOS"
407
+ if profile.user_agent.contains("Macintosh") {
408
+ assert!(profile.sec_ch_ua_platform.contains("macOS"));
409
+ }
410
+ }
411
+ }
412
+
413
+ #[test]
414
+ fn test_user_agent_rotator() {
415
+ let rotator = UserAgentRotator::new();
416
+ let first = rotator.next().user_agent.clone();
417
+ let second = rotator.next().user_agent.clone();
418
+ // With enough profiles, rotation should give different results eventually
419
+ // (may be same if only 1 profile, but we have many)
420
+ assert!(!first.is_empty());
421
+ assert!(!second.is_empty());
422
+ }
423
+
424
+ #[test]
425
+ fn test_user_agent_format() {
426
+ let version = &CHROME_VERSIONS[0];
427
+ let desktop = &PLATFORMS[0]; // Windows
428
+ let ua = generate_user_agent(version, desktop);
429
+ assert!(ua.starts_with("Mozilla/5.0"));
430
+ assert!(ua.contains("Chrome/124"));
431
+ assert!(ua.contains("Safari/537.36"));
432
+ assert!(!ua.contains("Mobile"));
433
+ }
434
+
435
+ #[test]
436
+ fn test_mobile_user_agent_format() {
437
+ let version = &CHROME_VERSIONS[0];
438
+ let mobile = &PLATFORMS[3]; // Android
439
+ let ua = generate_user_agent(version, mobile);
440
+ assert!(ua.contains("Android"));
441
+ assert!(ua.contains("Mobile"));
442
+ assert!(ua.contains("Chrome/124"));
443
+ }
444
+
445
+ #[test]
446
+ fn test_accept_language_variations() {
447
+ let mut rng = rand::thread_rng();
448
+ let mut langs = std::collections::HashSet::new();
449
+ for _ in 0..50 {
450
+ langs.insert(generate_accept_language(&mut rng));
451
+ }
452
+ // Should have multiple variations
453
+ assert!(langs.len() > 1);
454
+ }
455
+
456
+ #[test]
457
+ fn test_generate_headers() {
458
+ let gen = HeaderGenerator::new();
459
+ let headers = gen.generate_headers();
460
+ assert!(headers.contains_key("user-agent"));
461
+ assert!(headers.contains_key("sec-ch-ua"));
462
+ assert!(headers.contains_key("sec-ch-ua-mobile"));
463
+ assert!(headers.contains_key("sec-ch-ua-platform"));
464
+ assert!(headers.contains_key("accept"));
465
+ assert!(headers.contains_key("accept-language"));
466
+ }
467
+ }
src/anti_detection_client/mod.rs ADDED
@@ -0,0 +1,544 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #![allow(dead_code)]
2
+ //! Anti-Detection HTTP Client for IntentForge v2
3
+ //!
4
+ //! Provides human-like HTTP requests with:
5
+ //! - User agent rotation
6
+ //! - Proxy rotation (free proxy lists)
7
+ //! - Request queuing with rate limiting
8
+ //! - Cookie handling
9
+ //! - Retry with exponential backoff
10
+ //! - HTML scraping fallback when RSS fails
11
+
12
+ use anyhow::{Context, Result};
13
+ use rand::Rng;
14
+ use std::collections::VecDeque;
15
+ use std::sync::Arc;
16
+ use std::time::{Duration, Instant};
17
+ use tokio::sync::{Mutex, RwLock};
18
+
19
+ /// List of realistic user agents (Chrome, Firefox, Safari on different OS)
20
+ const USER_AGENTS: &[&str] = &[
21
+ // Chrome on Windows
22
+ "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36",
23
+ "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36",
24
+ "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/129.0.0.0 Safari/537.36",
25
+ // Chrome on Mac
26
+ "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36",
27
+ "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36",
28
+ // Firefox on Windows
29
+ "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:133.0) Gecko/20100101 Firefox/133.0",
30
+ "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:132.0) Gecko/20100101 Firefox/132.0",
31
+ // Firefox on Mac
32
+ "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:133.0) Gecko/20100101 Firefox/133.0",
33
+ // Safari on Mac
34
+ "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/18.2 Safari/605.1.15",
35
+ "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.6 Safari/605.1.15",
36
+ // Chrome on Linux
37
+ "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36",
38
+ // Edge on Windows
39
+ "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36 Edg/131.0.0.0",
40
+ ];
41
+
42
+ /// Common referer headers to appear more human-like
43
+ const REFERERS: &[&str] = &[
44
+ "https://www.google.com/",
45
+ "https://www.bing.com/",
46
+ "https://duckduckgo.com/",
47
+ "https://www.google.co.uk/",
48
+ "https://www.google.de/",
49
+ "",
50
+ ];
51
+
52
+ /// Accept-Language headers for different regions
53
+ const ACCEPT_LANGUAGES: &[&str] = &[
54
+ "en-US,en;q=0.9",
55
+ "en-US,en;q=0.9,es;q=0.8",
56
+ "en-GB,en;q=0.9",
57
+ "en-US,en;q=0.9,de;q=0.8",
58
+ "en;q=0.9",
59
+ ];
60
+
61
+ /// Proxy configuration
62
+ #[derive(Debug, Clone)]
63
+ pub struct Proxy {
64
+ pub url: String,
65
+ pub proxy_type: ProxyType,
66
+ pub latency_ms: u64,
67
+ pub last_used: Option<Instant>,
68
+ pub fail_count: u32,
69
+ }
70
+
71
+ #[derive(Debug, Clone, PartialEq)]
72
+ pub enum ProxyType {
73
+ Http,
74
+ Https,
75
+ Socks5,
76
+ }
77
+
78
+ /// Token bucket rate limiter
79
+ pub struct RateLimiter {
80
+ tokens: f64,
81
+ max_tokens: f64,
82
+ refill_rate: f64, // tokens per second
83
+ last_refill: Instant,
84
+ }
85
+
86
+ impl RateLimiter {
87
+ pub fn new(max_tokens: f64, refill_rate: f64) -> Self {
88
+ Self {
89
+ tokens: max_tokens,
90
+ max_tokens,
91
+ refill_rate,
92
+ last_refill: Instant::now(),
93
+ }
94
+ }
95
+
96
+ pub async fn acquire(&mut self) {
97
+ loop {
98
+ self.refill();
99
+ if self.tokens >= 1.0 {
100
+ self.tokens -= 1.0;
101
+ return;
102
+ }
103
+ // Wait for a token to become available
104
+ let wait_time = Duration::from_secs_f64((1.0 - self.tokens) / self.refill_rate);
105
+ tokio::time::sleep(wait_time).await;
106
+ }
107
+ }
108
+
109
+ fn refill(&mut self) {
110
+ let now = Instant::now();
111
+ let elapsed = now.duration_since(self.last_refill).as_secs_f64();
112
+ self.tokens = (self.tokens + elapsed * self.refill_rate).min(self.max_tokens);
113
+ self.last_refill = now;
114
+ }
115
+ }
116
+
117
+ /// Anti-detection HTTP client
118
+ pub struct AntiDetectionClient {
119
+ client: reqwest::Client,
120
+ proxies: Arc<RwLock<Vec<Proxy>>>,
121
+ rate_limiters: Arc<RwLock<std::collections::HashMap<String, RateLimiter>>>,
122
+ request_queue: Arc<Mutex<VecDeque<QueuedRequest>>>,
123
+ cookie_jar: Arc<RwLock<std::collections::HashMap<String, String>>>,
124
+ }
125
+
126
+ struct QueuedRequest {
127
+ url: String,
128
+ domain: String,
129
+ created_at: Instant,
130
+ }
131
+
132
+ impl AntiDetectionClient {
133
+ /// Create a new anti-detection client
134
+ pub async fn new() -> Result<Self> {
135
+ let mut headers = reqwest::header::HeaderMap::new();
136
+ headers.insert(
137
+ reqwest::header::ACCEPT,
138
+ reqwest::header::HeaderValue::from_static(
139
+ "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8",
140
+ ),
141
+ );
142
+ headers.insert(
143
+ reqwest::header::ACCEPT_ENCODING,
144
+ reqwest::header::HeaderValue::from_static("gzip, deflate, br"),
145
+ );
146
+
147
+ let client = reqwest::Client::builder()
148
+ .user_agent(USER_AGENTS[0])
149
+ .default_headers(headers)
150
+ .timeout(Duration::from_secs(30))
151
+ .pool_max_idle_per_host(2)
152
+ .pool_idle_timeout(Duration::from_secs(30))
153
+ .tcp_keepalive(Duration::from_secs(60))
154
+ .build()
155
+ .context("Failed to create HTTP client")?;
156
+
157
+ let proxies = Arc::new(RwLock::new(Vec::new()));
158
+ let rate_limiters = Arc::new(RwLock::new(std::collections::HashMap::new()));
159
+ let request_queue = Arc::new(Mutex::new(VecDeque::new()));
160
+ let cookie_jar = Arc::new(RwLock::new(std::collections::HashMap::new()));
161
+
162
+ let instance = Self {
163
+ client,
164
+ proxies,
165
+ rate_limiters,
166
+ request_queue,
167
+ cookie_jar,
168
+ };
169
+
170
+ // Load initial proxies
171
+ instance.load_proxies().await?;
172
+
173
+ Ok(instance)
174
+ }
175
+
176
+ /// Load proxies from free proxy lists
177
+ async fn load_proxies(&self) -> Result<()> {
178
+ let proxy_sources = vec![
179
+ "https://api.proxyscrape.com/v2/?request=displayproxies&protocol=http&timeout=10000&country=all&ssl=all&anonymity=all",
180
+ "https://raw.githubusercontent.com/TheSpeedX/PROXY-List/master/http.txt",
181
+ "https://raw.githubusercontent.com/clarketm/proxy-list/master/proxy-list-raw.txt",
182
+ ];
183
+
184
+ let mut proxies = self.proxies.write().await;
185
+ proxies.clear();
186
+
187
+ for source in proxy_sources {
188
+ match self.client.get(source).send().await {
189
+ Ok(resp) => {
190
+ if let Ok(text) = resp.text().await {
191
+ for line in text.lines() {
192
+ let line = line.trim();
193
+ if !line.is_empty() && line.contains(':') {
194
+ let url = if line.starts_with("http") {
195
+ line.to_string()
196
+ } else {
197
+ format!("http://{}", line)
198
+ };
199
+ proxies.push(Proxy {
200
+ url,
201
+ proxy_type: ProxyType::Http,
202
+ latency_ms: 0,
203
+ last_used: None,
204
+ fail_count: 0,
205
+ });
206
+ }
207
+ }
208
+ }
209
+ }
210
+ Err(e) => {
211
+ tracing::warn!("Failed to load proxies from {}: {}", source, e);
212
+ }
213
+ }
214
+ }
215
+
216
+ tracing::info!("Loaded {} proxies", proxies.len());
217
+ Ok(())
218
+ }
219
+
220
+ /// Get a random user agent
221
+ fn random_user_agent() -> &'static str {
222
+ let mut rng = rand::thread_rng();
223
+ USER_AGENTS[rng.gen_range(0..USER_AGENTS.len())]
224
+ }
225
+
226
+ /// Get a random referer
227
+ fn random_referer() -> &'static str {
228
+ let mut rng = rand::thread_rng();
229
+ REFERERS[rng.gen_range(0..REFERERS.len())]
230
+ }
231
+
232
+ /// Get a random accept language
233
+ fn random_accept_language() -> &'static str {
234
+ let mut rng = rand::thread_rng();
235
+ ACCEPT_LANGUAGES[rng.gen_range(0..ACCEPT_LANGUAGES.len())]
236
+ }
237
+
238
+ /// Get rate limiter for a domain
239
+ async fn get_rate_limiter(&self, domain: &str) -> RateLimiter {
240
+ let mut limiters = self.rate_limiters.write().await;
241
+ limiters
242
+ .entry(domain.to_string())
243
+ .or_insert_with(|| {
244
+ // Default: 2 requests per second per domain
245
+ RateLimiter::new(5.0, 2.0)
246
+ })
247
+ .clone()
248
+ }
249
+
250
+ /// Add random delay between requests (200-800ms)
251
+ async fn random_delay() {
252
+ let mut rng = rand::thread_rng();
253
+ let delay_ms = rng.gen_range(200..800);
254
+ tokio::time::sleep(Duration::from_millis(delay_ms)).await;
255
+ }
256
+
257
+ /// Extract domain from URL
258
+ fn extract_domain(url: &str) -> String {
259
+ url::Url::parse(url)
260
+ .ok()
261
+ .and_then(|u| u.host_str().map(|h| h.to_string()))
262
+ .unwrap_or_default()
263
+ }
264
+
265
+ /// Make a GET request with anti-detection measures
266
+ pub async fn get(&self, url: &str) -> Result<reqwest::Response> {
267
+ let domain = Self::extract_domain(url);
268
+
269
+ // Rate limit per domain
270
+ {
271
+ let mut limiters = self.rate_limiters.write().await;
272
+ let limiter = limiters
273
+ .entry(domain.clone())
274
+ .or_insert_with(|| RateLimiter::new(5.0, 2.0));
275
+ limiter.acquire().await;
276
+ }
277
+
278
+ // Random delay
279
+ Self::random_delay().await;
280
+
281
+ // Build request with human-like headers
282
+ let user_agent = Self::random_user_agent();
283
+ let referer = Self::random_referer();
284
+ let accept_language = Self::random_accept_language();
285
+
286
+ let mut request = self
287
+ .client
288
+ .get(url)
289
+ .header("User-Agent", user_agent)
290
+ .header("Accept-Language", accept_language)
291
+ .header("DNT", "1")
292
+ .header("Connection", "keep-alive")
293
+ .header("Upgrade-Insecure-Requests", "1")
294
+ .header("Sec-Fetch-Dest", "document")
295
+ .header("Sec-Fetch-Mode", "navigate")
296
+ .header("Sec-Fetch-Site", "none")
297
+ .header("Sec-Fetch-User", "?1")
298
+ .header("Cache-Control", "max-age=0");
299
+
300
+ if !referer.is_empty() {
301
+ request = request.header("Referer", referer);
302
+ }
303
+
304
+ // Add cookies if we have any for this domain
305
+ {
306
+ let cookies = self.cookie_jar.read().await;
307
+ if let Some(cookie) = cookies.get(&domain) {
308
+ request = request.header("Cookie", cookie);
309
+ }
310
+ }
311
+
312
+ // Send request with retry
313
+ let response = self.send_with_retry(request, url, 3).await?;
314
+
315
+ // Store cookies from response
316
+ if let Some(set_cookie) = response.headers().get("set-cookie") {
317
+ if let Ok(cookie_str) = set_cookie.to_str() {
318
+ let mut cookies = self.cookie_jar.write().await;
319
+ cookies.insert(domain, cookie_str.to_string());
320
+ }
321
+ }
322
+
323
+ Ok(response)
324
+ }
325
+
326
+ /// Send request with retry and exponential backoff
327
+ async fn send_with_retry(
328
+ &self,
329
+ request: reqwest::RequestBuilder,
330
+ url: &str,
331
+ max_retries: u32,
332
+ ) -> Result<reqwest::Response> {
333
+ let mut last_error = None;
334
+
335
+ for attempt in 0..max_retries {
336
+ let req = request.try_clone().context("Failed to clone request")?;
337
+
338
+ match req.send().await {
339
+ Ok(response) => {
340
+ let status = response.status();
341
+
342
+ // Handle rate limiting (429)
343
+ if status == 429 {
344
+ let retry_after = response
345
+ .headers()
346
+ .get("retry-after")
347
+ .and_then(|v| v.to_str().ok())
348
+ .and_then(|v| v.parse::<u64>().ok())
349
+ .unwrap_or(60);
350
+
351
+ tracing::warn!(
352
+ "Rate limited on {} (attempt {}/{}), waiting {}s",
353
+ url,
354
+ attempt + 1,
355
+ max_retries,
356
+ retry_after
357
+ );
358
+
359
+ tokio::time::sleep(Duration::from_secs(retry_after)).await;
360
+ continue;
361
+ }
362
+
363
+ // Handle 403 Forbidden - try with different user agent
364
+ if status == 403 && attempt < max_retries - 1 {
365
+ tracing::warn!(
366
+ "403 Forbidden on {} (attempt {}/{}), retrying with different headers",
367
+ url,
368
+ attempt + 1,
369
+ max_retries
370
+ );
371
+
372
+ // Wait before retry with exponential backoff
373
+ let wait_time = Duration::from_secs(2u64.pow(attempt));
374
+ tokio::time::sleep(wait_time).await;
375
+ continue;
376
+ }
377
+
378
+ return Ok(response);
379
+ }
380
+ Err(e) => {
381
+ last_error = Some(e);
382
+
383
+ if attempt < max_retries - 1 {
384
+ let wait_time = Duration::from_secs(2u64.pow(attempt));
385
+ tracing::warn!(
386
+ "Request failed on {} (attempt {}/{}): retrying in {:?}",
387
+ url,
388
+ attempt + 1,
389
+ max_retries,
390
+ wait_time
391
+ );
392
+ tokio::time::sleep(wait_time).await;
393
+ }
394
+ }
395
+ }
396
+ }
397
+
398
+ Err(last_error
399
+ .map(|e| anyhow::anyhow!("{}", e))
400
+ .unwrap_or_else(|| anyhow::anyhow!("Request failed after {} attempts", max_retries)))
401
+ }
402
+
403
+ /// Try fetching with proxy
404
+ pub async fn get_with_proxy(&self, url: &str) -> Result<reqwest::Response> {
405
+ let proxies = self.proxies.read().await;
406
+
407
+ if proxies.is_empty() {
408
+ return self.get(url).await;
409
+ }
410
+
411
+ // Try up to 3 different proxies
412
+ let mut rng = rand::thread_rng();
413
+ for _ in 0..3 {
414
+ let proxy_idx = rng.gen_range(0..proxies.len());
415
+ let proxy = &proxies[proxy_idx];
416
+
417
+ let proxy_client = reqwest::Client::builder()
418
+ .user_agent(Self::random_user_agent())
419
+ .timeout(Duration::from_secs(15))
420
+ .proxy(reqwest::Proxy::all(&proxy.url)?)
421
+ .build();
422
+
423
+ if let Ok(client) = proxy_client {
424
+ match client.get(url).send().await {
425
+ Ok(resp) if resp.status().is_success() => {
426
+ return Ok(resp);
427
+ }
428
+ _ => continue,
429
+ }
430
+ }
431
+ }
432
+
433
+ // Fall back to direct request
434
+ self.get(url).await
435
+ }
436
+
437
+ /// Scrape content from HTML page (fallback when RSS fails)
438
+ pub async fn scrape_html(&self, url: &str) -> Result<Vec<ScrapedItem>> {
439
+ let response = self.get(url).await?;
440
+ let html = response.text().await?;
441
+
442
+ let mut items = Vec::new();
443
+
444
+ // Simple link extraction (for article-like pages)
445
+ let link_regex = regex::Regex::new(r#"<a[^>]+href="([^"]+)"[^>]*>([^<]+)</a>"#).unwrap();
446
+
447
+ for cap in link_regex.captures_iter(&html) {
448
+ if let (Some(href), Some(title)) = (cap.get(1), cap.get(2)) {
449
+ let href = href.as_str();
450
+ let title = title.as_str().trim();
451
+
452
+ // Filter for article-like links
453
+ if title.len() > 20
454
+ && title.len() < 200
455
+ && !href.starts_with('#')
456
+ && !href.starts_with("javascript:")
457
+ && (href.starts_with("http") || href.starts_with('/'))
458
+ {
459
+ let full_url = if href.starts_with('/') {
460
+ let base = url::Url::parse(url)?;
461
+ base.join(href)?.to_string()
462
+ } else {
463
+ href.to_string()
464
+ };
465
+
466
+ items.push(ScrapedItem {
467
+ title: title.to_string(),
468
+ url: full_url,
469
+ description: None,
470
+ });
471
+ }
472
+ }
473
+ }
474
+
475
+ // Limit to reasonable number
476
+ items.truncate(20);
477
+
478
+ Ok(items)
479
+ }
480
+ }
481
+
482
+ /// Scraped item from HTML
483
+ #[derive(Debug, Clone)]
484
+ pub struct ScrapedItem {
485
+ pub title: String,
486
+ pub url: String,
487
+ pub description: Option<String>,
488
+ }
489
+
490
+ impl Clone for RateLimiter {
491
+ fn clone(&self) -> Self {
492
+ Self {
493
+ tokens: self.tokens,
494
+ max_tokens: self.max_tokens,
495
+ refill_rate: self.refill_rate,
496
+ last_refill: Instant::now(),
497
+ }
498
+ }
499
+ }
500
+
501
+ #[cfg(test)]
502
+ mod tests {
503
+ use super::*;
504
+
505
+ #[tokio::test]
506
+ async fn test_rate_limiter() {
507
+ let mut limiter = RateLimiter::new(5.0, 10.0);
508
+
509
+ // Should be able to acquire 5 tokens immediately
510
+ for _ in 0..5 {
511
+ limiter.acquire().await;
512
+ }
513
+
514
+ // 6th token should require waiting
515
+ let start = Instant::now();
516
+ limiter.acquire().await;
517
+ let elapsed = start.elapsed();
518
+
519
+ // Should have waited approximately 0.1 seconds (1/10 tokens per second)
520
+ assert!(elapsed >= Duration::from_millis(50));
521
+ }
522
+
523
+ #[test]
524
+ fn test_extract_domain() {
525
+ assert_eq!(
526
+ AntiDetectionClient::extract_domain("https://example.com/path"),
527
+ "example.com"
528
+ );
529
+ assert_eq!(
530
+ AntiDetectionClient::extract_domain("http://sub.example.com:8080/path"),
531
+ "sub.example.com"
532
+ );
533
+ }
534
+
535
+ #[test]
536
+ fn test_user_agent_rotation() {
537
+ let mut agents = std::collections::HashSet::new();
538
+ for _ in 0..20 {
539
+ agents.insert(AntiDetectionClient::random_user_agent());
540
+ }
541
+ // Should have at least 3 different user agents
542
+ assert!(agents.len() >= 3);
543
+ }
544
+ }
src/api/mod.rs ADDED
@@ -0,0 +1,1659 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #![allow(dead_code)]
2
+ //! HTTP API module for IntentForge v2
3
+ //!
4
+ //! Provides REST endpoints for crawling, searching, and health checks
5
+ //! using axum web framework.
6
+
7
+ use axum::{
8
+ extract::{Path, Query, Request, State},
9
+ http::{HeaderMap, StatusCode},
10
+ middleware::{self, Next},
11
+ response::{IntoResponse, Response},
12
+ routing::{get, post},
13
+ Json, Router,
14
+ };
15
+ use serde::{Deserialize, Serialize};
16
+ use std::collections::HashSet;
17
+ use std::hash::{Hash, Hasher};
18
+ use std::sync::Arc;
19
+ use std::time::Instant;
20
+
21
+ use crate::metrics::Metrics;
22
+ use crate::AppState;
23
+
24
+ /// Count phrase-aware significant term hits in a text.
25
+ /// Phrase matches count as 2 hits each; individual terms that are part of a matched phrase are skipped.
26
+ fn count_phrase_aware_hits<S: AsRef<str>>(
27
+ combined: &str,
28
+ phrase_terms: &[String],
29
+ significant_terms: &[S],
30
+ ) -> usize {
31
+ let phrase_hits = phrase_terms
32
+ .iter()
33
+ .filter(|p| combined.contains(p.as_str()))
34
+ .count();
35
+ let individual_hits = significant_terms
36
+ .iter()
37
+ .filter(|t| {
38
+ let t_str = t.as_ref();
39
+ let in_phrase = phrase_terms.iter().any(|p| p.contains(t_str));
40
+ if in_phrase {
41
+ return false;
42
+ }
43
+ combined.contains(t_str)
44
+ })
45
+ .count();
46
+ phrase_hits * 2 + individual_hits
47
+ }
48
+
49
+ /// Helper to hash a string for ID generation
50
+ fn hash_string(s: &str) -> String {
51
+ let mut hasher = std::collections::hash_map::DefaultHasher::new();
52
+ s.hash(&mut hasher);
53
+ format!("{:x}", hasher.finish())
54
+ }
55
+
56
+ /// Shared API state wrapping the app state with metrics
57
+ pub struct ApiState {
58
+ pub app: Arc<AppState>,
59
+ pub metrics: Metrics,
60
+ }
61
+
62
+ /// Query parameters for search endpoint
63
+ #[derive(Debug, Deserialize)]
64
+ pub struct SearchParams {
65
+ pub q: String,
66
+ #[serde(default = "default_limit")]
67
+ pub limit: usize,
68
+ #[serde(default = "default_offset")]
69
+ pub offset: usize,
70
+ pub filter: Option<String>,
71
+ pub category: Option<String>,
72
+ pub media_type: Option<String>,
73
+ pub semantic_ratio: Option<f32>,
74
+ }
75
+
76
+ fn default_limit() -> usize {
77
+ 15
78
+ }
79
+ fn default_offset() -> usize {
80
+ 0
81
+ }
82
+
83
+ /// Search result item
84
+ #[derive(Debug, Serialize, Deserialize, Clone)]
85
+ pub struct SearchResult {
86
+ pub id: String,
87
+ pub title: String,
88
+ pub url: String,
89
+ pub description: Option<String>,
90
+ pub category: String,
91
+ pub source: String,
92
+ pub media_type: String,
93
+ pub thumbnail_url: Option<String>,
94
+ pub intent_score: f32,
95
+ pub relevance_score: f32,
96
+ pub commercial_score: f32,
97
+ pub spam_score: f32,
98
+ }
99
+
100
+ /// Search response
101
+ #[derive(Debug, Serialize, Deserialize)]
102
+ pub struct SearchResponse {
103
+ pub query: String,
104
+ pub results: Vec<SearchResult>,
105
+ pub total: usize,
106
+ pub latency_ms: u64,
107
+ #[serde(skip_serializing_if = "Option::is_none")]
108
+ #[serde(default)]
109
+ pub message: Option<String>,
110
+ #[serde(skip_serializing_if = "Vec::is_empty")]
111
+ #[serde(default)]
112
+ pub intent_scores: Vec<crate::intent_classifier::GroupScore>,
113
+ #[serde(default)]
114
+ pub self_improving: bool,
115
+ }
116
+
117
+ /// Query parameters for news/images/videos endpoints
118
+ #[derive(Debug, Deserialize)]
119
+ pub struct MediaSearchParams {
120
+ pub q: String,
121
+ #[serde(default = "default_limit")]
122
+ pub limit: usize,
123
+ pub category: Option<String>,
124
+ pub location: Option<String>,
125
+ }
126
+
127
+ /// News result item
128
+ #[derive(Debug, Serialize, Clone)]
129
+ pub struct NewsResult {
130
+ pub title: String,
131
+ pub url: String,
132
+ pub description: String,
133
+ pub source: String,
134
+ pub published_at: Option<String>,
135
+ #[serde(skip_serializing_if = "Option::is_none")]
136
+ pub thumbnail_url: Option<String>,
137
+ }
138
+
139
+ /// News search response
140
+ #[derive(Debug, Serialize)]
141
+ pub struct NewsResponse {
142
+ pub query: String,
143
+ pub results: Vec<NewsResult>,
144
+ pub total: usize,
145
+ pub latency_ms: u64,
146
+ pub sources: Vec<String>,
147
+ }
148
+
149
+ /// Image result item
150
+ #[derive(Debug, Serialize, Clone)]
151
+ pub struct ImageResult {
152
+ pub id: String,
153
+ pub title: String,
154
+ pub url: String,
155
+ pub source: String,
156
+ pub category: String,
157
+ pub intent_score: f32,
158
+ pub relevance_score: f32,
159
+ #[serde(skip_serializing_if = "Option::is_none")]
160
+ pub thumbnail_url: Option<String>,
161
+ #[serde(skip_serializing_if = "Option::is_none")]
162
+ pub alt_text: Option<String>,
163
+ #[serde(skip_serializing_if = "Option::is_none")]
164
+ pub photographer: Option<String>,
165
+ pub width: Option<u32>,
166
+ pub height: Option<u32>,
167
+ pub avg_color: Option<String>,
168
+ }
169
+
170
+ /// Image search response
171
+ #[derive(Debug, Serialize)]
172
+ pub struct ImageResponse {
173
+ pub query: String,
174
+ pub results: Vec<ImageResult>,
175
+ pub total: usize,
176
+ pub latency_ms: u64,
177
+ pub sources: Vec<String>,
178
+ }
179
+
180
+ /// Video result item
181
+ #[derive(Debug, Serialize, Clone)]
182
+ pub struct VideoResult {
183
+ pub id: String,
184
+ pub title: String,
185
+ pub url: String,
186
+ pub source: String,
187
+ pub description: Option<String>,
188
+ pub intent_score: f32,
189
+ pub relevance_score: f32,
190
+ #[serde(skip_serializing_if = "Option::is_none")]
191
+ pub thumbnail_url: Option<String>,
192
+ pub duration_secs: Option<u32>,
193
+ pub view_count: Option<u64>,
194
+ pub channel: Option<String>,
195
+ pub published_at: Option<String>,
196
+ }
197
+
198
+ /// Video search response
199
+ #[derive(Debug, Serialize)]
200
+ pub struct VideoResponse {
201
+ pub query: String,
202
+ pub results: Vec<VideoResult>,
203
+ pub total: usize,
204
+ pub latency_ms: u64,
205
+ pub sources: Vec<String>,
206
+ }
207
+
208
+ /// Crawl parameters
209
+ #[derive(Debug, Deserialize)]
210
+ pub struct CrawlParams {
211
+ pub url: String,
212
+ }
213
+
214
+ /// Crawl response
215
+ #[derive(Debug, Serialize)]
216
+ pub struct CrawlResponse {
217
+ pub url: String,
218
+ pub title: String,
219
+ pub content_length: usize,
220
+ pub success: bool,
221
+ pub latency_ms: u64,
222
+ pub error: Option<String>,
223
+ }
224
+
225
+ /// Batch crawl request
226
+ #[derive(Debug, Deserialize)]
227
+ pub struct BatchCrawlRequest {
228
+ pub urls: Vec<String>,
229
+ }
230
+
231
+ /// Discovery enqueue request
232
+ #[derive(Debug, Deserialize)]
233
+ pub struct DiscoveryEnqueueRequest {
234
+ pub url: String,
235
+ #[serde(default)]
236
+ pub category: Option<String>,
237
+ #[serde(default = "default_priority")]
238
+ pub priority: u32,
239
+ }
240
+
241
+ fn default_priority() -> u32 {
242
+ 5
243
+ }
244
+
245
+ /// Discovery enqueue response
246
+ #[derive(Debug, Serialize)]
247
+ pub struct DiscoveryEnqueueResponse {
248
+ pub url: String,
249
+ pub enqueued: bool,
250
+ pub error: Option<String>,
251
+ }
252
+
253
+ async fn auth_middleware(
254
+ State(state): State<Arc<ApiState>>,
255
+ headers: HeaderMap,
256
+ request: Request,
257
+ next: Next,
258
+ ) -> Response {
259
+ // If no API key is configured, allow all requests (for dev/local)
260
+ let expected_key = match &state.app.config.api_key {
261
+ Some(k) if !k.is_empty() => k,
262
+ _ => return next.run(request).await,
263
+ };
264
+
265
+ let api_key = headers.get("X-API-Key").and_then(|h| h.to_str().ok());
266
+
267
+ match api_key {
268
+ Some(key) if key == expected_key => next.run(request).await,
269
+ _ => {
270
+ tracing::warn!("Unauthorized access attempt from {:?}", request.uri());
271
+ (
272
+ StatusCode::UNAUTHORIZED,
273
+ Json(serde_json::json!({ "error": "Unauthorized" })),
274
+ )
275
+ .into_response()
276
+ }
277
+ }
278
+ }
279
+
280
+ /// Initialize the API router
281
+ pub fn create_router(state: Arc<ApiState>) -> Router {
282
+ let public_routes = Router::new()
283
+ .route("/health", get(health_handler))
284
+ .route("/metrics", get(metrics_handler));
285
+
286
+ let protected_routes = Router::new()
287
+ .route("/search", get(search_handler))
288
+ .route("/meta", get(meta_search_handler))
289
+ .route("/news", get(news_handler))
290
+ .route("/images", get(images_handler))
291
+ .route("/videos", get(videos_handler))
292
+ .route("/crawl", get(crawl_single_handler))
293
+ .route("/crawl/batch", post(crawl_batch_handler))
294
+ .route("/content/:id", get(get_full_content_handler))
295
+ .route("/discovery/status", get(discovery_status_handler))
296
+ .route("/discovery/enqueue", post(discovery_enqueue_handler))
297
+ .route("/admin/reindex-scores", post(reindex_scores_handler))
298
+ .layer(middleware::from_fn_with_state(
299
+ state.clone(),
300
+ auth_middleware,
301
+ ));
302
+
303
+ Router::new()
304
+ .merge(public_routes)
305
+ .merge(protected_routes)
306
+ .with_state(state)
307
+ }
308
+
309
+ /// Health check endpoint
310
+ async fn health_handler() -> impl IntoResponse {
311
+ (StatusCode::OK, Json(serde_json::json!({"status": "ok"})))
312
+ }
313
+
314
+ /// Validate filter string to prevent injection attacks
315
+ fn validate_filter(filter: &str) -> Result<(), (StatusCode, String)> {
316
+ if filter.contains('\0') {
317
+ return Err((
318
+ StatusCode::BAD_REQUEST,
319
+ "Invalid filter: contains null bytes".to_string(),
320
+ ));
321
+ }
322
+ let dangerous_patterns = [
323
+ "DROP TABLE",
324
+ "DELETE FROM",
325
+ "UPDATE SET",
326
+ "INSERT INTO",
327
+ "ALTER TABLE",
328
+ "CREATE TABLE",
329
+ "EXEC ",
330
+ "--",
331
+ ];
332
+ let upper_filter = filter.to_uppercase();
333
+ for pattern in dangerous_patterns {
334
+ if upper_filter.contains(pattern) {
335
+ return Err((
336
+ StatusCode::BAD_REQUEST,
337
+ "Invalid filter: contains dangerous pattern".to_string(),
338
+ ));
339
+ }
340
+ }
341
+ Ok(())
342
+ }
343
+
344
+ /// Query expansion and rewriting
345
+ fn rewrite_query(
346
+ query: &str,
347
+ config: &crate::query_expansion::QueryExpansionConfig,
348
+ ) -> (String, Vec<String>) {
349
+ let expansion = crate::query_expansion::expand_query(query, config);
350
+ let mut auto_filters = Vec::new();
351
+ let lower = query.to_lowercase();
352
+ if !(lower.contains("buy") || lower.contains("price") || lower.contains("discount")) {
353
+ auto_filters.push("commercial_score < 0.7".to_string());
354
+ }
355
+ auto_filters.push("spam_score < 0.5".to_string());
356
+ (expansion.expanded, auto_filters)
357
+ }
358
+
359
+ /// Search endpoint - hybrid semantic + keyword search
360
+ async fn search_handler(
361
+ State(state): State<Arc<ApiState>>,
362
+ Query(params): Query<SearchParams>,
363
+ ) -> impl IntoResponse {
364
+ let start = Instant::now();
365
+ state.metrics.search_requests_total.inc();
366
+
367
+ // Validate empty query
368
+ if params.q.trim().is_empty() {
369
+ return (
370
+ StatusCode::BAD_REQUEST,
371
+ Json(SearchResponse {
372
+ query: params.q.clone(),
373
+ total: 0,
374
+ results: vec![],
375
+ latency_ms: start.elapsed().as_millis() as u64,
376
+ message: Some("Query cannot be empty".to_string()),
377
+ intent_scores: vec![],
378
+ self_improving: false,
379
+ }),
380
+ )
381
+ .into_response();
382
+ }
383
+
384
+ // Check response cache (only quality responses are cached)
385
+ let cache_key = format!("search_cache:{}", params.q.to_lowercase().trim());
386
+ if let Ok(Some(cached)) = state.app.redis.get_json::<SearchResponse>(&cache_key).await {
387
+ tracing::info!(
388
+ "Cache HIT for '{}' ({} results)",
389
+ params.q,
390
+ cached.results.len()
391
+ );
392
+ return (StatusCode::OK, Json(cached)).into_response();
393
+ }
394
+
395
+ let (expanded_query, auto_filters) =
396
+ rewrite_query(&params.q, &state.app.query_expansion_config);
397
+
398
+ let mut filter_parts = Vec::new();
399
+ if let Some(f) = &params.filter {
400
+ if let Err((status, msg)) = validate_filter(f) {
401
+ return (
402
+ status,
403
+ Json(SearchResponse {
404
+ query: params.q.clone(),
405
+ total: 0,
406
+ results: vec![],
407
+ latency_ms: start.elapsed().as_millis() as u64,
408
+ message: Some(msg),
409
+ intent_scores: vec![],
410
+ self_improving: false,
411
+ }),
412
+ )
413
+ .into_response();
414
+ }
415
+ filter_parts.push(format!("({})", f));
416
+ }
417
+ for af in auto_filters {
418
+ filter_parts.push(af);
419
+ }
420
+ if let Some(category) = &params.category {
421
+ filter_parts.push(format!("category = \"{}\"", category));
422
+ }
423
+ if let Some(media_type) = &params.media_type {
424
+ filter_parts.push(format!("media_type = \"{}\"", media_type));
425
+ }
426
+
427
+ let final_filter = if filter_parts.is_empty() {
428
+ if params.media_type.is_none() {
429
+ Some("media_type = \"text\"".to_string())
430
+ } else {
431
+ None
432
+ }
433
+ } else {
434
+ Some(filter_parts.join(" AND "))
435
+ };
436
+
437
+ let _semantic_ratio = params
438
+ .semantic_ratio
439
+ .unwrap_or(state.app.config.meilisearch.semantic_ratio);
440
+
441
+ // --- DYNAMIC INTENT CLASSIFICATION (no hardcoded keywords) ---
442
+ let intent_scores = state
443
+ .app
444
+ .intent_classifier
445
+ .classify_with_scores(&params.q, None);
446
+ let primary_intent = intent_scores.first().map(|g| g.primary_intent.clone());
447
+ let primary_intent_score = intent_scores.first().map(|g| g.score).unwrap_or(0.0);
448
+ let primary = primary_intent
449
+ .clone()
450
+ .unwrap_or(crate::intent_classifier::QueryIntent::General);
451
+
452
+ // Extract query keywords for term matching
453
+ let query_terms: Vec<String> = params
454
+ .q
455
+ .to_lowercase()
456
+ .split_whitespace()
457
+ .filter(|w| w.len() > 2)
458
+ .map(|w| w.to_string())
459
+ .collect();
460
+
461
+ // Stop words that don't carry query-specific meaning
462
+ let stop_words: HashSet<&str> = [
463
+ "the", "and", "for", "with", "from", "that", "this", "what", "how", "are", "was", "were",
464
+ "been", "being", "have", "has", "had", "does", "did", "will", "would", "could", "should",
465
+ "may", "might", "can", "not", "but", "yet", "also", "just", "than", "then", "too", "very",
466
+ "best", "top", "most", "more", "about", "into", "some", "any", "all", "who", "which",
467
+ "when", "where", "why", "use", "using", "used",
468
+ ]
469
+ .iter()
470
+ .copied()
471
+ .collect();
472
+
473
+ // Significant terms: content-bearing words that discriminate this query
474
+ let significant_terms: Vec<&String> = query_terms
475
+ .iter()
476
+ .filter(|t| !stop_words.contains(t.as_str()))
477
+ .collect();
478
+ let has_significant_terms = !significant_terms.is_empty();
479
+
480
+ // Known compound terms that should be matched as phrases
481
+ let compound_terms: Vec<(&str, &str)> = vec![
482
+ ("machine", "learning"),
483
+ ("deep", "learning"),
484
+ ("reinforcement", "learning"),
485
+ ("neural", "network"),
486
+ ("natural", "language"),
487
+ ("computer", "vision"),
488
+ ("data", "science"),
489
+ ("cloud", "computing"),
490
+ ("web", "development"),
491
+ ("async", "programming"),
492
+ ("binary", "search"),
493
+ ("linked", "list"),
494
+ ("hash", "table"),
495
+ ("red", "black"),
496
+ ("dynamic", "programming"),
497
+ ("zero", "knowledge"),
498
+ ("state", "locking"),
499
+ ("full", "text"),
500
+ ("black", "pine"),
501
+ ("reward", "shaping"),
502
+ ("cold", "ferment"),
503
+ ("pressure", "profiling"),
504
+ ("pod", "affinity"),
505
+ ("helm", "chart"),
506
+ ("near", "duplicate"),
507
+ ("sourdough", "starter"),
508
+ ("knife", "sharpening"),
509
+ ("espresso", "machine"),
510
+ ("ground", "plane"),
511
+ ];
512
+
513
+ let mut phrase_terms: Vec<String> = Vec::new();
514
+ let sig_words: Vec<&str> = query_terms.iter().map(|s| s.as_str()).collect();
515
+ for window in sig_words.windows(2) {
516
+ let pair = (window[0], window[1]);
517
+ if compound_terms
518
+ .iter()
519
+ .any(|&(a, b)| a == pair.0 && b == pair.1)
520
+ {
521
+ phrase_terms.push(format!("{} {}", pair.0, pair.1));
522
+ }
523
+ }
524
+
525
+ // Effective sig count: each phrase replaces 2 individual terms with 1 phrase unit
526
+ let effective_sig_count = significant_terms.len().saturating_sub(phrase_terms.len());
527
+ let min_sig_required = if effective_sig_count <= 1 {
528
+ 1
529
+ } else if effective_sig_count == 2 {
530
+ 2
531
+ } else {
532
+ effective_sig_count.div_ceil(2)
533
+ };
534
+
535
+ // PHASE 1: Fast local index search (<1 second target)
536
+ let q_local = expanded_query.clone();
537
+ let filter_local = final_filter.clone();
538
+ let local_res = state
539
+ .app
540
+ .indexer
541
+ .search(&q_local, filter_local.as_deref(), Some(50))
542
+ .await
543
+ .unwrap_or_default();
544
+
545
+ // Pre-filter obvious garbage
546
+ let valid_docs: Vec<_> = local_res
547
+ .iter()
548
+ .filter(|doc| {
549
+ let title_low = doc.title.to_lowercase();
550
+ !(title_low.contains("just a moment")
551
+ || title_low.contains("cloudflare")
552
+ || doc.title.trim().is_empty())
553
+ })
554
+ .collect();
555
+
556
+ // Batch alignment boost for all valid documents
557
+ let combined_texts: Vec<String> = valid_docs
558
+ .iter()
559
+ .map(|doc| {
560
+ let title_low = doc.title.to_lowercase();
561
+ let desc_low = doc.description.as_deref().unwrap_or("").to_lowercase();
562
+ format!("{} {}", title_low, desc_low)
563
+ })
564
+ .collect();
565
+ let combined_refs: Vec<&str> = combined_texts.iter().map(|s| s.as_str()).collect();
566
+ let alignments = if primary == crate::intent_classifier::QueryIntent::General {
567
+ vec![1.0; combined_refs.len()]
568
+ } else {
569
+ state
570
+ .app
571
+ .intent_classifier
572
+ .calculate_alignment_boost_batch(&primary, &combined_refs)
573
+ };
574
+
575
+ let mut local_results: Vec<SearchResult> = Vec::new();
576
+ let mut local_urls = HashSet::new();
577
+
578
+ for (idx, doc) in valid_docs.iter().enumerate() {
579
+ let combined = &combined_texts[idx];
580
+ let alignment = alignments[idx];
581
+
582
+ if alignment < 0.2 {
583
+ continue;
584
+ }
585
+
586
+ // Significant term overlap (phrase-aware)
587
+ let sig_hits = count_phrase_aware_hits(combined, &phrase_terms, &significant_terms);
588
+
589
+ // Require minimum significant term coverage to pass
590
+ if has_significant_terms && sig_hits < min_sig_required {
591
+ continue;
592
+ }
593
+
594
+ // Score based on significant term coverage + alignment
595
+ let term_relevance = if !has_significant_terms {
596
+ 0.5
597
+ } else {
598
+ sig_hits as f32 / significant_terms.len() as f32
599
+ };
600
+ let alignment_norm = (alignment / 1.2).min(1.0);
601
+ let computed_intent = (term_relevance * 0.7 + alignment_norm * 0.3).clamp(0.0, 1.0);
602
+ let intent_score = computed_intent.max(doc.intent_score * 0.7);
603
+
604
+ if !local_urls.contains(&doc.url) {
605
+ local_results.push(SearchResult {
606
+ id: doc.id.clone(),
607
+ title: doc.title.clone(),
608
+ url: doc.url.clone(),
609
+ description: doc.description.clone(),
610
+ category: doc.category.clone(),
611
+ source: doc.source.clone(),
612
+ media_type: doc.media_type.clone(),
613
+ thumbnail_url: doc.thumbnail_url.clone(),
614
+ intent_score,
615
+ relevance_score: doc.relevance_score,
616
+ commercial_score: doc.commercial_score,
617
+ spam_score: doc.spam_score,
618
+ });
619
+ local_urls.insert(doc.url.clone());
620
+ }
621
+ }
622
+
623
+ // Sort local results: intent-first, then relevance
624
+ local_results.sort_by(|a, b| {
625
+ let a_priority = a.intent_score * 0.6 + a.relevance_score * 0.4;
626
+ let b_priority = b.intent_score * 0.6 + b.relevance_score * 0.4;
627
+ b_priority
628
+ .partial_cmp(&a_priority)
629
+ .unwrap_or(std::cmp::Ordering::Equal)
630
+ });
631
+
632
+ let local_elapsed = start.elapsed().as_millis() as u64;
633
+
634
+ // Check if we already have 15+ high-quality, intent-matching results
635
+ let target_count = 15;
636
+ let quality_threshold = 0.35;
637
+ let high_quality_local: Vec<&SearchResult> = local_results
638
+ .iter()
639
+ .filter(|r| {
640
+ r.relevance_score >= quality_threshold && r.intent_score >= 0.35 && r.spam_score < 0.3
641
+ })
642
+ .collect();
643
+
644
+ let needs_improvement = local_results.len() < target_count
645
+ || high_quality_local.len() < target_count
646
+ || primary_intent_score < 0.3;
647
+
648
+ tracing::info!(
649
+ "Search quality: local={}, high_quality={}, intent={:.2}, needs_improve={}",
650
+ local_results.len(),
651
+ high_quality_local.len(),
652
+ primary_intent_score,
653
+ needs_improvement
654
+ );
655
+
656
+ // PHASE 2: Lightweight synchronous meta-search when local results are insufficient
657
+ let mut meta_count = 0usize;
658
+ if needs_improvement && local_elapsed < 1500 {
659
+ let meta_timeout = std::time::Duration::from_millis(2000);
660
+ if let Ok(meta_resp) = tokio::time::timeout(
661
+ meta_timeout,
662
+ state
663
+ .app
664
+ .aggregator
665
+ .search_with_intent(&params.q, Some(&primary)),
666
+ )
667
+ .await
668
+ {
669
+ for r in &meta_resp.results {
670
+ if local_urls.contains(&r.url) {
671
+ continue;
672
+ }
673
+ if params.media_type.is_none() && r.media_type != "text" {
674
+ continue;
675
+ }
676
+
677
+ let combined = format!(
678
+ "{} {}",
679
+ r.title.to_lowercase(),
680
+ r.description.to_lowercase()
681
+ );
682
+
683
+ let alignment = state
684
+ .app
685
+ .intent_classifier
686
+ .calculate_alignment_boost(&primary, &combined);
687
+ if alignment < 0.2 {
688
+ continue;
689
+ }
690
+
691
+ if has_significant_terms {
692
+ let meta_sig_hits =
693
+ count_phrase_aware_hits(&combined, &phrase_terms, &significant_terms);
694
+ if meta_sig_hits < 1 {
695
+ continue;
696
+ }
697
+ }
698
+
699
+ let alignment_norm = (alignment / 1.2).min(1.0);
700
+ let rrf_contribution = (r.score * 10.0).min(0.3);
701
+ let intent_score = (alignment_norm * 0.5 + rrf_contribution + 0.2).clamp(0.0, 1.0);
702
+
703
+ let doc_text = format!("{} {}", r.title, r.description);
704
+ let cat_intent = state.app.intent_classifier.get_intent_for_text(&doc_text);
705
+
706
+ local_results.push(SearchResult {
707
+ id: hash_string(&r.url),
708
+ title: r.title.clone(),
709
+ url: r.url.clone(),
710
+ description: Some(r.description.clone()),
711
+ category: format!("{:?}", cat_intent),
712
+ source: r.source.clone(),
713
+ media_type: r.media_type.clone(),
714
+ thumbnail_url: r.thumbnail_url.clone(),
715
+ intent_score,
716
+ relevance_score: intent_score,
717
+ commercial_score: 0.0,
718
+ spam_score: 0.0,
719
+ });
720
+ local_urls.insert(r.url.clone());
721
+ meta_count += 1;
722
+ }
723
+ }
724
+
725
+ if meta_count > 0 {
726
+ local_results.sort_by(|a, b| {
727
+ let a_priority = a.intent_score * 0.6 + a.relevance_score * 0.4;
728
+ let b_priority = b.intent_score * 0.6 + b.relevance_score * 0.4;
729
+ b_priority
730
+ .partial_cmp(&a_priority)
731
+ .unwrap_or(std::cmp::Ordering::Equal)
732
+ });
733
+ }
734
+ }
735
+
736
+ let self_improving_flag = needs_improvement && meta_count < 5;
737
+
738
+ // Apply pagination to merged results
739
+ let local_count = local_results.len();
740
+ let paginated_results: Vec<SearchResult> = local_results
741
+ .into_iter()
742
+ .skip(params.offset)
743
+ .take(params.limit)
744
+ .collect();
745
+
746
+ let quality_count = paginated_results
747
+ .iter()
748
+ .filter(|r| r.intent_score >= 0.35 && r.relevance_score >= 0.35 && r.spam_score < 0.3)
749
+ .count();
750
+ let is_quality_response = quality_count >= 5 && paginated_results.len() >= target_count;
751
+
752
+ let message = if meta_count > 0 {
753
+ Some(format!(
754
+ "Local {} + meta {} in {}ms ({} quality)",
755
+ local_count - meta_count,
756
+ meta_count,
757
+ start.elapsed().as_millis(),
758
+ quality_count
759
+ ))
760
+ } else if self_improving_flag {
761
+ Some(format!(
762
+ "Found {} results ({}ms), {} quality. Improving in background — retry in ~30-60s for better results.",
763
+ paginated_results.len(), local_elapsed, quality_count
764
+ ))
765
+ } else {
766
+ Some(format!(
767
+ "Local index: {} results in {}ms ({} quality)",
768
+ local_count, local_elapsed, quality_count
769
+ ))
770
+ };
771
+
772
+ let query_owned = params.q.clone();
773
+
774
+ let response = SearchResponse {
775
+ query: params.q,
776
+ total: paginated_results.len(),
777
+ results: paginated_results,
778
+ latency_ms: start.elapsed().as_millis() as u64,
779
+ message,
780
+ intent_scores,
781
+ self_improving: self_improving_flag,
782
+ };
783
+
784
+ // Cache quality responses
785
+ if is_quality_response {
786
+ let _ = state.app.redis.set_json(&cache_key, &response, 300).await;
787
+ tracing::info!(
788
+ "Cached quality response for '{}' ({} quality, {} total)",
789
+ query_owned,
790
+ quality_count,
791
+ response.results.len()
792
+ );
793
+ }
794
+
795
+ // Spawn background self-improvement when quality is insufficient (3-min budget)
796
+ if self_improving_flag {
797
+ let lock_key = format!("self_imp:active:{}", query_owned.to_lowercase().trim());
798
+
799
+ // Acquire distributed lock via SETNX to prevent duplicate tasks
800
+ let lock_acquired = if let Ok(mut conn) = state.app.redis.get_connection().await {
801
+ let acquired: bool = redis::cmd("SETNX")
802
+ .arg(&lock_key)
803
+ .arg("1")
804
+ .query_async(&mut conn)
805
+ .await
806
+ .unwrap_or(true);
807
+ if acquired {
808
+ let _: Result<(), _> = redis::cmd("EXPIRE")
809
+ .arg(&lock_key)
810
+ .arg(180i64)
811
+ .query_async(&mut conn)
812
+ .await;
813
+ }
814
+ acquired
815
+ } else {
816
+ true
817
+ };
818
+
819
+ if lock_acquired {
820
+ let imp_state = state.clone();
821
+ let imp_query = query_owned.clone();
822
+ let imp_intent = primary.clone();
823
+ let imp_sig_terms: Vec<String> =
824
+ significant_terms.iter().map(|s| s.to_string()).collect();
825
+ let imp_phrase_terms: Vec<String> = phrase_terms.clone();
826
+ let imp_min_sig = min_sig_required;
827
+ let imp_query_terms = query_terms.clone();
828
+ let imp_cache_key = cache_key.clone();
829
+ let imp_lock_key = lock_key;
830
+ let imp_expanded_query = expanded_query.clone();
831
+
832
+ tokio::spawn(async move {
833
+ let task_start = Instant::now();
834
+ let budget = std::time::Duration::from_secs(300); // 5 minutes
835
+ let target = 15usize;
836
+ let max_rounds = 10;
837
+ let mut quality_indexed = 0usize;
838
+ let mut seen_urls: HashSet<String> = HashSet::new();
839
+
840
+ // Generate query variations for multi-round search
841
+ let mut variations = imp_state
842
+ .app
843
+ .intent_classifier
844
+ .generate_variations(&imp_query, &imp_intent);
845
+ if !variations.contains(&imp_query) {
846
+ variations.insert(0, imp_query.clone());
847
+ }
848
+ variations.push(imp_query_terms.join(" "));
849
+ // Add more aggressive variations for persistent discovery
850
+ variations.push(format!("{} tutorial examples", imp_query));
851
+ variations.push(format!("{} complete guide walkthrough", imp_query));
852
+ variations.push(format!("{} best practices tips", imp_query));
853
+ variations.push(format!("{} advanced techniques", imp_query));
854
+ variations.push(format!("{} how to step by step", imp_query));
855
+
856
+ tracing::info!(
857
+ "Background self-improvement started for '{}' (target: {}, max rounds: {}, budget: 300s, variations: {})",
858
+ imp_query, target, max_rounds, variations.len()
859
+ );
860
+
861
+ // Embed query once for intent scoring
862
+ let query_embedding = match imp_state
863
+ .app
864
+ .embedding_model
865
+ .embed_batch(std::slice::from_ref(&imp_query))
866
+ {
867
+ Ok(embs) => embs.into_iter().next().unwrap_or_default(),
868
+ Err(_) => imp_state
869
+ .app
870
+ .embedding_model
871
+ .embed_fallback(std::slice::from_ref(&imp_query))
872
+ .into_iter()
873
+ .next()
874
+ .unwrap_or_default(),
875
+ };
876
+
877
+ let mut round = 0;
878
+ let mut consecutive_empty = 0;
879
+ loop {
880
+ // Hard stop conditions
881
+ if quality_indexed >= target
882
+ || task_start.elapsed() >= budget
883
+ || round >= max_rounds
884
+ {
885
+ break;
886
+ }
887
+
888
+ // Stop if we've had too many consecutive empty rounds (no new URLs found)
889
+ if consecutive_empty >= 5 {
890
+ tracing::info!(
891
+ "Background self-improvement stopping for '{}': {} consecutive empty rounds, quality={}/{} (partial)",
892
+ imp_query, consecutive_empty, quality_indexed, target
893
+ );
894
+ break;
895
+ }
896
+
897
+ let search_query = &variations[round % variations.len()];
898
+ let remaining = budget.saturating_sub(task_start.elapsed());
899
+ if remaining < std::time::Duration::from_secs(10) {
900
+ break;
901
+ }
902
+
903
+ tracing::info!(
904
+ "Self-improvement round {}/{} for '{}': query='{}', quality={}/{}, elapsed={}s",
905
+ round + 1, max_rounds, imp_query, search_query, quality_indexed, target,
906
+ task_start.elapsed().as_secs()
907
+ );
908
+
909
+ // Meta search with per-round timeout (intent-aware weighted RRF)
910
+ let meta_res = tokio::time::timeout(
911
+ std::time::Duration::from_secs(10),
912
+ imp_state
913
+ .app
914
+ .aggregator
915
+ .search_with_intent(search_query, Some(&imp_intent)),
916
+ )
917
+ .await;
918
+
919
+ let meta_resp = match meta_res {
920
+ Ok(resp) => resp,
921
+ Err(_) => {
922
+ tracing::warn!(
923
+ "Self-improvement: meta search timed out round {}",
924
+ round + 1
925
+ );
926
+ round += 1;
927
+ consecutive_empty += 1;
928
+ tokio::time::sleep(std::time::Duration::from_secs(1)).await;
929
+ continue;
930
+ }
931
+ };
932
+
933
+ if meta_resp.results.is_empty() {
934
+ consecutive_empty += 1;
935
+ tracing::debug!(
936
+ "Self-improvement round {}: meta returned 0 results, consecutive_empty={}",
937
+ round + 1, consecutive_empty
938
+ );
939
+ round += 1;
940
+ tokio::time::sleep(std::time::Duration::from_secs(1)).await;
941
+ continue;
942
+ }
943
+
944
+ // Collect ALL unseen URLs with their scores for relative ranking
945
+ let mut scored_candidates: Vec<(
946
+ &crate::meta_search::models::SearchResult,
947
+ f32,
948
+ )> = Vec::new();
949
+ for r in &meta_resp.results {
950
+ if seen_urls.contains(&r.url) {
951
+ continue;
952
+ }
953
+ seen_urls.insert(r.url.clone());
954
+
955
+ let combined = format!(
956
+ "{} {}",
957
+ r.title.to_lowercase(),
958
+ r.description.to_lowercase()
959
+ );
960
+ let alignment = imp_state
961
+ .app
962
+ .intent_classifier
963
+ .calculate_alignment_boost(&imp_intent, &combined);
964
+ if alignment < 0.2 {
965
+ continue;
966
+ } // Relaxed alignment threshold
967
+
968
+ // Score = RRF score * 0.4 + alignment * 0.3 + source weight * 0.3
969
+ let source_weight = match r.source.as_str() {
970
+ "searxng" => 1.0,
971
+ "arxiv" | "github" => 0.9,
972
+ "reddit" => 0.8,
973
+ "duckduckgo" => 0.7,
974
+ _ => 0.5,
975
+ };
976
+ let combined_score = r.score * 0.4 + alignment * 0.3 + source_weight * 0.3;
977
+ scored_candidates.push((r, combined_score));
978
+ }
979
+
980
+ if scored_candidates.is_empty() {
981
+ consecutive_empty += 1;
982
+ tracing::debug!(
983
+ "Self-improvement round {}: all {} results already seen or filtered, consecutive_empty={}",
984
+ round + 1, meta_resp.results.len(), consecutive_empty
985
+ );
986
+ round += 1;
987
+ tokio::time::sleep(std::time::Duration::from_secs(1)).await;
988
+ continue;
989
+ }
990
+
991
+ // Reset consecutive empty counter since we found new candidates
992
+ consecutive_empty = 0;
993
+
994
+ // Sort by combined score and take top candidates (relative ranking)
995
+ scored_candidates
996
+ .sort_by(|a, b| b.1.partial_cmp(&a.1).unwrap_or(std::cmp::Ordering::Equal));
997
+ let take_count = std::cmp::min(10, scored_candidates.len());
998
+ let top_candidates: Vec<_> = scored_candidates
999
+ .into_iter()
1000
+ .take(take_count)
1001
+ .map(|(r, _)| r)
1002
+ .collect();
1003
+
1004
+ tracing::info!(
1005
+ "Self-improvement round {}: selected {}/{} candidates (top by relative score, best={:.3})",
1006
+ round + 1, take_count, meta_resp.results.len(),
1007
+ top_candidates.first().map(|r| r.score).unwrap_or(0.0)
1008
+ );
1009
+
1010
+ // Crawl candidates
1011
+ let urls: Vec<&str> = top_candidates.iter().map(|r| r.url.as_str()).collect();
1012
+ let crawl_results = match imp_state.app.crawler.fetch_batch(urls).await {
1013
+ Ok(r) => r,
1014
+ Err(e) => {
1015
+ tracing::warn!(
1016
+ "Self-improvement: crawl failed round {}: {}",
1017
+ round + 1,
1018
+ e
1019
+ );
1020
+ round += 1;
1021
+ tokio::time::sleep(std::time::Duration::from_secs(1)).await;
1022
+ continue;
1023
+ }
1024
+ };
1025
+
1026
+ // Embed, score, and index each document
1027
+ for (idx, crawl_result) in crawl_results.iter().enumerate() {
1028
+ if quality_indexed >= target {
1029
+ break;
1030
+ }
1031
+
1032
+ let ext = top_candidates.get(idx);
1033
+ let source = ext.map(|r| r.source.as_str()).unwrap_or("self_improvement");
1034
+ let rrf_score = ext.map(|r| r.score).unwrap_or(0.0);
1035
+
1036
+ let text = format!("{} {}", crawl_result.title, crawl_result.content);
1037
+ let embedding = match imp_state
1038
+ .app
1039
+ .embedding_model
1040
+ .embed_batch(std::slice::from_ref(&text))
1041
+ {
1042
+ Ok(embs) => embs.into_iter().next().unwrap_or_default(),
1043
+ Err(_) => imp_state
1044
+ .app
1045
+ .embedding_model
1046
+ .embed_fallback(std::slice::from_ref(&text))
1047
+ .into_iter()
1048
+ .next()
1049
+ .unwrap_or_default(),
1050
+ };
1051
+
1052
+ let intent_score =
1053
+ crate::utils::cosine_similarity(&query_embedding, &embedding)
1054
+ .clamp(0.0, 1.0);
1055
+ let quality_score = imp_state
1056
+ .app
1057
+ .embedding_model
1058
+ .calculate_quality_score(&text, &crawl_result.url);
1059
+ let relevance_score =
1060
+ (intent_score * 0.5 + quality_score * 0.3 + rrf_score.min(0.2))
1061
+ .clamp(0.1, 1.0);
1062
+
1063
+ // Relaxed intent threshold for partial improvements
1064
+ if intent_score < 0.25 {
1065
+ continue;
1066
+ }
1067
+
1068
+ // Dynamic category via intent classifier
1069
+ let content_snippet: String =
1070
+ crawl_result.content.chars().take(500).collect();
1071
+ let doc_text = format!("{} {}", crawl_result.title, content_snippet);
1072
+ let dynamic_cat = format!(
1073
+ "{:?}",
1074
+ imp_state
1075
+ .app
1076
+ .intent_classifier
1077
+ .get_intent_for_text(&doc_text)
1078
+ );
1079
+
1080
+ let safe_id = hash_string(&crawl_result.url);
1081
+ let _ = imp_state
1082
+ .app
1083
+ .indexer
1084
+ .get_redis()
1085
+ .store_content(&safe_id, &crawl_result.content)
1086
+ .await;
1087
+
1088
+ let doc = crate::indexer::IntentDocument::new(
1089
+ format!("ext-{}", safe_id),
1090
+ crawl_result.title.clone(),
1091
+ crawl_result.content.clone(),
1092
+ crawl_result.url.clone(),
1093
+ source.to_string(),
1094
+ dynamic_cat,
1095
+ intent_score,
1096
+ relevance_score,
1097
+ embedding,
1098
+ )
1099
+ .with_extra_scores(0.0, 0.0);
1100
+
1101
+ if let Err(e) = imp_state.app.indexer.index_document(&doc).await {
1102
+ tracing::warn!(
1103
+ "Self-improvement: failed to index {}: {}",
1104
+ crawl_result.url,
1105
+ e
1106
+ );
1107
+ } else {
1108
+ // Relaxed quality gate for partial improvements
1109
+ let is_quality = intent_score >= 0.3 && relevance_score >= 0.3;
1110
+ if is_quality {
1111
+ quality_indexed += 1;
1112
+ }
1113
+ tracing::info!(
1114
+ "Self-improvement indexed: intent={:.3} rel={:.3} quality={} [{}/{}] | {}",
1115
+ intent_score, relevance_score, is_quality,
1116
+ quality_indexed, target, doc.title
1117
+ );
1118
+ }
1119
+ }
1120
+
1121
+ round += 1;
1122
+
1123
+ // Add delay between rounds to avoid rate limiting
1124
+ tokio::time::sleep(std::time::Duration::from_secs(2)).await;
1125
+ }
1126
+
1127
+ // After indexing, re-run the search to see if quality improved
1128
+ if quality_indexed > 0 {
1129
+ tracing::info!(
1130
+ "Re-running search for '{}' after indexing {} quality docs",
1131
+ imp_query,
1132
+ quality_indexed
1133
+ );
1134
+
1135
+ let re_filter = Some(
1136
+ "media_type = \"text\" AND commercial_score < 0.7 AND spam_score < 0.5"
1137
+ .to_string(),
1138
+ );
1139
+ let re_local = imp_state
1140
+ .app
1141
+ .indexer
1142
+ .search(&imp_expanded_query, re_filter.as_deref(), Some(50))
1143
+ .await
1144
+ .unwrap_or_default();
1145
+
1146
+ let mut re_results: Vec<SearchResult> = Vec::new();
1147
+ let mut re_urls = HashSet::new();
1148
+
1149
+ for doc in &re_local {
1150
+ let title_low = doc.title.to_lowercase();
1151
+ let desc_low = doc.description.as_deref().unwrap_or("").to_lowercase();
1152
+ let combined = format!("{} {}", title_low, desc_low);
1153
+
1154
+ if title_low.contains("just a moment")
1155
+ || title_low.contains("cloudflare")
1156
+ || doc.title.trim().is_empty()
1157
+ {
1158
+ continue;
1159
+ }
1160
+
1161
+ let alignment = imp_state
1162
+ .app
1163
+ .intent_classifier
1164
+ .calculate_alignment_boost(&imp_intent, &combined);
1165
+ if alignment < 0.2 {
1166
+ continue;
1167
+ }
1168
+
1169
+ let sig_hits =
1170
+ count_phrase_aware_hits(&combined, &imp_phrase_terms, &imp_sig_terms);
1171
+ if !imp_sig_terms.is_empty() && sig_hits < imp_min_sig {
1172
+ continue;
1173
+ }
1174
+
1175
+ let term_relevance = if imp_sig_terms.is_empty() {
1176
+ 0.5
1177
+ } else {
1178
+ sig_hits as f32 / imp_sig_terms.len() as f32
1179
+ };
1180
+ let alignment_norm = (alignment / 1.2).min(1.0);
1181
+ let computed_intent =
1182
+ (term_relevance * 0.7 + alignment_norm * 0.3).clamp(0.0, 1.0);
1183
+ let intent_score = computed_intent.max(doc.intent_score * 0.7);
1184
+
1185
+ if !re_urls.contains(&doc.url) {
1186
+ re_results.push(SearchResult {
1187
+ id: doc.id.clone(),
1188
+ title: doc.title.clone(),
1189
+ url: doc.url.clone(),
1190
+ description: doc.description.clone(),
1191
+ category: doc.category.clone(),
1192
+ source: doc.source.clone(),
1193
+ media_type: doc.media_type.clone(),
1194
+ thumbnail_url: doc.thumbnail_url.clone(),
1195
+ intent_score,
1196
+ relevance_score: doc.relevance_score,
1197
+ commercial_score: doc.commercial_score,
1198
+ spam_score: doc.spam_score,
1199
+ });
1200
+ re_urls.insert(doc.url.clone());
1201
+ }
1202
+ }
1203
+
1204
+ re_results.sort_by(|a, b| {
1205
+ let a_p = a.intent_score * 0.6 + a.relevance_score * 0.4;
1206
+ let b_p = b.intent_score * 0.6 + b.relevance_score * 0.4;
1207
+ b_p.partial_cmp(&a_p).unwrap_or(std::cmp::Ordering::Equal)
1208
+ });
1209
+
1210
+ let re_final: Vec<SearchResult> = re_results
1211
+ .into_iter()
1212
+ .filter(|r| r.media_type == "text")
1213
+ .take(15)
1214
+ .collect();
1215
+
1216
+ let re_total = re_final.len();
1217
+ let re_quality = re_final
1218
+ .iter()
1219
+ .filter(|r| {
1220
+ r.intent_score >= 0.35
1221
+ && r.relevance_score >= 0.35
1222
+ && r.spam_score < 0.3
1223
+ })
1224
+ .count();
1225
+
1226
+ if re_quality >= 5 && re_total >= 15 {
1227
+ let cached_response = SearchResponse {
1228
+ query: imp_query.clone(),
1229
+ total: re_total,
1230
+ results: re_final,
1231
+ latency_ms: 0,
1232
+ message: Some(format!(
1233
+ "Self-improved: {} quality results indexed and cached",
1234
+ quality_indexed
1235
+ )),
1236
+ intent_scores: vec![],
1237
+ self_improving: false,
1238
+ };
1239
+ let _ = imp_state
1240
+ .app
1241
+ .redis
1242
+ .set_json(&imp_cache_key, &cached_response, 300)
1243
+ .await;
1244
+ tracing::info!(
1245
+ "Cached quality response for '{}' after self-improvement ({}/{} quality)",
1246
+ imp_query, re_quality, re_total
1247
+ );
1248
+ } else {
1249
+ // Not quality yet — clear any stale cache so next request re-evaluates
1250
+ if let Ok(mut conn) = imp_state.app.redis.get_connection().await {
1251
+ let _: Result<(), _> = redis::cmd("DEL")
1252
+ .arg(&imp_cache_key)
1253
+ .query_async(&mut conn)
1254
+ .await;
1255
+ }
1256
+ tracing::info!(
1257
+ "Self-improvement for '{}': re-search has {}/{} quality (not yet sufficient to cache)",
1258
+ imp_query, re_quality, re_total
1259
+ );
1260
+ }
1261
+ }
1262
+
1263
+ // Release lock
1264
+ if let Ok(mut conn) = imp_state.app.redis.get_connection().await {
1265
+ let _: Result<(), _> = redis::cmd("DEL")
1266
+ .arg(&imp_lock_key)
1267
+ .query_async(&mut conn)
1268
+ .await;
1269
+ }
1270
+
1271
+ tracing::info!(
1272
+ "Background self-improvement completed for '{}': quality={}/{} in {}s",
1273
+ imp_query,
1274
+ quality_indexed,
1275
+ target,
1276
+ task_start.elapsed().as_secs()
1277
+ );
1278
+ });
1279
+ }
1280
+ }
1281
+
1282
+ (StatusCode::OK, Json(response)).into_response()
1283
+ }
1284
+
1285
+ /// Meta-search endpoint
1286
+ async fn meta_search_handler(
1287
+ State(state): State<Arc<ApiState>>,
1288
+ Query(params): Query<SearchParams>,
1289
+ ) -> impl IntoResponse {
1290
+ let start = Instant::now();
1291
+ let intent = state.app.intent_classifier.classify(&params.q);
1292
+ let response = state
1293
+ .app
1294
+ .aggregator
1295
+ .search_with_intent(&params.q, Some(&intent))
1296
+ .await;
1297
+ (
1298
+ StatusCode::OK,
1299
+ Json(SearchResponse {
1300
+ query: params.q,
1301
+ total: response.results.len(),
1302
+ results: response
1303
+ .results
1304
+ .into_iter()
1305
+ .map(|r| SearchResult {
1306
+ id: hash_string(&r.url),
1307
+ title: r.title,
1308
+ url: r.url,
1309
+ description: Some(r.description),
1310
+ category: "meta".to_string(),
1311
+ source: r.source,
1312
+ media_type: r.media_type,
1313
+ thumbnail_url: r.thumbnail_url,
1314
+ intent_score: r.score,
1315
+ relevance_score: r.score,
1316
+ commercial_score: 0.0,
1317
+ spam_score: 0.0,
1318
+ })
1319
+ .collect(),
1320
+ latency_ms: start.elapsed().as_millis() as u64,
1321
+ message: None,
1322
+ intent_scores: vec![],
1323
+ self_improving: false,
1324
+ }),
1325
+ )
1326
+ }
1327
+
1328
+ /// Dedicated news search endpoint
1329
+ async fn news_handler(
1330
+ State(state): State<Arc<ApiState>>,
1331
+ Query(params): Query<MediaSearchParams>,
1332
+ ) -> impl IntoResponse {
1333
+ let start = Instant::now();
1334
+ let aggregator = &state.app.aggregator;
1335
+ let response = if let Some(location) = &params.location {
1336
+ aggregator.search_news_geo(&params.q, location).await
1337
+ } else {
1338
+ aggregator.search_news(&params.q).await
1339
+ };
1340
+
1341
+ let mut seen_urls = HashSet::new();
1342
+ let mut sources = HashSet::new();
1343
+ let results: Vec<NewsResult> = response
1344
+ .results
1345
+ .into_iter()
1346
+ .filter(|r| {
1347
+ if seen_urls.contains(&r.url) {
1348
+ return false;
1349
+ }
1350
+ seen_urls.insert(r.url.clone());
1351
+ sources.insert(r.source.clone());
1352
+ true
1353
+ })
1354
+ .map(|r| NewsResult {
1355
+ title: r.title,
1356
+ url: r.url,
1357
+ description: r.description,
1358
+ source: r.source,
1359
+ published_at: r.published_at,
1360
+ thumbnail_url: r.thumbnail_url,
1361
+ })
1362
+ .take(params.limit)
1363
+ .collect();
1364
+
1365
+ (
1366
+ StatusCode::OK,
1367
+ Json(NewsResponse {
1368
+ query: params.q,
1369
+ total: results.len(),
1370
+ results,
1371
+ latency_ms: start.elapsed().as_millis() as u64,
1372
+ sources: sources.into_iter().collect(),
1373
+ }),
1374
+ )
1375
+ }
1376
+
1377
+ /// Dedicated image search endpoint
1378
+ async fn images_handler(
1379
+ State(state): State<Arc<ApiState>>,
1380
+ Query(params): Query<MediaSearchParams>,
1381
+ ) -> impl IntoResponse {
1382
+ let start = Instant::now();
1383
+ let (expanded_query, _) = rewrite_query(&params.q, &state.app.query_expansion_config);
1384
+ let filter = Some("media_type = \"image\"".to_string());
1385
+ let (local_docs, ext_res) = tokio::join!(
1386
+ state
1387
+ .app
1388
+ .indexer
1389
+ .search(&expanded_query, filter.as_deref(), Some(30)),
1390
+ state.app.image_search.search(&expanded_query, params.limit)
1391
+ );
1392
+
1393
+ let mut results = Vec::new();
1394
+ let mut seen = HashSet::new();
1395
+ let mut sources = Vec::new();
1396
+
1397
+ if let Ok(docs) = local_docs {
1398
+ for d in docs {
1399
+ seen.insert(d.url.clone());
1400
+ results.push(ImageResult {
1401
+ id: d.id,
1402
+ title: d.title,
1403
+ url: d.url,
1404
+ source: d.source,
1405
+ category: d.category,
1406
+ intent_score: d.intent_score,
1407
+ relevance_score: d.relevance_score,
1408
+ thumbnail_url: d.thumbnail_url,
1409
+ alt_text: d.description,
1410
+ photographer: None,
1411
+ width: None,
1412
+ height: None,
1413
+ avg_color: None,
1414
+ });
1415
+ }
1416
+ }
1417
+
1418
+ if let Ok(ext) = ext_res {
1419
+ for i in ext {
1420
+ if !sources.contains(&i.source) {
1421
+ sources.push(i.source.clone());
1422
+ }
1423
+ if !seen.contains(&i.url) {
1424
+ results.push(ImageResult {
1425
+ id: i.id,
1426
+ title: i.title,
1427
+ url: i.url,
1428
+ source: i.source,
1429
+ category: "".into(),
1430
+ intent_score: 0.5,
1431
+ relevance_score: 0.5,
1432
+ thumbnail_url: i.thumbnail_url,
1433
+ alt_text: None,
1434
+ photographer: i.photographer,
1435
+ width: i.width,
1436
+ height: i.height,
1437
+ avg_color: i.avg_color,
1438
+ });
1439
+ }
1440
+ }
1441
+ }
1442
+
1443
+ (
1444
+ StatusCode::OK,
1445
+ Json(ImageResponse {
1446
+ query: params.q,
1447
+ total: results.len(),
1448
+ results: results.into_iter().take(params.limit).collect(),
1449
+ latency_ms: start.elapsed().as_millis() as u64,
1450
+ sources,
1451
+ }),
1452
+ )
1453
+ }
1454
+
1455
+ /// Dedicated video search endpoint
1456
+ async fn videos_handler(
1457
+ State(state): State<Arc<ApiState>>,
1458
+ Query(params): Query<MediaSearchParams>,
1459
+ ) -> impl IntoResponse {
1460
+ let start = Instant::now();
1461
+ let mut results = Vec::new();
1462
+ let mut seen = HashSet::new();
1463
+ let mut sources = Vec::new();
1464
+
1465
+ if let Ok(docs) = state
1466
+ .app
1467
+ .indexer
1468
+ .search(&params.q, Some("media_type = \"video\""), Some(20))
1469
+ .await
1470
+ {
1471
+ for d in docs {
1472
+ seen.insert(d.url.clone());
1473
+ results.push(VideoResult {
1474
+ id: d.id,
1475
+ title: d.title,
1476
+ url: d.url,
1477
+ source: d.source,
1478
+ description: d.description,
1479
+ intent_score: d.intent_score,
1480
+ relevance_score: d.relevance_score,
1481
+ thumbnail_url: d.thumbnail_url,
1482
+ duration_secs: None,
1483
+ view_count: None,
1484
+ channel: None,
1485
+ published_at: None,
1486
+ });
1487
+ }
1488
+ }
1489
+
1490
+ if let Ok(videos) = state.app.video_discovery.search(&params.q).await {
1491
+ for v in videos {
1492
+ if !seen.contains(&v.url) {
1493
+ if !sources.contains(&v.source) {
1494
+ sources.push(v.source.clone());
1495
+ }
1496
+ results.push(VideoResult {
1497
+ id: v.id,
1498
+ title: v.title,
1499
+ url: v.url,
1500
+ source: v.source,
1501
+ description: v.description,
1502
+ intent_score: v.intent_score,
1503
+ relevance_score: v.relevance_score,
1504
+ thumbnail_url: Some(v.thumbnail),
1505
+ duration_secs: v.duration_secs,
1506
+ view_count: v.view_count,
1507
+ channel: v.uploader,
1508
+ published_at: v.published_at.map(|dt| dt.to_rfc3339()),
1509
+ });
1510
+ }
1511
+ }
1512
+ }
1513
+
1514
+ (
1515
+ StatusCode::OK,
1516
+ Json(VideoResponse {
1517
+ query: params.q,
1518
+ total: results.len(),
1519
+ results: results.into_iter().take(params.limit).collect(),
1520
+ latency_ms: start.elapsed().as_millis() as u64,
1521
+ sources,
1522
+ }),
1523
+ )
1524
+ }
1525
+
1526
+ async fn crawl_single_handler(
1527
+ State(state): State<Arc<ApiState>>,
1528
+ Query(params): Query<CrawlParams>,
1529
+ ) -> impl IntoResponse {
1530
+ let start = Instant::now();
1531
+ match state.app.crawler.fetch(&params.url).await {
1532
+ Ok(res) => (
1533
+ StatusCode::OK,
1534
+ Json(CrawlResponse {
1535
+ url: res.url,
1536
+ title: res.title,
1537
+ content_length: res.content.len(),
1538
+ success: true,
1539
+ latency_ms: start.elapsed().as_millis() as u64,
1540
+ error: None,
1541
+ }),
1542
+ ),
1543
+ Err(e) => (
1544
+ StatusCode::OK,
1545
+ Json(CrawlResponse {
1546
+ url: params.url,
1547
+ title: "".into(),
1548
+ content_length: 0,
1549
+ success: false,
1550
+ latency_ms: start.elapsed().as_millis() as u64,
1551
+ error: Some(e.to_string()),
1552
+ }),
1553
+ ),
1554
+ }
1555
+ }
1556
+
1557
+ async fn crawl_batch_handler(
1558
+ State(state): State<Arc<ApiState>>,
1559
+ Json(req): Json<BatchCrawlRequest>,
1560
+ ) -> impl IntoResponse {
1561
+ let start = Instant::now();
1562
+ let urls: Vec<&str> = req.urls.iter().map(|s| s.as_str()).collect();
1563
+ match state.app.crawler.fetch_batch(urls).await {
1564
+ Ok(res) => (
1565
+ StatusCode::OK,
1566
+ Json(
1567
+ res.into_iter()
1568
+ .map(|r| CrawlResponse {
1569
+ url: r.url,
1570
+ title: r.title,
1571
+ content_length: r.content.len(),
1572
+ success: true,
1573
+ latency_ms: 0,
1574
+ error: None,
1575
+ })
1576
+ .collect::<Vec<_>>(),
1577
+ ),
1578
+ ),
1579
+ Err(e) => (
1580
+ StatusCode::INTERNAL_SERVER_ERROR,
1581
+ Json(vec![CrawlResponse {
1582
+ url: "batch".into(),
1583
+ title: "".into(),
1584
+ content_length: 0,
1585
+ success: false,
1586
+ latency_ms: start.elapsed().as_millis() as u64,
1587
+ error: Some(e.to_string()),
1588
+ }]),
1589
+ ),
1590
+ }
1591
+ }
1592
+
1593
+ async fn metrics_handler(State(state): State<Arc<ApiState>>) -> impl IntoResponse {
1594
+ use prometheus::Encoder;
1595
+ let encoder = prometheus::TextEncoder::new();
1596
+ let mut buffer = Vec::new();
1597
+ let _ = encoder.encode(&state.metrics.registry.gather(), &mut buffer);
1598
+ String::from_utf8_lossy(&buffer).to_string()
1599
+ }
1600
+
1601
+ async fn discovery_status_handler(State(state): State<Arc<ApiState>>) -> impl IntoResponse {
1602
+ let queue_size = state.app.discovery.queue_size().await.unwrap_or(0);
1603
+ Json(
1604
+ serde_json::json!({ "queue_size": queue_size, "last_cycle_secs": state.app.discovery.last_cycle_secs(), "max_queue_size": state.app.config.discovery.max_queue_size }),
1605
+ )
1606
+ }
1607
+
1608
+ async fn discovery_enqueue_handler(
1609
+ State(state): State<Arc<ApiState>>,
1610
+ Json(req): Json<DiscoveryEnqueueRequest>,
1611
+ ) -> impl IntoResponse {
1612
+ let cat = req.category.as_deref().unwrap_or("manual");
1613
+ match state
1614
+ .app
1615
+ .discovery
1616
+ .enqueue_url_public(&req.url, req.priority, cat)
1617
+ .await
1618
+ {
1619
+ Ok(enqueued) => (
1620
+ StatusCode::OK,
1621
+ Json(DiscoveryEnqueueResponse {
1622
+ url: req.url,
1623
+ enqueued,
1624
+ error: None,
1625
+ }),
1626
+ ),
1627
+ Err(e) => (
1628
+ StatusCode::INTERNAL_SERVER_ERROR,
1629
+ Json(DiscoveryEnqueueResponse {
1630
+ url: req.url,
1631
+ enqueued: false,
1632
+ error: Some(e.to_string()),
1633
+ }),
1634
+ ),
1635
+ }
1636
+ }
1637
+
1638
+ async fn reindex_scores_handler(State(_state): State<Arc<ApiState>>) -> impl IntoResponse {
1639
+ (
1640
+ StatusCode::OK,
1641
+ Json(serde_json::json!({"status": "deprecated"})),
1642
+ )
1643
+ }
1644
+
1645
+ async fn get_full_content_handler(
1646
+ Path(id): Path<String>,
1647
+ State(state): State<Arc<ApiState>>,
1648
+ ) -> impl IntoResponse {
1649
+ match state.app.redis.get_content(&id).await {
1650
+ Ok(Some(c)) => (
1651
+ StatusCode::OK,
1652
+ Json(serde_json::json!({"id": id, "content": c})),
1653
+ ),
1654
+ _ => (
1655
+ StatusCode::NOT_FOUND,
1656
+ Json(serde_json::json!({"error": "not found"})),
1657
+ ),
1658
+ }
1659
+ }
src/cloudflare_bypass/detector.rs ADDED
@@ -0,0 +1,197 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ //! Cloudflare challenge detection
2
+ //!
3
+ //! Identifies when a response is a Cloudflare challenge page rather than
4
+ //! actual content, so we can skip it or escalate to a solver.
5
+
6
+ /// Types of Cloudflare challenges
7
+ #[derive(Debug, Clone, PartialEq)]
8
+ pub enum ChallengeType {
9
+ /// No challenge detected — response is real content
10
+ None,
11
+ /// "Just a moment..." JS challenge page
12
+ JsChallenge,
13
+ /// Turnstile interactive CAPTCHA widget
14
+ Turnstile,
15
+ /// HTTP 403 with Cloudflare headers
16
+ AccessDenied,
17
+ /// Rate limited (HTTP 429 or 1015)
18
+ RateLimited,
19
+ /// HTTP 1020 — site-specific WAF rule
20
+ WafBlocked,
21
+ }
22
+
23
+ pub struct CloudflareDetector;
24
+
25
+ impl CloudflareDetector {
26
+ /// Inspect a response body and status to detect Cloudflare challenges.
27
+ /// Returns the challenge type, or `None` if the page is real content.
28
+ pub fn detect(status: u16, headers: &[(String, String)], body: &str) -> ChallengeType {
29
+ // Check server header for cloudflare
30
+ let is_cf = headers.iter().any(|(k, v)| {
31
+ k.eq_ignore_ascii_case("server") && v.to_lowercase().contains("cloudflare")
32
+ });
33
+
34
+ // Check for cf-mitigated header (CF 2024+)
35
+ let is_cf_mitigated = headers.iter().any(|(k, v)| {
36
+ k.eq_ignore_ascii_case("cf-mitigated") && v.to_lowercase().contains("challenge")
37
+ });
38
+
39
+ // 1020 = Access Denied (site WAF rule)
40
+ if status == 1020 || (status == 403 && body.contains("error code: 1020")) {
41
+ return ChallengeType::WafBlocked;
42
+ }
43
+
44
+ // 429 or 1015 = rate limited
45
+ if status == 429 || (status == 403 && body.contains("error code: 1015")) {
46
+ return ChallengeType::RateLimited;
47
+ }
48
+
49
+ // 403 with Cloudflare = access denied
50
+ if status == 403 && is_cf {
51
+ // Check if it's a challenge page vs plain denial
52
+ if body.contains("Just a moment...") || body.contains("cf_chl_opt") {
53
+ return ChallengeType::JsChallenge;
54
+ }
55
+ return ChallengeType::AccessDenied;
56
+ }
57
+
58
+ // 403/503 with cf-mitigated header
59
+ if (status == 403 || status == 503) && is_cf_mitigated {
60
+ return ChallengeType::JsChallenge;
61
+ }
62
+
63
+ // 503 with Cloudflare = usually JS challenge
64
+ if status == 503
65
+ && is_cf
66
+ && (body.contains("Just a moment...") || body.contains("Checking your browser"))
67
+ {
68
+ return ChallengeType::JsChallenge;
69
+ }
70
+
71
+ // 200 but body is a Cloudflare challenge page
72
+ // (Cloudflare sometimes returns 200 with challenge HTML)
73
+ if is_cf && Self::is_challenge_html(body) {
74
+ if body.contains("turnstile") || body.contains("cf-turnstile") {
75
+ return ChallengeType::Turnstile;
76
+ }
77
+ return ChallengeType::JsChallenge;
78
+ }
79
+
80
+ ChallengeType::None
81
+ }
82
+
83
+ /// Check if an HTML body is a Cloudflare challenge page
84
+ fn is_challenge_html(body: &str) -> bool {
85
+ // Cloudflare challenge page indicators
86
+ let indicators = [
87
+ "Just a moment...",
88
+ "Checking your browser",
89
+ "cf_chl_opt",
90
+ "challenge-platform",
91
+ "__cf_chl_f_tk",
92
+ "managed-challenge",
93
+ "cf-turnstile",
94
+ "Attention Required! | Cloudflare",
95
+ "Ray ID:",
96
+ "cf-browser-verification",
97
+ ];
98
+
99
+ // Only check first 5KB — challenge pages are detected early
100
+ let snippet = &body[..body.len().min(5120)];
101
+ indicators.iter().any(|i| snippet.contains(i))
102
+ }
103
+
104
+ /// Check if body is the "Just a moment..." Cloudflare interstitial
105
+ pub fn is_just_a_moment(body: &str) -> bool {
106
+ body.contains("Just a moment...") && body.contains("cloudflare")
107
+ }
108
+
109
+ /// Check if a URL's response is usable content (not a challenge)
110
+ pub fn is_usable_content(status: u16, body: &str) -> bool {
111
+ if status != 200 {
112
+ return false;
113
+ }
114
+ // Reject if body is too short (likely challenge/error)
115
+ if body.len() < 200 {
116
+ return false;
117
+ }
118
+ // Reject if it's a Cloudflare challenge page
119
+ if Self::is_challenge_html(body) {
120
+ return false;
121
+ }
122
+ true
123
+ }
124
+ }
125
+
126
+ #[cfg(test)]
127
+ mod tests {
128
+ use super::*;
129
+
130
+ #[test]
131
+ fn test_detect_just_a_moment() {
132
+ let body = r#"<html><head><title>Just a moment...</title></head>
133
+ <body>Checking your browser... <div id="challenge-platform"></div></body></html>"#;
134
+ let headers = vec![
135
+ ("server".to_string(), "cloudflare".to_string()),
136
+ ("cf-mitigated".to_string(), "challenge".to_string()),
137
+ ];
138
+ assert_eq!(
139
+ CloudflareDetector::detect(403, &headers, body),
140
+ ChallengeType::JsChallenge
141
+ );
142
+ }
143
+
144
+ #[test]
145
+ fn test_detect_turnstile() {
146
+ let body = r#"<html><div class="cf-turnstile" data-sitekey="abc"></div></html>"#;
147
+ let headers = vec![("server".to_string(), "cloudflare".to_string())];
148
+ assert_eq!(
149
+ CloudflareDetector::detect(200, &headers, body),
150
+ ChallengeType::Turnstile
151
+ );
152
+ }
153
+
154
+ #[test]
155
+ fn test_detect_rate_limited() {
156
+ let body = "error code: 1015 You are being rate limited";
157
+ let headers = vec![("server".to_string(), "cloudflare".to_string())];
158
+ assert_eq!(
159
+ CloudflareDetector::detect(403, &headers, body),
160
+ ChallengeType::RateLimited
161
+ );
162
+ }
163
+
164
+ #[test]
165
+ fn test_detect_waf_blocked() {
166
+ let body = "error code: 1020";
167
+ let headers = vec![("server".to_string(), "cloudflare".to_string())];
168
+ assert_eq!(
169
+ CloudflareDetector::detect(403, &headers, body),
170
+ ChallengeType::WafBlocked
171
+ );
172
+ }
173
+
174
+ #[test]
175
+ fn test_no_challenge_normal_page() {
176
+ let body = "<html><head><title>My Blog</title></head><body><p>Content</p></body></html>";
177
+ let headers = vec![];
178
+ assert_eq!(
179
+ CloudflareDetector::detect(200, &headers, body),
180
+ ChallengeType::None
181
+ );
182
+ }
183
+
184
+ #[test]
185
+ fn test_is_usable_content() {
186
+ assert!(CloudflareDetector::is_usable_content(
187
+ 200,
188
+ &("<html><body>".to_string() + &"x".repeat(200) + "</body></html>")
189
+ ));
190
+ assert!(!CloudflareDetector::is_usable_content(403, "blocked"));
191
+ assert!(!CloudflareDetector::is_usable_content(
192
+ 200,
193
+ "Just a moment... cloudflare"
194
+ ));
195
+ assert!(!CloudflareDetector::is_usable_content(200, "short"));
196
+ }
197
+ }