Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Text extraction code for columns. #366

Merged
merged 54 commits into from
Jun 30, 2020
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
Show all changes
54 commits
Select commit Hold shift + click to select a range
6fe0d20
Fixed filename:page in logging
peterwilliams97 May 19, 2020
22680be
Got CMap working for multi-rune entries
peterwilliams97 May 19, 2020
a9910e7
Treat CMap entries as strings instead of runes to handle multi-byte e…
peterwilliams97 May 20, 2020
0c54cec
Added a test for multibyte encoding.
peterwilliams97 May 20, 2020
6103fb8
Merge branch 'development' of https://github.com/unidoc/unipdf into cmap
peterwilliams97 May 20, 2020
e9c46fa
Merge branch 'cmap' into columns
peterwilliams97 May 24, 2020
6b13a99
First version of text extraction that recognizes columns
peterwilliams97 May 24, 2020
a5c538f
Added an expanation of the text columns code to README.md.
peterwilliams97 May 24, 2020
8303318
fixed typos
peterwilliams97 May 24, 2020
c515472
Abstracted textWord depth calculation. This required change textMark …
peterwilliams97 May 24, 2020
603b5ff
Added function comments.
peterwilliams97 May 25, 2020
fad1552
Fixed text state save/restore.
peterwilliams97 May 26, 2020
6b4314f
Adjusted inter-word search distance to make paragrah division work fo…
peterwilliams97 May 26, 2020
d21e2f8
Got text_test.go passing.
peterwilliams97 May 27, 2020
418f859
Reinstated hyphen suppression
peterwilliams97 May 27, 2020
2260e24
Handle more cases of fonts not being set in text extraction code.
peterwilliams97 May 28, 2020
a14d8e7
Fixed typo
peterwilliams97 May 28, 2020
49bbef0
More verbose logging
peterwilliams97 May 28, 2020
40806d7
Adding tables to text extractor.
peterwilliams97 Jun 1, 2020
29f2d9b
Merge branch 'development' of https://github.com/unidoc/unipdf into c…
peterwilliams97 Jun 5, 2020
af9508c
Added tests for columns extraction.
peterwilliams97 Jun 5, 2020
16b3c1c
Removed commented code
peterwilliams97 Jun 5, 2020
30fc953
Check for textParas that are on the same line when writing out extrac…
peterwilliams97 Jun 5, 2020
b4d90b6
Absorb text to the left of paras into paras e.g. Footnote numbers
peterwilliams97 Jun 5, 2020
975e038
Removed funny character from text_test.go
peterwilliams97 Jun 15, 2020
e6be021
Merge branch 'development' of https://github.com/unidoc/unipdf into c…
peterwilliams97 Jun 15, 2020
a7779a3
Merge branch 'development' of https://github.com/unidoc/unipdf into c…
peterwilliams97 Jun 22, 2020
5d7e4aa
Commented out a creator_test.go test that was broken by my text extra…
peterwilliams97 Jun 22, 2020
acb5caa
Big changes to columns text extraction code for PR.
peterwilliams97 Jun 22, 2020
80b54ef
Updated extractor/README
peterwilliams97 Jun 22, 2020
91479a7
Cleaned up some comments and removed a panic
peterwilliams97 Jun 22, 2020
72155a0
Increased threshold for truncating extracted text when there is no li…
peterwilliams97 Jun 22, 2020
09ebbcf
Improved an error message.
peterwilliams97 Jun 22, 2020
1c54e01
Removed irrelevant spaces
peterwilliams97 Jun 22, 2020
17bee4d
Commented code and removed unused functions.
peterwilliams97 Jun 23, 2020
e65fb04
Reverted PdfRectangle changes
peterwilliams97 Jun 23, 2020
5933a3d
Added duplicate text detection.
peterwilliams97 Jun 23, 2020
933021c
Combine diacritic textMarks in text extraction
peterwilliams97 Jun 24, 2020
f3770ee
Reinstated a diacritic recombination test.
peterwilliams97 Jun 24, 2020
e8abebd
Small code reorganisation
peterwilliams97 Jun 24, 2020
3f1df97
Reinstated handling of rotated text
peterwilliams97 Jun 25, 2020
3cca581
Addressed issues in PR review
peterwilliams97 Jun 25, 2020
b39f205
Merge branch 'development' of https://github.com/unidoc/unipdf into c…
peterwilliams97 Jun 25, 2020
d5c344d
Added color fields to TextMark
peterwilliams97 Jun 25, 2020
fe6afef
Updated README
peterwilliams97 Jun 25, 2020
8be2607
Reinstated the disabled tests I missed before.
peterwilliams97 Jun 25, 2020
a5e21a7
Tightened definition for tables to prevent detection of tables where …
peterwilliams97 Jun 25, 2020
8f64966
Compute line splitting search range based on fontsize of first word i…
peterwilliams97 Jun 26, 2020
25414d4
Use errors.Is(err, core.ErrNotSupported) to distinguish unsupported f…
peterwilliams97 Jun 27, 2020
cf91ad6
Fixed some naming and added some comments.
peterwilliams97 Jun 27, 2020
9caa40e
Merge branch 'development' of https://github.com/unidoc/unipdf into c…
peterwilliams97 Jun 27, 2020
b7f91fd
errors.Is -> xerrors.Is and %w -> %v for go 1.12 compatibility
peterwilliams97 Jun 29, 2020
d3deac8
Removed code that doesn't ever get called.
peterwilliams97 Jun 29, 2020
fe35826
Removed unused test
peterwilliams97 Jun 29, 2020
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
Prev Previous commit
Next Next commit
Combine diacritic textMarks in text extraction
  • Loading branch information
