-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathutils.py
More file actions
297 lines (257 loc) · 12.6 KB
/
Copy pathutils.py
File metadata and controls
297 lines (257 loc) · 12.6 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
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
"""
유틸리티 함수들
"""
import json
import re
import logging
from typing import Dict, Any, Optional, List
logger = logging.getLogger(__name__)
def extract_json_from_response(response_content: str) -> Optional[Dict[str, Any]]:
"""AI 응답에서 JSON 추출 및 파싱"""
try:
# JSON 블록 찾기
json_match = re.search(r'```json\s*(.*?)\s*```', response_content, re.DOTALL)
if json_match:
json_str = json_match.group(1).strip()
return json.loads(json_str)
# JSON 블록이 없다면 응답 내 임의 위치에서 JSON 구조 추출 시도
decoder = json.JSONDecoder()
content = response_content.strip()
# 전체 문자열이 JSON일 수 있으므로 먼저 시도
try:
return json.loads(content)
except json.JSONDecodeError:
pass
# 텍스트 중간에 포함된 첫 번째 JSON 객체 탐색
for match in re.finditer(r'[{\[]', content):
start = match.start()
try:
obj, _ = decoder.raw_decode(content[start:])
return obj
except json.JSONDecodeError:
continue
logger.warning(f"JSON 블록을 찾을 수 없습니다: {content[:100]}...")
return None
except json.JSONDecodeError as e:
logger.error(f"JSON 파싱 실패: {e}")
return None
except Exception as e:
logger.error(f"JSON 추출 중 오류: {e}")
return None
def validate_json_schema(data: Dict[str, Any], required_fields: List[str]) -> bool:
"""JSON 스키마 기본 검증"""
try:
for field in required_fields:
if field not in data:
logger.warning(f"필수 필드 누락: {field}")
return False
return True
except Exception as e:
logger.error(f"스키마 검증 오류: {e}")
return False
def format_search_results(results: List[Dict]) -> str:
"""벡터 검색 결과를 포맷팅"""
if not results:
return "관련 정보 없음"
formatted = []
for result in results:
formatted.append(f"- {result.get('rule_name', 'Unknown')} ({result.get('rule_type', 'Unknown')})")
formatted.append(f" 카테고리: {result.get('category', 'Unknown')}")
content = result.get('content', '')
if len(content) > 150:
content = content[:150] + "..."
formatted.append(f" 내용: {content}")
return "\n".join(formatted)
def generate_simple_rule_description(rule: Dict) -> str:
"""규칙에 대한 간단한 설명 생성 (새 JSON 형식 지원)"""
try:
conditions_desc = []
actions_desc = []
# 조건 설명 생성
for condition in rule.get("conditions", []):
condition_type = condition.get("condition_type", "")
details = condition.get("condition_details", {})
is_negated = condition.get("is_negated", False)
if condition_type == "name":
pattern = details.get("pattern", "")
match_type = details.get("match_type", "")
if match_type == "contains":
desc = f"파일명에 '{pattern}'이 포함된 파일"
elif match_type == "starts_with":
desc = f"'{pattern}'로 시작하는 파일"
elif match_type == "ends_with":
desc = f"'{pattern}'로 끝나는 파일"
elif match_type == "is":
desc = f"파일명이 '{pattern}'인 파일"
elif match_type == "regex":
desc = f"파일명이 정규식 '{pattern}'과 일치하는 파일"
else:
desc = f"파일명 조건: {pattern}"
elif condition_type == "extension":
extensions = details.get("extensions", [])
groups = details.get("groups", [])
group_overrides = details.get("group_overrides", {})
# 기본 설명 생성
desc_parts = []
if extensions:
desc_parts.append(f"{', '.join(extensions)}")
if groups:
desc_parts.append(f"{', '.join(groups)}")
# group_overrides 처리
if group_overrides:
override_desc = []
for group_name, overrides in group_overrides.items():
removed = overrides.get("removed", [])
added = overrides.get("added", [])
if removed and added:
override_desc.append(f"{group_name}에서 {', '.join(removed)} 제외, {', '.join(added)} 추가")
elif removed:
override_desc.append(f"{group_name}에서 {', '.join(removed)} 제외")
elif added:
override_desc.append(f"{group_name}에 {', '.join(added)} 추가")
if override_desc:
desc_parts.append(f"({'; '.join(override_desc)})")
if desc_parts:
desc = f"{' '.join(desc_parts)} 파일"
else:
desc = "확장자 조건"
elif condition_type == "date":
date_type = details.get("date_type", "created")
condition_type_detail = details.get("condition_type", "")
if condition_type_detail == "within_last":
value = details.get("value", "")
unit = details.get("unit", "")
desc = f"최근 {value}{unit} 내에 {date_type}된 파일"
elif condition_type_detail == "after":
target_date = details.get("target_date", "")
desc = f"{target_date} 이후에 {date_type}된 파일"
elif condition_type_detail == "before":
target_date = details.get("target_date", "")
desc = f"{target_date} 이전에 {date_type}된 파일"
else:
desc = f"{date_type} 날짜 조건"
elif condition_type == "size":
operator = details.get("operator", "")
value = details.get("value", "")
unit = details.get("unit", "")
max_value = details.get("max_value")
if operator == "greater_than":
desc = f"크기가 {value}{unit}보다 큰 파일"
elif operator == "less_than":
desc = f"크기가 {value}{unit}보다 작은 파일"
elif operator == "equal_to":
desc = f"크기가 {value}{unit}인 파일"
elif operator == "between" and max_value:
desc = f"크기가 {value}{unit}~{max_value}{unit} 사이인 파일"
else:
desc = f"크기 조건: {value}{unit}"
elif condition_type == "tag":
tags = details.get("tags", [])
tag_names = [tag.get("name", tag.get("color", "")) for tag in tags if tag.get("name") or tag.get("color")]
if tag_names:
desc = f"태그가 '{', '.join(tag_names)}'인 파일"
else:
desc = "태그 조건"
elif condition_type == "any_file":
desc = "모든 파일"
else:
desc = f"{condition_type} 조건"
# 부정 조건 처리
if is_negated:
desc = f"{desc}를 제외한 파일"
conditions_desc.append(desc)
# 액션 설명 생성
for action in rule.get("actions", []):
action_type = action.get("action_type", "")
details = action.get("action_details", {})
if action_type == "move":
destination = details.get("destination", "")
actions_desc.append(f"'{destination}' 폴더로 이동")
elif action_type == "copy":
destination = details.get("destination", "")
actions_desc.append(f"'{destination}' 폴더로 복사")
elif action_type == "make_alias":
destination = details.get("destination", "")
actions_desc.append(f"'{destination}' 폴더에 별칭 생성")
elif action_type == "delete":
mode = details.get("mode", "")
if mode == "trash":
actions_desc.append("휴지통으로 이동")
elif mode == "permanent":
actions_desc.append("완전 삭제")
else:
actions_desc.append("삭제")
elif action_type == "rename":
mode = details.get("mode", "")
if mode == "prefix_add":
prefix = details.get("prefix", "")
actions_desc.append(f"파일명 앞에 '{prefix}' 추가")
elif mode == "suffix_add":
suffix = details.get("suffix", "")
actions_desc.append(f"파일명 뒤에 '{suffix}' 추가")
else:
actions_desc.append(f"이름 변경 ({mode})")
elif action_type == "sort_into_date":
folder_structure = details.get("folder_structure", "")
actions_desc.append(f"날짜별 폴더로 정리 ({folder_structure})")
elif action_type == "sort_into_kind":
selected_kinds = details.get("selected_kinds", [])
if selected_kinds:
actions_desc.append(f"종류별 폴더로 정리 ({', '.join(selected_kinds)})")
else:
actions_desc.append("종류별 폴더로 정리")
elif action_type == "tags":
action_type_detail = details.get("action_type", "")
tags = details.get("tags", [])
if action_type_detail == "add" and tags:
tag_names = [tag.get("name", "") for tag in tags if tag.get("name")]
actions_desc.append(f"태그 '{', '.join(tag_names)}' 추가")
elif action_type_detail == "delete":
actions_desc.append("태그 삭제")
else:
actions_desc.append("태그 작업")
elif action_type == "comment":
action_type_detail = details.get("action_type", "")
if action_type_detail == "add":
actions_desc.append("주석 추가")
elif action_type_detail == "delete":
actions_desc.append("주석 삭제")
else:
actions_desc.append("주석 작업")
else:
actions_desc.append(f"{action_type} 작업")
# 최종 설명 생성
condition_text = " 그리고 ".join(conditions_desc) if conditions_desc else "모든 파일"
action_text = " 그리고 ".join(actions_desc) if actions_desc else "작업"
return f"{condition_text}에 대해 {action_text}을 수행합니다."
except Exception as e:
logger.error(f"규칙 설명 생성 오류: {e}")
return "파일 자동화 규칙이 생성되었습니다."
def check_requires_destination(rule: Dict[str, Any]) -> bool:
"""규칙의 액션들이 목적지를 필요로 하는지 확인 (새 형식 지원)"""
try:
from schema_definitions import ACTION_SCHEMAS
actions = rule.get("actions", [])
if not actions:
return False
# 하나라도 목적지가 필요한 액션이 있으면 True
for action in actions:
action_type = action.get("action_type", "")
# 새 스키마에서 requires_destination 확인
schema = ACTION_SCHEMAS.get(action_type, {})
if schema.get("requires_destination", False):
return True
return False
except Exception as e:
logger.error(f"requires_destination 확인 오류: {e}")
return False
def setup_logging():
"""로깅 설정"""
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
handlers=[
logging.FileHandler('filient.log'),
logging.StreamHandler()
]
)