Skip to content

[Sub] OCR 데이터 모델 + 예외 처리 구현#52

Open
gaeunee2 wants to merge 2 commits into
devfrom
feat/46-ocr-models-exceptions
Open

[Sub] OCR 데이터 모델 + 예외 처리 구현#52
gaeunee2 wants to merge 2 commits into
devfrom
feat/46-ocr-models-exceptions

Conversation

@gaeunee2
Copy link
Copy Markdown
Collaborator

@gaeunee2 gaeunee2 commented May 20, 2026

📌 관련 이슈

🏷️ PR 타입

  • ✨ 기능 추가 (Feature)
  • 🐛 버그 수정 (Bug Fix)
  • ♻️ 리팩토링 (Refactoring)
  • 📝 문서 수정 (Documentation)
  • 🎨 스타일 변경 (Style)
  • ✅ 테스트 추가 (Test)

📝 작업 내용

  • OCR 데이터 모델 구현

    • OCROptions: OCR 처리 옵션 및 설정 (engines, language, math_mode, confidence_threshold, max_processing_time)
    • OCREngineResult: 개별 OCR 엔진 결과 (engine_name, raw_text, confidence, processing_time, bbox_data, metadata)
    • OCRRequest: OCR 처리 요청 데이터 (image_data, image_format, user_id, thread_id, processing_options)
    • OCRResult: 최종 OCR 처리 결과 (extracted_text, confidence, tags, math_expressions, engine_results, processing_time, metadata)
  • 포괄적 예외 처리 체계 구현

    • OCRError: 베이스 예외 클래스 (구조화된 에러 메시지 + 세부 정보)
    • ImageProcessingError: 이미지 전처리 실패 예외 (복구 제안 포함)
    • OCREngineError: 특정 OCR 엔진 실패 예외 (fallback 가능성 표시)
    • MathParsingError: 수학 표기법 후처리 실패 예외 (원본 텍스트 보존)
    • CommandParsingError: @커맨드 파싱 실패 예외 (잘못된 커맨드 목록 포함)
    • ConfidenceThresholdError: 신뢰도 기준 미달 예외 (임계값 및 최고 점수 표시)
    • OCRTimeoutError: OCR 처리 시간 초과 예외
    • OCRResourceError: 리소스 제약 예외 (메모리, GPU 등)
  • 데이터 검증 및 타입 안전성

    • Pydantic V2 @field_validator 사용으로 모든 모델의 데이터 무결성 보장
    • 이미지 크기 제한 (50MB), 신뢰도 범위 (0.0-1.0), 처리 시간 검증
    • Python 3.12+ 타입 힌트 적용 (list[T], dict[K, V], T | None)
    • 빈 텍스트, 빈 엔진 리스트 등 비즈니스 규칙 검증

📸 스크린샷

============================= 34 passed in 0.41s ==============================
All checks passed\!

✅ 체크리스트

  • 코드 리뷰를 받을 준비가 완료되었습니다
  • 테스트를 작성하고 모두 통과했습니다 (34개 단위 테스트 통과)
  • 문서를 업데이트했습니다 (상세한 docstring 작성 완료)
  • 코드 스타일 가이드를 준수했습니다 (ruff 검사 통과)
  • 셀프 리뷰를 완료했습니다

📎 기타 참고사항

  • 의존성: 다른 OCR 하위 컴포넌트들(image_processor, ocr_engines, math_postprocessor, command_parser, node)이 이 모델들을 사용
  • 타입 안전성: Pydantic V2 field_validator로 런타임 검증 및 IDE 지원 강화
  • 확장성: 향후 새로운 OCR 엔진, 다국어 지원을 고려한 구조적 설계
  • 에러 처리: 각 예외는 구체적인 복구 제안과 컨텍스트 정보 제공으로 디버깅 용이성 향상

Summary by CodeRabbit

  • New Features

    • OCR 작업 전반에서 발생하는 다양한 구체적 예외 유형 추가로 오류 원인 파악 및 사용자 안내 개선
  • Tests

    • 예외 동작과 데이터 모델의 입력 검증 및 경계 조건을 검증하는 단위 테스트 대거 추가
  • Chores

    • OCR 패키지의 공개 API와 모델/예외 노출 방식 정리 및 문서화 개선

