Update main.py
Browse files
main.py
CHANGED
|
@@ -1,52 +1,51 @@
|
|
|
|
|
|
|
|
| 1 |
import easyocr
|
| 2 |
import numpy as np
|
| 3 |
from PIL import Image
|
| 4 |
import cv2
|
| 5 |
-
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
#
|
| 14 |
-
|
| 15 |
-
#
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
#
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
#
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
#
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
# st.write(f"- {text}")
|
| 51 |
-
# else:
|
| 52 |
-
# st.warning("❌ No text found.")
|
|
|
|
| 1 |
+
from fastapi import FastAPI
|
| 2 |
+
from pydantic import BaseModel
|
| 3 |
import easyocr
|
| 4 |
import numpy as np
|
| 5 |
from PIL import Image
|
| 6 |
import cv2
|
| 7 |
+
import base64
|
| 8 |
+
import io
|
| 9 |
+
|
| 10 |
+
app = FastAPI(title="OCR Base64 API")
|
| 11 |
+
|
| 12 |
+
# Initialisation du lecteur EasyOCR (comme ton code)
|
| 13 |
+
reader = easyocr.Reader(['en'], gpu=False)
|
| 14 |
+
|
| 15 |
+
# Modèle de requête
|
| 16 |
+
class ImageRequest(BaseModel):
|
| 17 |
+
image_base64: str # Image encodée en Base64
|
| 18 |
+
|
| 19 |
+
def preprocess_image(image):
|
| 20 |
+
gray = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)
|
| 21 |
+
scale_percent = 200
|
| 22 |
+
width = int(gray.shape[1] * scale_percent / 100)
|
| 23 |
+
height = int(gray.shape[0] * scale_percent / 100)
|
| 24 |
+
resized = cv2.resize(gray, (width, height), interpolation=cv2.INTER_LINEAR)
|
| 25 |
+
_, thresh = cv2.threshold(resized, 150, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)
|
| 26 |
+
return thresh
|
| 27 |
+
|
| 28 |
+
@app.post("/extract-text/")
|
| 29 |
+
def extract_text(request: ImageRequest):
|
| 30 |
+
try:
|
| 31 |
+
# Supprimer le préfixe si présent
|
| 32 |
+
b64_data = request.image_base64
|
| 33 |
+
if "base64," in b64_data:
|
| 34 |
+
b64_data = b64_data.split("base64,")[1]
|
| 35 |
+
|
| 36 |
+
# Décoder le Base64
|
| 37 |
+
image_bytes = base64.b64decode(b64_data)
|
| 38 |
+
image = Image.open(io.BytesIO(image_bytes)).convert("RGB")
|
| 39 |
+
img_np = np.array(image)
|
| 40 |
+
|
| 41 |
+
# Prétraitement
|
| 42 |
+
processed_img = preprocess_image(img_np)
|
| 43 |
+
|
| 44 |
+
# OCR
|
| 45 |
+
results = reader.readtext(processed_img)
|
| 46 |
+
extracted_text = [text.replace(" ", "") for _, text, _ in results]
|
| 47 |
+
|
| 48 |
+
return {"text": extracted_text}
|
| 49 |
+
|
| 50 |
+
except Exception as e:
|
| 51 |
+
return {"error": str(e)}
|
|
|
|
|
|
|
|
|