matheusalencar commited on
Commit
1b64148
·
1 Parent(s): 9a80c0a

first commit

Browse files
.env.example ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Audio / ASR
2
+ APP_ASR_BACKEND=local
3
+ APP_ASR_MODEL=large-v3
4
+ APP_ASR_COMPUTE_TYPE=int8
5
+
6
+ # Texto / OCR
7
+ APP_OCR_BACKEND=local
8
+ APP_OCR_LANG=por
9
+ APP_PDF_OCR_DPI=300
10
+ APP_PDF_MIN_CHARS_PER_PAGE=20
11
+
12
+ # Compute
13
+ APP_DEVICE=cpu
.gitignore ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ __pycache__/
2
+ *.pyc
3
+ .env
4
+ .venv/
5
+ venv/
6
+ *.wav
7
+ *.bin
Dockerfile CHANGED
@@ -1,14 +1,25 @@
1
- FROM python:3.9
2
 
3
- RUN useradd -m -u 1000 appuser
4
- USER appuser
 
 
 
 
 
 
 
5
 
6
- ENV PATH="/home/appuser/.local/bin:$PATH"
7
 
8
- WORKDIR /app
 
9
 
10
- COPY --chown=appuser ./requirements.txt .
11
- RUN pip install --no-cache-dir --upgrade -r requirements.txt
12
- COPY --chown=appuser . .
13
- CMD ["uvicorn", "app:app", "--host", "0.0.0.0", "--port", "7860"]
14
 
 
 
 
 
 
 
 
1
+ FROM python:3.12-slim
2
 
