Skip to content

fix: 번역이 원활하게 작동되게 코드를 수정 - #37

Merged
Hminkyung merged 12 commits into
developfrom
fix/#36-translate-correct
Jun 11, 2026
Merged

fix: 번역이 원활하게 작동되게 코드를 수정#37
Hminkyung merged 12 commits into
developfrom
fix/#36-translate-correct

Conversation

@Hminkyung

@Hminkyung Hminkyung commented Jun 11, 2026

Copy link
Copy Markdown
Collaborator

📌 작업 요약

🌿 브랜치 정보

  • Source: fix/#36-translate-correct
  • Target: develop (기본)

✅ 체크리스트

  • 브랜치 컨벤션 준수 (feat/refac/hotfix/chore/design/bugfix)
  • 커밋 컨벤션 준수 (feat/fix/refactor/docs/style/chore)
  • self-review 완료
  • 테스트 및 로컬 실행 확인 완료

Summary by CodeRabbit

  • 새로운 기능
    • 뉴스레터 번역 정제 기능 추가로 번역 품질 자동 개선
    • OpenAI 기반 지능형 번역 정제 엔진 구현
    • OpenAI 미사용 시 기존 번역 결과 자동 폴백 지원
    • 시스템 오류 및 설정 오류에 대한 적절한 HTTP 상태 코드(502, 503) 처리

@Hminkyung Hminkyung self-assigned this Jun 11, 2026
@Hminkyung Hminkyung added the fix 버그 수정 작업 label Jun 11, 2026
@coderabbitai

coderabbitai Bot commented Jun 11, 2026

Copy link
Copy Markdown

Review Change Stack

📝 Walkthrough

개요

번역 정제(Translation Refinement) 기능의 완전한 스택을 추가합니다. Papago의 1차 번역 결과를 OpenAI를 통해 자동으로 정제/다듬기하며, 한국어 고정 필드의 제약을 명확히 하고, 빈 필드/누락/공백 처리 및 예외 매핑을 포함합니다.

변경 사항

번역 정제 기능

계층 / 파일 설명
정제 요청/응답 스키마
app/schemas.py
RefineFieldInput, TranslationRefineRequest, RefineFieldOutput, TranslationRefineResponse 4개 Pydantic 모델로 정제 요청/응답 계약 정의. id, koText(입력), translatedText(입력), text(출력) 필드와 alias 매핑, 기본값 포함.
정제 프롬프트 및 기존 제약 명확화
app/services/newsletter_prompt.py
기존 추출 프롬프트에서 conversationTopics[].topicchecklistItems[].content를 항상 한국어로 고정하는 규칙 명시, 번역 초안의 참조 범위 제한 문구 추가. 정제 전용: REFINE_FIELD_SCHEMA/REFINE_RESPONSE_SCHEMA JSON 스키마, build_refine_prompt_messages 함수로 시스템/사용자 프롬프트 조합, 정제 원칙(id/개수 불변, 불필요 재작성 금지, 핵심 정보 누락 시만 다듬기) 규정.
OpenAI 어댑터 정제 메서드
app/services/openai_adapter.py
OpenAINewsletterAdapter.refine_translation 메서드: API 키 검증, 빈 필드 조기 반환, refine 프롬프트 메시지 구성 및 OpenAI /responses 호출(JSON 스키마 제약), 응답 JSON 추출·검증, 검증 실패 시 예외 로깅 후 OpenAIAdapterError 재발생.
정제 서비스 오케스트레이션
app/services/newsletter_extractor.py
refine_translation 공개 함수: 빈 필드 조기 처리, OpenAI 비활성화 시 1차 번역(translated_text) 그대로 반환, 활성화 시 어댑터 호출 → 응답 id 매칭 검증 → 정제 또는 기존 텍스트로 대체, 누락/공백/미등록 id에 경고 로깅.
정제 API 엔드포인트
app/routers/newsletters.py
/refine-translation POST 라우트 추가: refine_translation_endpoint 함수로 서비스 호출 결과 반환, OpenAIConfigurationError → 503, OpenAIAdapterError → 502 예외 매핑.

시퀀스 다이어그램

sequenceDiagram
  participant Client
  participant RefineEndpoint
  participant RefineService
  participant OpenAIAdapter
  participant OpenAI as OpenAI API
  
  Client->>RefineEndpoint: POST /refine-translation
  RefineEndpoint->>RefineService: refine_translation(request)
  alt OpenAI disabled
    RefineService->>RefineService: Use translated_text as-is
    RefineService->>RefineEndpoint: TranslationRefineResponse
  else OpenAI enabled
    RefineService->>OpenAIAdapter: refine_translation(request)
    OpenAIAdapter->>OpenAI: POST /responses with refine schema
    OpenAI->>OpenAIAdapter: JSON response
    OpenAIAdapter->>OpenAIAdapter: Extract and validate JSON
    OpenAIAdapter->>RefineService: TranslationRefineResponse or error
    RefineService->>RefineService: Match/validate field IDs
    RefineService->>RefineEndpoint: TranslationRefineResponse
  end
  RefineEndpoint->>Client: 200 OK or 502/503 error
