Skip to content

[Feat] URL 분석 본문 이미지 최소 1개 보장 - #137

Merged
EH-OI merged 2 commits into
mainfrom
feat/required-content-image
Aug 10, 2026
Merged

EH-OI merged 2 commits into
mainfrom
feat/required-content-image

Conversation

@m00nsh

@m00nsh m00nsh commented Aug 10, 2026 •

Copy link
Copy Markdown
Collaborator

✨ 어떤 이유로 PR를 하셨나요?

  • feature 병합
  • 버그 수정(아래에 issue #를 남겨주세요)
  • 코드 개선
  • 코드 수정
  • 배포
  • 기타(아래에 자세한 내용 기입해주세요)

📋 세부 내용 - 왜 해당 PR이 필요한지 작업 내용을 자세하게 설명해주세요

작업 내용

URL 분석 시 본문에 유효한 이미지 후보가 존재하는 경우
long_analysis에 최소 1개의 이미지가 포함되도록 이미지 선택 정책과 backend fallback을 보강했습니다.

Prompt 변경

활성 URL 분석 prompt의 Image Selection 정책을 수정했습니다.

  • 이미지 후보가 존재하면 최소 1개 반드시 사용
  • 본문 이해에 도움이 되는 관련 이미지 1~3개 우선 선택
  • 서로 다른 핵심 내용을 보완할 수 있는 경우 복수 이미지 활용
  • 중복 이미지 사용 방지
  • 로고, 프로필, 아바타, 광고, 배너, 버튼, 아이콘, 사이트 UI, 단순 장식 이미지 제외
  • 제공된 후보 URL만 사용
  • 이미지 후보가 없으면 이미지 삽입 금지
  • 관련 문단/섹션 근처에 Markdown 이미지 배치

Backend fallback

Prompt 지시만으로 이미지 최소 1개를 완전히 보장할 수 없기 때문에
MaterialAiAnalysisResponseParser에 fallback을 추가했습니다.

동작:

  • imageCandidates 없음

    • 기존처럼 이미지 없이 분석 허용
  • LLM이 이미지 1~3개 반환

    • backend 미개입
    • 기존 long_analysis 그대로 사용
  • imageCandidates가 존재하지만 LLM 이미지가 0개

    • backend에서 후보 중 관련성이 높은 이미지 1개 선택
    • long_analysis의 관련 섹션에 Markdown 형식으로 삽입
    • 보정된 결과를 DB에 저장 및 API로 반환

이미지/섹션 매칭

fallback에서는 이미지 후보의 metadata와
long_analysis의 각 Markdown section을 비교합니다.

주요 metadata:

  • sectionHeading
  • context
  • caption
  • alt
  • title

각 candidate와 section의 관련도를 계산하여
가장 관련성이 높은 (candidate, section) pair를 선택합니다.

관련성이 전혀 확인되지 않는 경우에만
첫 번째 유효 candidate와 첫 번째 안전한 본문 위치를 최종 fallback으로 사용합니다.

Markdown 삽입

fallback 이미지 형식:

![이미지 설명](이미지 URL)

이미지 설명 우선순위:

  1. alt
  2. caption
  3. title
  4. 값이 없으면 이미지

관련 section의 첫 의미 있는 문단 뒤에 삽입하며,
code block이나 Markdown table 내부에는 삽입하지 않습니다.

기존 이미지 정책 유지

기존 backend 이미지 필터링은 변경하지 않았습니다.

  • 광고
  • 배너
  • 로고
  • 프로필/아바타
  • UI/아이콘
  • tracking/placeholder
  • invalid URL
  • tiny image
  • duplicate image

등 기존 noise filtering을 그대로 유지합니다.

또한 기존 image URL whitelist 및 AI retry 정책도 유지합니다.

성능

fallback을 위해 추가적인:

  • OpenAI 호출
  • Vision 호출
  • embedding 생성
  • Qdrant 검색
  • 이미지 다운로드
  • 외부 network 요청

을 수행하지 않습니다.

이미 추출된 image candidate metadata와 long_analysis 문자열만 비교합니다.

검증

  • .\gradlew.bat compileTestJava 성공
  • URL analysis parser/stage/prompt 관련 테스트 성공
  • .\gradlew.bat --no-daemon clean build -x test 성공
  • git diff --check 성공

실제 Swagger 테스트에서도
본문 이미지가 존재하는 Tistory URL을 forceAnalyze=true로 재분석했을 때:

  • HTTP 200
  • ANALYSIS_COMPLETED
  • fullAnalysis 내 Markdown 이미지 포함
  • OAuth 관련 이미지가 관련 분석 section에 배치

되는 것을 확인했습니다.

변경하지 않은 범위

  • URL Analyze API path
  • response DTO
  • DB schema
  • Finalize
  • ALREADY_ANALYZED / forceAnalyze 계약
  • Qdrant / embedding
  • Folder / Material capacity
  • membership / payment
  • Selenium runtime
  • 기존 HtmlContentParser 이미지 filtering

📸 작업 화면 스크린샷

⚠️ PR하기 전에 확인해주세요

  • 로컬테스트를 진행하셨나요?
  • 머지할 브랜치를 확인하셨나요?
  • 관련 label을 선택하셨나요?

🚨 관련 이슈 번호 [ ]

Summary by CodeRabbit

  • 새 기능

    • 장문 분석에 관련 이미지가 자동으로 삽입됩니다.
    • 이미지 후보가 있으면 최소 1개를 사용하고, 섹션별 관련도가 높은 위치를 선택합니다.
    • 이미지 설명은 대체 텍스트, 캡션, 제목 순으로 적용됩니다.
  • 개선 사항

    • 기존 이미지가 있거나 후보가 없으면 원문을 유지합니다.
    • 코드 블록, 표, 제목 영역에는 이미지가 삽입되지 않습니다.
    • 이미지 URL 검증이 보완되었습니다.

@coderabbitai

coderabbitai Bot commented Aug 10, 2026 •

Copy link
Copy Markdown

Review Change Stack

Warning

Review limit reached

@m00nsh, you've reached your PR review limit, so we couldn't start this review.

Next review available in: 30 minutes

You've used all free OSS reviews for now. Wait for the free limit to reset to keep reviewing this public repository.

How can I continue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based reviews.

How do review limits work?

CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability.

For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window.

Please refer docs for additional details.

Review details
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: c05343c7-961b-4220-bfbf-046a595bb163

📥 Commits

Reviewing files that changed from the base of the PR and between a8833ef and ba2e3dd.

📒 Files selected for processing (2)
  • src/main/java/com/teaching/backend/domain/material/service/MaterialAiAnalysisResponseParser.java
  • src/test/java/com/teaching/backend/domain/material/service/MaterialAiAnalysisResponseParserTest.java
📝 Walkthrough

Walkthrough

이미지 후보가 있으면 long_analysis에 fallback 이미지를 삽입하도록 프롬프트와 파서를 변경했습니다. 파서는 섹션별 유사도를 계산하고, Markdown의 안전한 위치에 이미지를 추가합니다. 관련 동작을 테스트로 검증합니다.

Changes

Fallback 이미지 삽입

Layer / File(s) Summary
이미지 선택 프롬프트 계약
src/main/resources/prompts/material/url-analysis-system-prompt.md, src/test/.../ai/MaterialUrlAnalysisPromptBuilderTest.java
이미지 후보가 있으면 long_analysis에 관련 이미지 1개 이상을 포함하도록 규칙과 테스트를 변경했습니다.
후보 선택 및 Markdown 삽입
src/main/java/.../MaterialAiAnalysisResponseParser.java
섹션 제목, 본문, 후보 메타데이터의 유사도를 계산해 후보와 삽입 위치를 선택합니다. 코드 블록, 표, 제목, 기존 이미지 영역을 제외합니다. 이미지 설명은 alt, caption, title 순으로 선택하고 80자로 제한합니다.
Fallback 동작 검증
src/test/.../MaterialAiAnalysisResponseParserTest.java
후보 유무, 기존 이미지 보존, 후보 선택, 설명 우선순위, 안전한 삽입 위치와 URL 분석 JSON 생성을 검증합니다.

Estimated code review effort: 4 (Complex) | ~45 minutes

Sequence Diagram(s)

sequenceDiagram
  participant URLAnalysisResponse
  participant MaterialAiAnalysisResponseParser
  participant MarkdownLongAnalysis
  participant URLValidation
  URLAnalysisResponse->>MaterialAiAnalysisResponseParser: long_analysis와 이미지 후보 전달
  MaterialAiAnalysisResponseParser->>MarkdownLongAnalysis: 섹션 점수 계산 및 fallback 이미지 삽입
  MaterialAiAnalysisResponseParser->>URLValidation: 삽입 전후 이미지 URL 검증
Loading

Possibly related PRs

Suggested labels: 🌟Feat

Suggested reviewers: mymyseoyoung

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% 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
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed URL 분석 본문에 유효한 이미지 최소 1개를 보장하는 핵심 변경 사항을 명확하게 설명합니다.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/required-content-image

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.

@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: 1

🧹 Nitpick comments (4)
src/test/java/com/teaching/backend/domain/material/service/MaterialAiAnalysisResponseParserTest.java (1)

403-440: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

표 회피 동작이 실제로 검증되지 않습니다.

이 테스트에서 후보 메타데이터는 어떤 섹션과도 일치하지 않습니다. 따라서 점수는 0이 되고, 파서는 첫 후보와 첫 섹션인 ## Overview를 선택합니다. ## Overview의 첫 문단은 코드 블록과 표보다 앞에 있습니다. 결과적으로 삽입 로직은 표 분기를 통과하지 않습니다.

Assertion도 이미지가 "```java" 앞에 있다는 점만 확인합니다. 표 회피 경로를 검증하려면 표와 코드 블록 앞에 안전한 문단이 없는 섹션을 후보 섹션으로 만드십시오. 예를 들어 후보의 sectionHeading을 해당 섹션 제목과 일치시키고, 그 섹션이 표로 시작하도록 구성하십시오.

🤖 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/test/java/com/teaching/backend/domain/material/service/MaterialAiAnalysisResponseParserTest.java`
around lines 403 - 440, Update
doesNotInsertFallbackInsideCodeBlockOrMarkdownTable so the image candidate’s
sectionHeading matches a section whose content begins with the Markdown table,
with no safe paragraph before the table or code block. Adjust the longAnalysis
fixture and candidate metadata accordingly, then strengthen the assertions to
verify the fallback is not inserted inside the table while preserving the
existing code-block safety check.
src/main/java/com/teaching/backend/domain/material/service/MaterialAiAnalysisResponseParser.java (2)

135-170: 🚀 Performance & Scalability | 🔵 Trivial | ⚡ Quick win

섹션 정규화 결과를 미리 계산하십시오.

selectFallbackImagePlacement는 후보와 섹션의 모든 조합을 순회합니다. 각 조합에서 scoreField가 5회 호출되고, 호출마다 normalizeSemanticText(section.heading())와 normalizeSemanticText(section.body())가 다시 실행됩니다. normalizeSemanticText는 정규식 치환을 3회 수행하고, semanticTokens도 매번 다시 생성합니다.

section.body()는 분석 본문 전체 길이에 비례합니다. 후보 수 × 섹션 수 × 5회만큼 같은 문자열을 반복 정규화합니다. 섹션별 정규화 문자열과 토큰 집합을 루프 진입 전에 한 번 계산해 재사용하면 비용이 크게 줄어듭니다.

Also applies to: 195-219

🤖 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/main/java/com/teaching/backend/domain/material/service/MaterialAiAnalysisResponseParser.java`
around lines 135 - 170, Update selectFallbackImagePlacement to precompute each
section’s normalized heading, normalized body, and semantic tokens before
iterating over imageCandidates, then pass or reuse this cached section data
within scoreCandidateForSection and its scoreField calls. Ensure each section’s
normalization and tokenization occurs only once while preserving the existing
placement scoring and fallback behavior.

323-389: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

삽입 위치 탐색 로직은 안전합니다.

findInsertionOffset은 fenced code, 표, 섹션 제목, 기존 이미지 줄을 삽입 후보에서 제외합니다. 문단을 찾지 못하면 section.end()를 사용합니다. insertMarkdownImage는 stripTrailing과 stripLeading으로 빈 줄 중복을 방지합니다.

다만 System.lineSeparator()를 사용합니다. 분석 본문의 나머지 줄바꿈은 LLM이 생성한 \n입니다. Windows 환경에서 실행하면 저장된 Markdown에 \r\n과 \n이 섞입니다. 줄바꿈 문자를 \n으로 고정하면 저장 데이터가 일관됩니다.

🤖 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/main/java/com/teaching/backend/domain/material/service/MaterialAiAnalysisResponseParser.java`
around lines 323 - 389, Update insertMarkdownImage to use the literal "\n"
newline consistently instead of System.lineSeparator(), preserving the existing
spacing and insertion behavior while ensuring generated Markdown uses the same
line endings as the analysis content.
src/main/resources/prompts/material/url-analysis-system-prompt.md (1)

63-67: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

규칙 우선순위를 명시하십시오.

Line 63은 후보 목록이 비어 있지 않으면 최소 1개 이미지를 필수로 요구합니다. Line 67은 로고, 배너, 아이콘 등 의미 없는 이미지의 사용을 금지합니다. 후보가 전부 장식성 이미지인 경우 두 규칙이 충돌합니다. 이 경우 모델은 금지된 이미지를 강제로 선택할 수 있습니다.

두 규칙의 우선순위를 문장에 포함하면 모델 동작이 결정적으로 됩니다.

♻️ 제안 수정
-  - 제공된 이미지 후보 목록이 비어 있지 않다면, long_analysis에 최소 1개의 이미지를 반드시 사용하십시오.
+  - 제공된 이미지 후보 목록에 본문 이해에 도움이 되는 이미지가 하나라도 있다면, long_analysis에 최소 1개의 이미지를 반드시 사용하십시오.
+  - 모든 후보가 아래 제외 대상(로고, 배너, 아이콘 등)에만 해당한다면 이미지를 사용하지 마십시오.
🤖 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/main/resources/prompts/material/url-analysis-system-prompt.md` around
lines 63 - 67, 이미지 선택 규칙에서 장식성 이미지 사용 금지 조건이 최소 1개 이미지 사용 조건보다 우선하도록 명시하십시오. 후보
목록이 비어 있지 않더라도 모든 후보가 로고·광고·배너·아이콘 등 제외 대상이면 이미지를 사용하지 않도록 관련 문장을 수정하십시오.
🤖 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/main/java/com/teaching/backend/domain/material/service/MaterialAiAnalysisResponseParser.java`:
- Around line 304-312: Update fallbackMarkdownImage to validate candidate.url()
against the same Markdown-safe URL constraints used by
validateMarkdownImageUrls, rejecting URLs containing whitespace or parentheses
before constructing the image syntax. If no safe candidate remains, skip
insertion by returning the established empty/absent fallback result, while
preserving the existing description normalization for valid URLs.

---

Nitpick comments:
In
`@src/main/java/com/teaching/backend/domain/material/service/MaterialAiAnalysisResponseParser.java`:
- Around line 135-170: Update selectFallbackImagePlacement to precompute each
section’s normalized heading, normalized body, and semantic tokens before
iterating over imageCandidates, then pass or reuse this cached section data
within scoreCandidateForSection and its scoreField calls. Ensure each section’s
normalization and tokenization occurs only once while preserving the existing
placement scoring and fallback behavior.
- Around line 323-389: Update insertMarkdownImage to use the literal "\n"
newline consistently instead of System.lineSeparator(), preserving the existing
spacing and insertion behavior while ensuring generated Markdown uses the same
line endings as the analysis content.

In `@src/main/resources/prompts/material/url-analysis-system-prompt.md`:
- Around line 63-67: 이미지 선택 규칙에서 장식성 이미지 사용 금지 조건이 최소 1개 이미지 사용 조건보다 우선하도록
명시하십시오. 후보 목록이 비어 있지 않더라도 모든 후보가 로고·광고·배너·아이콘 등 제외 대상이면 이미지를 사용하지 않도록 관련 문장을
수정하십시오.

In
`@src/test/java/com/teaching/backend/domain/material/service/MaterialAiAnalysisResponseParserTest.java`:
- Around line 403-440: Update
doesNotInsertFallbackInsideCodeBlockOrMarkdownTable so the image candidate’s
sectionHeading matches a section whose content begins with the Markdown table,
with no safe paragraph before the table or code block. Adjust the longAnalysis
fixture and candidate metadata accordingly, then strengthen the assertions to
verify the fallback is not inserted inside the table while preserving the
existing code-block safety check.
🪄 Autofix

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: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: dc39dbb8-a3a5-4175-9d7d-02a4b5607323

📥 Commits

Reviewing files that changed from the base of the PR and between 01825a9 and a8833ef.

📒 Files selected for processing (4)
  • src/main/java/com/teaching/backend/domain/material/service/MaterialAiAnalysisResponseParser.java
  • src/main/resources/prompts/material/url-analysis-system-prompt.md
  • src/test/java/com/teaching/backend/domain/material/service/MaterialAiAnalysisResponseParserTest.java
  • src/test/java/com/teaching/backend/domain/material/service/ai/MaterialUrlAnalysisPromptBuilderTest.java

@EH-OI
EH-OI merged commit 6e6b0c3 into main Aug 10, 2026
2 checks passed
@m00nsh
m00nsh deleted the feat/required-content-image branch August 13, 2026 12:14
@m00nsh m00nsh added the enhancement New feature or request label Aug 13, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

enhancement New feature or request

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants