Spaces:
Runtime error
Runtime error
AdityaAjithKumar commited on
Commit ·
9c6f85e
1
Parent(s): af67663
fixed the API
Browse files
app.py
CHANGED
|
@@ -47,7 +47,7 @@ async def ocr(image: UploadFile = File(...), prompt: str = Form("Extract all tex
|
|
| 47 |
logger.info(f"📸 OCR request received | Filename: {image.filename} | Prompt: {prompt[:100]}...")
|
| 48 |
|
| 49 |
try:
|
| 50 |
-
img = Image.open(io.BytesIO(await image.read()))
|
| 51 |
|
| 52 |
messages = [{"role": "user", "content": [
|
| 53 |
{"type": "image", "image": img},
|
|
@@ -55,10 +55,16 @@ async def ocr(image: UploadFile = File(...), prompt: str = Form("Extract all tex
|
|
| 55 |
]}]
|
| 56 |
|
| 57 |
text = processor.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
|
| 58 |
-
inputs = processor(text, images=img, return_tensors="pt").to("cpu")
|
| 59 |
|
| 60 |
-
|
| 61 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 62 |
|
| 63 |
logger.info("✅ OCR completed successfully")
|
| 64 |
return {"extracted_text": response}
|
|
@@ -66,8 +72,6 @@ async def ocr(image: UploadFile = File(...), prompt: str = Form("Extract all tex
|
|
| 66 |
except Exception as e:
|
| 67 |
logger.error(f"❌ OCR error: {e}")
|
| 68 |
return {"error": str(e)}
|
| 69 |
-
|
| 70 |
-
|
| 71 |
# === ROOT ===
|
| 72 |
@app.get("/")
|
| 73 |
async def root():
|
|
|
|
| 47 |
logger.info(f"📸 OCR request received | Filename: {image.filename} | Prompt: {prompt[:100]}...")
|
| 48 |
|
| 49 |
try:
|
| 50 |
+
img = Image.open(io.BytesIO(await image.read())).convert("RGB") # ensure RGB
|
| 51 |
|
| 52 |
messages = [{"role": "user", "content": [
|
| 53 |
{"type": "image", "image": img},
|
|
|
|
| 55 |
]}]
|
| 56 |
|
| 57 |
text = processor.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
|
|
|
|
| 58 |
|
| 59 |
+
# ✅ Fix: use keyword `text=` to avoid positional conflict with `images=`
|
| 60 |
+
inputs = processor(text=text, images=[img], return_tensors="pt").to("cpu")
|
| 61 |
+
|
| 62 |
+
outputs = model.generate(**inputs, max_new_tokens=512,
|
| 63 |
+
do_sample=False) # removed temperature when do_sample=False
|
| 64 |
+
|
| 65 |
+
# ✅ Fix: slice only the newly generated tokens to avoid echoing the prompt
|
| 66 |
+
input_len = inputs["input_ids"].shape[1]
|
| 67 |
+
response = processor.decode(outputs[0][input_len:], skip_special_tokens=True)
|
| 68 |
|
| 69 |
logger.info("✅ OCR completed successfully")
|
| 70 |
return {"extracted_text": response}
|
|
|
|
| 72 |
except Exception as e:
|
| 73 |
logger.error(f"❌ OCR error: {e}")
|
| 74 |
return {"error": str(e)}
|
|
|
|
|
|
|
| 75 |
# === ROOT ===
|
| 76 |
@app.get("/")
|
| 77 |
async def root():
|