Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
134 changes: 134 additions & 0 deletions Videos/WordSummarizerWithAzureOpenAI/Program.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,134 @@
using Azure.AI.OpenAI;
using OpenAI.Chat;
using Syncfusion.DocIO.DLS;
using System.ClientModel;

namespace WordSummarizerWithAzureOpenAI
{
internal class Program
{
static async Task Main(string[] args)
{
// Replace with your Azure OpenAI API key
string? azureOpenAIApiKey = "Replace your Azure OpenAI key";

// Start the Word document summarization process
await ExcuteSummarization(azureOpenAIApiKey);
}

/// <summary>
/// Execute summarization of Word document.
/// </summary>
private async static Task ExcuteSummarization(string azureOpenAIApiKey)
{
// Display application title
Console.WriteLine("AI Powered Word Summarizer");

// Prompt user for the input Word document path
Console.WriteLine("Enter full Word file path (e.g., C:\\Data\\Input.docx):");
string? wordFilePath = Console.ReadLine()?.Trim().Trim('"');

// Prompt user for the desired summary length
Console.WriteLine("Please enter the number of sentences you would like the summary to be (e.g., 3, 5):");
string? sentencesCount = Console.ReadLine()?.Trim().Trim('"');

// Validate the Word document path
if (string.IsNullOrWhiteSpace(wordFilePath) || !File.Exists(wordFilePath))
{
Console.WriteLine("Invalid path. Exiting.");
return;
}

// Validate the sentence count input
if (string.IsNullOrWhiteSpace(sentencesCount) || !int.TryParse(sentencesCount, out int result))
{
Console.WriteLine("Invalid Count. Exiting.");
return;
}

// Ensure the Azure OpenAI API key is available
if (string.IsNullOrWhiteSpace(azureOpenAIApiKey))
{
Console.WriteLine("AZURE_OPENAI_API_KEY not set. Exiting.");
return;
}

try
{
// Generate and save the summarized Word document
await SummarizeWordContent(azureOpenAIApiKey, wordFilePath, sentencesCount);
}
catch (Exception ex)
{
// Handle summarization errors
Console.WriteLine($"Failed to summarize Word document: {ex.StackTrace}");
return;
}
}

/// <summary>
/// Reads the content of a Word document, generates a summary using Azure OpenAI,
/// and saves the summarized content as a new Word document.
/// </summary>
private static async Task SummarizeWordContent(string azureOpenAIApiKey, string wordFilePath, string sentencesCount)
{
// Load the source Word document
WordDocument wordDocument = new WordDocument(wordFilePath);

// Create a prompt instructing the AI to summarize the content
string systemPrompt = @"You are a professional document summarizer integrated into an DocIO automation tool.
Your job is to summarize the word document content into the"" + sentencesCount + "" sentences";

// Extract all text from the document
string originalText = wordDocument.GetText();

// Close the source document after reading
wordDocument.Close();

// Send document content to Azure OpenAI and get the summary
string summarizedText = await AskAzureOpenAIAsync(azureOpenAIApiKey, systemPrompt, originalText);

// Create a new Word document to store the summary
WordDocument summarizedDocument = new WordDocument();
summarizedDocument.EnsureMinimal();

// Add the summarized text to the document
summarizedDocument.LastParagraph.AppendText(summarizedText);

// Save the summarized document with a new file name
summarizedDocument.Save(wordFilePath.Replace(".docx", "_DocIOsummarized.docx"));

// Close the summarized document
summarizedDocument.Close();
}

/// <summary>
/// Sends a chat completion request to OpenAI and returns the response.
/// </summary>
/// <param name="apiKey">Azure OpenAI API key.</param>
/// <param name="model">Model name.</param>
/// <param name="systemPrompt">System prompt.</param>
/// <param name="userContent">User content.</param>
/// <returns>AI-generated response as a string.</returns>
private static async Task<string> AskAzureOpenAIAsync(string apiKey, string systemPrompt, string userContent)
{
// Create the Azure OpenAI client using the endpoint and API key
AzureOpenAIClient azureClient = new(
new Uri("https://your-resource-name.openai.azure.com/"),
new ApiKeyCredential(apiKey)
);

// Create chat client for the specified mode
ChatClient chatClient = azureClient.GetChatClient("your-model-name");

// Send the system prompt and document content to the model
ClientResult<ChatCompletion> chatResult = await chatClient.CompleteChatAsync(
new SystemChatMessage(systemPrompt),
new UserChatMessage(userContent));

// Extract the generated summary from the response
string response = chatResult.Value.Content[0].Text ?? string.Empty;
return response;
}
}
}
46 changes: 46 additions & 0 deletions Videos/WordSummarizerWithAzureOpenAI/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
# Build an AI-Powered Word Document Summarizer Using the .NET Word Library

This repository provides an example of how to summarize the content of a Word document using **Azure OpenAI** and the **[.NET Word Library](https://www.syncfusion.com/document-sdk/net-word-library) (DocIO)**. The sample reads text from a Word document, generates an AI-powered summary, and saves the summarized content as a new Word document.

## Process Behind Word Document Summarization

This sample demonstrates how to automate document summarization by combining the document-processing capabilities of the **.NET Word Library (DocIO)** with the natural language processing capabilities of **Azure OpenAI**.

The workflow consists of the following steps:

1. Load and read the content of a Word document.
2. Extract the document text using DocIO.
3. Send the extracted content to Azure OpenAI with a summarization prompt.
4. Generate a concise summary based on the specified number of sentences.
5. Create a new Word document containing the generated summary.
6. Save the summarized content as a new Word document.

## Prerequisites

Before running the sample, ensure that you have:

- An Azure OpenAI resource.
- A deployed chat model in Azure OpenAI.
- A valid Azure OpenAI API key.
- The Syncfusion DocIO NuGet package installed.

## Steps to Use the Sample

1. Open the application where the Syncfusion DocIO package is installed.
2. Replace the following placeholders in the code:
- `Replace your Azure OpenAI key` with your Azure OpenAI API key.
- `https://your-resource-name.openai.azure.com/` with your Azure OpenAI endpoint.
- `your-model-name` with your deployed Azure OpenAI model name.
3. Run the application.
4. Enter the full path of the Word document to summarize.
5. Specify the number of sentences required in the summary.
6. The application generates the summary and saves it as a new Word document.

## Input

- Source Word document (`.docx`)
- Desired summary length (number of sentences)

## Output

A new Word document containing the summarized content:
Original file line number Diff line number Diff line change
@@ -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="Azure.AI.OpenAI" Version="2.1.0" />
<PackageReference Include="Syncfusion.DocIO.Net.Core" Version="*" />
</ItemGroup>

</Project>
2 changes: 1 addition & 1 deletion Videos/WordToText/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

This repository provides an example of how to convert a Word document to a text file using the **[.NET Word Library](https://www.syncfusion.com/document-sdk/net-word-library) (DocIO)**. It also demonstrates converting a text file back to a Word document and extracting plain text from a Word document.

## Process behind WordText Conversion
## Process behind Word-Text Conversion

This sample shows how you can easily switch between Word and text formats using the [.NET Word Library](https://www.syncfusion.com/document-sdk/net-word-library). These conversions are essential for scenarios such as storing content in a lightweight text format for efficient processing or extracting text for indexing and search operations.

Expand Down
Loading