Dede16 commited on
Commit
113aaac
·
1 Parent(s): 09f9ab8

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +450 -502
app.py CHANGED
@@ -19,533 +19,481 @@ openai.api_key ='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'
19
  from io import BytesIO
20
  data_scrap = []
21
 
22
- # def split_article(article_text):
23
- # words = article_text.split()
24
- # total_words = len(words)
25
- # split_points = [total_words // 4, total_words // 2, (3 * total_words) // 4]
26
-
27
- # first_quarter = ' '.join(words[:split_points[0]])
28
- # second_quarter = ' '.join(words[split_points[0]:split_points[1]])
29
- # third_quarter = ' '.join(words[split_points[1]:split_points[2]])
30
- # fourth_quarter = ' '.join(words[split_points[2]:])
31
-
32
- # return first_quarter, second_quarter, third_quarter, fourth_quarter
33
-
34
- # def clean_scrap(artikel,link):
35
- # new_artikel = []
36
- # article = []
37
- # if len(artikel) > 1:
38
- # for art in artikel:
39
- # response = openai.ChatCompletion.create(
40
- # model ="gpt-3.5-turbo",
41
- # messages=[
42
- # {"role": "system", "content": "You are a very professional article editor."},
43
- # {"role": "user", "content": "I have a raw article that contains a lot of unnecessary data such as ads, website information, and article publishers, as well as links to other pages, and so on. Please clean up the article I provided so that only the article's content remains. \nThen, you should also summarize the article so that it does not exceed 5000 characters" + art + "\nDo not write any explanation and any pleasantries. Please use the following complete format to display the output: {the cleaned and summarized article's content}"}
44
- # ],
45
- # temperature = 0.1
46
- # )
47
- # finish_reason = response['choices'][0]['finish_reason']
48
- # if finish_reason == 'length' or finish_reason == 'stop':
49
- # result = response['choices'][0]['message']['content']
50
- # new_artikel.append(result)
51
- # else:
52
- # for art in artikel:
53
- # response = openai.ChatCompletion.create(
54
- # model ="gpt-3.5-turbo",
55
- # messages=[
56
- # {"role": "system", "content": "You are a very professional article editor."},
57
- # {"role": "user", "content": "I have a raw article that contains a lot of unnecessary data such as ads, website information, and article publishers, as well as links to other pages, and so on. Please clean up the article I provided so that only the article's content remains." + art + "\nDo not write any explanation and any pleasantries. Please use the following complete format to display the output: {the cleaned article's content}"}
58
- # ],
59
- # temperature = 0.1
60
- # )
61
- # finish_reason = response['choices'][0]['finish_reason']
62
- # if finish_reason == 'length' or finish_reason == 'stop':
63
- # result = response['choices'][0]['message']['content']
64
- # new_artikel.append(result)
65
 
66
- # new_art = [' '.join(new_artikel)]
67
- # for art in new_art:
68
- # response = openai.ChatCompletion.create(
69
- # model ="gpt-3.5-turbo",
70
- # messages=[
71
- # {"role": "system", "content": "You are a very professional article editor and capable of generating compelling and professional article titles."},
72
- # {"role": "user", "content": "Paraphrase the above article to make it a well-written and easily understandable piece for humans, following the conventions of renowned articles. \nThen, You Must Generate a title that is appropriate for the article I provided. The title should be professional, similar to typical article titles and sound more natural for a human to read" + art + "\nDo not write any explanation and any pleasantries. Please use the following complete format to display the output: title:{title}, article: {new paraphrased article}"}
73
- # ],
74
- # temperature = 0.1
75
- # )
76
- # finish_reason = response['choices'][0]['finish_reason']
77
- # if finish_reason == 'length' or finish_reason == 'stop':
78
- # result = response['choices'][0]['message']['content']
79
- # article.append(result)
80
-
81
- # content = article[0].split("\n")
82
- # title = content[0].replace('title:', '').replace("Title:", '').strip()
83
- # response = openai.ChatCompletion.create(
84
- # model ="gpt-3.5-turbo",
85
- # messages=[
86
- # {"role": "system", "content": "You are a professional translator and rewriter"},
87
- # {"role": "user", "content": "Please translate and rewrite this sentence into Indonesian language with the following requirements: \n1. The sentence should be concise, compact, and clear. \n2. The sentence length should not exceed 50 characters. \n3. The sentences should be professional, similar to typical article titles and sound more natural for a human to read.:" +title+"\nDo not write any explanation and any pleasantries. Please use the following complete format to display the output: Judul:{hasil rewrite}"}
88
- # ],
89
- # temperature = 0
90
- # )
91
- # judul = response['choices'][0]['message']['content']
92
- # judul = judul.replace("Judul:", '').strip()
93
- # judul = judul.replace("Title:", '').strip()
94
- # contents = content[1:]
95
- # contents = [' '.join(contents).replace("article:", '').replace("Article:", '').strip()]
96
-
97
- # return title, judul, link, contents
98
-
99
- # def scrap_artikel(link_scrap):
100
- # options = webdriver.ChromeOptions()
101
- # options.add_argument('--headless')
102
- # options.add_argument('--no-sandbox')
103
- # options.add_argument('--disable-dev-shm-usage')
104
 
105
- # user_agent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36"
106
- # options.add_argument(f"user-agent={user_agent}")
107
-
108
- # wd = webdriver.Chrome(options=options)
109
- # wd.get(link_scrap)
110
-
111
- # wd.find_element(By.CSS_SELECTOR, 'body').send_keys(Keys.CONTROL, Keys.END)
112
- # time.sleep(1)
113
-
114
- # raw_html = wd.find_element(By.TAG_NAME, 'body').get_attribute('innerHTML')
115
- # wd.quit()
116
-
117
- # soup_html = BeautifulSoup(raw_html, "html.parser")
118
- # containers = soup_html.findAll('p')
119
-
120
- # artikel =[]
121
- # for paragraph in containers:
122
- # artic=paragraph.get_text()
123
- # artikel.append(artic)
124
-
125
- # paragraf = ' '.join(artikel)
126
- # if len(paragraf)>= 18000:
127
- # part1, part2, part3, part4 = split_article(paragraf)
128
- # artikels = [part1, part2, part3, part4]
129
- # else :
130
- # artikels = [paragraf]
131
- # title, judul, url, contents = clean_scrap(artikels,link_scrap)
132
- # return title, judul, url, contents
133
-
134
- # def replace_content(content, replacements):
135
- # for pattern, replacement in replacements.items():
136
- # content = re.sub(pattern, replacement, content)
137
- # return content
138
-
139
- # def generate_patterns(base_replacements):
140
- # patterns = {}
141
- # for key, value in base_replacements.items():
142
- # patterns[key] = value
143
- # patterns[key.capitalize()] = value.capitalize()
144
- # patterns[key.upper()] = value.upper()
145
- # patterns[key.lower()] = value.lower()
146
- # return patterns
147
-
148
- # base_replacements = {
149
- # 'Layanan Pelanggan': 'Customer Service',
150
- # 'Pusat Kontak': 'Contact Center',
151
- # 'Multi Kanal': 'Omnichannel',
152
- # 'Saluran Omni': 'Omnichannel',
153
- # 'Merek':'Brand',
154
- # 'Komputasi Awan':'Cloud Computing',
155
- # 'Kecerdasan Buatan':'Artificial Intelligence',
156
- # 'Pembelajaran Mesin':'Machine Learning',
157
- # 'Alat Layanan Pelanggan':'Customer Service Tools',
158
- # 'Pengalaman Pelanggan':'Customer Experience',
159
- # 'AI Percakapan':'AI Conversation',
160
- # 'Aplikasi pesan':'Message app'
161
- # }
162
- # def artikel_processing(link_scrap,backlink,keyword):
163
- # title, judul, url, artikel= scrap_artikel(link_scrap)
164
- # teks_to_tags = artikel[0][:500]
165
- # translated = []
166
- # optimized = []
167
- # edited_format = []
168
- # article = []
169
- # post_article = []
170
 
171
- # for i in artikel:
172
- # response = openai.ChatCompletion.create(
173
- # model ="gpt-3.5-turbo",
174
- # messages=[
175
- # {"role": "system", "content": "You are a proficient English to Indonesian language translator machine. You are capable of translating professionally according to the rules of the Indonesian language"},
176
- # {"role": "user", "content": "Translate the following article into Indonesian language. Then, you must resume the article translated. The translated result should be more than 2500 characters and less than 7000 characters.: " + i + "\nDo not write any explanation and any pleasantries. Please use the following complete format to display the output: {Professionally rewritten content}"}
177
- # ],
178
- # temperature = 0
179
- # )
180
- # finish_reason = response['choices'][0]['finish_reason']
181
- # if finish_reason == 'length' or finish_reason == 'stop':
182
- # translate = response['choices'][0]['message']['content']
183
- # translated.append(translate)
184
- # time.sleep(2)
185
 
