chore: 初始化仓库,导入项目基线代码
Academy v0.8.3 完整代码基线:Go 后端(internal/cmd/cli/mcp-server/docreader)、 Vue 前端(frontend)、数据库迁移(migrations)、部署编排(docker/helm/deploy)与文档。 今日开发的培训推送管理改动随后单独提交。
This commit is contained in:
commit
7ec21f35b0
5767 files changed
+1436788
No files matched your search
@@ -0,0 +1,297 @@
|
||||
package sourceloc
|
||||
|
||||
import (
|
||||
"html"
|
||||
"sort"
|
||||
"strings"
|
||||
"unicode"
|
||||
"unicode/utf8"
|
||||
|
||||
"academy/internal/types"
|
||||
)
|
||||
|
||||
// Unit is one structural piece of an original file (a paragraph, a slide
|
||||
// shape, a sheet row) with the locator it should resolve to.
|
||||
type Unit struct {
|
||||
Text string
|
||||
Locator types.SourceLocator
|
||||
}
|
||||
|
||||
// Skip units too short to place reliably.
|
||||
const alignMinRunes = 2
|
||||
|
||||
// Align maps complete source units, never extending a hit through unmatched
|
||||
// content. Unknown gaps must stay unknown: assigning them to the preceding
|
||||
// block can point a citation at an entirely different page.
|
||||
func Align(markdown string, units []Unit) []types.SourceBlock {
|
||||
norm := normalizeMarkdown(markdown)
|
||||
runes := []rune(markdown)
|
||||
var blocks []types.SourceBlock
|
||||
cursor, floor := 0, 0
|
||||
counts := make(map[string]int)
|
||||
for _, u := range units {
|
||||
counts[normalizeKey(u.Text)]++
|
||||
}
|
||||
matches := indexNormalizedMatches(norm.text, counts)
|
||||
for _, u := range units {
|
||||
key := normalizeKey(u.Text)
|
||||
if utf8.RuneCountInString(key) < alignMinRunes {
|
||||
continue
|
||||
}
|
||||
// A unit may only be placed when every occurrence of its text in the
|
||||
// document is accounted for by a source unit (not a TOC or an omitted
|
||||
// block). The occurrence index is built in one pass over the document.
|
||||
positions := matches[key]
|
||||
if len(positions) != counts[key] {
|
||||
continue
|
||||
}
|
||||
matchIndex := sort.SearchInts(positions, cursor)
|
||||
if matchIndex == len(positions) {
|
||||
continue
|
||||
}
|
||||
at := positions[matchIndex]
|
||||
endByte := at + len(key)
|
||||
start := lineLeadStart(runes, norm.pos[at], floor)
|
||||
end := norm.end[endByte-1]
|
||||
// Include trailing markup/URLs on the matched line and blank lines,
|
||||
// but stop before the next visible text's line. This also preserves
|
||||
// an image's destination without swallowing another paragraph.
|
||||
if endByte == len(norm.text) {
|
||||
end = len(runes)
|
||||
} else {
|
||||
next := norm.pos[endByte]
|
||||
lead := next
|
||||
for lead > 0 && runes[lead-1] != '\n' {
|
||||
lead--
|
||||
}
|
||||
if lead >= end {
|
||||
end = lead
|
||||
}
|
||||
}
|
||||
loc := u.Locator
|
||||
loc.Mapping = "exact"
|
||||
blocks = append(blocks, types.SourceBlock{Start: start, End: end, Locator: loc})
|
||||
cursor, floor = endByte, end
|
||||
}
|
||||
return blocks
|
||||
}
|
||||
|
||||
// alignIndexPrefixBytes bounds the prefix used to bucket patterns. Long unit
|
||||
// keys in tables and office documents usually diverge in their first few
|
||||
// cells, so a fixed prefix gives an O(1) candidate lookup per document
|
||||
// position while keeping the full key comparison as the correctness check.
|
||||
const alignIndexPrefixBytes = 32
|
||||
|
||||
// indexNormalizedMatches finds every occurrence of the requested normalized
|
||||
// keys in one pass. Align used to call normalizedMatches once per distinct
|
||||
// unit, so a table with one unit per row scanned the whole document once per
|
||||
// row. Long keys are bucketed by a fixed byte prefix; short keys are grouped
|
||||
// by their first rune and checked directly.
|
||||
func indexNormalizedMatches(text string, counts map[string]int) map[string][]int {
|
||||
long := make(map[string][]string)
|
||||
short := make(map[rune][]string)
|
||||
for key := range counts {
|
||||
if utf8.RuneCountInString(key) < alignMinRunes {
|
||||
continue
|
||||
}
|
||||
if len(key) >= alignIndexPrefixBytes {
|
||||
long[key[:alignIndexPrefixBytes]] = append(long[key[:alignIndexPrefixBytes]], key)
|
||||
continue
|
||||
}
|
||||
first, _ := utf8.DecodeRuneInString(key)
|
||||
short[first] = append(short[first], key)
|
||||
}
|
||||
|
||||
matches := make(map[string][]int)
|
||||
for at := 0; at < len(text); {
|
||||
first, size := utf8.DecodeRuneInString(text[at:])
|
||||
for _, key := range short[first] {
|
||||
if strings.HasPrefix(text[at:], key) && normalizedBoundaryOK(text, at, key) {
|
||||
matches[key] = append(matches[key], at)
|
||||
}
|
||||
}
|
||||
if end := at + alignIndexPrefixBytes; end <= len(text) {
|
||||
for _, key := range long[text[at:end]] {
|
||||
if strings.HasPrefix(text[at:], key) && normalizedBoundaryOK(text, at, key) {
|
||||
matches[key] = append(matches[key], at)
|
||||
}
|
||||
}
|
||||
}
|
||||
at += size
|
||||
}
|
||||
return matches
|
||||
}
|
||||
|
||||
// normalizedBoundaryOK rejects a key embedded in a different numeric value.
|
||||
func normalizedBoundaryOK(text string, at int, key string) bool {
|
||||
first, _ := utf8.DecodeRuneInString(key)
|
||||
last, _ := utf8.DecodeLastRuneInString(key)
|
||||
before, _ := utf8.DecodeLastRuneInString(text[:at])
|
||||
after, _ := utf8.DecodeRuneInString(text[at+len(key):])
|
||||
left := unicode.IsDigit(first) && (unicode.IsDigit(before) || strings.ContainsRune(".,:/+−-", before))
|
||||
right := unicode.IsDigit(last) && (unicode.IsDigit(after) || strings.ContainsRune(".,:/%‰", after))
|
||||
return !left && !right
|
||||
}
|
||||
|
||||
// lineLeadStart moves pos back to the start of its line when everything
|
||||
// before it on the line is markup or numbering ("## ", "| ", "1. ", "(2) "),
|
||||
// which belongs to the unit but was not part of its text. It never crosses
|
||||
// floor.
|
||||
func lineLeadStart(runes []rune, pos, floor int) int {
|
||||
const maxLead = 16
|
||||
start := pos
|
||||
for start > floor && runes[start-1] != '\n' {
|
||||
if pos-start >= maxLead || unicode.IsLetter(runes[start-1]) {
|
||||
return pos
|
||||
}
|
||||
start--
|
||||
}
|
||||
return start
|
||||
}
|
||||
|
||||
// normalized retains letters, digits and numeric symbols: text holds the
|
||||
// kept runes, pos[b] the rune offset in the source of the rune starting at
|
||||
// byte b of text.
|
||||
type normalized struct {
|
||||
text string
|
||||
pos []int
|
||||
end []int
|
||||
}
|
||||
|
||||
// normalizeMarkdown projects markdown onto its letters and digits, skipping
|
||||
// link and image destinations and HTML tags, whose URLs and attributes are
|
||||
// not text of the document.
|
||||
func normalizeMarkdown(markdown string) normalized {
|
||||
var b strings.Builder
|
||||
b.Grow(len(markdown))
|
||||
pos := make([]int, 0, len(markdown))
|
||||
ends := make([]int, 0, len(markdown))
|
||||
emit := func(r rune, start, end int) {
|
||||
before := b.Len()
|
||||
b.WriteRune(r)
|
||||
for k := before; k < b.Len(); k++ {
|
||||
pos = append(pos, start)
|
||||
ends = append(ends, end)
|
||||
}
|
||||
}
|
||||
runes := []rune(markdown)
|
||||
for i := 0; i < len(runes); i++ {
|
||||
r := runes[i]
|
||||
switch {
|
||||
case r == '<' && i+1 < len(runes) && (isASCIILetter(runes[i+1]) || runes[i+1] == '/' || runes[i+1] == '!'):
|
||||
if end := indexRune(runes, '>', i+1, 4096); end > 0 {
|
||||
i = end
|
||||
continue
|
||||
}
|
||||
case r == ']' && i+1 < len(runes) && runes[i+1] == '(':
|
||||
if end := indexRune(runes, ')', i+2, 1<<20); end > 0 {
|
||||
i = end
|
||||
continue
|
||||
}
|
||||
}
|
||||
if r == '&' {
|
||||
if end := indexRune(runes, ';', i+1, 32); end > 0 {
|
||||
raw := string(runes[i : end+1])
|
||||
if decoded := html.UnescapeString(raw); decoded != raw {
|
||||
context := []rune{' '}
|
||||
if i > 0 {
|
||||
context[0] = runes[i-1]
|
||||
}
|
||||
context = append(context, []rune(decoded)...)
|
||||
context = append(context, ' ')
|
||||
if end+1 < len(runes) {
|
||||
context[len(context)-1] = runes[end+1]
|
||||
}
|
||||
for j := 1; j+1 < len(context); j++ {
|
||||
if nr, ok := matchRune(context, j); ok {
|
||||
emit(nr, i, end+1)
|
||||
}
|
||||
}
|
||||
i = end
|
||||
continue
|
||||
}
|
||||
}
|
||||
}
|
||||
if nr, ok := matchRune(runes, i); ok {
|
||||
emit(nr, i, i+1)
|
||||
}
|
||||
}
|
||||
return normalized{text: b.String(), pos: pos, end: ends}
|
||||
}
|
||||
|
||||
// normalizeKey projects plain text onto its letters and digits.
|
||||
func normalizeKey(text string) string {
|
||||
var b strings.Builder
|
||||
runes := []rune(text)
|
||||
for i := range runes {
|
||||
if r, ok := matchRune(runes, i); ok {
|
||||
b.WriteRune(r)
|
||||
}
|
||||
}
|
||||
return b.String()
|
||||
}
|
||||
|
||||
// Preserve distinctions such as 1.5/15, -5/5, 5%/5 and <5/>5.
|
||||
func matchRune(rs []rune, i int) (rune, bool) {
|
||||
r := rs[i]
|
||||
if r >= 0xFF01 && r <= 0xFF5E {
|
||||
r -= 0xFEE0
|
||||
}
|
||||
if !strings.ContainsRune(".,:/+−-%‰<>=≤≥≠", r) {
|
||||
return foldRune(r)
|
||||
}
|
||||
before, after := i-1, i+1
|
||||
for before >= 0 && (rs[before] == ' ' || rs[before] == '\t') {
|
||||
before--
|
||||
}
|
||||
for after < len(rs) && (rs[after] == ' ' || rs[after] == '\t') {
|
||||
after++
|
||||
}
|
||||
prevDigit := before >= 0 && unicode.IsDigit(rs[before])
|
||||
nextDigit := after < len(rs) && unicode.IsDigit(rs[after])
|
||||
if ((r == '.' || r == ',' || r == '/' || r == ':') && prevDigit && nextDigit) ||
|
||||
((r == '-' || r == '+' || r == '−') && nextDigit) ||
|
||||
((r == '%' || r == '‰') && prevDigit) || strings.ContainsRune("<>=≤≥≠", r) {
|
||||
if r == '−' {
|
||||
r = '-'
|
||||
}
|
||||
return r, true
|
||||
}
|
||||
return foldRune(r)
|
||||
}
|
||||
|
||||
// foldRune keeps letters and digits, lower-cased and with full-width ASCII
|
||||
// folded to its half-width form.
|
||||
func foldRune(r rune) (rune, bool) {
|
||||
if r >= 0xFF01 && r <= 0xFF5E {
|
||||
r -= 0xFEE0
|
||||
}
|
||||
if !unicode.IsLetter(r) && !unicode.IsDigit(r) {
|
||||
return 0, false
|
||||
}
|
||||
return unicode.ToLower(r), true
|
||||
}
|
||||
|
||||
func isASCIILetter(r rune) bool {
|
||||
return (r >= 'a' && r <= 'z') || (r >= 'A' && r <= 'Z')
|
||||
}
|
||||
|
||||
// indexRune finds r in runes[from:], giving up after limit runes or at a
|
||||
// blank line.
|
||||
func indexRune(runes []rune, r rune, from, limit int) int {
|
||||
end := min(len(runes), from+limit)
|
||||
for i := from; i < end; i++ {
|
||||
if runes[i] == r {
|
||||
return i
|
||||
}
|
||||
if runes[i] == '\n' && i+1 < len(runes) && runes[i+1] == '\n' {
|
||||
return -1
|
||||
}
|
||||
}
|
||||
return -1
|
||||
}
|
||||
|
||||
// SortBlocks orders blocks by start offset.
|
||||
func SortBlocks(blocks []types.SourceBlock) {
|
||||
sort.SliceStable(blocks, func(i, j int) bool { return blocks[i].Start < blocks[j].Start })
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
package sourceloc
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"academy/internal/types"
|
||||
)
|
||||
|
||||
// TestAlignIndexesUniqueRowsInOnePass locks the large-table path: every row is
|
||||
// a distinct unit, and all of them must still align despite the former
|
||||
// per-key full-document scan. The linearity itself is covered by the benchmark.
|
||||
func TestAlignIndexesUniqueRowsInOnePass(t *testing.T) {
|
||||
const rows = 2000
|
||||
var md strings.Builder
|
||||
md.WriteString("| id | value |\n| --- | --- |\n")
|
||||
units := make([]Unit, 0, rows)
|
||||
for i := 0; i < rows; i++ {
|
||||
text := fmt.Sprintf("row-%04d value-%04d", i, i)
|
||||
fmt.Fprintf(&md, "| row-%04d | value-%04d |\n", i, i)
|
||||
units = append(units, Unit{Text: text, Locator: types.SourceLocator{
|
||||
Type: "sheet", Sheet: "CSV", RowStart: i + 2, RowEnd: i + 2,
|
||||
}})
|
||||
}
|
||||
blocks := Align(md.String(), units)
|
||||
if len(blocks) != len(units) {
|
||||
t.Fatalf("aligned %d of %d unique rows", len(blocks), len(units))
|
||||
}
|
||||
for i, block := range blocks {
|
||||
if block.Locator.RowStart != units[i].Locator.RowStart {
|
||||
t.Fatalf("row %d mapped to source row %d", i, block.Locator.RowStart)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Repeated keys must still be rejected unless the document and the source units
|
||||
// account for every occurrence. Prefix bucketing must not turn a TOC duplicate
|
||||
// into a false exact match.
|
||||
func TestAlignPrefixIndexKeepsDuplicateSafety(t *testing.T) {
|
||||
units := []Unit{
|
||||
{Text: "设备验收合格", Locator: types.SourceLocator{Type: "pdf", Page: 1}},
|
||||
}
|
||||
if blocks := Align("目录:设备验收合格。\n正文:设备验收合格。", units); len(blocks) != 0 {
|
||||
t.Fatalf("unaccounted duplicate aligned: %#v", blocks)
|
||||
}
|
||||
units = append(units, Unit{Text: "设备验收合格", Locator: types.SourceLocator{Type: "pdf", Page: 2}})
|
||||
blocks := Align("设备验收合格\n设备验收合格", units)
|
||||
if len(blocks) != 2 || blocks[1].Locator.Page != 2 {
|
||||
t.Fatalf("accounted duplicates = %#v", blocks)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,237 @@
|
||||
package sourceloc
|
||||
|
||||
import (
|
||||
"html"
|
||||
"regexp"
|
||||
"sort"
|
||||
"strings"
|
||||
"unicode/utf8"
|
||||
|
||||
"academy/internal/types"
|
||||
)
|
||||
|
||||
// Index answers "which source positions does this range of the final
|
||||
// Markdown cover" for the chunker's output.
|
||||
type Index struct {
|
||||
runes []rune
|
||||
blocks []types.SourceBlock // sorted by Start
|
||||
maxEnd []int // maxEnd[k] = max End over blocks[:k+1]
|
||||
}
|
||||
|
||||
// NewIndex builds an index over blocks recorded against markdown.
|
||||
func NewIndex(markdown string, blocks []types.SourceBlock) *Index {
|
||||
if len(blocks) == 0 {
|
||||
return nil
|
||||
}
|
||||
sorted := append([]types.SourceBlock(nil), blocks...)
|
||||
SortBlocks(sorted)
|
||||
maxEnd := make([]int, len(sorted))
|
||||
for k, b := range sorted {
|
||||
maxEnd[k] = b.End
|
||||
if k > 0 && maxEnd[k-1] > b.End {
|
||||
maxEnd[k] = maxEnd[k-1]
|
||||
}
|
||||
}
|
||||
return &Index{runes: []rune(markdown), blocks: sorted, maxEnd: maxEnd}
|
||||
}
|
||||
|
||||
// Locators returns the locators of the blocks overlapping the rune range
|
||||
// [start, end), each quoting the overlapping text. Adjacent locators that
|
||||
// point at the same place (one page without a region, one slide, a run of
|
||||
// rows) are folded together.
|
||||
func (x *Index) Locators(start, end int) types.SourceLocators {
|
||||
if x == nil || end <= start {
|
||||
return nil
|
||||
}
|
||||
start = max(start, 0)
|
||||
end = min(end, len(x.runes))
|
||||
// Blocks before i all end at or before start.
|
||||
i := sort.Search(len(x.blocks), func(k int) bool { return x.maxEnd[k] > start })
|
||||
var out types.SourceLocators
|
||||
covered, partial := start, false
|
||||
for ; i < len(x.blocks) && x.blocks[i].Start < end; i++ {
|
||||
b := x.blocks[i]
|
||||
lo, hi := max(b.Start, start), min(b.End, end)
|
||||
if hi <= lo {
|
||||
continue
|
||||
}
|
||||
if lo > covered && normalizeMarkdown(fullQuote(string(x.runes[covered:lo]))).text != "" {
|
||||
partial = true
|
||||
}
|
||||
covered = max(covered, hi)
|
||||
quote := fullQuote(string(x.runes[lo:hi]))
|
||||
if quote == "" && b.Locator.Type != types.SourceLocatorPDF {
|
||||
continue
|
||||
}
|
||||
loc := b.Locator
|
||||
loc.BBox = append([]float64(nil), loc.BBox...)
|
||||
loc.Quote = quote
|
||||
out = AppendLocator(out, loc)
|
||||
}
|
||||
if covered < end && normalizeMarkdown(fullQuote(string(x.runes[covered:end]))).text != "" {
|
||||
partial = true
|
||||
}
|
||||
if partial {
|
||||
for i := range out {
|
||||
out[i].Partial = true
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// LocatorsAt returns the locators of the blocks containing rune offset pos,
|
||||
// without quotes. Used to place an image reference found in the markdown.
|
||||
func (x *Index) LocatorsAt(pos int) types.SourceLocators {
|
||||
if x == nil || pos < 0 {
|
||||
return nil
|
||||
}
|
||||
i := sort.Search(len(x.blocks), func(k int) bool { return x.maxEnd[k] > pos })
|
||||
var out types.SourceLocators
|
||||
for ; i < len(x.blocks) && x.blocks[i].Start <= pos; i++ {
|
||||
if b := x.blocks[i]; b.End > pos {
|
||||
loc := b.Locator
|
||||
loc.BBox = append([]float64(nil), loc.BBox...)
|
||||
loc.Quote = ""
|
||||
out = append(out, loc)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// AppendLocator appends loc to list, folding it into the last entry when both
|
||||
// point at the same place.
|
||||
func AppendLocator(list types.SourceLocators, loc types.SourceLocator) types.SourceLocators {
|
||||
if n := len(list); n > 0 && foldInto(&list[n-1], loc) {
|
||||
return list
|
||||
}
|
||||
return append(list, loc)
|
||||
}
|
||||
|
||||
func foldInto(last *types.SourceLocator, loc types.SourceLocator) bool {
|
||||
if last.Type != loc.Type ||
|
||||
last.Partial != loc.Partial ||
|
||||
last.Mapping != loc.Mapping ||
|
||||
last.SourceHash != loc.SourceHash ||
|
||||
last.SourceID != loc.SourceID {
|
||||
return false
|
||||
}
|
||||
switch loc.Type {
|
||||
case types.SourceLocatorPDF:
|
||||
if last.Page != loc.Page || len(last.BBox) > 0 || len(loc.BBox) > 0 {
|
||||
return false
|
||||
}
|
||||
case types.SourceLocatorSlide:
|
||||
if last.Slide != loc.Slide {
|
||||
return false
|
||||
}
|
||||
case types.SourceLocatorSection:
|
||||
if last.Section != loc.Section {
|
||||
return false
|
||||
}
|
||||
case types.SourceLocatorSheet:
|
||||
if last.Sheet != loc.Sheet || loc.RowStart > last.RowEnd+1 || loc.RowEnd < last.RowStart {
|
||||
return false
|
||||
}
|
||||
last.RowStart = min(last.RowStart, loc.RowStart)
|
||||
last.RowEnd = max(last.RowEnd, loc.RowEnd)
|
||||
case types.SourceLocatorText:
|
||||
if loc.Start > last.End+2 || loc.End < last.Start {
|
||||
return false
|
||||
}
|
||||
last.Start = min(last.Start, loc.Start)
|
||||
last.End = max(last.End, loc.End)
|
||||
default:
|
||||
return false
|
||||
}
|
||||
last.Quote = joinQuote(last.Quote, loc.Quote)
|
||||
return true
|
||||
}
|
||||
|
||||
// MergeLocators unions two locator lists, dropping exact duplicates, for
|
||||
// search results that the chat pipeline merges.
|
||||
func MergeLocators(a, b types.SourceLocators) types.SourceLocators {
|
||||
if len(b) == 0 {
|
||||
return a
|
||||
}
|
||||
if len(a) == 0 {
|
||||
return b
|
||||
}
|
||||
out := append(types.SourceLocators(nil), a...)
|
||||
for _, loc := range b {
|
||||
dup := false
|
||||
for _, have := range out {
|
||||
if sameLocator(have, loc) {
|
||||
dup = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !dup {
|
||||
out = append(out, loc)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func sameLocator(a, b types.SourceLocator) bool {
|
||||
if a.Partial != b.Partial ||
|
||||
a.Quote != b.Quote ||
|
||||
a.SourceID != b.SourceID ||
|
||||
a.SourceHash != b.SourceHash ||
|
||||
a.Mapping != b.Mapping ||
|
||||
a.Type != b.Type ||
|
||||
a.Page != b.Page ||
|
||||
a.Block != b.Block ||
|
||||
a.Slide != b.Slide ||
|
||||
a.Sheet != b.Sheet || a.RowStart != b.RowStart || a.RowEnd != b.RowEnd ||
|
||||
a.Start != b.Start || a.End != b.End || a.StartMs != b.StartMs || a.EndMs != b.EndMs ||
|
||||
a.Section != b.Section || len(a.BBox) != len(b.BBox) {
|
||||
return false
|
||||
}
|
||||
for i := range a.BBox {
|
||||
if a.BBox[i] != b.BBox[i] {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
var (
|
||||
quoteImageRe = regexp.MustCompile(`!\[[^\]\n]*\]\([^)\n]*\)`)
|
||||
quoteLinkRe = regexp.MustCompile(`\[([^\]\n]*)\]\([^)\n]*\)`)
|
||||
quoteTagRe = regexp.MustCompile(`</?[a-zA-Z][^>\n]*>|<!--.*?-->`)
|
||||
quoteSpaceRe = regexp.MustCompile(`\s+`)
|
||||
)
|
||||
|
||||
// CleanQuote strips Markdown image and link destinations and HTML tags from
|
||||
// text, collapses whitespace, and caps it at types.SourceLocatorQuoteMax
|
||||
// runes.
|
||||
func CleanQuote(text string) string {
|
||||
return capRunes(fullQuote(text), types.SourceLocatorQuoteMax)
|
||||
}
|
||||
|
||||
// fullQuote keeps the complete evidence; truncation can hide a citation near its end.
|
||||
func fullQuote(text string) string {
|
||||
text = quoteImageRe.ReplaceAllString(text, " ")
|
||||
text = quoteLinkRe.ReplaceAllString(text, "$1")
|
||||
text = quoteTagRe.ReplaceAllString(text, " ")
|
||||
text = html.UnescapeString(text)
|
||||
text = strings.TrimSpace(quoteSpaceRe.ReplaceAllString(text, " "))
|
||||
return text
|
||||
}
|
||||
|
||||
func joinQuote(a, b string) string {
|
||||
if a == "" {
|
||||
return b
|
||||
}
|
||||
if b == "" {
|
||||
return a
|
||||
}
|
||||
return a + " " + b
|
||||
}
|
||||
|
||||
func capRunes(s string, n int) string {
|
||||
if utf8.RuneCountInString(s) <= n {
|
||||
return s
|
||||
}
|
||||
return string([]rune(s)[:n])
|
||||
}
|
||||
@@ -0,0 +1,557 @@
|
||||
package sourceloc
|
||||
|
||||
import (
|
||||
"archive/zip"
|
||||
"bytes"
|
||||
"encoding/csv"
|
||||
"encoding/xml"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"path"
|
||||
"strings"
|
||||
|
||||
"github.com/xuri/excelize/v2"
|
||||
"golang.org/x/net/html"
|
||||
|
||||
"academy/internal/types"
|
||||
)
|
||||
|
||||
// maxUnits bounds the structure extracted from one file.
|
||||
const maxUnits = 200000
|
||||
|
||||
// maxZipEntryBytes bounds a single archive member read during extraction.
|
||||
const maxZipEntryBytes = 64 << 20
|
||||
|
||||
// SupportsStructure reports whether StructureUnits can read fileType.
|
||||
func SupportsStructure(fileType string) bool {
|
||||
switch normalizeType(fileType) {
|
||||
case "docx", "docm", "pptx", "pptm", "xlsx", "xlsm", "csv", "epub":
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// AlignStructure reads the structure of an office file and aligns the
|
||||
// parser's markdown against it. It returns nil when the file type is not
|
||||
// supported or nothing could be placed.
|
||||
func AlignStructure(fileType string, data []byte, markdown string) ([]types.SourceBlock, error) {
|
||||
units, err := StructureUnits(fileType, data)
|
||||
if err != nil || len(units) == 0 {
|
||||
return nil, err
|
||||
}
|
||||
return Align(markdown, units), nil
|
||||
}
|
||||
|
||||
// StructureUnits lists the structural pieces of an office file in document
|
||||
// order, each with the locator it resolves to.
|
||||
func StructureUnits(fileType string, data []byte) ([]Unit, error) {
|
||||
switch normalizeType(fileType) {
|
||||
case "docx", "docm":
|
||||
return docxUnits(data)
|
||||
case "pptx", "pptm":
|
||||
return pptxUnits(data)
|
||||
case "xlsx", "xlsm":
|
||||
return xlsxUnits(data)
|
||||
case "csv":
|
||||
return csvUnits(data)
|
||||
case "epub":
|
||||
return epubUnits(data)
|
||||
}
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
func normalizeType(fileType string) string {
|
||||
return strings.ToLower(strings.TrimPrefix(strings.TrimSpace(fileType), "."))
|
||||
}
|
||||
|
||||
// ---- docx -----------------------------------------------------------------
|
||||
|
||||
// docxUnits walks word/document.xml. Every body-level paragraph and table
|
||||
// counts as one block, in the order Word lays them out; content controls
|
||||
// (w:sdt) are transparent, as they are for the docx-preview renderer.
|
||||
// Tables contribute one unit per row so long tables still align row by row.
|
||||
func docxUnits(data []byte) ([]Unit, error) {
|
||||
zr, err := zip.NewReader(bytes.NewReader(data), int64(len(data)))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
doc, err := readZipFile(zr, "word/document.xml")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
dec := xml.NewDecoder(bytes.NewReader(doc))
|
||||
var (
|
||||
units []Unit
|
||||
depth int // element depth below w:body; sdt wrappers do not count
|
||||
inBody bool
|
||||
block int
|
||||
tblDepth int
|
||||
text strings.Builder
|
||||
inText bool
|
||||
skipText int
|
||||
)
|
||||
flush := func() {
|
||||
t := strings.TrimSpace(text.String())
|
||||
text.Reset()
|
||||
if t != "" && len(units) < maxUnits {
|
||||
loc := types.SourceLocator{Type: types.SourceLocatorDocx, Block: block}
|
||||
units = append(units, Unit{Text: t, Locator: loc})
|
||||
}
|
||||
}
|
||||
for {
|
||||
tok, err := dec.Token()
|
||||
if err == io.EOF {
|
||||
break
|
||||
}
|
||||
if err != nil {
|
||||
return units, nil
|
||||
}
|
||||
switch t := tok.(type) {
|
||||
case xml.StartElement:
|
||||
name := t.Name.Local
|
||||
if !inBody {
|
||||
if name == "body" {
|
||||
inBody = true
|
||||
}
|
||||
continue
|
||||
}
|
||||
if name == "sdt" || name == "sdtContent" || name == "sdtPr" || name == "sdtEndPr" {
|
||||
if name == "sdtPr" || name == "sdtEndPr" {
|
||||
skipText++
|
||||
}
|
||||
continue
|
||||
}
|
||||
depth++
|
||||
if depth == 1 && (name == "p" || name == "tbl") {
|
||||
block++
|
||||
text.Reset()
|
||||
}
|
||||
switch name {
|
||||
case "tbl":
|
||||
tblDepth++
|
||||
case "t":
|
||||
inText = true
|
||||
case "tab":
|
||||
text.WriteByte(' ')
|
||||
case "br", "cr":
|
||||
text.WriteByte(' ')
|
||||
case "delText", "instrText":
|
||||
skipText++
|
||||
}
|
||||
case xml.EndElement:
|
||||
name := t.Name.Local
|
||||
if !inBody {
|
||||
continue
|
||||
}
|
||||
if name == "body" {
|
||||
inBody = false
|
||||
continue
|
||||
}
|
||||
if name == "sdt" || name == "sdtContent" || name == "sdtPr" || name == "sdtEndPr" {
|
||||
if name == "sdtPr" || name == "sdtEndPr" {
|
||||
skipText--
|
||||
}
|
||||
continue
|
||||
}
|
||||
switch name {
|
||||
case "t":
|
||||
inText = false
|
||||
case "delText", "instrText":
|
||||
skipText--
|
||||
case "tr":
|
||||
if tblDepth == 1 {
|
||||
flush()
|
||||
}
|
||||
case "tc":
|
||||
text.WriteByte(' ')
|
||||
case "tbl":
|
||||
tblDepth--
|
||||
}
|
||||
if depth == 1 && name == "p" && tblDepth == 0 {
|
||||
flush()
|
||||
}
|
||||
depth--
|
||||
case xml.CharData:
|
||||
if inText && skipText == 0 {
|
||||
text.Write(t)
|
||||
}
|
||||
}
|
||||
}
|
||||
return units, nil
|
||||
}
|
||||
|
||||
// ---- pptx -----------------------------------------------------------------
|
||||
|
||||
type pptxPresentation struct {
|
||||
SlideIDs []struct {
|
||||
RID string `xml:"http://schemas.openxmlformats.org/officeDocument/2006/relationships id,attr"`
|
||||
} `xml:"sldIdLst>sldId"`
|
||||
}
|
||||
|
||||
type opcRelationships struct {
|
||||
Items []struct {
|
||||
ID string `xml:"Id,attr"`
|
||||
Type string `xml:"Type,attr"`
|
||||
Target string `xml:"Target,attr"`
|
||||
} `xml:"Relationship"`
|
||||
}
|
||||
|
||||
// pptxUnits lists every text paragraph of every slide, and of its speaker
|
||||
// notes, in presentation order. Paragraphs rather than whole slides are the
|
||||
// units so a parser that orders shapes differently still aligns.
|
||||
func pptxUnits(data []byte) ([]Unit, error) {
|
||||
zr, err := zip.NewReader(bytes.NewReader(data), int64(len(data)))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
presXML, err := readZipFile(zr, "ppt/presentation.xml")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var pres pptxPresentation
|
||||
if err := xml.Unmarshal(presXML, &pres); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
rels, err := readRels(zr, "ppt/_rels/presentation.xml.rels")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var units []Unit
|
||||
for i, sld := range pres.SlideIDs {
|
||||
target, ok := rels[sld.RID]
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
slidePath := resolvePart("ppt", target.Target)
|
||||
slideXML, err := readZipFile(zr, slidePath)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
loc := types.SourceLocator{Type: types.SourceLocatorSlide, Slide: i + 1}
|
||||
for _, p := range drawingParagraphs(slideXML) {
|
||||
units = append(units, Unit{Text: p, Locator: loc})
|
||||
}
|
||||
// Speaker notes render after the slide in every parser we use.
|
||||
slideRels, err := readRels(zr, relsPathFor(slidePath))
|
||||
if err == nil {
|
||||
for _, rel := range slideRels {
|
||||
if strings.HasSuffix(rel.Type, "/notesSlide") {
|
||||
notesXML, err := readZipFile(zr, resolvePart(path.Dir(slidePath), rel.Target))
|
||||
if err == nil {
|
||||
for _, p := range drawingParagraphs(notesXML) {
|
||||
units = append(units, Unit{Text: p, Locator: loc})
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if len(units) >= maxUnits {
|
||||
break
|
||||
}
|
||||
}
|
||||
return units, nil
|
||||
}
|
||||
|
||||
// drawingParagraphs returns the text of each DrawingML paragraph (a:p).
|
||||
func drawingParagraphs(doc []byte) []string {
|
||||
dec := xml.NewDecoder(bytes.NewReader(doc))
|
||||
var (
|
||||
out []string
|
||||
text strings.Builder
|
||||
inText bool
|
||||
)
|
||||
for {
|
||||
tok, err := dec.Token()
|
||||
if err != nil {
|
||||
break
|
||||
}
|
||||
switch t := tok.(type) {
|
||||
case xml.StartElement:
|
||||
switch t.Name.Local {
|
||||
case "t":
|
||||
inText = true
|
||||
case "br":
|
||||
text.WriteByte(' ')
|
||||
}
|
||||
case xml.EndElement:
|
||||
switch t.Name.Local {
|
||||
case "t":
|
||||
inText = false
|
||||
case "p":
|
||||
if s := strings.TrimSpace(text.String()); s != "" {
|
||||
out = append(out, s)
|
||||
}
|
||||
text.Reset()
|
||||
}
|
||||
case xml.CharData:
|
||||
if inText {
|
||||
text.Write(t)
|
||||
}
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// ---- xlsx / csv -----------------------------------------------------------
|
||||
|
||||
// xlsxUnits lists every non-empty row of every sheet with its row number.
|
||||
// Rows are streamed so a large workbook is never materialized whole, and
|
||||
// reading stops once maxUnits rows are listed.
|
||||
func xlsxUnits(data []byte) ([]Unit, error) {
|
||||
f, err := excelize.OpenReader(bytes.NewReader(data))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer func() { _ = f.Close() }()
|
||||
var units []Unit
|
||||
for _, sheet := range f.GetSheetList() {
|
||||
units = appendSheetUnits(f, sheet, units)
|
||||
if len(units) >= maxUnits {
|
||||
break
|
||||
}
|
||||
}
|
||||
return units, nil
|
||||
}
|
||||
|
||||
// appendSheetUnits appends the non-empty rows of one sheet, up to maxUnits
|
||||
// units in total.
|
||||
func appendSheetUnits(f *excelize.File, sheet string, units []Unit) []Unit {
|
||||
rows, err := f.Rows(sheet)
|
||||
if err != nil {
|
||||
return units
|
||||
}
|
||||
defer func() { _ = rows.Close() }()
|
||||
// The iterator visits every row number, missing rows included.
|
||||
for row := 1; rows.Next() && len(units) < maxUnits; row++ {
|
||||
cells, err := rows.Columns()
|
||||
if err != nil {
|
||||
break
|
||||
}
|
||||
text := strings.TrimSpace(strings.Join(cells, " "))
|
||||
if text == "" {
|
||||
continue
|
||||
}
|
||||
units = append(units, Unit{Text: text, Locator: types.SourceLocator{
|
||||
Type: types.SourceLocatorSheet, Sheet: sheet, RowStart: row, RowEnd: row,
|
||||
}})
|
||||
}
|
||||
return units
|
||||
}
|
||||
|
||||
// csvUnits lists every record of a CSV file as a row of its only sheet.
|
||||
func csvUnits(data []byte) ([]Unit, error) {
|
||||
reader := csv.NewReader(bytes.NewReader(data))
|
||||
reader.LazyQuotes = true
|
||||
reader.TrimLeadingSpace = true
|
||||
reader.FieldsPerRecord = -1
|
||||
var units []Unit
|
||||
for row := 1; ; row++ {
|
||||
rec, err := reader.Read()
|
||||
if err == io.EOF {
|
||||
break
|
||||
}
|
||||
if err != nil {
|
||||
return units, nil
|
||||
}
|
||||
text := strings.TrimSpace(strings.Join(rec, " "))
|
||||
if text == "" {
|
||||
continue
|
||||
}
|
||||
units = append(units, Unit{Text: text, Locator: types.SourceLocator{
|
||||
Type: types.SourceLocatorSheet, RowStart: row, RowEnd: row,
|
||||
}})
|
||||
if len(units) >= maxUnits {
|
||||
break
|
||||
}
|
||||
}
|
||||
return units, nil
|
||||
}
|
||||
|
||||
// ---- epub -----------------------------------------------------------------
|
||||
|
||||
type epubContainer struct {
|
||||
Rootfiles []struct {
|
||||
FullPath string `xml:"full-path,attr"`
|
||||
} `xml:"rootfiles>rootfile"`
|
||||
}
|
||||
|
||||
type epubPackage struct {
|
||||
Manifest []struct {
|
||||
ID string `xml:"id,attr"`
|
||||
Href string `xml:"href,attr"`
|
||||
} `xml:"manifest>item"`
|
||||
Spine []struct {
|
||||
IDRef string `xml:"idref,attr"`
|
||||
} `xml:"spine>itemref"`
|
||||
}
|
||||
|
||||
// epubUnits lists the block-level text of every spine item. The section
|
||||
// number is the item's 1-based position in the spine; the title is its first
|
||||
// heading.
|
||||
func epubUnits(data []byte) ([]Unit, error) {
|
||||
zr, err := zip.NewReader(bytes.NewReader(data), int64(len(data)))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
containerXML, err := readZipFile(zr, "META-INF/container.xml")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var container epubContainer
|
||||
if err := xml.Unmarshal(containerXML, &container); err != nil || len(container.Rootfiles) == 0 {
|
||||
return nil, errors.New("epub: no rootfile")
|
||||
}
|
||||
opfPath := container.Rootfiles[0].FullPath
|
||||
opfXML, err := readZipFile(zr, opfPath)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var pkg epubPackage
|
||||
if err := xml.Unmarshal(opfXML, &pkg); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
hrefs := make(map[string]string, len(pkg.Manifest))
|
||||
for _, item := range pkg.Manifest {
|
||||
hrefs[item.ID] = item.Href
|
||||
}
|
||||
var units []Unit
|
||||
for i, ref := range pkg.Spine {
|
||||
href, ok := hrefs[ref.IDRef]
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
doc, err := readZipFile(zr, resolvePart(path.Dir(opfPath), stripFragment(href)))
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
title, blocks := htmlBlocks(doc)
|
||||
loc := types.SourceLocator{Type: types.SourceLocatorSection, Section: i + 1, Title: title}
|
||||
for _, b := range blocks {
|
||||
units = append(units, Unit{Text: b, Locator: loc})
|
||||
}
|
||||
if len(units) >= maxUnits {
|
||||
break
|
||||
}
|
||||
}
|
||||
return units, nil
|
||||
}
|
||||
|
||||
// htmlBlocks returns the first heading and the text of each block-level
|
||||
// element of an XHTML document.
|
||||
func htmlBlocks(doc []byte) (string, []string) {
|
||||
z := html.NewTokenizer(bytes.NewReader(doc))
|
||||
var (
|
||||
title string
|
||||
blocks []string
|
||||
text strings.Builder
|
||||
inHeading bool
|
||||
skip int
|
||||
)
|
||||
flush := func() {
|
||||
if s := strings.Join(strings.Fields(text.String()), " "); s != "" {
|
||||
blocks = append(blocks, s)
|
||||
if inHeading && title == "" {
|
||||
title = s
|
||||
}
|
||||
}
|
||||
text.Reset()
|
||||
}
|
||||
for {
|
||||
tt := z.Next()
|
||||
switch tt {
|
||||
case html.ErrorToken:
|
||||
flush()
|
||||
return title, blocks
|
||||
case html.StartTagToken, html.EndTagToken, html.SelfClosingTagToken:
|
||||
name, _ := z.TagName()
|
||||
tag := string(name)
|
||||
switch tag {
|
||||
case "script", "style", "head":
|
||||
if tt == html.StartTagToken {
|
||||
skip++
|
||||
} else if tt == html.EndTagToken && skip > 0 {
|
||||
skip--
|
||||
}
|
||||
continue
|
||||
}
|
||||
if isHTMLBlock(tag) {
|
||||
flush()
|
||||
if strings.HasPrefix(tag, "h") && len(tag) == 2 {
|
||||
inHeading = tt == html.StartTagToken
|
||||
}
|
||||
}
|
||||
case html.TextToken:
|
||||
if skip == 0 {
|
||||
text.Write(z.Text())
|
||||
text.WriteByte(' ')
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func isHTMLBlock(tag string) bool {
|
||||
switch tag {
|
||||
case "p", "div", "li", "tr", "h1", "h2", "h3", "h4", "h5", "h6",
|
||||
"blockquote", "pre", "section", "article", "table", "dt", "dd", "br", "figcaption":
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// ---- zip helpers ----------------------------------------------------------
|
||||
|
||||
func readZipFile(zr *zip.Reader, name string) ([]byte, error) {
|
||||
for _, f := range zr.File {
|
||||
if f.Name == name {
|
||||
if f.UncompressedSize64 > maxZipEntryBytes {
|
||||
return nil, fmt.Errorf("%s: entry too large", name)
|
||||
}
|
||||
rc, err := f.Open()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer func() { _ = rc.Close() }()
|
||||
return io.ReadAll(io.LimitReader(rc, maxZipEntryBytes))
|
||||
}
|
||||
}
|
||||
return nil, fmt.Errorf("%s: not found", name)
|
||||
}
|
||||
|
||||
func readRels(zr *zip.Reader, name string) (map[string]struct{ Type, Target string }, error) {
|
||||
raw, err := readZipFile(zr, name)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var rels opcRelationships
|
||||
if err := xml.Unmarshal(raw, &rels); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out := make(map[string]struct{ Type, Target string }, len(rels.Items))
|
||||
for _, r := range rels.Items {
|
||||
out[r.ID] = struct{ Type, Target string }{r.Type, r.Target}
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// relsPathFor returns the relationship part of an OPC part, e.g.
|
||||
// ppt/slides/slide1.xml -> ppt/slides/_rels/slide1.xml.rels.
|
||||
func relsPathFor(part string) string {
|
||||
return path.Join(path.Dir(part), "_rels", path.Base(part)+".rels")
|
||||
}
|
||||
|
||||
// resolvePart resolves a relationship target against the directory of its
|
||||
// source part. Absolute targets are rooted at the package root.
|
||||
func resolvePart(dir, target string) string {
|
||||
if strings.HasPrefix(target, "/") {
|
||||
return strings.TrimPrefix(path.Clean(target), "/")
|
||||
}
|
||||
return path.Clean(path.Join(dir, target))
|
||||
}
|
||||
|
||||
func stripFragment(href string) string {
|
||||
if i := strings.IndexByte(href, '#'); i >= 0 {
|
||||
return href[:i]
|
||||
}
|
||||
return href
|
||||
}
|
||||
@@ -0,0 +1,177 @@
|
||||
package sourceloc
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"academy/internal/types"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestAlignNeverAttributesMissingBlockToPreviousPage(t *testing.T) {
|
||||
md := "第一段正确文本。\n第二段实际内容没有匹配。\n第三段正确文本。"
|
||||
units := []Unit{
|
||||
{Text: "第一段正确文本", Locator: types.SourceLocator{Type: "pdf", Page: 1}},
|
||||
{Text: "第二段OCR错误内容", Locator: types.SourceLocator{Type: "pdf", Page: 2}},
|
||||
{Text: "第三段正确文本", Locator: types.SourceLocator{Type: "pdf", Page: 3}},
|
||||
}
|
||||
index := NewIndex(md, Align(md, units))
|
||||
at := runeIndex(md, "第二段")
|
||||
require.Empty(t, index.Locators(at, at+5))
|
||||
require.Equal(t, 3, index.Locators(runeIndex(md, "第三段"), len([]rune(md)))[0].Page)
|
||||
}
|
||||
|
||||
func TestAlignRequiresFullUnitNotCommonPrefix(t *testing.T) {
|
||||
prefix := strings.Repeat("共同前缀", 12)
|
||||
require.Empty(t,
|
||||
Align(prefix+"验收不合格",
|
||||
[]Unit{{
|
||||
Text: prefix + "验收合格",
|
||||
Locator: types.SourceLocator{
|
||||
Type: "pdf",
|
||||
Page: 1,
|
||||
},
|
||||
}}))
|
||||
}
|
||||
|
||||
func TestAlignPreservesNumericMeaning(t *testing.T) {
|
||||
for _, pair := range [][2]string{{"数值15毫米", "数值1.5毫米"}, {"温度5度", "温度-5度"}, {"比例5", "比例5%"}, {"值≤5", "值≥5"}} {
|
||||
require.Empty(t,
|
||||
Align(pair[0],
|
||||
[]Unit{{
|
||||
Text: pair[1],
|
||||
Locator: types.SourceLocator{
|
||||
Type: "pdf",
|
||||
Page: 1,
|
||||
},
|
||||
}}),
|
||||
pair)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAlignRejectsUnaccountedDuplicate(t *testing.T) {
|
||||
require.Empty(t,
|
||||
Align("目录:设备验收合格。\n正文:设备验收合格。",
|
||||
[]Unit{{
|
||||
Text: "设备验收合格",
|
||||
Locator: types.SourceLocator{
|
||||
Type: "pdf",
|
||||
Page: 9,
|
||||
},
|
||||
}}))
|
||||
units := []Unit{
|
||||
{
|
||||
Text: "相同段落内容",
|
||||
Locator: types.SourceLocator{
|
||||
Type: "pdf",
|
||||
Page: 1,
|
||||
},
|
||||
},
|
||||
{
|
||||
Text: "相同段落内容",
|
||||
Locator: types.SourceLocator{
|
||||
Type: "pdf",
|
||||
Page: 2,
|
||||
},
|
||||
},
|
||||
}
|
||||
blocks := Align("相同段落内容\n相同段落内容", units)
|
||||
require.Len(t, blocks, 2)
|
||||
require.Equal(t, 2, blocks[1].Locator.Page)
|
||||
}
|
||||
|
||||
func TestRemapNeverInterpolatesChangedText(t *testing.T) {
|
||||
old := "第一段\n已通过验收\n末段"
|
||||
blocks := []types.SourceBlock{{Start: 4, End: 9, Locator: types.SourceLocator{Type: "pdf", Page: 2}}}
|
||||
require.Empty(t, RemapBlocks(blocks, old, "第一段\n未通过检查\n末段"))
|
||||
}
|
||||
|
||||
func TestMergeKeepsDistinctExcerptsOfSameRegion(t *testing.T) {
|
||||
a := types.SourceLocator{Type: "pdf", Page: 2, BBox: []float64{0, 0, 1, 1}, Quote: "第一句"}
|
||||
b := a
|
||||
b.Quote = "另一句"
|
||||
require.Len(t, MergeLocators(types.SourceLocators{a}, types.SourceLocators{a, b}), 2)
|
||||
}
|
||||
|
||||
func TestLocatorsPreserveLongEvidenceAndAllRegions(t *testing.T) {
|
||||
text := strings.Repeat("完整原文", 100) + "末尾引用的关键结论"
|
||||
index := NewIndex(text,
|
||||
[]types.SourceBlock{{
|
||||
Start: 0,
|
||||
End: len([]rune(text)),
|
||||
Locator: types.SourceLocator{
|
||||
Type: "pdf",
|
||||
Page: 1,
|
||||
},
|
||||
}})
|
||||
require.Equal(t, text, index.Locators(0, len([]rune(text)))[0].Quote)
|
||||
var blocks []types.SourceBlock
|
||||
for i := 0; i < 80; i++ {
|
||||
blocks = append(blocks,
|
||||
types.SourceBlock{
|
||||
Start: i,
|
||||
End: i + 1,
|
||||
Locator: types.SourceLocator{
|
||||
Type: "pdf",
|
||||
Page: i + 1,
|
||||
},
|
||||
})
|
||||
}
|
||||
locs := NewIndex(strings.Repeat("文", 80), blocks).Locators(0, 80)
|
||||
require.Len(t, locs, 80)
|
||||
require.Len(t, MergeLocators(locs[:40], locs[40:]), 80)
|
||||
}
|
||||
|
||||
func TestFoldingCannotMixRevisionsOrMappingQuality(t *testing.T) {
|
||||
first := types.SourceLocator{Type: "pdf", Page: 1, Mapping: "exact", SourceHash: "original", Quote: "第一段"}
|
||||
second := first
|
||||
second.Mapping = ""
|
||||
require.Len(t, AppendLocator(types.SourceLocators{first}, second), 2)
|
||||
second = first
|
||||
second.SourceHash = "replacement"
|
||||
require.Len(t, AppendLocator(types.SourceLocators{first}, second), 2)
|
||||
}
|
||||
|
||||
func TestAlignRejectsPartialNumericValues(t *testing.T) {
|
||||
for _, pair := range [][2]string{{"增长为5%", "增长为5"}, {"115", "15"}, {"15.5", "15"}, {"-15", "15"}} {
|
||||
require.Empty(t,
|
||||
Align(pair[0], []Unit{{Text: pair[1], Locator: types.SourceLocator{Type: "pdf", Page: 1}}}),
|
||||
pair,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
func TestChunkWithUnmappedEvidenceIsMarkedPartial(t *testing.T) {
|
||||
md := "匹配的原文。\n未匹配的关键结论。"
|
||||
index := NewIndex(md, Align(md, []Unit{{Text: "匹配的原文", Locator: types.SourceLocator{Type: "pdf", Page: 1}}}))
|
||||
locs := index.Locators(0, len([]rune(md)))
|
||||
require.Len(t, locs, 1)
|
||||
require.True(t, locs[0].Partial)
|
||||
require.False(t, index.Locators(0, 5)[0].Partial)
|
||||
}
|
||||
|
||||
func TestAlignmentDecodesTableEntitiesWithoutLosingOffsets(t *testing.T) {
|
||||
md := "<table><tr><td>限值</td><td><1.5</td></tr></table>"
|
||||
loc := types.SourceLocator{Type: "pdf", Page: 2}
|
||||
blocks := Align(md, []Unit{{Text: "限值 <1.5", Locator: loc}})
|
||||
require.Len(t, blocks, 1)
|
||||
quotes := NewIndex(md, blocks).Locators(0, len([]rune(md)))
|
||||
require.False(t, quotes[0].Partial)
|
||||
require.Equal(t, "限值 <1.5", quotes[0].Quote)
|
||||
remapped := RemapBlocks(blocks, md, "|限值|<1.5|")
|
||||
require.Len(t, remapped, 1)
|
||||
require.Equal(t, 2, remapped[0].Locator.Page)
|
||||
}
|
||||
|
||||
func TestImagePlaceholderDoesNotInvalidateVerifiedTextLocators(t *testing.T) {
|
||||
md := "第一段完整的原文。\n\n\n\n第二段完整的原文。"
|
||||
blocks := Align(md, []Unit{
|
||||
{Text: "第一段完整的原文。", Locator: types.SourceLocator{Type: "docx", Block: 1}},
|
||||
{Text: "第二段完整的原文。", Locator: types.SourceLocator{Type: "docx", Block: 3}},
|
||||
})
|
||||
locs := NewIndex(md, blocks).Locators(0, len([]rune(md)))
|
||||
require.Len(t, locs, 2)
|
||||
for _, loc := range locs {
|
||||
require.False(t, loc.Partial)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,248 @@
|
||||
// Package sourceloc maps parsed Markdown back to positions in the original
|
||||
// file: it re-aims parser-reported source blocks after the ingestion pipeline
|
||||
// rewrites the text, aligns parser output to the structure of office files,
|
||||
// and derives the per-chunk locators that citations open.
|
||||
package sourceloc
|
||||
|
||||
import (
|
||||
"sort"
|
||||
"strings"
|
||||
|
||||
"academy/internal/types"
|
||||
)
|
||||
|
||||
// Remapper translates rune offsets in one version of a text to the matching
|
||||
// offsets in a rewritten version.
|
||||
//
|
||||
// Ingestion rewrites parser output before chunking (line endings, HTML
|
||||
// tables, image references). Every rewrite is local, so the two texts share
|
||||
// most of their lines: the remapper pairs identical lines, maps offsets
|
||||
// inside a paired line directly, and spreads offsets proportionally across
|
||||
// the unpaired stretches between pairs. That keeps it correct for any
|
||||
// future rewrite step without each step having to report its edits.
|
||||
type Remapper struct {
|
||||
oldStarts []int // rune offset of each old line
|
||||
newStarts []int
|
||||
oldLen int
|
||||
newLen int
|
||||
pair []int // pair[i] = new line index matched to old line i, or -1
|
||||
}
|
||||
|
||||
// NewRemapper prepares a best-effort offset mapping.
|
||||
// Deprecated: source positions must use RemapBlocks, which verifies full text.
|
||||
func NewRemapper(oldText, newText string) *Remapper {
|
||||
oldKeys, oldStarts, oldLen := splitLines(oldText)
|
||||
newKeys, newStarts, newLen := splitLines(newText)
|
||||
return &Remapper{
|
||||
oldStarts: oldStarts,
|
||||
newStarts: newStarts,
|
||||
oldLen: oldLen,
|
||||
newLen: newLen,
|
||||
pair: matchLines(oldKeys, newKeys),
|
||||
}
|
||||
}
|
||||
|
||||
// Map returns the offset in the new text corresponding to pos in the old one.
|
||||
func (r *Remapper) Map(pos int) int {
|
||||
if pos <= 0 {
|
||||
return 0
|
||||
}
|
||||
if pos >= r.oldLen {
|
||||
return r.newLen
|
||||
}
|
||||
i := sort.SearchInts(r.oldStarts, pos+1) - 1
|
||||
if j := r.pair[i]; j >= 0 {
|
||||
lineLen := r.lineLen(r.newStarts, r.newLen, j)
|
||||
return r.newStarts[j] + min(pos-r.oldStarts[i], lineLen)
|
||||
}
|
||||
// Unpaired line: find the unpaired stretch around it.
|
||||
lo := i
|
||||
for lo > 0 && r.pair[lo-1] < 0 {
|
||||
lo--
|
||||
}
|
||||
hi := i
|
||||
for hi+1 < len(r.pair) && r.pair[hi+1] < 0 {
|
||||
hi++
|
||||
}
|
||||
// A stretch rewritten line for line (image references given new URLs)
|
||||
// has as many lines on both sides: map each line onto its counterpart,
|
||||
// so the drift of a whole-document interpolation cannot accumulate.
|
||||
newLo, newHi := 0, len(r.newStarts)-1
|
||||
if lo > 0 {
|
||||
newLo = r.pair[lo-1] + 1
|
||||
}
|
||||
if hi+1 < len(r.pair) {
|
||||
newHi = r.pair[hi+1] - 1
|
||||
}
|
||||
if newHi-newLo == hi-lo {
|
||||
j := newLo + (i - lo)
|
||||
oldLine := r.lineLen(r.oldStarts, r.oldLen, i)
|
||||
newLine := r.lineLen(r.newStarts, r.newLen, j)
|
||||
within := pos - r.oldStarts[i]
|
||||
if within >= oldLine {
|
||||
return r.newStarts[j] + newLine
|
||||
}
|
||||
return r.newStarts[j] + within*newLine/oldLine
|
||||
}
|
||||
// Otherwise interpolate across the stretch.
|
||||
oldA := r.oldStarts[lo]
|
||||
oldB := r.oldLen
|
||||
if hi+1 < len(r.oldStarts) {
|
||||
oldB = r.oldStarts[hi+1]
|
||||
}
|
||||
newA := 0
|
||||
if lo > 0 {
|
||||
prev := r.pair[lo-1]
|
||||
newA = r.newStarts[prev] + r.lineLen(r.newStarts, r.newLen, prev) + 1
|
||||
}
|
||||
newB := r.newLen
|
||||
if hi+1 < len(r.pair) {
|
||||
newB = r.newStarts[r.pair[hi+1]]
|
||||
}
|
||||
newA = min(newA, newB)
|
||||
if oldB <= oldA {
|
||||
return newA
|
||||
}
|
||||
return newA + (pos-oldA)*(newB-newA)/(oldB-oldA)
|
||||
}
|
||||
|
||||
// lineLen is the rune length of line j excluding its trailing newline.
|
||||
func (r *Remapper) lineLen(starts []int, total, j int) int {
|
||||
end := total
|
||||
if j+1 < len(starts) {
|
||||
end = starts[j+1] - 1
|
||||
}
|
||||
return max(end-starts[j], 0)
|
||||
}
|
||||
|
||||
// RemapBlocks re-aims blocks recorded against oldText at newText. Blocks
|
||||
// that collapse to nothing are dropped.
|
||||
func RemapBlocks(blocks []types.SourceBlock, oldText, newText string) []types.SourceBlock {
|
||||
if len(blocks) == 0 || oldText == newText {
|
||||
return blocks
|
||||
}
|
||||
// Re-align full block text after markup/URL rewrites. Proportional
|
||||
// interpolation can manufacture a location for deleted or changed content.
|
||||
oldRunes := []rune(oldText)
|
||||
units := make([]Unit, 0, len(blocks))
|
||||
for _, b := range blocks {
|
||||
if b.Start < 0 || b.End > len(oldRunes) || b.End <= b.Start {
|
||||
continue
|
||||
}
|
||||
text := normalizeMarkdown(string(oldRunes[b.Start:b.End])).text
|
||||
units = append(units, Unit{Text: text, Locator: b.Locator})
|
||||
}
|
||||
return Align(newText, units)
|
||||
}
|
||||
|
||||
// splitLines returns each line's comparison key (without its line break or a
|
||||
// trailing carriage return), the rune offset where it starts, and the total
|
||||
// rune length.
|
||||
func splitLines(text string) (keys []string, starts []int, total int) {
|
||||
pos := 0
|
||||
for {
|
||||
idx := strings.IndexByte(text, '\n')
|
||||
line := text
|
||||
if idx >= 0 {
|
||||
line = text[:idx]
|
||||
}
|
||||
keys = append(keys, strings.TrimSuffix(line, "\r"))
|
||||
starts = append(starts, pos)
|
||||
pos += runeCount(line)
|
||||
if idx < 0 {
|
||||
break
|
||||
}
|
||||
pos++ // the newline
|
||||
text = text[idx+1:]
|
||||
}
|
||||
return keys, starts, pos
|
||||
}
|
||||
|
||||
// matchLines pairs equal lines of a and b in order. Lines unique to both
|
||||
// texts anchor the pairing (longest increasing run of anchors), and the
|
||||
// stretches between anchors are extended greedily from both ends.
|
||||
func matchLines(a, b []string) []int {
|
||||
pair := make([]int, len(a))
|
||||
for i := range pair {
|
||||
pair[i] = -1
|
||||
}
|
||||
countA := make(map[string]int, len(a))
|
||||
for _, k := range a {
|
||||
countA[k]++
|
||||
}
|
||||
countB := make(map[string]int, len(b))
|
||||
indexB := make(map[string]int, len(b))
|
||||
for j, k := range b {
|
||||
countB[k]++
|
||||
indexB[k] = j
|
||||
}
|
||||
var candA, candB []int
|
||||
for i, k := range a {
|
||||
if countA[k] == 1 && countB[k] == 1 {
|
||||
candA = append(candA, i)
|
||||
candB = append(candB, indexB[k])
|
||||
}
|
||||
}
|
||||
anchors := longestIncreasing(candB)
|
||||
prevA, prevB := 0, 0
|
||||
for _, idx := range anchors {
|
||||
ai, bj := candA[idx], candB[idx]
|
||||
fillGap(a, b, pair, prevA, ai, prevB, bj)
|
||||
pair[ai] = bj
|
||||
prevA, prevB = ai+1, bj+1
|
||||
}
|
||||
fillGap(a, b, pair, prevA, len(a), prevB, len(b))
|
||||
return pair
|
||||
}
|
||||
|
||||
// fillGap pairs equal lines of a[a0:a1] and b[b0:b1] from the front and the
|
||||
// back until the first mismatch on each side.
|
||||
func fillGap(a, b []string, pair []int, a0, a1, b0, b1 int) {
|
||||
for a0 < a1 && b0 < b1 && a[a0] == b[b0] {
|
||||
pair[a0] = b0
|
||||
a0++
|
||||
b0++
|
||||
}
|
||||
for a0 < a1 && b0 < b1 && a[a1-1] == b[b1-1] {
|
||||
pair[a1-1] = b1 - 1
|
||||
a1--
|
||||
b1--
|
||||
}
|
||||
}
|
||||
|
||||
// longestIncreasing returns the indices of a longest strictly increasing
|
||||
// subsequence of seq.
|
||||
func longestIncreasing(seq []int) []int {
|
||||
if len(seq) == 0 {
|
||||
return nil
|
||||
}
|
||||
tails := make([]int, 0, len(seq)) // index into seq of the tail of each length
|
||||
prev := make([]int, len(seq))
|
||||
for i, v := range seq {
|
||||
k := sort.Search(len(tails), func(t int) bool { return seq[tails[t]] >= v })
|
||||
if k > 0 {
|
||||
prev[i] = tails[k-1]
|
||||
} else {
|
||||
prev[i] = -1
|
||||
}
|
||||
if k == len(tails) {
|
||||
tails = append(tails, i)
|
||||
} else {
|
||||
tails[k] = i
|
||||
}
|
||||
}
|
||||
out := make([]int, len(tails))
|
||||
for i, k := len(tails)-1, tails[len(tails)-1]; i >= 0; i-- {
|
||||
out[i] = k
|
||||
k = prev[k]
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func runeCount(s string) int {
|
||||
n := 0
|
||||
for range s {
|
||||
n++
|
||||
}
|
||||
return n
|
||||
}
|
||||
@@ -0,0 +1,268 @@
|
||||
package sourceloc
|
||||
|
||||
import (
|
||||
"archive/zip"
|
||||
"bytes"
|
||||
"fmt"
|
||||
"strings"
|
||||
"testing"
|
||||
"unicode/utf8"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
"github.com/xuri/excelize/v2"
|
||||
|
||||
"academy/internal/types"
|
||||
)
|
||||
|
||||
func runeIndex(s, sub string) int {
|
||||
i := strings.Index(s, sub)
|
||||
if i < 0 {
|
||||
return -1
|
||||
}
|
||||
return len([]rune(s[:i]))
|
||||
}
|
||||
|
||||
func TestRemapperFollowsRewrites(t *testing.T) {
|
||||
oldText := "第一段\r\n\r\n<table><tr><td>a</td></tr></table>\r\n\r\n\r\n\r\n最后一段文字"
|
||||
newText := "第一段\n\n| a |\n| --- |\n\n\n\n最后一段文字"
|
||||
r := NewRemapper(oldText, newText)
|
||||
|
||||
assert.Equal(t, 0, r.Map(0))
|
||||
assert.Equal(t, runeIndex(newText, "最后"), r.Map(runeIndex(oldText, "最后")))
|
||||
assert.Equal(t, runeIndex(newText, "段文字")+1, r.Map(runeIndex(oldText, "段文字")+1))
|
||||
assert.Equal(t, len([]rune(newText)), r.Map(len([]rune(oldText))))
|
||||
|
||||
// Offsets inside the rewritten table stay inside the rewritten table.
|
||||
tableOld := runeIndex(oldText, "<table>")
|
||||
mapped := r.Map(tableOld + 5)
|
||||
assert.GreaterOrEqual(t, mapped, runeIndex(newText, "| a |"))
|
||||
assert.Less(t, mapped, runeIndex(newText, "![img]"))
|
||||
}
|
||||
|
||||
func TestRemapBlocksDropsCollapsedBlocks(t *testing.T) {
|
||||
blocks := []types.SourceBlock{{Start: 0, End: 3, Locator: types.SourceLocator{Type: "pdf", Page: 1}}}
|
||||
out := RemapBlocks(blocks, "abc\ndef", "abc\ndef")
|
||||
require.Len(t, out, 1)
|
||||
assert.Equal(t, 3, out[0].End)
|
||||
}
|
||||
|
||||
// A scanned PDF is only page images and blank lines, so no line survives the
|
||||
// image URL rewrite; each page must still land on its own line.
|
||||
func TestRemapBlocksKeepsRewrittenLinesOnTheirPages(t *testing.T) {
|
||||
var oldLines, newLines []string
|
||||
var blocks []types.SourceBlock
|
||||
offset := 0
|
||||
for page := 1; page <= 300; page++ {
|
||||
line := fmt.Sprintf("", page, page)
|
||||
if page > 1 {
|
||||
offset += 2
|
||||
}
|
||||
blocks = append(blocks, types.SourceBlock{
|
||||
Start: offset, End: offset + len(line),
|
||||
Locator: types.SourceLocator{Type: types.SourceLocatorPDF, Page: page},
|
||||
})
|
||||
offset += len(line)
|
||||
oldLines = append(oldLines, line)
|
||||
newLines = append(newLines, fmt.Sprintf("", page))
|
||||
}
|
||||
oldText, newText := strings.Join(oldLines, "\n\n"), strings.Join(newLines, "\n\n")
|
||||
idx := NewIndex(newText, RemapBlocks(blocks, oldText, newText))
|
||||
for i, line := range newLines {
|
||||
at := strings.Index(newText, line) + strings.Index(line, "local://")
|
||||
locs := idx.LocatorsAt(utf8.RuneCountInString(newText[:at]))
|
||||
require.Len(t, locs, 1, "page %d", i+1)
|
||||
assert.Equal(t, i+1, locs[0].Page)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAlignPlacesUnitsInOrder(t *testing.T) {
|
||||
md := "# 公路工程\n\n8.14.11 索夹与吊索施工应符合下列规定:\n\n1. 在满足施工需要的前提下,应减小猫道面层开孔面积。\n\n" +
|
||||
"\n\n| 列 | 值 |\n| --- | --- |\n| 高度 | 12m |\n"
|
||||
units := []Unit{
|
||||
{Text: "公路工程", Locator: types.SourceLocator{Type: "docx", Block: 1}},
|
||||
{Text: "8.14.11 索夹与吊索施工应符合下列规定:", Locator: types.SourceLocator{Type: "docx", Block: 2}},
|
||||
{Text: "在满足施工需要的前提下,应减小猫道面层开孔面积。", Locator: types.SourceLocator{Type: "docx", Block: 3}},
|
||||
{Text: "不存在的段落内容不会被放置", Locator: types.SourceLocator{Type: "docx", Block: 4}},
|
||||
{Text: "列 值", Locator: types.SourceLocator{Type: "docx", Block: 5}},
|
||||
{Text: "高度 12m", Locator: types.SourceLocator{Type: "docx", Block: 5}},
|
||||
}
|
||||
blocks := Align(md, units)
|
||||
require.Len(t, blocks, 5)
|
||||
assert.Equal(t, 1, blocks[0].Locator.Block)
|
||||
assert.Equal(t, runeIndex(md, "8.14.11"), blocks[1].Start)
|
||||
assert.Equal(t, blocks[1].End, blocks[2].Start)
|
||||
assert.Equal(t, runeIndex(md, "1. 在满足"), blocks[2].Start, "list numbering stays with its paragraph")
|
||||
assert.Equal(t, 5, blocks[4].Locator.Block)
|
||||
assert.Equal(t, len([]rune(md)), blocks[4].End)
|
||||
}
|
||||
|
||||
func TestIndexLocatorsFoldsAndQuotes(t *testing.T) {
|
||||
md := "第一页正文。\n\n第二页正文开始\n\n第二页正文继续\n\n第三页"
|
||||
p1 := runeIndex(md, "第二页正文开始")
|
||||
p2 := runeIndex(md, "第二页正文继续")
|
||||
p3 := runeIndex(md, "第三页")
|
||||
blocks := []types.SourceBlock{
|
||||
{Start: 0, End: p1, Locator: types.SourceLocator{Type: "pdf", Page: 1}},
|
||||
{Start: p1, End: p2, Locator: types.SourceLocator{Type: "pdf", Page: 2}},
|
||||
{Start: p2, End: p3, Locator: types.SourceLocator{Type: "pdf", Page: 2}},
|
||||
{Start: p3, End: len([]rune(md)), Locator: types.SourceLocator{
|
||||
Type: "pdf", Page: 3, BBox: []float64{0.1, 0.1, 0.9, 0.2},
|
||||
}},
|
||||
}
|
||||
idx := NewIndex(md, blocks)
|
||||
locs := idx.Locators(p1+2, len([]rune(md)))
|
||||
require.Len(t, locs, 2)
|
||||
assert.Equal(t, 2, locs[0].Page)
|
||||
assert.Equal(t, "页正文开始 第二页正文继续", locs[0].Quote)
|
||||
assert.Equal(t, 3, locs[1].Page)
|
||||
assert.Equal(t, []float64{0.1, 0.1, 0.9, 0.2}, locs[1].BBox)
|
||||
assert.Nil(t, idx.Locators(5, 5))
|
||||
}
|
||||
|
||||
func TestAppendLocatorMergesSheetRows(t *testing.T) {
|
||||
var list types.SourceLocators
|
||||
list = AppendLocator(list, types.SourceLocator{Type: "sheet", Sheet: "S1", RowStart: 3, RowEnd: 3, Quote: "a"})
|
||||
list = AppendLocator(list, types.SourceLocator{Type: "sheet", Sheet: "S1", RowStart: 4, RowEnd: 4, Quote: "b"})
|
||||
list = AppendLocator(list, types.SourceLocator{Type: "sheet", Sheet: "S1", RowStart: 9, RowEnd: 9, Quote: "c"})
|
||||
require.Len(t, list, 2)
|
||||
assert.Equal(t, 3, list[0].RowStart)
|
||||
assert.Equal(t, 4, list[0].RowEnd)
|
||||
assert.Equal(t, "a b", list[0].Quote)
|
||||
}
|
||||
|
||||
func TestMergeLocatorsDedupes(t *testing.T) {
|
||||
a := types.SourceLocators{{Type: "slide", Slide: 1}}
|
||||
b := types.SourceLocators{{Type: "slide", Slide: 1}, {Type: "slide", Slide: 2}}
|
||||
assert.Len(t, MergeLocators(a, b), 2)
|
||||
}
|
||||
|
||||
func TestCleanQuote(t *testing.T) {
|
||||
got := CleanQuote("见  和 [链接](https://a.b)\n<b>加粗</b> <!-- Slide number: 3 -->")
|
||||
assert.Equal(t, "见 和 链接 加粗", got)
|
||||
}
|
||||
|
||||
func TestTextBlocks(t *testing.T) {
|
||||
content := "# 标题\n\n第一段\n第一段续\n\n\n第二段"
|
||||
blocks := TextBlocks(content)
|
||||
require.Len(t, blocks, 3)
|
||||
assert.Equal(t, 0, blocks[0].Start)
|
||||
assert.Equal(t, runeIndex(content, "第一段"), blocks[1].Start)
|
||||
assert.Equal(t, runeIndex(content, "第二段"), blocks[2].Start)
|
||||
assert.Equal(t, len([]rune(content)), blocks[2].End)
|
||||
assert.Equal(t, blocks[1].Start, blocks[1].Locator.Start)
|
||||
}
|
||||
|
||||
func zipOf(t *testing.T, files map[string]string) []byte {
|
||||
t.Helper()
|
||||
var buf bytes.Buffer
|
||||
zw := zip.NewWriter(&buf)
|
||||
for name, body := range files {
|
||||
w, err := zw.Create(name)
|
||||
require.NoError(t, err)
|
||||
_, err = w.Write([]byte(body))
|
||||
require.NoError(t, err)
|
||||
}
|
||||
require.NoError(t, zw.Close())
|
||||
return buf.Bytes()
|
||||
}
|
||||
|
||||
func TestDocxUnits(t *testing.T) {
|
||||
doc := `<?xml version="1.0"?>
|
||||
<w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"><w:body>
|
||||
<w:p><w:r><w:t>标题</w:t></w:r></w:p>
|
||||
<w:sdt><w:sdtPr><w:alias w:val="x"/></w:sdtPr><w:sdtContent>
|
||||
<w:p><w:r><w:t>控件内</w:t></w:r><w:r><w:delText>删除</w:delText></w:r></w:p>
|
||||
</w:sdtContent></w:sdt>
|
||||
<w:tbl><w:tr><w:tc><w:p><w:r><w:t>A1</w:t></w:r></w:p></w:tc><w:tc><w:p><w:r><w:t>B1</w:t></w:r></w:p></w:tc></w:tr>
|
||||
<w:tr><w:tc><w:p><w:r><w:t>A2</w:t></w:r></w:p></w:tc></w:tr></w:tbl>
|
||||
<w:p/>
|
||||
<w:p><w:r><w:t xml:space="preserve">末段 </w:t></w:r><w:r><w:tab/><w:t>文字</w:t></w:r></w:p>
|
||||
<w:sectPr/></w:body></w:document>`
|
||||
units, err := docxUnits(zipOf(t, map[string]string{"word/document.xml": doc}))
|
||||
require.NoError(t, err)
|
||||
var got []string
|
||||
for _, u := range units {
|
||||
got = append(got, u.Text+"@"+string(rune('0'+u.Locator.Block)))
|
||||
}
|
||||
assert.Equal(t, []string{"标题@1", "控件内@2", "A1 B1@3", "A2@3", "末段 文字@5"}, got)
|
||||
}
|
||||
|
||||
func TestPptxUnits(t *testing.T) {
|
||||
const (
|
||||
pNS = `xmlns:p="http://schemas.openxmlformats.org/presentationml/2006/main"`
|
||||
rNS = `xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships"`
|
||||
)
|
||||
files := map[string]string{
|
||||
"ppt/presentation.xml": `<p:presentation ` + pNS + ` ` + rNS + `><p:sldIdLst>` +
|
||||
`<p:sldId id="256" r:id="rId3"/><p:sldId id="257" r:id="rId2"/></p:sldIdLst></p:presentation>`,
|
||||
"ppt/_rels/presentation.xml.rels": `<Relationships>` +
|
||||
`<Relationship Id="rId2" Type="http://x/slide" Target="slides/slide1.xml"/>` +
|
||||
`<Relationship Id="rId3" Type="http://x/slide" Target="slides/slide2.xml"/></Relationships>`,
|
||||
"ppt/slides/slide1.xml": `<p:sld xmlns:a="a"><a:p><a:r><a:t>第二张</a:t></a:r></a:p></p:sld>`,
|
||||
"ppt/slides/slide2.xml": `<p:sld xmlns:a="a"><a:p><a:r><a:t>封面</a:t></a:r>` +
|
||||
`<a:r><a:t>标题</a:t></a:r></a:p><a:p/></p:sld>`,
|
||||
"ppt/slides/_rels/slide2.xml.rels": `<Relationships><Relationship Id="rId1" ` +
|
||||
`Type="http://x/notesSlide" Target="../notesSlides/notesSlide1.xml"/></Relationships>`,
|
||||
"ppt/notesSlides/notesSlide1.xml": `<p:notes xmlns:a="a"><a:p><a:r><a:t>备注</a:t></a:r></a:p></p:notes>`,
|
||||
}
|
||||
units, err := pptxUnits(zipOf(t, files))
|
||||
require.NoError(t, err)
|
||||
require.Len(t, units, 3)
|
||||
assert.Equal(t, "封面标题", units[0].Text)
|
||||
assert.Equal(t, 1, units[0].Locator.Slide)
|
||||
assert.Equal(t, "备注", units[1].Text)
|
||||
assert.Equal(t, 1, units[1].Locator.Slide)
|
||||
assert.Equal(t, 2, units[2].Locator.Slide)
|
||||
}
|
||||
|
||||
func TestXlsxUnits(t *testing.T) {
|
||||
f := excelize.NewFile()
|
||||
require.NoError(t, f.SetCellValue("Sheet1", "A1", "名称"))
|
||||
require.NoError(t, f.SetCellValue("Sheet1", "B1", "数量"))
|
||||
require.NoError(t, f.SetCellValue("Sheet1", "A3", "螺栓"))
|
||||
require.NoError(t, f.SetCellValue("Sheet1", "B3", 12))
|
||||
_, err := f.NewSheet("汇总")
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, f.SetCellValue("汇总", "A2", "合计"))
|
||||
buf, err := f.WriteToBuffer()
|
||||
require.NoError(t, err)
|
||||
|
||||
units, err := xlsxUnits(buf.Bytes())
|
||||
require.NoError(t, err)
|
||||
require.Len(t, units, 3)
|
||||
assert.Equal(t, "螺栓 12", units[1].Text)
|
||||
assert.Equal(t, 3, units[1].Locator.RowStart)
|
||||
assert.Equal(t, "汇总", units[2].Locator.Sheet)
|
||||
assert.Equal(t, 2, units[2].Locator.RowStart)
|
||||
|
||||
md := "## Sheet1\n| 名称 | 数量 |\n| --- | --- |\n| 螺栓 | 12 |\n\n## 汇总\n| 合计 |\n"
|
||||
blocks := Align(md, units)
|
||||
require.Len(t, blocks, 3)
|
||||
assert.Equal(t, runeIndex(md, "| 螺栓"), blocks[1].Start, "a table row starts at its line")
|
||||
}
|
||||
|
||||
func TestEpubUnits(t *testing.T) {
|
||||
files := map[string]string{
|
||||
"META-INF/container.xml": `<container><rootfiles>` +
|
||||
`<rootfile full-path="OEBPS/content.opf"/></rootfiles></container>`,
|
||||
"OEBPS/content.opf": `<package><manifest><item id="c1" href="ch1.xhtml"/>` +
|
||||
`<item id="c2" href="text/ch2.xhtml"/></manifest>` +
|
||||
`<spine><itemref idref="c1"/><itemref idref="c2"/></spine></package>`,
|
||||
"OEBPS/ch1.xhtml": `<html><head><title>x</title></head><body><h1>第一章</h1><p>开篇<b>正文</b></p></body></html>`,
|
||||
"OEBPS/text/ch2.xhtml": `<html><body><h2>第二章</h2><p>后文</p><script>var a=1</script></body></html>`,
|
||||
}
|
||||
units, err := epubUnits(zipOf(t, files))
|
||||
require.NoError(t, err)
|
||||
require.Len(t, units, 4)
|
||||
assert.Equal(t, "开篇 正文", units[1].Text)
|
||||
assert.Equal(t, "第一章", units[1].Locator.Title)
|
||||
assert.Equal(t, 2, units[3].Locator.Section)
|
||||
}
|
||||
|
||||
func TestCSVUnits(t *testing.T) {
|
||||
units, err := csvUnits([]byte("name,qty\nbolt,12\n\nnut,3\n"))
|
||||
require.NoError(t, err)
|
||||
require.Len(t, units, 3)
|
||||
assert.Equal(t, 3, units[2].Locator.RowStart)
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
package sourceloc
|
||||
|
||||
import "academy/internal/types"
|
||||
|
||||
// TextBlocks splits a plain-text original (Markdown, TXT) that the parser
|
||||
// passed through unchanged into paragraph blocks whose text locators point at
|
||||
// the same rune ranges of the original file.
|
||||
func TextBlocks(content string) []types.SourceBlock {
|
||||
var blocks []types.SourceBlock
|
||||
start := -1 // rune offset where the current paragraph starts
|
||||
pos := 0
|
||||
blankRun := 0
|
||||
emit := func(end int) {
|
||||
if start >= 0 && end > start {
|
||||
blocks = append(blocks, types.SourceBlock{
|
||||
Start: start, End: end,
|
||||
Locator: types.SourceLocator{Type: types.SourceLocatorText, Mapping: "exact", Start: start, End: end},
|
||||
})
|
||||
}
|
||||
start = -1
|
||||
}
|
||||
lineHasText := false
|
||||
lineStart := 0
|
||||
for _, r := range content {
|
||||
switch r {
|
||||
case '\n':
|
||||
if !lineHasText {
|
||||
blankRun++
|
||||
if blankRun == 1 {
|
||||
emit(lineStart)
|
||||
}
|
||||
} else {
|
||||
blankRun = 0
|
||||
}
|
||||
lineHasText = false
|
||||
lineStart = pos + 1
|
||||
case ' ', '\t', '\r':
|
||||
default:
|
||||
if !lineHasText && start < 0 {
|
||||
start = lineStart
|
||||
}
|
||||
lineHasText = true
|
||||
}
|
||||
pos++
|
||||
}
|
||||
emit(pos)
|
||||
return blocks
|
||||
}
|
||||
Reference in new issue
Block a user