Dede16 commited on
Commit
0e93792
·
1 Parent(s): e273eac

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +304 -270
app.py CHANGED
@@ -245,7 +245,10 @@ def scrap_artikel(source_type,source,models,api_key,azure_api_base,keyword):
245
  else :
246
  artikels = [paragraf]
247
  title, judul, url, contents = clean_scrap(artikels,url,models,api_key,azure_api_base,keyword)
248
- return title, judul, url, contents
 
 
 
249
 
250
  else:
251
  wd.get(source)
@@ -271,7 +274,10 @@ def scrap_artikel(source_type,source,models,api_key,azure_api_base,keyword):
271
  else :
272
  artikels = [paragraf]
273
  title, judul, url, contents = clean_scrap(artikels,source,models,api_key,azure_api_base,keyword)
274
- return title, judul, url, contents
 
 
 
275
 
276
  def artikel_processing(source_type,source,backlink,keyword,models,api_key,azure_api_base,replicate_key):
277
  title, judul, url, artikel= scrap_artikel(source_type,source, models, api_key,azure_api_base,keyword)
@@ -282,194 +288,211 @@ def artikel_processing(source_type,source,backlink,keyword,models,api_key,azure_
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,96 +507,111 @@ def artikel_processing(source_type,source,backlink,keyword,models,api_key,azure_
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:
507
- judul,kontent,gambar, image_data,url= artikel_processing(source_type,source,backlink,keyword,version,api_key,azure_api_base,replicate_key)
508
- title = '<h1>'+judul+'</h1>'
509
- desired_timezone = pytz.timezone('Asia/Jakarta')
510
- current_time = datetime.datetime.now(desired_timezone)
511
- Timestamp = current_time.strftime('%Y-%m-%d %H:%M:%S')
512
-
513
- with open('log_activity.txt', 'r') as file:
514
- existing_data = file.read()
515
-
516
- log = url + "\n"
517
-
518
- combined_data = existing_data + log
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
519
 
520
- with tempfile.NamedTemporaryFile(mode='w', delete=False) as temp_file:
521
- temp_file.write(combined_data)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
522
 
523
- with open("judul.txt", "w") as file:
524
- file.write(judul)
525
 
526
- with open("kontent.txt", "w") as file:
527
- file.write(kontent)
528
-
529
- repo_name = get_full_repo_name(model_id="Article_Gen4", token="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")
530
- file_url = upload_file(
531
- path_or_fileobj=temp_file.name, # Use the temporary file name
532
- path_in_repo="log_activity.txt",
533
- repo_id=repo_name,
534
- repo_type="space",
535
- token="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",
536
- )
537
-
538
- file_url = upload_file(
539
- path_or_fileobj=image_data,
540
- path_in_repo="image_data.txt",
541
- repo_id=repo_name,
542
- repo_type="space",
543
- token="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",
544
- )
545
- file_url = upload_file(
546
- path_or_fileobj='judul.txt',
547
- path_in_repo="judul.txt",
548
- repo_id=repo_name,
549
- repo_type="space",
550
- token="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",
551
- )
552
- file_url = upload_file(
553
- path_or_fileobj='kontent.txt',
554
- path_in_repo="kontent.txt",
555
- repo_id=repo_name,
556
- repo_type="space",
557
- token="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",
558
- )
559
- if kontent:
560
- status = "<h3>Berhasil Generate Artikel</h3>"
561
- time.sleep(60)
562
- return status,gambar
563
- # except:
564
- # with open('log_url.txt', 'r') as file:
565
- # existing_data = file.read()
566
 
567
- # log = 'Source:' + source + "\n"
568
- # combined_data = existing_data + log
569
 
570
- # with tempfile.NamedTemporaryFile(mode='w', delete=False) as temp_file:
571
- # temp_file.write(combined_data)
 
 
 
 
 
 
 
 
 
572
 
573
- # status = "<h3>Gagal Generate Artikel</h3>"
574
- # gambar = Image.open('error.png')
575
- # return status,gamber
576
-
577
 
578
  def post(endpoint,endpoint_media,username,password,tags,categories,metode):
579
  credentials = base64.b64encode(f"{username}:{password}".encode("utf-8")).decode("utf-8")
@@ -616,7 +654,6 @@ def post(endpoint,endpoint_media,username,password,tags,categories,metode):
616
  return response_post.json()
617
 
618
  def view_output():
619
- # try:
620
  with open('judul.txt', 'r') as file:
621
  judul = file.read()
622
  title = '<h1>'+judul+'</h1>'
@@ -624,10 +661,7 @@ def view_output():
624
  kontent = file.read()
625
  time.sleep(5)
626
  return title,kontent
627
- # except:
628
- # title = 'Gagal Generate Judul'
629
- # kontent = 'Gagal Generate Konten'
630
- # return title,kontent
631
 
632
  def save(title,content):
633
  with open("judul.txt", "w") as file:
 
245
  else :
246
  artikels = [paragraf]
247
  title, judul, url, contents = clean_scrap(artikels,url,models,api_key,azure_api_base,keyword)
248
+ if len(contents)>=2500:
249
+ return title, judul, url, contents
250
+ else:
251
+ return None,None,None,None
252
 
253
  else:
254
  wd.get(source)
 
274
  else :
275
  artikels = [paragraf]
276
  title, judul, url, contents = clean_scrap(artikels,source,models,api_key,azure_api_base,keyword)
277
+ if len(contents)>=2500:
278
+ return title, judul, url, contents
279
+ else:
280
+ return None,None,None,None
281
 
282
  def artikel_processing(source_type,source,backlink,keyword,models,api_key,azure_api_base,replicate_key):
283
  title, judul, url, artikel= scrap_artikel(source_type,source, models, api_key,azure_api_base,keyword)
 
288
  article = []
289
  post_article = []
290
 
291
+ if artikel:
292
+ for i in artikel:
293
+ messages=[
294
+ {"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"},
295
+ {"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}"}
296
+ ]
297
+ if models == 'openai':
298
+ translate = get_openai_response(messages,api_key)
299
+ translated.append(translate)
300
+ time.sleep(2)
301
+ else:
302
+ translate = get_azure_response(messages,api_key,azure_api_base)
303
+ translated.append(translate)
304
+ time.sleep(2)
305
+
306
+ for i in translated:
307
+ messages=[
308
+ {"role": "system", "content": f"""
309
+ 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:
310
+ 1. Theme and Title: The blog article should have a clear and informative title that reflects the main topic.
311
+ 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.
312
+ 3. Use of Data and Statistics: The blog article should support its arguments with concrete data and statistics.
313
+ 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.
314
+ 5. Subheadings: The use of subheadings should help readers follow the flow of the article and understand key points more easily.
315
+ 6. Citations and Sources: The blog should cite reliable sources.
316
+ 7. Graphics: The blog should use graphics to visualize data clearly.
317
+ 8. SEO Keywords: Use keyword {keyword} that will help the blog become more discoverable in search results.
318
+ 9. Conclusion: The blog should also have a clear conclusion that summarizes the core findings of the study.
319
+ 10. Final Thought: You should conclude the blog by providing readers with broader insights on the topic.
320
+ 11. meta decription max 160 character
321
+ 12. sentences max 20 words
322
+ 13. paragraph max 300 words
323
+ 14. focus keyword {keyword} harus ada di content
324
+ 15. focus keyword {keyword} harus ada di intro
325
+ 16. focus keyword {keyword} harus ada di meta desccripton
326
+ 17. focus keyword {keyword} harus ada di url
327
+ 18. focus keyword {keyword} harus ada di intro
328
+ Here is the article that you need to edit to adhere to these 18 criteria: {i}
329
+ Please do not change the existing format in the article, just adjust the writing style according to the 10 criteria I mentioned.
330
+ """ },
331
+ {"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}"}
332
+ ]
333
+ if models == 'openai':
334
+ result = get_openai_response(messages,api_key)
335
+ article.append(result)
336
+ time.sleep(2)
337
+ else:
338
+ result = get_azure_response(messages,api_key,azure_api_base)
339
+ article.append(result)
340
+ time.sleep(2)
341
+
342
+ for i in article:
343
+ messages=[
344
+ {"role": "system", "content": "You are a professional article editor machine."},
345
+ {"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>"}
346
+ ]
347
+ if models == 'openai':
348
+ font_formatted = get_openai_response(messages,api_key)
349
+ edited_format.append(font_formatted)
350
+ time.sleep(2)
351
+ else:
352
+ font_formatted = get_azure_response(messages,api_key,azure_api_base)
353
+ edited_format.append(font_formatted)
354
+ time.sleep(2)
355
+
356
+ for i in edited_format:
357
+ messages=[
358
+ {"role": "system", "content": "You are a professional article editor machine."},
359
+ {"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}"}
360
+ ]
361
+ if models == 'openai':
362
+ artikel_post = get_openai_response(messages,api_key)
363
+ post_article.append(artikel_post )
364
+ time.sleep(2)
365
+ else:
366
+ artikel_post = get_azure_response(messages,api_key,azure_api_base)
367
+ post_article.append(artikel_post )
368
+ time.sleep(2)
369
 
370
+ 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 –->'
371
+ post_article.append(meta_keywords)
372
+ content = ''.join(post_article)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
373
 
374
+ try:
375
+ replacements = generate_patterns(base_replacements)
376
+ content = replace_content(content, replacements)
377
+ except:
378
+ content = content
379
+
380
+ def generate_image_prompt(title):
381
+ messages=[
382
+ {"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.
383
+ 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.
384
+ 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."
385
+ 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.
386
+ 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.
387
+ 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.
388
+ 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.
389
+ 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.
390
+ 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.
391
+ 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].
392
+ 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.
393
+ Instructions for AI Chatbots:
394
+ 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.
395
+ If you have any questions or concerns, please let me know. Otherwise, begin.
396
+ [Start MPGM]"""},
397
+ {"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."},
398
+ {"role": "user", "content": f"[prompt] {title}" }
399
+ ]
400
+
401
+ if models == 'openai':
402
+ image_prompt = get_openai_response(messages,api_key)
403
+ else:
404
+ image_prompt = get_azure_response(messages,api_key,azure_api_base)
405
+
406
+ return image_prompt
407
+
408
+ image_prompt = generate_image_prompt(title)
409
+ get_prompt = random.choice([1, 2, 3])
410
+ def preprocess_prompt(image_prompt):
411
+ try:
412
+ template = ['Here are three prompts', '[MPGM] Please select one of the following prompts', 'Generating prompts based on the input']
413
+ for i in template:
414
+ if i in image_prompt:
415
+ if get_prompt == 1:
416
+ pattern = r"1\. Prompt 1:(.*?)2\."
417
+ pattern2 = r"1\:(.*?)2\:"
418
+ elif get_prompt == 2:
419
+ pattern = r"2\. Prompt 2:(.*?)3\."
420
+ pattern2 = r"2\:(.*?)3\:"
421
+ elif get_prompt == 3:
422
+ pattern = r"3\. Prompt 3:(.*?)(?=\n\n)"
423
+ pattern2 = r"3\:(.*?)(?=\n\n)"
424
 
425
+ try:
426
+ prompt = re.findall(pattern, image_prompt, re.DOTALL)
427
+ except:
428
+ prompt = re.findall(pattern2, image_prompt, re.DOTALL)
429
 
430
+ try:
431
+ if f"Prompt {get_prompt}:" in prompt[0]:
432
+ prompt = prompt[0].replace(f"Prompt {get_prompt}:", '')
433
+ if f"[p{get_prompt}]" in prompt:
434
+ prompt = prompt.replace(f"Choose this prompt by entering [p{get_prompt}].", '')
435
+ prompt = prompt.replace(f"Select [p{get_prompt}] to proceed with this prompt.", '')
436
+ return prompt.strip()
437
+ else:
438
+ return prompt.strip()
439
+ except:
440
+ return prompt[0].strip()
441
+ except:
442
+ return None
443
+ prompt = preprocess_prompt(image_prompt)
444
+ if prompt is None:
445
+ 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.",
446
+ "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.",
447
+ "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.",
448
+ "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.",
449
+ "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.",
450
+ "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.",
451
+ "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.",
452
+ "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.",
453
+ "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.",
454
+ "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.",
455
+ "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."])
 
 
 
 
 
456
 
 
 
 
 
 
457
  try:
458
+ os.environ["REPLICATE_API_TOKEN"] = replicate_key
459
+ sdxl_model = replicate.models.get("stability-ai/sdxl")
460
+ sdxl_version = sdxl_model.versions.get("a00d0b7dcbb9c3fbb34ba87d2d5b46c56969c84a628bf778a7fdaec30b1b99c5")
461
+
462
+ prediction = replicate.predictions.create(version=sdxl_version,
463
+ input={"prompt":'Phantasmal iridescent, vibrant color, high contrast, award winning, trending in artstation, digital art' + prompt,
464
+ "negative_prompt":'NSFW, cityscape',
465
+ "width": 1648,
466
+ "height":1024}
467
+ )
468
+ prediction
469
+ prediction.reload()
470
+ prediction.wait()
471
+
472
+ if prediction.status == 'failed':
473
+ print(f"Error: {prediction.error}")
474
+ print(f"Last Log")
475
+ print(prediction.logs)
476
+ elif ((prediction.status == 'succeeded') | (prediction.output != None)):
477
+ response = requests.get(prediction.output[0])
478
+ image_base64 = base64.b64encode(response.content)
479
+ image = Image.open(io.BytesIO(base64.b64decode(image_base64)))
480
+ image = image.crop((3,0,1645,1024))
481
+ w,h = image.size
482
+ new_w = int(w/1.641)
483
+ new_h = int(h/1.641)
484
+ image = image.resize((new_w, new_h),Image.ANTIALIAS)
485
+ tmp_path = "image.png"
486
+ image.save(tmp_path)
487
+ with open(tmp_path, 'rb') as open_file:
488
+ byte_img = open_file.read()
489
+ base64_bytes = base64.b64encode(byte_img)
490
+ base64_string = base64_bytes.decode('utf-8')
491
+ base64_string = base64.b64decode(base64_string)
492
+ image_data= base64_string
493
+ os.remove(tmp_path)
494
  except:
495
+ image = Image.open('botika_logo.jpeg')
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
496
  image = image.crop((3,0,1645,1024))
497
  w,h = image.size
498
  new_w = int(w/1.641)
 
507
  base64_string = base64.b64decode(base64_string)
508
  image_data= base64_string
509
  os.remove(tmp_path)
510
+ return judul,content,image,image_data,url
511
+ else:
512
+ return None,None,None,None,None
 
 
 
 
 
 
 
 
 
 
 
 
 
 
513
 
514
  def scrap(source_type,source,backlink,keyword,version,api_key,azure_api_base,replicate_key):
515
+ try:
516
+ judul,kontent,gambar, image_data,url= artikel_processing(source_type,source,backlink,keyword,version,api_key,azure_api_base,replicate_key)
517
+ title = '<h1>'+judul+'</h1>'
518
+ desired_timezone = pytz.timezone('Asia/Jakarta')
519
+ current_time = datetime.datetime.now(desired_timezone)
520
+ Timestamp = current_time.strftime('%Y-%m-%d %H:%M:%S')
521
+
522
+ with open('log_activity.txt', 'r') as file:
523
+ existing_data = file.read()
524
+
525
+ log = url + "\n"
526
+
527
+ combined_data = existing_data + log
528
+
529
+ with tempfile.NamedTemporaryFile(mode='w', delete=False) as temp_file:
530
+ temp_file.write(combined_data)
531
+
532
+ with open("judul.txt", "w") as file:
533
+ file.write(judul)
534
+
535
+ with open("kontent.txt", "w") as file:
536
+ file.write(kontent)
537
+
538
+ repo_name = get_full_repo_name(model_id="Article_Gen4", token="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")
539
+ file_url = upload_file(
540
+ path_or_fileobj=temp_file.name,
541
+ path_in_repo="log_activity.txt",
542
+ repo_id=repo_name,
543
+ repo_type="space",
544
+ token="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",
545
+ )
546
 
547
+ file_url = upload_file(
548
+ path_or_fileobj=image_data,
549
+ path_in_repo="image_data.txt",
550
+ repo_id=repo_name,
551
+ repo_type="space",
552
+ token="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",
553
+ )
554
+ file_url = upload_file(
555
+ path_or_fileobj='judul.txt',
556
+ path_in_repo="judul.txt",
557
+ repo_id=repo_name,
558
+ repo_type="space",
559
+ token="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",
560
+ )
561
+ file_url = upload_file(
562
+ path_or_fileobj='kontent.txt',
563
+ path_in_repo="kontent.txt",
564
+ repo_id=repo_name,
565
+ repo_type="space",
566
+ token="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",
567
+ )
568
+ if kontent:
569
+ status = "<h3>Berhasil Generate Artikel</h3>"
570
+ time.sleep(60)
571
+ return status,gambar
572
+ else:
573
+ with open('log_url.txt', 'r') as file:
574
+ existing_data = file.read()
575
 
576
+ log = 'Source:' + source + "\n"
577
+ combined_data = existing_data + log
578
 
579
+ with tempfile.NamedTemporaryFile(mode='w', delete=False) as temp_file:
580
+ temp_file.write(combined_data)
581
+
582
+ repo_name = get_full_repo_name(model_id="Article_Gen4", token="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")
583
+ file_url = upload_file(
584
+ path_or_fileobj=temp_file.name,
585
+ path_in_repo="log_activity.txt",
586
+ repo_id=repo_name,
587
+ repo_type="space",
588
+ token="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",
589
+ )
590
+ status = "<h3>Gagal Generate Artikel, Coba Generate Ulang atau Ganti Input Source</h3>"
591
+ gambar = Image.open("error.png")
592
+ return status,gambar
593
+ except:
594
+ with open('log_url.txt', 'r') as file:
595
+ existing_data = file.read()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
596
 
597
+ log = 'Source:' + source + "\n"
598
+ combined_data = existing_data + log
599
 
600
+ with tempfile.NamedTemporaryFile(mode='w', delete=False) as temp_file:
601
+ temp_file.write(combined_data)
602
+
603
+ repo_name = get_full_repo_name(model_id="Article_Gen4", token="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")
604
+ file_url = upload_file(
605
+ path_or_fileobj=temp_file.name,
606
+ path_in_repo="log_activity.txt",
607
+ repo_id=repo_name,
608
+ repo_type="space",
609
+ token="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",
610
+ )
611
 
612
+ status = "<h3>Gagal Generate Artikel</h3>"
613
+ gambar = Image.open('error.png')
614
+ return status,gambar
 
615
 
616
  def post(endpoint,endpoint_media,username,password,tags,categories,metode):
617
  credentials = base64.b64encode(f"{username}:{password}".encode("utf-8")).decode("utf-8")
 
654
  return response_post.json()
655
 
656
  def view_output():
 
657
  with open('judul.txt', 'r') as file:
658
  judul = file.read()
659
  title = '<h1>'+judul+'</h1>'
 
661
  kontent = file.read()
662
  time.sleep(5)
663
  return title,kontent
664
+
 
 
 
665
 
666
  def save(title,content):
667
  with open("judul.txt", "w") as file: