File size: 12,670 Bytes
77f086b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1404f54
 
 
ed2152b
1f4e932
ed2152b
dd80ec5
77f086b
 
ed2152b
1404f54
77f086b
 
 
 
 
 
 
 
 
 
 
 
 
 
1404f54
 
77f086b
 
 
 
ed2152b
 
 
 
 
 
 
 
 
 
 
 
 
 
77f086b
ed2152b
 
 
 
 
77f086b
 
 
 
 
 
1404f54
 
 
77f086b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1404f54
77f086b
 
 
8071884
77f086b
 
ed2152b
77f086b
ed2152b
1f4e932
77f086b
1f4e932
 
 
77f086b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ed2152b
77f086b
ed2152b
1404f54
ed2152b
 
 
 
 
 
 
 
1404f54
 
 
 
ed2152b
 
77f086b
1404f54
ed2152b
77f086b
 
 
 
 
 
 
 
 
 
 
 
8071884
77f086b
 
 
 
 
 
8071884
77f086b
 
 
dd80ec5
 
77f086b
dd80ec5
 
1f4e932
9e77063
77f086b
1f4e932
77f086b
1f4e932
ed2152b
 
77f086b
ed2152b
1f4e932
dd80ec5
 
 
77f086b
 
8071884
77f086b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dd80ec5
 
1f4e932
77f086b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1f4e932
 
 
 
 
 
 
 
77f086b
 
1f4e932
 
77f086b
 
 
 
 
1404f54
 
77f086b
1404f54
 
77f086b
1404f54
 
77f086b
 
 
 
 
 
 
 
 
 
 
 
1404f54
 
 
1f4e932
1404f54
 
 
 
1f4e932
1404f54
dd80ec5
77f086b
 
 
 
 
1404f54
77f086b
 
 
 
 
 
1404f54
1f4e932
 
77f086b
 
 
 
 
 
1f4e932
 
 
 
 
 
 
 
ed2152b
1f4e932
 
 
 
 
ed2152b
1f4e932
77f086b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1404f54
77f086b
 
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
"""
Khmer Legal Bridge - Translation API
=====================================

Flask application with COMETKiwi-based confidence scoring.

Features:
- Bidirectional EN↔KM translation using fine-tuned NLLB-200
- Scientific confidence scoring with COMETKiwi
- PDF text extraction
- Privacy-first design (zero retention)

Author: Khmer Legal Bridge Project
License: MIT
"""

from flask import Flask, render_template, request, jsonify
from transformers import AutoModelForSeq2SeqLM, NllbTokenizerFast
import torch
import fitz
import re
import unicodedata
import time
import logging
import os
from sacremoses import MosesPunctNormalizer

# Import confidence scoring module
from confidence_scoring_v2 import (
    TransparencyScorer,
    DEFAULT_LEGAL_GLOSSARY,
    ConfidenceResult
)

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

app = Flask(__name__)

# ============================================================================
# Text Preprocessing
# ============================================================================

mpn = MosesPunctNormalizer(lang="en")
mpn.substitutions = [(re.compile(r), sub) for r, sub in mpn.substitutions]

def get_non_printing_char_replacer(replace_by: str = " "):
    non_printable_map = {
        ord(c): replace_by
        for c in (chr(i) for i in range(0x110000))
        if unicodedata.category(c) in {"C", "Cc", "Cf", "Cs", "Co", "Cn"}
    }
    return lambda line: line.translate(non_printable_map)

replace_nonprint = get_non_printing_char_replacer(" ")

def preprocess_text(text: str) -> str:
    """Clean and normalize text for translation."""
    clean = mpn.normalize(text)
    clean = replace_nonprint(clean)
    clean = unicodedata.normalize("NFKC", clean)
    return clean


# ============================================================================
# Model Loading
# ============================================================================

logger.info("Loading translation model...")
MODEL_ID = "ClaudBarbara/Open_Access_Khmer"
model = AutoModelForSeq2SeqLM.from_pretrained(MODEL_ID)
tokenizer = NllbTokenizerFast.from_pretrained(MODEL_ID)
logger.info("Translation model loaded!")

# Configuration
USE_COMET = os.environ.get("USE_COMET", "true").lower() == "true"
USE_DETAILED_SCORING = os.environ.get("DETAILED_SCORING", "true").lower() == "true"

# Initialize confidence scorer (lazy loading for COMETKiwi)
confidence_scorer = None

