-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathblog_editor.py
More file actions
359 lines (295 loc) · 12 KB
/
blog_editor.py
File metadata and controls
359 lines (295 loc) · 12 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
import time
import os
from typing import List
from file_system.file_helper import FileHelper
from llms.llm_service import LLMService
from helpers.transcriber import Transcriber
from helpers.resume_extractor import ResumeExtractor
from helpers.thumbnail_generator import ThumbnailGenerator
from prompts.prompts import Prompts
from helpers.notion_service import NotionService
from helpers.podcast_generator import PodcastGenerator
from dotenv import load_dotenv
from schemas.file import Blog, Thumbnails
from schemas.prompt import SimpleResponse, Prompt
from errors import GuestNotFoundError
class BlogEditor():
"""
Class to handle the blog editing process
"""
def __init__(self):
"""
Initialize the BlogEditor
"""
# Load env variables
load_dotenv()
config = self.get_env_vars()
# Initialize services
self.file_helper = FileHelper('/Users/anirudhh/Documents/Zoom_v2')
self.llm = LLMService(config)
self.prompts = Prompts(self.file_helper)
self.resume_extractor = ResumeExtractor(self.llm, self.prompts)
self.thumbnail_generator = ThumbnailGenerator()
self.transcriber = Transcriber(config, self.llm, self.prompts)
self.podcast_generator = PodcastGenerator(config, self.llm, self.prompts)
self.notion_service = NotionService(config)
def get_env_vars(self):
"""
Get the environment variables
"""
return {
"ASSEMBLYAI_API_KEY": os.getenv("ASSEMBLYAI_API_KEY"),
"NOTION_TOKEN": os.getenv("NOTION_TOKEN"),
"OPENAI_API_KEY": os.getenv("OPENAI_API_KEY"),
"ANTHROPIC_API_KEY": os.getenv("ANTHROPIC_API_KEY"),
"NOTION_DATABASE_ID": os.getenv("NOTION_DATABASE_ID"),
"FIREBASE_CREDENTIALS_PATH": os.getenv("FIREBASE_CREDENTIALS_PATH"),
"FIREBASE_STORAGE_BUCKET": os.getenv("FIREBASE_STORAGE_BUCKET"),
"ELEVENLABS_API_KEY": os.getenv("ELEVENLABS_API_KEY"),
}
# List & get files
def list_files(self) -> List[str]:
"""
List all the files in the file system
"""
return self.file_helper.list_files()
def get(self, file_name: str) -> Blog:
"""
Get the blog with the given file name
"""
return self.file_helper.get(file_name)
# Extract metadata from the existing documents
def extract_resume(self, file_name: str, callback=None) -> None:
"""
Extract the resume from the given file name
"""
blog = self.file_helper.get(file_name)
if not self.check_files(blog):
print("Missing files, upload them!")
return
if not blog.metadata.resume:
if callback:
callback("Extracting resume for " + file_name)
blog.metadata.resume = self.resume_extractor.extract(blog)
self.file_helper.save(blog)
def transcribe(self, file_name: str, callback=None) -> None:
"""
Transcribe the given file name
"""
blog = self.file_helper.get(file_name)
if not self.check_files(blog):
print("Missing files, upload them!")
return
if not blog.metadata.utterances:
if callback:
callback("Utterances not found, generating for " + file_name)
blog.metadata.utterances = self.transcriber.transcribe(blog.files.audio_file)
self.file_helper.save(blog)
if not blog.metadata.transcript:
if callback:
callback("Transcript not found, generating for " + file_name)
blog.metadata.transcript = self.transcriber.generate_transcript(blog.metadata.utterances)
self.file_helper.save(blog)
# Enrich guest
def enrich_guest(self, file_name: str, callback=None):
"""
Enrich the guest data with first_name, origin, top companies & universities
"""
blog = self.file_helper.get(file_name)
if not blog.metadata.guest:
blog.metadata.guest = self.resume_extractor.enrich_guest(blog)
self.file_helper.save(blog)
# Generate thumbnails
def generate_thumbnails(self, file_name, callback=None):
"""
Generate the thumbnails for the given file name
"""
blog = self.file_helper.get(file_name)
if not blog.files.photo:
print(f"Photo not found for {file_name}, upload it!")
return
if not blog.files.resume_file:
print(f"Resume not found for {file_name}, upload & generate it!")
return
# Always generate thumbnails
if callback:
callback(f"Generating thumbnails for {file_name}")
blog.thumbnails = self.thumbnail_generator.generate_thumbnails(blog)
self.file_helper.save(blog)
# Generate blog assets (title, description, linkedin, blog)
def generate(self, file_name: str, attr: str, model="opus", llm_stream=None, callback=None):
"""
Handle the generation of an attribute for a blog
"""
file = self.file_helper.get(file_name)
if not self.check_files(file):
print("Missing files, upload them!")
return
# The attribute has not been generated previously, so generate it
if not getattr(file.blog, attr):
prompt = self.prompts.get_prompt(file, attr)
self._generate(file, attr, prompt, model, llm_stream, callback)
else:
# Attribute was already generated once, ask the user what to do
message = f"{attr} already generated for {file_name}, skipping."
print(message)
llm_stream(message)
callback(message)
def edit(self, file_name: str, attr: str, instructions: str,model="opus", llm_stream=None, callback=None):
"""
Edit the given attribute for the given file name
TODO: This can be merged into generate method
"""
file = self.file_helper.get(file_name)
if not self.check_files(file):
print("Missing files, upload them!")
return
if not getattr(file.blog, attr):
message = f"{attr} not generated for {file_name}, generating it!"
print(message)
llm_stream(message)
callback(message)
self._generate(file, attr, model, llm_stream, callback)
return
attr_prompt = self.prompts.get_prompt(file, attr)
prompt = f"""
Here is the previous chat conversation:
<previous_chat_history>
<previous_instructions>
{attr_prompt.text}
</previous_instructions>
<output>
{getattr(file.blog, attr)}
</output>
</previous_chat_history>
You have been provided with the following user instructions:
<user_instructions>
{instructions}
</user_instructions>
Edit the text: {getattr(file.blog, attr)} using the above instructions and return.
"""
self._generate(file, attr, Prompt(text=prompt, model=attr_prompt.model), model, llm_stream, callback)
def _generate(self, file: Blog, attr: str, prompt: str, model="opus", llm_stream=None, callback=None):
"""
Generate a specified attribute for the blog
"""
if callback:
callback(f"Generating {attr} for {file.name}")
if llm_stream:
print(f"Streaming {attr} for {file.name}")
response = self.llm.stream_prompt(prompt.text, model=prompt.model, llm_stream=llm_stream)
setattr(file.blog, attr, response)
self.file_helper.save(file)
else:
if attr in ["title", "description", "linkedin"]:
response = self.llm.prompt(prompt.text, model=prompt.model, schema=SimpleResponse)
else:
response = self.llm.prompt(prompt.text, model=prompt.model)
setattr(file.blog, attr, response)
self.file_helper.save(file)
# Publish the blog
# TODO: Move these into a dedicated helper class
def publish_markdown_draft(self, file_name, callback=None):
"""
Publish the blog as a markdown draft
"""
file = self.file_helper.get(file_name)
if not file.blog:
file.blog = Blog()
if callback:
callback(f"Publishing markdown draft for {file_name}")
# TODO: Old code, this must be fixed
with open(f"/temp/{file_name}.md", "w") as f:
blog_content = f"""
# Title: {file.blog.title}
Description: {file.blog.description}
---
# Overview
{file.metadata.resume}
---
# Blog
{file.blog.content}
---
# LinkedIn
{file.blog.linkedin}
"""
f.write(blog_content)
def publish_notion_draft(self, file_name, callback=None):
"""
Publish the blog to notion
"""
file = self.file_helper.get(file_name)
if callback:
callback(f"Publishing {file_name} to notion")
if not file.files.photo:
print(f"Photo not found for {file_name}, upload it!")
return
if not file.thumbnails.landscape:
print(f"Banner not found for {file_name}, upload it!")
return
if not file.thumbnails.square:
print(f"Square thumbnail not found for {file_name}, generate it!")
return
if not file.metadata.resume:
print(f"Resume not found for {file_name}, generate it!")
return
if not file.blog.title:
print(f"Title not found for {file_name}, generate it!")
return
if not file.blog.description:
print(f"Description not found for {file_name}, generate it!")
return
if not file.blog.content:
print(f"Blog not found for {file_name}, generate it!")
return
if not file.blog.linkedin:
print(f"LinkedIn not found for {file_name}, generate it!")
return
self.notion_service.create_page(file)
if callback:
callback(f"Published {file_name} to notion")
def reset(self, file_name, callback=None):
"""
Reset the blog with the given file name
"""
# TODO: Not yet implemented
if callback:
callback(f"Resetting {file_name}. NOT YET IMPLEMENTED")
self.file_helper.reset(file_name)
def generate_all(self, file_name, model="opus", llm_stream=None, callback=None):
"""
Generate all the attributes for the given file name
"""
if callback:
callback(f"Generating all for {file_name}")
self.extract_resume(file_name, callback=callback)
self.transcribe(file_name, callback=callback)
# Enrich the guest
self.enrich_guest(file_name, callback=callback)
# Generate thumbnails
self.generate_thumbnails(file_name, callback=callback)
# Generate blog
for attr in Blog.__annotations__.keys():
self.generate(file_name, attr, model=model, llm_stream=llm_stream, callback=callback)
# Generate podcast
# if callback:
# callback("Generating podcast intro...")
# file = self.file_helper.get(file_name)
# self.podcast_generator.generate_intro(file)
# if callback:
# callback("Generating podcast...")
# self.podcast_generator.generate_podcast(file)
print(f"All generated for {file_name}")
# Validation
def check_files(self, file: Blog) -> bool:
"""
Check if all the required files are present for the given blog
To generate a blog, we need the following files: audio.m4a, resume.pdf and a photo.png
"""
if not file.files.audio_file:
return False
if not file.files.resume_file:
return False
if not file.files.photo:
return False
return True