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 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
# πŸš€ API & Architecture Documentation

## API Endpoints

### 1. Health Check
```http
GET /health
Content-Type: application/json
```

**Response (200 OK):**
```json
{
  "status": "ok",
  "spacy_model": "en_core_web_sm",
  "whisper_model": "small",
  "whisper_device": "cpu"
}
```

---

### 2. Analyze Text/Audio (JSON Response)
```http
POST /api/analyze
Content-Type: multipart/form-data

Parameters:
  file: File[Optional] - Audio file (.wav, .mp3, .m4a, .flac, .ogg, .aac, .webm)
  text: str[Optional] - Raw text or text file content
  language: str[Optional] - Language code (en, es, fr, de, zh, etc.) Default: "en"

Note: Either 'file' or 'text' must be provided, but not both
```

**Response (200 OK):**
```json
{
  "transcript": "string - normalized input text",
  "normalizedText": "string - same as transcript",
  "products": [
    {
      "name": "camera",
      "sentiment": "positive|neutral|negative",
      "score": 0.87,
      "confidence": 0.82,
      "mentions": 1,
      "context": "The camera quality is absolutely stunning",
      "contexts": ["The camera quality is..."],
      "highlights": [
        {
          "product": "camera",
          "text": "camera",
          "start": 4,
          "end": 10
        }
      ]
    }
  ],
  "highlights": [
    {
      "product": "camera",
      "text": "camera",
      "start": 4,
      "end": 10
    }
  ],
  "summary": {
    "positive": 75,
    "negative": 25,
    "neutral": 0,
    "counts": {
      "positive": 3,
      "negative": 1,
      "neutral": 0
    },
    "dominant": "positive",
    "averageScore": 0.555,
    "totalProducts": 4
  },
  "pipeline": [
    {
      "id": "uploading",
      "title": "Uploading",
      "status": "completed",
      "detail": "Accepted audio input from file.wav."
    },
    {
      "id": "speech_to_text",
      "title": "Speech-to-text",
      "status": "completed",
      "detail": "Converted audio to text with Whisper."
    },
    {
      "id": "nlp_extraction",
      "title": "NLP extraction",
      "status": "completed",
      "detail": "Extracted 4 aspect mentions with spaCy."
    },
    {
      "id": "sentiment_analysis",
      "title": "Sentiment analysis",
      "status": "completed",
      "detail": "Scored each aspect context with VADER."
    }
  ],
  "metadata": {
    "sourceType": "audio|text",
    "sourceName": "filename or typed-text",
    "language": "en",
    "processingMs": 245,
    "transcriptionConfidence": 0.95,
    "whisperModel": "small",
    "wordCount": 58,
    "sentenceCount": 6,
    "createdAt": "2026-04-13T10:30:45.123Z"
  }
}
```

**Error Responses:**

```json
400 Bad Request - Missing both text and file
{
  "detail": "Provide either text input or a file upload."
}
```

```json
400 Bad Request - Invalid file type
{
  "detail": "Unsupported file type '.xyz'. Upload audio or a text file."
}
```

```json
422 Unprocessable Entity - Empty transcription
{
  "detail": "Whisper returned an empty transcript. Try a clearer or longer audio sample."
}
```

```json
500 Internal Server Error
{
  "detail": "Aspect sentiment analysis failed: [error details]"
}
```

---

### 3. Analyze with Streaming (Server-Sent Events)
```http
POST /api/analyze-stream
Content-Type: multipart/form-data

Parameters: (same as /api/analyze)
```

**Response (200 OK with text/event-stream):**

The server streams JSONL (JSON Lines) events, one per line:

