맥에서 스크린샷을 찍을 때마다 매번 OCR 앱을 열어서 텍스트를 추출하는 게 번거로우셨나요? Python과 몇 가지 라이브러리만 있으면 스크린샷을 찍는 순간 자동으로 텍스트가 추출되고 클립보드에 복사되는 완전 자동화 시스템을 만들 수 있어요.
스크린샷 전용 폴더를 만들고 설정하기
먼저 스크린샷이 저장될 전용 폴더를 만들어야 해요. 터미널을 열고 다음 명령어를 입력해주세요.
mkdir -p ~/Pictures/Screenshots
defaults write com.apple.screencapture location ~/Pictures/Screenshots
killall SystemUIServer
이제 모든 스크린샷이 ~/Pictures/Screenshots 폴더에 자동으로 저장돼요. 폴더 경로는 원하는 곳으로 변경할 수 있어요.
필요한 Python 패키지 설치하기
폴더 감시와 OCR을 위한 패키지들을 설치해볼게요. 각 패키지의 역할은 다음과 같아요.
pip install watchdog pillow pytesseract pyperclip
brew install tesseract
- watchdog: 폴더를 실시간으로 감시하며 새 파일이 생기면 알려줘요
- pillow: 이미지 파일을 Python에서 다룰 수 있게 해줘요
- pytesseract: Tesseract OCR 엔진을 Python에서 사용할 수 있게 해줘요
- pyperclip: 추출한 텍스트를 클립보드로 복사해줘요
기본 OCR 자동화 스크립트 작성하기
이제 핵심 스크립트를 작성해볼게요. screenshot_ocr.py 라는 이름으로 저장해주세요.
import time
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
from PIL import Image
import pytesseract
import pyperclip
import os
# 스크린샷 폴더 경로 설정
WATCH_FOLDER = os.path.expanduser("~/Pictures/Screenshots")
class ScreenshotHandler(FileSystemEventHandler):
def on_created(self, event):
# 디렉토리가 아니고 이미지 파일인 경우만 처리
if not event.is_directory and event.src_path.lower().endswith((".png", ".jpg", ".jpeg")):
print(f"새 스크린샷 감지: {event.src_path}")
# 파일이 완전히 저장될 때까지 잠시 대기
time.sleep(0.5)
try:
# 이미지 열기
image = Image.open(event.src_path)
# OCR로 텍스트 추출 (한글+영어 동시 인식)
text = pytesseract.image_to_string(image, lang='kor+eng')
# 추출된 텍스트를 클립보드에 복사
pyperclip.copy(text)
print(f"✅ OCR 완료! 텍스트가 클립보드에 복사되었어요.")
print(f"추출된 텍스트:\n{text[:100]}...") # 처음 100자만 출력
except Exception as e:
print(f"❌ OCR 실패: {e}")
if __name__ == "__main__":
# 이벤트 핸들러와 옵저버 설정
event_handler = ScreenshotHandler()
observer = Observer()
observer.schedule(event_handler, WATCH_FOLDER, recursive=False)
# 감시 시작
observer.start()
print(f"📸 {WATCH_FOLDER} 폴더를 감시 중이에요...")
print("스크린샷을 찍으면 자동으로 텍스트가 추출돼요!")
try:
while True:
time.sleep(1)
except KeyboardInterrupt:
observer.stop()
print("\n감시를 종료해요.")
observer.join()
스크립트를 실행하면 이제 스크린샷을 찍을 때마다 자동으로 텍스트가 추출되고 클립보드에 복사돼요. Command+Shift+4로 스크린샷을 찍고 바로 Command+V로 붙여넣기 할 수 있어요.
Apple Vision 프레임워크를 활용한 고품질 OCR
Tesseract도 좋지만, macOS의 네이티브 Vision 프레임워크를 사용하면 더 빠르고 정확한 결과를 얻을 수 있어요. ocrmac 라이브러리를 사용해볼게요.
pip install ocrmac
Vision 프레임워크를 활용한 스크립트는 이렇게 작성해요.
import time
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
from ocrmac import ocrmac
import pyperclip
import os
WATCH_FOLDER = os.path.expanduser("~/Pictures/Screenshots")
class VisionOCRHandler(FileSystemEventHandler):
def on_created(self, event):
if not event.is_directory and event.src_path.lower().endswith((".png", ".jpg", ".jpeg")):
print(f"🎯 새 스크린샷 감지: {os.path.basename(event.src_path)}")
# 파일 저장 완료 대기
time.sleep(0.3)
try:
# Apple Vision으로 OCR 수행
# 결과는 [(텍스트, 신뢰도, 바운딩박스)] 형태로 반환돼요
annotations = ocrmac.OCR(event.src_path).recognize()
# 텍스트만 추출해서 합치기
extracted_text = "\n".join([item[0] for item in annotations])
if extracted_text.strip():
# 클립보드에 복사
pyperclip.copy(extracted_text)
print("✨ Vision OCR 완료! 클립보드에 복사됐어요.")
# 추출된 텍스트 미리보기
preview = extracted_text[:150] + "..." if len(extracted_text) > 150 else extracted_text
print(f"텍스트: {preview}")
else:
print("텍스트를 찾을 수 없어요.")
except Exception as e:
print(f"❌ OCR 오류: {e}")
if __name__ == "__main__":
handler = VisionOCRHandler()
observer = Observer()
observer.schedule(handler, WATCH_FOLDER, recursive=False)
observer.start()
print(f"🚀 Apple Vision OCR 감시 시작!")
print(f"📁 감시 폴더: {WATCH_FOLDER}")
try:
while True:
time.sleep(1)
except KeyboardInterrupt:
observer.stop()
observer.join()
실용적인 기능 추가하기
기본 기능만으로도 충분하지만, 몇 가지 유용한 기능을 더 추가해볼게요.
import time
import re
from datetime import datetime
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
from ocrmac import ocrmac
import pyperclip
import os
WATCH_FOLDER = os.path.expanduser("~/Pictures/Screenshots")
HISTORY_FILE = os.path.expanduser("~/Pictures/Screenshots/ocr_history.txt")
class AdvancedOCRHandler(FileSystemEventHandler):
def __init__(self):
self.processed_files = set() # 중복 처리 방지
def on_created(self, event):
# 이미 처리한 파일은 건너뛰기
if event.src_path in self.processed_files:
return
if not event.is_directory and event.src_path.lower().endswith((".png", ".jpg", ".jpeg")):
self.processed_files.add(event.src_path)
# 스크린샷 시간 기록
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
filename = os.path.basename(event.src_path)
print(f"\n{'='*50}")
print(f"📸 새 스크린샷: {filename}")
print(f"⏰ 시간: {timestamp}")
time.sleep(0.3)
try:
# OCR 수행
annotations = ocrmac.OCR(event.src_path).recognize()
text = "\n".join([item[0] for item in annotations])
if text.strip():
# 공백 정리
text = re.sub(r'\n{3,}', '\n\n', text) # 연속된 줄바꿈 정리
text = text.strip()
# 클립보드 복사
pyperclip.copy(text)
# 히스토리 파일에 저장
self.save_to_history(timestamp, filename, text)
# 텍스트 통계 표시
word_count = len(text.split())
char_count = len(text)
print(f"✅ OCR 성공!")
print(f"📊 통계: {word_count}단어, {char_count}자")
print(f"📋 클립보드에 복사 완료!")
# URL이 있으면 추출해서 보여주기
urls = re.findall(r'https?://[^\s]+', text)
if urls:
print(f"🔗 발견된 URL: {', '.join(urls)}")
else:
print("⚠️ 텍스트를 찾을 수 없어요.")
except Exception as e:
print(f"❌ 오류 발생: {e}")
def save_to_history(self, timestamp, filename, text):
"""OCR 결과를 히스토리 파일에 저장"""
try:
with open(HISTORY_FILE, 'a', encoding='utf-8') as f:
f.write(f"\n{'='*60}\n")
f.write(f"시간: {timestamp}\n")
f.write(f"파일: {filename}\n")
f.write(f"텍스트:\n{text}\n")
f.write(f"{'='*60}\n")
print(f"💾 히스토리 저장: {HISTORY_FILE}")
except Exception as e:
print(f"히스토리 저장 실패: {e}")
# 메인 실행 부분
if __name__ == "__main__":
handler = AdvancedOCRHandler()
observer = Observer()
observer.schedule(handler, WATCH_FOLDER, recursive=False)
observer.start()
print("🎉 고급 OCR 자동화 시작!")
print(f"📁 감시 폴더: {WATCH_FOLDER}")
print(f"📝 히스토리: {HISTORY_FILE}")
print("\n사용법:")
print("- Command+Shift+4: 영역 스크린샷")
print("- Command+Shift+3: 전체 스크린샷")
print("- 텍스트는 자동으로 클립보드에 복사돼요!")
print("- Control+C로 종료")
try:
while True:
time.sleep(1)
except KeyboardInterrupt:
observer.stop()
print("\n\n👋 OCR 자동화를 종료해요.")
observer.join()
백그라운드 실행을 위한 LaunchAgent 설정
스크립트를 매번 수동으로 실행하는 게 번거롭다면, macOS의 LaunchAgent를 사용해서 백그라운드에서 자동 실행되도록 설정할 수 있어요.
~/Library/LaunchAgents/com.user.screenshot-ocr.plist 파일을 만들고 다음 내용을 넣어주세요.
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>Label</key>
<string>com.user.screenshot-ocr</string>
<key>ProgramArguments</key>
<array>
<string>/usr/local/bin/python3</string>
<string>/Users/사용자명/Scripts/screenshot_ocr.py</string>
</array>
<key>RunAtLoad</key>
<true/>
<key>KeepAlive</key>
<true/>
<key>StandardOutPath</key>
<string>/tmp/screenshot-ocr.log</string>
<key>StandardErrorPath</key>
<string>/tmp/screenshot-ocr-error.log</string>
</dict>
</plist>
경로를 자신의 환경에 맞게 수정한 후, 다음 명령어로 활성화해요.
launchctl load ~/Library/LaunchAgents/com.user.screenshot-ocr.plist
성능 최적화 팁
OCR 속도와 정확도를 높이는 몇 가지 팁이 있어요.
스크린샷 해상도가 너무 높으면 처리 시간이 오래 걸려요. 필요한 경우 이미지 크기를 조정해서 처리할 수 있어요.
from PIL import Image
def optimize_image_for_ocr(image_path):
"""OCR을 위한 이미지 최적화"""
img = Image.open(image_path)
# 너무 큰 이미지는 리사이즈
if img.width > 2000 or img.height > 2000:
img.thumbnail((2000, 2000), Image.Resampling.LANCZOS)
# 그레이스케일로 변환 (텍스트 인식률 향상)
if img.mode != 'L':
img = img.convert('L')
return img
실제로 사용해보면 Apple Vision 프레임워크가 Tesseract보다 2-3배 빠르고 한글 인식률도 훨씬 좋아요. 특히 손글씨나 복잡한 레이아웃에서 차이가 크게 나타나요.
이제 스크린샷을 찍기만 하면 자동으로 텍스트가 추출되고 클립보드에 복사되는 나만의 OCR 자동화 시스템이 완성됐어요. 온라인 강의 자료나 이미지로 된 문서를 텍스트로 변환할 때 정말 유용하게 사용할 수 있어요.