Dede16 commited on
Commit
53e2a19
·
1 Parent(s): 5541984

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +228 -237
app.py CHANGED
@@ -200,29 +200,8 @@ def clean_scrap(artikel,link,models,api_key,azure_api_base,keyword):
200
  judul = judul
201
  contents = content[1:]
202
  contents = [' '.join(contents).replace("article:", '').replace("Article:", '').strip()]
203
-
204
- if len(contents)>=1200:
205
- return title, judul, link, contents
206
- else:
207
- with open('log_activity.txt', 'r') as file:
208
- existing_data = file.read()
209
-
210
- log = link + "\n"
211
-
212
- combined_data = existing_data + log
213
-
214
- with tempfile.NamedTemporaryFile(mode='w', delete=False) as temp_file:
215
- temp_file.write(combined_data)
216
-
217
- repo_name = get_full_repo_name(model_id="Article_Gen4", token="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")
218
- file_url = upload_file(
219
- path_or_fileobj=temp_file.name,
220
- path_in_repo="log_activity.txt",
221
- repo_id=repo_name,
222
- repo_type="space",
223
- token="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",
224
- )
225
- return None,None,None,None
226
 
227
  def scrap_artikel(source_type,source,models,api_key,azure_api_base,keyword):
228
  options = webdriver.ChromeOptions()
@@ -265,10 +244,8 @@ def scrap_artikel(source_type,source,models,api_key,azure_api_base,keyword):
265
  else :
266
  artikels = [paragraf]
267
  title, judul, url, contents = clean_scrap(artikels,url,models,api_key,azure_api_base,keyword)
268
- if len(contents)>=1200:
269
- return title, judul, url, contents
270
- else:
271
- return None,None,None,None
272
 
273
  else:
274
  wd.get(source)
@@ -294,10 +271,8 @@ def scrap_artikel(source_type,source,models,api_key,azure_api_base,keyword):
294
  else :
295
  artikels = [paragraf]
296
  title, judul, url, contents = clean_scrap(artikels,source,models,api_key,azure_api_base,keyword)
297
- if len(contents)>=1200:
298
- return title, judul, url, contents
299
- else:
300
- return None,None,None,None
301
 
302
  def artikel_processing(source_type,source,backlink,keyword,models,api_key,azure_api_base,replicate_key):
303
  title, judul, url, artikel= scrap_artikel(source_type,source, models, api_key,azure_api_base,keyword)