def get_confidence_scorer():
    """Lazy initialization of confidence scorer."""
    global confidence_scorer
    if confidence_scorer is None:
        logger.info(f"Initializing confidence scorer (COMETKiwi: {USE_COMET})")
        confidence_scorer = TransparencyScorer(
            translator_func=translate_simple,
            glossary=DEFAULT_LEGAL_GLOSSARY,
            use_comet=USE_COMET,
            use_back_translation=True,
            use_terminology=True
        )
    return confidence_scorer


# ============================================================================
# Translation Functions
# ============================================================================

def segment_text(text: str, src_lang: str) -> list:
    """Segment text into sentences for batch processing."""
    if src_lang == "khm_Khmr":
        # Khmer sentence boundaries
        sentences = re.split(r'(?<=[។៖])\s*', text)
    else:
        # English sentence boundaries
        sentences = re.split(r'(?<=[.!?])\s+', text)
    return [s.strip() for s in sentences if s.strip()]


def translate_simple(text: str, src_lang: str, tgt_lang: str) -> str:
    """
    Simple translation without confidence scoring.
    Used for back-translation verification.
    """
    tokenizer.src_lang = src_lang
    inputs = tokenizer(
        text,
        return_tensors='pt',
        padding=True,
        truncation=True,
        max_length=512
    )
    
    with torch.no_grad():
        outputs = model.generate(
            **inputs,
            forced_bos_token_id=tokenizer.convert_tokens_to_ids(tgt_lang),
            max_new_tokens=int(32 + 3 * inputs.input_ids.shape[1]),
            num_beams=4,
            early_stopping=True
        )
    
    return tokenizer.decode(outputs[0], skip_special_tokens=True)


def translate_batch(texts: list, src_lang: str, tgt_lang: str) -> list:
    """Translate a batch of texts efficiently."""
    if not texts:
        return []
    
    tokenizer.src_lang = src_lang
    inputs = tokenizer(
        texts,
        return_tensors='pt',
        padding=True,
        truncation=True,
        max_length=512
    )
    
    with torch.no_grad():
        outputs = model.generate(
            **inputs,
            forced_bos_token_id=tokenizer.convert_tokens_to_ids(tgt_lang),
            max_new_tokens=int(32 + 3 * inputs.input_ids.shape[1]),
            num_beams=4,
            early_stopping=True
        )
    
    return tokenizer.batch_decode(outputs, skip_special_tokens=True)


