Spaces:
Build error
Build error
Remove obsolete test scripts for follow-up behavior, detection fix, history filtering, hybrid context, Kendrick follow-up, simple extraction, and state management - Deleted multiple test files to streamline the codebase and eliminate unused tests. This cleanup supports ongoing refactoring efforts and enhances overall project maintainability.
Browse files- TODO/todo.md +256 -3
- src/agents/components/__init__.py +2 -1
- src/agents/components/{quality_scorer.py β quality_scorer_backup.py} +0 -0
- src/agents/components/scoring/__init__.py +27 -0
- src/agents/components/scoring/audio_quality_scorer.py +239 -0
- src/agents/components/scoring/comprehensive_quality_scorer.py +368 -0
- src/agents/components/scoring/engagement_scorer.py +97 -0
- src/agents/components/scoring/genre_mood_fit_scorer.py +149 -0
- src/agents/components/scoring/intent_aware_scorer.py +566 -0
- src/agents/components/scoring/popularity_balancer.py +121 -0
- src/agents/judge/ranking_logic.py +1 -1
- test_followup_behavior.py +0 -109
- test_followup_detection_fix.py +0 -137
- test_history_filtering.py +0 -253
- test_hybrid_context.py +0 -155
- test_kendrick_followup.py +0 -47
- test_simple_extraction.py +0 -58
- test_state_fix.py +0 -71
TODO/todo.md
CHANGED
|
@@ -1,3 +1,256 @@
|
|
| 1 |
-
|
| 2 |
-
|
| 3 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Okay, this is a substantial codebase with a good foundation, but there's definitely room for refinement to make it more production-ready, focusing on DRY principles and overall cleanliness.
|
| 2 |
+
|
| 3 |
+
Here's a design plan for refactoring:
|
| 4 |
+
|
| 5 |
+
## Design Plan: Production Refinement for BeatDebate
|
| 6 |
+
|
| 7 |
+
**Guiding Principles:**
|
| 8 |
+
|
| 9 |
+
1. **DRY (Don't Repeat Yourself):** Consolidate common logic into base classes, utility functions, or shared components.
|
| 10 |
+
2. **Single Responsibility Principle (SRP):** Ensure classes and modules have one primary reason to change.
|
| 11 |
+
3. **Dependency Inversion Principle (DIP):** Depend on abstractions, not concretions. The use of `APIService` and DI in agents is a good start.
|
| 12 |
+
4. **Clear Abstractions:** Make interfaces between components well-defined and intuitive.
|
| 13 |
+
5. **Configuration Management:** Centralize and simplify how configurations are handled and passed.
|
| 14 |
+
6. **Readability & Maintainability:** Improve code clarity through better organization and naming.
|
| 15 |
+
7. **Preserve Functionality:** All existing features should work as before.
|
| 16 |
+
|
| 17 |
+
---
|
| 18 |
+
|
| 19 |
+
**Key Refactoring Areas & Action Plan:**
|
| 20 |
+
|
| 21 |
+
### 1. Agents (`src/agents/`)
|
| 22 |
+
|
| 23 |
+
The agent structure has a good base with shared components. The main goal here is to ensure maximum leverage of these components and the `BaseAgent`.
|
| 24 |
+
|
| 25 |
+
* **`BaseAgent` Enhancement:**
|
| 26 |
+
* **Action:** Ensure `BaseAgent` handles common initialization patterns (e.g., logging setup, component instantiation if always the same type), standard error handling for `process`, and perhaps a standard way to access shared services like `APIService`, `MetadataService`.
|
| 27 |
+
* **Rationale:** Reduces boilerplate in concrete agent classes.
|
| 28 |
+
|
| 29 |
+
* **Advocate Agents (`GenreMoodAgent`, `DiscoveryAgent`):**
|
| 30 |
+
* **Action (Candidate Generation):** Verify that *all* candidate generation logic is exclusively within `UnifiedCandidateGenerator`. Remove any local API calls or direct list building for candidates within these agents. They should only configure and call the generator.
|
| 31 |
+
* **Action (Scoring):** Ensure that all scoring uses `ComprehensiveQualityScorer`. Agent-specific scoring logic should be encapsulated as strategies *within* the `QualityScorer` or passed as parameters, rather than being implemented directly in the agent.
|
| 32 |
+
* **Action (Intent Adaptation):** The `_adapt_to_intent` methods are good. Consider if the `intent_parameters` dictionaries could be loaded from a configuration file or a shared constants module for easier management if they grow very large.
|
| 33 |
+
* **Rationale:** Maximizes reuse of shared components, makes agents leaner and focused on their specific advocacy role (configuring shared tools).
|
| 34 |
+
|
| 35 |
+
* **`PlannerAgent`:**
|
| 36 |
+
* **Action (Query Understanding):** `QueryUnderstandingEngine` seems to be the core. Ensure it fully utilizes `LLMUtils`, `EntityExtractionUtils`, and `QueryAnalysisUtils`. The existing structure is good.
|
| 37 |
+
* **Action (Context Handling Logic):** Methods like `_is_followup_with_preserved_context`, `_create_understanding_from_context`, `_create_entities_from_context`, `_extract_entity_names` are specific to interpreting and transforming conversation context. These could potentially be moved to `ConversationContextService` or a new `ContextTransformationUtils` if they are general enough, or kept if tightly coupled with planner's decision-making. For now, let's assume they are planner-specific but review if they are used elsewhere.
|
| 38 |
+
* **Rationale:** Keeps planner focused on strategic planning, delegating detailed context interpretation.
|
| 39 |
+
|
| 40 |
+
* **`JudgeAgent`:**
|
| 41 |
+
* **Action (Ranking & Explanation):** Relies on `RankingLogic` and `ConversationalExplainer`. This is good. Ensure `ConversationalExplainer` uses `LLMUtils`.
|
| 42 |
+
* **Action (Hybrid Subtype Detection):** The `_detect_hybrid_subtype` logic might be better placed within `QueryAnalysisUtils` or as part of the output from `QueryUnderstandingEngine`, as it's a core part of understanding the query's nuances.
|
| 43 |
+
* **Action (Filtering Shown Tracks):** The `_filter_out_recently_shown` logic should ideally be a utility provided by `ConversationContextService` (e.g., `get_recommendations_excluding_seen(candidates, session_id)`).
|
| 44 |
+
* **Rationale:** Centralizes query analysis and session-specific filtering.
|
| 45 |
+
|
| 46 |
+
* **`src/agents/components/`:**
|
| 47 |
+
* **Action (General):** These are crucial. Review all agents to ensure they are *maximally* leveraging these utilities. Any local regex, list manipulation for entities, or direct LLM call patterns outside `LLMUtils` should be questioned and likely refactored to use these components.
|
| 48 |
+
* **`QualityScorer`:** The structure with sub-scorers and a `ComprehensiveQualityScorer` is good. Ensure it's the single point of entry for quality scoring.
|
| 49 |
+
* **`UnifiedCandidateGenerator`:** Ensure it's flexible enough to handle all generation strategies required by advocate agents. The intent-aware generation logic is a good pattern.
|
| 50 |
+
* **Rationale:** These components are the backbone of DRY for agent logic.
|
| 51 |
+
|
| 52 |
+
### 2. Services (`src/services/`)
|
| 53 |
+
|
| 54 |
+
* **`EnhancedRecommendationService`:**
|
| 55 |
+
* **Action:** This is the main orchestrator. Its primary role should be to manage the LangGraph workflow and interact with other services. Keep business logic minimal here; it should delegate.
|
| 56 |
+
* **Action (Context Handling):** The `ContextAwareIntentAnalyzer` inside this service. This is a good place for the high-level decision of *how* to use context (e.g., is this a follow-up that needs special handling?). It should use `ConversationContextService` to fetch and update history.
|
| 57 |
+
* **Action (Agent Initialization):** Ensure `initialize_agents` correctly passes shared instances of `APIService`, `MetadataService`, `CacheManager`, and `rate_limiter` to all agents.
|
| 58 |
+
* **Rationale:** Clear separation of orchestration from core business logic.
|
| 59 |
+
|
| 60 |
+
* **`ConversationContextService` & `SmartContextManager`:**
|
| 61 |
+
* There's an overlap. `ConversationContextService` in `conversation_context_service.py` seems to be the intended manager for session data. `SmartContextManager` in `smart_context_manager.py` contains logic for *deciding* context use.
|
| 62 |
+
* **Action:**
|
| 63 |
+
1. Rename `ConversationContextService` to something more encompassing like `SessionManagerService` or `UserContextService`.
|
| 64 |
+
2. Merge the "smart" decision-making logic from `SmartContextManager` into this service or make `SmartContextManager` a sub-component that `EnhancedRecommendationService` consults. The goal is one primary service for all things related to user session and conversation context.
|
| 65 |
+
3. Ensure methods like `_extract_recently_shown_tracks` (currently in `EnhancedRecommendationService`) are part of this unified context service.
|
| 66 |
+
* **Rationale:** Consolidates all context-related logic into a single, authoritative service.
|
| 67 |
+
|
| 68 |
+
* **`APIService` & `MetadataService` & `CacheManager`:**
|
| 69 |
+
* **Action:** These seem well-defined. Ensure `APIService` is the *only* way agents/services interact with external APIs (Last.fm, Spotify). `MetadataService` should be the sole provider of `UnifiedTrackMetadata`, potentially using `APIService` and `CacheManager`.
|
| 70 |
+
* **Rationale:** Enforces a clean abstraction layer for external data and caching.
|
| 71 |
+
|
| 72 |
+
* **`LLMFallbackService`:**
|
| 73 |
+
* **Action:** This is a distinct concern and is fine as a separate service. Ensure it uses `LLMUtils` for its Gemini calls.
|
| 74 |
+
* **Rationale:** Keeps fallback logic isolated.
|
| 75 |
+
|
| 76 |
+
### 3. API Layer (`src/api/`)
|
| 77 |
+
|
| 78 |
+
* **`backend.py`:**
|
| 79 |
+
* **Action:** The `transform_unified_to_ui_format` function is UI-specific. Move it to `src/ui/response_formatter.py` or a new `src/ui/ui_utils.py`. The backend should ideally return data in a consistent internal format, and the UI layer transforms it.
|
| 80 |
+
* **Action:** Ensure all endpoints only call the `EnhancedRecommendationService` and do not contain business logic themselves.
|
| 81 |
+
* **Rationale:** Keeps backend clean and focused on API contracts, decouples it from UI presentation details.
|
| 82 |
+
|
| 83 |
+
* **Other API Files (`base_client.py`, `client_factory.py`, `lastfm_client.py`, `spotify_client.py`, `rate_limiter.py`, `logging_middleware.py`):**
|
| 84 |
+
* **Action:** This structure is generally good. Ensure `LastFmClient` and `SpotifyClient` strictly adhere to `BaseAPIClient` and are always created via `APIClientFactory`. `UnifiedRateLimiter` is a good abstraction.
|
| 85 |
+
* **Rationale:** Maintains consistency and reusability for external API interactions.
|
| 86 |
+
|
| 87 |
+
### 4. Models (`src/models/`)
|
| 88 |
+
|
| 89 |
+
* **Action:** Review `agent_models.py`, `metadata_models.py`, `recommendation_models.py`.
|
| 90 |
+
* Ensure `UnifiedTrackMetadata` and `UnifiedArtistMetadata` are the standard for passing track/artist data internally after fetching from external APIs.
|
| 91 |
+
* `MusicRecommenderState` is the central state object for LangGraph, which is good.
|
| 92 |
+
* Clarify if `TrackRecommendation` in `recommendation_models.py` is still needed or if `UnifiedTrackMetadata` (with its recommendation-specific fields) can serve that purpose. If `TrackRecommendation` is a UI-focused or Judge-output-focused model, ensure its distinction from `UnifiedTrackMetadata` is clear. It seems `TrackRecommendation` is used by `JudgeAgent`. This might be okay, but if it largely duplicates `UnifiedTrackMetadata`, consider merging or having it inherit. Given the current use, keeping it separate for the Judge's output and final UI presentation seems reasonable but ensure it's constructed from `UnifiedTrackMetadata`.
|
| 93 |
+
* **Rationale:** Consistent data representation reduces errors and improves understanding.
|
| 94 |
+
|
| 95 |
+
### 5. UI Layer (`src/ui/`)
|
| 96 |
+
|
| 97 |
+
* **Action:**
|
| 98 |
+
* `BeatDebateChatInterface` should interact cleanly with the `/recommendations` and `/planning` endpoints.
|
| 99 |
+
* The fallback logic in `BeatDebateChatInterface` using `LLMFallbackService` is good. Ensure the conditions for fallback (`_should_use_fallback`) are robust.
|
| 100 |
+
* Move `transform_unified_to_ui_format` here from `backend.py` (as mentioned above).
|
| 101 |
+
* **Rationale:** Separates UI concerns.
|
| 102 |
+
|
| 103 |
+
### 6. Tests (`tests/`)
|
| 104 |
+
|
| 105 |
+
|
| 106 |
+
* **Action:** Consolidate `tests/agents/test_enhanced_judge.py` and `tests/agents/test_judge_agent.py` if they test the same current `JudgeAgent`. If `test_enhanced_judge.py` was for an older version, it could be archived or removed if its tests are covered.
|
| 107 |
+
* **Rationale:** Better test organization.
|
| 108 |
+
|
| 109 |
+
### 7. Root Directory & Miscellaneous
|
| 110 |
+
|
| 111 |
+
* **`TODO/todo.md`:**
|
| 112 |
+
* **Action:** Review and integrate these TODOs into this refactoring plan or a subsequent one. The items "Enhanced Planner Agent", "Agent Improvements", "Enhanced Judge Agent" are covered by this plan.
|
| 113 |
+
* **Logging:**
|
| 114 |
+
* **Action:** `logging_config.py` and `logging.conf` provide good structured logging. Ensure all modules use `get_logger(__name__)` from `logging_config.py` for consistency.
|
| 115 |
+
* **Rationale:** Centralized and consistent logging.
|
| 116 |
+
|
| 117 |
+
---
|
| 118 |
+
|
| 119 |
+
**Code that is getting too large / needs most refactoring attention:**
|
| 120 |
+
|
| 121 |
+
1. **`src/agents/components/quality_scorer.py`:** While modular with sub-scorers, this file is very large.
|
| 122 |
+
* **Action:** Consider splitting the individual scorer classes (e.g., `AudioQualityScorer`, `PopularityBalancer`) into their own files within a new `src/agents/components/scoring/` subdirectory. The `ComprehensiveQualityScorer` would then import and compose them.
|
| 123 |
+
* **Rationale:** Improves readability and maintainability of individual scoring components.
|
| 124 |
+
|
| 125 |
+
2. **`src/agents/discovery/agent.py` & `src/agents/genre_mood/agent.py`:** These advocate agents, while using shared components, still have substantial internal logic for scoring, filtering, and adapting to intent.
|
| 126 |
+
* **Action:** Ensure *all* complex scoring/filtering logic that can be generalized is pushed down into `ComprehensiveQualityScorer` or new specific strategy classes that `QualityScorer` can use. Agents should primarily be responsible for *configuring* these shared components based on the planner's strategy.
|
| 127 |
+
* **Rationale:** Makes agents thinner and more focused on their unique task of "advocating" for a certain type of recommendation by configuring common tools.
|
| 128 |
+
|
| 129 |
+
3. **`src/services/enhanced_recommendation_service.py`:** As the central orchestrator, this file can grow.
|
| 130 |
+
* **Action:** Keep the LangGraph node functions (`_planner_node`, `_genre_mood_node`, etc.) as thin wrappers. The actual agent logic should reside within the agent classes. The context analysis logic (`ContextAwareIntentAnalyzer`) is already well-encapsulated.
|
| 131 |
+
* **Rationale:** Keeps orchestration logic clean.
|
| 132 |
+
|
| 133 |
+
4. **`src/agents/planner/agent.py`:**
|
| 134 |
+
* **Action:** If the context handling methods mentioned earlier (`_is_followup_with_preserved_context`, etc.) are deemed general enough, moving them to the unified `ConversationContextService` (or `SessionManagerService`) would reduce this agent's size.
|
| 135 |
+
* **Rationale:** Centralizes context transformation logic.
|
| 136 |
+
|
| 137 |
+
---
|
| 138 |
+
|
| 139 |
+
**Proposed Final Directory Structure (Illustrative Changes):**
|
| 140 |
+
|
| 141 |
+
```
|
| 142 |
+
BeatDebate/
|
| 143 |
+
βββ Design/
|
| 144 |
+
βββ scripts/
|
| 145 |
+
β βββ validate_lastfm.py
|
| 146 |
+
βββ src/
|
| 147 |
+
β βββ agents/
|
| 148 |
+
β β βββ base_agent.py
|
| 149 |
+
β β βββ components/
|
| 150 |
+
β β β βββ __init__.py
|
| 151 |
+
β β β βββ entity_extraction_utils.py
|
| 152 |
+
β β β βββ llm_utils.py
|
| 153 |
+
β β β βββ query_analysis_utils.py
|
| 154 |
+
β β β βββ unified_candidate_generator.py
|
| 155 |
+
β β β βββ scoring/ # New subdirectory for scorers
|
| 156 |
+
β β β βββ __init__.py
|
| 157 |
+
β β β βββ audio_quality_scorer.py
|
| 158 |
+
β β β βββ popularity_balancer.py
|
| 159 |
+
β β β βββ engagement_scorer.py
|
| 160 |
+
β β β βββ genre_mood_fit_scorer.py
|
| 161 |
+
β β β βββ intent_aware_scorer.py
|
| 162 |
+
β β β βββ comprehensive_quality_scorer.py # Main entry point, imports others
|
| 163 |
+
β β βββ planner/
|
| 164 |
+
β β β βββ __init__.py
|
| 165 |
+
β β β βββ agent.py
|
| 166 |
+
β β β βββ entity_recognizer.py
|
| 167 |
+
β β β βββ query_understanding_engine.py
|
| 168 |
+
β β βββ genre_mood/
|
| 169 |
+
β β β βββ __init__.py
|
| 170 |
+
β β β βββ agent.py
|
| 171 |
+
β β β βββ mood_logic.py
|
| 172 |
+
β β β βββ tag_generator.py
|
| 173 |
+
β β βββ discovery/
|
| 174 |
+
β β β βββ __init__.py
|
| 175 |
+
β β β βββ agent.py
|
| 176 |
+
β β β βββ similarity_explorer.py
|
| 177 |
+
β β β βββ underground_detector.py
|
| 178 |
+
β β βββ judge/
|
| 179 |
+
β β βββ __init__.py
|
| 180 |
+
β β βββ agent.py
|
| 181 |
+
β β βββ explainer.py
|
| 182 |
+
β β βββ ranking_logic.py
|
| 183 |
+
β βββ api/
|
| 184 |
+
β β βββ __init__.py
|
| 185 |
+
β β βββ backend.py
|
| 186 |
+
β β βββ base_client.py
|
| 187 |
+
β β βββ client_factory.py
|
| 188 |
+
β β βββ lastfm_client.py
|
| 189 |
+
β β βββ logging_middleware.py
|
| 190 |
+
β β βββ rate_limiter.py
|
| 191 |
+
β β βββ spotify_client.py
|
| 192 |
+
β βββ models/
|
| 193 |
+
β β βββ __init__.py
|
| 194 |
+
β β βββ agent_models.py
|
| 195 |
+
β β βββ metadata_models.py
|
| 196 |
+
β β βββ recommendation_models.py
|
| 197 |
+
β βββ services/
|
| 198 |
+
β β βββ __init__.py
|
| 199 |
+
β β βββ api_service.py
|
| 200 |
+
β β βββ cache_manager.py
|
| 201 |
+
β β βββ conversation_context_service.py # Potentially renamed & merged
|
| 202 |
+
β β βββ enhanced_recommendation_service.py
|
| 203 |
+
β β βββ llm_fallback_service.py
|
| 204 |
+
β β βββ metadata_service.py
|
| 205 |
+
β β # Removed smart_context_manager.py (logic merged or moved)
|
| 206 |
+
β βββ ui/
|
| 207 |
+
β β βββ __init__.py
|
| 208 |
+
β β βββ chat_interface.py
|
| 209 |
+
β β βββ planning_display.py
|
| 210 |
+
β β βββ response_formatter.py
|
| 211 |
+
β β βββ ui_utils.py # New for UI-specific transformations
|
| 212 |
+
β βββ utils/
|
| 213 |
+
β β βββ __init__.py
|
| 214 |
+
β β βββ logging_config.py
|
| 215 |
+
β βββ __init__.py
|
| 216 |
+
β βββ main.py
|
| 217 |
+
βββ tests/
|
| 218 |
+
β βββ agents/
|
| 219 |
+
β β βββ test_advocate_agents.py # Could be split into test_genre_mood.py, test_discovery.py
|
| 220 |
+
β β βββ test_enhanced_planner.py
|
| 221 |
+
β β βββ test_judge_agent.py # Consolidated judge tests
|
| 222 |
+
β β βββ test_planner_agent.py
|
| 223 |
+
β βββ services/
|
| 224 |
+
β β βββ __init__.py
|
| 225 |
+
β β βββ test_enhanced_recommendation_service.py
|
| 226 |
+
β β βββ test_llm_fallback_service.py
|
| 227 |
+
β β βββ test_recommendation_engine_integration.py
|
| 228 |
+
β β βββ test_recommendation_engine.py
|
| 229 |
+
β βββ ui/
|
| 230 |
+
β β βββ test_chat_interface_fallback.py
|
| 231 |
+
β βββ integration/ # New for broader integration tests
|
| 232 |
+
β β βββ test_intent_aware_backend_integration.py
|
| 233 |
+
β β βββ test_phase3_demo.py
|
| 234 |
+
β βββ scenarios/ # New for specific scenario tests
|
| 235 |
+
β βββ test_followup_behavior.py
|
| 236 |
+
β βββ test_followup_detection_fix.py
|
| 237 |
+
β βββ test_history_filtering.py
|
| 238 |
+
β βββ test_hybrid_context.py
|
| 239 |
+
β βββ test_kendrick_followup.py
|
| 240 |
+
β βββ test_simple_extraction.py
|
| 241 |
+
β βββ test_state_fix.py
|
| 242 |
+
βββ TODO/
|
| 243 |
+
β βββ todo.md # To be updated or removed after refactoring
|
| 244 |
+
βββ .flake8
|
| 245 |
+
βββ .gitignore
|
| 246 |
+
βββ app.py
|
| 247 |
+
βββ env.example
|
| 248 |
+
βββ logging.conf
|
| 249 |
+
βββ pyproject.toml
|
| 250 |
+
βββ README.md
|
| 251 |
+
βββ requirements.txt
|
| 252 |
+
```
|
| 253 |
+
|
| 254 |
+
---
|
| 255 |
+
|
| 256 |
+
This plan provides a structured approach. It's iterative; some decisions (like exactly where to move `_is_followup_with_preserved_context`) might become clearer during implementation. The key is to consistently apply the guiding principles.
|
src/agents/components/__init__.py
CHANGED
|
@@ -6,9 +6,10 @@ This module contains reusable components that eliminate duplication across agent
|
|
| 6 |
- Shared LLM utilities
|
| 7 |
- Entity extraction utilities
|
| 8 |
- Query analysis utilities
|
|
|
|
| 9 |
"""
|
| 10 |
|
| 11 |
-
from .
|
| 12 |
from .unified_candidate_generator import UnifiedCandidateGenerator
|
| 13 |
from .llm_utils import LLMUtils
|
| 14 |
from .entity_extraction_utils import EntityExtractionUtils
|
|
|
|
| 6 |
- Shared LLM utilities
|
| 7 |
- Entity extraction utilities
|
| 8 |
- Query analysis utilities
|
| 9 |
+
- Modular scoring system (now in scoring/ subdirectory)
|
| 10 |
"""
|
| 11 |
|
| 12 |
+
from .scoring import ComprehensiveQualityScorer as QualityScorer
|
| 13 |
from .unified_candidate_generator import UnifiedCandidateGenerator
|
| 14 |
from .llm_utils import LLMUtils
|
| 15 |
from .entity_extraction_utils import EntityExtractionUtils
|
src/agents/components/{quality_scorer.py β quality_scorer_backup.py}
RENAMED
|
File without changes
|
src/agents/components/scoring/__init__.py
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Scoring Components for BeatDebate
|
| 3 |
+
|
| 4 |
+
Modular scoring system for track quality assessment:
|
| 5 |
+
- AudioQualityScorer: Audio feature analysis
|
| 6 |
+
- PopularityBalancer: Popularity and underground scoring
|
| 7 |
+
- EngagementScorer: User engagement metrics
|
| 8 |
+
- GenreMoodFitScorer: Genre and mood matching
|
| 9 |
+
- IntentAwareScorer: Intent-specific scoring strategies
|
| 10 |
+
- ComprehensiveQualityScorer: Main entry point combining all scorers
|
| 11 |
+
"""
|
| 12 |
+
|
| 13 |
+
from .audio_quality_scorer import AudioQualityScorer
|
| 14 |
+
from .popularity_balancer import PopularityBalancer
|
| 15 |
+
from .engagement_scorer import EngagementScorer
|
| 16 |
+
from .genre_mood_fit_scorer import GenreMoodFitScorer
|
| 17 |
+
from .intent_aware_scorer import IntentAwareScorer
|
| 18 |
+
from .comprehensive_quality_scorer import ComprehensiveQualityScorer
|
| 19 |
+
|
| 20 |
+
__all__ = [
|
| 21 |
+
'AudioQualityScorer',
|
| 22 |
+
'PopularityBalancer',
|
| 23 |
+
'EngagementScorer',
|
| 24 |
+
'GenreMoodFitScorer',
|
| 25 |
+
'IntentAwareScorer',
|
| 26 |
+
'ComprehensiveQualityScorer'
|
| 27 |
+
]
|
src/agents/components/scoring/audio_quality_scorer.py
ADDED
|
@@ -0,0 +1,239 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Audio Quality Scorer for BeatDebate
|
| 3 |
+
|
| 4 |
+
Scores tracks based on audio feature analysis, evaluating energy, danceability,
|
| 5 |
+
valence, and other audio characteristics to determine musical quality and appropriateness.
|
| 6 |
+
"""
|
| 7 |
+
|
| 8 |
+
from typing import Dict
|
| 9 |
+
import structlog
|
| 10 |
+
|
| 11 |
+
logger = structlog.get_logger(__name__)
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
class AudioQualityScorer:
|
| 15 |
+
"""
|
| 16 |
+
Scores tracks based on audio feature analysis.
|
| 17 |
+
|
| 18 |
+
Evaluates energy, danceability, valence, and other audio characteristics
|
| 19 |
+
to determine musical quality and appropriateness.
|
| 20 |
+
"""
|
| 21 |
+
|
| 22 |
+
def __init__(self):
|
| 23 |
+
"""Initialize audio quality scorer with feature weights."""
|
| 24 |
+
self.logger = logger.bind(component="AudioQualityScorer")
|
| 25 |
+
|
| 26 |
+
# Feature weights for audio quality calculation
|
| 27 |
+
self.feature_weights = {
|
| 28 |
+
'energy': 0.20, # Energy level appropriateness
|
| 29 |
+
'danceability': 0.15, # Rhythmic quality
|
| 30 |
+
'valence': 0.15, # Emotional positivity
|
| 31 |
+
'acousticness': 0.10, # Acoustic vs electronic balance
|
| 32 |
+
'instrumentalness': 0.10, # Vocal vs instrumental balance
|
| 33 |
+
'liveness': 0.10, # Live recording quality
|
| 34 |
+
'speechiness': 0.10, # Speech content appropriateness
|
| 35 |
+
'tempo_consistency': 0.10 # Tempo stability
|
| 36 |
+
}
|
| 37 |
+
|
| 38 |
+
self.logger.info("Audio Quality Scorer initialized")
|
| 39 |
+
|
| 40 |
+
def calculate_audio_quality_score(self, track_features: Dict, intent_analysis: Dict) -> float:
|
| 41 |
+
"""
|
| 42 |
+
Calculate quality score based on audio features.
|
| 43 |
+
|
| 44 |
+
Args:
|
| 45 |
+
track_features: Audio features from Last.fm or Spotify
|
| 46 |
+
intent_analysis: User intent for context-aware scoring
|
| 47 |
+
|
| 48 |
+
Returns:
|
| 49 |
+
Audio quality score (0.0 - 1.0)
|
| 50 |
+
"""
|
| 51 |
+
try:
|
| 52 |
+
quality_score = 0.0
|
| 53 |
+
|
| 54 |
+
# Energy optimization based on intent
|
| 55 |
+
energy_score = self._score_energy(track_features, intent_analysis)
|
| 56 |
+
quality_score += energy_score * self.feature_weights['energy']
|
| 57 |
+
|
| 58 |
+
# Danceability scoring
|
| 59 |
+
danceability_score = self._score_danceability(track_features, intent_analysis)
|
| 60 |
+
quality_score += danceability_score * self.feature_weights['danceability']
|
| 61 |
+
|
| 62 |
+
# Valence (mood) scoring
|
| 63 |
+
valence_score = self._score_valence(track_features, intent_analysis)
|
| 64 |
+
quality_score += valence_score * self.feature_weights['valence']
|
| 65 |
+
|
| 66 |
+
# Acousticness balance
|
| 67 |
+
acousticness_score = self._score_acousticness(track_features, intent_analysis)
|
| 68 |
+
quality_score += acousticness_score * self.feature_weights['acousticness']
|
| 69 |
+
|
| 70 |
+
# Instrumentalness balance
|
| 71 |
+
instrumentalness_score = self._score_instrumentalness(track_features, intent_analysis)
|
| 72 |
+
quality_score += instrumentalness_score * self.feature_weights['instrumentalness']
|
| 73 |
+
|
| 74 |
+
# Liveness quality
|
| 75 |
+
liveness_score = self._score_liveness(track_features)
|
| 76 |
+
quality_score += liveness_score * self.feature_weights['liveness']
|
| 77 |
+
|
| 78 |
+
# Speechiness appropriateness
|
| 79 |
+
speechiness_score = self._score_speechiness(track_features, intent_analysis)
|
| 80 |
+
quality_score += speechiness_score * self.feature_weights['speechiness']
|
| 81 |
+
|
| 82 |
+
# Tempo consistency
|
| 83 |
+
tempo_score = self._score_tempo(track_features, intent_analysis)
|
| 84 |
+
quality_score += tempo_score * self.feature_weights['tempo_consistency']
|
| 85 |
+
|
| 86 |
+
final_score = min(1.0, max(0.0, quality_score))
|
| 87 |
+
|
| 88 |
+
self.logger.debug(
|
| 89 |
+
"Audio quality calculated",
|
| 90 |
+
score=final_score,
|
| 91 |
+
energy=energy_score,
|
| 92 |
+
danceability=danceability_score,
|
| 93 |
+
valence=valence_score
|
| 94 |
+
)
|
| 95 |
+
|
| 96 |
+
return final_score
|
| 97 |
+
|
| 98 |
+
except Exception as e:
|
| 99 |
+
self.logger.warning("Audio quality calculation failed", error=str(e))
|
| 100 |
+
return 0.5 # Default neutral score
|
| 101 |
+
|
| 102 |
+
def _score_energy(self, features: Dict, intent: Dict) -> float:
|
| 103 |
+
"""Score energy level based on intent context."""
|
| 104 |
+
energy = features.get('energy', 0.5)
|
| 105 |
+
|
| 106 |
+
# Get activity context for energy preferences
|
| 107 |
+
primary_intent = intent.get('primary_intent', 'discovery')
|
| 108 |
+
|
| 109 |
+
# Energy preferences by intent
|
| 110 |
+
energy_preferences = {
|
| 111 |
+
'concentration': 0.3, # Lower energy for focus
|
| 112 |
+
'relaxation': 0.2, # Very low energy for relaxation
|
| 113 |
+
'energy': 0.8, # High energy for energetic activities
|
| 114 |
+
'discovery': 0.5, # Balanced energy for discovery
|
| 115 |
+
'workout': 0.9, # Very high energy for workouts
|
| 116 |
+
'study': 0.3 # Lower energy for studying
|
| 117 |
+
}
|
| 118 |
+
|
| 119 |
+
target_energy = energy_preferences.get(primary_intent, 0.5)
|
| 120 |
+
|
| 121 |
+
# Score based on distance from target
|
| 122 |
+
energy_distance = abs(energy - target_energy)
|
| 123 |
+
energy_score = 1.0 - (energy_distance / 1.0) # Normalize to 0-1
|
| 124 |
+
|
| 125 |
+
return max(0.0, energy_score)
|
| 126 |
+
|
| 127 |
+
def _score_danceability(self, features: Dict, intent: Dict) -> float:
|
| 128 |
+
"""Score danceability based on context."""
|
| 129 |
+
danceability = features.get('danceability', 0.5)
|
| 130 |
+
|
| 131 |
+
# Higher danceability is generally positive
|
| 132 |
+
# But adjust based on intent
|
| 133 |
+
primary_intent = intent.get('primary_intent', 'discovery')
|
| 134 |
+
|
| 135 |
+
if primary_intent in ['workout', 'energy', 'party']:
|
| 136 |
+
# High danceability preferred
|
| 137 |
+
return danceability
|
| 138 |
+
elif primary_intent in ['concentration', 'study', 'relaxation']:
|
| 139 |
+
# Moderate danceability preferred
|
| 140 |
+
return 1.0 - abs(danceability - 0.4) / 0.6
|
| 141 |
+
else:
|
| 142 |
+
# Balanced approach
|
| 143 |
+
return danceability * 0.8 + 0.2
|
| 144 |
+
|
| 145 |
+
def _score_valence(self, features: Dict, intent: Dict) -> float:
|
| 146 |
+
"""Score valence (musical positivity) based on intent."""
|
| 147 |
+
valence = features.get('valence', 0.5)
|
| 148 |
+
|
| 149 |
+
primary_intent = intent.get('primary_intent', 'discovery')
|
| 150 |
+
|
| 151 |
+
# Valence preferences by intent
|
| 152 |
+
if primary_intent in ['energy', 'workout', 'party']:
|
| 153 |
+
# Higher valence preferred for energetic activities
|
| 154 |
+
return valence
|
| 155 |
+
elif primary_intent in ['relaxation', 'study']:
|
| 156 |
+
# Moderate valence preferred
|
| 157 |
+
return 1.0 - abs(valence - 0.4) / 0.6
|
| 158 |
+
else:
|
| 159 |
+
# Avoid extremes, prefer moderate positivity
|
| 160 |
+
return 1.0 - abs(valence - 0.6) / 0.6
|
| 161 |
+
|
| 162 |
+
def _score_acousticness(self, features: Dict, intent: Dict) -> float:
|
| 163 |
+
"""Score acousticness based on context preferences."""
|
| 164 |
+
acousticness = features.get('acousticness', 0.5)
|
| 165 |
+
|
| 166 |
+
primary_intent = intent.get('primary_intent', 'discovery')
|
| 167 |
+
|
| 168 |
+
if primary_intent in ['relaxation', 'study', 'concentration']:
|
| 169 |
+
# Higher acousticness preferred for calm activities
|
| 170 |
+
return acousticness
|
| 171 |
+
elif primary_intent in ['workout', 'energy', 'party']:
|
| 172 |
+
# Lower acousticness (more electronic) preferred
|
| 173 |
+
return 1.0 - acousticness
|
| 174 |
+
else:
|
| 175 |
+
# Balanced preference
|
| 176 |
+
return 1.0 - abs(acousticness - 0.5) / 0.5
|
| 177 |
+
|
| 178 |
+
def _score_instrumentalness(self, features: Dict, intent: Dict) -> float:
|
| 179 |
+
"""Score instrumentalness based on context."""
|
| 180 |
+
instrumentalness = features.get('instrumentalness', 0.5)
|
| 181 |
+
|
| 182 |
+
primary_intent = intent.get('primary_intent', 'discovery')
|
| 183 |
+
|
| 184 |
+
if primary_intent in ['concentration', 'study']:
|
| 185 |
+
# Higher instrumentalness preferred for focus
|
| 186 |
+
return instrumentalness
|
| 187 |
+
else:
|
| 188 |
+
# Generally prefer some vocals
|
| 189 |
+
return 1.0 - (instrumentalness * 0.6)
|
| 190 |
+
|
| 191 |
+
def _score_liveness(self, features: Dict) -> float:
|
| 192 |
+
"""Score liveness - generally prefer studio recordings."""
|
| 193 |
+
liveness = features.get('liveness', 0.1)
|
| 194 |
+
|
| 195 |
+
# Prefer studio recordings (lower liveness)
|
| 196 |
+
# But don't penalize too heavily
|
| 197 |
+
return 1.0 - (liveness * 0.5)
|
| 198 |
+
|
| 199 |
+
def _score_speechiness(self, features: Dict, intent: Dict) -> float:
|
| 200 |
+
"""Score speechiness based on context."""
|
| 201 |
+
speechiness = features.get('speechiness', 0.1)
|
| 202 |
+
|
| 203 |
+
primary_intent = intent.get('primary_intent', 'discovery')
|
| 204 |
+
|
| 205 |
+
if primary_intent in ['concentration', 'study']:
|
| 206 |
+
# Lower speechiness preferred for focus
|
| 207 |
+
return 1.0 - speechiness
|
| 208 |
+
else:
|
| 209 |
+
# Moderate speechiness is fine
|
| 210 |
+
return 1.0 - (speechiness * 0.3)
|
| 211 |
+
|
| 212 |
+
def _score_tempo(self, features: Dict, intent: Dict) -> float:
|
| 213 |
+
"""Score tempo appropriateness."""
|
| 214 |
+
tempo = features.get('tempo', 120)
|
| 215 |
+
|
| 216 |
+
primary_intent = intent.get('primary_intent', 'discovery')
|
| 217 |
+
|
| 218 |
+
# Tempo preferences by intent
|
| 219 |
+
tempo_preferences = {
|
| 220 |
+
'concentration': (80, 110), # Slower tempo for focus
|
| 221 |
+
'relaxation': (60, 100), # Very slow tempo
|
| 222 |
+
'energy': (120, 180), # Fast tempo for energy
|
| 223 |
+
'workout': (130, 170), # High tempo for workouts
|
| 224 |
+
'study': (80, 120), # Moderate tempo for studying
|
| 225 |
+
'discovery': (90, 140) # Wide range for discovery
|
| 226 |
+
}
|
| 227 |
+
|
| 228 |
+
min_tempo, max_tempo = tempo_preferences.get(primary_intent, (90, 140))
|
| 229 |
+
|
| 230 |
+
if min_tempo <= tempo <= max_tempo:
|
| 231 |
+
return 1.0
|
| 232 |
+
elif tempo < min_tempo:
|
| 233 |
+
# Too slow
|
| 234 |
+
distance = min_tempo - tempo
|
| 235 |
+
return max(0.0, 1.0 - (distance / 50))
|
| 236 |
+
else:
|
| 237 |
+
# Too fast
|
| 238 |
+
distance = tempo - max_tempo
|
| 239 |
+
return max(0.0, 1.0 - (distance / 50))
|
src/agents/components/scoring/comprehensive_quality_scorer.py
ADDED
|
@@ -0,0 +1,368 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Comprehensive Quality Scorer for BeatDebate
|
| 3 |
+
|
| 4 |
+
Main quality scoring system that combines all scoring components.
|
| 5 |
+
This is the primary entry point for quality assessment, coordinating
|
| 6 |
+
all individual scoring components.
|
| 7 |
+
"""
|
| 8 |
+
|
| 9 |
+
from typing import Dict, Any
|
| 10 |
+
import structlog
|
| 11 |
+
|
| 12 |
+
from .audio_quality_scorer import AudioQualityScorer
|
| 13 |
+
from .popularity_balancer import PopularityBalancer
|
| 14 |
+
from .engagement_scorer import EngagementScorer
|
| 15 |
+
from .genre_mood_fit_scorer import GenreMoodFitScorer
|
| 16 |
+
from .intent_aware_scorer import IntentAwareScorer
|
| 17 |
+
|
| 18 |
+
logger = structlog.get_logger(__name__)
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
class ComprehensiveQualityScorer:
|
| 22 |
+
"""
|
| 23 |
+
Main quality scoring system that combines all scoring components.
|
| 24 |
+
"""
|
| 25 |
+
|
| 26 |
+
def __init__(self):
|
| 27 |
+
"""Initialize comprehensive quality scorer."""
|
| 28 |
+
self.logger = logger.bind(component="QualityScorer")
|
| 29 |
+
|
| 30 |
+
# Initialize component scorers
|
| 31 |
+
self.audio_scorer = AudioQualityScorer()
|
| 32 |
+
self.popularity_balancer = PopularityBalancer()
|
| 33 |
+
self.engagement_scorer = EngagementScorer()
|
| 34 |
+
self.genre_mood_scorer = GenreMoodFitScorer()
|
| 35 |
+
self.intent_aware_scorer = IntentAwareScorer()
|
| 36 |
+
|
| 37 |
+
# Component weights for final score
|
| 38 |
+
self.component_weights = {
|
| 39 |
+
'audio_quality': 0.40, # Audio features quality
|
| 40 |
+
'popularity_balance': 0.25, # Popularity balance
|
| 41 |
+
'engagement': 0.20, # User engagement signals
|
| 42 |
+
'genre_mood_fit': 0.15 # Genre/mood fit
|
| 43 |
+
}
|
| 44 |
+
|
| 45 |
+
self.logger.info("Comprehensive Quality Scorer initialized")
|
| 46 |
+
|
| 47 |
+
async def calculate_track_quality(
|
| 48 |
+
self,
|
| 49 |
+
track_data: Dict,
|
| 50 |
+
entities: Dict[str, Any],
|
| 51 |
+
intent_analysis: Dict[str, Any]
|
| 52 |
+
) -> Dict[str, Any]:
|
| 53 |
+
"""
|
| 54 |
+
Calculate comprehensive quality score for a track.
|
| 55 |
+
|
| 56 |
+
Args:
|
| 57 |
+
track_data: Track metadata and features
|
| 58 |
+
entities: Extracted entities from PlannerAgent
|
| 59 |
+
intent_analysis: Intent analysis from PlannerAgent
|
| 60 |
+
|
| 61 |
+
Returns:
|
| 62 |
+
Dictionary with quality score and breakdown
|
| 63 |
+
"""
|
| 64 |
+
try:
|
| 65 |
+
# Get audio features (placeholder - would integrate with Spotify API)
|
| 66 |
+
audio_features = self._get_audio_features_placeholder(track_data)
|
| 67 |
+
|
| 68 |
+
# Calculate component scores
|
| 69 |
+
audio_quality = self.audio_scorer.calculate_audio_quality_score(
|
| 70 |
+
audio_features, intent_analysis
|
| 71 |
+
)
|
| 72 |
+
|
| 73 |
+
popularity_score = self.popularity_balancer.calculate_popularity_score(
|
| 74 |
+
listeners=int(track_data.get('listeners', 0)),
|
| 75 |
+
playcount=int(track_data.get('playcount', 0)),
|
| 76 |
+
exploration_openness=intent_analysis.get('exploration_openness', 0.5),
|
| 77 |
+
entities=entities,
|
| 78 |
+
intent_analysis=intent_analysis
|
| 79 |
+
)
|
| 80 |
+
|
| 81 |
+
engagement_score = await self.engagement_scorer.calculate_engagement_score(
|
| 82 |
+
track_data, intent_analysis
|
| 83 |
+
)
|
| 84 |
+
|
| 85 |
+
genre_mood_fit = self.genre_mood_scorer.calculate_genre_mood_fit(
|
| 86 |
+
track_data, entities, intent_analysis
|
| 87 |
+
)
|
| 88 |
+
|
| 89 |
+
# Calculate weighted total score
|
| 90 |
+
total_quality = (
|
| 91 |
+
audio_quality * self.component_weights['audio_quality'] +
|
| 92 |
+
popularity_score * self.component_weights['popularity_balance'] +
|
| 93 |
+
engagement_score * self.component_weights['engagement'] +
|
| 94 |
+
genre_mood_fit * self.component_weights['genre_mood_fit']
|
| 95 |
+
)
|
| 96 |
+
|
| 97 |
+
quality_result = {
|
| 98 |
+
'total_quality_score': total_quality,
|
| 99 |
+
'quality_breakdown': {
|
| 100 |
+
'audio_quality': audio_quality,
|
| 101 |
+
'popularity_balance': popularity_score,
|
| 102 |
+
'engagement': engagement_score,
|
| 103 |
+
'genre_mood_fit': genre_mood_fit
|
| 104 |
+
},
|
| 105 |
+
'component_weights': self.component_weights,
|
| 106 |
+
'quality_tier': self._determine_quality_tier(total_quality)
|
| 107 |
+
}
|
| 108 |
+
|
| 109 |
+
self.logger.debug(
|
| 110 |
+
"Track quality calculated",
|
| 111 |
+
track=f"{track_data.get('artist', 'Unknown')} - {track_data.get('name', 'Unknown')}",
|
| 112 |
+
total_score=total_quality,
|
| 113 |
+
tier=quality_result['quality_tier']
|
| 114 |
+
)
|
| 115 |
+
|
| 116 |
+
return quality_result
|
| 117 |
+
|
| 118 |
+
except Exception as e:
|
| 119 |
+
self.logger.error("Quality calculation failed", error=str(e))
|
| 120 |
+
return {
|
| 121 |
+
'total_quality_score': 0.5,
|
| 122 |
+
'quality_breakdown': {},
|
| 123 |
+
'component_weights': self.component_weights,
|
| 124 |
+
'quality_tier': 'medium'
|
| 125 |
+
}
|
| 126 |
+
|
| 127 |
+
def _get_audio_features_placeholder(self, track_data: Dict) -> Dict:
|
| 128 |
+
"""
|
| 129 |
+
Placeholder for audio features - would integrate with Spotify API.
|
| 130 |
+
|
| 131 |
+
For now, generate reasonable defaults based on available data.
|
| 132 |
+
"""
|
| 133 |
+
# Generate reasonable defaults based on source and metadata
|
| 134 |
+
source = track_data.get('source', 'unknown')
|
| 135 |
+
|
| 136 |
+
if source == 'underground_gems':
|
| 137 |
+
# Underground tracks tend to be more experimental
|
| 138 |
+
return {
|
| 139 |
+
'energy': 0.6,
|
| 140 |
+
'danceability': 0.5,
|
| 141 |
+
'valence': 0.4,
|
| 142 |
+
'acousticness': 0.6,
|
| 143 |
+
'instrumentalness': 0.3,
|
| 144 |
+
'liveness': 0.2,
|
| 145 |
+
'speechiness': 0.1,
|
| 146 |
+
'tempo': 110
|
| 147 |
+
}
|
| 148 |
+
elif source == 'primary_search':
|
| 149 |
+
# Primary search results tend to be more mainstream
|
| 150 |
+
return {
|
| 151 |
+
'energy': 0.7,
|
| 152 |
+
'danceability': 0.6,
|
| 153 |
+
'valence': 0.6,
|
| 154 |
+
'acousticness': 0.3,
|
| 155 |
+
'instrumentalness': 0.2,
|
| 156 |
+
'liveness': 0.1,
|
| 157 |
+
'speechiness': 0.1,
|
| 158 |
+
'tempo': 120
|
| 159 |
+
}
|
| 160 |
+
else:
|
| 161 |
+
# Default balanced features
|
| 162 |
+
return {
|
| 163 |
+
'energy': 0.6,
|
| 164 |
+
'danceability': 0.6,
|
| 165 |
+
'valence': 0.5,
|
| 166 |
+
'acousticness': 0.4,
|
| 167 |
+
'instrumentalness': 0.2,
|
| 168 |
+
'liveness': 0.1,
|
| 169 |
+
'speechiness': 0.1,
|
| 170 |
+
'tempo': 115
|
| 171 |
+
}
|
| 172 |
+
|
| 173 |
+
def _determine_quality_tier(self, quality_score: float) -> str:
|
| 174 |
+
"""Determine quality tier based on score."""
|
| 175 |
+
if quality_score >= 0.8:
|
| 176 |
+
return 'excellent'
|
| 177 |
+
elif quality_score >= 0.7:
|
| 178 |
+
return 'high'
|
| 179 |
+
elif quality_score >= 0.6:
|
| 180 |
+
return 'good'
|
| 181 |
+
elif quality_score >= 0.4:
|
| 182 |
+
return 'medium'
|
| 183 |
+
else:
|
| 184 |
+
return 'low'
|
| 185 |
+
|
| 186 |
+
async def calculate_quality_score(
|
| 187 |
+
self,
|
| 188 |
+
track_data: Dict,
|
| 189 |
+
entities: Dict[str, Any],
|
| 190 |
+
intent_analysis: Dict[str, Any]
|
| 191 |
+
) -> float:
|
| 192 |
+
"""
|
| 193 |
+
Calculate quality score for a track (simplified version).
|
| 194 |
+
|
| 195 |
+
Args:
|
| 196 |
+
track_data: Track metadata and features
|
| 197 |
+
entities: Extracted entities from PlannerAgent
|
| 198 |
+
intent_analysis: Intent analysis from PlannerAgent
|
| 199 |
+
|
| 200 |
+
Returns:
|
| 201 |
+
Quality score (0.0 - 1.0)
|
| 202 |
+
"""
|
| 203 |
+
try:
|
| 204 |
+
# Use the comprehensive calculation and return just the score
|
| 205 |
+
quality_result = await self.calculate_track_quality(
|
| 206 |
+
track_data, entities, intent_analysis
|
| 207 |
+
)
|
| 208 |
+
return quality_result['total_quality_score']
|
| 209 |
+
|
| 210 |
+
except Exception as e:
|
| 211 |
+
self.logger.error("Quality score calculation failed", error=str(e))
|
| 212 |
+
return 0.5 # Default neutral score
|
| 213 |
+
|
| 214 |
+
def calculate_intent_aware_scores(
|
| 215 |
+
self,
|
| 216 |
+
track_data: Dict,
|
| 217 |
+
entities: Dict[str, Any],
|
| 218 |
+
intent_analysis: Dict[str, Any],
|
| 219 |
+
intent: str
|
| 220 |
+
) -> Dict[str, float]:
|
| 221 |
+
"""
|
| 222 |
+
π§ NEW: Calculate all intent-aware scoring components.
|
| 223 |
+
|
| 224 |
+
This provides all the scoring components needed by our ranking logic
|
| 225 |
+
for different intent types and hybrid sub-types.
|
| 226 |
+
|
| 227 |
+
Args:
|
| 228 |
+
track_data: Track metadata
|
| 229 |
+
entities: Musical entities
|
| 230 |
+
intent_analysis: Intent analysis results
|
| 231 |
+
intent: Intent type (including hybrid sub-types)
|
| 232 |
+
|
| 233 |
+
Returns:
|
| 234 |
+
Dictionary with all scoring components
|
| 235 |
+
"""
|
| 236 |
+
try:
|
| 237 |
+
scores = {}
|
| 238 |
+
|
| 239 |
+
# β
Basic quality score (always needed)
|
| 240 |
+
scores['quality'] = self.calculate_quality_score_sync(track_data, entities, intent_analysis)
|
| 241 |
+
|
| 242 |
+
# β
Genre/mood match score (always needed)
|
| 243 |
+
scores['genre_mood_match'] = self.genre_mood_scorer.calculate_genre_mood_fit(
|
| 244 |
+
track_data, entities, intent_analysis
|
| 245 |
+
)
|
| 246 |
+
scores['contextual_relevance'] = scores['genre_mood_match'] # Alias for compatibility
|
| 247 |
+
|
| 248 |
+
# π§ FIXED: Novelty score using intent-aware calculation
|
| 249 |
+
scores['novelty'] = self.intent_aware_scorer.calculate_novelty_score(
|
| 250 |
+
track_data, intent, entities
|
| 251 |
+
)
|
| 252 |
+
scores['novelty_score'] = scores['novelty'] # Alias for compatibility
|
| 253 |
+
|
| 254 |
+
# β
Similarity score (for artist similarity intents)
|
| 255 |
+
scores['similarity'] = self.intent_aware_scorer.calculate_similarity_score(
|
| 256 |
+
track_data, entities, intent_analysis
|
| 257 |
+
)
|
| 258 |
+
|
| 259 |
+
# β
Target artist boost (for artist similarity intents)
|
| 260 |
+
scores['target_artist_boost'] = self.intent_aware_scorer.calculate_target_artist_boost(
|
| 261 |
+
track_data, entities
|
| 262 |
+
)
|
| 263 |
+
|
| 264 |
+
# β
Underground score (for discovery intents)
|
| 265 |
+
scores['underground'] = self.intent_aware_scorer.calculate_underground_score(
|
| 266 |
+
track_data, intent
|
| 267 |
+
)
|
| 268 |
+
|
| 269 |
+
# β
Context fit score (for contextual intents)
|
| 270 |
+
scores['context_fit'] = self.intent_aware_scorer.calculate_context_fit_score(
|
| 271 |
+
track_data, intent_analysis, entities
|
| 272 |
+
)
|
| 273 |
+
|
| 274 |
+
# β
Familiarity score (for contextual intents)
|
| 275 |
+
scores['familiarity'] = self.intent_aware_scorer.calculate_familiarity_score(
|
| 276 |
+
track_data, intent_analysis
|
| 277 |
+
)
|
| 278 |
+
|
| 279 |
+
# π§ Compatibility scores
|
| 280 |
+
scores['quality_score'] = scores['quality']
|
| 281 |
+
scores['relevance_score'] = scores['genre_mood_match']
|
| 282 |
+
|
| 283 |
+
self.logger.debug(
|
| 284 |
+
"Intent-aware scores calculated",
|
| 285 |
+
intent=intent,
|
| 286 |
+
novelty=scores['novelty'],
|
| 287 |
+
similarity=scores['similarity'],
|
| 288 |
+
quality=scores['quality'],
|
| 289 |
+
track=f"{track_data.get('artist', 'Unknown')} - {track_data.get('name', 'Unknown')}"
|
| 290 |
+
)
|
| 291 |
+
|
| 292 |
+
return scores
|
| 293 |
+
|
| 294 |
+
except Exception as e:
|
| 295 |
+
self.logger.error("Intent-aware scoring failed", error=str(e))
|
| 296 |
+
return {
|
| 297 |
+
'quality': 0.5,
|
| 298 |
+
'genre_mood_match': 0.5,
|
| 299 |
+
'contextual_relevance': 0.5,
|
| 300 |
+
'novelty': 0.5,
|
| 301 |
+
'novelty_score': 0.5,
|
| 302 |
+
'similarity': 0.0,
|
| 303 |
+
'target_artist_boost': 0.0,
|
| 304 |
+
'underground': 0.5,
|
| 305 |
+
'context_fit': 0.5,
|
| 306 |
+
'familiarity': 0.5,
|
| 307 |
+
'quality_score': 0.5,
|
| 308 |
+
'relevance_score': 0.5
|
| 309 |
+
}
|
| 310 |
+
|
| 311 |
+
def calculate_quality_score_sync(
|
| 312 |
+
self,
|
| 313 |
+
track_data: Dict,
|
| 314 |
+
entities: Dict[str, Any],
|
| 315 |
+
intent_analysis: Dict[str, Any]
|
| 316 |
+
) -> float:
|
| 317 |
+
"""
|
| 318 |
+
Synchronous version of quality score calculation.
|
| 319 |
+
|
| 320 |
+
Args:
|
| 321 |
+
track_data: Track metadata and features
|
| 322 |
+
entities: Extracted entities from PlannerAgent
|
| 323 |
+
intent_analysis: Intent analysis from PlannerAgent
|
| 324 |
+
|
| 325 |
+
Returns:
|
| 326 |
+
Quality score (0.0 - 1.0)
|
| 327 |
+
"""
|
| 328 |
+
try:
|
| 329 |
+
# Get audio features (placeholder)
|
| 330 |
+
audio_features = self._get_audio_features_placeholder(track_data)
|
| 331 |
+
|
| 332 |
+
# Calculate component scores (simplified for sync version)
|
| 333 |
+
audio_quality = self.audio_scorer.calculate_audio_quality_score(
|
| 334 |
+
audio_features, intent_analysis
|
| 335 |
+
)
|
| 336 |
+
|
| 337 |
+
popularity_score = self.popularity_balancer.calculate_popularity_score(
|
| 338 |
+
listeners=int(track_data.get('listeners', 0)),
|
| 339 |
+
playcount=int(track_data.get('playcount', 0)),
|
| 340 |
+
exploration_openness=intent_analysis.get('exploration_openness', 0.5),
|
| 341 |
+
entities=entities,
|
| 342 |
+
intent_analysis=intent_analysis
|
| 343 |
+
)
|
| 344 |
+
|
| 345 |
+
# Simplified engagement score (skip async calculation)
|
| 346 |
+
engagement_score = 0.5
|
| 347 |
+
|
| 348 |
+
genre_mood_fit = self.genre_mood_scorer.calculate_genre_mood_fit(
|
| 349 |
+
track_data, entities, intent_analysis
|
| 350 |
+
)
|
| 351 |
+
|
| 352 |
+
# Calculate weighted total score
|
| 353 |
+
total_quality = (
|
| 354 |
+
audio_quality * self.component_weights['audio_quality'] +
|
| 355 |
+
popularity_score * self.component_weights['popularity_balance'] +
|
| 356 |
+
engagement_score * self.component_weights['engagement'] +
|
| 357 |
+
genre_mood_fit * self.component_weights['genre_mood_fit']
|
| 358 |
+
)
|
| 359 |
+
|
| 360 |
+
return min(1.0, max(0.0, total_quality))
|
| 361 |
+
|
| 362 |
+
except Exception as e:
|
| 363 |
+
self.logger.error("Sync quality score calculation failed", error=str(e))
|
| 364 |
+
return 0.5 # Default neutral score
|
| 365 |
+
|
| 366 |
+
|
| 367 |
+
# π§ Export the main scorer class for easy importing
|
| 368 |
+
QualityScorer = ComprehensiveQualityScorer
|
src/agents/components/scoring/engagement_scorer.py
ADDED
|
@@ -0,0 +1,97 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Engagement Scorer for BeatDebate
|
| 3 |
+
|
| 4 |
+
Scores tracks based on user engagement signals and track characteristics,
|
| 5 |
+
including engagement rates, recency, and tag diversity.
|
| 6 |
+
"""
|
| 7 |
+
|
| 8 |
+
from typing import Dict
|
| 9 |
+
import structlog
|
| 10 |
+
|
| 11 |
+
logger = structlog.get_logger(__name__)
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
class EngagementScorer:
|
| 15 |
+
"""
|
| 16 |
+
Scores tracks based on user engagement signals and track characteristics.
|
| 17 |
+
"""
|
| 18 |
+
|
| 19 |
+
def __init__(self):
|
| 20 |
+
"""Initialize engagement scorer."""
|
| 21 |
+
self.logger = logger.bind(component="EngagementScorer")
|
| 22 |
+
self.logger.info("Engagement Scorer initialized")
|
| 23 |
+
|
| 24 |
+
async def calculate_engagement_score(
|
| 25 |
+
self,
|
| 26 |
+
track_data: Dict,
|
| 27 |
+
intent_analysis: Dict
|
| 28 |
+
) -> float:
|
| 29 |
+
"""
|
| 30 |
+
Calculate engagement score based on various signals.
|
| 31 |
+
|
| 32 |
+
Args:
|
| 33 |
+
track_data: Track metadata and statistics
|
| 34 |
+
intent_analysis: User intent for context
|
| 35 |
+
|
| 36 |
+
Returns:
|
| 37 |
+
Engagement score (0.0 - 1.0)
|
| 38 |
+
"""
|
| 39 |
+
try:
|
| 40 |
+
# Calculate engagement rate (plays per listener)
|
| 41 |
+
engagement_rate = self._calculate_engagement_rate(track_data)
|
| 42 |
+
|
| 43 |
+
# Calculate recency score (newer tracks get slight boost)
|
| 44 |
+
recency_score = self._calculate_recency_score(track_data)
|
| 45 |
+
|
| 46 |
+
# Calculate tag diversity score
|
| 47 |
+
tag_diversity = self._calculate_tag_diversity(track_data)
|
| 48 |
+
|
| 49 |
+
# Combine scores with weights
|
| 50 |
+
total_engagement = (
|
| 51 |
+
engagement_rate * 0.5 +
|
| 52 |
+
recency_score * 0.3 +
|
| 53 |
+
tag_diversity * 0.2
|
| 54 |
+
)
|
| 55 |
+
|
| 56 |
+
self.logger.debug(
|
| 57 |
+
"Engagement score calculated",
|
| 58 |
+
engagement_rate=engagement_rate,
|
| 59 |
+
recency_score=recency_score,
|
| 60 |
+
tag_diversity=tag_diversity,
|
| 61 |
+
total_score=total_engagement
|
| 62 |
+
)
|
| 63 |
+
|
| 64 |
+
return min(1.0, max(0.0, total_engagement))
|
| 65 |
+
|
| 66 |
+
except Exception as e:
|
| 67 |
+
self.logger.warning("Engagement scoring failed", error=str(e))
|
| 68 |
+
return 0.5 # Default neutral score
|
| 69 |
+
|
| 70 |
+
def _calculate_engagement_rate(self, track_data: Dict) -> float:
|
| 71 |
+
"""Calculate engagement rate from play counts and listeners."""
|
| 72 |
+
playcount = int(track_data.get('playcount') or 0)
|
| 73 |
+
listeners = int(track_data.get('listeners') or 1) # Avoid division by zero
|
| 74 |
+
|
| 75 |
+
# Ensure we don't divide by zero
|
| 76 |
+
if listeners == 0:
|
| 77 |
+
listeners = 1
|
| 78 |
+
|
| 79 |
+
# Calculate plays per listener
|
| 80 |
+
engagement_rate = playcount / listeners
|
| 81 |
+
|
| 82 |
+
# Normalize to 0-1 scale (50 plays per listener = 1.0)
|
| 83 |
+
normalized_rate = min(1.0, engagement_rate / 50.0)
|
| 84 |
+
|
| 85 |
+
return normalized_rate
|
| 86 |
+
|
| 87 |
+
def _calculate_recency_score(self, track_data: Dict) -> float:
|
| 88 |
+
"""Calculate recency score - slight boost for newer tracks."""
|
| 89 |
+
# This is a placeholder - would need release date data
|
| 90 |
+
# For now, return neutral score
|
| 91 |
+
return 0.5
|
| 92 |
+
|
| 93 |
+
def _calculate_tag_diversity(self, track_data: Dict) -> float:
|
| 94 |
+
"""Calculate tag diversity score."""
|
| 95 |
+
# This is a placeholder - would need tag data from Last.fm
|
| 96 |
+
# For now, return neutral score
|
| 97 |
+
return 0.5
|
src/agents/components/scoring/genre_mood_fit_scorer.py
ADDED
|
@@ -0,0 +1,149 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Genre and Mood Fit Scorer for BeatDebate
|
| 3 |
+
|
| 4 |
+
Scores how well tracks fit the requested genres and moods,
|
| 5 |
+
evaluating genre matching, mood alignment, and artist similarity.
|
| 6 |
+
"""
|
| 7 |
+
|
| 8 |
+
from typing import Dict, Any
|
| 9 |
+
import structlog
|
| 10 |
+
|
| 11 |
+
logger = structlog.get_logger(__name__)
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
class GenreMoodFitScorer:
|
| 15 |
+
"""
|
| 16 |
+
Scores how well tracks fit the requested genres and moods.
|
| 17 |
+
"""
|
| 18 |
+
|
| 19 |
+
def __init__(self):
|
| 20 |
+
"""Initialize genre/mood fit scorer."""
|
| 21 |
+
self.logger = logger.bind(component="GenreMoodFitScorer")
|
| 22 |
+
self.logger.info("Genre/Mood Fit Scorer initialized")
|
| 23 |
+
|
| 24 |
+
def calculate_genre_mood_fit(
|
| 25 |
+
self,
|
| 26 |
+
track_data: Dict,
|
| 27 |
+
entities: Dict[str, Any],
|
| 28 |
+
intent_analysis: Dict[str, Any]
|
| 29 |
+
) -> float:
|
| 30 |
+
"""
|
| 31 |
+
Calculate how well track fits requested genres and moods.
|
| 32 |
+
|
| 33 |
+
Args:
|
| 34 |
+
track_data: Track metadata
|
| 35 |
+
entities: Extracted entities including genres and moods
|
| 36 |
+
intent_analysis: User intent analysis
|
| 37 |
+
|
| 38 |
+
Returns:
|
| 39 |
+
Genre/mood fit score (0.0 - 1.0)
|
| 40 |
+
"""
|
| 41 |
+
try:
|
| 42 |
+
# Calculate genre fit
|
| 43 |
+
genre_fit = self._calculate_genre_fit(track_data, entities)
|
| 44 |
+
|
| 45 |
+
# Calculate mood fit
|
| 46 |
+
mood_fit = self._calculate_mood_fit(track_data, entities, intent_analysis)
|
| 47 |
+
|
| 48 |
+
# Calculate artist fit (if artist was mentioned)
|
| 49 |
+
artist_fit = self._calculate_artist_fit(track_data, entities)
|
| 50 |
+
|
| 51 |
+
# Combine scores with weights
|
| 52 |
+
total_fit = (
|
| 53 |
+
genre_fit * 0.4 +
|
| 54 |
+
mood_fit * 0.4 +
|
| 55 |
+
artist_fit * 0.2
|
| 56 |
+
)
|
| 57 |
+
|
| 58 |
+
self.logger.debug(
|
| 59 |
+
"Genre/mood fit calculated",
|
| 60 |
+
genre_fit=genre_fit,
|
| 61 |
+
mood_fit=mood_fit,
|
| 62 |
+
artist_fit=artist_fit,
|
| 63 |
+
total_fit=total_fit
|
| 64 |
+
)
|
| 65 |
+
|
| 66 |
+
return min(1.0, max(0.0, total_fit))
|
| 67 |
+
|
| 68 |
+
except Exception as e:
|
| 69 |
+
self.logger.warning("Genre/mood fit calculation failed", error=str(e))
|
| 70 |
+
return 0.5 # Default neutral score
|
| 71 |
+
|
| 72 |
+
def _calculate_genre_fit(self, track_data: Dict, entities: Dict[str, Any]) -> float:
|
| 73 |
+
"""Calculate genre fit score."""
|
| 74 |
+
requested_genres = entities.get("musical_entities", {}).get("genres", {}).get("primary", [])
|
| 75 |
+
|
| 76 |
+
if not requested_genres:
|
| 77 |
+
return 0.7 # Neutral score if no specific genres requested
|
| 78 |
+
|
| 79 |
+
# This would need genre classification of the track
|
| 80 |
+
# For now, use source information as proxy
|
| 81 |
+
# source = track_data.get('source', '') # TODO: Use when implementing genre classification
|
| 82 |
+
search_term = track_data.get('search_term', '').lower()
|
| 83 |
+
|
| 84 |
+
# Check if search term matches requested genres
|
| 85 |
+
genre_matches = 0
|
| 86 |
+
for genre in requested_genres:
|
| 87 |
+
if genre.lower() in search_term:
|
| 88 |
+
genre_matches += 1
|
| 89 |
+
|
| 90 |
+
if genre_matches > 0:
|
| 91 |
+
return min(1.0, genre_matches / len(requested_genres))
|
| 92 |
+
else:
|
| 93 |
+
return 0.5 # Default if no clear match
|
| 94 |
+
|
| 95 |
+
def _calculate_mood_fit(
|
| 96 |
+
self,
|
| 97 |
+
track_data: Dict,
|
| 98 |
+
entities: Dict[str, Any],
|
| 99 |
+
intent_analysis: Dict[str, Any]
|
| 100 |
+
) -> float:
|
| 101 |
+
"""Calculate mood fit score."""
|
| 102 |
+
requested_moods = entities.get("contextual_entities", {}).get("moods", {})
|
| 103 |
+
|
| 104 |
+
if not requested_moods:
|
| 105 |
+
return 0.7 # Neutral score if no specific moods requested
|
| 106 |
+
|
| 107 |
+
# Extract all mood terms
|
| 108 |
+
all_moods = []
|
| 109 |
+
for mood_category in requested_moods.values():
|
| 110 |
+
all_moods.extend(mood_category)
|
| 111 |
+
|
| 112 |
+
# Check if search term or source matches moods
|
| 113 |
+
search_term = track_data.get('search_term', '').lower()
|
| 114 |
+
exploration_tag = track_data.get('exploration_tag', '').lower()
|
| 115 |
+
|
| 116 |
+
mood_matches = 0
|
| 117 |
+
for mood in all_moods:
|
| 118 |
+
if mood.lower() in search_term or mood.lower() in exploration_tag:
|
| 119 |
+
mood_matches += 1
|
| 120 |
+
|
| 121 |
+
if mood_matches > 0:
|
| 122 |
+
return min(1.0, mood_matches / len(all_moods))
|
| 123 |
+
else:
|
| 124 |
+
return 0.5 # Default if no clear match
|
| 125 |
+
|
| 126 |
+
def _calculate_artist_fit(self, track_data: Dict, entities: Dict[str, Any]) -> float:
|
| 127 |
+
"""Calculate artist fit score."""
|
| 128 |
+
requested_artists = entities.get("musical_entities", {}).get("artists", {})
|
| 129 |
+
|
| 130 |
+
if not requested_artists:
|
| 131 |
+
return 0.7 # Neutral score if no specific artists requested
|
| 132 |
+
|
| 133 |
+
track_artist = track_data.get('artist', '').lower()
|
| 134 |
+
source_artist = track_data.get('source_artist', '').lower()
|
| 135 |
+
|
| 136 |
+
# Check for direct artist matches
|
| 137 |
+
all_artists = []
|
| 138 |
+
all_artists.extend(requested_artists.get("primary", []))
|
| 139 |
+
all_artists.extend(requested_artists.get("similar_to", []))
|
| 140 |
+
|
| 141 |
+
for artist in all_artists:
|
| 142 |
+
if artist.lower() in track_artist or artist.lower() in source_artist:
|
| 143 |
+
return 1.0 # Perfect match
|
| 144 |
+
|
| 145 |
+
# Check if from similar artist source
|
| 146 |
+
if track_data.get('source') == 'similar_artists':
|
| 147 |
+
return 0.8 # High score for similar artist tracks
|
| 148 |
+
|
| 149 |
+
return 0.5 # Default score
|
src/agents/components/scoring/intent_aware_scorer.py
ADDED
|
@@ -0,0 +1,566 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Intent-Aware Scorer for BeatDebate
|
| 3 |
+
|
| 4 |
+
Provides specialized scoring methods for different recommendation approaches:
|
| 5 |
+
- Artist Similarity
|
| 6 |
+
- Discovery/Exploration
|
| 7 |
+
- Genre/Mood
|
| 8 |
+
- Contextual
|
| 9 |
+
- Hybrid (with sub-types)
|
| 10 |
+
"""
|
| 11 |
+
|
| 12 |
+
from typing import Dict, Any, List
|
| 13 |
+
import structlog
|
| 14 |
+
|
| 15 |
+
logger = structlog.get_logger(__name__)
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
class IntentAwareScorer:
|
| 19 |
+
"""
|
| 20 |
+
π§ NEW: Intent-aware scoring for different recommendation approaches.
|
| 21 |
+
|
| 22 |
+
Provides specialized scoring methods for all intent types:
|
| 23 |
+
- Artist Similarity
|
| 24 |
+
- Discovery/Exploration
|
| 25 |
+
- Genre/Mood
|
| 26 |
+
- Contextual
|
| 27 |
+
- Hybrid (with sub-types)
|
| 28 |
+
"""
|
| 29 |
+
|
| 30 |
+
def __init__(self):
|
| 31 |
+
"""Initialize intent-aware scorer."""
|
| 32 |
+
self.logger = logger.bind(component="IntentAwareScorer")
|
| 33 |
+
self.logger.info("Intent-Aware Scorer initialized")
|
| 34 |
+
|
| 35 |
+
def calculate_novelty_score(
|
| 36 |
+
self,
|
| 37 |
+
track_data: Dict,
|
| 38 |
+
intent: str,
|
| 39 |
+
entities: Dict[str, Any] = None
|
| 40 |
+
) -> float:
|
| 41 |
+
"""
|
| 42 |
+
π§ FIXED: Calculate proper novelty score based on popularity data.
|
| 43 |
+
|
| 44 |
+
Args:
|
| 45 |
+
track_data: Track metadata including play counts
|
| 46 |
+
intent: Intent type (discovery, hybrid_discovery_primary, etc.)
|
| 47 |
+
entities: Musical entities for context
|
| 48 |
+
|
| 49 |
+
Returns:
|
| 50 |
+
Novelty score (0.0 - 1.0) where 1.0 = truly underground
|
| 51 |
+
"""
|
| 52 |
+
try:
|
| 53 |
+
playcount = int(track_data.get('playcount') or 0)
|
| 54 |
+
listeners = int(track_data.get('listeners') or 0)
|
| 55 |
+
|
| 56 |
+
# Calculate popularity-based novelty (INVERSE of popularity)
|
| 57 |
+
novelty_score = self._calculate_underground_novelty(playcount, listeners, intent)
|
| 58 |
+
|
| 59 |
+
# Apply intent-specific thresholds and bonuses
|
| 60 |
+
if 'discovery' in intent or intent == 'discovery':
|
| 61 |
+
# Discovery intents: Strict novelty requirements
|
| 62 |
+
novelty_score = self._apply_discovery_novelty_boost(
|
| 63 |
+
novelty_score, track_data, entities
|
| 64 |
+
)
|
| 65 |
+
elif 'similarity' in intent or intent == 'artist_similarity':
|
| 66 |
+
# Similarity intents: Relaxed novelty, focus on similarity
|
| 67 |
+
novelty_score = max(0.3, novelty_score) # Minimum threshold
|
| 68 |
+
|
| 69 |
+
self.logger.debug(
|
| 70 |
+
"Novelty score calculated",
|
| 71 |
+
playcount=playcount,
|
| 72 |
+
listeners=listeners,
|
| 73 |
+
intent=intent,
|
| 74 |
+
novelty_score=novelty_score
|
| 75 |
+
)
|
| 76 |
+
|
| 77 |
+
return min(1.0, max(0.0, novelty_score))
|
| 78 |
+
|
| 79 |
+
except Exception as e:
|
| 80 |
+
self.logger.warning("Novelty scoring failed", error=str(e))
|
| 81 |
+
return 0.5
|
| 82 |
+
|
| 83 |
+
def _calculate_underground_novelty(self, playcount: int, listeners: int, intent: str) -> float:
|
| 84 |
+
"""
|
| 85 |
+
Calculate novelty score based on popularity metrics.
|
| 86 |
+
|
| 87 |
+
π§ FIXED: Higher popularity = LOWER novelty score
|
| 88 |
+
"""
|
| 89 |
+
# Handle zero values
|
| 90 |
+
if playcount == 0 and listeners == 0:
|
| 91 |
+
return 1.0 # Completely unknown = maximum novelty
|
| 92 |
+
|
| 93 |
+
# Intent-specific popularity thresholds
|
| 94 |
+
if 'discovery' in intent or intent == 'discovery':
|
| 95 |
+
# Discovery: Strict but realistic thresholds for truly underground focus
|
| 96 |
+
max_listeners = 500000 # 500k listeners = underground limit (was 50k - too strict!)
|
| 97 |
+
max_playcount = 5000000 # 5M plays = underground limit (was 500k - too strict!)
|
| 98 |
+
elif 'similarity' in intent or intent == 'artist_similarity':
|
| 99 |
+
# Similarity: Relaxed thresholds (allow moderate popularity)
|
| 100 |
+
max_listeners = 1000000 # 1M listeners = acceptable
|
| 101 |
+
max_playcount = 10000000 # 10M plays = acceptable
|
| 102 |
+
else:
|
| 103 |
+
# Default: Moderate thresholds
|
| 104 |
+
max_listeners = 200000 # 200k listeners
|
| 105 |
+
max_playcount = 2000000 # 2M plays
|
| 106 |
+
|
| 107 |
+
# Calculate novelty based on inverse popularity
|
| 108 |
+
if listeners > 0:
|
| 109 |
+
listener_novelty = 1.0 - min(1.0, listeners / max_listeners)
|
| 110 |
+
else:
|
| 111 |
+
listener_novelty = 1.0
|
| 112 |
+
|
| 113 |
+
if playcount > 0:
|
| 114 |
+
playcount_novelty = 1.0 - min(1.0, playcount / max_playcount)
|
| 115 |
+
else:
|
| 116 |
+
playcount_novelty = 1.0
|
| 117 |
+
|
| 118 |
+
# Combine listener and playcount novelty
|
| 119 |
+
combined_novelty = (listener_novelty + playcount_novelty) / 2
|
| 120 |
+
|
| 121 |
+
return combined_novelty
|
| 122 |
+
|
| 123 |
+
def _apply_discovery_novelty_boost(
|
| 124 |
+
self,
|
| 125 |
+
base_novelty: float,
|
| 126 |
+
track_data: Dict,
|
| 127 |
+
entities: Dict[str, Any] = None
|
| 128 |
+
) -> float:
|
| 129 |
+
"""Apply discovery-specific novelty bonuses."""
|
| 130 |
+
boosted_novelty = base_novelty
|
| 131 |
+
|
| 132 |
+
# Bonus for underground indicators in tags/genres
|
| 133 |
+
underground_tags = ['underground', 'experimental', 'obscure', 'hidden', 'indie']
|
| 134 |
+
track_tags = track_data.get('tags', [])
|
| 135 |
+
if isinstance(track_tags, list):
|
| 136 |
+
for tag in track_tags:
|
| 137 |
+
if any(indicator in tag.lower() for indicator in underground_tags):
|
| 138 |
+
boosted_novelty += 0.1
|
| 139 |
+
break
|
| 140 |
+
|
| 141 |
+
# Bonus for very low listener counts
|
| 142 |
+
listeners = int(track_data.get('listeners') or 0)
|
| 143 |
+
if listeners < 1000:
|
| 144 |
+
boosted_novelty += 0.2 # Very underground bonus
|
| 145 |
+
elif listeners < 10000:
|
| 146 |
+
boosted_novelty += 0.1 # Underground bonus
|
| 147 |
+
|
| 148 |
+
return min(1.0, boosted_novelty)
|
| 149 |
+
|
| 150 |
+
def calculate_similarity_score(
|
| 151 |
+
self,
|
| 152 |
+
candidate_data: Dict,
|
| 153 |
+
entities: Dict[str, Any],
|
| 154 |
+
intent_analysis: Dict[str, Any]
|
| 155 |
+
) -> float:
|
| 156 |
+
"""
|
| 157 |
+
Calculate similarity score for artist similarity intents.
|
| 158 |
+
|
| 159 |
+
Args:
|
| 160 |
+
candidate_data: Candidate track data
|
| 161 |
+
entities: Musical entities including target artists
|
| 162 |
+
intent_analysis: Intent analysis results
|
| 163 |
+
|
| 164 |
+
Returns:
|
| 165 |
+
Similarity score (0.0 - 1.0)
|
| 166 |
+
"""
|
| 167 |
+
try:
|
| 168 |
+
similarity_score = 0.0
|
| 169 |
+
|
| 170 |
+
# Extract target artists from entities
|
| 171 |
+
target_artists = self._extract_target_artists(entities)
|
| 172 |
+
if not target_artists:
|
| 173 |
+
return 0.0
|
| 174 |
+
|
| 175 |
+
candidate_artist = candidate_data.get('artist', '').lower()
|
| 176 |
+
|
| 177 |
+
# π§ NEW: Artist alias mapping for better artist recognition
|
| 178 |
+
artist_aliases = {
|
| 179 |
+
'bon iver': ['justin vernon', 'bonnie bear'],
|
| 180 |
+
'justin vernon': ['bon iver', 'bonnie bear'],
|
| 181 |
+
'radiohead': ['thom yorke', 'jonny greenwood', 'ed o\'brien', 'colin greenwood', 'phil selway'],
|
| 182 |
+
'thom yorke': ['radiohead', 'atoms for peace'],
|
| 183 |
+
'taylor swift': ['taylor swift feat.', 'taylor swift featuring'],
|
| 184 |
+
'kanye west': ['ye', 'kanye', 'yeezy'],
|
| 185 |
+
'the weeknd': ['weeknd'],
|
| 186 |
+
'frank ocean': ['christopher francis ocean'],
|
| 187 |
+
'tyler the creator': ['tyler okonma', 'ace creator'],
|
| 188 |
+
'childish gambino': ['donald glover'],
|
| 189 |
+
'daniel caesar': ['daniel caesar feat.'],
|
| 190 |
+
'sza': ['solΓ‘na imani rowe'],
|
| 191 |
+
'daft punk': ['thomas bangalter', 'guy-manuel de homem-christo'],
|
| 192 |
+
'lcd soundsystem': ['james murphy'],
|
| 193 |
+
'tame impala': ['kevin parker'],
|
| 194 |
+
'vampire weekend': ['ezra koenig'],
|
| 195 |
+
'arcade fire': ['win butler', 'rΓ©gine chassagne'],
|
| 196 |
+
'fleet foxes': ['robin pecknold'],
|
| 197 |
+
'sufjan stevens': ['sufjan stevens feat.']
|
| 198 |
+
}
|
| 199 |
+
|
| 200 |
+
# Check if candidate is from target artist (highest similarity)
|
| 201 |
+
target_artists_lower = [artist.lower() for artist in target_artists]
|
| 202 |
+
|
| 203 |
+
# Direct match
|
| 204 |
+
if any(candidate_artist == artist.lower() for artist in target_artists):
|
| 205 |
+
similarity_score = 1.0
|
| 206 |
+
else:
|
| 207 |
+
# π§ NEW: Check for artist aliases
|
| 208 |
+
alias_match = False
|
| 209 |
+
for target_artist in target_artists_lower:
|
| 210 |
+
# Check if target has aliases and candidate matches one
|
| 211 |
+
if target_artist in artist_aliases:
|
| 212 |
+
aliases = artist_aliases[target_artist]
|
| 213 |
+
if candidate_artist in [alias.lower() for alias in aliases]:
|
| 214 |
+
similarity_score = 1.0
|
| 215 |
+
alias_match = True
|
| 216 |
+
self.logger.info(f"π― SIMILARITY ALIAS MATCH: '{candidate_artist}' matches target '{target_artist}' via alias")
|
| 217 |
+
break
|
| 218 |
+
|
| 219 |
+
# Check reverse mapping
|
| 220 |
+
if candidate_artist in artist_aliases:
|
| 221 |
+
aliases = artist_aliases[candidate_artist]
|
| 222 |
+
if target_artist in [alias.lower() for alias in aliases]:
|
| 223 |
+
similarity_score = 1.0
|
| 224 |
+
alias_match = True
|
| 225 |
+
self.logger.info(f"π― REVERSE SIMILARITY ALIAS: '{candidate_artist}' is primary for target '{target_artist}'")
|
| 226 |
+
break
|
| 227 |
+
|
| 228 |
+
# If no alias match, calculate style similarity
|
| 229 |
+
if not alias_match:
|
| 230 |
+
similarity_score = self._calculate_style_similarity(
|
| 231 |
+
candidate_data, target_artists, entities
|
| 232 |
+
)
|
| 233 |
+
|
| 234 |
+
self.logger.debug(
|
| 235 |
+
"Similarity score calculated",
|
| 236 |
+
candidate_artist=candidate_artist,
|
| 237 |
+
target_artists=target_artists,
|
| 238 |
+
similarity_score=similarity_score
|
| 239 |
+
)
|
| 240 |
+
|
| 241 |
+
return similarity_score
|
| 242 |
+
|
| 243 |
+
except Exception as e:
|
| 244 |
+
self.logger.warning("Similarity scoring failed", error=str(e))
|
| 245 |
+
return 0.0
|
| 246 |
+
|
| 247 |
+
def _extract_target_artists(self, entities: Dict[str, Any]) -> List[str]:
|
| 248 |
+
"""Extract target artists from entities."""
|
| 249 |
+
target_artists = []
|
| 250 |
+
|
| 251 |
+
musical_entities = entities.get('musical_entities', {})
|
| 252 |
+
artists = musical_entities.get('artists', {})
|
| 253 |
+
|
| 254 |
+
# Get primary and similar_to artists
|
| 255 |
+
target_artists.extend(artists.get('primary', []))
|
| 256 |
+
target_artists.extend(artists.get('similar_to', []))
|
| 257 |
+
|
| 258 |
+
return list(set(target_artists)) # Remove duplicates
|
| 259 |
+
|
| 260 |
+
def _calculate_style_similarity(
|
| 261 |
+
self,
|
| 262 |
+
candidate_data: Dict,
|
| 263 |
+
target_artists: List[str],
|
| 264 |
+
entities: Dict[str, Any]
|
| 265 |
+
) -> float:
|
| 266 |
+
"""Calculate style-based similarity score."""
|
| 267 |
+
# This is a simplified implementation
|
| 268 |
+
# In a real system, this would use audio features, genre matching, etc.
|
| 269 |
+
|
| 270 |
+
similarity_score = 0.0
|
| 271 |
+
|
| 272 |
+
# Genre matching
|
| 273 |
+
candidate_genres = set(candidate_data.get('genres', []))
|
| 274 |
+
target_genres = set()
|
| 275 |
+
|
| 276 |
+
musical_entities = entities.get('musical_entities', {})
|
| 277 |
+
genres = musical_entities.get('genres', {})
|
| 278 |
+
target_genres.update(genres.get('primary', []))
|
| 279 |
+
target_genres.update(genres.get('secondary', []))
|
| 280 |
+
|
| 281 |
+
if candidate_genres and target_genres:
|
| 282 |
+
genre_overlap = len(candidate_genres.intersection(target_genres))
|
| 283 |
+
total_genres = len(candidate_genres.union(target_genres))
|
| 284 |
+
similarity_score += (genre_overlap / total_genres) * 0.6
|
| 285 |
+
|
| 286 |
+
# Tag matching (simplified)
|
| 287 |
+
similarity_score += 0.4 # Base similarity for being in similar artist results
|
| 288 |
+
|
| 289 |
+
return min(1.0, similarity_score)
|
| 290 |
+
|
| 291 |
+
def calculate_target_artist_boost(
|
| 292 |
+
self,
|
| 293 |
+
candidate_data: Dict,
|
| 294 |
+
entities: Dict[str, Any]
|
| 295 |
+
) -> float:
|
| 296 |
+
"""
|
| 297 |
+
Calculate boost for target artist's own tracks.
|
| 298 |
+
|
| 299 |
+
Args:
|
| 300 |
+
candidate_data: Candidate track data
|
| 301 |
+
entities: Musical entities including target artists
|
| 302 |
+
|
| 303 |
+
Returns:
|
| 304 |
+
Target artist boost score (0.0 - 1.0)
|
| 305 |
+
"""
|
| 306 |
+
try:
|
| 307 |
+
target_artists = self._extract_target_artists(entities)
|
| 308 |
+
if not target_artists:
|
| 309 |
+
return 0.0
|
| 310 |
+
|
| 311 |
+
candidate_artist = candidate_data.get('artist', '').lower()
|
| 312 |
+
|
| 313 |
+
# Check if candidate is from target artist
|
| 314 |
+
if any(candidate_artist == artist.lower() for artist in target_artists):
|
| 315 |
+
return 0.8 # High boost for target artist tracks
|
| 316 |
+
|
| 317 |
+
return 0.0
|
| 318 |
+
|
| 319 |
+
except Exception as e:
|
| 320 |
+
self.logger.warning("Target artist boost calculation failed", error=str(e))
|
| 321 |
+
return 0.0
|
| 322 |
+
|
| 323 |
+
def calculate_underground_score(
|
| 324 |
+
self,
|
| 325 |
+
track_data: Dict,
|
| 326 |
+
intent: str
|
| 327 |
+
) -> float:
|
| 328 |
+
"""
|
| 329 |
+
Calculate underground score for discovery intents.
|
| 330 |
+
|
| 331 |
+
Args:
|
| 332 |
+
track_data: Track metadata
|
| 333 |
+
intent: Intent type
|
| 334 |
+
|
| 335 |
+
Returns:
|
| 336 |
+
Underground score (0.0 - 1.0)
|
| 337 |
+
"""
|
| 338 |
+
# Underground score is similar to novelty but with stricter thresholds
|
| 339 |
+
return self.calculate_novelty_score(track_data, intent)
|
| 340 |
+
|
| 341 |
+
def calculate_context_fit_score(
|
| 342 |
+
self,
|
| 343 |
+
track_data: Dict,
|
| 344 |
+
intent_analysis: Dict[str, Any],
|
| 345 |
+
entities: Dict[str, Any]
|
| 346 |
+
) -> float:
|
| 347 |
+
"""
|
| 348 |
+
Calculate context fit for contextual intents.
|
| 349 |
+
|
| 350 |
+
Args:
|
| 351 |
+
track_data: Track metadata
|
| 352 |
+
intent_analysis: Intent analysis results
|
| 353 |
+
entities: Musical entities
|
| 354 |
+
|
| 355 |
+
Returns:
|
| 356 |
+
Context fit score (0.0 - 1.0)
|
| 357 |
+
"""
|
| 358 |
+
try:
|
| 359 |
+
# Extract context from intent analysis
|
| 360 |
+
contexts = intent_analysis.get('context_factors', [])
|
| 361 |
+
if not contexts:
|
| 362 |
+
return 0.5 # Neutral if no context specified
|
| 363 |
+
|
| 364 |
+
context_score = 0.0
|
| 365 |
+
|
| 366 |
+
# Context-specific scoring logic
|
| 367 |
+
for context in contexts:
|
| 368 |
+
if context in ['study', 'concentration', 'focus']:
|
| 369 |
+
# Prefer instrumental, moderate energy
|
| 370 |
+
context_score += self._score_study_context(track_data)
|
| 371 |
+
elif context in ['workout', 'exercise', 'gym']:
|
| 372 |
+
# Prefer high energy, upbeat
|
| 373 |
+
context_score += self._score_workout_context(track_data)
|
| 374 |
+
elif context in ['relaxation', 'chill', 'calm']:
|
| 375 |
+
# Prefer low energy, calming
|
| 376 |
+
context_score += self._score_relaxation_context(track_data)
|
| 377 |
+
else:
|
| 378 |
+
context_score += 0.5 # Neutral for unknown contexts
|
| 379 |
+
|
| 380 |
+
return min(1.0, context_score / len(contexts))
|
| 381 |
+
|
| 382 |
+
except Exception as e:
|
| 383 |
+
self.logger.warning("Context fit calculation failed", error=str(e))
|
| 384 |
+
return 0.5
|
| 385 |
+
|
| 386 |
+
def _score_study_context(self, track_data: Dict) -> float:
|
| 387 |
+
"""Score track for studying context."""
|
| 388 |
+
score = 0.5 # Base score
|
| 389 |
+
|
| 390 |
+
# Prefer instrumental tracks
|
| 391 |
+
genre = track_data.get('genre', '').lower()
|
| 392 |
+
tags = [tag.lower() for tag in (track_data.get('tags') or [])]
|
| 393 |
+
|
| 394 |
+
# Positive indicators for studying
|
| 395 |
+
study_positive = [
|
| 396 |
+
'instrumental', 'ambient', 'classical', 'piano', 'acoustic',
|
| 397 |
+
'minimal', 'meditation', 'focus', 'concentration', 'calm',
|
| 398 |
+
'peaceful', 'soft', 'gentle', 'atmospheric', 'soundtrack'
|
| 399 |
+
]
|
| 400 |
+
|
| 401 |
+
# Negative indicators for studying
|
| 402 |
+
study_negative = [
|
| 403 |
+
'vocal', 'lyrics', 'aggressive', 'loud', 'energetic', 'party',
|
| 404 |
+
'heavy', 'metal', 'punk', 'rap', 'hip hop', 'dance', 'club'
|
| 405 |
+
]
|
| 406 |
+
|
| 407 |
+
# Score based on positive indicators
|
| 408 |
+
positive_matches = sum(1 for indicator in study_positive
|
| 409 |
+
if indicator in genre or any(indicator in tag for tag in tags))
|
| 410 |
+
score += positive_matches * 0.1
|
| 411 |
+
|
| 412 |
+
# Penalize negative indicators
|
| 413 |
+
negative_matches = sum(1 for indicator in study_negative
|
| 414 |
+
if indicator in genre or any(indicator in tag for tag in tags))
|
| 415 |
+
score -= negative_matches * 0.15
|
| 416 |
+
|
| 417 |
+
# Tempo considerations (if available)
|
| 418 |
+
try:
|
| 419 |
+
tempo = float(track_data.get('tempo') or 0)
|
| 420 |
+
if 60 <= tempo <= 120: # Ideal study tempo range
|
| 421 |
+
score += 0.2
|
| 422 |
+
elif tempo > 140: # Too fast for studying
|
| 423 |
+
score -= 0.3
|
| 424 |
+
except (ValueError, TypeError):
|
| 425 |
+
pass
|
| 426 |
+
|
| 427 |
+
return min(1.0, max(0.0, score))
|
| 428 |
+
|
| 429 |
+
def _score_workout_context(self, track_data: Dict) -> float:
|
| 430 |
+
"""Score track for workout context."""
|
| 431 |
+
score = 0.5 # Base score
|
| 432 |
+
|
| 433 |
+
genre = track_data.get('genre', '').lower()
|
| 434 |
+
tags = [tag.lower() for tag in (track_data.get('tags') or [])]
|
| 435 |
+
|
| 436 |
+
# Positive indicators for workout
|
| 437 |
+
workout_positive = [
|
| 438 |
+
'energetic', 'upbeat', 'pump', 'motivation', 'electronic', 'dance',
|
| 439 |
+
'rock', 'metal', 'hip hop', 'pop', 'aggressive', 'powerful',
|
| 440 |
+
'driving', 'intense', 'bass', 'beat', 'rhythm', 'gym'
|
| 441 |
+
]
|
| 442 |
+
|
| 443 |
+
# Negative indicators for workout
|
| 444 |
+
workout_negative = [
|
| 445 |
+
'slow', 'ballad', 'sad', 'melancholy', 'ambient', 'meditation',
|
| 446 |
+
'acoustic', 'folk', 'classical', 'piano', 'soft', 'gentle',
|
| 447 |
+
'peaceful', 'calm', 'sleepy', 'relaxing'
|
| 448 |
+
]
|
| 449 |
+
|
| 450 |
+
# Score based on positive indicators
|
| 451 |
+
positive_matches = sum(1 for indicator in workout_positive
|
| 452 |
+
if indicator in genre or any(indicator in tag for tag in tags))
|
| 453 |
+
score += positive_matches * 0.1
|
| 454 |
+
|
| 455 |
+
# Penalize negative indicators
|
| 456 |
+
negative_matches = sum(1 for indicator in workout_negative
|
| 457 |
+
if indicator in genre or any(indicator in tag for tag in tags))
|
| 458 |
+
score -= negative_matches * 0.1
|
| 459 |
+
|
| 460 |
+
# Tempo considerations (if available)
|
| 461 |
+
try:
|
| 462 |
+
tempo = float(track_data.get('tempo') or 0)
|
| 463 |
+
if tempo >= 120: # High energy tempo for workout
|
| 464 |
+
score += 0.3
|
| 465 |
+
elif tempo < 90: # Too slow for workout
|
| 466 |
+
score -= 0.2
|
| 467 |
+
except (ValueError, TypeError):
|
| 468 |
+
pass
|
| 469 |
+
|
| 470 |
+
# Energy level (if available)
|
| 471 |
+
try:
|
| 472 |
+
energy = float(track_data.get('energy') or 0.5)
|
| 473 |
+
if energy >= 0.7: # High energy
|
| 474 |
+
score += 0.2
|
| 475 |
+
elif energy < 0.3: # Low energy
|
| 476 |
+
score -= 0.2
|
| 477 |
+
except (ValueError, TypeError):
|
| 478 |
+
pass
|
| 479 |
+
|
| 480 |
+
return min(1.0, max(0.0, score))
|
| 481 |
+
|
| 482 |
+
def _score_relaxation_context(self, track_data: Dict) -> float:
|
| 483 |
+
"""Score track for relaxation context."""
|
| 484 |
+
score = 0.5 # Base score
|
| 485 |
+
|
| 486 |
+
genre = track_data.get('genre', '').lower()
|
| 487 |
+
tags = [tag.lower() for tag in (track_data.get('tags') or [])]
|
| 488 |
+
|
| 489 |
+
# Positive indicators for relaxation
|
| 490 |
+
relaxation_positive = [
|
| 491 |
+
'chill', 'calm', 'peaceful', 'relaxing', 'soft', 'gentle',
|
| 492 |
+
'ambient', 'meditation', 'spa', 'nature', 'acoustic',
|
| 493 |
+
'piano', 'instrumental', 'lounge', 'jazz', 'smooth',
|
| 494 |
+
'mellow', 'soothing', 'tranquil', 'serene'
|
| 495 |
+
]
|
| 496 |
+
|
| 497 |
+
# Negative indicators for relaxation
|
| 498 |
+
relaxation_negative = [
|
| 499 |
+
'aggressive', 'loud', 'metal', 'punk', 'screaming', 'harsh',
|
| 500 |
+
'distorted', 'chaotic', 'frantic', 'intense', 'heavy',
|
| 501 |
+
'club', 'party', 'rave', 'thrash'
|
| 502 |
+
]
|
| 503 |
+
|
| 504 |
+
# Score based on positive indicators
|
| 505 |
+
positive_matches = sum(1 for indicator in relaxation_positive
|
| 506 |
+
if indicator in genre or any(indicator in tag for tag in tags))
|
| 507 |
+
score += positive_matches * 0.1
|
| 508 |
+
|
| 509 |
+
# Penalize negative indicators
|
| 510 |
+
negative_matches = sum(1 for indicator in relaxation_negative
|
| 511 |
+
if indicator in genre or any(indicator in tag for tag in tags))
|
| 512 |
+
score -= negative_matches * 0.2
|
| 513 |
+
|
| 514 |
+
# Tempo considerations (if available)
|
| 515 |
+
try:
|
| 516 |
+
tempo = float(track_data.get('tempo') or 0)
|
| 517 |
+
if 60 <= tempo <= 100: # Relaxed tempo range
|
| 518 |
+
score += 0.2
|
| 519 |
+
elif tempo > 130: # Too fast for relaxation
|
| 520 |
+
score -= 0.3
|
| 521 |
+
except (ValueError, TypeError):
|
| 522 |
+
pass
|
| 523 |
+
|
| 524 |
+
# Valence considerations (if available) - prefer positive but not too excited
|
| 525 |
+
try:
|
| 526 |
+
valence = float(track_data.get('valence') or 0.5)
|
| 527 |
+
if 0.4 <= valence <= 0.7: # Moderately positive
|
| 528 |
+
score += 0.1
|
| 529 |
+
elif valence < 0.2: # Too sad for relaxation
|
| 530 |
+
score -= 0.1
|
| 531 |
+
except (ValueError, TypeError):
|
| 532 |
+
pass
|
| 533 |
+
|
| 534 |
+
return min(1.0, max(0.0, score))
|
| 535 |
+
|
| 536 |
+
def calculate_familiarity_score(
|
| 537 |
+
self,
|
| 538 |
+
track_data: Dict,
|
| 539 |
+
intent_analysis: Dict[str, Any]
|
| 540 |
+
) -> float:
|
| 541 |
+
"""
|
| 542 |
+
Calculate familiarity score for contextual intents.
|
| 543 |
+
|
| 544 |
+
Args:
|
| 545 |
+
track_data: Track metadata
|
| 546 |
+
intent_analysis: Intent analysis results
|
| 547 |
+
|
| 548 |
+
Returns:
|
| 549 |
+
Familiarity score (0.0 - 1.0)
|
| 550 |
+
"""
|
| 551 |
+
try:
|
| 552 |
+
# For contextual queries, sometimes familiar tracks are preferred
|
| 553 |
+
playcount = int(track_data.get('playcount') or 0)
|
| 554 |
+
listeners = int(track_data.get('listeners') or 0)
|
| 555 |
+
|
| 556 |
+
# Moderate popularity = more familiar
|
| 557 |
+
if listeners > 10000 and listeners < 1000000:
|
| 558 |
+
return 0.8 # Well-known but not mainstream
|
| 559 |
+
elif listeners > 1000000:
|
| 560 |
+
return 0.6 # Very mainstream
|
| 561 |
+
else:
|
| 562 |
+
return 0.3 # Too underground for familiarity
|
| 563 |
+
|
| 564 |
+
except Exception as e:
|
| 565 |
+
self.logger.warning("Familiarity calculation failed", error=str(e))
|
| 566 |
+
return 0.5
|
src/agents/components/scoring/popularity_balancer.py
ADDED
|
@@ -0,0 +1,121 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Popularity Balancer for BeatDebate
|
| 3 |
+
|
| 4 |
+
Balances mainstream vs underground preferences based on user intent,
|
| 5 |
+
adjusting scoring based on track popularity and user's exploration preferences.
|
| 6 |
+
"""
|
| 7 |
+
|
| 8 |
+
import math
|
| 9 |
+
from typing import Dict, Any
|
| 10 |
+
import structlog
|
| 11 |
+
|
| 12 |
+
logger = structlog.get_logger(__name__)
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
class PopularityBalancer:
|
| 16 |
+
"""
|
| 17 |
+
Balances mainstream vs underground preferences based on user intent.
|
| 18 |
+
|
| 19 |
+
Adjusts scoring based on track popularity and user's exploration preferences.
|
| 20 |
+
"""
|
| 21 |
+
|
| 22 |
+
def __init__(self):
|
| 23 |
+
"""Initialize popularity balancer."""
|
| 24 |
+
self.logger = logger.bind(component="PopularityBalancer")
|
| 25 |
+
self.logger.info("Popularity Balancer initialized")
|
| 26 |
+
|
| 27 |
+
def calculate_popularity_score(
|
| 28 |
+
self,
|
| 29 |
+
listeners: int,
|
| 30 |
+
playcount: int,
|
| 31 |
+
exploration_openness: float = 0.5,
|
| 32 |
+
entities: Dict[str, Any] = None,
|
| 33 |
+
intent_analysis: Dict[str, Any] = None
|
| 34 |
+
) -> float:
|
| 35 |
+
"""
|
| 36 |
+
Calculate popularity-based score with configurable exploration preference.
|
| 37 |
+
|
| 38 |
+
Args:
|
| 39 |
+
listeners: Number of unique listeners
|
| 40 |
+
playcount: Total play count
|
| 41 |
+
exploration_openness: 0.0 = prefer popular, 1.0 = prefer underground
|
| 42 |
+
entities: Musical entities from query understanding
|
| 43 |
+
intent_analysis: Intent analysis for context-aware scoring
|
| 44 |
+
|
| 45 |
+
Returns:
|
| 46 |
+
Score from 0.0 to 1.0
|
| 47 |
+
"""
|
| 48 |
+
# π― NEW: Adjust exploration for genre-hybrid queries
|
| 49 |
+
if entities and intent_analysis and self._is_genre_hybrid_query(entities, intent_analysis):
|
| 50 |
+
exploration_openness = 0.75 # More tolerant of popular tracks for genre examples
|
| 51 |
+
|
| 52 |
+
base_popularity = self._calculate_base_popularity(listeners, playcount)
|
| 53 |
+
|
| 54 |
+
# Apply exploration preference
|
| 55 |
+
if exploration_openness <= 0.5:
|
| 56 |
+
# Prefer popular tracks
|
| 57 |
+
preference_factor = (0.5 - exploration_openness) * 2
|
| 58 |
+
score = base_popularity + (1 - base_popularity) * preference_factor
|
| 59 |
+
else:
|
| 60 |
+
# Prefer underground tracks
|
| 61 |
+
preference_factor = (exploration_openness - 0.5) * 2
|
| 62 |
+
score = base_popularity * (1 - preference_factor)
|
| 63 |
+
|
| 64 |
+
final_score = max(0.0, min(1.0, score))
|
| 65 |
+
|
| 66 |
+
self.logger.debug(
|
| 67 |
+
"Popularity score calculated",
|
| 68 |
+
listeners=listeners,
|
| 69 |
+
playcount=playcount,
|
| 70 |
+
base_popularity=base_popularity,
|
| 71 |
+
exploration_openness=exploration_openness,
|
| 72 |
+
final_score=final_score
|
| 73 |
+
)
|
| 74 |
+
|
| 75 |
+
return final_score
|
| 76 |
+
|
| 77 |
+
def _calculate_base_popularity(self, listeners: int, playcount: int) -> float:
|
| 78 |
+
"""Calculate base popularity score from play counts."""
|
| 79 |
+
# Use log scale to handle wide range of play counts
|
| 80 |
+
if playcount > 0:
|
| 81 |
+
# Normalize to roughly 0-1 scale (10M plays = 1.0)
|
| 82 |
+
playcount_score = min(1.0, math.log10(max(1, playcount)) / 7.0)
|
| 83 |
+
else:
|
| 84 |
+
playcount_score = 0.0
|
| 85 |
+
|
| 86 |
+
if listeners > 0:
|
| 87 |
+
# Normalize to roughly 0-1 scale (1M listeners = 1.0)
|
| 88 |
+
listeners_score = min(1.0, math.log10(max(1, listeners)) / 6.0)
|
| 89 |
+
else:
|
| 90 |
+
listeners_score = 0.0
|
| 91 |
+
|
| 92 |
+
# Combine play count and listener count
|
| 93 |
+
return (playcount_score + listeners_score) / 2
|
| 94 |
+
|
| 95 |
+
def _is_genre_hybrid_query(self, entities: Dict[str, Any], intent_analysis: Dict[str, Any]) -> bool:
|
| 96 |
+
"""
|
| 97 |
+
Detect if this is a genre-hybrid query that should be more tolerant of popular tracks.
|
| 98 |
+
|
| 99 |
+
Genre-hybrid queries like "Music like Kendrick Lamar but jazzy" want good examples
|
| 100 |
+
of genre fusion, not just underground tracks.
|
| 101 |
+
"""
|
| 102 |
+
if not entities or not intent_analysis:
|
| 103 |
+
return False
|
| 104 |
+
|
| 105 |
+
musical_entities = entities.get('musical_entities', {})
|
| 106 |
+
if not musical_entities:
|
| 107 |
+
return False
|
| 108 |
+
|
| 109 |
+
# Check for genre constraints
|
| 110 |
+
genres = musical_entities.get('genres', {})
|
| 111 |
+
has_genres = len(genres.get('primary', [])) > 0 or len(genres.get('secondary', [])) > 0
|
| 112 |
+
|
| 113 |
+
# Check for artist similarity component
|
| 114 |
+
has_artist_similarity = len(musical_entities.get('artists', [])) > 0
|
| 115 |
+
|
| 116 |
+
# Check if it's a hybrid intent
|
| 117 |
+
intent_type = intent_analysis.get('primary_intent', '')
|
| 118 |
+
is_hybrid_intent = intent_type == 'hybrid' or 'hybrid' in str(intent_type).lower()
|
| 119 |
+
|
| 120 |
+
# All conditions must be true for genre-hybrid query
|
| 121 |
+
return has_genres and has_artist_similarity and is_hybrid_intent
|
src/agents/judge/ranking_logic.py
CHANGED
|
@@ -55,7 +55,7 @@ class RankingLogic:
|
|
| 55 |
Ranked list of (track, scores) tuples
|
| 56 |
"""
|
| 57 |
try:
|
| 58 |
-
from ..components
|
| 59 |
|
| 60 |
# Initialize quality scorer for intent-aware scoring
|
| 61 |
quality_scorer = QualityScorer()
|
|
|
|
| 55 |
Ranked list of (track, scores) tuples
|
| 56 |
"""
|
| 57 |
try:
|
| 58 |
+
from ..components import QualityScorer
|
| 59 |
|
| 60 |
# Initialize quality scorer for intent-aware scoring
|
| 61 |
quality_scorer = QualityScorer()
|
test_followup_behavior.py
DELETED
|
@@ -1,109 +0,0 @@
|
|
| 1 |
-
#!/usr/bin/env python3
|
| 2 |
-
"""
|
| 3 |
-
Test follow-up query behavior to ensure no duplicates
|
| 4 |
-
"""
|
| 5 |
-
|
| 6 |
-
import asyncio
|
| 7 |
-
import json
|
| 8 |
-
import logging
|
| 9 |
-
from typing import Dict, Any, List
|
| 10 |
-
|
| 11 |
-
# Configure logging
|
| 12 |
-
logging.basicConfig(level=logging.INFO)
|
| 13 |
-
logger = logging.getLogger(__name__)
|
| 14 |
-
|
| 15 |
-
async def test_artist_deep_dive():
|
| 16 |
-
"""Test artist deep dive follow-up behavior."""
|
| 17 |
-
|
| 18 |
-
from src.services.enhanced_recommendation_service import EnhancedRecommendationService, RecommendationRequest
|
| 19 |
-
from src.services.api_service import APIService
|
| 20 |
-
|
| 21 |
-
print("π§ͺ Testing Artist Deep Dive")
|
| 22 |
-
print("=" * 60)
|
| 23 |
-
|
| 24 |
-
# Initialize services
|
| 25 |
-
api_service = APIService()
|
| 26 |
-
service = EnhancedRecommendationService(api_service)
|
| 27 |
-
|
| 28 |
-
# Step 1: Initial query
|
| 29 |
-
print("π΅ STEP 1: Initial Query - 'Music by Mk.gee'")
|
| 30 |
-
|
| 31 |
-
request1 = RecommendationRequest(
|
| 32 |
-
query="Music by Mk.gee",
|
| 33 |
-
max_recommendations=5,
|
| 34 |
-
session_id="test_session_artist_dive"
|
| 35 |
-
)
|
| 36 |
-
|
| 37 |
-
response1 = await service.get_recommendations(request1)
|
| 38 |
-
initial_tracks = response1.recommendations
|
| 39 |
-
print(f"β
Initial query returned {len(initial_tracks)} recommendations")
|
| 40 |
-
|
| 41 |
-
print("Initial recommendations:")
|
| 42 |
-
for i, rec in enumerate(initial_tracks, 1):
|
| 43 |
-
print(f" {i}. {rec.name} by {rec.artist}")
|
| 44 |
-
print()
|
| 45 |
-
|
| 46 |
-
# Convert to conversation history format
|
| 47 |
-
conversation_history = [
|
| 48 |
-
{
|
| 49 |
-
"query": "Music by Mk.gee",
|
| 50 |
-
"recommendations": [
|
| 51 |
-
{"artist": track.artist, "title": track.name}
|
| 52 |
-
for track in initial_tracks
|
| 53 |
-
]
|
| 54 |
-
}
|
| 55 |
-
]
|
| 56 |
-
|
| 57 |
-
# Step 2: Follow-up query
|
| 58 |
-
print("π΅ STEP 2: Follow-up Query - 'More from Mk.gee'")
|
| 59 |
-
|
| 60 |
-
request2 = RecommendationRequest(
|
| 61 |
-
query="More from Mk.gee",
|
| 62 |
-
max_recommendations=10,
|
| 63 |
-
session_id="test_session_artist_dive",
|
| 64 |
-
context={
|
| 65 |
-
"previous_queries": ["Music by Mk.gee"],
|
| 66 |
-
"previous_recommendations": [
|
| 67 |
-
[{"artist": track.artist, "title": track.name} for track in initial_tracks]
|
| 68 |
-
]
|
| 69 |
-
}
|
| 70 |
-
)
|
| 71 |
-
|
| 72 |
-
response2 = await service.get_recommendations(request2)
|
| 73 |
-
followup_tracks = response2.recommendations
|
| 74 |
-
print(f"β
Follow-up query returned {len(followup_tracks)} recommendations")
|
| 75 |
-
|
| 76 |
-
# Check for duplicates
|
| 77 |
-
initial_track_ids = {f"{track.artist.lower()}::{track.name.lower()}" for track in initial_tracks}
|
| 78 |
-
duplicates = []
|
| 79 |
-
new_tracks = []
|
| 80 |
-
|
| 81 |
-
for track in followup_tracks:
|
| 82 |
-
track_id = f"{track.artist.lower()}::{track.name.lower()}"
|
| 83 |
-
if track_id in initial_track_ids:
|
| 84 |
-
duplicates.append(f"{track.name} by {track.artist}")
|
| 85 |
-
else:
|
| 86 |
-
new_tracks.append(f"{track.name} by {track.artist}")
|
| 87 |
-
|
| 88 |
-
print("Follow-up recommendations:")
|
| 89 |
-
for i, rec in enumerate(followup_tracks, 1):
|
| 90 |
-
status = "β DUPLICATE" if f"{rec.artist.lower()}::{rec.name.lower()}" in initial_track_ids else "+ NEW"
|
| 91 |
-
print(f" {status}: {rec.name} by {rec.artist}")
|
| 92 |
-
print()
|
| 93 |
-
|
| 94 |
-
print(f"Found {len(followup_tracks)} tracks in follow-up")
|
| 95 |
-
print(f"Duplicates: {len(duplicates)}")
|
| 96 |
-
|
| 97 |
-
# Results
|
| 98 |
-
if len(duplicates) == 0:
|
| 99 |
-
print("β
PASS: No duplicates found!")
|
| 100 |
-
else:
|
| 101 |
-
print(f"β FAIL: Found {len(duplicates)} duplicates")
|
| 102 |
-
for dup in duplicates:
|
| 103 |
-
print(f" - {dup}")
|
| 104 |
-
|
| 105 |
-
async def main():
|
| 106 |
-
await test_artist_deep_dive()
|
| 107 |
-
|
| 108 |
-
if __name__ == "__main__":
|
| 109 |
-
asyncio.run(main())
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
test_followup_detection_fix.py
DELETED
|
@@ -1,137 +0,0 @@
|
|
| 1 |
-
#!/usr/bin/env python3
|
| 2 |
-
"""
|
| 3 |
-
Test script to verify follow-up detection fix handles different artists correctly
|
| 4 |
-
"""
|
| 5 |
-
|
| 6 |
-
import asyncio
|
| 7 |
-
import sys
|
| 8 |
-
import os
|
| 9 |
-
|
| 10 |
-
# Add the src directory to the path
|
| 11 |
-
sys.path.insert(0, os.path.join(os.path.dirname(__file__), 'src'))
|
| 12 |
-
|
| 13 |
-
from src.services.enhanced_recommendation_service import EnhancedRecommendationService, RecommendationRequest
|
| 14 |
-
|
| 15 |
-
async def test_followup_detection_fix():
|
| 16 |
-
"""Test that different artists are not detected as follow-ups"""
|
| 17 |
-
print("π§ͺ Testing Follow-up Detection Fix")
|
| 18 |
-
print("=" * 50)
|
| 19 |
-
|
| 20 |
-
# Initialize the service
|
| 21 |
-
service = EnhancedRecommendationService()
|
| 22 |
-
await service.initialize_agents()
|
| 23 |
-
|
| 24 |
-
try:
|
| 25 |
-
# Test Case 1: First query - Mk.gee
|
| 26 |
-
print("\nπ΅ TEST CASE 1: First Query - 'Discover underground tracks by Mk.gee'")
|
| 27 |
-
request1 = RecommendationRequest(
|
| 28 |
-
query="Discover underground tracks by Mk.gee",
|
| 29 |
-
max_recommendations=5,
|
| 30 |
-
session_id="test_session_fix",
|
| 31 |
-
context={
|
| 32 |
-
"previous_queries": [],
|
| 33 |
-
"previous_recommendations": []
|
| 34 |
-
}
|
| 35 |
-
)
|
| 36 |
-
|
| 37 |
-
response1 = await service.get_recommendations(request1)
|
| 38 |
-
print(f"β
First query completed: {len(response1.recommendations)} tracks found")
|
| 39 |
-
|
| 40 |
-
# Test Case 2: Different artist - should NOT be follow-up
|
| 41 |
-
print("\nπ΅ TEST CASE 2: Different Artist - 'Discover underground tracks by Kendrick Lamar'")
|
| 42 |
-
request2 = RecommendationRequest(
|
| 43 |
-
query="Discover underground tracks by Kendrick Lamar",
|
| 44 |
-
max_recommendations=5,
|
| 45 |
-
session_id="test_session_fix",
|
| 46 |
-
context={
|
| 47 |
-
"previous_queries": ["Discover underground tracks by Mk.gee"],
|
| 48 |
-
"previous_recommendations": [
|
| 49 |
-
[
|
| 50 |
-
{"artist": track.artist, "title": track.name}
|
| 51 |
-
for track in response1.recommendations[:5]
|
| 52 |
-
]
|
| 53 |
-
]
|
| 54 |
-
}
|
| 55 |
-
)
|
| 56 |
-
|
| 57 |
-
response2 = await service.get_recommendations(request2)
|
| 58 |
-
print(f"β
Second query completed: {len(response2.recommendations)} tracks found")
|
| 59 |
-
|
| 60 |
-
# Analyze results
|
| 61 |
-
print("\nπ RESULTS ANALYSIS:")
|
| 62 |
-
print("=" * 30)
|
| 63 |
-
|
| 64 |
-
# Check if any tracks are from Mk.gee (should be 0 for Kendrick query)
|
| 65 |
-
mkgee_tracks_in_kendrick = [
|
| 66 |
-
track for track in response2.recommendations
|
| 67 |
-
if "mk.gee" in track.artist.lower()
|
| 68 |
-
]
|
| 69 |
-
|
| 70 |
-
# Check if any tracks are actually from Kendrick Lamar
|
| 71 |
-
kendrick_tracks = [
|
| 72 |
-
track for track in response2.recommendations
|
| 73 |
-
if "kendrick" in track.artist.lower()
|
| 74 |
-
]
|
| 75 |
-
|
| 76 |
-
print(f"π Mk.gee tracks in Kendrick query: {len(mkgee_tracks_in_kendrick)}")
|
| 77 |
-
print(f"π Kendrick tracks in response: {len(kendrick_tracks)}")
|
| 78 |
-
|
| 79 |
-
# Success criteria
|
| 80 |
-
if len(mkgee_tracks_in_kendrick) == 0:
|
| 81 |
-
print("β
SUCCESS: No Mk.gee tracks in Kendrick query (follow-up NOT detected)")
|
| 82 |
-
else:
|
| 83 |
-
print("β FAILURE: Mk.gee tracks found in Kendrick query (follow-up incorrectly detected)")
|
| 84 |
-
for track in mkgee_tracks_in_kendrick:
|
| 85 |
-
print(f" - {track.artist} - {track.name}")
|
| 86 |
-
|
| 87 |
-
if len(kendrick_tracks) > 0:
|
| 88 |
-
print("β
SUCCESS: Found actual Kendrick Lamar tracks")
|
| 89 |
-
for track in kendrick_tracks[:3]:
|
| 90 |
-
print(f" - {track.artist} - {track.name}")
|
| 91 |
-
else:
|
| 92 |
-
print("β οΈ WARNING: No Kendrick Lamar tracks found (intent detection may need work)")
|
| 93 |
-
|
| 94 |
-
# Test Case 3: Same artist follow-up - should BE detected as follow-up
|
| 95 |
-
print("\nπ΅ TEST CASE 3: Same Artist Follow-up - 'More from Mk.gee'")
|
| 96 |
-
request3 = RecommendationRequest(
|
| 97 |
-
query="More from Mk.gee",
|
| 98 |
-
max_recommendations=5,
|
| 99 |
-
session_id="test_session_fix",
|
| 100 |
-
context={
|
| 101 |
-
"previous_queries": ["Discover underground tracks by Mk.gee"],
|
| 102 |
-
"previous_recommendations": [
|
| 103 |
-
[
|
| 104 |
-
{"artist": track.artist, "title": track.name}
|
| 105 |
-
for track in response1.recommendations[:5]
|
| 106 |
-
]
|
| 107 |
-
]
|
| 108 |
-
}
|
| 109 |
-
)
|
| 110 |
-
|
| 111 |
-
response3 = await service.get_recommendations(request3)
|
| 112 |
-
print(f"β
Third query completed: {len(response3.recommendations)} tracks found")
|
| 113 |
-
|
| 114 |
-
# Check for duplicates with first query
|
| 115 |
-
first_track_ids = {f"{track.artist.lower()}::{track.name.lower()}" for track in response1.recommendations}
|
| 116 |
-
third_track_ids = {f"{track.artist.lower()}::{track.name.lower()}" for track in response3.recommendations}
|
| 117 |
-
duplicates = first_track_ids.intersection(third_track_ids)
|
| 118 |
-
|
| 119 |
-
print(f"π Duplicates between first and third query: {len(duplicates)}")
|
| 120 |
-
|
| 121 |
-
if len(duplicates) == 0:
|
| 122 |
-
print("β
SUCCESS: No duplicates in same-artist follow-up (duplicate prevention working)")
|
| 123 |
-
else:
|
| 124 |
-
print("β οΈ NOTE: Some duplicates found (may be expected if database is limited)")
|
| 125 |
-
for dup in list(duplicates)[:3]:
|
| 126 |
-
print(f" - {dup}")
|
| 127 |
-
|
| 128 |
-
except Exception as e:
|
| 129 |
-
print(f"β ERROR during testing: {e}")
|
| 130 |
-
import traceback
|
| 131 |
-
traceback.print_exc()
|
| 132 |
-
|
| 133 |
-
finally:
|
| 134 |
-
await service.close()
|
| 135 |
-
|
| 136 |
-
if __name__ == "__main__":
|
| 137 |
-
asyncio.run(test_followup_detection_fix())
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
test_history_filtering.py
DELETED
|
@@ -1,253 +0,0 @@
|
|
| 1 |
-
#!/usr/bin/env python3
|
| 2 |
-
"""
|
| 3 |
-
Test script to verify history tracking and duplicate filtering for follow-up queries
|
| 4 |
-
"""
|
| 5 |
-
|
| 6 |
-
import asyncio
|
| 7 |
-
import logging
|
| 8 |
-
from typing import Dict, Any, List
|
| 9 |
-
|
| 10 |
-
# Configure logging
|
| 11 |
-
logging.basicConfig(level=logging.INFO)
|
| 12 |
-
logger = logging.getLogger(__name__)
|
| 13 |
-
|
| 14 |
-
async def test_history_filtering_end_to_end():
|
| 15 |
-
"""Test that follow-up queries don't return duplicate recommendations."""
|
| 16 |
-
|
| 17 |
-
# Import here to avoid circular dependencies
|
| 18 |
-
from src.services.enhanced_recommendation_service import EnhancedRecommendationService, RecommendationRequest
|
| 19 |
-
from src.services.api_service import APIService
|
| 20 |
-
|
| 21 |
-
# Initialize services
|
| 22 |
-
api_service = APIService()
|
| 23 |
-
service = EnhancedRecommendationService(api_service)
|
| 24 |
-
|
| 25 |
-
print("π§ͺ Testing End-to-End History Filtering")
|
| 26 |
-
print("=" * 60)
|
| 27 |
-
|
| 28 |
-
session_id = "test_session_e2e"
|
| 29 |
-
|
| 30 |
-
# Step 1: Initial query
|
| 31 |
-
print("π΅ STEP 1: Initial Query - 'Music like Mk.gee'")
|
| 32 |
-
|
| 33 |
-
request1 = RecommendationRequest(
|
| 34 |
-
query="Music like Mk.gee",
|
| 35 |
-
max_recommendations=5,
|
| 36 |
-
session_id=session_id
|
| 37 |
-
)
|
| 38 |
-
|
| 39 |
-
response1 = await service.get_recommendations(request1)
|
| 40 |
-
initial_tracks = response1.recommendations
|
| 41 |
-
|
| 42 |
-
print(f"β
Initial query returned {len(initial_tracks)} recommendations")
|
| 43 |
-
|
| 44 |
-
initial_track_names = []
|
| 45 |
-
initial_track_ids = set()
|
| 46 |
-
|
| 47 |
-
print("Initial recommendations:")
|
| 48 |
-
for i, rec in enumerate(initial_tracks, 1):
|
| 49 |
-
track_name = f"{rec.name} by {rec.artist}"
|
| 50 |
-
initial_track_names.append(track_name)
|
| 51 |
-
track_id = f"{rec.artist.lower()}::{rec.name.lower()}"
|
| 52 |
-
initial_track_ids.add(track_id)
|
| 53 |
-
print(f" {i}. {track_name}")
|
| 54 |
-
print()
|
| 55 |
-
|
| 56 |
-
# Step 2: Follow-up query with correct context format
|
| 57 |
-
print("π΅ STEP 2: Follow-up Query - 'More like that'")
|
| 58 |
-
|
| 59 |
-
# β
CORRECT FORMAT: Use the request.context format that the real chat interface uses
|
| 60 |
-
request2 = RecommendationRequest(
|
| 61 |
-
query="More like that",
|
| 62 |
-
max_recommendations=10,
|
| 63 |
-
session_id="test_session_e2e",
|
| 64 |
-
context={
|
| 65 |
-
"previous_queries": ["Music like Mk.gee"],
|
| 66 |
-
"previous_recommendations": [
|
| 67 |
-
[
|
| 68 |
-
{"artist": track.artist, "title": track.name}
|
| 69 |
-
for track in initial_tracks
|
| 70 |
-
]
|
| 71 |
-
]
|
| 72 |
-
}
|
| 73 |
-
)
|
| 74 |
-
|
| 75 |
-
response2 = await service.get_recommendations(request2)
|
| 76 |
-
followup_tracks = response2.recommendations
|
| 77 |
-
|
| 78 |
-
print(f"β
Follow-up query returned {len(followup_tracks)} recommendations")
|
| 79 |
-
|
| 80 |
-
print("Follow-up recommendations:")
|
| 81 |
-
duplicates_found = []
|
| 82 |
-
for i, rec in enumerate(followup_tracks, 1):
|
| 83 |
-
track_name = f"{rec.name} by {rec.artist}"
|
| 84 |
-
track_id = f"{rec.artist.lower()}::{rec.name.lower()}"
|
| 85 |
-
|
| 86 |
-
# Check if this is a duplicate
|
| 87 |
-
is_duplicate = track_id in initial_track_ids
|
| 88 |
-
duplicate_indicator = " β DUPLICATE" if is_duplicate else ""
|
| 89 |
-
|
| 90 |
-
print(f" {i}. {track_name}{duplicate_indicator}")
|
| 91 |
-
|
| 92 |
-
if is_duplicate:
|
| 93 |
-
duplicates_found.append(track_name)
|
| 94 |
-
print()
|
| 95 |
-
|
| 96 |
-
# Step 3: Analysis
|
| 97 |
-
print("π STEP 3: Duplicate Analysis")
|
| 98 |
-
print(f"Initial track IDs: {len(initial_track_ids)}")
|
| 99 |
-
print(f"Follow-up duplicates found: {len(duplicates_found)}")
|
| 100 |
-
|
| 101 |
-
# Check response metadata for context decision
|
| 102 |
-
context_decision = response2.metadata.get("context_decision", {})
|
| 103 |
-
print(f"Context Analysis Results:")
|
| 104 |
-
print(f" - Is follow-up: {context_decision.get('is_followup', 'Unknown')}")
|
| 105 |
-
print(f" - Intent override: {context_decision.get('intent_override', 'None')}")
|
| 106 |
-
print(f" - Target entity: {context_decision.get('target_entity', 'None')}")
|
| 107 |
-
print(f" - Confidence: {context_decision.get('confidence', 'Unknown')}")
|
| 108 |
-
|
| 109 |
-
if duplicates_found:
|
| 110 |
-
print("β DUPLICATES FOUND:")
|
| 111 |
-
for dup in duplicates_found:
|
| 112 |
-
print(f" - {dup}")
|
| 113 |
-
return False
|
| 114 |
-
else:
|
| 115 |
-
print("β
SUCCESS: No duplicates found in follow-up query!")
|
| 116 |
-
return True
|
| 117 |
-
|
| 118 |
-
async def test_artist_deep_dive_filtering():
|
| 119 |
-
"""Test artist deep dive follow-up behavior."""
|
| 120 |
-
|
| 121 |
-
from src.services.enhanced_recommendation_service import EnhancedRecommendationService, RecommendationRequest
|
| 122 |
-
from src.services.api_service import APIService
|
| 123 |
-
|
| 124 |
-
print("\nπ§ͺ Testing Artist Deep Dive History Filtering")
|
| 125 |
-
print("=" * 60)
|
| 126 |
-
|
| 127 |
-
# Initialize services
|
| 128 |
-
api_service = APIService()
|
| 129 |
-
service = EnhancedRecommendationService(api_service)
|
| 130 |
-
|
| 131 |
-
session_id = "test_session_artist_dive"
|
| 132 |
-
|
| 133 |
-
# Step 1: Get some Mk.gee tracks
|
| 134 |
-
print("π΅ STEP 1: Initial Query - 'Music by Mk.gee'")
|
| 135 |
-
|
| 136 |
-
request1 = RecommendationRequest(
|
| 137 |
-
query="Music by Mk.gee",
|
| 138 |
-
max_recommendations=10,
|
| 139 |
-
session_id=session_id
|
| 140 |
-
)
|
| 141 |
-
|
| 142 |
-
response1 = await service.get_recommendations(request1)
|
| 143 |
-
initial_tracks = response1.recommendations
|
| 144 |
-
|
| 145 |
-
print(f"β
Initial query returned {len(initial_tracks)} recommendations")
|
| 146 |
-
|
| 147 |
-
mkgee_tracks = []
|
| 148 |
-
mkgee_track_ids = set()
|
| 149 |
-
mkgee_track_count = 0
|
| 150 |
-
|
| 151 |
-
for track in initial_tracks:
|
| 152 |
-
if 'mk.gee' in track.artist.lower():
|
| 153 |
-
mkgee_track_count += 1
|
| 154 |
-
mkgee_tracks.append(track)
|
| 155 |
-
track_id = f"{track.artist.lower()}::{track.name.lower()}"
|
| 156 |
-
mkgee_track_ids.add(track_id)
|
| 157 |
-
print(f" - {track.name} by {track.artist}")
|
| 158 |
-
|
| 159 |
-
print(f"Found {mkgee_track_count} tracks by Mk.gee")
|
| 160 |
-
|
| 161 |
-
# Step 2: Follow-up query with correct context format
|
| 162 |
-
print("π΅ STEP 2: Follow-up Query - 'More from Mk.gee'")
|
| 163 |
-
|
| 164 |
-
# β
CORRECT FORMAT: Use the request.context format that the real chat interface uses
|
| 165 |
-
request2 = RecommendationRequest(
|
| 166 |
-
query="More from Mk.gee",
|
| 167 |
-
max_recommendations=10,
|
| 168 |
-
session_id="test_session_artist_dive",
|
| 169 |
-
context={
|
| 170 |
-
"previous_queries": ["Music by Mk.gee"],
|
| 171 |
-
"previous_recommendations": [
|
| 172 |
-
[
|
| 173 |
-
{"artist": track.artist, "title": track.name}
|
| 174 |
-
for track in initial_tracks
|
| 175 |
-
]
|
| 176 |
-
]
|
| 177 |
-
}
|
| 178 |
-
)
|
| 179 |
-
|
| 180 |
-
response2 = await service.get_recommendations(request2)
|
| 181 |
-
followup_tracks = response2.recommendations
|
| 182 |
-
|
| 183 |
-
print(f"β
Follow-up query returned {len(followup_tracks)} recommendations")
|
| 184 |
-
|
| 185 |
-
# Check for duplicates specifically from Mk.gee
|
| 186 |
-
mkgee_duplicates = []
|
| 187 |
-
new_mkgee_tracks = 0
|
| 188 |
-
|
| 189 |
-
for track in followup_tracks:
|
| 190 |
-
if 'mk.gee' in track.artist.lower():
|
| 191 |
-
new_mkgee_tracks += 1
|
| 192 |
-
track_id = f"{track.artist.lower()}::{track.name.lower()}"
|
| 193 |
-
|
| 194 |
-
if track_id in mkgee_track_ids:
|
| 195 |
-
mkgee_duplicates.append(f"{track.name} by {track.artist}")
|
| 196 |
-
print(f" β DUPLICATE: {track.name} by {track.artist}")
|
| 197 |
-
else:
|
| 198 |
-
print(f" + NEW: {track.name} by {track.artist}")
|
| 199 |
-
|
| 200 |
-
print(f"\nFound {new_mkgee_tracks} Mk.gee tracks in follow-up")
|
| 201 |
-
print(f"Mk.gee duplicates: {len(mkgee_duplicates)}")
|
| 202 |
-
|
| 203 |
-
# Check response metadata
|
| 204 |
-
context_decision = response2.metadata.get("context_decision", {})
|
| 205 |
-
print(f"Context Analysis Results:")
|
| 206 |
-
print(f" - Is follow-up: {context_decision.get('is_followup', 'Unknown')}")
|
| 207 |
-
print(f" - Intent override: {context_decision.get('intent_override', 'None')}")
|
| 208 |
-
print(f" - Target entity: {context_decision.get('target_entity', 'None')}")
|
| 209 |
-
print(f" - Confidence: {context_decision.get('confidence', 'Unknown')}")
|
| 210 |
-
|
| 211 |
-
if mkgee_duplicates:
|
| 212 |
-
print("β MK.GEE DUPLICATES FOUND:")
|
| 213 |
-
for dup in mkgee_duplicates:
|
| 214 |
-
print(f" - {dup}")
|
| 215 |
-
return False
|
| 216 |
-
else:
|
| 217 |
-
print("β
SUCCESS: No duplicate Mk.gee tracks in follow-up!")
|
| 218 |
-
return True
|
| 219 |
-
|
| 220 |
-
async def main():
|
| 221 |
-
"""Run comprehensive follow-up tests."""
|
| 222 |
-
|
| 223 |
-
print("π Starting Comprehensive History Filtering Tests")
|
| 224 |
-
print("=" * 60)
|
| 225 |
-
|
| 226 |
-
try:
|
| 227 |
-
# Test 1: Style continuation ("More like that")
|
| 228 |
-
style_success = await test_history_filtering_end_to_end()
|
| 229 |
-
|
| 230 |
-
# Test 2: Artist deep dive ("More from [Artist]")
|
| 231 |
-
artist_success = await test_artist_deep_dive_filtering()
|
| 232 |
-
|
| 233 |
-
print("\n" + "=" * 60)
|
| 234 |
-
print("π FINAL TEST RESULTS:")
|
| 235 |
-
print(f" Style Continuation ('More like that'): {'β
PASS' if style_success else 'β FAIL'}")
|
| 236 |
-
print(f" Artist Deep Dive ('More from Artist'): {'β
PASS' if artist_success else 'β FAIL'}")
|
| 237 |
-
|
| 238 |
-
if style_success and artist_success:
|
| 239 |
-
print("\nπ ALL HISTORY FILTERING TESTS PASSED!")
|
| 240 |
-
print("β
History filtering is working correctly.")
|
| 241 |
-
print("β
No duplicate recommendations in follow-up queries.")
|
| 242 |
-
else:
|
| 243 |
-
print("\nβ SOME HISTORY FILTERING TESTS FAILED.")
|
| 244 |
-
print("π§ Check the history filtering implementation.")
|
| 245 |
-
print("π‘ This indicates the system may be returning duplicate tracks in follow-up queries.")
|
| 246 |
-
|
| 247 |
-
except Exception as e:
|
| 248 |
-
print(f"\nπ₯ Test execution failed: {str(e)}")
|
| 249 |
-
import traceback
|
| 250 |
-
traceback.print_exc()
|
| 251 |
-
|
| 252 |
-
if __name__ == "__main__":
|
| 253 |
-
asyncio.run(main())
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
test_hybrid_context.py
DELETED
|
@@ -1,155 +0,0 @@
|
|
| 1 |
-
"""
|
| 2 |
-
Test script to verify hybrid query context preservation
|
| 3 |
-
"""
|
| 4 |
-
import sys
|
| 5 |
-
import os
|
| 6 |
-
sys.path.append('src')
|
| 7 |
-
|
| 8 |
-
from models.agent_models import MusicRecommenderState, AgentConfig, SystemConfig
|
| 9 |
-
from models.metadata_models import UnifiedTrackMetadata
|
| 10 |
-
from services.enhanced_recommendation_service import ContextAwareIntentAnalyzer
|
| 11 |
-
|
| 12 |
-
def test_context_preservation():
|
| 13 |
-
"""Test that R&B genre is preserved in follow-up queries"""
|
| 14 |
-
print("π§ͺ Testing hybrid query context preservation...")
|
| 15 |
-
|
| 16 |
-
# Mock conversation history for "Songs by Michael Jackson that are R&B"
|
| 17 |
-
conversation_history = [{
|
| 18 |
-
'query': 'Songs by Michael Jackson that are R&B',
|
| 19 |
-
'recommendations': [
|
| 20 |
-
{
|
| 21 |
-
'title': 'Black or White',
|
| 22 |
-
'artist': 'Michael Jackson',
|
| 23 |
-
'genres': ['r&b', 'pop'],
|
| 24 |
-
'moods': ['pop', 'michael jackson', '90s']
|
| 25 |
-
},
|
| 26 |
-
{
|
| 27 |
-
'title': 'Man in the Mirror',
|
| 28 |
-
'artist': 'Michael Jackson',
|
| 29 |
-
'genres': ['r&b', 'soul'],
|
| 30 |
-
'moods': ['pop', 'michael jackson', '80s', 'soul']
|
| 31 |
-
}
|
| 32 |
-
],
|
| 33 |
-
'extracted_entities': {
|
| 34 |
-
'artists': {'primary': [{'name': 'Michael Jackson', 'confidence': 0.9}]},
|
| 35 |
-
'genres': {'primary': [{'name': 'R&B', 'confidence': 0.9}]},
|
| 36 |
-
'tracks': {'primary': []},
|
| 37 |
-
'moods': {'primary': []}
|
| 38 |
-
}
|
| 39 |
-
}]
|
| 40 |
-
|
| 41 |
-
print(f"π Original query: {conversation_history[0]['query']}")
|
| 42 |
-
print(f"π΅ Original entities: {conversation_history[0].get('extracted_entities', {})}")
|
| 43 |
-
|
| 44 |
-
# Create analyzer (without LLM for testing)
|
| 45 |
-
analyzer = ContextAwareIntentAnalyzer(llm_client=None)
|
| 46 |
-
|
| 47 |
-
# Test 1: Extract complete entities from history
|
| 48 |
-
print("\nπ Testing _extract_complete_entities_from_history...")
|
| 49 |
-
try:
|
| 50 |
-
complete_entities = analyzer._extract_complete_entities_from_history(conversation_history)
|
| 51 |
-
print(f"β
Complete entities extracted: {complete_entities}")
|
| 52 |
-
|
| 53 |
-
# Check if genres are preserved
|
| 54 |
-
genres = complete_entities.get('genres', {}).get('primary', [])
|
| 55 |
-
print(f"π΅ Genres found in history: {genres}")
|
| 56 |
-
|
| 57 |
-
if any('r&b' in str(g).lower() for g in genres):
|
| 58 |
-
print("β
SUCCESS: R&B genre found in extracted entities!")
|
| 59 |
-
else:
|
| 60 |
-
print("β ISSUE: R&B genre not found in extracted entities")
|
| 61 |
-
|
| 62 |
-
except Exception as e:
|
| 63 |
-
print(f"β ERROR in entity extraction: {e}")
|
| 64 |
-
|
| 65 |
-
# Test 2: Create context override for follow-up
|
| 66 |
-
print("\nπ― Testing _create_context_override_from_llm...")
|
| 67 |
-
try:
|
| 68 |
-
# Simulate LLM detecting artist follow-up
|
| 69 |
-
llm_result = {
|
| 70 |
-
'is_followup': True,
|
| 71 |
-
'followup_type': 'artist_deep_dive',
|
| 72 |
-
'target_entity': 'Michael Jackson',
|
| 73 |
-
'confidence': 0.9,
|
| 74 |
-
'reasoning': "User wants more tracks by Michael Jackson"
|
| 75 |
-
}
|
| 76 |
-
|
| 77 |
-
context_override = analyzer._create_context_override_from_llm(llm_result, conversation_history)
|
| 78 |
-
print(f"π― Context override created: {context_override}")
|
| 79 |
-
|
| 80 |
-
# Check preserved genres
|
| 81 |
-
preserved_genres = context_override.get('preserved_genres', [])
|
| 82 |
-
constraint_overrides = context_override.get('constraint_overrides', {})
|
| 83 |
-
|
| 84 |
-
print(f"π΅ Preserved genres: {preserved_genres}")
|
| 85 |
-
print(f"π§ Constraint overrides: {constraint_overrides}")
|
| 86 |
-
|
| 87 |
-
if preserved_genres and any('r&b' in str(g).lower() for g in preserved_genres):
|
| 88 |
-
print("β
SUCCESS: R&B genre preserved in context override!")
|
| 89 |
-
else:
|
| 90 |
-
print("β ISSUE: R&B genre not preserved in context override")
|
| 91 |
-
|
| 92 |
-
# Check if intent is properly set for hybrid queries
|
| 93 |
-
intent_override = context_override.get('intent_override')
|
| 94 |
-
print(f"π Intent override: {intent_override}")
|
| 95 |
-
|
| 96 |
-
if intent_override in ['hybrid_artist_genre', 'by_artist']:
|
| 97 |
-
print("β
SUCCESS: Appropriate intent for hybrid query!")
|
| 98 |
-
else:
|
| 99 |
-
print("β ISSUE: Intent not appropriate for hybrid query")
|
| 100 |
-
|
| 101 |
-
except Exception as e:
|
| 102 |
-
print(f"β ERROR in context override: {e}")
|
| 103 |
-
|
| 104 |
-
return context_override
|
| 105 |
-
|
| 106 |
-
def test_discovery_agent_context():
|
| 107 |
-
"""Test that Discovery Agent can handle preserved genres"""
|
| 108 |
-
print("\nπ Testing Discovery Agent context handling...")
|
| 109 |
-
|
| 110 |
-
# Mock context override with preserved R&B genre
|
| 111 |
-
context_override = {
|
| 112 |
-
'is_followup': True,
|
| 113 |
-
'target_entity': 'Michael Jackson',
|
| 114 |
-
'intent_override': 'hybrid_artist_genre',
|
| 115 |
-
'preserved_genres': ['R&B'],
|
| 116 |
-
'constraint_overrides': {
|
| 117 |
-
'genre_requirements': ['R&B'],
|
| 118 |
-
'diversity_limits': {'same_artist_limit': 10}
|
| 119 |
-
}
|
| 120 |
-
}
|
| 121 |
-
|
| 122 |
-
print(f"π― Testing context override: {context_override}")
|
| 123 |
-
|
| 124 |
-
# Check if Discovery Agent would handle this correctly
|
| 125 |
-
preserved_genres = context_override.get('preserved_genres', [])
|
| 126 |
-
constraint_overrides = context_override.get('constraint_overrides', {})
|
| 127 |
-
genre_requirements = constraint_overrides.get('genre_requirements', [])
|
| 128 |
-
|
| 129 |
-
print(f"π΅ Preserved genres: {preserved_genres}")
|
| 130 |
-
print(f"π Genre requirements: {genre_requirements}")
|
| 131 |
-
|
| 132 |
-
if preserved_genres and genre_requirements:
|
| 133 |
-
print("β
SUCCESS: Discovery Agent should apply R&B filtering!")
|
| 134 |
-
else:
|
| 135 |
-
print("β ISSUE: Missing genre requirements for Discovery Agent")
|
| 136 |
-
|
| 137 |
-
if __name__ == "__main__":
|
| 138 |
-
print("πΌ BeatDebate Hybrid Query Context Test")
|
| 139 |
-
print("=" * 50)
|
| 140 |
-
|
| 141 |
-
try:
|
| 142 |
-
context_override = test_context_preservation()
|
| 143 |
-
test_discovery_agent_context()
|
| 144 |
-
|
| 145 |
-
print("\n" + "=" * 50)
|
| 146 |
-
print("π― Test Summary:")
|
| 147 |
-
print("- Follow-up detection: Should work β
")
|
| 148 |
-
print("- Artist preservation: Should work β
")
|
| 149 |
-
print("- Genre preservation: Needs verification π")
|
| 150 |
-
print("- Hybrid intent handling: Needs verification π")
|
| 151 |
-
|
| 152 |
-
except Exception as e:
|
| 153 |
-
print(f"β Test failed with error: {e}")
|
| 154 |
-
import traceback
|
| 155 |
-
traceback.print_exc()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
test_kendrick_followup.py
DELETED
|
@@ -1,47 +0,0 @@
|
|
| 1 |
-
#!/usr/bin/env python3
|
| 2 |
-
"""Test Kendrick Lamar follow-up scenario that was failing."""
|
| 3 |
-
|
| 4 |
-
from src.services.enhanced_recommendation_service import EnhancedRecommendationService, RecommendationRequest
|
| 5 |
-
import asyncio
|
| 6 |
-
|
| 7 |
-
async def test_kendrick_followup():
|
| 8 |
-
print('Testing Kendrick Lamar follow-up after Music by Kendrick Lamar...')
|
| 9 |
-
|
| 10 |
-
service = EnhancedRecommendationService()
|
| 11 |
-
|
| 12 |
-
# First query - Music by Kendrick Lamar
|
| 13 |
-
request1 = RecommendationRequest(
|
| 14 |
-
query='Music by Kendrick Lamar',
|
| 15 |
-
max_recommendations=10,
|
| 16 |
-
session_id='test_kendrick_session'
|
| 17 |
-
)
|
| 18 |
-
result1 = await service.get_recommendations(request1)
|
| 19 |
-
|
| 20 |
-
print(f'First query returned {len(result1.recommendations)} tracks')
|
| 21 |
-
first_track_ids = [f"{r.artist.lower()}::{r.name.lower()}" for r in result1.recommendations]
|
| 22 |
-
print(f'First query track IDs: {first_track_ids[:3]}...')
|
| 23 |
-
|
| 24 |
-
# Follow-up query - More Kendrick Lamar tracks
|
| 25 |
-
request2 = RecommendationRequest(
|
| 26 |
-
query='More Kendrick Lamar tracks',
|
| 27 |
-
max_recommendations=10,
|
| 28 |
-
session_id='test_kendrick_session'
|
| 29 |
-
)
|
| 30 |
-
result2 = await service.get_recommendations(request2)
|
| 31 |
-
|
| 32 |
-
print(f'Follow-up query returned {len(result2.recommendations)} tracks')
|
| 33 |
-
second_track_ids = [f"{r.artist.lower()}::{r.name.lower()}" for r in result2.recommendations]
|
| 34 |
-
|
| 35 |
-
# Check for duplicates
|
| 36 |
-
duplicates = set(first_track_ids) & set(second_track_ids)
|
| 37 |
-
print(f'Duplicates: {len(duplicates)}')
|
| 38 |
-
if duplicates:
|
| 39 |
-
print(f'Duplicate tracks: {list(duplicates)[:3]}...')
|
| 40 |
-
|
| 41 |
-
if len(result2.recommendations) >= 8:
|
| 42 |
-
print('β
PASS: Follow-up returned sufficient tracks!')
|
| 43 |
-
else:
|
| 44 |
-
print(f'β FAIL: Follow-up only returned {len(result2.recommendations)} tracks, expected 8+')
|
| 45 |
-
|
| 46 |
-
if __name__ == '__main__':
|
| 47 |
-
asyncio.run(test_kendrick_followup())
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
test_simple_extraction.py
DELETED
|
@@ -1,58 +0,0 @@
|
|
| 1 |
-
#!/usr/bin/env python3
|
| 2 |
-
"""
|
| 3 |
-
Simple test to verify track extraction logic
|
| 4 |
-
"""
|
| 5 |
-
|
| 6 |
-
def test_extraction_logic():
|
| 7 |
-
"""Test the _extract_recently_shown_tracks logic separately."""
|
| 8 |
-
|
| 9 |
-
from src.services.enhanced_recommendation_service import EnhancedRecommendationService
|
| 10 |
-
from src.services.api_service import APIService
|
| 11 |
-
|
| 12 |
-
print("π§ͺ Testing Extraction Logic")
|
| 13 |
-
print("=" * 60)
|
| 14 |
-
|
| 15 |
-
# Create service instance
|
| 16 |
-
api_service = APIService()
|
| 17 |
-
service = EnhancedRecommendationService(api_service)
|
| 18 |
-
|
| 19 |
-
# Test conversation history
|
| 20 |
-
conversation_history = [
|
| 21 |
-
{
|
| 22 |
-
"query": "Music like Mk.gee",
|
| 23 |
-
"recommendations": [
|
| 24 |
-
{"artist": "ML BUCH", "title": "I'm A Girl You Can Hold IRL"},
|
| 25 |
-
{"artist": "Chanel Beads", "title": "Police Scanner"},
|
| 26 |
-
{"artist": "DIJON", "title": "do you light up?"}
|
| 27 |
-
]
|
| 28 |
-
}
|
| 29 |
-
]
|
| 30 |
-
|
| 31 |
-
# Test context override for "More like that"
|
| 32 |
-
context_override = {
|
| 33 |
-
'is_followup': True,
|
| 34 |
-
'intent_override': 'style_continuation',
|
| 35 |
-
'target_entity': '',
|
| 36 |
-
'confidence': 0.9
|
| 37 |
-
}
|
| 38 |
-
|
| 39 |
-
# Extract recently shown tracks
|
| 40 |
-
recently_shown = service._extract_recently_shown_tracks(
|
| 41 |
-
conversation_history,
|
| 42 |
-
context_override
|
| 43 |
-
)
|
| 44 |
-
|
| 45 |
-
print(f"Extracted {len(recently_shown)} recently shown track IDs:")
|
| 46 |
-
for track_id in recently_shown:
|
| 47 |
-
print(f" - {track_id}")
|
| 48 |
-
|
| 49 |
-
expected_count = 3 # Should match the 3 tracks in conversation history
|
| 50 |
-
if len(recently_shown) == expected_count:
|
| 51 |
-
print("β
SUCCESS: Extraction logic working correctly!")
|
| 52 |
-
return True
|
| 53 |
-
else:
|
| 54 |
-
print(f"β FAILURE: Expected {expected_count} tracks, got {len(recently_shown)}")
|
| 55 |
-
return False
|
| 56 |
-
|
| 57 |
-
if __name__ == "__main__":
|
| 58 |
-
test_extraction_logic()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
test_state_fix.py
DELETED
|
@@ -1,71 +0,0 @@
|
|
| 1 |
-
#!/usr/bin/env python3
|
| 2 |
-
"""
|
| 3 |
-
Quick test to verify the state management fix works
|
| 4 |
-
"""
|
| 5 |
-
import asyncio
|
| 6 |
-
import sys
|
| 7 |
-
import os
|
| 8 |
-
sys.path.append('src')
|
| 9 |
-
|
| 10 |
-
from services.enhanced_recommendation_service import get_recommendation_service, RecommendationRequest
|
| 11 |
-
|
| 12 |
-
async def test_state_management_fix():
|
| 13 |
-
print('π§ͺ Testing state management fix...')
|
| 14 |
-
|
| 15 |
-
# Set up environment
|
| 16 |
-
os.environ['GEMINI_API_KEY'] = os.environ.get('GEMINI_API_KEY', 'test-key')
|
| 17 |
-
os.environ['LASTFM_API_KEY'] = os.environ.get('LASTFM_API_KEY', 'test-key')
|
| 18 |
-
os.environ['SPOTIFY_CLIENT_ID'] = os.environ.get('SPOTIFY_CLIENT_ID', 'test-id')
|
| 19 |
-
os.environ['SPOTIFY_CLIENT_SECRET'] = os.environ.get('SPOTIFY_CLIENT_SECRET', 'test-secret')
|
| 20 |
-
|
| 21 |
-
service = get_recommendation_service()
|
| 22 |
-
await service.initialize_agents()
|
| 23 |
-
|
| 24 |
-
# Simulate follow-up query with conversation history
|
| 25 |
-
request = RecommendationRequest(
|
| 26 |
-
query='More tracks by Kendrick Lamar',
|
| 27 |
-
session_id='test_session',
|
| 28 |
-
max_recommendations=10,
|
| 29 |
-
context={
|
| 30 |
-
'previous_queries': ['Music by Kendrick Lamar'],
|
| 31 |
-
'previous_recommendations': [[
|
| 32 |
-
{'artist': 'Kendrick Lamar', 'title': 'HUMBLE.', 'album': 'DAMN.'},
|
| 33 |
-
{'artist': 'Kendrick Lamar', 'title': 'Alright', 'album': 'To Pimp a Butterfly'},
|
| 34 |
-
{'artist': 'Kendrick Lamar', 'title': 'm.A.A.d city', 'album': 'good kid, m.A.A.d city'},
|
| 35 |
-
{'artist': 'Kendrick Lamar', 'title': 'DNA.', 'album': 'DAMN.'},
|
| 36 |
-
{'artist': 'Kendrick Lamar', 'title': 'King Kunta', 'album': 'To Pimp a Butterfly'}
|
| 37 |
-
]]
|
| 38 |
-
}
|
| 39 |
-
)
|
| 40 |
-
|
| 41 |
-
print('π Testing with follow-up query and 5 previous Kendrick Lamar tracks...')
|
| 42 |
-
print('π Looking for logs showing:')
|
| 43 |
-
print(' - π― STATE PREPARED: recently_shown=5 tracks')
|
| 44 |
-
print(' - π― DISCOVERY AGENT STATE: recently_shown=5 tracks')
|
| 45 |
-
print(' - π― CANDIDATE SCALING: [scaled number] (from 100)')
|
| 46 |
-
print()
|
| 47 |
-
|
| 48 |
-
try:
|
| 49 |
-
response = await service.get_recommendations(request)
|
| 50 |
-
print(f'β
SUCCESS: Got {len(response.recommendations)} recommendations')
|
| 51 |
-
|
| 52 |
-
# Check if it detected follow-up correctly
|
| 53 |
-
context_decision = response.metadata.get('context_decision', {})
|
| 54 |
-
if context_decision.get('is_followup'):
|
| 55 |
-
print(f'π― FOLLOW-UP DETECTED: {context_decision.get("target_entity")}')
|
| 56 |
-
else:
|
| 57 |
-
print(f'β FOLLOW-UP NOT DETECTED')
|
| 58 |
-
|
| 59 |
-
return len(response.recommendations)
|
| 60 |
-
|
| 61 |
-
except Exception as e:
|
| 62 |
-
print(f'β ERROR: {e}')
|
| 63 |
-
import traceback
|
| 64 |
-
traceback.print_exc()
|
| 65 |
-
return 0
|
| 66 |
-
finally:
|
| 67 |
-
await service.close()
|
| 68 |
-
|
| 69 |
-
if __name__ == "__main__":
|
| 70 |
-
result = asyncio.run(test_state_management_fix())
|
| 71 |
-
print(f'π Final result: {result} recommendations')
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|