using System;
|
using System.Collections.Generic;
|
using System.IO;
|
using System.Linq;
|
using System.Text;
|
using System.Threading.Tasks;
|
using System.IO.Compression;
|
|
namespace SmartScanner
|
{
|
public static class LBProjService
|
{
|
private const string ConfigFileName = "config.json";
|
private const string ModelNameFileName = "model_name.txt";
|
private const string ModelDir = "model"; // 固定模型目录
|
|
/// <summary>
|
/// 创建临时目录
|
/// </summary>
|
private static string CreateTempDirectory()
|
{
|
string tempDir = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());
|
Directory.CreateDirectory(tempDir);
|
return tempDir;
|
}
|
|
/// <summary>
|
/// 获取所有可用模型
|
/// </summary>
|
public static string[] GetAvailableModels()
|
{
|
string modelPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, ModelDir);
|
|
if (!Directory.Exists(modelPath))
|
{
|
Directory.CreateDirectory(modelPath);
|
return Array.Empty<string>();
|
}
|
|
return Directory.GetFiles(modelPath, "*.lb")
|
.Select(Path.GetFileName)
|
.ToArray();
|
}
|
|
/// <summary>
|
/// 创建工程文件
|
/// </summary>
|
public static (bool Success, string Message) CreateLBProj(
|
string paramFilePath,
|
string modelFileName,
|
string outputPath)
|
{
|
try
|
{
|
// 验证模型是否存在
|
string fullModelPath = Path.Combine(ModelDir, modelFileName);
|
if (!File.Exists(fullModelPath))
|
{
|
return (false, $"模型文件 {modelFileName} 不存在于 {ModelDir} 目录");
|
}
|
|
// 创建临时目录并打包
|
string tempDir = CreateTempDirectory();
|
try
|
{
|
// 1. 保存参数文件
|
File.Copy(paramFilePath, Path.Combine(tempDir, ConfigFileName), true);
|
|
// 2. 保存模型文件名(非路径)
|
File.WriteAllText(Path.Combine(tempDir, ModelNameFileName), modelFileName);
|
|
// 3. 创建ZIP包
|
ZipFile.CreateFromDirectory(tempDir, outputPath);
|
return (true, "工程文件创建成功");
|
}
|
finally
|
{
|
Directory.Delete(tempDir, true);
|
}
|
}
|
catch (Exception ex)
|
{
|
return (false, $"创建失败: {ex.Message}");
|
}
|
}
|
|
/// <summary>
|
/// 加载工程文件
|
/// </summary>
|
public static (string ModelName, string configPath, string ConfigContent, string Message) LoadLBProj(string projectFilePath)
|
{
|
try
|
{
|
string tempDir = CreateTempDirectory();
|
try
|
{
|
ZipFile.ExtractToDirectory(projectFilePath, tempDir);
|
|
// 1. 读取模型文件名
|
string modelNameFile = Path.Combine(tempDir, ModelNameFileName);
|
if (!File.Exists(modelNameFile))
|
{
|
return (null, null, null, "工程文件中缺少模型名称记录");
|
}
|
string modelName = File.ReadAllText(modelNameFile);
|
|
// 2. 验证模型是否存在
|
string fullModelPath = Path.Combine(ModelDir, modelName);
|
if (!File.Exists(fullModelPath))
|
{
|
return (null, null, null, $"模型 {modelName} 不存在于 {ModelDir} 目录");
|
}
|
|
// 3. 读取配置
|
string configPath = Path.Combine(tempDir, ConfigFileName);
|
string configContent = File.ReadAllText(configPath);
|
|
return (modelName, configPath, configContent, "加载成功");
|
}
|
finally
|
{
|
Directory.Delete(tempDir, true);
|
}
|
}
|
catch (Exception ex)
|
{
|
return (null, null, null, $"加载失败: 请输入正确的工程文件路径: {ex.Message}");
|
}
|
}
|
}
|
}
|