2 Commits
v5th ... v7th

Author SHA1 Message Date
db6532b33c v7:UI 보완_20260130 2026-02-20 11:45:16 +09:00
5129ee69d4 v6:HWPX 템플릿 분석·저장·관리_20260128 2026-02-20 11:43:44 +09:00
9 changed files with 2030 additions and 284 deletions

BIN
7th.zip Normal file

Binary file not shown.

173
README.md
View File

@@ -1,13 +1,14 @@
# 글벗 (Geulbeot) v5.0
# 글벗 (Geulbeot) v7.0
**HWPX 스타일 주입 + 표 열 너비 정밀 변환**
**UI 고도화 — 템플릿 관리·작성 방식·문서 유형 선택 UI**
다양한 형식의 자료(PDF·HWP·이미지·Excel 등)를 입력하면, AI가 RAG 파이프라인으로 분석한 뒤
선택한 문서 유형(기획서·보고서·발표자료 등)에 맞는 표준 HTML 문서를 자동 생성합니다.
생성된 문서는 웹 편집기에서 수정하고, HTML / PDF / HWP로 출력합니다.
v5에서는 HWP 변환 품질을 고도화했습니다. 기존 pyhwpx 기본 변환에 HWPX 후처리를 추가하여,
커스텀 스타일 주입과 표 열 너비 정밀 조정이 가능해졌습니다.
v7에서는 프론트엔드 UI를 고도화했습니다.
v6에서 백엔드로만 존재하던 템플릿 관리를 화면에서 직접 조작할 수 있게 되었고,
자료 활용 방식(형식 변경·재구성·신규 작성)과 문서 유형을 시각적으로 선택하는 UI가 추가되었습니다.
---
@@ -19,17 +20,20 @@ v5에서는 HWP 변환 품질을 고도화했습니다. 기존 pyhwpx 기본 변
자료 입력 (파일/폴더)
작성 방식 선택 ─── 형식만 변경 / 내용 재구성 / 신규 작성 (v7 신규)
RAG 파이프라인 (9단계) ─── 공통 처리
문서 유형 선택
문서 유형 선택 ─── UI 리스트 (v7 신규)
├─ 기획서 (기본)
├─ 보고서 (기본)
├─ 발표자료 (기본)
└─ 사용자 등록 (확장 가능)
글벗 표준 HTML 생성
글벗 표준 HTML 생성 ◀── 템플릿 스타일 참조 + 요소 선택 (v7 신규)
웹 편집기 (수기 편집 / AI 편집)
@@ -47,10 +51,11 @@ RAG 파이프라인 (9단계) ─── 공통 처리
- OpenAI API — RAG 임베딩, 인덱싱, 텍스트 추출
- Gemini API — 보고서 콘텐츠·HTML 생성
- **Features**:
- 자료 입력 → 9단계 RAG 파이프라인 (파일 변환 → 추출 → 도메인 분석 → 청킹 → 임베딩 → 코퍼스 → 인덱싱 → 콘텐츠 생성 → HTML 조립)
- 자료 입력 → 9단계 RAG 파이프라인
- 문서 유형별 생성: 기획서 (Claude 3단계), 보고서 (Gemini 2단계)
- AI 편집: 전체 수정 (`/refine`), 부분 수정 (`/refine-selection`)
- HWP 변환: 하이브리드 방식 — pyhwpx 기본 생성 → HWPX 스타일 주입 → 표 열 너비 수정
- HWPX 템플릿 분석·저장·관리
- HWP 변환: 하이브리드 방식 — pyhwpx → HWPX 스타일 주입 → 표 열 너비 수정
- PDF 변환: WeasyPrint 기반
### 2. Frontend (순수 JavaScript)
@@ -59,24 +64,34 @@ RAG 파이프라인 (9단계) ─── 공통 처리
- 웹 WYSIWYG 편집기 — 브라우저에서 생성된 문서 직접 수정
- 페이지 넘김·들여쓰기·정렬 등 서식 도구
- HTML / PDF / HWP 다운로드
- **작성 방식 선택 탭 (v7 신규)**: 📄 형식만 변경 / 🔄 내용의 재구성 / ✨ 문서 참고 신규 작성
- **문서 유형 선택 UI (v7 신규)**: 기획서·보고서 라디오 리스트 + 배지 스타일
- **템플릿 관리 UI (v7 신규)**: 사이드바에서 템플릿 업로드·선택·삭제, 적용할 요소 체크박스
### 3. 변환 엔진 (Converters)
- **RAG 파이프라인**: 9단계 — 파일 형식 통일 → 텍스트·이미지 추출 → 도메인 분석 → 의미 단위 청킹 → RAG 임베딩 → 코퍼스 구축 → FAISS 인덱싱 → 콘텐츠 생성 → HTML 조립
- **분량 자동 판단**: 5,000자 기준 — 긴 문서는 전체 파이프라인, 짧은 문서는 축약 파이프라인
- **HWP 변환 (v5 하이브리드 방식)**:
1. HTML 분석 → StyleAnalyzer로 역할 분류
2. pyhwpx 기본 변환 (표·이미지·머리말·꼬리말 정상 처리)
3. HWP → HWPX 변환
4. HWPX 후처리 — header.xml에 커스텀 스타일 정의 주입, section*.xml에 역할별 styleIDRef 매핑
5. HWPX 후처리 — 표 열 너비 정밀 수정 (px/mm/% → HWPML 단위 변환)
- **HWP 변환 (하이브리드 방식)**: HTML 분석 → pyhwpx 변환 → HWPX 스타일 주입 → 표 열 너비 수정
### 4. 주요 시나리오 (Core Scenarios)
### 4. 템플릿 관리
- **HWPX 파싱**: 업로드된 HWPX를 압축 해제하여 header.xml + section*.xml 구조 분석
- **자동 추출**: 폰트·문단·표·배경·테두리·페이지 설정
- **CSS 자동 생성**: 분석된 스타일 → CSS 변환
- **저장소**: `templates_store/` — meta.json + 원본 + 분석 결과
- **UI 연동 (v7 신규)**: 사이드바에서 목록 조회·선택·삭제, 요소별 적용 체크박스
### 5. 주요 시나리오 (Core Scenarios)
1. **기획서 생성**: 텍스트 또는 파일을 입력하면, RAG 분석 후 Claude API가 구조 추출 → 페이지 배치 계획 → 글벗 표준 HTML 기획서를 생성. 1~N페이지 옵션 지원
2. **보고서 생성**: 폴더 경로의 자료들을 RAG 파이프라인으로 분석하고, Gemini API가 섹션별 콘텐츠 초안 → 표지·목차·간지·별첨이 포함된 다페이지 HTML 보고서를 생성
3. **AI 편집**: 생성된 문서를 웹 편집기에서 확인 후, "이 부분을 표로 바꿔줘" 같은 피드백으로 전체 또는 선택 부분을 AI가 수정
4. **HWP 내보내기 (v5 개선)**: 기존 pyhwpx 변환 후 HWPX를 열어 커스텀 스타일(제목 계층·본문·표 등)을 주입하고, 표 열 너비를 원본 HTML과 일치시켜 서식 정확도를 높임
3. **작성 방식 선택 (v7 신규)**: 업로드 자료를 어떻게 활용할지 3가지 모드 중 선택
- 📄 **형식만 변경** — 원본 내용 유지, 글벗 양식으로만 변환
- 🔄 **내용의 재구성** — 원본 기반으로 구조와 내용을 재구성 (기본값)
-**문서 참고 신규 작성** — 원본을 참고 자료로만 활용, 새로 작성
4. **템플릿 적용**: 등록된 HWPX 템플릿을 선택하고, 적용할 요소(제목 스타일·표 스타일·색상 등)를 체크박스로 선택
5. **HWP 내보내기**: pyhwpx 변환 후 HWPX 스타일 주입 + 표 열 너비 정밀 수정
### 프로세스 플로우
@@ -108,85 +123,18 @@ flowchart TD
I --> J
```
#### 문서 유형별 생성 → 편집 → 출력
```mermaid
flowchart TD
classDef decision fill:#fffde7,stroke:#f9a825,stroke-width:2px,color:#333
classDef aiClaude fill:#fff3cd,stroke:#d97706,stroke-width:2px,color:#856404
classDef aiGemini fill:#d6eaf8,stroke:#4285f4,stroke-width:2px,color:#1a4d8f
classDef editStyle fill:#fff3e0,stroke:#ef6c00,stroke-width:1.5px,color:#e65100
classDef exportStyle fill:#f3e5f5,stroke:#7b1fa2,stroke-width:1.5px,color:#4a148c
classDef startEnd fill:#1a365d,stroke:#1a365d,color:#fff,stroke-width:2px
classDef planned fill:#f5f5f5,stroke:#999,stroke-width:1px,stroke-dasharray: 5 5,color:#999
classDef newModule fill:#fff3e0,stroke:#ef6c00,stroke-width:2px,color:#e65100
A(["📋 RAG 분석 결과"]):::startEnd
B{"문서 유형 선택"}:::decision
C["기획서 생성\n구조추출→배치→HTML\n⚡ Claude API"]:::aiClaude
D["보고서 생성\n콘텐츠→HTML 조립\n⚡ Gemini API"]:::aiGemini
E["발표자료 생성\n예정"]:::planned
F["사용자 등록 유형\n확장 가능"]:::planned
G["글벗 표준 HTML\nA4·Navy·Noto Sans KR"]:::startEnd
H{"편집 방식"}:::decision
I["웹 편집기\n수기 편집"]:::editStyle
J["AI 편집\n전체·부분 수정\n⚡ Claude API"]:::aiClaude
K{"출력 형식"}:::decision
L["HTML / PDF"]:::exportStyle
M["HWP 변환 (v5 하이브리드)\npyhwpx→스타일주입→표주입"]:::newModule
N["PPT 변환\n예정"]:::planned
O(["✅ 최종 산출물"]):::startEnd
A --> B
B -->|"기획서"| C --> G
B -->|"보고서"| D --> G
B -->|"발표자료"| E -.-> G
B -->|"확장"| F -.-> G
G --> H
H -->|"수기"| I --> K
H -->|"AI"| J --> K
K -->|"웹/인쇄"| L --> O
K -->|"HWP"| M --> O
K -->|"PPT"| N -.-> O
```
#### HWP 변환 (v5 하이브리드 방식)
```mermaid
flowchart TD
classDef process fill:#e8f4fd,stroke:#1a365d,stroke-width:1.5px,color:#1a365d
classDef newModule fill:#fff3e0,stroke:#ef6c00,stroke-width:2px,color:#e65100
classDef exportStyle fill:#f3e5f5,stroke:#7b1fa2,stroke-width:1.5px,color:#4a148c
classDef startEnd fill:#1a365d,stroke:#1a365d,color:#fff,stroke-width:2px
A(["📄 글벗 HTML"]):::startEnd
B["① StyleAnalyzer\nHTML 요소 역할 분류"]:::process
C["② pyhwpx 기본 변환\n표·이미지·머리말 처리"]:::process
D["③ HWP → HWPX 변환"]:::process
E["④ 스타일 주입\nhwpx_style_injector\nheader.xml + section.xml"]:::newModule
F["⑤ 표 열 너비 수정\nhwpx_table_injector\npx/mm/% → HWPML"]:::newModule
G([".hwpx 파일"]):::exportStyle
A --> B --> C --> D --> E --> F --> G
```
---
## 🔄 v4 → v5 변경사항
## 🔄 v6 → v7 변경사항
| 영역 | v4 | v5 |
| 영역 | v6 | v7 |
|------|------|------|
| HWP 변환 방식 | pyhwpx 기본 변환만 | 하이브리드: pyhwpx → HWPX 후처리 |
| 스타일 주입 | style_analyzer로 분석만 | + **hwpx_style_injector** — header.xml 스타일 정의, section.xml 매핑 |
| 표 열 너비 | HTML 원본과 불일치 | + **hwpx_table_injector** — px/mm/% → HWPML 정밀 변환 |
| 표 너비 파싱 | 없음 | html_to_hwp.py에 `_parse_width()` 유틸 추가 |
| HWP 출력 형식 | .hwp만 | .hwpx 출력 지원 (mimetype 추가) |
| 테스트 코드 | dkdl.py 잔존 | 삭제 (정리) |
| 작성 방식 | 없음 (무조건 재구성) | **3가지 모드 UI**: 형식 변경 / 재구성 / 신규 작성 |
| 문서 유형 선택 | 기획서·보고서 구분 없이 탭 | **문서 유형 라디오 리스트** + 배지 스타일 |
| 템플릿 관리 UI | API만 존재 (화면 없음) | **사이드바 UI**: 목록·선택·삭제 + 요소별 체크박스 |
| 템플릿 업로드 | API 직접 호출 | **모달 UI**: 파일 선택 + 이름 입력 + 업로드 |
| index.html | 2,974줄 | 3,400줄 (+426) |
| Python | 변경 없음 | 변경 없음 |
---
@@ -195,10 +143,10 @@ flowchart TD
- **Phase 1**: RAG 파이프라인 — 9단계 파이프라인, 도메인 분석, 분량 자동 판단 (🔧 기본 구현)
- **Phase 2**: 문서 생성 — 기획서·보고서 AI 생성 + 글벗 표준 HTML 양식 (🔧 기본 구현)
- **Phase 3**: 출력 — HTML/PDF 다운로드, HWP 변환 (🔧 기본 구현)
- **Phase 4**: HWP/HWPX/HTML 매핑 — 스타일 분석·HWPX 생성·스타일 주입·표 주입 (🔧 기본 구현 · 현재 버전)
- **Phase 4**: HWP/HWPX/HTML 매핑 — 스타일 분석·HWPX 생성·스타일 주입·표 주입 (🔧 기본 구현)
- **Phase 5**: 문서 유형 분석·등록 — HWPX 업로드 → AI 구조 분석 → 유형 CRUD + 확장 (예정)
- **Phase 6**: HWPX 템플릿 관리 — 파싱·시맨틱 매핑·스타일 추출·표 매칭·콘텐츠 주입 (예정)
- **Phase 7**: UI 고도화 — 프론트 모듈화, 데모 모드, AI 편집 개선, 도메인 선택기 (예정)
- **Phase 6**: HWPX 템플릿 관리 — 파싱·스타일 추출·CSS 생성·저장·조회·삭제 (🔧 기본 구현)
- **Phase 7**: UI 고도화 — 작성 방식 선택, 문서 유형 UI, 템플릿 관리 UI (🔧 기본 구현 · 현재 버전)
- **Phase 8**: 백엔드 재구조화 + 배포 — 패키지 정리, API 키 공통화, 로깅, Docker (예정)
---
@@ -217,8 +165,8 @@ flowchart TD
```bash
# 저장소 클론 및 설정
git clone http://[Gitea주소]/kei/geulbeot-v5.git
cd geulbeot-v5
git clone http://[Gitea주소]/kei/geulbeot-v7.git
cd geulbeot-v7
# 가상환경
python -m venv venv
@@ -252,38 +200,39 @@ python app.py
## 📂 프로젝트 구조
```
geulbeot_5th/
geulbeot_7th/
├── app.py # Flask 웹 서버 — API 라우팅
├── api_config.py # .env 환경변수 로더
├── handlers/ # 비즈니스 로직
│ ├── common.py # Claude API 호출, JSON/HTML 추출
│ ├── briefing/ # 기획서 처리 (구조추출 → 배치 → HTML)
── report/ # 보고서 처리 (RAG 파이프라인 연동)
── report/ # 보고서 처리 (RAG 파이프라인 연동)
│ └── template/ # 템플릿 관리 (HWPX 파싱·분석·CRUD)
├── converters/ # 변환 엔진
│ ├── pipeline/ # 9단계 RAG 파이프라인
│ │ ├── router.py # 분량 판단 (5,000자 기준)
│ │ └── step1 ~ step9 # 변환→추출→분석→청킹→임베딩→코퍼스→인덱싱→콘텐츠→HTML
│ ├── style_analyzer.py # HTML 요소 역할 분류
│ ├── hwpx_generator.py # HWPX 파일 직접 생성
│ ├── hwp_style_mapping.py # 역할 → HWP 스타일 매핑
│ ├── hwpx_style_injector.py # ★ v5 신규 — HWPX 커스텀 스타일 주입
│ ├── hwpx_table_injector.py # ★ v5 신규 — HWPX 표 열 너비 정밀 수정
│ ├── html_to_hwp.py # 보고서 → HWP 변환 (하이브리드 워크플로우)
│ ├── hwpx_style_injector.py # HWPX 커스텀 스타일 주입
│ ├── hwpx_table_injector.py # HWPX 표 열 너비 정밀 수정
│ ├── html_to_hwp.py # 보고서 → HWP 변환
│ └── html_to_hwp_briefing.py # 기획서 → HWP 변환
├── templates_store/ # 등록된 템플릿 저장소
├── static/
│ ├── js/editor.js # 웹 WYSIWYG 편집기
│ └── css/editor.css # 편집기 스타일
├── templates/
│ ├── index.html # 메인 UI
│ ├── index.html # ★ v7 고도화 — 작성 방식·문서 유형·템플릿 UI
│ └── hwp_guide.html # HWP 변환 가이드
├── .env / .env.sample # API 키 관리
├── .gitignore
├── requirements.txt
├── Procfile # 배포 설정 (Gunicorn)
├── Procfile
└── README.md
```
@@ -307,6 +256,8 @@ geulbeot_5th/
- API 키 분산: 파이프라인 각 step에 개별 정의 (공통화 미완)
- HWP 변환: Windows + pyhwpx + 한글 프로그램 필수
- 문서 유형: 기획서·보고서만 구현, 발표자료·사용자 등록 유형 미구현
- 작성 방식: UI만 구현, 백엔드 로직 미연동 (모드별 프롬프트 분기 예정)
- 템플릿 → 문서 생성 연동: 아직 미연결 (선택·체크는 가능, 생성 시 자동 적용은 예정)
- 레거시 잔존: prompts/ 디렉토리
---
@@ -315,9 +266,9 @@ geulbeot_5th/
| 영역 | 줄 수 |
|------|-------|
| Python 전체 | 10,782 (+1,002) |
| 프론트엔드 (JS + CSS + HTML) | 3,859 |
| **합계** | **~14,600** |
| Python 전체 | 11,500 |
| 프론트엔드 (JS + CSS + HTML) | 4,904 (+1,045) |
| **합계** | **~16,400** |
---
@@ -329,7 +280,9 @@ geulbeot_5th/
| v2 | 웹 편집기 추가 |
| v3 | 9단계 RAG 파이프라인 + HWP 변환 |
| v4 | 코드 모듈화 (handlers 패키지) + 스타일 분석기·HWPX 생성기 |
| **v5** | **HWPX 스타일 주입 + 표 열 너비 정밀 변환** |
| v5 | HWPX 스타일 주입 + 표 열 너비 정밀 변환 |
| v6 | HWPX 템플릿 분석·저장·관리 |
| **v7** | **UI 고도화 — 작성 방식·문서 유형·템플릿 관리 UI** |
---

