Spaces:
Sleeping
Sleeping
File size: 6,009 Bytes
eccc4ee 9eca3cd ce1d81d eccc4ee 9eca3cd eccc4ee 9eca3cd ce1d81d 9eca3cd ce1d81d 9eca3cd 08349ae 9eca3cd 08349ae 9eca3cd 08349ae 9eca3cd 08349ae 9eca3cd 7e2a0c4 |
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 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 |
import gradio as gr
import openai
import os
from typing import List, Tuple
import time
# Initialize OpenAI client
def initialize_openai():
"""Initialize OpenAI client with API key"""
api_key = os.getenv('OPENAI_API_KEY')
if not api_key:
raise ValueError("Please set your OPENAI_API_KEY environment variable")
return openai.OpenAI(api_key=api_key)
def generate_qa_pairs(topic: str, difficulty: str = "Medium") -> str:
"""
Generate 10 questions and answers for a given topic using GPT-4 Mini
Args:
topic (str): The topic to generate Q&A pairs for
difficulty (str): Difficulty level (Easy, Medium, Hard)
Returns:
str: Formatted Q&A pairs
"""
try:
client = initialize_openai()
time.sleep(5)
# Create the prompt
prompt = f"""Generate exactly 10 questions and answers about the topic: "{topic}"
Requirements:
- Difficulty level: {difficulty}
- Questions should be diverse and cover different aspects of the topic
- Answers should be comprehensive but concise (2-4 sentences each)
- Format each Q&A pair clearly with "Q:" and "A:" labels
- Number each pair (1-10)
Topic: {topic}
Difficulty: {difficulty}
Please generate the questions and answers now:"""
# Make API call to GPT-4 Mini
response = client.chat.completions.create(
model="gpt-4o-mini", # Updated model name
messages=[
{
"role": "system",
"content": "You are an expert educator who creates high-quality questions and answers on various topics. Your responses are well-structured, accurate, and educational."
},
{
"role": "user",
"content": prompt
}
],
max_tokens=2000,
temperature=0.2
)
return response.choices[0].message.content
except openai.AuthenticationError:
return "β Authentication Error: Please check your OpenAI API key."
except openai.RateLimitError:
return "β Rate Limit Error: You've exceeded your API quota. Please try again later."
except openai.APIError as e:
return f"β OpenAI API Error: {str(e)}"
except Exception as e:
return f"β Error: {str(e)}"
def create_interface():
"""Create and configure the Gradio interface"""
with gr.Blocks(
title="StudyBuddy-AI - Q&A Generator with LLM",
theme=gr.themes.Soft(),
css="""
.main-header {
text-align: center;
margin-bottom: 2rem;
}
.qa-output {
font-family: 'Georgia', serif;
line-height: 1.6;
}
"""
) as interface:
gr.HTML("""
<div class="main-header">
<h1>π€ StudyBuddy-AI </h1>
<p>Generate 10 comprehensive questions and answers on any topic using gpt-4-o mini</p>
</div>
""")
with gr.Row():
with gr.Column(scale=2):
topic_input = gr.Textbox(
label="Topic",
placeholder="Enter any topic (e.g., 'AWS', 'Machine Learning', 'Azure Web Apps')",
lines=2
)
difficulty_dropdown = gr.Dropdown(
label="Difficulty Level",
choices=["Easy", "Medium", "Hard"],
value="Medium"
)
generate_btn = gr.Button(
"Generate Q&A Pairs",
variant="primary",
size="lg"
)
with gr.Column(scale=1):
gr.HTML("""
<div style="padding: 1rem; background-color: #f0f8ff; border-radius: 8px; margin-top: 1rem;">
<h3>π Instructions:</h3>
<ol>
<li>Enter a topic you want to learn about</li>
<li>Choose difficulty level</li>
<li>Click "Generate Q&A Pairs"</li>
</ol>
<p><strong>Note:</strong> Make sure to set your <code>OPENAI_API_KEY</code> environment variable before running.</p>
</div>
""")
qa_output = gr.Textbox(
label="Generated Questions & Answers",
lines=25,
max_lines=50,
elem_classes=["qa-output"],
show_copy_button=True
)
# Example topics for quick testing
gr.Examples(
examples=[
["Artificial Intelligence", "Medium"],
["AWS", "Easy"],
["Azure", "Hard"],
["Renaissance Art", "Medium"],
["Cryptocurrency", "Medium"]
],
inputs=[topic_input, difficulty_dropdown]
)
# Event handlers
generate_btn.click(
fn=generate_qa_pairs,
inputs=[topic_input, difficulty_dropdown],
outputs=qa_output
)
# Allow Enter key to trigger generation
topic_input.submit(
fn=generate_qa_pairs,
inputs=[topic_input, difficulty_dropdown],
outputs=qa_output
)
return interface
def main():
"""Main function to launch the application"""
# Check if API key is set
if not os.getenv('OPENAI_API_KEY'):
print("β οΈ Warning: OPENAI_API_KEY environment variable not found!")
print("Please set it using: export OPENAI_API_KEY='your-api-key-here'")
print("You can get your API key from: https://platform.openai.com/api-keys")
# Create and launch interface
interface = create_interface()
interface.launch(
share=False,
show_error=True
)
if __name__ == "__main__":
main() |