File size: 12,645 Bytes
0ca462b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
"""
Intent Engine - Optimized Ranking Module (Unified ONNX Version)

This module implements improved constraint satisfaction and intent-aligned ranking
using the shared ONNX embedding service for high performance.
"""

import hashlib
import logging
from dataclasses import dataclass
from typing import Any

from app.config.query_cache import get_ranking_cache
from app.core.embedding_service import get_embedding_service
from app.core.schema import (
    Constraint,
    ConstraintType,
    DeclaredIntent,
    EthicalDimension,
    InferredIntent,
    SkillLevel,
    UniversalIntent,
)

logger = logging.getLogger(__name__)


@dataclass
class SearchResult:
    """Represents a search result candidate with metadata"""

    id: str
    title: str
    description: str
    platform: str | None = None
    provider: str | None = None
    license: str | None = None
    price: float | None = None
    tags: list[str] | None = None
    qualityScore: float | None = 0.5
    recency: str | None = None
    complexity: str | None = None
    compatibility: list[str] | None = None
    privacyRating: float | None = None
    opensource: bool | None = None


@dataclass
class RankedResult:
    """Represents a ranked result with alignment score and reasons"""

    result: SearchResult
    alignmentScore: float
    matchReasons: list[str]


@dataclass
class RankingRequest:
    """Request object for ranking API"""

    intent: UniversalIntent
    candidates: list[SearchResult]
    options: dict[str, Any] | None = None


@dataclass
class RankingResponse:
    """Response object for ranking API"""

    rankedResults: list[RankedResult]
    cache_hit: bool = False
    processing_time_ms: float = 0.0


class OptimizedConstraintSatisfactionEngine:
    """Improved constraint satisfaction with better performance"""

    def __init__(self):
        self.embedding_service = get_embedding_service()

    def satisfies_constraints(
        self, result: SearchResult, constraints: list[Constraint]
    ) -> bool:
        """Check if a result satisfies all hard constraints"""
        if not constraints:
            return True

        for constraint in constraints:
            if not constraint.hardFilter:
                continue

            if not self._satisfies_single_constraint(result, constraint):
                return False

        return True

    def _satisfies_single_constraint(
        self, result: SearchResult, constraint: Constraint
    ) -> bool:
        """Check if a result satisfies a single constraint"""
        dimension = constraint.dimension
        value = constraint.value
        constraint_type = constraint.type

        result_value = getattr(result, dimension, None)

        if constraint_type == ConstraintType.INCLUSION:
            if isinstance(value, str):
                if result_value is None:
                    return False
                return result_value.lower() == value.lower()
            if isinstance(value, list):
                if result_value is None:
                    return False
                result_lower = str(result_value).lower()
                return any(result_lower == str(v).lower() for v in value)

        elif constraint_type == ConstraintType.EXCLUSION:
            if isinstance(value, str):
                if result_value is None:
                    return True
                return result_value.lower() != value.lower()
            if isinstance(value, list):
                if result_value is None:
                    return True
                result_lower = str(result_value).lower()
                return all(result_lower != str(v).lower() for v in value)

        elif (
            constraint_type == ConstraintType.RANGE
            and dimension == "price"
            and result_value is not None
        ):
            return self._check_price_range(result_value, value)

        return True

    def _check_price_range(self, price: float, range_spec: str) -> bool:
        """Check if price satisfies range specification"""
        range_spec = str(range_spec).lower().strip()
        if range_spec in {"budget", "free", "0"}:
            return price == 0
        return True  # Simplified for now