```jsonl
{"type": "step", "step": {"id": "uploading", "title": "Uploading", "status": "completed", "detail": "Received input from file.wav."}}
{"type": "step", "step": {"id": "speech_to_text", "title": "Speech-to-text", "status": "active", "detail": "Transcribing audio with Whisper."}}
{"type": "step", "step": {"id": "speech_to_text", "title": "Speech-to-text", "status": "completed", "detail": "Audio successfully converted to text."}}
{"type": "step", "step": {"id": "nlp_extraction", "title": "NLP extraction", "status": "active", "detail": "Extracting noun phrases and feature mentions with spaCy."}}
{"type": "step", "step": {"id": "nlp_extraction", "title": "NLP extraction", "status": "completed", "detail": "Extracted 4 aspect mentions."}}
{"type": "step", "step": {"id": "sentiment_analysis", "title": "Sentiment analysis", "status": "active", "detail": "Scoring aspect-specific context windows with VADER."}}
{"type": "step", "step": {"id": "sentiment_analysis", "title": "Sentiment analysis", "status": "completed", "detail": "Calculated sentiment for 4 products/features."}}
{"type": "result", "data": {...full analysis response...}}
```

**Step Status Values:**
- `pending` - Not yet started
- `active` - Currently processing
- `completed` - Successfully finished
- `skipped` - Skipped (e.g., no audio input)
- `error` - Failed

---

## Architecture Overview

### System Components

```
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚   Frontend (React + TypeScript)     β”‚
β”‚                                     β”‚
β”‚  Components:                        β”‚
β”‚  - UploadSection                    β”‚
β”‚  - HeroSection                      β”‚
β”‚  - PipelineSection                  β”‚
β”‚  - SentimentSection                 β”‚
β”‚  - EntitySection                    β”‚
β”‚  - SummarySection                   β”‚
β”‚  - TranscriptSection                β”‚
β”‚                                     β”‚
β”‚  Libraries:                         β”‚
β”‚  - React 18                         β”‚
β”‚  - Framer Motion (animations)       β”‚
β”‚  - Chart.js (visualizations)        β”‚
β”‚  - Tailwind CSS (styling)           β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
              ↑↓ HTTP/SSE
         Port 8000 ↔ Port 5173
              ↓↑
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚   Backend (FastAPI + Python)        β”‚
β”‚                                     β”‚
β”‚  Endpoints:                         β”‚
β”‚  - GET /health                      β”‚
β”‚  - POST /api/analyze                β”‚
β”‚  - POST /api/analyze-stream         β”‚
β”‚                                     β”‚
β”‚  Core Modules:                      β”‚
β”‚  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”   β”‚
β”‚  β”‚ AspectSentimentEngine       β”‚   β”‚
β”‚  β”‚ - Text normalization        β”‚   β”‚
β”‚  β”‚ - spaCy parsing             β”‚   β”‚
β”‚  β”‚ - Noun extraction           β”‚   β”‚
β”‚  β”‚ - Context windowing         β”‚   β”‚
β”‚  β”‚ - VADER sentiment scoring   β”‚   β”‚
β”‚  β”‚ - Results aggregation       β”‚   β”‚
β”‚  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜   β”‚
β”‚                                     β”‚
β”‚  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”   β”‚
β”‚  β”‚ WhisperTranscriber          β”‚   β”‚
β”‚  β”‚ - Audio file handling       β”‚   β”‚
β”‚  β”‚ - Format detection          β”‚   β”‚
β”‚  β”‚ - Whisper integration       β”‚   β”‚
β”‚  β”‚ - Confidence estimation     β”‚   β”‚
β”‚  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜   β”‚
β”‚                                     β”‚
β”‚  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”   β”‚
β”‚  β”‚ Data Models (Pydantic)      β”‚   β”‚
β”‚  β”‚ - AnalysisResponse          β”‚   β”‚
β”‚  β”‚ - ProductSentiment          β”‚   β”‚
β”‚  β”‚ - SentimentSummary          β”‚   β”‚
β”‚  β”‚ - PipelineStage             β”‚   β”‚
β”‚  β”‚ - AnalysisMetadata          β”‚   β”‚
β”‚  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜   β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
              ↓↑
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚   NLP Processing Pipeline           β”‚
β”‚                                     β”‚
β”‚  1. Text Normalization              β”‚
β”‚     Input: "  Hello   WORLD  "      β”‚
β”‚     Output: "Hello WORLD"           β”‚
β”‚                                     β”‚
β”‚  2. Tokenization & POS Tagging      β”‚
β”‚     spaCy NLP pipeline              β”‚
β”‚     - Segmentation                  β”‚
β”‚     - Part-of-speech tagging        β”‚
β”‚     - Dependency parsing            β”‚
β”‚                                     β”‚
β”‚  3. Noun Extraction                 β”‚
β”‚     Filter: pos_ in ["NOUN","PROPN"]β”‚
β”‚     Results: [camera, battery, ...]β”‚
β”‚                                     β”‚
β”‚  4. Aspect Mention Detection        β”‚
β”‚     - Span extraction               β”‚
β”‚     - Name normalization            β”‚
β”‚     - Duplicate filtering           β”‚
β”‚     - Generic term removal          β”‚
β”‚                                     β”‚
β”‚  5. Context Window Selection        β”‚
β”‚     - Sentence isolation            β”‚
β”‚     - Clause boundary detection     β”‚
β”‚     - Negation handling             β”‚
β”‚                                     β”‚
β”‚  6. Sentiment Scoring (VADER)       β”‚
β”‚     For each context window:        β”‚
β”‚     - Tokenization                  β”‚
β”‚     - Lexicon lookup                β”‚
β”‚     - Valence computation           β”‚
β”‚     - Score normalization           β”‚
β”‚                                     β”‚
β”‚  7. Results Aggregation             β”‚
β”‚     - Unique products               β”‚
β”‚     - Score averaging               β”‚
β”‚     - Confidence calculation        β”‚
β”‚     - Summary statistics            β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
```

