Spaces:
Sleeping
Sleeping
Publish-ready PDF to poster demo with validated BF16 example and safe continuation
Browse filesFiles changed (9)
32 unmodified lines3334353632 unmodified lines*.zip filter=lfs diff=lfs merge=lfs -text*.zst filter=lfs diff=lfs merge=lfs -text*tfevents* filter=lfs diff=lfs merge=lfs -textexamples/gaussian_privacy/poster.png filter=lfs diff=lfs merge=lfs -text32 unmodified lines3334353637383940414243444546474832 unmodified lines ZeroGPU requests; partial previews are explicitly labeled incomplete.5. Download the completed poster and check its scientific content and layout.
A saved, actually generated example is available in the page without using GPUquota. It is clearly labeled as a saved output, not an interactive generation.
## Runtime and limitations
- ZeroGPU xlarge (96 GB) is requested per generation; no dedicated paid GPU.- Visitors use their own Hugging Face quota. A complete long poster can require more time than a free visitor's daily quota. This is not an unlimited service.- Sign in before live generation. Anonymous quota is too small for the current 120-second xlarge reservation. Viewing the saved example needs no GPU quota.- Each request reserves 120 seconds; generation stops after approximately 100 seconds and can resume without adding chat turns or changing the prompt.- The first PDF extraction after a cold start installs an isolated CPU parser5 unmodified lines678910111218 unmodified lines31323333343536375 unmodified linesimport jsonimport shutilimport timefrom pathlib import Pathimport torchimport gradio as grimport psutil18 unmodified linesdemo, artifacts = build(model, processor)demo.queue(default_concurrency_limit=1, max_size=8).launch( show_error=False, max_file_size='40mb', ssr_mode=False, allowed_paths=[str(artifacts)], allowed_paths=[str(artifacts),str(Path(__file__).parent/'examples')], blocked_paths=[str(__import__('pathlib').Path(__file__).parent/'.runtime'), '/root/.cache/huggingface','/home/user/.cache/huggingface', '/etc','/proc','/sys'],12334555 unmodified lines61626365666465666768691 unmodified line717273747475767778797980818283844 unmodified lines899091909192939492939495969798992 unmodified lines10210310410310410510610710810911011118 unmodified lines1301311321331341351361371381391401411421431441451461472 unmodified lines150151152137138153154155156157158159"""Public PDF -> assets -> model HTML -> rendered poster workflow."""import jsonimport osimport reimport tempfileimport time55 unmodified lines text=processor.decode(all_ids,skip_special_tokens=True) eos=model.generation_config.eos_token_id eos=eos if isinstance(eos,list) else [eos] complete=bool(new_ids and new_ids[-1] in eos) or bool(re.search(r'</html\s*>',text,re.I)) result={'ids':all_ids,'raw':text,'done':complete,'seconds':time.monotonic()-start, complete=bool(re.search(r'</html\s*>',text,re.I)) stopped=complete or bool(new_ids and new_ids[-1] in eos) or length+len(new_ids)>=WINDOW result={'ids':all_ids,'raw':text,'done':stopped,'complete':complete,'seconds':time.monotonic()-start, 'new_tokens':len(new_ids),'gpu':torch.cuda.get_device_name(), 'total_tokens':p['input_tokens']+len(all_ids)} del inputs,output1 unmodified line
def generate(p,progress=gr.Progress()): if not p:raise gr.Error('Click Analyze PDF first.') if p.get('done'):raise gr.Error('This poster is complete. Analyze again to start a new one.') if p.get('done'):raise gr.Error('Generation has ended. Analyze again to start a new poster.') progress(.1,desc='Waiting for ZeroGPU xlarge, then generating HTML…') result=gpu_chunk(p) p=dict(p,continuation_ids=result['ids'],raw=result['raw'],done=result['done']) rate=result['new_tokens']/max(result['seconds'],.01) status=(f'**{"Complete" if p["done"] else "Partial — click Generate / Continue to resume"}** · ' label=('Complete' if result['complete'] else 'Stopped — incomplete HTML; analyze again to retry' if p['done'] else 'Partial — click Generate / Continue to resume') status=(f'**{label}** · ' f'{len(result["ids"]):,} generated tokens · {result["total_tokens"]:,} / 16,384 total · ' f'{rate:.1f} tokens/s\n\nGPU: {result["gpu"]} · BF16 · checkpoint-240') progress(.9,desc='Resolving assets and rendering the poster…')4 unmodified lines return p,status,png,html,archive,p['raw'] except ValueError as e: return p,status+'\n\n'+str(e),None,None,None,p['raw']
def diagnostics(): setup=ROOT/'.runtime/layout_setup.log' return {'parser_ready':(ROOT/'.runtime/layout_env/rap_parser_ready').exists(), 'parser_log_tail':setup.read_text(errors='replace')[-7000:] if setup.exists() else 'not started'} except Exception as e: print('POSTER_RENDER_ERROR',type(e).__name__,flush=True) saved=Path(p['job'])/'output/poster.html' return p,status+'\n\nPreview rendering failed; the generated HTML is preserved.',None,\ str(saved) if saved.exists() else None,None,p['raw']
css='''#hero {padding:20px 24px;border-radius:18px;background:linear-gradient(115deg,#241541,#534180);color:white} #hero h1,#hero p {color:white} .gradio-container {max-width:1400px!important}'''2 unmodified lines gr.Markdown('# RAP · Paper to Poster\nTurn a research paper into an editable academic poster.',elem_id='hero') gr.Markdown('**RL checkpoint-240 · BF16, no quantization · no thinking · 16K context**\n\n' 'Upload a text-based PDF (≤40 MB). We analyze its first 12 pages, extract figures/tables/equations, ' 'then generate poster HTML. ZeroGPU uses your HF usage quota; sign in to HF for a larger allowance. ' 'Long posters may need more than one Generate / Continue request.') 'then generate poster HTML. Sign in to Hugging Face before generating. ' '**ZeroGPU xlarge uses 2× your personal GPU quota. A full poster usually needs several requests ' 'and can exceed a free account’s daily allowance.** Partial previews are not finished posters. ' 'The saved example below can be viewed without GPU quota.') state=gr.State() with gr.Row(): with gr.Column(scale=4):18 unmodified lines spec_view=gr.Textbox(label='Layout specification used for generation',lines=6,interactive=False) with gr.Accordion('Model-generated HTML',open=False): code=gr.Code(language='html',label='Model output (not executed in this page)',interactive=False) example=ROOT/'examples/gaussian_privacy' if (example/'poster.png').exists(): with gr.Accordion('View a completed example — no GPU quota required',open=False): gr.Markdown('**Saved output, not a live generation.** This poster was generated on this ' 'Space using RL checkpoint-240 in BF16 from ' '[Gaussian Membership Inference Privacy](https://arxiv.org/abs/2306.07273). ' 'Its figures are extracted from that paper. Please check scientific details before reuse.') gr.Image(value=str(example/'poster.png'),label='Completed model-generated example', interactive=False,height=600) with gr.Row(): gr.File(value=str(example/'poster.html'),label='Example HTML',interactive=False) gr.File(value=str(example/'poster_bundle.zip'),label='Example poster and assets',interactive=False) gr.Markdown('Research demo: verify scientific statements, captions and layout before publication. ' 'Uploaded papers are processed on the Space; do not upload confidential material. ' 'Outputs are temporary and may disappear after a restart. '2 unmodified lines [state,status,gallery,spec_view,poster,html_download,bundle,code],api_name='analyze',concurrency_limit=1) generate_btn.click(generate,[state],[state,status,poster,html_download,bundle,code], api_name='generate',concurrency_limit=1) if os.environ.get('RAP_DIAGNOSTICS')=='1': gr.Button('Private diagnostics').click(diagnostics,None,gr.JSON(),api_name='diagnostics') def reset_inputs(): return None,'Inputs changed — click Analyze PDF again.',None,None,None,'',[],'' for component in (pdf,instruction,canvas,accent,columns,custom_spec): component.change(reset_inputs,None, [state,status,poster,html_download,bundle,code,gallery,spec_view], queue=False,api_name=False) return demo,ARTIFACTS123version https://git-lfs.github.com/spec/v1oid sha256:d40955b68a38d689d8a6ddc715a67ccf24149d0a07d13f075ec6f2c0896d8dc9size 64978535 unmodified lines36373839404142435 unmodified lines495051525335 unmodified lines result=subprocess.run([str(python),'-m','pip','install','--disable-pip-version-check',*packages], env=env,stdout=log,stderr=log,timeout=900) if result.returncode: log.flush() print('PARSER_SETUP_ERROR', (RUNTIME/'layout_setup.log').read_text(errors='replace')[-6000:],flush=True) raise RuntimeError('LayoutLMv3 dependency setup failed. Please contact the demo maintainer.') marker.write_text('layoutlmv3-cpu-v1\n') return str(python)5 unmodified lines result=subprocess.run([python,str(ROOT/'layout_worker.py'),str(pdf),str(out)], env=worker_environment(),stdout=log,stderr=log,timeout=900) if result.returncode: print('PARSER_EXTRACTION_ERROR', (out/'extraction.log').read_text(errors='replace')[-6000:],flush=True) raise RuntimeError('LayoutLMv3 could not parse this PDF. Please try a text-based research paper.')44 unmodified lines4546474848495051525344 unmodified lines chosen=select_for_prompt(registry['assets'],[],16,{'figure':10,'table':5,'formula':3}) with fitz.open(pdf) as doc: first=doc[0].get_text('dict') spans=[s for b in first['blocks'] if 'lines' in b for l in b['lines'] for s in l['spans'] if s['text'].strip()] spans=[s for b in first['blocks'] if 'lines' in b for l in b['lines'] if abs(l.get('dir',(1,0))[1])<.1 for s in l['spans'] if s['text'].strip() and not re.search(r'arxiv:|preprint|under review',s['text'],re.I)] largest=max((s['size'] for s in spans),default=0) title=clean_text(' '.join(s['text'] for s in spans if s['size']>=largest*.85 and s['bbox'][1]<doc[0].rect.height*.45))[:400] authors=clean_text(doc.metadata.get('author',''))[:500].gitattributes+1
README.md+5
app.py+2-1
demo_ui.py+34-14
examples/gaussian_privacy/poster.htmlAdded
examples/gaussian_privacy/poster.pngAdded

Large File Pointer Details
- SHA256: c23f2139630e2b7a2345c013a5c81762131a1cddc5c56ad5fd13e6ad806dcd79
- Pointer size: 131 Bytes
- Size of remote file: 349 kB
examples/gaussian_privacy/poster_bundle.zipAdded+3
layout_runtime.py+3
pdf_pipeline.py+3-1