Spaces:
Sleeping
Sleeping
React UI + ZeroGPU generation + token proxy in one Space
Browse filesFiles changed (9)
- README.md+24-9
- app.py+83-206
- requirements.txt+7-5
- static/assets/__vite-browser-external-Cgmn0awE-DzRxVxK7.jsAdded+1
- static/assets/index-Cg3AJ6u0.jsAdded
- static/assets/index-DE4kGc84.cssAdded+1
- static/favicon.svgAdded
- static/icons.svgAdded
- static/index.htmlAdded+20
9 unmodified lines1011121314151617181920212223242526279 unmodified lines# Paper QAUpload a research paper and ask grounded questions about it.Answers come from [`whosouravsharma/paper-qa-lora`](https://huggingface.co/whosouravsharma/paper-qa-lora)— a QLoRA fine-tune of `Qwen2.5-1.5B-Instruct` trained to answer strictlyfrom retrieved context, cite the sentence it relied on, and say so plainlywhen the answer isn't in the paper. Generation runs here on[ZeroGPU](https://huggingface.co/docs/hub/spaces-zerogpu) (`@spaces.GPU`),so a GPU is attached only for the seconds each answer takes.Ingestion (PDF → OCR fallback → chunking → FAISS), retrieval, and liveLLM-as-a-judge scoring run in a companion CPU Space, `paper-qa-rag`.Every answer is scored for factual accuracy against the retrieved passagesand the score is shown inline.See the project's `PLAN.md` for the full architecture.9 unmodified lines1011121314151617181920212223242526272829303132333435363738394041429 unmodified lines# Paper QAUpload a research paper and ask grounded questions about it. Every answer isscored for how well it's grounded in the paper, and the score is shown inline.Answers come from [`whosouravsharma/paper-qa-lora`](https://huggingface.co/whosouravsharma/paper-qa-lora)— a QLoRA fine-tune of `Qwen2.5-1.5B-Instruct` trained to answer strictlyfrom retrieved context, cite the sentence it relied on, and say so plainlywhen the answer isn't in the paper.## ArchitectureTwo Spaces:**This Space** (Gradio, ZeroGPU) does three jobs from one process:- serves the React UI (`static/`, built from `paper-qa-web/`) at `/`- proxies `/api/rag/*` to the private backend, attaching `HF_TOKEN`server-side so the token never reaches the browser- runs generation under `@spaces.GPU`, mounted at `/gradio`ZeroGPU only works inside a Gradio Space's own process — that's whygeneration lives here rather than in the backend, and why the UI is servedfrom here rather than from a separate Docker Space.**`paper-qa-rag`** (Docker, private) handles ingestion (PDF → OCR fallback →chunking → FAISS), retrieval, and live LLM-as-a-judge scoring.Per question: `POST /api/rag/retrieve` → `@spaces.GPU` generation in-process→ `POST /api/rag/judge` → answer plus its grounding score.Requires `HF_TOKEN` as a Space secret to reach the private backend.
12345678910111213141516171819202122232425262728292 unmodified lines3233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246import loggingimport osimport sysimport timeimport uuidimport gradio as grimport requestsimport spacesimport torchfrom peft import PeftModelfrom transformers import AutoModelForCausalLM, AutoTokenizerlogging.basicConfig(level=logging.INFO,format="%(asctime)s [%(levelname)s] %(name)s - %(message)s",stream=sys.stdout,)logger = logging.getLogger("paper-qa-ui")BACKEND_URL = os.getenv("BACKEND_URL", "http://127.0.0.1:8000")HF_TOKEN = os.getenv("HF_TOKEN")AUTH_HEADERS = {"Authorization": f"Bearer {HF_TOKEN}"} if HF_TOKEN else {}BASE_MODEL = "Qwen/Qwen2.5-1.5B-Instruct"ADAPTER_REPO = "whosouravsharma/paper-qa-lora"SYSTEM_PROMPT = ("You are a research paper assistant. Answer the question using only the "2 unmodified lines"instead of guessing.")HEALTH_TIMEOUT = 5WAKE_POLL_INTERVAL = 3WAKE_MAX_WAIT = 120STYLE = """<style>footer[aria-label="Gradio footer navigation"] { display: none !important; }#paper-qa-footer {text-align: center;opacity: 0.6;font-size: 0.85rem;padding: 1rem 0 0.5rem;}</style>"""# ZeroGPU requires models be placed on cuda at module level — a PyTorch CUDA# emulation layer makes that work with no real GPU attached, and the transfer# is then optimised at startup instead of costing quota on every call.## The adapter itself must still be loaded with torch_device="cpu": peft reads# the safetensors through a path the emulation layer doesn't cover, which# raises "No CUDA GPUs are available". Merging it into the base weights right# after sidesteps that, drops the per-call adapter overhead, and leaves a# plain transformers model to place on cuda.tokenizer = AutoTokenizer.from_pretrained(BASE_MODEL)_base_model = AutoModelForCausalLM.from_pretrained(BASE_MODEL, dtype=torch.float16)model = PeftModel.from_pretrained(_base_model, ADAPTER_REPO, torch_device="cpu").merge_and_unload()model.eval()model.to("cuda")# ZeroGPU checks `duration` against remaining daily quota before admitting a# call, so an inflated value gets rejected even when the work is short (and# hurts queue priority). Measured generation is ~4s for 128 tokens with the# model already resident on the GPU; 20s leaves ample headroom.@spaces.GPU(duration=20)def generate_answer(context: str, question: str, max_new_tokens: int = 128) -> str:messages = [{"role": "system", "content": SYSTEM_PROMPT},{"role": "user", "content": f"Context:\n{context}\n\nQuestion: {question}"},]inputs = tokenizer.apply_chat_template(messages, add_generation_prompt=True, return_tensors="pt", return_dict=True).to("cuda")t1 = time.perf_counter()with torch.no_grad():output = model.generate(**inputs,max_new_tokens=max_new_tokens,do_sample=False,pad_token_id=tokenizer.eos_token_id,)logger.info("generated %d tokens in %.1fs",output.shape[1] - inputs["input_ids"].shape[1],time.perf_counter() - t1,)return tokenizer.decode(output[0][inputs["input_ids"].shape[1] :], skip_special_tokens=True)def _backend_awake() -> bool:try:r = requests.get(f"{BACKEND_URL}/health", headers=AUTH_HEADERS, timeout=HEALTH_TIMEOUT)return r.status_code == 200except requests.exceptions.RequestException:return Falsedef _wait_for_backend():if _backend_awake():returnwaited = 0while waited < WAKE_MAX_WAIT:yield f"⏳ Backend is asleep — waking it up, this can take up to a minute... ({waited}s)"time.sleep(WAKE_POLL_INTERVAL)waited += WAKE_POLL_INTERVALif _backend_awake():returnyield "⚠️ Backend is taking longer than expected to wake up. Try again shortly."def upload_pdf(file, thread_id):if file is None:yield "Upload a PDF to get started.", thread_id, [], []returnfor status_msg in _wait_for_backend():yield status_msg, thread_id, [], []new_thread_id = str(uuid.uuid4())yield "📖 Reading and indexing the document...", new_thread_id, [], []with open(file, "rb") as f:response = requests.post(f"{BACKEND_URL}/upload",files={"file": (os.path.basename(file), f, "application/pdf")},data={"thread_id": new_thread_id},headers=AUTH_HEADERS,)if response.status_code != 200:yield f"❌ Upload failed: {response.text}", new_thread_id, [], []returndata = response.json()title = data.get("title", "Your document")summary = data.get("summary", "")opening = f"**{title}**\n\n{summary}\n\n---\n\nAsk me anything about this paper."history = [{"role": "assistant", "content": opening}]yield f"✅ **{title}** is ready.", new_thread_id, history, historydef respond(message, history, thread_id):if not thread_id:yield "Upload a PDF first using the panel on the left."returnfor status_msg in _wait_for_backend():yield status_msgyield "🔍 Retrieving relevant passages..."retrieve_response = requests.post(f"{BACKEND_URL}/retrieve",json={"question": message, "thread_id": thread_id},headers=AUTH_HEADERS,)if retrieve_response.status_code != 200:yield f"Sorry, something went wrong: {retrieve_response.text}"returnretrieved = retrieve_response.json()context = retrieved["context"]yield "🤖 Generating answer..."t0 = time.perf_counter()try:answer = generate_answer(context, message)except Exception as e:# Surface GPU failures (ZeroGPU quota exhaustion above all) in the# chat instead of letting the event die silently.logger.exception("generation failed")yield f"⚠️ Generation failed: {e}"returngenerate_latency_ms = (time.perf_counter() - t0) * 1000logger.info("generation round-trip %.1fs", generate_latency_ms / 1000)yield answer + "\n\n---\n⏳ *Scoring answer...*"judge_response = requests.post(f"{BACKEND_URL}/judge",json={"context": context,"question": message,"answer": answer,"thread_id": thread_id,"retrieve_latency_ms": retrieved.get("retrieve_latency_ms"),"generate_latency_ms": generate_latency_ms,},headers=AUTH_HEADERS,)judgment = Noneif judge_response.status_code == 200:judgment = judge_response.json().get("judgment")if judgment:answer += (f"\n\n---\n🎯 **{judgment['accuracy_pct']:.0f}% accurate** "f"— judged by OpenAI `{judgment['judge_model']}`")yield answerwith gr.Blocks(title="Paper QA") as demo:gr.HTML(STYLE)thread_id_state = gr.State(None)gr.Markdown("# 📄 Paper QA\n""Upload a research paper and ask grounded questions — answered by a ""fine-tuned model, scored live for accuracy.")with gr.Row():with gr.Column(scale=1):pdf_upload = gr.File(label="Upload a PDF", file_types=[".pdf"], type="filepath")status = gr.Markdown("Upload a PDF to get started.")with gr.Column(scale=2):chat = gr.ChatInterface(fn=respond,additional_inputs=[thread_id_state],)gr.Markdown("Built with Gradio by Sourav Sharma", elem_id="paper-qa-footer")pdf_upload.change(upload_pdf,inputs=[pdf_upload, thread_id_state],outputs=[status, thread_id_state, chat.chatbot, chat.chatbot_state],)if __name__ == "__main__":demo.launch()12345678910111213141516171819202122232425262728293031323334352 unmodified lines3839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123"""Paper QA — React UI + ZeroGPU generation in one Gradio Space.Gradio runs on FastAPI, so this single Space does three jobs:1. serves the built React app (static/) at /2. proxies /api/rag/* to the private paper-qa-rag Space, attaching HF_TOKENserver-side so the token never reaches the browser bundle3. runs generation under @spaces.GPU, mounted at /gradioZeroGPU only works inside a Gradio Space's own process, which is whygeneration lives here rather than in the Docker backend, and why the UI isserved from here rather than from a separate Docker Space."""import osimport timeimport gradio as grimport httpximport spacesimport torchfrom fastapi import FastAPI, Request, Responsefrom fastapi.staticfiles import StaticFilesfrom peft import PeftModelfrom transformers import AutoModelForCausalLM, AutoTokenizerBASE_MODEL = "Qwen/Qwen2.5-1.5B-Instruct"ADAPTER_REPO = "whosouravsharma/paper-qa-lora"DEVICE = "cuda" if torch.cuda.is_available() else "cpu"RAG_BACKEND_URL = os.getenv("RAG_BACKEND_URL", "https://huggingface.co/proxy/whosouravsharma-paper-qa-rag.hf.space")HF_TOKEN = os.getenv("HF_TOKEN")SYSTEM_PROMPT = ("You are a research paper assistant. Answer the question using only the "2 unmodified lines"instead of guessing.")# Module-level load — required for ZeroGPU's CUDA emulation to place things# efficiently; HF documents in-function placement as "significantly less# efficient". peft's adapter loading bypasses that emulation ("No CUDA GPUs# are available"), so the adapter is applied on CPU and folded in with# merge_and_unload() before the plain model goes to the accelerator — which# also removes per-call adapter overhead._tokenizer = AutoTokenizer.from_pretrained(BASE_MODEL)_base = AutoModelForCausalLM.from_pretrained(BASE_MODEL, torch_dtype=torch.float16)_tuned = PeftModel.from_pretrained(_base, ADAPTER_REPO, torch_device="cpu")_tuned = _tuned.merge_and_unload()_tuned.to(DEVICE).eval()@spaces.GPU(duration=20)def generate(context: str, question: str):messages = [{"role": "system", "content": SYSTEM_PROMPT},{"role": "user", "content": f"Context:\n{context}\n\nQuestion: {question}"},]inputs = _tokenizer.apply_chat_template(messages, add_generation_prompt=True, return_tensors="pt", return_dict=True).to(_tuned.device)start = time.perf_counter()with torch.no_grad():output = _tuned.generate(**inputs, max_new_tokens=256, do_sample=False,pad_token_id=_tokenizer.eos_token_id,)latency_ms = (time.perf_counter() - start) * 1000answer = _tokenizer.decode(output[0][inputs["input_ids"].shape[1]:], skip_special_tokens=True).strip()return answer, round(latency_ms, 1)demo = gr.Interface(fn=generate,inputs=[gr.Textbox(label="context"), gr.Textbox(label="question")],outputs=[gr.Textbox(label="answer"), gr.Number(label="latency_ms")],api_name="generate",title="Paper QA — generation endpoint",description="Called by the React UI at /. Not meant to be used directly.",)app = FastAPI()@app.api_route("/api/rag/{path:path}", methods=["GET", "POST"])async def proxy_rag(path: str, request: Request):"""paper-qa-rag is a private Space, so every call needs a bearer token.Proxying here keeps that token server-side — a browser-side call wouldhave to ship it in the bundle."""headers = {}if HF_TOKEN:headers["Authorization"] = f"Bearer {HF_TOKEN}"content_type = request.headers.get("content-type")if content_type:headers["content-type"] = content_typebody = await request.body()async with httpx.AsyncClient(timeout=180) as client:upstream = await client.request(request.method, f"{RAG_BACKEND_URL}/{path}", content=body, headers=headers)return Response(content=upstream.content,status_code=upstream.status_code,media_type=upstream.headers.get("content-type"),)app = gr.mount_gradio_app(app, demo, path="/gradio")# Mounted last so /api/rag and /gradio win over the SPA's catch-all.app.mount("/", StaticFiles(directory="static", html=True), name="static")if __name__ == "__main__":import uvicornuvicorn.run(app, host="0.0.0.0", port=7860)
12345678gradio>=5.0audioop-lts; python_version>='3.13'requestsspacestorchtransformers>=5.16.1peft>=0.20.0accelerate>=1.14.012345678910gradio>=5.0spacesfastapiuvicornhttpxtorchtransformers>=4.46peft>=0.13accelerateaudioop-lts; python_version>='3.13'
1import{t as e}from"./index-Cg3AJ6u0.js";var t=e(((e,t)=>{t.exports={}}))();export{t as default};1:root{--paper:#fbfafc;--surface:#fff;--ink:#2f2c38;--ink-muted:#8e88a0;--rule:#ebe6f2;--accent:#a68fd4;--accent-quiet:#ece5f8;--grounding-low:#f3c6ba;--grounding-high:#bfe3ce;--shadow:0 2px 14px #46376417;--font-serif:"Source Serif 4", Georgia, serif;--font-sans:"IBM Plex Sans", system-ui, sans-serif;--font-mono:"IBM Plex Mono", ui-monospace, monospace;--lightningcss-light:initial;--lightningcss-dark: ;color-scheme:light}*{box-sizing:border-box}html,body,#root{height:100%;margin:0}body{background:var(--paper);color:var(--ink);font-family:var(--font-sans)}:focus-visible{outline:2px solid var(--accent);outline-offset:2px}.app{background:var(--paper);flex-direction:column;width:70%;height:100dvh;margin:0 auto;display:flex}.wake-gate{max-width:420px;height:100dvh;padding:2rem 1.5rem;padding-top:max(2rem, env(safe-area-inset-top));padding-bottom:max(2rem, env(safe-area-inset-bottom));text-align:center;background:var(--paper);flex-direction:column;justify-content:center;align-items:center;gap:1rem;margin:0 auto;display:flex}.wake-copy{font-family:var(--font-sans);color:var(--ink-muted);max-width:34ch;margin:0;font-size:.95rem}.wake-button{font-family:var(--font-sans);background:var(--accent);color:#fff;cursor:pointer;border:none;border-radius:10px;min-height:44px;padding:.7rem 1.4rem;font-size:.9rem;font-weight:500}.wake-button:hover{opacity:.9}.topbar{padding:1.1rem 1.25rem;padding-top:max(1.1rem, env(safe-area-inset-top));border-bottom:1px solid var(--rule);flex-wrap:wrap;justify-content:space-between;align-items:center;gap:1rem;display:flex}.brand{flex-shrink:0;align-items:center;gap:.55rem;display:flex}.brand-mark{background:var(--accent);border-radius:50%;flex-shrink:0;width:8px;height:8px}.brand-name{font-family:var(--font-serif);color:var(--ink);font-size:1.2rem;font-weight:600}.upload-slot{align-items:center;gap:.75rem;min-width:0;display:flex}.upload-button{font-family:var(--font-sans);background:var(--accent-quiet);color:var(--ink);cursor:pointer;border:none;border-radius:8px;flex-shrink:0;min-height:44px;padding:.5rem .9rem;font-size:.85rem;font-weight:500}.upload-button:hover:not(:disabled){background:var(--accent);color:#fff}.upload-button:disabled{opacity:.6;cursor:default}.status-text{font-family:var(--font-sans);color:var(--ink-muted);text-overflow:ellipsis;white-space:nowrap;font-size:.8rem;overflow:hidden}.thread{-webkit-overflow-scrolling:touch;flex-direction:column;flex:1;gap:1.4rem;padding:1.75rem 1.25rem;display:flex;overflow-y:auto}.empty-state{font-family:var(--font-sans);color:var(--ink-muted);text-align:center;max-width:32ch;margin:auto;font-size:.95rem}.message p{white-space:pre-wrap;overflow-wrap:break-word;margin:0}.message-user{background:var(--accent-quiet);max-width:75%;font-family:var(--font-sans);color:var(--ink);border-radius:18px;align-self:flex-end;padding:.65rem 1rem;font-size:.95rem;line-height:1.5}.message-assistant{max-width:100%;font-family:var(--font-sans);color:var(--ink);align-self:stretch;font-size:.98rem;line-height:1.65}.grounding-line{flex-wrap:wrap;align-items:center;gap:.5rem;display:flex}.grounding-tag{font-family:var(--font-mono);color:var(--ink);border-radius:999px;padding:.2rem .6rem;font-size:.72rem;display:inline-block}.grounding-judge{font-family:var(--font-sans);color:var(--ink-muted);font-size:.72rem}.pending-phase{font-family:var(--font-sans);color:var(--ink-muted);align-items:center;gap:.55rem;font-size:.92rem;display:flex}.pending-dot{background:var(--accent);border-radius:50%;flex-shrink:0;width:6px;height:6px;animation:1.4s ease-in-out infinite pulse}@keyframes pulse{0%,to{opacity:.3;transform:scale(.85)}50%{opacity:1;transform:scale(1)}}.composer-area{padding:.5rem 1.25rem 1rem;padding-bottom:max(1rem, env(safe-area-inset-bottom))}.composer-note{text-align:center;color:var(--ink-muted);margin:0 0 .6rem;font-size:.75rem}.composer{background:var(--surface);border:1px solid var(--rule);box-shadow:var(--shadow);border-radius:999px;align-items:center;gap:.5rem;padding:.35rem .35rem .35rem 1.1rem;display:flex}.composer input{min-width:0;font-family:var(--font-sans);color:var(--ink);background:0 0;border:none;flex:1;padding:.6rem 0;font-size:16px}.composer input:focus{outline:none}.composer input::placeholder{color:var(--ink-muted)}.send-button{background:var(--accent);color:#fff;cursor:pointer;border:none;border-radius:50%;flex-shrink:0;place-items:center;width:40px;height:40px;display:grid}.send-button:hover:not(:disabled){opacity:.9}.send-button:disabled{opacity:.35;cursor:default}.message-actions{align-items:center;gap:.75rem;margin-top:.5rem;display:flex}.icon-button{width:28px;height:28px;color:var(--ink-muted);cursor:pointer;background:0 0;border:none;border-radius:6px;place-items:center;padding:0;display:grid}.icon-button:hover{background:var(--accent-quiet);color:var(--ink)}@media (width<=1100px){.app{width:88%}}@media (width<=768px){.app{width:100%}}@media (width<=480px){.topbar{gap:.6rem}.brand-name{font-size:1.05rem}.status-text{max-width:140px}.message-user{max-width:85%}.thread{padding:1.25rem 1rem}.composer{padding:.85rem 1rem;padding-bottom:max(.85rem, env(safe-area-inset-bottom))}}@media (prefers-reduced-motion:reduce){.pending-dot{animation:none}}1234567891011121314151617181920<!doctype html><html lang="en"> <head> <meta charset="UTF-8" /> <link rel="icon" type="image/svg+xml" href="/favicon.svg" /> <meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover" /> <title>Paper QA</title> <link rel="preconnect" href="https://fonts.googleapis.com" /> <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin /> <link href="https://fonts.googleapis.com/css2?family=Source+Serif+4:opsz,wght@8..60,400;8..60,600&family=IBM+Plex+Sans:wght@400;500;600&family=IBM+Plex+Mono:wght@500&display=swap" rel="stylesheet" /> <script type="module" crossorigin src="/assets/index-Cg3AJ6u0.js"></script> <link rel="stylesheet" crossorigin href="/assets/index-DE4kGc84.css"> </head> <body> <div id="root"></div> </body></html>README.md+24-9
app.py+83-206
requirements.txt+7-5
static/assets/__vite-browser-external-Cgmn0awE-DzRxVxK7.jsAdded+1
static/assets/index-Cg3AJ6u0.jsAdded
static/assets/index-DE4kGc84.cssAdded+1
static/favicon.svgAdded
static/icons.svgAdded
static/index.htmlAdded+20