Update file_api.py
Browse files- file_api.py +38 -0
file_api.py
CHANGED
|
@@ -403,8 +403,46 @@ def download_file(url: str, save_dir: str, hint_filename: str = None) -> Tuple[O
|
|
| 403 |
filename = f"document_{hash(url) % 10000}.hwp"
|
| 404 |
else:
|
| 405 |
filename = f"file_{hash(url) % 10000}.bin"
|
|
|
|
|
|
|
|
|
|
| 406 |
filename = re.sub(r'[<>:"/\\|?*]', '_', filename)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 407 |
file_path = os.path.join(save_dir, filename)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 408 |
with open(file_path, 'wb') as f:
|
| 409 |
for chunk in response.iter_content(chunk_size=8192):
|
| 410 |
if chunk:
|
|
|
|
| 403 |
filename = f"document_{hash(url) % 10000}.hwp"
|
| 404 |
else:
|
| 405 |
filename = f"file_{hash(url) % 10000}.bin"
|
| 406 |
+
|
| 407 |
+
# ⭐ 파일명 정리 (인코딩 문제 해결)
|
| 408 |
+
# 1. 특수문자 제거
|
| 409 |
filename = re.sub(r'[<>:"/\\|?*]', '_', filename)
|
| 410 |
+
|
| 411 |
+
# 2. 파일명이 너무 길면 축약 (확장자 보존)
|
| 412 |
+
name_part, ext = os.path.splitext(filename)
|
| 413 |
+
if not ext:
|
| 414 |
+
# 확장자가 없으면 Content-Type에서 추측
|
| 415 |
+
content_type = response.headers.get('Content-Type', '').lower()
|
| 416 |
+
if 'pdf' in content_type:
|
| 417 |
+
ext = '.pdf'
|
| 418 |
+
elif 'hwp' in content_type:
|
| 419 |
+
ext = '.hwp'
|
| 420 |
+
else:
|
| 421 |
+
ext = '.bin'
|
| 422 |
+
|
| 423 |
+
# 3. 파일명 최대 길이 제한 (100자)
|
| 424 |
+
max_name_len = 100 - len(ext)
|
| 425 |
+
if len(name_part) > max_name_len:
|
| 426 |
+
# 앞 50자 + 해시 + 뒤 30자
|
| 427 |
+
name_hash = f"_{hash(name_part) % 10000:04d}_"
|
| 428 |
+
name_part = name_part[:50] + name_hash + name_part[-30:]
|
| 429 |
+
|
| 430 |
+
filename = name_part + ext
|
| 431 |
+
|
| 432 |
+
# 4. 안전한 ASCII 파일명 생성 (인코딩 문제 방지)
|
| 433 |
+
try:
|
| 434 |
+
filename.encode('utf-8')
|
| 435 |
+
except UnicodeEncodeError:
|
| 436 |
+
# 인코딩 문제 시 해시 기반 파일명 사용
|
| 437 |
+
filename = f"document_{hash(url) % 100000}{ext}"
|
| 438 |
+
|
| 439 |
file_path = os.path.join(save_dir, filename)
|
| 440 |
+
|
| 441 |
+
# 5. 최종 경로 길이 확인
|
| 442 |
+
if len(file_path) > 250:
|
| 443 |
+
filename = f"doc_{hash(url) % 100000}{ext}"
|
| 444 |
+
file_path = os.path.join(save_dir, filename)
|
| 445 |
+
|
| 446 |
with open(file_path, 'wb') as f:
|
| 447 |
for chunk in response.iter_content(chunk_size=8192):
|
| 448 |
if chunk:
|