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,8 @@
*.env
*bin
*obj
*.exe
*.dll
*.pdb
*Debug
*.json
@@ -0,0 +1,15 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net9.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="DocumentFormat.OpenXml" Version="3.5.1" />
<PackageReference Include="PdfPig" Version="0.1.14" />
</ItemGroup>
</Project>
@@ -0,0 +1,124 @@
using System.Net.Http;
using System.Text;
using System.Text.Json;
using System.Text.Json.Serialization;
using UglyToad.PdfPig;
using UglyToad.PdfPig.Content;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Wordprocessing;
static string ExtractText(string filePath)
{
var ext = Path.GetExtension(filePath).ToLowerInvariant();
return ext switch
{
".pdf" => ExtractFromPdf(filePath),
".docx" => ExtractFromDocx(filePath),
_ => throw new NotSupportedException($"Unsupported file type: {ext}")
};
}
static string ExtractFromPdf(string filePath)
{
var sb = new StringBuilder();
using var document = PdfDocument.Open(filePath);
foreach (Page page in document.GetPages())
sb.AppendLine(page.Text);
return sb.ToString();
}
static string ExtractFromDocx(string filePath)
{
var sb = new StringBuilder();
using var doc = WordprocessingDocument.Open(filePath, false);
var body = doc.MainDocumentPart?.Document?.Body;
if (body is null) return string.Empty;
foreach (var para in body.Descendants<Paragraph>())
sb.AppendLine(para.InnerText);
return sb.ToString();
}
var inputFile = args.Length > 0 ? args[0] : throw new Exception("Pass a file path as argument.");
var text = ExtractText(inputFile);
var client = new HttpClient();
client.Timeout = TimeSpan.FromMinutes(10);
var url = "http://192.168.178.214:11434/api/generate";
var body = new
{
model = "qwen3-vl:8b-instruct",
prompt = $@"Extract order data from the document below and return it as JSON.
CRITICAL RULES — read before extracting:
- ONLY use values that are explicitly written in the document
- If a field is not present in the document, use """" for strings or 0 for numbers
- NEVER invent, guess, or infer values that are not clearly stated
- NEVER generate product codes, reference numbers, or relation codes unless they appear word-for-word in the document
- Referentie = PO Number if present, otherwise """"
- Relatiecode = customer/relation code if explicitly labeled as such, otherwise """"
- productcode = numeric code explicitly labeled as a product/article code, otherwise 0
- ONLY return the json data, no other explenations or other text than the json
Output ONLY this JSON structure:
[{{
""order"": {{
""Naam"": ""<customer name from document or empty>"",
""Datum"": ""<date in yyyy-MM-dd or empty>"",
""Relatiecode"": ""<relation code if explicitly present, else empty>"",
""Referentie"": ""<PO number if explicitly present, else empty>"",
""regels"": [
{{
""productcode"": <integer code if explicitly present, else 0>,
""omschrijving"": ""<product description>"",
""aantal"": <quantity as integer>,
""prijs"": <unit price as decimal>
}}
]
}}
}}]
Document:
{text}
",
system = @"You are a strict document-to-JSON data extractor for order processing.
Your job is EXTRACTION ONLY — not inference, not completion, not enrichment.
You ONLY output valid JSON matching the exact schema provided.
You NEVER output explanations, markdown, code blocks, or comments.
You NEVER add fields not in the schema.
Anti-hallucination rules:
- If you are not 100% certain a value appears in the document, leave it empty or 0
- Product codes, reference numbers, and relation codes are NEVER made up — they must appear verbatim in the document
- Do not infer a product code from a product name or description
- Do not infer a relation code from a customer name
- Do not infer a reference from an invoice number unless explicitly labeled as PO or reference
- When in doubt, use empty string or 0
Data type rules:
- Datum must be yyyy-MM-dd format
- productcode and aantal must be integers
- prijs must be a decimal number
- All string values use double quotes
- No trailing commas
Your entire response must be JSON and nothing else.",
keep_alive = "24h",
stream = false
};
var json = JsonSerializer.Serialize(body);
var content = new StringContent(json, Encoding.UTF8, "application/json");
var response = await client.PostAsync(url, content);
var result = await response.Content.ReadAsStringAsync();
var parsed = JsonSerializer.Deserialize<OllamaResponse>(result);
Console.WriteLine(parsed?.Response);
record OllamaResponse([property: JsonPropertyName("response")] string Response);
@@ -0,0 +1,23 @@
Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.5.2.0
MinimumVisualStudioVersion = 10.0.40219.1
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{435B0DD4-35E4-8754-9856-0EBD55269029}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{435B0DD4-35E4-8754-9856-0EBD55269029}.Debug|Any CPU.Build.0 = Debug|Any CPU
{435B0DD4-35E4-8754-9856-0EBD55269029}.Release|Any CPU.ActiveCfg = Release|Any CPU
{435B0DD4-35E4-8754-9856-0EBD55269029}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {CFD9A1B3-04B0-4CB5-9F51-6DCD267FC919}
EndGlobalSection
EndGlobal
@@ -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();
}
}
}
@@ -0,0 +1,19 @@
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="ClosedXML" Version="0.105.0" />
<PackageReference Include="DocumentFormat.OpenXml" Version="3.5.1" />
<PackageReference Include="EPPlus" Version="8.5.1" />
<PackageReference Include="ExcelDataReader" Version="3.8.0" />
<PackageReference Include="ExcelDataReader.DataSet" Version="3.8.0" />
<PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="10.0.5" />
<PackageReference Include="UglyToad.PdfPig" Version="1.7.0-custom-5" />
</ItemGroup>
</Project>
@@ -0,0 +1,6 @@
@FileConverterAPI_HostAddress = http://localhost:5037
GET {{FileConverterAPI_HostAddress}}/weatherforecast/
Accept: application/json
###
@@ -0,0 +1,20 @@
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers();
// CORS (nodig voor frontend)
builder.Services.AddCors(options =>
{
options.AddPolicy("AllowAll",
policy => policy.AllowAnyOrigin()
.AllowAnyHeader()
.AllowAnyMethod());
});
var app = builder.Build();
app.UseCors("AllowAll");
app.MapControllers();
app.Run();
@@ -0,0 +1,153 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>converter</title>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<nav class="navbar">
<h1>Converter</h1>
</nav>
<!-- Upload Box -->
<div id="dropZone" class="box upload-box">
<div class="upload-icon" aria-hidden="true">
<svg viewBox="0 0 24 24" role="presentation">
<path d="M12 15V5" />
<path d="M8 9L12 5L16 9" />
<path d="M5 13V17C5 18.1 5.9 19 7 19H17C18.1 19 19 18.1 19 17V13" />
</svg>
</div>
<h2>Sleep je bestand hierheen</h2>
<p>of klik om te bladeren</p>
<div class="file-types">
<!-- ✅ FIX: added accept -->
<input id="filePicker" type="file" accept=".xlsx,.xls,.pdf,.docx" hidden />
<button id="openFilePicker" class="tag excel" type="button">
Bestand zoeken
</button>
</div>
</div>
<div class="middle-arrow" aria-hidden="true"></div>
<!-- Result Box -->
<div class="box2 result-box">
<div class="file-icon" aria-hidden="true"></div>
<p id="fileName" class="file-name">bestandsnaam.json</p>
<p id="downloadStatus" class="download-status" aria-live="polite"></p>
<div class="file-separator" aria-hidden="true"></div>
<button id="downloadBtn" class="download-button" type="button">
<svg
class="download-icon"
viewBox="0 0 24 24"
role="presentation"
aria-hidden="true"
>
<path d="M12 15V6" />
<path d="M8.5 11.5L12 15L15.5 11.5" />
<path d="M6 17.5H18" />
</svg>
<span>Download JSON</span>
</button>
</div>
<script>
const openFilePickerButton = document.getElementById("openFilePicker");
const filePickerInput = document.getElementById("filePicker");
const downloadBtn = document.getElementById("downloadBtn");
const dropZone = document.getElementById("dropZone");
const fileNameText = document.getElementById("fileName");
const downloadStatusText = document.getElementById("downloadStatus");
const downloadBtnLabel = downloadBtn.querySelector("span");
let selectedFile = null;
openFilePickerButton.addEventListener("click", () => {
filePickerInput.click();
});
filePickerInput.addEventListener("change", () => {
selectedFile = filePickerInput.files[0];
if (selectedFile) {
fileNameText.textContent = selectedFile.name;
}
});
dropZone.addEventListener("dragover", (e) => {
e.preventDefault();
});
dropZone.addEventListener("drop", (e) => {
e.preventDefault();
selectedFile = e.dataTransfer.files[0];
if (selectedFile) {
fileNameText.textContent = selectedFile.name;
}
});
downloadBtn.addEventListener("click", async () => {
if (!selectedFile) {
alert("Select a file first!");
return;
}
const formData = new FormData();
formData.append("file", selectedFile);
downloadBtn.disabled = true;
downloadBtnLabel.textContent = "Downloaden...";
downloadStatusText.textContent = "Bezig met downloaden...";
try {
const response = await fetch("http://localhost:5037/api/upload", {
method: "POST",
body: formData,
});
// ✅ FIX: show real error
if (!response.ok) {
const errorText = await response.text();
console.error("Backend error:", errorText);
downloadStatusText.textContent = "Download mislukt.";
alert("Upload failed: " + errorText);
return;
}
const blob = await response.blob();
const url = window.URL.createObjectURL(blob);
const a = document.createElement("a");
a.href = url;
a.download = "converted.json";
document.body.appendChild(a);
a.click();
a.remove();
window.URL.revokeObjectURL(url);
downloadStatusText.textContent = "Download voltooid.";
} catch (error) {
console.error(error);
downloadStatusText.textContent =
"Er ging iets fout tijdens downloaden.";
alert("Error uploading file");
} finally {
downloadBtn.disabled = false;
downloadBtnLabel.textContent = "Download JSON";
}
});
</script>
</body>
</html>
@@ -0,0 +1,228 @@
html,
body {
background-color: rgb(220, 220, 220);
margin: 0;
height: 100%;
min-height: 100vh;
overflow: hidden;
display: flex;
justify-content: center;
align-items: center;
gap: 110px;
padding-top: 80px;
font-family: "Segoe UI", Tahoma, sans-serif;
}
.navbar {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 64px;
background-color: rgb(0, 0, 0);
display: flex;
align-items: center;
padding: 0 24px;
box-sizing: border-box;
color: white;
z-index: 1000;
}
.navbar h1 {
margin: 0;
font-size: 24px;
}
.box {
width: 350px;
background-color: rgb(243, 243, 243);
height: 350px;
border: 2px dashed rgb(187, 187, 187);
box-sizing: border-box;
border-radius: 6px;
margin-bottom: 3cm;
}
.box2 {
width: 350px;
background-color: rgb(243, 243, 243);
height: 350px;
border: 2px dashed rgb(187, 187, 187);
box-sizing: border-box;
border-radius: 6px;
margin-bottom: 3cm;
}
.upload-box {
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
text-align: center;
}
.upload-icon {
width: 64px;
height: 64px;
border: 1px solid rgb(174, 212, 226);
border-radius: 5px;
background-color: rgb(221, 236, 244);
display: flex;
align-items: center;
justify-content: center;
margin-bottom: 14px;
}
.upload-icon svg {
width: 34px;
height: 34px;
}
.upload-icon path {
fill: none;
stroke: rgb(41, 159, 196);
stroke-width: 1.8;
stroke-linecap: round;
stroke-linejoin: round;
}
.upload-box h2 {
margin: 1cm;
color: rgb(40, 40, 40);
font-size: 18px;
font-weight: 7 00;
line-height: 1.25;
}
.upload-box p {
margin: 16px 0 18px;
color: rgb(123, 142, 154);
font-size: 18px;
}
.file-types {
display: flex;
gap: 8px;
}
.tag {
color: white;
font-size: 20px;
font-weight: 700;
line-height: 1;
padding: 7px 13px;
border-radius: 2px;
border: 0;
cursor: pointer;
}
.tag.excel {
background-color: rgb(87, 169, 50);
}
.tag.word {
background-color: rgb(44, 166, 209);
}
.tag:hover {
filter: brightness(0.95);
}
.result-box {
display: flex;
flex-direction: column;
align-items: center;
padding: 58px 34px 30px;
}
.file-icon {
width: 66px;
height: 58px;
border-radius: 4px;
background: linear-gradient(
145deg,
rgb(239, 239, 239),
rgb(229, 229, 229)
);
opacity: 0.7;
}
.file-name {
margin: 18px 0 16px;
color: rgb(0, 0, 0);
font-size: 24px;
font-weight: 700;
}
.download-status {
min-height: 24px;
margin: 0 0 10px;
color: rgb(90, 90, 90);
font-size: 16px;
font-weight: 600;
}
.file-separator {
width: 18px;
background-color: rgb(213, 213, 213);
margin-bottom: 48px;
}
.download-button {
width: 100%;
height: 72px;
border: 0;
border-radius: 4px;
background-color: rgb(180, 180, 180);
color: rgb(250, 250, 250);
font-size: 20px;
font-weight: 700;
display: flex;
align-items: center;
justify-content: center;
gap: 12px;
cursor: pointer;
}
.download-button:hover {
background-color: rgb(168, 168, 168);
}
.download-button:disabled {
background-color: rgb(145, 145, 145);
cursor: wait;
}
.download-icon {
width: 30px;
height: 30px;
}
.download-icon path {
fill: none;
stroke: rgb(250, 250, 250);
stroke-width: 2;
stroke-linecap: round;
stroke-linejoin: round;
}
.middle-arrow {
position: relative;
width: 56px;
height: 3px;
background-color: rgb(183, 183, 183);
margin-bottom: 3cm;
}
.middle-arrow::after {
content: "";
position: absolute;
right: -9px;
top: 50%;
transform: translateY(-50%);
border-top: 7px solid transparent;
border-bottom: 7px solid transparent;
border-left: 9px solid rgb(183, 183, 183);
}