package main
import (
"context"
"fmt"
"regexp"
"strings"
)
// OCRAgent represents the OCR service.
// It is assumed to have the method ExtractTextFromImage.
type OCRAgent struct{}
// ExtractTextFromImage simulates extracting text from a base64 encoded image data URI.
// In a real implementation, this would call an actual OCR service.
func (o *OCRAgent) ExtractTextFromImage(ctx context.Context, image string) (string, error) {
// Simulate some work and context check
select {
case <-ctx.Done():
return "", ctx.Err()
default:
// Simulate OCR processing time (optional)
// time.Sleep(10 * time.Millisecond)
// A very simple simulation: return a placeholder indicating OCR was called
// and maybe a snippet of the image data.
if len(image) > 50 {
return fmt.Sprintf("[Extracted text from image (OCR): ...%s]", image[len(image)-30:]), nil
}
return fmt.Sprintf("[Extracted text from image (OCR): %s]", image), nil
}
}
// PlainTextMarkdown takes a markdown string, finds embedded data URI images,
// extracts text from them using the OCRAgent, and replaces the image tags
// with the extracted text.
func PlainTextMarkdown(ctx context.Context, text string, ocr *OCRAgent) (string, error) {
// Regex to find Markdown embedded images with data URIs.
// It captures the full image tag `` and the data URI part `data:image/...`.
// Group 0: Full match ``
// Group 1: Captured data URI `data:image/type;base64,...`
dataImageRegex := regexp.MustCompile(`!\[[^\]]*\]\(\s*(data:image\/[a-zA-Z]+;base64,[^)]*)\)`)
// Find all matches of the image pattern.
// FindAllStringSubmatchIndex returns a slice of slices.
// Each inner slice contains the start/end index pairs for the whole match and submatches (capturing groups).
// e.g., [[full_start, full_end, group1_start, group1_end], ...]
matches := dataImageRegex.FindAllStringSubmatchIndex(text, -1)
if len(matches) == 0 {
// No embedded images found, return original text
return text, nil
}
// Since we are replacing parts of the string, modifying it from the end
// preserves the indices of subsequent matches relative to the start of the string.
// We'll build the new string by replacing from the last match backwards.
modifiedText := text
// Iterate through matches in reverse order
for i := len(matches) - 1; i >= 0; i-- {
match := matches[i]
fullMatchStart, fullMatchEnd := match[0], match[1] // Indices of the whole image tag
dataURIStart, dataURIEnd := match[2], match[3] // Indices of the captured data URI
// Check for context cancellation before potentially long OCR call
select {
case <-ctx.Done():
return "", ctx.Err()
default:
// Continue
}
// Extract the data URI string from the original text
// Use text here because indices are based on the original string
dataURI := text[dataURIStart:dataURIEnd]
// Call OCR to extract text from the image data
extractedText, err := ocr.ExtractTextFromImage(ctx, dataURI)
if err != nil {
// Return an error if OCR fails for any image
return "", fmt.Errorf("failed to extract text from image starting at index %d: %w", fullMatchStart, err)
}
// Replace the original image tag (full match) with the extracted text
// Perform replacement on the currently modified string.
// Because we process from the end, the indices fullMatchStart and fullMatchEnd
// are still valid relative to the start of the modifiedText up to this point.
modifiedText = modifiedText[:fullMatchStart] + extractedText + modifiedText[fullMatchEnd:]
}
return modifiedText, nil
}
func main() {
// Example usage:
ctx := context.Background()
ocrAgent := &OCRAgent{}
markdownWithImages := `
# Document with Embedded Images
Here is some text before the first image.

Text between images.

More text after the second image.
`
fmt.Println("--- Original Markdown ---")
fmt.Println(markdownWithImages)
fmt.Println("--------------------------")
plainText, err := PlainTextMarkdown(ctx, markdownWithImages, ocrAgent)
if err != nil {
fmt.Printf("Error processing markdown: %v\n", err)
} else {
fmt.Println("--- Processed Text ---")
fmt.Println(plainText)
fmt.Println("----------------------")
}
// Example with no images
markdownNoImages := `
# Just Plain Text
No images here.
`
plainTextNoImages, err := PlainTextMarkdown(ctx, markdownNoImages, ocrAgent)
if err != nil {
fmt.Printf("Error processing markdown (no images): %v\n", err)
} else {
fmt.Println("\n--- Original Markdown (No Images) ---")
fmt.Println(markdownNoImages)
fmt.Println("------------------------------------")
fmt.Println("--- Processed Text (No Images) ---")
fmt.Println(plainTextNoImages)
fmt.Println("----------------------------------")
}
// Example demonstrating potential OCR error handling (uncomment the error simulation in OCRAgent)
/*
fmt.Println("\n--- Testing OCR Error ---")
// Temporarily modify OCRAgent's ExtractTextFromImage to return an error for demonstration
originalExtract := ocrAgent.ExtractTextFromImage
ocrAgent.ExtractTextFromImage = func(ctx context.Context, image string) (string, error) {
return "", fmt.Errorf("simulated OCR failure for this image")
}
plainTextWithError, err := PlainTextMarkdown(ctx, markdownWithImages, ocrAgent)
if err != nil {
fmt.Printf("Correctly caught expected error: %v\n", err)
} else {
fmt.Println("Error: Expected processing error but got success.")
fmt.Println(plainTextWithError)
}
// Restore original function
ocrAgent.ExtractTextFromImage = originalExtract
*/
}
OCRAgent Struct (Dummy): A placeholder OCRAgent is defined with the required ExtractTextFromImage method. This method simulates returning some text based on the input image data URI. In a real application, this would contain the logic to send the image data to an actual OCR service.
dataImageRegex: A global or package-level compiled regular expression is used for efficiency.
!\[[^\]]*\]: Matches ![ followed by any character except ] (zero or more times) followed by ]. This captures the alt text part.
\(: Matches the opening parenthesis of the URL part.
\s*: Matches optional whitespace.
(data:image\/[a-zA-Z]+;base64,[^)]*): This is the crucial capturing group (Group 1).
data:image\/: Matches the literal prefix data:image/. \ escapes the /.
[a-zA-Z]+: Matches the image type (like png, jpeg) - one or more letters.
;base64,: Matches the literal separator.
[^)]*: Matches any character except ) (zero or more times). This captures the base64 data. It's safe because the data URI is inside parentheses ().
\): Matches the closing parenthesis of the URL part.
PlainTextMarkdown Function:
Takes ctx, text, and ocr as input.
Uses dataImageRegex.FindAllStringSubmatchIndex(text, -1) to find all occurrences of the pattern. This method is used because we need both the indices of the full match (the entire ![...] (...) tag) and the indices of the captured group (the data:image/... part). The -1 means find all matches.
If len(matches) == 0, no images are found, so the original text is returned directly with a nil error.
modifiedText := text: A variable is initialized with the original text. We will perform replacements on this variable.
This implementation correctly identifies embedded data URI images in Markdown, extracts the data URI, uses the provided OCRAgent to get text, and replaces the original image syntax with the returned text while handling potential errors and respecting context cancellation.
Reverse Iteration: The code iterates through the matches slice from the last element (len(matches) - 1) down to the first (0). This is a standard technique when modifying a string based on indices found in the original string, as replacing from the end avoids invalidating the indices of matches that occur earlier in the string.
Inside the loop:
match := matches[i]: Get the current match's index information. match is a slice like [full_start, full_end, data_start, data_end].
fullMatchStart, fullMatchEnd := match[0], match[1]: Get the start and end indices of the entire image tag.
dataURIStart, dataURIEnd := match[2], match[3]: Get the start and end indices of the captured data URI string.
Context Check:select { ... } checks if the context is cancelled before calling the potentially blocking or long-running ocr.ExtractTextFromImage.
dataURI := text[dataURIStart:dataURIEnd]: Extract the actual data URI string using the indices from the originaltext. This is crucial because the indices returned by FindAllStringSubmatchIndex are based on the string it was called on (text).
extractedText, err := ocr.ExtractTextFromImage(ctx, dataURI): Call the OCR agent's method.
Error Handling: If err is not nil, it means OCR failed for this specific image. The function immediately returns the error, wrapping it with context about which image failed (using its starting index).
Replacement:modifiedText = modifiedText[:fullMatchStart] + extractedText + modifiedText[fullMatchEnd:]. This is the core replacement step. It takes the part of the modifiedTextbefore the current image tag (modifiedText[:fullMatchStart]), appends the extractedText, and then appends the part of the modifiedTextafter the image tag (modifiedText[fullMatchEnd:]). Because we are working backwards, the indices fullMatchStart and fullMatchEnd correctly slice the string up to that point.
After the loop finishes, modifiedText contains the result with all image tags replaced by the extracted text.
return modifiedText, nil: Return the final modified string and a nil error.
main Function (Example): Demonstrates how to use PlainTextMarkdown with sample markdown containing embedded images. It prints the original and processed text. It also includes commented-out code to show how the OCR error handling would work.