-
Notifications
You must be signed in to change notification settings - Fork 2
/
ebook2site.py
126 lines (103 loc) · 2.89 KB
/
ebook2site.py
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
import re
import os
from os import path
import shutil
import sys
import subprocess as subp
import zipfile
from io import BytesIO
README_TMP = '''
# {title}
## 下载
### Docker
```
docker pull apachecn0/{docker_hub_name}
docker run -tid -p <port>:80 apachecn0/{docker_hub_name}
# 访问 http://localhost:{port} 查看文档
```
### PYPI
```
pip install {pip_name}
{pip_name} <port>
# 访问 http://localhost:{port} 查看文档
```
### NPM
```
npm install -g {npm_name}
{npm_name} <port>
# 访问 http://localhost:{port} 查看文档
```
'''
INDEX_HTML = '''
<html>
<head></head>
<body style="margin: 0;">
<iframe src='file.pdf' style='width: 100%; height: 100%; border: 0;'></iframe>
</body>
</html>
'''
numPinyinMap = {
'0': 'ling',
'1': 'yi',
'2': 'er',
'3': 'san',
'4': 'si',
'5': 'wu',
'6': 'liu',
'7': 'qi',
'8': 'ba',
'9': 'jiu',
}
def npm_filter_name(name):
name = re.sub(r'[^\w\-]', '-', name)
name = '-'.join(filter(None, name.split('-')))
def rep_func(m):
s = m.group()
return ''.join(numPinyinMap.get(ch, '') for ch in s)
name = re.sub(r'\d{2,}', rep_func, name)
return name
def main():
name = sys.argv[1]
fname = sys.argv[2]
dir = sys.argv[3] if len(sys.argv) > 3 else '.'
if not fname.endswith('.pdf') and \
not fname.endswith('.epub'):
print('请提供 PDF 或 EPUB')
return
proj_dir = path.join(dir, name)
os.mkdir(proj_dir)
if fname.endswith('.pdf'):
shutil.copy(fname, path.join(proj_dir, 'file.pdf'))
open(path.join(proj_dir, 'index.html'), 'w', encoding='utf8').write(INDEX_HTML)
else:
shutil.copy(fname, path.join(proj_dir, 'file.epub'))
zip = zipfile.ZipFile(BytesIO(open('epubjs-reader.zip', 'rb').read()))
for f in zip.namelist(): zip.extract(f, proj_dir)
zip.close()
title = path.basename(fname).replace('.pdf', '').replace('.epub', '')
npm_name = npm_filter_name(name)
README_MD = README_TMP \
.replace('{title}', title) \
.replace('{docker_hub_name}', name) \
.replace('{pip_name}', name) \
.replace('{npm_name}', npm_name)
open(path.join(proj_dir, 'README.md'), 'w', encoding='utf8').write(README_MD)
'''
if site in ['all', 'npm']:
subp.Popen(
f'nbp publish "{proj_dir}"',
shell=True,
).communicate()
if site in ['all', 'pip']:
subp.Popen(
f'pybp publish "{proj_dir}"',
shell=True,
).communicate()
if site in ['all', 'docker']:
subp.Popen(
f'python docker_pub.py "{proj_dir}"',
shell=True,
).communicate()
os.rmdir(proj_dir)
'''
if __name__ == '__main__': main()