123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123 |
- import datetime
- import json
- import openai
- import os
- from typing import Optional
- from tool_lib.util import EBC
- class Topic(EBC):
- def __init__(self, topic_name: str, topic_detailed_description=''):
- self.topic_name = topic_name
- self.topic_detailed_description = topic_detailed_description
- class Template(EBC):
- def __init__(self, template_name: str, template_content: str, formatting_kwargs: Optional[dict] = None):
- self.template_name = template_name
- self.template_content = template_content
- if formatting_kwargs is None:
- formatting_kwargs = {}
- self.formatting_kwargs = formatting_kwargs
- def update_formatting_kwargs(self, **kwargs):
- self.formatting_kwargs.update(kwargs)
- def format(self, topic: Topic):
- return self.template_content.format(topic_name=topic.topic_name, topic_detailed_description=topic.topic_detailed_description, **self.formatting_kwargs)
- class EnDBlogTemplate(Template):
- def __init__(self,
- min_words=400,
- max_words=600):
- template_name = 'end_blog_template'
- raise RuntimeError('Deprecated')
- template_content = '''For context: You are writing a blog post for publication on the website of our company EnD UG.
- We specialize in tour planning software and are proud that our product is fast, reliable and easy to use.
- It allows our customers to plan the driving routes of their employees automatically while optimizing the driving time, fuel usage and timeliness.
- It also allows our customers to plan the driving routes of their employees manually, while giving them suggestions on how to improve the route.
- Please write a blog post about the topic of "{topic_name}" in a length of {min_words} to {max_words}. {topic_detailed_description}
- 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.
- It should be written in an informative and factual way and not be promotional.
- 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, ...]".
- Include a title and format the output as markdown. In particular, after each sentence, add a newline, and an additional one after paragraphs.
- Do not include URLs, images or references to other blog posts.
- '''
- super().__init__(template_name, template_content, {'min_words': min_words, 'max_words': max_words})
- class TechnicalBlogTemplate(Template):
- def __init__(self,
- min_words=400,
- max_words=600,
- language='English'):
- mean_words = (min_words + max_words) / 2
- template_name = 'technical_blog_template'
- 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}
- 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.
- It should be written in an informative and factual way and not be promotional.
- Do not address the reader directly. Write in third person. Write in {language}.
- Include a title and format the output as markdown. In particular, after each sentence, add a newline, and an additional one after paragraphs.
- Structure sections with headings.
- Do not include URLs, images or references to other blog posts.
- '''
- super().__init__(template_name, template_content, {'min_words': min_words,
- 'max_words': max_words,
- 'mean_words': mean_words,
- 'language': language})
- class BlogCreator(EBC):
- def __init__(self, template: Template, topic: Topic):
- self.template = template
- self.topic = topic
- def request_template(self):
- return self.template.template_content
- def write(self):
- message = [{"role": "user",
- "content": self.request()}]
- response = openai.ChatCompletion.create(
- model="gpt-3.5-turbo",
- messages=message,
- temperature=0.2,
- max_tokens=1000,
- frequency_penalty=0.0
- )
- return response['choices'][0]['message']['content']
- def request(self):
- return self.template.format(self.topic)
- def to_disk(self):
- to_file = os.path.abspath(f'blog_posts/{topic.topic_name}_{datetime.datetime.now().strftime("%Y-%m-%d_%H-%M-%S")}.json')
- os.makedirs(os.path.dirname(to_file), exist_ok=True)
- print(f'Requesting info for {to_file}...')
- result = {'blogger': self.to_json(),
- 'dt_created': datetime.datetime.now().timestamp(),
- 'request': self.request(),
- 'result': self.write()}
- with open(to_file, 'w', encoding='utf-8') as f:
- json.dump(result, f, indent=4)
- with open(to_file.replace('.json', '.md'), 'w', encoding='utf-8') as f:
- f.write(result['result'])
- print(f'Wrote {to_file}')
- if __name__ == '__main__':
- topics = [
- # Topic('Problem des Handlungsreisenden (Traveling Salesperson)'),
- # Topic('k-opt Algorithmus für das Traveling Salesperson Problem'),
- # Topic('Lineare Programmierung'),
- # Topic('Ganzzahlige lineare Optimierung'),
- # Topic('Clustering', topic_detailed_description='Also mention that clustering can be used as a pre-processing step when solving the traveling salesperson problem.'),
- # Topic('OpenAPI und Swagger'),
- ]
- for topic in topics:
- BlogCreator(TechnicalBlogTemplate(language='German'), topic).to_disk()
|