Review Change Stack

@gaeunee2 gaeunee2 self-assigned this May 20, 2026
@gaeunee2 gaeunee2 changed the title [Sub] OCR 데이터 모델 + 예외 처리 구현 (models.py, exceptions.py) [Sub] OCR 데이터 모델 + 예외 처리 구현 May 20, 2026
@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented May 20, 2026

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 2040283c-7fc1-4491-bf35-d12424e2e2d3

📥 Commits

Reviewing files that changed from the base of the PR and between e82e2bd and 1fb4ef8.

📒 Files selected for processing (3)
  • src/proovy_agent/graph/nodes/ocr_node/__init__.py
  • src/proovy_agent/graph/nodes/ocr_node/exceptions.py
  • src/proovy_agent/graph/nodes/ocr_node/models.py
✅ Files skipped from review due to trivial changes (1)
  • src/proovy_agent/graph/nodes/ocr_node/init.py

📝 Walkthrough

워크스루

Pydantic 기반 OCR 요청/응답 모델 4개와 OCR 전용 예외 계층 8개를 추가하고, 패키지 초기화에서 공개 API를 정의하며 관련 단위 테스트를 포함합니다.

변경사항

OCR 노드 기반 구조

Layer / File(s) Summary
예외 클래스 계층 및 구현
src/proovy_agent/graph/nodes/ocr_node/exceptions.py, tests/ocr_node/test_exceptions.py
공통 베이스 OCRError와 구체 예외 7종을 구현하고, 각 예외의 컨텍스트 필드와 사용자용 문자열 표현을 정의합니다. 테스트는 문자열 포맷, 속성값, 상속 관계를 검증합니다.
OCR 요청/응답 데이터 모델
src/proovy_agent/graph/nodes/ocr_node/models.py, tests/ocr_node/test_models.py
OCROptions, OCREngineResult, OCRRequest, OCRResult를 추가하고 이미지 크기(50MB), 엔진 최소 1개, confidence 및 processing_time 범위 등의 검증 로직을 포함합니다. 관련 테스트는 기본/커스텀 값과 경계값을 검증합니다.
패키지 공개 API 및 초기화
src/proovy_agent/graph/nodes/ocr_node/__init__.py, tests/ocr_node/__init__.py
패키지 레벨에서 예외 및 모델 심볼을 import하고 __all__로 내보내며 테스트 모듈에 문서 문자열을 추가합니다.

예상 코드 리뷰 난이도

🎯 3 (Moderate) | ⏱️ ~25 minutes

제안 리뷰어

  • chowon442

나는 토끼, 코드 밭을 뛰노네 🐇
예외 씨앗 심고 모델 물 주니,
필드가 자라고 검증이 피어나네.
테스트 바구니에 안정성 담아,
새 OCR 밭에 햇살이 내리네 ☀️

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 72.55% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed 제목은 PR의 핵심 변경사항인 OCR 데이터 모델과 예외 처리 구현을 명확하게 설명하며, 전체 변경 내용을 잘 대표합니다.
Description check ✅ Passed PR 설명은 필수 섹션(이슈, PR 타입, 작업 내용, 체크리스트)을 모두 포함하고 있으며, 각 구현 내용을 상세히 설명하고 있습니다.
Linked Issues check ✅ Passed 모든 요구사항이 완료되었습니다: 4개 Pydantic 모델(OCRRequest, OCROptions, OCREngineResult, OCRResult)과 8개 예외 클래스가 구현되었고, Pydantic validator로 검증이 적용되었으며, 34개 테스트가 통과했습니다.
Out of Scope Changes check ✅ Passed 모든 변경사항이 이슈 #46의 요구사항 범위 내입니다: 데이터 모델, 예외 처리, 테스트, init.py 공개 API 정의만 포함되어 있습니다.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/46-ocr-models-exceptions

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@gaeunee2 gaeunee2 requested a review from chowon442 May 20, 2026 18:53
Copy link
Copy Markdown

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

🧹 Nitpick comments (1)
src/proovy_agent/graph/nodes/ocr_node/models.py (1)

