Spaces:
Running on Zero
Running on Zero
Update app.py
Browse files97 unmodified lines989910010110210380 unmodified lines184185186187188189182 unmodified lines372373374375376377378379380381139 unmodified lines52152252352452552632 unmodified lines55956056156256356455 unmodified lines6206216226236246258 unmodified lines634635636637638639124 unmodified lines7647657667677687697704 unmodified lines77577677777877978029 unmodified lines81081181281381481581681781881982013 unmodified lines83483583683783883997 unmodified linestext = "text"# --------------------------------------------------------------------------- engine80 unmodified linespassasync def save_upload(file: UploadFile):name = file.filename or "upload"ext = Path(name).suffix.lower()182 unmodified linesinclude_text_items: bool = Form(False, description="`json` only: include every text item with its bounding box and confidence."),):if STATE["status"] != "ready":raise HTTPException(503, "The model is still loading. Retry in a few seconds.", headers={"Retry-After": "5"})path, name = await save_upload(file)fmt = output_format.valueif stream:139 unmodified lines--mono:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;}*{box-sizing:border-box}html{background:var(--bg)}body{margin:0;color:var(--ink);font:16px/1.55 var(--sans);-webkit-font-smoothing:antialiased}a{color:var(--scan)}32 unmodified lines.seg{display:grid;grid-template-columns:repeat(3,1fr);border:1px solid var(--line);border-radius:8px;overflow:hidden;background:#fff}.seg label{text-align:center;padding:9px 6px;font-size:14px;cursor:pointer;border-right:1px solid var(--line)}.seg label:last-child{border-right:0}.seg input{position:absolute;opacity:0}.seg input:checked+span{font-weight:600}.seg label:has(input:checked){background:var(--ink);color:#fff}55 unmodified lines<div class="src"><label class="bed" id="bed"><i class="cn a"></i><i class="cn b"></i><i class="cn c"></i><i class="cn d"></i><i class="scan"></i><b id="bedTitle">Drop a document here</b><span id="bedHint">or click to choose a file</span><div class="file" id="fname" hidden></div>8 unmodified lines<label><input type="radio" name="fmt" value="text"><span>Text</span></label></div></div><label class="tg"><input type="checkbox" id="ocr" checked><span>Read scanned pages<em>Turn off for born-digital PDFs to skip OCR.</em></span></label><label class="tg"><input type="checkbox" id="stream"><span>Stream the result<em>Output arrives in pieces instead of all at once.</em></span></label><label class="tg" id="itemsRow" hidden><input type="checkbox" id="items"><span>Include text boxes<em>Adds position and confidence for each text item.</em></span></label>124 unmodified linesfunction curl(){const f = S.fmt, st = $('#stream').checked, oc = $('#ocr').checked;$('#curl').textContent = `curl ${st ? '-N ' : ''}-X POST ${location.origin}/api/parse \\\n -F file=@document.pdf \\\n -F output_format=${f}` +(st ? ' \\\n -F stream=true' : '') + (oc ? '' : ' \\\n -F ocr=false');}/* ---------- parse ---------- */4 unmodified linesconst fd = new FormData();fd.append('file', S.file); fd.append('output_format', S.fmt); fd.append('stream', stream);fd.append('ocr', $('#ocr').checked); fd.append('include_text_items', $('#items').checked);try{const res = await fetch('/api/parse', {method: 'POST', body: fd});if(!res.ok){29 unmodified linesif(S.fmt !== 'json') ui();}/* ---------- wiring ---------- */function pick(f){if(!f) return; S.file = f;$('#fname').hidden = false; $('#fname').textContent = f.name + ' (' + (f.size/1048576).toFixed(2) + ' MB)';$('#bedTitle').textContent = 'Ready to parse'; $('#bedHint').textContent = 'Drop another file to replace it'; ui();}const bed = $('#bed');$('#file').addEventListener('change', e => pick(e.target.files[0]));13 unmodified linesconst ext = {markdown: 'md', json: 'json', text: 'txt'}[S.fmt], base = (S.file ? S.file.name : 'document').replace(/\.[^.]+$/, '');const a = document.createElement('a'); a.href = URL.createObjectURL(new Blob([S.out], {type: 'text/plain'})); a.download = `${base}.${ext}`; a.click(); URL.revokeObjectURL(a.href);});ui(); health();</script></body>97 unmodified lines989910010110210310410510610710810911080 unmodified lines191192193194195196197198199200201202203204205206207208209210211212213214182 unmodified lines397398399400401402403404405406407408409410411412413414415416139 unmodified lines55655755855956056156232 unmodified lines59559659759859960060160260355 unmodified lines6596606616626636646658 unmodified lines674675676677678679680681682683684685686687688124 unmodified lines8138148158168178188198204 unmodified lines82582682782882983083129 unmodified lines86186286386486586686786886987087187287387487587687787887988088188288313 unmodified lines89789889990090190290397 unmodified linestext = "text"class Rotation(int, Enum):r0 = 0r90 = 90r180 = 180r270 = 270# --------------------------------------------------------------------------- engine80 unmodified linespassdef rotate_image(path: str, deg: int) -> None:ext = Path(path).suffix.lower()if ext not in IMG_EXT or ext == ".svg":raise HTTPException(400, "rotate only works on raster images (jpg, png, tiff, webp, gif, bmp), not PDFs or Office files.")try:from PIL import Image, ImageOpswith Image.open(path) as im:out = ImageOps.exif_transpose(im).rotate(-deg, expand=True)if ext in (".jpg", ".jpeg") and out.mode not in ("RGB", "L"):out = out.convert("RGB")out.save(path)except HTTPException:raiseexcept Exception as e: # noqa: BLE001raise HTTPException(422, f"Could not rotate the image: {e}")async def save_upload(file: UploadFile):name = file.filename or "upload"ext = Path(name).suffix.lower()182 unmodified linesinclude_text_items: bool = Form(False, description="`json` only: include every text item with its bounding box and confidence."),rotate: Rotation = Form(Rotation.r0,description="Rotate an image clockwise by this many degrees before parsing. Use 180 for an upside-down photo. Images only.",),):if STATE["status"] != "ready":raise HTTPException(503, "The model is still loading. Retry in a few seconds.", headers={"Retry-After": "5"})path, name = await save_upload(file)if rotate.value:try:await asyncio.to_thread(rotate_image, path, rotate.value)except HTTPException:cleanup(path)raisefmt = output_format.valueif stream:139 unmodified lines--mono:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;}*{box-sizing:border-box}[hidden]{display:none!important}html{background:var(--bg)}body{margin:0;color:var(--ink);font:16px/1.55 var(--sans);-webkit-font-smoothing:antialiased}a{color:var(--scan)}32 unmodified lines.seg{display:grid;grid-template-columns:repeat(3,1fr);border:1px solid var(--line);border-radius:8px;overflow:hidden;background:#fff}.seg label{text-align:center;padding:9px 6px;font-size:14px;cursor:pointer;border-right:1px solid var(--line)}.seg label:last-child{border-right:0}.seg.four{grid-template-columns:repeat(4,1fr)}.thumb{width:150px;height:150px;display:flex;align-items:center;justify-content:center;margin-bottom:6px;pointer-events:none}.thumb img{max-width:150px;max-height:150px;border-radius:4px;box-shadow:0 1px 6px rgba(15,27,42,.25);transition:transform .2s}.seg input{position:absolute;opacity:0}.seg input:checked+span{font-weight:600}.seg label:has(input:checked){background:var(--ink);color:#fff}55 unmodified lines<div class="src"><label class="bed" id="bed"><i class="cn a"></i><i class="cn b"></i><i class="cn c"></i><i class="cn d"></i><i class="scan"></i><div class="thumb" id="thumb" hidden><img alt="Preview"></div><b id="bedTitle">Drop a document here</b><span id="bedHint">or click to choose a file</span><div class="file" id="fname" hidden></div>8 unmodified lines<label><input type="radio" name="fmt" value="text"><span>Text</span></label></div></div><div id="rotRow" hidden><span class="lbl">Rotate image</span><div class="seg four" role="radiogroup" aria-label="Rotate image clockwise"><label><input type="radio" name="rot" value="0" checked><span>0°</span></label><label><input type="radio" name="rot" value="90"><span>90°</span></label><label><input type="radio" name="rot" value="180"><span>180°</span></label><label><input type="radio" name="rot" value="270"><span>270°</span></label></div></div><label class="tg"><input type="checkbox" id="ocr" checked><span>Read scanned pages<em>Turn off for born-digital PDFs to skip OCR.</em></span></label><label class="tg"><input type="checkbox" id="stream"><span>Stream the result<em>Output arrives in pieces instead of all at once.</em></span></label><label class="tg" id="itemsRow" hidden><input type="checkbox" id="items"><span>Include text boxes<em>Adds position and confidence for each text item.</em></span></label>124 unmodified linesfunction curl(){const f = S.fmt, st = $('#stream').checked, oc = $('#ocr').checked;$('#curl').textContent = `curl ${st ? '-N ' : ''}-X POST ${location.origin}/api/parse \\\n -F file=@document.pdf \\\n -F output_format=${f}` +(st ? ' \\\n -F stream=true' : '') + (oc ? '' : ' \\\n -F ocr=false') +(isImg(S.file) && rot() ? ' \\\n -F rotate=' + rot() : '');}/* ---------- parse ---------- */4 unmodified linesconst fd = new FormData();fd.append('file', S.file); fd.append('output_format', S.fmt); fd.append('stream', stream);fd.append('ocr', $('#ocr').checked); fd.append('include_text_items', $('#items').checked);fd.append('rotate', isImg(S.file) ? rot() : 0);try{const res = await fetch('/api/parse', {method: 'POST', body: fd});if(!res.ok){29 unmodified linesif(S.fmt !== 'json') ui();}/* ---------- rotation ---------- */const IMGX = BOOT.images.filter(x => x !== '.svg');const isImg = f => !!f && IMGX.includes('.' + f.name.split('.').pop().toLowerCase());const rot = () => +document.querySelector('input[name=rot]:checked').value;function applyRot(){ $('#thumb img').style.transform = 'rotate(' + rot() + 'deg)'; }/* ---------- wiring ---------- */function pick(f){if(!f) return; S.file = f;$('#fname').hidden = false; $('#fname').textContent = f.name + ' (' + (f.size/1048576).toFixed(2) + ' MB)';$('#bedTitle').textContent = 'Ready to parse'; $('#bedHint').textContent = 'Drop another file to replace it';const img = isImg(f);$('#rotRow').hidden = $('#thumb').hidden = !img;document.querySelector('input[name=rot][value="0"]').checked = true;if(S.url){ URL.revokeObjectURL(S.url); S.url = ''; }if(img){ S.url = URL.createObjectURL(f); $('#thumb img').src = S.url; }applyRot(); ui();}const bed = $('#bed');$('#file').addEventListener('change', e => pick(e.target.files[0]));13 unmodified linesconst ext = {markdown: 'md', json: 'json', text: 'txt'}[S.fmt], base = (S.file ? S.file.name : 'document').replace(/\.[^.]+$/, '');const a = document.createElement('a'); a.href = URL.createObjectURL(new Blob([S.out], {type: 'text/plain'})); a.download = `${base}.${ext}`; a.click(); URL.revokeObjectURL(a.href);});document.querySelectorAll('input[name=rot]').forEach(r => r.addEventListener('change', () => { applyRot(); curl(); }));ui(); health();</script></body>
app.py+66-2