Я использую эту модель искусственного интеллекта в приложении, которое я создает в 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
Integration API API API Gradio в Dotnet Maui ⇐ C#
Место общения программистов C#
-
Anonymous
1758922668
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;
}
}
}
Подробнее здесь: [url]https://stackoverflow.com/questions/79544654/gradio-app-api-integration-in-dotnet-maui[/url]
Ответить
1 сообщение
• Страница 1 из 1
Перейти
- Кемерово-IT
- ↳ Javascript
- ↳ C#
- ↳ JAVA
- ↳ Elasticsearch aggregation
- ↳ Python
- ↳ Php
- ↳ Android
- ↳ Html
- ↳ Jquery
- ↳ C++
- ↳ IOS
- ↳ CSS
- ↳ Excel
- ↳ Linux
- ↳ Apache
- ↳ MySql
- Детский мир
- Для души
- ↳ Музыкальные инструменты даром
- ↳ Печатная продукция даром
- Внешняя красота и здоровье
- ↳ Одежда и обувь для взрослых даром
- ↳ Товары для здоровья
- ↳ Физкультура и спорт
- Техника - даром!
- ↳ Автомобилистам
- ↳ Компьютерная техника
- ↳ Плиты: газовые и электрические
- ↳ Холодильники
- ↳ Стиральные машины
- ↳ Телевизоры
- ↳ Телефоны, смартфоны, плашеты
- ↳ Швейные машинки
- ↳ Прочая электроника и техника
- ↳ Фототехника
- Ремонт и интерьер
- ↳ Стройматериалы, инструмент
- ↳ Мебель и предметы интерьера даром
- ↳ Cантехника
- Другие темы
- ↳ Разное даром
- ↳ Давай меняться!
- ↳ Отдам\возьму за копеечку
- ↳ Работа и подработка в Кемерове
- ↳ Давай с тобой поговорим...
Мобильная версия