Код: Выделить всё
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}";
}
}
}
Подробнее здесь: https://stackoverflow.com/questions/790 ... ot-working
Мобильная версия