def translate_long(
    text: str, 
    src_lang: str, 
    tgt_lang: str, 
    batch_size: int = 8,
    compute_confidence: bool = True
) -> tuple:
    """
    Translate long text with sentence segmentation and confidence scoring.
    
    Args:
        text: Input text
        src_lang: Source language code
        tgt_lang: Target language code
        batch_size: Batch size for processing
        compute_confidence: Whether to compute detailed confidence
    
    Returns:
        Tuple of (translation, metrics_dict)
    """
    start_time = time.time()
    
    # Preprocess
    clean_text = preprocess_text(text)
    sentences = segment_text(clean_text, src_lang)
    
    if not sentences:
        return "", {"error": "No text to translate"}
    
    # Translate in batches
    translated_parts = []
    for i in range(0, len(sentences), batch_size):
        batch = sentences[i:i + batch_size]
        translations = translate_batch(batch, src_lang, tgt_lang)
        translated_parts.extend(translations)
    
    result = " ".join(translated_parts)
    elapsed = time.time() - start_time
    
    # Compute confidence score
    direction = "en2km" if src_lang == "eng_Latn" else "km2en"
    
    if compute_confidence and USE_COMET:
        try:
            scorer = get_confidence_scorer()
            
            # For long texts, sample representative sentences for scoring
            if len(sentences) > 5:
                # Score first, middle, and last sentences
                sample_indices = [0, len(sentences)//2, -1]
                sample_scores = []
                
                for idx in sample_indices:
                    src_sent = sentences[idx]
                    tgt_sent = translated_parts[idx]
                    
                    conf_result = scorer.score(
                        src_sent, tgt_sent, direction,
                        detailed=USE_DETAILED_SCORING
                    )
                    sample_scores.append(conf_result.overall_score)
                
                avg_score = sum(sample_scores) / len(sample_scores)
                min_score = min(sample_scores)
                
                # Use most conservative estimate
                confidence_score = min(avg_score, min_score + 0.1)
                
            else:
                # Score entire translation
                conf_result = scorer.score(
                    clean_text, result, direction,
                    detailed=USE_DETAILED_SCORING
                )
                confidence_score = conf_result.overall_score
            
            # Determine review recommendation
            needs_review = confidence_score < 0.75
            quality_level = (
                "excellent" if confidence_score >= 0.85 else
                "good" if confidence_score >= 0.70 else
                "acceptable" if confidence_score >= 0.55 else
                "low" if confidence_score >= 0.40 else
                "very_low"
            )
            
            metrics = {
                "confidence": round(confidence_score * 100, 1),
                "quality_level": quality_level,
                "needs_review": needs_review,
                "time_seconds": round(elapsed, 2),
                "sentences": len(sentences),
                "method": "comet_kiwi"
            }
            
        except Exception as e:
            logger.error(f"Confidence scoring failed: {e}")
            # Fallback to lightweight scoring
            metrics = compute_lightweight_metrics(
                clean_text, result, direction, elapsed, len(sentences)
            )
    else:
        # Use lightweight scoring
        metrics = compute_lightweight_metrics(
            clean_text, result, direction, elapsed, len(sentences)
        )
    
    return result, metrics


def compute_lightweight_metrics(
    source: str, 
    translation: str, 
    direction: str,
    elapsed: float,
    num_sentences: int
) -> dict:
    """
    Compute lightweight confidence metrics without COMETKiwi.
    """
    scorer = get_confidence_scorer()
    conf_result = scorer.score_fast(source, translation, direction)
    
    return {
        "confidence": round(conf_result.overall_score * 100, 1),
        "quality_level": conf_result.quality_level,
        "needs_review": conf_result.human_review_recommended,
        "time_seconds": round(elapsed, 2),
        "sentences": num_sentences,
        "method": "lightweight"
    }


# ============================================================================
# PDF Extraction
# ============================================================================

def extract_pdf_text(pdf_file) -> str:
    """Extract text from uploaded PDF file."""
    try:
        pdf_bytes = pdf_file.read()
        doc = fitz.open(stream=pdf_bytes, filetype="pdf")
        text = ""
        for page in doc:
            text += page.get_text()
        doc.close()
        return text.strip()
    except Exception as e:
        logger.error(f"PDF extraction failed: {e}")
        return None


# ============================================================================
# API Routes
# ============================================================================

@app.route("/")
def index():
    """Serve the main translation interface."""
    return render_template("index.html")


@app.route("/translate", methods=["POST"])
def translate_endpoint():
    """
    Translation API endpoint.
    
    Request JSON:
        - text: str - Text to translate
        - direction: str - "en-km" or "km-en"
    
    Response JSON:
        - success: bool
        - translation: str
        - metrics: dict with confidence scores
    """
    data = request.json
    text = data.get("text", "")
    direction = data.get("direction", "en-km")
    
    if direction == "en-km":
        src_lang, tgt_lang = "eng_Latn", "khm_Khmr"
    else:
        src_lang, tgt_lang = "khm_Khmr", "eng_Latn"
    
    try:
        result, metrics = translate_long(text, src_lang, tgt_lang)
        return jsonify({
            "success": True, 
            "translation": result, 
            "metrics": metrics
        })
    except Exception as e:
        logger.error(f"Translation failed: {e}")
        return jsonify({
            "success": False, 
            "error": str(e)
        })


@app.route("/upload-pdf", methods=["POST"])
def upload_pdf():
    """
    PDF upload endpoint.
    
    Accepts multipart form with 'file' field.
    Returns extracted text.
    """
    if 'file' not in request.files:
        return jsonify({"success": False, "error": "No file uploaded"})
    
    file = request.files['file']
    if file.filename == '':
        return jsonify({"success": False, "error": "No file selected"})
    
    if not file.filename.lower().endswith('.pdf'):
        return jsonify({"success": False, "error": "Only PDF files supported"})
    
    text = extract_pdf_text(file)
    if text:
        return jsonify({"success": True, "text": text})
    else:
        return jsonify({"success": False, "error": "Could not extract text"})


@app.route("/health", methods=["GET"])
def health_check():
    """Health check endpoint for monitoring."""
    return jsonify({
        "status": "healthy",
        "model": MODEL_ID,
        "comet_enabled": USE_COMET
    })


# ============================================================================
# Main Entry Point
# ============================================================================

if __name__ == "__main__":
    port = int(os.environ.get("PORT", 7860))
    app.run(host="0.0.0.0", port=port)