| | from fastapi import FastAPI, UploadFile, File, Form, HTTPException |
| | from fastapi.responses import HTMLResponse |
| | from fastapi.middleware.cors import CORSMiddleware |
| | import easyocr |
| | import numpy as np |
| | from PIL import Image |
| | import io |
| |
|
| | |
| | app = FastAPI(title="EasyOCR Đa Ngôn Ngữ API") |
| |
|
| | app.add_middleware( |
| | CORSMiddleware, |
| | allow_origins=["*"], |
| | allow_credentials=True, |
| | allow_methods=["*"], |
| | allow_headers=["*"], |
| | ) |
| |
|
| | |
| | print("Đang tải các mô hình EasyOCR vào RAM (Sẽ mất thêm chút thời gian cho lần đầu)...") |
| |
|
| | print("- Đang nạp mô hình: Tiếng Việt + Tiếng Anh...") |
| | reader_vi = easyocr.Reader(['vi', 'en'], gpu=False) |
| |
|
| | print("- Đang nạp mô hình: Tiếng Trung (Giản thể) + Tiếng Anh...") |
| | reader_zh = easyocr.Reader(['ch_sim', 'en'], gpu=False) |
| | |
| |
|
| | print("Tải mô hình hoàn tất, sẵn sàng phục vụ!") |
| |
|
| |
|
| | |
| | |
| | |
| | @app.get("/", response_class=HTMLResponse) |
| | async def serve_frontend(): |
| | try: |
| | with open("index.html", "r", encoding="utf-8") as f: |
| | return f.read() |
| | except FileNotFoundError: |
| | return "<h1>Lỗi: Không tìm thấy file index.html.</h1>" |
| |
|
| |
|
| | |
| | |
| | |
| | @app.post("/predict") |
| | async def predict_image( |
| | file: UploadFile = File(...), |
| | lang: str = Form("vi") |
| | ): |
| | if not file.content_type.startswith('image/'): |
| | raise HTTPException(status_code=400, detail="Vui lòng tải tệp hình ảnh.") |
| |
|
| | try: |
| | |
| | contents = await file.read() |
| | image = Image.open(io.BytesIO(contents)).convert('RGB') |
| | img_array = np.array(image) |
| |
|
| | |
| | if lang == "zh": |
| | |
| | results = reader_zh.readtext(img_array, detail=0) |
| | else: |
| | |
| | results = reader_vi.readtext(img_array, detail=0) |
| |
|
| | |
| | extracted_text = "\n".join(results) |
| |
|
| | return {"text": extracted_text} |
| |
|
| | except Exception as e: |
| | raise HTTPException(status_code=500, detail=f"Lỗi hệ thống: {str(e)}") |