jsakshi commited on
Commit
d9ef514
ยท
verified ยท
1 Parent(s): 2c24d99

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +45 -95
app.py CHANGED
@@ -363,108 +363,81 @@ import re
363
  import json
364
  import random
365
  from datetime import datetime
366
- from transformers import pipeline
367
- from huggingface_hub import HfApi
368
- from linkedin_api import Linkedin
369
 
370
- # Initialize models
371
- try:
372
- text_generation = pipeline(
373
- "text-generation",
374
- model="mistralai/Mistral-7B-Instruct-v0.2",
375
- max_length=4096,
376
- temperature=0.7
377
- )
378
- image_generation = pipeline("text-to-image", model="stabilityai/stable-diffusion-xl-base-1.0")
379
- except Exception as e:
380
- print(f"Error loading models: {e}")
381
- try:
382
- text_generation = pipeline(
383
- "text-generation",
384
- model="TinyLlama/TinyLlama-1.1B-Chat-v1.0",
385
- max_length=2048
386
- )
387
- image_generation = None
388
- except:
389
- text_generation = None
390
- image_generation = None
391
 
392
  def generate_blog_content(topic, tone="professional", length="medium"):
393
- if not text_generation:
394
- return "Error: Text generation model could not be loaded."
395
-
396
- length_words = {
397
- "short": "500-800",
398
- "medium": "1000-1500",
399
- "long": "2000-2500"
400
- }[length]
401
-
402
  current_date = datetime.now().strftime("%B %d, %Y")
403
  reading_time = {"short": "5-8", "medium": "8-12", "long": "15-20"}[length]
404
 
405
  prompt = f"""Write a comprehensive blog post about {topic} with this structure:
406
-
407
  # [Main Title]
408
- ## [Subtitle or Tagline]
409
-
410
  **Published**: {current_date}
411
  **Reading time**: {reading_time} minutes
412
- ![Featured Image](featured_image.png)
413
-
414
  ### Table of Contents
415
  - [Introduction](#introduction)
416
  - [Section 1](#section-1)
417
  - [Section 2](#section-2)
418
- - [Section 3](#section-3)
419
  - [Conclusion](#conclusion)
420
-
421
  ## Introduction
422
  [Engaging opening paragraph with statistics]
423
-
424
  ## Section 1: [Section Title]
425
  [Detailed content with examples and data]
426
-
427
- ## Section 2: [Section Title]
428
  [Technical details or case studies]
429
-
430
- ## Section 3: [Section Title]
431
- [Future trends or practical applications]
432
-
433
  ## Conclusion
434
  [Summary and final thoughts]
 
 
 
 
 
 
435
 
436
- **About the Author**
437
- [Author information]
438
-
439
- **Related Topics**
440
- - [Related Topic 1](#)
441
- - [Related Topic 2](#)
442
-
443
- ยฉ {datetime.now().strftime('%Y')} AI Generated Blog
444
- Created with AI Blog Generator
445
 
446
- Use {tone} tone and include:
447
- - Proper markdown formatting
448
- - Bullet points and numbered lists
449
- - Data points (include fake realistic statistics)
450
- - Real-world examples
451
- - Section links
452
- - At least 3 subsections per main section"""
453
-
454
  try:
455
- result = text_generation(prompt, max_length=4096)[0]['generated_text']
456
- blog_content = result.split(prompt)[-1].strip()
457
- return blog_content
 
 
 
458
  except Exception as e:
459
- return f"Error generating blog content: {str(e)}"
460
 
461
  def generate_featured_image(topic):
462
- if not image_generation:
463
- return None, "Image generation not available"
464
-
465
  prompt = f"Professional digital illustration for blog about {topic}, high quality, trending on artstation"
 
 
 
 
 
 
 
 
 
 
466
  try:
467
- image = image_generation(prompt, num_images_per_prompt=1)[0]
 
 
468
  temp_img = tempfile.NamedTemporaryFile(delete=False, suffix=".png")
469
  image.save(temp_img.name)
470
  return temp_img.name, "Image generated successfully"
@@ -473,20 +446,13 @@ def generate_featured_image(topic):
473
 
474
  def create_download_file(content, title, author):
475
  try:
476
- # Create temporary file
477
  temp_file = tempfile.NamedTemporaryFile(mode="w", delete=False, suffix=".md", encoding="utf-8")
478
-
479
- # Add author information
480
  full_content = content + f"\n\n**About the Author** \n{author}"