---

## Data Flow

### Text Input Flow
```
User Input
   ↓
Frontend: Form submission
   ↓
HTTP POST /api/analyze-stream
   ↓
Backend: Parse FormData
   ↓
AspectSentimentEngine.analyze_text()
   β”œβ”€ normalize_text()
   β”œβ”€ parse() β†’ spaCy Doc
   β”œβ”€ extract_mentions() β†’ [AspectMention]
   β”œβ”€ score_products() β†’ [ProductSentiment]
   β”œβ”€ summarize() β†’ SentimentSummary
   └─ Return AnalysisResponse
   ↓
Stream Events (SSE)
   β”œβ”€ uploading: completed
   β”œβ”€ speech_to_text: skipped
   β”œβ”€ nlp_extraction: completed
   β”œβ”€ sentiment_analysis: completed
   └─ result: {...}
   ↓
Frontend: Display Results Dashboard
```

### Audio Input Flow
```
User Uploads Audio
   ↓
Frontend: Read File
   ↓
HTTP POST /api/analyze-stream (multipart/form-data)
   β”œβ”€ file: [audio_data]
   └─ language: "en"
   ↓
Backend: Receive Upload
   β”œβ”€ Save to temp location
   └─ Stream: uploading: completed
   ↓
WhisperTranscriber.transcribe()
   β”œβ”€ Ensure ffmpeg on PATH
   β”œβ”€ Load model (if needed)
   β”œβ”€ Transcribe audio
   β”œβ”€ Extract language
   β”œβ”€ Estimate confidence
   └─ Clean up temp file
   ↓
Stream Events:
   └─ speech_to_text: completed β†’ transcript
   ↓
AspectSentimentEngine.analyze_text()
   (same as text flow)
   ↓
Frontend: Display Results
```

---

## Configuration

### Environment Variables

```bash
# .env file or system environment variables

# Whisper Settings
WHISPER_MODEL_SIZE=small         # small, base, medium, large
WHISPER_DEVICE=cpu               # cpu, cuda

# API Settings
LOG_LEVEL=INFO                   # DEBUG, INFO, WARNING, ERROR
PORT=8000                        # API port

# Frontend
VITE_API_BASE_URL=http://localhost:8000
```

