-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrequirement_classifier.py
More file actions
213 lines (173 loc) · 7.59 KB
/
requirement_classifier.py
File metadata and controls
213 lines (173 loc) · 7.59 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
"""
코드 ID: REQ_CLASSIFIER_001
연결 요구사항: AI-REQ-F-001 (문서 분석 및 요구사항 자동 추출)
작성자: AI System
작성일: 2025-09-01
설명: 추출된 요구사항을 기능/비기능으로 분류하는 모듈
"""
import re
from typing import List, Dict, Tuple
from enum import Enum
import logging
from dataclasses import dataclass
# 코드 ID: REQ_CLASSIFIER_001
class RequirementType(Enum):
FUNCTIONAL = "기능"
NON_FUNCTIONAL = "비기능"
CONSTRAINT = "제약사항"
class RequirementPriority(Enum):
HIGH = "상"
MEDIUM = "중"
LOW = "하"
@dataclass
class ClassificationResult:
"""분류 결과 데이터 클래스"""
requirement_id: str
text: str
type: RequirementType
priority: RequirementPriority
category: str
subcategory: str
confidence: float
reasoning: str
class RequirementClassifier:
"""
요구사항 분류 클래스
- 기능/비기능 요구사항 구분
- 우선순위 및 카테고리 분류
- 요구사항 ID: AI-REQ-F-001과 연결
"""
def __init__(self):
self.logger = logging.getLogger(__name__)
# 기능 요구사항 키워드
self.functional_keywords = [
'로그인', '저장', '조회', '수정', '삭제', '생성', '처리', '계산',
'전송', '수신', '출력', '입력', '검색', '정렬', '필터링'
]
# 비기능 요구사항 키워드
self.non_functional_keywords = [
'성능', '속도', '응답시간', '처리량', '보안', '안정성', '가용성',
'확장성', '유지보수', '사용성', '호환성', '이식성'
]
# 카테고리 분류 규칙
self.category_patterns = {
'사용자 관리': ['사용자', '로그인', '인증', '권한', '계정'],
'데이터 관리': ['데이터', '저장', '조회', '수정', '삭제', 'DB'],
'인터페이스': ['화면', 'UI', 'API', '인터페이스', '연동'],
'보안': ['보안', '암호화', '인증', '권한', '접근제어'],
'성능': ['성능', '속도', '응답시간', '처리량', '최적화']
}
def classify_requirement(self, requirement_text: str, requirement_id: str = "") -> ClassificationResult:
"""
단일 요구사항 분류
Args:
requirement_text (str): 요구사항 텍스트
requirement_id (str): 요구사항 ID
Returns:
ClassificationResult: 분류 결과
"""
# 타입 분류
req_type, type_confidence, type_reasoning = self._classify_type(requirement_text)
# 우선순위 분류
priority, priority_reasoning = self._classify_priority(requirement_text)
# 카테고리 분류
category, subcategory, category_reasoning = self._classify_category(requirement_text)
# 전체 신뢰도 계산
overall_confidence = type_confidence * 0.6 + 0.4 # 기본 신뢰도 추가
return ClassificationResult(
requirement_id=requirement_id,
text=requirement_text,
type=req_type,
priority=priority,
category=category,
subcategory=subcategory,
confidence=overall_confidence,
reasoning=f"타입: {type_reasoning}, 우선순위: {priority_reasoning}, 카테고리: {category_reasoning}"
)
def _classify_type(self, text: str) -> Tuple[RequirementType, float, str]:
"""요구사항 타입 분류"""
functional_score = 0
non_functional_score = 0
text_lower = text.lower()
# 기능 요구사항 키워드 매칭
for keyword in self.functional_keywords:
if keyword in text_lower:
functional_score += 1
# 비기능 요구사항 키워드 매칭
for keyword in self.non_functional_keywords:
if keyword in text_lower:
non_functional_score += 1
# 패턴 기반 분류
if re.search(r'.*는.*할\s+수\s+있다', text):
functional_score += 2
if re.search(r'성능|품질|속도', text):
non_functional_score += 2
# 제약사항 패턴
if re.search(r'제약|한계|조건', text):
return RequirementType.CONSTRAINT, 0.7, "제약사항 키워드 발견"
# 점수 비교
if functional_score > non_functional_score:
confidence = min(0.9, 0.5 + functional_score * 0.1)
return RequirementType.FUNCTIONAL, confidence, f"기능 키워드 {functional_score}개 매칭"
elif non_functional_score > functional_score:
confidence = min(0.9, 0.5 + non_functional_score * 0.1)
return RequirementType.NON_FUNCTIONAL, confidence, f"비기능 키워드 {non_functional_score}개 매칭"
else:
# 기본값: 기능 요구사항
return RequirementType.FUNCTIONAL, 0.5, "기본 분류 (기능)"
def _classify_priority(self, text: str) -> Tuple[RequirementPriority, str]:
"""요구사항 우선순위 분류"""
high_priority_keywords = ['필수', '중요', '핵심', '반드시', '우선']
low_priority_keywords = ['선택', '부가', '추가', '향후', '개선']
text_lower = text.lower()
for keyword in high_priority_keywords:
if keyword in text_lower:
return RequirementPriority.HIGH, f"고우선순위 키워드 '{keyword}' 발견"
for keyword in low_priority_keywords:
if keyword in text_lower:
return RequirementPriority.LOW, f"저우선순위 키워드 '{keyword}' 발견"
# 문장 길이 기반 우선순위 (긴 문장은 상세한 요구사항일 가능성)
if len(text) > 100:
return RequirementPriority.HIGH, "상세한 요구사항 (길이 기반)"
elif len(text) < 30:
return RequirementPriority.LOW, "간단한 요구사항 (길이 기반)"
else:
return RequirementPriority.MEDIUM, "기본 우선순위"
def _classify_category(self, text: str) -> Tuple[str, str, str]:
"""요구사항 카테고리 분류"""
text_lower = text.lower()
max_score = 0
best_category = "일반"
matching_keywords = []
for category, keywords in self.category_patterns.items():
score = 0
matched = []
for keyword in keywords:
if keyword in text_lower:
score += 1
matched.append(keyword)
if score > max_score:
max_score = score
best_category = category
matching_keywords = matched
# 서브카테고리는 첫 번째 매칭 키워드로 설정
subcategory = matching_keywords[0] if matching_keywords else "기타"
reasoning = f"키워드 매칭: {matching_keywords}" if matching_keywords else "기본 분류"
return best_category, subcategory, reasoning
def classify_batch(self, requirements: List[Dict[str, str]]) -> List[ClassificationResult]:
"""
여러 요구사항 일괄 분류
Args:
requirements: 요구사항 리스트 [{"id": "REQ-001", "text": "..."}]
Returns:
List[ClassificationResult]: 분류 결과 리스트
"""
results = []
for req in requirements:
result = self.classify_requirement(
req.get('text', ''),
req.get('id', '')
)
results.append(result)
self.logger.info(f"요구사항 {len(results)}개 분류 완료")
return results