91 lines
2.7 KiB
Plaintext
91 lines
2.7 KiB
Plaintext
@page "/createform/{SiteId:int}"
|
|
@using System.IO
|
|
@using BLAIzor.Models
|
|
@using BLAIzor.Services
|
|
@using Microsoft.AspNetCore.Components.Forms
|
|
@using System.Text
|
|
@using UglyToad.PdfPig
|
|
@using BLAIzor.Components.Layout
|
|
@attribute [Authorize]
|
|
@layout AdminLayout
|
|
@inject ContentEditorService ContentEditorService
|
|
|
|
<h3>Create a new from from pdf or word</h3>
|
|
|
|
<InputFile OnChange="HandleFileSelected" />
|
|
|
|
@if (ExtractedFields.Any())
|
|
{
|
|
<h5>Extracted Fields:</h5>
|
|
<ul>
|
|
@foreach (var field in ExtractedFields)
|
|
{
|
|
<li><strong>@field.GroupName:</strong> @field.Fields.Count (@(field.Repeatable?"Repeatable":"Non repeateble"))</li>
|
|
}
|
|
</ul>
|
|
<div class="col-12">
|
|
<FormDescriptionEditor Groups="@ExtractedFields" TitleString="Form preview" isEditing=true></FormDescriptionEditor>
|
|
</div>
|
|
}
|
|
|
|
@code {
|
|
[Parameter]
|
|
public int SiteId { get; set; }
|
|
private string PdfText = string.Empty;
|
|
private List<FormFieldGroup> ExtractedFields = new();
|
|
|
|
private async Task HandleFileSelected(InputFileChangeEventArgs e)
|
|
{
|
|
var file = e.File;
|
|
if (file == null || !file.ContentType.Contains("pdf")) return;
|
|
|
|
var tempPath = Path.Combine(Path.GetTempPath(), file.Name);
|
|
|
|
await using (var stream = file.OpenReadStream())
|
|
await using (var fileStream = File.Create(tempPath))
|
|
{
|
|
await stream.CopyToAsync(fileStream);
|
|
}
|
|
|
|
PdfText = ExtractPdfText(tempPath);
|
|
|
|
// Call OpenAI to analyze and extract structured fields
|
|
ExtractedFields = await CallAiForFieldExtraction(PdfText);
|
|
}
|
|
|
|
private string ExtractPdfText(string filePath)
|
|
{
|
|
var sb = new StringBuilder();
|
|
using (var document = PdfDocument.Open(filePath))
|
|
{
|
|
foreach (var page in document.GetPages())
|
|
{
|
|
sb.AppendLine(page.Text);
|
|
}
|
|
}
|
|
return sb.ToString();
|
|
}
|
|
|
|
private async Task<List<FormFieldGroup>> CallAiForFieldExtraction(string plainText)
|
|
{
|
|
var jsonResult = await ContentEditorService.AnalyzeGroupedFormFieldsFromText(plainText);
|
|
Console.WriteLine($"📄 PDF form AI response: {jsonResult}");
|
|
|
|
try
|
|
{
|
|
var groups = System.Text.Json.JsonSerializer.Deserialize<List<FormFieldGroup>>(jsonResult, new System.Text.Json.JsonSerializerOptions
|
|
{
|
|
PropertyNameCaseInsensitive = true
|
|
});
|
|
|
|
return groups ?? new List<FormFieldGroup>();
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
Console.WriteLine($"❌ Error parsing AI JSON: {ex.Message}");
|
|
return new List<FormFieldGroup>();
|
|
}
|
|
}
|
|
|
|
|
|
} |