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|
+
import difflib
|
| 5 |
+
import re
|
| 6 |
+
from typing import List, Tuple, Optional
|
| 7 |
+
import os
|
| 8 |
+
from dotenv import load_dotenv
|
| 9 |
+
|
| 10 |
+
# 환경변수 로드
|
| 11 |
+
load_dotenv()
|
| 12 |
+
|
| 13 |
+
# Google AI API 설정
|
| 14 |
+
GOOGLE_API_KEY = os.getenv("GOOGLE_API_KEY")
|
| 15 |
+
if GOOGLE_API_KEY:
|
| 16 |
+
genai.configure(api_key=GOOGLE_API_KEY)
|
| 17 |
+
model = genai.GenerativeModel('gemini-1.5-flash')
|
| 18 |
+
|
| 19 |
+
class TextDiffChecker:
|
| 20 |
+
def __init__(self):
|
| 21 |
+
self.model = model if GOOGLE_API_KEY else None
|
| 22 |
+
|
| 23 |
+
def extract_text_from_image(self, image: PIL.Image.Image) -> str:
|
| 24 |
+
"""이미지에서 텍스트 추출"""
|
| 25 |
+
if not self.model:
|
| 26 |
+
return "API 키가 설정되지 않았습니다."
|
| 27 |
+
|
| 28 |
+
try:
|
| 29 |
+
# Gemini Vision으로 텍스트 추출
|
| 30 |
+
prompt = """
|
| 31 |
+
이 이미지에서 모든 텍스트를 정확히 추출해주세요.
|
| 32 |
+
- 배경은 무시하고 텍스트만 인식
|
| 33 |
+
- 글자 크기, 색상, 폰트는 무시
|
| 34 |
+
- 줄바꿈과 공백을 유지
|
| 35 |
+
- 특수문자와 숫자도 모두 포함
|
| 36 |
+
- 추출된 텍스트만 반환 (다른 설명 없이)
|
| 37 |
+
"""
|
| 38 |
+
|
| 39 |
+
response = self.model.generate_content([prompt, image])
|
| 40 |
+
return response.text.strip()
|
| 41 |
+
|
| 42 |
+
except Exception as e:
|
| 43 |
+
return f"텍스트 추출 오류: {str(e)}"
|
| 44 |
+
|
| 45 |
+
def normalize_text(self, text: str) -> str:
|
| 46 |
+
"""텍스트 정규화 (공백, 줄바꿈 정리)"""
|
| 47 |
+
# 연속된 공백을 하나로
|
| 48 |
+
text = re.sub(r'\s+', ' ', text)
|
| 49 |
+
# 앞뒤 공백 제거
|
| 50 |
+
text = text.strip()
|
| 51 |
+
return text
|
| 52 |
+
|
| 53 |
+
def find_differences(self, text1: str, text2: str) -> Tuple[str, List[str]]:
|
| 54 |
+
"""두 텍스트의 차이점 찾기"""
|
| 55 |
+
# 텍스트 정규화
|
| 56 |
+
norm_text1 = self.normalize_text(text1)
|
| 57 |
+
norm_text2 = self.normalize_text(text2)
|
| 58 |
+
|
| 59 |
+
# 단어 단위로 분할
|
| 60 |
+
words1 = norm_text1.split()
|
| 61 |
+
words2 = norm_text2.split()
|
| 62 |
+
|
| 63 |
+
# difflib를 사용한 차이점 분석
|
| 64 |
+
differ = difflib.unified_diff(
|
| 65 |
+
words1, words2,
|
| 66 |
+
fromfile='원본', tofile='비교본',
|
| 67 |
+
lineterm=''
|
| 68 |
+
)
|
| 69 |
+
|
| 70 |
+
diff_result = list(differ)
|
| 71 |
+
|
| 72 |
+
# 차이점 요약
|
| 73 |
+
differences = []
|
| 74 |
+
added_words = []
|
| 75 |
+
removed_words = []
|
| 76 |
+
|
| 77 |
+
for line in diff_result:
|
| 78 |
+
if line.startswith('+') and not line.startswith('+++'):
|
| 79 |
+
added_words.extend(line[1:].split())
|
| 80 |
+
elif line.startswith('-') and not line.startswith('---'):
|
| 81 |
+
removed_words.extend(line[1:].split())
|
| 82 |
+
|
| 83 |
+
if removed_words:
|
| 84 |
+
differences.append(f"❌ 삭제된 단어: {', '.join(removed_words)}")
|
| 85 |
+
|
| 86 |
+
if added_words:
|
| 87 |
+
differences.append(f"✅ 추가된 단어: {', '.join(added_words)}")
|
| 88 |
+
|
| 89 |
+
# HTML로 차이점 강조 표시
|
| 90 |
+
html_diff = self.create_html_diff(words1, words2)
|
| 91 |
+
|
| 92 |
+
return html_diff, differences
|
| 93 |
+
|
| 94 |
+
def create_html_diff(self, words1: List[str], words2: List[str]) -> str:
|
| 95 |
+
"""HTML로 차이점 시각화"""
|
| 96 |
+
matcher = difflib.SequenceMatcher(None, words1, words2)
|
| 97 |
+
|
| 98 |
+
html_parts = []
|
| 99 |
+
html_parts.append("<div style='font-family: monospace; line-height: 1.6;'>")
|
| 100 |
+
html_parts.append("<h3>🔍 텍스트 비교 결과</h3>")
|
| 101 |
+
|
| 102 |
+
# 원본 텍스트
|
| 103 |
+
html_parts.append("<div style='margin: 10px 0;'>")
|
| 104 |
+
html_parts.append("<strong>📄 원본:</strong><br>")
|
| 105 |
+
html_parts.append("<div style='background: #f0f0f0; padding: 10px; border-radius: 5px; margin: 5px 0;'>")
|
| 106 |
+
|
| 107 |
+
for tag, i1, i2, j1, j2 in matcher.get_opcodes():
|
| 108 |
+
if tag == 'equal':
|
| 109 |
+
html_parts.append(' '.join(words1[i1:i2]))
|
| 110 |
+
elif tag == 'delete':
|
| 111 |
+
html_parts.append(f"<span style='background: #ffcccc; text-decoration: line-through;'>{' '.join(words1[i1:i2])}</span>")
|
| 112 |
+
elif tag == 'replace':
|
| 113 |
+
html_parts.append(f"<span style='background: #ffcccc; text-decoration: line-through;'>{' '.join(words1[i1:i2])}</span>")
|
| 114 |
+
|
| 115 |
+
if tag != 'equal':
|
| 116 |
+
html_parts.append(" ")
|
| 117 |
+
|
| 118 |
+
html_parts.append("</div></div>")
|
| 119 |
+
|
| 120 |
+
# 비교본 텍스트
|
| 121 |
+
html_parts.append("<div style='margin: 10px 0;'>")
|
| 122 |
+
html_parts.append("<strong>📝 비교본:</strong><br>")
|
| 123 |
+
html_parts.append("<div style='background: #f0f0f0; padding: 10px; border-radius: 5px; margin: 5px 0;'>")
|
| 124 |
+
|
| 125 |
+
for tag, i1, i2, j1, j2 in matcher.get_opcodes():
|
| 126 |
+
if tag == 'equal':
|
| 127 |
+
html_parts.append(' '.join(words2[j1:j2]))
|
| 128 |
+
elif tag == 'insert':
|
| 129 |
+
html_parts.append(f"<span style='background: #ccffcc; font-weight: bold;'>{' '.join(words2[j1:j2])}</span>")
|
| 130 |
+
elif tag == 'replace':
|
| 131 |
+
html_parts.append(f"<span style='background: #ccffcc; font-weight: bold;'>{' '.join(words2[j1:j2])}</span>")
|
| 132 |
+
|
| 133 |
+
if tag != 'equal':
|
| 134 |
+
html_parts.append(" ")
|
| 135 |
+
|
| 136 |
+
html_parts.append("</div></div>")
|
| 137 |
+
html_parts.append("</div>")
|
| 138 |
+
|
| 139 |
+
return ''.join(html_parts)
|
| 140 |
+
|
| 141 |
+
# 전역 인스턴스
|
| 142 |
+
checker = TextDiffChecker()
|
| 143 |
+
|
| 144 |
+
def process_comparison(image1, image2, text_input, comparison_mode):
|
| 145 |
+
"""메인 비교 처리 함수"""
|
| 146 |
+
if not GOOGLE_API_KEY:
|
| 147 |
+
return "❌ Google API 키를 설정해주세요.", "", []
|
| 148 |
+
|
| 149 |
+
try:
|
| 150 |
+
# 첫 번째 소스에서 텍스트 추출
|
| 151 |
+
if image1 is not None:
|
| 152 |
+
text1 = checker.extract_text_from_image(image1)
|
| 153 |
+
source1_info = "📷 이미지 1에서 추출된 텍스트"
|
| 154 |
+
else:
|
| 155 |
+
return "❌ 첫 번째 이미지를 업로드해주세요.", "", []
|
| 156 |
+
|
| 157 |
+
# 두 번째 소스 처리
|
| 158 |
+
if comparison_mode == "이미지 vs 이미지":
|
| 159 |
+
if image2 is not None:
|
| 160 |
+
text2 = checker.extract_text_from_image(image2)
|
| 161 |
+
source2_info = "📷 이미지 2에서 추출된 텍스트"
|
| 162 |
+
else:
|
| 163 |
+
return "❌ 두 번째 이미지를 업로드해주세요.", "", []
|
| 164 |
+
else: # 이미지 vs 텍스트
|
| 165 |
+
if text_input.strip():
|
| 166 |
+
text2 = text_input.strip()
|
| 167 |
+
source2_info = "📝 입력된 텍스트"
|
| 168 |
+
else:
|
| 169 |
+
return "❌ 비교할 텍스트를 입력해주세요.", "", []
|
| 170 |
+
|
| 171 |
+
# 추출된 텍스트 표시
|
| 172 |
+
extracted_info = f"""
|
| 173 |
+
### 📋 추출된 텍스트
|
| 174 |
+
|
| 175 |
+
**{source1_info}:**
|
| 176 |
+
```
|
| 177 |
+
{text1}
|
| 178 |
+
```
|
| 179 |
+
|
| 180 |
+
**{source2_info}:**
|
| 181 |
+
```
|
| 182 |
+
{text2}
|
| 183 |
+
```
|
| 184 |
+
"""
|
| 185 |
+
|
| 186 |
+
# 차이점 분석
|
| 187 |
+
html_diff, differences = checker.find_differences(text1, text2)
|
| 188 |
+
|
| 189 |
+
if not differences:
|
| 190 |
+
differences = ["✅ 두 텍스트가 동일합니다!"]
|
| 191 |
+
|
| 192 |
+
return extracted_info, html_diff, differences
|
| 193 |
+
|
| 194 |
+
except Exception as e:
|
| 195 |
+
return f"❌ 처리 중 오류 발생: {str(e)}", "", []
|
| 196 |
+
|
| 197 |
+
def create_interface():
|
| 198 |
+
"""Gradio 인터페이스 생성"""
|
| 199 |
+
|
| 200 |
+
with gr.Blocks(
|
| 201 |
+
title="📝 텍스트 비교 검수 시스템",
|
| 202 |
+
theme=gr.themes.Soft(),
|
| 203 |
+
css="""
|
| 204 |
+
.gradio-container {
|
| 205 |
+
max-width: 1200px;
|
| 206 |
+
margin: auto;
|
| 207 |
+
}
|
| 208 |
+
.diff-output {
|
| 209 |
+
border: 1px solid #ddd;
|
| 210 |
+
border-radius: 8px;
|
| 211 |
+
padding: 15px;
|
| 212 |
+
background: white;
|
| 213 |
+
}
|
| 214 |
+
"""
|
| 215 |
+
) as app:
|
| 216 |
+
|
| 217 |
+
gr.Markdown("""
|
| 218 |
+
# 📝 텍스트 비교 검수 시스템
|
| 219 |
+
|
| 220 |
+
이미지의 텍스트를 인식하고 비교하여 차이점을 찾아드립니다.
|
| 221 |
+
|
| 222 |
+
⚙️ **기능:**
|
| 223 |
+
- 🖼️ 이미지에서 텍스트 자동 추출 (Google Gemini Vision API)
|
| 224 |
+
- 🔍 두 텍스트 간 차이점 정확한 분석
|
| 225 |
+
- 📊 시각적 차이점 표시 (추가/삭제/변경)
|
| 226 |
+
- 🎯 배경 무시, 텍스트만 집중 분석
|
| 227 |
+
""")
|
| 228 |
+
|
| 229 |
+
with gr.Row():
|
| 230 |
+
with gr.Column(scale=1):
|
| 231 |
+
gr.Markdown("### 📤 입력")
|
| 232 |
+
|
| 233 |
+
comparison_mode = gr.Radio(
|
| 234 |
+
choices=["이미지 vs 이미지", "이미지 vs 텍스트"],
|
| 235 |
+
value="이미지 vs 이미지",
|
| 236 |
+
label="비교 모드"
|
| 237 |
+
)
|
| 238 |
+
|
| 239 |
+
image1 = gr.Image(
|
| 240 |
+
label="📷 첫 번째 이미지 (원본)",
|
| 241 |
+
type="pil"
|
| 242 |
+
)
|
| 243 |
+
|
| 244 |
+
with gr.Group() as image_group:
|
| 245 |
+
image2 = gr.Image(
|
| 246 |
+
label="📷 두 번째 이미지 (비교본)",
|
| 247 |
+
type="pil"
|
| 248 |
+
)
|
| 249 |
+
|
| 250 |
+
with gr.Group(visible=False) as text_group:
|
| 251 |
+
text_input = gr.Textbox(
|
| 252 |
+
label="📝 비교할 텍스트",
|
| 253 |
+
placeholder="비교하고 싶은 텍스트를 직접 입력하세요...",
|
| 254 |
+
lines=5
|
| 255 |
+
)
|
| 256 |
+
|
| 257 |
+
def toggle_input_mode(mode):
|
| 258 |
+
if mode == "이미지 vs 텍스트":
|
| 259 |
+
return gr.update(visible=False), gr.update(visible=True)
|
| 260 |
+
else:
|
| 261 |
+
return gr.update(visible=True), gr.update(visible=False)
|
| 262 |
+
|
| 263 |
+
comparison_mode.change(
|
| 264 |
+
toggle_input_mode,
|
| 265 |
+
inputs=[comparison_mode],
|
| 266 |
+
outputs=[image_group, text_group]
|
| 267 |
+
)
|
| 268 |
+
|
| 269 |
+
analyze_btn = gr.Button(
|
| 270 |
+
"🔍 텍스트 비교 분석 시작",
|
| 271 |
+
variant="primary",
|
| 272 |
+
size="lg"
|
| 273 |
+
)
|
| 274 |
+
|
| 275 |
+
with gr.Column(scale=2):
|
| 276 |
+
gr.Markdown("### 📊 분석 결과")
|
| 277 |
+
|
| 278 |
+
with gr.Tabs():
|
| 279 |
+
with gr.TabItem("📋 추출된 텍스트"):
|
| 280 |
+
extracted_text = gr.Markdown()
|
| 281 |
+
|
| 282 |
+
with gr.TabItem("🔍 시각적 비교"):
|
| 283 |
+
visual_diff = gr.HTML(elem_classes=["diff-output"])
|
| 284 |
+
|
| 285 |
+
with gr.TabItem("📝 차이점 요약"):
|
| 286 |
+
differences_list = gr.JSON(label="발견된 차이점")
|
| 287 |
+
|
| 288 |
+
# API 키 상태 표시
|
| 289 |
+
if not GOOGLE_API_KEY:
|
| 290 |
+
gr.Markdown("""
|
| 291 |
+
⚠️ **설정 필요:**
|
| 292 |
+
1. Google AI Studio에서 API 키를 발급받으세요
|
| 293 |
+
2. `.env` 파일에 `GOOGLE_API_KEY=your_api_key` 추가
|
| 294 |
+
3. 애플리케이션을 재시작하세요
|
| 295 |
+
""")
|
| 296 |
+
|
| 297 |
+
# 이벤트 연결
|
| 298 |
+
analyze_btn.click(
|
| 299 |
+
process_comparison,
|
| 300 |
+
inputs=[image1, image2, text_input, comparison_mode],
|
| 301 |
+
outputs=[extracted_text, visual_diff, differences_list]
|
| 302 |
+
)
|
| 303 |
+
|
| 304 |
+
# 예시 및 도움말
|
| 305 |
+
gr.Markdown("""
|
| 306 |
+
### 💡 사용 팁
|
| 307 |
+
- 📸 **고품질 이미지 사용**: 텍스트가 선명한 이미지일수록 정확도가 높아집니다
|
| 308 |
+
- 🔤 **다양한 언어 지원**: 한글, 영어, 숫자, 특수문자 모두 인식 가능
|
| 309 |
+
- 🎨 **배경 무시**: 복잡한 배경이 있어도 텍스트만 정확히 추출합니다
|
| 310 |
+
- ⚡ **실시간 비교**: 업로드와 동시에 즉시 분석 결과를 확인할 수 있습니다
|
| 311 |
+
""")
|
| 312 |
+
|
| 313 |
+
return app
|
| 314 |
+
|
| 315 |
+
if __name__ == "__main__":
|
| 316 |
+
app = create_interface()
|
| 317 |
+
app.launch(
|
| 318 |
+
server_name="0.0.0.0",
|
| 319 |
+
server_port=7860,
|
| 320 |
+
share=True
|
| 321 |
+
)
|