import gradio as gr
import openai
import re
import os

# Set up OpenAI API credentials
openai.api_key = os.environ["api"]

# Define the function that generates the blog article
def generate_article(topic):
    # Use OpenAI's GPT-3 to generate the article
    prompt = f"Write a blog about {topic} with required sections with titles and the article should be interesting and factual and minimum of 500 words"
    response = openai.Completion.create(
        engine="text-davinci-003",
        prompt=prompt,
        max_tokens=2048,
        n=1,
        stop=None,
        temperature=0.5,
    )
    article = response.choices[0].text

    article = re.sub('\n', ' ', article)
    article = re.sub('\s+', ' ', article)

    section_length = len(article) // 5
    sections = [article[i:i+section_length] for i in range(0, len(article), section_length)]

    blog_post = f"# {topic}\n\n"
    for i in range(5):
        blog_post += f"## Section {i+1}\n\n{sections[i]}\n\n"
    
    return article

# Set up the Gradio interface
iface = gr.Interface(
    generate_article,
    inputs=gr.inputs.Textbox("Enter a topic for your blog post"),
    outputs=gr.outputs.HTML(),
    title="Blog Post Generator",
)

# Launch the interface
iface.launch(share=False)