AI transcription and PDFs

Hi, I am using DT (Pro 4.4) to manage a huge number of scans of old letters and documents for a community archive project. As many of these are handwritten and our budget is minimal, I am experimenting with Apple Vision, a small investment in Claude and a couple of downloaded local AI models, within DT, to test the extent to which we can hope to transcribe the text. I realise (and accept) that the results will be patchy but I’m hitting a more particular block on progress which is that DT does not seem able to transcribe the contents of PDFs (via the Data menu and the Chat window), while generally speaking the results for jpgs and other image types are not at all bad. So I would like to understand whether that is expected behaviour or whether I’m missing a setting or a configuration in my set-up. Also, is that a limitation of DT’s implementation of AI transcription services or a more general limitation of the technology itself with regards to PDFs?

I’ll happily admit the above may also demonstrate the limitations on my powers of understanding. But if it’s the case that PDFs (usually PDF+Text) are just not available to transcription, then we’ll need to amend our workflow. Right now files are scanned to jpg then grouped, keyworded, assembled and merged to PDF. I usually OCR everything at this stage, because a good number of letters are typewritten and many more have printed letterheads, which is useful. And since AI translation has been something of an afterthought for us to OCR and PDFs, the next question is what’s the best way to handle transcribing the older PDFs, now that the original image files have long since been trashed and emptied!

Any thoughts and light anyone could shed would be much appreciated.

1 Like

The transcription is only available for images and PDF documents without a proper text layer currently.

1 Like

Thanks. Yes, I’m beginning to grasp now that it’s not the transcription that’s the problem per se, but the difficulties AI has with the way PDFs are constructed. But are you saying more particularly that it’s the OCR process of adding a text layer that gets in the way of AI’s ability to transcribe or parse a document? That feels so counterintuitive.

1 Like

The transcription is intentionally skipped (e.g. to avoid unnecessary costs and time) if there’s a text layer already, no matter whether added via OCR or by the creator of the document.

1 Like

OK that’s really helpful to know. I realise that this is a relatively new and evolving feature within DT, but I think it would be really helpful to have some advisory feedback when DT skips the process.

As a fallback is there any easy way to strip the text layer (preferably within DT) from a PDF-Text document?

1 Like

No. But AppleScript can easily convert a PDF to multi-page TIFFs or multiple images.

NOTE: The following script was created by DEVONthink’s script assistant using Claude Fable 5.1. A quick test was successful.

use AppleScript version "2.4"
use framework "Foundation"
use framework "AppKit"
use framework "Quartz"
use scripting additions

property pResolution : 150 -- resolution (dpi) of the rendered page images

on run
	try
		tell application id "DNtp"
			set theRecords to selected records
			if theRecords is {} then error "Please select one or more PDF documents."
			
			set theChoice to button returned of (display dialog "Convert the selected PDF documents to:" buttons {"Cancel", "Multi-page TIFF", "Individual Images"} default button 3 with title "Convert PDF to Images")
			set makeTIFF to (theChoice is "Multi-page TIFF")
			
			set tempFolder to POSIX path of (path to temporary items)
			set convertedCount to 0
			
			show progress indicator "Converting PDF documents…" steps (count of theRecords) with cancel button
			
			repeat with theRecord in theRecords
				if cancelled progress then exit repeat
				try
					if (record type of theRecord) is PDF document then
						set thePath to path of theRecord
						set theName to name without extension of theRecord
						step progress indicator theName
						
						set safeName to my sanitizeName(theName)
						set outputFiles to my renderPDF(thePath, safeName, tempFolder, makeTIFF)
						
						if outputFiles is not {} then
							if makeTIFF then
								set destinationGroup to location group of theRecord
							else
								-- one group per PDF for the individual page images
								set destinationGroup to create location ((location of theRecord) & safeName & " (Pages)") in (database of theRecord)
							end if
							
							repeat with outFile in outputFiles
								set importedRecord to import path outFile to destinationGroup
								if importedRecord is not missing value then
									set URL of importedRecord to (reference URL of theRecord)
								end if
								do shell script "rm -f " & quoted form of outFile
							end repeat
							set convertedCount to convertedCount + 1
						end if
					else
						step progress indicator (name of theRecord)
						log message (name of theRecord) info "Skipped: not a PDF document"
					end if
				on error errMsg
					log message (name of theRecord) info "Conversion failed: " & errMsg
				end try
			end repeat
			
			hide progress indicator
			if convertedCount is 0 then display alert "No PDF documents were converted." message "Select one or more PDF documents and try again."
		end tell
	on error errMsg number errNum
		tell application id "DNtp" to hide progress indicator
		if errNum is not -128 then display alert "Error" message errMsg
	end try
end run

