use dashmap::DashMap;
use lingua::Language::{
Arabic, Chinese, English, French, German, Italian, Japanese, Korean, Latvian, Lithuanian,
Russian, Spanish,
};
use lingua::{LanguageDetector, LanguageDetectorBuilder};
use ntex::web::types::Query;
use ntex::web::{self, App, HttpResponse, HttpServer, Responder};
use once_cell::sync::Lazy;
use serde::{Deserialize, Serialize};
use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering};
use std::time::{Duration, Instant};
use sysinfo::System;
static TOTAL_REQUESTS: AtomicUsize = AtomicUsize::new(0);
static CACHE_HITS: AtomicUsize = AtomicUsize::new(0);
static TOTAL_CACHE_TIME: AtomicU64 = AtomicU64::new(0);
static TOTAL_DETECTION_TIME: AtomicU64 = AtomicU64::new(0);
static DETECTION_COUNT: AtomicUsize = AtomicUsize::new(0);
static SYSTEM: Lazy<std::sync::Mutex<System>> = Lazy::new(|| {
let mut sys = System::new_all();
sys.refresh_all();
std::sync::Mutex::new(sys)
});
#[derive(Deserialize)]
struct DetectQuery {
text: String,
}
#[derive(Clone)]
struct CacheEntry {
lang_code: String,
timestamp: Instant,
}
#[derive(Serialize)]
struct CpuInfo {
model: String,
usage: f32,
frequency: u64,
cores: usize,
}
#[derive(Serialize)]
struct Stats {
cpu: CpuInfo,
memory_used_mb: u64,
total_memory_mb: u64,
total_requests: usize,
cache_hits: usize,
cache_hit_ratio: f64,
cache_entries: usize,
uptime_secs: u64,
avg_cache_time_micros: u64,
avg_detection_time_micros: u64,
}
static CACHE: Lazy<DashMap<String, CacheEntry>> = Lazy::new(DashMap::new);
static CACHE_DURATION: Duration = Duration::from_secs(43200); // 12 hours
static DETECTOR: Lazy<LanguageDetector> = Lazy::new(|| {
eprintln!("Initializing language detector");
LanguageDetectorBuilder::from_languages(&[
Arabic, Chinese, English, French, German, Italian, Japanese, Korean, Russian, Spanish,
Lithuanian, Latvian,
])
.with_preloaded_language_models()
.build()
});
fn build_response(body: String) -> HttpResponse {
HttpResponse::Ok()
.header("Access-Control-Allow-Origin", "*")
.header("Cache-Control", "max-age=3600")
.header("Access-Control-Allow-Headers", "*")
.body(body)
}
async fn detect_and_respond(text: &str) -> impl Responder {
let start_time = Instant::now();
TOTAL_REQUESTS.fetch_add(1, Ordering::SeqCst);
let now = Instant::now();
CACHE.retain(|_, entry| now.duration_since(entry.timestamp) < CACHE_DURATION);
if let Some(entry) = CACHE.get(text) {
eprintln!("Cache hit for text: {}", text);
CACHE_HITS.fetch_add(1, Ordering::SeqCst);
let cache_time = start_time.elapsed().as_micros() as u64;
TOTAL_CACHE_TIME.fetch_add(cache_time, Ordering::SeqCst);
return build_response(entry.lang_code.clone());
}
eprintln!("Detecting language for text: {}", text);
let detection_start = Instant::now();
let lang_code = DETECTOR
.detect_language_of(text)
.map(|lang| lang.iso_code_639_1().to_string())
.unwrap_or_else(|| "auto".to_string());
let detection_time = detection_start.elapsed().as_micros() as u64;
TOTAL_DETECTION_TIME.fetch_add(detection_time, Ordering::SeqCst);
DETECTION_COUNT.fetch_add(1, Ordering::SeqCst);
CACHE.insert(
text.to_string(),
CacheEntry {
lang_code: lang_code.clone(),
timestamp: now,
},
);
build_response(lang_code)
}
async fn detect_language_handler(body: String) -> impl Responder {
eprintln!("Received POST request");
detect_and_respond(&body).await
}
async fn detect_language_get(query: Query<DetectQuery>) -> impl Responder {
eprintln!("Received GET request");
detect_and_respond(&query.text).await
}
async fn stats_handler() -> impl Responder {
let mut sys = SYSTEM.lock().unwrap();
sys.refresh_all();
let total_requests = TOTAL_REQUESTS.load(Ordering::SeqCst);
let cache_hits = CACHE_HITS.load(Ordering::SeqCst);
let cache_hit_ratio = if total_requests > 0 {
(cache_hits as f64 / total_requests as f64) * 100.0
} else {
0.0
};
let cpu_info = CpuInfo {
model: sys.cpus()[0].brand().to_string(),
usage: sys.global_cpu_usage(),
frequency: sys.cpus()[0].frequency(),
cores: sys.cpus().len(),
};
let avg_cache_time = if cache_hits > 0 {
TOTAL_CACHE_TIME.load(Ordering::SeqCst) / cache_hits as u64
} else {
0
};
let detection_count = DETECTION_COUNT.load(Ordering::SeqCst);
let avg_detection_time = if detection_count > 0 {
TOTAL_DETECTION_TIME.load(Ordering::SeqCst) / detection_count as u64
} else {
0
};
let stats = Stats {
cpu: cpu_info,
memory_used_mb: sys.used_memory() / 1024 / 1024,
total_memory_mb: sys.total_memory() / 1024 / 1024,
total_requests,
cache_hits,
cache_hit_ratio,
cache_entries: CACHE.len(),
uptime_secs: System::uptime(),
avg_cache_time_micros: avg_cache_time,
avg_detection_time_micros: avg_detection_time,
};
HttpResponse::Ok()
.content_type("application/json")
.json(&stats)
}
#[ntex::main]
async fn main() -> std::io::Result<()> {
env_logger::init();
eprintln!("Starting language detection server");
HttpServer::new(|| {
App::new()
.service(
web::resource("/detect")
.route(web::post().to(detect_language_handler))
.route(web::get().to(detect_language_get)),
)
.service(web::resource("/stats").route(web::get().to(stats_handler)))
})
.bind("0.0.0.0:8080")?
.run()
.await
}
use actix_web::{web, App, HttpResponse, HttpServer, Responder};
use cached::proc_macro::cached;
use lingua::Language::{
Arabic, Chinese, English, French, German, Italian, Japanese, Korean, Latvian, Lithuanian,
Russian, Spanish,
};
use lingua::{LanguageDetector, LanguageDetectorBuilder};
use once_cell::sync::Lazy;
use serde::{Deserialize, Serialize};
use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering};
use std::time::{Duration, Instant};
use sysinfo::{CpuExt, System, SystemExt};
// Constants for cache durations and intervals
const CACHE_DURATION: Duration = Duration::from_secs(43200); // 12 hours
const STATS_UPDATE_INTERVAL: Duration = Duration::from_secs(5); // 5 seconds
// Atomic counters for performance metrics
static TOTAL_REQUESTS: AtomicUsize = AtomicUsize::new(0);
static CACHE_HITS: AtomicUsize = AtomicUsize::new(0);
static TOTAL_CACHE_TIME: AtomicU64 = AtomicU64::new(0);
static TOTAL_DETECTION_TIME: AtomicU64 = AtomicU64::new(0);
static DETECTION_COUNT: AtomicUsize = AtomicUsize::new(0);
// Startup time for uptime calculation
static START_TIME: Lazy<Instant> = Lazy::new(Instant::now);
// Initialize the language detector once
static DETECTOR: Lazy<LanguageDetector> = Lazy::new(|| {
println!("Initializing language detector");
LanguageDetectorBuilder::from_languages(&[
Arabic, Chinese, English, French, German, Italian, Japanese, Korean, Russian, Spanish,
Lithuanian, Latvian,
])
.with_preloaded_language_models()
.build()
});
// Cached system statistics to reduce overhead
static SYSTEM_STATS: Lazy<std::sync::Mutex<SystemStats>> =
Lazy::new(|| std::sync::Mutex::new(SystemStats::gather()));
// Data structures for request handling and system stats
#[derive(Deserialize)]
struct DetectQuery {
text: String,
}
#[derive(Serialize, Clone)]
struct CpuInfo {
model: String,
usage: f32,
frequency: u64,
cores: usize,
}
#[derive(Serialize)]
struct Stats {
cpu: CpuInfo,
memory_used_mb: u64,
total_memory_mb: u64,
total_requests: usize,
cache_hits: usize,
cache_hit_ratio: f64,
cache_entries: usize,
uptime_secs: u64,
avg_cache_time_micros: u64,
avg_detection_time_micros: u64,
}
// Structure to hold system statistics
struct SystemStats {
cpu_info: CpuInfo,
memory_used_mb: u64,
total_memory_mb: u64,
uptime_secs: u64,
last_updated: Instant,
}
impl SystemStats {
// Gather system stats
fn gather() -> Self {
let mut sys = System::new_all();
sys.refresh_all();
SystemStats {
cpu_info: CpuInfo {
model: sys.global_cpu_info().brand().to_string(),
usage: sys.global_cpu_info().cpu_usage(),
frequency: sys.global_cpu_info().frequency(),
cores: sys.cpus().len(),
},
memory_used_mb: sys.used_memory() / 1024, // Convert KB to MB
total_memory_mb: sys.total_memory() / 1024,
uptime_secs: sys.uptime(),
last_updated: Instant::now(),
}
}
// Update system stats at defined intervals
fn refresh(&mut self) {
if self.last_updated.elapsed() >= STATS_UPDATE_INTERVAL {
let mut sys = System::new_all();
sys.refresh_all();
self.cpu_info = CpuInfo {
model: sys.global_cpu_info().brand().to_string(),
usage: sys.global_cpu_info().cpu_usage(),
frequency: sys.global_cpu_info().frequency(),
cores: sys.cpus().len(),
};
self.memory_used_mb = sys.used_memory() / 1024;
self.total_memory_mb = sys.total_memory() / 1024;
self.uptime_secs = sys.uptime();
self.last_updated = Instant::now();
}
}
}
// Response builder to maintain consistent headers
fn build_response(body: String) -> HttpResponse {
HttpResponse::Ok()
.append_header(("Access-Control-Allow-Origin", "*"))
.append_header(("Cache-Control", "max-age=3600"))
.append_header(("Access-Control-Allow-Headers", "*"))
.body(body)
}
// Language detection function with caching
#[cached(
name = "LanguageCache",
type = "TimedSizedCache<String, String>",
create = "{ TimedSizedCache::with_size_and_lifespan(10000, CACHE_DURATION.as_secs()) }",
convert = r#"{ text.to_string() }"#
)]
fn detect_language(text: &str) -> String {
DETECTOR
.detect_language_of(text)
.map(|lang| lang.iso_code_639_1().to_string())
.unwrap_or_else(|| "unknown".to_string())
}
// Asynchronous handler for language detection
async fn detect_and_respond(text: &str) -> impl Responder {
let start_time = Instant::now();
TOTAL_REQUESTS.fetch_add(1, Ordering::Relaxed);
// Check the language cache
let lang_code = if let Some(cached_lang) = LanguageCache::cache_get(text) {
// Cache hit
CACHE_HITS.fetch_add(1, Ordering::Relaxed);
let cache_time = start_time.elapsed().as_micros() as u64;
TOTAL_CACHE_TIME.fetch_add(cache_time, Ordering::Relaxed);
cached_lang.clone()
} else {
// Cache miss, perform detection
let detection_start = Instant::now();
let lang_code = detect_language(text);
let detection_time = detection_start.elapsed().as_micros() as u64;
TOTAL_DETECTION_TIME.fetch_add(detection_time, Ordering::Relaxed);
DETECTION_COUNT.fetch_add(1, Ordering::Relaxed);
lang_code
};
build_response(lang_code)
}
// Handler for POST requests
async fn detect_language_post(body: String) -> impl Responder {
detect_and_respond(&body).await
}
// Handler for GET requests
async fn detect_language_get(query: web::Query<DetectQuery>) -> impl Responder {
detect_and_respond(&query.text).await
}
// Handler to return application statistics
async fn stats_handler() -> impl Responder {
let mut system_stats = SYSTEM_STATS.lock().unwrap();
system_stats.refresh();
let total_requests = TOTAL_REQUESTS.load(Ordering::Relaxed);
let cache_hits = CACHE_HITS.load(Ordering::Relaxed);
let cache_hit_ratio = if total_requests > 0 {
(cache_hits as f64 / total_requests as f64) * 100.0
} else {
0.0
};
let avg_cache_time = if cache_hits > 0 {
TOTAL_CACHE_TIME.load(Ordering::Relaxed) / cache_hits as u64
} else {
0
};
let detection_count = DETECTION_COUNT.load(Ordering::Relaxed);
let avg_detection_time = if detection_count > 0 {
TOTAL_DETECTION_TIME.load(Ordering::Relaxed) / detection_count as u64
} else {
0
};
let cache_size = LanguageCache::size();
let stats = Stats {
cpu: system_stats.cpu_info.clone(),
memory_used_mb: system_stats.memory_used_mb,
total_memory_mb: system_stats.total_memory_mb,
total_requests,
cache_hits,
cache_hit_ratio,
cache_entries: cache_size,
uptime_secs: system_stats.uptime_secs,
avg_cache_time_micros: avg_cache_time,
avg_detection_time_micros: avg_detection_time,
};
HttpResponse::Ok()
.content_type("application/json")
.json(&stats)
}
// Main function to start the server
#[actix_web::main]
async fn main() -> std::io::Result<()> {
println!("Starting language detection server");
HttpServer::new(|| {
App::new()
.route("/detect", web::post().to(detect_language_post))
.route("/detect", web::get().to(detect_language_get))
.route("/stats", web::get().to(stats_handler))
})
.workers(num_cpus::get()) // Utilize all available CPU cores
.bind("0.0.0.0:8080")?
.run()
.await
}