blog_writer.py 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117
  1. import datetime
  2. import json
  3. import openai
  4. import os
  5. from typing import Optional
  6. from tool_lib.util import EBC
  7. class Topic(EBC):
  8. def __init__(self, topic_name: str, topic_detailed_description=''):
  9. self.topic_name = topic_name
  10. self.topic_detailed_description = topic_detailed_description
  11. class Template(EBC):
  12. def __init__(self, template_name: str, template_content: str, formatting_kwargs: Optional[dict] = None):
  13. self.template_name = template_name
  14. self.template_content = template_content
  15. if formatting_kwargs is None:
  16. formatting_kwargs = {}
  17. self.formatting_kwargs = formatting_kwargs
  18. def update_formatting_kwargs(self, **kwargs):
  19. self.formatting_kwargs.update(kwargs)
  20. def format(self, topic: Topic):
  21. return self.template_content.format(topic_name=topic.topic_name, topic_detailed_description=topic.topic_detailed_description, **self.formatting_kwargs)
  22. class EnDBlogTemplate(Template):
  23. def __init__(self,
  24. min_words=400,
  25. max_words=600):
  26. template_name = 'end_blog_template'
  27. template_content = '''For context: You are writing a blog post for publication on the website of our company EnD UG.
  28. We specialize in tour planning software and are proud that our product is fast, reliable and easy to use.
  29. It allows our customers to plan the driving routes of their employees automatically while optimizing the driving time, fuel usage and timeliness.
  30. It also allows our customers to plan the driving routes of their employees manually, while giving them suggestions on how to improve the route.
  31. Please write a blog post about the topic of "{topic_name}" in a length of {min_words} to {max_words}. {topic_detailed_description}
  32. Make sure that the blog post is written in a way that is easy to understand for visitors to our website, including potential customers, but technically detailed enough to show that the writer has expertise in the topic.
  33. It should be written in an informative and factual way and not be promotional.
  34. Do not address the reader directly. Write in third person. In particular, avoid phrases like "At EnD UG we ..." or "As a business manager you ..." or "our [company, tool, software, ...]".
  35. Include a title and format the output as markdown. In particular, after each sentence, add a newline, and an additional one after paragraphs.
  36. Do not include URLs, images or references to other blog posts.
  37. '''
  38. super().__init__(template_name, template_content, {'min_words': min_words, 'max_words': max_words})
  39. class TechnicalBlogTemplate(Template):
  40. def __init__(self,
  41. min_words=400,
  42. max_words=600):
  43. mean_words = (min_words + max_words) / 2
  44. template_name = 'technical_blog_template'
  45. template_content = '''Please write a blog post about the topic of "{topic_name}" in a length of {min_words} to {max_words}, ideally around {mean_words}. {topic_detailed_description}
  46. Make sure that the blog post is written in a way that is easy to understand, but technically detailed enough to show that the writer has expertise in the topic.
  47. It should be written in an informative and factual way and not be promotional.
  48. Do not address the reader directly. Write in third person.
  49. Include a title and format the output as markdown. In particular, after each sentence, add a newline, and an additional one after paragraphs.
  50. Structure sections with headings.
  51. Do not include URLs, images or references to other blog posts.
  52. '''
  53. super().__init__(template_name, template_content, {'min_words': min_words, 'max_words': max_words, 'mean_words': mean_words})
  54. class BlogCreator(EBC):
  55. def __init__(self, template: Template, topic: Topic):
  56. self.template = template
  57. self.topic = topic
  58. def request_template(self):
  59. return self.template.template_content
  60. def write(self):
  61. message = [{"role": "user",
  62. "content": self.request()}]
  63. response = openai.ChatCompletion.create(
  64. model="gpt-3.5-turbo",
  65. messages=message,
  66. temperature=0.2,
  67. max_tokens=1000,
  68. frequency_penalty=0.0
  69. )
  70. return response['choices'][0]['message']['content']
  71. def request(self):
  72. return self.template.format(self.topic)
  73. def to_disk(self):
  74. to_file = os.path.abspath(f'blog_posts/{topic.topic_name}_{datetime.datetime.now().strftime("%Y-%m-%d_%H-%M-%S")}.json')
  75. os.makedirs(os.path.dirname(to_file), exist_ok=True)
  76. result = {'blogger': self.to_json(),
  77. 'dt_created': datetime.datetime.now().timestamp(),
  78. 'request': self.request(),
  79. 'result': self.write()}
  80. with open(to_file, 'w', encoding='utf-8') as f:
  81. json.dump(result, f, indent=4)
  82. with open(to_file.replace('.json', '.md'), 'w', encoding='utf-8') as f:
  83. f.write(result['result'])
  84. print(f'Wrote {to_file}')
  85. if __name__ == '__main__':
  86. topics = [
  87. # Topic('Travel Salesman'),
  88. # Topic('k-opt Algorithm for the Traveling Salesman Problem'),
  89. # Topic('Linear Programming'),
  90. # Topic('Mixed Linear Programming'),
  91. # Topic('Clustering'),
  92. # Topic('OpenAPI and Swagger'),
  93. ]
  94. for topic in topics:
  95. BlogCreator(TechnicalBlogTemplate(), topic).to_disk()