-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmodels.py
More file actions
317 lines (233 loc) · 10 KB
/
models.py
File metadata and controls
317 lines (233 loc) · 10 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
"""Data models for Language Flashcard Generator."""
from datetime import datetime
from enum import Enum
from pathlib import Path
from typing import Dict, List, Optional
from pydantic import BaseModel, Field
current_version = 1
class ExampleSentence(BaseModel):
"""An example sentence in the target language with English translation."""
target_language: str = Field(..., description="Example sentence in target language")
english: str = Field(..., description="English translation")
audio_file: Optional[str] = Field(None, description="Path to audio file")
class AdditionalMeaning(BaseModel):
"""An additional meaning with its part of speech."""
meaning: str = Field(..., description="The additional meaning")
part_of_speech: str = Field(
..., description="Part of speech (e.g., 'n.', 'adj.', 'v.')"
)
class AudioFiles(BaseModel):
"""Audio files associated with a card."""
word: Optional[str] = Field(None, description="Audio for the main word")
examples: List[str] = Field(
default_factory=list, description="Audio files for example sentences"
)
class EnhancedContent(BaseModel):
"""AI-generated enhanced content for a card."""
word: str = Field(..., description="Word in target language")
romanization: str = Field(..., description="Romanization of the word")
pronunciation_ipa: str = Field(..., description="IPA phonetic transcription")
main_part_of_speech: str = Field(..., description="Part of speech (e.g., 'n.')")
examples: List[ExampleSentence] = Field(
default_factory=list, description="Example sentences"
)
etymology: str = Field(default="", description="Etymology and word origin")
additional_meanings: List[AdditionalMeaning] = Field(
default_factory=list, description="Additional meanings"
)
pos_tags: List[str] = Field(
default_factory=list, description="Part-of-speech tags"
)
audio_files: AudioFiles = Field(
default_factory=AudioFiles, description="Associated audio files"
)
class CardData(BaseModel):
"""Original card data from CSV."""
id: str = Field(..., description="Unique card identifier")
word: str = Field(..., description="Word in target language")
english: str = Field(..., description="English translation")
class EnhancedCard(BaseModel):
"""Complete enhanced card with original and AI-generated content."""
original: CardData
enhanced: EnhancedContent
version: int = Field(default=current_version, description="Card version")
def to_mochi_content(self) -> str:
"""Convert to Mochi markdown format with audio links."""
examples_list = []
for ex in self.enhanced.examples:
example_text = f"{ex.target_language}\n\n*{ex.english}*"
if ex.audio_file and Path(ex.audio_file).exists():
example_text += f"\n\n.name})"
examples_list.append(example_text)
examples_text = "\n\n".join(examples_list)
additional_meanings_text = ""
if self.enhanced.additional_meanings:
meaning_parts = [
f"({m.part_of_speech} {m.meaning})"
for m in self.enhanced.additional_meanings
]
additional_meanings_text = "\n" + "\n".join(meaning_parts)
word_audio = ""
if (
self.enhanced.audio_files.word
and Path(self.enhanced.audio_files.word).exists()
):
word_audio = (
f"\n\n.name})"
)
additional_meanings_simple = ""
if self.enhanced.additional_meanings:
additional_meanings_simple = ", " + ", ".join(
[m.meaning for m in self.enhanced.additional_meanings]
)
content = f"""# {self.enhanced.word}{word_audio}
---
### {self.enhanced.word}{word_audio}
({self.enhanced.main_part_of_speech} {self.original.english}){additional_meanings_text}
{self.enhanced.romanization}
{self.enhanced.pronunciation_ipa}
**Examples:**
{examples_text}
**Etymology:**
{self.enhanced.etymology}
---
# {self.original.english}{additional_meanings_simple}"""
return content
class ProcessingProgress(BaseModel):
"""Track processing progress and failures."""
processed_ids: List[str] = Field(default_factory=list)
failed_ids: List[str] = Field(default_factory=list)
last_batch: int = Field(default=0)
total_cards: int = Field(default=0)
@property
def completion_rate(self) -> float:
if self.total_cards == 0:
return 0.0
return len(self.processed_ids) / self.total_cards
# --- Batch API models ---
class BatchProcessingStatus(str, Enum):
"""Status of batch processing."""
NOT_STARTED = "not_started"
IN_PROGRESS = "in_progress"
CANCELING = "canceling"
ENDED = "ended"
FAILED = "failed"
class BatchRequest(BaseModel):
"""Individual request within a batch."""
custom_id: str = Field(..., description="Unique identifier for this request")
params: Dict = Field(..., description="Message creation parameters")
class BatchInfo(BaseModel):
"""Information about a submitted batch."""
batch_id: str = Field(..., description="Batch identifier from Claude")
status: BatchProcessingStatus = Field(..., description="Current batch status")
created_at: str = Field(..., description="When batch was created")
expires_at: Optional[str] = Field(None, description="When batch expires")
ended_at: Optional[str] = Field(None, description="When batch completed")
results_url: Optional[str] = Field(None, description="URL to download results")
total_requests: int = Field(..., description="Total number of requests in batch")
succeeded: int = Field(default=0, description="Number of successful requests")
failed: int = Field(default=0, description="Number of failed requests")
processing: int = Field(default=0, description="Number of processing requests")
card_id_mapping: Optional[Dict[str, str]] = Field(
default=None,
description="Mapping from sanitized custom_id to original card_id",
)
class BatchProgress(BaseModel):
"""Track batch processing progress across multiple batches."""
batches: List[BatchInfo] = Field(default_factory=list)
cards_by_batch: Dict[str, List[str]] = Field(default_factory=dict)
completed_cards: List[str] = Field(default_factory=list)
failed_cards: List[str] = Field(default_factory=list)
total_cards: int = Field(default=0)
@property
def completion_rate(self) -> float:
if self.total_cards == 0:
return 0.0
return len(self.completed_cards) / self.total_cards
@property
def active_batches(self) -> List[BatchInfo]:
return [
b
for b in self.batches
if b.status
in [BatchProcessingStatus.IN_PROGRESS, BatchProcessingStatus.CANCELING]
]
class BatchResult(BaseModel):
"""Result from a batch request."""
custom_id: str = Field(..., description="The custom ID from the request")
result: Optional[Dict] = Field(None, description="The successful result")
error: Optional[Dict] = Field(None, description="Error information if failed")
# --- Config models ---
class AzureTTSConfig(BaseModel):
"""Azure TTS voice configuration."""
male_voice: str = Field(
default="zu-ZA-ThembaNeural", description="Male voice name"
)
female_voice: str = Field(
default="zu-ZA-ThandoNeural", description="Female voice name"
)
class TTSConfig(BaseModel):
"""TTS configuration."""
enabled: bool = Field(default=True, description="Whether to generate TTS")
azure: AzureTTSConfig = Field(
default_factory=AzureTTSConfig, description="Azure TTS settings"
)
class EnhancementConfig(BaseModel):
"""Configuration for a deck build."""
key: str = Field(..., description="Unique key for build isolation")
deck_name: str = Field(
default="Enhanced Vocabulary", description="Name of the Mochi deck"
)
frequency_dir: str = Field(..., description="Path to frequency list CSV directory")
ai_provider: str = Field(default="anthropic", description="AI provider")
model: str = Field(
default="claude-3-5-haiku-20241022", description="Model name"
)
batch_size: int = Field(default=10, description="Cards per processing batch")
rate_limit_delay: float = Field(
default=1.0, description="Delay between API calls in seconds"
)
max_retries: int = Field(default=3, description="Max retry attempts")
use_batch_api: bool = Field(default=False, description="Use Claude batch API")
batch_check_interval: int = Field(
default=10, description="Seconds between batch status checks"
)
audio_concurrency: int = Field(
default=16, description="Max parallel Azure TTS workers"
)
tts: TTSConfig = Field(default_factory=TTSConfig, description="TTS configuration")
enhancement_fields: Dict[str, bool] = Field(
default_factory=lambda: {
"romanization": True,
"pronunciation_ipa": True,
"example_sentences": True,
"etymology": False,
"additional_meanings": True,
"part_of_speech": True,
}
)
@property
def build_dir(self) -> Path:
"""Root directory for all build artifacts for this config."""
return Path("builds") / self.key
@property
def cached_cards_dir(self) -> Path:
return self.build_dir / "cached_cards"
@property
def audio_dir(self) -> Path:
return self.build_dir / "audio_files"
@property
def output_dir(self) -> Path:
return self.build_dir / "output"
@property
def input_dir(self) -> Path:
return self.build_dir / "input"
@property
def log_dir(self) -> Path:
return self.build_dir / "logs"
@property
def progress_file(self) -> Path:
return self.build_dir / "progress.json"
@property
def batch_progress_file(self) -> Path:
return self.build_dir / "batch_progress.json"