Spaces:
Runtime error
Runtime error
Rajeev Pandey commited on
Commit ·
e1242e7
1
Parent(s): 12a86e2
Improve document scrolling and interactive insights
Browse filesFiles changed (8)
92 unmodified lines9394959697989919 unmodified lines1191201211221231241251265 unmodified lines13213313413513613713813916 unmodified lines15615715815916016116215716316416516692 unmodified lines- [x] No more than three highest-confidence dots are shown on the page at once.- [x] Dots use the reduced 18px control size and can be dragged to uncover document text.- [x] A readable single-word OCR region can receive a contextual dot when it is not already represented by a verified term.- [x] Clicking selectable document text creates a dot at the clicked location without exceeding the three-dot limit.
### Selection, highlight, and business insight
19 unmodified lines- [x] Files over 15 MB are rejected before analysis.- [x] Uploaded document images and files are not persisted by default.- [x] Uploaded document previews use a dedicated scroll container with visible native scrollbars.- [x] Multi-page PDFs render into one continuous scroll surface with positioned text and dots across pages.- [x] DOCX rendering grows with document content rather than stopping at the earlier fixed preview height.
### Camera and performance
5 unmodified lines- [x] Large uploaded images are resized to a maximum 1600px edge in the browser before transfer.- [x] Small images avoid unnecessary recompression.- [x] Portable CPU OCR is warmed in the background to reduce first-scan latency.- [x] Uploaded images are preprocessed for contrast/sharpness at a bounded 1400px edge.- [x] The last four document analyses are cached in memory for immediate repeat uploads.
### Responsive UI and accessibility
16 unmodified lines- [x] SME-approved definitions override pending user corrections.- [x] Feedback and review actions preserve an audit history.- [x] AI-generated or unmatched explanations are marked unverified.- [x] Confidence combines recognition and knowledge signals using calibrated weighting rather than artificially multiplying scores downward.
### Automated verification recorded
- [x] Python/API suite: 12 tests passing.- [x] Python/API suite: 15 tests passing.- [x] JavaScript syntax checks: camera, overlay, feedback, and insights scripts passing.- [x] DOM integration: two terms produced two dots.- [x] DOM integration: dot click expanded the inline definition.1234567898101112131 unmodified line1516171819202122232425262 unmodified lines29303132333435363730313233343538394041424344454647484950511 unmodified line535455565743585960619 unmodified lines717273596061626374757677787980818283848586878889909192656667686993949596979899100101102103104105106107108109110111112113114737475767778798011511611711811912012121 unmodified lines14314414510814614714814922 unmodified lines172173174137175176177178import base64import hashlibimport ioimport textwrapimport zipfilefrom collections import OrderedDictfrom pathlib import Pathfrom xml.etree import ElementTree
from PIL import Image, ImageDraw, ImageFontfrom PIL import Image, ImageDraw, ImageFilter, ImageFont, ImageOps
from backend.glossary_service import GlossaryServicefrom backend.ocr_service import OCRService1 unmodified line
class DocumentService: MAX_BYTES = 15 * 1024 * 1024 MAX_PDF_PAGES = 12
def __init__(self, ocr: OCRService, glossary: GlossaryService): self.ocr = ocr self.glossary = glossary self._cache: OrderedDict[str, dict] = OrderedDict()
def analyze(self, encoded: str, filename: str, language: str) -> dict: try:2 unmodified lines raise ValueError("Invalid uploaded document") from exc if not raw or len(raw) > self.MAX_BYTES: raise ValueError("Document must be between 1 byte and 15 MB") cache_key = hashlib.sha256(raw + filename.lower().encode() + language.encode()).hexdigest() if cache_key in self._cache: self._cache.move_to_end(cache_key) return {**self._cache[cache_key], "cached": True} extension = Path(filename).suffix.lower() if extension in {".jpg", ".jpeg", ".png", ".webp"}: return self._image(raw, language) if extension == ".pdf": return self._pdf(raw) if extension == ".docx": return self._docx(raw) raise ValueError("Supported formats are JPG, PNG, WebP, PDF, and DOCX") result = self._image(raw, language) elif extension == ".pdf": result = self._pdf(raw) elif extension == ".docx": result = self._docx(raw) else: raise ValueError("Supported formats are JPG, PNG, WebP, PDF, and DOCX") self._cache[cache_key] = result while len(self._cache) > 4: self._cache.popitem(last=False) return {**result, "cached": False}
def _image(self, raw: bytes, language: str) -> dict: try:1 unmodified line image.load() except Exception as exc: raise ValueError("The uploaded image could not be opened") from exc image.thumbnail((1400, 1400), Image.Resampling.LANCZOS) prepared = ImageOps.autocontrast(image.convert("L")).filter(ImageFilter.SHARPEN).convert("RGB") detections = self.ocr.extract(image, language) detections = self.ocr.extract(prepared, language) terms = self.glossary.match_regions(detections) if len(terms) < 3: terms.extend(self.glossary.contextual_fallbacks(detections, 3 - len(terms), terms))9 unmodified lines document = fitz.open(stream=raw, filetype="pdf") if document.page_count < 1: raise ValueError("The PDF has no pages") page = document[0] zoom = min(2.0, 1800 / max(page.rect.width, page.rect.height)) matrix = fitz.Matrix(zoom, zoom) pixmap = page.get_pixmap(matrix=matrix, alpha=False) image = Image.frombytes("RGB", [pixmap.width, pixmap.height], pixmap.samples) page_count = min(document.page_count, self.MAX_PDF_PAGES) rendered = [] canvas_width = 0 for index in range(page_count): page = document[index] zoom = min(1.5, 1100 / max(1, page.rect.width)) pixmap = page.get_pixmap(matrix=fitz.Matrix(zoom, zoom), alpha=False) page_image = Image.frombytes("RGB", [pixmap.width, pixmap.height], pixmap.samples) rendered.append((page, page_image, zoom)) canvas_width = max(canvas_width, page_image.width) gap = 18 total_height = sum(item[1].height for item in rendered) + gap * max(0, page_count - 1) image = Image.new("RGB", (canvas_width, total_height), "#dfe3df") regions = [] y_offset = 0 for page, page_image, zoom in rendered: x_offset = (canvas_width - page_image.width) // 2 image.paste(page_image, (x_offset, y_offset)) page_regions = [] for block in page.get_text("blocks"): x1, y1, x2, y2, text = block[:5] if text.strip(): regions.append({"text": text, "bbox": [x1 * zoom, y1 * zoom, x2 * zoom, y2 * zoom], "confidence": 1.0, "language": self._language(text)}) for block in page.get_text("blocks"): x1, y1, x2, y2, text = block[:5] if text.strip(): page_regions.append({ "text": text, "bbox": [x_offset + x1 * zoom, y_offset + y1 * zoom, x_offset + x2 * zoom, y_offset + y2 * zoom], "confidence": 1.0, "language": self._language(text), }) if page_regions: regions.extend(page_regions) else: page_detections = self.ocr.extract(page_image, "en") for item in page_detections: item["bbox"] = [item["bbox"][0] + x_offset, item["bbox"][1] + y_offset, item["bbox"][2] + x_offset, item["bbox"][3] + y_offset] regions.extend(page_detections) y_offset += page_image.height + gap terms = self.glossary.match_regions(regions) if len(terms) < 3: terms.extend(self.glossary.contextual_fallbacks(regions, 3 - len(terms), terms)) if not regions: detections = self.ocr.extract(image, "en") terms = self.glossary.match_regions(detections) if len(terms) < 3: terms.extend(self.glossary.contextual_fallbacks(detections, 3 - len(terms), terms)) _, unknown = self.glossary.match_ocr(detections) return self._result(image, terms, detections, unknown, "scanned_pdf_ocr") return self._result(image, terms, regions, [], "pdf_text") result = self._result(image, terms, regions, [], "pdf_multpage") result.update({"page_count": document.page_count, "pages_analyzed": page_count, "truncated": document.page_count > page_count}) return result except (ValueError, RuntimeError): raise except Exception as exc:21 unmodified lines for paragraph in paragraphs: wrapped.extend(textwrap.wrap(paragraph, width=85, break_long_words=False) or [""]) wrapped.append("") height = min(2200, max(900, margin * 2 + len(wrapped) * line_height)) height = max(900, margin * 2 + len(wrapped) * line_height) image = Image.new("RGB", (width, height), "#ffffff") draw = ImageDraw.Draw(image) try:22 unmodified lines @staticmethod def _result(image: Image.Image, terms: list, detections: list, unknown: list, method: str) -> dict: output = io.BytesIO() image.save(output, format="JPEG", quality=88, optimize=True) image.save(output, format="JPEG", quality=80, optimize=True) return { "detected_terms": terms, "ocr_items": detections,143 unmodified lines144145146147148149150151148152153154155143 unmodified lines "ocr_confidence": region.get("confidence", 1.0), "language": region.get("language", "en"), }) knowledge_confidence = float(definition["confidence"]) recognition_confidence = float(region.get("confidence", 1.0)) # Calibrate two independent signals instead of multiplying them into an # artificially low score. OCR remains the dominant factor. definition["confidence"] = round( definition["confidence"] * float(region.get("confidence", 1.0)), 3 0.72 * recognition_confidence + 0.28 * knowledge_confidence, 3 ) found.append(definition) return found4 unmodified lines56788910114 unmodified lines "current_module": "Representative device validation", "pending_modules": ["Install production OCR models", "Configure optional hosted AI endpoint", "Configure optional VLM endpoint", "Persistent production database"], "open_issues": ["Local JSON storage is single-instance and ephemeral on default free Spaces", "PaddleOCR model download adds cold-start time", "Remote AI and VLM adapters require provider-specific endpoint contracts"], "last_completed_step": "Added scrollable document stage, three small draggable dots, full-page Info summary, faster multi-word selection, and removed right-panel selection history", "last_completed_step": "Added continuous multi-page scrolling, click-text-to-dot interaction, calibrated confidence, OCR preprocessing, and repeat-upload caching", "next_recommended_step": "Run the remaining physical iPhone/Android acceptance checks, then execute GitHub CI and Hugging Face smoke tests after remotes are configured", "last_updated": "2026-06-20T12:00:00Z"}217 unmodified lines218219220221221222223223224225226227228229230230231232233217 unmodified lines const objectUrl = URL.createObjectURL(file); try { const image = await loadImage(objectUrl); const maxEdge = 1600; const maxEdge = 1400; const scale = Math.min(1, maxEdge / Math.max(image.naturalWidth, image.naturalHeight)); if (scale === 1 && file.size < 2.5 * 1024 * 1024) { if (scale === 1 && file.size < 2 * 1024 * 1024) { return { base64: await readBase64(file), filename: file.name }; } const canvas = document.createElement("canvas"); canvas.width = Math.max(1, Math.round(image.naturalWidth * scale)); canvas.height = Math.max(1, Math.round(image.naturalHeight * scale)); canvas.getContext("2d").drawImage(image, 0, 0, canvas.width, canvas.height); const blob = await new Promise((resolve) => canvas.toBlob(resolve, "image/jpeg", 0.84)); const blob = await new Promise((resolve) => canvas.toBlob(resolve, "image/jpeg", 0.80)); return { base64: await readBase64(blob), filename: "optimized-upload.jpg" }; } finally { URL.revokeObjectURL(objectUrl);113 unmodified lines11411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116240 unmodified lines203204205206207208209113 unmodified lines marker.addEventListener("pointercancel", finish); }
function triggerDotAtText(event, region, layout) { const selection = window.getSelection(); if (selection && !selection.isCollapsed && selection.toString().trim()) return; const existingMarkers = [...overlay.querySelectorAll(".term-marker")]; if (existingMarkers.length >= 3) { (overlay.querySelector(".term-marker.user-triggered") || existingMarkers[existingMarkers.length - 1]).remove(); } const match = terms.find((item) => item.bbox?.every((value, index) => Math.abs(value - region.bbox[index]) < 2) || String(region.text).toLowerCase().includes(String(item.term).toLowerCase()) ); const item = match || { term: String(region.text).trim().slice(0, 58), definition: "Select this phrase for a contextual summary and business meaning.", confidence: Math.min(.72, Number(region.confidence || .75) * .72), source: "ai_generated_unverified", source_label: "Document context · needs verification", category: "Document Context", related_terms: [], document_types: [], bbox: region.bbox, }; const overlayRect = overlay.getBoundingClientRect(); const marker = document.createElement("button"); marker.className = "term-marker user-triggered"; marker.type = "button"; marker.style.left = `${clamp(event.clientX - overlayRect.left - 9, 5, layout.viewRect.width - 23)}px`; marker.style.top = `${clamp(event.clientY - overlayRect.top - 9, 5, layout.viewRect.height - 23)}px`; marker.setAttribute("aria-label", `Explain ${item.term}`); marker.innerHTML = "<span></span>"; let dragged = false; enableDrag(marker, layout, () => { dragged = true; }); marker.onclick = (clickEvent) => { clickEvent.stopPropagation(); if (dragged) { dragged = false; return; } openPopover(item, marker, layout); }; overlay.appendChild(marker); }
function openPopover(item, marker, layout) { closePopover(); marker.classList.add("active");40 unmodified lines span.style.width = `${Math.max(8, (x2 - x1) * layout.scale)}px`; span.style.height = `${Math.max(12, (y2 - y1) * layout.scale)}px`; span.style.fontSize = `${clamp((y2 - y1) * layout.scale * 0.72, 8, 24)}px`; span.addEventListener("click", (event) => triggerDotAtText(event, region, layout)); layer.appendChild(span); }); const explainSelection = () => {49 unmodified lines505152535354555623 unmodified lines8081828383848586878849 unmodified lines.scanner-shell { display: flex; flex-direction: column; min-height: 0; overflow: hidden; background: var(--white); border: 1px solid rgba(20,35,31,.06); border-radius: 20px; box-shadow: var(--shadow); transition: grid-template-columns .42s cubic-bezier(.22,1,.36,1); }.viewport { position: relative; min-height: min(62svh, 560px); background: radial-gradient(circle at center, #23423a, #071a18 72%); overflow: hidden; }.viewport video { position: absolute; width: 100%; height: 100%; object-fit: contain; }.document-scroller { position: absolute; inset: 0; z-index: 1; overflow: auto; overscroll-behavior: contain; scrollbar-gutter: stable; scrollbar-color: #71827c #162a25; scrollbar-width: auto; background: #152622; }.document-scroller { position: absolute; inset: 0; z-index: 1; overflow: auto; overscroll-behavior: contain; scrollbar-gutter: stable; scrollbar-color: #71827c #162a25; scrollbar-width: auto; background: #152622; -webkit-overflow-scrolling: touch; touch-action: pan-x pan-y; }.document-scroller[hidden] { display: none; }.document-scroller::-webkit-scrollbar { width: 11px; height: 11px; }.document-scroller::-webkit-scrollbar-track { background: #162a25; }23 unmodified lines.document-info span { display: grid; place-items: center; width: 25px; height: 25px; background: var(--lime); color: var(--dark); border-radius: 50%; font-family: Georgia, serif; font-weight: 800; }.document-info b { display: none; font-size: 10px; }.selection-layer { position: absolute; inset: 0; z-index: 2; pointer-events: none; }.selectable-region { position: absolute; display: block; overflow: hidden; color: transparent; line-height: 1; white-space: pre-wrap; user-select: text; -webkit-user-select: text; pointer-events: auto; cursor: text; }.selectable-region { position: absolute; display: block; overflow: hidden; color: transparent; line-height: 1; white-space: pre-wrap; user-select: text; -webkit-user-select: text; pointer-events: auto; cursor: text; touch-action: pan-x pan-y; }.term-marker.user-triggered { animation: marker-pulse .28s cubic-bezier(.22,1,.36,1); }@keyframes marker-pulse { from { opacity: 0; transform: scale(.2); } 70% { transform: scale(1.25); } }.selectable-region::selection { background: rgba(201,242,87,.72); color: rgba(8,28,24,.9); }@keyframes pop { from { scale: .2; opacity: 0; } }.corner { position: absolute; width: 34px; height: 34px; border-color: var(--lime); border-style: solid; opacity: .8; }124 unmodified lines125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165124 unmodified lines assert 'id="stabilityMetric"' not in html assert 'id="lightMetric"' not in html assert 'id="ocrMetric"' not in html
def test_multipage_pdf_is_rendered_as_one_scroll_surface(): import fitz document = fitz.open() first = document.new_page() first.insert_text((72, 100), "Commercial Invoice and HS Code", fontsize=16) second = document.new_page() second.insert_text((72, 100), "Packing List and Customs Duty", fontsize=16) response = client.post("/analyze-document", json={ "file_base64": base64.b64encode(document.tobytes()).decode(), "filename": "two-pages.pdf", "language_preference": "en", }) assert response.status_code == 200 data = response.json() assert data["page_count"] == 2 assert data["pages_analyzed"] == 2 assert data["frame_height"] > data["frame_width"] * 2 assert {item["term"] for item in data["detected_terms"]} >= {"HS Code", "Commercial Invoice"}
def test_document_cache_makes_repeat_upload_fast_path(): xml = '''<?xml version="1.0"?><w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"><w:body><w:p><w:r><w:t>Delivery Order</w:t></w:r></w:p></w:body></w:document>''' buffer = io.BytesIO() with zipfile.ZipFile(buffer, "w") as archive: archive.writestr("word/document.xml", xml) payload = {"file_base64": base64.b64encode(buffer.getvalue()).decode(), "filename": "repeat.docx", "language_preference": "en"} assert client.post("/analyze-document", json=payload).status_code == 200 second = client.post("/analyze-document", json=payload) assert second.status_code == 200 assert second.json()["cached"] is True
def test_confidence_calibration_does_not_multiply_down_verified_match(): service = GlossaryService(ROOT / "data/glossary.json", ROOT / "data/user_corrections.json", ROOT / "data/sme_approved_definitions.json") terms = service.match_regions([{"text": "HS Code", "bbox": [0, 0, 100, 20], "confidence": .8, "language": "en"}]) assert terms[0]["confidence"] > .8TASK_SHEET.md+7-1
backend/document_service.py+66-28
backend/glossary_service.py+5-1
data/project_progress.json+1-1
frontend/camera.js+3-3
frontend/overlay.js+44
frontend/styles.css+4-2
tests/test_services.py+38