Loading

예상 코드 리뷰 노력

🎯 3 (Moderate) | ⏱️ ~20 분

관련 PR

  • GACHI-Project/GACHI-AI#6: PR #6과 동일한 openai_adapterrouters/newsletters.py 통합 계층을 통해 /refine-translation 엔드포인트를 연결하며, 두 PR 모두 뉴스레터 OpenAI 어댑터를 확장하고 adapter 오류를 HTTP 502/503으로 변환합니다.

추천 라벨

feat

🚥 Pre-merge checks | ✅ 3 | ❌ 1

❌ Failed checks (1 inconclusive)

Check name Status Explanation Resolution
Description check ❓ Inconclusive PR 설명이 작업 목표는 명확하나 테스트 결과 섹션이 비어있고 검체크리스트가 표시되지 않아 완료도를 확인할 수 없습니다. 테스트 결과(스크린샷/로그)를 추가하고 체크리스트 항목들을 명확히 표시하여 완료 상태를 증명해주세요.
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed 제목이 변역 기능 수정과 관련되어 있으나, 실제 변경사항인 새로운 refine-translation 엔드포인트 추가와 프롬프트 재작성이 구체적으로 명시되지 않았습니다.
Linked Issues check ✅ Passed PR의 코드 변경사항(refine-translation 엔드포인트 추가, 프롬프트 재작성, 검증 로직 추가)이 이슈 #36의 '번역이 원활하게 작동되도록 수정'이라는 요구사항을 충족합니다.
Out of Scope Changes check ✅ Passed 모든 변경사항이 번역 기능 개선과 관련된 범위 내에 있으며, 이슈 #36의 목표 달성을 위한 변경입니다.

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

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/#36-translate-correct

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.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 4

🤖 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 `@app/schemas.py`:
- Around line 151-173: Add a non-empty string constraint to the translated_text
on RefineFieldInput and the text on RefineFieldOutput by specifying min_length=1
in their Field declarations (respecting the existing aliases like
koText/translatedText); update RefineFieldInput.translated_text to use
Field(..., alias="translatedText", min_length=1) and RefineFieldOutput.text to
use Field(..., min_length=1) so the Pydantic models enforce the same minLength:
1 requirement as REFINE_RESPONSE_SCHEMA.

In `@app/services/newsletter_extractor.py`:
- Around line 364-383: The variable requested_by_id is misleading and only used
to compute unknown_ids; replace it with a set of IDs (e.g., requested_ids =
{field.id for field in request.fields}) and use requested_ids when computing
unknown_ids, removing requested_by_id entirely; keep the rest of the logic that
iterates request.fields and uses refined_by_id unchanged so lookups and fallback
to field.translated_text still work.

In `@app/services/newsletter_prompt.py`:
- Around line 319-331: The function build_refine_prompt_messages currently types
fields as list[dict[str, str]] which is not type-safe; update the signature to
accept a well-defined TypedDict (e.g., RefineFieldDict with keys like "id",
"koText", "translatedText") or a pydantic/dataclass model (e.g.,
RefineFieldInput) and update any callers and _build_refine_user_prompt to use
that concrete type so key typos/missing keys are caught by the type checker;
ensure imports for TypedDict or the model are added and adjust any usages in
_build_refine_user_prompt and tests to access fields via the new typed
attributes/keys.
- Around line 358-376: The helper _build_refine_user_prompt uses defensive
field.get('koText', '') and field.get('translatedText', '') but fields are
produced from the RefineFieldInput Pydantic model so those keys always exist;
replace the .get(...) calls with direct indexing field['koText'] and
field['translatedText'] in _build_refine_user_prompt to make intent explicit and
let missing keys raise immediately (use the same concatenation/formatting logic
and keep building field_lines and sections unchanged).
🪄 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: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: de5b8ccf-6921-4f78-ae2c-37d5af659136

📥 Commits

Reviewing files that changed from the base of the PR and between 62049bf and 7493354.

📒 Files selected for processing (5)
  • app/routers/newsletters.py
  • app/schemas.py
  • app/services/newsletter_extractor.py
  • app/services/newsletter_prompt.py
  • app/services/openai_adapter.py

Comment thread app/schemas.py
Comment thread app/services/newsletter_extractor.py
Comment thread app/services/newsletter_prompt.py
Comment thread app/services/newsletter_prompt.py
@Hminkyung
Hminkyung merged commit 42225b3 into develop Jun 11, 2026
3 checks passed
@deli-minju deli-minju changed the title Fix: 번역이 원활하게 작동되게 코드를 수정합니다 fix: 번역이 원활하게 작동되게 코드를 수정 Jun 12, 2026
@deli-minju
deli-minju deleted the fix/#36-translate-correct branch June 12, 2026 19:39
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

fix 버그 수정 작업

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[BUG] 번역이 원활하게 작동되지 않는 부분들을 전부 수정

1 participant