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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import gradio as gr
|
2 |
+
import google.generativeai as genai
|
3 |
+
from PIL import Image
|
4 |
+
import io
|
5 |
+
import base64
|
6 |
+
import json
|
7 |
+
from typing import Optional, Tuple
|
8 |
+
|
9 |
+
class KoreanOCRApp:
|
10 |
+
def __init__(self):
|
11 |
+
self.model = None
|
12 |
+
self.api_key = None
|
13 |
+
|
14 |
+
def configure_api(self, api_key: str) -> str:
|
15 |
+
"""API 키를 설정하고 모델을 초기화합니다."""
|
16 |
+
try:
|
17 |
+
if not api_key or api_key.strip() == "":
|
18 |
+
return "❌ API 키를 입력해주세요."
|
19 |
+
|
20 |
+
genai.configure(api_key=api_key.strip())
|
21 |
+
self.model = genai.GenerativeModel('gemini-2.5-flash')
|
22 |
+
self.api_key = api_key.strip()
|
23 |
+
return "✅ API 키가 성공적으로 설정되었습니다."
|
24 |
+
except Exception as e:
|
25 |
+
return f"❌ API 키 설정 중 오류가 발생했습니다: {str(e)}"
|
26 |
+
|
27 |
+
def extract_korean_text(self, image: Image.Image, api_key: str) -> Tuple[str, Image.Image]:
|
28 |
+
"""이미지에서 한국어 텍스트를 추출합니다."""
|
29 |
+
try:
|
30 |
+
# API 키가 변경되었거나 처음 설정하는 경우
|
31 |
+
if not self.model or self.api_key != api_key.strip():
|
32 |
+
config_result = self.configure_api(api_key)
|
33 |
+
if "❌" in config_result:
|
34 |
+
return config_result, image
|
35 |
+
|
36 |
+
if not image:
|
37 |
+
return "❌ 이미지를 업로드해주세요.", None
|
38 |
+
|
39 |
+
# 이미지 전처리 (선택사항)
|
40 |
+
if image.mode != 'RGB':
|
41 |
+
image = image.convert('RGB')
|
42 |
+
|
43 |
+
# 이미지 크기 최적화 (너무 큰 경우)
|
44 |
+
max_size = 1024
|
45 |
+
if max(image.size) > max_size:
|
46 |
+
ratio = max_size / max(image.size)
|
47 |
+
new_size = tuple(int(dim * ratio) for dim in image.size)
|
48 |
+
image = image.resize(new_size, Image.Resampling.LANCZOS)
|
49 |
+
|
50 |
+
# 한국어 텍스트 추출을 위한 프롬프트
|
51 |
+
prompt = """
|
52 |
+
이 이미지에서 모든 한국어 텍스트를 추출해주세요.
|
53 |
+
다음 규칙을 따라주세요:
|
54 |
+
1. 이미지에 있는 모든 한국어 텍스트를 정확하게 읽어주세요
|
55 |
+
2. 텍스트의 위치나 순서를 고려하여 자연스럽게 배열해주세요
|
56 |
+
3. 줄바꿈이나 문단 구분이 있다면 그대로 유지해주세요
|
57 |
+
4. 영어나 숫자가 함께 있다면 그것도 포함해주세요
|
58 |
+
5. 읽을 수 없거나 불분명한 부분이 있다면 [불분명]으로 표시해주세요
|
59 |
+
|
60 |
+
추출된 텍스트만 출력해주세요:
|
61 |
+
"""
|
62 |
+
|
63 |
+
# Gemini API 호출
|
64 |
+
response = self.model.generate_content([prompt, image])
|
65 |
+
|
66 |
+
if response.text:
|
67 |
+
extracted_text = response.text.strip()
|
68 |
+
success_message = f"✅ 텍스트 추출 완료:\n\n{extracted_text}"
|
69 |
+
return success_message, image
|
70 |
+
else:
|
71 |
+
return "❌ 텍스트를 추출할 수 없습니다.", image
|
72 |
+
|
73 |
+
except Exception as e:
|
74 |
+
error_message = f"❌ 오류가 발생했습니다: {str(e)}"
|
75 |
+
return error_message, image
|
76 |
+
|
77 |
+
def verify_image_display(self, image: Image.Image) -> Tuple[str, Image.Image]:
|
78 |
+
"""업로드된 이미지와 출력창의 이미지가 같은지 확인합니다."""
|
79 |
+
if image is None:
|
80 |
+
return "❌ 이미지를 먼저 업로드해주세요.", None
|
81 |
+
|
82 |
+
try:
|
83 |
+
# 이미지 정보 확인
|
84 |
+
width, height = image.size
|
85 |
+
format_info = image.format if hasattr(image, 'format') else "Unknown"
|
86 |
+
mode = image.mode
|
87 |
+
|
88 |
+
verification_text = f"""
|
89 |
+
✅ 이미지 검증 완료
|
90 |
+
|
91 |
+
📊 이미지 정보:
|
92 |
+
- 크기: {width} x {height} 픽셀
|
93 |
+
- 포맷: {format_info}
|
94 |
+
- 색상 모드: {mode}
|
95 |
+
- 파일 크기: 약 {width * height * (3 if mode == 'RGB' else 1)} 바이트
|
96 |
+
|
97 |
+
🔍 이미지가 올바르게 표시되고 있습니다.
|
98 |
+
"""
|
99 |
+
|
100 |
+
return verification_text, image
|
101 |
+
|
102 |
+
except Exception as e:
|
103 |
+
return f"❌ 이미지 검증 중 오류가 발생했습니다: {str(e)}", image
|
104 |
+
|
105 |
+
def create_app():
|
106 |
+
"""그라디오 앱을 생성합니다."""
|
107 |
+
ocr_app = KoreanOCRApp()
|
108 |
+
|
109 |
+
with gr.Blocks(
|
110 |
+
title="한국어 OCR 텍스트 추출기",
|
111 |
+
theme=gr.themes.Soft(),
|
112 |
+
css="""
|
113 |
+
.container {
|
114 |
+
max-width: 1200px;
|
115 |
+
margin: auto;
|
116 |
+
}
|
117 |
+
.header {
|
118 |
+
text-align: center;
|
119 |
+
padding: 20px;
|
120 |
+
background: linear-gradient(90deg, #667eea 0%, #764ba2 100%);
|
121 |
+
color: white;
|
122 |
+
border-radius: 10px;
|
123 |
+
margin-bottom: 20px;
|
124 |
+
}
|
125 |
+
"""
|
126 |
+
) as app:
|
127 |
+
|
128 |
+
# 헤더
|
129 |
+
gr.HTML("""
|
130 |
+
<div class="header">
|
131 |
+
<h1>🔤 한국어 OCR 텍스트 추출기</h1>
|
132 |
+
<p>Google Gemini를 사용한 고성능 한국어 텍스트 인식</p>
|
133 |
+
</div>
|
134 |
+
""")
|
135 |
+
|
136 |
+
with gr.Row():
|
137 |
+
with gr.Column(scale=1):
|
138 |
+
# API 키 입력 섹션
|
139 |
+
gr.Markdown("## 🔑 API 키 설정")
|
140 |
+
api_key_input = gr.Textbox(
|
141 |
+
label="Google Gemini API 키",
|
142 |
+
placeholder="여기에 API 키를 입력하세요...",
|
143 |
+
type="password",
|
144 |
+
info="https://makersuite.google.com에서 API 키를 발급받으세요"
|
145 |
+
)
|
146 |
+
|
147 |
+
api_status = gr.Textbox(
|
148 |
+
label="API 상태",
|
149 |
+
value="API 키를 입력하고 설정하세요",
|
150 |
+
interactive=False
|
151 |
+
)
|
152 |
+
|
153 |
+
# API 키 설정 버튼
|
154 |
+
api_config_btn = gr.Button("🔧 API 키 설정", variant="primary")
|
155 |
+
|
156 |
+
gr.Markdown("---")
|
157 |
+
|
158 |
+
# 이미지 업로드 섹션
|
159 |
+
gr.Markdown("## 📤 이미지 업로드")
|
160 |
+
image_input = gr.Image(
|
161 |
+
label="한국어 텍스트가 포함된 이미지를 업로드하세요",
|
162 |
+
type="pil",
|
163 |
+
height=300
|
164 |
+
)
|
165 |
+
|
166 |
+
# 버튼들
|
167 |
+
with gr.Row():
|
168 |
+
extract_btn = gr.Button("📖 텍스트 추출", variant="primary")
|
169 |
+
verify_btn = gr.Button("🔍 이미지 검증", variant="secondary")
|
170 |
+
|
171 |
+
with gr.Column(scale=1):
|
172 |
+
# 결과 출력 섹션
|
173 |
+
gr.Markdown("## 📄 추출 결과")
|
174 |
+
|
175 |
+
text_output = gr.Textbox(
|
176 |
+
label="추출된 텍스트",
|
177 |
+
lines=10,
|
178 |
+
placeholder="여기에 추출된 한국어 텍스트가 표시됩니다...",
|
179 |
+
interactive=False
|
180 |
+
)
|
181 |
+
|
182 |
+
gr.Markdown("## 🖼️ 이미지 확인")
|
183 |
+
image_output = gr.Image(
|
184 |
+
label="업로드된 이미지 (검증용)",
|
185 |
+
height=300
|
186 |
+
)
|
187 |
+
|
188 |
+
# 이미지 정보
|
189 |
+
image_info = gr.Textbox(
|
190 |
+
label="이미지 정보",
|
191 |
+
lines=5,
|
192 |
+
interactive=False
|
193 |
+
)
|
194 |
+
|
195 |
+
# 사용법 안내
|
196 |
+
with gr.Accordion("📋 사용법 안내", open=False):
|
197 |
+
gr.Markdown("""
|
198 |
+
### 🔧 설정 방법
|
199 |
+
1. **API 키 발급**: [Google AI Studio](https://makersuite.google.com)에서 무료 API 키를 발급받으세요
|
200 |
+
2. **API 키 입력**: 위의 입력창에 발급받은 API 키를 입력하고 '설정' 버튼을 클릭하세요
|
201 |
+
|
202 |
+
### 📖 텍스트 추출 방법
|
203 |
+
1. **이미지 업로드**: 한국어 텍스트가 포함된 이미지를 업로드하세요
|
204 |
+
2. **텍스트 추출**: '텍스트 추출' 버튼을 클릭하여 OCR을 실행하세요
|
205 |
+
3. **결과 확인**: 오른쪽 결과창에서 추출된 텍스트를 확인하세요
|
206 |
+
|
207 |
+
### 📋 지원 형식
|
208 |
+
- **이미지 형식**: PNG, JPEG, WEBP, HEIC, HEIF
|
209 |
+
- **최대 크기**: 20MB (자동으로 최적화됩니다)
|
210 |
+
- **언어**: 한국어 중심 (영어, 숫자도 인식 가능)
|
211 |
+
|
212 |
+
### 💡 팁
|
213 |
+
- 선명하고 해상도가 높은 이미지를 사용하세요
|
214 |
+
- 텍스트가 잘 보이도록 조명이 충분한 사진을 촬영하세요
|
215 |
+
- 기울어진 이미지는 자동으로 보정을 시도합니다
|
216 |
+
""")
|
217 |
+
|
218 |
+
# 이벤트 핸들러 등록
|
219 |
+
api_config_btn.click(
|
220 |
+
fn=ocr_app.configure_api,
|
221 |
+
inputs=[api_key_input],
|
222 |
+
outputs=[api_status]
|
223 |
+
)
|
224 |
+
|
225 |
+
extract_btn.click(
|
226 |
+
fn=ocr_app.extract_korean_text,
|
227 |
+
inputs=[image_input, api_key_input],
|
228 |
+
outputs=[text_output, image_output]
|
229 |
+
)
|
230 |
+
|
231 |
+
verify_btn.click(
|
232 |
+
fn=ocr_app.verify_image_display,
|
233 |
+
inputs=[image_input],
|
234 |
+
outputs=[image_info, image_output]
|
235 |
+
)
|
236 |
+
|
237 |
+
# 이미지 업로드 시 자동으로 출력창에 표시
|
238 |
+
image_input.change(
|
239 |
+
fn=lambda img: (img, "이미지가 업로드되었습니다. 텍스트 추출을 실행하세요." if img else ""),
|
240 |
+
inputs=[image_input],
|
241 |
+
outputs=[image_output, image_info]
|
242 |
+
)
|
243 |
+
|
244 |
+
return app
|
245 |
+
|
246 |
+
if __name__ == "__main__":
|
247 |
+
app = create_app()
|
248 |
+
app.launch(
|
249 |
+
server_name="0.0.0.0",
|
250 |
+
server_port=7860,
|
251 |
+
share=True,
|
252 |
+
debug=True,
|
253 |
+
show_error=True
|
254 |
+
)
|