-
-
Notifications
You must be signed in to change notification settings - Fork 687
/
make_desc.py
207 lines (169 loc) · 6.92 KB
/
make_desc.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
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
import os
from typing import Optional, Literal
import asyncio
from openai import AsyncOpenAI
import typer
from rich.console import Console
from rich.progress import Progress
from rich.table import Table
from pydantic import BaseModel, Field
import instructor
import frontmatter
console = Console()
client = instructor.from_openai(AsyncOpenAI())
async def generate_ai_frontmatter(
client: AsyncOpenAI, title: str, content: str, categories: list[str]
):
"""
Generate a description and categories for the given content using AI.
Args:
client (AsyncOpenAI): The AsyncOpenAI client.
title (str): The title of the markdown file.
content (str): The content of the file.
categories (List[str]): List of all available categories.
Returns:
DescriptionAndCategories: The generated description, categories, tags, and reasoning.
"""
class DescriptionAndCategories(BaseModel):
description: str
reasoning: str = Field(
..., description="The reasoning for the correct categories"
)
tags: list[str]
categories: list[
Literal[
"OpenAI",
"Anthropic",
"LLama",
"LLM Observability",
"Data Processing",
"Python",
"LLM Techniques",
"Pydantic",
"Performance Optimization",
"Data Validation",
"API Development",
"Retrieval Augmented Generation",
]
]
response = await client.chat.completions.create(
model="gpt-4o-mini",
messages=[
{
"role": "system",
"content": "You are an AI assistant that generates SEO-friendly descriptions for markdown files.",
},
{"role": "user", "content": f"Title: {title}\n\nContent: {content}"},
{
"role": "user",
"content": f"Based on the title and content, generate a brief description (max 160 characters) that would be suitable for SEO purposes. Also, select up to 3 relevant categories from the following list: {', '.join(categories)}. Return both the description and the selected categories. The categories should be pretty strict, so only choose one if you're really sure it's the best choice. Also, suggest up to 5 relevant tags.",
},
],
max_tokens=150,
response_model=DescriptionAndCategories,
)
return response
def get_all_categories(root_dir: str) -> set[str]:
"""
Read all markdown files and extract unique categories.
Args:
root_dir (str): The root directory to start processing from.
Returns:
Set[str]: A set of unique categories.
"""
categories = set()
for root, _, files in os.walk(root_dir):
for file in files:
if file.endswith(".md"):
file_path = os.path.join(root, file)
post = frontmatter.load(file_path)
if "categories" in post.metadata:
categories.update(post.metadata["categories"])
return categories
def preview_categories(root_dir: str) -> None:
"""
Preview all categories found in markdown files.
Args:
root_dir (str): The root directory to start processing from.
"""
categories = get_all_categories(root_dir)
table = Table(title="Categories Preview")
table.add_column("Category", style="cyan")
for category in sorted(categories):
table.add_row(category)
console.print(table)
console.print(f"\nTotal categories found: {len(categories)}")
async def process_file(
client: AsyncOpenAI, file_path: str, categories: list[str], enable_comments: bool
) -> None:
"""
Process a single file, adding or updating the description and categories in the front matter.
Args:
client (AsyncOpenAI): The AsyncOpenAI client.
file_path (str): The path to the file to process.
categories (List[str]): List of all available categories.
enable_comments (bool): Whether to enable comments in the front matter.
"""
post = frontmatter.load(file_path)
title = post.metadata.get("title", os.path.basename(file_path))
response = await generate_ai_frontmatter(client, title, post.content, categories)
post.metadata["description"] = response.description
post.metadata["categories"] = response.categories
post.metadata["tags"] = response.tags
if enable_comments:
post.metadata["comments"] = True
with open(file_path, "w", encoding="utf-8") as file:
file.write(frontmatter.dumps(post))
console.print(f"[green]Updated front matter in {file_path}[/green]")
async def process_files(
root_dir: str,
api_key: Optional[str] = None, # noqa: ARG001
use_categories: bool = False,
enable_comments: bool = False,
) -> None:
"""
Process all markdown files in the given directory and its subdirectories.
Args:
root_dir (str): The root directory to start processing from.
api_key (Optional[str]): The OpenAI API key. If not provided, it will be read from the OPENAI_API_KEY environment variable.
use_categories (bool): Whether to first read all files and generate a list of categories.
enable_comments (bool): Whether to enable comments in the front matter.
"""
markdown_files = []
for root, _, files in os.walk(root_dir):
for file in files:
if file.endswith(".md"):
markdown_files.append(os.path.join(root, file))
categories = list(get_all_categories(root_dir)) if use_categories else []
with Progress() as progress:
task = progress.add_task(
"[green]Processing files...", total=len(markdown_files)
)
async def process_and_update(file_path: str) -> None:
await process_file(client, file_path, categories, enable_comments)
progress.update(task, advance=1)
tasks = [process_and_update(file_path) for file_path in markdown_files]
await asyncio.gather(*tasks)
console.print("[bold green]All files processed successfully![/bold green]")
app = typer.Typer()
@app.command()
def main(
root_dir: str = typer.Option("docs", help="Root directory to process"),
api_key: Optional[str] = typer.Option(None, help="OpenAI API key"),
use_categories: bool = typer.Option(False, help="Use categories from all files"),
preview_only: bool = typer.Option(
False, help="Preview categories without processing files"
),
enable_comments: bool = typer.Option(
False, help="Enable comments in the front matter"
),
):
"""
Add or update description in front matter of markdown files in the given directory and its subdirectories.
"""
if preview_only:
preview_categories(root_dir)
else:
asyncio.run(process_files(root_dir, api_key, use_categories, enable_comments))
if __name__ == "__main__":
app()