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 lines93949596979819 unmodified lines1181191201211221235 unmodified lines12913013113213313416 unmodified lines15115215315415515615715815916092 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.### Selection, highlight, and business insight19 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.### Camera and performance5 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.### Responsive UI and accessibility16 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.### Automated verification recorded- [x] Python/API suite: 12 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.92 unmodified lines9394959697989919 unmodified lines1191201211221231241251265 unmodified lines13213313413513613713813916 unmodified lines15615715815916016116216316416516692 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 insight19 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 performance5 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 accessibility16 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: 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.
12345678910111 unmodified line131415161718192021222 unmodified lines25262728293031323334353637381 unmodified line404142434445469 unmodified lines5657585960616263646566676869707172737475767778798081828321 unmodified lines10510610710810911011122 unmodified lines134135136137138139140import base64import ioimport textwrapimport zipfilefrom pathlib import Pathfrom xml.etree import ElementTreefrom PIL import Image, ImageDraw, ImageFontfrom backend.glossary_service import GlossaryServicefrom backend.ocr_service import OCRService1 unmodified lineclass DocumentService:MAX_BYTES = 15 * 1024 * 1024def __init__(self, ocr: OCRService, glossary: GlossaryService):self.ocr = ocrself.glossary = glossarydef analyze(self, encoded: str, filename: str, language: str) -> dict:try:2 unmodified linesraise ValueError("Invalid uploaded document") from excif not raw or len(raw) > self.MAX_BYTES:raise ValueError("Document must be between 1 byte and 15 MB")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")def _image(self, raw: bytes, language: str) -> dict:try:1 unmodified lineimage.load()except Exception as exc:raise ValueError("The uploaded image could not be opened") from excdetections = self.ocr.extract(image, language)terms = self.glossary.match_regions(detections)if len(terms) < 3:terms.extend(self.glossary.contextual_fallbacks(detections, 3 - len(terms), terms))9 unmodified linesdocument = 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)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)})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")except (ValueError, RuntimeError):raiseexcept Exception as exc:21 unmodified linesfor 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))image = Image.new("RGB", (width, height), "#ffffff")draw = ImageDraw.Draw(image)try:22 unmodified lines@staticmethoddef _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)return {"detected_terms": terms,"ocr_items": detections,123456789101112131 unmodified line1516171819202122232425262 unmodified lines29303132333435363738394041424344454647484950511 unmodified line5354555657585960619 unmodified lines717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012121 unmodified lines14314414514614714814922 unmodified lines172173174175176177178import base64import hashlibimport ioimport textwrapimport zipfilefrom collections import OrderedDictfrom pathlib import Pathfrom xml.etree import ElementTreefrom PIL import Image, ImageDraw, ImageFilter, ImageFont, ImageOpsfrom backend.glossary_service import GlossaryServicefrom backend.ocr_service import OCRService1 unmodified lineclass DocumentService:MAX_BYTES = 15 * 1024 * 1024MAX_PDF_PAGES = 12def __init__(self, ocr: OCRService, glossary: GlossaryService):self.ocr = ocrself.glossary = glossaryself._cache: OrderedDict[str, dict] = OrderedDict()def analyze(self, encoded: str, filename: str, language: str) -> dict:try:2 unmodified linesraise ValueError("Invalid uploaded document") from excif 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"}: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] = resultwhile len(self._cache) > 4:self._cache.popitem(last=False)return {**result, "cached": False}def _image(self, raw: bytes, language: str) -> dict:try:1 unmodified lineimage.load()except Exception as exc:raise ValueError("The uploaded image could not be opened") from excimage.thumbnail((1400, 1400), Image.Resampling.LANCZOS)prepared = ImageOps.autocontrast(image.convert("L")).filter(ImageFilter.SHARPEN).convert("RGB")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 linesdocument = fitz.open(stream=raw, filetype="pdf")if document.page_count < 1:raise ValueError("The PDF has no pages")page_count = min(document.page_count, self.MAX_PDF_PAGES)rendered = []canvas_width = 0for 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 = 18total_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 = 0for page, page_image, zoom in rendered:x_offset = (canvas_width - page_image.width) // 2image.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():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 + gapterms = self.glossary.match_regions(regions)if len(terms) < 3:terms.extend(self.glossary.contextual_fallbacks(regions, 3 - len(terms), terms))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 resultexcept (ValueError, RuntimeError):raiseexcept Exception as exc:21 unmodified linesfor paragraph in paragraphs:wrapped.extend(textwrap.wrap(paragraph, width=85, break_long_words=False) or [""])wrapped.append("")height = max(900, margin * 2 + len(wrapped) * line_height)image = Image.new("RGB", (width, height), "#ffffff")draw = ImageDraw.Draw(image)try:22 unmodified lines@staticmethoddef _result(image: Image.Image, terms: list, detections: list, unknown: list, method: str) -> dict:output = io.BytesIO()image.save(output, format="JPEG", quality=80, optimize=True)return {"detected_terms": terms,"ocr_items": detections,
143 unmodified lines144145146147148149150151143 unmodified lines"ocr_confidence": region.get("confidence", 1.0),"language": region.get("language", "en"),})definition["confidence"] = round(definition["confidence"] * float(region.get("confidence", 1.0)), 3)found.append(definition)return found143 unmodified lines144145146147148149150151152153154155143 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(0.72 * recognition_confidence + 0.28 * knowledge_confidence, 3)found.append(definition)return found
4 unmodified lines5678910114 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","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"}4 unmodified lines5678910114 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 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 lines218219220221222223224225226227228229230231232233217 unmodified linesconst objectUrl = URL.createObjectURL(file);try {const image = await loadImage(objectUrl);const maxEdge = 1600;const scale = Math.min(1, maxEdge / Math.max(image.naturalWidth, image.naturalHeight));if (scale === 1 && file.size < 2.5 * 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));return { base64: await readBase64(blob), filename: "optimized-upload.jpg" };} finally {URL.revokeObjectURL(objectUrl);217 unmodified lines218219220221222223224225226227228229230231232233217 unmodified linesconst objectUrl = URL.createObjectURL(file);try {const image = await loadImage(objectUrl);const maxEdge = 1400;const scale = Math.min(1, maxEdge / Math.max(image.naturalWidth, image.naturalHeight));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.80));return { base64: await readBase64(blob), filename: "optimized-upload.jpg" };} finally {URL.revokeObjectURL(objectUrl);
113 unmodified lines11411511611711811940 unmodified lines160161162163164165113 unmodified linesmarker.addEventListener("pointercancel", finish);}function openPopover(item, marker, layout) {closePopover();marker.classList.add("active");40 unmodified linesspan.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`;layer.appendChild(span);});const explainSelection = () => {113 unmodified lines11411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116240 unmodified lines203204205206207208209113 unmodified linesmarker.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 linesspan.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 lines5051525354555623 unmodified lines8081828384858649 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[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::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; }49 unmodified lines5051525354555623 unmodified lines80818283848586878849 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; -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; 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 lines125126127124 unmodified linesassert 'id="stabilityMetric"' not in htmlassert 'id="lightMetric"' not in htmlassert 'id="ocrMetric"' not in html124 unmodified lines125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165124 unmodified linesassert 'id="stabilityMetric"' not in htmlassert 'id="lightMetric"' not in htmlassert 'id="ocrMetric"' not in htmldef test_multipage_pdf_is_rendered_as_one_scroll_surface():import fitzdocument = 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 == 200data = response.json()assert data["page_count"] == 2assert data["pages_analyzed"] == 2assert data["frame_height"] > data["frame_width"] * 2assert {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 == 200second = client.post("/analyze-document", json=payload)assert second.status_code == 200assert second.json()["cached"] is Truedef 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"] > .8
TASK_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