-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathword_to_html_converter.py
More file actions
106 lines (84 loc) · 3.67 KB
/
word_to_html_converter.py
File metadata and controls
106 lines (84 loc) · 3.67 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
import io
import os
from typing import Tuple, Optional
from google.oauth2 import service_account
from googleapiclient.discovery import build
from googleapiclient.http import MediaFileUpload, MediaIoBaseDownload
from constants import TEMP_DIR
from utils import get_resource_path
def convert(word_path):
converter = WordToHtmlConverter()
success, path = converter.convert(word_path)
if not success or not path:
raise ValueError("Ошибка конвертации")
return path
SERVICE_ACCOUNT_PATH = get_resource_path("service_account.json")
class WordToHtmlConverter:
"""
Конвертер Word в HTML+ZIP
Сохраняет точное оригинальное имя для всех файлов
"""
def __init__(self, service_account_file: str = SERVICE_ACCOUNT_PATH):
if not os.path.exists(service_account_file):
raise FileNotFoundError(f"Конфиг файл сервисного аккаунта google не найден: {service_account_file}")
self.SERVICE_ACCOUNT_FILE = service_account_file
self.creds = None
self.drive_service = None
def convert(self, word_path) -> Tuple[bool, Optional[str]]:
try:
original_name = os.path.splitext(os.path.basename(word_path))[0]
output_zip = TEMP_DIR / f"{original_name}.zip"
if self._convert_to_zip(word_path, output_zip, original_name):
print(f"✅ Конвертация прошла успешно. Файл сохранён: {output_zip}")
return True, output_zip
print("❌ Конвертация не удалась.")
return False, None
except Exception as e:
print(f"❌ Ошибка: {e}")
return False, None
def _convert_to_zip(self, word_path: str, output_zip: str, original_name: str) -> bool:
if not self._authenticate():
print("Ошибка аутентификации Google Drive")
return False
try:
file_metadata = {
'name': original_name,
'mimeType': 'application/vnd.google-apps.document'
}
media = MediaFileUpload(
word_path,
mimetype='application/vnd.openxmlformats-officedocument.wordprocessingml.document'
)
file = self.drive_service.files().create(
body=file_metadata,
media_body=media,
fields='id'
).execute()
file_id = file['id']
with io.FileIO(output_zip, 'wb') as fh:
downloader = MediaIoBaseDownload(
fh,
self.drive_service.files().export_media(
fileId=file_id,
mimeType='application/zip'
)
)
while not downloader.next_chunk()[1]:
pass
self.drive_service.files().delete(fileId=file_id).execute()
return True
except Exception as e:
print(f"Ошибка конвертации: {e}")
return False
def _authenticate(self) -> bool:
"""Аутентификация в Google Drive API"""
try:
self.creds = service_account.Credentials.from_service_account_file(
self.SERVICE_ACCOUNT_FILE,
scopes=['https://www.googleapis.com/auth/drive.file']
)
self.drive_service = build('drive', 'v3', credentials=self.creds)
return True
except Exception as e:
print(f"Ошибка аутентификации: {e}")
return False