File size: 9,677 Bytes
17f4503
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9c56a9c
17f4503
9c56a9c
 
17f4503
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9c56a9c
 
17f4503
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9c56a9c
 
17f4503
9c56a9c
17f4503
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9c56a9c
17f4503
 
 
9c56a9c
17f4503
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9c56a9c
 
 
 
17f4503
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
Reading text out of uploaded files, and the background queue that processes note uploads.

Reading a PDF or photo with Sarvam Vision can take minutes, so /upload_note only checks the file
and queues it. A worker thread reads the text, saves it for search, and only then adds the file
to the user's folder tree. The browser polls /jobs/{job_id} to show progress.
"""
import logging
import os
import threading
import time
import uuid
from concurrent.futures import ThreadPoolExecutor
from dataclasses import dataclass

from fastapi import HTTPException, UploadFile

from backend import alerts, ocr, originals, usage
from backend.pages import PageStarts, anchor_page_starts, join_pages, pdf_page_texts
from backend.pipeline.indexing import index_note
from backend.store import user_document_upsert, user_lock, vfs_set_tree
from backend.paths import get_vfs_tree_clean
from backend.settings import MAX_ACTIVE_UPLOADS_PER_USER, MAX_UPLOAD_BYTES, MAX_UPLOAD_MB
from backend.vfs_tree import tree_add_file

logger = logging.getLogger(__name__)

IMAGE_MIME_TYPES = {
    ".jpg": "image/jpeg",
    ".jpeg": "image/jpeg",
    ".png": "image/png",
    ".webp": "image/webp",
    ".gif": "image/gif",
    ".bmp": "image/bmp",
    ".tiff": "image/tiff",
}
PLAIN_TEXT_EXTS = (".txt", ".md", ".csv", ".json", ".log")
JOB_KEEP_SECONDS = 3600


class ExtractionError(Exception):
    """No text could be read from the file; the message is shown to the user."""


def clean_upload_name(file: UploadFile) -> str:
    raw_name = (file.filename or "upload").replace("\\", "/").split("/")[-1].strip()
    if not raw_name or ".." in raw_name:
        raise HTTPException(status_code=400, detail="Invalid file name.")
    return raw_name


def check_supported_type(raw_name: str) -> None:
    ext = os.path.splitext(raw_name)[1].lower()
    if ext != ".pdf" and ext not in IMAGE_MIME_TYPES and ext not in PLAIN_TEXT_EXTS:
        raise HTTPException(
            status_code=415,
            detail="This file type isn't supported. Upload a PDF, an image, or a text file "
            "(.txt, .md, .csv, .json, .log).",
        )


def read_upload(file: UploadFile) -> bytes:
    """Read the upload, refusing files over MAX_UPLOAD_MB without reading the whole thing."""
    data = file.file.read(MAX_UPLOAD_BYTES + 1)
    if len(data) > MAX_UPLOAD_BYTES:
        raise HTTPException(
            status_code=413,
            detail=f"File is too large. The limit is {MAX_UPLOAD_MB:g} MB.",
        )
    return data


@dataclass
class Extracted:
    text: str
    note: str
    page_starts: PageStarts | None = None  # where each PDF page starts in `text`
    pages_sent_to_ai: int = 0              # pages Sarvam Vision was asked to read (for cost tracking)


def _read_pdf(data: bytes) -> Extracted:
    local_error: Exception | None = None
    try:
        local_pages = pdf_page_texts(data)
    except Exception as e:  # not a readable PDF for PyMuPDF; Sarvam may still manage
        local_pages, local_error = [], e
    text, note, ai_pages = ocr.transcribe_pdf_with_pages(data)
    sent = (len(local_pages) or 1) if ocr.sarvam_api_key() else 0
    if (text or "").strip():
        # Find each page inside Sarvam's text: its own per-page text first, else PyMuPDF's.
        starts = anchor_page_starts(text, ai_pages) or anchor_page_starts(text, local_pages)
        return Extracted(text, note or "", starts, sent)
    if local_error is not None:
        raise local_error
    joined, starts = join_pages(local_pages)
    return Extracted(joined, note or "used_pdf_parser_fallback", starts if len(starts) > 1 else None, sent)


def extract_text(raw_name: str, data: bytes) -> Extracted:
    """
    Read the text of a PDF, image or plain-text file of a supported type.
    Raises ExtractionError when no text can be read.
    """
    ext = os.path.splitext(raw_name)[1].lower()
    try:
        if ext == ".pdf":
            result = _read_pdf(data)
        elif ext in IMAGE_MIME_TYPES:
            text, note = ocr.transcribe_handwritten_image(data, IMAGE_MIME_TYPES[ext])
            sent = 1 if ocr.sarvam_api_key() else 0
            if not (text or "").strip():
                text = ocr.tesseract_image_text(data)
                note = note or "used_tesseract_fallback"
            result = Extracted(text, note or "", None, sent)
        else:
            result = Extracted(data.decode("utf-8", errors="replace"), "plain_text")
    except Exception as e:
        logger.exception("Text extraction failed for %s", raw_name)
        raise ExtractionError("Couldn't read this file. It may be damaged or password-protected.") from e
    stripped = (result.text or "").strip()
    if not stripped:
        raise ExtractionError("Couldn't find any text in this file.")
    if stripped != result.text and result.page_starts:
        shift = len(result.text) - len(result.text.lstrip())
        result.page_starts = [(max(0, off - shift), page) for off, page in result.page_starts]
    result.text = stripped
    return result


def extract_text_or_http_error(raw_name: str, data: bytes) -> Extracted:
    try:
        return extract_text(raw_name, data)
    except ExtractionError as e:
        raise HTTPException(status_code=422, detail=str(e))


def save_note_text(user_id: str, folder: str, raw_name: str, text: str, page_starts: PageStarts | None = None) -> dict:
    """Save text for search and as the file's stored text, then add the file to the tree."""
    rel_path = f"{folder}/{raw_name}" if folder else raw_name
    ingest_result = index_note(user_id, rel_path, raw_name, text, page_starts)
    try:
        user_document_upsert(user_id, rel_path, text, raw_name)
    except Exception:
        # The passages make it searchable; the full-text copy is used for viewing, editing and study tools.
        logger.warning("Stored-text write failed for %s", rel_path, exc_info=True)
    with user_lock(user_id):
        tree = get_vfs_tree_clean(user_id)
        vfs_set_tree(user_id, tree_add_file(tree, folder, raw_name))
    return ingest_result


