-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBlogGenerator.py
More file actions
567 lines (488 loc) · 21.8 KB
/
Copy pathBlogGenerator.py
File metadata and controls
567 lines (488 loc) · 21.8 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
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
"""
Blog Generator - Fully Working Version
Converts Markdown files to HTML blog
Author: Python Learning Project
"""
import os
import shutil
from pathlib import Path
from datetime import datetime
import sys
import argparse
try:
import markdown
except ImportError:
print("❌ Please install markdown library: pip install markdown")
sys.exit(1)
class BlogGenerator:
"""Static blog generator from Markdown files"""
def __init__(self, content_dir="content", output_dir="output"):
self.content_dir = Path(content_dir)
self.output_dir = Path(output_dir)
self.posts = []
self.tags = {}
# Create directories
self.content_dir.mkdir(exist_ok=True)
self.output_dir.mkdir(exist_ok=True)
(self.output_dir / "posts").mkdir(exist_ok=True)
(self.output_dir / "tags").mkdir(exist_ok=True)
def parse_post(self, content):
"""Parse markdown post with frontmatter"""
metadata = {
'title': 'Untitled',
'date': datetime.now(),
'tags': '',
'excerpt': ''
}
# Check for frontmatter
if content.startswith('---'):
parts = content.split('---', 2)
if len(parts) >= 3:
frontmatter = parts[1].strip()
content = parts[2].strip()
for line in frontmatter.split('\n'):
if ':' in line:
key, value = line.split(':', 1)
key = key.strip()
value = value.strip()
if key == 'title':
metadata['title'] = value
elif key == 'date':
try:
metadata['date'] = datetime.strptime(value, '%Y-%m-%d')
except:
pass
elif key == 'tags':
metadata['tags'] = value
elif key == 'excerpt':
metadata['excerpt'] = value
# Convert markdown to HTML
html_content = markdown.markdown(content, extensions=['fenced_code', 'tables'])
return metadata, html_content
def load_posts(self):
"""Load all markdown posts"""
self.posts = []
self.tags = {}
md_files = list(self.content_dir.glob("*.md"))
if not md_files:
return
for file_path in md_files:
with open(file_path, 'r', encoding='utf-8') as f:
content = f.read()
metadata, html_content = self.parse_post(content)
# Get tags as list
tags_list = [t.strip() for t in metadata['tags'].split(',')] if metadata['tags'] else []
post = {
'filename': file_path.stem,
'title': metadata['title'],
'date': metadata['date'],
'date_str': metadata['date'].strftime('%B %d, %Y'),
'tags': tags_list,
'tags_str': metadata['tags'],
'excerpt': metadata['excerpt'] or html_content[:150].replace('\n', ' ') + '...',
'content': html_content,
}
self.posts.append(post)
# Update tags
for tag in tags_list:
if tag:
if tag not in self.tags:
self.tags[tag] = []
self.tags[tag].append(post)
# Sort posts by date (newest first)
self.posts.sort(key=lambda x: x['date'], reverse=True)
def generate_homepage(self):
"""Generate homepage"""
html = '''<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>My Blog</title>
<style>
* { margin: 0; padding: 0; box-sizing: border-box; }
body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Arial, sans-serif; line-height: 1.6; color: #333; background: #f5f5f5; }
.container { max-width: 1000px; margin: 0 auto; padding: 20px; }
header { background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; padding: 60px 0; text-align: center; margin-bottom: 40px; }
header h1 { font-size: 3em; margin-bottom: 10px; }
header p { font-size: 1.2em; opacity: 0.9; }
nav { background: white; padding: 15px; border-radius: 8px; margin-bottom: 30px; box-shadow: 0 2px 4px rgba(0,0,0,0.1); text-align: center; }
nav a { color: #667eea; text-decoration: none; margin: 0 15px; font-weight: 500; }
nav a:hover { text-decoration: underline; }
.post-card { background: white; border-radius: 8px; padding: 25px; margin-bottom: 25px; box-shadow: 0 2px 4px rgba(0,0,0,0.1); transition: transform 0.2s; }
.post-card:hover { transform: translateY(-3px); box-shadow: 0 4px 8px rgba(0,0,0,0.15); }
.post-title { margin-bottom: 10px; }
.post-title a { color: #333; text-decoration: none; }
.post-title a:hover { color: #667eea; }
.post-meta { color: #666; font-size: 0.9em; margin-bottom: 15px; }
.post-excerpt { color: #555; margin-bottom: 15px; }
.post-tags { margin-top: 15px; }
.tag { display: inline-block; background: #e0e7ff; color: #667eea; padding: 4px 10px; border-radius: 20px; font-size: 0.8em; margin-right: 8px; text-decoration: none; }
.tag:hover { background: #667eea; color: white; }
.sidebar { background: white; padding: 20px; border-radius: 8px; margin-bottom: 25px; }
.sidebar h3 { margin-bottom: 15px; color: #667eea; }
.tag-cloud { display: flex; flex-wrap: wrap; gap: 10px; }
.tag-cloud a { background: #f0f0f0; padding: 5px 12px; border-radius: 20px; text-decoration: none; color: #666; font-size: 0.9em; }
.tag-cloud a:hover { background: #667eea; color: white; }
.flex { display: flex; gap: 30px; }
.main { flex: 2; }
.side { flex: 1; }
footer { text-align: center; padding: 40px 0; color: #666; margin-top: 40px; border-top: 1px solid #ddd; }
@media (max-width: 768px) { .flex { flex-direction: column; } header h1 { font-size: 2em; } }
</style>
</head>
<body>
<header>
<div class="container">
<h1>My Python Blog</h1>
<p>A blog generated with Python</p>
</div>
</header>
<div class="container">
<nav>
<a href="/">Home</a>
<a href="/archive.html">Archive</a>
<a href="/tags.html">Tags</a>
</nav>
<div class="flex">
<div class="main">
'''
for post in self.posts[:10]:
tags_html = " ".join([f'<a href="/tags/{tag}.html" class="tag">#{tag}</a>' for tag in post['tags'] if tag])
html += f'''
<div class="post-card">
<h2 class="post-title"><a href="/posts/{post['filename']}.html">{post['title']}</a></h2>
<div class="post-meta">📅 {post['date_str']} | 🏷️ {post['tags_str'] if post['tags_str'] else 'No tags'}</div>
<div class="post-excerpt">{post['excerpt']}</div>
<div class="post-tags">{tags_html}</div>
</div>
'''
# Sidebar
tag_cloud = ""
for tag in sorted(self.tags.keys()):
tag_cloud += f'<a href="/tags/{tag}.html" class="tag">#{tag} ({len(self.tags[tag])})</a>'
html += f'''
</div>
<div class="side">
<div class="sidebar">
<h3>📊 Statistics</h3>
<p>📝 Total Posts: {len(self.posts)}</p>
<p>🏷️ Total Tags: {len(self.tags)}</p>
</div>
<div class="sidebar">
<h3>🏷️ Tag Cloud</h3>
<div class="tag-cloud">{tag_cloud}</div>
</div>
</div>
</div>
<footer>
<p>© {datetime.now().year} My Python Blog. Generated with Python Blog Generator</p>
</footer>
</div>
</body>
</html>'''
with open(self.output_dir / "index.html", 'w', encoding='utf-8') as f:
f.write(html)
print(" ✅ Generated: index.html")
def generate_post_pages(self):
"""Generate individual post pages"""
for post in self.posts:
tags_display = ", ".join([f'#{tag}' for tag in post['tags'] if tag]) if post['tags'] else "No tags"
tags_links = " ".join([f'<a href="/tags/{tag}.html" class="tag">#{tag}</a>' for tag in post['tags'] if tag])
html = f'''<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>{post['title']} - My Blog</title>
<style>
* {{ margin: 0; padding: 0; box-sizing: border-box; }}
body {{ font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Arial, sans-serif; line-height: 1.8; color: #333; background: #f5f5f5; }}
.container {{ max-width: 800px; margin: 0 auto; padding: 20px; }}
header {{ background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; padding: 40px 0; text-align: center; }}
header h1 {{ font-size: 2.5em; }}
.back-link {{ display: inline-block; margin: 20px 0; color: #667eea; text-decoration: none; }}
.back-link:hover {{ text-decoration: underline; }}
.post-meta {{ color: #666; border-bottom: 1px solid #ddd; padding-bottom: 20px; margin-bottom: 30px; }}
.post-content {{ background: white; padding: 40px; border-radius: 8px; box-shadow: 0 2px 4px rgba(0,0,0,0.1); }}
.post-content h1, .post-content h2, .post-content h3 {{ margin-top: 1.5em; margin-bottom: 0.5em; }}
.post-content h1 {{ color: #667eea; }}
.post-content code {{ background: #f4f4f4; padding: 2px 5px; border-radius: 3px; font-family: monospace; }}
.post-content pre {{ background: #f4f4f4; padding: 15px; border-radius: 5px; overflow-x: auto; }}
.post-content blockquote {{ border-left: 4px solid #667eea; padding-left: 20px; margin: 20px 0; color: #666; }}
.post-tags {{ margin-top: 30px; padding-top: 20px; border-top: 1px solid #ddd; }}
.tag {{ display: inline-block; background: #e0e7ff; color: #667eea; padding: 4px 10px; border-radius: 20px; font-size: 0.8em; margin-right: 8px; text-decoration: none; }}
footer {{ text-align: center; padding: 40px 0; color: #666; margin-top: 40px; }}
</style>
</head>
<body>
<header>
<div class="container">
<h1>{post['title']}</h1>
</div>
</header>
<div class="container">
<a href="/" class="back-link">← Back to Home</a>
<article class="post-content">
<div class="post-meta">📅 {post['date_str']} | 🏷️ {tags_display}</div>
{post['content']}
<div class="post-tags">Tags: {tags_links}</div>
</article>
<footer>
<p>© {datetime.now().year} My Python Blog</p>
</footer>
</div>
</body>
</html>'''
with open(self.output_dir / "posts" / f"{post['filename']}.html", 'w', encoding='utf-8') as f:
f.write(html)
print(f" ✅ Generated: posts/{post['filename']}.html")
def generate_tag_pages(self):
"""Generate pages for each tag"""
for tag, posts in self.tags.items():
posts_html = ""
for post in posts:
posts_html += f'''
<div class="post-card">
<h2 class="post-title"><a href="/posts/{post['filename']}.html">{post['title']}</a></h2>
<div class="post-meta">📅 {post['date_str']}</div>
<div class="post-excerpt">{post['excerpt']}</div>
</div>
'''
html = f'''<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Tag: {tag} - My Blog</title>
<style>
* {{ margin: 0; padding: 0; box-sizing: border-box; }}
body {{ font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Arial, sans-serif; line-height: 1.6; color: #333; background: #f5f5f5; }}
.container {{ max-width: 800px; margin: 0 auto; padding: 20px; }}
header {{ background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; padding: 40px 0; text-align: center; }}
.post-card {{ background: white; border-radius: 8px; padding: 25px; margin-bottom: 25px; box-shadow: 0 2px 4px rgba(0,0,0,0.1); }}
.post-title {{ margin-bottom: 10px; }}
.post-title a {{ color: #333; text-decoration: none; }}
.post-title a:hover {{ color: #667eea; }}
.post-meta {{ color: #666; font-size: 0.9em; margin-bottom: 15px; }}
.post-excerpt {{ color: #555; }}
.back-link {{ display: inline-block; margin: 20px 0; color: #667eea; text-decoration: none; }}
footer {{ text-align: center; padding: 40px 0; color: #666; margin-top: 40px; }}
</style>
</head>
<body>
<header>
<div class="container">
<h1>Posts tagged with #{tag}</h1>
<p>{len(posts)} posts</p>
</div>
</header>
<div class="container">
<a href="/" class="back-link">← Back to Home</a>
{posts_html}
<footer>
<p>© {datetime.now().year} My Python Blog</p>
</footer>
</div>
</body>
</html>'''
with open(self.output_dir / "tags" / f"{tag}.html", 'w', encoding='utf-8') as f:
f.write(html)
print(f" ✅ Generated: tags/{tag}.html")
def generate_tags_index(self):
"""Generate main tags index page"""
tag_cloud = ""
for tag in sorted(self.tags.keys()):
count = len(self.tags[tag])
size = 14 + min(20, count)
tag_cloud += f'<a href="/tags/{tag}.html" style="font-size: {size}px; display: inline-block; margin: 5px;">#{tag} ({count})</a>\n'
html = f'''<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>All Tags - My Blog</title>
<style>
* {{ margin: 0; padding: 0; box-sizing: border-box; }}
body {{ font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Arial, sans-serif; line-height: 1.6; color: #333; background: #f5f5f5; }}
.container {{ max-width: 800px; margin: 0 auto; padding: 20px; }}
header {{ background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; padding: 40px 0; text-align: center; }}
.tag-cloud {{ background: white; padding: 40px; border-radius: 8px; margin: 30px 0; text-align: center; }}
.tag-cloud a {{ background: #e0e7ff; color: #667eea; padding: 8px 16px; border-radius: 25px; text-decoration: none; transition: all 0.3s; display: inline-block; margin: 5px; }}
.tag-cloud a:hover {{ background: #667eea; color: white; transform: scale(1.05); }}
.back-link {{ display: inline-block; margin: 20px 0; color: #667eea; text-decoration: none; }}
footer {{ text-align: center; padding: 40px 0; color: #666; }}
</style>
</head>
<body>
<header>
<div class="container">
<h1>All Tags</h1>
<p>Browse posts by category</p>
</div>
</header>
<div class="container">
<a href="/" class="back-link">← Back to Home</a>
<div class="tag-cloud">
{tag_cloud}
</div>
<footer>
<p>© {datetime.now().year} My Python Blog</p>
</footer>
</div>
</body>
</html>'''
with open(self.output_dir / "tags.html", 'w', encoding='utf-8') as f:
f.write(html)
print(" ✅ Generated: tags.html")
def generate_archive(self):
"""Generate archive page"""
# Group by year
posts_by_year = {}
for post in self.posts:
year = post['date'].year
if year not in posts_by_year:
posts_by_year[year] = []
posts_by_year[year].append(post)
archive_html = ""
for year in sorted(posts_by_year.keys(), reverse=True):
archive_html += f'<div class="archive-year"><h2>{year}</h2>'
for post in posts_by_year[year]:
archive_html += f'''
<div class="archive-item">
<span class="date">{post['date'].strftime('%b %d')}</span>
<a href="/posts/{post['filename']}.html">{post['title']}</a>
</div>'''
archive_html += '</div>'
html = f'''<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Archive - My Blog</title>
<style>
* {{ margin: 0; padding: 0; box-sizing: border-box; }}
body {{ font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Arial, sans-serif; line-height: 1.6; color: #333; background: #f5f5f5; }}
.container {{ max-width: 800px; margin: 0 auto; padding: 20px; }}
header {{ background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; padding: 40px 0; text-align: center; }}
.archive-list {{ background: white; padding: 30px; border-radius: 8px; margin: 30px 0; }}
.archive-year {{ margin-bottom: 30px; }}
.archive-year h2 {{ color: #667eea; border-bottom: 2px solid #e0e7ff; padding-bottom: 10px; margin-bottom: 20px; }}
.archive-item {{ padding: 10px 0; border-bottom: 1px solid #eee; }}
.date {{ color: #666; font-size: 0.9em; margin-right: 20px; }}
.archive-item a {{ color: #333; text-decoration: none; }}
.archive-item a:hover {{ color: #667eea; }}
.back-link {{ display: inline-block; margin: 20px 0; color: #667eea; text-decoration: none; }}
footer {{ text-align: center; padding: 40px 0; color: #666; }}
</style>
</head>
<body>
<header>
<div class="container">
<h1>Archive</h1>
<p>All posts by date</p>
</div>
</header>
<div class="container">
<a href="/" class="back-link">← Back to Home</a>
<div class="archive-list">
{archive_html}
</div>
<footer>
<p>© {datetime.now().year} My Python Blog</p>
</footer>
</div>
</body>
</html>'''
with open(self.output_dir / "archive.html", 'w', encoding='utf-8') as f:
f.write(html)
print(" ✅ Generated: archive.html")
def generate(self):
"""Generate everything"""
print("\n" + "="*50)
print("📝 BLOG GENERATOR")
print("="*50)
print("\n📂 Loading posts...")
self.load_posts()
if not self.posts:
print("\n⚠️ No posts found!")
print("\nCreate a sample post with:")
print(" python blog_generator.py --sample")
return
print(f"✅ Loaded {len(self.posts)} posts")
print(f"✅ Found {len(self.tags)} tags")
print("\n📄 Generating pages...")
print("-"*40)
self.generate_homepage()
self.generate_post_pages()
self.generate_tag_pages()
self.generate_tags_index()
self.generate_archive()
print("\n" + "="*50)
print("🎉 BLOG GENERATED SUCCESSFULLY!")
print("="*50)
print(f"\n📁 Output: {self.output_dir.absolute()}")
print("\n🌐 To view your blog:")
print(" cd output")
print(" python -m http.server 8000")
print(" Then open http://localhost:8000")
print("="*50)
def create_sample_post():
"""Create sample post"""
content_dir = Path("content")
content_dir.mkdir(exist_ok=True)
sample_post = content_dir / "welcome.md"
if not sample_post.exists():
content = """---
title: Welcome to My Blog
date: 2024-01-15
tags: Welcome, Python, Tutorial
excerpt: This is my first blog post using the static blog generator.
---
# Welcome to My Blog!
Hello everyone! This is my first blog post generated using my **Python Blog Generator**.
## Why I built this
I wanted a simple way to write blog posts in **Markdown** and generate a static website without dealing with complex CMS systems.
## Features
- Write posts in Markdown
- Automatic HTML generation
- Tag support
- Archive page
- Clean, responsive design
## Code Example
Here's a Python code block:
def hello_world():
print("Hello, Blog!")
hello_world()
## What's Next?
I'll be posting regularly about:
- Python programming
- Web development
- Productivity tips
Stay tuned for more content!
---
Thanks for reading! 🚀
"""
sample_post.write_text(content, encoding='utf-8')
print(f"✅ Created sample post: {sample_post}")
print("\n📝 Run 'python blog_generator.py' to generate your blog!")
else:
print(f"⚠️ Sample post already exists: {sample_post}")
def main():
parser = argparse.ArgumentParser(description='Static Blog Generator')
parser.add_argument('--sample', action='store_true', help='Create a sample post')
args = parser.parse_args()
if args.sample:
create_sample_post()
else:
generator = BlogGenerator()
generator.generate()
if __name__ == "__main__":
try:
main()
except KeyboardInterrupt:
print("\n\n⚠️ Cancelled")
sys.exit(0)
except Exception as e:
print(f"\n❌ Error: {e}")
sys.exit(1)