Spaces:
Sleeping
Sleeping
Update app.py
Browse files1234567891011121314151617181920212223242526272829303132333435363738394041421 unmodified line444546474849502 unmodified lines5354555657585960616263642 unmodified lines6768697071727374import torchfrom transformers import AutoProcessor, AutoModelForVision2Seqfrom PIL import Imagefrom fastapi import FastAPI, UploadFile, Filefrom fastapi.responses import JSONResponseimport ioimport transformersprint(f"Transformers version: {transformers.__version__}")app = FastAPI()# SmolVLM - lightweight, works on CPU/low VRAM, same team as Idefics3model_id = "HuggingFaceTB/SmolVLM-Instruct"print("Loading processor...")processor = AutoProcessor.from_pretrained(model_id)print("Loading model...")model = AutoModelForVision2Seq.from_pretrained(model_id,torch_dtype=torch.float32, # float32 for CPUdevice_map="auto")model.eval()print("Model ready!")@app.get("/")def root():return {"status": "running", "model": model_id}@app.post("/extract")async def extract_text(file: UploadFile = File(...)):# Read uploaded imagecontents = await file.read()image = Image.open(io.BytesIO(contents)).convert("RGB")# Prompt for NEET question extractionmessages = [{"role": "user",1 unmodified line{"type": "image"},{"type": "text", "text": ("Extract all text from this image exactly as it appears. ""Preserve question numbers, options (A, B, C, D), tables, ""and any mathematical or chemical expressions. ""Format clearly.")}2 unmodified lines]prompt = processor.apply_chat_template(messages, add_generation_prompt=True)inputs = processor(text=prompt,images=[image],return_tensors="pt")with torch.no_grad():outputs = model.generate(2 unmodified linesdo_sample=False)# Decode only the generated partgenerated = outputs[0][inputs["input_ids"].shape[1]:]result = processor.decode(generated, skip_special_tokens=True)return JSONResponse({"extracted_text": result})1234567891011121314151617181920211 unmodified line232425262728292 unmodified lines323334353637382 unmodified lines41424344454647484950515253545556import torchimport gradio as grfrom transformers import AutoProcessor, AutoModelForVision2Seqfrom PIL import Imagemodel_id = "HuggingFaceTB/SmolVLM-Instruct"print("Loading model...")processor = AutoProcessor.from_pretrained(model_id)model = AutoModelForVision2Seq.from_pretrained(model_id,torch_dtype=torch.float32,device_map="auto")model.eval()print("Model ready!")def extract_text(image: Image.Image) -> str:messages = [{"role": "user",1 unmodified line{"type": "image"},{"type": "text", "text": ("Extract all text from this image exactly as it appears. ""Preserve question numbers, options A B C D, tables, ""and any mathematical or chemical expressions. ""Format clearly.")}2 unmodified lines]prompt = processor.apply_chat_template(messages, add_generation_prompt=True)inputs = processor(text=prompt, images=[image], return_tensors="pt")with torch.no_grad():outputs = model.generate(2 unmodified linesdo_sample=False)generated = outputs[0][inputs["input_ids"].shape[1]:]return processor.decode(generated, skip_special_tokens=True)demo = gr.Interface(fn=extract_text,inputs=gr.Image(type="pil", label="Upload NEET Question Image"),outputs=gr.Textbox(label="Extracted Text", lines=20),title="NEET Question Extractor",description="Upload a scanned NEET question paper image to extract text")demo.launch()
app.py+17-35