Home >  > OpenAI自动生成文章

OpenAI自动生成文章

OpenAI GPT-3 到文章文件或 WordPress 帖子。 几乎免费且高质量的 AI 生成内容。 制作自己的自动博客?

一、价格
Check out the pricing page, costs are like 60 cents per 1k tokens and 1k tokens are around 750 words. So if you set max_tokens to 500 you get about 350 words and it would cost you 30 cents.

查看定价页面,成本约为每 1k 代币 60 美分,1k 代币约为 750 个字。 因此,如果您将 max_tokens 设置为 500,您将获得大约 350 个单词,这将花费您 30 美分。

二、代码
Version 1.01

Changelog
1. Better Exception Handling
2. Reads only txt files from the generated content folder and ignores os files like desktop.ini and DS_store
3. Passes an empty string to content when flag is False while posting to wp from file
4. Replaced profanity with kid-friendly messages
5. Checks if q.txt is empty after checking if it exists.
6. Added a quit operation to the main menu
7. Renames file if file already exists in the generated_content folder

1import os,openai, requests, random, base64
2from concurrent.futures import ProcessPoolExecutor
3 
4'''OpenAI Key goes within the quotes'''
5openai_key = 'Key Here'
6 
7# WP
8wordpress_domain = '' ##DO NOT INCLUDE HTTPS OR WWW OR ANY TRAILING SLASHES. ONLY ENTER domainname.tld
9wordpress_username = ''
10wordpress_application_password = ''
11 
12wordpress_post_status = 'draft'
13 
14# OpenAI Tweaks
15aiTemperature = 0.7
16maxTokens = 100
17 
18'''Paths. Change these only if you know wtf you're doing'''
19generated_content = 'new_content_files/'
20uploaded_content = 'content_uploaded_to_wp/'
21 
22# Menu Items
23singleq = ('''OpenAI is a bitch. Please format your questions clearly.
24        Sample Question: Tell me about guitar strings in 200 words
25        Sample Answer below has only 199 words... OpenAI is a bitch
26 
27        Guitar strings are one of the most important aspects of the instrument, and the type of string you use can have
28        a big impact on your sound. There are a variety of different types of strings available, each with their own
29        unique properties.
30 
31        The most common type of string is the steel string, which is most often used on acoustic guitars. Steel strings
32        are known for their bright, clear tone and are a good choice for most styles of music.
33 
34        If you're looking for a warmer, more mellow sound, you might want to try a set of nylon strings. Nylon strings
35        are typically used on classical and flamenco guitars, and they offer a softer, more delicate sound.
36 
37        If you're looking for the ultimate in shredding capabilities, you'll want to check out a set of stainless steel
38        strings. These strings are incredibly durable and can stand up to serious abuse, making them a good choice for
39        metal and hard rock players.
40 
41        No matter what type of music you play, there's a set of guitar strings that's perfect for you. With so many
42        different types available, there's no reason not to experiment until you find the perfect set for your sound.
43 
44        So, type in your question accordingly: ''')
45 
46mainmenu = '''
47    Howdy!
48 
49        Hit
50            1: Generate Articles and write them to file
51            2: Generate Articles and post them to WordPress
52            3: Read Articles from file and post them to WordPress
53            4: Quit
54 
55        Wachawannado? : '''
56 
57a2menu = '''
58        1: Imput single question here
59        2: Read list of questions from file (One question per line)
60        3: Go back to previous menu
61 
62        Wachawannadonow? : '''
63 
64 
65def post2wp(q, i, flag, content):
66    if flag:
67        openai.api_key = openai_key
68        content = openai.Completion.create(model="text-davinci-002", prompt=q, temperature=aiTemperature,
69                                           max_tokens=maxTokens)["choices"][0]["text"]
70 
71    cred = f'{wordpress_username}:{wordpress_application_password}'
72    tkn = base64.b64encode(cred.encode())
73    wpheader = {'Authorization': 'Basic ' + tkn.decode('utf-8')}
74    api_url = f'https://{wordpress_domain}/wp-json/wp/v2/posts'
75    data = {
76    'title' : q.capitalize(),
77    'status': wordpress_post_status,
78    'content': content,
79    }
80    print(content)
81    wp_response = requests.post(url=api_url,headers=wpheader, json=data)
82    print(f'Item no. {i+1} posted, with title{q} and post content \n\n {content} \n\n {wp_response})
83 
84 
85def article2file(q,i):
86    openai.api_key = openai_key
87    response = openai.Completion.create(model="text-davinci-002", prompt=q, temperature=aiTemperature,
88                                        max_tokens=maxTokens)["choices"][0]["text"]
89    fname = q.replace(' ', '_') + '.txt'
90    if os.path.exists(generated_content+fname):
91        print('File with title already exists, renaming it with a random number prefix')
92        os.replace(generated_content+fname,generated_content+str(random.randint(1000,9999))+fname)
93    with open(generated_content+fname, 'w') as f:
94        f.write(response)
95        print(f'Item: {i} in list done.\nQuery string: {q}\nArticle:\n{response}\n\nSaved to {fname}')
96 
97 
98 
99 
100 
101if __name__ == '__main__':
102    if not os.path.exists(generated_content):
103        os.mkdir(generated_content)
104    if not os.path.exists(uploaded_content):
105        os.mkdir(uploaded_content)
106    try:
107        while True:
108            try:
109                wachawannado = int(input(mainmenu))
110            except ValueError:
111                print('\nPlease enter a number')
112                continue
113            if wachawannado == 1: #Article to file
114                try:
115                    wachawannadonow = int(input(a2menu))
116                except ValueError:
117                    print('\nPlease enter a number')
118                    continue
119                if wachawannadonow == 1: #a2f single
120                    article2file(q=input(singleq), i=1)
121 
122                elif wachawannadonow == 2: #a2f file
123                    if os.path.exists('q.txt'):
124                        if not os.stat("file").st_size == 0:
125                            with open('q.txt', 'r') as f:
126                                with ProcessPoolExecutor(max_workers=16) as executor:
127                                    for i, line in enumerate(f):
128                                        executor.submit(article2file, i=i, q=line)
129                        else:
130                            print('\nq.txt is empty')
131                            continue
132                    else:
133                        print("Can't find q.txt")
134                        continue
135                else:
136                    continue
137 
138            elif wachawannado == 2: #Article to WordPress
139                try:
140                    wachawannadonow = int(input(a2menu))
141                except ValueError:
142                    print('\nPlease enter a number')
143                    continue
144                if wachawannadonow == 1: #a2wp single
145                    post2wp(q=input(singleq), i=1, flag = True, content = '')
146                elif wachawannadonow == 2: #a2wp file
147                    if os.path.exists('q.txt'):
148                        if not os.stat("file").st_size == 0:
149                            with open('q.txt', 'r') as f:
150                                with ProcessPoolExecutor(max_workers=16) as executor:
151                                    for i, line in enumerate(f):
152                                        executor.submit(post2wp, q=line, i=i, flag = True, content = '')
153                        else:
154                            print('\nq.txt is empty')
155                            continue
156                    else:
157                        print("Can't find q.txt")
158                        continue
159                else:
160                    continue
161            elif wachawannado == 3: #Files to WP
162                contentfiles = os.listdir(generated_content)
163                if contentfiles:
164                    with ProcessPoolExecutor(max_workers=16) as executor:
165                        for i, file in enumerate(contentfiles):
166                            if file.endswith('.txt'):
167                                print('Posting from file:', file)
168                                with open(generated_content+file,'r') as f:
169                                    executor.submit(post2wp, flag = False, content = f.read(), q = file.replace('_', '').replace('.txt',''), i=i)
170                                os.replace(generated_content+file, uploaded_content+file)
171                else:
172                    print('Generated Content folder is empty')
173            elif wachawannado == 4:
174                print('Bye!')
175                break
176            else:
177                print('Invalid Choice, try that again')
178    except KeyboardInterrupt:
179        print('Bye!')

暧昧帖

本文暂无标签