Spaces:
Sleeping
Sleeping
Update app.py
Browse files1234567891011121314151617181920212223242526272829303132333435363738394041424344454647import gradio as grimport torchfrom transformers import Idefics3Processor, Idefics3ForConditionalGenerationfrom PIL import Image# Load model and processormodel_id = "HuggingFaceM4/Idefics3-8B-Llama3"# FIX: Import the specific processor class directly to bypass the AutoProcessor bugprocessor = Idefics3Processor.from_pretrained(model_id, trust_remote_code=True)model = Idefics3ForConditionalGeneration.from_pretrained(model_id,trust_remote_code=True,torch_dtype=torch.float32)def process_image(image):# Safety check for empty inputif image is None:return "Please upload an image first."# Ensure image is PIL formatif not isinstance(image, Image.Image):image = Image.fromarray(image)image = image.convert("RGB")# Prepare inputsmessages = [{"role": "user", "content": [{"type": "image"}, {"type": "text", "text": "Describe this image."}]}]prompt = processor.apply_chat_template(messages, add_generation_prompt=True)inputs = processor(text=prompt, images=image, return_tensors="pt")# Generategenerated_ids = model.generate(**inputs, max_new_tokens=500)result = processor.batch_decode(generated_ids, skip_special_tokens=True)return result[0]# UI Setupdemo = gr.Interface(fn=process_image,inputs=gr.Image(type="pil"),outputs="text")demo.launch()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172import torchfrom transformers import AutoProcessor, AutoModelForVision2Seqfrom PIL import Imagefrom fastapi import FastAPI, UploadFile, Filefrom fastapi.responses import JSONResponseimport ioapp = 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","content": [{"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.")}]}]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(**inputs,max_new_tokens=1024,do_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})
app.py+63-38