File size: 5,079 Bytes
6ef5dd5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
import gradio as gr
from groq import Groq

# Function to validate the API key entered by the user
def validate_api_key(api_key):
    try:
        # Initialize the Groq client with the provided API key
        client = Groq(api_key=api_key)
        # Perform a minimal valid API call
        response = client.chat.completions.create(
            model="llama-3.1-70b-versatile",
            messages=[
                {"role": "system", "content": "Validation test for API key."},
                {"role": "user", "content": "Hello, world!"}
            ],
            temperature=0.1,
            max_tokens=5,
        )
        if response and response.choices:
            return True, "API key is valid!"
        else:
            return False, "API key validation failed: Empty response."
    except Exception as e:
        return False, f"Invalid API key. Error: {str(e)}"

# Blog content generation function
def generate_blog_content(topic, api_key):
    client = Groq(api_key=api_key)
    
    prompt = f"""Generate a blog post on '{topic}' with the following structure:

1. **Create 20 sections**, with a **FAQs section as the last one**.
2. **Use <section> tags** for sections, with <h2> for headings and <p> for content.
3. **If there are sub-headings under an <h2> tag, use <h3> for those sub-headings** (e.g., in FAQs or where additional structure is needed).
4. **Highlight key terms** with <strong> tags for clarity.
5. Each section should be **250-300 words** and directly relate to the topic.
6. Write in a **formal tone** suitable for a professional medical audience.
7. Avoid single-word headings and ensure every paragraph adds informative value.
8. FAQs should address potential reader questions based on the main content.

**Example:**
<section>
    <h2>Overview of [Medical Condition]</h2>
    <p>Explanation with <strong>key terms</strong> highlighted...</p>
</section>

<section>
    <h2>FAQs</h2>
    <h3>What causes [Medical Condition]?</h3>
    <p>A clear, accurate answer with <strong>relevant terms</strong> highlighted.</p>
    <h3>How is [Medical Condition] treated?</h3>
    <p>Explanation of treatment options, with <strong>important terms</strong> highlighted...</p>
</section>
"""

    try:
        completion = client.chat.completions.create(
            model="llama-3.1-70b-versatile",  # Groq's Mixtral model
            messages=[
                {"role": "system", "content": "You are a medical content specialist experienced in healthcare writing for patients and medical professionals in India. Your writing should be clear, accurate, and suitable for both educated laypersons and healthcare practitioners."},
                {"role": "user", "content": prompt}
            ],
            temperature=0.5,
            max_tokens=8000,
        )
        return completion.choices[0].message.content
    except Exception as e:
        return f"Error generating content: {str(e)}"

# Callback function for login
def on_login(api_key):
    is_valid, message = validate_api_key(api_key)
    if is_valid:
        return api_key, gr.update(visible=False), gr.update(visible=True), gr.Markdown(f"**Success!** {message}")
    else:
        return "", gr.update(visible=True), gr.update(visible=False), gr.Markdown(f"**Error!** {message}", visible=True)

# Callback function for generating content
def on_generate_click(topic, api_key):
    if not api_key:
        return "Error: API key not provided.", ""
    if not topic:
        return "Please enter a blog topic.", ""
    content = generate_blog_content(topic, api_key)
    return content, content

# Gradio app
with gr.Blocks(title="ArogyaJivan") as demo:

    # Login Section
    with gr.Column(visible=True) as login_section:
        gr.Markdown("## Login to Access the Blog Generator")
        api_key_input = gr.Textbox(label="Enter your API Key:", type="password")
        login_button = gr.Button("Login")
        login_feedback = gr.Markdown(visible=False) 
        gr.Markdown("""
        ### How to Get an API Key
        - Visit [Groq API Key Portal](https://groq.com/get-api-key)
        - Sign up or log in to your account.
        - Navigate to the **API Keys** section and generate a new key.
        - Copy the API key and paste it Above.
        """)
        

    # Blog Content Generator Section
    with gr.Column(visible=False) as blog_section:
        gr.Markdown("# Blog Content Generator")
        with gr.Column():
            topic_input = gr.Textbox(label="Enter your blog topic:")
            generate_button = gr.Button("Generate Blog Content")
        with gr.Row():
            output_html = gr.Code(label="Generated HTML Content:", language='html')
            output_preview = gr.HTML(label="Preview:")

    state = gr.State()  # Manage API key state

    login_button.click(
        on_login,
        inputs=api_key_input,
        outputs=[state, login_section, blog_section, login_feedback]
    )
    generate_button.click(
        on_generate_click,
        inputs=[topic_input, state],
        outputs=[output_html, output_preview]
    )

demo.launch()