-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathall_code.txt
More file actions
2606 lines (2105 loc) · 73.6 KB
/
all_code.txt
File metadata and controls
2606 lines (2105 loc) · 73.6 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
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
----- FILE: ./.env.example -----
# .env
# API Keys
DEEPL_API_KEY=your-deepl-key-here
OPENAI_API_KEY=your-openai-key-here
GOOGLE_APPLICATION_CREDENTIALS=path/to/google-credentials.json
# Storage
STORAGE_TYPE=local
STORAGE_PATH=./storage
# Audio
AUDIO_PROVIDER=google
GOOGLE_TTS_VOICE=fr-FR-Neural2-A
# Translation
TRANSLATION_PROVIDER=openai # or "deepl"
# Dictionary
DICTIONARY_PROVIDER=openai
----- FILE: ./Makefile -----
# Makefile
.PHONY: install test add batch clean help
install:
poetry install
mkdir -p output storage/audio cache
test:
poetry run python infrastructure/cli/main.py test
add:
@echo "Usage: make add SENTENCE='Your French sentence here'"
poetry run python infrastructure/cli/main.py add "$(SENTENCE)"
batch:
@echo "Usage: make batch FILE=sentences.txt DECK='Deck Name'"
poetry run python infrastructure/cli/main.py batch $(FILE) --deck-name "$(DECK)"
clean:
rm -rf output/*.apkg
rm -rf cache/*
rm -rf storage/audio/*
help:
@echo "French Flashcard Generator"
@echo ""
@echo "Commands:"
@echo " make install Install dependencies"
@echo " make test Test configuration"
@echo " make add SENTENCE='...' Generate single card"
@echo " make batch FILE=... Generate deck from file"
@echo " make clean Clean output files"
----- FILE: ./adapters/anki/genanki_exporter.py -----
# adapters/anki/genanki_exporter.py
import genanki
import hashlib
from pathlib import Path
from typing import List, Optional
from core.domain.interfaces import DeckExporter
from core.domain.models import Deck, FlashCard
class GenankiExporter(DeckExporter):
"""
Adapter for exporting decks to Anki's .apkg format using genanki library.
This adapter converts our domain models into genanki's format and
handles the creation of proper Anki card templates with styling.
"""
# Class-level constants for model IDs (must be unique and stable)
# These are generated once and should not change
DEFAULT_MODEL_ID = 1891667001
DEFAULT_DECK_ID_SALT = "french-flashcard-generator"
def __init__(self):
self._card_model = self._create_card_model()
def _create_card_model(self) -> genanki.Model:
"""
Create the Anki card template (note type).
This defines:
- What fields each card has
- How the front/back are rendered (HTML templates)
- CSS styling for the cards
"""
return genanki.Model(
model_id=self.DEFAULT_MODEL_ID,
name='French Language Card (Enhanced)',
fields=[
{'name': 'French'}, # Front: The sentence in French
{'name': 'English'}, # Back: English translation
{'name': 'WordBreakdown'}, # Back: Word-by-word definitions
{'name': 'Audio'}, # Front/Back: Audio pronunciation
{'name': 'GrammarNotes'}, # Back: Grammar explanations
{'name': 'Tags'}, # Metadata: Tags for organization
{'name': 'SentenceId'}, # Hidden: For tracking/updates
],
templates=[
{
'name': 'Card 1',
'qfmt': self._get_front_template(), # Question (front) format
'afmt': self._get_back_template(), # Answer (back) format
},
],
css=self._get_card_styles()
)
def _get_front_template(self) -> str:
"""HTML template for the front of the card"""
return '''
<div class="card-container">
<div class="card-header">
<span class="language-label">🇫🇷 Français</span>
</div>
<div class="french-text">
{{French}}
</div>
<div class="audio-container">
{{Audio}}
</div>
<div class="hint">
💡 Tap to reveal translation
</div>
</div>
'''
def _get_back_template(self) -> str:
"""HTML template for the back of the card"""
return '''
{{FrontSide}}
<hr class="divider">
<div class="card-container">
<div class="card-header">
<span class="language-label">🇬🇧 English</span>
</div>
<div class="english-text">
{{English}}
</div>
{{#WordBreakdown}}
<div class="breakdown-section">
<div class="section-title">📚 Word Breakdown</div>
<div class="breakdown-content">
{{WordBreakdown}}
</div>
</div>
{{/WordBreakdown}}
{{#GrammarNotes}}
<div class="grammar-section">
<div class="section-title">✏️ Grammar Notes</div>
<div class="grammar-content">
{{GrammarNotes}}
</div>
</div>
{{/GrammarNotes}}
</div>
'''
def _get_card_styles(self) -> str:
"""CSS styling for the cards"""
return '''
/* Base card styling */
.card {
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto,
'Helvetica Neue', Arial, sans-serif;
font-size: 18px;
line-height: 1.6;
color: #2c3e50;
background: #ffffff;
padding: 20px;
max-width: 600px;
margin: 0 auto;
}
.card-container {
text-align: center;
}
/* Header with language label */
.card-header {
margin-bottom: 15px;
}
.language-label {
display: inline-block;
padding: 6px 12px;
background: #f8f9fa;
border-radius: 20px;
font-size: 14px;
font-weight: 600;
color: #6c757d;
}
/* Main text styling */
.french-text {
font-size: 28px;
font-weight: 600;
color: #2c3e50;
margin: 25px 0;
line-height: 1.4;
}
.english-text {
font-size: 22px;
font-weight: 500;
color: #27ae60;
margin: 20px 0;
line-height: 1.4;
}
/* Audio player */
.audio-container {
margin: 20px 0;
}
/* Hint text on front */
.hint {
font-size: 14px;
color: #95a5a6;
margin-top: 30px;
font-style: italic;
}
/* Divider between front and back */
.divider {
margin: 30px 0;
border: none;
border-top: 2px solid #ecf0f1;
}
/* Word breakdown section */
.breakdown-section {
margin-top: 30px;
text-align: left;
background: #f8f9fa;
padding: 20px;
border-radius: 12px;
}
.section-title {
font-size: 16px;
font-weight: 700;
color: #495057;
margin-bottom: 12px;
text-transform: uppercase;
letter-spacing: 0.5px;
}
.breakdown-content {
font-size: 15px;
line-height: 1.8;
}
.breakdown-content b {
color: #3498db;
font-weight: 600;
}
/* Grammar notes section */
.grammar-section {
margin-top: 20px;
text-align: left;
background: #fff9e6;
padding: 20px;
border-radius: 12px;
border-left: 4px solid #f39c12;
}
.grammar-content {
font-size: 15px;
line-height: 1.8;
color: #7f6d00;
}
/* Mobile responsiveness */
@media (max-width: 600px) {
.card {
padding: 15px;
font-size: 16px;
}
.french-text {
font-size: 24px;
}
.english-text {
font-size: 20px;
}
}
/* Dark mode support (Anki 2.1.50+) */
.nightMode .card {
background: #1e1e1e;
color: #e0e0e0;
}
.nightMode .french-text {
color: #ffffff;
}
.nightMode .english-text {
color: #4caf50;
}
.nightMode .breakdown-section {
background: #2d2d2d;
}
.nightMode .grammar-section {
background: #3d3520;
border-left-color: #ffa726;
}
.nightMode .language-label {
background: #2d2d2d;
color: #b0b0b0;
}
'''
async def export_deck(
self,
deck: Deck,
output_path: str
) -> str:
"""
Export a Deck to .apkg format.
Args:
deck: The Deck domain model to export
output_path: Where to save the .apkg file
Returns:
The full path to the created .apkg file
"""
# Generate a stable deck ID based on deck name
deck_id = self._generate_deck_id(deck.name)
# Create genanki deck
anki_deck = genanki.Deck(
deck_id=deck_id,
name=deck.name
)
# Convert each card and add to deck
media_files = []
for card in deck.cards:
note = self._convert_card_to_note(card)
anki_deck.add_note(note)
# Collect media files (audio)
if card.audio and card.audio.filename:
media_files.append(card.audio.filename)
# Create package with media
package = genanki.Package(anki_deck)
# Add media files if they exist
if media_files:
package.media_files = self._resolve_media_paths(media_files)
# Ensure output directory exists
output_file = Path(output_path)
output_file.parent.mkdir(parents=True, exist_ok=True)
# Write .apkg file
package.write_to_file(str(output_file))
return str(output_file.absolute())
def _convert_card_to_note(self, card: FlashCard) -> genanki.Note:
"""
Convert a FlashCard domain model to a genanki Note.
Args:
card: The FlashCard to convert
Returns:
A genanki.Note instance ready to be added to a deck
"""
# Format word breakdown as HTML
word_breakdown_html = self._format_word_breakdown(card)
# Format grammar notes as HTML
grammar_notes_html = self._format_grammar_notes(card)
# Format audio field
audio_field = self._format_audio_field(card)
# Format tags
tags_str = " ".join(card.tags) if card.tags else ""
# Create note with all fields
note = genanki.Note(
model=self._card_model,
fields=[
card.sentence.text, # French
card.translation.text, # English
word_breakdown_html, # WordBreakdown
audio_field, # Audio
grammar_notes_html, # GrammarNotes
tags_str, # Tags
card.id, # SentenceId (hidden)
],
tags=card.tags if card.tags else []
)
return note
def _format_word_breakdown(self, card: FlashCard) -> str:
"""Format word breakdown as HTML"""
if not card.word_breakdown or not card.word_breakdown.words:
return ""
lines = []
for word in card.word_breakdown.words:
# Format: <b>word</b> (pos): definition
line = f"<b>{word.text}</b> <span class='pos'>({word.pos})</span>: {word.definition}"
lines.append(line)
return "<br>".join(lines)
def _format_grammar_notes(self, card: FlashCard) -> str:
"""Format grammar notes as HTML"""
if not card.grammar_notes:
return ""
lines = []
for note in card.grammar_notes:
# Format with bullet points
lines.append(f"• <strong>{note.title}:</strong> {note.explanation}")
# Add examples if present
if note.examples:
for example in note.examples:
lines.append(f" <em>Example: {example}</em>")
return "<br>".join(lines)
def _format_audio_field(self, card: FlashCard) -> str:
"""
Format audio field for Anki.
Anki expects: [sound:filename.mp3]
"""
if not card.audio or not card.audio.filename:
return ""
return f"[sound:{card.audio.filename}]"
def _generate_deck_id(self, deck_name: str) -> int:
"""
Generate a stable deck ID from the deck name.
Uses hash to ensure:
1. Same deck name = same ID (for updates)
2. Different deck names = different IDs
3. IDs are valid positive integers for Anki
"""
# Create hash of deck name + salt
hash_input = f"{deck_name}{self.DEFAULT_DECK_ID_SALT}"
hash_value = hashlib.md5(hash_input.encode()).hexdigest()
# Convert first 8 hex chars to int (ensures 32-bit positive int)
deck_id = int(hash_value[:8], 16)
# Ensure it's positive and within Anki's range
return deck_id & 0x7FFFFFFF
def _resolve_media_paths(self, filenames: List[str]) -> List[str]:
"""
Resolve media file paths.
This assumes audio files are stored in a known location.
In production, this would interface with the StorageService.
"""
# For now, assume files are in ./storage/audio/
# In production, you'd get these from StorageService
base_path = Path("./storage/audio")
resolved_paths = []
for filename in filenames:
file_path = base_path / filename
if file_path.exists():
resolved_paths.append(str(file_path))
else:
# Log warning but don't fail
print(f"⚠️ Warning: Audio file not found: {filename}")
return resolved_paths
class GenankiExporterWithProgressTracking(GenankiExporter):
"""
Enhanced version with progress tracking for large decks.
Useful for API/background job scenarios where you want to
report progress to users.
"""
def __init__(self, progress_callback: Optional[callable] = None):
super().__init__()
self.progress_callback = progress_callback
async def export_deck(
self,
deck: Deck,
output_path: str
) -> str:
"""Export with progress updates"""
total_cards = len(deck.cards)
# Generate deck ID
deck_id = self._generate_deck_id(deck.name)
anki_deck = genanki.Deck(deck_id=deck_id, name=deck.name)
# Process cards with progress tracking
media_files = []
for i, card in enumerate(deck.cards):
note = self._convert_card_to_note(card)
anki_deck.add_note(note)
if card.audio and card.audio.filename:
media_files.append(card.audio.filename)
# Report progress
if self.progress_callback:
progress = (i + 1) / total_cards * 100
self.progress_callback(progress, f"Processing card {i+1}/{total_cards}")
# Create package
if self.progress_callback:
self.progress_callback(95, "Creating .apkg file...")
package = genanki.Package(anki_deck)
if media_files:
package.media_files = self._resolve_media_paths(media_files)
# Write file
output_file = Path(output_path)
output_file.parent.mkdir(parents=True, exist_ok=True)
package.write_to_file(str(output_file))
if self.progress_callback:
self.progress_callback(100, "Complete!")
return str(output_file.absolute())
# Convenience function for direct usage
def export_cards_to_anki(
cards: List[FlashCard],
deck_name: str,
output_path: str
) -> str:
"""
Quick utility function to export cards without using the full architecture.
Useful for simple scripts or testing.
Args:
cards: List of FlashCard objects
deck_name: Name for the Anki deck
output_path: Where to save the .apkg file
Returns:
Path to the created .apkg file
"""
from core.domain.models import Deck
import asyncio
# Create a deck from the cards
deck = Deck(name=deck_name, cards=cards)
# Export
exporter = GenankiExporter()
return asyncio.run(exporter.export_deck(deck, output_path))
# Example usage
# if __name__ == "__main__":
# """
# Example of how to use the exporter directly
# """
# from core.domain.models import (
# FlashCard, Sentence, Translation, WordBreakdown,
# Word, AudioFile, AudioFormat, GrammarNote
# )
# # Create a sample card
# card = FlashCard(
# sentence=Sentence(text="Je mange une pomme."),
# translation=Translation(text="I eat an apple."),
# word_breakdown=WordBreakdown(words=[
# Word(text="Je", lemma="je", pos="pronoun", definition="I"),
# Word(text="mange", lemma="manger", pos="verb", definition="eat"),
# Word(text="une", lemma="un", pos="article", definition="a/an"),
# Word(text="pomme", lemma="pomme", pos="noun", definition="apple"),
# ]),
# audio=AudioFile(
# filename="je_mange_une_pomme.mp3",
# format=AudioFormat.MP3,
# provider="google-tts"
# ),
# grammar_notes=[
# GrammarNote(
# title="Present tense",
# explanation="'mange' is the present tense conjugation of 'manger' for 'je'",
# examples=["Tu manges", "Il mange"]
# )
# ],
# tags=["food", "beginner", "verbs"]
# )
# # Export single card
# output = export_cards_to_anki(
# cards=[card],
# deck_name="French Practice",
# output_path="./output/french_practice.apkg"
# )
# print(f"✅ Deck created: {output}")
----- FILE: ./adapters/audio/google_tts_adapter.py -----
# adapters/audio/google_tts_adapter.py
from google.cloud import texttospeech_v1 as tts
from core.domain.interfaces import AudioService
from core.domain.models import AudioFile, AudioFormat
import hashlib
class GoogleTTSAdapter(AudioService):
"""Google Cloud Text-to-Speech"""
def __init__(self, voice_name: str = "fr-FR-Neural2-A"):
self.client = tts.TextToSpeechClient()
self.voice_name = voice_name
async def generate_audio(
self,
text: str,
language: str,
format: AudioFormat = AudioFormat.MP3
) -> AudioFile:
synthesis_input = tts.SynthesisInput(text=text)
voice = tts.VoiceSelectionParams(
language_code=f"{language}-{language.upper()}",
name=self.voice_name,
ssml_gender=tts.SsmlVoiceGender.FEMALE
)
audio_config = tts.AudioConfig(
audio_encoding=tts.AudioEncoding.MP3
)
response = self.client.synthesize_speech(
input=synthesis_input,
voice=voice,
audio_config=audio_config
)
# Generate filename from content hash
text_hash = hashlib.md5(text.encode()).hexdigest()
filename = f"{text_hash}.{format.value}"
# Save audio data (would be handled by storage service)
# For now, just return metadata
return AudioFile(
filename=filename,
format=format,
provider="google-tts"
)
----- FILE: ./adapters/dictionary/openai_dictionary_adapter.py -----
# adapters/dictionary/openai_dictionary_adapter.py
import openai
import json
from typing import List
from core.domain.interfaces import DictionaryService
from core.domain.models import Word, WordBreakdown
class OpenAIDictionaryAdapter(DictionaryService):
"""Use GPT-4o for word analysis (most flexible)"""
def __init__(self, api_key: str):
self.client = openai.AsyncOpenAI(api_key=api_key)
async def lookup_word(
self,
word: str,
source_lang: str,
target_lang: str
) -> Word:
prompt = f"""Analyze this {source_lang} word: "{word}"
Provide JSON:
{{
"lemma": "base form of word",
"pos": "noun/verb/adj/etc",
"definition": "concise English definition (max 5 words)"
}}"""
response = await self.client.chat.completions.create(
model="gpt-4o-mini",
messages=[{"role": "user", "content": prompt}],
response_format={"type": "json_object"}
)
data = json.loads(response.choices[0].message.content)
return Word(
text=word,
lemma=data['lemma'],
pos=data['pos'],
definition=data['definition']
)
async def analyze_sentence(
self,
sentence: str,
source_lang: str,
target_lang: str
) -> WordBreakdown:
prompt = f"""Analyze each word in this {source_lang} sentence:
"{sentence}"
For each word provide JSON array:
[
{{
"text": "original word",
"lemma": "base form",
"pos": "part of speech",
"definition": "brief English definition"
}}
]
Skip punctuation."""
response = await self.client.chat.completions.create(
model="gpt-4o-mini",
messages=[{"role": "user", "content": prompt}],
response_format={"type": "json_object"}
)
data = json.loads(response.choices[0].message.content)
words = [
Word(**word_data)
for word_data in data.get('words', [])
]
return WordBreakdown(words=words)
----- FILE: ./adapters/storage/local_file_storage.py -----
# adapters/storage/local_file_storage.py
import os
from pathlib import Path
from core.domain.interfaces import StorageService
from core.domain.models import AudioFile
class LocalFileStorage(StorageService):
"""Store files locally (for laptop use)"""
def __init__(self, base_path: str = "./storage"):
self.base_path = Path(base_path)
self.audio_path = self.base_path / "audio"
self.audio_path.mkdir(parents=True, exist_ok=True)
async def save_audio(self, audio: AudioFile, data: bytes) -> str:
filepath = self.audio_path / audio.filename
with open(filepath, 'wb') as f:
f.write(data)
return str(filepath)
async def get_audio(self, filename: str) -> bytes:
filepath = self.audio_path / filename
with open(filepath, 'rb') as f:
return f.read()
async def delete_audio(self, filename: str) -> None:
filepath = self.audio_path / filename
filepath.unlink(missing_ok=True)
----- FILE: ./adapters/storage/s3_storage.py -----
# adapters/storage/s3_storage.py
import boto3
from core.domain.interfaces import StorageService
from core.domain.models import AudioFile
class S3StorageAdapter(StorageService):
"""Store files in S3 (for production)"""
def __init__(self, bucket_name: str, region: str = "us-east-1"):
self.bucket = bucket_name
self.s3 = boto3.client('s3', region_name=region)
async def save_audio(self, audio: AudioFile, data: bytes) -> str:
key = f"audio/{audio.filename}"
self.s3.put_object(
Bucket=self.bucket,
Key=key,
Body=data,
ContentType=f"audio/{audio.format.value}"
)
# Return public URL
url = f"https://{self.bucket}.s3.amazonaws.com/{key}"
return url
async def get_audio(self, filename: str) -> bytes:
key = f"audio/{filename}"
response = self.s3.get_object(Bucket=self.bucket, Key=key)
return response['Body'].read()
async def delete_audio(self, filename: str) -> None:
key = f"audio/{filename}"
self.s3.delete_object(Bucket=self.bucket, Key=key)
----- FILE: ./adapters/translation/deepl_adapter.py -----
# adapters/translation/deepl_adapter.py
import httpx
from core.domain.interfaces import TranslationService
from core.domain.models import Translation
class DeepLTranslationAdapter(TranslationService):
"""DeepL API implementation"""
def __init__(self, api_key: str):
self.api_key = api_key
self.base_url = "https://api-free.deepl.com/v2"
async def translate(
self,
text: str,
source_lang: str,
target_lang: str
) -> Translation:
async with httpx.AsyncClient() as client:
response = await client.post(
f"{self.base_url}/translate",
data={
'auth_key': self.api_key,
'text': text,
'source_lang': source_lang.upper(),
'target_lang': target_lang.upper()
}
)
response.raise_for_status()
data = response.json()
return Translation(
text=data['translations'][0]['text'],
target_language=target_lang,
provider="deepl",
confidence=1.0 # DeepL doesn't provide confidence
)
----- FILE: ./adapters/translation/openai_adapter.py -----
# adapters/translation/openai_adapter.py
import openai
from core.domain.interfaces import TranslationService
from core.domain.models import Translation
class OpenAITranslationAdapter(TranslationService):
"""OpenAI GPT-4o translation (more context-aware)"""
def __init__(self, api_key: str, model: str = "gpt-4o-mini"):
self.client = openai.AsyncOpenAI(api_key=api_key)
self.model = model
async def translate(
self,
text: str,
source_lang: str,
target_lang: str
) -> Translation:
prompt = f"""Translate this {source_lang} text to {target_lang}.
Provide ONLY the translation, no explanations.
Text: {text}"""
response = await self.client.chat.completions.create(
model=self.model,
messages=[{"role": "user", "content": prompt}],
temperature=0.3 # Lower = more consistent
)
translated_text = response.choices[0].message.content.strip()
return Translation(
text=translated_text,
target_language=target_lang,
provider=f"openai-{self.model}"
)
----- FILE: ./core/domain/interfaces.py -----
# core/domain/interfaces.py
from abc import ABC, abstractmethod
from typing import List, Optional
from .models import (
Sentence, Translation, WordBreakdown, AudioFile,
GrammarNote, FlashCard, Deck, AudioFormat
)
class TranslationService(ABC):
"""Port for translation providers"""
@abstractmethod
async def translate(
self,
text: str,
source_lang: str,
target_lang: str
) -> Translation:
"""Translate text from source to target language"""
pass
class DictionaryService(ABC):
"""Port for dictionary lookups"""
@abstractmethod
async def lookup_word(
self,
word: str,
source_lang: str,
target_lang: str
) -> Word:
"""Get definition for a single word"""
pass
@abstractmethod
async def analyze_sentence(
self,
sentence: str,
source_lang: str,
target_lang: str
) -> WordBreakdown:
"""Analyze all words in a sentence"""
pass
class AudioService(ABC):
"""Port for text-to-speech"""
@abstractmethod
async def generate_audio(
self,
text: str,
language: str,
format: AudioFormat = AudioFormat.MP3
) -> AudioFile:
"""Generate audio file for text"""
pass
class GrammarService(ABC):
"""Port for grammar explanations"""
@abstractmethod
async def explain_grammar(
self,
sentence: str,
language: str
) -> List[GrammarNote]:
"""Generate grammar explanations"""
pass
class SentenceSearchService(ABC):
"""Port for finding example sentences"""
@abstractmethod
async def search_by_topic(