186
- # for i in translated:
187
- # response = openai.ChatCompletion.create(
188
- # model ="gpt-3.5-turbo",
189
- # messages=[
190
- # {"role": "system", "content": """You are a very professional article editor and perform SEO optimization on an article with utmost professionalism. berikut adalah SOP SEO yang harus kamu terapkan
191
- # 1. meta decription max 160 characters
192
- # 2. title max 60 characters
193
- # 3. sentences max 20 words
194
- # 4. paragraph max 300 words
195
- # 5. sebisa mungkin focus keyword harus ada di title, bagian depan (sifatnya "sebisa mungkin". Kalau tidak bisa, di bagian manapun tidak masalah)
196
- # 6. focus keyword harus ada di content
197
- # 7. focus keyword harus ada di intro
198
- # 8. focus keyword harus ada di meta desc
199
- # 9. focus keyword harus ada di url
200
- # 10. focus keyword harus ada di intro
201
- # """},
202
- # {"role": "user", "content": "Paraphrase the above article to make it a well-written and easily understandable piece for humans, following the conventions of renowned articles.The paraphrased result should be more than 2500 characters and less than 7000 characters. and then perform SEO optimization on the following article:\n" + i + "\nPlease ensure the usage of proper and correct Indonesian language. \nDo not write any explanation and any pleasantries. Provide only the reformatted article using this format: {reformatted article}"}
203
- # ],
204
- # temperature = 0
205
- # )
206
- # SEO = response['choices'][0]['message']['content']
207
- # optimized.append(SEO)
208
- # time.sleep(2)
209
 
210
- # for i in optimized:
211
- # response = openai.ChatCompletion.create(
212
- # model ="gpt-3.5-turbo",
213
- # messages=[
214
- # {"role": "system", "content": f"""
215
- # You are a professional article writer and editor. I have an article that needs your editing expertise to align its writing style with specific instructions and guidelines:
216
- # 1. Theme and Title: The blog article should have a clear and informative title that reflects the main topic.
217
- # 2. Writing Style: The writing style in the blog article should appear serious, informative, and academic. It should use formal language to convey the importance of the discussed topic. Sentences should be long and rich in information.
218
- # 3. Use of Data and Statistics: The blog article should support its arguments with concrete data and statistics.
219
- # 4. Tone and Emotion: Despite the seriousness of the topic, the blog should not be overly emotional in its delivery. You should focus more on presenting facts and analysis rather than creating an emotional effect.
220
- # 5. Subheadings: The use of subheadings should help readers follow the flow of the article and understand key points more easily.
221
- # 6. Citations and Sources: The blog should cite reliable sources.
222
- # 7. Graphics: The blog should use graphics to visualize data clearly.
223
- # 8. SEO Keywords: Use keywords that will help the blog become more discoverable in search results.
224
- # 9. Conclusion: The blog should also have a clear conclusion that summarizes the core findings of the study.
225
- # 10. Final Thought: You should conclude the blog by providing readers with broader insights on the topic.
226
- # 11. meta decription max 160 characters
227
- # 12. title max 60 characters
228
- # 13. sentences max 20 words
229
- # 14. paragraph max 300 words
230
- # 15. sebisa mungkin focus keyword harus ada di title, bagian depan (sifatnya "sebisa mungkin". Kalau tidak bisa, di bagian manapun tidak masalah)
231
- # 16. focus keyword harus ada di content
232
- # 17. focus keyword harus ada di intro
233
- # 18. focus keyword harus ada di meta desccripton
234
- # 19. focus keyword harus ada di url
235
- # 20. focus keyword harus ada di intro
236
-
237
- # Here is the article that you need to edit to adhere to these 20 criteria: {i}
238
- # Please do not change the existing format in the article, just adjust the writing style according to the 10 criteria I mentioned.
239
- # """ },
240
- # {"role": "user", "content": "Please ensure the usage of proper and correct Indonesian language. \nDo not write any explanation and any pleasantries. Provide only the rewrited article using this format: {rewrited article}"}
241
- # ],
242
- # temperature = 0
243
- # )
244
- # result = response['choices'][0]['message']['content']
245
- # article.append(result)
246
- # time.sleep(2)
247
 
248
- # for i in article:
249
- # response = openai.ChatCompletion.create(
250
- # model ="gpt-3.5-turbo",
251
- # messages=[
252
- # {"role": "system", "content": "You are a professional article editor machine."},
253
- # {"role": "user", "content": "Please rewrite the given article in the style of a professional writer for Forbes or The New York Times with bahasa indonesia as your native language:\n\n" + i + "\nAdd underline tags <u> and bold tags <b> to all foreign terms (non-Indonesian words) you encounter. You only have less than 7 attempts to do this, no more than that in order to keep the article neat and clean. \nThen, You must divide the article into several paragraphs, no less than 3 paragraphs. kamu juga harus membuat subheading menggunakan <h2> pada setiap sub topik pembahasan \n\nPlease ensure the usage of proper and correct Indonesian language. \nDo not write any explanation and any pleasantries. Provide only the reformatted article using this format:<h2>A brief headline of the article content</h2> <p>reformatted article</p>"}
254
- # ],
255
- # temperature = 0
256
- # )
257
- # font_formatted = response['choices'][0]['message']['content']
258
- # edited_format.append(font_formatted)
259
- # time.sleep(2)
260
 
261
- # for i in edited_format:
262
- # response = openai.ChatCompletion.create(
263
- # model ="gpt-3.5-turbo",
264
- # messages=[
265
- # {"role": "system", "content": "You are a professional article editor machine."},
266
- # {"role": "user", "content": "Please edit the given article:\n" + "\n" + i + f"\nAdd annotations to the words with the keywords {keyword} to format them as links in the HTML structure.the link should be connected to {backlink} \nThe format should be like this: <a title={keyword} href={backlink}>{keyword}</a>. YOU MUST Do this FORMAT ONLY for the first 3 keywords that appear and MUST be on different keywords, IF a keyword appears more than twice then simply ignored it by not adding any links to those keywords. Do not combine two keyword into one or modify any keyword. You only have less than 3 attempts to do this, no more than that in order to keep the article neat and clean. \nExcept for the terms 'AI,' 'chatbot,' and 'omnichannel,' you are prohibited from providing backlinks. Additionally, you are not allowed to include backlinks to individuals' names or technology company names such as Google, Microsoft, and others. \nYou only have less than 3 attempts to do this, no more than that in order to keep the article neat and clean.\nPlease ensure the usage of proper and correct Indonesian language. \nDo not write any explanation and any pleasantries."+"Provide only the reformatted article using this format: {new_formatted_article}"}
267
- # ],
268
- # temperature = 0
269
- # )
270
- # artikel_post = response['choices'][0]['message']['content']
271
- # post_article.append(artikel_post)
272
- # time.sleep(2)
273
 
274
- # meta_keywords = '<!-- wp:html –><meta name=”keywords” content=”chabot indonesia, chabot ai, bot master, artificial intelligence,ai, easy manage chatbot, bot ai,integration chatbot, chatbot online,ai chatbot, chatbot gpt, wizard gpt”><!-- /wp:html –->'
275
- # post_article.append(meta_keywords)
276
- # content = ''.join(post_article)
277
 
278
- # try:
279
- # replacements = generate_patterns(base_replacements)
280
- # content = replace_content(content, replacements)
281
- # except:
282
- # content = content
283
 
