-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathupload_to_google_docs.py
More file actions
281 lines (231 loc) · 8.14 KB
/
Copy pathupload_to_google_docs.py
File metadata and controls
281 lines (231 loc) · 8.14 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
"""
上传 Markdown 章节到 Google Docs
使用前准备:
1. 访问 https://console.cloud.google.com/
2. 创建新项目或选择现有项目
3. 启用 Google Docs API
4. 创建 OAuth 2.0 凭据(桌面应用)
5. 下载 credentials.json 放到脚本同目录
"""
import os
import re
from pathlib import Path
from google.auth.transport.requests import Request
from google.oauth2.credentials import Credentials
from google_auth_oauthlib.flow import InstalledAppFlow
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError
# Google API 权限范围
SCOPES = ['https://www.googleapis.com/auth/documents']
# 配置
CHAPTERS_DIR = Path(r"/Users/am/Downloads/1lllllll1lll1llll1l-main/PIL_Chapters")
DOCUMENT_ID = "15zlTTawHQXO-5EoYfFxJbJifKMj9jGTUL9Db8wcM7YA"
def get_credentials():
"""获取 Google API 认证"""
creds = None
# token.json 存储用户的访问和刷新令牌
if os.path.exists('token.json'):
creds = Credentials.from_authorized_user_file('token.json', SCOPES)
# 如果没有有效凭据,让用户登录
if not creds or not creds.valid:
if creds and creds.expired and creds.refresh_token:
creds.refresh(Request())
else:
flow = InstalledAppFlow.from_client_secrets_file(
'credentials.json', SCOPES)
creds = flow.run_local_server(port=0)
# 保存凭据供下次使用
with open('token.json', 'w') as token:
token.write(creds.to_json())
return creds
def parse_markdown(md_file):
"""
解析 Markdown 文件
返回格式:[
{'type': 'heading1', 'text': '1.1 Introduction'},
{'type': 'paragraph', 'text': 'Public international law is...'},
{'type': 'heading2', 'text': '1.2.1 Historical context'},
]
"""
with open(md_file, 'r', encoding='utf-8') as f:
content = f.read()
elements = []
for block in content.split('\n\n'):
block = block.strip()
if not block:
continue
# 识别 Markdown 标题
heading_match = re.match(r'^(#{1,6})\s+(.+)$', block)
if heading_match:
level = len(heading_match.group(1)) # # 的数量
text = heading_match.group(2)
elements.append({
'type': f'heading{level}',
'text': text
})
else:
# 普通段落
elements.append({
'type': 'paragraph',
'text': block
})
return elements
def create_google_docs_requests(elements, start_index=1):
"""
生成 Google Docs API 请求
"""
requests = []
current_index = start_index
for element in elements:
text = element['text'] + '\n'
# 插入文本
requests.append({
'insertText': {
'location': {'index': current_index},
'text': text
}
})
# 应用样式
style = element['type']
if style.startswith('heading'):
# Heading 1, Heading 2, etc.
level = int(style.replace('heading', ''))
named_style = f'HEADING_{level}'
else:
named_style = 'NORMAL_TEXT'
requests.append({
'updateParagraphStyle': {
'range': {
'startIndex': current_index,
'endIndex': current_index + len(text)
},
'paragraphStyle': {
'namedStyleType': named_style
},
'fields': 'namedStyleType'
}
})
current_index += len(text)
return requests
def create_new_tab(service, document_id, tab_title):
"""创建新的标签页(Tab)"""
# 注意:Google Docs API 不直接支持 "tabs"
# 我们需要用其他方法:在文档末尾添加分页符和标题
# 获取文档当前长度
doc = service.documents().get(documentId=document_id).execute()
content = doc.get('body').get('content')
end_index = content[-1].get('endIndex') - 1
# 添加分页符
requests = [
{
'insertPageBreak': {
'location': {'index': end_index}
}
},
{
'insertText': {
'location': {'index': end_index + 1},
'text': f'\n{tab_title}\n\n'
}
},
{
'updateParagraphStyle': {
'range': {
'startIndex': end_index + 1,
'endIndex': end_index + len(tab_title) + 3
},
'paragraphStyle': {
'namedStyleType': 'TITLE'
},
'fields': 'namedStyleType'
}
}
]
result = service.documents().batchUpdate(
documentId=document_id,
body={'requests': requests}
).execute()
return end_index + len(tab_title) + 3
def upload_chapter(service, document_id, md_file, chapter_name):
"""上传单个章节"""
print(f"\n📄 处理:{md_file.name}")
# 解析 Markdown
elements = parse_markdown(md_file)
print(f" • 解析出 {len(elements)} 个元素")
# 创建新标签页
print(f" • 创建标签页:{chapter_name}")
start_index = create_new_tab(service, document_id, chapter_name)
# 生成插入请求
requests = create_google_docs_requests(elements, start_index)
# 批量更新(Google API 限制每次最多500个请求)
batch_size = 500
for i in range(0, len(requests), batch_size):
batch = requests[i:i + batch_size]
try:
service.documents().batchUpdate(
documentId=document_id,
body={'requests': batch}
).execute()
print(f" • 上传批次 {i//batch_size + 1}/{(len(requests)-1)//batch_size + 1}")
except HttpError as error:
print(f" ❌ 错误:{error}")
return False
print(f" ✓ 完成!")
return True
def main():
print(f"\n{'='*70}")
print("📚 上传 PIL 章节到 Google Docs")
print(f"{'='*70}\n")
# 检查目录
if not CHAPTERS_DIR.exists():
print(f"❌ 错误:找不到目录 {CHAPTERS_DIR}")
return
# 获取所有 Markdown 文件
md_files = sorted(CHAPTERS_DIR.glob("Chapter_*.md"))
print(f"📁 找到 {len(md_files)} 个章节文件\n")
if not md_files:
print("❌ 没有找到任何 Markdown 文件")
return
# 认证
print("🔐 Google API 认证中...")
try:
creds = get_credentials()
service = build('docs', 'v1', credentials=creds)
print("✓ 认证成功\n")
except Exception as e:
print(f"❌ 认证失败:{e}")
print("\n请确保:")
print("1. credentials.json 文件在当前目录")
print("2. 已启用 Google Docs API")
return
# 确认操作
print(f"📄 目标文档:https://docs.google.com/document/d/{DOCUMENT_ID}/edit")
print(f"\n⚠️ 将上传 {len(md_files)} 个章节到该文档")
confirm = input("\n继续?(y/n): ")
if confirm.lower() != 'y':
print("❌ 已取消")
return
# 上传每个章节
print(f"\n{'='*70}")
print("开始上传...")
print(f"{'='*70}")
success_count = 0
for md_file in md_files:
# 提取章节名称
match = re.match(r'Chapter_(\d+)_(.+)\.md', md_file.name)
if match:
chapter_num = match.group(1)
chapter_name = f"Chapter {chapter_num}"
else:
chapter_name = md_file.stem
if upload_chapter(service, DOCUMENT_ID, md_file, chapter_name):
success_count += 1
# 总结
print(f"\n{'='*70}")
print(f"✅ 完成!")
print(f"{'='*70}")
print(f"成功上传:{success_count}/{len(md_files)} 章节")
print(f"\n查看文档:https://docs.google.com/document/d/{DOCUMENT_ID}/edit")
print(f"{'='*70}\n")
if __name__ == '__main__':
main()