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
Addressed issues in PR review
  • Loading branch information
peterwilliams97 committed Jun 25, 2020
commit 3cca58106533ad41cb3027d16cd85e670450480b
3 changes: 0 additions & 3 deletions extractor/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -58,10 +58,7 @@ The entire order of extracted text from a page is expressed in `paraList.writeTe
TODO
-----

* Remove serial code?
* Remove `verbose*` logging?
* Come up with a better name for *reading* direction. Scanning direction? [Word order](https://www.ncbi.nlm.nih.gov/pmc/articles/PMC2694615/)?
* Handle diagonal text.
* Get R to L text extraction working.
* Get top to bottom text extraction working.
* Remove TM from ligature map.
5 changes: 5 additions & 0 deletions extractor/const.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,4 +5,9 @@

package extractor

import "errors"

var isTesting = false
var (
errTypeCheck = errors.New("type check error")
)
2 changes: 0 additions & 2 deletions extractor/extractor.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,6 @@ type Extractor struct {

// New returns an Extractor instance for extracting content from the input PDF page.
func New(page *model.PdfPage) (*Extractor, error) {
serial.reset()
contents, err := page.GetAllContentStreams()
if err != nil {
return nil, err
Expand All @@ -61,7 +60,6 @@ func New(page *model.PdfPage) (*Extractor, error) {
}

// NewFromContents creates a new extractor from contents and page resources.
// XXX(peterwilliams97). Does anyone use this?
func NewFromContents(contents string, resources *model.PdfPageResources) (*Extractor, error) {
e := &Extractor{
contents: contents,
Expand Down
2 changes: 1 addition & 1 deletion extractor/image.go
Original file line number Diff line number Diff line change
Expand Up @@ -124,7 +124,7 @@ func (ctx *imageExtractContext) processOperand(op *contentstream.ContentStreamOp
name, ok := core.GetName(op.Params[0])
if !ok {
common.Log.Debug("ERROR: Type")
return core.ErrTypeError
return errTypeCheck
}

_, xtype := resources.GetXObjectByName(*name)
Expand Down
18 changes: 12 additions & 6 deletions extractor/text.go
Original file line number Diff line number Diff line change
Expand Up @@ -1065,7 +1065,7 @@ func (ma *TextMarkArray) BBox() (model.PdfRectangle, bool) {
// bbox, ok := spanMarks.BBox()
// // handle errors
type TextMark struct {
// Text is the extracted text. It has been decoded to Unicode via ToUnicode().
// Text is the extracted text.
Text string
// Original is the text in the PDF. It has not been decoded like `Text`.
Original string
Expand All @@ -1084,8 +1084,6 @@ type TextMark struct {
// spaces (line breaks) when we see characters that are over a threshold horizontal (vertical)
// distance apart. See wordJoiner (lineJoiner) in PageText.computeViews().
Meta bool
// For debugging
count int64
}

// String returns a string describing `tm`.
Expand All @@ -1102,8 +1100,8 @@ func (tm TextMark) String() string {
if tm.Meta {
meta = " *M*"
}
return fmt.Sprintf("{@%04d TextMark: %d %q=%02x (%6.2f, %6.2f) (%6.2f, %6.2f) %s%s}",
tm.count, tm.Offset, tm.Text, []rune(tm.Text), b.Llx, b.Lly, b.Urx, b.Ury, font, meta)
return fmt.Sprintf("{TextMark: %d %q=%02x (%6.2f, %6.2f) (%6.2f, %6.2f) %s%s}",
tm.Offset, tm.Text, []rune(tm.Text), b.Llx, b.Lly, b.Urx, b.Ury, font, meta)
}

// spaceMark is a special TextMark used for spaces.
Expand All @@ -1119,7 +1117,15 @@ var spaceMark = TextMark{
// Cells[y][x] is the (0-offset) x'th column in the table.
type TextTable struct {
W, H int
Cells [][]string
Cells [][]TableCell
}

// TableCell is a cell in a TextTable.
type TableCell struct {
// Text is the extracted text.
Text string
// Marks returns the TextMarks corresponding to the text in Text.
Marks TextMarkArray
}

// getCurrentFont returns the font on top of the font stack, or DefaultFont if the font stack is
Expand Down
6 changes: 1 addition & 5 deletions extractor/text_bag.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,6 @@ import (
// In the current implementation, wordBag is a list of word fragment bins arranged by their depth on
// a page with the word fragments in each bin are sorted in reading order.
type wordBag struct {
serial int // Sequence number for debugging.
model.PdfRectangle // Bounding box of all the textWord in the wordBag.
fontsize float64 // The size of the largest font in the wordBag.
// The following fields are for the current bin based implementation
Expand All @@ -48,13 +47,11 @@ func newWordBag(word *textWord, pageHeight float64) *wordBag {
depthIdx := depthIndex(word.depth)
words := []*textWord{word}
bag := wordBag{
serial: serial.wordBag,
bins: map[int][]*textWord{depthIdx: words},
PdfRectangle: word.PdfRectangle,
fontsize: word.fontsize,
pageHeight: pageHeight,
}
serial.wordBag++
return &bag
}

Expand All @@ -67,8 +64,7 @@ func (b *wordBag) String() string {
texts = append(texts, w.text)
}
}
return fmt.Sprintf("serial=%d %.2f fontsize=%.2f %d %q",
b.serial, b.PdfRectangle, b.fontsize, len(texts), texts)
return fmt.Sprintf("%.2f fontsize=%.2f %d %q", b.PdfRectangle, b.fontsize, len(texts), texts)
}

// scanBand scans the bins for words w:
Expand Down
7 changes: 2 additions & 5 deletions extractor/text_line.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@ import (

// textLine repesents words on the same line within a textPara.
type textLine struct {
serial int // Sequence number for debugging.
model.PdfRectangle // Bounding box (union of `marks` bounding boxes).
depth float64 // Distance from bottom of line to top of page.
words []*textWord // Words in this line.
Expand All @@ -27,20 +26,18 @@ type textLine struct {
func newTextLine(b *wordBag, depthIdx int) *textLine {
word := b.firstWord(depthIdx)
line := textLine{
serial: serial.line,
PdfRectangle: word.PdfRectangle,
fontsize: word.fontsize,
depth: word.depth,
}
serial.line++
line.pullWord(b, word, depthIdx)
return &line
}

// String returns a description of `l`.
func (l *textLine) String() string {
return fmt.Sprintf("serial=%d %.2f %6.2f fontsize=%.2f \"%s\"",
l.serial, l.depth, l.PdfRectangle, l.fontsize, l.text())
return fmt.Sprintf("%.2f %6.2f fontsize=%.2f \"%s\"",
l.depth, l.PdfRectangle, l.fontsize, l.text())
}

// bbox makes textLine implement the `bounded` interface.
Expand Down
8 changes: 1 addition & 7 deletions extractor/text_mark.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@ import (
// textMark represents text drawn on a page and its position in device coordinates.
// All dimensions are in device coordinates.
type textMark struct {
serial int // Sequence number for debugging.
model.PdfRectangle // Bounding box oriented so character base is at bottom
orient int // Orientation
text string // The text (decoded via ToUnicode).
Expand Down Expand Up @@ -118,20 +117,16 @@ func (to *textObject) newTextMark(text string, trm transform.Matrix, end transfo
trm: trm,
end: end,
orient: orient,
serial: serial.mark,
}
serial.mark++
if verboseGeom {
common.Log.Info("newTextMark: start=%.2f end=%.2f %s", start, end, tm.String())
}

return tm, onPage
}

// String returns a description of `tm`.
func (tm *textMark) String() string {
return fmt.Sprintf("serial=%d %.2f fontsize=%.2f \"%s\"",
tm.serial, tm.PdfRectangle, tm.fontsize, tm.text)
return fmt.Sprintf("%.2f fontsize=%.2f \"%s\"", tm.PdfRectangle, tm.fontsize, tm.text)
}

// bbox makes textMark implement the `bounded` interface.
Expand All @@ -142,7 +137,6 @@ func (tm *textMark) bbox() model.PdfRectangle {
// ToTextMark returns the public view of `tm`.
func (tm *textMark) ToTextMark() TextMark {
return TextMark{
count: int64(tm.serial),
Text: tm.text,
Original: tm.original,
BBox: tm.originaBBox,
Expand Down
15 changes: 4 additions & 11 deletions extractor/text_para.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,11 +21,10 @@ import (
type paraList []*textPara

// textPara is a group of words in a rectangular region of a page that get read together.
// An peragraph in a document might span multiple pages. This is the paragraph framgent on one page.
// A paragraph in a document might span multiple pages. This is the paragraph fragment on one page.
// textParas can be tables in which case the content is in `table`, otherwise the content is in `lines`.
// textTable cells are textParas so this gives one level of recursion
type textPara struct {
serial int // Sequence number for debugging.
model.PdfRectangle // Bounding box.
eBBox model.PdfRectangle // Extended bounding box needed to compute reading order.
lines []*textLine // The lines in the paragraph. (nil for the table case)
Expand All @@ -40,13 +39,7 @@ type textPara struct {

// makeTextPara returns a textPara with bounding rectangle `bbox`.
func makeTextPara(bbox model.PdfRectangle, lines []*textLine) *textPara {
para := textPara{
serial: serial.para,
PdfRectangle: bbox,
lines: lines,
}
serial.para++
return &para
return &textPara{PdfRectangle: bbox, lines: lines}
}

// String returns a description of `p`.
Expand All @@ -55,8 +48,8 @@ func (p *textPara) String() string {
if p.table != nil {
table = fmt.Sprintf("[%dx%d] ", p.table.w, p.table.h)
}
return fmt.Sprintf("serial=%d %6.2f %s%d lines %q",
p.serial, p.PdfRectangle, table, len(p.lines), truncate(p.text(), 50))
return fmt.Sprintf("%6.2f %s%d lines %q",
p.PdfRectangle, table, len(p.lines), truncate(p.text(), 50))
}

// depth returns the paragraph's depth. which is the depth of its top line.
Expand Down
15 changes: 7 additions & 8 deletions extractor/text_table.go
Original file line number Diff line number Diff line change
Expand Up @@ -231,15 +231,11 @@ func (t *textTable) markCells() {
// newTablePara returns a textPara containing `t`.
func (t *textTable) newTablePara() *textPara {
bbox := t.computeBbox()
para := textPara{
serial: serial.para,
return &textPara{
PdfRectangle: bbox,
eBBox: bbox,
table: t,
}
t.log(fmt.Sprintf("newTablePara: serial=%d", para.serial))
serial.para++
return &para
}

// computeBbox computes and returns the bounding box of `t`.
Expand All @@ -258,11 +254,14 @@ func (t *textTable) computeBbox() model.PdfRectangle {

// toTextTable returns the TextTable corresponding to `t`.
func (t *textTable) toTextTable() TextTable {
cells := make([][]string, t.h)
cells := make([][]TableCell, t.h)
for y := 0; y < t.h; y++ {
cells[y] = make([]string, t.w)
cells[y] = make([]TableCell, t.w)
for x := 0; x < t.w; x++ {
cells[y][x] = t.get(x, y).text()
c := t.get(x, y)
cells[y][x].Text = c.text()
offset := 0
cells[y][x].Marks.marks = c.toTextMarks(&offset)
}
}
return TextTable{W: t.w, H: t.h, Cells: cells}
Expand Down
18 changes: 0 additions & 18 deletions extractor/text_utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,24 +11,6 @@ import (
"unicode"
)

// serial is used to add serial numbers to all text* instances.
var serial serialState

// serialState keeps serial number for text* structs.
type serialState struct {
mark int // textMark
word int // textWord
wordBag int // wordBag
line int // textLine
para int // textPara
}

// reset resets `serial` to all zeros.
func (serial *serialState) reset() {
var empty serialState
*serial = empty
}

// TOL is the tolerance for coordinates to be consideted equal. It is big enough to cover all
// rounding errors and small enough that TOL point differences on a page aren't visible.
const TOL = 1.0e-6
Expand Down
10 changes: 3 additions & 7 deletions extractor/text_word.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,6 @@ import (
// - A textLine is the textWords at similar depths sorted in reading order.
// - All textWords, w, in the textLine that start whole words have w.newWord = true
type textWord struct {
serial int // Sequence number for debugging.
model.PdfRectangle // Bounding box (union of `marks` bounding boxes).
depth float64 // Distance from bottom of this word to the top of the page.
text string // The word fragment text.
Expand Down Expand Up @@ -122,21 +121,18 @@ func newTextWord(marks []*textMark, pageSize model.PdfRectangle) *textWord {
}
}

word := textWord{
serial: serial.word,
return &textWord{
PdfRectangle: r,
marks: marks,
depth: pageSize.Ury - r.Lly,
fontsize: fontsize,
}
serial.word++
return &word
}

// String returns a description of `w`.
func (w *textWord) String() string {
return fmt.Sprintf("serial=%d %.2f %6.2f fontsize=%.2f \"%s\"",
w.serial, w.depth, w.PdfRectangle, w.fontsize, w.text)
return fmt.Sprintf("%.2f %6.2f fontsize=%.2f \"%s\"",
w.depth, w.PdfRectangle, w.fontsize, w.text)
}

// bbox makes textWord implement the `bounded` interface.
Expand Down
16 changes: 7 additions & 9 deletions internal/textencoding/glyphs_glyphlist.go
Original file line number Diff line number Diff line change
Expand Up @@ -148,15 +148,13 @@ var ligatureToString = map[rune]string{
'œ': "oe",
'Ꝏ': "OO",
'ꝏ': "oo",
// 'ẞ': "fs",
// 'ß': "fz",
'st': "st",
'ſt': "ſt",
'Ꜩ': "TZ",
'ꜩ': "tz",
'ᵫ': "ue",
'Ꝡ': "VY",
'ꝡ': "vy",
'st': "st",
'ſt': "ſt",
'Ꜩ': "TZ",
'ꜩ': "tz",
'ᵫ': "ue",
'Ꝡ': "VY",
'ꝡ': "vy",
// Reverse of ligatureMap
0xe000: "ft",
0xe001: "fj",
Expand Down