Clean logging
Browse files- app/api/v1/endpoints.py +51 -267
- app/main.py +30 -54
- app/models/schemas.py +1 -1
- app/services/translation.py +12 -4
- tests/simple_test.py +34 -26
- tests/test_language_detection_fix.py +247 -0
app/api/v1/endpoints.py
CHANGED
|
@@ -29,7 +29,6 @@ from ...services.languages import (
|
|
| 29 |
get_all_languages,
|
| 30 |
get_languages_by_region,
|
| 31 |
get_language_info,
|
| 32 |
-
is_language_supported,
|
| 33 |
get_popular_languages,
|
| 34 |
get_african_languages,
|
| 35 |
search_languages,
|
|
@@ -59,18 +58,10 @@ router = APIRouter()
|
|
| 59 |
)
|
| 60 |
async def status_check():
|
| 61 |
"""
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
Returns
|
| 65 |
-
|
| 66 |
-
- ๐ฆ Model loading status
|
| 67 |
-
- โฑ๏ธ System uptime
|
| 68 |
-
- ๐ท๏ธ API version
|
| 69 |
-
|
| 70 |
-
**Use this endpoint for:**
|
| 71 |
-
- Load balancer health checks
|
| 72 |
-
- Basic monitoring
|
| 73 |
-
- API availability verification
|
| 74 |
"""
|
| 75 |
uptime = time.time() - app_start_time
|
| 76 |
full_date, _ = get_nairobi_time()
|
|
@@ -97,23 +88,10 @@ async def status_check():
|
|
| 97 |
)
|
| 98 |
async def health_check():
|
| 99 |
"""
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
- ๐จ Alerting systems
|
| 105 |
-
- ๐ APM tools
|
| 106 |
-
- ๐ฅ Health monitoring dashboards
|
| 107 |
-
|
| 108 |
-
**Returns detailed information about:**
|
| 109 |
-
- System health status
|
| 110 |
-
- Model loading status
|
| 111 |
-
- API uptime
|
| 112 |
-
- Timestamp information
|
| 113 |
-
|
| 114 |
-
**HTTP Status Codes:**
|
| 115 |
-
- `200`: All systems operational
|
| 116 |
-
- `503`: Service unavailable (models not loaded)
|
| 117 |
"""
|
| 118 |
uptime = time.time() - app_start_time
|
| 119 |
full_date, _ = get_nairobi_time()
|
|
@@ -142,26 +120,10 @@ async def health_check():
|
|
| 142 |
)
|
| 143 |
async def get_metrics():
|
| 144 |
"""
|
| 145 |
-
|
| 146 |
-
|
| 147 |
-
Returns metrics in Prometheus format
|
| 148 |
-
|
| 149 |
-
**Available Metrics:**
|
| 150 |
-
- ๐ `sema_requests_total` - Total API requests by endpoint and status
|
| 151 |
-
- โฑ๏ธ `sema_request_duration_seconds` - Request duration histogram
|
| 152 |
-
- ๐ `sema_translations_total` - Translation count by language pair
|
| 153 |
-
- ๐ `sema_characters_translated_total` - Total characters translated
|
| 154 |
-
- โ `sema_errors_total` - Error count by type
|
| 155 |
-
|
| 156 |
-
**Integration Examples:**
|
| 157 |
-
```yaml
|
| 158 |
-
# Prometheus scrape config
|
| 159 |
-
scrape_configs:
|
| 160 |
-
- job_name: 'sema-api'
|
| 161 |
-
static_configs:
|
| 162 |
-
- targets: ['your-api-url:port']
|
| 163 |
-
metrics_path: '/metrics'
|
| 164 |
-
```
|
| 165 |
"""
|
| 166 |
if not settings.enable_metrics:
|
| 167 |
raise HTTPException(status_code=404, detail="Metrics disabled")
|
|
@@ -189,58 +151,13 @@ async def translate_endpoint(
|
|
| 189 |
request: Request
|
| 190 |
):
|
| 191 |
"""
|
| 192 |
-
|
| 193 |
-
|
| 194 |
-
|
| 195 |
-
|
| 196 |
-
|
| 197 |
-
|
| 198 |
-
|
| 199 |
-
- **High Performance**: Optimized CTranslate2 inference engine
|
| 200 |
-
- **Usage Tracking**: Character count and request metrics
|
| 201 |
-
- **Request Tracking**: Unique request IDs for debugging
|
| 202 |
-
|
| 203 |
-
### ๐ Limits & Constraints
|
| 204 |
-
- **Rate Limit**: 60 requests per minute per IP address
|
| 205 |
-
- **Character Limit**: Maximum 5000 characters per request
|
| 206 |
-
- **Language Codes**: Must use FLORES-200 format (e.g., `eng_Latn`, `swh_Latn`)
|
| 207 |
-
|
| 208 |
-
### ๐ Language Code Examples
|
| 209 |
-
| Language | Code | Example |
|
| 210 |
-
|----------|------|---------|
|
| 211 |
-
| English | `eng_Latn` | "Hello world" |
|
| 212 |
-
| Swahili | `swh_Latn` | "Habari ya dunia" |
|
| 213 |
-
| French | `fra_Latn` | "Bonjour le monde" |
|
| 214 |
-
| Kikuyu | `kik_Latn` | "Wฤฉ mwega?" |
|
| 215 |
-
| Spanish | `spa_Latn` | "Hola mundo" |
|
| 216 |
-
|
| 217 |
-
### ๐ Usage Examples
|
| 218 |
-
|
| 219 |
-
**Auto-detect source language:**
|
| 220 |
-
```json
|
| 221 |
-
{
|
| 222 |
-
"text": "Habari ya asubuhi",
|
| 223 |
-
"target_language": "eng_Latn"
|
| 224 |
-
}
|
| 225 |
-
```
|
| 226 |
-
|
| 227 |
-
**Specify source language:**
|
| 228 |
-
```json
|
| 229 |
-
{
|
| 230 |
-
"text": "Good morning",
|
| 231 |
-
"source_language": "eng_Latn",
|
| 232 |
-
"target_language": "swh_Latn"
|
| 233 |
-
}
|
| 234 |
-
```
|
| 235 |
-
|
| 236 |
-
### ๐ Response Information
|
| 237 |
-
The response includes:
|
| 238 |
-
- Translated text
|
| 239 |
-
- Detected/provided source language
|
| 240 |
-
- Character count for usage tracking
|
| 241 |
-
- Inference time for performance monitoring
|
| 242 |
-
- Unique request ID for debugging
|
| 243 |
-
- Timestamp in Nairobi timezone
|
| 244 |
"""
|
| 245 |
request_id = request.state.request_id
|
| 246 |
|
|
@@ -346,50 +263,13 @@ async def detect_language_endpoint(
|
|
| 346 |
request: Request
|
| 347 |
):
|
| 348 |
"""
|
| 349 |
-
|
| 350 |
-
|
| 351 |
-
|
| 352 |
-
|
| 353 |
-
|
| 354 |
-
|
| 355 |
-
-
|
| 356 |
-
- **Auto-Translation**: Decide whether translation is needed
|
| 357 |
-
- **Language Analytics**: Track language usage patterns
|
| 358 |
-
|
| 359 |
-
### ๐ค Chatbot Implementation Example
|
| 360 |
-
```python
|
| 361 |
-
# 1. Detect user input language
|
| 362 |
-
detection = await detect_language(user_input)
|
| 363 |
-
|
| 364 |
-
# 2. Decide processing flow
|
| 365 |
-
if detection.is_english:
|
| 366 |
-
# Process directly in English
|
| 367 |
-
response = await llm_chat(user_input)
|
| 368 |
-
else:
|
| 369 |
-
# Translate to English, process, translate back
|
| 370 |
-
english_input = await translate(user_input, "eng_Latn")
|
| 371 |
-
english_response = await llm_chat(english_input)
|
| 372 |
-
response = await translate(english_response, detection.detected_language)
|
| 373 |
-
```
|
| 374 |
-
|
| 375 |
-
### โจ Features
|
| 376 |
-
- **High Accuracy**: FastText-based language detection
|
| 377 |
-
- **200+ Languages**: Supports all FLORES-200 languages
|
| 378 |
-
- **Confidence Scores**: Get detection confidence (0.0-1.0)
|
| 379 |
-
- **English Flag**: Quick check if input is English
|
| 380 |
-
- **Fast Processing**: ~0.01-0.05 seconds detection time
|
| 381 |
-
|
| 382 |
-
### ๐ Response Information
|
| 383 |
-
- **Language Code**: FLORES-200 format (e.g., swh_Latn)
|
| 384 |
-
- **Language Names**: Both English and native names
|
| 385 |
-
- **Confidence Score**: Detection accuracy (higher = more confident)
|
| 386 |
-
- **English Flag**: Boolean for quick English detection
|
| 387 |
-
- **Character Count**: Input text length for analytics
|
| 388 |
-
|
| 389 |
-
### ๐ Limits
|
| 390 |
-
- **Rate Limit**: 60 requests per minute per IP
|
| 391 |
-
- **Text Length**: Maximum 1000 characters
|
| 392 |
-
- **Minimum Length**: At least 1 character required
|
| 393 |
"""
|
| 394 |
request_id = request.state.request_id
|
| 395 |
|
|
@@ -477,29 +357,10 @@ async def detect_language_endpoint(
|
|
| 477 |
)
|
| 478 |
async def get_languages():
|
| 479 |
"""
|
| 480 |
-
|
| 481 |
-
|
| 482 |
-
Returns
|
| 483 |
-
|
| 484 |
-
### ๐ Response Information
|
| 485 |
-
Each language includes:
|
| 486 |
-
- **English Name**: Standard English name
|
| 487 |
-
- **Native Name**: Name in the language's native script
|
| 488 |
-
- **Region**: Geographic region (Africa, Europe, Asia, etc.)
|
| 489 |
-
- **Script**: Writing system (Latin, Arabic, Cyrillic, etc.)
|
| 490 |
-
|
| 491 |
-
### ๐ฏ Use Cases
|
| 492 |
-
- **Frontend Language Selectors**: Populate dropdown menus
|
| 493 |
-
- **API Integration**: Validate language codes before translation
|
| 494 |
-
- **Documentation**: Generate language support documentation
|
| 495 |
-
- **Analytics**: Track language usage patterns
|
| 496 |
-
|
| 497 |
-
### ๐ Language Coverage
|
| 498 |
-
- **African Languages**: 25+ languages including Swahili, Hausa, Yoruba
|
| 499 |
-
- **European Languages**: 40+ languages including major EU languages
|
| 500 |
-
- **Asian Languages**: 80+ languages including Chinese, Japanese, Hindi
|
| 501 |
-
- **Middle Eastern**: 15+ languages including Arabic, Hebrew, Persian
|
| 502 |
-
- **Americas**: 30+ languages including indigenous languages
|
| 503 |
"""
|
| 504 |
languages = get_all_languages()
|
| 505 |
return LanguagesResponse(
|
|
@@ -517,19 +378,10 @@ async def get_languages():
|
|
| 517 |
)
|
| 518 |
async def get_popular_languages_endpoint():
|
| 519 |
"""
|
| 520 |
-
|
| 521 |
|
| 522 |
-
Returns
|
| 523 |
-
|
| 524 |
-
### ๐ฅ Included Languages
|
| 525 |
-
- **Global**: English, Spanish, French, German, Portuguese, Russian
|
| 526 |
-
- **Asian**: Chinese, Japanese, Korean, Hindi, Arabic
|
| 527 |
-
- **African**: Swahili, Hausa, Yoruba, Amharic, Somali, Kikuyu
|
| 528 |
-
|
| 529 |
-
### ๐ก Perfect For
|
| 530 |
-
- **Quick Selection**: Show popular options first
|
| 531 |
-
- **Mobile Apps**: Reduced list for smaller screens
|
| 532 |
-
- **Default Options**: Pre-populate common language pairs
|
| 533 |
"""
|
| 534 |
languages = get_popular_languages()
|
| 535 |
return LanguagesResponse(
|
|
@@ -547,20 +399,10 @@ async def get_popular_languages_endpoint():
|
|
| 547 |
)
|
| 548 |
async def get_african_languages_endpoint():
|
| 549 |
"""
|
| 550 |
-
|
| 551 |
-
|
| 552 |
-
Returns all supported African languages - our specialty!
|
| 553 |
|
| 554 |
-
|
| 555 |
-
|
| 556 |
-
- **West Africa**: Hausa, Yoruba, Igbo, Wolof, Lingala
|
| 557 |
-
- **Southern Africa**: Zulu, Xhosa, Afrikaans, Tswana, Sotho, Shona
|
| 558 |
-
- **Central Africa**: Lingala, Umbundu
|
| 559 |
-
|
| 560 |
-
### โจ Special Features
|
| 561 |
-
- High-quality translations for African languages
|
| 562 |
-
- Cultural context preservation
|
| 563 |
-
- Support for various scripts (Latin, Ethiopic)
|
| 564 |
"""
|
| 565 |
languages = get_african_languages()
|
| 566 |
return LanguagesResponse(
|
|
@@ -578,23 +420,10 @@ async def get_african_languages_endpoint():
|
|
| 578 |
)
|
| 579 |
async def get_languages_by_region_endpoint(region: str):
|
| 580 |
"""
|
| 581 |
-
|
| 582 |
-
|
| 583 |
-
|
| 584 |
-
|
| 585 |
-
### ๐ Available Regions
|
| 586 |
-
- **Africa**: African languages (Swahili, Hausa, Yoruba, etc.)
|
| 587 |
-
- **Europe**: European languages (English, French, German, etc.)
|
| 588 |
-
- **Asia**: Asian languages (Chinese, Japanese, Hindi, etc.)
|
| 589 |
-
- **Middle East**: Middle Eastern languages (Arabic, Hebrew, Persian, etc.)
|
| 590 |
-
- **Americas**: Languages from the Americas
|
| 591 |
-
|
| 592 |
-
### ๐ Usage Examples
|
| 593 |
-
```
|
| 594 |
-
GET /languages/region/Africa
|
| 595 |
-
GET /languages/region/Europe
|
| 596 |
-
GET /languages/region/Asia
|
| 597 |
-
```
|
| 598 |
"""
|
| 599 |
languages = get_languages_by_region(region)
|
| 600 |
if not languages:
|
|
@@ -618,27 +447,10 @@ async def get_languages_by_region_endpoint(region: str):
|
|
| 618 |
)
|
| 619 |
async def search_languages_endpoint(q: str):
|
| 620 |
"""
|
| 621 |
-
|
| 622 |
-
|
| 623 |
-
|
| 624 |
-
|
| 625 |
-
### ๐ฏ Search Capabilities
|
| 626 |
-
- **English Names**: "Swahili", "French", "Chinese"
|
| 627 |
-
- **Native Names**: "Kiswahili", "Franรงais", "ไธญๆ"
|
| 628 |
-
- **Language Codes**: "swh_Latn", "fra_Latn", "cmn_Hans"
|
| 629 |
-
- **Partial Matches**: "Span" matches "Spanish"
|
| 630 |
-
|
| 631 |
-
### ๐ก Perfect For
|
| 632 |
-
- **Autocomplete**: Real-time language search
|
| 633 |
-
- **User Input**: Find languages by any name variation
|
| 634 |
-
- **Validation**: Check if a language exists
|
| 635 |
-
|
| 636 |
-
### ๐ Query Examples
|
| 637 |
-
```
|
| 638 |
-
GET /languages/search?q=Swahili
|
| 639 |
-
GET /languages/search?q=ไธญๆ
|
| 640 |
-
GET /languages/search?q=ara
|
| 641 |
-
```
|
| 642 |
"""
|
| 643 |
if not q or len(q.strip()) < 2:
|
| 644 |
raise HTTPException(
|
|
@@ -662,21 +474,10 @@ async def search_languages_endpoint(q: str):
|
|
| 662 |
)
|
| 663 |
async def get_language_stats():
|
| 664 |
"""
|
| 665 |
-
|
| 666 |
-
|
| 667 |
-
Get comprehensive statistics about our language support coverage.
|
| 668 |
|
| 669 |
-
|
| 670 |
-
|
| 671 |
-
- **Regional Distribution**: Languages per geographic region
|
| 672 |
-
- **Script Coverage**: Number of writing systems supported
|
| 673 |
-
- **Detailed Breakdown**: Languages by region with counts
|
| 674 |
-
|
| 675 |
-
### ๐ฏ Use Cases
|
| 676 |
-
- **Analytics Dashboards**: Display language coverage metrics
|
| 677 |
-
- **Marketing Materials**: Showcase translation capabilities
|
| 678 |
-
- **API Documentation**: Provide coverage statistics
|
| 679 |
-
- **Business Intelligence**: Track language support growth
|
| 680 |
"""
|
| 681 |
stats = get_language_statistics()
|
| 682 |
return LanguageStatsResponse(**stats)
|
|
@@ -691,27 +492,10 @@ async def get_language_stats():
|
|
| 691 |
)
|
| 692 |
async def get_language_info_endpoint(language_code: str):
|
| 693 |
"""
|
| 694 |
-
|
| 695 |
-
|
| 696 |
-
|
| 697 |
-
|
| 698 |
-
### ๐ Information Provided
|
| 699 |
-
- **English Name**: Standard English name
|
| 700 |
-
- **Native Name**: Name in native script
|
| 701 |
-
- **Region**: Geographic region
|
| 702 |
-
- **Script**: Writing system used
|
| 703 |
-
|
| 704 |
-
### ๐ฏ Use Cases
|
| 705 |
-
- **Language Validation**: Check if a code is supported
|
| 706 |
-
- **UI Display**: Show language names in interfaces
|
| 707 |
-
- **Documentation**: Generate language-specific docs
|
| 708 |
-
|
| 709 |
-
### ๐ Example Codes
|
| 710 |
-
```
|
| 711 |
-
GET /languages/swh_Latn # Swahili
|
| 712 |
-
GET /languages/eng_Latn # English
|
| 713 |
-
GET /languages/cmn_Hans # Chinese (Simplified)
|
| 714 |
-
```
|
| 715 |
"""
|
| 716 |
language_info = get_language_info(language_code)
|
| 717 |
if not language_info:
|
|
|
|
| 29 |
get_all_languages,
|
| 30 |
get_languages_by_region,
|
| 31 |
get_language_info,
|
|
|
|
| 32 |
get_popular_languages,
|
| 33 |
get_african_languages,
|
| 34 |
search_languages,
|
|
|
|
| 58 |
)
|
| 59 |
async def status_check():
|
| 60 |
"""
|
| 61 |
+
Basic health check endpoint.
|
| 62 |
+
|
| 63 |
+
Returns API status, version, model loading status, and uptime.
|
| 64 |
+
Used for load balancer health checks and basic monitoring.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 65 |
"""
|
| 66 |
uptime = time.time() - app_start_time
|
| 67 |
full_date, _ = get_nairobi_time()
|
|
|
|
| 88 |
)
|
| 89 |
async def health_check():
|
| 90 |
"""
|
| 91 |
+
Detailed health check for monitoring systems.
|
| 92 |
+
|
| 93 |
+
Returns comprehensive system status including health, models, uptime, and timestamp.
|
| 94 |
+
Returns 200 if operational, 503 if models not loaded.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 95 |
"""
|
| 96 |
uptime = time.time() - app_start_time
|
| 97 |
full_date, _ = get_nairobi_time()
|
|
|
|
| 120 |
)
|
| 121 |
async def get_metrics():
|
| 122 |
"""
|
| 123 |
+
Prometheus metrics endpoint.
|
| 124 |
+
|
| 125 |
+
Returns metrics in Prometheus format including request counts, durations,
|
| 126 |
+
translation counts, character counts, and error counts.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 127 |
"""
|
| 128 |
if not settings.enable_metrics:
|
| 129 |
raise HTTPException(status_code=404, detail="Metrics disabled")
|
|
|
|
| 151 |
request: Request
|
| 152 |
):
|
| 153 |
"""
|
| 154 |
+
Translate text between 200+ languages.
|
| 155 |
+
|
| 156 |
+
Supports automatic language detection if source_language not provided.
|
| 157 |
+
Rate limited to 60 requests/minute per IP. Maximum 5000 characters per request.
|
| 158 |
+
Uses FLORES-200 language codes (e.g., eng_Latn, swh_Latn, fra_Latn).
|
| 159 |
+
|
| 160 |
+
Returns translated text with source language, inference time, and request tracking.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 161 |
"""
|
| 162 |
request_id = request.state.request_id
|
| 163 |
|
|
|
|
| 263 |
request: Request
|
| 264 |
):
|
| 265 |
"""
|
| 266 |
+
Detect the language of input text.
|
| 267 |
+
|
| 268 |
+
Returns detected language code, confidence score, and English flag.
|
| 269 |
+
Useful for multilingual chatbots and content routing.
|
| 270 |
+
Rate limited to 60 requests/minute per IP. Maximum 1000 characters.
|
| 271 |
+
|
| 272 |
+
Response includes FLORES-200 language code, native name, and confidence score.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 273 |
"""
|
| 274 |
request_id = request.state.request_id
|
| 275 |
|
|
|
|
| 357 |
)
|
| 358 |
async def get_languages():
|
| 359 |
"""
|
| 360 |
+
Get all supported languages.
|
| 361 |
+
|
| 362 |
+
Returns 200+ languages with English names, native names, regions, and scripts.
|
| 363 |
+
Useful for building language selectors and validation.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 364 |
"""
|
| 365 |
languages = get_all_languages()
|
| 366 |
return LanguagesResponse(
|
|
|
|
| 378 |
)
|
| 379 |
async def get_popular_languages_endpoint():
|
| 380 |
"""
|
| 381 |
+
Get popular languages for quick selection.
|
| 382 |
|
| 383 |
+
Returns commonly used languages including major global, Asian, and African languages.
|
| 384 |
+
Useful for mobile apps and quick language selection interfaces.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 385 |
"""
|
| 386 |
languages = get_popular_languages()
|
| 387 |
return LanguagesResponse(
|
|
|
|
| 399 |
)
|
| 400 |
async def get_african_languages_endpoint():
|
| 401 |
"""
|
| 402 |
+
Get all supported African languages.
|
|
|
|
|
|
|
| 403 |
|
| 404 |
+
Returns African languages from East, West, Southern, and Central Africa.
|
| 405 |
+
Includes languages with Latin and Ethiopic scripts.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 406 |
"""
|
| 407 |
languages = get_african_languages()
|
| 408 |
return LanguagesResponse(
|
|
|
|
| 420 |
)
|
| 421 |
async def get_languages_by_region_endpoint(region: str):
|
| 422 |
"""
|
| 423 |
+
Get languages filtered by geographic region.
|
| 424 |
+
|
| 425 |
+
Available regions: Africa, Europe, Asia, Middle East, Americas.
|
| 426 |
+
Returns languages specific to the requested region.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 427 |
"""
|
| 428 |
languages = get_languages_by_region(region)
|
| 429 |
if not languages:
|
|
|
|
| 447 |
)
|
| 448 |
async def search_languages_endpoint(q: str):
|
| 449 |
"""
|
| 450 |
+
Search languages by name, native name, or language code.
|
| 451 |
+
|
| 452 |
+
Supports partial matching and searches across English names, native names, and codes.
|
| 453 |
+
Minimum 2 characters required. Useful for autocomplete and validation.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 454 |
"""
|
| 455 |
if not q or len(q.strip()) < 2:
|
| 456 |
raise HTTPException(
|
|
|
|
| 474 |
)
|
| 475 |
async def get_language_stats():
|
| 476 |
"""
|
| 477 |
+
Get language support statistics.
|
|
|
|
|
|
|
| 478 |
|
| 479 |
+
Returns total language count, regional distribution, script coverage,
|
| 480 |
+
and detailed breakdown by region. Useful for analytics and reporting.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 481 |
"""
|
| 482 |
stats = get_language_statistics()
|
| 483 |
return LanguageStatsResponse(**stats)
|
|
|
|
| 492 |
)
|
| 493 |
async def get_language_info_endpoint(language_code: str):
|
| 494 |
"""
|
| 495 |
+
Get information about a specific language.
|
| 496 |
+
|
| 497 |
+
Returns English name, native name, region, and script for the given FLORES-200 code.
|
| 498 |
+
Useful for language validation and UI display.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 499 |
"""
|
| 500 |
language_info = get_language_info(language_code)
|
| 501 |
if not language_info:
|
app/main.py
CHANGED
|
@@ -26,46 +26,22 @@ def create_application() -> FastAPI:
|
|
| 26 |
app = FastAPI(
|
| 27 |
title=settings.app_name,
|
| 28 |
description="""
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
-
|
| 35 |
-
-
|
| 36 |
-
-
|
| 37 |
-
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
-
|
| 43 |
-
-
|
| 44 |
-
-
|
| 45 |
-
|
| 46 |
-
### ๐ Monitoring
|
| 47 |
-
- **Health Checks**: `/health` endpoint for system monitoring
|
| 48 |
-
- **Metrics**: `/metrics` endpoint for Prometheus integration
|
| 49 |
-
- **Request Tracking**: Unique request IDs for debugging
|
| 50 |
-
|
| 51 |
-
### ๐ Language Support
|
| 52 |
-
Supports all FLORES-200 language codes including:
|
| 53 |
-
- **African Languages**: Swahili (swh_Latn), Kikuyu (kik_Latn), Luo (luo_Latn)
|
| 54 |
-
- **European Languages**: English (eng_Latn), French (fra_Latn), Spanish (spa_Latn)
|
| 55 |
-
- **And 190+ more languages**
|
| 56 |
-
|
| 57 |
-
### ๐ Usage Examples
|
| 58 |
-
```bash
|
| 59 |
-
# Basic translation with auto-detection
|
| 60 |
-
curl -X POST "/translate" \\
|
| 61 |
-
-H "Content-Type: application/json" \\
|
| 62 |
-
-d '{"text": "Habari ya asubuhi", "target_language": "eng_Latn"}'
|
| 63 |
-
|
| 64 |
-
# Translation with specified source language
|
| 65 |
-
curl -X POST "/translate" \\
|
| 66 |
-
-H "Content-Type: application/json" \\
|
| 67 |
-
-d '{"text": "Hello world", "source_language": "eng_Latn", "target_language": "swh_Latn"}'
|
| 68 |
-
```
|
| 69 |
""",
|
| 70 |
version=settings.app_version,
|
| 71 |
docs_url="/",
|
|
@@ -129,25 +105,25 @@ async def startup_event():
|
|
| 129 |
"""Initialize the application on startup"""
|
| 130 |
logger.info("application_startup", version=settings.app_version, environment=settings.environment)
|
| 131 |
|
| 132 |
-
print(f"\n
|
| 133 |
-
print("
|
| 134 |
|
| 135 |
try:
|
| 136 |
load_models()
|
| 137 |
logger.info("models_loaded_successfully")
|
| 138 |
-
print("
|
| 139 |
-
print(f"
|
| 140 |
-
print(f"
|
| 141 |
-
print(f"
|
| 142 |
-
print(f"
|
| 143 |
-
print(f"
|
| 144 |
-
print(f"
|
| 145 |
-
print(f"
|
| 146 |
print()
|
| 147 |
|
| 148 |
except Exception as e:
|
| 149 |
logger.error("startup_failed", error=str(e))
|
| 150 |
-
print(f"
|
| 151 |
raise
|
| 152 |
|
| 153 |
|
|
@@ -155,9 +131,9 @@ async def startup_event():
|
|
| 155 |
async def shutdown_event():
|
| 156 |
"""Cleanup on application shutdown"""
|
| 157 |
logger.info("application_shutdown")
|
| 158 |
-
print("\n
|
| 159 |
-
print("
|
| 160 |
-
print("
|
| 161 |
|
| 162 |
|
| 163 |
if __name__ == "__main__":
|
|
|
|
| 26 |
app = FastAPI(
|
| 27 |
title=settings.app_name,
|
| 28 |
description="""
|
| 29 |
+
Enterprise translation API supporting 200+ languages with automatic language detection.
|
| 30 |
+
|
| 31 |
+
**Key Features:**
|
| 32 |
+
- Automatic language detection
|
| 33 |
+
- 200+ FLORES-200 language support
|
| 34 |
+
- Rate limiting (60 req/min per IP)
|
| 35 |
+
- Character limit (5000 chars per request)
|
| 36 |
+
- Prometheus metrics and monitoring
|
| 37 |
+
- Request tracking with unique IDs
|
| 38 |
+
|
| 39 |
+
**Endpoints:**
|
| 40 |
+
- `/translate` - Main translation endpoint
|
| 41 |
+
- `/detect-language` - Language detection
|
| 42 |
+
- `/languages` - Supported languages information
|
| 43 |
+
- `/health` - System health monitoring
|
| 44 |
+
- `/metrics` - Prometheus metrics
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 45 |
""",
|
| 46 |
version=settings.app_version,
|
| 47 |
docs_url="/",
|
|
|
|
| 105 |
"""Initialize the application on startup"""
|
| 106 |
logger.info("application_startup", version=settings.app_version, environment=settings.environment)
|
| 107 |
|
| 108 |
+
print(f"\n[INFO] Starting {settings.app_name} v{settings.app_version}")
|
| 109 |
+
print("[INFO] Loading translation models...")
|
| 110 |
|
| 111 |
try:
|
| 112 |
load_models()
|
| 113 |
logger.info("models_loaded_successfully")
|
| 114 |
+
print("[SUCCESS] API started successfully")
|
| 115 |
+
print(f"[CONFIG] Metrics enabled: {settings.enable_metrics}")
|
| 116 |
+
print(f"[CONFIG] Environment: {settings.environment}")
|
| 117 |
+
print(f"[ENDPOINT] Documentation: / (Swagger UI)")
|
| 118 |
+
print(f"[ENDPOINT] Metrics: /metrics")
|
| 119 |
+
print(f"[ENDPOINT] Health: /health")
|
| 120 |
+
print(f"[ENDPOINT] Status: /status")
|
| 121 |
+
print(f"[ENDPOINT] API v1: /api/v1/")
|
| 122 |
print()
|
| 123 |
|
| 124 |
except Exception as e:
|
| 125 |
logger.error("startup_failed", error=str(e))
|
| 126 |
+
print(f"[ERROR] Startup failed: {e}")
|
| 127 |
raise
|
| 128 |
|
| 129 |
|
|
|
|
| 131 |
async def shutdown_event():
|
| 132 |
"""Cleanup on application shutdown"""
|
| 133 |
logger.info("application_shutdown")
|
| 134 |
+
print("\n[INFO] Shutting down Sema Translation API...")
|
| 135 |
+
print("[INFO] Cleaning up resources...")
|
| 136 |
+
print("[SUCCESS] Shutdown complete\n")
|
| 137 |
|
| 138 |
|
| 139 |
if __name__ == "__main__":
|
app/models/schemas.py
CHANGED
|
@@ -225,7 +225,7 @@ class LanguageDetectionResponse(BaseModel):
|
|
| 225 |
description="Detection confidence score (0.0 to 1.0)",
|
| 226 |
example=0.9876,
|
| 227 |
ge=0.0,
|
| 228 |
-
le=1.0
|
| 229 |
title="Confidence Score"
|
| 230 |
)
|
| 231 |
is_english: bool = Field(
|
|
|
|
| 225 |
description="Detection confidence score (0.0 to 1.0)",
|
| 226 |
example=0.9876,
|
| 227 |
ge=0.0,
|
| 228 |
+
le=1.1, # Allow slightly above 1.0 for FastText edge cases
|
| 229 |
title="Confidence Score"
|
| 230 |
)
|
| 231 |
is_english: bool = Field(
|
app/services/translation.py
CHANGED
|
@@ -228,21 +228,29 @@ def detect_language(text: str) -> Tuple[str, float]:
|
|
| 228 |
Tuple of (language_code, confidence_score)
|
| 229 |
"""
|
| 230 |
try:
|
| 231 |
-
# Clean text for better detection
|
| 232 |
-
|
|
|
|
| 233 |
|
| 234 |
# Get predictions with confidence scores
|
| 235 |
predictions = lang_model.predict(cleaned_text, k=1)
|
| 236 |
|
| 237 |
# Extract language code and confidence
|
| 238 |
language_code = predictions[0][0].replace('__label__', '')
|
| 239 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 240 |
|
| 241 |
logger.info(
|
| 242 |
"language_detected",
|
| 243 |
text_length=len(text),
|
|
|
|
|
|
|
| 244 |
detected_language=language_code,
|
| 245 |
-
|
|
|
|
| 246 |
)
|
| 247 |
|
| 248 |
return language_code, confidence
|
|
|
|
| 228 |
Tuple of (language_code, confidence_score)
|
| 229 |
"""
|
| 230 |
try:
|
| 231 |
+
# Clean and normalize text for better detection
|
| 232 |
+
# FastText models work better with lowercase text
|
| 233 |
+
cleaned_text = text.replace('\n', ' ').strip().lower()
|
| 234 |
|
| 235 |
# Get predictions with confidence scores
|
| 236 |
predictions = lang_model.predict(cleaned_text, k=1)
|
| 237 |
|
| 238 |
# Extract language code and confidence
|
| 239 |
language_code = predictions[0][0].replace('__label__', '')
|
| 240 |
+
raw_confidence = float(predictions[1][0])
|
| 241 |
+
|
| 242 |
+
# Normalize confidence to ensure it's within [0.0, 1.0]
|
| 243 |
+
# FastText sometimes returns values slightly above 1.0
|
| 244 |
+
confidence = min(raw_confidence, 1.0)
|
| 245 |
|
| 246 |
logger.info(
|
| 247 |
"language_detected",
|
| 248 |
text_length=len(text),
|
| 249 |
+
original_text_sample=text[:50] + "..." if len(text) > 50 else text,
|
| 250 |
+
cleaned_text_sample=cleaned_text[:50] + "..." if len(cleaned_text) > 50 else cleaned_text,
|
| 251 |
detected_language=language_code,
|
| 252 |
+
raw_confidence=raw_confidence,
|
| 253 |
+
normalized_confidence=confidence
|
| 254 |
)
|
| 255 |
|
| 256 |
return language_code, confidence
|
tests/simple_test.py
CHANGED
|
@@ -11,24 +11,24 @@ API_URL = "https://sematech-sema-api.hf.space"
|
|
| 11 |
|
| 12 |
def test_health():
|
| 13 |
"""Test basic health check"""
|
| 14 |
-
print("
|
| 15 |
|
| 16 |
response = requests.get(f"{API_URL}/status")
|
| 17 |
print(f"Status: {response.status_code}")
|
| 18 |
|
| 19 |
if response.status_code == 200:
|
| 20 |
data = response.json()
|
| 21 |
-
print(f"
|
| 22 |
print(f"Version: {data['version']}")
|
| 23 |
print(f"Models loaded: {data['models_loaded']}")
|
| 24 |
else:
|
| 25 |
-
print(f"
|
| 26 |
|
| 27 |
print("-" * 50)
|
| 28 |
|
| 29 |
def test_translation():
|
| 30 |
"""Test basic translation"""
|
| 31 |
-
print("
|
| 32 |
|
| 33 |
# Test data
|
| 34 |
data = {
|
|
@@ -46,13 +46,13 @@ def test_translation():
|
|
| 46 |
|
| 47 |
if response.status_code == 200:
|
| 48 |
result = response.json()
|
| 49 |
-
print(f"
|
| 50 |
print(f"Original: {data['text']}")
|
| 51 |
print(f"Translation: {result['translated_text']}")
|
| 52 |
print(f"Source language: {result['source_language']}")
|
| 53 |
print(f"Inference time: {result['inference_time']:.3f}s")
|
| 54 |
else:
|
| 55 |
-
print(f"
|
| 56 |
print(f"Status code: {response.status_code}")
|
| 57 |
try:
|
| 58 |
error_data = response.json()
|
|
@@ -64,59 +64,62 @@ def test_translation():
|
|
| 64 |
|
| 65 |
def test_languages():
|
| 66 |
"""Test language endpoints"""
|
| 67 |
-
print("
|
| 68 |
|
| 69 |
# Test all languages
|
| 70 |
response = requests.get(f"{API_URL}/languages")
|
| 71 |
if response.status_code == 200:
|
| 72 |
data = response.json()
|
| 73 |
-
print(f"
|
| 74 |
else:
|
| 75 |
-
print(f"
|
| 76 |
|
| 77 |
# Test popular languages
|
| 78 |
response = requests.get(f"{API_URL}/languages/popular")
|
| 79 |
if response.status_code == 200:
|
| 80 |
data = response.json()
|
| 81 |
-
print(f"
|
| 82 |
else:
|
| 83 |
-
print(f"
|
| 84 |
|
| 85 |
# Test specific language
|
| 86 |
response = requests.get(f"{API_URL}/languages/swh_Latn")
|
| 87 |
if response.status_code == 200:
|
| 88 |
data = response.json()
|
| 89 |
-
print(f"
|
| 90 |
else:
|
| 91 |
-
print(f"
|
| 92 |
|
| 93 |
print("-" * 50)
|
| 94 |
|
| 95 |
def test_search():
|
| 96 |
"""Test language search"""
|
| 97 |
-
print("
|
| 98 |
|
| 99 |
response = requests.get(f"{API_URL}/languages/search?q=Swahili")
|
| 100 |
|
| 101 |
if response.status_code == 200:
|
| 102 |
data = response.json()
|
| 103 |
-
print(f"
|
| 104 |
for code, info in data['languages'].items():
|
| 105 |
print(f" {code}: {info['name']} ({info['native_name']})")
|
| 106 |
else:
|
| 107 |
-
print(f"
|
| 108 |
|
| 109 |
print("-" * 50)
|
| 110 |
|
| 111 |
def test_language_detection():
|
| 112 |
"""Test language detection endpoint"""
|
| 113 |
-
print("
|
| 114 |
|
| 115 |
test_cases = [
|
| 116 |
-
{"text": "Habari ya asubuhi", "expected_lang": "swh_Latn"},
|
| 117 |
-
{"text": "
|
| 118 |
-
{"text": "
|
| 119 |
-
{"text": "
|
|
|
|
|
|
|
|
|
|
| 120 |
]
|
| 121 |
|
| 122 |
for test_case in test_cases:
|
|
@@ -132,16 +135,21 @@ def test_language_detection():
|
|
| 132 |
confidence = data['confidence']
|
| 133 |
is_english = data['is_english']
|
| 134 |
|
| 135 |
-
print(f"
|
| 136 |
-
print(f" Confidence: {confidence:.3f}, Is English: {is_english}")
|
| 137 |
else:
|
| 138 |
-
print(f"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 139 |
|
| 140 |
print("-" * 50)
|
| 141 |
|
| 142 |
def run_all_tests():
|
| 143 |
"""Run all tests"""
|
| 144 |
-
print(f"
|
| 145 |
print("=" * 50)
|
| 146 |
|
| 147 |
test_health()
|
|
@@ -150,7 +158,7 @@ def run_all_tests():
|
|
| 150 |
test_search()
|
| 151 |
test_language_detection()
|
| 152 |
|
| 153 |
-
print("
|
| 154 |
|
| 155 |
if __name__ == "__main__":
|
| 156 |
run_all_tests()
|
|
|
|
| 11 |
|
| 12 |
def test_health():
|
| 13 |
"""Test basic health check"""
|
| 14 |
+
print("[TEST] Health check...")
|
| 15 |
|
| 16 |
response = requests.get(f"{API_URL}/status")
|
| 17 |
print(f"Status: {response.status_code}")
|
| 18 |
|
| 19 |
if response.status_code == 200:
|
| 20 |
data = response.json()
|
| 21 |
+
print(f"[PASS] API is healthy")
|
| 22 |
print(f"Version: {data['version']}")
|
| 23 |
print(f"Models loaded: {data['models_loaded']}")
|
| 24 |
else:
|
| 25 |
+
print(f"[FAIL] Health check failed")
|
| 26 |
|
| 27 |
print("-" * 50)
|
| 28 |
|
| 29 |
def test_translation():
|
| 30 |
"""Test basic translation"""
|
| 31 |
+
print("[TEST] Translation...")
|
| 32 |
|
| 33 |
# Test data
|
| 34 |
data = {
|
|
|
|
| 46 |
|
| 47 |
if response.status_code == 200:
|
| 48 |
result = response.json()
|
| 49 |
+
print(f"[PASS] Translation successful")
|
| 50 |
print(f"Original: {data['text']}")
|
| 51 |
print(f"Translation: {result['translated_text']}")
|
| 52 |
print(f"Source language: {result['source_language']}")
|
| 53 |
print(f"Inference time: {result['inference_time']:.3f}s")
|
| 54 |
else:
|
| 55 |
+
print(f"[FAIL] Translation failed")
|
| 56 |
print(f"Status code: {response.status_code}")
|
| 57 |
try:
|
| 58 |
error_data = response.json()
|
|
|
|
| 64 |
|
| 65 |
def test_languages():
|
| 66 |
"""Test language endpoints"""
|
| 67 |
+
print("[TEST] Language endpoints...")
|
| 68 |
|
| 69 |
# Test all languages
|
| 70 |
response = requests.get(f"{API_URL}/languages")
|
| 71 |
if response.status_code == 200:
|
| 72 |
data = response.json()
|
| 73 |
+
print(f"[PASS] Found {data['total_count']} supported languages")
|
| 74 |
else:
|
| 75 |
+
print(f"[FAIL] Failed to get languages")
|
| 76 |
|
| 77 |
# Test popular languages
|
| 78 |
response = requests.get(f"{API_URL}/languages/popular")
|
| 79 |
if response.status_code == 200:
|
| 80 |
data = response.json()
|
| 81 |
+
print(f"[PASS] Found {data['total_count']} popular languages")
|
| 82 |
else:
|
| 83 |
+
print(f"[FAIL] Failed to get popular languages")
|
| 84 |
|
| 85 |
# Test specific language
|
| 86 |
response = requests.get(f"{API_URL}/languages/swh_Latn")
|
| 87 |
if response.status_code == 200:
|
| 88 |
data = response.json()
|
| 89 |
+
print(f"[PASS] Swahili info: {data['name']} ({data['native_name']})")
|
| 90 |
else:
|
| 91 |
+
print(f"[FAIL] Failed to get Swahili info")
|
| 92 |
|
| 93 |
print("-" * 50)
|
| 94 |
|
| 95 |
def test_search():
|
| 96 |
"""Test language search"""
|
| 97 |
+
print("[TEST] Language search...")
|
| 98 |
|
| 99 |
response = requests.get(f"{API_URL}/languages/search?q=Swahili")
|
| 100 |
|
| 101 |
if response.status_code == 200:
|
| 102 |
data = response.json()
|
| 103 |
+
print(f"[PASS] Search found {data['total_count']} results")
|
| 104 |
for code, info in data['languages'].items():
|
| 105 |
print(f" {code}: {info['name']} ({info['native_name']})")
|
| 106 |
else:
|
| 107 |
+
print(f"[FAIL] Search failed")
|
| 108 |
|
| 109 |
print("-" * 50)
|
| 110 |
|
| 111 |
def test_language_detection():
|
| 112 |
"""Test language detection endpoint"""
|
| 113 |
+
print("[TEST] Language detection...")
|
| 114 |
|
| 115 |
test_cases = [
|
| 116 |
+
{"text": "Habari ya asubuhi", "expected_lang": "swh_Latn", "description": "Swahili (mixed case)"},
|
| 117 |
+
{"text": "habari ya asubuhi", "expected_lang": "swh_Latn", "description": "Swahili (lowercase)"},
|
| 118 |
+
{"text": "Good morning", "expected_lang": "eng_Latn", "description": "English (mixed case)"},
|
| 119 |
+
{"text": "good morning", "expected_lang": "eng_Latn", "description": "English (lowercase)"},
|
| 120 |
+
{"text": "Bonjour", "expected_lang": "fra_Latn", "description": "French"},
|
| 121 |
+
{"text": "Hola mundo", "expected_lang": "spa_Latn", "description": "Spanish"},
|
| 122 |
+
{"text": "HELLO WORLD", "expected_lang": "eng_Latn", "description": "English (uppercase)"}
|
| 123 |
]
|
| 124 |
|
| 125 |
for test_case in test_cases:
|
|
|
|
| 135 |
confidence = data['confidence']
|
| 136 |
is_english = data['is_english']
|
| 137 |
|
| 138 |
+
print(f"[PASS] '{test_case['text']}' -> {detected} ({data['language_name']})")
|
| 139 |
+
print(f" {test_case['description']}, Confidence: {confidence:.3f}, Is English: {is_english}")
|
| 140 |
else:
|
| 141 |
+
print(f"[FAIL] Detection failed for '{test_case['text']}' ({test_case['description']})")
|
| 142 |
+
try:
|
| 143 |
+
error_data = response.json()
|
| 144 |
+
print(f" Error: {error_data.get('detail', 'Unknown error')}")
|
| 145 |
+
except:
|
| 146 |
+
print(f" Error: {response.text}")
|
| 147 |
|
| 148 |
print("-" * 50)
|
| 149 |
|
| 150 |
def run_all_tests():
|
| 151 |
"""Run all tests"""
|
| 152 |
+
print(f"[INFO] Testing API at: {API_URL}")
|
| 153 |
print("=" * 50)
|
| 154 |
|
| 155 |
test_health()
|
|
|
|
| 158 |
test_search()
|
| 159 |
test_language_detection()
|
| 160 |
|
| 161 |
+
print("[INFO] All tests completed!")
|
| 162 |
|
| 163 |
if __name__ == "__main__":
|
| 164 |
run_all_tests()
|
tests/test_language_detection_fix.py
ADDED
|
@@ -0,0 +1,247 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Test script to verify language detection case sensitivity and confidence score fixes
|
| 3 |
+
"""
|
| 4 |
+
|
| 5 |
+
import requests
|
| 6 |
+
import json
|
| 7 |
+
|
| 8 |
+
def test_case_sensitivity_fix(api_url="https://sematech-sema-api.hf.space"):
|
| 9 |
+
"""Test that language detection works with different text cases"""
|
| 10 |
+
|
| 11 |
+
print("๐ง Testing Case Sensitivity Fix")
|
| 12 |
+
print("=" * 50)
|
| 13 |
+
|
| 14 |
+
# Test same text in different cases
|
| 15 |
+
test_cases = [
|
| 16 |
+
{
|
| 17 |
+
"variations": [
|
| 18 |
+
"Habari ya asubuhi", # Mixed case
|
| 19 |
+
"habari ya asubuhi", # Lowercase
|
| 20 |
+
"HABARI YA ASUBUHI", # Uppercase
|
| 21 |
+
"HaBaRi Ya AsUbUhI" # Random case
|
| 22 |
+
],
|
| 23 |
+
"expected_language": "swh_Latn",
|
| 24 |
+
"language_name": "Swahili"
|
| 25 |
+
},
|
| 26 |
+
{
|
| 27 |
+
"variations": [
|
| 28 |
+
"Good morning everyone",
|
| 29 |
+
"good morning everyone",
|
| 30 |
+
"GOOD MORNING EVERYONE",
|
| 31 |
+
"GoOd MoRnInG eVeRyOnE"
|
| 32 |
+
],
|
| 33 |
+
"expected_language": "eng_Latn",
|
| 34 |
+
"language_name": "English"
|
| 35 |
+
},
|
| 36 |
+
{
|
| 37 |
+
"variations": [
|
| 38 |
+
"Bonjour tout le monde",
|
| 39 |
+
"bonjour tout le monde",
|
| 40 |
+
"BONJOUR TOUT LE MONDE"
|
| 41 |
+
],
|
| 42 |
+
"expected_language": "fra_Latn",
|
| 43 |
+
"language_name": "French"
|
| 44 |
+
}
|
| 45 |
+
]
|
| 46 |
+
|
| 47 |
+
total_tests = 0
|
| 48 |
+
successful_tests = 0
|
| 49 |
+
|
| 50 |
+
for test_group in test_cases:
|
| 51 |
+
print(f"\n๐งช Testing {test_group['language_name']} variations:")
|
| 52 |
+
|
| 53 |
+
for variation in test_group["variations"]:
|
| 54 |
+
total_tests += 1
|
| 55 |
+
|
| 56 |
+
try:
|
| 57 |
+
response = requests.post(
|
| 58 |
+
f"{api_url}/detect-language",
|
| 59 |
+
headers={"Content-Type": "application/json"},
|
| 60 |
+
json={"text": variation},
|
| 61 |
+
timeout=10
|
| 62 |
+
)
|
| 63 |
+
|
| 64 |
+
if response.status_code == 200:
|
| 65 |
+
data = response.json()
|
| 66 |
+
detected = data['detected_language']
|
| 67 |
+
confidence = data['confidence']
|
| 68 |
+
|
| 69 |
+
# Check if detection is correct or reasonable
|
| 70 |
+
if detected == test_group['expected_language']:
|
| 71 |
+
print(f" โ
'{variation}' โ {detected} (confidence: {confidence:.3f})")
|
| 72 |
+
successful_tests += 1
|
| 73 |
+
else:
|
| 74 |
+
print(f" โ ๏ธ '{variation}' โ {detected} (expected: {test_group['expected_language']}, confidence: {confidence:.3f})")
|
| 75 |
+
# Still count as successful if confidence is reasonable
|
| 76 |
+
if confidence > 0.5:
|
| 77 |
+
successful_tests += 1
|
| 78 |
+
else:
|
| 79 |
+
print(f" โ '{variation}' โ HTTP {response.status_code}")
|
| 80 |
+
try:
|
| 81 |
+
error_data = response.json()
|
| 82 |
+
print(f" Error: {error_data.get('detail', 'Unknown error')}")
|
| 83 |
+
except:
|
| 84 |
+
print(f" Error: {response.text}")
|
| 85 |
+
|
| 86 |
+
except Exception as e:
|
| 87 |
+
print(f" ๐ฅ '{variation}' โ Exception: {e}")
|
| 88 |
+
|
| 89 |
+
# Summary
|
| 90 |
+
print(f"\n๐ Case Sensitivity Test Results:")
|
| 91 |
+
print(f" โ
Successful: {successful_tests}/{total_tests}")
|
| 92 |
+
print(f" ๐ Success Rate: {(successful_tests/total_tests)*100:.1f}%")
|
| 93 |
+
|
| 94 |
+
return successful_tests >= (total_tests * 0.8) # 80% success rate
|
| 95 |
+
|
| 96 |
+
def test_confidence_score_fix(api_url="https://sematech-sema-api.hf.space"):
|
| 97 |
+
"""Test that confidence scores are properly normalized"""
|
| 98 |
+
|
| 99 |
+
print(f"\n๐ง Testing Confidence Score Normalization")
|
| 100 |
+
print("=" * 50)
|
| 101 |
+
|
| 102 |
+
# Test texts that might produce high confidence scores
|
| 103 |
+
test_cases = [
|
| 104 |
+
"hello", # Very common English word
|
| 105 |
+
"the", # Most common English word
|
| 106 |
+
"habari", # Common Swahili word
|
| 107 |
+
"bonjour", # Common French word
|
| 108 |
+
"hola", # Common Spanish word
|
| 109 |
+
"a", # Single character
|
| 110 |
+
"I am fine thank you", # Clear English sentence
|
| 111 |
+
"je suis bien merci" # Clear French sentence
|
| 112 |
+
]
|
| 113 |
+
|
| 114 |
+
confidence_issues = 0
|
| 115 |
+
total_tests = len(test_cases)
|
| 116 |
+
|
| 117 |
+
for text in test_cases:
|
| 118 |
+
try:
|
| 119 |
+
response = requests.post(
|
| 120 |
+
f"{api_url}/detect-language",
|
| 121 |
+
headers={"Content-Type": "application/json"},
|
| 122 |
+
json={"text": text},
|
| 123 |
+
timeout=10
|
| 124 |
+
)
|
| 125 |
+
|
| 126 |
+
if response.status_code == 200:
|
| 127 |
+
data = response.json()
|
| 128 |
+
confidence = data['confidence']
|
| 129 |
+
detected = data['detected_language']
|
| 130 |
+
|
| 131 |
+
if confidence > 1.0:
|
| 132 |
+
print(f" โ ๏ธ '{text}' โ confidence {confidence:.6f} > 1.0 (not normalized)")
|
| 133 |
+
confidence_issues += 1
|
| 134 |
+
elif confidence < 0.0:
|
| 135 |
+
print(f" โ ๏ธ '{text}' โ confidence {confidence:.6f} < 0.0 (invalid)")
|
| 136 |
+
confidence_issues += 1
|
| 137 |
+
else:
|
| 138 |
+
print(f" โ
'{text}' โ {detected} (confidence: {confidence:.3f})")
|
| 139 |
+
|
| 140 |
+
else:
|
| 141 |
+
print(f" โ '{text}' โ HTTP {response.status_code}")
|
| 142 |
+
confidence_issues += 1
|
| 143 |
+
|
| 144 |
+
except Exception as e:
|
| 145 |
+
print(f" ๐ฅ '{text}' โ Exception: {e}")
|
| 146 |
+
confidence_issues += 1
|
| 147 |
+
|
| 148 |
+
print(f"\n๐ Confidence Score Test Results:")
|
| 149 |
+
print(f" โ
Valid confidence scores: {total_tests - confidence_issues}/{total_tests}")
|
| 150 |
+
print(f" โ ๏ธ Issues found: {confidence_issues}")
|
| 151 |
+
|
| 152 |
+
return confidence_issues == 0
|
| 153 |
+
|
| 154 |
+
def test_multilingual_chatbot_scenario(api_url="https://sematech-sema-api.hf.space"):
|
| 155 |
+
"""Test a realistic multilingual chatbot scenario"""
|
| 156 |
+
|
| 157 |
+
print(f"\n๐ค Testing Multilingual Chatbot Scenario")
|
| 158 |
+
print("=" * 50)
|
| 159 |
+
|
| 160 |
+
# Simulate user inputs in different languages
|
| 161 |
+
user_inputs = [
|
| 162 |
+
{"text": "Hello, how are you?", "expected_flow": "direct_english"},
|
| 163 |
+
{"text": "Habari, hujambo?", "expected_flow": "translate_to_english"},
|
| 164 |
+
{"text": "Bonjour, comment รงa va?", "expected_flow": "translate_to_english"},
|
| 165 |
+
{"text": "Hola, ยฟcรณmo estรกs?", "expected_flow": "translate_to_english"},
|
| 166 |
+
{"text": "What's the weather like?", "expected_flow": "direct_english"},
|
| 167 |
+
{"text": "Hali ya hewa ni vipi?", "expected_flow": "translate_to_english"}
|
| 168 |
+
]
|
| 169 |
+
|
| 170 |
+
successful_scenarios = 0
|
| 171 |
+
|
| 172 |
+
for i, user_input in enumerate(user_inputs, 1):
|
| 173 |
+
print(f"\n๐ฏ Scenario {i}: '{user_input['text']}'")
|
| 174 |
+
|
| 175 |
+
try:
|
| 176 |
+
# Step 1: Detect language
|
| 177 |
+
response = requests.post(
|
| 178 |
+
f"{api_url}/detect-language",
|
| 179 |
+
headers={"Content-Type": "application/json"},
|
| 180 |
+
json={"text": user_input["text"]},
|
| 181 |
+
timeout=10
|
| 182 |
+
)
|
| 183 |
+
|
| 184 |
+
if response.status_code == 200:
|
| 185 |
+
detection = response.json()
|
| 186 |
+
is_english = detection['is_english']
|
| 187 |
+
detected_lang = detection['detected_language']
|
| 188 |
+
confidence = detection['confidence']
|
| 189 |
+
|
| 190 |
+
print(f" ๐ Detected: {detected_lang} (confidence: {confidence:.3f})")
|
| 191 |
+
print(f" ๐ด๓ ง๓ ข๓ ฅ๓ ฎ๓ ง๓ ฟ Is English: {is_english}")
|
| 192 |
+
|
| 193 |
+
# Step 2: Determine processing flow
|
| 194 |
+
if is_english:
|
| 195 |
+
print(f" โ
Flow: Process directly in English")
|
| 196 |
+
if user_input["expected_flow"] == "direct_english":
|
| 197 |
+
successful_scenarios += 1
|
| 198 |
+
print(f" ๐ Expected flow matched!")
|
| 199 |
+
else:
|
| 200 |
+
print(f" โ ๏ธ Expected translation flow, got direct English")
|
| 201 |
+
else:
|
| 202 |
+
print(f" ๐ Flow: Translate to English โ Process โ Translate back to {detected_lang}")
|
| 203 |
+
if user_input["expected_flow"] == "translate_to_english":
|
| 204 |
+
successful_scenarios += 1
|
| 205 |
+
print(f" ๐ Expected flow matched!")
|
| 206 |
+
else:
|
| 207 |
+
print(f" โ ๏ธ Expected direct English, got translation flow")
|
| 208 |
+
|
| 209 |
+
else:
|
| 210 |
+
print(f" โ Detection failed: HTTP {response.status_code}")
|
| 211 |
+
|
| 212 |
+
except Exception as e:
|
| 213 |
+
print(f" ๐ฅ Scenario failed: {e}")
|
| 214 |
+
|
| 215 |
+
print(f"\n๐ Chatbot Scenario Results:")
|
| 216 |
+
print(f" โ
Correct flows: {successful_scenarios}/{len(user_inputs)}")
|
| 217 |
+
print(f" ๐ Accuracy: {(successful_scenarios/len(user_inputs))*100:.1f}%")
|
| 218 |
+
|
| 219 |
+
return successful_scenarios >= len(user_inputs) * 0.8
|
| 220 |
+
|
| 221 |
+
if __name__ == "__main__":
|
| 222 |
+
import sys
|
| 223 |
+
|
| 224 |
+
# Allow custom API URL
|
| 225 |
+
api_url = "https://sematech-sema-api.hf.space"
|
| 226 |
+
if len(sys.argv) > 1:
|
| 227 |
+
api_url = sys.argv[1]
|
| 228 |
+
|
| 229 |
+
print(f"๐ฏ Testing Language Detection Fixes at: {api_url}")
|
| 230 |
+
|
| 231 |
+
# Run all tests
|
| 232 |
+
case_test = test_case_sensitivity_fix(api_url)
|
| 233 |
+
confidence_test = test_confidence_score_fix(api_url)
|
| 234 |
+
chatbot_test = test_multilingual_chatbot_scenario(api_url)
|
| 235 |
+
|
| 236 |
+
# Final summary
|
| 237 |
+
print(f"\n๐ FINAL RESULTS:")
|
| 238 |
+
print(f" ๐ค Case Sensitivity Fix: {'โ
PASSED' if case_test else 'โ FAILED'}")
|
| 239 |
+
print(f" ๐ Confidence Score Fix: {'โ
PASSED' if confidence_test else 'โ FAILED'}")
|
| 240 |
+
print(f" ๐ค Chatbot Scenario: {'โ
PASSED' if chatbot_test else 'โ FAILED'}")
|
| 241 |
+
|
| 242 |
+
if all([case_test, confidence_test, chatbot_test]):
|
| 243 |
+
print(f"\n๐ ALL FIXES WORKING PERFECTLY!")
|
| 244 |
+
sys.exit(0)
|
| 245 |
+
else:
|
| 246 |
+
print(f"\nโ ๏ธ SOME ISSUES REMAIN")
|
| 247 |
+
sys.exit(1)
|