Анализ документов с помощью LLAVA на Олламе не работаетC#

Место общения программистов C#
Ответить
Anonymous
 Анализ документов с помощью LLAVA на Олламе не работает

Сообщение Anonymous »

В настоящее время я тестирую LLAVA для использования в задачах понимания документов. Я нашел некоторые многообещающие результаты в некоторых научных статьях и на некоторых веб-сайтах. Я установил модель на Олламе (в Windows) и попытался получить к ней доступ с помощью этого кода C#.

Код: Выделить всё

using System.Text;
using System.Text.Json;

public class Program
{
private static readonly HttpClient client = new HttpClient();
private static string? imageBase64;

static async Task Main(string[] args)
{
Console.WriteLine("Welcome to the Document Analysis Application!");

while (true)
{
Console.Write("Enter the path to the image file (or 'exit' to quit): ");
string imagePath;
do
{
imagePath = Console.ReadLine() ?? "";
} while (String.IsNullOrEmpty(imagePath));

if (imagePath.ToLower() == "exit")
break;

if (!File.Exists(imagePath))
{
Console.WriteLine("File not found. Please try again.");
continue;
}

imageBase64 = Convert.ToBase64String(File.ReadAllBytes(imagePath));
Console.WriteLine("Image loaded successfully.");

while (true)
{
Console.Write("Enter your question about the document (or 'new' for a new image, 'exit' to quit): ");
string question;
do
{
question = Console.ReadLine() ?? "";
} while (String.IsNullOrEmpty(question));

if (question.ToLower() == "new")
break;
if (question.ToLower() == "exit")
return;

Console.WriteLine("Response:");
_ = await AnalyzeDocument(question);
Console.WriteLine("\nEnd of response.");
}
}
}

static async Task AnalyzeDocument(string question)
{
var requestBody = new
{
model = "llava:13b-v1.6",
prompt = $"Analyze this invoice image carefully. Pay close attention to all numerical values, especially totals and subtotals. If the question is about a total or sum, make sure to double-check your calculation.  After your analysis, provide a clear, concise answer to this specific question: {question}",
images = new[] { imageBase64 },
stream = true
};

var content = new StringContent(JsonSerializer.Serialize(requestBody), Encoding.UTF8, "application/json");

try
{
HttpResponseMessage response = await client.PostAsync("http://localhost:11434/api/generate", content);
response.EnsureSuccessStatusCode();

using (var reader = new StreamReader(await response.Content.ReadAsStreamAsync()))
{
StringBuilder fullResponse = new StringBuilder();
string? line;
while ((line = await reader.ReadLineAsync()) != null)
{
if (string.IsNullOrWhiteSpace(line)) continue;

try
{
using (JsonDocument doc = JsonDocument.Parse(line))
{
JsonElement root = doc.RootElement;
if (root.TryGetProperty("response", out JsonElement responseElement))
{
string responsePart = responseElement.GetString() ?? "";
fullResponse.Append(responsePart);
Console.Write(responsePart); // Print each part as it's received
}
if (root.TryGetProperty("done", out JsonElement doneElement) && doneElement.GetBoolean())
{
break;
}
}
}
catch (JsonException)
{
Console.WriteLine($"Failed to parse JSON: {line}");
}
}
return fullResponse.ToString();
}
}
catch (HttpRequestException e)
{
return $"Error: {e.Message}";
}
}
}
К сожалению, результаты очень плохие и в основном это галлюцинации. Иногда LLM жалуется, что для ответа на вопросы потребуется более четкое представление документа. Я пробовал уменьшить масштаб изображения, но это все равно не помогло. Возможно, есть способ обработать изображение несколькими частями.

Подробнее здесь: https://stackoverflow.com/questions/790 ... ot-working
Ответить

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

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

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

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

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