@@ -307,211 +282,194 @@ def artikel_processing(source_type,source,backlink,keyword,models,api_key,azure_
307
  article = []
308
  post_article = []
309
 
310
- if artikel:
311
- for i in artikel:
312
- messages=[
313
- {"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"},
314
- {"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}"}
315
- ]
316
- if models == 'openai':
317
- translate = get_openai_response(messages,api_key)
318
- translated.append(translate)
319
- time.sleep(2)
320
- else:
321
- translate = get_azure_response(messages,api_key,azure_api_base)
322
- translated.append(translate)
323
- time.sleep(2)
324
-
325
- for i in translated:
326
- messages=[
327
- {"role": "system", "content": f"""
328
- 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:
329
- 1. Theme and Title: The blog article should have a clear and informative title that reflects the main topic.
330
- 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.
331
- 3. Use of Data and Statistics: The blog article should support its arguments with concrete data and statistics.
332
- 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.
333
- 5. Subheadings: The use of subheadings should help readers follow the flow of the article and understand key points more easily.
334
- 6. Citations and Sources: The blog should cite reliable sources.
335
- 7. Graphics: The blog should use graphics to visualize data clearly.
336
- 8. SEO Keywords: Use keyword {keyword} that will help the blog become more discoverable in search results.
337
- 9. Conclusion: The blog should also have a clear conclusion that summarizes the core findings of the study.
338
- 10. Final Thought: You should conclude the blog by providing readers with broader insights on the topic.
339
- 11. meta decription max 160 character
340
- 12. sentences max 20 words
341
- 13. paragraph max 300 words
342
- 14. focus keyword {keyword} harus ada di content
343
- 15. focus keyword {keyword} harus ada di intro
344
- 16. focus keyword {keyword} harus ada di meta desccripton
345
- 17. focus keyword {keyword} harus ada di url
346
- 18. focus keyword {keyword} harus ada di intro
347
- Here is the article that you need to edit to adhere to these 18 criteria: {i}
348
- Please do not change the existing format in the article, just adjust the writing style according to the 10 criteria I mentioned.
349
- """ },
350
- {"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}"}
351
- ]
352
- if models == 'openai':
353
- result = get_openai_response(messages,api_key)
354
- article.append(result)
355
- time.sleep(2)
356
- else:
357
- result = get_azure_response(messages,api_key,azure_api_base)
358
- article.append(result)
359
- time.sleep(2)
360
-
361
- for i in article:
362
- messages=[
363
- {"role": "system", "content": "You are a professional article editor machine."},
364
- {"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>"}
365
- ]
366
- if models == 'openai':
367
- font_formatted = get_openai_response(messages,api_key)
368
- edited_format.append(font_formatted)
369
- time.sleep(2)
370
- else:
371
- font_formatted = get_azure_response(messages,api_key,azure_api_base)
372
- edited_format.append(font_formatted)
373
- time.sleep(2)
374
-
375
- for i in edited_format:
376
- messages=[
377
- {"role": "system", "content": "You are a professional article editor machine."},
378
- {"role": "user", "content": "Please edit the given article:\n" + "\n" + i + f"\nAdd 3 annotations (Maximum) 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 {keyword} 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}"}
379
- ]
380
- if models == 'openai':
381
- artikel_post = get_openai_response(messages,api_key)
382
- post_article.append(artikel_post )
383
- time.sleep(2)
384
- else:
385
- artikel_post = get_azure_response(messages,api_key,azure_api_base)
386
- post_article.append(artikel_post )
387
- time.sleep(2)
388
-
389
- 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 –->'
390
- post_article.append(meta_keywords)
391
- content = ''.join(post_article)
392
 
393
- try:
394
- replacements = generate_patterns(base_replacements)
395
- content = replace_content(content, replacements)
396
- except:
397
- content = content
398
-
399
- def generate_image_prompt(title):
400
- messages=[
401
- {"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.
402
- 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.
403
- 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."
404
- 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.
405
- 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.
406
- 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.
407
- 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.
408
- 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.
409
- 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.
410
- 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].
411
- 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.
412
- Instructions for AI Chatbots:
413
- 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.
414
- If you have any questions or concerns, please let me know. Otherwise, begin.
415
- [Start MPGM]"""},
416
- {"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."},
417
- {"role": "user", "content": f"[prompt] {title}" }
418
- ]
419
-
420
- if models == 'openai':
421
- image_prompt = get_openai_response(messages,api_key)
422
- else:
423
- image_prompt = get_azure_response(messages,api_key,azure_api_base)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
424
 
425
- return image_prompt
426
-
427
- image_prompt = generate_image_prompt(title)
428
- get_prompt = random.choice([1, 2, 3])
429
- def preprocess_prompt(image_prompt):
430
- try:
431
- template = ['Here are three prompts', '[MPGM] Please select one of the following prompts', 'Generating prompts based on the input']
432
- for i in template:
433
- if i in image_prompt:
434
- if get_prompt == 1:
435
- pattern = r"1\. Prompt 1:(.*?)2\."
436
- pattern2 = r"1\:(.*?)2\:"
437
- elif get_prompt == 2:
438
- pattern = r"2\. Prompt 2:(.*?)3\."
439
- pattern2 = r"2\:(.*?)3\:"
440
- elif get_prompt == 3:
441
- pattern = r"3\. Prompt 3:(.*?)(?=\n\n)"
442
- pattern2 = r"3\:(.*?)(?=\n\n)"
443
 
444
- try:
445
- prompt = re.findall(pattern, image_prompt, re.DOTALL)
446
- except:
447
- prompt = re.findall(pattern2, image_prompt, re.DOTALL)
448
 
449
- try:
450
- if f"Prompt {get_prompt}:" in prompt[0]:
451
- prompt = prompt[0].replace(f"Prompt {get_prompt}:", '')
452
- if f"[p{get_prompt}]" in prompt:
453
- prompt = prompt.replace(f"Choose this prompt by entering [p{get_prompt}].", '')
454
- prompt = prompt.replace(f"Select [p{get_prompt}] to proceed with this prompt.", '')
455
- return prompt.strip()
456
- else:
457
- return prompt.strip()
458
- except:
459
- return prompt[0].strip()
460
- except:
461
- return None
462
- prompt = preprocess_prompt(image_prompt)
463
- if prompt is None:
464
- 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.",
465
- "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.",
466
- "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.",
467
- "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.",
468
- "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.",
469
- "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.",
470
- "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.",
471
- "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.",
472
- "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.",
473
- "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.",
474
- "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."])
 
 
 
 
 
475
 
476
- try:
477
- os.environ["REPLICATE_API_TOKEN"] = replicate_key
478
- sdxl_model = replicate.models.get("stability-ai/sdxl")
479
- sdxl_version = sdxl_model.versions.get("a00d0b7dcbb9c3fbb34ba87d2d5b46c56969c84a628bf778a7fdaec30b1b99c5")
480
-
481
- prediction = replicate.predictions.create(version=sdxl_version,
482
- input={"prompt":'Phantasmal iridescent, vibrant color, high contrast, award winning, trending in artstation, digital art' + prompt,
483
- "negative_prompt":'NSFW, cityscape',
484
- "width": 1648,
485
- "height":1024}
486
- )
487
- prediction
488
- prediction.reload()
489
- prediction.wait()
490
 
491
- if prediction.status == 'failed':
492
- print(f"Error: {prediction.error}")
493
- print(f"Last Log")
494
- print(prediction.logs)
495
- elif ((prediction.status == 'succeeded') | (prediction.output != None)):
496
- response = requests.get(prediction.output[0])
497
- image_base64 = base64.b64encode(response.content)
498
- image = Image.open(io.BytesIO(base64.b64decode(image_base64)))
499
- image = image.crop((3,0,1645,1024))
500
- w,h = image.size
501
- new_w = int(w/1.641)
502
- new_h = int(h/1.641)
503
- image = image.resize((new_w, new_h),Image.ANTIALIAS)
504
- tmp_path = "image.png"
505
- image.save(tmp_path)
506
- with open(tmp_path, 'rb') as open_file:
507
- byte_img = open_file.read()
508
- base64_bytes = base64.b64encode(byte_img)
509
- base64_string = base64_bytes.decode('utf-8')
510
- base64_string = base64.b64decode(base64_string)
511
- image_data= base64_string
512
- os.remove(tmp_path)
 
 
 
 
 
 
 
 
 
 
 
513
  except:
514
- image = Image.open('botika_logo.jpeg')
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
515
  image = image.crop((3,0,1645,1024))
516
  w,h = image.size
517
  new_w = int(w/1.641)
@@ -526,9 +484,23 @@ def artikel_processing(source_type,source,backlink,keyword,models,api_key,azure_
526
  base64_string = base64.b64decode(base64_string)
527
  image_data= base64_string
528
  os.remove(tmp_path)
529
- return judul,content,image,image_data,url
530
- else:
531
- return None,None,None,None,None
 
 
 
 
 
 
 
 
 
 
 
 
 
 
532
 
533
  def scrap(source_type,source,backlink,keyword,version,api_key,azure_api_base,replicate_key):
534
  # try:
@@ -566,7 +538,7 @@ def scrap(source_type,source,backlink,keyword,version,api_key,azure_api_base,rep
566
  repo_type="space",
567
  token="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",
568
  )
569
- if kontent:
570
  with open('log_activity.txt', 'r') as file:
571
  existing_data = file.read()
572
 
@@ -589,10 +561,29 @@ def scrap(source_type,source,backlink,keyword,version,api_key,azure_api_base,rep
589
  status = "<h3>Berhasil Generate Artikel</h3>"
590
  time.sleep(60)
591
  return status,gambar
592
- # else:
593
- # status = "<h3>Gagal Generate Artikel, Coba Generate Ulang atau Ganti Input Source</h3>"
594
- # gambar = Image.open("error.png")
595
- # return status,gambar
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
596
  # except:
597
  # status = "<h3>Gagal Generate Artikel</h3>"
598
  # gambar = Image.open('error.png')
 
200
  judul = judul
201
  contents = content[1:]
202
  contents = [' '.join(contents).replace("article:", '').replace("Article:", '').strip()]
203
+
204
+ return title, judul, link, contents
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
205
 
206
  def scrap_artikel(source_type,source,models,api_key,azure_api_base,keyword):
207
  options = webdriver.ChromeOptions()
 
244
  else :
245
  artikels = [paragraf]
246
  title, judul, url, contents = clean_scrap(artikels,url,models,api_key,azure_api_base,keyword)
247
+
248
+ return title, judul, url, contents
 
 
249
 
250
  else:
251
  wd.get(source)
 
271
  else :
272
  artikels = [paragraf]
273
  title, judul, url, contents = clean_scrap(artikels,source,models,api_key,azure_api_base,keyword)
274
+
275
+ return title, judul, url, contents
 
 
276
 
277
  def artikel_processing(source_type,source,backlink,keyword,models,api_key,azure_api_base,replicate_key):
278
  title, judul, url, artikel= scrap_artikel(source_type,source, models, api_key,azure_api_base,keyword)
 
282
  article = []
283
  post_article = []
284
 
285
+ for i in artikel:
286
+ messages=[
287
+ {"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"},
288
+ {"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}"}
289
+ ]
290
+ if models == 'openai':
291
+ translate = get_openai_response(messages,api_key)
292
+ translated.append(translate)
293
+ time.sleep(2)
294
+ else:
295
+ translate = get_azure_response(messages,api_key,azure_api_base)
296
+ translated.append(translate)
297
+ time.sleep(2)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
298
 
299
+ for i in translated:
300
+ messages=[
301
+ {"role": "system", "content": f"""
302
+ 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:
303
+ 1. Theme and Title: The blog article should have a clear and informative title that reflects the main topic.
304
+ 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.
305
+ 3. Use of Data and Statistics: The blog article should support its arguments with concrete data and statistics.
306
+ 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.
307
+ 5. Subheadings: The use of subheadings should help readers follow the flow of the article and understand key points more easily.
308
+ 6. Citations and Sources: The blog should cite reliable sources.
309
+ 7. Graphics: The blog should use graphics to visualize data clearly.
310
+ 8. SEO Keywords: Use keyword {keyword} that will help the blog become more discoverable in search results.
311
+ 9. Conclusion: The blog should also have a clear conclusion that summarizes the core findings of the study.
312
+ 10. Final Thought: You should conclude the blog by providing readers with broader insights on the topic.
313
+ 11. meta decription max 160 character
314
+ 12. sentences max 20 words
315
+ 13. paragraph max 300 words
316
+ 14. focus keyword {keyword} harus ada di content
317
+ 15. focus keyword {keyword} harus ada di intro
318
+ 16. focus keyword {keyword} harus ada di meta desccripton
319
+ 17. focus keyword {keyword} harus ada di url
320
+ 18. focus keyword {keyword} harus ada di intro
321
+ Here is the article that you need to edit to adhere to these 18 criteria: {i}
322
+ Please do not change the existing format in the article, just adjust the writing style according to the 10 criteria I mentioned.
323
+ """ },
324
+ {"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}"}
325
+ ]
326
+ if models == 'openai':
327
+ result = get_openai_response(messages,api_key)
328
+ article.append(result)
329
+ time.sleep(2)
330
+ else:
331
+ result = get_azure_response(messages,api_key,azure_api_base)
332
+ article.append(result)
333
+ time.sleep(2)
334
+
335
+ for i in article:
336
+ messages=[
337
+ {"role": "system", "content": "You are a professional article editor machine."},
338
+ {"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>"}
339
+ ]
340
+ if models == 'openai':
341
+ font_formatted = get_openai_response(messages,api_key)
342
+ edited_format.append(font_formatted)
343
+ time.sleep(2)
344
+ else:
345
+ font_formatted = get_azure_response(messages,api_key,azure_api_base)
346
+ edited_format.append(font_formatted)
347
+ time.sleep(2)
348
 
349
+ for i in edited_format:
350
+ messages=[
351
+ {"role": "system", "content": "You are a professional article editor machine."},
352
+ {"role": "user", "content": "Please edit the given article:\n" + "\n" + i + f"\nAdd 3 annotations (Maximum) 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 {keyword} 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}"}
353
+ ]
354
+ if models == 'openai':
355
+ artikel_post = get_openai_response(messages,api_key)
356
+ post_article.append(artikel_post )
357
+ time.sleep(2)
358
+ else:
359
+ artikel_post = get_azure_response(messages,api_key,azure_api_base)
360
+ post_article.append(artikel_post )
361
+ time.sleep(2)
 
 
 
 
 
362
 
363
+ 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 –->'
364
+ post_article.append(meta_keywords)
365
+ content = ''.join(post_article)
 
366
 
367
+ try:
368
+ replacements = generate_patterns(base_replacements)
369
+ content = replace_content(content, replacements)
370
+ except:
371
+ content = content
372
+
373
+ def generate_image_prompt(title):
374
+ messages=[
375
+ {"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.
376
+ 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.
377
+ 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."
378
+ 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.
379
+ 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.
380
+ 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.
381
+ 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.
382
+ 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.
383
+ 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.
384
+ 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].
385
+ 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.
386
+ Instructions for AI Chatbots:
387
+ 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.
388
+ If you have any questions or concerns, please let me know. Otherwise, begin.
389
+ [Start MPGM]"""},
390
+ {"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."},
391
+ {"role": "user", "content": f"[prompt] {title}" }
392
+ ]
393
+
394
+ if models == 'openai':
395
+ image_prompt = get_openai_response(messages,api_key)
396
+ else:
397
+ image_prompt = get_azure_response(messages,api_key,azure_api_base)
398
 