class OptimizedIntentAlignmentEngine:
    """Improved intent alignment with better scoring using ONNX"""

    def __init__(self):
        self.embedding_service = get_embedding_service()

    def compute_intent_alignment(
        self, result: SearchResult, intent: UniversalIntent
    ) -> tuple[float, list[str]]:
        """Compute alignment score with improved weighting"""
        scores = []
        reasons = []

        declared = intent.declared or DeclaredIntent()
        inferred = intent.inferred or InferredIntent()

        # 1. Query-content alignment (semantic similarity) - 40% (Boosted)
        query_score, query_reasons = self._compute_query_content_alignment(
            result, intent, declared
        )
        scores.append((query_score, 0.40))
        reasons.extend(query_reasons)

        # 2. Use case alignment - 20%
        use_case_score, use_case_reasons = self._compute_use_case_alignment(
            result, intent, inferred
        )
        scores.append((use_case_score, 0.20))
        reasons.extend(use_case_reasons)

        # 3. Ethical signal alignment - 15%
        ethical_score, ethical_reasons = self._compute_ethical_alignment(
            result, intent, inferred
        )
        scores.append((ethical_score, 0.15))
        reasons.extend(ethical_reasons)

        # 4. Skill level alignment - 15%
        skill_score, skill_reasons = self._compute_skill_alignment(
            result, intent, declared
        )
        scores.append((skill_score, 0.15))
        reasons.extend(skill_reasons)

        # 5. Quality score - 10%
        quality_score = result.qualityScore or 0.5
        scores.append((quality_score, 0.10))

        # Calculate weighted average
        alignment_score = sum(score * weight for score, weight in scores)
        alignment_score = max(0.0, min(1.0, alignment_score))

        return alignment_score, list(set(reasons))

    def _compute_query_content_alignment(
        self, result: SearchResult, intent: UniversalIntent, declared: DeclaredIntent
    ) -> tuple[float, list[str]]:
        """Compute semantic similarity between query and result using shared ONNX"""
        reasons = []
        query = declared.query if declared else None
        if not query:
            return 0.5, reasons

        content = f"{result.title} {result.description}".strip()
        if not content:
            return 0.0, reasons

        # Get embeddings via shared ONNX service
        query_emb = self.embedding_service.encode_text(query)
        content_emb = self.embedding_service.encode_text(content)

        if query_emb is not None and content_emb is not None:
            similarity = self.embedding_service.cosine_similarity(
                query_emb, content_emb
            )
            score = (similarity + 1) / 2  # Normalize to 0-1

            if score > 0.7:
                reasons.append("high-semantic-match")
            elif score > 0.5:
                reasons.append("semantic-match")

            return score, reasons

        return 0.5, ["keyword-fallback"]

    def _compute_use_case_alignment(
        self, result: SearchResult, intent: UniversalIntent, inferred: InferredIntent
    ) -> tuple[float, list[str]]:
        """Compute use case alignment"""
        reasons = []
        use_cases = inferred.useCases if inferred else []
        if not use_cases or not result.tags:
            return 0.5, reasons

        score = 0.0
        tag_text = " ".join(result.tags).lower()

        for use_case in use_cases:
            use_case_str = str(use_case.value).replace("_", " ")
            if use_case_str in tag_text:
                score += 1.0
                reasons.append(f"use-case-{use_case.value}")

        score = min(1.0, score / len(use_cases)) if use_cases else 0.5
        return score, reasons

    def _compute_ethical_alignment(
        self, result: SearchResult, intent: UniversalIntent, inferred: InferredIntent
    ) -> tuple[float, list[str]]:
        """Compute ethical signal alignment"""
        reasons = []
        ethical_signals = inferred.ethicalSignals if inferred else []
        if not ethical_signals:
            return 0.5, reasons

        score = 0.0
        for signal in ethical_signals:
            if signal.dimension == EthicalDimension.PRIVACY:
                if result.privacyRating and result.privacyRating > 0.7:
                    score += 1.0
                    reasons.append("privacy-aligned")
            elif signal.dimension == EthicalDimension.OPENNESS:
                if result.opensource:
                    score += 1.0
                    reasons.append("open-source-aligned")

        score = min(1.0, score / len(ethical_signals)) if ethical_signals else 0.5
        return score, reasons

    def _compute_skill_alignment(
        self, result: SearchResult, intent: UniversalIntent, declared: DeclaredIntent
    ) -> tuple[float, list[str]]:
        """Compute skill level alignment"""
        reasons = []
        declared_skill = declared.skillLevel if declared else SkillLevel.INTERMEDIATE
        result_complexity = result.complexity

        if not result_complexity:
            return 0.5, reasons

        # Simple string match for complexity
        if result_complexity.lower() in str(declared_skill.name).lower():
            return 1.0, ["exact-skill-match"]

        return 0.5, reasons


class ResultDeduplicator:
    """Deduplicate results based on content similarity"""

    def __init__(self, similarity_threshold: float = 0.9):
        self.similarity_threshold = similarity_threshold
        self.embedding_service = get_embedding_service()

    def deduplicate(self, results: list[RankedResult]) -> list[RankedResult]:
        if not results:
            return results

        unique_results = []
        seen_hashes = set()

        for result in results:
            # Fast hash-based deduplication
            content_hash = hashlib.md5(
                f"{result.result.title}".lower().encode()
            ).hexdigest()
            if content_hash not in seen_hashes:
                unique_results.append(result)
                seen_hashes.add(content_hash)

        return unique_results


class OptimizedIntentRanker:
    """Main ranking class with ONNX optimizations"""

    def __init__(self):
        self.constraint_engine = OptimizedConstraintSatisfactionEngine()
        self.alignment_engine = OptimizedIntentAlignmentEngine()
        self.deduplicator = ResultDeduplicator()
        self.cache = get_ranking_cache()

    def rank_results(self, request: RankingRequest) -> RankingResponse:
        import time

        start_time = time.time()

        # Filter candidates
        filtered_candidates = self._filter_candidates(request)

        # Compute alignment scores
        ranked_results = []
        for candidate in filtered_candidates:
            score, reasons = self.alignment_engine.compute_intent_alignment(
                candidate, request.intent
            )
            ranked_results.append(
                RankedResult(
                    result=candidate, alignmentScore=score, matchReasons=reasons
                )
            )

        # Deduplicate
        ranked_results = self.deduplicator.deduplicate(ranked_results)

        # Sort by score
        ranked_results.sort(key=lambda x: x.alignmentScore, reverse=True)

        processing_time = (time.time() - start_time) * 1000
        return RankingResponse(
            rankedResults=ranked_results,
            cache_hit=False,
            processing_time_ms=processing_time,
        )

    def _filter_candidates(self, request: RankingRequest) -> list[SearchResult]:
        if not request.intent.declared or not request.intent.declared.constraints:
            return request.candidates

        filtered = []
        for candidate in request.candidates:
            if self.constraint_engine.satisfies_constraints(
                candidate, request.intent.declared.constraints
            ):
                filtered.append(candidate)
        return filtered


# Global instance
_ranker_instance = None


def get_intent_ranker() -> OptimizedIntentRanker:
    global _ranker_instance
    if _ranker_instance is None:
        _ranker_instance = OptimizedIntentRanker()
    return _ranker_instance


def rank_results(request: RankingRequest) -> RankingResponse:
    ranker = get_intent_ranker()
    return ranker.rank_results(request)