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0a65
 
7d5083d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
Pydantic models for API response structures.

This module defines the output models for the topic segmentation API,
including topic responses, segmentation results, and metadata structures.
"""

from typing import List, Optional, Dict, Any, Union
from datetime import datetime
from enum import Enum

from pydantic import BaseModel, Field, ConfigDict, computed_field
from pydantic.types import PositiveInt, NonNegativeFloat

from models.input import SpeakerRole, LanguageCode


class TopicCategory(str, Enum):
    """Business categories for extracted topics."""
    CLIENT_NEEDS_B2B = "client_needs_b2b"
    CLIENT_NEEDS_B2C = "client_needs_b2c"
    CUSTOMER_FEEDBACK = "customer_feedback"
    EMPLOYEE_FEEDBACK = "employee_feedback"
    SOLUTION_BARRIERS = "solution_barriers"
    SOLUTION_BENEFITS = "solution_benefits"
    AHA_MOMENTS = "aha_moments"
    COMPANY_INFO = "company_info"
    TECHNICAL_REQUIREMENTS = "technical_requirements"
    ADDITIONAL_COMMENTS = "additional_comments"
    GENERAL = "general"


class ConfidenceLevel(str, Enum):
    """Confidence levels for topic extraction."""
    VERY_HIGH = "very_high"  # 0.9-1.0
    HIGH = "high"           # 0.7-0.89
    MEDIUM = "medium"       # 0.5-0.69
    LOW = "low"            # 0.3-0.49
    VERY_LOW = "very_low"  # 0.0-0.29


class ProcessingStatus(str, Enum):
    """Status of the processing request."""
    SUCCESS = "success"
    PARTIAL_SUCCESS = "partial_success"
    FAILED = "failed"
    TIMEOUT = "timeout"
    RATE_LIMITED = "rate_limited"


class SpeakerInsight(BaseModel):
    """
    Insights about a specific speaker in the transcript.
    """
    model_config = ConfigDict(
        validate_assignment=True,
        extra="forbid"
    )
    
    speaker: str = Field(
        ...,
        description="Speaker identifier"
    )
    
    speaker_role: Optional[SpeakerRole] = Field(
        default=None,
        description="Role of the speaker"
    )
    
    total_sentences: PositiveInt = Field(
        ...,
        description="Total number of sentences by this speaker"
    )
    
    total_duration: NonNegativeFloat = Field(
        ...,
        description="Total speaking time in seconds"
    )
    
    topics_mentioned: List[str] = Field(
        default_factory=list,
        description="List of topic names this speaker contributed to"
    )
    
    key_insights: List[str] = Field(
        default_factory=list,
        description="Key insights or quotes from this speaker"
    )
    
    sentiment_analysis: Optional[Dict[str, Any]] = Field(
        default=None,
        description="Optional sentiment analysis for this speaker"
    )


class TopicDetail(BaseModel):
    """
    Detailed information about an extracted topic.
    
    Contains the core topic information, timing, speakers,
    and business categorization.
    """
    model_config = ConfigDict(
        validate_assignment=True,
        extra="forbid"
    )
    
    # Core topic information
    topic_name: str = Field(
        ...,
        min_length=1,
        max_length=200,
        description="Descriptive name of the topic"
    )
    
    topic_type: TopicCategory = Field(
        ...,
        description="Business category of the topic"
    )
    
    topic_detail: str = Field(
        ...,
        min_length=1,
        max_length=1000,
        description="Detailed description or summary of the topic"
    )
    
    # Timing information
    start_time: NonNegativeFloat = Field(
        ...,
        description="Start time of the topic in seconds"
    )
    
    end_time: NonNegativeFloat = Field(
        ...,
        description="End time of the topic in seconds"
    )
    
    # Sentence range
    start_sentence_index: PositiveInt = Field(
        ...,
        description="Index of the first sentence in this topic"
    )
    
    end_sentence_index: PositiveInt = Field(
        ...,
        description="Index of the last sentence in this topic"
    )
    
    # Speaker information
    primary_speaker: str = Field(
        ...,
        description="Primary speaker for this topic"
    )
    
    all_speakers: List[str] = Field(
        ...,
        min_length=1,
        description="All speakers who contributed to this topic"
    )
    
    # Confidence and quality metrics
    confidence_score: float = Field(
        ...,
        ge=0.0,
        le=1.0,
        description="Confidence score for topic extraction (0.0 to 1.0)"
    )
    
    relevance_score: Optional[float] = Field(
        default=None,
        ge=0.0,
        le=1.0,
        description="Business relevance score (0.0 to 1.0)"
    )
    
    # Content analysis
    key_phrases: List[str] = Field(
        default_factory=list,
        description="Key phrases or keywords for this topic"
    )
    
    sentiment: Optional[str] = Field(
        default=None,
        description="Overall sentiment of the topic (positive/negative/neutral)"
    )
    
    # Business insights
    actionable_insights: List[str] = Field(
        default_factory=list,
        description="Actionable business insights from this topic"
    )
    
    related_topics: List[str] = Field(
        default_factory=list,
        description="Names of related topics in the transcript"
    )
    
    # Additional metadata
    metadata: Optional[Dict[str, Any]] = Field(
        default=None,
        description="Additional metadata for the topic"
    )
    
    @computed_field
    @property
    def duration(self) -> float:
        """Calculate topic duration in seconds."""
        return self.end_time - self.start_time
    
    @computed_field
    @property
    def sentence_count(self) -> int:
        """Calculate number of sentences in this topic."""
        return self.end_sentence_index - self.start_sentence_index + 1
    
    @computed_field
    @property
    def confidence_level(self) -> ConfidenceLevel:
        """Get confidence level based on confidence score."""
        if self.confidence_score >= 0.9:
            return ConfidenceLevel.VERY_HIGH
        elif self.confidence_score >= 0.7:
            return ConfidenceLevel.HIGH
        elif self.confidence_score >= 0.5:
            return ConfidenceLevel.MEDIUM
        elif self.confidence_score >= 0.3:
            return ConfidenceLevel.LOW
        else:
            return ConfidenceLevel.VERY_LOW


class ProcessingMetadata(BaseModel):
    """
    Metadata about the processing request and results.
    """
    model_config = ConfigDict(
        validate_assignment=True,
        extra="forbid",
        protected_namespaces=()
    )
    
    # Request information
    request_id: str = Field(
        ...,
        description="Unique identifier for this request"
    )
    
    timestamp: datetime = Field(
        ...,
        description="Timestamp when processing started"
    )
    
    # Processing details
    model_used: str = Field(
        ...,
        description="Anthropic model used for processing"
    )
    
    processing_time: NonNegativeFloat = Field(
        ...,
        description="Total processing time in seconds"
    )
    
    # Input statistics
    total_sentences: PositiveInt = Field(
        ...,
        description="Total number of sentences processed"
    )
    
    total_duration: NonNegativeFloat = Field(
        ...,
        description="Total duration of the transcript in seconds"
    )
    
    unique_speakers: PositiveInt = Field(
        ...,
        description="Number of unique speakers in the transcript"
    )
    
    # Output statistics
    topics_extracted: int = Field(
        ...,
        ge=0,
        description="Number of topics extracted"
    )
    
    topics_merged: int = Field(
        default=0,
        ge=0,
        description="Number of topics that were merged due to similarity"
    )
    
    # Quality metrics
    average_confidence: float = Field(
        ...,
        ge=0.0,
        le=1.0,
        description="Average confidence score across all topics"
    )
    
    coverage_percentage: float = Field(
        ...,
        ge=0.0,
        le=100.0,
        description="Percentage of transcript covered by extracted topics"
    )
    
    # Token usage
    tokens_used: Optional[Dict[str, int]] = Field(
        default=None,
        description="Token usage statistics from Anthropic API"
    )
    
    # Language information
    detected_language: Optional[LanguageCode] = Field(
        default=None,
        description="Detected primary language of the transcript"
    )
    
    # Warnings and notes
    warnings: List[str] = Field(
        default_factory=list,
        description="Any warnings or issues during processing"
    )
    
    processing_notes: List[str] = Field(
        default_factory=list,
        description="Additional notes about the processing"
    )


class SegmentationResult(BaseModel):
    """
    Complete result of topic segmentation analysis.
    
    Contains all extracted topics, speaker insights, and processing metadata.
    """
    model_config = ConfigDict(
        validate_assignment=True,
        extra="forbid"
    )
    
    # Processing status
    status: ProcessingStatus = Field(
        ...,
        description="Overall status of the processing"
    )
    
    # Core results
    topics: List[TopicDetail] = Field(
        ...,
        description="List of extracted topics with details"
    )
    
    # Speaker analysis
    speaker_insights: List[SpeakerInsight] = Field(
        default_factory=list,
        description="Insights about each speaker in the transcript"
    )
    
    # Processing information
    metadata: ProcessingMetadata = Field(
        ...,
        description="Metadata about the processing request and results"
    )
    
    # Summary information
    executive_summary: Optional[str] = Field(
        default=None,
        max_length=2000,
        description="Executive summary of the key findings"
    )
    
    key_takeaways: List[str] = Field(
        default_factory=list,
        description="Key takeaways and actionable insights"
    )
    
    # Business categorization summary
    category_summary: Dict[TopicCategory, int] = Field(
        default_factory=dict,
        description="Count of topics by business category"
    )
    
    @computed_field
    @property
    def total_topics(self) -> int:
        """Get total number of topics extracted."""
        return len(self.topics)
    
    @computed_field
    @property
    def high_confidence_topics(self) -> int:
        """Get number of high confidence topics (>= 0.7)."""
        return len([t for t in self.topics if t.confidence_score >= 0.7])
    
    @computed_field
    @property
    def success_rate(self) -> float:
        """Calculate success rate based on confidence scores."""
        if not self.topics:
            return 0.0
        return sum(t.confidence_score for t in self.topics) / len(self.topics)


class ErrorDetail(BaseModel):
    """
    Detailed error information for failed requests.
    """
    model_config = ConfigDict(
        validate_assignment=True,
        extra="forbid"
    )
    
    error_code: str = Field(
        ...,
        description="Specific error code"
    )
    
    error_message: str = Field(
        ...,
        description="Human-readable error message"
    )
    
    error_type: str = Field(
        ...,
        description="Type of error (validation, processing, api, etc.)"
    )
    
    field_errors: Optional[Dict[str, List[str]]] = Field(
        default=None,
        description="Field-specific validation errors"
    )
    
    suggestions: List[str] = Field(
        default_factory=list,
        description="Suggestions for fixing the error"
    )
    
    timestamp: datetime = Field(
        default_factory=datetime.now,
        description="When the error occurred"
    )


class HealthCheckResponse(BaseModel):
    """
    Response model for health check endpoint.
    """
    model_config = ConfigDict(
        validate_assignment=True,
        extra="forbid",
        protected_namespaces=()
    )
    
    status: str = Field(
        ...,
        description="Overall health status"
    )
    
    timestamp: datetime = Field(
        ...,
        description="Timestamp of the health check"
    )
    
    uptime_seconds: float = Field(
        ...,
        description="Service uptime in seconds"
    )
    
    anthropic_status: Dict[str, Any] = Field(
        ...,
        description="Anthropic integration status"
    )
    
    model_health: Optional[Dict[str, Any]] = Field(
        default=None,
        description="Detailed model health information"
    )
    
    performance_stats: Optional[Dict[str, Any]] = Field(
        default=None,
        description="Performance statistics"
    )


class ModelStatusResponse(BaseModel):
    """
    Response model for model status endpoint.
    """
    model_config = ConfigDict(
        validate_assignment=True,
        extra="forbid",
        protected_namespaces=()
    )
    
    current_model: str = Field(
        ...,
        description="Currently active model"
    )
    
    available_models: List[str] = Field(
        ...,
        description="List of available models"
    )
    
    model_health: Dict[str, Dict[str, Any]] = Field(
        ...,
        description="Health status for each model"
    )
    
    performance_stats: Dict[str, Dict[str, Any]] = Field(
        ...,
        description="Performance statistics for each model"
    )
    
    best_performing_model: str = Field(
        ...,
        description="Currently best performing model"
    )
    
    last_updated: datetime = Field(
        ...,
        description="When the status was last updated"
    )


# Type aliases for convenience
TopicList = List[TopicDetail]
SpeakerInsightList = List[SpeakerInsight]
ErrorResponse = ErrorDetail