-
Notifications
You must be signed in to change notification settings - Fork 50
/
generate_sitemap.py
143 lines (116 loc) · 4.69 KB
/
generate_sitemap.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
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
import os
import asyncio
import yaml
from typing import Generator, Tuple, Dict, Optional
from openai import AsyncOpenAI
import typer
from rich.console import Console
from rich.progress import Progress
import hashlib
console = Console()
def traverse_docs(
root_dir: str = "docs",
) -> Generator[Tuple[str, str, str], None, None]:
"""
Recursively traverse the docs folder and yield the path, content, and content hash of each file.
Args:
root_dir (str): The root directory to start traversing from. Defaults to 'docs'.
Yields:
Tuple[str, str, str]: A tuple containing the relative path from 'docs', the file content, and the content hash.
"""
for root, _, files in os.walk(root_dir):
for file in files:
if file.endswith(".md"): # Assuming we're only interested in Markdown files
file_path = os.path.join(root, file)
relative_path = os.path.relpath(file_path, root_dir)
with open(file_path, "r", encoding="utf-8") as f:
content = f.read()
content_hash = hashlib.md5(content.encode()).hexdigest()
yield relative_path, content, content_hash
async def summarize_content(client: AsyncOpenAI, path: str, content: str) -> str:
"""
Summarize the content of a file.
Args:
client (AsyncOpenAI): The AsyncOpenAI client.
path (str): The path of the file.
content (str): The content of the file.
Returns:
str: A summary of the content.
"""
try:
response = await client.chat.completions.create(
model="gpt-4o",
messages=[
{
"role": "system",
"content": "You are a helpful assistant that summarizes text.",
},
{"role": "user", "content": content},
{
"role": "user",
"content": "Please summarize the content in a few sentences so they can be used for SEO. Include core ideas, objectives, and important details and key points and key words",
},
],
max_tokens=4000,
)
return response.choices[0].message.content
except Exception as e:
console.print(f"[bold red]Error summarizing {path}: {str(e)}[/bold red]")
return ""
async def generate_sitemap(
root_dir: str, output_file: str, api_key: Optional[str] = None
) -> None:
"""
Generate a sitemap from the given root directory.
Args:
root_dir (str): The root directory to start traversing from.
output_file (str): The output file to save the sitemap.
api_key (Optional[str]): The OpenAI API key. If not provided, it will be read from the OPENAI_API_KEY environment variable.
"""
client = AsyncOpenAI(api_key=api_key)
# Load existing sitemap if it exists
existing_sitemap: Dict[str, Dict[str, str]] = {}
if os.path.exists(output_file):
with open(output_file, "r", encoding="utf-8") as sitemap_file:
existing_sitemap = yaml.safe_load(sitemap_file) or {}
sitemap_data: Dict[str, Dict[str, str]] = {}
async def process_file(
path: str, content: str, content_hash: str
) -> Tuple[str, Dict[str, str]]:
if (
path in existing_sitemap
and existing_sitemap[path].get("hash") == content_hash
):
return path, existing_sitemap[path]
summary = await summarize_content(client, path, content)
return path, {"summary": summary, "hash": content_hash}
with Progress() as progress:
task = progress.add_task(
"[green]Processing files...", total=len(list(traverse_docs(root_dir)))
)
tasks = [
process_file(path, content, content_hash)
for path, content, content_hash in traverse_docs(root_dir)
]
results = await asyncio.gather(*tasks)
for _ in results:
progress.update(task, advance=1)
sitemap_data = dict(results)
with open(output_file, "w", encoding="utf-8") as sitemap_file:
yaml.dump(sitemap_data, sitemap_file, default_flow_style=False)
console.print(
f"[bold green]Sitemap has been generated and saved to {output_file}[/bold green]"
)
app = typer.Typer()
@app.command()
def main(
root_dir: str = typer.Option("docs", help="Root directory to traverse"),
output_file: str = typer.Option("sitemap.yaml", help="Output file for the sitemap"),
api_key: Optional[str] = typer.Option(None, help="OpenAI API key"),
):
"""
Generate a sitemap from the given root directory.
"""
asyncio.run(generate_sitemap(root_dir, output_file, api_key))
if __name__ == "__main__":
app()