481
-
482
- # Write content to file
483
  temp_file.write(full_content)
484
  temp_file.close()
485
 
486
- # Sanitize filename
487
  sanitized_title = re.sub(r'[^\w\-_ ]', '_', title)[:50]
488
  new_filename = f"{sanitized_title}.md"
489
-
490
  return temp_file.name, new_filename
491
  except Exception as e:
492
  return None, f"Error creating file: {str(e)}"
@@ -497,28 +463,23 @@ def generate_blog(topic, tone, length, author_name, publish_option, linkedin_use
497
  download_filename = None
498
 
499
  try:
500
- # Generate content
501
  status_updates.append("๐Ÿš€ Starting blog generation...")
502
  blog_content = generate_blog_content(topic, tone, length)
503
 
504
  if "Error" in blog_content:
505
  return blog_content, "", "\n".join(status_updates), None
506
 
507
- # Extract title
508
  title_match = re.search(r'^#\s+(.+)$', blog_content, re.MULTILINE)
509
  title = title_match.group(1) if title_match else topic
510
 
511
- # Generate image
512
  status_updates.append("๐Ÿ–ผ๏ธ Generating featured image...")
513
  image_path, image_msg = generate_featured_image(topic)
514
  status_updates.append(image_msg)
515
 
516
- # Create downloadable file
517
  status_updates.append("๐Ÿ“ฅ Preparing download...")
518
  file_path, download_filename = create_download_file(blog_content, title, author_name)
519
  status_updates.append("โœ… Download ready!")
520
 
521
- # Publishing logic
522
  if publish_option != "none":
523
  status_updates.append(f"๐Ÿ“ฎ Publishing to {publish_option}...")
524
  # Add publishing logic here
@@ -529,7 +490,6 @@ def generate_blog(topic, tone, length, author_name, publish_option, linkedin_use
529
  status_updates.append(f"โŒ Error: {str(e)}")
530
  return blog_content, title if 'title' in locals() else "", "\n".join(status_updates), None
531
 
532
- # Gradio interface
533
  with gr.Blocks(title="AI Blog Generator", theme=gr.themes.Soft()) as app:
534
  gr.Markdown("# ๐Ÿ“ AI Blog Generator & Publisher")
535
  gr.Markdown("Generate professional blog posts with AI and export as Markdown")
@@ -587,16 +547,6 @@ with gr.Blocks(title="AI Blog Generator", theme=gr.themes.Soft()) as app:
587
  inputs=[topic_input, tone_input, length_input, author_input, publish_option, linkedin_user, linkedin_pass, hf_token],
588
  outputs=[blog_output, title_output, status_output, download_output]
589
  )
590
-
591
- # Show download button when file is ready
592
- def toggle_download(file_data):
593
- return gr.update(visible=file_data is not None)
594
-
595
- app.load(
596
- lambda: None,
597
- outputs=download_output,
598
- queue=False
599
- )
600
 
601
  if __name__ == "__main__":
602
  app.launch()
 
363
  import json
364
  import random
365
  from datetime import datetime
 
 
 
366
 
367
+ # Hugging Face Inference API endpoints
368
+ TEXT_API_URL = "https://api-inference.huggingface.co/models/mistralai/Mistral-7B-Instruct-v0.2"
369
+ IMAGE_API_URL = "https://api-inference.huggingface.co/models/stabilityai/stable-diffusion-xl-base-1.0"
370
+ HEADERS = {"Authorization": "HF_TOKEN"} # Replace with your token
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
371
 
372
  def generate_blog_content(topic, tone="professional", length="medium"):
 
 
 
 
 
 
 
 
 
373
  current_date = datetime.now().strftime("%B %d, %Y")
374
  reading_time = {"short": "5-8", "medium": "8-12", "long": "15-20"}[length]
375
 
376
  prompt = f"""Write a comprehensive blog post about {topic} with this structure:
 
377
  # [Main Title]
378
+ ## [Subtitle]
 
379
  **Published**: {current_date}
380
  **Reading time**: {reading_time} minutes
381
+
 
382
  ### Table of Contents
383
  - [Introduction](#introduction)
384
  - [Section 1](#section-1)
385
  - [Section 2](#section-2)
 
386
  - [Conclusion](#conclusion)
387
+
388
  ## Introduction
389
  [Engaging opening paragraph with statistics]
390
+
391
  ## Section 1: [Section Title]
392
  [Detailed content with examples and data]
393
+
394
+ ## Section 2: [Section Title]
395
  [Technical details or case studies]
396
+
 
 
 
397
  ## Conclusion
398
  [Summary and final thoughts]
399
+
400
+ Use {tone} tone and include:
401
+ - Markdown formatting
402
+ - Bullet points
403
+ - Realistic statistics
404
+ - 3 subsections per section"""
405
 
406
+ payload = {
407
+ "inputs": prompt,
408
+ "parameters": {
409
+ "max_length": 2000,
410
+ "temperature": 0.7,
411
+ "do_sample": True
412
+ }
413
+ }
 
414
 
 
 
 
 
 
 
 
 
415
  try:
416
+ response = requests.post(TEXT_API_URL, headers=HEADERS, json=payload)
417
+ response.raise_for_status()
418
+ result = response.json()
419
+ if isinstance(result, list) and len(result) > 0:
420
+ return result[0]['generated_text'].split(prompt)[-1].strip()
421
+ return f"Error: {result.get('error', 'Unknown error')}"
422
  except Exception as e:
423
+ return f"Error generating content: {str(e)}"
424
 
425
  def generate_featured_image(topic):
 
 
 
426
  prompt = f"Professional digital illustration for blog about {topic}, high quality, trending on artstation"
427
+
428
+ payload = {
429
+ "inputs": prompt,
430
+ "parameters": {
431
+ "height": 512,
432
+ "width": 768,
433
+ "num_inference_steps": 25
434
+ }
435
+ }
436
+
437
  try:
438
+ response = requests.post(IMAGE_API_URL, headers=HEADERS, json=payload)
439
+ response.raise_for_status()
440
+ image = Image.open(BytesIO(response.content))
441
  temp_img = tempfile.NamedTemporaryFile(delete=False, suffix=".png")
442
  image.save(temp_img.name)
443
  return temp_img.name, "Image generated successfully"
 
446
 
447
  def create_download_file(content, title, author):
448
  try:
 
449
  temp_file = tempfile.NamedTemporaryFile(mode="w", delete=False, suffix=".md", encoding="utf-8")
 
 
450
  full_content = content + f"\n\n**About the Author** \n{author}"
 
 
451
  temp_file.write(full_content)
452
  temp_file.close()
453
 
 
454
  sanitized_title = re.sub(r'[^\w\-_ ]', '_', title)[:50]
455
  new_filename = f"{sanitized_title}.md"
 
456
  return temp_file.name, new_filename
457
  except Exception as e:
458
  return None, f"Error creating file: {str(e)}"
 
463
  download_filename = None
464
 
465
  try:
 
466
  status_updates.append("๐Ÿš€ Starting blog generation...")
467
  blog_content = generate_blog_content(topic, tone, length)
468
 
469
  if "Error" in blog_content:
470
  return blog_content, "", "\n".join(status_updates), None
471
 
 
472
  title_match = re.search(r'^#\s+(.+)$', blog_content, re.MULTILINE)
473
  title = title_match.group(1) if title_match else topic
474
 
 
475
  status_updates.append("๐Ÿ–ผ๏ธ Generating featured image...")
476
  image_path, image_msg = generate_featured_image(topic)
477
  status_updates.append(image_msg)
478
 
 
479
  status_updates.append("๐Ÿ“ฅ Preparing download...")
480
  file_path, download_filename = create_download_file(blog_content, title, author_name)
481
  status_updates.append("โœ… Download ready!")
482
 
 
483
  if publish_option != "none":
484
  status_updates.append(f"๐Ÿ“ฎ Publishing to {publish_option}...")
485
  # Add publishing logic here
 
490
  status_updates.append(f"โŒ Error: {str(e)}")
491
  return blog_content, title if 'title' in locals() else "", "\n".join(status_updates), None
492
 
 
493
  with gr.Blocks(title="AI Blog Generator", theme=gr.themes.Soft()) as app:
494
  gr.Markdown("# ๐Ÿ“ AI Blog Generator & Publisher")
495
  gr.Markdown("Generate professional blog posts with AI and export as Markdown")
 
547
  inputs=[topic_input, tone_input, length_input, author_input, publish_option, linkedin_user, linkedin_pass, hf_token],
548
  outputs=[blog_output, title_output, status_output, download_output]
549
  )
 
 
 
 
 
 
 
 
 
 
550
 
551
  if __name__ == "__main__":
552
  app.launch()