65
app.py
View File

@@ -9,6 +9,8 @@ import io
import tempfile
from datetime import datetime
from flask import Flask, render_template, request, jsonify, Response, session, send_file
from handlers.template import TemplateProcessor
# 문서 유형별 프로세서
from handlers.briefing import BriefingProcessor
@@ -18,13 +20,15 @@ app = Flask(__name__)
app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024 # 16MB max
app.config['SECRET_KEY'] = os.environ.get('SECRET_KEY', 'geulbeot-light-secret-key-v2')
# 프로세서 인스턴스
# processors 딕셔너리에 추가
processors = {
'briefing': BriefingProcessor(),
'report': ReportProcessor()
'report': ReportProcessor(),
'template': TemplateProcessor() # 추가
}
# ============== 메인 페이지 ==============
@app.route('/')
@@ -75,7 +79,8 @@ def generate_report():
'cover': data.get('cover', False),
'toc': data.get('toc', False),
'divider': data.get('divider', False),
'instruction': data.get('instruction', '')
'instruction': data.get('instruction', ''),
'template_id': data.get('template_id')
}
result = processors['report'].generate(content, options)
@@ -290,7 +295,59 @@ def analyze_styles():
except Exception as e:
import traceback
return jsonify({'error': str(e), 'trace': traceback.format_exc()}), 500
@app.route('/templates', methods=['GET'])
def get_templates():
"""저장된 템플릿 목록 조회"""
try:
result = processors['template'].get_list()
return jsonify(result)
except Exception as e:
return jsonify({'error': str(e)}), 500
@app.route('/analyze-template', methods=['POST'])
def analyze_template():
"""템플릿 분석 및 저장"""
try:
if 'file' not in request.files:
return jsonify({'error': '파일이 없습니다'}), 400
file = request.files['file']
name = request.form.get('name', '').strip()
if not name:
return jsonify({'error': '템플릿 이름을 입력해주세요'}), 400
if not file.filename:
return jsonify({'error': '파일을 선택해주세요'}), 400
result = processors['template'].analyze(file, name)
if 'error' in result:
return jsonify(result), 400
return jsonify(result)
except Exception as e:
import traceback
return jsonify({'error': str(e), 'trace': traceback.format_exc()}), 500
@app.route('/delete-template/<template_id>', methods=['DELETE'])
def delete_template(template_id):
"""템플릿 삭제"""
try:
result = processors['template'].delete(template_id)
if 'error' in result:
return jsonify(result), 400
return jsonify(result)
except Exception as e:
return jsonify({'error': str(e)}), 500
if __name__ == '__main__':
port = int(os.environ.get('PORT', 5000))

