forked from attevon-llc/OpenTranscribe
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmedia.py
More file actions
587 lines (427 loc) · 17.7 KB
/
Copy pathmedia.py
File metadata and controls
587 lines (427 loc) · 17.7 KB
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
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
from datetime import datetime
from enum import Enum
from typing import Any
from typing import Optional
from uuid import UUID
from pydantic import BaseModel
from pydantic import ConfigDict
from pydantic import Field
from pydantic import field_validator
from pydantic import model_validator
from app.schemas.base import UUIDBaseSchema
class FileStatus(str, Enum):
PENDING = "pending"
PROCESSING = "processing"
COMPLETED = "completed"
ERROR = "error"
CANCELLING = "cancelling"
CANCELLED = "cancelled"
ORPHANED = "orphaned"
class TaskStatus(str, Enum):
PENDING = "pending"
IN_PROGRESS = "in_progress"
COMPLETED = "completed"
FAILED = "failed"
class ReprocessRequest(BaseModel):
"""Request schema for reprocessing a file with optional speaker diarization settings.
Attributes:
min_speakers: Optional minimum number of speakers for diarization
max_speakers: Optional maximum number of speakers for diarization
num_speakers: Optional fixed number of speakers for diarization (overrides min/max)
"""
min_speakers: Optional[int] = Field(
None, description="Minimum number of speakers for diarization (positive integer)"
)
max_speakers: Optional[int] = Field(
None, description="Maximum number of speakers for diarization (positive integer)"
)
num_speakers: Optional[int] = Field(
None, description="Fixed number of speakers for diarization (overrides min/max when set)"
)
@field_validator("min_speakers", "max_speakers", "num_speakers")
@classmethod
def validate_speaker_count_positive(cls, v: Optional[int]) -> Optional[int]:
"""Validate that speaker counts are positive integers (>= 1) if provided."""
if v is not None and v < 1:
raise ValueError("Speaker count must be at least 1")
return v
@model_validator(mode="after")
def validate_min_max_speakers(self) -> "ReprocessRequest":
"""Validate that min_speakers <= max_speakers if both are provided."""
if (
self.min_speakers is not None
and self.max_speakers is not None
and self.min_speakers > self.max_speakers
):
raise ValueError(
f"min_speakers ({self.min_speakers}) must be less than or equal to "
f"max_speakers ({self.max_speakers})"
)
return self
class PrepareUploadRequest(BaseModel):
"""Request schema for preparing a file upload.
This schema is used to create a file record before the actual upload starts.
Attributes:
filename: Name of the file to be uploaded
file_size: Size of the file in bytes
content_type: MIME type of the file
file_hash: SHA-256 hash of the file for duplicate detection
extracted_from_video: Optional metadata from original video file (if audio was extracted client-side)
min_speakers: Optional minimum number of speakers for diarization
max_speakers: Optional maximum number of speakers for diarization
num_speakers: Optional fixed number of speakers for diarization (overrides min/max)
"""
filename: str = Field(..., description="Name of the file to be uploaded")
file_size: int = Field(..., description="Size of the file in bytes")
content_type: str = Field(..., description="MIME type of the file")
file_hash: Optional[str] = Field(
None, description="SHA-256 hash of the file for duplicate detection"
)
extracted_from_video: Optional[dict[str, Any]] = Field(
None, description="Metadata from original video file if audio was extracted client-side"
)
min_speakers: Optional[int] = Field(
None, description="Minimum number of speakers for diarization (positive integer)"
)
max_speakers: Optional[int] = Field(
None, description="Maximum number of speakers for diarization (positive integer)"
)
num_speakers: Optional[int] = Field(
None, description="Fixed number of speakers for diarization (overrides min/max when set)"
)
@field_validator("min_speakers", "max_speakers", "num_speakers")
@classmethod
def validate_speaker_count_positive(cls, v: Optional[int]) -> Optional[int]:
"""Validate that speaker counts are positive integers (>= 1) if provided."""
if v is not None and v < 1:
raise ValueError("Speaker count must be at least 1")
return v
@model_validator(mode="after")
def validate_min_max_speakers(self) -> "PrepareUploadRequest":
"""Validate that min_speakers <= max_speakers if both are provided."""
if (
self.min_speakers is not None
and self.max_speakers is not None
and self.min_speakers > self.max_speakers
):
raise ValueError(
f"min_speakers ({self.min_speakers}) must be less than or equal to "
f"max_speakers ({self.max_speakers})"
)
return self
class SpeakerBase(BaseModel):
name: str
display_name: Optional[str] = None
suggested_name: Optional[str] = None
verified: bool = False
class SpeakerCreate(SpeakerBase):
embedding_vector: Optional[list[float]] = None
class SpeakerUpdate(BaseModel):
name: Optional[str] = None
display_name: Optional[str] = None
suggested_name: Optional[str] = None
verified: Optional[bool] = None
embedding_vector: Optional[list[float]] = None
profile_action: Optional[str] = None # 'update_profile' or 'create_new_profile'
class Speaker(SpeakerBase, UUIDBaseSchema):
"""Speaker with UUID as public identifier"""
user_id: UUID
media_file_id: UUID
profile_id: Optional[UUID] = None
confidence: Optional[float] = None
created_at: datetime
# Computed status fields from SpeakerStatusService
computed_status: Optional[str] = None # "verified", "suggested", "unverified"
status_text: Optional[str] = None # Human-readable status text
status_color: Optional[str] = None # CSS color for status display
resolved_display_name: Optional[str] = None # Best available display name
# Speaker Profile schemas
class SpeakerProfileBase(BaseModel):
name: str
description: Optional[str] = None
class SpeakerProfileCreate(SpeakerProfileBase):
pass
class SpeakerProfileUpdate(BaseModel):
name: Optional[str] = None
description: Optional[str] = None
class SpeakerProfile(SpeakerProfileBase, UUIDBaseSchema):
"""Speaker profile with UUID as public identifier"""
user_id: UUID
created_at: datetime
updated_at: datetime
# Speaker Collection schemas
class SpeakerCollectionBase(BaseModel):
name: str
description: Optional[str] = None
is_public: bool = False
class SpeakerCollectionCreate(SpeakerCollectionBase):
pass
class SpeakerCollectionUpdate(BaseModel):
name: Optional[str] = None
description: Optional[str] = None
is_public: Optional[bool] = None
class SpeakerCollection(SpeakerCollectionBase, UUIDBaseSchema):
"""Speaker collection with UUID as public identifier"""
user_id: UUID
created_at: datetime
updated_at: datetime
class TranscriptSegmentBase(BaseModel):
start_time: float
end_time: float
text: str
speaker_id: Optional[UUID] = None
class TranscriptSegmentCreate(TranscriptSegmentBase):
pass # media_file_id will be from URL path
class TranscriptSegmentUpdate(BaseModel):
id: Optional[int] = None # Optional since segment is identified by UUID in URL
start_time: Optional[float] = None
end_time: Optional[float] = None
text: Optional[str] = None
speaker_id: Optional[UUID] = None
class TranscriptSegment(TranscriptSegmentBase, UUIDBaseSchema):
"""Transcript segment with UUID as public identifier"""
media_file_id: UUID
speaker: Optional[Speaker] = None
# Formatted fields for frontend display
formatted_timestamp: Optional[str] = None # e.g., "0:45.2"
display_timestamp: Optional[str] = None # e.g., "0:45.2" for transcript UI
speaker_label: Optional[
str
] = None # ALWAYS original speaker ID (e.g., "SPEAKER_01") for color consistency
resolved_speaker_name: Optional[str] = None # Display name (user label or original ID)
class MediaFileBase(BaseModel):
filename: str
class MediaFileCreate(MediaFileBase):
storage_path: str
duration: Optional[float] = None
language: Optional[str] = None
file_hash: Optional[str] = None
thumbnail_path: Optional[str] = None
class MediaFileUpdate(BaseModel):
filename: Optional[str] = None
title: Optional[str] = None
status: Optional[FileStatus] = None
summary_data: Optional[dict[str, Any]] = None
translated_text: Optional[str] = None
duration: Optional[float] = None
language: Optional[str] = None
file_hash: Optional[str] = None
thumbnail_path: Optional[str] = None
class MediaFile(MediaFileBase, UUIDBaseSchema):
"""Media file with UUID as public identifier"""
user_id: UUID
storage_path: str
upload_time: datetime
file_size: Optional[int] = None
content_type: Optional[str] = None
duration: Optional[float] = None
language: Optional[str] = None
status: FileStatus
summary_data: Optional[dict[str, Any]] = None
translated_text: Optional[str] = None
download_url: Optional[str] = None
preview_url: Optional[str] = None
file_hash: Optional[str] = None
thumbnail_path: Optional[str] = None
thumbnail_url: Optional[str] = None
# Technical metadata
media_format: Optional[str] = None
codec: Optional[str] = None
resolution_width: Optional[int] = None
resolution_height: Optional[int] = None
frame_rate: Optional[float] = None
frame_count: Optional[int] = None
aspect_ratio: Optional[str] = None
# Audio specs
audio_channels: Optional[int] = None
audio_sample_rate: Optional[int] = None
audio_bit_depth: Optional[int] = None
# Creation and device information
creation_date: Optional[datetime] = None
last_modified_date: Optional[datetime] = None
device_make: Optional[str] = None
device_model: Optional[str] = None
# Content information
title: Optional[str] = None
author: Optional[str] = None
description: Optional[str] = None
source_url: Optional[str] = None
# Formatted fields for frontend display
formatted_duration: Optional[str] = None # e.g., "5:23"
formatted_upload_date: Optional[str] = None # e.g., "Oct 15, 2024"
formatted_file_age: Optional[str] = None # e.g., "2 hours ago"
formatted_file_size: Optional[str] = None # e.g., "2.5 MB"
display_status: Optional[str] = None # User-friendly status text
status_badge_class: Optional[str] = None # CSS class for status styling
# Error handling fields
error_category: Optional[str] = None # Error category for user-friendly handling
error_suggestions: Optional[list[str]] = None # User-friendly error suggestions
is_retryable: Optional[bool] = None # Whether the error is retryable
class MediaFileDetail(MediaFile):
transcript_segments: list[TranscriptSegment] = []
tags: list[str] = []
collections: list["Collection"] = []
analytics: Optional["Analytics"] = None
speakers: list[Speaker] = []
# Additional formatted fields for detail view
speaker_summary: Optional[dict[str, Any]] = None # Speaker count and primary speakers
# Transcript pagination metadata
total_segments: Optional[int] = None # Total number of transcript segments
segment_limit: Optional[int] = None # Max segments returned (None = all)
segment_offset: Optional[int] = None # Offset for pagination
class TagBase(BaseModel):
name: str
class Tag(TagBase, UUIDBaseSchema):
"""Tag with UUID as public identifier"""
class TagWithCount(Tag):
"""Tag with usage count for filtering UI"""
usage_count: int = 0
class CommentBase(BaseModel):
text: str
timestamp: Optional[float] = None
class CommentCreate(CommentBase):
pass # media_file_id will be from URL path
class CommentUpdate(BaseModel):
text: Optional[str] = None
timestamp: Optional[float] = None
class CommentUser(BaseModel):
"""Nested user info for comments"""
uuid: UUID
email: Optional[str] = None
full_name: Optional[str] = None
model_config = ConfigDict(from_attributes=True)
class Comment(CommentBase, UUIDBaseSchema):
"""Comment with UUID as public identifier"""
media_file_id: UUID
user_id: UUID
user: Optional[CommentUser] = None
created_at: datetime
class MediaFileInfo(BaseModel):
"""Schema for simplified media file information that gets included in tasks"""
uuid: UUID # Public UUID identifier
filename: str
file_size: Optional[int] = None
content_type: Optional[str] = None
duration: Optional[float] = None
language: Optional[str] = None
format: Optional[str] = None
media_format: Optional[str] = None
codec: Optional[str] = None
upload_time: Optional[datetime] = None
class TaskBase(BaseModel):
task_type: str
status: str
media_file_id: Optional[UUID] = None
class TaskCreate(TaskBase):
id: str # Celery task ID (string, not UUID)
user_id: UUID
class TaskUpdate(BaseModel):
status: Optional[str] = None
progress: Optional[float] = None
completed_at: Optional[datetime] = None
error_message: Optional[str] = None
class Task(TaskBase):
"""Task schema - uses Celery task ID (string), not UUID"""
id: str # Celery task ID
user_id: UUID
progress: float
created_at: datetime
updated_at: Optional[datetime] = None
completed_at: Optional[datetime] = None
error_message: Optional[str] = None
media_file: Optional[MediaFileInfo] = None
# Computed fields for frontend display
age_category: Optional[str] = None # "today", "week", "month", "older"
formatted_duration: Optional[str] = None # e.g., "5m", "1h 23m"
status_display: Optional[str] = None # Human-readable status
model_config = {"from_attributes": True}
# Analytics-related schemas
class SpeakerTimeStats(BaseModel):
by_speaker: dict[str, float] = {}
total: float = 0.0
class InterruptionStats(BaseModel):
by_speaker: dict[str, int] = {}
total: int = 0
class TurnTakingStats(BaseModel):
by_speaker: dict[str, int] = {}
total_turns: int = 0
class QuestionStats(BaseModel):
by_speaker: dict[str, int] = {}
total: int = 0
class OverallAnalytics(BaseModel):
word_count: int = 0
duration_seconds: float = 0.0
talk_time: SpeakerTimeStats = SpeakerTimeStats()
interruptions: InterruptionStats = InterruptionStats()
turn_taking: TurnTakingStats = TurnTakingStats()
questions: QuestionStats = QuestionStats()
speaking_pace: Optional[float] = None # words per minute
silence_ratio: Optional[float] = None # ratio of silence
class AnalyticsBase(BaseModel):
overall_analytics: Optional[OverallAnalytics] = None
class AnalyticsCreate(AnalyticsBase):
pass # media_file_id will be from context
class Analytics(AnalyticsBase, UUIDBaseSchema):
"""Analytics with UUID as public identifier"""
media_file_id: UUID
computed_at: Optional[datetime] = None
version: Optional[str] = None
# Collection schemas
class CollectionBase(BaseModel):
name: str
description: Optional[str] = None
is_public: bool = False
class CollectionCreate(CollectionBase):
pass
class CollectionUpdate(BaseModel):
name: Optional[str] = None
description: Optional[str] = None
is_public: Optional[bool] = None
class Collection(CollectionBase, UUIDBaseSchema):
"""Collection with UUID as public identifier"""
user_id: UUID
created_at: datetime
updated_at: datetime
class CollectionWithCount(Collection):
media_count: int = 0
class CollectionResponse(Collection):
media_files: Optional[list[MediaFile]] = []
class CollectionMemberAdd(BaseModel):
media_file_ids: list[UUID] # Changed from int to UUID
class CollectionMemberRemove(BaseModel):
media_file_ids: list[UUID] # Changed from int to UUID
# Subtitle-related schemas
class SubtitleFormat(str, Enum):
SRT = "srt"
WEBVTT = "webvtt"
MOV_TEXT = "mov_text"
class VideoFormat(str, Enum):
MP4 = "mp4"
MKV = "mkv"
WEBM = "webm"
class SubtitleRequest(BaseModel):
"""Request schema for generating subtitles."""
include_speakers: bool = Field(True, description="Include speaker labels in subtitles")
format: SubtitleFormat = Field(SubtitleFormat.SRT, description="Subtitle format")
class VideoWithSubtitlesRequest(BaseModel):
"""Request schema for video with embedded subtitles."""
output_format: Optional[VideoFormat] = Field(
None, description="Output video format (auto-detect if not specified)"
)
include_speakers: bool = Field(True, description="Include speaker labels in subtitles")
force_regenerate: bool = Field(
False, description="Force regeneration even if cached version exists"
)
class VideoWithSubtitlesResponse(BaseModel):
"""Response schema for video with embedded subtitles."""
download_url: str = Field(..., description="URL to download the video with embedded subtitles")
format: str = Field(..., description="Video format")
cache_key: str = Field(..., description="Cache key for the processed video")
expires_at: datetime = Field(..., description="When the download URL expires")
file_size: Optional[int] = Field(None, description="Size of the processed video file")
class SubtitleValidationResult(BaseModel):
"""Result of subtitle validation."""
is_valid: bool = Field(..., description="Whether subtitles are valid")
issues: list[str] = Field(default_factory=list, description="List of validation issues found")
total_segments: int = Field(..., description="Total number of subtitle segments")
total_duration: float = Field(..., description="Total duration of subtitles in seconds")