-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathassistant_attachment.go
More file actions
2132 lines (2001 loc) · 54.1 KB
/
Copy pathassistant_attachment.go
File metadata and controls
2132 lines (2001 loc) · 54.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package main
import (
"archive/zip"
"bytes"
"compress/zlib"
"encoding/binary"
"encoding/csv"
"encoding/json"
"encoding/xml"
"errors"
"fmt"
"image"
_ "image/gif"
_ "image/jpeg"
_ "image/png"
"io"
"os"
"path/filepath"
"sort"
"strconv"
"strings"
"time"
"unicode"
)
type AttachmentReader interface {
CanRead(meta AttachmentMeta) bool
Read(data []byte, meta AttachmentMeta) (AttachmentContent, error)
}
type AttachmentMeta struct {
Filename string
MimeType string
SizeBytes int64
AttachmentID string
MessageID string
}
type AttachmentContent struct {
Text string
Tables [][]string
Metadata map[string]string
Warnings []string
}
type ExtractedActions struct {
Summary string
ActionItems []string
Deadlines []Deadline
MeetingReqs []MeetingRequest
Entities []Entity
}
type Deadline struct {
Task string
Due time.Time
Raw string
}
type MeetingRequest struct {
Subject string
ProposedTimes []TimeSlot
Participants []string
Location string
}
type TimeSlot struct {
Start time.Time
End time.Time
Raw string
Timezone string
}
type Entity struct {
Type string
Value string
}
type documentSignals struct {
ActionItems []string
Deadlines []Deadline
Entities []Entity
Highlights []string
}
func DefaultAttachmentReaders() []AttachmentReader {
return []AttachmentReader{
plainAttachmentReader{},
markdownAttachmentReader{},
jsonAttachmentReader{},
xmlAttachmentReader{},
csvAttachmentReader{},
xlsxAttachmentReader{},
legacyExcelAttachmentReader{},
imageAttachmentReader{},
pdfAttachmentReader{},
docxAttachmentReader{},
}
}
func ReadAttachmentContent(data []byte, meta AttachmentMeta) (AttachmentContent, error) {
for _, reader := range DefaultAttachmentReaders() {
if reader.CanRead(meta) {
return reader.Read(data, meta)
}
}
return AttachmentContent{}, fmt.Errorf("no attachment reader available for %q (%s)", meta.Filename, meta.MimeType)
}
// ExtractActions is a deterministic fallback extractor. The main assistant path
// should prefer model-based reasoning and only use this when a provider is
// unavailable or a semantic extraction response cannot be parsed safely.
func ExtractActions(text string) ExtractedActions {
return ExtractActionsAt(text, time.Now())
}
// ExtractActionsAt is kept as a low-dependency fallback for offline/tooling
// paths. It is not intended to be the primary reasoning engine for the
// assistant experience.
func ExtractActionsAt(text string, now time.Time) ExtractedActions {
lines := splitLines(text)
actionItems := extractActionItems(lines)
deadlines := extractDeadlines(lines, now)
meetingReqs := extractMeetingRequests(lines, now)
entities := extractEntities(text, now)
signals := extractDocumentSignals(lines, now)
actionItems = mergeStrings(actionItems, signals.ActionItems)
deadlines = mergeDeadlines(deadlines, signals.Deadlines)
entities = mergeEntities(entities, signals.Entities)
return ExtractedActions{
Summary: buildActionSummaryWithHighlights(actionItems, deadlines, meetingReqs, signals.Highlights, lines),
ActionItems: actionItems,
Deadlines: deadlines,
MeetingReqs: meetingReqs,
Entities: entities,
}
}
func extractDocumentSignals(lines []string, now time.Time) documentSignals {
var signals documentSignals
seenDeadlines := map[string]struct{}{}
seenEntities := map[string]struct{}{}
seenHighlights := map[string]struct{}{}
addDeadline := func(task, raw string, due time.Time) {
task = strings.TrimSpace(task)
raw = strings.TrimSpace(raw)
if task == "" && raw == "" {
return
}
key := strings.ToLower(task + "|" + raw)
if _, exists := seenDeadlines[key]; exists {
return
}
seenDeadlines[key] = struct{}{}
signals.Deadlines = append(signals.Deadlines, Deadline{Task: task, Raw: raw, Due: due})
}
addEntity := func(typ, value string) {
value = strings.TrimSpace(strings.Trim(value, ",.;:"))
if value == "" {
return
}
key := typ + "|" + strings.ToLower(value)
if _, exists := seenEntities[key]; exists {
return
}
seenEntities[key] = struct{}{}
signals.Entities = append(signals.Entities, Entity{Type: typ, Value: value})
}
addHighlight := func(value string) {
value = strings.TrimSpace(strings.TrimRight(value, ".;"))
if value == "" {
return
}
key := strings.ToLower(value)
if _, exists := seenHighlights[key]; exists {
return
}
seenHighlights[key] = struct{}{}
signals.Highlights = append(signals.Highlights, value)
}
vendor := inferVendorHint(lines)
if vendor != "" {
addEntity("vendor", vendor)
addHighlight("Vendor: " + vendor)
}
for _, raw := range lines {
line := strings.TrimSpace(normalizeWhitespace(raw))
if line == "" || isLikelyBoilerplateLine(line) {
continue
}
lower := strings.ToLower(line)
if amount, ok := extractInvoiceTotal(line); ok {
addEntity("invoice_total", amount)
addHighlight("Invoice total: " + amount)
}
if ref, ok := extractInvoiceReference(line); ok {
addEntity("invoice_reference", ref)
addHighlight("Reference: " + ref)
}
if dueText, ok := extractInvoiceDueText(line, now); ok {
if dueTime, parsed := parseDeadlineTime(dueText, now), strings.TrimSpace(dueText); !dueTime.IsZero() {
addDeadline("Pay invoice", parsed, dueTime)
addEntity("invoice_due_date", parsed)
addHighlight("Invoice due: " + parsed)
}
}
if task, dueText, ok := fallbackDeadlineParts(line, now); ok {
dueTime := parseDeadlineTime(dueText, now)
if !dueTime.IsZero() {
addDeadline(task, dueText, dueTime)
addHighlight(task + " due: " + dueText)
}
} else if strings.Contains(lower, "deadline") || strings.Contains(lower, "due date") || strings.Contains(lower, "payment due") {
if dueText, dueTime, ok := extractDateSpan(line, now); ok {
task := documentDeadlineTaskLabel(line)
if task == "" {
task = "Deadline"
}
addDeadline(task, dueText, dueTime)
addEntity("date", dueText)
addHighlight(task + ": " + dueText)
}
}
if strings.Contains(lower, "invoice") && strings.Contains(lower, "total") {
if amount, ok := extractCurrencyAmount(line); ok {
addEntity("invoice_total", amount)
addHighlight("Invoice total: " + amount)
}
}
}
return signals
}
func mergeStrings(base []string, extra []string) []string {
if len(extra) == 0 {
return append([]string(nil), base...)
}
seen := map[string]struct{}{}
out := make([]string, 0, len(base)+len(extra))
for _, value := range base {
value = strings.TrimSpace(value)
if value == "" {
continue
}
key := strings.ToLower(value)
if _, exists := seen[key]; exists {
continue
}
seen[key] = struct{}{}
out = append(out, value)
}
for _, value := range extra {
value = strings.TrimSpace(value)
if value == "" {
continue
}
key := strings.ToLower(value)
if _, exists := seen[key]; exists {
continue
}
seen[key] = struct{}{}
out = append(out, value)
}
return out
}
func mergeDeadlines(base []Deadline, extra []Deadline) []Deadline {
if len(extra) == 0 {
return append([]Deadline(nil), base...)
}
seen := map[string]struct{}{}
out := make([]Deadline, 0, len(base)+len(extra))
appendDeadline := func(d Deadline) {
key := strings.ToLower(strings.TrimSpace(d.Task) + "|" + strings.TrimSpace(d.Raw) + "|" + d.Due.UTC().Format(time.RFC3339))
if _, exists := seen[key]; exists {
return
}
seen[key] = struct{}{}
out = append(out, d)
}
for _, deadline := range base {
appendDeadline(deadline)
}
for _, deadline := range extra {
appendDeadline(deadline)
}
return out
}
func mergeEntities(base []Entity, extra []Entity) []Entity {
if len(extra) == 0 {
return append([]Entity(nil), base...)
}
seen := map[string]struct{}{}
out := make([]Entity, 0, len(base)+len(extra))
appendEntity := func(e Entity) {
key := strings.ToLower(strings.TrimSpace(e.Type) + "|" + strings.TrimSpace(e.Value))
if _, exists := seen[key]; exists {
return
}
seen[key] = struct{}{}
out = append(out, e)
}
for _, entity := range base {
appendEntity(entity)
}
for _, entity := range extra {
appendEntity(entity)
}
return out
}
type plainAttachmentReader struct{}
func (plainAttachmentReader) CanRead(meta AttachmentMeta) bool {
return mimeMatches(meta, "text/plain") || strings.EqualFold(filepath.Ext(meta.Filename), ".txt")
}
func (plainAttachmentReader) Read(data []byte, meta AttachmentMeta) (AttachmentContent, error) {
return AttachmentContent{Text: strings.TrimRight(string(data), "\x00"), Metadata: map[string]string{"type": "text/plain"}}, nil
}
type markdownAttachmentReader struct{}
func (markdownAttachmentReader) CanRead(meta AttachmentMeta) bool {
return mimeMatches(meta, "text/markdown", "text/x-markdown") || strings.EqualFold(filepath.Ext(meta.Filename), ".md")
}
func (markdownAttachmentReader) Read(data []byte, meta AttachmentMeta) (AttachmentContent, error) {
return AttachmentContent{Text: strings.TrimRight(string(data), "\x00"), Metadata: map[string]string{"type": "text/markdown"}}, nil
}
type jsonAttachmentReader struct{}
func (jsonAttachmentReader) CanRead(meta AttachmentMeta) bool {
return mimeMatches(meta, "application/json") || strings.EqualFold(filepath.Ext(meta.Filename), ".json")
}
func (jsonAttachmentReader) Read(data []byte, meta AttachmentMeta) (AttachmentContent, error) {
var value any
if err := json.Unmarshal(data, &value); err != nil {
return AttachmentContent{}, err
}
pretty, err := json.MarshalIndent(value, "", " ")
if err != nil {
return AttachmentContent{}, err
}
content := AttachmentContent{
Text: string(pretty),
Metadata: map[string]string{"type": "application/json"},
}
if keys := topLevelJSONKeys(value); len(keys) > 0 {
content.Metadata["top_keys"] = strings.Join(keys, ",")
}
return content, nil
}
type csvAttachmentReader struct{}
func (csvAttachmentReader) CanRead(meta AttachmentMeta) bool {
return mimeMatches(meta, "text/csv", "application/csv") || strings.EqualFold(filepath.Ext(meta.Filename), ".csv")
}
func (csvAttachmentReader) Read(data []byte, meta AttachmentMeta) (AttachmentContent, error) {
reader := csv.NewReader(bytes.NewReader(data))
rows, err := reader.ReadAll()
if err != nil {
return AttachmentContent{}, err
}
content := AttachmentContent{
Text: renderTable(rows),
Tables: rows,
Metadata: map[string]string{"type": "text/csv", "rows": strconv.Itoa(len(rows))},
}
if len(rows) > 0 {
content.Metadata["columns"] = strconv.Itoa(len(rows[0]))
}
return content, nil
}
type xmlAttachmentReader struct{}
func (xmlAttachmentReader) CanRead(meta AttachmentMeta) bool {
return mimeMatches(meta, "application/xml", "text/xml") || strings.EqualFold(filepath.Ext(meta.Filename), ".xml")
}
func (xmlAttachmentReader) Read(data []byte, meta AttachmentMeta) (AttachmentContent, error) {
text, err := stripXMLText(data)
if err != nil {
return AttachmentContent{}, err
}
return AttachmentContent{
Text: strings.TrimSpace(text),
Metadata: map[string]string{"type": "application/xml"},
}, nil
}
type xlsxAttachmentReader struct{}
func (xlsxAttachmentReader) CanRead(meta AttachmentMeta) bool {
return mimeMatches(meta, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet") || strings.EqualFold(filepath.Ext(meta.Filename), ".xlsx")
}
func (xlsxAttachmentReader) Read(data []byte, meta AttachmentMeta) (AttachmentContent, error) {
zr, err := zip.NewReader(bytes.NewReader(data), int64(len(data)))
if err != nil {
return AttachmentContent{}, err
}
sharedStrings, _ := xlsxLoadSharedStrings(zr)
sheets, err := xlsxLoadSheets(zr, sharedStrings)
if err != nil {
return AttachmentContent{}, err
}
if len(sheets) == 0 {
return AttachmentContent{}, errors.New("no worksheets found in xlsx archive")
}
var textParts []string
var tables [][]string
for _, sheet := range sheets {
if len(sheet.Rows) == 0 {
continue
}
textParts = append(textParts, sheet.Name)
textParts = append(textParts, renderTable(sheet.Rows))
if len(tables) == 0 {
tables = sheet.Rows
}
}
return AttachmentContent{
Text: strings.TrimSpace(strings.Join(textParts, "\n\n")),
Tables: tables,
Metadata: map[string]string{"type": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "sheets": strconv.Itoa(len(sheets))},
}, nil
}
type legacyExcelAttachmentReader struct{}
func (legacyExcelAttachmentReader) CanRead(meta AttachmentMeta) bool {
return mimeMatches(meta, "application/vnd.ms-excel") || strings.EqualFold(filepath.Ext(meta.Filename), ".xls")
}
func (legacyExcelAttachmentReader) Read(data []byte, meta AttachmentMeta) (AttachmentContent, error) {
runs := printableASCIIRuns(data, 4)
content := AttachmentContent{
Text: strings.Join(runs, "\n"),
Metadata: map[string]string{"type": "application/vnd.ms-excel", "strategy": "printable-ascii-runs"},
Warnings: []string{"Legacy .xls extraction is best-effort only and may miss workbook structure or cell ordering"},
}
if content.Text == "" {
content.Warnings = append(content.Warnings, "no readable text runs were recovered from the spreadsheet bytes")
}
return content, nil
}
type imageAttachmentReader struct{}
func (imageAttachmentReader) CanRead(meta AttachmentMeta) bool {
if strings.HasPrefix(strings.ToLower(strings.TrimSpace(meta.MimeType)), "image/") {
return true
}
switch strings.ToLower(strings.TrimSpace(filepath.Ext(meta.Filename))) {
case ".png", ".jpg", ".jpeg", ".gif", ".bmp", ".tif", ".tiff", ".webp", ".heic", ".heif":
return true
default:
return false
}
}
func (imageAttachmentReader) Read(data []byte, meta AttachmentMeta) (AttachmentContent, error) {
content := AttachmentContent{
Metadata: map[string]string{
"type": "image",
"strategy": "embedded-text+runs",
},
Warnings: []string{"Image OCR is best-effort only; embedded text, comments, and readable byte runs may be incomplete"},
}
if meta.Filename != "" {
content.Metadata["filename"] = meta.Filename
}
if meta.MimeType != "" {
content.Metadata["mime"] = meta.MimeType
}
if cfg, format, err := image.DecodeConfig(bytes.NewReader(data)); err == nil {
content.Metadata["decoded_format"] = format
content.Metadata["width"] = strconv.Itoa(cfg.Width)
content.Metadata["height"] = strconv.Itoa(cfg.Height)
}
lines := make([]string, 0, 8)
if meta.Filename != "" {
lines = append(lines, fmt.Sprintf("Filename: %s", meta.Filename))
}
if meta.MimeType != "" {
lines = append(lines, fmt.Sprintf("MIME type: %s", meta.MimeType))
}
hints := extractImageTextHints(data)
if len(hints) > 0 {
lines = append(lines, hints...)
content.Metadata["recovered_text"] = "yes"
}
if len(lines) == 0 {
lines = append(lines, "Image attachment")
content.Warnings = append(content.Warnings, "No embedded text was recovered from the image bytes")
}
content.Text = strings.TrimSpace(strings.Join(compactStrings(lines), "\n"))
return content, nil
}
type pdfAttachmentReader struct{}
func (pdfAttachmentReader) CanRead(meta AttachmentMeta) bool {
return mimeMatches(meta, "application/pdf") || strings.EqualFold(filepath.Ext(meta.Filename), ".pdf")
}
func (pdfAttachmentReader) Read(data []byte, meta AttachmentMeta) (AttachmentContent, error) {
// Best-effort fallback only. Without a PDF parser we can only recover
// printable ASCII runs from the raw bytes, which may miss layout and text.
runs := printableASCIIRuns(data, 6)
content := AttachmentContent{
Text: strings.Join(runs, "\n"),
Metadata: map[string]string{"type": "application/pdf", "strategy": "printable-ascii-runs"},
Warnings: []string{"PDF text extraction is best-effort only and may miss content or ordering"},
}
if content.Text == "" {
content.Warnings = append(content.Warnings, "no printable ASCII text runs were found in the PDF bytes")
}
return content, nil
}
type docxAttachmentReader struct{}
func (docxAttachmentReader) CanRead(meta AttachmentMeta) bool {
return mimeMatches(meta, "application/vnd.openxmlformats-officedocument.wordprocessingml.document") || strings.EqualFold(filepath.Ext(meta.Filename), ".docx")
}
func (docxAttachmentReader) Read(data []byte, meta AttachmentMeta) (AttachmentContent, error) {
zr, err := zip.NewReader(bytes.NewReader(data), int64(len(data)))
if err != nil {
return AttachmentContent{}, err
}
var document []byte
for _, file := range zr.File {
if file.Name != "word/document.xml" {
continue
}
rc, err := file.Open()
if err != nil {
return AttachmentContent{}, err
}
document, err = io.ReadAll(rc)
_ = rc.Close()
if err != nil {
return AttachmentContent{}, err
}
break
}
if len(document) == 0 {
return AttachmentContent{}, errors.New("word/document.xml not found in docx archive")
}
text, err := stripXMLText(document)
if err != nil {
return AttachmentContent{}, err
}
return AttachmentContent{
Text: strings.TrimSpace(text),
Metadata: map[string]string{"type": "application/vnd.openxmlformats-officedocument.wordprocessingml.document"},
}, nil
}
func extractImageTextHints(data []byte) []string {
var hints []string
hints = append(hints, imageBinaryTextRuns(data)...)
hints = append(hints, pngTextChunks(data)...)
hints = append(hints, jpegCommentText(data)...)
hints = append(hints, gifCommentText(data)...)
return compactStrings(filterImageTextHints(hints))
}
func filterImageTextHints(values []string) []string {
out := make([]string, 0, len(values))
seen := map[string]struct{}{}
for _, value := range values {
value = normalizeWhitespace(strings.TrimSpace(value))
if !looksLikeReadableImageText(value) {
continue
}
key := strings.ToLower(value)
if _, exists := seen[key]; exists {
continue
}
seen[key] = struct{}{}
out = append(out, value)
}
return out
}
func looksLikeReadableImageText(value string) bool {
value = strings.TrimSpace(value)
if value == "" {
return false
}
runes := []rune(value)
if len(runes) < 4 {
return false
}
letters := 0
digits := 0
spaces := 0
for _, r := range runes {
switch {
case unicode.IsLetter(r):
letters++
case unicode.IsDigit(r):
digits++
case unicode.IsSpace(r):
spaces++
}
}
if letters == 0 && digits == 0 {
return false
}
alnumRatio := float64(letters+digits+spaces) / float64(len(runes))
return alnumRatio >= 0.55
}
func imageBinaryTextRuns(data []byte) []string {
runs := printableASCIIRuns(data, 8)
if len(runs) == 0 {
return nil
}
out := make([]string, 0, len(runs))
for _, run := range runs {
if looksLikeReadableImageText(run) {
out = append(out, run)
}
}
return out
}
func pngTextChunks(data []byte) []string {
const pngSignature = "\x89PNG\r\n\x1a\n"
if len(data) < len(pngSignature) || !bytes.Equal(data[:len(pngSignature)], []byte(pngSignature)) {
return nil
}
offset := len(pngSignature)
var out []string
for offset+8 <= len(data) {
length := int(binary.BigEndian.Uint32(data[offset : offset+4]))
chunkType := string(data[offset+4 : offset+8])
offset += 8
if length < 0 || offset+length > len(data) {
break
}
chunkData := data[offset : offset+length]
offset += length
if offset+4 > len(data) {
break
}
offset += 4
switch chunkType {
case "tEXt":
if text := pngDecodeTextChunk(chunkData); text != "" {
out = append(out, text)
}
case "zTXt":
if text := pngDecodeCompressedTextChunk(chunkData); text != "" {
out = append(out, text)
}
case "iTXt":
if text := pngDecodeInternationalTextChunk(chunkData); text != "" {
out = append(out, text)
}
case "IEND":
return out
}
}
return out
}
func pngDecodeTextChunk(data []byte) string {
parts := bytes.SplitN(data, []byte{0}, 2)
if len(parts) != 2 {
return ""
}
return strings.TrimSpace(string(parts[1]))
}
func pngDecodeCompressedTextChunk(data []byte) string {
parts := bytes.SplitN(data, []byte{0}, 3)
if len(parts) < 3 {
return ""
}
reader, err := zlib.NewReader(bytes.NewReader(parts[2]))
if err != nil {
return ""
}
defer reader.Close()
raw, err := io.ReadAll(reader)
if err != nil {
return ""
}
return strings.TrimSpace(string(raw))
}
func pngDecodeInternationalTextChunk(data []byte) string {
if len(data) < 3 {
return ""
}
i := bytes.IndexByte(data, 0)
if i < 0 || i+2 >= len(data) {
return ""
}
data = data[i+1:]
compressed := data[0] == 1
data = data[2:]
langEnd := bytes.IndexByte(data, 0)
if langEnd < 0 {
return ""
}
data = data[langEnd+1:]
transEnd := bytes.IndexByte(data, 0)
if transEnd < 0 {
return ""
}
text := data[transEnd+1:]
if compressed {
reader, err := zlib.NewReader(bytes.NewReader(text))
if err != nil {
return ""
}
defer reader.Close()
raw, err := io.ReadAll(reader)
if err != nil {
return ""
}
return strings.TrimSpace(string(raw))
}
return strings.TrimSpace(string(text))
}
func jpegCommentText(data []byte) []string {
if len(data) < 2 || data[0] != 0xFF || data[1] != 0xD8 {
return nil
}
var out []string
for i := 2; i+4 <= len(data); {
if data[i] != 0xFF {
i++
continue
}
for i < len(data) && data[i] == 0xFF {
i++
}
if i >= len(data) {
break
}
marker := data[i]
i++
if marker == 0xD9 || marker == 0xDA {
break
}
if i+2 > len(data) {
break
}
segLen := int(binary.BigEndian.Uint16(data[i : i+2]))
if segLen < 2 || i+segLen > len(data) {
break
}
segment := data[i+2 : i+segLen]
i += segLen
switch marker {
case 0xFE:
if text := strings.TrimSpace(string(segment)); text != "" {
out = append(out, text)
}
case 0xE1:
if text := strings.TrimSpace(strings.Join(filterImageTextHints(printableASCIIRuns(segment, 8)), "\n")); text != "" {
out = append(out, text)
}
}
}
return out
}
func gifCommentText(data []byte) []string {
if len(data) < 6 || (string(data[:6]) != "GIF87a" && string(data[:6]) != "GIF89a") {
return nil
}
var out []string
for i := 6; i < len(data); {
if i+1 < len(data) && data[i] == 0x21 && data[i+1] == 0xFE {
i += 2
var chunks [][]byte
for i < len(data) {
size := int(data[i])
i++
if size == 0 {
break
}
if i+size > len(data) {
break
}
chunks = append(chunks, append([]byte(nil), data[i:i+size]...))
i += size
}
if text := strings.TrimSpace(string(bytes.Join(chunks, nil))); text != "" {
out = append(out, text)
}
continue
}
i++
}
return out
}
func mimeMatches(meta AttachmentMeta, types ...string) bool {
actual := strings.ToLower(strings.TrimSpace(meta.MimeType))
if actual == "" {
return false
}
for _, candidate := range types {
if actual == strings.ToLower(candidate) {
return true
}
}
return false
}
func topLevelJSONKeys(value any) []string {
var keys []string
switch v := value.(type) {
case map[string]any:
for k := range v {
keys = append(keys, k)
}
case []any:
if len(v) > 0 {
if obj, ok := v[0].(map[string]any); ok {
for k := range obj {
keys = append(keys, k)
}
}
}
}
sort.Strings(keys)
return keys
}
func renderTable(rows [][]string) string {
if len(rows) == 0 {
return ""
}
var b strings.Builder
for i, row := range rows {
if i > 0 {
b.WriteByte('\n')
}
b.WriteString(strings.Join(row, " | "))
}
return b.String()
}
func printableASCIIRuns(data []byte, minLen int) []string {
if minLen < 1 {
minLen = 1
}
var runs []string
var current strings.Builder
flush := func() {
if current.Len() >= minLen {
runs = append(runs, strings.TrimSpace(current.String()))
}
current.Reset()
}
for _, b := range data {
switch {
case b == '\n' || b == '\r' || b == '\t':
if current.Len() > 0 && !strings.HasSuffix(current.String(), " ") {
current.WriteByte(' ')
}
case b >= 32 && b <= 126:
current.WriteByte(b)
default:
flush()
}
}
flush()
return compactStrings(runs)
}
func stripXMLText(data []byte) (string, error) {
dec := xml.NewDecoder(bytes.NewReader(data))
var buf bytes.Buffer
lastWasNewline := false
writeSpace := func() {
if buf.Len() == 0 {
return
}
last := buf.Bytes()[buf.Len()-1]
if last != ' ' && last != '\n' {
_ = buf.WriteByte(' ')
}
}
writeNewline := func() {
for buf.Len() > 0 {
last := buf.Bytes()[buf.Len()-1]
if last == ' ' || last == '\t' {
buf.Truncate(buf.Len() - 1)
continue
}
break
}
if buf.Len() > 0 && !lastWasNewline {
_ = buf.WriteByte('\n')
lastWasNewline = true
}
}
for {
tok, err := dec.Token()
if err != nil {
if errors.Is(err, io.EOF) {
break
}
return "", err
}
switch t := tok.(type) {
case xml.StartElement:
switch strings.ToLower(t.Name.Local) {
case "p", "tr":
writeNewline()
case "tab":
writeSpace()
case "br", "cr":
writeNewline()
}
case xml.EndElement:
switch strings.ToLower(t.Name.Local) {
case "p", "tr":
writeNewline()
}
case xml.CharData:
text := normalizeWhitespace(string(t))
if text == "" {
continue
}
if buf.Len() > 0 {
last := buf.Bytes()[buf.Len()-1]
if last != '\n' && last != ' ' {
_ = buf.WriteByte(' ')
}
}
_, _ = buf.WriteString(text)
lastWasNewline = false
}
}
return normalizeLineBreaks(buf.String()), nil
}
type xlsxSheet struct {
Name string
Rows [][]string
}
type xlsxSharedStrings struct {
Items []xlsxSharedStringItem `xml:"si"`
}
type xlsxSharedStringItem struct {
Text string `xml:"t"`
Runs []xlsxSharedStringRun `xml:"r"`
}
type xlsxSharedStringRun struct {
Text string `xml:"t"`
}
type xlsxWorksheet struct {
Rows []xlsxWorksheetRow `xml:"sheetData>row"`
}
type xlsxWorksheetRow struct {
Cells []xlsxWorksheetCell `xml:"c"`
}
type xlsxWorksheetCell struct {
Ref string `xml:"r,attr"`
Type string `xml:"t,attr"`
Value string `xml:"v"`
InlineText string `xml:"is>t"`
}