c# project conversion
This commit is contained in:
+137
-27
@@ -1,36 +1,146 @@
|
||||
# ---> Go
|
||||
# If you prefer the allow list template instead of the deny list, see community template:
|
||||
# https://github.com/github/gitignore/blob/main/community/Golang/Go.AllowList.gitignore
|
||||
#
|
||||
# Binaries for programs and plugins
|
||||
*.exe
|
||||
*.exe~
|
||||
*.dll
|
||||
*.so
|
||||
*.dylib
|
||||
## Ignore Visual Studio temporary files, build results, and
|
||||
## files generated by popular Visual Studio add-ons.
|
||||
##
|
||||
## Original source: https://github.com/github/gitignore/blob/main/VisualStudio.gitignore
|
||||
|
||||
# Test binary, built with `go test -c`
|
||||
*.test
|
||||
# User-specific files
|
||||
*.rsuser
|
||||
*.suo
|
||||
*.user
|
||||
*.userosscache
|
||||
*.sln.docstates
|
||||
|
||||
# Code coverage profiles and other test artifacts
|
||||
*.out
|
||||
coverage.*
|
||||
*.coverprofile
|
||||
profile.cov
|
||||
# User-specific files (MonoDevelop/Xamarin Studio)
|
||||
*.userprefs
|
||||
|
||||
# Dependency directories (remove the comment below to include it)
|
||||
# vendor/
|
||||
# Mono auto generated files
|
||||
mono_crash.*
|
||||
|
||||
# Go workspace file
|
||||
go.work
|
||||
go.work.sum
|
||||
# Build results
|
||||
[Dd]ebug/
|
||||
[Dd]ebugPublic/
|
||||
[Rr]elease/
|
||||
[Rr]eleases/
|
||||
x64/
|
||||
x86/
|
||||
[Ww][Iinit][Nn]32/
|
||||
[Aa][Rr][Mm]/
|
||||
[Aa][Rr][Mm]64/
|
||||
bld/
|
||||
[Bb]in/
|
||||
[Oo]bj/
|
||||
[Ll]og/
|
||||
[Ll]ogs/
|
||||
|
||||
# env file
|
||||
.env
|
||||
# Visual Studio 2015/2017/2019/2022 cache/options directory
|
||||
.vs/
|
||||
# Uncomment if you use Visual Studio Code
|
||||
.vscode/
|
||||
|
||||
# Editor/IDE
|
||||
# .idea/
|
||||
# .vscode/
|
||||
# MSTest test Results
|
||||
[Tt]est[Rr]esult*/
|
||||
[Bb]uild[Ll]og.*
|
||||
|
||||
# NUnit
|
||||
*.VisualState.xml
|
||||
TestResult.xml
|
||||
nunit-agent.log
|
||||
|
||||
# .NET Core
|
||||
project.lock.json
|
||||
project.fragment.lock.json
|
||||
artifacts/
|
||||
|
||||
# StyleCop
|
||||
StyleCopReport.xml
|
||||
|
||||
# Files built by Visual Studio
|
||||
*_i.c
|
||||
*_p.c
|
||||
*_h.h
|
||||
*.ilk
|
||||
*.meta
|
||||
*.obj
|
||||
*.iobj
|
||||
*.pch
|
||||
*.pdb
|
||||
*.ipdb
|
||||
*.pgc
|
||||
*.pgd
|
||||
*.rsp
|
||||
*.sbr
|
||||
*.tlb
|
||||
*.tli
|
||||
*.tlh
|
||||
*.tmp
|
||||
*.tmp_proj
|
||||
*_wpftmp.csproj
|
||||
*.log
|
||||
*.vspscc
|
||||
*.vssscc
|
||||
.buildlog
|
||||
*.aps
|
||||
*.ncb
|
||||
*.opendb
|
||||
*.sdf
|
||||
*.cachefile
|
||||
*.nosync
|
||||
*.dbmdl
|
||||
*.dbproj.schemaview
|
||||
*.vshost.exe
|
||||
*.vshost.exe.config
|
||||
*.vshost.exe.manifest
|
||||
*.manifest
|
||||
*.spec
|
||||
*.coverage
|
||||
*.coveragexml
|
||||
*_UnitTests.coverage
|
||||
*.orderedtest
|
||||
*.trx
|
||||
*.sur
|
||||
*.ipch
|
||||
*.vcmeta
|
||||
*.VC.db
|
||||
*.VC.VC.opendb
|
||||
|
||||
# JetBrains Resharper
|
||||
_ReSharper*/
|
||||
*.[Rr]e[Ss]harper.user
|
||||
|
||||
# JustMock
|
||||
*.jmconfig
|
||||
|
||||
# TeamCity
|
||||
_TeamCity*
|
||||
|
||||
# Octopus Deploy
|
||||
*.nupkg
|
||||
|
||||
# Cake
|
||||
Tools/
|
||||
!tools/
|
||||
|
||||
# NuGet Packages
|
||||
*.nupkg
|
||||
# The packages folder can be ignored because of Package Restore
|
||||
**/[Pp]ackages/*
|
||||
# except build/, which is used as an MSBuild target.
|
||||
!**/[Pp]ackages/build/
|
||||
# Uncomment if using NuGet Config to restore to a custom location
|
||||
# !NuGet.Config
|
||||
|
||||
# Rider
|
||||
.idea/
|
||||
*.sln.iml
|
||||
|
||||
# OS generated files
|
||||
.DS_Store
|
||||
.DS_Store?
|
||||
._*
|
||||
.Spotlight-V100
|
||||
.Trashes
|
||||
ehthumbs.db
|
||||
Thumbs.db
|
||||
|
||||
TODO
|
||||
/binaries/
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
<Application xmlns="https://github.com/avaloniaui"
|
||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||
x:Class="Finder2eFoundryConverterCS.App"
|
||||
xmlns:local="using:Finder2eFoundryConverterCS"
|
||||
RequestedThemeVariant="Default">
|
||||
<!-- "Default" ThemeVariant follows system theme variant. "Dark" or "Light" are other available options. -->
|
||||
|
||||
<Application.DataTemplates>
|
||||
<local:ViewLocator/>
|
||||
</Application.DataTemplates>
|
||||
|
||||
<Application.Styles>
|
||||
<FluentTheme />
|
||||
</Application.Styles>
|
||||
</Application>
|
||||
@@ -0,0 +1,31 @@
|
||||
using Avalonia;
|
||||
using Avalonia.Controls.ApplicationLifetimes;
|
||||
using Avalonia.Data.Core;
|
||||
using Avalonia.Data.Core.Plugins;
|
||||
using System.Linq;
|
||||
using Avalonia.Markup.Xaml;
|
||||
using Finder2eFoundryConverterCS.ViewModels;
|
||||
using Finder2eFoundryConverterCS.Views;
|
||||
|
||||
namespace Finder2eFoundryConverterCS;
|
||||
|
||||
public partial class App : Application
|
||||
{
|
||||
public override void Initialize()
|
||||
{
|
||||
AvaloniaXamlLoader.Load(this);
|
||||
}
|
||||
|
||||
public override void OnFrameworkInitializationCompleted()
|
||||
{
|
||||
if (ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop)
|
||||
{
|
||||
desktop.MainWindow = new MainWindow
|
||||
{
|
||||
DataContext = new MainWindowViewModel(),
|
||||
};
|
||||
}
|
||||
|
||||
base.OnFrameworkInitializationCompleted();
|
||||
}
|
||||
}
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 172 KiB |
@@ -0,0 +1,26 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
<PropertyGroup>
|
||||
<OutputType>WinExe</OutputType>
|
||||
<TargetFramework>net10.0</TargetFramework>
|
||||
<Nullable>enable</Nullable>
|
||||
<ApplicationManifest>app.manifest</ApplicationManifest>
|
||||
<AvaloniaUseCompiledBindingsByDefault>true</AvaloniaUseCompiledBindingsByDefault>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<Folder Include="Models\" />
|
||||
<AvaloniaResource Include="Assets\**" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Avalonia" Version="12.0.4" />
|
||||
<PackageReference Include="Avalonia.Desktop" Version="12.0.4" />
|
||||
<PackageReference Include="Avalonia.Themes.Fluent" Version="12.0.4" />
|
||||
<PackageReference Include="Avalonia.Fonts.Inter" Version="12.0.4" />
|
||||
<PackageReference Include="AvaloniaUI.DiagnosticsSupport" Version="2.2.1">
|
||||
<IncludeAssets Condition="'$(Configuration)' != 'Debug'">None</IncludeAssets>
|
||||
<PrivateAssets Condition="'$(Configuration)' != 'Debug'">All</PrivateAssets>
|
||||
</PackageReference>
|
||||
<PackageReference Include="CommunityToolkit.Mvvm" Version="8.4.1" />
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
@@ -0,0 +1,10 @@
|
||||
using Avalonia.Media.Imaging;
|
||||
|
||||
namespace Finder2eFoundryConverterCS.Models
|
||||
{
|
||||
public class ImageItem
|
||||
{
|
||||
public string Path { get; set; } = string.Empty;
|
||||
public Bitmap? Thumbnail { get; set; }
|
||||
}
|
||||
}
|
||||
+20
@@ -0,0 +1,20 @@
|
||||
using Avalonia;
|
||||
using System;
|
||||
|
||||
namespace Finder2eFoundryConverterCS;
|
||||
|
||||
sealed class Program
|
||||
{
|
||||
[STAThread]
|
||||
public static void Main(string[] args) => BuildAvaloniaApp()
|
||||
.StartWithClassicDesktopLifetime(args);
|
||||
|
||||
public static AppBuilder BuildAvaloniaApp()
|
||||
=> AppBuilder.Configure<App>()
|
||||
.UsePlatformDetect()
|
||||
#if DEBUG
|
||||
.WithDeveloperTools()
|
||||
#endif
|
||||
.WithInterFont()
|
||||
.LogToTrace();
|
||||
}
|
||||
@@ -0,0 +1,108 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Net.Http;
|
||||
using System.Net.Http.Json;
|
||||
using System.Text.Json;
|
||||
using System.Threading.Tasks;
|
||||
using System.Text.Json.Serialization;
|
||||
|
||||
namespace Finder2eFoundryConverterCS.Services
|
||||
{
|
||||
public class LlmService
|
||||
{
|
||||
private readonly HttpClient _httpClient = new HttpClient();
|
||||
|
||||
public async Task<List<string>> GetModelsAsync(string baseUrl)
|
||||
{
|
||||
try
|
||||
{
|
||||
var response = await _httpClient.GetFromJsonAsync<ModelsResponse>($"{baseUrl.TrimEnd('/')}/v1/models");
|
||||
if (response?.Data == null) return new List<string>();
|
||||
|
||||
var models = new List<string>();
|
||||
foreach (var model in response.Data)
|
||||
{
|
||||
models.Add(model.Id);
|
||||
}
|
||||
return models;
|
||||
}
|
||||
catch
|
||||
{
|
||||
return new List<string> { "Error: LM Studio not found" };
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<string> GenerateResponseAsync(string baseUrl, string model, string text, List<string> imagePaths)
|
||||
{
|
||||
try
|
||||
{
|
||||
var contents = new List<object>
|
||||
{
|
||||
new { type = "text", text = text }
|
||||
};
|
||||
|
||||
foreach (var path in imagePaths)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(path)) continue;
|
||||
|
||||
var bytes = await System.IO.File.ReadAllBytesAsync(path);
|
||||
var base64 = Convert.ToBase64String(bytes);
|
||||
var extension = System.IO.Path.GetExtension(path).ToLower();
|
||||
var mimeType = extension switch
|
||||
{
|
||||
".jpg" or ".jpeg" => "image/jpeg",
|
||||
".webp" => "image/webp",
|
||||
_ => "image/png"
|
||||
};
|
||||
|
||||
contents.Add(new
|
||||
{
|
||||
type = "image_url",
|
||||
image_url = new { url = $"data:{mimeType};base64,{base64}" }
|
||||
});
|
||||
}
|
||||
|
||||
var requestBody = new
|
||||
{
|
||||
model = model,
|
||||
messages = new[]
|
||||
{
|
||||
new { role = "user", content = contents }
|
||||
}
|
||||
};
|
||||
|
||||
var response = await _httpClient.PostAsJsonAsync($"{baseUrl.TrimEnd('/')}/v1/chat/completions", requestBody);
|
||||
var body = await response.Content.ReadAsStringAsync();
|
||||
|
||||
using var doc = JsonDocument.Parse(body);
|
||||
if (doc.RootElement.TryGetProperty("error", out var error))
|
||||
{
|
||||
return $"Error: {error.GetProperty("message").GetString()}";
|
||||
}
|
||||
|
||||
if (doc.RootElement.TryGetProperty("choices", out var choices) && choices.GetArrayLength() > 0)
|
||||
{
|
||||
return choices[0].GetProperty("message").GetProperty("content").GetString() ?? "No content returned";
|
||||
}
|
||||
|
||||
return "No response choices returned.";
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
return $"Error: {ex.Message}";
|
||||
}
|
||||
}
|
||||
|
||||
private class ModelsResponse
|
||||
{
|
||||
[JsonPropertyName("data")]
|
||||
public List<ModelData>? Data { get; set; }
|
||||
}
|
||||
|
||||
private class ModelData
|
||||
{
|
||||
[JsonPropertyName("id")]
|
||||
public string Id { get; set; } = string.Empty;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using Avalonia.Controls;
|
||||
using Avalonia.Controls.Templates;
|
||||
using Finder2eFoundryConverterCS.ViewModels;
|
||||
|
||||
namespace Finder2eFoundryConverterCS;
|
||||
|
||||
[RequiresUnreferencedCode(
|
||||
"Default implementation of ViewLocator involves reflection which may be trimmed away.",
|
||||
Url = "https://docs.avaloniaui.net/docs/concepts/view-locator")]
|
||||
public class ViewLocator : IDataTemplate
|
||||
{
|
||||
public Control? Build(object? param)
|
||||
{
|
||||
if (param is null)
|
||||
return null;
|
||||
|
||||
var name = param.GetType().FullName!.Replace("ViewModel", "View", StringComparison.Ordinal);
|
||||
var type = Type.GetType(name);
|
||||
|
||||
if (type != null)
|
||||
{
|
||||
return (Control)Activator.CreateInstance(type)!;
|
||||
}
|
||||
|
||||
return new TextBlock { Text = "Not Found: " + name };
|
||||
}
|
||||
|
||||
public bool Match(object? data)
|
||||
{
|
||||
return data is ViewModelBase;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,145 @@
|
||||
using System;
|
||||
using System.Collections.ObjectModel;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Threading.Tasks;
|
||||
using System.Windows.Input;
|
||||
using Avalonia.Media.Imaging;
|
||||
using CommunityToolkit.Mvvm.ComponentModel;
|
||||
using CommunityToolkit.Mvvm.Input;
|
||||
using Finder2eFoundryConverterCS.Models;
|
||||
using Finder2eFoundryConverterCS.Services;
|
||||
|
||||
namespace Finder2eFoundryConverterCS.ViewModels
|
||||
{
|
||||
public partial class MainWindowViewModel : ViewModelBase
|
||||
{
|
||||
private readonly LlmService _llmService = new LlmService();
|
||||
|
||||
[ObservableProperty]
|
||||
private string _lmStudioAddress = "http://localhost:1234";
|
||||
|
||||
[ObservableProperty]
|
||||
private bool _isAddressVisible = false;
|
||||
|
||||
[ObservableProperty]
|
||||
private string _selectedProvider = "LM Studio";
|
||||
|
||||
public ObservableCollection<string> Providers { get; } = new() { "LM Studio" };
|
||||
|
||||
[ObservableProperty]
|
||||
private string? _selectedModel;
|
||||
|
||||
public ObservableCollection<string> Models { get; } = new();
|
||||
|
||||
[ObservableProperty]
|
||||
private string _description = string.Empty;
|
||||
|
||||
public ObservableCollection<ImageItem> ImageItems { get; } = new();
|
||||
|
||||
[ObservableProperty]
|
||||
private string _statusMessage = string.Empty;
|
||||
|
||||
[ObservableProperty]
|
||||
private bool _isErrorVisible = false;
|
||||
|
||||
[ObservableProperty]
|
||||
private string _errorText = string.Empty;
|
||||
|
||||
public MainWindowViewModel()
|
||||
{
|
||||
// Load saved preferences would go here if we had a settings service
|
||||
_ = StartModelRefreshLoop();
|
||||
}
|
||||
|
||||
[RelayCommand]
|
||||
private void ToggleAddress()
|
||||
{
|
||||
IsAddressVisible = !IsAddressVisible;
|
||||
}
|
||||
|
||||
[RelayCommand]
|
||||
private async Task RefreshModels()
|
||||
{
|
||||
if (SelectedProvider != "LM Studio")
|
||||
{
|
||||
IsErrorVisible = false;
|
||||
return;
|
||||
}
|
||||
|
||||
var models = await _llmService.GetModelsAsync(LmStudioAddress);
|
||||
|
||||
Models.Clear();
|
||||
foreach (var m in models)
|
||||
{
|
||||
Models.Add(m);
|
||||
}
|
||||
|
||||
if (models.Count > 0 && !models[0].StartsWith("Error"))
|
||||
{
|
||||
IsErrorVisible = false;
|
||||
if (SelectedModel == null || !Models.Contains(SelectedModel))
|
||||
{
|
||||
SelectedModel = Models.FirstOrDefault();
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
ErrorText = models.FirstOrDefault() ?? "Error connecting to LM Studio";
|
||||
IsErrorVisible = true;
|
||||
IsAddressVisible = true; // Auto-show on failure
|
||||
}
|
||||
}
|
||||
|
||||
[RelayCommand]
|
||||
private async Task Generate()
|
||||
{
|
||||
if (string.IsNullOrEmpty(SelectedModel))
|
||||
{
|
||||
StatusMessage = "Please select a model first.";
|
||||
return;
|
||||
}
|
||||
|
||||
StatusMessage = "Generating...";
|
||||
var result = await _llmService.GenerateResponseAsync(LmStudioAddress, SelectedModel, Description, ImageItems.Select(i => i.Path).ToList());
|
||||
StatusMessage = result;
|
||||
}
|
||||
|
||||
[RelayCommand]
|
||||
private void AddImagePath(string path)
|
||||
{
|
||||
if (!string.IsNullOrWhiteSpace(path) && File.Exists(path))
|
||||
{
|
||||
if (ImageItems.Any(i => i.Path == path)) return;
|
||||
|
||||
try
|
||||
{
|
||||
// Load thumbnail
|
||||
using var stream = File.OpenRead(path);
|
||||
var bitmap = new Bitmap(stream);
|
||||
// We could resize it here for efficiency if needed, but for now let's just use it
|
||||
ImageItems.Add(new ImageItem { Path = path, Thumbnail = bitmap });
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
StatusMessage = $"Error loading image: {ex.Message}";
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
[RelayCommand]
|
||||
private void RemoveImage(ImageItem item)
|
||||
{
|
||||
ImageItems.Remove(item);
|
||||
}
|
||||
|
||||
private async Task StartModelRefreshLoop()
|
||||
{
|
||||
while (true)
|
||||
{
|
||||
await RefreshModels();
|
||||
await Task.Delay(IsErrorVisible ? 3000 : 10000);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
using CommunityToolkit.Mvvm.ComponentModel;
|
||||
|
||||
namespace Finder2eFoundryConverterCS.ViewModels;
|
||||
|
||||
public abstract class ViewModelBase : ObservableObject
|
||||
{
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
<Window xmlns="https://github.com/avaloniaui"
|
||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||
xmlns:vm="using:Finder2eFoundryConverterCS.ViewModels"
|
||||
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
|
||||
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
|
||||
mc:Ignorable="d" d:DesignWidth="500" d:DesignHeight="600"
|
||||
x:Class="Finder2eFoundryConverterCS.Views.MainWindow"
|
||||
x:DataType="vm:MainWindowViewModel"
|
||||
Icon="/Assets/avalonia-logo.ico"
|
||||
Title="Finder2e Foundry Converter"
|
||||
Width="500" Height="600"
|
||||
DragDrop.AllowDrop="True">
|
||||
|
||||
<Design.DataContext>
|
||||
<!-- This only sets the DataContext for the previewer in an IDE,
|
||||
to set the actual DataContext at runtime, set the DataContext property in code (look at App.axaml.cs) -->
|
||||
<vm:MainWindowViewModel/>
|
||||
</Design.DataContext>
|
||||
|
||||
<ScrollViewer>
|
||||
<StackPanel Margin="20" Spacing="10">
|
||||
<Label Content="Provider:"/>
|
||||
<Grid ColumnDefinitions="*,Auto">
|
||||
<ComboBox Grid.Column="0" HorizontalAlignment="Stretch"
|
||||
ItemsSource="{Binding Providers}"
|
||||
SelectedItem="{Binding SelectedProvider}"/>
|
||||
<Button Grid.Column="1" Content="Address" Command="{Binding ToggleAddressCommand}" Margin="5,0,0,0"/>
|
||||
</Grid>
|
||||
|
||||
<TextBlock Text="{Binding ErrorText}" Foreground="Red" HorizontalAlignment="Center" IsVisible="{Binding IsErrorVisible}"/>
|
||||
|
||||
<StackPanel IsVisible="{Binding IsAddressVisible}" Spacing="5">
|
||||
<Label Content="LM Studio Address:"/>
|
||||
<TextBox Text="{Binding LmStudioAddress}" PlaceholderText="http://localhost:1234"/>
|
||||
</StackPanel>
|
||||
|
||||
<Label Content="Model:"/>
|
||||
<Grid ColumnDefinitions="*,Auto">
|
||||
<ComboBox Grid.Column="0" HorizontalAlignment="Stretch"
|
||||
ItemsSource="{Binding Models}"
|
||||
SelectedItem="{Binding SelectedModel}"
|
||||
PlaceholderText="Select Model"/>
|
||||
<Button Grid.Column="1" Content="Refresh" Command="{Binding RefreshModelsCommand}" Margin="5,0,0,0"/>
|
||||
</Grid>
|
||||
|
||||
<Label Content="Description:"/>
|
||||
<TextBox Text="{Binding Description}" AcceptsReturn="True" Height="100" PlaceholderText="Enter description here..."/>
|
||||
|
||||
<Label Content="Images:"/>
|
||||
<ScrollViewer Height="180">
|
||||
<ItemsControl ItemsSource="{Binding ImageItems}">
|
||||
<ItemsControl.ItemsPanel>
|
||||
<ItemsPanelTemplate>
|
||||
<WrapPanel />
|
||||
</ItemsPanelTemplate>
|
||||
</ItemsControl.ItemsPanel>
|
||||
<ItemsControl.ItemTemplate>
|
||||
<DataTemplate>
|
||||
<Grid Margin="5">
|
||||
<Border BorderBrush="Gray" BorderThickness="1" CornerRadius="4" ClipToBounds="True">
|
||||
<Image Source="{Binding Thumbnail}" Width="100" Height="100" Stretch="UniformToFill" />
|
||||
</Border>
|
||||
<Button Content="X"
|
||||
Command="{Binding $parent[Window].((vm:MainWindowViewModel)DataContext).RemoveImageCommand}"
|
||||
CommandParameter="{Binding}"
|
||||
HorizontalAlignment="Right" VerticalAlignment="Top"
|
||||
Background="#80000000" Foreground="White" Padding="5,2"/>
|
||||
</Grid>
|
||||
</DataTemplate>
|
||||
</ItemsControl.ItemTemplate>
|
||||
</ItemsControl>
|
||||
</ScrollViewer>
|
||||
|
||||
<Button Content="Select Image" HorizontalAlignment="Stretch" HorizontalContentAlignment="Center" Click="SelectImage_Click"/>
|
||||
|
||||
<Button Content="Generate" HorizontalAlignment="Stretch" HorizontalContentAlignment="Center"
|
||||
Command="{Binding GenerateCommand}" FontWeight="Bold"/>
|
||||
|
||||
<TextBlock Text="{Binding StatusMessage}" TextWrapping="Wrap" Margin="0,10,0,0"/>
|
||||
</StackPanel>
|
||||
</ScrollViewer>
|
||||
|
||||
</Window>
|
||||
@@ -0,0 +1,134 @@
|
||||
using System;
|
||||
using System.Linq;
|
||||
using System.Threading.Tasks;
|
||||
using Avalonia;
|
||||
using Avalonia.Controls;
|
||||
using Avalonia.Input;
|
||||
using Avalonia.Input.Platform;
|
||||
using Avalonia.Interactivity;
|
||||
using Avalonia.Platform.Storage;
|
||||
using Finder2eFoundryConverterCS.ViewModels;
|
||||
|
||||
namespace Finder2eFoundryConverterCS.Views
|
||||
{
|
||||
public partial class MainWindow : Window
|
||||
{
|
||||
public MainWindow()
|
||||
{
|
||||
InitializeComponent();
|
||||
AddHandler(DragDrop.DropEvent, Drop);
|
||||
KeyDown += OnKeyDown;
|
||||
}
|
||||
|
||||
private async void OnKeyDown(object? sender, KeyEventArgs e)
|
||||
{
|
||||
if (e.Key == Key.V && e.KeyModifiers == KeyModifiers.Control)
|
||||
{
|
||||
var topLevel = GetTopLevel(this);
|
||||
if (topLevel?.Clipboard == null) return;
|
||||
|
||||
var vm = DataContext as MainWindowViewModel;
|
||||
if (vm == null) return;
|
||||
|
||||
// Try to get text (for file paths)
|
||||
var text = await topLevel.Clipboard.TryGetTextAsync();
|
||||
if (!string.IsNullOrWhiteSpace(text))
|
||||
{
|
||||
var path = text.Replace("file://", "").Trim();
|
||||
if (System.IO.File.Exists(path))
|
||||
{
|
||||
var ext = System.IO.Path.GetExtension(path).ToLower();
|
||||
if (new[] { ".png", ".jpg", ".jpeg", ".webp" }.Contains(ext))
|
||||
{
|
||||
vm.AddImagePathCommand.Execute(path);
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Try to get bitmap directly
|
||||
var bitmap = await topLevel.Clipboard.TryGetBitmapAsync();
|
||||
if (bitmap != null)
|
||||
{
|
||||
// Save bitmap to temp file
|
||||
var tempDir = System.IO.Path.Combine(System.IO.Path.GetTempPath(), "Finder2eFoundryConverter");
|
||||
if (!System.IO.Directory.Exists(tempDir)) System.IO.Directory.CreateDirectory(tempDir);
|
||||
|
||||
var tempPath = System.IO.Path.Combine(tempDir, $"pasted_image_{DateTime.Now.Ticks}.png");
|
||||
bitmap.Save(tempPath);
|
||||
vm.AddImagePathCommand.Execute(tempPath);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
private async void SelectImage_Click(object? sender, RoutedEventArgs e)
|
||||
{
|
||||
var topLevel = GetTopLevel(this);
|
||||
if (topLevel == null) return;
|
||||
|
||||
var files = await topLevel.StorageProvider.OpenFilePickerAsync(new FilePickerOpenOptions
|
||||
{
|
||||
Title = "Select Images",
|
||||
AllowMultiple = true,
|
||||
FileTypeFilter = new[]
|
||||
{
|
||||
new FilePickerFileType("Images")
|
||||
{
|
||||
Patterns = new[] { "*.png", "*.jpg", "*.jpeg", "*.webp" }
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
if (files.Count > 0)
|
||||
{
|
||||
var vm = DataContext as MainWindowViewModel;
|
||||
if (vm == null) return;
|
||||
|
||||
foreach (var file in files)
|
||||
{
|
||||
vm.AddImagePathCommand.Execute(file.Path.LocalPath);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private async void Drop(object? sender, DragEventArgs e)
|
||||
{
|
||||
var files = e.DataTransfer.TryGetFiles();
|
||||
if (files != null)
|
||||
{
|
||||
var vm = DataContext as MainWindowViewModel;
|
||||
if (vm == null) return;
|
||||
|
||||
foreach (var file in files)
|
||||
{
|
||||
var path = file.Path.LocalPath;
|
||||
if (path == null) continue;
|
||||
|
||||
var ext = System.IO.Path.GetExtension(path).ToLower();
|
||||
if (new[] { ".png", ".jpg", ".jpeg", ".webp" }.Contains(ext))
|
||||
{
|
||||
vm.AddImagePathCommand.Execute(path);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Try to get bitmap directly from drop
|
||||
var bitmap = e.DataTransfer.TryGetBitmap();
|
||||
if (bitmap != null)
|
||||
{
|
||||
var vm = DataContext as MainWindowViewModel;
|
||||
if (vm != null)
|
||||
{
|
||||
var tempDir = System.IO.Path.Combine(System.IO.Path.GetTempPath(), "Finder2eFoundryConverter");
|
||||
if (!System.IO.Directory.Exists(tempDir)) System.IO.Directory.CreateDirectory(tempDir);
|
||||
|
||||
var tempPath = System.IO.Path.Combine(tempDir, $"dropped_image_{DateTime.Now.Ticks}.png");
|
||||
bitmap.Save(tempPath);
|
||||
vm.AddImagePathCommand.Execute(tempPath);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
@@ -1,42 +0,0 @@
|
||||
module finder2e-foundry-converter
|
||||
|
||||
go 1.26.3
|
||||
|
||||
require fyne.io/fyne/v2 v2.7.4
|
||||
|
||||
require (
|
||||
fyne.io/systray v1.12.1 // indirect
|
||||
github.com/BurntSushi/toml v1.5.0 // indirect
|
||||
github.com/davecgh/go-spew v1.1.1 // indirect
|
||||
github.com/fredbi/uri v1.1.1 // indirect
|
||||
github.com/fsnotify/fsnotify v1.9.0 // indirect
|
||||
github.com/fyne-io/gl-js v0.2.0 // indirect
|
||||
github.com/fyne-io/glfw-js v0.3.0 // indirect
|
||||
github.com/fyne-io/image v0.1.1 // indirect
|
||||
github.com/fyne-io/oksvg v0.2.0 // indirect
|
||||
github.com/go-gl/gl v0.0.0-20231021071112-07e5d0ea2e71 // indirect
|
||||
github.com/go-gl/glfw/v3.3/glfw v0.0.0-20240506104042-037f3cc74f2a // indirect
|
||||
github.com/go-text/render v0.2.1 // indirect
|
||||
github.com/go-text/typesetting v0.3.4 // indirect
|
||||
github.com/godbus/dbus/v5 v5.1.0 // indirect
|
||||
github.com/hack-pad/go-indexeddb v0.3.2 // indirect
|
||||
github.com/hack-pad/safejs v0.1.0 // indirect
|
||||
github.com/jeandeaual/go-locale v0.0.0-20250612000132-0ef82f21eade // indirect
|
||||
github.com/jsummers/gobmp v0.0.0-20230614200233-a9de23ed2e25 // indirect
|
||||
github.com/kr/text v0.2.0 // indirect
|
||||
github.com/mattn/go-runewidth v0.0.17 // indirect
|
||||
github.com/nfnt/resize v0.0.0-20180221191011-83c6a9932646 // indirect
|
||||
github.com/nicksnyder/go-i18n/v2 v2.5.1 // indirect
|
||||
github.com/pmezard/go-difflib v1.0.0 // indirect
|
||||
github.com/rivo/uniseg v0.2.0 // indirect
|
||||
github.com/rymdport/portal v0.4.2 // indirect
|
||||
github.com/srwiley/oksvg v0.0.0-20221011165216-be6e8873101c // indirect
|
||||
github.com/srwiley/rasterx v0.0.0-20220730225603-2ab79fcdd4ef // indirect
|
||||
github.com/stretchr/testify v1.11.1 // indirect
|
||||
github.com/yuin/goldmark v1.7.8 // indirect
|
||||
golang.org/x/image v0.24.0 // indirect
|
||||
golang.org/x/net v0.35.0 // indirect
|
||||
golang.org/x/sys v0.30.0 // indirect
|
||||
golang.org/x/text v0.22.0 // indirect
|
||||
gopkg.in/yaml.v3 v3.0.1 // indirect
|
||||
)
|
||||
@@ -1,84 +0,0 @@
|
||||
fyne.io/fyne/v2 v2.7.4 h1:OVCI5mT+Onb2kA4wlmGA5pLCqKik9f4NDb5jiR1OMTc=
|
||||
fyne.io/fyne/v2 v2.7.4/go.mod h1:ZD1mmhBY75mSa97IXl3MPlICd1uNHfCXYh5hKIlVOII=
|
||||
fyne.io/systray v1.12.1 h1:ygBD6aZXwiOmZoY5N+ukbH9pih0Kq6fYgVeMYbr5skQ=
|
||||
fyne.io/systray v1.12.1/go.mod h1:RVwqP9nYMo7h5zViCBHri2FgjXF7H2cub7MAq4NSoLs=
|
||||
github.com/BurntSushi/toml v1.5.0 h1:W5quZX/G/csjUnuI8SUYlsHs9M38FC7znL0lIO+DvMg=
|
||||
github.com/BurntSushi/toml v1.5.0/go.mod h1:ukJfTF/6rtPPRCnwkur4qwRxa8vTRFBF0uk2lLoLwho=
|
||||
github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E=
|
||||
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
|
||||
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/felixge/fgprof v0.9.3 h1:VvyZxILNuCiUCSXtPtYmmtGvb65nqXh2QFWc0Wpf2/g=
|
||||
github.com/felixge/fgprof v0.9.3/go.mod h1:RdbpDgzqYVh/T9fPELJyV7EYJuHB55UTEULNun8eiPw=
|
||||
github.com/fredbi/uri v1.1.1 h1:xZHJC08GZNIUhbP5ImTHnt5Ya0T8FI2VAwI/37kh2Ko=
|
||||
github.com/fredbi/uri v1.1.1/go.mod h1:4+DZQ5zBjEwQCDmXW5JdIjz0PUA+yJbvtBv+u+adr5o=
|
||||
github.com/fsnotify/fsnotify v1.9.0 h1:2Ml+OJNzbYCTzsxtv8vKSFD9PbJjmhYF14k/jKC7S9k=
|
||||
github.com/fsnotify/fsnotify v1.9.0/go.mod h1:8jBTzvmWwFyi3Pb8djgCCO5IBqzKJ/Jwo8TRcHyHii0=
|
||||
github.com/fyne-io/gl-js v0.2.0 h1:+EXMLVEa18EfkXBVKhifYB6OGs3HwKO3lUElA0LlAjs=
|
||||
github.com/fyne-io/gl-js v0.2.0/go.mod h1:ZcepK8vmOYLu96JoxbCKJy2ybr+g1pTnaBDdl7c3ajI=
|
||||
github.com/fyne-io/glfw-js v0.3.0 h1:d8k2+Y7l+zy2pc7wlGRyPfTgZoqDf3AI4G+2zOWhWUk=
|
||||
github.com/fyne-io/glfw-js v0.3.0/go.mod h1:Ri6te7rdZtBgBpxLW19uBpp3Dl6K9K/bRaYdJ22G8Jk=
|
||||
github.com/fyne-io/image v0.1.1 h1:WH0z4H7qfvNUw5l4p3bC1q70sa5+YWVt6HCj7y4VNyA=
|
||||
github.com/fyne-io/image v0.1.1/go.mod h1:xrfYBh6yspc+KjkgdZU/ifUC9sPA5Iv7WYUBzQKK7JM=
|
||||
github.com/fyne-io/oksvg v0.2.0 h1:mxcGU2dx6nwjJsSA9PCYZDuoAcsZ/OuJlvg/Q9Njfo8=
|
||||
github.com/fyne-io/oksvg v0.2.0/go.mod h1:dJ9oEkPiWhnTFNCmRgEze+YNprJF7YRbpjgpWS4kzoI=
|
||||
github.com/go-gl/gl v0.0.0-20231021071112-07e5d0ea2e71 h1:5BVwOaUSBTlVZowGO6VZGw2H/zl9nrd3eCZfYV+NfQA=
|
||||
github.com/go-gl/gl v0.0.0-20231021071112-07e5d0ea2e71/go.mod h1:9YTyiznxEY1fVinfM7RvRcjRHbw2xLBJ3AAGIT0I4Nw=
|
||||
github.com/go-gl/glfw/v3.3/glfw v0.0.0-20240506104042-037f3cc74f2a h1:vxnBhFDDT+xzxf1jTJKMKZw3H0swfWk9RpWbBbDK5+0=
|
||||
github.com/go-gl/glfw/v3.3/glfw v0.0.0-20240506104042-037f3cc74f2a/go.mod h1:tQ2UAYgL5IevRw8kRxooKSPJfGvJ9fJQFa0TUsXzTg8=
|
||||
github.com/go-text/render v0.2.1 h1:qwHhxqGUjjg4L0XyJWj7M7bpY75NZM+kBpv2Yfw5mcg=
|
||||
github.com/go-text/render v0.2.1/go.mod h1:HCCAq8MUlm/WRcXshBb4K/n+IkjeXQ1c2Ba+yICSm0A=
|
||||
github.com/go-text/typesetting v0.3.4 h1:YYurUOtEb9kGSOz4uE3k4OpBGsp1dDL8+fjCeaFamAU=
|
||||
github.com/go-text/typesetting v0.3.4/go.mod h1:4qZCQphq4KSgGTAeI0uMEkVbROgfah8BuyF5LRYr7XY=
|
||||
github.com/go-text/typesetting-utils v0.0.0-20260223113751-2d88ac90dae3 h1:drBZzMgdYPbmyXqOto4YhhJGrFIQCX94FpR4MzTCsos=
|
||||
github.com/go-text/typesetting-utils v0.0.0-20260223113751-2d88ac90dae3/go.mod h1:3/62I4La/HBRX9TcTpBj4eipLiwzf+vhI+7whTc9V7o=
|
||||
github.com/godbus/dbus/v5 v5.1.0 h1:4KLkAxT3aOY8Li4FRJe/KvhoNFFxo0m6fNuFUO8QJUk=
|
||||
github.com/godbus/dbus/v5 v5.1.0/go.mod h1:xhWf0FNVPg57R7Z0UbKHbJfkEywrmjJnf7w5xrFpKfA=
|
||||
github.com/google/pprof v0.0.0-20211214055906-6f57359322fd h1:1FjCyPC+syAzJ5/2S8fqdZK1R22vvA0J7JZKcuOIQ7Y=
|
||||
github.com/google/pprof v0.0.0-20211214055906-6f57359322fd/go.mod h1:KgnwoLYCZ8IQu3XUZ8Nc/bM9CCZFOyjUNOSygVozoDg=
|
||||
github.com/hack-pad/go-indexeddb v0.3.2 h1:DTqeJJYc1usa45Q5r52t01KhvlSN02+Oq+tQbSBI91A=
|
||||
github.com/hack-pad/go-indexeddb v0.3.2/go.mod h1:QvfTevpDVlkfomY498LhstjwbPW6QC4VC/lxYb0Kom0=
|
||||
github.com/hack-pad/safejs v0.1.0 h1:qPS6vjreAqh2amUqj4WNG1zIw7qlRQJ9K10eDKMCnE8=
|
||||
github.com/hack-pad/safejs v0.1.0/go.mod h1:HdS+bKF1NrE72VoXZeWzxFOVQVUSqZJAG0xNCnb+Tio=
|
||||
github.com/jeandeaual/go-locale v0.0.0-20250612000132-0ef82f21eade h1:FmusiCI1wHw+XQbvL9M+1r/C3SPqKrmBaIOYwVfQoDE=
|
||||
github.com/jeandeaual/go-locale v0.0.0-20250612000132-0ef82f21eade/go.mod h1:ZDXo8KHryOWSIqnsb/CiDq7hQUYryCgdVnxbj8tDG7o=
|
||||
github.com/jsummers/gobmp v0.0.0-20230614200233-a9de23ed2e25 h1:YLvr1eE6cdCqjOe972w/cYF+FjW34v27+9Vo5106B4M=
|
||||
github.com/jsummers/gobmp v0.0.0-20230614200233-a9de23ed2e25/go.mod h1:kLgvv7o6UM+0QSf0QjAse3wReFDsb9qbZJdfexWlrQw=
|
||||
github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
|
||||
github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
|
||||
github.com/mattn/go-runewidth v0.0.17 h1:78v8ZlW0bP43XfmAfPsdXcoNCelfMHsDmd/pkENfrjQ=
|
||||
github.com/mattn/go-runewidth v0.0.17/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w=
|
||||
github.com/nfnt/resize v0.0.0-20180221191011-83c6a9932646 h1:zYyBkD/k9seD2A7fsi6Oo2LfFZAehjjQMERAvZLEDnQ=
|
||||
github.com/nfnt/resize v0.0.0-20180221191011-83c6a9932646/go.mod h1:jpp1/29i3P1S/RLdc7JQKbRpFeM1dOBd8T9ki5s+AY8=
|
||||
github.com/nicksnyder/go-i18n/v2 v2.5.1 h1:IxtPxYsR9Gp60cGXjfuR/llTqV8aYMsC472zD0D1vHk=
|
||||
github.com/nicksnyder/go-i18n/v2 v2.5.1/go.mod h1:DrhgsSDZxoAfvVrBVLXoxZn/pN5TXqaDbq7ju94viiQ=
|
||||
github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e h1:fD57ERR4JtEqsWbfPhv4DMiApHyliiK5xCTNVSPiaAs=
|
||||
github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e/go.mod h1:zD1mROLANZcx1PVRCS0qkT7pwLkGfwJo4zjcN/Tysno=
|
||||
github.com/pkg/profile v1.7.0 h1:hnbDkaNWPCLMO9wGLdBFTIZvzDrDfBM2072E1S9gJkA=
|
||||
github.com/pkg/profile v1.7.0/go.mod h1:8Uer0jas47ZQMJ7VD+OHknK4YDY07LPUC6dEvqDjvNo=
|
||||
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
|
||||
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||
github.com/rivo/uniseg v0.2.0 h1:S1pD9weZBuJdFmowNwbpi7BJ8TNftyUImj/0WQi72jY=
|
||||
github.com/rivo/uniseg v0.2.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc=
|
||||
github.com/rymdport/portal v0.4.2 h1:7jKRSemwlTyVHHrTGgQg7gmNPJs88xkbKcIL3NlcmSU=
|
||||
github.com/rymdport/portal v0.4.2/go.mod h1:kFF4jslnJ8pD5uCi17brj/ODlfIidOxlgUDTO5ncnC4=
|
||||
github.com/srwiley/oksvg v0.0.0-20221011165216-be6e8873101c h1:km8GpoQut05eY3GiYWEedbTT0qnSxrCjsVbb7yKY1KE=
|
||||
github.com/srwiley/oksvg v0.0.0-20221011165216-be6e8873101c/go.mod h1:cNQ3dwVJtS5Hmnjxy6AgTPd0Inb3pW05ftPSX7NZO7Q=
|
||||
github.com/srwiley/rasterx v0.0.0-20220730225603-2ab79fcdd4ef h1:Ch6Q+AZUxDBCVqdkI8FSpFyZDtCVBc2VmejdNrm5rRQ=
|
||||
github.com/srwiley/rasterx v0.0.0-20220730225603-2ab79fcdd4ef/go.mod h1:nXTWP6+gD5+LUJ8krVhhoeHjvHTutPxMYl5SvkcnJNE=
|
||||
github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=
|
||||
github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
|
||||
github.com/yuin/goldmark v1.7.8 h1:iERMLn0/QJeHFhxSt3p6PeN9mGnvIKSpG9YYorDMnic=
|
||||
github.com/yuin/goldmark v1.7.8/go.mod h1:uzxRWxtg69N339t3louHJ7+O03ezfj6PlliRlaOzY1E=
|
||||
golang.org/x/image v0.24.0 h1:AN7zRgVsbvmTfNyqIbbOraYL8mSwcKncEj8ofjgzcMQ=
|
||||
golang.org/x/image v0.24.0/go.mod h1:4b/ITuLfqYq1hqZcjofwctIhi7sZh2WaCjvsBNjjya8=
|
||||
golang.org/x/net v0.35.0 h1:T5GQRQb2y08kTAByq9L4/bz8cipCdA8FbRTXewonqY8=
|
||||
golang.org/x/net v0.35.0/go.mod h1:EglIi67kWsHKlRzzVMUD93VMSWGFOMSZgxFjparz1Qk=
|
||||
golang.org/x/sys v0.30.0 h1:QjkSwP/36a20jFYWkSue1YwXzLmsV5Gfq7Eiy72C1uc=
|
||||
golang.org/x/sys v0.30.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
|
||||
golang.org/x/text v0.22.0 h1:bofq7m3/HAFvbF51jz3Q9wLg3jkvSPuiZu/pD1XwgtM=
|
||||
golang.org/x/text v0.22.0/go.mod h1:YRoo4H8PVmsu+E3Ou7cqLVH8oXWIHVoX0jqUWALQhfY=
|
||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
gopkg.in/check.v1 v1.0.0-20200227125254-8fa46927fb4f h1:BLraFXnmrev5lT+xlilqcH8XK9/i0At2xKjWk4p6zsU=
|
||||
gopkg.in/check.v1 v1.0.0-20200227125254-8fa46927fb4f/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
||||
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
@@ -1,346 +0,0 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"image/color"
|
||||
"io"
|
||||
"net/http"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"fyne.io/fyne/v2"
|
||||
"fyne.io/fyne/v2/app"
|
||||
"fyne.io/fyne/v2/canvas"
|
||||
"fyne.io/fyne/v2/container"
|
||||
"fyne.io/fyne/v2/dialog"
|
||||
"fyne.io/fyne/v2/driver/desktop"
|
||||
"fyne.io/fyne/v2/storage"
|
||||
"fyne.io/fyne/v2/widget"
|
||||
)
|
||||
|
||||
func main() {
|
||||
myApp := app.NewWithID("finder2e_foundry_converter")
|
||||
myWindow := myApp.NewWindow("Finder2e Foundry Converter")
|
||||
|
||||
prefs := myApp.Preferences()
|
||||
|
||||
// LM Studio Integration
|
||||
savedAddr := prefs.StringWithFallback("LMStudioAddress", "http://localhost:1234")
|
||||
addrEntry := widget.NewEntry()
|
||||
addrEntry.SetText(savedAddr)
|
||||
addrEntry.SetPlaceHolder("LM Studio URL (e.g. http://192.168.1.10:1234)")
|
||||
addrEntry.OnChanged = func(s string) {
|
||||
prefs.SetString("LMStudioAddress", s)
|
||||
}
|
||||
|
||||
addrContainer := container.NewVBox(
|
||||
widget.NewLabel("LM Studio Address:"),
|
||||
addrEntry,
|
||||
)
|
||||
addrContainer.Hide()
|
||||
|
||||
// LLM Provider Selection
|
||||
var toggleAddrBtn *widget.Button
|
||||
savedProvider := prefs.StringWithFallback("SelectedProvider", "LM Studio")
|
||||
providerSelect := widget.NewSelect([]string{"LM Studio"}, func(s string) {
|
||||
fmt.Printf("Provider changed to: %s\n", s)
|
||||
prefs.SetString("SelectedProvider", s)
|
||||
if s == "LM Studio" {
|
||||
toggleAddrBtn.Show()
|
||||
} else {
|
||||
toggleAddrBtn.Hide()
|
||||
addrContainer.Hide()
|
||||
}
|
||||
})
|
||||
|
||||
addrManuallyOpened := false
|
||||
toggleAddrBtn = widget.NewButton("Address", func() {
|
||||
if addrContainer.Visible() {
|
||||
addrContainer.Hide()
|
||||
addrManuallyOpened = false
|
||||
} else {
|
||||
addrContainer.Show()
|
||||
addrManuallyOpened = true
|
||||
}
|
||||
})
|
||||
providerSelect.SetSelected(savedProvider)
|
||||
|
||||
errorLabel := canvas.NewText("Error: LM Studio not found. Retrying...", color.NRGBA{R: 255, G: 0, B: 0, A: 255})
|
||||
errorLabel.Alignment = fyne.TextAlignCenter
|
||||
errorLabel.Hide()
|
||||
|
||||
modelSelect := widget.NewSelect([]string{"Loading models..."}, func(s string) {
|
||||
if s != "" && !strings.HasPrefix(s, "Loading") && !strings.HasPrefix(s, "Error") && !strings.HasPrefix(s, "No models") {
|
||||
prefs.SetString("LastSelectedModel", s)
|
||||
}
|
||||
})
|
||||
modelSelect.PlaceHolder = "Select Model"
|
||||
|
||||
refreshModels := func() {
|
||||
if providerSelect.Selected != "LM Studio" {
|
||||
fyne.Do(func() {
|
||||
errorLabel.Hide()
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
currentAddr := strings.TrimSuffix(addrEntry.Text, "/")
|
||||
resp, err := http.Get(fmt.Sprintf("%s/v1/models", currentAddr))
|
||||
if err != nil {
|
||||
fyne.Do(func() {
|
||||
modelSelect.Options = []string{"Error: LM Studio not found"}
|
||||
modelSelect.Refresh()
|
||||
errorLabel.Show()
|
||||
errorLabel.Refresh()
|
||||
addrContainer.Show() // Auto-show on failure
|
||||
})
|
||||
return
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
var result struct {
|
||||
Data []struct {
|
||||
ID string `json:"id"`
|
||||
} `json:"data"`
|
||||
}
|
||||
if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
|
||||
fyne.Do(func() {
|
||||
modelSelect.Options = []string{"Error decoding models"}
|
||||
modelSelect.Refresh()
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
var models []string
|
||||
for _, m := range result.Data {
|
||||
models = append(models, m.ID)
|
||||
}
|
||||
if len(models) == 0 {
|
||||
models = []string{"No models loaded in LM Studio"}
|
||||
}
|
||||
|
||||
fyne.Do(func() {
|
||||
errorLabel.Hide()
|
||||
errorLabel.Refresh()
|
||||
modelSelect.Options = models
|
||||
modelSelect.Refresh()
|
||||
|
||||
lastModel := prefs.String("LastSelectedModel")
|
||||
if lastModel != "" && (modelSelect.Selected == "" || modelSelect.Selected == "Loading models...") {
|
||||
for _, m := range models {
|
||||
if m == lastModel {
|
||||
modelSelect.SetSelected(m)
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if !addrManuallyOpened {
|
||||
addrContainer.Hide()
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// Retry logic: Refresh models every 3 seconds with countdown
|
||||
go func() {
|
||||
for {
|
||||
refreshModels()
|
||||
if errorLabel.Visible() {
|
||||
for i := 3; i > 0; i-- {
|
||||
fyne.Do(func() {
|
||||
errorLabel.Text = fmt.Sprintf("Error: LM Studio not found. Retrying in %d...", i)
|
||||
errorLabel.Refresh()
|
||||
})
|
||||
time.Sleep(1 * time.Second)
|
||||
}
|
||||
} else {
|
||||
time.Sleep(3 * time.Second)
|
||||
}
|
||||
}
|
||||
}()
|
||||
|
||||
textEntry := widget.NewMultiLineEntry()
|
||||
textEntry.SetPlaceHolder("Enter description here...")
|
||||
|
||||
imagePathsContainer := container.NewVBox()
|
||||
|
||||
addImageEntry := func(path string) {
|
||||
fyne.Do(func() {
|
||||
newEntry := widget.NewEntry()
|
||||
newEntry.SetText(path)
|
||||
imagePathsContainer.Add(newEntry)
|
||||
imagePathsContainer.Refresh()
|
||||
})
|
||||
}
|
||||
|
||||
isImage := func(ext string) bool {
|
||||
switch ext {
|
||||
case ".png", ".jpg", ".jpeg", ".webp":
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
imagePickerButton := widget.NewButton("Select Image", func() {
|
||||
fd := dialog.NewFileOpen(func(reader fyne.URIReadCloser, err error) {
|
||||
if err != nil || reader == nil {
|
||||
return
|
||||
}
|
||||
defer reader.Close()
|
||||
|
||||
addImageEntry(reader.URI().Path())
|
||||
}, myWindow)
|
||||
|
||||
fd.SetFilter(storage.NewExtensionFileFilter([]string{".png", ".jpg", ".jpeg", ".webp"}))
|
||||
fd.Show()
|
||||
})
|
||||
|
||||
// Drag and Drop support
|
||||
myWindow.SetOnDropped(func(pos fyne.Position, uris []fyne.URI) {
|
||||
for _, u := range uris {
|
||||
if isImage(u.Extension()) {
|
||||
addImageEntry(u.Path())
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
// Paste support (Ctrl+V)
|
||||
pasteShortcut := &desktop.CustomShortcut{KeyName: fyne.KeyV, Modifier: fyne.KeyModifierShortcutDefault}
|
||||
myWindow.Canvas().AddShortcut(pasteShortcut, func(shortcut fyne.Shortcut) {
|
||||
content := myWindow.Clipboard().Content()
|
||||
if content == "" {
|
||||
return
|
||||
}
|
||||
|
||||
// Handle file URLs (sometimes copied from file managers)
|
||||
path := strings.TrimPrefix(content, "file://")
|
||||
path = strings.TrimSpace(path)
|
||||
|
||||
ext := strings.ToLower(filepath.Ext(path))
|
||||
if isImage(ext) {
|
||||
// Check if it's a valid local path
|
||||
if _, err := os.Stat(path); err == nil {
|
||||
addImageEntry(path)
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
generateButton := widget.NewButton("Generate", nil)
|
||||
generateButton.OnTapped = func() {
|
||||
if modelSelect.Selected == "" {
|
||||
dialog.ShowInformation("Selection Required", "Please select a model first.", myWindow)
|
||||
return
|
||||
}
|
||||
|
||||
if providerSelect.Selected == "LM Studio" {
|
||||
currentAddr := strings.TrimSuffix(addrEntry.Text, "/")
|
||||
fmt.Printf("Sending request to LM Studio at %s (%s)...\n", currentAddr, modelSelect.Selected)
|
||||
|
||||
// Prepare messages
|
||||
type MessageContent struct {
|
||||
Type string `json:"type"`
|
||||
Text string `json:"text,omitempty"`
|
||||
ImageURL *struct {
|
||||
URL string `json:"url"`
|
||||
} `json:"image_url,omitempty"`
|
||||
}
|
||||
|
||||
var content []MessageContent
|
||||
content = append(content, MessageContent{Type: "text", Text: textEntry.Text})
|
||||
|
||||
for _, obj := range imagePathsContainer.Objects {
|
||||
if entry, ok := obj.(*widget.Entry); ok && entry.Text != "" {
|
||||
imgData, err := os.ReadFile(entry.Text)
|
||||
if err != nil {
|
||||
fmt.Printf("Error reading image %s: %v\n", entry.Text, err)
|
||||
continue
|
||||
}
|
||||
base64Img := base64.StdEncoding.EncodeToString(imgData)
|
||||
mimeType := "image/png"
|
||||
if strings.HasSuffix(strings.ToLower(entry.Text), ".jpg") || strings.HasSuffix(strings.ToLower(entry.Text), ".jpeg") {
|
||||
mimeType = "image/jpeg"
|
||||
} else if strings.HasSuffix(strings.ToLower(entry.Text), ".webp") {
|
||||
mimeType = "image/webp"
|
||||
}
|
||||
|
||||
content = append(content, MessageContent{
|
||||
Type: "image_url",
|
||||
ImageURL: &struct {
|
||||
URL string `json:"url"`
|
||||
}{
|
||||
URL: fmt.Sprintf("data:%s;base64,%s", mimeType, base64Img),
|
||||
},
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
requestBody, _ := json.Marshal(map[string]interface{}{
|
||||
"model": modelSelect.Selected,
|
||||
"messages": []interface{}{map[string]interface{}{"role": "user", "content": content}},
|
||||
})
|
||||
|
||||
resp, err := http.Post(fmt.Sprintf("%s/v1/chat/completions", currentAddr), "application/json", strings.NewReader(string(requestBody)))
|
||||
if err != nil {
|
||||
fmt.Printf("Error calling LM Studio: %v\n", err)
|
||||
return
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
body, _ := io.ReadAll(resp.Body)
|
||||
var chatResp struct {
|
||||
Choices []struct {
|
||||
Message struct {
|
||||
Content string `json:"content"`
|
||||
} `json:"message"`
|
||||
} `json:"choices"`
|
||||
Error struct {
|
||||
Message string `json:"message"`
|
||||
} `json:"error"`
|
||||
}
|
||||
|
||||
if err := json.Unmarshal(body, &chatResp); err != nil {
|
||||
fmt.Printf("Error decoding response: %v\n", err)
|
||||
fmt.Println("Raw response:", string(body))
|
||||
return
|
||||
}
|
||||
|
||||
if chatResp.Error.Message != "" {
|
||||
fmt.Printf("LM Studio Error: %s\n", chatResp.Error.Message)
|
||||
return
|
||||
}
|
||||
|
||||
if len(chatResp.Choices) > 0 {
|
||||
fmt.Println("\nLM Studio Response:")
|
||||
fmt.Println(chatResp.Choices[0].Message.Content)
|
||||
} else {
|
||||
fmt.Println("No response choices returned.")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
scrollContainer := container.NewVScroll(imagePathsContainer)
|
||||
scrollContainer.SetMinSize(fyne.NewSize(0, 150))
|
||||
|
||||
content := container.NewVBox(
|
||||
widget.NewLabel("Provider:"),
|
||||
container.NewBorder(nil, nil, nil, toggleAddrBtn, providerSelect),
|
||||
errorLabel,
|
||||
addrContainer,
|
||||
widget.NewLabel("Model:"),
|
||||
container.NewBorder(nil, nil, nil, widget.NewButton("Refresh", refreshModels), modelSelect),
|
||||
widget.NewLabel("Description:"),
|
||||
textEntry,
|
||||
widget.NewLabel("Images:"),
|
||||
scrollContainer,
|
||||
imagePickerButton,
|
||||
generateButton,
|
||||
)
|
||||
|
||||
myWindow.SetContent(content)
|
||||
myWindow.Resize(fyne.NewSize(500, 500))
|
||||
myWindow.ShowAndRun()
|
||||
}
|
||||
Reference in New Issue
Block a user