using Godot; using System.IO; using BSEnroll; using System.Collections.Generic; public partial class ModelDownloadManager : Node { // This class is responsible for downloading models from the server and removing old versions // As a model is training on the server, partially trained models can be downloaded and used locally // This class is also responsible for removing old versions of a model when a new version is selected(downloaded) // The model filename will consist of its name and percentage of completion // Example: model_name(10% trained).model or model_name.model, signifying it's fully trained [Signal] public delegate void ModelReadyEventHandler(string modelPath); public async void OnModelSelected(string modelPath) { GD.Print($"Model selected: {modelPath}"); UserDataManager.Instance.ModelLoadingError = ""; // Provided model is a local path // Send ready signal if it is valid if (File.Exists(modelPath)) { EmitSignal(SignalName.ModelReady, modelPath); return; } string fileName = Path.GetFileName(modelPath); string parentFolderName = Path.GetFileName(Path.GetDirectoryName(modelPath)); // date and time of the enrollment string downloadName = parentFolderName + "_" + fileName; string localPath = Path.Combine("user://models", downloadName); string systemPath = ProjectSettings.GlobalizePath(localPath); if (!File.Exists(systemPath)) { RemoveOldVersions(downloadName); GD.Print($"Model not found locally, downloading..."); await UserDataManager.Instance.DownloadModelAsync(modelPath, systemPath); } EmitSignal(SignalName.ModelReady, systemPath); } private string GetBaseModelName(string fileName) { int openParenIndex = fileName.IndexOf('('); return openParenIndex > 0 ? fileName[..openParenIndex] : fileName; } private List FindModelVariants(string fileName) { List variants = new List(); string baseModelName = GetBaseModelName(fileName); string modelsDir = ProjectSettings.GlobalizePath("user://models"); if (!Directory.Exists(modelsDir)) return variants; foreach (string file in Directory.GetFiles(modelsDir)) { string currentFileName = Path.GetFileName(file); if (GetBaseModelName(currentFileName) == baseModelName) { variants.Add(currentFileName); } } return variants; } private void RemoveOldVersions(string newModelFileName) { foreach (string variant in FindModelVariants(newModelFileName)) { if (variant == newModelFileName) continue; string variantPath = ProjectSettings.GlobalizePath(Path.Combine("user://models", variant)); GD.Print($"Removing old model: {variantPath}"); try { File.Delete(variantPath); GD.Print($"Successfully removed old model: {variantPath}"); } catch { GD.PrintErr($"Failed to remove old model: {variantPath}"); } } } }