-- Renders every page of the PDF to a bitmap; returns list of written POSIX paths
on renderPDF(pdfPath, baseName, outputFolder, asTIFF)
	set theURL to current application's NSURL's fileURLWithPath:pdfPath
	set pdfDoc to current application's PDFDocument's alloc()'s initWithURL:theURL
	if pdfDoc is missing value then error "Unable to open the PDF document."
	
	set pageTotal to (pdfDoc's pageCount()) as integer
	if pageTotal is 0 then return {}
	
	set scaleFactor to pResolution / 72
	set outputPaths to {}
	set repList to {}
	
	repeat with i from 0 to (pageTotal - 1)
		set thePage to (pdfDoc's pageAtIndex:i)
		set pageData to thePage's dataRepresentation()
		set pageImage to (current application's NSImage's alloc()'s initWithData:pageData)
		if pageImage is missing value then error "Unable to render page " & (i + 1) & "."
		
		set imgSize to pageImage's |size|()
		set ptWidth to width of imgSize
		set ptHeight to height of imgSize
		set pxWide to (round (ptWidth * scaleFactor)) as integer
		set pxHigh to (round (ptHeight * scaleFactor)) as integer
		if pxWide < 1 then set pxWide to 1
		if pxHigh < 1 then set pxHigh to 1
		
		set theRep to (current application's NSBitmapImageRep's alloc()'s initWithBitmapDataPlanes:(missing value) pixelsWide:pxWide pixelsHigh:pxHigh bitsPerSample:8 samplesPerPixel:4 hasAlpha:true isPlanar:false colorSpaceName:"NSCalibratedRGBColorSpace" bytesPerRow:0 bitsPerPixel:0)
		if theRep is missing value then error "Unable to create bitmap for page " & (i + 1) & "."
		
		-- draw the page into the bitmap on a white background
		set theContext to (current application's NSGraphicsContext's graphicsContextWithBitmapImageRep:theRep)
		current application's NSGraphicsContext's saveGraphicsState()
		(current application's NSGraphicsContext's setCurrentContext:theContext)
		current application's NSColor's whiteColor()'s |set|()
		(current application's NSBezierPath's fillRect:{{0, 0}, {pxWide, pxHigh}})
		(pageImage's drawInRect:{{0, 0}, {pxWide, pxHigh}} fromRect:{{0, 0}, {0, 0}} operation:2 fraction:1.0)
		current application's NSGraphicsContext's restoreGraphicsState()
		
		-- store the point size so the image carries the correct dpi
		(theRep's setSize:{ptWidth, ptHeight})
		
		if asTIFF then
			set end of repList to theRep
		else
			set pngData to (theRep's representationUsingType:4 |properties|:(current application's NSDictionary's dictionary()))
			if pngData is missing value then error "Unable to encode page " & (i + 1) & "."
			set outPath to outputFolder & baseName & " - Page " & my padNumber(i + 1, pageTotal) & ".png"
			set writeOK to (pngData's writeToFile:outPath atomically:true) as boolean
			if writeOK then set end of outputPaths to outPath
		end if
	end repeat
	
	if asTIFF and repList is not {} then
		set tiffData to current application's NSBitmapImageRep's TIFFRepresentationOfImageRepsInArray:repList
		if tiffData is missing value then error "Unable to create multi-page TIFF."
		set outPath to outputFolder & baseName & ".tiff"
		set writeOK to (tiffData's writeToFile:outPath atomically:true) as boolean
		if writeOK then set end of outputPaths to outPath
	end if
	
	return outputPaths
end renderPDF

-- Zero-pads a page number to the width of the total page count
on padNumber(theNumber, maxNumber)
	set numText to theNumber as string
	set maxLength to length of (maxNumber as string)
	repeat while (length of numText) < maxLength
		set numText to "0" & numText
	end repeat
	return numText
end padNumber

-- Removes characters that are not allowed in file or group names
on sanitizeName(theName)
	set cleanName to theName
	repeat with badChar in {"/", ":"}
		set AppleScript's text item delimiters to (badChar as string)
		set nameParts to text items of cleanName
		set AppleScript's text item delimiters to "-"
		set cleanName to nameParts as string
	end repeat
	set AppleScript's text item delimiters to ""
	if cleanName is "" then set cleanName to "Untitled"
	return cleanName
end sanitizeName
1 Like

Thanks again. I’ll give that a go. Just to be clear, does the script convert and replace the pdfs or create a new set of files and trash the originals? Also, with my archivist hat on, is it the conversion process likely to degrade the quality of the image appreciably?

The script creates new files (like the Data > Convert commands) and therefore does neither modify nor delete the originals. And by default the script uses 150 DPI.

1 Like

Much obliged. I’ll let you know how that goes. Regards

1 Like