### Whisper Model Sizes

| Size | VRAM | Accuracy | Speed | Use Case |
|------|------|----------|-------|----------|
| tiny | 1GB | ~60% | Very Fast | Demo/Testing |
| small | 2GB | ~75% | Fast | Development |
| base | 2GB | ~80% | Moderate | Recommended |
| medium | 5GB | ~88% | Slow | High Quality |
| large | 10GB | ~95% | Very Slow | Maximum Accuracy |

---

## Performance Metrics

### Response Times (measured on test system)
- Text analysis (50 words): ~100ms
- Text analysis (500 words): ~200ms
- Audio transcription (1 min): ~2-5s
- Total end-to-end (audio): ~3-7s

### Resource Usage
- Memory: ~2-3GB (with models loaded)
- CPU: ~30-50% during processing
- GPU: Optional (significant speedup if available)

---

## Error Handling

### Common Error Scenarios

**1. Missing spaCy Model**
```
Error: OSError: [E050] Can't find model 'en_core_web_sm'
Solution: python -m spacy download en_core_web_sm
```

**2. ffmpeg Not Found**
```
Error: FileNotFoundError: ffmpeg not found
Solution: Already bundled, check PATH or install ffmpeg
```

**3. Invalid Audio File**
```
Error: [...] no matching input format found
Solution: Convert to .wav or .mp3 format
```

**4. Out of Memory**
```
Error: RuntimeError: CUDA out of memory
Solution: Use smaller whisper model or CPU device
```

**5. Empty Transcription**
```
Error: "Whisper returned an empty transcript"
Solution: Try clearer audio or longer duration
```

---

## Deployment

### Production Considerations

1. **Use Production ASGI Server**
```bash
# Instead of: uvicorn src.api.server:app --reload
gunicorn src.api.server:app -w 4 -b 0.0.0.0:8000 -k uvicorn.workers.UvicornWorker
```

2. **Enable HTTPS**
```python
# Use nginx reverse proxy or certbot for SSL
```

3. **Rate Limiting**
```python
# Add rate limiting middleware to prevent abuse
from slowapi import Limiter
```

4. **Caching**
```python
# Cache common requests using Redis
```

5. **Monitoring**
```python
# Add Prometheus metrics for monitoring
```

### Docker Deployment

```dockerfile
FROM python:3.11-slim

WORKDIR /app
COPY requirements.txt .
RUN pip install -r requirements.txt && \
    python -m spacy download en_core_web_sm

COPY . .

CMD ["uvicorn", "src.api.server:app", "--host", "0.0.0.0", "--port", "8000"]
```

---

## Testing

### API Testing

```bash
# Health check
curl http://localhost:8000/health

# Text analysis
curl -X POST "http://localhost:8000/api/analyze" \
  -F "text=The camera is amazing but battery drains fast"

# Audio analysis
curl -X POST "http://localhost:8000/api/analyze" \
  -F "file=@audio.wav" \
  -F "language=en"

# Streaming analysis
curl -X POST "http://localhost:8000/api/analyze-stream" \
  -F "text=Test text" \
  -N  # No buffering to see streaming events
```

### Frontend Testing

```bash
# Unit tests (if available)
npm test

# E2E tests
npm run test:e2e

# Build and preview
npm run build
npm run preview
```

---

## API Documentation UIs

When backend is running:
- **Swagger UI**: http://localhost:8000/docs
- **ReDoc**: http://localhost:8000/redoc

---

## Support & Troubleshooting

1. **Check API Status**
   ```bash
   curl http://localhost:8000/health
   ```

2. **Review Test Results**
   ```bash
   python test_system.py
   ```

3. **Check Logs**
   - Backend: Terminal output with `--reload` flag
   - Frontend: Browser console (F12)

4. **Verify Dependencies**
   ```bash
   .venv\Scripts\pip.exe list
   ```

---

**Last Updated:** April 2026
**Status:** Production Ready