399
+ return image_prompt
 
 
 
 
 
 
 
 
 
 
 
 
 
400
 
401
+ image_prompt = generate_image_prompt(title)
402
+ get_prompt = random.choice([1, 2, 3])
403
+ def preprocess_prompt(image_prompt):
404
+ try:
405
+ template = ['Here are three prompts', '[MPGM] Please select one of the following prompts', 'Generating prompts based on the input']
406
+ for i in template:
407
+ if i in image_prompt:
408
+ if get_prompt == 1:
409
+ pattern = r"1\. Prompt 1:(.*?)2\."
410
+ pattern2 = r"1\:(.*?)2\:"
411
+ elif get_prompt == 2:
412
+ pattern = r"2\. Prompt 2:(.*?)3\."
413
+ pattern2 = r"2\:(.*?)3\:"
414
+ elif get_prompt == 3:
415
+ pattern = r"3\. Prompt 3:(.*?)(?=\n\n)"
416
+ pattern2 = r"3\:(.*?)(?=\n\n)"
417
+
418
+ try:
419
+ prompt = re.findall(pattern, image_prompt, re.DOTALL)
420
+ except:
421
+ prompt = re.findall(pattern2, image_prompt, re.DOTALL)
422
+
423
+ try:
424
+ if f"Prompt {get_prompt}:" in prompt[0]:
425
+ prompt = prompt[0].replace(f"Prompt {get_prompt}:", '')
426
+ if f"[p{get_prompt}]" in prompt:
427
+ prompt = prompt.replace(f"Choose this prompt by entering [p{get_prompt}].", '')
428
+ prompt = prompt.replace(f"Select [p{get_prompt}] to proceed with this prompt.", '')
429
+ return prompt.strip()
430
+ else:
431
+ return prompt.strip()
432
+ except:
433
+ return prompt[0].strip()
434
  except:
