scholarly360 commited on
Commit
9eca3cd
Β·
verified Β·
1 Parent(s): 3be125b

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +162 -3
app.py CHANGED
@@ -1,7 +1,166 @@
1
  import gradio as gr
 
 
 
2
 
3
- def greet(name):
4
- return "Hello " + name + "!!"
 
 
 
 
 
5
 
6
- demo = gr.Interface(fn=greet, inputs="text", outputs="text")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7
  demo.launch()
 
1
  import gradio as gr
2
+ import openai
3
+ import os
4
+ from typing import List, Tuple
5
 
6
+ # Initialize OpenAI client
7
+ def initialize_openai():
8
+ """Initialize OpenAI client with API key"""
9
+ api_key = os.getenv('OPENAI_API_KEY')
10
+ if not api_key:
11
+ raise ValueError("Please set your OPENAI_API_KEY environment variable")
12
+ return openai.OpenAI(api_key=api_key)
13
 
14
+ def generate_qa_pairs(topic: str, difficulty: str = "Medium") -> str:
15
+ """
16
+ Generate 10 questions and answers for a given topic using GPT-4 Mini
17
+
18
+ Args:
19
+ topic (str): The topic to generate Q&A pairs for
20
+ difficulty (str): Difficulty level (Easy, Medium, Hard)
21
+
22
+ Returns:
23
+ str: Formatted Q&A pairs
24
+ """
25
+ try:
26
+ client = initialize_openai()
27
+
28
+ # Create the prompt
29
+ prompt = f"""Generate exactly 10 questions and answers about the topic: "{topic}"
30
+
31
+ Requirements:
32
+ - Difficulty level: {difficulty}
33
+ - Questions should be diverse and cover different aspects of the topic
34
+ - Answers should be comprehensive but concise (2-4 sentences each)
35
+ - Format each Q&A pair clearly with "Q:" and "A:" labels
36
+ - Number each pair (1-10)
37
+
38
+ Topic: {topic}
39
+ Difficulty: {difficulty}
40
+
41
+ Please generate the questions and answers now:"""
42
+
43
+ # Make API call to GPT-4 Mini
44
+ response = client.chat.completions.create(
45
+ model="gpt-4o-mini", # Updated model name
46
+ messages=[
47
+ {
48
+ "role": "system",
49
+ "content": "You are an expert educator who creates high-quality questions and answers on various topics. Your responses are well-structured, accurate, and educational."
50
+ },
51
+ {
52
+ "role": "user",
53
+ "content": prompt
54
+ }
55
+ ],
56
+ max_tokens=2000,
57
+ temperature=0.7
58
+ )
59
+
60
+ return response.choices[0].message.content
61
+
62
+ except openai.AuthenticationError:
63
+ return "❌ Authentication Error: Please check your OpenAI API key."
64
+ except openai.RateLimitError:
65
+ return "❌ Rate Limit Error: You've exceeded your API quota. Please try again later."
66
+ except openai.APIError as e:
67
+ return f"❌ OpenAI API Error: {str(e)}"
68
+ except Exception as e:
69
+ return f"❌ Error: {str(e)}"
70
+
71
+ def create_interface():
72
+ """Create and configure the Gradio interface"""
73
+
74
+ with gr.Blocks(
75
+ title="Q&A Generator with GPT-4 Mini",
76
+ theme=gr.themes.Soft(),
77
+ css="""
78
+ .main-header {
79
+ text-align: center;
80
+ margin-bottom: 2rem;
81
+ }
82
+ .qa-output {
83
+ font-family: 'Georgia', serif;
84
+ line-height: 1.6;
85
+ }
86
+ """
87
+ ) as interface:
88
+
89
+ gr.HTML("""
90
+ <div class="main-header">
91
+ <h1>πŸ€– Q&A Generator</h1>
92
+ <p>Generate 10 comprehensive questions and answers on any topic using GPT-4 Mini</p>
93
+ </div>
94
+ """)
95
+
96
+ with gr.Row():
97
+ with gr.Column(scale=2):
98
+ topic_input = gr.Textbox(
99
+ label="Topic",
100
+ placeholder="Enter any topic (e.g., 'Climate Change', 'Machine Learning', 'Ancient Rome')",
101
+ lines=2
102
+ )
103
+
104
+ difficulty_dropdown = gr.Dropdown(
105
+ label="Difficulty Level",
106
+ choices=["Easy", "Medium", "Hard"],
107
+ value="Medium"
108
+ )
109
+
110
+ generate_btn = gr.Button(
111
+ "Generate Q&A Pairs",
112
+ variant="primary",
113
+ size="lg"
114
+ )
115
+
116
+ with gr.Column(scale=1):
117
+ gr.HTML("""
118
+ <div style="padding: 1rem; background-color: #f0f8ff; border-radius: 8px; margin-top: 1rem;">
119
+ <h3>πŸ“ Instructions:</h3>
120
+ <ol>
121
+ <li>Enter a topic you want to learn about</li>
122
+ <li>Choose difficulty level</li>
123
+ <li>Click "Generate Q&A Pairs"</li>
124
+ </ol>
125
+ <p><strong>Note:</strong> Make sure to set your <code>OPENAI_API_KEY</code> environment variable before running.</p>
126
+ </div>
127
+ """)
128
+
129
+ qa_output = gr.Textbox(
130
+ label="Generated Questions & Answers",
131
+ lines=25,
132
+ max_lines=50,
133
+ elem_classes=["qa-output"],
134
+ show_copy_button=True
135
+ )
136
+
137
+ # Example topics for quick testing
138
+ gr.Examples(
139
+ examples=[
140
+ ["Artificial Intelligence", "Medium"],
141
+ ["Photosynthesis", "Easy"],
142
+ ["Quantum Physics", "Hard"],
143
+ ["Renaissance Art", "Medium"],
144
+ ["Cryptocurrency", "Medium"]
145
+ ],
146
+ inputs=[topic_input, difficulty_dropdown]
147
+ )
148
+
149
+ # Event handlers
150
+ generate_btn.click(
151
+ fn=generate_qa_pairs,
152
+ inputs=[topic_input, difficulty_dropdown],
153
+ outputs=qa_output
154
+ )
155
+
156
+ # Allow Enter key to trigger generation
157
+ topic_input.submit(
158
+ fn=generate_qa_pairs,
159
+ inputs=[topic_input, difficulty_dropdown],
160
+ outputs=qa_output
161
+ )
162
+
163
+ return interface
164
+
165
+ demo = gr.Interface(fn=create_interface, inputs="text", outputs="text")
166
  demo.launch()