45-49: ⚡ Quick win

컨테이너 필드 타입을 더 구체화하는 편이 안전합니다.

list[dict], dict는 정적 타입 검증 이점이 약합니다. 최소한 키/값 타입(dict[str, object] 등)까지 명시해 타입 안전성을 유지해 주세요.

Also applies to: 89-89

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/proovy_agent/graph/nodes/ocr_node/models.py` around lines 45 - 49, The
container fields bbox_data and metadata are currently typed as list[dict] and
dict which weakens static type checks; update their annotations to concrete
types (e.g., bbox_data: list[dict[str, Any]] or list[Mapping[str, Any]] and
metadata: dict[str, Any] or Mapping[str, Any]) and import Any/Mapping from
typing, and make the same change for the other occurrence referenced (the field
at the later occurrence). Ensure the Field(...) declarations remain unchanged
apart from the updated type annotations.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@src/proovy_agent/graph/nodes/ocr_node/__init__.py`:
- Around line 3-10: The module is missing two public exception exports: add
OCRTimeoutError and OCRResourceError to the exceptions import list (the from
.exceptions import (...) block) and include "OCRTimeoutError" and
"OCRResourceError" in the module's __all__ export list so they are accessible at
package level; update both the import statement that currently lists
CommandParsingError, ConfidenceThresholdError, ImageProcessingError,
MathParsingError, OCREngineError, OCRError and the __all__ tuple/list where
public symbols are declared to include these two names.

In `@src/proovy_agent/graph/nodes/ocr_node/exceptions.py`:
- Around line 21-27: The __init__ methods in this file are missing return type
annotations; update each constructor (the __init__ methods such as the one that
currently has signature "def __init__(self, message: str = 'Image preprocessing
failed', details: dict | None = None, recovery_suggestion: str | None = None)"
and the other __init__ definitions around the file) to include an explicit "->
None" return type; ensure every constructor signature (including the ones at the
other occurrences referenced in the review) is changed to "def __init__(...) ->
None:" and keep the existing parameters and super().__init__ calls unchanged.

In `@src/proovy_agent/graph/nodes/ocr_node/models.py`:
- Around line 29-35: Add explicit Python 3.12+ type hints to the Pydantic field
validators: update validate_engines to accept and return list[str] (e.g., v:
list[str]) so its signature is annotated; update validate_image_size to accept
and return tuple[int, int] (or the exact sequence type used by the image_size
field) and update validate_text_content to accept and return str; keep the
`@field_validator` decorator and cls parameter but annotate v and the return types
accordingly so the signatures for validate_engines, validate_image_size, and
validate_text_content are fully typed.

---

Nitpick comments:
In `@src/proovy_agent/graph/nodes/ocr_node/models.py`:
- Around line 45-49: The container fields bbox_data and metadata are currently
typed as list[dict] and dict which weakens static type checks; update their
annotations to concrete types (e.g., bbox_data: list[dict[str, Any]] or
list[Mapping[str, Any]] and metadata: dict[str, Any] or Mapping[str, Any]) and
import Any/Mapping from typing, and make the same change for the other
occurrence referenced (the field at the later occurrence). Ensure the Field(...)
declarations remain unchanged apart from the updated type annotations.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 14caf210-8d58-4abc-ae80-1db5bcf43194

📥 Commits

Reviewing files that changed from the base of the PR and between 266fdd3 and e82e2bd.

📒 Files selected for processing (6)
  • src/proovy_agent/graph/nodes/ocr_node/__init__.py
  • src/proovy_agent/graph/nodes/ocr_node/exceptions.py
  • src/proovy_agent/graph/nodes/ocr_node/models.py
  • tests/ocr_node/__init__.py
  • tests/ocr_node/test_exceptions.py
  • tests/ocr_node/test_models.py

Comment thread src/proovy_agent/graph/nodes/ocr_node/__init__.py
Comment thread src/proovy_agent/graph/nodes/ocr_node/exceptions.py
Comment thread src/proovy_agent/graph/nodes/ocr_node/models.py
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Sub] OCR 데이터 모델 + 예외 처리 구현 (models.py, exceptions.py)

1 participant