# ---------- Background upload jobs ----------
_executor = ThreadPoolExecutor(max_workers=2, thread_name_prefix="upload")
_jobs: dict[str, dict] = {}
_jobs_lock = threading.Lock()


def _public(job: dict) -> dict:
    return {k: job[k] for k in ("job_id", "status", "path", "name", "error", "message")}


def _prune_locked(now: float) -> None:
    old = [
        jid
        for jid, j in _jobs.items()
        if j["status"] in ("done", "failed") and now - j["updated_at"] > JOB_KEEP_SECONDS
    ]
    for jid in old:
        del _jobs[jid]


def _set(job_id: str, **fields) -> None:
    with _jobs_lock:
        job = _jobs.get(job_id)
        if job:
            job.update(fields, updated_at=time.time())


def _process(job_id: str, user_id: str, folder: str, raw_name: str, data: bytes) -> None:
    _set(job_id, status="processing")
    try:
        extracted = extract_text(raw_name, data)
        usage.record(user_id, pages_read=extracted.pages_sent_to_ai)
        result = save_note_text(user_id, folder, raw_name, extracted.text, extracted.page_starts)
        # Keep the PDF/photo itself too, so it opens on any device.
        kept = originals.keep(user_id, f"{folder}/{raw_name}" if folder else raw_name, raw_name, data)
        message = f"Ready: {result.get('chunks_created', 0)} searchable sections."
        _set(job_id, status="done", message=f"{message} {kept}" if kept else message)
    except ExtractionError as e:
        usage.record(user_id, upload_failures=1)
        _set(job_id, status="failed", error=str(e))
    except Exception as e:
        logger.exception("Upload job %s failed", job_id)
        usage.record(user_id, upload_failures=1)
        alerts.notify("upload-crash", f"Upload job failed unexpectedly: {type(e).__name__}: {e}")
        _set(job_id, status="failed", error=f"Couldn't save '{raw_name}' for search. Please try again.")


def submit_upload_job(user_id: str, folder: str, raw_name: str, data: bytes) -> dict:
    now = time.time()
    with _jobs_lock:
        _prune_locked(now)
        active = sum(1 for j in _jobs.values() if j["user_id"] == user_id and j["status"] in ("queued", "processing"))
        if active >= MAX_ACTIVE_UPLOADS_PER_USER:
            raise HTTPException(
                status_code=429,
                detail=f"You already have {active} files being processed. Please wait for them to finish.",
            )
        job_id = uuid.uuid4().hex
        job = {
            "job_id": job_id,
            "user_id": user_id,
            "status": "queued",
            "path": f"{folder}/{raw_name}" if folder else raw_name,
            "name": raw_name,
            "error": None,
            "message": None,
            "created_at": now,
            "updated_at": now,
        }
        _jobs[job_id] = job
        # Snapshot before the worker starts: a fast failure must not change the reply mid-build.
        reply = _public(job)
    _executor.submit(_process, job_id, user_id, folder, raw_name, data)
    return reply


def get_job(user_id: str, job_id: str) -> dict | None:
    with _jobs_lock:
        job = _jobs.get(job_id)
        return _public(job) if job and job["user_id"] == user_id else None


def list_jobs(user_id: str) -> list[dict]:
    with _jobs_lock:
        _prune_locked(time.time())
        mine = [j for j in _jobs.values() if j["user_id"] == user_id]
    mine.sort(key=lambda j: j["created_at"], reverse=True)
    return [_public(j) for j in mine]


def forget_user_jobs(user_id: str) -> None:
    with _jobs_lock:
        for jid in [jid for jid, j in _jobs.items() if j["user_id"] == user_id]:
            del _jobs[jid]