File size: 7,992 Bytes
c7e434a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
"""
Audio Processor - Main Orchestrator
Koordinasi semua analisis audio
"""

import time
from typing import Dict, Optional, List
from app.config import settings
from app.services.speech_to_text import SpeechToTextService
from app.services.tempo import TempoService
from app.services.articulation import ArticulationService, ProfanityDetector
from app.services.structure import StructureService
from app.services.keywords import KeywordService


class AudioProcessor:
    """Main orchestrator untuk audio analysis"""
    
    def __init__(self):
        """Initialize all services"""
        print("πŸš€ Initializing Audio Processor...")
        
        # Initialize services (lazy loading)
        self._stt_service = None
        self._tempo_service = None
        self._articulation_service = None
        self._structure_service = None
        self._keyword_service = None
        
        print("βœ… Audio Processor ready!\n")
    
    @property
    def stt_service(self):
        """Lazy load STT service"""
        if self._stt_service is None:
            self._stt_service = SpeechToTextService(
                model_name=settings.WHISPER_MODEL,
                device="auto",  # Auto-detect GPU/CPU
                language="id"
            )
        return self._stt_service
    
    @property
    def tempo_service(self):
        """Lazy load Tempo service"""
        if self._tempo_service is None:
            self._tempo_service = TempoService()
        return self._tempo_service
    
    @property
    def articulation_service(self):
        """Lazy load Articulation service"""
        if self._articulation_service is None:
            self._articulation_service = ArticulationService()
        return self._articulation_service
    
    @property
    def structure_service(self):
        """Lazy load Structure service"""
        if self._structure_service is None:
            # Uses default 'Cyberlace/swara-structure-model' from HF Hub
            self._structure_service = StructureService()
        return self._structure_service
    
    @property
    def keyword_service(self):
        """Lazy load Keyword service"""
        if self._keyword_service is None:
            self._keyword_service = KeywordService(
                dataset_path=settings.KATA_KUNCI_PATH
            )
        return self._keyword_service
    
    def process_audio(
        self,
        audio_path: str,
        reference_text: Optional[str] = None,
        topic_id: Optional[str] = None,
        custom_topic: Optional[str] = None,
        custom_keywords: Optional[List[str]] = None,
        analyze_tempo: bool = True,
        analyze_articulation: bool = True,
        analyze_structure: bool = True,
        analyze_keywords: bool = False,
        analyze_profanity: bool = False
    ) -> Dict:
        """
        Process audio file dengan semua analisis yang diminta
        
        Args:
            audio_path: Path ke file audio
            reference_text: Teks referensi (untuk artikulasi)
            topic_id: ID topik dari database (untuk Level 1-2)
            custom_topic: Topik custom dari user (untuk Level 3)
            custom_keywords: List kata kunci dari GPT (untuk Level 3)
            analyze_tempo: Flag untuk analisis tempo
            analyze_articulation: Flag untuk analisis artikulasi
            analyze_structure: Flag untuk analisis struktur
            analyze_keywords: Flag untuk analisis kata kunci
            analyze_profanity: Flag untuk deteksi kata tidak senonoh
            
        Returns:
            Dict berisi semua hasil analisis
        """
        start_time = time.time()
        
        print("="*70)
        print("🎯 STARTING AUDIO ANALYSIS")
        print("="*70)
        print(f"πŸ“ Audio file: {audio_path}")
        print(f"βš™οΈ  Tempo: {analyze_tempo}")
        print(f"βš™οΈ  Articulation: {analyze_articulation}")
        print(f"βš™οΈ  Structure: {analyze_structure}")
        print(f"βš™οΈ  Keywords: {analyze_keywords}")
        print(f"βš™οΈ  Profanity: {analyze_profanity}")
        print("="*70 + "\n")
        
        results = {}
        
        # 1. Speech to Text (always required)
        print("πŸ“ Step 1/6: Transcribing audio...")
        transcript_result = self.stt_service.transcribe(audio_path)
        transcript = transcript_result['text']
        results['transcript'] = transcript
        print(f"βœ… Transcript: {transcript[:100]}...\n")
        
        # 2. Tempo Analysis
        if analyze_tempo:
            print("🎡 Step 2/6: Analyzing tempo...")
            results['tempo'] = self.tempo_service.analyze(audio_path, transcript)
            print(f"βœ… Tempo score: {results['tempo']['score']}/5\n")
        
        # 3. Articulation Analysis
        if analyze_articulation and reference_text:
            print("πŸ—£οΈ  Step 3/6: Analyzing articulation...")
            results['articulation'] = self.articulation_service.analyze(
                transcribed_text=transcript,
                reference_text=reference_text
            )
            print(f"βœ… Articulation score: {results['articulation']['score']}/5\n")
        elif analyze_articulation:
            print("⚠️  Step 3/6: Skipping articulation (no reference text)\n")
        
        # 4. Structure Analysis
        if analyze_structure:
            print("πŸ“Š Step 4/6: Analyzing structure...")
            results['structure'] = self.structure_service.analyze(transcript)
            print(f"βœ… Structure score: {results['structure']['score']}/5\n")
        
        # 5. Keyword Analysis
        if analyze_keywords:
            print("πŸ” Step 5/6: Analyzing keywords...")
            
            # Custom keywords (Level 3 - dari GPT)
            if custom_topic and custom_keywords:
                results['keywords'] = self.keyword_service.analyze(
                    speech_text=transcript,
                    custom_topic=custom_topic,
                    custom_keywords=custom_keywords
                )
            # Predefined topic (Level 1-2 - dari database)
            elif topic_id:
                results['keywords'] = self.keyword_service.analyze(
                    speech_text=transcript,
                    topic_id=topic_id
                )
            else:
                print("⚠️  Step 5/6: Skipping keywords (no topic_id or custom_keywords)\n")
            
            if 'keywords' in results:
                print(f"βœ… Keyword score: {results['keywords']['score']}/5\n")
        elif analyze_keywords:
            print("⚠️  Step 5/6: Keywords analysis disabled\n")
        
        # 6. Profanity Detection
        if analyze_profanity:
            print("🚫 Step 6/6: Detecting profanity...")
            results['profanity'] = ProfanityDetector.detect_profanity(transcript)
            status = "DETECTED" if results['profanity']['has_profanity'] else "CLEAN"
            print(f"βœ… Profanity check: {status} ({results['profanity']['profanity_count']} words)\n")
        
        # Calculate overall score
        scores = []
        if 'tempo' in results:
            scores.append(results['tempo']['score'])
        if 'articulation' in results:
            scores.append(results['articulation']['score'])
        if 'structure' in results:
            scores.append(results['structure']['score'])
        if 'keywords' in results:
            scores.append(results['keywords']['score'])
        
        if scores:
            results['overall_score'] = round(sum(scores) / len(scores), 2)
        else:
            results['overall_score'] = 0
        
        processing_time = time.time() - start_time
        results['processing_time'] = round(processing_time, 2)
        
        print("="*70)
        print(f"βœ… ANALYSIS COMPLETE")
        print(f"⏱️  Processing time: {processing_time:.2f}s")
        print(f"πŸ“Š Overall score: {results['overall_score']}/5")
        print("="*70 + "\n")
        
        return results