435
+ return None
436
+ prompt = preprocess_prompt(image_prompt)
437
+ if prompt is None:
438
+ 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.",
439
+ "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.",
440
+ "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.",
441
+ "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.",
442
+ "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.",
443
+ "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.",
444
+ "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.",
445
+ "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.",
446
+ "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.",
447
+ "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.",
448
+ "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."])
449
+
450
+ try:
451
+ os.environ["REPLICATE_API_TOKEN"] = replicate_key
452
+ sdxl_model = replicate.models.get("stability-ai/sdxl")
453
+ sdxl_version = sdxl_model.versions.get("a00d0b7dcbb9c3fbb34ba87d2d5b46c56969c84a628bf778a7fdaec30b1b99c5")
454
+
455
+ prediction = replicate.predictions.create(version=sdxl_version,
456
+ input={"prompt":'Phantasmal iridescent, vibrant color, high contrast, award winning, trending in artstation, digital art' + prompt,
457
+ "negative_prompt":'NSFW, cityscape',
458
+ "width": 1648,
459
+ "height":1024}
460
+ )
461
+ prediction
462
+ prediction.reload()
463
+ prediction.wait()
464
+
465
+ if prediction.status == 'failed':
466
+ print(f"Error: {prediction.error}")
467
+ print(f"Last Log")
468
+ print(prediction.logs)
469
+ elif ((prediction.status == 'succeeded') | (prediction.output != None)):
470
+ response = requests.get(prediction.output[0])
471
+ image_base64 = base64.b64encode(response.content)
472
+ image = Image.open(io.BytesIO(base64.b64decode(image_base64)))
473
  image = image.crop((3,0,1645,1024))
