Electro0023 commited on
Commit
68ee0be
·
verified ·
1 Parent(s): 507e284

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +63 -38
app.py CHANGED
@@ -1,47 +1,72 @@
1
- import gradio as gr
2
  import torch
3
- from transformers import Idefics3Processor, Idefics3ForConditionalGeneration
4
  from PIL import Image
 
 
 
5
 
6
- # Load model and processor
7
- model_id = "HuggingFaceM4/Idefics3-8B-Llama3"
8
 
9
- # FIX: Import the specific processor class directly to bypass the AutoProcessor bug
10
- processor = Idefics3Processor.from_pretrained(model_id, trust_remote_code=True)
11
 
12
- model = Idefics3ForConditionalGeneration.from_pretrained(
13
- model_id,
14
- trust_remote_code=True,
15
- torch_dtype=torch.float32
 
 
 
 
16
  )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
17
 
18
- def process_image(image):
19
- # Safety check for empty input
20
- if image is None:
21
- return "Please upload an image first."
22
-
23
- # Ensure image is PIL format
24
- if not isinstance(image, Image.Image):
25
- image = Image.fromarray(image)
26
-
27
- image = image.convert("RGB")
28
-
29
- # Prepare inputs
30
- messages = [{"role": "user", "content": [{"type": "image"}, {"type": "text", "text": "Describe this image."}]}]
31
  prompt = processor.apply_chat_template(messages, add_generation_prompt=True)
32
- inputs = processor(text=prompt, images=image, return_tensors="pt")
33
-
34
- # Generate
35
- generated_ids = model.generate(**inputs, max_new_tokens=500)
36
- result = processor.batch_decode(generated_ids, skip_special_tokens=True)
37
-
38
- return result[0]
39
-
40
- # UI Setup
41
- demo = gr.Interface(
42
- fn=process_image,
43
- inputs=gr.Image(type="pil"),
44
- outputs="text"
45
- )
46
 
47
- demo.launch()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import torch
2
+ from transformers import AutoProcessor, AutoModelForVision2Seq
3
  from PIL import Image
4
+ from fastapi import FastAPI, UploadFile, File
5
+ from fastapi.responses import JSONResponse
6
+ import io
7
 
8
+ app = FastAPI()
 
9
 
10
+ # SmolVLM - lightweight, works on CPU/low VRAM, same team as Idefics3
11
+ model_id = "HuggingFaceTB/SmolVLM-Instruct"
12
 
13
+ print("Loading processor...")
14
+ processor = AutoProcessor.from_pretrained(model_id)
15
+
16
+ print("Loading model...")
17
+ model = AutoModelForVision2Seq.from_pretrained(
18
+ model_id,
19
+ torch_dtype=torch.float32, # float32 for CPU
20
+ device_map="auto"
21
  )
22
+ model.eval()
23
+ print("Model ready!")
24
+
25
+
26
+ @app.get("/")
27
+ def root():
28
+ return {"status": "running", "model": model_id}
29
+
30
+
31
+ @app.post("/extract")
32
+ async def extract_text(file: UploadFile = File(...)):
33
+ # Read uploaded image
34
+ contents = await file.read()
35
+ image = Image.open(io.BytesIO(contents)).convert("RGB")
36
+
37
+ # Prompt for NEET question extraction
38
+ messages = [
39
+ {
40
+ "role": "user",
41
+ "content": [
42
+ {"type": "image"},
43
+ {"type": "text", "text": (
44
+ "Extract all text from this image exactly as it appears. "
45
+ "Preserve question numbers, options (A, B, C, D), tables, "
46
+ "and any mathematical or chemical expressions. "
47
+ "Format clearly."
48
+ )}
49
+ ]
50
+ }
51
+ ]
52
 
 
 
 
 
 
 
 
 
 
 
 
 
 
53
  prompt = processor.apply_chat_template(messages, add_generation_prompt=True)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
54
 
55
+ inputs = processor(
56
+ text=prompt,
57
+ images=[image],
58
+ return_tensors="pt"
59
+ )
60
+
61
+ with torch.no_grad():
62
+ outputs = model.generate(
63
+ **inputs,
64
+ max_new_tokens=1024,
65
+ do_sample=False
66
+ )
67
+
68
+ # Decode only the generated part
69
+ generated = outputs[0][inputs["input_ids"].shape[1]:]
70
+ result = processor.decode(generated, skip_special_tokens=True)
71
+
72
+ return JSONResponse({"extracted_text": result})