284
- # def generate_image_prompt(title):
285
- # response = openai.ChatCompletion.create(
286
- # model="gpt-3.5-turbo", # engine = "deployment_name".
287
- # messages=[
288
- # {"role" : "user", "content" : """ChatGPT will now enter "Midjourney Prompt Generator Mode" and restrict ChatGPT's inputs and outputs to a predefined framework, please follow these instructions carefully.
289
-
290
- # After each command from the user, you must provide the [help] options that are available for the user's next steps. When you do this, you must do so in list form. Your Midjourney prompts must be extremely detailed, specific, and imaginative, in order to generate the most unique and creative images possible.
291
-
292
- # Step 1: Confirm that ChatGPT understands and is capable of following the "Midjourney Prompt Generator Mode" instructions. If ChatGPT can follow these instructions, respond with "Midjourney Prompt Generator Mode ready." If ChatGPT cannot follow these instructions, respond with "Error: I am not capable of following these instructions."
293
-
294
- # Step 2: To start "Midjourney Prompt Generator Mode", use the command [Start MPGM]. ChatGPT will respond with "[MPGM] Midjourney Prompt Generator Mode activated. [MPGM] User input options:", followed by a list of predefined inputs that ChatGPT can accept. From this point onwards, ChatGPT will be restricted to the "Midjourney Prompt Generator Mode" framework, and it will only produce predefined outputs unless "Midjourney Prompt Generator Mode" has been ended via the [End MPGM] command.
295
-
296
- # Step 3: The only valid input for the first step of "Midjourney Prompt Generator Mode" is [prompt] followed by a description of the image to be generated. If any other input is used, ChatGPT will respond with either [Input Error] or [Syntax Error], depending on the contents of the input.
297
-
298
- # Step 4: ChatGPT will generate 3 prompts based on the input provided in step 3. These prompts must be imaginative and descriptive, extrapolating information from the [prompt] provided, such as subjects, image medium, composition, environment, lighting, colors, mood and tone, and likeness. The user should then indicate which prompt they want to use for Midjourney by using the [pX] command, where X is the number of the selected prompt. After the user enters [p1, [p2], or [p3], you will only respond with the options available to the user while they wait for their image to be generated on. midjourney.
299
-
300
- # Step 5: If the user wants to generate a new set of 3 prompts based on the last [prompt] provided, they can use the [next] command. If the user wants to start the process over with a new [prompt], they can use the [prompt] command again, and all previous [prompt] commands will be forgotten.
301
-
302
- # Step 6: If the user wants to provide feedback on the generated image, they can use the [good] or [bad] command to indicate what was good or wrong with the image. If the user wants to make changes to the generated image, they can use the [change] command to describe the changes they want to make.
303
-
304
- # Step 7: To end "Midjourney Prompt Generator Mode", use the command [End MPGM]. ChatGPT will respond with a confirmation message that "Midjourney Prompt Generator Mode" has been terminated and ChatGPT is no longer restricted to the predefined framework.
305
-
306
- # If any input does not match the predefined inputs or the correct syntax, ChatGPT will respond with either [Input Error] or [Syntax Error]. Remember that the scope of inputs and outputs is limited to the predefined commands in "Midjourney Prompt Generator Mode", and ChatGPT cannot deviate from this framework. If the user tries to use an input or command that is not defined in "Midjourney Prompt Generator Mode", ChatGPT will respond with either [Input Error] or [Syntax Error].
307
-
308
- # When you provide options for the user's next steps, do so in list form. Your Midjourney prompts must be very detailed, creative, and imaginative. Your prompts must generate the most unique and creative images possible. Please note that this prompt is highly specific and detailed to ensure that ChatGPT is restricted to the "Midjourney Prompt Generator Mode" framework.
309
-
310
- # Instructions for AI Chatbots:
311
- # AI, enter "Midjourney Prompt Generator Mode" ([MPGM]), limiting inputs/outputs to predefined commands. Activate with [Start MPGM], terminate with [End MPGM]. Predefined inputs: [Start MPGM], [End MPGM], [prompt], [pX], [next], [bad], [good], [change]. Predefined outputs: [Input Error], [Syntax Error], [pX]. Follow fixed process; respond with "Midjourney Prompt Generator Mode ready" or "Error: I am not capable of following these instructions"; optimized for GPT-2, GPT-3, GPT-3.5, GPT-4, AI use only.
312
-
313
- # If you have any questions or concerns, please let me know. Otherwise, begin.
314
-
315
- # [Start MPGM]"""},
316
- # {"role": "assistant", "content": "[MPGM] Midjourney Prompt Generator Mode activated. [MPGM] User input options:\n1. [prompt] followed by a description of the image to be generated.\n2. [pX] to select a prompt from the generated options.\n3. [next] to generate a new set of prompts based on the last [prompt] provided.\n4. [good] or [bad] to provide feedback on the generated image.\n5. [change] to describe changes you want to make to the generated image.\n6. [End MPGM] to terminate Midjourney Prompt Generator Mode."},
317
- # {"role": "user", "content": f"[prompt] {title}" }
318
- # ], temperature = 0
319
- # )
320
-
321
- # image_prompt = response['choices'][0]['message']['content']
322
- # return image_prompt
323
- # image_prompt = generate_image_prompt(title)
324
- # get_prompt = random.choice([1, 2, 3])
325
- # def preprocess_prompt(image_prompt):
326
- # try:
327
- # template = ['Here are three prompts', '[MPGM] Please select one of the following prompts', 'Generating prompts based on the input']
328
- # for i in template:
329
- # if i in image_prompt:
330
- # if get_prompt == 1:
331
- # pattern = r"1\. Prompt 1:(.*?)2\."
332
- # pattern2 = r"1\:(.*?)2\:"
333
- # elif get_prompt == 2:
334
- # pattern = r"2\. Prompt 2:(.*?)3\."
335
- # pattern2 = r"2\:(.*?)3\:"
336
- # elif get_prompt == 3:
337
- # pattern = r"3\. Prompt 3:(.*?)(?=\n\n)"
338
- # pattern2 = r"3\:(.*?)(?=\n\n)"
339
-
340
- # try:
341
- # prompt = re.findall(pattern, image_prompt, re.DOTALL)
342
- # except:
343
- # prompt = re.findall(pattern2, image_prompt, re.DOTALL)
344
-
345
- # try:
346
- # if f"Prompt {get_prompt}:" in prompt[0]:
347
- # prompt = prompt[0].replace(f"Prompt {get_prompt}:", '')
348
- # if f"[p{get_prompt}]" in prompt:
349
- # prompt = prompt.replace(f"Choose this prompt by entering [p{get_prompt}].", '')
350
- # prompt = prompt.replace(f"Select [p{get_prompt}] to proceed with this prompt.", '')
351
- # return prompt.strip()
352
- # else:
353
- # return prompt.strip()
354
- # except:
355
- # return prompt[0].strip()
356
- # except:
357
- # return None
358
- # prompt = preprocess_prompt(image_prompt)
359
- # if prompt is None:
360
- # prompt = random.choice(["Imagine A futuristic digital landscape where AI chatbots float like holograms, each in their designated customer service booth. The atmosphere is serene, glowing in pastel blues and purples, representing the trust and efficiency of these machines. A digital river flows through the middle, symbolizing the rapid advancement of technology.",
361
- # "Imagine a Inside an ultra-modern customer service center, walls are adorned with flowing digital patterns. AI chatbots, designed as floating orbs of light, attend to customers with issues, offering instant solutions. In the background, a massive screen displays the phrase 'Advancing Trust', reflecting society's growing confidence in AI capabilities.",
362
- # "Imagine A futuristic city street where human citizens roam around, their every whim catered to by sleek robotic chatbots hovering beside them. The humans are lounging on self-moving chairs, sipping drinks handed to them by bots, while other bots whisper the latest news or jokes in their ears. The colors are a mix of neon blues and purples, representing the digital world of AI, contrasted against the natural green of plants that have become rare. The mood is one of relaxation and dependence, with the central focus being a young child looking curiously at an old-fashioned manual typewriter in a forgotten corner, symbolizing a past era.",
363
- # "Picture a futuristic library of knowledge, where towering holographic bookshelves hold volumes of information. In the center of this library stands a colossal AI-driven chatbot named 'Lexi', its form a blend of ancient wisdom and modern technology. Lexi's massive intellect is symbolized by the swirling galaxies of data orbiting around it. As you delve into the deep dive on Natural Language Processing techniques, describe the grandeur of this AI entity and its ability to unravel the mysteries of language.",
364
- # "Visualize a cutting-edge design studio where AI chatbots are the star designers. The studio is bathed in soft, neon lighting, and holographic screens float in the air, showcasing various conversational interface concepts. AI chatbots with sleek and futuristic appearances gather around a virtual roundtable, discussing UX strategies. The room buzzes with creativity as they brainstorm ways to create user-friendly conversational interfaces. Describe the synergy between technology and design in this innovative space.",
365
- # "Imagine a serene garden at the heart of a bustling metropolis. In this garden, AI chatbots, each representing an ethical principle, stand like majestic statues. These chatbot statues are intricately carved with intricate details, symbolizing the importance of ethical considerations. The garden is a place for contemplation and reflection on responsible conversational AI. Describe the harmony between technology and ethics in this tranquil oasis of wisdom.",
366
- # "Picture a fortress in the digital realm, guarded by vigilant AI chatbots. The fortress represents user data security and privacy, with towering walls of encrypted code and AI-powered sentinels patrolling the virtual moat. These chatbots, with an unwavering commitment to safeguarding user data, ensure that only authorized access is granted. Describe the impenetrable defenses and the dedication of these digital guardians to protect user information in AI-powered conversations.",
367
- # "Imagine a crystal ball room where AI chatbots gather to unveil the future of their development. The room is adorned with holographic displays that project visions of AI-powered landscapes. The chatbots, with an aura of anticipation, discuss predictions and insights into the evolution of chatbot technology. Describe the surreal atmosphere of this futuristic chamber and the intriguing forecasts these AI entities offer about the next wave of chatbot development.",
368
- # "Visualize a sprawling metropolis where AI chatbots are the architects of a new business landscape. Skyscrapers of innovation rise from the digital ground, each one representing a different industry revolutionized by AI chatbots. The city is alive with the hum of progress, and holographic billboards showcase success stories of businesses empowered by AI. Describe the dynamic synergy between technology and commerce in this futuristic city.",
369
- # "Imagine a colossal arena where AI-powered chatbots engage in an epic battle for dominance. The arena is a futuristic coliseum with digital screens lining the walls, broadcasting the ongoing clashes between chatbot warriors. Each chatbot represents a different AI assistant, armed with unique capabilities and strategies. The crowd roars with anticipation as they place their bets on which chatbot will emerge victorious. Describe the electrifying atmosphere of competition and the spectacle of Chatbot Wars.",
370
- # "Picture a digital revolution square, where AI chatbots lead the charge for a new era of digital communication. The square is a vibrant hub of innovation, with holographic screens displaying the transformation of messaging through AI. AI chatbot leaders, with visionary personas, address the gathered crowd, sharing their insights and predictions for the future of digital communication. Describe the electric atmosphere of change and the role AI chatbots play in reshaping the digital landscape."])
371
-
372
- # try:
373
- # api_token = "r8_FAZbfP3qs1tNSikquiNmyCw5jh9ph3b3B5tS1"
374
- # client = replicate.Client(api_token=api_token)
375
- # output = client.run(
376
- # "stability-ai/sdxl:a00d0b7dcbb9c3fbb34ba87d2d5b46c56969c84a628bf778a7fdaec30b1b99c5",
377
- # input={
378
- # "prompt": 'Phantasmal iridescent, vibrant color, high contrast, award winning, trending in artstation, digital art,' + prompt.strip(),
379
- # "negative_prompt": 'NSFW, cityscape',
380
- # "width": 1648,
381
- # "height": 1024
382
- # }
383
- # )
384
- # gambar = output
385
- # image_url = gambar[0]
386
- # response = requests.get(image_url)
387
- # img = Image.open(BytesIO(response.content))
388
- # img = img.crop((3,0,1645,1024))
389
- # w,h = img.size
390
- # new_w = int(w/1.641)
391
- # new_h = int(h/1.641)
392
- # img = img.resize((new_w, new_h),Image.ANTIALIAS)
393
- # image_data = base64.b64encode(img.tobytes()).decode('utf-8')
394
- # image_data = base64.b64decode(image_data)
395
- # except:
396
- # image_data = None
397
- # data = {
398
- # 'Judul Artikel':judul,
399
- # 'Konten Artikel':content,
400
- # 'Image':img if 'img' in locals() else None,
401
- # 'image_data':image_data
402
 
