This commit is contained in:
Alvin-Zilverstand committed 2026-09-09 10:45:31 +02:00
1 parent f3e79a7aeb
commit d420c317ab
88 files changed
+36601

No files matched your search

@@ -0,0 +1,305 @@
using Microsoft.AspNetCore.Mvc;
using System.Text;
using System.Text.Json;
using ExcelDataReader;
using System.Data;
using UglyToad.PdfPig;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Wordprocessing;
namespace FileConverterAPI.Controllers
{
[ApiController]
[Route("api/[controller]")]
public class UploadController : ControllerBase
{
[HttpPost]
public async Task<IActionResult> UploadFile(IFormFile file)
{
if (file == null || file.Length == 0)
return BadRequest("No file uploaded");
string text;
try
{
var ext = Path.GetExtension(file.FileName).ToLower();
text = ext switch
{
".xls" or ".xlsx" => ReadExcel(file),
".pdf" => ReadPdf(file),
".docx" => ReadWord(file),
_ => throw new Exception("Unsupported file type")
};
}
catch (Exception ex)
{
return BadRequest("FILE ERROR: " + ex.Message);
}
// stuurt het hele document zodat de ai alles pakt
var aiResponse = await SendToOllama(text);
var json = ExtractJson(aiResponse);
var finalResult = ParseJson(json);
var prettyJson = JsonSerializer.Serialize(finalResult, new JsonSerializerOptions
{
WriteIndented = true
});
return File(
Encoding.UTF8.GetBytes(prettyJson),
"application/json",
"converted.json"
);
}
// ---------------- OLLAMA ----------------
private async Task<string> SendToOllama(string text)
{
using var client = new HttpClient();
client.Timeout = TimeSpan.FromMinutes(10);
var body = new
{
model = "qwen2.5-coder:3b",
//model = "qwen3-vl:8b-instruct",
messages = new[]
{
new
{
role = "system",
content = $@"Je bent een extreem strikte document-naar-JSON extractor.
Jouw ENIGE taak is het extraheren van gegevens uit een document naar EXACT de toegestane JSON structuur.
ABSOLUTE REGELS:
- Retourneer UITSLUITEND geldige JSON
- Retourneer EXACT de opgegeven structuur
- ALLE andere structuren zijn VERBODEN
- ALLE velden buiten de toegestane structuur zijn VERBODEN
- GEEN extra velden
- GEEN extra objecten
- GEEN extra arrays
- GEEN uitleg
- GEEN markdown
- GEEN comments
- GEEN tekst buiten de JSON
- GEEN Engelse veldnamen
- ALLES moet Nederlands blijven
VERBODEN VELDEN:
- totalAmount
- currency
- invoiceDate
- dueDate
- vatRate
- vatExemptionReason
- customer
- supplier
- paymentTerms
- items
- discounts
- tax
- grossAmount
- netAmount
- deliveryNotes
- bankDetails
- contactInformation
- itemNumber
- quantity
- totalPrice
- unitPrice
- invoiceNumber
- subtotal
- btw
- leverancier
- klant
- adres
- iban
- bic
ALLEEN DEZE VELDEN ZIJN TOEGESTAAN:
- order
- Naam
- Datum
- Relatiecode
- Referentie
- regels
- productcode
- omschrijving
- aantal
- prijs
EXTRACTIE REGELS:
- Gebruik ALLEEN waarden die letterlijk in het document staan
- NOOIT gokken
- NOOIT afleiden
- NOOIT aanvullen
- NOOIT hernoemen van velden
- Indien een waarde ontbreekt:
- gebruik """" voor strings
- gebruik 0 voor integers
- gebruik 0.00 voor decimalen
- productcode mag ALLEEN gevuld worden indien expliciet vermeld als productcode, artikelcode of numerieke code
- Relatiecode mag ALLEEN gevuld worden indien expliciet gelabeld
- Referentie mag ALLEEN gevuld worden indien expliciet gelabeld als referentie of PO-nummer
- Datum MOET yyyy-MM-dd formaat gebruiken
DE OUTPUT MOET EXACT DIT FORMAAT HEBBEN:
[
{{
""order"": {{
""Naam"": """",
""Datum"": """",
""Relatiecode"": """",
""Referentie"": """",
""regels"": [
{{
""productcode"": 0,
""omschrijving"": """",
""aantal"": 0,
""prijs"": 0.00
}}
]
}}
}}
]
IEDERE OUTPUT DIE NIET EXACT DEZE STRUCTUUR GEBRUIKT IS ONGELDIG.
"
},
new
{
role = "user",
content = text
}
},
keep_alive = "24h",
stream = false
};
var json = JsonSerializer.Serialize(body);
var content = new StringContent(json, Encoding.UTF8, "application/json");
var response = await client.PostAsync("http://localhost:11434/api/chat", content);
//var response = await client.PostAsync("http://192.168.178.214:11434/api/chat", content);
var raw = await response.Content.ReadAsStringAsync();
using var doc = JsonDocument.Parse(raw);
if (!doc.RootElement.TryGetProperty("message", out var message))
return "";
if (!message.TryGetProperty("content", out var contentText))
return "";
return contentText.GetString() ?? "";
}
// ---------------- PARSE JSON RESPONSE ----------------
private Dictionary<string, object> ParseJson(string json)
{
var result = new Dictionary<string, object>();
try
{
if (string.IsNullOrWhiteSpace(json))
return result;
using var doc = JsonDocument.Parse(json);
foreach (var prop in doc.RootElement.EnumerateObject())
{
result[prop.Name] = prop.Value.GetRawText();
}
}
catch
{
// als het faalt geef niks terug
}
return result;
}
// ---------------- JSON ----------------
private string ExtractJson(string input)
{
if (string.IsNullOrWhiteSpace(input))
return "";
int start = input.IndexOf('{');
int end = input.LastIndexOf('}');
if (start == -1 || end == -1 || end <= start)
return "";
return input.Substring(start, end - start + 1);
}
// ---------------- EXCEL ----------------
private string ReadExcel(IFormFile file)
{
Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
using var stream = new MemoryStream();
file.CopyTo(stream);
stream.Position = 0;
using var reader = ExcelReaderFactory.CreateReader(stream);
var ds = reader.AsDataSet();
var sb = new StringBuilder();
foreach (DataTable table in ds.Tables)
{
foreach (DataRow row in table.Rows)
{
foreach (var cell in row.ItemArray)
sb.Append(cell?.ToString() + " ");
sb.AppendLine();
}
}
return sb.ToString();
}
// ---------------- PDF ----------------
private string ReadPdf(IFormFile file)
{
var sb = new StringBuilder();
using var stream = new MemoryStream();
file.CopyTo(stream);
stream.Position = 0;
using var doc = PdfDocument.Open(stream);
foreach (var page in doc.GetPages())
sb.AppendLine(page.Text);
return sb.ToString();
}
// ---------------- WORD ----------------
private string ReadWord(IFormFile file)
{
var sb = new StringBuilder();
using var stream = new MemoryStream();
file.CopyTo(stream);
stream.Position = 0;
using var doc = WordprocessingDocument.Open(stream, false);
var body = doc.MainDocumentPart.Document.Body;
foreach (var t in body.Descendants<Text>())
sb.Append(t.Text + " ");
return sb.ToString();
}
}
}