Integration API API API Gradio в Dotnet MauiC#

Место общения программистов C#
Ответить
Anonymous
 Integration API API API Gradio в Dotnet Maui

Сообщение Anonymous »

Я использую эту модель искусственного интеллекта в приложении, которое я создает в dotnet maui https://huggingface.co/spaces/franciszzj/leffa
Я новичок в API, так что я немного борюсь с инфекцией
Я и программа. />https://bd9862a938f0559157.gradio.live
Проблема, с которой я сталкиваюсь, заключается в том, что я возвращаю веб -страницу HTML, а не изображение, которое он должен вернуть. Я понимаю, что это потому, что я не добавил конечную точку, однако, когда я меняю URL, чтобы сдержать конечную точку (//BD9862A938F0559157.Gradio.live/leffa_predict_vt). Это возвращает ошибку, говоря, что он не может подключиться
im, используя публичные URL, потому что я не могу работать с местом. /> Вот какой -то соответствующий код (большинство из них является Chatgpt, поэтому его вероятность не оптимальная): < /p>
using System;
using System.Net.Http;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;

public class LeffaService
{
private readonly HttpClient _httpClient;

public LeffaService()
{
_httpClient = new HttpClient();
}

public async Task CallLeffaPredictVTAsync(string srcImageUrl, string refImageUrl, string refAcceleration = "false", int step = 30, double scale = 2.5, int seed = 42, string vtModelType = "viton_hd", string vtGarmentType = "upper_body", string vtRepaint = "false", bool preprocessGarment = false)
{
try
{
var baseUrl = "https://bd9862a938f0559157.gradio.live";
var requestUrl = $"{baseUrl}/leffa_predict_vt";

var requestData = new
{
srcImageUrl,
refImageUrl,
refAcceleration,
step,
scale,
seed,
vtModelType,
vtGarmentType,
vtRepaint,
preprocessGarment
};

var jsonContent = new StringContent(JsonSerializer.Serialize(requestData), Encoding.UTF8, "application/json");
Console.WriteLine($"POST Request to: {requestUrl}");
Console.WriteLine($"Request Body: {JsonSerializer.Serialize(requestData)}");

var response = await _httpClient.PostAsync(requestUrl, jsonContent);

if (!response.IsSuccessStatusCode)
{
Console.WriteLine($"API Error: {response.StatusCode}");
return $"Error: API Error: {response.StatusCode}";
}

return await response.Content.ReadAsStringAsync();
}
catch (Exception ex)
{
Console.WriteLine($"Request Failed: {ex.Message}");
return $"Error: {ex.Message}";
}
}
}
< /code>
using System.Reflection;

namespace closet_app;

public partial class TestPage : ContentPage
{
public TestPage()
{
InitializeComponent();
}

private bool _isLoading = false; // Track API call status

private async void ApiCall(object sender, EventArgs e)
{
if (_isLoading) return; // Prevent multiple calls
_isLoading = true;

try
{
LoadingIndicator.IsVisible = true;

var assembly = Assembly.GetExecutingAssembly();

// Load images from embedded resources
using var modelStream = assembly.GetManifestResourceStream("closet_app.Resources.Images.testmanmodel.jpg");
using var garmentStream = assembly.GetManifestResourceStream("closet_app.Resources.Images.testmodelshirt.jpg");

if (modelStream == null || garmentStream == null)
{
Console.WriteLine("Failed to load image resources.");
return;
}

// Save images as files
string modelPath = await SaveStreamToFileAsync(modelStream, "testmanmodel.jpg");
string garmentPath = await SaveStreamToFileAsync(garmentStream, "testmodelshirt.jpg");

if (string.IsNullOrEmpty(modelPath) || string.IsNullOrEmpty(garmentPath))
{
Console.WriteLine("Failed to save image resources.");
return;
}

var leffaService = new LeffaService();

if (!File.Exists(modelPath) || !File.Exists(garmentPath))
{
Console.WriteLine($"Error: One or both image files not found at {modelPath} and {garmentPath}");
return;
}

Console.WriteLine($"Model Path: {modelPath}");
Console.WriteLine($"Garment Path: {garmentPath}");

// Define parameters for the API call
var resultPath = await leffaService.CallLeffaPredictVTAsync(
modelPath,
garmentPath,
refAcceleration: "false",
step: 30,
scale: 2.5,
seed: 42,
vtModelType: "viton_hd",
vtGarmentType: "upper_body",
vtRepaint: "false",
preprocessGarment: false
);

Console.WriteLine($"Result Path: {resultPath}");

if (!string.IsNullOrEmpty(resultPath))
{
Console.WriteLine("Received valid response.");
var imageSource = ImageSource.FromFile(resultPath);
TestApiImg.Source = imageSource;
}
else
{
Console.WriteLine("Failed to get response from Leffa API.");
}
}
catch (Exception ex)
{
Console.WriteLine($"An error occurred: {ex.Message}");
}
finally
{
_isLoading = false;
LoadingIndicator.IsVisible = false;
}
}

private async Task SaveStreamToFileAsync(Stream stream, string fileName)
{
try
{
string tempPath = Path.Combine(FileSystem.AppDataDirectory, fileName);

using (var fileStream = File.Create(tempPath))
{
await stream.CopyToAsync(fileStream);
}

return tempPath;
}
catch (Exception ex)
{
Console.WriteLine($"Error saving file: {ex.Message}");
return string.Empty;
}
}
}


Подробнее здесь: https://stackoverflow.com/questions/795 ... otnet-maui
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «C#»