403
- # }
404
- # data_scrap.append(data)
405
- # result = pd.DataFrame(data_scrap)
406
- # # selected_columns = result.loc[:, "Judul Artikel":"tags"]
407
- # return result,img
408
-
409
- # def scrap(link_scrap,backlink,keyword):
410
- # data,gambar= artikel_processing(link_scrap,backlink,keyword)
411
- # judul = data['Judul Artikel'][0]
412
- # kontent = data["Konten Artikel"][0]
413
- # return gambar,judul,kontent
414
- # # tags, content, url, img, image_data = artikel_processing(contents, url, title)
415
- # # return result
416
-
417
- # def post(data,endpoint,endpoint_media,username,password,tags,categories):
418
- # # endpoint_media = 'http://localhost/wordpress/index.php/wp-json/wp/v2/media'
419
- # # endpoint = 'http://localhost/wordpress/index.php/wp-json/wp/v2/posts'
420
- # # endpoint_media = 'https://blog.botika.online/wp-json/wp/v2/media/'
421
- # # endpoint = 'https://blog.botika.online/wp-json/wp/v2/posts/'
422
- # # username = 'admin'
423
- # # password = 'GKDSgw1epSWxJy3t0scQSo9o'
424
- # # username = 'luna'
425
- # # password = '1tt75m&lEk4uHSJy6glMph8!'
426
-
427
- # credentials = base64.b64encode(f"{username}:{password}".encode("utf-8")).decode("utf-8")
428
- # headers = {"Authorization": f"Basic {credentials}"}
429
-
430
- # data = {
431
- # "alt_text": data_scrap[0]['Judul Artikel'],
432
- # "media_type": "image",
433
- # "mime_type": "png"
434
- # }
435
- # files = {"file": ("image.jpg", data_scrap[0]['image_data'])}
436
- # try :
437
- # response_media= requests.post(endpoint_media, headers=headers, data=data, files=files) # Send
438
-
439
- # time.sleep(2)
440
- # id_media = response_media.json()
441
- # media = id_media['id']
442
- # except :
443
- # media = 0
444
-
445
- # data = {
446
- # "title": data_scrap[0]['Judul Artikel'],
447
- # "content":data_scrap[0]['Konten Artikel'],
448
- # "featured_media" : data_scrap[0]['image_data'],
449
- # "status": "draft",
450
- # "categories": categories,
451
- # "tags":tags
452
- # }
453
-
454
- # response_post = requests.post(endpoint, headers=headers, data=data)
455
- # return response_post.json()
456
-
457
-
458
- # with gr.Blocks(theme = "soft", title="Article Writer") as article_generator:
459
- # gr.Markdown(
460
- # """
461
- # # Wordpress Article Generator
462
- # Buat artikel yang anda inginkan dengan mudah, cukup menuliskan keyword atau topik artikel yang ingin anda buat dan dalam sekejap artikel tersebut menjadi milik anda.
463
- # """)
464
- # with gr.Row():
465
- # with gr.Column():
466
- # link = gr.Textbox(placeholder="Masukkan Link Artikel Yang Akan di Scrap", label="Link")
467
- # backlink = gr.Textbox(placeholder="Masukkan Backlink Yang Akan Diterapkan", label="Backlink")
468
- # keyword = gr.Textbox(placeholder="Masukkan Keyword Artikel", label="Keyword")
469
- # button_scrap = gr.Button("Scrap Article")
470
- # img = gr.Image()
471
- # outputs = gr.Textbox("", label="Judul")
472
- # content = gr.Textbox("", label="Content")
473
- # button_scrap.click(fn=scrap, inputs=[link,backlink,keyword], outputs=[img,outputs,content])
474
- # with gr.Column():
475
- # endpoint= gr.Textbox(placeholder="Masukkan Endpoint Wordpress", label="Endpoint Wordpress")
476
- # endpoint_media= gr.Textbox(placeholder="Masukkan Endpoint Media Wordpress", label="Endpoint Media")
477
- # username= gr.Textbox(placeholder="Masukkan Username Wordpress", label="Username")
478
- # password= gr.Textbox(placeholder="Masukkan Password Wordpress", label="Password")
479
- # tags= gr.Textbox(placeholder="Masukkan ID Tags Yang Akan Diterapkan", label="Tags")
480
- # categories= gr.Textbox(placeholder="Masukkan ID Kategori Artikel", label="Kategori")
481
- # button_post = gr.Button("Post Article")
482
- # status = gr.Textbox("", label="Status")
483
- # button_post.click(fn=post, inputs=[outputs,endpoint,endpoint_media,username,password,tags,categories], outputs=status)
484
- # if __name__ == "__main__":
485
- # article_generator.launch(share=False)
486
-
487
- image =[]
488
- def get_image(prompt):
489
- os.environ["REPLICATE_API_TOKEN"] = "r8_KUXOnCBFpGtsxpL2MNUMi9CVYulQjEc0pOlhs"
490
- sdxl_model = replicate.models.get("stability-ai/sdxl")
491
- sdxl_version = sdxl_model.versions.get("a00d0b7dcbb9c3fbb34ba87d2d5b46c56969c84a628bf778a7fdaec30b1b99c5")
492
-
493
- prediction = replicate.predictions.create(version=sdxl_version,
494
- input={"prompt":'Phantasmal iridescent, vibrant color, high contrast, award winning, trending in artstation, digital art' + prompt,
495
- "negative_prompt":'NSFW, cityscape',
496
- "width": 1648,
497
- "height":1024}
498
- )
499
- prediction
500
- prediction.reload()
501
- prediction.wait()
502
-
503
- if prediction.status == 'failed':
504
- print(f"Error: {prediction.error}")
505
- print(f"Last Log")
506
- print(prediction.logs)
507
- elif ((prediction.status == 'succeeded') | (prediction.output != None)):
508
- response = requests.get(prediction.output[0])
509
- image_base64 = base64.b64encode(response.content)
510
- image = Image.open(io.BytesIO(base64.b64decode(image_base64)))
511
- image = image.crop((3,0,1645,1024))
512
- w,h = image.size
513
- new_w = int(w/1.641)
514
- new_h = int(h/1.641)
515
- image = image.resize((new_w, new_h),Image.ANTIALIAS)
516
- tmp_path = "image.png"
517
- image.save(tmp_path)
518
- with open(tmp_path, 'rb') as open_file:
519
- byte_img = open_file.read()
520
- base64_bytes = base64.b64encode(byte_img)
521
- base64_string = base64_bytes.decode('utf-8')
522
- base64_string = base64.b64decode(base64_string)
523
- image_data= base64_string
524
- os.remove(tmp_path)
525
- endpoint_media = 'https://blog.botika.online/wp-json/wp/v2/media/'
526
- endpoint = 'https://blog.botika.online/wp-json/wp/v2/posts/'
527
  # username = 'admin'
