jsakshi commited on
Commit
2c24d99
·
verified ·
1 Parent(s): a9ce203

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +252 -1
app.py CHANGED
@@ -1,4 +1,4 @@
1
- import gradio as gr
2
  import os
3
  import time
4
  import tempfile
@@ -347,5 +347,256 @@ with gr.Blocks(title="Blog Generator & Publisher") as app:
347
  - Gradio for the interface
348
  """)
349
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
350
  if __name__ == "__main__":
351
  app.launch()
 
1
+ '''import gradio as gr
2
  import os
3
  import time
4
  import tempfile
 
347
  - Gradio for the interface
348
  """)
349
 
350
+ if __name__ == "__main__":
351
+ app.launch()'''
352
+
353
+
354
+ import gradio as gr
355
+ import os
356
+ import time
357
+ import tempfile
358
+ import requests
359
+ from PIL import Image
360
+ from io import BytesIO
361
+ import markdown
362
+ 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"
471
+ except Exception as e:
472
+ return None, f"Error generating image: {str(e)}"
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)}"
493
+
494
+ def generate_blog(topic, tone, length, author_name, publish_option, linkedin_username=None, linkedin_password=None, hf_token=None):
495
+ status_updates = []
496
+ file_path = None
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
525
+
526
+ return blog_content, title, "\n".join(status_updates), (file_path, download_filename) if file_path else None
527
+
528
+ except Exception as e:
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")
536
+
537
+ with gr.Row():
538
+ with gr.Column(scale=1):
539
+ topic_input = gr.Textbox(label="Blog Topic", placeholder="Enter your blog topic...")
540
+ tone_input = gr.Dropdown(
541
+ label="Writing Style",
542
+ choices=["professional", "casual", "technical", "storytelling"],
543
+ value="professional"
544
+ )
545
+ length_input = gr.Dropdown(
546
+ label="Article Length",
547
+ choices=["short", "medium", "long"],
548
+ value="medium"
549
+ )
550
+ author_input = gr.Textbox(label="Author Name", placeholder="John Doe")
551
+
552
+ with gr.Accordion("⚙️ Publishing Options", open=False):
553
+ publish_option = gr.Radio(
554
+ label="Publish Destination",
555
+ choices=["none", "linkedin", "huggingface", "both"],
556
+ value="none"
557
+ )
558
+ linkedin_user = gr.Textbox(label="LinkedIn Email", visible=False)
559
+ linkedin_pass = gr.Textbox(label="LinkedIn Password", type="password", visible=False)
560
+ hf_token = gr.Textbox(label="Hugging Face Token", type="password", visible=False)
561
+
562
+ def update_publish_fields(choice):
563
+ linkedin_vis = choice in ["linkedin", "both"]
564
+ hf_vis = choice in ["huggingface", "both"]
565
+ return [
566
+ gr.update(visible=linkedin_vis),
567
+ gr.update(visible=linkedin_vis),
568
+ gr.update(visible=hf_vis)
569
+ ]
570
+ publish_option.change(update_publish_fields, publish_option, [linkedin_user, linkedin_pass, hf_token])
571
+
572
+ generate_btn = gr.Button("Generate Blog", variant="primary")
573
+
574
+ with gr.Column(scale=2):
575
+ title_output = gr.Textbox(label="Generated Title")
576
+ blog_output = gr.Markdown(label="Blog Content", show_label=False)
577
+ status_output = gr.Textbox(label="Status", interactive=False)
578
+ download_output = gr.File(
579
+ label="Download Blog",
580
+ visible=False,
581
+ file_types=[".md"],
582
+ file_count="single"
583
+ )
584
+
585
+ generate_btn.click(
586
+ generate_blog,
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()