Follow-ups to Phase E (ADR-15): - Recordings over 25 MB are cut into pieces and transcribed in turn: with ffmpeg (now in the server and all-in-one images) any format is re-encoded to 16 kHz mono MP3 in 20-minute pieces; without it, MP3 is cut at frame boundaries and WAV at sample boundaries in Go. - PDFs without a text layer are written out by a document-capable chat model (Anthropic document input, OpenAI file input); Ollama is skipped. - Phone app: AI answers render as Markdown with tappable citations; the editing toolbar opens the writing actions on the selection; audio files get Transcribe. Editor bridge protocol 4 adds setAi, getSelection, insertMarkdown and transcribe/transcribed. - The transcript HTML builder moves to @docwell/editor, shared by the web app and the phone editor. - An integration test runs chat, Transcribe and writing actions on a device against a live server; the editor test no longer expects headings to have only a level. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
216 lines
6.8 KiB
Go
216 lines
6.8 KiB
Go
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
|
|
package ai
|
|
|
|
import (
|
|
"bytes"
|
|
"context"
|
|
"errors"
|
|
"fmt"
|
|
"path/filepath"
|
|
"strings"
|
|
"unicode/utf8"
|
|
|
|
"docwell/server/internal/access"
|
|
"docwell/server/internal/apperr"
|
|
"docwell/server/internal/convert"
|
|
"docwell/server/internal/store/pocketbase"
|
|
|
|
"github.com/ledongthuc/pdf"
|
|
)
|
|
|
|
// ---- Extra files for retrieval ----------------------------------------------------
|
|
//
|
|
// Workspace admins can add documents that are not pages (a handbook, a
|
|
// spec) to what chat retrieves. Only their text is kept.
|
|
|
|
// MaxFileBytes caps one uploaded file.
|
|
const MaxFileBytes = 10 << 20
|
|
|
|
const maxFileText = 2_000_000
|
|
|
|
type fileRecord struct {
|
|
ID string `json:"id"`
|
|
Workspace string `json:"workspace"`
|
|
Name string `json:"name"`
|
|
ContentText string `json:"content_text"`
|
|
Size float64 `json:"size"`
|
|
Updated string `json:"updated"`
|
|
Created string `json:"created"`
|
|
}
|
|
|
|
// File is an extra document as admins see it.
|
|
type File struct {
|
|
ID string `json:"id"`
|
|
Name string `json:"name"`
|
|
Size int `json:"size"`
|
|
Chars int `json:"chars"`
|
|
Indexed bool `json:"indexed"`
|
|
Created string `json:"created"`
|
|
}
|
|
|
|
// extractText reads the text of a supported file.
|
|
func extractText(name string, data []byte) (string, error) {
|
|
switch strings.ToLower(filepath.Ext(name)) {
|
|
case ".txt", ".md", ".markdown", ".csv", ".json", ".yaml", ".yml", ".xml", ".rst", ".org":
|
|
if !utf8.Valid(data) {
|
|
return "", apperr.Invalid("The file is not UTF-8 text.")
|
|
}
|
|
return string(data), nil
|
|
case ".html", ".htm":
|
|
doc, err := convert.FromHTML(string(data))
|
|
if err != nil {
|
|
return "", apperr.Invalid("The HTML file could not be read.")
|
|
}
|
|
return convert.Markdown(doc, convert.Options{}), nil
|
|
case ".pdf":
|
|
return pdfText(data)
|
|
case ".docx":
|
|
doc, _, err := convert.FromDOCX(data)
|
|
if err != nil {
|
|
return "", apperr.Invalid("The Word document could not be read.")
|
|
}
|
|
return convert.Markdown(doc, convert.Options{}), nil
|
|
}
|
|
return "", apperr.Invalid("Add text, Markdown, HTML, Word (.docx) or PDF files.")
|
|
}
|
|
|
|
// errNoPDFText is a PDF without a text layer (scanned pages).
|
|
var errNoPDFText = apperr.Invalid("The PDF has no text layer.")
|
|
|
|
const ocrSystem = `You turn documents into text for a team wiki. Write out all the text of the document, page by page, as Markdown: keep headings, lists and tables, and describe charts or pictures in one short line in brackets. No preamble and no remarks of your own.`
|
|
|
|
// readScannedPDF has a document-reading chat model write out a PDF without
|
|
// a text layer (scanned pages).
|
|
func (s *Service) readScannedPDF(ctx context.Context, c access.Caller, wsID string, data []byte) (string, error) {
|
|
_, chain, err := s.ready(ctx, c, wsID)
|
|
if err != nil {
|
|
return "", apperr.Invalid("The PDF has no text layer, and AI cannot read it here: " + userError(err))
|
|
}
|
|
var out strings.Builder
|
|
_, err = s.chat(ctx, wsID, chain, ChatRequest{
|
|
System: ocrSystem, MaxTokens: 32000, PDF: data,
|
|
Messages: []Message{{Role: "user", Content: "Write out the text of this document."}},
|
|
}, func(d string) { out.WriteString(d) })
|
|
if err != nil {
|
|
if errors.Is(err, ErrNoDocuments) || errors.Is(err, errNoProfile) {
|
|
return "", apperr.Invalid("The PDF has no text layer (scanned pages). To read it, add an Anthropic or OpenAI provider whose model reads PDF files.")
|
|
}
|
|
return "", apperr.Invalid("The PDF has no text layer, and AI could not read it: " + userError(err))
|
|
}
|
|
return out.String(), nil
|
|
}
|
|
|
|
// pdfText reads a PDF's text page by page. Scanned PDFs have none (no OCR).
|
|
// The reader panics on some malformed files, so that becomes an error.
|
|
func pdfText(data []byte) (text string, err error) {
|
|
bad := apperr.Invalid("The PDF could not be read.")
|
|
defer func() {
|
|
if recover() != nil {
|
|
text, err = "", bad
|
|
}
|
|
}()
|
|
r, err := pdf.NewReader(bytes.NewReader(data), int64(len(data)))
|
|
if err != nil {
|
|
return "", bad
|
|
}
|
|
var b strings.Builder
|
|
for i := 1; i <= r.NumPage(); i++ {
|
|
p := r.Page(i)
|
|
if p.V.IsNull() {
|
|
continue
|
|
}
|
|
t, err := p.GetPlainText(nil)
|
|
if err != nil {
|
|
continue
|
|
}
|
|
if t = strings.TrimSpace(t); t != "" {
|
|
b.WriteString(t)
|
|
b.WriteString("\n\n")
|
|
}
|
|
}
|
|
if strings.TrimSpace(b.String()) == "" {
|
|
return "", errNoPDFText
|
|
}
|
|
return b.String(), nil
|
|
}
|
|
|
|
func (s *Service) fileView(ws string, r fileRecord) File {
|
|
h, _ := s.store.Hash(ws, "file/"+r.ID)
|
|
return File{ID: r.ID, Name: r.Name, Size: int(r.Size), Chars: utf8.RuneCountInString(r.ContentText), Indexed: h != "", Created: r.Created}
|
|
}
|
|
|
|
// ListFiles lists a workspace's extra files (workspace admin).
|
|
func (s *Service) ListFiles(ctx context.Context, c access.Caller, wsID string) ([]File, error) {
|
|
if err := s.canManage(ctx, c, wsID); err != nil {
|
|
return nil, err
|
|
}
|
|
res, err := pocketbase.List[fileRecord](ctx, s.pb, "ai_files", pocketbase.ListOptions{
|
|
PerPage: 500, Filter: fmt.Sprintf("workspace = '%s'", wsID), Sort: "name",
|
|
})
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
out := make([]File, 0, len(res.Items))
|
|
for _, r := range res.Items {
|
|
out = append(out, s.fileView(wsID, r))
|
|
}
|
|
return out, nil
|
|
}
|
|
|
|
// AddFile stores an extra file's text (workspace admin).
|
|
func (s *Service) AddFile(ctx context.Context, c access.Caller, wsID, name string, data []byte) (File, error) {
|
|
if err := s.canManage(ctx, c, wsID); err != nil {
|
|
return File{}, err
|
|
}
|
|
name = strings.TrimSpace(filepath.Base(name))
|
|
if name == "" || name == "." || len(name) > 200 {
|
|
return File{}, apperr.Invalid("The file needs a name of up to 200 characters.")
|
|
}
|
|
if len(data) > MaxFileBytes {
|
|
return File{}, apperr.Invalid("Files can be up to 10 MB.")
|
|
}
|
|
text, err := extractText(name, data)
|
|
if errors.Is(err, errNoPDFText) {
|
|
text, err = s.readScannedPDF(ctx, c, wsID, data)
|
|
}
|
|
if err != nil {
|
|
return File{}, err
|
|
}
|
|
if strings.TrimSpace(text) == "" {
|
|
return File{}, apperr.Invalid("The file has no text.")
|
|
}
|
|
if utf8.RuneCountInString(text) > maxFileText {
|
|
text = string([]rune(text)[:maxFileText])
|
|
}
|
|
rec, err := pocketbase.Create[fileRecord](ctx, s.pb, "ai_files", map[string]any{
|
|
"workspace": wsID, "name": name, "content_text": text, "size": len(data), "created_by": c.ID,
|
|
})
|
|
if err != nil {
|
|
return File{}, err
|
|
}
|
|
s.wake()
|
|
return s.fileView(wsID, rec), nil
|
|
}
|
|
|
|
// DeleteFile removes an extra file and its vectors (workspace admin).
|
|
func (s *Service) DeleteFile(ctx context.Context, c access.Caller, id string) error {
|
|
if !validID(id) {
|
|
return apperr.NotFound("file not found")
|
|
}
|
|
rec, err := pocketbase.Get[fileRecord](ctx, s.pb, "ai_files", id)
|
|
if err != nil {
|
|
if pocketbase.IsNotFound(err) {
|
|
return apperr.NotFound("file not found")
|
|
}
|
|
return err
|
|
}
|
|
if err := s.canManage(ctx, c, rec.Workspace); err != nil {
|
|
return apperr.NotFound("file not found")
|
|
}
|
|
if err := s.pb.Delete(ctx, "ai_files", id); err != nil {
|
|
return err
|
|
}
|
|
return s.store.Drop(rec.Workspace, "file/"+id)
|
|
}
|