File size: 21,357 Bytes
1aee8e8
 
 
 
34b9253
92593b8
1aee8e8
 
595752f
 
 
1aee8e8
 
595752f
1aee8e8
 
595752f
6bd1e51
 
fe109d5
6bd1e51
 
 
1aee8e8
6bd1e51
595752f
1aee8e8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
595752f
1aee8e8
 
 
 
 
6bd1e51
1aee8e8
 
6bd1e51
1aee8e8
 
 
fe109d5
1aee8e8
 
 
 
 
595752f
1aee8e8
 
 
595752f
 
1aee8e8
595752f
 
1aee8e8
 
 
595752f
1aee8e8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
595752f
 
 
1aee8e8
595752f
1aee8e8
 
 
 
 
 
 
 
 
 
 
 
 
595752f
1aee8e8
 
 
 
 
 
595752f
1aee8e8
 
 
595752f
1aee8e8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6bd1e51
595752f
1aee8e8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
34b9253
1aee8e8
 
 
 
 
 
 
 
 
 
 
34b9253
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1aee8e8
 
 
bbd3488
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
LocaleNLP Translation Service
============================
A multi-language translation application supporting English, Wolof, Hausa, and Darija.
Features text, audio, and document translation with automatic chaining for all language pairs.
Author: LocaleNLP
"""

import os
import re
import logging
import tempfile
from typing import Optional, Dict, Tuple, Any, Union
from pathlib import Path
from dataclasses import dataclass
from enum import Enum

import gradio as gr
import torch
import whisper
import fitz  # PyMuPDF
import docx
from bs4 import BeautifulSoup
from markdown import markdown
import chardet
from transformers import pipeline, MarianTokenizer, AutoModelForSeq2SeqLM
from huggingface_hub import login

# ================================
# Configuration & Constants
# ================================

class Language(str, Enum):
    """Supported languages for translation."""
    ENGLISH = "English"
    WOLOF = "Wolof"
    HAUSA = "Hausa"
    DARIJA = "Darija"

class InputMode(str, Enum):
    """Supported input modes."""
    TEXT = "Text"
    AUDIO = "Audio"
    FILE = "File"

@dataclass
class ModelConfig:
    """Configuration for translation models."""
    model_name: str
    language_tag: str

# Language pair configurations
TRANSLATION_MODELS: Dict[Tuple[Language, Language], ModelConfig] = {
    (Language.ENGLISH, Language.WOLOF): ModelConfig(
        "LocaleNLP/localenlp-eng-wol-0.03", ">>wol<<"
    ),
    (Language.WOLOF, Language.ENGLISH): ModelConfig(
        "LocaleNLP/localenlp-wol-eng-0.03", ">>eng<<"
    ),
    (Language.ENGLISH, Language.HAUSA): ModelConfig(
        "LocaleNLP/localenlp-eng-hau-0.01", ">>hau<<"
    ),
    (Language.HAUSA, Language.ENGLISH): ModelConfig(
        "LocaleNLP/localenlp-hau-eng-0.01", ">>eng<<"
    ),
    (Language.ENGLISH, Language.DARIJA): ModelConfig(
        "LocaleNLP/english_darija", ">>dar<<"
    )
}

# File type support
SUPPORTED_FILE_TYPES = [
    ".pdf", ".docx", ".html", ".htm", ".md", 
    ".srt", ".txt", ".text"
]

# Audio file extensions
AUDIO_EXTENSIONS = [".wav", ".mp3", ".m4a"]

# ================================
# Logging Configuration
# ================================

logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger(__name__)

# ================================
# Model Management
# ================================

class ModelManager:
    """Centralized model management for translation and transcription."""
    
    def __init__(self):
        self._translation_pipeline = None
        self._whisper_model = None
        self._current_model_name = None
        
    def get_translation_pipeline(
        self, 
        source_lang: Language, 
        target_lang: Language
    ) -> Tuple[Any, str]:
        """
        Load and return translation pipeline for given language pair.
        
        Args:
            source_lang: Source language
            target_lang: Target language
            
        Returns:
            Tuple of (pipeline, language_tag)
            
        Raises:
            ValueError: If language pair is not supported
        """
        key = (source_lang, target_lang)
        if key not in TRANSLATION_MODELS:
            raise ValueError(f"Unsupported translation pair: {source_lang} -> {target_lang}")
            
        config = TRANSLATION_MODELS[key]
        
        # Load model if not loaded or different model needed
        if (self._translation_pipeline is None or 
            self._current_model_name != config.model_name):
            
            logger.info(f"Loading translation model: {config.model_name}")
            
            # Authenticate with Hugging Face if token provided
            if hf_token := os.getenv("hffff"):
                login(token=hf_token)
            
            model = AutoModelForSeq2SeqLM.from_pretrained(
                config.model_name,
                token=hf_token
            ).to(self._get_device())
            
            tokenizer = MarianTokenizer.from_pretrained(
                config.model_name,
                token=hf_token
            )
            
            self._translation_pipeline = pipeline(
                "translation",
                model=model,
                tokenizer=tokenizer,
                device=0 if self._get_device().type == "cuda" else -1
            )
            
            self._current_model_name = config.model_name
            
        return self._translation_pipeline, config.language_tag
    
    def get_whisper_model(self) -> Any:
        """
        Load and return Whisper transcription model.
        
        Returns:
            Whisper model instance
        """
        if self._whisper_model is None:
            logger.info("Loading Whisper base model...")
            self._whisper_model = whisper.load_model("base")
        return self._whisper_model
    
    def _get_device(self) -> torch.device:
        """Get appropriate device for model execution."""
        return torch.device("cuda" if torch.cuda.is_available() else "cpu")

# ================================
# Content Processing
# ================================

class ContentProcessor:
    """Handles extraction and processing of content from various sources."""
    
    @staticmethod
    def extract_text_from_file(file_path: Union[str, Path]) -> str:
        """
        Extract text content from various file formats.
        
        Args:
            file_path: Path to the file
            
        Returns:
            Extracted text content
            
        Raises:
            ValueError: If file type is unsupported
            Exception: If file processing fails
        """
        file_path = Path(file_path)
        extension = file_path.suffix.lower()
        
        try:
            content = file_path.read_bytes()
            
            if extension == ".pdf":
                return ContentProcessor._extract_pdf_text(content)
            elif extension == ".docx":
                return ContentProcessor._extract_docx_text(file_path)
            elif extension in (".html", ".htm"):
                return ContentProcessor._extract_html_text(content)
            elif extension == ".md":
                return ContentProcessor._extract_markdown_text(content)
            elif extension == ".srt":
                return ContentProcessor._extract_srt_text(content)
            elif extension in (".txt", ".text"):
                return ContentProcessor._extract_plain_text(content)
            else:
                raise ValueError(f"Unsupported file type: {extension}")
                
        except Exception as e:
            logger.error(f"Failed to extract text from {file_path}: {e}")
            raise
    
    @staticmethod
    def _extract_pdf_text(content: bytes) -> str:
        """Extract text from PDF file."""
        with fitz.open(stream=content, filetype="pdf") as doc:
            return "\n".join(page.get_text() for page in doc)
    
    @staticmethod
    def _extract_docx_text(file_path: Path) -> str:
        """Extract text from DOCX file."""
        doc = docx.Document(str(file_path))
        return "\n".join(paragraph.text for paragraph in doc.paragraphs)
    
    @staticmethod
    def _extract_html_text(content: bytes) -> str:
        """Extract text from HTML file."""
        encoding = chardet.detect(content)["encoding"] or "utf-8"
        text = content.decode(encoding, errors="ignore")
        soup = BeautifulSoup(text, "html.parser")
        return soup.get_text()
    
    @staticmethod
    def _extract_markdown_text(content: bytes) -> str:
        """Extract text from Markdown file."""
        encoding = chardet.detect(content)["encoding"] or "utf-8"
        text = content.decode(encoding, errors="ignore")
        html = markdown(text)
        soup = BeautifulSoup(html, "html.parser")
        return soup.get_text()
    
    @staticmethod
    def _extract_srt_text(content: bytes) -> str:
        """Extract text from SRT subtitle file."""
        encoding = chardet.detect(content)["encoding"] or "utf-8"
        text = content.decode(encoding, errors="ignore")
        # Remove timestamp lines
        return re.sub(r"\d+\n\d{2}:\d{2}:\d{2},\d{3} --> .*?\n", "", text)
    
    @staticmethod
    def _extract_plain_text(content: bytes) -> str:
        """Extract text from plain text file."""
        encoding = chardet.detect(content)["encoding"] or "utf-8"
        return content.decode(encoding, errors="ignore")

# ================================
# Translation Service
# ================================

class TranslationService:
    """Core translation service with advanced processing capabilities."""
    
    def __init__(self, model_manager: ModelManager):
        self.model_manager = model_manager
    
    def translate(
        self, 
        text: str, 
        source_lang: Language, 
        target_lang: Language
    ) -> str:
        """
        Translate text from source to target language with automatic chaining.
        
        Args:
            text: Input text to translate
            source_lang: Source language
            target_lang: Target language
            
        Returns:
            Translated text
        """
        if not text.strip():
            return "No input text to translate."
        
        # Direct translation if model exists
        if (source_lang, target_lang) in TRANSLATION_MODELS:
            return self._direct_translate(text, source_lang, target_lang)
        
        # Automatic chaining through English
        return self._chained_translate(text, source_lang, target_lang)
    
    def _direct_translate(
        self, 
        text: str, 
        source_lang: Language, 
        target_lang: Language
    ) -> str:
        """Perform direct translation using available model."""
        pipeline_obj, lang_tag = self.model_manager.get_translation_pipeline(
            source_lang, target_lang
        )
        
        return self._process_text_with_pipeline(text, pipeline_obj, lang_tag)
    
    def _chained_translate(
        self, 
        text: str, 
        source_lang: Language, 
        target_lang: Language
    ) -> str:
        """
        Perform chained translation through English as intermediate language.
        
        Args:
            text: Input text to translate
            source_lang: Source language
            target_lang: Target language
            
        Returns:
            Translated text through chaining
        """
        # First: source_lang -> English
        intermediate_text = self._direct_translate(
            text, source_lang, Language.ENGLISH
        )
        
        # Second: English -> target_lang
        final_text = self._direct_translate(
            intermediate_text, Language.ENGLISH, target_lang
        )
        
        return final_text
    
    def _process_text_with_pipeline(
        self, 
        text: str, 
        pipeline_obj: Any, 
        lang_tag: str
    ) -> str:
        """Process text using translation pipeline."""
        # Process text in paragraphs
        paragraphs = text.splitlines()
        translated_paragraphs = []
        
        with torch.no_grad():
            for paragraph in paragraphs:
                if not paragraph.strip():
                    translated_paragraphs.append("")
                    continue
                    
                # Split into sentences and translate
                sentences = [
                    s.strip() for s in paragraph.split(". ") 
                    if s.strip()
                ]
                
                # Add language tag to each sentence
                formatted_sentences = [
                    f"{lang_tag} {sentence}" 
                    for sentence in sentences
                ]
                
                # Perform translation
                results = pipeline_obj(
                    formatted_sentences,
                    max_length=5000,
                    num_beams=5,
                    early_stopping=True,
                    no_repeat_ngram_size=3,
                    repetition_penalty=1.5,
                    length_penalty=1.2
                )
                
                # Process results
                translated_sentences = [
                    result["translation_text"].capitalize() 
                    for result in results
                ]
                
                translated_paragraphs.append(". ".join(translated_sentences))
        
        return "\n".join(translated_paragraphs)

# ================================
# Audio Processing
# ================================

class AudioProcessor:
    """Handles audio file transcription using Whisper."""
    
    def __init__(self, model_manager: ModelManager):
        self.model_manager = model_manager
    
    def transcribe(self, audio_file_path: str) -> str:
        """
        Transcribe audio file to text.
        
        Args:
            audio_file_path: Path to audio file
            
        Returns:
            Transcribed text
        """
        model = self.model_manager.get_whisper_model()
        result = model.transcribe(audio_file_path)
        return result["text"]

# ================================
# Main Application
# ================================

class TranslationApp:
    """Main application orchestrating all components."""
    
    def __init__(self):
        self.model_manager = ModelManager()
        self.content_processor = ContentProcessor()
        self.translation_service = TranslationService(self.model_manager)
        self.audio_processor = AudioProcessor(self.model_manager)
    
    def process_input(
        self,
        mode: InputMode,
        source_lang: Language,
        text_input: str,
        audio_file: Optional[str],
        file_obj: Optional[gr.FileData]
    ) -> str:
        """
        Process input based on selected mode.
        
        Args:
            mode: Input mode
            source_lang: Source language
            text_input: Text input
            audio_file: Audio file path
            file_obj: Uploaded file object
            
        Returns:
            Processed text content
        """
        if mode == InputMode.TEXT:
            return text_input
            
        elif mode == InputMode.AUDIO:
            if source_lang != Language.ENGLISH:
                raise ValueError("Audio input must be in English.")
            if not audio_file:
                raise ValueError("No audio file provided.")
            return self.audio_processor.transcribe(audio_file)
            
        elif mode == InputMode.FILE:
            if not file_obj:
                raise ValueError("No file uploaded.")
            return self.content_processor.extract_text_from_file(file_obj.name)
            
        return ""
    
    def create_interface(self) -> gr.Blocks:
        """Create and return the Gradio interface."""
        
        with gr.Blocks(
            title="LocaleNLP Translation Service",
            theme=gr.themes.Monochrome()
        ) as interface:
            # Header
            gr.Markdown("""
            # 🌍 LocaleNLP Translation Service
            Translate between English, Wolof, Hausa, and Darija with support for text, audio, and documents.
            """)
            
            # Input controls
            with gr.Row():
                input_mode = gr.Radio(
                    choices=[mode.value for mode in InputMode],
                    label="Input Type",
                    value=InputMode.TEXT.value
                )
                
                input_lang = gr.Dropdown(
                    choices=[lang.value for lang in Language],
                    label="Input Language",
                    value=Language.ENGLISH.value
                )
                
                output_lang = gr.Dropdown(
                    choices=[lang.value for lang in Language],
                    label="Output Language",
                    value=Language.WOLOF.value
                )
            
            # Input components
            input_text = gr.Textbox(
                label="Enter Text",
                lines=8,
                visible=True,
                placeholder="Type or paste your text here..."
            )
            
            audio_input = gr.Audio(
                label="Upload Audio",
                type="filepath",
                visible=False
            )
            
            file_input = gr.File(
                file_types=SUPPORTED_FILE_TYPES,
                label="Upload Document",
                visible=False
            )
            
            # Processing area
            extracted_text = gr.Textbox(
                label="Extracted / Transcribed Text",
                lines=8,
                interactive=False
            )
            
            translate_btn = gr.Button(
                "🔄 Process & Translate",
                variant="secondary"
            )
            
            output_text = gr.Textbox(
                label="Translated Text",
                lines=10,
                interactive=False
            )
            
            # Event handlers
            def update_visibility(mode: str) -> Dict[str, Any]:
                """Update component visibility based on input mode."""
                return {
                    input_text: gr.update(visible=(mode == InputMode.TEXT.value)),
                    audio_input: gr.update(visible=(mode == InputMode.AUDIO.value)),
                    file_input: gr.update(visible=(mode == InputMode.FILE.value)),
                    extracted_text: gr.update(value="", visible=True),
                    output_text: gr.update(value="")
                }
            
            def handle_process(
                mode: str,
                source_lang: str,
                text_input: str,
                audio_file: Optional[str],
                file_obj: Optional[gr.FileData]
            ) -> Tuple[str, str]:
                """Handle initial input processing."""
                try:
                    processed_text = self.process_input(
                        InputMode(mode),
                        Language(source_lang),
                        text_input,
                        audio_file,
                        file_obj
                    )
                    return processed_text, ""
                except Exception as e:
                    logger.error(f"Processing error: {e}")
                    return "", f"❌ Error: {str(e)}"
            
            def handle_translate(
                extracted_text: str,
                source_lang: str,
                target_lang: str
            ) -> str:
                """Handle translation of processed text."""
                if not extracted_text.strip():
                    return "📝 No text to translate."
                try:
                    return self.translation_service.translate(
                        extracted_text,
                        Language(source_lang),
                        Language(target_lang)
                    )
                except Exception as e:
                    logger.error(f"Translation error: {e}")
                    return f"❌ Translation error: {str(e)}"
            
            # Connect events
            input_mode.change(
                fn=update_visibility,
                inputs=input_mode,
                outputs=[input_text, audio_input, file_input, extracted_text, output_text]
            )
            
            translate_btn.click(
                fn=handle_process,
                inputs=[input_mode, input_lang, input_text, audio_input, file_input],
                outputs=[extracted_text, output_text]
            ).then(
                fn=handle_translate,
                inputs=[extracted_text, input_lang, output_lang],
                outputs=output_text
            )
            
            # Custom CSS for black button (applied after interface creation)
            interface.load(lambda: None, None, None, _js="""
            () => {
                const style = document.createElement('style');
                style.textContent = `
                    .gr-button-secondary {
                        background-color: #000000 !important;
                        border-color: #000000 !important;
                        color: white !important;
                    }
                    .gr-button-secondary:hover {
                        background-color: #333333 !important;
                        border-color: #333333 !important;
                    }
                `;
                document.head.appendChild(style);
            }
            """)
        
        return interface

# ================================
# Application Entry Point
# ================================

def main():
    """Main application entry point."""
    try:
        app = TranslationApp()
        interface = app.create_interface()
        interface.launch(
            server_name="0.0.0.0",
            server_port=int(os.getenv("PORT", 7860)),
            share=False
        )
    except Exception as e:
        logger.critical(f"Failed to start application: {e}")
        raise

if __name__ == "__main__":
    main()