474
  w,h = image.size
475
  new_w = int(w/1.641)
 
484
  base64_string = base64.b64decode(base64_string)
485
  image_data= base64_string
486
  os.remove(tmp_path)
487
+ except:
488
+ image = Image.open('botika_logo.jpeg')
489
+ image = image.crop((3,0,1645,1024))
490
+ w,h = image.size
491
+ new_w = int(w/1.641)
492
+ new_h = int(h/1.641)
493
+ image = image.resize((new_w, new_h),Image.ANTIALIAS)
494
+ tmp_path = "image.png"
495
+ image.save(tmp_path)
496
+ with open(tmp_path, 'rb') as open_file:
497
+ byte_img = open_file.read()
498
+ base64_bytes = base64.b64encode(byte_img)
499
+ base64_string = base64_bytes.decode('utf-8')
500
+ base64_string = base64.b64decode(base64_string)
501
+ image_data= base64_string
502
+ os.remove(tmp_path)
503
+ return judul,content,image,image_data,url
504
 
505
  def scrap(source_type,source,backlink,keyword,version,api_key,azure_api_base,replicate_key):
506
  # try:
 
538
  repo_type="space",
539
  token="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",
540
  )
541
+ if len(kontent)>=1200:
542
  with open('log_activity.txt', 'r') as file:
543
  existing_data = file.read()
544
 
 
561
  status = "<h3>Berhasil Generate Artikel</h3>"
562
  time.sleep(60)
563
  return status,gambar
564
+ else:
565
+ with open('log_activity.txt', 'r') as file:
566
+ existing_data = file.read()
567
+
568
+ log = url + "\n"
569
+
570
+ combined_data = existing_data + log
571
+
572
+ with tempfile.NamedTemporaryFile(mode='w', delete=False) as temp_file:
573
+ temp_file.write(combined_data)
574
+
575
+
576
+ repo_name = get_full_repo_name(model_id="Article_Gen4", token="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")
577
+ file_url = upload_file(
578
+ path_or_fileobj=temp_file.name,
579
+ path_in_repo="log_activity.txt",
580
+ repo_id=repo_name,
581
+ repo_type="space",
582
+ token="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",
583
+ )
584
+ status = "<h3>Gagal Generate Artikel, Coba Generate Ulang atau Ganti Input Source</h3>"
585
+ gambar = Image.open("error.png")
586
+ return status,gambar
587
  # except:
588
  # status = "<h3>Gagal Generate Artikel</h3>"
589
  # gambar = Image.open('error.png')