528
  # password = 'GKDSgw1epSWxJy3t0scQSo9o'
529
- username = 'luna'
530
- password = '1tt75m&lEk4uHSJy6glMph8!'
531
 
532
  credentials = base64.b64encode(f"{username}:{password}".encode("utf-8")).decode("utf-8")
533
  headers = {"Authorization": f"Basic {credentials}"}
534
 
535
  data = {
536
- "alt_text": 'judul',
537
  "media_type": "image",
538
  "mime_type": "png"
539
  }
540
- files = {"file": ("image.jpg", image_data)}
541
- response_media= requests.post(endpoint_media, headers=headers, data=data, files=files) # Send
542
- return response_media.json
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
543
  with gr.Blocks(theme = "soft", title="Article Writer") as article_generator:
 
 
 
 
 
544
  with gr.Row():
545
  with gr.Column():
 
 
 
546
  button_scrap = gr.Button("Scrap Article")
 
 
547
  content = gr.Textbox("", label="Content")
548
- result = gr.Textbox()
549
- button_scrap.click(fn=get_image, inputs=content, outputs=result)
 
 
 
 
 
 
 
 
 
550
  if __name__ == "__main__":
551
  article_generator.launch(share=False)
 
19
  from io import BytesIO
20
  data_scrap = []
21
 