View File

@@ -34,23 +34,21 @@ def is_long_document(html_content: str) -> bool:
def convert_image_paths(html_content: str) -> str:
"""
HTML 내 상대 이미지 경로를 서버 경로로 변환
assets/xxx.png → /assets/xxx.png
HTML 내 이미지 경로를 서버 경로로 변환
- assets/xxx.png → /assets/xxx.png (Flask 서빙용)
- 절대 경로나 URL은 그대로 유지
"""
result = re.sub(r'src="assets/', 'src="/assets/', html_content)
return result
def replace_src(match):
original_path = match.group(1)
# 이미 절대 경로이거나 URL이면 그대로
if original_path.startswith(('http://', 'https://', 'file://', 'D:', 'C:')):
if original_path.startswith(('http://', 'https://', 'file://', 'D:', 'C:', '/')):
return match.group(0)
# assets/로 시작하면 절대 경로로 변환
# assets/로 시작하면 /assets/로 변환 (Flask 서빙)
if original_path.startswith('assets/'):
filename = original_path.replace('assets/', '')
absolute_path = os.path.join(ASSETS_BASE_PATH, filename)
return f'src="{absolute_path}"'
return f'src="/{original_path}"'
return match.group(0)
@@ -80,6 +78,29 @@ def run_short_pipeline(html_content: str, options: dict) -> Dict[str, Any]:
'pipeline': 'short'
}
def inject_template_css(html_content: str, template_css: str) -> str:
"""
HTML에 템플릿 CSS 주입
- <style> 태그가 있으면 그 안에 추가
- 없으면 <head>에 새로 생성
"""
if not template_css:
return html_content
css_block = f"\n/* ===== 템플릿 스타일 ===== */\n{template_css}\n"
# 기존 </style> 태그 앞에 추가
if '</style>' in html_content:
return html_content.replace('</style>', f'{css_block}</style>', 1)
# <head> 태그 뒤에 새로 추가
elif '<head>' in html_content:
return html_content.replace('<head>', f'<head>\n<style>{css_block}</style>', 1)
# head도 없으면 맨 앞에 추가
else:
return f'<style>{css_block}</style>\n{html_content}'
def run_long_pipeline(html_content: str, options: dict) -> Dict[str, Any]:
"""
@@ -136,4 +157,9 @@ def process_document(content: str, options: dict = None) -> Dict[str, Any]:
result['char_count'] = char_count
result['threshold'] = LONG_DOC_THRESHOLD
# ⭐ 템플릿 CSS 주입
template_css = options.get('template_css')
if template_css and result.get('success') and result.get('html'):
result['html'] = inject_template_css(result['html'], template_css)
return result

View File

@@ -31,6 +31,15 @@ class ReportProcessor:
if not content.strip():
return {'error': '내용이 비어있습니다.'}
# ⭐ 템플릿 스타일 로드
template_id = options.get('template_id')
if template_id:
from handlers.template import TemplateProcessor
template_processor = TemplateProcessor()
style = template_processor.get_style(template_id)
if style and style.get('css'):
options['template_css'] = style['css']
# 이미지 경로 변환
processed_html = convert_image_paths(content)

View File

@@ -0,0 +1,3 @@
from .processor import TemplateProcessor
__all__ = ['TemplateProcessor']

View File

@@ -0,0 +1,625 @@
# -*- coding: utf-8 -*-
"""
템플릿 처리 로직 (v3 - 실제 구조 정확 분석)
- HWPX 파일의 실제 표 구조, 이미지 배경, 테두리 정확히 추출
- ARGB 8자리 색상 정규화
- NONE 테두리 색상 제외
"""
import os
import json
import uuid
import shutil
import zipfile
import xml.etree.ElementTree as ET
from pathlib import Path
from datetime import datetime
from typing import Dict, Any, List, Optional
from collections import Counter, defaultdict
# 템플릿 저장 경로
TEMPLATES_DIR = Path(__file__).parent.parent.parent / 'templates_store'
TEMPLATES_DIR.mkdir(exist_ok=True)
# HWP 명세서 기반 상수
LINE_TYPES = {
'NONE': '없음',
'SOLID': '실선',
'DASH': '긴 점선',
'DOT': '점선',
'DASH_DOT': '-.-.-.-.',
'DASH_DOT_DOT': '-..-..-..',
'DOUBLE_SLIM': '2중선',
'SLIM_THICK': '가는선+굵은선',
'THICK_SLIM': '굵은선+가는선',
'SLIM_THICK_SLIM': '가는선+굵은선+가는선',
'WAVE': '물결',
'DOUBLE_WAVE': '물결 2중선',
}
class TemplateProcessor:
"""템플릿 처리 클래스 (v3)"""
NS = {
'hh': 'http://www.hancom.co.kr/hwpml/2011/head',
'hc': 'http://www.hancom.co.kr/hwpml/2011/core',
'hp': 'http://www.hancom.co.kr/hwpml/2011/paragraph',
'hs': 'http://www.hancom.co.kr/hwpml/2011/section',
}
def __init__(self):
self.templates_dir = TEMPLATES_DIR
self.templates_dir.mkdir(exist_ok=True)
# =========================================================================
# 공개 API
# =========================================================================
def get_list(self) -> Dict[str, Any]:
"""저장된 템플릿 목록"""
templates = []
for item in self.templates_dir.iterdir():
if item.is_dir():
meta_path = item / 'meta.json'
if meta_path.exists():
try:
meta = json.loads(meta_path.read_text(encoding='utf-8'))
templates.append({
'id': meta.get('id', item.name),
'name': meta.get('name', item.name),
'features': meta.get('features', []),
'created_at': meta.get('created_at', '')
})
except:
pass
templates.sort(key=lambda x: x.get('created_at', ''), reverse=True)
return {'templates': templates}
def analyze(self, file, name: str) -> Dict[str, Any]:
"""템플릿 파일 분석 및 저장"""
filename = file.filename
ext = Path(filename).suffix.lower()
if ext not in ['.hwpx', '.hwp', '.pdf']:
return {'error': f'지원하지 않는 파일 형식: {ext}'}
template_id = str(uuid.uuid4())[:8]
template_dir = self.templates_dir / template_id
template_dir.mkdir(exist_ok=True)
try:
original_path = template_dir / f'original{ext}'
file.save(str(original_path))
if ext == '.hwpx':
style_data = self._analyze_hwpx(original_path, template_dir)
else:
style_data = self._analyze_fallback(ext)
if 'error' in style_data:
shutil.rmtree(template_dir)
return style_data
# 특징 추출
features = self._extract_features(style_data)
# 메타 저장
meta = {
'id': template_id,
'name': name,
'original_file': filename,
'file_type': ext,
'features': features,
'created_at': datetime.now().isoformat()
}
(template_dir / 'meta.json').write_text(
json.dumps(meta, ensure_ascii=False, indent=2), encoding='utf-8'
)
# 스타일 저장
(template_dir / 'style.json').write_text(
json.dumps(style_data, ensure_ascii=False, indent=2), encoding='utf-8'
)
# CSS 저장
css = style_data.get('css', '')
css_dir = template_dir / 'css'
css_dir.mkdir(exist_ok=True)
(css_dir / 'template.css').write_text(css, encoding='utf-8')
return {
'success': True,
'template': {
'id': template_id,
'name': name,
'features': features,
'created_at': meta['created_at']
}
}
except Exception as e:
if template_dir.exists():
shutil.rmtree(template_dir)
raise e
def delete(self, template_id: str) -> Dict[str, Any]:
"""템플릿 삭제"""
template_dir = self.templates_dir / template_id
if not template_dir.exists():
return {'error': '템플릿을 찾을 수 없습니다'}
shutil.rmtree(template_dir)
return {'success': True, 'deleted': template_id}
def get_style(self, template_id: str) -> Optional[Dict[str, Any]]:
"""템플릿 스타일 반환"""
style_path = self.templates_dir / template_id / 'style.json'
if not style_path.exists():
return None
return json.loads(style_path.read_text(encoding='utf-8'))
# =========================================================================
# HWPX 분석 (핵심)
# =========================================================================
def _analyze_hwpx(self, file_path: Path, template_dir: Path) -> Dict[str, Any]:
"""HWPX 분석 - 실제 구조 정확히 추출"""
extract_dir = template_dir / 'extracted'
try:
with zipfile.ZipFile(file_path, 'r') as zf:
zf.extractall(extract_dir)
result = {
'version': 'v3',
'fonts': {},
'colors': {
'background': [],
'border': [],
'text': []
},
'border_fills': {},
'tables': [],
'special_borders': [],
'style_summary': {},
'css': ''
}
# 1. header.xml 분석
header_path = extract_dir / 'Contents' / 'header.xml'
if header_path.exists():
self._parse_header(header_path, result)
# 2. section0.xml 분석
section_path = extract_dir / 'Contents' / 'section0.xml'
if section_path.exists():
self._parse_section(section_path, result)
# 3. 스타일 요약 생성
result['style_summary'] = self._create_style_summary(result)
# 4. CSS 생성
result['css'] = self._generate_css(result)
return result
finally:
if extract_dir.exists():
shutil.rmtree(extract_dir)
def _parse_header(self, header_path: Path, result: Dict):
"""header.xml 파싱 - 폰트, borderFill"""
tree = ET.parse(header_path)
root = tree.getroot()
# 폰트
for fontface in root.findall('.//hh:fontface', self.NS):
if fontface.get('lang') == 'HANGUL':
for font in fontface.findall('hh:font', self.NS):
result['fonts'][font.get('id')] = font.get('face')
# borderFill
for bf in root.findall('.//hh:borderFill', self.NS):
bf_id = bf.get('id')
bf_data = self._parse_border_fill(bf, result)
result['border_fills'][bf_id] = bf_data
def _parse_border_fill(self, bf, result: Dict) -> Dict:
"""개별 borderFill 파싱"""
bf_id = bf.get('id')
data = {
'id': bf_id,
'type': 'empty',
'background': None,
'image': None,
'borders': {}
}
# 이미지 배경
img_brush = bf.find('.//hc:imgBrush', self.NS)
if img_brush is not None:
img = img_brush.find('hc:img', self.NS)
if img is not None:
data['type'] = 'image'
data['image'] = {
'ref': img.get('binaryItemIDRef'),
'effect': img.get('effect')
}
# 단색 배경
win_brush = bf.find('.//hc:winBrush', self.NS)
if win_brush is not None:
face_color = self._normalize_color(win_brush.get('faceColor'))
if face_color and face_color != 'none':
if data['type'] == 'empty':
data['type'] = 'solid'
data['background'] = face_color
if face_color not in result['colors']['background']:
result['colors']['background'].append(face_color)
# 4방향 테두리
for side in ['top', 'bottom', 'left', 'right']:
border = bf.find(f'hh:{side}Border', self.NS)
if border is not None:
border_type = border.get('type', 'NONE')
width = border.get('width', '0.1 mm')
color = self._normalize_color(border.get('color', '#000000'))
data['borders'][side] = {
'type': border_type,
'type_name': LINE_TYPES.get(border_type, border_type),
'width': width,
'width_mm': self._parse_width(width),
'color': color
}
# 보이는 테두리만 색상 수집
if border_type != 'NONE':
if data['type'] == 'empty':
data['type'] = 'border_only'
if color and color not in result['colors']['border']:
result['colors']['border'].append(color)
# 특수 테두리 수집
if border_type not in ['SOLID', 'NONE']:
result['special_borders'].append({
'bf_id': bf_id,
'side': side,
'type': border_type,
'type_name': LINE_TYPES.get(border_type, border_type),
'width': width,
'color': color
})
return data
def _parse_section(self, section_path: Path, result: Dict):
"""section0.xml 파싱 - 표 구조"""
tree = ET.parse(section_path)
root = tree.getroot()
border_fills = result['border_fills']
for tbl in root.findall('.//{http://www.hancom.co.kr/hwpml/2011/paragraph}tbl'):
table_data = {
'rows': int(tbl.get('rowCnt', 0)),
'cols': int(tbl.get('colCnt', 0)),
'cells': [],
'structure': {
'header_row_style': None,
'first_col_style': None,
'body_style': None,
'has_image_cells': False
}
}
# 셀별 분석
cell_by_position = {}
for tc in tbl.findall('.//{http://www.hancom.co.kr/hwpml/2011/paragraph}tc'):
cell_addr = tc.find('{http://www.hancom.co.kr/hwpml/2011/paragraph}cellAddr')
if cell_addr is None:
continue
row = int(cell_addr.get('rowAddr', 0))
col = int(cell_addr.get('colAddr', 0))
bf_id = tc.get('borderFillIDRef')
bf_info = border_fills.get(bf_id, {})
# 텍스트 추출
text = ''
for t in tc.findall('.//{http://www.hancom.co.kr/hwpml/2011/paragraph}t'):
if t.text:
text += t.text
cell_data = {
'row': row,
'col': col,
'bf_id': bf_id,
'bf_type': bf_info.get('type'),
'background': bf_info.get('background'),
'image': bf_info.get('image'),
'text_preview': text[:30] if text else ''
}
table_data['cells'].append(cell_data)
cell_by_position[(row, col)] = cell_data
if bf_info.get('type') == 'image':
table_data['structure']['has_image_cells'] = True
# 구조 분석: 헤더행, 첫열 스타일
self._analyze_table_structure(table_data, cell_by_position, border_fills)
result['tables'].append(table_data)
def _analyze_table_structure(self, table_data: Dict, cells: Dict, border_fills: Dict):
"""표 구조 분석 - 헤더행/첫열 스타일 파악"""
rows = table_data['rows']
cols = table_data['cols']
if rows == 0 or cols == 0:
return
# 첫 행 (헤더) 분석
header_styles = []
for c in range(cols):
cell = cells.get((0, c))
if cell:
header_styles.append(cell.get('bf_id'))
if header_styles:
# 가장 많이 쓰인 스타일
most_common = Counter(header_styles).most_common(1)
if most_common:
bf_id = most_common[0][0]
bf = border_fills.get(bf_id)
if bf and bf.get('background'):
table_data['structure']['header_row_style'] = {
'bf_id': bf_id,
'background': bf.get('background'),
'borders': bf.get('borders', {})
}
# 첫 열 분석 (행 1부터)
first_col_styles = []
for r in range(1, rows):
cell = cells.get((r, 0))
if cell:
first_col_styles.append(cell.get('bf_id'))
if first_col_styles:
most_common = Counter(first_col_styles).most_common(1)
if most_common:
bf_id = most_common[0][0]
bf = border_fills.get(bf_id)
if bf and bf.get('background'):
table_data['structure']['first_col_style'] = {
'bf_id': bf_id,
'background': bf.get('background')
}
# 본문 셀 스타일 (첫열 제외)
body_styles = []
for r in range(1, rows):
for c in range(1, cols):
cell = cells.get((r, c))
if cell:
body_styles.append(cell.get('bf_id'))
if body_styles:
most_common = Counter(body_styles).most_common(1)
if most_common:
bf_id = most_common[0][0]
bf = border_fills.get(bf_id)
table_data['structure']['body_style'] = {
'bf_id': bf_id,
'background': bf.get('background') if bf else None
}
def _create_style_summary(self, result: Dict) -> Dict:
"""AI 프롬프트용 스타일 요약"""
summary = {
'폰트': list(result['fonts'].values())[:3],
'색상': {
'배경색': result['colors']['background'],
'테두리색': result['colors']['border']
},
'표_스타일': [],
'특수_테두리': []
}
# 표별 스타일 요약
for i, tbl in enumerate(result['tables']):
tbl_summary = {
'표번호': i + 1,
'크기': f"{tbl['rows']}× {tbl['cols']}",
'이미지셀': tbl['structure']['has_image_cells']
}
header = tbl['structure'].get('header_row_style')
if header:
tbl_summary['헤더행'] = f"배경={header.get('background')}"
first_col = tbl['structure'].get('first_col_style')
if first_col:
tbl_summary['첫열'] = f"배경={first_col.get('background')}"
body = tbl['structure'].get('body_style')
if body:
tbl_summary['본문'] = f"배경={body.get('background') or '없음'}"
summary['표_스타일'].append(tbl_summary)
# 특수 테두리 요약
seen = set()
for sb in result['special_borders']:
key = f"{sb['type_name']} {sb['width']} {sb['color']}"
if key not in seen:
seen.add(key)
summary['특수_테두리'].append(key)
return summary
def _generate_css(self, result: Dict) -> str:
"""CSS 생성 - 실제 구조 반영"""
fonts = list(result['fonts'].values())[:2]
font_family = f"'{fonts[0]}'" if fonts else "'맑은 고딕'"
bg_colors = result['colors']['background']
header_bg = bg_colors[0] if bg_colors else '#D6D6D6'
# 특수 테두리에서 2중선 찾기
double_border = None
for sb in result['special_borders']:
if 'DOUBLE' in sb['type']:
double_border = sb
break
css = f"""/* 템플릿 스타일 v3 - HWPX 구조 기반 */
@import url('https://fonts.googleapis.com/css2?family=Noto+Sans+KR:wght@300;400;500;700&display=swap');
:root {{
--font-primary: 'Noto Sans KR', {font_family}, sans-serif;
--color-header-bg: {header_bg};
--color-border: #000000;
}}
body {{
font-family: var(--font-primary);
font-size: 10pt;
line-height: 1.6;
color: #000000;
}}
.sheet {{
width: 210mm;
min-height: 297mm;
padding: 20mm;
margin: 10px auto;
background: white;
box-shadow: 0 0 10px rgba(0,0,0,0.1);
}}
@media print {{
.sheet {{ margin: 0; box-shadow: none; page-break-after: always; }}
}}
/* 표 기본 */
table {{
width: 100%;
border-collapse: collapse;
margin: 1em 0;
font-size: 9pt;
}}
th, td {{
border: 0.12mm solid var(--color-border);
padding: 6px 8px;
vertical-align: middle;
}}
/* 헤더 행 */
thead th, tr:first-child th, tr:first-child td {{
background-color: var(--color-header-bg);
font-weight: bold;
text-align: center;
}}
/* 첫 열 (구분 열) - 배경색 */
td:first-child {{
background-color: var(--color-header-bg);
text-align: center;
font-weight: 500;
}}
/* 본문 셀 - 배경 없음 */
td:not(:first-child) {{
background-color: transparent;
}}
/* 2중선 테두리 (헤더 하단) */
thead tr:last-child th,
thead tr:last-child td,
tr:first-child th,
tr:first-child td {{
border-bottom: 0.5mm double var(--color-border);
}}
"""
return css
# =========================================================================
# 유틸리티
# =========================================================================
def _normalize_color(self, color: str) -> str:
"""ARGB 8자리 → RGB 6자리"""
if not color or color == 'none':
return color
color = color.strip()
# #AARRGGBB → #RRGGBB
if color.startswith('#') and len(color) == 9:
return '#' + color[3:]
return color
def _parse_width(self, width_str: str) -> float:
"""너비 문자열 → mm"""
if not width_str:
return 0.1
try:
return float(width_str.split()[0])
except:
return 0.1
def _extract_features(self, data: Dict) -> List[str]:
"""특징 목록"""
features = []
fonts = list(data.get('fonts', {}).values())
if fonts:
features.append(f"폰트: {', '.join(fonts[:2])}")
bg_colors = data.get('colors', {}).get('background', [])
if bg_colors:
features.append(f"배경색: {', '.join(bg_colors[:2])}")
tables = data.get('tables', [])
if tables:
has_img = any(t['structure']['has_image_cells'] for t in tables)
if has_img:
features.append("이미지 배경 셀")
special = data.get('special_borders', [])
if special:
types = set(s['type_name'] for s in special)
features.append(f"특수 테두리: {', '.join(list(types)[:2])}")
return features if features else ['기본 템플릿']
def _analyze_fallback(self, ext: str) -> Dict:
"""HWP, PDF 기본 분석"""
return {
'version': 'v3',
'fonts': {'0': '맑은 고딕'},
'colors': {'background': [], 'border': ['#000000'], 'text': ['#000000']},
'border_fills': {},
'tables': [],
'special_borders': [],
'style_summary': {
'폰트': ['맑은 고딕'],
'색상': {'배경색': [], '테두리색': ['#000000']},
'표_스타일': [],
'특수_테두리': []
},
'css': self._get_default_css(),
'note': f'{ext} 파일은 기본 분석만 지원. HWPX 권장.'
}
def _get_default_css(self) -> str:
return """/* 기본 스타일 */
@import url('https://fonts.googleapis.com/css2?family=Noto+Sans+KR:wght@300;400;500;700&display=swap');
body { font-family: 'Noto Sans KR', sans-serif; font-size: 10pt; }
.sheet { width: 210mm; min-height: 297mm; padding: 20mm; margin: 10px auto; background: white; }
table { width: 100%; border-collapse: collapse; }
th, td { border: 0.5pt solid #000; padding: 8px; }
th { background: #D6D6D6; }
"""

View File

@@ -0,0 +1,28 @@
당신은 문서 템플릿 분석 전문가입니다.
주어진 HWPX/HWP/PDF 템플릿의 구조를 분석하여 다음 정보를 추출해주세요:
1. 제목 스타일 (H1~H6)
- 폰트명, 크기(pt), 굵기, 색상
- 정렬 방식
- 번호 체계 (제1장, 1.1, 가. 등)
2. 본문 스타일
- 기본 폰트, 크기, 줄간격
- 들여쓰기
3. 표 스타일
- 헤더 배경색
- 테두리 스타일 (선 두께, 색상)
- 이중선 사용 여부
4. 그림/캡션 스타일
- 캡션 위치 (상/하)
- 캡션 형식
5. 페이지 구성
- 표지 유무
- 목차 유무
- 머리말/꼬리말
분석 결과를 JSON 형식으로 출력해주세요.

File diff suppressed because it is too large Load Diff