fix NAM model loading
This commit is contained in:
+28
-17
@@ -1,14 +1,13 @@
|
||||
use std::path::Path;
|
||||
|
||||
#[cfg(windows)]
|
||||
type WChar = u16;
|
||||
#[cfg(not(windows))]
|
||||
type WChar = u32;
|
||||
|
||||
#[allow(dead_code)]
|
||||
mod ffi {
|
||||
use super::WChar;
|
||||
use std::os::raw::{c_float, c_int};
|
||||
use std::os::raw::{c_char, c_float, c_int};
|
||||
|
||||
#[cfg(windows)]
|
||||
type PathChar = u16; // wchar_t on Windows
|
||||
#[cfg(not(windows))]
|
||||
type PathChar = c_char; // char on Linux/macOS
|
||||
|
||||
#[repr(C)]
|
||||
pub struct NeuralModel {
|
||||
@@ -16,7 +15,7 @@ mod ffi {
|
||||
}
|
||||
|
||||
unsafe extern "C" {
|
||||
pub fn CreateModelFromFile(model_path: *const WChar) -> *mut NeuralModel;
|
||||
pub fn CreateModelFromFile(model_path: *const PathChar) -> *mut NeuralModel;
|
||||
pub fn DeleteModel(model: *mut NeuralModel);
|
||||
|
||||
pub fn SetLSTMLoadMode(load_mode: c_int);
|
||||
@@ -58,24 +57,36 @@ pub struct NamModel {
|
||||
}
|
||||
|
||||
impl NamModel {
|
||||
/// Load a model from in-memory bytes by writing to a temp file first.
|
||||
/// The NAM C API only supports file-based loading.
|
||||
pub fn from_bytes(name: &str, data: &[u8]) -> Result<Self, NamError> {
|
||||
let dir = std::env::temp_dir().join("lightningbeam-nam");
|
||||
eprintln!("[NAM] from_bytes: name={}, data_len={}, temp_dir={}", name, data.len(), dir.display());
|
||||
std::fs::create_dir_all(&dir)
|
||||
.map_err(|e| NamError::ModelLoadFailed(format!("create_dir_all failed: {}", e)))?;
|
||||
let file_path = dir.join(name);
|
||||
std::fs::write(&file_path, data)
|
||||
.map_err(|e| NamError::ModelLoadFailed(format!("write failed: {}", e)))?;
|
||||
eprintln!("[NAM] Wrote {} bytes to {}", data.len(), file_path.display());
|
||||
Self::from_file(&file_path)
|
||||
}
|
||||
|
||||
pub fn from_file(path: &Path) -> Result<Self, NamError> {
|
||||
let wide: Vec<WChar> = {
|
||||
let ptr = unsafe {
|
||||
#[cfg(windows)]
|
||||
{
|
||||
use std::os::windows::ffi::OsStrExt;
|
||||
path.as_os_str().encode_wide().chain(std::iter::once(0)).collect()
|
||||
let wide: Vec<u16> = path.as_os_str().encode_wide().chain(std::iter::once(0)).collect();
|
||||
ffi::CreateModelFromFile(wide.as_ptr())
|
||||
}
|
||||
#[cfg(not(windows))]
|
||||
{
|
||||
path.to_string_lossy()
|
||||
.chars()
|
||||
.map(|c| c as WChar)
|
||||
.chain(std::iter::once(0))
|
||||
.collect()
|
||||
use std::ffi::CString;
|
||||
let c_path = CString::new(path.to_string_lossy().as_bytes())
|
||||
.map_err(|_| NamError::ModelLoadFailed(path.display().to_string()))?;
|
||||
ffi::CreateModelFromFile(c_path.as_ptr())
|
||||
}
|
||||
};
|
||||
|
||||
let ptr = unsafe { ffi::CreateModelFromFile(wide.as_ptr()) };
|
||||
if ptr.is_null() {
|
||||
return Err(NamError::ModelLoadFailed(path.display().to_string()));
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user