File size: 10,135 Bytes
937c29e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5aa0409
937c29e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7dd7ca0
 
 
937c29e
 
7dd7ca0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
937c29e
 
 
 
7dd7ca0
937c29e
 
 
 
 
 
 
 
7dd7ca0
 
937c29e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
Sema Translation API - New Implementation
Created for testing consolidated sema-utils repository
Uses HuggingFace Hub for model downloading
"""

import os
import time
from datetime import datetime
import pytz
from typing import Optional

from fastapi import FastAPI, HTTPException, Request
from fastapi.middleware.cors import CORSMiddleware
from pydantic import BaseModel, Field
from huggingface_hub import hf_hub_download
import ctranslate2
import sentencepiece as spm
import fasttext

# --- Data Models ---
class TranslationRequest(BaseModel):
    text: str = Field(..., example="Habari ya asubuhi", description="Text to translate")
    target_language: str = Field(..., example="eng_Latn", description="FLORES-200 target language code")
    source_language: Optional[str] = Field(None, example="swh_Latn", description="Optional FLORES-200 source language code")

class TranslationResponse(BaseModel):
    translated_text: str
    source_language: str
    target_language: str
    inference_time: float
    timestamp: str

# --- FastAPI App Setup ---
app = FastAPI(
    title="Sema Translation API",
    description="Translation API using consolidated sema-utils models from HuggingFace",
    version="2.0.0"
)

# CORS middleware
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=False,
    allow_methods=["*"],
    allow_headers=["*"],
)

# --- Global Variables ---
REPO_ID = "sematech/sema-utils"
beam_size = 1
device = "cpu"

# Model instances (will be loaded on startup)
lang_model = None
sp_model = None
translator = None

def get_nairobi_time():
    """Get current time in Nairobi timezone"""
    nairobi_timezone = pytz.timezone('Africa/Nairobi')
    current_time_nairobi = datetime.now(nairobi_timezone)

    curr_day = current_time_nairobi.strftime('%A')
    curr_date = current_time_nairobi.strftime('%Y-%m-%d')
    curr_time = current_time_nairobi.strftime('%H:%M:%S')

    full_date = f"{curr_day} | {curr_date} | {curr_time}"
    return full_date, curr_time

def get_model_paths():
    """Get model paths from HuggingFace cache (models pre-downloaded in Docker)"""
    print("πŸ”„ Loading models from cache...")

    try:
        # Check if we're in offline mode (Docker environment)
        offline_mode = os.environ.get("HF_HUB_OFFLINE", "0") == "1"

        if offline_mode:
            print("πŸ“¦ Running in offline mode - using cached models")
            # In offline mode, models are already downloaded and cached
            # We need to find them in the cache directory

            # Get paths from cache using hf_hub_download with local_files_only=True
            spm_path = hf_hub_download(
                repo_id=REPO_ID,
                filename="spm.model",
                local_files_only=True
            )

            ft_path = hf_hub_download(
                repo_id=REPO_ID,
                filename="lid218e.bin",
                local_files_only=True
            )

            # Get the translation model path
            model_bin_path = hf_hub_download(
                repo_id=REPO_ID,
                filename="translation_models/sematrans-3.3B/model.bin",
                local_files_only=True
            )

            # The model directory is the parent of the model.bin file
            ct_model_full_path = os.path.dirname(model_bin_path)

        else:
            print("🌐 Running in online mode - downloading models")
            # Online mode - download models (for local development)
            spm_path = hf_hub_download(
                repo_id=REPO_ID,
                filename="spm.model"
            )

            ft_path = hf_hub_download(
                repo_id=REPO_ID,
                filename="lid218e.bin"
            )

            # Download all necessary CTranslate2 files
            model_bin_path = hf_hub_download(
                repo_id=REPO_ID,
                filename="translation_models/sematrans-3.3B/model.bin"
            )

            hf_hub_download(
                repo_id=REPO_ID,
                filename="translation_models/sematrans-3.3B/config.json"
            )

            hf_hub_download(
                repo_id=REPO_ID,
                filename="translation_models/sematrans-3.3B/shared_vocabulary.txt"
            )

            ct_model_full_path = os.path.dirname(model_bin_path)

        print(f"πŸ“ Model paths:")
        print(f"   SentencePiece: {spm_path}")
        print(f"   Language detection: {ft_path}")
        print(f"   Translation model: {ct_model_full_path}")

        return spm_path, ft_path, ct_model_full_path

    except Exception as e:
        print(f"❌ Error loading models: {e}")
        raise e

def load_models():
    """Load all models into memory"""
    global lang_model, sp_model, translator

    print("πŸš€ Loading models into memory...")

    # Get model paths (from cache or download)
    spm_path, ft_path, ct_model_path = get_model_paths()

    # Suppress fasttext warnings
    fasttext.FastText.eprint = lambda x: None

    try:
        # Load language detection model
        print("1️⃣ Loading language detection model...")
        lang_model = fasttext.load_model(ft_path)

        # Load SentencePiece model
        print("2️⃣ Loading SentencePiece model...")
        sp_model = spm.SentencePieceProcessor()
        sp_model.load(spm_path)

        # Load translation model
        print("3️⃣ Loading translation model...")
        translator = ctranslate2.Translator(ct_model_path, device)

        print("βœ… All models loaded successfully!")

    except Exception as e:
        print(f"❌ Error loading models: {e}")
        raise e

def translate_with_detection(text: str, target_lang: str):
    """Translate text with automatic source language detection"""
    start_time = time.time()

    # Prepare input
    source_sents = [text.strip()]
    target_prefix = [[target_lang]]

    # Detect source language
    predictions = lang_model.predict(text.replace('\n', ' '), k=1)
    source_lang = predictions[0][0].replace('__label__', '')

    # Tokenize source text
    source_sents_subworded = sp_model.encode(source_sents, out_type=str)
    source_sents_subworded = [[source_lang] + sent + ["</s>"] for sent in source_sents_subworded]

    # Translate
    translations = translator.translate_batch(
        source_sents_subworded,
        batch_type="tokens",
        max_batch_size=2048,
        beam_size=beam_size,
        target_prefix=target_prefix,
    )

    # Decode translation
    translations = [translation[0]['tokens'] for translation in translations]
    translations_desubword = sp_model.decode(translations)
    translated_text = translations_desubword[0][len(target_lang):]

    inference_time = time.time() - start_time

    return source_lang, translated_text, inference_time

def translate_with_source(text: str, source_lang: str, target_lang: str):
    """Translate text with provided source language"""
    start_time = time.time()

    # Prepare input
    source_sents = [text.strip()]
    target_prefix = [[target_lang]]

    # Tokenize source text
    source_sents_subworded = sp_model.encode(source_sents, out_type=str)
    source_sents_subworded = [[source_lang] + sent + ["</s>"] for sent in source_sents_subworded]

    # Translate
    translations = translator.translate_batch(
        source_sents_subworded,
        batch_type="tokens",
        max_batch_size=2048,
        beam_size=beam_size,
        target_prefix=target_prefix
    )

    # Decode translation
    translations = [translation[0]['tokens'] for translation in translations]
    translations_desubword = sp_model.decode(translations)
    translated_text = translations_desubword[0][len(target_lang):]

    inference_time = time.time() - start_time

    return translated_text, inference_time

# --- API Endpoints ---

@app.get("/")
async def root():
    """Health check endpoint"""
    return {
        "status": "ok",
        "message": "Sema Translation API is running",
        "version": "2.0.0",
        "models_loaded": all([lang_model, sp_model, translator])
    }

@app.post("/translate", response_model=TranslationResponse)
async def translate_endpoint(request: TranslationRequest):
    """
    Main translation endpoint.
    Automatically detects source language if not provided.
    """
    if not request.text.strip():
        raise HTTPException(status_code=400, detail="Input text cannot be empty")

    full_date, current_time = get_nairobi_time()
    print(f"\nπŸ”„ Request: {full_date}")
    print(f"Target: {request.target_language}, Text: {request.text[:50]}...")

    try:
        if request.source_language:
            # Use provided source language
            translated_text, inference_time = translate_with_source(
                request.text,
                request.source_language,
                request.target_language
            )
            source_lang = request.source_language
        else:
            # Auto-detect source language
            source_lang, translated_text, inference_time = translate_with_detection(
                request.text,
                request.target_language
            )

        _, response_time = get_nairobi_time()
        print(f"βœ… Response: {response_time}")
        print(f"Source: {source_lang}, Translation: {translated_text[:50]}...\n")

        return TranslationResponse(
            translated_text=translated_text,
            source_language=source_lang,
            target_language=request.target_language,
            inference_time=inference_time,
            timestamp=full_date
        )

    except Exception as e:
        print(f"❌ Translation error: {e}")
        raise HTTPException(status_code=500, detail=f"Translation failed: {str(e)}")

# --- Startup Event ---
@app.on_event("startup")
async def startup_event():
    """Load models when the application starts"""
    print("\n🎡 Starting Sema Translation API...")
    print("🎼 Loading the Orchestra... πŸ¦‹")
    load_models()
    print("πŸŽ‰ API started successfully!\n")

if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="0.0.0.0", port=8000)