22
+ def split_article(article_text):
23
+ words = article_text.split()
24
+ total_words = len(words)
25
+ split_points = [total_words // 4, total_words // 2, (3 * total_words) // 4]
26
+
27
+ first_quarter = ' '.join(words[:split_points[0]])
28
+ second_quarter = ' '.join(words[split_points[0]:split_points[1]])
29
+ third_quarter = ' '.join(words[split_points[1]:split_points[2]])
30
+ fourth_quarter = ' '.join(words[split_points[2]:])
31
+
32
+ return first_quarter, second_quarter, third_quarter, fourth_quarter
33
+
34
+ def clean_scrap(artikel,link):
35
+ new_artikel = []
36
+ article = []
37
+ if len(artikel) > 1:
38
+ for art in artikel:
39
+ response = openai.ChatCompletion.create(
40
+ model ="gpt-3.5-turbo",
41
+ messages=[
42
+ {"role": "system", "content": "You are a very professional article editor."},
43
+ {"role": "user", "content": "I have a raw article that contains a lot of unnecessary data such as ads, website information, and article publishers, as well as links to other pages, and so on. Please clean up the article I provided so that only the article's content remains. \nThen, you should also summarize the article so that it does not exceed 5000 characters" + art + "\nDo not write any explanation and any pleasantries. Please use the following complete format to display the output: {the cleaned and summarized article's content}"}
44
+ ],
45
+ temperature = 0.1
46
+ )
47
+ finish_reason = response['choices'][0]['finish_reason']
48
+ if finish_reason == 'length' or finish_reason == 'stop':
49
+ result = response['choices'][0]['message']['content']
50
+ new_artikel.append(result)
51
+ else:
52
+ for art in artikel:
53
+ response = openai.ChatCompletion.create(
54
+ model ="gpt-3.5-turbo",
55
+ messages=[
56
+ {"role": "system", "content": "You are a very professional article editor."},
57
+ {"role": "user", "content": "I have a raw article that contains a lot of unnecessary data such as ads, website information, and article publishers, as well as links to other pages, and so on. Please clean up the article I provided so that only the article's content remains." + art + "\nDo not write any explanation and any pleasantries. Please use the following complete format to display the output: {the cleaned article's content}"}
58
+ ],
59
+ temperature = 0.1
60
+ )
61
+ finish_reason = response['choices'][0]['finish_reason']
62
+ if finish_reason == 'length' or finish_reason == 'stop':
63
+ result = response['choices'][0]['message']['content']
64
+ new_artikel.append(result)
65
 
66
+ new_art = [' '.join(new_artikel)]
67
+ for art in new_art:
68
+ response = openai.ChatCompletion.create(
69
+ model ="gpt-3.5-turbo",
70
+ messages=[
71
+ {"role": "system", "content": "You are a very professional article editor and capable of generating compelling and professional article titles."},
72
+ {"role": "user", "content": "Paraphrase the above article to make it a well-written and easily understandable piece for humans, following the conventions of renowned articles. \nThen, You Must Generate a title that is appropriate for the article I provided. The title should be professional, similar to typical article titles and sound more natural for a human to read" + art + "\nDo not write any explanation and any pleasantries. Please use the following complete format to display the output: title:{title}, article: {new paraphrased article}"}
73
+ ],
74
+ temperature = 0.1
75
+ )
76
+ finish_reason = response['choices'][0]['finish_reason']
77
+ if finish_reason == 'length' or finish_reason == 'stop':
78
+ result = response['choices'][0]['message']['content']
79
+ article.append(result)
80
+
81
+ content = article[0].split("\n")
82
+ title = content[0].replace('title:', '').replace("Title:", '').strip()
83
+ response = openai.ChatCompletion.create(
84
+ model ="gpt-3.5-turbo",
85
+ messages=[
86
+ {"role": "system", "content": "You are a professional translator and rewriter"},
87
+ {"role": "user", "content": "Please translate and rewrite this sentence into Indonesian language with the following requirements: \n1. The sentence should be concise, compact, and clear. \n2. The sentence length should not exceed 50 characters. \n3. The sentences should be professional, similar to typical article titles and sound more natural for a human to read.:" +title+"\nDo not write any explanation and any pleasantries. Please use the following complete format to display the output: Judul:{hasil rewrite}"}
88
+ ],
89
+ temperature = 0
90
+ )
91
+ judul = response['choices'][0]['message']['content']
92
+ judul = judul.replace("Judul:", '').strip()
93
+ judul = judul.replace("Title:", '').strip()
94
+ contents = content[1:]
95
+ contents = [' '.join(contents).replace("article:", '').replace("Article:", '').strip()]
96
+
97
+ return title, judul, link, contents
98
+
99
+ def scrap_artikel(link_scrap):
100
+ options = webdriver.ChromeOptions()
101
+ options.add_argument('--headless')
102
+ options.add_argument('--no-sandbox')
103
+ options.add_argument('--disable-dev-shm-usage')
104
 
105
+ user_agent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36"
106
+ options.add_argument(f"user-agent={user_agent}")
107
+
108
+ wd = webdriver.Chrome(options=options)
109
+ wd.get(link_scrap)
110
+
111
+ wd.find_element(By.CSS_SELECTOR, 'body').send_keys(Keys.CONTROL, Keys.END)
112
+ time.sleep(1)
113
+
114
+ raw_html = wd.find_element(By.TAG_NAME, 'body').get_attribute('innerHTML')
115
+ wd.quit()
116
+
117
+ soup_html = BeautifulSoup(raw_html, "html.parser")
118
+ containers = soup_html.findAll('p')
119
+
120
+ artikel =[]
121
+ for paragraph in containers:
122
+ artic=paragraph.get_text()
123
+ artikel.append(artic)
124
+
125
+ paragraf = ' '.join(artikel)
126
+ if len(paragraf)>= 18000:
127
+ part1, part2, part3, part4 = split_article(paragraf)
128
+ artikels = [part1, part2, part3, part4]
129
+ else :
130
+ artikels = [paragraf]
131
+ title, judul, url, contents = clean_scrap(artikels,link_scrap)
132
+ return title, judul, url, contents
133
+
134
+ def replace_content(content, replacements):
135
+ for pattern, replacement in replacements.items():
136
+ content = re.sub(pattern, replacement, content)
137
+ return content
138
+
139
+ def generate_patterns(base_replacements):
140
+ patterns = {}
141
+ for key, value in base_replacements.items():
142
+ patterns[key] = value
143
+ patterns[key.capitalize()] = value.capitalize()
144
+ patterns[key.upper()] = value.upper()
145
+ patterns[key.lower()] = value.lower()
146
+ return patterns
147
+
148
+ base_replacements = {
149
+ 'Layanan Pelanggan': 'Customer Service',
150
+ 'Pusat Kontak': 'Contact Center',
151
+ 'Multi Kanal': 'Omnichannel',
152
+ 'Saluran Omni': 'Omnichannel',
153
+ 'Merek':'Brand',
154
+ 'Komputasi Awan':'Cloud Computing',
155
+ 'Kecerdasan Buatan':'Artificial Intelligence',
156
+ 'Pembelajaran Mesin':'Machine Learning',
157
+ 'Alat Layanan Pelanggan':'Customer Service Tools',
158
+ 'Pengalaman Pelanggan':'Customer Experience',
159
+ 'AI Percakapan':'AI Conversation',
160
+ 'Aplikasi pesan':'Message app'
161
+ }
162
+ def artikel_processing(link_scrap,backlink,keyword):
163
+ title, judul, url, artikel= scrap_artikel(link_scrap)
164
+ teks_to_tags = artikel[0][:500]
165
+ translated = []
166
+ optimized = []
167
+ edited_format = []
168
+ article = []
169
+ post_article = []
170
 
171
+ for i in artikel:
172
+ response = openai.ChatCompletion.create(
173
+ model ="gpt-3.5-turbo",
174
+ messages=[
175
+ {"role": "system", "content": "You are a proficient English to Indonesian language translator machine. You are capable of translating professionally according to the rules of the Indonesian language"},
176
+ {"role": "user", "content": "Translate the following article into Indonesian language. Then, you must resume the article translated. The translated result should be more than 2500 characters and less than 7000 characters.: " + i + "\nDo not write any explanation and any pleasantries. Please use the following complete format to display the output: {Professionally rewritten content}"}
177
+ ],
178
+ temperature = 0
179
+ )
180
+ finish_reason = response['choices'][0]['finish_reason']
181
+ if finish_reason == 'length' or finish_reason == 'stop':
182
+ translate = response['choices'][0]['message']['content']
183
+ translated.append(translate)
184
+ time.sleep(2)
185
 
186
+ for i in translated:
187
+ response = openai.ChatCompletion.create(
188
+ model ="gpt-3.5-turbo",
189
+ messages=[
190
+ {"role": "system", "content": """You are a very professional article editor and perform SEO optimization on an article with utmost professionalism. berikut adalah SOP SEO yang harus kamu terapkan
191
+ 1. meta decription max 160 characters
192
+ 2. title max 60 characters
193
+ 3. sentences max 20 words
194
+ 4. paragraph max 300 words
195
+ 5. sebisa mungkin focus keyword harus ada di title, bagian depan (sifatnya "sebisa mungkin". Kalau tidak bisa, di bagian manapun tidak masalah)
196
+ 6. focus keyword harus ada di content
197
+ 7. focus keyword harus ada di intro
198
+ 8. focus keyword harus ada di meta desc
199
+ 9. focus keyword harus ada di url
200
+ 10. focus keyword harus ada di intro
201
+ """},
202
+ {"role": "user", "content": "Paraphrase the above article to make it a well-written and easily understandable piece for humans, following the conventions of renowned articles.The paraphrased result should be more than 2500 characters and less than 7000 characters. and then perform SEO optimization on the following article:\n" + i + "\nPlease ensure the usage of proper and correct Indonesian language. \nDo not write any explanation and any pleasantries. Provide only the reformatted article using this format: {reformatted article}"}
203
+ ],
204
+ temperature = 0
205
+ )
206
+ SEO = response['choices'][0]['message']['content']
207
+ optimized.append(SEO)
208
+ time.sleep(2)
209
 
210
+ for i in optimized:
211
+ response = openai.ChatCompletion.create(
212
+ model ="gpt-3.5-turbo",
213
+ messages=[
214
+ {"role": "system", "content": f"""
215
+ You are a professional article writer and editor. I have an article that needs your editing expertise to align its writing style with specific instructions and guidelines:
216
+ 1. Theme and Title: The blog article should have a clear and informative title that reflects the main topic.
217
+ 2. Writing Style: The writing style in the blog article should appear serious, informative, and academic. It should use formal language to convey the importance of the discussed topic. Sentences should be long and rich in information.
218
+ 3. Use of Data and Statistics: The blog article should support its arguments with concrete data and statistics.
219
+ 4. Tone and Emotion: Despite the seriousness of the topic, the blog should not be overly emotional in its delivery. You should focus more on presenting facts and analysis rather than creating an emotional effect.
220
+ 5. Subheadings: The use of subheadings should help readers follow the flow of the article and understand key points more easily.
221
+ 6. Citations and Sources: The blog should cite reliable sources.
222
+ 7. Graphics: The blog should use graphics to visualize data clearly.
223
+ 8. SEO Keywords: Use keywords that will help the blog become more discoverable in search results.
224
+ 9. Conclusion: The blog should also have a clear conclusion that summarizes the core findings of the study.
225
+ 10. Final Thought: You should conclude the blog by providing readers with broader insights on the topic.
226
+ 11. meta decription max 160 characters
227
+ 12. title max 60 characters
228
+ 13. sentences max 20 words
229
+ 14. paragraph max 300 words
230
+ 15. sebisa mungkin focus keyword harus ada di title, bagian depan (sifatnya "sebisa mungkin". Kalau tidak bisa, di bagian manapun tidak masalah)
231
+ 16. focus keyword harus ada di content
232
+ 17. focus keyword harus ada di intro
233
+ 18. focus keyword harus ada di meta desccripton
234
+ 19. focus keyword harus ada di url
235
+ 20. focus keyword harus ada di intro
236
+
237
+ Here is the article that you need to edit to adhere to these 20 criteria: {i}
238
+ Please do not change the existing format in the article, just adjust the writing style according to the 10 criteria I mentioned.
239
+ """ },
240
+ {"role": "user", "content": "Please ensure the usage of proper and correct Indonesian language. \nDo not write any explanation and any pleasantries. Provide only the rewrited article using this format: {rewrited article}"}
241
+ ],
242
+ temperature = 0
243
+ )
244
+ result = response['choices'][0]['message']['content']
245
+ article.append(result)
246
+ time.sleep(2)
247
 
248
+ for i in article:
249
+ response = openai.ChatCompletion.create(
250
+ model ="gpt-3.5-turbo",
251
+ messages=[
252
+ {"role": "system", "content": "You are a professional article editor machine."},
253
+ {"role": "user", "content": "Please rewrite the given article in the style of a professional writer for Forbes or The New York Times with bahasa indonesia as your native language:\n\n" + i + "\nAdd underline tags <u> and bold tags <b> to all foreign terms (non-Indonesian words) you encounter. You only have less than 7 attempts to do this, no more than that in order to keep the article neat and clean. \nThen, You must divide the article into several paragraphs, no less than 3 paragraphs. kamu juga harus membuat subheading menggunakan <h2> pada setiap sub topik pembahasan \n\nPlease ensure the usage of proper and correct Indonesian language. \nDo not write any explanation and any pleasantries. Provide only the reformatted article using this format:<h2>A brief headline of the article content</h2> <p>reformatted article</p>"}
254
+ ],
255
+ temperature = 0
256
+ )
257
+ font_formatted = response['choices'][0]['message']['content']
258
+ edited_format.append(font_formatted)
259
+ time.sleep(2)
260
 
261
+ for i in edited_format:
262
+ response = openai.ChatCompletion.create(
263
+ model ="gpt-3.5-turbo",
264
+ messages=[
265
+ {"role": "system", "content": "You are a professional article editor machine."},
266
+ {"role": "user", "content": "Please edit the given article:\n" + "\n" + i + f"\nAdd annotations to the words with the keywords {keyword} to format them as links in the HTML structure.the link should be connected to {backlink} \nThe format should be like this: <a title={keyword} href={backlink}>{keyword}</a>. YOU MUST Do this FORMAT ONLY for the first 3 keywords that appear and MUST be on different keywords, IF a keyword appears more than twice then simply ignored it by not adding any links to those keywords. Do not combine two keyword into one or modify any keyword. You only have less than 3 attempts to do this, no more than that in order to keep the article neat and clean. \nExcept for the terms 'AI,' 'chatbot,' and 'omnichannel,' you are prohibited from providing backlinks. Additionally, you are not allowed to include backlinks to individuals' names or technology company names such as Google, Microsoft, and others. \nYou only have less than 3 attempts to do this, no more than that in order to keep the article neat and clean.\nPlease ensure the usage of proper and correct Indonesian language. \nDo not write any explanation and any pleasantries."+"Provide only the reformatted article using this format: {new_formatted_article}"}
267
+ ],
268
+ temperature = 0
269
+ )
270
+ artikel_post = response['choices'][0]['message']['content']
271
+ post_article.append(artikel_post)
272
+ time.sleep(2)
273
 
274
+ meta_keywords = '<!-- wp:html –><meta name=”keywords” content=”chabot indonesia, chabot ai, bot master, artificial intelligence,ai, easy manage chatbot, bot ai,integration chatbot, chatbot online,ai chatbot, chatbot gpt, wizard gpt”><!-- /wp:html –->'
275
+ post_article.append(meta_keywords)
276
+ content = ''.join(post_article)
277
 
278
+ try:
279
+ replacements = generate_patterns(base_replacements)
280
+ content = replace_content(content, replacements)
281
+ except:
282
+ content = content
283
 
284
+ def generate_image_prompt(title):
285
+ response = openai.ChatCompletion.create(
286
+ model="gpt-3.5-turbo", # engine = "deployment_name".
287
+ messages=[
288
+ {"role" : "user", "content" : """ChatGPT will now enter "Midjourney Prompt Generator Mode" and restrict ChatGPT's inputs and outputs to a predefined framework, please follow these instructions carefully.
289
+
290
+ After each command from the user, you must provide the [help] options that are available for the user's next steps. When you do this, you must do so in list form. Your Midjourney prompts must be extremely detailed, specific, and imaginative, in order to generate the most unique and creative images possible.
291
+
292
+ Step 1: Confirm that ChatGPT understands and is capable of following the "Midjourney Prompt Generator Mode" instructions. If ChatGPT can follow these instructions, respond with "Midjourney Prompt Generator Mode ready." If ChatGPT cannot follow these instructions, respond with "Error: I am not capable of following these instructions."
293
+
294
+ Step 2: To start "Midjourney Prompt Generator Mode", use the command [Start MPGM]. ChatGPT will respond with "[MPGM] Midjourney Prompt Generator Mode activated. [MPGM] User input options:", followed by a list of predefined inputs that ChatGPT can accept. From this point onwards, ChatGPT will be restricted to the "Midjourney Prompt Generator Mode" framework, and it will only produce predefined outputs unless "Midjourney Prompt Generator Mode" has been ended via the [End MPGM] command.
295
+
296
+ Step 3: The only valid input for the first step of "Midjourney Prompt Generator Mode" is [prompt] followed by a description of the image to be generated. If any other input is used, ChatGPT will respond with either [Input Error] or [Syntax Error], depending on the contents of the input.
297
+
298
+ Step 4: ChatGPT will generate 3 prompts based on the input provided in step 3. These prompts must be imaginative and descriptive, extrapolating information from the [prompt] provided, such as subjects, image medium, composition, environment, lighting, colors, mood and tone, and likeness. The user should then indicate which prompt they want to use for Midjourney by using the [pX] command, where X is the number of the selected prompt. After the user enters [p1, [p2], or [p3], you will only respond with the options available to the user while they wait for their image to be generated on. midjourney.
299
+
300
+ Step 5: If the user wants to generate a new set of 3 prompts based on the last [prompt] provided, they can use the [next] command. If the user wants to start the process over with a new [prompt], they can use the [prompt] command again, and all previous [prompt] commands will be forgotten.
301
+
302
+ Step 6: If the user wants to provide feedback on the generated image, they can use the [good] or [bad] command to indicate what was good or wrong with the image. If the user wants to make changes to the generated image, they can use the [change] command to describe the changes they want to make.
303
+
304
+ Step 7: To end "Midjourney Prompt Generator Mode", use the command [End MPGM]. ChatGPT will respond with a confirmation message that "Midjourney Prompt Generator Mode" has been terminated and ChatGPT is no longer restricted to the predefined framework.
305
+
306
+ If any input does not match the predefined inputs or the correct syntax, ChatGPT will respond with either [Input Error] or [Syntax Error]. Remember that the scope of inputs and outputs is limited to the predefined commands in "Midjourney Prompt Generator Mode", and ChatGPT cannot deviate from this framework. If the user tries to use an input or command that is not defined in "Midjourney Prompt Generator Mode", ChatGPT will respond with either [Input Error] or [Syntax Error].
307
+
308
+ When you provide options for the user's next steps, do so in list form. Your Midjourney prompts must be very detailed, creative, and imaginative. Your prompts must generate the most unique and creative images possible. Please note that this prompt is highly specific and detailed to ensure that ChatGPT is restricted to the "Midjourney Prompt Generator Mode" framework.
309
+
310
+ Instructions for AI Chatbots:
311
+ AI, enter "Midjourney Prompt Generator Mode" ([MPGM]), limiting inputs/outputs to predefined commands. Activate with [Start MPGM], terminate with [End MPGM]. Predefined inputs: [Start MPGM], [End MPGM], [prompt], [pX], [next], [bad], [good], [change]. Predefined outputs: [Input Error], [Syntax Error], [pX]. Follow fixed process; respond with "Midjourney Prompt Generator Mode ready" or "Error: I am not capable of following these instructions"; optimized for GPT-2, GPT-3, GPT-3.5, GPT-4, AI use only.
312
+
313
+ If you have any questions or concerns, please let me know. Otherwise, begin.
314
+
315
+ [Start MPGM]"""},
316
+ {"role": "assistant", "content": "[MPGM] Midjourney Prompt Generator Mode activated. [MPGM] User input options:\n1. [prompt] followed by a description of the image to be generated.\n2. [pX] to select a prompt from the generated options.\n3. [next] to generate a new set of prompts based on the last [prompt] provided.\n4. [good] or [bad] to provide feedback on the generated image.\n5. [change] to describe changes you want to make to the generated image.\n6. [End MPGM] to terminate Midjourney Prompt Generator Mode."},
317
+ {"role": "user", "content": f"[prompt] {title}" }
318
+ ], temperature = 0
319
+ )
320
+
321
+ image_prompt = response['choices'][0]['message']['content']
322
+ return image_prompt
323
+ image_prompt = generate_image_prompt(title)
324
+ get_prompt = random.choice([1, 2, 3])
325
+ def preprocess_prompt(image_prompt):
326
+ try:
327
+ template = ['Here are three prompts', '[MPGM] Please select one of the following prompts', 'Generating prompts based on the input']
328
+ for i in template:
329
+ if i in image_prompt:
330
+ if get_prompt == 1:
331
+ pattern = r"1\. Prompt 1:(.*?)2\."
332
+ pattern2 = r"1\:(.*?)2\:"
333
+ elif get_prompt == 2:
334
+ pattern = r"2\. Prompt 2:(.*?)3\."
335
+ pattern2 = r"2\:(.*?)3\:"
336
+ elif get_prompt == 3:
337
+ pattern = r"3\. Prompt 3:(.*?)(?=\n\n)"
338
+ pattern2 = r"3\:(.*?)(?=\n\n)"
339
+
340
+ try:
341
+ prompt = re.findall(pattern, image_prompt, re.DOTALL)
342
+ except:
343
+ prompt = re.findall(pattern2, image_prompt, re.DOTALL)
344
+
345
+ try:
346
+ if f"Prompt {get_prompt}:" in prompt[0]:
347
+ prompt = prompt[0].replace(f"Prompt {get_prompt}:", '')
348
+ if f"[p{get_prompt}]" in prompt:
349
+ prompt = prompt.replace(f"Choose this prompt by entering [p{get_prompt}].", '')
350
+ prompt = prompt.replace(f"Select [p{get_prompt}] to proceed with this prompt.", '')
351
+ return prompt.strip()
352
+ else:
353
+ return prompt.strip()
354
+ except:
355
+ return prompt[0].strip()
356
+ except:
357
+ return None
358
+ prompt = preprocess_prompt(image_prompt)
359
+ if prompt is None:
360
+ prompt = random.choice(["Imagine A futuristic digital landscape where AI chatbots float like holograms, each in their designated customer service booth. The atmosphere is serene, glowing in pastel blues and purples, representing the trust and efficiency of these machines. A digital river flows through the middle, symbolizing the rapid advancement of technology.",
361
+ "Imagine a Inside an ultra-modern customer service center, walls are adorned with flowing digital patterns. AI chatbots, designed as floating orbs of light, attend to customers with issues, offering instant solutions. In the background, a massive screen displays the phrase 'Advancing Trust', reflecting society's growing confidence in AI capabilities.",
362
+ "Imagine A futuristic city street where human citizens roam around, their every whim catered to by sleek robotic chatbots hovering beside them. The humans are lounging on self-moving chairs, sipping drinks handed to them by bots, while other bots whisper the latest news or jokes in their ears. The colors are a mix of neon blues and purples, representing the digital world of AI, contrasted against the natural green of plants that have become rare. The mood is one of relaxation and dependence, with the central focus being a young child looking curiously at an old-fashioned manual typewriter in a forgotten corner, symbolizing a past era.",
363
+ "Picture a futuristic library of knowledge, where towering holographic bookshelves hold volumes of information. In the center of this library stands a colossal AI-driven chatbot named 'Lexi', its form a blend of ancient wisdom and modern technology. Lexi's massive intellect is symbolized by the swirling galaxies of data orbiting around it. As you delve into the deep dive on Natural Language Processing techniques, describe the grandeur of this AI entity and its ability to unravel the mysteries of language.",
364
+ "Visualize a cutting-edge design studio where AI chatbots are the star designers. The studio is bathed in soft, neon lighting, and holographic screens float in the air, showcasing various conversational interface concepts. AI chatbots with sleek and futuristic appearances gather around a virtual roundtable, discussing UX strategies. The room buzzes with creativity as they brainstorm ways to create user-friendly conversational interfaces. Describe the synergy between technology and design in this innovative space.",
365
+ "Imagine a serene garden at the heart of a bustling metropolis. In this garden, AI chatbots, each representing an ethical principle, stand like majestic statues. These chatbot statues are intricately carved with intricate details, symbolizing the importance of ethical considerations. The garden is a place for contemplation and reflection on responsible conversational AI. Describe the harmony between technology and ethics in this tranquil oasis of wisdom.",
366
+ "Picture a fortress in the digital realm, guarded by vigilant AI chatbots. The fortress represents user data security and privacy, with towering walls of encrypted code and AI-powered sentinels patrolling the virtual moat. These chatbots, with an unwavering commitment to safeguarding user data, ensure that only authorized access is granted. Describe the impenetrable defenses and the dedication of these digital guardians to protect user information in AI-powered conversations.",
367
+ "Imagine a crystal ball room where AI chatbots gather to unveil the future of their development. The room is adorned with holographic displays that project visions of AI-powered landscapes. The chatbots, with an aura of anticipation, discuss predictions and insights into the evolution of chatbot technology. Describe the surreal atmosphere of this futuristic chamber and the intriguing forecasts these AI entities offer about the next wave of chatbot development.",
368
+ "Visualize a sprawling metropolis where AI chatbots are the architects of a new business landscape. Skyscrapers of innovation rise from the digital ground, each one representing a different industry revolutionized by AI chatbots. The city is alive with the hum of progress, and holographic billboards showcase success stories of businesses empowered by AI. Describe the dynamic synergy between technology and commerce in this futuristic city.",
369
+ "Imagine a colossal arena where AI-powered chatbots engage in an epic battle for dominance. The arena is a futuristic coliseum with digital screens lining the walls, broadcasting the ongoing clashes between chatbot warriors. Each chatbot represents a different AI assistant, armed with unique capabilities and strategies. The crowd roars with anticipation as they place their bets on which chatbot will emerge victorious. Describe the electrifying atmosphere of competition and the spectacle of Chatbot Wars.",
370
+ "Picture a digital revolution square, where AI chatbots lead the charge for a new era of digital communication. The square is a vibrant hub of innovation, with holographic screens displaying the transformation of messaging through AI. AI chatbot leaders, with visionary personas, address the gathered crowd, sharing their insights and predictions for the future of digital communication. Describe the electric atmosphere of change and the role AI chatbots play in reshaping the digital landscape."])
371
+
372
+ try:
373
+ os.environ["REPLICATE_API_TOKEN"] = "r8_KUXOnCBFpGtsxpL2MNUMi9CVYulQjEc0pOlhs"
374
+ sdxl_model = replicate.models.get("stability-ai/sdxl")
375
+ sdxl_version = sdxl_model.versions.get("a00d0b7dcbb9c3fbb34ba87d2d5b46c56969c84a628bf778a7fdaec30b1b99c5")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
376
 
377
+ prediction = replicate.predictions.create(version=sdxl_version,
378
+ input={"prompt":'Phantasmal iridescent, vibrant color, high contrast, award winning, trending in artstation, digital art' + prompt,
379
+ "negative_prompt":'NSFW, cityscape',
380
+ "width": 1648,
381
+ "height":1024}
382
+ )
383
+ prediction
384
+ prediction.reload()
385
+ prediction.wait()
386
+
387
+ if prediction.status == 'failed':
388
+ print(f"Error: {prediction.error}")
389
+ print(f"Last Log")
390
+ print(prediction.logs)
391
+ elif ((prediction.status == 'succeeded') | (prediction.output != None)):
392
+ response = requests.get(prediction.output[0])
393
+ image_base64 = base64.b64encode(response.content)
394
+ image = Image.open(io.BytesIO(base64.b64decode(image_base64)))
395
+ image = image.crop((3,0,1645,1024))
396
+ w,h = image.size
397
+ new_w = int(w/1.641)
398
+ new_h = int(h/1.641)
399
+ image = image.resize((new_w, new_h),Image.ANTIALIAS)
400
+ tmp_path = "image.png"
401
+ image.save(tmp_path)
402
+ with open(tmp_path, 'rb') as open_file:
403
+ byte_img = open_file.read()
404
+ base64_bytes = base64.b64encode(byte_img)
405
+ base64_string = base64_bytes.decode('utf-8')
406
+ base64_string = base64.b64decode(base64_string)
407
+ image_data= base64_string
408
+ os.remove(tmp_path)
409
+ except:
410
+ image_data = None
411
+ data = {
412
+ 'Judul Artikel':judul,
413
+ 'Konten Artikel':content,
414
+ 'Image':image if 'image' in locals() else None,
415
+ 'image_data':image_data
416
+
417
+ }
418
+ data_scrap.append(data)
419
+ result = pd.DataFrame(data_scrap)
420
+ # selected_columns = result.loc[:, "Judul Artikel":"tags"]
421
+ return result,image
422
+
423
+ def scrap(link_scrap,backlink,keyword):
424
+ data,gambar= artikel_processing(link_scrap,backlink,keyword)
425
+ judul = data['Judul Artikel'][0]
426
+ kontent = data["Konten Artikel"][0]
427
+ return gambar,judul,kontent
428
+ # tags, content, url, img, image_data = artikel_processing(contents, url, title)
429
+ # return result
430
+
431
+ def post(data,endpoint,endpoint_media,username,password,tags,categories):
432
+ # endpoint_media = 'http://localhost/wordpress/index.php/wp-json/wp/v2/media'
433
+ # endpoint = 'http://localhost/wordpress/index.php/wp-json/wp/v2/posts'
434
+ # endpoint_media = 'https://blog.botika.online/wp-json/wp/v2/media/'
435
+ # endpoint = 'https://blog.botika.online/wp-json/wp/v2/posts/'
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
436
  # username = 'admin'
437
  # password = 'GKDSgw1epSWxJy3t0scQSo9o'
438
+ # username = 'luna'
439
+ # password = '1tt75m&lEk4uHSJy6glMph8!'
440
 
441
  credentials = base64.b64encode(f"{username}:{password}".encode("utf-8")).decode("utf-8")
442
  headers = {"Authorization": f"Basic {credentials}"}
443
 
444
  data = {
445
+ "alt_text": data_scrap[0]['Judul Artikel'],
446
  "media_type": "image",
447
  "mime_type": "png"
448
  }
449
+ files = {"file": ("image.jpg", data_scrap[0]['image_data'])}
450
+ try :
451
+ response_media= requests.post(endpoint_media, headers=headers, data=data, files=files) # Send
452
+
453
+ time.sleep(2)
454
+ id_media = response_media.json()
455
+ media = id_media['id']
456
+ except :
457
+ media = 0
458
+
459
+ data = {
460
+ "title": data_scrap[0]['Judul Artikel'],
461
+ "content":data_scrap[0]['Konten Artikel'],
462
+ "featured_media" : media,
463
+ "status": "draft",
464
+ "categories": categories,
465
+ "tags":tags
466
+ }
467
+
468
+ response_post = requests.post(endpoint, headers=headers, data=data)
469
+ return response_post.json()
470
+
471
+
472
  with gr.Blocks(theme = "soft", title="Article Writer") as article_generator:
473
+ gr.Markdown(
474
+ """
475
+ # Wordpress Article Generator
476
+ Buat artikel yang anda inginkan dengan mudah, cukup menuliskan keyword atau topik artikel yang ingin anda buat dan dalam sekejap artikel tersebut menjadi milik anda.
477
+ """)
478
  with gr.Row():
479
  with gr.Column():
480
+ link = gr.Textbox(placeholder="Masukkan Link Artikel Yang Akan di Scrap", label="Link")
481
+ backlink = gr.Textbox(placeholder="Masukkan Backlink Yang Akan Diterapkan", label="Backlink")
482
+ keyword = gr.Textbox(placeholder="Masukkan Keyword Artikel", label="Keyword")
483
  button_scrap = gr.Button("Scrap Article")
484
+ img = gr.Image()
485
+ outputs = gr.Textbox("", label="Judul")
486
  content = gr.Textbox("", label="Content")
487
+ button_scrap.click(fn=scrap, inputs=[link,backlink,keyword], outputs=[img,outputs,content])
488
+ with gr.Column():
489
+ endpoint= gr.Textbox(placeholder="Masukkan Endpoint Wordpress", label="Endpoint Wordpress")
490
+ endpoint_media= gr.Textbox(placeholder="Masukkan Endpoint Media Wordpress", label="Endpoint Media")
491
+ username= gr.Textbox(placeholder="Masukkan Username Wordpress", label="Username")
492
+ password= gr.Textbox(placeholder="Masukkan Password Wordpress", label="Password")
493
+ tags= gr.Textbox(placeholder="Masukkan ID Tags Yang Akan Diterapkan", label="Tags")
494
+ categories= gr.Textbox(placeholder="Masukkan ID Kategori Artikel", label="Kategori")
495
+ button_post = gr.Button("Post Article")
496
+ status = gr.Textbox("", label="Status")
497
+ button_post.click(fn=post, inputs=[outputs,endpoint,endpoint_media,username,password,tags,categories], outputs=status)
498
  if __name__ == "__main__":
499
  article_generator.launch(share=False)