peterwilliams97 committed Jun 24, 2020
commit 933021cfef936110526e1b818d9eb5c6b7de33b9
6 changes: 2 additions & 4 deletions extractor/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@ In English text,
- the *reading* direction is left to right, increasing X in the PDF coordinate system.
- the *depth* directon is top to bottom, decreasing Y in the PDF coordinate system.


HOW TEXT IS EXTRACTED
---------------------

Expand Down Expand Up @@ -62,8 +61,7 @@ TODO
* Remove serial code?
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Are these todos current?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I update them every day. If there haven't any commits in the last 24 hours they should be up to date.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

They are up to date now.

* Remove verbose* logging?
* Reinstate rotated text handling.
* Reinstate diacritic composition.
* Reinstate duplicate text removal.
* Come up with a better name for *reading* direction.
* Come up with a better name for *reading* direction. Scanning direction? [Word order](https://www.ncbi.nlm.nih.gov/pmc/articles/PMC2694615/)?
peterwilliams97 marked this conversation as resolved.
Show resolved Hide resolved
* Get R to L text extraction working.
* Get top to bottom text extraction working.
* Remove TM from ligature map.
11 changes: 0 additions & 11 deletions extractor/text.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@ import (
"math"
"sort"
"strings"
"unicode"

"github.com/unidoc/unipdf/v3/common"
"github.com/unidoc/unipdf/v3/contentstream"
Expand Down Expand Up @@ -877,16 +876,6 @@ func (to *textObject) moveTo(tx, ty float64) {
to.tm = to.tlm
}

// isTextSpace returns true if `text` contains nothing but space code points.
func isTextSpace(text string) bool {
for _, r := range text {
if !unicode.IsSpace(r) {
return false
}
}
return true
}

// PageText represents the layout of text on a device page.
type PageText struct {
marks []*textMark // Texts and their positions on a PDF page.
Expand Down
2 changes: 1 addition & 1 deletion extractor/text_bag.go
Original file line number Diff line number Diff line change
Expand Up @@ -289,7 +289,7 @@ func mergWordBags(paraWords []*wordBag) []*wordBag {
}
para1 := paraWords[i1]
r := para0.PdfRectangle
r.Llx -= para0.fontsize * 0.99
r.Llx -= para0.fontsize
if rectContainsRect(r, para1.PdfRectangle) {
para0.absorb(para1)
absorbed[i1] = struct{}{}
Expand Down
15 changes: 11 additions & 4 deletions extractor/text_const.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,10 @@ const (

// The following constants control the approaches used in the code.
const (
doHyphens = true
useEBBox = false
doHyphens = true
doRemoveDuplicates = true
doCombineDiacritics = true
useEBBox = false
)

// The following constants are the tuning parameter for text extracton
Expand Down Expand Up @@ -67,13 +69,18 @@ const (
// Maximum spacing between characters within a line.
maxIntraLineGapR = 0.02

// Max difference in coordinates of duplicated textWords.
// Maximum difference in coordinates of duplicated textWords.
maxDuplicateWordR = 0.2

// Maximum distance from a character to its diacritic marks as a fraction of the character size.
diacriticRadiusR = 0.5

// Minimum number of rumes in the first half of a hyphenated word
minHyphenation = 4

// The distance we look down from the top of a wordBag for the leftmost word.
topWordRangeR = 4.0
// minimum number of cells in a textTable

// Minimum number of cells in a textTable
minTableParas = 6
)
23 changes: 12 additions & 11 deletions extractor/text_para.go
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,13 @@ func (p *textPara) depth() float64 {
return p.table.get(0, 0).depth()
}

// text is a convenience function that returns the text `p` including tables.
func (p *textPara) text() string {
w := new(bytes.Buffer)
p.writeText(w)
return w.String()
}

// writeText writes the text of `p` including tables to `w`.
func (p *textPara) writeText(w io.Writer) {
if p.table == nil {
Expand Down Expand Up @@ -133,7 +140,7 @@ func (p *textPara) writeCellText(w io.Writer) {
}

// toCellTextMarks creates the TextMarkArray corresponding to the extracted text created by
// paras `paras`.writeCellText().
// paras `p`.writeCellText().
func (p *textPara) toCellTextMarks(offset *int) []TextMark {
var marks []TextMark
for il, line := range p.lines {
Expand All @@ -150,7 +157,7 @@ func (p *textPara) toCellTextMarks(offset *int) []TextMark {
return marks
}

// removeLastTextMarkRune removes the last run from `marks`.
// removeLastTextMarkRune removes the last rune from `marks`.
func removeLastTextMarkRune(marks []TextMark, offset *int) []TextMark {
tm := marks[len(marks)-1]
runes := []rune(tm.Text)
Expand Down Expand Up @@ -235,7 +242,9 @@ func (b *wordBag) removeDuplicates() {
func (b *wordBag) arrangeText() *textPara {
b.sort() // Sort the words in `b`'s bins in the reading direction.

b.removeDuplicates()
if doRemoveDuplicates {
b.removeDuplicates()
}

var lines []*textLine

Expand Down Expand Up @@ -342,11 +351,3 @@ func (paras paraList) log(title string) {
fmt.Printf("%4d: %6.2f %s %q\n", i, para.PdfRectangle, tabl, truncate(text, 50))
}
}

// text returns the text of the lines in `p`.
// NOTE: For debugging only/
func (p *textPara) text() string {
w := new(bytes.Buffer)
p.writeText(w)
return w.String()
}
69 changes: 69 additions & 0 deletions extractor/text_utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ package extractor
import (
"math"
"sort"
"unicode"
)

// serial is used to add serial numbers to all text* instances.
Expand Down Expand Up @@ -178,3 +179,71 @@ func (paras paraList) eventNeighbours(events []event) map[*textPara][]int {
}
return paraNeighbors
}

// isTextSpace returns true if `text` contains nothing but space code points.
func isTextSpace(text string) bool {
for _, r := range text {
if !unicode.IsSpace(r) {
return false
}
}
return true
}

// combiningDiacritic returns the combining version of `text` if text contains a single uncombined
// diacritic rune.
func combiningDiacritic(text string) (string, bool) {
runes := []rune(text)
if len(runes) != 1 {
return "", false
}
combining, isDiacritic := diacriticsToCombining[runes[0]]
return combining, isDiacritic
}

var (
// diacriticsToCombining is a map of diacritic runes to their combining diacritic equivalents.
// These values were copied from (https://svn.apache.org/repos/asf/pdfbox/trunk/pdfbox/src/main/java/org/apache/pdfbox/text/TextPosition.java)
diacriticsToCombining = map[rune]string{
0x0060: "\u0300", // ` -> ò
0x02CB: "\u0300", // ˋ -> ò
0x0027: "\u0301", // ' -> ó
0x00B4: "\u0301", // ´ -> ó
0x02B9: "\u0301", // ʹ -> ó
0x02CA: "\u0301", // ˊ -> ó
0x005E: "\u0302", // ^ -> ô
0x02C6: "\u0302", // ˆ -> ô
0x007E: "\u0303", // ~ -> õ
0x02DC: "\u0303", // ˜ -> õ
0x00AF: "\u0304", // ¯ -> ō
0x02C9: "\u0304", // ˉ -> ō
0x02D8: "\u0306", // ˘ -> ŏ
0x02D9: "\u0307", // ˙ -> ȯ
0x00A8: "\u0308", // ¨ -> ö
0x00B0: "\u030A", // ° -> o̊
0x02DA: "\u030A", // ˚ -> o̊
0x02BA: "\u030B", // ʺ -> ő
0x02DD: "\u030B", // ˝ -> ő
0x02C7: "\u030C", // ˇ -> ǒ
0x02C8: "\u030D", // ˈ -> o̍
0x0022: "\u030E", // " -> o̎
0x02BB: "\u0312", // ʻ -> o̒
0x02BC: "\u0313", // ʼ -> o̓
0x0486: "\u0313", // ҆ -> o̓
0x055A: "\u0313", // ՚ -> o̓
0x02BD: "\u0314", // ʽ -> o̔
0x0485: "\u0314", // ҅ -> o̔
0x0559: "\u0314", // ՙ -> o̔
0x02D4: "\u031D", // ˔ -> o̝
0x02D5: "\u031E", // ˕ -> o̞
0x02D6: "\u031F", // ˖ -> o̟
0x02D7: "\u0320", // ˗ -> o̠
0x02B2: "\u0321", // ʲ -> o̡
0x00B8: "\u0327", // ¸ -> o̧
0x02CC: "\u0329", // ˌ -> o̩
0x02B7: "\u032B", // ʷ -> o̫
0x02CD: "\u0331", // ˍ -> o̱
0x005F: "\u0332", // _ -> o̲
0x204E: "\u0359", // ⁎ -> o͙
}
)
50 changes: 45 additions & 5 deletions extractor/text_word.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import (

"github.com/unidoc/unipdf/v3/common"
"github.com/unidoc/unipdf/v3/model"
"golang.org/x/text/unicode/norm"
)

// textWord represents a word fragment.
Expand Down Expand Up @@ -59,16 +60,38 @@ func makeTextWords(marks []*textMark, pageSize model.PdfRectangle) []*textWord {
}

for _, tm := range marks {
isSpace := isTextSpace(tm.text)
if newWord == nil && !isSpace {
newWord = newTextWord([]*textMark{tm}, pageSize)
continue
if doCombineDiacritics {
// Combine diacritic marks into neighbourimg non-diacritics marks.
if newWord != nil && len(newWord.marks) > 0 {
prev := newWord.marks[len(newWord.marks)-1]
text, isDiacritic := combiningDiacritic(tm.text)
prevText, prevDiacritic := combiningDiacritic(prev.text)
if isDiacritic && !prevDiacritic && prev.inDiacriticArea(tm) {
newWord.addDiacritic(text)
continue
}
if prevDiacritic && !isDiacritic && tm.inDiacriticArea(prev) {
// If the previous mark was the diacritic, merge it into this mark and re-append it
newWord.marks = newWord.marks[:len(newWord.marks)-1]
newWord.addMark(tm, pageSize)
newWord.addDiacritic(prevText)
continue
}
}
}

// Check for spaces between words.
isSpace := isTextSpace(tm.text)
if isSpace {
addNewWord()
continue
}

if newWord == nil && !isSpace {
newWord = newTextWord([]*textMark{tm}, pageSize)
continue
}

fontsize := newWord.fontsize
depthGap := math.Abs(getDepth(pageSize, tm)-newWord.depth) / fontsize
readingGap := gapReading(tm, newWord) / fontsize
Expand All @@ -89,6 +112,15 @@ func makeTextWords(marks []*textMark, pageSize model.PdfRectangle) []*textWord {
return words
}

// inDiacriticArea returns true if `diacritic` is in the area where it could be a diacritic of `tm`.
func (tm *textMark) inDiacriticArea(diacritic *textMark) bool {
dLlx := tm.Llx - diacritic.Llx
dUrx := tm.Urx - diacritic.Urx
dLly := tm.Lly - diacritic.Lly
return math.Abs(dLlx+dUrx) < tm.Width()*diacriticRadiusR &&
math.Abs(dLly) < tm.Height()*diacriticRadiusR
}

// newTextWord creates a textWords containing `marks`.
// `pageSize` is used to calculate the word's depth on the page.
func newTextWord(marks []*textMark, pageSize model.PdfRectangle) *textWord {
Expand Down Expand Up @@ -123,7 +155,7 @@ func (w *textWord) bbox() model.PdfRectangle {
return w.PdfRectangle
}

// addMark adds textMark `tm` to word `w`.
// addMark adds textMark `tm` to `w`.
// `pageSize` is used to calculate the word's depth on the page.
func (w *textWord) addMark(tm *textMark, pageSize model.PdfRectangle) {
w.marks = append(w.marks, tm)
Expand All @@ -134,6 +166,14 @@ func (w *textWord) addMark(tm *textMark, pageSize model.PdfRectangle) {
w.depth = pageSize.Ury - w.PdfRectangle.Lly
}

// addDiacritic adds combining diacritic `text` `tm` to `w`.
// It adds the diacritic to the last mark and doesn't update the size
func (w *textWord) addDiacritic(text string) {
lastMark := w.marks[len(w.marks)-1]
lastMark.text = lastMark.text + text
lastMark.text = norm.NFKC.String(lastMark.text)
}

// absorb combines `word` into `w`.
func (w *textWord) absorb(word *textWord) {
w.PdfRectangle = rectUnion(w.PdfRectangle, word.PdfRectangle)
Expand Down