seyominaoto Claude Opus 4.8 commited on
Commit
2c8fb6d
·
0 Parent(s):

Phase 0: FastAPI TrOCR OCR backend for Hugging Face Docker Space

Browse files
Files changed (5) hide show
  1. .gitignore +9 -0
  2. Dockerfile +21 -0
  3. README.md +50 -0
  4. app.py +76 -0
  5. requirements.txt +8 -0
.gitignore ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ __pycache__/
2
+ *.pyc
3
+ *.pyo
4
+ .venv/
5
+ venv/
6
+ env/
7
+ .cache/
8
+ .DS_Store
9
+ *.egg-info/
Dockerfile ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM python:3.10-slim
2
+
3
+ WORKDIR /app
4
+
5
+ # HF Spaces run the container as a non-root user; give the HF cache a writable home
6
+ # so the model download at startup doesn't hit a permissions error.
7
+ ENV HF_HOME=/app/.cache \
8
+ TRANSFORMERS_CACHE=/app/.cache \
9
+ PYTHONUNBUFFERED=1
10
+
11
+ COPY requirements.txt .
12
+
13
+ RUN pip install --no-cache-dir -r requirements.txt
14
+
15
+ COPY app.py .
16
+
17
+ RUN mkdir -p /app/.cache && chmod -R 777 /app/.cache
18
+
19
+ EXPOSE 7860
20
+
21
+ CMD ["uvicorn", "app:app", "--host", "0.0.0.0", "--port", "7860"]
README.md ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ title: NeuroWrite Backend
3
+ emoji: 🧠
4
+ colorFrom: blue
5
+ colorTo: purple
6
+ sdk: docker
7
+ app_port: 7860
8
+ pinned: false
9
+ ---
10
+
11
+ # NeuroWrite Backend
12
+
13
+ FastAPI backend for handwriting OCR using `microsoft/trocr-base-handwritten`.
14
+ Phase 0 exposes the OCR inference service; cognitive-load and visual analysis
15
+ arrive in later phases.
16
+
17
+ This is a neuro-inspired educational prototype, **not** a medical/diagnostic tool.
18
+
19
+ ## Endpoints
20
+
21
+ | Method | Path | Description |
22
+ | ------ | --------- | -------------------------------------------- |
23
+ | GET | `/` | Service info |
24
+ | GET | `/health` | Liveness check + device |
25
+ | POST | `/ocr` | Upload an image, get recognized text (JSON) |
26
+ | GET | `/docs` | Interactive Swagger UI (test uploads here) |
27
+
28
+ ### `POST /ocr`
29
+
30
+ Send `multipart/form-data` with a `file` field containing an image.
31
+
32
+ ```json
33
+ {
34
+ "text": "neurons communicate using electrical signals",
35
+ "model": "microsoft/trocr-base-handwritten",
36
+ "device": "cpu",
37
+ "latency_seconds": 3.8
38
+ }
39
+ ```
40
+
41
+ > Tip: TrOCR works best on a **single, clear, cropped handwritten line**.
42
+ > Upload a cropped line or short phrase for reliable results.
43
+
44
+ ## Run locally with Docker
45
+
46
+ ```bash
47
+ docker build -t neurowrite-backend .
48
+ docker run -p 7860:7860 neurowrite-backend
49
+ # then open http://localhost:7860/docs
50
+ ```
app.py ADDED
@@ -0,0 +1,76 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import io
2
+ import time
3
+
4
+ import torch
5
+ from fastapi import FastAPI, File, HTTPException, UploadFile
6
+ from fastapi.middleware.cors import CORSMiddleware
7
+ from PIL import Image, UnidentifiedImageError
8
+ from transformers import TrOCRProcessor, VisionEncoderDecoderModel
9
+
10
+ MODEL_NAME = "microsoft/trocr-base-handwritten"
11
+
12
+ app = FastAPI(title="NeuroWrite OCR API", version="0.1.0")
13
+
14
+ # Prototype CORS: allow any origin so a local frontend can call the deployed API.
15
+ # Tighten this to the deployed frontend origin in a later phase.
16
+ app.add_middleware(
17
+ CORSMiddleware,
18
+ allow_origins=["*"],
19
+ allow_credentials=True,
20
+ allow_methods=["*"],
21
+ allow_headers=["*"],
22
+ )
23
+
24
+ device = "cuda" if torch.cuda.is_available() else "cpu"
25
+
26
+ # Load the model once at import time so requests don't pay the load cost.
27
+ processor = TrOCRProcessor.from_pretrained(MODEL_NAME)
28
+ model = VisionEncoderDecoderModel.from_pretrained(MODEL_NAME)
29
+ model.to(device)
30
+ model.eval()
31
+
32
+
33
+ @app.get("/")
34
+ def root():
35
+ return {
36
+ "name": "NeuroWrite OCR API",
37
+ "status": "running",
38
+ "model": MODEL_NAME,
39
+ "docs": "/docs",
40
+ }
41
+
42
+
43
+ @app.get("/health")
44
+ def health():
45
+ return {"status": "ok", "device": device}
46
+
47
+
48
+ @app.post("/ocr")
49
+ async def ocr(file: UploadFile = File(...)):
50
+ start_time = time.time()
51
+
52
+ image_bytes = await file.read()
53
+ if not image_bytes:
54
+ raise HTTPException(status_code=400, detail="Empty file upload.")
55
+
56
+ try:
57
+ image = Image.open(io.BytesIO(image_bytes)).convert("RGB")
58
+ except (UnidentifiedImageError, OSError):
59
+ raise HTTPException(
60
+ status_code=400,
61
+ detail="Could not read the uploaded file as an image.",
62
+ )
63
+
64
+ pixel_values = processor(images=image, return_tensors="pt").pixel_values.to(device)
65
+
66
+ with torch.inference_mode():
67
+ generated_ids = model.generate(pixel_values, max_new_tokens=64)
68
+
69
+ text = processor.batch_decode(generated_ids, skip_special_tokens=True)[0]
70
+
71
+ return {
72
+ "text": text,
73
+ "model": MODEL_NAME,
74
+ "device": device,
75
+ "latency_seconds": round(time.time() - start_time, 2),
76
+ }
requirements.txt ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ fastapi
2
+ uvicorn[standard]
3
+ transformers
4
+ torch
5
+ pillow
6
+ python-multipart
7
+ sentencepiece
8
+ protobuf