Spaces:
Build error
Build error
Download services/query_layer/app/main.py from LuckyMod/intentforge: direct link, hf CLI and curl.
- Browser
- Download file 13.6 kB
-
https://huggingface.co/spaces/LuckyMod/intentforge/resolve/main/services/query_layer/app/main.py
- Command line
-
hf download hf://spaces/LuckyMod/intentforge/services/query_layer/app/main.py
-
curl -L -o main.py https://huggingface.co/spaces/LuckyMod/intentforge/resolve/main/services/query_layer/app/main.py
13.6 kB
| """ | |
| IntentForge Unified Query & Ranking Layer | |
| Combines semantic/hybrid search with advanced intent-aligned ranking. | |
| """ | |
| import asyncio | |
| import os | |
| import time | |
| import logging | |
| from typing import List, Optional, Dict, Any | |
| from math import exp | |
| import numpy as np | |
| import onnxruntime as ort | |
| from qdrant_client import QdrantClient | |
| from qdrant_client.http import models as qmodels | |
| from fastapi import FastAPI, HTTPException, Query | |
| from pydantic import BaseModel | |
| from transformers import AutoTokenizer | |
| from sentence_transformers import CrossEncoder | |
| # Import ranking components | |
| from app.ranking.optimized_ranker import ( | |
| rank_results, | |
| RankingRequest as InternalRankingRequest, | |
| SearchResult as InternalSearchResult, | |
| ) | |
| from app.core.schema import UniversalIntent | |
| from app.core.embedding_service import get_embedding_service | |
| logging.basicConfig(level=logging.INFO) | |
| logger = logging.getLogger("unified-layer") | |
| # Configuration from environment | |
| QDRANT_URL = os.getenv("QDRANT_URL", "http://localhost:6334") | |
| QDRANT_API_KEY = os.getenv("QDRANT_API_KEY", None) | |
| MODEL_PATH = os.getenv("MODEL_PATH", "/models/all-MiniLM-L6-v2.onnx") | |
| TOKENIZER_NAME = os.getenv("TOKENIZER_NAME", "sentence-transformers/all-MiniLM-L6-v2") | |
| INDEX_NAME = os.getenv("INDEX_NAME", "intentforge") | |
| app = FastAPI( | |
| title="IntentForge Unified Layer", | |
| description="Unified API for Search and Intent Ranking", | |
| version="0.2.0", | |
| ) | |
| # Global state | |
| model_session = None | |
| tokenizer = None | |
| cross_encoder_model = None | |
| # Initialize Qdrant client | |
| qdrant_client = QdrantClient(url=QDRANT_URL, api_key=QDRANT_API_KEY) | |
| # --- Search Models --- | |
| class SearchResult(BaseModel): | |
| id: str | |
| title: str | |
| snippet: Optional[str] = None | |
| url: str | |
| source: str | |
| category: str | |
| intent_score: float | |
| relevance_score: float | |
| commercial_score: float = 0.0 | |
| spam_score: float = 0.0 | |
| score: float | |
| class SearchResponse(BaseModel): | |
| query: str | |
| total_hits: int | |
| results: List[SearchResult] | |
| processing_time_ms: float | |
| # --- Ranking Models --- | |
| class SearchResultModel(BaseModel): | |
| id: str | |
| title: str | |
| description: str | |
| platform: Optional[str] = None | |
| provider: Optional[str] = None | |
| license: Optional[str] = None | |
| price: Optional[float] = None | |
| tags: Optional[List[str]] = None | |
| qualityScore: Optional[float] = 0.5 | |
| recency: Optional[str] = None | |
| complexity: Optional[str] = None | |
| compatibility: Optional[List[str]] = None | |
| privacyRating: Optional[float] = None | |
| opensource: Optional[bool] = None | |
| class RankingAPIRequest(BaseModel): | |
| intent: UniversalIntent | |
| candidates: List[SearchResultModel] | |
| options: Optional[dict] = None | |
| async def startup_event(): | |
| global model_session, tokenizer | |
| # Load tokenizer | |
| logger.info(f"Loading tokenizer: {TOKENIZER_NAME}") | |
| try: | |
| tokenizer = AutoTokenizer.from_pretrained(TOKENIZER_NAME) | |
| except Exception as e: | |
| logger.error(f"Failed to load tokenizer: {e}") | |
| # Fallback to local path | |
| try: | |
| tokenizer = AutoTokenizer.from_pretrained("/models/") | |
| except Exception: | |
| pass | |
| # Load ONNX model for embeddings | |
| if os.path.exists(MODEL_PATH): | |
| logger.info(f"Loading ONNX model: {MODEL_PATH}") | |
| try: | |
| model_session = ort.InferenceSession(MODEL_PATH) | |
| except Exception as e: | |
| logger.error(f"Failed to load ONNX model: {e}") | |
| else: | |
| logger.warning( | |
| f"ONNX model not found at {MODEL_PATH}. Semantic search fallback will be used." | |
| ) | |
| # Initialize shared EmbeddingService with ONNX session | |
| if model_session and tokenizer: | |
| logger.info("Initializing shared EmbeddingService with ONNX session") | |
| emb_service = get_embedding_service() | |
| emb_service.initialize(onnx_session=model_session, tokenizer=tokenizer) | |
| # Load cross-encoder model for reranking | |
| global cross_encoder_model | |
| try: | |
| logger.info("Loading cross-encoder model: cross-encoder/ms-marco-MiniLM-L6-v2") | |
| cross_encoder_model = CrossEncoder("cross-encoder/ms-marco-MiniLM-L6-v2") | |
| logger.info("Cross-encoder model loaded successfully") | |
| except Exception as e: | |
| logger.error( | |
| f"Failed to load cross-encoder model: {e}. Falling back to bi-encoder cosine similarity for reranking." | |
| ) | |
| cross_encoder_model = None | |
| # --- Shared Logic --- | |
| def generate_embedding(query: str) -> Optional[List[float]]: | |
| emb_service = get_embedding_service() | |
| vector = emb_service.encode_text(query) | |
| return vector.tolist() if vector is not None else None | |
| def cosine_similarity(a: List[float], b: List[float]) -> float: | |
| a_arr = np.array(a) | |
| b_arr = np.array(b) | |
| dot = np.dot(a_arr, b_arr) | |
| norm_a = np.linalg.norm(a_arr) | |
| norm_b = np.linalg.norm(b_arr) | |
| if norm_a == 0 or norm_b == 0: | |
| return 0.0 | |
| return float(dot / (norm_a * norm_b)) | |
| # --- Endpoints --- | |
| async def health(): | |
| return { | |
| "status": "healthy", | |
| "service": "unified-layer", | |
| "model_loaded": model_session is not None, | |
| "tokenizer_loaded": tokenizer is not None, | |
| "cross_encoder_loaded": cross_encoder_model is not None, | |
| "meili_connection": True, # Basic check | |
| } | |
| class RerankResult(BaseModel): | |
| id: str | |
| score: float | |
| class RerankRequest(BaseModel): | |
| query: str | |
| candidates: List[Dict[str, Any]] | |
| class RerankResponse(BaseModel): | |
| results: List[RerankResult] | |
| processing_time_ms: float | |
| async def rerank_endpoint(request: RerankRequest): | |
| """ | |
| Rerank candidates using a true cross-encoder model (ms-marco-MiniLM-L6-v2). | |
| Falls back to bi-encoder cosine similarity if the cross-encoder is unavailable. | |
| """ | |
| start_time = time.time() | |
| if not request.candidates: | |
| return RerankResponse(results=[], processing_time_ms=0.0) | |
| if cross_encoder_model is not None: | |
| # --- True cross-encoder reranking --- | |
| pairs = [] | |
| ids = [] | |
| for cand in request.candidates: | |
| cand_text = f"{cand.get('title', '')} {cand.get('description', '')}" | |
| pairs.append((request.query, cand_text)) | |
| ids.append(cand.get("id", "")) | |
| try: | |
| raw_scores = await asyncio.to_thread(cross_encoder_model.predict, pairs) | |
| # Normalize logits to 0-1 via sigmoid | |
| results = [ | |
| RerankResult( | |
| id=ids[i], score=float(1 / (1 + exp(-float(raw_scores[i])))) | |
| ) | |
| for i in range(len(ids)) | |
| ] | |
| except Exception as e: | |
| logger.error( | |
| f"Cross-encoder prediction failed: {e}. Falling back to cosine similarity." | |
| ) | |
| results = _cosine_fallback_rerank(request) | |
| else: | |
| # --- Fallback: bi-encoder cosine similarity --- | |
| results = _cosine_fallback_rerank(request) | |
| # Sort by score descending | |
| results.sort(key=lambda x: x.score, reverse=True) | |
| return RerankResponse( | |
| results=results, processing_time_ms=(time.time() - start_time) * 1000 | |
| ) | |
| def _cosine_fallback_rerank(request: RerankRequest) -> List[RerankResult]: | |
| """Fallback reranking using bi-encoder cosine similarity.""" | |
| emb_service = get_embedding_service() | |
| query_vec = emb_service.encode_text(request.query) | |
| if query_vec is None: | |
| raise HTTPException(status_code=500, detail="Failed to encode query") | |
| results = [] | |
| for cand in request.candidates: | |
| cand_text = f"{cand.get('title', '')} {cand.get('description', '')}" | |
| cand_vec = emb_service.encode_text(cand_text) | |
| if cand_vec is not None: | |
| score = float( | |
| np.dot(query_vec, cand_vec) | |
| / (np.linalg.norm(query_vec) * np.linalg.norm(cand_vec)) | |
| ) | |
| results.append(RerankResult(id=cand.get("id", ""), score=score)) | |
| else: | |
| results.append(RerankResult(id=cand.get("id", ""), score=0.0)) | |
| return results | |
| async def search( | |
| q: str = Query(..., description="The search query"), | |
| limit: int = Query(10, ge=1, le=100), | |
| offset: int = Query(0, ge=0), | |
| category: Optional[str] = None, | |
| media_type: str = Query( | |
| "text", description="Filter by media type: text, image, video" | |
| ), | |
| semantic_ratio: float = Query(0.0, ge=0.0, le=1.0), | |
| ): | |
| start_time = time.time() | |
| embedding = generate_embedding(q) if semantic_ratio > 0.0 else None | |
| # Re-ranking depth | |
| fetch_limit = 100 if embedding else limit | |
| # Build Qdrant filter | |
| filter_conditions = [] | |
| if category: | |
| filter_conditions.append( | |
| qmodels.FieldCondition( | |
| key="category", match=qmodels.MatchValue(value=category) | |
| ) | |
| ) | |
| if media_type: | |
| filter_conditions.append( | |
| qmodels.FieldCondition( | |
| key="media_type", match=qmodels.MatchValue(value=media_type) | |
| ) | |
| ) | |
| query_filter = qmodels.Filter(must=filter_conditions) if filter_conditions else None | |
| try: | |
| if embedding: | |
| # Semantic Search | |
| search_result = qdrant_client.search( | |
| collection_name=INDEX_NAME, | |
| query_vector=embedding, | |
| query_filter=query_filter, | |
| limit=fetch_limit, | |
| offset=offset, | |
| with_payload=True, | |
| with_vectors=True, | |
| ) | |
| else: | |
| # Full-text Fallback (using Qdrant MatchText) | |
| # Since Qdrant doesn't have a top-level 'search' for text without vector, | |
| # we use a dummy vector or better, just retrieve with text filter. | |
| # But Qdrant 1.10+ supports Query API which is better. | |
| # For simplicity, we'll use a zero vector if no embedding is generated. | |
| search_result = qdrant_client.search( | |
| collection_name=INDEX_NAME, | |
| query_vector=[0.0] * 384, | |
| query_filter=qmodels.Filter( | |
| must=[ | |
| qmodels.FieldCondition( | |
| key="title", match=qmodels.MatchText(text=q) | |
| ) | |
| ] | |
| + (filter_conditions or []) | |
| ), | |
| limit=fetch_limit, | |
| offset=offset, | |
| with_payload=True, | |
| with_vectors=True, | |
| ) | |
| except Exception as e: | |
| logger.error(f"Qdrant search failed: {e}") | |
| return SearchResponse( | |
| query=q, | |
| total_hits=0, | |
| results=[], | |
| processing_time_ms=(time.time() - start_time) * 1000, | |
| ) | |
| scored_results = [] | |
| for hit in search_result: | |
| payload = hit.payload | |
| # Original scores from crawler | |
| calc_intent = payload.get("intent_score", 0.5) | |
| calc_rel = payload.get("relevance_score", 0.5) | |
| # If we have an embedding, we can use the Qdrant score (cosine similarity) | |
| # to refine the intent score | |
| if embedding: | |
| # hit.score is the cosine similarity from Qdrant | |
| intent_sim = hit.score | |
| calc_intent = intent_sim * 0.5 + calc_intent * 0.5 | |
| final_score = calc_intent * semantic_ratio + calc_rel * (1.0 - semantic_ratio) | |
| scored_results.append((final_score, calc_intent, calc_rel, hit)) | |
| scored_results.sort(key=lambda x: x[0], reverse=True) | |
| hits = [] | |
| for _, calc_intent, calc_rel, hit in scored_results[:limit]: | |
| payload = hit.payload | |
| # Snippet generation (Qdrant doesn't have auto-crop in basic search) | |
| content = payload.get("content", "") | |
| snippet = content[:160] + "..." if len(content) > 160 else content | |
| hits.append( | |
| SearchResult( | |
| id=payload.get("id", str(hit.id)), | |
| title=payload.get("title", "Untitled"), | |
| snippet=snippet, | |
| url=payload.get("url", ""), | |
| source=payload.get("source", "unknown"), | |
| category=payload.get("category", "general"), | |
| intent_score=float(calc_intent), | |
| relevance_score=float(calc_rel), | |
| commercial_score=float(payload.get("commercial_score", 0.0)), | |
| spam_score=float(payload.get("spam_score", 0.0)), | |
| score=final_score, | |
| ) | |
| ) | |
| return SearchResponse( | |
| query=q, | |
| total_hits=len( | |
| search_result | |
| ), # Qdrant search() doesn't return total count easily without separate count() | |
| results=hits, | |
| processing_time_ms=(time.time() - start_time) * 1000, | |
| ) | |
| async def rank_candidates(request: RankingAPIRequest): | |
| try: | |
| # Convert Pydantic models to internal dataclasses | |
| internal_candidates = [ | |
| InternalSearchResult(**c.model_dump()) for c in request.candidates | |
| ] | |
| internal_request = InternalRankingRequest( | |
| intent=request.intent, | |
| candidates=internal_candidates, | |
| options=request.options, | |
| ) | |
| # Perform ranking using the OptimizedIntentRanker | |
| response = rank_results(internal_request) | |
| return response | |
| except Exception as e: | |
| logger.error(f"Ranking failed: {e}") | |
| raise HTTPException(status_code=500, detail=str(e)) | |
| if __name__ == "__main__": | |
| import uvicorn | |
| uvicorn.run(app, host="0.0.0.0", port=8000) | |