AiGetAbstract.cs
//
// This code is part of Document Solutions for PDF demos.
// Copyright (c) MESCIUS inc. All rights reserved.
//
using System;
using System.IO;
using System.Drawing;
using GrapeCity.Documents.Pdf;
using GrapeCity.Documents.Text;
using GrapeCity.Documents.Pdf.AI;
using DsPdfWeb.Demos.Common;
using System.Threading.Tasks;

namespace DsPdfWeb.Demos
{
    // This sample uses the PDF AI Assistant (DsPdfAI) to analyze the document content,
    // generate an abstract summarizing the PDF, and insert it as the first page.
    //
    // An abstract is a concise and formal description of the document's purpose and scope,
    // typically used in academic or technical contexts.
    // See the AiGetSummary sample for how to generate a summary of a PDF.
    //
    // To run this sample locally, set your OpenAI credentials
    // using Util.OpenAIToken.
    public class AiGetAbstract
    {
        public int CreatePDF(Stream stream)
        {
            var doc = new GcPdfDocument();
            using var fs = File.OpenRead(Path.Combine("Resources", "PDFs", "Wetlands.pdf"));
            doc.Load(fs);
            try
            {
                var a = new OpenAIDocumentAssistant(Util.OpenAIToken);
                var task = a.GetAbstract(doc);
                task.Wait();
                var page = doc.Pages.Insert(0);
                Util.AddNote("Abstract generated using DsPdf AI Assistant\n\n" + task.Result, page);
            }
            catch (Exception ex)
            {
                // Make sure you have assigned your OpenAI API key to Util.OpenAIToken:
                Util.CreatePdfError(doc, ex.Message);
            }
            doc.Save(stream);
            return doc.Pages.Count;
        }
    }
}