3
+ # Dependencias de sistema:
4
+ # ffmpeg -> decodifica o opus/ogg do WhatsApp (e demais formatos)
5
+ # tesseract-ocr -> motor de OCR
6
+ # tesseract-ocr-por -> pacote de idioma portugues
7
+ RUN apt-get update && apt-get install -y --no-install-recommends \
8
+ ffmpeg \
9
+ tesseract-ocr \
10
+ tesseract-ocr-por \
11
+ && rm -rf /var/lib/apt/lists/*
12
 
13
+ WORKDIR /app
14
 
15
+ COPY requirements.txt .
16
+ RUN pip install --no-cache-dir -r requirements.txt
17
 
18
+ COPY . .
 
 
 
19
 
20
+ # Em producao, descomente para embutir os pesos na imagem e nao depender
21
+ # do HF Hub em runtime (evita cold start lento e chamadas de saida):
22
+ # RUN python -c "from faster_whisper import WhisperModel; WhisperModel('large-v3', compute_type='int8')"
23
+
24
+ EXPOSE 8000
25
+ CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000"]
README.md CHANGED
@@ -1,11 +1,80 @@
1
- ---
2
- title: Zelotech
3
- emoji: 🐢
4
- colorFrom: pink
5
- colorTo: indigo
6
- sdk: docker
7
- pinned: false
8
- short_description: Zelo Tech API Server
9
- ---
10
-
11
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Servico de Extracao e Transcricao
2
+
3
+ API em FastAPI com dois endpoints:
4
+
5
+ - `POST /extract-text` — recebe PDF, JPG ou PNG e devolve o texto contido (cru, sem tratamento).
6
+ - `POST /transcribe` — recebe audio (ogg/opus do WhatsApp, mp3, m4a, wav...) e devolve a transcricao em PT-BR.
7
+
8
+ A inferencia fica isolada atras de uma interface, entao rodar local hoje e na nuvem depois e questao de deploy e configuracao, nao de reescrita.
9
+
10
+ ## Estrutura
11
+
12
+ ```
13
+ app/
14
+ main.py # monta o FastAPI, carrega os modelos no boot
15
+ config.py # configuracao por env (flags das decisoes adiadas)
16
+ api/
17
+ deps.py # injecao de dependencia
18
+ routes_text.py # /extract-text
19
+ routes_audio.py # /transcribe
20
+ domain/
21
+ transcriber.py # interface Transcriber (o contrato)
22
+ extractor.py # interface TextExtractor (o contrato)
23
+ infra/
24
+ factory.py # escolhe a implementacao pela config
25
+ local_transcriber.py # faster-whisper (hoje)
26
+ local_extractor.py # Tesseract + PyMuPDF (hoje)
27
+ services/
28
+ files.py # upload -> arquivo temporario, limpeza
29
+ detect.py # tipo do arquivo por magic bytes
30
+ audio_utils.py # ffmpeg: normaliza audio -> wav 16k mono
31
+ pdf_utils.py # camada de texto vs. OCR, pagina a pagina
32
+ ocr.py # Tesseract
33
+ ```
34
+
35
+ ## Rodando local
36
+
37
+ Pre-requisitos de sistema: `ffmpeg` e `tesseract-ocr` com o idioma portugues (`tesseract-ocr-por`).
38
+
39
+ ```bash
40
+ # Ubuntu/Debian
41
+ sudo apt install ffmpeg tesseract-ocr tesseract-ocr-por
42
+
43
+ python -m venv .venv && source .venv/bin/activate
44
+ pip install -r requirements.txt
45
+ cp .env.example .env
46
+
47
+ uvicorn app.main:app --reload
48
+ ```
49
+
50
+ Testando:
51
+
52
+ ```bash
53
+ curl -F "file=@documento.pdf" http://localhost:8000/extract-text
54
+ curl -F "file=@audio.opus" http://localhost:8000/transcribe
55
+ ```
56
+
57
+ Docs interativas em `http://localhost:8000/docs`.
58
+
59
+ ## Docker
60
+
61
+ ```bash
62
+ docker build -t extracao-transcricao .
63
+ docker run -p 8000:8000 extracao-transcricao
64
+ ```
65
+
66
+ ## As duas decisoes que ficaram para depois
67
+
68
+ Nenhuma exige tocar nas rotas ou na logica de upload.
69
+
70
+ **Self-managed vs. gerenciado** — campo `APP_ASR_BACKEND` / `APP_OCR_BACKEND`. Hoje e `local`. Para migrar, escreva uma classe adaptadora nova em `infra/` que implemente o mesmo metodo (`transcribe` ou `extract`), registre-a na `factory.py` e troque a env var.
71
+
72
+ **GPU vs. CPU** — campo `APP_DEVICE` (`cpu` ou `cuda`). Em GPU, ajuste tambem `APP_ASR_COMPUTE_TYPE` para `float16`. O codigo e o mesmo; muda so a config e o alvo de deploy.
73
+
74
+ ## Notas para producao
75
+
76
+ - **Pesos do modelo:** evite baixar do HF Hub em runtime. Descomente a linha de pre-download no `Dockerfile` para embuti-los na imagem (cold start menor, sem chamada de saida).
77
+ - **Perfis de compute distintos:** o OCR e leve (CPU) e a transcricao e pesada (pode querer GPU). Da para separar os dois em deployments independentes e escalar cada um sozinho.
78
+ - **Carga:** para volume alto ou arquivos grandes, processe a inferencia em fila/worker em vez de inline na requisicao.
79
+ - **Pinagem:** troque os `>=` do `requirements.txt` por versoes exatas quando fechar o ambiente.
80
+ - **Manter o pipeline `transformers` atual:** crie um adaptador com o mesmo metodo e aponte a factory para ele.
__init__.py ADDED
File without changes
api/__init__.py ADDED
File without changes
api/deps.py ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from fastapi import Request
2
+
3
+ from domain.extractor import TextExtractor
4
+ from domain.transcriber import Transcriber
5
+
6
+
7
+ def get_transcriber(request: Request) -> Transcriber:
8
+ return request.app.state.transcriber
9
+
10
+
11
+ def get_extractor(request: Request) -> TextExtractor:
12
+ return request.app.state.extractor
api/routes_audio.py ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from fastapi import APIRouter, Depends, File, HTTPException, UploadFile
2
+
3
+ from api.deps import get_transcriber
4
+ from domain.transcriber import Transcriber
5
+ from services.audio_utils import normalize_to_wav
6
+ from services.files import cleanup, save_upload_to_temp
7
+
8
+ router = APIRouter(tags=["audio"])
9
+
10
+
11
+ @router.post("/transcribe")
12
+ async def transcribe(
13
+ file: UploadFile = File(...),
14
+ transcriber: Transcriber = Depends(get_transcriber),
15
+ ):
16
+ """Recebe audio (ogg/opus do WhatsApp, mp3, m4a, wav...) e devolve a transcricao em PT-BR."""
17
+ src = await save_upload_to_temp(file)
18
+ wav = None
19
+ try:
20
+ try:
21
+ wav = normalize_to_wav(src)
22
+ except RuntimeError:
23
+ raise HTTPException(
24
+ status_code=422,
25
+ detail="Nao foi possivel decodificar o audio. Envie ogg/opus, mp3, m4a ou wav.",
26
+ )
27
+ text = transcriber.transcribe(wav, language="pt")
28
+ return {"text": text}
29
+ finally:
30
+ cleanup(src, wav)
api/routes_text.py ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from fastapi import APIRouter, Depends, File, HTTPException, UploadFile
2
+
3
+ from api.deps import get_extractor
4
+ from domain.extractor import TextExtractor
5
+ from services.detect import sniff_kind
6
+ from services.files import cleanup, save_upload_to_temp
7
+
8
+ router = APIRouter(tags=["texto"])
9
+
10
+
11
+ @router.post("/extract-text")
12
+ async def extract_text(
13
+ file: UploadFile = File(...),
14
+ extractor: TextExtractor = Depends(get_extractor),
15
+ ):
16
+ """Recebe PDF, JPG ou PNG e devolve o texto extraido (cru, sem tratamento)."""
17
+ src = await save_upload_to_temp(file)
18
+ try:
19
+ kind = sniff_kind(src)
20
+ if kind == "unknown":
21
+ raise HTTPException(
22
+ status_code=415,
23
+ detail="Formato nao suportado. Envie PDF, JPG ou PNG.",
24
+ )
25
+ text = extractor.extract(src, kind=kind)
26
+ return {"text": text}
27
+ finally:
28
+ cleanup(src)
config.py ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from functools import lru_cache
2
+
3
+ from pydantic_settings import BaseSettings, SettingsConfigDict
4
+
5
+
6
+ class Settings(BaseSettings):
7
+ """Configuracao por variaveis de ambiente (prefixo APP_) ou arquivo .env.
8
+
9
+ As duas decisoes que voce ainda nao tomou viram simples flags aqui:
10
+ - self-managed vs. gerenciado -> asr_backend / ocr_backend
11
+ - GPU vs. CPU -> device (+ asr_compute_type)
12
+ Nenhuma delas exige mexer no resto do codigo.
13
+ """
14
+
15
+ model_config = SettingsConfigDict(env_file=".env", env_prefix="APP_", extra="ignore")
16
+
17
+ # --- inferencia de audio (ASR) ---
18
+ asr_backend: str = "local" # "local" hoje; amanha "azure" | "endpoint"
19
+ asr_model: str = "large-v3"
20
+ asr_compute_type: str = "int8" # "int8" p/ CPU, "float16" p/ GPU
21
+
22
+ # --- inferencia de texto (OCR) ---
23
+ ocr_backend: str = "local" # "local" hoje; amanha "azure" (Document Intelligence)...
24
+ ocr_lang: str = "por"
25
+ pdf_ocr_dpi: int = 300
26
+ pdf_min_chars_per_page: int = 20
27
+
28
+ # --- compute ---
29
+ device: str = "cpu" # "cpu" | "cuda"
30
+
31
+
32
+ @lru_cache
33
+ def get_settings() -> Settings:
34
+ return Settings()
domain/__init__.py ADDED
File without changes
domain/extractor.py ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Literal, Protocol
2
+
3
+ Kind = Literal["pdf", "image"]
4
+
5
+
6
+ class TextExtractor(Protocol):
7
+ """Contrato de extracao de texto de documentos (PDF ou imagem)."""
8
+
9
+ def extract(self, path: str, kind: Kind) -> str: ...
domain/transcriber.py ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ from typing import Protocol
2
+
3
+
4
+ class Transcriber(Protocol):
5
+ """Contrato de transcricao. Quem chama nao sabe se por tras esta
6
+ faster-whisper local, um endpoint gerenciado ou uma API de nuvem."""
7
+
8
+ def transcribe(self, audio_path: str, language: str = "pt") -> str: ...
infra/__init__.py ADDED
File without changes
infra/factory.py ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from config import Settings
2
+ from domain.extractor import TextExtractor
3
+ from domain.transcriber import Transcriber
4
+ from infra.local_extractor import TesseractExtractor
5
+ from infra.local_transcriber import LocalWhisperTranscriber
6
+
7
+
8
+ def build_transcriber(s: Settings) -> Transcriber:
9
+ if s.asr_backend == "local":
10
+ return LocalWhisperTranscriber(
11
+ model=s.asr_model, device=s.device, compute_type=s.asr_compute_type
12
+ )
13
+ # Amanha, sem tocar em rotas nem na logica de upload:
14
+ # if s.asr_backend == "azure":
15
+ # from app.infra.azure_transcriber import AzureTranscriber
16
+ # return AzureTranscriber(...)
17
+ raise ValueError(f"asr_backend desconhecido: {s.asr_backend!r}")
18
+
19
+
20
+ def build_extractor(s: Settings) -> TextExtractor:
21
+ if s.ocr_backend == "local":
22
+ return TesseractExtractor(
23
+ lang=s.ocr_lang, dpi=s.pdf_ocr_dpi, min_chars_per_page=s.pdf_min_chars_per_page
24
+ )
25
+ # if s.ocr_backend == "azure":
26
+ # from app.infra.azure_extractor import AzureExtractor
27
+ # return AzureExtractor(...)
28
+ raise ValueError(f"ocr_backend desconhecido: {s.ocr_backend!r}")
infra/local_extractor.py ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from services.ocr import ocr_image_path
2
+ from services.pdf_utils import extract_pdf_text
3
+
4
+
5
+ class TesseractExtractor:
6
+ """Extracao local de texto.
7
+
8
+ PDF: usa a camada de texto quando existe (instantaneo, via PyMuPDF) e so
9
+ cai para OCR (Tesseract) nas paginas que forem escaneadas.
10
+ Imagem (JPG/PNG): vai direto para OCR.
11
+
12
+ Retorna o texto cru, sem nenhum tratamento, como voce pediu.
13
+ """
14
+
15
+ def __init__(self, lang: str = "por", dpi: int = 300, min_chars_per_page: int = 20):
16
+ self._lang = lang
17
+ self._dpi = dpi
18
+ self._min_chars = min_chars_per_page
19
+
20
+ def extract(self, path: str, kind: str) -> str:
21
+ if kind == "pdf":
22
+ return extract_pdf_text(
23
+ path, dpi=self._dpi, min_chars_per_page=self._min_chars, lang=self._lang
24
+ )
25
+ if kind == "image":
26
+ return ocr_image_path(path, lang=self._lang).strip()
27
+ raise ValueError(f"kind nao suportado: {kind!r}")
infra/local_transcriber.py ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from faster_whisper import WhisperModel
2
+
3
+
4
+ class LocalWhisperTranscriber:
5
+ """Transcricao local com faster-whisper (CTranslate2).
6
+
7
+ Os pesos vem do HF Hub na primeira carga (mesma familia de modelos que
8
+ voce ja usa). Em producao, prefira pre-baixa-los na imagem para nao
9
+ depender do Hub em runtime -- veja o Dockerfile e o README.
10
+
11
+ Quer manter exatamente o pipeline `transformers` que voce usa hoje?
12
+ Basta criar outra classe com este mesmo metodo `transcribe` e apontar
13
+ a factory para ela. O resto do servico nao muda.
14
+ """
15
+
16
+ def __init__(self, model: str, device: str = "cpu", compute_type: str = "int8"):
17
+ self._model = WhisperModel(model, device=device, compute_type=compute_type)
18
+
19
+ def transcribe(self, audio_path: str, language: str = "pt") -> str:
20
+ segments, _info = self._model.transcribe(audio_path, language=language, beam_size=5)
21
+ return " ".join(seg.text.strip() for seg in segments).strip()
main.py ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from contextlib import asynccontextmanager
2
+
3
+ from fastapi import FastAPI
4
+
5
+ from api import routes_audio, routes_text
6
+ from config import get_settings
7
+ from infra.factory import build_extractor, build_transcriber
8
+
9
+
10
+ @asynccontextmanager
11
+ async def lifespan(app: FastAPI):
12
+ # Carrega os modelos uma unica vez, no boot. Se algo estiver errado
13
+ # (modelo, device, dependencia), o servico falha cedo, nao na 1a requisicao.
14
+ settings = get_settings()
15
+ app.state.transcriber = build_transcriber(settings)
16
+ app.state.extractor = build_extractor(settings)
17
+ yield
18
+ # espaco para liberar recursos, se um dia for necessario
19
+
20
+
21
+ app = FastAPI(title="Extracao & Transcricao", version="0.1.0", lifespan=lifespan)
22
+ app.include_router(routes_text.router)
23
+ app.include_router(routes_audio.router)
24
+
25
+
26
+ @app.get("/health")
27
+ def health():
28
+ return {"status": "ok"}
requirements.txt CHANGED
@@ -1,3 +1,8 @@
1
  fastapi
2
  uvicorn[standard]
3
-
 
 
 
 
 
 
1
  fastapi
2
  uvicorn[standard]
3
+ python-multipart>=0.0.9
4
+ pydantic-settings>=2.2
5
+ faster-whisper>=1.0
6
+ pymupdf>=1.24
7
+ pytesseract>=0.3.10
8
+ pillow>=10.0
services/__init__.py ADDED
File without changes
services/audio_utils.py ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import shutil
2
+ import subprocess
3
+
4
+
5
+ def normalize_to_wav(src_path: str) -> str:
6
+ """Converte qualquer audio de entrada em WAV PCM 16 kHz mono via ffmpeg.
7
+
8
+ E isto que resolve o opus/ogg do WhatsApp: o ffmpeg decodifica o Opus e
9
+ entrega um WAV padrao para o modelo. 16 kHz mono e o formato que o Whisper
10
+ espera, entao normalizamos sempre (inclusive se ja vier wav).
11
+ """
12
+ if shutil.which("ffmpeg") is None:
13
+ raise RuntimeError("ffmpeg nao encontrado no PATH.")
14
+
15
+ out_path = src_path + ".16k.wav"
16
+ cmd = [
17
+ "ffmpeg", "-y",
18
+ "-i", src_path,
19
+ "-ar", "16000",
20
+ "-ac", "1",
21
+ "-c:a", "pcm_s16le",
22
+ out_path,
23
+ ]
24
+ proc = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
25
+ if proc.returncode != 0:
26
+ raise RuntimeError(proc.stderr.decode(errors="ignore")[:500])
27
+ return out_path
services/detect.py ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ def sniff_kind(path: str) -> str:
2
+ """Detecta o tipo do arquivo pelos magic bytes, nao pela extensao.
3
+
4
+ Mais confiavel que confiar no nome/Content-Type enviado pelo cliente.
5
+ Retorna "pdf", "image" ou "unknown".
6
+ """
7
+ with open(path, "rb") as f:
8
+ head = f.read(12)
9
+
10
+ if head[:5] == b"%PDF-":
11
+ return "pdf"
12
+ if head[:8] == b"\x89PNG\r\n\x1a\n":
13
+ return "image"
14
+ if head[:3] == b"\xff\xd8\xff": # JPEG
15
+ return "image"
16
+ return "unknown"
services/files.py ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import tempfile
3
+
4
+ from fastapi import UploadFile
5
+
6
+
7
+ async def save_upload_to_temp(file: UploadFile) -> str:
8
+ """Salva o upload em um arquivo temporario e devolve o caminho."""
9
+ suffix = os.path.splitext(file.filename or "")[1] or ".bin"
10
+ fd, path = tempfile.mkstemp(suffix=suffix)
11
+ with os.fdopen(fd, "wb") as out:
12
+ out.write(await file.read())
13
+ return path
14
+
15
+
16
+ def cleanup(*paths: str | None) -> None:
17
+ """Remove arquivos temporarios, ignorando o que nao existir."""
18
+ for p in paths:
19
+ if p and os.path.exists(p):
20
+ try:
21
+ os.remove(p)
22
+ except OSError:
23
+ pass
services/ocr.py ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pytesseract
2
+ from PIL import Image
3
+
4
+
5
+ def ocr_image(image: Image.Image, lang: str = "por") -> str:
6
+ return pytesseract.image_to_string(image, lang=lang)
7
+
8
+
9
+ def ocr_image_path(path: str, lang: str = "por") -> str:
10
+ with Image.open(path) as img:
11
+ return ocr_image(img, lang=lang)
services/pdf_utils.py ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import io
2
+
3
+ import fitz # PyMuPDF
4
+ from PIL import Image
5
+
6
+ from services.ocr import ocr_image
7
+
8
+
9
+ def extract_pdf_text(
10
+ path: str,
11
+ dpi: int = 300,
12
+ min_chars_per_page: int = 20,
13
+ lang: str = "por",
14
+ ) -> str:
15
+ """Extrai texto de um PDF, pagina a pagina.
16
+
17
+ Se a pagina ja tem camada de texto, usa-a direto (rapido e exato).
18
+ Se for uma pagina escaneada (texto ausente ou irrisorio), rasteriza
19
+ a pagina e roda OCR. Assim PDFs mistos tambem funcionam.
20
+ """
21
+ parts: list[str] = []
22
+ with fitz.open(path) as doc:
23
+ for page in doc:
24
+ text = page.get_text("text").strip()
25
+ if len(text) >= min_chars_per_page:
26
+ parts.append(text)
27
+ else:
28
+ pix = page.get_pixmap(dpi=dpi)
29
+ img = Image.open(io.BytesIO(pix.tobytes("png")))
30
+ parts.append(ocr_image(img, lang=lang).strip())
31
+
32
+ return "\n".join(p for p in parts if p).strip()