using System;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using xAiModels.Models;
using xCommons.Extensions;
using OfficeIMO.PowerPoint;
using xExceptions.Constants;
using System.Threading.Tasks;
using System.Collections.Generic;
using xAiApi.Interfaces.Extractors;
using DocumentFormat.OpenXml.Packaging;
using DrawingText = DocumentFormat.OpenXml.Drawing.Text;
namespace xAiApi.Providers.Extractors
{
///
/// Extracts content from all PowerPoint formats
/// (OpenXML: pptx/ppsx/potx/pptm/ppsm/potm | Legacy Binary: ppt/pps/pot)
///
public class XPowerPointFileContentExtractor : IXPowerPointFileContentExtractor
{
///
/// Supported MIME Types ...
///
private static readonly string[] SupportedMimeTypes =
[
// OpenXML Formats
"application/vnd.openxmlformats-officedocument.presentationml.presentation", // .pptx
"application/vnd.openxmlformats-officedocument.presentationml.slideshow", // .ppsx
"application/vnd.openxmlformats-officedocument.presentationml.template", // .potx
"application/vnd.ms-powerpoint.presentation.macroEnabled.12", // .pptm
"application/vnd.ms-powerpoint.slideshow.macroEnabled.12", // .ppsm
"application/vnd.ms-powerpoint.template.macroEnabled.12", // .potm
// Legacy Binary Formats (.ppt / .pps / .pot share same MIME)
"application/vnd.ms-powerpoint"
];
///
/// Check if this extractor supports the specified MIME type ...
///
public bool CanExtract(string mimeType)
{
//
return SupportedMimeTypes.Contains(
mimeType?.ToLowerInvariant() ?? string.Empty
);
}
///
/// Extract text content from file stream ...
///
public async Task ExtractAsync(
Stream fileStream,
string mimeType,
CancellationToken cancellationToken = default
)
{
//
var result = await ExtractRichAsync(
fileStream: fileStream,
fileName: "presentation",
mimeType: mimeType,
cancellationToken: cancellationToken
);
return result.Text;
}
///
/// Extract content from stream as Rich Result ...
///
///
///
///
///
///
public async Task ExtractRichAsync(
Stream fileStream,
string fileName,
string mimeType,
CancellationToken cancellationToken = default
)
{
//
var result = new XFileExtractionResult
{
FileName = fileName,
MimeType = mimeType
};
//
try
{
//
if (IsOpenXmlFormat(mimeType))
{
//
result.Text = await ExtractOpenXmlAsync(
fileStream,
cancellationToken
);
}
else if (IsLegacyFormat(mimeType))
{
//
result.Text = await ExtractLegacyAsync(
fileStream,
cancellationToken
);
}
else
{
//
result.ErrorMessage =
$"Unsupported PowerPoint MIME type: {mimeType}";
}
}
catch (Exception ex)
{
result.ErrorMessage =
$"PowerPoint extraction failed: {ex.Message}";
}
//
return result;
}
///
/// Check Open XML Format ...
///
///
///
private bool IsOpenXmlFormat(string mimeType)
{
//
var result = mimeType?.ToLowerInvariant() switch
{
"application/vnd.openxmlformats-officedocument.presentationml.presentation" => true,
"application/vnd.openxmlformats-officedocument.presentationml.slideshow" => true,
"application/vnd.openxmlformats-officedocument.presentationml.template" => true,
"application/vnd.ms-powerpoint.presentation.macroEnabled.12" => true,
"application/vnd.ms-powerpoint.slideshow.macroEnabled.12" => true,
"application/vnd.ms-powerpoint.template.macroEnabled.12" => true,
_ => false
};
//
return result;
}
///
/// Check Legacy Format ...
///
///
///
private bool IsLegacyFormat(string mimeType)
{
//
var result = mimeType?.ToLowerInvariant() == "application/vnd.ms-powerpoint";
return result;
}
///
/// Extract an Slide Title ...
///
///
///
private string GetSlideTitle(SlidePart slidePart)
{
//
var result = string.Empty;
//
// Title placeholder has specific type
var titleShape = slidePart.Slide
.Descendants()
.FirstOrDefault(s => s.NonVisualShapeProperties?
.NonVisualDrawingProperties?
.Name?.Value?
.StartsWith("Title", StringComparison.OrdinalIgnoreCase) == true
);
if (titleShape != null)
{
//
var titleText = titleShape
.Descendants()
.Select(t => t.Text?.Trim())
.Where(t => !string.IsNullOrWhiteSpace(t));
result = string.Join(" ", titleText);
}
//
return result;
}
///
/// Extract Speaker Notes ...
///
///
///
private string GetSpeakerNotes(SlidePart slidePart)
{
//
var result = string.Empty;
//
var notesSlidePart = slidePart.NotesSlidePart;
if (notesSlidePart?.NotesSlide == null)
{
return result;
}
//
var notesTexts = notesSlidePart.NotesSlide
.Descendants()
.Select(t => t.Text?.Trim())
.Where(t => !string.IsNullOrWhiteSpace(t))
.ToList();
//
result = notesTexts.Count > 0
? string.Join(Environment.NewLine, notesTexts)
: null;
//
return result;
}
///
/// Extract OpenXML Tables ...
///
///
///
private static string ExtractOpenXmlTables(SlidePart slidePart)
{
//
var sb = new StringBuilder();
//
var tableElements = slidePart.Slide
.Descendants();
//
var tableIndex = 0;
foreach (var table in tableElements)
{
//
tableIndex++;
sb.AppendLine($" Table {tableIndex}:");
//
foreach (var row in table
.Descendants())
{
//
var cells = row
.Descendants()
.Select(c => string.Join(" ", c
.Descendants()
.Select(t => t.Text?.Trim())
.Where(t => !string.IsNullOrWhiteSpace(t))))
.ToList();
//
if (cells.Count > 0)
{
sb.AppendLine($" | {string.Join(" | ", cells)} |");
}
}
//
sb.AppendLine();
}
//
var result = sb.ToString();
//
return result;
}
///
/// Extract Open XML Format ...
///
///
///
///
private async Task ExtractOpenXmlAsync(
Stream fileStream,
CancellationToken cancellationToken
)
{
//
var sb = new StringBuilder();
//
// Copy to MemoryStream (OpenXml requires seekable stream)
await using var ms = new MemoryStream();
await fileStream.CopyToAsync(ms, cancellationToken);
ms.Position = 0;
//
using var presentationDocument = PresentationDocument.Open(ms, false);
var presentationPart = presentationDocument.PresentationPart;
if (presentationPart == null)
{
XException.InvalidData.Throw();
}
//
var slideParts = presentationPart.SlideParts.ToList();
var slideIndex = 0;
foreach (var slidePart in slideParts)
{
//
if (cancellationToken.IsCancellationRequested) break;
slideIndex++;
//
sb.AppendLine($"[Slide {slideIndex}]");
//
// 1. Extract slide title
var slideTitle = GetSlideTitle(slidePart);
if (!string.IsNullOrWhiteSpace(slideTitle))
{
sb.AppendLine($"Title: {slideTitle}");
}
//
// 2. Extract body texts
var bodyTexts = slidePart.Slide
.Descendants()
.Select(t => t.Text?.Trim())
.Where(t => !string.IsNullOrWhiteSpace(t) && t != slideTitle)
.ToList();
if (bodyTexts.Count > 0)
{
//
sb.AppendLine("Content:");
foreach (var text in bodyTexts)
{
sb.AppendLine($" - {text}");
}
}
//
// 3. Extract tables
var tables = ExtractOpenXmlTables(slidePart);
if (!string.IsNullOrWhiteSpace(tables))
{
//
sb.AppendLine("[Tables]");
sb.AppendLine(tables);
}
//
// 4. Extract speaker notes
var notes = GetSpeakerNotes(slidePart);
if (!string.IsNullOrWhiteSpace(notes))
{
//
sb.AppendLine("[Speaker Notes]");
sb.AppendLine(notes);
}
//
// 5. Image count metadata
var imageCount = slidePart.ImageParts?.Count() ?? 0;
if (imageCount > 0)
{
sb.AppendLine($"[Images: {imageCount}]");
}
//
sb.AppendLine();
}
//
var result = sb.ToString().TrimEnd();
//
return result;
}
///
/// Extract Legacy Format ...
///
///
///
///
private async Task ExtractLegacyAsync(
Stream fileStream,
CancellationToken cancellationToken
)
{
//
var sb = new StringBuilder();
//
await using var ms = new MemoryStream();
await fileStream.CopyToAsync(ms, cancellationToken);
ms.Position = 0;
//
using var presentation = PowerPointPresentation.Load(ms);
var slideIndex = 0;
foreach (var slide in presentation.Slides)
{
//
if (cancellationToken.IsCancellationRequested)
{
break;
}
slideIndex++;
//
sb.AppendLine($"[Slide {slideIndex}]");
//
var textParts = new List();
var imageCount = 0;
foreach (var shape in slide.Shapes)
{
//
if (shape is PowerPointTextBox textBox)
{
//
if (!textBox.Text.IsNullOrEmpty())
{
textParts.Add(textBox.Text.Trim());
}
}
else if (shape is PowerPointAutoShape autoShape)
{
//
if (!autoShape.AltText.IsNullOrEmpty())
{
textParts.Add(autoShape.AltText.Trim());
}
}
else if (shape is PowerPointPicture picture)
{
imageCount++;
}
}
//
if (textParts.Count > 0)
{
//
sb.AppendLine("Content:");
foreach (var text in textParts)
{
sb.AppendLine($" - {text}");
}
}
//
if (imageCount > 0)
{
sb.AppendLine($"[Images: {imageCount}]");
}
//
sb.AppendLine();
}
//
var result = sb.ToString().TrimEnd();
//
return result;
}
}
}